drm: Fix authentication kernel crash
[linux-2.6/linux-acpi-2.6/ibm-acpi-2.6.git] / mm / memcontrol.c
blobf538e9b824eb6955d46fa272548d79cb7f3f0b74
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/export.h>
37 #include <linux/mutex.h>
38 #include <linux/rbtree.h>
39 #include <linux/slab.h>
40 #include <linux/swap.h>
41 #include <linux/swapops.h>
42 #include <linux/spinlock.h>
43 #include <linux/eventfd.h>
44 #include <linux/sort.h>
45 #include <linux/fs.h>
46 #include <linux/seq_file.h>
47 #include <linux/vmalloc.h>
48 #include <linux/mm_inline.h>
49 #include <linux/page_cgroup.h>
50 #include <linux/cpu.h>
51 #include <linux/oom.h>
52 #include "internal.h"
54 #include <asm/uaccess.h>
56 #include <trace/events/vmscan.h>
58 struct cgroup_subsys mem_cgroup_subsys __read_mostly;
59 #define MEM_CGROUP_RECLAIM_RETRIES 5
60 struct mem_cgroup *root_mem_cgroup __read_mostly;
62 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
63 /* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
64 int do_swap_account __read_mostly;
66 /* for remember boot option*/
67 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP_ENABLED
68 static int really_do_swap_account __initdata = 1;
69 #else
70 static int really_do_swap_account __initdata = 0;
71 #endif
73 #else
74 #define do_swap_account (0)
75 #endif
79 * Statistics for memory cgroup.
81 enum mem_cgroup_stat_index {
83 * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
85 MEM_CGROUP_STAT_CACHE, /* # of pages charged as cache */
86 MEM_CGROUP_STAT_RSS, /* # of pages charged as anon rss */
87 MEM_CGROUP_STAT_FILE_MAPPED, /* # of pages charged as file rss */
88 MEM_CGROUP_STAT_SWAPOUT, /* # of pages, swapped out */
89 MEM_CGROUP_STAT_DATA, /* end of data requires synchronization */
90 MEM_CGROUP_ON_MOVE, /* someone is moving account between groups */
91 MEM_CGROUP_STAT_NSTATS,
94 enum mem_cgroup_events_index {
95 MEM_CGROUP_EVENTS_PGPGIN, /* # of pages paged in */
96 MEM_CGROUP_EVENTS_PGPGOUT, /* # of pages paged out */
97 MEM_CGROUP_EVENTS_COUNT, /* # of pages paged in/out */
98 MEM_CGROUP_EVENTS_PGFAULT, /* # of page-faults */
99 MEM_CGROUP_EVENTS_PGMAJFAULT, /* # of major page-faults */
100 MEM_CGROUP_EVENTS_NSTATS,
103 * Per memcg event counter is incremented at every pagein/pageout. With THP,
104 * it will be incremated by the number of pages. This counter is used for
105 * for trigger some periodic events. This is straightforward and better
106 * than using jiffies etc. to handle periodic memcg event.
108 enum mem_cgroup_events_target {
109 MEM_CGROUP_TARGET_THRESH,
110 MEM_CGROUP_TARGET_SOFTLIMIT,
111 MEM_CGROUP_TARGET_NUMAINFO,
112 MEM_CGROUP_NTARGETS,
114 #define THRESHOLDS_EVENTS_TARGET (128)
115 #define SOFTLIMIT_EVENTS_TARGET (1024)
116 #define NUMAINFO_EVENTS_TARGET (1024)
118 struct mem_cgroup_stat_cpu {
119 long count[MEM_CGROUP_STAT_NSTATS];
120 unsigned long events[MEM_CGROUP_EVENTS_NSTATS];
121 unsigned long targets[MEM_CGROUP_NTARGETS];
125 * per-zone information in memory controller.
127 struct mem_cgroup_per_zone {
129 * spin_lock to protect the per cgroup LRU
131 struct list_head lists[NR_LRU_LISTS];
132 unsigned long count[NR_LRU_LISTS];
134 struct zone_reclaim_stat reclaim_stat;
135 struct rb_node tree_node; /* RB tree node */
136 unsigned long long usage_in_excess;/* Set to the value by which */
137 /* the soft limit is exceeded*/
138 bool on_tree;
139 struct mem_cgroup *mem; /* Back pointer, we cannot */
140 /* use container_of */
142 /* Macro for accessing counter */
143 #define MEM_CGROUP_ZSTAT(mz, idx) ((mz)->count[(idx)])
145 struct mem_cgroup_per_node {
146 struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
149 struct mem_cgroup_lru_info {
150 struct mem_cgroup_per_node *nodeinfo[MAX_NUMNODES];
154 * Cgroups above their limits are maintained in a RB-Tree, independent of
155 * their hierarchy representation
158 struct mem_cgroup_tree_per_zone {
159 struct rb_root rb_root;
160 spinlock_t lock;
163 struct mem_cgroup_tree_per_node {
164 struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
167 struct mem_cgroup_tree {
168 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
171 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
173 struct mem_cgroup_threshold {
174 struct eventfd_ctx *eventfd;
175 u64 threshold;
178 /* For threshold */
179 struct mem_cgroup_threshold_ary {
180 /* An array index points to threshold just below usage. */
181 int current_threshold;
182 /* Size of entries[] */
183 unsigned int size;
184 /* Array of thresholds */
185 struct mem_cgroup_threshold entries[0];
188 struct mem_cgroup_thresholds {
189 /* Primary thresholds array */
190 struct mem_cgroup_threshold_ary *primary;
192 * Spare threshold array.
193 * This is needed to make mem_cgroup_unregister_event() "never fail".
194 * It must be able to store at least primary->size - 1 entries.
196 struct mem_cgroup_threshold_ary *spare;
199 /* for OOM */
200 struct mem_cgroup_eventfd_list {
201 struct list_head list;
202 struct eventfd_ctx *eventfd;
205 static void mem_cgroup_threshold(struct mem_cgroup *memcg);
206 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
209 * The memory controller data structure. The memory controller controls both
210 * page cache and RSS per cgroup. We would eventually like to provide
211 * statistics based on the statistics developed by Rik Van Riel for clock-pro,
212 * to help the administrator determine what knobs to tune.
214 * TODO: Add a water mark for the memory controller. Reclaim will begin when
215 * we hit the water mark. May be even add a low water mark, such that
216 * no reclaim occurs from a cgroup at it's low water mark, this is
217 * a feature that will be implemented much later in the future.
219 struct mem_cgroup {
220 struct cgroup_subsys_state css;
222 * the counter to account for memory usage
224 struct res_counter res;
226 * the counter to account for mem+swap usage.
228 struct res_counter memsw;
230 * Per cgroup active and inactive list, similar to the
231 * per zone LRU lists.
233 struct mem_cgroup_lru_info info;
235 * While reclaiming in a hierarchy, we cache the last child we
236 * reclaimed from.
238 int last_scanned_child;
239 int last_scanned_node;
240 #if MAX_NUMNODES > 1
241 nodemask_t scan_nodes;
242 atomic_t numainfo_events;
243 atomic_t numainfo_updating;
244 #endif
246 * Should the accounting and control be hierarchical, per subtree?
248 bool use_hierarchy;
250 bool oom_lock;
251 atomic_t under_oom;
253 atomic_t refcnt;
255 int swappiness;
256 /* OOM-Killer disable */
257 int oom_kill_disable;
259 /* set when res.limit == memsw.limit */
260 bool memsw_is_minimum;
262 /* protect arrays of thresholds */
263 struct mutex thresholds_lock;
265 /* thresholds for memory usage. RCU-protected */
266 struct mem_cgroup_thresholds thresholds;
268 /* thresholds for mem+swap usage. RCU-protected */
269 struct mem_cgroup_thresholds memsw_thresholds;
271 /* For oom notifier event fd */
272 struct list_head oom_notify;
275 * Should we move charges of a task when a task is moved into this
276 * mem_cgroup ? And what type of charges should we move ?
278 unsigned long move_charge_at_immigrate;
280 * percpu counter.
282 struct mem_cgroup_stat_cpu *stat;
284 * used when a cpu is offlined or other synchronizations
285 * See mem_cgroup_read_stat().
287 struct mem_cgroup_stat_cpu nocpu_base;
288 spinlock_t pcp_counter_lock;
291 /* Stuffs for move charges at task migration. */
293 * Types of charges to be moved. "move_charge_at_immitgrate" is treated as a
294 * left-shifted bitmap of these types.
296 enum move_type {
297 MOVE_CHARGE_TYPE_ANON, /* private anonymous page and swap of it */
298 MOVE_CHARGE_TYPE_FILE, /* file page(including tmpfs) and swap of it */
299 NR_MOVE_TYPE,
302 /* "mc" and its members are protected by cgroup_mutex */
303 static struct move_charge_struct {
304 spinlock_t lock; /* for from, to */
305 struct mem_cgroup *from;
306 struct mem_cgroup *to;
307 unsigned long precharge;
308 unsigned long moved_charge;
309 unsigned long moved_swap;
310 struct task_struct *moving_task; /* a task moving charges */
311 wait_queue_head_t waitq; /* a waitq for other context */
312 } mc = {
313 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
314 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
317 static bool move_anon(void)
319 return test_bit(MOVE_CHARGE_TYPE_ANON,
320 &mc.to->move_charge_at_immigrate);
323 static bool move_file(void)
325 return test_bit(MOVE_CHARGE_TYPE_FILE,
326 &mc.to->move_charge_at_immigrate);
330 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
331 * limit reclaim to prevent infinite loops, if they ever occur.
333 #define MEM_CGROUP_MAX_RECLAIM_LOOPS (100)
334 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS (2)
336 enum charge_type {
337 MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
338 MEM_CGROUP_CHARGE_TYPE_MAPPED,
339 MEM_CGROUP_CHARGE_TYPE_SHMEM, /* used by page migration of shmem */
340 MEM_CGROUP_CHARGE_TYPE_FORCE, /* used by force_empty */
341 MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
342 MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
343 NR_CHARGE_TYPE,
346 /* for encoding cft->private value on file */
347 #define _MEM (0)
348 #define _MEMSWAP (1)
349 #define _OOM_TYPE (2)
350 #define MEMFILE_PRIVATE(x, val) (((x) << 16) | (val))
351 #define MEMFILE_TYPE(val) (((val) >> 16) & 0xffff)
352 #define MEMFILE_ATTR(val) ((val) & 0xffff)
353 /* Used for OOM nofiier */
354 #define OOM_CONTROL (0)
357 * Reclaim flags for mem_cgroup_hierarchical_reclaim
359 #define MEM_CGROUP_RECLAIM_NOSWAP_BIT 0x0
360 #define MEM_CGROUP_RECLAIM_NOSWAP (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
361 #define MEM_CGROUP_RECLAIM_SHRINK_BIT 0x1
362 #define MEM_CGROUP_RECLAIM_SHRINK (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
363 #define MEM_CGROUP_RECLAIM_SOFT_BIT 0x2
364 #define MEM_CGROUP_RECLAIM_SOFT (1 << MEM_CGROUP_RECLAIM_SOFT_BIT)
366 static void mem_cgroup_get(struct mem_cgroup *memcg);
367 static void mem_cgroup_put(struct mem_cgroup *memcg);
368 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg);
369 static void drain_all_stock_async(struct mem_cgroup *memcg);
371 static struct mem_cgroup_per_zone *
372 mem_cgroup_zoneinfo(struct mem_cgroup *memcg, int nid, int zid)
374 return &memcg->info.nodeinfo[nid]->zoneinfo[zid];
377 struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *memcg)
379 return &memcg->css;
382 static struct mem_cgroup_per_zone *
383 page_cgroup_zoneinfo(struct mem_cgroup *memcg, struct page *page)
385 int nid = page_to_nid(page);
386 int zid = page_zonenum(page);
388 return mem_cgroup_zoneinfo(memcg, nid, zid);
391 static struct mem_cgroup_tree_per_zone *
392 soft_limit_tree_node_zone(int nid, int zid)
394 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
397 static struct mem_cgroup_tree_per_zone *
398 soft_limit_tree_from_page(struct page *page)
400 int nid = page_to_nid(page);
401 int zid = page_zonenum(page);
403 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
406 static void
407 __mem_cgroup_insert_exceeded(struct mem_cgroup *memcg,
408 struct mem_cgroup_per_zone *mz,
409 struct mem_cgroup_tree_per_zone *mctz,
410 unsigned long long new_usage_in_excess)
412 struct rb_node **p = &mctz->rb_root.rb_node;
413 struct rb_node *parent = NULL;
414 struct mem_cgroup_per_zone *mz_node;
416 if (mz->on_tree)
417 return;
419 mz->usage_in_excess = new_usage_in_excess;
420 if (!mz->usage_in_excess)
421 return;
422 while (*p) {
423 parent = *p;
424 mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
425 tree_node);
426 if (mz->usage_in_excess < mz_node->usage_in_excess)
427 p = &(*p)->rb_left;
429 * We can't avoid mem cgroups that are over their soft
430 * limit by the same amount
432 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
433 p = &(*p)->rb_right;
435 rb_link_node(&mz->tree_node, parent, p);
436 rb_insert_color(&mz->tree_node, &mctz->rb_root);
437 mz->on_tree = true;
440 static void
441 __mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
442 struct mem_cgroup_per_zone *mz,
443 struct mem_cgroup_tree_per_zone *mctz)
445 if (!mz->on_tree)
446 return;
447 rb_erase(&mz->tree_node, &mctz->rb_root);
448 mz->on_tree = false;
451 static void
452 mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
453 struct mem_cgroup_per_zone *mz,
454 struct mem_cgroup_tree_per_zone *mctz)
456 spin_lock(&mctz->lock);
457 __mem_cgroup_remove_exceeded(memcg, mz, mctz);
458 spin_unlock(&mctz->lock);
462 static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
464 unsigned long long excess;
465 struct mem_cgroup_per_zone *mz;
466 struct mem_cgroup_tree_per_zone *mctz;
467 int nid = page_to_nid(page);
468 int zid = page_zonenum(page);
469 mctz = soft_limit_tree_from_page(page);
472 * Necessary to update all ancestors when hierarchy is used.
473 * because their event counter is not touched.
475 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
476 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
477 excess = res_counter_soft_limit_excess(&memcg->res);
479 * We have to update the tree if mz is on RB-tree or
480 * mem is over its softlimit.
482 if (excess || mz->on_tree) {
483 spin_lock(&mctz->lock);
484 /* if on-tree, remove it */
485 if (mz->on_tree)
486 __mem_cgroup_remove_exceeded(memcg, mz, mctz);
488 * Insert again. mz->usage_in_excess will be updated.
489 * If excess is 0, no tree ops.
491 __mem_cgroup_insert_exceeded(memcg, mz, mctz, excess);
492 spin_unlock(&mctz->lock);
497 static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
499 int node, zone;
500 struct mem_cgroup_per_zone *mz;
501 struct mem_cgroup_tree_per_zone *mctz;
503 for_each_node_state(node, N_POSSIBLE) {
504 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
505 mz = mem_cgroup_zoneinfo(memcg, node, zone);
506 mctz = soft_limit_tree_node_zone(node, zone);
507 mem_cgroup_remove_exceeded(memcg, mz, mctz);
512 static struct mem_cgroup_per_zone *
513 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
515 struct rb_node *rightmost = NULL;
516 struct mem_cgroup_per_zone *mz;
518 retry:
519 mz = NULL;
520 rightmost = rb_last(&mctz->rb_root);
521 if (!rightmost)
522 goto done; /* Nothing to reclaim from */
524 mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
526 * Remove the node now but someone else can add it back,
527 * we will to add it back at the end of reclaim to its correct
528 * position in the tree.
530 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
531 if (!res_counter_soft_limit_excess(&mz->mem->res) ||
532 !css_tryget(&mz->mem->css))
533 goto retry;
534 done:
535 return mz;
538 static struct mem_cgroup_per_zone *
539 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
541 struct mem_cgroup_per_zone *mz;
543 spin_lock(&mctz->lock);
544 mz = __mem_cgroup_largest_soft_limit_node(mctz);
545 spin_unlock(&mctz->lock);
546 return mz;
550 * Implementation Note: reading percpu statistics for memcg.
552 * Both of vmstat[] and percpu_counter has threshold and do periodic
553 * synchronization to implement "quick" read. There are trade-off between
554 * reading cost and precision of value. Then, we may have a chance to implement
555 * a periodic synchronizion of counter in memcg's counter.
557 * But this _read() function is used for user interface now. The user accounts
558 * memory usage by memory cgroup and he _always_ requires exact value because
559 * he accounts memory. Even if we provide quick-and-fuzzy read, we always
560 * have to visit all online cpus and make sum. So, for now, unnecessary
561 * synchronization is not implemented. (just implemented for cpu hotplug)
563 * If there are kernel internal actions which can make use of some not-exact
564 * value, and reading all cpu value can be performance bottleneck in some
565 * common workload, threashold and synchonization as vmstat[] should be
566 * implemented.
568 static long mem_cgroup_read_stat(struct mem_cgroup *memcg,
569 enum mem_cgroup_stat_index idx)
571 long val = 0;
572 int cpu;
574 get_online_cpus();
575 for_each_online_cpu(cpu)
576 val += per_cpu(memcg->stat->count[idx], cpu);
577 #ifdef CONFIG_HOTPLUG_CPU
578 spin_lock(&memcg->pcp_counter_lock);
579 val += memcg->nocpu_base.count[idx];
580 spin_unlock(&memcg->pcp_counter_lock);
581 #endif
582 put_online_cpus();
583 return val;
586 static void mem_cgroup_swap_statistics(struct mem_cgroup *memcg,
587 bool charge)
589 int val = (charge) ? 1 : -1;
590 this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_SWAPOUT], val);
593 void mem_cgroup_pgfault(struct mem_cgroup *memcg, int val)
595 this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_PGFAULT], val);
598 void mem_cgroup_pgmajfault(struct mem_cgroup *memcg, int val)
600 this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_PGMAJFAULT], val);
603 static unsigned long mem_cgroup_read_events(struct mem_cgroup *memcg,
604 enum mem_cgroup_events_index idx)
606 unsigned long val = 0;
607 int cpu;
609 for_each_online_cpu(cpu)
610 val += per_cpu(memcg->stat->events[idx], cpu);
611 #ifdef CONFIG_HOTPLUG_CPU
612 spin_lock(&memcg->pcp_counter_lock);
613 val += memcg->nocpu_base.events[idx];
614 spin_unlock(&memcg->pcp_counter_lock);
615 #endif
616 return val;
619 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
620 bool file, int nr_pages)
622 preempt_disable();
624 if (file)
625 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_CACHE],
626 nr_pages);
627 else
628 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS],
629 nr_pages);
631 /* pagein of a big page is an event. So, ignore page size */
632 if (nr_pages > 0)
633 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGIN]);
634 else {
635 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGOUT]);
636 nr_pages = -nr_pages; /* for event */
639 __this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_COUNT], nr_pages);
641 preempt_enable();
644 unsigned long
645 mem_cgroup_zone_nr_lru_pages(struct mem_cgroup *memcg, int nid, int zid,
646 unsigned int lru_mask)
648 struct mem_cgroup_per_zone *mz;
649 enum lru_list l;
650 unsigned long ret = 0;
652 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
654 for_each_lru(l) {
655 if (BIT(l) & lru_mask)
656 ret += MEM_CGROUP_ZSTAT(mz, l);
658 return ret;
661 static unsigned long
662 mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
663 int nid, unsigned int lru_mask)
665 u64 total = 0;
666 int zid;
668 for (zid = 0; zid < MAX_NR_ZONES; zid++)
669 total += mem_cgroup_zone_nr_lru_pages(memcg,
670 nid, zid, lru_mask);
672 return total;
675 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
676 unsigned int lru_mask)
678 int nid;
679 u64 total = 0;
681 for_each_node_state(nid, N_HIGH_MEMORY)
682 total += mem_cgroup_node_nr_lru_pages(memcg, nid, lru_mask);
683 return total;
686 static bool __memcg_event_check(struct mem_cgroup *memcg, int target)
688 unsigned long val, next;
690 val = __this_cpu_read(memcg->stat->events[MEM_CGROUP_EVENTS_COUNT]);
691 next = __this_cpu_read(memcg->stat->targets[target]);
692 /* from time_after() in jiffies.h */
693 return ((long)next - (long)val < 0);
696 static void __mem_cgroup_target_update(struct mem_cgroup *memcg, int target)
698 unsigned long val, next;
700 val = __this_cpu_read(memcg->stat->events[MEM_CGROUP_EVENTS_COUNT]);
702 switch (target) {
703 case MEM_CGROUP_TARGET_THRESH:
704 next = val + THRESHOLDS_EVENTS_TARGET;
705 break;
706 case MEM_CGROUP_TARGET_SOFTLIMIT:
707 next = val + SOFTLIMIT_EVENTS_TARGET;
708 break;
709 case MEM_CGROUP_TARGET_NUMAINFO:
710 next = val + NUMAINFO_EVENTS_TARGET;
711 break;
712 default:
713 return;
716 __this_cpu_write(memcg->stat->targets[target], next);
720 * Check events in order.
723 static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
725 preempt_disable();
726 /* threshold event is triggered in finer grain than soft limit */
727 if (unlikely(__memcg_event_check(memcg, MEM_CGROUP_TARGET_THRESH))) {
728 mem_cgroup_threshold(memcg);
729 __mem_cgroup_target_update(memcg, MEM_CGROUP_TARGET_THRESH);
730 if (unlikely(__memcg_event_check(memcg,
731 MEM_CGROUP_TARGET_SOFTLIMIT))) {
732 mem_cgroup_update_tree(memcg, page);
733 __mem_cgroup_target_update(memcg,
734 MEM_CGROUP_TARGET_SOFTLIMIT);
736 #if MAX_NUMNODES > 1
737 if (unlikely(__memcg_event_check(memcg,
738 MEM_CGROUP_TARGET_NUMAINFO))) {
739 atomic_inc(&memcg->numainfo_events);
740 __mem_cgroup_target_update(memcg,
741 MEM_CGROUP_TARGET_NUMAINFO);
743 #endif
745 preempt_enable();
748 static struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
750 return container_of(cgroup_subsys_state(cont,
751 mem_cgroup_subsys_id), struct mem_cgroup,
752 css);
755 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
758 * mm_update_next_owner() may clear mm->owner to NULL
759 * if it races with swapoff, page migration, etc.
760 * So this can be called with p == NULL.
762 if (unlikely(!p))
763 return NULL;
765 return container_of(task_subsys_state(p, mem_cgroup_subsys_id),
766 struct mem_cgroup, css);
769 struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
771 struct mem_cgroup *memcg = NULL;
773 if (!mm)
774 return NULL;
776 * Because we have no locks, mm->owner's may be being moved to other
777 * cgroup. We use css_tryget() here even if this looks
778 * pessimistic (rather than adding locks here).
780 rcu_read_lock();
781 do {
782 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
783 if (unlikely(!memcg))
784 break;
785 } while (!css_tryget(&memcg->css));
786 rcu_read_unlock();
787 return memcg;
790 /* The caller has to guarantee "mem" exists before calling this */
791 static struct mem_cgroup *mem_cgroup_start_loop(struct mem_cgroup *memcg)
793 struct cgroup_subsys_state *css;
794 int found;
796 if (!memcg) /* ROOT cgroup has the smallest ID */
797 return root_mem_cgroup; /*css_put/get against root is ignored*/
798 if (!memcg->use_hierarchy) {
799 if (css_tryget(&memcg->css))
800 return memcg;
801 return NULL;
803 rcu_read_lock();
805 * searching a memory cgroup which has the smallest ID under given
806 * ROOT cgroup. (ID >= 1)
808 css = css_get_next(&mem_cgroup_subsys, 1, &memcg->css, &found);
809 if (css && css_tryget(css))
810 memcg = container_of(css, struct mem_cgroup, css);
811 else
812 memcg = NULL;
813 rcu_read_unlock();
814 return memcg;
817 static struct mem_cgroup *mem_cgroup_get_next(struct mem_cgroup *iter,
818 struct mem_cgroup *root,
819 bool cond)
821 int nextid = css_id(&iter->css) + 1;
822 int found;
823 int hierarchy_used;
824 struct cgroup_subsys_state *css;
826 hierarchy_used = iter->use_hierarchy;
828 css_put(&iter->css);
829 /* If no ROOT, walk all, ignore hierarchy */
830 if (!cond || (root && !hierarchy_used))
831 return NULL;
833 if (!root)
834 root = root_mem_cgroup;
836 do {
837 iter = NULL;
838 rcu_read_lock();
840 css = css_get_next(&mem_cgroup_subsys, nextid,
841 &root->css, &found);
842 if (css && css_tryget(css))
843 iter = container_of(css, struct mem_cgroup, css);
844 rcu_read_unlock();
845 /* If css is NULL, no more cgroups will be found */
846 nextid = found + 1;
847 } while (css && !iter);
849 return iter;
852 * for_eacn_mem_cgroup_tree() for visiting all cgroup under tree. Please
853 * be careful that "break" loop is not allowed. We have reference count.
854 * Instead of that modify "cond" to be false and "continue" to exit the loop.
856 #define for_each_mem_cgroup_tree_cond(iter, root, cond) \
857 for (iter = mem_cgroup_start_loop(root);\
858 iter != NULL;\
859 iter = mem_cgroup_get_next(iter, root, cond))
861 #define for_each_mem_cgroup_tree(iter, root) \
862 for_each_mem_cgroup_tree_cond(iter, root, true)
864 #define for_each_mem_cgroup_all(iter) \
865 for_each_mem_cgroup_tree_cond(iter, NULL, true)
868 static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg)
870 return (memcg == root_mem_cgroup);
873 void mem_cgroup_count_vm_event(struct mm_struct *mm, enum vm_event_item idx)
875 struct mem_cgroup *memcg;
877 if (!mm)
878 return;
880 rcu_read_lock();
881 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
882 if (unlikely(!memcg))
883 goto out;
885 switch (idx) {
886 case PGMAJFAULT:
887 mem_cgroup_pgmajfault(memcg, 1);
888 break;
889 case PGFAULT:
890 mem_cgroup_pgfault(memcg, 1);
891 break;
892 default:
893 BUG();
895 out:
896 rcu_read_unlock();
898 EXPORT_SYMBOL(mem_cgroup_count_vm_event);
901 * Following LRU functions are allowed to be used without PCG_LOCK.
902 * Operations are called by routine of global LRU independently from memcg.
903 * What we have to take care of here is validness of pc->mem_cgroup.
905 * Changes to pc->mem_cgroup happens when
906 * 1. charge
907 * 2. moving account
908 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
909 * It is added to LRU before charge.
910 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
911 * When moving account, the page is not on LRU. It's isolated.
914 void mem_cgroup_del_lru_list(struct page *page, enum lru_list lru)
916 struct page_cgroup *pc;
917 struct mem_cgroup_per_zone *mz;
919 if (mem_cgroup_disabled())
920 return;
921 pc = lookup_page_cgroup(page);
922 /* can happen while we handle swapcache. */
923 if (!TestClearPageCgroupAcctLRU(pc))
924 return;
925 VM_BUG_ON(!pc->mem_cgroup);
927 * We don't check PCG_USED bit. It's cleared when the "page" is finally
928 * removed from global LRU.
930 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
931 /* huge page split is done under lru_lock. so, we have no races. */
932 MEM_CGROUP_ZSTAT(mz, lru) -= 1 << compound_order(page);
933 if (mem_cgroup_is_root(pc->mem_cgroup))
934 return;
935 VM_BUG_ON(list_empty(&pc->lru));
936 list_del_init(&pc->lru);
939 void mem_cgroup_del_lru(struct page *page)
941 mem_cgroup_del_lru_list(page, page_lru(page));
945 * Writeback is about to end against a page which has been marked for immediate
946 * reclaim. If it still appears to be reclaimable, move it to the tail of the
947 * inactive list.
949 void mem_cgroup_rotate_reclaimable_page(struct page *page)
951 struct mem_cgroup_per_zone *mz;
952 struct page_cgroup *pc;
953 enum lru_list lru = page_lru(page);
955 if (mem_cgroup_disabled())
956 return;
958 pc = lookup_page_cgroup(page);
959 /* unused or root page is not rotated. */
960 if (!PageCgroupUsed(pc))
961 return;
962 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
963 smp_rmb();
964 if (mem_cgroup_is_root(pc->mem_cgroup))
965 return;
966 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
967 list_move_tail(&pc->lru, &mz->lists[lru]);
970 void mem_cgroup_rotate_lru_list(struct page *page, enum lru_list lru)
972 struct mem_cgroup_per_zone *mz;
973 struct page_cgroup *pc;
975 if (mem_cgroup_disabled())
976 return;
978 pc = lookup_page_cgroup(page);
979 /* unused or root page is not rotated. */
980 if (!PageCgroupUsed(pc))
981 return;
982 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
983 smp_rmb();
984 if (mem_cgroup_is_root(pc->mem_cgroup))
985 return;
986 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
987 list_move(&pc->lru, &mz->lists[lru]);
990 void mem_cgroup_add_lru_list(struct page *page, enum lru_list lru)
992 struct page_cgroup *pc;
993 struct mem_cgroup_per_zone *mz;
995 if (mem_cgroup_disabled())
996 return;
997 pc = lookup_page_cgroup(page);
998 VM_BUG_ON(PageCgroupAcctLRU(pc));
1000 * putback: charge:
1001 * SetPageLRU SetPageCgroupUsed
1002 * smp_mb smp_mb
1003 * PageCgroupUsed && add to memcg LRU PageLRU && add to memcg LRU
1005 * Ensure that one of the two sides adds the page to the memcg
1006 * LRU during a race.
1008 smp_mb();
1009 if (!PageCgroupUsed(pc))
1010 return;
1011 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1012 smp_rmb();
1013 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
1014 /* huge page split is done under lru_lock. so, we have no races. */
1015 MEM_CGROUP_ZSTAT(mz, lru) += 1 << compound_order(page);
1016 SetPageCgroupAcctLRU(pc);
1017 if (mem_cgroup_is_root(pc->mem_cgroup))
1018 return;
1019 list_add(&pc->lru, &mz->lists[lru]);
1023 * At handling SwapCache and other FUSE stuff, pc->mem_cgroup may be changed
1024 * while it's linked to lru because the page may be reused after it's fully
1025 * uncharged. To handle that, unlink page_cgroup from LRU when charge it again.
1026 * It's done under lock_page and expected that zone->lru_lock isnever held.
1028 static void mem_cgroup_lru_del_before_commit(struct page *page)
1030 unsigned long flags;
1031 struct zone *zone = page_zone(page);
1032 struct page_cgroup *pc = lookup_page_cgroup(page);
1035 * Doing this check without taking ->lru_lock seems wrong but this
1036 * is safe. Because if page_cgroup's USED bit is unset, the page
1037 * will not be added to any memcg's LRU. If page_cgroup's USED bit is
1038 * set, the commit after this will fail, anyway.
1039 * This all charge/uncharge is done under some mutual execustion.
1040 * So, we don't need to taking care of changes in USED bit.
1042 if (likely(!PageLRU(page)))
1043 return;
1045 spin_lock_irqsave(&zone->lru_lock, flags);
1047 * Forget old LRU when this page_cgroup is *not* used. This Used bit
1048 * is guarded by lock_page() because the page is SwapCache.
1050 if (!PageCgroupUsed(pc))
1051 mem_cgroup_del_lru_list(page, page_lru(page));
1052 spin_unlock_irqrestore(&zone->lru_lock, flags);
1055 static void mem_cgroup_lru_add_after_commit(struct page *page)
1057 unsigned long flags;
1058 struct zone *zone = page_zone(page);
1059 struct page_cgroup *pc = lookup_page_cgroup(page);
1061 * putback: charge:
1062 * SetPageLRU SetPageCgroupUsed
1063 * smp_mb smp_mb
1064 * PageCgroupUsed && add to memcg LRU PageLRU && add to memcg LRU
1066 * Ensure that one of the two sides adds the page to the memcg
1067 * LRU during a race.
1069 smp_mb();
1070 /* taking care of that the page is added to LRU while we commit it */
1071 if (likely(!PageLRU(page)))
1072 return;
1073 spin_lock_irqsave(&zone->lru_lock, flags);
1074 /* link when the page is linked to LRU but page_cgroup isn't */
1075 if (PageLRU(page) && !PageCgroupAcctLRU(pc))
1076 mem_cgroup_add_lru_list(page, page_lru(page));
1077 spin_unlock_irqrestore(&zone->lru_lock, flags);
1081 void mem_cgroup_move_lists(struct page *page,
1082 enum lru_list from, enum lru_list to)
1084 if (mem_cgroup_disabled())
1085 return;
1086 mem_cgroup_del_lru_list(page, from);
1087 mem_cgroup_add_lru_list(page, to);
1091 * Checks whether given mem is same or in the root_mem_cgroup's
1092 * hierarchy subtree
1094 static bool mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
1095 struct mem_cgroup *memcg)
1097 if (root_memcg != memcg) {
1098 return (root_memcg->use_hierarchy &&
1099 css_is_ancestor(&memcg->css, &root_memcg->css));
1102 return true;
1105 int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *memcg)
1107 int ret;
1108 struct mem_cgroup *curr = NULL;
1109 struct task_struct *p;
1111 p = find_lock_task_mm(task);
1112 if (!p)
1113 return 0;
1114 curr = try_get_mem_cgroup_from_mm(p->mm);
1115 task_unlock(p);
1116 if (!curr)
1117 return 0;
1119 * We should check use_hierarchy of "memcg" not "curr". Because checking
1120 * use_hierarchy of "curr" here make this function true if hierarchy is
1121 * enabled in "curr" and "curr" is a child of "memcg" in *cgroup*
1122 * hierarchy(even if use_hierarchy is disabled in "memcg").
1124 ret = mem_cgroup_same_or_subtree(memcg, curr);
1125 css_put(&curr->css);
1126 return ret;
1129 int mem_cgroup_inactive_anon_is_low(struct mem_cgroup *memcg, struct zone *zone)
1131 unsigned long inactive_ratio;
1132 int nid = zone_to_nid(zone);
1133 int zid = zone_idx(zone);
1134 unsigned long inactive;
1135 unsigned long active;
1136 unsigned long gb;
1138 inactive = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1139 BIT(LRU_INACTIVE_ANON));
1140 active = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1141 BIT(LRU_ACTIVE_ANON));
1143 gb = (inactive + active) >> (30 - PAGE_SHIFT);
1144 if (gb)
1145 inactive_ratio = int_sqrt(10 * gb);
1146 else
1147 inactive_ratio = 1;
1149 return inactive * inactive_ratio < active;
1152 int mem_cgroup_inactive_file_is_low(struct mem_cgroup *memcg, struct zone *zone)
1154 unsigned long active;
1155 unsigned long inactive;
1156 int zid = zone_idx(zone);
1157 int nid = zone_to_nid(zone);
1159 inactive = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1160 BIT(LRU_INACTIVE_FILE));
1161 active = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1162 BIT(LRU_ACTIVE_FILE));
1164 return (active > inactive);
1167 struct zone_reclaim_stat *mem_cgroup_get_reclaim_stat(struct mem_cgroup *memcg,
1168 struct zone *zone)
1170 int nid = zone_to_nid(zone);
1171 int zid = zone_idx(zone);
1172 struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
1174 return &mz->reclaim_stat;
1177 struct zone_reclaim_stat *
1178 mem_cgroup_get_reclaim_stat_from_page(struct page *page)
1180 struct page_cgroup *pc;
1181 struct mem_cgroup_per_zone *mz;
1183 if (mem_cgroup_disabled())
1184 return NULL;
1186 pc = lookup_page_cgroup(page);
1187 if (!PageCgroupUsed(pc))
1188 return NULL;
1189 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1190 smp_rmb();
1191 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
1192 return &mz->reclaim_stat;
1195 unsigned long mem_cgroup_isolate_pages(unsigned long nr_to_scan,
1196 struct list_head *dst,
1197 unsigned long *scanned, int order,
1198 isolate_mode_t mode,
1199 struct zone *z,
1200 struct mem_cgroup *mem_cont,
1201 int active, int file)
1203 unsigned long nr_taken = 0;
1204 struct page *page;
1205 unsigned long scan;
1206 LIST_HEAD(pc_list);
1207 struct list_head *src;
1208 struct page_cgroup *pc, *tmp;
1209 int nid = zone_to_nid(z);
1210 int zid = zone_idx(z);
1211 struct mem_cgroup_per_zone *mz;
1212 int lru = LRU_FILE * file + active;
1213 int ret;
1215 BUG_ON(!mem_cont);
1216 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
1217 src = &mz->lists[lru];
1219 scan = 0;
1220 list_for_each_entry_safe_reverse(pc, tmp, src, lru) {
1221 if (scan >= nr_to_scan)
1222 break;
1224 if (unlikely(!PageCgroupUsed(pc)))
1225 continue;
1227 page = lookup_cgroup_page(pc);
1229 if (unlikely(!PageLRU(page)))
1230 continue;
1232 scan++;
1233 ret = __isolate_lru_page(page, mode, file);
1234 switch (ret) {
1235 case 0:
1236 list_move(&page->lru, dst);
1237 mem_cgroup_del_lru(page);
1238 nr_taken += hpage_nr_pages(page);
1239 break;
1240 case -EBUSY:
1241 /* we don't affect global LRU but rotate in our LRU */
1242 mem_cgroup_rotate_lru_list(page, page_lru(page));
1243 break;
1244 default:
1245 break;
1249 *scanned = scan;
1251 trace_mm_vmscan_memcg_isolate(0, nr_to_scan, scan, nr_taken,
1252 0, 0, 0, mode);
1254 return nr_taken;
1257 #define mem_cgroup_from_res_counter(counter, member) \
1258 container_of(counter, struct mem_cgroup, member)
1261 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1262 * @mem: the memory cgroup
1264 * Returns the maximum amount of memory @mem can be charged with, in
1265 * pages.
1267 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1269 unsigned long long margin;
1271 margin = res_counter_margin(&memcg->res);
1272 if (do_swap_account)
1273 margin = min(margin, res_counter_margin(&memcg->memsw));
1274 return margin >> PAGE_SHIFT;
1277 int mem_cgroup_swappiness(struct mem_cgroup *memcg)
1279 struct cgroup *cgrp = memcg->css.cgroup;
1281 /* root ? */
1282 if (cgrp->parent == NULL)
1283 return vm_swappiness;
1285 return memcg->swappiness;
1288 static void mem_cgroup_start_move(struct mem_cgroup *memcg)
1290 int cpu;
1292 get_online_cpus();
1293 spin_lock(&memcg->pcp_counter_lock);
1294 for_each_online_cpu(cpu)
1295 per_cpu(memcg->stat->count[MEM_CGROUP_ON_MOVE], cpu) += 1;
1296 memcg->nocpu_base.count[MEM_CGROUP_ON_MOVE] += 1;
1297 spin_unlock(&memcg->pcp_counter_lock);
1298 put_online_cpus();
1300 synchronize_rcu();
1303 static void mem_cgroup_end_move(struct mem_cgroup *memcg)
1305 int cpu;
1307 if (!memcg)
1308 return;
1309 get_online_cpus();
1310 spin_lock(&memcg->pcp_counter_lock);
1311 for_each_online_cpu(cpu)
1312 per_cpu(memcg->stat->count[MEM_CGROUP_ON_MOVE], cpu) -= 1;
1313 memcg->nocpu_base.count[MEM_CGROUP_ON_MOVE] -= 1;
1314 spin_unlock(&memcg->pcp_counter_lock);
1315 put_online_cpus();
1318 * 2 routines for checking "mem" is under move_account() or not.
1320 * mem_cgroup_stealed() - checking a cgroup is mc.from or not. This is used
1321 * for avoiding race in accounting. If true,
1322 * pc->mem_cgroup may be overwritten.
1324 * mem_cgroup_under_move() - checking a cgroup is mc.from or mc.to or
1325 * under hierarchy of moving cgroups. This is for
1326 * waiting at hith-memory prressure caused by "move".
1329 static bool mem_cgroup_stealed(struct mem_cgroup *memcg)
1331 VM_BUG_ON(!rcu_read_lock_held());
1332 return this_cpu_read(memcg->stat->count[MEM_CGROUP_ON_MOVE]) > 0;
1335 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1337 struct mem_cgroup *from;
1338 struct mem_cgroup *to;
1339 bool ret = false;
1341 * Unlike task_move routines, we access mc.to, mc.from not under
1342 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1344 spin_lock(&mc.lock);
1345 from = mc.from;
1346 to = mc.to;
1347 if (!from)
1348 goto unlock;
1350 ret = mem_cgroup_same_or_subtree(memcg, from)
1351 || mem_cgroup_same_or_subtree(memcg, to);
1352 unlock:
1353 spin_unlock(&mc.lock);
1354 return ret;
1357 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1359 if (mc.moving_task && current != mc.moving_task) {
1360 if (mem_cgroup_under_move(memcg)) {
1361 DEFINE_WAIT(wait);
1362 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1363 /* moving charge context might have finished. */
1364 if (mc.moving_task)
1365 schedule();
1366 finish_wait(&mc.waitq, &wait);
1367 return true;
1370 return false;
1374 * mem_cgroup_print_oom_info: Called from OOM with tasklist_lock held in read mode.
1375 * @memcg: The memory cgroup that went over limit
1376 * @p: Task that is going to be killed
1378 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1379 * enabled
1381 void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1383 struct cgroup *task_cgrp;
1384 struct cgroup *mem_cgrp;
1386 * Need a buffer in BSS, can't rely on allocations. The code relies
1387 * on the assumption that OOM is serialized for memory controller.
1388 * If this assumption is broken, revisit this code.
1390 static char memcg_name[PATH_MAX];
1391 int ret;
1393 if (!memcg || !p)
1394 return;
1397 rcu_read_lock();
1399 mem_cgrp = memcg->css.cgroup;
1400 task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
1402 ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
1403 if (ret < 0) {
1405 * Unfortunately, we are unable to convert to a useful name
1406 * But we'll still print out the usage information
1408 rcu_read_unlock();
1409 goto done;
1411 rcu_read_unlock();
1413 printk(KERN_INFO "Task in %s killed", memcg_name);
1415 rcu_read_lock();
1416 ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
1417 if (ret < 0) {
1418 rcu_read_unlock();
1419 goto done;
1421 rcu_read_unlock();
1424 * Continues from above, so we don't need an KERN_ level
1426 printk(KERN_CONT " as a result of limit of %s\n", memcg_name);
1427 done:
1429 printk(KERN_INFO "memory: usage %llukB, limit %llukB, failcnt %llu\n",
1430 res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
1431 res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
1432 res_counter_read_u64(&memcg->res, RES_FAILCNT));
1433 printk(KERN_INFO "memory+swap: usage %llukB, limit %llukB, "
1434 "failcnt %llu\n",
1435 res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
1436 res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
1437 res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
1441 * This function returns the number of memcg under hierarchy tree. Returns
1442 * 1(self count) if no children.
1444 static int mem_cgroup_count_children(struct mem_cgroup *memcg)
1446 int num = 0;
1447 struct mem_cgroup *iter;
1449 for_each_mem_cgroup_tree(iter, memcg)
1450 num++;
1451 return num;
1455 * Return the memory (and swap, if configured) limit for a memcg.
1457 u64 mem_cgroup_get_limit(struct mem_cgroup *memcg)
1459 u64 limit;
1460 u64 memsw;
1462 limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
1463 limit += total_swap_pages << PAGE_SHIFT;
1465 memsw = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
1467 * If memsw is finite and limits the amount of swap space available
1468 * to this memcg, return that limit.
1470 return min(limit, memsw);
1474 * Visit the first child (need not be the first child as per the ordering
1475 * of the cgroup list, since we track last_scanned_child) of @mem and use
1476 * that to reclaim free pages from.
1478 static struct mem_cgroup *
1479 mem_cgroup_select_victim(struct mem_cgroup *root_memcg)
1481 struct mem_cgroup *ret = NULL;
1482 struct cgroup_subsys_state *css;
1483 int nextid, found;
1485 if (!root_memcg->use_hierarchy) {
1486 css_get(&root_memcg->css);
1487 ret = root_memcg;
1490 while (!ret) {
1491 rcu_read_lock();
1492 nextid = root_memcg->last_scanned_child + 1;
1493 css = css_get_next(&mem_cgroup_subsys, nextid, &root_memcg->css,
1494 &found);
1495 if (css && css_tryget(css))
1496 ret = container_of(css, struct mem_cgroup, css);
1498 rcu_read_unlock();
1499 /* Updates scanning parameter */
1500 if (!css) {
1501 /* this means start scan from ID:1 */
1502 root_memcg->last_scanned_child = 0;
1503 } else
1504 root_memcg->last_scanned_child = found;
1507 return ret;
1511 * test_mem_cgroup_node_reclaimable
1512 * @mem: the target memcg
1513 * @nid: the node ID to be checked.
1514 * @noswap : specify true here if the user wants flle only information.
1516 * This function returns whether the specified memcg contains any
1517 * reclaimable pages on a node. Returns true if there are any reclaimable
1518 * pages in the node.
1520 static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *memcg,
1521 int nid, bool noswap)
1523 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_FILE))
1524 return true;
1525 if (noswap || !total_swap_pages)
1526 return false;
1527 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_ANON))
1528 return true;
1529 return false;
1532 #if MAX_NUMNODES > 1
1535 * Always updating the nodemask is not very good - even if we have an empty
1536 * list or the wrong list here, we can start from some node and traverse all
1537 * nodes based on the zonelist. So update the list loosely once per 10 secs.
1540 static void mem_cgroup_may_update_nodemask(struct mem_cgroup *memcg)
1542 int nid;
1544 * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
1545 * pagein/pageout changes since the last update.
1547 if (!atomic_read(&memcg->numainfo_events))
1548 return;
1549 if (atomic_inc_return(&memcg->numainfo_updating) > 1)
1550 return;
1552 /* make a nodemask where this memcg uses memory from */
1553 memcg->scan_nodes = node_states[N_HIGH_MEMORY];
1555 for_each_node_mask(nid, node_states[N_HIGH_MEMORY]) {
1557 if (!test_mem_cgroup_node_reclaimable(memcg, nid, false))
1558 node_clear(nid, memcg->scan_nodes);
1561 atomic_set(&memcg->numainfo_events, 0);
1562 atomic_set(&memcg->numainfo_updating, 0);
1566 * Selecting a node where we start reclaim from. Because what we need is just
1567 * reducing usage counter, start from anywhere is O,K. Considering
1568 * memory reclaim from current node, there are pros. and cons.
1570 * Freeing memory from current node means freeing memory from a node which
1571 * we'll use or we've used. So, it may make LRU bad. And if several threads
1572 * hit limits, it will see a contention on a node. But freeing from remote
1573 * node means more costs for memory reclaim because of memory latency.
1575 * Now, we use round-robin. Better algorithm is welcomed.
1577 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1579 int node;
1581 mem_cgroup_may_update_nodemask(memcg);
1582 node = memcg->last_scanned_node;
1584 node = next_node(node, memcg->scan_nodes);
1585 if (node == MAX_NUMNODES)
1586 node = first_node(memcg->scan_nodes);
1588 * We call this when we hit limit, not when pages are added to LRU.
1589 * No LRU may hold pages because all pages are UNEVICTABLE or
1590 * memcg is too small and all pages are not on LRU. In that case,
1591 * we use curret node.
1593 if (unlikely(node == MAX_NUMNODES))
1594 node = numa_node_id();
1596 memcg->last_scanned_node = node;
1597 return node;
1601 * Check all nodes whether it contains reclaimable pages or not.
1602 * For quick scan, we make use of scan_nodes. This will allow us to skip
1603 * unused nodes. But scan_nodes is lazily updated and may not cotain
1604 * enough new information. We need to do double check.
1606 bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
1608 int nid;
1611 * quick check...making use of scan_node.
1612 * We can skip unused nodes.
1614 if (!nodes_empty(memcg->scan_nodes)) {
1615 for (nid = first_node(memcg->scan_nodes);
1616 nid < MAX_NUMNODES;
1617 nid = next_node(nid, memcg->scan_nodes)) {
1619 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
1620 return true;
1624 * Check rest of nodes.
1626 for_each_node_state(nid, N_HIGH_MEMORY) {
1627 if (node_isset(nid, memcg->scan_nodes))
1628 continue;
1629 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
1630 return true;
1632 return false;
1635 #else
1636 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1638 return 0;
1641 bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
1643 return test_mem_cgroup_node_reclaimable(memcg, 0, noswap);
1645 #endif
1648 * Scan the hierarchy if needed to reclaim memory. We remember the last child
1649 * we reclaimed from, so that we don't end up penalizing one child extensively
1650 * based on its position in the children list.
1652 * root_memcg is the original ancestor that we've been reclaim from.
1654 * We give up and return to the caller when we visit root_memcg twice.
1655 * (other groups can be removed while we're walking....)
1657 * If shrink==true, for avoiding to free too much, this returns immedieately.
1659 static int mem_cgroup_hierarchical_reclaim(struct mem_cgroup *root_memcg,
1660 struct zone *zone,
1661 gfp_t gfp_mask,
1662 unsigned long reclaim_options,
1663 unsigned long *total_scanned)
1665 struct mem_cgroup *victim;
1666 int ret, total = 0;
1667 int loop = 0;
1668 bool noswap = reclaim_options & MEM_CGROUP_RECLAIM_NOSWAP;
1669 bool shrink = reclaim_options & MEM_CGROUP_RECLAIM_SHRINK;
1670 bool check_soft = reclaim_options & MEM_CGROUP_RECLAIM_SOFT;
1671 unsigned long excess;
1672 unsigned long nr_scanned;
1674 excess = res_counter_soft_limit_excess(&root_memcg->res) >> PAGE_SHIFT;
1676 /* If memsw_is_minimum==1, swap-out is of-no-use. */
1677 if (!check_soft && !shrink && root_memcg->memsw_is_minimum)
1678 noswap = true;
1680 while (1) {
1681 victim = mem_cgroup_select_victim(root_memcg);
1682 if (victim == root_memcg) {
1683 loop++;
1685 * We are not draining per cpu cached charges during
1686 * soft limit reclaim because global reclaim doesn't
1687 * care about charges. It tries to free some memory and
1688 * charges will not give any.
1690 if (!check_soft && loop >= 1)
1691 drain_all_stock_async(root_memcg);
1692 if (loop >= 2) {
1694 * If we have not been able to reclaim
1695 * anything, it might because there are
1696 * no reclaimable pages under this hierarchy
1698 if (!check_soft || !total) {
1699 css_put(&victim->css);
1700 break;
1703 * We want to do more targeted reclaim.
1704 * excess >> 2 is not to excessive so as to
1705 * reclaim too much, nor too less that we keep
1706 * coming back to reclaim from this cgroup
1708 if (total >= (excess >> 2) ||
1709 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS)) {
1710 css_put(&victim->css);
1711 break;
1715 if (!mem_cgroup_reclaimable(victim, noswap)) {
1716 /* this cgroup's local usage == 0 */
1717 css_put(&victim->css);
1718 continue;
1720 /* we use swappiness of local cgroup */
1721 if (check_soft) {
1722 ret = mem_cgroup_shrink_node_zone(victim, gfp_mask,
1723 noswap, zone, &nr_scanned);
1724 *total_scanned += nr_scanned;
1725 } else
1726 ret = try_to_free_mem_cgroup_pages(victim, gfp_mask,
1727 noswap);
1728 css_put(&victim->css);
1730 * At shrinking usage, we can't check we should stop here or
1731 * reclaim more. It's depends on callers. last_scanned_child
1732 * will work enough for keeping fairness under tree.
1734 if (shrink)
1735 return ret;
1736 total += ret;
1737 if (check_soft) {
1738 if (!res_counter_soft_limit_excess(&root_memcg->res))
1739 return total;
1740 } else if (mem_cgroup_margin(root_memcg))
1741 return total;
1743 return total;
1747 * Check OOM-Killer is already running under our hierarchy.
1748 * If someone is running, return false.
1749 * Has to be called with memcg_oom_lock
1751 static bool mem_cgroup_oom_lock(struct mem_cgroup *memcg)
1753 struct mem_cgroup *iter, *failed = NULL;
1754 bool cond = true;
1756 for_each_mem_cgroup_tree_cond(iter, memcg, cond) {
1757 if (iter->oom_lock) {
1759 * this subtree of our hierarchy is already locked
1760 * so we cannot give a lock.
1762 failed = iter;
1763 cond = false;
1764 } else
1765 iter->oom_lock = true;
1768 if (!failed)
1769 return true;
1772 * OK, we failed to lock the whole subtree so we have to clean up
1773 * what we set up to the failing subtree
1775 cond = true;
1776 for_each_mem_cgroup_tree_cond(iter, memcg, cond) {
1777 if (iter == failed) {
1778 cond = false;
1779 continue;
1781 iter->oom_lock = false;
1783 return false;
1787 * Has to be called with memcg_oom_lock
1789 static int mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
1791 struct mem_cgroup *iter;
1793 for_each_mem_cgroup_tree(iter, memcg)
1794 iter->oom_lock = false;
1795 return 0;
1798 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
1800 struct mem_cgroup *iter;
1802 for_each_mem_cgroup_tree(iter, memcg)
1803 atomic_inc(&iter->under_oom);
1806 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
1808 struct mem_cgroup *iter;
1811 * When a new child is created while the hierarchy is under oom,
1812 * mem_cgroup_oom_lock() may not be called. We have to use
1813 * atomic_add_unless() here.
1815 for_each_mem_cgroup_tree(iter, memcg)
1816 atomic_add_unless(&iter->under_oom, -1, 0);
1819 static DEFINE_SPINLOCK(memcg_oom_lock);
1820 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1822 struct oom_wait_info {
1823 struct mem_cgroup *mem;
1824 wait_queue_t wait;
1827 static int memcg_oom_wake_function(wait_queue_t *wait,
1828 unsigned mode, int sync, void *arg)
1830 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg,
1831 *oom_wait_memcg;
1832 struct oom_wait_info *oom_wait_info;
1834 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1835 oom_wait_memcg = oom_wait_info->mem;
1838 * Both of oom_wait_info->mem and wake_mem are stable under us.
1839 * Then we can use css_is_ancestor without taking care of RCU.
1841 if (!mem_cgroup_same_or_subtree(oom_wait_memcg, wake_memcg)
1842 && !mem_cgroup_same_or_subtree(wake_memcg, oom_wait_memcg))
1843 return 0;
1844 return autoremove_wake_function(wait, mode, sync, arg);
1847 static void memcg_wakeup_oom(struct mem_cgroup *memcg)
1849 /* for filtering, pass "memcg" as argument. */
1850 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
1853 static void memcg_oom_recover(struct mem_cgroup *memcg)
1855 if (memcg && atomic_read(&memcg->under_oom))
1856 memcg_wakeup_oom(memcg);
1860 * try to call OOM killer. returns false if we should exit memory-reclaim loop.
1862 bool mem_cgroup_handle_oom(struct mem_cgroup *memcg, gfp_t mask)
1864 struct oom_wait_info owait;
1865 bool locked, need_to_kill;
1867 owait.mem = memcg;
1868 owait.wait.flags = 0;
1869 owait.wait.func = memcg_oom_wake_function;
1870 owait.wait.private = current;
1871 INIT_LIST_HEAD(&owait.wait.task_list);
1872 need_to_kill = true;
1873 mem_cgroup_mark_under_oom(memcg);
1875 /* At first, try to OOM lock hierarchy under memcg.*/
1876 spin_lock(&memcg_oom_lock);
1877 locked = mem_cgroup_oom_lock(memcg);
1879 * Even if signal_pending(), we can't quit charge() loop without
1880 * accounting. So, UNINTERRUPTIBLE is appropriate. But SIGKILL
1881 * under OOM is always welcomed, use TASK_KILLABLE here.
1883 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
1884 if (!locked || memcg->oom_kill_disable)
1885 need_to_kill = false;
1886 if (locked)
1887 mem_cgroup_oom_notify(memcg);
1888 spin_unlock(&memcg_oom_lock);
1890 if (need_to_kill) {
1891 finish_wait(&memcg_oom_waitq, &owait.wait);
1892 mem_cgroup_out_of_memory(memcg, mask);
1893 } else {
1894 schedule();
1895 finish_wait(&memcg_oom_waitq, &owait.wait);
1897 spin_lock(&memcg_oom_lock);
1898 if (locked)
1899 mem_cgroup_oom_unlock(memcg);
1900 memcg_wakeup_oom(memcg);
1901 spin_unlock(&memcg_oom_lock);
1903 mem_cgroup_unmark_under_oom(memcg);
1905 if (test_thread_flag(TIF_MEMDIE) || fatal_signal_pending(current))
1906 return false;
1907 /* Give chance to dying process */
1908 schedule_timeout_uninterruptible(1);
1909 return true;
1913 * Currently used to update mapped file statistics, but the routine can be
1914 * generalized to update other statistics as well.
1916 * Notes: Race condition
1918 * We usually use page_cgroup_lock() for accessing page_cgroup member but
1919 * it tends to be costly. But considering some conditions, we doesn't need
1920 * to do so _always_.
1922 * Considering "charge", lock_page_cgroup() is not required because all
1923 * file-stat operations happen after a page is attached to radix-tree. There
1924 * are no race with "charge".
1926 * Considering "uncharge", we know that memcg doesn't clear pc->mem_cgroup
1927 * at "uncharge" intentionally. So, we always see valid pc->mem_cgroup even
1928 * if there are race with "uncharge". Statistics itself is properly handled
1929 * by flags.
1931 * Considering "move", this is an only case we see a race. To make the race
1932 * small, we check MEM_CGROUP_ON_MOVE percpu value and detect there are
1933 * possibility of race condition. If there is, we take a lock.
1936 void mem_cgroup_update_page_stat(struct page *page,
1937 enum mem_cgroup_page_stat_item idx, int val)
1939 struct mem_cgroup *memcg;
1940 struct page_cgroup *pc = lookup_page_cgroup(page);
1941 bool need_unlock = false;
1942 unsigned long uninitialized_var(flags);
1944 if (unlikely(!pc))
1945 return;
1947 rcu_read_lock();
1948 memcg = pc->mem_cgroup;
1949 if (unlikely(!memcg || !PageCgroupUsed(pc)))
1950 goto out;
1951 /* pc->mem_cgroup is unstable ? */
1952 if (unlikely(mem_cgroup_stealed(memcg)) || PageTransHuge(page)) {
1953 /* take a lock against to access pc->mem_cgroup */
1954 move_lock_page_cgroup(pc, &flags);
1955 need_unlock = true;
1956 memcg = pc->mem_cgroup;
1957 if (!memcg || !PageCgroupUsed(pc))
1958 goto out;
1961 switch (idx) {
1962 case MEMCG_NR_FILE_MAPPED:
1963 if (val > 0)
1964 SetPageCgroupFileMapped(pc);
1965 else if (!page_mapped(page))
1966 ClearPageCgroupFileMapped(pc);
1967 idx = MEM_CGROUP_STAT_FILE_MAPPED;
1968 break;
1969 default:
1970 BUG();
1973 this_cpu_add(memcg->stat->count[idx], val);
1975 out:
1976 if (unlikely(need_unlock))
1977 move_unlock_page_cgroup(pc, &flags);
1978 rcu_read_unlock();
1979 return;
1981 EXPORT_SYMBOL(mem_cgroup_update_page_stat);
1984 * size of first charge trial. "32" comes from vmscan.c's magic value.
1985 * TODO: maybe necessary to use big numbers in big irons.
1987 #define CHARGE_BATCH 32U
1988 struct memcg_stock_pcp {
1989 struct mem_cgroup *cached; /* this never be root cgroup */
1990 unsigned int nr_pages;
1991 struct work_struct work;
1992 unsigned long flags;
1993 #define FLUSHING_CACHED_CHARGE (0)
1995 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
1996 static DEFINE_MUTEX(percpu_charge_mutex);
1999 * Try to consume stocked charge on this cpu. If success, one page is consumed
2000 * from local stock and true is returned. If the stock is 0 or charges from a
2001 * cgroup which is not current target, returns false. This stock will be
2002 * refilled.
2004 static bool consume_stock(struct mem_cgroup *memcg)
2006 struct memcg_stock_pcp *stock;
2007 bool ret = true;
2009 stock = &get_cpu_var(memcg_stock);
2010 if (memcg == stock->cached && stock->nr_pages)
2011 stock->nr_pages--;
2012 else /* need to call res_counter_charge */
2013 ret = false;
2014 put_cpu_var(memcg_stock);
2015 return ret;
2019 * Returns stocks cached in percpu to res_counter and reset cached information.
2021 static void drain_stock(struct memcg_stock_pcp *stock)
2023 struct mem_cgroup *old = stock->cached;
2025 if (stock->nr_pages) {
2026 unsigned long bytes = stock->nr_pages * PAGE_SIZE;
2028 res_counter_uncharge(&old->res, bytes);
2029 if (do_swap_account)
2030 res_counter_uncharge(&old->memsw, bytes);
2031 stock->nr_pages = 0;
2033 stock->cached = NULL;
2037 * This must be called under preempt disabled or must be called by
2038 * a thread which is pinned to local cpu.
2040 static void drain_local_stock(struct work_struct *dummy)
2042 struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
2043 drain_stock(stock);
2044 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2048 * Cache charges(val) which is from res_counter, to local per_cpu area.
2049 * This will be consumed by consume_stock() function, later.
2051 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2053 struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
2055 if (stock->cached != memcg) { /* reset if necessary */
2056 drain_stock(stock);
2057 stock->cached = memcg;
2059 stock->nr_pages += nr_pages;
2060 put_cpu_var(memcg_stock);
2064 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2065 * of the hierarchy under it. sync flag says whether we should block
2066 * until the work is done.
2068 static void drain_all_stock(struct mem_cgroup *root_memcg, bool sync)
2070 int cpu, curcpu;
2072 /* Notify other cpus that system-wide "drain" is running */
2073 get_online_cpus();
2074 curcpu = get_cpu();
2075 for_each_online_cpu(cpu) {
2076 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2077 struct mem_cgroup *memcg;
2079 memcg = stock->cached;
2080 if (!memcg || !stock->nr_pages)
2081 continue;
2082 if (!mem_cgroup_same_or_subtree(root_memcg, memcg))
2083 continue;
2084 if (!test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2085 if (cpu == curcpu)
2086 drain_local_stock(&stock->work);
2087 else
2088 schedule_work_on(cpu, &stock->work);
2091 put_cpu();
2093 if (!sync)
2094 goto out;
2096 for_each_online_cpu(cpu) {
2097 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2098 if (test_bit(FLUSHING_CACHED_CHARGE, &stock->flags))
2099 flush_work(&stock->work);
2101 out:
2102 put_online_cpus();
2106 * Tries to drain stocked charges in other cpus. This function is asynchronous
2107 * and just put a work per cpu for draining localy on each cpu. Caller can
2108 * expects some charges will be back to res_counter later but cannot wait for
2109 * it.
2111 static void drain_all_stock_async(struct mem_cgroup *root_memcg)
2114 * If someone calls draining, avoid adding more kworker runs.
2116 if (!mutex_trylock(&percpu_charge_mutex))
2117 return;
2118 drain_all_stock(root_memcg, false);
2119 mutex_unlock(&percpu_charge_mutex);
2122 /* This is a synchronous drain interface. */
2123 static void drain_all_stock_sync(struct mem_cgroup *root_memcg)
2125 /* called when force_empty is called */
2126 mutex_lock(&percpu_charge_mutex);
2127 drain_all_stock(root_memcg, true);
2128 mutex_unlock(&percpu_charge_mutex);
2132 * This function drains percpu counter value from DEAD cpu and
2133 * move it to local cpu. Note that this function can be preempted.
2135 static void mem_cgroup_drain_pcp_counter(struct mem_cgroup *memcg, int cpu)
2137 int i;
2139 spin_lock(&memcg->pcp_counter_lock);
2140 for (i = 0; i < MEM_CGROUP_STAT_DATA; i++) {
2141 long x = per_cpu(memcg->stat->count[i], cpu);
2143 per_cpu(memcg->stat->count[i], cpu) = 0;
2144 memcg->nocpu_base.count[i] += x;
2146 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
2147 unsigned long x = per_cpu(memcg->stat->events[i], cpu);
2149 per_cpu(memcg->stat->events[i], cpu) = 0;
2150 memcg->nocpu_base.events[i] += x;
2152 /* need to clear ON_MOVE value, works as a kind of lock. */
2153 per_cpu(memcg->stat->count[MEM_CGROUP_ON_MOVE], cpu) = 0;
2154 spin_unlock(&memcg->pcp_counter_lock);
2157 static void synchronize_mem_cgroup_on_move(struct mem_cgroup *memcg, int cpu)
2159 int idx = MEM_CGROUP_ON_MOVE;
2161 spin_lock(&memcg->pcp_counter_lock);
2162 per_cpu(memcg->stat->count[idx], cpu) = memcg->nocpu_base.count[idx];
2163 spin_unlock(&memcg->pcp_counter_lock);
2166 static int __cpuinit memcg_cpu_hotplug_callback(struct notifier_block *nb,
2167 unsigned long action,
2168 void *hcpu)
2170 int cpu = (unsigned long)hcpu;
2171 struct memcg_stock_pcp *stock;
2172 struct mem_cgroup *iter;
2174 if ((action == CPU_ONLINE)) {
2175 for_each_mem_cgroup_all(iter)
2176 synchronize_mem_cgroup_on_move(iter, cpu);
2177 return NOTIFY_OK;
2180 if ((action != CPU_DEAD) || action != CPU_DEAD_FROZEN)
2181 return NOTIFY_OK;
2183 for_each_mem_cgroup_all(iter)
2184 mem_cgroup_drain_pcp_counter(iter, cpu);
2186 stock = &per_cpu(memcg_stock, cpu);
2187 drain_stock(stock);
2188 return NOTIFY_OK;
2192 /* See __mem_cgroup_try_charge() for details */
2193 enum {
2194 CHARGE_OK, /* success */
2195 CHARGE_RETRY, /* need to retry but retry is not bad */
2196 CHARGE_NOMEM, /* we can't do more. return -ENOMEM */
2197 CHARGE_WOULDBLOCK, /* GFP_WAIT wasn't set and no enough res. */
2198 CHARGE_OOM_DIE, /* the current is killed because of OOM */
2201 static int mem_cgroup_do_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2202 unsigned int nr_pages, bool oom_check)
2204 unsigned long csize = nr_pages * PAGE_SIZE;
2205 struct mem_cgroup *mem_over_limit;
2206 struct res_counter *fail_res;
2207 unsigned long flags = 0;
2208 int ret;
2210 ret = res_counter_charge(&memcg->res, csize, &fail_res);
2212 if (likely(!ret)) {
2213 if (!do_swap_account)
2214 return CHARGE_OK;
2215 ret = res_counter_charge(&memcg->memsw, csize, &fail_res);
2216 if (likely(!ret))
2217 return CHARGE_OK;
2219 res_counter_uncharge(&memcg->res, csize);
2220 mem_over_limit = mem_cgroup_from_res_counter(fail_res, memsw);
2221 flags |= MEM_CGROUP_RECLAIM_NOSWAP;
2222 } else
2223 mem_over_limit = mem_cgroup_from_res_counter(fail_res, res);
2225 * nr_pages can be either a huge page (HPAGE_PMD_NR), a batch
2226 * of regular pages (CHARGE_BATCH), or a single regular page (1).
2228 * Never reclaim on behalf of optional batching, retry with a
2229 * single page instead.
2231 if (nr_pages == CHARGE_BATCH)
2232 return CHARGE_RETRY;
2234 if (!(gfp_mask & __GFP_WAIT))
2235 return CHARGE_WOULDBLOCK;
2237 ret = mem_cgroup_hierarchical_reclaim(mem_over_limit, NULL,
2238 gfp_mask, flags, NULL);
2239 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2240 return CHARGE_RETRY;
2242 * Even though the limit is exceeded at this point, reclaim
2243 * may have been able to free some pages. Retry the charge
2244 * before killing the task.
2246 * Only for regular pages, though: huge pages are rather
2247 * unlikely to succeed so close to the limit, and we fall back
2248 * to regular pages anyway in case of failure.
2250 if (nr_pages == 1 && ret)
2251 return CHARGE_RETRY;
2254 * At task move, charge accounts can be doubly counted. So, it's
2255 * better to wait until the end of task_move if something is going on.
2257 if (mem_cgroup_wait_acct_move(mem_over_limit))
2258 return CHARGE_RETRY;
2260 /* If we don't need to call oom-killer at el, return immediately */
2261 if (!oom_check)
2262 return CHARGE_NOMEM;
2263 /* check OOM */
2264 if (!mem_cgroup_handle_oom(mem_over_limit, gfp_mask))
2265 return CHARGE_OOM_DIE;
2267 return CHARGE_RETRY;
2271 * Unlike exported interface, "oom" parameter is added. if oom==true,
2272 * oom-killer can be invoked.
2274 static int __mem_cgroup_try_charge(struct mm_struct *mm,
2275 gfp_t gfp_mask,
2276 unsigned int nr_pages,
2277 struct mem_cgroup **ptr,
2278 bool oom)
2280 unsigned int batch = max(CHARGE_BATCH, nr_pages);
2281 int nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2282 struct mem_cgroup *memcg = NULL;
2283 int ret;
2286 * Unlike gloval-vm's OOM-kill, we're not in memory shortage
2287 * in system level. So, allow to go ahead dying process in addition to
2288 * MEMDIE process.
2290 if (unlikely(test_thread_flag(TIF_MEMDIE)
2291 || fatal_signal_pending(current)))
2292 goto bypass;
2295 * We always charge the cgroup the mm_struct belongs to.
2296 * The mm_struct's mem_cgroup changes on task migration if the
2297 * thread group leader migrates. It's possible that mm is not
2298 * set, if so charge the init_mm (happens for pagecache usage).
2300 if (!*ptr && !mm)
2301 goto bypass;
2302 again:
2303 if (*ptr) { /* css should be a valid one */
2304 memcg = *ptr;
2305 VM_BUG_ON(css_is_removed(&memcg->css));
2306 if (mem_cgroup_is_root(memcg))
2307 goto done;
2308 if (nr_pages == 1 && consume_stock(memcg))
2309 goto done;
2310 css_get(&memcg->css);
2311 } else {
2312 struct task_struct *p;
2314 rcu_read_lock();
2315 p = rcu_dereference(mm->owner);
2317 * Because we don't have task_lock(), "p" can exit.
2318 * In that case, "memcg" can point to root or p can be NULL with
2319 * race with swapoff. Then, we have small risk of mis-accouning.
2320 * But such kind of mis-account by race always happens because
2321 * we don't have cgroup_mutex(). It's overkill and we allo that
2322 * small race, here.
2323 * (*) swapoff at el will charge against mm-struct not against
2324 * task-struct. So, mm->owner can be NULL.
2326 memcg = mem_cgroup_from_task(p);
2327 if (!memcg || mem_cgroup_is_root(memcg)) {
2328 rcu_read_unlock();
2329 goto done;
2331 if (nr_pages == 1 && consume_stock(memcg)) {
2333 * It seems dagerous to access memcg without css_get().
2334 * But considering how consume_stok works, it's not
2335 * necessary. If consume_stock success, some charges
2336 * from this memcg are cached on this cpu. So, we
2337 * don't need to call css_get()/css_tryget() before
2338 * calling consume_stock().
2340 rcu_read_unlock();
2341 goto done;
2343 /* after here, we may be blocked. we need to get refcnt */
2344 if (!css_tryget(&memcg->css)) {
2345 rcu_read_unlock();
2346 goto again;
2348 rcu_read_unlock();
2351 do {
2352 bool oom_check;
2354 /* If killed, bypass charge */
2355 if (fatal_signal_pending(current)) {
2356 css_put(&memcg->css);
2357 goto bypass;
2360 oom_check = false;
2361 if (oom && !nr_oom_retries) {
2362 oom_check = true;
2363 nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2366 ret = mem_cgroup_do_charge(memcg, gfp_mask, batch, oom_check);
2367 switch (ret) {
2368 case CHARGE_OK:
2369 break;
2370 case CHARGE_RETRY: /* not in OOM situation but retry */
2371 batch = nr_pages;
2372 css_put(&memcg->css);
2373 memcg = NULL;
2374 goto again;
2375 case CHARGE_WOULDBLOCK: /* !__GFP_WAIT */
2376 css_put(&memcg->css);
2377 goto nomem;
2378 case CHARGE_NOMEM: /* OOM routine works */
2379 if (!oom) {
2380 css_put(&memcg->css);
2381 goto nomem;
2383 /* If oom, we never return -ENOMEM */
2384 nr_oom_retries--;
2385 break;
2386 case CHARGE_OOM_DIE: /* Killed by OOM Killer */
2387 css_put(&memcg->css);
2388 goto bypass;
2390 } while (ret != CHARGE_OK);
2392 if (batch > nr_pages)
2393 refill_stock(memcg, batch - nr_pages);
2394 css_put(&memcg->css);
2395 done:
2396 *ptr = memcg;
2397 return 0;
2398 nomem:
2399 *ptr = NULL;
2400 return -ENOMEM;
2401 bypass:
2402 *ptr = NULL;
2403 return 0;
2407 * Somemtimes we have to undo a charge we got by try_charge().
2408 * This function is for that and do uncharge, put css's refcnt.
2409 * gotten by try_charge().
2411 static void __mem_cgroup_cancel_charge(struct mem_cgroup *memcg,
2412 unsigned int nr_pages)
2414 if (!mem_cgroup_is_root(memcg)) {
2415 unsigned long bytes = nr_pages * PAGE_SIZE;
2417 res_counter_uncharge(&memcg->res, bytes);
2418 if (do_swap_account)
2419 res_counter_uncharge(&memcg->memsw, bytes);
2424 * A helper function to get mem_cgroup from ID. must be called under
2425 * rcu_read_lock(). The caller must check css_is_removed() or some if
2426 * it's concern. (dropping refcnt from swap can be called against removed
2427 * memcg.)
2429 static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
2431 struct cgroup_subsys_state *css;
2433 /* ID 0 is unused ID */
2434 if (!id)
2435 return NULL;
2436 css = css_lookup(&mem_cgroup_subsys, id);
2437 if (!css)
2438 return NULL;
2439 return container_of(css, struct mem_cgroup, css);
2442 struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
2444 struct mem_cgroup *memcg = NULL;
2445 struct page_cgroup *pc;
2446 unsigned short id;
2447 swp_entry_t ent;
2449 VM_BUG_ON(!PageLocked(page));
2451 pc = lookup_page_cgroup(page);
2452 lock_page_cgroup(pc);
2453 if (PageCgroupUsed(pc)) {
2454 memcg = pc->mem_cgroup;
2455 if (memcg && !css_tryget(&memcg->css))
2456 memcg = NULL;
2457 } else if (PageSwapCache(page)) {
2458 ent.val = page_private(page);
2459 id = lookup_swap_cgroup(ent);
2460 rcu_read_lock();
2461 memcg = mem_cgroup_lookup(id);
2462 if (memcg && !css_tryget(&memcg->css))
2463 memcg = NULL;
2464 rcu_read_unlock();
2466 unlock_page_cgroup(pc);
2467 return memcg;
2470 static void __mem_cgroup_commit_charge(struct mem_cgroup *memcg,
2471 struct page *page,
2472 unsigned int nr_pages,
2473 struct page_cgroup *pc,
2474 enum charge_type ctype)
2476 lock_page_cgroup(pc);
2477 if (unlikely(PageCgroupUsed(pc))) {
2478 unlock_page_cgroup(pc);
2479 __mem_cgroup_cancel_charge(memcg, nr_pages);
2480 return;
2483 * we don't need page_cgroup_lock about tail pages, becase they are not
2484 * accessed by any other context at this point.
2486 pc->mem_cgroup = memcg;
2488 * We access a page_cgroup asynchronously without lock_page_cgroup().
2489 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
2490 * is accessed after testing USED bit. To make pc->mem_cgroup visible
2491 * before USED bit, we need memory barrier here.
2492 * See mem_cgroup_add_lru_list(), etc.
2494 smp_wmb();
2495 switch (ctype) {
2496 case MEM_CGROUP_CHARGE_TYPE_CACHE:
2497 case MEM_CGROUP_CHARGE_TYPE_SHMEM:
2498 SetPageCgroupCache(pc);
2499 SetPageCgroupUsed(pc);
2500 break;
2501 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
2502 ClearPageCgroupCache(pc);
2503 SetPageCgroupUsed(pc);
2504 break;
2505 default:
2506 break;
2509 mem_cgroup_charge_statistics(memcg, PageCgroupCache(pc), nr_pages);
2510 unlock_page_cgroup(pc);
2512 * "charge_statistics" updated event counter. Then, check it.
2513 * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
2514 * if they exceeds softlimit.
2516 memcg_check_events(memcg, page);
2519 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
2521 #define PCGF_NOCOPY_AT_SPLIT ((1 << PCG_LOCK) | (1 << PCG_MOVE_LOCK) |\
2522 (1 << PCG_ACCT_LRU) | (1 << PCG_MIGRATION))
2524 * Because tail pages are not marked as "used", set it. We're under
2525 * zone->lru_lock, 'splitting on pmd' and compund_lock.
2527 void mem_cgroup_split_huge_fixup(struct page *head, struct page *tail)
2529 struct page_cgroup *head_pc = lookup_page_cgroup(head);
2530 struct page_cgroup *tail_pc = lookup_page_cgroup(tail);
2531 unsigned long flags;
2533 if (mem_cgroup_disabled())
2534 return;
2536 * We have no races with charge/uncharge but will have races with
2537 * page state accounting.
2539 move_lock_page_cgroup(head_pc, &flags);
2541 tail_pc->mem_cgroup = head_pc->mem_cgroup;
2542 smp_wmb(); /* see __commit_charge() */
2543 if (PageCgroupAcctLRU(head_pc)) {
2544 enum lru_list lru;
2545 struct mem_cgroup_per_zone *mz;
2548 * LRU flags cannot be copied because we need to add tail
2549 *.page to LRU by generic call and our hook will be called.
2550 * We hold lru_lock, then, reduce counter directly.
2552 lru = page_lru(head);
2553 mz = page_cgroup_zoneinfo(head_pc->mem_cgroup, head);
2554 MEM_CGROUP_ZSTAT(mz, lru) -= 1;
2556 tail_pc->flags = head_pc->flags & ~PCGF_NOCOPY_AT_SPLIT;
2557 move_unlock_page_cgroup(head_pc, &flags);
2559 #endif
2562 * mem_cgroup_move_account - move account of the page
2563 * @page: the page
2564 * @nr_pages: number of regular pages (>1 for huge pages)
2565 * @pc: page_cgroup of the page.
2566 * @from: mem_cgroup which the page is moved from.
2567 * @to: mem_cgroup which the page is moved to. @from != @to.
2568 * @uncharge: whether we should call uncharge and css_put against @from.
2570 * The caller must confirm following.
2571 * - page is not on LRU (isolate_page() is useful.)
2572 * - compound_lock is held when nr_pages > 1
2574 * This function doesn't do "charge" nor css_get to new cgroup. It should be
2575 * done by a caller(__mem_cgroup_try_charge would be useful). If @uncharge is
2576 * true, this function does "uncharge" from old cgroup, but it doesn't if
2577 * @uncharge is false, so a caller should do "uncharge".
2579 static int mem_cgroup_move_account(struct page *page,
2580 unsigned int nr_pages,
2581 struct page_cgroup *pc,
2582 struct mem_cgroup *from,
2583 struct mem_cgroup *to,
2584 bool uncharge)
2586 unsigned long flags;
2587 int ret;
2589 VM_BUG_ON(from == to);
2590 VM_BUG_ON(PageLRU(page));
2592 * The page is isolated from LRU. So, collapse function
2593 * will not handle this page. But page splitting can happen.
2594 * Do this check under compound_page_lock(). The caller should
2595 * hold it.
2597 ret = -EBUSY;
2598 if (nr_pages > 1 && !PageTransHuge(page))
2599 goto out;
2601 lock_page_cgroup(pc);
2603 ret = -EINVAL;
2604 if (!PageCgroupUsed(pc) || pc->mem_cgroup != from)
2605 goto unlock;
2607 move_lock_page_cgroup(pc, &flags);
2609 if (PageCgroupFileMapped(pc)) {
2610 /* Update mapped_file data for mem_cgroup */
2611 preempt_disable();
2612 __this_cpu_dec(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
2613 __this_cpu_inc(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
2614 preempt_enable();
2616 mem_cgroup_charge_statistics(from, PageCgroupCache(pc), -nr_pages);
2617 if (uncharge)
2618 /* This is not "cancel", but cancel_charge does all we need. */
2619 __mem_cgroup_cancel_charge(from, nr_pages);
2621 /* caller should have done css_get */
2622 pc->mem_cgroup = to;
2623 mem_cgroup_charge_statistics(to, PageCgroupCache(pc), nr_pages);
2625 * We charges against "to" which may not have any tasks. Then, "to"
2626 * can be under rmdir(). But in current implementation, caller of
2627 * this function is just force_empty() and move charge, so it's
2628 * guaranteed that "to" is never removed. So, we don't check rmdir
2629 * status here.
2631 move_unlock_page_cgroup(pc, &flags);
2632 ret = 0;
2633 unlock:
2634 unlock_page_cgroup(pc);
2636 * check events
2638 memcg_check_events(to, page);
2639 memcg_check_events(from, page);
2640 out:
2641 return ret;
2645 * move charges to its parent.
2648 static int mem_cgroup_move_parent(struct page *page,
2649 struct page_cgroup *pc,
2650 struct mem_cgroup *child,
2651 gfp_t gfp_mask)
2653 struct cgroup *cg = child->css.cgroup;
2654 struct cgroup *pcg = cg->parent;
2655 struct mem_cgroup *parent;
2656 unsigned int nr_pages;
2657 unsigned long uninitialized_var(flags);
2658 int ret;
2660 /* Is ROOT ? */
2661 if (!pcg)
2662 return -EINVAL;
2664 ret = -EBUSY;
2665 if (!get_page_unless_zero(page))
2666 goto out;
2667 if (isolate_lru_page(page))
2668 goto put;
2670 nr_pages = hpage_nr_pages(page);
2672 parent = mem_cgroup_from_cont(pcg);
2673 ret = __mem_cgroup_try_charge(NULL, gfp_mask, nr_pages, &parent, false);
2674 if (ret || !parent)
2675 goto put_back;
2677 if (nr_pages > 1)
2678 flags = compound_lock_irqsave(page);
2680 ret = mem_cgroup_move_account(page, nr_pages, pc, child, parent, true);
2681 if (ret)
2682 __mem_cgroup_cancel_charge(parent, nr_pages);
2684 if (nr_pages > 1)
2685 compound_unlock_irqrestore(page, flags);
2686 put_back:
2687 putback_lru_page(page);
2688 put:
2689 put_page(page);
2690 out:
2691 return ret;
2695 * Charge the memory controller for page usage.
2696 * Return
2697 * 0 if the charge was successful
2698 * < 0 if the cgroup is over its limit
2700 static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
2701 gfp_t gfp_mask, enum charge_type ctype)
2703 struct mem_cgroup *memcg = NULL;
2704 unsigned int nr_pages = 1;
2705 struct page_cgroup *pc;
2706 bool oom = true;
2707 int ret;
2709 if (PageTransHuge(page)) {
2710 nr_pages <<= compound_order(page);
2711 VM_BUG_ON(!PageTransHuge(page));
2713 * Never OOM-kill a process for a huge page. The
2714 * fault handler will fall back to regular pages.
2716 oom = false;
2719 pc = lookup_page_cgroup(page);
2720 BUG_ON(!pc); /* XXX: remove this and move pc lookup into commit */
2722 ret = __mem_cgroup_try_charge(mm, gfp_mask, nr_pages, &memcg, oom);
2723 if (ret || !memcg)
2724 return ret;
2726 __mem_cgroup_commit_charge(memcg, page, nr_pages, pc, ctype);
2727 return 0;
2730 int mem_cgroup_newpage_charge(struct page *page,
2731 struct mm_struct *mm, gfp_t gfp_mask)
2733 if (mem_cgroup_disabled())
2734 return 0;
2736 * If already mapped, we don't have to account.
2737 * If page cache, page->mapping has address_space.
2738 * But page->mapping may have out-of-use anon_vma pointer,
2739 * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
2740 * is NULL.
2742 if (page_mapped(page) || (page->mapping && !PageAnon(page)))
2743 return 0;
2744 if (unlikely(!mm))
2745 mm = &init_mm;
2746 return mem_cgroup_charge_common(page, mm, gfp_mask,
2747 MEM_CGROUP_CHARGE_TYPE_MAPPED);
2750 static void
2751 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
2752 enum charge_type ctype);
2754 static void
2755 __mem_cgroup_commit_charge_lrucare(struct page *page, struct mem_cgroup *memcg,
2756 enum charge_type ctype)
2758 struct page_cgroup *pc = lookup_page_cgroup(page);
2760 * In some case, SwapCache, FUSE(splice_buf->radixtree), the page
2761 * is already on LRU. It means the page may on some other page_cgroup's
2762 * LRU. Take care of it.
2764 mem_cgroup_lru_del_before_commit(page);
2765 __mem_cgroup_commit_charge(memcg, page, 1, pc, ctype);
2766 mem_cgroup_lru_add_after_commit(page);
2767 return;
2770 int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
2771 gfp_t gfp_mask)
2773 struct mem_cgroup *memcg = NULL;
2774 int ret;
2776 if (mem_cgroup_disabled())
2777 return 0;
2778 if (PageCompound(page))
2779 return 0;
2781 if (unlikely(!mm))
2782 mm = &init_mm;
2784 if (page_is_file_cache(page)) {
2785 ret = __mem_cgroup_try_charge(mm, gfp_mask, 1, &memcg, true);
2786 if (ret || !memcg)
2787 return ret;
2790 * FUSE reuses pages without going through the final
2791 * put that would remove them from the LRU list, make
2792 * sure that they get relinked properly.
2794 __mem_cgroup_commit_charge_lrucare(page, memcg,
2795 MEM_CGROUP_CHARGE_TYPE_CACHE);
2796 return ret;
2798 /* shmem */
2799 if (PageSwapCache(page)) {
2800 ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &memcg);
2801 if (!ret)
2802 __mem_cgroup_commit_charge_swapin(page, memcg,
2803 MEM_CGROUP_CHARGE_TYPE_SHMEM);
2804 } else
2805 ret = mem_cgroup_charge_common(page, mm, gfp_mask,
2806 MEM_CGROUP_CHARGE_TYPE_SHMEM);
2808 return ret;
2812 * While swap-in, try_charge -> commit or cancel, the page is locked.
2813 * And when try_charge() successfully returns, one refcnt to memcg without
2814 * struct page_cgroup is acquired. This refcnt will be consumed by
2815 * "commit()" or removed by "cancel()"
2817 int mem_cgroup_try_charge_swapin(struct mm_struct *mm,
2818 struct page *page,
2819 gfp_t mask, struct mem_cgroup **ptr)
2821 struct mem_cgroup *memcg;
2822 int ret;
2824 *ptr = NULL;
2826 if (mem_cgroup_disabled())
2827 return 0;
2829 if (!do_swap_account)
2830 goto charge_cur_mm;
2832 * A racing thread's fault, or swapoff, may have already updated
2833 * the pte, and even removed page from swap cache: in those cases
2834 * do_swap_page()'s pte_same() test will fail; but there's also a
2835 * KSM case which does need to charge the page.
2837 if (!PageSwapCache(page))
2838 goto charge_cur_mm;
2839 memcg = try_get_mem_cgroup_from_page(page);
2840 if (!memcg)
2841 goto charge_cur_mm;
2842 *ptr = memcg;
2843 ret = __mem_cgroup_try_charge(NULL, mask, 1, ptr, true);
2844 css_put(&memcg->css);
2845 return ret;
2846 charge_cur_mm:
2847 if (unlikely(!mm))
2848 mm = &init_mm;
2849 return __mem_cgroup_try_charge(mm, mask, 1, ptr, true);
2852 static void
2853 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
2854 enum charge_type ctype)
2856 if (mem_cgroup_disabled())
2857 return;
2858 if (!ptr)
2859 return;
2860 cgroup_exclude_rmdir(&ptr->css);
2862 __mem_cgroup_commit_charge_lrucare(page, ptr, ctype);
2864 * Now swap is on-memory. This means this page may be
2865 * counted both as mem and swap....double count.
2866 * Fix it by uncharging from memsw. Basically, this SwapCache is stable
2867 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
2868 * may call delete_from_swap_cache() before reach here.
2870 if (do_swap_account && PageSwapCache(page)) {
2871 swp_entry_t ent = {.val = page_private(page)};
2872 unsigned short id;
2873 struct mem_cgroup *memcg;
2875 id = swap_cgroup_record(ent, 0);
2876 rcu_read_lock();
2877 memcg = mem_cgroup_lookup(id);
2878 if (memcg) {
2880 * This recorded memcg can be obsolete one. So, avoid
2881 * calling css_tryget
2883 if (!mem_cgroup_is_root(memcg))
2884 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
2885 mem_cgroup_swap_statistics(memcg, false);
2886 mem_cgroup_put(memcg);
2888 rcu_read_unlock();
2891 * At swapin, we may charge account against cgroup which has no tasks.
2892 * So, rmdir()->pre_destroy() can be called while we do this charge.
2893 * In that case, we need to call pre_destroy() again. check it here.
2895 cgroup_release_and_wakeup_rmdir(&ptr->css);
2898 void mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr)
2900 __mem_cgroup_commit_charge_swapin(page, ptr,
2901 MEM_CGROUP_CHARGE_TYPE_MAPPED);
2904 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *memcg)
2906 if (mem_cgroup_disabled())
2907 return;
2908 if (!memcg)
2909 return;
2910 __mem_cgroup_cancel_charge(memcg, 1);
2913 static void mem_cgroup_do_uncharge(struct mem_cgroup *memcg,
2914 unsigned int nr_pages,
2915 const enum charge_type ctype)
2917 struct memcg_batch_info *batch = NULL;
2918 bool uncharge_memsw = true;
2920 /* If swapout, usage of swap doesn't decrease */
2921 if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2922 uncharge_memsw = false;
2924 batch = &current->memcg_batch;
2926 * In usual, we do css_get() when we remember memcg pointer.
2927 * But in this case, we keep res->usage until end of a series of
2928 * uncharges. Then, it's ok to ignore memcg's refcnt.
2930 if (!batch->memcg)
2931 batch->memcg = memcg;
2933 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
2934 * In those cases, all pages freed continuously can be expected to be in
2935 * the same cgroup and we have chance to coalesce uncharges.
2936 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
2937 * because we want to do uncharge as soon as possible.
2940 if (!batch->do_batch || test_thread_flag(TIF_MEMDIE))
2941 goto direct_uncharge;
2943 if (nr_pages > 1)
2944 goto direct_uncharge;
2947 * In typical case, batch->memcg == mem. This means we can
2948 * merge a series of uncharges to an uncharge of res_counter.
2949 * If not, we uncharge res_counter ony by one.
2951 if (batch->memcg != memcg)
2952 goto direct_uncharge;
2953 /* remember freed charge and uncharge it later */
2954 batch->nr_pages++;
2955 if (uncharge_memsw)
2956 batch->memsw_nr_pages++;
2957 return;
2958 direct_uncharge:
2959 res_counter_uncharge(&memcg->res, nr_pages * PAGE_SIZE);
2960 if (uncharge_memsw)
2961 res_counter_uncharge(&memcg->memsw, nr_pages * PAGE_SIZE);
2962 if (unlikely(batch->memcg != memcg))
2963 memcg_oom_recover(memcg);
2964 return;
2968 * uncharge if !page_mapped(page)
2970 static struct mem_cgroup *
2971 __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype)
2973 struct mem_cgroup *memcg = NULL;
2974 unsigned int nr_pages = 1;
2975 struct page_cgroup *pc;
2977 if (mem_cgroup_disabled())
2978 return NULL;
2980 if (PageSwapCache(page))
2981 return NULL;
2983 if (PageTransHuge(page)) {
2984 nr_pages <<= compound_order(page);
2985 VM_BUG_ON(!PageTransHuge(page));
2988 * Check if our page_cgroup is valid
2990 pc = lookup_page_cgroup(page);
2991 if (unlikely(!pc || !PageCgroupUsed(pc)))
2992 return NULL;
2994 lock_page_cgroup(pc);
2996 memcg = pc->mem_cgroup;
2998 if (!PageCgroupUsed(pc))
2999 goto unlock_out;
3001 switch (ctype) {
3002 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
3003 case MEM_CGROUP_CHARGE_TYPE_DROP:
3004 /* See mem_cgroup_prepare_migration() */
3005 if (page_mapped(page) || PageCgroupMigration(pc))
3006 goto unlock_out;
3007 break;
3008 case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
3009 if (!PageAnon(page)) { /* Shared memory */
3010 if (page->mapping && !page_is_file_cache(page))
3011 goto unlock_out;
3012 } else if (page_mapped(page)) /* Anon */
3013 goto unlock_out;
3014 break;
3015 default:
3016 break;
3019 mem_cgroup_charge_statistics(memcg, PageCgroupCache(pc), -nr_pages);
3021 ClearPageCgroupUsed(pc);
3023 * pc->mem_cgroup is not cleared here. It will be accessed when it's
3024 * freed from LRU. This is safe because uncharged page is expected not
3025 * to be reused (freed soon). Exception is SwapCache, it's handled by
3026 * special functions.
3029 unlock_page_cgroup(pc);
3031 * even after unlock, we have memcg->res.usage here and this memcg
3032 * will never be freed.
3034 memcg_check_events(memcg, page);
3035 if (do_swap_account && ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT) {
3036 mem_cgroup_swap_statistics(memcg, true);
3037 mem_cgroup_get(memcg);
3039 if (!mem_cgroup_is_root(memcg))
3040 mem_cgroup_do_uncharge(memcg, nr_pages, ctype);
3042 return memcg;
3044 unlock_out:
3045 unlock_page_cgroup(pc);
3046 return NULL;
3049 void mem_cgroup_uncharge_page(struct page *page)
3051 /* early check. */
3052 if (page_mapped(page))
3053 return;
3054 if (page->mapping && !PageAnon(page))
3055 return;
3056 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_MAPPED);
3059 void mem_cgroup_uncharge_cache_page(struct page *page)
3061 VM_BUG_ON(page_mapped(page));
3062 VM_BUG_ON(page->mapping);
3063 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE);
3067 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
3068 * In that cases, pages are freed continuously and we can expect pages
3069 * are in the same memcg. All these calls itself limits the number of
3070 * pages freed at once, then uncharge_start/end() is called properly.
3071 * This may be called prural(2) times in a context,
3074 void mem_cgroup_uncharge_start(void)
3076 current->memcg_batch.do_batch++;
3077 /* We can do nest. */
3078 if (current->memcg_batch.do_batch == 1) {
3079 current->memcg_batch.memcg = NULL;
3080 current->memcg_batch.nr_pages = 0;
3081 current->memcg_batch.memsw_nr_pages = 0;
3085 void mem_cgroup_uncharge_end(void)
3087 struct memcg_batch_info *batch = &current->memcg_batch;
3089 if (!batch->do_batch)
3090 return;
3092 batch->do_batch--;
3093 if (batch->do_batch) /* If stacked, do nothing. */
3094 return;
3096 if (!batch->memcg)
3097 return;
3099 * This "batch->memcg" is valid without any css_get/put etc...
3100 * bacause we hide charges behind us.
3102 if (batch->nr_pages)
3103 res_counter_uncharge(&batch->memcg->res,
3104 batch->nr_pages * PAGE_SIZE);
3105 if (batch->memsw_nr_pages)
3106 res_counter_uncharge(&batch->memcg->memsw,
3107 batch->memsw_nr_pages * PAGE_SIZE);
3108 memcg_oom_recover(batch->memcg);
3109 /* forget this pointer (for sanity check) */
3110 batch->memcg = NULL;
3113 #ifdef CONFIG_SWAP
3115 * called after __delete_from_swap_cache() and drop "page" account.
3116 * memcg information is recorded to swap_cgroup of "ent"
3118 void
3119 mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
3121 struct mem_cgroup *memcg;
3122 int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
3124 if (!swapout) /* this was a swap cache but the swap is unused ! */
3125 ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
3127 memcg = __mem_cgroup_uncharge_common(page, ctype);
3130 * record memcg information, if swapout && memcg != NULL,
3131 * mem_cgroup_get() was called in uncharge().
3133 if (do_swap_account && swapout && memcg)
3134 swap_cgroup_record(ent, css_id(&memcg->css));
3136 #endif
3138 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3140 * called from swap_entry_free(). remove record in swap_cgroup and
3141 * uncharge "memsw" account.
3143 void mem_cgroup_uncharge_swap(swp_entry_t ent)
3145 struct mem_cgroup *memcg;
3146 unsigned short id;
3148 if (!do_swap_account)
3149 return;
3151 id = swap_cgroup_record(ent, 0);
3152 rcu_read_lock();
3153 memcg = mem_cgroup_lookup(id);
3154 if (memcg) {
3156 * We uncharge this because swap is freed.
3157 * This memcg can be obsolete one. We avoid calling css_tryget
3159 if (!mem_cgroup_is_root(memcg))
3160 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
3161 mem_cgroup_swap_statistics(memcg, false);
3162 mem_cgroup_put(memcg);
3164 rcu_read_unlock();
3168 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3169 * @entry: swap entry to be moved
3170 * @from: mem_cgroup which the entry is moved from
3171 * @to: mem_cgroup which the entry is moved to
3172 * @need_fixup: whether we should fixup res_counters and refcounts.
3174 * It succeeds only when the swap_cgroup's record for this entry is the same
3175 * as the mem_cgroup's id of @from.
3177 * Returns 0 on success, -EINVAL on failure.
3179 * The caller must have charged to @to, IOW, called res_counter_charge() about
3180 * both res and memsw, and called css_get().
3182 static int mem_cgroup_move_swap_account(swp_entry_t entry,
3183 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
3185 unsigned short old_id, new_id;
3187 old_id = css_id(&from->css);
3188 new_id = css_id(&to->css);
3190 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
3191 mem_cgroup_swap_statistics(from, false);
3192 mem_cgroup_swap_statistics(to, true);
3194 * This function is only called from task migration context now.
3195 * It postpones res_counter and refcount handling till the end
3196 * of task migration(mem_cgroup_clear_mc()) for performance
3197 * improvement. But we cannot postpone mem_cgroup_get(to)
3198 * because if the process that has been moved to @to does
3199 * swap-in, the refcount of @to might be decreased to 0.
3201 mem_cgroup_get(to);
3202 if (need_fixup) {
3203 if (!mem_cgroup_is_root(from))
3204 res_counter_uncharge(&from->memsw, PAGE_SIZE);
3205 mem_cgroup_put(from);
3207 * we charged both to->res and to->memsw, so we should
3208 * uncharge to->res.
3210 if (!mem_cgroup_is_root(to))
3211 res_counter_uncharge(&to->res, PAGE_SIZE);
3213 return 0;
3215 return -EINVAL;
3217 #else
3218 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
3219 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
3221 return -EINVAL;
3223 #endif
3226 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
3227 * page belongs to.
3229 int mem_cgroup_prepare_migration(struct page *page,
3230 struct page *newpage, struct mem_cgroup **ptr, gfp_t gfp_mask)
3232 struct mem_cgroup *memcg = NULL;
3233 struct page_cgroup *pc;
3234 enum charge_type ctype;
3235 int ret = 0;
3237 *ptr = NULL;
3239 VM_BUG_ON(PageTransHuge(page));
3240 if (mem_cgroup_disabled())
3241 return 0;
3243 pc = lookup_page_cgroup(page);
3244 lock_page_cgroup(pc);
3245 if (PageCgroupUsed(pc)) {
3246 memcg = pc->mem_cgroup;
3247 css_get(&memcg->css);
3249 * At migrating an anonymous page, its mapcount goes down
3250 * to 0 and uncharge() will be called. But, even if it's fully
3251 * unmapped, migration may fail and this page has to be
3252 * charged again. We set MIGRATION flag here and delay uncharge
3253 * until end_migration() is called
3255 * Corner Case Thinking
3256 * A)
3257 * When the old page was mapped as Anon and it's unmap-and-freed
3258 * while migration was ongoing.
3259 * If unmap finds the old page, uncharge() of it will be delayed
3260 * until end_migration(). If unmap finds a new page, it's
3261 * uncharged when it make mapcount to be 1->0. If unmap code
3262 * finds swap_migration_entry, the new page will not be mapped
3263 * and end_migration() will find it(mapcount==0).
3265 * B)
3266 * When the old page was mapped but migraion fails, the kernel
3267 * remaps it. A charge for it is kept by MIGRATION flag even
3268 * if mapcount goes down to 0. We can do remap successfully
3269 * without charging it again.
3271 * C)
3272 * The "old" page is under lock_page() until the end of
3273 * migration, so, the old page itself will not be swapped-out.
3274 * If the new page is swapped out before end_migraton, our
3275 * hook to usual swap-out path will catch the event.
3277 if (PageAnon(page))
3278 SetPageCgroupMigration(pc);
3280 unlock_page_cgroup(pc);
3282 * If the page is not charged at this point,
3283 * we return here.
3285 if (!memcg)
3286 return 0;
3288 *ptr = memcg;
3289 ret = __mem_cgroup_try_charge(NULL, gfp_mask, 1, ptr, false);
3290 css_put(&memcg->css);/* drop extra refcnt */
3291 if (ret || *ptr == NULL) {
3292 if (PageAnon(page)) {
3293 lock_page_cgroup(pc);
3294 ClearPageCgroupMigration(pc);
3295 unlock_page_cgroup(pc);
3297 * The old page may be fully unmapped while we kept it.
3299 mem_cgroup_uncharge_page(page);
3301 return -ENOMEM;
3304 * We charge new page before it's used/mapped. So, even if unlock_page()
3305 * is called before end_migration, we can catch all events on this new
3306 * page. In the case new page is migrated but not remapped, new page's
3307 * mapcount will be finally 0 and we call uncharge in end_migration().
3309 pc = lookup_page_cgroup(newpage);
3310 if (PageAnon(page))
3311 ctype = MEM_CGROUP_CHARGE_TYPE_MAPPED;
3312 else if (page_is_file_cache(page))
3313 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
3314 else
3315 ctype = MEM_CGROUP_CHARGE_TYPE_SHMEM;
3316 __mem_cgroup_commit_charge(memcg, page, 1, pc, ctype);
3317 return ret;
3320 /* remove redundant charge if migration failed*/
3321 void mem_cgroup_end_migration(struct mem_cgroup *memcg,
3322 struct page *oldpage, struct page *newpage, bool migration_ok)
3324 struct page *used, *unused;
3325 struct page_cgroup *pc;
3327 if (!memcg)
3328 return;
3329 /* blocks rmdir() */
3330 cgroup_exclude_rmdir(&memcg->css);
3331 if (!migration_ok) {
3332 used = oldpage;
3333 unused = newpage;
3334 } else {
3335 used = newpage;
3336 unused = oldpage;
3339 * We disallowed uncharge of pages under migration because mapcount
3340 * of the page goes down to zero, temporarly.
3341 * Clear the flag and check the page should be charged.
3343 pc = lookup_page_cgroup(oldpage);
3344 lock_page_cgroup(pc);
3345 ClearPageCgroupMigration(pc);
3346 unlock_page_cgroup(pc);
3348 __mem_cgroup_uncharge_common(unused, MEM_CGROUP_CHARGE_TYPE_FORCE);
3351 * If a page is a file cache, radix-tree replacement is very atomic
3352 * and we can skip this check. When it was an Anon page, its mapcount
3353 * goes down to 0. But because we added MIGRATION flage, it's not
3354 * uncharged yet. There are several case but page->mapcount check
3355 * and USED bit check in mem_cgroup_uncharge_page() will do enough
3356 * check. (see prepare_charge() also)
3358 if (PageAnon(used))
3359 mem_cgroup_uncharge_page(used);
3361 * At migration, we may charge account against cgroup which has no
3362 * tasks.
3363 * So, rmdir()->pre_destroy() can be called while we do this charge.
3364 * In that case, we need to call pre_destroy() again. check it here.
3366 cgroup_release_and_wakeup_rmdir(&memcg->css);
3370 * At replace page cache, newpage is not under any memcg but it's on
3371 * LRU. So, this function doesn't touch res_counter but handles LRU
3372 * in correct way. Both pages are locked so we cannot race with uncharge.
3374 void mem_cgroup_replace_page_cache(struct page *oldpage,
3375 struct page *newpage)
3377 struct mem_cgroup *memcg;
3378 struct page_cgroup *pc;
3379 struct zone *zone;
3380 enum charge_type type = MEM_CGROUP_CHARGE_TYPE_CACHE;
3381 unsigned long flags;
3383 if (mem_cgroup_disabled())
3384 return;
3386 pc = lookup_page_cgroup(oldpage);
3387 /* fix accounting on old pages */
3388 lock_page_cgroup(pc);
3389 memcg = pc->mem_cgroup;
3390 mem_cgroup_charge_statistics(memcg, PageCgroupCache(pc), -1);
3391 ClearPageCgroupUsed(pc);
3392 unlock_page_cgroup(pc);
3394 if (PageSwapBacked(oldpage))
3395 type = MEM_CGROUP_CHARGE_TYPE_SHMEM;
3397 zone = page_zone(newpage);
3398 pc = lookup_page_cgroup(newpage);
3400 * Even if newpage->mapping was NULL before starting replacement,
3401 * the newpage may be on LRU(or pagevec for LRU) already. We lock
3402 * LRU while we overwrite pc->mem_cgroup.
3404 spin_lock_irqsave(&zone->lru_lock, flags);
3405 if (PageLRU(newpage))
3406 del_page_from_lru_list(zone, newpage, page_lru(newpage));
3407 __mem_cgroup_commit_charge(memcg, newpage, 1, pc, type);
3408 if (PageLRU(newpage))
3409 add_page_to_lru_list(zone, newpage, page_lru(newpage));
3410 spin_unlock_irqrestore(&zone->lru_lock, flags);
3413 #ifdef CONFIG_DEBUG_VM
3414 static struct page_cgroup *lookup_page_cgroup_used(struct page *page)
3416 struct page_cgroup *pc;
3418 pc = lookup_page_cgroup(page);
3419 if (likely(pc) && PageCgroupUsed(pc))
3420 return pc;
3421 return NULL;
3424 bool mem_cgroup_bad_page_check(struct page *page)
3426 if (mem_cgroup_disabled())
3427 return false;
3429 return lookup_page_cgroup_used(page) != NULL;
3432 void mem_cgroup_print_bad_page(struct page *page)
3434 struct page_cgroup *pc;
3436 pc = lookup_page_cgroup_used(page);
3437 if (pc) {
3438 int ret = -1;
3439 char *path;
3441 printk(KERN_ALERT "pc:%p pc->flags:%lx pc->mem_cgroup:%p",
3442 pc, pc->flags, pc->mem_cgroup);
3444 path = kmalloc(PATH_MAX, GFP_KERNEL);
3445 if (path) {
3446 rcu_read_lock();
3447 ret = cgroup_path(pc->mem_cgroup->css.cgroup,
3448 path, PATH_MAX);
3449 rcu_read_unlock();
3452 printk(KERN_CONT "(%s)\n",
3453 (ret < 0) ? "cannot get the path" : path);
3454 kfree(path);
3457 #endif
3459 static DEFINE_MUTEX(set_limit_mutex);
3461 static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
3462 unsigned long long val)
3464 int retry_count;
3465 u64 memswlimit, memlimit;
3466 int ret = 0;
3467 int children = mem_cgroup_count_children(memcg);
3468 u64 curusage, oldusage;
3469 int enlarge;
3472 * For keeping hierarchical_reclaim simple, how long we should retry
3473 * is depends on callers. We set our retry-count to be function
3474 * of # of children which we should visit in this loop.
3476 retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
3478 oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
3480 enlarge = 0;
3481 while (retry_count) {
3482 if (signal_pending(current)) {
3483 ret = -EINTR;
3484 break;
3487 * Rather than hide all in some function, I do this in
3488 * open coded manner. You see what this really does.
3489 * We have to guarantee memcg->res.limit < memcg->memsw.limit.
3491 mutex_lock(&set_limit_mutex);
3492 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3493 if (memswlimit < val) {
3494 ret = -EINVAL;
3495 mutex_unlock(&set_limit_mutex);
3496 break;
3499 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3500 if (memlimit < val)
3501 enlarge = 1;
3503 ret = res_counter_set_limit(&memcg->res, val);
3504 if (!ret) {
3505 if (memswlimit == val)
3506 memcg->memsw_is_minimum = true;
3507 else
3508 memcg->memsw_is_minimum = false;
3510 mutex_unlock(&set_limit_mutex);
3512 if (!ret)
3513 break;
3515 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
3516 MEM_CGROUP_RECLAIM_SHRINK,
3517 NULL);
3518 curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
3519 /* Usage is reduced ? */
3520 if (curusage >= oldusage)
3521 retry_count--;
3522 else
3523 oldusage = curusage;
3525 if (!ret && enlarge)
3526 memcg_oom_recover(memcg);
3528 return ret;
3531 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
3532 unsigned long long val)
3534 int retry_count;
3535 u64 memlimit, memswlimit, oldusage, curusage;
3536 int children = mem_cgroup_count_children(memcg);
3537 int ret = -EBUSY;
3538 int enlarge = 0;
3540 /* see mem_cgroup_resize_res_limit */
3541 retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
3542 oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
3543 while (retry_count) {
3544 if (signal_pending(current)) {
3545 ret = -EINTR;
3546 break;
3549 * Rather than hide all in some function, I do this in
3550 * open coded manner. You see what this really does.
3551 * We have to guarantee memcg->res.limit < memcg->memsw.limit.
3553 mutex_lock(&set_limit_mutex);
3554 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3555 if (memlimit > val) {
3556 ret = -EINVAL;
3557 mutex_unlock(&set_limit_mutex);
3558 break;
3560 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3561 if (memswlimit < val)
3562 enlarge = 1;
3563 ret = res_counter_set_limit(&memcg->memsw, val);
3564 if (!ret) {
3565 if (memlimit == val)
3566 memcg->memsw_is_minimum = true;
3567 else
3568 memcg->memsw_is_minimum = false;
3570 mutex_unlock(&set_limit_mutex);
3572 if (!ret)
3573 break;
3575 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
3576 MEM_CGROUP_RECLAIM_NOSWAP |
3577 MEM_CGROUP_RECLAIM_SHRINK,
3578 NULL);
3579 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
3580 /* Usage is reduced ? */
3581 if (curusage >= oldusage)
3582 retry_count--;
3583 else
3584 oldusage = curusage;
3586 if (!ret && enlarge)
3587 memcg_oom_recover(memcg);
3588 return ret;
3591 unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
3592 gfp_t gfp_mask,
3593 unsigned long *total_scanned)
3595 unsigned long nr_reclaimed = 0;
3596 struct mem_cgroup_per_zone *mz, *next_mz = NULL;
3597 unsigned long reclaimed;
3598 int loop = 0;
3599 struct mem_cgroup_tree_per_zone *mctz;
3600 unsigned long long excess;
3601 unsigned long nr_scanned;
3603 if (order > 0)
3604 return 0;
3606 mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone));
3608 * This loop can run a while, specially if mem_cgroup's continuously
3609 * keep exceeding their soft limit and putting the system under
3610 * pressure
3612 do {
3613 if (next_mz)
3614 mz = next_mz;
3615 else
3616 mz = mem_cgroup_largest_soft_limit_node(mctz);
3617 if (!mz)
3618 break;
3620 nr_scanned = 0;
3621 reclaimed = mem_cgroup_hierarchical_reclaim(mz->mem, zone,
3622 gfp_mask,
3623 MEM_CGROUP_RECLAIM_SOFT,
3624 &nr_scanned);
3625 nr_reclaimed += reclaimed;
3626 *total_scanned += nr_scanned;
3627 spin_lock(&mctz->lock);
3630 * If we failed to reclaim anything from this memory cgroup
3631 * it is time to move on to the next cgroup
3633 next_mz = NULL;
3634 if (!reclaimed) {
3635 do {
3637 * Loop until we find yet another one.
3639 * By the time we get the soft_limit lock
3640 * again, someone might have aded the
3641 * group back on the RB tree. Iterate to
3642 * make sure we get a different mem.
3643 * mem_cgroup_largest_soft_limit_node returns
3644 * NULL if no other cgroup is present on
3645 * the tree
3647 next_mz =
3648 __mem_cgroup_largest_soft_limit_node(mctz);
3649 if (next_mz == mz)
3650 css_put(&next_mz->mem->css);
3651 else /* next_mz == NULL or other memcg */
3652 break;
3653 } while (1);
3655 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
3656 excess = res_counter_soft_limit_excess(&mz->mem->res);
3658 * One school of thought says that we should not add
3659 * back the node to the tree if reclaim returns 0.
3660 * But our reclaim could return 0, simply because due
3661 * to priority we are exposing a smaller subset of
3662 * memory to reclaim from. Consider this as a longer
3663 * term TODO.
3665 /* If excess == 0, no tree ops */
3666 __mem_cgroup_insert_exceeded(mz->mem, mz, mctz, excess);
3667 spin_unlock(&mctz->lock);
3668 css_put(&mz->mem->css);
3669 loop++;
3671 * Could not reclaim anything and there are no more
3672 * mem cgroups to try or we seem to be looping without
3673 * reclaiming anything.
3675 if (!nr_reclaimed &&
3676 (next_mz == NULL ||
3677 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3678 break;
3679 } while (!nr_reclaimed);
3680 if (next_mz)
3681 css_put(&next_mz->mem->css);
3682 return nr_reclaimed;
3686 * This routine traverse page_cgroup in given list and drop them all.
3687 * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
3689 static int mem_cgroup_force_empty_list(struct mem_cgroup *memcg,
3690 int node, int zid, enum lru_list lru)
3692 struct zone *zone;
3693 struct mem_cgroup_per_zone *mz;
3694 struct page_cgroup *pc, *busy;
3695 unsigned long flags, loop;
3696 struct list_head *list;
3697 int ret = 0;
3699 zone = &NODE_DATA(node)->node_zones[zid];
3700 mz = mem_cgroup_zoneinfo(memcg, node, zid);
3701 list = &mz->lists[lru];
3703 loop = MEM_CGROUP_ZSTAT(mz, lru);
3704 /* give some margin against EBUSY etc...*/
3705 loop += 256;
3706 busy = NULL;
3707 while (loop--) {
3708 struct page *page;
3710 ret = 0;
3711 spin_lock_irqsave(&zone->lru_lock, flags);
3712 if (list_empty(list)) {
3713 spin_unlock_irqrestore(&zone->lru_lock, flags);
3714 break;
3716 pc = list_entry(list->prev, struct page_cgroup, lru);
3717 if (busy == pc) {
3718 list_move(&pc->lru, list);
3719 busy = NULL;
3720 spin_unlock_irqrestore(&zone->lru_lock, flags);
3721 continue;
3723 spin_unlock_irqrestore(&zone->lru_lock, flags);
3725 page = lookup_cgroup_page(pc);
3727 ret = mem_cgroup_move_parent(page, pc, memcg, GFP_KERNEL);
3728 if (ret == -ENOMEM)
3729 break;
3731 if (ret == -EBUSY || ret == -EINVAL) {
3732 /* found lock contention or "pc" is obsolete. */
3733 busy = pc;
3734 cond_resched();
3735 } else
3736 busy = NULL;
3739 if (!ret && !list_empty(list))
3740 return -EBUSY;
3741 return ret;
3745 * make mem_cgroup's charge to be 0 if there is no task.
3746 * This enables deleting this mem_cgroup.
3748 static int mem_cgroup_force_empty(struct mem_cgroup *memcg, bool free_all)
3750 int ret;
3751 int node, zid, shrink;
3752 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
3753 struct cgroup *cgrp = memcg->css.cgroup;
3755 css_get(&memcg->css);
3757 shrink = 0;
3758 /* should free all ? */
3759 if (free_all)
3760 goto try_to_free;
3761 move_account:
3762 do {
3763 ret = -EBUSY;
3764 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
3765 goto out;
3766 ret = -EINTR;
3767 if (signal_pending(current))
3768 goto out;
3769 /* This is for making all *used* pages to be on LRU. */
3770 lru_add_drain_all();
3771 drain_all_stock_sync(memcg);
3772 ret = 0;
3773 mem_cgroup_start_move(memcg);
3774 for_each_node_state(node, N_HIGH_MEMORY) {
3775 for (zid = 0; !ret && zid < MAX_NR_ZONES; zid++) {
3776 enum lru_list l;
3777 for_each_lru(l) {
3778 ret = mem_cgroup_force_empty_list(memcg,
3779 node, zid, l);
3780 if (ret)
3781 break;
3784 if (ret)
3785 break;
3787 mem_cgroup_end_move(memcg);
3788 memcg_oom_recover(memcg);
3789 /* it seems parent cgroup doesn't have enough mem */
3790 if (ret == -ENOMEM)
3791 goto try_to_free;
3792 cond_resched();
3793 /* "ret" should also be checked to ensure all lists are empty. */
3794 } while (memcg->res.usage > 0 || ret);
3795 out:
3796 css_put(&memcg->css);
3797 return ret;
3799 try_to_free:
3800 /* returns EBUSY if there is a task or if we come here twice. */
3801 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children) || shrink) {
3802 ret = -EBUSY;
3803 goto out;
3805 /* we call try-to-free pages for make this cgroup empty */
3806 lru_add_drain_all();
3807 /* try to free all pages in this cgroup */
3808 shrink = 1;
3809 while (nr_retries && memcg->res.usage > 0) {
3810 int progress;
3812 if (signal_pending(current)) {
3813 ret = -EINTR;
3814 goto out;
3816 progress = try_to_free_mem_cgroup_pages(memcg, GFP_KERNEL,
3817 false);
3818 if (!progress) {
3819 nr_retries--;
3820 /* maybe some writeback is necessary */
3821 congestion_wait(BLK_RW_ASYNC, HZ/10);
3825 lru_add_drain();
3826 /* try move_account...there may be some *locked* pages. */
3827 goto move_account;
3830 int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
3832 return mem_cgroup_force_empty(mem_cgroup_from_cont(cont), true);
3836 static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
3838 return mem_cgroup_from_cont(cont)->use_hierarchy;
3841 static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
3842 u64 val)
3844 int retval = 0;
3845 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
3846 struct cgroup *parent = cont->parent;
3847 struct mem_cgroup *parent_memcg = NULL;
3849 if (parent)
3850 parent_memcg = mem_cgroup_from_cont(parent);
3852 cgroup_lock();
3854 * If parent's use_hierarchy is set, we can't make any modifications
3855 * in the child subtrees. If it is unset, then the change can
3856 * occur, provided the current cgroup has no children.
3858 * For the root cgroup, parent_mem is NULL, we allow value to be
3859 * set if there are no children.
3861 if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
3862 (val == 1 || val == 0)) {
3863 if (list_empty(&cont->children))
3864 memcg->use_hierarchy = val;
3865 else
3866 retval = -EBUSY;
3867 } else
3868 retval = -EINVAL;
3869 cgroup_unlock();
3871 return retval;
3875 static unsigned long mem_cgroup_recursive_stat(struct mem_cgroup *memcg,
3876 enum mem_cgroup_stat_index idx)
3878 struct mem_cgroup *iter;
3879 long val = 0;
3881 /* Per-cpu values can be negative, use a signed accumulator */
3882 for_each_mem_cgroup_tree(iter, memcg)
3883 val += mem_cgroup_read_stat(iter, idx);
3885 if (val < 0) /* race ? */
3886 val = 0;
3887 return val;
3890 static inline u64 mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
3892 u64 val;
3894 if (!mem_cgroup_is_root(memcg)) {
3895 if (!swap)
3896 return res_counter_read_u64(&memcg->res, RES_USAGE);
3897 else
3898 return res_counter_read_u64(&memcg->memsw, RES_USAGE);
3901 val = mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_CACHE);
3902 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_RSS);
3904 if (swap)
3905 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_SWAPOUT);
3907 return val << PAGE_SHIFT;
3910 static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft)
3912 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
3913 u64 val;
3914 int type, name;
3916 type = MEMFILE_TYPE(cft->private);
3917 name = MEMFILE_ATTR(cft->private);
3918 switch (type) {
3919 case _MEM:
3920 if (name == RES_USAGE)
3921 val = mem_cgroup_usage(memcg, false);
3922 else
3923 val = res_counter_read_u64(&memcg->res, name);
3924 break;
3925 case _MEMSWAP:
3926 if (name == RES_USAGE)
3927 val = mem_cgroup_usage(memcg, true);
3928 else
3929 val = res_counter_read_u64(&memcg->memsw, name);
3930 break;
3931 default:
3932 BUG();
3933 break;
3935 return val;
3938 * The user of this function is...
3939 * RES_LIMIT.
3941 static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
3942 const char *buffer)
3944 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
3945 int type, name;
3946 unsigned long long val;
3947 int ret;
3949 type = MEMFILE_TYPE(cft->private);
3950 name = MEMFILE_ATTR(cft->private);
3951 switch (name) {
3952 case RES_LIMIT:
3953 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3954 ret = -EINVAL;
3955 break;
3957 /* This function does all necessary parse...reuse it */
3958 ret = res_counter_memparse_write_strategy(buffer, &val);
3959 if (ret)
3960 break;
3961 if (type == _MEM)
3962 ret = mem_cgroup_resize_limit(memcg, val);
3963 else
3964 ret = mem_cgroup_resize_memsw_limit(memcg, val);
3965 break;
3966 case RES_SOFT_LIMIT:
3967 ret = res_counter_memparse_write_strategy(buffer, &val);
3968 if (ret)
3969 break;
3971 * For memsw, soft limits are hard to implement in terms
3972 * of semantics, for now, we support soft limits for
3973 * control without swap
3975 if (type == _MEM)
3976 ret = res_counter_set_soft_limit(&memcg->res, val);
3977 else
3978 ret = -EINVAL;
3979 break;
3980 default:
3981 ret = -EINVAL; /* should be BUG() ? */
3982 break;
3984 return ret;
3987 static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
3988 unsigned long long *mem_limit, unsigned long long *memsw_limit)
3990 struct cgroup *cgroup;
3991 unsigned long long min_limit, min_memsw_limit, tmp;
3993 min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3994 min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3995 cgroup = memcg->css.cgroup;
3996 if (!memcg->use_hierarchy)
3997 goto out;
3999 while (cgroup->parent) {
4000 cgroup = cgroup->parent;
4001 memcg = mem_cgroup_from_cont(cgroup);
4002 if (!memcg->use_hierarchy)
4003 break;
4004 tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
4005 min_limit = min(min_limit, tmp);
4006 tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
4007 min_memsw_limit = min(min_memsw_limit, tmp);
4009 out:
4010 *mem_limit = min_limit;
4011 *memsw_limit = min_memsw_limit;
4012 return;
4015 static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
4017 struct mem_cgroup *memcg;
4018 int type, name;
4020 memcg = mem_cgroup_from_cont(cont);
4021 type = MEMFILE_TYPE(event);
4022 name = MEMFILE_ATTR(event);
4023 switch (name) {
4024 case RES_MAX_USAGE:
4025 if (type == _MEM)
4026 res_counter_reset_max(&memcg->res);
4027 else
4028 res_counter_reset_max(&memcg->memsw);
4029 break;
4030 case RES_FAILCNT:
4031 if (type == _MEM)
4032 res_counter_reset_failcnt(&memcg->res);
4033 else
4034 res_counter_reset_failcnt(&memcg->memsw);
4035 break;
4038 return 0;
4041 static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp,
4042 struct cftype *cft)
4044 return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate;
4047 #ifdef CONFIG_MMU
4048 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
4049 struct cftype *cft, u64 val)
4051 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4053 if (val >= (1 << NR_MOVE_TYPE))
4054 return -EINVAL;
4056 * We check this value several times in both in can_attach() and
4057 * attach(), so we need cgroup lock to prevent this value from being
4058 * inconsistent.
4060 cgroup_lock();
4061 memcg->move_charge_at_immigrate = val;
4062 cgroup_unlock();
4064 return 0;
4066 #else
4067 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
4068 struct cftype *cft, u64 val)
4070 return -ENOSYS;
4072 #endif
4075 /* For read statistics */
4076 enum {
4077 MCS_CACHE,
4078 MCS_RSS,
4079 MCS_FILE_MAPPED,
4080 MCS_PGPGIN,
4081 MCS_PGPGOUT,
4082 MCS_SWAP,
4083 MCS_PGFAULT,
4084 MCS_PGMAJFAULT,
4085 MCS_INACTIVE_ANON,
4086 MCS_ACTIVE_ANON,
4087 MCS_INACTIVE_FILE,
4088 MCS_ACTIVE_FILE,
4089 MCS_UNEVICTABLE,
4090 NR_MCS_STAT,
4093 struct mcs_total_stat {
4094 s64 stat[NR_MCS_STAT];
4097 struct {
4098 char *local_name;
4099 char *total_name;
4100 } memcg_stat_strings[NR_MCS_STAT] = {
4101 {"cache", "total_cache"},
4102 {"rss", "total_rss"},
4103 {"mapped_file", "total_mapped_file"},
4104 {"pgpgin", "total_pgpgin"},
4105 {"pgpgout", "total_pgpgout"},
4106 {"swap", "total_swap"},
4107 {"pgfault", "total_pgfault"},
4108 {"pgmajfault", "total_pgmajfault"},
4109 {"inactive_anon", "total_inactive_anon"},
4110 {"active_anon", "total_active_anon"},
4111 {"inactive_file", "total_inactive_file"},
4112 {"active_file", "total_active_file"},
4113 {"unevictable", "total_unevictable"}
4117 static void
4118 mem_cgroup_get_local_stat(struct mem_cgroup *memcg, struct mcs_total_stat *s)
4120 s64 val;
4122 /* per cpu stat */
4123 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_CACHE);
4124 s->stat[MCS_CACHE] += val * PAGE_SIZE;
4125 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_RSS);
4126 s->stat[MCS_RSS] += val * PAGE_SIZE;
4127 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_FILE_MAPPED);
4128 s->stat[MCS_FILE_MAPPED] += val * PAGE_SIZE;
4129 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGPGIN);
4130 s->stat[MCS_PGPGIN] += val;
4131 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGPGOUT);
4132 s->stat[MCS_PGPGOUT] += val;
4133 if (do_swap_account) {
4134 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_SWAPOUT);
4135 s->stat[MCS_SWAP] += val * PAGE_SIZE;
4137 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGFAULT);
4138 s->stat[MCS_PGFAULT] += val;
4139 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGMAJFAULT);
4140 s->stat[MCS_PGMAJFAULT] += val;
4142 /* per zone stat */
4143 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_INACTIVE_ANON));
4144 s->stat[MCS_INACTIVE_ANON] += val * PAGE_SIZE;
4145 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_ACTIVE_ANON));
4146 s->stat[MCS_ACTIVE_ANON] += val * PAGE_SIZE;
4147 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_INACTIVE_FILE));
4148 s->stat[MCS_INACTIVE_FILE] += val * PAGE_SIZE;
4149 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_ACTIVE_FILE));
4150 s->stat[MCS_ACTIVE_FILE] += val * PAGE_SIZE;
4151 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_UNEVICTABLE));
4152 s->stat[MCS_UNEVICTABLE] += val * PAGE_SIZE;
4155 static void
4156 mem_cgroup_get_total_stat(struct mem_cgroup *memcg, struct mcs_total_stat *s)
4158 struct mem_cgroup *iter;
4160 for_each_mem_cgroup_tree(iter, memcg)
4161 mem_cgroup_get_local_stat(iter, s);
4164 #ifdef CONFIG_NUMA
4165 static int mem_control_numa_stat_show(struct seq_file *m, void *arg)
4167 int nid;
4168 unsigned long total_nr, file_nr, anon_nr, unevictable_nr;
4169 unsigned long node_nr;
4170 struct cgroup *cont = m->private;
4171 struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
4173 total_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL);
4174 seq_printf(m, "total=%lu", total_nr);
4175 for_each_node_state(nid, N_HIGH_MEMORY) {
4176 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid, LRU_ALL);
4177 seq_printf(m, " N%d=%lu", nid, node_nr);
4179 seq_putc(m, '\n');
4181 file_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL_FILE);
4182 seq_printf(m, "file=%lu", file_nr);
4183 for_each_node_state(nid, N_HIGH_MEMORY) {
4184 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4185 LRU_ALL_FILE);
4186 seq_printf(m, " N%d=%lu", nid, node_nr);
4188 seq_putc(m, '\n');
4190 anon_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL_ANON);
4191 seq_printf(m, "anon=%lu", anon_nr);
4192 for_each_node_state(nid, N_HIGH_MEMORY) {
4193 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4194 LRU_ALL_ANON);
4195 seq_printf(m, " N%d=%lu", nid, node_nr);
4197 seq_putc(m, '\n');
4199 unevictable_nr = mem_cgroup_nr_lru_pages(mem_cont, BIT(LRU_UNEVICTABLE));
4200 seq_printf(m, "unevictable=%lu", unevictable_nr);
4201 for_each_node_state(nid, N_HIGH_MEMORY) {
4202 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4203 BIT(LRU_UNEVICTABLE));
4204 seq_printf(m, " N%d=%lu", nid, node_nr);
4206 seq_putc(m, '\n');
4207 return 0;
4209 #endif /* CONFIG_NUMA */
4211 static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft,
4212 struct cgroup_map_cb *cb)
4214 struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
4215 struct mcs_total_stat mystat;
4216 int i;
4218 memset(&mystat, 0, sizeof(mystat));
4219 mem_cgroup_get_local_stat(mem_cont, &mystat);
4222 for (i = 0; i < NR_MCS_STAT; i++) {
4223 if (i == MCS_SWAP && !do_swap_account)
4224 continue;
4225 cb->fill(cb, memcg_stat_strings[i].local_name, mystat.stat[i]);
4228 /* Hierarchical information */
4230 unsigned long long limit, memsw_limit;
4231 memcg_get_hierarchical_limit(mem_cont, &limit, &memsw_limit);
4232 cb->fill(cb, "hierarchical_memory_limit", limit);
4233 if (do_swap_account)
4234 cb->fill(cb, "hierarchical_memsw_limit", memsw_limit);
4237 memset(&mystat, 0, sizeof(mystat));
4238 mem_cgroup_get_total_stat(mem_cont, &mystat);
4239 for (i = 0; i < NR_MCS_STAT; i++) {
4240 if (i == MCS_SWAP && !do_swap_account)
4241 continue;
4242 cb->fill(cb, memcg_stat_strings[i].total_name, mystat.stat[i]);
4245 #ifdef CONFIG_DEBUG_VM
4247 int nid, zid;
4248 struct mem_cgroup_per_zone *mz;
4249 unsigned long recent_rotated[2] = {0, 0};
4250 unsigned long recent_scanned[2] = {0, 0};
4252 for_each_online_node(nid)
4253 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
4254 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
4256 recent_rotated[0] +=
4257 mz->reclaim_stat.recent_rotated[0];
4258 recent_rotated[1] +=
4259 mz->reclaim_stat.recent_rotated[1];
4260 recent_scanned[0] +=
4261 mz->reclaim_stat.recent_scanned[0];
4262 recent_scanned[1] +=
4263 mz->reclaim_stat.recent_scanned[1];
4265 cb->fill(cb, "recent_rotated_anon", recent_rotated[0]);
4266 cb->fill(cb, "recent_rotated_file", recent_rotated[1]);
4267 cb->fill(cb, "recent_scanned_anon", recent_scanned[0]);
4268 cb->fill(cb, "recent_scanned_file", recent_scanned[1]);
4270 #endif
4272 return 0;
4275 static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
4277 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4279 return mem_cgroup_swappiness(memcg);
4282 static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
4283 u64 val)
4285 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4286 struct mem_cgroup *parent;
4288 if (val > 100)
4289 return -EINVAL;
4291 if (cgrp->parent == NULL)
4292 return -EINVAL;
4294 parent = mem_cgroup_from_cont(cgrp->parent);
4296 cgroup_lock();
4298 /* If under hierarchy, only empty-root can set this value */
4299 if ((parent->use_hierarchy) ||
4300 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
4301 cgroup_unlock();
4302 return -EINVAL;
4305 memcg->swappiness = val;
4307 cgroup_unlock();
4309 return 0;
4312 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4314 struct mem_cgroup_threshold_ary *t;
4315 u64 usage;
4316 int i;
4318 rcu_read_lock();
4319 if (!swap)
4320 t = rcu_dereference(memcg->thresholds.primary);
4321 else
4322 t = rcu_dereference(memcg->memsw_thresholds.primary);
4324 if (!t)
4325 goto unlock;
4327 usage = mem_cgroup_usage(memcg, swap);
4330 * current_threshold points to threshold just below usage.
4331 * If it's not true, a threshold was crossed after last
4332 * call of __mem_cgroup_threshold().
4334 i = t->current_threshold;
4337 * Iterate backward over array of thresholds starting from
4338 * current_threshold and check if a threshold is crossed.
4339 * If none of thresholds below usage is crossed, we read
4340 * only one element of the array here.
4342 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4343 eventfd_signal(t->entries[i].eventfd, 1);
4345 /* i = current_threshold + 1 */
4346 i++;
4349 * Iterate forward over array of thresholds starting from
4350 * current_threshold+1 and check if a threshold is crossed.
4351 * If none of thresholds above usage is crossed, we read
4352 * only one element of the array here.
4354 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4355 eventfd_signal(t->entries[i].eventfd, 1);
4357 /* Update current_threshold */
4358 t->current_threshold = i - 1;
4359 unlock:
4360 rcu_read_unlock();
4363 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4365 while (memcg) {
4366 __mem_cgroup_threshold(memcg, false);
4367 if (do_swap_account)
4368 __mem_cgroup_threshold(memcg, true);
4370 memcg = parent_mem_cgroup(memcg);
4374 static int compare_thresholds(const void *a, const void *b)
4376 const struct mem_cgroup_threshold *_a = a;
4377 const struct mem_cgroup_threshold *_b = b;
4379 return _a->threshold - _b->threshold;
4382 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
4384 struct mem_cgroup_eventfd_list *ev;
4386 list_for_each_entry(ev, &memcg->oom_notify, list)
4387 eventfd_signal(ev->eventfd, 1);
4388 return 0;
4391 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
4393 struct mem_cgroup *iter;
4395 for_each_mem_cgroup_tree(iter, memcg)
4396 mem_cgroup_oom_notify_cb(iter);
4399 static int mem_cgroup_usage_register_event(struct cgroup *cgrp,
4400 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
4402 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4403 struct mem_cgroup_thresholds *thresholds;
4404 struct mem_cgroup_threshold_ary *new;
4405 int type = MEMFILE_TYPE(cft->private);
4406 u64 threshold, usage;
4407 int i, size, ret;
4409 ret = res_counter_memparse_write_strategy(args, &threshold);
4410 if (ret)
4411 return ret;
4413 mutex_lock(&memcg->thresholds_lock);
4415 if (type == _MEM)
4416 thresholds = &memcg->thresholds;
4417 else if (type == _MEMSWAP)
4418 thresholds = &memcg->memsw_thresholds;
4419 else
4420 BUG();
4422 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
4424 /* Check if a threshold crossed before adding a new one */
4425 if (thresholds->primary)
4426 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4428 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
4430 /* Allocate memory for new array of thresholds */
4431 new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
4432 GFP_KERNEL);
4433 if (!new) {
4434 ret = -ENOMEM;
4435 goto unlock;
4437 new->size = size;
4439 /* Copy thresholds (if any) to new array */
4440 if (thresholds->primary) {
4441 memcpy(new->entries, thresholds->primary->entries, (size - 1) *
4442 sizeof(struct mem_cgroup_threshold));
4445 /* Add new threshold */
4446 new->entries[size - 1].eventfd = eventfd;
4447 new->entries[size - 1].threshold = threshold;
4449 /* Sort thresholds. Registering of new threshold isn't time-critical */
4450 sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
4451 compare_thresholds, NULL);
4453 /* Find current threshold */
4454 new->current_threshold = -1;
4455 for (i = 0; i < size; i++) {
4456 if (new->entries[i].threshold < usage) {
4458 * new->current_threshold will not be used until
4459 * rcu_assign_pointer(), so it's safe to increment
4460 * it here.
4462 ++new->current_threshold;
4466 /* Free old spare buffer and save old primary buffer as spare */
4467 kfree(thresholds->spare);
4468 thresholds->spare = thresholds->primary;
4470 rcu_assign_pointer(thresholds->primary, new);
4472 /* To be sure that nobody uses thresholds */
4473 synchronize_rcu();
4475 unlock:
4476 mutex_unlock(&memcg->thresholds_lock);
4478 return ret;
4481 static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,
4482 struct cftype *cft, struct eventfd_ctx *eventfd)
4484 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4485 struct mem_cgroup_thresholds *thresholds;
4486 struct mem_cgroup_threshold_ary *new;
4487 int type = MEMFILE_TYPE(cft->private);
4488 u64 usage;
4489 int i, j, size;
4491 mutex_lock(&memcg->thresholds_lock);
4492 if (type == _MEM)
4493 thresholds = &memcg->thresholds;
4494 else if (type == _MEMSWAP)
4495 thresholds = &memcg->memsw_thresholds;
4496 else
4497 BUG();
4500 * Something went wrong if we trying to unregister a threshold
4501 * if we don't have thresholds
4503 BUG_ON(!thresholds);
4505 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
4507 /* Check if a threshold crossed before removing */
4508 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4510 /* Calculate new number of threshold */
4511 size = 0;
4512 for (i = 0; i < thresholds->primary->size; i++) {
4513 if (thresholds->primary->entries[i].eventfd != eventfd)
4514 size++;
4517 new = thresholds->spare;
4519 /* Set thresholds array to NULL if we don't have thresholds */
4520 if (!size) {
4521 kfree(new);
4522 new = NULL;
4523 goto swap_buffers;
4526 new->size = size;
4528 /* Copy thresholds and find current threshold */
4529 new->current_threshold = -1;
4530 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4531 if (thresholds->primary->entries[i].eventfd == eventfd)
4532 continue;
4534 new->entries[j] = thresholds->primary->entries[i];
4535 if (new->entries[j].threshold < usage) {
4537 * new->current_threshold will not be used
4538 * until rcu_assign_pointer(), so it's safe to increment
4539 * it here.
4541 ++new->current_threshold;
4543 j++;
4546 swap_buffers:
4547 /* Swap primary and spare array */
4548 thresholds->spare = thresholds->primary;
4549 rcu_assign_pointer(thresholds->primary, new);
4551 /* To be sure that nobody uses thresholds */
4552 synchronize_rcu();
4554 mutex_unlock(&memcg->thresholds_lock);
4557 static int mem_cgroup_oom_register_event(struct cgroup *cgrp,
4558 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
4560 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4561 struct mem_cgroup_eventfd_list *event;
4562 int type = MEMFILE_TYPE(cft->private);
4564 BUG_ON(type != _OOM_TYPE);
4565 event = kmalloc(sizeof(*event), GFP_KERNEL);
4566 if (!event)
4567 return -ENOMEM;
4569 spin_lock(&memcg_oom_lock);
4571 event->eventfd = eventfd;
4572 list_add(&event->list, &memcg->oom_notify);
4574 /* already in OOM ? */
4575 if (atomic_read(&memcg->under_oom))
4576 eventfd_signal(eventfd, 1);
4577 spin_unlock(&memcg_oom_lock);
4579 return 0;
4582 static void mem_cgroup_oom_unregister_event(struct cgroup *cgrp,
4583 struct cftype *cft, struct eventfd_ctx *eventfd)
4585 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4586 struct mem_cgroup_eventfd_list *ev, *tmp;
4587 int type = MEMFILE_TYPE(cft->private);
4589 BUG_ON(type != _OOM_TYPE);
4591 spin_lock(&memcg_oom_lock);
4593 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
4594 if (ev->eventfd == eventfd) {
4595 list_del(&ev->list);
4596 kfree(ev);
4600 spin_unlock(&memcg_oom_lock);
4603 static int mem_cgroup_oom_control_read(struct cgroup *cgrp,
4604 struct cftype *cft, struct cgroup_map_cb *cb)
4606 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4608 cb->fill(cb, "oom_kill_disable", memcg->oom_kill_disable);
4610 if (atomic_read(&memcg->under_oom))
4611 cb->fill(cb, "under_oom", 1);
4612 else
4613 cb->fill(cb, "under_oom", 0);
4614 return 0;
4617 static int mem_cgroup_oom_control_write(struct cgroup *cgrp,
4618 struct cftype *cft, u64 val)
4620 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4621 struct mem_cgroup *parent;
4623 /* cannot set to root cgroup and only 0 and 1 are allowed */
4624 if (!cgrp->parent || !((val == 0) || (val == 1)))
4625 return -EINVAL;
4627 parent = mem_cgroup_from_cont(cgrp->parent);
4629 cgroup_lock();
4630 /* oom-kill-disable is a flag for subhierarchy. */
4631 if ((parent->use_hierarchy) ||
4632 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
4633 cgroup_unlock();
4634 return -EINVAL;
4636 memcg->oom_kill_disable = val;
4637 if (!val)
4638 memcg_oom_recover(memcg);
4639 cgroup_unlock();
4640 return 0;
4643 #ifdef CONFIG_NUMA
4644 static const struct file_operations mem_control_numa_stat_file_operations = {
4645 .read = seq_read,
4646 .llseek = seq_lseek,
4647 .release = single_release,
4650 static int mem_control_numa_stat_open(struct inode *unused, struct file *file)
4652 struct cgroup *cont = file->f_dentry->d_parent->d_fsdata;
4654 file->f_op = &mem_control_numa_stat_file_operations;
4655 return single_open(file, mem_control_numa_stat_show, cont);
4657 #endif /* CONFIG_NUMA */
4659 static struct cftype mem_cgroup_files[] = {
4661 .name = "usage_in_bytes",
4662 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
4663 .read_u64 = mem_cgroup_read,
4664 .register_event = mem_cgroup_usage_register_event,
4665 .unregister_event = mem_cgroup_usage_unregister_event,
4668 .name = "max_usage_in_bytes",
4669 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
4670 .trigger = mem_cgroup_reset,
4671 .read_u64 = mem_cgroup_read,
4674 .name = "limit_in_bytes",
4675 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
4676 .write_string = mem_cgroup_write,
4677 .read_u64 = mem_cgroup_read,
4680 .name = "soft_limit_in_bytes",
4681 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
4682 .write_string = mem_cgroup_write,
4683 .read_u64 = mem_cgroup_read,
4686 .name = "failcnt",
4687 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
4688 .trigger = mem_cgroup_reset,
4689 .read_u64 = mem_cgroup_read,
4692 .name = "stat",
4693 .read_map = mem_control_stat_show,
4696 .name = "force_empty",
4697 .trigger = mem_cgroup_force_empty_write,
4700 .name = "use_hierarchy",
4701 .write_u64 = mem_cgroup_hierarchy_write,
4702 .read_u64 = mem_cgroup_hierarchy_read,
4705 .name = "swappiness",
4706 .read_u64 = mem_cgroup_swappiness_read,
4707 .write_u64 = mem_cgroup_swappiness_write,
4710 .name = "move_charge_at_immigrate",
4711 .read_u64 = mem_cgroup_move_charge_read,
4712 .write_u64 = mem_cgroup_move_charge_write,
4715 .name = "oom_control",
4716 .read_map = mem_cgroup_oom_control_read,
4717 .write_u64 = mem_cgroup_oom_control_write,
4718 .register_event = mem_cgroup_oom_register_event,
4719 .unregister_event = mem_cgroup_oom_unregister_event,
4720 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
4722 #ifdef CONFIG_NUMA
4724 .name = "numa_stat",
4725 .open = mem_control_numa_stat_open,
4726 .mode = S_IRUGO,
4728 #endif
4731 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4732 static struct cftype memsw_cgroup_files[] = {
4734 .name = "memsw.usage_in_bytes",
4735 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
4736 .read_u64 = mem_cgroup_read,
4737 .register_event = mem_cgroup_usage_register_event,
4738 .unregister_event = mem_cgroup_usage_unregister_event,
4741 .name = "memsw.max_usage_in_bytes",
4742 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
4743 .trigger = mem_cgroup_reset,
4744 .read_u64 = mem_cgroup_read,
4747 .name = "memsw.limit_in_bytes",
4748 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
4749 .write_string = mem_cgroup_write,
4750 .read_u64 = mem_cgroup_read,
4753 .name = "memsw.failcnt",
4754 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
4755 .trigger = mem_cgroup_reset,
4756 .read_u64 = mem_cgroup_read,
4760 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
4762 if (!do_swap_account)
4763 return 0;
4764 return cgroup_add_files(cont, ss, memsw_cgroup_files,
4765 ARRAY_SIZE(memsw_cgroup_files));
4767 #else
4768 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
4770 return 0;
4772 #endif
4774 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
4776 struct mem_cgroup_per_node *pn;
4777 struct mem_cgroup_per_zone *mz;
4778 enum lru_list l;
4779 int zone, tmp = node;
4781 * This routine is called against possible nodes.
4782 * But it's BUG to call kmalloc() against offline node.
4784 * TODO: this routine can waste much memory for nodes which will
4785 * never be onlined. It's better to use memory hotplug callback
4786 * function.
4788 if (!node_state(node, N_NORMAL_MEMORY))
4789 tmp = -1;
4790 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
4791 if (!pn)
4792 return 1;
4794 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4795 mz = &pn->zoneinfo[zone];
4796 for_each_lru(l)
4797 INIT_LIST_HEAD(&mz->lists[l]);
4798 mz->usage_in_excess = 0;
4799 mz->on_tree = false;
4800 mz->mem = memcg;
4802 memcg->info.nodeinfo[node] = pn;
4803 return 0;
4806 static void free_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
4808 kfree(memcg->info.nodeinfo[node]);
4811 static struct mem_cgroup *mem_cgroup_alloc(void)
4813 struct mem_cgroup *mem;
4814 int size = sizeof(struct mem_cgroup);
4816 /* Can be very big if MAX_NUMNODES is very big */
4817 if (size < PAGE_SIZE)
4818 mem = kzalloc(size, GFP_KERNEL);
4819 else
4820 mem = vzalloc(size);
4822 if (!mem)
4823 return NULL;
4825 mem->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
4826 if (!mem->stat)
4827 goto out_free;
4828 spin_lock_init(&mem->pcp_counter_lock);
4829 return mem;
4831 out_free:
4832 if (size < PAGE_SIZE)
4833 kfree(mem);
4834 else
4835 vfree(mem);
4836 return NULL;
4840 * At destroying mem_cgroup, references from swap_cgroup can remain.
4841 * (scanning all at force_empty is too costly...)
4843 * Instead of clearing all references at force_empty, we remember
4844 * the number of reference from swap_cgroup and free mem_cgroup when
4845 * it goes down to 0.
4847 * Removal of cgroup itself succeeds regardless of refs from swap.
4850 static void __mem_cgroup_free(struct mem_cgroup *memcg)
4852 int node;
4854 mem_cgroup_remove_from_trees(memcg);
4855 free_css_id(&mem_cgroup_subsys, &memcg->css);
4857 for_each_node_state(node, N_POSSIBLE)
4858 free_mem_cgroup_per_zone_info(memcg, node);
4860 free_percpu(memcg->stat);
4861 if (sizeof(struct mem_cgroup) < PAGE_SIZE)
4862 kfree(memcg);
4863 else
4864 vfree(memcg);
4867 static void mem_cgroup_get(struct mem_cgroup *memcg)
4869 atomic_inc(&memcg->refcnt);
4872 static void __mem_cgroup_put(struct mem_cgroup *memcg, int count)
4874 if (atomic_sub_and_test(count, &memcg->refcnt)) {
4875 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
4876 __mem_cgroup_free(memcg);
4877 if (parent)
4878 mem_cgroup_put(parent);
4882 static void mem_cgroup_put(struct mem_cgroup *memcg)
4884 __mem_cgroup_put(memcg, 1);
4888 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
4890 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg)
4892 if (!memcg->res.parent)
4893 return NULL;
4894 return mem_cgroup_from_res_counter(memcg->res.parent, res);
4897 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4898 static void __init enable_swap_cgroup(void)
4900 if (!mem_cgroup_disabled() && really_do_swap_account)
4901 do_swap_account = 1;
4903 #else
4904 static void __init enable_swap_cgroup(void)
4907 #endif
4909 static int mem_cgroup_soft_limit_tree_init(void)
4911 struct mem_cgroup_tree_per_node *rtpn;
4912 struct mem_cgroup_tree_per_zone *rtpz;
4913 int tmp, node, zone;
4915 for_each_node_state(node, N_POSSIBLE) {
4916 tmp = node;
4917 if (!node_state(node, N_NORMAL_MEMORY))
4918 tmp = -1;
4919 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
4920 if (!rtpn)
4921 return 1;
4923 soft_limit_tree.rb_tree_per_node[node] = rtpn;
4925 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4926 rtpz = &rtpn->rb_tree_per_zone[zone];
4927 rtpz->rb_root = RB_ROOT;
4928 spin_lock_init(&rtpz->lock);
4931 return 0;
4934 static struct cgroup_subsys_state * __ref
4935 mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
4937 struct mem_cgroup *memcg, *parent;
4938 long error = -ENOMEM;
4939 int node;
4941 memcg = mem_cgroup_alloc();
4942 if (!memcg)
4943 return ERR_PTR(error);
4945 for_each_node_state(node, N_POSSIBLE)
4946 if (alloc_mem_cgroup_per_zone_info(memcg, node))
4947 goto free_out;
4949 /* root ? */
4950 if (cont->parent == NULL) {
4951 int cpu;
4952 enable_swap_cgroup();
4953 parent = NULL;
4954 if (mem_cgroup_soft_limit_tree_init())
4955 goto free_out;
4956 root_mem_cgroup = memcg;
4957 for_each_possible_cpu(cpu) {
4958 struct memcg_stock_pcp *stock =
4959 &per_cpu(memcg_stock, cpu);
4960 INIT_WORK(&stock->work, drain_local_stock);
4962 hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
4963 } else {
4964 parent = mem_cgroup_from_cont(cont->parent);
4965 memcg->use_hierarchy = parent->use_hierarchy;
4966 memcg->oom_kill_disable = parent->oom_kill_disable;
4969 if (parent && parent->use_hierarchy) {
4970 res_counter_init(&memcg->res, &parent->res);
4971 res_counter_init(&memcg->memsw, &parent->memsw);
4973 * We increment refcnt of the parent to ensure that we can
4974 * safely access it on res_counter_charge/uncharge.
4975 * This refcnt will be decremented when freeing this
4976 * mem_cgroup(see mem_cgroup_put).
4978 mem_cgroup_get(parent);
4979 } else {
4980 res_counter_init(&memcg->res, NULL);
4981 res_counter_init(&memcg->memsw, NULL);
4983 memcg->last_scanned_child = 0;
4984 memcg->last_scanned_node = MAX_NUMNODES;
4985 INIT_LIST_HEAD(&memcg->oom_notify);
4987 if (parent)
4988 memcg->swappiness = mem_cgroup_swappiness(parent);
4989 atomic_set(&memcg->refcnt, 1);
4990 memcg->move_charge_at_immigrate = 0;
4991 mutex_init(&memcg->thresholds_lock);
4992 return &memcg->css;
4993 free_out:
4994 __mem_cgroup_free(memcg);
4995 return ERR_PTR(error);
4998 static int mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
4999 struct cgroup *cont)
5001 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5003 return mem_cgroup_force_empty(memcg, false);
5006 static void mem_cgroup_destroy(struct cgroup_subsys *ss,
5007 struct cgroup *cont)
5009 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5011 mem_cgroup_put(memcg);
5014 static int mem_cgroup_populate(struct cgroup_subsys *ss,
5015 struct cgroup *cont)
5017 int ret;
5019 ret = cgroup_add_files(cont, ss, mem_cgroup_files,
5020 ARRAY_SIZE(mem_cgroup_files));
5022 if (!ret)
5023 ret = register_memsw_files(cont, ss);
5024 return ret;
5027 #ifdef CONFIG_MMU
5028 /* Handlers for move charge at task migration. */
5029 #define PRECHARGE_COUNT_AT_ONCE 256
5030 static int mem_cgroup_do_precharge(unsigned long count)
5032 int ret = 0;
5033 int batch_count = PRECHARGE_COUNT_AT_ONCE;
5034 struct mem_cgroup *memcg = mc.to;
5036 if (mem_cgroup_is_root(memcg)) {
5037 mc.precharge += count;
5038 /* we don't need css_get for root */
5039 return ret;
5041 /* try to charge at once */
5042 if (count > 1) {
5043 struct res_counter *dummy;
5045 * "memcg" cannot be under rmdir() because we've already checked
5046 * by cgroup_lock_live_cgroup() that it is not removed and we
5047 * are still under the same cgroup_mutex. So we can postpone
5048 * css_get().
5050 if (res_counter_charge(&memcg->res, PAGE_SIZE * count, &dummy))
5051 goto one_by_one;
5052 if (do_swap_account && res_counter_charge(&memcg->memsw,
5053 PAGE_SIZE * count, &dummy)) {
5054 res_counter_uncharge(&memcg->res, PAGE_SIZE * count);
5055 goto one_by_one;
5057 mc.precharge += count;
5058 return ret;
5060 one_by_one:
5061 /* fall back to one by one charge */
5062 while (count--) {
5063 if (signal_pending(current)) {
5064 ret = -EINTR;
5065 break;
5067 if (!batch_count--) {
5068 batch_count = PRECHARGE_COUNT_AT_ONCE;
5069 cond_resched();
5071 ret = __mem_cgroup_try_charge(NULL,
5072 GFP_KERNEL, 1, &memcg, false);
5073 if (ret || !memcg)
5074 /* mem_cgroup_clear_mc() will do uncharge later */
5075 return -ENOMEM;
5076 mc.precharge++;
5078 return ret;
5082 * is_target_pte_for_mc - check a pte whether it is valid for move charge
5083 * @vma: the vma the pte to be checked belongs
5084 * @addr: the address corresponding to the pte to be checked
5085 * @ptent: the pte to be checked
5086 * @target: the pointer the target page or swap ent will be stored(can be NULL)
5088 * Returns
5089 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
5090 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5091 * move charge. if @target is not NULL, the page is stored in target->page
5092 * with extra refcnt got(Callers should handle it).
5093 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5094 * target for charge migration. if @target is not NULL, the entry is stored
5095 * in target->ent.
5097 * Called with pte lock held.
5099 union mc_target {
5100 struct page *page;
5101 swp_entry_t ent;
5104 enum mc_target_type {
5105 MC_TARGET_NONE, /* not used */
5106 MC_TARGET_PAGE,
5107 MC_TARGET_SWAP,
5110 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5111 unsigned long addr, pte_t ptent)
5113 struct page *page = vm_normal_page(vma, addr, ptent);
5115 if (!page || !page_mapped(page))
5116 return NULL;
5117 if (PageAnon(page)) {
5118 /* we don't move shared anon */
5119 if (!move_anon() || page_mapcount(page) > 2)
5120 return NULL;
5121 } else if (!move_file())
5122 /* we ignore mapcount for file pages */
5123 return NULL;
5124 if (!get_page_unless_zero(page))
5125 return NULL;
5127 return page;
5130 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5131 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5133 int usage_count;
5134 struct page *page = NULL;
5135 swp_entry_t ent = pte_to_swp_entry(ptent);
5137 if (!move_anon() || non_swap_entry(ent))
5138 return NULL;
5139 usage_count = mem_cgroup_count_swap_user(ent, &page);
5140 if (usage_count > 1) { /* we don't move shared anon */
5141 if (page)
5142 put_page(page);
5143 return NULL;
5145 if (do_swap_account)
5146 entry->val = ent.val;
5148 return page;
5151 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5152 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5154 struct page *page = NULL;
5155 struct inode *inode;
5156 struct address_space *mapping;
5157 pgoff_t pgoff;
5159 if (!vma->vm_file) /* anonymous vma */
5160 return NULL;
5161 if (!move_file())
5162 return NULL;
5164 inode = vma->vm_file->f_path.dentry->d_inode;
5165 mapping = vma->vm_file->f_mapping;
5166 if (pte_none(ptent))
5167 pgoff = linear_page_index(vma, addr);
5168 else /* pte_file(ptent) is true */
5169 pgoff = pte_to_pgoff(ptent);
5171 /* page is moved even if it's not RSS of this task(page-faulted). */
5172 page = find_get_page(mapping, pgoff);
5174 #ifdef CONFIG_SWAP
5175 /* shmem/tmpfs may report page out on swap: account for that too. */
5176 if (radix_tree_exceptional_entry(page)) {
5177 swp_entry_t swap = radix_to_swp_entry(page);
5178 if (do_swap_account)
5179 *entry = swap;
5180 page = find_get_page(&swapper_space, swap.val);
5182 #endif
5183 return page;
5186 static int is_target_pte_for_mc(struct vm_area_struct *vma,
5187 unsigned long addr, pte_t ptent, union mc_target *target)
5189 struct page *page = NULL;
5190 struct page_cgroup *pc;
5191 int ret = 0;
5192 swp_entry_t ent = { .val = 0 };
5194 if (pte_present(ptent))
5195 page = mc_handle_present_pte(vma, addr, ptent);
5196 else if (is_swap_pte(ptent))
5197 page = mc_handle_swap_pte(vma, addr, ptent, &ent);
5198 else if (pte_none(ptent) || pte_file(ptent))
5199 page = mc_handle_file_pte(vma, addr, ptent, &ent);
5201 if (!page && !ent.val)
5202 return 0;
5203 if (page) {
5204 pc = lookup_page_cgroup(page);
5206 * Do only loose check w/o page_cgroup lock.
5207 * mem_cgroup_move_account() checks the pc is valid or not under
5208 * the lock.
5210 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
5211 ret = MC_TARGET_PAGE;
5212 if (target)
5213 target->page = page;
5215 if (!ret || !target)
5216 put_page(page);
5218 /* There is a swap entry and a page doesn't exist or isn't charged */
5219 if (ent.val && !ret &&
5220 css_id(&mc.from->css) == lookup_swap_cgroup(ent)) {
5221 ret = MC_TARGET_SWAP;
5222 if (target)
5223 target->ent = ent;
5225 return ret;
5228 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
5229 unsigned long addr, unsigned long end,
5230 struct mm_walk *walk)
5232 struct vm_area_struct *vma = walk->private;
5233 pte_t *pte;
5234 spinlock_t *ptl;
5236 split_huge_page_pmd(walk->mm, pmd);
5238 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5239 for (; addr != end; pte++, addr += PAGE_SIZE)
5240 if (is_target_pte_for_mc(vma, addr, *pte, NULL))
5241 mc.precharge++; /* increment precharge temporarily */
5242 pte_unmap_unlock(pte - 1, ptl);
5243 cond_resched();
5245 return 0;
5248 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
5250 unsigned long precharge;
5251 struct vm_area_struct *vma;
5253 down_read(&mm->mmap_sem);
5254 for (vma = mm->mmap; vma; vma = vma->vm_next) {
5255 struct mm_walk mem_cgroup_count_precharge_walk = {
5256 .pmd_entry = mem_cgroup_count_precharge_pte_range,
5257 .mm = mm,
5258 .private = vma,
5260 if (is_vm_hugetlb_page(vma))
5261 continue;
5262 walk_page_range(vma->vm_start, vma->vm_end,
5263 &mem_cgroup_count_precharge_walk);
5265 up_read(&mm->mmap_sem);
5267 precharge = mc.precharge;
5268 mc.precharge = 0;
5270 return precharge;
5273 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
5275 unsigned long precharge = mem_cgroup_count_precharge(mm);
5277 VM_BUG_ON(mc.moving_task);
5278 mc.moving_task = current;
5279 return mem_cgroup_do_precharge(precharge);
5282 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5283 static void __mem_cgroup_clear_mc(void)
5285 struct mem_cgroup *from = mc.from;
5286 struct mem_cgroup *to = mc.to;
5288 /* we must uncharge all the leftover precharges from mc.to */
5289 if (mc.precharge) {
5290 __mem_cgroup_cancel_charge(mc.to, mc.precharge);
5291 mc.precharge = 0;
5294 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5295 * we must uncharge here.
5297 if (mc.moved_charge) {
5298 __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
5299 mc.moved_charge = 0;
5301 /* we must fixup refcnts and charges */
5302 if (mc.moved_swap) {
5303 /* uncharge swap account from the old cgroup */
5304 if (!mem_cgroup_is_root(mc.from))
5305 res_counter_uncharge(&mc.from->memsw,
5306 PAGE_SIZE * mc.moved_swap);
5307 __mem_cgroup_put(mc.from, mc.moved_swap);
5309 if (!mem_cgroup_is_root(mc.to)) {
5311 * we charged both to->res and to->memsw, so we should
5312 * uncharge to->res.
5314 res_counter_uncharge(&mc.to->res,
5315 PAGE_SIZE * mc.moved_swap);
5317 /* we've already done mem_cgroup_get(mc.to) */
5318 mc.moved_swap = 0;
5320 memcg_oom_recover(from);
5321 memcg_oom_recover(to);
5322 wake_up_all(&mc.waitq);
5325 static void mem_cgroup_clear_mc(void)
5327 struct mem_cgroup *from = mc.from;
5330 * we must clear moving_task before waking up waiters at the end of
5331 * task migration.
5333 mc.moving_task = NULL;
5334 __mem_cgroup_clear_mc();
5335 spin_lock(&mc.lock);
5336 mc.from = NULL;
5337 mc.to = NULL;
5338 spin_unlock(&mc.lock);
5339 mem_cgroup_end_move(from);
5342 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
5343 struct cgroup *cgroup,
5344 struct task_struct *p)
5346 int ret = 0;
5347 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgroup);
5349 if (memcg->move_charge_at_immigrate) {
5350 struct mm_struct *mm;
5351 struct mem_cgroup *from = mem_cgroup_from_task(p);
5353 VM_BUG_ON(from == memcg);
5355 mm = get_task_mm(p);
5356 if (!mm)
5357 return 0;
5358 /* We move charges only when we move a owner of the mm */
5359 if (mm->owner == p) {
5360 VM_BUG_ON(mc.from);
5361 VM_BUG_ON(mc.to);
5362 VM_BUG_ON(mc.precharge);
5363 VM_BUG_ON(mc.moved_charge);
5364 VM_BUG_ON(mc.moved_swap);
5365 mem_cgroup_start_move(from);
5366 spin_lock(&mc.lock);
5367 mc.from = from;
5368 mc.to = memcg;
5369 spin_unlock(&mc.lock);
5370 /* We set mc.moving_task later */
5372 ret = mem_cgroup_precharge_mc(mm);
5373 if (ret)
5374 mem_cgroup_clear_mc();
5376 mmput(mm);
5378 return ret;
5381 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
5382 struct cgroup *cgroup,
5383 struct task_struct *p)
5385 mem_cgroup_clear_mc();
5388 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
5389 unsigned long addr, unsigned long end,
5390 struct mm_walk *walk)
5392 int ret = 0;
5393 struct vm_area_struct *vma = walk->private;
5394 pte_t *pte;
5395 spinlock_t *ptl;
5397 split_huge_page_pmd(walk->mm, pmd);
5398 retry:
5399 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5400 for (; addr != end; addr += PAGE_SIZE) {
5401 pte_t ptent = *(pte++);
5402 union mc_target target;
5403 int type;
5404 struct page *page;
5405 struct page_cgroup *pc;
5406 swp_entry_t ent;
5408 if (!mc.precharge)
5409 break;
5411 type = is_target_pte_for_mc(vma, addr, ptent, &target);
5412 switch (type) {
5413 case MC_TARGET_PAGE:
5414 page = target.page;
5415 if (isolate_lru_page(page))
5416 goto put;
5417 pc = lookup_page_cgroup(page);
5418 if (!mem_cgroup_move_account(page, 1, pc,
5419 mc.from, mc.to, false)) {
5420 mc.precharge--;
5421 /* we uncharge from mc.from later. */
5422 mc.moved_charge++;
5424 putback_lru_page(page);
5425 put: /* is_target_pte_for_mc() gets the page */
5426 put_page(page);
5427 break;
5428 case MC_TARGET_SWAP:
5429 ent = target.ent;
5430 if (!mem_cgroup_move_swap_account(ent,
5431 mc.from, mc.to, false)) {
5432 mc.precharge--;
5433 /* we fixup refcnts and charges later. */
5434 mc.moved_swap++;
5436 break;
5437 default:
5438 break;
5441 pte_unmap_unlock(pte - 1, ptl);
5442 cond_resched();
5444 if (addr != end) {
5446 * We have consumed all precharges we got in can_attach().
5447 * We try charge one by one, but don't do any additional
5448 * charges to mc.to if we have failed in charge once in attach()
5449 * phase.
5451 ret = mem_cgroup_do_precharge(1);
5452 if (!ret)
5453 goto retry;
5456 return ret;
5459 static void mem_cgroup_move_charge(struct mm_struct *mm)
5461 struct vm_area_struct *vma;
5463 lru_add_drain_all();
5464 retry:
5465 if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
5467 * Someone who are holding the mmap_sem might be waiting in
5468 * waitq. So we cancel all extra charges, wake up all waiters,
5469 * and retry. Because we cancel precharges, we might not be able
5470 * to move enough charges, but moving charge is a best-effort
5471 * feature anyway, so it wouldn't be a big problem.
5473 __mem_cgroup_clear_mc();
5474 cond_resched();
5475 goto retry;
5477 for (vma = mm->mmap; vma; vma = vma->vm_next) {
5478 int ret;
5479 struct mm_walk mem_cgroup_move_charge_walk = {
5480 .pmd_entry = mem_cgroup_move_charge_pte_range,
5481 .mm = mm,
5482 .private = vma,
5484 if (is_vm_hugetlb_page(vma))
5485 continue;
5486 ret = walk_page_range(vma->vm_start, vma->vm_end,
5487 &mem_cgroup_move_charge_walk);
5488 if (ret)
5490 * means we have consumed all precharges and failed in
5491 * doing additional charge. Just abandon here.
5493 break;
5495 up_read(&mm->mmap_sem);
5498 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
5499 struct cgroup *cont,
5500 struct cgroup *old_cont,
5501 struct task_struct *p)
5503 struct mm_struct *mm = get_task_mm(p);
5505 if (mm) {
5506 if (mc.to)
5507 mem_cgroup_move_charge(mm);
5508 put_swap_token(mm);
5509 mmput(mm);
5511 if (mc.to)
5512 mem_cgroup_clear_mc();
5514 #else /* !CONFIG_MMU */
5515 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
5516 struct cgroup *cgroup,
5517 struct task_struct *p)
5519 return 0;
5521 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
5522 struct cgroup *cgroup,
5523 struct task_struct *p)
5526 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
5527 struct cgroup *cont,
5528 struct cgroup *old_cont,
5529 struct task_struct *p)
5532 #endif
5534 struct cgroup_subsys mem_cgroup_subsys = {
5535 .name = "memory",
5536 .subsys_id = mem_cgroup_subsys_id,
5537 .create = mem_cgroup_create,
5538 .pre_destroy = mem_cgroup_pre_destroy,
5539 .destroy = mem_cgroup_destroy,
5540 .populate = mem_cgroup_populate,
5541 .can_attach = mem_cgroup_can_attach,
5542 .cancel_attach = mem_cgroup_cancel_attach,
5543 .attach = mem_cgroup_move_task,
5544 .early_init = 0,
5545 .use_id = 1,
5548 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
5549 static int __init enable_swap_account(char *s)
5551 /* consider enabled if no parameter or 1 is given */
5552 if (!strcmp(s, "1"))
5553 really_do_swap_account = 1;
5554 else if (!strcmp(s, "0"))
5555 really_do_swap_account = 0;
5556 return 1;
5558 __setup("swapaccount=", enable_swap_account);
5560 #endif