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