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