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