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