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