xref: /linux/mm/memcontrol.c (revision 34efe1c3b688944d9817a5faaab7aad870182c59)
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/page_counter.h>
29 #include <linux/memcontrol.h>
30 #include <linux/cgroup.h>
31 #include <linux/pagewalk.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/mutex.h>
46 #include <linux/rbtree.h>
47 #include <linux/slab.h>
48 #include <linux/swap.h>
49 #include <linux/swapops.h>
50 #include <linux/spinlock.h>
51 #include <linux/eventfd.h>
52 #include <linux/poll.h>
53 #include <linux/sort.h>
54 #include <linux/fs.h>
55 #include <linux/seq_file.h>
56 #include <linux/vmpressure.h>
57 #include <linux/memremap.h>
58 #include <linux/mm_inline.h>
59 #include <linux/swap_cgroup.h>
60 #include <linux/cpu.h>
61 #include <linux/oom.h>
62 #include <linux/lockdep.h>
63 #include <linux/file.h>
64 #include <linux/resume_user_mode.h>
65 #include <linux/psi.h>
66 #include <linux/seq_buf.h>
67 #include <linux/sched/isolation.h>
68 #include <linux/kmemleak.h>
69 #include "internal.h"
70 #include <net/sock.h>
71 #include <net/ip.h>
72 #include "slab.h"
73 #include "swap.h"
74 
75 #include <linux/uaccess.h>
76 
77 #include <trace/events/vmscan.h>
78 
79 struct cgroup_subsys memory_cgrp_subsys __read_mostly;
80 EXPORT_SYMBOL(memory_cgrp_subsys);
81 
82 struct mem_cgroup *root_mem_cgroup __read_mostly;
83 
84 /* Active memory cgroup to use from an interrupt context */
85 DEFINE_PER_CPU(struct mem_cgroup *, int_active_memcg);
86 EXPORT_PER_CPU_SYMBOL_GPL(int_active_memcg);
87 
88 /* Socket memory accounting disabled? */
89 static bool cgroup_memory_nosocket __ro_after_init;
90 
91 /* Kernel memory accounting disabled? */
92 static bool cgroup_memory_nokmem __ro_after_init;
93 
94 /* BPF memory accounting disabled? */
95 static bool cgroup_memory_nobpf __ro_after_init;
96 
97 #ifdef CONFIG_CGROUP_WRITEBACK
98 static DECLARE_WAIT_QUEUE_HEAD(memcg_cgwb_frn_waitq);
99 #endif
100 
101 /* Whether legacy memory+swap accounting is active */
102 static bool do_memsw_account(void)
103 {
104 	return !cgroup_subsys_on_dfl(memory_cgrp_subsys);
105 }
106 
107 #define THRESHOLDS_EVENTS_TARGET 128
108 #define SOFTLIMIT_EVENTS_TARGET 1024
109 
110 /*
111  * Cgroups above their limits are maintained in a RB-Tree, independent of
112  * their hierarchy representation
113  */
114 
115 struct mem_cgroup_tree_per_node {
116 	struct rb_root rb_root;
117 	struct rb_node *rb_rightmost;
118 	spinlock_t lock;
119 };
120 
121 struct mem_cgroup_tree {
122 	struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
123 };
124 
125 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
126 
127 /* for OOM */
128 struct mem_cgroup_eventfd_list {
129 	struct list_head list;
130 	struct eventfd_ctx *eventfd;
131 };
132 
133 /*
134  * cgroup_event represents events which userspace want to receive.
135  */
136 struct mem_cgroup_event {
137 	/*
138 	 * memcg which the event belongs to.
139 	 */
140 	struct mem_cgroup *memcg;
141 	/*
142 	 * eventfd to signal userspace about the event.
143 	 */
144 	struct eventfd_ctx *eventfd;
145 	/*
146 	 * Each of these stored in a list by the cgroup.
147 	 */
148 	struct list_head list;
149 	/*
150 	 * register_event() callback will be used to add new userspace
151 	 * waiter for changes related to this event.  Use eventfd_signal()
152 	 * on eventfd to send notification to userspace.
153 	 */
154 	int (*register_event)(struct mem_cgroup *memcg,
155 			      struct eventfd_ctx *eventfd, const char *args);
156 	/*
157 	 * unregister_event() callback will be called when userspace closes
158 	 * the eventfd or on cgroup removing.  This callback must be set,
159 	 * if you want provide notification functionality.
160 	 */
161 	void (*unregister_event)(struct mem_cgroup *memcg,
162 				 struct eventfd_ctx *eventfd);
163 	/*
164 	 * All fields below needed to unregister event when
165 	 * userspace closes eventfd.
166 	 */
167 	poll_table pt;
168 	wait_queue_head_t *wqh;
169 	wait_queue_entry_t wait;
170 	struct work_struct remove;
171 };
172 
173 static void mem_cgroup_threshold(struct mem_cgroup *memcg);
174 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
175 
176 /* Stuffs for move charges at task migration. */
177 /*
178  * Types of charges to be moved.
179  */
180 #define MOVE_ANON	0x1U
181 #define MOVE_FILE	0x2U
182 #define MOVE_MASK	(MOVE_ANON | MOVE_FILE)
183 
184 /* "mc" and its members are protected by cgroup_mutex */
185 static struct move_charge_struct {
186 	spinlock_t	  lock; /* for from, to */
187 	struct mm_struct  *mm;
188 	struct mem_cgroup *from;
189 	struct mem_cgroup *to;
190 	unsigned long flags;
191 	unsigned long precharge;
192 	unsigned long moved_charge;
193 	unsigned long moved_swap;
194 	struct task_struct *moving_task;	/* a task moving charges */
195 	wait_queue_head_t waitq;		/* a waitq for other context */
196 } mc = {
197 	.lock = __SPIN_LOCK_UNLOCKED(mc.lock),
198 	.waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
199 };
200 
201 /*
202  * Maximum loops in mem_cgroup_soft_reclaim(), used for soft
203  * limit reclaim to prevent infinite loops, if they ever occur.
204  */
205 #define	MEM_CGROUP_MAX_RECLAIM_LOOPS		100
206 #define	MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS	2
207 
208 /* for encoding cft->private value on file */
209 enum res_type {
210 	_MEM,
211 	_MEMSWAP,
212 	_KMEM,
213 	_TCP,
214 };
215 
216 #define MEMFILE_PRIVATE(x, val)	((x) << 16 | (val))
217 #define MEMFILE_TYPE(val)	((val) >> 16 & 0xffff)
218 #define MEMFILE_ATTR(val)	((val) & 0xffff)
219 
220 /*
221  * Iteration constructs for visiting all cgroups (under a tree).  If
222  * loops are exited prematurely (break), mem_cgroup_iter_break() must
223  * be used for reference counting.
224  */
225 #define for_each_mem_cgroup_tree(iter, root)		\
226 	for (iter = mem_cgroup_iter(root, NULL, NULL);	\
227 	     iter != NULL;				\
228 	     iter = mem_cgroup_iter(root, iter, NULL))
229 
230 #define for_each_mem_cgroup(iter)			\
231 	for (iter = mem_cgroup_iter(NULL, NULL, NULL);	\
232 	     iter != NULL;				\
233 	     iter = mem_cgroup_iter(NULL, iter, NULL))
234 
235 static inline bool task_is_dying(void)
236 {
237 	return tsk_is_oom_victim(current) || fatal_signal_pending(current) ||
238 		(current->flags & PF_EXITING);
239 }
240 
241 /* Some nice accessors for the vmpressure. */
242 struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
243 {
244 	if (!memcg)
245 		memcg = root_mem_cgroup;
246 	return &memcg->vmpressure;
247 }
248 
249 struct mem_cgroup *vmpressure_to_memcg(struct vmpressure *vmpr)
250 {
251 	return container_of(vmpr, struct mem_cgroup, vmpressure);
252 }
253 
254 #define CURRENT_OBJCG_UPDATE_BIT 0
255 #define CURRENT_OBJCG_UPDATE_FLAG (1UL << CURRENT_OBJCG_UPDATE_BIT)
256 
257 #ifdef CONFIG_MEMCG_KMEM
258 static DEFINE_SPINLOCK(objcg_lock);
259 
260 bool mem_cgroup_kmem_disabled(void)
261 {
262 	return cgroup_memory_nokmem;
263 }
264 
265 static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
266 				      unsigned int nr_pages);
267 
268 static void obj_cgroup_release(struct percpu_ref *ref)
269 {
270 	struct obj_cgroup *objcg = container_of(ref, struct obj_cgroup, refcnt);
271 	unsigned int nr_bytes;
272 	unsigned int nr_pages;
273 	unsigned long flags;
274 
275 	/*
276 	 * At this point all allocated objects are freed, and
277 	 * objcg->nr_charged_bytes can't have an arbitrary byte value.
278 	 * However, it can be PAGE_SIZE or (x * PAGE_SIZE).
279 	 *
280 	 * The following sequence can lead to it:
281 	 * 1) CPU0: objcg == stock->cached_objcg
282 	 * 2) CPU1: we do a small allocation (e.g. 92 bytes),
283 	 *          PAGE_SIZE bytes are charged
284 	 * 3) CPU1: a process from another memcg is allocating something,
285 	 *          the stock if flushed,
286 	 *          objcg->nr_charged_bytes = PAGE_SIZE - 92
287 	 * 5) CPU0: we do release this object,
288 	 *          92 bytes are added to stock->nr_bytes
289 	 * 6) CPU0: stock is flushed,
290 	 *          92 bytes are added to objcg->nr_charged_bytes
291 	 *
292 	 * In the result, nr_charged_bytes == PAGE_SIZE.
293 	 * This page will be uncharged in obj_cgroup_release().
294 	 */
295 	nr_bytes = atomic_read(&objcg->nr_charged_bytes);
296 	WARN_ON_ONCE(nr_bytes & (PAGE_SIZE - 1));
297 	nr_pages = nr_bytes >> PAGE_SHIFT;
298 
299 	if (nr_pages)
300 		obj_cgroup_uncharge_pages(objcg, nr_pages);
301 
302 	spin_lock_irqsave(&objcg_lock, flags);
303 	list_del(&objcg->list);
304 	spin_unlock_irqrestore(&objcg_lock, flags);
305 
306 	percpu_ref_exit(ref);
307 	kfree_rcu(objcg, rcu);
308 }
309 
310 static struct obj_cgroup *obj_cgroup_alloc(void)
311 {
312 	struct obj_cgroup *objcg;
313 	int ret;
314 
315 	objcg = kzalloc(sizeof(struct obj_cgroup), GFP_KERNEL);
316 	if (!objcg)
317 		return NULL;
318 
319 	ret = percpu_ref_init(&objcg->refcnt, obj_cgroup_release, 0,
320 			      GFP_KERNEL);
321 	if (ret) {
322 		kfree(objcg);
323 		return NULL;
324 	}
325 	INIT_LIST_HEAD(&objcg->list);
326 	return objcg;
327 }
328 
329 static void memcg_reparent_objcgs(struct mem_cgroup *memcg,
330 				  struct mem_cgroup *parent)
331 {
332 	struct obj_cgroup *objcg, *iter;
333 
334 	objcg = rcu_replace_pointer(memcg->objcg, NULL, true);
335 
336 	spin_lock_irq(&objcg_lock);
337 
338 	/* 1) Ready to reparent active objcg. */
339 	list_add(&objcg->list, &memcg->objcg_list);
340 	/* 2) Reparent active objcg and already reparented objcgs to parent. */
341 	list_for_each_entry(iter, &memcg->objcg_list, list)
342 		WRITE_ONCE(iter->memcg, parent);
343 	/* 3) Move already reparented objcgs to the parent's list */
344 	list_splice(&memcg->objcg_list, &parent->objcg_list);
345 
346 	spin_unlock_irq(&objcg_lock);
347 
348 	percpu_ref_kill(&objcg->refcnt);
349 }
350 
351 /*
352  * A lot of the calls to the cache allocation functions are expected to be
353  * inlined by the compiler. Since the calls to memcg_slab_post_alloc_hook() are
354  * conditional to this static branch, we'll have to allow modules that does
355  * kmem_cache_alloc and the such to see this symbol as well
356  */
357 DEFINE_STATIC_KEY_FALSE(memcg_kmem_online_key);
358 EXPORT_SYMBOL(memcg_kmem_online_key);
359 
360 DEFINE_STATIC_KEY_FALSE(memcg_bpf_enabled_key);
361 EXPORT_SYMBOL(memcg_bpf_enabled_key);
362 #endif
363 
364 /**
365  * mem_cgroup_css_from_folio - css of the memcg associated with a folio
366  * @folio: folio of interest
367  *
368  * If memcg is bound to the default hierarchy, css of the memcg associated
369  * with @folio is returned.  The returned css remains associated with @folio
370  * until it is released.
371  *
372  * If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup
373  * is returned.
374  */
375 struct cgroup_subsys_state *mem_cgroup_css_from_folio(struct folio *folio)
376 {
377 	struct mem_cgroup *memcg = folio_memcg(folio);
378 
379 	if (!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
380 		memcg = root_mem_cgroup;
381 
382 	return &memcg->css;
383 }
384 
385 /**
386  * page_cgroup_ino - return inode number of the memcg a page is charged to
387  * @page: the page
388  *
389  * Look up the closest online ancestor of the memory cgroup @page is charged to
390  * and return its inode number or 0 if @page is not charged to any cgroup. It
391  * is safe to call this function without holding a reference to @page.
392  *
393  * Note, this function is inherently racy, because there is nothing to prevent
394  * the cgroup inode from getting torn down and potentially reallocated a moment
395  * after page_cgroup_ino() returns, so it only should be used by callers that
396  * do not care (such as procfs interfaces).
397  */
398 ino_t page_cgroup_ino(struct page *page)
399 {
400 	struct mem_cgroup *memcg;
401 	unsigned long ino = 0;
402 
403 	rcu_read_lock();
404 	/* page_folio() is racy here, but the entire function is racy anyway */
405 	memcg = folio_memcg_check(page_folio(page));
406 
407 	while (memcg && !(memcg->css.flags & CSS_ONLINE))
408 		memcg = parent_mem_cgroup(memcg);
409 	if (memcg)
410 		ino = cgroup_ino(memcg->css.cgroup);
411 	rcu_read_unlock();
412 	return ino;
413 }
414 
415 static void __mem_cgroup_insert_exceeded(struct mem_cgroup_per_node *mz,
416 					 struct mem_cgroup_tree_per_node *mctz,
417 					 unsigned long new_usage_in_excess)
418 {
419 	struct rb_node **p = &mctz->rb_root.rb_node;
420 	struct rb_node *parent = NULL;
421 	struct mem_cgroup_per_node *mz_node;
422 	bool rightmost = true;
423 
424 	if (mz->on_tree)
425 		return;
426 
427 	mz->usage_in_excess = new_usage_in_excess;
428 	if (!mz->usage_in_excess)
429 		return;
430 	while (*p) {
431 		parent = *p;
432 		mz_node = rb_entry(parent, struct mem_cgroup_per_node,
433 					tree_node);
434 		if (mz->usage_in_excess < mz_node->usage_in_excess) {
435 			p = &(*p)->rb_left;
436 			rightmost = false;
437 		} else {
438 			p = &(*p)->rb_right;
439 		}
440 	}
441 
442 	if (rightmost)
443 		mctz->rb_rightmost = &mz->tree_node;
444 
445 	rb_link_node(&mz->tree_node, parent, p);
446 	rb_insert_color(&mz->tree_node, &mctz->rb_root);
447 	mz->on_tree = true;
448 }
449 
450 static void __mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
451 					 struct mem_cgroup_tree_per_node *mctz)
452 {
453 	if (!mz->on_tree)
454 		return;
455 
456 	if (&mz->tree_node == mctz->rb_rightmost)
457 		mctz->rb_rightmost = rb_prev(&mz->tree_node);
458 
459 	rb_erase(&mz->tree_node, &mctz->rb_root);
460 	mz->on_tree = false;
461 }
462 
463 static void mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
464 				       struct mem_cgroup_tree_per_node *mctz)
465 {
466 	unsigned long flags;
467 
468 	spin_lock_irqsave(&mctz->lock, flags);
469 	__mem_cgroup_remove_exceeded(mz, mctz);
470 	spin_unlock_irqrestore(&mctz->lock, flags);
471 }
472 
473 static unsigned long soft_limit_excess(struct mem_cgroup *memcg)
474 {
475 	unsigned long nr_pages = page_counter_read(&memcg->memory);
476 	unsigned long soft_limit = READ_ONCE(memcg->soft_limit);
477 	unsigned long excess = 0;
478 
479 	if (nr_pages > soft_limit)
480 		excess = nr_pages - soft_limit;
481 
482 	return excess;
483 }
484 
485 static void mem_cgroup_update_tree(struct mem_cgroup *memcg, int nid)
486 {
487 	unsigned long excess;
488 	struct mem_cgroup_per_node *mz;
489 	struct mem_cgroup_tree_per_node *mctz;
490 
491 	if (lru_gen_enabled()) {
492 		if (soft_limit_excess(memcg))
493 			lru_gen_soft_reclaim(memcg, nid);
494 		return;
495 	}
496 
497 	mctz = soft_limit_tree.rb_tree_per_node[nid];
498 	if (!mctz)
499 		return;
500 	/*
501 	 * Necessary to update all ancestors when hierarchy is used.
502 	 * because their event counter is not touched.
503 	 */
504 	for (; memcg; memcg = parent_mem_cgroup(memcg)) {
505 		mz = memcg->nodeinfo[nid];
506 		excess = soft_limit_excess(memcg);
507 		/*
508 		 * We have to update the tree if mz is on RB-tree or
509 		 * mem is over its softlimit.
510 		 */
511 		if (excess || mz->on_tree) {
512 			unsigned long flags;
513 
514 			spin_lock_irqsave(&mctz->lock, flags);
515 			/* if on-tree, remove it */
516 			if (mz->on_tree)
517 				__mem_cgroup_remove_exceeded(mz, mctz);
518 			/*
519 			 * Insert again. mz->usage_in_excess will be updated.
520 			 * If excess is 0, no tree ops.
521 			 */
522 			__mem_cgroup_insert_exceeded(mz, mctz, excess);
523 			spin_unlock_irqrestore(&mctz->lock, flags);
524 		}
525 	}
526 }
527 
528 static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
529 {
530 	struct mem_cgroup_tree_per_node *mctz;
531 	struct mem_cgroup_per_node *mz;
532 	int nid;
533 
534 	for_each_node(nid) {
535 		mz = memcg->nodeinfo[nid];
536 		mctz = soft_limit_tree.rb_tree_per_node[nid];
537 		if (mctz)
538 			mem_cgroup_remove_exceeded(mz, mctz);
539 	}
540 }
541 
542 static struct mem_cgroup_per_node *
543 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
544 {
545 	struct mem_cgroup_per_node *mz;
546 
547 retry:
548 	mz = NULL;
549 	if (!mctz->rb_rightmost)
550 		goto done;		/* Nothing to reclaim from */
551 
552 	mz = rb_entry(mctz->rb_rightmost,
553 		      struct mem_cgroup_per_node, tree_node);
554 	/*
555 	 * Remove the node now but someone else can add it back,
556 	 * we will to add it back at the end of reclaim to its correct
557 	 * position in the tree.
558 	 */
559 	__mem_cgroup_remove_exceeded(mz, mctz);
560 	if (!soft_limit_excess(mz->memcg) ||
561 	    !css_tryget(&mz->memcg->css))
562 		goto retry;
563 done:
564 	return mz;
565 }
566 
567 static struct mem_cgroup_per_node *
568 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
569 {
570 	struct mem_cgroup_per_node *mz;
571 
572 	spin_lock_irq(&mctz->lock);
573 	mz = __mem_cgroup_largest_soft_limit_node(mctz);
574 	spin_unlock_irq(&mctz->lock);
575 	return mz;
576 }
577 
578 /* Subset of vm_event_item to report for memcg event stats */
579 static const unsigned int memcg_vm_event_stat[] = {
580 	PGPGIN,
581 	PGPGOUT,
582 	PGSCAN_KSWAPD,
583 	PGSCAN_DIRECT,
584 	PGSCAN_KHUGEPAGED,
585 	PGSTEAL_KSWAPD,
586 	PGSTEAL_DIRECT,
587 	PGSTEAL_KHUGEPAGED,
588 	PGFAULT,
589 	PGMAJFAULT,
590 	PGREFILL,
591 	PGACTIVATE,
592 	PGDEACTIVATE,
593 	PGLAZYFREE,
594 	PGLAZYFREED,
595 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
596 	ZSWPIN,
597 	ZSWPOUT,
598 	ZSWPWB,
599 #endif
600 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
601 	THP_FAULT_ALLOC,
602 	THP_COLLAPSE_ALLOC,
603 	THP_SWPOUT,
604 	THP_SWPOUT_FALLBACK,
605 #endif
606 };
607 
608 #define NR_MEMCG_EVENTS ARRAY_SIZE(memcg_vm_event_stat)
609 static int mem_cgroup_events_index[NR_VM_EVENT_ITEMS] __read_mostly;
610 
611 static void init_memcg_events(void)
612 {
613 	int i;
614 
615 	for (i = 0; i < NR_MEMCG_EVENTS; ++i)
616 		mem_cgroup_events_index[memcg_vm_event_stat[i]] = i + 1;
617 }
618 
619 static inline int memcg_events_index(enum vm_event_item idx)
620 {
621 	return mem_cgroup_events_index[idx] - 1;
622 }
623 
624 struct memcg_vmstats_percpu {
625 	/* Stats updates since the last flush */
626 	unsigned int			stats_updates;
627 
628 	/* Cached pointers for fast iteration in memcg_rstat_updated() */
629 	struct memcg_vmstats_percpu	*parent;
630 	struct memcg_vmstats		*vmstats;
631 
632 	/* The above should fit a single cacheline for memcg_rstat_updated() */
633 
634 	/* Local (CPU and cgroup) page state & events */
635 	long			state[MEMCG_NR_STAT];
636 	unsigned long		events[NR_MEMCG_EVENTS];
637 
638 	/* Delta calculation for lockless upward propagation */
639 	long			state_prev[MEMCG_NR_STAT];
640 	unsigned long		events_prev[NR_MEMCG_EVENTS];
641 
642 	/* Cgroup1: threshold notifications & softlimit tree updates */
643 	unsigned long		nr_page_events;
644 	unsigned long		targets[MEM_CGROUP_NTARGETS];
645 } ____cacheline_aligned;
646 
647 struct memcg_vmstats {
648 	/* Aggregated (CPU and subtree) page state & events */
649 	long			state[MEMCG_NR_STAT];
650 	unsigned long		events[NR_MEMCG_EVENTS];
651 
652 	/* Non-hierarchical (CPU aggregated) page state & events */
653 	long			state_local[MEMCG_NR_STAT];
654 	unsigned long		events_local[NR_MEMCG_EVENTS];
655 
656 	/* Pending child counts during tree propagation */
657 	long			state_pending[MEMCG_NR_STAT];
658 	unsigned long		events_pending[NR_MEMCG_EVENTS];
659 
660 	/* Stats updates since the last flush */
661 	atomic64_t		stats_updates;
662 };
663 
664 /*
665  * memcg and lruvec stats flushing
666  *
667  * Many codepaths leading to stats update or read are performance sensitive and
668  * adding stats flushing in such codepaths is not desirable. So, to optimize the
669  * flushing the kernel does:
670  *
671  * 1) Periodically and asynchronously flush the stats every 2 seconds to not let
672  *    rstat update tree grow unbounded.
673  *
674  * 2) Flush the stats synchronously on reader side only when there are more than
675  *    (MEMCG_CHARGE_BATCH * nr_cpus) update events. Though this optimization
676  *    will let stats be out of sync by atmost (MEMCG_CHARGE_BATCH * nr_cpus) but
677  *    only for 2 seconds due to (1).
678  */
679 static void flush_memcg_stats_dwork(struct work_struct *w);
680 static DECLARE_DEFERRABLE_WORK(stats_flush_dwork, flush_memcg_stats_dwork);
681 static u64 flush_last_time;
682 
683 #define FLUSH_TIME (2UL*HZ)
684 
685 /*
686  * Accessors to ensure that preemption is disabled on PREEMPT_RT because it can
687  * not rely on this as part of an acquired spinlock_t lock. These functions are
688  * never used in hardirq context on PREEMPT_RT and therefore disabling preemtion
689  * is sufficient.
690  */
691 static void memcg_stats_lock(void)
692 {
693 	preempt_disable_nested();
694 	VM_WARN_ON_IRQS_ENABLED();
695 }
696 
697 static void __memcg_stats_lock(void)
698 {
699 	preempt_disable_nested();
700 }
701 
702 static void memcg_stats_unlock(void)
703 {
704 	preempt_enable_nested();
705 }
706 
707 
708 static bool memcg_vmstats_needs_flush(struct memcg_vmstats *vmstats)
709 {
710 	return atomic64_read(&vmstats->stats_updates) >
711 		MEMCG_CHARGE_BATCH * num_online_cpus();
712 }
713 
714 static inline void memcg_rstat_updated(struct mem_cgroup *memcg, int val)
715 {
716 	struct memcg_vmstats_percpu *statc;
717 	int cpu = smp_processor_id();
718 
719 	if (!val)
720 		return;
721 
722 	cgroup_rstat_updated(memcg->css.cgroup, cpu);
723 	statc = this_cpu_ptr(memcg->vmstats_percpu);
724 	for (; statc; statc = statc->parent) {
725 		statc->stats_updates += abs(val);
726 		if (statc->stats_updates < MEMCG_CHARGE_BATCH)
727 			continue;
728 
729 		/*
730 		 * If @memcg is already flush-able, increasing stats_updates is
731 		 * redundant. Avoid the overhead of the atomic update.
732 		 */
733 		if (!memcg_vmstats_needs_flush(statc->vmstats))
734 			atomic64_add(statc->stats_updates,
735 				     &statc->vmstats->stats_updates);
736 		statc->stats_updates = 0;
737 	}
738 }
739 
740 static void do_flush_stats(struct mem_cgroup *memcg)
741 {
742 	if (mem_cgroup_is_root(memcg))
743 		WRITE_ONCE(flush_last_time, jiffies_64);
744 
745 	cgroup_rstat_flush(memcg->css.cgroup);
746 }
747 
748 /*
749  * mem_cgroup_flush_stats - flush the stats of a memory cgroup subtree
750  * @memcg: root of the subtree to flush
751  *
752  * Flushing is serialized by the underlying global rstat lock. There is also a
753  * minimum amount of work to be done even if there are no stat updates to flush.
754  * Hence, we only flush the stats if the updates delta exceeds a threshold. This
755  * avoids unnecessary work and contention on the underlying lock.
756  */
757 void mem_cgroup_flush_stats(struct mem_cgroup *memcg)
758 {
759 	if (mem_cgroup_disabled())
760 		return;
761 
762 	if (!memcg)
763 		memcg = root_mem_cgroup;
764 
765 	if (memcg_vmstats_needs_flush(memcg->vmstats))
766 		do_flush_stats(memcg);
767 }
768 
769 void mem_cgroup_flush_stats_ratelimited(struct mem_cgroup *memcg)
770 {
771 	/* Only flush if the periodic flusher is one full cycle late */
772 	if (time_after64(jiffies_64, READ_ONCE(flush_last_time) + 2*FLUSH_TIME))
773 		mem_cgroup_flush_stats(memcg);
774 }
775 
776 static void flush_memcg_stats_dwork(struct work_struct *w)
777 {
778 	/*
779 	 * Deliberately ignore memcg_vmstats_needs_flush() here so that flushing
780 	 * in latency-sensitive paths is as cheap as possible.
781 	 */
782 	do_flush_stats(root_mem_cgroup);
783 	queue_delayed_work(system_unbound_wq, &stats_flush_dwork, FLUSH_TIME);
784 }
785 
786 unsigned long memcg_page_state(struct mem_cgroup *memcg, int idx)
787 {
788 	long x = READ_ONCE(memcg->vmstats->state[idx]);
789 #ifdef CONFIG_SMP
790 	if (x < 0)
791 		x = 0;
792 #endif
793 	return x;
794 }
795 
796 static int memcg_page_state_unit(int item);
797 
798 /*
799  * Normalize the value passed into memcg_rstat_updated() to be in pages. Round
800  * up non-zero sub-page updates to 1 page as zero page updates are ignored.
801  */
802 static int memcg_state_val_in_pages(int idx, int val)
803 {
804 	int unit = memcg_page_state_unit(idx);
805 
806 	if (!val || unit == PAGE_SIZE)
807 		return val;
808 	else
809 		return max(val * unit / PAGE_SIZE, 1UL);
810 }
811 
812 /**
813  * __mod_memcg_state - update cgroup memory statistics
814  * @memcg: the memory cgroup
815  * @idx: the stat item - can be enum memcg_stat_item or enum node_stat_item
816  * @val: delta to add to the counter, can be negative
817  */
818 void __mod_memcg_state(struct mem_cgroup *memcg, int idx, int val)
819 {
820 	if (mem_cgroup_disabled())
821 		return;
822 
823 	__this_cpu_add(memcg->vmstats_percpu->state[idx], val);
824 	memcg_rstat_updated(memcg, memcg_state_val_in_pages(idx, val));
825 }
826 
827 /* idx can be of type enum memcg_stat_item or node_stat_item. */
828 static unsigned long memcg_page_state_local(struct mem_cgroup *memcg, int idx)
829 {
830 	long x = READ_ONCE(memcg->vmstats->state_local[idx]);
831 
832 #ifdef CONFIG_SMP
833 	if (x < 0)
834 		x = 0;
835 #endif
836 	return x;
837 }
838 
839 void __mod_memcg_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
840 			      int val)
841 {
842 	struct mem_cgroup_per_node *pn;
843 	struct mem_cgroup *memcg;
844 
845 	pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
846 	memcg = pn->memcg;
847 
848 	/*
849 	 * The caller from rmap relies on disabled preemption because they never
850 	 * update their counter from in-interrupt context. For these two
851 	 * counters we check that the update is never performed from an
852 	 * interrupt context while other caller need to have disabled interrupt.
853 	 */
854 	__memcg_stats_lock();
855 	if (IS_ENABLED(CONFIG_DEBUG_VM)) {
856 		switch (idx) {
857 		case NR_ANON_MAPPED:
858 		case NR_FILE_MAPPED:
859 		case NR_ANON_THPS:
860 		case NR_SHMEM_PMDMAPPED:
861 		case NR_FILE_PMDMAPPED:
862 			WARN_ON_ONCE(!in_task());
863 			break;
864 		default:
865 			VM_WARN_ON_IRQS_ENABLED();
866 		}
867 	}
868 
869 	/* Update memcg */
870 	__this_cpu_add(memcg->vmstats_percpu->state[idx], val);
871 
872 	/* Update lruvec */
873 	__this_cpu_add(pn->lruvec_stats_percpu->state[idx], val);
874 
875 	memcg_rstat_updated(memcg, memcg_state_val_in_pages(idx, val));
876 	memcg_stats_unlock();
877 }
878 
879 /**
880  * __mod_lruvec_state - update lruvec memory statistics
881  * @lruvec: the lruvec
882  * @idx: the stat item
883  * @val: delta to add to the counter, can be negative
884  *
885  * The lruvec is the intersection of the NUMA node and a cgroup. This
886  * function updates the all three counters that are affected by a
887  * change of state at this level: per-node, per-cgroup, per-lruvec.
888  */
889 void __mod_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
890 			int val)
891 {
892 	/* Update node */
893 	__mod_node_page_state(lruvec_pgdat(lruvec), idx, val);
894 
895 	/* Update memcg and lruvec */
896 	if (!mem_cgroup_disabled())
897 		__mod_memcg_lruvec_state(lruvec, idx, val);
898 }
899 
900 void __lruvec_stat_mod_folio(struct folio *folio, enum node_stat_item idx,
901 			     int val)
902 {
903 	struct mem_cgroup *memcg;
904 	pg_data_t *pgdat = folio_pgdat(folio);
905 	struct lruvec *lruvec;
906 
907 	rcu_read_lock();
908 	memcg = folio_memcg(folio);
909 	/* Untracked pages have no memcg, no lruvec. Update only the node */
910 	if (!memcg) {
911 		rcu_read_unlock();
912 		__mod_node_page_state(pgdat, idx, val);
913 		return;
914 	}
915 
916 	lruvec = mem_cgroup_lruvec(memcg, pgdat);
917 	__mod_lruvec_state(lruvec, idx, val);
918 	rcu_read_unlock();
919 }
920 EXPORT_SYMBOL(__lruvec_stat_mod_folio);
921 
922 void __mod_lruvec_kmem_state(void *p, enum node_stat_item idx, int val)
923 {
924 	pg_data_t *pgdat = page_pgdat(virt_to_page(p));
925 	struct mem_cgroup *memcg;
926 	struct lruvec *lruvec;
927 
928 	rcu_read_lock();
929 	memcg = mem_cgroup_from_slab_obj(p);
930 
931 	/*
932 	 * Untracked pages have no memcg, no lruvec. Update only the
933 	 * node. If we reparent the slab objects to the root memcg,
934 	 * when we free the slab object, we need to update the per-memcg
935 	 * vmstats to keep it correct for the root memcg.
936 	 */
937 	if (!memcg) {
938 		__mod_node_page_state(pgdat, idx, val);
939 	} else {
940 		lruvec = mem_cgroup_lruvec(memcg, pgdat);
941 		__mod_lruvec_state(lruvec, idx, val);
942 	}
943 	rcu_read_unlock();
944 }
945 
946 /**
947  * __count_memcg_events - account VM events in a cgroup
948  * @memcg: the memory cgroup
949  * @idx: the event item
950  * @count: the number of events that occurred
951  */
952 void __count_memcg_events(struct mem_cgroup *memcg, enum vm_event_item idx,
953 			  unsigned long count)
954 {
955 	int index = memcg_events_index(idx);
956 
957 	if (mem_cgroup_disabled() || index < 0)
958 		return;
959 
960 	memcg_stats_lock();
961 	__this_cpu_add(memcg->vmstats_percpu->events[index], count);
962 	memcg_rstat_updated(memcg, count);
963 	memcg_stats_unlock();
964 }
965 
966 static unsigned long memcg_events(struct mem_cgroup *memcg, int event)
967 {
968 	int index = memcg_events_index(event);
969 
970 	if (index < 0)
971 		return 0;
972 	return READ_ONCE(memcg->vmstats->events[index]);
973 }
974 
975 static unsigned long memcg_events_local(struct mem_cgroup *memcg, int event)
976 {
977 	int index = memcg_events_index(event);
978 
979 	if (index < 0)
980 		return 0;
981 
982 	return READ_ONCE(memcg->vmstats->events_local[index]);
983 }
984 
985 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
986 					 int nr_pages)
987 {
988 	/* pagein of a big page is an event. So, ignore page size */
989 	if (nr_pages > 0)
990 		__count_memcg_events(memcg, PGPGIN, 1);
991 	else {
992 		__count_memcg_events(memcg, PGPGOUT, 1);
993 		nr_pages = -nr_pages; /* for event */
994 	}
995 
996 	__this_cpu_add(memcg->vmstats_percpu->nr_page_events, nr_pages);
997 }
998 
999 static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
1000 				       enum mem_cgroup_events_target target)
1001 {
1002 	unsigned long val, next;
1003 
1004 	val = __this_cpu_read(memcg->vmstats_percpu->nr_page_events);
1005 	next = __this_cpu_read(memcg->vmstats_percpu->targets[target]);
1006 	/* from time_after() in jiffies.h */
1007 	if ((long)(next - val) < 0) {
1008 		switch (target) {
1009 		case MEM_CGROUP_TARGET_THRESH:
1010 			next = val + THRESHOLDS_EVENTS_TARGET;
1011 			break;
1012 		case MEM_CGROUP_TARGET_SOFTLIMIT:
1013 			next = val + SOFTLIMIT_EVENTS_TARGET;
1014 			break;
1015 		default:
1016 			break;
1017 		}
1018 		__this_cpu_write(memcg->vmstats_percpu->targets[target], next);
1019 		return true;
1020 	}
1021 	return false;
1022 }
1023 
1024 /*
1025  * Check events in order.
1026  *
1027  */
1028 static void memcg_check_events(struct mem_cgroup *memcg, int nid)
1029 {
1030 	if (IS_ENABLED(CONFIG_PREEMPT_RT))
1031 		return;
1032 
1033 	/* threshold event is triggered in finer grain than soft limit */
1034 	if (unlikely(mem_cgroup_event_ratelimit(memcg,
1035 						MEM_CGROUP_TARGET_THRESH))) {
1036 		bool do_softlimit;
1037 
1038 		do_softlimit = mem_cgroup_event_ratelimit(memcg,
1039 						MEM_CGROUP_TARGET_SOFTLIMIT);
1040 		mem_cgroup_threshold(memcg);
1041 		if (unlikely(do_softlimit))
1042 			mem_cgroup_update_tree(memcg, nid);
1043 	}
1044 }
1045 
1046 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
1047 {
1048 	/*
1049 	 * mm_update_next_owner() may clear mm->owner to NULL
1050 	 * if it races with swapoff, page migration, etc.
1051 	 * So this can be called with p == NULL.
1052 	 */
1053 	if (unlikely(!p))
1054 		return NULL;
1055 
1056 	return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
1057 }
1058 EXPORT_SYMBOL(mem_cgroup_from_task);
1059 
1060 static __always_inline struct mem_cgroup *active_memcg(void)
1061 {
1062 	if (!in_task())
1063 		return this_cpu_read(int_active_memcg);
1064 	else
1065 		return current->active_memcg;
1066 }
1067 
1068 /**
1069  * get_mem_cgroup_from_mm: Obtain a reference on given mm_struct's memcg.
1070  * @mm: mm from which memcg should be extracted. It can be NULL.
1071  *
1072  * Obtain a reference on mm->memcg and returns it if successful. If mm
1073  * is NULL, then the memcg is chosen as follows:
1074  * 1) The active memcg, if set.
1075  * 2) current->mm->memcg, if available
1076  * 3) root memcg
1077  * If mem_cgroup is disabled, NULL is returned.
1078  */
1079 struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
1080 {
1081 	struct mem_cgroup *memcg;
1082 
1083 	if (mem_cgroup_disabled())
1084 		return NULL;
1085 
1086 	/*
1087 	 * Page cache insertions can happen without an
1088 	 * actual mm context, e.g. during disk probing
1089 	 * on boot, loopback IO, acct() writes etc.
1090 	 *
1091 	 * No need to css_get on root memcg as the reference
1092 	 * counting is disabled on the root level in the
1093 	 * cgroup core. See CSS_NO_REF.
1094 	 */
1095 	if (unlikely(!mm)) {
1096 		memcg = active_memcg();
1097 		if (unlikely(memcg)) {
1098 			/* remote memcg must hold a ref */
1099 			css_get(&memcg->css);
1100 			return memcg;
1101 		}
1102 		mm = current->mm;
1103 		if (unlikely(!mm))
1104 			return root_mem_cgroup;
1105 	}
1106 
1107 	rcu_read_lock();
1108 	do {
1109 		memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
1110 		if (unlikely(!memcg))
1111 			memcg = root_mem_cgroup;
1112 	} while (!css_tryget(&memcg->css));
1113 	rcu_read_unlock();
1114 	return memcg;
1115 }
1116 EXPORT_SYMBOL(get_mem_cgroup_from_mm);
1117 
1118 /**
1119  * get_mem_cgroup_from_current - Obtain a reference on current task's memcg.
1120  */
1121 struct mem_cgroup *get_mem_cgroup_from_current(void)
1122 {
1123 	struct mem_cgroup *memcg;
1124 
1125 	if (mem_cgroup_disabled())
1126 		return NULL;
1127 
1128 again:
1129 	rcu_read_lock();
1130 	memcg = mem_cgroup_from_task(current);
1131 	if (!css_tryget(&memcg->css)) {
1132 		rcu_read_unlock();
1133 		goto again;
1134 	}
1135 	rcu_read_unlock();
1136 	return memcg;
1137 }
1138 
1139 /**
1140  * mem_cgroup_iter - iterate over memory cgroup hierarchy
1141  * @root: hierarchy root
1142  * @prev: previously returned memcg, NULL on first invocation
1143  * @reclaim: cookie for shared reclaim walks, NULL for full walks
1144  *
1145  * Returns references to children of the hierarchy below @root, or
1146  * @root itself, or %NULL after a full round-trip.
1147  *
1148  * Caller must pass the return value in @prev on subsequent
1149  * invocations for reference counting, or use mem_cgroup_iter_break()
1150  * to cancel a hierarchy walk before the round-trip is complete.
1151  *
1152  * Reclaimers can specify a node in @reclaim to divide up the memcgs
1153  * in the hierarchy among all concurrent reclaimers operating on the
1154  * same node.
1155  */
1156 struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
1157 				   struct mem_cgroup *prev,
1158 				   struct mem_cgroup_reclaim_cookie *reclaim)
1159 {
1160 	struct mem_cgroup_reclaim_iter *iter;
1161 	struct cgroup_subsys_state *css = NULL;
1162 	struct mem_cgroup *memcg = NULL;
1163 	struct mem_cgroup *pos = NULL;
1164 
1165 	if (mem_cgroup_disabled())
1166 		return NULL;
1167 
1168 	if (!root)
1169 		root = root_mem_cgroup;
1170 
1171 	rcu_read_lock();
1172 
1173 	if (reclaim) {
1174 		struct mem_cgroup_per_node *mz;
1175 
1176 		mz = root->nodeinfo[reclaim->pgdat->node_id];
1177 		iter = &mz->iter;
1178 
1179 		/*
1180 		 * On start, join the current reclaim iteration cycle.
1181 		 * Exit when a concurrent walker completes it.
1182 		 */
1183 		if (!prev)
1184 			reclaim->generation = iter->generation;
1185 		else if (reclaim->generation != iter->generation)
1186 			goto out_unlock;
1187 
1188 		while (1) {
1189 			pos = READ_ONCE(iter->position);
1190 			if (!pos || css_tryget(&pos->css))
1191 				break;
1192 			/*
1193 			 * css reference reached zero, so iter->position will
1194 			 * be cleared by ->css_released. However, we should not
1195 			 * rely on this happening soon, because ->css_released
1196 			 * is called from a work queue, and by busy-waiting we
1197 			 * might block it. So we clear iter->position right
1198 			 * away.
1199 			 */
1200 			(void)cmpxchg(&iter->position, pos, NULL);
1201 		}
1202 	} else if (prev) {
1203 		pos = prev;
1204 	}
1205 
1206 	if (pos)
1207 		css = &pos->css;
1208 
1209 	for (;;) {
1210 		css = css_next_descendant_pre(css, &root->css);
1211 		if (!css) {
1212 			/*
1213 			 * Reclaimers share the hierarchy walk, and a
1214 			 * new one might jump in right at the end of
1215 			 * the hierarchy - make sure they see at least
1216 			 * one group and restart from the beginning.
1217 			 */
1218 			if (!prev)
1219 				continue;
1220 			break;
1221 		}
1222 
1223 		/*
1224 		 * Verify the css and acquire a reference.  The root
1225 		 * is provided by the caller, so we know it's alive
1226 		 * and kicking, and don't take an extra reference.
1227 		 */
1228 		if (css == &root->css || css_tryget(css)) {
1229 			memcg = mem_cgroup_from_css(css);
1230 			break;
1231 		}
1232 	}
1233 
1234 	if (reclaim) {
1235 		/*
1236 		 * The position could have already been updated by a competing
1237 		 * thread, so check that the value hasn't changed since we read
1238 		 * it to avoid reclaiming from the same cgroup twice.
1239 		 */
1240 		(void)cmpxchg(&iter->position, pos, memcg);
1241 
1242 		if (pos)
1243 			css_put(&pos->css);
1244 
1245 		if (!memcg)
1246 			iter->generation++;
1247 	}
1248 
1249 out_unlock:
1250 	rcu_read_unlock();
1251 	if (prev && prev != root)
1252 		css_put(&prev->css);
1253 
1254 	return memcg;
1255 }
1256 
1257 /**
1258  * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1259  * @root: hierarchy root
1260  * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1261  */
1262 void mem_cgroup_iter_break(struct mem_cgroup *root,
1263 			   struct mem_cgroup *prev)
1264 {
1265 	if (!root)
1266 		root = root_mem_cgroup;
1267 	if (prev && prev != root)
1268 		css_put(&prev->css);
1269 }
1270 
1271 static void __invalidate_reclaim_iterators(struct mem_cgroup *from,
1272 					struct mem_cgroup *dead_memcg)
1273 {
1274 	struct mem_cgroup_reclaim_iter *iter;
1275 	struct mem_cgroup_per_node *mz;
1276 	int nid;
1277 
1278 	for_each_node(nid) {
1279 		mz = from->nodeinfo[nid];
1280 		iter = &mz->iter;
1281 		cmpxchg(&iter->position, dead_memcg, NULL);
1282 	}
1283 }
1284 
1285 static void invalidate_reclaim_iterators(struct mem_cgroup *dead_memcg)
1286 {
1287 	struct mem_cgroup *memcg = dead_memcg;
1288 	struct mem_cgroup *last;
1289 
1290 	do {
1291 		__invalidate_reclaim_iterators(memcg, dead_memcg);
1292 		last = memcg;
1293 	} while ((memcg = parent_mem_cgroup(memcg)));
1294 
1295 	/*
1296 	 * When cgroup1 non-hierarchy mode is used,
1297 	 * parent_mem_cgroup() does not walk all the way up to the
1298 	 * cgroup root (root_mem_cgroup). So we have to handle
1299 	 * dead_memcg from cgroup root separately.
1300 	 */
1301 	if (!mem_cgroup_is_root(last))
1302 		__invalidate_reclaim_iterators(root_mem_cgroup,
1303 						dead_memcg);
1304 }
1305 
1306 /**
1307  * mem_cgroup_scan_tasks - iterate over tasks of a memory cgroup hierarchy
1308  * @memcg: hierarchy root
1309  * @fn: function to call for each task
1310  * @arg: argument passed to @fn
1311  *
1312  * This function iterates over tasks attached to @memcg or to any of its
1313  * descendants and calls @fn for each task. If @fn returns a non-zero
1314  * value, the function breaks the iteration loop. Otherwise, it will iterate
1315  * over all tasks and return 0.
1316  *
1317  * This function must not be called for the root memory cgroup.
1318  */
1319 void mem_cgroup_scan_tasks(struct mem_cgroup *memcg,
1320 			   int (*fn)(struct task_struct *, void *), void *arg)
1321 {
1322 	struct mem_cgroup *iter;
1323 	int ret = 0;
1324 
1325 	BUG_ON(mem_cgroup_is_root(memcg));
1326 
1327 	for_each_mem_cgroup_tree(iter, memcg) {
1328 		struct css_task_iter it;
1329 		struct task_struct *task;
1330 
1331 		css_task_iter_start(&iter->css, CSS_TASK_ITER_PROCS, &it);
1332 		while (!ret && (task = css_task_iter_next(&it)))
1333 			ret = fn(task, arg);
1334 		css_task_iter_end(&it);
1335 		if (ret) {
1336 			mem_cgroup_iter_break(memcg, iter);
1337 			break;
1338 		}
1339 	}
1340 }
1341 
1342 #ifdef CONFIG_DEBUG_VM
1343 void lruvec_memcg_debug(struct lruvec *lruvec, struct folio *folio)
1344 {
1345 	struct mem_cgroup *memcg;
1346 
1347 	if (mem_cgroup_disabled())
1348 		return;
1349 
1350 	memcg = folio_memcg(folio);
1351 
1352 	if (!memcg)
1353 		VM_BUG_ON_FOLIO(!mem_cgroup_is_root(lruvec_memcg(lruvec)), folio);
1354 	else
1355 		VM_BUG_ON_FOLIO(lruvec_memcg(lruvec) != memcg, folio);
1356 }
1357 #endif
1358 
1359 /**
1360  * folio_lruvec_lock - Lock the lruvec for a folio.
1361  * @folio: Pointer to the folio.
1362  *
1363  * These functions are safe to use under any of the following conditions:
1364  * - folio locked
1365  * - folio_test_lru false
1366  * - folio_memcg_lock()
1367  * - folio frozen (refcount of 0)
1368  *
1369  * Return: The lruvec this folio is on with its lock held.
1370  */
1371 struct lruvec *folio_lruvec_lock(struct folio *folio)
1372 {
1373 	struct lruvec *lruvec = folio_lruvec(folio);
1374 
1375 	spin_lock(&lruvec->lru_lock);
1376 	lruvec_memcg_debug(lruvec, folio);
1377 
1378 	return lruvec;
1379 }
1380 
1381 /**
1382  * folio_lruvec_lock_irq - Lock the lruvec for a folio.
1383  * @folio: Pointer to the folio.
1384  *
1385  * These functions are safe to use under any of the following conditions:
1386  * - folio locked
1387  * - folio_test_lru false
1388  * - folio_memcg_lock()
1389  * - folio frozen (refcount of 0)
1390  *
1391  * Return: The lruvec this folio is on with its lock held and interrupts
1392  * disabled.
1393  */
1394 struct lruvec *folio_lruvec_lock_irq(struct folio *folio)
1395 {
1396 	struct lruvec *lruvec = folio_lruvec(folio);
1397 
1398 	spin_lock_irq(&lruvec->lru_lock);
1399 	lruvec_memcg_debug(lruvec, folio);
1400 
1401 	return lruvec;
1402 }
1403 
1404 /**
1405  * folio_lruvec_lock_irqsave - Lock the lruvec for a folio.
1406  * @folio: Pointer to the folio.
1407  * @flags: Pointer to irqsave flags.
1408  *
1409  * These functions are safe to use under any of the following conditions:
1410  * - folio locked
1411  * - folio_test_lru false
1412  * - folio_memcg_lock()
1413  * - folio frozen (refcount of 0)
1414  *
1415  * Return: The lruvec this folio is on with its lock held and interrupts
1416  * disabled.
1417  */
1418 struct lruvec *folio_lruvec_lock_irqsave(struct folio *folio,
1419 		unsigned long *flags)
1420 {
1421 	struct lruvec *lruvec = folio_lruvec(folio);
1422 
1423 	spin_lock_irqsave(&lruvec->lru_lock, *flags);
1424 	lruvec_memcg_debug(lruvec, folio);
1425 
1426 	return lruvec;
1427 }
1428 
1429 /**
1430  * mem_cgroup_update_lru_size - account for adding or removing an lru page
1431  * @lruvec: mem_cgroup per zone lru vector
1432  * @lru: index of lru list the page is sitting on
1433  * @zid: zone id of the accounted pages
1434  * @nr_pages: positive when adding or negative when removing
1435  *
1436  * This function must be called under lru_lock, just before a page is added
1437  * to or just after a page is removed from an lru list.
1438  */
1439 void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
1440 				int zid, int nr_pages)
1441 {
1442 	struct mem_cgroup_per_node *mz;
1443 	unsigned long *lru_size;
1444 	long size;
1445 
1446 	if (mem_cgroup_disabled())
1447 		return;
1448 
1449 	mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
1450 	lru_size = &mz->lru_zone_size[zid][lru];
1451 
1452 	if (nr_pages < 0)
1453 		*lru_size += nr_pages;
1454 
1455 	size = *lru_size;
1456 	if (WARN_ONCE(size < 0,
1457 		"%s(%p, %d, %d): lru_size %ld\n",
1458 		__func__, lruvec, lru, nr_pages, size)) {
1459 		VM_BUG_ON(1);
1460 		*lru_size = 0;
1461 	}
1462 
1463 	if (nr_pages > 0)
1464 		*lru_size += nr_pages;
1465 }
1466 
1467 /**
1468  * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1469  * @memcg: the memory cgroup
1470  *
1471  * Returns the maximum amount of memory @mem can be charged with, in
1472  * pages.
1473  */
1474 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1475 {
1476 	unsigned long margin = 0;
1477 	unsigned long count;
1478 	unsigned long limit;
1479 
1480 	count = page_counter_read(&memcg->memory);
1481 	limit = READ_ONCE(memcg->memory.max);
1482 	if (count < limit)
1483 		margin = limit - count;
1484 
1485 	if (do_memsw_account()) {
1486 		count = page_counter_read(&memcg->memsw);
1487 		limit = READ_ONCE(memcg->memsw.max);
1488 		if (count < limit)
1489 			margin = min(margin, limit - count);
1490 		else
1491 			margin = 0;
1492 	}
1493 
1494 	return margin;
1495 }
1496 
1497 /*
1498  * A routine for checking "mem" is under move_account() or not.
1499  *
1500  * Checking a cgroup is mc.from or mc.to or under hierarchy of
1501  * moving cgroups. This is for waiting at high-memory pressure
1502  * caused by "move".
1503  */
1504 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1505 {
1506 	struct mem_cgroup *from;
1507 	struct mem_cgroup *to;
1508 	bool ret = false;
1509 	/*
1510 	 * Unlike task_move routines, we access mc.to, mc.from not under
1511 	 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1512 	 */
1513 	spin_lock(&mc.lock);
1514 	from = mc.from;
1515 	to = mc.to;
1516 	if (!from)
1517 		goto unlock;
1518 
1519 	ret = mem_cgroup_is_descendant(from, memcg) ||
1520 		mem_cgroup_is_descendant(to, memcg);
1521 unlock:
1522 	spin_unlock(&mc.lock);
1523 	return ret;
1524 }
1525 
1526 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1527 {
1528 	if (mc.moving_task && current != mc.moving_task) {
1529 		if (mem_cgroup_under_move(memcg)) {
1530 			DEFINE_WAIT(wait);
1531 			prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1532 			/* moving charge context might have finished. */
1533 			if (mc.moving_task)
1534 				schedule();
1535 			finish_wait(&mc.waitq, &wait);
1536 			return true;
1537 		}
1538 	}
1539 	return false;
1540 }
1541 
1542 struct memory_stat {
1543 	const char *name;
1544 	unsigned int idx;
1545 };
1546 
1547 static const struct memory_stat memory_stats[] = {
1548 	{ "anon",			NR_ANON_MAPPED			},
1549 	{ "file",			NR_FILE_PAGES			},
1550 	{ "kernel",			MEMCG_KMEM			},
1551 	{ "kernel_stack",		NR_KERNEL_STACK_KB		},
1552 	{ "pagetables",			NR_PAGETABLE			},
1553 	{ "sec_pagetables",		NR_SECONDARY_PAGETABLE		},
1554 	{ "percpu",			MEMCG_PERCPU_B			},
1555 	{ "sock",			MEMCG_SOCK			},
1556 	{ "vmalloc",			MEMCG_VMALLOC			},
1557 	{ "shmem",			NR_SHMEM			},
1558 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
1559 	{ "zswap",			MEMCG_ZSWAP_B			},
1560 	{ "zswapped",			MEMCG_ZSWAPPED			},
1561 #endif
1562 	{ "file_mapped",		NR_FILE_MAPPED			},
1563 	{ "file_dirty",			NR_FILE_DIRTY			},
1564 	{ "file_writeback",		NR_WRITEBACK			},
1565 #ifdef CONFIG_SWAP
1566 	{ "swapcached",			NR_SWAPCACHE			},
1567 #endif
1568 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1569 	{ "anon_thp",			NR_ANON_THPS			},
1570 	{ "file_thp",			NR_FILE_THPS			},
1571 	{ "shmem_thp",			NR_SHMEM_THPS			},
1572 #endif
1573 	{ "inactive_anon",		NR_INACTIVE_ANON		},
1574 	{ "active_anon",		NR_ACTIVE_ANON			},
1575 	{ "inactive_file",		NR_INACTIVE_FILE		},
1576 	{ "active_file",		NR_ACTIVE_FILE			},
1577 	{ "unevictable",		NR_UNEVICTABLE			},
1578 	{ "slab_reclaimable",		NR_SLAB_RECLAIMABLE_B		},
1579 	{ "slab_unreclaimable",		NR_SLAB_UNRECLAIMABLE_B		},
1580 
1581 	/* The memory events */
1582 	{ "workingset_refault_anon",	WORKINGSET_REFAULT_ANON		},
1583 	{ "workingset_refault_file",	WORKINGSET_REFAULT_FILE		},
1584 	{ "workingset_activate_anon",	WORKINGSET_ACTIVATE_ANON	},
1585 	{ "workingset_activate_file",	WORKINGSET_ACTIVATE_FILE	},
1586 	{ "workingset_restore_anon",	WORKINGSET_RESTORE_ANON		},
1587 	{ "workingset_restore_file",	WORKINGSET_RESTORE_FILE		},
1588 	{ "workingset_nodereclaim",	WORKINGSET_NODERECLAIM		},
1589 };
1590 
1591 /* The actual unit of the state item, not the same as the output unit */
1592 static int memcg_page_state_unit(int item)
1593 {
1594 	switch (item) {
1595 	case MEMCG_PERCPU_B:
1596 	case MEMCG_ZSWAP_B:
1597 	case NR_SLAB_RECLAIMABLE_B:
1598 	case NR_SLAB_UNRECLAIMABLE_B:
1599 		return 1;
1600 	case NR_KERNEL_STACK_KB:
1601 		return SZ_1K;
1602 	default:
1603 		return PAGE_SIZE;
1604 	}
1605 }
1606 
1607 /* Translate stat items to the correct unit for memory.stat output */
1608 static int memcg_page_state_output_unit(int item)
1609 {
1610 	/*
1611 	 * Workingset state is actually in pages, but we export it to userspace
1612 	 * as a scalar count of events, so special case it here.
1613 	 */
1614 	switch (item) {
1615 	case WORKINGSET_REFAULT_ANON:
1616 	case WORKINGSET_REFAULT_FILE:
1617 	case WORKINGSET_ACTIVATE_ANON:
1618 	case WORKINGSET_ACTIVATE_FILE:
1619 	case WORKINGSET_RESTORE_ANON:
1620 	case WORKINGSET_RESTORE_FILE:
1621 	case WORKINGSET_NODERECLAIM:
1622 		return 1;
1623 	default:
1624 		return memcg_page_state_unit(item);
1625 	}
1626 }
1627 
1628 static inline unsigned long memcg_page_state_output(struct mem_cgroup *memcg,
1629 						    int item)
1630 {
1631 	return memcg_page_state(memcg, item) *
1632 		memcg_page_state_output_unit(item);
1633 }
1634 
1635 static inline unsigned long memcg_page_state_local_output(
1636 		struct mem_cgroup *memcg, int item)
1637 {
1638 	return memcg_page_state_local(memcg, item) *
1639 		memcg_page_state_output_unit(item);
1640 }
1641 
1642 static void memcg_stat_format(struct mem_cgroup *memcg, struct seq_buf *s)
1643 {
1644 	int i;
1645 
1646 	/*
1647 	 * Provide statistics on the state of the memory subsystem as
1648 	 * well as cumulative event counters that show past behavior.
1649 	 *
1650 	 * This list is ordered following a combination of these gradients:
1651 	 * 1) generic big picture -> specifics and details
1652 	 * 2) reflecting userspace activity -> reflecting kernel heuristics
1653 	 *
1654 	 * Current memory state:
1655 	 */
1656 	mem_cgroup_flush_stats(memcg);
1657 
1658 	for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
1659 		u64 size;
1660 
1661 		size = memcg_page_state_output(memcg, memory_stats[i].idx);
1662 		seq_buf_printf(s, "%s %llu\n", memory_stats[i].name, size);
1663 
1664 		if (unlikely(memory_stats[i].idx == NR_SLAB_UNRECLAIMABLE_B)) {
1665 			size += memcg_page_state_output(memcg,
1666 							NR_SLAB_RECLAIMABLE_B);
1667 			seq_buf_printf(s, "slab %llu\n", size);
1668 		}
1669 	}
1670 
1671 	/* Accumulated memory events */
1672 	seq_buf_printf(s, "pgscan %lu\n",
1673 		       memcg_events(memcg, PGSCAN_KSWAPD) +
1674 		       memcg_events(memcg, PGSCAN_DIRECT) +
1675 		       memcg_events(memcg, PGSCAN_KHUGEPAGED));
1676 	seq_buf_printf(s, "pgsteal %lu\n",
1677 		       memcg_events(memcg, PGSTEAL_KSWAPD) +
1678 		       memcg_events(memcg, PGSTEAL_DIRECT) +
1679 		       memcg_events(memcg, PGSTEAL_KHUGEPAGED));
1680 
1681 	for (i = 0; i < ARRAY_SIZE(memcg_vm_event_stat); i++) {
1682 		if (memcg_vm_event_stat[i] == PGPGIN ||
1683 		    memcg_vm_event_stat[i] == PGPGOUT)
1684 			continue;
1685 
1686 		seq_buf_printf(s, "%s %lu\n",
1687 			       vm_event_name(memcg_vm_event_stat[i]),
1688 			       memcg_events(memcg, memcg_vm_event_stat[i]));
1689 	}
1690 
1691 	/* The above should easily fit into one page */
1692 	WARN_ON_ONCE(seq_buf_has_overflowed(s));
1693 }
1694 
1695 static void memcg1_stat_format(struct mem_cgroup *memcg, struct seq_buf *s);
1696 
1697 static void memory_stat_format(struct mem_cgroup *memcg, struct seq_buf *s)
1698 {
1699 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1700 		memcg_stat_format(memcg, s);
1701 	else
1702 		memcg1_stat_format(memcg, s);
1703 	WARN_ON_ONCE(seq_buf_has_overflowed(s));
1704 }
1705 
1706 /**
1707  * mem_cgroup_print_oom_context: Print OOM information relevant to
1708  * memory controller.
1709  * @memcg: The memory cgroup that went over limit
1710  * @p: Task that is going to be killed
1711  *
1712  * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1713  * enabled
1714  */
1715 void mem_cgroup_print_oom_context(struct mem_cgroup *memcg, struct task_struct *p)
1716 {
1717 	rcu_read_lock();
1718 
1719 	if (memcg) {
1720 		pr_cont(",oom_memcg=");
1721 		pr_cont_cgroup_path(memcg->css.cgroup);
1722 	} else
1723 		pr_cont(",global_oom");
1724 	if (p) {
1725 		pr_cont(",task_memcg=");
1726 		pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
1727 	}
1728 	rcu_read_unlock();
1729 }
1730 
1731 /**
1732  * mem_cgroup_print_oom_meminfo: Print OOM memory information relevant to
1733  * memory controller.
1734  * @memcg: The memory cgroup that went over limit
1735  */
1736 void mem_cgroup_print_oom_meminfo(struct mem_cgroup *memcg)
1737 {
1738 	/* Use static buffer, for the caller is holding oom_lock. */
1739 	static char buf[PAGE_SIZE];
1740 	struct seq_buf s;
1741 
1742 	lockdep_assert_held(&oom_lock);
1743 
1744 	pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
1745 		K((u64)page_counter_read(&memcg->memory)),
1746 		K((u64)READ_ONCE(memcg->memory.max)), memcg->memory.failcnt);
1747 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1748 		pr_info("swap: usage %llukB, limit %llukB, failcnt %lu\n",
1749 			K((u64)page_counter_read(&memcg->swap)),
1750 			K((u64)READ_ONCE(memcg->swap.max)), memcg->swap.failcnt);
1751 	else {
1752 		pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
1753 			K((u64)page_counter_read(&memcg->memsw)),
1754 			K((u64)memcg->memsw.max), memcg->memsw.failcnt);
1755 		pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
1756 			K((u64)page_counter_read(&memcg->kmem)),
1757 			K((u64)memcg->kmem.max), memcg->kmem.failcnt);
1758 	}
1759 
1760 	pr_info("Memory cgroup stats for ");
1761 	pr_cont_cgroup_path(memcg->css.cgroup);
1762 	pr_cont(":");
1763 	seq_buf_init(&s, buf, sizeof(buf));
1764 	memory_stat_format(memcg, &s);
1765 	seq_buf_do_printk(&s, KERN_INFO);
1766 }
1767 
1768 /*
1769  * Return the memory (and swap, if configured) limit for a memcg.
1770  */
1771 unsigned long mem_cgroup_get_max(struct mem_cgroup *memcg)
1772 {
1773 	unsigned long max = READ_ONCE(memcg->memory.max);
1774 
1775 	if (do_memsw_account()) {
1776 		if (mem_cgroup_swappiness(memcg)) {
1777 			/* Calculate swap excess capacity from memsw limit */
1778 			unsigned long swap = READ_ONCE(memcg->memsw.max) - max;
1779 
1780 			max += min(swap, (unsigned long)total_swap_pages);
1781 		}
1782 	} else {
1783 		if (mem_cgroup_swappiness(memcg))
1784 			max += min(READ_ONCE(memcg->swap.max),
1785 				   (unsigned long)total_swap_pages);
1786 	}
1787 	return max;
1788 }
1789 
1790 unsigned long mem_cgroup_size(struct mem_cgroup *memcg)
1791 {
1792 	return page_counter_read(&memcg->memory);
1793 }
1794 
1795 static bool mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
1796 				     int order)
1797 {
1798 	struct oom_control oc = {
1799 		.zonelist = NULL,
1800 		.nodemask = NULL,
1801 		.memcg = memcg,
1802 		.gfp_mask = gfp_mask,
1803 		.order = order,
1804 	};
1805 	bool ret = true;
1806 
1807 	if (mutex_lock_killable(&oom_lock))
1808 		return true;
1809 
1810 	if (mem_cgroup_margin(memcg) >= (1 << order))
1811 		goto unlock;
1812 
1813 	/*
1814 	 * A few threads which were not waiting at mutex_lock_killable() can
1815 	 * fail to bail out. Therefore, check again after holding oom_lock.
1816 	 */
1817 	ret = task_is_dying() || out_of_memory(&oc);
1818 
1819 unlock:
1820 	mutex_unlock(&oom_lock);
1821 	return ret;
1822 }
1823 
1824 static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
1825 				   pg_data_t *pgdat,
1826 				   gfp_t gfp_mask,
1827 				   unsigned long *total_scanned)
1828 {
1829 	struct mem_cgroup *victim = NULL;
1830 	int total = 0;
1831 	int loop = 0;
1832 	unsigned long excess;
1833 	unsigned long nr_scanned;
1834 	struct mem_cgroup_reclaim_cookie reclaim = {
1835 		.pgdat = pgdat,
1836 	};
1837 
1838 	excess = soft_limit_excess(root_memcg);
1839 
1840 	while (1) {
1841 		victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
1842 		if (!victim) {
1843 			loop++;
1844 			if (loop >= 2) {
1845 				/*
1846 				 * If we have not been able to reclaim
1847 				 * anything, it might because there are
1848 				 * no reclaimable pages under this hierarchy
1849 				 */
1850 				if (!total)
1851 					break;
1852 				/*
1853 				 * We want to do more targeted reclaim.
1854 				 * excess >> 2 is not to excessive so as to
1855 				 * reclaim too much, nor too less that we keep
1856 				 * coming back to reclaim from this cgroup
1857 				 */
1858 				if (total >= (excess >> 2) ||
1859 					(loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
1860 					break;
1861 			}
1862 			continue;
1863 		}
1864 		total += mem_cgroup_shrink_node(victim, gfp_mask, false,
1865 					pgdat, &nr_scanned);
1866 		*total_scanned += nr_scanned;
1867 		if (!soft_limit_excess(root_memcg))
1868 			break;
1869 	}
1870 	mem_cgroup_iter_break(root_memcg, victim);
1871 	return total;
1872 }
1873 
1874 #ifdef CONFIG_LOCKDEP
1875 static struct lockdep_map memcg_oom_lock_dep_map = {
1876 	.name = "memcg_oom_lock",
1877 };
1878 #endif
1879 
1880 static DEFINE_SPINLOCK(memcg_oom_lock);
1881 
1882 /*
1883  * Check OOM-Killer is already running under our hierarchy.
1884  * If someone is running, return false.
1885  */
1886 static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
1887 {
1888 	struct mem_cgroup *iter, *failed = NULL;
1889 
1890 	spin_lock(&memcg_oom_lock);
1891 
1892 	for_each_mem_cgroup_tree(iter, memcg) {
1893 		if (iter->oom_lock) {
1894 			/*
1895 			 * this subtree of our hierarchy is already locked
1896 			 * so we cannot give a lock.
1897 			 */
1898 			failed = iter;
1899 			mem_cgroup_iter_break(memcg, iter);
1900 			break;
1901 		} else
1902 			iter->oom_lock = true;
1903 	}
1904 
1905 	if (failed) {
1906 		/*
1907 		 * OK, we failed to lock the whole subtree so we have
1908 		 * to clean up what we set up to the failing subtree
1909 		 */
1910 		for_each_mem_cgroup_tree(iter, memcg) {
1911 			if (iter == failed) {
1912 				mem_cgroup_iter_break(memcg, iter);
1913 				break;
1914 			}
1915 			iter->oom_lock = false;
1916 		}
1917 	} else
1918 		mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_);
1919 
1920 	spin_unlock(&memcg_oom_lock);
1921 
1922 	return !failed;
1923 }
1924 
1925 static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
1926 {
1927 	struct mem_cgroup *iter;
1928 
1929 	spin_lock(&memcg_oom_lock);
1930 	mutex_release(&memcg_oom_lock_dep_map, _RET_IP_);
1931 	for_each_mem_cgroup_tree(iter, memcg)
1932 		iter->oom_lock = false;
1933 	spin_unlock(&memcg_oom_lock);
1934 }
1935 
1936 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
1937 {
1938 	struct mem_cgroup *iter;
1939 
1940 	spin_lock(&memcg_oom_lock);
1941 	for_each_mem_cgroup_tree(iter, memcg)
1942 		iter->under_oom++;
1943 	spin_unlock(&memcg_oom_lock);
1944 }
1945 
1946 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
1947 {
1948 	struct mem_cgroup *iter;
1949 
1950 	/*
1951 	 * Be careful about under_oom underflows because a child memcg
1952 	 * could have been added after mem_cgroup_mark_under_oom.
1953 	 */
1954 	spin_lock(&memcg_oom_lock);
1955 	for_each_mem_cgroup_tree(iter, memcg)
1956 		if (iter->under_oom > 0)
1957 			iter->under_oom--;
1958 	spin_unlock(&memcg_oom_lock);
1959 }
1960 
1961 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1962 
1963 struct oom_wait_info {
1964 	struct mem_cgroup *memcg;
1965 	wait_queue_entry_t	wait;
1966 };
1967 
1968 static int memcg_oom_wake_function(wait_queue_entry_t *wait,
1969 	unsigned mode, int sync, void *arg)
1970 {
1971 	struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
1972 	struct mem_cgroup *oom_wait_memcg;
1973 	struct oom_wait_info *oom_wait_info;
1974 
1975 	oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1976 	oom_wait_memcg = oom_wait_info->memcg;
1977 
1978 	if (!mem_cgroup_is_descendant(wake_memcg, oom_wait_memcg) &&
1979 	    !mem_cgroup_is_descendant(oom_wait_memcg, wake_memcg))
1980 		return 0;
1981 	return autoremove_wake_function(wait, mode, sync, arg);
1982 }
1983 
1984 static void memcg_oom_recover(struct mem_cgroup *memcg)
1985 {
1986 	/*
1987 	 * For the following lockless ->under_oom test, the only required
1988 	 * guarantee is that it must see the state asserted by an OOM when
1989 	 * this function is called as a result of userland actions
1990 	 * triggered by the notification of the OOM.  This is trivially
1991 	 * achieved by invoking mem_cgroup_mark_under_oom() before
1992 	 * triggering notification.
1993 	 */
1994 	if (memcg && memcg->under_oom)
1995 		__wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
1996 }
1997 
1998 /*
1999  * Returns true if successfully killed one or more processes. Though in some
2000  * corner cases it can return true even without killing any process.
2001  */
2002 static bool mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
2003 {
2004 	bool locked, ret;
2005 
2006 	if (order > PAGE_ALLOC_COSTLY_ORDER)
2007 		return false;
2008 
2009 	memcg_memory_event(memcg, MEMCG_OOM);
2010 
2011 	/*
2012 	 * We are in the middle of the charge context here, so we
2013 	 * don't want to block when potentially sitting on a callstack
2014 	 * that holds all kinds of filesystem and mm locks.
2015 	 *
2016 	 * cgroup1 allows disabling the OOM killer and waiting for outside
2017 	 * handling until the charge can succeed; remember the context and put
2018 	 * the task to sleep at the end of the page fault when all locks are
2019 	 * released.
2020 	 *
2021 	 * On the other hand, in-kernel OOM killer allows for an async victim
2022 	 * memory reclaim (oom_reaper) and that means that we are not solely
2023 	 * relying on the oom victim to make a forward progress and we can
2024 	 * invoke the oom killer here.
2025 	 *
2026 	 * Please note that mem_cgroup_out_of_memory might fail to find a
2027 	 * victim and then we have to bail out from the charge path.
2028 	 */
2029 	if (READ_ONCE(memcg->oom_kill_disable)) {
2030 		if (current->in_user_fault) {
2031 			css_get(&memcg->css);
2032 			current->memcg_in_oom = memcg;
2033 			current->memcg_oom_gfp_mask = mask;
2034 			current->memcg_oom_order = order;
2035 		}
2036 		return false;
2037 	}
2038 
2039 	mem_cgroup_mark_under_oom(memcg);
2040 
2041 	locked = mem_cgroup_oom_trylock(memcg);
2042 
2043 	if (locked)
2044 		mem_cgroup_oom_notify(memcg);
2045 
2046 	mem_cgroup_unmark_under_oom(memcg);
2047 	ret = mem_cgroup_out_of_memory(memcg, mask, order);
2048 
2049 	if (locked)
2050 		mem_cgroup_oom_unlock(memcg);
2051 
2052 	return ret;
2053 }
2054 
2055 /**
2056  * mem_cgroup_oom_synchronize - complete memcg OOM handling
2057  * @handle: actually kill/wait or just clean up the OOM state
2058  *
2059  * This has to be called at the end of a page fault if the memcg OOM
2060  * handler was enabled.
2061  *
2062  * Memcg supports userspace OOM handling where failed allocations must
2063  * sleep on a waitqueue until the userspace task resolves the
2064  * situation.  Sleeping directly in the charge context with all kinds
2065  * of locks held is not a good idea, instead we remember an OOM state
2066  * in the task and mem_cgroup_oom_synchronize() has to be called at
2067  * the end of the page fault to complete the OOM handling.
2068  *
2069  * Returns %true if an ongoing memcg OOM situation was detected and
2070  * completed, %false otherwise.
2071  */
2072 bool mem_cgroup_oom_synchronize(bool handle)
2073 {
2074 	struct mem_cgroup *memcg = current->memcg_in_oom;
2075 	struct oom_wait_info owait;
2076 	bool locked;
2077 
2078 	/* OOM is global, do not handle */
2079 	if (!memcg)
2080 		return false;
2081 
2082 	if (!handle)
2083 		goto cleanup;
2084 
2085 	owait.memcg = memcg;
2086 	owait.wait.flags = 0;
2087 	owait.wait.func = memcg_oom_wake_function;
2088 	owait.wait.private = current;
2089 	INIT_LIST_HEAD(&owait.wait.entry);
2090 
2091 	prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
2092 	mem_cgroup_mark_under_oom(memcg);
2093 
2094 	locked = mem_cgroup_oom_trylock(memcg);
2095 
2096 	if (locked)
2097 		mem_cgroup_oom_notify(memcg);
2098 
2099 	schedule();
2100 	mem_cgroup_unmark_under_oom(memcg);
2101 	finish_wait(&memcg_oom_waitq, &owait.wait);
2102 
2103 	if (locked)
2104 		mem_cgroup_oom_unlock(memcg);
2105 cleanup:
2106 	current->memcg_in_oom = NULL;
2107 	css_put(&memcg->css);
2108 	return true;
2109 }
2110 
2111 /**
2112  * mem_cgroup_get_oom_group - get a memory cgroup to clean up after OOM
2113  * @victim: task to be killed by the OOM killer
2114  * @oom_domain: memcg in case of memcg OOM, NULL in case of system-wide OOM
2115  *
2116  * Returns a pointer to a memory cgroup, which has to be cleaned up
2117  * by killing all belonging OOM-killable tasks.
2118  *
2119  * Caller has to call mem_cgroup_put() on the returned non-NULL memcg.
2120  */
2121 struct mem_cgroup *mem_cgroup_get_oom_group(struct task_struct *victim,
2122 					    struct mem_cgroup *oom_domain)
2123 {
2124 	struct mem_cgroup *oom_group = NULL;
2125 	struct mem_cgroup *memcg;
2126 
2127 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
2128 		return NULL;
2129 
2130 	if (!oom_domain)
2131 		oom_domain = root_mem_cgroup;
2132 
2133 	rcu_read_lock();
2134 
2135 	memcg = mem_cgroup_from_task(victim);
2136 	if (mem_cgroup_is_root(memcg))
2137 		goto out;
2138 
2139 	/*
2140 	 * If the victim task has been asynchronously moved to a different
2141 	 * memory cgroup, we might end up killing tasks outside oom_domain.
2142 	 * In this case it's better to ignore memory.group.oom.
2143 	 */
2144 	if (unlikely(!mem_cgroup_is_descendant(memcg, oom_domain)))
2145 		goto out;
2146 
2147 	/*
2148 	 * Traverse the memory cgroup hierarchy from the victim task's
2149 	 * cgroup up to the OOMing cgroup (or root) to find the
2150 	 * highest-level memory cgroup with oom.group set.
2151 	 */
2152 	for (; memcg; memcg = parent_mem_cgroup(memcg)) {
2153 		if (READ_ONCE(memcg->oom_group))
2154 			oom_group = memcg;
2155 
2156 		if (memcg == oom_domain)
2157 			break;
2158 	}
2159 
2160 	if (oom_group)
2161 		css_get(&oom_group->css);
2162 out:
2163 	rcu_read_unlock();
2164 
2165 	return oom_group;
2166 }
2167 
2168 void mem_cgroup_print_oom_group(struct mem_cgroup *memcg)
2169 {
2170 	pr_info("Tasks in ");
2171 	pr_cont_cgroup_path(memcg->css.cgroup);
2172 	pr_cont(" are going to be killed due to memory.oom.group set\n");
2173 }
2174 
2175 /**
2176  * folio_memcg_lock - Bind a folio to its memcg.
2177  * @folio: The folio.
2178  *
2179  * This function prevents unlocked LRU folios from being moved to
2180  * another cgroup.
2181  *
2182  * It ensures lifetime of the bound memcg.  The caller is responsible
2183  * for the lifetime of the folio.
2184  */
2185 void folio_memcg_lock(struct folio *folio)
2186 {
2187 	struct mem_cgroup *memcg;
2188 	unsigned long flags;
2189 
2190 	/*
2191 	 * The RCU lock is held throughout the transaction.  The fast
2192 	 * path can get away without acquiring the memcg->move_lock
2193 	 * because page moving starts with an RCU grace period.
2194          */
2195 	rcu_read_lock();
2196 
2197 	if (mem_cgroup_disabled())
2198 		return;
2199 again:
2200 	memcg = folio_memcg(folio);
2201 	if (unlikely(!memcg))
2202 		return;
2203 
2204 #ifdef CONFIG_PROVE_LOCKING
2205 	local_irq_save(flags);
2206 	might_lock(&memcg->move_lock);
2207 	local_irq_restore(flags);
2208 #endif
2209 
2210 	if (atomic_read(&memcg->moving_account) <= 0)
2211 		return;
2212 
2213 	spin_lock_irqsave(&memcg->move_lock, flags);
2214 	if (memcg != folio_memcg(folio)) {
2215 		spin_unlock_irqrestore(&memcg->move_lock, flags);
2216 		goto again;
2217 	}
2218 
2219 	/*
2220 	 * When charge migration first begins, we can have multiple
2221 	 * critical sections holding the fast-path RCU lock and one
2222 	 * holding the slowpath move_lock. Track the task who has the
2223 	 * move_lock for folio_memcg_unlock().
2224 	 */
2225 	memcg->move_lock_task = current;
2226 	memcg->move_lock_flags = flags;
2227 }
2228 
2229 static void __folio_memcg_unlock(struct mem_cgroup *memcg)
2230 {
2231 	if (memcg && memcg->move_lock_task == current) {
2232 		unsigned long flags = memcg->move_lock_flags;
2233 
2234 		memcg->move_lock_task = NULL;
2235 		memcg->move_lock_flags = 0;
2236 
2237 		spin_unlock_irqrestore(&memcg->move_lock, flags);
2238 	}
2239 
2240 	rcu_read_unlock();
2241 }
2242 
2243 /**
2244  * folio_memcg_unlock - Release the binding between a folio and its memcg.
2245  * @folio: The folio.
2246  *
2247  * This releases the binding created by folio_memcg_lock().  This does
2248  * not change the accounting of this folio to its memcg, but it does
2249  * permit others to change it.
2250  */
2251 void folio_memcg_unlock(struct folio *folio)
2252 {
2253 	__folio_memcg_unlock(folio_memcg(folio));
2254 }
2255 
2256 struct memcg_stock_pcp {
2257 	local_lock_t stock_lock;
2258 	struct mem_cgroup *cached; /* this never be root cgroup */
2259 	unsigned int nr_pages;
2260 
2261 #ifdef CONFIG_MEMCG_KMEM
2262 	struct obj_cgroup *cached_objcg;
2263 	struct pglist_data *cached_pgdat;
2264 	unsigned int nr_bytes;
2265 	int nr_slab_reclaimable_b;
2266 	int nr_slab_unreclaimable_b;
2267 #endif
2268 
2269 	struct work_struct work;
2270 	unsigned long flags;
2271 #define FLUSHING_CACHED_CHARGE	0
2272 };
2273 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock) = {
2274 	.stock_lock = INIT_LOCAL_LOCK(stock_lock),
2275 };
2276 static DEFINE_MUTEX(percpu_charge_mutex);
2277 
2278 #ifdef CONFIG_MEMCG_KMEM
2279 static struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock);
2280 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2281 				     struct mem_cgroup *root_memcg);
2282 static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages);
2283 
2284 #else
2285 static inline struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock)
2286 {
2287 	return NULL;
2288 }
2289 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2290 				     struct mem_cgroup *root_memcg)
2291 {
2292 	return false;
2293 }
2294 static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages)
2295 {
2296 }
2297 #endif
2298 
2299 /**
2300  * consume_stock: Try to consume stocked charge on this cpu.
2301  * @memcg: memcg to consume from.
2302  * @nr_pages: how many pages to charge.
2303  *
2304  * The charges will only happen if @memcg matches the current cpu's memcg
2305  * stock, and at least @nr_pages are available in that stock.  Failure to
2306  * service an allocation will refill the stock.
2307  *
2308  * returns true if successful, false otherwise.
2309  */
2310 static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2311 {
2312 	struct memcg_stock_pcp *stock;
2313 	unsigned long flags;
2314 	bool ret = false;
2315 
2316 	if (nr_pages > MEMCG_CHARGE_BATCH)
2317 		return ret;
2318 
2319 	local_lock_irqsave(&memcg_stock.stock_lock, flags);
2320 
2321 	stock = this_cpu_ptr(&memcg_stock);
2322 	if (memcg == READ_ONCE(stock->cached) && stock->nr_pages >= nr_pages) {
2323 		stock->nr_pages -= nr_pages;
2324 		ret = true;
2325 	}
2326 
2327 	local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
2328 
2329 	return ret;
2330 }
2331 
2332 /*
2333  * Returns stocks cached in percpu and reset cached information.
2334  */
2335 static void drain_stock(struct memcg_stock_pcp *stock)
2336 {
2337 	struct mem_cgroup *old = READ_ONCE(stock->cached);
2338 
2339 	if (!old)
2340 		return;
2341 
2342 	if (stock->nr_pages) {
2343 		page_counter_uncharge(&old->memory, stock->nr_pages);
2344 		if (do_memsw_account())
2345 			page_counter_uncharge(&old->memsw, stock->nr_pages);
2346 		stock->nr_pages = 0;
2347 	}
2348 
2349 	css_put(&old->css);
2350 	WRITE_ONCE(stock->cached, NULL);
2351 }
2352 
2353 static void drain_local_stock(struct work_struct *dummy)
2354 {
2355 	struct memcg_stock_pcp *stock;
2356 	struct obj_cgroup *old = NULL;
2357 	unsigned long flags;
2358 
2359 	/*
2360 	 * The only protection from cpu hotplug (memcg_hotplug_cpu_dead) vs.
2361 	 * drain_stock races is that we always operate on local CPU stock
2362 	 * here with IRQ disabled
2363 	 */
2364 	local_lock_irqsave(&memcg_stock.stock_lock, flags);
2365 
2366 	stock = this_cpu_ptr(&memcg_stock);
2367 	old = drain_obj_stock(stock);
2368 	drain_stock(stock);
2369 	clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2370 
2371 	local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
2372 	obj_cgroup_put(old);
2373 }
2374 
2375 /*
2376  * Cache charges(val) to local per_cpu area.
2377  * This will be consumed by consume_stock() function, later.
2378  */
2379 static void __refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2380 {
2381 	struct memcg_stock_pcp *stock;
2382 
2383 	stock = this_cpu_ptr(&memcg_stock);
2384 	if (READ_ONCE(stock->cached) != memcg) { /* reset if necessary */
2385 		drain_stock(stock);
2386 		css_get(&memcg->css);
2387 		WRITE_ONCE(stock->cached, memcg);
2388 	}
2389 	stock->nr_pages += nr_pages;
2390 
2391 	if (stock->nr_pages > MEMCG_CHARGE_BATCH)
2392 		drain_stock(stock);
2393 }
2394 
2395 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2396 {
2397 	unsigned long flags;
2398 
2399 	local_lock_irqsave(&memcg_stock.stock_lock, flags);
2400 	__refill_stock(memcg, nr_pages);
2401 	local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
2402 }
2403 
2404 /*
2405  * Drains all per-CPU charge caches for given root_memcg resp. subtree
2406  * of the hierarchy under it.
2407  */
2408 static void drain_all_stock(struct mem_cgroup *root_memcg)
2409 {
2410 	int cpu, curcpu;
2411 
2412 	/* If someone's already draining, avoid adding running more workers. */
2413 	if (!mutex_trylock(&percpu_charge_mutex))
2414 		return;
2415 	/*
2416 	 * Notify other cpus that system-wide "drain" is running
2417 	 * We do not care about races with the cpu hotplug because cpu down
2418 	 * as well as workers from this path always operate on the local
2419 	 * per-cpu data. CPU up doesn't touch memcg_stock at all.
2420 	 */
2421 	migrate_disable();
2422 	curcpu = smp_processor_id();
2423 	for_each_online_cpu(cpu) {
2424 		struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2425 		struct mem_cgroup *memcg;
2426 		bool flush = false;
2427 
2428 		rcu_read_lock();
2429 		memcg = READ_ONCE(stock->cached);
2430 		if (memcg && stock->nr_pages &&
2431 		    mem_cgroup_is_descendant(memcg, root_memcg))
2432 			flush = true;
2433 		else if (obj_stock_flush_required(stock, root_memcg))
2434 			flush = true;
2435 		rcu_read_unlock();
2436 
2437 		if (flush &&
2438 		    !test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2439 			if (cpu == curcpu)
2440 				drain_local_stock(&stock->work);
2441 			else if (!cpu_is_isolated(cpu))
2442 				schedule_work_on(cpu, &stock->work);
2443 		}
2444 	}
2445 	migrate_enable();
2446 	mutex_unlock(&percpu_charge_mutex);
2447 }
2448 
2449 static int memcg_hotplug_cpu_dead(unsigned int cpu)
2450 {
2451 	struct memcg_stock_pcp *stock;
2452 
2453 	stock = &per_cpu(memcg_stock, cpu);
2454 	drain_stock(stock);
2455 
2456 	return 0;
2457 }
2458 
2459 static unsigned long reclaim_high(struct mem_cgroup *memcg,
2460 				  unsigned int nr_pages,
2461 				  gfp_t gfp_mask)
2462 {
2463 	unsigned long nr_reclaimed = 0;
2464 
2465 	do {
2466 		unsigned long pflags;
2467 
2468 		if (page_counter_read(&memcg->memory) <=
2469 		    READ_ONCE(memcg->memory.high))
2470 			continue;
2471 
2472 		memcg_memory_event(memcg, MEMCG_HIGH);
2473 
2474 		psi_memstall_enter(&pflags);
2475 		nr_reclaimed += try_to_free_mem_cgroup_pages(memcg, nr_pages,
2476 							gfp_mask,
2477 							MEMCG_RECLAIM_MAY_SWAP);
2478 		psi_memstall_leave(&pflags);
2479 	} while ((memcg = parent_mem_cgroup(memcg)) &&
2480 		 !mem_cgroup_is_root(memcg));
2481 
2482 	return nr_reclaimed;
2483 }
2484 
2485 static void high_work_func(struct work_struct *work)
2486 {
2487 	struct mem_cgroup *memcg;
2488 
2489 	memcg = container_of(work, struct mem_cgroup, high_work);
2490 	reclaim_high(memcg, MEMCG_CHARGE_BATCH, GFP_KERNEL);
2491 }
2492 
2493 /*
2494  * Clamp the maximum sleep time per allocation batch to 2 seconds. This is
2495  * enough to still cause a significant slowdown in most cases, while still
2496  * allowing diagnostics and tracing to proceed without becoming stuck.
2497  */
2498 #define MEMCG_MAX_HIGH_DELAY_JIFFIES (2UL*HZ)
2499 
2500 /*
2501  * When calculating the delay, we use these either side of the exponentiation to
2502  * maintain precision and scale to a reasonable number of jiffies (see the table
2503  * below.
2504  *
2505  * - MEMCG_DELAY_PRECISION_SHIFT: Extra precision bits while translating the
2506  *   overage ratio to a delay.
2507  * - MEMCG_DELAY_SCALING_SHIFT: The number of bits to scale down the
2508  *   proposed penalty in order to reduce to a reasonable number of jiffies, and
2509  *   to produce a reasonable delay curve.
2510  *
2511  * MEMCG_DELAY_SCALING_SHIFT just happens to be a number that produces a
2512  * reasonable delay curve compared to precision-adjusted overage, not
2513  * penalising heavily at first, but still making sure that growth beyond the
2514  * limit penalises misbehaviour cgroups by slowing them down exponentially. For
2515  * example, with a high of 100 megabytes:
2516  *
2517  *  +-------+------------------------+
2518  *  | usage | time to allocate in ms |
2519  *  +-------+------------------------+
2520  *  | 100M  |                      0 |
2521  *  | 101M  |                      6 |
2522  *  | 102M  |                     25 |
2523  *  | 103M  |                     57 |
2524  *  | 104M  |                    102 |
2525  *  | 105M  |                    159 |
2526  *  | 106M  |                    230 |
2527  *  | 107M  |                    313 |
2528  *  | 108M  |                    409 |
2529  *  | 109M  |                    518 |
2530  *  | 110M  |                    639 |
2531  *  | 111M  |                    774 |
2532  *  | 112M  |                    921 |
2533  *  | 113M  |                   1081 |
2534  *  | 114M  |                   1254 |
2535  *  | 115M  |                   1439 |
2536  *  | 116M  |                   1638 |
2537  *  | 117M  |                   1849 |
2538  *  | 118M  |                   2000 |
2539  *  | 119M  |                   2000 |
2540  *  | 120M  |                   2000 |
2541  *  +-------+------------------------+
2542  */
2543  #define MEMCG_DELAY_PRECISION_SHIFT 20
2544  #define MEMCG_DELAY_SCALING_SHIFT 14
2545 
2546 static u64 calculate_overage(unsigned long usage, unsigned long high)
2547 {
2548 	u64 overage;
2549 
2550 	if (usage <= high)
2551 		return 0;
2552 
2553 	/*
2554 	 * Prevent division by 0 in overage calculation by acting as if
2555 	 * it was a threshold of 1 page
2556 	 */
2557 	high = max(high, 1UL);
2558 
2559 	overage = usage - high;
2560 	overage <<= MEMCG_DELAY_PRECISION_SHIFT;
2561 	return div64_u64(overage, high);
2562 }
2563 
2564 static u64 mem_find_max_overage(struct mem_cgroup *memcg)
2565 {
2566 	u64 overage, max_overage = 0;
2567 
2568 	do {
2569 		overage = calculate_overage(page_counter_read(&memcg->memory),
2570 					    READ_ONCE(memcg->memory.high));
2571 		max_overage = max(overage, max_overage);
2572 	} while ((memcg = parent_mem_cgroup(memcg)) &&
2573 		 !mem_cgroup_is_root(memcg));
2574 
2575 	return max_overage;
2576 }
2577 
2578 static u64 swap_find_max_overage(struct mem_cgroup *memcg)
2579 {
2580 	u64 overage, max_overage = 0;
2581 
2582 	do {
2583 		overage = calculate_overage(page_counter_read(&memcg->swap),
2584 					    READ_ONCE(memcg->swap.high));
2585 		if (overage)
2586 			memcg_memory_event(memcg, MEMCG_SWAP_HIGH);
2587 		max_overage = max(overage, max_overage);
2588 	} while ((memcg = parent_mem_cgroup(memcg)) &&
2589 		 !mem_cgroup_is_root(memcg));
2590 
2591 	return max_overage;
2592 }
2593 
2594 /*
2595  * Get the number of jiffies that we should penalise a mischievous cgroup which
2596  * is exceeding its memory.high by checking both it and its ancestors.
2597  */
2598 static unsigned long calculate_high_delay(struct mem_cgroup *memcg,
2599 					  unsigned int nr_pages,
2600 					  u64 max_overage)
2601 {
2602 	unsigned long penalty_jiffies;
2603 
2604 	if (!max_overage)
2605 		return 0;
2606 
2607 	/*
2608 	 * We use overage compared to memory.high to calculate the number of
2609 	 * jiffies to sleep (penalty_jiffies). Ideally this value should be
2610 	 * fairly lenient on small overages, and increasingly harsh when the
2611 	 * memcg in question makes it clear that it has no intention of stopping
2612 	 * its crazy behaviour, so we exponentially increase the delay based on
2613 	 * overage amount.
2614 	 */
2615 	penalty_jiffies = max_overage * max_overage * HZ;
2616 	penalty_jiffies >>= MEMCG_DELAY_PRECISION_SHIFT;
2617 	penalty_jiffies >>= MEMCG_DELAY_SCALING_SHIFT;
2618 
2619 	/*
2620 	 * Factor in the task's own contribution to the overage, such that four
2621 	 * N-sized allocations are throttled approximately the same as one
2622 	 * 4N-sized allocation.
2623 	 *
2624 	 * MEMCG_CHARGE_BATCH pages is nominal, so work out how much smaller or
2625 	 * larger the current charge patch is than that.
2626 	 */
2627 	return penalty_jiffies * nr_pages / MEMCG_CHARGE_BATCH;
2628 }
2629 
2630 /*
2631  * Reclaims memory over the high limit. Called directly from
2632  * try_charge() (context permitting), as well as from the userland
2633  * return path where reclaim is always able to block.
2634  */
2635 void mem_cgroup_handle_over_high(gfp_t gfp_mask)
2636 {
2637 	unsigned long penalty_jiffies;
2638 	unsigned long pflags;
2639 	unsigned long nr_reclaimed;
2640 	unsigned int nr_pages = current->memcg_nr_pages_over_high;
2641 	int nr_retries = MAX_RECLAIM_RETRIES;
2642 	struct mem_cgroup *memcg;
2643 	bool in_retry = false;
2644 
2645 	if (likely(!nr_pages))
2646 		return;
2647 
2648 	memcg = get_mem_cgroup_from_mm(current->mm);
2649 	current->memcg_nr_pages_over_high = 0;
2650 
2651 retry_reclaim:
2652 	/*
2653 	 * Bail if the task is already exiting. Unlike memory.max,
2654 	 * memory.high enforcement isn't as strict, and there is no
2655 	 * OOM killer involved, which means the excess could already
2656 	 * be much bigger (and still growing) than it could for
2657 	 * memory.max; the dying task could get stuck in fruitless
2658 	 * reclaim for a long time, which isn't desirable.
2659 	 */
2660 	if (task_is_dying())
2661 		goto out;
2662 
2663 	/*
2664 	 * The allocating task should reclaim at least the batch size, but for
2665 	 * subsequent retries we only want to do what's necessary to prevent oom
2666 	 * or breaching resource isolation.
2667 	 *
2668 	 * This is distinct from memory.max or page allocator behaviour because
2669 	 * memory.high is currently batched, whereas memory.max and the page
2670 	 * allocator run every time an allocation is made.
2671 	 */
2672 	nr_reclaimed = reclaim_high(memcg,
2673 				    in_retry ? SWAP_CLUSTER_MAX : nr_pages,
2674 				    gfp_mask);
2675 
2676 	/*
2677 	 * memory.high is breached and reclaim is unable to keep up. Throttle
2678 	 * allocators proactively to slow down excessive growth.
2679 	 */
2680 	penalty_jiffies = calculate_high_delay(memcg, nr_pages,
2681 					       mem_find_max_overage(memcg));
2682 
2683 	penalty_jiffies += calculate_high_delay(memcg, nr_pages,
2684 						swap_find_max_overage(memcg));
2685 
2686 	/*
2687 	 * Clamp the max delay per usermode return so as to still keep the
2688 	 * application moving forwards and also permit diagnostics, albeit
2689 	 * extremely slowly.
2690 	 */
2691 	penalty_jiffies = min(penalty_jiffies, MEMCG_MAX_HIGH_DELAY_JIFFIES);
2692 
2693 	/*
2694 	 * Don't sleep if the amount of jiffies this memcg owes us is so low
2695 	 * that it's not even worth doing, in an attempt to be nice to those who
2696 	 * go only a small amount over their memory.high value and maybe haven't
2697 	 * been aggressively reclaimed enough yet.
2698 	 */
2699 	if (penalty_jiffies <= HZ / 100)
2700 		goto out;
2701 
2702 	/*
2703 	 * If reclaim is making forward progress but we're still over
2704 	 * memory.high, we want to encourage that rather than doing allocator
2705 	 * throttling.
2706 	 */
2707 	if (nr_reclaimed || nr_retries--) {
2708 		in_retry = true;
2709 		goto retry_reclaim;
2710 	}
2711 
2712 	/*
2713 	 * Reclaim didn't manage to push usage below the limit, slow
2714 	 * this allocating task down.
2715 	 *
2716 	 * If we exit early, we're guaranteed to die (since
2717 	 * schedule_timeout_killable sets TASK_KILLABLE). This means we don't
2718 	 * need to account for any ill-begotten jiffies to pay them off later.
2719 	 */
2720 	psi_memstall_enter(&pflags);
2721 	schedule_timeout_killable(penalty_jiffies);
2722 	psi_memstall_leave(&pflags);
2723 
2724 out:
2725 	css_put(&memcg->css);
2726 }
2727 
2728 static int try_charge_memcg(struct mem_cgroup *memcg, gfp_t gfp_mask,
2729 			unsigned int nr_pages)
2730 {
2731 	unsigned int batch = max(MEMCG_CHARGE_BATCH, nr_pages);
2732 	int nr_retries = MAX_RECLAIM_RETRIES;
2733 	struct mem_cgroup *mem_over_limit;
2734 	struct page_counter *counter;
2735 	unsigned long nr_reclaimed;
2736 	bool passed_oom = false;
2737 	unsigned int reclaim_options = MEMCG_RECLAIM_MAY_SWAP;
2738 	bool drained = false;
2739 	bool raised_max_event = false;
2740 	unsigned long pflags;
2741 
2742 retry:
2743 	if (consume_stock(memcg, nr_pages))
2744 		return 0;
2745 
2746 	if (!do_memsw_account() ||
2747 	    page_counter_try_charge(&memcg->memsw, batch, &counter)) {
2748 		if (page_counter_try_charge(&memcg->memory, batch, &counter))
2749 			goto done_restock;
2750 		if (do_memsw_account())
2751 			page_counter_uncharge(&memcg->memsw, batch);
2752 		mem_over_limit = mem_cgroup_from_counter(counter, memory);
2753 	} else {
2754 		mem_over_limit = mem_cgroup_from_counter(counter, memsw);
2755 		reclaim_options &= ~MEMCG_RECLAIM_MAY_SWAP;
2756 	}
2757 
2758 	if (batch > nr_pages) {
2759 		batch = nr_pages;
2760 		goto retry;
2761 	}
2762 
2763 	/*
2764 	 * Prevent unbounded recursion when reclaim operations need to
2765 	 * allocate memory. This might exceed the limits temporarily,
2766 	 * but we prefer facilitating memory reclaim and getting back
2767 	 * under the limit over triggering OOM kills in these cases.
2768 	 */
2769 	if (unlikely(current->flags & PF_MEMALLOC))
2770 		goto force;
2771 
2772 	if (unlikely(task_in_memcg_oom(current)))
2773 		goto nomem;
2774 
2775 	if (!gfpflags_allow_blocking(gfp_mask))
2776 		goto nomem;
2777 
2778 	memcg_memory_event(mem_over_limit, MEMCG_MAX);
2779 	raised_max_event = true;
2780 
2781 	psi_memstall_enter(&pflags);
2782 	nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
2783 						    gfp_mask, reclaim_options);
2784 	psi_memstall_leave(&pflags);
2785 
2786 	if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2787 		goto retry;
2788 
2789 	if (!drained) {
2790 		drain_all_stock(mem_over_limit);
2791 		drained = true;
2792 		goto retry;
2793 	}
2794 
2795 	if (gfp_mask & __GFP_NORETRY)
2796 		goto nomem;
2797 	/*
2798 	 * Even though the limit is exceeded at this point, reclaim
2799 	 * may have been able to free some pages.  Retry the charge
2800 	 * before killing the task.
2801 	 *
2802 	 * Only for regular pages, though: huge pages are rather
2803 	 * unlikely to succeed so close to the limit, and we fall back
2804 	 * to regular pages anyway in case of failure.
2805 	 */
2806 	if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
2807 		goto retry;
2808 	/*
2809 	 * At task move, charge accounts can be doubly counted. So, it's
2810 	 * better to wait until the end of task_move if something is going on.
2811 	 */
2812 	if (mem_cgroup_wait_acct_move(mem_over_limit))
2813 		goto retry;
2814 
2815 	if (nr_retries--)
2816 		goto retry;
2817 
2818 	if (gfp_mask & __GFP_RETRY_MAYFAIL)
2819 		goto nomem;
2820 
2821 	/* Avoid endless loop for tasks bypassed by the oom killer */
2822 	if (passed_oom && task_is_dying())
2823 		goto nomem;
2824 
2825 	/*
2826 	 * keep retrying as long as the memcg oom killer is able to make
2827 	 * a forward progress or bypass the charge if the oom killer
2828 	 * couldn't make any progress.
2829 	 */
2830 	if (mem_cgroup_oom(mem_over_limit, gfp_mask,
2831 			   get_order(nr_pages * PAGE_SIZE))) {
2832 		passed_oom = true;
2833 		nr_retries = MAX_RECLAIM_RETRIES;
2834 		goto retry;
2835 	}
2836 nomem:
2837 	/*
2838 	 * Memcg doesn't have a dedicated reserve for atomic
2839 	 * allocations. But like the global atomic pool, we need to
2840 	 * put the burden of reclaim on regular allocation requests
2841 	 * and let these go through as privileged allocations.
2842 	 */
2843 	if (!(gfp_mask & (__GFP_NOFAIL | __GFP_HIGH)))
2844 		return -ENOMEM;
2845 force:
2846 	/*
2847 	 * If the allocation has to be enforced, don't forget to raise
2848 	 * a MEMCG_MAX event.
2849 	 */
2850 	if (!raised_max_event)
2851 		memcg_memory_event(mem_over_limit, MEMCG_MAX);
2852 
2853 	/*
2854 	 * The allocation either can't fail or will lead to more memory
2855 	 * being freed very soon.  Allow memory usage go over the limit
2856 	 * temporarily by force charging it.
2857 	 */
2858 	page_counter_charge(&memcg->memory, nr_pages);
2859 	if (do_memsw_account())
2860 		page_counter_charge(&memcg->memsw, nr_pages);
2861 
2862 	return 0;
2863 
2864 done_restock:
2865 	if (batch > nr_pages)
2866 		refill_stock(memcg, batch - nr_pages);
2867 
2868 	/*
2869 	 * If the hierarchy is above the normal consumption range, schedule
2870 	 * reclaim on returning to userland.  We can perform reclaim here
2871 	 * if __GFP_RECLAIM but let's always punt for simplicity and so that
2872 	 * GFP_KERNEL can consistently be used during reclaim.  @memcg is
2873 	 * not recorded as it most likely matches current's and won't
2874 	 * change in the meantime.  As high limit is checked again before
2875 	 * reclaim, the cost of mismatch is negligible.
2876 	 */
2877 	do {
2878 		bool mem_high, swap_high;
2879 
2880 		mem_high = page_counter_read(&memcg->memory) >
2881 			READ_ONCE(memcg->memory.high);
2882 		swap_high = page_counter_read(&memcg->swap) >
2883 			READ_ONCE(memcg->swap.high);
2884 
2885 		/* Don't bother a random interrupted task */
2886 		if (!in_task()) {
2887 			if (mem_high) {
2888 				schedule_work(&memcg->high_work);
2889 				break;
2890 			}
2891 			continue;
2892 		}
2893 
2894 		if (mem_high || swap_high) {
2895 			/*
2896 			 * The allocating tasks in this cgroup will need to do
2897 			 * reclaim or be throttled to prevent further growth
2898 			 * of the memory or swap footprints.
2899 			 *
2900 			 * Target some best-effort fairness between the tasks,
2901 			 * and distribute reclaim work and delay penalties
2902 			 * based on how much each task is actually allocating.
2903 			 */
2904 			current->memcg_nr_pages_over_high += batch;
2905 			set_notify_resume(current);
2906 			break;
2907 		}
2908 	} while ((memcg = parent_mem_cgroup(memcg)));
2909 
2910 	/*
2911 	 * Reclaim is set up above to be called from the userland
2912 	 * return path. But also attempt synchronous reclaim to avoid
2913 	 * excessive overrun while the task is still inside the
2914 	 * kernel. If this is successful, the return path will see it
2915 	 * when it rechecks the overage and simply bail out.
2916 	 */
2917 	if (current->memcg_nr_pages_over_high > MEMCG_CHARGE_BATCH &&
2918 	    !(current->flags & PF_MEMALLOC) &&
2919 	    gfpflags_allow_blocking(gfp_mask))
2920 		mem_cgroup_handle_over_high(gfp_mask);
2921 	return 0;
2922 }
2923 
2924 static inline int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2925 			     unsigned int nr_pages)
2926 {
2927 	if (mem_cgroup_is_root(memcg))
2928 		return 0;
2929 
2930 	return try_charge_memcg(memcg, gfp_mask, nr_pages);
2931 }
2932 
2933 /**
2934  * mem_cgroup_cancel_charge() - cancel an uncommitted try_charge() call.
2935  * @memcg: memcg previously charged.
2936  * @nr_pages: number of pages previously charged.
2937  */
2938 void mem_cgroup_cancel_charge(struct mem_cgroup *memcg, unsigned int nr_pages)
2939 {
2940 	if (mem_cgroup_is_root(memcg))
2941 		return;
2942 
2943 	page_counter_uncharge(&memcg->memory, nr_pages);
2944 	if (do_memsw_account())
2945 		page_counter_uncharge(&memcg->memsw, nr_pages);
2946 }
2947 
2948 static void commit_charge(struct folio *folio, struct mem_cgroup *memcg)
2949 {
2950 	VM_BUG_ON_FOLIO(folio_memcg(folio), folio);
2951 	/*
2952 	 * Any of the following ensures page's memcg stability:
2953 	 *
2954 	 * - the page lock
2955 	 * - LRU isolation
2956 	 * - folio_memcg_lock()
2957 	 * - exclusive reference
2958 	 * - mem_cgroup_trylock_pages()
2959 	 */
2960 	folio->memcg_data = (unsigned long)memcg;
2961 }
2962 
2963 /**
2964  * mem_cgroup_commit_charge - commit a previously successful try_charge().
2965  * @folio: folio to commit the charge to.
2966  * @memcg: memcg previously charged.
2967  */
2968 void mem_cgroup_commit_charge(struct folio *folio, struct mem_cgroup *memcg)
2969 {
2970 	css_get(&memcg->css);
2971 	commit_charge(folio, memcg);
2972 
2973 	local_irq_disable();
2974 	mem_cgroup_charge_statistics(memcg, folio_nr_pages(folio));
2975 	memcg_check_events(memcg, folio_nid(folio));
2976 	local_irq_enable();
2977 }
2978 
2979 #ifdef CONFIG_MEMCG_KMEM
2980 
2981 /*
2982  * mod_objcg_mlstate() may be called with irq enabled, so
2983  * mod_memcg_lruvec_state() should be used.
2984  */
2985 static inline void mod_objcg_mlstate(struct obj_cgroup *objcg,
2986 				     struct pglist_data *pgdat,
2987 				     enum node_stat_item idx, int nr)
2988 {
2989 	struct mem_cgroup *memcg;
2990 	struct lruvec *lruvec;
2991 
2992 	rcu_read_lock();
2993 	memcg = obj_cgroup_memcg(objcg);
2994 	lruvec = mem_cgroup_lruvec(memcg, pgdat);
2995 	mod_memcg_lruvec_state(lruvec, idx, nr);
2996 	rcu_read_unlock();
2997 }
2998 
2999 static __always_inline
3000 struct mem_cgroup *mem_cgroup_from_obj_folio(struct folio *folio, void *p)
3001 {
3002 	/*
3003 	 * Slab objects are accounted individually, not per-page.
3004 	 * Memcg membership data for each individual object is saved in
3005 	 * slab->obj_exts.
3006 	 */
3007 	if (folio_test_slab(folio)) {
3008 		struct slabobj_ext *obj_exts;
3009 		struct slab *slab;
3010 		unsigned int off;
3011 
3012 		slab = folio_slab(folio);
3013 		obj_exts = slab_obj_exts(slab);
3014 		if (!obj_exts)
3015 			return NULL;
3016 
3017 		off = obj_to_index(slab->slab_cache, slab, p);
3018 		if (obj_exts[off].objcg)
3019 			return obj_cgroup_memcg(obj_exts[off].objcg);
3020 
3021 		return NULL;
3022 	}
3023 
3024 	/*
3025 	 * folio_memcg_check() is used here, because in theory we can encounter
3026 	 * a folio where the slab flag has been cleared already, but
3027 	 * slab->obj_exts has not been freed yet
3028 	 * folio_memcg_check() will guarantee that a proper memory
3029 	 * cgroup pointer or NULL will be returned.
3030 	 */
3031 	return folio_memcg_check(folio);
3032 }
3033 
3034 /*
3035  * Returns a pointer to the memory cgroup to which the kernel object is charged.
3036  *
3037  * A passed kernel object can be a slab object, vmalloc object or a generic
3038  * kernel page, so different mechanisms for getting the memory cgroup pointer
3039  * should be used.
3040  *
3041  * In certain cases (e.g. kernel stacks or large kmallocs with SLUB) the caller
3042  * can not know for sure how the kernel object is implemented.
3043  * mem_cgroup_from_obj() can be safely used in such cases.
3044  *
3045  * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
3046  * cgroup_mutex, etc.
3047  */
3048 struct mem_cgroup *mem_cgroup_from_obj(void *p)
3049 {
3050 	struct folio *folio;
3051 
3052 	if (mem_cgroup_disabled())
3053 		return NULL;
3054 
3055 	if (unlikely(is_vmalloc_addr(p)))
3056 		folio = page_folio(vmalloc_to_page(p));
3057 	else
3058 		folio = virt_to_folio(p);
3059 
3060 	return mem_cgroup_from_obj_folio(folio, p);
3061 }
3062 
3063 /*
3064  * Returns a pointer to the memory cgroup to which the kernel object is charged.
3065  * Similar to mem_cgroup_from_obj(), but faster and not suitable for objects,
3066  * allocated using vmalloc().
3067  *
3068  * A passed kernel object must be a slab object or a generic kernel page.
3069  *
3070  * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
3071  * cgroup_mutex, etc.
3072  */
3073 struct mem_cgroup *mem_cgroup_from_slab_obj(void *p)
3074 {
3075 	if (mem_cgroup_disabled())
3076 		return NULL;
3077 
3078 	return mem_cgroup_from_obj_folio(virt_to_folio(p), p);
3079 }
3080 
3081 static struct obj_cgroup *__get_obj_cgroup_from_memcg(struct mem_cgroup *memcg)
3082 {
3083 	struct obj_cgroup *objcg = NULL;
3084 
3085 	for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
3086 		objcg = rcu_dereference(memcg->objcg);
3087 		if (likely(objcg && obj_cgroup_tryget(objcg)))
3088 			break;
3089 		objcg = NULL;
3090 	}
3091 	return objcg;
3092 }
3093 
3094 static struct obj_cgroup *current_objcg_update(void)
3095 {
3096 	struct mem_cgroup *memcg;
3097 	struct obj_cgroup *old, *objcg = NULL;
3098 
3099 	do {
3100 		/* Atomically drop the update bit. */
3101 		old = xchg(&current->objcg, NULL);
3102 		if (old) {
3103 			old = (struct obj_cgroup *)
3104 				((unsigned long)old & ~CURRENT_OBJCG_UPDATE_FLAG);
3105 			obj_cgroup_put(old);
3106 
3107 			old = NULL;
3108 		}
3109 
3110 		/* If new objcg is NULL, no reason for the second atomic update. */
3111 		if (!current->mm || (current->flags & PF_KTHREAD))
3112 			return NULL;
3113 
3114 		/*
3115 		 * Release the objcg pointer from the previous iteration,
3116 		 * if try_cmpxcg() below fails.
3117 		 */
3118 		if (unlikely(objcg)) {
3119 			obj_cgroup_put(objcg);
3120 			objcg = NULL;
3121 		}
3122 
3123 		/*
3124 		 * Obtain the new objcg pointer. The current task can be
3125 		 * asynchronously moved to another memcg and the previous
3126 		 * memcg can be offlined. So let's get the memcg pointer
3127 		 * and try get a reference to objcg under a rcu read lock.
3128 		 */
3129 
3130 		rcu_read_lock();
3131 		memcg = mem_cgroup_from_task(current);
3132 		objcg = __get_obj_cgroup_from_memcg(memcg);
3133 		rcu_read_unlock();
3134 
3135 		/*
3136 		 * Try set up a new objcg pointer atomically. If it
3137 		 * fails, it means the update flag was set concurrently, so
3138 		 * the whole procedure should be repeated.
3139 		 */
3140 	} while (!try_cmpxchg(&current->objcg, &old, objcg));
3141 
3142 	return objcg;
3143 }
3144 
3145 __always_inline struct obj_cgroup *current_obj_cgroup(void)
3146 {
3147 	struct mem_cgroup *memcg;
3148 	struct obj_cgroup *objcg;
3149 
3150 	if (in_task()) {
3151 		memcg = current->active_memcg;
3152 		if (unlikely(memcg))
3153 			goto from_memcg;
3154 
3155 		objcg = READ_ONCE(current->objcg);
3156 		if (unlikely((unsigned long)objcg & CURRENT_OBJCG_UPDATE_FLAG))
3157 			objcg = current_objcg_update();
3158 		/*
3159 		 * Objcg reference is kept by the task, so it's safe
3160 		 * to use the objcg by the current task.
3161 		 */
3162 		return objcg;
3163 	}
3164 
3165 	memcg = this_cpu_read(int_active_memcg);
3166 	if (unlikely(memcg))
3167 		goto from_memcg;
3168 
3169 	return NULL;
3170 
3171 from_memcg:
3172 	objcg = NULL;
3173 	for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
3174 		/*
3175 		 * Memcg pointer is protected by scope (see set_active_memcg())
3176 		 * and is pinning the corresponding objcg, so objcg can't go
3177 		 * away and can be used within the scope without any additional
3178 		 * protection.
3179 		 */
3180 		objcg = rcu_dereference_check(memcg->objcg, 1);
3181 		if (likely(objcg))
3182 			break;
3183 	}
3184 
3185 	return objcg;
3186 }
3187 
3188 struct obj_cgroup *get_obj_cgroup_from_folio(struct folio *folio)
3189 {
3190 	struct obj_cgroup *objcg;
3191 
3192 	if (!memcg_kmem_online())
3193 		return NULL;
3194 
3195 	if (folio_memcg_kmem(folio)) {
3196 		objcg = __folio_objcg(folio);
3197 		obj_cgroup_get(objcg);
3198 	} else {
3199 		struct mem_cgroup *memcg;
3200 
3201 		rcu_read_lock();
3202 		memcg = __folio_memcg(folio);
3203 		if (memcg)
3204 			objcg = __get_obj_cgroup_from_memcg(memcg);
3205 		else
3206 			objcg = NULL;
3207 		rcu_read_unlock();
3208 	}
3209 	return objcg;
3210 }
3211 
3212 static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages)
3213 {
3214 	mod_memcg_state(memcg, MEMCG_KMEM, nr_pages);
3215 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
3216 		if (nr_pages > 0)
3217 			page_counter_charge(&memcg->kmem, nr_pages);
3218 		else
3219 			page_counter_uncharge(&memcg->kmem, -nr_pages);
3220 	}
3221 }
3222 
3223 
3224 /*
3225  * obj_cgroup_uncharge_pages: uncharge a number of kernel pages from a objcg
3226  * @objcg: object cgroup to uncharge
3227  * @nr_pages: number of pages to uncharge
3228  */
3229 static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
3230 				      unsigned int nr_pages)
3231 {
3232 	struct mem_cgroup *memcg;
3233 
3234 	memcg = get_mem_cgroup_from_objcg(objcg);
3235 
3236 	memcg_account_kmem(memcg, -nr_pages);
3237 	refill_stock(memcg, nr_pages);
3238 
3239 	css_put(&memcg->css);
3240 }
3241 
3242 /*
3243  * obj_cgroup_charge_pages: charge a number of kernel pages to a objcg
3244  * @objcg: object cgroup to charge
3245  * @gfp: reclaim mode
3246  * @nr_pages: number of pages to charge
3247  *
3248  * Returns 0 on success, an error code on failure.
3249  */
3250 static int obj_cgroup_charge_pages(struct obj_cgroup *objcg, gfp_t gfp,
3251 				   unsigned int nr_pages)
3252 {
3253 	struct mem_cgroup *memcg;
3254 	int ret;
3255 
3256 	memcg = get_mem_cgroup_from_objcg(objcg);
3257 
3258 	ret = try_charge_memcg(memcg, gfp, nr_pages);
3259 	if (ret)
3260 		goto out;
3261 
3262 	memcg_account_kmem(memcg, nr_pages);
3263 out:
3264 	css_put(&memcg->css);
3265 
3266 	return ret;
3267 }
3268 
3269 /**
3270  * __memcg_kmem_charge_page: charge a kmem page to the current memory cgroup
3271  * @page: page to charge
3272  * @gfp: reclaim mode
3273  * @order: allocation order
3274  *
3275  * Returns 0 on success, an error code on failure.
3276  */
3277 int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order)
3278 {
3279 	struct obj_cgroup *objcg;
3280 	int ret = 0;
3281 
3282 	objcg = current_obj_cgroup();
3283 	if (objcg) {
3284 		ret = obj_cgroup_charge_pages(objcg, gfp, 1 << order);
3285 		if (!ret) {
3286 			obj_cgroup_get(objcg);
3287 			page->memcg_data = (unsigned long)objcg |
3288 				MEMCG_DATA_KMEM;
3289 			return 0;
3290 		}
3291 	}
3292 	return ret;
3293 }
3294 
3295 /**
3296  * __memcg_kmem_uncharge_page: uncharge a kmem page
3297  * @page: page to uncharge
3298  * @order: allocation order
3299  */
3300 void __memcg_kmem_uncharge_page(struct page *page, int order)
3301 {
3302 	struct folio *folio = page_folio(page);
3303 	struct obj_cgroup *objcg;
3304 	unsigned int nr_pages = 1 << order;
3305 
3306 	if (!folio_memcg_kmem(folio))
3307 		return;
3308 
3309 	objcg = __folio_objcg(folio);
3310 	obj_cgroup_uncharge_pages(objcg, nr_pages);
3311 	folio->memcg_data = 0;
3312 	obj_cgroup_put(objcg);
3313 }
3314 
3315 void mod_objcg_state(struct obj_cgroup *objcg, struct pglist_data *pgdat,
3316 		     enum node_stat_item idx, int nr)
3317 {
3318 	struct memcg_stock_pcp *stock;
3319 	struct obj_cgroup *old = NULL;
3320 	unsigned long flags;
3321 	int *bytes;
3322 
3323 	local_lock_irqsave(&memcg_stock.stock_lock, flags);
3324 	stock = this_cpu_ptr(&memcg_stock);
3325 
3326 	/*
3327 	 * Save vmstat data in stock and skip vmstat array update unless
3328 	 * accumulating over a page of vmstat data or when pgdat or idx
3329 	 * changes.
3330 	 */
3331 	if (READ_ONCE(stock->cached_objcg) != objcg) {
3332 		old = drain_obj_stock(stock);
3333 		obj_cgroup_get(objcg);
3334 		stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
3335 				? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
3336 		WRITE_ONCE(stock->cached_objcg, objcg);
3337 		stock->cached_pgdat = pgdat;
3338 	} else if (stock->cached_pgdat != pgdat) {
3339 		/* Flush the existing cached vmstat data */
3340 		struct pglist_data *oldpg = stock->cached_pgdat;
3341 
3342 		if (stock->nr_slab_reclaimable_b) {
3343 			mod_objcg_mlstate(objcg, oldpg, NR_SLAB_RECLAIMABLE_B,
3344 					  stock->nr_slab_reclaimable_b);
3345 			stock->nr_slab_reclaimable_b = 0;
3346 		}
3347 		if (stock->nr_slab_unreclaimable_b) {
3348 			mod_objcg_mlstate(objcg, oldpg, NR_SLAB_UNRECLAIMABLE_B,
3349 					  stock->nr_slab_unreclaimable_b);
3350 			stock->nr_slab_unreclaimable_b = 0;
3351 		}
3352 		stock->cached_pgdat = pgdat;
3353 	}
3354 
3355 	bytes = (idx == NR_SLAB_RECLAIMABLE_B) ? &stock->nr_slab_reclaimable_b
3356 					       : &stock->nr_slab_unreclaimable_b;
3357 	/*
3358 	 * Even for large object >= PAGE_SIZE, the vmstat data will still be
3359 	 * cached locally at least once before pushing it out.
3360 	 */
3361 	if (!*bytes) {
3362 		*bytes = nr;
3363 		nr = 0;
3364 	} else {
3365 		*bytes += nr;
3366 		if (abs(*bytes) > PAGE_SIZE) {
3367 			nr = *bytes;
3368 			*bytes = 0;
3369 		} else {
3370 			nr = 0;
3371 		}
3372 	}
3373 	if (nr)
3374 		mod_objcg_mlstate(objcg, pgdat, idx, nr);
3375 
3376 	local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
3377 	obj_cgroup_put(old);
3378 }
3379 
3380 static bool consume_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes)
3381 {
3382 	struct memcg_stock_pcp *stock;
3383 	unsigned long flags;
3384 	bool ret = false;
3385 
3386 	local_lock_irqsave(&memcg_stock.stock_lock, flags);
3387 
3388 	stock = this_cpu_ptr(&memcg_stock);
3389 	if (objcg == READ_ONCE(stock->cached_objcg) && stock->nr_bytes >= nr_bytes) {
3390 		stock->nr_bytes -= nr_bytes;
3391 		ret = true;
3392 	}
3393 
3394 	local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
3395 
3396 	return ret;
3397 }
3398 
3399 static struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock)
3400 {
3401 	struct obj_cgroup *old = READ_ONCE(stock->cached_objcg);
3402 
3403 	if (!old)
3404 		return NULL;
3405 
3406 	if (stock->nr_bytes) {
3407 		unsigned int nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3408 		unsigned int nr_bytes = stock->nr_bytes & (PAGE_SIZE - 1);
3409 
3410 		if (nr_pages) {
3411 			struct mem_cgroup *memcg;
3412 
3413 			memcg = get_mem_cgroup_from_objcg(old);
3414 
3415 			memcg_account_kmem(memcg, -nr_pages);
3416 			__refill_stock(memcg, nr_pages);
3417 
3418 			css_put(&memcg->css);
3419 		}
3420 
3421 		/*
3422 		 * The leftover is flushed to the centralized per-memcg value.
3423 		 * On the next attempt to refill obj stock it will be moved
3424 		 * to a per-cpu stock (probably, on an other CPU), see
3425 		 * refill_obj_stock().
3426 		 *
3427 		 * How often it's flushed is a trade-off between the memory
3428 		 * limit enforcement accuracy and potential CPU contention,
3429 		 * so it might be changed in the future.
3430 		 */
3431 		atomic_add(nr_bytes, &old->nr_charged_bytes);
3432 		stock->nr_bytes = 0;
3433 	}
3434 
3435 	/*
3436 	 * Flush the vmstat data in current stock
3437 	 */
3438 	if (stock->nr_slab_reclaimable_b || stock->nr_slab_unreclaimable_b) {
3439 		if (stock->nr_slab_reclaimable_b) {
3440 			mod_objcg_mlstate(old, stock->cached_pgdat,
3441 					  NR_SLAB_RECLAIMABLE_B,
3442 					  stock->nr_slab_reclaimable_b);
3443 			stock->nr_slab_reclaimable_b = 0;
3444 		}
3445 		if (stock->nr_slab_unreclaimable_b) {
3446 			mod_objcg_mlstate(old, stock->cached_pgdat,
3447 					  NR_SLAB_UNRECLAIMABLE_B,
3448 					  stock->nr_slab_unreclaimable_b);
3449 			stock->nr_slab_unreclaimable_b = 0;
3450 		}
3451 		stock->cached_pgdat = NULL;
3452 	}
3453 
3454 	WRITE_ONCE(stock->cached_objcg, NULL);
3455 	/*
3456 	 * The `old' objects needs to be released by the caller via
3457 	 * obj_cgroup_put() outside of memcg_stock_pcp::stock_lock.
3458 	 */
3459 	return old;
3460 }
3461 
3462 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
3463 				     struct mem_cgroup *root_memcg)
3464 {
3465 	struct obj_cgroup *objcg = READ_ONCE(stock->cached_objcg);
3466 	struct mem_cgroup *memcg;
3467 
3468 	if (objcg) {
3469 		memcg = obj_cgroup_memcg(objcg);
3470 		if (memcg && mem_cgroup_is_descendant(memcg, root_memcg))
3471 			return true;
3472 	}
3473 
3474 	return false;
3475 }
3476 
3477 static void refill_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes,
3478 			     bool allow_uncharge)
3479 {
3480 	struct memcg_stock_pcp *stock;
3481 	struct obj_cgroup *old = NULL;
3482 	unsigned long flags;
3483 	unsigned int nr_pages = 0;
3484 
3485 	local_lock_irqsave(&memcg_stock.stock_lock, flags);
3486 
3487 	stock = this_cpu_ptr(&memcg_stock);
3488 	if (READ_ONCE(stock->cached_objcg) != objcg) { /* reset if necessary */
3489 		old = drain_obj_stock(stock);
3490 		obj_cgroup_get(objcg);
3491 		WRITE_ONCE(stock->cached_objcg, objcg);
3492 		stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
3493 				? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
3494 		allow_uncharge = true;	/* Allow uncharge when objcg changes */
3495 	}
3496 	stock->nr_bytes += nr_bytes;
3497 
3498 	if (allow_uncharge && (stock->nr_bytes > PAGE_SIZE)) {
3499 		nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3500 		stock->nr_bytes &= (PAGE_SIZE - 1);
3501 	}
3502 
3503 	local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
3504 	obj_cgroup_put(old);
3505 
3506 	if (nr_pages)
3507 		obj_cgroup_uncharge_pages(objcg, nr_pages);
3508 }
3509 
3510 int obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp, size_t size)
3511 {
3512 	unsigned int nr_pages, nr_bytes;
3513 	int ret;
3514 
3515 	if (consume_obj_stock(objcg, size))
3516 		return 0;
3517 
3518 	/*
3519 	 * In theory, objcg->nr_charged_bytes can have enough
3520 	 * pre-charged bytes to satisfy the allocation. However,
3521 	 * flushing objcg->nr_charged_bytes requires two atomic
3522 	 * operations, and objcg->nr_charged_bytes can't be big.
3523 	 * The shared objcg->nr_charged_bytes can also become a
3524 	 * performance bottleneck if all tasks of the same memcg are
3525 	 * trying to update it. So it's better to ignore it and try
3526 	 * grab some new pages. The stock's nr_bytes will be flushed to
3527 	 * objcg->nr_charged_bytes later on when objcg changes.
3528 	 *
3529 	 * The stock's nr_bytes may contain enough pre-charged bytes
3530 	 * to allow one less page from being charged, but we can't rely
3531 	 * on the pre-charged bytes not being changed outside of
3532 	 * consume_obj_stock() or refill_obj_stock(). So ignore those
3533 	 * pre-charged bytes as well when charging pages. To avoid a
3534 	 * page uncharge right after a page charge, we set the
3535 	 * allow_uncharge flag to false when calling refill_obj_stock()
3536 	 * to temporarily allow the pre-charged bytes to exceed the page
3537 	 * size limit. The maximum reachable value of the pre-charged
3538 	 * bytes is (sizeof(object) + PAGE_SIZE - 2) if there is no data
3539 	 * race.
3540 	 */
3541 	nr_pages = size >> PAGE_SHIFT;
3542 	nr_bytes = size & (PAGE_SIZE - 1);
3543 
3544 	if (nr_bytes)
3545 		nr_pages += 1;
3546 
3547 	ret = obj_cgroup_charge_pages(objcg, gfp, nr_pages);
3548 	if (!ret && nr_bytes)
3549 		refill_obj_stock(objcg, PAGE_SIZE - nr_bytes, false);
3550 
3551 	return ret;
3552 }
3553 
3554 void obj_cgroup_uncharge(struct obj_cgroup *objcg, size_t size)
3555 {
3556 	refill_obj_stock(objcg, size, true);
3557 }
3558 
3559 static inline size_t obj_full_size(struct kmem_cache *s)
3560 {
3561 	/*
3562 	 * For each accounted object there is an extra space which is used
3563 	 * to store obj_cgroup membership. Charge it too.
3564 	 */
3565 	return s->size + sizeof(struct obj_cgroup *);
3566 }
3567 
3568 bool __memcg_slab_post_alloc_hook(struct kmem_cache *s, struct list_lru *lru,
3569 				  gfp_t flags, size_t size, void **p)
3570 {
3571 	struct obj_cgroup *objcg;
3572 	struct slab *slab;
3573 	unsigned long off;
3574 	size_t i;
3575 
3576 	/*
3577 	 * The obtained objcg pointer is safe to use within the current scope,
3578 	 * defined by current task or set_active_memcg() pair.
3579 	 * obj_cgroup_get() is used to get a permanent reference.
3580 	 */
3581 	objcg = current_obj_cgroup();
3582 	if (!objcg)
3583 		return true;
3584 
3585 	/*
3586 	 * slab_alloc_node() avoids the NULL check, so we might be called with a
3587 	 * single NULL object. kmem_cache_alloc_bulk() aborts if it can't fill
3588 	 * the whole requested size.
3589 	 * return success as there's nothing to free back
3590 	 */
3591 	if (unlikely(*p == NULL))
3592 		return true;
3593 
3594 	flags &= gfp_allowed_mask;
3595 
3596 	if (lru) {
3597 		int ret;
3598 		struct mem_cgroup *memcg;
3599 
3600 		memcg = get_mem_cgroup_from_objcg(objcg);
3601 		ret = memcg_list_lru_alloc(memcg, lru, flags);
3602 		css_put(&memcg->css);
3603 
3604 		if (ret)
3605 			return false;
3606 	}
3607 
3608 	if (obj_cgroup_charge(objcg, flags, size * obj_full_size(s)))
3609 		return false;
3610 
3611 	for (i = 0; i < size; i++) {
3612 		slab = virt_to_slab(p[i]);
3613 
3614 		if (!slab_obj_exts(slab) &&
3615 		    alloc_slab_obj_exts(slab, s, flags, false)) {
3616 			obj_cgroup_uncharge(objcg, obj_full_size(s));
3617 			continue;
3618 		}
3619 
3620 		off = obj_to_index(s, slab, p[i]);
3621 		obj_cgroup_get(objcg);
3622 		slab_obj_exts(slab)[off].objcg = objcg;
3623 		mod_objcg_state(objcg, slab_pgdat(slab),
3624 				cache_vmstat_idx(s), obj_full_size(s));
3625 	}
3626 
3627 	return true;
3628 }
3629 
3630 void __memcg_slab_free_hook(struct kmem_cache *s, struct slab *slab,
3631 			    void **p, int objects, struct slabobj_ext *obj_exts)
3632 {
3633 	for (int i = 0; i < objects; i++) {
3634 		struct obj_cgroup *objcg;
3635 		unsigned int off;
3636 
3637 		off = obj_to_index(s, slab, p[i]);
3638 		objcg = obj_exts[off].objcg;
3639 		if (!objcg)
3640 			continue;
3641 
3642 		obj_exts[off].objcg = NULL;
3643 		obj_cgroup_uncharge(objcg, obj_full_size(s));
3644 		mod_objcg_state(objcg, slab_pgdat(slab), cache_vmstat_idx(s),
3645 				-obj_full_size(s));
3646 		obj_cgroup_put(objcg);
3647 	}
3648 }
3649 #endif /* CONFIG_MEMCG_KMEM */
3650 
3651 /*
3652  * Because page_memcg(head) is not set on tails, set it now.
3653  */
3654 void split_page_memcg(struct page *head, int old_order, int new_order)
3655 {
3656 	struct folio *folio = page_folio(head);
3657 	struct mem_cgroup *memcg = folio_memcg(folio);
3658 	int i;
3659 	unsigned int old_nr = 1 << old_order;
3660 	unsigned int new_nr = 1 << new_order;
3661 
3662 	if (mem_cgroup_disabled() || !memcg)
3663 		return;
3664 
3665 	for (i = new_nr; i < old_nr; i += new_nr)
3666 		folio_page(folio, i)->memcg_data = folio->memcg_data;
3667 
3668 	if (folio_memcg_kmem(folio))
3669 		obj_cgroup_get_many(__folio_objcg(folio), old_nr / new_nr - 1);
3670 	else
3671 		css_get_many(&memcg->css, old_nr / new_nr - 1);
3672 }
3673 
3674 #ifdef CONFIG_SWAP
3675 /**
3676  * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3677  * @entry: swap entry to be moved
3678  * @from:  mem_cgroup which the entry is moved from
3679  * @to:  mem_cgroup which the entry is moved to
3680  *
3681  * It succeeds only when the swap_cgroup's record for this entry is the same
3682  * as the mem_cgroup's id of @from.
3683  *
3684  * Returns 0 on success, -EINVAL on failure.
3685  *
3686  * The caller must have charged to @to, IOW, called page_counter_charge() about
3687  * both res and memsw, and called css_get().
3688  */
3689 static int mem_cgroup_move_swap_account(swp_entry_t entry,
3690 				struct mem_cgroup *from, struct mem_cgroup *to)
3691 {
3692 	unsigned short old_id, new_id;
3693 
3694 	old_id = mem_cgroup_id(from);
3695 	new_id = mem_cgroup_id(to);
3696 
3697 	if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
3698 		mod_memcg_state(from, MEMCG_SWAP, -1);
3699 		mod_memcg_state(to, MEMCG_SWAP, 1);
3700 		return 0;
3701 	}
3702 	return -EINVAL;
3703 }
3704 #else
3705 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
3706 				struct mem_cgroup *from, struct mem_cgroup *to)
3707 {
3708 	return -EINVAL;
3709 }
3710 #endif
3711 
3712 static DEFINE_MUTEX(memcg_max_mutex);
3713 
3714 static int mem_cgroup_resize_max(struct mem_cgroup *memcg,
3715 				 unsigned long max, bool memsw)
3716 {
3717 	bool enlarge = false;
3718 	bool drained = false;
3719 	int ret;
3720 	bool limits_invariant;
3721 	struct page_counter *counter = memsw ? &memcg->memsw : &memcg->memory;
3722 
3723 	do {
3724 		if (signal_pending(current)) {
3725 			ret = -EINTR;
3726 			break;
3727 		}
3728 
3729 		mutex_lock(&memcg_max_mutex);
3730 		/*
3731 		 * Make sure that the new limit (memsw or memory limit) doesn't
3732 		 * break our basic invariant rule memory.max <= memsw.max.
3733 		 */
3734 		limits_invariant = memsw ? max >= READ_ONCE(memcg->memory.max) :
3735 					   max <= memcg->memsw.max;
3736 		if (!limits_invariant) {
3737 			mutex_unlock(&memcg_max_mutex);
3738 			ret = -EINVAL;
3739 			break;
3740 		}
3741 		if (max > counter->max)
3742 			enlarge = true;
3743 		ret = page_counter_set_max(counter, max);
3744 		mutex_unlock(&memcg_max_mutex);
3745 
3746 		if (!ret)
3747 			break;
3748 
3749 		if (!drained) {
3750 			drain_all_stock(memcg);
3751 			drained = true;
3752 			continue;
3753 		}
3754 
3755 		if (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL,
3756 					memsw ? 0 : MEMCG_RECLAIM_MAY_SWAP)) {
3757 			ret = -EBUSY;
3758 			break;
3759 		}
3760 	} while (true);
3761 
3762 	if (!ret && enlarge)
3763 		memcg_oom_recover(memcg);
3764 
3765 	return ret;
3766 }
3767 
3768 unsigned long mem_cgroup_soft_limit_reclaim(pg_data_t *pgdat, int order,
3769 					    gfp_t gfp_mask,
3770 					    unsigned long *total_scanned)
3771 {
3772 	unsigned long nr_reclaimed = 0;
3773 	struct mem_cgroup_per_node *mz, *next_mz = NULL;
3774 	unsigned long reclaimed;
3775 	int loop = 0;
3776 	struct mem_cgroup_tree_per_node *mctz;
3777 	unsigned long excess;
3778 
3779 	if (lru_gen_enabled())
3780 		return 0;
3781 
3782 	if (order > 0)
3783 		return 0;
3784 
3785 	mctz = soft_limit_tree.rb_tree_per_node[pgdat->node_id];
3786 
3787 	/*
3788 	 * Do not even bother to check the largest node if the root
3789 	 * is empty. Do it lockless to prevent lock bouncing. Races
3790 	 * are acceptable as soft limit is best effort anyway.
3791 	 */
3792 	if (!mctz || RB_EMPTY_ROOT(&mctz->rb_root))
3793 		return 0;
3794 
3795 	/*
3796 	 * This loop can run a while, specially if mem_cgroup's continuously
3797 	 * keep exceeding their soft limit and putting the system under
3798 	 * pressure
3799 	 */
3800 	do {
3801 		if (next_mz)
3802 			mz = next_mz;
3803 		else
3804 			mz = mem_cgroup_largest_soft_limit_node(mctz);
3805 		if (!mz)
3806 			break;
3807 
3808 		reclaimed = mem_cgroup_soft_reclaim(mz->memcg, pgdat,
3809 						    gfp_mask, total_scanned);
3810 		nr_reclaimed += reclaimed;
3811 		spin_lock_irq(&mctz->lock);
3812 
3813 		/*
3814 		 * If we failed to reclaim anything from this memory cgroup
3815 		 * it is time to move on to the next cgroup
3816 		 */
3817 		next_mz = NULL;
3818 		if (!reclaimed)
3819 			next_mz = __mem_cgroup_largest_soft_limit_node(mctz);
3820 
3821 		excess = soft_limit_excess(mz->memcg);
3822 		/*
3823 		 * One school of thought says that we should not add
3824 		 * back the node to the tree if reclaim returns 0.
3825 		 * But our reclaim could return 0, simply because due
3826 		 * to priority we are exposing a smaller subset of
3827 		 * memory to reclaim from. Consider this as a longer
3828 		 * term TODO.
3829 		 */
3830 		/* If excess == 0, no tree ops */
3831 		__mem_cgroup_insert_exceeded(mz, mctz, excess);
3832 		spin_unlock_irq(&mctz->lock);
3833 		css_put(&mz->memcg->css);
3834 		loop++;
3835 		/*
3836 		 * Could not reclaim anything and there are no more
3837 		 * mem cgroups to try or we seem to be looping without
3838 		 * reclaiming anything.
3839 		 */
3840 		if (!nr_reclaimed &&
3841 			(next_mz == NULL ||
3842 			loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3843 			break;
3844 	} while (!nr_reclaimed);
3845 	if (next_mz)
3846 		css_put(&next_mz->memcg->css);
3847 	return nr_reclaimed;
3848 }
3849 
3850 /*
3851  * Reclaims as many pages from the given memcg as possible.
3852  *
3853  * Caller is responsible for holding css reference for memcg.
3854  */
3855 static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
3856 {
3857 	int nr_retries = MAX_RECLAIM_RETRIES;
3858 
3859 	/* we call try-to-free pages for make this cgroup empty */
3860 	lru_add_drain_all();
3861 
3862 	drain_all_stock(memcg);
3863 
3864 	/* try to free all pages in this cgroup */
3865 	while (nr_retries && page_counter_read(&memcg->memory)) {
3866 		if (signal_pending(current))
3867 			return -EINTR;
3868 
3869 		if (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL,
3870 						  MEMCG_RECLAIM_MAY_SWAP))
3871 			nr_retries--;
3872 	}
3873 
3874 	return 0;
3875 }
3876 
3877 static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
3878 					    char *buf, size_t nbytes,
3879 					    loff_t off)
3880 {
3881 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3882 
3883 	if (mem_cgroup_is_root(memcg))
3884 		return -EINVAL;
3885 	return mem_cgroup_force_empty(memcg) ?: nbytes;
3886 }
3887 
3888 static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
3889 				     struct cftype *cft)
3890 {
3891 	return 1;
3892 }
3893 
3894 static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
3895 				      struct cftype *cft, u64 val)
3896 {
3897 	if (val == 1)
3898 		return 0;
3899 
3900 	pr_warn_once("Non-hierarchical mode is deprecated. "
3901 		     "Please report your usecase to linux-mm@kvack.org if you "
3902 		     "depend on this functionality.\n");
3903 
3904 	return -EINVAL;
3905 }
3906 
3907 static unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
3908 {
3909 	unsigned long val;
3910 
3911 	if (mem_cgroup_is_root(memcg)) {
3912 		/*
3913 		 * Approximate root's usage from global state. This isn't
3914 		 * perfect, but the root usage was always an approximation.
3915 		 */
3916 		val = global_node_page_state(NR_FILE_PAGES) +
3917 			global_node_page_state(NR_ANON_MAPPED);
3918 		if (swap)
3919 			val += total_swap_pages - get_nr_swap_pages();
3920 	} else {
3921 		if (!swap)
3922 			val = page_counter_read(&memcg->memory);
3923 		else
3924 			val = page_counter_read(&memcg->memsw);
3925 	}
3926 	return val;
3927 }
3928 
3929 enum {
3930 	RES_USAGE,
3931 	RES_LIMIT,
3932 	RES_MAX_USAGE,
3933 	RES_FAILCNT,
3934 	RES_SOFT_LIMIT,
3935 };
3936 
3937 static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
3938 			       struct cftype *cft)
3939 {
3940 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3941 	struct page_counter *counter;
3942 
3943 	switch (MEMFILE_TYPE(cft->private)) {
3944 	case _MEM:
3945 		counter = &memcg->memory;
3946 		break;
3947 	case _MEMSWAP:
3948 		counter = &memcg->memsw;
3949 		break;
3950 	case _KMEM:
3951 		counter = &memcg->kmem;
3952 		break;
3953 	case _TCP:
3954 		counter = &memcg->tcpmem;
3955 		break;
3956 	default:
3957 		BUG();
3958 	}
3959 
3960 	switch (MEMFILE_ATTR(cft->private)) {
3961 	case RES_USAGE:
3962 		if (counter == &memcg->memory)
3963 			return (u64)mem_cgroup_usage(memcg, false) * PAGE_SIZE;
3964 		if (counter == &memcg->memsw)
3965 			return (u64)mem_cgroup_usage(memcg, true) * PAGE_SIZE;
3966 		return (u64)page_counter_read(counter) * PAGE_SIZE;
3967 	case RES_LIMIT:
3968 		return (u64)counter->max * PAGE_SIZE;
3969 	case RES_MAX_USAGE:
3970 		return (u64)counter->watermark * PAGE_SIZE;
3971 	case RES_FAILCNT:
3972 		return counter->failcnt;
3973 	case RES_SOFT_LIMIT:
3974 		return (u64)READ_ONCE(memcg->soft_limit) * PAGE_SIZE;
3975 	default:
3976 		BUG();
3977 	}
3978 }
3979 
3980 /*
3981  * This function doesn't do anything useful. Its only job is to provide a read
3982  * handler for a file so that cgroup_file_mode() will add read permissions.
3983  */
3984 static int mem_cgroup_dummy_seq_show(__always_unused struct seq_file *m,
3985 				     __always_unused void *v)
3986 {
3987 	return -EINVAL;
3988 }
3989 
3990 #ifdef CONFIG_MEMCG_KMEM
3991 static int memcg_online_kmem(struct mem_cgroup *memcg)
3992 {
3993 	struct obj_cgroup *objcg;
3994 
3995 	if (mem_cgroup_kmem_disabled())
3996 		return 0;
3997 
3998 	if (unlikely(mem_cgroup_is_root(memcg)))
3999 		return 0;
4000 
4001 	objcg = obj_cgroup_alloc();
4002 	if (!objcg)
4003 		return -ENOMEM;
4004 
4005 	objcg->memcg = memcg;
4006 	rcu_assign_pointer(memcg->objcg, objcg);
4007 	obj_cgroup_get(objcg);
4008 	memcg->orig_objcg = objcg;
4009 
4010 	static_branch_enable(&memcg_kmem_online_key);
4011 
4012 	memcg->kmemcg_id = memcg->id.id;
4013 
4014 	return 0;
4015 }
4016 
4017 static void memcg_offline_kmem(struct mem_cgroup *memcg)
4018 {
4019 	struct mem_cgroup *parent;
4020 
4021 	if (mem_cgroup_kmem_disabled())
4022 		return;
4023 
4024 	if (unlikely(mem_cgroup_is_root(memcg)))
4025 		return;
4026 
4027 	parent = parent_mem_cgroup(memcg);
4028 	if (!parent)
4029 		parent = root_mem_cgroup;
4030 
4031 	memcg_reparent_objcgs(memcg, parent);
4032 
4033 	/*
4034 	 * After we have finished memcg_reparent_objcgs(), all list_lrus
4035 	 * corresponding to this cgroup are guaranteed to remain empty.
4036 	 * The ordering is imposed by list_lru_node->lock taken by
4037 	 * memcg_reparent_list_lrus().
4038 	 */
4039 	memcg_reparent_list_lrus(memcg, parent);
4040 }
4041 #else
4042 static int memcg_online_kmem(struct mem_cgroup *memcg)
4043 {
4044 	return 0;
4045 }
4046 static void memcg_offline_kmem(struct mem_cgroup *memcg)
4047 {
4048 }
4049 #endif /* CONFIG_MEMCG_KMEM */
4050 
4051 static int memcg_update_tcp_max(struct mem_cgroup *memcg, unsigned long max)
4052 {
4053 	int ret;
4054 
4055 	mutex_lock(&memcg_max_mutex);
4056 
4057 	ret = page_counter_set_max(&memcg->tcpmem, max);
4058 	if (ret)
4059 		goto out;
4060 
4061 	if (!memcg->tcpmem_active) {
4062 		/*
4063 		 * The active flag needs to be written after the static_key
4064 		 * update. This is what guarantees that the socket activation
4065 		 * function is the last one to run. See mem_cgroup_sk_alloc()
4066 		 * for details, and note that we don't mark any socket as
4067 		 * belonging to this memcg until that flag is up.
4068 		 *
4069 		 * We need to do this, because static_keys will span multiple
4070 		 * sites, but we can't control their order. If we mark a socket
4071 		 * as accounted, but the accounting functions are not patched in
4072 		 * yet, we'll lose accounting.
4073 		 *
4074 		 * We never race with the readers in mem_cgroup_sk_alloc(),
4075 		 * because when this value change, the code to process it is not
4076 		 * patched in yet.
4077 		 */
4078 		static_branch_inc(&memcg_sockets_enabled_key);
4079 		memcg->tcpmem_active = true;
4080 	}
4081 out:
4082 	mutex_unlock(&memcg_max_mutex);
4083 	return ret;
4084 }
4085 
4086 /*
4087  * The user of this function is...
4088  * RES_LIMIT.
4089  */
4090 static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
4091 				char *buf, size_t nbytes, loff_t off)
4092 {
4093 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4094 	unsigned long nr_pages;
4095 	int ret;
4096 
4097 	buf = strstrip(buf);
4098 	ret = page_counter_memparse(buf, "-1", &nr_pages);
4099 	if (ret)
4100 		return ret;
4101 
4102 	switch (MEMFILE_ATTR(of_cft(of)->private)) {
4103 	case RES_LIMIT:
4104 		if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
4105 			ret = -EINVAL;
4106 			break;
4107 		}
4108 		switch (MEMFILE_TYPE(of_cft(of)->private)) {
4109 		case _MEM:
4110 			ret = mem_cgroup_resize_max(memcg, nr_pages, false);
4111 			break;
4112 		case _MEMSWAP:
4113 			ret = mem_cgroup_resize_max(memcg, nr_pages, true);
4114 			break;
4115 		case _KMEM:
4116 			pr_warn_once("kmem.limit_in_bytes is deprecated and will be removed. "
4117 				     "Writing any value to this file has no effect. "
4118 				     "Please report your usecase to linux-mm@kvack.org if you "
4119 				     "depend on this functionality.\n");
4120 			ret = 0;
4121 			break;
4122 		case _TCP:
4123 			ret = memcg_update_tcp_max(memcg, nr_pages);
4124 			break;
4125 		}
4126 		break;
4127 	case RES_SOFT_LIMIT:
4128 		if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
4129 			ret = -EOPNOTSUPP;
4130 		} else {
4131 			WRITE_ONCE(memcg->soft_limit, nr_pages);
4132 			ret = 0;
4133 		}
4134 		break;
4135 	}
4136 	return ret ?: nbytes;
4137 }
4138 
4139 static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
4140 				size_t nbytes, loff_t off)
4141 {
4142 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4143 	struct page_counter *counter;
4144 
4145 	switch (MEMFILE_TYPE(of_cft(of)->private)) {
4146 	case _MEM:
4147 		counter = &memcg->memory;
4148 		break;
4149 	case _MEMSWAP:
4150 		counter = &memcg->memsw;
4151 		break;
4152 	case _KMEM:
4153 		counter = &memcg->kmem;
4154 		break;
4155 	case _TCP:
4156 		counter = &memcg->tcpmem;
4157 		break;
4158 	default:
4159 		BUG();
4160 	}
4161 
4162 	switch (MEMFILE_ATTR(of_cft(of)->private)) {
4163 	case RES_MAX_USAGE:
4164 		page_counter_reset_watermark(counter);
4165 		break;
4166 	case RES_FAILCNT:
4167 		counter->failcnt = 0;
4168 		break;
4169 	default:
4170 		BUG();
4171 	}
4172 
4173 	return nbytes;
4174 }
4175 
4176 static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
4177 					struct cftype *cft)
4178 {
4179 	return mem_cgroup_from_css(css)->move_charge_at_immigrate;
4180 }
4181 
4182 #ifdef CONFIG_MMU
4183 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
4184 					struct cftype *cft, u64 val)
4185 {
4186 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4187 
4188 	pr_warn_once("Cgroup memory moving (move_charge_at_immigrate) is deprecated. "
4189 		     "Please report your usecase to linux-mm@kvack.org if you "
4190 		     "depend on this functionality.\n");
4191 
4192 	if (val & ~MOVE_MASK)
4193 		return -EINVAL;
4194 
4195 	/*
4196 	 * No kind of locking is needed in here, because ->can_attach() will
4197 	 * check this value once in the beginning of the process, and then carry
4198 	 * on with stale data. This means that changes to this value will only
4199 	 * affect task migrations starting after the change.
4200 	 */
4201 	memcg->move_charge_at_immigrate = val;
4202 	return 0;
4203 }
4204 #else
4205 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
4206 					struct cftype *cft, u64 val)
4207 {
4208 	return -ENOSYS;
4209 }
4210 #endif
4211 
4212 #ifdef CONFIG_NUMA
4213 
4214 #define LRU_ALL_FILE (BIT(LRU_INACTIVE_FILE) | BIT(LRU_ACTIVE_FILE))
4215 #define LRU_ALL_ANON (BIT(LRU_INACTIVE_ANON) | BIT(LRU_ACTIVE_ANON))
4216 #define LRU_ALL	     ((1 << NR_LRU_LISTS) - 1)
4217 
4218 static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
4219 				int nid, unsigned int lru_mask, bool tree)
4220 {
4221 	struct lruvec *lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
4222 	unsigned long nr = 0;
4223 	enum lru_list lru;
4224 
4225 	VM_BUG_ON((unsigned)nid >= nr_node_ids);
4226 
4227 	for_each_lru(lru) {
4228 		if (!(BIT(lru) & lru_mask))
4229 			continue;
4230 		if (tree)
4231 			nr += lruvec_page_state(lruvec, NR_LRU_BASE + lru);
4232 		else
4233 			nr += lruvec_page_state_local(lruvec, NR_LRU_BASE + lru);
4234 	}
4235 	return nr;
4236 }
4237 
4238 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
4239 					     unsigned int lru_mask,
4240 					     bool tree)
4241 {
4242 	unsigned long nr = 0;
4243 	enum lru_list lru;
4244 
4245 	for_each_lru(lru) {
4246 		if (!(BIT(lru) & lru_mask))
4247 			continue;
4248 		if (tree)
4249 			nr += memcg_page_state(memcg, NR_LRU_BASE + lru);
4250 		else
4251 			nr += memcg_page_state_local(memcg, NR_LRU_BASE + lru);
4252 	}
4253 	return nr;
4254 }
4255 
4256 static int memcg_numa_stat_show(struct seq_file *m, void *v)
4257 {
4258 	struct numa_stat {
4259 		const char *name;
4260 		unsigned int lru_mask;
4261 	};
4262 
4263 	static const struct numa_stat stats[] = {
4264 		{ "total", LRU_ALL },
4265 		{ "file", LRU_ALL_FILE },
4266 		{ "anon", LRU_ALL_ANON },
4267 		{ "unevictable", BIT(LRU_UNEVICTABLE) },
4268 	};
4269 	const struct numa_stat *stat;
4270 	int nid;
4271 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
4272 
4273 	mem_cgroup_flush_stats(memcg);
4274 
4275 	for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
4276 		seq_printf(m, "%s=%lu", stat->name,
4277 			   mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
4278 						   false));
4279 		for_each_node_state(nid, N_MEMORY)
4280 			seq_printf(m, " N%d=%lu", nid,
4281 				   mem_cgroup_node_nr_lru_pages(memcg, nid,
4282 							stat->lru_mask, false));
4283 		seq_putc(m, '\n');
4284 	}
4285 
4286 	for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
4287 
4288 		seq_printf(m, "hierarchical_%s=%lu", stat->name,
4289 			   mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
4290 						   true));
4291 		for_each_node_state(nid, N_MEMORY)
4292 			seq_printf(m, " N%d=%lu", nid,
4293 				   mem_cgroup_node_nr_lru_pages(memcg, nid,
4294 							stat->lru_mask, true));
4295 		seq_putc(m, '\n');
4296 	}
4297 
4298 	return 0;
4299 }
4300 #endif /* CONFIG_NUMA */
4301 
4302 static const unsigned int memcg1_stats[] = {
4303 	NR_FILE_PAGES,
4304 	NR_ANON_MAPPED,
4305 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4306 	NR_ANON_THPS,
4307 #endif
4308 	NR_SHMEM,
4309 	NR_FILE_MAPPED,
4310 	NR_FILE_DIRTY,
4311 	NR_WRITEBACK,
4312 	WORKINGSET_REFAULT_ANON,
4313 	WORKINGSET_REFAULT_FILE,
4314 #ifdef CONFIG_SWAP
4315 	MEMCG_SWAP,
4316 	NR_SWAPCACHE,
4317 #endif
4318 };
4319 
4320 static const char *const memcg1_stat_names[] = {
4321 	"cache",
4322 	"rss",
4323 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4324 	"rss_huge",
4325 #endif
4326 	"shmem",
4327 	"mapped_file",
4328 	"dirty",
4329 	"writeback",
4330 	"workingset_refault_anon",
4331 	"workingset_refault_file",
4332 #ifdef CONFIG_SWAP
4333 	"swap",
4334 	"swapcached",
4335 #endif
4336 };
4337 
4338 /* Universal VM events cgroup1 shows, original sort order */
4339 static const unsigned int memcg1_events[] = {
4340 	PGPGIN,
4341 	PGPGOUT,
4342 	PGFAULT,
4343 	PGMAJFAULT,
4344 };
4345 
4346 static void memcg1_stat_format(struct mem_cgroup *memcg, struct seq_buf *s)
4347 {
4348 	unsigned long memory, memsw;
4349 	struct mem_cgroup *mi;
4350 	unsigned int i;
4351 
4352 	BUILD_BUG_ON(ARRAY_SIZE(memcg1_stat_names) != ARRAY_SIZE(memcg1_stats));
4353 
4354 	mem_cgroup_flush_stats(memcg);
4355 
4356 	for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
4357 		unsigned long nr;
4358 
4359 		nr = memcg_page_state_local_output(memcg, memcg1_stats[i]);
4360 		seq_buf_printf(s, "%s %lu\n", memcg1_stat_names[i], nr);
4361 	}
4362 
4363 	for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
4364 		seq_buf_printf(s, "%s %lu\n", vm_event_name(memcg1_events[i]),
4365 			       memcg_events_local(memcg, memcg1_events[i]));
4366 
4367 	for (i = 0; i < NR_LRU_LISTS; i++)
4368 		seq_buf_printf(s, "%s %lu\n", lru_list_name(i),
4369 			       memcg_page_state_local(memcg, NR_LRU_BASE + i) *
4370 			       PAGE_SIZE);
4371 
4372 	/* Hierarchical information */
4373 	memory = memsw = PAGE_COUNTER_MAX;
4374 	for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
4375 		memory = min(memory, READ_ONCE(mi->memory.max));
4376 		memsw = min(memsw, READ_ONCE(mi->memsw.max));
4377 	}
4378 	seq_buf_printf(s, "hierarchical_memory_limit %llu\n",
4379 		       (u64)memory * PAGE_SIZE);
4380 	seq_buf_printf(s, "hierarchical_memsw_limit %llu\n",
4381 		       (u64)memsw * PAGE_SIZE);
4382 
4383 	for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
4384 		unsigned long nr;
4385 
4386 		nr = memcg_page_state_output(memcg, memcg1_stats[i]);
4387 		seq_buf_printf(s, "total_%s %llu\n", memcg1_stat_names[i],
4388 			       (u64)nr);
4389 	}
4390 
4391 	for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
4392 		seq_buf_printf(s, "total_%s %llu\n",
4393 			       vm_event_name(memcg1_events[i]),
4394 			       (u64)memcg_events(memcg, memcg1_events[i]));
4395 
4396 	for (i = 0; i < NR_LRU_LISTS; i++)
4397 		seq_buf_printf(s, "total_%s %llu\n", lru_list_name(i),
4398 			       (u64)memcg_page_state(memcg, NR_LRU_BASE + i) *
4399 			       PAGE_SIZE);
4400 
4401 #ifdef CONFIG_DEBUG_VM
4402 	{
4403 		pg_data_t *pgdat;
4404 		struct mem_cgroup_per_node *mz;
4405 		unsigned long anon_cost = 0;
4406 		unsigned long file_cost = 0;
4407 
4408 		for_each_online_pgdat(pgdat) {
4409 			mz = memcg->nodeinfo[pgdat->node_id];
4410 
4411 			anon_cost += mz->lruvec.anon_cost;
4412 			file_cost += mz->lruvec.file_cost;
4413 		}
4414 		seq_buf_printf(s, "anon_cost %lu\n", anon_cost);
4415 		seq_buf_printf(s, "file_cost %lu\n", file_cost);
4416 	}
4417 #endif
4418 }
4419 
4420 static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
4421 				      struct cftype *cft)
4422 {
4423 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4424 
4425 	return mem_cgroup_swappiness(memcg);
4426 }
4427 
4428 static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
4429 				       struct cftype *cft, u64 val)
4430 {
4431 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4432 
4433 	if (val > 200)
4434 		return -EINVAL;
4435 
4436 	if (!mem_cgroup_is_root(memcg))
4437 		WRITE_ONCE(memcg->swappiness, val);
4438 	else
4439 		WRITE_ONCE(vm_swappiness, val);
4440 
4441 	return 0;
4442 }
4443 
4444 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4445 {
4446 	struct mem_cgroup_threshold_ary *t;
4447 	unsigned long usage;
4448 	int i;
4449 
4450 	rcu_read_lock();
4451 	if (!swap)
4452 		t = rcu_dereference(memcg->thresholds.primary);
4453 	else
4454 		t = rcu_dereference(memcg->memsw_thresholds.primary);
4455 
4456 	if (!t)
4457 		goto unlock;
4458 
4459 	usage = mem_cgroup_usage(memcg, swap);
4460 
4461 	/*
4462 	 * current_threshold points to threshold just below or equal to usage.
4463 	 * If it's not true, a threshold was crossed after last
4464 	 * call of __mem_cgroup_threshold().
4465 	 */
4466 	i = t->current_threshold;
4467 
4468 	/*
4469 	 * Iterate backward over array of thresholds starting from
4470 	 * current_threshold and check if a threshold is crossed.
4471 	 * If none of thresholds below usage is crossed, we read
4472 	 * only one element of the array here.
4473 	 */
4474 	for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4475 		eventfd_signal(t->entries[i].eventfd);
4476 
4477 	/* i = current_threshold + 1 */
4478 	i++;
4479 
4480 	/*
4481 	 * Iterate forward over array of thresholds starting from
4482 	 * current_threshold+1 and check if a threshold is crossed.
4483 	 * If none of thresholds above usage is crossed, we read
4484 	 * only one element of the array here.
4485 	 */
4486 	for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4487 		eventfd_signal(t->entries[i].eventfd);
4488 
4489 	/* Update current_threshold */
4490 	t->current_threshold = i - 1;
4491 unlock:
4492 	rcu_read_unlock();
4493 }
4494 
4495 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4496 {
4497 	while (memcg) {
4498 		__mem_cgroup_threshold(memcg, false);
4499 		if (do_memsw_account())
4500 			__mem_cgroup_threshold(memcg, true);
4501 
4502 		memcg = parent_mem_cgroup(memcg);
4503 	}
4504 }
4505 
4506 static int compare_thresholds(const void *a, const void *b)
4507 {
4508 	const struct mem_cgroup_threshold *_a = a;
4509 	const struct mem_cgroup_threshold *_b = b;
4510 
4511 	if (_a->threshold > _b->threshold)
4512 		return 1;
4513 
4514 	if (_a->threshold < _b->threshold)
4515 		return -1;
4516 
4517 	return 0;
4518 }
4519 
4520 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
4521 {
4522 	struct mem_cgroup_eventfd_list *ev;
4523 
4524 	spin_lock(&memcg_oom_lock);
4525 
4526 	list_for_each_entry(ev, &memcg->oom_notify, list)
4527 		eventfd_signal(ev->eventfd);
4528 
4529 	spin_unlock(&memcg_oom_lock);
4530 	return 0;
4531 }
4532 
4533 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
4534 {
4535 	struct mem_cgroup *iter;
4536 
4537 	for_each_mem_cgroup_tree(iter, memcg)
4538 		mem_cgroup_oom_notify_cb(iter);
4539 }
4540 
4541 static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4542 	struct eventfd_ctx *eventfd, const char *args, enum res_type type)
4543 {
4544 	struct mem_cgroup_thresholds *thresholds;
4545 	struct mem_cgroup_threshold_ary *new;
4546 	unsigned long threshold;
4547 	unsigned long usage;
4548 	int i, size, ret;
4549 
4550 	ret = page_counter_memparse(args, "-1", &threshold);
4551 	if (ret)
4552 		return ret;
4553 
4554 	mutex_lock(&memcg->thresholds_lock);
4555 
4556 	if (type == _MEM) {
4557 		thresholds = &memcg->thresholds;
4558 		usage = mem_cgroup_usage(memcg, false);
4559 	} else if (type == _MEMSWAP) {
4560 		thresholds = &memcg->memsw_thresholds;
4561 		usage = mem_cgroup_usage(memcg, true);
4562 	} else
4563 		BUG();
4564 
4565 	/* Check if a threshold crossed before adding a new one */
4566 	if (thresholds->primary)
4567 		__mem_cgroup_threshold(memcg, type == _MEMSWAP);
4568 
4569 	size = thresholds->primary ? thresholds->primary->size + 1 : 1;
4570 
4571 	/* Allocate memory for new array of thresholds */
4572 	new = kmalloc(struct_size(new, entries, size), GFP_KERNEL);
4573 	if (!new) {
4574 		ret = -ENOMEM;
4575 		goto unlock;
4576 	}
4577 	new->size = size;
4578 
4579 	/* Copy thresholds (if any) to new array */
4580 	if (thresholds->primary)
4581 		memcpy(new->entries, thresholds->primary->entries,
4582 		       flex_array_size(new, entries, size - 1));
4583 
4584 	/* Add new threshold */
4585 	new->entries[size - 1].eventfd = eventfd;
4586 	new->entries[size - 1].threshold = threshold;
4587 
4588 	/* Sort thresholds. Registering of new threshold isn't time-critical */
4589 	sort(new->entries, size, sizeof(*new->entries),
4590 			compare_thresholds, NULL);
4591 
4592 	/* Find current threshold */
4593 	new->current_threshold = -1;
4594 	for (i = 0; i < size; i++) {
4595 		if (new->entries[i].threshold <= usage) {
4596 			/*
4597 			 * new->current_threshold will not be used until
4598 			 * rcu_assign_pointer(), so it's safe to increment
4599 			 * it here.
4600 			 */
4601 			++new->current_threshold;
4602 		} else
4603 			break;
4604 	}
4605 
4606 	/* Free old spare buffer and save old primary buffer as spare */
4607 	kfree(thresholds->spare);
4608 	thresholds->spare = thresholds->primary;
4609 
4610 	rcu_assign_pointer(thresholds->primary, new);
4611 
4612 	/* To be sure that nobody uses thresholds */
4613 	synchronize_rcu();
4614 
4615 unlock:
4616 	mutex_unlock(&memcg->thresholds_lock);
4617 
4618 	return ret;
4619 }
4620 
4621 static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4622 	struct eventfd_ctx *eventfd, const char *args)
4623 {
4624 	return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
4625 }
4626 
4627 static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
4628 	struct eventfd_ctx *eventfd, const char *args)
4629 {
4630 	return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
4631 }
4632 
4633 static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4634 	struct eventfd_ctx *eventfd, enum res_type type)
4635 {
4636 	struct mem_cgroup_thresholds *thresholds;
4637 	struct mem_cgroup_threshold_ary *new;
4638 	unsigned long usage;
4639 	int i, j, size, entries;
4640 
4641 	mutex_lock(&memcg->thresholds_lock);
4642 
4643 	if (type == _MEM) {
4644 		thresholds = &memcg->thresholds;
4645 		usage = mem_cgroup_usage(memcg, false);
4646 	} else if (type == _MEMSWAP) {
4647 		thresholds = &memcg->memsw_thresholds;
4648 		usage = mem_cgroup_usage(memcg, true);
4649 	} else
4650 		BUG();
4651 
4652 	if (!thresholds->primary)
4653 		goto unlock;
4654 
4655 	/* Check if a threshold crossed before removing */
4656 	__mem_cgroup_threshold(memcg, type == _MEMSWAP);
4657 
4658 	/* Calculate new number of threshold */
4659 	size = entries = 0;
4660 	for (i = 0; i < thresholds->primary->size; i++) {
4661 		if (thresholds->primary->entries[i].eventfd != eventfd)
4662 			size++;
4663 		else
4664 			entries++;
4665 	}
4666 
4667 	new = thresholds->spare;
4668 
4669 	/* If no items related to eventfd have been cleared, nothing to do */
4670 	if (!entries)
4671 		goto unlock;
4672 
4673 	/* Set thresholds array to NULL if we don't have thresholds */
4674 	if (!size) {
4675 		kfree(new);
4676 		new = NULL;
4677 		goto swap_buffers;
4678 	}
4679 
4680 	new->size = size;
4681 
4682 	/* Copy thresholds and find current threshold */
4683 	new->current_threshold = -1;
4684 	for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4685 		if (thresholds->primary->entries[i].eventfd == eventfd)
4686 			continue;
4687 
4688 		new->entries[j] = thresholds->primary->entries[i];
4689 		if (new->entries[j].threshold <= usage) {
4690 			/*
4691 			 * new->current_threshold will not be used
4692 			 * until rcu_assign_pointer(), so it's safe to increment
4693 			 * it here.
4694 			 */
4695 			++new->current_threshold;
4696 		}
4697 		j++;
4698 	}
4699 
4700 swap_buffers:
4701 	/* Swap primary and spare array */
4702 	thresholds->spare = thresholds->primary;
4703 
4704 	rcu_assign_pointer(thresholds->primary, new);
4705 
4706 	/* To be sure that nobody uses thresholds */
4707 	synchronize_rcu();
4708 
4709 	/* If all events are unregistered, free the spare array */
4710 	if (!new) {
4711 		kfree(thresholds->spare);
4712 		thresholds->spare = NULL;
4713 	}
4714 unlock:
4715 	mutex_unlock(&memcg->thresholds_lock);
4716 }
4717 
4718 static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4719 	struct eventfd_ctx *eventfd)
4720 {
4721 	return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
4722 }
4723 
4724 static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4725 	struct eventfd_ctx *eventfd)
4726 {
4727 	return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
4728 }
4729 
4730 static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
4731 	struct eventfd_ctx *eventfd, const char *args)
4732 {
4733 	struct mem_cgroup_eventfd_list *event;
4734 
4735 	event = kmalloc(sizeof(*event),	GFP_KERNEL);
4736 	if (!event)
4737 		return -ENOMEM;
4738 
4739 	spin_lock(&memcg_oom_lock);
4740 
4741 	event->eventfd = eventfd;
4742 	list_add(&event->list, &memcg->oom_notify);
4743 
4744 	/* already in OOM ? */
4745 	if (memcg->under_oom)
4746 		eventfd_signal(eventfd);
4747 	spin_unlock(&memcg_oom_lock);
4748 
4749 	return 0;
4750 }
4751 
4752 static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
4753 	struct eventfd_ctx *eventfd)
4754 {
4755 	struct mem_cgroup_eventfd_list *ev, *tmp;
4756 
4757 	spin_lock(&memcg_oom_lock);
4758 
4759 	list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
4760 		if (ev->eventfd == eventfd) {
4761 			list_del(&ev->list);
4762 			kfree(ev);
4763 		}
4764 	}
4765 
4766 	spin_unlock(&memcg_oom_lock);
4767 }
4768 
4769 static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
4770 {
4771 	struct mem_cgroup *memcg = mem_cgroup_from_seq(sf);
4772 
4773 	seq_printf(sf, "oom_kill_disable %d\n", READ_ONCE(memcg->oom_kill_disable));
4774 	seq_printf(sf, "under_oom %d\n", (bool)memcg->under_oom);
4775 	seq_printf(sf, "oom_kill %lu\n",
4776 		   atomic_long_read(&memcg->memory_events[MEMCG_OOM_KILL]));
4777 	return 0;
4778 }
4779 
4780 static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
4781 	struct cftype *cft, u64 val)
4782 {
4783 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4784 
4785 	/* cannot set to root cgroup and only 0 and 1 are allowed */
4786 	if (mem_cgroup_is_root(memcg) || !((val == 0) || (val == 1)))
4787 		return -EINVAL;
4788 
4789 	WRITE_ONCE(memcg->oom_kill_disable, val);
4790 	if (!val)
4791 		memcg_oom_recover(memcg);
4792 
4793 	return 0;
4794 }
4795 
4796 #ifdef CONFIG_CGROUP_WRITEBACK
4797 
4798 #include <trace/events/writeback.h>
4799 
4800 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4801 {
4802 	return wb_domain_init(&memcg->cgwb_domain, gfp);
4803 }
4804 
4805 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4806 {
4807 	wb_domain_exit(&memcg->cgwb_domain);
4808 }
4809 
4810 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4811 {
4812 	wb_domain_size_changed(&memcg->cgwb_domain);
4813 }
4814 
4815 struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb)
4816 {
4817 	struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4818 
4819 	if (!memcg->css.parent)
4820 		return NULL;
4821 
4822 	return &memcg->cgwb_domain;
4823 }
4824 
4825 /**
4826  * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
4827  * @wb: bdi_writeback in question
4828  * @pfilepages: out parameter for number of file pages
4829  * @pheadroom: out parameter for number of allocatable pages according to memcg
4830  * @pdirty: out parameter for number of dirty pages
4831  * @pwriteback: out parameter for number of pages under writeback
4832  *
4833  * Determine the numbers of file, headroom, dirty, and writeback pages in
4834  * @wb's memcg.  File, dirty and writeback are self-explanatory.  Headroom
4835  * is a bit more involved.
4836  *
4837  * A memcg's headroom is "min(max, high) - used".  In the hierarchy, the
4838  * headroom is calculated as the lowest headroom of itself and the
4839  * ancestors.  Note that this doesn't consider the actual amount of
4840  * available memory in the system.  The caller should further cap
4841  * *@pheadroom accordingly.
4842  */
4843 void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages,
4844 			 unsigned long *pheadroom, unsigned long *pdirty,
4845 			 unsigned long *pwriteback)
4846 {
4847 	struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4848 	struct mem_cgroup *parent;
4849 
4850 	mem_cgroup_flush_stats_ratelimited(memcg);
4851 
4852 	*pdirty = memcg_page_state(memcg, NR_FILE_DIRTY);
4853 	*pwriteback = memcg_page_state(memcg, NR_WRITEBACK);
4854 	*pfilepages = memcg_page_state(memcg, NR_INACTIVE_FILE) +
4855 			memcg_page_state(memcg, NR_ACTIVE_FILE);
4856 
4857 	*pheadroom = PAGE_COUNTER_MAX;
4858 	while ((parent = parent_mem_cgroup(memcg))) {
4859 		unsigned long ceiling = min(READ_ONCE(memcg->memory.max),
4860 					    READ_ONCE(memcg->memory.high));
4861 		unsigned long used = page_counter_read(&memcg->memory);
4862 
4863 		*pheadroom = min(*pheadroom, ceiling - min(ceiling, used));
4864 		memcg = parent;
4865 	}
4866 }
4867 
4868 /*
4869  * Foreign dirty flushing
4870  *
4871  * There's an inherent mismatch between memcg and writeback.  The former
4872  * tracks ownership per-page while the latter per-inode.  This was a
4873  * deliberate design decision because honoring per-page ownership in the
4874  * writeback path is complicated, may lead to higher CPU and IO overheads
4875  * and deemed unnecessary given that write-sharing an inode across
4876  * different cgroups isn't a common use-case.
4877  *
4878  * Combined with inode majority-writer ownership switching, this works well
4879  * enough in most cases but there are some pathological cases.  For
4880  * example, let's say there are two cgroups A and B which keep writing to
4881  * different but confined parts of the same inode.  B owns the inode and
4882  * A's memory is limited far below B's.  A's dirty ratio can rise enough to
4883  * trigger balance_dirty_pages() sleeps but B's can be low enough to avoid
4884  * triggering background writeback.  A will be slowed down without a way to
4885  * make writeback of the dirty pages happen.
4886  *
4887  * Conditions like the above can lead to a cgroup getting repeatedly and
4888  * severely throttled after making some progress after each
4889  * dirty_expire_interval while the underlying IO device is almost
4890  * completely idle.
4891  *
4892  * Solving this problem completely requires matching the ownership tracking
4893  * granularities between memcg and writeback in either direction.  However,
4894  * the more egregious behaviors can be avoided by simply remembering the
4895  * most recent foreign dirtying events and initiating remote flushes on
4896  * them when local writeback isn't enough to keep the memory clean enough.
4897  *
4898  * The following two functions implement such mechanism.  When a foreign
4899  * page - a page whose memcg and writeback ownerships don't match - is
4900  * dirtied, mem_cgroup_track_foreign_dirty() records the inode owning
4901  * bdi_writeback on the page owning memcg.  When balance_dirty_pages()
4902  * decides that the memcg needs to sleep due to high dirty ratio, it calls
4903  * mem_cgroup_flush_foreign() which queues writeback on the recorded
4904  * foreign bdi_writebacks which haven't expired.  Both the numbers of
4905  * recorded bdi_writebacks and concurrent in-flight foreign writebacks are
4906  * limited to MEMCG_CGWB_FRN_CNT.
4907  *
4908  * The mechanism only remembers IDs and doesn't hold any object references.
4909  * As being wrong occasionally doesn't matter, updates and accesses to the
4910  * records are lockless and racy.
4911  */
4912 void mem_cgroup_track_foreign_dirty_slowpath(struct folio *folio,
4913 					     struct bdi_writeback *wb)
4914 {
4915 	struct mem_cgroup *memcg = folio_memcg(folio);
4916 	struct memcg_cgwb_frn *frn;
4917 	u64 now = get_jiffies_64();
4918 	u64 oldest_at = now;
4919 	int oldest = -1;
4920 	int i;
4921 
4922 	trace_track_foreign_dirty(folio, wb);
4923 
4924 	/*
4925 	 * Pick the slot to use.  If there is already a slot for @wb, keep
4926 	 * using it.  If not replace the oldest one which isn't being
4927 	 * written out.
4928 	 */
4929 	for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4930 		frn = &memcg->cgwb_frn[i];
4931 		if (frn->bdi_id == wb->bdi->id &&
4932 		    frn->memcg_id == wb->memcg_css->id)
4933 			break;
4934 		if (time_before64(frn->at, oldest_at) &&
4935 		    atomic_read(&frn->done.cnt) == 1) {
4936 			oldest = i;
4937 			oldest_at = frn->at;
4938 		}
4939 	}
4940 
4941 	if (i < MEMCG_CGWB_FRN_CNT) {
4942 		/*
4943 		 * Re-using an existing one.  Update timestamp lazily to
4944 		 * avoid making the cacheline hot.  We want them to be
4945 		 * reasonably up-to-date and significantly shorter than
4946 		 * dirty_expire_interval as that's what expires the record.
4947 		 * Use the shorter of 1s and dirty_expire_interval / 8.
4948 		 */
4949 		unsigned long update_intv =
4950 			min_t(unsigned long, HZ,
4951 			      msecs_to_jiffies(dirty_expire_interval * 10) / 8);
4952 
4953 		if (time_before64(frn->at, now - update_intv))
4954 			frn->at = now;
4955 	} else if (oldest >= 0) {
4956 		/* replace the oldest free one */
4957 		frn = &memcg->cgwb_frn[oldest];
4958 		frn->bdi_id = wb->bdi->id;
4959 		frn->memcg_id = wb->memcg_css->id;
4960 		frn->at = now;
4961 	}
4962 }
4963 
4964 /* issue foreign writeback flushes for recorded foreign dirtying events */
4965 void mem_cgroup_flush_foreign(struct bdi_writeback *wb)
4966 {
4967 	struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4968 	unsigned long intv = msecs_to_jiffies(dirty_expire_interval * 10);
4969 	u64 now = jiffies_64;
4970 	int i;
4971 
4972 	for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4973 		struct memcg_cgwb_frn *frn = &memcg->cgwb_frn[i];
4974 
4975 		/*
4976 		 * If the record is older than dirty_expire_interval,
4977 		 * writeback on it has already started.  No need to kick it
4978 		 * off again.  Also, don't start a new one if there's
4979 		 * already one in flight.
4980 		 */
4981 		if (time_after64(frn->at, now - intv) &&
4982 		    atomic_read(&frn->done.cnt) == 1) {
4983 			frn->at = 0;
4984 			trace_flush_foreign(wb, frn->bdi_id, frn->memcg_id);
4985 			cgroup_writeback_by_id(frn->bdi_id, frn->memcg_id,
4986 					       WB_REASON_FOREIGN_FLUSH,
4987 					       &frn->done);
4988 		}
4989 	}
4990 }
4991 
4992 #else	/* CONFIG_CGROUP_WRITEBACK */
4993 
4994 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4995 {
4996 	return 0;
4997 }
4998 
4999 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
5000 {
5001 }
5002 
5003 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
5004 {
5005 }
5006 
5007 #endif	/* CONFIG_CGROUP_WRITEBACK */
5008 
5009 /*
5010  * DO NOT USE IN NEW FILES.
5011  *
5012  * "cgroup.event_control" implementation.
5013  *
5014  * This is way over-engineered.  It tries to support fully configurable
5015  * events for each user.  Such level of flexibility is completely
5016  * unnecessary especially in the light of the planned unified hierarchy.
5017  *
5018  * Please deprecate this and replace with something simpler if at all
5019  * possible.
5020  */
5021 
5022 /*
5023  * Unregister event and free resources.
5024  *
5025  * Gets called from workqueue.
5026  */
5027 static void memcg_event_remove(struct work_struct *work)
5028 {
5029 	struct mem_cgroup_event *event =
5030 		container_of(work, struct mem_cgroup_event, remove);
5031 	struct mem_cgroup *memcg = event->memcg;
5032 
5033 	remove_wait_queue(event->wqh, &event->wait);
5034 
5035 	event->unregister_event(memcg, event->eventfd);
5036 
5037 	/* Notify userspace the event is going away. */
5038 	eventfd_signal(event->eventfd);
5039 
5040 	eventfd_ctx_put(event->eventfd);
5041 	kfree(event);
5042 	css_put(&memcg->css);
5043 }
5044 
5045 /*
5046  * Gets called on EPOLLHUP on eventfd when user closes it.
5047  *
5048  * Called with wqh->lock held and interrupts disabled.
5049  */
5050 static int memcg_event_wake(wait_queue_entry_t *wait, unsigned mode,
5051 			    int sync, void *key)
5052 {
5053 	struct mem_cgroup_event *event =
5054 		container_of(wait, struct mem_cgroup_event, wait);
5055 	struct mem_cgroup *memcg = event->memcg;
5056 	__poll_t flags = key_to_poll(key);
5057 
5058 	if (flags & EPOLLHUP) {
5059 		/*
5060 		 * If the event has been detached at cgroup removal, we
5061 		 * can simply return knowing the other side will cleanup
5062 		 * for us.
5063 		 *
5064 		 * We can't race against event freeing since the other
5065 		 * side will require wqh->lock via remove_wait_queue(),
5066 		 * which we hold.
5067 		 */
5068 		spin_lock(&memcg->event_list_lock);
5069 		if (!list_empty(&event->list)) {
5070 			list_del_init(&event->list);
5071 			/*
5072 			 * We are in atomic context, but cgroup_event_remove()
5073 			 * may sleep, so we have to call it in workqueue.
5074 			 */
5075 			schedule_work(&event->remove);
5076 		}
5077 		spin_unlock(&memcg->event_list_lock);
5078 	}
5079 
5080 	return 0;
5081 }
5082 
5083 static void memcg_event_ptable_queue_proc(struct file *file,
5084 		wait_queue_head_t *wqh, poll_table *pt)
5085 {
5086 	struct mem_cgroup_event *event =
5087 		container_of(pt, struct mem_cgroup_event, pt);
5088 
5089 	event->wqh = wqh;
5090 	add_wait_queue(wqh, &event->wait);
5091 }
5092 
5093 /*
5094  * DO NOT USE IN NEW FILES.
5095  *
5096  * Parse input and register new cgroup event handler.
5097  *
5098  * Input must be in format '<event_fd> <control_fd> <args>'.
5099  * Interpretation of args is defined by control file implementation.
5100  */
5101 static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
5102 					 char *buf, size_t nbytes, loff_t off)
5103 {
5104 	struct cgroup_subsys_state *css = of_css(of);
5105 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5106 	struct mem_cgroup_event *event;
5107 	struct cgroup_subsys_state *cfile_css;
5108 	unsigned int efd, cfd;
5109 	struct fd efile;
5110 	struct fd cfile;
5111 	struct dentry *cdentry;
5112 	const char *name;
5113 	char *endp;
5114 	int ret;
5115 
5116 	if (IS_ENABLED(CONFIG_PREEMPT_RT))
5117 		return -EOPNOTSUPP;
5118 
5119 	buf = strstrip(buf);
5120 
5121 	efd = simple_strtoul(buf, &endp, 10);
5122 	if (*endp != ' ')
5123 		return -EINVAL;
5124 	buf = endp + 1;
5125 
5126 	cfd = simple_strtoul(buf, &endp, 10);
5127 	if ((*endp != ' ') && (*endp != '\0'))
5128 		return -EINVAL;
5129 	buf = endp + 1;
5130 
5131 	event = kzalloc(sizeof(*event), GFP_KERNEL);
5132 	if (!event)
5133 		return -ENOMEM;
5134 
5135 	event->memcg = memcg;
5136 	INIT_LIST_HEAD(&event->list);
5137 	init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
5138 	init_waitqueue_func_entry(&event->wait, memcg_event_wake);
5139 	INIT_WORK(&event->remove, memcg_event_remove);
5140 
5141 	efile = fdget(efd);
5142 	if (!efile.file) {
5143 		ret = -EBADF;
5144 		goto out_kfree;
5145 	}
5146 
5147 	event->eventfd = eventfd_ctx_fileget(efile.file);
5148 	if (IS_ERR(event->eventfd)) {
5149 		ret = PTR_ERR(event->eventfd);
5150 		goto out_put_efile;
5151 	}
5152 
5153 	cfile = fdget(cfd);
5154 	if (!cfile.file) {
5155 		ret = -EBADF;
5156 		goto out_put_eventfd;
5157 	}
5158 
5159 	/* the process need read permission on control file */
5160 	/* AV: shouldn't we check that it's been opened for read instead? */
5161 	ret = file_permission(cfile.file, MAY_READ);
5162 	if (ret < 0)
5163 		goto out_put_cfile;
5164 
5165 	/*
5166 	 * The control file must be a regular cgroup1 file. As a regular cgroup
5167 	 * file can't be renamed, it's safe to access its name afterwards.
5168 	 */
5169 	cdentry = cfile.file->f_path.dentry;
5170 	if (cdentry->d_sb->s_type != &cgroup_fs_type || !d_is_reg(cdentry)) {
5171 		ret = -EINVAL;
5172 		goto out_put_cfile;
5173 	}
5174 
5175 	/*
5176 	 * Determine the event callbacks and set them in @event.  This used
5177 	 * to be done via struct cftype but cgroup core no longer knows
5178 	 * about these events.  The following is crude but the whole thing
5179 	 * is for compatibility anyway.
5180 	 *
5181 	 * DO NOT ADD NEW FILES.
5182 	 */
5183 	name = cdentry->d_name.name;
5184 
5185 	if (!strcmp(name, "memory.usage_in_bytes")) {
5186 		event->register_event = mem_cgroup_usage_register_event;
5187 		event->unregister_event = mem_cgroup_usage_unregister_event;
5188 	} else if (!strcmp(name, "memory.oom_control")) {
5189 		event->register_event = mem_cgroup_oom_register_event;
5190 		event->unregister_event = mem_cgroup_oom_unregister_event;
5191 	} else if (!strcmp(name, "memory.pressure_level")) {
5192 		event->register_event = vmpressure_register_event;
5193 		event->unregister_event = vmpressure_unregister_event;
5194 	} else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
5195 		event->register_event = memsw_cgroup_usage_register_event;
5196 		event->unregister_event = memsw_cgroup_usage_unregister_event;
5197 	} else {
5198 		ret = -EINVAL;
5199 		goto out_put_cfile;
5200 	}
5201 
5202 	/*
5203 	 * Verify @cfile should belong to @css.  Also, remaining events are
5204 	 * automatically removed on cgroup destruction but the removal is
5205 	 * asynchronous, so take an extra ref on @css.
5206 	 */
5207 	cfile_css = css_tryget_online_from_dir(cdentry->d_parent,
5208 					       &memory_cgrp_subsys);
5209 	ret = -EINVAL;
5210 	if (IS_ERR(cfile_css))
5211 		goto out_put_cfile;
5212 	if (cfile_css != css) {
5213 		css_put(cfile_css);
5214 		goto out_put_cfile;
5215 	}
5216 
5217 	ret = event->register_event(memcg, event->eventfd, buf);
5218 	if (ret)
5219 		goto out_put_css;
5220 
5221 	vfs_poll(efile.file, &event->pt);
5222 
5223 	spin_lock_irq(&memcg->event_list_lock);
5224 	list_add(&event->list, &memcg->event_list);
5225 	spin_unlock_irq(&memcg->event_list_lock);
5226 
5227 	fdput(cfile);
5228 	fdput(efile);
5229 
5230 	return nbytes;
5231 
5232 out_put_css:
5233 	css_put(css);
5234 out_put_cfile:
5235 	fdput(cfile);
5236 out_put_eventfd:
5237 	eventfd_ctx_put(event->eventfd);
5238 out_put_efile:
5239 	fdput(efile);
5240 out_kfree:
5241 	kfree(event);
5242 
5243 	return ret;
5244 }
5245 
5246 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_SLUB_DEBUG)
5247 static int mem_cgroup_slab_show(struct seq_file *m, void *p)
5248 {
5249 	/*
5250 	 * Deprecated.
5251 	 * Please, take a look at tools/cgroup/memcg_slabinfo.py .
5252 	 */
5253 	return 0;
5254 }
5255 #endif
5256 
5257 static int memory_stat_show(struct seq_file *m, void *v);
5258 
5259 static struct cftype mem_cgroup_legacy_files[] = {
5260 	{
5261 		.name = "usage_in_bytes",
5262 		.private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
5263 		.read_u64 = mem_cgroup_read_u64,
5264 	},
5265 	{
5266 		.name = "max_usage_in_bytes",
5267 		.private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
5268 		.write = mem_cgroup_reset,
5269 		.read_u64 = mem_cgroup_read_u64,
5270 	},
5271 	{
5272 		.name = "limit_in_bytes",
5273 		.private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
5274 		.write = mem_cgroup_write,
5275 		.read_u64 = mem_cgroup_read_u64,
5276 	},
5277 	{
5278 		.name = "soft_limit_in_bytes",
5279 		.private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
5280 		.write = mem_cgroup_write,
5281 		.read_u64 = mem_cgroup_read_u64,
5282 	},
5283 	{
5284 		.name = "failcnt",
5285 		.private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
5286 		.write = mem_cgroup_reset,
5287 		.read_u64 = mem_cgroup_read_u64,
5288 	},
5289 	{
5290 		.name = "stat",
5291 		.seq_show = memory_stat_show,
5292 	},
5293 	{
5294 		.name = "force_empty",
5295 		.write = mem_cgroup_force_empty_write,
5296 	},
5297 	{
5298 		.name = "use_hierarchy",
5299 		.write_u64 = mem_cgroup_hierarchy_write,
5300 		.read_u64 = mem_cgroup_hierarchy_read,
5301 	},
5302 	{
5303 		.name = "cgroup.event_control",		/* XXX: for compat */
5304 		.write = memcg_write_event_control,
5305 		.flags = CFTYPE_NO_PREFIX | CFTYPE_WORLD_WRITABLE,
5306 	},
5307 	{
5308 		.name = "swappiness",
5309 		.read_u64 = mem_cgroup_swappiness_read,
5310 		.write_u64 = mem_cgroup_swappiness_write,
5311 	},
5312 	{
5313 		.name = "move_charge_at_immigrate",
5314 		.read_u64 = mem_cgroup_move_charge_read,
5315 		.write_u64 = mem_cgroup_move_charge_write,
5316 	},
5317 	{
5318 		.name = "oom_control",
5319 		.seq_show = mem_cgroup_oom_control_read,
5320 		.write_u64 = mem_cgroup_oom_control_write,
5321 	},
5322 	{
5323 		.name = "pressure_level",
5324 		.seq_show = mem_cgroup_dummy_seq_show,
5325 	},
5326 #ifdef CONFIG_NUMA
5327 	{
5328 		.name = "numa_stat",
5329 		.seq_show = memcg_numa_stat_show,
5330 	},
5331 #endif
5332 	{
5333 		.name = "kmem.limit_in_bytes",
5334 		.private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
5335 		.write = mem_cgroup_write,
5336 		.read_u64 = mem_cgroup_read_u64,
5337 	},
5338 	{
5339 		.name = "kmem.usage_in_bytes",
5340 		.private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
5341 		.read_u64 = mem_cgroup_read_u64,
5342 	},
5343 	{
5344 		.name = "kmem.failcnt",
5345 		.private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
5346 		.write = mem_cgroup_reset,
5347 		.read_u64 = mem_cgroup_read_u64,
5348 	},
5349 	{
5350 		.name = "kmem.max_usage_in_bytes",
5351 		.private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
5352 		.write = mem_cgroup_reset,
5353 		.read_u64 = mem_cgroup_read_u64,
5354 	},
5355 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_SLUB_DEBUG)
5356 	{
5357 		.name = "kmem.slabinfo",
5358 		.seq_show = mem_cgroup_slab_show,
5359 	},
5360 #endif
5361 	{
5362 		.name = "kmem.tcp.limit_in_bytes",
5363 		.private = MEMFILE_PRIVATE(_TCP, RES_LIMIT),
5364 		.write = mem_cgroup_write,
5365 		.read_u64 = mem_cgroup_read_u64,
5366 	},
5367 	{
5368 		.name = "kmem.tcp.usage_in_bytes",
5369 		.private = MEMFILE_PRIVATE(_TCP, RES_USAGE),
5370 		.read_u64 = mem_cgroup_read_u64,
5371 	},
5372 	{
5373 		.name = "kmem.tcp.failcnt",
5374 		.private = MEMFILE_PRIVATE(_TCP, RES_FAILCNT),
5375 		.write = mem_cgroup_reset,
5376 		.read_u64 = mem_cgroup_read_u64,
5377 	},
5378 	{
5379 		.name = "kmem.tcp.max_usage_in_bytes",
5380 		.private = MEMFILE_PRIVATE(_TCP, RES_MAX_USAGE),
5381 		.write = mem_cgroup_reset,
5382 		.read_u64 = mem_cgroup_read_u64,
5383 	},
5384 	{ },	/* terminate */
5385 };
5386 
5387 /*
5388  * Private memory cgroup IDR
5389  *
5390  * Swap-out records and page cache shadow entries need to store memcg
5391  * references in constrained space, so we maintain an ID space that is
5392  * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of
5393  * memory-controlled cgroups to 64k.
5394  *
5395  * However, there usually are many references to the offline CSS after
5396  * the cgroup has been destroyed, such as page cache or reclaimable
5397  * slab objects, that don't need to hang on to the ID. We want to keep
5398  * those dead CSS from occupying IDs, or we might quickly exhaust the
5399  * relatively small ID space and prevent the creation of new cgroups
5400  * even when there are much fewer than 64k cgroups - possibly none.
5401  *
5402  * Maintain a private 16-bit ID space for memcg, and allow the ID to
5403  * be freed and recycled when it's no longer needed, which is usually
5404  * when the CSS is offlined.
5405  *
5406  * The only exception to that are records of swapped out tmpfs/shmem
5407  * pages that need to be attributed to live ancestors on swapin. But
5408  * those references are manageable from userspace.
5409  */
5410 
5411 #define MEM_CGROUP_ID_MAX	((1UL << MEM_CGROUP_ID_SHIFT) - 1)
5412 static DEFINE_IDR(mem_cgroup_idr);
5413 
5414 static void mem_cgroup_id_remove(struct mem_cgroup *memcg)
5415 {
5416 	if (memcg->id.id > 0) {
5417 		idr_remove(&mem_cgroup_idr, memcg->id.id);
5418 		memcg->id.id = 0;
5419 	}
5420 }
5421 
5422 static void __maybe_unused mem_cgroup_id_get_many(struct mem_cgroup *memcg,
5423 						  unsigned int n)
5424 {
5425 	refcount_add(n, &memcg->id.ref);
5426 }
5427 
5428 static void mem_cgroup_id_put_many(struct mem_cgroup *memcg, unsigned int n)
5429 {
5430 	if (refcount_sub_and_test(n, &memcg->id.ref)) {
5431 		mem_cgroup_id_remove(memcg);
5432 
5433 		/* Memcg ID pins CSS */
5434 		css_put(&memcg->css);
5435 	}
5436 }
5437 
5438 static inline void mem_cgroup_id_put(struct mem_cgroup *memcg)
5439 {
5440 	mem_cgroup_id_put_many(memcg, 1);
5441 }
5442 
5443 /**
5444  * mem_cgroup_from_id - look up a memcg from a memcg id
5445  * @id: the memcg id to look up
5446  *
5447  * Caller must hold rcu_read_lock().
5448  */
5449 struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
5450 {
5451 	WARN_ON_ONCE(!rcu_read_lock_held());
5452 	return idr_find(&mem_cgroup_idr, id);
5453 }
5454 
5455 #ifdef CONFIG_SHRINKER_DEBUG
5456 struct mem_cgroup *mem_cgroup_get_from_ino(unsigned long ino)
5457 {
5458 	struct cgroup *cgrp;
5459 	struct cgroup_subsys_state *css;
5460 	struct mem_cgroup *memcg;
5461 
5462 	cgrp = cgroup_get_from_id(ino);
5463 	if (IS_ERR(cgrp))
5464 		return ERR_CAST(cgrp);
5465 
5466 	css = cgroup_get_e_css(cgrp, &memory_cgrp_subsys);
5467 	if (css)
5468 		memcg = container_of(css, struct mem_cgroup, css);
5469 	else
5470 		memcg = ERR_PTR(-ENOENT);
5471 
5472 	cgroup_put(cgrp);
5473 
5474 	return memcg;
5475 }
5476 #endif
5477 
5478 static int alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5479 {
5480 	struct mem_cgroup_per_node *pn;
5481 
5482 	pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, node);
5483 	if (!pn)
5484 		return 1;
5485 
5486 	pn->lruvec_stats_percpu = alloc_percpu_gfp(struct lruvec_stats_percpu,
5487 						   GFP_KERNEL_ACCOUNT);
5488 	if (!pn->lruvec_stats_percpu) {
5489 		kfree(pn);
5490 		return 1;
5491 	}
5492 
5493 	lruvec_init(&pn->lruvec);
5494 	pn->memcg = memcg;
5495 
5496 	memcg->nodeinfo[node] = pn;
5497 	return 0;
5498 }
5499 
5500 static void free_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5501 {
5502 	struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
5503 
5504 	if (!pn)
5505 		return;
5506 
5507 	free_percpu(pn->lruvec_stats_percpu);
5508 	kfree(pn);
5509 }
5510 
5511 static void __mem_cgroup_free(struct mem_cgroup *memcg)
5512 {
5513 	int node;
5514 
5515 	obj_cgroup_put(memcg->orig_objcg);
5516 
5517 	for_each_node(node)
5518 		free_mem_cgroup_per_node_info(memcg, node);
5519 	kfree(memcg->vmstats);
5520 	free_percpu(memcg->vmstats_percpu);
5521 	kfree(memcg);
5522 }
5523 
5524 static void mem_cgroup_free(struct mem_cgroup *memcg)
5525 {
5526 	lru_gen_exit_memcg(memcg);
5527 	memcg_wb_domain_exit(memcg);
5528 	__mem_cgroup_free(memcg);
5529 }
5530 
5531 static struct mem_cgroup *mem_cgroup_alloc(struct mem_cgroup *parent)
5532 {
5533 	struct memcg_vmstats_percpu *statc, *pstatc;
5534 	struct mem_cgroup *memcg;
5535 	int node, cpu;
5536 	int __maybe_unused i;
5537 	long error = -ENOMEM;
5538 
5539 	memcg = kzalloc(struct_size(memcg, nodeinfo, nr_node_ids), GFP_KERNEL);
5540 	if (!memcg)
5541 		return ERR_PTR(error);
5542 
5543 	memcg->id.id = idr_alloc(&mem_cgroup_idr, NULL,
5544 				 1, MEM_CGROUP_ID_MAX + 1, GFP_KERNEL);
5545 	if (memcg->id.id < 0) {
5546 		error = memcg->id.id;
5547 		goto fail;
5548 	}
5549 
5550 	memcg->vmstats = kzalloc(sizeof(struct memcg_vmstats), GFP_KERNEL);
5551 	if (!memcg->vmstats)
5552 		goto fail;
5553 
5554 	memcg->vmstats_percpu = alloc_percpu_gfp(struct memcg_vmstats_percpu,
5555 						 GFP_KERNEL_ACCOUNT);
5556 	if (!memcg->vmstats_percpu)
5557 		goto fail;
5558 
5559 	for_each_possible_cpu(cpu) {
5560 		if (parent)
5561 			pstatc = per_cpu_ptr(parent->vmstats_percpu, cpu);
5562 		statc = per_cpu_ptr(memcg->vmstats_percpu, cpu);
5563 		statc->parent = parent ? pstatc : NULL;
5564 		statc->vmstats = memcg->vmstats;
5565 	}
5566 
5567 	for_each_node(node)
5568 		if (alloc_mem_cgroup_per_node_info(memcg, node))
5569 			goto fail;
5570 
5571 	if (memcg_wb_domain_init(memcg, GFP_KERNEL))
5572 		goto fail;
5573 
5574 	INIT_WORK(&memcg->high_work, high_work_func);
5575 	INIT_LIST_HEAD(&memcg->oom_notify);
5576 	mutex_init(&memcg->thresholds_lock);
5577 	spin_lock_init(&memcg->move_lock);
5578 	vmpressure_init(&memcg->vmpressure);
5579 	INIT_LIST_HEAD(&memcg->event_list);
5580 	spin_lock_init(&memcg->event_list_lock);
5581 	memcg->socket_pressure = jiffies;
5582 #ifdef CONFIG_MEMCG_KMEM
5583 	memcg->kmemcg_id = -1;
5584 	INIT_LIST_HEAD(&memcg->objcg_list);
5585 #endif
5586 #ifdef CONFIG_CGROUP_WRITEBACK
5587 	INIT_LIST_HEAD(&memcg->cgwb_list);
5588 	for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5589 		memcg->cgwb_frn[i].done =
5590 			__WB_COMPLETION_INIT(&memcg_cgwb_frn_waitq);
5591 #endif
5592 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5593 	spin_lock_init(&memcg->deferred_split_queue.split_queue_lock);
5594 	INIT_LIST_HEAD(&memcg->deferred_split_queue.split_queue);
5595 	memcg->deferred_split_queue.split_queue_len = 0;
5596 #endif
5597 	lru_gen_init_memcg(memcg);
5598 	return memcg;
5599 fail:
5600 	mem_cgroup_id_remove(memcg);
5601 	__mem_cgroup_free(memcg);
5602 	return ERR_PTR(error);
5603 }
5604 
5605 static struct cgroup_subsys_state * __ref
5606 mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
5607 {
5608 	struct mem_cgroup *parent = mem_cgroup_from_css(parent_css);
5609 	struct mem_cgroup *memcg, *old_memcg;
5610 
5611 	old_memcg = set_active_memcg(parent);
5612 	memcg = mem_cgroup_alloc(parent);
5613 	set_active_memcg(old_memcg);
5614 	if (IS_ERR(memcg))
5615 		return ERR_CAST(memcg);
5616 
5617 	page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
5618 	WRITE_ONCE(memcg->soft_limit, PAGE_COUNTER_MAX);
5619 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
5620 	memcg->zswap_max = PAGE_COUNTER_MAX;
5621 	WRITE_ONCE(memcg->zswap_writeback,
5622 		!parent || READ_ONCE(parent->zswap_writeback));
5623 #endif
5624 	page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
5625 	if (parent) {
5626 		WRITE_ONCE(memcg->swappiness, mem_cgroup_swappiness(parent));
5627 		WRITE_ONCE(memcg->oom_kill_disable, READ_ONCE(parent->oom_kill_disable));
5628 
5629 		page_counter_init(&memcg->memory, &parent->memory);
5630 		page_counter_init(&memcg->swap, &parent->swap);
5631 		page_counter_init(&memcg->kmem, &parent->kmem);
5632 		page_counter_init(&memcg->tcpmem, &parent->tcpmem);
5633 	} else {
5634 		init_memcg_events();
5635 		page_counter_init(&memcg->memory, NULL);
5636 		page_counter_init(&memcg->swap, NULL);
5637 		page_counter_init(&memcg->kmem, NULL);
5638 		page_counter_init(&memcg->tcpmem, NULL);
5639 
5640 		root_mem_cgroup = memcg;
5641 		return &memcg->css;
5642 	}
5643 
5644 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5645 		static_branch_inc(&memcg_sockets_enabled_key);
5646 
5647 #if defined(CONFIG_MEMCG_KMEM)
5648 	if (!cgroup_memory_nobpf)
5649 		static_branch_inc(&memcg_bpf_enabled_key);
5650 #endif
5651 
5652 	return &memcg->css;
5653 }
5654 
5655 static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
5656 {
5657 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5658 
5659 	if (memcg_online_kmem(memcg))
5660 		goto remove_id;
5661 
5662 	/*
5663 	 * A memcg must be visible for expand_shrinker_info()
5664 	 * by the time the maps are allocated. So, we allocate maps
5665 	 * here, when for_each_mem_cgroup() can't skip it.
5666 	 */
5667 	if (alloc_shrinker_info(memcg))
5668 		goto offline_kmem;
5669 
5670 	if (unlikely(mem_cgroup_is_root(memcg)) && !mem_cgroup_disabled())
5671 		queue_delayed_work(system_unbound_wq, &stats_flush_dwork,
5672 				   FLUSH_TIME);
5673 	lru_gen_online_memcg(memcg);
5674 
5675 	/* Online state pins memcg ID, memcg ID pins CSS */
5676 	refcount_set(&memcg->id.ref, 1);
5677 	css_get(css);
5678 
5679 	/*
5680 	 * Ensure mem_cgroup_from_id() works once we're fully online.
5681 	 *
5682 	 * We could do this earlier and require callers to filter with
5683 	 * css_tryget_online(). But right now there are no users that
5684 	 * need earlier access, and the workingset code relies on the
5685 	 * cgroup tree linkage (mem_cgroup_get_nr_swap_pages()). So
5686 	 * publish it here at the end of onlining. This matches the
5687 	 * regular ID destruction during offlining.
5688 	 */
5689 	idr_replace(&mem_cgroup_idr, memcg, memcg->id.id);
5690 
5691 	return 0;
5692 offline_kmem:
5693 	memcg_offline_kmem(memcg);
5694 remove_id:
5695 	mem_cgroup_id_remove(memcg);
5696 	return -ENOMEM;
5697 }
5698 
5699 static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
5700 {
5701 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5702 	struct mem_cgroup_event *event, *tmp;
5703 
5704 	/*
5705 	 * Unregister events and notify userspace.
5706 	 * Notify userspace about cgroup removing only after rmdir of cgroup
5707 	 * directory to avoid race between userspace and kernelspace.
5708 	 */
5709 	spin_lock_irq(&memcg->event_list_lock);
5710 	list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
5711 		list_del_init(&event->list);
5712 		schedule_work(&event->remove);
5713 	}
5714 	spin_unlock_irq(&memcg->event_list_lock);
5715 
5716 	page_counter_set_min(&memcg->memory, 0);
5717 	page_counter_set_low(&memcg->memory, 0);
5718 
5719 	zswap_memcg_offline_cleanup(memcg);
5720 
5721 	memcg_offline_kmem(memcg);
5722 	reparent_shrinker_deferred(memcg);
5723 	wb_memcg_offline(memcg);
5724 	lru_gen_offline_memcg(memcg);
5725 
5726 	drain_all_stock(memcg);
5727 
5728 	mem_cgroup_id_put(memcg);
5729 }
5730 
5731 static void mem_cgroup_css_released(struct cgroup_subsys_state *css)
5732 {
5733 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5734 
5735 	invalidate_reclaim_iterators(memcg);
5736 	lru_gen_release_memcg(memcg);
5737 }
5738 
5739 static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
5740 {
5741 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5742 	int __maybe_unused i;
5743 
5744 #ifdef CONFIG_CGROUP_WRITEBACK
5745 	for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5746 		wb_wait_for_completion(&memcg->cgwb_frn[i].done);
5747 #endif
5748 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5749 		static_branch_dec(&memcg_sockets_enabled_key);
5750 
5751 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg->tcpmem_active)
5752 		static_branch_dec(&memcg_sockets_enabled_key);
5753 
5754 #if defined(CONFIG_MEMCG_KMEM)
5755 	if (!cgroup_memory_nobpf)
5756 		static_branch_dec(&memcg_bpf_enabled_key);
5757 #endif
5758 
5759 	vmpressure_cleanup(&memcg->vmpressure);
5760 	cancel_work_sync(&memcg->high_work);
5761 	mem_cgroup_remove_from_trees(memcg);
5762 	free_shrinker_info(memcg);
5763 	mem_cgroup_free(memcg);
5764 }
5765 
5766 /**
5767  * mem_cgroup_css_reset - reset the states of a mem_cgroup
5768  * @css: the target css
5769  *
5770  * Reset the states of the mem_cgroup associated with @css.  This is
5771  * invoked when the userland requests disabling on the default hierarchy
5772  * but the memcg is pinned through dependency.  The memcg should stop
5773  * applying policies and should revert to the vanilla state as it may be
5774  * made visible again.
5775  *
5776  * The current implementation only resets the essential configurations.
5777  * This needs to be expanded to cover all the visible parts.
5778  */
5779 static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
5780 {
5781 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5782 
5783 	page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX);
5784 	page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX);
5785 	page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX);
5786 	page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX);
5787 	page_counter_set_min(&memcg->memory, 0);
5788 	page_counter_set_low(&memcg->memory, 0);
5789 	page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
5790 	WRITE_ONCE(memcg->soft_limit, PAGE_COUNTER_MAX);
5791 	page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
5792 	memcg_wb_domain_size_changed(memcg);
5793 }
5794 
5795 static void mem_cgroup_css_rstat_flush(struct cgroup_subsys_state *css, int cpu)
5796 {
5797 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5798 	struct mem_cgroup *parent = parent_mem_cgroup(memcg);
5799 	struct memcg_vmstats_percpu *statc;
5800 	long delta, delta_cpu, v;
5801 	int i, nid;
5802 
5803 	statc = per_cpu_ptr(memcg->vmstats_percpu, cpu);
5804 
5805 	for (i = 0; i < MEMCG_NR_STAT; i++) {
5806 		/*
5807 		 * Collect the aggregated propagation counts of groups
5808 		 * below us. We're in a per-cpu loop here and this is
5809 		 * a global counter, so the first cycle will get them.
5810 		 */
5811 		delta = memcg->vmstats->state_pending[i];
5812 		if (delta)
5813 			memcg->vmstats->state_pending[i] = 0;
5814 
5815 		/* Add CPU changes on this level since the last flush */
5816 		delta_cpu = 0;
5817 		v = READ_ONCE(statc->state[i]);
5818 		if (v != statc->state_prev[i]) {
5819 			delta_cpu = v - statc->state_prev[i];
5820 			delta += delta_cpu;
5821 			statc->state_prev[i] = v;
5822 		}
5823 
5824 		/* Aggregate counts on this level and propagate upwards */
5825 		if (delta_cpu)
5826 			memcg->vmstats->state_local[i] += delta_cpu;
5827 
5828 		if (delta) {
5829 			memcg->vmstats->state[i] += delta;
5830 			if (parent)
5831 				parent->vmstats->state_pending[i] += delta;
5832 		}
5833 	}
5834 
5835 	for (i = 0; i < NR_MEMCG_EVENTS; i++) {
5836 		delta = memcg->vmstats->events_pending[i];
5837 		if (delta)
5838 			memcg->vmstats->events_pending[i] = 0;
5839 
5840 		delta_cpu = 0;
5841 		v = READ_ONCE(statc->events[i]);
5842 		if (v != statc->events_prev[i]) {
5843 			delta_cpu = v - statc->events_prev[i];
5844 			delta += delta_cpu;
5845 			statc->events_prev[i] = v;
5846 		}
5847 
5848 		if (delta_cpu)
5849 			memcg->vmstats->events_local[i] += delta_cpu;
5850 
5851 		if (delta) {
5852 			memcg->vmstats->events[i] += delta;
5853 			if (parent)
5854 				parent->vmstats->events_pending[i] += delta;
5855 		}
5856 	}
5857 
5858 	for_each_node_state(nid, N_MEMORY) {
5859 		struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid];
5860 		struct mem_cgroup_per_node *ppn = NULL;
5861 		struct lruvec_stats_percpu *lstatc;
5862 
5863 		if (parent)
5864 			ppn = parent->nodeinfo[nid];
5865 
5866 		lstatc = per_cpu_ptr(pn->lruvec_stats_percpu, cpu);
5867 
5868 		for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++) {
5869 			delta = pn->lruvec_stats.state_pending[i];
5870 			if (delta)
5871 				pn->lruvec_stats.state_pending[i] = 0;
5872 
5873 			delta_cpu = 0;
5874 			v = READ_ONCE(lstatc->state[i]);
5875 			if (v != lstatc->state_prev[i]) {
5876 				delta_cpu = v - lstatc->state_prev[i];
5877 				delta += delta_cpu;
5878 				lstatc->state_prev[i] = v;
5879 			}
5880 
5881 			if (delta_cpu)
5882 				pn->lruvec_stats.state_local[i] += delta_cpu;
5883 
5884 			if (delta) {
5885 				pn->lruvec_stats.state[i] += delta;
5886 				if (ppn)
5887 					ppn->lruvec_stats.state_pending[i] += delta;
5888 			}
5889 		}
5890 	}
5891 	statc->stats_updates = 0;
5892 	/* We are in a per-cpu loop here, only do the atomic write once */
5893 	if (atomic64_read(&memcg->vmstats->stats_updates))
5894 		atomic64_set(&memcg->vmstats->stats_updates, 0);
5895 }
5896 
5897 #ifdef CONFIG_MMU
5898 /* Handlers for move charge at task migration. */
5899 static int mem_cgroup_do_precharge(unsigned long count)
5900 {
5901 	int ret;
5902 
5903 	/* Try a single bulk charge without reclaim first, kswapd may wake */
5904 	ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_DIRECT_RECLAIM, count);
5905 	if (!ret) {
5906 		mc.precharge += count;
5907 		return ret;
5908 	}
5909 
5910 	/* Try charges one by one with reclaim, but do not retry */
5911 	while (count--) {
5912 		ret = try_charge(mc.to, GFP_KERNEL | __GFP_NORETRY, 1);
5913 		if (ret)
5914 			return ret;
5915 		mc.precharge++;
5916 		cond_resched();
5917 	}
5918 	return 0;
5919 }
5920 
5921 union mc_target {
5922 	struct folio	*folio;
5923 	swp_entry_t	ent;
5924 };
5925 
5926 enum mc_target_type {
5927 	MC_TARGET_NONE = 0,
5928 	MC_TARGET_PAGE,
5929 	MC_TARGET_SWAP,
5930 	MC_TARGET_DEVICE,
5931 };
5932 
5933 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5934 						unsigned long addr, pte_t ptent)
5935 {
5936 	struct page *page = vm_normal_page(vma, addr, ptent);
5937 
5938 	if (!page)
5939 		return NULL;
5940 	if (PageAnon(page)) {
5941 		if (!(mc.flags & MOVE_ANON))
5942 			return NULL;
5943 	} else {
5944 		if (!(mc.flags & MOVE_FILE))
5945 			return NULL;
5946 	}
5947 	get_page(page);
5948 
5949 	return page;
5950 }
5951 
5952 #if defined(CONFIG_SWAP) || defined(CONFIG_DEVICE_PRIVATE)
5953 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5954 			pte_t ptent, swp_entry_t *entry)
5955 {
5956 	struct page *page = NULL;
5957 	swp_entry_t ent = pte_to_swp_entry(ptent);
5958 
5959 	if (!(mc.flags & MOVE_ANON))
5960 		return NULL;
5961 
5962 	/*
5963 	 * Handle device private pages that are not accessible by the CPU, but
5964 	 * stored as special swap entries in the page table.
5965 	 */
5966 	if (is_device_private_entry(ent)) {
5967 		page = pfn_swap_entry_to_page(ent);
5968 		if (!get_page_unless_zero(page))
5969 			return NULL;
5970 		return page;
5971 	}
5972 
5973 	if (non_swap_entry(ent))
5974 		return NULL;
5975 
5976 	/*
5977 	 * Because swap_cache_get_folio() updates some statistics counter,
5978 	 * we call find_get_page() with swapper_space directly.
5979 	 */
5980 	page = find_get_page(swap_address_space(ent), swp_offset(ent));
5981 	entry->val = ent.val;
5982 
5983 	return page;
5984 }
5985 #else
5986 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5987 			pte_t ptent, swp_entry_t *entry)
5988 {
5989 	return NULL;
5990 }
5991 #endif
5992 
5993 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5994 			unsigned long addr, pte_t ptent)
5995 {
5996 	unsigned long index;
5997 	struct folio *folio;
5998 
5999 	if (!vma->vm_file) /* anonymous vma */
6000 		return NULL;
6001 	if (!(mc.flags & MOVE_FILE))
6002 		return NULL;
6003 
6004 	/* folio is moved even if it's not RSS of this task(page-faulted). */
6005 	/* shmem/tmpfs may report page out on swap: account for that too. */
6006 	index = linear_page_index(vma, addr);
6007 	folio = filemap_get_incore_folio(vma->vm_file->f_mapping, index);
6008 	if (IS_ERR(folio))
6009 		return NULL;
6010 	return folio_file_page(folio, index);
6011 }
6012 
6013 /**
6014  * mem_cgroup_move_account - move account of the folio
6015  * @folio: The folio.
6016  * @compound: charge the page as compound or small page
6017  * @from: mem_cgroup which the folio is moved from.
6018  * @to:	mem_cgroup which the folio is moved to. @from != @to.
6019  *
6020  * The folio must be locked and not on the LRU.
6021  *
6022  * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
6023  * from old cgroup.
6024  */
6025 static int mem_cgroup_move_account(struct folio *folio,
6026 				   bool compound,
6027 				   struct mem_cgroup *from,
6028 				   struct mem_cgroup *to)
6029 {
6030 	struct lruvec *from_vec, *to_vec;
6031 	struct pglist_data *pgdat;
6032 	unsigned int nr_pages = compound ? folio_nr_pages(folio) : 1;
6033 	int nid, ret;
6034 
6035 	VM_BUG_ON(from == to);
6036 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
6037 	VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
6038 	VM_BUG_ON(compound && !folio_test_large(folio));
6039 
6040 	ret = -EINVAL;
6041 	if (folio_memcg(folio) != from)
6042 		goto out;
6043 
6044 	pgdat = folio_pgdat(folio);
6045 	from_vec = mem_cgroup_lruvec(from, pgdat);
6046 	to_vec = mem_cgroup_lruvec(to, pgdat);
6047 
6048 	folio_memcg_lock(folio);
6049 
6050 	if (folio_test_anon(folio)) {
6051 		if (folio_mapped(folio)) {
6052 			__mod_lruvec_state(from_vec, NR_ANON_MAPPED, -nr_pages);
6053 			__mod_lruvec_state(to_vec, NR_ANON_MAPPED, nr_pages);
6054 			if (folio_test_pmd_mappable(folio)) {
6055 				__mod_lruvec_state(from_vec, NR_ANON_THPS,
6056 						   -nr_pages);
6057 				__mod_lruvec_state(to_vec, NR_ANON_THPS,
6058 						   nr_pages);
6059 			}
6060 		}
6061 	} else {
6062 		__mod_lruvec_state(from_vec, NR_FILE_PAGES, -nr_pages);
6063 		__mod_lruvec_state(to_vec, NR_FILE_PAGES, nr_pages);
6064 
6065 		if (folio_test_swapbacked(folio)) {
6066 			__mod_lruvec_state(from_vec, NR_SHMEM, -nr_pages);
6067 			__mod_lruvec_state(to_vec, NR_SHMEM, nr_pages);
6068 		}
6069 
6070 		if (folio_mapped(folio)) {
6071 			__mod_lruvec_state(from_vec, NR_FILE_MAPPED, -nr_pages);
6072 			__mod_lruvec_state(to_vec, NR_FILE_MAPPED, nr_pages);
6073 		}
6074 
6075 		if (folio_test_dirty(folio)) {
6076 			struct address_space *mapping = folio_mapping(folio);
6077 
6078 			if (mapping_can_writeback(mapping)) {
6079 				__mod_lruvec_state(from_vec, NR_FILE_DIRTY,
6080 						   -nr_pages);
6081 				__mod_lruvec_state(to_vec, NR_FILE_DIRTY,
6082 						   nr_pages);
6083 			}
6084 		}
6085 	}
6086 
6087 #ifdef CONFIG_SWAP
6088 	if (folio_test_swapcache(folio)) {
6089 		__mod_lruvec_state(from_vec, NR_SWAPCACHE, -nr_pages);
6090 		__mod_lruvec_state(to_vec, NR_SWAPCACHE, nr_pages);
6091 	}
6092 #endif
6093 	if (folio_test_writeback(folio)) {
6094 		__mod_lruvec_state(from_vec, NR_WRITEBACK, -nr_pages);
6095 		__mod_lruvec_state(to_vec, NR_WRITEBACK, nr_pages);
6096 	}
6097 
6098 	/*
6099 	 * All state has been migrated, let's switch to the new memcg.
6100 	 *
6101 	 * It is safe to change page's memcg here because the page
6102 	 * is referenced, charged, isolated, and locked: we can't race
6103 	 * with (un)charging, migration, LRU putback, or anything else
6104 	 * that would rely on a stable page's memory cgroup.
6105 	 *
6106 	 * Note that folio_memcg_lock is a memcg lock, not a page lock,
6107 	 * to save space. As soon as we switch page's memory cgroup to a
6108 	 * new memcg that isn't locked, the above state can change
6109 	 * concurrently again. Make sure we're truly done with it.
6110 	 */
6111 	smp_mb();
6112 
6113 	css_get(&to->css);
6114 	css_put(&from->css);
6115 
6116 	folio->memcg_data = (unsigned long)to;
6117 
6118 	__folio_memcg_unlock(from);
6119 
6120 	ret = 0;
6121 	nid = folio_nid(folio);
6122 
6123 	local_irq_disable();
6124 	mem_cgroup_charge_statistics(to, nr_pages);
6125 	memcg_check_events(to, nid);
6126 	mem_cgroup_charge_statistics(from, -nr_pages);
6127 	memcg_check_events(from, nid);
6128 	local_irq_enable();
6129 out:
6130 	return ret;
6131 }
6132 
6133 /**
6134  * get_mctgt_type - get target type of moving charge
6135  * @vma: the vma the pte to be checked belongs
6136  * @addr: the address corresponding to the pte to be checked
6137  * @ptent: the pte to be checked
6138  * @target: the pointer the target page or swap ent will be stored(can be NULL)
6139  *
6140  * Context: Called with pte lock held.
6141  * Return:
6142  * * MC_TARGET_NONE - If the pte is not a target for move charge.
6143  * * MC_TARGET_PAGE - If the page corresponding to this pte is a target for
6144  *   move charge. If @target is not NULL, the folio is stored in target->folio
6145  *   with extra refcnt taken (Caller should release it).
6146  * * MC_TARGET_SWAP - If the swap entry corresponding to this pte is a
6147  *   target for charge migration.  If @target is not NULL, the entry is
6148  *   stored in target->ent.
6149  * * MC_TARGET_DEVICE - Like MC_TARGET_PAGE but page is device memory and
6150  *   thus not on the lru.  For now such page is charged like a regular page
6151  *   would be as it is just special memory taking the place of a regular page.
6152  *   See Documentations/vm/hmm.txt and include/linux/hmm.h
6153  */
6154 static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
6155 		unsigned long addr, pte_t ptent, union mc_target *target)
6156 {
6157 	struct page *page = NULL;
6158 	struct folio *folio;
6159 	enum mc_target_type ret = MC_TARGET_NONE;
6160 	swp_entry_t ent = { .val = 0 };
6161 
6162 	if (pte_present(ptent))
6163 		page = mc_handle_present_pte(vma, addr, ptent);
6164 	else if (pte_none_mostly(ptent))
6165 		/*
6166 		 * PTE markers should be treated as a none pte here, separated
6167 		 * from other swap handling below.
6168 		 */
6169 		page = mc_handle_file_pte(vma, addr, ptent);
6170 	else if (is_swap_pte(ptent))
6171 		page = mc_handle_swap_pte(vma, ptent, &ent);
6172 
6173 	if (page)
6174 		folio = page_folio(page);
6175 	if (target && page) {
6176 		if (!folio_trylock(folio)) {
6177 			folio_put(folio);
6178 			return ret;
6179 		}
6180 		/*
6181 		 * page_mapped() must be stable during the move. This
6182 		 * pte is locked, so if it's present, the page cannot
6183 		 * become unmapped. If it isn't, we have only partial
6184 		 * control over the mapped state: the page lock will
6185 		 * prevent new faults against pagecache and swapcache,
6186 		 * so an unmapped page cannot become mapped. However,
6187 		 * if the page is already mapped elsewhere, it can
6188 		 * unmap, and there is nothing we can do about it.
6189 		 * Alas, skip moving the page in this case.
6190 		 */
6191 		if (!pte_present(ptent) && page_mapped(page)) {
6192 			folio_unlock(folio);
6193 			folio_put(folio);
6194 			return ret;
6195 		}
6196 	}
6197 
6198 	if (!page && !ent.val)
6199 		return ret;
6200 	if (page) {
6201 		/*
6202 		 * Do only loose check w/o serialization.
6203 		 * mem_cgroup_move_account() checks the page is valid or
6204 		 * not under LRU exclusion.
6205 		 */
6206 		if (folio_memcg(folio) == mc.from) {
6207 			ret = MC_TARGET_PAGE;
6208 			if (folio_is_device_private(folio) ||
6209 			    folio_is_device_coherent(folio))
6210 				ret = MC_TARGET_DEVICE;
6211 			if (target)
6212 				target->folio = folio;
6213 		}
6214 		if (!ret || !target) {
6215 			if (target)
6216 				folio_unlock(folio);
6217 			folio_put(folio);
6218 		}
6219 	}
6220 	/*
6221 	 * There is a swap entry and a page doesn't exist or isn't charged.
6222 	 * But we cannot move a tail-page in a THP.
6223 	 */
6224 	if (ent.val && !ret && (!page || !PageTransCompound(page)) &&
6225 	    mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
6226 		ret = MC_TARGET_SWAP;
6227 		if (target)
6228 			target->ent = ent;
6229 	}
6230 	return ret;
6231 }
6232 
6233 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
6234 /*
6235  * We don't consider PMD mapped swapping or file mapped pages because THP does
6236  * not support them for now.
6237  * Caller should make sure that pmd_trans_huge(pmd) is true.
6238  */
6239 static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
6240 		unsigned long addr, pmd_t pmd, union mc_target *target)
6241 {
6242 	struct page *page = NULL;
6243 	struct folio *folio;
6244 	enum mc_target_type ret = MC_TARGET_NONE;
6245 
6246 	if (unlikely(is_swap_pmd(pmd))) {
6247 		VM_BUG_ON(thp_migration_supported() &&
6248 				  !is_pmd_migration_entry(pmd));
6249 		return ret;
6250 	}
6251 	page = pmd_page(pmd);
6252 	VM_BUG_ON_PAGE(!page || !PageHead(page), page);
6253 	folio = page_folio(page);
6254 	if (!(mc.flags & MOVE_ANON))
6255 		return ret;
6256 	if (folio_memcg(folio) == mc.from) {
6257 		ret = MC_TARGET_PAGE;
6258 		if (target) {
6259 			folio_get(folio);
6260 			if (!folio_trylock(folio)) {
6261 				folio_put(folio);
6262 				return MC_TARGET_NONE;
6263 			}
6264 			target->folio = folio;
6265 		}
6266 	}
6267 	return ret;
6268 }
6269 #else
6270 static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
6271 		unsigned long addr, pmd_t pmd, union mc_target *target)
6272 {
6273 	return MC_TARGET_NONE;
6274 }
6275 #endif
6276 
6277 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
6278 					unsigned long addr, unsigned long end,
6279 					struct mm_walk *walk)
6280 {
6281 	struct vm_area_struct *vma = walk->vma;
6282 	pte_t *pte;
6283 	spinlock_t *ptl;
6284 
6285 	ptl = pmd_trans_huge_lock(pmd, vma);
6286 	if (ptl) {
6287 		/*
6288 		 * Note their can not be MC_TARGET_DEVICE for now as we do not
6289 		 * support transparent huge page with MEMORY_DEVICE_PRIVATE but
6290 		 * this might change.
6291 		 */
6292 		if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
6293 			mc.precharge += HPAGE_PMD_NR;
6294 		spin_unlock(ptl);
6295 		return 0;
6296 	}
6297 
6298 	pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6299 	if (!pte)
6300 		return 0;
6301 	for (; addr != end; pte++, addr += PAGE_SIZE)
6302 		if (get_mctgt_type(vma, addr, ptep_get(pte), NULL))
6303 			mc.precharge++;	/* increment precharge temporarily */
6304 	pte_unmap_unlock(pte - 1, ptl);
6305 	cond_resched();
6306 
6307 	return 0;
6308 }
6309 
6310 static const struct mm_walk_ops precharge_walk_ops = {
6311 	.pmd_entry	= mem_cgroup_count_precharge_pte_range,
6312 	.walk_lock	= PGWALK_RDLOCK,
6313 };
6314 
6315 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
6316 {
6317 	unsigned long precharge;
6318 
6319 	mmap_read_lock(mm);
6320 	walk_page_range(mm, 0, ULONG_MAX, &precharge_walk_ops, NULL);
6321 	mmap_read_unlock(mm);
6322 
6323 	precharge = mc.precharge;
6324 	mc.precharge = 0;
6325 
6326 	return precharge;
6327 }
6328 
6329 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
6330 {
6331 	unsigned long precharge = mem_cgroup_count_precharge(mm);
6332 
6333 	VM_BUG_ON(mc.moving_task);
6334 	mc.moving_task = current;
6335 	return mem_cgroup_do_precharge(precharge);
6336 }
6337 
6338 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
6339 static void __mem_cgroup_clear_mc(void)
6340 {
6341 	struct mem_cgroup *from = mc.from;
6342 	struct mem_cgroup *to = mc.to;
6343 
6344 	/* we must uncharge all the leftover precharges from mc.to */
6345 	if (mc.precharge) {
6346 		mem_cgroup_cancel_charge(mc.to, mc.precharge);
6347 		mc.precharge = 0;
6348 	}
6349 	/*
6350 	 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
6351 	 * we must uncharge here.
6352 	 */
6353 	if (mc.moved_charge) {
6354 		mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
6355 		mc.moved_charge = 0;
6356 	}
6357 	/* we must fixup refcnts and charges */
6358 	if (mc.moved_swap) {
6359 		/* uncharge swap account from the old cgroup */
6360 		if (!mem_cgroup_is_root(mc.from))
6361 			page_counter_uncharge(&mc.from->memsw, mc.moved_swap);
6362 
6363 		mem_cgroup_id_put_many(mc.from, mc.moved_swap);
6364 
6365 		/*
6366 		 * we charged both to->memory and to->memsw, so we
6367 		 * should uncharge to->memory.
6368 		 */
6369 		if (!mem_cgroup_is_root(mc.to))
6370 			page_counter_uncharge(&mc.to->memory, mc.moved_swap);
6371 
6372 		mc.moved_swap = 0;
6373 	}
6374 	memcg_oom_recover(from);
6375 	memcg_oom_recover(to);
6376 	wake_up_all(&mc.waitq);
6377 }
6378 
6379 static void mem_cgroup_clear_mc(void)
6380 {
6381 	struct mm_struct *mm = mc.mm;
6382 
6383 	/*
6384 	 * we must clear moving_task before waking up waiters at the end of
6385 	 * task migration.
6386 	 */
6387 	mc.moving_task = NULL;
6388 	__mem_cgroup_clear_mc();
6389 	spin_lock(&mc.lock);
6390 	mc.from = NULL;
6391 	mc.to = NULL;
6392 	mc.mm = NULL;
6393 	spin_unlock(&mc.lock);
6394 
6395 	mmput(mm);
6396 }
6397 
6398 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
6399 {
6400 	struct cgroup_subsys_state *css;
6401 	struct mem_cgroup *memcg = NULL; /* unneeded init to make gcc happy */
6402 	struct mem_cgroup *from;
6403 	struct task_struct *leader, *p;
6404 	struct mm_struct *mm;
6405 	unsigned long move_flags;
6406 	int ret = 0;
6407 
6408 	/* charge immigration isn't supported on the default hierarchy */
6409 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
6410 		return 0;
6411 
6412 	/*
6413 	 * Multi-process migrations only happen on the default hierarchy
6414 	 * where charge immigration is not used.  Perform charge
6415 	 * immigration if @tset contains a leader and whine if there are
6416 	 * multiple.
6417 	 */
6418 	p = NULL;
6419 	cgroup_taskset_for_each_leader(leader, css, tset) {
6420 		WARN_ON_ONCE(p);
6421 		p = leader;
6422 		memcg = mem_cgroup_from_css(css);
6423 	}
6424 	if (!p)
6425 		return 0;
6426 
6427 	/*
6428 	 * We are now committed to this value whatever it is. Changes in this
6429 	 * tunable will only affect upcoming migrations, not the current one.
6430 	 * So we need to save it, and keep it going.
6431 	 */
6432 	move_flags = READ_ONCE(memcg->move_charge_at_immigrate);
6433 	if (!move_flags)
6434 		return 0;
6435 
6436 	from = mem_cgroup_from_task(p);
6437 
6438 	VM_BUG_ON(from == memcg);
6439 
6440 	mm = get_task_mm(p);
6441 	if (!mm)
6442 		return 0;
6443 	/* We move charges only when we move a owner of the mm */
6444 	if (mm->owner == p) {
6445 		VM_BUG_ON(mc.from);
6446 		VM_BUG_ON(mc.to);
6447 		VM_BUG_ON(mc.precharge);
6448 		VM_BUG_ON(mc.moved_charge);
6449 		VM_BUG_ON(mc.moved_swap);
6450 
6451 		spin_lock(&mc.lock);
6452 		mc.mm = mm;
6453 		mc.from = from;
6454 		mc.to = memcg;
6455 		mc.flags = move_flags;
6456 		spin_unlock(&mc.lock);
6457 		/* We set mc.moving_task later */
6458 
6459 		ret = mem_cgroup_precharge_mc(mm);
6460 		if (ret)
6461 			mem_cgroup_clear_mc();
6462 	} else {
6463 		mmput(mm);
6464 	}
6465 	return ret;
6466 }
6467 
6468 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
6469 {
6470 	if (mc.to)
6471 		mem_cgroup_clear_mc();
6472 }
6473 
6474 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
6475 				unsigned long addr, unsigned long end,
6476 				struct mm_walk *walk)
6477 {
6478 	int ret = 0;
6479 	struct vm_area_struct *vma = walk->vma;
6480 	pte_t *pte;
6481 	spinlock_t *ptl;
6482 	enum mc_target_type target_type;
6483 	union mc_target target;
6484 	struct folio *folio;
6485 
6486 	ptl = pmd_trans_huge_lock(pmd, vma);
6487 	if (ptl) {
6488 		if (mc.precharge < HPAGE_PMD_NR) {
6489 			spin_unlock(ptl);
6490 			return 0;
6491 		}
6492 		target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
6493 		if (target_type == MC_TARGET_PAGE) {
6494 			folio = target.folio;
6495 			if (folio_isolate_lru(folio)) {
6496 				if (!mem_cgroup_move_account(folio, true,
6497 							     mc.from, mc.to)) {
6498 					mc.precharge -= HPAGE_PMD_NR;
6499 					mc.moved_charge += HPAGE_PMD_NR;
6500 				}
6501 				folio_putback_lru(folio);
6502 			}
6503 			folio_unlock(folio);
6504 			folio_put(folio);
6505 		} else if (target_type == MC_TARGET_DEVICE) {
6506 			folio = target.folio;
6507 			if (!mem_cgroup_move_account(folio, true,
6508 						     mc.from, mc.to)) {
6509 				mc.precharge -= HPAGE_PMD_NR;
6510 				mc.moved_charge += HPAGE_PMD_NR;
6511 			}
6512 			folio_unlock(folio);
6513 			folio_put(folio);
6514 		}
6515 		spin_unlock(ptl);
6516 		return 0;
6517 	}
6518 
6519 retry:
6520 	pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6521 	if (!pte)
6522 		return 0;
6523 	for (; addr != end; addr += PAGE_SIZE) {
6524 		pte_t ptent = ptep_get(pte++);
6525 		bool device = false;
6526 		swp_entry_t ent;
6527 
6528 		if (!mc.precharge)
6529 			break;
6530 
6531 		switch (get_mctgt_type(vma, addr, ptent, &target)) {
6532 		case MC_TARGET_DEVICE:
6533 			device = true;
6534 			fallthrough;
6535 		case MC_TARGET_PAGE:
6536 			folio = target.folio;
6537 			/*
6538 			 * We can have a part of the split pmd here. Moving it
6539 			 * can be done but it would be too convoluted so simply
6540 			 * ignore such a partial THP and keep it in original
6541 			 * memcg. There should be somebody mapping the head.
6542 			 */
6543 			if (folio_test_large(folio))
6544 				goto put;
6545 			if (!device && !folio_isolate_lru(folio))
6546 				goto put;
6547 			if (!mem_cgroup_move_account(folio, false,
6548 						mc.from, mc.to)) {
6549 				mc.precharge--;
6550 				/* we uncharge from mc.from later. */
6551 				mc.moved_charge++;
6552 			}
6553 			if (!device)
6554 				folio_putback_lru(folio);
6555 put:			/* get_mctgt_type() gets & locks the page */
6556 			folio_unlock(folio);
6557 			folio_put(folio);
6558 			break;
6559 		case MC_TARGET_SWAP:
6560 			ent = target.ent;
6561 			if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
6562 				mc.precharge--;
6563 				mem_cgroup_id_get_many(mc.to, 1);
6564 				/* we fixup other refcnts and charges later. */
6565 				mc.moved_swap++;
6566 			}
6567 			break;
6568 		default:
6569 			break;
6570 		}
6571 	}
6572 	pte_unmap_unlock(pte - 1, ptl);
6573 	cond_resched();
6574 
6575 	if (addr != end) {
6576 		/*
6577 		 * We have consumed all precharges we got in can_attach().
6578 		 * We try charge one by one, but don't do any additional
6579 		 * charges to mc.to if we have failed in charge once in attach()
6580 		 * phase.
6581 		 */
6582 		ret = mem_cgroup_do_precharge(1);
6583 		if (!ret)
6584 			goto retry;
6585 	}
6586 
6587 	return ret;
6588 }
6589 
6590 static const struct mm_walk_ops charge_walk_ops = {
6591 	.pmd_entry	= mem_cgroup_move_charge_pte_range,
6592 	.walk_lock	= PGWALK_RDLOCK,
6593 };
6594 
6595 static void mem_cgroup_move_charge(void)
6596 {
6597 	lru_add_drain_all();
6598 	/*
6599 	 * Signal folio_memcg_lock() to take the memcg's move_lock
6600 	 * while we're moving its pages to another memcg. Then wait
6601 	 * for already started RCU-only updates to finish.
6602 	 */
6603 	atomic_inc(&mc.from->moving_account);
6604 	synchronize_rcu();
6605 retry:
6606 	if (unlikely(!mmap_read_trylock(mc.mm))) {
6607 		/*
6608 		 * Someone who are holding the mmap_lock might be waiting in
6609 		 * waitq. So we cancel all extra charges, wake up all waiters,
6610 		 * and retry. Because we cancel precharges, we might not be able
6611 		 * to move enough charges, but moving charge is a best-effort
6612 		 * feature anyway, so it wouldn't be a big problem.
6613 		 */
6614 		__mem_cgroup_clear_mc();
6615 		cond_resched();
6616 		goto retry;
6617 	}
6618 	/*
6619 	 * When we have consumed all precharges and failed in doing
6620 	 * additional charge, the page walk just aborts.
6621 	 */
6622 	walk_page_range(mc.mm, 0, ULONG_MAX, &charge_walk_ops, NULL);
6623 	mmap_read_unlock(mc.mm);
6624 	atomic_dec(&mc.from->moving_account);
6625 }
6626 
6627 static void mem_cgroup_move_task(void)
6628 {
6629 	if (mc.to) {
6630 		mem_cgroup_move_charge();
6631 		mem_cgroup_clear_mc();
6632 	}
6633 }
6634 
6635 #else	/* !CONFIG_MMU */
6636 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
6637 {
6638 	return 0;
6639 }
6640 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
6641 {
6642 }
6643 static void mem_cgroup_move_task(void)
6644 {
6645 }
6646 #endif
6647 
6648 #ifdef CONFIG_MEMCG_KMEM
6649 static void mem_cgroup_fork(struct task_struct *task)
6650 {
6651 	/*
6652 	 * Set the update flag to cause task->objcg to be initialized lazily
6653 	 * on the first allocation. It can be done without any synchronization
6654 	 * because it's always performed on the current task, so does
6655 	 * current_objcg_update().
6656 	 */
6657 	task->objcg = (struct obj_cgroup *)CURRENT_OBJCG_UPDATE_FLAG;
6658 }
6659 
6660 static void mem_cgroup_exit(struct task_struct *task)
6661 {
6662 	struct obj_cgroup *objcg = task->objcg;
6663 
6664 	objcg = (struct obj_cgroup *)
6665 		((unsigned long)objcg & ~CURRENT_OBJCG_UPDATE_FLAG);
6666 	obj_cgroup_put(objcg);
6667 
6668 	/*
6669 	 * Some kernel allocations can happen after this point,
6670 	 * but let's ignore them. It can be done without any synchronization
6671 	 * because it's always performed on the current task, so does
6672 	 * current_objcg_update().
6673 	 */
6674 	task->objcg = NULL;
6675 }
6676 #endif
6677 
6678 #ifdef CONFIG_LRU_GEN
6679 static void mem_cgroup_lru_gen_attach(struct cgroup_taskset *tset)
6680 {
6681 	struct task_struct *task;
6682 	struct cgroup_subsys_state *css;
6683 
6684 	/* find the first leader if there is any */
6685 	cgroup_taskset_for_each_leader(task, css, tset)
6686 		break;
6687 
6688 	if (!task)
6689 		return;
6690 
6691 	task_lock(task);
6692 	if (task->mm && READ_ONCE(task->mm->owner) == task)
6693 		lru_gen_migrate_mm(task->mm);
6694 	task_unlock(task);
6695 }
6696 #else
6697 static void mem_cgroup_lru_gen_attach(struct cgroup_taskset *tset) {}
6698 #endif /* CONFIG_LRU_GEN */
6699 
6700 #ifdef CONFIG_MEMCG_KMEM
6701 static void mem_cgroup_kmem_attach(struct cgroup_taskset *tset)
6702 {
6703 	struct task_struct *task;
6704 	struct cgroup_subsys_state *css;
6705 
6706 	cgroup_taskset_for_each(task, css, tset) {
6707 		/* atomically set the update bit */
6708 		set_bit(CURRENT_OBJCG_UPDATE_BIT, (unsigned long *)&task->objcg);
6709 	}
6710 }
6711 #else
6712 static void mem_cgroup_kmem_attach(struct cgroup_taskset *tset) {}
6713 #endif /* CONFIG_MEMCG_KMEM */
6714 
6715 #if defined(CONFIG_LRU_GEN) || defined(CONFIG_MEMCG_KMEM)
6716 static void mem_cgroup_attach(struct cgroup_taskset *tset)
6717 {
6718 	mem_cgroup_lru_gen_attach(tset);
6719 	mem_cgroup_kmem_attach(tset);
6720 }
6721 #endif
6722 
6723 static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value)
6724 {
6725 	if (value == PAGE_COUNTER_MAX)
6726 		seq_puts(m, "max\n");
6727 	else
6728 		seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE);
6729 
6730 	return 0;
6731 }
6732 
6733 static u64 memory_current_read(struct cgroup_subsys_state *css,
6734 			       struct cftype *cft)
6735 {
6736 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6737 
6738 	return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
6739 }
6740 
6741 static u64 memory_peak_read(struct cgroup_subsys_state *css,
6742 			    struct cftype *cft)
6743 {
6744 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6745 
6746 	return (u64)memcg->memory.watermark * PAGE_SIZE;
6747 }
6748 
6749 static int memory_min_show(struct seq_file *m, void *v)
6750 {
6751 	return seq_puts_memcg_tunable(m,
6752 		READ_ONCE(mem_cgroup_from_seq(m)->memory.min));
6753 }
6754 
6755 static ssize_t memory_min_write(struct kernfs_open_file *of,
6756 				char *buf, size_t nbytes, loff_t off)
6757 {
6758 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6759 	unsigned long min;
6760 	int err;
6761 
6762 	buf = strstrip(buf);
6763 	err = page_counter_memparse(buf, "max", &min);
6764 	if (err)
6765 		return err;
6766 
6767 	page_counter_set_min(&memcg->memory, min);
6768 
6769 	return nbytes;
6770 }
6771 
6772 static int memory_low_show(struct seq_file *m, void *v)
6773 {
6774 	return seq_puts_memcg_tunable(m,
6775 		READ_ONCE(mem_cgroup_from_seq(m)->memory.low));
6776 }
6777 
6778 static ssize_t memory_low_write(struct kernfs_open_file *of,
6779 				char *buf, size_t nbytes, loff_t off)
6780 {
6781 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6782 	unsigned long low;
6783 	int err;
6784 
6785 	buf = strstrip(buf);
6786 	err = page_counter_memparse(buf, "max", &low);
6787 	if (err)
6788 		return err;
6789 
6790 	page_counter_set_low(&memcg->memory, low);
6791 
6792 	return nbytes;
6793 }
6794 
6795 static int memory_high_show(struct seq_file *m, void *v)
6796 {
6797 	return seq_puts_memcg_tunable(m,
6798 		READ_ONCE(mem_cgroup_from_seq(m)->memory.high));
6799 }
6800 
6801 static ssize_t memory_high_write(struct kernfs_open_file *of,
6802 				 char *buf, size_t nbytes, loff_t off)
6803 {
6804 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6805 	unsigned int nr_retries = MAX_RECLAIM_RETRIES;
6806 	bool drained = false;
6807 	unsigned long high;
6808 	int err;
6809 
6810 	buf = strstrip(buf);
6811 	err = page_counter_memparse(buf, "max", &high);
6812 	if (err)
6813 		return err;
6814 
6815 	page_counter_set_high(&memcg->memory, high);
6816 
6817 	for (;;) {
6818 		unsigned long nr_pages = page_counter_read(&memcg->memory);
6819 		unsigned long reclaimed;
6820 
6821 		if (nr_pages <= high)
6822 			break;
6823 
6824 		if (signal_pending(current))
6825 			break;
6826 
6827 		if (!drained) {
6828 			drain_all_stock(memcg);
6829 			drained = true;
6830 			continue;
6831 		}
6832 
6833 		reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages - high,
6834 					GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP);
6835 
6836 		if (!reclaimed && !nr_retries--)
6837 			break;
6838 	}
6839 
6840 	memcg_wb_domain_size_changed(memcg);
6841 	return nbytes;
6842 }
6843 
6844 static int memory_max_show(struct seq_file *m, void *v)
6845 {
6846 	return seq_puts_memcg_tunable(m,
6847 		READ_ONCE(mem_cgroup_from_seq(m)->memory.max));
6848 }
6849 
6850 static ssize_t memory_max_write(struct kernfs_open_file *of,
6851 				char *buf, size_t nbytes, loff_t off)
6852 {
6853 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6854 	unsigned int nr_reclaims = MAX_RECLAIM_RETRIES;
6855 	bool drained = false;
6856 	unsigned long max;
6857 	int err;
6858 
6859 	buf = strstrip(buf);
6860 	err = page_counter_memparse(buf, "max", &max);
6861 	if (err)
6862 		return err;
6863 
6864 	xchg(&memcg->memory.max, max);
6865 
6866 	for (;;) {
6867 		unsigned long nr_pages = page_counter_read(&memcg->memory);
6868 
6869 		if (nr_pages <= max)
6870 			break;
6871 
6872 		if (signal_pending(current))
6873 			break;
6874 
6875 		if (!drained) {
6876 			drain_all_stock(memcg);
6877 			drained = true;
6878 			continue;
6879 		}
6880 
6881 		if (nr_reclaims) {
6882 			if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,
6883 					GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP))
6884 				nr_reclaims--;
6885 			continue;
6886 		}
6887 
6888 		memcg_memory_event(memcg, MEMCG_OOM);
6889 		if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0))
6890 			break;
6891 	}
6892 
6893 	memcg_wb_domain_size_changed(memcg);
6894 	return nbytes;
6895 }
6896 
6897 /*
6898  * Note: don't forget to update the 'samples/cgroup/memcg_event_listener'
6899  * if any new events become available.
6900  */
6901 static void __memory_events_show(struct seq_file *m, atomic_long_t *events)
6902 {
6903 	seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW]));
6904 	seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH]));
6905 	seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX]));
6906 	seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM]));
6907 	seq_printf(m, "oom_kill %lu\n",
6908 		   atomic_long_read(&events[MEMCG_OOM_KILL]));
6909 	seq_printf(m, "oom_group_kill %lu\n",
6910 		   atomic_long_read(&events[MEMCG_OOM_GROUP_KILL]));
6911 }
6912 
6913 static int memory_events_show(struct seq_file *m, void *v)
6914 {
6915 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6916 
6917 	__memory_events_show(m, memcg->memory_events);
6918 	return 0;
6919 }
6920 
6921 static int memory_events_local_show(struct seq_file *m, void *v)
6922 {
6923 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6924 
6925 	__memory_events_show(m, memcg->memory_events_local);
6926 	return 0;
6927 }
6928 
6929 static int memory_stat_show(struct seq_file *m, void *v)
6930 {
6931 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6932 	char *buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
6933 	struct seq_buf s;
6934 
6935 	if (!buf)
6936 		return -ENOMEM;
6937 	seq_buf_init(&s, buf, PAGE_SIZE);
6938 	memory_stat_format(memcg, &s);
6939 	seq_puts(m, buf);
6940 	kfree(buf);
6941 	return 0;
6942 }
6943 
6944 #ifdef CONFIG_NUMA
6945 static inline unsigned long lruvec_page_state_output(struct lruvec *lruvec,
6946 						     int item)
6947 {
6948 	return lruvec_page_state(lruvec, item) *
6949 		memcg_page_state_output_unit(item);
6950 }
6951 
6952 static int memory_numa_stat_show(struct seq_file *m, void *v)
6953 {
6954 	int i;
6955 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6956 
6957 	mem_cgroup_flush_stats(memcg);
6958 
6959 	for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
6960 		int nid;
6961 
6962 		if (memory_stats[i].idx >= NR_VM_NODE_STAT_ITEMS)
6963 			continue;
6964 
6965 		seq_printf(m, "%s", memory_stats[i].name);
6966 		for_each_node_state(nid, N_MEMORY) {
6967 			u64 size;
6968 			struct lruvec *lruvec;
6969 
6970 			lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
6971 			size = lruvec_page_state_output(lruvec,
6972 							memory_stats[i].idx);
6973 			seq_printf(m, " N%d=%llu", nid, size);
6974 		}
6975 		seq_putc(m, '\n');
6976 	}
6977 
6978 	return 0;
6979 }
6980 #endif
6981 
6982 static int memory_oom_group_show(struct seq_file *m, void *v)
6983 {
6984 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6985 
6986 	seq_printf(m, "%d\n", READ_ONCE(memcg->oom_group));
6987 
6988 	return 0;
6989 }
6990 
6991 static ssize_t memory_oom_group_write(struct kernfs_open_file *of,
6992 				      char *buf, size_t nbytes, loff_t off)
6993 {
6994 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6995 	int ret, oom_group;
6996 
6997 	buf = strstrip(buf);
6998 	if (!buf)
6999 		return -EINVAL;
7000 
7001 	ret = kstrtoint(buf, 0, &oom_group);
7002 	if (ret)
7003 		return ret;
7004 
7005 	if (oom_group != 0 && oom_group != 1)
7006 		return -EINVAL;
7007 
7008 	WRITE_ONCE(memcg->oom_group, oom_group);
7009 
7010 	return nbytes;
7011 }
7012 
7013 static ssize_t memory_reclaim(struct kernfs_open_file *of, char *buf,
7014 			      size_t nbytes, loff_t off)
7015 {
7016 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7017 	unsigned int nr_retries = MAX_RECLAIM_RETRIES;
7018 	unsigned long nr_to_reclaim, nr_reclaimed = 0;
7019 	unsigned int reclaim_options;
7020 	int err;
7021 
7022 	buf = strstrip(buf);
7023 	err = page_counter_memparse(buf, "", &nr_to_reclaim);
7024 	if (err)
7025 		return err;
7026 
7027 	reclaim_options	= MEMCG_RECLAIM_MAY_SWAP | MEMCG_RECLAIM_PROACTIVE;
7028 	while (nr_reclaimed < nr_to_reclaim) {
7029 		/* Will converge on zero, but reclaim enforces a minimum */
7030 		unsigned long batch_size = (nr_to_reclaim - nr_reclaimed) / 4;
7031 		unsigned long reclaimed;
7032 
7033 		if (signal_pending(current))
7034 			return -EINTR;
7035 
7036 		/*
7037 		 * This is the final attempt, drain percpu lru caches in the
7038 		 * hope of introducing more evictable pages for
7039 		 * try_to_free_mem_cgroup_pages().
7040 		 */
7041 		if (!nr_retries)
7042 			lru_add_drain_all();
7043 
7044 		reclaimed = try_to_free_mem_cgroup_pages(memcg,
7045 					batch_size, GFP_KERNEL, reclaim_options);
7046 
7047 		if (!reclaimed && !nr_retries--)
7048 			return -EAGAIN;
7049 
7050 		nr_reclaimed += reclaimed;
7051 	}
7052 
7053 	return nbytes;
7054 }
7055 
7056 static struct cftype memory_files[] = {
7057 	{
7058 		.name = "current",
7059 		.flags = CFTYPE_NOT_ON_ROOT,
7060 		.read_u64 = memory_current_read,
7061 	},
7062 	{
7063 		.name = "peak",
7064 		.flags = CFTYPE_NOT_ON_ROOT,
7065 		.read_u64 = memory_peak_read,
7066 	},
7067 	{
7068 		.name = "min",
7069 		.flags = CFTYPE_NOT_ON_ROOT,
7070 		.seq_show = memory_min_show,
7071 		.write = memory_min_write,
7072 	},
7073 	{
7074 		.name = "low",
7075 		.flags = CFTYPE_NOT_ON_ROOT,
7076 		.seq_show = memory_low_show,
7077 		.write = memory_low_write,
7078 	},
7079 	{
7080 		.name = "high",
7081 		.flags = CFTYPE_NOT_ON_ROOT,
7082 		.seq_show = memory_high_show,
7083 		.write = memory_high_write,
7084 	},
7085 	{
7086 		.name = "max",
7087 		.flags = CFTYPE_NOT_ON_ROOT,
7088 		.seq_show = memory_max_show,
7089 		.write = memory_max_write,
7090 	},
7091 	{
7092 		.name = "events",
7093 		.flags = CFTYPE_NOT_ON_ROOT,
7094 		.file_offset = offsetof(struct mem_cgroup, events_file),
7095 		.seq_show = memory_events_show,
7096 	},
7097 	{
7098 		.name = "events.local",
7099 		.flags = CFTYPE_NOT_ON_ROOT,
7100 		.file_offset = offsetof(struct mem_cgroup, events_local_file),
7101 		.seq_show = memory_events_local_show,
7102 	},
7103 	{
7104 		.name = "stat",
7105 		.seq_show = memory_stat_show,
7106 	},
7107 #ifdef CONFIG_NUMA
7108 	{
7109 		.name = "numa_stat",
7110 		.seq_show = memory_numa_stat_show,
7111 	},
7112 #endif
7113 	{
7114 		.name = "oom.group",
7115 		.flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE,
7116 		.seq_show = memory_oom_group_show,
7117 		.write = memory_oom_group_write,
7118 	},
7119 	{
7120 		.name = "reclaim",
7121 		.flags = CFTYPE_NS_DELEGATABLE,
7122 		.write = memory_reclaim,
7123 	},
7124 	{ }	/* terminate */
7125 };
7126 
7127 struct cgroup_subsys memory_cgrp_subsys = {
7128 	.css_alloc = mem_cgroup_css_alloc,
7129 	.css_online = mem_cgroup_css_online,
7130 	.css_offline = mem_cgroup_css_offline,
7131 	.css_released = mem_cgroup_css_released,
7132 	.css_free = mem_cgroup_css_free,
7133 	.css_reset = mem_cgroup_css_reset,
7134 	.css_rstat_flush = mem_cgroup_css_rstat_flush,
7135 	.can_attach = mem_cgroup_can_attach,
7136 #if defined(CONFIG_LRU_GEN) || defined(CONFIG_MEMCG_KMEM)
7137 	.attach = mem_cgroup_attach,
7138 #endif
7139 	.cancel_attach = mem_cgroup_cancel_attach,
7140 	.post_attach = mem_cgroup_move_task,
7141 #ifdef CONFIG_MEMCG_KMEM
7142 	.fork = mem_cgroup_fork,
7143 	.exit = mem_cgroup_exit,
7144 #endif
7145 	.dfl_cftypes = memory_files,
7146 	.legacy_cftypes = mem_cgroup_legacy_files,
7147 	.early_init = 0,
7148 };
7149 
7150 /*
7151  * This function calculates an individual cgroup's effective
7152  * protection which is derived from its own memory.min/low, its
7153  * parent's and siblings' settings, as well as the actual memory
7154  * distribution in the tree.
7155  *
7156  * The following rules apply to the effective protection values:
7157  *
7158  * 1. At the first level of reclaim, effective protection is equal to
7159  *    the declared protection in memory.min and memory.low.
7160  *
7161  * 2. To enable safe delegation of the protection configuration, at
7162  *    subsequent levels the effective protection is capped to the
7163  *    parent's effective protection.
7164  *
7165  * 3. To make complex and dynamic subtrees easier to configure, the
7166  *    user is allowed to overcommit the declared protection at a given
7167  *    level. If that is the case, the parent's effective protection is
7168  *    distributed to the children in proportion to how much protection
7169  *    they have declared and how much of it they are utilizing.
7170  *
7171  *    This makes distribution proportional, but also work-conserving:
7172  *    if one cgroup claims much more protection than it uses memory,
7173  *    the unused remainder is available to its siblings.
7174  *
7175  * 4. Conversely, when the declared protection is undercommitted at a
7176  *    given level, the distribution of the larger parental protection
7177  *    budget is NOT proportional. A cgroup's protection from a sibling
7178  *    is capped to its own memory.min/low setting.
7179  *
7180  * 5. However, to allow protecting recursive subtrees from each other
7181  *    without having to declare each individual cgroup's fixed share
7182  *    of the ancestor's claim to protection, any unutilized -
7183  *    "floating" - protection from up the tree is distributed in
7184  *    proportion to each cgroup's *usage*. This makes the protection
7185  *    neutral wrt sibling cgroups and lets them compete freely over
7186  *    the shared parental protection budget, but it protects the
7187  *    subtree as a whole from neighboring subtrees.
7188  *
7189  * Note that 4. and 5. are not in conflict: 4. is about protecting
7190  * against immediate siblings whereas 5. is about protecting against
7191  * neighboring subtrees.
7192  */
7193 static unsigned long effective_protection(unsigned long usage,
7194 					  unsigned long parent_usage,
7195 					  unsigned long setting,
7196 					  unsigned long parent_effective,
7197 					  unsigned long siblings_protected)
7198 {
7199 	unsigned long protected;
7200 	unsigned long ep;
7201 
7202 	protected = min(usage, setting);
7203 	/*
7204 	 * If all cgroups at this level combined claim and use more
7205 	 * protection than what the parent affords them, distribute
7206 	 * shares in proportion to utilization.
7207 	 *
7208 	 * We are using actual utilization rather than the statically
7209 	 * claimed protection in order to be work-conserving: claimed
7210 	 * but unused protection is available to siblings that would
7211 	 * otherwise get a smaller chunk than what they claimed.
7212 	 */
7213 	if (siblings_protected > parent_effective)
7214 		return protected * parent_effective / siblings_protected;
7215 
7216 	/*
7217 	 * Ok, utilized protection of all children is within what the
7218 	 * parent affords them, so we know whatever this child claims
7219 	 * and utilizes is effectively protected.
7220 	 *
7221 	 * If there is unprotected usage beyond this value, reclaim
7222 	 * will apply pressure in proportion to that amount.
7223 	 *
7224 	 * If there is unutilized protection, the cgroup will be fully
7225 	 * shielded from reclaim, but we do return a smaller value for
7226 	 * protection than what the group could enjoy in theory. This
7227 	 * is okay. With the overcommit distribution above, effective
7228 	 * protection is always dependent on how memory is actually
7229 	 * consumed among the siblings anyway.
7230 	 */
7231 	ep = protected;
7232 
7233 	/*
7234 	 * If the children aren't claiming (all of) the protection
7235 	 * afforded to them by the parent, distribute the remainder in
7236 	 * proportion to the (unprotected) memory of each cgroup. That
7237 	 * way, cgroups that aren't explicitly prioritized wrt each
7238 	 * other compete freely over the allowance, but they are
7239 	 * collectively protected from neighboring trees.
7240 	 *
7241 	 * We're using unprotected memory for the weight so that if
7242 	 * some cgroups DO claim explicit protection, we don't protect
7243 	 * the same bytes twice.
7244 	 *
7245 	 * Check both usage and parent_usage against the respective
7246 	 * protected values. One should imply the other, but they
7247 	 * aren't read atomically - make sure the division is sane.
7248 	 */
7249 	if (!(cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT))
7250 		return ep;
7251 	if (parent_effective > siblings_protected &&
7252 	    parent_usage > siblings_protected &&
7253 	    usage > protected) {
7254 		unsigned long unclaimed;
7255 
7256 		unclaimed = parent_effective - siblings_protected;
7257 		unclaimed *= usage - protected;
7258 		unclaimed /= parent_usage - siblings_protected;
7259 
7260 		ep += unclaimed;
7261 	}
7262 
7263 	return ep;
7264 }
7265 
7266 /**
7267  * mem_cgroup_calculate_protection - check if memory consumption is in the normal range
7268  * @root: the top ancestor of the sub-tree being checked
7269  * @memcg: the memory cgroup to check
7270  *
7271  * WARNING: This function is not stateless! It can only be used as part
7272  *          of a top-down tree iteration, not for isolated queries.
7273  */
7274 void mem_cgroup_calculate_protection(struct mem_cgroup *root,
7275 				     struct mem_cgroup *memcg)
7276 {
7277 	unsigned long usage, parent_usage;
7278 	struct mem_cgroup *parent;
7279 
7280 	if (mem_cgroup_disabled())
7281 		return;
7282 
7283 	if (!root)
7284 		root = root_mem_cgroup;
7285 
7286 	/*
7287 	 * Effective values of the reclaim targets are ignored so they
7288 	 * can be stale. Have a look at mem_cgroup_protection for more
7289 	 * details.
7290 	 * TODO: calculation should be more robust so that we do not need
7291 	 * that special casing.
7292 	 */
7293 	if (memcg == root)
7294 		return;
7295 
7296 	usage = page_counter_read(&memcg->memory);
7297 	if (!usage)
7298 		return;
7299 
7300 	parent = parent_mem_cgroup(memcg);
7301 
7302 	if (parent == root) {
7303 		memcg->memory.emin = READ_ONCE(memcg->memory.min);
7304 		memcg->memory.elow = READ_ONCE(memcg->memory.low);
7305 		return;
7306 	}
7307 
7308 	parent_usage = page_counter_read(&parent->memory);
7309 
7310 	WRITE_ONCE(memcg->memory.emin, effective_protection(usage, parent_usage,
7311 			READ_ONCE(memcg->memory.min),
7312 			READ_ONCE(parent->memory.emin),
7313 			atomic_long_read(&parent->memory.children_min_usage)));
7314 
7315 	WRITE_ONCE(memcg->memory.elow, effective_protection(usage, parent_usage,
7316 			READ_ONCE(memcg->memory.low),
7317 			READ_ONCE(parent->memory.elow),
7318 			atomic_long_read(&parent->memory.children_low_usage)));
7319 }
7320 
7321 static int charge_memcg(struct folio *folio, struct mem_cgroup *memcg,
7322 			gfp_t gfp)
7323 {
7324 	int ret;
7325 
7326 	ret = try_charge(memcg, gfp, folio_nr_pages(folio));
7327 	if (ret)
7328 		goto out;
7329 
7330 	mem_cgroup_commit_charge(folio, memcg);
7331 out:
7332 	return ret;
7333 }
7334 
7335 int __mem_cgroup_charge(struct folio *folio, struct mm_struct *mm, gfp_t gfp)
7336 {
7337 	struct mem_cgroup *memcg;
7338 	int ret;
7339 
7340 	memcg = get_mem_cgroup_from_mm(mm);
7341 	ret = charge_memcg(folio, memcg, gfp);
7342 	css_put(&memcg->css);
7343 
7344 	return ret;
7345 }
7346 
7347 /**
7348  * mem_cgroup_hugetlb_try_charge - try to charge the memcg for a hugetlb folio
7349  * @memcg: memcg to charge.
7350  * @gfp: reclaim mode.
7351  * @nr_pages: number of pages to charge.
7352  *
7353  * This function is called when allocating a huge page folio to determine if
7354  * the memcg has the capacity for it. It does not commit the charge yet,
7355  * as the hugetlb folio itself has not been obtained from the hugetlb pool.
7356  *
7357  * Once we have obtained the hugetlb folio, we can call
7358  * mem_cgroup_commit_charge() to commit the charge. If we fail to obtain the
7359  * folio, we should instead call mem_cgroup_cancel_charge() to undo the effect
7360  * of try_charge().
7361  *
7362  * Returns 0 on success. Otherwise, an error code is returned.
7363  */
7364 int mem_cgroup_hugetlb_try_charge(struct mem_cgroup *memcg, gfp_t gfp,
7365 			long nr_pages)
7366 {
7367 	/*
7368 	 * If hugetlb memcg charging is not enabled, do not fail hugetlb allocation,
7369 	 * but do not attempt to commit charge later (or cancel on error) either.
7370 	 */
7371 	if (mem_cgroup_disabled() || !memcg ||
7372 		!cgroup_subsys_on_dfl(memory_cgrp_subsys) ||
7373 		!(cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_HUGETLB_ACCOUNTING))
7374 		return -EOPNOTSUPP;
7375 
7376 	if (try_charge(memcg, gfp, nr_pages))
7377 		return -ENOMEM;
7378 
7379 	return 0;
7380 }
7381 
7382 /**
7383  * mem_cgroup_swapin_charge_folio - Charge a newly allocated folio for swapin.
7384  * @folio: folio to charge.
7385  * @mm: mm context of the victim
7386  * @gfp: reclaim mode
7387  * @entry: swap entry for which the folio is allocated
7388  *
7389  * This function charges a folio allocated for swapin. Please call this before
7390  * adding the folio to the swapcache.
7391  *
7392  * Returns 0 on success. Otherwise, an error code is returned.
7393  */
7394 int mem_cgroup_swapin_charge_folio(struct folio *folio, struct mm_struct *mm,
7395 				  gfp_t gfp, swp_entry_t entry)
7396 {
7397 	struct mem_cgroup *memcg;
7398 	unsigned short id;
7399 	int ret;
7400 
7401 	if (mem_cgroup_disabled())
7402 		return 0;
7403 
7404 	id = lookup_swap_cgroup_id(entry);
7405 	rcu_read_lock();
7406 	memcg = mem_cgroup_from_id(id);
7407 	if (!memcg || !css_tryget_online(&memcg->css))
7408 		memcg = get_mem_cgroup_from_mm(mm);
7409 	rcu_read_unlock();
7410 
7411 	ret = charge_memcg(folio, memcg, gfp);
7412 
7413 	css_put(&memcg->css);
7414 	return ret;
7415 }
7416 
7417 /*
7418  * mem_cgroup_swapin_uncharge_swap - uncharge swap slot
7419  * @entry: swap entry for which the page is charged
7420  *
7421  * Call this function after successfully adding the charged page to swapcache.
7422  *
7423  * Note: This function assumes the page for which swap slot is being uncharged
7424  * is order 0 page.
7425  */
7426 void mem_cgroup_swapin_uncharge_swap(swp_entry_t entry)
7427 {
7428 	/*
7429 	 * Cgroup1's unified memory+swap counter has been charged with the
7430 	 * new swapcache page, finish the transfer by uncharging the swap
7431 	 * slot. The swap slot would also get uncharged when it dies, but
7432 	 * it can stick around indefinitely and we'd count the page twice
7433 	 * the entire time.
7434 	 *
7435 	 * Cgroup2 has separate resource counters for memory and swap,
7436 	 * so this is a non-issue here. Memory and swap charge lifetimes
7437 	 * correspond 1:1 to page and swap slot lifetimes: we charge the
7438 	 * page to memory here, and uncharge swap when the slot is freed.
7439 	 */
7440 	if (!mem_cgroup_disabled() && do_memsw_account()) {
7441 		/*
7442 		 * The swap entry might not get freed for a long time,
7443 		 * let's not wait for it.  The page already received a
7444 		 * memory+swap charge, drop the swap entry duplicate.
7445 		 */
7446 		mem_cgroup_uncharge_swap(entry, 1);
7447 	}
7448 }
7449 
7450 struct uncharge_gather {
7451 	struct mem_cgroup *memcg;
7452 	unsigned long nr_memory;
7453 	unsigned long pgpgout;
7454 	unsigned long nr_kmem;
7455 	int nid;
7456 };
7457 
7458 static inline void uncharge_gather_clear(struct uncharge_gather *ug)
7459 {
7460 	memset(ug, 0, sizeof(*ug));
7461 }
7462 
7463 static void uncharge_batch(const struct uncharge_gather *ug)
7464 {
7465 	unsigned long flags;
7466 
7467 	if (ug->nr_memory) {
7468 		page_counter_uncharge(&ug->memcg->memory, ug->nr_memory);
7469 		if (do_memsw_account())
7470 			page_counter_uncharge(&ug->memcg->memsw, ug->nr_memory);
7471 		if (ug->nr_kmem)
7472 			memcg_account_kmem(ug->memcg, -ug->nr_kmem);
7473 		memcg_oom_recover(ug->memcg);
7474 	}
7475 
7476 	local_irq_save(flags);
7477 	__count_memcg_events(ug->memcg, PGPGOUT, ug->pgpgout);
7478 	__this_cpu_add(ug->memcg->vmstats_percpu->nr_page_events, ug->nr_memory);
7479 	memcg_check_events(ug->memcg, ug->nid);
7480 	local_irq_restore(flags);
7481 
7482 	/* drop reference from uncharge_folio */
7483 	css_put(&ug->memcg->css);
7484 }
7485 
7486 static void uncharge_folio(struct folio *folio, struct uncharge_gather *ug)
7487 {
7488 	long nr_pages;
7489 	struct mem_cgroup *memcg;
7490 	struct obj_cgroup *objcg;
7491 
7492 	VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
7493 	VM_BUG_ON_FOLIO(folio_order(folio) > 1 &&
7494 			!folio_test_hugetlb(folio) &&
7495 			!list_empty(&folio->_deferred_list), folio);
7496 
7497 	/*
7498 	 * Nobody should be changing or seriously looking at
7499 	 * folio memcg or objcg at this point, we have fully
7500 	 * exclusive access to the folio.
7501 	 */
7502 	if (folio_memcg_kmem(folio)) {
7503 		objcg = __folio_objcg(folio);
7504 		/*
7505 		 * This get matches the put at the end of the function and
7506 		 * kmem pages do not hold memcg references anymore.
7507 		 */
7508 		memcg = get_mem_cgroup_from_objcg(objcg);
7509 	} else {
7510 		memcg = __folio_memcg(folio);
7511 	}
7512 
7513 	if (!memcg)
7514 		return;
7515 
7516 	if (ug->memcg != memcg) {
7517 		if (ug->memcg) {
7518 			uncharge_batch(ug);
7519 			uncharge_gather_clear(ug);
7520 		}
7521 		ug->memcg = memcg;
7522 		ug->nid = folio_nid(folio);
7523 
7524 		/* pairs with css_put in uncharge_batch */
7525 		css_get(&memcg->css);
7526 	}
7527 
7528 	nr_pages = folio_nr_pages(folio);
7529 
7530 	if (folio_memcg_kmem(folio)) {
7531 		ug->nr_memory += nr_pages;
7532 		ug->nr_kmem += nr_pages;
7533 
7534 		folio->memcg_data = 0;
7535 		obj_cgroup_put(objcg);
7536 	} else {
7537 		/* LRU pages aren't accounted at the root level */
7538 		if (!mem_cgroup_is_root(memcg))
7539 			ug->nr_memory += nr_pages;
7540 		ug->pgpgout++;
7541 
7542 		folio->memcg_data = 0;
7543 	}
7544 
7545 	css_put(&memcg->css);
7546 }
7547 
7548 void __mem_cgroup_uncharge(struct folio *folio)
7549 {
7550 	struct uncharge_gather ug;
7551 
7552 	/* Don't touch folio->lru of any random page, pre-check: */
7553 	if (!folio_memcg(folio))
7554 		return;
7555 
7556 	uncharge_gather_clear(&ug);
7557 	uncharge_folio(folio, &ug);
7558 	uncharge_batch(&ug);
7559 }
7560 
7561 void __mem_cgroup_uncharge_folios(struct folio_batch *folios)
7562 {
7563 	struct uncharge_gather ug;
7564 	unsigned int i;
7565 
7566 	uncharge_gather_clear(&ug);
7567 	for (i = 0; i < folios->nr; i++)
7568 		uncharge_folio(folios->folios[i], &ug);
7569 	if (ug.memcg)
7570 		uncharge_batch(&ug);
7571 }
7572 
7573 /**
7574  * mem_cgroup_replace_folio - Charge a folio's replacement.
7575  * @old: Currently circulating folio.
7576  * @new: Replacement folio.
7577  *
7578  * Charge @new as a replacement folio for @old. @old will
7579  * be uncharged upon free. This is only used by the page cache
7580  * (in replace_page_cache_folio()).
7581  *
7582  * Both folios must be locked, @new->mapping must be set up.
7583  */
7584 void mem_cgroup_replace_folio(struct folio *old, struct folio *new)
7585 {
7586 	struct mem_cgroup *memcg;
7587 	long nr_pages = folio_nr_pages(new);
7588 	unsigned long flags;
7589 
7590 	VM_BUG_ON_FOLIO(!folio_test_locked(old), old);
7591 	VM_BUG_ON_FOLIO(!folio_test_locked(new), new);
7592 	VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new);
7593 	VM_BUG_ON_FOLIO(folio_nr_pages(old) != nr_pages, new);
7594 
7595 	if (mem_cgroup_disabled())
7596 		return;
7597 
7598 	/* Page cache replacement: new folio already charged? */
7599 	if (folio_memcg(new))
7600 		return;
7601 
7602 	memcg = folio_memcg(old);
7603 	VM_WARN_ON_ONCE_FOLIO(!memcg, old);
7604 	if (!memcg)
7605 		return;
7606 
7607 	/* Force-charge the new page. The old one will be freed soon */
7608 	if (!mem_cgroup_is_root(memcg)) {
7609 		page_counter_charge(&memcg->memory, nr_pages);
7610 		if (do_memsw_account())
7611 			page_counter_charge(&memcg->memsw, nr_pages);
7612 	}
7613 
7614 	css_get(&memcg->css);
7615 	commit_charge(new, memcg);
7616 
7617 	local_irq_save(flags);
7618 	mem_cgroup_charge_statistics(memcg, nr_pages);
7619 	memcg_check_events(memcg, folio_nid(new));
7620 	local_irq_restore(flags);
7621 }
7622 
7623 /**
7624  * mem_cgroup_migrate - Transfer the memcg data from the old to the new folio.
7625  * @old: Currently circulating folio.
7626  * @new: Replacement folio.
7627  *
7628  * Transfer the memcg data from the old folio to the new folio for migration.
7629  * The old folio's data info will be cleared. Note that the memory counters
7630  * will remain unchanged throughout the process.
7631  *
7632  * Both folios must be locked, @new->mapping must be set up.
7633  */
7634 void mem_cgroup_migrate(struct folio *old, struct folio *new)
7635 {
7636 	struct mem_cgroup *memcg;
7637 
7638 	VM_BUG_ON_FOLIO(!folio_test_locked(old), old);
7639 	VM_BUG_ON_FOLIO(!folio_test_locked(new), new);
7640 	VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new);
7641 	VM_BUG_ON_FOLIO(folio_nr_pages(old) != folio_nr_pages(new), new);
7642 
7643 	if (mem_cgroup_disabled())
7644 		return;
7645 
7646 	memcg = folio_memcg(old);
7647 	/*
7648 	 * Note that it is normal to see !memcg for a hugetlb folio.
7649 	 * For e.g, itt could have been allocated when memory_hugetlb_accounting
7650 	 * was not selected.
7651 	 */
7652 	VM_WARN_ON_ONCE_FOLIO(!folio_test_hugetlb(old) && !memcg, old);
7653 	if (!memcg)
7654 		return;
7655 
7656 	/* Transfer the charge and the css ref */
7657 	commit_charge(new, memcg);
7658 	/*
7659 	 * If the old folio is a large folio and is in the split queue, it needs
7660 	 * to be removed from the split queue now, in case getting an incorrect
7661 	 * split queue in destroy_large_folio() after the memcg of the old folio
7662 	 * is cleared.
7663 	 *
7664 	 * In addition, the old folio is about to be freed after migration, so
7665 	 * removing from the split queue a bit earlier seems reasonable.
7666 	 */
7667 	if (folio_test_large(old) && folio_test_large_rmappable(old))
7668 		folio_undo_large_rmappable(old);
7669 	old->memcg_data = 0;
7670 }
7671 
7672 DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key);
7673 EXPORT_SYMBOL(memcg_sockets_enabled_key);
7674 
7675 void mem_cgroup_sk_alloc(struct sock *sk)
7676 {
7677 	struct mem_cgroup *memcg;
7678 
7679 	if (!mem_cgroup_sockets_enabled)
7680 		return;
7681 
7682 	/* Do not associate the sock with unrelated interrupted task's memcg. */
7683 	if (!in_task())
7684 		return;
7685 
7686 	rcu_read_lock();
7687 	memcg = mem_cgroup_from_task(current);
7688 	if (mem_cgroup_is_root(memcg))
7689 		goto out;
7690 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg->tcpmem_active)
7691 		goto out;
7692 	if (css_tryget(&memcg->css))
7693 		sk->sk_memcg = memcg;
7694 out:
7695 	rcu_read_unlock();
7696 }
7697 
7698 void mem_cgroup_sk_free(struct sock *sk)
7699 {
7700 	if (sk->sk_memcg)
7701 		css_put(&sk->sk_memcg->css);
7702 }
7703 
7704 /**
7705  * mem_cgroup_charge_skmem - charge socket memory
7706  * @memcg: memcg to charge
7707  * @nr_pages: number of pages to charge
7708  * @gfp_mask: reclaim mode
7709  *
7710  * Charges @nr_pages to @memcg. Returns %true if the charge fit within
7711  * @memcg's configured limit, %false if it doesn't.
7712  */
7713 bool mem_cgroup_charge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages,
7714 			     gfp_t gfp_mask)
7715 {
7716 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
7717 		struct page_counter *fail;
7718 
7719 		if (page_counter_try_charge(&memcg->tcpmem, nr_pages, &fail)) {
7720 			memcg->tcpmem_pressure = 0;
7721 			return true;
7722 		}
7723 		memcg->tcpmem_pressure = 1;
7724 		if (gfp_mask & __GFP_NOFAIL) {
7725 			page_counter_charge(&memcg->tcpmem, nr_pages);
7726 			return true;
7727 		}
7728 		return false;
7729 	}
7730 
7731 	if (try_charge(memcg, gfp_mask, nr_pages) == 0) {
7732 		mod_memcg_state(memcg, MEMCG_SOCK, nr_pages);
7733 		return true;
7734 	}
7735 
7736 	return false;
7737 }
7738 
7739 /**
7740  * mem_cgroup_uncharge_skmem - uncharge socket memory
7741  * @memcg: memcg to uncharge
7742  * @nr_pages: number of pages to uncharge
7743  */
7744 void mem_cgroup_uncharge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
7745 {
7746 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
7747 		page_counter_uncharge(&memcg->tcpmem, nr_pages);
7748 		return;
7749 	}
7750 
7751 	mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages);
7752 
7753 	refill_stock(memcg, nr_pages);
7754 }
7755 
7756 static int __init cgroup_memory(char *s)
7757 {
7758 	char *token;
7759 
7760 	while ((token = strsep(&s, ",")) != NULL) {
7761 		if (!*token)
7762 			continue;
7763 		if (!strcmp(token, "nosocket"))
7764 			cgroup_memory_nosocket = true;
7765 		if (!strcmp(token, "nokmem"))
7766 			cgroup_memory_nokmem = true;
7767 		if (!strcmp(token, "nobpf"))
7768 			cgroup_memory_nobpf = true;
7769 	}
7770 	return 1;
7771 }
7772 __setup("cgroup.memory=", cgroup_memory);
7773 
7774 /*
7775  * subsys_initcall() for memory controller.
7776  *
7777  * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this
7778  * context because of lock dependencies (cgroup_lock -> cpu hotplug) but
7779  * basically everything that doesn't depend on a specific mem_cgroup structure
7780  * should be initialized from here.
7781  */
7782 static int __init mem_cgroup_init(void)
7783 {
7784 	int cpu, node;
7785 
7786 	/*
7787 	 * Currently s32 type (can refer to struct batched_lruvec_stat) is
7788 	 * used for per-memcg-per-cpu caching of per-node statistics. In order
7789 	 * to work fine, we should make sure that the overfill threshold can't
7790 	 * exceed S32_MAX / PAGE_SIZE.
7791 	 */
7792 	BUILD_BUG_ON(MEMCG_CHARGE_BATCH > S32_MAX / PAGE_SIZE);
7793 
7794 	cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL,
7795 				  memcg_hotplug_cpu_dead);
7796 
7797 	for_each_possible_cpu(cpu)
7798 		INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
7799 			  drain_local_stock);
7800 
7801 	for_each_node(node) {
7802 		struct mem_cgroup_tree_per_node *rtpn;
7803 
7804 		rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, node);
7805 
7806 		rtpn->rb_root = RB_ROOT;
7807 		rtpn->rb_rightmost = NULL;
7808 		spin_lock_init(&rtpn->lock);
7809 		soft_limit_tree.rb_tree_per_node[node] = rtpn;
7810 	}
7811 
7812 	return 0;
7813 }
7814 subsys_initcall(mem_cgroup_init);
7815 
7816 #ifdef CONFIG_SWAP
7817 static struct mem_cgroup *mem_cgroup_id_get_online(struct mem_cgroup *memcg)
7818 {
7819 	while (!refcount_inc_not_zero(&memcg->id.ref)) {
7820 		/*
7821 		 * The root cgroup cannot be destroyed, so it's refcount must
7822 		 * always be >= 1.
7823 		 */
7824 		if (WARN_ON_ONCE(mem_cgroup_is_root(memcg))) {
7825 			VM_BUG_ON(1);
7826 			break;
7827 		}
7828 		memcg = parent_mem_cgroup(memcg);
7829 		if (!memcg)
7830 			memcg = root_mem_cgroup;
7831 	}
7832 	return memcg;
7833 }
7834 
7835 /**
7836  * mem_cgroup_swapout - transfer a memsw charge to swap
7837  * @folio: folio whose memsw charge to transfer
7838  * @entry: swap entry to move the charge to
7839  *
7840  * Transfer the memsw charge of @folio to @entry.
7841  */
7842 void mem_cgroup_swapout(struct folio *folio, swp_entry_t entry)
7843 {
7844 	struct mem_cgroup *memcg, *swap_memcg;
7845 	unsigned int nr_entries;
7846 	unsigned short oldid;
7847 
7848 	VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
7849 	VM_BUG_ON_FOLIO(folio_ref_count(folio), folio);
7850 
7851 	if (mem_cgroup_disabled())
7852 		return;
7853 
7854 	if (!do_memsw_account())
7855 		return;
7856 
7857 	memcg = folio_memcg(folio);
7858 
7859 	VM_WARN_ON_ONCE_FOLIO(!memcg, folio);
7860 	if (!memcg)
7861 		return;
7862 
7863 	/*
7864 	 * In case the memcg owning these pages has been offlined and doesn't
7865 	 * have an ID allocated to it anymore, charge the closest online
7866 	 * ancestor for the swap instead and transfer the memory+swap charge.
7867 	 */
7868 	swap_memcg = mem_cgroup_id_get_online(memcg);
7869 	nr_entries = folio_nr_pages(folio);
7870 	/* Get references for the tail pages, too */
7871 	if (nr_entries > 1)
7872 		mem_cgroup_id_get_many(swap_memcg, nr_entries - 1);
7873 	oldid = swap_cgroup_record(entry, mem_cgroup_id(swap_memcg),
7874 				   nr_entries);
7875 	VM_BUG_ON_FOLIO(oldid, folio);
7876 	mod_memcg_state(swap_memcg, MEMCG_SWAP, nr_entries);
7877 
7878 	folio->memcg_data = 0;
7879 
7880 	if (!mem_cgroup_is_root(memcg))
7881 		page_counter_uncharge(&memcg->memory, nr_entries);
7882 
7883 	if (memcg != swap_memcg) {
7884 		if (!mem_cgroup_is_root(swap_memcg))
7885 			page_counter_charge(&swap_memcg->memsw, nr_entries);
7886 		page_counter_uncharge(&memcg->memsw, nr_entries);
7887 	}
7888 
7889 	/*
7890 	 * Interrupts should be disabled here because the caller holds the
7891 	 * i_pages lock which is taken with interrupts-off. It is
7892 	 * important here to have the interrupts disabled because it is the
7893 	 * only synchronisation we have for updating the per-CPU variables.
7894 	 */
7895 	memcg_stats_lock();
7896 	mem_cgroup_charge_statistics(memcg, -nr_entries);
7897 	memcg_stats_unlock();
7898 	memcg_check_events(memcg, folio_nid(folio));
7899 
7900 	css_put(&memcg->css);
7901 }
7902 
7903 /**
7904  * __mem_cgroup_try_charge_swap - try charging swap space for a folio
7905  * @folio: folio being added to swap
7906  * @entry: swap entry to charge
7907  *
7908  * Try to charge @folio's memcg for the swap space at @entry.
7909  *
7910  * Returns 0 on success, -ENOMEM on failure.
7911  */
7912 int __mem_cgroup_try_charge_swap(struct folio *folio, swp_entry_t entry)
7913 {
7914 	unsigned int nr_pages = folio_nr_pages(folio);
7915 	struct page_counter *counter;
7916 	struct mem_cgroup *memcg;
7917 	unsigned short oldid;
7918 
7919 	if (do_memsw_account())
7920 		return 0;
7921 
7922 	memcg = folio_memcg(folio);
7923 
7924 	VM_WARN_ON_ONCE_FOLIO(!memcg, folio);
7925 	if (!memcg)
7926 		return 0;
7927 
7928 	if (!entry.val) {
7929 		memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
7930 		return 0;
7931 	}
7932 
7933 	memcg = mem_cgroup_id_get_online(memcg);
7934 
7935 	if (!mem_cgroup_is_root(memcg) &&
7936 	    !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
7937 		memcg_memory_event(memcg, MEMCG_SWAP_MAX);
7938 		memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
7939 		mem_cgroup_id_put(memcg);
7940 		return -ENOMEM;
7941 	}
7942 
7943 	/* Get references for the tail pages, too */
7944 	if (nr_pages > 1)
7945 		mem_cgroup_id_get_many(memcg, nr_pages - 1);
7946 	oldid = swap_cgroup_record(entry, mem_cgroup_id(memcg), nr_pages);
7947 	VM_BUG_ON_FOLIO(oldid, folio);
7948 	mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
7949 
7950 	return 0;
7951 }
7952 
7953 /**
7954  * __mem_cgroup_uncharge_swap - uncharge swap space
7955  * @entry: swap entry to uncharge
7956  * @nr_pages: the amount of swap space to uncharge
7957  */
7958 void __mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages)
7959 {
7960 	struct mem_cgroup *memcg;
7961 	unsigned short id;
7962 
7963 	id = swap_cgroup_record(entry, 0, nr_pages);
7964 	rcu_read_lock();
7965 	memcg = mem_cgroup_from_id(id);
7966 	if (memcg) {
7967 		if (!mem_cgroup_is_root(memcg)) {
7968 			if (do_memsw_account())
7969 				page_counter_uncharge(&memcg->memsw, nr_pages);
7970 			else
7971 				page_counter_uncharge(&memcg->swap, nr_pages);
7972 		}
7973 		mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
7974 		mem_cgroup_id_put_many(memcg, nr_pages);
7975 	}
7976 	rcu_read_unlock();
7977 }
7978 
7979 long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg)
7980 {
7981 	long nr_swap_pages = get_nr_swap_pages();
7982 
7983 	if (mem_cgroup_disabled() || do_memsw_account())
7984 		return nr_swap_pages;
7985 	for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg))
7986 		nr_swap_pages = min_t(long, nr_swap_pages,
7987 				      READ_ONCE(memcg->swap.max) -
7988 				      page_counter_read(&memcg->swap));
7989 	return nr_swap_pages;
7990 }
7991 
7992 bool mem_cgroup_swap_full(struct folio *folio)
7993 {
7994 	struct mem_cgroup *memcg;
7995 
7996 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
7997 
7998 	if (vm_swap_full())
7999 		return true;
8000 	if (do_memsw_account())
8001 		return false;
8002 
8003 	memcg = folio_memcg(folio);
8004 	if (!memcg)
8005 		return false;
8006 
8007 	for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
8008 		unsigned long usage = page_counter_read(&memcg->swap);
8009 
8010 		if (usage * 2 >= READ_ONCE(memcg->swap.high) ||
8011 		    usage * 2 >= READ_ONCE(memcg->swap.max))
8012 			return true;
8013 	}
8014 
8015 	return false;
8016 }
8017 
8018 static int __init setup_swap_account(char *s)
8019 {
8020 	bool res;
8021 
8022 	if (!kstrtobool(s, &res) && !res)
8023 		pr_warn_once("The swapaccount=0 commandline option is deprecated "
8024 			     "in favor of configuring swap control via cgroupfs. "
8025 			     "Please report your usecase to linux-mm@kvack.org if you "
8026 			     "depend on this functionality.\n");
8027 	return 1;
8028 }
8029 __setup("swapaccount=", setup_swap_account);
8030 
8031 static u64 swap_current_read(struct cgroup_subsys_state *css,
8032 			     struct cftype *cft)
8033 {
8034 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
8035 
8036 	return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE;
8037 }
8038 
8039 static u64 swap_peak_read(struct cgroup_subsys_state *css,
8040 			  struct cftype *cft)
8041 {
8042 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
8043 
8044 	return (u64)memcg->swap.watermark * PAGE_SIZE;
8045 }
8046 
8047 static int swap_high_show(struct seq_file *m, void *v)
8048 {
8049 	return seq_puts_memcg_tunable(m,
8050 		READ_ONCE(mem_cgroup_from_seq(m)->swap.high));
8051 }
8052 
8053 static ssize_t swap_high_write(struct kernfs_open_file *of,
8054 			       char *buf, size_t nbytes, loff_t off)
8055 {
8056 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
8057 	unsigned long high;
8058 	int err;
8059 
8060 	buf = strstrip(buf);
8061 	err = page_counter_memparse(buf, "max", &high);
8062 	if (err)
8063 		return err;
8064 
8065 	page_counter_set_high(&memcg->swap, high);
8066 
8067 	return nbytes;
8068 }
8069 
8070 static int swap_max_show(struct seq_file *m, void *v)
8071 {
8072 	return seq_puts_memcg_tunable(m,
8073 		READ_ONCE(mem_cgroup_from_seq(m)->swap.max));
8074 }
8075 
8076 static ssize_t swap_max_write(struct kernfs_open_file *of,
8077 			      char *buf, size_t nbytes, loff_t off)
8078 {
8079 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
8080 	unsigned long max;
8081 	int err;
8082 
8083 	buf = strstrip(buf);
8084 	err = page_counter_memparse(buf, "max", &max);
8085 	if (err)
8086 		return err;
8087 
8088 	xchg(&memcg->swap.max, max);
8089 
8090 	return nbytes;
8091 }
8092 
8093 static int swap_events_show(struct seq_file *m, void *v)
8094 {
8095 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
8096 
8097 	seq_printf(m, "high %lu\n",
8098 		   atomic_long_read(&memcg->memory_events[MEMCG_SWAP_HIGH]));
8099 	seq_printf(m, "max %lu\n",
8100 		   atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
8101 	seq_printf(m, "fail %lu\n",
8102 		   atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL]));
8103 
8104 	return 0;
8105 }
8106 
8107 static struct cftype swap_files[] = {
8108 	{
8109 		.name = "swap.current",
8110 		.flags = CFTYPE_NOT_ON_ROOT,
8111 		.read_u64 = swap_current_read,
8112 	},
8113 	{
8114 		.name = "swap.high",
8115 		.flags = CFTYPE_NOT_ON_ROOT,
8116 		.seq_show = swap_high_show,
8117 		.write = swap_high_write,
8118 	},
8119 	{
8120 		.name = "swap.max",
8121 		.flags = CFTYPE_NOT_ON_ROOT,
8122 		.seq_show = swap_max_show,
8123 		.write = swap_max_write,
8124 	},
8125 	{
8126 		.name = "swap.peak",
8127 		.flags = CFTYPE_NOT_ON_ROOT,
8128 		.read_u64 = swap_peak_read,
8129 	},
8130 	{
8131 		.name = "swap.events",
8132 		.flags = CFTYPE_NOT_ON_ROOT,
8133 		.file_offset = offsetof(struct mem_cgroup, swap_events_file),
8134 		.seq_show = swap_events_show,
8135 	},
8136 	{ }	/* terminate */
8137 };
8138 
8139 static struct cftype memsw_files[] = {
8140 	{
8141 		.name = "memsw.usage_in_bytes",
8142 		.private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
8143 		.read_u64 = mem_cgroup_read_u64,
8144 	},
8145 	{
8146 		.name = "memsw.max_usage_in_bytes",
8147 		.private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
8148 		.write = mem_cgroup_reset,
8149 		.read_u64 = mem_cgroup_read_u64,
8150 	},
8151 	{
8152 		.name = "memsw.limit_in_bytes",
8153 		.private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
8154 		.write = mem_cgroup_write,
8155 		.read_u64 = mem_cgroup_read_u64,
8156 	},
8157 	{
8158 		.name = "memsw.failcnt",
8159 		.private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
8160 		.write = mem_cgroup_reset,
8161 		.read_u64 = mem_cgroup_read_u64,
8162 	},
8163 	{ },	/* terminate */
8164 };
8165 
8166 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
8167 /**
8168  * obj_cgroup_may_zswap - check if this cgroup can zswap
8169  * @objcg: the object cgroup
8170  *
8171  * Check if the hierarchical zswap limit has been reached.
8172  *
8173  * This doesn't check for specific headroom, and it is not atomic
8174  * either. But with zswap, the size of the allocation is only known
8175  * once compression has occurred, and this optimistic pre-check avoids
8176  * spending cycles on compression when there is already no room left
8177  * or zswap is disabled altogether somewhere in the hierarchy.
8178  */
8179 bool obj_cgroup_may_zswap(struct obj_cgroup *objcg)
8180 {
8181 	struct mem_cgroup *memcg, *original_memcg;
8182 	bool ret = true;
8183 
8184 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
8185 		return true;
8186 
8187 	original_memcg = get_mem_cgroup_from_objcg(objcg);
8188 	for (memcg = original_memcg; !mem_cgroup_is_root(memcg);
8189 	     memcg = parent_mem_cgroup(memcg)) {
8190 		unsigned long max = READ_ONCE(memcg->zswap_max);
8191 		unsigned long pages;
8192 
8193 		if (max == PAGE_COUNTER_MAX)
8194 			continue;
8195 		if (max == 0) {
8196 			ret = false;
8197 			break;
8198 		}
8199 
8200 		/*
8201 		 * mem_cgroup_flush_stats() ignores small changes. Use
8202 		 * do_flush_stats() directly to get accurate stats for charging.
8203 		 */
8204 		do_flush_stats(memcg);
8205 		pages = memcg_page_state(memcg, MEMCG_ZSWAP_B) / PAGE_SIZE;
8206 		if (pages < max)
8207 			continue;
8208 		ret = false;
8209 		break;
8210 	}
8211 	mem_cgroup_put(original_memcg);
8212 	return ret;
8213 }
8214 
8215 /**
8216  * obj_cgroup_charge_zswap - charge compression backend memory
8217  * @objcg: the object cgroup
8218  * @size: size of compressed object
8219  *
8220  * This forces the charge after obj_cgroup_may_zswap() allowed
8221  * compression and storage in zwap for this cgroup to go ahead.
8222  */
8223 void obj_cgroup_charge_zswap(struct obj_cgroup *objcg, size_t size)
8224 {
8225 	struct mem_cgroup *memcg;
8226 
8227 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
8228 		return;
8229 
8230 	VM_WARN_ON_ONCE(!(current->flags & PF_MEMALLOC));
8231 
8232 	/* PF_MEMALLOC context, charging must succeed */
8233 	if (obj_cgroup_charge(objcg, GFP_KERNEL, size))
8234 		VM_WARN_ON_ONCE(1);
8235 
8236 	rcu_read_lock();
8237 	memcg = obj_cgroup_memcg(objcg);
8238 	mod_memcg_state(memcg, MEMCG_ZSWAP_B, size);
8239 	mod_memcg_state(memcg, MEMCG_ZSWAPPED, 1);
8240 	rcu_read_unlock();
8241 }
8242 
8243 /**
8244  * obj_cgroup_uncharge_zswap - uncharge compression backend memory
8245  * @objcg: the object cgroup
8246  * @size: size of compressed object
8247  *
8248  * Uncharges zswap memory on page in.
8249  */
8250 void obj_cgroup_uncharge_zswap(struct obj_cgroup *objcg, size_t size)
8251 {
8252 	struct mem_cgroup *memcg;
8253 
8254 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
8255 		return;
8256 
8257 	obj_cgroup_uncharge(objcg, size);
8258 
8259 	rcu_read_lock();
8260 	memcg = obj_cgroup_memcg(objcg);
8261 	mod_memcg_state(memcg, MEMCG_ZSWAP_B, -size);
8262 	mod_memcg_state(memcg, MEMCG_ZSWAPPED, -1);
8263 	rcu_read_unlock();
8264 }
8265 
8266 bool mem_cgroup_zswap_writeback_enabled(struct mem_cgroup *memcg)
8267 {
8268 	/* if zswap is disabled, do not block pages going to the swapping device */
8269 	return !is_zswap_enabled() || !memcg || READ_ONCE(memcg->zswap_writeback);
8270 }
8271 
8272 static u64 zswap_current_read(struct cgroup_subsys_state *css,
8273 			      struct cftype *cft)
8274 {
8275 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
8276 
8277 	mem_cgroup_flush_stats(memcg);
8278 	return memcg_page_state(memcg, MEMCG_ZSWAP_B);
8279 }
8280 
8281 static int zswap_max_show(struct seq_file *m, void *v)
8282 {
8283 	return seq_puts_memcg_tunable(m,
8284 		READ_ONCE(mem_cgroup_from_seq(m)->zswap_max));
8285 }
8286 
8287 static ssize_t zswap_max_write(struct kernfs_open_file *of,
8288 			       char *buf, size_t nbytes, loff_t off)
8289 {
8290 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
8291 	unsigned long max;
8292 	int err;
8293 
8294 	buf = strstrip(buf);
8295 	err = page_counter_memparse(buf, "max", &max);
8296 	if (err)
8297 		return err;
8298 
8299 	xchg(&memcg->zswap_max, max);
8300 
8301 	return nbytes;
8302 }
8303 
8304 static int zswap_writeback_show(struct seq_file *m, void *v)
8305 {
8306 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
8307 
8308 	seq_printf(m, "%d\n", READ_ONCE(memcg->zswap_writeback));
8309 	return 0;
8310 }
8311 
8312 static ssize_t zswap_writeback_write(struct kernfs_open_file *of,
8313 				char *buf, size_t nbytes, loff_t off)
8314 {
8315 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
8316 	int zswap_writeback;
8317 	ssize_t parse_ret = kstrtoint(strstrip(buf), 0, &zswap_writeback);
8318 
8319 	if (parse_ret)
8320 		return parse_ret;
8321 
8322 	if (zswap_writeback != 0 && zswap_writeback != 1)
8323 		return -EINVAL;
8324 
8325 	WRITE_ONCE(memcg->zswap_writeback, zswap_writeback);
8326 	return nbytes;
8327 }
8328 
8329 static struct cftype zswap_files[] = {
8330 	{
8331 		.name = "zswap.current",
8332 		.flags = CFTYPE_NOT_ON_ROOT,
8333 		.read_u64 = zswap_current_read,
8334 	},
8335 	{
8336 		.name = "zswap.max",
8337 		.flags = CFTYPE_NOT_ON_ROOT,
8338 		.seq_show = zswap_max_show,
8339 		.write = zswap_max_write,
8340 	},
8341 	{
8342 		.name = "zswap.writeback",
8343 		.seq_show = zswap_writeback_show,
8344 		.write = zswap_writeback_write,
8345 	},
8346 	{ }	/* terminate */
8347 };
8348 #endif /* CONFIG_MEMCG_KMEM && CONFIG_ZSWAP */
8349 
8350 static int __init mem_cgroup_swap_init(void)
8351 {
8352 	if (mem_cgroup_disabled())
8353 		return 0;
8354 
8355 	WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, swap_files));
8356 	WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys, memsw_files));
8357 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
8358 	WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, zswap_files));
8359 #endif
8360 	return 0;
8361 }
8362 subsys_initcall(mem_cgroup_swap_init);
8363 
8364 #endif /* CONFIG_SWAP */
8365