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