• 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 extern spinlock_t css_set_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(&css_set_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(&css_set_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(&css_set_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(&css_set_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 		seq_printf(m, "%s %lu\n", lru_list_name(i),
4132 			   memcg_page_state_local(memcg, NR_LRU_BASE + i) *
4133 			   PAGE_SIZE);
4134 
4135 	/* Hierarchical information */
4136 	memory = memsw = PAGE_COUNTER_MAX;
4137 	for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
4138 		memory = min(memory, READ_ONCE(mi->memory.max));
4139 		memsw = min(memsw, READ_ONCE(mi->memsw.max));
4140 	}
4141 	seq_printf(m, "hierarchical_memory_limit %llu\n",
4142 		   (u64)memory * PAGE_SIZE);
4143 	if (do_memsw_account())
4144 		seq_printf(m, "hierarchical_memsw_limit %llu\n",
4145 			   (u64)memsw * PAGE_SIZE);
4146 
4147 	for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
4148 		unsigned long nr;
4149 
4150 		if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
4151 			continue;
4152 		nr = memcg_page_state(memcg, memcg1_stats[i]);
4153 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4154 		if (memcg1_stats[i] == NR_ANON_THPS)
4155 			nr *= HPAGE_PMD_NR;
4156 #endif
4157 		seq_printf(m, "total_%s %llu\n", memcg1_stat_names[i],
4158 						(u64)nr * PAGE_SIZE);
4159 	}
4160 
4161 	for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
4162 		seq_printf(m, "total_%s %llu\n",
4163 			   vm_event_name(memcg1_events[i]),
4164 			   (u64)memcg_events(memcg, memcg1_events[i]));
4165 
4166 	for (i = 0; i < NR_LRU_LISTS; i++)
4167 		seq_printf(m, "total_%s %llu\n", lru_list_name(i),
4168 			   (u64)memcg_page_state(memcg, NR_LRU_BASE + i) *
4169 			   PAGE_SIZE);
4170 
4171 #ifdef CONFIG_DEBUG_VM
4172 	{
4173 		pg_data_t *pgdat;
4174 		struct mem_cgroup_per_node *mz;
4175 		unsigned long anon_cost = 0;
4176 		unsigned long file_cost = 0;
4177 
4178 		for_each_online_pgdat(pgdat) {
4179 			mz = mem_cgroup_nodeinfo(memcg, pgdat->node_id);
4180 
4181 			anon_cost += mz->lruvec.anon_cost;
4182 			file_cost += mz->lruvec.file_cost;
4183 		}
4184 		seq_printf(m, "anon_cost %lu\n", anon_cost);
4185 		seq_printf(m, "file_cost %lu\n", file_cost);
4186 	}
4187 #endif
4188 
4189 #ifdef CONFIG_HYPERHOLD_DEBUG
4190 	memcg_eswap_info_show(m);
4191 #endif
4192 	return 0;
4193 }
4194 
mem_cgroup_swappiness_read(struct cgroup_subsys_state * css,struct cftype * cft)4195 static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
4196 				      struct cftype *cft)
4197 {
4198 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4199 
4200 	return mem_cgroup_swappiness(memcg);
4201 }
4202 
mem_cgroup_swappiness_write(struct cgroup_subsys_state * css,struct cftype * cft,u64 val)4203 static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
4204 				       struct cftype *cft, u64 val)
4205 {
4206 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4207 
4208 	if (val > 200)
4209 		return -EINVAL;
4210 
4211 	if (css->parent)
4212 		memcg->swappiness = val;
4213 	else
4214 		vm_swappiness = val;
4215 
4216 	return 0;
4217 }
4218 
__mem_cgroup_threshold(struct mem_cgroup * memcg,bool swap)4219 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4220 {
4221 	struct mem_cgroup_threshold_ary *t;
4222 	unsigned long usage;
4223 	int i;
4224 
4225 	rcu_read_lock();
4226 	if (!swap)
4227 		t = rcu_dereference(memcg->thresholds.primary);
4228 	else
4229 		t = rcu_dereference(memcg->memsw_thresholds.primary);
4230 
4231 	if (!t)
4232 		goto unlock;
4233 
4234 	usage = mem_cgroup_usage(memcg, swap);
4235 
4236 	/*
4237 	 * current_threshold points to threshold just below or equal to usage.
4238 	 * If it's not true, a threshold was crossed after last
4239 	 * call of __mem_cgroup_threshold().
4240 	 */
4241 	i = t->current_threshold;
4242 
4243 	/*
4244 	 * Iterate backward over array of thresholds starting from
4245 	 * current_threshold and check if a threshold is crossed.
4246 	 * If none of thresholds below usage is crossed, we read
4247 	 * only one element of the array here.
4248 	 */
4249 	for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4250 		eventfd_signal(t->entries[i].eventfd, 1);
4251 
4252 	/* i = current_threshold + 1 */
4253 	i++;
4254 
4255 	/*
4256 	 * Iterate forward over array of thresholds starting from
4257 	 * current_threshold+1 and check if a threshold is crossed.
4258 	 * If none of thresholds above usage is crossed, we read
4259 	 * only one element of the array here.
4260 	 */
4261 	for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4262 		eventfd_signal(t->entries[i].eventfd, 1);
4263 
4264 	/* Update current_threshold */
4265 	t->current_threshold = i - 1;
4266 unlock:
4267 	rcu_read_unlock();
4268 }
4269 
mem_cgroup_threshold(struct mem_cgroup * memcg)4270 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4271 {
4272 	while (memcg) {
4273 		__mem_cgroup_threshold(memcg, false);
4274 		if (do_memsw_account())
4275 			__mem_cgroup_threshold(memcg, true);
4276 
4277 		memcg = parent_mem_cgroup(memcg);
4278 	}
4279 }
4280 
compare_thresholds(const void * a,const void * b)4281 static int compare_thresholds(const void *a, const void *b)
4282 {
4283 	const struct mem_cgroup_threshold *_a = a;
4284 	const struct mem_cgroup_threshold *_b = b;
4285 
4286 	if (_a->threshold > _b->threshold)
4287 		return 1;
4288 
4289 	if (_a->threshold < _b->threshold)
4290 		return -1;
4291 
4292 	return 0;
4293 }
4294 
mem_cgroup_oom_notify_cb(struct mem_cgroup * memcg)4295 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
4296 {
4297 	struct mem_cgroup_eventfd_list *ev;
4298 
4299 	spin_lock(&memcg_oom_lock);
4300 
4301 	list_for_each_entry(ev, &memcg->oom_notify, list)
4302 		eventfd_signal(ev->eventfd, 1);
4303 
4304 	spin_unlock(&memcg_oom_lock);
4305 	return 0;
4306 }
4307 
mem_cgroup_oom_notify(struct mem_cgroup * memcg)4308 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
4309 {
4310 	struct mem_cgroup *iter;
4311 
4312 	for_each_mem_cgroup_tree(iter, memcg)
4313 		mem_cgroup_oom_notify_cb(iter);
4314 }
4315 
__mem_cgroup_usage_register_event(struct mem_cgroup * memcg,struct eventfd_ctx * eventfd,const char * args,enum res_type type)4316 static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4317 	struct eventfd_ctx *eventfd, const char *args, enum res_type type)
4318 {
4319 	struct mem_cgroup_thresholds *thresholds;
4320 	struct mem_cgroup_threshold_ary *new;
4321 	unsigned long threshold;
4322 	unsigned long usage;
4323 	int i, size, ret;
4324 
4325 	ret = page_counter_memparse(args, "-1", &threshold);
4326 	if (ret)
4327 		return ret;
4328 
4329 	mutex_lock(&memcg->thresholds_lock);
4330 
4331 	if (type == _MEM) {
4332 		thresholds = &memcg->thresholds;
4333 		usage = mem_cgroup_usage(memcg, false);
4334 	} else if (type == _MEMSWAP) {
4335 		thresholds = &memcg->memsw_thresholds;
4336 		usage = mem_cgroup_usage(memcg, true);
4337 	} else
4338 		BUG();
4339 
4340 	/* Check if a threshold crossed before adding a new one */
4341 	if (thresholds->primary)
4342 		__mem_cgroup_threshold(memcg, type == _MEMSWAP);
4343 
4344 	size = thresholds->primary ? thresholds->primary->size + 1 : 1;
4345 
4346 	/* Allocate memory for new array of thresholds */
4347 	new = kmalloc(struct_size(new, entries, size), GFP_KERNEL);
4348 	if (!new) {
4349 		ret = -ENOMEM;
4350 		goto unlock;
4351 	}
4352 	new->size = size;
4353 
4354 	/* Copy thresholds (if any) to new array */
4355 	if (thresholds->primary)
4356 		memcpy(new->entries, thresholds->primary->entries,
4357 		       flex_array_size(new, entries, size - 1));
4358 
4359 	/* Add new threshold */
4360 	new->entries[size - 1].eventfd = eventfd;
4361 	new->entries[size - 1].threshold = threshold;
4362 
4363 	/* Sort thresholds. Registering of new threshold isn't time-critical */
4364 	sort(new->entries, size, sizeof(*new->entries),
4365 			compare_thresholds, NULL);
4366 
4367 	/* Find current threshold */
4368 	new->current_threshold = -1;
4369 	for (i = 0; i < size; i++) {
4370 		if (new->entries[i].threshold <= usage) {
4371 			/*
4372 			 * new->current_threshold will not be used until
4373 			 * rcu_assign_pointer(), so it's safe to increment
4374 			 * it here.
4375 			 */
4376 			++new->current_threshold;
4377 		} else
4378 			break;
4379 	}
4380 
4381 	/* Free old spare buffer and save old primary buffer as spare */
4382 	kfree(thresholds->spare);
4383 	thresholds->spare = thresholds->primary;
4384 
4385 	rcu_assign_pointer(thresholds->primary, new);
4386 
4387 	/* To be sure that nobody uses thresholds */
4388 	synchronize_rcu();
4389 
4390 unlock:
4391 	mutex_unlock(&memcg->thresholds_lock);
4392 
4393 	return ret;
4394 }
4395 
mem_cgroup_usage_register_event(struct mem_cgroup * memcg,struct eventfd_ctx * eventfd,const char * args)4396 static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4397 	struct eventfd_ctx *eventfd, const char *args)
4398 {
4399 	return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
4400 }
4401 
memsw_cgroup_usage_register_event(struct mem_cgroup * memcg,struct eventfd_ctx * eventfd,const char * args)4402 static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
4403 	struct eventfd_ctx *eventfd, const char *args)
4404 {
4405 	return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
4406 }
4407 
__mem_cgroup_usage_unregister_event(struct mem_cgroup * memcg,struct eventfd_ctx * eventfd,enum res_type type)4408 static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4409 	struct eventfd_ctx *eventfd, enum res_type type)
4410 {
4411 	struct mem_cgroup_thresholds *thresholds;
4412 	struct mem_cgroup_threshold_ary *new;
4413 	unsigned long usage;
4414 	int i, j, size, entries;
4415 
4416 	mutex_lock(&memcg->thresholds_lock);
4417 
4418 	if (type == _MEM) {
4419 		thresholds = &memcg->thresholds;
4420 		usage = mem_cgroup_usage(memcg, false);
4421 	} else if (type == _MEMSWAP) {
4422 		thresholds = &memcg->memsw_thresholds;
4423 		usage = mem_cgroup_usage(memcg, true);
4424 	} else
4425 		BUG();
4426 
4427 	if (!thresholds->primary)
4428 		goto unlock;
4429 
4430 	/* Check if a threshold crossed before removing */
4431 	__mem_cgroup_threshold(memcg, type == _MEMSWAP);
4432 
4433 	/* Calculate new number of threshold */
4434 	size = entries = 0;
4435 	for (i = 0; i < thresholds->primary->size; i++) {
4436 		if (thresholds->primary->entries[i].eventfd != eventfd)
4437 			size++;
4438 		else
4439 			entries++;
4440 	}
4441 
4442 	new = thresholds->spare;
4443 
4444 	/* If no items related to eventfd have been cleared, nothing to do */
4445 	if (!entries)
4446 		goto unlock;
4447 
4448 	/* Set thresholds array to NULL if we don't have thresholds */
4449 	if (!size) {
4450 		kfree(new);
4451 		new = NULL;
4452 		goto swap_buffers;
4453 	}
4454 
4455 	new->size = size;
4456 
4457 	/* Copy thresholds and find current threshold */
4458 	new->current_threshold = -1;
4459 	for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4460 		if (thresholds->primary->entries[i].eventfd == eventfd)
4461 			continue;
4462 
4463 		new->entries[j] = thresholds->primary->entries[i];
4464 		if (new->entries[j].threshold <= usage) {
4465 			/*
4466 			 * new->current_threshold will not be used
4467 			 * until rcu_assign_pointer(), so it's safe to increment
4468 			 * it here.
4469 			 */
4470 			++new->current_threshold;
4471 		}
4472 		j++;
4473 	}
4474 
4475 swap_buffers:
4476 	/* Swap primary and spare array */
4477 	thresholds->spare = thresholds->primary;
4478 
4479 	rcu_assign_pointer(thresholds->primary, new);
4480 
4481 	/* To be sure that nobody uses thresholds */
4482 	synchronize_rcu();
4483 
4484 	/* If all events are unregistered, free the spare array */
4485 	if (!new) {
4486 		kfree(thresholds->spare);
4487 		thresholds->spare = NULL;
4488 	}
4489 unlock:
4490 	mutex_unlock(&memcg->thresholds_lock);
4491 }
4492 
mem_cgroup_usage_unregister_event(struct mem_cgroup * memcg,struct eventfd_ctx * eventfd)4493 static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4494 	struct eventfd_ctx *eventfd)
4495 {
4496 	return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
4497 }
4498 
memsw_cgroup_usage_unregister_event(struct mem_cgroup * memcg,struct eventfd_ctx * eventfd)4499 static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4500 	struct eventfd_ctx *eventfd)
4501 {
4502 	return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
4503 }
4504 
mem_cgroup_oom_register_event(struct mem_cgroup * memcg,struct eventfd_ctx * eventfd,const char * args)4505 static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
4506 	struct eventfd_ctx *eventfd, const char *args)
4507 {
4508 	struct mem_cgroup_eventfd_list *event;
4509 
4510 	event = kmalloc(sizeof(*event),	GFP_KERNEL);
4511 	if (!event)
4512 		return -ENOMEM;
4513 
4514 	spin_lock(&memcg_oom_lock);
4515 
4516 	event->eventfd = eventfd;
4517 	list_add(&event->list, &memcg->oom_notify);
4518 
4519 	/* already in OOM ? */
4520 	if (memcg->under_oom)
4521 		eventfd_signal(eventfd, 1);
4522 	spin_unlock(&memcg_oom_lock);
4523 
4524 	return 0;
4525 }
4526 
mem_cgroup_oom_unregister_event(struct mem_cgroup * memcg,struct eventfd_ctx * eventfd)4527 static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
4528 	struct eventfd_ctx *eventfd)
4529 {
4530 	struct mem_cgroup_eventfd_list *ev, *tmp;
4531 
4532 	spin_lock(&memcg_oom_lock);
4533 
4534 	list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
4535 		if (ev->eventfd == eventfd) {
4536 			list_del(&ev->list);
4537 			kfree(ev);
4538 		}
4539 	}
4540 
4541 	spin_unlock(&memcg_oom_lock);
4542 }
4543 
mem_cgroup_oom_control_read(struct seq_file * sf,void * v)4544 static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
4545 {
4546 	struct mem_cgroup *memcg = mem_cgroup_from_seq(sf);
4547 
4548 	seq_printf(sf, "oom_kill_disable %d\n", memcg->oom_kill_disable);
4549 	seq_printf(sf, "under_oom %d\n", (bool)memcg->under_oom);
4550 	seq_printf(sf, "oom_kill %lu\n",
4551 		   atomic_long_read(&memcg->memory_events[MEMCG_OOM_KILL]));
4552 	return 0;
4553 }
4554 
mem_cgroup_oom_control_write(struct cgroup_subsys_state * css,struct cftype * cft,u64 val)4555 static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
4556 	struct cftype *cft, u64 val)
4557 {
4558 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4559 
4560 	/* cannot set to root cgroup and only 0 and 1 are allowed */
4561 	if (!css->parent || !((val == 0) || (val == 1)))
4562 		return -EINVAL;
4563 
4564 	memcg->oom_kill_disable = val;
4565 	if (!val)
4566 		memcg_oom_recover(memcg);
4567 
4568 	return 0;
4569 }
4570 
4571 #ifdef CONFIG_CGROUP_WRITEBACK
4572 
4573 #include <trace/events/writeback.h>
4574 
memcg_wb_domain_init(struct mem_cgroup * memcg,gfp_t gfp)4575 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4576 {
4577 	return wb_domain_init(&memcg->cgwb_domain, gfp);
4578 }
4579 
memcg_wb_domain_exit(struct mem_cgroup * memcg)4580 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4581 {
4582 	wb_domain_exit(&memcg->cgwb_domain);
4583 }
4584 
memcg_wb_domain_size_changed(struct mem_cgroup * memcg)4585 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4586 {
4587 	wb_domain_size_changed(&memcg->cgwb_domain);
4588 }
4589 
mem_cgroup_wb_domain(struct bdi_writeback * wb)4590 struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb)
4591 {
4592 	struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4593 
4594 	if (!memcg->css.parent)
4595 		return NULL;
4596 
4597 	return &memcg->cgwb_domain;
4598 }
4599 
4600 /*
4601  * idx can be of type enum memcg_stat_item or node_stat_item.
4602  * Keep in sync with memcg_exact_page().
4603  */
memcg_exact_page_state(struct mem_cgroup * memcg,int idx)4604 static unsigned long memcg_exact_page_state(struct mem_cgroup *memcg, int idx)
4605 {
4606 	long x = atomic_long_read(&memcg->vmstats[idx]);
4607 	int cpu;
4608 
4609 	for_each_online_cpu(cpu)
4610 		x += per_cpu_ptr(memcg->vmstats_percpu, cpu)->stat[idx];
4611 	if (x < 0)
4612 		x = 0;
4613 	return x;
4614 }
4615 
4616 /**
4617  * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
4618  * @wb: bdi_writeback in question
4619  * @pfilepages: out parameter for number of file pages
4620  * @pheadroom: out parameter for number of allocatable pages according to memcg
4621  * @pdirty: out parameter for number of dirty pages
4622  * @pwriteback: out parameter for number of pages under writeback
4623  *
4624  * Determine the numbers of file, headroom, dirty, and writeback pages in
4625  * @wb's memcg.  File, dirty and writeback are self-explanatory.  Headroom
4626  * is a bit more involved.
4627  *
4628  * A memcg's headroom is "min(max, high) - used".  In the hierarchy, the
4629  * headroom is calculated as the lowest headroom of itself and the
4630  * ancestors.  Note that this doesn't consider the actual amount of
4631  * available memory in the system.  The caller should further cap
4632  * *@pheadroom accordingly.
4633  */
mem_cgroup_wb_stats(struct bdi_writeback * wb,unsigned long * pfilepages,unsigned long * pheadroom,unsigned long * pdirty,unsigned long * pwriteback)4634 void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages,
4635 			 unsigned long *pheadroom, unsigned long *pdirty,
4636 			 unsigned long *pwriteback)
4637 {
4638 	struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4639 	struct mem_cgroup *parent;
4640 
4641 	*pdirty = memcg_exact_page_state(memcg, NR_FILE_DIRTY);
4642 
4643 	*pwriteback = memcg_exact_page_state(memcg, NR_WRITEBACK);
4644 	*pfilepages = memcg_exact_page_state(memcg, NR_INACTIVE_FILE) +
4645 			memcg_exact_page_state(memcg, NR_ACTIVE_FILE);
4646 	*pheadroom = PAGE_COUNTER_MAX;
4647 
4648 	while ((parent = parent_mem_cgroup(memcg))) {
4649 		unsigned long ceiling = min(READ_ONCE(memcg->memory.max),
4650 					    READ_ONCE(memcg->memory.high));
4651 		unsigned long used = page_counter_read(&memcg->memory);
4652 
4653 		*pheadroom = min(*pheadroom, ceiling - min(ceiling, used));
4654 		memcg = parent;
4655 	}
4656 }
4657 
4658 /*
4659  * Foreign dirty flushing
4660  *
4661  * There's an inherent mismatch between memcg and writeback.  The former
4662  * trackes ownership per-page while the latter per-inode.  This was a
4663  * deliberate design decision because honoring per-page ownership in the
4664  * writeback path is complicated, may lead to higher CPU and IO overheads
4665  * and deemed unnecessary given that write-sharing an inode across
4666  * different cgroups isn't a common use-case.
4667  *
4668  * Combined with inode majority-writer ownership switching, this works well
4669  * enough in most cases but there are some pathological cases.  For
4670  * example, let's say there are two cgroups A and B which keep writing to
4671  * different but confined parts of the same inode.  B owns the inode and
4672  * A's memory is limited far below B's.  A's dirty ratio can rise enough to
4673  * trigger balance_dirty_pages() sleeps but B's can be low enough to avoid
4674  * triggering background writeback.  A will be slowed down without a way to
4675  * make writeback of the dirty pages happen.
4676  *
4677  * Conditions like the above can lead to a cgroup getting repatedly and
4678  * severely throttled after making some progress after each
4679  * dirty_expire_interval while the underyling IO device is almost
4680  * completely idle.
4681  *
4682  * Solving this problem completely requires matching the ownership tracking
4683  * granularities between memcg and writeback in either direction.  However,
4684  * the more egregious behaviors can be avoided by simply remembering the
4685  * most recent foreign dirtying events and initiating remote flushes on
4686  * them when local writeback isn't enough to keep the memory clean enough.
4687  *
4688  * The following two functions implement such mechanism.  When a foreign
4689  * page - a page whose memcg and writeback ownerships don't match - is
4690  * dirtied, mem_cgroup_track_foreign_dirty() records the inode owning
4691  * bdi_writeback on the page owning memcg.  When balance_dirty_pages()
4692  * decides that the memcg needs to sleep due to high dirty ratio, it calls
4693  * mem_cgroup_flush_foreign() which queues writeback on the recorded
4694  * foreign bdi_writebacks which haven't expired.  Both the numbers of
4695  * recorded bdi_writebacks and concurrent in-flight foreign writebacks are
4696  * limited to MEMCG_CGWB_FRN_CNT.
4697  *
4698  * The mechanism only remembers IDs and doesn't hold any object references.
4699  * As being wrong occasionally doesn't matter, updates and accesses to the
4700  * records are lockless and racy.
4701  */
mem_cgroup_track_foreign_dirty_slowpath(struct page * page,struct bdi_writeback * wb)4702 void mem_cgroup_track_foreign_dirty_slowpath(struct page *page,
4703 					     struct bdi_writeback *wb)
4704 {
4705 	struct mem_cgroup *memcg = page->mem_cgroup;
4706 	struct memcg_cgwb_frn *frn;
4707 	u64 now = get_jiffies_64();
4708 	u64 oldest_at = now;
4709 	int oldest = -1;
4710 	int i;
4711 
4712 	trace_track_foreign_dirty(page, wb);
4713 
4714 	/*
4715 	 * Pick the slot to use.  If there is already a slot for @wb, keep
4716 	 * using it.  If not replace the oldest one which isn't being
4717 	 * written out.
4718 	 */
4719 	for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4720 		frn = &memcg->cgwb_frn[i];
4721 		if (frn->bdi_id == wb->bdi->id &&
4722 		    frn->memcg_id == wb->memcg_css->id)
4723 			break;
4724 		if (time_before64(frn->at, oldest_at) &&
4725 		    atomic_read(&frn->done.cnt) == 1) {
4726 			oldest = i;
4727 			oldest_at = frn->at;
4728 		}
4729 	}
4730 
4731 	if (i < MEMCG_CGWB_FRN_CNT) {
4732 		/*
4733 		 * Re-using an existing one.  Update timestamp lazily to
4734 		 * avoid making the cacheline hot.  We want them to be
4735 		 * reasonably up-to-date and significantly shorter than
4736 		 * dirty_expire_interval as that's what expires the record.
4737 		 * Use the shorter of 1s and dirty_expire_interval / 8.
4738 		 */
4739 		unsigned long update_intv =
4740 			min_t(unsigned long, HZ,
4741 			      msecs_to_jiffies(dirty_expire_interval * 10) / 8);
4742 
4743 		if (time_before64(frn->at, now - update_intv))
4744 			frn->at = now;
4745 	} else if (oldest >= 0) {
4746 		/* replace the oldest free one */
4747 		frn = &memcg->cgwb_frn[oldest];
4748 		frn->bdi_id = wb->bdi->id;
4749 		frn->memcg_id = wb->memcg_css->id;
4750 		frn->at = now;
4751 	}
4752 }
4753 
4754 /* issue foreign writeback flushes for recorded foreign dirtying events */
mem_cgroup_flush_foreign(struct bdi_writeback * wb)4755 void mem_cgroup_flush_foreign(struct bdi_writeback *wb)
4756 {
4757 	struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4758 	unsigned long intv = msecs_to_jiffies(dirty_expire_interval * 10);
4759 	u64 now = jiffies_64;
4760 	int i;
4761 
4762 	for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4763 		struct memcg_cgwb_frn *frn = &memcg->cgwb_frn[i];
4764 
4765 		/*
4766 		 * If the record is older than dirty_expire_interval,
4767 		 * writeback on it has already started.  No need to kick it
4768 		 * off again.  Also, don't start a new one if there's
4769 		 * already one in flight.
4770 		 */
4771 		if (time_after64(frn->at, now - intv) &&
4772 		    atomic_read(&frn->done.cnt) == 1) {
4773 			frn->at = 0;
4774 			trace_flush_foreign(wb, frn->bdi_id, frn->memcg_id);
4775 			cgroup_writeback_by_id(frn->bdi_id, frn->memcg_id, 0,
4776 					       WB_REASON_FOREIGN_FLUSH,
4777 					       &frn->done);
4778 		}
4779 	}
4780 }
4781 
4782 #else	/* CONFIG_CGROUP_WRITEBACK */
4783 
memcg_wb_domain_init(struct mem_cgroup * memcg,gfp_t gfp)4784 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4785 {
4786 	return 0;
4787 }
4788 
memcg_wb_domain_exit(struct mem_cgroup * memcg)4789 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4790 {
4791 }
4792 
memcg_wb_domain_size_changed(struct mem_cgroup * memcg)4793 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4794 {
4795 }
4796 
4797 #endif	/* CONFIG_CGROUP_WRITEBACK */
4798 
4799 /*
4800  * DO NOT USE IN NEW FILES.
4801  *
4802  * "cgroup.event_control" implementation.
4803  *
4804  * This is way over-engineered.  It tries to support fully configurable
4805  * events for each user.  Such level of flexibility is completely
4806  * unnecessary especially in the light of the planned unified hierarchy.
4807  *
4808  * Please deprecate this and replace with something simpler if at all
4809  * possible.
4810  */
4811 
4812 /*
4813  * Unregister event and free resources.
4814  *
4815  * Gets called from workqueue.
4816  */
memcg_event_remove(struct work_struct * work)4817 static void memcg_event_remove(struct work_struct *work)
4818 {
4819 	struct mem_cgroup_event *event =
4820 		container_of(work, struct mem_cgroup_event, remove);
4821 	struct mem_cgroup *memcg = event->memcg;
4822 
4823 	remove_wait_queue(event->wqh, &event->wait);
4824 
4825 	event->unregister_event(memcg, event->eventfd);
4826 
4827 	/* Notify userspace the event is going away. */
4828 	eventfd_signal(event->eventfd, 1);
4829 
4830 	eventfd_ctx_put(event->eventfd);
4831 	kfree(event);
4832 	css_put(&memcg->css);
4833 }
4834 
4835 /*
4836  * Gets called on EPOLLHUP on eventfd when user closes it.
4837  *
4838  * Called with wqh->lock held and interrupts disabled.
4839  */
memcg_event_wake(wait_queue_entry_t * wait,unsigned mode,int sync,void * key)4840 static int memcg_event_wake(wait_queue_entry_t *wait, unsigned mode,
4841 			    int sync, void *key)
4842 {
4843 	struct mem_cgroup_event *event =
4844 		container_of(wait, struct mem_cgroup_event, wait);
4845 	struct mem_cgroup *memcg = event->memcg;
4846 	__poll_t flags = key_to_poll(key);
4847 
4848 	if (flags & EPOLLHUP) {
4849 		/*
4850 		 * If the event has been detached at cgroup removal, we
4851 		 * can simply return knowing the other side will cleanup
4852 		 * for us.
4853 		 *
4854 		 * We can't race against event freeing since the other
4855 		 * side will require wqh->lock via remove_wait_queue(),
4856 		 * which we hold.
4857 		 */
4858 		spin_lock(&memcg->event_list_lock);
4859 		if (!list_empty(&event->list)) {
4860 			list_del_init(&event->list);
4861 			/*
4862 			 * We are in atomic context, but cgroup_event_remove()
4863 			 * may sleep, so we have to call it in workqueue.
4864 			 */
4865 			schedule_work(&event->remove);
4866 		}
4867 		spin_unlock(&memcg->event_list_lock);
4868 	}
4869 
4870 	return 0;
4871 }
4872 
memcg_event_ptable_queue_proc(struct file * file,wait_queue_head_t * wqh,poll_table * pt)4873 static void memcg_event_ptable_queue_proc(struct file *file,
4874 		wait_queue_head_t *wqh, poll_table *pt)
4875 {
4876 	struct mem_cgroup_event *event =
4877 		container_of(pt, struct mem_cgroup_event, pt);
4878 
4879 	event->wqh = wqh;
4880 	add_wait_queue(wqh, &event->wait);
4881 }
4882 
4883 /*
4884  * DO NOT USE IN NEW FILES.
4885  *
4886  * Parse input and register new cgroup event handler.
4887  *
4888  * Input must be in format '<event_fd> <control_fd> <args>'.
4889  * Interpretation of args is defined by control file implementation.
4890  */
memcg_write_event_control(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)4891 static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
4892 					 char *buf, size_t nbytes, loff_t off)
4893 {
4894 	struct cgroup_subsys_state *css = of_css(of);
4895 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4896 	struct mem_cgroup_event *event;
4897 	struct cgroup_subsys_state *cfile_css;
4898 	unsigned int efd, cfd;
4899 	struct fd efile;
4900 	struct fd cfile;
4901 	const char *name;
4902 	char *endp;
4903 	int ret;
4904 
4905 	buf = strstrip(buf);
4906 
4907 	efd = simple_strtoul(buf, &endp, 10);
4908 	if (*endp != ' ')
4909 		return -EINVAL;
4910 	buf = endp + 1;
4911 
4912 	cfd = simple_strtoul(buf, &endp, 10);
4913 	if ((*endp != ' ') && (*endp != '\0'))
4914 		return -EINVAL;
4915 	buf = endp + 1;
4916 
4917 	event = kzalloc(sizeof(*event), GFP_KERNEL);
4918 	if (!event)
4919 		return -ENOMEM;
4920 
4921 	event->memcg = memcg;
4922 	INIT_LIST_HEAD(&event->list);
4923 	init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
4924 	init_waitqueue_func_entry(&event->wait, memcg_event_wake);
4925 	INIT_WORK(&event->remove, memcg_event_remove);
4926 
4927 	efile = fdget(efd);
4928 	if (!efile.file) {
4929 		ret = -EBADF;
4930 		goto out_kfree;
4931 	}
4932 
4933 	event->eventfd = eventfd_ctx_fileget(efile.file);
4934 	if (IS_ERR(event->eventfd)) {
4935 		ret = PTR_ERR(event->eventfd);
4936 		goto out_put_efile;
4937 	}
4938 
4939 	cfile = fdget(cfd);
4940 	if (!cfile.file) {
4941 		ret = -EBADF;
4942 		goto out_put_eventfd;
4943 	}
4944 
4945 	/* the process need read permission on control file */
4946 	/* AV: shouldn't we check that it's been opened for read instead? */
4947 	ret = inode_permission(file_inode(cfile.file), MAY_READ);
4948 	if (ret < 0)
4949 		goto out_put_cfile;
4950 
4951 	/*
4952 	 * Determine the event callbacks and set them in @event.  This used
4953 	 * to be done via struct cftype but cgroup core no longer knows
4954 	 * about these events.  The following is crude but the whole thing
4955 	 * is for compatibility anyway.
4956 	 *
4957 	 * DO NOT ADD NEW FILES.
4958 	 */
4959 	name = cfile.file->f_path.dentry->d_name.name;
4960 
4961 	if (!strcmp(name, "memory.usage_in_bytes")) {
4962 		event->register_event = mem_cgroup_usage_register_event;
4963 		event->unregister_event = mem_cgroup_usage_unregister_event;
4964 	} else if (!strcmp(name, "memory.oom_control")) {
4965 		event->register_event = mem_cgroup_oom_register_event;
4966 		event->unregister_event = mem_cgroup_oom_unregister_event;
4967 	} else if (!strcmp(name, "memory.pressure_level")) {
4968 		event->register_event = vmpressure_register_event;
4969 		event->unregister_event = vmpressure_unregister_event;
4970 	} else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
4971 		event->register_event = memsw_cgroup_usage_register_event;
4972 		event->unregister_event = memsw_cgroup_usage_unregister_event;
4973 	} else {
4974 		ret = -EINVAL;
4975 		goto out_put_cfile;
4976 	}
4977 
4978 	/*
4979 	 * Verify @cfile should belong to @css.  Also, remaining events are
4980 	 * automatically removed on cgroup destruction but the removal is
4981 	 * asynchronous, so take an extra ref on @css.
4982 	 */
4983 	cfile_css = css_tryget_online_from_dir(cfile.file->f_path.dentry->d_parent,
4984 					       &memory_cgrp_subsys);
4985 	ret = -EINVAL;
4986 	if (IS_ERR(cfile_css))
4987 		goto out_put_cfile;
4988 	if (cfile_css != css) {
4989 		css_put(cfile_css);
4990 		goto out_put_cfile;
4991 	}
4992 
4993 	ret = event->register_event(memcg, event->eventfd, buf);
4994 	if (ret)
4995 		goto out_put_css;
4996 
4997 	vfs_poll(efile.file, &event->pt);
4998 
4999 	spin_lock(&memcg->event_list_lock);
5000 	list_add(&event->list, &memcg->event_list);
5001 	spin_unlock(&memcg->event_list_lock);
5002 
5003 	fdput(cfile);
5004 	fdput(efile);
5005 
5006 	return nbytes;
5007 
5008 out_put_css:
5009 	css_put(css);
5010 out_put_cfile:
5011 	fdput(cfile);
5012 out_put_eventfd:
5013 	eventfd_ctx_put(event->eventfd);
5014 out_put_efile:
5015 	fdput(efile);
5016 out_kfree:
5017 	kfree(event);
5018 
5019 	return ret;
5020 }
5021 
5022 static struct cftype mem_cgroup_legacy_files[] = {
5023 	{
5024 		.name = "usage_in_bytes",
5025 		.private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
5026 		.read_u64 = mem_cgroup_read_u64,
5027 	},
5028 	{
5029 		.name = "max_usage_in_bytes",
5030 		.private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
5031 		.write = mem_cgroup_reset,
5032 		.read_u64 = mem_cgroup_read_u64,
5033 	},
5034 	{
5035 		.name = "limit_in_bytes",
5036 		.private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
5037 		.write = mem_cgroup_write,
5038 		.read_u64 = mem_cgroup_read_u64,
5039 	},
5040 	{
5041 		.name = "soft_limit_in_bytes",
5042 		.private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
5043 		.write = mem_cgroup_write,
5044 		.read_u64 = mem_cgroup_read_u64,
5045 	},
5046 	{
5047 		.name = "failcnt",
5048 		.private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
5049 		.write = mem_cgroup_reset,
5050 		.read_u64 = mem_cgroup_read_u64,
5051 	},
5052 	{
5053 		.name = "stat",
5054 		.seq_show = memcg_stat_show,
5055 	},
5056 	{
5057 		.name = "force_empty",
5058 		.write = mem_cgroup_force_empty_write,
5059 	},
5060 	{
5061 		.name = "use_hierarchy",
5062 		.write_u64 = mem_cgroup_hierarchy_write,
5063 		.read_u64 = mem_cgroup_hierarchy_read,
5064 	},
5065 	{
5066 		.name = "cgroup.event_control",		/* XXX: for compat */
5067 		.write = memcg_write_event_control,
5068 		.flags = CFTYPE_NO_PREFIX | CFTYPE_WORLD_WRITABLE,
5069 	},
5070 	{
5071 		.name = "swappiness",
5072 		.read_u64 = mem_cgroup_swappiness_read,
5073 		.write_u64 = mem_cgroup_swappiness_write,
5074 	},
5075 	{
5076 		.name = "move_charge_at_immigrate",
5077 		.read_u64 = mem_cgroup_move_charge_read,
5078 		.write_u64 = mem_cgroup_move_charge_write,
5079 	},
5080 	{
5081 		.name = "oom_control",
5082 		.seq_show = mem_cgroup_oom_control_read,
5083 		.write_u64 = mem_cgroup_oom_control_write,
5084 		.private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
5085 	},
5086 	{
5087 		.name = "pressure_level",
5088 	},
5089 #ifdef CONFIG_NUMA
5090 	{
5091 		.name = "numa_stat",
5092 		.seq_show = memcg_numa_stat_show,
5093 	},
5094 #endif
5095 	{
5096 		.name = "kmem.limit_in_bytes",
5097 		.private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
5098 		.write = mem_cgroup_write,
5099 		.read_u64 = mem_cgroup_read_u64,
5100 	},
5101 	{
5102 		.name = "kmem.usage_in_bytes",
5103 		.private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
5104 		.read_u64 = mem_cgroup_read_u64,
5105 	},
5106 	{
5107 		.name = "kmem.failcnt",
5108 		.private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
5109 		.write = mem_cgroup_reset,
5110 		.read_u64 = mem_cgroup_read_u64,
5111 	},
5112 	{
5113 		.name = "kmem.max_usage_in_bytes",
5114 		.private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
5115 		.write = mem_cgroup_reset,
5116 		.read_u64 = mem_cgroup_read_u64,
5117 	},
5118 #if defined(CONFIG_MEMCG_KMEM) && \
5119 	(defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG))
5120 	{
5121 		.name = "kmem.slabinfo",
5122 		.seq_show = memcg_slab_show,
5123 	},
5124 #endif
5125 	{
5126 		.name = "kmem.tcp.limit_in_bytes",
5127 		.private = MEMFILE_PRIVATE(_TCP, RES_LIMIT),
5128 		.write = mem_cgroup_write,
5129 		.read_u64 = mem_cgroup_read_u64,
5130 	},
5131 	{
5132 		.name = "kmem.tcp.usage_in_bytes",
5133 		.private = MEMFILE_PRIVATE(_TCP, RES_USAGE),
5134 		.read_u64 = mem_cgroup_read_u64,
5135 	},
5136 	{
5137 		.name = "kmem.tcp.failcnt",
5138 		.private = MEMFILE_PRIVATE(_TCP, RES_FAILCNT),
5139 		.write = mem_cgroup_reset,
5140 		.read_u64 = mem_cgroup_read_u64,
5141 	},
5142 	{
5143 		.name = "kmem.tcp.max_usage_in_bytes",
5144 		.private = MEMFILE_PRIVATE(_TCP, RES_MAX_USAGE),
5145 		.write = mem_cgroup_reset,
5146 		.read_u64 = mem_cgroup_read_u64,
5147 	},
5148 	{ },	/* terminate */
5149 };
5150 
5151 /*
5152  * Private memory cgroup IDR
5153  *
5154  * Swap-out records and page cache shadow entries need to store memcg
5155  * references in constrained space, so we maintain an ID space that is
5156  * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of
5157  * memory-controlled cgroups to 64k.
5158  *
5159  * However, there usually are many references to the offline CSS after
5160  * the cgroup has been destroyed, such as page cache or reclaimable
5161  * slab objects, that don't need to hang on to the ID. We want to keep
5162  * those dead CSS from occupying IDs, or we might quickly exhaust the
5163  * relatively small ID space and prevent the creation of new cgroups
5164  * even when there are much fewer than 64k cgroups - possibly none.
5165  *
5166  * Maintain a private 16-bit ID space for memcg, and allow the ID to
5167  * be freed and recycled when it's no longer needed, which is usually
5168  * when the CSS is offlined.
5169  *
5170  * The only exception to that are records of swapped out tmpfs/shmem
5171  * pages that need to be attributed to live ancestors on swapin. But
5172  * those references are manageable from userspace.
5173  */
5174 
5175 static DEFINE_IDR(mem_cgroup_idr);
5176 
mem_cgroup_id_remove(struct mem_cgroup * memcg)5177 static void mem_cgroup_id_remove(struct mem_cgroup *memcg)
5178 {
5179 	if (memcg->id.id > 0) {
5180 		idr_remove(&mem_cgroup_idr, memcg->id.id);
5181 		memcg->id.id = 0;
5182 	}
5183 }
5184 
mem_cgroup_id_get_many(struct mem_cgroup * memcg,unsigned int n)5185 static void __maybe_unused mem_cgroup_id_get_many(struct mem_cgroup *memcg,
5186 						  unsigned int n)
5187 {
5188 	refcount_add(n, &memcg->id.ref);
5189 }
5190 
mem_cgroup_id_put_many(struct mem_cgroup * memcg,unsigned int n)5191 static void mem_cgroup_id_put_many(struct mem_cgroup *memcg, unsigned int n)
5192 {
5193 	if (refcount_sub_and_test(n, &memcg->id.ref)) {
5194 		mem_cgroup_id_remove(memcg);
5195 
5196 		/* Memcg ID pins CSS */
5197 		css_put(&memcg->css);
5198 	}
5199 }
5200 
mem_cgroup_id_put(struct mem_cgroup * memcg)5201 static inline void mem_cgroup_id_put(struct mem_cgroup *memcg)
5202 {
5203 	mem_cgroup_id_put_many(memcg, 1);
5204 }
5205 
5206 /**
5207  * mem_cgroup_from_id - look up a memcg from a memcg id
5208  * @id: the memcg id to look up
5209  *
5210  * Caller must hold rcu_read_lock().
5211  */
mem_cgroup_from_id(unsigned short id)5212 struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
5213 {
5214 	WARN_ON_ONCE(!rcu_read_lock_held());
5215 #ifdef CONFIG_HYPERHOLD_FILE_LRU
5216 	if (id == -1)
5217 		return NULL;
5218 #endif
5219 	return idr_find(&mem_cgroup_idr, id);
5220 }
5221 
alloc_mem_cgroup_per_node_info(struct mem_cgroup * memcg,int node)5222 static int alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5223 {
5224 	struct mem_cgroup_per_node *pn;
5225 	int tmp = node;
5226 	/*
5227 	 * This routine is called against possible nodes.
5228 	 * But it's BUG to call kmalloc() against offline node.
5229 	 *
5230 	 * TODO: this routine can waste much memory for nodes which will
5231 	 *       never be onlined. It's better to use memory hotplug callback
5232 	 *       function.
5233 	 */
5234 	if (!node_state(node, N_NORMAL_MEMORY))
5235 		tmp = -1;
5236 	pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
5237 	if (!pn)
5238 		return 1;
5239 
5240 	pn->lruvec_stat_local = alloc_percpu_gfp(struct lruvec_stat,
5241 						 GFP_KERNEL_ACCOUNT);
5242 	if (!pn->lruvec_stat_local) {
5243 		kfree(pn);
5244 		return 1;
5245 	}
5246 
5247 	pn->lruvec_stat_cpu = alloc_percpu_gfp(struct lruvec_stat,
5248 					       GFP_KERNEL_ACCOUNT);
5249 	if (!pn->lruvec_stat_cpu) {
5250 		free_percpu(pn->lruvec_stat_local);
5251 		kfree(pn);
5252 		return 1;
5253 	}
5254 
5255 	lruvec_init(&pn->lruvec);
5256 	pn->usage_in_excess = 0;
5257 	pn->lruvec.pgdat = NODE_DATA(node);
5258 	pn->on_tree = false;
5259 	pn->memcg = memcg;
5260 
5261 	memcg->nodeinfo[node] = pn;
5262 	return 0;
5263 }
5264 
free_mem_cgroup_per_node_info(struct mem_cgroup * memcg,int node)5265 static void free_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5266 {
5267 	struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
5268 
5269 	if (!pn)
5270 		return;
5271 
5272 	free_percpu(pn->lruvec_stat_cpu);
5273 	free_percpu(pn->lruvec_stat_local);
5274 	kfree(pn);
5275 }
5276 
__mem_cgroup_free(struct mem_cgroup * memcg)5277 static void __mem_cgroup_free(struct mem_cgroup *memcg)
5278 {
5279 	int node;
5280 
5281 	for_each_node(node)
5282 		free_mem_cgroup_per_node_info(memcg, node);
5283 	free_percpu(memcg->vmstats_percpu);
5284 	free_percpu(memcg->vmstats_local);
5285 	kfree(memcg);
5286 }
5287 
mem_cgroup_free(struct mem_cgroup * memcg)5288 static void mem_cgroup_free(struct mem_cgroup *memcg)
5289 {
5290 	memcg_wb_domain_exit(memcg);
5291 	/*
5292 	 * Flush percpu vmstats and vmevents to guarantee the value correctness
5293 	 * on parent's and all ancestor levels.
5294 	 */
5295 	memcg_flush_percpu_vmstats(memcg);
5296 	memcg_flush_percpu_vmevents(memcg);
5297 	__mem_cgroup_free(memcg);
5298 }
5299 
mem_cgroup_alloc(void)5300 static struct mem_cgroup *mem_cgroup_alloc(void)
5301 {
5302 	struct mem_cgroup *memcg;
5303 	unsigned int size;
5304 	int node;
5305 	int __maybe_unused i;
5306 	long error = -ENOMEM;
5307 
5308 	size = sizeof(struct mem_cgroup);
5309 	size += nr_node_ids * sizeof(struct mem_cgroup_per_node *);
5310 
5311 	memcg = kzalloc(size, GFP_KERNEL);
5312 	if (!memcg)
5313 		return ERR_PTR(error);
5314 
5315 	memcg->id.id = idr_alloc(&mem_cgroup_idr, NULL,
5316 				 1, MEM_CGROUP_ID_MAX,
5317 				 GFP_KERNEL);
5318 	if (memcg->id.id < 0) {
5319 		error = memcg->id.id;
5320 		goto fail;
5321 	}
5322 
5323 	memcg->vmstats_local = alloc_percpu_gfp(struct memcg_vmstats_percpu,
5324 						GFP_KERNEL_ACCOUNT);
5325 	if (!memcg->vmstats_local)
5326 		goto fail;
5327 
5328 	memcg->vmstats_percpu = alloc_percpu_gfp(struct memcg_vmstats_percpu,
5329 						 GFP_KERNEL_ACCOUNT);
5330 	if (!memcg->vmstats_percpu)
5331 		goto fail;
5332 
5333 	for_each_node(node)
5334 		if (alloc_mem_cgroup_per_node_info(memcg, node))
5335 			goto fail;
5336 
5337 	if (memcg_wb_domain_init(memcg, GFP_KERNEL))
5338 		goto fail;
5339 
5340 	INIT_WORK(&memcg->high_work, high_work_func);
5341 	INIT_LIST_HEAD(&memcg->oom_notify);
5342 	mutex_init(&memcg->thresholds_lock);
5343 	spin_lock_init(&memcg->move_lock);
5344 	vmpressure_init(&memcg->vmpressure);
5345 	INIT_LIST_HEAD(&memcg->event_list);
5346 	spin_lock_init(&memcg->event_list_lock);
5347 	memcg->socket_pressure = jiffies;
5348 #ifdef CONFIG_MEMCG_KMEM
5349 	memcg->kmemcg_id = -1;
5350 	INIT_LIST_HEAD(&memcg->objcg_list);
5351 #endif
5352 #ifdef CONFIG_CGROUP_WRITEBACK
5353 	INIT_LIST_HEAD(&memcg->cgwb_list);
5354 	for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5355 		memcg->cgwb_frn[i].done =
5356 			__WB_COMPLETION_INIT(&memcg_cgwb_frn_waitq);
5357 #endif
5358 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5359 	spin_lock_init(&memcg->deferred_split_queue.split_queue_lock);
5360 	INIT_LIST_HEAD(&memcg->deferred_split_queue.split_queue);
5361 	memcg->deferred_split_queue.split_queue_len = 0;
5362 #endif
5363 
5364 #ifdef CONFIG_HYPERHOLD_MEMCG
5365 	if (unlikely(!score_head_inited)) {
5366 		INIT_LIST_HEAD(&score_head);
5367 		score_head_inited = true;
5368 	}
5369 #endif
5370 
5371 #ifdef CONFIG_HYPERHOLD_MEMCG
5372 	INIT_LIST_HEAD(&memcg->score_node);
5373 #endif
5374 	idr_replace(&mem_cgroup_idr, memcg, memcg->id.id);
5375 	return memcg;
5376 fail:
5377 	mem_cgroup_id_remove(memcg);
5378 	__mem_cgroup_free(memcg);
5379 	return ERR_PTR(error);
5380 }
5381 
5382 static struct cgroup_subsys_state * __ref
mem_cgroup_css_alloc(struct cgroup_subsys_state * parent_css)5383 mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
5384 {
5385 	struct mem_cgroup *parent = mem_cgroup_from_css(parent_css);
5386 	struct mem_cgroup *memcg, *old_memcg;
5387 	long error = -ENOMEM;
5388 
5389 	old_memcg = set_active_memcg(parent);
5390 	memcg = mem_cgroup_alloc();
5391 	set_active_memcg(old_memcg);
5392 	if (IS_ERR(memcg))
5393 		return ERR_CAST(memcg);
5394 
5395 #ifdef CONFIG_HYPERHOLD_MEMCG
5396 	atomic64_set(&memcg->memcg_reclaimed.app_score, 300);
5397 #endif
5398 #ifdef CONFIG_HYPERHOLD_ZSWAPD
5399 	atomic_set(&memcg->memcg_reclaimed.ub_zram2ufs_ratio, 10);
5400 	atomic_set(&memcg->memcg_reclaimed.ub_mem2zram_ratio, 60);
5401 	atomic_set(&memcg->memcg_reclaimed.refault_threshold, 50);
5402 #endif
5403 	page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
5404 	memcg->soft_limit = PAGE_COUNTER_MAX;
5405 	page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
5406 	if (parent) {
5407 		memcg->swappiness = mem_cgroup_swappiness(parent);
5408 		memcg->oom_kill_disable = parent->oom_kill_disable;
5409 	}
5410 	if (!parent) {
5411 		page_counter_init(&memcg->memory, NULL);
5412 		page_counter_init(&memcg->swap, NULL);
5413 		page_counter_init(&memcg->kmem, NULL);
5414 		page_counter_init(&memcg->tcpmem, NULL);
5415 	} else if (parent->use_hierarchy) {
5416 		memcg->use_hierarchy = true;
5417 		page_counter_init(&memcg->memory, &parent->memory);
5418 		page_counter_init(&memcg->swap, &parent->swap);
5419 		page_counter_init(&memcg->kmem, &parent->kmem);
5420 		page_counter_init(&memcg->tcpmem, &parent->tcpmem);
5421 	} else {
5422 		page_counter_init(&memcg->memory, &root_mem_cgroup->memory);
5423 		page_counter_init(&memcg->swap, &root_mem_cgroup->swap);
5424 		page_counter_init(&memcg->kmem, &root_mem_cgroup->kmem);
5425 		page_counter_init(&memcg->tcpmem, &root_mem_cgroup->tcpmem);
5426 		/*
5427 		 * Deeper hierachy with use_hierarchy == false doesn't make
5428 		 * much sense so let cgroup subsystem know about this
5429 		 * unfortunate state in our controller.
5430 		 */
5431 		if (parent != root_mem_cgroup)
5432 			memory_cgrp_subsys.broken_hierarchy = true;
5433 	}
5434 
5435 	/* The following stuff does not apply to the root */
5436 	if (!parent) {
5437 		root_mem_cgroup = memcg;
5438 		return &memcg->css;
5439 	}
5440 
5441 	error = memcg_online_kmem(memcg);
5442 	if (error)
5443 		goto fail;
5444 
5445 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5446 		static_branch_inc(&memcg_sockets_enabled_key);
5447 
5448 	return &memcg->css;
5449 fail:
5450 	mem_cgroup_id_remove(memcg);
5451 	mem_cgroup_free(memcg);
5452 	return ERR_PTR(error);
5453 }
5454 
mem_cgroup_css_online(struct cgroup_subsys_state * css)5455 static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
5456 {
5457 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5458 
5459 	/*
5460 	 * A memcg must be visible for memcg_expand_shrinker_maps()
5461 	 * by the time the maps are allocated. So, we allocate maps
5462 	 * here, when for_each_mem_cgroup() can't skip it.
5463 	 */
5464 	if (memcg_alloc_shrinker_maps(memcg)) {
5465 		mem_cgroup_id_remove(memcg);
5466 		return -ENOMEM;
5467 	}
5468 
5469 #ifdef CONFIG_HYPERHOLD_MEMCG
5470 	memcg_app_score_update(memcg);
5471 	css_get(css);
5472 #endif
5473 
5474 	/* Online state pins memcg ID, memcg ID pins CSS */
5475 	refcount_set(&memcg->id.ref, 1);
5476 	css_get(css);
5477 	return 0;
5478 }
5479 
mem_cgroup_css_offline(struct cgroup_subsys_state * css)5480 static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
5481 {
5482 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5483 	struct mem_cgroup_event *event, *tmp;
5484 
5485 #ifdef CONFIG_HYPERHOLD_MEMCG
5486 	unsigned long flags;
5487 
5488 	write_lock_irqsave(&score_list_lock, flags);
5489 	list_del_init(&memcg->score_node);
5490 	write_unlock_irqrestore(&score_list_lock, flags);
5491 	css_put(css);
5492 #endif
5493 
5494 	/*
5495 	 * Unregister events and notify userspace.
5496 	 * Notify userspace about cgroup removing only after rmdir of cgroup
5497 	 * directory to avoid race between userspace and kernelspace.
5498 	 */
5499 	spin_lock(&memcg->event_list_lock);
5500 	list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
5501 		list_del_init(&event->list);
5502 		schedule_work(&event->remove);
5503 	}
5504 	spin_unlock(&memcg->event_list_lock);
5505 
5506 	page_counter_set_min(&memcg->memory, 0);
5507 	page_counter_set_low(&memcg->memory, 0);
5508 
5509 	memcg_offline_kmem(memcg);
5510 	wb_memcg_offline(memcg);
5511 
5512 	drain_all_stock(memcg);
5513 
5514 	mem_cgroup_id_put(memcg);
5515 }
5516 
mem_cgroup_css_released(struct cgroup_subsys_state * css)5517 static void mem_cgroup_css_released(struct cgroup_subsys_state *css)
5518 {
5519 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5520 
5521 	invalidate_reclaim_iterators(memcg);
5522 }
5523 
mem_cgroup_css_free(struct cgroup_subsys_state * css)5524 static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
5525 {
5526 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5527 	int __maybe_unused i;
5528 
5529 #ifdef CONFIG_CGROUP_WRITEBACK
5530 	for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5531 		wb_wait_for_completion(&memcg->cgwb_frn[i].done);
5532 #endif
5533 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5534 		static_branch_dec(&memcg_sockets_enabled_key);
5535 
5536 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg->tcpmem_active)
5537 		static_branch_dec(&memcg_sockets_enabled_key);
5538 
5539 	vmpressure_cleanup(&memcg->vmpressure);
5540 	cancel_work_sync(&memcg->high_work);
5541 	mem_cgroup_remove_from_trees(memcg);
5542 	memcg_free_shrinker_maps(memcg);
5543 	memcg_free_kmem(memcg);
5544 	mem_cgroup_free(memcg);
5545 }
5546 
5547 /**
5548  * mem_cgroup_css_reset - reset the states of a mem_cgroup
5549  * @css: the target css
5550  *
5551  * Reset the states of the mem_cgroup associated with @css.  This is
5552  * invoked when the userland requests disabling on the default hierarchy
5553  * but the memcg is pinned through dependency.  The memcg should stop
5554  * applying policies and should revert to the vanilla state as it may be
5555  * made visible again.
5556  *
5557  * The current implementation only resets the essential configurations.
5558  * This needs to be expanded to cover all the visible parts.
5559  */
mem_cgroup_css_reset(struct cgroup_subsys_state * css)5560 static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
5561 {
5562 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5563 
5564 	page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX);
5565 	page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX);
5566 	page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX);
5567 	page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX);
5568 	page_counter_set_min(&memcg->memory, 0);
5569 	page_counter_set_low(&memcg->memory, 0);
5570 	page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
5571 	memcg->soft_limit = PAGE_COUNTER_MAX;
5572 	page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
5573 	memcg_wb_domain_size_changed(memcg);
5574 }
5575 
5576 #ifdef CONFIG_MMU
5577 /* Handlers for move charge at task migration. */
mem_cgroup_do_precharge(unsigned long count)5578 static int mem_cgroup_do_precharge(unsigned long count)
5579 {
5580 	int ret;
5581 
5582 	/* Try a single bulk charge without reclaim first, kswapd may wake */
5583 	ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_DIRECT_RECLAIM, count);
5584 	if (!ret) {
5585 		mc.precharge += count;
5586 		return ret;
5587 	}
5588 
5589 	/* Try charges one by one with reclaim, but do not retry */
5590 	while (count--) {
5591 		ret = try_charge(mc.to, GFP_KERNEL | __GFP_NORETRY, 1);
5592 		if (ret)
5593 			return ret;
5594 		mc.precharge++;
5595 		cond_resched();
5596 	}
5597 	return 0;
5598 }
5599 
5600 union mc_target {
5601 	struct page	*page;
5602 	swp_entry_t	ent;
5603 };
5604 
5605 enum mc_target_type {
5606 	MC_TARGET_NONE = 0,
5607 	MC_TARGET_PAGE,
5608 	MC_TARGET_SWAP,
5609 	MC_TARGET_DEVICE,
5610 };
5611 
mc_handle_present_pte(struct vm_area_struct * vma,unsigned long addr,pte_t ptent)5612 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5613 						unsigned long addr, pte_t ptent)
5614 {
5615 	struct page *page = vm_normal_page(vma, addr, ptent);
5616 
5617 	if (!page || !page_mapped(page))
5618 		return NULL;
5619 	if (PageAnon(page)) {
5620 		if (!(mc.flags & MOVE_ANON))
5621 			return NULL;
5622 	} else {
5623 		if (!(mc.flags & MOVE_FILE))
5624 			return NULL;
5625 	}
5626 	if (!get_page_unless_zero(page))
5627 		return NULL;
5628 
5629 	return page;
5630 }
5631 
5632 #if defined(CONFIG_SWAP) || defined(CONFIG_DEVICE_PRIVATE)
mc_handle_swap_pte(struct vm_area_struct * vma,pte_t ptent,swp_entry_t * entry)5633 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5634 			pte_t ptent, swp_entry_t *entry)
5635 {
5636 	struct page *page = NULL;
5637 	swp_entry_t ent = pte_to_swp_entry(ptent);
5638 
5639 	if (!(mc.flags & MOVE_ANON))
5640 		return NULL;
5641 
5642 	/*
5643 	 * Handle MEMORY_DEVICE_PRIVATE which are ZONE_DEVICE page belonging to
5644 	 * a device and because they are not accessible by CPU they are store
5645 	 * as special swap entry in the CPU page table.
5646 	 */
5647 	if (is_device_private_entry(ent)) {
5648 		page = device_private_entry_to_page(ent);
5649 		/*
5650 		 * MEMORY_DEVICE_PRIVATE means ZONE_DEVICE page and which have
5651 		 * a refcount of 1 when free (unlike normal page)
5652 		 */
5653 		if (!page_ref_add_unless(page, 1, 1))
5654 			return NULL;
5655 		return page;
5656 	}
5657 
5658 	if (non_swap_entry(ent))
5659 		return NULL;
5660 
5661 	/*
5662 	 * Because lookup_swap_cache() updates some statistics counter,
5663 	 * we call find_get_page() with swapper_space directly.
5664 	 */
5665 	page = find_get_page(swap_address_space(ent), swp_offset(ent));
5666 	entry->val = ent.val;
5667 
5668 	return page;
5669 }
5670 #else
mc_handle_swap_pte(struct vm_area_struct * vma,pte_t ptent,swp_entry_t * entry)5671 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5672 			pte_t ptent, swp_entry_t *entry)
5673 {
5674 	return NULL;
5675 }
5676 #endif
5677 
mc_handle_file_pte(struct vm_area_struct * vma,unsigned long addr,pte_t ptent,swp_entry_t * entry)5678 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5679 			unsigned long addr, pte_t ptent, swp_entry_t *entry)
5680 {
5681 	if (!vma->vm_file) /* anonymous vma */
5682 		return NULL;
5683 	if (!(mc.flags & MOVE_FILE))
5684 		return NULL;
5685 
5686 	/* page is moved even if it's not RSS of this task(page-faulted). */
5687 	/* shmem/tmpfs may report page out on swap: account for that too. */
5688 	return find_get_incore_page(vma->vm_file->f_mapping,
5689 			linear_page_index(vma, addr));
5690 }
5691 
5692 /**
5693  * mem_cgroup_move_account - move account of the page
5694  * @page: the page
5695  * @compound: charge the page as compound or small page
5696  * @from: mem_cgroup which the page is moved from.
5697  * @to:	mem_cgroup which the page is moved to. @from != @to.
5698  *
5699  * The caller must make sure the page is not on LRU (isolate_page() is useful.)
5700  *
5701  * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
5702  * from old cgroup.
5703  */
mem_cgroup_move_account(struct page * page,bool compound,struct mem_cgroup * from,struct mem_cgroup * to)5704 static int mem_cgroup_move_account(struct page *page,
5705 				   bool compound,
5706 				   struct mem_cgroup *from,
5707 				   struct mem_cgroup *to)
5708 {
5709 	struct lruvec *from_vec, *to_vec;
5710 	struct pglist_data *pgdat;
5711 	unsigned int nr_pages = compound ? thp_nr_pages(page) : 1;
5712 	int ret;
5713 
5714 	VM_BUG_ON(from == to);
5715 	VM_BUG_ON_PAGE(PageLRU(page), page);
5716 	VM_BUG_ON(compound && !PageTransHuge(page));
5717 
5718 	/*
5719 	 * Prevent mem_cgroup_migrate() from looking at
5720 	 * page->mem_cgroup of its source page while we change it.
5721 	 */
5722 	ret = -EBUSY;
5723 	if (!trylock_page(page))
5724 		goto out;
5725 
5726 	ret = -EINVAL;
5727 	if (page->mem_cgroup != from)
5728 		goto out_unlock;
5729 
5730 	pgdat = page_pgdat(page);
5731 	from_vec = mem_cgroup_lruvec(from, pgdat);
5732 	to_vec = mem_cgroup_lruvec(to, pgdat);
5733 
5734 	lock_page_memcg(page);
5735 
5736 	if (PageAnon(page)) {
5737 		if (page_mapped(page)) {
5738 			__mod_lruvec_state(from_vec, NR_ANON_MAPPED, -nr_pages);
5739 			__mod_lruvec_state(to_vec, NR_ANON_MAPPED, nr_pages);
5740 			if (PageTransHuge(page)) {
5741 				__dec_lruvec_state(from_vec, NR_ANON_THPS);
5742 				__inc_lruvec_state(to_vec, NR_ANON_THPS);
5743 			}
5744 
5745 		}
5746 	} else {
5747 		__mod_lruvec_state(from_vec, NR_FILE_PAGES, -nr_pages);
5748 		__mod_lruvec_state(to_vec, NR_FILE_PAGES, nr_pages);
5749 
5750 		if (PageSwapBacked(page)) {
5751 			__mod_lruvec_state(from_vec, NR_SHMEM, -nr_pages);
5752 			__mod_lruvec_state(to_vec, NR_SHMEM, nr_pages);
5753 		}
5754 
5755 		if (page_mapped(page)) {
5756 			__mod_lruvec_state(from_vec, NR_FILE_MAPPED, -nr_pages);
5757 			__mod_lruvec_state(to_vec, NR_FILE_MAPPED, nr_pages);
5758 		}
5759 
5760 		if (PageDirty(page)) {
5761 			struct address_space *mapping = page_mapping(page);
5762 
5763 			if (mapping_can_writeback(mapping)) {
5764 				__mod_lruvec_state(from_vec, NR_FILE_DIRTY,
5765 						   -nr_pages);
5766 				__mod_lruvec_state(to_vec, NR_FILE_DIRTY,
5767 						   nr_pages);
5768 			}
5769 		}
5770 	}
5771 
5772 	if (PageWriteback(page)) {
5773 		__mod_lruvec_state(from_vec, NR_WRITEBACK, -nr_pages);
5774 		__mod_lruvec_state(to_vec, NR_WRITEBACK, nr_pages);
5775 	}
5776 
5777 	/*
5778 	 * All state has been migrated, let's switch to the new memcg.
5779 	 *
5780 	 * It is safe to change page->mem_cgroup here because the page
5781 	 * is referenced, charged, isolated, and locked: we can't race
5782 	 * with (un)charging, migration, LRU putback, or anything else
5783 	 * that would rely on a stable page->mem_cgroup.
5784 	 *
5785 	 * Note that lock_page_memcg is a memcg lock, not a page lock,
5786 	 * to save space. As soon as we switch page->mem_cgroup to a
5787 	 * new memcg that isn't locked, the above state can change
5788 	 * concurrently again. Make sure we're truly done with it.
5789 	 */
5790 	smp_mb();
5791 
5792 	css_get(&to->css);
5793 	css_put(&from->css);
5794 
5795 	page->mem_cgroup = to;
5796 
5797 	__unlock_page_memcg(from);
5798 
5799 	ret = 0;
5800 
5801 	local_irq_disable();
5802 	mem_cgroup_charge_statistics(to, page, nr_pages);
5803 	memcg_check_events(to, page);
5804 	mem_cgroup_charge_statistics(from, page, -nr_pages);
5805 	memcg_check_events(from, page);
5806 	local_irq_enable();
5807 out_unlock:
5808 	unlock_page(page);
5809 out:
5810 	return ret;
5811 }
5812 
5813 /**
5814  * get_mctgt_type - get target type of moving charge
5815  * @vma: the vma the pte to be checked belongs
5816  * @addr: the address corresponding to the pte to be checked
5817  * @ptent: the pte to be checked
5818  * @target: the pointer the target page or swap ent will be stored(can be NULL)
5819  *
5820  * Returns
5821  *   0(MC_TARGET_NONE): if the pte is not a target for move charge.
5822  *   1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5823  *     move charge. if @target is not NULL, the page is stored in target->page
5824  *     with extra refcnt got(Callers should handle it).
5825  *   2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5826  *     target for charge migration. if @target is not NULL, the entry is stored
5827  *     in target->ent.
5828  *   3(MC_TARGET_DEVICE): like MC_TARGET_PAGE  but page is MEMORY_DEVICE_PRIVATE
5829  *     (so ZONE_DEVICE page and thus not on the lru).
5830  *     For now we such page is charge like a regular page would be as for all
5831  *     intent and purposes it is just special memory taking the place of a
5832  *     regular page.
5833  *
5834  *     See Documentations/vm/hmm.txt and include/linux/hmm.h
5835  *
5836  * Called with pte lock held.
5837  */
5838 
get_mctgt_type(struct vm_area_struct * vma,unsigned long addr,pte_t ptent,union mc_target * target)5839 static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
5840 		unsigned long addr, pte_t ptent, union mc_target *target)
5841 {
5842 	struct page *page = NULL;
5843 	enum mc_target_type ret = MC_TARGET_NONE;
5844 	swp_entry_t ent = { .val = 0 };
5845 
5846 	if (pte_present(ptent))
5847 		page = mc_handle_present_pte(vma, addr, ptent);
5848 	else if (is_swap_pte(ptent))
5849 		page = mc_handle_swap_pte(vma, ptent, &ent);
5850 	else if (pte_none(ptent))
5851 		page = mc_handle_file_pte(vma, addr, ptent, &ent);
5852 
5853 	if (!page && !ent.val)
5854 		return ret;
5855 	if (page) {
5856 		/*
5857 		 * Do only loose check w/o serialization.
5858 		 * mem_cgroup_move_account() checks the page is valid or
5859 		 * not under LRU exclusion.
5860 		 */
5861 		if (page->mem_cgroup == mc.from) {
5862 			ret = MC_TARGET_PAGE;
5863 			if (is_device_private_page(page))
5864 				ret = MC_TARGET_DEVICE;
5865 			if (target)
5866 				target->page = page;
5867 		}
5868 		if (!ret || !target)
5869 			put_page(page);
5870 	}
5871 	/*
5872 	 * There is a swap entry and a page doesn't exist or isn't charged.
5873 	 * But we cannot move a tail-page in a THP.
5874 	 */
5875 	if (ent.val && !ret && (!page || !PageTransCompound(page)) &&
5876 	    mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
5877 		ret = MC_TARGET_SWAP;
5878 		if (target)
5879 			target->ent = ent;
5880 	}
5881 	return ret;
5882 }
5883 
5884 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5885 /*
5886  * We don't consider PMD mapped swapping or file mapped pages because THP does
5887  * not support them for now.
5888  * Caller should make sure that pmd_trans_huge(pmd) is true.
5889  */
get_mctgt_type_thp(struct vm_area_struct * vma,unsigned long addr,pmd_t pmd,union mc_target * target)5890 static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5891 		unsigned long addr, pmd_t pmd, union mc_target *target)
5892 {
5893 	struct page *page = NULL;
5894 	enum mc_target_type ret = MC_TARGET_NONE;
5895 
5896 	if (unlikely(is_swap_pmd(pmd))) {
5897 		VM_BUG_ON(thp_migration_supported() &&
5898 				  !is_pmd_migration_entry(pmd));
5899 		return ret;
5900 	}
5901 	page = pmd_page(pmd);
5902 	VM_BUG_ON_PAGE(!page || !PageHead(page), page);
5903 	if (!(mc.flags & MOVE_ANON))
5904 		return ret;
5905 	if (page->mem_cgroup == mc.from) {
5906 		ret = MC_TARGET_PAGE;
5907 		if (target) {
5908 			get_page(page);
5909 			target->page = page;
5910 		}
5911 	}
5912 	return ret;
5913 }
5914 #else
get_mctgt_type_thp(struct vm_area_struct * vma,unsigned long addr,pmd_t pmd,union mc_target * target)5915 static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5916 		unsigned long addr, pmd_t pmd, union mc_target *target)
5917 {
5918 	return MC_TARGET_NONE;
5919 }
5920 #endif
5921 
mem_cgroup_count_precharge_pte_range(pmd_t * pmd,unsigned long addr,unsigned long end,struct mm_walk * walk)5922 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
5923 					unsigned long addr, unsigned long end,
5924 					struct mm_walk *walk)
5925 {
5926 	struct vm_area_struct *vma = walk->vma;
5927 	pte_t *pte;
5928 	spinlock_t *ptl;
5929 
5930 	ptl = pmd_trans_huge_lock(pmd, vma);
5931 	if (ptl) {
5932 		/*
5933 		 * Note their can not be MC_TARGET_DEVICE for now as we do not
5934 		 * support transparent huge page with MEMORY_DEVICE_PRIVATE but
5935 		 * this might change.
5936 		 */
5937 		if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
5938 			mc.precharge += HPAGE_PMD_NR;
5939 		spin_unlock(ptl);
5940 		return 0;
5941 	}
5942 
5943 	if (pmd_trans_unstable(pmd))
5944 		return 0;
5945 	pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5946 	for (; addr != end; pte++, addr += PAGE_SIZE)
5947 		if (get_mctgt_type(vma, addr, *pte, NULL))
5948 			mc.precharge++;	/* increment precharge temporarily */
5949 	pte_unmap_unlock(pte - 1, ptl);
5950 	cond_resched();
5951 
5952 	return 0;
5953 }
5954 
5955 static const struct mm_walk_ops precharge_walk_ops = {
5956 	.pmd_entry	= mem_cgroup_count_precharge_pte_range,
5957 };
5958 
mem_cgroup_count_precharge(struct mm_struct * mm)5959 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
5960 {
5961 	unsigned long precharge;
5962 
5963 	mmap_read_lock(mm);
5964 	walk_page_range(mm, 0, mm->highest_vm_end, &precharge_walk_ops, NULL);
5965 	mmap_read_unlock(mm);
5966 
5967 	precharge = mc.precharge;
5968 	mc.precharge = 0;
5969 
5970 	return precharge;
5971 }
5972 
mem_cgroup_precharge_mc(struct mm_struct * mm)5973 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
5974 {
5975 	unsigned long precharge = mem_cgroup_count_precharge(mm);
5976 
5977 	VM_BUG_ON(mc.moving_task);
5978 	mc.moving_task = current;
5979 	return mem_cgroup_do_precharge(precharge);
5980 }
5981 
5982 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
__mem_cgroup_clear_mc(void)5983 static void __mem_cgroup_clear_mc(void)
5984 {
5985 	struct mem_cgroup *from = mc.from;
5986 	struct mem_cgroup *to = mc.to;
5987 
5988 	/* we must uncharge all the leftover precharges from mc.to */
5989 	if (mc.precharge) {
5990 		cancel_charge(mc.to, mc.precharge);
5991 		mc.precharge = 0;
5992 	}
5993 	/*
5994 	 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5995 	 * we must uncharge here.
5996 	 */
5997 	if (mc.moved_charge) {
5998 		cancel_charge(mc.from, mc.moved_charge);
5999 		mc.moved_charge = 0;
6000 	}
6001 	/* we must fixup refcnts and charges */
6002 	if (mc.moved_swap) {
6003 		/* uncharge swap account from the old cgroup */
6004 		if (!mem_cgroup_is_root(mc.from))
6005 			page_counter_uncharge(&mc.from->memsw, mc.moved_swap);
6006 
6007 		mem_cgroup_id_put_many(mc.from, mc.moved_swap);
6008 
6009 		/*
6010 		 * we charged both to->memory and to->memsw, so we
6011 		 * should uncharge to->memory.
6012 		 */
6013 		if (!mem_cgroup_is_root(mc.to))
6014 			page_counter_uncharge(&mc.to->memory, mc.moved_swap);
6015 
6016 		mc.moved_swap = 0;
6017 	}
6018 	memcg_oom_recover(from);
6019 	memcg_oom_recover(to);
6020 	wake_up_all(&mc.waitq);
6021 }
6022 
mem_cgroup_clear_mc(void)6023 static void mem_cgroup_clear_mc(void)
6024 {
6025 	struct mm_struct *mm = mc.mm;
6026 
6027 	/*
6028 	 * we must clear moving_task before waking up waiters at the end of
6029 	 * task migration.
6030 	 */
6031 	mc.moving_task = NULL;
6032 	__mem_cgroup_clear_mc();
6033 	spin_lock(&mc.lock);
6034 	mc.from = NULL;
6035 	mc.to = NULL;
6036 	mc.mm = NULL;
6037 	spin_unlock(&mc.lock);
6038 
6039 	mmput(mm);
6040 }
6041 
mem_cgroup_can_attach(struct cgroup_taskset * tset)6042 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
6043 {
6044 	struct cgroup_subsys_state *css;
6045 	struct mem_cgroup *memcg = NULL; /* unneeded init to make gcc happy */
6046 	struct mem_cgroup *from;
6047 	struct task_struct *leader, *p;
6048 	struct mm_struct *mm;
6049 	unsigned long move_flags;
6050 	int ret = 0;
6051 
6052 	/* charge immigration isn't supported on the default hierarchy */
6053 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
6054 		return 0;
6055 
6056 	/*
6057 	 * Multi-process migrations only happen on the default hierarchy
6058 	 * where charge immigration is not used.  Perform charge
6059 	 * immigration if @tset contains a leader and whine if there are
6060 	 * multiple.
6061 	 */
6062 	p = NULL;
6063 	cgroup_taskset_for_each_leader(leader, css, tset) {
6064 		WARN_ON_ONCE(p);
6065 		p = leader;
6066 		memcg = mem_cgroup_from_css(css);
6067 	}
6068 	if (!p)
6069 		return 0;
6070 
6071 	/*
6072 	 * We are now commited to this value whatever it is. Changes in this
6073 	 * tunable will only affect upcoming migrations, not the current one.
6074 	 * So we need to save it, and keep it going.
6075 	 */
6076 	move_flags = READ_ONCE(memcg->move_charge_at_immigrate);
6077 	if (!move_flags)
6078 		return 0;
6079 
6080 	from = mem_cgroup_from_task(p);
6081 
6082 	VM_BUG_ON(from == memcg);
6083 
6084 	mm = get_task_mm(p);
6085 	if (!mm)
6086 		return 0;
6087 	/* We move charges only when we move a owner of the mm */
6088 	if (mm->owner == p) {
6089 		VM_BUG_ON(mc.from);
6090 		VM_BUG_ON(mc.to);
6091 		VM_BUG_ON(mc.precharge);
6092 		VM_BUG_ON(mc.moved_charge);
6093 		VM_BUG_ON(mc.moved_swap);
6094 
6095 		spin_lock(&mc.lock);
6096 		mc.mm = mm;
6097 		mc.from = from;
6098 		mc.to = memcg;
6099 		mc.flags = move_flags;
6100 		spin_unlock(&mc.lock);
6101 		/* We set mc.moving_task later */
6102 
6103 		ret = mem_cgroup_precharge_mc(mm);
6104 		if (ret)
6105 			mem_cgroup_clear_mc();
6106 	} else {
6107 		mmput(mm);
6108 	}
6109 	return ret;
6110 }
6111 
mem_cgroup_cancel_attach(struct cgroup_taskset * tset)6112 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
6113 {
6114 	if (mc.to)
6115 		mem_cgroup_clear_mc();
6116 }
6117 
mem_cgroup_move_charge_pte_range(pmd_t * pmd,unsigned long addr,unsigned long end,struct mm_walk * walk)6118 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
6119 				unsigned long addr, unsigned long end,
6120 				struct mm_walk *walk)
6121 {
6122 	int ret = 0;
6123 	struct vm_area_struct *vma = walk->vma;
6124 	pte_t *pte;
6125 	spinlock_t *ptl;
6126 	enum mc_target_type target_type;
6127 	union mc_target target;
6128 	struct page *page;
6129 
6130 	ptl = pmd_trans_huge_lock(pmd, vma);
6131 	if (ptl) {
6132 		if (mc.precharge < HPAGE_PMD_NR) {
6133 			spin_unlock(ptl);
6134 			return 0;
6135 		}
6136 		target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
6137 		if (target_type == MC_TARGET_PAGE) {
6138 			page = target.page;
6139 			if (!isolate_lru_page(page)) {
6140 				if (!mem_cgroup_move_account(page, true,
6141 							     mc.from, mc.to)) {
6142 					mc.precharge -= HPAGE_PMD_NR;
6143 					mc.moved_charge += HPAGE_PMD_NR;
6144 				}
6145 				putback_lru_page(page);
6146 			}
6147 			put_page(page);
6148 		} else if (target_type == MC_TARGET_DEVICE) {
6149 			page = target.page;
6150 			if (!mem_cgroup_move_account(page, true,
6151 						     mc.from, mc.to)) {
6152 				mc.precharge -= HPAGE_PMD_NR;
6153 				mc.moved_charge += HPAGE_PMD_NR;
6154 			}
6155 			put_page(page);
6156 		}
6157 		spin_unlock(ptl);
6158 		return 0;
6159 	}
6160 
6161 	if (pmd_trans_unstable(pmd))
6162 		return 0;
6163 retry:
6164 	pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6165 	for (; addr != end; addr += PAGE_SIZE) {
6166 		pte_t ptent = *(pte++);
6167 		bool device = false;
6168 		swp_entry_t ent;
6169 
6170 		if (!mc.precharge)
6171 			break;
6172 
6173 		switch (get_mctgt_type(vma, addr, ptent, &target)) {
6174 		case MC_TARGET_DEVICE:
6175 			device = true;
6176 			fallthrough;
6177 		case MC_TARGET_PAGE:
6178 			page = target.page;
6179 			/*
6180 			 * We can have a part of the split pmd here. Moving it
6181 			 * can be done but it would be too convoluted so simply
6182 			 * ignore such a partial THP and keep it in original
6183 			 * memcg. There should be somebody mapping the head.
6184 			 */
6185 			if (PageTransCompound(page))
6186 				goto put;
6187 			if (!device && isolate_lru_page(page))
6188 				goto put;
6189 			if (!mem_cgroup_move_account(page, false,
6190 						mc.from, mc.to)) {
6191 				mc.precharge--;
6192 				/* we uncharge from mc.from later. */
6193 				mc.moved_charge++;
6194 			}
6195 			if (!device)
6196 				putback_lru_page(page);
6197 put:			/* get_mctgt_type() gets the page */
6198 			put_page(page);
6199 			break;
6200 		case MC_TARGET_SWAP:
6201 			ent = target.ent;
6202 			if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
6203 				mc.precharge--;
6204 				mem_cgroup_id_get_many(mc.to, 1);
6205 				/* we fixup other refcnts and charges later. */
6206 				mc.moved_swap++;
6207 			}
6208 			break;
6209 		default:
6210 			break;
6211 		}
6212 	}
6213 	pte_unmap_unlock(pte - 1, ptl);
6214 	cond_resched();
6215 
6216 	if (addr != end) {
6217 		/*
6218 		 * We have consumed all precharges we got in can_attach().
6219 		 * We try charge one by one, but don't do any additional
6220 		 * charges to mc.to if we have failed in charge once in attach()
6221 		 * phase.
6222 		 */
6223 		ret = mem_cgroup_do_precharge(1);
6224 		if (!ret)
6225 			goto retry;
6226 	}
6227 
6228 	return ret;
6229 }
6230 
6231 static const struct mm_walk_ops charge_walk_ops = {
6232 	.pmd_entry	= mem_cgroup_move_charge_pte_range,
6233 };
6234 
mem_cgroup_move_charge(void)6235 static void mem_cgroup_move_charge(void)
6236 {
6237 	lru_add_drain_all();
6238 	/*
6239 	 * Signal lock_page_memcg() to take the memcg's move_lock
6240 	 * while we're moving its pages to another memcg. Then wait
6241 	 * for already started RCU-only updates to finish.
6242 	 */
6243 	atomic_inc(&mc.from->moving_account);
6244 	synchronize_rcu();
6245 retry:
6246 	if (unlikely(!mmap_read_trylock(mc.mm))) {
6247 		/*
6248 		 * Someone who are holding the mmap_lock might be waiting in
6249 		 * waitq. So we cancel all extra charges, wake up all waiters,
6250 		 * and retry. Because we cancel precharges, we might not be able
6251 		 * to move enough charges, but moving charge is a best-effort
6252 		 * feature anyway, so it wouldn't be a big problem.
6253 		 */
6254 		__mem_cgroup_clear_mc();
6255 		cond_resched();
6256 		goto retry;
6257 	}
6258 	/*
6259 	 * When we have consumed all precharges and failed in doing
6260 	 * additional charge, the page walk just aborts.
6261 	 */
6262 	walk_page_range(mc.mm, 0, mc.mm->highest_vm_end, &charge_walk_ops,
6263 			NULL);
6264 
6265 	mmap_read_unlock(mc.mm);
6266 	atomic_dec(&mc.from->moving_account);
6267 }
6268 
mem_cgroup_move_task(void)6269 static void mem_cgroup_move_task(void)
6270 {
6271 	if (mc.to) {
6272 		mem_cgroup_move_charge();
6273 		mem_cgroup_clear_mc();
6274 	}
6275 }
6276 #else	/* !CONFIG_MMU */
mem_cgroup_can_attach(struct cgroup_taskset * tset)6277 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
6278 {
6279 	return 0;
6280 }
mem_cgroup_cancel_attach(struct cgroup_taskset * tset)6281 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
6282 {
6283 }
mem_cgroup_move_task(void)6284 static void mem_cgroup_move_task(void)
6285 {
6286 }
6287 #endif
6288 
6289 /*
6290  * Cgroup retains root cgroups across [un]mount cycles making it necessary
6291  * to verify whether we're attached to the default hierarchy on each mount
6292  * attempt.
6293  */
mem_cgroup_bind(struct cgroup_subsys_state * root_css)6294 static void mem_cgroup_bind(struct cgroup_subsys_state *root_css)
6295 {
6296 	/*
6297 	 * use_hierarchy is forced on the default hierarchy.  cgroup core
6298 	 * guarantees that @root doesn't have any children, so turning it
6299 	 * on for the root memcg is enough.
6300 	 */
6301 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
6302 		root_mem_cgroup->use_hierarchy = true;
6303 	else
6304 		root_mem_cgroup->use_hierarchy = false;
6305 }
6306 
seq_puts_memcg_tunable(struct seq_file * m,unsigned long value)6307 static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value)
6308 {
6309 	if (value == PAGE_COUNTER_MAX)
6310 		seq_puts(m, "max\n");
6311 	else
6312 		seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE);
6313 
6314 	return 0;
6315 }
6316 
memory_current_read(struct cgroup_subsys_state * css,struct cftype * cft)6317 static u64 memory_current_read(struct cgroup_subsys_state *css,
6318 			       struct cftype *cft)
6319 {
6320 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6321 
6322 	return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
6323 }
6324 
memory_min_show(struct seq_file * m,void * v)6325 static int memory_min_show(struct seq_file *m, void *v)
6326 {
6327 	return seq_puts_memcg_tunable(m,
6328 		READ_ONCE(mem_cgroup_from_seq(m)->memory.min));
6329 }
6330 
memory_min_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)6331 static ssize_t memory_min_write(struct kernfs_open_file *of,
6332 				char *buf, size_t nbytes, loff_t off)
6333 {
6334 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6335 	unsigned long min;
6336 	int err;
6337 
6338 	buf = strstrip(buf);
6339 	err = page_counter_memparse(buf, "max", &min);
6340 	if (err)
6341 		return err;
6342 
6343 	page_counter_set_min(&memcg->memory, min);
6344 
6345 	return nbytes;
6346 }
6347 
memory_low_show(struct seq_file * m,void * v)6348 static int memory_low_show(struct seq_file *m, void *v)
6349 {
6350 	return seq_puts_memcg_tunable(m,
6351 		READ_ONCE(mem_cgroup_from_seq(m)->memory.low));
6352 }
6353 
memory_low_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)6354 static ssize_t memory_low_write(struct kernfs_open_file *of,
6355 				char *buf, size_t nbytes, loff_t off)
6356 {
6357 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6358 	unsigned long low;
6359 	int err;
6360 
6361 	buf = strstrip(buf);
6362 	err = page_counter_memparse(buf, "max", &low);
6363 	if (err)
6364 		return err;
6365 
6366 	page_counter_set_low(&memcg->memory, low);
6367 
6368 	return nbytes;
6369 }
6370 
memory_high_show(struct seq_file * m,void * v)6371 static int memory_high_show(struct seq_file *m, void *v)
6372 {
6373 	return seq_puts_memcg_tunable(m,
6374 		READ_ONCE(mem_cgroup_from_seq(m)->memory.high));
6375 }
6376 
memory_high_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)6377 static ssize_t memory_high_write(struct kernfs_open_file *of,
6378 				 char *buf, size_t nbytes, loff_t off)
6379 {
6380 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6381 	unsigned int nr_retries = MAX_RECLAIM_RETRIES;
6382 	bool drained = false;
6383 	unsigned long high;
6384 	int err;
6385 
6386 	buf = strstrip(buf);
6387 	err = page_counter_memparse(buf, "max", &high);
6388 	if (err)
6389 		return err;
6390 
6391 	page_counter_set_high(&memcg->memory, high);
6392 
6393 	for (;;) {
6394 		unsigned long nr_pages = page_counter_read(&memcg->memory);
6395 		unsigned long reclaimed;
6396 
6397 		if (nr_pages <= high)
6398 			break;
6399 
6400 		if (signal_pending(current))
6401 			break;
6402 
6403 		if (!drained) {
6404 			drain_all_stock(memcg);
6405 			drained = true;
6406 			continue;
6407 		}
6408 
6409 		reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages - high,
6410 							 GFP_KERNEL, true);
6411 
6412 		if (!reclaimed && !nr_retries--)
6413 			break;
6414 	}
6415 
6416 	memcg_wb_domain_size_changed(memcg);
6417 	return nbytes;
6418 }
6419 
memory_max_show(struct seq_file * m,void * v)6420 static int memory_max_show(struct seq_file *m, void *v)
6421 {
6422 	return seq_puts_memcg_tunable(m,
6423 		READ_ONCE(mem_cgroup_from_seq(m)->memory.max));
6424 }
6425 
memory_max_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)6426 static ssize_t memory_max_write(struct kernfs_open_file *of,
6427 				char *buf, size_t nbytes, loff_t off)
6428 {
6429 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6430 	unsigned int nr_reclaims = MAX_RECLAIM_RETRIES;
6431 	bool drained = false;
6432 	unsigned long max;
6433 	int err;
6434 
6435 	buf = strstrip(buf);
6436 	err = page_counter_memparse(buf, "max", &max);
6437 	if (err)
6438 		return err;
6439 
6440 	xchg(&memcg->memory.max, max);
6441 
6442 	for (;;) {
6443 		unsigned long nr_pages = page_counter_read(&memcg->memory);
6444 
6445 		if (nr_pages <= max)
6446 			break;
6447 
6448 		if (signal_pending(current))
6449 			break;
6450 
6451 		if (!drained) {
6452 			drain_all_stock(memcg);
6453 			drained = true;
6454 			continue;
6455 		}
6456 
6457 		if (nr_reclaims) {
6458 			if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,
6459 							  GFP_KERNEL, true))
6460 				nr_reclaims--;
6461 			continue;
6462 		}
6463 
6464 		memcg_memory_event(memcg, MEMCG_OOM);
6465 		if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0))
6466 			break;
6467 	}
6468 
6469 	memcg_wb_domain_size_changed(memcg);
6470 	return nbytes;
6471 }
6472 
__memory_events_show(struct seq_file * m,atomic_long_t * events)6473 static void __memory_events_show(struct seq_file *m, atomic_long_t *events)
6474 {
6475 	seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW]));
6476 	seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH]));
6477 	seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX]));
6478 	seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM]));
6479 	seq_printf(m, "oom_kill %lu\n",
6480 		   atomic_long_read(&events[MEMCG_OOM_KILL]));
6481 }
6482 
memory_events_show(struct seq_file * m,void * v)6483 static int memory_events_show(struct seq_file *m, void *v)
6484 {
6485 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6486 
6487 	__memory_events_show(m, memcg->memory_events);
6488 	return 0;
6489 }
6490 
memory_events_local_show(struct seq_file * m,void * v)6491 static int memory_events_local_show(struct seq_file *m, void *v)
6492 {
6493 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6494 
6495 	__memory_events_show(m, memcg->memory_events_local);
6496 	return 0;
6497 }
6498 
memory_stat_show(struct seq_file * m,void * v)6499 static int memory_stat_show(struct seq_file *m, void *v)
6500 {
6501 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6502 	char *buf;
6503 
6504 	buf = memory_stat_format(memcg);
6505 	if (!buf)
6506 		return -ENOMEM;
6507 	seq_puts(m, buf);
6508 	kfree(buf);
6509 	return 0;
6510 }
6511 
6512 #ifdef CONFIG_NUMA
memory_numa_stat_show(struct seq_file * m,void * v)6513 static int memory_numa_stat_show(struct seq_file *m, void *v)
6514 {
6515 	int i;
6516 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6517 
6518 	for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
6519 		int nid;
6520 
6521 		if (memory_stats[i].idx >= NR_VM_NODE_STAT_ITEMS)
6522 			continue;
6523 
6524 		seq_printf(m, "%s", memory_stats[i].name);
6525 		for_each_node_state(nid, N_MEMORY) {
6526 			u64 size;
6527 			struct lruvec *lruvec;
6528 
6529 			lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
6530 			size = lruvec_page_state(lruvec, memory_stats[i].idx);
6531 			size *= memory_stats[i].ratio;
6532 			seq_printf(m, " N%d=%llu", nid, size);
6533 		}
6534 		seq_putc(m, '\n');
6535 	}
6536 
6537 	return 0;
6538 }
6539 #endif
6540 
memory_oom_group_show(struct seq_file * m,void * v)6541 static int memory_oom_group_show(struct seq_file *m, void *v)
6542 {
6543 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6544 
6545 	seq_printf(m, "%d\n", memcg->oom_group);
6546 
6547 	return 0;
6548 }
6549 
memory_oom_group_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)6550 static ssize_t memory_oom_group_write(struct kernfs_open_file *of,
6551 				      char *buf, size_t nbytes, loff_t off)
6552 {
6553 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6554 	int ret, oom_group;
6555 
6556 	buf = strstrip(buf);
6557 	if (!buf)
6558 		return -EINVAL;
6559 
6560 	ret = kstrtoint(buf, 0, &oom_group);
6561 	if (ret)
6562 		return ret;
6563 
6564 	if (oom_group != 0 && oom_group != 1)
6565 		return -EINVAL;
6566 
6567 	memcg->oom_group = oom_group;
6568 
6569 	return nbytes;
6570 }
6571 
6572 static struct cftype memory_files[] = {
6573 	{
6574 		.name = "current",
6575 		.flags = CFTYPE_NOT_ON_ROOT,
6576 		.read_u64 = memory_current_read,
6577 	},
6578 	{
6579 		.name = "min",
6580 		.flags = CFTYPE_NOT_ON_ROOT,
6581 		.seq_show = memory_min_show,
6582 		.write = memory_min_write,
6583 	},
6584 	{
6585 		.name = "low",
6586 		.flags = CFTYPE_NOT_ON_ROOT,
6587 		.seq_show = memory_low_show,
6588 		.write = memory_low_write,
6589 	},
6590 	{
6591 		.name = "high",
6592 		.flags = CFTYPE_NOT_ON_ROOT,
6593 		.seq_show = memory_high_show,
6594 		.write = memory_high_write,
6595 	},
6596 	{
6597 		.name = "max",
6598 		.flags = CFTYPE_NOT_ON_ROOT,
6599 		.seq_show = memory_max_show,
6600 		.write = memory_max_write,
6601 	},
6602 	{
6603 		.name = "events",
6604 		.flags = CFTYPE_NOT_ON_ROOT,
6605 		.file_offset = offsetof(struct mem_cgroup, events_file),
6606 		.seq_show = memory_events_show,
6607 	},
6608 	{
6609 		.name = "events.local",
6610 		.flags = CFTYPE_NOT_ON_ROOT,
6611 		.file_offset = offsetof(struct mem_cgroup, events_local_file),
6612 		.seq_show = memory_events_local_show,
6613 	},
6614 	{
6615 		.name = "stat",
6616 		.seq_show = memory_stat_show,
6617 	},
6618 #ifdef CONFIG_NUMA
6619 	{
6620 		.name = "numa_stat",
6621 		.seq_show = memory_numa_stat_show,
6622 	},
6623 #endif
6624 	{
6625 		.name = "oom.group",
6626 		.flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE,
6627 		.seq_show = memory_oom_group_show,
6628 		.write = memory_oom_group_write,
6629 	},
6630 	{ }	/* terminate */
6631 };
6632 
6633 struct cgroup_subsys memory_cgrp_subsys = {
6634 	.css_alloc = mem_cgroup_css_alloc,
6635 	.css_online = mem_cgroup_css_online,
6636 	.css_offline = mem_cgroup_css_offline,
6637 	.css_released = mem_cgroup_css_released,
6638 	.css_free = mem_cgroup_css_free,
6639 	.css_reset = mem_cgroup_css_reset,
6640 	.can_attach = mem_cgroup_can_attach,
6641 	.cancel_attach = mem_cgroup_cancel_attach,
6642 	.post_attach = mem_cgroup_move_task,
6643 	.bind = mem_cgroup_bind,
6644 	.dfl_cftypes = memory_files,
6645 	.legacy_cftypes = mem_cgroup_legacy_files,
6646 	.early_init = 0,
6647 };
6648 
6649 /*
6650  * This function calculates an individual cgroup's effective
6651  * protection which is derived from its own memory.min/low, its
6652  * parent's and siblings' settings, as well as the actual memory
6653  * distribution in the tree.
6654  *
6655  * The following rules apply to the effective protection values:
6656  *
6657  * 1. At the first level of reclaim, effective protection is equal to
6658  *    the declared protection in memory.min and memory.low.
6659  *
6660  * 2. To enable safe delegation of the protection configuration, at
6661  *    subsequent levels the effective protection is capped to the
6662  *    parent's effective protection.
6663  *
6664  * 3. To make complex and dynamic subtrees easier to configure, the
6665  *    user is allowed to overcommit the declared protection at a given
6666  *    level. If that is the case, the parent's effective protection is
6667  *    distributed to the children in proportion to how much protection
6668  *    they have declared and how much of it they are utilizing.
6669  *
6670  *    This makes distribution proportional, but also work-conserving:
6671  *    if one cgroup claims much more protection than it uses memory,
6672  *    the unused remainder is available to its siblings.
6673  *
6674  * 4. Conversely, when the declared protection is undercommitted at a
6675  *    given level, the distribution of the larger parental protection
6676  *    budget is NOT proportional. A cgroup's protection from a sibling
6677  *    is capped to its own memory.min/low setting.
6678  *
6679  * 5. However, to allow protecting recursive subtrees from each other
6680  *    without having to declare each individual cgroup's fixed share
6681  *    of the ancestor's claim to protection, any unutilized -
6682  *    "floating" - protection from up the tree is distributed in
6683  *    proportion to each cgroup's *usage*. This makes the protection
6684  *    neutral wrt sibling cgroups and lets them compete freely over
6685  *    the shared parental protection budget, but it protects the
6686  *    subtree as a whole from neighboring subtrees.
6687  *
6688  * Note that 4. and 5. are not in conflict: 4. is about protecting
6689  * against immediate siblings whereas 5. is about protecting against
6690  * neighboring subtrees.
6691  */
effective_protection(unsigned long usage,unsigned long parent_usage,unsigned long setting,unsigned long parent_effective,unsigned long siblings_protected)6692 static unsigned long effective_protection(unsigned long usage,
6693 					  unsigned long parent_usage,
6694 					  unsigned long setting,
6695 					  unsigned long parent_effective,
6696 					  unsigned long siblings_protected)
6697 {
6698 	unsigned long protected;
6699 	unsigned long ep;
6700 
6701 	protected = min(usage, setting);
6702 	/*
6703 	 * If all cgroups at this level combined claim and use more
6704 	 * protection then what the parent affords them, distribute
6705 	 * shares in proportion to utilization.
6706 	 *
6707 	 * We are using actual utilization rather than the statically
6708 	 * claimed protection in order to be work-conserving: claimed
6709 	 * but unused protection is available to siblings that would
6710 	 * otherwise get a smaller chunk than what they claimed.
6711 	 */
6712 	if (siblings_protected > parent_effective)
6713 		return protected * parent_effective / siblings_protected;
6714 
6715 	/*
6716 	 * Ok, utilized protection of all children is within what the
6717 	 * parent affords them, so we know whatever this child claims
6718 	 * and utilizes is effectively protected.
6719 	 *
6720 	 * If there is unprotected usage beyond this value, reclaim
6721 	 * will apply pressure in proportion to that amount.
6722 	 *
6723 	 * If there is unutilized protection, the cgroup will be fully
6724 	 * shielded from reclaim, but we do return a smaller value for
6725 	 * protection than what the group could enjoy in theory. This
6726 	 * is okay. With the overcommit distribution above, effective
6727 	 * protection is always dependent on how memory is actually
6728 	 * consumed among the siblings anyway.
6729 	 */
6730 	ep = protected;
6731 
6732 	/*
6733 	 * If the children aren't claiming (all of) the protection
6734 	 * afforded to them by the parent, distribute the remainder in
6735 	 * proportion to the (unprotected) memory of each cgroup. That
6736 	 * way, cgroups that aren't explicitly prioritized wrt each
6737 	 * other compete freely over the allowance, but they are
6738 	 * collectively protected from neighboring trees.
6739 	 *
6740 	 * We're using unprotected memory for the weight so that if
6741 	 * some cgroups DO claim explicit protection, we don't protect
6742 	 * the same bytes twice.
6743 	 *
6744 	 * Check both usage and parent_usage against the respective
6745 	 * protected values. One should imply the other, but they
6746 	 * aren't read atomically - make sure the division is sane.
6747 	 */
6748 	if (!(cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT))
6749 		return ep;
6750 	if (parent_effective > siblings_protected &&
6751 	    parent_usage > siblings_protected &&
6752 	    usage > protected) {
6753 		unsigned long unclaimed;
6754 
6755 		unclaimed = parent_effective - siblings_protected;
6756 		unclaimed *= usage - protected;
6757 		unclaimed /= parent_usage - siblings_protected;
6758 
6759 		ep += unclaimed;
6760 	}
6761 
6762 	return ep;
6763 }
6764 
6765 /**
6766  * mem_cgroup_protected - check if memory consumption is in the normal range
6767  * @root: the top ancestor of the sub-tree being checked
6768  * @memcg: the memory cgroup to check
6769  *
6770  * WARNING: This function is not stateless! It can only be used as part
6771  *          of a top-down tree iteration, not for isolated queries.
6772  */
mem_cgroup_calculate_protection(struct mem_cgroup * root,struct mem_cgroup * memcg)6773 void mem_cgroup_calculate_protection(struct mem_cgroup *root,
6774 				     struct mem_cgroup *memcg)
6775 {
6776 	unsigned long usage, parent_usage;
6777 	struct mem_cgroup *parent;
6778 
6779 	if (mem_cgroup_disabled())
6780 		return;
6781 
6782 	if (!root)
6783 		root = root_mem_cgroup;
6784 
6785 	/*
6786 	 * Effective values of the reclaim targets are ignored so they
6787 	 * can be stale. Have a look at mem_cgroup_protection for more
6788 	 * details.
6789 	 * TODO: calculation should be more robust so that we do not need
6790 	 * that special casing.
6791 	 */
6792 	if (memcg == root)
6793 		return;
6794 
6795 	usage = page_counter_read(&memcg->memory);
6796 	if (!usage)
6797 		return;
6798 
6799 	parent = parent_mem_cgroup(memcg);
6800 	/* No parent means a non-hierarchical mode on v1 memcg */
6801 	if (!parent)
6802 		return;
6803 
6804 	if (parent == root) {
6805 		memcg->memory.emin = READ_ONCE(memcg->memory.min);
6806 		memcg->memory.elow = READ_ONCE(memcg->memory.low);
6807 		return;
6808 	}
6809 
6810 	parent_usage = page_counter_read(&parent->memory);
6811 
6812 	WRITE_ONCE(memcg->memory.emin, effective_protection(usage, parent_usage,
6813 			READ_ONCE(memcg->memory.min),
6814 			READ_ONCE(parent->memory.emin),
6815 			atomic_long_read(&parent->memory.children_min_usage)));
6816 
6817 	WRITE_ONCE(memcg->memory.elow, effective_protection(usage, parent_usage,
6818 			READ_ONCE(memcg->memory.low),
6819 			READ_ONCE(parent->memory.elow),
6820 			atomic_long_read(&parent->memory.children_low_usage)));
6821 }
6822 
6823 /**
6824  * mem_cgroup_charge - charge a newly allocated page to a cgroup
6825  * @page: page to charge
6826  * @mm: mm context of the victim
6827  * @gfp_mask: reclaim mode
6828  *
6829  * Try to charge @page to the memcg that @mm belongs to, reclaiming
6830  * pages according to @gfp_mask if necessary.
6831  *
6832  * Returns 0 on success. Otherwise, an error code is returned.
6833  */
mem_cgroup_charge(struct page * page,struct mm_struct * mm,gfp_t gfp_mask)6834 int mem_cgroup_charge(struct page *page, struct mm_struct *mm, gfp_t gfp_mask)
6835 {
6836 	unsigned int nr_pages = thp_nr_pages(page);
6837 	struct mem_cgroup *memcg = NULL;
6838 	int ret = 0;
6839 
6840 	if (mem_cgroup_disabled())
6841 		goto out;
6842 
6843 	if (PageSwapCache(page)) {
6844 		swp_entry_t ent = { .val = page_private(page), };
6845 		unsigned short id;
6846 
6847 		/*
6848 		 * Every swap fault against a single page tries to charge the
6849 		 * page, bail as early as possible.  shmem_unuse() encounters
6850 		 * already charged pages, too.  page->mem_cgroup is protected
6851 		 * by the page lock, which serializes swap cache removal, which
6852 		 * in turn serializes uncharging.
6853 		 */
6854 		VM_BUG_ON_PAGE(!PageLocked(page), page);
6855 		if (compound_head(page)->mem_cgroup)
6856 			goto out;
6857 
6858 		id = lookup_swap_cgroup_id(ent);
6859 		rcu_read_lock();
6860 		memcg = mem_cgroup_from_id(id);
6861 		if (memcg && !css_tryget_online(&memcg->css))
6862 			memcg = NULL;
6863 		rcu_read_unlock();
6864 	}
6865 
6866 	if (!memcg)
6867 		memcg = get_mem_cgroup_from_mm(mm);
6868 
6869 	ret = try_charge(memcg, gfp_mask, nr_pages);
6870 	if (ret)
6871 		goto out_put;
6872 
6873 	css_get(&memcg->css);
6874 	commit_charge(page, memcg);
6875 
6876 	local_irq_disable();
6877 	mem_cgroup_charge_statistics(memcg, page, nr_pages);
6878 	memcg_check_events(memcg, page);
6879 	local_irq_enable();
6880 
6881 	/*
6882 	 * Cgroup1's unified memory+swap counter has been charged with the
6883 	 * new swapcache page, finish the transfer by uncharging the swap
6884 	 * slot. The swap slot would also get uncharged when it dies, but
6885 	 * it can stick around indefinitely and we'd count the page twice
6886 	 * the entire time.
6887 	 *
6888 	 * Cgroup2 has separate resource counters for memory and swap,
6889 	 * so this is a non-issue here. Memory and swap charge lifetimes
6890 	 * correspond 1:1 to page and swap slot lifetimes: we charge the
6891 	 * page to memory here, and uncharge swap when the slot is freed.
6892 	 */
6893 	if (do_memsw_account() && PageSwapCache(page)) {
6894 		swp_entry_t entry = { .val = page_private(page) };
6895 		/*
6896 		 * The swap entry might not get freed for a long time,
6897 		 * let's not wait for it.  The page already received a
6898 		 * memory+swap charge, drop the swap entry duplicate.
6899 		 */
6900 		mem_cgroup_uncharge_swap(entry, nr_pages);
6901 	}
6902 
6903 out_put:
6904 	css_put(&memcg->css);
6905 out:
6906 	return ret;
6907 }
6908 
6909 struct uncharge_gather {
6910 	struct mem_cgroup *memcg;
6911 	unsigned long nr_pages;
6912 	unsigned long pgpgout;
6913 	unsigned long nr_kmem;
6914 	struct page *dummy_page;
6915 };
6916 
uncharge_gather_clear(struct uncharge_gather * ug)6917 static inline void uncharge_gather_clear(struct uncharge_gather *ug)
6918 {
6919 	memset(ug, 0, sizeof(*ug));
6920 }
6921 
uncharge_batch(const struct uncharge_gather * ug)6922 static void uncharge_batch(const struct uncharge_gather *ug)
6923 {
6924 	unsigned long flags;
6925 
6926 	if (!mem_cgroup_is_root(ug->memcg)) {
6927 		page_counter_uncharge(&ug->memcg->memory, ug->nr_pages);
6928 		if (do_memsw_account())
6929 			page_counter_uncharge(&ug->memcg->memsw, ug->nr_pages);
6930 		if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && ug->nr_kmem)
6931 			page_counter_uncharge(&ug->memcg->kmem, ug->nr_kmem);
6932 		memcg_oom_recover(ug->memcg);
6933 	}
6934 
6935 	local_irq_save(flags);
6936 	__count_memcg_events(ug->memcg, PGPGOUT, ug->pgpgout);
6937 	__this_cpu_add(ug->memcg->vmstats_percpu->nr_page_events, ug->nr_pages);
6938 	memcg_check_events(ug->memcg, ug->dummy_page);
6939 	local_irq_restore(flags);
6940 
6941 	/* drop reference from uncharge_page */
6942 	css_put(&ug->memcg->css);
6943 }
6944 
uncharge_page(struct page * page,struct uncharge_gather * ug)6945 static void uncharge_page(struct page *page, struct uncharge_gather *ug)
6946 {
6947 	unsigned long nr_pages;
6948 
6949 	VM_BUG_ON_PAGE(PageLRU(page), page);
6950 
6951 	if (!page->mem_cgroup)
6952 		return;
6953 
6954 	/*
6955 	 * Nobody should be changing or seriously looking at
6956 	 * page->mem_cgroup at this point, we have fully
6957 	 * exclusive access to the page.
6958 	 */
6959 
6960 	if (ug->memcg != page->mem_cgroup) {
6961 		if (ug->memcg) {
6962 			uncharge_batch(ug);
6963 			uncharge_gather_clear(ug);
6964 		}
6965 		ug->memcg = page->mem_cgroup;
6966 
6967 		/* pairs with css_put in uncharge_batch */
6968 		css_get(&ug->memcg->css);
6969 	}
6970 
6971 	nr_pages = compound_nr(page);
6972 	ug->nr_pages += nr_pages;
6973 
6974 	if (!PageKmemcg(page)) {
6975 		ug->pgpgout++;
6976 	} else {
6977 		ug->nr_kmem += nr_pages;
6978 		__ClearPageKmemcg(page);
6979 	}
6980 
6981 	ug->dummy_page = page;
6982 	page->mem_cgroup = NULL;
6983 	css_put(&ug->memcg->css);
6984 }
6985 
uncharge_list(struct list_head * page_list)6986 static void uncharge_list(struct list_head *page_list)
6987 {
6988 	struct uncharge_gather ug;
6989 	struct list_head *next;
6990 
6991 	uncharge_gather_clear(&ug);
6992 
6993 	/*
6994 	 * Note that the list can be a single page->lru; hence the
6995 	 * do-while loop instead of a simple list_for_each_entry().
6996 	 */
6997 	next = page_list->next;
6998 	do {
6999 		struct page *page;
7000 
7001 		page = list_entry(next, struct page, lru);
7002 		next = page->lru.next;
7003 
7004 		uncharge_page(page, &ug);
7005 	} while (next != page_list);
7006 
7007 	if (ug.memcg)
7008 		uncharge_batch(&ug);
7009 }
7010 
7011 /**
7012  * mem_cgroup_uncharge - uncharge a page
7013  * @page: page to uncharge
7014  *
7015  * Uncharge a page previously charged with mem_cgroup_charge().
7016  */
mem_cgroup_uncharge(struct page * page)7017 void mem_cgroup_uncharge(struct page *page)
7018 {
7019 	struct uncharge_gather ug;
7020 
7021 	if (mem_cgroup_disabled())
7022 		return;
7023 
7024 	/* Don't touch page->lru of any random page, pre-check: */
7025 	if (!page->mem_cgroup)
7026 		return;
7027 
7028 	uncharge_gather_clear(&ug);
7029 	uncharge_page(page, &ug);
7030 	uncharge_batch(&ug);
7031 }
7032 
7033 /**
7034  * mem_cgroup_uncharge_list - uncharge a list of page
7035  * @page_list: list of pages to uncharge
7036  *
7037  * Uncharge a list of pages previously charged with
7038  * mem_cgroup_charge().
7039  */
mem_cgroup_uncharge_list(struct list_head * page_list)7040 void mem_cgroup_uncharge_list(struct list_head *page_list)
7041 {
7042 	if (mem_cgroup_disabled())
7043 		return;
7044 
7045 	if (!list_empty(page_list))
7046 		uncharge_list(page_list);
7047 }
7048 
7049 /**
7050  * mem_cgroup_migrate - charge a page's replacement
7051  * @oldpage: currently circulating page
7052  * @newpage: replacement page
7053  *
7054  * Charge @newpage as a replacement page for @oldpage. @oldpage will
7055  * be uncharged upon free.
7056  *
7057  * Both pages must be locked, @newpage->mapping must be set up.
7058  */
mem_cgroup_migrate(struct page * oldpage,struct page * newpage)7059 void mem_cgroup_migrate(struct page *oldpage, struct page *newpage)
7060 {
7061 	struct mem_cgroup *memcg;
7062 	unsigned int nr_pages;
7063 	unsigned long flags;
7064 
7065 	VM_BUG_ON_PAGE(!PageLocked(oldpage), oldpage);
7066 	VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
7067 	VM_BUG_ON_PAGE(PageAnon(oldpage) != PageAnon(newpage), newpage);
7068 	VM_BUG_ON_PAGE(PageTransHuge(oldpage) != PageTransHuge(newpage),
7069 		       newpage);
7070 
7071 	if (mem_cgroup_disabled())
7072 		return;
7073 
7074 	/* Page cache replacement: new page already charged? */
7075 	if (newpage->mem_cgroup)
7076 		return;
7077 
7078 	/* Swapcache readahead pages can get replaced before being charged */
7079 	memcg = oldpage->mem_cgroup;
7080 	if (!memcg)
7081 		return;
7082 
7083 	/* Force-charge the new page. The old one will be freed soon */
7084 	nr_pages = thp_nr_pages(newpage);
7085 
7086 	page_counter_charge(&memcg->memory, nr_pages);
7087 	if (do_memsw_account())
7088 		page_counter_charge(&memcg->memsw, nr_pages);
7089 
7090 	css_get(&memcg->css);
7091 	commit_charge(newpage, memcg);
7092 
7093 	local_irq_save(flags);
7094 	mem_cgroup_charge_statistics(memcg, newpage, nr_pages);
7095 	memcg_check_events(memcg, newpage);
7096 	local_irq_restore(flags);
7097 }
7098 
7099 DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key);
7100 EXPORT_SYMBOL(memcg_sockets_enabled_key);
7101 
mem_cgroup_sk_alloc(struct sock * sk)7102 void mem_cgroup_sk_alloc(struct sock *sk)
7103 {
7104 	struct mem_cgroup *memcg;
7105 
7106 	if (!mem_cgroup_sockets_enabled)
7107 		return;
7108 
7109 	/* Do not associate the sock with unrelated interrupted task's memcg. */
7110 	if (in_interrupt())
7111 		return;
7112 
7113 	rcu_read_lock();
7114 	memcg = mem_cgroup_from_task(current);
7115 	if (memcg == root_mem_cgroup)
7116 		goto out;
7117 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg->tcpmem_active)
7118 		goto out;
7119 	if (css_tryget(&memcg->css))
7120 		sk->sk_memcg = memcg;
7121 out:
7122 	rcu_read_unlock();
7123 }
7124 
mem_cgroup_sk_free(struct sock * sk)7125 void mem_cgroup_sk_free(struct sock *sk)
7126 {
7127 	if (sk->sk_memcg)
7128 		css_put(&sk->sk_memcg->css);
7129 }
7130 
7131 /**
7132  * mem_cgroup_charge_skmem - charge socket memory
7133  * @memcg: memcg to charge
7134  * @nr_pages: number of pages to charge
7135  *
7136  * Charges @nr_pages to @memcg. Returns %true if the charge fit within
7137  * @memcg's configured limit, %false if the charge had to be forced.
7138  */
mem_cgroup_charge_skmem(struct mem_cgroup * memcg,unsigned int nr_pages)7139 bool mem_cgroup_charge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
7140 {
7141 	gfp_t gfp_mask = GFP_KERNEL;
7142 
7143 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
7144 		struct page_counter *fail;
7145 
7146 		if (page_counter_try_charge(&memcg->tcpmem, nr_pages, &fail)) {
7147 			memcg->tcpmem_pressure = 0;
7148 			return true;
7149 		}
7150 		page_counter_charge(&memcg->tcpmem, nr_pages);
7151 		memcg->tcpmem_pressure = 1;
7152 		return false;
7153 	}
7154 
7155 	/* Don't block in the packet receive path */
7156 	if (in_softirq())
7157 		gfp_mask = GFP_NOWAIT;
7158 
7159 	mod_memcg_state(memcg, MEMCG_SOCK, nr_pages);
7160 
7161 	if (try_charge(memcg, gfp_mask, nr_pages) == 0)
7162 		return true;
7163 
7164 	try_charge(memcg, gfp_mask|__GFP_NOFAIL, nr_pages);
7165 	return false;
7166 }
7167 
7168 /**
7169  * mem_cgroup_uncharge_skmem - uncharge socket memory
7170  * @memcg: memcg to uncharge
7171  * @nr_pages: number of pages to uncharge
7172  */
mem_cgroup_uncharge_skmem(struct mem_cgroup * memcg,unsigned int nr_pages)7173 void mem_cgroup_uncharge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
7174 {
7175 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
7176 		page_counter_uncharge(&memcg->tcpmem, nr_pages);
7177 		return;
7178 	}
7179 
7180 	mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages);
7181 
7182 	refill_stock(memcg, nr_pages);
7183 }
7184 
cgroup_memory(char * s)7185 static int __init cgroup_memory(char *s)
7186 {
7187 	char *token;
7188 
7189 	while ((token = strsep(&s, ",")) != NULL) {
7190 		if (!*token)
7191 			continue;
7192 		if (!strcmp(token, "nosocket"))
7193 			cgroup_memory_nosocket = true;
7194 		if (!strcmp(token, "nokmem"))
7195 			cgroup_memory_nokmem = true;
7196 		else if (!strcmp(token, "kmem"))
7197 			cgroup_memory_nokmem = false;
7198 	}
7199 	return 0;
7200 }
7201 __setup("cgroup.memory=", cgroup_memory);
7202 
7203 /*
7204  * subsys_initcall() for memory controller.
7205  *
7206  * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this
7207  * context because of lock dependencies (cgroup_lock -> cpu hotplug) but
7208  * basically everything that doesn't depend on a specific mem_cgroup structure
7209  * should be initialized from here.
7210  */
mem_cgroup_init(void)7211 static int __init mem_cgroup_init(void)
7212 {
7213 	int cpu, node;
7214 
7215 	cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL,
7216 				  memcg_hotplug_cpu_dead);
7217 
7218 	for_each_possible_cpu(cpu)
7219 		INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
7220 			  drain_local_stock);
7221 
7222 	for_each_node(node) {
7223 		struct mem_cgroup_tree_per_node *rtpn;
7224 
7225 		rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL,
7226 				    node_online(node) ? node : NUMA_NO_NODE);
7227 
7228 		rtpn->rb_root = RB_ROOT;
7229 		rtpn->rb_rightmost = NULL;
7230 		spin_lock_init(&rtpn->lock);
7231 		soft_limit_tree.rb_tree_per_node[node] = rtpn;
7232 	}
7233 
7234 	return 0;
7235 }
7236 subsys_initcall(mem_cgroup_init);
7237 
7238 #ifdef CONFIG_MEMCG_SWAP
mem_cgroup_id_get_online(struct mem_cgroup * memcg)7239 static struct mem_cgroup *mem_cgroup_id_get_online(struct mem_cgroup *memcg)
7240 {
7241 	while (!refcount_inc_not_zero(&memcg->id.ref)) {
7242 		/*
7243 		 * The root cgroup cannot be destroyed, so it's refcount must
7244 		 * always be >= 1.
7245 		 */
7246 		if (WARN_ON_ONCE(memcg == root_mem_cgroup)) {
7247 			VM_BUG_ON(1);
7248 			break;
7249 		}
7250 		memcg = parent_mem_cgroup(memcg);
7251 		if (!memcg)
7252 			memcg = root_mem_cgroup;
7253 	}
7254 	return memcg;
7255 }
7256 
7257 /**
7258  * mem_cgroup_swapout - transfer a memsw charge to swap
7259  * @page: page whose memsw charge to transfer
7260  * @entry: swap entry to move the charge to
7261  *
7262  * Transfer the memsw charge of @page to @entry.
7263  */
mem_cgroup_swapout(struct page * page,swp_entry_t entry)7264 void mem_cgroup_swapout(struct page *page, swp_entry_t entry)
7265 {
7266 	struct mem_cgroup *memcg, *swap_memcg;
7267 	unsigned int nr_entries;
7268 	unsigned short oldid;
7269 
7270 	VM_BUG_ON_PAGE(PageLRU(page), page);
7271 	VM_BUG_ON_PAGE(page_count(page), page);
7272 
7273 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
7274 		return;
7275 
7276 	memcg = page->mem_cgroup;
7277 
7278 	/* Readahead page, never charged */
7279 	if (!memcg)
7280 		return;
7281 
7282 	/*
7283 	 * In case the memcg owning these pages has been offlined and doesn't
7284 	 * have an ID allocated to it anymore, charge the closest online
7285 	 * ancestor for the swap instead and transfer the memory+swap charge.
7286 	 */
7287 	swap_memcg = mem_cgroup_id_get_online(memcg);
7288 	nr_entries = thp_nr_pages(page);
7289 	/* Get references for the tail pages, too */
7290 	if (nr_entries > 1)
7291 		mem_cgroup_id_get_many(swap_memcg, nr_entries - 1);
7292 	oldid = swap_cgroup_record(entry, mem_cgroup_id(swap_memcg),
7293 				   nr_entries);
7294 	VM_BUG_ON_PAGE(oldid, page);
7295 	mod_memcg_state(swap_memcg, MEMCG_SWAP, nr_entries);
7296 
7297 	page->mem_cgroup = NULL;
7298 
7299 	if (!mem_cgroup_is_root(memcg))
7300 		page_counter_uncharge(&memcg->memory, nr_entries);
7301 
7302 	if (!cgroup_memory_noswap && memcg != swap_memcg) {
7303 		if (!mem_cgroup_is_root(swap_memcg))
7304 			page_counter_charge(&swap_memcg->memsw, nr_entries);
7305 		page_counter_uncharge(&memcg->memsw, nr_entries);
7306 	}
7307 
7308 	/*
7309 	 * Interrupts should be disabled here because the caller holds the
7310 	 * i_pages lock which is taken with interrupts-off. It is
7311 	 * important here to have the interrupts disabled because it is the
7312 	 * only synchronisation we have for updating the per-CPU variables.
7313 	 */
7314 	VM_BUG_ON(!irqs_disabled());
7315 	mem_cgroup_charge_statistics(memcg, page, -nr_entries);
7316 	memcg_check_events(memcg, page);
7317 
7318 	css_put(&memcg->css);
7319 }
7320 
7321 /**
7322  * mem_cgroup_try_charge_swap - try charging swap space for a page
7323  * @page: page being added to swap
7324  * @entry: swap entry to charge
7325  *
7326  * Try to charge @page's memcg for the swap space at @entry.
7327  *
7328  * Returns 0 on success, -ENOMEM on failure.
7329  */
mem_cgroup_try_charge_swap(struct page * page,swp_entry_t entry)7330 int mem_cgroup_try_charge_swap(struct page *page, swp_entry_t entry)
7331 {
7332 	unsigned int nr_pages = thp_nr_pages(page);
7333 	struct page_counter *counter;
7334 	struct mem_cgroup *memcg;
7335 	unsigned short oldid;
7336 
7337 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
7338 		return 0;
7339 
7340 	memcg = page->mem_cgroup;
7341 
7342 	/* Readahead page, never charged */
7343 	if (!memcg)
7344 		return 0;
7345 
7346 	if (!entry.val) {
7347 		memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
7348 		return 0;
7349 	}
7350 
7351 	memcg = mem_cgroup_id_get_online(memcg);
7352 
7353 	if (!cgroup_memory_noswap && !mem_cgroup_is_root(memcg) &&
7354 	    !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
7355 		memcg_memory_event(memcg, MEMCG_SWAP_MAX);
7356 		memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
7357 		mem_cgroup_id_put(memcg);
7358 		return -ENOMEM;
7359 	}
7360 
7361 	/* Get references for the tail pages, too */
7362 	if (nr_pages > 1)
7363 		mem_cgroup_id_get_many(memcg, nr_pages - 1);
7364 	oldid = swap_cgroup_record(entry, mem_cgroup_id(memcg), nr_pages);
7365 	VM_BUG_ON_PAGE(oldid, page);
7366 	mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
7367 
7368 	return 0;
7369 }
7370 
7371 /**
7372  * mem_cgroup_uncharge_swap - uncharge swap space
7373  * @entry: swap entry to uncharge
7374  * @nr_pages: the amount of swap space to uncharge
7375  */
mem_cgroup_uncharge_swap(swp_entry_t entry,unsigned int nr_pages)7376 void mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages)
7377 {
7378 	struct mem_cgroup *memcg;
7379 	unsigned short id;
7380 
7381 	id = swap_cgroup_record(entry, 0, nr_pages);
7382 	rcu_read_lock();
7383 	memcg = mem_cgroup_from_id(id);
7384 	if (memcg) {
7385 		if (!cgroup_memory_noswap && !mem_cgroup_is_root(memcg)) {
7386 			if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
7387 				page_counter_uncharge(&memcg->swap, nr_pages);
7388 			else
7389 				page_counter_uncharge(&memcg->memsw, nr_pages);
7390 		}
7391 		mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
7392 		mem_cgroup_id_put_many(memcg, nr_pages);
7393 	}
7394 	rcu_read_unlock();
7395 }
7396 
mem_cgroup_get_nr_swap_pages(struct mem_cgroup * memcg)7397 long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg)
7398 {
7399 	long nr_swap_pages = get_nr_swap_pages();
7400 
7401 	if (cgroup_memory_noswap || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
7402 		return nr_swap_pages;
7403 	for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg))
7404 		nr_swap_pages = min_t(long, nr_swap_pages,
7405 				      READ_ONCE(memcg->swap.max) -
7406 				      page_counter_read(&memcg->swap));
7407 	return nr_swap_pages;
7408 }
7409 
mem_cgroup_swap_full(struct page * page)7410 bool mem_cgroup_swap_full(struct page *page)
7411 {
7412 	struct mem_cgroup *memcg;
7413 
7414 	VM_BUG_ON_PAGE(!PageLocked(page), page);
7415 
7416 	if (vm_swap_full())
7417 		return true;
7418 	if (cgroup_memory_noswap || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
7419 		return false;
7420 
7421 	memcg = page->mem_cgroup;
7422 	if (!memcg)
7423 		return false;
7424 
7425 	for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg)) {
7426 		unsigned long usage = page_counter_read(&memcg->swap);
7427 
7428 		if (usage * 2 >= READ_ONCE(memcg->swap.high) ||
7429 		    usage * 2 >= READ_ONCE(memcg->swap.max))
7430 			return true;
7431 	}
7432 
7433 	return false;
7434 }
7435 
setup_swap_account(char * s)7436 static int __init setup_swap_account(char *s)
7437 {
7438 	if (!strcmp(s, "1"))
7439 		cgroup_memory_noswap = 0;
7440 	else if (!strcmp(s, "0"))
7441 		cgroup_memory_noswap = 1;
7442 	return 1;
7443 }
7444 __setup("swapaccount=", setup_swap_account);
7445 
swap_current_read(struct cgroup_subsys_state * css,struct cftype * cft)7446 static u64 swap_current_read(struct cgroup_subsys_state *css,
7447 			     struct cftype *cft)
7448 {
7449 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
7450 
7451 	return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE;
7452 }
7453 
swap_high_show(struct seq_file * m,void * v)7454 static int swap_high_show(struct seq_file *m, void *v)
7455 {
7456 	return seq_puts_memcg_tunable(m,
7457 		READ_ONCE(mem_cgroup_from_seq(m)->swap.high));
7458 }
7459 
swap_high_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)7460 static ssize_t swap_high_write(struct kernfs_open_file *of,
7461 			       char *buf, size_t nbytes, loff_t off)
7462 {
7463 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7464 	unsigned long high;
7465 	int err;
7466 
7467 	buf = strstrip(buf);
7468 	err = page_counter_memparse(buf, "max", &high);
7469 	if (err)
7470 		return err;
7471 
7472 	page_counter_set_high(&memcg->swap, high);
7473 
7474 	return nbytes;
7475 }
7476 
swap_max_show(struct seq_file * m,void * v)7477 static int swap_max_show(struct seq_file *m, void *v)
7478 {
7479 	return seq_puts_memcg_tunable(m,
7480 		READ_ONCE(mem_cgroup_from_seq(m)->swap.max));
7481 }
7482 
swap_max_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)7483 static ssize_t swap_max_write(struct kernfs_open_file *of,
7484 			      char *buf, size_t nbytes, loff_t off)
7485 {
7486 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7487 	unsigned long max;
7488 	int err;
7489 
7490 	buf = strstrip(buf);
7491 	err = page_counter_memparse(buf, "max", &max);
7492 	if (err)
7493 		return err;
7494 
7495 	xchg(&memcg->swap.max, max);
7496 
7497 	return nbytes;
7498 }
7499 
swap_events_show(struct seq_file * m,void * v)7500 static int swap_events_show(struct seq_file *m, void *v)
7501 {
7502 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
7503 
7504 	seq_printf(m, "high %lu\n",
7505 		   atomic_long_read(&memcg->memory_events[MEMCG_SWAP_HIGH]));
7506 	seq_printf(m, "max %lu\n",
7507 		   atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
7508 	seq_printf(m, "fail %lu\n",
7509 		   atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL]));
7510 
7511 	return 0;
7512 }
7513 
7514 static struct cftype swap_files[] = {
7515 	{
7516 		.name = "swap.current",
7517 		.flags = CFTYPE_NOT_ON_ROOT,
7518 		.read_u64 = swap_current_read,
7519 	},
7520 	{
7521 		.name = "swap.high",
7522 		.flags = CFTYPE_NOT_ON_ROOT,
7523 		.seq_show = swap_high_show,
7524 		.write = swap_high_write,
7525 	},
7526 	{
7527 		.name = "swap.max",
7528 		.flags = CFTYPE_NOT_ON_ROOT,
7529 		.seq_show = swap_max_show,
7530 		.write = swap_max_write,
7531 	},
7532 	{
7533 		.name = "swap.events",
7534 		.flags = CFTYPE_NOT_ON_ROOT,
7535 		.file_offset = offsetof(struct mem_cgroup, swap_events_file),
7536 		.seq_show = swap_events_show,
7537 	},
7538 	{ }	/* terminate */
7539 };
7540 
7541 static struct cftype memsw_files[] = {
7542 	{
7543 		.name = "memsw.usage_in_bytes",
7544 		.private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
7545 		.read_u64 = mem_cgroup_read_u64,
7546 	},
7547 	{
7548 		.name = "memsw.max_usage_in_bytes",
7549 		.private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
7550 		.write = mem_cgroup_reset,
7551 		.read_u64 = mem_cgroup_read_u64,
7552 	},
7553 	{
7554 		.name = "memsw.limit_in_bytes",
7555 		.private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
7556 		.write = mem_cgroup_write,
7557 		.read_u64 = mem_cgroup_read_u64,
7558 	},
7559 	{
7560 		.name = "memsw.failcnt",
7561 		.private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
7562 		.write = mem_cgroup_reset,
7563 		.read_u64 = mem_cgroup_read_u64,
7564 	},
7565 	{ },	/* terminate */
7566 };
7567 
7568 /*
7569  * If mem_cgroup_swap_init() is implemented as a subsys_initcall()
7570  * instead of a core_initcall(), this could mean cgroup_memory_noswap still
7571  * remains set to false even when memcg is disabled via "cgroup_disable=memory"
7572  * boot parameter. This may result in premature OOPS inside
7573  * mem_cgroup_get_nr_swap_pages() function in corner cases.
7574  */
mem_cgroup_swap_init(void)7575 static int __init mem_cgroup_swap_init(void)
7576 {
7577 	/* No memory control -> no swap control */
7578 	if (mem_cgroup_disabled())
7579 		cgroup_memory_noswap = true;
7580 
7581 	if (cgroup_memory_noswap)
7582 		return 0;
7583 
7584 	WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, swap_files));
7585 	WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys, memsw_files));
7586 
7587 	return 0;
7588 }
7589 core_initcall(mem_cgroup_swap_init);
7590 
7591 #endif /* CONFIG_MEMCG_SWAP */
7592