memcg: fix mem_cgroup_move_lists locking
[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/smp.h>
25 #include <linux/page-flags.h>
26 #include <linux/backing-dev.h>
27 #include <linux/bit_spinlock.h>
28 #include <linux/rcupdate.h>
29 #include <linux/swap.h>
30 #include <linux/spinlock.h>
31 #include <linux/fs.h>
32 #include <linux/seq_file.h>
33
34 #include <asm/uaccess.h>
35
36 struct cgroup_subsys mem_cgroup_subsys;
37 static const int MEM_CGROUP_RECLAIM_RETRIES = 5;
38
39 /*
40  * Statistics for memory cgroup.
41  */
42 enum mem_cgroup_stat_index {
43         /*
44          * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
45          */
46         MEM_CGROUP_STAT_CACHE,     /* # of pages charged as cache */
47         MEM_CGROUP_STAT_RSS,       /* # of pages charged as rss */
48
49         MEM_CGROUP_STAT_NSTATS,
50 };
51
52 struct mem_cgroup_stat_cpu {
53         s64 count[MEM_CGROUP_STAT_NSTATS];
54 } ____cacheline_aligned_in_smp;
55
56 struct mem_cgroup_stat {
57         struct mem_cgroup_stat_cpu cpustat[NR_CPUS];
58 };
59
60 /*
61  * For accounting under irq disable, no need for increment preempt count.
62  */
63 static void __mem_cgroup_stat_add_safe(struct mem_cgroup_stat *stat,
64                 enum mem_cgroup_stat_index idx, int val)
65 {
66         int cpu = smp_processor_id();
67         stat->cpustat[cpu].count[idx] += val;
68 }
69
70 static s64 mem_cgroup_read_stat(struct mem_cgroup_stat *stat,
71                 enum mem_cgroup_stat_index idx)
72 {
73         int cpu;
74         s64 ret = 0;
75         for_each_possible_cpu(cpu)
76                 ret += stat->cpustat[cpu].count[idx];
77         return ret;
78 }
79
80 /*
81  * per-zone information in memory controller.
82  */
83
84 enum mem_cgroup_zstat_index {
85         MEM_CGROUP_ZSTAT_ACTIVE,
86         MEM_CGROUP_ZSTAT_INACTIVE,
87
88         NR_MEM_CGROUP_ZSTAT,
89 };
90
91 struct mem_cgroup_per_zone {
92         /*
93          * spin_lock to protect the per cgroup LRU
94          */
95         spinlock_t              lru_lock;
96         struct list_head        active_list;
97         struct list_head        inactive_list;
98         unsigned long count[NR_MEM_CGROUP_ZSTAT];
99 };
100 /* Macro for accessing counter */
101 #define MEM_CGROUP_ZSTAT(mz, idx)       ((mz)->count[(idx)])
102
103 struct mem_cgroup_per_node {
104         struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
105 };
106
107 struct mem_cgroup_lru_info {
108         struct mem_cgroup_per_node *nodeinfo[MAX_NUMNODES];
109 };
110
111 /*
112  * The memory controller data structure. The memory controller controls both
113  * page cache and RSS per cgroup. We would eventually like to provide
114  * statistics based on the statistics developed by Rik Van Riel for clock-pro,
115  * to help the administrator determine what knobs to tune.
116  *
117  * TODO: Add a water mark for the memory controller. Reclaim will begin when
118  * we hit the water mark. May be even add a low water mark, such that
119  * no reclaim occurs from a cgroup at it's low water mark, this is
120  * a feature that will be implemented much later in the future.
121  */
122 struct mem_cgroup {
123         struct cgroup_subsys_state css;
124         /*
125          * the counter to account for memory usage
126          */
127         struct res_counter res;
128         /*
129          * Per cgroup active and inactive list, similar to the
130          * per zone LRU lists.
131          */
132         struct mem_cgroup_lru_info info;
133
134         int     prev_priority;  /* for recording reclaim priority */
135         /*
136          * statistics.
137          */
138         struct mem_cgroup_stat stat;
139 };
140 static struct mem_cgroup init_mem_cgroup;
141
142 /*
143  * We use the lower bit of the page->page_cgroup pointer as a bit spin
144  * lock.  We need to ensure that page->page_cgroup is at least two
145  * byte aligned (based on comments from Nick Piggin).  But since
146  * bit_spin_lock doesn't actually set that lock bit in a non-debug
147  * uniprocessor kernel, we should avoid setting it here too.
148  */
149 #define PAGE_CGROUP_LOCK_BIT    0x0
150 #if defined(CONFIG_SMP) || defined(CONFIG_DEBUG_SPINLOCK)
151 #define PAGE_CGROUP_LOCK        (1 << PAGE_CGROUP_LOCK_BIT)
152 #else
153 #define PAGE_CGROUP_LOCK        0x0
154 #endif
155
156 /*
157  * A page_cgroup page is associated with every page descriptor. The
158  * page_cgroup helps us identify information about the cgroup
159  */
160 struct page_cgroup {
161         struct list_head lru;           /* per cgroup LRU list */
162         struct page *page;
163         struct mem_cgroup *mem_cgroup;
164         int ref_cnt;                    /* cached, mapped, migrating */
165         int flags;
166 };
167 #define PAGE_CGROUP_FLAG_CACHE  (0x1)   /* charged as cache */
168 #define PAGE_CGROUP_FLAG_ACTIVE (0x2)   /* page is active in this cgroup */
169
170 static int page_cgroup_nid(struct page_cgroup *pc)
171 {
172         return page_to_nid(pc->page);
173 }
174
175 static enum zone_type page_cgroup_zid(struct page_cgroup *pc)
176 {
177         return page_zonenum(pc->page);
178 }
179
180 enum charge_type {
181         MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
182         MEM_CGROUP_CHARGE_TYPE_MAPPED,
183 };
184
185 /*
186  * Always modified under lru lock. Then, not necessary to preempt_disable()
187  */
188 static void mem_cgroup_charge_statistics(struct mem_cgroup *mem, int flags,
189                                         bool charge)
190 {
191         int val = (charge)? 1 : -1;
192         struct mem_cgroup_stat *stat = &mem->stat;
193
194         VM_BUG_ON(!irqs_disabled());
195         if (flags & PAGE_CGROUP_FLAG_CACHE)
196                 __mem_cgroup_stat_add_safe(stat, MEM_CGROUP_STAT_CACHE, val);
197         else
198                 __mem_cgroup_stat_add_safe(stat, MEM_CGROUP_STAT_RSS, val);
199 }
200
201 static struct mem_cgroup_per_zone *
202 mem_cgroup_zoneinfo(struct mem_cgroup *mem, int nid, int zid)
203 {
204         return &mem->info.nodeinfo[nid]->zoneinfo[zid];
205 }
206
207 static struct mem_cgroup_per_zone *
208 page_cgroup_zoneinfo(struct page_cgroup *pc)
209 {
210         struct mem_cgroup *mem = pc->mem_cgroup;
211         int nid = page_cgroup_nid(pc);
212         int zid = page_cgroup_zid(pc);
213
214         return mem_cgroup_zoneinfo(mem, nid, zid);
215 }
216
217 static unsigned long mem_cgroup_get_all_zonestat(struct mem_cgroup *mem,
218                                         enum mem_cgroup_zstat_index idx)
219 {
220         int nid, zid;
221         struct mem_cgroup_per_zone *mz;
222         u64 total = 0;
223
224         for_each_online_node(nid)
225                 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
226                         mz = mem_cgroup_zoneinfo(mem, nid, zid);
227                         total += MEM_CGROUP_ZSTAT(mz, idx);
228                 }
229         return total;
230 }
231
232 static struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
233 {
234         return container_of(cgroup_subsys_state(cont,
235                                 mem_cgroup_subsys_id), struct mem_cgroup,
236                                 css);
237 }
238
239 static struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
240 {
241         return container_of(task_subsys_state(p, mem_cgroup_subsys_id),
242                                 struct mem_cgroup, css);
243 }
244
245 void mm_init_cgroup(struct mm_struct *mm, struct task_struct *p)
246 {
247         struct mem_cgroup *mem;
248
249         mem = mem_cgroup_from_task(p);
250         css_get(&mem->css);
251         mm->mem_cgroup = mem;
252 }
253
254 void mm_free_cgroup(struct mm_struct *mm)
255 {
256         css_put(&mm->mem_cgroup->css);
257 }
258
259 static inline int page_cgroup_locked(struct page *page)
260 {
261         return bit_spin_is_locked(PAGE_CGROUP_LOCK_BIT, &page->page_cgroup);
262 }
263
264 static void page_assign_page_cgroup(struct page *page, struct page_cgroup *pc)
265 {
266         VM_BUG_ON(!page_cgroup_locked(page));
267         page->page_cgroup = ((unsigned long)pc | PAGE_CGROUP_LOCK);
268 }
269
270 struct page_cgroup *page_get_page_cgroup(struct page *page)
271 {
272         return (struct page_cgroup *) (page->page_cgroup & ~PAGE_CGROUP_LOCK);
273 }
274
275 static void lock_page_cgroup(struct page *page)
276 {
277         bit_spin_lock(PAGE_CGROUP_LOCK_BIT, &page->page_cgroup);
278 }
279
280 static int try_lock_page_cgroup(struct page *page)
281 {
282         return bit_spin_trylock(PAGE_CGROUP_LOCK_BIT, &page->page_cgroup);
283 }
284
285 static void unlock_page_cgroup(struct page *page)
286 {
287         bit_spin_unlock(PAGE_CGROUP_LOCK_BIT, &page->page_cgroup);
288 }
289
290 static void __mem_cgroup_remove_list(struct page_cgroup *pc)
291 {
292         int from = pc->flags & PAGE_CGROUP_FLAG_ACTIVE;
293         struct mem_cgroup_per_zone *mz = page_cgroup_zoneinfo(pc);
294
295         if (from)
296                 MEM_CGROUP_ZSTAT(mz, MEM_CGROUP_ZSTAT_ACTIVE) -= 1;
297         else
298                 MEM_CGROUP_ZSTAT(mz, MEM_CGROUP_ZSTAT_INACTIVE) -= 1;
299
300         mem_cgroup_charge_statistics(pc->mem_cgroup, pc->flags, false);
301         list_del_init(&pc->lru);
302 }
303
304 static void __mem_cgroup_add_list(struct page_cgroup *pc)
305 {
306         int to = pc->flags & PAGE_CGROUP_FLAG_ACTIVE;
307         struct mem_cgroup_per_zone *mz = page_cgroup_zoneinfo(pc);
308
309         if (!to) {
310                 MEM_CGROUP_ZSTAT(mz, MEM_CGROUP_ZSTAT_INACTIVE) += 1;
311                 list_add(&pc->lru, &mz->inactive_list);
312         } else {
313                 MEM_CGROUP_ZSTAT(mz, MEM_CGROUP_ZSTAT_ACTIVE) += 1;
314                 list_add(&pc->lru, &mz->active_list);
315         }
316         mem_cgroup_charge_statistics(pc->mem_cgroup, pc->flags, true);
317 }
318
319 static void __mem_cgroup_move_lists(struct page_cgroup *pc, bool active)
320 {
321         int from = pc->flags & PAGE_CGROUP_FLAG_ACTIVE;
322         struct mem_cgroup_per_zone *mz = page_cgroup_zoneinfo(pc);
323
324         if (from)
325                 MEM_CGROUP_ZSTAT(mz, MEM_CGROUP_ZSTAT_ACTIVE) -= 1;
326         else
327                 MEM_CGROUP_ZSTAT(mz, MEM_CGROUP_ZSTAT_INACTIVE) -= 1;
328
329         if (active) {
330                 MEM_CGROUP_ZSTAT(mz, MEM_CGROUP_ZSTAT_ACTIVE) += 1;
331                 pc->flags |= PAGE_CGROUP_FLAG_ACTIVE;
332                 list_move(&pc->lru, &mz->active_list);
333         } else {
334                 MEM_CGROUP_ZSTAT(mz, MEM_CGROUP_ZSTAT_INACTIVE) += 1;
335                 pc->flags &= ~PAGE_CGROUP_FLAG_ACTIVE;
336                 list_move(&pc->lru, &mz->inactive_list);
337         }
338 }
339
340 int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *mem)
341 {
342         int ret;
343
344         task_lock(task);
345         ret = task->mm && mm_match_cgroup(task->mm, mem);
346         task_unlock(task);
347         return ret;
348 }
349
350 /*
351  * This routine assumes that the appropriate zone's lru lock is already held
352  */
353 void mem_cgroup_move_lists(struct page *page, bool active)
354 {
355         struct page_cgroup *pc;
356         struct mem_cgroup *mem;
357         struct mem_cgroup_per_zone *mz;
358         unsigned long flags;
359
360         /*
361          * We cannot lock_page_cgroup while holding zone's lru_lock,
362          * because other holders of lock_page_cgroup can be interrupted
363          * with an attempt to rotate_reclaimable_page.  But we cannot
364          * safely get to page_cgroup without it, so just try_lock it:
365          * mem_cgroup_isolate_pages allows for page left on wrong list.
366          */
367         if (!try_lock_page_cgroup(page))
368                 return;
369
370         /*
371          * Now page_cgroup is stable, but we cannot acquire mz->lru_lock
372          * while holding it, because mem_cgroup_force_empty_list does the
373          * reverse.  Get a hold on the mem_cgroup before unlocking, so that
374          * the zoneinfo remains stable, then take mz->lru_lock; then check
375          * that page still points to pc and pc (even if freed and reassigned
376          * to that same page meanwhile) still points to the same mem_cgroup.
377          * Then we know mz still points to the right spinlock, so it's safe
378          * to move_lists (page->page_cgroup might be reset while we do so, but
379          * that doesn't matter: pc->page is stable till we drop mz->lru_lock).
380          * We're being a little naughty not to try_lock_page_cgroup again
381          * inside there, but we are safe, aren't we?  Aren't we?  Whistle...
382          */
383         pc = page_get_page_cgroup(page);
384         if (pc) {
385                 mem = pc->mem_cgroup;
386                 mz = page_cgroup_zoneinfo(pc);
387                 css_get(&mem->css);
388
389                 unlock_page_cgroup(page);
390
391                 spin_lock_irqsave(&mz->lru_lock, flags);
392                 if (page_get_page_cgroup(page) == pc && pc->mem_cgroup == mem)
393                         __mem_cgroup_move_lists(pc, active);
394                 spin_unlock_irqrestore(&mz->lru_lock, flags);
395
396                 css_put(&mem->css);
397         } else
398                 unlock_page_cgroup(page);
399 }
400
401 /*
402  * Calculate mapped_ratio under memory controller. This will be used in
403  * vmscan.c for deteremining we have to reclaim mapped pages.
404  */
405 int mem_cgroup_calc_mapped_ratio(struct mem_cgroup *mem)
406 {
407         long total, rss;
408
409         /*
410          * usage is recorded in bytes. But, here, we assume the number of
411          * physical pages can be represented by "long" on any arch.
412          */
413         total = (long) (mem->res.usage >> PAGE_SHIFT) + 1L;
414         rss = (long)mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_RSS);
415         return (int)((rss * 100L) / total);
416 }
417
418 /*
419  * This function is called from vmscan.c. In page reclaiming loop. balance
420  * between active and inactive list is calculated. For memory controller
421  * page reclaiming, we should use using mem_cgroup's imbalance rather than
422  * zone's global lru imbalance.
423  */
424 long mem_cgroup_reclaim_imbalance(struct mem_cgroup *mem)
425 {
426         unsigned long active, inactive;
427         /* active and inactive are the number of pages. 'long' is ok.*/
428         active = mem_cgroup_get_all_zonestat(mem, MEM_CGROUP_ZSTAT_ACTIVE);
429         inactive = mem_cgroup_get_all_zonestat(mem, MEM_CGROUP_ZSTAT_INACTIVE);
430         return (long) (active / (inactive + 1));
431 }
432
433 /*
434  * prev_priority control...this will be used in memory reclaim path.
435  */
436 int mem_cgroup_get_reclaim_priority(struct mem_cgroup *mem)
437 {
438         return mem->prev_priority;
439 }
440
441 void mem_cgroup_note_reclaim_priority(struct mem_cgroup *mem, int priority)
442 {
443         if (priority < mem->prev_priority)
444                 mem->prev_priority = priority;
445 }
446
447 void mem_cgroup_record_reclaim_priority(struct mem_cgroup *mem, int priority)
448 {
449         mem->prev_priority = priority;
450 }
451
452 /*
453  * Calculate # of pages to be scanned in this priority/zone.
454  * See also vmscan.c
455  *
456  * priority starts from "DEF_PRIORITY" and decremented in each loop.
457  * (see include/linux/mmzone.h)
458  */
459
460 long mem_cgroup_calc_reclaim_active(struct mem_cgroup *mem,
461                                    struct zone *zone, int priority)
462 {
463         long nr_active;
464         int nid = zone->zone_pgdat->node_id;
465         int zid = zone_idx(zone);
466         struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(mem, nid, zid);
467
468         nr_active = MEM_CGROUP_ZSTAT(mz, MEM_CGROUP_ZSTAT_ACTIVE);
469         return (nr_active >> priority);
470 }
471
472 long mem_cgroup_calc_reclaim_inactive(struct mem_cgroup *mem,
473                                         struct zone *zone, int priority)
474 {
475         long nr_inactive;
476         int nid = zone->zone_pgdat->node_id;
477         int zid = zone_idx(zone);
478         struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(mem, nid, zid);
479
480         nr_inactive = MEM_CGROUP_ZSTAT(mz, MEM_CGROUP_ZSTAT_INACTIVE);
481         return (nr_inactive >> priority);
482 }
483
484 unsigned long mem_cgroup_isolate_pages(unsigned long nr_to_scan,
485                                         struct list_head *dst,
486                                         unsigned long *scanned, int order,
487                                         int mode, struct zone *z,
488                                         struct mem_cgroup *mem_cont,
489                                         int active)
490 {
491         unsigned long nr_taken = 0;
492         struct page *page;
493         unsigned long scan;
494         LIST_HEAD(pc_list);
495         struct list_head *src;
496         struct page_cgroup *pc, *tmp;
497         int nid = z->zone_pgdat->node_id;
498         int zid = zone_idx(z);
499         struct mem_cgroup_per_zone *mz;
500
501         mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
502         if (active)
503                 src = &mz->active_list;
504         else
505                 src = &mz->inactive_list;
506
507
508         spin_lock(&mz->lru_lock);
509         scan = 0;
510         list_for_each_entry_safe_reverse(pc, tmp, src, lru) {
511                 if (scan >= nr_to_scan)
512                         break;
513                 page = pc->page;
514
515                 if (unlikely(!PageLRU(page)))
516                         continue;
517
518                 if (PageActive(page) && !active) {
519                         __mem_cgroup_move_lists(pc, true);
520                         continue;
521                 }
522                 if (!PageActive(page) && active) {
523                         __mem_cgroup_move_lists(pc, false);
524                         continue;
525                 }
526
527                 scan++;
528                 list_move(&pc->lru, &pc_list);
529
530                 if (__isolate_lru_page(page, mode) == 0) {
531                         list_move(&page->lru, dst);
532                         nr_taken++;
533                 }
534         }
535
536         list_splice(&pc_list, src);
537         spin_unlock(&mz->lru_lock);
538
539         *scanned = scan;
540         return nr_taken;
541 }
542
543 /*
544  * Charge the memory controller for page usage.
545  * Return
546  * 0 if the charge was successful
547  * < 0 if the cgroup is over its limit
548  */
549 static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
550                                 gfp_t gfp_mask, enum charge_type ctype)
551 {
552         struct mem_cgroup *mem;
553         struct page_cgroup *pc;
554         unsigned long flags;
555         unsigned long nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
556         struct mem_cgroup_per_zone *mz;
557
558         /*
559          * Should page_cgroup's go to their own slab?
560          * One could optimize the performance of the charging routine
561          * by saving a bit in the page_flags and using it as a lock
562          * to see if the cgroup page already has a page_cgroup associated
563          * with it
564          */
565 retry:
566         lock_page_cgroup(page);
567         pc = page_get_page_cgroup(page);
568         /*
569          * The page_cgroup exists and
570          * the page has already been accounted.
571          */
572         if (pc) {
573                 VM_BUG_ON(pc->page != page);
574                 VM_BUG_ON(pc->ref_cnt <= 0);
575
576                 pc->ref_cnt++;
577                 unlock_page_cgroup(page);
578                 goto done;
579         }
580         unlock_page_cgroup(page);
581
582         pc = kzalloc(sizeof(struct page_cgroup), gfp_mask);
583         if (pc == NULL)
584                 goto err;
585
586         /*
587          * We always charge the cgroup the mm_struct belongs to.
588          * The mm_struct's mem_cgroup changes on task migration if the
589          * thread group leader migrates. It's possible that mm is not
590          * set, if so charge the init_mm (happens for pagecache usage).
591          */
592         if (!mm)
593                 mm = &init_mm;
594
595         rcu_read_lock();
596         mem = rcu_dereference(mm->mem_cgroup);
597         /*
598          * For every charge from the cgroup, increment reference count
599          */
600         css_get(&mem->css);
601         rcu_read_unlock();
602
603         while (res_counter_charge(&mem->res, PAGE_SIZE)) {
604                 if (!(gfp_mask & __GFP_WAIT))
605                         goto out;
606
607                 if (try_to_free_mem_cgroup_pages(mem, gfp_mask))
608                         continue;
609
610                 /*
611                  * try_to_free_mem_cgroup_pages() might not give us a full
612                  * picture of reclaim. Some pages are reclaimed and might be
613                  * moved to swap cache or just unmapped from the cgroup.
614                  * Check the limit again to see if the reclaim reduced the
615                  * current usage of the cgroup before giving up
616                  */
617                 if (res_counter_check_under_limit(&mem->res))
618                         continue;
619
620                 if (!nr_retries--) {
621                         mem_cgroup_out_of_memory(mem, gfp_mask);
622                         goto out;
623                 }
624                 congestion_wait(WRITE, HZ/10);
625         }
626
627         pc->ref_cnt = 1;
628         pc->mem_cgroup = mem;
629         pc->page = page;
630         pc->flags = PAGE_CGROUP_FLAG_ACTIVE;
631         if (ctype == MEM_CGROUP_CHARGE_TYPE_CACHE)
632                 pc->flags |= PAGE_CGROUP_FLAG_CACHE;
633
634         lock_page_cgroup(page);
635         if (page_get_page_cgroup(page)) {
636                 unlock_page_cgroup(page);
637                 /*
638                  * Another charge has been added to this page already.
639                  * We take lock_page_cgroup(page) again and read
640                  * page->cgroup, increment refcnt.... just retry is OK.
641                  */
642                 res_counter_uncharge(&mem->res, PAGE_SIZE);
643                 css_put(&mem->css);
644                 kfree(pc);
645                 goto retry;
646         }
647         page_assign_page_cgroup(page, pc);
648         unlock_page_cgroup(page);
649
650         mz = page_cgroup_zoneinfo(pc);
651         spin_lock_irqsave(&mz->lru_lock, flags);
652         __mem_cgroup_add_list(pc);
653         spin_unlock_irqrestore(&mz->lru_lock, flags);
654
655 done:
656         return 0;
657 out:
658         css_put(&mem->css);
659         kfree(pc);
660 err:
661         return -ENOMEM;
662 }
663
664 int mem_cgroup_charge(struct page *page, struct mm_struct *mm, gfp_t gfp_mask)
665 {
666         return mem_cgroup_charge_common(page, mm, gfp_mask,
667                                 MEM_CGROUP_CHARGE_TYPE_MAPPED);
668 }
669
670 int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
671                                 gfp_t gfp_mask)
672 {
673         if (!mm)
674                 mm = &init_mm;
675         return mem_cgroup_charge_common(page, mm, gfp_mask,
676                                 MEM_CGROUP_CHARGE_TYPE_CACHE);
677 }
678
679 /*
680  * Uncharging is always a welcome operation, we never complain, simply
681  * uncharge.
682  */
683 void mem_cgroup_uncharge_page(struct page *page)
684 {
685         struct page_cgroup *pc;
686         struct mem_cgroup *mem;
687         struct mem_cgroup_per_zone *mz;
688         unsigned long flags;
689
690         /*
691          * Check if our page_cgroup is valid
692          */
693         lock_page_cgroup(page);
694         pc = page_get_page_cgroup(page);
695         if (!pc)
696                 goto unlock;
697
698         VM_BUG_ON(pc->page != page);
699         VM_BUG_ON(pc->ref_cnt <= 0);
700
701         if (--(pc->ref_cnt) == 0) {
702                 page_assign_page_cgroup(page, NULL);
703                 unlock_page_cgroup(page);
704
705                 mz = page_cgroup_zoneinfo(pc);
706                 spin_lock_irqsave(&mz->lru_lock, flags);
707                 __mem_cgroup_remove_list(pc);
708                 spin_unlock_irqrestore(&mz->lru_lock, flags);
709
710                 mem = pc->mem_cgroup;
711                 res_counter_uncharge(&mem->res, PAGE_SIZE);
712                 css_put(&mem->css);
713
714                 kfree(pc);
715                 return;
716         }
717
718 unlock:
719         unlock_page_cgroup(page);
720 }
721
722 /*
723  * Returns non-zero if a page (under migration) has valid page_cgroup member.
724  * Refcnt of page_cgroup is incremented.
725  */
726 int mem_cgroup_prepare_migration(struct page *page)
727 {
728         struct page_cgroup *pc;
729
730         lock_page_cgroup(page);
731         pc = page_get_page_cgroup(page);
732         if (pc)
733                 pc->ref_cnt++;
734         unlock_page_cgroup(page);
735         return pc != NULL;
736 }
737
738 void mem_cgroup_end_migration(struct page *page)
739 {
740         mem_cgroup_uncharge_page(page);
741 }
742
743 /*
744  * We know both *page* and *newpage* are now not-on-LRU and PG_locked.
745  * And no race with uncharge() routines because page_cgroup for *page*
746  * has extra one reference by mem_cgroup_prepare_migration.
747  */
748 void mem_cgroup_page_migration(struct page *page, struct page *newpage)
749 {
750         struct page_cgroup *pc;
751         struct mem_cgroup_per_zone *mz;
752         unsigned long flags;
753
754         lock_page_cgroup(page);
755         pc = page_get_page_cgroup(page);
756         if (!pc) {
757                 unlock_page_cgroup(page);
758                 return;
759         }
760
761         page_assign_page_cgroup(page, NULL);
762         unlock_page_cgroup(page);
763
764         mz = page_cgroup_zoneinfo(pc);
765         spin_lock_irqsave(&mz->lru_lock, flags);
766         __mem_cgroup_remove_list(pc);
767         spin_unlock_irqrestore(&mz->lru_lock, flags);
768
769         pc->page = newpage;
770         lock_page_cgroup(newpage);
771         page_assign_page_cgroup(newpage, pc);
772         unlock_page_cgroup(newpage);
773
774         mz = page_cgroup_zoneinfo(pc);
775         spin_lock_irqsave(&mz->lru_lock, flags);
776         __mem_cgroup_add_list(pc);
777         spin_unlock_irqrestore(&mz->lru_lock, flags);
778 }
779
780 /*
781  * This routine traverse page_cgroup in given list and drop them all.
782  * This routine ignores page_cgroup->ref_cnt.
783  * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
784  */
785 #define FORCE_UNCHARGE_BATCH    (128)
786 static void mem_cgroup_force_empty_list(struct mem_cgroup *mem,
787                             struct mem_cgroup_per_zone *mz,
788                             int active)
789 {
790         struct page_cgroup *pc;
791         struct page *page;
792         int count;
793         unsigned long flags;
794         struct list_head *list;
795
796         if (active)
797                 list = &mz->active_list;
798         else
799                 list = &mz->inactive_list;
800
801         if (list_empty(list))
802                 return;
803 retry:
804         count = FORCE_UNCHARGE_BATCH;
805         spin_lock_irqsave(&mz->lru_lock, flags);
806
807         while (--count && !list_empty(list)) {
808                 pc = list_entry(list->prev, struct page_cgroup, lru);
809                 page = pc->page;
810                 lock_page_cgroup(page);
811                 if (page_get_page_cgroup(page) == pc) {
812                         page_assign_page_cgroup(page, NULL);
813                         unlock_page_cgroup(page);
814                         __mem_cgroup_remove_list(pc);
815                         res_counter_uncharge(&mem->res, PAGE_SIZE);
816                         css_put(&mem->css);
817                         kfree(pc);
818                 } else {
819                         /* racing uncharge: let page go then retry */
820                         unlock_page_cgroup(page);
821                         break;
822                 }
823         }
824
825         spin_unlock_irqrestore(&mz->lru_lock, flags);
826         if (!list_empty(list)) {
827                 cond_resched();
828                 goto retry;
829         }
830 }
831
832 /*
833  * make mem_cgroup's charge to be 0 if there is no task.
834  * This enables deleting this mem_cgroup.
835  */
836 static int mem_cgroup_force_empty(struct mem_cgroup *mem)
837 {
838         int ret = -EBUSY;
839         int node, zid;
840
841         css_get(&mem->css);
842         /*
843          * page reclaim code (kswapd etc..) will move pages between
844          * active_list <-> inactive_list while we don't take a lock.
845          * So, we have to do loop here until all lists are empty.
846          */
847         while (mem->res.usage > 0) {
848                 if (atomic_read(&mem->css.cgroup->count) > 0)
849                         goto out;
850                 for_each_node_state(node, N_POSSIBLE)
851                         for (zid = 0; zid < MAX_NR_ZONES; zid++) {
852                                 struct mem_cgroup_per_zone *mz;
853                                 mz = mem_cgroup_zoneinfo(mem, node, zid);
854                                 /* drop all page_cgroup in active_list */
855                                 mem_cgroup_force_empty_list(mem, mz, 1);
856                                 /* drop all page_cgroup in inactive_list */
857                                 mem_cgroup_force_empty_list(mem, mz, 0);
858                         }
859         }
860         ret = 0;
861 out:
862         css_put(&mem->css);
863         return ret;
864 }
865
866 static int mem_cgroup_write_strategy(char *buf, unsigned long long *tmp)
867 {
868         *tmp = memparse(buf, &buf);
869         if (*buf != '\0')
870                 return -EINVAL;
871
872         /*
873          * Round up the value to the closest page size
874          */
875         *tmp = ((*tmp + PAGE_SIZE - 1) >> PAGE_SHIFT) << PAGE_SHIFT;
876         return 0;
877 }
878
879 static ssize_t mem_cgroup_read(struct cgroup *cont,
880                         struct cftype *cft, struct file *file,
881                         char __user *userbuf, size_t nbytes, loff_t *ppos)
882 {
883         return res_counter_read(&mem_cgroup_from_cont(cont)->res,
884                                 cft->private, userbuf, nbytes, ppos,
885                                 NULL);
886 }
887
888 static ssize_t mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
889                                 struct file *file, const char __user *userbuf,
890                                 size_t nbytes, loff_t *ppos)
891 {
892         return res_counter_write(&mem_cgroup_from_cont(cont)->res,
893                                 cft->private, userbuf, nbytes, ppos,
894                                 mem_cgroup_write_strategy);
895 }
896
897 static ssize_t mem_force_empty_write(struct cgroup *cont,
898                                 struct cftype *cft, struct file *file,
899                                 const char __user *userbuf,
900                                 size_t nbytes, loff_t *ppos)
901 {
902         struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
903         int ret = mem_cgroup_force_empty(mem);
904         if (!ret)
905                 ret = nbytes;
906         return ret;
907 }
908
909 /*
910  * Note: This should be removed if cgroup supports write-only file.
911  */
912 static ssize_t mem_force_empty_read(struct cgroup *cont,
913                                 struct cftype *cft,
914                                 struct file *file, char __user *userbuf,
915                                 size_t nbytes, loff_t *ppos)
916 {
917         return -EINVAL;
918 }
919
920 static const struct mem_cgroup_stat_desc {
921         const char *msg;
922         u64 unit;
923 } mem_cgroup_stat_desc[] = {
924         [MEM_CGROUP_STAT_CACHE] = { "cache", PAGE_SIZE, },
925         [MEM_CGROUP_STAT_RSS] = { "rss", PAGE_SIZE, },
926 };
927
928 static int mem_control_stat_show(struct seq_file *m, void *arg)
929 {
930         struct cgroup *cont = m->private;
931         struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
932         struct mem_cgroup_stat *stat = &mem_cont->stat;
933         int i;
934
935         for (i = 0; i < ARRAY_SIZE(stat->cpustat[0].count); i++) {
936                 s64 val;
937
938                 val = mem_cgroup_read_stat(stat, i);
939                 val *= mem_cgroup_stat_desc[i].unit;
940                 seq_printf(m, "%s %lld\n", mem_cgroup_stat_desc[i].msg,
941                                 (long long)val);
942         }
943         /* showing # of active pages */
944         {
945                 unsigned long active, inactive;
946
947                 inactive = mem_cgroup_get_all_zonestat(mem_cont,
948                                                 MEM_CGROUP_ZSTAT_INACTIVE);
949                 active = mem_cgroup_get_all_zonestat(mem_cont,
950                                                 MEM_CGROUP_ZSTAT_ACTIVE);
951                 seq_printf(m, "active %ld\n", (active) * PAGE_SIZE);
952                 seq_printf(m, "inactive %ld\n", (inactive) * PAGE_SIZE);
953         }
954         return 0;
955 }
956
957 static const struct file_operations mem_control_stat_file_operations = {
958         .read = seq_read,
959         .llseek = seq_lseek,
960         .release = single_release,
961 };
962
963 static int mem_control_stat_open(struct inode *unused, struct file *file)
964 {
965         /* XXX __d_cont */
966         struct cgroup *cont = file->f_dentry->d_parent->d_fsdata;
967
968         file->f_op = &mem_control_stat_file_operations;
969         return single_open(file, mem_control_stat_show, cont);
970 }
971
972 static struct cftype mem_cgroup_files[] = {
973         {
974                 .name = "usage_in_bytes",
975                 .private = RES_USAGE,
976                 .read = mem_cgroup_read,
977         },
978         {
979                 .name = "limit_in_bytes",
980                 .private = RES_LIMIT,
981                 .write = mem_cgroup_write,
982                 .read = mem_cgroup_read,
983         },
984         {
985                 .name = "failcnt",
986                 .private = RES_FAILCNT,
987                 .read = mem_cgroup_read,
988         },
989         {
990                 .name = "force_empty",
991                 .write = mem_force_empty_write,
992                 .read = mem_force_empty_read,
993         },
994         {
995                 .name = "stat",
996                 .open = mem_control_stat_open,
997         },
998 };
999
1000 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
1001 {
1002         struct mem_cgroup_per_node *pn;
1003         struct mem_cgroup_per_zone *mz;
1004         int zone;
1005         /*
1006          * This routine is called against possible nodes.
1007          * But it's BUG to call kmalloc() against offline node.
1008          *
1009          * TODO: this routine can waste much memory for nodes which will
1010          *       never be onlined. It's better to use memory hotplug callback
1011          *       function.
1012          */
1013         if (node_state(node, N_HIGH_MEMORY))
1014                 pn = kmalloc_node(sizeof(*pn), GFP_KERNEL, node);
1015         else
1016                 pn = kmalloc(sizeof(*pn), GFP_KERNEL);
1017         if (!pn)
1018                 return 1;
1019
1020         mem->info.nodeinfo[node] = pn;
1021         memset(pn, 0, sizeof(*pn));
1022
1023         for (zone = 0; zone < MAX_NR_ZONES; zone++) {
1024                 mz = &pn->zoneinfo[zone];
1025                 INIT_LIST_HEAD(&mz->active_list);
1026                 INIT_LIST_HEAD(&mz->inactive_list);
1027                 spin_lock_init(&mz->lru_lock);
1028         }
1029         return 0;
1030 }
1031
1032 static void free_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
1033 {
1034         kfree(mem->info.nodeinfo[node]);
1035 }
1036
1037 static struct cgroup_subsys_state *
1038 mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
1039 {
1040         struct mem_cgroup *mem;
1041         int node;
1042
1043         if (unlikely((cont->parent) == NULL)) {
1044                 mem = &init_mem_cgroup;
1045                 init_mm.mem_cgroup = mem;
1046         } else
1047                 mem = kzalloc(sizeof(struct mem_cgroup), GFP_KERNEL);
1048
1049         if (mem == NULL)
1050                 return ERR_PTR(-ENOMEM);
1051
1052         res_counter_init(&mem->res);
1053
1054         memset(&mem->info, 0, sizeof(mem->info));
1055
1056         for_each_node_state(node, N_POSSIBLE)
1057                 if (alloc_mem_cgroup_per_zone_info(mem, node))
1058                         goto free_out;
1059
1060         return &mem->css;
1061 free_out:
1062         for_each_node_state(node, N_POSSIBLE)
1063                 free_mem_cgroup_per_zone_info(mem, node);
1064         if (cont->parent != NULL)
1065                 kfree(mem);
1066         return ERR_PTR(-ENOMEM);
1067 }
1068
1069 static void mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
1070                                         struct cgroup *cont)
1071 {
1072         struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
1073         mem_cgroup_force_empty(mem);
1074 }
1075
1076 static void mem_cgroup_destroy(struct cgroup_subsys *ss,
1077                                 struct cgroup *cont)
1078 {
1079         int node;
1080         struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
1081
1082         for_each_node_state(node, N_POSSIBLE)
1083                 free_mem_cgroup_per_zone_info(mem, node);
1084
1085         kfree(mem_cgroup_from_cont(cont));
1086 }
1087
1088 static int mem_cgroup_populate(struct cgroup_subsys *ss,
1089                                 struct cgroup *cont)
1090 {
1091         return cgroup_add_files(cont, ss, mem_cgroup_files,
1092                                         ARRAY_SIZE(mem_cgroup_files));
1093 }
1094
1095 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
1096                                 struct cgroup *cont,
1097                                 struct cgroup *old_cont,
1098                                 struct task_struct *p)
1099 {
1100         struct mm_struct *mm;
1101         struct mem_cgroup *mem, *old_mem;
1102
1103         mm = get_task_mm(p);
1104         if (mm == NULL)
1105                 return;
1106
1107         mem = mem_cgroup_from_cont(cont);
1108         old_mem = mem_cgroup_from_cont(old_cont);
1109
1110         if (mem == old_mem)
1111                 goto out;
1112
1113         /*
1114          * Only thread group leaders are allowed to migrate, the mm_struct is
1115          * in effect owned by the leader
1116          */
1117         if (p->tgid != p->pid)
1118                 goto out;
1119
1120         css_get(&mem->css);
1121         rcu_assign_pointer(mm->mem_cgroup, mem);
1122         css_put(&old_mem->css);
1123
1124 out:
1125         mmput(mm);
1126 }
1127
1128 struct cgroup_subsys mem_cgroup_subsys = {
1129         .name = "memory",
1130         .subsys_id = mem_cgroup_subsys_id,
1131         .create = mem_cgroup_create,
1132         .pre_destroy = mem_cgroup_pre_destroy,
1133         .destroy = mem_cgroup_destroy,
1134         .populate = mem_cgroup_populate,
1135         .attach = mem_cgroup_move_task,
1136         .early_init = 0,
1137 };