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