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