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