Make FRAME_POINTER default=y, so that people compiling their own kernels
[mmotm.git] / mm / memcontrol.c
blobf8509412b4f3e190819be31bcdaa001236119dff
1 /* memcontrol.c - Memory Controller
3 * Copyright IBM Corporation, 2007
4 * Author Balbir Singh <balbir@linux.vnet.ibm.com>
6 * Copyright 2007 OpenVZ SWsoft Inc
7 * Author: Pavel Emelianov <xemul@openvz.org>
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.
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.
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/limits.h>
31 #include <linux/mutex.h>
32 #include <linux/rbtree.h>
33 #include <linux/slab.h>
34 #include <linux/swap.h>
35 #include <linux/spinlock.h>
36 #include <linux/fs.h>
37 #include <linux/seq_file.h>
38 #include <linux/vmalloc.h>
39 #include <linux/mm_inline.h>
40 #include <linux/page_cgroup.h>
41 #include <linux/cpu.h>
42 #include "internal.h"
44 #include <asm/uaccess.h>
46 struct cgroup_subsys mem_cgroup_subsys __read_mostly;
47 #define MEM_CGROUP_RECLAIM_RETRIES 5
48 struct mem_cgroup *root_mem_cgroup __read_mostly;
50 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
51 /* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
52 int do_swap_account __read_mostly;
53 static int really_do_swap_account __initdata = 1; /* for remember boot option*/
54 #else
55 #define do_swap_account (0)
56 #endif
58 static DEFINE_MUTEX(memcg_tasklist); /* can be hold under cgroup_mutex */
59 #define SOFTLIMIT_EVENTS_THRESH (1000)
62 * Statistics for memory cgroup.
64 enum mem_cgroup_stat_index {
66 * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
68 MEM_CGROUP_STAT_CACHE, /* # of pages charged as cache */
69 MEM_CGROUP_STAT_RSS, /* # of pages charged as anon rss */
70 MEM_CGROUP_STAT_MAPPED_FILE, /* # of pages charged as file rss */
71 MEM_CGROUP_STAT_PGPGIN_COUNT, /* # of pages paged in */
72 MEM_CGROUP_STAT_PGPGOUT_COUNT, /* # of pages paged out */
73 MEM_CGROUP_STAT_EVENTS, /* sum of pagein + pageout for internal use */
74 MEM_CGROUP_STAT_SWAPOUT, /* # of pages, swapped out */
76 MEM_CGROUP_STAT_NSTATS,
79 struct mem_cgroup_stat_cpu {
80 s64 count[MEM_CGROUP_STAT_NSTATS];
81 } ____cacheline_aligned_in_smp;
83 struct mem_cgroup_stat {
84 struct mem_cgroup_stat_cpu cpustat[0];
87 static inline void
88 __mem_cgroup_stat_reset_safe(struct mem_cgroup_stat_cpu *stat,
89 enum mem_cgroup_stat_index idx)
91 stat->count[idx] = 0;
94 static inline s64
95 __mem_cgroup_stat_read_local(struct mem_cgroup_stat_cpu *stat,
96 enum mem_cgroup_stat_index idx)
98 return stat->count[idx];
102 * For accounting under irq disable, no need for increment preempt count.
104 static inline void __mem_cgroup_stat_add_safe(struct mem_cgroup_stat_cpu *stat,
105 enum mem_cgroup_stat_index idx, int val)
107 stat->count[idx] += val;
110 static s64 mem_cgroup_read_stat(struct mem_cgroup_stat *stat,
111 enum mem_cgroup_stat_index idx)
113 int cpu;
114 s64 ret = 0;
115 for_each_possible_cpu(cpu)
116 ret += stat->cpustat[cpu].count[idx];
117 return ret;
120 static s64 mem_cgroup_local_usage(struct mem_cgroup_stat *stat)
122 s64 ret;
124 ret = mem_cgroup_read_stat(stat, MEM_CGROUP_STAT_CACHE);
125 ret += mem_cgroup_read_stat(stat, MEM_CGROUP_STAT_RSS);
126 return ret;
130 * per-zone information in memory controller.
132 struct mem_cgroup_per_zone {
134 * spin_lock to protect the per cgroup LRU
136 struct list_head lists[NR_LRU_LISTS];
137 unsigned long count[NR_LRU_LISTS];
139 struct zone_reclaim_stat reclaim_stat;
140 struct rb_node tree_node; /* RB tree node */
141 unsigned long long usage_in_excess;/* Set to the value by which */
142 /* the soft limit is exceeded*/
143 bool on_tree;
144 struct mem_cgroup *mem; /* Back pointer, we cannot */
145 /* use container_of */
147 /* Macro for accessing counter */
148 #define MEM_CGROUP_ZSTAT(mz, idx) ((mz)->count[(idx)])
150 struct mem_cgroup_per_node {
151 struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
154 struct mem_cgroup_lru_info {
155 struct mem_cgroup_per_node *nodeinfo[MAX_NUMNODES];
159 * Cgroups above their limits are maintained in a RB-Tree, independent of
160 * their hierarchy representation
163 struct mem_cgroup_tree_per_zone {
164 struct rb_root rb_root;
165 spinlock_t lock;
168 struct mem_cgroup_tree_per_node {
169 struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
172 struct mem_cgroup_tree {
173 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
176 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
179 * The memory controller data structure. The memory controller controls both
180 * page cache and RSS per cgroup. We would eventually like to provide
181 * statistics based on the statistics developed by Rik Van Riel for clock-pro,
182 * to help the administrator determine what knobs to tune.
184 * TODO: Add a water mark for the memory controller. Reclaim will begin when
185 * we hit the water mark. May be even add a low water mark, such that
186 * no reclaim occurs from a cgroup at it's low water mark, this is
187 * a feature that will be implemented much later in the future.
189 struct mem_cgroup {
190 struct cgroup_subsys_state css;
192 * the counter to account for memory usage
194 struct res_counter res;
196 * the counter to account for mem+swap usage.
198 struct res_counter memsw;
200 * Per cgroup active and inactive list, similar to the
201 * per zone LRU lists.
203 struct mem_cgroup_lru_info info;
206 protect against reclaim related member.
208 spinlock_t reclaim_param_lock;
210 int prev_priority; /* for recording reclaim priority */
213 * While reclaiming in a hiearchy, we cache the last child we
214 * reclaimed from.
216 int last_scanned_child;
218 * Should the accounting and control be hierarchical, per subtree?
220 bool use_hierarchy;
221 unsigned long last_oom_jiffies;
222 atomic_t refcnt;
224 unsigned int swappiness;
226 /* set when res.limit == memsw.limit */
227 bool memsw_is_minimum;
230 * statistics. This must be placed at the end of memcg.
232 struct mem_cgroup_stat stat;
236 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
237 * limit reclaim to prevent infinite loops, if they ever occur.
239 #define MEM_CGROUP_MAX_RECLAIM_LOOPS (100)
240 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS (2)
242 enum charge_type {
243 MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
244 MEM_CGROUP_CHARGE_TYPE_MAPPED,
245 MEM_CGROUP_CHARGE_TYPE_SHMEM, /* used by page migration of shmem */
246 MEM_CGROUP_CHARGE_TYPE_FORCE, /* used by force_empty */
247 MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
248 MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
249 NR_CHARGE_TYPE,
252 /* only for here (for easy reading.) */
253 #define PCGF_CACHE (1UL << PCG_CACHE)
254 #define PCGF_USED (1UL << PCG_USED)
255 #define PCGF_LOCK (1UL << PCG_LOCK)
256 /* Not used, but added here for completeness */
257 #define PCGF_ACCT (1UL << PCG_ACCT)
259 /* for encoding cft->private value on file */
260 #define _MEM (0)
261 #define _MEMSWAP (1)
262 #define MEMFILE_PRIVATE(x, val) (((x) << 16) | (val))
263 #define MEMFILE_TYPE(val) (((val) >> 16) & 0xffff)
264 #define MEMFILE_ATTR(val) ((val) & 0xffff)
267 * Reclaim flags for mem_cgroup_hierarchical_reclaim
269 #define MEM_CGROUP_RECLAIM_NOSWAP_BIT 0x0
270 #define MEM_CGROUP_RECLAIM_NOSWAP (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
271 #define MEM_CGROUP_RECLAIM_SHRINK_BIT 0x1
272 #define MEM_CGROUP_RECLAIM_SHRINK (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
273 #define MEM_CGROUP_RECLAIM_SOFT_BIT 0x2
274 #define MEM_CGROUP_RECLAIM_SOFT (1 << MEM_CGROUP_RECLAIM_SOFT_BIT)
276 static void mem_cgroup_get(struct mem_cgroup *mem);
277 static void mem_cgroup_put(struct mem_cgroup *mem);
278 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem);
279 static void drain_all_stock_async(void);
281 static struct mem_cgroup_per_zone *
282 mem_cgroup_zoneinfo(struct mem_cgroup *mem, int nid, int zid)
284 return &mem->info.nodeinfo[nid]->zoneinfo[zid];
287 static struct mem_cgroup_per_zone *
288 page_cgroup_zoneinfo(struct page_cgroup *pc)
290 struct mem_cgroup *mem = pc->mem_cgroup;
291 int nid = page_cgroup_nid(pc);
292 int zid = page_cgroup_zid(pc);
294 if (!mem)
295 return NULL;
297 return mem_cgroup_zoneinfo(mem, nid, zid);
300 static struct mem_cgroup_tree_per_zone *
301 soft_limit_tree_node_zone(int nid, int zid)
303 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
306 static struct mem_cgroup_tree_per_zone *
307 soft_limit_tree_from_page(struct page *page)
309 int nid = page_to_nid(page);
310 int zid = page_zonenum(page);
312 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
315 static void
316 __mem_cgroup_insert_exceeded(struct mem_cgroup *mem,
317 struct mem_cgroup_per_zone *mz,
318 struct mem_cgroup_tree_per_zone *mctz,
319 unsigned long long new_usage_in_excess)
321 struct rb_node **p = &mctz->rb_root.rb_node;
322 struct rb_node *parent = NULL;
323 struct mem_cgroup_per_zone *mz_node;
325 if (mz->on_tree)
326 return;
328 mz->usage_in_excess = new_usage_in_excess;
329 if (!mz->usage_in_excess)
330 return;
331 while (*p) {
332 parent = *p;
333 mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
334 tree_node);
335 if (mz->usage_in_excess < mz_node->usage_in_excess)
336 p = &(*p)->rb_left;
338 * We can't avoid mem cgroups that are over their soft
339 * limit by the same amount
341 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
342 p = &(*p)->rb_right;
344 rb_link_node(&mz->tree_node, parent, p);
345 rb_insert_color(&mz->tree_node, &mctz->rb_root);
346 mz->on_tree = true;
349 static void
350 __mem_cgroup_remove_exceeded(struct mem_cgroup *mem,
351 struct mem_cgroup_per_zone *mz,
352 struct mem_cgroup_tree_per_zone *mctz)
354 if (!mz->on_tree)
355 return;
356 rb_erase(&mz->tree_node, &mctz->rb_root);
357 mz->on_tree = false;
360 static void
361 mem_cgroup_remove_exceeded(struct mem_cgroup *mem,
362 struct mem_cgroup_per_zone *mz,
363 struct mem_cgroup_tree_per_zone *mctz)
365 spin_lock(&mctz->lock);
366 __mem_cgroup_remove_exceeded(mem, mz, mctz);
367 spin_unlock(&mctz->lock);
370 static bool mem_cgroup_soft_limit_check(struct mem_cgroup *mem)
372 bool ret = false;
373 int cpu;
374 s64 val;
375 struct mem_cgroup_stat_cpu *cpustat;
377 cpu = get_cpu();
378 cpustat = &mem->stat.cpustat[cpu];
379 val = __mem_cgroup_stat_read_local(cpustat, MEM_CGROUP_STAT_EVENTS);
380 if (unlikely(val > SOFTLIMIT_EVENTS_THRESH)) {
381 __mem_cgroup_stat_reset_safe(cpustat, MEM_CGROUP_STAT_EVENTS);
382 ret = true;
384 put_cpu();
385 return ret;
388 static void mem_cgroup_update_tree(struct mem_cgroup *mem, struct page *page)
390 unsigned long long excess;
391 struct mem_cgroup_per_zone *mz;
392 struct mem_cgroup_tree_per_zone *mctz;
393 int nid = page_to_nid(page);
394 int zid = page_zonenum(page);
395 mctz = soft_limit_tree_from_page(page);
398 * Necessary to update all ancestors when hierarchy is used.
399 * because their event counter is not touched.
401 for (; mem; mem = parent_mem_cgroup(mem)) {
402 mz = mem_cgroup_zoneinfo(mem, nid, zid);
403 excess = res_counter_soft_limit_excess(&mem->res);
405 * We have to update the tree if mz is on RB-tree or
406 * mem is over its softlimit.
408 if (excess || mz->on_tree) {
409 spin_lock(&mctz->lock);
410 /* if on-tree, remove it */
411 if (mz->on_tree)
412 __mem_cgroup_remove_exceeded(mem, mz, mctz);
414 * Insert again. mz->usage_in_excess will be updated.
415 * If excess is 0, no tree ops.
417 __mem_cgroup_insert_exceeded(mem, mz, mctz, excess);
418 spin_unlock(&mctz->lock);
423 static void mem_cgroup_remove_from_trees(struct mem_cgroup *mem)
425 int node, zone;
426 struct mem_cgroup_per_zone *mz;
427 struct mem_cgroup_tree_per_zone *mctz;
429 for_each_node_state(node, N_POSSIBLE) {
430 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
431 mz = mem_cgroup_zoneinfo(mem, node, zone);
432 mctz = soft_limit_tree_node_zone(node, zone);
433 mem_cgroup_remove_exceeded(mem, mz, mctz);
438 static inline unsigned long mem_cgroup_get_excess(struct mem_cgroup *mem)
440 return res_counter_soft_limit_excess(&mem->res) >> PAGE_SHIFT;
443 static struct mem_cgroup_per_zone *
444 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
446 struct rb_node *rightmost = NULL;
447 struct mem_cgroup_per_zone *mz;
449 retry:
450 mz = NULL;
451 rightmost = rb_last(&mctz->rb_root);
452 if (!rightmost)
453 goto done; /* Nothing to reclaim from */
455 mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
457 * Remove the node now but someone else can add it back,
458 * we will to add it back at the end of reclaim to its correct
459 * position in the tree.
461 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
462 if (!res_counter_soft_limit_excess(&mz->mem->res) ||
463 !css_tryget(&mz->mem->css))
464 goto retry;
465 done:
466 return mz;
469 static struct mem_cgroup_per_zone *
470 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
472 struct mem_cgroup_per_zone *mz;
474 spin_lock(&mctz->lock);
475 mz = __mem_cgroup_largest_soft_limit_node(mctz);
476 spin_unlock(&mctz->lock);
477 return mz;
480 static void mem_cgroup_swap_statistics(struct mem_cgroup *mem,
481 bool charge)
483 int val = (charge) ? 1 : -1;
484 struct mem_cgroup_stat *stat = &mem->stat;
485 struct mem_cgroup_stat_cpu *cpustat;
486 int cpu = get_cpu();
488 cpustat = &stat->cpustat[cpu];
489 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_SWAPOUT, val);
490 put_cpu();
493 static void mem_cgroup_charge_statistics(struct mem_cgroup *mem,
494 struct page_cgroup *pc,
495 bool charge)
497 int val = (charge) ? 1 : -1;
498 struct mem_cgroup_stat *stat = &mem->stat;
499 struct mem_cgroup_stat_cpu *cpustat;
500 int cpu = get_cpu();
502 cpustat = &stat->cpustat[cpu];
503 if (PageCgroupCache(pc))
504 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_CACHE, val);
505 else
506 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_RSS, val);
508 if (charge)
509 __mem_cgroup_stat_add_safe(cpustat,
510 MEM_CGROUP_STAT_PGPGIN_COUNT, 1);
511 else
512 __mem_cgroup_stat_add_safe(cpustat,
513 MEM_CGROUP_STAT_PGPGOUT_COUNT, 1);
514 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_EVENTS, 1);
515 put_cpu();
518 static unsigned long mem_cgroup_get_local_zonestat(struct mem_cgroup *mem,
519 enum lru_list idx)
521 int nid, zid;
522 struct mem_cgroup_per_zone *mz;
523 u64 total = 0;
525 for_each_online_node(nid)
526 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
527 mz = mem_cgroup_zoneinfo(mem, nid, zid);
528 total += MEM_CGROUP_ZSTAT(mz, idx);
530 return total;
533 static struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
535 return container_of(cgroup_subsys_state(cont,
536 mem_cgroup_subsys_id), struct mem_cgroup,
537 css);
540 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
543 * mm_update_next_owner() may clear mm->owner to NULL
544 * if it races with swapoff, page migration, etc.
545 * So this can be called with p == NULL.
547 if (unlikely(!p))
548 return NULL;
550 return container_of(task_subsys_state(p, mem_cgroup_subsys_id),
551 struct mem_cgroup, css);
554 static struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
556 struct mem_cgroup *mem = NULL;
558 if (!mm)
559 return NULL;
561 * Because we have no locks, mm->owner's may be being moved to other
562 * cgroup. We use css_tryget() here even if this looks
563 * pessimistic (rather than adding locks here).
565 rcu_read_lock();
566 do {
567 mem = mem_cgroup_from_task(rcu_dereference(mm->owner));
568 if (unlikely(!mem))
569 break;
570 } while (!css_tryget(&mem->css));
571 rcu_read_unlock();
572 return mem;
576 * Call callback function against all cgroup under hierarchy tree.
578 static int mem_cgroup_walk_tree(struct mem_cgroup *root, void *data,
579 int (*func)(struct mem_cgroup *, void *))
581 int found, ret, nextid;
582 struct cgroup_subsys_state *css;
583 struct mem_cgroup *mem;
585 if (!root->use_hierarchy)
586 return (*func)(root, data);
588 nextid = 1;
589 do {
590 ret = 0;
591 mem = NULL;
593 rcu_read_lock();
594 css = css_get_next(&mem_cgroup_subsys, nextid, &root->css,
595 &found);
596 if (css && css_tryget(css))
597 mem = container_of(css, struct mem_cgroup, css);
598 rcu_read_unlock();
600 if (mem) {
601 ret = (*func)(mem, data);
602 css_put(&mem->css);
604 nextid = found + 1;
605 } while (!ret && css);
607 return ret;
610 static inline bool mem_cgroup_is_root(struct mem_cgroup *mem)
612 return (mem == root_mem_cgroup);
616 * Following LRU functions are allowed to be used without PCG_LOCK.
617 * Operations are called by routine of global LRU independently from memcg.
618 * What we have to take care of here is validness of pc->mem_cgroup.
620 * Changes to pc->mem_cgroup happens when
621 * 1. charge
622 * 2. moving account
623 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
624 * It is added to LRU before charge.
625 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
626 * When moving account, the page is not on LRU. It's isolated.
629 void mem_cgroup_del_lru_list(struct page *page, enum lru_list lru)
631 struct page_cgroup *pc;
632 struct mem_cgroup_per_zone *mz;
634 if (mem_cgroup_disabled())
635 return;
636 pc = lookup_page_cgroup(page);
637 /* can happen while we handle swapcache. */
638 if (!TestClearPageCgroupAcctLRU(pc))
639 return;
640 VM_BUG_ON(!pc->mem_cgroup);
642 * We don't check PCG_USED bit. It's cleared when the "page" is finally
643 * removed from global LRU.
645 mz = page_cgroup_zoneinfo(pc);
646 MEM_CGROUP_ZSTAT(mz, lru) -= 1;
647 if (mem_cgroup_is_root(pc->mem_cgroup))
648 return;
649 VM_BUG_ON(list_empty(&pc->lru));
650 list_del_init(&pc->lru);
651 return;
654 void mem_cgroup_del_lru(struct page *page)
656 mem_cgroup_del_lru_list(page, page_lru(page));
659 void mem_cgroup_rotate_lru_list(struct page *page, enum lru_list lru)
661 struct mem_cgroup_per_zone *mz;
662 struct page_cgroup *pc;
664 if (mem_cgroup_disabled())
665 return;
667 pc = lookup_page_cgroup(page);
669 * Used bit is set without atomic ops but after smp_wmb().
670 * For making pc->mem_cgroup visible, insert smp_rmb() here.
672 smp_rmb();
673 /* unused or root page is not rotated. */
674 if (!PageCgroupUsed(pc) || mem_cgroup_is_root(pc->mem_cgroup))
675 return;
676 mz = page_cgroup_zoneinfo(pc);
677 list_move(&pc->lru, &mz->lists[lru]);
680 void mem_cgroup_add_lru_list(struct page *page, enum lru_list lru)
682 struct page_cgroup *pc;
683 struct mem_cgroup_per_zone *mz;
685 if (mem_cgroup_disabled())
686 return;
687 pc = lookup_page_cgroup(page);
688 VM_BUG_ON(PageCgroupAcctLRU(pc));
690 * Used bit is set without atomic ops but after smp_wmb().
691 * For making pc->mem_cgroup visible, insert smp_rmb() here.
693 smp_rmb();
694 if (!PageCgroupUsed(pc))
695 return;
697 mz = page_cgroup_zoneinfo(pc);
698 MEM_CGROUP_ZSTAT(mz, lru) += 1;
699 SetPageCgroupAcctLRU(pc);
700 if (mem_cgroup_is_root(pc->mem_cgroup))
701 return;
702 list_add(&pc->lru, &mz->lists[lru]);
706 * At handling SwapCache, pc->mem_cgroup may be changed while it's linked to
707 * lru because the page may.be reused after it's fully uncharged (because of
708 * SwapCache behavior).To handle that, unlink page_cgroup from LRU when charge
709 * it again. This function is only used to charge SwapCache. It's done under
710 * lock_page and expected that zone->lru_lock is never held.
712 static void mem_cgroup_lru_del_before_commit_swapcache(struct page *page)
714 unsigned long flags;
715 struct zone *zone = page_zone(page);
716 struct page_cgroup *pc = lookup_page_cgroup(page);
718 spin_lock_irqsave(&zone->lru_lock, flags);
720 * Forget old LRU when this page_cgroup is *not* used. This Used bit
721 * is guarded by lock_page() because the page is SwapCache.
723 if (!PageCgroupUsed(pc))
724 mem_cgroup_del_lru_list(page, page_lru(page));
725 spin_unlock_irqrestore(&zone->lru_lock, flags);
728 static void mem_cgroup_lru_add_after_commit_swapcache(struct page *page)
730 unsigned long flags;
731 struct zone *zone = page_zone(page);
732 struct page_cgroup *pc = lookup_page_cgroup(page);
734 spin_lock_irqsave(&zone->lru_lock, flags);
735 /* link when the page is linked to LRU but page_cgroup isn't */
736 if (PageLRU(page) && !PageCgroupAcctLRU(pc))
737 mem_cgroup_add_lru_list(page, page_lru(page));
738 spin_unlock_irqrestore(&zone->lru_lock, flags);
742 void mem_cgroup_move_lists(struct page *page,
743 enum lru_list from, enum lru_list to)
745 if (mem_cgroup_disabled())
746 return;
747 mem_cgroup_del_lru_list(page, from);
748 mem_cgroup_add_lru_list(page, to);
751 int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *mem)
753 int ret;
754 struct mem_cgroup *curr = NULL;
756 task_lock(task);
757 rcu_read_lock();
758 curr = try_get_mem_cgroup_from_mm(task->mm);
759 rcu_read_unlock();
760 task_unlock(task);
761 if (!curr)
762 return 0;
763 if (curr->use_hierarchy)
764 ret = css_is_ancestor(&curr->css, &mem->css);
765 else
766 ret = (curr == mem);
767 css_put(&curr->css);
768 return ret;
772 * prev_priority control...this will be used in memory reclaim path.
774 int mem_cgroup_get_reclaim_priority(struct mem_cgroup *mem)
776 int prev_priority;
778 spin_lock(&mem->reclaim_param_lock);
779 prev_priority = mem->prev_priority;
780 spin_unlock(&mem->reclaim_param_lock);
782 return prev_priority;
785 void mem_cgroup_note_reclaim_priority(struct mem_cgroup *mem, int priority)
787 spin_lock(&mem->reclaim_param_lock);
788 if (priority < mem->prev_priority)
789 mem->prev_priority = priority;
790 spin_unlock(&mem->reclaim_param_lock);
793 void mem_cgroup_record_reclaim_priority(struct mem_cgroup *mem, int priority)
795 spin_lock(&mem->reclaim_param_lock);
796 mem->prev_priority = priority;
797 spin_unlock(&mem->reclaim_param_lock);
800 static int calc_inactive_ratio(struct mem_cgroup *memcg, unsigned long *present_pages)
802 unsigned long active;
803 unsigned long inactive;
804 unsigned long gb;
805 unsigned long inactive_ratio;
807 inactive = mem_cgroup_get_local_zonestat(memcg, LRU_INACTIVE_ANON);
808 active = mem_cgroup_get_local_zonestat(memcg, LRU_ACTIVE_ANON);
810 gb = (inactive + active) >> (30 - PAGE_SHIFT);
811 if (gb)
812 inactive_ratio = int_sqrt(10 * gb);
813 else
814 inactive_ratio = 1;
816 if (present_pages) {
817 present_pages[0] = inactive;
818 present_pages[1] = active;
821 return inactive_ratio;
824 int mem_cgroup_inactive_anon_is_low(struct mem_cgroup *memcg)
826 unsigned long active;
827 unsigned long inactive;
828 unsigned long present_pages[2];
829 unsigned long inactive_ratio;
831 inactive_ratio = calc_inactive_ratio(memcg, present_pages);
833 inactive = present_pages[0];
834 active = present_pages[1];
836 if (inactive * inactive_ratio < active)
837 return 1;
839 return 0;
842 int mem_cgroup_inactive_file_is_low(struct mem_cgroup *memcg)
844 unsigned long active;
845 unsigned long inactive;
847 inactive = mem_cgroup_get_local_zonestat(memcg, LRU_INACTIVE_FILE);
848 active = mem_cgroup_get_local_zonestat(memcg, LRU_ACTIVE_FILE);
850 return (active > inactive);
853 unsigned long mem_cgroup_zone_nr_pages(struct mem_cgroup *memcg,
854 struct zone *zone,
855 enum lru_list lru)
857 int nid = zone->zone_pgdat->node_id;
858 int zid = zone_idx(zone);
859 struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
861 return MEM_CGROUP_ZSTAT(mz, lru);
864 struct zone_reclaim_stat *mem_cgroup_get_reclaim_stat(struct mem_cgroup *memcg,
865 struct zone *zone)
867 int nid = zone->zone_pgdat->node_id;
868 int zid = zone_idx(zone);
869 struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
871 return &mz->reclaim_stat;
874 struct zone_reclaim_stat *
875 mem_cgroup_get_reclaim_stat_from_page(struct page *page)
877 struct page_cgroup *pc;
878 struct mem_cgroup_per_zone *mz;
880 if (mem_cgroup_disabled())
881 return NULL;
883 pc = lookup_page_cgroup(page);
885 * Used bit is set without atomic ops but after smp_wmb().
886 * For making pc->mem_cgroup visible, insert smp_rmb() here.
888 smp_rmb();
889 if (!PageCgroupUsed(pc))
890 return NULL;
892 mz = page_cgroup_zoneinfo(pc);
893 if (!mz)
894 return NULL;
896 return &mz->reclaim_stat;
899 unsigned long mem_cgroup_isolate_pages(unsigned long nr_to_scan,
900 struct list_head *dst,
901 unsigned long *scanned, int order,
902 int mode, struct zone *z,
903 struct mem_cgroup *mem_cont,
904 int active, int file)
906 unsigned long nr_taken = 0;
907 struct page *page;
908 unsigned long scan;
909 LIST_HEAD(pc_list);
910 struct list_head *src;
911 struct page_cgroup *pc, *tmp;
912 int nid = z->zone_pgdat->node_id;
913 int zid = zone_idx(z);
914 struct mem_cgroup_per_zone *mz;
915 int lru = LRU_FILE * file + active;
916 int ret;
918 BUG_ON(!mem_cont);
919 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
920 src = &mz->lists[lru];
922 scan = 0;
923 list_for_each_entry_safe_reverse(pc, tmp, src, lru) {
924 if (scan >= nr_to_scan)
925 break;
927 page = pc->page;
928 if (unlikely(!PageCgroupUsed(pc)))
929 continue;
930 if (unlikely(!PageLRU(page)))
931 continue;
933 scan++;
934 ret = __isolate_lru_page(page, mode, file);
935 switch (ret) {
936 case 0:
937 list_move(&page->lru, dst);
938 mem_cgroup_del_lru(page);
939 nr_taken++;
940 break;
941 case -EBUSY:
942 /* we don't affect global LRU but rotate in our LRU */
943 mem_cgroup_rotate_lru_list(page, page_lru(page));
944 break;
945 default:
946 break;
950 *scanned = scan;
951 return nr_taken;
954 #define mem_cgroup_from_res_counter(counter, member) \
955 container_of(counter, struct mem_cgroup, member)
957 static bool mem_cgroup_check_under_limit(struct mem_cgroup *mem)
959 if (do_swap_account) {
960 if (res_counter_check_under_limit(&mem->res) &&
961 res_counter_check_under_limit(&mem->memsw))
962 return true;
963 } else
964 if (res_counter_check_under_limit(&mem->res))
965 return true;
966 return false;
969 static unsigned int get_swappiness(struct mem_cgroup *memcg)
971 struct cgroup *cgrp = memcg->css.cgroup;
972 unsigned int swappiness;
974 /* root ? */
975 if (cgrp->parent == NULL)
976 return vm_swappiness;
978 spin_lock(&memcg->reclaim_param_lock);
979 swappiness = memcg->swappiness;
980 spin_unlock(&memcg->reclaim_param_lock);
982 return swappiness;
985 static int mem_cgroup_count_children_cb(struct mem_cgroup *mem, void *data)
987 int *val = data;
988 (*val)++;
989 return 0;
993 * mem_cgroup_print_mem_info: Called from OOM with tasklist_lock held in read mode.
994 * @memcg: The memory cgroup that went over limit
995 * @p: Task that is going to be killed
997 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
998 * enabled
1000 void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1002 struct cgroup *task_cgrp;
1003 struct cgroup *mem_cgrp;
1005 * Need a buffer in BSS, can't rely on allocations. The code relies
1006 * on the assumption that OOM is serialized for memory controller.
1007 * If this assumption is broken, revisit this code.
1009 static char memcg_name[PATH_MAX];
1010 int ret;
1012 if (!memcg)
1013 return;
1016 rcu_read_lock();
1018 mem_cgrp = memcg->css.cgroup;
1019 task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
1021 ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
1022 if (ret < 0) {
1024 * Unfortunately, we are unable to convert to a useful name
1025 * But we'll still print out the usage information
1027 rcu_read_unlock();
1028 goto done;
1030 rcu_read_unlock();
1032 printk(KERN_INFO "Task in %s killed", memcg_name);
1034 rcu_read_lock();
1035 ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
1036 if (ret < 0) {
1037 rcu_read_unlock();
1038 goto done;
1040 rcu_read_unlock();
1043 * Continues from above, so we don't need an KERN_ level
1045 printk(KERN_CONT " as a result of limit of %s\n", memcg_name);
1046 done:
1048 printk(KERN_INFO "memory: usage %llukB, limit %llukB, failcnt %llu\n",
1049 res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
1050 res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
1051 res_counter_read_u64(&memcg->res, RES_FAILCNT));
1052 printk(KERN_INFO "memory+swap: usage %llukB, limit %llukB, "
1053 "failcnt %llu\n",
1054 res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
1055 res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
1056 res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
1060 * This function returns the number of memcg under hierarchy tree. Returns
1061 * 1(self count) if no children.
1063 static int mem_cgroup_count_children(struct mem_cgroup *mem)
1065 int num = 0;
1066 mem_cgroup_walk_tree(mem, &num, mem_cgroup_count_children_cb);
1067 return num;
1071 * Visit the first child (need not be the first child as per the ordering
1072 * of the cgroup list, since we track last_scanned_child) of @mem and use
1073 * that to reclaim free pages from.
1075 static struct mem_cgroup *
1076 mem_cgroup_select_victim(struct mem_cgroup *root_mem)
1078 struct mem_cgroup *ret = NULL;
1079 struct cgroup_subsys_state *css;
1080 int nextid, found;
1082 if (!root_mem->use_hierarchy) {
1083 css_get(&root_mem->css);
1084 ret = root_mem;
1087 while (!ret) {
1088 rcu_read_lock();
1089 nextid = root_mem->last_scanned_child + 1;
1090 css = css_get_next(&mem_cgroup_subsys, nextid, &root_mem->css,
1091 &found);
1092 if (css && css_tryget(css))
1093 ret = container_of(css, struct mem_cgroup, css);
1095 rcu_read_unlock();
1096 /* Updates scanning parameter */
1097 spin_lock(&root_mem->reclaim_param_lock);
1098 if (!css) {
1099 /* this means start scan from ID:1 */
1100 root_mem->last_scanned_child = 0;
1101 } else
1102 root_mem->last_scanned_child = found;
1103 spin_unlock(&root_mem->reclaim_param_lock);
1106 return ret;
1110 * Scan the hierarchy if needed to reclaim memory. We remember the last child
1111 * we reclaimed from, so that we don't end up penalizing one child extensively
1112 * based on its position in the children list.
1114 * root_mem is the original ancestor that we've been reclaim from.
1116 * We give up and return to the caller when we visit root_mem twice.
1117 * (other groups can be removed while we're walking....)
1119 * If shrink==true, for avoiding to free too much, this returns immedieately.
1121 static int mem_cgroup_hierarchical_reclaim(struct mem_cgroup *root_mem,
1122 struct zone *zone,
1123 gfp_t gfp_mask,
1124 unsigned long reclaim_options)
1126 struct mem_cgroup *victim;
1127 int ret, total = 0;
1128 int loop = 0;
1129 bool noswap = reclaim_options & MEM_CGROUP_RECLAIM_NOSWAP;
1130 bool shrink = reclaim_options & MEM_CGROUP_RECLAIM_SHRINK;
1131 bool check_soft = reclaim_options & MEM_CGROUP_RECLAIM_SOFT;
1132 unsigned long excess = mem_cgroup_get_excess(root_mem);
1134 /* If memsw_is_minimum==1, swap-out is of-no-use. */
1135 if (root_mem->memsw_is_minimum)
1136 noswap = true;
1138 while (1) {
1139 victim = mem_cgroup_select_victim(root_mem);
1140 if (victim == root_mem) {
1141 loop++;
1142 if (loop >= 1)
1143 drain_all_stock_async();
1144 if (loop >= 2) {
1146 * If we have not been able to reclaim
1147 * anything, it might because there are
1148 * no reclaimable pages under this hierarchy
1150 if (!check_soft || !total) {
1151 css_put(&victim->css);
1152 break;
1155 * We want to do more targetted reclaim.
1156 * excess >> 2 is not to excessive so as to
1157 * reclaim too much, nor too less that we keep
1158 * coming back to reclaim from this cgroup
1160 if (total >= (excess >> 2) ||
1161 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS)) {
1162 css_put(&victim->css);
1163 break;
1167 if (!mem_cgroup_local_usage(&victim->stat)) {
1168 /* this cgroup's local usage == 0 */
1169 css_put(&victim->css);
1170 continue;
1172 /* we use swappiness of local cgroup */
1173 if (check_soft)
1174 ret = mem_cgroup_shrink_node_zone(victim, gfp_mask,
1175 noswap, get_swappiness(victim), zone,
1176 zone->zone_pgdat->node_id);
1177 else
1178 ret = try_to_free_mem_cgroup_pages(victim, gfp_mask,
1179 noswap, get_swappiness(victim));
1180 css_put(&victim->css);
1182 * At shrinking usage, we can't check we should stop here or
1183 * reclaim more. It's depends on callers. last_scanned_child
1184 * will work enough for keeping fairness under tree.
1186 if (shrink)
1187 return ret;
1188 total += ret;
1189 if (check_soft) {
1190 if (res_counter_check_under_soft_limit(&root_mem->res))
1191 return total;
1192 } else if (mem_cgroup_check_under_limit(root_mem))
1193 return 1 + total;
1195 return total;
1198 bool mem_cgroup_oom_called(struct task_struct *task)
1200 bool ret = false;
1201 struct mem_cgroup *mem;
1202 struct mm_struct *mm;
1204 rcu_read_lock();
1205 mm = task->mm;
1206 if (!mm)
1207 mm = &init_mm;
1208 mem = mem_cgroup_from_task(rcu_dereference(mm->owner));
1209 if (mem && time_before(jiffies, mem->last_oom_jiffies + HZ/10))
1210 ret = true;
1211 rcu_read_unlock();
1212 return ret;
1215 static int record_last_oom_cb(struct mem_cgroup *mem, void *data)
1217 mem->last_oom_jiffies = jiffies;
1218 return 0;
1221 static void record_last_oom(struct mem_cgroup *mem)
1223 mem_cgroup_walk_tree(mem, NULL, record_last_oom_cb);
1227 * Currently used to update mapped file statistics, but the routine can be
1228 * generalized to update other statistics as well.
1230 void mem_cgroup_update_mapped_file_stat(struct page *page, int val)
1232 struct mem_cgroup *mem;
1233 struct mem_cgroup_stat *stat;
1234 struct mem_cgroup_stat_cpu *cpustat;
1235 int cpu;
1236 struct page_cgroup *pc;
1238 if (!page_is_file_cache(page))
1239 return;
1241 pc = lookup_page_cgroup(page);
1242 if (unlikely(!pc))
1243 return;
1245 lock_page_cgroup(pc);
1246 mem = pc->mem_cgroup;
1247 if (!mem)
1248 goto done;
1250 if (!PageCgroupUsed(pc))
1251 goto done;
1254 * Preemption is already disabled, we don't need get_cpu()
1256 cpu = smp_processor_id();
1257 stat = &mem->stat;
1258 cpustat = &stat->cpustat[cpu];
1260 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_MAPPED_FILE, val);
1261 done:
1262 unlock_page_cgroup(pc);
1266 * size of first charge trial. "32" comes from vmscan.c's magic value.
1267 * TODO: maybe necessary to use big numbers in big irons.
1269 #define CHARGE_SIZE (32 * PAGE_SIZE)
1270 struct memcg_stock_pcp {
1271 struct mem_cgroup *cached; /* this never be root cgroup */
1272 int charge;
1273 struct work_struct work;
1275 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
1276 static atomic_t memcg_drain_count;
1279 * Try to consume stocked charge on this cpu. If success, PAGE_SIZE is consumed
1280 * from local stock and true is returned. If the stock is 0 or charges from a
1281 * cgroup which is not current target, returns false. This stock will be
1282 * refilled.
1284 static bool consume_stock(struct mem_cgroup *mem)
1286 struct memcg_stock_pcp *stock;
1287 bool ret = true;
1289 stock = &get_cpu_var(memcg_stock);
1290 if (mem == stock->cached && stock->charge)
1291 stock->charge -= PAGE_SIZE;
1292 else /* need to call res_counter_charge */
1293 ret = false;
1294 put_cpu_var(memcg_stock);
1295 return ret;
1299 * Returns stocks cached in percpu to res_counter and reset cached information.
1301 static void drain_stock(struct memcg_stock_pcp *stock)
1303 struct mem_cgroup *old = stock->cached;
1305 if (stock->charge) {
1306 res_counter_uncharge(&old->res, stock->charge);
1307 if (do_swap_account)
1308 res_counter_uncharge(&old->memsw, stock->charge);
1310 stock->cached = NULL;
1311 stock->charge = 0;
1315 * This must be called under preempt disabled or must be called by
1316 * a thread which is pinned to local cpu.
1318 static void drain_local_stock(struct work_struct *dummy)
1320 struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
1321 drain_stock(stock);
1325 * Cache charges(val) which is from res_counter, to local per_cpu area.
1326 * This will be consumed by consumt_stock() function, later.
1328 static void refill_stock(struct mem_cgroup *mem, int val)
1330 struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
1332 if (stock->cached != mem) { /* reset if necessary */
1333 drain_stock(stock);
1334 stock->cached = mem;
1336 stock->charge += val;
1337 put_cpu_var(memcg_stock);
1341 * Tries to drain stocked charges in other cpus. This function is asynchronous
1342 * and just put a work per cpu for draining localy on each cpu. Caller can
1343 * expects some charges will be back to res_counter later but cannot wait for
1344 * it.
1346 static void drain_all_stock_async(void)
1348 int cpu;
1349 /* This function is for scheduling "drain" in asynchronous way.
1350 * The result of "drain" is not directly handled by callers. Then,
1351 * if someone is calling drain, we don't have to call drain more.
1352 * Anyway, work_pending() will catch if there is a race. We just do
1353 * loose check here.
1355 if (atomic_read(&memcg_drain_count))
1356 return;
1357 /* Notify other cpus that system-wide "drain" is running */
1358 atomic_inc(&memcg_drain_count);
1359 get_online_cpus();
1360 for_each_online_cpu(cpu) {
1361 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
1362 if (work_pending(&stock->work))
1363 continue;
1364 INIT_WORK(&stock->work, drain_local_stock);
1365 schedule_work_on(cpu, &stock->work);
1367 put_online_cpus();
1368 atomic_dec(&memcg_drain_count);
1369 /* We don't wait for flush_work */
1372 /* This is a synchronous drain interface. */
1373 static void drain_all_stock_sync(void)
1375 /* called when force_empty is called */
1376 atomic_inc(&memcg_drain_count);
1377 schedule_on_each_cpu(drain_local_stock);
1378 atomic_dec(&memcg_drain_count);
1381 static int __cpuinit memcg_stock_cpu_callback(struct notifier_block *nb,
1382 unsigned long action,
1383 void *hcpu)
1385 int cpu = (unsigned long)hcpu;
1386 struct memcg_stock_pcp *stock;
1388 if (action != CPU_DEAD)
1389 return NOTIFY_OK;
1390 stock = &per_cpu(memcg_stock, cpu);
1391 drain_stock(stock);
1392 return NOTIFY_OK;
1396 * Unlike exported interface, "oom" parameter is added. if oom==true,
1397 * oom-killer can be invoked.
1399 static int __mem_cgroup_try_charge(struct mm_struct *mm,
1400 gfp_t gfp_mask, struct mem_cgroup **memcg,
1401 bool oom, struct page *page)
1403 struct mem_cgroup *mem, *mem_over_limit;
1404 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
1405 struct res_counter *fail_res;
1406 int csize = CHARGE_SIZE;
1408 if (unlikely(test_thread_flag(TIF_MEMDIE))) {
1409 /* Don't account this! */
1410 *memcg = NULL;
1411 return 0;
1415 * We always charge the cgroup the mm_struct belongs to.
1416 * The mm_struct's mem_cgroup changes on task migration if the
1417 * thread group leader migrates. It's possible that mm is not
1418 * set, if so charge the init_mm (happens for pagecache usage).
1420 mem = *memcg;
1421 if (likely(!mem)) {
1422 mem = try_get_mem_cgroup_from_mm(mm);
1423 *memcg = mem;
1424 } else {
1425 css_get(&mem->css);
1427 if (unlikely(!mem))
1428 return 0;
1430 VM_BUG_ON(css_is_removed(&mem->css));
1431 if (mem_cgroup_is_root(mem))
1432 goto done;
1434 while (1) {
1435 int ret = 0;
1436 unsigned long flags = 0;
1438 if (consume_stock(mem))
1439 goto charged;
1441 ret = res_counter_charge(&mem->res, csize, &fail_res);
1442 if (likely(!ret)) {
1443 if (!do_swap_account)
1444 break;
1445 ret = res_counter_charge(&mem->memsw, csize, &fail_res);
1446 if (likely(!ret))
1447 break;
1448 /* mem+swap counter fails */
1449 res_counter_uncharge(&mem->res, csize);
1450 flags |= MEM_CGROUP_RECLAIM_NOSWAP;
1451 mem_over_limit = mem_cgroup_from_res_counter(fail_res,
1452 memsw);
1453 } else
1454 /* mem counter fails */
1455 mem_over_limit = mem_cgroup_from_res_counter(fail_res,
1456 res);
1458 /* reduce request size and retry */
1459 if (csize > PAGE_SIZE) {
1460 csize = PAGE_SIZE;
1461 continue;
1463 if (!(gfp_mask & __GFP_WAIT))
1464 goto nomem;
1466 ret = mem_cgroup_hierarchical_reclaim(mem_over_limit, NULL,
1467 gfp_mask, flags);
1468 if (ret)
1469 continue;
1472 * try_to_free_mem_cgroup_pages() might not give us a full
1473 * picture of reclaim. Some pages are reclaimed and might be
1474 * moved to swap cache or just unmapped from the cgroup.
1475 * Check the limit again to see if the reclaim reduced the
1476 * current usage of the cgroup before giving up
1479 if (mem_cgroup_check_under_limit(mem_over_limit))
1480 continue;
1482 if (!nr_retries--) {
1483 if (oom) {
1484 mutex_lock(&memcg_tasklist);
1485 mem_cgroup_out_of_memory(mem_over_limit, gfp_mask);
1486 mutex_unlock(&memcg_tasklist);
1487 record_last_oom(mem_over_limit);
1489 goto nomem;
1492 if (csize > PAGE_SIZE)
1493 refill_stock(mem, csize - PAGE_SIZE);
1494 charged:
1496 * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
1497 * if they exceeds softlimit.
1499 if (mem_cgroup_soft_limit_check(mem))
1500 mem_cgroup_update_tree(mem, page);
1501 done:
1502 return 0;
1503 nomem:
1504 css_put(&mem->css);
1505 return -ENOMEM;
1509 * A helper function to get mem_cgroup from ID. must be called under
1510 * rcu_read_lock(). The caller must check css_is_removed() or some if
1511 * it's concern. (dropping refcnt from swap can be called against removed
1512 * memcg.)
1514 static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
1516 struct cgroup_subsys_state *css;
1518 /* ID 0 is unused ID */
1519 if (!id)
1520 return NULL;
1521 css = css_lookup(&mem_cgroup_subsys, id);
1522 if (!css)
1523 return NULL;
1524 return container_of(css, struct mem_cgroup, css);
1527 static struct mem_cgroup *try_get_mem_cgroup_from_swapcache(struct page *page)
1529 struct mem_cgroup *mem;
1530 struct page_cgroup *pc;
1531 unsigned short id;
1532 swp_entry_t ent;
1534 VM_BUG_ON(!PageLocked(page));
1536 if (!PageSwapCache(page))
1537 return NULL;
1539 pc = lookup_page_cgroup(page);
1540 lock_page_cgroup(pc);
1541 if (PageCgroupUsed(pc)) {
1542 mem = pc->mem_cgroup;
1543 if (mem && !css_tryget(&mem->css))
1544 mem = NULL;
1545 } else {
1546 ent.val = page_private(page);
1547 id = lookup_swap_cgroup(ent);
1548 rcu_read_lock();
1549 mem = mem_cgroup_lookup(id);
1550 if (mem && !css_tryget(&mem->css))
1551 mem = NULL;
1552 rcu_read_unlock();
1554 unlock_page_cgroup(pc);
1555 return mem;
1559 * commit a charge got by __mem_cgroup_try_charge() and makes page_cgroup to be
1560 * USED state. If already USED, uncharge and return.
1563 static void __mem_cgroup_commit_charge(struct mem_cgroup *mem,
1564 struct page_cgroup *pc,
1565 enum charge_type ctype)
1567 /* try_charge() can return NULL to *memcg, taking care of it. */
1568 if (!mem)
1569 return;
1571 lock_page_cgroup(pc);
1572 if (unlikely(PageCgroupUsed(pc))) {
1573 unlock_page_cgroup(pc);
1574 if (!mem_cgroup_is_root(mem)) {
1575 res_counter_uncharge(&mem->res, PAGE_SIZE);
1576 if (do_swap_account)
1577 res_counter_uncharge(&mem->memsw, PAGE_SIZE);
1579 css_put(&mem->css);
1580 return;
1583 pc->mem_cgroup = mem;
1585 * We access a page_cgroup asynchronously without lock_page_cgroup().
1586 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
1587 * is accessed after testing USED bit. To make pc->mem_cgroup visible
1588 * before USED bit, we need memory barrier here.
1589 * See mem_cgroup_add_lru_list(), etc.
1591 smp_wmb();
1592 switch (ctype) {
1593 case MEM_CGROUP_CHARGE_TYPE_CACHE:
1594 case MEM_CGROUP_CHARGE_TYPE_SHMEM:
1595 SetPageCgroupCache(pc);
1596 SetPageCgroupUsed(pc);
1597 break;
1598 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
1599 ClearPageCgroupCache(pc);
1600 SetPageCgroupUsed(pc);
1601 break;
1602 default:
1603 break;
1606 mem_cgroup_charge_statistics(mem, pc, true);
1608 unlock_page_cgroup(pc);
1612 * mem_cgroup_move_account - move account of the page
1613 * @pc: page_cgroup of the page.
1614 * @from: mem_cgroup which the page is moved from.
1615 * @to: mem_cgroup which the page is moved to. @from != @to.
1617 * The caller must confirm following.
1618 * - page is not on LRU (isolate_page() is useful.)
1620 * returns 0 at success,
1621 * returns -EBUSY when lock is busy or "pc" is unstable.
1623 * This function does "uncharge" from old cgroup but doesn't do "charge" to
1624 * new cgroup. It should be done by a caller.
1627 static int mem_cgroup_move_account(struct page_cgroup *pc,
1628 struct mem_cgroup *from, struct mem_cgroup *to)
1630 struct mem_cgroup_per_zone *from_mz, *to_mz;
1631 int nid, zid;
1632 int ret = -EBUSY;
1633 struct page *page;
1634 int cpu;
1635 struct mem_cgroup_stat *stat;
1636 struct mem_cgroup_stat_cpu *cpustat;
1638 VM_BUG_ON(from == to);
1639 VM_BUG_ON(PageLRU(pc->page));
1641 nid = page_cgroup_nid(pc);
1642 zid = page_cgroup_zid(pc);
1643 from_mz = mem_cgroup_zoneinfo(from, nid, zid);
1644 to_mz = mem_cgroup_zoneinfo(to, nid, zid);
1646 if (!trylock_page_cgroup(pc))
1647 return ret;
1649 if (!PageCgroupUsed(pc))
1650 goto out;
1652 if (pc->mem_cgroup != from)
1653 goto out;
1655 if (!mem_cgroup_is_root(from))
1656 res_counter_uncharge(&from->res, PAGE_SIZE);
1657 mem_cgroup_charge_statistics(from, pc, false);
1659 page = pc->page;
1660 if (page_is_file_cache(page) && page_mapped(page)) {
1661 cpu = smp_processor_id();
1662 /* Update mapped_file data for mem_cgroup "from" */
1663 stat = &from->stat;
1664 cpustat = &stat->cpustat[cpu];
1665 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_MAPPED_FILE,
1666 -1);
1668 /* Update mapped_file data for mem_cgroup "to" */
1669 stat = &to->stat;
1670 cpustat = &stat->cpustat[cpu];
1671 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_MAPPED_FILE,
1675 if (do_swap_account && !mem_cgroup_is_root(from))
1676 res_counter_uncharge(&from->memsw, PAGE_SIZE);
1677 css_put(&from->css);
1679 css_get(&to->css);
1680 pc->mem_cgroup = to;
1681 mem_cgroup_charge_statistics(to, pc, true);
1682 ret = 0;
1683 out:
1684 unlock_page_cgroup(pc);
1686 * We charges against "to" which may not have any tasks. Then, "to"
1687 * can be under rmdir(). But in current implementation, caller of
1688 * this function is just force_empty() and it's garanteed that
1689 * "to" is never removed. So, we don't check rmdir status here.
1691 return ret;
1695 * move charges to its parent.
1698 static int mem_cgroup_move_parent(struct page_cgroup *pc,
1699 struct mem_cgroup *child,
1700 gfp_t gfp_mask)
1702 struct page *page = pc->page;
1703 struct cgroup *cg = child->css.cgroup;
1704 struct cgroup *pcg = cg->parent;
1705 struct mem_cgroup *parent;
1706 int ret;
1708 /* Is ROOT ? */
1709 if (!pcg)
1710 return -EINVAL;
1713 parent = mem_cgroup_from_cont(pcg);
1716 ret = __mem_cgroup_try_charge(NULL, gfp_mask, &parent, false, page);
1717 if (ret || !parent)
1718 return ret;
1720 if (!get_page_unless_zero(page)) {
1721 ret = -EBUSY;
1722 goto uncharge;
1725 ret = isolate_lru_page(page);
1727 if (ret)
1728 goto cancel;
1730 ret = mem_cgroup_move_account(pc, child, parent);
1732 putback_lru_page(page);
1733 if (!ret) {
1734 put_page(page);
1735 /* drop extra refcnt by try_charge() */
1736 css_put(&parent->css);
1737 return 0;
1740 cancel:
1741 put_page(page);
1742 uncharge:
1743 /* drop extra refcnt by try_charge() */
1744 css_put(&parent->css);
1745 /* uncharge if move fails */
1746 if (!mem_cgroup_is_root(parent)) {
1747 res_counter_uncharge(&parent->res, PAGE_SIZE);
1748 if (do_swap_account)
1749 res_counter_uncharge(&parent->memsw, PAGE_SIZE);
1751 return ret;
1755 * Charge the memory controller for page usage.
1756 * Return
1757 * 0 if the charge was successful
1758 * < 0 if the cgroup is over its limit
1760 static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
1761 gfp_t gfp_mask, enum charge_type ctype,
1762 struct mem_cgroup *memcg)
1764 struct mem_cgroup *mem;
1765 struct page_cgroup *pc;
1766 int ret;
1768 pc = lookup_page_cgroup(page);
1769 /* can happen at boot */
1770 if (unlikely(!pc))
1771 return 0;
1772 prefetchw(pc);
1774 mem = memcg;
1775 ret = __mem_cgroup_try_charge(mm, gfp_mask, &mem, true, page);
1776 if (ret || !mem)
1777 return ret;
1779 __mem_cgroup_commit_charge(mem, pc, ctype);
1780 return 0;
1783 int mem_cgroup_newpage_charge(struct page *page,
1784 struct mm_struct *mm, gfp_t gfp_mask)
1786 if (mem_cgroup_disabled())
1787 return 0;
1788 if (PageCompound(page))
1789 return 0;
1791 * If already mapped, we don't have to account.
1792 * If page cache, page->mapping has address_space.
1793 * But page->mapping may have out-of-use anon_vma pointer,
1794 * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
1795 * is NULL.
1797 if (page_mapped(page) || (page->mapping && !PageAnon(page)))
1798 return 0;
1799 if (unlikely(!mm))
1800 mm = &init_mm;
1801 return mem_cgroup_charge_common(page, mm, gfp_mask,
1802 MEM_CGROUP_CHARGE_TYPE_MAPPED, NULL);
1805 static void
1806 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
1807 enum charge_type ctype);
1809 int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
1810 gfp_t gfp_mask)
1812 struct mem_cgroup *mem = NULL;
1813 int ret;
1815 if (mem_cgroup_disabled())
1816 return 0;
1817 if (PageCompound(page))
1818 return 0;
1820 * Corner case handling. This is called from add_to_page_cache()
1821 * in usual. But some FS (shmem) precharges this page before calling it
1822 * and call add_to_page_cache() with GFP_NOWAIT.
1824 * For GFP_NOWAIT case, the page may be pre-charged before calling
1825 * add_to_page_cache(). (See shmem.c) check it here and avoid to call
1826 * charge twice. (It works but has to pay a bit larger cost.)
1827 * And when the page is SwapCache, it should take swap information
1828 * into account. This is under lock_page() now.
1830 if (!(gfp_mask & __GFP_WAIT)) {
1831 struct page_cgroup *pc;
1834 pc = lookup_page_cgroup(page);
1835 if (!pc)
1836 return 0;
1837 lock_page_cgroup(pc);
1838 if (PageCgroupUsed(pc)) {
1839 unlock_page_cgroup(pc);
1840 return 0;
1842 unlock_page_cgroup(pc);
1845 if (unlikely(!mm && !mem))
1846 mm = &init_mm;
1848 if (page_is_file_cache(page))
1849 return mem_cgroup_charge_common(page, mm, gfp_mask,
1850 MEM_CGROUP_CHARGE_TYPE_CACHE, NULL);
1852 /* shmem */
1853 if (PageSwapCache(page)) {
1854 ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
1855 if (!ret)
1856 __mem_cgroup_commit_charge_swapin(page, mem,
1857 MEM_CGROUP_CHARGE_TYPE_SHMEM);
1858 } else
1859 ret = mem_cgroup_charge_common(page, mm, gfp_mask,
1860 MEM_CGROUP_CHARGE_TYPE_SHMEM, mem);
1862 return ret;
1866 * While swap-in, try_charge -> commit or cancel, the page is locked.
1867 * And when try_charge() successfully returns, one refcnt to memcg without
1868 * struct page_cgroup is acquired. This refcnt will be consumed by
1869 * "commit()" or removed by "cancel()"
1871 int mem_cgroup_try_charge_swapin(struct mm_struct *mm,
1872 struct page *page,
1873 gfp_t mask, struct mem_cgroup **ptr)
1875 struct mem_cgroup *mem;
1876 int ret;
1878 if (mem_cgroup_disabled())
1879 return 0;
1881 if (!do_swap_account)
1882 goto charge_cur_mm;
1884 * A racing thread's fault, or swapoff, may have already updated
1885 * the pte, and even removed page from swap cache: return success
1886 * to go on to do_swap_page()'s pte_same() test, which should fail.
1888 if (!PageSwapCache(page))
1889 return 0;
1890 mem = try_get_mem_cgroup_from_swapcache(page);
1891 if (!mem)
1892 goto charge_cur_mm;
1893 *ptr = mem;
1894 ret = __mem_cgroup_try_charge(NULL, mask, ptr, true, page);
1895 /* drop extra refcnt from tryget */
1896 css_put(&mem->css);
1897 return ret;
1898 charge_cur_mm:
1899 if (unlikely(!mm))
1900 mm = &init_mm;
1901 return __mem_cgroup_try_charge(mm, mask, ptr, true, page);
1904 static void
1905 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
1906 enum charge_type ctype)
1908 struct page_cgroup *pc;
1910 if (mem_cgroup_disabled())
1911 return;
1912 if (!ptr)
1913 return;
1914 cgroup_exclude_rmdir(&ptr->css);
1915 pc = lookup_page_cgroup(page);
1916 mem_cgroup_lru_del_before_commit_swapcache(page);
1917 __mem_cgroup_commit_charge(ptr, pc, ctype);
1918 mem_cgroup_lru_add_after_commit_swapcache(page);
1920 * Now swap is on-memory. This means this page may be
1921 * counted both as mem and swap....double count.
1922 * Fix it by uncharging from memsw. Basically, this SwapCache is stable
1923 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
1924 * may call delete_from_swap_cache() before reach here.
1926 if (do_swap_account && PageSwapCache(page)) {
1927 swp_entry_t ent = {.val = page_private(page)};
1928 unsigned short id;
1929 struct mem_cgroup *memcg;
1931 id = swap_cgroup_record(ent, 0);
1932 rcu_read_lock();
1933 memcg = mem_cgroup_lookup(id);
1934 if (memcg) {
1936 * This recorded memcg can be obsolete one. So, avoid
1937 * calling css_tryget
1939 if (!mem_cgroup_is_root(memcg))
1940 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
1941 mem_cgroup_swap_statistics(memcg, false);
1942 mem_cgroup_put(memcg);
1944 rcu_read_unlock();
1947 * At swapin, we may charge account against cgroup which has no tasks.
1948 * So, rmdir()->pre_destroy() can be called while we do this charge.
1949 * In that case, we need to call pre_destroy() again. check it here.
1951 cgroup_release_and_wakeup_rmdir(&ptr->css);
1954 void mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr)
1956 __mem_cgroup_commit_charge_swapin(page, ptr,
1957 MEM_CGROUP_CHARGE_TYPE_MAPPED);
1960 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *mem)
1962 if (mem_cgroup_disabled())
1963 return;
1964 if (!mem)
1965 return;
1966 if (!mem_cgroup_is_root(mem)) {
1967 res_counter_uncharge(&mem->res, PAGE_SIZE);
1968 if (do_swap_account)
1969 res_counter_uncharge(&mem->memsw, PAGE_SIZE);
1971 css_put(&mem->css);
1974 static void
1975 __do_uncharge(struct mem_cgroup *mem, const enum charge_type ctype)
1977 struct memcg_batch_info *batch = NULL;
1978 bool uncharge_memsw = true;
1979 /* If swapout, usage of swap doesn't decrease */
1980 if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
1981 uncharge_memsw = false;
1983 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
1984 * In those cases, all pages freed continously can be expected to be in
1985 * the same cgroup and we have chance to coalesce uncharges.
1986 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
1987 * because we want to do uncharge as soon as possible.
1989 if (!current->memcg_batch.do_batch || test_thread_flag(TIF_MEMDIE))
1990 goto direct_uncharge;
1992 batch = &current->memcg_batch;
1994 * In usual, we do css_get() when we remember memcg pointer.
1995 * But in this case, we keep res->usage until end of a series of
1996 * uncharges. Then, it's ok to ignore memcg's refcnt.
1998 if (!batch->memcg)
1999 batch->memcg = mem;
2001 * In typical case, batch->memcg == mem. This means we can
2002 * merge a series of uncharges to an uncharge of res_counter.
2003 * If not, we uncharge res_counter ony by one.
2005 if (batch->memcg != mem)
2006 goto direct_uncharge;
2007 /* remember freed charge and uncharge it later */
2008 batch->bytes += PAGE_SIZE;
2009 if (uncharge_memsw)
2010 batch->memsw_bytes += PAGE_SIZE;
2011 return;
2012 direct_uncharge:
2013 res_counter_uncharge(&mem->res, PAGE_SIZE);
2014 if (uncharge_memsw)
2015 res_counter_uncharge(&mem->memsw, PAGE_SIZE);
2016 return;
2020 * uncharge if !page_mapped(page)
2022 static struct mem_cgroup *
2023 __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype)
2025 struct page_cgroup *pc;
2026 struct mem_cgroup *mem = NULL;
2027 struct mem_cgroup_per_zone *mz;
2029 if (mem_cgroup_disabled())
2030 return NULL;
2032 if (PageSwapCache(page))
2033 return NULL;
2036 * Check if our page_cgroup is valid
2038 pc = lookup_page_cgroup(page);
2039 if (unlikely(!pc || !PageCgroupUsed(pc)))
2040 return NULL;
2042 lock_page_cgroup(pc);
2044 mem = pc->mem_cgroup;
2046 if (!PageCgroupUsed(pc))
2047 goto unlock_out;
2049 switch (ctype) {
2050 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
2051 case MEM_CGROUP_CHARGE_TYPE_DROP:
2052 if (page_mapped(page))
2053 goto unlock_out;
2054 break;
2055 case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
2056 if (!PageAnon(page)) { /* Shared memory */
2057 if (page->mapping && !page_is_file_cache(page))
2058 goto unlock_out;
2059 } else if (page_mapped(page)) /* Anon */
2060 goto unlock_out;
2061 break;
2062 default:
2063 break;
2066 if (!mem_cgroup_is_root(mem))
2067 __do_uncharge(mem, ctype);
2068 if (ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2069 mem_cgroup_swap_statistics(mem, true);
2070 mem_cgroup_charge_statistics(mem, pc, false);
2072 ClearPageCgroupUsed(pc);
2074 * pc->mem_cgroup is not cleared here. It will be accessed when it's
2075 * freed from LRU. This is safe because uncharged page is expected not
2076 * to be reused (freed soon). Exception is SwapCache, it's handled by
2077 * special functions.
2080 mz = page_cgroup_zoneinfo(pc);
2081 unlock_page_cgroup(pc);
2083 if (mem_cgroup_soft_limit_check(mem))
2084 mem_cgroup_update_tree(mem, page);
2085 /* at swapout, this memcg will be accessed to record to swap */
2086 if (ctype != MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2087 css_put(&mem->css);
2089 return mem;
2091 unlock_out:
2092 unlock_page_cgroup(pc);
2093 return NULL;
2096 void mem_cgroup_uncharge_page(struct page *page)
2098 /* early check. */
2099 if (page_mapped(page))
2100 return;
2101 if (page->mapping && !PageAnon(page))
2102 return;
2103 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_MAPPED);
2106 void mem_cgroup_uncharge_cache_page(struct page *page)
2108 VM_BUG_ON(page_mapped(page));
2109 VM_BUG_ON(page->mapping);
2110 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE);
2114 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
2115 * In that cases, pages are freed continuously and we can expect pages
2116 * are in the same memcg. All these calls itself limits the number of
2117 * pages freed at once, then uncharge_start/end() is called properly.
2118 * This may be called prural(2) times in a context,
2121 void mem_cgroup_uncharge_start(void)
2123 current->memcg_batch.do_batch++;
2124 /* We can do nest. */
2125 if (current->memcg_batch.do_batch == 1) {
2126 current->memcg_batch.memcg = NULL;
2127 current->memcg_batch.bytes = 0;
2128 current->memcg_batch.memsw_bytes = 0;
2132 void mem_cgroup_uncharge_end(void)
2134 struct memcg_batch_info *batch = &current->memcg_batch;
2136 if (!batch->do_batch)
2137 return;
2139 batch->do_batch--;
2140 if (batch->do_batch) /* If stacked, do nothing. */
2141 return;
2143 if (!batch->memcg)
2144 return;
2146 * This "batch->memcg" is valid without any css_get/put etc...
2147 * bacause we hide charges behind us.
2149 if (batch->bytes)
2150 res_counter_uncharge(&batch->memcg->res, batch->bytes);
2151 if (batch->memsw_bytes)
2152 res_counter_uncharge(&batch->memcg->memsw, batch->memsw_bytes);
2153 /* forget this pointer (for sanity check) */
2154 batch->memcg = NULL;
2157 #ifdef CONFIG_SWAP
2159 * called after __delete_from_swap_cache() and drop "page" account.
2160 * memcg information is recorded to swap_cgroup of "ent"
2162 void
2163 mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
2165 struct mem_cgroup *memcg;
2166 int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
2168 if (!swapout) /* this was a swap cache but the swap is unused ! */
2169 ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
2171 memcg = __mem_cgroup_uncharge_common(page, ctype);
2173 /* record memcg information */
2174 if (do_swap_account && swapout && memcg) {
2175 swap_cgroup_record(ent, css_id(&memcg->css));
2176 mem_cgroup_get(memcg);
2178 if (swapout && memcg)
2179 css_put(&memcg->css);
2181 #endif
2183 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
2185 * called from swap_entry_free(). remove record in swap_cgroup and
2186 * uncharge "memsw" account.
2188 void mem_cgroup_uncharge_swap(swp_entry_t ent)
2190 struct mem_cgroup *memcg;
2191 unsigned short id;
2193 if (!do_swap_account)
2194 return;
2196 id = swap_cgroup_record(ent, 0);
2197 rcu_read_lock();
2198 memcg = mem_cgroup_lookup(id);
2199 if (memcg) {
2201 * We uncharge this because swap is freed.
2202 * This memcg can be obsolete one. We avoid calling css_tryget
2204 if (!mem_cgroup_is_root(memcg))
2205 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
2206 mem_cgroup_swap_statistics(memcg, false);
2207 mem_cgroup_put(memcg);
2209 rcu_read_unlock();
2211 #endif
2214 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
2215 * page belongs to.
2217 int mem_cgroup_prepare_migration(struct page *page, struct mem_cgroup **ptr)
2219 struct page_cgroup *pc;
2220 struct mem_cgroup *mem = NULL;
2221 int ret = 0;
2223 if (mem_cgroup_disabled())
2224 return 0;
2226 pc = lookup_page_cgroup(page);
2227 lock_page_cgroup(pc);
2228 if (PageCgroupUsed(pc)) {
2229 mem = pc->mem_cgroup;
2230 css_get(&mem->css);
2232 unlock_page_cgroup(pc);
2234 if (mem) {
2235 ret = __mem_cgroup_try_charge(NULL, GFP_KERNEL, &mem, false,
2236 page);
2237 css_put(&mem->css);
2239 *ptr = mem;
2240 return ret;
2243 /* remove redundant charge if migration failed*/
2244 void mem_cgroup_end_migration(struct mem_cgroup *mem,
2245 struct page *oldpage, struct page *newpage)
2247 struct page *target, *unused;
2248 struct page_cgroup *pc;
2249 enum charge_type ctype;
2251 if (!mem)
2252 return;
2253 cgroup_exclude_rmdir(&mem->css);
2254 /* at migration success, oldpage->mapping is NULL. */
2255 if (oldpage->mapping) {
2256 target = oldpage;
2257 unused = NULL;
2258 } else {
2259 target = newpage;
2260 unused = oldpage;
2263 if (PageAnon(target))
2264 ctype = MEM_CGROUP_CHARGE_TYPE_MAPPED;
2265 else if (page_is_file_cache(target))
2266 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
2267 else
2268 ctype = MEM_CGROUP_CHARGE_TYPE_SHMEM;
2270 /* unused page is not on radix-tree now. */
2271 if (unused)
2272 __mem_cgroup_uncharge_common(unused, ctype);
2274 pc = lookup_page_cgroup(target);
2276 * __mem_cgroup_commit_charge() check PCG_USED bit of page_cgroup.
2277 * So, double-counting is effectively avoided.
2279 __mem_cgroup_commit_charge(mem, pc, ctype);
2282 * Both of oldpage and newpage are still under lock_page().
2283 * Then, we don't have to care about race in radix-tree.
2284 * But we have to be careful that this page is unmapped or not.
2286 * There is a case for !page_mapped(). At the start of
2287 * migration, oldpage was mapped. But now, it's zapped.
2288 * But we know *target* page is not freed/reused under us.
2289 * mem_cgroup_uncharge_page() does all necessary checks.
2291 if (ctype == MEM_CGROUP_CHARGE_TYPE_MAPPED)
2292 mem_cgroup_uncharge_page(target);
2294 * At migration, we may charge account against cgroup which has no tasks
2295 * So, rmdir()->pre_destroy() can be called while we do this charge.
2296 * In that case, we need to call pre_destroy() again. check it here.
2298 cgroup_release_and_wakeup_rmdir(&mem->css);
2302 * A call to try to shrink memory usage on charge failure at shmem's swapin.
2303 * Calling hierarchical_reclaim is not enough because we should update
2304 * last_oom_jiffies to prevent pagefault_out_of_memory from invoking global OOM.
2305 * Moreover considering hierarchy, we should reclaim from the mem_over_limit,
2306 * not from the memcg which this page would be charged to.
2307 * try_charge_swapin does all of these works properly.
2309 int mem_cgroup_shmem_charge_fallback(struct page *page,
2310 struct mm_struct *mm,
2311 gfp_t gfp_mask)
2313 struct mem_cgroup *mem = NULL;
2314 int ret;
2316 if (mem_cgroup_disabled())
2317 return 0;
2319 ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
2320 if (!ret)
2321 mem_cgroup_cancel_charge_swapin(mem); /* it does !mem check */
2323 return ret;
2326 static DEFINE_MUTEX(set_limit_mutex);
2328 static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
2329 unsigned long long val)
2331 int retry_count;
2332 int progress;
2333 u64 memswlimit;
2334 int ret = 0;
2335 int children = mem_cgroup_count_children(memcg);
2336 u64 curusage, oldusage;
2339 * For keeping hierarchical_reclaim simple, how long we should retry
2340 * is depends on callers. We set our retry-count to be function
2341 * of # of children which we should visit in this loop.
2343 retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
2345 oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
2347 while (retry_count) {
2348 if (signal_pending(current)) {
2349 ret = -EINTR;
2350 break;
2353 * Rather than hide all in some function, I do this in
2354 * open coded manner. You see what this really does.
2355 * We have to guarantee mem->res.limit < mem->memsw.limit.
2357 mutex_lock(&set_limit_mutex);
2358 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
2359 if (memswlimit < val) {
2360 ret = -EINVAL;
2361 mutex_unlock(&set_limit_mutex);
2362 break;
2364 ret = res_counter_set_limit(&memcg->res, val);
2365 if (!ret) {
2366 if (memswlimit == val)
2367 memcg->memsw_is_minimum = true;
2368 else
2369 memcg->memsw_is_minimum = false;
2371 mutex_unlock(&set_limit_mutex);
2373 if (!ret)
2374 break;
2376 progress = mem_cgroup_hierarchical_reclaim(memcg, NULL,
2377 GFP_KERNEL,
2378 MEM_CGROUP_RECLAIM_SHRINK);
2379 curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
2380 /* Usage is reduced ? */
2381 if (curusage >= oldusage)
2382 retry_count--;
2383 else
2384 oldusage = curusage;
2387 return ret;
2390 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
2391 unsigned long long val)
2393 int retry_count;
2394 u64 memlimit, oldusage, curusage;
2395 int children = mem_cgroup_count_children(memcg);
2396 int ret = -EBUSY;
2398 /* see mem_cgroup_resize_res_limit */
2399 retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
2400 oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
2401 while (retry_count) {
2402 if (signal_pending(current)) {
2403 ret = -EINTR;
2404 break;
2407 * Rather than hide all in some function, I do this in
2408 * open coded manner. You see what this really does.
2409 * We have to guarantee mem->res.limit < mem->memsw.limit.
2411 mutex_lock(&set_limit_mutex);
2412 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
2413 if (memlimit > val) {
2414 ret = -EINVAL;
2415 mutex_unlock(&set_limit_mutex);
2416 break;
2418 ret = res_counter_set_limit(&memcg->memsw, val);
2419 if (!ret) {
2420 if (memlimit == val)
2421 memcg->memsw_is_minimum = true;
2422 else
2423 memcg->memsw_is_minimum = false;
2425 mutex_unlock(&set_limit_mutex);
2427 if (!ret)
2428 break;
2430 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
2431 MEM_CGROUP_RECLAIM_NOSWAP |
2432 MEM_CGROUP_RECLAIM_SHRINK);
2433 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
2434 /* Usage is reduced ? */
2435 if (curusage >= oldusage)
2436 retry_count--;
2437 else
2438 oldusage = curusage;
2440 return ret;
2443 unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
2444 gfp_t gfp_mask, int nid,
2445 int zid)
2447 unsigned long nr_reclaimed = 0;
2448 struct mem_cgroup_per_zone *mz, *next_mz = NULL;
2449 unsigned long reclaimed;
2450 int loop = 0;
2451 struct mem_cgroup_tree_per_zone *mctz;
2452 unsigned long long excess;
2454 if (order > 0)
2455 return 0;
2457 mctz = soft_limit_tree_node_zone(nid, zid);
2459 * This loop can run a while, specially if mem_cgroup's continuously
2460 * keep exceeding their soft limit and putting the system under
2461 * pressure
2463 do {
2464 if (next_mz)
2465 mz = next_mz;
2466 else
2467 mz = mem_cgroup_largest_soft_limit_node(mctz);
2468 if (!mz)
2469 break;
2471 reclaimed = mem_cgroup_hierarchical_reclaim(mz->mem, zone,
2472 gfp_mask,
2473 MEM_CGROUP_RECLAIM_SOFT);
2474 nr_reclaimed += reclaimed;
2475 spin_lock(&mctz->lock);
2478 * If we failed to reclaim anything from this memory cgroup
2479 * it is time to move on to the next cgroup
2481 next_mz = NULL;
2482 if (!reclaimed) {
2483 do {
2485 * Loop until we find yet another one.
2487 * By the time we get the soft_limit lock
2488 * again, someone might have aded the
2489 * group back on the RB tree. Iterate to
2490 * make sure we get a different mem.
2491 * mem_cgroup_largest_soft_limit_node returns
2492 * NULL if no other cgroup is present on
2493 * the tree
2495 next_mz =
2496 __mem_cgroup_largest_soft_limit_node(mctz);
2497 if (next_mz == mz) {
2498 css_put(&next_mz->mem->css);
2499 next_mz = NULL;
2500 } else /* next_mz == NULL or other memcg */
2501 break;
2502 } while (1);
2504 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
2505 excess = res_counter_soft_limit_excess(&mz->mem->res);
2507 * One school of thought says that we should not add
2508 * back the node to the tree if reclaim returns 0.
2509 * But our reclaim could return 0, simply because due
2510 * to priority we are exposing a smaller subset of
2511 * memory to reclaim from. Consider this as a longer
2512 * term TODO.
2514 /* If excess == 0, no tree ops */
2515 __mem_cgroup_insert_exceeded(mz->mem, mz, mctz, excess);
2516 spin_unlock(&mctz->lock);
2517 css_put(&mz->mem->css);
2518 loop++;
2520 * Could not reclaim anything and there are no more
2521 * mem cgroups to try or we seem to be looping without
2522 * reclaiming anything.
2524 if (!nr_reclaimed &&
2525 (next_mz == NULL ||
2526 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
2527 break;
2528 } while (!nr_reclaimed);
2529 if (next_mz)
2530 css_put(&next_mz->mem->css);
2531 return nr_reclaimed;
2535 * This routine traverse page_cgroup in given list and drop them all.
2536 * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
2538 static int mem_cgroup_force_empty_list(struct mem_cgroup *mem,
2539 int node, int zid, enum lru_list lru)
2541 struct zone *zone;
2542 struct mem_cgroup_per_zone *mz;
2543 struct page_cgroup *pc, *busy;
2544 unsigned long flags, loop;
2545 struct list_head *list;
2546 int ret = 0;
2548 zone = &NODE_DATA(node)->node_zones[zid];
2549 mz = mem_cgroup_zoneinfo(mem, node, zid);
2550 list = &mz->lists[lru];
2552 loop = MEM_CGROUP_ZSTAT(mz, lru);
2553 /* give some margin against EBUSY etc...*/
2554 loop += 256;
2555 busy = NULL;
2556 while (loop--) {
2557 ret = 0;
2558 spin_lock_irqsave(&zone->lru_lock, flags);
2559 if (list_empty(list)) {
2560 spin_unlock_irqrestore(&zone->lru_lock, flags);
2561 break;
2563 pc = list_entry(list->prev, struct page_cgroup, lru);
2564 if (busy == pc) {
2565 list_move(&pc->lru, list);
2566 busy = 0;
2567 spin_unlock_irqrestore(&zone->lru_lock, flags);
2568 continue;
2570 spin_unlock_irqrestore(&zone->lru_lock, flags);
2572 ret = mem_cgroup_move_parent(pc, mem, GFP_KERNEL);
2573 if (ret == -ENOMEM)
2574 break;
2576 if (ret == -EBUSY || ret == -EINVAL) {
2577 /* found lock contention or "pc" is obsolete. */
2578 busy = pc;
2579 cond_resched();
2580 } else
2581 busy = NULL;
2584 if (!ret && !list_empty(list))
2585 return -EBUSY;
2586 return ret;
2590 * make mem_cgroup's charge to be 0 if there is no task.
2591 * This enables deleting this mem_cgroup.
2593 static int mem_cgroup_force_empty(struct mem_cgroup *mem, bool free_all)
2595 int ret;
2596 int node, zid, shrink;
2597 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
2598 struct cgroup *cgrp = mem->css.cgroup;
2600 css_get(&mem->css);
2602 shrink = 0;
2603 /* should free all ? */
2604 if (free_all)
2605 goto try_to_free;
2606 move_account:
2607 while (mem->res.usage > 0) {
2608 ret = -EBUSY;
2609 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
2610 goto out;
2611 ret = -EINTR;
2612 if (signal_pending(current))
2613 goto out;
2614 /* This is for making all *used* pages to be on LRU. */
2615 lru_add_drain_all();
2616 drain_all_stock_sync();
2617 ret = 0;
2618 for_each_node_state(node, N_HIGH_MEMORY) {
2619 for (zid = 0; !ret && zid < MAX_NR_ZONES; zid++) {
2620 enum lru_list l;
2621 for_each_lru(l) {
2622 ret = mem_cgroup_force_empty_list(mem,
2623 node, zid, l);
2624 if (ret)
2625 break;
2628 if (ret)
2629 break;
2631 /* it seems parent cgroup doesn't have enough mem */
2632 if (ret == -ENOMEM)
2633 goto try_to_free;
2634 cond_resched();
2636 ret = 0;
2637 out:
2638 css_put(&mem->css);
2639 return ret;
2641 try_to_free:
2642 /* returns EBUSY if there is a task or if we come here twice. */
2643 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children) || shrink) {
2644 ret = -EBUSY;
2645 goto out;
2647 /* we call try-to-free pages for make this cgroup empty */
2648 lru_add_drain_all();
2649 /* try to free all pages in this cgroup */
2650 shrink = 1;
2651 while (nr_retries && mem->res.usage > 0) {
2652 int progress;
2654 if (signal_pending(current)) {
2655 ret = -EINTR;
2656 goto out;
2658 progress = try_to_free_mem_cgroup_pages(mem, GFP_KERNEL,
2659 false, get_swappiness(mem));
2660 if (!progress) {
2661 nr_retries--;
2662 /* maybe some writeback is necessary */
2663 congestion_wait(BLK_RW_ASYNC, HZ/10);
2667 lru_add_drain();
2668 /* try move_account...there may be some *locked* pages. */
2669 if (mem->res.usage)
2670 goto move_account;
2671 ret = 0;
2672 goto out;
2675 int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
2677 return mem_cgroup_force_empty(mem_cgroup_from_cont(cont), true);
2681 static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
2683 return mem_cgroup_from_cont(cont)->use_hierarchy;
2686 static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
2687 u64 val)
2689 int retval = 0;
2690 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
2691 struct cgroup *parent = cont->parent;
2692 struct mem_cgroup *parent_mem = NULL;
2694 if (parent)
2695 parent_mem = mem_cgroup_from_cont(parent);
2697 cgroup_lock();
2699 * If parent's use_hiearchy is set, we can't make any modifications
2700 * in the child subtrees. If it is unset, then the change can
2701 * occur, provided the current cgroup has no children.
2703 * For the root cgroup, parent_mem is NULL, we allow value to be
2704 * set if there are no children.
2706 if ((!parent_mem || !parent_mem->use_hierarchy) &&
2707 (val == 1 || val == 0)) {
2708 if (list_empty(&cont->children))
2709 mem->use_hierarchy = val;
2710 else
2711 retval = -EBUSY;
2712 } else
2713 retval = -EINVAL;
2714 cgroup_unlock();
2716 return retval;
2719 struct mem_cgroup_idx_data {
2720 s64 val;
2721 enum mem_cgroup_stat_index idx;
2724 static int
2725 mem_cgroup_get_idx_stat(struct mem_cgroup *mem, void *data)
2727 struct mem_cgroup_idx_data *d = data;
2728 d->val += mem_cgroup_read_stat(&mem->stat, d->idx);
2729 return 0;
2732 static void
2733 mem_cgroup_get_recursive_idx_stat(struct mem_cgroup *mem,
2734 enum mem_cgroup_stat_index idx, s64 *val)
2736 struct mem_cgroup_idx_data d;
2737 d.idx = idx;
2738 d.val = 0;
2739 mem_cgroup_walk_tree(mem, &d, mem_cgroup_get_idx_stat);
2740 *val = d.val;
2743 static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft)
2745 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
2746 u64 idx_val, val;
2747 int type, name;
2749 type = MEMFILE_TYPE(cft->private);
2750 name = MEMFILE_ATTR(cft->private);
2751 switch (type) {
2752 case _MEM:
2753 if (name == RES_USAGE && mem_cgroup_is_root(mem)) {
2754 mem_cgroup_get_recursive_idx_stat(mem,
2755 MEM_CGROUP_STAT_CACHE, &idx_val);
2756 val = idx_val;
2757 mem_cgroup_get_recursive_idx_stat(mem,
2758 MEM_CGROUP_STAT_RSS, &idx_val);
2759 val += idx_val;
2760 val <<= PAGE_SHIFT;
2761 } else
2762 val = res_counter_read_u64(&mem->res, name);
2763 break;
2764 case _MEMSWAP:
2765 if (name == RES_USAGE && mem_cgroup_is_root(mem)) {
2766 mem_cgroup_get_recursive_idx_stat(mem,
2767 MEM_CGROUP_STAT_CACHE, &idx_val);
2768 val = idx_val;
2769 mem_cgroup_get_recursive_idx_stat(mem,
2770 MEM_CGROUP_STAT_RSS, &idx_val);
2771 val += idx_val;
2772 mem_cgroup_get_recursive_idx_stat(mem,
2773 MEM_CGROUP_STAT_SWAPOUT, &idx_val);
2774 val <<= PAGE_SHIFT;
2775 } else
2776 val = res_counter_read_u64(&mem->memsw, name);
2777 break;
2778 default:
2779 BUG();
2780 break;
2782 return val;
2785 * The user of this function is...
2786 * RES_LIMIT.
2788 static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
2789 const char *buffer)
2791 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
2792 int type, name;
2793 unsigned long long val;
2794 int ret;
2796 type = MEMFILE_TYPE(cft->private);
2797 name = MEMFILE_ATTR(cft->private);
2798 switch (name) {
2799 case RES_LIMIT:
2800 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
2801 ret = -EINVAL;
2802 break;
2804 /* This function does all necessary parse...reuse it */
2805 ret = res_counter_memparse_write_strategy(buffer, &val);
2806 if (ret)
2807 break;
2808 if (type == _MEM)
2809 ret = mem_cgroup_resize_limit(memcg, val);
2810 else
2811 ret = mem_cgroup_resize_memsw_limit(memcg, val);
2812 break;
2813 case RES_SOFT_LIMIT:
2814 ret = res_counter_memparse_write_strategy(buffer, &val);
2815 if (ret)
2816 break;
2818 * For memsw, soft limits are hard to implement in terms
2819 * of semantics, for now, we support soft limits for
2820 * control without swap
2822 if (type == _MEM)
2823 ret = res_counter_set_soft_limit(&memcg->res, val);
2824 else
2825 ret = -EINVAL;
2826 break;
2827 default:
2828 ret = -EINVAL; /* should be BUG() ? */
2829 break;
2831 return ret;
2834 static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
2835 unsigned long long *mem_limit, unsigned long long *memsw_limit)
2837 struct cgroup *cgroup;
2838 unsigned long long min_limit, min_memsw_limit, tmp;
2840 min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
2841 min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
2842 cgroup = memcg->css.cgroup;
2843 if (!memcg->use_hierarchy)
2844 goto out;
2846 while (cgroup->parent) {
2847 cgroup = cgroup->parent;
2848 memcg = mem_cgroup_from_cont(cgroup);
2849 if (!memcg->use_hierarchy)
2850 break;
2851 tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
2852 min_limit = min(min_limit, tmp);
2853 tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
2854 min_memsw_limit = min(min_memsw_limit, tmp);
2856 out:
2857 *mem_limit = min_limit;
2858 *memsw_limit = min_memsw_limit;
2859 return;
2862 static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
2864 struct mem_cgroup *mem;
2865 int type, name;
2867 mem = mem_cgroup_from_cont(cont);
2868 type = MEMFILE_TYPE(event);
2869 name = MEMFILE_ATTR(event);
2870 switch (name) {
2871 case RES_MAX_USAGE:
2872 if (type == _MEM)
2873 res_counter_reset_max(&mem->res);
2874 else
2875 res_counter_reset_max(&mem->memsw);
2876 break;
2877 case RES_FAILCNT:
2878 if (type == _MEM)
2879 res_counter_reset_failcnt(&mem->res);
2880 else
2881 res_counter_reset_failcnt(&mem->memsw);
2882 break;
2885 return 0;
2889 /* For read statistics */
2890 enum {
2891 MCS_CACHE,
2892 MCS_RSS,
2893 MCS_MAPPED_FILE,
2894 MCS_PGPGIN,
2895 MCS_PGPGOUT,
2896 MCS_SWAP,
2897 MCS_INACTIVE_ANON,
2898 MCS_ACTIVE_ANON,
2899 MCS_INACTIVE_FILE,
2900 MCS_ACTIVE_FILE,
2901 MCS_UNEVICTABLE,
2902 NR_MCS_STAT,
2905 struct mcs_total_stat {
2906 s64 stat[NR_MCS_STAT];
2909 struct {
2910 char *local_name;
2911 char *total_name;
2912 } memcg_stat_strings[NR_MCS_STAT] = {
2913 {"cache", "total_cache"},
2914 {"rss", "total_rss"},
2915 {"mapped_file", "total_mapped_file"},
2916 {"pgpgin", "total_pgpgin"},
2917 {"pgpgout", "total_pgpgout"},
2918 {"swap", "total_swap"},
2919 {"inactive_anon", "total_inactive_anon"},
2920 {"active_anon", "total_active_anon"},
2921 {"inactive_file", "total_inactive_file"},
2922 {"active_file", "total_active_file"},
2923 {"unevictable", "total_unevictable"}
2927 static int mem_cgroup_get_local_stat(struct mem_cgroup *mem, void *data)
2929 struct mcs_total_stat *s = data;
2930 s64 val;
2932 /* per cpu stat */
2933 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_CACHE);
2934 s->stat[MCS_CACHE] += val * PAGE_SIZE;
2935 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_RSS);
2936 s->stat[MCS_RSS] += val * PAGE_SIZE;
2937 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_MAPPED_FILE);
2938 s->stat[MCS_MAPPED_FILE] += val * PAGE_SIZE;
2939 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_PGPGIN_COUNT);
2940 s->stat[MCS_PGPGIN] += val;
2941 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_PGPGOUT_COUNT);
2942 s->stat[MCS_PGPGOUT] += val;
2943 if (do_swap_account) {
2944 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_SWAPOUT);
2945 s->stat[MCS_SWAP] += val * PAGE_SIZE;
2948 /* per zone stat */
2949 val = mem_cgroup_get_local_zonestat(mem, LRU_INACTIVE_ANON);
2950 s->stat[MCS_INACTIVE_ANON] += val * PAGE_SIZE;
2951 val = mem_cgroup_get_local_zonestat(mem, LRU_ACTIVE_ANON);
2952 s->stat[MCS_ACTIVE_ANON] += val * PAGE_SIZE;
2953 val = mem_cgroup_get_local_zonestat(mem, LRU_INACTIVE_FILE);
2954 s->stat[MCS_INACTIVE_FILE] += val * PAGE_SIZE;
2955 val = mem_cgroup_get_local_zonestat(mem, LRU_ACTIVE_FILE);
2956 s->stat[MCS_ACTIVE_FILE] += val * PAGE_SIZE;
2957 val = mem_cgroup_get_local_zonestat(mem, LRU_UNEVICTABLE);
2958 s->stat[MCS_UNEVICTABLE] += val * PAGE_SIZE;
2959 return 0;
2962 static void
2963 mem_cgroup_get_total_stat(struct mem_cgroup *mem, struct mcs_total_stat *s)
2965 mem_cgroup_walk_tree(mem, s, mem_cgroup_get_local_stat);
2968 static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft,
2969 struct cgroup_map_cb *cb)
2971 struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
2972 struct mcs_total_stat mystat;
2973 int i;
2975 memset(&mystat, 0, sizeof(mystat));
2976 mem_cgroup_get_local_stat(mem_cont, &mystat);
2978 for (i = 0; i < NR_MCS_STAT; i++) {
2979 if (i == MCS_SWAP && !do_swap_account)
2980 continue;
2981 cb->fill(cb, memcg_stat_strings[i].local_name, mystat.stat[i]);
2984 /* Hierarchical information */
2986 unsigned long long limit, memsw_limit;
2987 memcg_get_hierarchical_limit(mem_cont, &limit, &memsw_limit);
2988 cb->fill(cb, "hierarchical_memory_limit", limit);
2989 if (do_swap_account)
2990 cb->fill(cb, "hierarchical_memsw_limit", memsw_limit);
2993 memset(&mystat, 0, sizeof(mystat));
2994 mem_cgroup_get_total_stat(mem_cont, &mystat);
2995 for (i = 0; i < NR_MCS_STAT; i++) {
2996 if (i == MCS_SWAP && !do_swap_account)
2997 continue;
2998 cb->fill(cb, memcg_stat_strings[i].total_name, mystat.stat[i]);
3001 #ifdef CONFIG_DEBUG_VM
3002 cb->fill(cb, "inactive_ratio", calc_inactive_ratio(mem_cont, NULL));
3005 int nid, zid;
3006 struct mem_cgroup_per_zone *mz;
3007 unsigned long recent_rotated[2] = {0, 0};
3008 unsigned long recent_scanned[2] = {0, 0};
3010 for_each_online_node(nid)
3011 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
3012 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
3014 recent_rotated[0] +=
3015 mz->reclaim_stat.recent_rotated[0];
3016 recent_rotated[1] +=
3017 mz->reclaim_stat.recent_rotated[1];
3018 recent_scanned[0] +=
3019 mz->reclaim_stat.recent_scanned[0];
3020 recent_scanned[1] +=
3021 mz->reclaim_stat.recent_scanned[1];
3023 cb->fill(cb, "recent_rotated_anon", recent_rotated[0]);
3024 cb->fill(cb, "recent_rotated_file", recent_rotated[1]);
3025 cb->fill(cb, "recent_scanned_anon", recent_scanned[0]);
3026 cb->fill(cb, "recent_scanned_file", recent_scanned[1]);
3028 #endif
3030 return 0;
3033 static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
3035 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3037 return get_swappiness(memcg);
3040 static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
3041 u64 val)
3043 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3044 struct mem_cgroup *parent;
3046 if (val > 100)
3047 return -EINVAL;
3049 if (cgrp->parent == NULL)
3050 return -EINVAL;
3052 parent = mem_cgroup_from_cont(cgrp->parent);
3054 cgroup_lock();
3056 /* If under hierarchy, only empty-root can set this value */
3057 if ((parent->use_hierarchy) ||
3058 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
3059 cgroup_unlock();
3060 return -EINVAL;
3063 spin_lock(&memcg->reclaim_param_lock);
3064 memcg->swappiness = val;
3065 spin_unlock(&memcg->reclaim_param_lock);
3067 cgroup_unlock();
3069 return 0;
3073 static struct cftype mem_cgroup_files[] = {
3075 .name = "usage_in_bytes",
3076 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
3077 .read_u64 = mem_cgroup_read,
3080 .name = "max_usage_in_bytes",
3081 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
3082 .trigger = mem_cgroup_reset,
3083 .read_u64 = mem_cgroup_read,
3086 .name = "limit_in_bytes",
3087 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
3088 .write_string = mem_cgroup_write,
3089 .read_u64 = mem_cgroup_read,
3092 .name = "soft_limit_in_bytes",
3093 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
3094 .write_string = mem_cgroup_write,
3095 .read_u64 = mem_cgroup_read,
3098 .name = "failcnt",
3099 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
3100 .trigger = mem_cgroup_reset,
3101 .read_u64 = mem_cgroup_read,
3104 .name = "stat",
3105 .read_map = mem_control_stat_show,
3108 .name = "force_empty",
3109 .trigger = mem_cgroup_force_empty_write,
3112 .name = "use_hierarchy",
3113 .write_u64 = mem_cgroup_hierarchy_write,
3114 .read_u64 = mem_cgroup_hierarchy_read,
3117 .name = "swappiness",
3118 .read_u64 = mem_cgroup_swappiness_read,
3119 .write_u64 = mem_cgroup_swappiness_write,
3123 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3124 static struct cftype memsw_cgroup_files[] = {
3126 .name = "memsw.usage_in_bytes",
3127 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
3128 .read_u64 = mem_cgroup_read,
3131 .name = "memsw.max_usage_in_bytes",
3132 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
3133 .trigger = mem_cgroup_reset,
3134 .read_u64 = mem_cgroup_read,
3137 .name = "memsw.limit_in_bytes",
3138 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
3139 .write_string = mem_cgroup_write,
3140 .read_u64 = mem_cgroup_read,
3143 .name = "memsw.failcnt",
3144 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
3145 .trigger = mem_cgroup_reset,
3146 .read_u64 = mem_cgroup_read,
3150 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
3152 if (!do_swap_account)
3153 return 0;
3154 return cgroup_add_files(cont, ss, memsw_cgroup_files,
3155 ARRAY_SIZE(memsw_cgroup_files));
3157 #else
3158 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
3160 return 0;
3162 #endif
3164 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
3166 struct mem_cgroup_per_node *pn;
3167 struct mem_cgroup_per_zone *mz;
3168 enum lru_list l;
3169 int zone, tmp = node;
3171 * This routine is called against possible nodes.
3172 * But it's BUG to call kmalloc() against offline node.
3174 * TODO: this routine can waste much memory for nodes which will
3175 * never be onlined. It's better to use memory hotplug callback
3176 * function.
3178 if (!node_state(node, N_NORMAL_MEMORY))
3179 tmp = -1;
3180 pn = kmalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
3181 if (!pn)
3182 return 1;
3184 mem->info.nodeinfo[node] = pn;
3185 memset(pn, 0, sizeof(*pn));
3187 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3188 mz = &pn->zoneinfo[zone];
3189 for_each_lru(l)
3190 INIT_LIST_HEAD(&mz->lists[l]);
3191 mz->usage_in_excess = 0;
3192 mz->on_tree = false;
3193 mz->mem = mem;
3195 return 0;
3198 static void free_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
3200 kfree(mem->info.nodeinfo[node]);
3203 static int mem_cgroup_size(void)
3205 int cpustat_size = nr_cpu_ids * sizeof(struct mem_cgroup_stat_cpu);
3206 return sizeof(struct mem_cgroup) + cpustat_size;
3209 static struct mem_cgroup *mem_cgroup_alloc(void)
3211 struct mem_cgroup *mem;
3212 int size = mem_cgroup_size();
3214 if (size < PAGE_SIZE)
3215 mem = kmalloc(size, GFP_KERNEL);
3216 else
3217 mem = vmalloc(size);
3219 if (mem)
3220 memset(mem, 0, size);
3221 return mem;
3225 * At destroying mem_cgroup, references from swap_cgroup can remain.
3226 * (scanning all at force_empty is too costly...)
3228 * Instead of clearing all references at force_empty, we remember
3229 * the number of reference from swap_cgroup and free mem_cgroup when
3230 * it goes down to 0.
3232 * Removal of cgroup itself succeeds regardless of refs from swap.
3235 static void __mem_cgroup_free(struct mem_cgroup *mem)
3237 int node;
3239 mem_cgroup_remove_from_trees(mem);
3240 free_css_id(&mem_cgroup_subsys, &mem->css);
3242 for_each_node_state(node, N_POSSIBLE)
3243 free_mem_cgroup_per_zone_info(mem, node);
3245 if (mem_cgroup_size() < PAGE_SIZE)
3246 kfree(mem);
3247 else
3248 vfree(mem);
3251 static void mem_cgroup_get(struct mem_cgroup *mem)
3253 atomic_inc(&mem->refcnt);
3256 static void mem_cgroup_put(struct mem_cgroup *mem)
3258 if (atomic_dec_and_test(&mem->refcnt)) {
3259 struct mem_cgroup *parent = parent_mem_cgroup(mem);
3260 __mem_cgroup_free(mem);
3261 if (parent)
3262 mem_cgroup_put(parent);
3267 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
3269 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem)
3271 if (!mem->res.parent)
3272 return NULL;
3273 return mem_cgroup_from_res_counter(mem->res.parent, res);
3276 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3277 static void __init enable_swap_cgroup(void)
3279 if (!mem_cgroup_disabled() && really_do_swap_account)
3280 do_swap_account = 1;
3282 #else
3283 static void __init enable_swap_cgroup(void)
3286 #endif
3288 static int mem_cgroup_soft_limit_tree_init(void)
3290 struct mem_cgroup_tree_per_node *rtpn;
3291 struct mem_cgroup_tree_per_zone *rtpz;
3292 int tmp, node, zone;
3294 for_each_node_state(node, N_POSSIBLE) {
3295 tmp = node;
3296 if (!node_state(node, N_NORMAL_MEMORY))
3297 tmp = -1;
3298 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
3299 if (!rtpn)
3300 return 1;
3302 soft_limit_tree.rb_tree_per_node[node] = rtpn;
3304 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3305 rtpz = &rtpn->rb_tree_per_zone[zone];
3306 rtpz->rb_root = RB_ROOT;
3307 spin_lock_init(&rtpz->lock);
3310 return 0;
3313 static struct cgroup_subsys_state * __ref
3314 mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
3316 struct mem_cgroup *mem, *parent;
3317 long error = -ENOMEM;
3318 int node;
3320 mem = mem_cgroup_alloc();
3321 if (!mem)
3322 return ERR_PTR(error);
3324 for_each_node_state(node, N_POSSIBLE)
3325 if (alloc_mem_cgroup_per_zone_info(mem, node))
3326 goto free_out;
3328 /* root ? */
3329 if (cont->parent == NULL) {
3330 enable_swap_cgroup();
3331 parent = NULL;
3332 root_mem_cgroup = mem;
3333 if (mem_cgroup_soft_limit_tree_init())
3334 goto free_out;
3335 hotcpu_notifier(memcg_stock_cpu_callback, 0);
3337 } else {
3338 parent = mem_cgroup_from_cont(cont->parent);
3339 mem->use_hierarchy = parent->use_hierarchy;
3342 if (parent && parent->use_hierarchy) {
3343 res_counter_init(&mem->res, &parent->res);
3344 res_counter_init(&mem->memsw, &parent->memsw);
3346 * We increment refcnt of the parent to ensure that we can
3347 * safely access it on res_counter_charge/uncharge.
3348 * This refcnt will be decremented when freeing this
3349 * mem_cgroup(see mem_cgroup_put).
3351 mem_cgroup_get(parent);
3352 } else {
3353 res_counter_init(&mem->res, NULL);
3354 res_counter_init(&mem->memsw, NULL);
3356 mem->last_scanned_child = 0;
3357 spin_lock_init(&mem->reclaim_param_lock);
3359 if (parent)
3360 mem->swappiness = get_swappiness(parent);
3361 atomic_set(&mem->refcnt, 1);
3362 return &mem->css;
3363 free_out:
3364 __mem_cgroup_free(mem);
3365 root_mem_cgroup = NULL;
3366 return ERR_PTR(error);
3369 static int mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
3370 struct cgroup *cont)
3372 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
3374 return mem_cgroup_force_empty(mem, false);
3377 static void mem_cgroup_destroy(struct cgroup_subsys *ss,
3378 struct cgroup *cont)
3380 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
3382 mem_cgroup_put(mem);
3385 static int mem_cgroup_populate(struct cgroup_subsys *ss,
3386 struct cgroup *cont)
3388 int ret;
3390 ret = cgroup_add_files(cont, ss, mem_cgroup_files,
3391 ARRAY_SIZE(mem_cgroup_files));
3393 if (!ret)
3394 ret = register_memsw_files(cont, ss);
3395 return ret;
3398 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
3399 struct cgroup *cont,
3400 struct cgroup *old_cont,
3401 struct task_struct *p,
3402 bool threadgroup)
3404 mutex_lock(&memcg_tasklist);
3406 * FIXME: It's better to move charges of this process from old
3407 * memcg to new memcg. But it's just on TODO-List now.
3409 mutex_unlock(&memcg_tasklist);
3412 struct cgroup_subsys mem_cgroup_subsys = {
3413 .name = "memory",
3414 .subsys_id = mem_cgroup_subsys_id,
3415 .create = mem_cgroup_create,
3416 .pre_destroy = mem_cgroup_pre_destroy,
3417 .destroy = mem_cgroup_destroy,
3418 .populate = mem_cgroup_populate,
3419 .attach = mem_cgroup_move_task,
3420 .early_init = 0,
3421 .use_id = 1,
3424 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3426 static int __init disable_swap_account(char *s)
3428 really_do_swap_account = 0;
3429 return 1;
3431 __setup("noswapaccount", disable_swap_account);
3432 #endif