This client driver allows you to use a GPIO pin as a source for PPS
[linux-2.6/next.git] / mm / memcontrol.c
blob54b35b35ea04477748cd62104ee3e02d6a7a53b6
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);
208 enum {
209 SCAN_BY_LIMIT,
210 SCAN_BY_SYSTEM,
211 NR_SCAN_CONTEXT,
212 SCAN_BY_SHRINK, /* not recorded now */
215 enum {
216 SCAN,
217 SCAN_ANON,
218 SCAN_FILE,
219 ROTATE,
220 ROTATE_ANON,
221 ROTATE_FILE,
222 FREED,
223 FREED_ANON,
224 FREED_FILE,
225 ELAPSED,
226 NR_SCANSTATS,
229 struct scanstat {
230 spinlock_t lock;
231 unsigned long stats[NR_SCAN_CONTEXT][NR_SCANSTATS];
232 unsigned long rootstats[NR_SCAN_CONTEXT][NR_SCANSTATS];
235 const char *scanstat_string[NR_SCANSTATS] = {
236 "scanned_pages",
237 "scanned_anon_pages",
238 "scanned_file_pages",
239 "rotated_pages",
240 "rotated_anon_pages",
241 "rotated_file_pages",
242 "freed_pages",
243 "freed_anon_pages",
244 "freed_file_pages",
245 "elapsed_ns",
247 #define SCANSTAT_WORD_LIMIT "_by_limit"
248 #define SCANSTAT_WORD_SYSTEM "_by_system"
249 #define SCANSTAT_WORD_HIERARCHY "_under_hierarchy"
253 * The memory controller data structure. The memory controller controls both
254 * page cache and RSS per cgroup. We would eventually like to provide
255 * statistics based on the statistics developed by Rik Van Riel for clock-pro,
256 * to help the administrator determine what knobs to tune.
258 * TODO: Add a water mark for the memory controller. Reclaim will begin when
259 * we hit the water mark. May be even add a low water mark, such that
260 * no reclaim occurs from a cgroup at it's low water mark, this is
261 * a feature that will be implemented much later in the future.
263 struct mem_cgroup {
264 struct cgroup_subsys_state css;
266 * the counter to account for memory usage
268 struct res_counter res;
270 * the counter to account for mem+swap usage.
272 struct res_counter memsw;
274 * Per cgroup active and inactive list, similar to the
275 * per zone LRU lists.
277 struct mem_cgroup_lru_info info;
279 * While reclaiming in a hierarchy, we cache the last child we
280 * reclaimed from.
282 int last_scanned_child;
283 int last_scanned_node;
284 #if MAX_NUMNODES > 1
285 nodemask_t scan_nodes;
286 atomic_t numainfo_events;
287 atomic_t numainfo_updating;
288 #endif
290 * Should the accounting and control be hierarchical, per subtree?
292 bool use_hierarchy;
294 bool oom_lock;
295 atomic_t under_oom;
297 atomic_t refcnt;
299 int swappiness;
300 /* OOM-Killer disable */
301 int oom_kill_disable;
303 /* set when res.limit == memsw.limit */
304 bool memsw_is_minimum;
306 /* protect arrays of thresholds */
307 struct mutex thresholds_lock;
309 /* thresholds for memory usage. RCU-protected */
310 struct mem_cgroup_thresholds thresholds;
312 /* thresholds for mem+swap usage. RCU-protected */
313 struct mem_cgroup_thresholds memsw_thresholds;
315 /* For oom notifier event fd */
316 struct list_head oom_notify;
317 /* For recording LRU-scan statistics */
318 struct scanstat scanstat;
320 * Should we move charges of a task when a task is moved into this
321 * mem_cgroup ? And what type of charges should we move ?
323 unsigned long move_charge_at_immigrate;
325 * percpu counter.
327 struct mem_cgroup_stat_cpu *stat;
329 * used when a cpu is offlined or other synchronizations
330 * See mem_cgroup_read_stat().
332 struct mem_cgroup_stat_cpu nocpu_base;
333 spinlock_t pcp_counter_lock;
336 /* Stuffs for move charges at task migration. */
338 * Types of charges to be moved. "move_charge_at_immitgrate" is treated as a
339 * left-shifted bitmap of these types.
341 enum move_type {
342 MOVE_CHARGE_TYPE_ANON, /* private anonymous page and swap of it */
343 MOVE_CHARGE_TYPE_FILE, /* file page(including tmpfs) and swap of it */
344 NR_MOVE_TYPE,
347 /* "mc" and its members are protected by cgroup_mutex */
348 static struct move_charge_struct {
349 spinlock_t lock; /* for from, to */
350 struct mem_cgroup *from;
351 struct mem_cgroup *to;
352 unsigned long precharge;
353 unsigned long moved_charge;
354 unsigned long moved_swap;
355 struct task_struct *moving_task; /* a task moving charges */
356 wait_queue_head_t waitq; /* a waitq for other context */
357 } mc = {
358 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
359 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
362 static bool move_anon(void)
364 return test_bit(MOVE_CHARGE_TYPE_ANON,
365 &mc.to->move_charge_at_immigrate);
368 static bool move_file(void)
370 return test_bit(MOVE_CHARGE_TYPE_FILE,
371 &mc.to->move_charge_at_immigrate);
375 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
376 * limit reclaim to prevent infinite loops, if they ever occur.
378 #define MEM_CGROUP_MAX_RECLAIM_LOOPS (100)
379 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS (2)
381 enum charge_type {
382 MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
383 MEM_CGROUP_CHARGE_TYPE_MAPPED,
384 MEM_CGROUP_CHARGE_TYPE_SHMEM, /* used by page migration of shmem */
385 MEM_CGROUP_CHARGE_TYPE_FORCE, /* used by force_empty */
386 MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
387 MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
388 NR_CHARGE_TYPE,
391 /* for encoding cft->private value on file */
392 #define _MEM (0)
393 #define _MEMSWAP (1)
394 #define _OOM_TYPE (2)
395 #define MEMFILE_PRIVATE(x, val) (((x) << 16) | (val))
396 #define MEMFILE_TYPE(val) (((val) >> 16) & 0xffff)
397 #define MEMFILE_ATTR(val) ((val) & 0xffff)
398 /* Used for OOM nofiier */
399 #define OOM_CONTROL (0)
402 * Reclaim flags for mem_cgroup_hierarchical_reclaim
404 #define MEM_CGROUP_RECLAIM_NOSWAP_BIT 0x0
405 #define MEM_CGROUP_RECLAIM_NOSWAP (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
406 #define MEM_CGROUP_RECLAIM_SHRINK_BIT 0x1
407 #define MEM_CGROUP_RECLAIM_SHRINK (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
408 #define MEM_CGROUP_RECLAIM_SOFT_BIT 0x2
409 #define MEM_CGROUP_RECLAIM_SOFT (1 << MEM_CGROUP_RECLAIM_SOFT_BIT)
411 static void mem_cgroup_get(struct mem_cgroup *memcg);
412 static void mem_cgroup_put(struct mem_cgroup *memcg);
413 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg);
414 static void drain_all_stock_async(struct mem_cgroup *memcg);
416 static struct mem_cgroup_per_zone *
417 mem_cgroup_zoneinfo(struct mem_cgroup *memcg, int nid, int zid)
419 return &memcg->info.nodeinfo[nid]->zoneinfo[zid];
422 struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *memcg)
424 return &memcg->css;
427 static struct mem_cgroup_per_zone *
428 page_cgroup_zoneinfo(struct mem_cgroup *memcg, struct page *page)
430 int nid = page_to_nid(page);
431 int zid = page_zonenum(page);
433 return mem_cgroup_zoneinfo(memcg, nid, zid);
436 static struct mem_cgroup_tree_per_zone *
437 soft_limit_tree_node_zone(int nid, int zid)
439 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
442 static struct mem_cgroup_tree_per_zone *
443 soft_limit_tree_from_page(struct page *page)
445 int nid = page_to_nid(page);
446 int zid = page_zonenum(page);
448 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
451 static void
452 __mem_cgroup_insert_exceeded(struct mem_cgroup *memcg,
453 struct mem_cgroup_per_zone *mz,
454 struct mem_cgroup_tree_per_zone *mctz,
455 unsigned long long new_usage_in_excess)
457 struct rb_node **p = &mctz->rb_root.rb_node;
458 struct rb_node *parent = NULL;
459 struct mem_cgroup_per_zone *mz_node;
461 if (mz->on_tree)
462 return;
464 mz->usage_in_excess = new_usage_in_excess;
465 if (!mz->usage_in_excess)
466 return;
467 while (*p) {
468 parent = *p;
469 mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
470 tree_node);
471 if (mz->usage_in_excess < mz_node->usage_in_excess)
472 p = &(*p)->rb_left;
474 * We can't avoid mem cgroups that are over their soft
475 * limit by the same amount
477 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
478 p = &(*p)->rb_right;
480 rb_link_node(&mz->tree_node, parent, p);
481 rb_insert_color(&mz->tree_node, &mctz->rb_root);
482 mz->on_tree = true;
485 static void
486 __mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
487 struct mem_cgroup_per_zone *mz,
488 struct mem_cgroup_tree_per_zone *mctz)
490 if (!mz->on_tree)
491 return;
492 rb_erase(&mz->tree_node, &mctz->rb_root);
493 mz->on_tree = false;
496 static void
497 mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
498 struct mem_cgroup_per_zone *mz,
499 struct mem_cgroup_tree_per_zone *mctz)
501 spin_lock(&mctz->lock);
502 __mem_cgroup_remove_exceeded(memcg, mz, mctz);
503 spin_unlock(&mctz->lock);
507 static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
509 unsigned long long excess;
510 struct mem_cgroup_per_zone *mz;
511 struct mem_cgroup_tree_per_zone *mctz;
512 int nid = page_to_nid(page);
513 int zid = page_zonenum(page);
514 mctz = soft_limit_tree_from_page(page);
517 * Necessary to update all ancestors when hierarchy is used.
518 * because their event counter is not touched.
520 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
521 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
522 excess = res_counter_soft_limit_excess(&memcg->res);
524 * We have to update the tree if mz is on RB-tree or
525 * mem is over its softlimit.
527 if (excess || mz->on_tree) {
528 spin_lock(&mctz->lock);
529 /* if on-tree, remove it */
530 if (mz->on_tree)
531 __mem_cgroup_remove_exceeded(memcg, mz, mctz);
533 * Insert again. mz->usage_in_excess will be updated.
534 * If excess is 0, no tree ops.
536 __mem_cgroup_insert_exceeded(memcg, mz, mctz, excess);
537 spin_unlock(&mctz->lock);
542 static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
544 int node, zone;
545 struct mem_cgroup_per_zone *mz;
546 struct mem_cgroup_tree_per_zone *mctz;
548 for_each_node_state(node, N_POSSIBLE) {
549 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
550 mz = mem_cgroup_zoneinfo(memcg, node, zone);
551 mctz = soft_limit_tree_node_zone(node, zone);
552 mem_cgroup_remove_exceeded(memcg, mz, mctz);
557 static struct mem_cgroup_per_zone *
558 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
560 struct rb_node *rightmost = NULL;
561 struct mem_cgroup_per_zone *mz;
563 retry:
564 mz = NULL;
565 rightmost = rb_last(&mctz->rb_root);
566 if (!rightmost)
567 goto done; /* Nothing to reclaim from */
569 mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
571 * Remove the node now but someone else can add it back,
572 * we will to add it back at the end of reclaim to its correct
573 * position in the tree.
575 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
576 if (!res_counter_soft_limit_excess(&mz->mem->res) ||
577 !css_tryget(&mz->mem->css))
578 goto retry;
579 done:
580 return mz;
583 static struct mem_cgroup_per_zone *
584 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
586 struct mem_cgroup_per_zone *mz;
588 spin_lock(&mctz->lock);
589 mz = __mem_cgroup_largest_soft_limit_node(mctz);
590 spin_unlock(&mctz->lock);
591 return mz;
595 * Implementation Note: reading percpu statistics for memcg.
597 * Both of vmstat[] and percpu_counter has threshold and do periodic
598 * synchronization to implement "quick" read. There are trade-off between
599 * reading cost and precision of value. Then, we may have a chance to implement
600 * a periodic synchronizion of counter in memcg's counter.
602 * But this _read() function is used for user interface now. The user accounts
603 * memory usage by memory cgroup and he _always_ requires exact value because
604 * he accounts memory. Even if we provide quick-and-fuzzy read, we always
605 * have to visit all online cpus and make sum. So, for now, unnecessary
606 * synchronization is not implemented. (just implemented for cpu hotplug)
608 * If there are kernel internal actions which can make use of some not-exact
609 * value, and reading all cpu value can be performance bottleneck in some
610 * common workload, threashold and synchonization as vmstat[] should be
611 * implemented.
613 static long mem_cgroup_read_stat(struct mem_cgroup *memcg,
614 enum mem_cgroup_stat_index idx)
616 long val = 0;
617 int cpu;
619 get_online_cpus();
620 for_each_online_cpu(cpu)
621 val += per_cpu(memcg->stat->count[idx], cpu);
622 #ifdef CONFIG_HOTPLUG_CPU
623 spin_lock(&memcg->pcp_counter_lock);
624 val += memcg->nocpu_base.count[idx];
625 spin_unlock(&memcg->pcp_counter_lock);
626 #endif
627 put_online_cpus();
628 return val;
631 static void mem_cgroup_swap_statistics(struct mem_cgroup *memcg,
632 bool charge)
634 int val = (charge) ? 1 : -1;
635 this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_SWAPOUT], val);
638 void mem_cgroup_pgfault(struct mem_cgroup *memcg, int val)
640 this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_PGFAULT], val);
643 void mem_cgroup_pgmajfault(struct mem_cgroup *memcg, int val)
645 this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_PGMAJFAULT], val);
648 static unsigned long mem_cgroup_read_events(struct mem_cgroup *memcg,
649 enum mem_cgroup_events_index idx)
651 unsigned long val = 0;
652 int cpu;
654 for_each_online_cpu(cpu)
655 val += per_cpu(memcg->stat->events[idx], cpu);
656 #ifdef CONFIG_HOTPLUG_CPU
657 spin_lock(&memcg->pcp_counter_lock);
658 val += memcg->nocpu_base.events[idx];
659 spin_unlock(&memcg->pcp_counter_lock);
660 #endif
661 return val;
664 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
665 bool file, int nr_pages)
667 if (file)
668 this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_CACHE],
669 nr_pages);
670 else
671 this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS],
672 nr_pages);
674 /* pagein of a big page is an event. So, ignore page size */
675 if (nr_pages > 0) {
676 this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGIN]);
677 } else {
678 this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGOUT]);
679 nr_pages = -nr_pages; /* for event */
682 this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_COUNT], nr_pages);
685 unsigned long
686 mem_cgroup_zone_nr_lru_pages(struct mem_cgroup *memcg, int nid, int zid,
687 unsigned int lru_mask)
689 struct mem_cgroup_per_zone *mz;
690 enum lru_list l;
691 unsigned long ret = 0;
693 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
695 for_each_lru(l) {
696 if (BIT(l) & lru_mask)
697 ret += MEM_CGROUP_ZSTAT(mz, l);
699 return ret;
702 static unsigned long
703 mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
704 int nid, unsigned int lru_mask)
706 u64 total = 0;
707 int zid;
709 for (zid = 0; zid < MAX_NR_ZONES; zid++)
710 total += mem_cgroup_zone_nr_lru_pages(memcg,
711 nid, zid, lru_mask);
713 return total;
716 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
717 unsigned int lru_mask)
719 int nid;
720 u64 total = 0;
722 for_each_node_state(nid, N_HIGH_MEMORY)
723 total += mem_cgroup_node_nr_lru_pages(memcg, nid, lru_mask);
724 return total;
727 static bool __memcg_event_check(struct mem_cgroup *memcg, int target)
729 unsigned long val, next;
731 val = this_cpu_read(memcg->stat->events[MEM_CGROUP_EVENTS_COUNT]);
732 next = this_cpu_read(memcg->stat->targets[target]);
733 /* from time_after() in jiffies.h */
734 return ((long)next - (long)val < 0);
737 static void __mem_cgroup_target_update(struct mem_cgroup *memcg, int target)
739 unsigned long val, next;
741 val = this_cpu_read(memcg->stat->events[MEM_CGROUP_EVENTS_COUNT]);
743 switch (target) {
744 case MEM_CGROUP_TARGET_THRESH:
745 next = val + THRESHOLDS_EVENTS_TARGET;
746 break;
747 case MEM_CGROUP_TARGET_SOFTLIMIT:
748 next = val + SOFTLIMIT_EVENTS_TARGET;
749 break;
750 case MEM_CGROUP_TARGET_NUMAINFO:
751 next = val + NUMAINFO_EVENTS_TARGET;
752 break;
753 default:
754 return;
757 this_cpu_write(memcg->stat->targets[target], next);
761 * Check events in order.
764 static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
766 /* threshold event is triggered in finer grain than soft limit */
767 if (unlikely(__memcg_event_check(memcg, MEM_CGROUP_TARGET_THRESH))) {
768 mem_cgroup_threshold(memcg);
769 __mem_cgroup_target_update(memcg, MEM_CGROUP_TARGET_THRESH);
770 if (unlikely(__memcg_event_check(memcg,
771 MEM_CGROUP_TARGET_SOFTLIMIT))) {
772 mem_cgroup_update_tree(memcg, page);
773 __mem_cgroup_target_update(memcg,
774 MEM_CGROUP_TARGET_SOFTLIMIT);
776 #if MAX_NUMNODES > 1
777 if (unlikely(__memcg_event_check(memcg,
778 MEM_CGROUP_TARGET_NUMAINFO))) {
779 atomic_inc(&memcg->numainfo_events);
780 __mem_cgroup_target_update(memcg,
781 MEM_CGROUP_TARGET_NUMAINFO);
783 #endif
787 static struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
789 return container_of(cgroup_subsys_state(cont,
790 mem_cgroup_subsys_id), struct mem_cgroup,
791 css);
794 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
797 * mm_update_next_owner() may clear mm->owner to NULL
798 * if it races with swapoff, page migration, etc.
799 * So this can be called with p == NULL.
801 if (unlikely(!p))
802 return NULL;
804 return container_of(task_subsys_state(p, mem_cgroup_subsys_id),
805 struct mem_cgroup, css);
808 struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
810 struct mem_cgroup *memcg = NULL;
812 if (!mm)
813 return NULL;
815 * Because we have no locks, mm->owner's may be being moved to other
816 * cgroup. We use css_tryget() here even if this looks
817 * pessimistic (rather than adding locks here).
819 rcu_read_lock();
820 do {
821 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
822 if (unlikely(!memcg))
823 break;
824 } while (!css_tryget(&memcg->css));
825 rcu_read_unlock();
826 return memcg;
829 /* The caller has to guarantee "mem" exists before calling this */
830 static struct mem_cgroup *mem_cgroup_start_loop(struct mem_cgroup *memcg)
832 struct cgroup_subsys_state *css;
833 int found;
835 if (!memcg) /* ROOT cgroup has the smallest ID */
836 return root_mem_cgroup; /*css_put/get against root is ignored*/
837 if (!memcg->use_hierarchy) {
838 if (css_tryget(&memcg->css))
839 return memcg;
840 return NULL;
842 rcu_read_lock();
844 * searching a memory cgroup which has the smallest ID under given
845 * ROOT cgroup. (ID >= 1)
847 css = css_get_next(&mem_cgroup_subsys, 1, &memcg->css, &found);
848 if (css && css_tryget(css))
849 memcg = container_of(css, struct mem_cgroup, css);
850 else
851 memcg = NULL;
852 rcu_read_unlock();
853 return memcg;
856 static struct mem_cgroup *mem_cgroup_get_next(struct mem_cgroup *iter,
857 struct mem_cgroup *root,
858 bool cond)
860 int nextid = css_id(&iter->css) + 1;
861 int found;
862 int hierarchy_used;
863 struct cgroup_subsys_state *css;
865 hierarchy_used = iter->use_hierarchy;
867 css_put(&iter->css);
868 /* If no ROOT, walk all, ignore hierarchy */
869 if (!cond || (root && !hierarchy_used))
870 return NULL;
872 if (!root)
873 root = root_mem_cgroup;
875 do {
876 iter = NULL;
877 rcu_read_lock();
879 css = css_get_next(&mem_cgroup_subsys, nextid,
880 &root->css, &found);
881 if (css && css_tryget(css))
882 iter = container_of(css, struct mem_cgroup, css);
883 rcu_read_unlock();
884 /* If css is NULL, no more cgroups will be found */
885 nextid = found + 1;
886 } while (css && !iter);
888 return iter;
891 * for_eacn_mem_cgroup_tree() for visiting all cgroup under tree. Please
892 * be careful that "break" loop is not allowed. We have reference count.
893 * Instead of that modify "cond" to be false and "continue" to exit the loop.
895 #define for_each_mem_cgroup_tree_cond(iter, root, cond) \
896 for (iter = mem_cgroup_start_loop(root);\
897 iter != NULL;\
898 iter = mem_cgroup_get_next(iter, root, cond))
900 #define for_each_mem_cgroup_tree(iter, root) \
901 for_each_mem_cgroup_tree_cond(iter, root, true)
903 #define for_each_mem_cgroup_all(iter) \
904 for_each_mem_cgroup_tree_cond(iter, NULL, true)
907 static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg)
909 return (memcg == root_mem_cgroup);
912 void mem_cgroup_count_vm_event(struct mm_struct *mm, enum vm_event_item idx)
914 struct mem_cgroup *memcg;
916 if (!mm)
917 return;
919 rcu_read_lock();
920 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
921 if (unlikely(!memcg))
922 goto out;
924 switch (idx) {
925 case PGMAJFAULT:
926 mem_cgroup_pgmajfault(memcg, 1);
927 break;
928 case PGFAULT:
929 mem_cgroup_pgfault(memcg, 1);
930 break;
931 default:
932 BUG();
934 out:
935 rcu_read_unlock();
937 EXPORT_SYMBOL(mem_cgroup_count_vm_event);
940 * Following LRU functions are allowed to be used without PCG_LOCK.
941 * Operations are called by routine of global LRU independently from memcg.
942 * What we have to take care of here is validness of pc->mem_cgroup.
944 * Changes to pc->mem_cgroup happens when
945 * 1. charge
946 * 2. moving account
947 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
948 * It is added to LRU before charge.
949 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
950 * When moving account, the page is not on LRU. It's isolated.
953 void mem_cgroup_del_lru_list(struct page *page, enum lru_list lru)
955 struct page_cgroup *pc;
956 struct mem_cgroup_per_zone *mz;
958 if (mem_cgroup_disabled())
959 return;
960 pc = lookup_page_cgroup(page);
961 /* can happen while we handle swapcache. */
962 if (!TestClearPageCgroupAcctLRU(pc))
963 return;
964 VM_BUG_ON(!pc->mem_cgroup);
966 * We don't check PCG_USED bit. It's cleared when the "page" is finally
967 * removed from global LRU.
969 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
970 /* huge page split is done under lru_lock. so, we have no races. */
971 MEM_CGROUP_ZSTAT(mz, lru) -= 1 << compound_order(page);
972 if (mem_cgroup_is_root(pc->mem_cgroup))
973 return;
974 VM_BUG_ON(list_empty(&pc->lru));
975 list_del_init(&pc->lru);
978 void mem_cgroup_del_lru(struct page *page)
980 mem_cgroup_del_lru_list(page, page_lru(page));
984 * Writeback is about to end against a page which has been marked for immediate
985 * reclaim. If it still appears to be reclaimable, move it to the tail of the
986 * inactive list.
988 void mem_cgroup_rotate_reclaimable_page(struct page *page)
990 struct mem_cgroup_per_zone *mz;
991 struct page_cgroup *pc;
992 enum lru_list lru = page_lru(page);
994 if (mem_cgroup_disabled())
995 return;
997 pc = lookup_page_cgroup(page);
998 /* unused or root page is not rotated. */
999 if (!PageCgroupUsed(pc))
1000 return;
1001 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1002 smp_rmb();
1003 if (mem_cgroup_is_root(pc->mem_cgroup))
1004 return;
1005 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
1006 list_move_tail(&pc->lru, &mz->lists[lru]);
1009 void mem_cgroup_rotate_lru_list(struct page *page, enum lru_list lru)
1011 struct mem_cgroup_per_zone *mz;
1012 struct page_cgroup *pc;
1014 if (mem_cgroup_disabled())
1015 return;
1017 pc = lookup_page_cgroup(page);
1018 /* unused or root page is not rotated. */
1019 if (!PageCgroupUsed(pc))
1020 return;
1021 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1022 smp_rmb();
1023 if (mem_cgroup_is_root(pc->mem_cgroup))
1024 return;
1025 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
1026 list_move(&pc->lru, &mz->lists[lru]);
1029 void mem_cgroup_add_lru_list(struct page *page, enum lru_list lru)
1031 struct page_cgroup *pc;
1032 struct mem_cgroup_per_zone *mz;
1034 if (mem_cgroup_disabled())
1035 return;
1036 pc = lookup_page_cgroup(page);
1037 VM_BUG_ON(PageCgroupAcctLRU(pc));
1038 if (!PageCgroupUsed(pc))
1039 return;
1040 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1041 smp_rmb();
1042 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
1043 /* huge page split is done under lru_lock. so, we have no races. */
1044 MEM_CGROUP_ZSTAT(mz, lru) += 1 << compound_order(page);
1045 SetPageCgroupAcctLRU(pc);
1046 if (mem_cgroup_is_root(pc->mem_cgroup))
1047 return;
1048 list_add(&pc->lru, &mz->lists[lru]);
1052 * At handling SwapCache and other FUSE stuff, pc->mem_cgroup may be changed
1053 * while it's linked to lru because the page may be reused after it's fully
1054 * uncharged. To handle that, unlink page_cgroup from LRU when charge it again.
1055 * It's done under lock_page and expected that zone->lru_lock isnever held.
1057 static void mem_cgroup_lru_del_before_commit(struct page *page)
1059 unsigned long flags;
1060 struct zone *zone = page_zone(page);
1061 struct page_cgroup *pc = lookup_page_cgroup(page);
1064 * Doing this check without taking ->lru_lock seems wrong but this
1065 * is safe. Because if page_cgroup's USED bit is unset, the page
1066 * will not be added to any memcg's LRU. If page_cgroup's USED bit is
1067 * set, the commit after this will fail, anyway.
1068 * This all charge/uncharge is done under some mutual execustion.
1069 * So, we don't need to taking care of changes in USED bit.
1071 if (likely(!PageLRU(page)))
1072 return;
1074 spin_lock_irqsave(&zone->lru_lock, flags);
1076 * Forget old LRU when this page_cgroup is *not* used. This Used bit
1077 * is guarded by lock_page() because the page is SwapCache.
1079 if (!PageCgroupUsed(pc))
1080 mem_cgroup_del_lru_list(page, page_lru(page));
1081 spin_unlock_irqrestore(&zone->lru_lock, flags);
1084 static void mem_cgroup_lru_add_after_commit(struct page *page)
1086 unsigned long flags;
1087 struct zone *zone = page_zone(page);
1088 struct page_cgroup *pc = lookup_page_cgroup(page);
1090 /* taking care of that the page is added to LRU while we commit it */
1091 if (likely(!PageLRU(page)))
1092 return;
1093 spin_lock_irqsave(&zone->lru_lock, flags);
1094 /* link when the page is linked to LRU but page_cgroup isn't */
1095 if (PageLRU(page) && !PageCgroupAcctLRU(pc))
1096 mem_cgroup_add_lru_list(page, page_lru(page));
1097 spin_unlock_irqrestore(&zone->lru_lock, flags);
1101 void mem_cgroup_move_lists(struct page *page,
1102 enum lru_list from, enum lru_list to)
1104 if (mem_cgroup_disabled())
1105 return;
1106 mem_cgroup_del_lru_list(page, from);
1107 mem_cgroup_add_lru_list(page, to);
1111 * Checks whether given mem is same or in the root_mem's
1112 * hierarchy subtree
1114 static bool mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
1115 struct mem_cgroup *memcg)
1117 if (root_memcg != memcg) {
1118 return (root_memcg->use_hierarchy &&
1119 css_is_ancestor(&memcg->css, &root_memcg->css));
1122 return true;
1125 int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *memcg)
1127 int ret;
1128 struct mem_cgroup *curr = NULL;
1129 struct task_struct *p;
1131 p = find_lock_task_mm(task);
1132 if (!p)
1133 return 0;
1134 curr = try_get_mem_cgroup_from_mm(p->mm);
1135 task_unlock(p);
1136 if (!curr)
1137 return 0;
1139 * We should check use_hierarchy of "memcg" not "curr". Because checking
1140 * use_hierarchy of "curr" here make this function true if hierarchy is
1141 * enabled in "curr" and "curr" is a child of "memcg" in *cgroup*
1142 * hierarchy(even if use_hierarchy is disabled in "memcg").
1144 ret = mem_cgroup_same_or_subtree(memcg, curr);
1145 css_put(&curr->css);
1146 return ret;
1149 static int calc_inactive_ratio(struct mem_cgroup *memcg, unsigned long *present_pages)
1151 unsigned long active;
1152 unsigned long inactive;
1153 unsigned long gb;
1154 unsigned long inactive_ratio;
1156 inactive = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_INACTIVE_ANON));
1157 active = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_ACTIVE_ANON));
1159 gb = (inactive + active) >> (30 - PAGE_SHIFT);
1160 if (gb)
1161 inactive_ratio = int_sqrt(10 * gb);
1162 else
1163 inactive_ratio = 1;
1165 if (present_pages) {
1166 present_pages[0] = inactive;
1167 present_pages[1] = active;
1170 return inactive_ratio;
1173 int mem_cgroup_inactive_anon_is_low(struct mem_cgroup *memcg)
1175 unsigned long active;
1176 unsigned long inactive;
1177 unsigned long present_pages[2];
1178 unsigned long inactive_ratio;
1180 inactive_ratio = calc_inactive_ratio(memcg, present_pages);
1182 inactive = present_pages[0];
1183 active = present_pages[1];
1185 if (inactive * inactive_ratio < active)
1186 return 1;
1188 return 0;
1191 int mem_cgroup_inactive_file_is_low(struct mem_cgroup *memcg)
1193 unsigned long active;
1194 unsigned long inactive;
1196 inactive = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_INACTIVE_FILE));
1197 active = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_ACTIVE_FILE));
1199 return (active > inactive);
1202 struct zone_reclaim_stat *mem_cgroup_get_reclaim_stat(struct mem_cgroup *memcg,
1203 struct zone *zone)
1205 int nid = zone_to_nid(zone);
1206 int zid = zone_idx(zone);
1207 struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
1209 return &mz->reclaim_stat;
1212 struct zone_reclaim_stat *
1213 mem_cgroup_get_reclaim_stat_from_page(struct page *page)
1215 struct page_cgroup *pc;
1216 struct mem_cgroup_per_zone *mz;
1218 if (mem_cgroup_disabled())
1219 return NULL;
1221 pc = lookup_page_cgroup(page);
1222 if (!PageCgroupUsed(pc))
1223 return NULL;
1224 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1225 smp_rmb();
1226 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
1227 return &mz->reclaim_stat;
1230 unsigned long mem_cgroup_isolate_pages(unsigned long nr_to_scan,
1231 struct list_head *dst,
1232 unsigned long *scanned, int order,
1233 isolate_mode_t mode,
1234 struct zone *z,
1235 struct mem_cgroup *mem_cont,
1236 int active, int file)
1238 unsigned long nr_taken = 0;
1239 struct page *page;
1240 unsigned long scan;
1241 LIST_HEAD(pc_list);
1242 struct list_head *src;
1243 struct page_cgroup *pc, *tmp;
1244 int nid = zone_to_nid(z);
1245 int zid = zone_idx(z);
1246 struct mem_cgroup_per_zone *mz;
1247 int lru = LRU_FILE * file + active;
1248 int ret;
1250 BUG_ON(!mem_cont);
1251 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
1252 src = &mz->lists[lru];
1254 scan = 0;
1255 list_for_each_entry_safe_reverse(pc, tmp, src, lru) {
1256 if (scan >= nr_to_scan)
1257 break;
1259 if (unlikely(!PageCgroupUsed(pc)))
1260 continue;
1262 page = lookup_cgroup_page(pc);
1264 if (unlikely(!PageLRU(page)))
1265 continue;
1267 scan++;
1268 ret = __isolate_lru_page(page, mode, file);
1269 switch (ret) {
1270 case 0:
1271 list_move(&page->lru, dst);
1272 mem_cgroup_del_lru(page);
1273 nr_taken += hpage_nr_pages(page);
1274 break;
1275 case -EBUSY:
1276 /* we don't affect global LRU but rotate in our LRU */
1277 mem_cgroup_rotate_lru_list(page, page_lru(page));
1278 break;
1279 default:
1280 break;
1284 *scanned = scan;
1286 trace_mm_vmscan_memcg_isolate(0, nr_to_scan, scan, nr_taken,
1287 0, 0, 0, mode);
1289 return nr_taken;
1292 #define mem_cgroup_from_res_counter(counter, member) \
1293 container_of(counter, struct mem_cgroup, member)
1296 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1297 * @mem: the memory cgroup
1299 * Returns the maximum amount of memory @mem can be charged with, in
1300 * pages.
1302 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1304 unsigned long long margin;
1306 margin = res_counter_margin(&memcg->res);
1307 if (do_swap_account)
1308 margin = min(margin, res_counter_margin(&memcg->memsw));
1309 return margin >> PAGE_SHIFT;
1312 int mem_cgroup_swappiness(struct mem_cgroup *memcg)
1314 struct cgroup *cgrp = memcg->css.cgroup;
1316 /* root ? */
1317 if (cgrp->parent == NULL)
1318 return vm_swappiness;
1320 return memcg->swappiness;
1323 static void mem_cgroup_start_move(struct mem_cgroup *memcg)
1325 int cpu;
1327 get_online_cpus();
1328 spin_lock(&memcg->pcp_counter_lock);
1329 for_each_online_cpu(cpu)
1330 per_cpu(memcg->stat->count[MEM_CGROUP_ON_MOVE], cpu) += 1;
1331 memcg->nocpu_base.count[MEM_CGROUP_ON_MOVE] += 1;
1332 spin_unlock(&memcg->pcp_counter_lock);
1333 put_online_cpus();
1335 synchronize_rcu();
1338 static void mem_cgroup_end_move(struct mem_cgroup *memcg)
1340 int cpu;
1342 if (!memcg)
1343 return;
1344 get_online_cpus();
1345 spin_lock(&memcg->pcp_counter_lock);
1346 for_each_online_cpu(cpu)
1347 per_cpu(memcg->stat->count[MEM_CGROUP_ON_MOVE], cpu) -= 1;
1348 memcg->nocpu_base.count[MEM_CGROUP_ON_MOVE] -= 1;
1349 spin_unlock(&memcg->pcp_counter_lock);
1350 put_online_cpus();
1353 * 2 routines for checking "mem" is under move_account() or not.
1355 * mem_cgroup_stealed() - checking a cgroup is mc.from or not. This is used
1356 * for avoiding race in accounting. If true,
1357 * pc->mem_cgroup may be overwritten.
1359 * mem_cgroup_under_move() - checking a cgroup is mc.from or mc.to or
1360 * under hierarchy of moving cgroups. This is for
1361 * waiting at hith-memory prressure caused by "move".
1364 static bool mem_cgroup_stealed(struct mem_cgroup *memcg)
1366 VM_BUG_ON(!rcu_read_lock_held());
1367 return this_cpu_read(memcg->stat->count[MEM_CGROUP_ON_MOVE]) > 0;
1370 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1372 struct mem_cgroup *from;
1373 struct mem_cgroup *to;
1374 bool ret = false;
1376 * Unlike task_move routines, we access mc.to, mc.from not under
1377 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1379 spin_lock(&mc.lock);
1380 from = mc.from;
1381 to = mc.to;
1382 if (!from)
1383 goto unlock;
1385 ret = mem_cgroup_same_or_subtree(memcg, from)
1386 || mem_cgroup_same_or_subtree(memcg, to);
1387 unlock:
1388 spin_unlock(&mc.lock);
1389 return ret;
1392 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1394 if (mc.moving_task && current != mc.moving_task) {
1395 if (mem_cgroup_under_move(memcg)) {
1396 DEFINE_WAIT(wait);
1397 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1398 /* moving charge context might have finished. */
1399 if (mc.moving_task)
1400 schedule();
1401 finish_wait(&mc.waitq, &wait);
1402 return true;
1405 return false;
1409 * mem_cgroup_print_oom_info: Called from OOM with tasklist_lock held in read mode.
1410 * @memcg: The memory cgroup that went over limit
1411 * @p: Task that is going to be killed
1413 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1414 * enabled
1416 void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1418 struct cgroup *task_cgrp;
1419 struct cgroup *mem_cgrp;
1421 * Need a buffer in BSS, can't rely on allocations. The code relies
1422 * on the assumption that OOM is serialized for memory controller.
1423 * If this assumption is broken, revisit this code.
1425 static char memcg_name[PATH_MAX];
1426 int ret;
1428 if (!memcg || !p)
1429 return;
1432 rcu_read_lock();
1434 mem_cgrp = memcg->css.cgroup;
1435 task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
1437 ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
1438 if (ret < 0) {
1440 * Unfortunately, we are unable to convert to a useful name
1441 * But we'll still print out the usage information
1443 rcu_read_unlock();
1444 goto done;
1446 rcu_read_unlock();
1448 printk(KERN_INFO "Task in %s killed", memcg_name);
1450 rcu_read_lock();
1451 ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
1452 if (ret < 0) {
1453 rcu_read_unlock();
1454 goto done;
1456 rcu_read_unlock();
1459 * Continues from above, so we don't need an KERN_ level
1461 printk(KERN_CONT " as a result of limit of %s\n", memcg_name);
1462 done:
1464 printk(KERN_INFO "memory: usage %llukB, limit %llukB, failcnt %llu\n",
1465 res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
1466 res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
1467 res_counter_read_u64(&memcg->res, RES_FAILCNT));
1468 printk(KERN_INFO "memory+swap: usage %llukB, limit %llukB, "
1469 "failcnt %llu\n",
1470 res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
1471 res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
1472 res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
1476 * This function returns the number of memcg under hierarchy tree. Returns
1477 * 1(self count) if no children.
1479 static int mem_cgroup_count_children(struct mem_cgroup *memcg)
1481 int num = 0;
1482 struct mem_cgroup *iter;
1484 for_each_mem_cgroup_tree(iter, memcg)
1485 num++;
1486 return num;
1490 * Return the memory (and swap, if configured) limit for a memcg.
1492 u64 mem_cgroup_get_limit(struct mem_cgroup *memcg)
1494 u64 limit;
1495 u64 memsw;
1497 limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
1498 limit += total_swap_pages << PAGE_SHIFT;
1500 memsw = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
1502 * If memsw is finite and limits the amount of swap space available
1503 * to this memcg, return that limit.
1505 return min(limit, memsw);
1509 * Visit the first child (need not be the first child as per the ordering
1510 * of the cgroup list, since we track last_scanned_child) of @mem and use
1511 * that to reclaim free pages from.
1513 static struct mem_cgroup *
1514 mem_cgroup_select_victim(struct mem_cgroup *root_memcg)
1516 struct mem_cgroup *ret = NULL;
1517 struct cgroup_subsys_state *css;
1518 int nextid, found;
1520 if (!root_memcg->use_hierarchy) {
1521 css_get(&root_memcg->css);
1522 ret = root_memcg;
1525 while (!ret) {
1526 rcu_read_lock();
1527 nextid = root_memcg->last_scanned_child + 1;
1528 css = css_get_next(&mem_cgroup_subsys, nextid, &root_memcg->css,
1529 &found);
1530 if (css && css_tryget(css))
1531 ret = container_of(css, struct mem_cgroup, css);
1533 rcu_read_unlock();
1534 /* Updates scanning parameter */
1535 if (!css) {
1536 /* this means start scan from ID:1 */
1537 root_memcg->last_scanned_child = 0;
1538 } else
1539 root_memcg->last_scanned_child = found;
1542 return ret;
1546 * test_mem_cgroup_node_reclaimable
1547 * @mem: the target memcg
1548 * @nid: the node ID to be checked.
1549 * @noswap : specify true here if the user wants flle only information.
1551 * This function returns whether the specified memcg contains any
1552 * reclaimable pages on a node. Returns true if there are any reclaimable
1553 * pages in the node.
1555 static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *memcg,
1556 int nid, bool noswap)
1558 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_FILE))
1559 return true;
1560 if (noswap || !total_swap_pages)
1561 return false;
1562 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_ANON))
1563 return true;
1564 return false;
1567 #if MAX_NUMNODES > 1
1570 * Always updating the nodemask is not very good - even if we have an empty
1571 * list or the wrong list here, we can start from some node and traverse all
1572 * nodes based on the zonelist. So update the list loosely once per 10 secs.
1575 static void mem_cgroup_may_update_nodemask(struct mem_cgroup *memcg)
1577 int nid;
1579 * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
1580 * pagein/pageout changes since the last update.
1582 if (!atomic_read(&memcg->numainfo_events))
1583 return;
1584 if (atomic_inc_return(&memcg->numainfo_updating) > 1)
1585 return;
1587 /* make a nodemask where this memcg uses memory from */
1588 memcg->scan_nodes = node_states[N_HIGH_MEMORY];
1590 for_each_node_mask(nid, node_states[N_HIGH_MEMORY]) {
1592 if (!test_mem_cgroup_node_reclaimable(memcg, nid, false))
1593 node_clear(nid, memcg->scan_nodes);
1596 atomic_set(&memcg->numainfo_events, 0);
1597 atomic_set(&memcg->numainfo_updating, 0);
1601 * Selecting a node where we start reclaim from. Because what we need is just
1602 * reducing usage counter, start from anywhere is O,K. Considering
1603 * memory reclaim from current node, there are pros. and cons.
1605 * Freeing memory from current node means freeing memory from a node which
1606 * we'll use or we've used. So, it may make LRU bad. And if several threads
1607 * hit limits, it will see a contention on a node. But freeing from remote
1608 * node means more costs for memory reclaim because of memory latency.
1610 * Now, we use round-robin. Better algorithm is welcomed.
1612 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1614 int node;
1616 mem_cgroup_may_update_nodemask(memcg);
1617 node = memcg->last_scanned_node;
1619 node = next_node(node, memcg->scan_nodes);
1620 if (node == MAX_NUMNODES)
1621 node = first_node(memcg->scan_nodes);
1623 * We call this when we hit limit, not when pages are added to LRU.
1624 * No LRU may hold pages because all pages are UNEVICTABLE or
1625 * memcg is too small and all pages are not on LRU. In that case,
1626 * we use curret node.
1628 if (unlikely(node == MAX_NUMNODES))
1629 node = numa_node_id();
1631 memcg->last_scanned_node = node;
1632 return node;
1636 * Check all nodes whether it contains reclaimable pages or not.
1637 * For quick scan, we make use of scan_nodes. This will allow us to skip
1638 * unused nodes. But scan_nodes is lazily updated and may not cotain
1639 * enough new information. We need to do double check.
1641 bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
1643 int nid;
1646 * quick check...making use of scan_node.
1647 * We can skip unused nodes.
1649 if (!nodes_empty(memcg->scan_nodes)) {
1650 for (nid = first_node(memcg->scan_nodes);
1651 nid < MAX_NUMNODES;
1652 nid = next_node(nid, memcg->scan_nodes)) {
1654 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
1655 return true;
1659 * Check rest of nodes.
1661 for_each_node_state(nid, N_HIGH_MEMORY) {
1662 if (node_isset(nid, memcg->scan_nodes))
1663 continue;
1664 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
1665 return true;
1667 return false;
1670 #else
1671 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1673 return 0;
1676 bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
1678 return test_mem_cgroup_node_reclaimable(memcg, 0, noswap);
1680 #endif
1682 static void __mem_cgroup_record_scanstat(unsigned long *stats,
1683 struct memcg_scanrecord *rec)
1686 stats[SCAN] += rec->nr_scanned[0] + rec->nr_scanned[1];
1687 stats[SCAN_ANON] += rec->nr_scanned[0];
1688 stats[SCAN_FILE] += rec->nr_scanned[1];
1690 stats[ROTATE] += rec->nr_rotated[0] + rec->nr_rotated[1];
1691 stats[ROTATE_ANON] += rec->nr_rotated[0];
1692 stats[ROTATE_FILE] += rec->nr_rotated[1];
1694 stats[FREED] += rec->nr_freed[0] + rec->nr_freed[1];
1695 stats[FREED_ANON] += rec->nr_freed[0];
1696 stats[FREED_FILE] += rec->nr_freed[1];
1698 stats[ELAPSED] += rec->elapsed;
1701 static void mem_cgroup_record_scanstat(struct memcg_scanrecord *rec)
1703 struct mem_cgroup *memcg;
1704 int context = rec->context;
1706 if (context >= NR_SCAN_CONTEXT)
1707 return;
1709 memcg = rec->mem;
1710 spin_lock(&memcg->scanstat.lock);
1711 __mem_cgroup_record_scanstat(memcg->scanstat.stats[context], rec);
1712 spin_unlock(&memcg->scanstat.lock);
1714 memcg = rec->root;
1715 spin_lock(&memcg->scanstat.lock);
1716 __mem_cgroup_record_scanstat(memcg->scanstat.rootstats[context], rec);
1717 spin_unlock(&memcg->scanstat.lock);
1721 * Scan the hierarchy if needed to reclaim memory. We remember the last child
1722 * we reclaimed from, so that we don't end up penalizing one child extensively
1723 * based on its position in the children list.
1725 * root_memcg is the original ancestor that we've been reclaim from.
1727 * We give up and return to the caller when we visit root_memcg twice.
1728 * (other groups can be removed while we're walking....)
1730 * If shrink==true, for avoiding to free too much, this returns immedieately.
1732 static int mem_cgroup_hierarchical_reclaim(struct mem_cgroup *root_memcg,
1733 struct zone *zone,
1734 gfp_t gfp_mask,
1735 unsigned long reclaim_options,
1736 unsigned long *total_scanned)
1738 struct mem_cgroup *victim;
1739 int ret, total = 0;
1740 int loop = 0;
1741 bool noswap = reclaim_options & MEM_CGROUP_RECLAIM_NOSWAP;
1742 bool shrink = reclaim_options & MEM_CGROUP_RECLAIM_SHRINK;
1743 bool check_soft = reclaim_options & MEM_CGROUP_RECLAIM_SOFT;
1744 struct memcg_scanrecord rec;
1745 unsigned long excess;
1746 unsigned long scanned;
1748 excess = res_counter_soft_limit_excess(&root_memcg->res) >> PAGE_SHIFT;
1750 /* If memsw_is_minimum==1, swap-out is of-no-use. */
1751 if (!check_soft && !shrink && root_memcg->memsw_is_minimum)
1752 noswap = true;
1754 if (shrink)
1755 rec.context = SCAN_BY_SHRINK;
1756 else if (check_soft)
1757 rec.context = SCAN_BY_SYSTEM;
1758 else
1759 rec.context = SCAN_BY_LIMIT;
1761 rec.root = root_memcg;
1763 while (1) {
1764 victim = mem_cgroup_select_victim(root_memcg);
1765 if (victim == root_memcg) {
1766 loop++;
1768 * We are not draining per cpu cached charges during
1769 * soft limit reclaim because global reclaim doesn't
1770 * care about charges. It tries to free some memory and
1771 * charges will not give any.
1773 if (!check_soft && loop >= 1)
1774 drain_all_stock_async(root_memcg);
1775 if (loop >= 2) {
1777 * If we have not been able to reclaim
1778 * anything, it might because there are
1779 * no reclaimable pages under this hierarchy
1781 if (!check_soft || !total) {
1782 css_put(&victim->css);
1783 break;
1786 * We want to do more targeted reclaim.
1787 * excess >> 2 is not to excessive so as to
1788 * reclaim too much, nor too less that we keep
1789 * coming back to reclaim from this cgroup
1791 if (total >= (excess >> 2) ||
1792 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS)) {
1793 css_put(&victim->css);
1794 break;
1798 if (!mem_cgroup_reclaimable(victim, noswap)) {
1799 /* this cgroup's local usage == 0 */
1800 css_put(&victim->css);
1801 continue;
1803 rec.mem = victim;
1804 rec.nr_scanned[0] = 0;
1805 rec.nr_scanned[1] = 0;
1806 rec.nr_rotated[0] = 0;
1807 rec.nr_rotated[1] = 0;
1808 rec.nr_freed[0] = 0;
1809 rec.nr_freed[1] = 0;
1810 rec.elapsed = 0;
1811 /* we use swappiness of local cgroup */
1812 if (check_soft) {
1813 ret = mem_cgroup_shrink_node_zone(victim, gfp_mask,
1814 noswap, zone, &rec, &scanned);
1815 *total_scanned += scanned;
1816 } else
1817 ret = try_to_free_mem_cgroup_pages(victim, gfp_mask,
1818 noswap, &rec);
1819 mem_cgroup_record_scanstat(&rec);
1820 css_put(&victim->css);
1822 * At shrinking usage, we can't check we should stop here or
1823 * reclaim more. It's depends on callers. last_scanned_child
1824 * will work enough for keeping fairness under tree.
1826 if (shrink)
1827 return ret;
1828 total += ret;
1829 if (check_soft) {
1830 if (!res_counter_soft_limit_excess(&root_memcg->res))
1831 return total;
1832 } else if (mem_cgroup_margin(root_memcg))
1833 return total;
1835 return total;
1839 * Check OOM-Killer is already running under our hierarchy.
1840 * If someone is running, return false.
1841 * Has to be called with memcg_oom_lock
1843 static bool mem_cgroup_oom_lock(struct mem_cgroup *memcg)
1845 struct mem_cgroup *iter, *failed = NULL;
1846 bool cond = true;
1848 for_each_mem_cgroup_tree_cond(iter, memcg, cond) {
1849 if (iter->oom_lock) {
1851 * this subtree of our hierarchy is already locked
1852 * so we cannot give a lock.
1854 failed = iter;
1855 cond = false;
1856 } else
1857 iter->oom_lock = true;
1860 if (!failed)
1861 return true;
1864 * OK, we failed to lock the whole subtree so we have to clean up
1865 * what we set up to the failing subtree
1867 cond = true;
1868 for_each_mem_cgroup_tree_cond(iter, memcg, cond) {
1869 if (iter == failed) {
1870 cond = false;
1871 continue;
1873 iter->oom_lock = false;
1875 return false;
1879 * Has to be called with memcg_oom_lock
1881 static int mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
1883 struct mem_cgroup *iter;
1885 for_each_mem_cgroup_tree(iter, memcg)
1886 iter->oom_lock = false;
1887 return 0;
1890 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
1892 struct mem_cgroup *iter;
1894 for_each_mem_cgroup_tree(iter, memcg)
1895 atomic_inc(&iter->under_oom);
1898 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
1900 struct mem_cgroup *iter;
1903 * When a new child is created while the hierarchy is under oom,
1904 * mem_cgroup_oom_lock() may not be called. We have to use
1905 * atomic_add_unless() here.
1907 for_each_mem_cgroup_tree(iter, memcg)
1908 atomic_add_unless(&iter->under_oom, -1, 0);
1911 static DEFINE_SPINLOCK(memcg_oom_lock);
1912 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1914 struct oom_wait_info {
1915 struct mem_cgroup *mem;
1916 wait_queue_t wait;
1919 static int memcg_oom_wake_function(wait_queue_t *wait,
1920 unsigned mode, int sync, void *arg)
1922 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg,
1923 *oom_wait_memcg;
1924 struct oom_wait_info *oom_wait_info;
1926 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1927 oom_wait_memcg = oom_wait_info->mem;
1930 * Both of oom_wait_info->mem and wake_mem are stable under us.
1931 * Then we can use css_is_ancestor without taking care of RCU.
1933 if (!mem_cgroup_same_or_subtree(oom_wait_memcg, wake_memcg)
1934 && !mem_cgroup_same_or_subtree(wake_memcg, oom_wait_memcg))
1935 return 0;
1936 return autoremove_wake_function(wait, mode, sync, arg);
1939 static void memcg_wakeup_oom(struct mem_cgroup *memcg)
1941 /* for filtering, pass "memcg" as argument. */
1942 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
1945 static void memcg_oom_recover(struct mem_cgroup *memcg)
1947 if (memcg && atomic_read(&memcg->under_oom))
1948 memcg_wakeup_oom(memcg);
1952 * try to call OOM killer. returns false if we should exit memory-reclaim loop.
1954 bool mem_cgroup_handle_oom(struct mem_cgroup *memcg, gfp_t mask)
1956 struct oom_wait_info owait;
1957 bool locked, need_to_kill;
1959 owait.mem = memcg;
1960 owait.wait.flags = 0;
1961 owait.wait.func = memcg_oom_wake_function;
1962 owait.wait.private = current;
1963 INIT_LIST_HEAD(&owait.wait.task_list);
1964 need_to_kill = true;
1965 mem_cgroup_mark_under_oom(memcg);
1967 /* At first, try to OOM lock hierarchy under memcg.*/
1968 spin_lock(&memcg_oom_lock);
1969 locked = mem_cgroup_oom_lock(memcg);
1971 * Even if signal_pending(), we can't quit charge() loop without
1972 * accounting. So, UNINTERRUPTIBLE is appropriate. But SIGKILL
1973 * under OOM is always welcomed, use TASK_KILLABLE here.
1975 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
1976 if (!locked || memcg->oom_kill_disable)
1977 need_to_kill = false;
1978 if (locked)
1979 mem_cgroup_oom_notify(memcg);
1980 spin_unlock(&memcg_oom_lock);
1982 if (need_to_kill) {
1983 finish_wait(&memcg_oom_waitq, &owait.wait);
1984 mem_cgroup_out_of_memory(memcg, mask);
1985 } else {
1986 schedule();
1987 finish_wait(&memcg_oom_waitq, &owait.wait);
1989 spin_lock(&memcg_oom_lock);
1990 if (locked)
1991 mem_cgroup_oom_unlock(memcg);
1992 memcg_wakeup_oom(memcg);
1993 spin_unlock(&memcg_oom_lock);
1995 mem_cgroup_unmark_under_oom(memcg);
1997 if (test_thread_flag(TIF_MEMDIE) || fatal_signal_pending(current))
1998 return false;
1999 /* Give chance to dying process */
2000 schedule_timeout_uninterruptible(1);
2001 return true;
2005 * Currently used to update mapped file statistics, but the routine can be
2006 * generalized to update other statistics as well.
2008 * Notes: Race condition
2010 * We usually use page_cgroup_lock() for accessing page_cgroup member but
2011 * it tends to be costly. But considering some conditions, we doesn't need
2012 * to do so _always_.
2014 * Considering "charge", lock_page_cgroup() is not required because all
2015 * file-stat operations happen after a page is attached to radix-tree. There
2016 * are no race with "charge".
2018 * Considering "uncharge", we know that memcg doesn't clear pc->mem_cgroup
2019 * at "uncharge" intentionally. So, we always see valid pc->mem_cgroup even
2020 * if there are race with "uncharge". Statistics itself is properly handled
2021 * by flags.
2023 * Considering "move", this is an only case we see a race. To make the race
2024 * small, we check MEM_CGROUP_ON_MOVE percpu value and detect there are
2025 * possibility of race condition. If there is, we take a lock.
2028 void mem_cgroup_update_page_stat(struct page *page,
2029 enum mem_cgroup_page_stat_item idx, int val)
2031 struct mem_cgroup *memcg;
2032 struct page_cgroup *pc = lookup_page_cgroup(page);
2033 bool need_unlock = false;
2034 unsigned long uninitialized_var(flags);
2036 if (unlikely(!pc))
2037 return;
2039 rcu_read_lock();
2040 memcg = pc->mem_cgroup;
2041 if (unlikely(!memcg || !PageCgroupUsed(pc)))
2042 goto out;
2043 /* pc->mem_cgroup is unstable ? */
2044 if (unlikely(mem_cgroup_stealed(memcg)) || PageTransHuge(page)) {
2045 /* take a lock against to access pc->mem_cgroup */
2046 move_lock_page_cgroup(pc, &flags);
2047 need_unlock = true;
2048 memcg = pc->mem_cgroup;
2049 if (!memcg || !PageCgroupUsed(pc))
2050 goto out;
2053 switch (idx) {
2054 case MEMCG_NR_FILE_MAPPED:
2055 if (val > 0)
2056 SetPageCgroupFileMapped(pc);
2057 else if (!page_mapped(page))
2058 ClearPageCgroupFileMapped(pc);
2059 idx = MEM_CGROUP_STAT_FILE_MAPPED;
2060 break;
2061 default:
2062 BUG();
2065 this_cpu_add(memcg->stat->count[idx], val);
2067 out:
2068 if (unlikely(need_unlock))
2069 move_unlock_page_cgroup(pc, &flags);
2070 rcu_read_unlock();
2071 return;
2073 EXPORT_SYMBOL(mem_cgroup_update_page_stat);
2076 * size of first charge trial. "32" comes from vmscan.c's magic value.
2077 * TODO: maybe necessary to use big numbers in big irons.
2079 #define CHARGE_BATCH 32U
2080 struct memcg_stock_pcp {
2081 struct mem_cgroup *cached; /* this never be root cgroup */
2082 unsigned int nr_pages;
2083 struct work_struct work;
2084 unsigned long flags;
2085 #define FLUSHING_CACHED_CHARGE (0)
2087 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
2088 static DEFINE_MUTEX(percpu_charge_mutex);
2091 * Try to consume stocked charge on this cpu. If success, one page is consumed
2092 * from local stock and true is returned. If the stock is 0 or charges from a
2093 * cgroup which is not current target, returns false. This stock will be
2094 * refilled.
2096 static bool consume_stock(struct mem_cgroup *memcg)
2098 struct memcg_stock_pcp *stock;
2099 bool ret = true;
2101 stock = &get_cpu_var(memcg_stock);
2102 if (memcg == stock->cached && stock->nr_pages)
2103 stock->nr_pages--;
2104 else /* need to call res_counter_charge */
2105 ret = false;
2106 put_cpu_var(memcg_stock);
2107 return ret;
2111 * Returns stocks cached in percpu to res_counter and reset cached information.
2113 static void drain_stock(struct memcg_stock_pcp *stock)
2115 struct mem_cgroup *old = stock->cached;
2117 if (stock->nr_pages) {
2118 unsigned long bytes = stock->nr_pages * PAGE_SIZE;
2120 res_counter_uncharge(&old->res, bytes);
2121 if (do_swap_account)
2122 res_counter_uncharge(&old->memsw, bytes);
2123 stock->nr_pages = 0;
2125 stock->cached = NULL;
2129 * This must be called under preempt disabled or must be called by
2130 * a thread which is pinned to local cpu.
2132 static void drain_local_stock(struct work_struct *dummy)
2134 struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
2135 drain_stock(stock);
2136 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2140 * Cache charges(val) which is from res_counter, to local per_cpu area.
2141 * This will be consumed by consume_stock() function, later.
2143 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2145 struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
2147 if (stock->cached != memcg) { /* reset if necessary */
2148 drain_stock(stock);
2149 stock->cached = memcg;
2151 stock->nr_pages += nr_pages;
2152 put_cpu_var(memcg_stock);
2156 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2157 * of the hierarchy under it. sync flag says whether we should block
2158 * until the work is done.
2160 static void drain_all_stock(struct mem_cgroup *root_memcg, bool sync)
2162 int cpu, curcpu;
2164 /* Notify other cpus that system-wide "drain" is running */
2165 get_online_cpus();
2166 curcpu = get_cpu();
2167 for_each_online_cpu(cpu) {
2168 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2169 struct mem_cgroup *memcg;
2171 memcg = stock->cached;
2172 if (!memcg || !stock->nr_pages)
2173 continue;
2174 if (!mem_cgroup_same_or_subtree(root_memcg, memcg))
2175 continue;
2176 if (!test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2177 if (cpu == curcpu)
2178 drain_local_stock(&stock->work);
2179 else
2180 schedule_work_on(cpu, &stock->work);
2183 put_cpu();
2185 if (!sync)
2186 goto out;
2188 for_each_online_cpu(cpu) {
2189 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2190 if (test_bit(FLUSHING_CACHED_CHARGE, &stock->flags))
2191 flush_work(&stock->work);
2193 out:
2194 put_online_cpus();
2198 * Tries to drain stocked charges in other cpus. This function is asynchronous
2199 * and just put a work per cpu for draining localy on each cpu. Caller can
2200 * expects some charges will be back to res_counter later but cannot wait for
2201 * it.
2203 static void drain_all_stock_async(struct mem_cgroup *root_memcg)
2206 * If someone calls draining, avoid adding more kworker runs.
2208 if (!mutex_trylock(&percpu_charge_mutex))
2209 return;
2210 drain_all_stock(root_memcg, false);
2211 mutex_unlock(&percpu_charge_mutex);
2214 /* This is a synchronous drain interface. */
2215 static void drain_all_stock_sync(struct mem_cgroup *root_memcg)
2217 /* called when force_empty is called */
2218 mutex_lock(&percpu_charge_mutex);
2219 drain_all_stock(root_memcg, true);
2220 mutex_unlock(&percpu_charge_mutex);
2224 * This function drains percpu counter value from DEAD cpu and
2225 * move it to local cpu. Note that this function can be preempted.
2227 static void mem_cgroup_drain_pcp_counter(struct mem_cgroup *memcg, int cpu)
2229 int i;
2231 spin_lock(&memcg->pcp_counter_lock);
2232 for (i = 0; i < MEM_CGROUP_STAT_DATA; i++) {
2233 long x = per_cpu(memcg->stat->count[i], cpu);
2235 per_cpu(memcg->stat->count[i], cpu) = 0;
2236 memcg->nocpu_base.count[i] += x;
2238 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
2239 unsigned long x = per_cpu(memcg->stat->events[i], cpu);
2241 per_cpu(memcg->stat->events[i], cpu) = 0;
2242 memcg->nocpu_base.events[i] += x;
2244 /* need to clear ON_MOVE value, works as a kind of lock. */
2245 per_cpu(memcg->stat->count[MEM_CGROUP_ON_MOVE], cpu) = 0;
2246 spin_unlock(&memcg->pcp_counter_lock);
2249 static void synchronize_mem_cgroup_on_move(struct mem_cgroup *memcg, int cpu)
2251 int idx = MEM_CGROUP_ON_MOVE;
2253 spin_lock(&memcg->pcp_counter_lock);
2254 per_cpu(memcg->stat->count[idx], cpu) = memcg->nocpu_base.count[idx];
2255 spin_unlock(&memcg->pcp_counter_lock);
2258 static int __cpuinit memcg_cpu_hotplug_callback(struct notifier_block *nb,
2259 unsigned long action,
2260 void *hcpu)
2262 int cpu = (unsigned long)hcpu;
2263 struct memcg_stock_pcp *stock;
2264 struct mem_cgroup *iter;
2266 if ((action == CPU_ONLINE)) {
2267 for_each_mem_cgroup_all(iter)
2268 synchronize_mem_cgroup_on_move(iter, cpu);
2269 return NOTIFY_OK;
2272 if ((action != CPU_DEAD) || action != CPU_DEAD_FROZEN)
2273 return NOTIFY_OK;
2275 for_each_mem_cgroup_all(iter)
2276 mem_cgroup_drain_pcp_counter(iter, cpu);
2278 stock = &per_cpu(memcg_stock, cpu);
2279 drain_stock(stock);
2280 return NOTIFY_OK;
2284 /* See __mem_cgroup_try_charge() for details */
2285 enum {
2286 CHARGE_OK, /* success */
2287 CHARGE_RETRY, /* need to retry but retry is not bad */
2288 CHARGE_NOMEM, /* we can't do more. return -ENOMEM */
2289 CHARGE_WOULDBLOCK, /* GFP_WAIT wasn't set and no enough res. */
2290 CHARGE_OOM_DIE, /* the current is killed because of OOM */
2293 static int mem_cgroup_do_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2294 unsigned int nr_pages, bool oom_check)
2296 unsigned long csize = nr_pages * PAGE_SIZE;
2297 struct mem_cgroup *mem_over_limit;
2298 struct res_counter *fail_res;
2299 unsigned long flags = 0;
2300 int ret;
2302 ret = res_counter_charge(&memcg->res, csize, &fail_res);
2304 if (likely(!ret)) {
2305 if (!do_swap_account)
2306 return CHARGE_OK;
2307 ret = res_counter_charge(&memcg->memsw, csize, &fail_res);
2308 if (likely(!ret))
2309 return CHARGE_OK;
2311 res_counter_uncharge(&memcg->res, csize);
2312 mem_over_limit = mem_cgroup_from_res_counter(fail_res, memsw);
2313 flags |= MEM_CGROUP_RECLAIM_NOSWAP;
2314 } else
2315 mem_over_limit = mem_cgroup_from_res_counter(fail_res, res);
2317 * nr_pages can be either a huge page (HPAGE_PMD_NR), a batch
2318 * of regular pages (CHARGE_BATCH), or a single regular page (1).
2320 * Never reclaim on behalf of optional batching, retry with a
2321 * single page instead.
2323 if (nr_pages == CHARGE_BATCH)
2324 return CHARGE_RETRY;
2326 if (!(gfp_mask & __GFP_WAIT))
2327 return CHARGE_WOULDBLOCK;
2329 ret = mem_cgroup_hierarchical_reclaim(mem_over_limit, NULL,
2330 gfp_mask, flags, NULL);
2331 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2332 return CHARGE_RETRY;
2334 * Even though the limit is exceeded at this point, reclaim
2335 * may have been able to free some pages. Retry the charge
2336 * before killing the task.
2338 * Only for regular pages, though: huge pages are rather
2339 * unlikely to succeed so close to the limit, and we fall back
2340 * to regular pages anyway in case of failure.
2342 if (nr_pages == 1 && ret)
2343 return CHARGE_RETRY;
2346 * At task move, charge accounts can be doubly counted. So, it's
2347 * better to wait until the end of task_move if something is going on.
2349 if (mem_cgroup_wait_acct_move(mem_over_limit))
2350 return CHARGE_RETRY;
2352 /* If we don't need to call oom-killer at el, return immediately */
2353 if (!oom_check)
2354 return CHARGE_NOMEM;
2355 /* check OOM */
2356 if (!mem_cgroup_handle_oom(mem_over_limit, gfp_mask))
2357 return CHARGE_OOM_DIE;
2359 return CHARGE_RETRY;
2363 * Unlike exported interface, "oom" parameter is added. if oom==true,
2364 * oom-killer can be invoked.
2366 static int __mem_cgroup_try_charge(struct mm_struct *mm,
2367 gfp_t gfp_mask,
2368 unsigned int nr_pages,
2369 struct mem_cgroup **ptr,
2370 bool oom)
2372 unsigned int batch = max(CHARGE_BATCH, nr_pages);
2373 int nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2374 struct mem_cgroup *memcg = NULL;
2375 int ret;
2378 * Unlike gloval-vm's OOM-kill, we're not in memory shortage
2379 * in system level. So, allow to go ahead dying process in addition to
2380 * MEMDIE process.
2382 if (unlikely(test_thread_flag(TIF_MEMDIE)
2383 || fatal_signal_pending(current)))
2384 goto bypass;
2387 * We always charge the cgroup the mm_struct belongs to.
2388 * The mm_struct's mem_cgroup changes on task migration if the
2389 * thread group leader migrates. It's possible that mm is not
2390 * set, if so charge the init_mm (happens for pagecache usage).
2392 if (!*ptr && !mm)
2393 goto bypass;
2394 again:
2395 if (*ptr) { /* css should be a valid one */
2396 memcg = *ptr;
2397 VM_BUG_ON(css_is_removed(&memcg->css));
2398 if (mem_cgroup_is_root(memcg))
2399 goto done;
2400 if (nr_pages == 1 && consume_stock(memcg))
2401 goto done;
2402 css_get(&memcg->css);
2403 } else {
2404 struct task_struct *p;
2406 rcu_read_lock();
2407 p = rcu_dereference(mm->owner);
2409 * Because we don't have task_lock(), "p" can exit.
2410 * In that case, "memcg" can point to root or p can be NULL with
2411 * race with swapoff. Then, we have small risk of mis-accouning.
2412 * But such kind of mis-account by race always happens because
2413 * we don't have cgroup_mutex(). It's overkill and we allo that
2414 * small race, here.
2415 * (*) swapoff at el will charge against mm-struct not against
2416 * task-struct. So, mm->owner can be NULL.
2418 memcg = mem_cgroup_from_task(p);
2419 if (!memcg || mem_cgroup_is_root(memcg)) {
2420 rcu_read_unlock();
2421 goto done;
2423 if (nr_pages == 1 && consume_stock(memcg)) {
2425 * It seems dagerous to access memcg without css_get().
2426 * But considering how consume_stok works, it's not
2427 * necessary. If consume_stock success, some charges
2428 * from this memcg are cached on this cpu. So, we
2429 * don't need to call css_get()/css_tryget() before
2430 * calling consume_stock().
2432 rcu_read_unlock();
2433 goto done;
2435 /* after here, we may be blocked. we need to get refcnt */
2436 if (!css_tryget(&memcg->css)) {
2437 rcu_read_unlock();
2438 goto again;
2440 rcu_read_unlock();
2443 do {
2444 bool oom_check;
2446 /* If killed, bypass charge */
2447 if (fatal_signal_pending(current)) {
2448 css_put(&memcg->css);
2449 goto bypass;
2452 oom_check = false;
2453 if (oom && !nr_oom_retries) {
2454 oom_check = true;
2455 nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2458 ret = mem_cgroup_do_charge(memcg, gfp_mask, batch, oom_check);
2459 switch (ret) {
2460 case CHARGE_OK:
2461 break;
2462 case CHARGE_RETRY: /* not in OOM situation but retry */
2463 batch = nr_pages;
2464 css_put(&memcg->css);
2465 memcg = NULL;
2466 goto again;
2467 case CHARGE_WOULDBLOCK: /* !__GFP_WAIT */
2468 css_put(&memcg->css);
2469 goto nomem;
2470 case CHARGE_NOMEM: /* OOM routine works */
2471 if (!oom) {
2472 css_put(&memcg->css);
2473 goto nomem;
2475 /* If oom, we never return -ENOMEM */
2476 nr_oom_retries--;
2477 break;
2478 case CHARGE_OOM_DIE: /* Killed by OOM Killer */
2479 css_put(&memcg->css);
2480 goto bypass;
2482 } while (ret != CHARGE_OK);
2484 if (batch > nr_pages)
2485 refill_stock(memcg, batch - nr_pages);
2486 css_put(&memcg->css);
2487 done:
2488 *ptr = memcg;
2489 return 0;
2490 nomem:
2491 *ptr = NULL;
2492 return -ENOMEM;
2493 bypass:
2494 *ptr = NULL;
2495 return 0;
2499 * Somemtimes we have to undo a charge we got by try_charge().
2500 * This function is for that and do uncharge, put css's refcnt.
2501 * gotten by try_charge().
2503 static void __mem_cgroup_cancel_charge(struct mem_cgroup *memcg,
2504 unsigned int nr_pages)
2506 if (!mem_cgroup_is_root(memcg)) {
2507 unsigned long bytes = nr_pages * PAGE_SIZE;
2509 res_counter_uncharge(&memcg->res, bytes);
2510 if (do_swap_account)
2511 res_counter_uncharge(&memcg->memsw, bytes);
2516 * A helper function to get mem_cgroup from ID. must be called under
2517 * rcu_read_lock(). The caller must check css_is_removed() or some if
2518 * it's concern. (dropping refcnt from swap can be called against removed
2519 * memcg.)
2521 static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
2523 struct cgroup_subsys_state *css;
2525 /* ID 0 is unused ID */
2526 if (!id)
2527 return NULL;
2528 css = css_lookup(&mem_cgroup_subsys, id);
2529 if (!css)
2530 return NULL;
2531 return container_of(css, struct mem_cgroup, css);
2534 struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
2536 struct mem_cgroup *memcg = NULL;
2537 struct page_cgroup *pc;
2538 unsigned short id;
2539 swp_entry_t ent;
2541 VM_BUG_ON(!PageLocked(page));
2543 pc = lookup_page_cgroup(page);
2544 lock_page_cgroup(pc);
2545 if (PageCgroupUsed(pc)) {
2546 memcg = pc->mem_cgroup;
2547 if (memcg && !css_tryget(&memcg->css))
2548 memcg = NULL;
2549 } else if (PageSwapCache(page)) {
2550 ent.val = page_private(page);
2551 id = lookup_swap_cgroup(ent);
2552 rcu_read_lock();
2553 memcg = mem_cgroup_lookup(id);
2554 if (memcg && !css_tryget(&memcg->css))
2555 memcg = NULL;
2556 rcu_read_unlock();
2558 unlock_page_cgroup(pc);
2559 return memcg;
2562 static void __mem_cgroup_commit_charge(struct mem_cgroup *memcg,
2563 struct page *page,
2564 unsigned int nr_pages,
2565 struct page_cgroup *pc,
2566 enum charge_type ctype)
2568 lock_page_cgroup(pc);
2569 if (unlikely(PageCgroupUsed(pc))) {
2570 unlock_page_cgroup(pc);
2571 __mem_cgroup_cancel_charge(memcg, nr_pages);
2572 return;
2575 * we don't need page_cgroup_lock about tail pages, becase they are not
2576 * accessed by any other context at this point.
2578 pc->mem_cgroup = memcg;
2580 * We access a page_cgroup asynchronously without lock_page_cgroup().
2581 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
2582 * is accessed after testing USED bit. To make pc->mem_cgroup visible
2583 * before USED bit, we need memory barrier here.
2584 * See mem_cgroup_add_lru_list(), etc.
2586 smp_wmb();
2587 switch (ctype) {
2588 case MEM_CGROUP_CHARGE_TYPE_CACHE:
2589 case MEM_CGROUP_CHARGE_TYPE_SHMEM:
2590 SetPageCgroupCache(pc);
2591 SetPageCgroupUsed(pc);
2592 break;
2593 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
2594 ClearPageCgroupCache(pc);
2595 SetPageCgroupUsed(pc);
2596 break;
2597 default:
2598 break;
2601 mem_cgroup_charge_statistics(memcg, PageCgroupCache(pc), nr_pages);
2602 unlock_page_cgroup(pc);
2604 * "charge_statistics" updated event counter. Then, check it.
2605 * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
2606 * if they exceeds softlimit.
2608 memcg_check_events(memcg, page);
2611 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
2613 #define PCGF_NOCOPY_AT_SPLIT ((1 << PCG_LOCK) | (1 << PCG_MOVE_LOCK) |\
2614 (1 << PCG_ACCT_LRU) | (1 << PCG_MIGRATION))
2616 * Because tail pages are not marked as "used", set it. We're under
2617 * zone->lru_lock, 'splitting on pmd' and compund_lock.
2619 void mem_cgroup_split_huge_fixup(struct page *head, struct page *tail)
2621 struct page_cgroup *head_pc = lookup_page_cgroup(head);
2622 struct page_cgroup *tail_pc = lookup_page_cgroup(tail);
2623 unsigned long flags;
2625 if (mem_cgroup_disabled())
2626 return;
2628 * We have no races with charge/uncharge but will have races with
2629 * page state accounting.
2631 move_lock_page_cgroup(head_pc, &flags);
2633 tail_pc->mem_cgroup = head_pc->mem_cgroup;
2634 smp_wmb(); /* see __commit_charge() */
2635 if (PageCgroupAcctLRU(head_pc)) {
2636 enum lru_list lru;
2637 struct mem_cgroup_per_zone *mz;
2640 * LRU flags cannot be copied because we need to add tail
2641 *.page to LRU by generic call and our hook will be called.
2642 * We hold lru_lock, then, reduce counter directly.
2644 lru = page_lru(head);
2645 mz = page_cgroup_zoneinfo(head_pc->mem_cgroup, head);
2646 MEM_CGROUP_ZSTAT(mz, lru) -= 1;
2648 tail_pc->flags = head_pc->flags & ~PCGF_NOCOPY_AT_SPLIT;
2649 move_unlock_page_cgroup(head_pc, &flags);
2651 #endif
2654 * mem_cgroup_move_account - move account of the page
2655 * @page: the page
2656 * @nr_pages: number of regular pages (>1 for huge pages)
2657 * @pc: page_cgroup of the page.
2658 * @from: mem_cgroup which the page is moved from.
2659 * @to: mem_cgroup which the page is moved to. @from != @to.
2660 * @uncharge: whether we should call uncharge and css_put against @from.
2662 * The caller must confirm following.
2663 * - page is not on LRU (isolate_page() is useful.)
2664 * - compound_lock is held when nr_pages > 1
2666 * This function doesn't do "charge" nor css_get to new cgroup. It should be
2667 * done by a caller(__mem_cgroup_try_charge would be useful). If @uncharge is
2668 * true, this function does "uncharge" from old cgroup, but it doesn't if
2669 * @uncharge is false, so a caller should do "uncharge".
2671 static int mem_cgroup_move_account(struct page *page,
2672 unsigned int nr_pages,
2673 struct page_cgroup *pc,
2674 struct mem_cgroup *from,
2675 struct mem_cgroup *to,
2676 bool uncharge)
2678 unsigned long flags;
2679 int ret;
2681 VM_BUG_ON(from == to);
2682 VM_BUG_ON(PageLRU(page));
2684 * The page is isolated from LRU. So, collapse function
2685 * will not handle this page. But page splitting can happen.
2686 * Do this check under compound_page_lock(). The caller should
2687 * hold it.
2689 ret = -EBUSY;
2690 if (nr_pages > 1 && !PageTransHuge(page))
2691 goto out;
2693 lock_page_cgroup(pc);
2695 ret = -EINVAL;
2696 if (!PageCgroupUsed(pc) || pc->mem_cgroup != from)
2697 goto unlock;
2699 move_lock_page_cgroup(pc, &flags);
2701 if (PageCgroupFileMapped(pc)) {
2702 /* Update mapped_file data for mem_cgroup */
2703 this_cpu_dec(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
2704 this_cpu_inc(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
2706 mem_cgroup_charge_statistics(from, PageCgroupCache(pc), -nr_pages);
2707 if (uncharge)
2708 /* This is not "cancel", but cancel_charge does all we need. */
2709 __mem_cgroup_cancel_charge(from, nr_pages);
2711 /* caller should have done css_get */
2712 pc->mem_cgroup = to;
2713 mem_cgroup_charge_statistics(to, PageCgroupCache(pc), nr_pages);
2715 * We charges against "to" which may not have any tasks. Then, "to"
2716 * can be under rmdir(). But in current implementation, caller of
2717 * this function is just force_empty() and move charge, so it's
2718 * guaranteed that "to" is never removed. So, we don't check rmdir
2719 * status here.
2721 move_unlock_page_cgroup(pc, &flags);
2722 ret = 0;
2723 unlock:
2724 unlock_page_cgroup(pc);
2726 * check events
2728 memcg_check_events(to, page);
2729 memcg_check_events(from, page);
2730 out:
2731 return ret;
2735 * move charges to its parent.
2738 static int mem_cgroup_move_parent(struct page *page,
2739 struct page_cgroup *pc,
2740 struct mem_cgroup *child,
2741 gfp_t gfp_mask)
2743 struct cgroup *cg = child->css.cgroup;
2744 struct cgroup *pcg = cg->parent;
2745 struct mem_cgroup *parent;
2746 unsigned int nr_pages;
2747 unsigned long uninitialized_var(flags);
2748 int ret;
2750 /* Is ROOT ? */
2751 if (!pcg)
2752 return -EINVAL;
2754 ret = -EBUSY;
2755 if (!get_page_unless_zero(page))
2756 goto out;
2757 if (isolate_lru_page(page))
2758 goto put;
2760 nr_pages = hpage_nr_pages(page);
2762 parent = mem_cgroup_from_cont(pcg);
2763 ret = __mem_cgroup_try_charge(NULL, gfp_mask, nr_pages, &parent, false);
2764 if (ret || !parent)
2765 goto put_back;
2767 if (nr_pages > 1)
2768 flags = compound_lock_irqsave(page);
2770 ret = mem_cgroup_move_account(page, nr_pages, pc, child, parent, true);
2771 if (ret)
2772 __mem_cgroup_cancel_charge(parent, nr_pages);
2774 if (nr_pages > 1)
2775 compound_unlock_irqrestore(page, flags);
2776 put_back:
2777 putback_lru_page(page);
2778 put:
2779 put_page(page);
2780 out:
2781 return ret;
2785 * Charge the memory controller for page usage.
2786 * Return
2787 * 0 if the charge was successful
2788 * < 0 if the cgroup is over its limit
2790 static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
2791 gfp_t gfp_mask, enum charge_type ctype)
2793 struct mem_cgroup *memcg = NULL;
2794 unsigned int nr_pages = 1;
2795 struct page_cgroup *pc;
2796 bool oom = true;
2797 int ret;
2799 if (PageTransHuge(page)) {
2800 nr_pages <<= compound_order(page);
2801 VM_BUG_ON(!PageTransHuge(page));
2803 * Never OOM-kill a process for a huge page. The
2804 * fault handler will fall back to regular pages.
2806 oom = false;
2809 pc = lookup_page_cgroup(page);
2810 BUG_ON(!pc); /* XXX: remove this and move pc lookup into commit */
2812 ret = __mem_cgroup_try_charge(mm, gfp_mask, nr_pages, &memcg, oom);
2813 if (ret || !memcg)
2814 return ret;
2816 __mem_cgroup_commit_charge(memcg, page, nr_pages, pc, ctype);
2817 return 0;
2820 int mem_cgroup_newpage_charge(struct page *page,
2821 struct mm_struct *mm, gfp_t gfp_mask)
2823 if (mem_cgroup_disabled())
2824 return 0;
2826 * If already mapped, we don't have to account.
2827 * If page cache, page->mapping has address_space.
2828 * But page->mapping may have out-of-use anon_vma pointer,
2829 * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
2830 * is NULL.
2832 if (page_mapped(page) || (page->mapping && !PageAnon(page)))
2833 return 0;
2834 if (unlikely(!mm))
2835 mm = &init_mm;
2836 return mem_cgroup_charge_common(page, mm, gfp_mask,
2837 MEM_CGROUP_CHARGE_TYPE_MAPPED);
2840 static void
2841 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
2842 enum charge_type ctype);
2844 static void
2845 __mem_cgroup_commit_charge_lrucare(struct page *page, struct mem_cgroup *memcg,
2846 enum charge_type ctype)
2848 struct page_cgroup *pc = lookup_page_cgroup(page);
2850 * In some case, SwapCache, FUSE(splice_buf->radixtree), the page
2851 * is already on LRU. It means the page may on some other page_cgroup's
2852 * LRU. Take care of it.
2854 mem_cgroup_lru_del_before_commit(page);
2855 __mem_cgroup_commit_charge(memcg, page, 1, pc, ctype);
2856 mem_cgroup_lru_add_after_commit(page);
2857 return;
2860 int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
2861 gfp_t gfp_mask)
2863 struct mem_cgroup *memcg = NULL;
2864 int ret;
2866 if (mem_cgroup_disabled())
2867 return 0;
2868 if (PageCompound(page))
2869 return 0;
2871 if (unlikely(!mm))
2872 mm = &init_mm;
2874 if (page_is_file_cache(page)) {
2875 ret = __mem_cgroup_try_charge(mm, gfp_mask, 1, &memcg, true);
2876 if (ret || !memcg)
2877 return ret;
2880 * FUSE reuses pages without going through the final
2881 * put that would remove them from the LRU list, make
2882 * sure that they get relinked properly.
2884 __mem_cgroup_commit_charge_lrucare(page, memcg,
2885 MEM_CGROUP_CHARGE_TYPE_CACHE);
2886 return ret;
2888 /* shmem */
2889 if (PageSwapCache(page)) {
2890 ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &memcg);
2891 if (!ret)
2892 __mem_cgroup_commit_charge_swapin(page, memcg,
2893 MEM_CGROUP_CHARGE_TYPE_SHMEM);
2894 } else
2895 ret = mem_cgroup_charge_common(page, mm, gfp_mask,
2896 MEM_CGROUP_CHARGE_TYPE_SHMEM);
2898 return ret;
2902 * While swap-in, try_charge -> commit or cancel, the page is locked.
2903 * And when try_charge() successfully returns, one refcnt to memcg without
2904 * struct page_cgroup is acquired. This refcnt will be consumed by
2905 * "commit()" or removed by "cancel()"
2907 int mem_cgroup_try_charge_swapin(struct mm_struct *mm,
2908 struct page *page,
2909 gfp_t mask, struct mem_cgroup **ptr)
2911 struct mem_cgroup *memcg;
2912 int ret;
2914 *ptr = NULL;
2916 if (mem_cgroup_disabled())
2917 return 0;
2919 if (!do_swap_account)
2920 goto charge_cur_mm;
2922 * A racing thread's fault, or swapoff, may have already updated
2923 * the pte, and even removed page from swap cache: in those cases
2924 * do_swap_page()'s pte_same() test will fail; but there's also a
2925 * KSM case which does need to charge the page.
2927 if (!PageSwapCache(page))
2928 goto charge_cur_mm;
2929 memcg = try_get_mem_cgroup_from_page(page);
2930 if (!memcg)
2931 goto charge_cur_mm;
2932 *ptr = memcg;
2933 ret = __mem_cgroup_try_charge(NULL, mask, 1, ptr, true);
2934 css_put(&memcg->css);
2935 return ret;
2936 charge_cur_mm:
2937 if (unlikely(!mm))
2938 mm = &init_mm;
2939 return __mem_cgroup_try_charge(mm, mask, 1, ptr, true);
2942 static void
2943 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
2944 enum charge_type ctype)
2946 if (mem_cgroup_disabled())
2947 return;
2948 if (!ptr)
2949 return;
2950 cgroup_exclude_rmdir(&ptr->css);
2952 __mem_cgroup_commit_charge_lrucare(page, ptr, ctype);
2954 * Now swap is on-memory. This means this page may be
2955 * counted both as mem and swap....double count.
2956 * Fix it by uncharging from memsw. Basically, this SwapCache is stable
2957 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
2958 * may call delete_from_swap_cache() before reach here.
2960 if (do_swap_account && PageSwapCache(page)) {
2961 swp_entry_t ent = {.val = page_private(page)};
2962 unsigned short id;
2963 struct mem_cgroup *memcg;
2965 id = swap_cgroup_record(ent, 0);
2966 rcu_read_lock();
2967 memcg = mem_cgroup_lookup(id);
2968 if (memcg) {
2970 * This recorded memcg can be obsolete one. So, avoid
2971 * calling css_tryget
2973 if (!mem_cgroup_is_root(memcg))
2974 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
2975 mem_cgroup_swap_statistics(memcg, false);
2976 mem_cgroup_put(memcg);
2978 rcu_read_unlock();
2981 * At swapin, we may charge account against cgroup which has no tasks.
2982 * So, rmdir()->pre_destroy() can be called while we do this charge.
2983 * In that case, we need to call pre_destroy() again. check it here.
2985 cgroup_release_and_wakeup_rmdir(&ptr->css);
2988 void mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr)
2990 __mem_cgroup_commit_charge_swapin(page, ptr,
2991 MEM_CGROUP_CHARGE_TYPE_MAPPED);
2994 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *memcg)
2996 if (mem_cgroup_disabled())
2997 return;
2998 if (!memcg)
2999 return;
3000 __mem_cgroup_cancel_charge(memcg, 1);
3003 static void mem_cgroup_do_uncharge(struct mem_cgroup *memcg,
3004 unsigned int nr_pages,
3005 const enum charge_type ctype)
3007 struct memcg_batch_info *batch = NULL;
3008 bool uncharge_memsw = true;
3010 /* If swapout, usage of swap doesn't decrease */
3011 if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
3012 uncharge_memsw = false;
3014 batch = &current->memcg_batch;
3016 * In usual, we do css_get() when we remember memcg pointer.
3017 * But in this case, we keep res->usage until end of a series of
3018 * uncharges. Then, it's ok to ignore memcg's refcnt.
3020 if (!batch->memcg)
3021 batch->memcg = memcg;
3023 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
3024 * In those cases, all pages freed continuously can be expected to be in
3025 * the same cgroup and we have chance to coalesce uncharges.
3026 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
3027 * because we want to do uncharge as soon as possible.
3030 if (!batch->do_batch || test_thread_flag(TIF_MEMDIE))
3031 goto direct_uncharge;
3033 if (nr_pages > 1)
3034 goto direct_uncharge;
3037 * In typical case, batch->memcg == mem. This means we can
3038 * merge a series of uncharges to an uncharge of res_counter.
3039 * If not, we uncharge res_counter ony by one.
3041 if (batch->memcg != memcg)
3042 goto direct_uncharge;
3043 /* remember freed charge and uncharge it later */
3044 batch->nr_pages++;
3045 if (uncharge_memsw)
3046 batch->memsw_nr_pages++;
3047 return;
3048 direct_uncharge:
3049 res_counter_uncharge(&memcg->res, nr_pages * PAGE_SIZE);
3050 if (uncharge_memsw)
3051 res_counter_uncharge(&memcg->memsw, nr_pages * PAGE_SIZE);
3052 if (unlikely(batch->memcg != memcg))
3053 memcg_oom_recover(memcg);
3054 return;
3058 * uncharge if !page_mapped(page)
3060 static struct mem_cgroup *
3061 __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype)
3063 struct mem_cgroup *memcg = NULL;
3064 unsigned int nr_pages = 1;
3065 struct page_cgroup *pc;
3067 if (mem_cgroup_disabled())
3068 return NULL;
3070 if (PageSwapCache(page))
3071 return NULL;
3073 if (PageTransHuge(page)) {
3074 nr_pages <<= compound_order(page);
3075 VM_BUG_ON(!PageTransHuge(page));
3078 * Check if our page_cgroup is valid
3080 pc = lookup_page_cgroup(page);
3081 if (unlikely(!pc || !PageCgroupUsed(pc)))
3082 return NULL;
3084 lock_page_cgroup(pc);
3086 memcg = pc->mem_cgroup;
3088 if (!PageCgroupUsed(pc))
3089 goto unlock_out;
3091 switch (ctype) {
3092 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
3093 case MEM_CGROUP_CHARGE_TYPE_DROP:
3094 /* See mem_cgroup_prepare_migration() */
3095 if (page_mapped(page) || PageCgroupMigration(pc))
3096 goto unlock_out;
3097 break;
3098 case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
3099 if (!PageAnon(page)) { /* Shared memory */
3100 if (page->mapping && !page_is_file_cache(page))
3101 goto unlock_out;
3102 } else if (page_mapped(page)) /* Anon */
3103 goto unlock_out;
3104 break;
3105 default:
3106 break;
3109 mem_cgroup_charge_statistics(memcg, PageCgroupCache(pc), -nr_pages);
3111 ClearPageCgroupUsed(pc);
3113 * pc->mem_cgroup is not cleared here. It will be accessed when it's
3114 * freed from LRU. This is safe because uncharged page is expected not
3115 * to be reused (freed soon). Exception is SwapCache, it's handled by
3116 * special functions.
3119 unlock_page_cgroup(pc);
3121 * even after unlock, we have mem->res.usage here and this memcg
3122 * will never be freed.
3124 memcg_check_events(memcg, page);
3125 if (do_swap_account && ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT) {
3126 mem_cgroup_swap_statistics(memcg, true);
3127 mem_cgroup_get(memcg);
3129 if (!mem_cgroup_is_root(memcg))
3130 mem_cgroup_do_uncharge(memcg, nr_pages, ctype);
3132 return memcg;
3134 unlock_out:
3135 unlock_page_cgroup(pc);
3136 return NULL;
3139 void mem_cgroup_uncharge_page(struct page *page)
3141 /* early check. */
3142 if (page_mapped(page))
3143 return;
3144 if (page->mapping && !PageAnon(page))
3145 return;
3146 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_MAPPED);
3149 void mem_cgroup_uncharge_cache_page(struct page *page)
3151 VM_BUG_ON(page_mapped(page));
3152 VM_BUG_ON(page->mapping);
3153 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE);
3157 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
3158 * In that cases, pages are freed continuously and we can expect pages
3159 * are in the same memcg. All these calls itself limits the number of
3160 * pages freed at once, then uncharge_start/end() is called properly.
3161 * This may be called prural(2) times in a context,
3164 void mem_cgroup_uncharge_start(void)
3166 current->memcg_batch.do_batch++;
3167 /* We can do nest. */
3168 if (current->memcg_batch.do_batch == 1) {
3169 current->memcg_batch.memcg = NULL;
3170 current->memcg_batch.nr_pages = 0;
3171 current->memcg_batch.memsw_nr_pages = 0;
3175 void mem_cgroup_uncharge_end(void)
3177 struct memcg_batch_info *batch = &current->memcg_batch;
3179 if (!batch->do_batch)
3180 return;
3182 batch->do_batch--;
3183 if (batch->do_batch) /* If stacked, do nothing. */
3184 return;
3186 if (!batch->memcg)
3187 return;
3189 * This "batch->memcg" is valid without any css_get/put etc...
3190 * bacause we hide charges behind us.
3192 if (batch->nr_pages)
3193 res_counter_uncharge(&batch->memcg->res,
3194 batch->nr_pages * PAGE_SIZE);
3195 if (batch->memsw_nr_pages)
3196 res_counter_uncharge(&batch->memcg->memsw,
3197 batch->memsw_nr_pages * PAGE_SIZE);
3198 memcg_oom_recover(batch->memcg);
3199 /* forget this pointer (for sanity check) */
3200 batch->memcg = NULL;
3203 #ifdef CONFIG_SWAP
3205 * called after __delete_from_swap_cache() and drop "page" account.
3206 * memcg information is recorded to swap_cgroup of "ent"
3208 void
3209 mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
3211 struct mem_cgroup *memcg;
3212 int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
3214 if (!swapout) /* this was a swap cache but the swap is unused ! */
3215 ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
3217 memcg = __mem_cgroup_uncharge_common(page, ctype);
3220 * record memcg information, if swapout && memcg != NULL,
3221 * mem_cgroup_get() was called in uncharge().
3223 if (do_swap_account && swapout && memcg)
3224 swap_cgroup_record(ent, css_id(&memcg->css));
3226 #endif
3228 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3230 * called from swap_entry_free(). remove record in swap_cgroup and
3231 * uncharge "memsw" account.
3233 void mem_cgroup_uncharge_swap(swp_entry_t ent)
3235 struct mem_cgroup *memcg;
3236 unsigned short id;
3238 if (!do_swap_account)
3239 return;
3241 id = swap_cgroup_record(ent, 0);
3242 rcu_read_lock();
3243 memcg = mem_cgroup_lookup(id);
3244 if (memcg) {
3246 * We uncharge this because swap is freed.
3247 * This memcg can be obsolete one. We avoid calling css_tryget
3249 if (!mem_cgroup_is_root(memcg))
3250 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
3251 mem_cgroup_swap_statistics(memcg, false);
3252 mem_cgroup_put(memcg);
3254 rcu_read_unlock();
3258 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3259 * @entry: swap entry to be moved
3260 * @from: mem_cgroup which the entry is moved from
3261 * @to: mem_cgroup which the entry is moved to
3262 * @need_fixup: whether we should fixup res_counters and refcounts.
3264 * It succeeds only when the swap_cgroup's record for this entry is the same
3265 * as the mem_cgroup's id of @from.
3267 * Returns 0 on success, -EINVAL on failure.
3269 * The caller must have charged to @to, IOW, called res_counter_charge() about
3270 * both res and memsw, and called css_get().
3272 static int mem_cgroup_move_swap_account(swp_entry_t entry,
3273 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
3275 unsigned short old_id, new_id;
3277 old_id = css_id(&from->css);
3278 new_id = css_id(&to->css);
3280 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
3281 mem_cgroup_swap_statistics(from, false);
3282 mem_cgroup_swap_statistics(to, true);
3284 * This function is only called from task migration context now.
3285 * It postpones res_counter and refcount handling till the end
3286 * of task migration(mem_cgroup_clear_mc()) for performance
3287 * improvement. But we cannot postpone mem_cgroup_get(to)
3288 * because if the process that has been moved to @to does
3289 * swap-in, the refcount of @to might be decreased to 0.
3291 mem_cgroup_get(to);
3292 if (need_fixup) {
3293 if (!mem_cgroup_is_root(from))
3294 res_counter_uncharge(&from->memsw, PAGE_SIZE);
3295 mem_cgroup_put(from);
3297 * we charged both to->res and to->memsw, so we should
3298 * uncharge to->res.
3300 if (!mem_cgroup_is_root(to))
3301 res_counter_uncharge(&to->res, PAGE_SIZE);
3303 return 0;
3305 return -EINVAL;
3307 #else
3308 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
3309 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
3311 return -EINVAL;
3313 #endif
3316 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
3317 * page belongs to.
3319 int mem_cgroup_prepare_migration(struct page *page,
3320 struct page *newpage, struct mem_cgroup **ptr, gfp_t gfp_mask)
3322 struct mem_cgroup *memcg = NULL;
3323 struct page_cgroup *pc;
3324 enum charge_type ctype;
3325 int ret = 0;
3327 *ptr = NULL;
3329 VM_BUG_ON(PageTransHuge(page));
3330 if (mem_cgroup_disabled())
3331 return 0;
3333 pc = lookup_page_cgroup(page);
3334 lock_page_cgroup(pc);
3335 if (PageCgroupUsed(pc)) {
3336 memcg = pc->mem_cgroup;
3337 css_get(&memcg->css);
3339 * At migrating an anonymous page, its mapcount goes down
3340 * to 0 and uncharge() will be called. But, even if it's fully
3341 * unmapped, migration may fail and this page has to be
3342 * charged again. We set MIGRATION flag here and delay uncharge
3343 * until end_migration() is called
3345 * Corner Case Thinking
3346 * A)
3347 * When the old page was mapped as Anon and it's unmap-and-freed
3348 * while migration was ongoing.
3349 * If unmap finds the old page, uncharge() of it will be delayed
3350 * until end_migration(). If unmap finds a new page, it's
3351 * uncharged when it make mapcount to be 1->0. If unmap code
3352 * finds swap_migration_entry, the new page will not be mapped
3353 * and end_migration() will find it(mapcount==0).
3355 * B)
3356 * When the old page was mapped but migraion fails, the kernel
3357 * remaps it. A charge for it is kept by MIGRATION flag even
3358 * if mapcount goes down to 0. We can do remap successfully
3359 * without charging it again.
3361 * C)
3362 * The "old" page is under lock_page() until the end of
3363 * migration, so, the old page itself will not be swapped-out.
3364 * If the new page is swapped out before end_migraton, our
3365 * hook to usual swap-out path will catch the event.
3367 if (PageAnon(page))
3368 SetPageCgroupMigration(pc);
3370 unlock_page_cgroup(pc);
3372 * If the page is not charged at this point,
3373 * we return here.
3375 if (!memcg)
3376 return 0;
3378 *ptr = memcg;
3379 ret = __mem_cgroup_try_charge(NULL, gfp_mask, 1, ptr, false);
3380 css_put(&memcg->css);/* drop extra refcnt */
3381 if (ret || *ptr == NULL) {
3382 if (PageAnon(page)) {
3383 lock_page_cgroup(pc);
3384 ClearPageCgroupMigration(pc);
3385 unlock_page_cgroup(pc);
3387 * The old page may be fully unmapped while we kept it.
3389 mem_cgroup_uncharge_page(page);
3391 return -ENOMEM;
3394 * We charge new page before it's used/mapped. So, even if unlock_page()
3395 * is called before end_migration, we can catch all events on this new
3396 * page. In the case new page is migrated but not remapped, new page's
3397 * mapcount will be finally 0 and we call uncharge in end_migration().
3399 pc = lookup_page_cgroup(newpage);
3400 if (PageAnon(page))
3401 ctype = MEM_CGROUP_CHARGE_TYPE_MAPPED;
3402 else if (page_is_file_cache(page))
3403 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
3404 else
3405 ctype = MEM_CGROUP_CHARGE_TYPE_SHMEM;
3406 __mem_cgroup_commit_charge(memcg, page, 1, pc, ctype);
3407 return ret;
3410 /* remove redundant charge if migration failed*/
3411 void mem_cgroup_end_migration(struct mem_cgroup *memcg,
3412 struct page *oldpage, struct page *newpage, bool migration_ok)
3414 struct page *used, *unused;
3415 struct page_cgroup *pc;
3417 if (!memcg)
3418 return;
3419 /* blocks rmdir() */
3420 cgroup_exclude_rmdir(&memcg->css);
3421 if (!migration_ok) {
3422 used = oldpage;
3423 unused = newpage;
3424 } else {
3425 used = newpage;
3426 unused = oldpage;
3429 * We disallowed uncharge of pages under migration because mapcount
3430 * of the page goes down to zero, temporarly.
3431 * Clear the flag and check the page should be charged.
3433 pc = lookup_page_cgroup(oldpage);
3434 lock_page_cgroup(pc);
3435 ClearPageCgroupMigration(pc);
3436 unlock_page_cgroup(pc);
3438 __mem_cgroup_uncharge_common(unused, MEM_CGROUP_CHARGE_TYPE_FORCE);
3441 * If a page is a file cache, radix-tree replacement is very atomic
3442 * and we can skip this check. When it was an Anon page, its mapcount
3443 * goes down to 0. But because we added MIGRATION flage, it's not
3444 * uncharged yet. There are several case but page->mapcount check
3445 * and USED bit check in mem_cgroup_uncharge_page() will do enough
3446 * check. (see prepare_charge() also)
3448 if (PageAnon(used))
3449 mem_cgroup_uncharge_page(used);
3451 * At migration, we may charge account against cgroup which has no
3452 * tasks.
3453 * So, rmdir()->pre_destroy() can be called while we do this charge.
3454 * In that case, we need to call pre_destroy() again. check it here.
3456 cgroup_release_and_wakeup_rmdir(&memcg->css);
3459 #ifdef CONFIG_DEBUG_VM
3460 static struct page_cgroup *lookup_page_cgroup_used(struct page *page)
3462 struct page_cgroup *pc;
3464 pc = lookup_page_cgroup(page);
3465 if (likely(pc) && PageCgroupUsed(pc))
3466 return pc;
3467 return NULL;
3470 bool mem_cgroup_bad_page_check(struct page *page)
3472 if (mem_cgroup_disabled())
3473 return false;
3475 return lookup_page_cgroup_used(page) != NULL;
3478 void mem_cgroup_print_bad_page(struct page *page)
3480 struct page_cgroup *pc;
3482 pc = lookup_page_cgroup_used(page);
3483 if (pc) {
3484 int ret = -1;
3485 char *path;
3487 printk(KERN_ALERT "pc:%p pc->flags:%lx pc->mem_cgroup:%p",
3488 pc, pc->flags, pc->mem_cgroup);
3490 path = kmalloc(PATH_MAX, GFP_KERNEL);
3491 if (path) {
3492 rcu_read_lock();
3493 ret = cgroup_path(pc->mem_cgroup->css.cgroup,
3494 path, PATH_MAX);
3495 rcu_read_unlock();
3498 printk(KERN_CONT "(%s)\n",
3499 (ret < 0) ? "cannot get the path" : path);
3500 kfree(path);
3503 #endif
3505 static DEFINE_MUTEX(set_limit_mutex);
3507 static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
3508 unsigned long long val)
3510 int retry_count;
3511 u64 memswlimit, memlimit;
3512 int ret = 0;
3513 int children = mem_cgroup_count_children(memcg);
3514 u64 curusage, oldusage;
3515 int enlarge;
3518 * For keeping hierarchical_reclaim simple, how long we should retry
3519 * is depends on callers. We set our retry-count to be function
3520 * of # of children which we should visit in this loop.
3522 retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
3524 oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
3526 enlarge = 0;
3527 while (retry_count) {
3528 if (signal_pending(current)) {
3529 ret = -EINTR;
3530 break;
3533 * Rather than hide all in some function, I do this in
3534 * open coded manner. You see what this really does.
3535 * We have to guarantee memcg->res.limit < memcg->memsw.limit.
3537 mutex_lock(&set_limit_mutex);
3538 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3539 if (memswlimit < val) {
3540 ret = -EINVAL;
3541 mutex_unlock(&set_limit_mutex);
3542 break;
3545 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3546 if (memlimit < val)
3547 enlarge = 1;
3549 ret = res_counter_set_limit(&memcg->res, val);
3550 if (!ret) {
3551 if (memswlimit == val)
3552 memcg->memsw_is_minimum = true;
3553 else
3554 memcg->memsw_is_minimum = false;
3556 mutex_unlock(&set_limit_mutex);
3558 if (!ret)
3559 break;
3561 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
3562 MEM_CGROUP_RECLAIM_SHRINK,
3563 NULL);
3564 curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
3565 /* Usage is reduced ? */
3566 if (curusage >= oldusage)
3567 retry_count--;
3568 else
3569 oldusage = curusage;
3571 if (!ret && enlarge)
3572 memcg_oom_recover(memcg);
3574 return ret;
3577 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
3578 unsigned long long val)
3580 int retry_count;
3581 u64 memlimit, memswlimit, oldusage, curusage;
3582 int children = mem_cgroup_count_children(memcg);
3583 int ret = -EBUSY;
3584 int enlarge = 0;
3586 /* see mem_cgroup_resize_res_limit */
3587 retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
3588 oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
3589 while (retry_count) {
3590 if (signal_pending(current)) {
3591 ret = -EINTR;
3592 break;
3595 * Rather than hide all in some function, I do this in
3596 * open coded manner. You see what this really does.
3597 * We have to guarantee memcg->res.limit < memcg->memsw.limit.
3599 mutex_lock(&set_limit_mutex);
3600 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3601 if (memlimit > val) {
3602 ret = -EINVAL;
3603 mutex_unlock(&set_limit_mutex);
3604 break;
3606 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3607 if (memswlimit < val)
3608 enlarge = 1;
3609 ret = res_counter_set_limit(&memcg->memsw, val);
3610 if (!ret) {
3611 if (memlimit == val)
3612 memcg->memsw_is_minimum = true;
3613 else
3614 memcg->memsw_is_minimum = false;
3616 mutex_unlock(&set_limit_mutex);
3618 if (!ret)
3619 break;
3621 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
3622 MEM_CGROUP_RECLAIM_NOSWAP |
3623 MEM_CGROUP_RECLAIM_SHRINK,
3624 NULL);
3625 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
3626 /* Usage is reduced ? */
3627 if (curusage >= oldusage)
3628 retry_count--;
3629 else
3630 oldusage = curusage;
3632 if (!ret && enlarge)
3633 memcg_oom_recover(memcg);
3634 return ret;
3637 unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
3638 gfp_t gfp_mask,
3639 unsigned long *total_scanned)
3641 unsigned long nr_reclaimed = 0;
3642 struct mem_cgroup_per_zone *mz, *next_mz = NULL;
3643 unsigned long reclaimed;
3644 int loop = 0;
3645 struct mem_cgroup_tree_per_zone *mctz;
3646 unsigned long long excess;
3647 unsigned long nr_scanned;
3649 if (order > 0)
3650 return 0;
3652 mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone));
3654 * This loop can run a while, specially if mem_cgroup's continuously
3655 * keep exceeding their soft limit and putting the system under
3656 * pressure
3658 do {
3659 if (next_mz)
3660 mz = next_mz;
3661 else
3662 mz = mem_cgroup_largest_soft_limit_node(mctz);
3663 if (!mz)
3664 break;
3666 nr_scanned = 0;
3667 reclaimed = mem_cgroup_hierarchical_reclaim(mz->mem, zone,
3668 gfp_mask,
3669 MEM_CGROUP_RECLAIM_SOFT,
3670 &nr_scanned);
3671 nr_reclaimed += reclaimed;
3672 *total_scanned += nr_scanned;
3673 spin_lock(&mctz->lock);
3676 * If we failed to reclaim anything from this memory cgroup
3677 * it is time to move on to the next cgroup
3679 next_mz = NULL;
3680 if (!reclaimed) {
3681 do {
3683 * Loop until we find yet another one.
3685 * By the time we get the soft_limit lock
3686 * again, someone might have aded the
3687 * group back on the RB tree. Iterate to
3688 * make sure we get a different mem.
3689 * mem_cgroup_largest_soft_limit_node returns
3690 * NULL if no other cgroup is present on
3691 * the tree
3693 next_mz =
3694 __mem_cgroup_largest_soft_limit_node(mctz);
3695 if (next_mz == mz)
3696 css_put(&next_mz->mem->css);
3697 else /* next_mz == NULL or other memcg */
3698 break;
3699 } while (1);
3701 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
3702 excess = res_counter_soft_limit_excess(&mz->mem->res);
3704 * One school of thought says that we should not add
3705 * back the node to the tree if reclaim returns 0.
3706 * But our reclaim could return 0, simply because due
3707 * to priority we are exposing a smaller subset of
3708 * memory to reclaim from. Consider this as a longer
3709 * term TODO.
3711 /* If excess == 0, no tree ops */
3712 __mem_cgroup_insert_exceeded(mz->mem, mz, mctz, excess);
3713 spin_unlock(&mctz->lock);
3714 css_put(&mz->mem->css);
3715 loop++;
3717 * Could not reclaim anything and there are no more
3718 * mem cgroups to try or we seem to be looping without
3719 * reclaiming anything.
3721 if (!nr_reclaimed &&
3722 (next_mz == NULL ||
3723 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3724 break;
3725 } while (!nr_reclaimed);
3726 if (next_mz)
3727 css_put(&next_mz->mem->css);
3728 return nr_reclaimed;
3732 * This routine traverse page_cgroup in given list and drop them all.
3733 * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
3735 static int mem_cgroup_force_empty_list(struct mem_cgroup *memcg,
3736 int node, int zid, enum lru_list lru)
3738 struct zone *zone;
3739 struct mem_cgroup_per_zone *mz;
3740 struct page_cgroup *pc, *busy;
3741 unsigned long flags, loop;
3742 struct list_head *list;
3743 int ret = 0;
3745 zone = &NODE_DATA(node)->node_zones[zid];
3746 mz = mem_cgroup_zoneinfo(memcg, node, zid);
3747 list = &mz->lists[lru];
3749 loop = MEM_CGROUP_ZSTAT(mz, lru);
3750 /* give some margin against EBUSY etc...*/
3751 loop += 256;
3752 busy = NULL;
3753 while (loop--) {
3754 struct page *page;
3756 ret = 0;
3757 spin_lock_irqsave(&zone->lru_lock, flags);
3758 if (list_empty(list)) {
3759 spin_unlock_irqrestore(&zone->lru_lock, flags);
3760 break;
3762 pc = list_entry(list->prev, struct page_cgroup, lru);
3763 if (busy == pc) {
3764 list_move(&pc->lru, list);
3765 busy = NULL;
3766 spin_unlock_irqrestore(&zone->lru_lock, flags);
3767 continue;
3769 spin_unlock_irqrestore(&zone->lru_lock, flags);
3771 page = lookup_cgroup_page(pc);
3773 ret = mem_cgroup_move_parent(page, pc, memcg, GFP_KERNEL);
3774 if (ret == -ENOMEM)
3775 break;
3777 if (ret == -EBUSY || ret == -EINVAL) {
3778 /* found lock contention or "pc" is obsolete. */
3779 busy = pc;
3780 cond_resched();
3781 } else
3782 busy = NULL;
3785 if (!ret && !list_empty(list))
3786 return -EBUSY;
3787 return ret;
3791 * make mem_cgroup's charge to be 0 if there is no task.
3792 * This enables deleting this mem_cgroup.
3794 static int mem_cgroup_force_empty(struct mem_cgroup *memcg, bool free_all)
3796 int ret;
3797 int node, zid, shrink;
3798 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
3799 struct cgroup *cgrp = memcg->css.cgroup;
3801 css_get(&memcg->css);
3803 shrink = 0;
3804 /* should free all ? */
3805 if (free_all)
3806 goto try_to_free;
3807 move_account:
3808 do {
3809 ret = -EBUSY;
3810 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
3811 goto out;
3812 ret = -EINTR;
3813 if (signal_pending(current))
3814 goto out;
3815 /* This is for making all *used* pages to be on LRU. */
3816 lru_add_drain_all();
3817 drain_all_stock_sync(memcg);
3818 ret = 0;
3819 mem_cgroup_start_move(memcg);
3820 for_each_node_state(node, N_HIGH_MEMORY) {
3821 for (zid = 0; !ret && zid < MAX_NR_ZONES; zid++) {
3822 enum lru_list l;
3823 for_each_lru(l) {
3824 ret = mem_cgroup_force_empty_list(memcg,
3825 node, zid, l);
3826 if (ret)
3827 break;
3830 if (ret)
3831 break;
3833 mem_cgroup_end_move(memcg);
3834 memcg_oom_recover(memcg);
3835 /* it seems parent cgroup doesn't have enough mem */
3836 if (ret == -ENOMEM)
3837 goto try_to_free;
3838 cond_resched();
3839 /* "ret" should also be checked to ensure all lists are empty. */
3840 } while (memcg->res.usage > 0 || ret);
3841 out:
3842 css_put(&memcg->css);
3843 return ret;
3845 try_to_free:
3846 /* returns EBUSY if there is a task or if we come here twice. */
3847 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children) || shrink) {
3848 ret = -EBUSY;
3849 goto out;
3851 /* we call try-to-free pages for make this cgroup empty */
3852 lru_add_drain_all();
3853 /* try to free all pages in this cgroup */
3854 shrink = 1;
3855 while (nr_retries && memcg->res.usage > 0) {
3856 struct memcg_scanrecord rec;
3857 int progress;
3859 if (signal_pending(current)) {
3860 ret = -EINTR;
3861 goto out;
3863 rec.context = SCAN_BY_SHRINK;
3864 rec.mem = memcg;
3865 rec.root = memcg;
3866 progress = try_to_free_mem_cgroup_pages(memcg, GFP_KERNEL,
3867 false, &rec);
3868 if (!progress) {
3869 nr_retries--;
3870 /* maybe some writeback is necessary */
3871 congestion_wait(BLK_RW_ASYNC, HZ/10);
3875 lru_add_drain();
3876 /* try move_account...there may be some *locked* pages. */
3877 goto move_account;
3880 int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
3882 return mem_cgroup_force_empty(mem_cgroup_from_cont(cont), true);
3886 static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
3888 return mem_cgroup_from_cont(cont)->use_hierarchy;
3891 static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
3892 u64 val)
3894 int retval = 0;
3895 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
3896 struct cgroup *parent = cont->parent;
3897 struct mem_cgroup *parent_memcg = NULL;
3899 if (parent)
3900 parent_memcg = mem_cgroup_from_cont(parent);
3902 cgroup_lock();
3904 * If parent's use_hierarchy is set, we can't make any modifications
3905 * in the child subtrees. If it is unset, then the change can
3906 * occur, provided the current cgroup has no children.
3908 * For the root cgroup, parent_mem is NULL, we allow value to be
3909 * set if there are no children.
3911 if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
3912 (val == 1 || val == 0)) {
3913 if (list_empty(&cont->children))
3914 memcg->use_hierarchy = val;
3915 else
3916 retval = -EBUSY;
3917 } else
3918 retval = -EINVAL;
3919 cgroup_unlock();
3921 return retval;
3925 static unsigned long mem_cgroup_recursive_stat(struct mem_cgroup *memcg,
3926 enum mem_cgroup_stat_index idx)
3928 struct mem_cgroup *iter;
3929 long val = 0;
3931 /* Per-cpu values can be negative, use a signed accumulator */
3932 for_each_mem_cgroup_tree(iter, memcg)
3933 val += mem_cgroup_read_stat(iter, idx);
3935 if (val < 0) /* race ? */
3936 val = 0;
3937 return val;
3940 static inline u64 mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
3942 u64 val;
3944 if (!mem_cgroup_is_root(memcg)) {
3945 if (!swap)
3946 return res_counter_read_u64(&memcg->res, RES_USAGE);
3947 else
3948 return res_counter_read_u64(&memcg->memsw, RES_USAGE);
3951 val = mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_CACHE);
3952 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_RSS);
3954 if (swap)
3955 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_SWAPOUT);
3957 return val << PAGE_SHIFT;
3960 static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft)
3962 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
3963 u64 val;
3964 int type, name;
3966 type = MEMFILE_TYPE(cft->private);
3967 name = MEMFILE_ATTR(cft->private);
3968 switch (type) {
3969 case _MEM:
3970 if (name == RES_USAGE)
3971 val = mem_cgroup_usage(memcg, false);
3972 else
3973 val = res_counter_read_u64(&memcg->res, name);
3974 break;
3975 case _MEMSWAP:
3976 if (name == RES_USAGE)
3977 val = mem_cgroup_usage(memcg, true);
3978 else
3979 val = res_counter_read_u64(&memcg->memsw, name);
3980 break;
3981 default:
3982 BUG();
3983 break;
3985 return val;
3988 * The user of this function is...
3989 * RES_LIMIT.
3991 static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
3992 const char *buffer)
3994 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
3995 int type, name;
3996 unsigned long long val;
3997 int ret;
3999 type = MEMFILE_TYPE(cft->private);
4000 name = MEMFILE_ATTR(cft->private);
4001 switch (name) {
4002 case RES_LIMIT:
4003 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
4004 ret = -EINVAL;
4005 break;
4007 /* This function does all necessary parse...reuse it */
4008 ret = res_counter_memparse_write_strategy(buffer, &val);
4009 if (ret)
4010 break;
4011 if (type == _MEM)
4012 ret = mem_cgroup_resize_limit(memcg, val);
4013 else
4014 ret = mem_cgroup_resize_memsw_limit(memcg, val);
4015 break;
4016 case RES_SOFT_LIMIT:
4017 ret = res_counter_memparse_write_strategy(buffer, &val);
4018 if (ret)
4019 break;
4021 * For memsw, soft limits are hard to implement in terms
4022 * of semantics, for now, we support soft limits for
4023 * control without swap
4025 if (type == _MEM)
4026 ret = res_counter_set_soft_limit(&memcg->res, val);
4027 else
4028 ret = -EINVAL;
4029 break;
4030 default:
4031 ret = -EINVAL; /* should be BUG() ? */
4032 break;
4034 return ret;
4037 static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
4038 unsigned long long *mem_limit, unsigned long long *memsw_limit)
4040 struct cgroup *cgroup;
4041 unsigned long long min_limit, min_memsw_limit, tmp;
4043 min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
4044 min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
4045 cgroup = memcg->css.cgroup;
4046 if (!memcg->use_hierarchy)
4047 goto out;
4049 while (cgroup->parent) {
4050 cgroup = cgroup->parent;
4051 memcg = mem_cgroup_from_cont(cgroup);
4052 if (!memcg->use_hierarchy)
4053 break;
4054 tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
4055 min_limit = min(min_limit, tmp);
4056 tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
4057 min_memsw_limit = min(min_memsw_limit, tmp);
4059 out:
4060 *mem_limit = min_limit;
4061 *memsw_limit = min_memsw_limit;
4062 return;
4065 static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
4067 struct mem_cgroup *memcg;
4068 int type, name;
4070 memcg = mem_cgroup_from_cont(cont);
4071 type = MEMFILE_TYPE(event);
4072 name = MEMFILE_ATTR(event);
4073 switch (name) {
4074 case RES_MAX_USAGE:
4075 if (type == _MEM)
4076 res_counter_reset_max(&memcg->res);
4077 else
4078 res_counter_reset_max(&memcg->memsw);
4079 break;
4080 case RES_FAILCNT:
4081 if (type == _MEM)
4082 res_counter_reset_failcnt(&memcg->res);
4083 else
4084 res_counter_reset_failcnt(&memcg->memsw);
4085 break;
4088 return 0;
4091 static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp,
4092 struct cftype *cft)
4094 return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate;
4097 #ifdef CONFIG_MMU
4098 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
4099 struct cftype *cft, u64 val)
4101 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4103 if (val >= (1 << NR_MOVE_TYPE))
4104 return -EINVAL;
4106 * We check this value several times in both in can_attach() and
4107 * attach(), so we need cgroup lock to prevent this value from being
4108 * inconsistent.
4110 cgroup_lock();
4111 memcg->move_charge_at_immigrate = val;
4112 cgroup_unlock();
4114 return 0;
4116 #else
4117 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
4118 struct cftype *cft, u64 val)
4120 return -ENOSYS;
4122 #endif
4125 /* For read statistics */
4126 enum {
4127 MCS_CACHE,
4128 MCS_RSS,
4129 MCS_FILE_MAPPED,
4130 MCS_PGPGIN,
4131 MCS_PGPGOUT,
4132 MCS_SWAP,
4133 MCS_PGFAULT,
4134 MCS_PGMAJFAULT,
4135 MCS_INACTIVE_ANON,
4136 MCS_ACTIVE_ANON,
4137 MCS_INACTIVE_FILE,
4138 MCS_ACTIVE_FILE,
4139 MCS_UNEVICTABLE,
4140 NR_MCS_STAT,
4143 struct mcs_total_stat {
4144 s64 stat[NR_MCS_STAT];
4147 struct {
4148 char *local_name;
4149 char *total_name;
4150 } memcg_stat_strings[NR_MCS_STAT] = {
4151 {"cache", "total_cache"},
4152 {"rss", "total_rss"},
4153 {"mapped_file", "total_mapped_file"},
4154 {"pgpgin", "total_pgpgin"},
4155 {"pgpgout", "total_pgpgout"},
4156 {"swap", "total_swap"},
4157 {"pgfault", "total_pgfault"},
4158 {"pgmajfault", "total_pgmajfault"},
4159 {"inactive_anon", "total_inactive_anon"},
4160 {"active_anon", "total_active_anon"},
4161 {"inactive_file", "total_inactive_file"},
4162 {"active_file", "total_active_file"},
4163 {"unevictable", "total_unevictable"}
4167 static void
4168 mem_cgroup_get_local_stat(struct mem_cgroup *memcg, struct mcs_total_stat *s)
4170 s64 val;
4172 /* per cpu stat */
4173 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_CACHE);
4174 s->stat[MCS_CACHE] += val * PAGE_SIZE;
4175 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_RSS);
4176 s->stat[MCS_RSS] += val * PAGE_SIZE;
4177 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_FILE_MAPPED);
4178 s->stat[MCS_FILE_MAPPED] += val * PAGE_SIZE;
4179 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGPGIN);
4180 s->stat[MCS_PGPGIN] += val;
4181 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGPGOUT);
4182 s->stat[MCS_PGPGOUT] += val;
4183 if (do_swap_account) {
4184 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_SWAPOUT);
4185 s->stat[MCS_SWAP] += val * PAGE_SIZE;
4187 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGFAULT);
4188 s->stat[MCS_PGFAULT] += val;
4189 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGMAJFAULT);
4190 s->stat[MCS_PGMAJFAULT] += val;
4192 /* per zone stat */
4193 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_INACTIVE_ANON));
4194 s->stat[MCS_INACTIVE_ANON] += val * PAGE_SIZE;
4195 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_ACTIVE_ANON));
4196 s->stat[MCS_ACTIVE_ANON] += val * PAGE_SIZE;
4197 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_INACTIVE_FILE));
4198 s->stat[MCS_INACTIVE_FILE] += val * PAGE_SIZE;
4199 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_ACTIVE_FILE));
4200 s->stat[MCS_ACTIVE_FILE] += val * PAGE_SIZE;
4201 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_UNEVICTABLE));
4202 s->stat[MCS_UNEVICTABLE] += val * PAGE_SIZE;
4205 static void
4206 mem_cgroup_get_total_stat(struct mem_cgroup *memcg, struct mcs_total_stat *s)
4208 struct mem_cgroup *iter;
4210 for_each_mem_cgroup_tree(iter, memcg)
4211 mem_cgroup_get_local_stat(iter, s);
4214 #ifdef CONFIG_NUMA
4215 static int mem_control_numa_stat_show(struct seq_file *m, void *arg)
4217 int nid;
4218 unsigned long total_nr, file_nr, anon_nr, unevictable_nr;
4219 unsigned long node_nr;
4220 struct cgroup *cont = m->private;
4221 struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
4223 total_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL);
4224 seq_printf(m, "total=%lu", total_nr);
4225 for_each_node_state(nid, N_HIGH_MEMORY) {
4226 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid, LRU_ALL);
4227 seq_printf(m, " N%d=%lu", nid, node_nr);
4229 seq_putc(m, '\n');
4231 file_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL_FILE);
4232 seq_printf(m, "file=%lu", file_nr);
4233 for_each_node_state(nid, N_HIGH_MEMORY) {
4234 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4235 LRU_ALL_FILE);
4236 seq_printf(m, " N%d=%lu", nid, node_nr);
4238 seq_putc(m, '\n');
4240 anon_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL_ANON);
4241 seq_printf(m, "anon=%lu", anon_nr);
4242 for_each_node_state(nid, N_HIGH_MEMORY) {
4243 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4244 LRU_ALL_ANON);
4245 seq_printf(m, " N%d=%lu", nid, node_nr);
4247 seq_putc(m, '\n');
4249 unevictable_nr = mem_cgroup_nr_lru_pages(mem_cont, BIT(LRU_UNEVICTABLE));
4250 seq_printf(m, "unevictable=%lu", unevictable_nr);
4251 for_each_node_state(nid, N_HIGH_MEMORY) {
4252 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4253 BIT(LRU_UNEVICTABLE));
4254 seq_printf(m, " N%d=%lu", nid, node_nr);
4256 seq_putc(m, '\n');
4257 return 0;
4259 #endif /* CONFIG_NUMA */
4261 static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft,
4262 struct cgroup_map_cb *cb)
4264 struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
4265 struct mcs_total_stat mystat;
4266 int i;
4268 memset(&mystat, 0, sizeof(mystat));
4269 mem_cgroup_get_local_stat(mem_cont, &mystat);
4272 for (i = 0; i < NR_MCS_STAT; i++) {
4273 if (i == MCS_SWAP && !do_swap_account)
4274 continue;
4275 cb->fill(cb, memcg_stat_strings[i].local_name, mystat.stat[i]);
4278 /* Hierarchical information */
4280 unsigned long long limit, memsw_limit;
4281 memcg_get_hierarchical_limit(mem_cont, &limit, &memsw_limit);
4282 cb->fill(cb, "hierarchical_memory_limit", limit);
4283 if (do_swap_account)
4284 cb->fill(cb, "hierarchical_memsw_limit", memsw_limit);
4287 memset(&mystat, 0, sizeof(mystat));
4288 mem_cgroup_get_total_stat(mem_cont, &mystat);
4289 for (i = 0; i < NR_MCS_STAT; i++) {
4290 if (i == MCS_SWAP && !do_swap_account)
4291 continue;
4292 cb->fill(cb, memcg_stat_strings[i].total_name, mystat.stat[i]);
4295 #ifdef CONFIG_DEBUG_VM
4296 cb->fill(cb, "inactive_ratio", calc_inactive_ratio(mem_cont, NULL));
4299 int nid, zid;
4300 struct mem_cgroup_per_zone *mz;
4301 unsigned long recent_rotated[2] = {0, 0};
4302 unsigned long recent_scanned[2] = {0, 0};
4304 for_each_online_node(nid)
4305 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
4306 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
4308 recent_rotated[0] +=
4309 mz->reclaim_stat.recent_rotated[0];
4310 recent_rotated[1] +=
4311 mz->reclaim_stat.recent_rotated[1];
4312 recent_scanned[0] +=
4313 mz->reclaim_stat.recent_scanned[0];
4314 recent_scanned[1] +=
4315 mz->reclaim_stat.recent_scanned[1];
4317 cb->fill(cb, "recent_rotated_anon", recent_rotated[0]);
4318 cb->fill(cb, "recent_rotated_file", recent_rotated[1]);
4319 cb->fill(cb, "recent_scanned_anon", recent_scanned[0]);
4320 cb->fill(cb, "recent_scanned_file", recent_scanned[1]);
4322 #endif
4324 return 0;
4327 static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
4329 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4331 return mem_cgroup_swappiness(memcg);
4334 static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
4335 u64 val)
4337 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4338 struct mem_cgroup *parent;
4340 if (val > 100)
4341 return -EINVAL;
4343 if (cgrp->parent == NULL)
4344 return -EINVAL;
4346 parent = mem_cgroup_from_cont(cgrp->parent);
4348 cgroup_lock();
4350 /* If under hierarchy, only empty-root can set this value */
4351 if ((parent->use_hierarchy) ||
4352 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
4353 cgroup_unlock();
4354 return -EINVAL;
4357 memcg->swappiness = val;
4359 cgroup_unlock();
4361 return 0;
4364 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4366 struct mem_cgroup_threshold_ary *t;
4367 u64 usage;
4368 int i;
4370 rcu_read_lock();
4371 if (!swap)
4372 t = rcu_dereference(memcg->thresholds.primary);
4373 else
4374 t = rcu_dereference(memcg->memsw_thresholds.primary);
4376 if (!t)
4377 goto unlock;
4379 usage = mem_cgroup_usage(memcg, swap);
4382 * current_threshold points to threshold just below usage.
4383 * If it's not true, a threshold was crossed after last
4384 * call of __mem_cgroup_threshold().
4386 i = t->current_threshold;
4389 * Iterate backward over array of thresholds starting from
4390 * current_threshold and check if a threshold is crossed.
4391 * If none of thresholds below usage is crossed, we read
4392 * only one element of the array here.
4394 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4395 eventfd_signal(t->entries[i].eventfd, 1);
4397 /* i = current_threshold + 1 */
4398 i++;
4401 * Iterate forward over array of thresholds starting from
4402 * current_threshold+1 and check if a threshold is crossed.
4403 * If none of thresholds above usage is crossed, we read
4404 * only one element of the array here.
4406 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4407 eventfd_signal(t->entries[i].eventfd, 1);
4409 /* Update current_threshold */
4410 t->current_threshold = i - 1;
4411 unlock:
4412 rcu_read_unlock();
4415 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4417 while (memcg) {
4418 __mem_cgroup_threshold(memcg, false);
4419 if (do_swap_account)
4420 __mem_cgroup_threshold(memcg, true);
4422 memcg = parent_mem_cgroup(memcg);
4426 static int compare_thresholds(const void *a, const void *b)
4428 const struct mem_cgroup_threshold *_a = a;
4429 const struct mem_cgroup_threshold *_b = b;
4431 return _a->threshold - _b->threshold;
4434 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
4436 struct mem_cgroup_eventfd_list *ev;
4438 list_for_each_entry(ev, &memcg->oom_notify, list)
4439 eventfd_signal(ev->eventfd, 1);
4440 return 0;
4443 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
4445 struct mem_cgroup *iter;
4447 for_each_mem_cgroup_tree(iter, memcg)
4448 mem_cgroup_oom_notify_cb(iter);
4451 static int mem_cgroup_usage_register_event(struct cgroup *cgrp,
4452 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
4454 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4455 struct mem_cgroup_thresholds *thresholds;
4456 struct mem_cgroup_threshold_ary *new;
4457 int type = MEMFILE_TYPE(cft->private);
4458 u64 threshold, usage;
4459 int i, size, ret;
4461 ret = res_counter_memparse_write_strategy(args, &threshold);
4462 if (ret)
4463 return ret;
4465 mutex_lock(&memcg->thresholds_lock);
4467 if (type == _MEM)
4468 thresholds = &memcg->thresholds;
4469 else if (type == _MEMSWAP)
4470 thresholds = &memcg->memsw_thresholds;
4471 else
4472 BUG();
4474 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
4476 /* Check if a threshold crossed before adding a new one */
4477 if (thresholds->primary)
4478 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4480 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
4482 /* Allocate memory for new array of thresholds */
4483 new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
4484 GFP_KERNEL);
4485 if (!new) {
4486 ret = -ENOMEM;
4487 goto unlock;
4489 new->size = size;
4491 /* Copy thresholds (if any) to new array */
4492 if (thresholds->primary) {
4493 memcpy(new->entries, thresholds->primary->entries, (size - 1) *
4494 sizeof(struct mem_cgroup_threshold));
4497 /* Add new threshold */
4498 new->entries[size - 1].eventfd = eventfd;
4499 new->entries[size - 1].threshold = threshold;
4501 /* Sort thresholds. Registering of new threshold isn't time-critical */
4502 sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
4503 compare_thresholds, NULL);
4505 /* Find current threshold */
4506 new->current_threshold = -1;
4507 for (i = 0; i < size; i++) {
4508 if (new->entries[i].threshold < usage) {
4510 * new->current_threshold will not be used until
4511 * rcu_assign_pointer(), so it's safe to increment
4512 * it here.
4514 ++new->current_threshold;
4518 /* Free old spare buffer and save old primary buffer as spare */
4519 kfree(thresholds->spare);
4520 thresholds->spare = thresholds->primary;
4522 rcu_assign_pointer(thresholds->primary, new);
4524 /* To be sure that nobody uses thresholds */
4525 synchronize_rcu();
4527 unlock:
4528 mutex_unlock(&memcg->thresholds_lock);
4530 return ret;
4533 static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,
4534 struct cftype *cft, struct eventfd_ctx *eventfd)
4536 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4537 struct mem_cgroup_thresholds *thresholds;
4538 struct mem_cgroup_threshold_ary *new;
4539 int type = MEMFILE_TYPE(cft->private);
4540 u64 usage;
4541 int i, j, size;
4543 mutex_lock(&memcg->thresholds_lock);
4544 if (type == _MEM)
4545 thresholds = &memcg->thresholds;
4546 else if (type == _MEMSWAP)
4547 thresholds = &memcg->memsw_thresholds;
4548 else
4549 BUG();
4552 * Something went wrong if we trying to unregister a threshold
4553 * if we don't have thresholds
4555 BUG_ON(!thresholds);
4557 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
4559 /* Check if a threshold crossed before removing */
4560 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4562 /* Calculate new number of threshold */
4563 size = 0;
4564 for (i = 0; i < thresholds->primary->size; i++) {
4565 if (thresholds->primary->entries[i].eventfd != eventfd)
4566 size++;
4569 new = thresholds->spare;
4571 /* Set thresholds array to NULL if we don't have thresholds */
4572 if (!size) {
4573 kfree(new);
4574 new = NULL;
4575 goto swap_buffers;
4578 new->size = size;
4580 /* Copy thresholds and find current threshold */
4581 new->current_threshold = -1;
4582 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4583 if (thresholds->primary->entries[i].eventfd == eventfd)
4584 continue;
4586 new->entries[j] = thresholds->primary->entries[i];
4587 if (new->entries[j].threshold < usage) {
4589 * new->current_threshold will not be used
4590 * until rcu_assign_pointer(), so it's safe to increment
4591 * it here.
4593 ++new->current_threshold;
4595 j++;
4598 swap_buffers:
4599 /* Swap primary and spare array */
4600 thresholds->spare = thresholds->primary;
4601 rcu_assign_pointer(thresholds->primary, new);
4603 /* To be sure that nobody uses thresholds */
4604 synchronize_rcu();
4606 mutex_unlock(&memcg->thresholds_lock);
4609 static int mem_cgroup_oom_register_event(struct cgroup *cgrp,
4610 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
4612 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4613 struct mem_cgroup_eventfd_list *event;
4614 int type = MEMFILE_TYPE(cft->private);
4616 BUG_ON(type != _OOM_TYPE);
4617 event = kmalloc(sizeof(*event), GFP_KERNEL);
4618 if (!event)
4619 return -ENOMEM;
4621 spin_lock(&memcg_oom_lock);
4623 event->eventfd = eventfd;
4624 list_add(&event->list, &memcg->oom_notify);
4626 /* already in OOM ? */
4627 if (atomic_read(&memcg->under_oom))
4628 eventfd_signal(eventfd, 1);
4629 spin_unlock(&memcg_oom_lock);
4631 return 0;
4634 static void mem_cgroup_oom_unregister_event(struct cgroup *cgrp,
4635 struct cftype *cft, struct eventfd_ctx *eventfd)
4637 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4638 struct mem_cgroup_eventfd_list *ev, *tmp;
4639 int type = MEMFILE_TYPE(cft->private);
4641 BUG_ON(type != _OOM_TYPE);
4643 spin_lock(&memcg_oom_lock);
4645 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
4646 if (ev->eventfd == eventfd) {
4647 list_del(&ev->list);
4648 kfree(ev);
4652 spin_unlock(&memcg_oom_lock);
4655 static int mem_cgroup_oom_control_read(struct cgroup *cgrp,
4656 struct cftype *cft, struct cgroup_map_cb *cb)
4658 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4660 cb->fill(cb, "oom_kill_disable", memcg->oom_kill_disable);
4662 if (atomic_read(&memcg->under_oom))
4663 cb->fill(cb, "under_oom", 1);
4664 else
4665 cb->fill(cb, "under_oom", 0);
4666 return 0;
4669 static int mem_cgroup_oom_control_write(struct cgroup *cgrp,
4670 struct cftype *cft, u64 val)
4672 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4673 struct mem_cgroup *parent;
4675 /* cannot set to root cgroup and only 0 and 1 are allowed */
4676 if (!cgrp->parent || !((val == 0) || (val == 1)))
4677 return -EINVAL;
4679 parent = mem_cgroup_from_cont(cgrp->parent);
4681 cgroup_lock();
4682 /* oom-kill-disable is a flag for subhierarchy. */
4683 if ((parent->use_hierarchy) ||
4684 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
4685 cgroup_unlock();
4686 return -EINVAL;
4688 memcg->oom_kill_disable = val;
4689 if (!val)
4690 memcg_oom_recover(memcg);
4691 cgroup_unlock();
4692 return 0;
4695 #ifdef CONFIG_NUMA
4696 static const struct file_operations mem_control_numa_stat_file_operations = {
4697 .read = seq_read,
4698 .llseek = seq_lseek,
4699 .release = single_release,
4702 static int mem_control_numa_stat_open(struct inode *unused, struct file *file)
4704 struct cgroup *cont = file->f_dentry->d_parent->d_fsdata;
4706 file->f_op = &mem_control_numa_stat_file_operations;
4707 return single_open(file, mem_control_numa_stat_show, cont);
4709 #endif /* CONFIG_NUMA */
4711 static int mem_cgroup_vmscan_stat_read(struct cgroup *cgrp,
4712 struct cftype *cft,
4713 struct cgroup_map_cb *cb)
4715 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4716 char string[64];
4717 int i;
4719 for (i = 0; i < NR_SCANSTATS; i++) {
4720 strcpy(string, scanstat_string[i]);
4721 strcat(string, SCANSTAT_WORD_LIMIT);
4722 cb->fill(cb, string, memcg->scanstat.stats[SCAN_BY_LIMIT][i]);
4725 for (i = 0; i < NR_SCANSTATS; i++) {
4726 strcpy(string, scanstat_string[i]);
4727 strcat(string, SCANSTAT_WORD_SYSTEM);
4728 cb->fill(cb, string, memcg->scanstat.stats[SCAN_BY_SYSTEM][i]);
4731 for (i = 0; i < NR_SCANSTATS; i++) {
4732 strcpy(string, scanstat_string[i]);
4733 strcat(string, SCANSTAT_WORD_LIMIT);
4734 strcat(string, SCANSTAT_WORD_HIERARCHY);
4735 cb->fill(cb,
4736 string, memcg->scanstat.rootstats[SCAN_BY_LIMIT][i]);
4738 for (i = 0; i < NR_SCANSTATS; i++) {
4739 strcpy(string, scanstat_string[i]);
4740 strcat(string, SCANSTAT_WORD_SYSTEM);
4741 strcat(string, SCANSTAT_WORD_HIERARCHY);
4742 cb->fill(cb,
4743 string, memcg->scanstat.rootstats[SCAN_BY_SYSTEM][i]);
4745 return 0;
4748 static int mem_cgroup_reset_vmscan_stat(struct cgroup *cgrp,
4749 unsigned int event)
4751 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4753 spin_lock(&memcg->scanstat.lock);
4754 memset(&memcg->scanstat.stats, 0, sizeof(memcg->scanstat.stats));
4755 memset(&memcg->scanstat.rootstats,
4756 0, sizeof(memcg->scanstat.rootstats));
4757 spin_unlock(&memcg->scanstat.lock);
4758 return 0;
4762 static struct cftype mem_cgroup_files[] = {
4764 .name = "usage_in_bytes",
4765 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
4766 .read_u64 = mem_cgroup_read,
4767 .register_event = mem_cgroup_usage_register_event,
4768 .unregister_event = mem_cgroup_usage_unregister_event,
4771 .name = "max_usage_in_bytes",
4772 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
4773 .trigger = mem_cgroup_reset,
4774 .read_u64 = mem_cgroup_read,
4777 .name = "limit_in_bytes",
4778 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
4779 .write_string = mem_cgroup_write,
4780 .read_u64 = mem_cgroup_read,
4783 .name = "soft_limit_in_bytes",
4784 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
4785 .write_string = mem_cgroup_write,
4786 .read_u64 = mem_cgroup_read,
4789 .name = "failcnt",
4790 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
4791 .trigger = mem_cgroup_reset,
4792 .read_u64 = mem_cgroup_read,
4795 .name = "stat",
4796 .read_map = mem_control_stat_show,
4799 .name = "force_empty",
4800 .trigger = mem_cgroup_force_empty_write,
4803 .name = "use_hierarchy",
4804 .write_u64 = mem_cgroup_hierarchy_write,
4805 .read_u64 = mem_cgroup_hierarchy_read,
4808 .name = "swappiness",
4809 .read_u64 = mem_cgroup_swappiness_read,
4810 .write_u64 = mem_cgroup_swappiness_write,
4813 .name = "move_charge_at_immigrate",
4814 .read_u64 = mem_cgroup_move_charge_read,
4815 .write_u64 = mem_cgroup_move_charge_write,
4818 .name = "oom_control",
4819 .read_map = mem_cgroup_oom_control_read,
4820 .write_u64 = mem_cgroup_oom_control_write,
4821 .register_event = mem_cgroup_oom_register_event,
4822 .unregister_event = mem_cgroup_oom_unregister_event,
4823 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
4825 #ifdef CONFIG_NUMA
4827 .name = "numa_stat",
4828 .open = mem_control_numa_stat_open,
4829 .mode = S_IRUGO,
4831 #endif
4833 .name = "vmscan_stat",
4834 .read_map = mem_cgroup_vmscan_stat_read,
4835 .trigger = mem_cgroup_reset_vmscan_stat,
4839 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4840 static struct cftype memsw_cgroup_files[] = {
4842 .name = "memsw.usage_in_bytes",
4843 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
4844 .read_u64 = mem_cgroup_read,
4845 .register_event = mem_cgroup_usage_register_event,
4846 .unregister_event = mem_cgroup_usage_unregister_event,
4849 .name = "memsw.max_usage_in_bytes",
4850 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
4851 .trigger = mem_cgroup_reset,
4852 .read_u64 = mem_cgroup_read,
4855 .name = "memsw.limit_in_bytes",
4856 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
4857 .write_string = mem_cgroup_write,
4858 .read_u64 = mem_cgroup_read,
4861 .name = "memsw.failcnt",
4862 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
4863 .trigger = mem_cgroup_reset,
4864 .read_u64 = mem_cgroup_read,
4868 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
4870 if (!do_swap_account)
4871 return 0;
4872 return cgroup_add_files(cont, ss, memsw_cgroup_files,
4873 ARRAY_SIZE(memsw_cgroup_files));
4875 #else
4876 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
4878 return 0;
4880 #endif
4882 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
4884 struct mem_cgroup_per_node *pn;
4885 struct mem_cgroup_per_zone *mz;
4886 enum lru_list l;
4887 int zone, tmp = node;
4889 * This routine is called against possible nodes.
4890 * But it's BUG to call kmalloc() against offline node.
4892 * TODO: this routine can waste much memory for nodes which will
4893 * never be onlined. It's better to use memory hotplug callback
4894 * function.
4896 if (!node_state(node, N_NORMAL_MEMORY))
4897 tmp = -1;
4898 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
4899 if (!pn)
4900 return 1;
4902 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4903 mz = &pn->zoneinfo[zone];
4904 for_each_lru(l)
4905 INIT_LIST_HEAD(&mz->lists[l]);
4906 mz->usage_in_excess = 0;
4907 mz->on_tree = false;
4908 mz->mem = memcg;
4910 memcg->info.nodeinfo[node] = pn;
4911 return 0;
4914 static void free_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
4916 kfree(memcg->info.nodeinfo[node]);
4919 static struct mem_cgroup *mem_cgroup_alloc(void)
4921 struct mem_cgroup *mem;
4922 int size = sizeof(struct mem_cgroup);
4924 /* Can be very big if MAX_NUMNODES is very big */
4925 if (size < PAGE_SIZE)
4926 mem = kzalloc(size, GFP_KERNEL);
4927 else
4928 mem = vzalloc(size);
4930 if (!mem)
4931 return NULL;
4933 mem->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
4934 if (!mem->stat)
4935 goto out_free;
4936 spin_lock_init(&mem->pcp_counter_lock);
4937 return mem;
4939 out_free:
4940 if (size < PAGE_SIZE)
4941 kfree(mem);
4942 else
4943 vfree(mem);
4944 return NULL;
4948 * At destroying mem_cgroup, references from swap_cgroup can remain.
4949 * (scanning all at force_empty is too costly...)
4951 * Instead of clearing all references at force_empty, we remember
4952 * the number of reference from swap_cgroup and free mem_cgroup when
4953 * it goes down to 0.
4955 * Removal of cgroup itself succeeds regardless of refs from swap.
4958 static void __mem_cgroup_free(struct mem_cgroup *memcg)
4960 int node;
4962 mem_cgroup_remove_from_trees(memcg);
4963 free_css_id(&mem_cgroup_subsys, &memcg->css);
4965 for_each_node_state(node, N_POSSIBLE)
4966 free_mem_cgroup_per_zone_info(memcg, node);
4968 free_percpu(memcg->stat);
4969 if (sizeof(struct mem_cgroup) < PAGE_SIZE)
4970 kfree(memcg);
4971 else
4972 vfree(memcg);
4975 static void mem_cgroup_get(struct mem_cgroup *memcg)
4977 atomic_inc(&memcg->refcnt);
4980 static void __mem_cgroup_put(struct mem_cgroup *memcg, int count)
4982 if (atomic_sub_and_test(count, &memcg->refcnt)) {
4983 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
4984 __mem_cgroup_free(memcg);
4985 if (parent)
4986 mem_cgroup_put(parent);
4990 static void mem_cgroup_put(struct mem_cgroup *memcg)
4992 __mem_cgroup_put(memcg, 1);
4996 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
4998 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg)
5000 if (!memcg->res.parent)
5001 return NULL;
5002 return mem_cgroup_from_res_counter(memcg->res.parent, res);
5005 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
5006 static void __init enable_swap_cgroup(void)
5008 if (!mem_cgroup_disabled() && really_do_swap_account)
5009 do_swap_account = 1;
5011 #else
5012 static void __init enable_swap_cgroup(void)
5015 #endif
5017 static int mem_cgroup_soft_limit_tree_init(void)
5019 struct mem_cgroup_tree_per_node *rtpn;
5020 struct mem_cgroup_tree_per_zone *rtpz;
5021 int tmp, node, zone;
5023 for_each_node_state(node, N_POSSIBLE) {
5024 tmp = node;
5025 if (!node_state(node, N_NORMAL_MEMORY))
5026 tmp = -1;
5027 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
5028 if (!rtpn)
5029 return 1;
5031 soft_limit_tree.rb_tree_per_node[node] = rtpn;
5033 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
5034 rtpz = &rtpn->rb_tree_per_zone[zone];
5035 rtpz->rb_root = RB_ROOT;
5036 spin_lock_init(&rtpz->lock);
5039 return 0;
5042 static struct cgroup_subsys_state * __ref
5043 mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
5045 struct mem_cgroup *memcg, *parent;
5046 long error = -ENOMEM;
5047 int node;
5049 memcg = mem_cgroup_alloc();
5050 if (!memcg)
5051 return ERR_PTR(error);
5053 for_each_node_state(node, N_POSSIBLE)
5054 if (alloc_mem_cgroup_per_zone_info(memcg, node))
5055 goto free_out;
5057 /* root ? */
5058 if (cont->parent == NULL) {
5059 int cpu;
5060 enable_swap_cgroup();
5061 parent = NULL;
5062 root_mem_cgroup = memcg;
5063 if (mem_cgroup_soft_limit_tree_init())
5064 goto free_out;
5065 for_each_possible_cpu(cpu) {
5066 struct memcg_stock_pcp *stock =
5067 &per_cpu(memcg_stock, cpu);
5068 INIT_WORK(&stock->work, drain_local_stock);
5070 hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
5071 } else {
5072 parent = mem_cgroup_from_cont(cont->parent);
5073 memcg->use_hierarchy = parent->use_hierarchy;
5074 memcg->oom_kill_disable = parent->oom_kill_disable;
5077 if (parent && parent->use_hierarchy) {
5078 res_counter_init(&memcg->res, &parent->res);
5079 res_counter_init(&memcg->memsw, &parent->memsw);
5081 * We increment refcnt of the parent to ensure that we can
5082 * safely access it on res_counter_charge/uncharge.
5083 * This refcnt will be decremented when freeing this
5084 * mem_cgroup(see mem_cgroup_put).
5086 mem_cgroup_get(parent);
5087 } else {
5088 res_counter_init(&memcg->res, NULL);
5089 res_counter_init(&memcg->memsw, NULL);
5091 memcg->last_scanned_child = 0;
5092 memcg->last_scanned_node = MAX_NUMNODES;
5093 INIT_LIST_HEAD(&memcg->oom_notify);
5095 if (parent)
5096 memcg->swappiness = mem_cgroup_swappiness(parent);
5097 atomic_set(&memcg->refcnt, 1);
5098 memcg->move_charge_at_immigrate = 0;
5099 mutex_init(&memcg->thresholds_lock);
5100 spin_lock_init(&memcg->scanstat.lock);
5101 return &memcg->css;
5102 free_out:
5103 __mem_cgroup_free(memcg);
5104 root_mem_cgroup = NULL;
5105 return ERR_PTR(error);
5108 static int mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
5109 struct cgroup *cont)
5111 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5113 return mem_cgroup_force_empty(memcg, false);
5116 static void mem_cgroup_destroy(struct cgroup_subsys *ss,
5117 struct cgroup *cont)
5119 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5121 mem_cgroup_put(memcg);
5124 static int mem_cgroup_populate(struct cgroup_subsys *ss,
5125 struct cgroup *cont)
5127 int ret;
5129 ret = cgroup_add_files(cont, ss, mem_cgroup_files,
5130 ARRAY_SIZE(mem_cgroup_files));
5132 if (!ret)
5133 ret = register_memsw_files(cont, ss);
5134 return ret;
5137 #ifdef CONFIG_MMU
5138 /* Handlers for move charge at task migration. */
5139 #define PRECHARGE_COUNT_AT_ONCE 256
5140 static int mem_cgroup_do_precharge(unsigned long count)
5142 int ret = 0;
5143 int batch_count = PRECHARGE_COUNT_AT_ONCE;
5144 struct mem_cgroup *memcg = mc.to;
5146 if (mem_cgroup_is_root(memcg)) {
5147 mc.precharge += count;
5148 /* we don't need css_get for root */
5149 return ret;
5151 /* try to charge at once */
5152 if (count > 1) {
5153 struct res_counter *dummy;
5155 * "memcg" cannot be under rmdir() because we've already checked
5156 * by cgroup_lock_live_cgroup() that it is not removed and we
5157 * are still under the same cgroup_mutex. So we can postpone
5158 * css_get().
5160 if (res_counter_charge(&memcg->res, PAGE_SIZE * count, &dummy))
5161 goto one_by_one;
5162 if (do_swap_account && res_counter_charge(&memcg->memsw,
5163 PAGE_SIZE * count, &dummy)) {
5164 res_counter_uncharge(&memcg->res, PAGE_SIZE * count);
5165 goto one_by_one;
5167 mc.precharge += count;
5168 return ret;
5170 one_by_one:
5171 /* fall back to one by one charge */
5172 while (count--) {
5173 if (signal_pending(current)) {
5174 ret = -EINTR;
5175 break;
5177 if (!batch_count--) {
5178 batch_count = PRECHARGE_COUNT_AT_ONCE;
5179 cond_resched();
5181 ret = __mem_cgroup_try_charge(NULL,
5182 GFP_KERNEL, 1, &memcg, false);
5183 if (ret || !memcg)
5184 /* mem_cgroup_clear_mc() will do uncharge later */
5185 return -ENOMEM;
5186 mc.precharge++;
5188 return ret;
5192 * is_target_pte_for_mc - check a pte whether it is valid for move charge
5193 * @vma: the vma the pte to be checked belongs
5194 * @addr: the address corresponding to the pte to be checked
5195 * @ptent: the pte to be checked
5196 * @target: the pointer the target page or swap ent will be stored(can be NULL)
5198 * Returns
5199 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
5200 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5201 * move charge. if @target is not NULL, the page is stored in target->page
5202 * with extra refcnt got(Callers should handle it).
5203 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5204 * target for charge migration. if @target is not NULL, the entry is stored
5205 * in target->ent.
5207 * Called with pte lock held.
5209 union mc_target {
5210 struct page *page;
5211 swp_entry_t ent;
5214 enum mc_target_type {
5215 MC_TARGET_NONE, /* not used */
5216 MC_TARGET_PAGE,
5217 MC_TARGET_SWAP,
5220 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5221 unsigned long addr, pte_t ptent)
5223 struct page *page = vm_normal_page(vma, addr, ptent);
5225 if (!page || !page_mapped(page))
5226 return NULL;
5227 if (PageAnon(page)) {
5228 /* we don't move shared anon */
5229 if (!move_anon() || page_mapcount(page) > 2)
5230 return NULL;
5231 } else if (!move_file())
5232 /* we ignore mapcount for file pages */
5233 return NULL;
5234 if (!get_page_unless_zero(page))
5235 return NULL;
5237 return page;
5240 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5241 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5243 int usage_count;
5244 struct page *page = NULL;
5245 swp_entry_t ent = pte_to_swp_entry(ptent);
5247 if (!move_anon() || non_swap_entry(ent))
5248 return NULL;
5249 usage_count = mem_cgroup_count_swap_user(ent, &page);
5250 if (usage_count > 1) { /* we don't move shared anon */
5251 if (page)
5252 put_page(page);
5253 return NULL;
5255 if (do_swap_account)
5256 entry->val = ent.val;
5258 return page;
5261 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5262 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5264 struct page *page = NULL;
5265 struct inode *inode;
5266 struct address_space *mapping;
5267 pgoff_t pgoff;
5269 if (!vma->vm_file) /* anonymous vma */
5270 return NULL;
5271 if (!move_file())
5272 return NULL;
5274 inode = vma->vm_file->f_path.dentry->d_inode;
5275 mapping = vma->vm_file->f_mapping;
5276 if (pte_none(ptent))
5277 pgoff = linear_page_index(vma, addr);
5278 else /* pte_file(ptent) is true */
5279 pgoff = pte_to_pgoff(ptent);
5281 /* page is moved even if it's not RSS of this task(page-faulted). */
5282 page = find_get_page(mapping, pgoff);
5284 #ifdef CONFIG_SWAP
5285 /* shmem/tmpfs may report page out on swap: account for that too. */
5286 if (radix_tree_exceptional_entry(page)) {
5287 swp_entry_t swap = radix_to_swp_entry(page);
5288 if (do_swap_account)
5289 *entry = swap;
5290 page = find_get_page(&swapper_space, swap.val);
5292 #endif
5293 return page;
5296 static int is_target_pte_for_mc(struct vm_area_struct *vma,
5297 unsigned long addr, pte_t ptent, union mc_target *target)
5299 struct page *page = NULL;
5300 struct page_cgroup *pc;
5301 int ret = 0;
5302 swp_entry_t ent = { .val = 0 };
5304 if (pte_present(ptent))
5305 page = mc_handle_present_pte(vma, addr, ptent);
5306 else if (is_swap_pte(ptent))
5307 page = mc_handle_swap_pte(vma, addr, ptent, &ent);
5308 else if (pte_none(ptent) || pte_file(ptent))
5309 page = mc_handle_file_pte(vma, addr, ptent, &ent);
5311 if (!page && !ent.val)
5312 return 0;
5313 if (page) {
5314 pc = lookup_page_cgroup(page);
5316 * Do only loose check w/o page_cgroup lock.
5317 * mem_cgroup_move_account() checks the pc is valid or not under
5318 * the lock.
5320 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
5321 ret = MC_TARGET_PAGE;
5322 if (target)
5323 target->page = page;
5325 if (!ret || !target)
5326 put_page(page);
5328 /* There is a swap entry and a page doesn't exist or isn't charged */
5329 if (ent.val && !ret &&
5330 css_id(&mc.from->css) == lookup_swap_cgroup(ent)) {
5331 ret = MC_TARGET_SWAP;
5332 if (target)
5333 target->ent = ent;
5335 return ret;
5338 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
5339 unsigned long addr, unsigned long end,
5340 struct mm_walk *walk)
5342 struct vm_area_struct *vma = walk->private;
5343 pte_t *pte;
5344 spinlock_t *ptl;
5346 split_huge_page_pmd(walk->mm, pmd);
5348 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5349 for (; addr != end; pte++, addr += PAGE_SIZE)
5350 if (is_target_pte_for_mc(vma, addr, *pte, NULL))
5351 mc.precharge++; /* increment precharge temporarily */
5352 pte_unmap_unlock(pte - 1, ptl);
5353 cond_resched();
5355 return 0;
5358 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
5360 unsigned long precharge;
5361 struct vm_area_struct *vma;
5363 down_read(&mm->mmap_sem);
5364 for (vma = mm->mmap; vma; vma = vma->vm_next) {
5365 struct mm_walk mem_cgroup_count_precharge_walk = {
5366 .pmd_entry = mem_cgroup_count_precharge_pte_range,
5367 .mm = mm,
5368 .private = vma,
5370 if (is_vm_hugetlb_page(vma))
5371 continue;
5372 walk_page_range(vma->vm_start, vma->vm_end,
5373 &mem_cgroup_count_precharge_walk);
5375 up_read(&mm->mmap_sem);
5377 precharge = mc.precharge;
5378 mc.precharge = 0;
5380 return precharge;
5383 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
5385 unsigned long precharge = mem_cgroup_count_precharge(mm);
5387 VM_BUG_ON(mc.moving_task);
5388 mc.moving_task = current;
5389 return mem_cgroup_do_precharge(precharge);
5392 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5393 static void __mem_cgroup_clear_mc(void)
5395 struct mem_cgroup *from = mc.from;
5396 struct mem_cgroup *to = mc.to;
5398 /* we must uncharge all the leftover precharges from mc.to */
5399 if (mc.precharge) {
5400 __mem_cgroup_cancel_charge(mc.to, mc.precharge);
5401 mc.precharge = 0;
5404 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5405 * we must uncharge here.
5407 if (mc.moved_charge) {
5408 __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
5409 mc.moved_charge = 0;
5411 /* we must fixup refcnts and charges */
5412 if (mc.moved_swap) {
5413 /* uncharge swap account from the old cgroup */
5414 if (!mem_cgroup_is_root(mc.from))
5415 res_counter_uncharge(&mc.from->memsw,
5416 PAGE_SIZE * mc.moved_swap);
5417 __mem_cgroup_put(mc.from, mc.moved_swap);
5419 if (!mem_cgroup_is_root(mc.to)) {
5421 * we charged both to->res and to->memsw, so we should
5422 * uncharge to->res.
5424 res_counter_uncharge(&mc.to->res,
5425 PAGE_SIZE * mc.moved_swap);
5427 /* we've already done mem_cgroup_get(mc.to) */
5428 mc.moved_swap = 0;
5430 memcg_oom_recover(from);
5431 memcg_oom_recover(to);
5432 wake_up_all(&mc.waitq);
5435 static void mem_cgroup_clear_mc(void)
5437 struct mem_cgroup *from = mc.from;
5440 * we must clear moving_task before waking up waiters at the end of
5441 * task migration.
5443 mc.moving_task = NULL;
5444 __mem_cgroup_clear_mc();
5445 spin_lock(&mc.lock);
5446 mc.from = NULL;
5447 mc.to = NULL;
5448 spin_unlock(&mc.lock);
5449 mem_cgroup_end_move(from);
5452 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
5453 struct cgroup *cgroup,
5454 struct task_struct *p)
5456 int ret = 0;
5457 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgroup);
5459 if (memcg->move_charge_at_immigrate) {
5460 struct mm_struct *mm;
5461 struct mem_cgroup *from = mem_cgroup_from_task(p);
5463 VM_BUG_ON(from == memcg);
5465 mm = get_task_mm(p);
5466 if (!mm)
5467 return 0;
5468 /* We move charges only when we move a owner of the mm */
5469 if (mm->owner == p) {
5470 VM_BUG_ON(mc.from);
5471 VM_BUG_ON(mc.to);
5472 VM_BUG_ON(mc.precharge);
5473 VM_BUG_ON(mc.moved_charge);
5474 VM_BUG_ON(mc.moved_swap);
5475 mem_cgroup_start_move(from);
5476 spin_lock(&mc.lock);
5477 mc.from = from;
5478 mc.to = memcg;
5479 spin_unlock(&mc.lock);
5480 /* We set mc.moving_task later */
5482 ret = mem_cgroup_precharge_mc(mm);
5483 if (ret)
5484 mem_cgroup_clear_mc();
5486 mmput(mm);
5488 return ret;
5491 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
5492 struct cgroup *cgroup,
5493 struct task_struct *p)
5495 mem_cgroup_clear_mc();
5498 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
5499 unsigned long addr, unsigned long end,
5500 struct mm_walk *walk)
5502 int ret = 0;
5503 struct vm_area_struct *vma = walk->private;
5504 pte_t *pte;
5505 spinlock_t *ptl;
5507 split_huge_page_pmd(walk->mm, pmd);
5508 retry:
5509 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5510 for (; addr != end; addr += PAGE_SIZE) {
5511 pte_t ptent = *(pte++);
5512 union mc_target target;
5513 int type;
5514 struct page *page;
5515 struct page_cgroup *pc;
5516 swp_entry_t ent;
5518 if (!mc.precharge)
5519 break;
5521 type = is_target_pte_for_mc(vma, addr, ptent, &target);
5522 switch (type) {
5523 case MC_TARGET_PAGE:
5524 page = target.page;
5525 if (isolate_lru_page(page))
5526 goto put;
5527 pc = lookup_page_cgroup(page);
5528 if (!mem_cgroup_move_account(page, 1, pc,
5529 mc.from, mc.to, false)) {
5530 mc.precharge--;
5531 /* we uncharge from mc.from later. */
5532 mc.moved_charge++;
5534 putback_lru_page(page);
5535 put: /* is_target_pte_for_mc() gets the page */
5536 put_page(page);
5537 break;
5538 case MC_TARGET_SWAP:
5539 ent = target.ent;
5540 if (!mem_cgroup_move_swap_account(ent,
5541 mc.from, mc.to, false)) {
5542 mc.precharge--;
5543 /* we fixup refcnts and charges later. */
5544 mc.moved_swap++;
5546 break;
5547 default:
5548 break;
5551 pte_unmap_unlock(pte - 1, ptl);
5552 cond_resched();
5554 if (addr != end) {
5556 * We have consumed all precharges we got in can_attach().
5557 * We try charge one by one, but don't do any additional
5558 * charges to mc.to if we have failed in charge once in attach()
5559 * phase.
5561 ret = mem_cgroup_do_precharge(1);
5562 if (!ret)
5563 goto retry;
5566 return ret;
5569 static void mem_cgroup_move_charge(struct mm_struct *mm)
5571 struct vm_area_struct *vma;
5573 lru_add_drain_all();
5574 retry:
5575 if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
5577 * Someone who are holding the mmap_sem might be waiting in
5578 * waitq. So we cancel all extra charges, wake up all waiters,
5579 * and retry. Because we cancel precharges, we might not be able
5580 * to move enough charges, but moving charge is a best-effort
5581 * feature anyway, so it wouldn't be a big problem.
5583 __mem_cgroup_clear_mc();
5584 cond_resched();
5585 goto retry;
5587 for (vma = mm->mmap; vma; vma = vma->vm_next) {
5588 int ret;
5589 struct mm_walk mem_cgroup_move_charge_walk = {
5590 .pmd_entry = mem_cgroup_move_charge_pte_range,
5591 .mm = mm,
5592 .private = vma,
5594 if (is_vm_hugetlb_page(vma))
5595 continue;
5596 ret = walk_page_range(vma->vm_start, vma->vm_end,
5597 &mem_cgroup_move_charge_walk);
5598 if (ret)
5600 * means we have consumed all precharges and failed in
5601 * doing additional charge. Just abandon here.
5603 break;
5605 up_read(&mm->mmap_sem);
5608 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
5609 struct cgroup *cont,
5610 struct cgroup *old_cont,
5611 struct task_struct *p)
5613 struct mm_struct *mm = get_task_mm(p);
5615 if (mm) {
5616 if (mc.to)
5617 mem_cgroup_move_charge(mm);
5618 put_swap_token(mm);
5619 mmput(mm);
5621 if (mc.to)
5622 mem_cgroup_clear_mc();
5624 #else /* !CONFIG_MMU */
5625 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
5626 struct cgroup *cgroup,
5627 struct task_struct *p)
5629 return 0;
5631 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
5632 struct cgroup *cgroup,
5633 struct task_struct *p)
5636 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
5637 struct cgroup *cont,
5638 struct cgroup *old_cont,
5639 struct task_struct *p)
5642 #endif
5644 struct cgroup_subsys mem_cgroup_subsys = {
5645 .name = "memory",
5646 .subsys_id = mem_cgroup_subsys_id,
5647 .create = mem_cgroup_create,
5648 .pre_destroy = mem_cgroup_pre_destroy,
5649 .destroy = mem_cgroup_destroy,
5650 .populate = mem_cgroup_populate,
5651 .can_attach = mem_cgroup_can_attach,
5652 .cancel_attach = mem_cgroup_cancel_attach,
5653 .attach = mem_cgroup_move_task,
5654 .early_init = 0,
5655 .use_id = 1,
5658 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
5659 static int __init enable_swap_account(char *s)
5661 /* consider enabled if no parameter or 1 is given */
5662 if (!strcmp(s, "1"))
5663 really_do_swap_account = 1;
5664 else if (!strcmp(s, "0"))
5665 really_do_swap_account = 0;
5666 return 1;
5668 __setup("swapaccount=", enable_swap_account);
5670 #endif