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