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