Merge branch 'kconfig' of git://git.kernel.org/pub/scm/linux/kernel/git/mmarek/kbuild
[linux-2.6.git] / mm / memcontrol.c
blob7af1d5ee1598d485ced61f57c1b165fac4e0808d
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 * Memory thresholds
10 * Copyright (C) 2009 Nokia Corporation
11 * Author: Kirill A. Shutemov
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
24 #include <linux/res_counter.h>
25 #include <linux/memcontrol.h>
26 #include <linux/cgroup.h>
27 #include <linux/mm.h>
28 #include <linux/hugetlb.h>
29 #include <linux/pagemap.h>
30 #include <linux/smp.h>
31 #include <linux/page-flags.h>
32 #include <linux/backing-dev.h>
33 #include <linux/bit_spinlock.h>
34 #include <linux/rcupdate.h>
35 #include <linux/limits.h>
36 #include <linux/mutex.h>
37 #include <linux/rbtree.h>
38 #include <linux/slab.h>
39 #include <linux/swap.h>
40 #include <linux/swapops.h>
41 #include <linux/spinlock.h>
42 #include <linux/eventfd.h>
43 #include <linux/sort.h>
44 #include <linux/fs.h>
45 #include <linux/seq_file.h>
46 #include <linux/vmalloc.h>
47 #include <linux/mm_inline.h>
48 #include <linux/page_cgroup.h>
49 #include <linux/cpu.h>
50 #include <linux/oom.h>
51 #include "internal.h"
53 #include <asm/uaccess.h>
55 #include <trace/events/vmscan.h>
57 struct cgroup_subsys mem_cgroup_subsys __read_mostly;
58 #define MEM_CGROUP_RECLAIM_RETRIES 5
59 struct mem_cgroup *root_mem_cgroup __read_mostly;
61 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
62 /* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
63 int do_swap_account __read_mostly;
65 /* for remember boot option*/
66 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP_ENABLED
67 static int really_do_swap_account __initdata = 1;
68 #else
69 static int really_do_swap_account __initdata = 0;
70 #endif
72 #else
73 #define do_swap_account (0)
74 #endif
78 * Statistics for memory cgroup.
80 enum mem_cgroup_stat_index {
82 * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
84 MEM_CGROUP_STAT_CACHE, /* # of pages charged as cache */
85 MEM_CGROUP_STAT_RSS, /* # of pages charged as anon rss */
86 MEM_CGROUP_STAT_FILE_MAPPED, /* # of pages charged as file rss */
87 MEM_CGROUP_STAT_SWAPOUT, /* # of pages, swapped out */
88 MEM_CGROUP_STAT_DATA, /* end of data requires synchronization */
89 MEM_CGROUP_ON_MOVE, /* someone is moving account between groups */
90 MEM_CGROUP_STAT_NSTATS,
93 enum mem_cgroup_events_index {
94 MEM_CGROUP_EVENTS_PGPGIN, /* # of pages paged in */
95 MEM_CGROUP_EVENTS_PGPGOUT, /* # of pages paged out */
96 MEM_CGROUP_EVENTS_COUNT, /* # of pages paged in/out */
97 MEM_CGROUP_EVENTS_PGFAULT, /* # of page-faults */
98 MEM_CGROUP_EVENTS_PGMAJFAULT, /* # of major page-faults */
99 MEM_CGROUP_EVENTS_NSTATS,
102 * Per memcg event counter is incremented at every pagein/pageout. With THP,
103 * it will be incremated by the number of pages. This counter is used for
104 * for trigger some periodic events. This is straightforward and better
105 * than using jiffies etc. to handle periodic memcg event.
107 enum mem_cgroup_events_target {
108 MEM_CGROUP_TARGET_THRESH,
109 MEM_CGROUP_TARGET_SOFTLIMIT,
110 MEM_CGROUP_TARGET_NUMAINFO,
111 MEM_CGROUP_NTARGETS,
113 #define THRESHOLDS_EVENTS_TARGET (128)
114 #define SOFTLIMIT_EVENTS_TARGET (1024)
115 #define NUMAINFO_EVENTS_TARGET (1024)
117 struct mem_cgroup_stat_cpu {
118 long count[MEM_CGROUP_STAT_NSTATS];
119 unsigned long events[MEM_CGROUP_EVENTS_NSTATS];
120 unsigned long targets[MEM_CGROUP_NTARGETS];
124 * per-zone information in memory controller.
126 struct mem_cgroup_per_zone {
128 * spin_lock to protect the per cgroup LRU
130 struct list_head lists[NR_LRU_LISTS];
131 unsigned long count[NR_LRU_LISTS];
133 struct zone_reclaim_stat reclaim_stat;
134 struct rb_node tree_node; /* RB tree node */
135 unsigned long long usage_in_excess;/* Set to the value by which */
136 /* the soft limit is exceeded*/
137 bool on_tree;
138 struct mem_cgroup *mem; /* Back pointer, we cannot */
139 /* use container_of */
141 /* Macro for accessing counter */
142 #define MEM_CGROUP_ZSTAT(mz, idx) ((mz)->count[(idx)])
144 struct mem_cgroup_per_node {
145 struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
148 struct mem_cgroup_lru_info {
149 struct mem_cgroup_per_node *nodeinfo[MAX_NUMNODES];
153 * Cgroups above their limits are maintained in a RB-Tree, independent of
154 * their hierarchy representation
157 struct mem_cgroup_tree_per_zone {
158 struct rb_root rb_root;
159 spinlock_t lock;
162 struct mem_cgroup_tree_per_node {
163 struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
166 struct mem_cgroup_tree {
167 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
170 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
172 struct mem_cgroup_threshold {
173 struct eventfd_ctx *eventfd;
174 u64 threshold;
177 /* For threshold */
178 struct mem_cgroup_threshold_ary {
179 /* An array index points to threshold just below usage. */
180 int current_threshold;
181 /* Size of entries[] */
182 unsigned int size;
183 /* Array of thresholds */
184 struct mem_cgroup_threshold entries[0];
187 struct mem_cgroup_thresholds {
188 /* Primary thresholds array */
189 struct mem_cgroup_threshold_ary *primary;
191 * Spare threshold array.
192 * This is needed to make mem_cgroup_unregister_event() "never fail".
193 * It must be able to store at least primary->size - 1 entries.
195 struct mem_cgroup_threshold_ary *spare;
198 /* for OOM */
199 struct mem_cgroup_eventfd_list {
200 struct list_head list;
201 struct eventfd_ctx *eventfd;
204 static void mem_cgroup_threshold(struct mem_cgroup *memcg);
205 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
208 * The memory controller data structure. The memory controller controls both
209 * page cache and RSS per cgroup. We would eventually like to provide
210 * statistics based on the statistics developed by Rik Van Riel for clock-pro,
211 * to help the administrator determine what knobs to tune.
213 * TODO: Add a water mark for the memory controller. Reclaim will begin when
214 * we hit the water mark. May be even add a low water mark, such that
215 * no reclaim occurs from a cgroup at it's low water mark, this is
216 * a feature that will be implemented much later in the future.
218 struct mem_cgroup {
219 struct cgroup_subsys_state css;
221 * the counter to account for memory usage
223 struct res_counter res;
225 * the counter to account for mem+swap usage.
227 struct res_counter memsw;
229 * Per cgroup active and inactive list, similar to the
230 * per zone LRU lists.
232 struct mem_cgroup_lru_info info;
234 * While reclaiming in a hierarchy, we cache the last child we
235 * reclaimed from.
237 int last_scanned_child;
238 int last_scanned_node;
239 #if MAX_NUMNODES > 1
240 nodemask_t scan_nodes;
241 atomic_t numainfo_events;
242 atomic_t numainfo_updating;
243 #endif
245 * Should the accounting and control be hierarchical, per subtree?
247 bool use_hierarchy;
249 bool oom_lock;
250 atomic_t under_oom;
252 atomic_t refcnt;
254 int swappiness;
255 /* OOM-Killer disable */
256 int oom_kill_disable;
258 /* set when res.limit == memsw.limit */
259 bool memsw_is_minimum;
261 /* protect arrays of thresholds */
262 struct mutex thresholds_lock;
264 /* thresholds for memory usage. RCU-protected */
265 struct mem_cgroup_thresholds thresholds;
267 /* thresholds for mem+swap usage. RCU-protected */
268 struct mem_cgroup_thresholds memsw_thresholds;
270 /* For oom notifier event fd */
271 struct list_head oom_notify;
274 * Should we move charges of a task when a task is moved into this
275 * mem_cgroup ? And what type of charges should we move ?
277 unsigned long move_charge_at_immigrate;
279 * percpu counter.
281 struct mem_cgroup_stat_cpu *stat;
283 * used when a cpu is offlined or other synchronizations
284 * See mem_cgroup_read_stat().
286 struct mem_cgroup_stat_cpu nocpu_base;
287 spinlock_t pcp_counter_lock;
290 /* Stuffs for move charges at task migration. */
292 * Types of charges to be moved. "move_charge_at_immitgrate" is treated as a
293 * left-shifted bitmap of these types.
295 enum move_type {
296 MOVE_CHARGE_TYPE_ANON, /* private anonymous page and swap of it */
297 MOVE_CHARGE_TYPE_FILE, /* file page(including tmpfs) and swap of it */
298 NR_MOVE_TYPE,
301 /* "mc" and its members are protected by cgroup_mutex */
302 static struct move_charge_struct {
303 spinlock_t lock; /* for from, to */
304 struct mem_cgroup *from;
305 struct mem_cgroup *to;
306 unsigned long precharge;
307 unsigned long moved_charge;
308 unsigned long moved_swap;
309 struct task_struct *moving_task; /* a task moving charges */
310 wait_queue_head_t waitq; /* a waitq for other context */
311 } mc = {
312 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
313 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
316 static bool move_anon(void)
318 return test_bit(MOVE_CHARGE_TYPE_ANON,
319 &mc.to->move_charge_at_immigrate);
322 static bool move_file(void)
324 return test_bit(MOVE_CHARGE_TYPE_FILE,
325 &mc.to->move_charge_at_immigrate);
329 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
330 * limit reclaim to prevent infinite loops, if they ever occur.
332 #define MEM_CGROUP_MAX_RECLAIM_LOOPS (100)
333 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS (2)
335 enum charge_type {
336 MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
337 MEM_CGROUP_CHARGE_TYPE_MAPPED,
338 MEM_CGROUP_CHARGE_TYPE_SHMEM, /* used by page migration of shmem */
339 MEM_CGROUP_CHARGE_TYPE_FORCE, /* used by force_empty */
340 MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
341 MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
342 NR_CHARGE_TYPE,
345 /* for encoding cft->private value on file */
346 #define _MEM (0)
347 #define _MEMSWAP (1)
348 #define _OOM_TYPE (2)
349 #define MEMFILE_PRIVATE(x, val) (((x) << 16) | (val))
350 #define MEMFILE_TYPE(val) (((val) >> 16) & 0xffff)
351 #define MEMFILE_ATTR(val) ((val) & 0xffff)
352 /* Used for OOM nofiier */
353 #define OOM_CONTROL (0)
356 * Reclaim flags for mem_cgroup_hierarchical_reclaim
358 #define MEM_CGROUP_RECLAIM_NOSWAP_BIT 0x0
359 #define MEM_CGROUP_RECLAIM_NOSWAP (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
360 #define MEM_CGROUP_RECLAIM_SHRINK_BIT 0x1
361 #define MEM_CGROUP_RECLAIM_SHRINK (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
362 #define MEM_CGROUP_RECLAIM_SOFT_BIT 0x2
363 #define MEM_CGROUP_RECLAIM_SOFT (1 << MEM_CGROUP_RECLAIM_SOFT_BIT)
365 static void mem_cgroup_get(struct mem_cgroup *memcg);
366 static void mem_cgroup_put(struct mem_cgroup *memcg);
367 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg);
368 static void drain_all_stock_async(struct mem_cgroup *memcg);
370 static struct mem_cgroup_per_zone *
371 mem_cgroup_zoneinfo(struct mem_cgroup *memcg, int nid, int zid)
373 return &memcg->info.nodeinfo[nid]->zoneinfo[zid];
376 struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *memcg)
378 return &memcg->css;
381 static struct mem_cgroup_per_zone *
382 page_cgroup_zoneinfo(struct mem_cgroup *memcg, struct page *page)
384 int nid = page_to_nid(page);
385 int zid = page_zonenum(page);
387 return mem_cgroup_zoneinfo(memcg, nid, zid);
390 static struct mem_cgroup_tree_per_zone *
391 soft_limit_tree_node_zone(int nid, int zid)
393 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
396 static struct mem_cgroup_tree_per_zone *
397 soft_limit_tree_from_page(struct page *page)
399 int nid = page_to_nid(page);
400 int zid = page_zonenum(page);
402 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
405 static void
406 __mem_cgroup_insert_exceeded(struct mem_cgroup *memcg,
407 struct mem_cgroup_per_zone *mz,
408 struct mem_cgroup_tree_per_zone *mctz,
409 unsigned long long new_usage_in_excess)
411 struct rb_node **p = &mctz->rb_root.rb_node;
412 struct rb_node *parent = NULL;
413 struct mem_cgroup_per_zone *mz_node;
415 if (mz->on_tree)
416 return;
418 mz->usage_in_excess = new_usage_in_excess;
419 if (!mz->usage_in_excess)
420 return;
421 while (*p) {
422 parent = *p;
423 mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
424 tree_node);
425 if (mz->usage_in_excess < mz_node->usage_in_excess)
426 p = &(*p)->rb_left;
428 * We can't avoid mem cgroups that are over their soft
429 * limit by the same amount
431 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
432 p = &(*p)->rb_right;
434 rb_link_node(&mz->tree_node, parent, p);
435 rb_insert_color(&mz->tree_node, &mctz->rb_root);
436 mz->on_tree = true;
439 static void
440 __mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
441 struct mem_cgroup_per_zone *mz,
442 struct mem_cgroup_tree_per_zone *mctz)
444 if (!mz->on_tree)
445 return;
446 rb_erase(&mz->tree_node, &mctz->rb_root);
447 mz->on_tree = false;
450 static void
451 mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
452 struct mem_cgroup_per_zone *mz,
453 struct mem_cgroup_tree_per_zone *mctz)
455 spin_lock(&mctz->lock);
456 __mem_cgroup_remove_exceeded(memcg, mz, mctz);
457 spin_unlock(&mctz->lock);
461 static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
463 unsigned long long excess;
464 struct mem_cgroup_per_zone *mz;
465 struct mem_cgroup_tree_per_zone *mctz;
466 int nid = page_to_nid(page);
467 int zid = page_zonenum(page);
468 mctz = soft_limit_tree_from_page(page);
471 * Necessary to update all ancestors when hierarchy is used.
472 * because their event counter is not touched.
474 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
475 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
476 excess = res_counter_soft_limit_excess(&memcg->res);
478 * We have to update the tree if mz is on RB-tree or
479 * mem is over its softlimit.
481 if (excess || mz->on_tree) {
482 spin_lock(&mctz->lock);
483 /* if on-tree, remove it */
484 if (mz->on_tree)
485 __mem_cgroup_remove_exceeded(memcg, mz, mctz);
487 * Insert again. mz->usage_in_excess will be updated.
488 * If excess is 0, no tree ops.
490 __mem_cgroup_insert_exceeded(memcg, mz, mctz, excess);
491 spin_unlock(&mctz->lock);
496 static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
498 int node, zone;
499 struct mem_cgroup_per_zone *mz;
500 struct mem_cgroup_tree_per_zone *mctz;
502 for_each_node_state(node, N_POSSIBLE) {
503 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
504 mz = mem_cgroup_zoneinfo(memcg, node, zone);
505 mctz = soft_limit_tree_node_zone(node, zone);
506 mem_cgroup_remove_exceeded(memcg, mz, mctz);
511 static struct mem_cgroup_per_zone *
512 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
514 struct rb_node *rightmost = NULL;
515 struct mem_cgroup_per_zone *mz;
517 retry:
518 mz = NULL;
519 rightmost = rb_last(&mctz->rb_root);
520 if (!rightmost)
521 goto done; /* Nothing to reclaim from */
523 mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
525 * Remove the node now but someone else can add it back,
526 * we will to add it back at the end of reclaim to its correct
527 * position in the tree.
529 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
530 if (!res_counter_soft_limit_excess(&mz->mem->res) ||
531 !css_tryget(&mz->mem->css))
532 goto retry;
533 done:
534 return mz;
537 static struct mem_cgroup_per_zone *
538 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
540 struct mem_cgroup_per_zone *mz;
542 spin_lock(&mctz->lock);
543 mz = __mem_cgroup_largest_soft_limit_node(mctz);
544 spin_unlock(&mctz->lock);
545 return mz;
549 * Implementation Note: reading percpu statistics for memcg.
551 * Both of vmstat[] and percpu_counter has threshold and do periodic
552 * synchronization to implement "quick" read. There are trade-off between
553 * reading cost and precision of value. Then, we may have a chance to implement
554 * a periodic synchronizion of counter in memcg's counter.
556 * But this _read() function is used for user interface now. The user accounts
557 * memory usage by memory cgroup and he _always_ requires exact value because
558 * he accounts memory. Even if we provide quick-and-fuzzy read, we always
559 * have to visit all online cpus and make sum. So, for now, unnecessary
560 * synchronization is not implemented. (just implemented for cpu hotplug)
562 * If there are kernel internal actions which can make use of some not-exact
563 * value, and reading all cpu value can be performance bottleneck in some
564 * common workload, threashold and synchonization as vmstat[] should be
565 * implemented.
567 static long mem_cgroup_read_stat(struct mem_cgroup *memcg,
568 enum mem_cgroup_stat_index idx)
570 long val = 0;
571 int cpu;
573 get_online_cpus();
574 for_each_online_cpu(cpu)
575 val += per_cpu(memcg->stat->count[idx], cpu);
576 #ifdef CONFIG_HOTPLUG_CPU
577 spin_lock(&memcg->pcp_counter_lock);
578 val += memcg->nocpu_base.count[idx];
579 spin_unlock(&memcg->pcp_counter_lock);
580 #endif
581 put_online_cpus();
582 return val;
585 static void mem_cgroup_swap_statistics(struct mem_cgroup *memcg,
586 bool charge)
588 int val = (charge) ? 1 : -1;
589 this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_SWAPOUT], val);
592 void mem_cgroup_pgfault(struct mem_cgroup *memcg, int val)
594 this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_PGFAULT], val);
597 void mem_cgroup_pgmajfault(struct mem_cgroup *memcg, int val)
599 this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_PGMAJFAULT], val);
602 static unsigned long mem_cgroup_read_events(struct mem_cgroup *memcg,
603 enum mem_cgroup_events_index idx)
605 unsigned long val = 0;
606 int cpu;
608 for_each_online_cpu(cpu)
609 val += per_cpu(memcg->stat->events[idx], cpu);
610 #ifdef CONFIG_HOTPLUG_CPU
611 spin_lock(&memcg->pcp_counter_lock);
612 val += memcg->nocpu_base.events[idx];
613 spin_unlock(&memcg->pcp_counter_lock);
614 #endif
615 return val;
618 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
619 bool file, int nr_pages)
621 preempt_disable();
623 if (file)
624 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_CACHE],
625 nr_pages);
626 else
627 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS],
628 nr_pages);
630 /* pagein of a big page is an event. So, ignore page size */
631 if (nr_pages > 0)
632 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGIN]);
633 else {
634 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGOUT]);
635 nr_pages = -nr_pages; /* for event */
638 __this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_COUNT], nr_pages);
640 preempt_enable();
643 unsigned long
644 mem_cgroup_zone_nr_lru_pages(struct mem_cgroup *memcg, int nid, int zid,
645 unsigned int lru_mask)
647 struct mem_cgroup_per_zone *mz;
648 enum lru_list l;
649 unsigned long ret = 0;
651 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
653 for_each_lru(l) {
654 if (BIT(l) & lru_mask)
655 ret += MEM_CGROUP_ZSTAT(mz, l);
657 return ret;
660 static unsigned long
661 mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
662 int nid, unsigned int lru_mask)
664 u64 total = 0;
665 int zid;
667 for (zid = 0; zid < MAX_NR_ZONES; zid++)
668 total += mem_cgroup_zone_nr_lru_pages(memcg,
669 nid, zid, lru_mask);
671 return total;
674 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
675 unsigned int lru_mask)
677 int nid;
678 u64 total = 0;
680 for_each_node_state(nid, N_HIGH_MEMORY)
681 total += mem_cgroup_node_nr_lru_pages(memcg, nid, lru_mask);
682 return total;
685 static bool __memcg_event_check(struct mem_cgroup *memcg, int target)
687 unsigned long val, next;
689 val = __this_cpu_read(memcg->stat->events[MEM_CGROUP_EVENTS_COUNT]);
690 next = __this_cpu_read(memcg->stat->targets[target]);
691 /* from time_after() in jiffies.h */
692 return ((long)next - (long)val < 0);
695 static void __mem_cgroup_target_update(struct mem_cgroup *memcg, int target)
697 unsigned long val, next;
699 val = __this_cpu_read(memcg->stat->events[MEM_CGROUP_EVENTS_COUNT]);
701 switch (target) {
702 case MEM_CGROUP_TARGET_THRESH:
703 next = val + THRESHOLDS_EVENTS_TARGET;
704 break;
705 case MEM_CGROUP_TARGET_SOFTLIMIT:
706 next = val + SOFTLIMIT_EVENTS_TARGET;
707 break;
708 case MEM_CGROUP_TARGET_NUMAINFO:
709 next = val + NUMAINFO_EVENTS_TARGET;
710 break;
711 default:
712 return;
715 __this_cpu_write(memcg->stat->targets[target], next);
719 * Check events in order.
722 static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
724 preempt_disable();
725 /* threshold event is triggered in finer grain than soft limit */
726 if (unlikely(__memcg_event_check(memcg, MEM_CGROUP_TARGET_THRESH))) {
727 mem_cgroup_threshold(memcg);
728 __mem_cgroup_target_update(memcg, MEM_CGROUP_TARGET_THRESH);
729 if (unlikely(__memcg_event_check(memcg,
730 MEM_CGROUP_TARGET_SOFTLIMIT))) {
731 mem_cgroup_update_tree(memcg, page);
732 __mem_cgroup_target_update(memcg,
733 MEM_CGROUP_TARGET_SOFTLIMIT);
735 #if MAX_NUMNODES > 1
736 if (unlikely(__memcg_event_check(memcg,
737 MEM_CGROUP_TARGET_NUMAINFO))) {
738 atomic_inc(&memcg->numainfo_events);
739 __mem_cgroup_target_update(memcg,
740 MEM_CGROUP_TARGET_NUMAINFO);
742 #endif
744 preempt_enable();
747 static struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
749 return container_of(cgroup_subsys_state(cont,
750 mem_cgroup_subsys_id), struct mem_cgroup,
751 css);
754 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
757 * mm_update_next_owner() may clear mm->owner to NULL
758 * if it races with swapoff, page migration, etc.
759 * So this can be called with p == NULL.
761 if (unlikely(!p))
762 return NULL;
764 return container_of(task_subsys_state(p, mem_cgroup_subsys_id),
765 struct mem_cgroup, css);
768 struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
770 struct mem_cgroup *memcg = NULL;
772 if (!mm)
773 return NULL;
775 * Because we have no locks, mm->owner's may be being moved to other
776 * cgroup. We use css_tryget() here even if this looks
777 * pessimistic (rather than adding locks here).
779 rcu_read_lock();
780 do {
781 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
782 if (unlikely(!memcg))
783 break;
784 } while (!css_tryget(&memcg->css));
785 rcu_read_unlock();
786 return memcg;
789 /* The caller has to guarantee "mem" exists before calling this */
790 static struct mem_cgroup *mem_cgroup_start_loop(struct mem_cgroup *memcg)
792 struct cgroup_subsys_state *css;
793 int found;
795 if (!memcg) /* ROOT cgroup has the smallest ID */
796 return root_mem_cgroup; /*css_put/get against root is ignored*/
797 if (!memcg->use_hierarchy) {
798 if (css_tryget(&memcg->css))
799 return memcg;
800 return NULL;
802 rcu_read_lock();
804 * searching a memory cgroup which has the smallest ID under given
805 * ROOT cgroup. (ID >= 1)
807 css = css_get_next(&mem_cgroup_subsys, 1, &memcg->css, &found);
808 if (css && css_tryget(css))
809 memcg = container_of(css, struct mem_cgroup, css);
810 else
811 memcg = NULL;
812 rcu_read_unlock();
813 return memcg;
816 static struct mem_cgroup *mem_cgroup_get_next(struct mem_cgroup *iter,
817 struct mem_cgroup *root,
818 bool cond)
820 int nextid = css_id(&iter->css) + 1;
821 int found;
822 int hierarchy_used;
823 struct cgroup_subsys_state *css;
825 hierarchy_used = iter->use_hierarchy;
827 css_put(&iter->css);
828 /* If no ROOT, walk all, ignore hierarchy */
829 if (!cond || (root && !hierarchy_used))
830 return NULL;
832 if (!root)
833 root = root_mem_cgroup;
835 do {
836 iter = NULL;
837 rcu_read_lock();
839 css = css_get_next(&mem_cgroup_subsys, nextid,
840 &root->css, &found);
841 if (css && css_tryget(css))
842 iter = container_of(css, struct mem_cgroup, css);
843 rcu_read_unlock();
844 /* If css is NULL, no more cgroups will be found */
845 nextid = found + 1;
846 } while (css && !iter);
848 return iter;
851 * for_eacn_mem_cgroup_tree() for visiting all cgroup under tree. Please
852 * be careful that "break" loop is not allowed. We have reference count.
853 * Instead of that modify "cond" to be false and "continue" to exit the loop.
855 #define for_each_mem_cgroup_tree_cond(iter, root, cond) \
856 for (iter = mem_cgroup_start_loop(root);\
857 iter != NULL;\
858 iter = mem_cgroup_get_next(iter, root, cond))
860 #define for_each_mem_cgroup_tree(iter, root) \
861 for_each_mem_cgroup_tree_cond(iter, root, true)
863 #define for_each_mem_cgroup_all(iter) \
864 for_each_mem_cgroup_tree_cond(iter, NULL, true)
867 static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg)
869 return (memcg == root_mem_cgroup);
872 void mem_cgroup_count_vm_event(struct mm_struct *mm, enum vm_event_item idx)
874 struct mem_cgroup *memcg;
876 if (!mm)
877 return;
879 rcu_read_lock();
880 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
881 if (unlikely(!memcg))
882 goto out;
884 switch (idx) {
885 case PGMAJFAULT:
886 mem_cgroup_pgmajfault(memcg, 1);
887 break;
888 case PGFAULT:
889 mem_cgroup_pgfault(memcg, 1);
890 break;
891 default:
892 BUG();
894 out:
895 rcu_read_unlock();
897 EXPORT_SYMBOL(mem_cgroup_count_vm_event);
900 * Following LRU functions are allowed to be used without PCG_LOCK.
901 * Operations are called by routine of global LRU independently from memcg.
902 * What we have to take care of here is validness of pc->mem_cgroup.
904 * Changes to pc->mem_cgroup happens when
905 * 1. charge
906 * 2. moving account
907 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
908 * It is added to LRU before charge.
909 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
910 * When moving account, the page is not on LRU. It's isolated.
913 void mem_cgroup_del_lru_list(struct page *page, enum lru_list lru)
915 struct page_cgroup *pc;
916 struct mem_cgroup_per_zone *mz;
918 if (mem_cgroup_disabled())
919 return;
920 pc = lookup_page_cgroup(page);
921 /* can happen while we handle swapcache. */
922 if (!TestClearPageCgroupAcctLRU(pc))
923 return;
924 VM_BUG_ON(!pc->mem_cgroup);
926 * We don't check PCG_USED bit. It's cleared when the "page" is finally
927 * removed from global LRU.
929 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
930 /* huge page split is done under lru_lock. so, we have no races. */
931 MEM_CGROUP_ZSTAT(mz, lru) -= 1 << compound_order(page);
932 if (mem_cgroup_is_root(pc->mem_cgroup))
933 return;
934 VM_BUG_ON(list_empty(&pc->lru));
935 list_del_init(&pc->lru);
938 void mem_cgroup_del_lru(struct page *page)
940 mem_cgroup_del_lru_list(page, page_lru(page));
944 * Writeback is about to end against a page which has been marked for immediate
945 * reclaim. If it still appears to be reclaimable, move it to the tail of the
946 * inactive list.
948 void mem_cgroup_rotate_reclaimable_page(struct page *page)
950 struct mem_cgroup_per_zone *mz;
951 struct page_cgroup *pc;
952 enum lru_list lru = page_lru(page);
954 if (mem_cgroup_disabled())
955 return;
957 pc = lookup_page_cgroup(page);
958 /* unused or root page is not rotated. */
959 if (!PageCgroupUsed(pc))
960 return;
961 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
962 smp_rmb();
963 if (mem_cgroup_is_root(pc->mem_cgroup))
964 return;
965 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
966 list_move_tail(&pc->lru, &mz->lists[lru]);
969 void mem_cgroup_rotate_lru_list(struct page *page, enum lru_list lru)
971 struct mem_cgroup_per_zone *mz;
972 struct page_cgroup *pc;
974 if (mem_cgroup_disabled())
975 return;
977 pc = lookup_page_cgroup(page);
978 /* unused or root page is not rotated. */
979 if (!PageCgroupUsed(pc))
980 return;
981 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
982 smp_rmb();
983 if (mem_cgroup_is_root(pc->mem_cgroup))
984 return;
985 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
986 list_move(&pc->lru, &mz->lists[lru]);
989 void mem_cgroup_add_lru_list(struct page *page, enum lru_list lru)
991 struct page_cgroup *pc;
992 struct mem_cgroup_per_zone *mz;
994 if (mem_cgroup_disabled())
995 return;
996 pc = lookup_page_cgroup(page);
997 VM_BUG_ON(PageCgroupAcctLRU(pc));
999 * putback: charge:
1000 * SetPageLRU SetPageCgroupUsed
1001 * smp_mb smp_mb
1002 * PageCgroupUsed && add to memcg LRU PageLRU && add to memcg LRU
1004 * Ensure that one of the two sides adds the page to the memcg
1005 * LRU during a race.
1007 smp_mb();
1008 if (!PageCgroupUsed(pc))
1009 return;
1010 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1011 smp_rmb();
1012 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
1013 /* huge page split is done under lru_lock. so, we have no races. */
1014 MEM_CGROUP_ZSTAT(mz, lru) += 1 << compound_order(page);
1015 SetPageCgroupAcctLRU(pc);
1016 if (mem_cgroup_is_root(pc->mem_cgroup))
1017 return;
1018 list_add(&pc->lru, &mz->lists[lru]);
1022 * At handling SwapCache and other FUSE stuff, pc->mem_cgroup may be changed
1023 * while it's linked to lru because the page may be reused after it's fully
1024 * uncharged. To handle that, unlink page_cgroup from LRU when charge it again.
1025 * It's done under lock_page and expected that zone->lru_lock isnever held.
1027 static void mem_cgroup_lru_del_before_commit(struct page *page)
1029 unsigned long flags;
1030 struct zone *zone = page_zone(page);
1031 struct page_cgroup *pc = lookup_page_cgroup(page);
1034 * Doing this check without taking ->lru_lock seems wrong but this
1035 * is safe. Because if page_cgroup's USED bit is unset, the page
1036 * will not be added to any memcg's LRU. If page_cgroup's USED bit is
1037 * set, the commit after this will fail, anyway.
1038 * This all charge/uncharge is done under some mutual execustion.
1039 * So, we don't need to taking care of changes in USED bit.
1041 if (likely(!PageLRU(page)))
1042 return;
1044 spin_lock_irqsave(&zone->lru_lock, flags);
1046 * Forget old LRU when this page_cgroup is *not* used. This Used bit
1047 * is guarded by lock_page() because the page is SwapCache.
1049 if (!PageCgroupUsed(pc))
1050 mem_cgroup_del_lru_list(page, page_lru(page));
1051 spin_unlock_irqrestore(&zone->lru_lock, flags);
1054 static void mem_cgroup_lru_add_after_commit(struct page *page)
1056 unsigned long flags;
1057 struct zone *zone = page_zone(page);
1058 struct page_cgroup *pc = lookup_page_cgroup(page);
1060 * putback: charge:
1061 * SetPageLRU SetPageCgroupUsed
1062 * smp_mb smp_mb
1063 * PageCgroupUsed && add to memcg LRU PageLRU && add to memcg LRU
1065 * Ensure that one of the two sides adds the page to the memcg
1066 * LRU during a race.
1068 smp_mb();
1069 /* taking care of that the page is added to LRU while we commit it */
1070 if (likely(!PageLRU(page)))
1071 return;
1072 spin_lock_irqsave(&zone->lru_lock, flags);
1073 /* link when the page is linked to LRU but page_cgroup isn't */
1074 if (PageLRU(page) && !PageCgroupAcctLRU(pc))
1075 mem_cgroup_add_lru_list(page, page_lru(page));
1076 spin_unlock_irqrestore(&zone->lru_lock, flags);
1080 void mem_cgroup_move_lists(struct page *page,
1081 enum lru_list from, enum lru_list to)
1083 if (mem_cgroup_disabled())
1084 return;
1085 mem_cgroup_del_lru_list(page, from);
1086 mem_cgroup_add_lru_list(page, to);
1090 * Checks whether given mem is same or in the root_mem_cgroup's
1091 * hierarchy subtree
1093 static bool mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
1094 struct mem_cgroup *memcg)
1096 if (root_memcg != memcg) {
1097 return (root_memcg->use_hierarchy &&
1098 css_is_ancestor(&memcg->css, &root_memcg->css));
1101 return true;
1104 int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *memcg)
1106 int ret;
1107 struct mem_cgroup *curr = NULL;
1108 struct task_struct *p;
1110 p = find_lock_task_mm(task);
1111 if (!p)
1112 return 0;
1113 curr = try_get_mem_cgroup_from_mm(p->mm);
1114 task_unlock(p);
1115 if (!curr)
1116 return 0;
1118 * We should check use_hierarchy of "memcg" not "curr". Because checking
1119 * use_hierarchy of "curr" here make this function true if hierarchy is
1120 * enabled in "curr" and "curr" is a child of "memcg" in *cgroup*
1121 * hierarchy(even if use_hierarchy is disabled in "memcg").
1123 ret = mem_cgroup_same_or_subtree(memcg, curr);
1124 css_put(&curr->css);
1125 return ret;
1128 int mem_cgroup_inactive_anon_is_low(struct mem_cgroup *memcg, struct zone *zone)
1130 unsigned long inactive_ratio;
1131 int nid = zone_to_nid(zone);
1132 int zid = zone_idx(zone);
1133 unsigned long inactive;
1134 unsigned long active;
1135 unsigned long gb;
1137 inactive = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1138 BIT(LRU_INACTIVE_ANON));
1139 active = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1140 BIT(LRU_ACTIVE_ANON));
1142 gb = (inactive + active) >> (30 - PAGE_SHIFT);
1143 if (gb)
1144 inactive_ratio = int_sqrt(10 * gb);
1145 else
1146 inactive_ratio = 1;
1148 return inactive * inactive_ratio < active;
1151 int mem_cgroup_inactive_file_is_low(struct mem_cgroup *memcg, struct zone *zone)
1153 unsigned long active;
1154 unsigned long inactive;
1155 int zid = zone_idx(zone);
1156 int nid = zone_to_nid(zone);
1158 inactive = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1159 BIT(LRU_INACTIVE_FILE));
1160 active = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1161 BIT(LRU_ACTIVE_FILE));
1163 return (active > inactive);
1166 struct zone_reclaim_stat *mem_cgroup_get_reclaim_stat(struct mem_cgroup *memcg,
1167 struct zone *zone)
1169 int nid = zone_to_nid(zone);
1170 int zid = zone_idx(zone);
1171 struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
1173 return &mz->reclaim_stat;
1176 struct zone_reclaim_stat *
1177 mem_cgroup_get_reclaim_stat_from_page(struct page *page)
1179 struct page_cgroup *pc;
1180 struct mem_cgroup_per_zone *mz;
1182 if (mem_cgroup_disabled())
1183 return NULL;
1185 pc = lookup_page_cgroup(page);
1186 if (!PageCgroupUsed(pc))
1187 return NULL;
1188 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1189 smp_rmb();
1190 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
1191 return &mz->reclaim_stat;
1194 unsigned long mem_cgroup_isolate_pages(unsigned long nr_to_scan,
1195 struct list_head *dst,
1196 unsigned long *scanned, int order,
1197 isolate_mode_t mode,
1198 struct zone *z,
1199 struct mem_cgroup *mem_cont,
1200 int active, int file)
1202 unsigned long nr_taken = 0;
1203 struct page *page;
1204 unsigned long scan;
1205 LIST_HEAD(pc_list);
1206 struct list_head *src;
1207 struct page_cgroup *pc, *tmp;
1208 int nid = zone_to_nid(z);
1209 int zid = zone_idx(z);
1210 struct mem_cgroup_per_zone *mz;
1211 int lru = LRU_FILE * file + active;
1212 int ret;
1214 BUG_ON(!mem_cont);
1215 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
1216 src = &mz->lists[lru];
1218 scan = 0;
1219 list_for_each_entry_safe_reverse(pc, tmp, src, lru) {
1220 if (scan >= nr_to_scan)
1221 break;
1223 if (unlikely(!PageCgroupUsed(pc)))
1224 continue;
1226 page = lookup_cgroup_page(pc);
1228 if (unlikely(!PageLRU(page)))
1229 continue;
1231 scan++;
1232 ret = __isolate_lru_page(page, mode, file);
1233 switch (ret) {
1234 case 0:
1235 list_move(&page->lru, dst);
1236 mem_cgroup_del_lru(page);
1237 nr_taken += hpage_nr_pages(page);
1238 break;
1239 case -EBUSY:
1240 /* we don't affect global LRU but rotate in our LRU */
1241 mem_cgroup_rotate_lru_list(page, page_lru(page));
1242 break;
1243 default:
1244 break;
1248 *scanned = scan;
1250 trace_mm_vmscan_memcg_isolate(0, nr_to_scan, scan, nr_taken,
1251 0, 0, 0, mode);
1253 return nr_taken;
1256 #define mem_cgroup_from_res_counter(counter, member) \
1257 container_of(counter, struct mem_cgroup, member)
1260 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1261 * @mem: the memory cgroup
1263 * Returns the maximum amount of memory @mem can be charged with, in
1264 * pages.
1266 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1268 unsigned long long margin;
1270 margin = res_counter_margin(&memcg->res);
1271 if (do_swap_account)
1272 margin = min(margin, res_counter_margin(&memcg->memsw));
1273 return margin >> PAGE_SHIFT;
1276 int mem_cgroup_swappiness(struct mem_cgroup *memcg)
1278 struct cgroup *cgrp = memcg->css.cgroup;
1280 /* root ? */
1281 if (cgrp->parent == NULL)
1282 return vm_swappiness;
1284 return memcg->swappiness;
1287 static void mem_cgroup_start_move(struct mem_cgroup *memcg)
1289 int cpu;
1291 get_online_cpus();
1292 spin_lock(&memcg->pcp_counter_lock);
1293 for_each_online_cpu(cpu)
1294 per_cpu(memcg->stat->count[MEM_CGROUP_ON_MOVE], cpu) += 1;
1295 memcg->nocpu_base.count[MEM_CGROUP_ON_MOVE] += 1;
1296 spin_unlock(&memcg->pcp_counter_lock);
1297 put_online_cpus();
1299 synchronize_rcu();
1302 static void mem_cgroup_end_move(struct mem_cgroup *memcg)
1304 int cpu;
1306 if (!memcg)
1307 return;
1308 get_online_cpus();
1309 spin_lock(&memcg->pcp_counter_lock);
1310 for_each_online_cpu(cpu)
1311 per_cpu(memcg->stat->count[MEM_CGROUP_ON_MOVE], cpu) -= 1;
1312 memcg->nocpu_base.count[MEM_CGROUP_ON_MOVE] -= 1;
1313 spin_unlock(&memcg->pcp_counter_lock);
1314 put_online_cpus();
1317 * 2 routines for checking "mem" is under move_account() or not.
1319 * mem_cgroup_stealed() - checking a cgroup is mc.from or not. This is used
1320 * for avoiding race in accounting. If true,
1321 * pc->mem_cgroup may be overwritten.
1323 * mem_cgroup_under_move() - checking a cgroup is mc.from or mc.to or
1324 * under hierarchy of moving cgroups. This is for
1325 * waiting at hith-memory prressure caused by "move".
1328 static bool mem_cgroup_stealed(struct mem_cgroup *memcg)
1330 VM_BUG_ON(!rcu_read_lock_held());
1331 return this_cpu_read(memcg->stat->count[MEM_CGROUP_ON_MOVE]) > 0;
1334 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1336 struct mem_cgroup *from;
1337 struct mem_cgroup *to;
1338 bool ret = false;
1340 * Unlike task_move routines, we access mc.to, mc.from not under
1341 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1343 spin_lock(&mc.lock);
1344 from = mc.from;
1345 to = mc.to;
1346 if (!from)
1347 goto unlock;
1349 ret = mem_cgroup_same_or_subtree(memcg, from)
1350 || mem_cgroup_same_or_subtree(memcg, to);
1351 unlock:
1352 spin_unlock(&mc.lock);
1353 return ret;
1356 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1358 if (mc.moving_task && current != mc.moving_task) {
1359 if (mem_cgroup_under_move(memcg)) {
1360 DEFINE_WAIT(wait);
1361 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1362 /* moving charge context might have finished. */
1363 if (mc.moving_task)
1364 schedule();
1365 finish_wait(&mc.waitq, &wait);
1366 return true;
1369 return false;
1373 * mem_cgroup_print_oom_info: Called from OOM with tasklist_lock held in read mode.
1374 * @memcg: The memory cgroup that went over limit
1375 * @p: Task that is going to be killed
1377 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1378 * enabled
1380 void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1382 struct cgroup *task_cgrp;
1383 struct cgroup *mem_cgrp;
1385 * Need a buffer in BSS, can't rely on allocations. The code relies
1386 * on the assumption that OOM is serialized for memory controller.
1387 * If this assumption is broken, revisit this code.
1389 static char memcg_name[PATH_MAX];
1390 int ret;
1392 if (!memcg || !p)
1393 return;
1396 rcu_read_lock();
1398 mem_cgrp = memcg->css.cgroup;
1399 task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
1401 ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
1402 if (ret < 0) {
1404 * Unfortunately, we are unable to convert to a useful name
1405 * But we'll still print out the usage information
1407 rcu_read_unlock();
1408 goto done;
1410 rcu_read_unlock();
1412 printk(KERN_INFO "Task in %s killed", memcg_name);
1414 rcu_read_lock();
1415 ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
1416 if (ret < 0) {
1417 rcu_read_unlock();
1418 goto done;
1420 rcu_read_unlock();
1423 * Continues from above, so we don't need an KERN_ level
1425 printk(KERN_CONT " as a result of limit of %s\n", memcg_name);
1426 done:
1428 printk(KERN_INFO "memory: usage %llukB, limit %llukB, failcnt %llu\n",
1429 res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
1430 res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
1431 res_counter_read_u64(&memcg->res, RES_FAILCNT));
1432 printk(KERN_INFO "memory+swap: usage %llukB, limit %llukB, "
1433 "failcnt %llu\n",
1434 res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
1435 res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
1436 res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
1440 * This function returns the number of memcg under hierarchy tree. Returns
1441 * 1(self count) if no children.
1443 static int mem_cgroup_count_children(struct mem_cgroup *memcg)
1445 int num = 0;
1446 struct mem_cgroup *iter;
1448 for_each_mem_cgroup_tree(iter, memcg)
1449 num++;
1450 return num;
1454 * Return the memory (and swap, if configured) limit for a memcg.
1456 u64 mem_cgroup_get_limit(struct mem_cgroup *memcg)
1458 u64 limit;
1459 u64 memsw;
1461 limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
1462 limit += total_swap_pages << PAGE_SHIFT;
1464 memsw = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
1466 * If memsw is finite and limits the amount of swap space available
1467 * to this memcg, return that limit.
1469 return min(limit, memsw);
1473 * Visit the first child (need not be the first child as per the ordering
1474 * of the cgroup list, since we track last_scanned_child) of @mem and use
1475 * that to reclaim free pages from.
1477 static struct mem_cgroup *
1478 mem_cgroup_select_victim(struct mem_cgroup *root_memcg)
1480 struct mem_cgroup *ret = NULL;
1481 struct cgroup_subsys_state *css;
1482 int nextid, found;
1484 if (!root_memcg->use_hierarchy) {
1485 css_get(&root_memcg->css);
1486 ret = root_memcg;
1489 while (!ret) {
1490 rcu_read_lock();
1491 nextid = root_memcg->last_scanned_child + 1;
1492 css = css_get_next(&mem_cgroup_subsys, nextid, &root_memcg->css,
1493 &found);
1494 if (css && css_tryget(css))
1495 ret = container_of(css, struct mem_cgroup, css);
1497 rcu_read_unlock();
1498 /* Updates scanning parameter */
1499 if (!css) {
1500 /* this means start scan from ID:1 */
1501 root_memcg->last_scanned_child = 0;
1502 } else
1503 root_memcg->last_scanned_child = found;
1506 return ret;
1510 * test_mem_cgroup_node_reclaimable
1511 * @mem: the target memcg
1512 * @nid: the node ID to be checked.
1513 * @noswap : specify true here if the user wants flle only information.
1515 * This function returns whether the specified memcg contains any
1516 * reclaimable pages on a node. Returns true if there are any reclaimable
1517 * pages in the node.
1519 static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *memcg,
1520 int nid, bool noswap)
1522 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_FILE))
1523 return true;
1524 if (noswap || !total_swap_pages)
1525 return false;
1526 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_ANON))
1527 return true;
1528 return false;
1531 #if MAX_NUMNODES > 1
1534 * Always updating the nodemask is not very good - even if we have an empty
1535 * list or the wrong list here, we can start from some node and traverse all
1536 * nodes based on the zonelist. So update the list loosely once per 10 secs.
1539 static void mem_cgroup_may_update_nodemask(struct mem_cgroup *memcg)
1541 int nid;
1543 * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
1544 * pagein/pageout changes since the last update.
1546 if (!atomic_read(&memcg->numainfo_events))
1547 return;
1548 if (atomic_inc_return(&memcg->numainfo_updating) > 1)
1549 return;
1551 /* make a nodemask where this memcg uses memory from */
1552 memcg->scan_nodes = node_states[N_HIGH_MEMORY];
1554 for_each_node_mask(nid, node_states[N_HIGH_MEMORY]) {
1556 if (!test_mem_cgroup_node_reclaimable(memcg, nid, false))
1557 node_clear(nid, memcg->scan_nodes);
1560 atomic_set(&memcg->numainfo_events, 0);
1561 atomic_set(&memcg->numainfo_updating, 0);
1565 * Selecting a node where we start reclaim from. Because what we need is just
1566 * reducing usage counter, start from anywhere is O,K. Considering
1567 * memory reclaim from current node, there are pros. and cons.
1569 * Freeing memory from current node means freeing memory from a node which
1570 * we'll use or we've used. So, it may make LRU bad. And if several threads
1571 * hit limits, it will see a contention on a node. But freeing from remote
1572 * node means more costs for memory reclaim because of memory latency.
1574 * Now, we use round-robin. Better algorithm is welcomed.
1576 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1578 int node;
1580 mem_cgroup_may_update_nodemask(memcg);
1581 node = memcg->last_scanned_node;
1583 node = next_node(node, memcg->scan_nodes);
1584 if (node == MAX_NUMNODES)
1585 node = first_node(memcg->scan_nodes);
1587 * We call this when we hit limit, not when pages are added to LRU.
1588 * No LRU may hold pages because all pages are UNEVICTABLE or
1589 * memcg is too small and all pages are not on LRU. In that case,
1590 * we use curret node.
1592 if (unlikely(node == MAX_NUMNODES))
1593 node = numa_node_id();
1595 memcg->last_scanned_node = node;
1596 return node;
1600 * Check all nodes whether it contains reclaimable pages or not.
1601 * For quick scan, we make use of scan_nodes. This will allow us to skip
1602 * unused nodes. But scan_nodes is lazily updated and may not cotain
1603 * enough new information. We need to do double check.
1605 bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
1607 int nid;
1610 * quick check...making use of scan_node.
1611 * We can skip unused nodes.
1613 if (!nodes_empty(memcg->scan_nodes)) {
1614 for (nid = first_node(memcg->scan_nodes);
1615 nid < MAX_NUMNODES;
1616 nid = next_node(nid, memcg->scan_nodes)) {
1618 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
1619 return true;
1623 * Check rest of nodes.
1625 for_each_node_state(nid, N_HIGH_MEMORY) {
1626 if (node_isset(nid, memcg->scan_nodes))
1627 continue;
1628 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
1629 return true;
1631 return false;
1634 #else
1635 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1637 return 0;
1640 bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
1642 return test_mem_cgroup_node_reclaimable(memcg, 0, noswap);
1644 #endif
1647 * Scan the hierarchy if needed to reclaim memory. We remember the last child
1648 * we reclaimed from, so that we don't end up penalizing one child extensively
1649 * based on its position in the children list.
1651 * root_memcg is the original ancestor that we've been reclaim from.
1653 * We give up and return to the caller when we visit root_memcg twice.
1654 * (other groups can be removed while we're walking....)
1656 * If shrink==true, for avoiding to free too much, this returns immedieately.
1658 static int mem_cgroup_hierarchical_reclaim(struct mem_cgroup *root_memcg,
1659 struct zone *zone,
1660 gfp_t gfp_mask,
1661 unsigned long reclaim_options,
1662 unsigned long *total_scanned)
1664 struct mem_cgroup *victim;
1665 int ret, total = 0;
1666 int loop = 0;
1667 bool noswap = reclaim_options & MEM_CGROUP_RECLAIM_NOSWAP;
1668 bool shrink = reclaim_options & MEM_CGROUP_RECLAIM_SHRINK;
1669 bool check_soft = reclaim_options & MEM_CGROUP_RECLAIM_SOFT;
1670 unsigned long excess;
1671 unsigned long nr_scanned;
1673 excess = res_counter_soft_limit_excess(&root_memcg->res) >> PAGE_SHIFT;
1675 /* If memsw_is_minimum==1, swap-out is of-no-use. */
1676 if (!check_soft && !shrink && root_memcg->memsw_is_minimum)
1677 noswap = true;
1679 while (1) {
1680 victim = mem_cgroup_select_victim(root_memcg);
1681 if (victim == root_memcg) {
1682 loop++;
1684 * We are not draining per cpu cached charges during
1685 * soft limit reclaim because global reclaim doesn't
1686 * care about charges. It tries to free some memory and
1687 * charges will not give any.
1689 if (!check_soft && loop >= 1)
1690 drain_all_stock_async(root_memcg);
1691 if (loop >= 2) {
1693 * If we have not been able to reclaim
1694 * anything, it might because there are
1695 * no reclaimable pages under this hierarchy
1697 if (!check_soft || !total) {
1698 css_put(&victim->css);
1699 break;
1702 * We want to do more targeted reclaim.
1703 * excess >> 2 is not to excessive so as to
1704 * reclaim too much, nor too less that we keep
1705 * coming back to reclaim from this cgroup
1707 if (total >= (excess >> 2) ||
1708 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS)) {
1709 css_put(&victim->css);
1710 break;
1714 if (!mem_cgroup_reclaimable(victim, noswap)) {
1715 /* this cgroup's local usage == 0 */
1716 css_put(&victim->css);
1717 continue;
1719 /* we use swappiness of local cgroup */
1720 if (check_soft) {
1721 ret = mem_cgroup_shrink_node_zone(victim, gfp_mask,
1722 noswap, zone, &nr_scanned);
1723 *total_scanned += nr_scanned;
1724 } else
1725 ret = try_to_free_mem_cgroup_pages(victim, gfp_mask,
1726 noswap);
1727 css_put(&victim->css);
1729 * At shrinking usage, we can't check we should stop here or
1730 * reclaim more. It's depends on callers. last_scanned_child
1731 * will work enough for keeping fairness under tree.
1733 if (shrink)
1734 return ret;
1735 total += ret;
1736 if (check_soft) {
1737 if (!res_counter_soft_limit_excess(&root_memcg->res))
1738 return total;
1739 } else if (mem_cgroup_margin(root_memcg))
1740 return total;
1742 return total;
1746 * Check OOM-Killer is already running under our hierarchy.
1747 * If someone is running, return false.
1748 * Has to be called with memcg_oom_lock
1750 static bool mem_cgroup_oom_lock(struct mem_cgroup *memcg)
1752 struct mem_cgroup *iter, *failed = NULL;
1753 bool cond = true;
1755 for_each_mem_cgroup_tree_cond(iter, memcg, cond) {
1756 if (iter->oom_lock) {
1758 * this subtree of our hierarchy is already locked
1759 * so we cannot give a lock.
1761 failed = iter;
1762 cond = false;
1763 } else
1764 iter->oom_lock = true;
1767 if (!failed)
1768 return true;
1771 * OK, we failed to lock the whole subtree so we have to clean up
1772 * what we set up to the failing subtree
1774 cond = true;
1775 for_each_mem_cgroup_tree_cond(iter, memcg, cond) {
1776 if (iter == failed) {
1777 cond = false;
1778 continue;
1780 iter->oom_lock = false;
1782 return false;
1786 * Has to be called with memcg_oom_lock
1788 static int mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
1790 struct mem_cgroup *iter;
1792 for_each_mem_cgroup_tree(iter, memcg)
1793 iter->oom_lock = false;
1794 return 0;
1797 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
1799 struct mem_cgroup *iter;
1801 for_each_mem_cgroup_tree(iter, memcg)
1802 atomic_inc(&iter->under_oom);
1805 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
1807 struct mem_cgroup *iter;
1810 * When a new child is created while the hierarchy is under oom,
1811 * mem_cgroup_oom_lock() may not be called. We have to use
1812 * atomic_add_unless() here.
1814 for_each_mem_cgroup_tree(iter, memcg)
1815 atomic_add_unless(&iter->under_oom, -1, 0);
1818 static DEFINE_SPINLOCK(memcg_oom_lock);
1819 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1821 struct oom_wait_info {
1822 struct mem_cgroup *mem;
1823 wait_queue_t wait;
1826 static int memcg_oom_wake_function(wait_queue_t *wait,
1827 unsigned mode, int sync, void *arg)
1829 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg,
1830 *oom_wait_memcg;
1831 struct oom_wait_info *oom_wait_info;
1833 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1834 oom_wait_memcg = oom_wait_info->mem;
1837 * Both of oom_wait_info->mem and wake_mem are stable under us.
1838 * Then we can use css_is_ancestor without taking care of RCU.
1840 if (!mem_cgroup_same_or_subtree(oom_wait_memcg, wake_memcg)
1841 && !mem_cgroup_same_or_subtree(wake_memcg, oom_wait_memcg))
1842 return 0;
1843 return autoremove_wake_function(wait, mode, sync, arg);
1846 static void memcg_wakeup_oom(struct mem_cgroup *memcg)
1848 /* for filtering, pass "memcg" as argument. */
1849 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
1852 static void memcg_oom_recover(struct mem_cgroup *memcg)
1854 if (memcg && atomic_read(&memcg->under_oom))
1855 memcg_wakeup_oom(memcg);
1859 * try to call OOM killer. returns false if we should exit memory-reclaim loop.
1861 bool mem_cgroup_handle_oom(struct mem_cgroup *memcg, gfp_t mask)
1863 struct oom_wait_info owait;
1864 bool locked, need_to_kill;
1866 owait.mem = memcg;
1867 owait.wait.flags = 0;
1868 owait.wait.func = memcg_oom_wake_function;
1869 owait.wait.private = current;
1870 INIT_LIST_HEAD(&owait.wait.task_list);
1871 need_to_kill = true;
1872 mem_cgroup_mark_under_oom(memcg);
1874 /* At first, try to OOM lock hierarchy under memcg.*/
1875 spin_lock(&memcg_oom_lock);
1876 locked = mem_cgroup_oom_lock(memcg);
1878 * Even if signal_pending(), we can't quit charge() loop without
1879 * accounting. So, UNINTERRUPTIBLE is appropriate. But SIGKILL
1880 * under OOM is always welcomed, use TASK_KILLABLE here.
1882 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
1883 if (!locked || memcg->oom_kill_disable)
1884 need_to_kill = false;
1885 if (locked)
1886 mem_cgroup_oom_notify(memcg);
1887 spin_unlock(&memcg_oom_lock);
1889 if (need_to_kill) {
1890 finish_wait(&memcg_oom_waitq, &owait.wait);
1891 mem_cgroup_out_of_memory(memcg, mask);
1892 } else {
1893 schedule();
1894 finish_wait(&memcg_oom_waitq, &owait.wait);
1896 spin_lock(&memcg_oom_lock);
1897 if (locked)
1898 mem_cgroup_oom_unlock(memcg);
1899 memcg_wakeup_oom(memcg);
1900 spin_unlock(&memcg_oom_lock);
1902 mem_cgroup_unmark_under_oom(memcg);
1904 if (test_thread_flag(TIF_MEMDIE) || fatal_signal_pending(current))
1905 return false;
1906 /* Give chance to dying process */
1907 schedule_timeout_uninterruptible(1);
1908 return true;
1912 * Currently used to update mapped file statistics, but the routine can be
1913 * generalized to update other statistics as well.
1915 * Notes: Race condition
1917 * We usually use page_cgroup_lock() for accessing page_cgroup member but
1918 * it tends to be costly. But considering some conditions, we doesn't need
1919 * to do so _always_.
1921 * Considering "charge", lock_page_cgroup() is not required because all
1922 * file-stat operations happen after a page is attached to radix-tree. There
1923 * are no race with "charge".
1925 * Considering "uncharge", we know that memcg doesn't clear pc->mem_cgroup
1926 * at "uncharge" intentionally. So, we always see valid pc->mem_cgroup even
1927 * if there are race with "uncharge". Statistics itself is properly handled
1928 * by flags.
1930 * Considering "move", this is an only case we see a race. To make the race
1931 * small, we check MEM_CGROUP_ON_MOVE percpu value and detect there are
1932 * possibility of race condition. If there is, we take a lock.
1935 void mem_cgroup_update_page_stat(struct page *page,
1936 enum mem_cgroup_page_stat_item idx, int val)
1938 struct mem_cgroup *memcg;
1939 struct page_cgroup *pc = lookup_page_cgroup(page);
1940 bool need_unlock = false;
1941 unsigned long uninitialized_var(flags);
1943 if (unlikely(!pc))
1944 return;
1946 rcu_read_lock();
1947 memcg = pc->mem_cgroup;
1948 if (unlikely(!memcg || !PageCgroupUsed(pc)))
1949 goto out;
1950 /* pc->mem_cgroup is unstable ? */
1951 if (unlikely(mem_cgroup_stealed(memcg)) || PageTransHuge(page)) {
1952 /* take a lock against to access pc->mem_cgroup */
1953 move_lock_page_cgroup(pc, &flags);
1954 need_unlock = true;
1955 memcg = pc->mem_cgroup;
1956 if (!memcg || !PageCgroupUsed(pc))
1957 goto out;
1960 switch (idx) {
1961 case MEMCG_NR_FILE_MAPPED:
1962 if (val > 0)
1963 SetPageCgroupFileMapped(pc);
1964 else if (!page_mapped(page))
1965 ClearPageCgroupFileMapped(pc);
1966 idx = MEM_CGROUP_STAT_FILE_MAPPED;
1967 break;
1968 default:
1969 BUG();
1972 this_cpu_add(memcg->stat->count[idx], val);
1974 out:
1975 if (unlikely(need_unlock))
1976 move_unlock_page_cgroup(pc, &flags);
1977 rcu_read_unlock();
1978 return;
1980 EXPORT_SYMBOL(mem_cgroup_update_page_stat);
1983 * size of first charge trial. "32" comes from vmscan.c's magic value.
1984 * TODO: maybe necessary to use big numbers in big irons.
1986 #define CHARGE_BATCH 32U
1987 struct memcg_stock_pcp {
1988 struct mem_cgroup *cached; /* this never be root cgroup */
1989 unsigned int nr_pages;
1990 struct work_struct work;
1991 unsigned long flags;
1992 #define FLUSHING_CACHED_CHARGE (0)
1994 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
1995 static DEFINE_MUTEX(percpu_charge_mutex);
1998 * Try to consume stocked charge on this cpu. If success, one page is consumed
1999 * from local stock and true is returned. If the stock is 0 or charges from a
2000 * cgroup which is not current target, returns false. This stock will be
2001 * refilled.
2003 static bool consume_stock(struct mem_cgroup *memcg)
2005 struct memcg_stock_pcp *stock;
2006 bool ret = true;
2008 stock = &get_cpu_var(memcg_stock);
2009 if (memcg == stock->cached && stock->nr_pages)
2010 stock->nr_pages--;
2011 else /* need to call res_counter_charge */
2012 ret = false;
2013 put_cpu_var(memcg_stock);
2014 return ret;
2018 * Returns stocks cached in percpu to res_counter and reset cached information.
2020 static void drain_stock(struct memcg_stock_pcp *stock)
2022 struct mem_cgroup *old = stock->cached;
2024 if (stock->nr_pages) {
2025 unsigned long bytes = stock->nr_pages * PAGE_SIZE;
2027 res_counter_uncharge(&old->res, bytes);
2028 if (do_swap_account)
2029 res_counter_uncharge(&old->memsw, bytes);
2030 stock->nr_pages = 0;
2032 stock->cached = NULL;
2036 * This must be called under preempt disabled or must be called by
2037 * a thread which is pinned to local cpu.
2039 static void drain_local_stock(struct work_struct *dummy)
2041 struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
2042 drain_stock(stock);
2043 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2047 * Cache charges(val) which is from res_counter, to local per_cpu area.
2048 * This will be consumed by consume_stock() function, later.
2050 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2052 struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
2054 if (stock->cached != memcg) { /* reset if necessary */
2055 drain_stock(stock);
2056 stock->cached = memcg;
2058 stock->nr_pages += nr_pages;
2059 put_cpu_var(memcg_stock);
2063 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2064 * of the hierarchy under it. sync flag says whether we should block
2065 * until the work is done.
2067 static void drain_all_stock(struct mem_cgroup *root_memcg, bool sync)
2069 int cpu, curcpu;
2071 /* Notify other cpus that system-wide "drain" is running */
2072 get_online_cpus();
2073 curcpu = get_cpu();
2074 for_each_online_cpu(cpu) {
2075 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2076 struct mem_cgroup *memcg;
2078 memcg = stock->cached;
2079 if (!memcg || !stock->nr_pages)
2080 continue;
2081 if (!mem_cgroup_same_or_subtree(root_memcg, memcg))
2082 continue;
2083 if (!test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2084 if (cpu == curcpu)
2085 drain_local_stock(&stock->work);
2086 else
2087 schedule_work_on(cpu, &stock->work);
2090 put_cpu();
2092 if (!sync)
2093 goto out;
2095 for_each_online_cpu(cpu) {
2096 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2097 if (test_bit(FLUSHING_CACHED_CHARGE, &stock->flags))
2098 flush_work(&stock->work);
2100 out:
2101 put_online_cpus();
2105 * Tries to drain stocked charges in other cpus. This function is asynchronous
2106 * and just put a work per cpu for draining localy on each cpu. Caller can
2107 * expects some charges will be back to res_counter later but cannot wait for
2108 * it.
2110 static void drain_all_stock_async(struct mem_cgroup *root_memcg)
2113 * If someone calls draining, avoid adding more kworker runs.
2115 if (!mutex_trylock(&percpu_charge_mutex))
2116 return;
2117 drain_all_stock(root_memcg, false);
2118 mutex_unlock(&percpu_charge_mutex);
2121 /* This is a synchronous drain interface. */
2122 static void drain_all_stock_sync(struct mem_cgroup *root_memcg)
2124 /* called when force_empty is called */
2125 mutex_lock(&percpu_charge_mutex);
2126 drain_all_stock(root_memcg, true);
2127 mutex_unlock(&percpu_charge_mutex);
2131 * This function drains percpu counter value from DEAD cpu and
2132 * move it to local cpu. Note that this function can be preempted.
2134 static void mem_cgroup_drain_pcp_counter(struct mem_cgroup *memcg, int cpu)
2136 int i;
2138 spin_lock(&memcg->pcp_counter_lock);
2139 for (i = 0; i < MEM_CGROUP_STAT_DATA; i++) {
2140 long x = per_cpu(memcg->stat->count[i], cpu);
2142 per_cpu(memcg->stat->count[i], cpu) = 0;
2143 memcg->nocpu_base.count[i] += x;
2145 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
2146 unsigned long x = per_cpu(memcg->stat->events[i], cpu);
2148 per_cpu(memcg->stat->events[i], cpu) = 0;
2149 memcg->nocpu_base.events[i] += x;
2151 /* need to clear ON_MOVE value, works as a kind of lock. */
2152 per_cpu(memcg->stat->count[MEM_CGROUP_ON_MOVE], cpu) = 0;
2153 spin_unlock(&memcg->pcp_counter_lock);
2156 static void synchronize_mem_cgroup_on_move(struct mem_cgroup *memcg, int cpu)
2158 int idx = MEM_CGROUP_ON_MOVE;
2160 spin_lock(&memcg->pcp_counter_lock);
2161 per_cpu(memcg->stat->count[idx], cpu) = memcg->nocpu_base.count[idx];
2162 spin_unlock(&memcg->pcp_counter_lock);
2165 static int __cpuinit memcg_cpu_hotplug_callback(struct notifier_block *nb,
2166 unsigned long action,
2167 void *hcpu)
2169 int cpu = (unsigned long)hcpu;
2170 struct memcg_stock_pcp *stock;
2171 struct mem_cgroup *iter;
2173 if ((action == CPU_ONLINE)) {
2174 for_each_mem_cgroup_all(iter)
2175 synchronize_mem_cgroup_on_move(iter, cpu);
2176 return NOTIFY_OK;
2179 if ((action != CPU_DEAD) || action != CPU_DEAD_FROZEN)
2180 return NOTIFY_OK;
2182 for_each_mem_cgroup_all(iter)
2183 mem_cgroup_drain_pcp_counter(iter, cpu);
2185 stock = &per_cpu(memcg_stock, cpu);
2186 drain_stock(stock);
2187 return NOTIFY_OK;
2191 /* See __mem_cgroup_try_charge() for details */
2192 enum {
2193 CHARGE_OK, /* success */
2194 CHARGE_RETRY, /* need to retry but retry is not bad */
2195 CHARGE_NOMEM, /* we can't do more. return -ENOMEM */
2196 CHARGE_WOULDBLOCK, /* GFP_WAIT wasn't set and no enough res. */
2197 CHARGE_OOM_DIE, /* the current is killed because of OOM */
2200 static int mem_cgroup_do_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2201 unsigned int nr_pages, bool oom_check)
2203 unsigned long csize = nr_pages * PAGE_SIZE;
2204 struct mem_cgroup *mem_over_limit;
2205 struct res_counter *fail_res;
2206 unsigned long flags = 0;
2207 int ret;
2209 ret = res_counter_charge(&memcg->res, csize, &fail_res);
2211 if (likely(!ret)) {
2212 if (!do_swap_account)
2213 return CHARGE_OK;
2214 ret = res_counter_charge(&memcg->memsw, csize, &fail_res);
2215 if (likely(!ret))
2216 return CHARGE_OK;
2218 res_counter_uncharge(&memcg->res, csize);
2219 mem_over_limit = mem_cgroup_from_res_counter(fail_res, memsw);
2220 flags |= MEM_CGROUP_RECLAIM_NOSWAP;
2221 } else
2222 mem_over_limit = mem_cgroup_from_res_counter(fail_res, res);
2224 * nr_pages can be either a huge page (HPAGE_PMD_NR), a batch
2225 * of regular pages (CHARGE_BATCH), or a single regular page (1).
2227 * Never reclaim on behalf of optional batching, retry with a
2228 * single page instead.
2230 if (nr_pages == CHARGE_BATCH)
2231 return CHARGE_RETRY;
2233 if (!(gfp_mask & __GFP_WAIT))
2234 return CHARGE_WOULDBLOCK;
2236 ret = mem_cgroup_hierarchical_reclaim(mem_over_limit, NULL,
2237 gfp_mask, flags, NULL);
2238 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2239 return CHARGE_RETRY;
2241 * Even though the limit is exceeded at this point, reclaim
2242 * may have been able to free some pages. Retry the charge
2243 * before killing the task.
2245 * Only for regular pages, though: huge pages are rather
2246 * unlikely to succeed so close to the limit, and we fall back
2247 * to regular pages anyway in case of failure.
2249 if (nr_pages == 1 && ret)
2250 return CHARGE_RETRY;
2253 * At task move, charge accounts can be doubly counted. So, it's
2254 * better to wait until the end of task_move if something is going on.
2256 if (mem_cgroup_wait_acct_move(mem_over_limit))
2257 return CHARGE_RETRY;
2259 /* If we don't need to call oom-killer at el, return immediately */
2260 if (!oom_check)
2261 return CHARGE_NOMEM;
2262 /* check OOM */
2263 if (!mem_cgroup_handle_oom(mem_over_limit, gfp_mask))
2264 return CHARGE_OOM_DIE;
2266 return CHARGE_RETRY;
2270 * Unlike exported interface, "oom" parameter is added. if oom==true,
2271 * oom-killer can be invoked.
2273 static int __mem_cgroup_try_charge(struct mm_struct *mm,
2274 gfp_t gfp_mask,
2275 unsigned int nr_pages,
2276 struct mem_cgroup **ptr,
2277 bool oom)
2279 unsigned int batch = max(CHARGE_BATCH, nr_pages);
2280 int nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2281 struct mem_cgroup *memcg = NULL;
2282 int ret;
2285 * Unlike gloval-vm's OOM-kill, we're not in memory shortage
2286 * in system level. So, allow to go ahead dying process in addition to
2287 * MEMDIE process.
2289 if (unlikely(test_thread_flag(TIF_MEMDIE)
2290 || fatal_signal_pending(current)))
2291 goto bypass;
2294 * We always charge the cgroup the mm_struct belongs to.
2295 * The mm_struct's mem_cgroup changes on task migration if the
2296 * thread group leader migrates. It's possible that mm is not
2297 * set, if so charge the init_mm (happens for pagecache usage).
2299 if (!*ptr && !mm)
2300 goto bypass;
2301 again:
2302 if (*ptr) { /* css should be a valid one */
2303 memcg = *ptr;
2304 VM_BUG_ON(css_is_removed(&memcg->css));
2305 if (mem_cgroup_is_root(memcg))
2306 goto done;
2307 if (nr_pages == 1 && consume_stock(memcg))
2308 goto done;
2309 css_get(&memcg->css);
2310 } else {
2311 struct task_struct *p;
2313 rcu_read_lock();
2314 p = rcu_dereference(mm->owner);
2316 * Because we don't have task_lock(), "p" can exit.
2317 * In that case, "memcg" can point to root or p can be NULL with
2318 * race with swapoff. Then, we have small risk of mis-accouning.
2319 * But such kind of mis-account by race always happens because
2320 * we don't have cgroup_mutex(). It's overkill and we allo that
2321 * small race, here.
2322 * (*) swapoff at el will charge against mm-struct not against
2323 * task-struct. So, mm->owner can be NULL.
2325 memcg = mem_cgroup_from_task(p);
2326 if (!memcg || mem_cgroup_is_root(memcg)) {
2327 rcu_read_unlock();
2328 goto done;
2330 if (nr_pages == 1 && consume_stock(memcg)) {
2332 * It seems dagerous to access memcg without css_get().
2333 * But considering how consume_stok works, it's not
2334 * necessary. If consume_stock success, some charges
2335 * from this memcg are cached on this cpu. So, we
2336 * don't need to call css_get()/css_tryget() before
2337 * calling consume_stock().
2339 rcu_read_unlock();
2340 goto done;
2342 /* after here, we may be blocked. we need to get refcnt */
2343 if (!css_tryget(&memcg->css)) {
2344 rcu_read_unlock();
2345 goto again;
2347 rcu_read_unlock();
2350 do {
2351 bool oom_check;
2353 /* If killed, bypass charge */
2354 if (fatal_signal_pending(current)) {
2355 css_put(&memcg->css);
2356 goto bypass;
2359 oom_check = false;
2360 if (oom && !nr_oom_retries) {
2361 oom_check = true;
2362 nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2365 ret = mem_cgroup_do_charge(memcg, gfp_mask, batch, oom_check);
2366 switch (ret) {
2367 case CHARGE_OK:
2368 break;
2369 case CHARGE_RETRY: /* not in OOM situation but retry */
2370 batch = nr_pages;
2371 css_put(&memcg->css);
2372 memcg = NULL;
2373 goto again;
2374 case CHARGE_WOULDBLOCK: /* !__GFP_WAIT */
2375 css_put(&memcg->css);
2376 goto nomem;
2377 case CHARGE_NOMEM: /* OOM routine works */
2378 if (!oom) {
2379 css_put(&memcg->css);
2380 goto nomem;
2382 /* If oom, we never return -ENOMEM */
2383 nr_oom_retries--;
2384 break;
2385 case CHARGE_OOM_DIE: /* Killed by OOM Killer */
2386 css_put(&memcg->css);
2387 goto bypass;
2389 } while (ret != CHARGE_OK);
2391 if (batch > nr_pages)
2392 refill_stock(memcg, batch - nr_pages);
2393 css_put(&memcg->css);
2394 done:
2395 *ptr = memcg;
2396 return 0;
2397 nomem:
2398 *ptr = NULL;
2399 return -ENOMEM;
2400 bypass:
2401 *ptr = NULL;
2402 return 0;
2406 * Somemtimes we have to undo a charge we got by try_charge().
2407 * This function is for that and do uncharge, put css's refcnt.
2408 * gotten by try_charge().
2410 static void __mem_cgroup_cancel_charge(struct mem_cgroup *memcg,
2411 unsigned int nr_pages)
2413 if (!mem_cgroup_is_root(memcg)) {
2414 unsigned long bytes = nr_pages * PAGE_SIZE;
2416 res_counter_uncharge(&memcg->res, bytes);
2417 if (do_swap_account)
2418 res_counter_uncharge(&memcg->memsw, bytes);
2423 * A helper function to get mem_cgroup from ID. must be called under
2424 * rcu_read_lock(). The caller must check css_is_removed() or some if
2425 * it's concern. (dropping refcnt from swap can be called against removed
2426 * memcg.)
2428 static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
2430 struct cgroup_subsys_state *css;
2432 /* ID 0 is unused ID */
2433 if (!id)
2434 return NULL;
2435 css = css_lookup(&mem_cgroup_subsys, id);
2436 if (!css)
2437 return NULL;
2438 return container_of(css, struct mem_cgroup, css);
2441 struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
2443 struct mem_cgroup *memcg = NULL;
2444 struct page_cgroup *pc;
2445 unsigned short id;
2446 swp_entry_t ent;
2448 VM_BUG_ON(!PageLocked(page));
2450 pc = lookup_page_cgroup(page);
2451 lock_page_cgroup(pc);
2452 if (PageCgroupUsed(pc)) {
2453 memcg = pc->mem_cgroup;
2454 if (memcg && !css_tryget(&memcg->css))
2455 memcg = NULL;
2456 } else if (PageSwapCache(page)) {
2457 ent.val = page_private(page);
2458 id = lookup_swap_cgroup(ent);
2459 rcu_read_lock();
2460 memcg = mem_cgroup_lookup(id);
2461 if (memcg && !css_tryget(&memcg->css))
2462 memcg = NULL;
2463 rcu_read_unlock();
2465 unlock_page_cgroup(pc);
2466 return memcg;
2469 static void __mem_cgroup_commit_charge(struct mem_cgroup *memcg,
2470 struct page *page,
2471 unsigned int nr_pages,
2472 struct page_cgroup *pc,
2473 enum charge_type ctype)
2475 lock_page_cgroup(pc);
2476 if (unlikely(PageCgroupUsed(pc))) {
2477 unlock_page_cgroup(pc);
2478 __mem_cgroup_cancel_charge(memcg, nr_pages);
2479 return;
2482 * we don't need page_cgroup_lock about tail pages, becase they are not
2483 * accessed by any other context at this point.
2485 pc->mem_cgroup = memcg;
2487 * We access a page_cgroup asynchronously without lock_page_cgroup().
2488 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
2489 * is accessed after testing USED bit. To make pc->mem_cgroup visible
2490 * before USED bit, we need memory barrier here.
2491 * See mem_cgroup_add_lru_list(), etc.
2493 smp_wmb();
2494 switch (ctype) {
2495 case MEM_CGROUP_CHARGE_TYPE_CACHE:
2496 case MEM_CGROUP_CHARGE_TYPE_SHMEM:
2497 SetPageCgroupCache(pc);
2498 SetPageCgroupUsed(pc);
2499 break;
2500 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
2501 ClearPageCgroupCache(pc);
2502 SetPageCgroupUsed(pc);
2503 break;
2504 default:
2505 break;
2508 mem_cgroup_charge_statistics(memcg, PageCgroupCache(pc), nr_pages);
2509 unlock_page_cgroup(pc);
2511 * "charge_statistics" updated event counter. Then, check it.
2512 * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
2513 * if they exceeds softlimit.
2515 memcg_check_events(memcg, page);
2518 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
2520 #define PCGF_NOCOPY_AT_SPLIT ((1 << PCG_LOCK) | (1 << PCG_MOVE_LOCK) |\
2521 (1 << PCG_ACCT_LRU) | (1 << PCG_MIGRATION))
2523 * Because tail pages are not marked as "used", set it. We're under
2524 * zone->lru_lock, 'splitting on pmd' and compund_lock.
2526 void mem_cgroup_split_huge_fixup(struct page *head, struct page *tail)
2528 struct page_cgroup *head_pc = lookup_page_cgroup(head);
2529 struct page_cgroup *tail_pc = lookup_page_cgroup(tail);
2530 unsigned long flags;
2532 if (mem_cgroup_disabled())
2533 return;
2535 * We have no races with charge/uncharge but will have races with
2536 * page state accounting.
2538 move_lock_page_cgroup(head_pc, &flags);
2540 tail_pc->mem_cgroup = head_pc->mem_cgroup;
2541 smp_wmb(); /* see __commit_charge() */
2542 if (PageCgroupAcctLRU(head_pc)) {
2543 enum lru_list lru;
2544 struct mem_cgroup_per_zone *mz;
2547 * LRU flags cannot be copied because we need to add tail
2548 *.page to LRU by generic call and our hook will be called.
2549 * We hold lru_lock, then, reduce counter directly.
2551 lru = page_lru(head);
2552 mz = page_cgroup_zoneinfo(head_pc->mem_cgroup, head);
2553 MEM_CGROUP_ZSTAT(mz, lru) -= 1;
2555 tail_pc->flags = head_pc->flags & ~PCGF_NOCOPY_AT_SPLIT;
2556 move_unlock_page_cgroup(head_pc, &flags);
2558 #endif
2561 * mem_cgroup_move_account - move account of the page
2562 * @page: the page
2563 * @nr_pages: number of regular pages (>1 for huge pages)
2564 * @pc: page_cgroup of the page.
2565 * @from: mem_cgroup which the page is moved from.
2566 * @to: mem_cgroup which the page is moved to. @from != @to.
2567 * @uncharge: whether we should call uncharge and css_put against @from.
2569 * The caller must confirm following.
2570 * - page is not on LRU (isolate_page() is useful.)
2571 * - compound_lock is held when nr_pages > 1
2573 * This function doesn't do "charge" nor css_get to new cgroup. It should be
2574 * done by a caller(__mem_cgroup_try_charge would be useful). If @uncharge is
2575 * true, this function does "uncharge" from old cgroup, but it doesn't if
2576 * @uncharge is false, so a caller should do "uncharge".
2578 static int mem_cgroup_move_account(struct page *page,
2579 unsigned int nr_pages,
2580 struct page_cgroup *pc,
2581 struct mem_cgroup *from,
2582 struct mem_cgroup *to,
2583 bool uncharge)
2585 unsigned long flags;
2586 int ret;
2588 VM_BUG_ON(from == to);
2589 VM_BUG_ON(PageLRU(page));
2591 * The page is isolated from LRU. So, collapse function
2592 * will not handle this page. But page splitting can happen.
2593 * Do this check under compound_page_lock(). The caller should
2594 * hold it.
2596 ret = -EBUSY;
2597 if (nr_pages > 1 && !PageTransHuge(page))
2598 goto out;
2600 lock_page_cgroup(pc);
2602 ret = -EINVAL;
2603 if (!PageCgroupUsed(pc) || pc->mem_cgroup != from)
2604 goto unlock;
2606 move_lock_page_cgroup(pc, &flags);
2608 if (PageCgroupFileMapped(pc)) {
2609 /* Update mapped_file data for mem_cgroup */
2610 preempt_disable();
2611 __this_cpu_dec(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
2612 __this_cpu_inc(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
2613 preempt_enable();
2615 mem_cgroup_charge_statistics(from, PageCgroupCache(pc), -nr_pages);
2616 if (uncharge)
2617 /* This is not "cancel", but cancel_charge does all we need. */
2618 __mem_cgroup_cancel_charge(from, nr_pages);
2620 /* caller should have done css_get */
2621 pc->mem_cgroup = to;
2622 mem_cgroup_charge_statistics(to, PageCgroupCache(pc), nr_pages);
2624 * We charges against "to" which may not have any tasks. Then, "to"
2625 * can be under rmdir(). But in current implementation, caller of
2626 * this function is just force_empty() and move charge, so it's
2627 * guaranteed that "to" is never removed. So, we don't check rmdir
2628 * status here.
2630 move_unlock_page_cgroup(pc, &flags);
2631 ret = 0;
2632 unlock:
2633 unlock_page_cgroup(pc);
2635 * check events
2637 memcg_check_events(to, page);
2638 memcg_check_events(from, page);
2639 out:
2640 return ret;
2644 * move charges to its parent.
2647 static int mem_cgroup_move_parent(struct page *page,
2648 struct page_cgroup *pc,
2649 struct mem_cgroup *child,
2650 gfp_t gfp_mask)
2652 struct cgroup *cg = child->css.cgroup;
2653 struct cgroup *pcg = cg->parent;
2654 struct mem_cgroup *parent;
2655 unsigned int nr_pages;
2656 unsigned long uninitialized_var(flags);
2657 int ret;
2659 /* Is ROOT ? */
2660 if (!pcg)
2661 return -EINVAL;
2663 ret = -EBUSY;
2664 if (!get_page_unless_zero(page))
2665 goto out;
2666 if (isolate_lru_page(page))
2667 goto put;
2669 nr_pages = hpage_nr_pages(page);
2671 parent = mem_cgroup_from_cont(pcg);
2672 ret = __mem_cgroup_try_charge(NULL, gfp_mask, nr_pages, &parent, false);
2673 if (ret || !parent)
2674 goto put_back;
2676 if (nr_pages > 1)
2677 flags = compound_lock_irqsave(page);
2679 ret = mem_cgroup_move_account(page, nr_pages, pc, child, parent, true);
2680 if (ret)
2681 __mem_cgroup_cancel_charge(parent, nr_pages);
2683 if (nr_pages > 1)
2684 compound_unlock_irqrestore(page, flags);
2685 put_back:
2686 putback_lru_page(page);
2687 put:
2688 put_page(page);
2689 out:
2690 return ret;
2694 * Charge the memory controller for page usage.
2695 * Return
2696 * 0 if the charge was successful
2697 * < 0 if the cgroup is over its limit
2699 static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
2700 gfp_t gfp_mask, enum charge_type ctype)
2702 struct mem_cgroup *memcg = NULL;
2703 unsigned int nr_pages = 1;
2704 struct page_cgroup *pc;
2705 bool oom = true;
2706 int ret;
2708 if (PageTransHuge(page)) {
2709 nr_pages <<= compound_order(page);
2710 VM_BUG_ON(!PageTransHuge(page));
2712 * Never OOM-kill a process for a huge page. The
2713 * fault handler will fall back to regular pages.
2715 oom = false;
2718 pc = lookup_page_cgroup(page);
2719 BUG_ON(!pc); /* XXX: remove this and move pc lookup into commit */
2721 ret = __mem_cgroup_try_charge(mm, gfp_mask, nr_pages, &memcg, oom);
2722 if (ret || !memcg)
2723 return ret;
2725 __mem_cgroup_commit_charge(memcg, page, nr_pages, pc, ctype);
2726 return 0;
2729 int mem_cgroup_newpage_charge(struct page *page,
2730 struct mm_struct *mm, gfp_t gfp_mask)
2732 if (mem_cgroup_disabled())
2733 return 0;
2735 * If already mapped, we don't have to account.
2736 * If page cache, page->mapping has address_space.
2737 * But page->mapping may have out-of-use anon_vma pointer,
2738 * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
2739 * is NULL.
2741 if (page_mapped(page) || (page->mapping && !PageAnon(page)))
2742 return 0;
2743 if (unlikely(!mm))
2744 mm = &init_mm;
2745 return mem_cgroup_charge_common(page, mm, gfp_mask,
2746 MEM_CGROUP_CHARGE_TYPE_MAPPED);
2749 static void
2750 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
2751 enum charge_type ctype);
2753 static void
2754 __mem_cgroup_commit_charge_lrucare(struct page *page, struct mem_cgroup *memcg,
2755 enum charge_type ctype)
2757 struct page_cgroup *pc = lookup_page_cgroup(page);
2759 * In some case, SwapCache, FUSE(splice_buf->radixtree), the page
2760 * is already on LRU. It means the page may on some other page_cgroup's
2761 * LRU. Take care of it.
2763 mem_cgroup_lru_del_before_commit(page);
2764 __mem_cgroup_commit_charge(memcg, page, 1, pc, ctype);
2765 mem_cgroup_lru_add_after_commit(page);
2766 return;
2769 int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
2770 gfp_t gfp_mask)
2772 struct mem_cgroup *memcg = NULL;
2773 int ret;
2775 if (mem_cgroup_disabled())
2776 return 0;
2777 if (PageCompound(page))
2778 return 0;
2780 if (unlikely(!mm))
2781 mm = &init_mm;
2783 if (page_is_file_cache(page)) {
2784 ret = __mem_cgroup_try_charge(mm, gfp_mask, 1, &memcg, true);
2785 if (ret || !memcg)
2786 return ret;
2789 * FUSE reuses pages without going through the final
2790 * put that would remove them from the LRU list, make
2791 * sure that they get relinked properly.
2793 __mem_cgroup_commit_charge_lrucare(page, memcg,
2794 MEM_CGROUP_CHARGE_TYPE_CACHE);
2795 return ret;
2797 /* shmem */
2798 if (PageSwapCache(page)) {
2799 ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &memcg);
2800 if (!ret)
2801 __mem_cgroup_commit_charge_swapin(page, memcg,
2802 MEM_CGROUP_CHARGE_TYPE_SHMEM);
2803 } else
2804 ret = mem_cgroup_charge_common(page, mm, gfp_mask,
2805 MEM_CGROUP_CHARGE_TYPE_SHMEM);
2807 return ret;
2811 * While swap-in, try_charge -> commit or cancel, the page is locked.
2812 * And when try_charge() successfully returns, one refcnt to memcg without
2813 * struct page_cgroup is acquired. This refcnt will be consumed by
2814 * "commit()" or removed by "cancel()"
2816 int mem_cgroup_try_charge_swapin(struct mm_struct *mm,
2817 struct page *page,
2818 gfp_t mask, struct mem_cgroup **ptr)
2820 struct mem_cgroup *memcg;
2821 int ret;
2823 *ptr = NULL;
2825 if (mem_cgroup_disabled())
2826 return 0;
2828 if (!do_swap_account)
2829 goto charge_cur_mm;
2831 * A racing thread's fault, or swapoff, may have already updated
2832 * the pte, and even removed page from swap cache: in those cases
2833 * do_swap_page()'s pte_same() test will fail; but there's also a
2834 * KSM case which does need to charge the page.
2836 if (!PageSwapCache(page))
2837 goto charge_cur_mm;
2838 memcg = try_get_mem_cgroup_from_page(page);
2839 if (!memcg)
2840 goto charge_cur_mm;
2841 *ptr = memcg;
2842 ret = __mem_cgroup_try_charge(NULL, mask, 1, ptr, true);
2843 css_put(&memcg->css);
2844 return ret;
2845 charge_cur_mm:
2846 if (unlikely(!mm))
2847 mm = &init_mm;
2848 return __mem_cgroup_try_charge(mm, mask, 1, ptr, true);
2851 static void
2852 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
2853 enum charge_type ctype)
2855 if (mem_cgroup_disabled())
2856 return;
2857 if (!ptr)
2858 return;
2859 cgroup_exclude_rmdir(&ptr->css);
2861 __mem_cgroup_commit_charge_lrucare(page, ptr, ctype);
2863 * Now swap is on-memory. This means this page may be
2864 * counted both as mem and swap....double count.
2865 * Fix it by uncharging from memsw. Basically, this SwapCache is stable
2866 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
2867 * may call delete_from_swap_cache() before reach here.
2869 if (do_swap_account && PageSwapCache(page)) {
2870 swp_entry_t ent = {.val = page_private(page)};
2871 unsigned short id;
2872 struct mem_cgroup *memcg;
2874 id = swap_cgroup_record(ent, 0);
2875 rcu_read_lock();
2876 memcg = mem_cgroup_lookup(id);
2877 if (memcg) {
2879 * This recorded memcg can be obsolete one. So, avoid
2880 * calling css_tryget
2882 if (!mem_cgroup_is_root(memcg))
2883 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
2884 mem_cgroup_swap_statistics(memcg, false);
2885 mem_cgroup_put(memcg);
2887 rcu_read_unlock();
2890 * At swapin, we may charge account against cgroup which has no tasks.
2891 * So, rmdir()->pre_destroy() can be called while we do this charge.
2892 * In that case, we need to call pre_destroy() again. check it here.
2894 cgroup_release_and_wakeup_rmdir(&ptr->css);
2897 void mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr)
2899 __mem_cgroup_commit_charge_swapin(page, ptr,
2900 MEM_CGROUP_CHARGE_TYPE_MAPPED);
2903 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *memcg)
2905 if (mem_cgroup_disabled())
2906 return;
2907 if (!memcg)
2908 return;
2909 __mem_cgroup_cancel_charge(memcg, 1);
2912 static void mem_cgroup_do_uncharge(struct mem_cgroup *memcg,
2913 unsigned int nr_pages,
2914 const enum charge_type ctype)
2916 struct memcg_batch_info *batch = NULL;
2917 bool uncharge_memsw = true;
2919 /* If swapout, usage of swap doesn't decrease */
2920 if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2921 uncharge_memsw = false;
2923 batch = &current->memcg_batch;
2925 * In usual, we do css_get() when we remember memcg pointer.
2926 * But in this case, we keep res->usage until end of a series of
2927 * uncharges. Then, it's ok to ignore memcg's refcnt.
2929 if (!batch->memcg)
2930 batch->memcg = memcg;
2932 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
2933 * In those cases, all pages freed continuously can be expected to be in
2934 * the same cgroup and we have chance to coalesce uncharges.
2935 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
2936 * because we want to do uncharge as soon as possible.
2939 if (!batch->do_batch || test_thread_flag(TIF_MEMDIE))
2940 goto direct_uncharge;
2942 if (nr_pages > 1)
2943 goto direct_uncharge;
2946 * In typical case, batch->memcg == mem. This means we can
2947 * merge a series of uncharges to an uncharge of res_counter.
2948 * If not, we uncharge res_counter ony by one.
2950 if (batch->memcg != memcg)
2951 goto direct_uncharge;
2952 /* remember freed charge and uncharge it later */
2953 batch->nr_pages++;
2954 if (uncharge_memsw)
2955 batch->memsw_nr_pages++;
2956 return;
2957 direct_uncharge:
2958 res_counter_uncharge(&memcg->res, nr_pages * PAGE_SIZE);
2959 if (uncharge_memsw)
2960 res_counter_uncharge(&memcg->memsw, nr_pages * PAGE_SIZE);
2961 if (unlikely(batch->memcg != memcg))
2962 memcg_oom_recover(memcg);
2963 return;
2967 * uncharge if !page_mapped(page)
2969 static struct mem_cgroup *
2970 __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype)
2972 struct mem_cgroup *memcg = NULL;
2973 unsigned int nr_pages = 1;
2974 struct page_cgroup *pc;
2976 if (mem_cgroup_disabled())
2977 return NULL;
2979 if (PageSwapCache(page))
2980 return NULL;
2982 if (PageTransHuge(page)) {
2983 nr_pages <<= compound_order(page);
2984 VM_BUG_ON(!PageTransHuge(page));
2987 * Check if our page_cgroup is valid
2989 pc = lookup_page_cgroup(page);
2990 if (unlikely(!pc || !PageCgroupUsed(pc)))
2991 return NULL;
2993 lock_page_cgroup(pc);
2995 memcg = pc->mem_cgroup;
2997 if (!PageCgroupUsed(pc))
2998 goto unlock_out;
3000 switch (ctype) {
3001 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
3002 case MEM_CGROUP_CHARGE_TYPE_DROP:
3003 /* See mem_cgroup_prepare_migration() */
3004 if (page_mapped(page) || PageCgroupMigration(pc))
3005 goto unlock_out;
3006 break;
3007 case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
3008 if (!PageAnon(page)) { /* Shared memory */
3009 if (page->mapping && !page_is_file_cache(page))
3010 goto unlock_out;
3011 } else if (page_mapped(page)) /* Anon */
3012 goto unlock_out;
3013 break;
3014 default:
3015 break;
3018 mem_cgroup_charge_statistics(memcg, PageCgroupCache(pc), -nr_pages);
3020 ClearPageCgroupUsed(pc);
3022 * pc->mem_cgroup is not cleared here. It will be accessed when it's
3023 * freed from LRU. This is safe because uncharged page is expected not
3024 * to be reused (freed soon). Exception is SwapCache, it's handled by
3025 * special functions.
3028 unlock_page_cgroup(pc);
3030 * even after unlock, we have memcg->res.usage here and this memcg
3031 * will never be freed.
3033 memcg_check_events(memcg, page);
3034 if (do_swap_account && ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT) {
3035 mem_cgroup_swap_statistics(memcg, true);
3036 mem_cgroup_get(memcg);
3038 if (!mem_cgroup_is_root(memcg))
3039 mem_cgroup_do_uncharge(memcg, nr_pages, ctype);
3041 return memcg;
3043 unlock_out:
3044 unlock_page_cgroup(pc);
3045 return NULL;
3048 void mem_cgroup_uncharge_page(struct page *page)
3050 /* early check. */
3051 if (page_mapped(page))
3052 return;
3053 if (page->mapping && !PageAnon(page))
3054 return;
3055 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_MAPPED);
3058 void mem_cgroup_uncharge_cache_page(struct page *page)
3060 VM_BUG_ON(page_mapped(page));
3061 VM_BUG_ON(page->mapping);
3062 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE);
3066 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
3067 * In that cases, pages are freed continuously and we can expect pages
3068 * are in the same memcg. All these calls itself limits the number of
3069 * pages freed at once, then uncharge_start/end() is called properly.
3070 * This may be called prural(2) times in a context,
3073 void mem_cgroup_uncharge_start(void)
3075 current->memcg_batch.do_batch++;
3076 /* We can do nest. */
3077 if (current->memcg_batch.do_batch == 1) {
3078 current->memcg_batch.memcg = NULL;
3079 current->memcg_batch.nr_pages = 0;
3080 current->memcg_batch.memsw_nr_pages = 0;
3084 void mem_cgroup_uncharge_end(void)
3086 struct memcg_batch_info *batch = &current->memcg_batch;
3088 if (!batch->do_batch)
3089 return;
3091 batch->do_batch--;
3092 if (batch->do_batch) /* If stacked, do nothing. */
3093 return;
3095 if (!batch->memcg)
3096 return;
3098 * This "batch->memcg" is valid without any css_get/put etc...
3099 * bacause we hide charges behind us.
3101 if (batch->nr_pages)
3102 res_counter_uncharge(&batch->memcg->res,
3103 batch->nr_pages * PAGE_SIZE);
3104 if (batch->memsw_nr_pages)
3105 res_counter_uncharge(&batch->memcg->memsw,
3106 batch->memsw_nr_pages * PAGE_SIZE);
3107 memcg_oom_recover(batch->memcg);
3108 /* forget this pointer (for sanity check) */
3109 batch->memcg = NULL;
3112 #ifdef CONFIG_SWAP
3114 * called after __delete_from_swap_cache() and drop "page" account.
3115 * memcg information is recorded to swap_cgroup of "ent"
3117 void
3118 mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
3120 struct mem_cgroup *memcg;
3121 int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
3123 if (!swapout) /* this was a swap cache but the swap is unused ! */
3124 ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
3126 memcg = __mem_cgroup_uncharge_common(page, ctype);
3129 * record memcg information, if swapout && memcg != NULL,
3130 * mem_cgroup_get() was called in uncharge().
3132 if (do_swap_account && swapout && memcg)
3133 swap_cgroup_record(ent, css_id(&memcg->css));
3135 #endif
3137 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3139 * called from swap_entry_free(). remove record in swap_cgroup and
3140 * uncharge "memsw" account.
3142 void mem_cgroup_uncharge_swap(swp_entry_t ent)
3144 struct mem_cgroup *memcg;
3145 unsigned short id;
3147 if (!do_swap_account)
3148 return;
3150 id = swap_cgroup_record(ent, 0);
3151 rcu_read_lock();
3152 memcg = mem_cgroup_lookup(id);
3153 if (memcg) {
3155 * We uncharge this because swap is freed.
3156 * This memcg can be obsolete one. We avoid calling css_tryget
3158 if (!mem_cgroup_is_root(memcg))
3159 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
3160 mem_cgroup_swap_statistics(memcg, false);
3161 mem_cgroup_put(memcg);
3163 rcu_read_unlock();
3167 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3168 * @entry: swap entry to be moved
3169 * @from: mem_cgroup which the entry is moved from
3170 * @to: mem_cgroup which the entry is moved to
3171 * @need_fixup: whether we should fixup res_counters and refcounts.
3173 * It succeeds only when the swap_cgroup's record for this entry is the same
3174 * as the mem_cgroup's id of @from.
3176 * Returns 0 on success, -EINVAL on failure.
3178 * The caller must have charged to @to, IOW, called res_counter_charge() about
3179 * both res and memsw, and called css_get().
3181 static int mem_cgroup_move_swap_account(swp_entry_t entry,
3182 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
3184 unsigned short old_id, new_id;
3186 old_id = css_id(&from->css);
3187 new_id = css_id(&to->css);
3189 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
3190 mem_cgroup_swap_statistics(from, false);
3191 mem_cgroup_swap_statistics(to, true);
3193 * This function is only called from task migration context now.
3194 * It postpones res_counter and refcount handling till the end
3195 * of task migration(mem_cgroup_clear_mc()) for performance
3196 * improvement. But we cannot postpone mem_cgroup_get(to)
3197 * because if the process that has been moved to @to does
3198 * swap-in, the refcount of @to might be decreased to 0.
3200 mem_cgroup_get(to);
3201 if (need_fixup) {
3202 if (!mem_cgroup_is_root(from))
3203 res_counter_uncharge(&from->memsw, PAGE_SIZE);
3204 mem_cgroup_put(from);
3206 * we charged both to->res and to->memsw, so we should
3207 * uncharge to->res.
3209 if (!mem_cgroup_is_root(to))
3210 res_counter_uncharge(&to->res, PAGE_SIZE);
3212 return 0;
3214 return -EINVAL;
3216 #else
3217 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
3218 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
3220 return -EINVAL;
3222 #endif
3225 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
3226 * page belongs to.
3228 int mem_cgroup_prepare_migration(struct page *page,
3229 struct page *newpage, struct mem_cgroup **ptr, gfp_t gfp_mask)
3231 struct mem_cgroup *memcg = NULL;
3232 struct page_cgroup *pc;
3233 enum charge_type ctype;
3234 int ret = 0;
3236 *ptr = NULL;
3238 VM_BUG_ON(PageTransHuge(page));
3239 if (mem_cgroup_disabled())
3240 return 0;
3242 pc = lookup_page_cgroup(page);
3243 lock_page_cgroup(pc);
3244 if (PageCgroupUsed(pc)) {
3245 memcg = pc->mem_cgroup;
3246 css_get(&memcg->css);
3248 * At migrating an anonymous page, its mapcount goes down
3249 * to 0 and uncharge() will be called. But, even if it's fully
3250 * unmapped, migration may fail and this page has to be
3251 * charged again. We set MIGRATION flag here and delay uncharge
3252 * until end_migration() is called
3254 * Corner Case Thinking
3255 * A)
3256 * When the old page was mapped as Anon and it's unmap-and-freed
3257 * while migration was ongoing.
3258 * If unmap finds the old page, uncharge() of it will be delayed
3259 * until end_migration(). If unmap finds a new page, it's
3260 * uncharged when it make mapcount to be 1->0. If unmap code
3261 * finds swap_migration_entry, the new page will not be mapped
3262 * and end_migration() will find it(mapcount==0).
3264 * B)
3265 * When the old page was mapped but migraion fails, the kernel
3266 * remaps it. A charge for it is kept by MIGRATION flag even
3267 * if mapcount goes down to 0. We can do remap successfully
3268 * without charging it again.
3270 * C)
3271 * The "old" page is under lock_page() until the end of
3272 * migration, so, the old page itself will not be swapped-out.
3273 * If the new page is swapped out before end_migraton, our
3274 * hook to usual swap-out path will catch the event.
3276 if (PageAnon(page))
3277 SetPageCgroupMigration(pc);
3279 unlock_page_cgroup(pc);
3281 * If the page is not charged at this point,
3282 * we return here.
3284 if (!memcg)
3285 return 0;
3287 *ptr = memcg;
3288 ret = __mem_cgroup_try_charge(NULL, gfp_mask, 1, ptr, false);
3289 css_put(&memcg->css);/* drop extra refcnt */
3290 if (ret || *ptr == NULL) {
3291 if (PageAnon(page)) {
3292 lock_page_cgroup(pc);
3293 ClearPageCgroupMigration(pc);
3294 unlock_page_cgroup(pc);
3296 * The old page may be fully unmapped while we kept it.
3298 mem_cgroup_uncharge_page(page);
3300 return -ENOMEM;
3303 * We charge new page before it's used/mapped. So, even if unlock_page()
3304 * is called before end_migration, we can catch all events on this new
3305 * page. In the case new page is migrated but not remapped, new page's
3306 * mapcount will be finally 0 and we call uncharge in end_migration().
3308 pc = lookup_page_cgroup(newpage);
3309 if (PageAnon(page))
3310 ctype = MEM_CGROUP_CHARGE_TYPE_MAPPED;
3311 else if (page_is_file_cache(page))
3312 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
3313 else
3314 ctype = MEM_CGROUP_CHARGE_TYPE_SHMEM;
3315 __mem_cgroup_commit_charge(memcg, page, 1, pc, ctype);
3316 return ret;
3319 /* remove redundant charge if migration failed*/
3320 void mem_cgroup_end_migration(struct mem_cgroup *memcg,
3321 struct page *oldpage, struct page *newpage, bool migration_ok)
3323 struct page *used, *unused;
3324 struct page_cgroup *pc;
3326 if (!memcg)
3327 return;
3328 /* blocks rmdir() */
3329 cgroup_exclude_rmdir(&memcg->css);
3330 if (!migration_ok) {
3331 used = oldpage;
3332 unused = newpage;
3333 } else {
3334 used = newpage;
3335 unused = oldpage;
3338 * We disallowed uncharge of pages under migration because mapcount
3339 * of the page goes down to zero, temporarly.
3340 * Clear the flag and check the page should be charged.
3342 pc = lookup_page_cgroup(oldpage);
3343 lock_page_cgroup(pc);
3344 ClearPageCgroupMigration(pc);
3345 unlock_page_cgroup(pc);
3347 __mem_cgroup_uncharge_common(unused, MEM_CGROUP_CHARGE_TYPE_FORCE);
3350 * If a page is a file cache, radix-tree replacement is very atomic
3351 * and we can skip this check. When it was an Anon page, its mapcount
3352 * goes down to 0. But because we added MIGRATION flage, it's not
3353 * uncharged yet. There are several case but page->mapcount check
3354 * and USED bit check in mem_cgroup_uncharge_page() will do enough
3355 * check. (see prepare_charge() also)
3357 if (PageAnon(used))
3358 mem_cgroup_uncharge_page(used);
3360 * At migration, we may charge account against cgroup which has no
3361 * tasks.
3362 * So, rmdir()->pre_destroy() can be called while we do this charge.
3363 * In that case, we need to call pre_destroy() again. check it here.
3365 cgroup_release_and_wakeup_rmdir(&memcg->css);
3368 #ifdef CONFIG_DEBUG_VM
3369 static struct page_cgroup *lookup_page_cgroup_used(struct page *page)
3371 struct page_cgroup *pc;
3373 pc = lookup_page_cgroup(page);
3374 if (likely(pc) && PageCgroupUsed(pc))
3375 return pc;
3376 return NULL;
3379 bool mem_cgroup_bad_page_check(struct page *page)
3381 if (mem_cgroup_disabled())
3382 return false;
3384 return lookup_page_cgroup_used(page) != NULL;
3387 void mem_cgroup_print_bad_page(struct page *page)
3389 struct page_cgroup *pc;
3391 pc = lookup_page_cgroup_used(page);
3392 if (pc) {
3393 int ret = -1;
3394 char *path;
3396 printk(KERN_ALERT "pc:%p pc->flags:%lx pc->mem_cgroup:%p",
3397 pc, pc->flags, pc->mem_cgroup);
3399 path = kmalloc(PATH_MAX, GFP_KERNEL);
3400 if (path) {
3401 rcu_read_lock();
3402 ret = cgroup_path(pc->mem_cgroup->css.cgroup,
3403 path, PATH_MAX);
3404 rcu_read_unlock();
3407 printk(KERN_CONT "(%s)\n",
3408 (ret < 0) ? "cannot get the path" : path);
3409 kfree(path);
3412 #endif
3414 static DEFINE_MUTEX(set_limit_mutex);
3416 static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
3417 unsigned long long val)
3419 int retry_count;
3420 u64 memswlimit, memlimit;
3421 int ret = 0;
3422 int children = mem_cgroup_count_children(memcg);
3423 u64 curusage, oldusage;
3424 int enlarge;
3427 * For keeping hierarchical_reclaim simple, how long we should retry
3428 * is depends on callers. We set our retry-count to be function
3429 * of # of children which we should visit in this loop.
3431 retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
3433 oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
3435 enlarge = 0;
3436 while (retry_count) {
3437 if (signal_pending(current)) {
3438 ret = -EINTR;
3439 break;
3442 * Rather than hide all in some function, I do this in
3443 * open coded manner. You see what this really does.
3444 * We have to guarantee memcg->res.limit < memcg->memsw.limit.
3446 mutex_lock(&set_limit_mutex);
3447 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3448 if (memswlimit < val) {
3449 ret = -EINVAL;
3450 mutex_unlock(&set_limit_mutex);
3451 break;
3454 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3455 if (memlimit < val)
3456 enlarge = 1;
3458 ret = res_counter_set_limit(&memcg->res, val);
3459 if (!ret) {
3460 if (memswlimit == val)
3461 memcg->memsw_is_minimum = true;
3462 else
3463 memcg->memsw_is_minimum = false;
3465 mutex_unlock(&set_limit_mutex);
3467 if (!ret)
3468 break;
3470 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
3471 MEM_CGROUP_RECLAIM_SHRINK,
3472 NULL);
3473 curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
3474 /* Usage is reduced ? */
3475 if (curusage >= oldusage)
3476 retry_count--;
3477 else
3478 oldusage = curusage;
3480 if (!ret && enlarge)
3481 memcg_oom_recover(memcg);
3483 return ret;
3486 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
3487 unsigned long long val)
3489 int retry_count;
3490 u64 memlimit, memswlimit, oldusage, curusage;
3491 int children = mem_cgroup_count_children(memcg);
3492 int ret = -EBUSY;
3493 int enlarge = 0;
3495 /* see mem_cgroup_resize_res_limit */
3496 retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
3497 oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
3498 while (retry_count) {
3499 if (signal_pending(current)) {
3500 ret = -EINTR;
3501 break;
3504 * Rather than hide all in some function, I do this in
3505 * open coded manner. You see what this really does.
3506 * We have to guarantee memcg->res.limit < memcg->memsw.limit.
3508 mutex_lock(&set_limit_mutex);
3509 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3510 if (memlimit > val) {
3511 ret = -EINVAL;
3512 mutex_unlock(&set_limit_mutex);
3513 break;
3515 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3516 if (memswlimit < val)
3517 enlarge = 1;
3518 ret = res_counter_set_limit(&memcg->memsw, val);
3519 if (!ret) {
3520 if (memlimit == val)
3521 memcg->memsw_is_minimum = true;
3522 else
3523 memcg->memsw_is_minimum = false;
3525 mutex_unlock(&set_limit_mutex);
3527 if (!ret)
3528 break;
3530 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
3531 MEM_CGROUP_RECLAIM_NOSWAP |
3532 MEM_CGROUP_RECLAIM_SHRINK,
3533 NULL);
3534 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
3535 /* Usage is reduced ? */
3536 if (curusage >= oldusage)
3537 retry_count--;
3538 else
3539 oldusage = curusage;
3541 if (!ret && enlarge)
3542 memcg_oom_recover(memcg);
3543 return ret;
3546 unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
3547 gfp_t gfp_mask,
3548 unsigned long *total_scanned)
3550 unsigned long nr_reclaimed = 0;
3551 struct mem_cgroup_per_zone *mz, *next_mz = NULL;
3552 unsigned long reclaimed;
3553 int loop = 0;
3554 struct mem_cgroup_tree_per_zone *mctz;
3555 unsigned long long excess;
3556 unsigned long nr_scanned;
3558 if (order > 0)
3559 return 0;
3561 mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone));
3563 * This loop can run a while, specially if mem_cgroup's continuously
3564 * keep exceeding their soft limit and putting the system under
3565 * pressure
3567 do {
3568 if (next_mz)
3569 mz = next_mz;
3570 else
3571 mz = mem_cgroup_largest_soft_limit_node(mctz);
3572 if (!mz)
3573 break;
3575 nr_scanned = 0;
3576 reclaimed = mem_cgroup_hierarchical_reclaim(mz->mem, zone,
3577 gfp_mask,
3578 MEM_CGROUP_RECLAIM_SOFT,
3579 &nr_scanned);
3580 nr_reclaimed += reclaimed;
3581 *total_scanned += nr_scanned;
3582 spin_lock(&mctz->lock);
3585 * If we failed to reclaim anything from this memory cgroup
3586 * it is time to move on to the next cgroup
3588 next_mz = NULL;
3589 if (!reclaimed) {
3590 do {
3592 * Loop until we find yet another one.
3594 * By the time we get the soft_limit lock
3595 * again, someone might have aded the
3596 * group back on the RB tree. Iterate to
3597 * make sure we get a different mem.
3598 * mem_cgroup_largest_soft_limit_node returns
3599 * NULL if no other cgroup is present on
3600 * the tree
3602 next_mz =
3603 __mem_cgroup_largest_soft_limit_node(mctz);
3604 if (next_mz == mz)
3605 css_put(&next_mz->mem->css);
3606 else /* next_mz == NULL or other memcg */
3607 break;
3608 } while (1);
3610 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
3611 excess = res_counter_soft_limit_excess(&mz->mem->res);
3613 * One school of thought says that we should not add
3614 * back the node to the tree if reclaim returns 0.
3615 * But our reclaim could return 0, simply because due
3616 * to priority we are exposing a smaller subset of
3617 * memory to reclaim from. Consider this as a longer
3618 * term TODO.
3620 /* If excess == 0, no tree ops */
3621 __mem_cgroup_insert_exceeded(mz->mem, mz, mctz, excess);
3622 spin_unlock(&mctz->lock);
3623 css_put(&mz->mem->css);
3624 loop++;
3626 * Could not reclaim anything and there are no more
3627 * mem cgroups to try or we seem to be looping without
3628 * reclaiming anything.
3630 if (!nr_reclaimed &&
3631 (next_mz == NULL ||
3632 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3633 break;
3634 } while (!nr_reclaimed);
3635 if (next_mz)
3636 css_put(&next_mz->mem->css);
3637 return nr_reclaimed;
3641 * This routine traverse page_cgroup in given list and drop them all.
3642 * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
3644 static int mem_cgroup_force_empty_list(struct mem_cgroup *memcg,
3645 int node, int zid, enum lru_list lru)
3647 struct zone *zone;
3648 struct mem_cgroup_per_zone *mz;
3649 struct page_cgroup *pc, *busy;
3650 unsigned long flags, loop;
3651 struct list_head *list;
3652 int ret = 0;
3654 zone = &NODE_DATA(node)->node_zones[zid];
3655 mz = mem_cgroup_zoneinfo(memcg, node, zid);
3656 list = &mz->lists[lru];
3658 loop = MEM_CGROUP_ZSTAT(mz, lru);
3659 /* give some margin against EBUSY etc...*/
3660 loop += 256;
3661 busy = NULL;
3662 while (loop--) {
3663 struct page *page;
3665 ret = 0;
3666 spin_lock_irqsave(&zone->lru_lock, flags);
3667 if (list_empty(list)) {
3668 spin_unlock_irqrestore(&zone->lru_lock, flags);
3669 break;
3671 pc = list_entry(list->prev, struct page_cgroup, lru);
3672 if (busy == pc) {
3673 list_move(&pc->lru, list);
3674 busy = NULL;
3675 spin_unlock_irqrestore(&zone->lru_lock, flags);
3676 continue;
3678 spin_unlock_irqrestore(&zone->lru_lock, flags);
3680 page = lookup_cgroup_page(pc);
3682 ret = mem_cgroup_move_parent(page, pc, memcg, GFP_KERNEL);
3683 if (ret == -ENOMEM)
3684 break;
3686 if (ret == -EBUSY || ret == -EINVAL) {
3687 /* found lock contention or "pc" is obsolete. */
3688 busy = pc;
3689 cond_resched();
3690 } else
3691 busy = NULL;
3694 if (!ret && !list_empty(list))
3695 return -EBUSY;
3696 return ret;
3700 * make mem_cgroup's charge to be 0 if there is no task.
3701 * This enables deleting this mem_cgroup.
3703 static int mem_cgroup_force_empty(struct mem_cgroup *memcg, bool free_all)
3705 int ret;
3706 int node, zid, shrink;
3707 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
3708 struct cgroup *cgrp = memcg->css.cgroup;
3710 css_get(&memcg->css);
3712 shrink = 0;
3713 /* should free all ? */
3714 if (free_all)
3715 goto try_to_free;
3716 move_account:
3717 do {
3718 ret = -EBUSY;
3719 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
3720 goto out;
3721 ret = -EINTR;
3722 if (signal_pending(current))
3723 goto out;
3724 /* This is for making all *used* pages to be on LRU. */
3725 lru_add_drain_all();
3726 drain_all_stock_sync(memcg);
3727 ret = 0;
3728 mem_cgroup_start_move(memcg);
3729 for_each_node_state(node, N_HIGH_MEMORY) {
3730 for (zid = 0; !ret && zid < MAX_NR_ZONES; zid++) {
3731 enum lru_list l;
3732 for_each_lru(l) {
3733 ret = mem_cgroup_force_empty_list(memcg,
3734 node, zid, l);
3735 if (ret)
3736 break;
3739 if (ret)
3740 break;
3742 mem_cgroup_end_move(memcg);
3743 memcg_oom_recover(memcg);
3744 /* it seems parent cgroup doesn't have enough mem */
3745 if (ret == -ENOMEM)
3746 goto try_to_free;
3747 cond_resched();
3748 /* "ret" should also be checked to ensure all lists are empty. */
3749 } while (memcg->res.usage > 0 || ret);
3750 out:
3751 css_put(&memcg->css);
3752 return ret;
3754 try_to_free:
3755 /* returns EBUSY if there is a task or if we come here twice. */
3756 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children) || shrink) {
3757 ret = -EBUSY;
3758 goto out;
3760 /* we call try-to-free pages for make this cgroup empty */
3761 lru_add_drain_all();
3762 /* try to free all pages in this cgroup */
3763 shrink = 1;
3764 while (nr_retries && memcg->res.usage > 0) {
3765 int progress;
3767 if (signal_pending(current)) {
3768 ret = -EINTR;
3769 goto out;
3771 progress = try_to_free_mem_cgroup_pages(memcg, GFP_KERNEL,
3772 false);
3773 if (!progress) {
3774 nr_retries--;
3775 /* maybe some writeback is necessary */
3776 congestion_wait(BLK_RW_ASYNC, HZ/10);
3780 lru_add_drain();
3781 /* try move_account...there may be some *locked* pages. */
3782 goto move_account;
3785 int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
3787 return mem_cgroup_force_empty(mem_cgroup_from_cont(cont), true);
3791 static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
3793 return mem_cgroup_from_cont(cont)->use_hierarchy;
3796 static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
3797 u64 val)
3799 int retval = 0;
3800 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
3801 struct cgroup *parent = cont->parent;
3802 struct mem_cgroup *parent_memcg = NULL;
3804 if (parent)
3805 parent_memcg = mem_cgroup_from_cont(parent);
3807 cgroup_lock();
3809 * If parent's use_hierarchy is set, we can't make any modifications
3810 * in the child subtrees. If it is unset, then the change can
3811 * occur, provided the current cgroup has no children.
3813 * For the root cgroup, parent_mem is NULL, we allow value to be
3814 * set if there are no children.
3816 if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
3817 (val == 1 || val == 0)) {
3818 if (list_empty(&cont->children))
3819 memcg->use_hierarchy = val;
3820 else
3821 retval = -EBUSY;
3822 } else
3823 retval = -EINVAL;
3824 cgroup_unlock();
3826 return retval;
3830 static unsigned long mem_cgroup_recursive_stat(struct mem_cgroup *memcg,
3831 enum mem_cgroup_stat_index idx)
3833 struct mem_cgroup *iter;
3834 long val = 0;
3836 /* Per-cpu values can be negative, use a signed accumulator */
3837 for_each_mem_cgroup_tree(iter, memcg)
3838 val += mem_cgroup_read_stat(iter, idx);
3840 if (val < 0) /* race ? */
3841 val = 0;
3842 return val;
3845 static inline u64 mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
3847 u64 val;
3849 if (!mem_cgroup_is_root(memcg)) {
3850 if (!swap)
3851 return res_counter_read_u64(&memcg->res, RES_USAGE);
3852 else
3853 return res_counter_read_u64(&memcg->memsw, RES_USAGE);
3856 val = mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_CACHE);
3857 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_RSS);
3859 if (swap)
3860 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_SWAPOUT);
3862 return val << PAGE_SHIFT;
3865 static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft)
3867 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
3868 u64 val;
3869 int type, name;
3871 type = MEMFILE_TYPE(cft->private);
3872 name = MEMFILE_ATTR(cft->private);
3873 switch (type) {
3874 case _MEM:
3875 if (name == RES_USAGE)
3876 val = mem_cgroup_usage(memcg, false);
3877 else
3878 val = res_counter_read_u64(&memcg->res, name);
3879 break;
3880 case _MEMSWAP:
3881 if (name == RES_USAGE)
3882 val = mem_cgroup_usage(memcg, true);
3883 else
3884 val = res_counter_read_u64(&memcg->memsw, name);
3885 break;
3886 default:
3887 BUG();
3888 break;
3890 return val;
3893 * The user of this function is...
3894 * RES_LIMIT.
3896 static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
3897 const char *buffer)
3899 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
3900 int type, name;
3901 unsigned long long val;
3902 int ret;
3904 type = MEMFILE_TYPE(cft->private);
3905 name = MEMFILE_ATTR(cft->private);
3906 switch (name) {
3907 case RES_LIMIT:
3908 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3909 ret = -EINVAL;
3910 break;
3912 /* This function does all necessary parse...reuse it */
3913 ret = res_counter_memparse_write_strategy(buffer, &val);
3914 if (ret)
3915 break;
3916 if (type == _MEM)
3917 ret = mem_cgroup_resize_limit(memcg, val);
3918 else
3919 ret = mem_cgroup_resize_memsw_limit(memcg, val);
3920 break;
3921 case RES_SOFT_LIMIT:
3922 ret = res_counter_memparse_write_strategy(buffer, &val);
3923 if (ret)
3924 break;
3926 * For memsw, soft limits are hard to implement in terms
3927 * of semantics, for now, we support soft limits for
3928 * control without swap
3930 if (type == _MEM)
3931 ret = res_counter_set_soft_limit(&memcg->res, val);
3932 else
3933 ret = -EINVAL;
3934 break;
3935 default:
3936 ret = -EINVAL; /* should be BUG() ? */
3937 break;
3939 return ret;
3942 static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
3943 unsigned long long *mem_limit, unsigned long long *memsw_limit)
3945 struct cgroup *cgroup;
3946 unsigned long long min_limit, min_memsw_limit, tmp;
3948 min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3949 min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3950 cgroup = memcg->css.cgroup;
3951 if (!memcg->use_hierarchy)
3952 goto out;
3954 while (cgroup->parent) {
3955 cgroup = cgroup->parent;
3956 memcg = mem_cgroup_from_cont(cgroup);
3957 if (!memcg->use_hierarchy)
3958 break;
3959 tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
3960 min_limit = min(min_limit, tmp);
3961 tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3962 min_memsw_limit = min(min_memsw_limit, tmp);
3964 out:
3965 *mem_limit = min_limit;
3966 *memsw_limit = min_memsw_limit;
3967 return;
3970 static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
3972 struct mem_cgroup *memcg;
3973 int type, name;
3975 memcg = mem_cgroup_from_cont(cont);
3976 type = MEMFILE_TYPE(event);
3977 name = MEMFILE_ATTR(event);
3978 switch (name) {
3979 case RES_MAX_USAGE:
3980 if (type == _MEM)
3981 res_counter_reset_max(&memcg->res);
3982 else
3983 res_counter_reset_max(&memcg->memsw);
3984 break;
3985 case RES_FAILCNT:
3986 if (type == _MEM)
3987 res_counter_reset_failcnt(&memcg->res);
3988 else
3989 res_counter_reset_failcnt(&memcg->memsw);
3990 break;
3993 return 0;
3996 static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp,
3997 struct cftype *cft)
3999 return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate;
4002 #ifdef CONFIG_MMU
4003 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
4004 struct cftype *cft, u64 val)
4006 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4008 if (val >= (1 << NR_MOVE_TYPE))
4009 return -EINVAL;
4011 * We check this value several times in both in can_attach() and
4012 * attach(), so we need cgroup lock to prevent this value from being
4013 * inconsistent.
4015 cgroup_lock();
4016 memcg->move_charge_at_immigrate = val;
4017 cgroup_unlock();
4019 return 0;
4021 #else
4022 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
4023 struct cftype *cft, u64 val)
4025 return -ENOSYS;
4027 #endif
4030 /* For read statistics */
4031 enum {
4032 MCS_CACHE,
4033 MCS_RSS,
4034 MCS_FILE_MAPPED,
4035 MCS_PGPGIN,
4036 MCS_PGPGOUT,
4037 MCS_SWAP,
4038 MCS_PGFAULT,
4039 MCS_PGMAJFAULT,
4040 MCS_INACTIVE_ANON,
4041 MCS_ACTIVE_ANON,
4042 MCS_INACTIVE_FILE,
4043 MCS_ACTIVE_FILE,
4044 MCS_UNEVICTABLE,
4045 NR_MCS_STAT,
4048 struct mcs_total_stat {
4049 s64 stat[NR_MCS_STAT];
4052 struct {
4053 char *local_name;
4054 char *total_name;
4055 } memcg_stat_strings[NR_MCS_STAT] = {
4056 {"cache", "total_cache"},
4057 {"rss", "total_rss"},
4058 {"mapped_file", "total_mapped_file"},
4059 {"pgpgin", "total_pgpgin"},
4060 {"pgpgout", "total_pgpgout"},
4061 {"swap", "total_swap"},
4062 {"pgfault", "total_pgfault"},
4063 {"pgmajfault", "total_pgmajfault"},
4064 {"inactive_anon", "total_inactive_anon"},
4065 {"active_anon", "total_active_anon"},
4066 {"inactive_file", "total_inactive_file"},
4067 {"active_file", "total_active_file"},
4068 {"unevictable", "total_unevictable"}
4072 static void
4073 mem_cgroup_get_local_stat(struct mem_cgroup *memcg, struct mcs_total_stat *s)
4075 s64 val;
4077 /* per cpu stat */
4078 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_CACHE);
4079 s->stat[MCS_CACHE] += val * PAGE_SIZE;
4080 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_RSS);
4081 s->stat[MCS_RSS] += val * PAGE_SIZE;
4082 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_FILE_MAPPED);
4083 s->stat[MCS_FILE_MAPPED] += val * PAGE_SIZE;
4084 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGPGIN);
4085 s->stat[MCS_PGPGIN] += val;
4086 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGPGOUT);
4087 s->stat[MCS_PGPGOUT] += val;
4088 if (do_swap_account) {
4089 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_SWAPOUT);
4090 s->stat[MCS_SWAP] += val * PAGE_SIZE;
4092 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGFAULT);
4093 s->stat[MCS_PGFAULT] += val;
4094 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGMAJFAULT);
4095 s->stat[MCS_PGMAJFAULT] += val;
4097 /* per zone stat */
4098 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_INACTIVE_ANON));
4099 s->stat[MCS_INACTIVE_ANON] += val * PAGE_SIZE;
4100 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_ACTIVE_ANON));
4101 s->stat[MCS_ACTIVE_ANON] += val * PAGE_SIZE;
4102 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_INACTIVE_FILE));
4103 s->stat[MCS_INACTIVE_FILE] += val * PAGE_SIZE;
4104 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_ACTIVE_FILE));
4105 s->stat[MCS_ACTIVE_FILE] += val * PAGE_SIZE;
4106 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_UNEVICTABLE));
4107 s->stat[MCS_UNEVICTABLE] += val * PAGE_SIZE;
4110 static void
4111 mem_cgroup_get_total_stat(struct mem_cgroup *memcg, struct mcs_total_stat *s)
4113 struct mem_cgroup *iter;
4115 for_each_mem_cgroup_tree(iter, memcg)
4116 mem_cgroup_get_local_stat(iter, s);
4119 #ifdef CONFIG_NUMA
4120 static int mem_control_numa_stat_show(struct seq_file *m, void *arg)
4122 int nid;
4123 unsigned long total_nr, file_nr, anon_nr, unevictable_nr;
4124 unsigned long node_nr;
4125 struct cgroup *cont = m->private;
4126 struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
4128 total_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL);
4129 seq_printf(m, "total=%lu", total_nr);
4130 for_each_node_state(nid, N_HIGH_MEMORY) {
4131 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid, LRU_ALL);
4132 seq_printf(m, " N%d=%lu", nid, node_nr);
4134 seq_putc(m, '\n');
4136 file_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL_FILE);
4137 seq_printf(m, "file=%lu", file_nr);
4138 for_each_node_state(nid, N_HIGH_MEMORY) {
4139 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4140 LRU_ALL_FILE);
4141 seq_printf(m, " N%d=%lu", nid, node_nr);
4143 seq_putc(m, '\n');
4145 anon_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL_ANON);
4146 seq_printf(m, "anon=%lu", anon_nr);
4147 for_each_node_state(nid, N_HIGH_MEMORY) {
4148 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4149 LRU_ALL_ANON);
4150 seq_printf(m, " N%d=%lu", nid, node_nr);
4152 seq_putc(m, '\n');
4154 unevictable_nr = mem_cgroup_nr_lru_pages(mem_cont, BIT(LRU_UNEVICTABLE));
4155 seq_printf(m, "unevictable=%lu", unevictable_nr);
4156 for_each_node_state(nid, N_HIGH_MEMORY) {
4157 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4158 BIT(LRU_UNEVICTABLE));
4159 seq_printf(m, " N%d=%lu", nid, node_nr);
4161 seq_putc(m, '\n');
4162 return 0;
4164 #endif /* CONFIG_NUMA */
4166 static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft,
4167 struct cgroup_map_cb *cb)
4169 struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
4170 struct mcs_total_stat mystat;
4171 int i;
4173 memset(&mystat, 0, sizeof(mystat));
4174 mem_cgroup_get_local_stat(mem_cont, &mystat);
4177 for (i = 0; i < NR_MCS_STAT; i++) {
4178 if (i == MCS_SWAP && !do_swap_account)
4179 continue;
4180 cb->fill(cb, memcg_stat_strings[i].local_name, mystat.stat[i]);
4183 /* Hierarchical information */
4185 unsigned long long limit, memsw_limit;
4186 memcg_get_hierarchical_limit(mem_cont, &limit, &memsw_limit);
4187 cb->fill(cb, "hierarchical_memory_limit", limit);
4188 if (do_swap_account)
4189 cb->fill(cb, "hierarchical_memsw_limit", memsw_limit);
4192 memset(&mystat, 0, sizeof(mystat));
4193 mem_cgroup_get_total_stat(mem_cont, &mystat);
4194 for (i = 0; i < NR_MCS_STAT; i++) {
4195 if (i == MCS_SWAP && !do_swap_account)
4196 continue;
4197 cb->fill(cb, memcg_stat_strings[i].total_name, mystat.stat[i]);
4200 #ifdef CONFIG_DEBUG_VM
4202 int nid, zid;
4203 struct mem_cgroup_per_zone *mz;
4204 unsigned long recent_rotated[2] = {0, 0};
4205 unsigned long recent_scanned[2] = {0, 0};
4207 for_each_online_node(nid)
4208 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
4209 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
4211 recent_rotated[0] +=
4212 mz->reclaim_stat.recent_rotated[0];
4213 recent_rotated[1] +=
4214 mz->reclaim_stat.recent_rotated[1];
4215 recent_scanned[0] +=
4216 mz->reclaim_stat.recent_scanned[0];
4217 recent_scanned[1] +=
4218 mz->reclaim_stat.recent_scanned[1];
4220 cb->fill(cb, "recent_rotated_anon", recent_rotated[0]);
4221 cb->fill(cb, "recent_rotated_file", recent_rotated[1]);
4222 cb->fill(cb, "recent_scanned_anon", recent_scanned[0]);
4223 cb->fill(cb, "recent_scanned_file", recent_scanned[1]);
4225 #endif
4227 return 0;
4230 static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
4232 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4234 return mem_cgroup_swappiness(memcg);
4237 static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
4238 u64 val)
4240 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4241 struct mem_cgroup *parent;
4243 if (val > 100)
4244 return -EINVAL;
4246 if (cgrp->parent == NULL)
4247 return -EINVAL;
4249 parent = mem_cgroup_from_cont(cgrp->parent);
4251 cgroup_lock();
4253 /* If under hierarchy, only empty-root can set this value */
4254 if ((parent->use_hierarchy) ||
4255 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
4256 cgroup_unlock();
4257 return -EINVAL;
4260 memcg->swappiness = val;
4262 cgroup_unlock();
4264 return 0;
4267 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4269 struct mem_cgroup_threshold_ary *t;
4270 u64 usage;
4271 int i;
4273 rcu_read_lock();
4274 if (!swap)
4275 t = rcu_dereference(memcg->thresholds.primary);
4276 else
4277 t = rcu_dereference(memcg->memsw_thresholds.primary);
4279 if (!t)
4280 goto unlock;
4282 usage = mem_cgroup_usage(memcg, swap);
4285 * current_threshold points to threshold just below usage.
4286 * If it's not true, a threshold was crossed after last
4287 * call of __mem_cgroup_threshold().
4289 i = t->current_threshold;
4292 * Iterate backward over array of thresholds starting from
4293 * current_threshold and check if a threshold is crossed.
4294 * If none of thresholds below usage is crossed, we read
4295 * only one element of the array here.
4297 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4298 eventfd_signal(t->entries[i].eventfd, 1);
4300 /* i = current_threshold + 1 */
4301 i++;
4304 * Iterate forward over array of thresholds starting from
4305 * current_threshold+1 and check if a threshold is crossed.
4306 * If none of thresholds above usage is crossed, we read
4307 * only one element of the array here.
4309 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4310 eventfd_signal(t->entries[i].eventfd, 1);
4312 /* Update current_threshold */
4313 t->current_threshold = i - 1;
4314 unlock:
4315 rcu_read_unlock();
4318 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4320 while (memcg) {
4321 __mem_cgroup_threshold(memcg, false);
4322 if (do_swap_account)
4323 __mem_cgroup_threshold(memcg, true);
4325 memcg = parent_mem_cgroup(memcg);
4329 static int compare_thresholds(const void *a, const void *b)
4331 const struct mem_cgroup_threshold *_a = a;
4332 const struct mem_cgroup_threshold *_b = b;
4334 return _a->threshold - _b->threshold;
4337 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
4339 struct mem_cgroup_eventfd_list *ev;
4341 list_for_each_entry(ev, &memcg->oom_notify, list)
4342 eventfd_signal(ev->eventfd, 1);
4343 return 0;
4346 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
4348 struct mem_cgroup *iter;
4350 for_each_mem_cgroup_tree(iter, memcg)
4351 mem_cgroup_oom_notify_cb(iter);
4354 static int mem_cgroup_usage_register_event(struct cgroup *cgrp,
4355 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
4357 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4358 struct mem_cgroup_thresholds *thresholds;
4359 struct mem_cgroup_threshold_ary *new;
4360 int type = MEMFILE_TYPE(cft->private);
4361 u64 threshold, usage;
4362 int i, size, ret;
4364 ret = res_counter_memparse_write_strategy(args, &threshold);
4365 if (ret)
4366 return ret;
4368 mutex_lock(&memcg->thresholds_lock);
4370 if (type == _MEM)
4371 thresholds = &memcg->thresholds;
4372 else if (type == _MEMSWAP)
4373 thresholds = &memcg->memsw_thresholds;
4374 else
4375 BUG();
4377 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
4379 /* Check if a threshold crossed before adding a new one */
4380 if (thresholds->primary)
4381 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4383 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
4385 /* Allocate memory for new array of thresholds */
4386 new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
4387 GFP_KERNEL);
4388 if (!new) {
4389 ret = -ENOMEM;
4390 goto unlock;
4392 new->size = size;
4394 /* Copy thresholds (if any) to new array */
4395 if (thresholds->primary) {
4396 memcpy(new->entries, thresholds->primary->entries, (size - 1) *
4397 sizeof(struct mem_cgroup_threshold));
4400 /* Add new threshold */
4401 new->entries[size - 1].eventfd = eventfd;
4402 new->entries[size - 1].threshold = threshold;
4404 /* Sort thresholds. Registering of new threshold isn't time-critical */
4405 sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
4406 compare_thresholds, NULL);
4408 /* Find current threshold */
4409 new->current_threshold = -1;
4410 for (i = 0; i < size; i++) {
4411 if (new->entries[i].threshold < usage) {
4413 * new->current_threshold will not be used until
4414 * rcu_assign_pointer(), so it's safe to increment
4415 * it here.
4417 ++new->current_threshold;
4421 /* Free old spare buffer and save old primary buffer as spare */
4422 kfree(thresholds->spare);
4423 thresholds->spare = thresholds->primary;
4425 rcu_assign_pointer(thresholds->primary, new);
4427 /* To be sure that nobody uses thresholds */
4428 synchronize_rcu();
4430 unlock:
4431 mutex_unlock(&memcg->thresholds_lock);
4433 return ret;
4436 static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,
4437 struct cftype *cft, struct eventfd_ctx *eventfd)
4439 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4440 struct mem_cgroup_thresholds *thresholds;
4441 struct mem_cgroup_threshold_ary *new;
4442 int type = MEMFILE_TYPE(cft->private);
4443 u64 usage;
4444 int i, j, size;
4446 mutex_lock(&memcg->thresholds_lock);
4447 if (type == _MEM)
4448 thresholds = &memcg->thresholds;
4449 else if (type == _MEMSWAP)
4450 thresholds = &memcg->memsw_thresholds;
4451 else
4452 BUG();
4455 * Something went wrong if we trying to unregister a threshold
4456 * if we don't have thresholds
4458 BUG_ON(!thresholds);
4460 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
4462 /* Check if a threshold crossed before removing */
4463 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4465 /* Calculate new number of threshold */
4466 size = 0;
4467 for (i = 0; i < thresholds->primary->size; i++) {
4468 if (thresholds->primary->entries[i].eventfd != eventfd)
4469 size++;
4472 new = thresholds->spare;
4474 /* Set thresholds array to NULL if we don't have thresholds */
4475 if (!size) {
4476 kfree(new);
4477 new = NULL;
4478 goto swap_buffers;
4481 new->size = size;
4483 /* Copy thresholds and find current threshold */
4484 new->current_threshold = -1;
4485 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4486 if (thresholds->primary->entries[i].eventfd == eventfd)
4487 continue;
4489 new->entries[j] = thresholds->primary->entries[i];
4490 if (new->entries[j].threshold < usage) {
4492 * new->current_threshold will not be used
4493 * until rcu_assign_pointer(), so it's safe to increment
4494 * it here.
4496 ++new->current_threshold;
4498 j++;
4501 swap_buffers:
4502 /* Swap primary and spare array */
4503 thresholds->spare = thresholds->primary;
4504 rcu_assign_pointer(thresholds->primary, new);
4506 /* To be sure that nobody uses thresholds */
4507 synchronize_rcu();
4509 mutex_unlock(&memcg->thresholds_lock);
4512 static int mem_cgroup_oom_register_event(struct cgroup *cgrp,
4513 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
4515 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4516 struct mem_cgroup_eventfd_list *event;
4517 int type = MEMFILE_TYPE(cft->private);
4519 BUG_ON(type != _OOM_TYPE);
4520 event = kmalloc(sizeof(*event), GFP_KERNEL);
4521 if (!event)
4522 return -ENOMEM;
4524 spin_lock(&memcg_oom_lock);
4526 event->eventfd = eventfd;
4527 list_add(&event->list, &memcg->oom_notify);
4529 /* already in OOM ? */
4530 if (atomic_read(&memcg->under_oom))
4531 eventfd_signal(eventfd, 1);
4532 spin_unlock(&memcg_oom_lock);
4534 return 0;
4537 static void mem_cgroup_oom_unregister_event(struct cgroup *cgrp,
4538 struct cftype *cft, struct eventfd_ctx *eventfd)
4540 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4541 struct mem_cgroup_eventfd_list *ev, *tmp;
4542 int type = MEMFILE_TYPE(cft->private);
4544 BUG_ON(type != _OOM_TYPE);
4546 spin_lock(&memcg_oom_lock);
4548 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
4549 if (ev->eventfd == eventfd) {
4550 list_del(&ev->list);
4551 kfree(ev);
4555 spin_unlock(&memcg_oom_lock);
4558 static int mem_cgroup_oom_control_read(struct cgroup *cgrp,
4559 struct cftype *cft, struct cgroup_map_cb *cb)
4561 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4563 cb->fill(cb, "oom_kill_disable", memcg->oom_kill_disable);
4565 if (atomic_read(&memcg->under_oom))
4566 cb->fill(cb, "under_oom", 1);
4567 else
4568 cb->fill(cb, "under_oom", 0);
4569 return 0;
4572 static int mem_cgroup_oom_control_write(struct cgroup *cgrp,
4573 struct cftype *cft, u64 val)
4575 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4576 struct mem_cgroup *parent;
4578 /* cannot set to root cgroup and only 0 and 1 are allowed */
4579 if (!cgrp->parent || !((val == 0) || (val == 1)))
4580 return -EINVAL;
4582 parent = mem_cgroup_from_cont(cgrp->parent);
4584 cgroup_lock();
4585 /* oom-kill-disable is a flag for subhierarchy. */
4586 if ((parent->use_hierarchy) ||
4587 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
4588 cgroup_unlock();
4589 return -EINVAL;
4591 memcg->oom_kill_disable = val;
4592 if (!val)
4593 memcg_oom_recover(memcg);
4594 cgroup_unlock();
4595 return 0;
4598 #ifdef CONFIG_NUMA
4599 static const struct file_operations mem_control_numa_stat_file_operations = {
4600 .read = seq_read,
4601 .llseek = seq_lseek,
4602 .release = single_release,
4605 static int mem_control_numa_stat_open(struct inode *unused, struct file *file)
4607 struct cgroup *cont = file->f_dentry->d_parent->d_fsdata;
4609 file->f_op = &mem_control_numa_stat_file_operations;
4610 return single_open(file, mem_control_numa_stat_show, cont);
4612 #endif /* CONFIG_NUMA */
4614 static struct cftype mem_cgroup_files[] = {
4616 .name = "usage_in_bytes",
4617 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
4618 .read_u64 = mem_cgroup_read,
4619 .register_event = mem_cgroup_usage_register_event,
4620 .unregister_event = mem_cgroup_usage_unregister_event,
4623 .name = "max_usage_in_bytes",
4624 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
4625 .trigger = mem_cgroup_reset,
4626 .read_u64 = mem_cgroup_read,
4629 .name = "limit_in_bytes",
4630 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
4631 .write_string = mem_cgroup_write,
4632 .read_u64 = mem_cgroup_read,
4635 .name = "soft_limit_in_bytes",
4636 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
4637 .write_string = mem_cgroup_write,
4638 .read_u64 = mem_cgroup_read,
4641 .name = "failcnt",
4642 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
4643 .trigger = mem_cgroup_reset,
4644 .read_u64 = mem_cgroup_read,
4647 .name = "stat",
4648 .read_map = mem_control_stat_show,
4651 .name = "force_empty",
4652 .trigger = mem_cgroup_force_empty_write,
4655 .name = "use_hierarchy",
4656 .write_u64 = mem_cgroup_hierarchy_write,
4657 .read_u64 = mem_cgroup_hierarchy_read,
4660 .name = "swappiness",
4661 .read_u64 = mem_cgroup_swappiness_read,
4662 .write_u64 = mem_cgroup_swappiness_write,
4665 .name = "move_charge_at_immigrate",
4666 .read_u64 = mem_cgroup_move_charge_read,
4667 .write_u64 = mem_cgroup_move_charge_write,
4670 .name = "oom_control",
4671 .read_map = mem_cgroup_oom_control_read,
4672 .write_u64 = mem_cgroup_oom_control_write,
4673 .register_event = mem_cgroup_oom_register_event,
4674 .unregister_event = mem_cgroup_oom_unregister_event,
4675 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
4677 #ifdef CONFIG_NUMA
4679 .name = "numa_stat",
4680 .open = mem_control_numa_stat_open,
4681 .mode = S_IRUGO,
4683 #endif
4686 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4687 static struct cftype memsw_cgroup_files[] = {
4689 .name = "memsw.usage_in_bytes",
4690 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
4691 .read_u64 = mem_cgroup_read,
4692 .register_event = mem_cgroup_usage_register_event,
4693 .unregister_event = mem_cgroup_usage_unregister_event,
4696 .name = "memsw.max_usage_in_bytes",
4697 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
4698 .trigger = mem_cgroup_reset,
4699 .read_u64 = mem_cgroup_read,
4702 .name = "memsw.limit_in_bytes",
4703 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
4704 .write_string = mem_cgroup_write,
4705 .read_u64 = mem_cgroup_read,
4708 .name = "memsw.failcnt",
4709 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
4710 .trigger = mem_cgroup_reset,
4711 .read_u64 = mem_cgroup_read,
4715 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
4717 if (!do_swap_account)
4718 return 0;
4719 return cgroup_add_files(cont, ss, memsw_cgroup_files,
4720 ARRAY_SIZE(memsw_cgroup_files));
4722 #else
4723 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
4725 return 0;
4727 #endif
4729 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
4731 struct mem_cgroup_per_node *pn;
4732 struct mem_cgroup_per_zone *mz;
4733 enum lru_list l;
4734 int zone, tmp = node;
4736 * This routine is called against possible nodes.
4737 * But it's BUG to call kmalloc() against offline node.
4739 * TODO: this routine can waste much memory for nodes which will
4740 * never be onlined. It's better to use memory hotplug callback
4741 * function.
4743 if (!node_state(node, N_NORMAL_MEMORY))
4744 tmp = -1;
4745 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
4746 if (!pn)
4747 return 1;
4749 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4750 mz = &pn->zoneinfo[zone];
4751 for_each_lru(l)
4752 INIT_LIST_HEAD(&mz->lists[l]);
4753 mz->usage_in_excess = 0;
4754 mz->on_tree = false;
4755 mz->mem = memcg;
4757 memcg->info.nodeinfo[node] = pn;
4758 return 0;
4761 static void free_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
4763 kfree(memcg->info.nodeinfo[node]);
4766 static struct mem_cgroup *mem_cgroup_alloc(void)
4768 struct mem_cgroup *mem;
4769 int size = sizeof(struct mem_cgroup);
4771 /* Can be very big if MAX_NUMNODES is very big */
4772 if (size < PAGE_SIZE)
4773 mem = kzalloc(size, GFP_KERNEL);
4774 else
4775 mem = vzalloc(size);
4777 if (!mem)
4778 return NULL;
4780 mem->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
4781 if (!mem->stat)
4782 goto out_free;
4783 spin_lock_init(&mem->pcp_counter_lock);
4784 return mem;
4786 out_free:
4787 if (size < PAGE_SIZE)
4788 kfree(mem);
4789 else
4790 vfree(mem);
4791 return NULL;
4795 * At destroying mem_cgroup, references from swap_cgroup can remain.
4796 * (scanning all at force_empty is too costly...)
4798 * Instead of clearing all references at force_empty, we remember
4799 * the number of reference from swap_cgroup and free mem_cgroup when
4800 * it goes down to 0.
4802 * Removal of cgroup itself succeeds regardless of refs from swap.
4805 static void __mem_cgroup_free(struct mem_cgroup *memcg)
4807 int node;
4809 mem_cgroup_remove_from_trees(memcg);
4810 free_css_id(&mem_cgroup_subsys, &memcg->css);
4812 for_each_node_state(node, N_POSSIBLE)
4813 free_mem_cgroup_per_zone_info(memcg, node);
4815 free_percpu(memcg->stat);
4816 if (sizeof(struct mem_cgroup) < PAGE_SIZE)
4817 kfree(memcg);
4818 else
4819 vfree(memcg);
4822 static void mem_cgroup_get(struct mem_cgroup *memcg)
4824 atomic_inc(&memcg->refcnt);
4827 static void __mem_cgroup_put(struct mem_cgroup *memcg, int count)
4829 if (atomic_sub_and_test(count, &memcg->refcnt)) {
4830 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
4831 __mem_cgroup_free(memcg);
4832 if (parent)
4833 mem_cgroup_put(parent);
4837 static void mem_cgroup_put(struct mem_cgroup *memcg)
4839 __mem_cgroup_put(memcg, 1);
4843 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
4845 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg)
4847 if (!memcg->res.parent)
4848 return NULL;
4849 return mem_cgroup_from_res_counter(memcg->res.parent, res);
4852 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4853 static void __init enable_swap_cgroup(void)
4855 if (!mem_cgroup_disabled() && really_do_swap_account)
4856 do_swap_account = 1;
4858 #else
4859 static void __init enable_swap_cgroup(void)
4862 #endif
4864 static int mem_cgroup_soft_limit_tree_init(void)
4866 struct mem_cgroup_tree_per_node *rtpn;
4867 struct mem_cgroup_tree_per_zone *rtpz;
4868 int tmp, node, zone;
4870 for_each_node_state(node, N_POSSIBLE) {
4871 tmp = node;
4872 if (!node_state(node, N_NORMAL_MEMORY))
4873 tmp = -1;
4874 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
4875 if (!rtpn)
4876 return 1;
4878 soft_limit_tree.rb_tree_per_node[node] = rtpn;
4880 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4881 rtpz = &rtpn->rb_tree_per_zone[zone];
4882 rtpz->rb_root = RB_ROOT;
4883 spin_lock_init(&rtpz->lock);
4886 return 0;
4889 static struct cgroup_subsys_state * __ref
4890 mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
4892 struct mem_cgroup *memcg, *parent;
4893 long error = -ENOMEM;
4894 int node;
4896 memcg = mem_cgroup_alloc();
4897 if (!memcg)
4898 return ERR_PTR(error);
4900 for_each_node_state(node, N_POSSIBLE)
4901 if (alloc_mem_cgroup_per_zone_info(memcg, node))
4902 goto free_out;
4904 /* root ? */
4905 if (cont->parent == NULL) {
4906 int cpu;
4907 enable_swap_cgroup();
4908 parent = NULL;
4909 root_mem_cgroup = memcg;
4910 if (mem_cgroup_soft_limit_tree_init())
4911 goto free_out;
4912 for_each_possible_cpu(cpu) {
4913 struct memcg_stock_pcp *stock =
4914 &per_cpu(memcg_stock, cpu);
4915 INIT_WORK(&stock->work, drain_local_stock);
4917 hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
4918 } else {
4919 parent = mem_cgroup_from_cont(cont->parent);
4920 memcg->use_hierarchy = parent->use_hierarchy;
4921 memcg->oom_kill_disable = parent->oom_kill_disable;
4924 if (parent && parent->use_hierarchy) {
4925 res_counter_init(&memcg->res, &parent->res);
4926 res_counter_init(&memcg->memsw, &parent->memsw);
4928 * We increment refcnt of the parent to ensure that we can
4929 * safely access it on res_counter_charge/uncharge.
4930 * This refcnt will be decremented when freeing this
4931 * mem_cgroup(see mem_cgroup_put).
4933 mem_cgroup_get(parent);
4934 } else {
4935 res_counter_init(&memcg->res, NULL);
4936 res_counter_init(&memcg->memsw, NULL);
4938 memcg->last_scanned_child = 0;
4939 memcg->last_scanned_node = MAX_NUMNODES;
4940 INIT_LIST_HEAD(&memcg->oom_notify);
4942 if (parent)
4943 memcg->swappiness = mem_cgroup_swappiness(parent);
4944 atomic_set(&memcg->refcnt, 1);
4945 memcg->move_charge_at_immigrate = 0;
4946 mutex_init(&memcg->thresholds_lock);
4947 return &memcg->css;
4948 free_out:
4949 __mem_cgroup_free(memcg);
4950 root_mem_cgroup = NULL;
4951 return ERR_PTR(error);
4954 static int mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
4955 struct cgroup *cont)
4957 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
4959 return mem_cgroup_force_empty(memcg, false);
4962 static void mem_cgroup_destroy(struct cgroup_subsys *ss,
4963 struct cgroup *cont)
4965 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
4967 mem_cgroup_put(memcg);
4970 static int mem_cgroup_populate(struct cgroup_subsys *ss,
4971 struct cgroup *cont)
4973 int ret;
4975 ret = cgroup_add_files(cont, ss, mem_cgroup_files,
4976 ARRAY_SIZE(mem_cgroup_files));
4978 if (!ret)
4979 ret = register_memsw_files(cont, ss);
4980 return ret;
4983 #ifdef CONFIG_MMU
4984 /* Handlers for move charge at task migration. */
4985 #define PRECHARGE_COUNT_AT_ONCE 256
4986 static int mem_cgroup_do_precharge(unsigned long count)
4988 int ret = 0;
4989 int batch_count = PRECHARGE_COUNT_AT_ONCE;
4990 struct mem_cgroup *memcg = mc.to;
4992 if (mem_cgroup_is_root(memcg)) {
4993 mc.precharge += count;
4994 /* we don't need css_get for root */
4995 return ret;
4997 /* try to charge at once */
4998 if (count > 1) {
4999 struct res_counter *dummy;
5001 * "memcg" cannot be under rmdir() because we've already checked
5002 * by cgroup_lock_live_cgroup() that it is not removed and we
5003 * are still under the same cgroup_mutex. So we can postpone
5004 * css_get().
5006 if (res_counter_charge(&memcg->res, PAGE_SIZE * count, &dummy))
5007 goto one_by_one;
5008 if (do_swap_account && res_counter_charge(&memcg->memsw,
5009 PAGE_SIZE * count, &dummy)) {
5010 res_counter_uncharge(&memcg->res, PAGE_SIZE * count);
5011 goto one_by_one;
5013 mc.precharge += count;
5014 return ret;
5016 one_by_one:
5017 /* fall back to one by one charge */
5018 while (count--) {
5019 if (signal_pending(current)) {
5020 ret = -EINTR;
5021 break;
5023 if (!batch_count--) {
5024 batch_count = PRECHARGE_COUNT_AT_ONCE;
5025 cond_resched();
5027 ret = __mem_cgroup_try_charge(NULL,
5028 GFP_KERNEL, 1, &memcg, false);
5029 if (ret || !memcg)
5030 /* mem_cgroup_clear_mc() will do uncharge later */
5031 return -ENOMEM;
5032 mc.precharge++;
5034 return ret;
5038 * is_target_pte_for_mc - check a pte whether it is valid for move charge
5039 * @vma: the vma the pte to be checked belongs
5040 * @addr: the address corresponding to the pte to be checked
5041 * @ptent: the pte to be checked
5042 * @target: the pointer the target page or swap ent will be stored(can be NULL)
5044 * Returns
5045 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
5046 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5047 * move charge. if @target is not NULL, the page is stored in target->page
5048 * with extra refcnt got(Callers should handle it).
5049 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5050 * target for charge migration. if @target is not NULL, the entry is stored
5051 * in target->ent.
5053 * Called with pte lock held.
5055 union mc_target {
5056 struct page *page;
5057 swp_entry_t ent;
5060 enum mc_target_type {
5061 MC_TARGET_NONE, /* not used */
5062 MC_TARGET_PAGE,
5063 MC_TARGET_SWAP,
5066 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5067 unsigned long addr, pte_t ptent)
5069 struct page *page = vm_normal_page(vma, addr, ptent);
5071 if (!page || !page_mapped(page))
5072 return NULL;
5073 if (PageAnon(page)) {
5074 /* we don't move shared anon */
5075 if (!move_anon() || page_mapcount(page) > 2)
5076 return NULL;
5077 } else if (!move_file())
5078 /* we ignore mapcount for file pages */
5079 return NULL;
5080 if (!get_page_unless_zero(page))
5081 return NULL;
5083 return page;
5086 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5087 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5089 int usage_count;
5090 struct page *page = NULL;
5091 swp_entry_t ent = pte_to_swp_entry(ptent);
5093 if (!move_anon() || non_swap_entry(ent))
5094 return NULL;
5095 usage_count = mem_cgroup_count_swap_user(ent, &page);
5096 if (usage_count > 1) { /* we don't move shared anon */
5097 if (page)
5098 put_page(page);
5099 return NULL;
5101 if (do_swap_account)
5102 entry->val = ent.val;
5104 return page;
5107 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5108 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5110 struct page *page = NULL;
5111 struct inode *inode;
5112 struct address_space *mapping;
5113 pgoff_t pgoff;
5115 if (!vma->vm_file) /* anonymous vma */
5116 return NULL;
5117 if (!move_file())
5118 return NULL;
5120 inode = vma->vm_file->f_path.dentry->d_inode;
5121 mapping = vma->vm_file->f_mapping;
5122 if (pte_none(ptent))
5123 pgoff = linear_page_index(vma, addr);
5124 else /* pte_file(ptent) is true */
5125 pgoff = pte_to_pgoff(ptent);
5127 /* page is moved even if it's not RSS of this task(page-faulted). */
5128 page = find_get_page(mapping, pgoff);
5130 #ifdef CONFIG_SWAP
5131 /* shmem/tmpfs may report page out on swap: account for that too. */
5132 if (radix_tree_exceptional_entry(page)) {
5133 swp_entry_t swap = radix_to_swp_entry(page);
5134 if (do_swap_account)
5135 *entry = swap;
5136 page = find_get_page(&swapper_space, swap.val);
5138 #endif
5139 return page;
5142 static int is_target_pte_for_mc(struct vm_area_struct *vma,
5143 unsigned long addr, pte_t ptent, union mc_target *target)
5145 struct page *page = NULL;
5146 struct page_cgroup *pc;
5147 int ret = 0;
5148 swp_entry_t ent = { .val = 0 };
5150 if (pte_present(ptent))
5151 page = mc_handle_present_pte(vma, addr, ptent);
5152 else if (is_swap_pte(ptent))
5153 page = mc_handle_swap_pte(vma, addr, ptent, &ent);
5154 else if (pte_none(ptent) || pte_file(ptent))
5155 page = mc_handle_file_pte(vma, addr, ptent, &ent);
5157 if (!page && !ent.val)
5158 return 0;
5159 if (page) {
5160 pc = lookup_page_cgroup(page);
5162 * Do only loose check w/o page_cgroup lock.
5163 * mem_cgroup_move_account() checks the pc is valid or not under
5164 * the lock.
5166 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
5167 ret = MC_TARGET_PAGE;
5168 if (target)
5169 target->page = page;
5171 if (!ret || !target)
5172 put_page(page);
5174 /* There is a swap entry and a page doesn't exist or isn't charged */
5175 if (ent.val && !ret &&
5176 css_id(&mc.from->css) == lookup_swap_cgroup(ent)) {
5177 ret = MC_TARGET_SWAP;
5178 if (target)
5179 target->ent = ent;
5181 return ret;
5184 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
5185 unsigned long addr, unsigned long end,
5186 struct mm_walk *walk)
5188 struct vm_area_struct *vma = walk->private;
5189 pte_t *pte;
5190 spinlock_t *ptl;
5192 split_huge_page_pmd(walk->mm, pmd);
5194 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5195 for (; addr != end; pte++, addr += PAGE_SIZE)
5196 if (is_target_pte_for_mc(vma, addr, *pte, NULL))
5197 mc.precharge++; /* increment precharge temporarily */
5198 pte_unmap_unlock(pte - 1, ptl);
5199 cond_resched();
5201 return 0;
5204 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
5206 unsigned long precharge;
5207 struct vm_area_struct *vma;
5209 down_read(&mm->mmap_sem);
5210 for (vma = mm->mmap; vma; vma = vma->vm_next) {
5211 struct mm_walk mem_cgroup_count_precharge_walk = {
5212 .pmd_entry = mem_cgroup_count_precharge_pte_range,
5213 .mm = mm,
5214 .private = vma,
5216 if (is_vm_hugetlb_page(vma))
5217 continue;
5218 walk_page_range(vma->vm_start, vma->vm_end,
5219 &mem_cgroup_count_precharge_walk);
5221 up_read(&mm->mmap_sem);
5223 precharge = mc.precharge;
5224 mc.precharge = 0;
5226 return precharge;
5229 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
5231 unsigned long precharge = mem_cgroup_count_precharge(mm);
5233 VM_BUG_ON(mc.moving_task);
5234 mc.moving_task = current;
5235 return mem_cgroup_do_precharge(precharge);
5238 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5239 static void __mem_cgroup_clear_mc(void)
5241 struct mem_cgroup *from = mc.from;
5242 struct mem_cgroup *to = mc.to;
5244 /* we must uncharge all the leftover precharges from mc.to */
5245 if (mc.precharge) {
5246 __mem_cgroup_cancel_charge(mc.to, mc.precharge);
5247 mc.precharge = 0;
5250 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5251 * we must uncharge here.
5253 if (mc.moved_charge) {
5254 __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
5255 mc.moved_charge = 0;
5257 /* we must fixup refcnts and charges */
5258 if (mc.moved_swap) {
5259 /* uncharge swap account from the old cgroup */
5260 if (!mem_cgroup_is_root(mc.from))
5261 res_counter_uncharge(&mc.from->memsw,
5262 PAGE_SIZE * mc.moved_swap);
5263 __mem_cgroup_put(mc.from, mc.moved_swap);
5265 if (!mem_cgroup_is_root(mc.to)) {
5267 * we charged both to->res and to->memsw, so we should
5268 * uncharge to->res.
5270 res_counter_uncharge(&mc.to->res,
5271 PAGE_SIZE * mc.moved_swap);
5273 /* we've already done mem_cgroup_get(mc.to) */
5274 mc.moved_swap = 0;
5276 memcg_oom_recover(from);
5277 memcg_oom_recover(to);
5278 wake_up_all(&mc.waitq);
5281 static void mem_cgroup_clear_mc(void)
5283 struct mem_cgroup *from = mc.from;
5286 * we must clear moving_task before waking up waiters at the end of
5287 * task migration.
5289 mc.moving_task = NULL;
5290 __mem_cgroup_clear_mc();
5291 spin_lock(&mc.lock);
5292 mc.from = NULL;
5293 mc.to = NULL;
5294 spin_unlock(&mc.lock);
5295 mem_cgroup_end_move(from);
5298 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
5299 struct cgroup *cgroup,
5300 struct task_struct *p)
5302 int ret = 0;
5303 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgroup);
5305 if (memcg->move_charge_at_immigrate) {
5306 struct mm_struct *mm;
5307 struct mem_cgroup *from = mem_cgroup_from_task(p);
5309 VM_BUG_ON(from == memcg);
5311 mm = get_task_mm(p);
5312 if (!mm)
5313 return 0;
5314 /* We move charges only when we move a owner of the mm */
5315 if (mm->owner == p) {
5316 VM_BUG_ON(mc.from);
5317 VM_BUG_ON(mc.to);
5318 VM_BUG_ON(mc.precharge);
5319 VM_BUG_ON(mc.moved_charge);
5320 VM_BUG_ON(mc.moved_swap);
5321 mem_cgroup_start_move(from);
5322 spin_lock(&mc.lock);
5323 mc.from = from;
5324 mc.to = memcg;
5325 spin_unlock(&mc.lock);
5326 /* We set mc.moving_task later */
5328 ret = mem_cgroup_precharge_mc(mm);
5329 if (ret)
5330 mem_cgroup_clear_mc();
5332 mmput(mm);
5334 return ret;
5337 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
5338 struct cgroup *cgroup,
5339 struct task_struct *p)
5341 mem_cgroup_clear_mc();
5344 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
5345 unsigned long addr, unsigned long end,
5346 struct mm_walk *walk)
5348 int ret = 0;
5349 struct vm_area_struct *vma = walk->private;
5350 pte_t *pte;
5351 spinlock_t *ptl;
5353 split_huge_page_pmd(walk->mm, pmd);
5354 retry:
5355 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5356 for (; addr != end; addr += PAGE_SIZE) {
5357 pte_t ptent = *(pte++);
5358 union mc_target target;
5359 int type;
5360 struct page *page;
5361 struct page_cgroup *pc;
5362 swp_entry_t ent;
5364 if (!mc.precharge)
5365 break;
5367 type = is_target_pte_for_mc(vma, addr, ptent, &target);
5368 switch (type) {
5369 case MC_TARGET_PAGE:
5370 page = target.page;
5371 if (isolate_lru_page(page))
5372 goto put;
5373 pc = lookup_page_cgroup(page);
5374 if (!mem_cgroup_move_account(page, 1, pc,
5375 mc.from, mc.to, false)) {
5376 mc.precharge--;
5377 /* we uncharge from mc.from later. */
5378 mc.moved_charge++;
5380 putback_lru_page(page);
5381 put: /* is_target_pte_for_mc() gets the page */
5382 put_page(page);
5383 break;
5384 case MC_TARGET_SWAP:
5385 ent = target.ent;
5386 if (!mem_cgroup_move_swap_account(ent,
5387 mc.from, mc.to, false)) {
5388 mc.precharge--;
5389 /* we fixup refcnts and charges later. */
5390 mc.moved_swap++;
5392 break;
5393 default:
5394 break;
5397 pte_unmap_unlock(pte - 1, ptl);
5398 cond_resched();
5400 if (addr != end) {
5402 * We have consumed all precharges we got in can_attach().
5403 * We try charge one by one, but don't do any additional
5404 * charges to mc.to if we have failed in charge once in attach()
5405 * phase.
5407 ret = mem_cgroup_do_precharge(1);
5408 if (!ret)
5409 goto retry;
5412 return ret;
5415 static void mem_cgroup_move_charge(struct mm_struct *mm)
5417 struct vm_area_struct *vma;
5419 lru_add_drain_all();
5420 retry:
5421 if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
5423 * Someone who are holding the mmap_sem might be waiting in
5424 * waitq. So we cancel all extra charges, wake up all waiters,
5425 * and retry. Because we cancel precharges, we might not be able
5426 * to move enough charges, but moving charge is a best-effort
5427 * feature anyway, so it wouldn't be a big problem.
5429 __mem_cgroup_clear_mc();
5430 cond_resched();
5431 goto retry;
5433 for (vma = mm->mmap; vma; vma = vma->vm_next) {
5434 int ret;
5435 struct mm_walk mem_cgroup_move_charge_walk = {
5436 .pmd_entry = mem_cgroup_move_charge_pte_range,
5437 .mm = mm,
5438 .private = vma,
5440 if (is_vm_hugetlb_page(vma))
5441 continue;
5442 ret = walk_page_range(vma->vm_start, vma->vm_end,
5443 &mem_cgroup_move_charge_walk);
5444 if (ret)
5446 * means we have consumed all precharges and failed in
5447 * doing additional charge. Just abandon here.
5449 break;
5451 up_read(&mm->mmap_sem);
5454 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
5455 struct cgroup *cont,
5456 struct cgroup *old_cont,
5457 struct task_struct *p)
5459 struct mm_struct *mm = get_task_mm(p);
5461 if (mm) {
5462 if (mc.to)
5463 mem_cgroup_move_charge(mm);
5464 put_swap_token(mm);
5465 mmput(mm);
5467 if (mc.to)
5468 mem_cgroup_clear_mc();
5470 #else /* !CONFIG_MMU */
5471 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
5472 struct cgroup *cgroup,
5473 struct task_struct *p)
5475 return 0;
5477 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
5478 struct cgroup *cgroup,
5479 struct task_struct *p)
5482 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
5483 struct cgroup *cont,
5484 struct cgroup *old_cont,
5485 struct task_struct *p)
5488 #endif
5490 struct cgroup_subsys mem_cgroup_subsys = {
5491 .name = "memory",
5492 .subsys_id = mem_cgroup_subsys_id,
5493 .create = mem_cgroup_create,
5494 .pre_destroy = mem_cgroup_pre_destroy,
5495 .destroy = mem_cgroup_destroy,
5496 .populate = mem_cgroup_populate,
5497 .can_attach = mem_cgroup_can_attach,
5498 .cancel_attach = mem_cgroup_cancel_attach,
5499 .attach = mem_cgroup_move_task,
5500 .early_init = 0,
5501 .use_id = 1,
5504 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
5505 static int __init enable_swap_account(char *s)
5507 /* consider enabled if no parameter or 1 is given */
5508 if (!strcmp(s, "1"))
5509 really_do_swap_account = 1;
5510 else if (!strcmp(s, "0"))
5511 really_do_swap_account = 0;
5512 return 1;
5514 __setup("swapaccount=", enable_swap_account);
5516 #endif