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