memcg: handle swap caches
[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/slab.h>
31 #include <linux/swap.h>
32 #include <linux/spinlock.h>
33 #include <linux/fs.h>
34 #include <linux/seq_file.h>
35 #include <linux/vmalloc.h>
36 #include <linux/mm_inline.h>
37 #include <linux/page_cgroup.h>
38
39 #include <asm/uaccess.h>
40
41 struct cgroup_subsys mem_cgroup_subsys __read_mostly;
42 #define MEM_CGROUP_RECLAIM_RETRIES      5
43
44 /*
45  * Statistics for memory cgroup.
46  */
47 enum mem_cgroup_stat_index {
48         /*
49          * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
50          */
51         MEM_CGROUP_STAT_CACHE,     /* # of pages charged as cache */
52         MEM_CGROUP_STAT_RSS,       /* # of pages charged as rss */
53         MEM_CGROUP_STAT_PGPGIN_COUNT,   /* # of pages paged in */
54         MEM_CGROUP_STAT_PGPGOUT_COUNT,  /* # of pages paged out */
55
56         MEM_CGROUP_STAT_NSTATS,
57 };
58
59 struct mem_cgroup_stat_cpu {
60         s64 count[MEM_CGROUP_STAT_NSTATS];
61 } ____cacheline_aligned_in_smp;
62
63 struct mem_cgroup_stat {
64         struct mem_cgroup_stat_cpu cpustat[0];
65 };
66
67 /*
68  * For accounting under irq disable, no need for increment preempt count.
69  */
70 static inline void __mem_cgroup_stat_add_safe(struct mem_cgroup_stat_cpu *stat,
71                 enum mem_cgroup_stat_index idx, int val)
72 {
73         stat->count[idx] += val;
74 }
75
76 static s64 mem_cgroup_read_stat(struct mem_cgroup_stat *stat,
77                 enum mem_cgroup_stat_index idx)
78 {
79         int cpu;
80         s64 ret = 0;
81         for_each_possible_cpu(cpu)
82                 ret += stat->cpustat[cpu].count[idx];
83         return ret;
84 }
85
86 /*
87  * per-zone information in memory controller.
88  */
89 struct mem_cgroup_per_zone {
90         /*
91          * spin_lock to protect the per cgroup LRU
92          */
93         spinlock_t              lru_lock;
94         struct list_head        lists[NR_LRU_LISTS];
95         unsigned long           count[NR_LRU_LISTS];
96 };
97 /* Macro for accessing counter */
98 #define MEM_CGROUP_ZSTAT(mz, idx)       ((mz)->count[(idx)])
99
100 struct mem_cgroup_per_node {
101         struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
102 };
103
104 struct mem_cgroup_lru_info {
105         struct mem_cgroup_per_node *nodeinfo[MAX_NUMNODES];
106 };
107
108 /*
109  * The memory controller data structure. The memory controller controls both
110  * page cache and RSS per cgroup. We would eventually like to provide
111  * statistics based on the statistics developed by Rik Van Riel for clock-pro,
112  * to help the administrator determine what knobs to tune.
113  *
114  * TODO: Add a water mark for the memory controller. Reclaim will begin when
115  * we hit the water mark. May be even add a low water mark, such that
116  * no reclaim occurs from a cgroup at it's low water mark, this is
117  * a feature that will be implemented much later in the future.
118  */
119 struct mem_cgroup {
120         struct cgroup_subsys_state css;
121         /*
122          * the counter to account for memory usage
123          */
124         struct res_counter res;
125         /*
126          * Per cgroup active and inactive list, similar to the
127          * per zone LRU lists.
128          */
129         struct mem_cgroup_lru_info info;
130
131         int     prev_priority;  /* for recording reclaim priority */
132         /*
133          * statistics. This must be placed at the end of memcg.
134          */
135         struct mem_cgroup_stat stat;
136 };
137
138 enum charge_type {
139         MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
140         MEM_CGROUP_CHARGE_TYPE_MAPPED,
141         MEM_CGROUP_CHARGE_TYPE_SHMEM,   /* used by page migration of shmem */
142         MEM_CGROUP_CHARGE_TYPE_FORCE,   /* used by force_empty */
143         MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
144         NR_CHARGE_TYPE,
145 };
146
147 /* only for here (for easy reading.) */
148 #define PCGF_CACHE      (1UL << PCG_CACHE)
149 #define PCGF_USED       (1UL << PCG_USED)
150 #define PCGF_ACTIVE     (1UL << PCG_ACTIVE)
151 #define PCGF_LOCK       (1UL << PCG_LOCK)
152 #define PCGF_FILE       (1UL << PCG_FILE)
153 static const unsigned long
154 pcg_default_flags[NR_CHARGE_TYPE] = {
155         PCGF_CACHE | PCGF_FILE | PCGF_USED | PCGF_LOCK, /* File Cache */
156         PCGF_ACTIVE | PCGF_USED | PCGF_LOCK, /* Anon */
157         PCGF_ACTIVE | PCGF_CACHE | PCGF_USED | PCGF_LOCK, /* Shmem */
158         0, /* FORCE */
159 };
160
161 /*
162  * Always modified under lru lock. Then, not necessary to preempt_disable()
163  */
164 static void mem_cgroup_charge_statistics(struct mem_cgroup *mem,
165                                          struct page_cgroup *pc,
166                                          bool charge)
167 {
168         int val = (charge)? 1 : -1;
169         struct mem_cgroup_stat *stat = &mem->stat;
170         struct mem_cgroup_stat_cpu *cpustat;
171
172         VM_BUG_ON(!irqs_disabled());
173
174         cpustat = &stat->cpustat[smp_processor_id()];
175         if (PageCgroupCache(pc))
176                 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_CACHE, val);
177         else
178                 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_RSS, val);
179
180         if (charge)
181                 __mem_cgroup_stat_add_safe(cpustat,
182                                 MEM_CGROUP_STAT_PGPGIN_COUNT, 1);
183         else
184                 __mem_cgroup_stat_add_safe(cpustat,
185                                 MEM_CGROUP_STAT_PGPGOUT_COUNT, 1);
186 }
187
188 static struct mem_cgroup_per_zone *
189 mem_cgroup_zoneinfo(struct mem_cgroup *mem, int nid, int zid)
190 {
191         return &mem->info.nodeinfo[nid]->zoneinfo[zid];
192 }
193
194 static struct mem_cgroup_per_zone *
195 page_cgroup_zoneinfo(struct page_cgroup *pc)
196 {
197         struct mem_cgroup *mem = pc->mem_cgroup;
198         int nid = page_cgroup_nid(pc);
199         int zid = page_cgroup_zid(pc);
200
201         return mem_cgroup_zoneinfo(mem, nid, zid);
202 }
203
204 static unsigned long mem_cgroup_get_all_zonestat(struct mem_cgroup *mem,
205                                         enum lru_list idx)
206 {
207         int nid, zid;
208         struct mem_cgroup_per_zone *mz;
209         u64 total = 0;
210
211         for_each_online_node(nid)
212                 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
213                         mz = mem_cgroup_zoneinfo(mem, nid, zid);
214                         total += MEM_CGROUP_ZSTAT(mz, idx);
215                 }
216         return total;
217 }
218
219 static struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
220 {
221         return container_of(cgroup_subsys_state(cont,
222                                 mem_cgroup_subsys_id), struct mem_cgroup,
223                                 css);
224 }
225
226 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
227 {
228         /*
229          * mm_update_next_owner() may clear mm->owner to NULL
230          * if it races with swapoff, page migration, etc.
231          * So this can be called with p == NULL.
232          */
233         if (unlikely(!p))
234                 return NULL;
235
236         return container_of(task_subsys_state(p, mem_cgroup_subsys_id),
237                                 struct mem_cgroup, css);
238 }
239
240 static void __mem_cgroup_remove_list(struct mem_cgroup_per_zone *mz,
241                         struct page_cgroup *pc)
242 {
243         int lru = LRU_BASE;
244
245         if (PageCgroupUnevictable(pc))
246                 lru = LRU_UNEVICTABLE;
247         else {
248                 if (PageCgroupActive(pc))
249                         lru += LRU_ACTIVE;
250                 if (PageCgroupFile(pc))
251                         lru += LRU_FILE;
252         }
253
254         MEM_CGROUP_ZSTAT(mz, lru) -= 1;
255
256         mem_cgroup_charge_statistics(pc->mem_cgroup, pc, false);
257         list_del(&pc->lru);
258 }
259
260 static void __mem_cgroup_add_list(struct mem_cgroup_per_zone *mz,
261                                 struct page_cgroup *pc, bool hot)
262 {
263         int lru = LRU_BASE;
264
265         if (PageCgroupUnevictable(pc))
266                 lru = LRU_UNEVICTABLE;
267         else {
268                 if (PageCgroupActive(pc))
269                         lru += LRU_ACTIVE;
270                 if (PageCgroupFile(pc))
271                         lru += LRU_FILE;
272         }
273
274         MEM_CGROUP_ZSTAT(mz, lru) += 1;
275         if (hot)
276                 list_add(&pc->lru, &mz->lists[lru]);
277         else
278                 list_add_tail(&pc->lru, &mz->lists[lru]);
279
280         mem_cgroup_charge_statistics(pc->mem_cgroup, pc, true);
281 }
282
283 static void __mem_cgroup_move_lists(struct page_cgroup *pc, enum lru_list lru)
284 {
285         struct mem_cgroup_per_zone *mz = page_cgroup_zoneinfo(pc);
286         int active    = PageCgroupActive(pc);
287         int file      = PageCgroupFile(pc);
288         int unevictable = PageCgroupUnevictable(pc);
289         enum lru_list from = unevictable ? LRU_UNEVICTABLE :
290                                 (LRU_FILE * !!file + !!active);
291
292         if (lru == from)
293                 return;
294
295         MEM_CGROUP_ZSTAT(mz, from) -= 1;
296         /*
297          * However this is done under mz->lru_lock, another flags, which
298          * are not related to LRU, will be modified from out-of-lock.
299          * We have to use atomic set/clear flags.
300          */
301         if (is_unevictable_lru(lru)) {
302                 ClearPageCgroupActive(pc);
303                 SetPageCgroupUnevictable(pc);
304         } else {
305                 if (is_active_lru(lru))
306                         SetPageCgroupActive(pc);
307                 else
308                         ClearPageCgroupActive(pc);
309                 ClearPageCgroupUnevictable(pc);
310         }
311
312         MEM_CGROUP_ZSTAT(mz, lru) += 1;
313         list_move(&pc->lru, &mz->lists[lru]);
314 }
315
316 int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *mem)
317 {
318         int ret;
319
320         task_lock(task);
321         ret = task->mm && mm_match_cgroup(task->mm, mem);
322         task_unlock(task);
323         return ret;
324 }
325
326 /*
327  * This routine assumes that the appropriate zone's lru lock is already held
328  */
329 void mem_cgroup_move_lists(struct page *page, enum lru_list lru)
330 {
331         struct page_cgroup *pc;
332         struct mem_cgroup_per_zone *mz;
333         unsigned long flags;
334
335         if (mem_cgroup_subsys.disabled)
336                 return;
337
338         /*
339          * We cannot lock_page_cgroup while holding zone's lru_lock,
340          * because other holders of lock_page_cgroup can be interrupted
341          * with an attempt to rotate_reclaimable_page.  But we cannot
342          * safely get to page_cgroup without it, so just try_lock it:
343          * mem_cgroup_isolate_pages allows for page left on wrong list.
344          */
345         pc = lookup_page_cgroup(page);
346         if (!trylock_page_cgroup(pc))
347                 return;
348         if (pc && PageCgroupUsed(pc)) {
349                 mz = page_cgroup_zoneinfo(pc);
350                 spin_lock_irqsave(&mz->lru_lock, flags);
351                 __mem_cgroup_move_lists(pc, lru);
352                 spin_unlock_irqrestore(&mz->lru_lock, flags);
353         }
354         unlock_page_cgroup(pc);
355 }
356
357 /*
358  * Calculate mapped_ratio under memory controller. This will be used in
359  * vmscan.c for deteremining we have to reclaim mapped pages.
360  */
361 int mem_cgroup_calc_mapped_ratio(struct mem_cgroup *mem)
362 {
363         long total, rss;
364
365         /*
366          * usage is recorded in bytes. But, here, we assume the number of
367          * physical pages can be represented by "long" on any arch.
368          */
369         total = (long) (mem->res.usage >> PAGE_SHIFT) + 1L;
370         rss = (long)mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_RSS);
371         return (int)((rss * 100L) / total);
372 }
373
374 /*
375  * prev_priority control...this will be used in memory reclaim path.
376  */
377 int mem_cgroup_get_reclaim_priority(struct mem_cgroup *mem)
378 {
379         return mem->prev_priority;
380 }
381
382 void mem_cgroup_note_reclaim_priority(struct mem_cgroup *mem, int priority)
383 {
384         if (priority < mem->prev_priority)
385                 mem->prev_priority = priority;
386 }
387
388 void mem_cgroup_record_reclaim_priority(struct mem_cgroup *mem, int priority)
389 {
390         mem->prev_priority = priority;
391 }
392
393 /*
394  * Calculate # of pages to be scanned in this priority/zone.
395  * See also vmscan.c
396  *
397  * priority starts from "DEF_PRIORITY" and decremented in each loop.
398  * (see include/linux/mmzone.h)
399  */
400
401 long mem_cgroup_calc_reclaim(struct mem_cgroup *mem, struct zone *zone,
402                                         int priority, enum lru_list lru)
403 {
404         long nr_pages;
405         int nid = zone->zone_pgdat->node_id;
406         int zid = zone_idx(zone);
407         struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(mem, nid, zid);
408
409         nr_pages = MEM_CGROUP_ZSTAT(mz, lru);
410
411         return (nr_pages >> priority);
412 }
413
414 unsigned long mem_cgroup_isolate_pages(unsigned long nr_to_scan,
415                                         struct list_head *dst,
416                                         unsigned long *scanned, int order,
417                                         int mode, struct zone *z,
418                                         struct mem_cgroup *mem_cont,
419                                         int active, int file)
420 {
421         unsigned long nr_taken = 0;
422         struct page *page;
423         unsigned long scan;
424         LIST_HEAD(pc_list);
425         struct list_head *src;
426         struct page_cgroup *pc, *tmp;
427         int nid = z->zone_pgdat->node_id;
428         int zid = zone_idx(z);
429         struct mem_cgroup_per_zone *mz;
430         int lru = LRU_FILE * !!file + !!active;
431
432         BUG_ON(!mem_cont);
433         mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
434         src = &mz->lists[lru];
435
436         spin_lock(&mz->lru_lock);
437         scan = 0;
438         list_for_each_entry_safe_reverse(pc, tmp, src, lru) {
439                 if (scan >= nr_to_scan)
440                         break;
441                 if (unlikely(!PageCgroupUsed(pc)))
442                         continue;
443                 page = pc->page;
444
445                 if (unlikely(!PageLRU(page)))
446                         continue;
447
448                 /*
449                  * TODO: play better with lumpy reclaim, grabbing anything.
450                  */
451                 if (PageUnevictable(page) ||
452                     (PageActive(page) && !active) ||
453                     (!PageActive(page) && active)) {
454                         __mem_cgroup_move_lists(pc, page_lru(page));
455                         continue;
456                 }
457
458                 scan++;
459                 list_move(&pc->lru, &pc_list);
460
461                 if (__isolate_lru_page(page, mode, file) == 0) {
462                         list_move(&page->lru, dst);
463                         nr_taken++;
464                 }
465         }
466
467         list_splice(&pc_list, src);
468         spin_unlock(&mz->lru_lock);
469
470         *scanned = scan;
471         return nr_taken;
472 }
473
474 /*
475  * Unlike exported interface, "oom" parameter is added. if oom==true,
476  * oom-killer can be invoked.
477  */
478 static int __mem_cgroup_try_charge(struct mm_struct *mm,
479                         gfp_t gfp_mask, struct mem_cgroup **memcg, bool oom)
480 {
481         struct mem_cgroup *mem;
482         int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
483         /*
484          * We always charge the cgroup the mm_struct belongs to.
485          * The mm_struct's mem_cgroup changes on task migration if the
486          * thread group leader migrates. It's possible that mm is not
487          * set, if so charge the init_mm (happens for pagecache usage).
488          */
489         if (likely(!*memcg)) {
490                 rcu_read_lock();
491                 mem = mem_cgroup_from_task(rcu_dereference(mm->owner));
492                 if (unlikely(!mem)) {
493                         rcu_read_unlock();
494                         return 0;
495                 }
496                 /*
497                  * For every charge from the cgroup, increment reference count
498                  */
499                 css_get(&mem->css);
500                 *memcg = mem;
501                 rcu_read_unlock();
502         } else {
503                 mem = *memcg;
504                 css_get(&mem->css);
505         }
506
507
508         while (unlikely(res_counter_charge(&mem->res, PAGE_SIZE))) {
509                 if (!(gfp_mask & __GFP_WAIT))
510                         goto nomem;
511
512                 if (try_to_free_mem_cgroup_pages(mem, gfp_mask))
513                         continue;
514
515                 /*
516                  * try_to_free_mem_cgroup_pages() might not give us a full
517                  * picture of reclaim. Some pages are reclaimed and might be
518                  * moved to swap cache or just unmapped from the cgroup.
519                  * Check the limit again to see if the reclaim reduced the
520                  * current usage of the cgroup before giving up
521                  */
522                 if (res_counter_check_under_limit(&mem->res))
523                         continue;
524
525                 if (!nr_retries--) {
526                         if (oom)
527                                 mem_cgroup_out_of_memory(mem, gfp_mask);
528                         goto nomem;
529                 }
530         }
531         return 0;
532 nomem:
533         css_put(&mem->css);
534         return -ENOMEM;
535 }
536
537 /**
538  * mem_cgroup_try_charge - get charge of PAGE_SIZE.
539  * @mm: an mm_struct which is charged against. (when *memcg is NULL)
540  * @gfp_mask: gfp_mask for reclaim.
541  * @memcg: a pointer to memory cgroup which is charged against.
542  *
543  * charge against memory cgroup pointed by *memcg. if *memcg == NULL, estimated
544  * memory cgroup from @mm is got and stored in *memcg.
545  *
546  * Returns 0 if success. -ENOMEM at failure.
547  * This call can invoke OOM-Killer.
548  */
549
550 int mem_cgroup_try_charge(struct mm_struct *mm,
551                           gfp_t mask, struct mem_cgroup **memcg)
552 {
553         return __mem_cgroup_try_charge(mm, mask, memcg, true);
554 }
555
556 /*
557  * commit a charge got by mem_cgroup_try_charge() and makes page_cgroup to be
558  * USED state. If already USED, uncharge and return.
559  */
560
561 static void __mem_cgroup_commit_charge(struct mem_cgroup *mem,
562                                      struct page_cgroup *pc,
563                                      enum charge_type ctype)
564 {
565         struct mem_cgroup_per_zone *mz;
566         unsigned long flags;
567
568         /* try_charge() can return NULL to *memcg, taking care of it. */
569         if (!mem)
570                 return;
571
572         lock_page_cgroup(pc);
573         if (unlikely(PageCgroupUsed(pc))) {
574                 unlock_page_cgroup(pc);
575                 res_counter_uncharge(&mem->res, PAGE_SIZE);
576                 css_put(&mem->css);
577                 return;
578         }
579         pc->mem_cgroup = mem;
580         /*
581          * If a page is accounted as a page cache, insert to inactive list.
582          * If anon, insert to active list.
583          */
584         pc->flags = pcg_default_flags[ctype];
585
586         mz = page_cgroup_zoneinfo(pc);
587
588         spin_lock_irqsave(&mz->lru_lock, flags);
589         __mem_cgroup_add_list(mz, pc, true);
590         spin_unlock_irqrestore(&mz->lru_lock, flags);
591         unlock_page_cgroup(pc);
592 }
593
594 /**
595  * mem_cgroup_move_account - move account of the page
596  * @pc: page_cgroup of the page.
597  * @from: mem_cgroup which the page is moved from.
598  * @to: mem_cgroup which the page is moved to. @from != @to.
599  *
600  * The caller must confirm following.
601  * 1. disable irq.
602  * 2. lru_lock of old mem_cgroup(@from) should be held.
603  *
604  * returns 0 at success,
605  * returns -EBUSY when lock is busy or "pc" is unstable.
606  *
607  * This function does "uncharge" from old cgroup but doesn't do "charge" to
608  * new cgroup. It should be done by a caller.
609  */
610
611 static int mem_cgroup_move_account(struct page_cgroup *pc,
612         struct mem_cgroup *from, struct mem_cgroup *to)
613 {
614         struct mem_cgroup_per_zone *from_mz, *to_mz;
615         int nid, zid;
616         int ret = -EBUSY;
617
618         VM_BUG_ON(!irqs_disabled());
619         VM_BUG_ON(from == to);
620
621         nid = page_cgroup_nid(pc);
622         zid = page_cgroup_zid(pc);
623         from_mz =  mem_cgroup_zoneinfo(from, nid, zid);
624         to_mz =  mem_cgroup_zoneinfo(to, nid, zid);
625
626
627         if (!trylock_page_cgroup(pc))
628                 return ret;
629
630         if (!PageCgroupUsed(pc))
631                 goto out;
632
633         if (pc->mem_cgroup != from)
634                 goto out;
635
636         if (spin_trylock(&to_mz->lru_lock)) {
637                 __mem_cgroup_remove_list(from_mz, pc);
638                 css_put(&from->css);
639                 res_counter_uncharge(&from->res, PAGE_SIZE);
640                 pc->mem_cgroup = to;
641                 css_get(&to->css);
642                 __mem_cgroup_add_list(to_mz, pc, false);
643                 ret = 0;
644                 spin_unlock(&to_mz->lru_lock);
645         }
646 out:
647         unlock_page_cgroup(pc);
648         return ret;
649 }
650
651 /*
652  * move charges to its parent.
653  */
654
655 static int mem_cgroup_move_parent(struct page_cgroup *pc,
656                                   struct mem_cgroup *child,
657                                   gfp_t gfp_mask)
658 {
659         struct cgroup *cg = child->css.cgroup;
660         struct cgroup *pcg = cg->parent;
661         struct mem_cgroup *parent;
662         struct mem_cgroup_per_zone *mz;
663         unsigned long flags;
664         int ret;
665
666         /* Is ROOT ? */
667         if (!pcg)
668                 return -EINVAL;
669
670         parent = mem_cgroup_from_cont(pcg);
671
672         ret = __mem_cgroup_try_charge(NULL, gfp_mask, &parent, false);
673         if (ret)
674                 return ret;
675
676         mz = mem_cgroup_zoneinfo(child,
677                         page_cgroup_nid(pc), page_cgroup_zid(pc));
678
679         spin_lock_irqsave(&mz->lru_lock, flags);
680         ret = mem_cgroup_move_account(pc, child, parent);
681         spin_unlock_irqrestore(&mz->lru_lock, flags);
682
683         /* drop extra refcnt */
684         css_put(&parent->css);
685         /* uncharge if move fails */
686         if (ret)
687                 res_counter_uncharge(&parent->res, PAGE_SIZE);
688
689         return ret;
690 }
691
692 /*
693  * Charge the memory controller for page usage.
694  * Return
695  * 0 if the charge was successful
696  * < 0 if the cgroup is over its limit
697  */
698 static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
699                                 gfp_t gfp_mask, enum charge_type ctype,
700                                 struct mem_cgroup *memcg)
701 {
702         struct mem_cgroup *mem;
703         struct page_cgroup *pc;
704         int ret;
705
706         pc = lookup_page_cgroup(page);
707         /* can happen at boot */
708         if (unlikely(!pc))
709                 return 0;
710         prefetchw(pc);
711
712         mem = memcg;
713         ret = __mem_cgroup_try_charge(mm, gfp_mask, &mem, true);
714         if (ret)
715                 return ret;
716
717         __mem_cgroup_commit_charge(mem, pc, ctype);
718         return 0;
719 }
720
721 int mem_cgroup_newpage_charge(struct page *page,
722                               struct mm_struct *mm, gfp_t gfp_mask)
723 {
724         if (mem_cgroup_subsys.disabled)
725                 return 0;
726         if (PageCompound(page))
727                 return 0;
728         /*
729          * If already mapped, we don't have to account.
730          * If page cache, page->mapping has address_space.
731          * But page->mapping may have out-of-use anon_vma pointer,
732          * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
733          * is NULL.
734          */
735         if (page_mapped(page) || (page->mapping && !PageAnon(page)))
736                 return 0;
737         if (unlikely(!mm))
738                 mm = &init_mm;
739         return mem_cgroup_charge_common(page, mm, gfp_mask,
740                                 MEM_CGROUP_CHARGE_TYPE_MAPPED, NULL);
741 }
742
743 int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
744                                 gfp_t gfp_mask)
745 {
746         if (mem_cgroup_subsys.disabled)
747                 return 0;
748         if (PageCompound(page))
749                 return 0;
750         /*
751          * Corner case handling. This is called from add_to_page_cache()
752          * in usual. But some FS (shmem) precharges this page before calling it
753          * and call add_to_page_cache() with GFP_NOWAIT.
754          *
755          * For GFP_NOWAIT case, the page may be pre-charged before calling
756          * add_to_page_cache(). (See shmem.c) check it here and avoid to call
757          * charge twice. (It works but has to pay a bit larger cost.)
758          */
759         if (!(gfp_mask & __GFP_WAIT)) {
760                 struct page_cgroup *pc;
761
762
763                 pc = lookup_page_cgroup(page);
764                 if (!pc)
765                         return 0;
766                 lock_page_cgroup(pc);
767                 if (PageCgroupUsed(pc)) {
768                         unlock_page_cgroup(pc);
769                         return 0;
770                 }
771                 unlock_page_cgroup(pc);
772         }
773
774         if (unlikely(!mm))
775                 mm = &init_mm;
776
777         if (page_is_file_cache(page))
778                 return mem_cgroup_charge_common(page, mm, gfp_mask,
779                                 MEM_CGROUP_CHARGE_TYPE_CACHE, NULL);
780         else
781                 return mem_cgroup_charge_common(page, mm, gfp_mask,
782                                 MEM_CGROUP_CHARGE_TYPE_SHMEM, NULL);
783 }
784
785 #ifdef CONFIG_SWAP
786 int mem_cgroup_cache_charge_swapin(struct page *page,
787                         struct mm_struct *mm, gfp_t mask, bool locked)
788 {
789         int ret = 0;
790
791         if (mem_cgroup_subsys.disabled)
792                 return 0;
793         if (unlikely(!mm))
794                 mm = &init_mm;
795         if (!locked)
796                 lock_page(page);
797         /*
798          * If not locked, the page can be dropped from SwapCache until
799          * we reach here.
800          */
801         if (PageSwapCache(page)) {
802                 ret = mem_cgroup_charge_common(page, mm, mask,
803                                 MEM_CGROUP_CHARGE_TYPE_SHMEM, NULL);
804         }
805         if (!locked)
806                 unlock_page(page);
807
808         return ret;
809 }
810 #endif
811
812 void mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr)
813 {
814         struct page_cgroup *pc;
815
816         if (mem_cgroup_subsys.disabled)
817                 return;
818         if (!ptr)
819                 return;
820         pc = lookup_page_cgroup(page);
821         __mem_cgroup_commit_charge(ptr, pc, MEM_CGROUP_CHARGE_TYPE_MAPPED);
822 }
823
824 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *mem)
825 {
826         if (mem_cgroup_subsys.disabled)
827                 return;
828         if (!mem)
829                 return;
830         res_counter_uncharge(&mem->res, PAGE_SIZE);
831         css_put(&mem->css);
832 }
833
834
835 /*
836  * uncharge if !page_mapped(page)
837  */
838 static void
839 __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype)
840 {
841         struct page_cgroup *pc;
842         struct mem_cgroup *mem;
843         struct mem_cgroup_per_zone *mz;
844         unsigned long flags;
845
846         if (mem_cgroup_subsys.disabled)
847                 return;
848
849         if (PageSwapCache(page))
850                 return;
851
852         /*
853          * Check if our page_cgroup is valid
854          */
855         pc = lookup_page_cgroup(page);
856         if (unlikely(!pc || !PageCgroupUsed(pc)))
857                 return;
858
859         lock_page_cgroup(pc);
860
861         if (!PageCgroupUsed(pc))
862                 goto unlock_out;
863
864         switch (ctype) {
865         case MEM_CGROUP_CHARGE_TYPE_MAPPED:
866                 if (page_mapped(page))
867                         goto unlock_out;
868                 break;
869         case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
870                 if (!PageAnon(page)) {  /* Shared memory */
871                         if (page->mapping && !page_is_file_cache(page))
872                                 goto unlock_out;
873                 } else if (page_mapped(page)) /* Anon */
874                                 goto unlock_out;
875                 break;
876         default:
877                 break;
878         }
879
880         ClearPageCgroupUsed(pc);
881         mem = pc->mem_cgroup;
882
883         mz = page_cgroup_zoneinfo(pc);
884         spin_lock_irqsave(&mz->lru_lock, flags);
885         __mem_cgroup_remove_list(mz, pc);
886         spin_unlock_irqrestore(&mz->lru_lock, flags);
887         unlock_page_cgroup(pc);
888
889         res_counter_uncharge(&mem->res, PAGE_SIZE);
890         css_put(&mem->css);
891
892         return;
893
894 unlock_out:
895         unlock_page_cgroup(pc);
896         return;
897 }
898
899 void mem_cgroup_uncharge_page(struct page *page)
900 {
901         /* early check. */
902         if (page_mapped(page))
903                 return;
904         if (page->mapping && !PageAnon(page))
905                 return;
906         __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_MAPPED);
907 }
908
909 void mem_cgroup_uncharge_cache_page(struct page *page)
910 {
911         VM_BUG_ON(page_mapped(page));
912         VM_BUG_ON(page->mapping);
913         __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE);
914 }
915
916 void mem_cgroup_uncharge_swapcache(struct page *page)
917 {
918         __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_SWAPOUT);
919 }
920
921 /*
922  * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
923  * page belongs to.
924  */
925 int mem_cgroup_prepare_migration(struct page *page, struct mem_cgroup **ptr)
926 {
927         struct page_cgroup *pc;
928         struct mem_cgroup *mem = NULL;
929         int ret = 0;
930
931         if (mem_cgroup_subsys.disabled)
932                 return 0;
933
934         pc = lookup_page_cgroup(page);
935         lock_page_cgroup(pc);
936         if (PageCgroupUsed(pc)) {
937                 mem = pc->mem_cgroup;
938                 css_get(&mem->css);
939         }
940         unlock_page_cgroup(pc);
941
942         if (mem) {
943                 ret = mem_cgroup_try_charge(NULL, GFP_HIGHUSER_MOVABLE, &mem);
944                 css_put(&mem->css);
945         }
946         *ptr = mem;
947         return ret;
948 }
949
950 /* remove redundant charge if migration failed*/
951 void mem_cgroup_end_migration(struct mem_cgroup *mem,
952                 struct page *oldpage, struct page *newpage)
953 {
954         struct page *target, *unused;
955         struct page_cgroup *pc;
956         enum charge_type ctype;
957
958         if (!mem)
959                 return;
960
961         /* at migration success, oldpage->mapping is NULL. */
962         if (oldpage->mapping) {
963                 target = oldpage;
964                 unused = NULL;
965         } else {
966                 target = newpage;
967                 unused = oldpage;
968         }
969
970         if (PageAnon(target))
971                 ctype = MEM_CGROUP_CHARGE_TYPE_MAPPED;
972         else if (page_is_file_cache(target))
973                 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
974         else
975                 ctype = MEM_CGROUP_CHARGE_TYPE_SHMEM;
976
977         /* unused page is not on radix-tree now. */
978         if (unused)
979                 __mem_cgroup_uncharge_common(unused, ctype);
980
981         pc = lookup_page_cgroup(target);
982         /*
983          * __mem_cgroup_commit_charge() check PCG_USED bit of page_cgroup.
984          * So, double-counting is effectively avoided.
985          */
986         __mem_cgroup_commit_charge(mem, pc, ctype);
987
988         /*
989          * Both of oldpage and newpage are still under lock_page().
990          * Then, we don't have to care about race in radix-tree.
991          * But we have to be careful that this page is unmapped or not.
992          *
993          * There is a case for !page_mapped(). At the start of
994          * migration, oldpage was mapped. But now, it's zapped.
995          * But we know *target* page is not freed/reused under us.
996          * mem_cgroup_uncharge_page() does all necessary checks.
997          */
998         if (ctype == MEM_CGROUP_CHARGE_TYPE_MAPPED)
999                 mem_cgroup_uncharge_page(target);
1000 }
1001
1002 /*
1003  * A call to try to shrink memory usage under specified resource controller.
1004  * This is typically used for page reclaiming for shmem for reducing side
1005  * effect of page allocation from shmem, which is used by some mem_cgroup.
1006  */
1007 int mem_cgroup_shrink_usage(struct mm_struct *mm, gfp_t gfp_mask)
1008 {
1009         struct mem_cgroup *mem;
1010         int progress = 0;
1011         int retry = MEM_CGROUP_RECLAIM_RETRIES;
1012
1013         if (mem_cgroup_subsys.disabled)
1014                 return 0;
1015         if (!mm)
1016                 return 0;
1017
1018         rcu_read_lock();
1019         mem = mem_cgroup_from_task(rcu_dereference(mm->owner));
1020         if (unlikely(!mem)) {
1021                 rcu_read_unlock();
1022                 return 0;
1023         }
1024         css_get(&mem->css);
1025         rcu_read_unlock();
1026
1027         do {
1028                 progress = try_to_free_mem_cgroup_pages(mem, gfp_mask);
1029                 progress += res_counter_check_under_limit(&mem->res);
1030         } while (!progress && --retry);
1031
1032         css_put(&mem->css);
1033         if (!retry)
1034                 return -ENOMEM;
1035         return 0;
1036 }
1037
1038 static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
1039                                    unsigned long long val)
1040 {
1041
1042         int retry_count = MEM_CGROUP_RECLAIM_RETRIES;
1043         int progress;
1044         int ret = 0;
1045
1046         while (res_counter_set_limit(&memcg->res, val)) {
1047                 if (signal_pending(current)) {
1048                         ret = -EINTR;
1049                         break;
1050                 }
1051                 if (!retry_count) {
1052                         ret = -EBUSY;
1053                         break;
1054                 }
1055                 progress = try_to_free_mem_cgroup_pages(memcg,
1056                                 GFP_HIGHUSER_MOVABLE);
1057                 if (!progress)
1058                         retry_count--;
1059         }
1060         return ret;
1061 }
1062
1063
1064 /*
1065  * This routine traverse page_cgroup in given list and drop them all.
1066  * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
1067  */
1068 static int mem_cgroup_force_empty_list(struct mem_cgroup *mem,
1069                             struct mem_cgroup_per_zone *mz,
1070                             enum lru_list lru)
1071 {
1072         struct page_cgroup *pc, *busy;
1073         unsigned long flags;
1074         unsigned long loop;
1075         struct list_head *list;
1076         int ret = 0;
1077
1078         list = &mz->lists[lru];
1079
1080         loop = MEM_CGROUP_ZSTAT(mz, lru);
1081         /* give some margin against EBUSY etc...*/
1082         loop += 256;
1083         busy = NULL;
1084         while (loop--) {
1085                 ret = 0;
1086                 spin_lock_irqsave(&mz->lru_lock, flags);
1087                 if (list_empty(list)) {
1088                         spin_unlock_irqrestore(&mz->lru_lock, flags);
1089                         break;
1090                 }
1091                 pc = list_entry(list->prev, struct page_cgroup, lru);
1092                 if (busy == pc) {
1093                         list_move(&pc->lru, list);
1094                         busy = 0;
1095                         spin_unlock_irqrestore(&mz->lru_lock, flags);
1096                         continue;
1097                 }
1098                 spin_unlock_irqrestore(&mz->lru_lock, flags);
1099
1100                 ret = mem_cgroup_move_parent(pc, mem, GFP_HIGHUSER_MOVABLE);
1101                 if (ret == -ENOMEM)
1102                         break;
1103
1104                 if (ret == -EBUSY || ret == -EINVAL) {
1105                         /* found lock contention or "pc" is obsolete. */
1106                         busy = pc;
1107                         cond_resched();
1108                 } else
1109                         busy = NULL;
1110         }
1111         if (!ret && !list_empty(list))
1112                 return -EBUSY;
1113         return ret;
1114 }
1115
1116 /*
1117  * make mem_cgroup's charge to be 0 if there is no task.
1118  * This enables deleting this mem_cgroup.
1119  */
1120 static int mem_cgroup_force_empty(struct mem_cgroup *mem, bool free_all)
1121 {
1122         int ret;
1123         int node, zid, shrink;
1124         int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
1125         struct cgroup *cgrp = mem->css.cgroup;
1126
1127         css_get(&mem->css);
1128
1129         shrink = 0;
1130         /* should free all ? */
1131         if (free_all)
1132                 goto try_to_free;
1133 move_account:
1134         while (mem->res.usage > 0) {
1135                 ret = -EBUSY;
1136                 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
1137                         goto out;
1138                 ret = -EINTR;
1139                 if (signal_pending(current))
1140                         goto out;
1141                 /* This is for making all *used* pages to be on LRU. */
1142                 lru_add_drain_all();
1143                 ret = 0;
1144                 for_each_node_state(node, N_POSSIBLE) {
1145                         for (zid = 0; !ret && zid < MAX_NR_ZONES; zid++) {
1146                                 struct mem_cgroup_per_zone *mz;
1147                                 enum lru_list l;
1148                                 mz = mem_cgroup_zoneinfo(mem, node, zid);
1149                                 for_each_lru(l) {
1150                                         ret = mem_cgroup_force_empty_list(mem,
1151                                                                   mz, l);
1152                                         if (ret)
1153                                                 break;
1154                                 }
1155                         }
1156                         if (ret)
1157                                 break;
1158                 }
1159                 /* it seems parent cgroup doesn't have enough mem */
1160                 if (ret == -ENOMEM)
1161                         goto try_to_free;
1162                 cond_resched();
1163         }
1164         ret = 0;
1165 out:
1166         css_put(&mem->css);
1167         return ret;
1168
1169 try_to_free:
1170         /* returns EBUSY if there is a task or if we come here twice. */
1171         if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children) || shrink) {
1172                 ret = -EBUSY;
1173                 goto out;
1174         }
1175         /* we call try-to-free pages for make this cgroup empty */
1176         lru_add_drain_all();
1177         /* try to free all pages in this cgroup */
1178         shrink = 1;
1179         while (nr_retries && mem->res.usage > 0) {
1180                 int progress;
1181
1182                 if (signal_pending(current)) {
1183                         ret = -EINTR;
1184                         goto out;
1185                 }
1186                 progress = try_to_free_mem_cgroup_pages(mem,
1187                                                   GFP_HIGHUSER_MOVABLE);
1188                 if (!progress) {
1189                         nr_retries--;
1190                         /* maybe some writeback is necessary */
1191                         congestion_wait(WRITE, HZ/10);
1192                 }
1193
1194         }
1195         /* try move_account...there may be some *locked* pages. */
1196         if (mem->res.usage)
1197                 goto move_account;
1198         ret = 0;
1199         goto out;
1200 }
1201
1202 int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
1203 {
1204         return mem_cgroup_force_empty(mem_cgroup_from_cont(cont), true);
1205 }
1206
1207
1208 static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft)
1209 {
1210         return res_counter_read_u64(&mem_cgroup_from_cont(cont)->res,
1211                                     cft->private);
1212 }
1213 /*
1214  * The user of this function is...
1215  * RES_LIMIT.
1216  */
1217 static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
1218                             const char *buffer)
1219 {
1220         struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
1221         unsigned long long val;
1222         int ret;
1223
1224         switch (cft->private) {
1225         case RES_LIMIT:
1226                 /* This function does all necessary parse...reuse it */
1227                 ret = res_counter_memparse_write_strategy(buffer, &val);
1228                 if (!ret)
1229                         ret = mem_cgroup_resize_limit(memcg, val);
1230                 break;
1231         default:
1232                 ret = -EINVAL; /* should be BUG() ? */
1233                 break;
1234         }
1235         return ret;
1236 }
1237
1238 static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
1239 {
1240         struct mem_cgroup *mem;
1241
1242         mem = mem_cgroup_from_cont(cont);
1243         switch (event) {
1244         case RES_MAX_USAGE:
1245                 res_counter_reset_max(&mem->res);
1246                 break;
1247         case RES_FAILCNT:
1248                 res_counter_reset_failcnt(&mem->res);
1249                 break;
1250         }
1251         return 0;
1252 }
1253
1254 static const struct mem_cgroup_stat_desc {
1255         const char *msg;
1256         u64 unit;
1257 } mem_cgroup_stat_desc[] = {
1258         [MEM_CGROUP_STAT_CACHE] = { "cache", PAGE_SIZE, },
1259         [MEM_CGROUP_STAT_RSS] = { "rss", PAGE_SIZE, },
1260         [MEM_CGROUP_STAT_PGPGIN_COUNT] = {"pgpgin", 1, },
1261         [MEM_CGROUP_STAT_PGPGOUT_COUNT] = {"pgpgout", 1, },
1262 };
1263
1264 static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft,
1265                                  struct cgroup_map_cb *cb)
1266 {
1267         struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
1268         struct mem_cgroup_stat *stat = &mem_cont->stat;
1269         int i;
1270
1271         for (i = 0; i < ARRAY_SIZE(stat->cpustat[0].count); i++) {
1272                 s64 val;
1273
1274                 val = mem_cgroup_read_stat(stat, i);
1275                 val *= mem_cgroup_stat_desc[i].unit;
1276                 cb->fill(cb, mem_cgroup_stat_desc[i].msg, val);
1277         }
1278         /* showing # of active pages */
1279         {
1280                 unsigned long active_anon, inactive_anon;
1281                 unsigned long active_file, inactive_file;
1282                 unsigned long unevictable;
1283
1284                 inactive_anon = mem_cgroup_get_all_zonestat(mem_cont,
1285                                                 LRU_INACTIVE_ANON);
1286                 active_anon = mem_cgroup_get_all_zonestat(mem_cont,
1287                                                 LRU_ACTIVE_ANON);
1288                 inactive_file = mem_cgroup_get_all_zonestat(mem_cont,
1289                                                 LRU_INACTIVE_FILE);
1290                 active_file = mem_cgroup_get_all_zonestat(mem_cont,
1291                                                 LRU_ACTIVE_FILE);
1292                 unevictable = mem_cgroup_get_all_zonestat(mem_cont,
1293                                                         LRU_UNEVICTABLE);
1294
1295                 cb->fill(cb, "active_anon", (active_anon) * PAGE_SIZE);
1296                 cb->fill(cb, "inactive_anon", (inactive_anon) * PAGE_SIZE);
1297                 cb->fill(cb, "active_file", (active_file) * PAGE_SIZE);
1298                 cb->fill(cb, "inactive_file", (inactive_file) * PAGE_SIZE);
1299                 cb->fill(cb, "unevictable", unevictable * PAGE_SIZE);
1300
1301         }
1302         return 0;
1303 }
1304
1305
1306 static struct cftype mem_cgroup_files[] = {
1307         {
1308                 .name = "usage_in_bytes",
1309                 .private = RES_USAGE,
1310                 .read_u64 = mem_cgroup_read,
1311         },
1312         {
1313                 .name = "max_usage_in_bytes",
1314                 .private = RES_MAX_USAGE,
1315                 .trigger = mem_cgroup_reset,
1316                 .read_u64 = mem_cgroup_read,
1317         },
1318         {
1319                 .name = "limit_in_bytes",
1320                 .private = RES_LIMIT,
1321                 .write_string = mem_cgroup_write,
1322                 .read_u64 = mem_cgroup_read,
1323         },
1324         {
1325                 .name = "failcnt",
1326                 .private = RES_FAILCNT,
1327                 .trigger = mem_cgroup_reset,
1328                 .read_u64 = mem_cgroup_read,
1329         },
1330         {
1331                 .name = "stat",
1332                 .read_map = mem_control_stat_show,
1333         },
1334         {
1335                 .name = "force_empty",
1336                 .trigger = mem_cgroup_force_empty_write,
1337         },
1338 };
1339
1340 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
1341 {
1342         struct mem_cgroup_per_node *pn;
1343         struct mem_cgroup_per_zone *mz;
1344         enum lru_list l;
1345         int zone, tmp = node;
1346         /*
1347          * This routine is called against possible nodes.
1348          * But it's BUG to call kmalloc() against offline node.
1349          *
1350          * TODO: this routine can waste much memory for nodes which will
1351          *       never be onlined. It's better to use memory hotplug callback
1352          *       function.
1353          */
1354         if (!node_state(node, N_NORMAL_MEMORY))
1355                 tmp = -1;
1356         pn = kmalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
1357         if (!pn)
1358                 return 1;
1359
1360         mem->info.nodeinfo[node] = pn;
1361         memset(pn, 0, sizeof(*pn));
1362
1363         for (zone = 0; zone < MAX_NR_ZONES; zone++) {
1364                 mz = &pn->zoneinfo[zone];
1365                 spin_lock_init(&mz->lru_lock);
1366                 for_each_lru(l)
1367                         INIT_LIST_HEAD(&mz->lists[l]);
1368         }
1369         return 0;
1370 }
1371
1372 static void free_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
1373 {
1374         kfree(mem->info.nodeinfo[node]);
1375 }
1376
1377 static int mem_cgroup_size(void)
1378 {
1379         int cpustat_size = nr_cpu_ids * sizeof(struct mem_cgroup_stat_cpu);
1380         return sizeof(struct mem_cgroup) + cpustat_size;
1381 }
1382
1383 static struct mem_cgroup *mem_cgroup_alloc(void)
1384 {
1385         struct mem_cgroup *mem;
1386         int size = mem_cgroup_size();
1387
1388         if (size < PAGE_SIZE)
1389                 mem = kmalloc(size, GFP_KERNEL);
1390         else
1391                 mem = vmalloc(size);
1392
1393         if (mem)
1394                 memset(mem, 0, size);
1395         return mem;
1396 }
1397
1398 static void mem_cgroup_free(struct mem_cgroup *mem)
1399 {
1400         if (mem_cgroup_size() < PAGE_SIZE)
1401                 kfree(mem);
1402         else
1403                 vfree(mem);
1404 }
1405
1406
1407 static struct cgroup_subsys_state *
1408 mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
1409 {
1410         struct mem_cgroup *mem;
1411         int node;
1412
1413         mem = mem_cgroup_alloc();
1414         if (!mem)
1415                 return ERR_PTR(-ENOMEM);
1416
1417         res_counter_init(&mem->res);
1418
1419         for_each_node_state(node, N_POSSIBLE)
1420                 if (alloc_mem_cgroup_per_zone_info(mem, node))
1421                         goto free_out;
1422
1423         return &mem->css;
1424 free_out:
1425         for_each_node_state(node, N_POSSIBLE)
1426                 free_mem_cgroup_per_zone_info(mem, node);
1427         mem_cgroup_free(mem);
1428         return ERR_PTR(-ENOMEM);
1429 }
1430
1431 static void mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
1432                                         struct cgroup *cont)
1433 {
1434         struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
1435         mem_cgroup_force_empty(mem, false);
1436 }
1437
1438 static void mem_cgroup_destroy(struct cgroup_subsys *ss,
1439                                 struct cgroup *cont)
1440 {
1441         int node;
1442         struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
1443
1444         for_each_node_state(node, N_POSSIBLE)
1445                 free_mem_cgroup_per_zone_info(mem, node);
1446
1447         mem_cgroup_free(mem_cgroup_from_cont(cont));
1448 }
1449
1450 static int mem_cgroup_populate(struct cgroup_subsys *ss,
1451                                 struct cgroup *cont)
1452 {
1453         return cgroup_add_files(cont, ss, mem_cgroup_files,
1454                                         ARRAY_SIZE(mem_cgroup_files));
1455 }
1456
1457 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
1458                                 struct cgroup *cont,
1459                                 struct cgroup *old_cont,
1460                                 struct task_struct *p)
1461 {
1462         struct mm_struct *mm;
1463         struct mem_cgroup *mem, *old_mem;
1464
1465         mm = get_task_mm(p);
1466         if (mm == NULL)
1467                 return;
1468
1469         mem = mem_cgroup_from_cont(cont);
1470         old_mem = mem_cgroup_from_cont(old_cont);
1471
1472         /*
1473          * Only thread group leaders are allowed to migrate, the mm_struct is
1474          * in effect owned by the leader
1475          */
1476         if (!thread_group_leader(p))
1477                 goto out;
1478
1479 out:
1480         mmput(mm);
1481 }
1482
1483 struct cgroup_subsys mem_cgroup_subsys = {
1484         .name = "memory",
1485         .subsys_id = mem_cgroup_subsys_id,
1486         .create = mem_cgroup_create,
1487         .pre_destroy = mem_cgroup_pre_destroy,
1488         .destroy = mem_cgroup_destroy,
1489         .populate = mem_cgroup_populate,
1490         .attach = mem_cgroup_move_task,
1491         .early_init = 0,
1492 };