memcg: memory cgroup hierarchical reclaim
[safe/jmp/linux-2.6] / 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
55 /*
56  * Statistics for memory cgroup.
57  */
58 enum mem_cgroup_stat_index {
59         /*
60          * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
61          */
62         MEM_CGROUP_STAT_CACHE,     /* # of pages charged as cache */
63         MEM_CGROUP_STAT_RSS,       /* # of pages charged as rss */
64         MEM_CGROUP_STAT_PGPGIN_COUNT,   /* # of pages paged in */
65         MEM_CGROUP_STAT_PGPGOUT_COUNT,  /* # of pages paged out */
66
67         MEM_CGROUP_STAT_NSTATS,
68 };
69
70 struct mem_cgroup_stat_cpu {
71         s64 count[MEM_CGROUP_STAT_NSTATS];
72 } ____cacheline_aligned_in_smp;
73
74 struct mem_cgroup_stat {
75         struct mem_cgroup_stat_cpu cpustat[0];
76 };
77
78 /*
79  * For accounting under irq disable, no need for increment preempt count.
80  */
81 static inline void __mem_cgroup_stat_add_safe(struct mem_cgroup_stat_cpu *stat,
82                 enum mem_cgroup_stat_index idx, int val)
83 {
84         stat->count[idx] += val;
85 }
86
87 static s64 mem_cgroup_read_stat(struct mem_cgroup_stat *stat,
88                 enum mem_cgroup_stat_index idx)
89 {
90         int cpu;
91         s64 ret = 0;
92         for_each_possible_cpu(cpu)
93                 ret += stat->cpustat[cpu].count[idx];
94         return ret;
95 }
96
97 /*
98  * per-zone information in memory controller.
99  */
100 struct mem_cgroup_per_zone {
101         /*
102          * spin_lock to protect the per cgroup LRU
103          */
104         struct list_head        lists[NR_LRU_LISTS];
105         unsigned long           count[NR_LRU_LISTS];
106 };
107 /* Macro for accessing counter */
108 #define MEM_CGROUP_ZSTAT(mz, idx)       ((mz)->count[(idx)])
109
110 struct mem_cgroup_per_node {
111         struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
112 };
113
114 struct mem_cgroup_lru_info {
115         struct mem_cgroup_per_node *nodeinfo[MAX_NUMNODES];
116 };
117
118 /*
119  * The memory controller data structure. The memory controller controls both
120  * page cache and RSS per cgroup. We would eventually like to provide
121  * statistics based on the statistics developed by Rik Van Riel for clock-pro,
122  * to help the administrator determine what knobs to tune.
123  *
124  * TODO: Add a water mark for the memory controller. Reclaim will begin when
125  * we hit the water mark. May be even add a low water mark, such that
126  * no reclaim occurs from a cgroup at it's low water mark, this is
127  * a feature that will be implemented much later in the future.
128  */
129 struct mem_cgroup {
130         struct cgroup_subsys_state css;
131         /*
132          * the counter to account for memory usage
133          */
134         struct res_counter res;
135         /*
136          * the counter to account for mem+swap usage.
137          */
138         struct res_counter memsw;
139         /*
140          * Per cgroup active and inactive list, similar to the
141          * per zone LRU lists.
142          */
143         struct mem_cgroup_lru_info info;
144
145         int     prev_priority;  /* for recording reclaim priority */
146
147         /*
148          * While reclaiming in a hiearchy, we cache the last child we
149          * reclaimed from. Protected by cgroup_lock()
150          */
151         struct mem_cgroup *last_scanned_child;
152
153         int             obsolete;
154         atomic_t        refcnt;
155         /*
156          * statistics. This must be placed at the end of memcg.
157          */
158         struct mem_cgroup_stat stat;
159 };
160
161 enum charge_type {
162         MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
163         MEM_CGROUP_CHARGE_TYPE_MAPPED,
164         MEM_CGROUP_CHARGE_TYPE_SHMEM,   /* used by page migration of shmem */
165         MEM_CGROUP_CHARGE_TYPE_FORCE,   /* used by force_empty */
166         MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
167         NR_CHARGE_TYPE,
168 };
169
170 /* only for here (for easy reading.) */
171 #define PCGF_CACHE      (1UL << PCG_CACHE)
172 #define PCGF_USED       (1UL << PCG_USED)
173 #define PCGF_LOCK       (1UL << PCG_LOCK)
174 static const unsigned long
175 pcg_default_flags[NR_CHARGE_TYPE] = {
176         PCGF_CACHE | PCGF_USED | PCGF_LOCK, /* File Cache */
177         PCGF_USED | PCGF_LOCK, /* Anon */
178         PCGF_CACHE | PCGF_USED | PCGF_LOCK, /* Shmem */
179         0, /* FORCE */
180 };
181
182
183 /* for encoding cft->private value on file */
184 #define _MEM                    (0)
185 #define _MEMSWAP                (1)
186 #define MEMFILE_PRIVATE(x, val) (((x) << 16) | (val))
187 #define MEMFILE_TYPE(val)       (((val) >> 16) & 0xffff)
188 #define MEMFILE_ATTR(val)       ((val) & 0xffff)
189
190 static void mem_cgroup_get(struct mem_cgroup *mem);
191 static void mem_cgroup_put(struct mem_cgroup *mem);
192
193 static void mem_cgroup_charge_statistics(struct mem_cgroup *mem,
194                                          struct page_cgroup *pc,
195                                          bool charge)
196 {
197         int val = (charge)? 1 : -1;
198         struct mem_cgroup_stat *stat = &mem->stat;
199         struct mem_cgroup_stat_cpu *cpustat;
200         int cpu = get_cpu();
201
202         cpustat = &stat->cpustat[cpu];
203         if (PageCgroupCache(pc))
204                 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_CACHE, val);
205         else
206                 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_RSS, val);
207
208         if (charge)
209                 __mem_cgroup_stat_add_safe(cpustat,
210                                 MEM_CGROUP_STAT_PGPGIN_COUNT, 1);
211         else
212                 __mem_cgroup_stat_add_safe(cpustat,
213                                 MEM_CGROUP_STAT_PGPGOUT_COUNT, 1);
214         put_cpu();
215 }
216
217 static struct mem_cgroup_per_zone *
218 mem_cgroup_zoneinfo(struct mem_cgroup *mem, int nid, int zid)
219 {
220         return &mem->info.nodeinfo[nid]->zoneinfo[zid];
221 }
222
223 static struct mem_cgroup_per_zone *
224 page_cgroup_zoneinfo(struct page_cgroup *pc)
225 {
226         struct mem_cgroup *mem = pc->mem_cgroup;
227         int nid = page_cgroup_nid(pc);
228         int zid = page_cgroup_zid(pc);
229
230         return mem_cgroup_zoneinfo(mem, nid, zid);
231 }
232
233 static unsigned long mem_cgroup_get_all_zonestat(struct mem_cgroup *mem,
234                                         enum lru_list idx)
235 {
236         int nid, zid;
237         struct mem_cgroup_per_zone *mz;
238         u64 total = 0;
239
240         for_each_online_node(nid)
241                 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
242                         mz = mem_cgroup_zoneinfo(mem, nid, zid);
243                         total += MEM_CGROUP_ZSTAT(mz, idx);
244                 }
245         return total;
246 }
247
248 static struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
249 {
250         return container_of(cgroup_subsys_state(cont,
251                                 mem_cgroup_subsys_id), struct mem_cgroup,
252                                 css);
253 }
254
255 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
256 {
257         /*
258          * mm_update_next_owner() may clear mm->owner to NULL
259          * if it races with swapoff, page migration, etc.
260          * So this can be called with p == NULL.
261          */
262         if (unlikely(!p))
263                 return NULL;
264
265         return container_of(task_subsys_state(p, mem_cgroup_subsys_id),
266                                 struct mem_cgroup, css);
267 }
268
269 /*
270  * Following LRU functions are allowed to be used without PCG_LOCK.
271  * Operations are called by routine of global LRU independently from memcg.
272  * What we have to take care of here is validness of pc->mem_cgroup.
273  *
274  * Changes to pc->mem_cgroup happens when
275  * 1. charge
276  * 2. moving account
277  * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
278  * It is added to LRU before charge.
279  * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
280  * When moving account, the page is not on LRU. It's isolated.
281  */
282
283 void mem_cgroup_del_lru_list(struct page *page, enum lru_list lru)
284 {
285         struct page_cgroup *pc;
286         struct mem_cgroup *mem;
287         struct mem_cgroup_per_zone *mz;
288
289         if (mem_cgroup_disabled())
290                 return;
291         pc = lookup_page_cgroup(page);
292         /* can happen while we handle swapcache. */
293         if (list_empty(&pc->lru))
294                 return;
295         mz = page_cgroup_zoneinfo(pc);
296         mem = pc->mem_cgroup;
297         MEM_CGROUP_ZSTAT(mz, lru) -= 1;
298         list_del_init(&pc->lru);
299         return;
300 }
301
302 void mem_cgroup_del_lru(struct page *page)
303 {
304         mem_cgroup_del_lru_list(page, page_lru(page));
305 }
306
307 void mem_cgroup_rotate_lru_list(struct page *page, enum lru_list lru)
308 {
309         struct mem_cgroup_per_zone *mz;
310         struct page_cgroup *pc;
311
312         if (mem_cgroup_disabled())
313                 return;
314
315         pc = lookup_page_cgroup(page);
316         smp_rmb();
317         /* unused page is not rotated. */
318         if (!PageCgroupUsed(pc))
319                 return;
320         mz = page_cgroup_zoneinfo(pc);
321         list_move(&pc->lru, &mz->lists[lru]);
322 }
323
324 void mem_cgroup_add_lru_list(struct page *page, enum lru_list lru)
325 {
326         struct page_cgroup *pc;
327         struct mem_cgroup_per_zone *mz;
328
329         if (mem_cgroup_disabled())
330                 return;
331         pc = lookup_page_cgroup(page);
332         /* barrier to sync with "charge" */
333         smp_rmb();
334         if (!PageCgroupUsed(pc))
335                 return;
336
337         mz = page_cgroup_zoneinfo(pc);
338         MEM_CGROUP_ZSTAT(mz, lru) += 1;
339         list_add(&pc->lru, &mz->lists[lru]);
340 }
341 /*
342  * To add swapcache into LRU. Be careful to all this function.
343  * zone->lru_lock shouldn't be held and irq must not be disabled.
344  */
345 static void mem_cgroup_lru_fixup(struct page *page)
346 {
347         if (!isolate_lru_page(page))
348                 putback_lru_page(page);
349 }
350
351 void mem_cgroup_move_lists(struct page *page,
352                            enum lru_list from, enum lru_list to)
353 {
354         if (mem_cgroup_disabled())
355                 return;
356         mem_cgroup_del_lru_list(page, from);
357         mem_cgroup_add_lru_list(page, to);
358 }
359
360 int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *mem)
361 {
362         int ret;
363
364         task_lock(task);
365         ret = task->mm && mm_match_cgroup(task->mm, mem);
366         task_unlock(task);
367         return ret;
368 }
369
370 /*
371  * Calculate mapped_ratio under memory controller. This will be used in
372  * vmscan.c for deteremining we have to reclaim mapped pages.
373  */
374 int mem_cgroup_calc_mapped_ratio(struct mem_cgroup *mem)
375 {
376         long total, rss;
377
378         /*
379          * usage is recorded in bytes. But, here, we assume the number of
380          * physical pages can be represented by "long" on any arch.
381          */
382         total = (long) (mem->res.usage >> PAGE_SHIFT) + 1L;
383         rss = (long)mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_RSS);
384         return (int)((rss * 100L) / total);
385 }
386
387 /*
388  * prev_priority control...this will be used in memory reclaim path.
389  */
390 int mem_cgroup_get_reclaim_priority(struct mem_cgroup *mem)
391 {
392         return mem->prev_priority;
393 }
394
395 void mem_cgroup_note_reclaim_priority(struct mem_cgroup *mem, int priority)
396 {
397         if (priority < mem->prev_priority)
398                 mem->prev_priority = priority;
399 }
400
401 void mem_cgroup_record_reclaim_priority(struct mem_cgroup *mem, int priority)
402 {
403         mem->prev_priority = priority;
404 }
405
406 /*
407  * Calculate # of pages to be scanned in this priority/zone.
408  * See also vmscan.c
409  *
410  * priority starts from "DEF_PRIORITY" and decremented in each loop.
411  * (see include/linux/mmzone.h)
412  */
413
414 long mem_cgroup_calc_reclaim(struct mem_cgroup *mem, struct zone *zone,
415                                         int priority, enum lru_list lru)
416 {
417         long nr_pages;
418         int nid = zone->zone_pgdat->node_id;
419         int zid = zone_idx(zone);
420         struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(mem, nid, zid);
421
422         nr_pages = MEM_CGROUP_ZSTAT(mz, lru);
423
424         return (nr_pages >> priority);
425 }
426
427 unsigned long mem_cgroup_isolate_pages(unsigned long nr_to_scan,
428                                         struct list_head *dst,
429                                         unsigned long *scanned, int order,
430                                         int mode, struct zone *z,
431                                         struct mem_cgroup *mem_cont,
432                                         int active, int file)
433 {
434         unsigned long nr_taken = 0;
435         struct page *page;
436         unsigned long scan;
437         LIST_HEAD(pc_list);
438         struct list_head *src;
439         struct page_cgroup *pc, *tmp;
440         int nid = z->zone_pgdat->node_id;
441         int zid = zone_idx(z);
442         struct mem_cgroup_per_zone *mz;
443         int lru = LRU_FILE * !!file + !!active;
444
445         BUG_ON(!mem_cont);
446         mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
447         src = &mz->lists[lru];
448
449         scan = 0;
450         list_for_each_entry_safe_reverse(pc, tmp, src, lru) {
451                 if (scan >= nr_to_scan)
452                         break;
453
454                 page = pc->page;
455                 if (unlikely(!PageCgroupUsed(pc)))
456                         continue;
457                 if (unlikely(!PageLRU(page)))
458                         continue;
459
460                 scan++;
461                 if (__isolate_lru_page(page, mode, file) == 0) {
462                         list_move(&page->lru, dst);
463                         nr_taken++;
464                 }
465         }
466
467         *scanned = scan;
468         return nr_taken;
469 }
470
471 #define mem_cgroup_from_res_counter(counter, member)    \
472         container_of(counter, struct mem_cgroup, member)
473
474 /*
475  * This routine finds the DFS walk successor. This routine should be
476  * called with cgroup_mutex held
477  */
478 static struct mem_cgroup *
479 mem_cgroup_get_next_node(struct mem_cgroup *curr, struct mem_cgroup *root_mem)
480 {
481         struct cgroup *cgroup, *curr_cgroup, *root_cgroup;
482
483         curr_cgroup = curr->css.cgroup;
484         root_cgroup = root_mem->css.cgroup;
485
486         if (!list_empty(&curr_cgroup->children)) {
487                 /*
488                  * Walk down to children
489                  */
490                 mem_cgroup_put(curr);
491                 cgroup = list_entry(curr_cgroup->children.next,
492                                                 struct cgroup, sibling);
493                 curr = mem_cgroup_from_cont(cgroup);
494                 mem_cgroup_get(curr);
495                 goto done;
496         }
497
498 visit_parent:
499         if (curr_cgroup == root_cgroup) {
500                 mem_cgroup_put(curr);
501                 curr = root_mem;
502                 mem_cgroup_get(curr);
503                 goto done;
504         }
505
506         /*
507          * Goto next sibling
508          */
509         if (curr_cgroup->sibling.next != &curr_cgroup->parent->children) {
510                 mem_cgroup_put(curr);
511                 cgroup = list_entry(curr_cgroup->sibling.next, struct cgroup,
512                                                 sibling);
513                 curr = mem_cgroup_from_cont(cgroup);
514                 mem_cgroup_get(curr);
515                 goto done;
516         }
517
518         /*
519          * Go up to next parent and next parent's sibling if need be
520          */
521         curr_cgroup = curr_cgroup->parent;
522         goto visit_parent;
523
524 done:
525         root_mem->last_scanned_child = curr;
526         return curr;
527 }
528
529 /*
530  * Visit the first child (need not be the first child as per the ordering
531  * of the cgroup list, since we track last_scanned_child) of @mem and use
532  * that to reclaim free pages from.
533  */
534 static struct mem_cgroup *
535 mem_cgroup_get_first_node(struct mem_cgroup *root_mem)
536 {
537         struct cgroup *cgroup;
538         struct mem_cgroup *ret;
539         bool obsolete = (root_mem->last_scanned_child &&
540                                 root_mem->last_scanned_child->obsolete);
541
542         /*
543          * Scan all children under the mem_cgroup mem
544          */
545         cgroup_lock();
546         if (list_empty(&root_mem->css.cgroup->children)) {
547                 ret = root_mem;
548                 goto done;
549         }
550
551         if (!root_mem->last_scanned_child || obsolete) {
552
553                 if (obsolete)
554                         mem_cgroup_put(root_mem->last_scanned_child);
555
556                 cgroup = list_first_entry(&root_mem->css.cgroup->children,
557                                 struct cgroup, sibling);
558                 ret = mem_cgroup_from_cont(cgroup);
559                 mem_cgroup_get(ret);
560         } else
561                 ret = mem_cgroup_get_next_node(root_mem->last_scanned_child,
562                                                 root_mem);
563
564 done:
565         root_mem->last_scanned_child = ret;
566         cgroup_unlock();
567         return ret;
568 }
569
570 /*
571  * Dance down the hierarchy if needed to reclaim memory. We remember the
572  * last child we reclaimed from, so that we don't end up penalizing
573  * one child extensively based on its position in the children list.
574  *
575  * root_mem is the original ancestor that we've been reclaim from.
576  */
577 static int mem_cgroup_hierarchical_reclaim(struct mem_cgroup *root_mem,
578                                                 gfp_t gfp_mask, bool noswap)
579 {
580         struct mem_cgroup *next_mem;
581         int ret = 0;
582
583         /*
584          * Reclaim unconditionally and don't check for return value.
585          * We need to reclaim in the current group and down the tree.
586          * One might think about checking for children before reclaiming,
587          * but there might be left over accounting, even after children
588          * have left.
589          */
590         ret = try_to_free_mem_cgroup_pages(root_mem, gfp_mask, noswap);
591         if (res_counter_check_under_limit(&root_mem->res))
592                 return 0;
593
594         next_mem = mem_cgroup_get_first_node(root_mem);
595
596         while (next_mem != root_mem) {
597                 if (next_mem->obsolete) {
598                         mem_cgroup_put(next_mem);
599                         cgroup_lock();
600                         next_mem = mem_cgroup_get_first_node(root_mem);
601                         cgroup_unlock();
602                         continue;
603                 }
604                 ret = try_to_free_mem_cgroup_pages(next_mem, gfp_mask, noswap);
605                 if (res_counter_check_under_limit(&root_mem->res))
606                         return 0;
607                 cgroup_lock();
608                 next_mem = mem_cgroup_get_next_node(next_mem, root_mem);
609                 cgroup_unlock();
610         }
611         return ret;
612 }
613
614 /*
615  * Unlike exported interface, "oom" parameter is added. if oom==true,
616  * oom-killer can be invoked.
617  */
618 static int __mem_cgroup_try_charge(struct mm_struct *mm,
619                         gfp_t gfp_mask, struct mem_cgroup **memcg,
620                         bool oom)
621 {
622         struct mem_cgroup *mem, *mem_over_limit;
623         int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
624         struct res_counter *fail_res;
625         /*
626          * We always charge the cgroup the mm_struct belongs to.
627          * The mm_struct's mem_cgroup changes on task migration if the
628          * thread group leader migrates. It's possible that mm is not
629          * set, if so charge the init_mm (happens for pagecache usage).
630          */
631         if (likely(!*memcg)) {
632                 rcu_read_lock();
633                 mem = mem_cgroup_from_task(rcu_dereference(mm->owner));
634                 if (unlikely(!mem)) {
635                         rcu_read_unlock();
636                         return 0;
637                 }
638                 /*
639                  * For every charge from the cgroup, increment reference count
640                  */
641                 css_get(&mem->css);
642                 *memcg = mem;
643                 rcu_read_unlock();
644         } else {
645                 mem = *memcg;
646                 css_get(&mem->css);
647         }
648
649         while (1) {
650                 int ret;
651                 bool noswap = false;
652
653                 ret = res_counter_charge(&mem->res, PAGE_SIZE, &fail_res);
654                 if (likely(!ret)) {
655                         if (!do_swap_account)
656                                 break;
657                         ret = res_counter_charge(&mem->memsw, PAGE_SIZE,
658                                                         &fail_res);
659                         if (likely(!ret))
660                                 break;
661                         /* mem+swap counter fails */
662                         res_counter_uncharge(&mem->res, PAGE_SIZE);
663                         noswap = true;
664                         mem_over_limit = mem_cgroup_from_res_counter(fail_res,
665                                                                         memsw);
666                 } else
667                         /* mem counter fails */
668                         mem_over_limit = mem_cgroup_from_res_counter(fail_res,
669                                                                         res);
670
671                 if (!(gfp_mask & __GFP_WAIT))
672                         goto nomem;
673
674                 ret = mem_cgroup_hierarchical_reclaim(mem_over_limit, gfp_mask,
675                                                         noswap);
676
677                 /*
678                  * try_to_free_mem_cgroup_pages() might not give us a full
679                  * picture of reclaim. Some pages are reclaimed and might be
680                  * moved to swap cache or just unmapped from the cgroup.
681                  * Check the limit again to see if the reclaim reduced the
682                  * current usage of the cgroup before giving up
683                  *
684                  */
685                 if (!do_swap_account &&
686                         res_counter_check_under_limit(&mem->res))
687                         continue;
688                 if (do_swap_account &&
689                         res_counter_check_under_limit(&mem->memsw))
690                         continue;
691
692                 if (!nr_retries--) {
693                         if (oom)
694                                 mem_cgroup_out_of_memory(mem, gfp_mask);
695                         goto nomem;
696                 }
697         }
698         return 0;
699 nomem:
700         css_put(&mem->css);
701         return -ENOMEM;
702 }
703
704 /**
705  * mem_cgroup_try_charge - get charge of PAGE_SIZE.
706  * @mm: an mm_struct which is charged against. (when *memcg is NULL)
707  * @gfp_mask: gfp_mask for reclaim.
708  * @memcg: a pointer to memory cgroup which is charged against.
709  *
710  * charge against memory cgroup pointed by *memcg. if *memcg == NULL, estimated
711  * memory cgroup from @mm is got and stored in *memcg.
712  *
713  * Returns 0 if success. -ENOMEM at failure.
714  * This call can invoke OOM-Killer.
715  */
716
717 int mem_cgroup_try_charge(struct mm_struct *mm,
718                           gfp_t mask, struct mem_cgroup **memcg)
719 {
720         return __mem_cgroup_try_charge(mm, mask, memcg, true);
721 }
722
723 /*
724  * commit a charge got by mem_cgroup_try_charge() and makes page_cgroup to be
725  * USED state. If already USED, uncharge and return.
726  */
727
728 static void __mem_cgroup_commit_charge(struct mem_cgroup *mem,
729                                      struct page_cgroup *pc,
730                                      enum charge_type ctype)
731 {
732         /* try_charge() can return NULL to *memcg, taking care of it. */
733         if (!mem)
734                 return;
735
736         lock_page_cgroup(pc);
737         if (unlikely(PageCgroupUsed(pc))) {
738                 unlock_page_cgroup(pc);
739                 res_counter_uncharge(&mem->res, PAGE_SIZE);
740                 if (do_swap_account)
741                         res_counter_uncharge(&mem->memsw, PAGE_SIZE);
742                 css_put(&mem->css);
743                 return;
744         }
745         pc->mem_cgroup = mem;
746         smp_wmb();
747         pc->flags = pcg_default_flags[ctype];
748
749         mem_cgroup_charge_statistics(mem, pc, true);
750
751         unlock_page_cgroup(pc);
752 }
753
754 /**
755  * mem_cgroup_move_account - move account of the page
756  * @pc: page_cgroup of the page.
757  * @from: mem_cgroup which the page is moved from.
758  * @to: mem_cgroup which the page is moved to. @from != @to.
759  *
760  * The caller must confirm following.
761  * - page is not on LRU (isolate_page() is useful.)
762  *
763  * returns 0 at success,
764  * returns -EBUSY when lock is busy or "pc" is unstable.
765  *
766  * This function does "uncharge" from old cgroup but doesn't do "charge" to
767  * new cgroup. It should be done by a caller.
768  */
769
770 static int mem_cgroup_move_account(struct page_cgroup *pc,
771         struct mem_cgroup *from, struct mem_cgroup *to)
772 {
773         struct mem_cgroup_per_zone *from_mz, *to_mz;
774         int nid, zid;
775         int ret = -EBUSY;
776
777         VM_BUG_ON(from == to);
778         VM_BUG_ON(PageLRU(pc->page));
779
780         nid = page_cgroup_nid(pc);
781         zid = page_cgroup_zid(pc);
782         from_mz =  mem_cgroup_zoneinfo(from, nid, zid);
783         to_mz =  mem_cgroup_zoneinfo(to, nid, zid);
784
785         if (!trylock_page_cgroup(pc))
786                 return ret;
787
788         if (!PageCgroupUsed(pc))
789                 goto out;
790
791         if (pc->mem_cgroup != from)
792                 goto out;
793
794         css_put(&from->css);
795         res_counter_uncharge(&from->res, PAGE_SIZE);
796         mem_cgroup_charge_statistics(from, pc, false);
797         if (do_swap_account)
798                 res_counter_uncharge(&from->memsw, PAGE_SIZE);
799         pc->mem_cgroup = to;
800         mem_cgroup_charge_statistics(to, pc, true);
801         css_get(&to->css);
802         ret = 0;
803 out:
804         unlock_page_cgroup(pc);
805         return ret;
806 }
807
808 /*
809  * move charges to its parent.
810  */
811
812 static int mem_cgroup_move_parent(struct page_cgroup *pc,
813                                   struct mem_cgroup *child,
814                                   gfp_t gfp_mask)
815 {
816         struct page *page = pc->page;
817         struct cgroup *cg = child->css.cgroup;
818         struct cgroup *pcg = cg->parent;
819         struct mem_cgroup *parent;
820         int ret;
821
822         /* Is ROOT ? */
823         if (!pcg)
824                 return -EINVAL;
825
826
827         parent = mem_cgroup_from_cont(pcg);
828
829
830         ret = __mem_cgroup_try_charge(NULL, gfp_mask, &parent, false);
831         if (ret)
832                 return ret;
833
834         if (!get_page_unless_zero(page))
835                 return -EBUSY;
836
837         ret = isolate_lru_page(page);
838
839         if (ret)
840                 goto cancel;
841
842         ret = mem_cgroup_move_account(pc, child, parent);
843
844         /* drop extra refcnt by try_charge() (move_account increment one) */
845         css_put(&parent->css);
846         putback_lru_page(page);
847         if (!ret) {
848                 put_page(page);
849                 return 0;
850         }
851         /* uncharge if move fails */
852 cancel:
853         res_counter_uncharge(&parent->res, PAGE_SIZE);
854         if (do_swap_account)
855                 res_counter_uncharge(&parent->memsw, PAGE_SIZE);
856         put_page(page);
857         return ret;
858 }
859
860 /*
861  * Charge the memory controller for page usage.
862  * Return
863  * 0 if the charge was successful
864  * < 0 if the cgroup is over its limit
865  */
866 static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
867                                 gfp_t gfp_mask, enum charge_type ctype,
868                                 struct mem_cgroup *memcg)
869 {
870         struct mem_cgroup *mem;
871         struct page_cgroup *pc;
872         int ret;
873
874         pc = lookup_page_cgroup(page);
875         /* can happen at boot */
876         if (unlikely(!pc))
877                 return 0;
878         prefetchw(pc);
879
880         mem = memcg;
881         ret = __mem_cgroup_try_charge(mm, gfp_mask, &mem, true);
882         if (ret)
883                 return ret;
884
885         __mem_cgroup_commit_charge(mem, pc, ctype);
886         return 0;
887 }
888
889 int mem_cgroup_newpage_charge(struct page *page,
890                               struct mm_struct *mm, gfp_t gfp_mask)
891 {
892         if (mem_cgroup_disabled())
893                 return 0;
894         if (PageCompound(page))
895                 return 0;
896         /*
897          * If already mapped, we don't have to account.
898          * If page cache, page->mapping has address_space.
899          * But page->mapping may have out-of-use anon_vma pointer,
900          * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
901          * is NULL.
902          */
903         if (page_mapped(page) || (page->mapping && !PageAnon(page)))
904                 return 0;
905         if (unlikely(!mm))
906                 mm = &init_mm;
907         return mem_cgroup_charge_common(page, mm, gfp_mask,
908                                 MEM_CGROUP_CHARGE_TYPE_MAPPED, NULL);
909 }
910
911 int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
912                                 gfp_t gfp_mask)
913 {
914         if (mem_cgroup_disabled())
915                 return 0;
916         if (PageCompound(page))
917                 return 0;
918         /*
919          * Corner case handling. This is called from add_to_page_cache()
920          * in usual. But some FS (shmem) precharges this page before calling it
921          * and call add_to_page_cache() with GFP_NOWAIT.
922          *
923          * For GFP_NOWAIT case, the page may be pre-charged before calling
924          * add_to_page_cache(). (See shmem.c) check it here and avoid to call
925          * charge twice. (It works but has to pay a bit larger cost.)
926          */
927         if (!(gfp_mask & __GFP_WAIT)) {
928                 struct page_cgroup *pc;
929
930
931                 pc = lookup_page_cgroup(page);
932                 if (!pc)
933                         return 0;
934                 lock_page_cgroup(pc);
935                 if (PageCgroupUsed(pc)) {
936                         unlock_page_cgroup(pc);
937                         return 0;
938                 }
939                 unlock_page_cgroup(pc);
940         }
941
942         if (unlikely(!mm))
943                 mm = &init_mm;
944
945         if (page_is_file_cache(page))
946                 return mem_cgroup_charge_common(page, mm, gfp_mask,
947                                 MEM_CGROUP_CHARGE_TYPE_CACHE, NULL);
948         else
949                 return mem_cgroup_charge_common(page, mm, gfp_mask,
950                                 MEM_CGROUP_CHARGE_TYPE_SHMEM, NULL);
951 }
952
953 int mem_cgroup_try_charge_swapin(struct mm_struct *mm,
954                                  struct page *page,
955                                  gfp_t mask, struct mem_cgroup **ptr)
956 {
957         struct mem_cgroup *mem;
958         swp_entry_t     ent;
959
960         if (mem_cgroup_disabled())
961                 return 0;
962
963         if (!do_swap_account)
964                 goto charge_cur_mm;
965
966         /*
967          * A racing thread's fault, or swapoff, may have already updated
968          * the pte, and even removed page from swap cache: return success
969          * to go on to do_swap_page()'s pte_same() test, which should fail.
970          */
971         if (!PageSwapCache(page))
972                 return 0;
973
974         ent.val = page_private(page);
975
976         mem = lookup_swap_cgroup(ent);
977         if (!mem || mem->obsolete)
978                 goto charge_cur_mm;
979         *ptr = mem;
980         return __mem_cgroup_try_charge(NULL, mask, ptr, true);
981 charge_cur_mm:
982         if (unlikely(!mm))
983                 mm = &init_mm;
984         return __mem_cgroup_try_charge(mm, mask, ptr, true);
985 }
986
987 #ifdef CONFIG_SWAP
988
989 int mem_cgroup_cache_charge_swapin(struct page *page,
990                         struct mm_struct *mm, gfp_t mask, bool locked)
991 {
992         int ret = 0;
993
994         if (mem_cgroup_disabled())
995                 return 0;
996         if (unlikely(!mm))
997                 mm = &init_mm;
998         if (!locked)
999                 lock_page(page);
1000         /*
1001          * If not locked, the page can be dropped from SwapCache until
1002          * we reach here.
1003          */
1004         if (PageSwapCache(page)) {
1005                 struct mem_cgroup *mem = NULL;
1006                 swp_entry_t ent;
1007
1008                 ent.val = page_private(page);
1009                 if (do_swap_account) {
1010                         mem = lookup_swap_cgroup(ent);
1011                         if (mem && mem->obsolete)
1012                                 mem = NULL;
1013                         if (mem)
1014                                 mm = NULL;
1015                 }
1016                 ret = mem_cgroup_charge_common(page, mm, mask,
1017                                 MEM_CGROUP_CHARGE_TYPE_SHMEM, mem);
1018
1019                 if (!ret && do_swap_account) {
1020                         /* avoid double counting */
1021                         mem = swap_cgroup_record(ent, NULL);
1022                         if (mem) {
1023                                 res_counter_uncharge(&mem->memsw, PAGE_SIZE);
1024                                 mem_cgroup_put(mem);
1025                         }
1026                 }
1027         }
1028         if (!locked)
1029                 unlock_page(page);
1030         /* add this page(page_cgroup) to the LRU we want. */
1031         mem_cgroup_lru_fixup(page);
1032
1033         return ret;
1034 }
1035 #endif
1036
1037 void mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr)
1038 {
1039         struct page_cgroup *pc;
1040
1041         if (mem_cgroup_disabled())
1042                 return;
1043         if (!ptr)
1044                 return;
1045         pc = lookup_page_cgroup(page);
1046         __mem_cgroup_commit_charge(ptr, pc, MEM_CGROUP_CHARGE_TYPE_MAPPED);
1047         /*
1048          * Now swap is on-memory. This means this page may be
1049          * counted both as mem and swap....double count.
1050          * Fix it by uncharging from memsw. This SwapCache is stable
1051          * because we're still under lock_page().
1052          */
1053         if (do_swap_account) {
1054                 swp_entry_t ent = {.val = page_private(page)};
1055                 struct mem_cgroup *memcg;
1056                 memcg = swap_cgroup_record(ent, NULL);
1057                 if (memcg) {
1058                         /* If memcg is obsolete, memcg can be != ptr */
1059                         res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
1060                         mem_cgroup_put(memcg);
1061                 }
1062
1063         }
1064         /* add this page(page_cgroup) to the LRU we want. */
1065         mem_cgroup_lru_fixup(page);
1066 }
1067
1068 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *mem)
1069 {
1070         if (mem_cgroup_disabled())
1071                 return;
1072         if (!mem)
1073                 return;
1074         res_counter_uncharge(&mem->res, PAGE_SIZE);
1075         if (do_swap_account)
1076                 res_counter_uncharge(&mem->memsw, PAGE_SIZE);
1077         css_put(&mem->css);
1078 }
1079
1080
1081 /*
1082  * uncharge if !page_mapped(page)
1083  */
1084 static struct mem_cgroup *
1085 __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype)
1086 {
1087         struct page_cgroup *pc;
1088         struct mem_cgroup *mem = NULL;
1089         struct mem_cgroup_per_zone *mz;
1090
1091         if (mem_cgroup_disabled())
1092                 return NULL;
1093
1094         if (PageSwapCache(page))
1095                 return NULL;
1096
1097         /*
1098          * Check if our page_cgroup is valid
1099          */
1100         pc = lookup_page_cgroup(page);
1101         if (unlikely(!pc || !PageCgroupUsed(pc)))
1102                 return NULL;
1103
1104         lock_page_cgroup(pc);
1105
1106         mem = pc->mem_cgroup;
1107
1108         if (!PageCgroupUsed(pc))
1109                 goto unlock_out;
1110
1111         switch (ctype) {
1112         case MEM_CGROUP_CHARGE_TYPE_MAPPED:
1113                 if (page_mapped(page))
1114                         goto unlock_out;
1115                 break;
1116         case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
1117                 if (!PageAnon(page)) {  /* Shared memory */
1118                         if (page->mapping && !page_is_file_cache(page))
1119                                 goto unlock_out;
1120                 } else if (page_mapped(page)) /* Anon */
1121                                 goto unlock_out;
1122                 break;
1123         default:
1124                 break;
1125         }
1126
1127         res_counter_uncharge(&mem->res, PAGE_SIZE);
1128         if (do_swap_account && (ctype != MEM_CGROUP_CHARGE_TYPE_SWAPOUT))
1129                 res_counter_uncharge(&mem->memsw, PAGE_SIZE);
1130
1131         mem_cgroup_charge_statistics(mem, pc, false);
1132         ClearPageCgroupUsed(pc);
1133
1134         mz = page_cgroup_zoneinfo(pc);
1135         unlock_page_cgroup(pc);
1136
1137         css_put(&mem->css);
1138
1139         return mem;
1140
1141 unlock_out:
1142         unlock_page_cgroup(pc);
1143         return NULL;
1144 }
1145
1146 void mem_cgroup_uncharge_page(struct page *page)
1147 {
1148         /* early check. */
1149         if (page_mapped(page))
1150                 return;
1151         if (page->mapping && !PageAnon(page))
1152                 return;
1153         __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_MAPPED);
1154 }
1155
1156 void mem_cgroup_uncharge_cache_page(struct page *page)
1157 {
1158         VM_BUG_ON(page_mapped(page));
1159         VM_BUG_ON(page->mapping);
1160         __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE);
1161 }
1162
1163 /*
1164  * called from __delete_from_swap_cache() and drop "page" account.
1165  * memcg information is recorded to swap_cgroup of "ent"
1166  */
1167 void mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent)
1168 {
1169         struct mem_cgroup *memcg;
1170
1171         memcg = __mem_cgroup_uncharge_common(page,
1172                                         MEM_CGROUP_CHARGE_TYPE_SWAPOUT);
1173         /* record memcg information */
1174         if (do_swap_account && memcg) {
1175                 swap_cgroup_record(ent, memcg);
1176                 mem_cgroup_get(memcg);
1177         }
1178 }
1179
1180 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
1181 /*
1182  * called from swap_entry_free(). remove record in swap_cgroup and
1183  * uncharge "memsw" account.
1184  */
1185 void mem_cgroup_uncharge_swap(swp_entry_t ent)
1186 {
1187         struct mem_cgroup *memcg;
1188
1189         if (!do_swap_account)
1190                 return;
1191
1192         memcg = swap_cgroup_record(ent, NULL);
1193         if (memcg) {
1194                 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
1195                 mem_cgroup_put(memcg);
1196         }
1197 }
1198 #endif
1199
1200 /*
1201  * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
1202  * page belongs to.
1203  */
1204 int mem_cgroup_prepare_migration(struct page *page, struct mem_cgroup **ptr)
1205 {
1206         struct page_cgroup *pc;
1207         struct mem_cgroup *mem = NULL;
1208         int ret = 0;
1209
1210         if (mem_cgroup_disabled())
1211                 return 0;
1212
1213         pc = lookup_page_cgroup(page);
1214         lock_page_cgroup(pc);
1215         if (PageCgroupUsed(pc)) {
1216                 mem = pc->mem_cgroup;
1217                 css_get(&mem->css);
1218         }
1219         unlock_page_cgroup(pc);
1220
1221         if (mem) {
1222                 ret = mem_cgroup_try_charge(NULL, GFP_HIGHUSER_MOVABLE, &mem);
1223                 css_put(&mem->css);
1224         }
1225         *ptr = mem;
1226         return ret;
1227 }
1228
1229 /* remove redundant charge if migration failed*/
1230 void mem_cgroup_end_migration(struct mem_cgroup *mem,
1231                 struct page *oldpage, struct page *newpage)
1232 {
1233         struct page *target, *unused;
1234         struct page_cgroup *pc;
1235         enum charge_type ctype;
1236
1237         if (!mem)
1238                 return;
1239
1240         /* at migration success, oldpage->mapping is NULL. */
1241         if (oldpage->mapping) {
1242                 target = oldpage;
1243                 unused = NULL;
1244         } else {
1245                 target = newpage;
1246                 unused = oldpage;
1247         }
1248
1249         if (PageAnon(target))
1250                 ctype = MEM_CGROUP_CHARGE_TYPE_MAPPED;
1251         else if (page_is_file_cache(target))
1252                 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
1253         else
1254                 ctype = MEM_CGROUP_CHARGE_TYPE_SHMEM;
1255
1256         /* unused page is not on radix-tree now. */
1257         if (unused)
1258                 __mem_cgroup_uncharge_common(unused, ctype);
1259
1260         pc = lookup_page_cgroup(target);
1261         /*
1262          * __mem_cgroup_commit_charge() check PCG_USED bit of page_cgroup.
1263          * So, double-counting is effectively avoided.
1264          */
1265         __mem_cgroup_commit_charge(mem, pc, ctype);
1266
1267         /*
1268          * Both of oldpage and newpage are still under lock_page().
1269          * Then, we don't have to care about race in radix-tree.
1270          * But we have to be careful that this page is unmapped or not.
1271          *
1272          * There is a case for !page_mapped(). At the start of
1273          * migration, oldpage was mapped. But now, it's zapped.
1274          * But we know *target* page is not freed/reused under us.
1275          * mem_cgroup_uncharge_page() does all necessary checks.
1276          */
1277         if (ctype == MEM_CGROUP_CHARGE_TYPE_MAPPED)
1278                 mem_cgroup_uncharge_page(target);
1279 }
1280
1281 /*
1282  * A call to try to shrink memory usage under specified resource controller.
1283  * This is typically used for page reclaiming for shmem for reducing side
1284  * effect of page allocation from shmem, which is used by some mem_cgroup.
1285  */
1286 int mem_cgroup_shrink_usage(struct mm_struct *mm, gfp_t gfp_mask)
1287 {
1288         struct mem_cgroup *mem;
1289         int progress = 0;
1290         int retry = MEM_CGROUP_RECLAIM_RETRIES;
1291
1292         if (mem_cgroup_disabled())
1293                 return 0;
1294         if (!mm)
1295                 return 0;
1296
1297         rcu_read_lock();
1298         mem = mem_cgroup_from_task(rcu_dereference(mm->owner));
1299         if (unlikely(!mem)) {
1300                 rcu_read_unlock();
1301                 return 0;
1302         }
1303         css_get(&mem->css);
1304         rcu_read_unlock();
1305
1306         do {
1307                 progress = try_to_free_mem_cgroup_pages(mem, gfp_mask, true);
1308                 progress += res_counter_check_under_limit(&mem->res);
1309         } while (!progress && --retry);
1310
1311         css_put(&mem->css);
1312         if (!retry)
1313                 return -ENOMEM;
1314         return 0;
1315 }
1316
1317 static DEFINE_MUTEX(set_limit_mutex);
1318
1319 static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
1320                                 unsigned long long val)
1321 {
1322
1323         int retry_count = MEM_CGROUP_RECLAIM_RETRIES;
1324         int progress;
1325         u64 memswlimit;
1326         int ret = 0;
1327
1328         while (retry_count) {
1329                 if (signal_pending(current)) {
1330                         ret = -EINTR;
1331                         break;
1332                 }
1333                 /*
1334                  * Rather than hide all in some function, I do this in
1335                  * open coded manner. You see what this really does.
1336                  * We have to guarantee mem->res.limit < mem->memsw.limit.
1337                  */
1338                 mutex_lock(&set_limit_mutex);
1339                 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
1340                 if (memswlimit < val) {
1341                         ret = -EINVAL;
1342                         mutex_unlock(&set_limit_mutex);
1343                         break;
1344                 }
1345                 ret = res_counter_set_limit(&memcg->res, val);
1346                 mutex_unlock(&set_limit_mutex);
1347
1348                 if (!ret)
1349                         break;
1350
1351                 progress = try_to_free_mem_cgroup_pages(memcg,
1352                                 GFP_HIGHUSER_MOVABLE, false);
1353                 if (!progress)                  retry_count--;
1354         }
1355         return ret;
1356 }
1357
1358 int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
1359                                 unsigned long long val)
1360 {
1361         int retry_count = MEM_CGROUP_RECLAIM_RETRIES;
1362         u64 memlimit, oldusage, curusage;
1363         int ret;
1364
1365         if (!do_swap_account)
1366                 return -EINVAL;
1367
1368         while (retry_count) {
1369                 if (signal_pending(current)) {
1370                         ret = -EINTR;
1371                         break;
1372                 }
1373                 /*
1374                  * Rather than hide all in some function, I do this in
1375                  * open coded manner. You see what this really does.
1376                  * We have to guarantee mem->res.limit < mem->memsw.limit.
1377                  */
1378                 mutex_lock(&set_limit_mutex);
1379                 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
1380                 if (memlimit > val) {
1381                         ret = -EINVAL;
1382                         mutex_unlock(&set_limit_mutex);
1383                         break;
1384                 }
1385                 ret = res_counter_set_limit(&memcg->memsw, val);
1386                 mutex_unlock(&set_limit_mutex);
1387
1388                 if (!ret)
1389                         break;
1390
1391                 oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
1392                 try_to_free_mem_cgroup_pages(memcg, GFP_HIGHUSER_MOVABLE, true);
1393                 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
1394                 if (curusage >= oldusage)
1395                         retry_count--;
1396         }
1397         return ret;
1398 }
1399
1400 /*
1401  * This routine traverse page_cgroup in given list and drop them all.
1402  * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
1403  */
1404 static int mem_cgroup_force_empty_list(struct mem_cgroup *mem,
1405                                 int node, int zid, enum lru_list lru)
1406 {
1407         struct zone *zone;
1408         struct mem_cgroup_per_zone *mz;
1409         struct page_cgroup *pc, *busy;
1410         unsigned long flags, loop;
1411         struct list_head *list;
1412         int ret = 0;
1413
1414         zone = &NODE_DATA(node)->node_zones[zid];
1415         mz = mem_cgroup_zoneinfo(mem, node, zid);
1416         list = &mz->lists[lru];
1417
1418         loop = MEM_CGROUP_ZSTAT(mz, lru);
1419         /* give some margin against EBUSY etc...*/
1420         loop += 256;
1421         busy = NULL;
1422         while (loop--) {
1423                 ret = 0;
1424                 spin_lock_irqsave(&zone->lru_lock, flags);
1425                 if (list_empty(list)) {
1426                         spin_unlock_irqrestore(&zone->lru_lock, flags);
1427                         break;
1428                 }
1429                 pc = list_entry(list->prev, struct page_cgroup, lru);
1430                 if (busy == pc) {
1431                         list_move(&pc->lru, list);
1432                         busy = 0;
1433                         spin_unlock_irqrestore(&zone->lru_lock, flags);
1434                         continue;
1435                 }
1436                 spin_unlock_irqrestore(&zone->lru_lock, flags);
1437
1438                 ret = mem_cgroup_move_parent(pc, mem, GFP_HIGHUSER_MOVABLE);
1439                 if (ret == -ENOMEM)
1440                         break;
1441
1442                 if (ret == -EBUSY || ret == -EINVAL) {
1443                         /* found lock contention or "pc" is obsolete. */
1444                         busy = pc;
1445                         cond_resched();
1446                 } else
1447                         busy = NULL;
1448         }
1449
1450         if (!ret && !list_empty(list))
1451                 return -EBUSY;
1452         return ret;
1453 }
1454
1455 /*
1456  * make mem_cgroup's charge to be 0 if there is no task.
1457  * This enables deleting this mem_cgroup.
1458  */
1459 static int mem_cgroup_force_empty(struct mem_cgroup *mem, bool free_all)
1460 {
1461         int ret;
1462         int node, zid, shrink;
1463         int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
1464         struct cgroup *cgrp = mem->css.cgroup;
1465
1466         css_get(&mem->css);
1467
1468         shrink = 0;
1469         /* should free all ? */
1470         if (free_all)
1471                 goto try_to_free;
1472 move_account:
1473         while (mem->res.usage > 0) {
1474                 ret = -EBUSY;
1475                 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
1476                         goto out;
1477                 ret = -EINTR;
1478                 if (signal_pending(current))
1479                         goto out;
1480                 /* This is for making all *used* pages to be on LRU. */
1481                 lru_add_drain_all();
1482                 ret = 0;
1483                 for_each_node_state(node, N_POSSIBLE) {
1484                         for (zid = 0; !ret && zid < MAX_NR_ZONES; zid++) {
1485                                 enum lru_list l;
1486                                 for_each_lru(l) {
1487                                         ret = mem_cgroup_force_empty_list(mem,
1488                                                         node, zid, l);
1489                                         if (ret)
1490                                                 break;
1491                                 }
1492                         }
1493                         if (ret)
1494                                 break;
1495                 }
1496                 /* it seems parent cgroup doesn't have enough mem */
1497                 if (ret == -ENOMEM)
1498                         goto try_to_free;
1499                 cond_resched();
1500         }
1501         ret = 0;
1502 out:
1503         css_put(&mem->css);
1504         return ret;
1505
1506 try_to_free:
1507         /* returns EBUSY if there is a task or if we come here twice. */
1508         if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children) || shrink) {
1509                 ret = -EBUSY;
1510                 goto out;
1511         }
1512         /* we call try-to-free pages for make this cgroup empty */
1513         lru_add_drain_all();
1514         /* try to free all pages in this cgroup */
1515         shrink = 1;
1516         while (nr_retries && mem->res.usage > 0) {
1517                 int progress;
1518
1519                 if (signal_pending(current)) {
1520                         ret = -EINTR;
1521                         goto out;
1522                 }
1523                 progress = try_to_free_mem_cgroup_pages(mem,
1524                                                   GFP_HIGHUSER_MOVABLE, false);
1525                 if (!progress) {
1526                         nr_retries--;
1527                         /* maybe some writeback is necessary */
1528                         congestion_wait(WRITE, HZ/10);
1529                 }
1530
1531         }
1532         lru_add_drain();
1533         /* try move_account...there may be some *locked* pages. */
1534         if (mem->res.usage)
1535                 goto move_account;
1536         ret = 0;
1537         goto out;
1538 }
1539
1540 int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
1541 {
1542         return mem_cgroup_force_empty(mem_cgroup_from_cont(cont), true);
1543 }
1544
1545
1546 static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft)
1547 {
1548         struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
1549         u64 val = 0;
1550         int type, name;
1551
1552         type = MEMFILE_TYPE(cft->private);
1553         name = MEMFILE_ATTR(cft->private);
1554         switch (type) {
1555         case _MEM:
1556                 val = res_counter_read_u64(&mem->res, name);
1557                 break;
1558         case _MEMSWAP:
1559                 if (do_swap_account)
1560                         val = res_counter_read_u64(&mem->memsw, name);
1561                 break;
1562         default:
1563                 BUG();
1564                 break;
1565         }
1566         return val;
1567 }
1568 /*
1569  * The user of this function is...
1570  * RES_LIMIT.
1571  */
1572 static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
1573                             const char *buffer)
1574 {
1575         struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
1576         int type, name;
1577         unsigned long long val;
1578         int ret;
1579
1580         type = MEMFILE_TYPE(cft->private);
1581         name = MEMFILE_ATTR(cft->private);
1582         switch (name) {
1583         case RES_LIMIT:
1584                 /* This function does all necessary parse...reuse it */
1585                 ret = res_counter_memparse_write_strategy(buffer, &val);
1586                 if (ret)
1587                         break;
1588                 if (type == _MEM)
1589                         ret = mem_cgroup_resize_limit(memcg, val);
1590                 else
1591                         ret = mem_cgroup_resize_memsw_limit(memcg, val);
1592                 break;
1593         default:
1594                 ret = -EINVAL; /* should be BUG() ? */
1595                 break;
1596         }
1597         return ret;
1598 }
1599
1600 static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
1601 {
1602         struct mem_cgroup *mem;
1603         int type, name;
1604
1605         mem = mem_cgroup_from_cont(cont);
1606         type = MEMFILE_TYPE(event);
1607         name = MEMFILE_ATTR(event);
1608         switch (name) {
1609         case RES_MAX_USAGE:
1610                 if (type == _MEM)
1611                         res_counter_reset_max(&mem->res);
1612                 else
1613                         res_counter_reset_max(&mem->memsw);
1614                 break;
1615         case RES_FAILCNT:
1616                 if (type == _MEM)
1617                         res_counter_reset_failcnt(&mem->res);
1618                 else
1619                         res_counter_reset_failcnt(&mem->memsw);
1620                 break;
1621         }
1622         return 0;
1623 }
1624
1625 static const struct mem_cgroup_stat_desc {
1626         const char *msg;
1627         u64 unit;
1628 } mem_cgroup_stat_desc[] = {
1629         [MEM_CGROUP_STAT_CACHE] = { "cache", PAGE_SIZE, },
1630         [MEM_CGROUP_STAT_RSS] = { "rss", PAGE_SIZE, },
1631         [MEM_CGROUP_STAT_PGPGIN_COUNT] = {"pgpgin", 1, },
1632         [MEM_CGROUP_STAT_PGPGOUT_COUNT] = {"pgpgout", 1, },
1633 };
1634
1635 static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft,
1636                                  struct cgroup_map_cb *cb)
1637 {
1638         struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
1639         struct mem_cgroup_stat *stat = &mem_cont->stat;
1640         int i;
1641
1642         for (i = 0; i < ARRAY_SIZE(stat->cpustat[0].count); i++) {
1643                 s64 val;
1644
1645                 val = mem_cgroup_read_stat(stat, i);
1646                 val *= mem_cgroup_stat_desc[i].unit;
1647                 cb->fill(cb, mem_cgroup_stat_desc[i].msg, val);
1648         }
1649         /* showing # of active pages */
1650         {
1651                 unsigned long active_anon, inactive_anon;
1652                 unsigned long active_file, inactive_file;
1653                 unsigned long unevictable;
1654
1655                 inactive_anon = mem_cgroup_get_all_zonestat(mem_cont,
1656                                                 LRU_INACTIVE_ANON);
1657                 active_anon = mem_cgroup_get_all_zonestat(mem_cont,
1658                                                 LRU_ACTIVE_ANON);
1659                 inactive_file = mem_cgroup_get_all_zonestat(mem_cont,
1660                                                 LRU_INACTIVE_FILE);
1661                 active_file = mem_cgroup_get_all_zonestat(mem_cont,
1662                                                 LRU_ACTIVE_FILE);
1663                 unevictable = mem_cgroup_get_all_zonestat(mem_cont,
1664                                                         LRU_UNEVICTABLE);
1665
1666                 cb->fill(cb, "active_anon", (active_anon) * PAGE_SIZE);
1667                 cb->fill(cb, "inactive_anon", (inactive_anon) * PAGE_SIZE);
1668                 cb->fill(cb, "active_file", (active_file) * PAGE_SIZE);
1669                 cb->fill(cb, "inactive_file", (inactive_file) * PAGE_SIZE);
1670                 cb->fill(cb, "unevictable", unevictable * PAGE_SIZE);
1671
1672         }
1673         return 0;
1674 }
1675
1676
1677 static struct cftype mem_cgroup_files[] = {
1678         {
1679                 .name = "usage_in_bytes",
1680                 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
1681                 .read_u64 = mem_cgroup_read,
1682         },
1683         {
1684                 .name = "max_usage_in_bytes",
1685                 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
1686                 .trigger = mem_cgroup_reset,
1687                 .read_u64 = mem_cgroup_read,
1688         },
1689         {
1690                 .name = "limit_in_bytes",
1691                 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
1692                 .write_string = mem_cgroup_write,
1693                 .read_u64 = mem_cgroup_read,
1694         },
1695         {
1696                 .name = "failcnt",
1697                 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
1698                 .trigger = mem_cgroup_reset,
1699                 .read_u64 = mem_cgroup_read,
1700         },
1701         {
1702                 .name = "stat",
1703                 .read_map = mem_control_stat_show,
1704         },
1705         {
1706                 .name = "force_empty",
1707                 .trigger = mem_cgroup_force_empty_write,
1708         },
1709 };
1710
1711 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
1712 static struct cftype memsw_cgroup_files[] = {
1713         {
1714                 .name = "memsw.usage_in_bytes",
1715                 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
1716                 .read_u64 = mem_cgroup_read,
1717         },
1718         {
1719                 .name = "memsw.max_usage_in_bytes",
1720                 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
1721                 .trigger = mem_cgroup_reset,
1722                 .read_u64 = mem_cgroup_read,
1723         },
1724         {
1725                 .name = "memsw.limit_in_bytes",
1726                 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
1727                 .write_string = mem_cgroup_write,
1728                 .read_u64 = mem_cgroup_read,
1729         },
1730         {
1731                 .name = "memsw.failcnt",
1732                 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
1733                 .trigger = mem_cgroup_reset,
1734                 .read_u64 = mem_cgroup_read,
1735         },
1736 };
1737
1738 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
1739 {
1740         if (!do_swap_account)
1741                 return 0;
1742         return cgroup_add_files(cont, ss, memsw_cgroup_files,
1743                                 ARRAY_SIZE(memsw_cgroup_files));
1744 };
1745 #else
1746 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
1747 {
1748         return 0;
1749 }
1750 #endif
1751
1752 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
1753 {
1754         struct mem_cgroup_per_node *pn;
1755         struct mem_cgroup_per_zone *mz;
1756         enum lru_list l;
1757         int zone, tmp = node;
1758         /*
1759          * This routine is called against possible nodes.
1760          * But it's BUG to call kmalloc() against offline node.
1761          *
1762          * TODO: this routine can waste much memory for nodes which will
1763          *       never be onlined. It's better to use memory hotplug callback
1764          *       function.
1765          */
1766         if (!node_state(node, N_NORMAL_MEMORY))
1767                 tmp = -1;
1768         pn = kmalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
1769         if (!pn)
1770                 return 1;
1771
1772         mem->info.nodeinfo[node] = pn;
1773         memset(pn, 0, sizeof(*pn));
1774
1775         for (zone = 0; zone < MAX_NR_ZONES; zone++) {
1776                 mz = &pn->zoneinfo[zone];
1777                 for_each_lru(l)
1778                         INIT_LIST_HEAD(&mz->lists[l]);
1779         }
1780         return 0;
1781 }
1782
1783 static void free_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
1784 {
1785         kfree(mem->info.nodeinfo[node]);
1786 }
1787
1788 static int mem_cgroup_size(void)
1789 {
1790         int cpustat_size = nr_cpu_ids * sizeof(struct mem_cgroup_stat_cpu);
1791         return sizeof(struct mem_cgroup) + cpustat_size;
1792 }
1793
1794 static struct mem_cgroup *mem_cgroup_alloc(void)
1795 {
1796         struct mem_cgroup *mem;
1797         int size = mem_cgroup_size();
1798
1799         if (size < PAGE_SIZE)
1800                 mem = kmalloc(size, GFP_KERNEL);
1801         else
1802                 mem = vmalloc(size);
1803
1804         if (mem)
1805                 memset(mem, 0, size);
1806         return mem;
1807 }
1808
1809 /*
1810  * At destroying mem_cgroup, references from swap_cgroup can remain.
1811  * (scanning all at force_empty is too costly...)
1812  *
1813  * Instead of clearing all references at force_empty, we remember
1814  * the number of reference from swap_cgroup and free mem_cgroup when
1815  * it goes down to 0.
1816  *
1817  * When mem_cgroup is destroyed, mem->obsolete will be set to 0 and
1818  * entry which points to this memcg will be ignore at swapin.
1819  *
1820  * Removal of cgroup itself succeeds regardless of refs from swap.
1821  */
1822
1823 static void mem_cgroup_free(struct mem_cgroup *mem)
1824 {
1825         int node;
1826
1827         if (atomic_read(&mem->refcnt) > 0)
1828                 return;
1829
1830
1831         for_each_node_state(node, N_POSSIBLE)
1832                 free_mem_cgroup_per_zone_info(mem, node);
1833
1834         if (mem_cgroup_size() < PAGE_SIZE)
1835                 kfree(mem);
1836         else
1837                 vfree(mem);
1838 }
1839
1840 static void mem_cgroup_get(struct mem_cgroup *mem)
1841 {
1842         atomic_inc(&mem->refcnt);
1843 }
1844
1845 static void mem_cgroup_put(struct mem_cgroup *mem)
1846 {
1847         if (atomic_dec_and_test(&mem->refcnt)) {
1848                 if (!mem->obsolete)
1849                         return;
1850                 mem_cgroup_free(mem);
1851         }
1852 }
1853
1854
1855 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
1856 static void __init enable_swap_cgroup(void)
1857 {
1858         if (!mem_cgroup_disabled() && really_do_swap_account)
1859                 do_swap_account = 1;
1860 }
1861 #else
1862 static void __init enable_swap_cgroup(void)
1863 {
1864 }
1865 #endif
1866
1867 static struct cgroup_subsys_state *
1868 mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
1869 {
1870         struct mem_cgroup *mem, *parent;
1871         int node;
1872
1873         mem = mem_cgroup_alloc();
1874         if (!mem)
1875                 return ERR_PTR(-ENOMEM);
1876
1877         for_each_node_state(node, N_POSSIBLE)
1878                 if (alloc_mem_cgroup_per_zone_info(mem, node))
1879                         goto free_out;
1880         /* root ? */
1881         if (cont->parent == NULL) {
1882                 enable_swap_cgroup();
1883                 parent = NULL;
1884         } else
1885                 parent = mem_cgroup_from_cont(cont->parent);
1886
1887         res_counter_init(&mem->res, parent ? &parent->res : NULL);
1888         res_counter_init(&mem->memsw, parent ? &parent->memsw : NULL);
1889
1890
1891         mem->last_scanned_child = NULL;
1892
1893         return &mem->css;
1894 free_out:
1895         for_each_node_state(node, N_POSSIBLE)
1896                 free_mem_cgroup_per_zone_info(mem, node);
1897         mem_cgroup_free(mem);
1898         return ERR_PTR(-ENOMEM);
1899 }
1900
1901 static void mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
1902                                         struct cgroup *cont)
1903 {
1904         struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
1905         mem->obsolete = 1;
1906         mem_cgroup_force_empty(mem, false);
1907 }
1908
1909 static void mem_cgroup_destroy(struct cgroup_subsys *ss,
1910                                 struct cgroup *cont)
1911 {
1912         mem_cgroup_free(mem_cgroup_from_cont(cont));
1913 }
1914
1915 static int mem_cgroup_populate(struct cgroup_subsys *ss,
1916                                 struct cgroup *cont)
1917 {
1918         int ret;
1919
1920         ret = cgroup_add_files(cont, ss, mem_cgroup_files,
1921                                 ARRAY_SIZE(mem_cgroup_files));
1922
1923         if (!ret)
1924                 ret = register_memsw_files(cont, ss);
1925         return ret;
1926 }
1927
1928 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
1929                                 struct cgroup *cont,
1930                                 struct cgroup *old_cont,
1931                                 struct task_struct *p)
1932 {
1933         struct mm_struct *mm;
1934         struct mem_cgroup *mem, *old_mem;
1935
1936         mm = get_task_mm(p);
1937         if (mm == NULL)
1938                 return;
1939
1940         mem = mem_cgroup_from_cont(cont);
1941         old_mem = mem_cgroup_from_cont(old_cont);
1942
1943         /*
1944          * Only thread group leaders are allowed to migrate, the mm_struct is
1945          * in effect owned by the leader
1946          */
1947         if (!thread_group_leader(p))
1948                 goto out;
1949
1950 out:
1951         mmput(mm);
1952 }
1953
1954 struct cgroup_subsys mem_cgroup_subsys = {
1955         .name = "memory",
1956         .subsys_id = mem_cgroup_subsys_id,
1957         .create = mem_cgroup_create,
1958         .pre_destroy = mem_cgroup_pre_destroy,
1959         .destroy = mem_cgroup_destroy,
1960         .populate = mem_cgroup_populate,
1961         .attach = mem_cgroup_move_task,
1962         .early_init = 0,
1963 };
1964
1965 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
1966
1967 static int __init disable_swap_account(char *s)
1968 {
1969         really_do_swap_account = 0;
1970         return 1;
1971 }
1972 __setup("noswapaccount", disable_swap_account);
1973 #endif