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