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