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