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