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