xref: /linux/mm/memcontrol.c (revision 61d0b5a4b2777dcf5daef245e212b3c1fa8091ca)
1 /* memcontrol.c - Memory Controller
2  *
3  * Copyright IBM Corporation, 2007
4  * Author Balbir Singh <balbir@linux.vnet.ibm.com>
5  *
6  * Copyright 2007 OpenVZ SWsoft Inc
7  * Author: Pavel Emelianov <xemul@openvz.org>
8  *
9  * Memory thresholds
10  * Copyright (C) 2009 Nokia Corporation
11  * Author: Kirill A. Shutemov
12  *
13  * Kernel Memory Controller
14  * Copyright (C) 2012 Parallels Inc. and Google Inc.
15  * Authors: Glauber Costa and Suleiman Souhlal
16  *
17  * This program is free software; you can redistribute it and/or modify
18  * it under the terms of the GNU General Public License as published by
19  * the Free Software Foundation; either version 2 of the License, or
20  * (at your option) any later version.
21  *
22  * This program is distributed in the hope that it will be useful,
23  * but WITHOUT ANY WARRANTY; without even the implied warranty of
24  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25  * GNU General Public License for more details.
26  */
27 
28 #include <linux/res_counter.h>
29 #include <linux/memcontrol.h>
30 #include <linux/cgroup.h>
31 #include <linux/mm.h>
32 #include <linux/hugetlb.h>
33 #include <linux/pagemap.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/sort.h>
49 #include <linux/fs.h>
50 #include <linux/seq_file.h>
51 #include <linux/vmalloc.h>
52 #include <linux/mm_inline.h>
53 #include <linux/page_cgroup.h>
54 #include <linux/cpu.h>
55 #include <linux/oom.h>
56 #include "internal.h"
57 #include <net/sock.h>
58 #include <net/ip.h>
59 #include <net/tcp_memcontrol.h>
60 
61 #include <asm/uaccess.h>
62 
63 #include <trace/events/vmscan.h>
64 
65 struct cgroup_subsys mem_cgroup_subsys __read_mostly;
66 EXPORT_SYMBOL(mem_cgroup_subsys);
67 
68 #define MEM_CGROUP_RECLAIM_RETRIES	5
69 static struct mem_cgroup *root_mem_cgroup __read_mostly;
70 
71 #ifdef CONFIG_MEMCG_SWAP
72 /* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
73 int do_swap_account __read_mostly;
74 
75 /* for remember boot option*/
76 #ifdef CONFIG_MEMCG_SWAP_ENABLED
77 static int really_do_swap_account __initdata = 1;
78 #else
79 static int really_do_swap_account __initdata = 0;
80 #endif
81 
82 #else
83 #define do_swap_account		0
84 #endif
85 
86 
87 /*
88  * Statistics for memory cgroup.
89  */
90 enum mem_cgroup_stat_index {
91 	/*
92 	 * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
93 	 */
94 	MEM_CGROUP_STAT_CACHE, 	   /* # of pages charged as cache */
95 	MEM_CGROUP_STAT_RSS,	   /* # of pages charged as anon rss */
96 	MEM_CGROUP_STAT_FILE_MAPPED,  /* # of pages charged as file rss */
97 	MEM_CGROUP_STAT_SWAP, /* # of pages, swapped out */
98 	MEM_CGROUP_STAT_NSTATS,
99 };
100 
101 static const char * const mem_cgroup_stat_names[] = {
102 	"cache",
103 	"rss",
104 	"mapped_file",
105 	"swap",
106 };
107 
108 enum mem_cgroup_events_index {
109 	MEM_CGROUP_EVENTS_PGPGIN,	/* # of pages paged in */
110 	MEM_CGROUP_EVENTS_PGPGOUT,	/* # of pages paged out */
111 	MEM_CGROUP_EVENTS_PGFAULT,	/* # of page-faults */
112 	MEM_CGROUP_EVENTS_PGMAJFAULT,	/* # of major page-faults */
113 	MEM_CGROUP_EVENTS_NSTATS,
114 };
115 
116 static const char * const mem_cgroup_events_names[] = {
117 	"pgpgin",
118 	"pgpgout",
119 	"pgfault",
120 	"pgmajfault",
121 };
122 
123 static const char * const mem_cgroup_lru_names[] = {
124 	"inactive_anon",
125 	"active_anon",
126 	"inactive_file",
127 	"active_file",
128 	"unevictable",
129 };
130 
131 /*
132  * Per memcg event counter is incremented at every pagein/pageout. With THP,
133  * it will be incremated by the number of pages. This counter is used for
134  * for trigger some periodic events. This is straightforward and better
135  * than using jiffies etc. to handle periodic memcg event.
136  */
137 enum mem_cgroup_events_target {
138 	MEM_CGROUP_TARGET_THRESH,
139 	MEM_CGROUP_TARGET_SOFTLIMIT,
140 	MEM_CGROUP_TARGET_NUMAINFO,
141 	MEM_CGROUP_NTARGETS,
142 };
143 #define THRESHOLDS_EVENTS_TARGET 128
144 #define SOFTLIMIT_EVENTS_TARGET 1024
145 #define NUMAINFO_EVENTS_TARGET	1024
146 
147 struct mem_cgroup_stat_cpu {
148 	long count[MEM_CGROUP_STAT_NSTATS];
149 	unsigned long events[MEM_CGROUP_EVENTS_NSTATS];
150 	unsigned long nr_page_events;
151 	unsigned long targets[MEM_CGROUP_NTARGETS];
152 };
153 
154 struct mem_cgroup_reclaim_iter {
155 	/* css_id of the last scanned hierarchy member */
156 	int position;
157 	/* scan generation, increased every round-trip */
158 	unsigned int generation;
159 };
160 
161 /*
162  * per-zone information in memory controller.
163  */
164 struct mem_cgroup_per_zone {
165 	struct lruvec		lruvec;
166 	unsigned long		lru_size[NR_LRU_LISTS];
167 
168 	struct mem_cgroup_reclaim_iter reclaim_iter[DEF_PRIORITY + 1];
169 
170 	struct rb_node		tree_node;	/* RB tree node */
171 	unsigned long long	usage_in_excess;/* Set to the value by which */
172 						/* the soft limit is exceeded*/
173 	bool			on_tree;
174 	struct mem_cgroup	*memcg;		/* Back pointer, we cannot */
175 						/* use container_of	   */
176 };
177 
178 struct mem_cgroup_per_node {
179 	struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
180 };
181 
182 struct mem_cgroup_lru_info {
183 	struct mem_cgroup_per_node *nodeinfo[0];
184 };
185 
186 /*
187  * Cgroups above their limits are maintained in a RB-Tree, independent of
188  * their hierarchy representation
189  */
190 
191 struct mem_cgroup_tree_per_zone {
192 	struct rb_root rb_root;
193 	spinlock_t lock;
194 };
195 
196 struct mem_cgroup_tree_per_node {
197 	struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
198 };
199 
200 struct mem_cgroup_tree {
201 	struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
202 };
203 
204 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
205 
206 struct mem_cgroup_threshold {
207 	struct eventfd_ctx *eventfd;
208 	u64 threshold;
209 };
210 
211 /* For threshold */
212 struct mem_cgroup_threshold_ary {
213 	/* An array index points to threshold just below or equal to usage. */
214 	int current_threshold;
215 	/* Size of entries[] */
216 	unsigned int size;
217 	/* Array of thresholds */
218 	struct mem_cgroup_threshold entries[0];
219 };
220 
221 struct mem_cgroup_thresholds {
222 	/* Primary thresholds array */
223 	struct mem_cgroup_threshold_ary *primary;
224 	/*
225 	 * Spare threshold array.
226 	 * This is needed to make mem_cgroup_unregister_event() "never fail".
227 	 * It must be able to store at least primary->size - 1 entries.
228 	 */
229 	struct mem_cgroup_threshold_ary *spare;
230 };
231 
232 /* for OOM */
233 struct mem_cgroup_eventfd_list {
234 	struct list_head list;
235 	struct eventfd_ctx *eventfd;
236 };
237 
238 static void mem_cgroup_threshold(struct mem_cgroup *memcg);
239 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
240 
241 /*
242  * The memory controller data structure. The memory controller controls both
243  * page cache and RSS per cgroup. We would eventually like to provide
244  * statistics based on the statistics developed by Rik Van Riel for clock-pro,
245  * to help the administrator determine what knobs to tune.
246  *
247  * TODO: Add a water mark for the memory controller. Reclaim will begin when
248  * we hit the water mark. May be even add a low water mark, such that
249  * no reclaim occurs from a cgroup at it's low water mark, this is
250  * a feature that will be implemented much later in the future.
251  */
252 struct mem_cgroup {
253 	struct cgroup_subsys_state css;
254 	/*
255 	 * the counter to account for memory usage
256 	 */
257 	struct res_counter res;
258 
259 	union {
260 		/*
261 		 * the counter to account for mem+swap usage.
262 		 */
263 		struct res_counter memsw;
264 
265 		/*
266 		 * rcu_freeing is used only when freeing struct mem_cgroup,
267 		 * so put it into a union to avoid wasting more memory.
268 		 * It must be disjoint from the css field.  It could be
269 		 * in a union with the res field, but res plays a much
270 		 * larger part in mem_cgroup life than memsw, and might
271 		 * be of interest, even at time of free, when debugging.
272 		 * So share rcu_head with the less interesting memsw.
273 		 */
274 		struct rcu_head rcu_freeing;
275 		/*
276 		 * We also need some space for a worker in deferred freeing.
277 		 * By the time we call it, rcu_freeing is no longer in use.
278 		 */
279 		struct work_struct work_freeing;
280 	};
281 
282 	/*
283 	 * the counter to account for kernel memory usage.
284 	 */
285 	struct res_counter kmem;
286 	/*
287 	 * Should the accounting and control be hierarchical, per subtree?
288 	 */
289 	bool use_hierarchy;
290 	unsigned long kmem_account_flags; /* See KMEM_ACCOUNTED_*, below */
291 
292 	bool		oom_lock;
293 	atomic_t	under_oom;
294 
295 	atomic_t	refcnt;
296 
297 	int	swappiness;
298 	/* OOM-Killer disable */
299 	int		oom_kill_disable;
300 
301 	/* set when res.limit == memsw.limit */
302 	bool		memsw_is_minimum;
303 
304 	/* protect arrays of thresholds */
305 	struct mutex thresholds_lock;
306 
307 	/* thresholds for memory usage. RCU-protected */
308 	struct mem_cgroup_thresholds thresholds;
309 
310 	/* thresholds for mem+swap usage. RCU-protected */
311 	struct mem_cgroup_thresholds memsw_thresholds;
312 
313 	/* For oom notifier event fd */
314 	struct list_head oom_notify;
315 
316 	/*
317 	 * Should we move charges of a task when a task is moved into this
318 	 * mem_cgroup ? And what type of charges should we move ?
319 	 */
320 	unsigned long 	move_charge_at_immigrate;
321 	/*
322 	 * set > 0 if pages under this cgroup are moving to other cgroup.
323 	 */
324 	atomic_t	moving_account;
325 	/* taken only while moving_account > 0 */
326 	spinlock_t	move_lock;
327 	/*
328 	 * percpu counter.
329 	 */
330 	struct mem_cgroup_stat_cpu __percpu *stat;
331 	/*
332 	 * used when a cpu is offlined or other synchronizations
333 	 * See mem_cgroup_read_stat().
334 	 */
335 	struct mem_cgroup_stat_cpu nocpu_base;
336 	spinlock_t pcp_counter_lock;
337 
338 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_INET)
339 	struct tcp_memcontrol tcp_mem;
340 #endif
341 #if defined(CONFIG_MEMCG_KMEM)
342 	/* analogous to slab_common's slab_caches list. per-memcg */
343 	struct list_head memcg_slab_caches;
344 	/* Not a spinlock, we can take a lot of time walking the list */
345 	struct mutex slab_caches_mutex;
346         /* Index in the kmem_cache->memcg_params->memcg_caches array */
347 	int kmemcg_id;
348 #endif
349 
350 	int last_scanned_node;
351 #if MAX_NUMNODES > 1
352 	nodemask_t	scan_nodes;
353 	atomic_t	numainfo_events;
354 	atomic_t	numainfo_updating;
355 #endif
356 	/*
357 	 * Per cgroup active and inactive list, similar to the
358 	 * per zone LRU lists.
359 	 *
360 	 * WARNING: This has to be the last element of the struct. Don't
361 	 * add new fields after this point.
362 	 */
363 	struct mem_cgroup_lru_info info;
364 };
365 
366 static size_t memcg_size(void)
367 {
368 	return sizeof(struct mem_cgroup) +
369 		nr_node_ids * sizeof(struct mem_cgroup_per_node);
370 }
371 
372 /* internal only representation about the status of kmem accounting. */
373 enum {
374 	KMEM_ACCOUNTED_ACTIVE = 0, /* accounted by this cgroup itself */
375 	KMEM_ACCOUNTED_ACTIVATED, /* static key enabled. */
376 	KMEM_ACCOUNTED_DEAD, /* dead memcg with pending kmem charges */
377 };
378 
379 /* We account when limit is on, but only after call sites are patched */
380 #define KMEM_ACCOUNTED_MASK \
381 		((1 << KMEM_ACCOUNTED_ACTIVE) | (1 << KMEM_ACCOUNTED_ACTIVATED))
382 
383 #ifdef CONFIG_MEMCG_KMEM
384 static inline void memcg_kmem_set_active(struct mem_cgroup *memcg)
385 {
386 	set_bit(KMEM_ACCOUNTED_ACTIVE, &memcg->kmem_account_flags);
387 }
388 
389 static bool memcg_kmem_is_active(struct mem_cgroup *memcg)
390 {
391 	return test_bit(KMEM_ACCOUNTED_ACTIVE, &memcg->kmem_account_flags);
392 }
393 
394 static void memcg_kmem_set_activated(struct mem_cgroup *memcg)
395 {
396 	set_bit(KMEM_ACCOUNTED_ACTIVATED, &memcg->kmem_account_flags);
397 }
398 
399 static void memcg_kmem_clear_activated(struct mem_cgroup *memcg)
400 {
401 	clear_bit(KMEM_ACCOUNTED_ACTIVATED, &memcg->kmem_account_flags);
402 }
403 
404 static void memcg_kmem_mark_dead(struct mem_cgroup *memcg)
405 {
406 	if (test_bit(KMEM_ACCOUNTED_ACTIVE, &memcg->kmem_account_flags))
407 		set_bit(KMEM_ACCOUNTED_DEAD, &memcg->kmem_account_flags);
408 }
409 
410 static bool memcg_kmem_test_and_clear_dead(struct mem_cgroup *memcg)
411 {
412 	return test_and_clear_bit(KMEM_ACCOUNTED_DEAD,
413 				  &memcg->kmem_account_flags);
414 }
415 #endif
416 
417 /* Stuffs for move charges at task migration. */
418 /*
419  * Types of charges to be moved. "move_charge_at_immitgrate" and
420  * "immigrate_flags" are treated as a left-shifted bitmap of these types.
421  */
422 enum move_type {
423 	MOVE_CHARGE_TYPE_ANON,	/* private anonymous page and swap of it */
424 	MOVE_CHARGE_TYPE_FILE,	/* file page(including tmpfs) and swap of it */
425 	NR_MOVE_TYPE,
426 };
427 
428 /* "mc" and its members are protected by cgroup_mutex */
429 static struct move_charge_struct {
430 	spinlock_t	  lock; /* for from, to */
431 	struct mem_cgroup *from;
432 	struct mem_cgroup *to;
433 	unsigned long immigrate_flags;
434 	unsigned long precharge;
435 	unsigned long moved_charge;
436 	unsigned long moved_swap;
437 	struct task_struct *moving_task;	/* a task moving charges */
438 	wait_queue_head_t waitq;		/* a waitq for other context */
439 } mc = {
440 	.lock = __SPIN_LOCK_UNLOCKED(mc.lock),
441 	.waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
442 };
443 
444 static bool move_anon(void)
445 {
446 	return test_bit(MOVE_CHARGE_TYPE_ANON, &mc.immigrate_flags);
447 }
448 
449 static bool move_file(void)
450 {
451 	return test_bit(MOVE_CHARGE_TYPE_FILE, &mc.immigrate_flags);
452 }
453 
454 /*
455  * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
456  * limit reclaim to prevent infinite loops, if they ever occur.
457  */
458 #define	MEM_CGROUP_MAX_RECLAIM_LOOPS		100
459 #define	MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS	2
460 
461 enum charge_type {
462 	MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
463 	MEM_CGROUP_CHARGE_TYPE_ANON,
464 	MEM_CGROUP_CHARGE_TYPE_SWAPOUT,	/* for accounting swapcache */
465 	MEM_CGROUP_CHARGE_TYPE_DROP,	/* a page was unused swap cache */
466 	NR_CHARGE_TYPE,
467 };
468 
469 /* for encoding cft->private value on file */
470 enum res_type {
471 	_MEM,
472 	_MEMSWAP,
473 	_OOM_TYPE,
474 	_KMEM,
475 };
476 
477 #define MEMFILE_PRIVATE(x, val)	((x) << 16 | (val))
478 #define MEMFILE_TYPE(val)	((val) >> 16 & 0xffff)
479 #define MEMFILE_ATTR(val)	((val) & 0xffff)
480 /* Used for OOM nofiier */
481 #define OOM_CONTROL		(0)
482 
483 /*
484  * Reclaim flags for mem_cgroup_hierarchical_reclaim
485  */
486 #define MEM_CGROUP_RECLAIM_NOSWAP_BIT	0x0
487 #define MEM_CGROUP_RECLAIM_NOSWAP	(1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
488 #define MEM_CGROUP_RECLAIM_SHRINK_BIT	0x1
489 #define MEM_CGROUP_RECLAIM_SHRINK	(1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
490 
491 /*
492  * The memcg_create_mutex will be held whenever a new cgroup is created.
493  * As a consequence, any change that needs to protect against new child cgroups
494  * appearing has to hold it as well.
495  */
496 static DEFINE_MUTEX(memcg_create_mutex);
497 
498 static void mem_cgroup_get(struct mem_cgroup *memcg);
499 static void mem_cgroup_put(struct mem_cgroup *memcg);
500 
501 static inline
502 struct mem_cgroup *mem_cgroup_from_css(struct cgroup_subsys_state *s)
503 {
504 	return container_of(s, struct mem_cgroup, css);
505 }
506 
507 static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg)
508 {
509 	return (memcg == root_mem_cgroup);
510 }
511 
512 /* Writing them here to avoid exposing memcg's inner layout */
513 #if defined(CONFIG_INET) && defined(CONFIG_MEMCG_KMEM)
514 
515 void sock_update_memcg(struct sock *sk)
516 {
517 	if (mem_cgroup_sockets_enabled) {
518 		struct mem_cgroup *memcg;
519 		struct cg_proto *cg_proto;
520 
521 		BUG_ON(!sk->sk_prot->proto_cgroup);
522 
523 		/* Socket cloning can throw us here with sk_cgrp already
524 		 * filled. It won't however, necessarily happen from
525 		 * process context. So the test for root memcg given
526 		 * the current task's memcg won't help us in this case.
527 		 *
528 		 * Respecting the original socket's memcg is a better
529 		 * decision in this case.
530 		 */
531 		if (sk->sk_cgrp) {
532 			BUG_ON(mem_cgroup_is_root(sk->sk_cgrp->memcg));
533 			mem_cgroup_get(sk->sk_cgrp->memcg);
534 			return;
535 		}
536 
537 		rcu_read_lock();
538 		memcg = mem_cgroup_from_task(current);
539 		cg_proto = sk->sk_prot->proto_cgroup(memcg);
540 		if (!mem_cgroup_is_root(memcg) && memcg_proto_active(cg_proto)) {
541 			mem_cgroup_get(memcg);
542 			sk->sk_cgrp = cg_proto;
543 		}
544 		rcu_read_unlock();
545 	}
546 }
547 EXPORT_SYMBOL(sock_update_memcg);
548 
549 void sock_release_memcg(struct sock *sk)
550 {
551 	if (mem_cgroup_sockets_enabled && sk->sk_cgrp) {
552 		struct mem_cgroup *memcg;
553 		WARN_ON(!sk->sk_cgrp->memcg);
554 		memcg = sk->sk_cgrp->memcg;
555 		mem_cgroup_put(memcg);
556 	}
557 }
558 
559 struct cg_proto *tcp_proto_cgroup(struct mem_cgroup *memcg)
560 {
561 	if (!memcg || mem_cgroup_is_root(memcg))
562 		return NULL;
563 
564 	return &memcg->tcp_mem.cg_proto;
565 }
566 EXPORT_SYMBOL(tcp_proto_cgroup);
567 
568 static void disarm_sock_keys(struct mem_cgroup *memcg)
569 {
570 	if (!memcg_proto_activated(&memcg->tcp_mem.cg_proto))
571 		return;
572 	static_key_slow_dec(&memcg_socket_limit_enabled);
573 }
574 #else
575 static void disarm_sock_keys(struct mem_cgroup *memcg)
576 {
577 }
578 #endif
579 
580 #ifdef CONFIG_MEMCG_KMEM
581 /*
582  * This will be the memcg's index in each cache's ->memcg_params->memcg_caches.
583  * There are two main reasons for not using the css_id for this:
584  *  1) this works better in sparse environments, where we have a lot of memcgs,
585  *     but only a few kmem-limited. Or also, if we have, for instance, 200
586  *     memcgs, and none but the 200th is kmem-limited, we'd have to have a
587  *     200 entry array for that.
588  *
589  *  2) In order not to violate the cgroup API, we would like to do all memory
590  *     allocation in ->create(). At that point, we haven't yet allocated the
591  *     css_id. Having a separate index prevents us from messing with the cgroup
592  *     core for this
593  *
594  * The current size of the caches array is stored in
595  * memcg_limited_groups_array_size.  It will double each time we have to
596  * increase it.
597  */
598 static DEFINE_IDA(kmem_limited_groups);
599 int memcg_limited_groups_array_size;
600 
601 /*
602  * MIN_SIZE is different than 1, because we would like to avoid going through
603  * the alloc/free process all the time. In a small machine, 4 kmem-limited
604  * cgroups is a reasonable guess. In the future, it could be a parameter or
605  * tunable, but that is strictly not necessary.
606  *
607  * MAX_SIZE should be as large as the number of css_ids. Ideally, we could get
608  * this constant directly from cgroup, but it is understandable that this is
609  * better kept as an internal representation in cgroup.c. In any case, the
610  * css_id space is not getting any smaller, and we don't have to necessarily
611  * increase ours as well if it increases.
612  */
613 #define MEMCG_CACHES_MIN_SIZE 4
614 #define MEMCG_CACHES_MAX_SIZE 65535
615 
616 /*
617  * A lot of the calls to the cache allocation functions are expected to be
618  * inlined by the compiler. Since the calls to memcg_kmem_get_cache are
619  * conditional to this static branch, we'll have to allow modules that does
620  * kmem_cache_alloc and the such to see this symbol as well
621  */
622 struct static_key memcg_kmem_enabled_key;
623 EXPORT_SYMBOL(memcg_kmem_enabled_key);
624 
625 static void disarm_kmem_keys(struct mem_cgroup *memcg)
626 {
627 	if (memcg_kmem_is_active(memcg)) {
628 		static_key_slow_dec(&memcg_kmem_enabled_key);
629 		ida_simple_remove(&kmem_limited_groups, memcg->kmemcg_id);
630 	}
631 	/*
632 	 * This check can't live in kmem destruction function,
633 	 * since the charges will outlive the cgroup
634 	 */
635 	WARN_ON(res_counter_read_u64(&memcg->kmem, RES_USAGE) != 0);
636 }
637 #else
638 static void disarm_kmem_keys(struct mem_cgroup *memcg)
639 {
640 }
641 #endif /* CONFIG_MEMCG_KMEM */
642 
643 static void disarm_static_keys(struct mem_cgroup *memcg)
644 {
645 	disarm_sock_keys(memcg);
646 	disarm_kmem_keys(memcg);
647 }
648 
649 static void drain_all_stock_async(struct mem_cgroup *memcg);
650 
651 static struct mem_cgroup_per_zone *
652 mem_cgroup_zoneinfo(struct mem_cgroup *memcg, int nid, int zid)
653 {
654 	VM_BUG_ON((unsigned)nid >= nr_node_ids);
655 	return &memcg->info.nodeinfo[nid]->zoneinfo[zid];
656 }
657 
658 struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *memcg)
659 {
660 	return &memcg->css;
661 }
662 
663 static struct mem_cgroup_per_zone *
664 page_cgroup_zoneinfo(struct mem_cgroup *memcg, struct page *page)
665 {
666 	int nid = page_to_nid(page);
667 	int zid = page_zonenum(page);
668 
669 	return mem_cgroup_zoneinfo(memcg, nid, zid);
670 }
671 
672 static struct mem_cgroup_tree_per_zone *
673 soft_limit_tree_node_zone(int nid, int zid)
674 {
675 	return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
676 }
677 
678 static struct mem_cgroup_tree_per_zone *
679 soft_limit_tree_from_page(struct page *page)
680 {
681 	int nid = page_to_nid(page);
682 	int zid = page_zonenum(page);
683 
684 	return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
685 }
686 
687 static void
688 __mem_cgroup_insert_exceeded(struct mem_cgroup *memcg,
689 				struct mem_cgroup_per_zone *mz,
690 				struct mem_cgroup_tree_per_zone *mctz,
691 				unsigned long long new_usage_in_excess)
692 {
693 	struct rb_node **p = &mctz->rb_root.rb_node;
694 	struct rb_node *parent = NULL;
695 	struct mem_cgroup_per_zone *mz_node;
696 
697 	if (mz->on_tree)
698 		return;
699 
700 	mz->usage_in_excess = new_usage_in_excess;
701 	if (!mz->usage_in_excess)
702 		return;
703 	while (*p) {
704 		parent = *p;
705 		mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
706 					tree_node);
707 		if (mz->usage_in_excess < mz_node->usage_in_excess)
708 			p = &(*p)->rb_left;
709 		/*
710 		 * We can't avoid mem cgroups that are over their soft
711 		 * limit by the same amount
712 		 */
713 		else if (mz->usage_in_excess >= mz_node->usage_in_excess)
714 			p = &(*p)->rb_right;
715 	}
716 	rb_link_node(&mz->tree_node, parent, p);
717 	rb_insert_color(&mz->tree_node, &mctz->rb_root);
718 	mz->on_tree = true;
719 }
720 
721 static void
722 __mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
723 				struct mem_cgroup_per_zone *mz,
724 				struct mem_cgroup_tree_per_zone *mctz)
725 {
726 	if (!mz->on_tree)
727 		return;
728 	rb_erase(&mz->tree_node, &mctz->rb_root);
729 	mz->on_tree = false;
730 }
731 
732 static void
733 mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
734 				struct mem_cgroup_per_zone *mz,
735 				struct mem_cgroup_tree_per_zone *mctz)
736 {
737 	spin_lock(&mctz->lock);
738 	__mem_cgroup_remove_exceeded(memcg, mz, mctz);
739 	spin_unlock(&mctz->lock);
740 }
741 
742 
743 static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
744 {
745 	unsigned long long excess;
746 	struct mem_cgroup_per_zone *mz;
747 	struct mem_cgroup_tree_per_zone *mctz;
748 	int nid = page_to_nid(page);
749 	int zid = page_zonenum(page);
750 	mctz = soft_limit_tree_from_page(page);
751 
752 	/*
753 	 * Necessary to update all ancestors when hierarchy is used.
754 	 * because their event counter is not touched.
755 	 */
756 	for (; memcg; memcg = parent_mem_cgroup(memcg)) {
757 		mz = mem_cgroup_zoneinfo(memcg, nid, zid);
758 		excess = res_counter_soft_limit_excess(&memcg->res);
759 		/*
760 		 * We have to update the tree if mz is on RB-tree or
761 		 * mem is over its softlimit.
762 		 */
763 		if (excess || mz->on_tree) {
764 			spin_lock(&mctz->lock);
765 			/* if on-tree, remove it */
766 			if (mz->on_tree)
767 				__mem_cgroup_remove_exceeded(memcg, mz, mctz);
768 			/*
769 			 * Insert again. mz->usage_in_excess will be updated.
770 			 * If excess is 0, no tree ops.
771 			 */
772 			__mem_cgroup_insert_exceeded(memcg, mz, mctz, excess);
773 			spin_unlock(&mctz->lock);
774 		}
775 	}
776 }
777 
778 static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
779 {
780 	int node, zone;
781 	struct mem_cgroup_per_zone *mz;
782 	struct mem_cgroup_tree_per_zone *mctz;
783 
784 	for_each_node(node) {
785 		for (zone = 0; zone < MAX_NR_ZONES; zone++) {
786 			mz = mem_cgroup_zoneinfo(memcg, node, zone);
787 			mctz = soft_limit_tree_node_zone(node, zone);
788 			mem_cgroup_remove_exceeded(memcg, mz, mctz);
789 		}
790 	}
791 }
792 
793 static struct mem_cgroup_per_zone *
794 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
795 {
796 	struct rb_node *rightmost = NULL;
797 	struct mem_cgroup_per_zone *mz;
798 
799 retry:
800 	mz = NULL;
801 	rightmost = rb_last(&mctz->rb_root);
802 	if (!rightmost)
803 		goto done;		/* Nothing to reclaim from */
804 
805 	mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
806 	/*
807 	 * Remove the node now but someone else can add it back,
808 	 * we will to add it back at the end of reclaim to its correct
809 	 * position in the tree.
810 	 */
811 	__mem_cgroup_remove_exceeded(mz->memcg, mz, mctz);
812 	if (!res_counter_soft_limit_excess(&mz->memcg->res) ||
813 		!css_tryget(&mz->memcg->css))
814 		goto retry;
815 done:
816 	return mz;
817 }
818 
819 static struct mem_cgroup_per_zone *
820 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
821 {
822 	struct mem_cgroup_per_zone *mz;
823 
824 	spin_lock(&mctz->lock);
825 	mz = __mem_cgroup_largest_soft_limit_node(mctz);
826 	spin_unlock(&mctz->lock);
827 	return mz;
828 }
829 
830 /*
831  * Implementation Note: reading percpu statistics for memcg.
832  *
833  * Both of vmstat[] and percpu_counter has threshold and do periodic
834  * synchronization to implement "quick" read. There are trade-off between
835  * reading cost and precision of value. Then, we may have a chance to implement
836  * a periodic synchronizion of counter in memcg's counter.
837  *
838  * But this _read() function is used for user interface now. The user accounts
839  * memory usage by memory cgroup and he _always_ requires exact value because
840  * he accounts memory. Even if we provide quick-and-fuzzy read, we always
841  * have to visit all online cpus and make sum. So, for now, unnecessary
842  * synchronization is not implemented. (just implemented for cpu hotplug)
843  *
844  * If there are kernel internal actions which can make use of some not-exact
845  * value, and reading all cpu value can be performance bottleneck in some
846  * common workload, threashold and synchonization as vmstat[] should be
847  * implemented.
848  */
849 static long mem_cgroup_read_stat(struct mem_cgroup *memcg,
850 				 enum mem_cgroup_stat_index idx)
851 {
852 	long val = 0;
853 	int cpu;
854 
855 	get_online_cpus();
856 	for_each_online_cpu(cpu)
857 		val += per_cpu(memcg->stat->count[idx], cpu);
858 #ifdef CONFIG_HOTPLUG_CPU
859 	spin_lock(&memcg->pcp_counter_lock);
860 	val += memcg->nocpu_base.count[idx];
861 	spin_unlock(&memcg->pcp_counter_lock);
862 #endif
863 	put_online_cpus();
864 	return val;
865 }
866 
867 static void mem_cgroup_swap_statistics(struct mem_cgroup *memcg,
868 					 bool charge)
869 {
870 	int val = (charge) ? 1 : -1;
871 	this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_SWAP], val);
872 }
873 
874 static unsigned long mem_cgroup_read_events(struct mem_cgroup *memcg,
875 					    enum mem_cgroup_events_index idx)
876 {
877 	unsigned long val = 0;
878 	int cpu;
879 
880 	for_each_online_cpu(cpu)
881 		val += per_cpu(memcg->stat->events[idx], cpu);
882 #ifdef CONFIG_HOTPLUG_CPU
883 	spin_lock(&memcg->pcp_counter_lock);
884 	val += memcg->nocpu_base.events[idx];
885 	spin_unlock(&memcg->pcp_counter_lock);
886 #endif
887 	return val;
888 }
889 
890 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
891 					 bool anon, int nr_pages)
892 {
893 	preempt_disable();
894 
895 	/*
896 	 * Here, RSS means 'mapped anon' and anon's SwapCache. Shmem/tmpfs is
897 	 * counted as CACHE even if it's on ANON LRU.
898 	 */
899 	if (anon)
900 		__this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS],
901 				nr_pages);
902 	else
903 		__this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_CACHE],
904 				nr_pages);
905 
906 	/* pagein of a big page is an event. So, ignore page size */
907 	if (nr_pages > 0)
908 		__this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGIN]);
909 	else {
910 		__this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGOUT]);
911 		nr_pages = -nr_pages; /* for event */
912 	}
913 
914 	__this_cpu_add(memcg->stat->nr_page_events, nr_pages);
915 
916 	preempt_enable();
917 }
918 
919 unsigned long
920 mem_cgroup_get_lru_size(struct lruvec *lruvec, enum lru_list lru)
921 {
922 	struct mem_cgroup_per_zone *mz;
923 
924 	mz = container_of(lruvec, struct mem_cgroup_per_zone, lruvec);
925 	return mz->lru_size[lru];
926 }
927 
928 static unsigned long
929 mem_cgroup_zone_nr_lru_pages(struct mem_cgroup *memcg, int nid, int zid,
930 			unsigned int lru_mask)
931 {
932 	struct mem_cgroup_per_zone *mz;
933 	enum lru_list lru;
934 	unsigned long ret = 0;
935 
936 	mz = mem_cgroup_zoneinfo(memcg, nid, zid);
937 
938 	for_each_lru(lru) {
939 		if (BIT(lru) & lru_mask)
940 			ret += mz->lru_size[lru];
941 	}
942 	return ret;
943 }
944 
945 static unsigned long
946 mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
947 			int nid, unsigned int lru_mask)
948 {
949 	u64 total = 0;
950 	int zid;
951 
952 	for (zid = 0; zid < MAX_NR_ZONES; zid++)
953 		total += mem_cgroup_zone_nr_lru_pages(memcg,
954 						nid, zid, lru_mask);
955 
956 	return total;
957 }
958 
959 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
960 			unsigned int lru_mask)
961 {
962 	int nid;
963 	u64 total = 0;
964 
965 	for_each_node_state(nid, N_MEMORY)
966 		total += mem_cgroup_node_nr_lru_pages(memcg, nid, lru_mask);
967 	return total;
968 }
969 
970 static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
971 				       enum mem_cgroup_events_target target)
972 {
973 	unsigned long val, next;
974 
975 	val = __this_cpu_read(memcg->stat->nr_page_events);
976 	next = __this_cpu_read(memcg->stat->targets[target]);
977 	/* from time_after() in jiffies.h */
978 	if ((long)next - (long)val < 0) {
979 		switch (target) {
980 		case MEM_CGROUP_TARGET_THRESH:
981 			next = val + THRESHOLDS_EVENTS_TARGET;
982 			break;
983 		case MEM_CGROUP_TARGET_SOFTLIMIT:
984 			next = val + SOFTLIMIT_EVENTS_TARGET;
985 			break;
986 		case MEM_CGROUP_TARGET_NUMAINFO:
987 			next = val + NUMAINFO_EVENTS_TARGET;
988 			break;
989 		default:
990 			break;
991 		}
992 		__this_cpu_write(memcg->stat->targets[target], next);
993 		return true;
994 	}
995 	return false;
996 }
997 
998 /*
999  * Check events in order.
1000  *
1001  */
1002 static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
1003 {
1004 	preempt_disable();
1005 	/* threshold event is triggered in finer grain than soft limit */
1006 	if (unlikely(mem_cgroup_event_ratelimit(memcg,
1007 						MEM_CGROUP_TARGET_THRESH))) {
1008 		bool do_softlimit;
1009 		bool do_numainfo __maybe_unused;
1010 
1011 		do_softlimit = mem_cgroup_event_ratelimit(memcg,
1012 						MEM_CGROUP_TARGET_SOFTLIMIT);
1013 #if MAX_NUMNODES > 1
1014 		do_numainfo = mem_cgroup_event_ratelimit(memcg,
1015 						MEM_CGROUP_TARGET_NUMAINFO);
1016 #endif
1017 		preempt_enable();
1018 
1019 		mem_cgroup_threshold(memcg);
1020 		if (unlikely(do_softlimit))
1021 			mem_cgroup_update_tree(memcg, page);
1022 #if MAX_NUMNODES > 1
1023 		if (unlikely(do_numainfo))
1024 			atomic_inc(&memcg->numainfo_events);
1025 #endif
1026 	} else
1027 		preempt_enable();
1028 }
1029 
1030 struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
1031 {
1032 	return mem_cgroup_from_css(
1033 		cgroup_subsys_state(cont, mem_cgroup_subsys_id));
1034 }
1035 
1036 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
1037 {
1038 	/*
1039 	 * mm_update_next_owner() may clear mm->owner to NULL
1040 	 * if it races with swapoff, page migration, etc.
1041 	 * So this can be called with p == NULL.
1042 	 */
1043 	if (unlikely(!p))
1044 		return NULL;
1045 
1046 	return mem_cgroup_from_css(task_subsys_state(p, mem_cgroup_subsys_id));
1047 }
1048 
1049 struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
1050 {
1051 	struct mem_cgroup *memcg = NULL;
1052 
1053 	if (!mm)
1054 		return NULL;
1055 	/*
1056 	 * Because we have no locks, mm->owner's may be being moved to other
1057 	 * cgroup. We use css_tryget() here even if this looks
1058 	 * pessimistic (rather than adding locks here).
1059 	 */
1060 	rcu_read_lock();
1061 	do {
1062 		memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
1063 		if (unlikely(!memcg))
1064 			break;
1065 	} while (!css_tryget(&memcg->css));
1066 	rcu_read_unlock();
1067 	return memcg;
1068 }
1069 
1070 /**
1071  * mem_cgroup_iter - iterate over memory cgroup hierarchy
1072  * @root: hierarchy root
1073  * @prev: previously returned memcg, NULL on first invocation
1074  * @reclaim: cookie for shared reclaim walks, NULL for full walks
1075  *
1076  * Returns references to children of the hierarchy below @root, or
1077  * @root itself, or %NULL after a full round-trip.
1078  *
1079  * Caller must pass the return value in @prev on subsequent
1080  * invocations for reference counting, or use mem_cgroup_iter_break()
1081  * to cancel a hierarchy walk before the round-trip is complete.
1082  *
1083  * Reclaimers can specify a zone and a priority level in @reclaim to
1084  * divide up the memcgs in the hierarchy among all concurrent
1085  * reclaimers operating on the same zone and priority.
1086  */
1087 struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
1088 				   struct mem_cgroup *prev,
1089 				   struct mem_cgroup_reclaim_cookie *reclaim)
1090 {
1091 	struct mem_cgroup *memcg = NULL;
1092 	int id = 0;
1093 
1094 	if (mem_cgroup_disabled())
1095 		return NULL;
1096 
1097 	if (!root)
1098 		root = root_mem_cgroup;
1099 
1100 	if (prev && !reclaim)
1101 		id = css_id(&prev->css);
1102 
1103 	if (prev && prev != root)
1104 		css_put(&prev->css);
1105 
1106 	if (!root->use_hierarchy && root != root_mem_cgroup) {
1107 		if (prev)
1108 			return NULL;
1109 		return root;
1110 	}
1111 
1112 	while (!memcg) {
1113 		struct mem_cgroup_reclaim_iter *uninitialized_var(iter);
1114 		struct cgroup_subsys_state *css;
1115 
1116 		if (reclaim) {
1117 			int nid = zone_to_nid(reclaim->zone);
1118 			int zid = zone_idx(reclaim->zone);
1119 			struct mem_cgroup_per_zone *mz;
1120 
1121 			mz = mem_cgroup_zoneinfo(root, nid, zid);
1122 			iter = &mz->reclaim_iter[reclaim->priority];
1123 			if (prev && reclaim->generation != iter->generation)
1124 				return NULL;
1125 			id = iter->position;
1126 		}
1127 
1128 		rcu_read_lock();
1129 		css = css_get_next(&mem_cgroup_subsys, id + 1, &root->css, &id);
1130 		if (css) {
1131 			if (css == &root->css || css_tryget(css))
1132 				memcg = mem_cgroup_from_css(css);
1133 		} else
1134 			id = 0;
1135 		rcu_read_unlock();
1136 
1137 		if (reclaim) {
1138 			iter->position = id;
1139 			if (!css)
1140 				iter->generation++;
1141 			else if (!prev && memcg)
1142 				reclaim->generation = iter->generation;
1143 		}
1144 
1145 		if (prev && !css)
1146 			return NULL;
1147 	}
1148 	return memcg;
1149 }
1150 
1151 /**
1152  * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1153  * @root: hierarchy root
1154  * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1155  */
1156 void mem_cgroup_iter_break(struct mem_cgroup *root,
1157 			   struct mem_cgroup *prev)
1158 {
1159 	if (!root)
1160 		root = root_mem_cgroup;
1161 	if (prev && prev != root)
1162 		css_put(&prev->css);
1163 }
1164 
1165 /*
1166  * Iteration constructs for visiting all cgroups (under a tree).  If
1167  * loops are exited prematurely (break), mem_cgroup_iter_break() must
1168  * be used for reference counting.
1169  */
1170 #define for_each_mem_cgroup_tree(iter, root)		\
1171 	for (iter = mem_cgroup_iter(root, NULL, NULL);	\
1172 	     iter != NULL;				\
1173 	     iter = mem_cgroup_iter(root, iter, NULL))
1174 
1175 #define for_each_mem_cgroup(iter)			\
1176 	for (iter = mem_cgroup_iter(NULL, NULL, NULL);	\
1177 	     iter != NULL;				\
1178 	     iter = mem_cgroup_iter(NULL, iter, NULL))
1179 
1180 void __mem_cgroup_count_vm_event(struct mm_struct *mm, enum vm_event_item idx)
1181 {
1182 	struct mem_cgroup *memcg;
1183 
1184 	rcu_read_lock();
1185 	memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
1186 	if (unlikely(!memcg))
1187 		goto out;
1188 
1189 	switch (idx) {
1190 	case PGFAULT:
1191 		this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGFAULT]);
1192 		break;
1193 	case PGMAJFAULT:
1194 		this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGMAJFAULT]);
1195 		break;
1196 	default:
1197 		BUG();
1198 	}
1199 out:
1200 	rcu_read_unlock();
1201 }
1202 EXPORT_SYMBOL(__mem_cgroup_count_vm_event);
1203 
1204 /**
1205  * mem_cgroup_zone_lruvec - get the lru list vector for a zone and memcg
1206  * @zone: zone of the wanted lruvec
1207  * @memcg: memcg of the wanted lruvec
1208  *
1209  * Returns the lru list vector holding pages for the given @zone and
1210  * @mem.  This can be the global zone lruvec, if the memory controller
1211  * is disabled.
1212  */
1213 struct lruvec *mem_cgroup_zone_lruvec(struct zone *zone,
1214 				      struct mem_cgroup *memcg)
1215 {
1216 	struct mem_cgroup_per_zone *mz;
1217 	struct lruvec *lruvec;
1218 
1219 	if (mem_cgroup_disabled()) {
1220 		lruvec = &zone->lruvec;
1221 		goto out;
1222 	}
1223 
1224 	mz = mem_cgroup_zoneinfo(memcg, zone_to_nid(zone), zone_idx(zone));
1225 	lruvec = &mz->lruvec;
1226 out:
1227 	/*
1228 	 * Since a node can be onlined after the mem_cgroup was created,
1229 	 * we have to be prepared to initialize lruvec->zone here;
1230 	 * and if offlined then reonlined, we need to reinitialize it.
1231 	 */
1232 	if (unlikely(lruvec->zone != zone))
1233 		lruvec->zone = zone;
1234 	return lruvec;
1235 }
1236 
1237 /*
1238  * Following LRU functions are allowed to be used without PCG_LOCK.
1239  * Operations are called by routine of global LRU independently from memcg.
1240  * What we have to take care of here is validness of pc->mem_cgroup.
1241  *
1242  * Changes to pc->mem_cgroup happens when
1243  * 1. charge
1244  * 2. moving account
1245  * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
1246  * It is added to LRU before charge.
1247  * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
1248  * When moving account, the page is not on LRU. It's isolated.
1249  */
1250 
1251 /**
1252  * mem_cgroup_page_lruvec - return lruvec for adding an lru page
1253  * @page: the page
1254  * @zone: zone of the page
1255  */
1256 struct lruvec *mem_cgroup_page_lruvec(struct page *page, struct zone *zone)
1257 {
1258 	struct mem_cgroup_per_zone *mz;
1259 	struct mem_cgroup *memcg;
1260 	struct page_cgroup *pc;
1261 	struct lruvec *lruvec;
1262 
1263 	if (mem_cgroup_disabled()) {
1264 		lruvec = &zone->lruvec;
1265 		goto out;
1266 	}
1267 
1268 	pc = lookup_page_cgroup(page);
1269 	memcg = pc->mem_cgroup;
1270 
1271 	/*
1272 	 * Surreptitiously switch any uncharged offlist page to root:
1273 	 * an uncharged page off lru does nothing to secure
1274 	 * its former mem_cgroup from sudden removal.
1275 	 *
1276 	 * Our caller holds lru_lock, and PageCgroupUsed is updated
1277 	 * under page_cgroup lock: between them, they make all uses
1278 	 * of pc->mem_cgroup safe.
1279 	 */
1280 	if (!PageLRU(page) && !PageCgroupUsed(pc) && memcg != root_mem_cgroup)
1281 		pc->mem_cgroup = memcg = root_mem_cgroup;
1282 
1283 	mz = page_cgroup_zoneinfo(memcg, page);
1284 	lruvec = &mz->lruvec;
1285 out:
1286 	/*
1287 	 * Since a node can be onlined after the mem_cgroup was created,
1288 	 * we have to be prepared to initialize lruvec->zone here;
1289 	 * and if offlined then reonlined, we need to reinitialize it.
1290 	 */
1291 	if (unlikely(lruvec->zone != zone))
1292 		lruvec->zone = zone;
1293 	return lruvec;
1294 }
1295 
1296 /**
1297  * mem_cgroup_update_lru_size - account for adding or removing an lru page
1298  * @lruvec: mem_cgroup per zone lru vector
1299  * @lru: index of lru list the page is sitting on
1300  * @nr_pages: positive when adding or negative when removing
1301  *
1302  * This function must be called when a page is added to or removed from an
1303  * lru list.
1304  */
1305 void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
1306 				int nr_pages)
1307 {
1308 	struct mem_cgroup_per_zone *mz;
1309 	unsigned long *lru_size;
1310 
1311 	if (mem_cgroup_disabled())
1312 		return;
1313 
1314 	mz = container_of(lruvec, struct mem_cgroup_per_zone, lruvec);
1315 	lru_size = mz->lru_size + lru;
1316 	*lru_size += nr_pages;
1317 	VM_BUG_ON((long)(*lru_size) < 0);
1318 }
1319 
1320 /*
1321  * Checks whether given mem is same or in the root_mem_cgroup's
1322  * hierarchy subtree
1323  */
1324 bool __mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
1325 				  struct mem_cgroup *memcg)
1326 {
1327 	if (root_memcg == memcg)
1328 		return true;
1329 	if (!root_memcg->use_hierarchy || !memcg)
1330 		return false;
1331 	return css_is_ancestor(&memcg->css, &root_memcg->css);
1332 }
1333 
1334 static bool mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
1335 				       struct mem_cgroup *memcg)
1336 {
1337 	bool ret;
1338 
1339 	rcu_read_lock();
1340 	ret = __mem_cgroup_same_or_subtree(root_memcg, memcg);
1341 	rcu_read_unlock();
1342 	return ret;
1343 }
1344 
1345 int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *memcg)
1346 {
1347 	int ret;
1348 	struct mem_cgroup *curr = NULL;
1349 	struct task_struct *p;
1350 
1351 	p = find_lock_task_mm(task);
1352 	if (p) {
1353 		curr = try_get_mem_cgroup_from_mm(p->mm);
1354 		task_unlock(p);
1355 	} else {
1356 		/*
1357 		 * All threads may have already detached their mm's, but the oom
1358 		 * killer still needs to detect if they have already been oom
1359 		 * killed to prevent needlessly killing additional tasks.
1360 		 */
1361 		task_lock(task);
1362 		curr = mem_cgroup_from_task(task);
1363 		if (curr)
1364 			css_get(&curr->css);
1365 		task_unlock(task);
1366 	}
1367 	if (!curr)
1368 		return 0;
1369 	/*
1370 	 * We should check use_hierarchy of "memcg" not "curr". Because checking
1371 	 * use_hierarchy of "curr" here make this function true if hierarchy is
1372 	 * enabled in "curr" and "curr" is a child of "memcg" in *cgroup*
1373 	 * hierarchy(even if use_hierarchy is disabled in "memcg").
1374 	 */
1375 	ret = mem_cgroup_same_or_subtree(memcg, curr);
1376 	css_put(&curr->css);
1377 	return ret;
1378 }
1379 
1380 int mem_cgroup_inactive_anon_is_low(struct lruvec *lruvec)
1381 {
1382 	unsigned long inactive_ratio;
1383 	unsigned long inactive;
1384 	unsigned long active;
1385 	unsigned long gb;
1386 
1387 	inactive = mem_cgroup_get_lru_size(lruvec, LRU_INACTIVE_ANON);
1388 	active = mem_cgroup_get_lru_size(lruvec, LRU_ACTIVE_ANON);
1389 
1390 	gb = (inactive + active) >> (30 - PAGE_SHIFT);
1391 	if (gb)
1392 		inactive_ratio = int_sqrt(10 * gb);
1393 	else
1394 		inactive_ratio = 1;
1395 
1396 	return inactive * inactive_ratio < active;
1397 }
1398 
1399 #define mem_cgroup_from_res_counter(counter, member)	\
1400 	container_of(counter, struct mem_cgroup, member)
1401 
1402 /**
1403  * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1404  * @memcg: the memory cgroup
1405  *
1406  * Returns the maximum amount of memory @mem can be charged with, in
1407  * pages.
1408  */
1409 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1410 {
1411 	unsigned long long margin;
1412 
1413 	margin = res_counter_margin(&memcg->res);
1414 	if (do_swap_account)
1415 		margin = min(margin, res_counter_margin(&memcg->memsw));
1416 	return margin >> PAGE_SHIFT;
1417 }
1418 
1419 int mem_cgroup_swappiness(struct mem_cgroup *memcg)
1420 {
1421 	struct cgroup *cgrp = memcg->css.cgroup;
1422 
1423 	/* root ? */
1424 	if (cgrp->parent == NULL)
1425 		return vm_swappiness;
1426 
1427 	return memcg->swappiness;
1428 }
1429 
1430 /*
1431  * memcg->moving_account is used for checking possibility that some thread is
1432  * calling move_account(). When a thread on CPU-A starts moving pages under
1433  * a memcg, other threads should check memcg->moving_account under
1434  * rcu_read_lock(), like this:
1435  *
1436  *         CPU-A                                    CPU-B
1437  *                                              rcu_read_lock()
1438  *         memcg->moving_account+1              if (memcg->mocing_account)
1439  *                                                   take heavy locks.
1440  *         synchronize_rcu()                    update something.
1441  *                                              rcu_read_unlock()
1442  *         start move here.
1443  */
1444 
1445 /* for quick checking without looking up memcg */
1446 atomic_t memcg_moving __read_mostly;
1447 
1448 static void mem_cgroup_start_move(struct mem_cgroup *memcg)
1449 {
1450 	atomic_inc(&memcg_moving);
1451 	atomic_inc(&memcg->moving_account);
1452 	synchronize_rcu();
1453 }
1454 
1455 static void mem_cgroup_end_move(struct mem_cgroup *memcg)
1456 {
1457 	/*
1458 	 * Now, mem_cgroup_clear_mc() may call this function with NULL.
1459 	 * We check NULL in callee rather than caller.
1460 	 */
1461 	if (memcg) {
1462 		atomic_dec(&memcg_moving);
1463 		atomic_dec(&memcg->moving_account);
1464 	}
1465 }
1466 
1467 /*
1468  * 2 routines for checking "mem" is under move_account() or not.
1469  *
1470  * mem_cgroup_stolen() -  checking whether a cgroup is mc.from or not. This
1471  *			  is used for avoiding races in accounting.  If true,
1472  *			  pc->mem_cgroup may be overwritten.
1473  *
1474  * mem_cgroup_under_move() - checking a cgroup is mc.from or mc.to or
1475  *			  under hierarchy of moving cgroups. This is for
1476  *			  waiting at hith-memory prressure caused by "move".
1477  */
1478 
1479 static bool mem_cgroup_stolen(struct mem_cgroup *memcg)
1480 {
1481 	VM_BUG_ON(!rcu_read_lock_held());
1482 	return atomic_read(&memcg->moving_account) > 0;
1483 }
1484 
1485 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1486 {
1487 	struct mem_cgroup *from;
1488 	struct mem_cgroup *to;
1489 	bool ret = false;
1490 	/*
1491 	 * Unlike task_move routines, we access mc.to, mc.from not under
1492 	 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1493 	 */
1494 	spin_lock(&mc.lock);
1495 	from = mc.from;
1496 	to = mc.to;
1497 	if (!from)
1498 		goto unlock;
1499 
1500 	ret = mem_cgroup_same_or_subtree(memcg, from)
1501 		|| mem_cgroup_same_or_subtree(memcg, to);
1502 unlock:
1503 	spin_unlock(&mc.lock);
1504 	return ret;
1505 }
1506 
1507 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1508 {
1509 	if (mc.moving_task && current != mc.moving_task) {
1510 		if (mem_cgroup_under_move(memcg)) {
1511 			DEFINE_WAIT(wait);
1512 			prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1513 			/* moving charge context might have finished. */
1514 			if (mc.moving_task)
1515 				schedule();
1516 			finish_wait(&mc.waitq, &wait);
1517 			return true;
1518 		}
1519 	}
1520 	return false;
1521 }
1522 
1523 /*
1524  * Take this lock when
1525  * - a code tries to modify page's memcg while it's USED.
1526  * - a code tries to modify page state accounting in a memcg.
1527  * see mem_cgroup_stolen(), too.
1528  */
1529 static void move_lock_mem_cgroup(struct mem_cgroup *memcg,
1530 				  unsigned long *flags)
1531 {
1532 	spin_lock_irqsave(&memcg->move_lock, *flags);
1533 }
1534 
1535 static void move_unlock_mem_cgroup(struct mem_cgroup *memcg,
1536 				unsigned long *flags)
1537 {
1538 	spin_unlock_irqrestore(&memcg->move_lock, *flags);
1539 }
1540 
1541 #define K(x) ((x) << (PAGE_SHIFT-10))
1542 /**
1543  * mem_cgroup_print_oom_info: Print OOM information relevant to memory controller.
1544  * @memcg: The memory cgroup that went over limit
1545  * @p: Task that is going to be killed
1546  *
1547  * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1548  * enabled
1549  */
1550 void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1551 {
1552 	struct cgroup *task_cgrp;
1553 	struct cgroup *mem_cgrp;
1554 	/*
1555 	 * Need a buffer in BSS, can't rely on allocations. The code relies
1556 	 * on the assumption that OOM is serialized for memory controller.
1557 	 * If this assumption is broken, revisit this code.
1558 	 */
1559 	static char memcg_name[PATH_MAX];
1560 	int ret;
1561 	struct mem_cgroup *iter;
1562 	unsigned int i;
1563 
1564 	if (!p)
1565 		return;
1566 
1567 	rcu_read_lock();
1568 
1569 	mem_cgrp = memcg->css.cgroup;
1570 	task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
1571 
1572 	ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
1573 	if (ret < 0) {
1574 		/*
1575 		 * Unfortunately, we are unable to convert to a useful name
1576 		 * But we'll still print out the usage information
1577 		 */
1578 		rcu_read_unlock();
1579 		goto done;
1580 	}
1581 	rcu_read_unlock();
1582 
1583 	pr_info("Task in %s killed", memcg_name);
1584 
1585 	rcu_read_lock();
1586 	ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
1587 	if (ret < 0) {
1588 		rcu_read_unlock();
1589 		goto done;
1590 	}
1591 	rcu_read_unlock();
1592 
1593 	/*
1594 	 * Continues from above, so we don't need an KERN_ level
1595 	 */
1596 	pr_cont(" as a result of limit of %s\n", memcg_name);
1597 done:
1598 
1599 	pr_info("memory: usage %llukB, limit %llukB, failcnt %llu\n",
1600 		res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
1601 		res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
1602 		res_counter_read_u64(&memcg->res, RES_FAILCNT));
1603 	pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %llu\n",
1604 		res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
1605 		res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
1606 		res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
1607 	pr_info("kmem: usage %llukB, limit %llukB, failcnt %llu\n",
1608 		res_counter_read_u64(&memcg->kmem, RES_USAGE) >> 10,
1609 		res_counter_read_u64(&memcg->kmem, RES_LIMIT) >> 10,
1610 		res_counter_read_u64(&memcg->kmem, RES_FAILCNT));
1611 
1612 	for_each_mem_cgroup_tree(iter, memcg) {
1613 		pr_info("Memory cgroup stats");
1614 
1615 		rcu_read_lock();
1616 		ret = cgroup_path(iter->css.cgroup, memcg_name, PATH_MAX);
1617 		if (!ret)
1618 			pr_cont(" for %s", memcg_name);
1619 		rcu_read_unlock();
1620 		pr_cont(":");
1621 
1622 		for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
1623 			if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
1624 				continue;
1625 			pr_cont(" %s:%ldKB", mem_cgroup_stat_names[i],
1626 				K(mem_cgroup_read_stat(iter, i)));
1627 		}
1628 
1629 		for (i = 0; i < NR_LRU_LISTS; i++)
1630 			pr_cont(" %s:%luKB", mem_cgroup_lru_names[i],
1631 				K(mem_cgroup_nr_lru_pages(iter, BIT(i))));
1632 
1633 		pr_cont("\n");
1634 	}
1635 }
1636 
1637 /*
1638  * This function returns the number of memcg under hierarchy tree. Returns
1639  * 1(self count) if no children.
1640  */
1641 static int mem_cgroup_count_children(struct mem_cgroup *memcg)
1642 {
1643 	int num = 0;
1644 	struct mem_cgroup *iter;
1645 
1646 	for_each_mem_cgroup_tree(iter, memcg)
1647 		num++;
1648 	return num;
1649 }
1650 
1651 /*
1652  * Return the memory (and swap, if configured) limit for a memcg.
1653  */
1654 static u64 mem_cgroup_get_limit(struct mem_cgroup *memcg)
1655 {
1656 	u64 limit;
1657 
1658 	limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
1659 
1660 	/*
1661 	 * Do not consider swap space if we cannot swap due to swappiness
1662 	 */
1663 	if (mem_cgroup_swappiness(memcg)) {
1664 		u64 memsw;
1665 
1666 		limit += total_swap_pages << PAGE_SHIFT;
1667 		memsw = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
1668 
1669 		/*
1670 		 * If memsw is finite and limits the amount of swap space
1671 		 * available to this memcg, return that limit.
1672 		 */
1673 		limit = min(limit, memsw);
1674 	}
1675 
1676 	return limit;
1677 }
1678 
1679 static void mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
1680 				     int order)
1681 {
1682 	struct mem_cgroup *iter;
1683 	unsigned long chosen_points = 0;
1684 	unsigned long totalpages;
1685 	unsigned int points = 0;
1686 	struct task_struct *chosen = NULL;
1687 
1688 	/*
1689 	 * If current has a pending SIGKILL, then automatically select it.  The
1690 	 * goal is to allow it to allocate so that it may quickly exit and free
1691 	 * its memory.
1692 	 */
1693 	if (fatal_signal_pending(current)) {
1694 		set_thread_flag(TIF_MEMDIE);
1695 		return;
1696 	}
1697 
1698 	check_panic_on_oom(CONSTRAINT_MEMCG, gfp_mask, order, NULL);
1699 	totalpages = mem_cgroup_get_limit(memcg) >> PAGE_SHIFT ? : 1;
1700 	for_each_mem_cgroup_tree(iter, memcg) {
1701 		struct cgroup *cgroup = iter->css.cgroup;
1702 		struct cgroup_iter it;
1703 		struct task_struct *task;
1704 
1705 		cgroup_iter_start(cgroup, &it);
1706 		while ((task = cgroup_iter_next(cgroup, &it))) {
1707 			switch (oom_scan_process_thread(task, totalpages, NULL,
1708 							false)) {
1709 			case OOM_SCAN_SELECT:
1710 				if (chosen)
1711 					put_task_struct(chosen);
1712 				chosen = task;
1713 				chosen_points = ULONG_MAX;
1714 				get_task_struct(chosen);
1715 				/* fall through */
1716 			case OOM_SCAN_CONTINUE:
1717 				continue;
1718 			case OOM_SCAN_ABORT:
1719 				cgroup_iter_end(cgroup, &it);
1720 				mem_cgroup_iter_break(memcg, iter);
1721 				if (chosen)
1722 					put_task_struct(chosen);
1723 				return;
1724 			case OOM_SCAN_OK:
1725 				break;
1726 			};
1727 			points = oom_badness(task, memcg, NULL, totalpages);
1728 			if (points > chosen_points) {
1729 				if (chosen)
1730 					put_task_struct(chosen);
1731 				chosen = task;
1732 				chosen_points = points;
1733 				get_task_struct(chosen);
1734 			}
1735 		}
1736 		cgroup_iter_end(cgroup, &it);
1737 	}
1738 
1739 	if (!chosen)
1740 		return;
1741 	points = chosen_points * 1000 / totalpages;
1742 	oom_kill_process(chosen, gfp_mask, order, points, totalpages, memcg,
1743 			 NULL, "Memory cgroup out of memory");
1744 }
1745 
1746 static unsigned long mem_cgroup_reclaim(struct mem_cgroup *memcg,
1747 					gfp_t gfp_mask,
1748 					unsigned long flags)
1749 {
1750 	unsigned long total = 0;
1751 	bool noswap = false;
1752 	int loop;
1753 
1754 	if (flags & MEM_CGROUP_RECLAIM_NOSWAP)
1755 		noswap = true;
1756 	if (!(flags & MEM_CGROUP_RECLAIM_SHRINK) && memcg->memsw_is_minimum)
1757 		noswap = true;
1758 
1759 	for (loop = 0; loop < MEM_CGROUP_MAX_RECLAIM_LOOPS; loop++) {
1760 		if (loop)
1761 			drain_all_stock_async(memcg);
1762 		total += try_to_free_mem_cgroup_pages(memcg, gfp_mask, noswap);
1763 		/*
1764 		 * Allow limit shrinkers, which are triggered directly
1765 		 * by userspace, to catch signals and stop reclaim
1766 		 * after minimal progress, regardless of the margin.
1767 		 */
1768 		if (total && (flags & MEM_CGROUP_RECLAIM_SHRINK))
1769 			break;
1770 		if (mem_cgroup_margin(memcg))
1771 			break;
1772 		/*
1773 		 * If nothing was reclaimed after two attempts, there
1774 		 * may be no reclaimable pages in this hierarchy.
1775 		 */
1776 		if (loop && !total)
1777 			break;
1778 	}
1779 	return total;
1780 }
1781 
1782 /**
1783  * test_mem_cgroup_node_reclaimable
1784  * @memcg: the target memcg
1785  * @nid: the node ID to be checked.
1786  * @noswap : specify true here if the user wants flle only information.
1787  *
1788  * This function returns whether the specified memcg contains any
1789  * reclaimable pages on a node. Returns true if there are any reclaimable
1790  * pages in the node.
1791  */
1792 static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *memcg,
1793 		int nid, bool noswap)
1794 {
1795 	if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_FILE))
1796 		return true;
1797 	if (noswap || !total_swap_pages)
1798 		return false;
1799 	if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_ANON))
1800 		return true;
1801 	return false;
1802 
1803 }
1804 #if MAX_NUMNODES > 1
1805 
1806 /*
1807  * Always updating the nodemask is not very good - even if we have an empty
1808  * list or the wrong list here, we can start from some node and traverse all
1809  * nodes based on the zonelist. So update the list loosely once per 10 secs.
1810  *
1811  */
1812 static void mem_cgroup_may_update_nodemask(struct mem_cgroup *memcg)
1813 {
1814 	int nid;
1815 	/*
1816 	 * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
1817 	 * pagein/pageout changes since the last update.
1818 	 */
1819 	if (!atomic_read(&memcg->numainfo_events))
1820 		return;
1821 	if (atomic_inc_return(&memcg->numainfo_updating) > 1)
1822 		return;
1823 
1824 	/* make a nodemask where this memcg uses memory from */
1825 	memcg->scan_nodes = node_states[N_MEMORY];
1826 
1827 	for_each_node_mask(nid, node_states[N_MEMORY]) {
1828 
1829 		if (!test_mem_cgroup_node_reclaimable(memcg, nid, false))
1830 			node_clear(nid, memcg->scan_nodes);
1831 	}
1832 
1833 	atomic_set(&memcg->numainfo_events, 0);
1834 	atomic_set(&memcg->numainfo_updating, 0);
1835 }
1836 
1837 /*
1838  * Selecting a node where we start reclaim from. Because what we need is just
1839  * reducing usage counter, start from anywhere is O,K. Considering
1840  * memory reclaim from current node, there are pros. and cons.
1841  *
1842  * Freeing memory from current node means freeing memory from a node which
1843  * we'll use or we've used. So, it may make LRU bad. And if several threads
1844  * hit limits, it will see a contention on a node. But freeing from remote
1845  * node means more costs for memory reclaim because of memory latency.
1846  *
1847  * Now, we use round-robin. Better algorithm is welcomed.
1848  */
1849 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1850 {
1851 	int node;
1852 
1853 	mem_cgroup_may_update_nodemask(memcg);
1854 	node = memcg->last_scanned_node;
1855 
1856 	node = next_node(node, memcg->scan_nodes);
1857 	if (node == MAX_NUMNODES)
1858 		node = first_node(memcg->scan_nodes);
1859 	/*
1860 	 * We call this when we hit limit, not when pages are added to LRU.
1861 	 * No LRU may hold pages because all pages are UNEVICTABLE or
1862 	 * memcg is too small and all pages are not on LRU. In that case,
1863 	 * we use curret node.
1864 	 */
1865 	if (unlikely(node == MAX_NUMNODES))
1866 		node = numa_node_id();
1867 
1868 	memcg->last_scanned_node = node;
1869 	return node;
1870 }
1871 
1872 /*
1873  * Check all nodes whether it contains reclaimable pages or not.
1874  * For quick scan, we make use of scan_nodes. This will allow us to skip
1875  * unused nodes. But scan_nodes is lazily updated and may not cotain
1876  * enough new information. We need to do double check.
1877  */
1878 static bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
1879 {
1880 	int nid;
1881 
1882 	/*
1883 	 * quick check...making use of scan_node.
1884 	 * We can skip unused nodes.
1885 	 */
1886 	if (!nodes_empty(memcg->scan_nodes)) {
1887 		for (nid = first_node(memcg->scan_nodes);
1888 		     nid < MAX_NUMNODES;
1889 		     nid = next_node(nid, memcg->scan_nodes)) {
1890 
1891 			if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
1892 				return true;
1893 		}
1894 	}
1895 	/*
1896 	 * Check rest of nodes.
1897 	 */
1898 	for_each_node_state(nid, N_MEMORY) {
1899 		if (node_isset(nid, memcg->scan_nodes))
1900 			continue;
1901 		if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
1902 			return true;
1903 	}
1904 	return false;
1905 }
1906 
1907 #else
1908 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1909 {
1910 	return 0;
1911 }
1912 
1913 static bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
1914 {
1915 	return test_mem_cgroup_node_reclaimable(memcg, 0, noswap);
1916 }
1917 #endif
1918 
1919 static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
1920 				   struct zone *zone,
1921 				   gfp_t gfp_mask,
1922 				   unsigned long *total_scanned)
1923 {
1924 	struct mem_cgroup *victim = NULL;
1925 	int total = 0;
1926 	int loop = 0;
1927 	unsigned long excess;
1928 	unsigned long nr_scanned;
1929 	struct mem_cgroup_reclaim_cookie reclaim = {
1930 		.zone = zone,
1931 		.priority = 0,
1932 	};
1933 
1934 	excess = res_counter_soft_limit_excess(&root_memcg->res) >> PAGE_SHIFT;
1935 
1936 	while (1) {
1937 		victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
1938 		if (!victim) {
1939 			loop++;
1940 			if (loop >= 2) {
1941 				/*
1942 				 * If we have not been able to reclaim
1943 				 * anything, it might because there are
1944 				 * no reclaimable pages under this hierarchy
1945 				 */
1946 				if (!total)
1947 					break;
1948 				/*
1949 				 * We want to do more targeted reclaim.
1950 				 * excess >> 2 is not to excessive so as to
1951 				 * reclaim too much, nor too less that we keep
1952 				 * coming back to reclaim from this cgroup
1953 				 */
1954 				if (total >= (excess >> 2) ||
1955 					(loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
1956 					break;
1957 			}
1958 			continue;
1959 		}
1960 		if (!mem_cgroup_reclaimable(victim, false))
1961 			continue;
1962 		total += mem_cgroup_shrink_node_zone(victim, gfp_mask, false,
1963 						     zone, &nr_scanned);
1964 		*total_scanned += nr_scanned;
1965 		if (!res_counter_soft_limit_excess(&root_memcg->res))
1966 			break;
1967 	}
1968 	mem_cgroup_iter_break(root_memcg, victim);
1969 	return total;
1970 }
1971 
1972 /*
1973  * Check OOM-Killer is already running under our hierarchy.
1974  * If someone is running, return false.
1975  * Has to be called with memcg_oom_lock
1976  */
1977 static bool mem_cgroup_oom_lock(struct mem_cgroup *memcg)
1978 {
1979 	struct mem_cgroup *iter, *failed = NULL;
1980 
1981 	for_each_mem_cgroup_tree(iter, memcg) {
1982 		if (iter->oom_lock) {
1983 			/*
1984 			 * this subtree of our hierarchy is already locked
1985 			 * so we cannot give a lock.
1986 			 */
1987 			failed = iter;
1988 			mem_cgroup_iter_break(memcg, iter);
1989 			break;
1990 		} else
1991 			iter->oom_lock = true;
1992 	}
1993 
1994 	if (!failed)
1995 		return true;
1996 
1997 	/*
1998 	 * OK, we failed to lock the whole subtree so we have to clean up
1999 	 * what we set up to the failing subtree
2000 	 */
2001 	for_each_mem_cgroup_tree(iter, memcg) {
2002 		if (iter == failed) {
2003 			mem_cgroup_iter_break(memcg, iter);
2004 			break;
2005 		}
2006 		iter->oom_lock = false;
2007 	}
2008 	return false;
2009 }
2010 
2011 /*
2012  * Has to be called with memcg_oom_lock
2013  */
2014 static int mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
2015 {
2016 	struct mem_cgroup *iter;
2017 
2018 	for_each_mem_cgroup_tree(iter, memcg)
2019 		iter->oom_lock = false;
2020 	return 0;
2021 }
2022 
2023 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
2024 {
2025 	struct mem_cgroup *iter;
2026 
2027 	for_each_mem_cgroup_tree(iter, memcg)
2028 		atomic_inc(&iter->under_oom);
2029 }
2030 
2031 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
2032 {
2033 	struct mem_cgroup *iter;
2034 
2035 	/*
2036 	 * When a new child is created while the hierarchy is under oom,
2037 	 * mem_cgroup_oom_lock() may not be called. We have to use
2038 	 * atomic_add_unless() here.
2039 	 */
2040 	for_each_mem_cgroup_tree(iter, memcg)
2041 		atomic_add_unless(&iter->under_oom, -1, 0);
2042 }
2043 
2044 static DEFINE_SPINLOCK(memcg_oom_lock);
2045 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
2046 
2047 struct oom_wait_info {
2048 	struct mem_cgroup *memcg;
2049 	wait_queue_t	wait;
2050 };
2051 
2052 static int memcg_oom_wake_function(wait_queue_t *wait,
2053 	unsigned mode, int sync, void *arg)
2054 {
2055 	struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
2056 	struct mem_cgroup *oom_wait_memcg;
2057 	struct oom_wait_info *oom_wait_info;
2058 
2059 	oom_wait_info = container_of(wait, struct oom_wait_info, wait);
2060 	oom_wait_memcg = oom_wait_info->memcg;
2061 
2062 	/*
2063 	 * Both of oom_wait_info->memcg and wake_memcg are stable under us.
2064 	 * Then we can use css_is_ancestor without taking care of RCU.
2065 	 */
2066 	if (!mem_cgroup_same_or_subtree(oom_wait_memcg, wake_memcg)
2067 		&& !mem_cgroup_same_or_subtree(wake_memcg, oom_wait_memcg))
2068 		return 0;
2069 	return autoremove_wake_function(wait, mode, sync, arg);
2070 }
2071 
2072 static void memcg_wakeup_oom(struct mem_cgroup *memcg)
2073 {
2074 	/* for filtering, pass "memcg" as argument. */
2075 	__wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
2076 }
2077 
2078 static void memcg_oom_recover(struct mem_cgroup *memcg)
2079 {
2080 	if (memcg && atomic_read(&memcg->under_oom))
2081 		memcg_wakeup_oom(memcg);
2082 }
2083 
2084 /*
2085  * try to call OOM killer. returns false if we should exit memory-reclaim loop.
2086  */
2087 static bool mem_cgroup_handle_oom(struct mem_cgroup *memcg, gfp_t mask,
2088 				  int order)
2089 {
2090 	struct oom_wait_info owait;
2091 	bool locked, need_to_kill;
2092 
2093 	owait.memcg = memcg;
2094 	owait.wait.flags = 0;
2095 	owait.wait.func = memcg_oom_wake_function;
2096 	owait.wait.private = current;
2097 	INIT_LIST_HEAD(&owait.wait.task_list);
2098 	need_to_kill = true;
2099 	mem_cgroup_mark_under_oom(memcg);
2100 
2101 	/* At first, try to OOM lock hierarchy under memcg.*/
2102 	spin_lock(&memcg_oom_lock);
2103 	locked = mem_cgroup_oom_lock(memcg);
2104 	/*
2105 	 * Even if signal_pending(), we can't quit charge() loop without
2106 	 * accounting. So, UNINTERRUPTIBLE is appropriate. But SIGKILL
2107 	 * under OOM is always welcomed, use TASK_KILLABLE here.
2108 	 */
2109 	prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
2110 	if (!locked || memcg->oom_kill_disable)
2111 		need_to_kill = false;
2112 	if (locked)
2113 		mem_cgroup_oom_notify(memcg);
2114 	spin_unlock(&memcg_oom_lock);
2115 
2116 	if (need_to_kill) {
2117 		finish_wait(&memcg_oom_waitq, &owait.wait);
2118 		mem_cgroup_out_of_memory(memcg, mask, order);
2119 	} else {
2120 		schedule();
2121 		finish_wait(&memcg_oom_waitq, &owait.wait);
2122 	}
2123 	spin_lock(&memcg_oom_lock);
2124 	if (locked)
2125 		mem_cgroup_oom_unlock(memcg);
2126 	memcg_wakeup_oom(memcg);
2127 	spin_unlock(&memcg_oom_lock);
2128 
2129 	mem_cgroup_unmark_under_oom(memcg);
2130 
2131 	if (test_thread_flag(TIF_MEMDIE) || fatal_signal_pending(current))
2132 		return false;
2133 	/* Give chance to dying process */
2134 	schedule_timeout_uninterruptible(1);
2135 	return true;
2136 }
2137 
2138 /*
2139  * Currently used to update mapped file statistics, but the routine can be
2140  * generalized to update other statistics as well.
2141  *
2142  * Notes: Race condition
2143  *
2144  * We usually use page_cgroup_lock() for accessing page_cgroup member but
2145  * it tends to be costly. But considering some conditions, we doesn't need
2146  * to do so _always_.
2147  *
2148  * Considering "charge", lock_page_cgroup() is not required because all
2149  * file-stat operations happen after a page is attached to radix-tree. There
2150  * are no race with "charge".
2151  *
2152  * Considering "uncharge", we know that memcg doesn't clear pc->mem_cgroup
2153  * at "uncharge" intentionally. So, we always see valid pc->mem_cgroup even
2154  * if there are race with "uncharge". Statistics itself is properly handled
2155  * by flags.
2156  *
2157  * Considering "move", this is an only case we see a race. To make the race
2158  * small, we check mm->moving_account and detect there are possibility of race
2159  * If there is, we take a lock.
2160  */
2161 
2162 void __mem_cgroup_begin_update_page_stat(struct page *page,
2163 				bool *locked, unsigned long *flags)
2164 {
2165 	struct mem_cgroup *memcg;
2166 	struct page_cgroup *pc;
2167 
2168 	pc = lookup_page_cgroup(page);
2169 again:
2170 	memcg = pc->mem_cgroup;
2171 	if (unlikely(!memcg || !PageCgroupUsed(pc)))
2172 		return;
2173 	/*
2174 	 * If this memory cgroup is not under account moving, we don't
2175 	 * need to take move_lock_mem_cgroup(). Because we already hold
2176 	 * rcu_read_lock(), any calls to move_account will be delayed until
2177 	 * rcu_read_unlock() if mem_cgroup_stolen() == true.
2178 	 */
2179 	if (!mem_cgroup_stolen(memcg))
2180 		return;
2181 
2182 	move_lock_mem_cgroup(memcg, flags);
2183 	if (memcg != pc->mem_cgroup || !PageCgroupUsed(pc)) {
2184 		move_unlock_mem_cgroup(memcg, flags);
2185 		goto again;
2186 	}
2187 	*locked = true;
2188 }
2189 
2190 void __mem_cgroup_end_update_page_stat(struct page *page, unsigned long *flags)
2191 {
2192 	struct page_cgroup *pc = lookup_page_cgroup(page);
2193 
2194 	/*
2195 	 * It's guaranteed that pc->mem_cgroup never changes while
2196 	 * lock is held because a routine modifies pc->mem_cgroup
2197 	 * should take move_lock_mem_cgroup().
2198 	 */
2199 	move_unlock_mem_cgroup(pc->mem_cgroup, flags);
2200 }
2201 
2202 void mem_cgroup_update_page_stat(struct page *page,
2203 				 enum mem_cgroup_page_stat_item idx, int val)
2204 {
2205 	struct mem_cgroup *memcg;
2206 	struct page_cgroup *pc = lookup_page_cgroup(page);
2207 	unsigned long uninitialized_var(flags);
2208 
2209 	if (mem_cgroup_disabled())
2210 		return;
2211 
2212 	memcg = pc->mem_cgroup;
2213 	if (unlikely(!memcg || !PageCgroupUsed(pc)))
2214 		return;
2215 
2216 	switch (idx) {
2217 	case MEMCG_NR_FILE_MAPPED:
2218 		idx = MEM_CGROUP_STAT_FILE_MAPPED;
2219 		break;
2220 	default:
2221 		BUG();
2222 	}
2223 
2224 	this_cpu_add(memcg->stat->count[idx], val);
2225 }
2226 
2227 /*
2228  * size of first charge trial. "32" comes from vmscan.c's magic value.
2229  * TODO: maybe necessary to use big numbers in big irons.
2230  */
2231 #define CHARGE_BATCH	32U
2232 struct memcg_stock_pcp {
2233 	struct mem_cgroup *cached; /* this never be root cgroup */
2234 	unsigned int nr_pages;
2235 	struct work_struct work;
2236 	unsigned long flags;
2237 #define FLUSHING_CACHED_CHARGE	0
2238 };
2239 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
2240 static DEFINE_MUTEX(percpu_charge_mutex);
2241 
2242 /**
2243  * consume_stock: Try to consume stocked charge on this cpu.
2244  * @memcg: memcg to consume from.
2245  * @nr_pages: how many pages to charge.
2246  *
2247  * The charges will only happen if @memcg matches the current cpu's memcg
2248  * stock, and at least @nr_pages are available in that stock.  Failure to
2249  * service an allocation will refill the stock.
2250  *
2251  * returns true if successful, false otherwise.
2252  */
2253 static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2254 {
2255 	struct memcg_stock_pcp *stock;
2256 	bool ret = true;
2257 
2258 	if (nr_pages > CHARGE_BATCH)
2259 		return false;
2260 
2261 	stock = &get_cpu_var(memcg_stock);
2262 	if (memcg == stock->cached && stock->nr_pages >= nr_pages)
2263 		stock->nr_pages -= nr_pages;
2264 	else /* need to call res_counter_charge */
2265 		ret = false;
2266 	put_cpu_var(memcg_stock);
2267 	return ret;
2268 }
2269 
2270 /*
2271  * Returns stocks cached in percpu to res_counter and reset cached information.
2272  */
2273 static void drain_stock(struct memcg_stock_pcp *stock)
2274 {
2275 	struct mem_cgroup *old = stock->cached;
2276 
2277 	if (stock->nr_pages) {
2278 		unsigned long bytes = stock->nr_pages * PAGE_SIZE;
2279 
2280 		res_counter_uncharge(&old->res, bytes);
2281 		if (do_swap_account)
2282 			res_counter_uncharge(&old->memsw, bytes);
2283 		stock->nr_pages = 0;
2284 	}
2285 	stock->cached = NULL;
2286 }
2287 
2288 /*
2289  * This must be called under preempt disabled or must be called by
2290  * a thread which is pinned to local cpu.
2291  */
2292 static void drain_local_stock(struct work_struct *dummy)
2293 {
2294 	struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
2295 	drain_stock(stock);
2296 	clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2297 }
2298 
2299 static void __init memcg_stock_init(void)
2300 {
2301 	int cpu;
2302 
2303 	for_each_possible_cpu(cpu) {
2304 		struct memcg_stock_pcp *stock =
2305 					&per_cpu(memcg_stock, cpu);
2306 		INIT_WORK(&stock->work, drain_local_stock);
2307 	}
2308 }
2309 
2310 /*
2311  * Cache charges(val) which is from res_counter, to local per_cpu area.
2312  * This will be consumed by consume_stock() function, later.
2313  */
2314 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2315 {
2316 	struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
2317 
2318 	if (stock->cached != memcg) { /* reset if necessary */
2319 		drain_stock(stock);
2320 		stock->cached = memcg;
2321 	}
2322 	stock->nr_pages += nr_pages;
2323 	put_cpu_var(memcg_stock);
2324 }
2325 
2326 /*
2327  * Drains all per-CPU charge caches for given root_memcg resp. subtree
2328  * of the hierarchy under it. sync flag says whether we should block
2329  * until the work is done.
2330  */
2331 static void drain_all_stock(struct mem_cgroup *root_memcg, bool sync)
2332 {
2333 	int cpu, curcpu;
2334 
2335 	/* Notify other cpus that system-wide "drain" is running */
2336 	get_online_cpus();
2337 	curcpu = get_cpu();
2338 	for_each_online_cpu(cpu) {
2339 		struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2340 		struct mem_cgroup *memcg;
2341 
2342 		memcg = stock->cached;
2343 		if (!memcg || !stock->nr_pages)
2344 			continue;
2345 		if (!mem_cgroup_same_or_subtree(root_memcg, memcg))
2346 			continue;
2347 		if (!test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2348 			if (cpu == curcpu)
2349 				drain_local_stock(&stock->work);
2350 			else
2351 				schedule_work_on(cpu, &stock->work);
2352 		}
2353 	}
2354 	put_cpu();
2355 
2356 	if (!sync)
2357 		goto out;
2358 
2359 	for_each_online_cpu(cpu) {
2360 		struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2361 		if (test_bit(FLUSHING_CACHED_CHARGE, &stock->flags))
2362 			flush_work(&stock->work);
2363 	}
2364 out:
2365  	put_online_cpus();
2366 }
2367 
2368 /*
2369  * Tries to drain stocked charges in other cpus. This function is asynchronous
2370  * and just put a work per cpu for draining localy on each cpu. Caller can
2371  * expects some charges will be back to res_counter later but cannot wait for
2372  * it.
2373  */
2374 static void drain_all_stock_async(struct mem_cgroup *root_memcg)
2375 {
2376 	/*
2377 	 * If someone calls draining, avoid adding more kworker runs.
2378 	 */
2379 	if (!mutex_trylock(&percpu_charge_mutex))
2380 		return;
2381 	drain_all_stock(root_memcg, false);
2382 	mutex_unlock(&percpu_charge_mutex);
2383 }
2384 
2385 /* This is a synchronous drain interface. */
2386 static void drain_all_stock_sync(struct mem_cgroup *root_memcg)
2387 {
2388 	/* called when force_empty is called */
2389 	mutex_lock(&percpu_charge_mutex);
2390 	drain_all_stock(root_memcg, true);
2391 	mutex_unlock(&percpu_charge_mutex);
2392 }
2393 
2394 /*
2395  * This function drains percpu counter value from DEAD cpu and
2396  * move it to local cpu. Note that this function can be preempted.
2397  */
2398 static void mem_cgroup_drain_pcp_counter(struct mem_cgroup *memcg, int cpu)
2399 {
2400 	int i;
2401 
2402 	spin_lock(&memcg->pcp_counter_lock);
2403 	for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
2404 		long x = per_cpu(memcg->stat->count[i], cpu);
2405 
2406 		per_cpu(memcg->stat->count[i], cpu) = 0;
2407 		memcg->nocpu_base.count[i] += x;
2408 	}
2409 	for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
2410 		unsigned long x = per_cpu(memcg->stat->events[i], cpu);
2411 
2412 		per_cpu(memcg->stat->events[i], cpu) = 0;
2413 		memcg->nocpu_base.events[i] += x;
2414 	}
2415 	spin_unlock(&memcg->pcp_counter_lock);
2416 }
2417 
2418 static int __cpuinit memcg_cpu_hotplug_callback(struct notifier_block *nb,
2419 					unsigned long action,
2420 					void *hcpu)
2421 {
2422 	int cpu = (unsigned long)hcpu;
2423 	struct memcg_stock_pcp *stock;
2424 	struct mem_cgroup *iter;
2425 
2426 	if (action == CPU_ONLINE)
2427 		return NOTIFY_OK;
2428 
2429 	if (action != CPU_DEAD && action != CPU_DEAD_FROZEN)
2430 		return NOTIFY_OK;
2431 
2432 	for_each_mem_cgroup(iter)
2433 		mem_cgroup_drain_pcp_counter(iter, cpu);
2434 
2435 	stock = &per_cpu(memcg_stock, cpu);
2436 	drain_stock(stock);
2437 	return NOTIFY_OK;
2438 }
2439 
2440 
2441 /* See __mem_cgroup_try_charge() for details */
2442 enum {
2443 	CHARGE_OK,		/* success */
2444 	CHARGE_RETRY,		/* need to retry but retry is not bad */
2445 	CHARGE_NOMEM,		/* we can't do more. return -ENOMEM */
2446 	CHARGE_WOULDBLOCK,	/* GFP_WAIT wasn't set and no enough res. */
2447 	CHARGE_OOM_DIE,		/* the current is killed because of OOM */
2448 };
2449 
2450 static int mem_cgroup_do_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2451 				unsigned int nr_pages, unsigned int min_pages,
2452 				bool oom_check)
2453 {
2454 	unsigned long csize = nr_pages * PAGE_SIZE;
2455 	struct mem_cgroup *mem_over_limit;
2456 	struct res_counter *fail_res;
2457 	unsigned long flags = 0;
2458 	int ret;
2459 
2460 	ret = res_counter_charge(&memcg->res, csize, &fail_res);
2461 
2462 	if (likely(!ret)) {
2463 		if (!do_swap_account)
2464 			return CHARGE_OK;
2465 		ret = res_counter_charge(&memcg->memsw, csize, &fail_res);
2466 		if (likely(!ret))
2467 			return CHARGE_OK;
2468 
2469 		res_counter_uncharge(&memcg->res, csize);
2470 		mem_over_limit = mem_cgroup_from_res_counter(fail_res, memsw);
2471 		flags |= MEM_CGROUP_RECLAIM_NOSWAP;
2472 	} else
2473 		mem_over_limit = mem_cgroup_from_res_counter(fail_res, res);
2474 	/*
2475 	 * Never reclaim on behalf of optional batching, retry with a
2476 	 * single page instead.
2477 	 */
2478 	if (nr_pages > min_pages)
2479 		return CHARGE_RETRY;
2480 
2481 	if (!(gfp_mask & __GFP_WAIT))
2482 		return CHARGE_WOULDBLOCK;
2483 
2484 	if (gfp_mask & __GFP_NORETRY)
2485 		return CHARGE_NOMEM;
2486 
2487 	ret = mem_cgroup_reclaim(mem_over_limit, gfp_mask, flags);
2488 	if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2489 		return CHARGE_RETRY;
2490 	/*
2491 	 * Even though the limit is exceeded at this point, reclaim
2492 	 * may have been able to free some pages.  Retry the charge
2493 	 * before killing the task.
2494 	 *
2495 	 * Only for regular pages, though: huge pages are rather
2496 	 * unlikely to succeed so close to the limit, and we fall back
2497 	 * to regular pages anyway in case of failure.
2498 	 */
2499 	if (nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER) && ret)
2500 		return CHARGE_RETRY;
2501 
2502 	/*
2503 	 * At task move, charge accounts can be doubly counted. So, it's
2504 	 * better to wait until the end of task_move if something is going on.
2505 	 */
2506 	if (mem_cgroup_wait_acct_move(mem_over_limit))
2507 		return CHARGE_RETRY;
2508 
2509 	/* If we don't need to call oom-killer at el, return immediately */
2510 	if (!oom_check)
2511 		return CHARGE_NOMEM;
2512 	/* check OOM */
2513 	if (!mem_cgroup_handle_oom(mem_over_limit, gfp_mask, get_order(csize)))
2514 		return CHARGE_OOM_DIE;
2515 
2516 	return CHARGE_RETRY;
2517 }
2518 
2519 /*
2520  * __mem_cgroup_try_charge() does
2521  * 1. detect memcg to be charged against from passed *mm and *ptr,
2522  * 2. update res_counter
2523  * 3. call memory reclaim if necessary.
2524  *
2525  * In some special case, if the task is fatal, fatal_signal_pending() or
2526  * has TIF_MEMDIE, this function returns -EINTR while writing root_mem_cgroup
2527  * to *ptr. There are two reasons for this. 1: fatal threads should quit as soon
2528  * as possible without any hazards. 2: all pages should have a valid
2529  * pc->mem_cgroup. If mm is NULL and the caller doesn't pass a valid memcg
2530  * pointer, that is treated as a charge to root_mem_cgroup.
2531  *
2532  * So __mem_cgroup_try_charge() will return
2533  *  0       ...  on success, filling *ptr with a valid memcg pointer.
2534  *  -ENOMEM ...  charge failure because of resource limits.
2535  *  -EINTR  ...  if thread is fatal. *ptr is filled with root_mem_cgroup.
2536  *
2537  * Unlike the exported interface, an "oom" parameter is added. if oom==true,
2538  * the oom-killer can be invoked.
2539  */
2540 static int __mem_cgroup_try_charge(struct mm_struct *mm,
2541 				   gfp_t gfp_mask,
2542 				   unsigned int nr_pages,
2543 				   struct mem_cgroup **ptr,
2544 				   bool oom)
2545 {
2546 	unsigned int batch = max(CHARGE_BATCH, nr_pages);
2547 	int nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2548 	struct mem_cgroup *memcg = NULL;
2549 	int ret;
2550 
2551 	/*
2552 	 * Unlike gloval-vm's OOM-kill, we're not in memory shortage
2553 	 * in system level. So, allow to go ahead dying process in addition to
2554 	 * MEMDIE process.
2555 	 */
2556 	if (unlikely(test_thread_flag(TIF_MEMDIE)
2557 		     || fatal_signal_pending(current)))
2558 		goto bypass;
2559 
2560 	/*
2561 	 * We always charge the cgroup the mm_struct belongs to.
2562 	 * The mm_struct's mem_cgroup changes on task migration if the
2563 	 * thread group leader migrates. It's possible that mm is not
2564 	 * set, if so charge the root memcg (happens for pagecache usage).
2565 	 */
2566 	if (!*ptr && !mm)
2567 		*ptr = root_mem_cgroup;
2568 again:
2569 	if (*ptr) { /* css should be a valid one */
2570 		memcg = *ptr;
2571 		if (mem_cgroup_is_root(memcg))
2572 			goto done;
2573 		if (consume_stock(memcg, nr_pages))
2574 			goto done;
2575 		css_get(&memcg->css);
2576 	} else {
2577 		struct task_struct *p;
2578 
2579 		rcu_read_lock();
2580 		p = rcu_dereference(mm->owner);
2581 		/*
2582 		 * Because we don't have task_lock(), "p" can exit.
2583 		 * In that case, "memcg" can point to root or p can be NULL with
2584 		 * race with swapoff. Then, we have small risk of mis-accouning.
2585 		 * But such kind of mis-account by race always happens because
2586 		 * we don't have cgroup_mutex(). It's overkill and we allo that
2587 		 * small race, here.
2588 		 * (*) swapoff at el will charge against mm-struct not against
2589 		 * task-struct. So, mm->owner can be NULL.
2590 		 */
2591 		memcg = mem_cgroup_from_task(p);
2592 		if (!memcg)
2593 			memcg = root_mem_cgroup;
2594 		if (mem_cgroup_is_root(memcg)) {
2595 			rcu_read_unlock();
2596 			goto done;
2597 		}
2598 		if (consume_stock(memcg, nr_pages)) {
2599 			/*
2600 			 * It seems dagerous to access memcg without css_get().
2601 			 * But considering how consume_stok works, it's not
2602 			 * necessary. If consume_stock success, some charges
2603 			 * from this memcg are cached on this cpu. So, we
2604 			 * don't need to call css_get()/css_tryget() before
2605 			 * calling consume_stock().
2606 			 */
2607 			rcu_read_unlock();
2608 			goto done;
2609 		}
2610 		/* after here, we may be blocked. we need to get refcnt */
2611 		if (!css_tryget(&memcg->css)) {
2612 			rcu_read_unlock();
2613 			goto again;
2614 		}
2615 		rcu_read_unlock();
2616 	}
2617 
2618 	do {
2619 		bool oom_check;
2620 
2621 		/* If killed, bypass charge */
2622 		if (fatal_signal_pending(current)) {
2623 			css_put(&memcg->css);
2624 			goto bypass;
2625 		}
2626 
2627 		oom_check = false;
2628 		if (oom && !nr_oom_retries) {
2629 			oom_check = true;
2630 			nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2631 		}
2632 
2633 		ret = mem_cgroup_do_charge(memcg, gfp_mask, batch, nr_pages,
2634 		    oom_check);
2635 		switch (ret) {
2636 		case CHARGE_OK:
2637 			break;
2638 		case CHARGE_RETRY: /* not in OOM situation but retry */
2639 			batch = nr_pages;
2640 			css_put(&memcg->css);
2641 			memcg = NULL;
2642 			goto again;
2643 		case CHARGE_WOULDBLOCK: /* !__GFP_WAIT */
2644 			css_put(&memcg->css);
2645 			goto nomem;
2646 		case CHARGE_NOMEM: /* OOM routine works */
2647 			if (!oom) {
2648 				css_put(&memcg->css);
2649 				goto nomem;
2650 			}
2651 			/* If oom, we never return -ENOMEM */
2652 			nr_oom_retries--;
2653 			break;
2654 		case CHARGE_OOM_DIE: /* Killed by OOM Killer */
2655 			css_put(&memcg->css);
2656 			goto bypass;
2657 		}
2658 	} while (ret != CHARGE_OK);
2659 
2660 	if (batch > nr_pages)
2661 		refill_stock(memcg, batch - nr_pages);
2662 	css_put(&memcg->css);
2663 done:
2664 	*ptr = memcg;
2665 	return 0;
2666 nomem:
2667 	*ptr = NULL;
2668 	return -ENOMEM;
2669 bypass:
2670 	*ptr = root_mem_cgroup;
2671 	return -EINTR;
2672 }
2673 
2674 /*
2675  * Somemtimes we have to undo a charge we got by try_charge().
2676  * This function is for that and do uncharge, put css's refcnt.
2677  * gotten by try_charge().
2678  */
2679 static void __mem_cgroup_cancel_charge(struct mem_cgroup *memcg,
2680 				       unsigned int nr_pages)
2681 {
2682 	if (!mem_cgroup_is_root(memcg)) {
2683 		unsigned long bytes = nr_pages * PAGE_SIZE;
2684 
2685 		res_counter_uncharge(&memcg->res, bytes);
2686 		if (do_swap_account)
2687 			res_counter_uncharge(&memcg->memsw, bytes);
2688 	}
2689 }
2690 
2691 /*
2692  * Cancel chrages in this cgroup....doesn't propagate to parent cgroup.
2693  * This is useful when moving usage to parent cgroup.
2694  */
2695 static void __mem_cgroup_cancel_local_charge(struct mem_cgroup *memcg,
2696 					unsigned int nr_pages)
2697 {
2698 	unsigned long bytes = nr_pages * PAGE_SIZE;
2699 
2700 	if (mem_cgroup_is_root(memcg))
2701 		return;
2702 
2703 	res_counter_uncharge_until(&memcg->res, memcg->res.parent, bytes);
2704 	if (do_swap_account)
2705 		res_counter_uncharge_until(&memcg->memsw,
2706 						memcg->memsw.parent, bytes);
2707 }
2708 
2709 /*
2710  * A helper function to get mem_cgroup from ID. must be called under
2711  * rcu_read_lock().  The caller is responsible for calling css_tryget if
2712  * the mem_cgroup is used for charging. (dropping refcnt from swap can be
2713  * called against removed memcg.)
2714  */
2715 static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
2716 {
2717 	struct cgroup_subsys_state *css;
2718 
2719 	/* ID 0 is unused ID */
2720 	if (!id)
2721 		return NULL;
2722 	css = css_lookup(&mem_cgroup_subsys, id);
2723 	if (!css)
2724 		return NULL;
2725 	return mem_cgroup_from_css(css);
2726 }
2727 
2728 struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
2729 {
2730 	struct mem_cgroup *memcg = NULL;
2731 	struct page_cgroup *pc;
2732 	unsigned short id;
2733 	swp_entry_t ent;
2734 
2735 	VM_BUG_ON(!PageLocked(page));
2736 
2737 	pc = lookup_page_cgroup(page);
2738 	lock_page_cgroup(pc);
2739 	if (PageCgroupUsed(pc)) {
2740 		memcg = pc->mem_cgroup;
2741 		if (memcg && !css_tryget(&memcg->css))
2742 			memcg = NULL;
2743 	} else if (PageSwapCache(page)) {
2744 		ent.val = page_private(page);
2745 		id = lookup_swap_cgroup_id(ent);
2746 		rcu_read_lock();
2747 		memcg = mem_cgroup_lookup(id);
2748 		if (memcg && !css_tryget(&memcg->css))
2749 			memcg = NULL;
2750 		rcu_read_unlock();
2751 	}
2752 	unlock_page_cgroup(pc);
2753 	return memcg;
2754 }
2755 
2756 static void __mem_cgroup_commit_charge(struct mem_cgroup *memcg,
2757 				       struct page *page,
2758 				       unsigned int nr_pages,
2759 				       enum charge_type ctype,
2760 				       bool lrucare)
2761 {
2762 	struct page_cgroup *pc = lookup_page_cgroup(page);
2763 	struct zone *uninitialized_var(zone);
2764 	struct lruvec *lruvec;
2765 	bool was_on_lru = false;
2766 	bool anon;
2767 
2768 	lock_page_cgroup(pc);
2769 	VM_BUG_ON(PageCgroupUsed(pc));
2770 	/*
2771 	 * we don't need page_cgroup_lock about tail pages, becase they are not
2772 	 * accessed by any other context at this point.
2773 	 */
2774 
2775 	/*
2776 	 * In some cases, SwapCache and FUSE(splice_buf->radixtree), the page
2777 	 * may already be on some other mem_cgroup's LRU.  Take care of it.
2778 	 */
2779 	if (lrucare) {
2780 		zone = page_zone(page);
2781 		spin_lock_irq(&zone->lru_lock);
2782 		if (PageLRU(page)) {
2783 			lruvec = mem_cgroup_zone_lruvec(zone, pc->mem_cgroup);
2784 			ClearPageLRU(page);
2785 			del_page_from_lru_list(page, lruvec, page_lru(page));
2786 			was_on_lru = true;
2787 		}
2788 	}
2789 
2790 	pc->mem_cgroup = memcg;
2791 	/*
2792 	 * We access a page_cgroup asynchronously without lock_page_cgroup().
2793 	 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
2794 	 * is accessed after testing USED bit. To make pc->mem_cgroup visible
2795 	 * before USED bit, we need memory barrier here.
2796 	 * See mem_cgroup_add_lru_list(), etc.
2797  	 */
2798 	smp_wmb();
2799 	SetPageCgroupUsed(pc);
2800 
2801 	if (lrucare) {
2802 		if (was_on_lru) {
2803 			lruvec = mem_cgroup_zone_lruvec(zone, pc->mem_cgroup);
2804 			VM_BUG_ON(PageLRU(page));
2805 			SetPageLRU(page);
2806 			add_page_to_lru_list(page, lruvec, page_lru(page));
2807 		}
2808 		spin_unlock_irq(&zone->lru_lock);
2809 	}
2810 
2811 	if (ctype == MEM_CGROUP_CHARGE_TYPE_ANON)
2812 		anon = true;
2813 	else
2814 		anon = false;
2815 
2816 	mem_cgroup_charge_statistics(memcg, anon, nr_pages);
2817 	unlock_page_cgroup(pc);
2818 
2819 	/*
2820 	 * "charge_statistics" updated event counter. Then, check it.
2821 	 * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
2822 	 * if they exceeds softlimit.
2823 	 */
2824 	memcg_check_events(memcg, page);
2825 }
2826 
2827 static DEFINE_MUTEX(set_limit_mutex);
2828 
2829 #ifdef CONFIG_MEMCG_KMEM
2830 static inline bool memcg_can_account_kmem(struct mem_cgroup *memcg)
2831 {
2832 	return !mem_cgroup_disabled() && !mem_cgroup_is_root(memcg) &&
2833 		(memcg->kmem_account_flags & KMEM_ACCOUNTED_MASK);
2834 }
2835 
2836 /*
2837  * This is a bit cumbersome, but it is rarely used and avoids a backpointer
2838  * in the memcg_cache_params struct.
2839  */
2840 static struct kmem_cache *memcg_params_to_cache(struct memcg_cache_params *p)
2841 {
2842 	struct kmem_cache *cachep;
2843 
2844 	VM_BUG_ON(p->is_root_cache);
2845 	cachep = p->root_cache;
2846 	return cachep->memcg_params->memcg_caches[memcg_cache_id(p->memcg)];
2847 }
2848 
2849 #ifdef CONFIG_SLABINFO
2850 static int mem_cgroup_slabinfo_read(struct cgroup *cont, struct cftype *cft,
2851 					struct seq_file *m)
2852 {
2853 	struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
2854 	struct memcg_cache_params *params;
2855 
2856 	if (!memcg_can_account_kmem(memcg))
2857 		return -EIO;
2858 
2859 	print_slabinfo_header(m);
2860 
2861 	mutex_lock(&memcg->slab_caches_mutex);
2862 	list_for_each_entry(params, &memcg->memcg_slab_caches, list)
2863 		cache_show(memcg_params_to_cache(params), m);
2864 	mutex_unlock(&memcg->slab_caches_mutex);
2865 
2866 	return 0;
2867 }
2868 #endif
2869 
2870 static int memcg_charge_kmem(struct mem_cgroup *memcg, gfp_t gfp, u64 size)
2871 {
2872 	struct res_counter *fail_res;
2873 	struct mem_cgroup *_memcg;
2874 	int ret = 0;
2875 	bool may_oom;
2876 
2877 	ret = res_counter_charge(&memcg->kmem, size, &fail_res);
2878 	if (ret)
2879 		return ret;
2880 
2881 	/*
2882 	 * Conditions under which we can wait for the oom_killer. Those are
2883 	 * the same conditions tested by the core page allocator
2884 	 */
2885 	may_oom = (gfp & __GFP_FS) && !(gfp & __GFP_NORETRY);
2886 
2887 	_memcg = memcg;
2888 	ret = __mem_cgroup_try_charge(NULL, gfp, size >> PAGE_SHIFT,
2889 				      &_memcg, may_oom);
2890 
2891 	if (ret == -EINTR)  {
2892 		/*
2893 		 * __mem_cgroup_try_charge() chosed to bypass to root due to
2894 		 * OOM kill or fatal signal.  Since our only options are to
2895 		 * either fail the allocation or charge it to this cgroup, do
2896 		 * it as a temporary condition. But we can't fail. From a
2897 		 * kmem/slab perspective, the cache has already been selected,
2898 		 * by mem_cgroup_kmem_get_cache(), so it is too late to change
2899 		 * our minds.
2900 		 *
2901 		 * This condition will only trigger if the task entered
2902 		 * memcg_charge_kmem in a sane state, but was OOM-killed during
2903 		 * __mem_cgroup_try_charge() above. Tasks that were already
2904 		 * dying when the allocation triggers should have been already
2905 		 * directed to the root cgroup in memcontrol.h
2906 		 */
2907 		res_counter_charge_nofail(&memcg->res, size, &fail_res);
2908 		if (do_swap_account)
2909 			res_counter_charge_nofail(&memcg->memsw, size,
2910 						  &fail_res);
2911 		ret = 0;
2912 	} else if (ret)
2913 		res_counter_uncharge(&memcg->kmem, size);
2914 
2915 	return ret;
2916 }
2917 
2918 static void memcg_uncharge_kmem(struct mem_cgroup *memcg, u64 size)
2919 {
2920 	res_counter_uncharge(&memcg->res, size);
2921 	if (do_swap_account)
2922 		res_counter_uncharge(&memcg->memsw, size);
2923 
2924 	/* Not down to 0 */
2925 	if (res_counter_uncharge(&memcg->kmem, size))
2926 		return;
2927 
2928 	if (memcg_kmem_test_and_clear_dead(memcg))
2929 		mem_cgroup_put(memcg);
2930 }
2931 
2932 void memcg_cache_list_add(struct mem_cgroup *memcg, struct kmem_cache *cachep)
2933 {
2934 	if (!memcg)
2935 		return;
2936 
2937 	mutex_lock(&memcg->slab_caches_mutex);
2938 	list_add(&cachep->memcg_params->list, &memcg->memcg_slab_caches);
2939 	mutex_unlock(&memcg->slab_caches_mutex);
2940 }
2941 
2942 /*
2943  * helper for acessing a memcg's index. It will be used as an index in the
2944  * child cache array in kmem_cache, and also to derive its name. This function
2945  * will return -1 when this is not a kmem-limited memcg.
2946  */
2947 int memcg_cache_id(struct mem_cgroup *memcg)
2948 {
2949 	return memcg ? memcg->kmemcg_id : -1;
2950 }
2951 
2952 /*
2953  * This ends up being protected by the set_limit mutex, during normal
2954  * operation, because that is its main call site.
2955  *
2956  * But when we create a new cache, we can call this as well if its parent
2957  * is kmem-limited. That will have to hold set_limit_mutex as well.
2958  */
2959 int memcg_update_cache_sizes(struct mem_cgroup *memcg)
2960 {
2961 	int num, ret;
2962 
2963 	num = ida_simple_get(&kmem_limited_groups,
2964 				0, MEMCG_CACHES_MAX_SIZE, GFP_KERNEL);
2965 	if (num < 0)
2966 		return num;
2967 	/*
2968 	 * After this point, kmem_accounted (that we test atomically in
2969 	 * the beginning of this conditional), is no longer 0. This
2970 	 * guarantees only one process will set the following boolean
2971 	 * to true. We don't need test_and_set because we're protected
2972 	 * by the set_limit_mutex anyway.
2973 	 */
2974 	memcg_kmem_set_activated(memcg);
2975 
2976 	ret = memcg_update_all_caches(num+1);
2977 	if (ret) {
2978 		ida_simple_remove(&kmem_limited_groups, num);
2979 		memcg_kmem_clear_activated(memcg);
2980 		return ret;
2981 	}
2982 
2983 	memcg->kmemcg_id = num;
2984 	INIT_LIST_HEAD(&memcg->memcg_slab_caches);
2985 	mutex_init(&memcg->slab_caches_mutex);
2986 	return 0;
2987 }
2988 
2989 static size_t memcg_caches_array_size(int num_groups)
2990 {
2991 	ssize_t size;
2992 	if (num_groups <= 0)
2993 		return 0;
2994 
2995 	size = 2 * num_groups;
2996 	if (size < MEMCG_CACHES_MIN_SIZE)
2997 		size = MEMCG_CACHES_MIN_SIZE;
2998 	else if (size > MEMCG_CACHES_MAX_SIZE)
2999 		size = MEMCG_CACHES_MAX_SIZE;
3000 
3001 	return size;
3002 }
3003 
3004 /*
3005  * We should update the current array size iff all caches updates succeed. This
3006  * can only be done from the slab side. The slab mutex needs to be held when
3007  * calling this.
3008  */
3009 void memcg_update_array_size(int num)
3010 {
3011 	if (num > memcg_limited_groups_array_size)
3012 		memcg_limited_groups_array_size = memcg_caches_array_size(num);
3013 }
3014 
3015 int memcg_update_cache_size(struct kmem_cache *s, int num_groups)
3016 {
3017 	struct memcg_cache_params *cur_params = s->memcg_params;
3018 
3019 	VM_BUG_ON(s->memcg_params && !s->memcg_params->is_root_cache);
3020 
3021 	if (num_groups > memcg_limited_groups_array_size) {
3022 		int i;
3023 		ssize_t size = memcg_caches_array_size(num_groups);
3024 
3025 		size *= sizeof(void *);
3026 		size += sizeof(struct memcg_cache_params);
3027 
3028 		s->memcg_params = kzalloc(size, GFP_KERNEL);
3029 		if (!s->memcg_params) {
3030 			s->memcg_params = cur_params;
3031 			return -ENOMEM;
3032 		}
3033 
3034 		s->memcg_params->is_root_cache = true;
3035 
3036 		/*
3037 		 * There is the chance it will be bigger than
3038 		 * memcg_limited_groups_array_size, if we failed an allocation
3039 		 * in a cache, in which case all caches updated before it, will
3040 		 * have a bigger array.
3041 		 *
3042 		 * But if that is the case, the data after
3043 		 * memcg_limited_groups_array_size is certainly unused
3044 		 */
3045 		for (i = 0; i < memcg_limited_groups_array_size; i++) {
3046 			if (!cur_params->memcg_caches[i])
3047 				continue;
3048 			s->memcg_params->memcg_caches[i] =
3049 						cur_params->memcg_caches[i];
3050 		}
3051 
3052 		/*
3053 		 * Ideally, we would wait until all caches succeed, and only
3054 		 * then free the old one. But this is not worth the extra
3055 		 * pointer per-cache we'd have to have for this.
3056 		 *
3057 		 * It is not a big deal if some caches are left with a size
3058 		 * bigger than the others. And all updates will reset this
3059 		 * anyway.
3060 		 */
3061 		kfree(cur_params);
3062 	}
3063 	return 0;
3064 }
3065 
3066 int memcg_register_cache(struct mem_cgroup *memcg, struct kmem_cache *s,
3067 			 struct kmem_cache *root_cache)
3068 {
3069 	size_t size = sizeof(struct memcg_cache_params);
3070 
3071 	if (!memcg_kmem_enabled())
3072 		return 0;
3073 
3074 	if (!memcg)
3075 		size += memcg_limited_groups_array_size * sizeof(void *);
3076 
3077 	s->memcg_params = kzalloc(size, GFP_KERNEL);
3078 	if (!s->memcg_params)
3079 		return -ENOMEM;
3080 
3081 	if (memcg) {
3082 		s->memcg_params->memcg = memcg;
3083 		s->memcg_params->root_cache = root_cache;
3084 	} else
3085 		s->memcg_params->is_root_cache = true;
3086 
3087 	return 0;
3088 }
3089 
3090 void memcg_release_cache(struct kmem_cache *s)
3091 {
3092 	struct kmem_cache *root;
3093 	struct mem_cgroup *memcg;
3094 	int id;
3095 
3096 	/*
3097 	 * This happens, for instance, when a root cache goes away before we
3098 	 * add any memcg.
3099 	 */
3100 	if (!s->memcg_params)
3101 		return;
3102 
3103 	if (s->memcg_params->is_root_cache)
3104 		goto out;
3105 
3106 	memcg = s->memcg_params->memcg;
3107 	id  = memcg_cache_id(memcg);
3108 
3109 	root = s->memcg_params->root_cache;
3110 	root->memcg_params->memcg_caches[id] = NULL;
3111 	mem_cgroup_put(memcg);
3112 
3113 	mutex_lock(&memcg->slab_caches_mutex);
3114 	list_del(&s->memcg_params->list);
3115 	mutex_unlock(&memcg->slab_caches_mutex);
3116 
3117 out:
3118 	kfree(s->memcg_params);
3119 }
3120 
3121 /*
3122  * During the creation a new cache, we need to disable our accounting mechanism
3123  * altogether. This is true even if we are not creating, but rather just
3124  * enqueing new caches to be created.
3125  *
3126  * This is because that process will trigger allocations; some visible, like
3127  * explicit kmallocs to auxiliary data structures, name strings and internal
3128  * cache structures; some well concealed, like INIT_WORK() that can allocate
3129  * objects during debug.
3130  *
3131  * If any allocation happens during memcg_kmem_get_cache, we will recurse back
3132  * to it. This may not be a bounded recursion: since the first cache creation
3133  * failed to complete (waiting on the allocation), we'll just try to create the
3134  * cache again, failing at the same point.
3135  *
3136  * memcg_kmem_get_cache is prepared to abort after seeing a positive count of
3137  * memcg_kmem_skip_account. So we enclose anything that might allocate memory
3138  * inside the following two functions.
3139  */
3140 static inline void memcg_stop_kmem_account(void)
3141 {
3142 	VM_BUG_ON(!current->mm);
3143 	current->memcg_kmem_skip_account++;
3144 }
3145 
3146 static inline void memcg_resume_kmem_account(void)
3147 {
3148 	VM_BUG_ON(!current->mm);
3149 	current->memcg_kmem_skip_account--;
3150 }
3151 
3152 static void kmem_cache_destroy_work_func(struct work_struct *w)
3153 {
3154 	struct kmem_cache *cachep;
3155 	struct memcg_cache_params *p;
3156 
3157 	p = container_of(w, struct memcg_cache_params, destroy);
3158 
3159 	cachep = memcg_params_to_cache(p);
3160 
3161 	/*
3162 	 * If we get down to 0 after shrink, we could delete right away.
3163 	 * However, memcg_release_pages() already puts us back in the workqueue
3164 	 * in that case. If we proceed deleting, we'll get a dangling
3165 	 * reference, and removing the object from the workqueue in that case
3166 	 * is unnecessary complication. We are not a fast path.
3167 	 *
3168 	 * Note that this case is fundamentally different from racing with
3169 	 * shrink_slab(): if memcg_cgroup_destroy_cache() is called in
3170 	 * kmem_cache_shrink, not only we would be reinserting a dead cache
3171 	 * into the queue, but doing so from inside the worker racing to
3172 	 * destroy it.
3173 	 *
3174 	 * So if we aren't down to zero, we'll just schedule a worker and try
3175 	 * again
3176 	 */
3177 	if (atomic_read(&cachep->memcg_params->nr_pages) != 0) {
3178 		kmem_cache_shrink(cachep);
3179 		if (atomic_read(&cachep->memcg_params->nr_pages) == 0)
3180 			return;
3181 	} else
3182 		kmem_cache_destroy(cachep);
3183 }
3184 
3185 void mem_cgroup_destroy_cache(struct kmem_cache *cachep)
3186 {
3187 	if (!cachep->memcg_params->dead)
3188 		return;
3189 
3190 	/*
3191 	 * There are many ways in which we can get here.
3192 	 *
3193 	 * We can get to a memory-pressure situation while the delayed work is
3194 	 * still pending to run. The vmscan shrinkers can then release all
3195 	 * cache memory and get us to destruction. If this is the case, we'll
3196 	 * be executed twice, which is a bug (the second time will execute over
3197 	 * bogus data). In this case, cancelling the work should be fine.
3198 	 *
3199 	 * But we can also get here from the worker itself, if
3200 	 * kmem_cache_shrink is enough to shake all the remaining objects and
3201 	 * get the page count to 0. In this case, we'll deadlock if we try to
3202 	 * cancel the work (the worker runs with an internal lock held, which
3203 	 * is the same lock we would hold for cancel_work_sync().)
3204 	 *
3205 	 * Since we can't possibly know who got us here, just refrain from
3206 	 * running if there is already work pending
3207 	 */
3208 	if (work_pending(&cachep->memcg_params->destroy))
3209 		return;
3210 	/*
3211 	 * We have to defer the actual destroying to a workqueue, because
3212 	 * we might currently be in a context that cannot sleep.
3213 	 */
3214 	schedule_work(&cachep->memcg_params->destroy);
3215 }
3216 
3217 static char *memcg_cache_name(struct mem_cgroup *memcg, struct kmem_cache *s)
3218 {
3219 	char *name;
3220 	struct dentry *dentry;
3221 
3222 	rcu_read_lock();
3223 	dentry = rcu_dereference(memcg->css.cgroup->dentry);
3224 	rcu_read_unlock();
3225 
3226 	BUG_ON(dentry == NULL);
3227 
3228 	name = kasprintf(GFP_KERNEL, "%s(%d:%s)", s->name,
3229 			 memcg_cache_id(memcg), dentry->d_name.name);
3230 
3231 	return name;
3232 }
3233 
3234 static struct kmem_cache *kmem_cache_dup(struct mem_cgroup *memcg,
3235 					 struct kmem_cache *s)
3236 {
3237 	char *name;
3238 	struct kmem_cache *new;
3239 
3240 	name = memcg_cache_name(memcg, s);
3241 	if (!name)
3242 		return NULL;
3243 
3244 	new = kmem_cache_create_memcg(memcg, name, s->object_size, s->align,
3245 				      (s->flags & ~SLAB_PANIC), s->ctor, s);
3246 
3247 	if (new)
3248 		new->allocflags |= __GFP_KMEMCG;
3249 
3250 	kfree(name);
3251 	return new;
3252 }
3253 
3254 /*
3255  * This lock protects updaters, not readers. We want readers to be as fast as
3256  * they can, and they will either see NULL or a valid cache value. Our model
3257  * allow them to see NULL, in which case the root memcg will be selected.
3258  *
3259  * We need this lock because multiple allocations to the same cache from a non
3260  * will span more than one worker. Only one of them can create the cache.
3261  */
3262 static DEFINE_MUTEX(memcg_cache_mutex);
3263 static struct kmem_cache *memcg_create_kmem_cache(struct mem_cgroup *memcg,
3264 						  struct kmem_cache *cachep)
3265 {
3266 	struct kmem_cache *new_cachep;
3267 	int idx;
3268 
3269 	BUG_ON(!memcg_can_account_kmem(memcg));
3270 
3271 	idx = memcg_cache_id(memcg);
3272 
3273 	mutex_lock(&memcg_cache_mutex);
3274 	new_cachep = cachep->memcg_params->memcg_caches[idx];
3275 	if (new_cachep)
3276 		goto out;
3277 
3278 	new_cachep = kmem_cache_dup(memcg, cachep);
3279 	if (new_cachep == NULL) {
3280 		new_cachep = cachep;
3281 		goto out;
3282 	}
3283 
3284 	mem_cgroup_get(memcg);
3285 	atomic_set(&new_cachep->memcg_params->nr_pages , 0);
3286 
3287 	cachep->memcg_params->memcg_caches[idx] = new_cachep;
3288 	/*
3289 	 * the readers won't lock, make sure everybody sees the updated value,
3290 	 * so they won't put stuff in the queue again for no reason
3291 	 */
3292 	wmb();
3293 out:
3294 	mutex_unlock(&memcg_cache_mutex);
3295 	return new_cachep;
3296 }
3297 
3298 void kmem_cache_destroy_memcg_children(struct kmem_cache *s)
3299 {
3300 	struct kmem_cache *c;
3301 	int i;
3302 
3303 	if (!s->memcg_params)
3304 		return;
3305 	if (!s->memcg_params->is_root_cache)
3306 		return;
3307 
3308 	/*
3309 	 * If the cache is being destroyed, we trust that there is no one else
3310 	 * requesting objects from it. Even if there are, the sanity checks in
3311 	 * kmem_cache_destroy should caught this ill-case.
3312 	 *
3313 	 * Still, we don't want anyone else freeing memcg_caches under our
3314 	 * noses, which can happen if a new memcg comes to life. As usual,
3315 	 * we'll take the set_limit_mutex to protect ourselves against this.
3316 	 */
3317 	mutex_lock(&set_limit_mutex);
3318 	for (i = 0; i < memcg_limited_groups_array_size; i++) {
3319 		c = s->memcg_params->memcg_caches[i];
3320 		if (!c)
3321 			continue;
3322 
3323 		/*
3324 		 * We will now manually delete the caches, so to avoid races
3325 		 * we need to cancel all pending destruction workers and
3326 		 * proceed with destruction ourselves.
3327 		 *
3328 		 * kmem_cache_destroy() will call kmem_cache_shrink internally,
3329 		 * and that could spawn the workers again: it is likely that
3330 		 * the cache still have active pages until this very moment.
3331 		 * This would lead us back to mem_cgroup_destroy_cache.
3332 		 *
3333 		 * But that will not execute at all if the "dead" flag is not
3334 		 * set, so flip it down to guarantee we are in control.
3335 		 */
3336 		c->memcg_params->dead = false;
3337 		cancel_work_sync(&c->memcg_params->destroy);
3338 		kmem_cache_destroy(c);
3339 	}
3340 	mutex_unlock(&set_limit_mutex);
3341 }
3342 
3343 struct create_work {
3344 	struct mem_cgroup *memcg;
3345 	struct kmem_cache *cachep;
3346 	struct work_struct work;
3347 };
3348 
3349 static void mem_cgroup_destroy_all_caches(struct mem_cgroup *memcg)
3350 {
3351 	struct kmem_cache *cachep;
3352 	struct memcg_cache_params *params;
3353 
3354 	if (!memcg_kmem_is_active(memcg))
3355 		return;
3356 
3357 	mutex_lock(&memcg->slab_caches_mutex);
3358 	list_for_each_entry(params, &memcg->memcg_slab_caches, list) {
3359 		cachep = memcg_params_to_cache(params);
3360 		cachep->memcg_params->dead = true;
3361 		INIT_WORK(&cachep->memcg_params->destroy,
3362 				  kmem_cache_destroy_work_func);
3363 		schedule_work(&cachep->memcg_params->destroy);
3364 	}
3365 	mutex_unlock(&memcg->slab_caches_mutex);
3366 }
3367 
3368 static void memcg_create_cache_work_func(struct work_struct *w)
3369 {
3370 	struct create_work *cw;
3371 
3372 	cw = container_of(w, struct create_work, work);
3373 	memcg_create_kmem_cache(cw->memcg, cw->cachep);
3374 	/* Drop the reference gotten when we enqueued. */
3375 	css_put(&cw->memcg->css);
3376 	kfree(cw);
3377 }
3378 
3379 /*
3380  * Enqueue the creation of a per-memcg kmem_cache.
3381  * Called with rcu_read_lock.
3382  */
3383 static void __memcg_create_cache_enqueue(struct mem_cgroup *memcg,
3384 					 struct kmem_cache *cachep)
3385 {
3386 	struct create_work *cw;
3387 
3388 	cw = kmalloc(sizeof(struct create_work), GFP_NOWAIT);
3389 	if (cw == NULL)
3390 		return;
3391 
3392 	/* The corresponding put will be done in the workqueue. */
3393 	if (!css_tryget(&memcg->css)) {
3394 		kfree(cw);
3395 		return;
3396 	}
3397 
3398 	cw->memcg = memcg;
3399 	cw->cachep = cachep;
3400 
3401 	INIT_WORK(&cw->work, memcg_create_cache_work_func);
3402 	schedule_work(&cw->work);
3403 }
3404 
3405 static void memcg_create_cache_enqueue(struct mem_cgroup *memcg,
3406 				       struct kmem_cache *cachep)
3407 {
3408 	/*
3409 	 * We need to stop accounting when we kmalloc, because if the
3410 	 * corresponding kmalloc cache is not yet created, the first allocation
3411 	 * in __memcg_create_cache_enqueue will recurse.
3412 	 *
3413 	 * However, it is better to enclose the whole function. Depending on
3414 	 * the debugging options enabled, INIT_WORK(), for instance, can
3415 	 * trigger an allocation. This too, will make us recurse. Because at
3416 	 * this point we can't allow ourselves back into memcg_kmem_get_cache,
3417 	 * the safest choice is to do it like this, wrapping the whole function.
3418 	 */
3419 	memcg_stop_kmem_account();
3420 	__memcg_create_cache_enqueue(memcg, cachep);
3421 	memcg_resume_kmem_account();
3422 }
3423 /*
3424  * Return the kmem_cache we're supposed to use for a slab allocation.
3425  * We try to use the current memcg's version of the cache.
3426  *
3427  * If the cache does not exist yet, if we are the first user of it,
3428  * we either create it immediately, if possible, or create it asynchronously
3429  * in a workqueue.
3430  * In the latter case, we will let the current allocation go through with
3431  * the original cache.
3432  *
3433  * Can't be called in interrupt context or from kernel threads.
3434  * This function needs to be called with rcu_read_lock() held.
3435  */
3436 struct kmem_cache *__memcg_kmem_get_cache(struct kmem_cache *cachep,
3437 					  gfp_t gfp)
3438 {
3439 	struct mem_cgroup *memcg;
3440 	int idx;
3441 
3442 	VM_BUG_ON(!cachep->memcg_params);
3443 	VM_BUG_ON(!cachep->memcg_params->is_root_cache);
3444 
3445 	if (!current->mm || current->memcg_kmem_skip_account)
3446 		return cachep;
3447 
3448 	rcu_read_lock();
3449 	memcg = mem_cgroup_from_task(rcu_dereference(current->mm->owner));
3450 	rcu_read_unlock();
3451 
3452 	if (!memcg_can_account_kmem(memcg))
3453 		return cachep;
3454 
3455 	idx = memcg_cache_id(memcg);
3456 
3457 	/*
3458 	 * barrier to mare sure we're always seeing the up to date value.  The
3459 	 * code updating memcg_caches will issue a write barrier to match this.
3460 	 */
3461 	read_barrier_depends();
3462 	if (unlikely(cachep->memcg_params->memcg_caches[idx] == NULL)) {
3463 		/*
3464 		 * If we are in a safe context (can wait, and not in interrupt
3465 		 * context), we could be be predictable and return right away.
3466 		 * This would guarantee that the allocation being performed
3467 		 * already belongs in the new cache.
3468 		 *
3469 		 * However, there are some clashes that can arrive from locking.
3470 		 * For instance, because we acquire the slab_mutex while doing
3471 		 * kmem_cache_dup, this means no further allocation could happen
3472 		 * with the slab_mutex held.
3473 		 *
3474 		 * Also, because cache creation issue get_online_cpus(), this
3475 		 * creates a lock chain: memcg_slab_mutex -> cpu_hotplug_mutex,
3476 		 * that ends up reversed during cpu hotplug. (cpuset allocates
3477 		 * a bunch of GFP_KERNEL memory during cpuup). Due to all that,
3478 		 * better to defer everything.
3479 		 */
3480 		memcg_create_cache_enqueue(memcg, cachep);
3481 		return cachep;
3482 	}
3483 
3484 	return cachep->memcg_params->memcg_caches[idx];
3485 }
3486 EXPORT_SYMBOL(__memcg_kmem_get_cache);
3487 
3488 /*
3489  * We need to verify if the allocation against current->mm->owner's memcg is
3490  * possible for the given order. But the page is not allocated yet, so we'll
3491  * need a further commit step to do the final arrangements.
3492  *
3493  * It is possible for the task to switch cgroups in this mean time, so at
3494  * commit time, we can't rely on task conversion any longer.  We'll then use
3495  * the handle argument to return to the caller which cgroup we should commit
3496  * against. We could also return the memcg directly and avoid the pointer
3497  * passing, but a boolean return value gives better semantics considering
3498  * the compiled-out case as well.
3499  *
3500  * Returning true means the allocation is possible.
3501  */
3502 bool
3503 __memcg_kmem_newpage_charge(gfp_t gfp, struct mem_cgroup **_memcg, int order)
3504 {
3505 	struct mem_cgroup *memcg;
3506 	int ret;
3507 
3508 	*_memcg = NULL;
3509 	memcg = try_get_mem_cgroup_from_mm(current->mm);
3510 
3511 	/*
3512 	 * very rare case described in mem_cgroup_from_task. Unfortunately there
3513 	 * isn't much we can do without complicating this too much, and it would
3514 	 * be gfp-dependent anyway. Just let it go
3515 	 */
3516 	if (unlikely(!memcg))
3517 		return true;
3518 
3519 	if (!memcg_can_account_kmem(memcg)) {
3520 		css_put(&memcg->css);
3521 		return true;
3522 	}
3523 
3524 	ret = memcg_charge_kmem(memcg, gfp, PAGE_SIZE << order);
3525 	if (!ret)
3526 		*_memcg = memcg;
3527 
3528 	css_put(&memcg->css);
3529 	return (ret == 0);
3530 }
3531 
3532 void __memcg_kmem_commit_charge(struct page *page, struct mem_cgroup *memcg,
3533 			      int order)
3534 {
3535 	struct page_cgroup *pc;
3536 
3537 	VM_BUG_ON(mem_cgroup_is_root(memcg));
3538 
3539 	/* The page allocation failed. Revert */
3540 	if (!page) {
3541 		memcg_uncharge_kmem(memcg, PAGE_SIZE << order);
3542 		return;
3543 	}
3544 
3545 	pc = lookup_page_cgroup(page);
3546 	lock_page_cgroup(pc);
3547 	pc->mem_cgroup = memcg;
3548 	SetPageCgroupUsed(pc);
3549 	unlock_page_cgroup(pc);
3550 }
3551 
3552 void __memcg_kmem_uncharge_pages(struct page *page, int order)
3553 {
3554 	struct mem_cgroup *memcg = NULL;
3555 	struct page_cgroup *pc;
3556 
3557 
3558 	pc = lookup_page_cgroup(page);
3559 	/*
3560 	 * Fast unlocked return. Theoretically might have changed, have to
3561 	 * check again after locking.
3562 	 */
3563 	if (!PageCgroupUsed(pc))
3564 		return;
3565 
3566 	lock_page_cgroup(pc);
3567 	if (PageCgroupUsed(pc)) {
3568 		memcg = pc->mem_cgroup;
3569 		ClearPageCgroupUsed(pc);
3570 	}
3571 	unlock_page_cgroup(pc);
3572 
3573 	/*
3574 	 * We trust that only if there is a memcg associated with the page, it
3575 	 * is a valid allocation
3576 	 */
3577 	if (!memcg)
3578 		return;
3579 
3580 	VM_BUG_ON(mem_cgroup_is_root(memcg));
3581 	memcg_uncharge_kmem(memcg, PAGE_SIZE << order);
3582 }
3583 #else
3584 static inline void mem_cgroup_destroy_all_caches(struct mem_cgroup *memcg)
3585 {
3586 }
3587 #endif /* CONFIG_MEMCG_KMEM */
3588 
3589 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3590 
3591 #define PCGF_NOCOPY_AT_SPLIT (1 << PCG_LOCK | 1 << PCG_MIGRATION)
3592 /*
3593  * Because tail pages are not marked as "used", set it. We're under
3594  * zone->lru_lock, 'splitting on pmd' and compound_lock.
3595  * charge/uncharge will be never happen and move_account() is done under
3596  * compound_lock(), so we don't have to take care of races.
3597  */
3598 void mem_cgroup_split_huge_fixup(struct page *head)
3599 {
3600 	struct page_cgroup *head_pc = lookup_page_cgroup(head);
3601 	struct page_cgroup *pc;
3602 	int i;
3603 
3604 	if (mem_cgroup_disabled())
3605 		return;
3606 	for (i = 1; i < HPAGE_PMD_NR; i++) {
3607 		pc = head_pc + i;
3608 		pc->mem_cgroup = head_pc->mem_cgroup;
3609 		smp_wmb();/* see __commit_charge() */
3610 		pc->flags = head_pc->flags & ~PCGF_NOCOPY_AT_SPLIT;
3611 	}
3612 }
3613 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
3614 
3615 /**
3616  * mem_cgroup_move_account - move account of the page
3617  * @page: the page
3618  * @nr_pages: number of regular pages (>1 for huge pages)
3619  * @pc:	page_cgroup of the page.
3620  * @from: mem_cgroup which the page is moved from.
3621  * @to:	mem_cgroup which the page is moved to. @from != @to.
3622  *
3623  * The caller must confirm following.
3624  * - page is not on LRU (isolate_page() is useful.)
3625  * - compound_lock is held when nr_pages > 1
3626  *
3627  * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
3628  * from old cgroup.
3629  */
3630 static int mem_cgroup_move_account(struct page *page,
3631 				   unsigned int nr_pages,
3632 				   struct page_cgroup *pc,
3633 				   struct mem_cgroup *from,
3634 				   struct mem_cgroup *to)
3635 {
3636 	unsigned long flags;
3637 	int ret;
3638 	bool anon = PageAnon(page);
3639 
3640 	VM_BUG_ON(from == to);
3641 	VM_BUG_ON(PageLRU(page));
3642 	/*
3643 	 * The page is isolated from LRU. So, collapse function
3644 	 * will not handle this page. But page splitting can happen.
3645 	 * Do this check under compound_page_lock(). The caller should
3646 	 * hold it.
3647 	 */
3648 	ret = -EBUSY;
3649 	if (nr_pages > 1 && !PageTransHuge(page))
3650 		goto out;
3651 
3652 	lock_page_cgroup(pc);
3653 
3654 	ret = -EINVAL;
3655 	if (!PageCgroupUsed(pc) || pc->mem_cgroup != from)
3656 		goto unlock;
3657 
3658 	move_lock_mem_cgroup(from, &flags);
3659 
3660 	if (!anon && page_mapped(page)) {
3661 		/* Update mapped_file data for mem_cgroup */
3662 		preempt_disable();
3663 		__this_cpu_dec(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
3664 		__this_cpu_inc(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
3665 		preempt_enable();
3666 	}
3667 	mem_cgroup_charge_statistics(from, anon, -nr_pages);
3668 
3669 	/* caller should have done css_get */
3670 	pc->mem_cgroup = to;
3671 	mem_cgroup_charge_statistics(to, anon, nr_pages);
3672 	move_unlock_mem_cgroup(from, &flags);
3673 	ret = 0;
3674 unlock:
3675 	unlock_page_cgroup(pc);
3676 	/*
3677 	 * check events
3678 	 */
3679 	memcg_check_events(to, page);
3680 	memcg_check_events(from, page);
3681 out:
3682 	return ret;
3683 }
3684 
3685 /**
3686  * mem_cgroup_move_parent - moves page to the parent group
3687  * @page: the page to move
3688  * @pc: page_cgroup of the page
3689  * @child: page's cgroup
3690  *
3691  * move charges to its parent or the root cgroup if the group has no
3692  * parent (aka use_hierarchy==0).
3693  * Although this might fail (get_page_unless_zero, isolate_lru_page or
3694  * mem_cgroup_move_account fails) the failure is always temporary and
3695  * it signals a race with a page removal/uncharge or migration. In the
3696  * first case the page is on the way out and it will vanish from the LRU
3697  * on the next attempt and the call should be retried later.
3698  * Isolation from the LRU fails only if page has been isolated from
3699  * the LRU since we looked at it and that usually means either global
3700  * reclaim or migration going on. The page will either get back to the
3701  * LRU or vanish.
3702  * Finaly mem_cgroup_move_account fails only if the page got uncharged
3703  * (!PageCgroupUsed) or moved to a different group. The page will
3704  * disappear in the next attempt.
3705  */
3706 static int mem_cgroup_move_parent(struct page *page,
3707 				  struct page_cgroup *pc,
3708 				  struct mem_cgroup *child)
3709 {
3710 	struct mem_cgroup *parent;
3711 	unsigned int nr_pages;
3712 	unsigned long uninitialized_var(flags);
3713 	int ret;
3714 
3715 	VM_BUG_ON(mem_cgroup_is_root(child));
3716 
3717 	ret = -EBUSY;
3718 	if (!get_page_unless_zero(page))
3719 		goto out;
3720 	if (isolate_lru_page(page))
3721 		goto put;
3722 
3723 	nr_pages = hpage_nr_pages(page);
3724 
3725 	parent = parent_mem_cgroup(child);
3726 	/*
3727 	 * If no parent, move charges to root cgroup.
3728 	 */
3729 	if (!parent)
3730 		parent = root_mem_cgroup;
3731 
3732 	if (nr_pages > 1) {
3733 		VM_BUG_ON(!PageTransHuge(page));
3734 		flags = compound_lock_irqsave(page);
3735 	}
3736 
3737 	ret = mem_cgroup_move_account(page, nr_pages,
3738 				pc, child, parent);
3739 	if (!ret)
3740 		__mem_cgroup_cancel_local_charge(child, nr_pages);
3741 
3742 	if (nr_pages > 1)
3743 		compound_unlock_irqrestore(page, flags);
3744 	putback_lru_page(page);
3745 put:
3746 	put_page(page);
3747 out:
3748 	return ret;
3749 }
3750 
3751 /*
3752  * Charge the memory controller for page usage.
3753  * Return
3754  * 0 if the charge was successful
3755  * < 0 if the cgroup is over its limit
3756  */
3757 static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
3758 				gfp_t gfp_mask, enum charge_type ctype)
3759 {
3760 	struct mem_cgroup *memcg = NULL;
3761 	unsigned int nr_pages = 1;
3762 	bool oom = true;
3763 	int ret;
3764 
3765 	if (PageTransHuge(page)) {
3766 		nr_pages <<= compound_order(page);
3767 		VM_BUG_ON(!PageTransHuge(page));
3768 		/*
3769 		 * Never OOM-kill a process for a huge page.  The
3770 		 * fault handler will fall back to regular pages.
3771 		 */
3772 		oom = false;
3773 	}
3774 
3775 	ret = __mem_cgroup_try_charge(mm, gfp_mask, nr_pages, &memcg, oom);
3776 	if (ret == -ENOMEM)
3777 		return ret;
3778 	__mem_cgroup_commit_charge(memcg, page, nr_pages, ctype, false);
3779 	return 0;
3780 }
3781 
3782 int mem_cgroup_newpage_charge(struct page *page,
3783 			      struct mm_struct *mm, gfp_t gfp_mask)
3784 {
3785 	if (mem_cgroup_disabled())
3786 		return 0;
3787 	VM_BUG_ON(page_mapped(page));
3788 	VM_BUG_ON(page->mapping && !PageAnon(page));
3789 	VM_BUG_ON(!mm);
3790 	return mem_cgroup_charge_common(page, mm, gfp_mask,
3791 					MEM_CGROUP_CHARGE_TYPE_ANON);
3792 }
3793 
3794 /*
3795  * While swap-in, try_charge -> commit or cancel, the page is locked.
3796  * And when try_charge() successfully returns, one refcnt to memcg without
3797  * struct page_cgroup is acquired. This refcnt will be consumed by
3798  * "commit()" or removed by "cancel()"
3799  */
3800 static int __mem_cgroup_try_charge_swapin(struct mm_struct *mm,
3801 					  struct page *page,
3802 					  gfp_t mask,
3803 					  struct mem_cgroup **memcgp)
3804 {
3805 	struct mem_cgroup *memcg;
3806 	struct page_cgroup *pc;
3807 	int ret;
3808 
3809 	pc = lookup_page_cgroup(page);
3810 	/*
3811 	 * Every swap fault against a single page tries to charge the
3812 	 * page, bail as early as possible.  shmem_unuse() encounters
3813 	 * already charged pages, too.  The USED bit is protected by
3814 	 * the page lock, which serializes swap cache removal, which
3815 	 * in turn serializes uncharging.
3816 	 */
3817 	if (PageCgroupUsed(pc))
3818 		return 0;
3819 	if (!do_swap_account)
3820 		goto charge_cur_mm;
3821 	memcg = try_get_mem_cgroup_from_page(page);
3822 	if (!memcg)
3823 		goto charge_cur_mm;
3824 	*memcgp = memcg;
3825 	ret = __mem_cgroup_try_charge(NULL, mask, 1, memcgp, true);
3826 	css_put(&memcg->css);
3827 	if (ret == -EINTR)
3828 		ret = 0;
3829 	return ret;
3830 charge_cur_mm:
3831 	ret = __mem_cgroup_try_charge(mm, mask, 1, memcgp, true);
3832 	if (ret == -EINTR)
3833 		ret = 0;
3834 	return ret;
3835 }
3836 
3837 int mem_cgroup_try_charge_swapin(struct mm_struct *mm, struct page *page,
3838 				 gfp_t gfp_mask, struct mem_cgroup **memcgp)
3839 {
3840 	*memcgp = NULL;
3841 	if (mem_cgroup_disabled())
3842 		return 0;
3843 	/*
3844 	 * A racing thread's fault, or swapoff, may have already
3845 	 * updated the pte, and even removed page from swap cache: in
3846 	 * those cases unuse_pte()'s pte_same() test will fail; but
3847 	 * there's also a KSM case which does need to charge the page.
3848 	 */
3849 	if (!PageSwapCache(page)) {
3850 		int ret;
3851 
3852 		ret = __mem_cgroup_try_charge(mm, gfp_mask, 1, memcgp, true);
3853 		if (ret == -EINTR)
3854 			ret = 0;
3855 		return ret;
3856 	}
3857 	return __mem_cgroup_try_charge_swapin(mm, page, gfp_mask, memcgp);
3858 }
3859 
3860 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *memcg)
3861 {
3862 	if (mem_cgroup_disabled())
3863 		return;
3864 	if (!memcg)
3865 		return;
3866 	__mem_cgroup_cancel_charge(memcg, 1);
3867 }
3868 
3869 static void
3870 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *memcg,
3871 					enum charge_type ctype)
3872 {
3873 	if (mem_cgroup_disabled())
3874 		return;
3875 	if (!memcg)
3876 		return;
3877 
3878 	__mem_cgroup_commit_charge(memcg, page, 1, ctype, true);
3879 	/*
3880 	 * Now swap is on-memory. This means this page may be
3881 	 * counted both as mem and swap....double count.
3882 	 * Fix it by uncharging from memsw. Basically, this SwapCache is stable
3883 	 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
3884 	 * may call delete_from_swap_cache() before reach here.
3885 	 */
3886 	if (do_swap_account && PageSwapCache(page)) {
3887 		swp_entry_t ent = {.val = page_private(page)};
3888 		mem_cgroup_uncharge_swap(ent);
3889 	}
3890 }
3891 
3892 void mem_cgroup_commit_charge_swapin(struct page *page,
3893 				     struct mem_cgroup *memcg)
3894 {
3895 	__mem_cgroup_commit_charge_swapin(page, memcg,
3896 					  MEM_CGROUP_CHARGE_TYPE_ANON);
3897 }
3898 
3899 int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
3900 				gfp_t gfp_mask)
3901 {
3902 	struct mem_cgroup *memcg = NULL;
3903 	enum charge_type type = MEM_CGROUP_CHARGE_TYPE_CACHE;
3904 	int ret;
3905 
3906 	if (mem_cgroup_disabled())
3907 		return 0;
3908 	if (PageCompound(page))
3909 		return 0;
3910 
3911 	if (!PageSwapCache(page))
3912 		ret = mem_cgroup_charge_common(page, mm, gfp_mask, type);
3913 	else { /* page is swapcache/shmem */
3914 		ret = __mem_cgroup_try_charge_swapin(mm, page,
3915 						     gfp_mask, &memcg);
3916 		if (!ret)
3917 			__mem_cgroup_commit_charge_swapin(page, memcg, type);
3918 	}
3919 	return ret;
3920 }
3921 
3922 static void mem_cgroup_do_uncharge(struct mem_cgroup *memcg,
3923 				   unsigned int nr_pages,
3924 				   const enum charge_type ctype)
3925 {
3926 	struct memcg_batch_info *batch = NULL;
3927 	bool uncharge_memsw = true;
3928 
3929 	/* If swapout, usage of swap doesn't decrease */
3930 	if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
3931 		uncharge_memsw = false;
3932 
3933 	batch = &current->memcg_batch;
3934 	/*
3935 	 * In usual, we do css_get() when we remember memcg pointer.
3936 	 * But in this case, we keep res->usage until end of a series of
3937 	 * uncharges. Then, it's ok to ignore memcg's refcnt.
3938 	 */
3939 	if (!batch->memcg)
3940 		batch->memcg = memcg;
3941 	/*
3942 	 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
3943 	 * In those cases, all pages freed continuously can be expected to be in
3944 	 * the same cgroup and we have chance to coalesce uncharges.
3945 	 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
3946 	 * because we want to do uncharge as soon as possible.
3947 	 */
3948 
3949 	if (!batch->do_batch || test_thread_flag(TIF_MEMDIE))
3950 		goto direct_uncharge;
3951 
3952 	if (nr_pages > 1)
3953 		goto direct_uncharge;
3954 
3955 	/*
3956 	 * In typical case, batch->memcg == mem. This means we can
3957 	 * merge a series of uncharges to an uncharge of res_counter.
3958 	 * If not, we uncharge res_counter ony by one.
3959 	 */
3960 	if (batch->memcg != memcg)
3961 		goto direct_uncharge;
3962 	/* remember freed charge and uncharge it later */
3963 	batch->nr_pages++;
3964 	if (uncharge_memsw)
3965 		batch->memsw_nr_pages++;
3966 	return;
3967 direct_uncharge:
3968 	res_counter_uncharge(&memcg->res, nr_pages * PAGE_SIZE);
3969 	if (uncharge_memsw)
3970 		res_counter_uncharge(&memcg->memsw, nr_pages * PAGE_SIZE);
3971 	if (unlikely(batch->memcg != memcg))
3972 		memcg_oom_recover(memcg);
3973 }
3974 
3975 /*
3976  * uncharge if !page_mapped(page)
3977  */
3978 static struct mem_cgroup *
3979 __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype,
3980 			     bool end_migration)
3981 {
3982 	struct mem_cgroup *memcg = NULL;
3983 	unsigned int nr_pages = 1;
3984 	struct page_cgroup *pc;
3985 	bool anon;
3986 
3987 	if (mem_cgroup_disabled())
3988 		return NULL;
3989 
3990 	VM_BUG_ON(PageSwapCache(page));
3991 
3992 	if (PageTransHuge(page)) {
3993 		nr_pages <<= compound_order(page);
3994 		VM_BUG_ON(!PageTransHuge(page));
3995 	}
3996 	/*
3997 	 * Check if our page_cgroup is valid
3998 	 */
3999 	pc = lookup_page_cgroup(page);
4000 	if (unlikely(!PageCgroupUsed(pc)))
4001 		return NULL;
4002 
4003 	lock_page_cgroup(pc);
4004 
4005 	memcg = pc->mem_cgroup;
4006 
4007 	if (!PageCgroupUsed(pc))
4008 		goto unlock_out;
4009 
4010 	anon = PageAnon(page);
4011 
4012 	switch (ctype) {
4013 	case MEM_CGROUP_CHARGE_TYPE_ANON:
4014 		/*
4015 		 * Generally PageAnon tells if it's the anon statistics to be
4016 		 * updated; but sometimes e.g. mem_cgroup_uncharge_page() is
4017 		 * used before page reached the stage of being marked PageAnon.
4018 		 */
4019 		anon = true;
4020 		/* fallthrough */
4021 	case MEM_CGROUP_CHARGE_TYPE_DROP:
4022 		/* See mem_cgroup_prepare_migration() */
4023 		if (page_mapped(page))
4024 			goto unlock_out;
4025 		/*
4026 		 * Pages under migration may not be uncharged.  But
4027 		 * end_migration() /must/ be the one uncharging the
4028 		 * unused post-migration page and so it has to call
4029 		 * here with the migration bit still set.  See the
4030 		 * res_counter handling below.
4031 		 */
4032 		if (!end_migration && PageCgroupMigration(pc))
4033 			goto unlock_out;
4034 		break;
4035 	case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
4036 		if (!PageAnon(page)) {	/* Shared memory */
4037 			if (page->mapping && !page_is_file_cache(page))
4038 				goto unlock_out;
4039 		} else if (page_mapped(page)) /* Anon */
4040 				goto unlock_out;
4041 		break;
4042 	default:
4043 		break;
4044 	}
4045 
4046 	mem_cgroup_charge_statistics(memcg, anon, -nr_pages);
4047 
4048 	ClearPageCgroupUsed(pc);
4049 	/*
4050 	 * pc->mem_cgroup is not cleared here. It will be accessed when it's
4051 	 * freed from LRU. This is safe because uncharged page is expected not
4052 	 * to be reused (freed soon). Exception is SwapCache, it's handled by
4053 	 * special functions.
4054 	 */
4055 
4056 	unlock_page_cgroup(pc);
4057 	/*
4058 	 * even after unlock, we have memcg->res.usage here and this memcg
4059 	 * will never be freed.
4060 	 */
4061 	memcg_check_events(memcg, page);
4062 	if (do_swap_account && ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT) {
4063 		mem_cgroup_swap_statistics(memcg, true);
4064 		mem_cgroup_get(memcg);
4065 	}
4066 	/*
4067 	 * Migration does not charge the res_counter for the
4068 	 * replacement page, so leave it alone when phasing out the
4069 	 * page that is unused after the migration.
4070 	 */
4071 	if (!end_migration && !mem_cgroup_is_root(memcg))
4072 		mem_cgroup_do_uncharge(memcg, nr_pages, ctype);
4073 
4074 	return memcg;
4075 
4076 unlock_out:
4077 	unlock_page_cgroup(pc);
4078 	return NULL;
4079 }
4080 
4081 void mem_cgroup_uncharge_page(struct page *page)
4082 {
4083 	/* early check. */
4084 	if (page_mapped(page))
4085 		return;
4086 	VM_BUG_ON(page->mapping && !PageAnon(page));
4087 	if (PageSwapCache(page))
4088 		return;
4089 	__mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_ANON, false);
4090 }
4091 
4092 void mem_cgroup_uncharge_cache_page(struct page *page)
4093 {
4094 	VM_BUG_ON(page_mapped(page));
4095 	VM_BUG_ON(page->mapping);
4096 	__mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE, false);
4097 }
4098 
4099 /*
4100  * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
4101  * In that cases, pages are freed continuously and we can expect pages
4102  * are in the same memcg. All these calls itself limits the number of
4103  * pages freed at once, then uncharge_start/end() is called properly.
4104  * This may be called prural(2) times in a context,
4105  */
4106 
4107 void mem_cgroup_uncharge_start(void)
4108 {
4109 	current->memcg_batch.do_batch++;
4110 	/* We can do nest. */
4111 	if (current->memcg_batch.do_batch == 1) {
4112 		current->memcg_batch.memcg = NULL;
4113 		current->memcg_batch.nr_pages = 0;
4114 		current->memcg_batch.memsw_nr_pages = 0;
4115 	}
4116 }
4117 
4118 void mem_cgroup_uncharge_end(void)
4119 {
4120 	struct memcg_batch_info *batch = &current->memcg_batch;
4121 
4122 	if (!batch->do_batch)
4123 		return;
4124 
4125 	batch->do_batch--;
4126 	if (batch->do_batch) /* If stacked, do nothing. */
4127 		return;
4128 
4129 	if (!batch->memcg)
4130 		return;
4131 	/*
4132 	 * This "batch->memcg" is valid without any css_get/put etc...
4133 	 * bacause we hide charges behind us.
4134 	 */
4135 	if (batch->nr_pages)
4136 		res_counter_uncharge(&batch->memcg->res,
4137 				     batch->nr_pages * PAGE_SIZE);
4138 	if (batch->memsw_nr_pages)
4139 		res_counter_uncharge(&batch->memcg->memsw,
4140 				     batch->memsw_nr_pages * PAGE_SIZE);
4141 	memcg_oom_recover(batch->memcg);
4142 	/* forget this pointer (for sanity check) */
4143 	batch->memcg = NULL;
4144 }
4145 
4146 #ifdef CONFIG_SWAP
4147 /*
4148  * called after __delete_from_swap_cache() and drop "page" account.
4149  * memcg information is recorded to swap_cgroup of "ent"
4150  */
4151 void
4152 mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
4153 {
4154 	struct mem_cgroup *memcg;
4155 	int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
4156 
4157 	if (!swapout) /* this was a swap cache but the swap is unused ! */
4158 		ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
4159 
4160 	memcg = __mem_cgroup_uncharge_common(page, ctype, false);
4161 
4162 	/*
4163 	 * record memcg information,  if swapout && memcg != NULL,
4164 	 * mem_cgroup_get() was called in uncharge().
4165 	 */
4166 	if (do_swap_account && swapout && memcg)
4167 		swap_cgroup_record(ent, css_id(&memcg->css));
4168 }
4169 #endif
4170 
4171 #ifdef CONFIG_MEMCG_SWAP
4172 /*
4173  * called from swap_entry_free(). remove record in swap_cgroup and
4174  * uncharge "memsw" account.
4175  */
4176 void mem_cgroup_uncharge_swap(swp_entry_t ent)
4177 {
4178 	struct mem_cgroup *memcg;
4179 	unsigned short id;
4180 
4181 	if (!do_swap_account)
4182 		return;
4183 
4184 	id = swap_cgroup_record(ent, 0);
4185 	rcu_read_lock();
4186 	memcg = mem_cgroup_lookup(id);
4187 	if (memcg) {
4188 		/*
4189 		 * We uncharge this because swap is freed.
4190 		 * This memcg can be obsolete one. We avoid calling css_tryget
4191 		 */
4192 		if (!mem_cgroup_is_root(memcg))
4193 			res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
4194 		mem_cgroup_swap_statistics(memcg, false);
4195 		mem_cgroup_put(memcg);
4196 	}
4197 	rcu_read_unlock();
4198 }
4199 
4200 /**
4201  * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
4202  * @entry: swap entry to be moved
4203  * @from:  mem_cgroup which the entry is moved from
4204  * @to:  mem_cgroup which the entry is moved to
4205  *
4206  * It succeeds only when the swap_cgroup's record for this entry is the same
4207  * as the mem_cgroup's id of @from.
4208  *
4209  * Returns 0 on success, -EINVAL on failure.
4210  *
4211  * The caller must have charged to @to, IOW, called res_counter_charge() about
4212  * both res and memsw, and called css_get().
4213  */
4214 static int mem_cgroup_move_swap_account(swp_entry_t entry,
4215 				struct mem_cgroup *from, struct mem_cgroup *to)
4216 {
4217 	unsigned short old_id, new_id;
4218 
4219 	old_id = css_id(&from->css);
4220 	new_id = css_id(&to->css);
4221 
4222 	if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
4223 		mem_cgroup_swap_statistics(from, false);
4224 		mem_cgroup_swap_statistics(to, true);
4225 		/*
4226 		 * This function is only called from task migration context now.
4227 		 * It postpones res_counter and refcount handling till the end
4228 		 * of task migration(mem_cgroup_clear_mc()) for performance
4229 		 * improvement. But we cannot postpone mem_cgroup_get(to)
4230 		 * because if the process that has been moved to @to does
4231 		 * swap-in, the refcount of @to might be decreased to 0.
4232 		 */
4233 		mem_cgroup_get(to);
4234 		return 0;
4235 	}
4236 	return -EINVAL;
4237 }
4238 #else
4239 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
4240 				struct mem_cgroup *from, struct mem_cgroup *to)
4241 {
4242 	return -EINVAL;
4243 }
4244 #endif
4245 
4246 /*
4247  * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
4248  * page belongs to.
4249  */
4250 void mem_cgroup_prepare_migration(struct page *page, struct page *newpage,
4251 				  struct mem_cgroup **memcgp)
4252 {
4253 	struct mem_cgroup *memcg = NULL;
4254 	unsigned int nr_pages = 1;
4255 	struct page_cgroup *pc;
4256 	enum charge_type ctype;
4257 
4258 	*memcgp = NULL;
4259 
4260 	if (mem_cgroup_disabled())
4261 		return;
4262 
4263 	if (PageTransHuge(page))
4264 		nr_pages <<= compound_order(page);
4265 
4266 	pc = lookup_page_cgroup(page);
4267 	lock_page_cgroup(pc);
4268 	if (PageCgroupUsed(pc)) {
4269 		memcg = pc->mem_cgroup;
4270 		css_get(&memcg->css);
4271 		/*
4272 		 * At migrating an anonymous page, its mapcount goes down
4273 		 * to 0 and uncharge() will be called. But, even if it's fully
4274 		 * unmapped, migration may fail and this page has to be
4275 		 * charged again. We set MIGRATION flag here and delay uncharge
4276 		 * until end_migration() is called
4277 		 *
4278 		 * Corner Case Thinking
4279 		 * A)
4280 		 * When the old page was mapped as Anon and it's unmap-and-freed
4281 		 * while migration was ongoing.
4282 		 * If unmap finds the old page, uncharge() of it will be delayed
4283 		 * until end_migration(). If unmap finds a new page, it's
4284 		 * uncharged when it make mapcount to be 1->0. If unmap code
4285 		 * finds swap_migration_entry, the new page will not be mapped
4286 		 * and end_migration() will find it(mapcount==0).
4287 		 *
4288 		 * B)
4289 		 * When the old page was mapped but migraion fails, the kernel
4290 		 * remaps it. A charge for it is kept by MIGRATION flag even
4291 		 * if mapcount goes down to 0. We can do remap successfully
4292 		 * without charging it again.
4293 		 *
4294 		 * C)
4295 		 * The "old" page is under lock_page() until the end of
4296 		 * migration, so, the old page itself will not be swapped-out.
4297 		 * If the new page is swapped out before end_migraton, our
4298 		 * hook to usual swap-out path will catch the event.
4299 		 */
4300 		if (PageAnon(page))
4301 			SetPageCgroupMigration(pc);
4302 	}
4303 	unlock_page_cgroup(pc);
4304 	/*
4305 	 * If the page is not charged at this point,
4306 	 * we return here.
4307 	 */
4308 	if (!memcg)
4309 		return;
4310 
4311 	*memcgp = memcg;
4312 	/*
4313 	 * We charge new page before it's used/mapped. So, even if unlock_page()
4314 	 * is called before end_migration, we can catch all events on this new
4315 	 * page. In the case new page is migrated but not remapped, new page's
4316 	 * mapcount will be finally 0 and we call uncharge in end_migration().
4317 	 */
4318 	if (PageAnon(page))
4319 		ctype = MEM_CGROUP_CHARGE_TYPE_ANON;
4320 	else
4321 		ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
4322 	/*
4323 	 * The page is committed to the memcg, but it's not actually
4324 	 * charged to the res_counter since we plan on replacing the
4325 	 * old one and only one page is going to be left afterwards.
4326 	 */
4327 	__mem_cgroup_commit_charge(memcg, newpage, nr_pages, ctype, false);
4328 }
4329 
4330 /* remove redundant charge if migration failed*/
4331 void mem_cgroup_end_migration(struct mem_cgroup *memcg,
4332 	struct page *oldpage, struct page *newpage, bool migration_ok)
4333 {
4334 	struct page *used, *unused;
4335 	struct page_cgroup *pc;
4336 	bool anon;
4337 
4338 	if (!memcg)
4339 		return;
4340 
4341 	if (!migration_ok) {
4342 		used = oldpage;
4343 		unused = newpage;
4344 	} else {
4345 		used = newpage;
4346 		unused = oldpage;
4347 	}
4348 	anon = PageAnon(used);
4349 	__mem_cgroup_uncharge_common(unused,
4350 				     anon ? MEM_CGROUP_CHARGE_TYPE_ANON
4351 				     : MEM_CGROUP_CHARGE_TYPE_CACHE,
4352 				     true);
4353 	css_put(&memcg->css);
4354 	/*
4355 	 * We disallowed uncharge of pages under migration because mapcount
4356 	 * of the page goes down to zero, temporarly.
4357 	 * Clear the flag and check the page should be charged.
4358 	 */
4359 	pc = lookup_page_cgroup(oldpage);
4360 	lock_page_cgroup(pc);
4361 	ClearPageCgroupMigration(pc);
4362 	unlock_page_cgroup(pc);
4363 
4364 	/*
4365 	 * If a page is a file cache, radix-tree replacement is very atomic
4366 	 * and we can skip this check. When it was an Anon page, its mapcount
4367 	 * goes down to 0. But because we added MIGRATION flage, it's not
4368 	 * uncharged yet. There are several case but page->mapcount check
4369 	 * and USED bit check in mem_cgroup_uncharge_page() will do enough
4370 	 * check. (see prepare_charge() also)
4371 	 */
4372 	if (anon)
4373 		mem_cgroup_uncharge_page(used);
4374 }
4375 
4376 /*
4377  * At replace page cache, newpage is not under any memcg but it's on
4378  * LRU. So, this function doesn't touch res_counter but handles LRU
4379  * in correct way. Both pages are locked so we cannot race with uncharge.
4380  */
4381 void mem_cgroup_replace_page_cache(struct page *oldpage,
4382 				  struct page *newpage)
4383 {
4384 	struct mem_cgroup *memcg = NULL;
4385 	struct page_cgroup *pc;
4386 	enum charge_type type = MEM_CGROUP_CHARGE_TYPE_CACHE;
4387 
4388 	if (mem_cgroup_disabled())
4389 		return;
4390 
4391 	pc = lookup_page_cgroup(oldpage);
4392 	/* fix accounting on old pages */
4393 	lock_page_cgroup(pc);
4394 	if (PageCgroupUsed(pc)) {
4395 		memcg = pc->mem_cgroup;
4396 		mem_cgroup_charge_statistics(memcg, false, -1);
4397 		ClearPageCgroupUsed(pc);
4398 	}
4399 	unlock_page_cgroup(pc);
4400 
4401 	/*
4402 	 * When called from shmem_replace_page(), in some cases the
4403 	 * oldpage has already been charged, and in some cases not.
4404 	 */
4405 	if (!memcg)
4406 		return;
4407 	/*
4408 	 * Even if newpage->mapping was NULL before starting replacement,
4409 	 * the newpage may be on LRU(or pagevec for LRU) already. We lock
4410 	 * LRU while we overwrite pc->mem_cgroup.
4411 	 */
4412 	__mem_cgroup_commit_charge(memcg, newpage, 1, type, true);
4413 }
4414 
4415 #ifdef CONFIG_DEBUG_VM
4416 static struct page_cgroup *lookup_page_cgroup_used(struct page *page)
4417 {
4418 	struct page_cgroup *pc;
4419 
4420 	pc = lookup_page_cgroup(page);
4421 	/*
4422 	 * Can be NULL while feeding pages into the page allocator for
4423 	 * the first time, i.e. during boot or memory hotplug;
4424 	 * or when mem_cgroup_disabled().
4425 	 */
4426 	if (likely(pc) && PageCgroupUsed(pc))
4427 		return pc;
4428 	return NULL;
4429 }
4430 
4431 bool mem_cgroup_bad_page_check(struct page *page)
4432 {
4433 	if (mem_cgroup_disabled())
4434 		return false;
4435 
4436 	return lookup_page_cgroup_used(page) != NULL;
4437 }
4438 
4439 void mem_cgroup_print_bad_page(struct page *page)
4440 {
4441 	struct page_cgroup *pc;
4442 
4443 	pc = lookup_page_cgroup_used(page);
4444 	if (pc) {
4445 		pr_alert("pc:%p pc->flags:%lx pc->mem_cgroup:%p\n",
4446 			 pc, pc->flags, pc->mem_cgroup);
4447 	}
4448 }
4449 #endif
4450 
4451 static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
4452 				unsigned long long val)
4453 {
4454 	int retry_count;
4455 	u64 memswlimit, memlimit;
4456 	int ret = 0;
4457 	int children = mem_cgroup_count_children(memcg);
4458 	u64 curusage, oldusage;
4459 	int enlarge;
4460 
4461 	/*
4462 	 * For keeping hierarchical_reclaim simple, how long we should retry
4463 	 * is depends on callers. We set our retry-count to be function
4464 	 * of # of children which we should visit in this loop.
4465 	 */
4466 	retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
4467 
4468 	oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
4469 
4470 	enlarge = 0;
4471 	while (retry_count) {
4472 		if (signal_pending(current)) {
4473 			ret = -EINTR;
4474 			break;
4475 		}
4476 		/*
4477 		 * Rather than hide all in some function, I do this in
4478 		 * open coded manner. You see what this really does.
4479 		 * We have to guarantee memcg->res.limit <= memcg->memsw.limit.
4480 		 */
4481 		mutex_lock(&set_limit_mutex);
4482 		memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
4483 		if (memswlimit < val) {
4484 			ret = -EINVAL;
4485 			mutex_unlock(&set_limit_mutex);
4486 			break;
4487 		}
4488 
4489 		memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
4490 		if (memlimit < val)
4491 			enlarge = 1;
4492 
4493 		ret = res_counter_set_limit(&memcg->res, val);
4494 		if (!ret) {
4495 			if (memswlimit == val)
4496 				memcg->memsw_is_minimum = true;
4497 			else
4498 				memcg->memsw_is_minimum = false;
4499 		}
4500 		mutex_unlock(&set_limit_mutex);
4501 
4502 		if (!ret)
4503 			break;
4504 
4505 		mem_cgroup_reclaim(memcg, GFP_KERNEL,
4506 				   MEM_CGROUP_RECLAIM_SHRINK);
4507 		curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
4508 		/* Usage is reduced ? */
4509   		if (curusage >= oldusage)
4510 			retry_count--;
4511 		else
4512 			oldusage = curusage;
4513 	}
4514 	if (!ret && enlarge)
4515 		memcg_oom_recover(memcg);
4516 
4517 	return ret;
4518 }
4519 
4520 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
4521 					unsigned long long val)
4522 {
4523 	int retry_count;
4524 	u64 memlimit, memswlimit, oldusage, curusage;
4525 	int children = mem_cgroup_count_children(memcg);
4526 	int ret = -EBUSY;
4527 	int enlarge = 0;
4528 
4529 	/* see mem_cgroup_resize_res_limit */
4530  	retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
4531 	oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
4532 	while (retry_count) {
4533 		if (signal_pending(current)) {
4534 			ret = -EINTR;
4535 			break;
4536 		}
4537 		/*
4538 		 * Rather than hide all in some function, I do this in
4539 		 * open coded manner. You see what this really does.
4540 		 * We have to guarantee memcg->res.limit <= memcg->memsw.limit.
4541 		 */
4542 		mutex_lock(&set_limit_mutex);
4543 		memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
4544 		if (memlimit > val) {
4545 			ret = -EINVAL;
4546 			mutex_unlock(&set_limit_mutex);
4547 			break;
4548 		}
4549 		memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
4550 		if (memswlimit < val)
4551 			enlarge = 1;
4552 		ret = res_counter_set_limit(&memcg->memsw, val);
4553 		if (!ret) {
4554 			if (memlimit == val)
4555 				memcg->memsw_is_minimum = true;
4556 			else
4557 				memcg->memsw_is_minimum = false;
4558 		}
4559 		mutex_unlock(&set_limit_mutex);
4560 
4561 		if (!ret)
4562 			break;
4563 
4564 		mem_cgroup_reclaim(memcg, GFP_KERNEL,
4565 				   MEM_CGROUP_RECLAIM_NOSWAP |
4566 				   MEM_CGROUP_RECLAIM_SHRINK);
4567 		curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
4568 		/* Usage is reduced ? */
4569 		if (curusage >= oldusage)
4570 			retry_count--;
4571 		else
4572 			oldusage = curusage;
4573 	}
4574 	if (!ret && enlarge)
4575 		memcg_oom_recover(memcg);
4576 	return ret;
4577 }
4578 
4579 unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
4580 					    gfp_t gfp_mask,
4581 					    unsigned long *total_scanned)
4582 {
4583 	unsigned long nr_reclaimed = 0;
4584 	struct mem_cgroup_per_zone *mz, *next_mz = NULL;
4585 	unsigned long reclaimed;
4586 	int loop = 0;
4587 	struct mem_cgroup_tree_per_zone *mctz;
4588 	unsigned long long excess;
4589 	unsigned long nr_scanned;
4590 
4591 	if (order > 0)
4592 		return 0;
4593 
4594 	mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone));
4595 	/*
4596 	 * This loop can run a while, specially if mem_cgroup's continuously
4597 	 * keep exceeding their soft limit and putting the system under
4598 	 * pressure
4599 	 */
4600 	do {
4601 		if (next_mz)
4602 			mz = next_mz;
4603 		else
4604 			mz = mem_cgroup_largest_soft_limit_node(mctz);
4605 		if (!mz)
4606 			break;
4607 
4608 		nr_scanned = 0;
4609 		reclaimed = mem_cgroup_soft_reclaim(mz->memcg, zone,
4610 						    gfp_mask, &nr_scanned);
4611 		nr_reclaimed += reclaimed;
4612 		*total_scanned += nr_scanned;
4613 		spin_lock(&mctz->lock);
4614 
4615 		/*
4616 		 * If we failed to reclaim anything from this memory cgroup
4617 		 * it is time to move on to the next cgroup
4618 		 */
4619 		next_mz = NULL;
4620 		if (!reclaimed) {
4621 			do {
4622 				/*
4623 				 * Loop until we find yet another one.
4624 				 *
4625 				 * By the time we get the soft_limit lock
4626 				 * again, someone might have aded the
4627 				 * group back on the RB tree. Iterate to
4628 				 * make sure we get a different mem.
4629 				 * mem_cgroup_largest_soft_limit_node returns
4630 				 * NULL if no other cgroup is present on
4631 				 * the tree
4632 				 */
4633 				next_mz =
4634 				__mem_cgroup_largest_soft_limit_node(mctz);
4635 				if (next_mz == mz)
4636 					css_put(&next_mz->memcg->css);
4637 				else /* next_mz == NULL or other memcg */
4638 					break;
4639 			} while (1);
4640 		}
4641 		__mem_cgroup_remove_exceeded(mz->memcg, mz, mctz);
4642 		excess = res_counter_soft_limit_excess(&mz->memcg->res);
4643 		/*
4644 		 * One school of thought says that we should not add
4645 		 * back the node to the tree if reclaim returns 0.
4646 		 * But our reclaim could return 0, simply because due
4647 		 * to priority we are exposing a smaller subset of
4648 		 * memory to reclaim from. Consider this as a longer
4649 		 * term TODO.
4650 		 */
4651 		/* If excess == 0, no tree ops */
4652 		__mem_cgroup_insert_exceeded(mz->memcg, mz, mctz, excess);
4653 		spin_unlock(&mctz->lock);
4654 		css_put(&mz->memcg->css);
4655 		loop++;
4656 		/*
4657 		 * Could not reclaim anything and there are no more
4658 		 * mem cgroups to try or we seem to be looping without
4659 		 * reclaiming anything.
4660 		 */
4661 		if (!nr_reclaimed &&
4662 			(next_mz == NULL ||
4663 			loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
4664 			break;
4665 	} while (!nr_reclaimed);
4666 	if (next_mz)
4667 		css_put(&next_mz->memcg->css);
4668 	return nr_reclaimed;
4669 }
4670 
4671 /**
4672  * mem_cgroup_force_empty_list - clears LRU of a group
4673  * @memcg: group to clear
4674  * @node: NUMA node
4675  * @zid: zone id
4676  * @lru: lru to to clear
4677  *
4678  * Traverse a specified page_cgroup list and try to drop them all.  This doesn't
4679  * reclaim the pages page themselves - pages are moved to the parent (or root)
4680  * group.
4681  */
4682 static void mem_cgroup_force_empty_list(struct mem_cgroup *memcg,
4683 				int node, int zid, enum lru_list lru)
4684 {
4685 	struct lruvec *lruvec;
4686 	unsigned long flags;
4687 	struct list_head *list;
4688 	struct page *busy;
4689 	struct zone *zone;
4690 
4691 	zone = &NODE_DATA(node)->node_zones[zid];
4692 	lruvec = mem_cgroup_zone_lruvec(zone, memcg);
4693 	list = &lruvec->lists[lru];
4694 
4695 	busy = NULL;
4696 	do {
4697 		struct page_cgroup *pc;
4698 		struct page *page;
4699 
4700 		spin_lock_irqsave(&zone->lru_lock, flags);
4701 		if (list_empty(list)) {
4702 			spin_unlock_irqrestore(&zone->lru_lock, flags);
4703 			break;
4704 		}
4705 		page = list_entry(list->prev, struct page, lru);
4706 		if (busy == page) {
4707 			list_move(&page->lru, list);
4708 			busy = NULL;
4709 			spin_unlock_irqrestore(&zone->lru_lock, flags);
4710 			continue;
4711 		}
4712 		spin_unlock_irqrestore(&zone->lru_lock, flags);
4713 
4714 		pc = lookup_page_cgroup(page);
4715 
4716 		if (mem_cgroup_move_parent(page, pc, memcg)) {
4717 			/* found lock contention or "pc" is obsolete. */
4718 			busy = page;
4719 			cond_resched();
4720 		} else
4721 			busy = NULL;
4722 	} while (!list_empty(list));
4723 }
4724 
4725 /*
4726  * make mem_cgroup's charge to be 0 if there is no task by moving
4727  * all the charges and pages to the parent.
4728  * This enables deleting this mem_cgroup.
4729  *
4730  * Caller is responsible for holding css reference on the memcg.
4731  */
4732 static void mem_cgroup_reparent_charges(struct mem_cgroup *memcg)
4733 {
4734 	int node, zid;
4735 	u64 usage;
4736 
4737 	do {
4738 		/* This is for making all *used* pages to be on LRU. */
4739 		lru_add_drain_all();
4740 		drain_all_stock_sync(memcg);
4741 		mem_cgroup_start_move(memcg);
4742 		for_each_node_state(node, N_MEMORY) {
4743 			for (zid = 0; zid < MAX_NR_ZONES; zid++) {
4744 				enum lru_list lru;
4745 				for_each_lru(lru) {
4746 					mem_cgroup_force_empty_list(memcg,
4747 							node, zid, lru);
4748 				}
4749 			}
4750 		}
4751 		mem_cgroup_end_move(memcg);
4752 		memcg_oom_recover(memcg);
4753 		cond_resched();
4754 
4755 		/*
4756 		 * Kernel memory may not necessarily be trackable to a specific
4757 		 * process. So they are not migrated, and therefore we can't
4758 		 * expect their value to drop to 0 here.
4759 		 * Having res filled up with kmem only is enough.
4760 		 *
4761 		 * This is a safety check because mem_cgroup_force_empty_list
4762 		 * could have raced with mem_cgroup_replace_page_cache callers
4763 		 * so the lru seemed empty but the page could have been added
4764 		 * right after the check. RES_USAGE should be safe as we always
4765 		 * charge before adding to the LRU.
4766 		 */
4767 		usage = res_counter_read_u64(&memcg->res, RES_USAGE) -
4768 			res_counter_read_u64(&memcg->kmem, RES_USAGE);
4769 	} while (usage > 0);
4770 }
4771 
4772 /*
4773  * This mainly exists for tests during the setting of set of use_hierarchy.
4774  * Since this is the very setting we are changing, the current hierarchy value
4775  * is meaningless
4776  */
4777 static inline bool __memcg_has_children(struct mem_cgroup *memcg)
4778 {
4779 	struct cgroup *pos;
4780 
4781 	/* bounce at first found */
4782 	cgroup_for_each_child(pos, memcg->css.cgroup)
4783 		return true;
4784 	return false;
4785 }
4786 
4787 /*
4788  * Must be called with memcg_create_mutex held, unless the cgroup is guaranteed
4789  * to be already dead (as in mem_cgroup_force_empty, for instance).  This is
4790  * from mem_cgroup_count_children(), in the sense that we don't really care how
4791  * many children we have; we only need to know if we have any.  It also counts
4792  * any memcg without hierarchy as infertile.
4793  */
4794 static inline bool memcg_has_children(struct mem_cgroup *memcg)
4795 {
4796 	return memcg->use_hierarchy && __memcg_has_children(memcg);
4797 }
4798 
4799 /*
4800  * Reclaims as many pages from the given memcg as possible and moves
4801  * the rest to the parent.
4802  *
4803  * Caller is responsible for holding css reference for memcg.
4804  */
4805 static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
4806 {
4807 	int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
4808 	struct cgroup *cgrp = memcg->css.cgroup;
4809 
4810 	/* returns EBUSY if there is a task or if we come here twice. */
4811 	if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
4812 		return -EBUSY;
4813 
4814 	/* we call try-to-free pages for make this cgroup empty */
4815 	lru_add_drain_all();
4816 	/* try to free all pages in this cgroup */
4817 	while (nr_retries && res_counter_read_u64(&memcg->res, RES_USAGE) > 0) {
4818 		int progress;
4819 
4820 		if (signal_pending(current))
4821 			return -EINTR;
4822 
4823 		progress = try_to_free_mem_cgroup_pages(memcg, GFP_KERNEL,
4824 						false);
4825 		if (!progress) {
4826 			nr_retries--;
4827 			/* maybe some writeback is necessary */
4828 			congestion_wait(BLK_RW_ASYNC, HZ/10);
4829 		}
4830 
4831 	}
4832 	lru_add_drain();
4833 	mem_cgroup_reparent_charges(memcg);
4834 
4835 	return 0;
4836 }
4837 
4838 static int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
4839 {
4840 	struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
4841 	int ret;
4842 
4843 	if (mem_cgroup_is_root(memcg))
4844 		return -EINVAL;
4845 	css_get(&memcg->css);
4846 	ret = mem_cgroup_force_empty(memcg);
4847 	css_put(&memcg->css);
4848 
4849 	return ret;
4850 }
4851 
4852 
4853 static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
4854 {
4855 	return mem_cgroup_from_cont(cont)->use_hierarchy;
4856 }
4857 
4858 static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
4859 					u64 val)
4860 {
4861 	int retval = 0;
4862 	struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
4863 	struct cgroup *parent = cont->parent;
4864 	struct mem_cgroup *parent_memcg = NULL;
4865 
4866 	if (parent)
4867 		parent_memcg = mem_cgroup_from_cont(parent);
4868 
4869 	mutex_lock(&memcg_create_mutex);
4870 
4871 	if (memcg->use_hierarchy == val)
4872 		goto out;
4873 
4874 	/*
4875 	 * If parent's use_hierarchy is set, we can't make any modifications
4876 	 * in the child subtrees. If it is unset, then the change can
4877 	 * occur, provided the current cgroup has no children.
4878 	 *
4879 	 * For the root cgroup, parent_mem is NULL, we allow value to be
4880 	 * set if there are no children.
4881 	 */
4882 	if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
4883 				(val == 1 || val == 0)) {
4884 		if (!__memcg_has_children(memcg))
4885 			memcg->use_hierarchy = val;
4886 		else
4887 			retval = -EBUSY;
4888 	} else
4889 		retval = -EINVAL;
4890 
4891 out:
4892 	mutex_unlock(&memcg_create_mutex);
4893 
4894 	return retval;
4895 }
4896 
4897 
4898 static unsigned long mem_cgroup_recursive_stat(struct mem_cgroup *memcg,
4899 					       enum mem_cgroup_stat_index idx)
4900 {
4901 	struct mem_cgroup *iter;
4902 	long val = 0;
4903 
4904 	/* Per-cpu values can be negative, use a signed accumulator */
4905 	for_each_mem_cgroup_tree(iter, memcg)
4906 		val += mem_cgroup_read_stat(iter, idx);
4907 
4908 	if (val < 0) /* race ? */
4909 		val = 0;
4910 	return val;
4911 }
4912 
4913 static inline u64 mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
4914 {
4915 	u64 val;
4916 
4917 	if (!mem_cgroup_is_root(memcg)) {
4918 		if (!swap)
4919 			return res_counter_read_u64(&memcg->res, RES_USAGE);
4920 		else
4921 			return res_counter_read_u64(&memcg->memsw, RES_USAGE);
4922 	}
4923 
4924 	val = mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_CACHE);
4925 	val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_RSS);
4926 
4927 	if (swap)
4928 		val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_SWAP);
4929 
4930 	return val << PAGE_SHIFT;
4931 }
4932 
4933 static ssize_t mem_cgroup_read(struct cgroup *cont, struct cftype *cft,
4934 			       struct file *file, char __user *buf,
4935 			       size_t nbytes, loff_t *ppos)
4936 {
4937 	struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
4938 	char str[64];
4939 	u64 val;
4940 	int name, len;
4941 	enum res_type type;
4942 
4943 	type = MEMFILE_TYPE(cft->private);
4944 	name = MEMFILE_ATTR(cft->private);
4945 
4946 	if (!do_swap_account && type == _MEMSWAP)
4947 		return -EOPNOTSUPP;
4948 
4949 	switch (type) {
4950 	case _MEM:
4951 		if (name == RES_USAGE)
4952 			val = mem_cgroup_usage(memcg, false);
4953 		else
4954 			val = res_counter_read_u64(&memcg->res, name);
4955 		break;
4956 	case _MEMSWAP:
4957 		if (name == RES_USAGE)
4958 			val = mem_cgroup_usage(memcg, true);
4959 		else
4960 			val = res_counter_read_u64(&memcg->memsw, name);
4961 		break;
4962 	case _KMEM:
4963 		val = res_counter_read_u64(&memcg->kmem, name);
4964 		break;
4965 	default:
4966 		BUG();
4967 	}
4968 
4969 	len = scnprintf(str, sizeof(str), "%llu\n", (unsigned long long)val);
4970 	return simple_read_from_buffer(buf, nbytes, ppos, str, len);
4971 }
4972 
4973 static int memcg_update_kmem_limit(struct cgroup *cont, u64 val)
4974 {
4975 	int ret = -EINVAL;
4976 #ifdef CONFIG_MEMCG_KMEM
4977 	struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
4978 	/*
4979 	 * For simplicity, we won't allow this to be disabled.  It also can't
4980 	 * be changed if the cgroup has children already, or if tasks had
4981 	 * already joined.
4982 	 *
4983 	 * If tasks join before we set the limit, a person looking at
4984 	 * kmem.usage_in_bytes will have no way to determine when it took
4985 	 * place, which makes the value quite meaningless.
4986 	 *
4987 	 * After it first became limited, changes in the value of the limit are
4988 	 * of course permitted.
4989 	 */
4990 	mutex_lock(&memcg_create_mutex);
4991 	mutex_lock(&set_limit_mutex);
4992 	if (!memcg->kmem_account_flags && val != RESOURCE_MAX) {
4993 		if (cgroup_task_count(cont) || memcg_has_children(memcg)) {
4994 			ret = -EBUSY;
4995 			goto out;
4996 		}
4997 		ret = res_counter_set_limit(&memcg->kmem, val);
4998 		VM_BUG_ON(ret);
4999 
5000 		ret = memcg_update_cache_sizes(memcg);
5001 		if (ret) {
5002 			res_counter_set_limit(&memcg->kmem, RESOURCE_MAX);
5003 			goto out;
5004 		}
5005 		static_key_slow_inc(&memcg_kmem_enabled_key);
5006 		/*
5007 		 * setting the active bit after the inc will guarantee no one
5008 		 * starts accounting before all call sites are patched
5009 		 */
5010 		memcg_kmem_set_active(memcg);
5011 
5012 		/*
5013 		 * kmem charges can outlive the cgroup. In the case of slab
5014 		 * pages, for instance, a page contain objects from various
5015 		 * processes, so it is unfeasible to migrate them away. We
5016 		 * need to reference count the memcg because of that.
5017 		 */
5018 		mem_cgroup_get(memcg);
5019 	} else
5020 		ret = res_counter_set_limit(&memcg->kmem, val);
5021 out:
5022 	mutex_unlock(&set_limit_mutex);
5023 	mutex_unlock(&memcg_create_mutex);
5024 #endif
5025 	return ret;
5026 }
5027 
5028 #ifdef CONFIG_MEMCG_KMEM
5029 static int memcg_propagate_kmem(struct mem_cgroup *memcg)
5030 {
5031 	int ret = 0;
5032 	struct mem_cgroup *parent = parent_mem_cgroup(memcg);
5033 	if (!parent)
5034 		goto out;
5035 
5036 	memcg->kmem_account_flags = parent->kmem_account_flags;
5037 	/*
5038 	 * When that happen, we need to disable the static branch only on those
5039 	 * memcgs that enabled it. To achieve this, we would be forced to
5040 	 * complicate the code by keeping track of which memcgs were the ones
5041 	 * that actually enabled limits, and which ones got it from its
5042 	 * parents.
5043 	 *
5044 	 * It is a lot simpler just to do static_key_slow_inc() on every child
5045 	 * that is accounted.
5046 	 */
5047 	if (!memcg_kmem_is_active(memcg))
5048 		goto out;
5049 
5050 	/*
5051 	 * destroy(), called if we fail, will issue static_key_slow_inc() and
5052 	 * mem_cgroup_put() if kmem is enabled. We have to either call them
5053 	 * unconditionally, or clear the KMEM_ACTIVE flag. I personally find
5054 	 * this more consistent, since it always leads to the same destroy path
5055 	 */
5056 	mem_cgroup_get(memcg);
5057 	static_key_slow_inc(&memcg_kmem_enabled_key);
5058 
5059 	mutex_lock(&set_limit_mutex);
5060 	ret = memcg_update_cache_sizes(memcg);
5061 	mutex_unlock(&set_limit_mutex);
5062 out:
5063 	return ret;
5064 }
5065 #endif /* CONFIG_MEMCG_KMEM */
5066 
5067 /*
5068  * The user of this function is...
5069  * RES_LIMIT.
5070  */
5071 static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
5072 			    const char *buffer)
5073 {
5074 	struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5075 	enum res_type type;
5076 	int name;
5077 	unsigned long long val;
5078 	int ret;
5079 
5080 	type = MEMFILE_TYPE(cft->private);
5081 	name = MEMFILE_ATTR(cft->private);
5082 
5083 	if (!do_swap_account && type == _MEMSWAP)
5084 		return -EOPNOTSUPP;
5085 
5086 	switch (name) {
5087 	case RES_LIMIT:
5088 		if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
5089 			ret = -EINVAL;
5090 			break;
5091 		}
5092 		/* This function does all necessary parse...reuse it */
5093 		ret = res_counter_memparse_write_strategy(buffer, &val);
5094 		if (ret)
5095 			break;
5096 		if (type == _MEM)
5097 			ret = mem_cgroup_resize_limit(memcg, val);
5098 		else if (type == _MEMSWAP)
5099 			ret = mem_cgroup_resize_memsw_limit(memcg, val);
5100 		else if (type == _KMEM)
5101 			ret = memcg_update_kmem_limit(cont, val);
5102 		else
5103 			return -EINVAL;
5104 		break;
5105 	case RES_SOFT_LIMIT:
5106 		ret = res_counter_memparse_write_strategy(buffer, &val);
5107 		if (ret)
5108 			break;
5109 		/*
5110 		 * For memsw, soft limits are hard to implement in terms
5111 		 * of semantics, for now, we support soft limits for
5112 		 * control without swap
5113 		 */
5114 		if (type == _MEM)
5115 			ret = res_counter_set_soft_limit(&memcg->res, val);
5116 		else
5117 			ret = -EINVAL;
5118 		break;
5119 	default:
5120 		ret = -EINVAL; /* should be BUG() ? */
5121 		break;
5122 	}
5123 	return ret;
5124 }
5125 
5126 static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
5127 		unsigned long long *mem_limit, unsigned long long *memsw_limit)
5128 {
5129 	struct cgroup *cgroup;
5130 	unsigned long long min_limit, min_memsw_limit, tmp;
5131 
5132 	min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
5133 	min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
5134 	cgroup = memcg->css.cgroup;
5135 	if (!memcg->use_hierarchy)
5136 		goto out;
5137 
5138 	while (cgroup->parent) {
5139 		cgroup = cgroup->parent;
5140 		memcg = mem_cgroup_from_cont(cgroup);
5141 		if (!memcg->use_hierarchy)
5142 			break;
5143 		tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
5144 		min_limit = min(min_limit, tmp);
5145 		tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
5146 		min_memsw_limit = min(min_memsw_limit, tmp);
5147 	}
5148 out:
5149 	*mem_limit = min_limit;
5150 	*memsw_limit = min_memsw_limit;
5151 }
5152 
5153 static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
5154 {
5155 	struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5156 	int name;
5157 	enum res_type type;
5158 
5159 	type = MEMFILE_TYPE(event);
5160 	name = MEMFILE_ATTR(event);
5161 
5162 	if (!do_swap_account && type == _MEMSWAP)
5163 		return -EOPNOTSUPP;
5164 
5165 	switch (name) {
5166 	case RES_MAX_USAGE:
5167 		if (type == _MEM)
5168 			res_counter_reset_max(&memcg->res);
5169 		else if (type == _MEMSWAP)
5170 			res_counter_reset_max(&memcg->memsw);
5171 		else if (type == _KMEM)
5172 			res_counter_reset_max(&memcg->kmem);
5173 		else
5174 			return -EINVAL;
5175 		break;
5176 	case RES_FAILCNT:
5177 		if (type == _MEM)
5178 			res_counter_reset_failcnt(&memcg->res);
5179 		else if (type == _MEMSWAP)
5180 			res_counter_reset_failcnt(&memcg->memsw);
5181 		else if (type == _KMEM)
5182 			res_counter_reset_failcnt(&memcg->kmem);
5183 		else
5184 			return -EINVAL;
5185 		break;
5186 	}
5187 
5188 	return 0;
5189 }
5190 
5191 static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp,
5192 					struct cftype *cft)
5193 {
5194 	return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate;
5195 }
5196 
5197 #ifdef CONFIG_MMU
5198 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
5199 					struct cftype *cft, u64 val)
5200 {
5201 	struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5202 
5203 	if (val >= (1 << NR_MOVE_TYPE))
5204 		return -EINVAL;
5205 
5206 	/*
5207 	 * No kind of locking is needed in here, because ->can_attach() will
5208 	 * check this value once in the beginning of the process, and then carry
5209 	 * on with stale data. This means that changes to this value will only
5210 	 * affect task migrations starting after the change.
5211 	 */
5212 	memcg->move_charge_at_immigrate = val;
5213 	return 0;
5214 }
5215 #else
5216 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
5217 					struct cftype *cft, u64 val)
5218 {
5219 	return -ENOSYS;
5220 }
5221 #endif
5222 
5223 #ifdef CONFIG_NUMA
5224 static int memcg_numa_stat_show(struct cgroup *cont, struct cftype *cft,
5225 				      struct seq_file *m)
5226 {
5227 	int nid;
5228 	unsigned long total_nr, file_nr, anon_nr, unevictable_nr;
5229 	unsigned long node_nr;
5230 	struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5231 
5232 	total_nr = mem_cgroup_nr_lru_pages(memcg, LRU_ALL);
5233 	seq_printf(m, "total=%lu", total_nr);
5234 	for_each_node_state(nid, N_MEMORY) {
5235 		node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL);
5236 		seq_printf(m, " N%d=%lu", nid, node_nr);
5237 	}
5238 	seq_putc(m, '\n');
5239 
5240 	file_nr = mem_cgroup_nr_lru_pages(memcg, LRU_ALL_FILE);
5241 	seq_printf(m, "file=%lu", file_nr);
5242 	for_each_node_state(nid, N_MEMORY) {
5243 		node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
5244 				LRU_ALL_FILE);
5245 		seq_printf(m, " N%d=%lu", nid, node_nr);
5246 	}
5247 	seq_putc(m, '\n');
5248 
5249 	anon_nr = mem_cgroup_nr_lru_pages(memcg, LRU_ALL_ANON);
5250 	seq_printf(m, "anon=%lu", anon_nr);
5251 	for_each_node_state(nid, N_MEMORY) {
5252 		node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
5253 				LRU_ALL_ANON);
5254 		seq_printf(m, " N%d=%lu", nid, node_nr);
5255 	}
5256 	seq_putc(m, '\n');
5257 
5258 	unevictable_nr = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_UNEVICTABLE));
5259 	seq_printf(m, "unevictable=%lu", unevictable_nr);
5260 	for_each_node_state(nid, N_MEMORY) {
5261 		node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
5262 				BIT(LRU_UNEVICTABLE));
5263 		seq_printf(m, " N%d=%lu", nid, node_nr);
5264 	}
5265 	seq_putc(m, '\n');
5266 	return 0;
5267 }
5268 #endif /* CONFIG_NUMA */
5269 
5270 static inline void mem_cgroup_lru_names_not_uptodate(void)
5271 {
5272 	BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_lru_names) != NR_LRU_LISTS);
5273 }
5274 
5275 static int memcg_stat_show(struct cgroup *cont, struct cftype *cft,
5276 				 struct seq_file *m)
5277 {
5278 	struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5279 	struct mem_cgroup *mi;
5280 	unsigned int i;
5281 
5282 	for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
5283 		if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
5284 			continue;
5285 		seq_printf(m, "%s %ld\n", mem_cgroup_stat_names[i],
5286 			   mem_cgroup_read_stat(memcg, i) * PAGE_SIZE);
5287 	}
5288 
5289 	for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++)
5290 		seq_printf(m, "%s %lu\n", mem_cgroup_events_names[i],
5291 			   mem_cgroup_read_events(memcg, i));
5292 
5293 	for (i = 0; i < NR_LRU_LISTS; i++)
5294 		seq_printf(m, "%s %lu\n", mem_cgroup_lru_names[i],
5295 			   mem_cgroup_nr_lru_pages(memcg, BIT(i)) * PAGE_SIZE);
5296 
5297 	/* Hierarchical information */
5298 	{
5299 		unsigned long long limit, memsw_limit;
5300 		memcg_get_hierarchical_limit(memcg, &limit, &memsw_limit);
5301 		seq_printf(m, "hierarchical_memory_limit %llu\n", limit);
5302 		if (do_swap_account)
5303 			seq_printf(m, "hierarchical_memsw_limit %llu\n",
5304 				   memsw_limit);
5305 	}
5306 
5307 	for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
5308 		long long val = 0;
5309 
5310 		if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
5311 			continue;
5312 		for_each_mem_cgroup_tree(mi, memcg)
5313 			val += mem_cgroup_read_stat(mi, i) * PAGE_SIZE;
5314 		seq_printf(m, "total_%s %lld\n", mem_cgroup_stat_names[i], val);
5315 	}
5316 
5317 	for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
5318 		unsigned long long val = 0;
5319 
5320 		for_each_mem_cgroup_tree(mi, memcg)
5321 			val += mem_cgroup_read_events(mi, i);
5322 		seq_printf(m, "total_%s %llu\n",
5323 			   mem_cgroup_events_names[i], val);
5324 	}
5325 
5326 	for (i = 0; i < NR_LRU_LISTS; i++) {
5327 		unsigned long long val = 0;
5328 
5329 		for_each_mem_cgroup_tree(mi, memcg)
5330 			val += mem_cgroup_nr_lru_pages(mi, BIT(i)) * PAGE_SIZE;
5331 		seq_printf(m, "total_%s %llu\n", mem_cgroup_lru_names[i], val);
5332 	}
5333 
5334 #ifdef CONFIG_DEBUG_VM
5335 	{
5336 		int nid, zid;
5337 		struct mem_cgroup_per_zone *mz;
5338 		struct zone_reclaim_stat *rstat;
5339 		unsigned long recent_rotated[2] = {0, 0};
5340 		unsigned long recent_scanned[2] = {0, 0};
5341 
5342 		for_each_online_node(nid)
5343 			for (zid = 0; zid < MAX_NR_ZONES; zid++) {
5344 				mz = mem_cgroup_zoneinfo(memcg, nid, zid);
5345 				rstat = &mz->lruvec.reclaim_stat;
5346 
5347 				recent_rotated[0] += rstat->recent_rotated[0];
5348 				recent_rotated[1] += rstat->recent_rotated[1];
5349 				recent_scanned[0] += rstat->recent_scanned[0];
5350 				recent_scanned[1] += rstat->recent_scanned[1];
5351 			}
5352 		seq_printf(m, "recent_rotated_anon %lu\n", recent_rotated[0]);
5353 		seq_printf(m, "recent_rotated_file %lu\n", recent_rotated[1]);
5354 		seq_printf(m, "recent_scanned_anon %lu\n", recent_scanned[0]);
5355 		seq_printf(m, "recent_scanned_file %lu\n", recent_scanned[1]);
5356 	}
5357 #endif
5358 
5359 	return 0;
5360 }
5361 
5362 static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
5363 {
5364 	struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5365 
5366 	return mem_cgroup_swappiness(memcg);
5367 }
5368 
5369 static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
5370 				       u64 val)
5371 {
5372 	struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5373 	struct mem_cgroup *parent;
5374 
5375 	if (val > 100)
5376 		return -EINVAL;
5377 
5378 	if (cgrp->parent == NULL)
5379 		return -EINVAL;
5380 
5381 	parent = mem_cgroup_from_cont(cgrp->parent);
5382 
5383 	mutex_lock(&memcg_create_mutex);
5384 
5385 	/* If under hierarchy, only empty-root can set this value */
5386 	if ((parent->use_hierarchy) || memcg_has_children(memcg)) {
5387 		mutex_unlock(&memcg_create_mutex);
5388 		return -EINVAL;
5389 	}
5390 
5391 	memcg->swappiness = val;
5392 
5393 	mutex_unlock(&memcg_create_mutex);
5394 
5395 	return 0;
5396 }
5397 
5398 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
5399 {
5400 	struct mem_cgroup_threshold_ary *t;
5401 	u64 usage;
5402 	int i;
5403 
5404 	rcu_read_lock();
5405 	if (!swap)
5406 		t = rcu_dereference(memcg->thresholds.primary);
5407 	else
5408 		t = rcu_dereference(memcg->memsw_thresholds.primary);
5409 
5410 	if (!t)
5411 		goto unlock;
5412 
5413 	usage = mem_cgroup_usage(memcg, swap);
5414 
5415 	/*
5416 	 * current_threshold points to threshold just below or equal to usage.
5417 	 * If it's not true, a threshold was crossed after last
5418 	 * call of __mem_cgroup_threshold().
5419 	 */
5420 	i = t->current_threshold;
5421 
5422 	/*
5423 	 * Iterate backward over array of thresholds starting from
5424 	 * current_threshold and check if a threshold is crossed.
5425 	 * If none of thresholds below usage is crossed, we read
5426 	 * only one element of the array here.
5427 	 */
5428 	for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
5429 		eventfd_signal(t->entries[i].eventfd, 1);
5430 
5431 	/* i = current_threshold + 1 */
5432 	i++;
5433 
5434 	/*
5435 	 * Iterate forward over array of thresholds starting from
5436 	 * current_threshold+1 and check if a threshold is crossed.
5437 	 * If none of thresholds above usage is crossed, we read
5438 	 * only one element of the array here.
5439 	 */
5440 	for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
5441 		eventfd_signal(t->entries[i].eventfd, 1);
5442 
5443 	/* Update current_threshold */
5444 	t->current_threshold = i - 1;
5445 unlock:
5446 	rcu_read_unlock();
5447 }
5448 
5449 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
5450 {
5451 	while (memcg) {
5452 		__mem_cgroup_threshold(memcg, false);
5453 		if (do_swap_account)
5454 			__mem_cgroup_threshold(memcg, true);
5455 
5456 		memcg = parent_mem_cgroup(memcg);
5457 	}
5458 }
5459 
5460 static int compare_thresholds(const void *a, const void *b)
5461 {
5462 	const struct mem_cgroup_threshold *_a = a;
5463 	const struct mem_cgroup_threshold *_b = b;
5464 
5465 	return _a->threshold - _b->threshold;
5466 }
5467 
5468 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
5469 {
5470 	struct mem_cgroup_eventfd_list *ev;
5471 
5472 	list_for_each_entry(ev, &memcg->oom_notify, list)
5473 		eventfd_signal(ev->eventfd, 1);
5474 	return 0;
5475 }
5476 
5477 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
5478 {
5479 	struct mem_cgroup *iter;
5480 
5481 	for_each_mem_cgroup_tree(iter, memcg)
5482 		mem_cgroup_oom_notify_cb(iter);
5483 }
5484 
5485 static int mem_cgroup_usage_register_event(struct cgroup *cgrp,
5486 	struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
5487 {
5488 	struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5489 	struct mem_cgroup_thresholds *thresholds;
5490 	struct mem_cgroup_threshold_ary *new;
5491 	enum res_type type = MEMFILE_TYPE(cft->private);
5492 	u64 threshold, usage;
5493 	int i, size, ret;
5494 
5495 	ret = res_counter_memparse_write_strategy(args, &threshold);
5496 	if (ret)
5497 		return ret;
5498 
5499 	mutex_lock(&memcg->thresholds_lock);
5500 
5501 	if (type == _MEM)
5502 		thresholds = &memcg->thresholds;
5503 	else if (type == _MEMSWAP)
5504 		thresholds = &memcg->memsw_thresholds;
5505 	else
5506 		BUG();
5507 
5508 	usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
5509 
5510 	/* Check if a threshold crossed before adding a new one */
5511 	if (thresholds->primary)
5512 		__mem_cgroup_threshold(memcg, type == _MEMSWAP);
5513 
5514 	size = thresholds->primary ? thresholds->primary->size + 1 : 1;
5515 
5516 	/* Allocate memory for new array of thresholds */
5517 	new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
5518 			GFP_KERNEL);
5519 	if (!new) {
5520 		ret = -ENOMEM;
5521 		goto unlock;
5522 	}
5523 	new->size = size;
5524 
5525 	/* Copy thresholds (if any) to new array */
5526 	if (thresholds->primary) {
5527 		memcpy(new->entries, thresholds->primary->entries, (size - 1) *
5528 				sizeof(struct mem_cgroup_threshold));
5529 	}
5530 
5531 	/* Add new threshold */
5532 	new->entries[size - 1].eventfd = eventfd;
5533 	new->entries[size - 1].threshold = threshold;
5534 
5535 	/* Sort thresholds. Registering of new threshold isn't time-critical */
5536 	sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
5537 			compare_thresholds, NULL);
5538 
5539 	/* Find current threshold */
5540 	new->current_threshold = -1;
5541 	for (i = 0; i < size; i++) {
5542 		if (new->entries[i].threshold <= usage) {
5543 			/*
5544 			 * new->current_threshold will not be used until
5545 			 * rcu_assign_pointer(), so it's safe to increment
5546 			 * it here.
5547 			 */
5548 			++new->current_threshold;
5549 		} else
5550 			break;
5551 	}
5552 
5553 	/* Free old spare buffer and save old primary buffer as spare */
5554 	kfree(thresholds->spare);
5555 	thresholds->spare = thresholds->primary;
5556 
5557 	rcu_assign_pointer(thresholds->primary, new);
5558 
5559 	/* To be sure that nobody uses thresholds */
5560 	synchronize_rcu();
5561 
5562 unlock:
5563 	mutex_unlock(&memcg->thresholds_lock);
5564 
5565 	return ret;
5566 }
5567 
5568 static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,
5569 	struct cftype *cft, struct eventfd_ctx *eventfd)
5570 {
5571 	struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5572 	struct mem_cgroup_thresholds *thresholds;
5573 	struct mem_cgroup_threshold_ary *new;
5574 	enum res_type type = MEMFILE_TYPE(cft->private);
5575 	u64 usage;
5576 	int i, j, size;
5577 
5578 	mutex_lock(&memcg->thresholds_lock);
5579 	if (type == _MEM)
5580 		thresholds = &memcg->thresholds;
5581 	else if (type == _MEMSWAP)
5582 		thresholds = &memcg->memsw_thresholds;
5583 	else
5584 		BUG();
5585 
5586 	if (!thresholds->primary)
5587 		goto unlock;
5588 
5589 	usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
5590 
5591 	/* Check if a threshold crossed before removing */
5592 	__mem_cgroup_threshold(memcg, type == _MEMSWAP);
5593 
5594 	/* Calculate new number of threshold */
5595 	size = 0;
5596 	for (i = 0; i < thresholds->primary->size; i++) {
5597 		if (thresholds->primary->entries[i].eventfd != eventfd)
5598 			size++;
5599 	}
5600 
5601 	new = thresholds->spare;
5602 
5603 	/* Set thresholds array to NULL if we don't have thresholds */
5604 	if (!size) {
5605 		kfree(new);
5606 		new = NULL;
5607 		goto swap_buffers;
5608 	}
5609 
5610 	new->size = size;
5611 
5612 	/* Copy thresholds and find current threshold */
5613 	new->current_threshold = -1;
5614 	for (i = 0, j = 0; i < thresholds->primary->size; i++) {
5615 		if (thresholds->primary->entries[i].eventfd == eventfd)
5616 			continue;
5617 
5618 		new->entries[j] = thresholds->primary->entries[i];
5619 		if (new->entries[j].threshold <= usage) {
5620 			/*
5621 			 * new->current_threshold will not be used
5622 			 * until rcu_assign_pointer(), so it's safe to increment
5623 			 * it here.
5624 			 */
5625 			++new->current_threshold;
5626 		}
5627 		j++;
5628 	}
5629 
5630 swap_buffers:
5631 	/* Swap primary and spare array */
5632 	thresholds->spare = thresholds->primary;
5633 	/* If all events are unregistered, free the spare array */
5634 	if (!new) {
5635 		kfree(thresholds->spare);
5636 		thresholds->spare = NULL;
5637 	}
5638 
5639 	rcu_assign_pointer(thresholds->primary, new);
5640 
5641 	/* To be sure that nobody uses thresholds */
5642 	synchronize_rcu();
5643 unlock:
5644 	mutex_unlock(&memcg->thresholds_lock);
5645 }
5646 
5647 static int mem_cgroup_oom_register_event(struct cgroup *cgrp,
5648 	struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
5649 {
5650 	struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5651 	struct mem_cgroup_eventfd_list *event;
5652 	enum res_type type = MEMFILE_TYPE(cft->private);
5653 
5654 	BUG_ON(type != _OOM_TYPE);
5655 	event = kmalloc(sizeof(*event),	GFP_KERNEL);
5656 	if (!event)
5657 		return -ENOMEM;
5658 
5659 	spin_lock(&memcg_oom_lock);
5660 
5661 	event->eventfd = eventfd;
5662 	list_add(&event->list, &memcg->oom_notify);
5663 
5664 	/* already in OOM ? */
5665 	if (atomic_read(&memcg->under_oom))
5666 		eventfd_signal(eventfd, 1);
5667 	spin_unlock(&memcg_oom_lock);
5668 
5669 	return 0;
5670 }
5671 
5672 static void mem_cgroup_oom_unregister_event(struct cgroup *cgrp,
5673 	struct cftype *cft, struct eventfd_ctx *eventfd)
5674 {
5675 	struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5676 	struct mem_cgroup_eventfd_list *ev, *tmp;
5677 	enum res_type type = MEMFILE_TYPE(cft->private);
5678 
5679 	BUG_ON(type != _OOM_TYPE);
5680 
5681 	spin_lock(&memcg_oom_lock);
5682 
5683 	list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
5684 		if (ev->eventfd == eventfd) {
5685 			list_del(&ev->list);
5686 			kfree(ev);
5687 		}
5688 	}
5689 
5690 	spin_unlock(&memcg_oom_lock);
5691 }
5692 
5693 static int mem_cgroup_oom_control_read(struct cgroup *cgrp,
5694 	struct cftype *cft,  struct cgroup_map_cb *cb)
5695 {
5696 	struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5697 
5698 	cb->fill(cb, "oom_kill_disable", memcg->oom_kill_disable);
5699 
5700 	if (atomic_read(&memcg->under_oom))
5701 		cb->fill(cb, "under_oom", 1);
5702 	else
5703 		cb->fill(cb, "under_oom", 0);
5704 	return 0;
5705 }
5706 
5707 static int mem_cgroup_oom_control_write(struct cgroup *cgrp,
5708 	struct cftype *cft, u64 val)
5709 {
5710 	struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5711 	struct mem_cgroup *parent;
5712 
5713 	/* cannot set to root cgroup and only 0 and 1 are allowed */
5714 	if (!cgrp->parent || !((val == 0) || (val == 1)))
5715 		return -EINVAL;
5716 
5717 	parent = mem_cgroup_from_cont(cgrp->parent);
5718 
5719 	mutex_lock(&memcg_create_mutex);
5720 	/* oom-kill-disable is a flag for subhierarchy. */
5721 	if ((parent->use_hierarchy) || memcg_has_children(memcg)) {
5722 		mutex_unlock(&memcg_create_mutex);
5723 		return -EINVAL;
5724 	}
5725 	memcg->oom_kill_disable = val;
5726 	if (!val)
5727 		memcg_oom_recover(memcg);
5728 	mutex_unlock(&memcg_create_mutex);
5729 	return 0;
5730 }
5731 
5732 #ifdef CONFIG_MEMCG_KMEM
5733 static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
5734 {
5735 	int ret;
5736 
5737 	memcg->kmemcg_id = -1;
5738 	ret = memcg_propagate_kmem(memcg);
5739 	if (ret)
5740 		return ret;
5741 
5742 	return mem_cgroup_sockets_init(memcg, ss);
5743 };
5744 
5745 static void kmem_cgroup_destroy(struct mem_cgroup *memcg)
5746 {
5747 	mem_cgroup_sockets_destroy(memcg);
5748 
5749 	memcg_kmem_mark_dead(memcg);
5750 
5751 	if (res_counter_read_u64(&memcg->kmem, RES_USAGE) != 0)
5752 		return;
5753 
5754 	/*
5755 	 * Charges already down to 0, undo mem_cgroup_get() done in the charge
5756 	 * path here, being careful not to race with memcg_uncharge_kmem: it is
5757 	 * possible that the charges went down to 0 between mark_dead and the
5758 	 * res_counter read, so in that case, we don't need the put
5759 	 */
5760 	if (memcg_kmem_test_and_clear_dead(memcg))
5761 		mem_cgroup_put(memcg);
5762 }
5763 #else
5764 static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
5765 {
5766 	return 0;
5767 }
5768 
5769 static void kmem_cgroup_destroy(struct mem_cgroup *memcg)
5770 {
5771 }
5772 #endif
5773 
5774 static struct cftype mem_cgroup_files[] = {
5775 	{
5776 		.name = "usage_in_bytes",
5777 		.private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
5778 		.read = mem_cgroup_read,
5779 		.register_event = mem_cgroup_usage_register_event,
5780 		.unregister_event = mem_cgroup_usage_unregister_event,
5781 	},
5782 	{
5783 		.name = "max_usage_in_bytes",
5784 		.private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
5785 		.trigger = mem_cgroup_reset,
5786 		.read = mem_cgroup_read,
5787 	},
5788 	{
5789 		.name = "limit_in_bytes",
5790 		.private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
5791 		.write_string = mem_cgroup_write,
5792 		.read = mem_cgroup_read,
5793 	},
5794 	{
5795 		.name = "soft_limit_in_bytes",
5796 		.private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
5797 		.write_string = mem_cgroup_write,
5798 		.read = mem_cgroup_read,
5799 	},
5800 	{
5801 		.name = "failcnt",
5802 		.private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
5803 		.trigger = mem_cgroup_reset,
5804 		.read = mem_cgroup_read,
5805 	},
5806 	{
5807 		.name = "stat",
5808 		.read_seq_string = memcg_stat_show,
5809 	},
5810 	{
5811 		.name = "force_empty",
5812 		.trigger = mem_cgroup_force_empty_write,
5813 	},
5814 	{
5815 		.name = "use_hierarchy",
5816 		.write_u64 = mem_cgroup_hierarchy_write,
5817 		.read_u64 = mem_cgroup_hierarchy_read,
5818 	},
5819 	{
5820 		.name = "swappiness",
5821 		.read_u64 = mem_cgroup_swappiness_read,
5822 		.write_u64 = mem_cgroup_swappiness_write,
5823 	},
5824 	{
5825 		.name = "move_charge_at_immigrate",
5826 		.read_u64 = mem_cgroup_move_charge_read,
5827 		.write_u64 = mem_cgroup_move_charge_write,
5828 	},
5829 	{
5830 		.name = "oom_control",
5831 		.read_map = mem_cgroup_oom_control_read,
5832 		.write_u64 = mem_cgroup_oom_control_write,
5833 		.register_event = mem_cgroup_oom_register_event,
5834 		.unregister_event = mem_cgroup_oom_unregister_event,
5835 		.private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
5836 	},
5837 #ifdef CONFIG_NUMA
5838 	{
5839 		.name = "numa_stat",
5840 		.read_seq_string = memcg_numa_stat_show,
5841 	},
5842 #endif
5843 #ifdef CONFIG_MEMCG_KMEM
5844 	{
5845 		.name = "kmem.limit_in_bytes",
5846 		.private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
5847 		.write_string = mem_cgroup_write,
5848 		.read = mem_cgroup_read,
5849 	},
5850 	{
5851 		.name = "kmem.usage_in_bytes",
5852 		.private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
5853 		.read = mem_cgroup_read,
5854 	},
5855 	{
5856 		.name = "kmem.failcnt",
5857 		.private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
5858 		.trigger = mem_cgroup_reset,
5859 		.read = mem_cgroup_read,
5860 	},
5861 	{
5862 		.name = "kmem.max_usage_in_bytes",
5863 		.private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
5864 		.trigger = mem_cgroup_reset,
5865 		.read = mem_cgroup_read,
5866 	},
5867 #ifdef CONFIG_SLABINFO
5868 	{
5869 		.name = "kmem.slabinfo",
5870 		.read_seq_string = mem_cgroup_slabinfo_read,
5871 	},
5872 #endif
5873 #endif
5874 	{ },	/* terminate */
5875 };
5876 
5877 #ifdef CONFIG_MEMCG_SWAP
5878 static struct cftype memsw_cgroup_files[] = {
5879 	{
5880 		.name = "memsw.usage_in_bytes",
5881 		.private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
5882 		.read = mem_cgroup_read,
5883 		.register_event = mem_cgroup_usage_register_event,
5884 		.unregister_event = mem_cgroup_usage_unregister_event,
5885 	},
5886 	{
5887 		.name = "memsw.max_usage_in_bytes",
5888 		.private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
5889 		.trigger = mem_cgroup_reset,
5890 		.read = mem_cgroup_read,
5891 	},
5892 	{
5893 		.name = "memsw.limit_in_bytes",
5894 		.private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
5895 		.write_string = mem_cgroup_write,
5896 		.read = mem_cgroup_read,
5897 	},
5898 	{
5899 		.name = "memsw.failcnt",
5900 		.private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
5901 		.trigger = mem_cgroup_reset,
5902 		.read = mem_cgroup_read,
5903 	},
5904 	{ },	/* terminate */
5905 };
5906 #endif
5907 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
5908 {
5909 	struct mem_cgroup_per_node *pn;
5910 	struct mem_cgroup_per_zone *mz;
5911 	int zone, tmp = node;
5912 	/*
5913 	 * This routine is called against possible nodes.
5914 	 * But it's BUG to call kmalloc() against offline node.
5915 	 *
5916 	 * TODO: this routine can waste much memory for nodes which will
5917 	 *       never be onlined. It's better to use memory hotplug callback
5918 	 *       function.
5919 	 */
5920 	if (!node_state(node, N_NORMAL_MEMORY))
5921 		tmp = -1;
5922 	pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
5923 	if (!pn)
5924 		return 1;
5925 
5926 	for (zone = 0; zone < MAX_NR_ZONES; zone++) {
5927 		mz = &pn->zoneinfo[zone];
5928 		lruvec_init(&mz->lruvec);
5929 		mz->usage_in_excess = 0;
5930 		mz->on_tree = false;
5931 		mz->memcg = memcg;
5932 	}
5933 	memcg->info.nodeinfo[node] = pn;
5934 	return 0;
5935 }
5936 
5937 static void free_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
5938 {
5939 	kfree(memcg->info.nodeinfo[node]);
5940 }
5941 
5942 static struct mem_cgroup *mem_cgroup_alloc(void)
5943 {
5944 	struct mem_cgroup *memcg;
5945 	size_t size = memcg_size();
5946 
5947 	/* Can be very big if nr_node_ids is very big */
5948 	if (size < PAGE_SIZE)
5949 		memcg = kzalloc(size, GFP_KERNEL);
5950 	else
5951 		memcg = vzalloc(size);
5952 
5953 	if (!memcg)
5954 		return NULL;
5955 
5956 	memcg->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
5957 	if (!memcg->stat)
5958 		goto out_free;
5959 	spin_lock_init(&memcg->pcp_counter_lock);
5960 	return memcg;
5961 
5962 out_free:
5963 	if (size < PAGE_SIZE)
5964 		kfree(memcg);
5965 	else
5966 		vfree(memcg);
5967 	return NULL;
5968 }
5969 
5970 /*
5971  * At destroying mem_cgroup, references from swap_cgroup can remain.
5972  * (scanning all at force_empty is too costly...)
5973  *
5974  * Instead of clearing all references at force_empty, we remember
5975  * the number of reference from swap_cgroup and free mem_cgroup when
5976  * it goes down to 0.
5977  *
5978  * Removal of cgroup itself succeeds regardless of refs from swap.
5979  */
5980 
5981 static void __mem_cgroup_free(struct mem_cgroup *memcg)
5982 {
5983 	int node;
5984 	size_t size = memcg_size();
5985 
5986 	mem_cgroup_remove_from_trees(memcg);
5987 	free_css_id(&mem_cgroup_subsys, &memcg->css);
5988 
5989 	for_each_node(node)
5990 		free_mem_cgroup_per_zone_info(memcg, node);
5991 
5992 	free_percpu(memcg->stat);
5993 
5994 	/*
5995 	 * We need to make sure that (at least for now), the jump label
5996 	 * destruction code runs outside of the cgroup lock. This is because
5997 	 * get_online_cpus(), which is called from the static_branch update,
5998 	 * can't be called inside the cgroup_lock. cpusets are the ones
5999 	 * enforcing this dependency, so if they ever change, we might as well.
6000 	 *
6001 	 * schedule_work() will guarantee this happens. Be careful if you need
6002 	 * to move this code around, and make sure it is outside
6003 	 * the cgroup_lock.
6004 	 */
6005 	disarm_static_keys(memcg);
6006 	if (size < PAGE_SIZE)
6007 		kfree(memcg);
6008 	else
6009 		vfree(memcg);
6010 }
6011 
6012 
6013 /*
6014  * Helpers for freeing a kmalloc()ed/vzalloc()ed mem_cgroup by RCU,
6015  * but in process context.  The work_freeing structure is overlaid
6016  * on the rcu_freeing structure, which itself is overlaid on memsw.
6017  */
6018 static void free_work(struct work_struct *work)
6019 {
6020 	struct mem_cgroup *memcg;
6021 
6022 	memcg = container_of(work, struct mem_cgroup, work_freeing);
6023 	__mem_cgroup_free(memcg);
6024 }
6025 
6026 static void free_rcu(struct rcu_head *rcu_head)
6027 {
6028 	struct mem_cgroup *memcg;
6029 
6030 	memcg = container_of(rcu_head, struct mem_cgroup, rcu_freeing);
6031 	INIT_WORK(&memcg->work_freeing, free_work);
6032 	schedule_work(&memcg->work_freeing);
6033 }
6034 
6035 static void mem_cgroup_get(struct mem_cgroup *memcg)
6036 {
6037 	atomic_inc(&memcg->refcnt);
6038 }
6039 
6040 static void __mem_cgroup_put(struct mem_cgroup *memcg, int count)
6041 {
6042 	if (atomic_sub_and_test(count, &memcg->refcnt)) {
6043 		struct mem_cgroup *parent = parent_mem_cgroup(memcg);
6044 		call_rcu(&memcg->rcu_freeing, free_rcu);
6045 		if (parent)
6046 			mem_cgroup_put(parent);
6047 	}
6048 }
6049 
6050 static void mem_cgroup_put(struct mem_cgroup *memcg)
6051 {
6052 	__mem_cgroup_put(memcg, 1);
6053 }
6054 
6055 /*
6056  * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
6057  */
6058 struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg)
6059 {
6060 	if (!memcg->res.parent)
6061 		return NULL;
6062 	return mem_cgroup_from_res_counter(memcg->res.parent, res);
6063 }
6064 EXPORT_SYMBOL(parent_mem_cgroup);
6065 
6066 static void __init mem_cgroup_soft_limit_tree_init(void)
6067 {
6068 	struct mem_cgroup_tree_per_node *rtpn;
6069 	struct mem_cgroup_tree_per_zone *rtpz;
6070 	int tmp, node, zone;
6071 
6072 	for_each_node(node) {
6073 		tmp = node;
6074 		if (!node_state(node, N_NORMAL_MEMORY))
6075 			tmp = -1;
6076 		rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
6077 		BUG_ON(!rtpn);
6078 
6079 		soft_limit_tree.rb_tree_per_node[node] = rtpn;
6080 
6081 		for (zone = 0; zone < MAX_NR_ZONES; zone++) {
6082 			rtpz = &rtpn->rb_tree_per_zone[zone];
6083 			rtpz->rb_root = RB_ROOT;
6084 			spin_lock_init(&rtpz->lock);
6085 		}
6086 	}
6087 }
6088 
6089 static struct cgroup_subsys_state * __ref
6090 mem_cgroup_css_alloc(struct cgroup *cont)
6091 {
6092 	struct mem_cgroup *memcg;
6093 	long error = -ENOMEM;
6094 	int node;
6095 
6096 	memcg = mem_cgroup_alloc();
6097 	if (!memcg)
6098 		return ERR_PTR(error);
6099 
6100 	for_each_node(node)
6101 		if (alloc_mem_cgroup_per_zone_info(memcg, node))
6102 			goto free_out;
6103 
6104 	/* root ? */
6105 	if (cont->parent == NULL) {
6106 		root_mem_cgroup = memcg;
6107 		res_counter_init(&memcg->res, NULL);
6108 		res_counter_init(&memcg->memsw, NULL);
6109 		res_counter_init(&memcg->kmem, NULL);
6110 	}
6111 
6112 	memcg->last_scanned_node = MAX_NUMNODES;
6113 	INIT_LIST_HEAD(&memcg->oom_notify);
6114 	atomic_set(&memcg->refcnt, 1);
6115 	memcg->move_charge_at_immigrate = 0;
6116 	mutex_init(&memcg->thresholds_lock);
6117 	spin_lock_init(&memcg->move_lock);
6118 
6119 	return &memcg->css;
6120 
6121 free_out:
6122 	__mem_cgroup_free(memcg);
6123 	return ERR_PTR(error);
6124 }
6125 
6126 static int
6127 mem_cgroup_css_online(struct cgroup *cont)
6128 {
6129 	struct mem_cgroup *memcg, *parent;
6130 	int error = 0;
6131 
6132 	if (!cont->parent)
6133 		return 0;
6134 
6135 	mutex_lock(&memcg_create_mutex);
6136 	memcg = mem_cgroup_from_cont(cont);
6137 	parent = mem_cgroup_from_cont(cont->parent);
6138 
6139 	memcg->use_hierarchy = parent->use_hierarchy;
6140 	memcg->oom_kill_disable = parent->oom_kill_disable;
6141 	memcg->swappiness = mem_cgroup_swappiness(parent);
6142 
6143 	if (parent->use_hierarchy) {
6144 		res_counter_init(&memcg->res, &parent->res);
6145 		res_counter_init(&memcg->memsw, &parent->memsw);
6146 		res_counter_init(&memcg->kmem, &parent->kmem);
6147 
6148 		/*
6149 		 * We increment refcnt of the parent to ensure that we can
6150 		 * safely access it on res_counter_charge/uncharge.
6151 		 * This refcnt will be decremented when freeing this
6152 		 * mem_cgroup(see mem_cgroup_put).
6153 		 */
6154 		mem_cgroup_get(parent);
6155 	} else {
6156 		res_counter_init(&memcg->res, NULL);
6157 		res_counter_init(&memcg->memsw, NULL);
6158 		res_counter_init(&memcg->kmem, NULL);
6159 		/*
6160 		 * Deeper hierachy with use_hierarchy == false doesn't make
6161 		 * much sense so let cgroup subsystem know about this
6162 		 * unfortunate state in our controller.
6163 		 */
6164 		if (parent != root_mem_cgroup)
6165 			mem_cgroup_subsys.broken_hierarchy = true;
6166 	}
6167 
6168 	error = memcg_init_kmem(memcg, &mem_cgroup_subsys);
6169 	mutex_unlock(&memcg_create_mutex);
6170 	if (error) {
6171 		/*
6172 		 * We call put now because our (and parent's) refcnts
6173 		 * are already in place. mem_cgroup_put() will internally
6174 		 * call __mem_cgroup_free, so return directly
6175 		 */
6176 		mem_cgroup_put(memcg);
6177 		if (parent->use_hierarchy)
6178 			mem_cgroup_put(parent);
6179 	}
6180 	return error;
6181 }
6182 
6183 static void mem_cgroup_css_offline(struct cgroup *cont)
6184 {
6185 	struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
6186 
6187 	mem_cgroup_reparent_charges(memcg);
6188 	mem_cgroup_destroy_all_caches(memcg);
6189 }
6190 
6191 static void mem_cgroup_css_free(struct cgroup *cont)
6192 {
6193 	struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
6194 
6195 	kmem_cgroup_destroy(memcg);
6196 
6197 	mem_cgroup_put(memcg);
6198 }
6199 
6200 #ifdef CONFIG_MMU
6201 /* Handlers for move charge at task migration. */
6202 #define PRECHARGE_COUNT_AT_ONCE	256
6203 static int mem_cgroup_do_precharge(unsigned long count)
6204 {
6205 	int ret = 0;
6206 	int batch_count = PRECHARGE_COUNT_AT_ONCE;
6207 	struct mem_cgroup *memcg = mc.to;
6208 
6209 	if (mem_cgroup_is_root(memcg)) {
6210 		mc.precharge += count;
6211 		/* we don't need css_get for root */
6212 		return ret;
6213 	}
6214 	/* try to charge at once */
6215 	if (count > 1) {
6216 		struct res_counter *dummy;
6217 		/*
6218 		 * "memcg" cannot be under rmdir() because we've already checked
6219 		 * by cgroup_lock_live_cgroup() that it is not removed and we
6220 		 * are still under the same cgroup_mutex. So we can postpone
6221 		 * css_get().
6222 		 */
6223 		if (res_counter_charge(&memcg->res, PAGE_SIZE * count, &dummy))
6224 			goto one_by_one;
6225 		if (do_swap_account && res_counter_charge(&memcg->memsw,
6226 						PAGE_SIZE * count, &dummy)) {
6227 			res_counter_uncharge(&memcg->res, PAGE_SIZE * count);
6228 			goto one_by_one;
6229 		}
6230 		mc.precharge += count;
6231 		return ret;
6232 	}
6233 one_by_one:
6234 	/* fall back to one by one charge */
6235 	while (count--) {
6236 		if (signal_pending(current)) {
6237 			ret = -EINTR;
6238 			break;
6239 		}
6240 		if (!batch_count--) {
6241 			batch_count = PRECHARGE_COUNT_AT_ONCE;
6242 			cond_resched();
6243 		}
6244 		ret = __mem_cgroup_try_charge(NULL,
6245 					GFP_KERNEL, 1, &memcg, false);
6246 		if (ret)
6247 			/* mem_cgroup_clear_mc() will do uncharge later */
6248 			return ret;
6249 		mc.precharge++;
6250 	}
6251 	return ret;
6252 }
6253 
6254 /**
6255  * get_mctgt_type - get target type of moving charge
6256  * @vma: the vma the pte to be checked belongs
6257  * @addr: the address corresponding to the pte to be checked
6258  * @ptent: the pte to be checked
6259  * @target: the pointer the target page or swap ent will be stored(can be NULL)
6260  *
6261  * Returns
6262  *   0(MC_TARGET_NONE): if the pte is not a target for move charge.
6263  *   1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
6264  *     move charge. if @target is not NULL, the page is stored in target->page
6265  *     with extra refcnt got(Callers should handle it).
6266  *   2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
6267  *     target for charge migration. if @target is not NULL, the entry is stored
6268  *     in target->ent.
6269  *
6270  * Called with pte lock held.
6271  */
6272 union mc_target {
6273 	struct page	*page;
6274 	swp_entry_t	ent;
6275 };
6276 
6277 enum mc_target_type {
6278 	MC_TARGET_NONE = 0,
6279 	MC_TARGET_PAGE,
6280 	MC_TARGET_SWAP,
6281 };
6282 
6283 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
6284 						unsigned long addr, pte_t ptent)
6285 {
6286 	struct page *page = vm_normal_page(vma, addr, ptent);
6287 
6288 	if (!page || !page_mapped(page))
6289 		return NULL;
6290 	if (PageAnon(page)) {
6291 		/* we don't move shared anon */
6292 		if (!move_anon())
6293 			return NULL;
6294 	} else if (!move_file())
6295 		/* we ignore mapcount for file pages */
6296 		return NULL;
6297 	if (!get_page_unless_zero(page))
6298 		return NULL;
6299 
6300 	return page;
6301 }
6302 
6303 #ifdef CONFIG_SWAP
6304 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
6305 			unsigned long addr, pte_t ptent, swp_entry_t *entry)
6306 {
6307 	struct page *page = NULL;
6308 	swp_entry_t ent = pte_to_swp_entry(ptent);
6309 
6310 	if (!move_anon() || non_swap_entry(ent))
6311 		return NULL;
6312 	/*
6313 	 * Because lookup_swap_cache() updates some statistics counter,
6314 	 * we call find_get_page() with swapper_space directly.
6315 	 */
6316 	page = find_get_page(swap_address_space(ent), ent.val);
6317 	if (do_swap_account)
6318 		entry->val = ent.val;
6319 
6320 	return page;
6321 }
6322 #else
6323 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
6324 			unsigned long addr, pte_t ptent, swp_entry_t *entry)
6325 {
6326 	return NULL;
6327 }
6328 #endif
6329 
6330 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
6331 			unsigned long addr, pte_t ptent, swp_entry_t *entry)
6332 {
6333 	struct page *page = NULL;
6334 	struct address_space *mapping;
6335 	pgoff_t pgoff;
6336 
6337 	if (!vma->vm_file) /* anonymous vma */
6338 		return NULL;
6339 	if (!move_file())
6340 		return NULL;
6341 
6342 	mapping = vma->vm_file->f_mapping;
6343 	if (pte_none(ptent))
6344 		pgoff = linear_page_index(vma, addr);
6345 	else /* pte_file(ptent) is true */
6346 		pgoff = pte_to_pgoff(ptent);
6347 
6348 	/* page is moved even if it's not RSS of this task(page-faulted). */
6349 	page = find_get_page(mapping, pgoff);
6350 
6351 #ifdef CONFIG_SWAP
6352 	/* shmem/tmpfs may report page out on swap: account for that too. */
6353 	if (radix_tree_exceptional_entry(page)) {
6354 		swp_entry_t swap = radix_to_swp_entry(page);
6355 		if (do_swap_account)
6356 			*entry = swap;
6357 		page = find_get_page(swap_address_space(swap), swap.val);
6358 	}
6359 #endif
6360 	return page;
6361 }
6362 
6363 static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
6364 		unsigned long addr, pte_t ptent, union mc_target *target)
6365 {
6366 	struct page *page = NULL;
6367 	struct page_cgroup *pc;
6368 	enum mc_target_type ret = MC_TARGET_NONE;
6369 	swp_entry_t ent = { .val = 0 };
6370 
6371 	if (pte_present(ptent))
6372 		page = mc_handle_present_pte(vma, addr, ptent);
6373 	else if (is_swap_pte(ptent))
6374 		page = mc_handle_swap_pte(vma, addr, ptent, &ent);
6375 	else if (pte_none(ptent) || pte_file(ptent))
6376 		page = mc_handle_file_pte(vma, addr, ptent, &ent);
6377 
6378 	if (!page && !ent.val)
6379 		return ret;
6380 	if (page) {
6381 		pc = lookup_page_cgroup(page);
6382 		/*
6383 		 * Do only loose check w/o page_cgroup lock.
6384 		 * mem_cgroup_move_account() checks the pc is valid or not under
6385 		 * the lock.
6386 		 */
6387 		if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
6388 			ret = MC_TARGET_PAGE;
6389 			if (target)
6390 				target->page = page;
6391 		}
6392 		if (!ret || !target)
6393 			put_page(page);
6394 	}
6395 	/* There is a swap entry and a page doesn't exist or isn't charged */
6396 	if (ent.val && !ret &&
6397 			css_id(&mc.from->css) == lookup_swap_cgroup_id(ent)) {
6398 		ret = MC_TARGET_SWAP;
6399 		if (target)
6400 			target->ent = ent;
6401 	}
6402 	return ret;
6403 }
6404 
6405 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
6406 /*
6407  * We don't consider swapping or file mapped pages because THP does not
6408  * support them for now.
6409  * Caller should make sure that pmd_trans_huge(pmd) is true.
6410  */
6411 static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
6412 		unsigned long addr, pmd_t pmd, union mc_target *target)
6413 {
6414 	struct page *page = NULL;
6415 	struct page_cgroup *pc;
6416 	enum mc_target_type ret = MC_TARGET_NONE;
6417 
6418 	page = pmd_page(pmd);
6419 	VM_BUG_ON(!page || !PageHead(page));
6420 	if (!move_anon())
6421 		return ret;
6422 	pc = lookup_page_cgroup(page);
6423 	if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
6424 		ret = MC_TARGET_PAGE;
6425 		if (target) {
6426 			get_page(page);
6427 			target->page = page;
6428 		}
6429 	}
6430 	return ret;
6431 }
6432 #else
6433 static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
6434 		unsigned long addr, pmd_t pmd, union mc_target *target)
6435 {
6436 	return MC_TARGET_NONE;
6437 }
6438 #endif
6439 
6440 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
6441 					unsigned long addr, unsigned long end,
6442 					struct mm_walk *walk)
6443 {
6444 	struct vm_area_struct *vma = walk->private;
6445 	pte_t *pte;
6446 	spinlock_t *ptl;
6447 
6448 	if (pmd_trans_huge_lock(pmd, vma) == 1) {
6449 		if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
6450 			mc.precharge += HPAGE_PMD_NR;
6451 		spin_unlock(&vma->vm_mm->page_table_lock);
6452 		return 0;
6453 	}
6454 
6455 	if (pmd_trans_unstable(pmd))
6456 		return 0;
6457 	pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6458 	for (; addr != end; pte++, addr += PAGE_SIZE)
6459 		if (get_mctgt_type(vma, addr, *pte, NULL))
6460 			mc.precharge++;	/* increment precharge temporarily */
6461 	pte_unmap_unlock(pte - 1, ptl);
6462 	cond_resched();
6463 
6464 	return 0;
6465 }
6466 
6467 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
6468 {
6469 	unsigned long precharge;
6470 	struct vm_area_struct *vma;
6471 
6472 	down_read(&mm->mmap_sem);
6473 	for (vma = mm->mmap; vma; vma = vma->vm_next) {
6474 		struct mm_walk mem_cgroup_count_precharge_walk = {
6475 			.pmd_entry = mem_cgroup_count_precharge_pte_range,
6476 			.mm = mm,
6477 			.private = vma,
6478 		};
6479 		if (is_vm_hugetlb_page(vma))
6480 			continue;
6481 		walk_page_range(vma->vm_start, vma->vm_end,
6482 					&mem_cgroup_count_precharge_walk);
6483 	}
6484 	up_read(&mm->mmap_sem);
6485 
6486 	precharge = mc.precharge;
6487 	mc.precharge = 0;
6488 
6489 	return precharge;
6490 }
6491 
6492 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
6493 {
6494 	unsigned long precharge = mem_cgroup_count_precharge(mm);
6495 
6496 	VM_BUG_ON(mc.moving_task);
6497 	mc.moving_task = current;
6498 	return mem_cgroup_do_precharge(precharge);
6499 }
6500 
6501 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
6502 static void __mem_cgroup_clear_mc(void)
6503 {
6504 	struct mem_cgroup *from = mc.from;
6505 	struct mem_cgroup *to = mc.to;
6506 
6507 	/* we must uncharge all the leftover precharges from mc.to */
6508 	if (mc.precharge) {
6509 		__mem_cgroup_cancel_charge(mc.to, mc.precharge);
6510 		mc.precharge = 0;
6511 	}
6512 	/*
6513 	 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
6514 	 * we must uncharge here.
6515 	 */
6516 	if (mc.moved_charge) {
6517 		__mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
6518 		mc.moved_charge = 0;
6519 	}
6520 	/* we must fixup refcnts and charges */
6521 	if (mc.moved_swap) {
6522 		/* uncharge swap account from the old cgroup */
6523 		if (!mem_cgroup_is_root(mc.from))
6524 			res_counter_uncharge(&mc.from->memsw,
6525 						PAGE_SIZE * mc.moved_swap);
6526 		__mem_cgroup_put(mc.from, mc.moved_swap);
6527 
6528 		if (!mem_cgroup_is_root(mc.to)) {
6529 			/*
6530 			 * we charged both to->res and to->memsw, so we should
6531 			 * uncharge to->res.
6532 			 */
6533 			res_counter_uncharge(&mc.to->res,
6534 						PAGE_SIZE * mc.moved_swap);
6535 		}
6536 		/* we've already done mem_cgroup_get(mc.to) */
6537 		mc.moved_swap = 0;
6538 	}
6539 	memcg_oom_recover(from);
6540 	memcg_oom_recover(to);
6541 	wake_up_all(&mc.waitq);
6542 }
6543 
6544 static void mem_cgroup_clear_mc(void)
6545 {
6546 	struct mem_cgroup *from = mc.from;
6547 
6548 	/*
6549 	 * we must clear moving_task before waking up waiters at the end of
6550 	 * task migration.
6551 	 */
6552 	mc.moving_task = NULL;
6553 	__mem_cgroup_clear_mc();
6554 	spin_lock(&mc.lock);
6555 	mc.from = NULL;
6556 	mc.to = NULL;
6557 	spin_unlock(&mc.lock);
6558 	mem_cgroup_end_move(from);
6559 }
6560 
6561 static int mem_cgroup_can_attach(struct cgroup *cgroup,
6562 				 struct cgroup_taskset *tset)
6563 {
6564 	struct task_struct *p = cgroup_taskset_first(tset);
6565 	int ret = 0;
6566 	struct mem_cgroup *memcg = mem_cgroup_from_cont(cgroup);
6567 	unsigned long move_charge_at_immigrate;
6568 
6569 	/*
6570 	 * We are now commited to this value whatever it is. Changes in this
6571 	 * tunable will only affect upcoming migrations, not the current one.
6572 	 * So we need to save it, and keep it going.
6573 	 */
6574 	move_charge_at_immigrate  = memcg->move_charge_at_immigrate;
6575 	if (move_charge_at_immigrate) {
6576 		struct mm_struct *mm;
6577 		struct mem_cgroup *from = mem_cgroup_from_task(p);
6578 
6579 		VM_BUG_ON(from == memcg);
6580 
6581 		mm = get_task_mm(p);
6582 		if (!mm)
6583 			return 0;
6584 		/* We move charges only when we move a owner of the mm */
6585 		if (mm->owner == p) {
6586 			VM_BUG_ON(mc.from);
6587 			VM_BUG_ON(mc.to);
6588 			VM_BUG_ON(mc.precharge);
6589 			VM_BUG_ON(mc.moved_charge);
6590 			VM_BUG_ON(mc.moved_swap);
6591 			mem_cgroup_start_move(from);
6592 			spin_lock(&mc.lock);
6593 			mc.from = from;
6594 			mc.to = memcg;
6595 			mc.immigrate_flags = move_charge_at_immigrate;
6596 			spin_unlock(&mc.lock);
6597 			/* We set mc.moving_task later */
6598 
6599 			ret = mem_cgroup_precharge_mc(mm);
6600 			if (ret)
6601 				mem_cgroup_clear_mc();
6602 		}
6603 		mmput(mm);
6604 	}
6605 	return ret;
6606 }
6607 
6608 static void mem_cgroup_cancel_attach(struct cgroup *cgroup,
6609 				     struct cgroup_taskset *tset)
6610 {
6611 	mem_cgroup_clear_mc();
6612 }
6613 
6614 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
6615 				unsigned long addr, unsigned long end,
6616 				struct mm_walk *walk)
6617 {
6618 	int ret = 0;
6619 	struct vm_area_struct *vma = walk->private;
6620 	pte_t *pte;
6621 	spinlock_t *ptl;
6622 	enum mc_target_type target_type;
6623 	union mc_target target;
6624 	struct page *page;
6625 	struct page_cgroup *pc;
6626 
6627 	/*
6628 	 * We don't take compound_lock() here but no race with splitting thp
6629 	 * happens because:
6630 	 *  - if pmd_trans_huge_lock() returns 1, the relevant thp is not
6631 	 *    under splitting, which means there's no concurrent thp split,
6632 	 *  - if another thread runs into split_huge_page() just after we
6633 	 *    entered this if-block, the thread must wait for page table lock
6634 	 *    to be unlocked in __split_huge_page_splitting(), where the main
6635 	 *    part of thp split is not executed yet.
6636 	 */
6637 	if (pmd_trans_huge_lock(pmd, vma) == 1) {
6638 		if (mc.precharge < HPAGE_PMD_NR) {
6639 			spin_unlock(&vma->vm_mm->page_table_lock);
6640 			return 0;
6641 		}
6642 		target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
6643 		if (target_type == MC_TARGET_PAGE) {
6644 			page = target.page;
6645 			if (!isolate_lru_page(page)) {
6646 				pc = lookup_page_cgroup(page);
6647 				if (!mem_cgroup_move_account(page, HPAGE_PMD_NR,
6648 							pc, mc.from, mc.to)) {
6649 					mc.precharge -= HPAGE_PMD_NR;
6650 					mc.moved_charge += HPAGE_PMD_NR;
6651 				}
6652 				putback_lru_page(page);
6653 			}
6654 			put_page(page);
6655 		}
6656 		spin_unlock(&vma->vm_mm->page_table_lock);
6657 		return 0;
6658 	}
6659 
6660 	if (pmd_trans_unstable(pmd))
6661 		return 0;
6662 retry:
6663 	pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6664 	for (; addr != end; addr += PAGE_SIZE) {
6665 		pte_t ptent = *(pte++);
6666 		swp_entry_t ent;
6667 
6668 		if (!mc.precharge)
6669 			break;
6670 
6671 		switch (get_mctgt_type(vma, addr, ptent, &target)) {
6672 		case MC_TARGET_PAGE:
6673 			page = target.page;
6674 			if (isolate_lru_page(page))
6675 				goto put;
6676 			pc = lookup_page_cgroup(page);
6677 			if (!mem_cgroup_move_account(page, 1, pc,
6678 						     mc.from, mc.to)) {
6679 				mc.precharge--;
6680 				/* we uncharge from mc.from later. */
6681 				mc.moved_charge++;
6682 			}
6683 			putback_lru_page(page);
6684 put:			/* get_mctgt_type() gets the page */
6685 			put_page(page);
6686 			break;
6687 		case MC_TARGET_SWAP:
6688 			ent = target.ent;
6689 			if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
6690 				mc.precharge--;
6691 				/* we fixup refcnts and charges later. */
6692 				mc.moved_swap++;
6693 			}
6694 			break;
6695 		default:
6696 			break;
6697 		}
6698 	}
6699 	pte_unmap_unlock(pte - 1, ptl);
6700 	cond_resched();
6701 
6702 	if (addr != end) {
6703 		/*
6704 		 * We have consumed all precharges we got in can_attach().
6705 		 * We try charge one by one, but don't do any additional
6706 		 * charges to mc.to if we have failed in charge once in attach()
6707 		 * phase.
6708 		 */
6709 		ret = mem_cgroup_do_precharge(1);
6710 		if (!ret)
6711 			goto retry;
6712 	}
6713 
6714 	return ret;
6715 }
6716 
6717 static void mem_cgroup_move_charge(struct mm_struct *mm)
6718 {
6719 	struct vm_area_struct *vma;
6720 
6721 	lru_add_drain_all();
6722 retry:
6723 	if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
6724 		/*
6725 		 * Someone who are holding the mmap_sem might be waiting in
6726 		 * waitq. So we cancel all extra charges, wake up all waiters,
6727 		 * and retry. Because we cancel precharges, we might not be able
6728 		 * to move enough charges, but moving charge is a best-effort
6729 		 * feature anyway, so it wouldn't be a big problem.
6730 		 */
6731 		__mem_cgroup_clear_mc();
6732 		cond_resched();
6733 		goto retry;
6734 	}
6735 	for (vma = mm->mmap; vma; vma = vma->vm_next) {
6736 		int ret;
6737 		struct mm_walk mem_cgroup_move_charge_walk = {
6738 			.pmd_entry = mem_cgroup_move_charge_pte_range,
6739 			.mm = mm,
6740 			.private = vma,
6741 		};
6742 		if (is_vm_hugetlb_page(vma))
6743 			continue;
6744 		ret = walk_page_range(vma->vm_start, vma->vm_end,
6745 						&mem_cgroup_move_charge_walk);
6746 		if (ret)
6747 			/*
6748 			 * means we have consumed all precharges and failed in
6749 			 * doing additional charge. Just abandon here.
6750 			 */
6751 			break;
6752 	}
6753 	up_read(&mm->mmap_sem);
6754 }
6755 
6756 static void mem_cgroup_move_task(struct cgroup *cont,
6757 				 struct cgroup_taskset *tset)
6758 {
6759 	struct task_struct *p = cgroup_taskset_first(tset);
6760 	struct mm_struct *mm = get_task_mm(p);
6761 
6762 	if (mm) {
6763 		if (mc.to)
6764 			mem_cgroup_move_charge(mm);
6765 		mmput(mm);
6766 	}
6767 	if (mc.to)
6768 		mem_cgroup_clear_mc();
6769 }
6770 #else	/* !CONFIG_MMU */
6771 static int mem_cgroup_can_attach(struct cgroup *cgroup,
6772 				 struct cgroup_taskset *tset)
6773 {
6774 	return 0;
6775 }
6776 static void mem_cgroup_cancel_attach(struct cgroup *cgroup,
6777 				     struct cgroup_taskset *tset)
6778 {
6779 }
6780 static void mem_cgroup_move_task(struct cgroup *cont,
6781 				 struct cgroup_taskset *tset)
6782 {
6783 }
6784 #endif
6785 
6786 struct cgroup_subsys mem_cgroup_subsys = {
6787 	.name = "memory",
6788 	.subsys_id = mem_cgroup_subsys_id,
6789 	.css_alloc = mem_cgroup_css_alloc,
6790 	.css_online = mem_cgroup_css_online,
6791 	.css_offline = mem_cgroup_css_offline,
6792 	.css_free = mem_cgroup_css_free,
6793 	.can_attach = mem_cgroup_can_attach,
6794 	.cancel_attach = mem_cgroup_cancel_attach,
6795 	.attach = mem_cgroup_move_task,
6796 	.base_cftypes = mem_cgroup_files,
6797 	.early_init = 0,
6798 	.use_id = 1,
6799 };
6800 
6801 #ifdef CONFIG_MEMCG_SWAP
6802 static int __init enable_swap_account(char *s)
6803 {
6804 	/* consider enabled if no parameter or 1 is given */
6805 	if (!strcmp(s, "1"))
6806 		really_do_swap_account = 1;
6807 	else if (!strcmp(s, "0"))
6808 		really_do_swap_account = 0;
6809 	return 1;
6810 }
6811 __setup("swapaccount=", enable_swap_account);
6812 
6813 static void __init memsw_file_init(void)
6814 {
6815 	WARN_ON(cgroup_add_cftypes(&mem_cgroup_subsys, memsw_cgroup_files));
6816 }
6817 
6818 static void __init enable_swap_cgroup(void)
6819 {
6820 	if (!mem_cgroup_disabled() && really_do_swap_account) {
6821 		do_swap_account = 1;
6822 		memsw_file_init();
6823 	}
6824 }
6825 
6826 #else
6827 static void __init enable_swap_cgroup(void)
6828 {
6829 }
6830 #endif
6831 
6832 /*
6833  * subsys_initcall() for memory controller.
6834  *
6835  * Some parts like hotcpu_notifier() have to be initialized from this context
6836  * because of lock dependencies (cgroup_lock -> cpu hotplug) but basically
6837  * everything that doesn't depend on a specific mem_cgroup structure should
6838  * be initialized from here.
6839  */
6840 static int __init mem_cgroup_init(void)
6841 {
6842 	hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
6843 	enable_swap_cgroup();
6844 	mem_cgroup_soft_limit_tree_init();
6845 	memcg_stock_init();
6846 	return 0;
6847 }
6848 subsys_initcall(mem_cgroup_init);
6849