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