]> www.pilppa.org Git - linux-2.6-omap-h63xx.git/blob - mm/memcontrol.c
memcg: fix OOM killer under memcg
[linux-2.6-omap-h63xx.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  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  */
19
20 #include <linux/res_counter.h>
21 #include <linux/memcontrol.h>
22 #include <linux/cgroup.h>
23 #include <linux/mm.h>
24 #include <linux/pagemap.h>
25 #include <linux/smp.h>
26 #include <linux/page-flags.h>
27 #include <linux/backing-dev.h>
28 #include <linux/bit_spinlock.h>
29 #include <linux/rcupdate.h>
30 #include <linux/mutex.h>
31 #include <linux/slab.h>
32 #include <linux/swap.h>
33 #include <linux/spinlock.h>
34 #include <linux/fs.h>
35 #include <linux/seq_file.h>
36 #include <linux/vmalloc.h>
37 #include <linux/mm_inline.h>
38 #include <linux/page_cgroup.h>
39 #include "internal.h"
40
41 #include <asm/uaccess.h>
42
43 struct cgroup_subsys mem_cgroup_subsys __read_mostly;
44 #define MEM_CGROUP_RECLAIM_RETRIES      5
45
46 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
47 /* Turned on only when memory cgroup is enabled && really_do_swap_account = 0 */
48 int do_swap_account __read_mostly;
49 static int really_do_swap_account __initdata = 1; /* for remember boot option*/
50 #else
51 #define do_swap_account         (0)
52 #endif
53
54 static DEFINE_MUTEX(memcg_tasklist);    /* can be hold under cgroup_mutex */
55
56 /*
57  * Statistics for memory cgroup.
58  */
59 enum mem_cgroup_stat_index {
60         /*
61          * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
62          */
63         MEM_CGROUP_STAT_CACHE,     /* # of pages charged as cache */
64         MEM_CGROUP_STAT_RSS,       /* # of pages charged as rss */
65         MEM_CGROUP_STAT_PGPGIN_COUNT,   /* # of pages paged in */
66         MEM_CGROUP_STAT_PGPGOUT_COUNT,  /* # of pages paged out */
67
68         MEM_CGROUP_STAT_NSTATS,
69 };
70
71 struct mem_cgroup_stat_cpu {
72         s64 count[MEM_CGROUP_STAT_NSTATS];
73 } ____cacheline_aligned_in_smp;
74
75 struct mem_cgroup_stat {
76         struct mem_cgroup_stat_cpu cpustat[0];
77 };
78
79 /*
80  * For accounting under irq disable, no need for increment preempt count.
81  */
82 static inline void __mem_cgroup_stat_add_safe(struct mem_cgroup_stat_cpu *stat,
83                 enum mem_cgroup_stat_index idx, int val)
84 {
85         stat->count[idx] += val;
86 }
87
88 static s64 mem_cgroup_read_stat(struct mem_cgroup_stat *stat,
89                 enum mem_cgroup_stat_index idx)
90 {
91         int cpu;
92         s64 ret = 0;
93         for_each_possible_cpu(cpu)
94                 ret += stat->cpustat[cpu].count[idx];
95         return ret;
96 }
97
98 static s64 mem_cgroup_local_usage(struct mem_cgroup_stat *stat)
99 {
100         s64 ret;
101
102         ret = mem_cgroup_read_stat(stat, MEM_CGROUP_STAT_CACHE);
103         ret += mem_cgroup_read_stat(stat, MEM_CGROUP_STAT_RSS);
104         return ret;
105 }
106
107 /*
108  * per-zone information in memory controller.
109  */
110 struct mem_cgroup_per_zone {
111         /*
112          * spin_lock to protect the per cgroup LRU
113          */
114         struct list_head        lists[NR_LRU_LISTS];
115         unsigned long           count[NR_LRU_LISTS];
116
117         struct zone_reclaim_stat reclaim_stat;
118 };
119 /* Macro for accessing counter */
120 #define MEM_CGROUP_ZSTAT(mz, idx)       ((mz)->count[(idx)])
121
122 struct mem_cgroup_per_node {
123         struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
124 };
125
126 struct mem_cgroup_lru_info {
127         struct mem_cgroup_per_node *nodeinfo[MAX_NUMNODES];
128 };
129
130 /*
131  * The memory controller data structure. The memory controller controls both
132  * page cache and RSS per cgroup. We would eventually like to provide
133  * statistics based on the statistics developed by Rik Van Riel for clock-pro,
134  * to help the administrator determine what knobs to tune.
135  *
136  * TODO: Add a water mark for the memory controller. Reclaim will begin when
137  * we hit the water mark. May be even add a low water mark, such that
138  * no reclaim occurs from a cgroup at it's low water mark, this is
139  * a feature that will be implemented much later in the future.
140  */
141 struct mem_cgroup {
142         struct cgroup_subsys_state css;
143         /*
144          * the counter to account for memory usage
145          */
146         struct res_counter res;
147         /*
148          * the counter to account for mem+swap usage.
149          */
150         struct res_counter memsw;
151         /*
152          * Per cgroup active and inactive list, similar to the
153          * per zone LRU lists.
154          */
155         struct mem_cgroup_lru_info info;
156
157         /*
158           protect against reclaim related member.
159         */
160         spinlock_t reclaim_param_lock;
161
162         int     prev_priority;  /* for recording reclaim priority */
163
164         /*
165          * While reclaiming in a hiearchy, we cache the last child we
166          * reclaimed from.
167          */
168         int last_scanned_child;
169         /*
170          * Should the accounting and control be hierarchical, per subtree?
171          */
172         bool use_hierarchy;
173         unsigned long   last_oom_jiffies;
174         atomic_t        refcnt;
175
176         unsigned int    swappiness;
177
178         /*
179          * statistics. This must be placed at the end of memcg.
180          */
181         struct mem_cgroup_stat stat;
182 };
183
184 enum charge_type {
185         MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
186         MEM_CGROUP_CHARGE_TYPE_MAPPED,
187         MEM_CGROUP_CHARGE_TYPE_SHMEM,   /* used by page migration of shmem */
188         MEM_CGROUP_CHARGE_TYPE_FORCE,   /* used by force_empty */
189         MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
190         NR_CHARGE_TYPE,
191 };
192
193 /* only for here (for easy reading.) */
194 #define PCGF_CACHE      (1UL << PCG_CACHE)
195 #define PCGF_USED       (1UL << PCG_USED)
196 #define PCGF_LOCK       (1UL << PCG_LOCK)
197 static const unsigned long
198 pcg_default_flags[NR_CHARGE_TYPE] = {
199         PCGF_CACHE | PCGF_USED | PCGF_LOCK, /* File Cache */
200         PCGF_USED | PCGF_LOCK, /* Anon */
201         PCGF_CACHE | PCGF_USED | PCGF_LOCK, /* Shmem */
202         0, /* FORCE */
203 };
204
205 /* for encoding cft->private value on file */
206 #define _MEM                    (0)
207 #define _MEMSWAP                (1)
208 #define MEMFILE_PRIVATE(x, val) (((x) << 16) | (val))
209 #define MEMFILE_TYPE(val)       (((val) >> 16) & 0xffff)
210 #define MEMFILE_ATTR(val)       ((val) & 0xffff)
211
212 static void mem_cgroup_get(struct mem_cgroup *mem);
213 static void mem_cgroup_put(struct mem_cgroup *mem);
214 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem);
215
216 static void mem_cgroup_charge_statistics(struct mem_cgroup *mem,
217                                          struct page_cgroup *pc,
218                                          bool charge)
219 {
220         int val = (charge)? 1 : -1;
221         struct mem_cgroup_stat *stat = &mem->stat;
222         struct mem_cgroup_stat_cpu *cpustat;
223         int cpu = get_cpu();
224
225         cpustat = &stat->cpustat[cpu];
226         if (PageCgroupCache(pc))
227                 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_CACHE, val);
228         else
229                 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_RSS, val);
230
231         if (charge)
232                 __mem_cgroup_stat_add_safe(cpustat,
233                                 MEM_CGROUP_STAT_PGPGIN_COUNT, 1);
234         else
235                 __mem_cgroup_stat_add_safe(cpustat,
236                                 MEM_CGROUP_STAT_PGPGOUT_COUNT, 1);
237         put_cpu();
238 }
239
240 static struct mem_cgroup_per_zone *
241 mem_cgroup_zoneinfo(struct mem_cgroup *mem, int nid, int zid)
242 {
243         return &mem->info.nodeinfo[nid]->zoneinfo[zid];
244 }
245
246 static struct mem_cgroup_per_zone *
247 page_cgroup_zoneinfo(struct page_cgroup *pc)
248 {
249         struct mem_cgroup *mem = pc->mem_cgroup;
250         int nid = page_cgroup_nid(pc);
251         int zid = page_cgroup_zid(pc);
252
253         if (!mem)
254                 return NULL;
255
256         return mem_cgroup_zoneinfo(mem, nid, zid);
257 }
258
259 static unsigned long mem_cgroup_get_local_zonestat(struct mem_cgroup *mem,
260                                         enum lru_list idx)
261 {
262         int nid, zid;
263         struct mem_cgroup_per_zone *mz;
264         u64 total = 0;
265
266         for_each_online_node(nid)
267                 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
268                         mz = mem_cgroup_zoneinfo(mem, nid, zid);
269                         total += MEM_CGROUP_ZSTAT(mz, idx);
270                 }
271         return total;
272 }
273
274 static struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
275 {
276         return container_of(cgroup_subsys_state(cont,
277                                 mem_cgroup_subsys_id), struct mem_cgroup,
278                                 css);
279 }
280
281 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
282 {
283         /*
284          * mm_update_next_owner() may clear mm->owner to NULL
285          * if it races with swapoff, page migration, etc.
286          * So this can be called with p == NULL.
287          */
288         if (unlikely(!p))
289                 return NULL;
290
291         return container_of(task_subsys_state(p, mem_cgroup_subsys_id),
292                                 struct mem_cgroup, css);
293 }
294
295 static struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
296 {
297         struct mem_cgroup *mem = NULL;
298
299         if (!mm)
300                 return NULL;
301         /*
302          * Because we have no locks, mm->owner's may be being moved to other
303          * cgroup. We use css_tryget() here even if this looks
304          * pessimistic (rather than adding locks here).
305          */
306         rcu_read_lock();
307         do {
308                 mem = mem_cgroup_from_task(rcu_dereference(mm->owner));
309                 if (unlikely(!mem))
310                         break;
311         } while (!css_tryget(&mem->css));
312         rcu_read_unlock();
313         return mem;
314 }
315
316 static bool mem_cgroup_is_obsolete(struct mem_cgroup *mem)
317 {
318         if (!mem)
319                 return true;
320         return css_is_removed(&mem->css);
321 }
322
323
324 /*
325  * Call callback function against all cgroup under hierarchy tree.
326  */
327 static int mem_cgroup_walk_tree(struct mem_cgroup *root, void *data,
328                           int (*func)(struct mem_cgroup *, void *))
329 {
330         int found, ret, nextid;
331         struct cgroup_subsys_state *css;
332         struct mem_cgroup *mem;
333
334         if (!root->use_hierarchy)
335                 return (*func)(root, data);
336
337         nextid = 1;
338         do {
339                 ret = 0;
340                 mem = NULL;
341
342                 rcu_read_lock();
343                 css = css_get_next(&mem_cgroup_subsys, nextid, &root->css,
344                                    &found);
345                 if (css && css_tryget(css))
346                         mem = container_of(css, struct mem_cgroup, css);
347                 rcu_read_unlock();
348
349                 if (mem) {
350                         ret = (*func)(mem, data);
351                         css_put(&mem->css);
352                 }
353                 nextid = found + 1;
354         } while (!ret && css);
355
356         return ret;
357 }
358
359 /*
360  * Following LRU functions are allowed to be used without PCG_LOCK.
361  * Operations are called by routine of global LRU independently from memcg.
362  * What we have to take care of here is validness of pc->mem_cgroup.
363  *
364  * Changes to pc->mem_cgroup happens when
365  * 1. charge
366  * 2. moving account
367  * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
368  * It is added to LRU before charge.
369  * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
370  * When moving account, the page is not on LRU. It's isolated.
371  */
372
373 void mem_cgroup_del_lru_list(struct page *page, enum lru_list lru)
374 {
375         struct page_cgroup *pc;
376         struct mem_cgroup *mem;
377         struct mem_cgroup_per_zone *mz;
378
379         if (mem_cgroup_disabled())
380                 return;
381         pc = lookup_page_cgroup(page);
382         /* can happen while we handle swapcache. */
383         if (list_empty(&pc->lru) || !pc->mem_cgroup)
384                 return;
385         /*
386          * We don't check PCG_USED bit. It's cleared when the "page" is finally
387          * removed from global LRU.
388          */
389         mz = page_cgroup_zoneinfo(pc);
390         mem = pc->mem_cgroup;
391         MEM_CGROUP_ZSTAT(mz, lru) -= 1;
392         list_del_init(&pc->lru);
393         return;
394 }
395
396 void mem_cgroup_del_lru(struct page *page)
397 {
398         mem_cgroup_del_lru_list(page, page_lru(page));
399 }
400
401 void mem_cgroup_rotate_lru_list(struct page *page, enum lru_list lru)
402 {
403         struct mem_cgroup_per_zone *mz;
404         struct page_cgroup *pc;
405
406         if (mem_cgroup_disabled())
407                 return;
408
409         pc = lookup_page_cgroup(page);
410         /*
411          * Used bit is set without atomic ops but after smp_wmb().
412          * For making pc->mem_cgroup visible, insert smp_rmb() here.
413          */
414         smp_rmb();
415         /* unused page is not rotated. */
416         if (!PageCgroupUsed(pc))
417                 return;
418         mz = page_cgroup_zoneinfo(pc);
419         list_move(&pc->lru, &mz->lists[lru]);
420 }
421
422 void mem_cgroup_add_lru_list(struct page *page, enum lru_list lru)
423 {
424         struct page_cgroup *pc;
425         struct mem_cgroup_per_zone *mz;
426
427         if (mem_cgroup_disabled())
428                 return;
429         pc = lookup_page_cgroup(page);
430         /*
431          * Used bit is set without atomic ops but after smp_wmb().
432          * For making pc->mem_cgroup visible, insert smp_rmb() here.
433          */
434         smp_rmb();
435         if (!PageCgroupUsed(pc))
436                 return;
437
438         mz = page_cgroup_zoneinfo(pc);
439         MEM_CGROUP_ZSTAT(mz, lru) += 1;
440         list_add(&pc->lru, &mz->lists[lru]);
441 }
442
443 /*
444  * At handling SwapCache, pc->mem_cgroup may be changed while it's linked to
445  * lru because the page may.be reused after it's fully uncharged (because of
446  * SwapCache behavior).To handle that, unlink page_cgroup from LRU when charge
447  * it again. This function is only used to charge SwapCache. It's done under
448  * lock_page and expected that zone->lru_lock is never held.
449  */
450 static void mem_cgroup_lru_del_before_commit_swapcache(struct page *page)
451 {
452         unsigned long flags;
453         struct zone *zone = page_zone(page);
454         struct page_cgroup *pc = lookup_page_cgroup(page);
455
456         spin_lock_irqsave(&zone->lru_lock, flags);
457         /*
458          * Forget old LRU when this page_cgroup is *not* used. This Used bit
459          * is guarded by lock_page() because the page is SwapCache.
460          */
461         if (!PageCgroupUsed(pc))
462                 mem_cgroup_del_lru_list(page, page_lru(page));
463         spin_unlock_irqrestore(&zone->lru_lock, flags);
464 }
465
466 static void mem_cgroup_lru_add_after_commit_swapcache(struct page *page)
467 {
468         unsigned long flags;
469         struct zone *zone = page_zone(page);
470         struct page_cgroup *pc = lookup_page_cgroup(page);
471
472         spin_lock_irqsave(&zone->lru_lock, flags);
473         /* link when the page is linked to LRU but page_cgroup isn't */
474         if (PageLRU(page) && list_empty(&pc->lru))
475                 mem_cgroup_add_lru_list(page, page_lru(page));
476         spin_unlock_irqrestore(&zone->lru_lock, flags);
477 }
478
479
480 void mem_cgroup_move_lists(struct page *page,
481                            enum lru_list from, enum lru_list to)
482 {
483         if (mem_cgroup_disabled())
484                 return;
485         mem_cgroup_del_lru_list(page, from);
486         mem_cgroup_add_lru_list(page, to);
487 }
488
489 int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *mem)
490 {
491         int ret;
492         struct mem_cgroup *curr = NULL;
493
494         task_lock(task);
495         rcu_read_lock();
496         curr = try_get_mem_cgroup_from_mm(task->mm);
497         rcu_read_unlock();
498         task_unlock(task);
499         if (!curr)
500                 return 0;
501         if (curr->use_hierarchy)
502                 ret = css_is_ancestor(&curr->css, &mem->css);
503         else
504                 ret = (curr == mem);
505         css_put(&curr->css);
506         return ret;
507 }
508
509 /*
510  * Calculate mapped_ratio under memory controller. This will be used in
511  * vmscan.c for deteremining we have to reclaim mapped pages.
512  */
513 int mem_cgroup_calc_mapped_ratio(struct mem_cgroup *mem)
514 {
515         long total, rss;
516
517         /*
518          * usage is recorded in bytes. But, here, we assume the number of
519          * physical pages can be represented by "long" on any arch.
520          */
521         total = (long) (mem->res.usage >> PAGE_SHIFT) + 1L;
522         rss = (long)mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_RSS);
523         return (int)((rss * 100L) / total);
524 }
525
526 /*
527  * prev_priority control...this will be used in memory reclaim path.
528  */
529 int mem_cgroup_get_reclaim_priority(struct mem_cgroup *mem)
530 {
531         int prev_priority;
532
533         spin_lock(&mem->reclaim_param_lock);
534         prev_priority = mem->prev_priority;
535         spin_unlock(&mem->reclaim_param_lock);
536
537         return prev_priority;
538 }
539
540 void mem_cgroup_note_reclaim_priority(struct mem_cgroup *mem, int priority)
541 {
542         spin_lock(&mem->reclaim_param_lock);
543         if (priority < mem->prev_priority)
544                 mem->prev_priority = priority;
545         spin_unlock(&mem->reclaim_param_lock);
546 }
547
548 void mem_cgroup_record_reclaim_priority(struct mem_cgroup *mem, int priority)
549 {
550         spin_lock(&mem->reclaim_param_lock);
551         mem->prev_priority = priority;
552         spin_unlock(&mem->reclaim_param_lock);
553 }
554
555 static int calc_inactive_ratio(struct mem_cgroup *memcg, unsigned long *present_pages)
556 {
557         unsigned long active;
558         unsigned long inactive;
559         unsigned long gb;
560         unsigned long inactive_ratio;
561
562         inactive = mem_cgroup_get_local_zonestat(memcg, LRU_INACTIVE_ANON);
563         active = mem_cgroup_get_local_zonestat(memcg, LRU_ACTIVE_ANON);
564
565         gb = (inactive + active) >> (30 - PAGE_SHIFT);
566         if (gb)
567                 inactive_ratio = int_sqrt(10 * gb);
568         else
569                 inactive_ratio = 1;
570
571         if (present_pages) {
572                 present_pages[0] = inactive;
573                 present_pages[1] = active;
574         }
575
576         return inactive_ratio;
577 }
578
579 int mem_cgroup_inactive_anon_is_low(struct mem_cgroup *memcg)
580 {
581         unsigned long active;
582         unsigned long inactive;
583         unsigned long present_pages[2];
584         unsigned long inactive_ratio;
585
586         inactive_ratio = calc_inactive_ratio(memcg, present_pages);
587
588         inactive = present_pages[0];
589         active = present_pages[1];
590
591         if (inactive * inactive_ratio < active)
592                 return 1;
593
594         return 0;
595 }
596
597 unsigned long mem_cgroup_zone_nr_pages(struct mem_cgroup *memcg,
598                                        struct zone *zone,
599                                        enum lru_list lru)
600 {
601         int nid = zone->zone_pgdat->node_id;
602         int zid = zone_idx(zone);
603         struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
604
605         return MEM_CGROUP_ZSTAT(mz, lru);
606 }
607
608 struct zone_reclaim_stat *mem_cgroup_get_reclaim_stat(struct mem_cgroup *memcg,
609                                                       struct zone *zone)
610 {
611         int nid = zone->zone_pgdat->node_id;
612         int zid = zone_idx(zone);
613         struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
614
615         return &mz->reclaim_stat;
616 }
617
618 struct zone_reclaim_stat *
619 mem_cgroup_get_reclaim_stat_from_page(struct page *page)
620 {
621         struct page_cgroup *pc;
622         struct mem_cgroup_per_zone *mz;
623
624         if (mem_cgroup_disabled())
625                 return NULL;
626
627         pc = lookup_page_cgroup(page);
628         /*
629          * Used bit is set without atomic ops but after smp_wmb().
630          * For making pc->mem_cgroup visible, insert smp_rmb() here.
631          */
632         smp_rmb();
633         if (!PageCgroupUsed(pc))
634                 return NULL;
635
636         mz = page_cgroup_zoneinfo(pc);
637         if (!mz)
638                 return NULL;
639
640         return &mz->reclaim_stat;
641 }
642
643 unsigned long mem_cgroup_isolate_pages(unsigned long nr_to_scan,
644                                         struct list_head *dst,
645                                         unsigned long *scanned, int order,
646                                         int mode, struct zone *z,
647                                         struct mem_cgroup *mem_cont,
648                                         int active, int file)
649 {
650         unsigned long nr_taken = 0;
651         struct page *page;
652         unsigned long scan;
653         LIST_HEAD(pc_list);
654         struct list_head *src;
655         struct page_cgroup *pc, *tmp;
656         int nid = z->zone_pgdat->node_id;
657         int zid = zone_idx(z);
658         struct mem_cgroup_per_zone *mz;
659         int lru = LRU_FILE * !!file + !!active;
660
661         BUG_ON(!mem_cont);
662         mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
663         src = &mz->lists[lru];
664
665         scan = 0;
666         list_for_each_entry_safe_reverse(pc, tmp, src, lru) {
667                 if (scan >= nr_to_scan)
668                         break;
669
670                 page = pc->page;
671                 if (unlikely(!PageCgroupUsed(pc)))
672                         continue;
673                 if (unlikely(!PageLRU(page)))
674                         continue;
675
676                 scan++;
677                 if (__isolate_lru_page(page, mode, file) == 0) {
678                         list_move(&page->lru, dst);
679                         nr_taken++;
680                 }
681         }
682
683         *scanned = scan;
684         return nr_taken;
685 }
686
687 #define mem_cgroup_from_res_counter(counter, member)    \
688         container_of(counter, struct mem_cgroup, member)
689
690 static bool mem_cgroup_check_under_limit(struct mem_cgroup *mem)
691 {
692         if (do_swap_account) {
693                 if (res_counter_check_under_limit(&mem->res) &&
694                         res_counter_check_under_limit(&mem->memsw))
695                         return true;
696         } else
697                 if (res_counter_check_under_limit(&mem->res))
698                         return true;
699         return false;
700 }
701
702 static unsigned int get_swappiness(struct mem_cgroup *memcg)
703 {
704         struct cgroup *cgrp = memcg->css.cgroup;
705         unsigned int swappiness;
706
707         /* root ? */
708         if (cgrp->parent == NULL)
709                 return vm_swappiness;
710
711         spin_lock(&memcg->reclaim_param_lock);
712         swappiness = memcg->swappiness;
713         spin_unlock(&memcg->reclaim_param_lock);
714
715         return swappiness;
716 }
717
718 static int mem_cgroup_count_children_cb(struct mem_cgroup *mem, void *data)
719 {
720         int *val = data;
721         (*val)++;
722         return 0;
723 }
724 /*
725  * This function returns the number of memcg under hierarchy tree. Returns
726  * 1(self count) if no children.
727  */
728 static int mem_cgroup_count_children(struct mem_cgroup *mem)
729 {
730         int num = 0;
731         mem_cgroup_walk_tree(mem, &num, mem_cgroup_count_children_cb);
732         return num;
733 }
734
735 /*
736  * Visit the first child (need not be the first child as per the ordering
737  * of the cgroup list, since we track last_scanned_child) of @mem and use
738  * that to reclaim free pages from.
739  */
740 static struct mem_cgroup *
741 mem_cgroup_select_victim(struct mem_cgroup *root_mem)
742 {
743         struct mem_cgroup *ret = NULL;
744         struct cgroup_subsys_state *css;
745         int nextid, found;
746
747         if (!root_mem->use_hierarchy) {
748                 css_get(&root_mem->css);
749                 ret = root_mem;
750         }
751
752         while (!ret) {
753                 rcu_read_lock();
754                 nextid = root_mem->last_scanned_child + 1;
755                 css = css_get_next(&mem_cgroup_subsys, nextid, &root_mem->css,
756                                    &found);
757                 if (css && css_tryget(css))
758                         ret = container_of(css, struct mem_cgroup, css);
759
760                 rcu_read_unlock();
761                 /* Updates scanning parameter */
762                 spin_lock(&root_mem->reclaim_param_lock);
763                 if (!css) {
764                         /* this means start scan from ID:1 */
765                         root_mem->last_scanned_child = 0;
766                 } else
767                         root_mem->last_scanned_child = found;
768                 spin_unlock(&root_mem->reclaim_param_lock);
769         }
770
771         return ret;
772 }
773
774 /*
775  * Scan the hierarchy if needed to reclaim memory. We remember the last child
776  * we reclaimed from, so that we don't end up penalizing one child extensively
777  * based on its position in the children list.
778  *
779  * root_mem is the original ancestor that we've been reclaim from.
780  *
781  * We give up and return to the caller when we visit root_mem twice.
782  * (other groups can be removed while we're walking....)
783  *
784  * If shrink==true, for avoiding to free too much, this returns immedieately.
785  */
786 static int mem_cgroup_hierarchical_reclaim(struct mem_cgroup *root_mem,
787                                    gfp_t gfp_mask, bool noswap, bool shrink)
788 {
789         struct mem_cgroup *victim;
790         int ret, total = 0;
791         int loop = 0;
792
793         while (loop < 2) {
794                 victim = mem_cgroup_select_victim(root_mem);
795                 if (victim == root_mem)
796                         loop++;
797                 if (!mem_cgroup_local_usage(&victim->stat)) {
798                         /* this cgroup's local usage == 0 */
799                         css_put(&victim->css);
800                         continue;
801                 }
802                 /* we use swappiness of local cgroup */
803                 ret = try_to_free_mem_cgroup_pages(victim, gfp_mask, noswap,
804                                                    get_swappiness(victim));
805                 css_put(&victim->css);
806                 /*
807                  * At shrinking usage, we can't check we should stop here or
808                  * reclaim more. It's depends on callers. last_scanned_child
809                  * will work enough for keeping fairness under tree.
810                  */
811                 if (shrink)
812                         return ret;
813                 total += ret;
814                 if (mem_cgroup_check_under_limit(root_mem))
815                         return 1 + total;
816         }
817         return total;
818 }
819
820 bool mem_cgroup_oom_called(struct task_struct *task)
821 {
822         bool ret = false;
823         struct mem_cgroup *mem;
824         struct mm_struct *mm;
825
826         rcu_read_lock();
827         mm = task->mm;
828         if (!mm)
829                 mm = &init_mm;
830         mem = mem_cgroup_from_task(rcu_dereference(mm->owner));
831         if (mem && time_before(jiffies, mem->last_oom_jiffies + HZ/10))
832                 ret = true;
833         rcu_read_unlock();
834         return ret;
835 }
836
837 static int record_last_oom_cb(struct mem_cgroup *mem, void *data)
838 {
839         mem->last_oom_jiffies = jiffies;
840         return 0;
841 }
842
843 static void record_last_oom(struct mem_cgroup *mem)
844 {
845         mem_cgroup_walk_tree(mem, NULL, record_last_oom_cb);
846 }
847
848
849 /*
850  * Unlike exported interface, "oom" parameter is added. if oom==true,
851  * oom-killer can be invoked.
852  */
853 static int __mem_cgroup_try_charge(struct mm_struct *mm,
854                         gfp_t gfp_mask, struct mem_cgroup **memcg,
855                         bool oom)
856 {
857         struct mem_cgroup *mem, *mem_over_limit;
858         int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
859         struct res_counter *fail_res;
860
861         if (unlikely(test_thread_flag(TIF_MEMDIE))) {
862                 /* Don't account this! */
863                 *memcg = NULL;
864                 return 0;
865         }
866
867         /*
868          * We always charge the cgroup the mm_struct belongs to.
869          * The mm_struct's mem_cgroup changes on task migration if the
870          * thread group leader migrates. It's possible that mm is not
871          * set, if so charge the init_mm (happens for pagecache usage).
872          */
873         mem = *memcg;
874         if (likely(!mem)) {
875                 mem = try_get_mem_cgroup_from_mm(mm);
876                 *memcg = mem;
877         } else {
878                 css_get(&mem->css);
879         }
880         if (unlikely(!mem))
881                 return 0;
882
883         VM_BUG_ON(mem_cgroup_is_obsolete(mem));
884
885         while (1) {
886                 int ret;
887                 bool noswap = false;
888
889                 ret = res_counter_charge(&mem->res, PAGE_SIZE, &fail_res);
890                 if (likely(!ret)) {
891                         if (!do_swap_account)
892                                 break;
893                         ret = res_counter_charge(&mem->memsw, PAGE_SIZE,
894                                                         &fail_res);
895                         if (likely(!ret))
896                                 break;
897                         /* mem+swap counter fails */
898                         res_counter_uncharge(&mem->res, PAGE_SIZE);
899                         noswap = true;
900                         mem_over_limit = mem_cgroup_from_res_counter(fail_res,
901                                                                         memsw);
902                 } else
903                         /* mem counter fails */
904                         mem_over_limit = mem_cgroup_from_res_counter(fail_res,
905                                                                         res);
906
907                 if (!(gfp_mask & __GFP_WAIT))
908                         goto nomem;
909
910                 ret = mem_cgroup_hierarchical_reclaim(mem_over_limit, gfp_mask,
911                                                         noswap, false);
912                 if (ret)
913                         continue;
914
915                 /*
916                  * try_to_free_mem_cgroup_pages() might not give us a full
917                  * picture of reclaim. Some pages are reclaimed and might be
918                  * moved to swap cache or just unmapped from the cgroup.
919                  * Check the limit again to see if the reclaim reduced the
920                  * current usage of the cgroup before giving up
921                  *
922                  */
923                 if (mem_cgroup_check_under_limit(mem_over_limit))
924                         continue;
925
926                 if (!nr_retries--) {
927                         if (oom) {
928                                 mutex_lock(&memcg_tasklist);
929                                 mem_cgroup_out_of_memory(mem_over_limit, gfp_mask);
930                                 mutex_unlock(&memcg_tasklist);
931                                 record_last_oom(mem_over_limit);
932                         }
933                         goto nomem;
934                 }
935         }
936         return 0;
937 nomem:
938         css_put(&mem->css);
939         return -ENOMEM;
940 }
941
942 static struct mem_cgroup *try_get_mem_cgroup_from_swapcache(struct page *page)
943 {
944         struct mem_cgroup *mem;
945         swp_entry_t ent;
946
947         if (!PageSwapCache(page))
948                 return NULL;
949
950         ent.val = page_private(page);
951         mem = lookup_swap_cgroup(ent);
952         if (!mem)
953                 return NULL;
954         if (!css_tryget(&mem->css))
955                 return NULL;
956         return mem;
957 }
958
959 /*
960  * commit a charge got by __mem_cgroup_try_charge() and makes page_cgroup to be
961  * USED state. If already USED, uncharge and return.
962  */
963
964 static void __mem_cgroup_commit_charge(struct mem_cgroup *mem,
965                                      struct page_cgroup *pc,
966                                      enum charge_type ctype)
967 {
968         /* try_charge() can return NULL to *memcg, taking care of it. */
969         if (!mem)
970                 return;
971
972         lock_page_cgroup(pc);
973         if (unlikely(PageCgroupUsed(pc))) {
974                 unlock_page_cgroup(pc);
975                 res_counter_uncharge(&mem->res, PAGE_SIZE);
976                 if (do_swap_account)
977                         res_counter_uncharge(&mem->memsw, PAGE_SIZE);
978                 css_put(&mem->css);
979                 return;
980         }
981         pc->mem_cgroup = mem;
982         smp_wmb();
983         pc->flags = pcg_default_flags[ctype];
984
985         mem_cgroup_charge_statistics(mem, pc, true);
986
987         unlock_page_cgroup(pc);
988 }
989
990 /**
991  * mem_cgroup_move_account - move account of the page
992  * @pc: page_cgroup of the page.
993  * @from: mem_cgroup which the page is moved from.
994  * @to: mem_cgroup which the page is moved to. @from != @to.
995  *
996  * The caller must confirm following.
997  * - page is not on LRU (isolate_page() is useful.)
998  *
999  * returns 0 at success,
1000  * returns -EBUSY when lock is busy or "pc" is unstable.
1001  *
1002  * This function does "uncharge" from old cgroup but doesn't do "charge" to
1003  * new cgroup. It should be done by a caller.
1004  */
1005
1006 static int mem_cgroup_move_account(struct page_cgroup *pc,
1007         struct mem_cgroup *from, struct mem_cgroup *to)
1008 {
1009         struct mem_cgroup_per_zone *from_mz, *to_mz;
1010         int nid, zid;
1011         int ret = -EBUSY;
1012
1013         VM_BUG_ON(from == to);
1014         VM_BUG_ON(PageLRU(pc->page));
1015
1016         nid = page_cgroup_nid(pc);
1017         zid = page_cgroup_zid(pc);
1018         from_mz =  mem_cgroup_zoneinfo(from, nid, zid);
1019         to_mz =  mem_cgroup_zoneinfo(to, nid, zid);
1020
1021         if (!trylock_page_cgroup(pc))
1022                 return ret;
1023
1024         if (!PageCgroupUsed(pc))
1025                 goto out;
1026
1027         if (pc->mem_cgroup != from)
1028                 goto out;
1029
1030         res_counter_uncharge(&from->res, PAGE_SIZE);
1031         mem_cgroup_charge_statistics(from, pc, false);
1032         if (do_swap_account)
1033                 res_counter_uncharge(&from->memsw, PAGE_SIZE);
1034         css_put(&from->css);
1035
1036         css_get(&to->css);
1037         pc->mem_cgroup = to;
1038         mem_cgroup_charge_statistics(to, pc, true);
1039         ret = 0;
1040 out:
1041         unlock_page_cgroup(pc);
1042         return ret;
1043 }
1044
1045 /*
1046  * move charges to its parent.
1047  */
1048
1049 static int mem_cgroup_move_parent(struct page_cgroup *pc,
1050                                   struct mem_cgroup *child,
1051                                   gfp_t gfp_mask)
1052 {
1053         struct page *page = pc->page;
1054         struct cgroup *cg = child->css.cgroup;
1055         struct cgroup *pcg = cg->parent;
1056         struct mem_cgroup *parent;
1057         int ret;
1058
1059         /* Is ROOT ? */
1060         if (!pcg)
1061                 return -EINVAL;
1062
1063
1064         parent = mem_cgroup_from_cont(pcg);
1065
1066
1067         ret = __mem_cgroup_try_charge(NULL, gfp_mask, &parent, false);
1068         if (ret || !parent)
1069                 return ret;
1070
1071         if (!get_page_unless_zero(page)) {
1072                 ret = -EBUSY;
1073                 goto uncharge;
1074         }
1075
1076         ret = isolate_lru_page(page);
1077
1078         if (ret)
1079                 goto cancel;
1080
1081         ret = mem_cgroup_move_account(pc, child, parent);
1082
1083         putback_lru_page(page);
1084         if (!ret) {
1085                 put_page(page);
1086                 /* drop extra refcnt by try_charge() */
1087                 css_put(&parent->css);
1088                 return 0;
1089         }
1090
1091 cancel:
1092         put_page(page);
1093 uncharge:
1094         /* drop extra refcnt by try_charge() */
1095         css_put(&parent->css);
1096         /* uncharge if move fails */
1097         res_counter_uncharge(&parent->res, PAGE_SIZE);
1098         if (do_swap_account)
1099                 res_counter_uncharge(&parent->memsw, PAGE_SIZE);
1100         return ret;
1101 }
1102
1103 /*
1104  * Charge the memory controller for page usage.
1105  * Return
1106  * 0 if the charge was successful
1107  * < 0 if the cgroup is over its limit
1108  */
1109 static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
1110                                 gfp_t gfp_mask, enum charge_type ctype,
1111                                 struct mem_cgroup *memcg)
1112 {
1113         struct mem_cgroup *mem;
1114         struct page_cgroup *pc;
1115         int ret;
1116
1117         pc = lookup_page_cgroup(page);
1118         /* can happen at boot */
1119         if (unlikely(!pc))
1120                 return 0;
1121         prefetchw(pc);
1122
1123         mem = memcg;
1124         ret = __mem_cgroup_try_charge(mm, gfp_mask, &mem, true);
1125         if (ret || !mem)
1126                 return ret;
1127
1128         __mem_cgroup_commit_charge(mem, pc, ctype);
1129         return 0;
1130 }
1131
1132 int mem_cgroup_newpage_charge(struct page *page,
1133                               struct mm_struct *mm, gfp_t gfp_mask)
1134 {
1135         if (mem_cgroup_disabled())
1136                 return 0;
1137         if (PageCompound(page))
1138                 return 0;
1139         /*
1140          * If already mapped, we don't have to account.
1141          * If page cache, page->mapping has address_space.
1142          * But page->mapping may have out-of-use anon_vma pointer,
1143          * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
1144          * is NULL.
1145          */
1146         if (page_mapped(page) || (page->mapping && !PageAnon(page)))
1147                 return 0;
1148         if (unlikely(!mm))
1149                 mm = &init_mm;
1150         return mem_cgroup_charge_common(page, mm, gfp_mask,
1151                                 MEM_CGROUP_CHARGE_TYPE_MAPPED, NULL);
1152 }
1153
1154 int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
1155                                 gfp_t gfp_mask)
1156 {
1157         struct mem_cgroup *mem = NULL;
1158         int ret;
1159
1160         if (mem_cgroup_disabled())
1161                 return 0;
1162         if (PageCompound(page))
1163                 return 0;
1164         /*
1165          * Corner case handling. This is called from add_to_page_cache()
1166          * in usual. But some FS (shmem) precharges this page before calling it
1167          * and call add_to_page_cache() with GFP_NOWAIT.
1168          *
1169          * For GFP_NOWAIT case, the page may be pre-charged before calling
1170          * add_to_page_cache(). (See shmem.c) check it here and avoid to call
1171          * charge twice. (It works but has to pay a bit larger cost.)
1172          * And when the page is SwapCache, it should take swap information
1173          * into account. This is under lock_page() now.
1174          */
1175         if (!(gfp_mask & __GFP_WAIT)) {
1176                 struct page_cgroup *pc;
1177
1178
1179                 pc = lookup_page_cgroup(page);
1180                 if (!pc)
1181                         return 0;
1182                 lock_page_cgroup(pc);
1183                 if (PageCgroupUsed(pc)) {
1184                         unlock_page_cgroup(pc);
1185                         return 0;
1186                 }
1187                 unlock_page_cgroup(pc);
1188         }
1189
1190         if (do_swap_account && PageSwapCache(page)) {
1191                 mem = try_get_mem_cgroup_from_swapcache(page);
1192                 if (mem)
1193                         mm = NULL;
1194                   else
1195                         mem = NULL;
1196                 /* SwapCache may be still linked to LRU now. */
1197                 mem_cgroup_lru_del_before_commit_swapcache(page);
1198         }
1199
1200         if (unlikely(!mm && !mem))
1201                 mm = &init_mm;
1202
1203         if (page_is_file_cache(page))
1204                 return mem_cgroup_charge_common(page, mm, gfp_mask,
1205                                 MEM_CGROUP_CHARGE_TYPE_CACHE, NULL);
1206
1207         ret = mem_cgroup_charge_common(page, mm, gfp_mask,
1208                                 MEM_CGROUP_CHARGE_TYPE_SHMEM, mem);
1209         if (mem)
1210                 css_put(&mem->css);
1211         if (PageSwapCache(page))
1212                 mem_cgroup_lru_add_after_commit_swapcache(page);
1213
1214         if (do_swap_account && !ret && PageSwapCache(page)) {
1215                 swp_entry_t ent = {.val = page_private(page)};
1216                 /* avoid double counting */
1217                 mem = swap_cgroup_record(ent, NULL);
1218                 if (mem) {
1219                         res_counter_uncharge(&mem->memsw, PAGE_SIZE);
1220                         mem_cgroup_put(mem);
1221                 }
1222         }
1223         return ret;
1224 }
1225
1226 /*
1227  * While swap-in, try_charge -> commit or cancel, the page is locked.
1228  * And when try_charge() successfully returns, one refcnt to memcg without
1229  * struct page_cgroup is aquired. This refcnt will be cumsumed by
1230  * "commit()" or removed by "cancel()"
1231  */
1232 int mem_cgroup_try_charge_swapin(struct mm_struct *mm,
1233                                  struct page *page,
1234                                  gfp_t mask, struct mem_cgroup **ptr)
1235 {
1236         struct mem_cgroup *mem;
1237         int ret;
1238
1239         if (mem_cgroup_disabled())
1240                 return 0;
1241
1242         if (!do_swap_account)
1243                 goto charge_cur_mm;
1244         /*
1245          * A racing thread's fault, or swapoff, may have already updated
1246          * the pte, and even removed page from swap cache: return success
1247          * to go on to do_swap_page()'s pte_same() test, which should fail.
1248          */
1249         if (!PageSwapCache(page))
1250                 return 0;
1251         mem = try_get_mem_cgroup_from_swapcache(page);
1252         if (!mem)
1253                 goto charge_cur_mm;
1254         *ptr = mem;
1255         ret = __mem_cgroup_try_charge(NULL, mask, ptr, true);
1256         /* drop extra refcnt from tryget */
1257         css_put(&mem->css);
1258         return ret;
1259 charge_cur_mm:
1260         if (unlikely(!mm))
1261                 mm = &init_mm;
1262         return __mem_cgroup_try_charge(mm, mask, ptr, true);
1263 }
1264
1265 void mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr)
1266 {
1267         struct page_cgroup *pc;
1268
1269         if (mem_cgroup_disabled())
1270                 return;
1271         if (!ptr)
1272                 return;
1273         pc = lookup_page_cgroup(page);
1274         mem_cgroup_lru_del_before_commit_swapcache(page);
1275         __mem_cgroup_commit_charge(ptr, pc, MEM_CGROUP_CHARGE_TYPE_MAPPED);
1276         mem_cgroup_lru_add_after_commit_swapcache(page);
1277         /*
1278          * Now swap is on-memory. This means this page may be
1279          * counted both as mem and swap....double count.
1280          * Fix it by uncharging from memsw. Basically, this SwapCache is stable
1281          * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
1282          * may call delete_from_swap_cache() before reach here.
1283          */
1284         if (do_swap_account && PageSwapCache(page)) {
1285                 swp_entry_t ent = {.val = page_private(page)};
1286                 struct mem_cgroup *memcg;
1287                 memcg = swap_cgroup_record(ent, NULL);
1288                 if (memcg) {
1289                         res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
1290                         mem_cgroup_put(memcg);
1291                 }
1292
1293         }
1294         /* add this page(page_cgroup) to the LRU we want. */
1295
1296 }
1297
1298 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *mem)
1299 {
1300         if (mem_cgroup_disabled())
1301                 return;
1302         if (!mem)
1303                 return;
1304         res_counter_uncharge(&mem->res, PAGE_SIZE);
1305         if (do_swap_account)
1306                 res_counter_uncharge(&mem->memsw, PAGE_SIZE);
1307         css_put(&mem->css);
1308 }
1309
1310
1311 /*
1312  * uncharge if !page_mapped(page)
1313  */
1314 static struct mem_cgroup *
1315 __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype)
1316 {
1317         struct page_cgroup *pc;
1318         struct mem_cgroup *mem = NULL;
1319         struct mem_cgroup_per_zone *mz;
1320
1321         if (mem_cgroup_disabled())
1322                 return NULL;
1323
1324         if (PageSwapCache(page))
1325                 return NULL;
1326
1327         /*
1328          * Check if our page_cgroup is valid
1329          */
1330         pc = lookup_page_cgroup(page);
1331         if (unlikely(!pc || !PageCgroupUsed(pc)))
1332                 return NULL;
1333
1334         lock_page_cgroup(pc);
1335
1336         mem = pc->mem_cgroup;
1337
1338         if (!PageCgroupUsed(pc))
1339                 goto unlock_out;
1340
1341         switch (ctype) {
1342         case MEM_CGROUP_CHARGE_TYPE_MAPPED:
1343                 if (page_mapped(page))
1344                         goto unlock_out;
1345                 break;
1346         case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
1347                 if (!PageAnon(page)) {  /* Shared memory */
1348                         if (page->mapping && !page_is_file_cache(page))
1349                                 goto unlock_out;
1350                 } else if (page_mapped(page)) /* Anon */
1351                                 goto unlock_out;
1352                 break;
1353         default:
1354                 break;
1355         }
1356
1357         res_counter_uncharge(&mem->res, PAGE_SIZE);
1358         if (do_swap_account && (ctype != MEM_CGROUP_CHARGE_TYPE_SWAPOUT))
1359                 res_counter_uncharge(&mem->memsw, PAGE_SIZE);
1360         mem_cgroup_charge_statistics(mem, pc, false);
1361
1362         ClearPageCgroupUsed(pc);
1363         /*
1364          * pc->mem_cgroup is not cleared here. It will be accessed when it's
1365          * freed from LRU. This is safe because uncharged page is expected not
1366          * to be reused (freed soon). Exception is SwapCache, it's handled by
1367          * special functions.
1368          */
1369
1370         mz = page_cgroup_zoneinfo(pc);
1371         unlock_page_cgroup(pc);
1372
1373         /* at swapout, this memcg will be accessed to record to swap */
1374         if (ctype != MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
1375                 css_put(&mem->css);
1376
1377         return mem;
1378
1379 unlock_out:
1380         unlock_page_cgroup(pc);
1381         return NULL;
1382 }
1383
1384 void mem_cgroup_uncharge_page(struct page *page)
1385 {
1386         /* early check. */
1387         if (page_mapped(page))
1388                 return;
1389         if (page->mapping && !PageAnon(page))
1390                 return;
1391         __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_MAPPED);
1392 }
1393
1394 void mem_cgroup_uncharge_cache_page(struct page *page)
1395 {
1396         VM_BUG_ON(page_mapped(page));
1397         VM_BUG_ON(page->mapping);
1398         __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE);
1399 }
1400
1401 /*
1402  * called from __delete_from_swap_cache() and drop "page" account.
1403  * memcg information is recorded to swap_cgroup of "ent"
1404  */
1405 void mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent)
1406 {
1407         struct mem_cgroup *memcg;
1408
1409         memcg = __mem_cgroup_uncharge_common(page,
1410                                         MEM_CGROUP_CHARGE_TYPE_SWAPOUT);
1411         /* record memcg information */
1412         if (do_swap_account && memcg) {
1413                 swap_cgroup_record(ent, memcg);
1414                 mem_cgroup_get(memcg);
1415         }
1416         if (memcg)
1417                 css_put(&memcg->css);
1418 }
1419
1420 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
1421 /*
1422  * called from swap_entry_free(). remove record in swap_cgroup and
1423  * uncharge "memsw" account.
1424  */
1425 void mem_cgroup_uncharge_swap(swp_entry_t ent)
1426 {
1427         struct mem_cgroup *memcg;
1428
1429         if (!do_swap_account)
1430                 return;
1431
1432         memcg = swap_cgroup_record(ent, NULL);
1433         if (memcg) {
1434                 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
1435                 mem_cgroup_put(memcg);
1436         }
1437 }
1438 #endif
1439
1440 /*
1441  * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
1442  * page belongs to.
1443  */
1444 int mem_cgroup_prepare_migration(struct page *page, struct mem_cgroup **ptr)
1445 {
1446         struct page_cgroup *pc;
1447         struct mem_cgroup *mem = NULL;
1448         int ret = 0;
1449
1450         if (mem_cgroup_disabled())
1451                 return 0;
1452
1453         pc = lookup_page_cgroup(page);
1454         lock_page_cgroup(pc);
1455         if (PageCgroupUsed(pc)) {
1456                 mem = pc->mem_cgroup;
1457                 css_get(&mem->css);
1458         }
1459         unlock_page_cgroup(pc);
1460
1461         if (mem) {
1462                 ret = __mem_cgroup_try_charge(NULL, GFP_KERNEL, &mem, false);
1463                 css_put(&mem->css);
1464         }
1465         *ptr = mem;
1466         return ret;
1467 }
1468
1469 /* remove redundant charge if migration failed*/
1470 void mem_cgroup_end_migration(struct mem_cgroup *mem,
1471                 struct page *oldpage, struct page *newpage)
1472 {
1473         struct page *target, *unused;
1474         struct page_cgroup *pc;
1475         enum charge_type ctype;
1476
1477         if (!mem)
1478                 return;
1479
1480         /* at migration success, oldpage->mapping is NULL. */
1481         if (oldpage->mapping) {
1482                 target = oldpage;
1483                 unused = NULL;
1484         } else {
1485                 target = newpage;
1486                 unused = oldpage;
1487         }
1488
1489         if (PageAnon(target))
1490                 ctype = MEM_CGROUP_CHARGE_TYPE_MAPPED;
1491         else if (page_is_file_cache(target))
1492                 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
1493         else
1494                 ctype = MEM_CGROUP_CHARGE_TYPE_SHMEM;
1495
1496         /* unused page is not on radix-tree now. */
1497         if (unused)
1498                 __mem_cgroup_uncharge_common(unused, ctype);
1499
1500         pc = lookup_page_cgroup(target);
1501         /*
1502          * __mem_cgroup_commit_charge() check PCG_USED bit of page_cgroup.
1503          * So, double-counting is effectively avoided.
1504          */
1505         __mem_cgroup_commit_charge(mem, pc, ctype);
1506
1507         /*
1508          * Both of oldpage and newpage are still under lock_page().
1509          * Then, we don't have to care about race in radix-tree.
1510          * But we have to be careful that this page is unmapped or not.
1511          *
1512          * There is a case for !page_mapped(). At the start of
1513          * migration, oldpage was mapped. But now, it's zapped.
1514          * But we know *target* page is not freed/reused under us.
1515          * mem_cgroup_uncharge_page() does all necessary checks.
1516          */
1517         if (ctype == MEM_CGROUP_CHARGE_TYPE_MAPPED)
1518                 mem_cgroup_uncharge_page(target);
1519 }
1520
1521 /*
1522  * A call to try to shrink memory usage under specified resource controller.
1523  * This is typically used for page reclaiming for shmem for reducing side
1524  * effect of page allocation from shmem, which is used by some mem_cgroup.
1525  */
1526 int mem_cgroup_shrink_usage(struct page *page,
1527                             struct mm_struct *mm,
1528                             gfp_t gfp_mask)
1529 {
1530         struct mem_cgroup *mem = NULL;
1531         int progress = 0;
1532         int retry = MEM_CGROUP_RECLAIM_RETRIES;
1533
1534         if (mem_cgroup_disabled())
1535                 return 0;
1536         if (page)
1537                 mem = try_get_mem_cgroup_from_swapcache(page);
1538         if (!mem && mm)
1539                 mem = try_get_mem_cgroup_from_mm(mm);
1540         if (unlikely(!mem))
1541                 return 0;
1542
1543         do {
1544                 progress = mem_cgroup_hierarchical_reclaim(mem,
1545                                         gfp_mask, true, false);
1546                 progress += mem_cgroup_check_under_limit(mem);
1547         } while (!progress && --retry);
1548
1549         css_put(&mem->css);
1550         if (!retry)
1551                 return -ENOMEM;
1552         return 0;
1553 }
1554
1555 static DEFINE_MUTEX(set_limit_mutex);
1556
1557 static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
1558                                 unsigned long long val)
1559 {
1560         int retry_count;
1561         int progress;
1562         u64 memswlimit;
1563         int ret = 0;
1564         int children = mem_cgroup_count_children(memcg);
1565         u64 curusage, oldusage;
1566
1567         /*
1568          * For keeping hierarchical_reclaim simple, how long we should retry
1569          * is depends on callers. We set our retry-count to be function
1570          * of # of children which we should visit in this loop.
1571          */
1572         retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
1573
1574         oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
1575
1576         while (retry_count) {
1577                 if (signal_pending(current)) {
1578                         ret = -EINTR;
1579                         break;
1580                 }
1581                 /*
1582                  * Rather than hide all in some function, I do this in
1583                  * open coded manner. You see what this really does.
1584                  * We have to guarantee mem->res.limit < mem->memsw.limit.
1585                  */
1586                 mutex_lock(&set_limit_mutex);
1587                 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
1588                 if (memswlimit < val) {
1589                         ret = -EINVAL;
1590                         mutex_unlock(&set_limit_mutex);
1591                         break;
1592                 }
1593                 ret = res_counter_set_limit(&memcg->res, val);
1594                 mutex_unlock(&set_limit_mutex);
1595
1596                 if (!ret)
1597                         break;
1598
1599                 progress = mem_cgroup_hierarchical_reclaim(memcg, GFP_KERNEL,
1600                                                    false, true);
1601                 curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
1602                 /* Usage is reduced ? */
1603                 if (curusage >= oldusage)
1604                         retry_count--;
1605                 else
1606                         oldusage = curusage;
1607         }
1608
1609         return ret;
1610 }
1611
1612 int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
1613                                 unsigned long long val)
1614 {
1615         int retry_count;
1616         u64 memlimit, oldusage, curusage;
1617         int children = mem_cgroup_count_children(memcg);
1618         int ret = -EBUSY;
1619
1620         if (!do_swap_account)
1621                 return -EINVAL;
1622         /* see mem_cgroup_resize_res_limit */
1623         retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
1624         oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
1625         while (retry_count) {
1626                 if (signal_pending(current)) {
1627                         ret = -EINTR;
1628                         break;
1629                 }
1630                 /*
1631                  * Rather than hide all in some function, I do this in
1632                  * open coded manner. You see what this really does.
1633                  * We have to guarantee mem->res.limit < mem->memsw.limit.
1634                  */
1635                 mutex_lock(&set_limit_mutex);
1636                 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
1637                 if (memlimit > val) {
1638                         ret = -EINVAL;
1639                         mutex_unlock(&set_limit_mutex);
1640                         break;
1641                 }
1642                 ret = res_counter_set_limit(&memcg->memsw, val);
1643                 mutex_unlock(&set_limit_mutex);
1644
1645                 if (!ret)
1646                         break;
1647
1648                 mem_cgroup_hierarchical_reclaim(memcg, GFP_KERNEL, true, true);
1649                 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
1650                 /* Usage is reduced ? */
1651                 if (curusage >= oldusage)
1652                         retry_count--;
1653                 else
1654                         oldusage = curusage;
1655         }
1656         return ret;
1657 }
1658
1659 /*
1660  * This routine traverse page_cgroup in given list and drop them all.
1661  * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
1662  */
1663 static int mem_cgroup_force_empty_list(struct mem_cgroup *mem,
1664                                 int node, int zid, enum lru_list lru)
1665 {
1666         struct zone *zone;
1667         struct mem_cgroup_per_zone *mz;
1668         struct page_cgroup *pc, *busy;
1669         unsigned long flags, loop;
1670         struct list_head *list;
1671         int ret = 0;
1672
1673         zone = &NODE_DATA(node)->node_zones[zid];
1674         mz = mem_cgroup_zoneinfo(mem, node, zid);
1675         list = &mz->lists[lru];
1676
1677         loop = MEM_CGROUP_ZSTAT(mz, lru);
1678         /* give some margin against EBUSY etc...*/
1679         loop += 256;
1680         busy = NULL;
1681         while (loop--) {
1682                 ret = 0;
1683                 spin_lock_irqsave(&zone->lru_lock, flags);
1684                 if (list_empty(list)) {
1685                         spin_unlock_irqrestore(&zone->lru_lock, flags);
1686                         break;
1687                 }
1688                 pc = list_entry(list->prev, struct page_cgroup, lru);
1689                 if (busy == pc) {
1690                         list_move(&pc->lru, list);
1691                         busy = 0;
1692                         spin_unlock_irqrestore(&zone->lru_lock, flags);
1693                         continue;
1694                 }
1695                 spin_unlock_irqrestore(&zone->lru_lock, flags);
1696
1697                 ret = mem_cgroup_move_parent(pc, mem, GFP_KERNEL);
1698                 if (ret == -ENOMEM)
1699                         break;
1700
1701                 if (ret == -EBUSY || ret == -EINVAL) {
1702                         /* found lock contention or "pc" is obsolete. */
1703                         busy = pc;
1704                         cond_resched();
1705                 } else
1706                         busy = NULL;
1707         }
1708
1709         if (!ret && !list_empty(list))
1710                 return -EBUSY;
1711         return ret;
1712 }
1713
1714 /*
1715  * make mem_cgroup's charge to be 0 if there is no task.
1716  * This enables deleting this mem_cgroup.
1717  */
1718 static int mem_cgroup_force_empty(struct mem_cgroup *mem, bool free_all)
1719 {
1720         int ret;
1721         int node, zid, shrink;
1722         int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
1723         struct cgroup *cgrp = mem->css.cgroup;
1724
1725         css_get(&mem->css);
1726
1727         shrink = 0;
1728         /* should free all ? */
1729         if (free_all)
1730                 goto try_to_free;
1731 move_account:
1732         while (mem->res.usage > 0) {
1733                 ret = -EBUSY;
1734                 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
1735                         goto out;
1736                 ret = -EINTR;
1737                 if (signal_pending(current))
1738                         goto out;
1739                 /* This is for making all *used* pages to be on LRU. */
1740                 lru_add_drain_all();
1741                 ret = 0;
1742                 for_each_node_state(node, N_HIGH_MEMORY) {
1743                         for (zid = 0; !ret && zid < MAX_NR_ZONES; zid++) {
1744                                 enum lru_list l;
1745                                 for_each_lru(l) {
1746                                         ret = mem_cgroup_force_empty_list(mem,
1747                                                         node, zid, l);
1748                                         if (ret)
1749                                                 break;
1750                                 }
1751                         }
1752                         if (ret)
1753                                 break;
1754                 }
1755                 /* it seems parent cgroup doesn't have enough mem */
1756                 if (ret == -ENOMEM)
1757                         goto try_to_free;
1758                 cond_resched();
1759         }
1760         ret = 0;
1761 out:
1762         css_put(&mem->css);
1763         return ret;
1764
1765 try_to_free:
1766         /* returns EBUSY if there is a task or if we come here twice. */
1767         if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children) || shrink) {
1768                 ret = -EBUSY;
1769                 goto out;
1770         }
1771         /* we call try-to-free pages for make this cgroup empty */
1772         lru_add_drain_all();
1773         /* try to free all pages in this cgroup */
1774         shrink = 1;
1775         while (nr_retries && mem->res.usage > 0) {
1776                 int progress;
1777
1778                 if (signal_pending(current)) {
1779                         ret = -EINTR;
1780                         goto out;
1781                 }
1782                 progress = try_to_free_mem_cgroup_pages(mem, GFP_KERNEL,
1783                                                 false, get_swappiness(mem));
1784                 if (!progress) {
1785                         nr_retries--;
1786                         /* maybe some writeback is necessary */
1787                         congestion_wait(WRITE, HZ/10);
1788                 }
1789
1790         }
1791         lru_add_drain();
1792         /* try move_account...there may be some *locked* pages. */
1793         if (mem->res.usage)
1794                 goto move_account;
1795         ret = 0;
1796         goto out;
1797 }
1798
1799 int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
1800 {
1801         return mem_cgroup_force_empty(mem_cgroup_from_cont(cont), true);
1802 }
1803
1804
1805 static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
1806 {
1807         return mem_cgroup_from_cont(cont)->use_hierarchy;
1808 }
1809
1810 static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
1811                                         u64 val)
1812 {
1813         int retval = 0;
1814         struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
1815         struct cgroup *parent = cont->parent;
1816         struct mem_cgroup *parent_mem = NULL;
1817
1818         if (parent)
1819                 parent_mem = mem_cgroup_from_cont(parent);
1820
1821         cgroup_lock();
1822         /*
1823          * If parent's use_hiearchy is set, we can't make any modifications
1824          * in the child subtrees. If it is unset, then the change can
1825          * occur, provided the current cgroup has no children.
1826          *
1827          * For the root cgroup, parent_mem is NULL, we allow value to be
1828          * set if there are no children.
1829          */
1830         if ((!parent_mem || !parent_mem->use_hierarchy) &&
1831                                 (val == 1 || val == 0)) {
1832                 if (list_empty(&cont->children))
1833                         mem->use_hierarchy = val;
1834                 else
1835                         retval = -EBUSY;
1836         } else
1837                 retval = -EINVAL;
1838         cgroup_unlock();
1839
1840         return retval;
1841 }
1842
1843 static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft)
1844 {
1845         struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
1846         u64 val = 0;
1847         int type, name;
1848
1849         type = MEMFILE_TYPE(cft->private);
1850         name = MEMFILE_ATTR(cft->private);
1851         switch (type) {
1852         case _MEM:
1853                 val = res_counter_read_u64(&mem->res, name);
1854                 break;
1855         case _MEMSWAP:
1856                 if (do_swap_account)
1857                         val = res_counter_read_u64(&mem->memsw, name);
1858                 break;
1859         default:
1860                 BUG();
1861                 break;
1862         }
1863         return val;
1864 }
1865 /*
1866  * The user of this function is...
1867  * RES_LIMIT.
1868  */
1869 static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
1870                             const char *buffer)
1871 {
1872         struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
1873         int type, name;
1874         unsigned long long val;
1875         int ret;
1876
1877         type = MEMFILE_TYPE(cft->private);
1878         name = MEMFILE_ATTR(cft->private);
1879         switch (name) {
1880         case RES_LIMIT:
1881                 /* This function does all necessary parse...reuse it */
1882                 ret = res_counter_memparse_write_strategy(buffer, &val);
1883                 if (ret)
1884                         break;
1885                 if (type == _MEM)
1886                         ret = mem_cgroup_resize_limit(memcg, val);
1887                 else
1888                         ret = mem_cgroup_resize_memsw_limit(memcg, val);
1889                 break;
1890         default:
1891                 ret = -EINVAL; /* should be BUG() ? */
1892                 break;
1893         }
1894         return ret;
1895 }
1896
1897 static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
1898                 unsigned long long *mem_limit, unsigned long long *memsw_limit)
1899 {
1900         struct cgroup *cgroup;
1901         unsigned long long min_limit, min_memsw_limit, tmp;
1902
1903         min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
1904         min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
1905         cgroup = memcg->css.cgroup;
1906         if (!memcg->use_hierarchy)
1907                 goto out;
1908
1909         while (cgroup->parent) {
1910                 cgroup = cgroup->parent;
1911                 memcg = mem_cgroup_from_cont(cgroup);
1912                 if (!memcg->use_hierarchy)
1913                         break;
1914                 tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
1915                 min_limit = min(min_limit, tmp);
1916                 tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
1917                 min_memsw_limit = min(min_memsw_limit, tmp);
1918         }
1919 out:
1920         *mem_limit = min_limit;
1921         *memsw_limit = min_memsw_limit;
1922         return;
1923 }
1924
1925 static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
1926 {
1927         struct mem_cgroup *mem;
1928         int type, name;
1929
1930         mem = mem_cgroup_from_cont(cont);
1931         type = MEMFILE_TYPE(event);
1932         name = MEMFILE_ATTR(event);
1933         switch (name) {
1934         case RES_MAX_USAGE:
1935                 if (type == _MEM)
1936                         res_counter_reset_max(&mem->res);
1937                 else
1938                         res_counter_reset_max(&mem->memsw);
1939                 break;
1940         case RES_FAILCNT:
1941                 if (type == _MEM)
1942                         res_counter_reset_failcnt(&mem->res);
1943                 else
1944                         res_counter_reset_failcnt(&mem->memsw);
1945                 break;
1946         }
1947         return 0;
1948 }
1949
1950
1951 /* For read statistics */
1952 enum {
1953         MCS_CACHE,
1954         MCS_RSS,
1955         MCS_PGPGIN,
1956         MCS_PGPGOUT,
1957         MCS_INACTIVE_ANON,
1958         MCS_ACTIVE_ANON,
1959         MCS_INACTIVE_FILE,
1960         MCS_ACTIVE_FILE,
1961         MCS_UNEVICTABLE,
1962         NR_MCS_STAT,
1963 };
1964
1965 struct mcs_total_stat {
1966         s64 stat[NR_MCS_STAT];
1967 };
1968
1969 struct {
1970         char *local_name;
1971         char *total_name;
1972 } memcg_stat_strings[NR_MCS_STAT] = {
1973         {"cache", "total_cache"},
1974         {"rss", "total_rss"},
1975         {"pgpgin", "total_pgpgin"},
1976         {"pgpgout", "total_pgpgout"},
1977         {"inactive_anon", "total_inactive_anon"},
1978         {"active_anon", "total_active_anon"},
1979         {"inactive_file", "total_inactive_file"},
1980         {"active_file", "total_active_file"},
1981         {"unevictable", "total_unevictable"}
1982 };
1983
1984
1985 static int mem_cgroup_get_local_stat(struct mem_cgroup *mem, void *data)
1986 {
1987         struct mcs_total_stat *s = data;
1988         s64 val;
1989
1990         /* per cpu stat */
1991         val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_CACHE);
1992         s->stat[MCS_CACHE] += val * PAGE_SIZE;
1993         val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_RSS);
1994         s->stat[MCS_RSS] += val * PAGE_SIZE;
1995         val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_PGPGIN_COUNT);
1996         s->stat[MCS_PGPGIN] += val;
1997         val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_PGPGOUT_COUNT);
1998         s->stat[MCS_PGPGOUT] += val;
1999
2000         /* per zone stat */
2001         val = mem_cgroup_get_local_zonestat(mem, LRU_INACTIVE_ANON);
2002         s->stat[MCS_INACTIVE_ANON] += val * PAGE_SIZE;
2003         val = mem_cgroup_get_local_zonestat(mem, LRU_ACTIVE_ANON);
2004         s->stat[MCS_ACTIVE_ANON] += val * PAGE_SIZE;
2005         val = mem_cgroup_get_local_zonestat(mem, LRU_INACTIVE_FILE);
2006         s->stat[MCS_INACTIVE_FILE] += val * PAGE_SIZE;
2007         val = mem_cgroup_get_local_zonestat(mem, LRU_ACTIVE_FILE);
2008         s->stat[MCS_ACTIVE_FILE] += val * PAGE_SIZE;
2009         val = mem_cgroup_get_local_zonestat(mem, LRU_UNEVICTABLE);
2010         s->stat[MCS_UNEVICTABLE] += val * PAGE_SIZE;
2011         return 0;
2012 }
2013
2014 static void
2015 mem_cgroup_get_total_stat(struct mem_cgroup *mem, struct mcs_total_stat *s)
2016 {
2017         mem_cgroup_walk_tree(mem, s, mem_cgroup_get_local_stat);
2018 }
2019
2020 static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft,
2021                                  struct cgroup_map_cb *cb)
2022 {
2023         struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
2024         struct mcs_total_stat mystat;
2025         int i;
2026
2027         memset(&mystat, 0, sizeof(mystat));
2028         mem_cgroup_get_local_stat(mem_cont, &mystat);
2029
2030         for (i = 0; i < NR_MCS_STAT; i++)
2031                 cb->fill(cb, memcg_stat_strings[i].local_name, mystat.stat[i]);
2032
2033         /* Hierarchical information */
2034         {
2035                 unsigned long long limit, memsw_limit;
2036                 memcg_get_hierarchical_limit(mem_cont, &limit, &memsw_limit);
2037                 cb->fill(cb, "hierarchical_memory_limit", limit);
2038                 if (do_swap_account)
2039                         cb->fill(cb, "hierarchical_memsw_limit", memsw_limit);
2040         }
2041
2042         memset(&mystat, 0, sizeof(mystat));
2043         mem_cgroup_get_total_stat(mem_cont, &mystat);
2044         for (i = 0; i < NR_MCS_STAT; i++)
2045                 cb->fill(cb, memcg_stat_strings[i].total_name, mystat.stat[i]);
2046
2047
2048 #ifdef CONFIG_DEBUG_VM
2049         cb->fill(cb, "inactive_ratio", calc_inactive_ratio(mem_cont, NULL));
2050
2051         {
2052                 int nid, zid;
2053                 struct mem_cgroup_per_zone *mz;
2054                 unsigned long recent_rotated[2] = {0, 0};
2055                 unsigned long recent_scanned[2] = {0, 0};
2056
2057                 for_each_online_node(nid)
2058                         for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2059                                 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
2060
2061                                 recent_rotated[0] +=
2062                                         mz->reclaim_stat.recent_rotated[0];
2063                                 recent_rotated[1] +=
2064                                         mz->reclaim_stat.recent_rotated[1];
2065                                 recent_scanned[0] +=
2066                                         mz->reclaim_stat.recent_scanned[0];
2067                                 recent_scanned[1] +=
2068                                         mz->reclaim_stat.recent_scanned[1];
2069                         }
2070                 cb->fill(cb, "recent_rotated_anon", recent_rotated[0]);
2071                 cb->fill(cb, "recent_rotated_file", recent_rotated[1]);
2072                 cb->fill(cb, "recent_scanned_anon", recent_scanned[0]);
2073                 cb->fill(cb, "recent_scanned_file", recent_scanned[1]);
2074         }
2075 #endif
2076
2077         return 0;
2078 }
2079
2080 static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
2081 {
2082         struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
2083
2084         return get_swappiness(memcg);
2085 }
2086
2087 static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
2088                                        u64 val)
2089 {
2090         struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
2091         struct mem_cgroup *parent;
2092
2093         if (val > 100)
2094                 return -EINVAL;
2095
2096         if (cgrp->parent == NULL)
2097                 return -EINVAL;
2098
2099         parent = mem_cgroup_from_cont(cgrp->parent);
2100
2101         cgroup_lock();
2102
2103         /* If under hierarchy, only empty-root can set this value */
2104         if ((parent->use_hierarchy) ||
2105             (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
2106                 cgroup_unlock();
2107                 return -EINVAL;
2108         }
2109
2110         spin_lock(&memcg->reclaim_param_lock);
2111         memcg->swappiness = val;
2112         spin_unlock(&memcg->reclaim_param_lock);
2113
2114         cgroup_unlock();
2115
2116         return 0;
2117 }
2118
2119
2120 static struct cftype mem_cgroup_files[] = {
2121         {
2122                 .name = "usage_in_bytes",
2123                 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
2124                 .read_u64 = mem_cgroup_read,
2125         },
2126         {
2127                 .name = "max_usage_in_bytes",
2128                 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
2129                 .trigger = mem_cgroup_reset,
2130                 .read_u64 = mem_cgroup_read,
2131         },
2132         {
2133                 .name = "limit_in_bytes",
2134                 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
2135                 .write_string = mem_cgroup_write,
2136                 .read_u64 = mem_cgroup_read,
2137         },
2138         {
2139                 .name = "failcnt",
2140                 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
2141                 .trigger = mem_cgroup_reset,
2142                 .read_u64 = mem_cgroup_read,
2143         },
2144         {
2145                 .name = "stat",
2146                 .read_map = mem_control_stat_show,
2147         },
2148         {
2149                 .name = "force_empty",
2150                 .trigger = mem_cgroup_force_empty_write,
2151         },
2152         {
2153                 .name = "use_hierarchy",
2154                 .write_u64 = mem_cgroup_hierarchy_write,
2155                 .read_u64 = mem_cgroup_hierarchy_read,
2156         },
2157         {
2158                 .name = "swappiness",
2159                 .read_u64 = mem_cgroup_swappiness_read,
2160                 .write_u64 = mem_cgroup_swappiness_write,
2161         },
2162 };
2163
2164 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
2165 static struct cftype memsw_cgroup_files[] = {
2166         {
2167                 .name = "memsw.usage_in_bytes",
2168                 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
2169                 .read_u64 = mem_cgroup_read,
2170         },
2171         {
2172                 .name = "memsw.max_usage_in_bytes",
2173                 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
2174                 .trigger = mem_cgroup_reset,
2175                 .read_u64 = mem_cgroup_read,
2176         },
2177         {
2178                 .name = "memsw.limit_in_bytes",
2179                 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
2180                 .write_string = mem_cgroup_write,
2181                 .read_u64 = mem_cgroup_read,
2182         },
2183         {
2184                 .name = "memsw.failcnt",
2185                 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
2186                 .trigger = mem_cgroup_reset,
2187                 .read_u64 = mem_cgroup_read,
2188         },
2189 };
2190
2191 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
2192 {
2193         if (!do_swap_account)
2194                 return 0;
2195         return cgroup_add_files(cont, ss, memsw_cgroup_files,
2196                                 ARRAY_SIZE(memsw_cgroup_files));
2197 };
2198 #else
2199 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
2200 {
2201         return 0;
2202 }
2203 #endif
2204
2205 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
2206 {
2207         struct mem_cgroup_per_node *pn;
2208         struct mem_cgroup_per_zone *mz;
2209         enum lru_list l;
2210         int zone, tmp = node;
2211         /*
2212          * This routine is called against possible nodes.
2213          * But it's BUG to call kmalloc() against offline node.
2214          *
2215          * TODO: this routine can waste much memory for nodes which will
2216          *       never be onlined. It's better to use memory hotplug callback
2217          *       function.
2218          */
2219         if (!node_state(node, N_NORMAL_MEMORY))
2220                 tmp = -1;
2221         pn = kmalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
2222         if (!pn)
2223                 return 1;
2224
2225         mem->info.nodeinfo[node] = pn;
2226         memset(pn, 0, sizeof(*pn));
2227
2228         for (zone = 0; zone < MAX_NR_ZONES; zone++) {
2229                 mz = &pn->zoneinfo[zone];
2230                 for_each_lru(l)
2231                         INIT_LIST_HEAD(&mz->lists[l]);
2232         }
2233         return 0;
2234 }
2235
2236 static void free_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
2237 {
2238         kfree(mem->info.nodeinfo[node]);
2239 }
2240
2241 static int mem_cgroup_size(void)
2242 {
2243         int cpustat_size = nr_cpu_ids * sizeof(struct mem_cgroup_stat_cpu);
2244         return sizeof(struct mem_cgroup) + cpustat_size;
2245 }
2246
2247 static struct mem_cgroup *mem_cgroup_alloc(void)
2248 {
2249         struct mem_cgroup *mem;
2250         int size = mem_cgroup_size();
2251
2252         if (size < PAGE_SIZE)
2253                 mem = kmalloc(size, GFP_KERNEL);
2254         else
2255                 mem = vmalloc(size);
2256
2257         if (mem)
2258                 memset(mem, 0, size);
2259         return mem;
2260 }
2261
2262 /*
2263  * At destroying mem_cgroup, references from swap_cgroup can remain.
2264  * (scanning all at force_empty is too costly...)
2265  *
2266  * Instead of clearing all references at force_empty, we remember
2267  * the number of reference from swap_cgroup and free mem_cgroup when
2268  * it goes down to 0.
2269  *
2270  * Removal of cgroup itself succeeds regardless of refs from swap.
2271  */
2272
2273 static void __mem_cgroup_free(struct mem_cgroup *mem)
2274 {
2275         int node;
2276
2277         free_css_id(&mem_cgroup_subsys, &mem->css);
2278
2279         for_each_node_state(node, N_POSSIBLE)
2280                 free_mem_cgroup_per_zone_info(mem, node);
2281
2282         if (mem_cgroup_size() < PAGE_SIZE)
2283                 kfree(mem);
2284         else
2285                 vfree(mem);
2286 }
2287
2288 static void mem_cgroup_get(struct mem_cgroup *mem)
2289 {
2290         atomic_inc(&mem->refcnt);
2291 }
2292
2293 static void mem_cgroup_put(struct mem_cgroup *mem)
2294 {
2295         if (atomic_dec_and_test(&mem->refcnt)) {
2296                 struct mem_cgroup *parent = parent_mem_cgroup(mem);
2297                 __mem_cgroup_free(mem);
2298                 if (parent)
2299                         mem_cgroup_put(parent);
2300         }
2301 }
2302
2303 /*
2304  * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
2305  */
2306 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem)
2307 {
2308         if (!mem->res.parent)
2309                 return NULL;
2310         return mem_cgroup_from_res_counter(mem->res.parent, res);
2311 }
2312
2313 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
2314 static void __init enable_swap_cgroup(void)
2315 {
2316         if (!mem_cgroup_disabled() && really_do_swap_account)
2317                 do_swap_account = 1;
2318 }
2319 #else
2320 static void __init enable_swap_cgroup(void)
2321 {
2322 }
2323 #endif
2324
2325 static struct cgroup_subsys_state * __ref
2326 mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
2327 {
2328         struct mem_cgroup *mem, *parent;
2329         long error = -ENOMEM;
2330         int node;
2331
2332         mem = mem_cgroup_alloc();
2333         if (!mem)
2334                 return ERR_PTR(error);
2335
2336         for_each_node_state(node, N_POSSIBLE)
2337                 if (alloc_mem_cgroup_per_zone_info(mem, node))
2338                         goto free_out;
2339         /* root ? */
2340         if (cont->parent == NULL) {
2341                 enable_swap_cgroup();
2342                 parent = NULL;
2343         } else {
2344                 parent = mem_cgroup_from_cont(cont->parent);
2345                 mem->use_hierarchy = parent->use_hierarchy;
2346         }
2347
2348         if (parent && parent->use_hierarchy) {
2349                 res_counter_init(&mem->res, &parent->res);
2350                 res_counter_init(&mem->memsw, &parent->memsw);
2351                 /*
2352                  * We increment refcnt of the parent to ensure that we can
2353                  * safely access it on res_counter_charge/uncharge.
2354                  * This refcnt will be decremented when freeing this
2355                  * mem_cgroup(see mem_cgroup_put).
2356                  */
2357                 mem_cgroup_get(parent);
2358         } else {
2359                 res_counter_init(&mem->res, NULL);
2360                 res_counter_init(&mem->memsw, NULL);
2361         }
2362         mem->last_scanned_child = 0;
2363         spin_lock_init(&mem->reclaim_param_lock);
2364
2365         if (parent)
2366                 mem->swappiness = get_swappiness(parent);
2367         atomic_set(&mem->refcnt, 1);
2368         return &mem->css;
2369 free_out:
2370         __mem_cgroup_free(mem);
2371         return ERR_PTR(error);
2372 }
2373
2374 static int mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
2375                                         struct cgroup *cont)
2376 {
2377         struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
2378
2379         return mem_cgroup_force_empty(mem, false);
2380 }
2381
2382 static void mem_cgroup_destroy(struct cgroup_subsys *ss,
2383                                 struct cgroup *cont)
2384 {
2385         struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
2386
2387         mem_cgroup_put(mem);
2388 }
2389
2390 static int mem_cgroup_populate(struct cgroup_subsys *ss,
2391                                 struct cgroup *cont)
2392 {
2393         int ret;
2394
2395         ret = cgroup_add_files(cont, ss, mem_cgroup_files,
2396                                 ARRAY_SIZE(mem_cgroup_files));
2397
2398         if (!ret)
2399                 ret = register_memsw_files(cont, ss);
2400         return ret;
2401 }
2402
2403 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
2404                                 struct cgroup *cont,
2405                                 struct cgroup *old_cont,
2406                                 struct task_struct *p)
2407 {
2408         mutex_lock(&memcg_tasklist);
2409         /*
2410          * FIXME: It's better to move charges of this process from old
2411          * memcg to new memcg. But it's just on TODO-List now.
2412          */
2413         mutex_unlock(&memcg_tasklist);
2414 }
2415
2416 struct cgroup_subsys mem_cgroup_subsys = {
2417         .name = "memory",
2418         .subsys_id = mem_cgroup_subsys_id,
2419         .create = mem_cgroup_create,
2420         .pre_destroy = mem_cgroup_pre_destroy,
2421         .destroy = mem_cgroup_destroy,
2422         .populate = mem_cgroup_populate,
2423         .attach = mem_cgroup_move_task,
2424         .early_init = 0,
2425         .use_id = 1,
2426 };
2427
2428 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
2429
2430 static int __init disable_swap_account(char *s)
2431 {
2432         really_do_swap_account = 0;
2433         return 1;
2434 }
2435 __setup("noswapaccount", disable_swap_account);
2436 #endif