Add linux-next specific files for 20110822
[linux-2.6/next.git] / mm / memcontrol.c
blobc6faa329b88b07a7d8b9256ed813eb4928c99931
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 *mem);
206 static void mem_cgroup_oom_notify(struct mem_cgroup *mem);
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 *mem);
412 static void mem_cgroup_put(struct mem_cgroup *mem);
413 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem);
414 static void drain_all_stock_async(struct mem_cgroup *mem);
416 static struct mem_cgroup_per_zone *
417 mem_cgroup_zoneinfo(struct mem_cgroup *mem, int nid, int zid)
419 return &mem->info.nodeinfo[nid]->zoneinfo[zid];
422 struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *mem)
424 return &mem->css;
427 static struct mem_cgroup_per_zone *
428 page_cgroup_zoneinfo(struct mem_cgroup *mem, struct page *page)
430 int nid = page_to_nid(page);
431 int zid = page_zonenum(page);
433 return mem_cgroup_zoneinfo(mem, 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 *mem,
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 *mem,
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 *mem,
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(mem, mz, mctz);
503 spin_unlock(&mctz->lock);
507 static void mem_cgroup_update_tree(struct mem_cgroup *mem, 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 (; mem; mem = parent_mem_cgroup(mem)) {
521 mz = mem_cgroup_zoneinfo(mem, nid, zid);
522 excess = res_counter_soft_limit_excess(&mem->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(mem, 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(mem, mz, mctz, excess);
537 spin_unlock(&mctz->lock);
542 static void mem_cgroup_remove_from_trees(struct mem_cgroup *mem)
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(mem, node, zone);
551 mctz = soft_limit_tree_node_zone(node, zone);
552 mem_cgroup_remove_exceeded(mem, 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 *mem,
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(mem->stat->count[idx], cpu);
622 #ifdef CONFIG_HOTPLUG_CPU
623 spin_lock(&mem->pcp_counter_lock);
624 val += mem->nocpu_base.count[idx];
625 spin_unlock(&mem->pcp_counter_lock);
626 #endif
627 put_online_cpus();
628 return val;
631 static void mem_cgroup_swap_statistics(struct mem_cgroup *mem,
632 bool charge)
634 int val = (charge) ? 1 : -1;
635 this_cpu_add(mem->stat->count[MEM_CGROUP_STAT_SWAPOUT], val);
638 void mem_cgroup_pgfault(struct mem_cgroup *mem, int val)
640 this_cpu_add(mem->stat->events[MEM_CGROUP_EVENTS_PGFAULT], val);
643 void mem_cgroup_pgmajfault(struct mem_cgroup *mem, int val)
645 this_cpu_add(mem->stat->events[MEM_CGROUP_EVENTS_PGMAJFAULT], val);
648 static unsigned long mem_cgroup_read_events(struct mem_cgroup *mem,
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(mem->stat->events[idx], cpu);
656 #ifdef CONFIG_HOTPLUG_CPU
657 spin_lock(&mem->pcp_counter_lock);
658 val += mem->nocpu_base.events[idx];
659 spin_unlock(&mem->pcp_counter_lock);
660 #endif
661 return val;
664 static void mem_cgroup_charge_statistics(struct mem_cgroup *mem,
665 bool file, int nr_pages)
667 preempt_disable();
669 if (file)
670 __this_cpu_add(mem->stat->count[MEM_CGROUP_STAT_CACHE], nr_pages);
671 else
672 __this_cpu_add(mem->stat->count[MEM_CGROUP_STAT_RSS], nr_pages);
674 /* pagein of a big page is an event. So, ignore page size */
675 if (nr_pages > 0)
676 __this_cpu_inc(mem->stat->events[MEM_CGROUP_EVENTS_PGPGIN]);
677 else {
678 __this_cpu_inc(mem->stat->events[MEM_CGROUP_EVENTS_PGPGOUT]);
679 nr_pages = -nr_pages; /* for event */
682 __this_cpu_add(mem->stat->events[MEM_CGROUP_EVENTS_COUNT], nr_pages);
684 preempt_enable();
687 unsigned long
688 mem_cgroup_zone_nr_lru_pages(struct mem_cgroup *mem, int nid, int zid,
689 unsigned int lru_mask)
691 struct mem_cgroup_per_zone *mz;
692 enum lru_list l;
693 unsigned long ret = 0;
695 mz = mem_cgroup_zoneinfo(mem, nid, zid);
697 for_each_lru(l) {
698 if (BIT(l) & lru_mask)
699 ret += MEM_CGROUP_ZSTAT(mz, l);
701 return ret;
704 static unsigned long
705 mem_cgroup_node_nr_lru_pages(struct mem_cgroup *mem,
706 int nid, unsigned int lru_mask)
708 u64 total = 0;
709 int zid;
711 for (zid = 0; zid < MAX_NR_ZONES; zid++)
712 total += mem_cgroup_zone_nr_lru_pages(mem, nid, zid, lru_mask);
714 return total;
717 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *mem,
718 unsigned int lru_mask)
720 int nid;
721 u64 total = 0;
723 for_each_node_state(nid, N_HIGH_MEMORY)
724 total += mem_cgroup_node_nr_lru_pages(mem, nid, lru_mask);
725 return total;
728 static bool __memcg_event_check(struct mem_cgroup *mem, int target)
730 unsigned long val, next;
732 val = this_cpu_read(mem->stat->events[MEM_CGROUP_EVENTS_COUNT]);
733 next = this_cpu_read(mem->stat->targets[target]);
734 /* from time_after() in jiffies.h */
735 return ((long)next - (long)val < 0);
738 static void __mem_cgroup_target_update(struct mem_cgroup *mem, int target)
740 unsigned long val, next;
742 val = this_cpu_read(mem->stat->events[MEM_CGROUP_EVENTS_COUNT]);
744 switch (target) {
745 case MEM_CGROUP_TARGET_THRESH:
746 next = val + THRESHOLDS_EVENTS_TARGET;
747 break;
748 case MEM_CGROUP_TARGET_SOFTLIMIT:
749 next = val + SOFTLIMIT_EVENTS_TARGET;
750 break;
751 case MEM_CGROUP_TARGET_NUMAINFO:
752 next = val + NUMAINFO_EVENTS_TARGET;
753 break;
754 default:
755 return;
758 this_cpu_write(mem->stat->targets[target], next);
762 * Check events in order.
765 static void memcg_check_events(struct mem_cgroup *mem, struct page *page)
767 /* threshold event is triggered in finer grain than soft limit */
768 if (unlikely(__memcg_event_check(mem, MEM_CGROUP_TARGET_THRESH))) {
769 mem_cgroup_threshold(mem);
770 __mem_cgroup_target_update(mem, MEM_CGROUP_TARGET_THRESH);
771 if (unlikely(__memcg_event_check(mem,
772 MEM_CGROUP_TARGET_SOFTLIMIT))) {
773 mem_cgroup_update_tree(mem, page);
774 __mem_cgroup_target_update(mem,
775 MEM_CGROUP_TARGET_SOFTLIMIT);
777 #if MAX_NUMNODES > 1
778 if (unlikely(__memcg_event_check(mem,
779 MEM_CGROUP_TARGET_NUMAINFO))) {
780 atomic_inc(&mem->numainfo_events);
781 __mem_cgroup_target_update(mem,
782 MEM_CGROUP_TARGET_NUMAINFO);
784 #endif
788 static struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
790 return container_of(cgroup_subsys_state(cont,
791 mem_cgroup_subsys_id), struct mem_cgroup,
792 css);
795 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
798 * mm_update_next_owner() may clear mm->owner to NULL
799 * if it races with swapoff, page migration, etc.
800 * So this can be called with p == NULL.
802 if (unlikely(!p))
803 return NULL;
805 return container_of(task_subsys_state(p, mem_cgroup_subsys_id),
806 struct mem_cgroup, css);
809 struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
811 struct mem_cgroup *mem = NULL;
813 if (!mm)
814 return NULL;
816 * Because we have no locks, mm->owner's may be being moved to other
817 * cgroup. We use css_tryget() here even if this looks
818 * pessimistic (rather than adding locks here).
820 rcu_read_lock();
821 do {
822 mem = mem_cgroup_from_task(rcu_dereference(mm->owner));
823 if (unlikely(!mem))
824 break;
825 } while (!css_tryget(&mem->css));
826 rcu_read_unlock();
827 return mem;
830 /* The caller has to guarantee "mem" exists before calling this */
831 static struct mem_cgroup *mem_cgroup_start_loop(struct mem_cgroup *mem)
833 struct cgroup_subsys_state *css;
834 int found;
836 if (!mem) /* ROOT cgroup has the smallest ID */
837 return root_mem_cgroup; /*css_put/get against root is ignored*/
838 if (!mem->use_hierarchy) {
839 if (css_tryget(&mem->css))
840 return mem;
841 return NULL;
843 rcu_read_lock();
845 * searching a memory cgroup which has the smallest ID under given
846 * ROOT cgroup. (ID >= 1)
848 css = css_get_next(&mem_cgroup_subsys, 1, &mem->css, &found);
849 if (css && css_tryget(css))
850 mem = container_of(css, struct mem_cgroup, css);
851 else
852 mem = NULL;
853 rcu_read_unlock();
854 return mem;
857 static struct mem_cgroup *mem_cgroup_get_next(struct mem_cgroup *iter,
858 struct mem_cgroup *root,
859 bool cond)
861 int nextid = css_id(&iter->css) + 1;
862 int found;
863 int hierarchy_used;
864 struct cgroup_subsys_state *css;
866 hierarchy_used = iter->use_hierarchy;
868 css_put(&iter->css);
869 /* If no ROOT, walk all, ignore hierarchy */
870 if (!cond || (root && !hierarchy_used))
871 return NULL;
873 if (!root)
874 root = root_mem_cgroup;
876 do {
877 iter = NULL;
878 rcu_read_lock();
880 css = css_get_next(&mem_cgroup_subsys, nextid,
881 &root->css, &found);
882 if (css && css_tryget(css))
883 iter = container_of(css, struct mem_cgroup, css);
884 rcu_read_unlock();
885 /* If css is NULL, no more cgroups will be found */
886 nextid = found + 1;
887 } while (css && !iter);
889 return iter;
892 * for_eacn_mem_cgroup_tree() for visiting all cgroup under tree. Please
893 * be careful that "break" loop is not allowed. We have reference count.
894 * Instead of that modify "cond" to be false and "continue" to exit the loop.
896 #define for_each_mem_cgroup_tree_cond(iter, root, cond) \
897 for (iter = mem_cgroup_start_loop(root);\
898 iter != NULL;\
899 iter = mem_cgroup_get_next(iter, root, cond))
901 #define for_each_mem_cgroup_tree(iter, root) \
902 for_each_mem_cgroup_tree_cond(iter, root, true)
904 #define for_each_mem_cgroup_all(iter) \
905 for_each_mem_cgroup_tree_cond(iter, NULL, true)
908 static inline bool mem_cgroup_is_root(struct mem_cgroup *mem)
910 return (mem == root_mem_cgroup);
913 void mem_cgroup_count_vm_event(struct mm_struct *mm, enum vm_event_item idx)
915 struct mem_cgroup *mem;
917 if (!mm)
918 return;
920 rcu_read_lock();
921 mem = mem_cgroup_from_task(rcu_dereference(mm->owner));
922 if (unlikely(!mem))
923 goto out;
925 switch (idx) {
926 case PGMAJFAULT:
927 mem_cgroup_pgmajfault(mem, 1);
928 break;
929 case PGFAULT:
930 mem_cgroup_pgfault(mem, 1);
931 break;
932 default:
933 BUG();
935 out:
936 rcu_read_unlock();
938 EXPORT_SYMBOL(mem_cgroup_count_vm_event);
941 * Following LRU functions are allowed to be used without PCG_LOCK.
942 * Operations are called by routine of global LRU independently from memcg.
943 * What we have to take care of here is validness of pc->mem_cgroup.
945 * Changes to pc->mem_cgroup happens when
946 * 1. charge
947 * 2. moving account
948 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
949 * It is added to LRU before charge.
950 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
951 * When moving account, the page is not on LRU. It's isolated.
954 void mem_cgroup_del_lru_list(struct page *page, enum lru_list lru)
956 struct page_cgroup *pc;
957 struct mem_cgroup_per_zone *mz;
959 if (mem_cgroup_disabled())
960 return;
961 pc = lookup_page_cgroup(page);
962 /* can happen while we handle swapcache. */
963 if (!TestClearPageCgroupAcctLRU(pc))
964 return;
965 VM_BUG_ON(!pc->mem_cgroup);
967 * We don't check PCG_USED bit. It's cleared when the "page" is finally
968 * removed from global LRU.
970 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
971 /* huge page split is done under lru_lock. so, we have no races. */
972 MEM_CGROUP_ZSTAT(mz, lru) -= 1 << compound_order(page);
973 if (mem_cgroup_is_root(pc->mem_cgroup))
974 return;
975 VM_BUG_ON(list_empty(&pc->lru));
976 list_del_init(&pc->lru);
979 void mem_cgroup_del_lru(struct page *page)
981 mem_cgroup_del_lru_list(page, page_lru(page));
985 * Writeback is about to end against a page which has been marked for immediate
986 * reclaim. If it still appears to be reclaimable, move it to the tail of the
987 * inactive list.
989 void mem_cgroup_rotate_reclaimable_page(struct page *page)
991 struct mem_cgroup_per_zone *mz;
992 struct page_cgroup *pc;
993 enum lru_list lru = page_lru(page);
995 if (mem_cgroup_disabled())
996 return;
998 pc = lookup_page_cgroup(page);
999 /* unused or root page is not rotated. */
1000 if (!PageCgroupUsed(pc))
1001 return;
1002 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1003 smp_rmb();
1004 if (mem_cgroup_is_root(pc->mem_cgroup))
1005 return;
1006 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
1007 list_move_tail(&pc->lru, &mz->lists[lru]);
1010 void mem_cgroup_rotate_lru_list(struct page *page, enum lru_list lru)
1012 struct mem_cgroup_per_zone *mz;
1013 struct page_cgroup *pc;
1015 if (mem_cgroup_disabled())
1016 return;
1018 pc = lookup_page_cgroup(page);
1019 /* unused or root page is not rotated. */
1020 if (!PageCgroupUsed(pc))
1021 return;
1022 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1023 smp_rmb();
1024 if (mem_cgroup_is_root(pc->mem_cgroup))
1025 return;
1026 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
1027 list_move(&pc->lru, &mz->lists[lru]);
1030 void mem_cgroup_add_lru_list(struct page *page, enum lru_list lru)
1032 struct page_cgroup *pc;
1033 struct mem_cgroup_per_zone *mz;
1035 if (mem_cgroup_disabled())
1036 return;
1037 pc = lookup_page_cgroup(page);
1038 VM_BUG_ON(PageCgroupAcctLRU(pc));
1039 if (!PageCgroupUsed(pc))
1040 return;
1041 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1042 smp_rmb();
1043 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
1044 /* huge page split is done under lru_lock. so, we have no races. */
1045 MEM_CGROUP_ZSTAT(mz, lru) += 1 << compound_order(page);
1046 SetPageCgroupAcctLRU(pc);
1047 if (mem_cgroup_is_root(pc->mem_cgroup))
1048 return;
1049 list_add(&pc->lru, &mz->lists[lru]);
1053 * At handling SwapCache and other FUSE stuff, pc->mem_cgroup may be changed
1054 * while it's linked to lru because the page may be reused after it's fully
1055 * uncharged. To handle that, unlink page_cgroup from LRU when charge it again.
1056 * It's done under lock_page and expected that zone->lru_lock isnever held.
1058 static void mem_cgroup_lru_del_before_commit(struct page *page)
1060 unsigned long flags;
1061 struct zone *zone = page_zone(page);
1062 struct page_cgroup *pc = lookup_page_cgroup(page);
1065 * Doing this check without taking ->lru_lock seems wrong but this
1066 * is safe. Because if page_cgroup's USED bit is unset, the page
1067 * will not be added to any memcg's LRU. If page_cgroup's USED bit is
1068 * set, the commit after this will fail, anyway.
1069 * This all charge/uncharge is done under some mutual execustion.
1070 * So, we don't need to taking care of changes in USED bit.
1072 if (likely(!PageLRU(page)))
1073 return;
1075 spin_lock_irqsave(&zone->lru_lock, flags);
1077 * Forget old LRU when this page_cgroup is *not* used. This Used bit
1078 * is guarded by lock_page() because the page is SwapCache.
1080 if (!PageCgroupUsed(pc))
1081 mem_cgroup_del_lru_list(page, page_lru(page));
1082 spin_unlock_irqrestore(&zone->lru_lock, flags);
1085 static void mem_cgroup_lru_add_after_commit(struct page *page)
1087 unsigned long flags;
1088 struct zone *zone = page_zone(page);
1089 struct page_cgroup *pc = lookup_page_cgroup(page);
1091 /* taking care of that the page is added to LRU while we commit it */
1092 if (likely(!PageLRU(page)))
1093 return;
1094 spin_lock_irqsave(&zone->lru_lock, flags);
1095 /* link when the page is linked to LRU but page_cgroup isn't */
1096 if (PageLRU(page) && !PageCgroupAcctLRU(pc))
1097 mem_cgroup_add_lru_list(page, page_lru(page));
1098 spin_unlock_irqrestore(&zone->lru_lock, flags);
1102 void mem_cgroup_move_lists(struct page *page,
1103 enum lru_list from, enum lru_list to)
1105 if (mem_cgroup_disabled())
1106 return;
1107 mem_cgroup_del_lru_list(page, from);
1108 mem_cgroup_add_lru_list(page, to);
1112 * Checks whether given mem is same or in the root_mem's
1113 * hierarchy subtree
1115 static bool mem_cgroup_same_or_subtree(const struct mem_cgroup *root_mem,
1116 struct mem_cgroup *mem)
1118 if (root_mem != mem) {
1119 return (root_mem->use_hierarchy &&
1120 css_is_ancestor(&mem->css, &root_mem->css));
1123 return true;
1126 int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *mem)
1128 int ret;
1129 struct mem_cgroup *curr = NULL;
1130 struct task_struct *p;
1132 p = find_lock_task_mm(task);
1133 if (!p)
1134 return 0;
1135 curr = try_get_mem_cgroup_from_mm(p->mm);
1136 task_unlock(p);
1137 if (!curr)
1138 return 0;
1140 * We should check use_hierarchy of "mem" not "curr". Because checking
1141 * use_hierarchy of "curr" here make this function true if hierarchy is
1142 * enabled in "curr" and "curr" is a child of "mem" in *cgroup*
1143 * hierarchy(even if use_hierarchy is disabled in "mem").
1145 ret = mem_cgroup_same_or_subtree(mem, curr);
1146 css_put(&curr->css);
1147 return ret;
1150 static int calc_inactive_ratio(struct mem_cgroup *memcg, unsigned long *present_pages)
1152 unsigned long active;
1153 unsigned long inactive;
1154 unsigned long gb;
1155 unsigned long inactive_ratio;
1157 inactive = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_INACTIVE_ANON));
1158 active = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_ACTIVE_ANON));
1160 gb = (inactive + active) >> (30 - PAGE_SHIFT);
1161 if (gb)
1162 inactive_ratio = int_sqrt(10 * gb);
1163 else
1164 inactive_ratio = 1;
1166 if (present_pages) {
1167 present_pages[0] = inactive;
1168 present_pages[1] = active;
1171 return inactive_ratio;
1174 int mem_cgroup_inactive_anon_is_low(struct mem_cgroup *memcg)
1176 unsigned long active;
1177 unsigned long inactive;
1178 unsigned long present_pages[2];
1179 unsigned long inactive_ratio;
1181 inactive_ratio = calc_inactive_ratio(memcg, present_pages);
1183 inactive = present_pages[0];
1184 active = present_pages[1];
1186 if (inactive * inactive_ratio < active)
1187 return 1;
1189 return 0;
1192 int mem_cgroup_inactive_file_is_low(struct mem_cgroup *memcg)
1194 unsigned long active;
1195 unsigned long inactive;
1197 inactive = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_INACTIVE_FILE));
1198 active = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_ACTIVE_FILE));
1200 return (active > inactive);
1203 struct zone_reclaim_stat *mem_cgroup_get_reclaim_stat(struct mem_cgroup *memcg,
1204 struct zone *zone)
1206 int nid = zone_to_nid(zone);
1207 int zid = zone_idx(zone);
1208 struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
1210 return &mz->reclaim_stat;
1213 struct zone_reclaim_stat *
1214 mem_cgroup_get_reclaim_stat_from_page(struct page *page)
1216 struct page_cgroup *pc;
1217 struct mem_cgroup_per_zone *mz;
1219 if (mem_cgroup_disabled())
1220 return NULL;
1222 pc = lookup_page_cgroup(page);
1223 if (!PageCgroupUsed(pc))
1224 return NULL;
1225 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1226 smp_rmb();
1227 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
1228 return &mz->reclaim_stat;
1231 unsigned long mem_cgroup_isolate_pages(unsigned long nr_to_scan,
1232 struct list_head *dst,
1233 unsigned long *scanned, int order,
1234 isolate_mode_t mode,
1235 struct zone *z,
1236 struct mem_cgroup *mem_cont,
1237 int active, int file)
1239 unsigned long nr_taken = 0;
1240 struct page *page;
1241 unsigned long scan;
1242 LIST_HEAD(pc_list);
1243 struct list_head *src;
1244 struct page_cgroup *pc, *tmp;
1245 int nid = zone_to_nid(z);
1246 int zid = zone_idx(z);
1247 struct mem_cgroup_per_zone *mz;
1248 int lru = LRU_FILE * file + active;
1249 int ret;
1251 BUG_ON(!mem_cont);
1252 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
1253 src = &mz->lists[lru];
1255 scan = 0;
1256 list_for_each_entry_safe_reverse(pc, tmp, src, lru) {
1257 if (scan >= nr_to_scan)
1258 break;
1260 if (unlikely(!PageCgroupUsed(pc)))
1261 continue;
1263 page = lookup_cgroup_page(pc);
1265 if (unlikely(!PageLRU(page)))
1266 continue;
1268 scan++;
1269 ret = __isolate_lru_page(page, mode, file);
1270 switch (ret) {
1271 case 0:
1272 list_move(&page->lru, dst);
1273 mem_cgroup_del_lru(page);
1274 nr_taken += hpage_nr_pages(page);
1275 break;
1276 case -EBUSY:
1277 /* we don't affect global LRU but rotate in our LRU */
1278 mem_cgroup_rotate_lru_list(page, page_lru(page));
1279 break;
1280 default:
1281 break;
1285 *scanned = scan;
1287 trace_mm_vmscan_memcg_isolate(0, nr_to_scan, scan, nr_taken,
1288 0, 0, 0, mode);
1290 return nr_taken;
1293 #define mem_cgroup_from_res_counter(counter, member) \
1294 container_of(counter, struct mem_cgroup, member)
1297 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1298 * @mem: the memory cgroup
1300 * Returns the maximum amount of memory @mem can be charged with, in
1301 * pages.
1303 static unsigned long mem_cgroup_margin(struct mem_cgroup *mem)
1305 unsigned long long margin;
1307 margin = res_counter_margin(&mem->res);
1308 if (do_swap_account)
1309 margin = min(margin, res_counter_margin(&mem->memsw));
1310 return margin >> PAGE_SHIFT;
1313 int mem_cgroup_swappiness(struct mem_cgroup *memcg)
1315 struct cgroup *cgrp = memcg->css.cgroup;
1317 /* root ? */
1318 if (cgrp->parent == NULL)
1319 return vm_swappiness;
1321 return memcg->swappiness;
1324 static void mem_cgroup_start_move(struct mem_cgroup *mem)
1326 int cpu;
1328 get_online_cpus();
1329 spin_lock(&mem->pcp_counter_lock);
1330 for_each_online_cpu(cpu)
1331 per_cpu(mem->stat->count[MEM_CGROUP_ON_MOVE], cpu) += 1;
1332 mem->nocpu_base.count[MEM_CGROUP_ON_MOVE] += 1;
1333 spin_unlock(&mem->pcp_counter_lock);
1334 put_online_cpus();
1336 synchronize_rcu();
1339 static void mem_cgroup_end_move(struct mem_cgroup *mem)
1341 int cpu;
1343 if (!mem)
1344 return;
1345 get_online_cpus();
1346 spin_lock(&mem->pcp_counter_lock);
1347 for_each_online_cpu(cpu)
1348 per_cpu(mem->stat->count[MEM_CGROUP_ON_MOVE], cpu) -= 1;
1349 mem->nocpu_base.count[MEM_CGROUP_ON_MOVE] -= 1;
1350 spin_unlock(&mem->pcp_counter_lock);
1351 put_online_cpus();
1354 * 2 routines for checking "mem" is under move_account() or not.
1356 * mem_cgroup_stealed() - checking a cgroup is mc.from or not. This is used
1357 * for avoiding race in accounting. If true,
1358 * pc->mem_cgroup may be overwritten.
1360 * mem_cgroup_under_move() - checking a cgroup is mc.from or mc.to or
1361 * under hierarchy of moving cgroups. This is for
1362 * waiting at hith-memory prressure caused by "move".
1365 static bool mem_cgroup_stealed(struct mem_cgroup *mem)
1367 VM_BUG_ON(!rcu_read_lock_held());
1368 return this_cpu_read(mem->stat->count[MEM_CGROUP_ON_MOVE]) > 0;
1371 static bool mem_cgroup_under_move(struct mem_cgroup *mem)
1373 struct mem_cgroup *from;
1374 struct mem_cgroup *to;
1375 bool ret = false;
1377 * Unlike task_move routines, we access mc.to, mc.from not under
1378 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1380 spin_lock(&mc.lock);
1381 from = mc.from;
1382 to = mc.to;
1383 if (!from)
1384 goto unlock;
1386 ret = mem_cgroup_same_or_subtree(mem, from)
1387 || mem_cgroup_same_or_subtree(mem, to);
1388 unlock:
1389 spin_unlock(&mc.lock);
1390 return ret;
1393 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *mem)
1395 if (mc.moving_task && current != mc.moving_task) {
1396 if (mem_cgroup_under_move(mem)) {
1397 DEFINE_WAIT(wait);
1398 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1399 /* moving charge context might have finished. */
1400 if (mc.moving_task)
1401 schedule();
1402 finish_wait(&mc.waitq, &wait);
1403 return true;
1406 return false;
1410 * mem_cgroup_print_oom_info: Called from OOM with tasklist_lock held in read mode.
1411 * @memcg: The memory cgroup that went over limit
1412 * @p: Task that is going to be killed
1414 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1415 * enabled
1417 void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1419 struct cgroup *task_cgrp;
1420 struct cgroup *mem_cgrp;
1422 * Need a buffer in BSS, can't rely on allocations. The code relies
1423 * on the assumption that OOM is serialized for memory controller.
1424 * If this assumption is broken, revisit this code.
1426 static char memcg_name[PATH_MAX];
1427 int ret;
1429 if (!memcg || !p)
1430 return;
1433 rcu_read_lock();
1435 mem_cgrp = memcg->css.cgroup;
1436 task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
1438 ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
1439 if (ret < 0) {
1441 * Unfortunately, we are unable to convert to a useful name
1442 * But we'll still print out the usage information
1444 rcu_read_unlock();
1445 goto done;
1447 rcu_read_unlock();
1449 printk(KERN_INFO "Task in %s killed", memcg_name);
1451 rcu_read_lock();
1452 ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
1453 if (ret < 0) {
1454 rcu_read_unlock();
1455 goto done;
1457 rcu_read_unlock();
1460 * Continues from above, so we don't need an KERN_ level
1462 printk(KERN_CONT " as a result of limit of %s\n", memcg_name);
1463 done:
1465 printk(KERN_INFO "memory: usage %llukB, limit %llukB, failcnt %llu\n",
1466 res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
1467 res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
1468 res_counter_read_u64(&memcg->res, RES_FAILCNT));
1469 printk(KERN_INFO "memory+swap: usage %llukB, limit %llukB, "
1470 "failcnt %llu\n",
1471 res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
1472 res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
1473 res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
1477 * This function returns the number of memcg under hierarchy tree. Returns
1478 * 1(self count) if no children.
1480 static int mem_cgroup_count_children(struct mem_cgroup *mem)
1482 int num = 0;
1483 struct mem_cgroup *iter;
1485 for_each_mem_cgroup_tree(iter, mem)
1486 num++;
1487 return num;
1491 * Return the memory (and swap, if configured) limit for a memcg.
1493 u64 mem_cgroup_get_limit(struct mem_cgroup *memcg)
1495 u64 limit;
1496 u64 memsw;
1498 limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
1499 limit += total_swap_pages << PAGE_SHIFT;
1501 memsw = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
1503 * If memsw is finite and limits the amount of swap space available
1504 * to this memcg, return that limit.
1506 return min(limit, memsw);
1510 * Visit the first child (need not be the first child as per the ordering
1511 * of the cgroup list, since we track last_scanned_child) of @mem and use
1512 * that to reclaim free pages from.
1514 static struct mem_cgroup *
1515 mem_cgroup_select_victim(struct mem_cgroup *root_mem)
1517 struct mem_cgroup *ret = NULL;
1518 struct cgroup_subsys_state *css;
1519 int nextid, found;
1521 if (!root_mem->use_hierarchy) {
1522 css_get(&root_mem->css);
1523 ret = root_mem;
1526 while (!ret) {
1527 rcu_read_lock();
1528 nextid = root_mem->last_scanned_child + 1;
1529 css = css_get_next(&mem_cgroup_subsys, nextid, &root_mem->css,
1530 &found);
1531 if (css && css_tryget(css))
1532 ret = container_of(css, struct mem_cgroup, css);
1534 rcu_read_unlock();
1535 /* Updates scanning parameter */
1536 if (!css) {
1537 /* this means start scan from ID:1 */
1538 root_mem->last_scanned_child = 0;
1539 } else
1540 root_mem->last_scanned_child = found;
1543 return ret;
1547 * test_mem_cgroup_node_reclaimable
1548 * @mem: the target memcg
1549 * @nid: the node ID to be checked.
1550 * @noswap : specify true here if the user wants flle only information.
1552 * This function returns whether the specified memcg contains any
1553 * reclaimable pages on a node. Returns true if there are any reclaimable
1554 * pages in the node.
1556 static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *mem,
1557 int nid, bool noswap)
1559 if (mem_cgroup_node_nr_lru_pages(mem, nid, LRU_ALL_FILE))
1560 return true;
1561 if (noswap || !total_swap_pages)
1562 return false;
1563 if (mem_cgroup_node_nr_lru_pages(mem, nid, LRU_ALL_ANON))
1564 return true;
1565 return false;
1568 #if MAX_NUMNODES > 1
1571 * Always updating the nodemask is not very good - even if we have an empty
1572 * list or the wrong list here, we can start from some node and traverse all
1573 * nodes based on the zonelist. So update the list loosely once per 10 secs.
1576 static void mem_cgroup_may_update_nodemask(struct mem_cgroup *mem)
1578 int nid;
1580 * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
1581 * pagein/pageout changes since the last update.
1583 if (!atomic_read(&mem->numainfo_events))
1584 return;
1585 if (atomic_inc_return(&mem->numainfo_updating) > 1)
1586 return;
1588 /* make a nodemask where this memcg uses memory from */
1589 mem->scan_nodes = node_states[N_HIGH_MEMORY];
1591 for_each_node_mask(nid, node_states[N_HIGH_MEMORY]) {
1593 if (!test_mem_cgroup_node_reclaimable(mem, nid, false))
1594 node_clear(nid, mem->scan_nodes);
1597 atomic_set(&mem->numainfo_events, 0);
1598 atomic_set(&mem->numainfo_updating, 0);
1602 * Selecting a node where we start reclaim from. Because what we need is just
1603 * reducing usage counter, start from anywhere is O,K. Considering
1604 * memory reclaim from current node, there are pros. and cons.
1606 * Freeing memory from current node means freeing memory from a node which
1607 * we'll use or we've used. So, it may make LRU bad. And if several threads
1608 * hit limits, it will see a contention on a node. But freeing from remote
1609 * node means more costs for memory reclaim because of memory latency.
1611 * Now, we use round-robin. Better algorithm is welcomed.
1613 int mem_cgroup_select_victim_node(struct mem_cgroup *mem)
1615 int node;
1617 mem_cgroup_may_update_nodemask(mem);
1618 node = mem->last_scanned_node;
1620 node = next_node(node, mem->scan_nodes);
1621 if (node == MAX_NUMNODES)
1622 node = first_node(mem->scan_nodes);
1624 * We call this when we hit limit, not when pages are added to LRU.
1625 * No LRU may hold pages because all pages are UNEVICTABLE or
1626 * memcg is too small and all pages are not on LRU. In that case,
1627 * we use curret node.
1629 if (unlikely(node == MAX_NUMNODES))
1630 node = numa_node_id();
1632 mem->last_scanned_node = node;
1633 return node;
1637 * Check all nodes whether it contains reclaimable pages or not.
1638 * For quick scan, we make use of scan_nodes. This will allow us to skip
1639 * unused nodes. But scan_nodes is lazily updated and may not cotain
1640 * enough new information. We need to do double check.
1642 bool mem_cgroup_reclaimable(struct mem_cgroup *mem, bool noswap)
1644 int nid;
1647 * quick check...making use of scan_node.
1648 * We can skip unused nodes.
1650 if (!nodes_empty(mem->scan_nodes)) {
1651 for (nid = first_node(mem->scan_nodes);
1652 nid < MAX_NUMNODES;
1653 nid = next_node(nid, mem->scan_nodes)) {
1655 if (test_mem_cgroup_node_reclaimable(mem, nid, noswap))
1656 return true;
1660 * Check rest of nodes.
1662 for_each_node_state(nid, N_HIGH_MEMORY) {
1663 if (node_isset(nid, mem->scan_nodes))
1664 continue;
1665 if (test_mem_cgroup_node_reclaimable(mem, nid, noswap))
1666 return true;
1668 return false;
1671 #else
1672 int mem_cgroup_select_victim_node(struct mem_cgroup *mem)
1674 return 0;
1677 bool mem_cgroup_reclaimable(struct mem_cgroup *mem, bool noswap)
1679 return test_mem_cgroup_node_reclaimable(mem, 0, noswap);
1681 #endif
1683 static void __mem_cgroup_record_scanstat(unsigned long *stats,
1684 struct memcg_scanrecord *rec)
1687 stats[SCAN] += rec->nr_scanned[0] + rec->nr_scanned[1];
1688 stats[SCAN_ANON] += rec->nr_scanned[0];
1689 stats[SCAN_FILE] += rec->nr_scanned[1];
1691 stats[ROTATE] += rec->nr_rotated[0] + rec->nr_rotated[1];
1692 stats[ROTATE_ANON] += rec->nr_rotated[0];
1693 stats[ROTATE_FILE] += rec->nr_rotated[1];
1695 stats[FREED] += rec->nr_freed[0] + rec->nr_freed[1];
1696 stats[FREED_ANON] += rec->nr_freed[0];
1697 stats[FREED_FILE] += rec->nr_freed[1];
1699 stats[ELAPSED] += rec->elapsed;
1702 static void mem_cgroup_record_scanstat(struct memcg_scanrecord *rec)
1704 struct mem_cgroup *mem;
1705 int context = rec->context;
1707 if (context >= NR_SCAN_CONTEXT)
1708 return;
1710 mem = rec->mem;
1711 spin_lock(&mem->scanstat.lock);
1712 __mem_cgroup_record_scanstat(mem->scanstat.stats[context], rec);
1713 spin_unlock(&mem->scanstat.lock);
1715 mem = rec->root;
1716 spin_lock(&mem->scanstat.lock);
1717 __mem_cgroup_record_scanstat(mem->scanstat.rootstats[context], rec);
1718 spin_unlock(&mem->scanstat.lock);
1722 * Scan the hierarchy if needed to reclaim memory. We remember the last child
1723 * we reclaimed from, so that we don't end up penalizing one child extensively
1724 * based on its position in the children list.
1726 * root_mem is the original ancestor that we've been reclaim from.
1728 * We give up and return to the caller when we visit root_mem twice.
1729 * (other groups can be removed while we're walking....)
1731 * If shrink==true, for avoiding to free too much, this returns immedieately.
1733 static int mem_cgroup_hierarchical_reclaim(struct mem_cgroup *root_mem,
1734 struct zone *zone,
1735 gfp_t gfp_mask,
1736 unsigned long reclaim_options,
1737 unsigned long *total_scanned)
1739 struct mem_cgroup *victim;
1740 int ret, total = 0;
1741 int loop = 0;
1742 bool noswap = reclaim_options & MEM_CGROUP_RECLAIM_NOSWAP;
1743 bool shrink = reclaim_options & MEM_CGROUP_RECLAIM_SHRINK;
1744 bool check_soft = reclaim_options & MEM_CGROUP_RECLAIM_SOFT;
1745 struct memcg_scanrecord rec;
1746 unsigned long excess;
1747 unsigned long scanned;
1749 excess = res_counter_soft_limit_excess(&root_mem->res) >> PAGE_SHIFT;
1751 /* If memsw_is_minimum==1, swap-out is of-no-use. */
1752 if (!check_soft && !shrink && root_mem->memsw_is_minimum)
1753 noswap = true;
1755 if (shrink)
1756 rec.context = SCAN_BY_SHRINK;
1757 else if (check_soft)
1758 rec.context = SCAN_BY_SYSTEM;
1759 else
1760 rec.context = SCAN_BY_LIMIT;
1762 rec.root = root_mem;
1764 while (1) {
1765 victim = mem_cgroup_select_victim(root_mem);
1766 if (victim == root_mem) {
1767 loop++;
1769 * We are not draining per cpu cached charges during
1770 * soft limit reclaim because global reclaim doesn't
1771 * care about charges. It tries to free some memory and
1772 * charges will not give any.
1774 if (!check_soft && loop >= 1)
1775 drain_all_stock_async(root_mem);
1776 if (loop >= 2) {
1778 * If we have not been able to reclaim
1779 * anything, it might because there are
1780 * no reclaimable pages under this hierarchy
1782 if (!check_soft || !total) {
1783 css_put(&victim->css);
1784 break;
1787 * We want to do more targeted reclaim.
1788 * excess >> 2 is not to excessive so as to
1789 * reclaim too much, nor too less that we keep
1790 * coming back to reclaim from this cgroup
1792 if (total >= (excess >> 2) ||
1793 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS)) {
1794 css_put(&victim->css);
1795 break;
1799 if (!mem_cgroup_reclaimable(victim, noswap)) {
1800 /* this cgroup's local usage == 0 */
1801 css_put(&victim->css);
1802 continue;
1804 rec.mem = victim;
1805 rec.nr_scanned[0] = 0;
1806 rec.nr_scanned[1] = 0;
1807 rec.nr_rotated[0] = 0;
1808 rec.nr_rotated[1] = 0;
1809 rec.nr_freed[0] = 0;
1810 rec.nr_freed[1] = 0;
1811 rec.elapsed = 0;
1812 /* we use swappiness of local cgroup */
1813 if (check_soft) {
1814 ret = mem_cgroup_shrink_node_zone(victim, gfp_mask,
1815 noswap, zone, &rec, &scanned);
1816 *total_scanned += scanned;
1817 } else
1818 ret = try_to_free_mem_cgroup_pages(victim, gfp_mask,
1819 noswap, &rec);
1820 mem_cgroup_record_scanstat(&rec);
1821 css_put(&victim->css);
1823 * At shrinking usage, we can't check we should stop here or
1824 * reclaim more. It's depends on callers. last_scanned_child
1825 * will work enough for keeping fairness under tree.
1827 if (shrink)
1828 return ret;
1829 total += ret;
1830 if (check_soft) {
1831 if (!res_counter_soft_limit_excess(&root_mem->res))
1832 return total;
1833 } else if (mem_cgroup_margin(root_mem))
1834 return total;
1836 return total;
1840 * Check OOM-Killer is already running under our hierarchy.
1841 * If someone is running, return false.
1842 * Has to be called with memcg_oom_lock
1844 static bool mem_cgroup_oom_lock(struct mem_cgroup *mem)
1846 int lock_count = -1;
1847 struct mem_cgroup *iter, *failed = NULL;
1848 bool cond = true;
1850 for_each_mem_cgroup_tree_cond(iter, mem, cond) {
1851 bool locked = iter->oom_lock;
1853 iter->oom_lock = true;
1854 if (lock_count == -1)
1855 lock_count = iter->oom_lock;
1856 else if (lock_count != locked) {
1858 * this subtree of our hierarchy is already locked
1859 * so we cannot give a lock.
1861 lock_count = 0;
1862 failed = iter;
1863 cond = false;
1867 if (!failed)
1868 goto done;
1871 * OK, we failed to lock the whole subtree so we have to clean up
1872 * what we set up to the failing subtree
1874 cond = true;
1875 for_each_mem_cgroup_tree_cond(iter, mem, cond) {
1876 if (iter == failed) {
1877 cond = false;
1878 continue;
1880 iter->oom_lock = false;
1882 done:
1883 return lock_count;
1887 * Has to be called with memcg_oom_lock
1889 static int mem_cgroup_oom_unlock(struct mem_cgroup *mem)
1891 struct mem_cgroup *iter;
1893 for_each_mem_cgroup_tree(iter, mem)
1894 iter->oom_lock = false;
1895 return 0;
1898 static void mem_cgroup_mark_under_oom(struct mem_cgroup *mem)
1900 struct mem_cgroup *iter;
1902 for_each_mem_cgroup_tree(iter, mem)
1903 atomic_inc(&iter->under_oom);
1906 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *mem)
1908 struct mem_cgroup *iter;
1911 * When a new child is created while the hierarchy is under oom,
1912 * mem_cgroup_oom_lock() may not be called. We have to use
1913 * atomic_add_unless() here.
1915 for_each_mem_cgroup_tree(iter, mem)
1916 atomic_add_unless(&iter->under_oom, -1, 0);
1919 static DEFINE_SPINLOCK(memcg_oom_lock);
1920 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1922 struct oom_wait_info {
1923 struct mem_cgroup *mem;
1924 wait_queue_t wait;
1927 static int memcg_oom_wake_function(wait_queue_t *wait,
1928 unsigned mode, int sync, void *arg)
1930 struct mem_cgroup *wake_mem = (struct mem_cgroup *)arg,
1931 *oom_wait_mem;
1932 struct oom_wait_info *oom_wait_info;
1934 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1935 oom_wait_mem = oom_wait_info->mem;
1938 * Both of oom_wait_info->mem and wake_mem are stable under us.
1939 * Then we can use css_is_ancestor without taking care of RCU.
1941 if (!mem_cgroup_same_or_subtree(oom_wait_mem, wake_mem)
1942 && !mem_cgroup_same_or_subtree(wake_mem, oom_wait_mem))
1943 return 0;
1944 return autoremove_wake_function(wait, mode, sync, arg);
1947 static void memcg_wakeup_oom(struct mem_cgroup *mem)
1949 /* for filtering, pass "mem" as argument. */
1950 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, mem);
1953 static void memcg_oom_recover(struct mem_cgroup *mem)
1955 if (mem && atomic_read(&mem->under_oom))
1956 memcg_wakeup_oom(mem);
1960 * try to call OOM killer. returns false if we should exit memory-reclaim loop.
1962 bool mem_cgroup_handle_oom(struct mem_cgroup *mem, gfp_t mask)
1964 struct oom_wait_info owait;
1965 bool locked, need_to_kill;
1967 owait.mem = mem;
1968 owait.wait.flags = 0;
1969 owait.wait.func = memcg_oom_wake_function;
1970 owait.wait.private = current;
1971 INIT_LIST_HEAD(&owait.wait.task_list);
1972 need_to_kill = true;
1973 mem_cgroup_mark_under_oom(mem);
1975 /* At first, try to OOM lock hierarchy under mem.*/
1976 spin_lock(&memcg_oom_lock);
1977 locked = mem_cgroup_oom_lock(mem);
1979 * Even if signal_pending(), we can't quit charge() loop without
1980 * accounting. So, UNINTERRUPTIBLE is appropriate. But SIGKILL
1981 * under OOM is always welcomed, use TASK_KILLABLE here.
1983 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
1984 if (!locked || mem->oom_kill_disable)
1985 need_to_kill = false;
1986 if (locked)
1987 mem_cgroup_oom_notify(mem);
1988 spin_unlock(&memcg_oom_lock);
1990 if (need_to_kill) {
1991 finish_wait(&memcg_oom_waitq, &owait.wait);
1992 mem_cgroup_out_of_memory(mem, mask);
1993 } else {
1994 schedule();
1995 finish_wait(&memcg_oom_waitq, &owait.wait);
1997 spin_lock(&memcg_oom_lock);
1998 if (locked)
1999 mem_cgroup_oom_unlock(mem);
2000 memcg_wakeup_oom(mem);
2001 spin_unlock(&memcg_oom_lock);
2003 mem_cgroup_unmark_under_oom(mem);
2005 if (test_thread_flag(TIF_MEMDIE) || fatal_signal_pending(current))
2006 return false;
2007 /* Give chance to dying process */
2008 schedule_timeout(1);
2009 return true;
2013 * Currently used to update mapped file statistics, but the routine can be
2014 * generalized to update other statistics as well.
2016 * Notes: Race condition
2018 * We usually use page_cgroup_lock() for accessing page_cgroup member but
2019 * it tends to be costly. But considering some conditions, we doesn't need
2020 * to do so _always_.
2022 * Considering "charge", lock_page_cgroup() is not required because all
2023 * file-stat operations happen after a page is attached to radix-tree. There
2024 * are no race with "charge".
2026 * Considering "uncharge", we know that memcg doesn't clear pc->mem_cgroup
2027 * at "uncharge" intentionally. So, we always see valid pc->mem_cgroup even
2028 * if there are race with "uncharge". Statistics itself is properly handled
2029 * by flags.
2031 * Considering "move", this is an only case we see a race. To make the race
2032 * small, we check MEM_CGROUP_ON_MOVE percpu value and detect there are
2033 * possibility of race condition. If there is, we take a lock.
2036 void mem_cgroup_update_page_stat(struct page *page,
2037 enum mem_cgroup_page_stat_item idx, int val)
2039 struct mem_cgroup *mem;
2040 struct page_cgroup *pc = lookup_page_cgroup(page);
2041 bool need_unlock = false;
2042 unsigned long uninitialized_var(flags);
2044 if (unlikely(!pc))
2045 return;
2047 rcu_read_lock();
2048 mem = pc->mem_cgroup;
2049 if (unlikely(!mem || !PageCgroupUsed(pc)))
2050 goto out;
2051 /* pc->mem_cgroup is unstable ? */
2052 if (unlikely(mem_cgroup_stealed(mem)) || PageTransHuge(page)) {
2053 /* take a lock against to access pc->mem_cgroup */
2054 move_lock_page_cgroup(pc, &flags);
2055 need_unlock = true;
2056 mem = pc->mem_cgroup;
2057 if (!mem || !PageCgroupUsed(pc))
2058 goto out;
2061 switch (idx) {
2062 case MEMCG_NR_FILE_MAPPED:
2063 if (val > 0)
2064 SetPageCgroupFileMapped(pc);
2065 else if (!page_mapped(page))
2066 ClearPageCgroupFileMapped(pc);
2067 idx = MEM_CGROUP_STAT_FILE_MAPPED;
2068 break;
2069 default:
2070 BUG();
2073 this_cpu_add(mem->stat->count[idx], val);
2075 out:
2076 if (unlikely(need_unlock))
2077 move_unlock_page_cgroup(pc, &flags);
2078 rcu_read_unlock();
2079 return;
2081 EXPORT_SYMBOL(mem_cgroup_update_page_stat);
2084 * size of first charge trial. "32" comes from vmscan.c's magic value.
2085 * TODO: maybe necessary to use big numbers in big irons.
2087 #define CHARGE_BATCH 32U
2088 struct memcg_stock_pcp {
2089 struct mem_cgroup *cached; /* this never be root cgroup */
2090 unsigned int nr_pages;
2091 struct work_struct work;
2092 unsigned long flags;
2093 #define FLUSHING_CACHED_CHARGE (0)
2095 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
2096 static DEFINE_MUTEX(percpu_charge_mutex);
2099 * Try to consume stocked charge on this cpu. If success, one page is consumed
2100 * from local stock and true is returned. If the stock is 0 or charges from a
2101 * cgroup which is not current target, returns false. This stock will be
2102 * refilled.
2104 static bool consume_stock(struct mem_cgroup *mem)
2106 struct memcg_stock_pcp *stock;
2107 bool ret = true;
2109 stock = &get_cpu_var(memcg_stock);
2110 if (mem == stock->cached && stock->nr_pages)
2111 stock->nr_pages--;
2112 else /* need to call res_counter_charge */
2113 ret = false;
2114 put_cpu_var(memcg_stock);
2115 return ret;
2119 * Returns stocks cached in percpu to res_counter and reset cached information.
2121 static void drain_stock(struct memcg_stock_pcp *stock)
2123 struct mem_cgroup *old = stock->cached;
2125 if (stock->nr_pages) {
2126 unsigned long bytes = stock->nr_pages * PAGE_SIZE;
2128 res_counter_uncharge(&old->res, bytes);
2129 if (do_swap_account)
2130 res_counter_uncharge(&old->memsw, bytes);
2131 stock->nr_pages = 0;
2133 stock->cached = NULL;
2137 * This must be called under preempt disabled or must be called by
2138 * a thread which is pinned to local cpu.
2140 static void drain_local_stock(struct work_struct *dummy)
2142 struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
2143 drain_stock(stock);
2144 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2148 * Cache charges(val) which is from res_counter, to local per_cpu area.
2149 * This will be consumed by consume_stock() function, later.
2151 static void refill_stock(struct mem_cgroup *mem, unsigned int nr_pages)
2153 struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
2155 if (stock->cached != mem) { /* reset if necessary */
2156 drain_stock(stock);
2157 stock->cached = mem;
2159 stock->nr_pages += nr_pages;
2160 put_cpu_var(memcg_stock);
2164 * Drains all per-CPU charge caches for given root_mem resp. subtree
2165 * of the hierarchy under it. sync flag says whether we should block
2166 * until the work is done.
2168 static void drain_all_stock(struct mem_cgroup *root_mem, bool sync)
2170 int cpu, curcpu;
2172 /* Notify other cpus that system-wide "drain" is running */
2173 get_online_cpus();
2175 * Get a hint for avoiding draining charges on the current cpu,
2176 * which must be exhausted by our charging. It is not required that
2177 * this be a precise check, so we use raw_smp_processor_id() instead of
2178 * getcpu()/putcpu().
2180 curcpu = raw_smp_processor_id();
2181 for_each_online_cpu(cpu) {
2182 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2183 struct mem_cgroup *mem;
2185 mem = stock->cached;
2186 if (!mem || !stock->nr_pages)
2187 continue;
2188 if (!mem_cgroup_same_or_subtree(root_mem, mem))
2189 continue;
2190 if (!test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2191 if (cpu == curcpu)
2192 drain_local_stock(&stock->work);
2193 else
2194 schedule_work_on(cpu, &stock->work);
2198 if (!sync)
2199 goto out;
2201 for_each_online_cpu(cpu) {
2202 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2203 if (test_bit(FLUSHING_CACHED_CHARGE, &stock->flags))
2204 flush_work(&stock->work);
2206 out:
2207 put_online_cpus();
2211 * Tries to drain stocked charges in other cpus. This function is asynchronous
2212 * and just put a work per cpu for draining localy on each cpu. Caller can
2213 * expects some charges will be back to res_counter later but cannot wait for
2214 * it.
2216 static void drain_all_stock_async(struct mem_cgroup *root_mem)
2219 * If someone calls draining, avoid adding more kworker runs.
2221 if (!mutex_trylock(&percpu_charge_mutex))
2222 return;
2223 drain_all_stock(root_mem, false);
2224 mutex_unlock(&percpu_charge_mutex);
2227 /* This is a synchronous drain interface. */
2228 static void drain_all_stock_sync(struct mem_cgroup *root_mem)
2230 /* called when force_empty is called */
2231 mutex_lock(&percpu_charge_mutex);
2232 drain_all_stock(root_mem, true);
2233 mutex_unlock(&percpu_charge_mutex);
2237 * This function drains percpu counter value from DEAD cpu and
2238 * move it to local cpu. Note that this function can be preempted.
2240 static void mem_cgroup_drain_pcp_counter(struct mem_cgroup *mem, int cpu)
2242 int i;
2244 spin_lock(&mem->pcp_counter_lock);
2245 for (i = 0; i < MEM_CGROUP_STAT_DATA; i++) {
2246 long x = per_cpu(mem->stat->count[i], cpu);
2248 per_cpu(mem->stat->count[i], cpu) = 0;
2249 mem->nocpu_base.count[i] += x;
2251 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
2252 unsigned long x = per_cpu(mem->stat->events[i], cpu);
2254 per_cpu(mem->stat->events[i], cpu) = 0;
2255 mem->nocpu_base.events[i] += x;
2257 /* need to clear ON_MOVE value, works as a kind of lock. */
2258 per_cpu(mem->stat->count[MEM_CGROUP_ON_MOVE], cpu) = 0;
2259 spin_unlock(&mem->pcp_counter_lock);
2262 static void synchronize_mem_cgroup_on_move(struct mem_cgroup *mem, int cpu)
2264 int idx = MEM_CGROUP_ON_MOVE;
2266 spin_lock(&mem->pcp_counter_lock);
2267 per_cpu(mem->stat->count[idx], cpu) = mem->nocpu_base.count[idx];
2268 spin_unlock(&mem->pcp_counter_lock);
2271 static int __cpuinit memcg_cpu_hotplug_callback(struct notifier_block *nb,
2272 unsigned long action,
2273 void *hcpu)
2275 int cpu = (unsigned long)hcpu;
2276 struct memcg_stock_pcp *stock;
2277 struct mem_cgroup *iter;
2279 if ((action == CPU_ONLINE)) {
2280 for_each_mem_cgroup_all(iter)
2281 synchronize_mem_cgroup_on_move(iter, cpu);
2282 return NOTIFY_OK;
2285 if ((action != CPU_DEAD) || action != CPU_DEAD_FROZEN)
2286 return NOTIFY_OK;
2288 for_each_mem_cgroup_all(iter)
2289 mem_cgroup_drain_pcp_counter(iter, cpu);
2291 stock = &per_cpu(memcg_stock, cpu);
2292 drain_stock(stock);
2293 return NOTIFY_OK;
2297 /* See __mem_cgroup_try_charge() for details */
2298 enum {
2299 CHARGE_OK, /* success */
2300 CHARGE_RETRY, /* need to retry but retry is not bad */
2301 CHARGE_NOMEM, /* we can't do more. return -ENOMEM */
2302 CHARGE_WOULDBLOCK, /* GFP_WAIT wasn't set and no enough res. */
2303 CHARGE_OOM_DIE, /* the current is killed because of OOM */
2306 static int mem_cgroup_do_charge(struct mem_cgroup *mem, gfp_t gfp_mask,
2307 unsigned int nr_pages, bool oom_check)
2309 unsigned long csize = nr_pages * PAGE_SIZE;
2310 struct mem_cgroup *mem_over_limit;
2311 struct res_counter *fail_res;
2312 unsigned long flags = 0;
2313 int ret;
2315 ret = res_counter_charge(&mem->res, csize, &fail_res);
2317 if (likely(!ret)) {
2318 if (!do_swap_account)
2319 return CHARGE_OK;
2320 ret = res_counter_charge(&mem->memsw, csize, &fail_res);
2321 if (likely(!ret))
2322 return CHARGE_OK;
2324 res_counter_uncharge(&mem->res, csize);
2325 mem_over_limit = mem_cgroup_from_res_counter(fail_res, memsw);
2326 flags |= MEM_CGROUP_RECLAIM_NOSWAP;
2327 } else
2328 mem_over_limit = mem_cgroup_from_res_counter(fail_res, res);
2330 * nr_pages can be either a huge page (HPAGE_PMD_NR), a batch
2331 * of regular pages (CHARGE_BATCH), or a single regular page (1).
2333 * Never reclaim on behalf of optional batching, retry with a
2334 * single page instead.
2336 if (nr_pages == CHARGE_BATCH)
2337 return CHARGE_RETRY;
2339 if (!(gfp_mask & __GFP_WAIT))
2340 return CHARGE_WOULDBLOCK;
2342 ret = mem_cgroup_hierarchical_reclaim(mem_over_limit, NULL,
2343 gfp_mask, flags, NULL);
2344 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2345 return CHARGE_RETRY;
2347 * Even though the limit is exceeded at this point, reclaim
2348 * may have been able to free some pages. Retry the charge
2349 * before killing the task.
2351 * Only for regular pages, though: huge pages are rather
2352 * unlikely to succeed so close to the limit, and we fall back
2353 * to regular pages anyway in case of failure.
2355 if (nr_pages == 1 && ret)
2356 return CHARGE_RETRY;
2359 * At task move, charge accounts can be doubly counted. So, it's
2360 * better to wait until the end of task_move if something is going on.
2362 if (mem_cgroup_wait_acct_move(mem_over_limit))
2363 return CHARGE_RETRY;
2365 /* If we don't need to call oom-killer at el, return immediately */
2366 if (!oom_check)
2367 return CHARGE_NOMEM;
2368 /* check OOM */
2369 if (!mem_cgroup_handle_oom(mem_over_limit, gfp_mask))
2370 return CHARGE_OOM_DIE;
2372 return CHARGE_RETRY;
2376 * Unlike exported interface, "oom" parameter is added. if oom==true,
2377 * oom-killer can be invoked.
2379 static int __mem_cgroup_try_charge(struct mm_struct *mm,
2380 gfp_t gfp_mask,
2381 unsigned int nr_pages,
2382 struct mem_cgroup **memcg,
2383 bool oom)
2385 unsigned int batch = max(CHARGE_BATCH, nr_pages);
2386 int nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2387 struct mem_cgroup *mem = NULL;
2388 int ret;
2391 * Unlike gloval-vm's OOM-kill, we're not in memory shortage
2392 * in system level. So, allow to go ahead dying process in addition to
2393 * MEMDIE process.
2395 if (unlikely(test_thread_flag(TIF_MEMDIE)
2396 || fatal_signal_pending(current)))
2397 goto bypass;
2400 * We always charge the cgroup the mm_struct belongs to.
2401 * The mm_struct's mem_cgroup changes on task migration if the
2402 * thread group leader migrates. It's possible that mm is not
2403 * set, if so charge the init_mm (happens for pagecache usage).
2405 if (!*memcg && !mm)
2406 goto bypass;
2407 again:
2408 if (*memcg) { /* css should be a valid one */
2409 mem = *memcg;
2410 VM_BUG_ON(css_is_removed(&mem->css));
2411 if (mem_cgroup_is_root(mem))
2412 goto done;
2413 if (nr_pages == 1 && consume_stock(mem))
2414 goto done;
2415 css_get(&mem->css);
2416 } else {
2417 struct task_struct *p;
2419 rcu_read_lock();
2420 p = rcu_dereference(mm->owner);
2422 * Because we don't have task_lock(), "p" can exit.
2423 * In that case, "mem" can point to root or p can be NULL with
2424 * race with swapoff. Then, we have small risk of mis-accouning.
2425 * But such kind of mis-account by race always happens because
2426 * we don't have cgroup_mutex(). It's overkill and we allo that
2427 * small race, here.
2428 * (*) swapoff at el will charge against mm-struct not against
2429 * task-struct. So, mm->owner can be NULL.
2431 mem = mem_cgroup_from_task(p);
2432 if (!mem || mem_cgroup_is_root(mem)) {
2433 rcu_read_unlock();
2434 goto done;
2436 if (nr_pages == 1 && consume_stock(mem)) {
2438 * It seems dagerous to access memcg without css_get().
2439 * But considering how consume_stok works, it's not
2440 * necessary. If consume_stock success, some charges
2441 * from this memcg are cached on this cpu. So, we
2442 * don't need to call css_get()/css_tryget() before
2443 * calling consume_stock().
2445 rcu_read_unlock();
2446 goto done;
2448 /* after here, we may be blocked. we need to get refcnt */
2449 if (!css_tryget(&mem->css)) {
2450 rcu_read_unlock();
2451 goto again;
2453 rcu_read_unlock();
2456 do {
2457 bool oom_check;
2459 /* If killed, bypass charge */
2460 if (fatal_signal_pending(current)) {
2461 css_put(&mem->css);
2462 goto bypass;
2465 oom_check = false;
2466 if (oom && !nr_oom_retries) {
2467 oom_check = true;
2468 nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2471 ret = mem_cgroup_do_charge(mem, gfp_mask, batch, oom_check);
2472 switch (ret) {
2473 case CHARGE_OK:
2474 break;
2475 case CHARGE_RETRY: /* not in OOM situation but retry */
2476 batch = nr_pages;
2477 css_put(&mem->css);
2478 mem = NULL;
2479 goto again;
2480 case CHARGE_WOULDBLOCK: /* !__GFP_WAIT */
2481 css_put(&mem->css);
2482 goto nomem;
2483 case CHARGE_NOMEM: /* OOM routine works */
2484 if (!oom) {
2485 css_put(&mem->css);
2486 goto nomem;
2488 /* If oom, we never return -ENOMEM */
2489 nr_oom_retries--;
2490 break;
2491 case CHARGE_OOM_DIE: /* Killed by OOM Killer */
2492 css_put(&mem->css);
2493 goto bypass;
2495 } while (ret != CHARGE_OK);
2497 if (batch > nr_pages)
2498 refill_stock(mem, batch - nr_pages);
2499 css_put(&mem->css);
2500 done:
2501 *memcg = mem;
2502 return 0;
2503 nomem:
2504 *memcg = NULL;
2505 return -ENOMEM;
2506 bypass:
2507 *memcg = NULL;
2508 return 0;
2512 * Somemtimes we have to undo a charge we got by try_charge().
2513 * This function is for that and do uncharge, put css's refcnt.
2514 * gotten by try_charge().
2516 static void __mem_cgroup_cancel_charge(struct mem_cgroup *mem,
2517 unsigned int nr_pages)
2519 if (!mem_cgroup_is_root(mem)) {
2520 unsigned long bytes = nr_pages * PAGE_SIZE;
2522 res_counter_uncharge(&mem->res, bytes);
2523 if (do_swap_account)
2524 res_counter_uncharge(&mem->memsw, bytes);
2529 * A helper function to get mem_cgroup from ID. must be called under
2530 * rcu_read_lock(). The caller must check css_is_removed() or some if
2531 * it's concern. (dropping refcnt from swap can be called against removed
2532 * memcg.)
2534 static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
2536 struct cgroup_subsys_state *css;
2538 /* ID 0 is unused ID */
2539 if (!id)
2540 return NULL;
2541 css = css_lookup(&mem_cgroup_subsys, id);
2542 if (!css)
2543 return NULL;
2544 return container_of(css, struct mem_cgroup, css);
2547 struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
2549 struct mem_cgroup *mem = NULL;
2550 struct page_cgroup *pc;
2551 unsigned short id;
2552 swp_entry_t ent;
2554 VM_BUG_ON(!PageLocked(page));
2556 pc = lookup_page_cgroup(page);
2557 lock_page_cgroup(pc);
2558 if (PageCgroupUsed(pc)) {
2559 mem = pc->mem_cgroup;
2560 if (mem && !css_tryget(&mem->css))
2561 mem = NULL;
2562 } else if (PageSwapCache(page)) {
2563 ent.val = page_private(page);
2564 id = lookup_swap_cgroup(ent);
2565 rcu_read_lock();
2566 mem = mem_cgroup_lookup(id);
2567 if (mem && !css_tryget(&mem->css))
2568 mem = NULL;
2569 rcu_read_unlock();
2571 unlock_page_cgroup(pc);
2572 return mem;
2575 static void __mem_cgroup_commit_charge(struct mem_cgroup *mem,
2576 struct page *page,
2577 unsigned int nr_pages,
2578 struct page_cgroup *pc,
2579 enum charge_type ctype)
2581 lock_page_cgroup(pc);
2582 if (unlikely(PageCgroupUsed(pc))) {
2583 unlock_page_cgroup(pc);
2584 __mem_cgroup_cancel_charge(mem, nr_pages);
2585 return;
2588 * we don't need page_cgroup_lock about tail pages, becase they are not
2589 * accessed by any other context at this point.
2591 pc->mem_cgroup = mem;
2593 * We access a page_cgroup asynchronously without lock_page_cgroup().
2594 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
2595 * is accessed after testing USED bit. To make pc->mem_cgroup visible
2596 * before USED bit, we need memory barrier here.
2597 * See mem_cgroup_add_lru_list(), etc.
2599 smp_wmb();
2600 switch (ctype) {
2601 case MEM_CGROUP_CHARGE_TYPE_CACHE:
2602 case MEM_CGROUP_CHARGE_TYPE_SHMEM:
2603 SetPageCgroupCache(pc);
2604 SetPageCgroupUsed(pc);
2605 break;
2606 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
2607 ClearPageCgroupCache(pc);
2608 SetPageCgroupUsed(pc);
2609 break;
2610 default:
2611 break;
2614 mem_cgroup_charge_statistics(mem, PageCgroupCache(pc), nr_pages);
2615 unlock_page_cgroup(pc);
2617 * "charge_statistics" updated event counter. Then, check it.
2618 * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
2619 * if they exceeds softlimit.
2621 memcg_check_events(mem, page);
2624 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
2626 #define PCGF_NOCOPY_AT_SPLIT ((1 << PCG_LOCK) | (1 << PCG_MOVE_LOCK) |\
2627 (1 << PCG_ACCT_LRU) | (1 << PCG_MIGRATION))
2629 * Because tail pages are not marked as "used", set it. We're under
2630 * zone->lru_lock, 'splitting on pmd' and compund_lock.
2632 void mem_cgroup_split_huge_fixup(struct page *head, struct page *tail)
2634 struct page_cgroup *head_pc = lookup_page_cgroup(head);
2635 struct page_cgroup *tail_pc = lookup_page_cgroup(tail);
2636 unsigned long flags;
2638 if (mem_cgroup_disabled())
2639 return;
2641 * We have no races with charge/uncharge but will have races with
2642 * page state accounting.
2644 move_lock_page_cgroup(head_pc, &flags);
2646 tail_pc->mem_cgroup = head_pc->mem_cgroup;
2647 smp_wmb(); /* see __commit_charge() */
2648 if (PageCgroupAcctLRU(head_pc)) {
2649 enum lru_list lru;
2650 struct mem_cgroup_per_zone *mz;
2653 * LRU flags cannot be copied because we need to add tail
2654 *.page to LRU by generic call and our hook will be called.
2655 * We hold lru_lock, then, reduce counter directly.
2657 lru = page_lru(head);
2658 mz = page_cgroup_zoneinfo(head_pc->mem_cgroup, head);
2659 MEM_CGROUP_ZSTAT(mz, lru) -= 1;
2661 tail_pc->flags = head_pc->flags & ~PCGF_NOCOPY_AT_SPLIT;
2662 move_unlock_page_cgroup(head_pc, &flags);
2664 #endif
2667 * mem_cgroup_move_account - move account of the page
2668 * @page: the page
2669 * @nr_pages: number of regular pages (>1 for huge pages)
2670 * @pc: page_cgroup of the page.
2671 * @from: mem_cgroup which the page is moved from.
2672 * @to: mem_cgroup which the page is moved to. @from != @to.
2673 * @uncharge: whether we should call uncharge and css_put against @from.
2675 * The caller must confirm following.
2676 * - page is not on LRU (isolate_page() is useful.)
2677 * - compound_lock is held when nr_pages > 1
2679 * This function doesn't do "charge" nor css_get to new cgroup. It should be
2680 * done by a caller(__mem_cgroup_try_charge would be useful). If @uncharge is
2681 * true, this function does "uncharge" from old cgroup, but it doesn't if
2682 * @uncharge is false, so a caller should do "uncharge".
2684 static int mem_cgroup_move_account(struct page *page,
2685 unsigned int nr_pages,
2686 struct page_cgroup *pc,
2687 struct mem_cgroup *from,
2688 struct mem_cgroup *to,
2689 bool uncharge)
2691 unsigned long flags;
2692 int ret;
2694 VM_BUG_ON(from == to);
2695 VM_BUG_ON(PageLRU(page));
2697 * The page is isolated from LRU. So, collapse function
2698 * will not handle this page. But page splitting can happen.
2699 * Do this check under compound_page_lock(). The caller should
2700 * hold it.
2702 ret = -EBUSY;
2703 if (nr_pages > 1 && !PageTransHuge(page))
2704 goto out;
2706 lock_page_cgroup(pc);
2708 ret = -EINVAL;
2709 if (!PageCgroupUsed(pc) || pc->mem_cgroup != from)
2710 goto unlock;
2712 move_lock_page_cgroup(pc, &flags);
2714 if (PageCgroupFileMapped(pc)) {
2715 /* Update mapped_file data for mem_cgroup */
2716 preempt_disable();
2717 __this_cpu_dec(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
2718 __this_cpu_inc(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
2719 preempt_enable();
2721 mem_cgroup_charge_statistics(from, PageCgroupCache(pc), -nr_pages);
2722 if (uncharge)
2723 /* This is not "cancel", but cancel_charge does all we need. */
2724 __mem_cgroup_cancel_charge(from, nr_pages);
2726 /* caller should have done css_get */
2727 pc->mem_cgroup = to;
2728 mem_cgroup_charge_statistics(to, PageCgroupCache(pc), nr_pages);
2730 * We charges against "to" which may not have any tasks. Then, "to"
2731 * can be under rmdir(). But in current implementation, caller of
2732 * this function is just force_empty() and move charge, so it's
2733 * guaranteed that "to" is never removed. So, we don't check rmdir
2734 * status here.
2736 move_unlock_page_cgroup(pc, &flags);
2737 ret = 0;
2738 unlock:
2739 unlock_page_cgroup(pc);
2741 * check events
2743 memcg_check_events(to, page);
2744 memcg_check_events(from, page);
2745 out:
2746 return ret;
2750 * move charges to its parent.
2753 static int mem_cgroup_move_parent(struct page *page,
2754 struct page_cgroup *pc,
2755 struct mem_cgroup *child,
2756 gfp_t gfp_mask)
2758 struct cgroup *cg = child->css.cgroup;
2759 struct cgroup *pcg = cg->parent;
2760 struct mem_cgroup *parent;
2761 unsigned int nr_pages;
2762 unsigned long uninitialized_var(flags);
2763 int ret;
2765 /* Is ROOT ? */
2766 if (!pcg)
2767 return -EINVAL;
2769 ret = -EBUSY;
2770 if (!get_page_unless_zero(page))
2771 goto out;
2772 if (isolate_lru_page(page))
2773 goto put;
2775 nr_pages = hpage_nr_pages(page);
2777 parent = mem_cgroup_from_cont(pcg);
2778 ret = __mem_cgroup_try_charge(NULL, gfp_mask, nr_pages, &parent, false);
2779 if (ret || !parent)
2780 goto put_back;
2782 if (nr_pages > 1)
2783 flags = compound_lock_irqsave(page);
2785 ret = mem_cgroup_move_account(page, nr_pages, pc, child, parent, true);
2786 if (ret)
2787 __mem_cgroup_cancel_charge(parent, nr_pages);
2789 if (nr_pages > 1)
2790 compound_unlock_irqrestore(page, flags);
2791 put_back:
2792 putback_lru_page(page);
2793 put:
2794 put_page(page);
2795 out:
2796 return ret;
2800 * Charge the memory controller for page usage.
2801 * Return
2802 * 0 if the charge was successful
2803 * < 0 if the cgroup is over its limit
2805 static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
2806 gfp_t gfp_mask, enum charge_type ctype)
2808 struct mem_cgroup *mem = NULL;
2809 unsigned int nr_pages = 1;
2810 struct page_cgroup *pc;
2811 bool oom = true;
2812 int ret;
2814 if (PageTransHuge(page)) {
2815 nr_pages <<= compound_order(page);
2816 VM_BUG_ON(!PageTransHuge(page));
2818 * Never OOM-kill a process for a huge page. The
2819 * fault handler will fall back to regular pages.
2821 oom = false;
2824 pc = lookup_page_cgroup(page);
2825 BUG_ON(!pc); /* XXX: remove this and move pc lookup into commit */
2827 ret = __mem_cgroup_try_charge(mm, gfp_mask, nr_pages, &mem, oom);
2828 if (ret || !mem)
2829 return ret;
2831 __mem_cgroup_commit_charge(mem, page, nr_pages, pc, ctype);
2832 return 0;
2835 int mem_cgroup_newpage_charge(struct page *page,
2836 struct mm_struct *mm, gfp_t gfp_mask)
2838 if (mem_cgroup_disabled())
2839 return 0;
2841 * If already mapped, we don't have to account.
2842 * If page cache, page->mapping has address_space.
2843 * But page->mapping may have out-of-use anon_vma pointer,
2844 * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
2845 * is NULL.
2847 if (page_mapped(page) || (page->mapping && !PageAnon(page)))
2848 return 0;
2849 if (unlikely(!mm))
2850 mm = &init_mm;
2851 return mem_cgroup_charge_common(page, mm, gfp_mask,
2852 MEM_CGROUP_CHARGE_TYPE_MAPPED);
2855 static void
2856 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
2857 enum charge_type ctype);
2859 static void
2860 __mem_cgroup_commit_charge_lrucare(struct page *page, struct mem_cgroup *mem,
2861 enum charge_type ctype)
2863 struct page_cgroup *pc = lookup_page_cgroup(page);
2865 * In some case, SwapCache, FUSE(splice_buf->radixtree), the page
2866 * is already on LRU. It means the page may on some other page_cgroup's
2867 * LRU. Take care of it.
2869 mem_cgroup_lru_del_before_commit(page);
2870 __mem_cgroup_commit_charge(mem, page, 1, pc, ctype);
2871 mem_cgroup_lru_add_after_commit(page);
2872 return;
2875 int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
2876 gfp_t gfp_mask)
2878 struct mem_cgroup *mem = NULL;
2879 int ret;
2881 if (mem_cgroup_disabled())
2882 return 0;
2883 if (PageCompound(page))
2884 return 0;
2886 if (unlikely(!mm))
2887 mm = &init_mm;
2889 if (page_is_file_cache(page)) {
2890 ret = __mem_cgroup_try_charge(mm, gfp_mask, 1, &mem, true);
2891 if (ret || !mem)
2892 return ret;
2895 * FUSE reuses pages without going through the final
2896 * put that would remove them from the LRU list, make
2897 * sure that they get relinked properly.
2899 __mem_cgroup_commit_charge_lrucare(page, mem,
2900 MEM_CGROUP_CHARGE_TYPE_CACHE);
2901 return ret;
2903 /* shmem */
2904 if (PageSwapCache(page)) {
2905 ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
2906 if (!ret)
2907 __mem_cgroup_commit_charge_swapin(page, mem,
2908 MEM_CGROUP_CHARGE_TYPE_SHMEM);
2909 } else
2910 ret = mem_cgroup_charge_common(page, mm, gfp_mask,
2911 MEM_CGROUP_CHARGE_TYPE_SHMEM);
2913 return ret;
2917 * While swap-in, try_charge -> commit or cancel, the page is locked.
2918 * And when try_charge() successfully returns, one refcnt to memcg without
2919 * struct page_cgroup is acquired. This refcnt will be consumed by
2920 * "commit()" or removed by "cancel()"
2922 int mem_cgroup_try_charge_swapin(struct mm_struct *mm,
2923 struct page *page,
2924 gfp_t mask, struct mem_cgroup **ptr)
2926 struct mem_cgroup *mem;
2927 int ret;
2929 *ptr = NULL;
2931 if (mem_cgroup_disabled())
2932 return 0;
2934 if (!do_swap_account)
2935 goto charge_cur_mm;
2937 * A racing thread's fault, or swapoff, may have already updated
2938 * the pte, and even removed page from swap cache: in those cases
2939 * do_swap_page()'s pte_same() test will fail; but there's also a
2940 * KSM case which does need to charge the page.
2942 if (!PageSwapCache(page))
2943 goto charge_cur_mm;
2944 mem = try_get_mem_cgroup_from_page(page);
2945 if (!mem)
2946 goto charge_cur_mm;
2947 *ptr = mem;
2948 ret = __mem_cgroup_try_charge(NULL, mask, 1, ptr, true);
2949 css_put(&mem->css);
2950 return ret;
2951 charge_cur_mm:
2952 if (unlikely(!mm))
2953 mm = &init_mm;
2954 return __mem_cgroup_try_charge(mm, mask, 1, ptr, true);
2957 static void
2958 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
2959 enum charge_type ctype)
2961 if (mem_cgroup_disabled())
2962 return;
2963 if (!ptr)
2964 return;
2965 cgroup_exclude_rmdir(&ptr->css);
2967 __mem_cgroup_commit_charge_lrucare(page, ptr, ctype);
2969 * Now swap is on-memory. This means this page may be
2970 * counted both as mem and swap....double count.
2971 * Fix it by uncharging from memsw. Basically, this SwapCache is stable
2972 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
2973 * may call delete_from_swap_cache() before reach here.
2975 if (do_swap_account && PageSwapCache(page)) {
2976 swp_entry_t ent = {.val = page_private(page)};
2977 unsigned short id;
2978 struct mem_cgroup *memcg;
2980 id = swap_cgroup_record(ent, 0);
2981 rcu_read_lock();
2982 memcg = mem_cgroup_lookup(id);
2983 if (memcg) {
2985 * This recorded memcg can be obsolete one. So, avoid
2986 * calling css_tryget
2988 if (!mem_cgroup_is_root(memcg))
2989 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
2990 mem_cgroup_swap_statistics(memcg, false);
2991 mem_cgroup_put(memcg);
2993 rcu_read_unlock();
2996 * At swapin, we may charge account against cgroup which has no tasks.
2997 * So, rmdir()->pre_destroy() can be called while we do this charge.
2998 * In that case, we need to call pre_destroy() again. check it here.
3000 cgroup_release_and_wakeup_rmdir(&ptr->css);
3003 void mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr)
3005 __mem_cgroup_commit_charge_swapin(page, ptr,
3006 MEM_CGROUP_CHARGE_TYPE_MAPPED);
3009 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *mem)
3011 if (mem_cgroup_disabled())
3012 return;
3013 if (!mem)
3014 return;
3015 __mem_cgroup_cancel_charge(mem, 1);
3018 static void mem_cgroup_do_uncharge(struct mem_cgroup *mem,
3019 unsigned int nr_pages,
3020 const enum charge_type ctype)
3022 struct memcg_batch_info *batch = NULL;
3023 bool uncharge_memsw = true;
3025 /* If swapout, usage of swap doesn't decrease */
3026 if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
3027 uncharge_memsw = false;
3029 batch = &current->memcg_batch;
3031 * In usual, we do css_get() when we remember memcg pointer.
3032 * But in this case, we keep res->usage until end of a series of
3033 * uncharges. Then, it's ok to ignore memcg's refcnt.
3035 if (!batch->memcg)
3036 batch->memcg = mem;
3038 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
3039 * In those cases, all pages freed continuously can be expected to be in
3040 * the same cgroup and we have chance to coalesce uncharges.
3041 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
3042 * because we want to do uncharge as soon as possible.
3045 if (!batch->do_batch || test_thread_flag(TIF_MEMDIE))
3046 goto direct_uncharge;
3048 if (nr_pages > 1)
3049 goto direct_uncharge;
3052 * In typical case, batch->memcg == mem. This means we can
3053 * merge a series of uncharges to an uncharge of res_counter.
3054 * If not, we uncharge res_counter ony by one.
3056 if (batch->memcg != mem)
3057 goto direct_uncharge;
3058 /* remember freed charge and uncharge it later */
3059 batch->nr_pages++;
3060 if (uncharge_memsw)
3061 batch->memsw_nr_pages++;
3062 return;
3063 direct_uncharge:
3064 res_counter_uncharge(&mem->res, nr_pages * PAGE_SIZE);
3065 if (uncharge_memsw)
3066 res_counter_uncharge(&mem->memsw, nr_pages * PAGE_SIZE);
3067 if (unlikely(batch->memcg != mem))
3068 memcg_oom_recover(mem);
3069 return;
3073 * uncharge if !page_mapped(page)
3075 static struct mem_cgroup *
3076 __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype)
3078 struct mem_cgroup *mem = NULL;
3079 unsigned int nr_pages = 1;
3080 struct page_cgroup *pc;
3082 if (mem_cgroup_disabled())
3083 return NULL;
3085 if (PageSwapCache(page))
3086 return NULL;
3088 if (PageTransHuge(page)) {
3089 nr_pages <<= compound_order(page);
3090 VM_BUG_ON(!PageTransHuge(page));
3093 * Check if our page_cgroup is valid
3095 pc = lookup_page_cgroup(page);
3096 if (unlikely(!pc || !PageCgroupUsed(pc)))
3097 return NULL;
3099 lock_page_cgroup(pc);
3101 mem = pc->mem_cgroup;
3103 if (!PageCgroupUsed(pc))
3104 goto unlock_out;
3106 switch (ctype) {
3107 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
3108 case MEM_CGROUP_CHARGE_TYPE_DROP:
3109 /* See mem_cgroup_prepare_migration() */
3110 if (page_mapped(page) || PageCgroupMigration(pc))
3111 goto unlock_out;
3112 break;
3113 case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
3114 if (!PageAnon(page)) { /* Shared memory */
3115 if (page->mapping && !page_is_file_cache(page))
3116 goto unlock_out;
3117 } else if (page_mapped(page)) /* Anon */
3118 goto unlock_out;
3119 break;
3120 default:
3121 break;
3124 mem_cgroup_charge_statistics(mem, PageCgroupCache(pc), -nr_pages);
3126 ClearPageCgroupUsed(pc);
3128 * pc->mem_cgroup is not cleared here. It will be accessed when it's
3129 * freed from LRU. This is safe because uncharged page is expected not
3130 * to be reused (freed soon). Exception is SwapCache, it's handled by
3131 * special functions.
3134 unlock_page_cgroup(pc);
3136 * even after unlock, we have mem->res.usage here and this memcg
3137 * will never be freed.
3139 memcg_check_events(mem, page);
3140 if (do_swap_account && ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT) {
3141 mem_cgroup_swap_statistics(mem, true);
3142 mem_cgroup_get(mem);
3144 if (!mem_cgroup_is_root(mem))
3145 mem_cgroup_do_uncharge(mem, nr_pages, ctype);
3147 return mem;
3149 unlock_out:
3150 unlock_page_cgroup(pc);
3151 return NULL;
3154 void mem_cgroup_uncharge_page(struct page *page)
3156 /* early check. */
3157 if (page_mapped(page))
3158 return;
3159 if (page->mapping && !PageAnon(page))
3160 return;
3161 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_MAPPED);
3164 void mem_cgroup_uncharge_cache_page(struct page *page)
3166 VM_BUG_ON(page_mapped(page));
3167 VM_BUG_ON(page->mapping);
3168 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE);
3172 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
3173 * In that cases, pages are freed continuously and we can expect pages
3174 * are in the same memcg. All these calls itself limits the number of
3175 * pages freed at once, then uncharge_start/end() is called properly.
3176 * This may be called prural(2) times in a context,
3179 void mem_cgroup_uncharge_start(void)
3181 current->memcg_batch.do_batch++;
3182 /* We can do nest. */
3183 if (current->memcg_batch.do_batch == 1) {
3184 current->memcg_batch.memcg = NULL;
3185 current->memcg_batch.nr_pages = 0;
3186 current->memcg_batch.memsw_nr_pages = 0;
3190 void mem_cgroup_uncharge_end(void)
3192 struct memcg_batch_info *batch = &current->memcg_batch;
3194 if (!batch->do_batch)
3195 return;
3197 batch->do_batch--;
3198 if (batch->do_batch) /* If stacked, do nothing. */
3199 return;
3201 if (!batch->memcg)
3202 return;
3204 * This "batch->memcg" is valid without any css_get/put etc...
3205 * bacause we hide charges behind us.
3207 if (batch->nr_pages)
3208 res_counter_uncharge(&batch->memcg->res,
3209 batch->nr_pages * PAGE_SIZE);
3210 if (batch->memsw_nr_pages)
3211 res_counter_uncharge(&batch->memcg->memsw,
3212 batch->memsw_nr_pages * PAGE_SIZE);
3213 memcg_oom_recover(batch->memcg);
3214 /* forget this pointer (for sanity check) */
3215 batch->memcg = NULL;
3218 #ifdef CONFIG_SWAP
3220 * called after __delete_from_swap_cache() and drop "page" account.
3221 * memcg information is recorded to swap_cgroup of "ent"
3223 void
3224 mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
3226 struct mem_cgroup *memcg;
3227 int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
3229 if (!swapout) /* this was a swap cache but the swap is unused ! */
3230 ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
3232 memcg = __mem_cgroup_uncharge_common(page, ctype);
3235 * record memcg information, if swapout && memcg != NULL,
3236 * mem_cgroup_get() was called in uncharge().
3238 if (do_swap_account && swapout && memcg)
3239 swap_cgroup_record(ent, css_id(&memcg->css));
3241 #endif
3243 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3245 * called from swap_entry_free(). remove record in swap_cgroup and
3246 * uncharge "memsw" account.
3248 void mem_cgroup_uncharge_swap(swp_entry_t ent)
3250 struct mem_cgroup *memcg;
3251 unsigned short id;
3253 if (!do_swap_account)
3254 return;
3256 id = swap_cgroup_record(ent, 0);
3257 rcu_read_lock();
3258 memcg = mem_cgroup_lookup(id);
3259 if (memcg) {
3261 * We uncharge this because swap is freed.
3262 * This memcg can be obsolete one. We avoid calling css_tryget
3264 if (!mem_cgroup_is_root(memcg))
3265 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
3266 mem_cgroup_swap_statistics(memcg, false);
3267 mem_cgroup_put(memcg);
3269 rcu_read_unlock();
3273 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3274 * @entry: swap entry to be moved
3275 * @from: mem_cgroup which the entry is moved from
3276 * @to: mem_cgroup which the entry is moved to
3277 * @need_fixup: whether we should fixup res_counters and refcounts.
3279 * It succeeds only when the swap_cgroup's record for this entry is the same
3280 * as the mem_cgroup's id of @from.
3282 * Returns 0 on success, -EINVAL on failure.
3284 * The caller must have charged to @to, IOW, called res_counter_charge() about
3285 * both res and memsw, and called css_get().
3287 static int mem_cgroup_move_swap_account(swp_entry_t entry,
3288 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
3290 unsigned short old_id, new_id;
3292 old_id = css_id(&from->css);
3293 new_id = css_id(&to->css);
3295 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
3296 mem_cgroup_swap_statistics(from, false);
3297 mem_cgroup_swap_statistics(to, true);
3299 * This function is only called from task migration context now.
3300 * It postpones res_counter and refcount handling till the end
3301 * of task migration(mem_cgroup_clear_mc()) for performance
3302 * improvement. But we cannot postpone mem_cgroup_get(to)
3303 * because if the process that has been moved to @to does
3304 * swap-in, the refcount of @to might be decreased to 0.
3306 mem_cgroup_get(to);
3307 if (need_fixup) {
3308 if (!mem_cgroup_is_root(from))
3309 res_counter_uncharge(&from->memsw, PAGE_SIZE);
3310 mem_cgroup_put(from);
3312 * we charged both to->res and to->memsw, so we should
3313 * uncharge to->res.
3315 if (!mem_cgroup_is_root(to))
3316 res_counter_uncharge(&to->res, PAGE_SIZE);
3318 return 0;
3320 return -EINVAL;
3322 #else
3323 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
3324 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
3326 return -EINVAL;
3328 #endif
3331 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
3332 * page belongs to.
3334 int mem_cgroup_prepare_migration(struct page *page,
3335 struct page *newpage, struct mem_cgroup **ptr, gfp_t gfp_mask)
3337 struct mem_cgroup *mem = NULL;
3338 struct page_cgroup *pc;
3339 enum charge_type ctype;
3340 int ret = 0;
3342 *ptr = NULL;
3344 VM_BUG_ON(PageTransHuge(page));
3345 if (mem_cgroup_disabled())
3346 return 0;
3348 pc = lookup_page_cgroup(page);
3349 lock_page_cgroup(pc);
3350 if (PageCgroupUsed(pc)) {
3351 mem = pc->mem_cgroup;
3352 css_get(&mem->css);
3354 * At migrating an anonymous page, its mapcount goes down
3355 * to 0 and uncharge() will be called. But, even if it's fully
3356 * unmapped, migration may fail and this page has to be
3357 * charged again. We set MIGRATION flag here and delay uncharge
3358 * until end_migration() is called
3360 * Corner Case Thinking
3361 * A)
3362 * When the old page was mapped as Anon and it's unmap-and-freed
3363 * while migration was ongoing.
3364 * If unmap finds the old page, uncharge() of it will be delayed
3365 * until end_migration(). If unmap finds a new page, it's
3366 * uncharged when it make mapcount to be 1->0. If unmap code
3367 * finds swap_migration_entry, the new page will not be mapped
3368 * and end_migration() will find it(mapcount==0).
3370 * B)
3371 * When the old page was mapped but migraion fails, the kernel
3372 * remaps it. A charge for it is kept by MIGRATION flag even
3373 * if mapcount goes down to 0. We can do remap successfully
3374 * without charging it again.
3376 * C)
3377 * The "old" page is under lock_page() until the end of
3378 * migration, so, the old page itself will not be swapped-out.
3379 * If the new page is swapped out before end_migraton, our
3380 * hook to usual swap-out path will catch the event.
3382 if (PageAnon(page))
3383 SetPageCgroupMigration(pc);
3385 unlock_page_cgroup(pc);
3387 * If the page is not charged at this point,
3388 * we return here.
3390 if (!mem)
3391 return 0;
3393 *ptr = mem;
3394 ret = __mem_cgroup_try_charge(NULL, gfp_mask, 1, ptr, false);
3395 css_put(&mem->css);/* drop extra refcnt */
3396 if (ret || *ptr == NULL) {
3397 if (PageAnon(page)) {
3398 lock_page_cgroup(pc);
3399 ClearPageCgroupMigration(pc);
3400 unlock_page_cgroup(pc);
3402 * The old page may be fully unmapped while we kept it.
3404 mem_cgroup_uncharge_page(page);
3406 return -ENOMEM;
3409 * We charge new page before it's used/mapped. So, even if unlock_page()
3410 * is called before end_migration, we can catch all events on this new
3411 * page. In the case new page is migrated but not remapped, new page's
3412 * mapcount will be finally 0 and we call uncharge in end_migration().
3414 pc = lookup_page_cgroup(newpage);
3415 if (PageAnon(page))
3416 ctype = MEM_CGROUP_CHARGE_TYPE_MAPPED;
3417 else if (page_is_file_cache(page))
3418 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
3419 else
3420 ctype = MEM_CGROUP_CHARGE_TYPE_SHMEM;
3421 __mem_cgroup_commit_charge(mem, page, 1, pc, ctype);
3422 return ret;
3425 /* remove redundant charge if migration failed*/
3426 void mem_cgroup_end_migration(struct mem_cgroup *mem,
3427 struct page *oldpage, struct page *newpage, bool migration_ok)
3429 struct page *used, *unused;
3430 struct page_cgroup *pc;
3432 if (!mem)
3433 return;
3434 /* blocks rmdir() */
3435 cgroup_exclude_rmdir(&mem->css);
3436 if (!migration_ok) {
3437 used = oldpage;
3438 unused = newpage;
3439 } else {
3440 used = newpage;
3441 unused = oldpage;
3444 * We disallowed uncharge of pages under migration because mapcount
3445 * of the page goes down to zero, temporarly.
3446 * Clear the flag and check the page should be charged.
3448 pc = lookup_page_cgroup(oldpage);
3449 lock_page_cgroup(pc);
3450 ClearPageCgroupMigration(pc);
3451 unlock_page_cgroup(pc);
3453 __mem_cgroup_uncharge_common(unused, MEM_CGROUP_CHARGE_TYPE_FORCE);
3456 * If a page is a file cache, radix-tree replacement is very atomic
3457 * and we can skip this check. When it was an Anon page, its mapcount
3458 * goes down to 0. But because we added MIGRATION flage, it's not
3459 * uncharged yet. There are several case but page->mapcount check
3460 * and USED bit check in mem_cgroup_uncharge_page() will do enough
3461 * check. (see prepare_charge() also)
3463 if (PageAnon(used))
3464 mem_cgroup_uncharge_page(used);
3466 * At migration, we may charge account against cgroup which has no
3467 * tasks.
3468 * So, rmdir()->pre_destroy() can be called while we do this charge.
3469 * In that case, we need to call pre_destroy() again. check it here.
3471 cgroup_release_and_wakeup_rmdir(&mem->css);
3474 #ifdef CONFIG_DEBUG_VM
3475 static struct page_cgroup *lookup_page_cgroup_used(struct page *page)
3477 struct page_cgroup *pc;
3479 pc = lookup_page_cgroup(page);
3480 if (likely(pc) && PageCgroupUsed(pc))
3481 return pc;
3482 return NULL;
3485 bool mem_cgroup_bad_page_check(struct page *page)
3487 if (mem_cgroup_disabled())
3488 return false;
3490 return lookup_page_cgroup_used(page) != NULL;
3493 void mem_cgroup_print_bad_page(struct page *page)
3495 struct page_cgroup *pc;
3497 pc = lookup_page_cgroup_used(page);
3498 if (pc) {
3499 int ret = -1;
3500 char *path;
3502 printk(KERN_ALERT "pc:%p pc->flags:%lx pc->mem_cgroup:%p",
3503 pc, pc->flags, pc->mem_cgroup);
3505 path = kmalloc(PATH_MAX, GFP_KERNEL);
3506 if (path) {
3507 rcu_read_lock();
3508 ret = cgroup_path(pc->mem_cgroup->css.cgroup,
3509 path, PATH_MAX);
3510 rcu_read_unlock();
3513 printk(KERN_CONT "(%s)\n",
3514 (ret < 0) ? "cannot get the path" : path);
3515 kfree(path);
3518 #endif
3520 static DEFINE_MUTEX(set_limit_mutex);
3522 static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
3523 unsigned long long val)
3525 int retry_count;
3526 u64 memswlimit, memlimit;
3527 int ret = 0;
3528 int children = mem_cgroup_count_children(memcg);
3529 u64 curusage, oldusage;
3530 int enlarge;
3533 * For keeping hierarchical_reclaim simple, how long we should retry
3534 * is depends on callers. We set our retry-count to be function
3535 * of # of children which we should visit in this loop.
3537 retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
3539 oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
3541 enlarge = 0;
3542 while (retry_count) {
3543 if (signal_pending(current)) {
3544 ret = -EINTR;
3545 break;
3548 * Rather than hide all in some function, I do this in
3549 * open coded manner. You see what this really does.
3550 * We have to guarantee mem->res.limit < mem->memsw.limit.
3552 mutex_lock(&set_limit_mutex);
3553 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3554 if (memswlimit < val) {
3555 ret = -EINVAL;
3556 mutex_unlock(&set_limit_mutex);
3557 break;
3560 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3561 if (memlimit < val)
3562 enlarge = 1;
3564 ret = res_counter_set_limit(&memcg->res, val);
3565 if (!ret) {
3566 if (memswlimit == val)
3567 memcg->memsw_is_minimum = true;
3568 else
3569 memcg->memsw_is_minimum = false;
3571 mutex_unlock(&set_limit_mutex);
3573 if (!ret)
3574 break;
3576 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
3577 MEM_CGROUP_RECLAIM_SHRINK,
3578 NULL);
3579 curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
3580 /* Usage is reduced ? */
3581 if (curusage >= oldusage)
3582 retry_count--;
3583 else
3584 oldusage = curusage;
3586 if (!ret && enlarge)
3587 memcg_oom_recover(memcg);
3589 return ret;
3592 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
3593 unsigned long long val)
3595 int retry_count;
3596 u64 memlimit, memswlimit, oldusage, curusage;
3597 int children = mem_cgroup_count_children(memcg);
3598 int ret = -EBUSY;
3599 int enlarge = 0;
3601 /* see mem_cgroup_resize_res_limit */
3602 retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
3603 oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
3604 while (retry_count) {
3605 if (signal_pending(current)) {
3606 ret = -EINTR;
3607 break;
3610 * Rather than hide all in some function, I do this in
3611 * open coded manner. You see what this really does.
3612 * We have to guarantee mem->res.limit < mem->memsw.limit.
3614 mutex_lock(&set_limit_mutex);
3615 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3616 if (memlimit > val) {
3617 ret = -EINVAL;
3618 mutex_unlock(&set_limit_mutex);
3619 break;
3621 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3622 if (memswlimit < val)
3623 enlarge = 1;
3624 ret = res_counter_set_limit(&memcg->memsw, val);
3625 if (!ret) {
3626 if (memlimit == val)
3627 memcg->memsw_is_minimum = true;
3628 else
3629 memcg->memsw_is_minimum = false;
3631 mutex_unlock(&set_limit_mutex);
3633 if (!ret)
3634 break;
3636 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
3637 MEM_CGROUP_RECLAIM_NOSWAP |
3638 MEM_CGROUP_RECLAIM_SHRINK,
3639 NULL);
3640 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
3641 /* Usage is reduced ? */
3642 if (curusage >= oldusage)
3643 retry_count--;
3644 else
3645 oldusage = curusage;
3647 if (!ret && enlarge)
3648 memcg_oom_recover(memcg);
3649 return ret;
3652 unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
3653 gfp_t gfp_mask,
3654 unsigned long *total_scanned)
3656 unsigned long nr_reclaimed = 0;
3657 struct mem_cgroup_per_zone *mz, *next_mz = NULL;
3658 unsigned long reclaimed;
3659 int loop = 0;
3660 struct mem_cgroup_tree_per_zone *mctz;
3661 unsigned long long excess;
3662 unsigned long nr_scanned;
3664 if (order > 0)
3665 return 0;
3667 mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone));
3669 * This loop can run a while, specially if mem_cgroup's continuously
3670 * keep exceeding their soft limit and putting the system under
3671 * pressure
3673 do {
3674 if (next_mz)
3675 mz = next_mz;
3676 else
3677 mz = mem_cgroup_largest_soft_limit_node(mctz);
3678 if (!mz)
3679 break;
3681 nr_scanned = 0;
3682 reclaimed = mem_cgroup_hierarchical_reclaim(mz->mem, zone,
3683 gfp_mask,
3684 MEM_CGROUP_RECLAIM_SOFT,
3685 &nr_scanned);
3686 nr_reclaimed += reclaimed;
3687 *total_scanned += nr_scanned;
3688 spin_lock(&mctz->lock);
3691 * If we failed to reclaim anything from this memory cgroup
3692 * it is time to move on to the next cgroup
3694 next_mz = NULL;
3695 if (!reclaimed) {
3696 do {
3698 * Loop until we find yet another one.
3700 * By the time we get the soft_limit lock
3701 * again, someone might have aded the
3702 * group back on the RB tree. Iterate to
3703 * make sure we get a different mem.
3704 * mem_cgroup_largest_soft_limit_node returns
3705 * NULL if no other cgroup is present on
3706 * the tree
3708 next_mz =
3709 __mem_cgroup_largest_soft_limit_node(mctz);
3710 if (next_mz == mz)
3711 css_put(&next_mz->mem->css);
3712 else /* next_mz == NULL or other memcg */
3713 break;
3714 } while (1);
3716 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
3717 excess = res_counter_soft_limit_excess(&mz->mem->res);
3719 * One school of thought says that we should not add
3720 * back the node to the tree if reclaim returns 0.
3721 * But our reclaim could return 0, simply because due
3722 * to priority we are exposing a smaller subset of
3723 * memory to reclaim from. Consider this as a longer
3724 * term TODO.
3726 /* If excess == 0, no tree ops */
3727 __mem_cgroup_insert_exceeded(mz->mem, mz, mctz, excess);
3728 spin_unlock(&mctz->lock);
3729 css_put(&mz->mem->css);
3730 loop++;
3732 * Could not reclaim anything and there are no more
3733 * mem cgroups to try or we seem to be looping without
3734 * reclaiming anything.
3736 if (!nr_reclaimed &&
3737 (next_mz == NULL ||
3738 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3739 break;
3740 } while (!nr_reclaimed);
3741 if (next_mz)
3742 css_put(&next_mz->mem->css);
3743 return nr_reclaimed;
3747 * This routine traverse page_cgroup in given list and drop them all.
3748 * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
3750 static int mem_cgroup_force_empty_list(struct mem_cgroup *mem,
3751 int node, int zid, enum lru_list lru)
3753 struct zone *zone;
3754 struct mem_cgroup_per_zone *mz;
3755 struct page_cgroup *pc, *busy;
3756 unsigned long flags, loop;
3757 struct list_head *list;
3758 int ret = 0;
3760 zone = &NODE_DATA(node)->node_zones[zid];
3761 mz = mem_cgroup_zoneinfo(mem, node, zid);
3762 list = &mz->lists[lru];
3764 loop = MEM_CGROUP_ZSTAT(mz, lru);
3765 /* give some margin against EBUSY etc...*/
3766 loop += 256;
3767 busy = NULL;
3768 while (loop--) {
3769 struct page *page;
3771 ret = 0;
3772 spin_lock_irqsave(&zone->lru_lock, flags);
3773 if (list_empty(list)) {
3774 spin_unlock_irqrestore(&zone->lru_lock, flags);
3775 break;
3777 pc = list_entry(list->prev, struct page_cgroup, lru);
3778 if (busy == pc) {
3779 list_move(&pc->lru, list);
3780 busy = NULL;
3781 spin_unlock_irqrestore(&zone->lru_lock, flags);
3782 continue;
3784 spin_unlock_irqrestore(&zone->lru_lock, flags);
3786 page = lookup_cgroup_page(pc);
3788 ret = mem_cgroup_move_parent(page, pc, mem, GFP_KERNEL);
3789 if (ret == -ENOMEM)
3790 break;
3792 if (ret == -EBUSY || ret == -EINVAL) {
3793 /* found lock contention or "pc" is obsolete. */
3794 busy = pc;
3795 cond_resched();
3796 } else
3797 busy = NULL;
3800 if (!ret && !list_empty(list))
3801 return -EBUSY;
3802 return ret;
3806 * make mem_cgroup's charge to be 0 if there is no task.
3807 * This enables deleting this mem_cgroup.
3809 static int mem_cgroup_force_empty(struct mem_cgroup *mem, bool free_all)
3811 int ret;
3812 int node, zid, shrink;
3813 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
3814 struct cgroup *cgrp = mem->css.cgroup;
3816 css_get(&mem->css);
3818 shrink = 0;
3819 /* should free all ? */
3820 if (free_all)
3821 goto try_to_free;
3822 move_account:
3823 do {
3824 ret = -EBUSY;
3825 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
3826 goto out;
3827 ret = -EINTR;
3828 if (signal_pending(current))
3829 goto out;
3830 /* This is for making all *used* pages to be on LRU. */
3831 lru_add_drain_all();
3832 drain_all_stock_sync(mem);
3833 ret = 0;
3834 mem_cgroup_start_move(mem);
3835 for_each_node_state(node, N_HIGH_MEMORY) {
3836 for (zid = 0; !ret && zid < MAX_NR_ZONES; zid++) {
3837 enum lru_list l;
3838 for_each_lru(l) {
3839 ret = mem_cgroup_force_empty_list(mem,
3840 node, zid, l);
3841 if (ret)
3842 break;
3845 if (ret)
3846 break;
3848 mem_cgroup_end_move(mem);
3849 memcg_oom_recover(mem);
3850 /* it seems parent cgroup doesn't have enough mem */
3851 if (ret == -ENOMEM)
3852 goto try_to_free;
3853 cond_resched();
3854 /* "ret" should also be checked to ensure all lists are empty. */
3855 } while (mem->res.usage > 0 || ret);
3856 out:
3857 css_put(&mem->css);
3858 return ret;
3860 try_to_free:
3861 /* returns EBUSY if there is a task or if we come here twice. */
3862 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children) || shrink) {
3863 ret = -EBUSY;
3864 goto out;
3866 /* we call try-to-free pages for make this cgroup empty */
3867 lru_add_drain_all();
3868 /* try to free all pages in this cgroup */
3869 shrink = 1;
3870 while (nr_retries && mem->res.usage > 0) {
3871 struct memcg_scanrecord rec;
3872 int progress;
3874 if (signal_pending(current)) {
3875 ret = -EINTR;
3876 goto out;
3878 rec.context = SCAN_BY_SHRINK;
3879 rec.mem = mem;
3880 rec.root = mem;
3881 progress = try_to_free_mem_cgroup_pages(mem, GFP_KERNEL,
3882 false, &rec);
3883 if (!progress) {
3884 nr_retries--;
3885 /* maybe some writeback is necessary */
3886 congestion_wait(BLK_RW_ASYNC, HZ/10);
3890 lru_add_drain();
3891 /* try move_account...there may be some *locked* pages. */
3892 goto move_account;
3895 int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
3897 return mem_cgroup_force_empty(mem_cgroup_from_cont(cont), true);
3901 static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
3903 return mem_cgroup_from_cont(cont)->use_hierarchy;
3906 static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
3907 u64 val)
3909 int retval = 0;
3910 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
3911 struct cgroup *parent = cont->parent;
3912 struct mem_cgroup *parent_mem = NULL;
3914 if (parent)
3915 parent_mem = mem_cgroup_from_cont(parent);
3917 cgroup_lock();
3919 * If parent's use_hierarchy is set, we can't make any modifications
3920 * in the child subtrees. If it is unset, then the change can
3921 * occur, provided the current cgroup has no children.
3923 * For the root cgroup, parent_mem is NULL, we allow value to be
3924 * set if there are no children.
3926 if ((!parent_mem || !parent_mem->use_hierarchy) &&
3927 (val == 1 || val == 0)) {
3928 if (list_empty(&cont->children))
3929 mem->use_hierarchy = val;
3930 else
3931 retval = -EBUSY;
3932 } else
3933 retval = -EINVAL;
3934 cgroup_unlock();
3936 return retval;
3940 static unsigned long mem_cgroup_recursive_stat(struct mem_cgroup *mem,
3941 enum mem_cgroup_stat_index idx)
3943 struct mem_cgroup *iter;
3944 long val = 0;
3946 /* Per-cpu values can be negative, use a signed accumulator */
3947 for_each_mem_cgroup_tree(iter, mem)
3948 val += mem_cgroup_read_stat(iter, idx);
3950 if (val < 0) /* race ? */
3951 val = 0;
3952 return val;
3955 static inline u64 mem_cgroup_usage(struct mem_cgroup *mem, bool swap)
3957 u64 val;
3959 if (!mem_cgroup_is_root(mem)) {
3960 if (!swap)
3961 return res_counter_read_u64(&mem->res, RES_USAGE);
3962 else
3963 return res_counter_read_u64(&mem->memsw, RES_USAGE);
3966 val = mem_cgroup_recursive_stat(mem, MEM_CGROUP_STAT_CACHE);
3967 val += mem_cgroup_recursive_stat(mem, MEM_CGROUP_STAT_RSS);
3969 if (swap)
3970 val += mem_cgroup_recursive_stat(mem, MEM_CGROUP_STAT_SWAPOUT);
3972 return val << PAGE_SHIFT;
3975 static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft)
3977 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
3978 u64 val;
3979 int type, name;
3981 type = MEMFILE_TYPE(cft->private);
3982 name = MEMFILE_ATTR(cft->private);
3983 switch (type) {
3984 case _MEM:
3985 if (name == RES_USAGE)
3986 val = mem_cgroup_usage(mem, false);
3987 else
3988 val = res_counter_read_u64(&mem->res, name);
3989 break;
3990 case _MEMSWAP:
3991 if (name == RES_USAGE)
3992 val = mem_cgroup_usage(mem, true);
3993 else
3994 val = res_counter_read_u64(&mem->memsw, name);
3995 break;
3996 default:
3997 BUG();
3998 break;
4000 return val;
4003 * The user of this function is...
4004 * RES_LIMIT.
4006 static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
4007 const char *buffer)
4009 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
4010 int type, name;
4011 unsigned long long val;
4012 int ret;
4014 type = MEMFILE_TYPE(cft->private);
4015 name = MEMFILE_ATTR(cft->private);
4016 switch (name) {
4017 case RES_LIMIT:
4018 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
4019 ret = -EINVAL;
4020 break;
4022 /* This function does all necessary parse...reuse it */
4023 ret = res_counter_memparse_write_strategy(buffer, &val);
4024 if (ret)
4025 break;
4026 if (type == _MEM)
4027 ret = mem_cgroup_resize_limit(memcg, val);
4028 else
4029 ret = mem_cgroup_resize_memsw_limit(memcg, val);
4030 break;
4031 case RES_SOFT_LIMIT:
4032 ret = res_counter_memparse_write_strategy(buffer, &val);
4033 if (ret)
4034 break;
4036 * For memsw, soft limits are hard to implement in terms
4037 * of semantics, for now, we support soft limits for
4038 * control without swap
4040 if (type == _MEM)
4041 ret = res_counter_set_soft_limit(&memcg->res, val);
4042 else
4043 ret = -EINVAL;
4044 break;
4045 default:
4046 ret = -EINVAL; /* should be BUG() ? */
4047 break;
4049 return ret;
4052 static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
4053 unsigned long long *mem_limit, unsigned long long *memsw_limit)
4055 struct cgroup *cgroup;
4056 unsigned long long min_limit, min_memsw_limit, tmp;
4058 min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
4059 min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
4060 cgroup = memcg->css.cgroup;
4061 if (!memcg->use_hierarchy)
4062 goto out;
4064 while (cgroup->parent) {
4065 cgroup = cgroup->parent;
4066 memcg = mem_cgroup_from_cont(cgroup);
4067 if (!memcg->use_hierarchy)
4068 break;
4069 tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
4070 min_limit = min(min_limit, tmp);
4071 tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
4072 min_memsw_limit = min(min_memsw_limit, tmp);
4074 out:
4075 *mem_limit = min_limit;
4076 *memsw_limit = min_memsw_limit;
4077 return;
4080 static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
4082 struct mem_cgroup *mem;
4083 int type, name;
4085 mem = mem_cgroup_from_cont(cont);
4086 type = MEMFILE_TYPE(event);
4087 name = MEMFILE_ATTR(event);
4088 switch (name) {
4089 case RES_MAX_USAGE:
4090 if (type == _MEM)
4091 res_counter_reset_max(&mem->res);
4092 else
4093 res_counter_reset_max(&mem->memsw);
4094 break;
4095 case RES_FAILCNT:
4096 if (type == _MEM)
4097 res_counter_reset_failcnt(&mem->res);
4098 else
4099 res_counter_reset_failcnt(&mem->memsw);
4100 break;
4103 return 0;
4106 static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp,
4107 struct cftype *cft)
4109 return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate;
4112 #ifdef CONFIG_MMU
4113 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
4114 struct cftype *cft, u64 val)
4116 struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
4118 if (val >= (1 << NR_MOVE_TYPE))
4119 return -EINVAL;
4121 * We check this value several times in both in can_attach() and
4122 * attach(), so we need cgroup lock to prevent this value from being
4123 * inconsistent.
4125 cgroup_lock();
4126 mem->move_charge_at_immigrate = val;
4127 cgroup_unlock();
4129 return 0;
4131 #else
4132 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
4133 struct cftype *cft, u64 val)
4135 return -ENOSYS;
4137 #endif
4140 /* For read statistics */
4141 enum {
4142 MCS_CACHE,
4143 MCS_RSS,
4144 MCS_FILE_MAPPED,
4145 MCS_PGPGIN,
4146 MCS_PGPGOUT,
4147 MCS_SWAP,
4148 MCS_PGFAULT,
4149 MCS_PGMAJFAULT,
4150 MCS_INACTIVE_ANON,
4151 MCS_ACTIVE_ANON,
4152 MCS_INACTIVE_FILE,
4153 MCS_ACTIVE_FILE,
4154 MCS_UNEVICTABLE,
4155 NR_MCS_STAT,
4158 struct mcs_total_stat {
4159 s64 stat[NR_MCS_STAT];
4162 struct {
4163 char *local_name;
4164 char *total_name;
4165 } memcg_stat_strings[NR_MCS_STAT] = {
4166 {"cache", "total_cache"},
4167 {"rss", "total_rss"},
4168 {"mapped_file", "total_mapped_file"},
4169 {"pgpgin", "total_pgpgin"},
4170 {"pgpgout", "total_pgpgout"},
4171 {"swap", "total_swap"},
4172 {"pgfault", "total_pgfault"},
4173 {"pgmajfault", "total_pgmajfault"},
4174 {"inactive_anon", "total_inactive_anon"},
4175 {"active_anon", "total_active_anon"},
4176 {"inactive_file", "total_inactive_file"},
4177 {"active_file", "total_active_file"},
4178 {"unevictable", "total_unevictable"}
4182 static void
4183 mem_cgroup_get_local_stat(struct mem_cgroup *mem, struct mcs_total_stat *s)
4185 s64 val;
4187 /* per cpu stat */
4188 val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_CACHE);
4189 s->stat[MCS_CACHE] += val * PAGE_SIZE;
4190 val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_RSS);
4191 s->stat[MCS_RSS] += val * PAGE_SIZE;
4192 val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_FILE_MAPPED);
4193 s->stat[MCS_FILE_MAPPED] += val * PAGE_SIZE;
4194 val = mem_cgroup_read_events(mem, MEM_CGROUP_EVENTS_PGPGIN);
4195 s->stat[MCS_PGPGIN] += val;
4196 val = mem_cgroup_read_events(mem, MEM_CGROUP_EVENTS_PGPGOUT);
4197 s->stat[MCS_PGPGOUT] += val;
4198 if (do_swap_account) {
4199 val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_SWAPOUT);
4200 s->stat[MCS_SWAP] += val * PAGE_SIZE;
4202 val = mem_cgroup_read_events(mem, MEM_CGROUP_EVENTS_PGFAULT);
4203 s->stat[MCS_PGFAULT] += val;
4204 val = mem_cgroup_read_events(mem, MEM_CGROUP_EVENTS_PGMAJFAULT);
4205 s->stat[MCS_PGMAJFAULT] += val;
4207 /* per zone stat */
4208 val = mem_cgroup_nr_lru_pages(mem, BIT(LRU_INACTIVE_ANON));
4209 s->stat[MCS_INACTIVE_ANON] += val * PAGE_SIZE;
4210 val = mem_cgroup_nr_lru_pages(mem, BIT(LRU_ACTIVE_ANON));
4211 s->stat[MCS_ACTIVE_ANON] += val * PAGE_SIZE;
4212 val = mem_cgroup_nr_lru_pages(mem, BIT(LRU_INACTIVE_FILE));
4213 s->stat[MCS_INACTIVE_FILE] += val * PAGE_SIZE;
4214 val = mem_cgroup_nr_lru_pages(mem, BIT(LRU_ACTIVE_FILE));
4215 s->stat[MCS_ACTIVE_FILE] += val * PAGE_SIZE;
4216 val = mem_cgroup_nr_lru_pages(mem, BIT(LRU_UNEVICTABLE));
4217 s->stat[MCS_UNEVICTABLE] += val * PAGE_SIZE;
4220 static void
4221 mem_cgroup_get_total_stat(struct mem_cgroup *mem, struct mcs_total_stat *s)
4223 struct mem_cgroup *iter;
4225 for_each_mem_cgroup_tree(iter, mem)
4226 mem_cgroup_get_local_stat(iter, s);
4229 #ifdef CONFIG_NUMA
4230 static int mem_control_numa_stat_show(struct seq_file *m, void *arg)
4232 int nid;
4233 unsigned long total_nr, file_nr, anon_nr, unevictable_nr;
4234 unsigned long node_nr;
4235 struct cgroup *cont = m->private;
4236 struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
4238 total_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL);
4239 seq_printf(m, "total=%lu", total_nr);
4240 for_each_node_state(nid, N_HIGH_MEMORY) {
4241 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid, LRU_ALL);
4242 seq_printf(m, " N%d=%lu", nid, node_nr);
4244 seq_putc(m, '\n');
4246 file_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL_FILE);
4247 seq_printf(m, "file=%lu", file_nr);
4248 for_each_node_state(nid, N_HIGH_MEMORY) {
4249 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4250 LRU_ALL_FILE);
4251 seq_printf(m, " N%d=%lu", nid, node_nr);
4253 seq_putc(m, '\n');
4255 anon_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL_ANON);
4256 seq_printf(m, "anon=%lu", anon_nr);
4257 for_each_node_state(nid, N_HIGH_MEMORY) {
4258 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4259 LRU_ALL_ANON);
4260 seq_printf(m, " N%d=%lu", nid, node_nr);
4262 seq_putc(m, '\n');
4264 unevictable_nr = mem_cgroup_nr_lru_pages(mem_cont, BIT(LRU_UNEVICTABLE));
4265 seq_printf(m, "unevictable=%lu", unevictable_nr);
4266 for_each_node_state(nid, N_HIGH_MEMORY) {
4267 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4268 BIT(LRU_UNEVICTABLE));
4269 seq_printf(m, " N%d=%lu", nid, node_nr);
4271 seq_putc(m, '\n');
4272 return 0;
4274 #endif /* CONFIG_NUMA */
4276 static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft,
4277 struct cgroup_map_cb *cb)
4279 struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
4280 struct mcs_total_stat mystat;
4281 int i;
4283 memset(&mystat, 0, sizeof(mystat));
4284 mem_cgroup_get_local_stat(mem_cont, &mystat);
4287 for (i = 0; i < NR_MCS_STAT; i++) {
4288 if (i == MCS_SWAP && !do_swap_account)
4289 continue;
4290 cb->fill(cb, memcg_stat_strings[i].local_name, mystat.stat[i]);
4293 /* Hierarchical information */
4295 unsigned long long limit, memsw_limit;
4296 memcg_get_hierarchical_limit(mem_cont, &limit, &memsw_limit);
4297 cb->fill(cb, "hierarchical_memory_limit", limit);
4298 if (do_swap_account)
4299 cb->fill(cb, "hierarchical_memsw_limit", memsw_limit);
4302 memset(&mystat, 0, sizeof(mystat));
4303 mem_cgroup_get_total_stat(mem_cont, &mystat);
4304 for (i = 0; i < NR_MCS_STAT; i++) {
4305 if (i == MCS_SWAP && !do_swap_account)
4306 continue;
4307 cb->fill(cb, memcg_stat_strings[i].total_name, mystat.stat[i]);
4310 #ifdef CONFIG_DEBUG_VM
4311 cb->fill(cb, "inactive_ratio", calc_inactive_ratio(mem_cont, NULL));
4314 int nid, zid;
4315 struct mem_cgroup_per_zone *mz;
4316 unsigned long recent_rotated[2] = {0, 0};
4317 unsigned long recent_scanned[2] = {0, 0};
4319 for_each_online_node(nid)
4320 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
4321 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
4323 recent_rotated[0] +=
4324 mz->reclaim_stat.recent_rotated[0];
4325 recent_rotated[1] +=
4326 mz->reclaim_stat.recent_rotated[1];
4327 recent_scanned[0] +=
4328 mz->reclaim_stat.recent_scanned[0];
4329 recent_scanned[1] +=
4330 mz->reclaim_stat.recent_scanned[1];
4332 cb->fill(cb, "recent_rotated_anon", recent_rotated[0]);
4333 cb->fill(cb, "recent_rotated_file", recent_rotated[1]);
4334 cb->fill(cb, "recent_scanned_anon", recent_scanned[0]);
4335 cb->fill(cb, "recent_scanned_file", recent_scanned[1]);
4337 #endif
4339 return 0;
4342 static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
4344 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4346 return mem_cgroup_swappiness(memcg);
4349 static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
4350 u64 val)
4352 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4353 struct mem_cgroup *parent;
4355 if (val > 100)
4356 return -EINVAL;
4358 if (cgrp->parent == NULL)
4359 return -EINVAL;
4361 parent = mem_cgroup_from_cont(cgrp->parent);
4363 cgroup_lock();
4365 /* If under hierarchy, only empty-root can set this value */
4366 if ((parent->use_hierarchy) ||
4367 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
4368 cgroup_unlock();
4369 return -EINVAL;
4372 memcg->swappiness = val;
4374 cgroup_unlock();
4376 return 0;
4379 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4381 struct mem_cgroup_threshold_ary *t;
4382 u64 usage;
4383 int i;
4385 rcu_read_lock();
4386 if (!swap)
4387 t = rcu_dereference(memcg->thresholds.primary);
4388 else
4389 t = rcu_dereference(memcg->memsw_thresholds.primary);
4391 if (!t)
4392 goto unlock;
4394 usage = mem_cgroup_usage(memcg, swap);
4397 * current_threshold points to threshold just below usage.
4398 * If it's not true, a threshold was crossed after last
4399 * call of __mem_cgroup_threshold().
4401 i = t->current_threshold;
4404 * Iterate backward over array of thresholds starting from
4405 * current_threshold and check if a threshold is crossed.
4406 * If none of thresholds below usage is crossed, we read
4407 * only one element of the array here.
4409 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4410 eventfd_signal(t->entries[i].eventfd, 1);
4412 /* i = current_threshold + 1 */
4413 i++;
4416 * Iterate forward over array of thresholds starting from
4417 * current_threshold+1 and check if a threshold is crossed.
4418 * If none of thresholds above usage is crossed, we read
4419 * only one element of the array here.
4421 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4422 eventfd_signal(t->entries[i].eventfd, 1);
4424 /* Update current_threshold */
4425 t->current_threshold = i - 1;
4426 unlock:
4427 rcu_read_unlock();
4430 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4432 while (memcg) {
4433 __mem_cgroup_threshold(memcg, false);
4434 if (do_swap_account)
4435 __mem_cgroup_threshold(memcg, true);
4437 memcg = parent_mem_cgroup(memcg);
4441 static int compare_thresholds(const void *a, const void *b)
4443 const struct mem_cgroup_threshold *_a = a;
4444 const struct mem_cgroup_threshold *_b = b;
4446 return _a->threshold - _b->threshold;
4449 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *mem)
4451 struct mem_cgroup_eventfd_list *ev;
4453 list_for_each_entry(ev, &mem->oom_notify, list)
4454 eventfd_signal(ev->eventfd, 1);
4455 return 0;
4458 static void mem_cgroup_oom_notify(struct mem_cgroup *mem)
4460 struct mem_cgroup *iter;
4462 for_each_mem_cgroup_tree(iter, mem)
4463 mem_cgroup_oom_notify_cb(iter);
4466 static int mem_cgroup_usage_register_event(struct cgroup *cgrp,
4467 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
4469 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4470 struct mem_cgroup_thresholds *thresholds;
4471 struct mem_cgroup_threshold_ary *new;
4472 int type = MEMFILE_TYPE(cft->private);
4473 u64 threshold, usage;
4474 int i, size, ret;
4476 ret = res_counter_memparse_write_strategy(args, &threshold);
4477 if (ret)
4478 return ret;
4480 mutex_lock(&memcg->thresholds_lock);
4482 if (type == _MEM)
4483 thresholds = &memcg->thresholds;
4484 else if (type == _MEMSWAP)
4485 thresholds = &memcg->memsw_thresholds;
4486 else
4487 BUG();
4489 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
4491 /* Check if a threshold crossed before adding a new one */
4492 if (thresholds->primary)
4493 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4495 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
4497 /* Allocate memory for new array of thresholds */
4498 new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
4499 GFP_KERNEL);
4500 if (!new) {
4501 ret = -ENOMEM;
4502 goto unlock;
4504 new->size = size;
4506 /* Copy thresholds (if any) to new array */
4507 if (thresholds->primary) {
4508 memcpy(new->entries, thresholds->primary->entries, (size - 1) *
4509 sizeof(struct mem_cgroup_threshold));
4512 /* Add new threshold */
4513 new->entries[size - 1].eventfd = eventfd;
4514 new->entries[size - 1].threshold = threshold;
4516 /* Sort thresholds. Registering of new threshold isn't time-critical */
4517 sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
4518 compare_thresholds, NULL);
4520 /* Find current threshold */
4521 new->current_threshold = -1;
4522 for (i = 0; i < size; i++) {
4523 if (new->entries[i].threshold < usage) {
4525 * new->current_threshold will not be used until
4526 * rcu_assign_pointer(), so it's safe to increment
4527 * it here.
4529 ++new->current_threshold;
4533 /* Free old spare buffer and save old primary buffer as spare */
4534 kfree(thresholds->spare);
4535 thresholds->spare = thresholds->primary;
4537 rcu_assign_pointer(thresholds->primary, new);
4539 /* To be sure that nobody uses thresholds */
4540 synchronize_rcu();
4542 unlock:
4543 mutex_unlock(&memcg->thresholds_lock);
4545 return ret;
4548 static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,
4549 struct cftype *cft, struct eventfd_ctx *eventfd)
4551 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4552 struct mem_cgroup_thresholds *thresholds;
4553 struct mem_cgroup_threshold_ary *new;
4554 int type = MEMFILE_TYPE(cft->private);
4555 u64 usage;
4556 int i, j, size;
4558 mutex_lock(&memcg->thresholds_lock);
4559 if (type == _MEM)
4560 thresholds = &memcg->thresholds;
4561 else if (type == _MEMSWAP)
4562 thresholds = &memcg->memsw_thresholds;
4563 else
4564 BUG();
4567 * Something went wrong if we trying to unregister a threshold
4568 * if we don't have thresholds
4570 BUG_ON(!thresholds);
4572 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
4574 /* Check if a threshold crossed before removing */
4575 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4577 /* Calculate new number of threshold */
4578 size = 0;
4579 for (i = 0; i < thresholds->primary->size; i++) {
4580 if (thresholds->primary->entries[i].eventfd != eventfd)
4581 size++;
4584 new = thresholds->spare;
4586 /* Set thresholds array to NULL if we don't have thresholds */
4587 if (!size) {
4588 kfree(new);
4589 new = NULL;
4590 goto swap_buffers;
4593 new->size = size;
4595 /* Copy thresholds and find current threshold */
4596 new->current_threshold = -1;
4597 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4598 if (thresholds->primary->entries[i].eventfd == eventfd)
4599 continue;
4601 new->entries[j] = thresholds->primary->entries[i];
4602 if (new->entries[j].threshold < usage) {
4604 * new->current_threshold will not be used
4605 * until rcu_assign_pointer(), so it's safe to increment
4606 * it here.
4608 ++new->current_threshold;
4610 j++;
4613 swap_buffers:
4614 /* Swap primary and spare array */
4615 thresholds->spare = thresholds->primary;
4616 rcu_assign_pointer(thresholds->primary, new);
4618 /* To be sure that nobody uses thresholds */
4619 synchronize_rcu();
4621 mutex_unlock(&memcg->thresholds_lock);
4624 static int mem_cgroup_oom_register_event(struct cgroup *cgrp,
4625 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
4627 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4628 struct mem_cgroup_eventfd_list *event;
4629 int type = MEMFILE_TYPE(cft->private);
4631 BUG_ON(type != _OOM_TYPE);
4632 event = kmalloc(sizeof(*event), GFP_KERNEL);
4633 if (!event)
4634 return -ENOMEM;
4636 spin_lock(&memcg_oom_lock);
4638 event->eventfd = eventfd;
4639 list_add(&event->list, &memcg->oom_notify);
4641 /* already in OOM ? */
4642 if (atomic_read(&memcg->under_oom))
4643 eventfd_signal(eventfd, 1);
4644 spin_unlock(&memcg_oom_lock);
4646 return 0;
4649 static void mem_cgroup_oom_unregister_event(struct cgroup *cgrp,
4650 struct cftype *cft, struct eventfd_ctx *eventfd)
4652 struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
4653 struct mem_cgroup_eventfd_list *ev, *tmp;
4654 int type = MEMFILE_TYPE(cft->private);
4656 BUG_ON(type != _OOM_TYPE);
4658 spin_lock(&memcg_oom_lock);
4660 list_for_each_entry_safe(ev, tmp, &mem->oom_notify, list) {
4661 if (ev->eventfd == eventfd) {
4662 list_del(&ev->list);
4663 kfree(ev);
4667 spin_unlock(&memcg_oom_lock);
4670 static int mem_cgroup_oom_control_read(struct cgroup *cgrp,
4671 struct cftype *cft, struct cgroup_map_cb *cb)
4673 struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
4675 cb->fill(cb, "oom_kill_disable", mem->oom_kill_disable);
4677 if (atomic_read(&mem->under_oom))
4678 cb->fill(cb, "under_oom", 1);
4679 else
4680 cb->fill(cb, "under_oom", 0);
4681 return 0;
4684 static int mem_cgroup_oom_control_write(struct cgroup *cgrp,
4685 struct cftype *cft, u64 val)
4687 struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
4688 struct mem_cgroup *parent;
4690 /* cannot set to root cgroup and only 0 and 1 are allowed */
4691 if (!cgrp->parent || !((val == 0) || (val == 1)))
4692 return -EINVAL;
4694 parent = mem_cgroup_from_cont(cgrp->parent);
4696 cgroup_lock();
4697 /* oom-kill-disable is a flag for subhierarchy. */
4698 if ((parent->use_hierarchy) ||
4699 (mem->use_hierarchy && !list_empty(&cgrp->children))) {
4700 cgroup_unlock();
4701 return -EINVAL;
4703 mem->oom_kill_disable = val;
4704 if (!val)
4705 memcg_oom_recover(mem);
4706 cgroup_unlock();
4707 return 0;
4710 #ifdef CONFIG_NUMA
4711 static const struct file_operations mem_control_numa_stat_file_operations = {
4712 .read = seq_read,
4713 .llseek = seq_lseek,
4714 .release = single_release,
4717 static int mem_control_numa_stat_open(struct inode *unused, struct file *file)
4719 struct cgroup *cont = file->f_dentry->d_parent->d_fsdata;
4721 file->f_op = &mem_control_numa_stat_file_operations;
4722 return single_open(file, mem_control_numa_stat_show, cont);
4724 #endif /* CONFIG_NUMA */
4726 static int mem_cgroup_vmscan_stat_read(struct cgroup *cgrp,
4727 struct cftype *cft,
4728 struct cgroup_map_cb *cb)
4730 struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
4731 char string[64];
4732 int i;
4734 for (i = 0; i < NR_SCANSTATS; i++) {
4735 strcpy(string, scanstat_string[i]);
4736 strcat(string, SCANSTAT_WORD_LIMIT);
4737 cb->fill(cb, string, mem->scanstat.stats[SCAN_BY_LIMIT][i]);
4740 for (i = 0; i < NR_SCANSTATS; i++) {
4741 strcpy(string, scanstat_string[i]);
4742 strcat(string, SCANSTAT_WORD_SYSTEM);
4743 cb->fill(cb, string, mem->scanstat.stats[SCAN_BY_SYSTEM][i]);
4746 for (i = 0; i < NR_SCANSTATS; i++) {
4747 strcpy(string, scanstat_string[i]);
4748 strcat(string, SCANSTAT_WORD_LIMIT);
4749 strcat(string, SCANSTAT_WORD_HIERARCHY);
4750 cb->fill(cb, string, mem->scanstat.rootstats[SCAN_BY_LIMIT][i]);
4752 for (i = 0; i < NR_SCANSTATS; i++) {
4753 strcpy(string, scanstat_string[i]);
4754 strcat(string, SCANSTAT_WORD_SYSTEM);
4755 strcat(string, SCANSTAT_WORD_HIERARCHY);
4756 cb->fill(cb, string, mem->scanstat.rootstats[SCAN_BY_SYSTEM][i]);
4758 return 0;
4761 static int mem_cgroup_reset_vmscan_stat(struct cgroup *cgrp,
4762 unsigned int event)
4764 struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
4766 spin_lock(&mem->scanstat.lock);
4767 memset(&mem->scanstat.stats, 0, sizeof(mem->scanstat.stats));
4768 memset(&mem->scanstat.rootstats, 0, sizeof(mem->scanstat.rootstats));
4769 spin_unlock(&mem->scanstat.lock);
4770 return 0;
4774 static struct cftype mem_cgroup_files[] = {
4776 .name = "usage_in_bytes",
4777 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
4778 .read_u64 = mem_cgroup_read,
4779 .register_event = mem_cgroup_usage_register_event,
4780 .unregister_event = mem_cgroup_usage_unregister_event,
4783 .name = "max_usage_in_bytes",
4784 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
4785 .trigger = mem_cgroup_reset,
4786 .read_u64 = mem_cgroup_read,
4789 .name = "limit_in_bytes",
4790 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
4791 .write_string = mem_cgroup_write,
4792 .read_u64 = mem_cgroup_read,
4795 .name = "soft_limit_in_bytes",
4796 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
4797 .write_string = mem_cgroup_write,
4798 .read_u64 = mem_cgroup_read,
4801 .name = "failcnt",
4802 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
4803 .trigger = mem_cgroup_reset,
4804 .read_u64 = mem_cgroup_read,
4807 .name = "stat",
4808 .read_map = mem_control_stat_show,
4811 .name = "force_empty",
4812 .trigger = mem_cgroup_force_empty_write,
4815 .name = "use_hierarchy",
4816 .write_u64 = mem_cgroup_hierarchy_write,
4817 .read_u64 = mem_cgroup_hierarchy_read,
4820 .name = "swappiness",
4821 .read_u64 = mem_cgroup_swappiness_read,
4822 .write_u64 = mem_cgroup_swappiness_write,
4825 .name = "move_charge_at_immigrate",
4826 .read_u64 = mem_cgroup_move_charge_read,
4827 .write_u64 = mem_cgroup_move_charge_write,
4830 .name = "oom_control",
4831 .read_map = mem_cgroup_oom_control_read,
4832 .write_u64 = mem_cgroup_oom_control_write,
4833 .register_event = mem_cgroup_oom_register_event,
4834 .unregister_event = mem_cgroup_oom_unregister_event,
4835 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
4837 #ifdef CONFIG_NUMA
4839 .name = "numa_stat",
4840 .open = mem_control_numa_stat_open,
4841 .mode = S_IRUGO,
4843 #endif
4845 .name = "vmscan_stat",
4846 .read_map = mem_cgroup_vmscan_stat_read,
4847 .trigger = mem_cgroup_reset_vmscan_stat,
4851 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4852 static struct cftype memsw_cgroup_files[] = {
4854 .name = "memsw.usage_in_bytes",
4855 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
4856 .read_u64 = mem_cgroup_read,
4857 .register_event = mem_cgroup_usage_register_event,
4858 .unregister_event = mem_cgroup_usage_unregister_event,
4861 .name = "memsw.max_usage_in_bytes",
4862 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
4863 .trigger = mem_cgroup_reset,
4864 .read_u64 = mem_cgroup_read,
4867 .name = "memsw.limit_in_bytes",
4868 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
4869 .write_string = mem_cgroup_write,
4870 .read_u64 = mem_cgroup_read,
4873 .name = "memsw.failcnt",
4874 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
4875 .trigger = mem_cgroup_reset,
4876 .read_u64 = mem_cgroup_read,
4880 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
4882 if (!do_swap_account)
4883 return 0;
4884 return cgroup_add_files(cont, ss, memsw_cgroup_files,
4885 ARRAY_SIZE(memsw_cgroup_files));
4887 #else
4888 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
4890 return 0;
4892 #endif
4894 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
4896 struct mem_cgroup_per_node *pn;
4897 struct mem_cgroup_per_zone *mz;
4898 enum lru_list l;
4899 int zone, tmp = node;
4901 * This routine is called against possible nodes.
4902 * But it's BUG to call kmalloc() against offline node.
4904 * TODO: this routine can waste much memory for nodes which will
4905 * never be onlined. It's better to use memory hotplug callback
4906 * function.
4908 if (!node_state(node, N_NORMAL_MEMORY))
4909 tmp = -1;
4910 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
4911 if (!pn)
4912 return 1;
4914 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4915 mz = &pn->zoneinfo[zone];
4916 for_each_lru(l)
4917 INIT_LIST_HEAD(&mz->lists[l]);
4918 mz->usage_in_excess = 0;
4919 mz->on_tree = false;
4920 mz->mem = mem;
4922 mem->info.nodeinfo[node] = pn;
4923 return 0;
4926 static void free_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
4928 kfree(mem->info.nodeinfo[node]);
4931 static struct mem_cgroup *mem_cgroup_alloc(void)
4933 struct mem_cgroup *mem;
4934 int size = sizeof(struct mem_cgroup);
4936 /* Can be very big if MAX_NUMNODES is very big */
4937 if (size < PAGE_SIZE)
4938 mem = kzalloc(size, GFP_KERNEL);
4939 else
4940 mem = vzalloc(size);
4942 if (!mem)
4943 return NULL;
4945 mem->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
4946 if (!mem->stat)
4947 goto out_free;
4948 spin_lock_init(&mem->pcp_counter_lock);
4949 return mem;
4951 out_free:
4952 if (size < PAGE_SIZE)
4953 kfree(mem);
4954 else
4955 vfree(mem);
4956 return NULL;
4960 * At destroying mem_cgroup, references from swap_cgroup can remain.
4961 * (scanning all at force_empty is too costly...)
4963 * Instead of clearing all references at force_empty, we remember
4964 * the number of reference from swap_cgroup and free mem_cgroup when
4965 * it goes down to 0.
4967 * Removal of cgroup itself succeeds regardless of refs from swap.
4970 static void __mem_cgroup_free(struct mem_cgroup *mem)
4972 int node;
4974 mem_cgroup_remove_from_trees(mem);
4975 free_css_id(&mem_cgroup_subsys, &mem->css);
4977 for_each_node_state(node, N_POSSIBLE)
4978 free_mem_cgroup_per_zone_info(mem, node);
4980 free_percpu(mem->stat);
4981 if (sizeof(struct mem_cgroup) < PAGE_SIZE)
4982 kfree(mem);
4983 else
4984 vfree(mem);
4987 static void mem_cgroup_get(struct mem_cgroup *mem)
4989 atomic_inc(&mem->refcnt);
4992 static void __mem_cgroup_put(struct mem_cgroup *mem, int count)
4994 if (atomic_sub_and_test(count, &mem->refcnt)) {
4995 struct mem_cgroup *parent = parent_mem_cgroup(mem);
4996 __mem_cgroup_free(mem);
4997 if (parent)
4998 mem_cgroup_put(parent);
5002 static void mem_cgroup_put(struct mem_cgroup *mem)
5004 __mem_cgroup_put(mem, 1);
5008 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
5010 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem)
5012 if (!mem->res.parent)
5013 return NULL;
5014 return mem_cgroup_from_res_counter(mem->res.parent, res);
5017 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
5018 static void __init enable_swap_cgroup(void)
5020 if (!mem_cgroup_disabled() && really_do_swap_account)
5021 do_swap_account = 1;
5023 #else
5024 static void __init enable_swap_cgroup(void)
5027 #endif
5029 static int mem_cgroup_soft_limit_tree_init(void)
5031 struct mem_cgroup_tree_per_node *rtpn;
5032 struct mem_cgroup_tree_per_zone *rtpz;
5033 int tmp, node, zone;
5035 for_each_node_state(node, N_POSSIBLE) {
5036 tmp = node;
5037 if (!node_state(node, N_NORMAL_MEMORY))
5038 tmp = -1;
5039 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
5040 if (!rtpn)
5041 return 1;
5043 soft_limit_tree.rb_tree_per_node[node] = rtpn;
5045 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
5046 rtpz = &rtpn->rb_tree_per_zone[zone];
5047 rtpz->rb_root = RB_ROOT;
5048 spin_lock_init(&rtpz->lock);
5051 return 0;
5054 static struct cgroup_subsys_state * __ref
5055 mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
5057 struct mem_cgroup *mem, *parent;
5058 long error = -ENOMEM;
5059 int node;
5061 mem = mem_cgroup_alloc();
5062 if (!mem)
5063 return ERR_PTR(error);
5065 for_each_node_state(node, N_POSSIBLE)
5066 if (alloc_mem_cgroup_per_zone_info(mem, node))
5067 goto free_out;
5069 /* root ? */
5070 if (cont->parent == NULL) {
5071 int cpu;
5072 enable_swap_cgroup();
5073 parent = NULL;
5074 root_mem_cgroup = mem;
5075 if (mem_cgroup_soft_limit_tree_init())
5076 goto free_out;
5077 for_each_possible_cpu(cpu) {
5078 struct memcg_stock_pcp *stock =
5079 &per_cpu(memcg_stock, cpu);
5080 INIT_WORK(&stock->work, drain_local_stock);
5082 hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
5083 } else {
5084 parent = mem_cgroup_from_cont(cont->parent);
5085 mem->use_hierarchy = parent->use_hierarchy;
5086 mem->oom_kill_disable = parent->oom_kill_disable;
5089 if (parent && parent->use_hierarchy) {
5090 res_counter_init(&mem->res, &parent->res);
5091 res_counter_init(&mem->memsw, &parent->memsw);
5093 * We increment refcnt of the parent to ensure that we can
5094 * safely access it on res_counter_charge/uncharge.
5095 * This refcnt will be decremented when freeing this
5096 * mem_cgroup(see mem_cgroup_put).
5098 mem_cgroup_get(parent);
5099 } else {
5100 res_counter_init(&mem->res, NULL);
5101 res_counter_init(&mem->memsw, NULL);
5103 mem->last_scanned_child = 0;
5104 mem->last_scanned_node = MAX_NUMNODES;
5105 INIT_LIST_HEAD(&mem->oom_notify);
5107 if (parent)
5108 mem->swappiness = mem_cgroup_swappiness(parent);
5109 atomic_set(&mem->refcnt, 1);
5110 mem->move_charge_at_immigrate = 0;
5111 mutex_init(&mem->thresholds_lock);
5112 spin_lock_init(&mem->scanstat.lock);
5113 return &mem->css;
5114 free_out:
5115 __mem_cgroup_free(mem);
5116 root_mem_cgroup = NULL;
5117 return ERR_PTR(error);
5120 static int mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
5121 struct cgroup *cont)
5123 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
5125 return mem_cgroup_force_empty(mem, false);
5128 static void mem_cgroup_destroy(struct cgroup_subsys *ss,
5129 struct cgroup *cont)
5131 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
5133 mem_cgroup_put(mem);
5136 static int mem_cgroup_populate(struct cgroup_subsys *ss,
5137 struct cgroup *cont)
5139 int ret;
5141 ret = cgroup_add_files(cont, ss, mem_cgroup_files,
5142 ARRAY_SIZE(mem_cgroup_files));
5144 if (!ret)
5145 ret = register_memsw_files(cont, ss);
5146 return ret;
5149 #ifdef CONFIG_MMU
5150 /* Handlers for move charge at task migration. */
5151 #define PRECHARGE_COUNT_AT_ONCE 256
5152 static int mem_cgroup_do_precharge(unsigned long count)
5154 int ret = 0;
5155 int batch_count = PRECHARGE_COUNT_AT_ONCE;
5156 struct mem_cgroup *mem = mc.to;
5158 if (mem_cgroup_is_root(mem)) {
5159 mc.precharge += count;
5160 /* we don't need css_get for root */
5161 return ret;
5163 /* try to charge at once */
5164 if (count > 1) {
5165 struct res_counter *dummy;
5167 * "mem" cannot be under rmdir() because we've already checked
5168 * by cgroup_lock_live_cgroup() that it is not removed and we
5169 * are still under the same cgroup_mutex. So we can postpone
5170 * css_get().
5172 if (res_counter_charge(&mem->res, PAGE_SIZE * count, &dummy))
5173 goto one_by_one;
5174 if (do_swap_account && res_counter_charge(&mem->memsw,
5175 PAGE_SIZE * count, &dummy)) {
5176 res_counter_uncharge(&mem->res, PAGE_SIZE * count);
5177 goto one_by_one;
5179 mc.precharge += count;
5180 return ret;
5182 one_by_one:
5183 /* fall back to one by one charge */
5184 while (count--) {
5185 if (signal_pending(current)) {
5186 ret = -EINTR;
5187 break;
5189 if (!batch_count--) {
5190 batch_count = PRECHARGE_COUNT_AT_ONCE;
5191 cond_resched();
5193 ret = __mem_cgroup_try_charge(NULL, GFP_KERNEL, 1, &mem, false);
5194 if (ret || !mem)
5195 /* mem_cgroup_clear_mc() will do uncharge later */
5196 return -ENOMEM;
5197 mc.precharge++;
5199 return ret;
5203 * is_target_pte_for_mc - check a pte whether it is valid for move charge
5204 * @vma: the vma the pte to be checked belongs
5205 * @addr: the address corresponding to the pte to be checked
5206 * @ptent: the pte to be checked
5207 * @target: the pointer the target page or swap ent will be stored(can be NULL)
5209 * Returns
5210 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
5211 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5212 * move charge. if @target is not NULL, the page is stored in target->page
5213 * with extra refcnt got(Callers should handle it).
5214 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5215 * target for charge migration. if @target is not NULL, the entry is stored
5216 * in target->ent.
5218 * Called with pte lock held.
5220 union mc_target {
5221 struct page *page;
5222 swp_entry_t ent;
5225 enum mc_target_type {
5226 MC_TARGET_NONE, /* not used */
5227 MC_TARGET_PAGE,
5228 MC_TARGET_SWAP,
5231 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5232 unsigned long addr, pte_t ptent)
5234 struct page *page = vm_normal_page(vma, addr, ptent);
5236 if (!page || !page_mapped(page))
5237 return NULL;
5238 if (PageAnon(page)) {
5239 /* we don't move shared anon */
5240 if (!move_anon() || page_mapcount(page) > 2)
5241 return NULL;
5242 } else if (!move_file())
5243 /* we ignore mapcount for file pages */
5244 return NULL;
5245 if (!get_page_unless_zero(page))
5246 return NULL;
5248 return page;
5251 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5252 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5254 int usage_count;
5255 struct page *page = NULL;
5256 swp_entry_t ent = pte_to_swp_entry(ptent);
5258 if (!move_anon() || non_swap_entry(ent))
5259 return NULL;
5260 usage_count = mem_cgroup_count_swap_user(ent, &page);
5261 if (usage_count > 1) { /* we don't move shared anon */
5262 if (page)
5263 put_page(page);
5264 return NULL;
5266 if (do_swap_account)
5267 entry->val = ent.val;
5269 return page;
5272 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5273 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5275 struct page *page = NULL;
5276 struct inode *inode;
5277 struct address_space *mapping;
5278 pgoff_t pgoff;
5280 if (!vma->vm_file) /* anonymous vma */
5281 return NULL;
5282 if (!move_file())
5283 return NULL;
5285 inode = vma->vm_file->f_path.dentry->d_inode;
5286 mapping = vma->vm_file->f_mapping;
5287 if (pte_none(ptent))
5288 pgoff = linear_page_index(vma, addr);
5289 else /* pte_file(ptent) is true */
5290 pgoff = pte_to_pgoff(ptent);
5292 /* page is moved even if it's not RSS of this task(page-faulted). */
5293 page = find_get_page(mapping, pgoff);
5295 #ifdef CONFIG_SWAP
5296 /* shmem/tmpfs may report page out on swap: account for that too. */
5297 if (radix_tree_exceptional_entry(page)) {
5298 swp_entry_t swap = radix_to_swp_entry(page);
5299 if (do_swap_account)
5300 *entry = swap;
5301 page = find_get_page(&swapper_space, swap.val);
5303 #endif
5304 return page;
5307 static int is_target_pte_for_mc(struct vm_area_struct *vma,
5308 unsigned long addr, pte_t ptent, union mc_target *target)
5310 struct page *page = NULL;
5311 struct page_cgroup *pc;
5312 int ret = 0;
5313 swp_entry_t ent = { .val = 0 };
5315 if (pte_present(ptent))
5316 page = mc_handle_present_pte(vma, addr, ptent);
5317 else if (is_swap_pte(ptent))
5318 page = mc_handle_swap_pte(vma, addr, ptent, &ent);
5319 else if (pte_none(ptent) || pte_file(ptent))
5320 page = mc_handle_file_pte(vma, addr, ptent, &ent);
5322 if (!page && !ent.val)
5323 return 0;
5324 if (page) {
5325 pc = lookup_page_cgroup(page);
5327 * Do only loose check w/o page_cgroup lock.
5328 * mem_cgroup_move_account() checks the pc is valid or not under
5329 * the lock.
5331 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
5332 ret = MC_TARGET_PAGE;
5333 if (target)
5334 target->page = page;
5336 if (!ret || !target)
5337 put_page(page);
5339 /* There is a swap entry and a page doesn't exist or isn't charged */
5340 if (ent.val && !ret &&
5341 css_id(&mc.from->css) == lookup_swap_cgroup(ent)) {
5342 ret = MC_TARGET_SWAP;
5343 if (target)
5344 target->ent = ent;
5346 return ret;
5349 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
5350 unsigned long addr, unsigned long end,
5351 struct mm_walk *walk)
5353 struct vm_area_struct *vma = walk->private;
5354 pte_t *pte;
5355 spinlock_t *ptl;
5357 split_huge_page_pmd(walk->mm, pmd);
5359 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5360 for (; addr != end; pte++, addr += PAGE_SIZE)
5361 if (is_target_pte_for_mc(vma, addr, *pte, NULL))
5362 mc.precharge++; /* increment precharge temporarily */
5363 pte_unmap_unlock(pte - 1, ptl);
5364 cond_resched();
5366 return 0;
5369 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
5371 unsigned long precharge;
5372 struct vm_area_struct *vma;
5374 down_read(&mm->mmap_sem);
5375 for (vma = mm->mmap; vma; vma = vma->vm_next) {
5376 struct mm_walk mem_cgroup_count_precharge_walk = {
5377 .pmd_entry = mem_cgroup_count_precharge_pte_range,
5378 .mm = mm,
5379 .private = vma,
5381 if (is_vm_hugetlb_page(vma))
5382 continue;
5383 walk_page_range(vma->vm_start, vma->vm_end,
5384 &mem_cgroup_count_precharge_walk);
5386 up_read(&mm->mmap_sem);
5388 precharge = mc.precharge;
5389 mc.precharge = 0;
5391 return precharge;
5394 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
5396 unsigned long precharge = mem_cgroup_count_precharge(mm);
5398 VM_BUG_ON(mc.moving_task);
5399 mc.moving_task = current;
5400 return mem_cgroup_do_precharge(precharge);
5403 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5404 static void __mem_cgroup_clear_mc(void)
5406 struct mem_cgroup *from = mc.from;
5407 struct mem_cgroup *to = mc.to;
5409 /* we must uncharge all the leftover precharges from mc.to */
5410 if (mc.precharge) {
5411 __mem_cgroup_cancel_charge(mc.to, mc.precharge);
5412 mc.precharge = 0;
5415 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5416 * we must uncharge here.
5418 if (mc.moved_charge) {
5419 __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
5420 mc.moved_charge = 0;
5422 /* we must fixup refcnts and charges */
5423 if (mc.moved_swap) {
5424 /* uncharge swap account from the old cgroup */
5425 if (!mem_cgroup_is_root(mc.from))
5426 res_counter_uncharge(&mc.from->memsw,
5427 PAGE_SIZE * mc.moved_swap);
5428 __mem_cgroup_put(mc.from, mc.moved_swap);
5430 if (!mem_cgroup_is_root(mc.to)) {
5432 * we charged both to->res and to->memsw, so we should
5433 * uncharge to->res.
5435 res_counter_uncharge(&mc.to->res,
5436 PAGE_SIZE * mc.moved_swap);
5438 /* we've already done mem_cgroup_get(mc.to) */
5439 mc.moved_swap = 0;
5441 memcg_oom_recover(from);
5442 memcg_oom_recover(to);
5443 wake_up_all(&mc.waitq);
5446 static void mem_cgroup_clear_mc(void)
5448 struct mem_cgroup *from = mc.from;
5451 * we must clear moving_task before waking up waiters at the end of
5452 * task migration.
5454 mc.moving_task = NULL;
5455 __mem_cgroup_clear_mc();
5456 spin_lock(&mc.lock);
5457 mc.from = NULL;
5458 mc.to = NULL;
5459 spin_unlock(&mc.lock);
5460 mem_cgroup_end_move(from);
5463 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
5464 struct cgroup *cgroup,
5465 struct task_struct *p)
5467 int ret = 0;
5468 struct mem_cgroup *mem = mem_cgroup_from_cont(cgroup);
5470 if (mem->move_charge_at_immigrate) {
5471 struct mm_struct *mm;
5472 struct mem_cgroup *from = mem_cgroup_from_task(p);
5474 VM_BUG_ON(from == mem);
5476 mm = get_task_mm(p);
5477 if (!mm)
5478 return 0;
5479 /* We move charges only when we move a owner of the mm */
5480 if (mm->owner == p) {
5481 VM_BUG_ON(mc.from);
5482 VM_BUG_ON(mc.to);
5483 VM_BUG_ON(mc.precharge);
5484 VM_BUG_ON(mc.moved_charge);
5485 VM_BUG_ON(mc.moved_swap);
5486 mem_cgroup_start_move(from);
5487 spin_lock(&mc.lock);
5488 mc.from = from;
5489 mc.to = mem;
5490 spin_unlock(&mc.lock);
5491 /* We set mc.moving_task later */
5493 ret = mem_cgroup_precharge_mc(mm);
5494 if (ret)
5495 mem_cgroup_clear_mc();
5497 mmput(mm);
5499 return ret;
5502 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
5503 struct cgroup *cgroup,
5504 struct task_struct *p)
5506 mem_cgroup_clear_mc();
5509 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
5510 unsigned long addr, unsigned long end,
5511 struct mm_walk *walk)
5513 int ret = 0;
5514 struct vm_area_struct *vma = walk->private;
5515 pte_t *pte;
5516 spinlock_t *ptl;
5518 split_huge_page_pmd(walk->mm, pmd);
5519 retry:
5520 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5521 for (; addr != end; addr += PAGE_SIZE) {
5522 pte_t ptent = *(pte++);
5523 union mc_target target;
5524 int type;
5525 struct page *page;
5526 struct page_cgroup *pc;
5527 swp_entry_t ent;
5529 if (!mc.precharge)
5530 break;
5532 type = is_target_pte_for_mc(vma, addr, ptent, &target);
5533 switch (type) {
5534 case MC_TARGET_PAGE:
5535 page = target.page;
5536 if (isolate_lru_page(page))
5537 goto put;
5538 pc = lookup_page_cgroup(page);
5539 if (!mem_cgroup_move_account(page, 1, pc,
5540 mc.from, mc.to, false)) {
5541 mc.precharge--;
5542 /* we uncharge from mc.from later. */
5543 mc.moved_charge++;
5545 putback_lru_page(page);
5546 put: /* is_target_pte_for_mc() gets the page */
5547 put_page(page);
5548 break;
5549 case MC_TARGET_SWAP:
5550 ent = target.ent;
5551 if (!mem_cgroup_move_swap_account(ent,
5552 mc.from, mc.to, false)) {
5553 mc.precharge--;
5554 /* we fixup refcnts and charges later. */
5555 mc.moved_swap++;
5557 break;
5558 default:
5559 break;
5562 pte_unmap_unlock(pte - 1, ptl);
5563 cond_resched();
5565 if (addr != end) {
5567 * We have consumed all precharges we got in can_attach().
5568 * We try charge one by one, but don't do any additional
5569 * charges to mc.to if we have failed in charge once in attach()
5570 * phase.
5572 ret = mem_cgroup_do_precharge(1);
5573 if (!ret)
5574 goto retry;
5577 return ret;
5580 static void mem_cgroup_move_charge(struct mm_struct *mm)
5582 struct vm_area_struct *vma;
5584 lru_add_drain_all();
5585 retry:
5586 if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
5588 * Someone who are holding the mmap_sem might be waiting in
5589 * waitq. So we cancel all extra charges, wake up all waiters,
5590 * and retry. Because we cancel precharges, we might not be able
5591 * to move enough charges, but moving charge is a best-effort
5592 * feature anyway, so it wouldn't be a big problem.
5594 __mem_cgroup_clear_mc();
5595 cond_resched();
5596 goto retry;
5598 for (vma = mm->mmap; vma; vma = vma->vm_next) {
5599 int ret;
5600 struct mm_walk mem_cgroup_move_charge_walk = {
5601 .pmd_entry = mem_cgroup_move_charge_pte_range,
5602 .mm = mm,
5603 .private = vma,
5605 if (is_vm_hugetlb_page(vma))
5606 continue;
5607 ret = walk_page_range(vma->vm_start, vma->vm_end,
5608 &mem_cgroup_move_charge_walk);
5609 if (ret)
5611 * means we have consumed all precharges and failed in
5612 * doing additional charge. Just abandon here.
5614 break;
5616 up_read(&mm->mmap_sem);
5619 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
5620 struct cgroup *cont,
5621 struct cgroup *old_cont,
5622 struct task_struct *p)
5624 struct mm_struct *mm = get_task_mm(p);
5626 if (mm) {
5627 if (mc.to)
5628 mem_cgroup_move_charge(mm);
5629 put_swap_token(mm);
5630 mmput(mm);
5632 if (mc.to)
5633 mem_cgroup_clear_mc();
5635 #else /* !CONFIG_MMU */
5636 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
5637 struct cgroup *cgroup,
5638 struct task_struct *p)
5640 return 0;
5642 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
5643 struct cgroup *cgroup,
5644 struct task_struct *p)
5647 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
5648 struct cgroup *cont,
5649 struct cgroup *old_cont,
5650 struct task_struct *p)
5653 #endif
5655 struct cgroup_subsys mem_cgroup_subsys = {
5656 .name = "memory",
5657 .subsys_id = mem_cgroup_subsys_id,
5658 .create = mem_cgroup_create,
5659 .pre_destroy = mem_cgroup_pre_destroy,
5660 .destroy = mem_cgroup_destroy,
5661 .populate = mem_cgroup_populate,
5662 .can_attach = mem_cgroup_can_attach,
5663 .cancel_attach = mem_cgroup_cancel_attach,
5664 .attach = mem_cgroup_move_task,
5665 .early_init = 0,
5666 .use_id = 1,
5669 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
5670 static int __init enable_swap_account(char *s)
5672 /* consider enabled if no parameter or 1 is given */
5673 if (!strcmp(s, "1"))
5674 really_do_swap_account = 1;
5675 else if (!strcmp(s, "0"))
5676 really_do_swap_account = 0;
5677 return 1;
5679 __setup("swapaccount=", enable_swap_account);
5681 #endif