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