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