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