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