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