]> rtime.felk.cvut.cz Git - can-eth-gw-linux.git/blob - mm/memcontrol.c
memcg: remove unused retry signal from reclaim
[can-eth-gw-linux.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  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 2 of the License, or
16  * (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  */
23
24 #include <linux/res_counter.h>
25 #include <linux/memcontrol.h>
26 #include <linux/cgroup.h>
27 #include <linux/mm.h>
28 #include <linux/hugetlb.h>
29 #include <linux/pagemap.h>
30 #include <linux/smp.h>
31 #include <linux/page-flags.h>
32 #include <linux/backing-dev.h>
33 #include <linux/bit_spinlock.h>
34 #include <linux/rcupdate.h>
35 #include <linux/limits.h>
36 #include <linux/mutex.h>
37 #include <linux/rbtree.h>
38 #include <linux/slab.h>
39 #include <linux/swap.h>
40 #include <linux/swapops.h>
41 #include <linux/spinlock.h>
42 #include <linux/eventfd.h>
43 #include <linux/sort.h>
44 #include <linux/fs.h>
45 #include <linux/seq_file.h>
46 #include <linux/vmalloc.h>
47 #include <linux/mm_inline.h>
48 #include <linux/page_cgroup.h>
49 #include <linux/cpu.h>
50 #include <linux/oom.h>
51 #include "internal.h"
52
53 #include <asm/uaccess.h>
54
55 #include <trace/events/vmscan.h>
56
57 struct cgroup_subsys mem_cgroup_subsys __read_mostly;
58 #define MEM_CGROUP_RECLAIM_RETRIES      5
59 struct mem_cgroup *root_mem_cgroup __read_mostly;
60
61 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
62 /* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
63 int do_swap_account __read_mostly;
64
65 /* for remember boot option*/
66 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP_ENABLED
67 static int really_do_swap_account __initdata = 1;
68 #else
69 static int really_do_swap_account __initdata = 0;
70 #endif
71
72 #else
73 #define do_swap_account         (0)
74 #endif
75
76
77 /*
78  * Statistics for memory cgroup.
79  */
80 enum mem_cgroup_stat_index {
81         /*
82          * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
83          */
84         MEM_CGROUP_STAT_CACHE,     /* # of pages charged as cache */
85         MEM_CGROUP_STAT_RSS,       /* # of pages charged as anon rss */
86         MEM_CGROUP_STAT_FILE_MAPPED,  /* # of pages charged as file rss */
87         MEM_CGROUP_STAT_SWAPOUT, /* # of pages, swapped out */
88         MEM_CGROUP_STAT_DATA, /* end of data requires synchronization */
89         MEM_CGROUP_ON_MOVE,     /* someone is moving account between groups */
90         MEM_CGROUP_STAT_NSTATS,
91 };
92
93 enum mem_cgroup_events_index {
94         MEM_CGROUP_EVENTS_PGPGIN,       /* # of pages paged in */
95         MEM_CGROUP_EVENTS_PGPGOUT,      /* # of pages paged out */
96         MEM_CGROUP_EVENTS_COUNT,        /* # of pages paged in/out */
97         MEM_CGROUP_EVENTS_NSTATS,
98 };
99 /*
100  * Per memcg event counter is incremented at every pagein/pageout. With THP,
101  * it will be incremated by the number of pages. This counter is used for
102  * for trigger some periodic events. This is straightforward and better
103  * than using jiffies etc. to handle periodic memcg event.
104  */
105 enum mem_cgroup_events_target {
106         MEM_CGROUP_TARGET_THRESH,
107         MEM_CGROUP_TARGET_SOFTLIMIT,
108         MEM_CGROUP_NTARGETS,
109 };
110 #define THRESHOLDS_EVENTS_TARGET (128)
111 #define SOFTLIMIT_EVENTS_TARGET (1024)
112
113 struct mem_cgroup_stat_cpu {
114         long count[MEM_CGROUP_STAT_NSTATS];
115         unsigned long events[MEM_CGROUP_EVENTS_NSTATS];
116         unsigned long targets[MEM_CGROUP_NTARGETS];
117 };
118
119 /*
120  * per-zone information in memory controller.
121  */
122 struct mem_cgroup_per_zone {
123         /*
124          * spin_lock to protect the per cgroup LRU
125          */
126         struct list_head        lists[NR_LRU_LISTS];
127         unsigned long           count[NR_LRU_LISTS];
128
129         struct zone_reclaim_stat reclaim_stat;
130         struct rb_node          tree_node;      /* RB tree node */
131         unsigned long long      usage_in_excess;/* Set to the value by which */
132                                                 /* the soft limit is exceeded*/
133         bool                    on_tree;
134         struct mem_cgroup       *mem;           /* Back pointer, we cannot */
135                                                 /* use container_of        */
136 };
137 /* Macro for accessing counter */
138 #define MEM_CGROUP_ZSTAT(mz, idx)       ((mz)->count[(idx)])
139
140 struct mem_cgroup_per_node {
141         struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
142 };
143
144 struct mem_cgroup_lru_info {
145         struct mem_cgroup_per_node *nodeinfo[MAX_NUMNODES];
146 };
147
148 /*
149  * Cgroups above their limits are maintained in a RB-Tree, independent of
150  * their hierarchy representation
151  */
152
153 struct mem_cgroup_tree_per_zone {
154         struct rb_root rb_root;
155         spinlock_t lock;
156 };
157
158 struct mem_cgroup_tree_per_node {
159         struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
160 };
161
162 struct mem_cgroup_tree {
163         struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
164 };
165
166 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
167
168 struct mem_cgroup_threshold {
169         struct eventfd_ctx *eventfd;
170         u64 threshold;
171 };
172
173 /* For threshold */
174 struct mem_cgroup_threshold_ary {
175         /* An array index points to threshold just below usage. */
176         int current_threshold;
177         /* Size of entries[] */
178         unsigned int size;
179         /* Array of thresholds */
180         struct mem_cgroup_threshold entries[0];
181 };
182
183 struct mem_cgroup_thresholds {
184         /* Primary thresholds array */
185         struct mem_cgroup_threshold_ary *primary;
186         /*
187          * Spare threshold array.
188          * This is needed to make mem_cgroup_unregister_event() "never fail".
189          * It must be able to store at least primary->size - 1 entries.
190          */
191         struct mem_cgroup_threshold_ary *spare;
192 };
193
194 /* for OOM */
195 struct mem_cgroup_eventfd_list {
196         struct list_head list;
197         struct eventfd_ctx *eventfd;
198 };
199
200 static void mem_cgroup_threshold(struct mem_cgroup *mem);
201 static void mem_cgroup_oom_notify(struct mem_cgroup *mem);
202
203 /*
204  * The memory controller data structure. The memory controller controls both
205  * page cache and RSS per cgroup. We would eventually like to provide
206  * statistics based on the statistics developed by Rik Van Riel for clock-pro,
207  * to help the administrator determine what knobs to tune.
208  *
209  * TODO: Add a water mark for the memory controller. Reclaim will begin when
210  * we hit the water mark. May be even add a low water mark, such that
211  * no reclaim occurs from a cgroup at it's low water mark, this is
212  * a feature that will be implemented much later in the future.
213  */
214 struct mem_cgroup {
215         struct cgroup_subsys_state css;
216         /*
217          * the counter to account for memory usage
218          */
219         struct res_counter res;
220         /*
221          * the counter to account for mem+swap usage.
222          */
223         struct res_counter memsw;
224         /*
225          * Per cgroup active and inactive list, similar to the
226          * per zone LRU lists.
227          */
228         struct mem_cgroup_lru_info info;
229         /*
230          * While reclaiming in a hierarchy, we cache the last child we
231          * reclaimed from.
232          */
233         int last_scanned_child;
234         int last_scanned_node;
235 #if MAX_NUMNODES > 1
236         nodemask_t      scan_nodes;
237         unsigned long   next_scan_node_update;
238 #endif
239         /*
240          * Should the accounting and control be hierarchical, per subtree?
241          */
242         bool use_hierarchy;
243         atomic_t        oom_lock;
244         atomic_t        refcnt;
245
246         unsigned int    swappiness;
247         /* OOM-Killer disable */
248         int             oom_kill_disable;
249
250         /* set when res.limit == memsw.limit */
251         bool            memsw_is_minimum;
252
253         /* protect arrays of thresholds */
254         struct mutex thresholds_lock;
255
256         /* thresholds for memory usage. RCU-protected */
257         struct mem_cgroup_thresholds thresholds;
258
259         /* thresholds for mem+swap usage. RCU-protected */
260         struct mem_cgroup_thresholds memsw_thresholds;
261
262         /* For oom notifier event fd */
263         struct list_head oom_notify;
264
265         /*
266          * Should we move charges of a task when a task is moved into this
267          * mem_cgroup ? And what type of charges should we move ?
268          */
269         unsigned long   move_charge_at_immigrate;
270         /*
271          * percpu counter.
272          */
273         struct mem_cgroup_stat_cpu *stat;
274         /*
275          * used when a cpu is offlined or other synchronizations
276          * See mem_cgroup_read_stat().
277          */
278         struct mem_cgroup_stat_cpu nocpu_base;
279         spinlock_t pcp_counter_lock;
280 };
281
282 /* Stuffs for move charges at task migration. */
283 /*
284  * Types of charges to be moved. "move_charge_at_immitgrate" is treated as a
285  * left-shifted bitmap of these types.
286  */
287 enum move_type {
288         MOVE_CHARGE_TYPE_ANON,  /* private anonymous page and swap of it */
289         MOVE_CHARGE_TYPE_FILE,  /* file page(including tmpfs) and swap of it */
290         NR_MOVE_TYPE,
291 };
292
293 /* "mc" and its members are protected by cgroup_mutex */
294 static struct move_charge_struct {
295         spinlock_t        lock; /* for from, to */
296         struct mem_cgroup *from;
297         struct mem_cgroup *to;
298         unsigned long precharge;
299         unsigned long moved_charge;
300         unsigned long moved_swap;
301         struct task_struct *moving_task;        /* a task moving charges */
302         wait_queue_head_t waitq;                /* a waitq for other context */
303 } mc = {
304         .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
305         .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
306 };
307
308 static bool move_anon(void)
309 {
310         return test_bit(MOVE_CHARGE_TYPE_ANON,
311                                         &mc.to->move_charge_at_immigrate);
312 }
313
314 static bool move_file(void)
315 {
316         return test_bit(MOVE_CHARGE_TYPE_FILE,
317                                         &mc.to->move_charge_at_immigrate);
318 }
319
320 /*
321  * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
322  * limit reclaim to prevent infinite loops, if they ever occur.
323  */
324 #define MEM_CGROUP_MAX_RECLAIM_LOOPS            (100)
325 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS (2)
326
327 enum charge_type {
328         MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
329         MEM_CGROUP_CHARGE_TYPE_MAPPED,
330         MEM_CGROUP_CHARGE_TYPE_SHMEM,   /* used by page migration of shmem */
331         MEM_CGROUP_CHARGE_TYPE_FORCE,   /* used by force_empty */
332         MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
333         MEM_CGROUP_CHARGE_TYPE_DROP,    /* a page was unused swap cache */
334         NR_CHARGE_TYPE,
335 };
336
337 /* for encoding cft->private value on file */
338 #define _MEM                    (0)
339 #define _MEMSWAP                (1)
340 #define _OOM_TYPE               (2)
341 #define MEMFILE_PRIVATE(x, val) (((x) << 16) | (val))
342 #define MEMFILE_TYPE(val)       (((val) >> 16) & 0xffff)
343 #define MEMFILE_ATTR(val)       ((val) & 0xffff)
344 /* Used for OOM nofiier */
345 #define OOM_CONTROL             (0)
346
347 /*
348  * Reclaim flags for mem_cgroup_hierarchical_reclaim
349  */
350 #define MEM_CGROUP_RECLAIM_NOSWAP_BIT   0x0
351 #define MEM_CGROUP_RECLAIM_NOSWAP       (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
352 #define MEM_CGROUP_RECLAIM_SHRINK_BIT   0x1
353 #define MEM_CGROUP_RECLAIM_SHRINK       (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
354 #define MEM_CGROUP_RECLAIM_SOFT_BIT     0x2
355 #define MEM_CGROUP_RECLAIM_SOFT         (1 << MEM_CGROUP_RECLAIM_SOFT_BIT)
356
357 static void mem_cgroup_get(struct mem_cgroup *mem);
358 static void mem_cgroup_put(struct mem_cgroup *mem);
359 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem);
360 static void drain_all_stock_async(void);
361
362 static struct mem_cgroup_per_zone *
363 mem_cgroup_zoneinfo(struct mem_cgroup *mem, int nid, int zid)
364 {
365         return &mem->info.nodeinfo[nid]->zoneinfo[zid];
366 }
367
368 struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *mem)
369 {
370         return &mem->css;
371 }
372
373 static struct mem_cgroup_per_zone *
374 page_cgroup_zoneinfo(struct mem_cgroup *mem, struct page *page)
375 {
376         int nid = page_to_nid(page);
377         int zid = page_zonenum(page);
378
379         return mem_cgroup_zoneinfo(mem, nid, zid);
380 }
381
382 static struct mem_cgroup_tree_per_zone *
383 soft_limit_tree_node_zone(int nid, int zid)
384 {
385         return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
386 }
387
388 static struct mem_cgroup_tree_per_zone *
389 soft_limit_tree_from_page(struct page *page)
390 {
391         int nid = page_to_nid(page);
392         int zid = page_zonenum(page);
393
394         return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
395 }
396
397 static void
398 __mem_cgroup_insert_exceeded(struct mem_cgroup *mem,
399                                 struct mem_cgroup_per_zone *mz,
400                                 struct mem_cgroup_tree_per_zone *mctz,
401                                 unsigned long long new_usage_in_excess)
402 {
403         struct rb_node **p = &mctz->rb_root.rb_node;
404         struct rb_node *parent = NULL;
405         struct mem_cgroup_per_zone *mz_node;
406
407         if (mz->on_tree)
408                 return;
409
410         mz->usage_in_excess = new_usage_in_excess;
411         if (!mz->usage_in_excess)
412                 return;
413         while (*p) {
414                 parent = *p;
415                 mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
416                                         tree_node);
417                 if (mz->usage_in_excess < mz_node->usage_in_excess)
418                         p = &(*p)->rb_left;
419                 /*
420                  * We can't avoid mem cgroups that are over their soft
421                  * limit by the same amount
422                  */
423                 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
424                         p = &(*p)->rb_right;
425         }
426         rb_link_node(&mz->tree_node, parent, p);
427         rb_insert_color(&mz->tree_node, &mctz->rb_root);
428         mz->on_tree = true;
429 }
430
431 static void
432 __mem_cgroup_remove_exceeded(struct mem_cgroup *mem,
433                                 struct mem_cgroup_per_zone *mz,
434                                 struct mem_cgroup_tree_per_zone *mctz)
435 {
436         if (!mz->on_tree)
437                 return;
438         rb_erase(&mz->tree_node, &mctz->rb_root);
439         mz->on_tree = false;
440 }
441
442 static void
443 mem_cgroup_remove_exceeded(struct mem_cgroup *mem,
444                                 struct mem_cgroup_per_zone *mz,
445                                 struct mem_cgroup_tree_per_zone *mctz)
446 {
447         spin_lock(&mctz->lock);
448         __mem_cgroup_remove_exceeded(mem, mz, mctz);
449         spin_unlock(&mctz->lock);
450 }
451
452
453 static void mem_cgroup_update_tree(struct mem_cgroup *mem, struct page *page)
454 {
455         unsigned long long excess;
456         struct mem_cgroup_per_zone *mz;
457         struct mem_cgroup_tree_per_zone *mctz;
458         int nid = page_to_nid(page);
459         int zid = page_zonenum(page);
460         mctz = soft_limit_tree_from_page(page);
461
462         /*
463          * Necessary to update all ancestors when hierarchy is used.
464          * because their event counter is not touched.
465          */
466         for (; mem; mem = parent_mem_cgroup(mem)) {
467                 mz = mem_cgroup_zoneinfo(mem, nid, zid);
468                 excess = res_counter_soft_limit_excess(&mem->res);
469                 /*
470                  * We have to update the tree if mz is on RB-tree or
471                  * mem is over its softlimit.
472                  */
473                 if (excess || mz->on_tree) {
474                         spin_lock(&mctz->lock);
475                         /* if on-tree, remove it */
476                         if (mz->on_tree)
477                                 __mem_cgroup_remove_exceeded(mem, mz, mctz);
478                         /*
479                          * Insert again. mz->usage_in_excess will be updated.
480                          * If excess is 0, no tree ops.
481                          */
482                         __mem_cgroup_insert_exceeded(mem, mz, mctz, excess);
483                         spin_unlock(&mctz->lock);
484                 }
485         }
486 }
487
488 static void mem_cgroup_remove_from_trees(struct mem_cgroup *mem)
489 {
490         int node, zone;
491         struct mem_cgroup_per_zone *mz;
492         struct mem_cgroup_tree_per_zone *mctz;
493
494         for_each_node_state(node, N_POSSIBLE) {
495                 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
496                         mz = mem_cgroup_zoneinfo(mem, node, zone);
497                         mctz = soft_limit_tree_node_zone(node, zone);
498                         mem_cgroup_remove_exceeded(mem, mz, mctz);
499                 }
500         }
501 }
502
503 static struct mem_cgroup_per_zone *
504 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
505 {
506         struct rb_node *rightmost = NULL;
507         struct mem_cgroup_per_zone *mz;
508
509 retry:
510         mz = NULL;
511         rightmost = rb_last(&mctz->rb_root);
512         if (!rightmost)
513                 goto done;              /* Nothing to reclaim from */
514
515         mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
516         /*
517          * Remove the node now but someone else can add it back,
518          * we will to add it back at the end of reclaim to its correct
519          * position in the tree.
520          */
521         __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
522         if (!res_counter_soft_limit_excess(&mz->mem->res) ||
523                 !css_tryget(&mz->mem->css))
524                 goto retry;
525 done:
526         return mz;
527 }
528
529 static struct mem_cgroup_per_zone *
530 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
531 {
532         struct mem_cgroup_per_zone *mz;
533
534         spin_lock(&mctz->lock);
535         mz = __mem_cgroup_largest_soft_limit_node(mctz);
536         spin_unlock(&mctz->lock);
537         return mz;
538 }
539
540 /*
541  * Implementation Note: reading percpu statistics for memcg.
542  *
543  * Both of vmstat[] and percpu_counter has threshold and do periodic
544  * synchronization to implement "quick" read. There are trade-off between
545  * reading cost and precision of value. Then, we may have a chance to implement
546  * a periodic synchronizion of counter in memcg's counter.
547  *
548  * But this _read() function is used for user interface now. The user accounts
549  * memory usage by memory cgroup and he _always_ requires exact value because
550  * he accounts memory. Even if we provide quick-and-fuzzy read, we always
551  * have to visit all online cpus and make sum. So, for now, unnecessary
552  * synchronization is not implemented. (just implemented for cpu hotplug)
553  *
554  * If there are kernel internal actions which can make use of some not-exact
555  * value, and reading all cpu value can be performance bottleneck in some
556  * common workload, threashold and synchonization as vmstat[] should be
557  * implemented.
558  */
559 static long mem_cgroup_read_stat(struct mem_cgroup *mem,
560                                  enum mem_cgroup_stat_index idx)
561 {
562         long val = 0;
563         int cpu;
564
565         get_online_cpus();
566         for_each_online_cpu(cpu)
567                 val += per_cpu(mem->stat->count[idx], cpu);
568 #ifdef CONFIG_HOTPLUG_CPU
569         spin_lock(&mem->pcp_counter_lock);
570         val += mem->nocpu_base.count[idx];
571         spin_unlock(&mem->pcp_counter_lock);
572 #endif
573         put_online_cpus();
574         return val;
575 }
576
577 static long mem_cgroup_local_usage(struct mem_cgroup *mem)
578 {
579         long ret;
580
581         ret = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_RSS);
582         ret += mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_CACHE);
583         return ret;
584 }
585
586 static void mem_cgroup_swap_statistics(struct mem_cgroup *mem,
587                                          bool charge)
588 {
589         int val = (charge) ? 1 : -1;
590         this_cpu_add(mem->stat->count[MEM_CGROUP_STAT_SWAPOUT], val);
591 }
592
593 static unsigned long mem_cgroup_read_events(struct mem_cgroup *mem,
594                                             enum mem_cgroup_events_index idx)
595 {
596         unsigned long val = 0;
597         int cpu;
598
599         for_each_online_cpu(cpu)
600                 val += per_cpu(mem->stat->events[idx], cpu);
601 #ifdef CONFIG_HOTPLUG_CPU
602         spin_lock(&mem->pcp_counter_lock);
603         val += mem->nocpu_base.events[idx];
604         spin_unlock(&mem->pcp_counter_lock);
605 #endif
606         return val;
607 }
608
609 static void mem_cgroup_charge_statistics(struct mem_cgroup *mem,
610                                          bool file, int nr_pages)
611 {
612         preempt_disable();
613
614         if (file)
615                 __this_cpu_add(mem->stat->count[MEM_CGROUP_STAT_CACHE], nr_pages);
616         else
617                 __this_cpu_add(mem->stat->count[MEM_CGROUP_STAT_RSS], nr_pages);
618
619         /* pagein of a big page is an event. So, ignore page size */
620         if (nr_pages > 0)
621                 __this_cpu_inc(mem->stat->events[MEM_CGROUP_EVENTS_PGPGIN]);
622         else {
623                 __this_cpu_inc(mem->stat->events[MEM_CGROUP_EVENTS_PGPGOUT]);
624                 nr_pages = -nr_pages; /* for event */
625         }
626
627         __this_cpu_add(mem->stat->events[MEM_CGROUP_EVENTS_COUNT], nr_pages);
628
629         preempt_enable();
630 }
631
632 static unsigned long
633 mem_cgroup_get_zonestat_node(struct mem_cgroup *mem, int nid, enum lru_list idx)
634 {
635         struct mem_cgroup_per_zone *mz;
636         u64 total = 0;
637         int zid;
638
639         for (zid = 0; zid < MAX_NR_ZONES; zid++) {
640                 mz = mem_cgroup_zoneinfo(mem, nid, zid);
641                 total += MEM_CGROUP_ZSTAT(mz, idx);
642         }
643         return total;
644 }
645 static unsigned long mem_cgroup_get_local_zonestat(struct mem_cgroup *mem,
646                                         enum lru_list idx)
647 {
648         int nid;
649         u64 total = 0;
650
651         for_each_online_node(nid)
652                 total += mem_cgroup_get_zonestat_node(mem, nid, idx);
653         return total;
654 }
655
656 static bool __memcg_event_check(struct mem_cgroup *mem, int target)
657 {
658         unsigned long val, next;
659
660         val = this_cpu_read(mem->stat->events[MEM_CGROUP_EVENTS_COUNT]);
661         next = this_cpu_read(mem->stat->targets[target]);
662         /* from time_after() in jiffies.h */
663         return ((long)next - (long)val < 0);
664 }
665
666 static void __mem_cgroup_target_update(struct mem_cgroup *mem, int target)
667 {
668         unsigned long val, next;
669
670         val = this_cpu_read(mem->stat->events[MEM_CGROUP_EVENTS_COUNT]);
671
672         switch (target) {
673         case MEM_CGROUP_TARGET_THRESH:
674                 next = val + THRESHOLDS_EVENTS_TARGET;
675                 break;
676         case MEM_CGROUP_TARGET_SOFTLIMIT:
677                 next = val + SOFTLIMIT_EVENTS_TARGET;
678                 break;
679         default:
680                 return;
681         }
682
683         this_cpu_write(mem->stat->targets[target], next);
684 }
685
686 /*
687  * Check events in order.
688  *
689  */
690 static void memcg_check_events(struct mem_cgroup *mem, struct page *page)
691 {
692         /* threshold event is triggered in finer grain than soft limit */
693         if (unlikely(__memcg_event_check(mem, MEM_CGROUP_TARGET_THRESH))) {
694                 mem_cgroup_threshold(mem);
695                 __mem_cgroup_target_update(mem, MEM_CGROUP_TARGET_THRESH);
696                 if (unlikely(__memcg_event_check(mem,
697                         MEM_CGROUP_TARGET_SOFTLIMIT))){
698                         mem_cgroup_update_tree(mem, page);
699                         __mem_cgroup_target_update(mem,
700                                 MEM_CGROUP_TARGET_SOFTLIMIT);
701                 }
702         }
703 }
704
705 static struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
706 {
707         return container_of(cgroup_subsys_state(cont,
708                                 mem_cgroup_subsys_id), struct mem_cgroup,
709                                 css);
710 }
711
712 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
713 {
714         /*
715          * mm_update_next_owner() may clear mm->owner to NULL
716          * if it races with swapoff, page migration, etc.
717          * So this can be called with p == NULL.
718          */
719         if (unlikely(!p))
720                 return NULL;
721
722         return container_of(task_subsys_state(p, mem_cgroup_subsys_id),
723                                 struct mem_cgroup, css);
724 }
725
726 static struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
727 {
728         struct mem_cgroup *mem = NULL;
729
730         if (!mm)
731                 return NULL;
732         /*
733          * Because we have no locks, mm->owner's may be being moved to other
734          * cgroup. We use css_tryget() here even if this looks
735          * pessimistic (rather than adding locks here).
736          */
737         rcu_read_lock();
738         do {
739                 mem = mem_cgroup_from_task(rcu_dereference(mm->owner));
740                 if (unlikely(!mem))
741                         break;
742         } while (!css_tryget(&mem->css));
743         rcu_read_unlock();
744         return mem;
745 }
746
747 /* The caller has to guarantee "mem" exists before calling this */
748 static struct mem_cgroup *mem_cgroup_start_loop(struct mem_cgroup *mem)
749 {
750         struct cgroup_subsys_state *css;
751         int found;
752
753         if (!mem) /* ROOT cgroup has the smallest ID */
754                 return root_mem_cgroup; /*css_put/get against root is ignored*/
755         if (!mem->use_hierarchy) {
756                 if (css_tryget(&mem->css))
757                         return mem;
758                 return NULL;
759         }
760         rcu_read_lock();
761         /*
762          * searching a memory cgroup which has the smallest ID under given
763          * ROOT cgroup. (ID >= 1)
764          */
765         css = css_get_next(&mem_cgroup_subsys, 1, &mem->css, &found);
766         if (css && css_tryget(css))
767                 mem = container_of(css, struct mem_cgroup, css);
768         else
769                 mem = NULL;
770         rcu_read_unlock();
771         return mem;
772 }
773
774 static struct mem_cgroup *mem_cgroup_get_next(struct mem_cgroup *iter,
775                                         struct mem_cgroup *root,
776                                         bool cond)
777 {
778         int nextid = css_id(&iter->css) + 1;
779         int found;
780         int hierarchy_used;
781         struct cgroup_subsys_state *css;
782
783         hierarchy_used = iter->use_hierarchy;
784
785         css_put(&iter->css);
786         /* If no ROOT, walk all, ignore hierarchy */
787         if (!cond || (root && !hierarchy_used))
788                 return NULL;
789
790         if (!root)
791                 root = root_mem_cgroup;
792
793         do {
794                 iter = NULL;
795                 rcu_read_lock();
796
797                 css = css_get_next(&mem_cgroup_subsys, nextid,
798                                 &root->css, &found);
799                 if (css && css_tryget(css))
800                         iter = container_of(css, struct mem_cgroup, css);
801                 rcu_read_unlock();
802                 /* If css is NULL, no more cgroups will be found */
803                 nextid = found + 1;
804         } while (css && !iter);
805
806         return iter;
807 }
808 /*
809  * for_eacn_mem_cgroup_tree() for visiting all cgroup under tree. Please
810  * be careful that "break" loop is not allowed. We have reference count.
811  * Instead of that modify "cond" to be false and "continue" to exit the loop.
812  */
813 #define for_each_mem_cgroup_tree_cond(iter, root, cond) \
814         for (iter = mem_cgroup_start_loop(root);\
815              iter != NULL;\
816              iter = mem_cgroup_get_next(iter, root, cond))
817
818 #define for_each_mem_cgroup_tree(iter, root) \
819         for_each_mem_cgroup_tree_cond(iter, root, true)
820
821 #define for_each_mem_cgroup_all(iter) \
822         for_each_mem_cgroup_tree_cond(iter, NULL, true)
823
824
825 static inline bool mem_cgroup_is_root(struct mem_cgroup *mem)
826 {
827         return (mem == root_mem_cgroup);
828 }
829
830 /*
831  * Following LRU functions are allowed to be used without PCG_LOCK.
832  * Operations are called by routine of global LRU independently from memcg.
833  * What we have to take care of here is validness of pc->mem_cgroup.
834  *
835  * Changes to pc->mem_cgroup happens when
836  * 1. charge
837  * 2. moving account
838  * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
839  * It is added to LRU before charge.
840  * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
841  * When moving account, the page is not on LRU. It's isolated.
842  */
843
844 void mem_cgroup_del_lru_list(struct page *page, enum lru_list lru)
845 {
846         struct page_cgroup *pc;
847         struct mem_cgroup_per_zone *mz;
848
849         if (mem_cgroup_disabled())
850                 return;
851         pc = lookup_page_cgroup(page);
852         /* can happen while we handle swapcache. */
853         if (!TestClearPageCgroupAcctLRU(pc))
854                 return;
855         VM_BUG_ON(!pc->mem_cgroup);
856         /*
857          * We don't check PCG_USED bit. It's cleared when the "page" is finally
858          * removed from global LRU.
859          */
860         mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
861         /* huge page split is done under lru_lock. so, we have no races. */
862         MEM_CGROUP_ZSTAT(mz, lru) -= 1 << compound_order(page);
863         if (mem_cgroup_is_root(pc->mem_cgroup))
864                 return;
865         VM_BUG_ON(list_empty(&pc->lru));
866         list_del_init(&pc->lru);
867 }
868
869 void mem_cgroup_del_lru(struct page *page)
870 {
871         mem_cgroup_del_lru_list(page, page_lru(page));
872 }
873
874 /*
875  * Writeback is about to end against a page which has been marked for immediate
876  * reclaim.  If it still appears to be reclaimable, move it to the tail of the
877  * inactive list.
878  */
879 void mem_cgroup_rotate_reclaimable_page(struct page *page)
880 {
881         struct mem_cgroup_per_zone *mz;
882         struct page_cgroup *pc;
883         enum lru_list lru = page_lru(page);
884
885         if (mem_cgroup_disabled())
886                 return;
887
888         pc = lookup_page_cgroup(page);
889         /* unused or root page is not rotated. */
890         if (!PageCgroupUsed(pc))
891                 return;
892         /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
893         smp_rmb();
894         if (mem_cgroup_is_root(pc->mem_cgroup))
895                 return;
896         mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
897         list_move_tail(&pc->lru, &mz->lists[lru]);
898 }
899
900 void mem_cgroup_rotate_lru_list(struct page *page, enum lru_list lru)
901 {
902         struct mem_cgroup_per_zone *mz;
903         struct page_cgroup *pc;
904
905         if (mem_cgroup_disabled())
906                 return;
907
908         pc = lookup_page_cgroup(page);
909         /* unused or root page is not rotated. */
910         if (!PageCgroupUsed(pc))
911                 return;
912         /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
913         smp_rmb();
914         if (mem_cgroup_is_root(pc->mem_cgroup))
915                 return;
916         mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
917         list_move(&pc->lru, &mz->lists[lru]);
918 }
919
920 void mem_cgroup_add_lru_list(struct page *page, enum lru_list lru)
921 {
922         struct page_cgroup *pc;
923         struct mem_cgroup_per_zone *mz;
924
925         if (mem_cgroup_disabled())
926                 return;
927         pc = lookup_page_cgroup(page);
928         VM_BUG_ON(PageCgroupAcctLRU(pc));
929         if (!PageCgroupUsed(pc))
930                 return;
931         /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
932         smp_rmb();
933         mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
934         /* huge page split is done under lru_lock. so, we have no races. */
935         MEM_CGROUP_ZSTAT(mz, lru) += 1 << compound_order(page);
936         SetPageCgroupAcctLRU(pc);
937         if (mem_cgroup_is_root(pc->mem_cgroup))
938                 return;
939         list_add(&pc->lru, &mz->lists[lru]);
940 }
941
942 /*
943  * At handling SwapCache and other FUSE stuff, pc->mem_cgroup may be changed
944  * while it's linked to lru because the page may be reused after it's fully
945  * uncharged. To handle that, unlink page_cgroup from LRU when charge it again.
946  * It's done under lock_page and expected that zone->lru_lock isnever held.
947  */
948 static void mem_cgroup_lru_del_before_commit(struct page *page)
949 {
950         unsigned long flags;
951         struct zone *zone = page_zone(page);
952         struct page_cgroup *pc = lookup_page_cgroup(page);
953
954         /*
955          * Doing this check without taking ->lru_lock seems wrong but this
956          * is safe. Because if page_cgroup's USED bit is unset, the page
957          * will not be added to any memcg's LRU. If page_cgroup's USED bit is
958          * set, the commit after this will fail, anyway.
959          * This all charge/uncharge is done under some mutual execustion.
960          * So, we don't need to taking care of changes in USED bit.
961          */
962         if (likely(!PageLRU(page)))
963                 return;
964
965         spin_lock_irqsave(&zone->lru_lock, flags);
966         /*
967          * Forget old LRU when this page_cgroup is *not* used. This Used bit
968          * is guarded by lock_page() because the page is SwapCache.
969          */
970         if (!PageCgroupUsed(pc))
971                 mem_cgroup_del_lru_list(page, page_lru(page));
972         spin_unlock_irqrestore(&zone->lru_lock, flags);
973 }
974
975 static void mem_cgroup_lru_add_after_commit(struct page *page)
976 {
977         unsigned long flags;
978         struct zone *zone = page_zone(page);
979         struct page_cgroup *pc = lookup_page_cgroup(page);
980
981         /* taking care of that the page is added to LRU while we commit it */
982         if (likely(!PageLRU(page)))
983                 return;
984         spin_lock_irqsave(&zone->lru_lock, flags);
985         /* link when the page is linked to LRU but page_cgroup isn't */
986         if (PageLRU(page) && !PageCgroupAcctLRU(pc))
987                 mem_cgroup_add_lru_list(page, page_lru(page));
988         spin_unlock_irqrestore(&zone->lru_lock, flags);
989 }
990
991
992 void mem_cgroup_move_lists(struct page *page,
993                            enum lru_list from, enum lru_list to)
994 {
995         if (mem_cgroup_disabled())
996                 return;
997         mem_cgroup_del_lru_list(page, from);
998         mem_cgroup_add_lru_list(page, to);
999 }
1000
1001 int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *mem)
1002 {
1003         int ret;
1004         struct mem_cgroup *curr = NULL;
1005         struct task_struct *p;
1006
1007         p = find_lock_task_mm(task);
1008         if (!p)
1009                 return 0;
1010         curr = try_get_mem_cgroup_from_mm(p->mm);
1011         task_unlock(p);
1012         if (!curr)
1013                 return 0;
1014         /*
1015          * We should check use_hierarchy of "mem" not "curr". Because checking
1016          * use_hierarchy of "curr" here make this function true if hierarchy is
1017          * enabled in "curr" and "curr" is a child of "mem" in *cgroup*
1018          * hierarchy(even if use_hierarchy is disabled in "mem").
1019          */
1020         if (mem->use_hierarchy)
1021                 ret = css_is_ancestor(&curr->css, &mem->css);
1022         else
1023                 ret = (curr == mem);
1024         css_put(&curr->css);
1025         return ret;
1026 }
1027
1028 static int calc_inactive_ratio(struct mem_cgroup *memcg, unsigned long *present_pages)
1029 {
1030         unsigned long active;
1031         unsigned long inactive;
1032         unsigned long gb;
1033         unsigned long inactive_ratio;
1034
1035         inactive = mem_cgroup_get_local_zonestat(memcg, LRU_INACTIVE_ANON);
1036         active = mem_cgroup_get_local_zonestat(memcg, LRU_ACTIVE_ANON);
1037
1038         gb = (inactive + active) >> (30 - PAGE_SHIFT);
1039         if (gb)
1040                 inactive_ratio = int_sqrt(10 * gb);
1041         else
1042                 inactive_ratio = 1;
1043
1044         if (present_pages) {
1045                 present_pages[0] = inactive;
1046                 present_pages[1] = active;
1047         }
1048
1049         return inactive_ratio;
1050 }
1051
1052 int mem_cgroup_inactive_anon_is_low(struct mem_cgroup *memcg)
1053 {
1054         unsigned long active;
1055         unsigned long inactive;
1056         unsigned long present_pages[2];
1057         unsigned long inactive_ratio;
1058
1059         inactive_ratio = calc_inactive_ratio(memcg, present_pages);
1060
1061         inactive = present_pages[0];
1062         active = present_pages[1];
1063
1064         if (inactive * inactive_ratio < active)
1065                 return 1;
1066
1067         return 0;
1068 }
1069
1070 int mem_cgroup_inactive_file_is_low(struct mem_cgroup *memcg)
1071 {
1072         unsigned long active;
1073         unsigned long inactive;
1074
1075         inactive = mem_cgroup_get_local_zonestat(memcg, LRU_INACTIVE_FILE);
1076         active = mem_cgroup_get_local_zonestat(memcg, LRU_ACTIVE_FILE);
1077
1078         return (active > inactive);
1079 }
1080
1081 unsigned long mem_cgroup_zone_nr_pages(struct mem_cgroup *memcg,
1082                                        struct zone *zone,
1083                                        enum lru_list lru)
1084 {
1085         int nid = zone_to_nid(zone);
1086         int zid = zone_idx(zone);
1087         struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
1088
1089         return MEM_CGROUP_ZSTAT(mz, lru);
1090 }
1091
1092 struct zone_reclaim_stat *mem_cgroup_get_reclaim_stat(struct mem_cgroup *memcg,
1093                                                       struct zone *zone)
1094 {
1095         int nid = zone_to_nid(zone);
1096         int zid = zone_idx(zone);
1097         struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
1098
1099         return &mz->reclaim_stat;
1100 }
1101
1102 struct zone_reclaim_stat *
1103 mem_cgroup_get_reclaim_stat_from_page(struct page *page)
1104 {
1105         struct page_cgroup *pc;
1106         struct mem_cgroup_per_zone *mz;
1107
1108         if (mem_cgroup_disabled())
1109                 return NULL;
1110
1111         pc = lookup_page_cgroup(page);
1112         if (!PageCgroupUsed(pc))
1113                 return NULL;
1114         /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1115         smp_rmb();
1116         mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
1117         return &mz->reclaim_stat;
1118 }
1119
1120 unsigned long mem_cgroup_isolate_pages(unsigned long nr_to_scan,
1121                                         struct list_head *dst,
1122                                         unsigned long *scanned, int order,
1123                                         int mode, struct zone *z,
1124                                         struct mem_cgroup *mem_cont,
1125                                         int active, int file)
1126 {
1127         unsigned long nr_taken = 0;
1128         struct page *page;
1129         unsigned long scan;
1130         LIST_HEAD(pc_list);
1131         struct list_head *src;
1132         struct page_cgroup *pc, *tmp;
1133         int nid = zone_to_nid(z);
1134         int zid = zone_idx(z);
1135         struct mem_cgroup_per_zone *mz;
1136         int lru = LRU_FILE * file + active;
1137         int ret;
1138
1139         BUG_ON(!mem_cont);
1140         mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
1141         src = &mz->lists[lru];
1142
1143         scan = 0;
1144         list_for_each_entry_safe_reverse(pc, tmp, src, lru) {
1145                 if (scan >= nr_to_scan)
1146                         break;
1147
1148                 if (unlikely(!PageCgroupUsed(pc)))
1149                         continue;
1150
1151                 page = lookup_cgroup_page(pc);
1152
1153                 if (unlikely(!PageLRU(page)))
1154                         continue;
1155
1156                 scan++;
1157                 ret = __isolate_lru_page(page, mode, file);
1158                 switch (ret) {
1159                 case 0:
1160                         list_move(&page->lru, dst);
1161                         mem_cgroup_del_lru(page);
1162                         nr_taken += hpage_nr_pages(page);
1163                         break;
1164                 case -EBUSY:
1165                         /* we don't affect global LRU but rotate in our LRU */
1166                         mem_cgroup_rotate_lru_list(page, page_lru(page));
1167                         break;
1168                 default:
1169                         break;
1170                 }
1171         }
1172
1173         *scanned = scan;
1174
1175         trace_mm_vmscan_memcg_isolate(0, nr_to_scan, scan, nr_taken,
1176                                       0, 0, 0, mode);
1177
1178         return nr_taken;
1179 }
1180
1181 #define mem_cgroup_from_res_counter(counter, member)    \
1182         container_of(counter, struct mem_cgroup, member)
1183
1184 /**
1185  * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1186  * @mem: the memory cgroup
1187  *
1188  * Returns the maximum amount of memory @mem can be charged with, in
1189  * pages.
1190  */
1191 static unsigned long mem_cgroup_margin(struct mem_cgroup *mem)
1192 {
1193         unsigned long long margin;
1194
1195         margin = res_counter_margin(&mem->res);
1196         if (do_swap_account)
1197                 margin = min(margin, res_counter_margin(&mem->memsw));
1198         return margin >> PAGE_SHIFT;
1199 }
1200
1201 static unsigned int get_swappiness(struct mem_cgroup *memcg)
1202 {
1203         struct cgroup *cgrp = memcg->css.cgroup;
1204
1205         /* root ? */
1206         if (cgrp->parent == NULL)
1207                 return vm_swappiness;
1208
1209         return memcg->swappiness;
1210 }
1211
1212 static void mem_cgroup_start_move(struct mem_cgroup *mem)
1213 {
1214         int cpu;
1215
1216         get_online_cpus();
1217         spin_lock(&mem->pcp_counter_lock);
1218         for_each_online_cpu(cpu)
1219                 per_cpu(mem->stat->count[MEM_CGROUP_ON_MOVE], cpu) += 1;
1220         mem->nocpu_base.count[MEM_CGROUP_ON_MOVE] += 1;
1221         spin_unlock(&mem->pcp_counter_lock);
1222         put_online_cpus();
1223
1224         synchronize_rcu();
1225 }
1226
1227 static void mem_cgroup_end_move(struct mem_cgroup *mem)
1228 {
1229         int cpu;
1230
1231         if (!mem)
1232                 return;
1233         get_online_cpus();
1234         spin_lock(&mem->pcp_counter_lock);
1235         for_each_online_cpu(cpu)
1236                 per_cpu(mem->stat->count[MEM_CGROUP_ON_MOVE], cpu) -= 1;
1237         mem->nocpu_base.count[MEM_CGROUP_ON_MOVE] -= 1;
1238         spin_unlock(&mem->pcp_counter_lock);
1239         put_online_cpus();
1240 }
1241 /*
1242  * 2 routines for checking "mem" is under move_account() or not.
1243  *
1244  * mem_cgroup_stealed() - checking a cgroup is mc.from or not. This is used
1245  *                        for avoiding race in accounting. If true,
1246  *                        pc->mem_cgroup may be overwritten.
1247  *
1248  * mem_cgroup_under_move() - checking a cgroup is mc.from or mc.to or
1249  *                        under hierarchy of moving cgroups. This is for
1250  *                        waiting at hith-memory prressure caused by "move".
1251  */
1252
1253 static bool mem_cgroup_stealed(struct mem_cgroup *mem)
1254 {
1255         VM_BUG_ON(!rcu_read_lock_held());
1256         return this_cpu_read(mem->stat->count[MEM_CGROUP_ON_MOVE]) > 0;
1257 }
1258
1259 static bool mem_cgroup_under_move(struct mem_cgroup *mem)
1260 {
1261         struct mem_cgroup *from;
1262         struct mem_cgroup *to;
1263         bool ret = false;
1264         /*
1265          * Unlike task_move routines, we access mc.to, mc.from not under
1266          * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1267          */
1268         spin_lock(&mc.lock);
1269         from = mc.from;
1270         to = mc.to;
1271         if (!from)
1272                 goto unlock;
1273         if (from == mem || to == mem
1274             || (mem->use_hierarchy && css_is_ancestor(&from->css, &mem->css))
1275             || (mem->use_hierarchy && css_is_ancestor(&to->css, &mem->css)))
1276                 ret = true;
1277 unlock:
1278         spin_unlock(&mc.lock);
1279         return ret;
1280 }
1281
1282 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *mem)
1283 {
1284         if (mc.moving_task && current != mc.moving_task) {
1285                 if (mem_cgroup_under_move(mem)) {
1286                         DEFINE_WAIT(wait);
1287                         prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1288                         /* moving charge context might have finished. */
1289                         if (mc.moving_task)
1290                                 schedule();
1291                         finish_wait(&mc.waitq, &wait);
1292                         return true;
1293                 }
1294         }
1295         return false;
1296 }
1297
1298 /**
1299  * mem_cgroup_print_oom_info: Called from OOM with tasklist_lock held in read mode.
1300  * @memcg: The memory cgroup that went over limit
1301  * @p: Task that is going to be killed
1302  *
1303  * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1304  * enabled
1305  */
1306 void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1307 {
1308         struct cgroup *task_cgrp;
1309         struct cgroup *mem_cgrp;
1310         /*
1311          * Need a buffer in BSS, can't rely on allocations. The code relies
1312          * on the assumption that OOM is serialized for memory controller.
1313          * If this assumption is broken, revisit this code.
1314          */
1315         static char memcg_name[PATH_MAX];
1316         int ret;
1317
1318         if (!memcg || !p)
1319                 return;
1320
1321
1322         rcu_read_lock();
1323
1324         mem_cgrp = memcg->css.cgroup;
1325         task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
1326
1327         ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
1328         if (ret < 0) {
1329                 /*
1330                  * Unfortunately, we are unable to convert to a useful name
1331                  * But we'll still print out the usage information
1332                  */
1333                 rcu_read_unlock();
1334                 goto done;
1335         }
1336         rcu_read_unlock();
1337
1338         printk(KERN_INFO "Task in %s killed", memcg_name);
1339
1340         rcu_read_lock();
1341         ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
1342         if (ret < 0) {
1343                 rcu_read_unlock();
1344                 goto done;
1345         }
1346         rcu_read_unlock();
1347
1348         /*
1349          * Continues from above, so we don't need an KERN_ level
1350          */
1351         printk(KERN_CONT " as a result of limit of %s\n", memcg_name);
1352 done:
1353
1354         printk(KERN_INFO "memory: usage %llukB, limit %llukB, failcnt %llu\n",
1355                 res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
1356                 res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
1357                 res_counter_read_u64(&memcg->res, RES_FAILCNT));
1358         printk(KERN_INFO "memory+swap: usage %llukB, limit %llukB, "
1359                 "failcnt %llu\n",
1360                 res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
1361                 res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
1362                 res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
1363 }
1364
1365 /*
1366  * This function returns the number of memcg under hierarchy tree. Returns
1367  * 1(self count) if no children.
1368  */
1369 static int mem_cgroup_count_children(struct mem_cgroup *mem)
1370 {
1371         int num = 0;
1372         struct mem_cgroup *iter;
1373
1374         for_each_mem_cgroup_tree(iter, mem)
1375                 num++;
1376         return num;
1377 }
1378
1379 /*
1380  * Return the memory (and swap, if configured) limit for a memcg.
1381  */
1382 u64 mem_cgroup_get_limit(struct mem_cgroup *memcg)
1383 {
1384         u64 limit;
1385         u64 memsw;
1386
1387         limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
1388         limit += total_swap_pages << PAGE_SHIFT;
1389
1390         memsw = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
1391         /*
1392          * If memsw is finite and limits the amount of swap space available
1393          * to this memcg, return that limit.
1394          */
1395         return min(limit, memsw);
1396 }
1397
1398 /*
1399  * Visit the first child (need not be the first child as per the ordering
1400  * of the cgroup list, since we track last_scanned_child) of @mem and use
1401  * that to reclaim free pages from.
1402  */
1403 static struct mem_cgroup *
1404 mem_cgroup_select_victim(struct mem_cgroup *root_mem)
1405 {
1406         struct mem_cgroup *ret = NULL;
1407         struct cgroup_subsys_state *css;
1408         int nextid, found;
1409
1410         if (!root_mem->use_hierarchy) {
1411                 css_get(&root_mem->css);
1412                 ret = root_mem;
1413         }
1414
1415         while (!ret) {
1416                 rcu_read_lock();
1417                 nextid = root_mem->last_scanned_child + 1;
1418                 css = css_get_next(&mem_cgroup_subsys, nextid, &root_mem->css,
1419                                    &found);
1420                 if (css && css_tryget(css))
1421                         ret = container_of(css, struct mem_cgroup, css);
1422
1423                 rcu_read_unlock();
1424                 /* Updates scanning parameter */
1425                 if (!css) {
1426                         /* this means start scan from ID:1 */
1427                         root_mem->last_scanned_child = 0;
1428                 } else
1429                         root_mem->last_scanned_child = found;
1430         }
1431
1432         return ret;
1433 }
1434
1435 #if MAX_NUMNODES > 1
1436
1437 /*
1438  * Always updating the nodemask is not very good - even if we have an empty
1439  * list or the wrong list here, we can start from some node and traverse all
1440  * nodes based on the zonelist. So update the list loosely once per 10 secs.
1441  *
1442  */
1443 static void mem_cgroup_may_update_nodemask(struct mem_cgroup *mem)
1444 {
1445         int nid;
1446
1447         if (time_after(mem->next_scan_node_update, jiffies))
1448                 return;
1449
1450         mem->next_scan_node_update = jiffies + 10*HZ;
1451         /* make a nodemask where this memcg uses memory from */
1452         mem->scan_nodes = node_states[N_HIGH_MEMORY];
1453
1454         for_each_node_mask(nid, node_states[N_HIGH_MEMORY]) {
1455
1456                 if (mem_cgroup_get_zonestat_node(mem, nid, LRU_INACTIVE_FILE) ||
1457                     mem_cgroup_get_zonestat_node(mem, nid, LRU_ACTIVE_FILE))
1458                         continue;
1459
1460                 if (total_swap_pages &&
1461                     (mem_cgroup_get_zonestat_node(mem, nid, LRU_INACTIVE_ANON) ||
1462                      mem_cgroup_get_zonestat_node(mem, nid, LRU_ACTIVE_ANON)))
1463                         continue;
1464                 node_clear(nid, mem->scan_nodes);
1465         }
1466 }
1467
1468 /*
1469  * Selecting a node where we start reclaim from. Because what we need is just
1470  * reducing usage counter, start from anywhere is O,K. Considering
1471  * memory reclaim from current node, there are pros. and cons.
1472  *
1473  * Freeing memory from current node means freeing memory from a node which
1474  * we'll use or we've used. So, it may make LRU bad. And if several threads
1475  * hit limits, it will see a contention on a node. But freeing from remote
1476  * node means more costs for memory reclaim because of memory latency.
1477  *
1478  * Now, we use round-robin. Better algorithm is welcomed.
1479  */
1480 int mem_cgroup_select_victim_node(struct mem_cgroup *mem)
1481 {
1482         int node;
1483
1484         mem_cgroup_may_update_nodemask(mem);
1485         node = mem->last_scanned_node;
1486
1487         node = next_node(node, mem->scan_nodes);
1488         if (node == MAX_NUMNODES)
1489                 node = first_node(mem->scan_nodes);
1490         /*
1491          * We call this when we hit limit, not when pages are added to LRU.
1492          * No LRU may hold pages because all pages are UNEVICTABLE or
1493          * memcg is too small and all pages are not on LRU. In that case,
1494          * we use curret node.
1495          */
1496         if (unlikely(node == MAX_NUMNODES))
1497                 node = numa_node_id();
1498
1499         mem->last_scanned_node = node;
1500         return node;
1501 }
1502
1503 #else
1504 int mem_cgroup_select_victim_node(struct mem_cgroup *mem)
1505 {
1506         return 0;
1507 }
1508 #endif
1509
1510 /*
1511  * Scan the hierarchy if needed to reclaim memory. We remember the last child
1512  * we reclaimed from, so that we don't end up penalizing one child extensively
1513  * based on its position in the children list.
1514  *
1515  * root_mem is the original ancestor that we've been reclaim from.
1516  *
1517  * We give up and return to the caller when we visit root_mem twice.
1518  * (other groups can be removed while we're walking....)
1519  *
1520  * If shrink==true, for avoiding to free too much, this returns immedieately.
1521  */
1522 static int mem_cgroup_hierarchical_reclaim(struct mem_cgroup *root_mem,
1523                                                 struct zone *zone,
1524                                                 gfp_t gfp_mask,
1525                                                 unsigned long reclaim_options,
1526                                                 unsigned long *total_scanned)
1527 {
1528         struct mem_cgroup *victim;
1529         int ret, total = 0;
1530         int loop = 0;
1531         bool noswap = reclaim_options & MEM_CGROUP_RECLAIM_NOSWAP;
1532         bool shrink = reclaim_options & MEM_CGROUP_RECLAIM_SHRINK;
1533         bool check_soft = reclaim_options & MEM_CGROUP_RECLAIM_SOFT;
1534         unsigned long excess;
1535         unsigned long nr_scanned;
1536
1537         excess = res_counter_soft_limit_excess(&root_mem->res) >> PAGE_SHIFT;
1538
1539         /* If memsw_is_minimum==1, swap-out is of-no-use. */
1540         if (root_mem->memsw_is_minimum)
1541                 noswap = true;
1542
1543         while (1) {
1544                 victim = mem_cgroup_select_victim(root_mem);
1545                 if (victim == root_mem) {
1546                         loop++;
1547                         if (loop >= 1)
1548                                 drain_all_stock_async();
1549                         if (loop >= 2) {
1550                                 /*
1551                                  * If we have not been able to reclaim
1552                                  * anything, it might because there are
1553                                  * no reclaimable pages under this hierarchy
1554                                  */
1555                                 if (!check_soft || !total) {
1556                                         css_put(&victim->css);
1557                                         break;
1558                                 }
1559                                 /*
1560                                  * We want to do more targeted reclaim.
1561                                  * excess >> 2 is not to excessive so as to
1562                                  * reclaim too much, nor too less that we keep
1563                                  * coming back to reclaim from this cgroup
1564                                  */
1565                                 if (total >= (excess >> 2) ||
1566                                         (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS)) {
1567                                         css_put(&victim->css);
1568                                         break;
1569                                 }
1570                         }
1571                 }
1572                 if (!mem_cgroup_local_usage(victim)) {
1573                         /* this cgroup's local usage == 0 */
1574                         css_put(&victim->css);
1575                         continue;
1576                 }
1577                 /* we use swappiness of local cgroup */
1578                 if (check_soft) {
1579                         ret = mem_cgroup_shrink_node_zone(victim, gfp_mask,
1580                                 noswap, get_swappiness(victim), zone,
1581                                 &nr_scanned);
1582                         *total_scanned += nr_scanned;
1583                 } else
1584                         ret = try_to_free_mem_cgroup_pages(victim, gfp_mask,
1585                                                 noswap, get_swappiness(victim));
1586                 css_put(&victim->css);
1587                 /*
1588                  * At shrinking usage, we can't check we should stop here or
1589                  * reclaim more. It's depends on callers. last_scanned_child
1590                  * will work enough for keeping fairness under tree.
1591                  */
1592                 if (shrink)
1593                         return ret;
1594                 total += ret;
1595                 if (check_soft) {
1596                         if (!res_counter_soft_limit_excess(&root_mem->res))
1597                                 return total;
1598                 } else if (mem_cgroup_margin(root_mem))
1599                         return total;
1600         }
1601         return total;
1602 }
1603
1604 /*
1605  * Check OOM-Killer is already running under our hierarchy.
1606  * If someone is running, return false.
1607  */
1608 static bool mem_cgroup_oom_lock(struct mem_cgroup *mem)
1609 {
1610         int x, lock_count = 0;
1611         struct mem_cgroup *iter;
1612
1613         for_each_mem_cgroup_tree(iter, mem) {
1614                 x = atomic_inc_return(&iter->oom_lock);
1615                 lock_count = max(x, lock_count);
1616         }
1617
1618         if (lock_count == 1)
1619                 return true;
1620         return false;
1621 }
1622
1623 static int mem_cgroup_oom_unlock(struct mem_cgroup *mem)
1624 {
1625         struct mem_cgroup *iter;
1626
1627         /*
1628          * When a new child is created while the hierarchy is under oom,
1629          * mem_cgroup_oom_lock() may not be called. We have to use
1630          * atomic_add_unless() here.
1631          */
1632         for_each_mem_cgroup_tree(iter, mem)
1633                 atomic_add_unless(&iter->oom_lock, -1, 0);
1634         return 0;
1635 }
1636
1637
1638 static DEFINE_MUTEX(memcg_oom_mutex);
1639 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1640
1641 struct oom_wait_info {
1642         struct mem_cgroup *mem;
1643         wait_queue_t    wait;
1644 };
1645
1646 static int memcg_oom_wake_function(wait_queue_t *wait,
1647         unsigned mode, int sync, void *arg)
1648 {
1649         struct mem_cgroup *wake_mem = (struct mem_cgroup *)arg;
1650         struct oom_wait_info *oom_wait_info;
1651
1652         oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1653
1654         if (oom_wait_info->mem == wake_mem)
1655                 goto wakeup;
1656         /* if no hierarchy, no match */
1657         if (!oom_wait_info->mem->use_hierarchy || !wake_mem->use_hierarchy)
1658                 return 0;
1659         /*
1660          * Both of oom_wait_info->mem and wake_mem are stable under us.
1661          * Then we can use css_is_ancestor without taking care of RCU.
1662          */
1663         if (!css_is_ancestor(&oom_wait_info->mem->css, &wake_mem->css) &&
1664             !css_is_ancestor(&wake_mem->css, &oom_wait_info->mem->css))
1665                 return 0;
1666
1667 wakeup:
1668         return autoremove_wake_function(wait, mode, sync, arg);
1669 }
1670
1671 static void memcg_wakeup_oom(struct mem_cgroup *mem)
1672 {
1673         /* for filtering, pass "mem" as argument. */
1674         __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, mem);
1675 }
1676
1677 static void memcg_oom_recover(struct mem_cgroup *mem)
1678 {
1679         if (mem && atomic_read(&mem->oom_lock))
1680                 memcg_wakeup_oom(mem);
1681 }
1682
1683 /*
1684  * try to call OOM killer. returns false if we should exit memory-reclaim loop.
1685  */
1686 bool mem_cgroup_handle_oom(struct mem_cgroup *mem, gfp_t mask)
1687 {
1688         struct oom_wait_info owait;
1689         bool locked, need_to_kill;
1690
1691         owait.mem = mem;
1692         owait.wait.flags = 0;
1693         owait.wait.func = memcg_oom_wake_function;
1694         owait.wait.private = current;
1695         INIT_LIST_HEAD(&owait.wait.task_list);
1696         need_to_kill = true;
1697         /* At first, try to OOM lock hierarchy under mem.*/
1698         mutex_lock(&memcg_oom_mutex);
1699         locked = mem_cgroup_oom_lock(mem);
1700         /*
1701          * Even if signal_pending(), we can't quit charge() loop without
1702          * accounting. So, UNINTERRUPTIBLE is appropriate. But SIGKILL
1703          * under OOM is always welcomed, use TASK_KILLABLE here.
1704          */
1705         prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
1706         if (!locked || mem->oom_kill_disable)
1707                 need_to_kill = false;
1708         if (locked)
1709                 mem_cgroup_oom_notify(mem);
1710         mutex_unlock(&memcg_oom_mutex);
1711
1712         if (need_to_kill) {
1713                 finish_wait(&memcg_oom_waitq, &owait.wait);
1714                 mem_cgroup_out_of_memory(mem, mask);
1715         } else {
1716                 schedule();
1717                 finish_wait(&memcg_oom_waitq, &owait.wait);
1718         }
1719         mutex_lock(&memcg_oom_mutex);
1720         mem_cgroup_oom_unlock(mem);
1721         memcg_wakeup_oom(mem);
1722         mutex_unlock(&memcg_oom_mutex);
1723
1724         if (test_thread_flag(TIF_MEMDIE) || fatal_signal_pending(current))
1725                 return false;
1726         /* Give chance to dying process */
1727         schedule_timeout(1);
1728         return true;
1729 }
1730
1731 /*
1732  * Currently used to update mapped file statistics, but the routine can be
1733  * generalized to update other statistics as well.
1734  *
1735  * Notes: Race condition
1736  *
1737  * We usually use page_cgroup_lock() for accessing page_cgroup member but
1738  * it tends to be costly. But considering some conditions, we doesn't need
1739  * to do so _always_.
1740  *
1741  * Considering "charge", lock_page_cgroup() is not required because all
1742  * file-stat operations happen after a page is attached to radix-tree. There
1743  * are no race with "charge".
1744  *
1745  * Considering "uncharge", we know that memcg doesn't clear pc->mem_cgroup
1746  * at "uncharge" intentionally. So, we always see valid pc->mem_cgroup even
1747  * if there are race with "uncharge". Statistics itself is properly handled
1748  * by flags.
1749  *
1750  * Considering "move", this is an only case we see a race. To make the race
1751  * small, we check MEM_CGROUP_ON_MOVE percpu value and detect there are
1752  * possibility of race condition. If there is, we take a lock.
1753  */
1754
1755 void mem_cgroup_update_page_stat(struct page *page,
1756                                  enum mem_cgroup_page_stat_item idx, int val)
1757 {
1758         struct mem_cgroup *mem;
1759         struct page_cgroup *pc = lookup_page_cgroup(page);
1760         bool need_unlock = false;
1761         unsigned long uninitialized_var(flags);
1762
1763         if (unlikely(!pc))
1764                 return;
1765
1766         rcu_read_lock();
1767         mem = pc->mem_cgroup;
1768         if (unlikely(!mem || !PageCgroupUsed(pc)))
1769                 goto out;
1770         /* pc->mem_cgroup is unstable ? */
1771         if (unlikely(mem_cgroup_stealed(mem)) || PageTransHuge(page)) {
1772                 /* take a lock against to access pc->mem_cgroup */
1773                 move_lock_page_cgroup(pc, &flags);
1774                 need_unlock = true;
1775                 mem = pc->mem_cgroup;
1776                 if (!mem || !PageCgroupUsed(pc))
1777                         goto out;
1778         }
1779
1780         switch (idx) {
1781         case MEMCG_NR_FILE_MAPPED:
1782                 if (val > 0)
1783                         SetPageCgroupFileMapped(pc);
1784                 else if (!page_mapped(page))
1785                         ClearPageCgroupFileMapped(pc);
1786                 idx = MEM_CGROUP_STAT_FILE_MAPPED;
1787                 break;
1788         default:
1789                 BUG();
1790         }
1791
1792         this_cpu_add(mem->stat->count[idx], val);
1793
1794 out:
1795         if (unlikely(need_unlock))
1796                 move_unlock_page_cgroup(pc, &flags);
1797         rcu_read_unlock();
1798         return;
1799 }
1800 EXPORT_SYMBOL(mem_cgroup_update_page_stat);
1801
1802 /*
1803  * size of first charge trial. "32" comes from vmscan.c's magic value.
1804  * TODO: maybe necessary to use big numbers in big irons.
1805  */
1806 #define CHARGE_BATCH    32U
1807 struct memcg_stock_pcp {
1808         struct mem_cgroup *cached; /* this never be root cgroup */
1809         unsigned int nr_pages;
1810         struct work_struct work;
1811 };
1812 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
1813 static atomic_t memcg_drain_count;
1814
1815 /*
1816  * Try to consume stocked charge on this cpu. If success, one page is consumed
1817  * from local stock and true is returned. If the stock is 0 or charges from a
1818  * cgroup which is not current target, returns false. This stock will be
1819  * refilled.
1820  */
1821 static bool consume_stock(struct mem_cgroup *mem)
1822 {
1823         struct memcg_stock_pcp *stock;
1824         bool ret = true;
1825
1826         stock = &get_cpu_var(memcg_stock);
1827         if (mem == stock->cached && stock->nr_pages)
1828                 stock->nr_pages--;
1829         else /* need to call res_counter_charge */
1830                 ret = false;
1831         put_cpu_var(memcg_stock);
1832         return ret;
1833 }
1834
1835 /*
1836  * Returns stocks cached in percpu to res_counter and reset cached information.
1837  */
1838 static void drain_stock(struct memcg_stock_pcp *stock)
1839 {
1840         struct mem_cgroup *old = stock->cached;
1841
1842         if (stock->nr_pages) {
1843                 unsigned long bytes = stock->nr_pages * PAGE_SIZE;
1844
1845                 res_counter_uncharge(&old->res, bytes);
1846                 if (do_swap_account)
1847                         res_counter_uncharge(&old->memsw, bytes);
1848                 stock->nr_pages = 0;
1849         }
1850         stock->cached = NULL;
1851 }
1852
1853 /*
1854  * This must be called under preempt disabled or must be called by
1855  * a thread which is pinned to local cpu.
1856  */
1857 static void drain_local_stock(struct work_struct *dummy)
1858 {
1859         struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
1860         drain_stock(stock);
1861 }
1862
1863 /*
1864  * Cache charges(val) which is from res_counter, to local per_cpu area.
1865  * This will be consumed by consume_stock() function, later.
1866  */
1867 static void refill_stock(struct mem_cgroup *mem, unsigned int nr_pages)
1868 {
1869         struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
1870
1871         if (stock->cached != mem) { /* reset if necessary */
1872                 drain_stock(stock);
1873                 stock->cached = mem;
1874         }
1875         stock->nr_pages += nr_pages;
1876         put_cpu_var(memcg_stock);
1877 }
1878
1879 /*
1880  * Tries to drain stocked charges in other cpus. This function is asynchronous
1881  * and just put a work per cpu for draining localy on each cpu. Caller can
1882  * expects some charges will be back to res_counter later but cannot wait for
1883  * it.
1884  */
1885 static void drain_all_stock_async(void)
1886 {
1887         int cpu;
1888         /* This function is for scheduling "drain" in asynchronous way.
1889          * The result of "drain" is not directly handled by callers. Then,
1890          * if someone is calling drain, we don't have to call drain more.
1891          * Anyway, WORK_STRUCT_PENDING check in queue_work_on() will catch if
1892          * there is a race. We just do loose check here.
1893          */
1894         if (atomic_read(&memcg_drain_count))
1895                 return;
1896         /* Notify other cpus that system-wide "drain" is running */
1897         atomic_inc(&memcg_drain_count);
1898         get_online_cpus();
1899         for_each_online_cpu(cpu) {
1900                 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
1901                 schedule_work_on(cpu, &stock->work);
1902         }
1903         put_online_cpus();
1904         atomic_dec(&memcg_drain_count);
1905         /* We don't wait for flush_work */
1906 }
1907
1908 /* This is a synchronous drain interface. */
1909 static void drain_all_stock_sync(void)
1910 {
1911         /* called when force_empty is called */
1912         atomic_inc(&memcg_drain_count);
1913         schedule_on_each_cpu(drain_local_stock);
1914         atomic_dec(&memcg_drain_count);
1915 }
1916
1917 /*
1918  * This function drains percpu counter value from DEAD cpu and
1919  * move it to local cpu. Note that this function can be preempted.
1920  */
1921 static void mem_cgroup_drain_pcp_counter(struct mem_cgroup *mem, int cpu)
1922 {
1923         int i;
1924
1925         spin_lock(&mem->pcp_counter_lock);
1926         for (i = 0; i < MEM_CGROUP_STAT_DATA; i++) {
1927                 long x = per_cpu(mem->stat->count[i], cpu);
1928
1929                 per_cpu(mem->stat->count[i], cpu) = 0;
1930                 mem->nocpu_base.count[i] += x;
1931         }
1932         for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
1933                 unsigned long x = per_cpu(mem->stat->events[i], cpu);
1934
1935                 per_cpu(mem->stat->events[i], cpu) = 0;
1936                 mem->nocpu_base.events[i] += x;
1937         }
1938         /* need to clear ON_MOVE value, works as a kind of lock. */
1939         per_cpu(mem->stat->count[MEM_CGROUP_ON_MOVE], cpu) = 0;
1940         spin_unlock(&mem->pcp_counter_lock);
1941 }
1942
1943 static void synchronize_mem_cgroup_on_move(struct mem_cgroup *mem, int cpu)
1944 {
1945         int idx = MEM_CGROUP_ON_MOVE;
1946
1947         spin_lock(&mem->pcp_counter_lock);
1948         per_cpu(mem->stat->count[idx], cpu) = mem->nocpu_base.count[idx];
1949         spin_unlock(&mem->pcp_counter_lock);
1950 }
1951
1952 static int __cpuinit memcg_cpu_hotplug_callback(struct notifier_block *nb,
1953                                         unsigned long action,
1954                                         void *hcpu)
1955 {
1956         int cpu = (unsigned long)hcpu;
1957         struct memcg_stock_pcp *stock;
1958         struct mem_cgroup *iter;
1959
1960         if ((action == CPU_ONLINE)) {
1961                 for_each_mem_cgroup_all(iter)
1962                         synchronize_mem_cgroup_on_move(iter, cpu);
1963                 return NOTIFY_OK;
1964         }
1965
1966         if ((action != CPU_DEAD) || action != CPU_DEAD_FROZEN)
1967                 return NOTIFY_OK;
1968
1969         for_each_mem_cgroup_all(iter)
1970                 mem_cgroup_drain_pcp_counter(iter, cpu);
1971
1972         stock = &per_cpu(memcg_stock, cpu);
1973         drain_stock(stock);
1974         return NOTIFY_OK;
1975 }
1976
1977
1978 /* See __mem_cgroup_try_charge() for details */
1979 enum {
1980         CHARGE_OK,              /* success */
1981         CHARGE_RETRY,           /* need to retry but retry is not bad */
1982         CHARGE_NOMEM,           /* we can't do more. return -ENOMEM */
1983         CHARGE_WOULDBLOCK,      /* GFP_WAIT wasn't set and no enough res. */
1984         CHARGE_OOM_DIE,         /* the current is killed because of OOM */
1985 };
1986
1987 static int mem_cgroup_do_charge(struct mem_cgroup *mem, gfp_t gfp_mask,
1988                                 unsigned int nr_pages, bool oom_check)
1989 {
1990         unsigned long csize = nr_pages * PAGE_SIZE;
1991         struct mem_cgroup *mem_over_limit;
1992         struct res_counter *fail_res;
1993         unsigned long flags = 0;
1994         int ret;
1995
1996         ret = res_counter_charge(&mem->res, csize, &fail_res);
1997
1998         if (likely(!ret)) {
1999                 if (!do_swap_account)
2000                         return CHARGE_OK;
2001                 ret = res_counter_charge(&mem->memsw, csize, &fail_res);
2002                 if (likely(!ret))
2003                         return CHARGE_OK;
2004
2005                 res_counter_uncharge(&mem->res, csize);
2006                 mem_over_limit = mem_cgroup_from_res_counter(fail_res, memsw);
2007                 flags |= MEM_CGROUP_RECLAIM_NOSWAP;
2008         } else
2009                 mem_over_limit = mem_cgroup_from_res_counter(fail_res, res);
2010         /*
2011          * nr_pages can be either a huge page (HPAGE_PMD_NR), a batch
2012          * of regular pages (CHARGE_BATCH), or a single regular page (1).
2013          *
2014          * Never reclaim on behalf of optional batching, retry with a
2015          * single page instead.
2016          */
2017         if (nr_pages == CHARGE_BATCH)
2018                 return CHARGE_RETRY;
2019
2020         if (!(gfp_mask & __GFP_WAIT))
2021                 return CHARGE_WOULDBLOCK;
2022
2023         ret = mem_cgroup_hierarchical_reclaim(mem_over_limit, NULL,
2024                                               gfp_mask, flags, NULL);
2025         if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2026                 return CHARGE_RETRY;
2027         /*
2028          * Even though the limit is exceeded at this point, reclaim
2029          * may have been able to free some pages.  Retry the charge
2030          * before killing the task.
2031          *
2032          * Only for regular pages, though: huge pages are rather
2033          * unlikely to succeed so close to the limit, and we fall back
2034          * to regular pages anyway in case of failure.
2035          */
2036         if (nr_pages == 1 && ret)
2037                 return CHARGE_RETRY;
2038
2039         /*
2040          * At task move, charge accounts can be doubly counted. So, it's
2041          * better to wait until the end of task_move if something is going on.
2042          */
2043         if (mem_cgroup_wait_acct_move(mem_over_limit))
2044                 return CHARGE_RETRY;
2045
2046         /* If we don't need to call oom-killer at el, return immediately */
2047         if (!oom_check)
2048                 return CHARGE_NOMEM;
2049         /* check OOM */
2050         if (!mem_cgroup_handle_oom(mem_over_limit, gfp_mask))
2051                 return CHARGE_OOM_DIE;
2052
2053         return CHARGE_RETRY;
2054 }
2055
2056 /*
2057  * Unlike exported interface, "oom" parameter is added. if oom==true,
2058  * oom-killer can be invoked.
2059  */
2060 static int __mem_cgroup_try_charge(struct mm_struct *mm,
2061                                    gfp_t gfp_mask,
2062                                    unsigned int nr_pages,
2063                                    struct mem_cgroup **memcg,
2064                                    bool oom)
2065 {
2066         unsigned int batch = max(CHARGE_BATCH, nr_pages);
2067         int nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2068         struct mem_cgroup *mem = NULL;
2069         int ret;
2070
2071         /*
2072          * Unlike gloval-vm's OOM-kill, we're not in memory shortage
2073          * in system level. So, allow to go ahead dying process in addition to
2074          * MEMDIE process.
2075          */
2076         if (unlikely(test_thread_flag(TIF_MEMDIE)
2077                      || fatal_signal_pending(current)))
2078                 goto bypass;
2079
2080         /*
2081          * We always charge the cgroup the mm_struct belongs to.
2082          * The mm_struct's mem_cgroup changes on task migration if the
2083          * thread group leader migrates. It's possible that mm is not
2084          * set, if so charge the init_mm (happens for pagecache usage).
2085          */
2086         if (!*memcg && !mm)
2087                 goto bypass;
2088 again:
2089         if (*memcg) { /* css should be a valid one */
2090                 mem = *memcg;
2091                 VM_BUG_ON(css_is_removed(&mem->css));
2092                 if (mem_cgroup_is_root(mem))
2093                         goto done;
2094                 if (nr_pages == 1 && consume_stock(mem))
2095                         goto done;
2096                 css_get(&mem->css);
2097         } else {
2098                 struct task_struct *p;
2099
2100                 rcu_read_lock();
2101                 p = rcu_dereference(mm->owner);
2102                 /*
2103                  * Because we don't have task_lock(), "p" can exit.
2104                  * In that case, "mem" can point to root or p can be NULL with
2105                  * race with swapoff. Then, we have small risk of mis-accouning.
2106                  * But such kind of mis-account by race always happens because
2107                  * we don't have cgroup_mutex(). It's overkill and we allo that
2108                  * small race, here.
2109                  * (*) swapoff at el will charge against mm-struct not against
2110                  * task-struct. So, mm->owner can be NULL.
2111                  */
2112                 mem = mem_cgroup_from_task(p);
2113                 if (!mem || mem_cgroup_is_root(mem)) {
2114                         rcu_read_unlock();
2115                         goto done;
2116                 }
2117                 if (nr_pages == 1 && consume_stock(mem)) {
2118                         /*
2119                          * It seems dagerous to access memcg without css_get().
2120                          * But considering how consume_stok works, it's not
2121                          * necessary. If consume_stock success, some charges
2122                          * from this memcg are cached on this cpu. So, we
2123                          * don't need to call css_get()/css_tryget() before
2124                          * calling consume_stock().
2125                          */
2126                         rcu_read_unlock();
2127                         goto done;
2128                 }
2129                 /* after here, we may be blocked. we need to get refcnt */
2130                 if (!css_tryget(&mem->css)) {
2131                         rcu_read_unlock();
2132                         goto again;
2133                 }
2134                 rcu_read_unlock();
2135         }
2136
2137         do {
2138                 bool oom_check;
2139
2140                 /* If killed, bypass charge */
2141                 if (fatal_signal_pending(current)) {
2142                         css_put(&mem->css);
2143                         goto bypass;
2144                 }
2145
2146                 oom_check = false;
2147                 if (oom && !nr_oom_retries) {
2148                         oom_check = true;
2149                         nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2150                 }
2151
2152                 ret = mem_cgroup_do_charge(mem, gfp_mask, batch, oom_check);
2153                 switch (ret) {
2154                 case CHARGE_OK:
2155                         break;
2156                 case CHARGE_RETRY: /* not in OOM situation but retry */
2157                         batch = nr_pages;
2158                         css_put(&mem->css);
2159                         mem = NULL;
2160                         goto again;
2161                 case CHARGE_WOULDBLOCK: /* !__GFP_WAIT */
2162                         css_put(&mem->css);
2163                         goto nomem;
2164                 case CHARGE_NOMEM: /* OOM routine works */
2165                         if (!oom) {
2166                                 css_put(&mem->css);
2167                                 goto nomem;
2168                         }
2169                         /* If oom, we never return -ENOMEM */
2170                         nr_oom_retries--;
2171                         break;
2172                 case CHARGE_OOM_DIE: /* Killed by OOM Killer */
2173                         css_put(&mem->css);
2174                         goto bypass;
2175                 }
2176         } while (ret != CHARGE_OK);
2177
2178         if (batch > nr_pages)
2179                 refill_stock(mem, batch - nr_pages);
2180         css_put(&mem->css);
2181 done:
2182         *memcg = mem;
2183         return 0;
2184 nomem:
2185         *memcg = NULL;
2186         return -ENOMEM;
2187 bypass:
2188         *memcg = NULL;
2189         return 0;
2190 }
2191
2192 /*
2193  * Somemtimes we have to undo a charge we got by try_charge().
2194  * This function is for that and do uncharge, put css's refcnt.
2195  * gotten by try_charge().
2196  */
2197 static void __mem_cgroup_cancel_charge(struct mem_cgroup *mem,
2198                                        unsigned int nr_pages)
2199 {
2200         if (!mem_cgroup_is_root(mem)) {
2201                 unsigned long bytes = nr_pages * PAGE_SIZE;
2202
2203                 res_counter_uncharge(&mem->res, bytes);
2204                 if (do_swap_account)
2205                         res_counter_uncharge(&mem->memsw, bytes);
2206         }
2207 }
2208
2209 /*
2210  * A helper function to get mem_cgroup from ID. must be called under
2211  * rcu_read_lock(). The caller must check css_is_removed() or some if
2212  * it's concern. (dropping refcnt from swap can be called against removed
2213  * memcg.)
2214  */
2215 static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
2216 {
2217         struct cgroup_subsys_state *css;
2218
2219         /* ID 0 is unused ID */
2220         if (!id)
2221                 return NULL;
2222         css = css_lookup(&mem_cgroup_subsys, id);
2223         if (!css)
2224                 return NULL;
2225         return container_of(css, struct mem_cgroup, css);
2226 }
2227
2228 struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
2229 {
2230         struct mem_cgroup *mem = NULL;
2231         struct page_cgroup *pc;
2232         unsigned short id;
2233         swp_entry_t ent;
2234
2235         VM_BUG_ON(!PageLocked(page));
2236
2237         pc = lookup_page_cgroup(page);
2238         lock_page_cgroup(pc);
2239         if (PageCgroupUsed(pc)) {
2240                 mem = pc->mem_cgroup;
2241                 if (mem && !css_tryget(&mem->css))
2242                         mem = NULL;
2243         } else if (PageSwapCache(page)) {
2244                 ent.val = page_private(page);
2245                 id = lookup_swap_cgroup(ent);
2246                 rcu_read_lock();
2247                 mem = mem_cgroup_lookup(id);
2248                 if (mem && !css_tryget(&mem->css))
2249                         mem = NULL;
2250                 rcu_read_unlock();
2251         }
2252         unlock_page_cgroup(pc);
2253         return mem;
2254 }
2255
2256 static void __mem_cgroup_commit_charge(struct mem_cgroup *mem,
2257                                        struct page *page,
2258                                        unsigned int nr_pages,
2259                                        struct page_cgroup *pc,
2260                                        enum charge_type ctype)
2261 {
2262         lock_page_cgroup(pc);
2263         if (unlikely(PageCgroupUsed(pc))) {
2264                 unlock_page_cgroup(pc);
2265                 __mem_cgroup_cancel_charge(mem, nr_pages);
2266                 return;
2267         }
2268         /*
2269          * we don't need page_cgroup_lock about tail pages, becase they are not
2270          * accessed by any other context at this point.
2271          */
2272         pc->mem_cgroup = mem;
2273         /*
2274          * We access a page_cgroup asynchronously without lock_page_cgroup().
2275          * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
2276          * is accessed after testing USED bit. To make pc->mem_cgroup visible
2277          * before USED bit, we need memory barrier here.
2278          * See mem_cgroup_add_lru_list(), etc.
2279          */
2280         smp_wmb();
2281         switch (ctype) {
2282         case MEM_CGROUP_CHARGE_TYPE_CACHE:
2283         case MEM_CGROUP_CHARGE_TYPE_SHMEM:
2284                 SetPageCgroupCache(pc);
2285                 SetPageCgroupUsed(pc);
2286                 break;
2287         case MEM_CGROUP_CHARGE_TYPE_MAPPED:
2288                 ClearPageCgroupCache(pc);
2289                 SetPageCgroupUsed(pc);
2290                 break;
2291         default:
2292                 break;
2293         }
2294
2295         mem_cgroup_charge_statistics(mem, PageCgroupCache(pc), nr_pages);
2296         unlock_page_cgroup(pc);
2297         /*
2298          * "charge_statistics" updated event counter. Then, check it.
2299          * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
2300          * if they exceeds softlimit.
2301          */
2302         memcg_check_events(mem, page);
2303 }
2304
2305 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
2306
2307 #define PCGF_NOCOPY_AT_SPLIT ((1 << PCG_LOCK) | (1 << PCG_MOVE_LOCK) |\
2308                         (1 << PCG_ACCT_LRU) | (1 << PCG_MIGRATION))
2309 /*
2310  * Because tail pages are not marked as "used", set it. We're under
2311  * zone->lru_lock, 'splitting on pmd' and compund_lock.
2312  */
2313 void mem_cgroup_split_huge_fixup(struct page *head, struct page *tail)
2314 {
2315         struct page_cgroup *head_pc = lookup_page_cgroup(head);
2316         struct page_cgroup *tail_pc = lookup_page_cgroup(tail);
2317         unsigned long flags;
2318
2319         if (mem_cgroup_disabled())
2320                 return;
2321         /*
2322          * We have no races with charge/uncharge but will have races with
2323          * page state accounting.
2324          */
2325         move_lock_page_cgroup(head_pc, &flags);
2326
2327         tail_pc->mem_cgroup = head_pc->mem_cgroup;
2328         smp_wmb(); /* see __commit_charge() */
2329         if (PageCgroupAcctLRU(head_pc)) {
2330                 enum lru_list lru;
2331                 struct mem_cgroup_per_zone *mz;
2332
2333                 /*
2334                  * LRU flags cannot be copied because we need to add tail
2335                  *.page to LRU by generic call and our hook will be called.
2336                  * We hold lru_lock, then, reduce counter directly.
2337                  */
2338                 lru = page_lru(head);
2339                 mz = page_cgroup_zoneinfo(head_pc->mem_cgroup, head);
2340                 MEM_CGROUP_ZSTAT(mz, lru) -= 1;
2341         }
2342         tail_pc->flags = head_pc->flags & ~PCGF_NOCOPY_AT_SPLIT;
2343         move_unlock_page_cgroup(head_pc, &flags);
2344 }
2345 #endif
2346
2347 /**
2348  * mem_cgroup_move_account - move account of the page
2349  * @page: the page
2350  * @nr_pages: number of regular pages (>1 for huge pages)
2351  * @pc: page_cgroup of the page.
2352  * @from: mem_cgroup which the page is moved from.
2353  * @to: mem_cgroup which the page is moved to. @from != @to.
2354  * @uncharge: whether we should call uncharge and css_put against @from.
2355  *
2356  * The caller must confirm following.
2357  * - page is not on LRU (isolate_page() is useful.)
2358  * - compound_lock is held when nr_pages > 1
2359  *
2360  * This function doesn't do "charge" nor css_get to new cgroup. It should be
2361  * done by a caller(__mem_cgroup_try_charge would be useful). If @uncharge is
2362  * true, this function does "uncharge" from old cgroup, but it doesn't if
2363  * @uncharge is false, so a caller should do "uncharge".
2364  */
2365 static int mem_cgroup_move_account(struct page *page,
2366                                    unsigned int nr_pages,
2367                                    struct page_cgroup *pc,
2368                                    struct mem_cgroup *from,
2369                                    struct mem_cgroup *to,
2370                                    bool uncharge)
2371 {
2372         unsigned long flags;
2373         int ret;
2374
2375         VM_BUG_ON(from == to);
2376         VM_BUG_ON(PageLRU(page));
2377         /*
2378          * The page is isolated from LRU. So, collapse function
2379          * will not handle this page. But page splitting can happen.
2380          * Do this check under compound_page_lock(). The caller should
2381          * hold it.
2382          */
2383         ret = -EBUSY;
2384         if (nr_pages > 1 && !PageTransHuge(page))
2385                 goto out;
2386
2387         lock_page_cgroup(pc);
2388
2389         ret = -EINVAL;
2390         if (!PageCgroupUsed(pc) || pc->mem_cgroup != from)
2391                 goto unlock;
2392
2393         move_lock_page_cgroup(pc, &flags);
2394
2395         if (PageCgroupFileMapped(pc)) {
2396                 /* Update mapped_file data for mem_cgroup */
2397                 preempt_disable();
2398                 __this_cpu_dec(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
2399                 __this_cpu_inc(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
2400                 preempt_enable();
2401         }
2402         mem_cgroup_charge_statistics(from, PageCgroupCache(pc), -nr_pages);
2403         if (uncharge)
2404                 /* This is not "cancel", but cancel_charge does all we need. */
2405                 __mem_cgroup_cancel_charge(from, nr_pages);
2406
2407         /* caller should have done css_get */
2408         pc->mem_cgroup = to;
2409         mem_cgroup_charge_statistics(to, PageCgroupCache(pc), nr_pages);
2410         /*
2411          * We charges against "to" which may not have any tasks. Then, "to"
2412          * can be under rmdir(). But in current implementation, caller of
2413          * this function is just force_empty() and move charge, so it's
2414          * guaranteed that "to" is never removed. So, we don't check rmdir
2415          * status here.
2416          */
2417         move_unlock_page_cgroup(pc, &flags);
2418         ret = 0;
2419 unlock:
2420         unlock_page_cgroup(pc);
2421         /*
2422          * check events
2423          */
2424         memcg_check_events(to, page);
2425         memcg_check_events(from, page);
2426 out:
2427         return ret;
2428 }
2429
2430 /*
2431  * move charges to its parent.
2432  */
2433
2434 static int mem_cgroup_move_parent(struct page *page,
2435                                   struct page_cgroup *pc,
2436                                   struct mem_cgroup *child,
2437                                   gfp_t gfp_mask)
2438 {
2439         struct cgroup *cg = child->css.cgroup;
2440         struct cgroup *pcg = cg->parent;
2441         struct mem_cgroup *parent;
2442         unsigned int nr_pages;
2443         unsigned long uninitialized_var(flags);
2444         int ret;
2445
2446         /* Is ROOT ? */
2447         if (!pcg)
2448                 return -EINVAL;
2449
2450         ret = -EBUSY;
2451         if (!get_page_unless_zero(page))
2452                 goto out;
2453         if (isolate_lru_page(page))
2454                 goto put;
2455
2456         nr_pages = hpage_nr_pages(page);
2457
2458         parent = mem_cgroup_from_cont(pcg);
2459         ret = __mem_cgroup_try_charge(NULL, gfp_mask, nr_pages, &parent, false);
2460         if (ret || !parent)
2461                 goto put_back;
2462
2463         if (nr_pages > 1)
2464                 flags = compound_lock_irqsave(page);
2465
2466         ret = mem_cgroup_move_account(page, nr_pages, pc, child, parent, true);
2467         if (ret)
2468                 __mem_cgroup_cancel_charge(parent, nr_pages);
2469
2470         if (nr_pages > 1)
2471                 compound_unlock_irqrestore(page, flags);
2472 put_back:
2473         putback_lru_page(page);
2474 put:
2475         put_page(page);
2476 out:
2477         return ret;
2478 }
2479
2480 /*
2481  * Charge the memory controller for page usage.
2482  * Return
2483  * 0 if the charge was successful
2484  * < 0 if the cgroup is over its limit
2485  */
2486 static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
2487                                 gfp_t gfp_mask, enum charge_type ctype)
2488 {
2489         struct mem_cgroup *mem = NULL;
2490         unsigned int nr_pages = 1;
2491         struct page_cgroup *pc;
2492         bool oom = true;
2493         int ret;
2494
2495         if (PageTransHuge(page)) {
2496                 nr_pages <<= compound_order(page);
2497                 VM_BUG_ON(!PageTransHuge(page));
2498                 /*
2499                  * Never OOM-kill a process for a huge page.  The
2500                  * fault handler will fall back to regular pages.
2501                  */
2502                 oom = false;
2503         }
2504
2505         pc = lookup_page_cgroup(page);
2506         BUG_ON(!pc); /* XXX: remove this and move pc lookup into commit */
2507
2508         ret = __mem_cgroup_try_charge(mm, gfp_mask, nr_pages, &mem, oom);
2509         if (ret || !mem)
2510                 return ret;
2511
2512         __mem_cgroup_commit_charge(mem, page, nr_pages, pc, ctype);
2513         return 0;
2514 }
2515
2516 int mem_cgroup_newpage_charge(struct page *page,
2517                               struct mm_struct *mm, gfp_t gfp_mask)
2518 {
2519         if (mem_cgroup_disabled())
2520                 return 0;
2521         /*
2522          * If already mapped, we don't have to account.
2523          * If page cache, page->mapping has address_space.
2524          * But page->mapping may have out-of-use anon_vma pointer,
2525          * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
2526          * is NULL.
2527          */
2528         if (page_mapped(page) || (page->mapping && !PageAnon(page)))
2529                 return 0;
2530         if (unlikely(!mm))
2531                 mm = &init_mm;
2532         return mem_cgroup_charge_common(page, mm, gfp_mask,
2533                                 MEM_CGROUP_CHARGE_TYPE_MAPPED);
2534 }
2535
2536 static void
2537 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
2538                                         enum charge_type ctype);
2539
2540 static void
2541 __mem_cgroup_commit_charge_lrucare(struct page *page, struct mem_cgroup *mem,
2542                                         enum charge_type ctype)
2543 {
2544         struct page_cgroup *pc = lookup_page_cgroup(page);
2545         /*
2546          * In some case, SwapCache, FUSE(splice_buf->radixtree), the page
2547          * is already on LRU. It means the page may on some other page_cgroup's
2548          * LRU. Take care of it.
2549          */
2550         mem_cgroup_lru_del_before_commit(page);
2551         __mem_cgroup_commit_charge(mem, page, 1, pc, ctype);
2552         mem_cgroup_lru_add_after_commit(page);
2553         return;
2554 }
2555
2556 int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
2557                                 gfp_t gfp_mask)
2558 {
2559         struct mem_cgroup *mem = NULL;
2560         int ret;
2561
2562         if (mem_cgroup_disabled())
2563                 return 0;
2564         if (PageCompound(page))
2565                 return 0;
2566         /*
2567          * Corner case handling. This is called from add_to_page_cache()
2568          * in usual. But some FS (shmem) precharges this page before calling it
2569          * and call add_to_page_cache() with GFP_NOWAIT.
2570          *
2571          * For GFP_NOWAIT case, the page may be pre-charged before calling
2572          * add_to_page_cache(). (See shmem.c) check it here and avoid to call
2573          * charge twice. (It works but has to pay a bit larger cost.)
2574          * And when the page is SwapCache, it should take swap information
2575          * into account. This is under lock_page() now.
2576          */
2577         if (!(gfp_mask & __GFP_WAIT)) {
2578                 struct page_cgroup *pc;
2579
2580                 pc = lookup_page_cgroup(page);
2581                 if (!pc)
2582                         return 0;
2583                 lock_page_cgroup(pc);
2584                 if (PageCgroupUsed(pc)) {
2585                         unlock_page_cgroup(pc);
2586                         return 0;
2587                 }
2588                 unlock_page_cgroup(pc);
2589         }
2590
2591         if (unlikely(!mm))
2592                 mm = &init_mm;
2593
2594         if (page_is_file_cache(page)) {
2595                 ret = __mem_cgroup_try_charge(mm, gfp_mask, 1, &mem, true);
2596                 if (ret || !mem)
2597                         return ret;
2598
2599                 /*
2600                  * FUSE reuses pages without going through the final
2601                  * put that would remove them from the LRU list, make
2602                  * sure that they get relinked properly.
2603                  */
2604                 __mem_cgroup_commit_charge_lrucare(page, mem,
2605                                         MEM_CGROUP_CHARGE_TYPE_CACHE);
2606                 return ret;
2607         }
2608         /* shmem */
2609         if (PageSwapCache(page)) {
2610                 ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
2611                 if (!ret)
2612                         __mem_cgroup_commit_charge_swapin(page, mem,
2613                                         MEM_CGROUP_CHARGE_TYPE_SHMEM);
2614         } else
2615                 ret = mem_cgroup_charge_common(page, mm, gfp_mask,
2616                                         MEM_CGROUP_CHARGE_TYPE_SHMEM);
2617
2618         return ret;
2619 }
2620
2621 /*
2622  * While swap-in, try_charge -> commit or cancel, the page is locked.
2623  * And when try_charge() successfully returns, one refcnt to memcg without
2624  * struct page_cgroup is acquired. This refcnt will be consumed by
2625  * "commit()" or removed by "cancel()"
2626  */
2627 int mem_cgroup_try_charge_swapin(struct mm_struct *mm,
2628                                  struct page *page,
2629                                  gfp_t mask, struct mem_cgroup **ptr)
2630 {
2631         struct mem_cgroup *mem;
2632         int ret;
2633
2634         *ptr = NULL;
2635
2636         if (mem_cgroup_disabled())
2637                 return 0;
2638
2639         if (!do_swap_account)
2640                 goto charge_cur_mm;
2641         /*
2642          * A racing thread's fault, or swapoff, may have already updated
2643          * the pte, and even removed page from swap cache: in those cases
2644          * do_swap_page()'s pte_same() test will fail; but there's also a
2645          * KSM case which does need to charge the page.
2646          */
2647         if (!PageSwapCache(page))
2648                 goto charge_cur_mm;
2649         mem = try_get_mem_cgroup_from_page(page);
2650         if (!mem)
2651                 goto charge_cur_mm;
2652         *ptr = mem;
2653         ret = __mem_cgroup_try_charge(NULL, mask, 1, ptr, true);
2654         css_put(&mem->css);
2655         return ret;
2656 charge_cur_mm:
2657         if (unlikely(!mm))
2658                 mm = &init_mm;
2659         return __mem_cgroup_try_charge(mm, mask, 1, ptr, true);
2660 }
2661
2662 static void
2663 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
2664                                         enum charge_type ctype)
2665 {
2666         if (mem_cgroup_disabled())
2667                 return;
2668         if (!ptr)
2669                 return;
2670         cgroup_exclude_rmdir(&ptr->css);
2671
2672         __mem_cgroup_commit_charge_lrucare(page, ptr, ctype);
2673         /*
2674          * Now swap is on-memory. This means this page may be
2675          * counted both as mem and swap....double count.
2676          * Fix it by uncharging from memsw. Basically, this SwapCache is stable
2677          * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
2678          * may call delete_from_swap_cache() before reach here.
2679          */
2680         if (do_swap_account && PageSwapCache(page)) {
2681                 swp_entry_t ent = {.val = page_private(page)};
2682                 unsigned short id;
2683                 struct mem_cgroup *memcg;
2684
2685                 id = swap_cgroup_record(ent, 0);
2686                 rcu_read_lock();
2687                 memcg = mem_cgroup_lookup(id);
2688                 if (memcg) {
2689                         /*
2690                          * This recorded memcg can be obsolete one. So, avoid
2691                          * calling css_tryget
2692                          */
2693                         if (!mem_cgroup_is_root(memcg))
2694                                 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
2695                         mem_cgroup_swap_statistics(memcg, false);
2696                         mem_cgroup_put(memcg);
2697                 }
2698                 rcu_read_unlock();
2699         }
2700         /*
2701          * At swapin, we may charge account against cgroup which has no tasks.
2702          * So, rmdir()->pre_destroy() can be called while we do this charge.
2703          * In that case, we need to call pre_destroy() again. check it here.
2704          */
2705         cgroup_release_and_wakeup_rmdir(&ptr->css);
2706 }
2707
2708 void mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr)
2709 {
2710         __mem_cgroup_commit_charge_swapin(page, ptr,
2711                                         MEM_CGROUP_CHARGE_TYPE_MAPPED);
2712 }
2713
2714 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *mem)
2715 {
2716         if (mem_cgroup_disabled())
2717                 return;
2718         if (!mem)
2719                 return;
2720         __mem_cgroup_cancel_charge(mem, 1);
2721 }
2722
2723 static void mem_cgroup_do_uncharge(struct mem_cgroup *mem,
2724                                    unsigned int nr_pages,
2725                                    const enum charge_type ctype)
2726 {
2727         struct memcg_batch_info *batch = NULL;
2728         bool uncharge_memsw = true;
2729
2730         /* If swapout, usage of swap doesn't decrease */
2731         if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2732                 uncharge_memsw = false;
2733
2734         batch = &current->memcg_batch;
2735         /*
2736          * In usual, we do css_get() when we remember memcg pointer.
2737          * But in this case, we keep res->usage until end of a series of
2738          * uncharges. Then, it's ok to ignore memcg's refcnt.
2739          */
2740         if (!batch->memcg)
2741                 batch->memcg = mem;
2742         /*
2743          * do_batch > 0 when unmapping pages or inode invalidate/truncate.
2744          * In those cases, all pages freed continuously can be expected to be in
2745          * the same cgroup and we have chance to coalesce uncharges.
2746          * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
2747          * because we want to do uncharge as soon as possible.
2748          */
2749
2750         if (!batch->do_batch || test_thread_flag(TIF_MEMDIE))
2751                 goto direct_uncharge;
2752
2753         if (nr_pages > 1)
2754                 goto direct_uncharge;
2755
2756         /*
2757          * In typical case, batch->memcg == mem. This means we can
2758          * merge a series of uncharges to an uncharge of res_counter.
2759          * If not, we uncharge res_counter ony by one.
2760          */
2761         if (batch->memcg != mem)
2762                 goto direct_uncharge;
2763         /* remember freed charge and uncharge it later */
2764         batch->nr_pages++;
2765         if (uncharge_memsw)
2766                 batch->memsw_nr_pages++;
2767         return;
2768 direct_uncharge:
2769         res_counter_uncharge(&mem->res, nr_pages * PAGE_SIZE);
2770         if (uncharge_memsw)
2771                 res_counter_uncharge(&mem->memsw, nr_pages * PAGE_SIZE);
2772         if (unlikely(batch->memcg != mem))
2773                 memcg_oom_recover(mem);
2774         return;
2775 }
2776
2777 /*
2778  * uncharge if !page_mapped(page)
2779  */
2780 static struct mem_cgroup *
2781 __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype)
2782 {
2783         struct mem_cgroup *mem = NULL;
2784         unsigned int nr_pages = 1;
2785         struct page_cgroup *pc;
2786
2787         if (mem_cgroup_disabled())
2788                 return NULL;
2789
2790         if (PageSwapCache(page))
2791                 return NULL;
2792
2793         if (PageTransHuge(page)) {
2794                 nr_pages <<= compound_order(page);
2795                 VM_BUG_ON(!PageTransHuge(page));
2796         }
2797         /*
2798          * Check if our page_cgroup is valid
2799          */
2800         pc = lookup_page_cgroup(page);
2801         if (unlikely(!pc || !PageCgroupUsed(pc)))
2802                 return NULL;
2803
2804         lock_page_cgroup(pc);
2805
2806         mem = pc->mem_cgroup;
2807
2808         if (!PageCgroupUsed(pc))
2809                 goto unlock_out;
2810
2811         switch (ctype) {
2812         case MEM_CGROUP_CHARGE_TYPE_MAPPED:
2813         case MEM_CGROUP_CHARGE_TYPE_DROP:
2814                 /* See mem_cgroup_prepare_migration() */
2815                 if (page_mapped(page) || PageCgroupMigration(pc))
2816                         goto unlock_out;
2817                 break;
2818         case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
2819                 if (!PageAnon(page)) {  /* Shared memory */
2820                         if (page->mapping && !page_is_file_cache(page))
2821                                 goto unlock_out;
2822                 } else if (page_mapped(page)) /* Anon */
2823                                 goto unlock_out;
2824                 break;
2825         default:
2826                 break;
2827         }
2828
2829         mem_cgroup_charge_statistics(mem, PageCgroupCache(pc), -nr_pages);
2830
2831         ClearPageCgroupUsed(pc);
2832         /*
2833          * pc->mem_cgroup is not cleared here. It will be accessed when it's
2834          * freed from LRU. This is safe because uncharged page is expected not
2835          * to be reused (freed soon). Exception is SwapCache, it's handled by
2836          * special functions.
2837          */
2838
2839         unlock_page_cgroup(pc);
2840         /*
2841          * even after unlock, we have mem->res.usage here and this memcg
2842          * will never be freed.
2843          */
2844         memcg_check_events(mem, page);
2845         if (do_swap_account && ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT) {
2846                 mem_cgroup_swap_statistics(mem, true);
2847                 mem_cgroup_get(mem);
2848         }
2849         if (!mem_cgroup_is_root(mem))
2850                 mem_cgroup_do_uncharge(mem, nr_pages, ctype);
2851
2852         return mem;
2853
2854 unlock_out:
2855         unlock_page_cgroup(pc);
2856         return NULL;
2857 }
2858
2859 void mem_cgroup_uncharge_page(struct page *page)
2860 {
2861         /* early check. */
2862         if (page_mapped(page))
2863                 return;
2864         if (page->mapping && !PageAnon(page))
2865                 return;
2866         __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_MAPPED);
2867 }
2868
2869 void mem_cgroup_uncharge_cache_page(struct page *page)
2870 {
2871         VM_BUG_ON(page_mapped(page));
2872         VM_BUG_ON(page->mapping);
2873         __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE);
2874 }
2875
2876 /*
2877  * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
2878  * In that cases, pages are freed continuously and we can expect pages
2879  * are in the same memcg. All these calls itself limits the number of
2880  * pages freed at once, then uncharge_start/end() is called properly.
2881  * This may be called prural(2) times in a context,
2882  */
2883
2884 void mem_cgroup_uncharge_start(void)
2885 {
2886         current->memcg_batch.do_batch++;
2887         /* We can do nest. */
2888         if (current->memcg_batch.do_batch == 1) {
2889                 current->memcg_batch.memcg = NULL;
2890                 current->memcg_batch.nr_pages = 0;
2891                 current->memcg_batch.memsw_nr_pages = 0;
2892         }
2893 }
2894
2895 void mem_cgroup_uncharge_end(void)
2896 {
2897         struct memcg_batch_info *batch = &current->memcg_batch;
2898
2899         if (!batch->do_batch)
2900                 return;
2901
2902         batch->do_batch--;
2903         if (batch->do_batch) /* If stacked, do nothing. */
2904                 return;
2905
2906         if (!batch->memcg)
2907                 return;
2908         /*
2909          * This "batch->memcg" is valid without any css_get/put etc...
2910          * bacause we hide charges behind us.
2911          */
2912         if (batch->nr_pages)
2913                 res_counter_uncharge(&batch->memcg->res,
2914                                      batch->nr_pages * PAGE_SIZE);
2915         if (batch->memsw_nr_pages)
2916                 res_counter_uncharge(&batch->memcg->memsw,
2917                                      batch->memsw_nr_pages * PAGE_SIZE);
2918         memcg_oom_recover(batch->memcg);
2919         /* forget this pointer (for sanity check) */
2920         batch->memcg = NULL;
2921 }
2922
2923 #ifdef CONFIG_SWAP
2924 /*
2925  * called after __delete_from_swap_cache() and drop "page" account.
2926  * memcg information is recorded to swap_cgroup of "ent"
2927  */
2928 void
2929 mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
2930 {
2931         struct mem_cgroup *memcg;
2932         int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
2933
2934         if (!swapout) /* this was a swap cache but the swap is unused ! */
2935                 ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
2936
2937         memcg = __mem_cgroup_uncharge_common(page, ctype);
2938
2939         /*
2940          * record memcg information,  if swapout && memcg != NULL,
2941          * mem_cgroup_get() was called in uncharge().
2942          */
2943         if (do_swap_account && swapout && memcg)
2944                 swap_cgroup_record(ent, css_id(&memcg->css));
2945 }
2946 #endif
2947
2948 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
2949 /*
2950  * called from swap_entry_free(). remove record in swap_cgroup and
2951  * uncharge "memsw" account.
2952  */
2953 void mem_cgroup_uncharge_swap(swp_entry_t ent)
2954 {
2955         struct mem_cgroup *memcg;
2956         unsigned short id;
2957
2958         if (!do_swap_account)
2959                 return;
2960
2961         id = swap_cgroup_record(ent, 0);
2962         rcu_read_lock();
2963         memcg = mem_cgroup_lookup(id);
2964         if (memcg) {
2965                 /*
2966                  * We uncharge this because swap is freed.
2967                  * This memcg can be obsolete one. We avoid calling css_tryget
2968                  */
2969                 if (!mem_cgroup_is_root(memcg))
2970                         res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
2971                 mem_cgroup_swap_statistics(memcg, false);
2972                 mem_cgroup_put(memcg);
2973         }
2974         rcu_read_unlock();
2975 }
2976
2977 /**
2978  * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
2979  * @entry: swap entry to be moved
2980  * @from:  mem_cgroup which the entry is moved from
2981  * @to:  mem_cgroup which the entry is moved to
2982  * @need_fixup: whether we should fixup res_counters and refcounts.
2983  *
2984  * It succeeds only when the swap_cgroup's record for this entry is the same
2985  * as the mem_cgroup's id of @from.
2986  *
2987  * Returns 0 on success, -EINVAL on failure.
2988  *
2989  * The caller must have charged to @to, IOW, called res_counter_charge() about
2990  * both res and memsw, and called css_get().
2991  */
2992 static int mem_cgroup_move_swap_account(swp_entry_t entry,
2993                 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
2994 {
2995         unsigned short old_id, new_id;
2996
2997         old_id = css_id(&from->css);
2998         new_id = css_id(&to->css);
2999
3000         if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
3001                 mem_cgroup_swap_statistics(from, false);
3002                 mem_cgroup_swap_statistics(to, true);
3003                 /*
3004                  * This function is only called from task migration context now.
3005                  * It postpones res_counter and refcount handling till the end
3006                  * of task migration(mem_cgroup_clear_mc()) for performance
3007                  * improvement. But we cannot postpone mem_cgroup_get(to)
3008                  * because if the process that has been moved to @to does
3009                  * swap-in, the refcount of @to might be decreased to 0.
3010                  */
3011                 mem_cgroup_get(to);
3012                 if (need_fixup) {
3013                         if (!mem_cgroup_is_root(from))
3014                                 res_counter_uncharge(&from->memsw, PAGE_SIZE);
3015                         mem_cgroup_put(from);
3016                         /*
3017                          * we charged both to->res and to->memsw, so we should
3018                          * uncharge to->res.
3019                          */
3020                         if (!mem_cgroup_is_root(to))
3021                                 res_counter_uncharge(&to->res, PAGE_SIZE);
3022                 }
3023                 return 0;
3024         }
3025         return -EINVAL;
3026 }
3027 #else
3028 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
3029                 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
3030 {
3031         return -EINVAL;
3032 }
3033 #endif
3034
3035 /*
3036  * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
3037  * page belongs to.
3038  */
3039 int mem_cgroup_prepare_migration(struct page *page,
3040         struct page *newpage, struct mem_cgroup **ptr, gfp_t gfp_mask)
3041 {
3042         struct mem_cgroup *mem = NULL;
3043         struct page_cgroup *pc;
3044         enum charge_type ctype;
3045         int ret = 0;
3046
3047         *ptr = NULL;
3048
3049         VM_BUG_ON(PageTransHuge(page));
3050         if (mem_cgroup_disabled())
3051                 return 0;
3052
3053         pc = lookup_page_cgroup(page);
3054         lock_page_cgroup(pc);
3055         if (PageCgroupUsed(pc)) {
3056                 mem = pc->mem_cgroup;
3057                 css_get(&mem->css);
3058                 /*
3059                  * At migrating an anonymous page, its mapcount goes down
3060                  * to 0 and uncharge() will be called. But, even if it's fully
3061                  * unmapped, migration may fail and this page has to be
3062                  * charged again. We set MIGRATION flag here and delay uncharge
3063                  * until end_migration() is called
3064                  *
3065                  * Corner Case Thinking
3066                  * A)
3067                  * When the old page was mapped as Anon and it's unmap-and-freed
3068                  * while migration was ongoing.
3069                  * If unmap finds the old page, uncharge() of it will be delayed
3070                  * until end_migration(). If unmap finds a new page, it's
3071                  * uncharged when it make mapcount to be 1->0. If unmap code
3072                  * finds swap_migration_entry, the new page will not be mapped
3073                  * and end_migration() will find it(mapcount==0).
3074                  *
3075                  * B)
3076                  * When the old page was mapped but migraion fails, the kernel
3077                  * remaps it. A charge for it is kept by MIGRATION flag even
3078                  * if mapcount goes down to 0. We can do remap successfully
3079                  * without charging it again.
3080                  *
3081                  * C)
3082                  * The "old" page is under lock_page() until the end of
3083                  * migration, so, the old page itself will not be swapped-out.
3084                  * If the new page is swapped out before end_migraton, our
3085                  * hook to usual swap-out path will catch the event.
3086                  */
3087                 if (PageAnon(page))
3088                         SetPageCgroupMigration(pc);
3089         }
3090         unlock_page_cgroup(pc);
3091         /*
3092          * If the page is not charged at this point,
3093          * we return here.
3094          */
3095         if (!mem)
3096                 return 0;
3097
3098         *ptr = mem;
3099         ret = __mem_cgroup_try_charge(NULL, gfp_mask, 1, ptr, false);
3100         css_put(&mem->css);/* drop extra refcnt */
3101         if (ret || *ptr == NULL) {
3102                 if (PageAnon(page)) {
3103                         lock_page_cgroup(pc);
3104                         ClearPageCgroupMigration(pc);
3105                         unlock_page_cgroup(pc);
3106                         /*
3107                          * The old page may be fully unmapped while we kept it.
3108                          */
3109                         mem_cgroup_uncharge_page(page);
3110                 }
3111                 return -ENOMEM;
3112         }
3113         /*
3114          * We charge new page before it's used/mapped. So, even if unlock_page()
3115          * is called before end_migration, we can catch all events on this new
3116          * page. In the case new page is migrated but not remapped, new page's
3117          * mapcount will be finally 0 and we call uncharge in end_migration().
3118          */
3119         pc = lookup_page_cgroup(newpage);
3120         if (PageAnon(page))
3121                 ctype = MEM_CGROUP_CHARGE_TYPE_MAPPED;
3122         else if (page_is_file_cache(page))
3123                 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
3124         else
3125                 ctype = MEM_CGROUP_CHARGE_TYPE_SHMEM;
3126         __mem_cgroup_commit_charge(mem, page, 1, pc, ctype);
3127         return ret;
3128 }
3129
3130 /* remove redundant charge if migration failed*/
3131 void mem_cgroup_end_migration(struct mem_cgroup *mem,
3132         struct page *oldpage, struct page *newpage, bool migration_ok)
3133 {
3134         struct page *used, *unused;
3135         struct page_cgroup *pc;
3136
3137         if (!mem)
3138                 return;
3139         /* blocks rmdir() */
3140         cgroup_exclude_rmdir(&mem->css);
3141         if (!migration_ok) {
3142                 used = oldpage;
3143                 unused = newpage;
3144         } else {
3145                 used = newpage;
3146                 unused = oldpage;
3147         }
3148         /*
3149          * We disallowed uncharge of pages under migration because mapcount
3150          * of the page goes down to zero, temporarly.
3151          * Clear the flag and check the page should be charged.
3152          */
3153         pc = lookup_page_cgroup(oldpage);
3154         lock_page_cgroup(pc);
3155         ClearPageCgroupMigration(pc);
3156         unlock_page_cgroup(pc);
3157
3158         __mem_cgroup_uncharge_common(unused, MEM_CGROUP_CHARGE_TYPE_FORCE);
3159
3160         /*
3161          * If a page is a file cache, radix-tree replacement is very atomic
3162          * and we can skip this check. When it was an Anon page, its mapcount
3163          * goes down to 0. But because we added MIGRATION flage, it's not
3164          * uncharged yet. There are several case but page->mapcount check
3165          * and USED bit check in mem_cgroup_uncharge_page() will do enough
3166          * check. (see prepare_charge() also)
3167          */
3168         if (PageAnon(used))
3169                 mem_cgroup_uncharge_page(used);
3170         /*
3171          * At migration, we may charge account against cgroup which has no
3172          * tasks.
3173          * So, rmdir()->pre_destroy() can be called while we do this charge.
3174          * In that case, we need to call pre_destroy() again. check it here.
3175          */
3176         cgroup_release_and_wakeup_rmdir(&mem->css);
3177 }
3178
3179 /*
3180  * A call to try to shrink memory usage on charge failure at shmem's swapin.
3181  * Calling hierarchical_reclaim is not enough because we should update
3182  * last_oom_jiffies to prevent pagefault_out_of_memory from invoking global OOM.
3183  * Moreover considering hierarchy, we should reclaim from the mem_over_limit,
3184  * not from the memcg which this page would be charged to.
3185  * try_charge_swapin does all of these works properly.
3186  */
3187 int mem_cgroup_shmem_charge_fallback(struct page *page,
3188                             struct mm_struct *mm,
3189                             gfp_t gfp_mask)
3190 {
3191         struct mem_cgroup *mem;
3192         int ret;
3193
3194         if (mem_cgroup_disabled())
3195                 return 0;
3196
3197         ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
3198         if (!ret)
3199                 mem_cgroup_cancel_charge_swapin(mem); /* it does !mem check */
3200
3201         return ret;
3202 }
3203
3204 #ifdef CONFIG_DEBUG_VM
3205 static struct page_cgroup *lookup_page_cgroup_used(struct page *page)
3206 {
3207         struct page_cgroup *pc;
3208
3209         pc = lookup_page_cgroup(page);
3210         if (likely(pc) && PageCgroupUsed(pc))
3211                 return pc;
3212         return NULL;
3213 }
3214
3215 bool mem_cgroup_bad_page_check(struct page *page)
3216 {
3217         if (mem_cgroup_disabled())
3218                 return false;
3219
3220         return lookup_page_cgroup_used(page) != NULL;
3221 }
3222
3223 void mem_cgroup_print_bad_page(struct page *page)
3224 {
3225         struct page_cgroup *pc;
3226
3227         pc = lookup_page_cgroup_used(page);
3228         if (pc) {
3229                 int ret = -1;
3230                 char *path;
3231
3232                 printk(KERN_ALERT "pc:%p pc->flags:%lx pc->mem_cgroup:%p",
3233                        pc, pc->flags, pc->mem_cgroup);
3234
3235                 path = kmalloc(PATH_MAX, GFP_KERNEL);
3236                 if (path) {
3237                         rcu_read_lock();
3238                         ret = cgroup_path(pc->mem_cgroup->css.cgroup,
3239                                                         path, PATH_MAX);
3240                         rcu_read_unlock();
3241                 }
3242
3243                 printk(KERN_CONT "(%s)\n",
3244                                 (ret < 0) ? "cannot get the path" : path);
3245                 kfree(path);
3246         }
3247 }
3248 #endif
3249
3250 static DEFINE_MUTEX(set_limit_mutex);
3251
3252 static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
3253                                 unsigned long long val)
3254 {
3255         int retry_count;
3256         u64 memswlimit, memlimit;
3257         int ret = 0;
3258         int children = mem_cgroup_count_children(memcg);
3259         u64 curusage, oldusage;
3260         int enlarge;
3261
3262         /*
3263          * For keeping hierarchical_reclaim simple, how long we should retry
3264          * is depends on callers. We set our retry-count to be function
3265          * of # of children which we should visit in this loop.
3266          */
3267         retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
3268
3269         oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
3270
3271         enlarge = 0;
3272         while (retry_count) {
3273                 if (signal_pending(current)) {
3274                         ret = -EINTR;
3275                         break;
3276                 }
3277                 /*
3278                  * Rather than hide all in some function, I do this in
3279                  * open coded manner. You see what this really does.
3280                  * We have to guarantee mem->res.limit < mem->memsw.limit.
3281                  */
3282                 mutex_lock(&set_limit_mutex);
3283                 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3284                 if (memswlimit < val) {
3285                         ret = -EINVAL;
3286                         mutex_unlock(&set_limit_mutex);
3287                         break;
3288                 }
3289
3290                 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3291                 if (memlimit < val)
3292                         enlarge = 1;
3293
3294                 ret = res_counter_set_limit(&memcg->res, val);
3295                 if (!ret) {
3296                         if (memswlimit == val)
3297                                 memcg->memsw_is_minimum = true;
3298                         else
3299                                 memcg->memsw_is_minimum = false;
3300                 }
3301                 mutex_unlock(&set_limit_mutex);
3302
3303                 if (!ret)
3304                         break;
3305
3306                 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
3307                                                 MEM_CGROUP_RECLAIM_SHRINK,
3308                                                 NULL);
3309                 curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
3310                 /* Usage is reduced ? */
3311                 if (curusage >= oldusage)
3312                         retry_count--;
3313                 else
3314                         oldusage = curusage;
3315         }
3316         if (!ret && enlarge)
3317                 memcg_oom_recover(memcg);
3318
3319         return ret;
3320 }
3321
3322 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
3323                                         unsigned long long val)
3324 {
3325         int retry_count;
3326         u64 memlimit, memswlimit, oldusage, curusage;
3327         int children = mem_cgroup_count_children(memcg);
3328         int ret = -EBUSY;
3329         int enlarge = 0;
3330
3331         /* see mem_cgroup_resize_res_limit */
3332         retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
3333         oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
3334         while (retry_count) {
3335                 if (signal_pending(current)) {
3336                         ret = -EINTR;
3337                         break;
3338                 }
3339                 /*
3340                  * Rather than hide all in some function, I do this in
3341                  * open coded manner. You see what this really does.
3342                  * We have to guarantee mem->res.limit < mem->memsw.limit.
3343                  */
3344                 mutex_lock(&set_limit_mutex);
3345                 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3346                 if (memlimit > val) {
3347                         ret = -EINVAL;
3348                         mutex_unlock(&set_limit_mutex);
3349                         break;
3350                 }
3351                 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3352                 if (memswlimit < val)
3353                         enlarge = 1;
3354                 ret = res_counter_set_limit(&memcg->memsw, val);
3355                 if (!ret) {
3356                         if (memlimit == val)
3357                                 memcg->memsw_is_minimum = true;
3358                         else
3359                                 memcg->memsw_is_minimum = false;
3360                 }
3361                 mutex_unlock(&set_limit_mutex);
3362
3363                 if (!ret)
3364                         break;
3365
3366                 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
3367                                                 MEM_CGROUP_RECLAIM_NOSWAP |
3368                                                 MEM_CGROUP_RECLAIM_SHRINK,
3369                                                 NULL);
3370                 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
3371                 /* Usage is reduced ? */
3372                 if (curusage >= oldusage)
3373                         retry_count--;
3374                 else
3375                         oldusage = curusage;
3376         }
3377         if (!ret && enlarge)
3378                 memcg_oom_recover(memcg);
3379         return ret;
3380 }
3381
3382 unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
3383                                             gfp_t gfp_mask,
3384                                             unsigned long *total_scanned)
3385 {
3386         unsigned long nr_reclaimed = 0;
3387         struct mem_cgroup_per_zone *mz, *next_mz = NULL;
3388         unsigned long reclaimed;
3389         int loop = 0;
3390         struct mem_cgroup_tree_per_zone *mctz;
3391         unsigned long long excess;
3392         unsigned long nr_scanned;
3393
3394         if (order > 0)
3395                 return 0;
3396
3397         mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone));
3398         /*
3399          * This loop can run a while, specially if mem_cgroup's continuously
3400          * keep exceeding their soft limit and putting the system under
3401          * pressure
3402          */
3403         do {
3404                 if (next_mz)
3405                         mz = next_mz;
3406                 else
3407                         mz = mem_cgroup_largest_soft_limit_node(mctz);
3408                 if (!mz)
3409                         break;
3410
3411                 nr_scanned = 0;
3412                 reclaimed = mem_cgroup_hierarchical_reclaim(mz->mem, zone,
3413                                                 gfp_mask,
3414                                                 MEM_CGROUP_RECLAIM_SOFT,
3415                                                 &nr_scanned);
3416                 nr_reclaimed += reclaimed;
3417                 *total_scanned += nr_scanned;
3418                 spin_lock(&mctz->lock);
3419
3420                 /*
3421                  * If we failed to reclaim anything from this memory cgroup
3422                  * it is time to move on to the next cgroup
3423                  */
3424                 next_mz = NULL;
3425                 if (!reclaimed) {
3426                         do {
3427                                 /*
3428                                  * Loop until we find yet another one.
3429                                  *
3430                                  * By the time we get the soft_limit lock
3431                                  * again, someone might have aded the
3432                                  * group back on the RB tree. Iterate to
3433                                  * make sure we get a different mem.
3434                                  * mem_cgroup_largest_soft_limit_node returns
3435                                  * NULL if no other cgroup is present on
3436                                  * the tree
3437                                  */
3438                                 next_mz =
3439                                 __mem_cgroup_largest_soft_limit_node(mctz);
3440                                 if (next_mz == mz)
3441                                         css_put(&next_mz->mem->css);
3442                                 else /* next_mz == NULL or other memcg */
3443                                         break;
3444                         } while (1);
3445                 }
3446                 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
3447                 excess = res_counter_soft_limit_excess(&mz->mem->res);
3448                 /*
3449                  * One school of thought says that we should not add
3450                  * back the node to the tree if reclaim returns 0.
3451                  * But our reclaim could return 0, simply because due
3452                  * to priority we are exposing a smaller subset of
3453                  * memory to reclaim from. Consider this as a longer
3454                  * term TODO.
3455                  */
3456                 /* If excess == 0, no tree ops */
3457                 __mem_cgroup_insert_exceeded(mz->mem, mz, mctz, excess);
3458                 spin_unlock(&mctz->lock);
3459                 css_put(&mz->mem->css);
3460                 loop++;
3461                 /*
3462                  * Could not reclaim anything and there are no more
3463                  * mem cgroups to try or we seem to be looping without
3464                  * reclaiming anything.
3465                  */
3466                 if (!nr_reclaimed &&
3467                         (next_mz == NULL ||
3468                         loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3469                         break;
3470         } while (!nr_reclaimed);
3471         if (next_mz)
3472                 css_put(&next_mz->mem->css);
3473         return nr_reclaimed;
3474 }
3475
3476 /*
3477  * This routine traverse page_cgroup in given list and drop them all.
3478  * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
3479  */
3480 static int mem_cgroup_force_empty_list(struct mem_cgroup *mem,
3481                                 int node, int zid, enum lru_list lru)
3482 {
3483         struct zone *zone;
3484         struct mem_cgroup_per_zone *mz;
3485         struct page_cgroup *pc, *busy;
3486         unsigned long flags, loop;
3487         struct list_head *list;
3488         int ret = 0;
3489
3490         zone = &NODE_DATA(node)->node_zones[zid];
3491         mz = mem_cgroup_zoneinfo(mem, node, zid);
3492         list = &mz->lists[lru];
3493
3494         loop = MEM_CGROUP_ZSTAT(mz, lru);
3495         /* give some margin against EBUSY etc...*/
3496         loop += 256;
3497         busy = NULL;
3498         while (loop--) {
3499                 struct page *page;
3500
3501                 ret = 0;
3502                 spin_lock_irqsave(&zone->lru_lock, flags);
3503                 if (list_empty(list)) {
3504                         spin_unlock_irqrestore(&zone->lru_lock, flags);
3505                         break;
3506                 }
3507                 pc = list_entry(list->prev, struct page_cgroup, lru);
3508                 if (busy == pc) {
3509                         list_move(&pc->lru, list);
3510                         busy = NULL;
3511                         spin_unlock_irqrestore(&zone->lru_lock, flags);
3512                         continue;
3513                 }
3514                 spin_unlock_irqrestore(&zone->lru_lock, flags);
3515
3516                 page = lookup_cgroup_page(pc);
3517
3518                 ret = mem_cgroup_move_parent(page, pc, mem, GFP_KERNEL);
3519                 if (ret == -ENOMEM)
3520                         break;
3521
3522                 if (ret == -EBUSY || ret == -EINVAL) {
3523                         /* found lock contention or "pc" is obsolete. */
3524                         busy = pc;
3525                         cond_resched();
3526                 } else
3527                         busy = NULL;
3528         }
3529
3530         if (!ret && !list_empty(list))
3531                 return -EBUSY;
3532         return ret;
3533 }
3534
3535 /*
3536  * make mem_cgroup's charge to be 0 if there is no task.
3537  * This enables deleting this mem_cgroup.
3538  */
3539 static int mem_cgroup_force_empty(struct mem_cgroup *mem, bool free_all)
3540 {
3541         int ret;
3542         int node, zid, shrink;
3543         int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
3544         struct cgroup *cgrp = mem->css.cgroup;
3545
3546         css_get(&mem->css);
3547
3548         shrink = 0;
3549         /* should free all ? */
3550         if (free_all)
3551                 goto try_to_free;
3552 move_account:
3553         do {
3554                 ret = -EBUSY;
3555                 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
3556                         goto out;
3557                 ret = -EINTR;
3558                 if (signal_pending(current))
3559                         goto out;
3560                 /* This is for making all *used* pages to be on LRU. */
3561                 lru_add_drain_all();
3562                 drain_all_stock_sync();
3563                 ret = 0;
3564                 mem_cgroup_start_move(mem);
3565                 for_each_node_state(node, N_HIGH_MEMORY) {
3566                         for (zid = 0; !ret && zid < MAX_NR_ZONES; zid++) {
3567                                 enum lru_list l;
3568                                 for_each_lru(l) {
3569                                         ret = mem_cgroup_force_empty_list(mem,
3570                                                         node, zid, l);
3571                                         if (ret)
3572                                                 break;
3573                                 }
3574                         }
3575                         if (ret)
3576                                 break;
3577                 }
3578                 mem_cgroup_end_move(mem);
3579                 memcg_oom_recover(mem);
3580                 /* it seems parent cgroup doesn't have enough mem */
3581                 if (ret == -ENOMEM)
3582                         goto try_to_free;
3583                 cond_resched();
3584         /* "ret" should also be checked to ensure all lists are empty. */
3585         } while (mem->res.usage > 0 || ret);
3586 out:
3587         css_put(&mem->css);
3588         return ret;
3589
3590 try_to_free:
3591         /* returns EBUSY if there is a task or if we come here twice. */
3592         if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children) || shrink) {
3593                 ret = -EBUSY;
3594                 goto out;
3595         }
3596         /* we call try-to-free pages for make this cgroup empty */
3597         lru_add_drain_all();
3598         /* try to free all pages in this cgroup */
3599         shrink = 1;
3600         while (nr_retries && mem->res.usage > 0) {
3601                 int progress;
3602
3603                 if (signal_pending(current)) {
3604                         ret = -EINTR;
3605                         goto out;
3606                 }
3607                 progress = try_to_free_mem_cgroup_pages(mem, GFP_KERNEL,
3608                                                 false, get_swappiness(mem));
3609                 if (!progress) {
3610                         nr_retries--;
3611                         /* maybe some writeback is necessary */
3612                         congestion_wait(BLK_RW_ASYNC, HZ/10);
3613                 }
3614
3615         }
3616         lru_add_drain();
3617         /* try move_account...there may be some *locked* pages. */
3618         goto move_account;
3619 }
3620
3621 int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
3622 {
3623         return mem_cgroup_force_empty(mem_cgroup_from_cont(cont), true);
3624 }
3625
3626
3627 static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
3628 {
3629         return mem_cgroup_from_cont(cont)->use_hierarchy;
3630 }
3631
3632 static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
3633                                         u64 val)
3634 {
3635         int retval = 0;
3636         struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
3637         struct cgroup *parent = cont->parent;
3638         struct mem_cgroup *parent_mem = NULL;
3639
3640         if (parent)
3641                 parent_mem = mem_cgroup_from_cont(parent);
3642
3643         cgroup_lock();
3644         /*
3645          * If parent's use_hierarchy is set, we can't make any modifications
3646          * in the child subtrees. If it is unset, then the change can
3647          * occur, provided the current cgroup has no children.
3648          *
3649          * For the root cgroup, parent_mem is NULL, we allow value to be
3650          * set if there are no children.
3651          */
3652         if ((!parent_mem || !parent_mem->use_hierarchy) &&
3653                                 (val == 1 || val == 0)) {
3654                 if (list_empty(&cont->children))
3655                         mem->use_hierarchy = val;
3656                 else
3657                         retval = -EBUSY;
3658         } else
3659                 retval = -EINVAL;
3660         cgroup_unlock();
3661
3662         return retval;
3663 }
3664
3665
3666 static unsigned long mem_cgroup_recursive_stat(struct mem_cgroup *mem,
3667                                                enum mem_cgroup_stat_index idx)
3668 {
3669         struct mem_cgroup *iter;
3670         long val = 0;
3671
3672         /* Per-cpu values can be negative, use a signed accumulator */
3673         for_each_mem_cgroup_tree(iter, mem)
3674                 val += mem_cgroup_read_stat(iter, idx);
3675
3676         if (val < 0) /* race ? */
3677                 val = 0;
3678         return val;
3679 }
3680
3681 static inline u64 mem_cgroup_usage(struct mem_cgroup *mem, bool swap)
3682 {
3683         u64 val;
3684
3685         if (!mem_cgroup_is_root(mem)) {
3686                 if (!swap)
3687                         return res_counter_read_u64(&mem->res, RES_USAGE);
3688                 else
3689                         return res_counter_read_u64(&mem->memsw, RES_USAGE);
3690         }
3691
3692         val = mem_cgroup_recursive_stat(mem, MEM_CGROUP_STAT_CACHE);
3693         val += mem_cgroup_recursive_stat(mem, MEM_CGROUP_STAT_RSS);
3694
3695         if (swap)
3696                 val += mem_cgroup_recursive_stat(mem, MEM_CGROUP_STAT_SWAPOUT);
3697
3698         return val << PAGE_SHIFT;
3699 }
3700
3701 static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft)
3702 {
3703         struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
3704         u64 val;
3705         int type, name;
3706
3707         type = MEMFILE_TYPE(cft->private);
3708         name = MEMFILE_ATTR(cft->private);
3709         switch (type) {
3710         case _MEM:
3711                 if (name == RES_USAGE)
3712                         val = mem_cgroup_usage(mem, false);
3713                 else
3714                         val = res_counter_read_u64(&mem->res, name);
3715                 break;
3716         case _MEMSWAP:
3717                 if (name == RES_USAGE)
3718                         val = mem_cgroup_usage(mem, true);
3719                 else
3720                         val = res_counter_read_u64(&mem->memsw, name);
3721                 break;
3722         default:
3723                 BUG();
3724                 break;
3725         }
3726         return val;
3727 }
3728 /*
3729  * The user of this function is...
3730  * RES_LIMIT.
3731  */
3732 static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
3733                             const char *buffer)
3734 {
3735         struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
3736         int type, name;
3737         unsigned long long val;
3738         int ret;
3739
3740         type = MEMFILE_TYPE(cft->private);
3741         name = MEMFILE_ATTR(cft->private);
3742         switch (name) {
3743         case RES_LIMIT:
3744                 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3745                         ret = -EINVAL;
3746                         break;
3747                 }
3748                 /* This function does all necessary parse...reuse it */
3749                 ret = res_counter_memparse_write_strategy(buffer, &val);
3750                 if (ret)
3751                         break;
3752                 if (type == _MEM)
3753                         ret = mem_cgroup_resize_limit(memcg, val);
3754                 else
3755                         ret = mem_cgroup_resize_memsw_limit(memcg, val);
3756                 break;
3757         case RES_SOFT_LIMIT:
3758                 ret = res_counter_memparse_write_strategy(buffer, &val);
3759                 if (ret)
3760                         break;
3761                 /*
3762                  * For memsw, soft limits are hard to implement in terms
3763                  * of semantics, for now, we support soft limits for
3764                  * control without swap
3765                  */
3766                 if (type == _MEM)
3767                         ret = res_counter_set_soft_limit(&memcg->res, val);
3768                 else
3769                         ret = -EINVAL;
3770                 break;
3771         default:
3772                 ret = -EINVAL; /* should be BUG() ? */
3773                 break;
3774         }
3775         return ret;
3776 }
3777
3778 static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
3779                 unsigned long long *mem_limit, unsigned long long *memsw_limit)
3780 {
3781         struct cgroup *cgroup;
3782         unsigned long long min_limit, min_memsw_limit, tmp;
3783
3784         min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3785         min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3786         cgroup = memcg->css.cgroup;
3787         if (!memcg->use_hierarchy)
3788                 goto out;
3789
3790         while (cgroup->parent) {
3791                 cgroup = cgroup->parent;
3792                 memcg = mem_cgroup_from_cont(cgroup);
3793                 if (!memcg->use_hierarchy)
3794                         break;
3795                 tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
3796                 min_limit = min(min_limit, tmp);
3797                 tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3798                 min_memsw_limit = min(min_memsw_limit, tmp);
3799         }
3800 out:
3801         *mem_limit = min_limit;
3802         *memsw_limit = min_memsw_limit;
3803         return;
3804 }
3805
3806 static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
3807 {
3808         struct mem_cgroup *mem;
3809         int type, name;
3810
3811         mem = mem_cgroup_from_cont(cont);
3812         type = MEMFILE_TYPE(event);
3813         name = MEMFILE_ATTR(event);
3814         switch (name) {
3815         case RES_MAX_USAGE:
3816                 if (type == _MEM)
3817                         res_counter_reset_max(&mem->res);
3818                 else
3819                         res_counter_reset_max(&mem->memsw);
3820                 break;
3821         case RES_FAILCNT:
3822                 if (type == _MEM)
3823                         res_counter_reset_failcnt(&mem->res);
3824                 else
3825                         res_counter_reset_failcnt(&mem->memsw);
3826                 break;
3827         }
3828
3829         return 0;
3830 }
3831
3832 static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp,
3833                                         struct cftype *cft)
3834 {
3835         return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate;
3836 }
3837
3838 #ifdef CONFIG_MMU
3839 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
3840                                         struct cftype *cft, u64 val)
3841 {
3842         struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
3843
3844         if (val >= (1 << NR_MOVE_TYPE))
3845                 return -EINVAL;
3846         /*
3847          * We check this value several times in both in can_attach() and
3848          * attach(), so we need cgroup lock to prevent this value from being
3849          * inconsistent.
3850          */
3851         cgroup_lock();
3852         mem->move_charge_at_immigrate = val;
3853         cgroup_unlock();
3854
3855         return 0;
3856 }
3857 #else
3858 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
3859                                         struct cftype *cft, u64 val)
3860 {
3861         return -ENOSYS;
3862 }
3863 #endif
3864
3865
3866 /* For read statistics */
3867 enum {
3868         MCS_CACHE,
3869         MCS_RSS,
3870         MCS_FILE_MAPPED,
3871         MCS_PGPGIN,
3872         MCS_PGPGOUT,
3873         MCS_SWAP,
3874         MCS_INACTIVE_ANON,
3875         MCS_ACTIVE_ANON,
3876         MCS_INACTIVE_FILE,
3877         MCS_ACTIVE_FILE,
3878         MCS_UNEVICTABLE,
3879         NR_MCS_STAT,
3880 };
3881
3882 struct mcs_total_stat {
3883         s64 stat[NR_MCS_STAT];
3884 };
3885
3886 struct {
3887         char *local_name;
3888         char *total_name;
3889 } memcg_stat_strings[NR_MCS_STAT] = {
3890         {"cache", "total_cache"},
3891         {"rss", "total_rss"},
3892         {"mapped_file", "total_mapped_file"},
3893         {"pgpgin", "total_pgpgin"},
3894         {"pgpgout", "total_pgpgout"},
3895         {"swap", "total_swap"},
3896         {"inactive_anon", "total_inactive_anon"},
3897         {"active_anon", "total_active_anon"},
3898         {"inactive_file", "total_inactive_file"},
3899         {"active_file", "total_active_file"},
3900         {"unevictable", "total_unevictable"}
3901 };
3902
3903
3904 static void
3905 mem_cgroup_get_local_stat(struct mem_cgroup *mem, struct mcs_total_stat *s)
3906 {
3907         s64 val;
3908
3909         /* per cpu stat */
3910         val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_CACHE);
3911         s->stat[MCS_CACHE] += val * PAGE_SIZE;
3912         val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_RSS);
3913         s->stat[MCS_RSS] += val * PAGE_SIZE;
3914         val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_FILE_MAPPED);
3915         s->stat[MCS_FILE_MAPPED] += val * PAGE_SIZE;
3916         val = mem_cgroup_read_events(mem, MEM_CGROUP_EVENTS_PGPGIN);
3917         s->stat[MCS_PGPGIN] += val;
3918         val = mem_cgroup_read_events(mem, MEM_CGROUP_EVENTS_PGPGOUT);
3919         s->stat[MCS_PGPGOUT] += val;
3920         if (do_swap_account) {
3921                 val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_SWAPOUT);
3922                 s->stat[MCS_SWAP] += val * PAGE_SIZE;
3923         }
3924
3925         /* per zone stat */
3926         val = mem_cgroup_get_local_zonestat(mem, LRU_INACTIVE_ANON);
3927         s->stat[MCS_INACTIVE_ANON] += val * PAGE_SIZE;
3928         val = mem_cgroup_get_local_zonestat(mem, LRU_ACTIVE_ANON);
3929         s->stat[MCS_ACTIVE_ANON] += val * PAGE_SIZE;
3930         val = mem_cgroup_get_local_zonestat(mem, LRU_INACTIVE_FILE);
3931         s->stat[MCS_INACTIVE_FILE] += val * PAGE_SIZE;
3932         val = mem_cgroup_get_local_zonestat(mem, LRU_ACTIVE_FILE);
3933         s->stat[MCS_ACTIVE_FILE] += val * PAGE_SIZE;
3934         val = mem_cgroup_get_local_zonestat(mem, LRU_UNEVICTABLE);
3935         s->stat[MCS_UNEVICTABLE] += val * PAGE_SIZE;
3936 }
3937
3938 static void
3939 mem_cgroup_get_total_stat(struct mem_cgroup *mem, struct mcs_total_stat *s)
3940 {
3941         struct mem_cgroup *iter;
3942
3943         for_each_mem_cgroup_tree(iter, mem)
3944                 mem_cgroup_get_local_stat(iter, s);
3945 }
3946
3947 static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft,
3948                                  struct cgroup_map_cb *cb)
3949 {
3950         struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
3951         struct mcs_total_stat mystat;
3952         int i;
3953
3954         memset(&mystat, 0, sizeof(mystat));
3955         mem_cgroup_get_local_stat(mem_cont, &mystat);
3956
3957         for (i = 0; i < NR_MCS_STAT; i++) {
3958                 if (i == MCS_SWAP && !do_swap_account)
3959                         continue;
3960                 cb->fill(cb, memcg_stat_strings[i].local_name, mystat.stat[i]);
3961         }
3962
3963         /* Hierarchical information */
3964         {
3965                 unsigned long long limit, memsw_limit;
3966                 memcg_get_hierarchical_limit(mem_cont, &limit, &memsw_limit);
3967                 cb->fill(cb, "hierarchical_memory_limit", limit);
3968                 if (do_swap_account)
3969                         cb->fill(cb, "hierarchical_memsw_limit", memsw_limit);
3970         }
3971
3972         memset(&mystat, 0, sizeof(mystat));
3973         mem_cgroup_get_total_stat(mem_cont, &mystat);
3974         for (i = 0; i < NR_MCS_STAT; i++) {
3975                 if (i == MCS_SWAP && !do_swap_account)
3976                         continue;
3977                 cb->fill(cb, memcg_stat_strings[i].total_name, mystat.stat[i]);
3978         }
3979
3980 #ifdef CONFIG_DEBUG_VM
3981         cb->fill(cb, "inactive_ratio", calc_inactive_ratio(mem_cont, NULL));
3982
3983         {
3984                 int nid, zid;
3985                 struct mem_cgroup_per_zone *mz;
3986                 unsigned long recent_rotated[2] = {0, 0};
3987                 unsigned long recent_scanned[2] = {0, 0};
3988
3989                 for_each_online_node(nid)
3990                         for (zid = 0; zid < MAX_NR_ZONES; zid++) {
3991                                 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
3992
3993                                 recent_rotated[0] +=
3994                                         mz->reclaim_stat.recent_rotated[0];
3995                                 recent_rotated[1] +=
3996                                         mz->reclaim_stat.recent_rotated[1];
3997                                 recent_scanned[0] +=
3998                                         mz->reclaim_stat.recent_scanned[0];
3999                                 recent_scanned[1] +=
4000                                         mz->reclaim_stat.recent_scanned[1];
4001                         }
4002                 cb->fill(cb, "recent_rotated_anon", recent_rotated[0]);
4003                 cb->fill(cb, "recent_rotated_file", recent_rotated[1]);
4004                 cb->fill(cb, "recent_scanned_anon", recent_scanned[0]);
4005                 cb->fill(cb, "recent_scanned_file", recent_scanned[1]);
4006         }
4007 #endif
4008
4009         return 0;
4010 }
4011
4012 static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
4013 {
4014         struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4015
4016         return get_swappiness(memcg);
4017 }
4018
4019 static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
4020                                        u64 val)
4021 {
4022         struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4023         struct mem_cgroup *parent;
4024
4025         if (val > 100)
4026                 return -EINVAL;
4027
4028         if (cgrp->parent == NULL)
4029                 return -EINVAL;
4030
4031         parent = mem_cgroup_from_cont(cgrp->parent);
4032
4033         cgroup_lock();
4034
4035         /* If under hierarchy, only empty-root can set this value */
4036         if ((parent->use_hierarchy) ||
4037             (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
4038                 cgroup_unlock();
4039                 return -EINVAL;
4040         }
4041
4042         memcg->swappiness = val;
4043
4044         cgroup_unlock();
4045
4046         return 0;
4047 }
4048
4049 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4050 {
4051         struct mem_cgroup_threshold_ary *t;
4052         u64 usage;
4053         int i;
4054
4055         rcu_read_lock();
4056         if (!swap)
4057                 t = rcu_dereference(memcg->thresholds.primary);
4058         else
4059                 t = rcu_dereference(memcg->memsw_thresholds.primary);
4060
4061         if (!t)
4062                 goto unlock;
4063
4064         usage = mem_cgroup_usage(memcg, swap);
4065
4066         /*
4067          * current_threshold points to threshold just below usage.
4068          * If it's not true, a threshold was crossed after last
4069          * call of __mem_cgroup_threshold().
4070          */
4071         i = t->current_threshold;
4072
4073         /*
4074          * Iterate backward over array of thresholds starting from
4075          * current_threshold and check if a threshold is crossed.
4076          * If none of thresholds below usage is crossed, we read
4077          * only one element of the array here.
4078          */
4079         for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4080                 eventfd_signal(t->entries[i].eventfd, 1);
4081
4082         /* i = current_threshold + 1 */
4083         i++;
4084
4085         /*
4086          * Iterate forward over array of thresholds starting from
4087          * current_threshold+1 and check if a threshold is crossed.
4088          * If none of thresholds above usage is crossed, we read
4089          * only one element of the array here.
4090          */
4091         for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4092                 eventfd_signal(t->entries[i].eventfd, 1);
4093
4094         /* Update current_threshold */
4095         t->current_threshold = i - 1;
4096 unlock:
4097         rcu_read_unlock();
4098 }
4099
4100 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4101 {
4102         while (memcg) {
4103                 __mem_cgroup_threshold(memcg, false);
4104                 if (do_swap_account)
4105                         __mem_cgroup_threshold(memcg, true);
4106
4107                 memcg = parent_mem_cgroup(memcg);
4108         }
4109 }
4110
4111 static int compare_thresholds(const void *a, const void *b)
4112 {
4113         const struct mem_cgroup_threshold *_a = a;
4114         const struct mem_cgroup_threshold *_b = b;
4115
4116         return _a->threshold - _b->threshold;
4117 }
4118
4119 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *mem)
4120 {
4121         struct mem_cgroup_eventfd_list *ev;
4122
4123         list_for_each_entry(ev, &mem->oom_notify, list)
4124                 eventfd_signal(ev->eventfd, 1);
4125         return 0;
4126 }
4127
4128 static void mem_cgroup_oom_notify(struct mem_cgroup *mem)
4129 {
4130         struct mem_cgroup *iter;
4131
4132         for_each_mem_cgroup_tree(iter, mem)
4133                 mem_cgroup_oom_notify_cb(iter);
4134 }
4135
4136 static int mem_cgroup_usage_register_event(struct cgroup *cgrp,
4137         struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
4138 {
4139         struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4140         struct mem_cgroup_thresholds *thresholds;
4141         struct mem_cgroup_threshold_ary *new;
4142         int type = MEMFILE_TYPE(cft->private);
4143         u64 threshold, usage;
4144         int i, size, ret;
4145
4146         ret = res_counter_memparse_write_strategy(args, &threshold);
4147         if (ret)
4148                 return ret;
4149
4150         mutex_lock(&memcg->thresholds_lock);
4151
4152         if (type == _MEM)
4153                 thresholds = &memcg->thresholds;
4154         else if (type == _MEMSWAP)
4155                 thresholds = &memcg->memsw_thresholds;
4156         else
4157                 BUG();
4158
4159         usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
4160
4161         /* Check if a threshold crossed before adding a new one */
4162         if (thresholds->primary)
4163                 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4164
4165         size = thresholds->primary ? thresholds->primary->size + 1 : 1;
4166
4167         /* Allocate memory for new array of thresholds */
4168         new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
4169                         GFP_KERNEL);
4170         if (!new) {
4171                 ret = -ENOMEM;
4172                 goto unlock;
4173         }
4174         new->size = size;
4175
4176         /* Copy thresholds (if any) to new array */
4177         if (thresholds->primary) {
4178                 memcpy(new->entries, thresholds->primary->entries, (size - 1) *
4179                                 sizeof(struct mem_cgroup_threshold));
4180         }
4181
4182         /* Add new threshold */
4183         new->entries[size - 1].eventfd = eventfd;
4184         new->entries[size - 1].threshold = threshold;
4185
4186         /* Sort thresholds. Registering of new threshold isn't time-critical */
4187         sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
4188                         compare_thresholds, NULL);
4189
4190         /* Find current threshold */
4191         new->current_threshold = -1;
4192         for (i = 0; i < size; i++) {
4193                 if (new->entries[i].threshold < usage) {
4194                         /*
4195                          * new->current_threshold will not be used until
4196                          * rcu_assign_pointer(), so it's safe to increment
4197                          * it here.
4198                          */
4199                         ++new->current_threshold;
4200                 }
4201         }
4202
4203         /* Free old spare buffer and save old primary buffer as spare */
4204         kfree(thresholds->spare);
4205         thresholds->spare = thresholds->primary;
4206
4207         rcu_assign_pointer(thresholds->primary, new);
4208
4209         /* To be sure that nobody uses thresholds */
4210         synchronize_rcu();
4211
4212 unlock:
4213         mutex_unlock(&memcg->thresholds_lock);
4214
4215         return ret;
4216 }
4217
4218 static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,
4219         struct cftype *cft, struct eventfd_ctx *eventfd)
4220 {
4221         struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4222         struct mem_cgroup_thresholds *thresholds;
4223         struct mem_cgroup_threshold_ary *new;
4224         int type = MEMFILE_TYPE(cft->private);
4225         u64 usage;
4226         int i, j, size;
4227
4228         mutex_lock(&memcg->thresholds_lock);
4229         if (type == _MEM)
4230                 thresholds = &memcg->thresholds;
4231         else if (type == _MEMSWAP)
4232                 thresholds = &memcg->memsw_thresholds;
4233         else
4234                 BUG();
4235
4236         /*
4237          * Something went wrong if we trying to unregister a threshold
4238          * if we don't have thresholds
4239          */
4240         BUG_ON(!thresholds);
4241
4242         usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
4243
4244         /* Check if a threshold crossed before removing */
4245         __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4246
4247         /* Calculate new number of threshold */
4248         size = 0;
4249         for (i = 0; i < thresholds->primary->size; i++) {
4250                 if (thresholds->primary->entries[i].eventfd != eventfd)
4251                         size++;
4252         }
4253
4254         new = thresholds->spare;
4255
4256         /* Set thresholds array to NULL if we don't have thresholds */
4257         if (!size) {
4258                 kfree(new);
4259                 new = NULL;
4260                 goto swap_buffers;
4261         }
4262
4263         new->size = size;
4264
4265         /* Copy thresholds and find current threshold */
4266         new->current_threshold = -1;
4267         for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4268                 if (thresholds->primary->entries[i].eventfd == eventfd)
4269                         continue;
4270
4271                 new->entries[j] = thresholds->primary->entries[i];
4272                 if (new->entries[j].threshold < usage) {
4273                         /*
4274                          * new->current_threshold will not be used
4275                          * until rcu_assign_pointer(), so it's safe to increment
4276                          * it here.
4277                          */
4278                         ++new->current_threshold;
4279                 }
4280                 j++;
4281         }
4282
4283 swap_buffers:
4284         /* Swap primary and spare array */
4285         thresholds->spare = thresholds->primary;
4286         rcu_assign_pointer(thresholds->primary, new);
4287
4288         /* To be sure that nobody uses thresholds */
4289         synchronize_rcu();
4290
4291         mutex_unlock(&memcg->thresholds_lock);
4292 }
4293
4294 static int mem_cgroup_oom_register_event(struct cgroup *cgrp,
4295         struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
4296 {
4297         struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4298         struct mem_cgroup_eventfd_list *event;
4299         int type = MEMFILE_TYPE(cft->private);
4300
4301         BUG_ON(type != _OOM_TYPE);
4302         event = kmalloc(sizeof(*event), GFP_KERNEL);
4303         if (!event)
4304                 return -ENOMEM;
4305
4306         mutex_lock(&memcg_oom_mutex);
4307
4308         event->eventfd = eventfd;
4309         list_add(&event->list, &memcg->oom_notify);
4310
4311         /* already in OOM ? */
4312         if (atomic_read(&memcg->oom_lock))
4313                 eventfd_signal(eventfd, 1);
4314         mutex_unlock(&memcg_oom_mutex);
4315
4316         return 0;
4317 }
4318
4319 static void mem_cgroup_oom_unregister_event(struct cgroup *cgrp,
4320         struct cftype *cft, struct eventfd_ctx *eventfd)
4321 {
4322         struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
4323         struct mem_cgroup_eventfd_list *ev, *tmp;
4324         int type = MEMFILE_TYPE(cft->private);
4325
4326         BUG_ON(type != _OOM_TYPE);
4327
4328         mutex_lock(&memcg_oom_mutex);
4329
4330         list_for_each_entry_safe(ev, tmp, &mem->oom_notify, list) {
4331                 if (ev->eventfd == eventfd) {
4332                         list_del(&ev->list);
4333                         kfree(ev);
4334                 }
4335         }
4336
4337         mutex_unlock(&memcg_oom_mutex);
4338 }
4339
4340 static int mem_cgroup_oom_control_read(struct cgroup *cgrp,
4341         struct cftype *cft,  struct cgroup_map_cb *cb)
4342 {
4343         struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
4344
4345         cb->fill(cb, "oom_kill_disable", mem->oom_kill_disable);
4346
4347         if (atomic_read(&mem->oom_lock))
4348                 cb->fill(cb, "under_oom", 1);
4349         else
4350                 cb->fill(cb, "under_oom", 0);
4351         return 0;
4352 }
4353
4354 static int mem_cgroup_oom_control_write(struct cgroup *cgrp,
4355         struct cftype *cft, u64 val)
4356 {
4357         struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
4358         struct mem_cgroup *parent;
4359
4360         /* cannot set to root cgroup and only 0 and 1 are allowed */
4361         if (!cgrp->parent || !((val == 0) || (val == 1)))
4362                 return -EINVAL;
4363
4364         parent = mem_cgroup_from_cont(cgrp->parent);
4365
4366         cgroup_lock();
4367         /* oom-kill-disable is a flag for subhierarchy. */
4368         if ((parent->use_hierarchy) ||
4369             (mem->use_hierarchy && !list_empty(&cgrp->children))) {
4370                 cgroup_unlock();
4371                 return -EINVAL;
4372         }
4373         mem->oom_kill_disable = val;
4374         if (!val)
4375                 memcg_oom_recover(mem);
4376         cgroup_unlock();
4377         return 0;
4378 }
4379
4380 static struct cftype mem_cgroup_files[] = {
4381         {
4382                 .name = "usage_in_bytes",
4383                 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
4384                 .read_u64 = mem_cgroup_read,
4385                 .register_event = mem_cgroup_usage_register_event,
4386                 .unregister_event = mem_cgroup_usage_unregister_event,
4387         },
4388         {
4389                 .name = "max_usage_in_bytes",
4390                 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
4391                 .trigger = mem_cgroup_reset,
4392                 .read_u64 = mem_cgroup_read,
4393         },
4394         {
4395                 .name = "limit_in_bytes",
4396                 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
4397                 .write_string = mem_cgroup_write,
4398                 .read_u64 = mem_cgroup_read,
4399         },
4400         {
4401                 .name = "soft_limit_in_bytes",
4402                 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
4403                 .write_string = mem_cgroup_write,
4404                 .read_u64 = mem_cgroup_read,
4405         },
4406         {
4407                 .name = "failcnt",
4408                 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
4409                 .trigger = mem_cgroup_reset,
4410                 .read_u64 = mem_cgroup_read,
4411         },
4412         {
4413                 .name = "stat",
4414                 .read_map = mem_control_stat_show,
4415         },
4416         {
4417                 .name = "force_empty",
4418                 .trigger = mem_cgroup_force_empty_write,
4419         },
4420         {
4421                 .name = "use_hierarchy",
4422                 .write_u64 = mem_cgroup_hierarchy_write,
4423                 .read_u64 = mem_cgroup_hierarchy_read,
4424         },
4425         {
4426                 .name = "swappiness",
4427                 .read_u64 = mem_cgroup_swappiness_read,
4428                 .write_u64 = mem_cgroup_swappiness_write,
4429         },
4430         {
4431                 .name = "move_charge_at_immigrate",
4432                 .read_u64 = mem_cgroup_move_charge_read,
4433                 .write_u64 = mem_cgroup_move_charge_write,
4434         },
4435         {
4436                 .name = "oom_control",
4437                 .read_map = mem_cgroup_oom_control_read,
4438                 .write_u64 = mem_cgroup_oom_control_write,
4439                 .register_event = mem_cgroup_oom_register_event,
4440                 .unregister_event = mem_cgroup_oom_unregister_event,
4441                 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
4442         },
4443 };
4444
4445 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4446 static struct cftype memsw_cgroup_files[] = {
4447         {
4448                 .name = "memsw.usage_in_bytes",
4449                 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
4450                 .read_u64 = mem_cgroup_read,
4451                 .register_event = mem_cgroup_usage_register_event,
4452                 .unregister_event = mem_cgroup_usage_unregister_event,
4453         },
4454         {
4455                 .name = "memsw.max_usage_in_bytes",
4456                 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
4457                 .trigger = mem_cgroup_reset,
4458                 .read_u64 = mem_cgroup_read,
4459         },
4460         {
4461                 .name = "memsw.limit_in_bytes",
4462                 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
4463                 .write_string = mem_cgroup_write,
4464                 .read_u64 = mem_cgroup_read,
4465         },
4466         {
4467                 .name = "memsw.failcnt",
4468                 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
4469                 .trigger = mem_cgroup_reset,
4470                 .read_u64 = mem_cgroup_read,
4471         },
4472 };
4473
4474 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
4475 {
4476         if (!do_swap_account)
4477                 return 0;
4478         return cgroup_add_files(cont, ss, memsw_cgroup_files,
4479                                 ARRAY_SIZE(memsw_cgroup_files));
4480 };
4481 #else
4482 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
4483 {
4484         return 0;
4485 }
4486 #endif
4487
4488 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
4489 {
4490         struct mem_cgroup_per_node *pn;
4491         struct mem_cgroup_per_zone *mz;
4492         enum lru_list l;
4493         int zone, tmp = node;
4494         /*
4495          * This routine is called against possible nodes.
4496          * But it's BUG to call kmalloc() against offline node.
4497          *
4498          * TODO: this routine can waste much memory for nodes which will
4499          *       never be onlined. It's better to use memory hotplug callback
4500          *       function.
4501          */
4502         if (!node_state(node, N_NORMAL_MEMORY))
4503                 tmp = -1;
4504         pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
4505         if (!pn)
4506                 return 1;
4507
4508         mem->info.nodeinfo[node] = pn;
4509         for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4510                 mz = &pn->zoneinfo[zone];
4511                 for_each_lru(l)
4512                         INIT_LIST_HEAD(&mz->lists[l]);
4513                 mz->usage_in_excess = 0;
4514                 mz->on_tree = false;
4515                 mz->mem = mem;
4516         }
4517         return 0;
4518 }
4519
4520 static void free_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
4521 {
4522         kfree(mem->info.nodeinfo[node]);
4523 }
4524
4525 static struct mem_cgroup *mem_cgroup_alloc(void)
4526 {
4527         struct mem_cgroup *mem;
4528         int size = sizeof(struct mem_cgroup);
4529
4530         /* Can be very big if MAX_NUMNODES is very big */
4531         if (size < PAGE_SIZE)
4532                 mem = kzalloc(size, GFP_KERNEL);
4533         else
4534                 mem = vzalloc(size);
4535
4536         if (!mem)
4537                 return NULL;
4538
4539         mem->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
4540         if (!mem->stat)
4541                 goto out_free;
4542         spin_lock_init(&mem->pcp_counter_lock);
4543         return mem;
4544
4545 out_free:
4546         if (size < PAGE_SIZE)
4547                 kfree(mem);
4548         else
4549                 vfree(mem);
4550         return NULL;
4551 }
4552
4553 /*
4554  * At destroying mem_cgroup, references from swap_cgroup can remain.
4555  * (scanning all at force_empty is too costly...)
4556  *
4557  * Instead of clearing all references at force_empty, we remember
4558  * the number of reference from swap_cgroup and free mem_cgroup when
4559  * it goes down to 0.
4560  *
4561  * Removal of cgroup itself succeeds regardless of refs from swap.
4562  */
4563
4564 static void __mem_cgroup_free(struct mem_cgroup *mem)
4565 {
4566         int node;
4567
4568         mem_cgroup_remove_from_trees(mem);
4569         free_css_id(&mem_cgroup_subsys, &mem->css);
4570
4571         for_each_node_state(node, N_POSSIBLE)
4572                 free_mem_cgroup_per_zone_info(mem, node);
4573
4574         free_percpu(mem->stat);
4575         if (sizeof(struct mem_cgroup) < PAGE_SIZE)
4576                 kfree(mem);
4577         else
4578                 vfree(mem);
4579 }
4580
4581 static void mem_cgroup_get(struct mem_cgroup *mem)
4582 {
4583         atomic_inc(&mem->refcnt);
4584 }
4585
4586 static void __mem_cgroup_put(struct mem_cgroup *mem, int count)
4587 {
4588         if (atomic_sub_and_test(count, &mem->refcnt)) {
4589                 struct mem_cgroup *parent = parent_mem_cgroup(mem);
4590                 __mem_cgroup_free(mem);
4591                 if (parent)
4592                         mem_cgroup_put(parent);
4593         }
4594 }
4595
4596 static void mem_cgroup_put(struct mem_cgroup *mem)
4597 {
4598         __mem_cgroup_put(mem, 1);
4599 }
4600
4601 /*
4602  * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
4603  */
4604 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem)
4605 {
4606         if (!mem->res.parent)
4607                 return NULL;
4608         return mem_cgroup_from_res_counter(mem->res.parent, res);
4609 }
4610
4611 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4612 static void __init enable_swap_cgroup(void)
4613 {
4614         if (!mem_cgroup_disabled() && really_do_swap_account)
4615                 do_swap_account = 1;
4616 }
4617 #else
4618 static void __init enable_swap_cgroup(void)
4619 {
4620 }
4621 #endif
4622
4623 static int mem_cgroup_soft_limit_tree_init(void)
4624 {
4625         struct mem_cgroup_tree_per_node *rtpn;
4626         struct mem_cgroup_tree_per_zone *rtpz;
4627         int tmp, node, zone;
4628
4629         for_each_node_state(node, N_POSSIBLE) {
4630                 tmp = node;
4631                 if (!node_state(node, N_NORMAL_MEMORY))
4632                         tmp = -1;
4633                 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
4634                 if (!rtpn)
4635                         return 1;
4636
4637                 soft_limit_tree.rb_tree_per_node[node] = rtpn;
4638
4639                 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4640                         rtpz = &rtpn->rb_tree_per_zone[zone];
4641                         rtpz->rb_root = RB_ROOT;
4642                         spin_lock_init(&rtpz->lock);
4643                 }
4644         }
4645         return 0;
4646 }
4647
4648 static struct cgroup_subsys_state * __ref
4649 mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
4650 {
4651         struct mem_cgroup *mem, *parent;
4652         long error = -ENOMEM;
4653         int node;
4654
4655         mem = mem_cgroup_alloc();
4656         if (!mem)
4657                 return ERR_PTR(error);
4658
4659         for_each_node_state(node, N_POSSIBLE)
4660                 if (alloc_mem_cgroup_per_zone_info(mem, node))
4661                         goto free_out;
4662
4663         /* root ? */
4664         if (cont->parent == NULL) {
4665                 int cpu;
4666                 enable_swap_cgroup();
4667                 parent = NULL;
4668                 root_mem_cgroup = mem;
4669                 if (mem_cgroup_soft_limit_tree_init())
4670                         goto free_out;
4671                 for_each_possible_cpu(cpu) {
4672                         struct memcg_stock_pcp *stock =
4673                                                 &per_cpu(memcg_stock, cpu);
4674                         INIT_WORK(&stock->work, drain_local_stock);
4675                 }
4676                 hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
4677         } else {
4678                 parent = mem_cgroup_from_cont(cont->parent);
4679                 mem->use_hierarchy = parent->use_hierarchy;
4680                 mem->oom_kill_disable = parent->oom_kill_disable;
4681         }
4682
4683         if (parent && parent->use_hierarchy) {
4684                 res_counter_init(&mem->res, &parent->res);
4685                 res_counter_init(&mem->memsw, &parent->memsw);
4686                 /*
4687                  * We increment refcnt of the parent to ensure that we can
4688                  * safely access it on res_counter_charge/uncharge.
4689                  * This refcnt will be decremented when freeing this
4690                  * mem_cgroup(see mem_cgroup_put).
4691                  */
4692                 mem_cgroup_get(parent);
4693         } else {
4694                 res_counter_init(&mem->res, NULL);
4695                 res_counter_init(&mem->memsw, NULL);
4696         }
4697         mem->last_scanned_child = 0;
4698         mem->last_scanned_node = MAX_NUMNODES;
4699         INIT_LIST_HEAD(&mem->oom_notify);
4700
4701         if (parent)
4702                 mem->swappiness = get_swappiness(parent);
4703         atomic_set(&mem->refcnt, 1);
4704         mem->move_charge_at_immigrate = 0;
4705         mutex_init(&mem->thresholds_lock);
4706         return &mem->css;
4707 free_out:
4708         __mem_cgroup_free(mem);
4709         root_mem_cgroup = NULL;
4710         return ERR_PTR(error);
4711 }
4712
4713 static int mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
4714                                         struct cgroup *cont)
4715 {
4716         struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
4717
4718         return mem_cgroup_force_empty(mem, false);
4719 }
4720
4721 static void mem_cgroup_destroy(struct cgroup_subsys *ss,
4722                                 struct cgroup *cont)
4723 {
4724         struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
4725
4726         mem_cgroup_put(mem);
4727 }
4728
4729 static int mem_cgroup_populate(struct cgroup_subsys *ss,
4730                                 struct cgroup *cont)
4731 {
4732         int ret;
4733
4734         ret = cgroup_add_files(cont, ss, mem_cgroup_files,
4735                                 ARRAY_SIZE(mem_cgroup_files));
4736
4737         if (!ret)
4738                 ret = register_memsw_files(cont, ss);
4739         return ret;
4740 }
4741
4742 #ifdef CONFIG_MMU
4743 /* Handlers for move charge at task migration. */
4744 #define PRECHARGE_COUNT_AT_ONCE 256
4745 static int mem_cgroup_do_precharge(unsigned long count)
4746 {
4747         int ret = 0;
4748         int batch_count = PRECHARGE_COUNT_AT_ONCE;
4749         struct mem_cgroup *mem = mc.to;
4750
4751         if (mem_cgroup_is_root(mem)) {
4752                 mc.precharge += count;
4753                 /* we don't need css_get for root */
4754                 return ret;
4755         }
4756         /* try to charge at once */
4757         if (count > 1) {
4758                 struct res_counter *dummy;
4759                 /*
4760                  * "mem" cannot be under rmdir() because we've already checked
4761                  * by cgroup_lock_live_cgroup() that it is not removed and we
4762                  * are still under the same cgroup_mutex. So we can postpone
4763                  * css_get().
4764                  */
4765                 if (res_counter_charge(&mem->res, PAGE_SIZE * count, &dummy))
4766                         goto one_by_one;
4767                 if (do_swap_account && res_counter_charge(&mem->memsw,
4768                                                 PAGE_SIZE * count, &dummy)) {
4769                         res_counter_uncharge(&mem->res, PAGE_SIZE * count);
4770                         goto one_by_one;
4771                 }
4772                 mc.precharge += count;
4773                 return ret;
4774         }
4775 one_by_one:
4776         /* fall back to one by one charge */
4777         while (count--) {
4778                 if (signal_pending(current)) {
4779                         ret = -EINTR;
4780                         break;
4781                 }
4782                 if (!batch_count--) {
4783                         batch_count = PRECHARGE_COUNT_AT_ONCE;
4784                         cond_resched();
4785                 }
4786                 ret = __mem_cgroup_try_charge(NULL, GFP_KERNEL, 1, &mem, false);
4787                 if (ret || !mem)
4788                         /* mem_cgroup_clear_mc() will do uncharge later */
4789                         return -ENOMEM;
4790                 mc.precharge++;
4791         }
4792         return ret;
4793 }
4794
4795 /**
4796  * is_target_pte_for_mc - check a pte whether it is valid for move charge
4797  * @vma: the vma the pte to be checked belongs
4798  * @addr: the address corresponding to the pte to be checked
4799  * @ptent: the pte to be checked
4800  * @target: the pointer the target page or swap ent will be stored(can be NULL)
4801  *
4802  * Returns
4803  *   0(MC_TARGET_NONE): if the pte is not a target for move charge.
4804  *   1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
4805  *     move charge. if @target is not NULL, the page is stored in target->page
4806  *     with extra refcnt got(Callers should handle it).
4807  *   2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
4808  *     target for charge migration. if @target is not NULL, the entry is stored
4809  *     in target->ent.
4810  *
4811  * Called with pte lock held.
4812  */
4813 union mc_target {
4814         struct page     *page;
4815         swp_entry_t     ent;
4816 };
4817
4818 enum mc_target_type {
4819         MC_TARGET_NONE, /* not used */
4820         MC_TARGET_PAGE,
4821         MC_TARGET_SWAP,
4822 };
4823
4824 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
4825                                                 unsigned long addr, pte_t ptent)
4826 {
4827         struct page *page = vm_normal_page(vma, addr, ptent);
4828
4829         if (!page || !page_mapped(page))
4830                 return NULL;
4831         if (PageAnon(page)) {
4832                 /* we don't move shared anon */
4833                 if (!move_anon() || page_mapcount(page) > 2)
4834                         return NULL;
4835         } else if (!move_file())
4836                 /* we ignore mapcount for file pages */
4837                 return NULL;
4838         if (!get_page_unless_zero(page))
4839                 return NULL;
4840
4841         return page;
4842 }
4843
4844 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
4845                         unsigned long addr, pte_t ptent, swp_entry_t *entry)
4846 {
4847         int usage_count;
4848         struct page *page = NULL;
4849         swp_entry_t ent = pte_to_swp_entry(ptent);
4850
4851         if (!move_anon() || non_swap_entry(ent))
4852                 return NULL;
4853         usage_count = mem_cgroup_count_swap_user(ent, &page);
4854         if (usage_count > 1) { /* we don't move shared anon */
4855                 if (page)
4856                         put_page(page);
4857                 return NULL;
4858         }
4859         if (do_swap_account)
4860                 entry->val = ent.val;
4861
4862         return page;
4863 }
4864
4865 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
4866                         unsigned long addr, pte_t ptent, swp_entry_t *entry)
4867 {
4868         struct page *page = NULL;
4869         struct inode *inode;
4870         struct address_space *mapping;
4871         pgoff_t pgoff;
4872
4873         if (!vma->vm_file) /* anonymous vma */
4874                 return NULL;
4875         if (!move_file())
4876                 return NULL;
4877
4878         inode = vma->vm_file->f_path.dentry->d_inode;
4879         mapping = vma->vm_file->f_mapping;
4880         if (pte_none(ptent))
4881                 pgoff = linear_page_index(vma, addr);
4882         else /* pte_file(ptent) is true */
4883                 pgoff = pte_to_pgoff(ptent);
4884
4885         /* page is moved even if it's not RSS of this task(page-faulted). */
4886         if (!mapping_cap_swap_backed(mapping)) { /* normal file */
4887                 page = find_get_page(mapping, pgoff);
4888         } else { /* shmem/tmpfs file. we should take account of swap too. */
4889                 swp_entry_t ent;
4890                 mem_cgroup_get_shmem_target(inode, pgoff, &page, &ent);
4891                 if (do_swap_account)
4892                         entry->val = ent.val;
4893         }
4894
4895         return page;
4896 }
4897
4898 static int is_target_pte_for_mc(struct vm_area_struct *vma,
4899                 unsigned long addr, pte_t ptent, union mc_target *target)
4900 {
4901         struct page *page = NULL;
4902         struct page_cgroup *pc;
4903         int ret = 0;
4904         swp_entry_t ent = { .val = 0 };
4905
4906         if (pte_present(ptent))
4907                 page = mc_handle_present_pte(vma, addr, ptent);
4908         else if (is_swap_pte(ptent))
4909                 page = mc_handle_swap_pte(vma, addr, ptent, &ent);
4910         else if (pte_none(ptent) || pte_file(ptent))
4911                 page = mc_handle_file_pte(vma, addr, ptent, &ent);
4912
4913         if (!page && !ent.val)
4914                 return 0;
4915         if (page) {
4916                 pc = lookup_page_cgroup(page);
4917                 /*
4918                  * Do only loose check w/o page_cgroup lock.
4919                  * mem_cgroup_move_account() checks the pc is valid or not under
4920                  * the lock.
4921                  */
4922                 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
4923                         ret = MC_TARGET_PAGE;
4924                         if (target)
4925                                 target->page = page;
4926                 }
4927                 if (!ret || !target)
4928                         put_page(page);
4929         }
4930         /* There is a swap entry and a page doesn't exist or isn't charged */
4931         if (ent.val && !ret &&
4932                         css_id(&mc.from->css) == lookup_swap_cgroup(ent)) {
4933                 ret = MC_TARGET_SWAP;
4934                 if (target)
4935                         target->ent = ent;
4936         }
4937         return ret;
4938 }
4939
4940 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
4941                                         unsigned long addr, unsigned long end,
4942                                         struct mm_walk *walk)
4943 {
4944         struct vm_area_struct *vma = walk->private;
4945         pte_t *pte;
4946         spinlock_t *ptl;
4947
4948         split_huge_page_pmd(walk->mm, pmd);
4949
4950         pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
4951         for (; addr != end; pte++, addr += PAGE_SIZE)
4952                 if (is_target_pte_for_mc(vma, addr, *pte, NULL))
4953                         mc.precharge++; /* increment precharge temporarily */
4954         pte_unmap_unlock(pte - 1, ptl);
4955         cond_resched();
4956
4957         return 0;
4958 }
4959
4960 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
4961 {
4962         unsigned long precharge;
4963         struct vm_area_struct *vma;
4964
4965         down_read(&mm->mmap_sem);
4966         for (vma = mm->mmap; vma; vma = vma->vm_next) {
4967                 struct mm_walk mem_cgroup_count_precharge_walk = {
4968                         .pmd_entry = mem_cgroup_count_precharge_pte_range,
4969                         .mm = mm,
4970                         .private = vma,
4971                 };
4972                 if (is_vm_hugetlb_page(vma))
4973                         continue;
4974                 walk_page_range(vma->vm_start, vma->vm_end,
4975                                         &mem_cgroup_count_precharge_walk);
4976         }
4977         up_read(&mm->mmap_sem);
4978
4979         precharge = mc.precharge;
4980         mc.precharge = 0;
4981
4982         return precharge;
4983 }
4984
4985 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
4986 {
4987         unsigned long precharge = mem_cgroup_count_precharge(mm);
4988
4989         VM_BUG_ON(mc.moving_task);
4990         mc.moving_task = current;
4991         return mem_cgroup_do_precharge(precharge);
4992 }
4993
4994 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
4995 static void __mem_cgroup_clear_mc(void)
4996 {
4997         struct mem_cgroup *from = mc.from;
4998         struct mem_cgroup *to = mc.to;
4999
5000         /* we must uncharge all the leftover precharges from mc.to */
5001         if (mc.precharge) {
5002                 __mem_cgroup_cancel_charge(mc.to, mc.precharge);
5003                 mc.precharge = 0;
5004         }
5005         /*
5006          * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5007          * we must uncharge here.
5008          */
5009         if (mc.moved_charge) {
5010                 __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
5011                 mc.moved_charge = 0;
5012         }
5013         /* we must fixup refcnts and charges */
5014         if (mc.moved_swap) {
5015                 /* uncharge swap account from the old cgroup */
5016                 if (!mem_cgroup_is_root(mc.from))
5017                         res_counter_uncharge(&mc.from->memsw,
5018                                                 PAGE_SIZE * mc.moved_swap);
5019                 __mem_cgroup_put(mc.from, mc.moved_swap);
5020
5021                 if (!mem_cgroup_is_root(mc.to)) {
5022                         /*
5023                          * we charged both to->res and to->memsw, so we should
5024                          * uncharge to->res.
5025                          */
5026                         res_counter_uncharge(&mc.to->res,
5027                                                 PAGE_SIZE * mc.moved_swap);
5028                 }
5029                 /* we've already done mem_cgroup_get(mc.to) */
5030                 mc.moved_swap = 0;
5031         }
5032         memcg_oom_recover(from);
5033         memcg_oom_recover(to);
5034         wake_up_all(&mc.waitq);
5035 }
5036
5037 static void mem_cgroup_clear_mc(void)
5038 {
5039         struct mem_cgroup *from = mc.from;
5040
5041         /*
5042          * we must clear moving_task before waking up waiters at the end of
5043          * task migration.
5044          */
5045         mc.moving_task = NULL;
5046         __mem_cgroup_clear_mc();
5047         spin_lock(&mc.lock);
5048         mc.from = NULL;
5049         mc.to = NULL;
5050         spin_unlock(&mc.lock);
5051         mem_cgroup_end_move(from);
5052 }
5053
5054 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
5055                                 struct cgroup *cgroup,
5056                                 struct task_struct *p)
5057 {
5058         int ret = 0;
5059         struct mem_cgroup *mem = mem_cgroup_from_cont(cgroup);
5060
5061         if (mem->move_charge_at_immigrate) {
5062                 struct mm_struct *mm;
5063                 struct mem_cgroup *from = mem_cgroup_from_task(p);
5064
5065                 VM_BUG_ON(from == mem);
5066
5067                 mm = get_task_mm(p);
5068                 if (!mm)
5069                         return 0;
5070                 /* We move charges only when we move a owner of the mm */
5071                 if (mm->owner == p) {
5072                         VM_BUG_ON(mc.from);
5073                         VM_BUG_ON(mc.to);
5074                         VM_BUG_ON(mc.precharge);
5075                         VM_BUG_ON(mc.moved_charge);
5076                         VM_BUG_ON(mc.moved_swap);
5077                         mem_cgroup_start_move(from);
5078                         spin_lock(&mc.lock);
5079                         mc.from = from;
5080                         mc.to = mem;
5081                         spin_unlock(&mc.lock);
5082                         /* We set mc.moving_task later */
5083
5084                         ret = mem_cgroup_precharge_mc(mm);
5085                         if (ret)
5086                                 mem_cgroup_clear_mc();
5087                 }
5088                 mmput(mm);
5089         }
5090         return ret;
5091 }
5092
5093 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
5094                                 struct cgroup *cgroup,
5095                                 struct task_struct *p)
5096 {
5097         mem_cgroup_clear_mc();
5098 }
5099
5100 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
5101                                 unsigned long addr, unsigned long end,
5102                                 struct mm_walk *walk)
5103 {
5104         int ret = 0;
5105         struct vm_area_struct *vma = walk->private;
5106         pte_t *pte;
5107         spinlock_t *ptl;
5108
5109         split_huge_page_pmd(walk->mm, pmd);
5110 retry:
5111         pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5112         for (; addr != end; addr += PAGE_SIZE) {
5113                 pte_t ptent = *(pte++);
5114                 union mc_target target;
5115                 int type;
5116                 struct page *page;
5117                 struct page_cgroup *pc;
5118                 swp_entry_t ent;
5119
5120                 if (!mc.precharge)
5121                         break;
5122
5123                 type = is_target_pte_for_mc(vma, addr, ptent, &target);
5124                 switch (type) {
5125                 case MC_TARGET_PAGE:
5126                         page = target.page;
5127                         if (isolate_lru_page(page))
5128                                 goto put;
5129                         pc = lookup_page_cgroup(page);
5130                         if (!mem_cgroup_move_account(page, 1, pc,
5131                                                      mc.from, mc.to, false)) {
5132                                 mc.precharge--;
5133                                 /* we uncharge from mc.from later. */
5134                                 mc.moved_charge++;
5135                         }
5136                         putback_lru_page(page);
5137 put:                    /* is_target_pte_for_mc() gets the page */
5138                         put_page(page);
5139                         break;
5140                 case MC_TARGET_SWAP:
5141                         ent = target.ent;
5142                         if (!mem_cgroup_move_swap_account(ent,
5143                                                 mc.from, mc.to, false)) {
5144                                 mc.precharge--;
5145                                 /* we fixup refcnts and charges later. */
5146                                 mc.moved_swap++;
5147                         }
5148                         break;
5149                 default:
5150                         break;
5151                 }
5152         }
5153         pte_unmap_unlock(pte - 1, ptl);
5154         cond_resched();
5155
5156         if (addr != end) {
5157                 /*
5158                  * We have consumed all precharges we got in can_attach().
5159                  * We try charge one by one, but don't do any additional
5160                  * charges to mc.to if we have failed in charge once in attach()
5161                  * phase.
5162                  */
5163                 ret = mem_cgroup_do_precharge(1);
5164                 if (!ret)
5165                         goto retry;
5166         }
5167
5168         return ret;
5169 }
5170
5171 static void mem_cgroup_move_charge(struct mm_struct *mm)
5172 {
5173         struct vm_area_struct *vma;
5174
5175         lru_add_drain_all();
5176 retry:
5177         if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
5178                 /*
5179                  * Someone who are holding the mmap_sem might be waiting in
5180                  * waitq. So we cancel all extra charges, wake up all waiters,
5181                  * and retry. Because we cancel precharges, we might not be able
5182                  * to move enough charges, but moving charge is a best-effort
5183                  * feature anyway, so it wouldn't be a big problem.
5184                  */
5185                 __mem_cgroup_clear_mc();
5186                 cond_resched();
5187                 goto retry;
5188         }
5189         for (vma = mm->mmap; vma; vma = vma->vm_next) {
5190                 int ret;
5191                 struct mm_walk mem_cgroup_move_charge_walk = {
5192                         .pmd_entry = mem_cgroup_move_charge_pte_range,
5193                         .mm = mm,
5194                         .private = vma,
5195                 };
5196                 if (is_vm_hugetlb_page(vma))
5197                         continue;
5198                 ret = walk_page_range(vma->vm_start, vma->vm_end,
5199                                                 &mem_cgroup_move_charge_walk);
5200                 if (ret)
5201                         /*
5202                          * means we have consumed all precharges and failed in
5203                          * doing additional charge. Just abandon here.
5204                          */
5205                         break;
5206         }
5207         up_read(&mm->mmap_sem);
5208 }
5209
5210 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
5211                                 struct cgroup *cont,
5212                                 struct cgroup *old_cont,
5213                                 struct task_struct *p)
5214 {
5215         struct mm_struct *mm;
5216
5217         if (!mc.to)
5218                 /* no need to move charge */
5219                 return;
5220
5221         mm = get_task_mm(p);
5222         if (mm) {
5223                 mem_cgroup_move_charge(mm);
5224                 mmput(mm);
5225         }
5226         mem_cgroup_clear_mc();
5227 }
5228 #else   /* !CONFIG_MMU */
5229 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
5230                                 struct cgroup *cgroup,
5231                                 struct task_struct *p)
5232 {
5233         return 0;
5234 }
5235 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
5236                                 struct cgroup *cgroup,
5237                                 struct task_struct *p)
5238 {
5239 }
5240 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
5241                                 struct cgroup *cont,
5242                                 struct cgroup *old_cont,
5243                                 struct task_struct *p)
5244 {
5245 }
5246 #endif
5247
5248 struct cgroup_subsys mem_cgroup_subsys = {
5249         .name = "memory",
5250         .subsys_id = mem_cgroup_subsys_id,
5251         .create = mem_cgroup_create,
5252         .pre_destroy = mem_cgroup_pre_destroy,
5253         .destroy = mem_cgroup_destroy,
5254         .populate = mem_cgroup_populate,
5255         .can_attach = mem_cgroup_can_attach,
5256         .cancel_attach = mem_cgroup_cancel_attach,
5257         .attach = mem_cgroup_move_task,
5258         .early_init = 0,
5259         .use_id = 1,
5260 };
5261
5262 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
5263 static int __init enable_swap_account(char *s)
5264 {
5265         /* consider enabled if no parameter or 1 is given */
5266         if (!strcmp(s, "1"))
5267                 really_do_swap_account = 1;
5268         else if (!strcmp(s, "0"))
5269                 really_do_swap_account = 0;
5270         return 1;
5271 }
5272 __setup("swapaccount=", enable_swap_account);
5273
5274 #endif