tcp memory pressure controls
[linux-2.6/linux-acpi-2.6/ibm-acpi-2.6.git] / mm / memcontrol.c
blob7266202fa7cf4f26147833cced4362cb302e72c0
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"
53 #include <net/sock.h>
54 #include <net/tcp_memcontrol.h>
56 #include <asm/uaccess.h>
58 #include <trace/events/vmscan.h>
60 struct cgroup_subsys mem_cgroup_subsys __read_mostly;
61 #define MEM_CGROUP_RECLAIM_RETRIES 5
62 struct mem_cgroup *root_mem_cgroup __read_mostly;
64 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
65 /* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
66 int do_swap_account __read_mostly;
68 /* for remember boot option*/
69 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP_ENABLED
70 static int really_do_swap_account __initdata = 1;
71 #else
72 static int really_do_swap_account __initdata = 0;
73 #endif
75 #else
76 #define do_swap_account (0)
77 #endif
81 * Statistics for memory cgroup.
83 enum mem_cgroup_stat_index {
85 * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
87 MEM_CGROUP_STAT_CACHE, /* # of pages charged as cache */
88 MEM_CGROUP_STAT_RSS, /* # of pages charged as anon rss */
89 MEM_CGROUP_STAT_FILE_MAPPED, /* # of pages charged as file rss */
90 MEM_CGROUP_STAT_SWAPOUT, /* # of pages, swapped out */
91 MEM_CGROUP_STAT_DATA, /* end of data requires synchronization */
92 MEM_CGROUP_ON_MOVE, /* someone is moving account between groups */
93 MEM_CGROUP_STAT_NSTATS,
96 enum mem_cgroup_events_index {
97 MEM_CGROUP_EVENTS_PGPGIN, /* # of pages paged in */
98 MEM_CGROUP_EVENTS_PGPGOUT, /* # of pages paged out */
99 MEM_CGROUP_EVENTS_COUNT, /* # of pages paged in/out */
100 MEM_CGROUP_EVENTS_PGFAULT, /* # of page-faults */
101 MEM_CGROUP_EVENTS_PGMAJFAULT, /* # of major page-faults */
102 MEM_CGROUP_EVENTS_NSTATS,
105 * Per memcg event counter is incremented at every pagein/pageout. With THP,
106 * it will be incremated by the number of pages. This counter is used for
107 * for trigger some periodic events. This is straightforward and better
108 * than using jiffies etc. to handle periodic memcg event.
110 enum mem_cgroup_events_target {
111 MEM_CGROUP_TARGET_THRESH,
112 MEM_CGROUP_TARGET_SOFTLIMIT,
113 MEM_CGROUP_TARGET_NUMAINFO,
114 MEM_CGROUP_NTARGETS,
116 #define THRESHOLDS_EVENTS_TARGET (128)
117 #define SOFTLIMIT_EVENTS_TARGET (1024)
118 #define NUMAINFO_EVENTS_TARGET (1024)
120 struct mem_cgroup_stat_cpu {
121 long count[MEM_CGROUP_STAT_NSTATS];
122 unsigned long events[MEM_CGROUP_EVENTS_NSTATS];
123 unsigned long targets[MEM_CGROUP_NTARGETS];
127 * per-zone information in memory controller.
129 struct mem_cgroup_per_zone {
131 * spin_lock to protect the per cgroup LRU
133 struct list_head lists[NR_LRU_LISTS];
134 unsigned long count[NR_LRU_LISTS];
136 struct zone_reclaim_stat reclaim_stat;
137 struct rb_node tree_node; /* RB tree node */
138 unsigned long long usage_in_excess;/* Set to the value by which */
139 /* the soft limit is exceeded*/
140 bool on_tree;
141 struct mem_cgroup *mem; /* Back pointer, we cannot */
142 /* use container_of */
144 /* Macro for accessing counter */
145 #define MEM_CGROUP_ZSTAT(mz, idx) ((mz)->count[(idx)])
147 struct mem_cgroup_per_node {
148 struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
151 struct mem_cgroup_lru_info {
152 struct mem_cgroup_per_node *nodeinfo[MAX_NUMNODES];
156 * Cgroups above their limits are maintained in a RB-Tree, independent of
157 * their hierarchy representation
160 struct mem_cgroup_tree_per_zone {
161 struct rb_root rb_root;
162 spinlock_t lock;
165 struct mem_cgroup_tree_per_node {
166 struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
169 struct mem_cgroup_tree {
170 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
173 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
175 struct mem_cgroup_threshold {
176 struct eventfd_ctx *eventfd;
177 u64 threshold;
180 /* For threshold */
181 struct mem_cgroup_threshold_ary {
182 /* An array index points to threshold just below usage. */
183 int current_threshold;
184 /* Size of entries[] */
185 unsigned int size;
186 /* Array of thresholds */
187 struct mem_cgroup_threshold entries[0];
190 struct mem_cgroup_thresholds {
191 /* Primary thresholds array */
192 struct mem_cgroup_threshold_ary *primary;
194 * Spare threshold array.
195 * This is needed to make mem_cgroup_unregister_event() "never fail".
196 * It must be able to store at least primary->size - 1 entries.
198 struct mem_cgroup_threshold_ary *spare;
201 /* for OOM */
202 struct mem_cgroup_eventfd_list {
203 struct list_head list;
204 struct eventfd_ctx *eventfd;
207 static void mem_cgroup_threshold(struct mem_cgroup *memcg);
208 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
211 * The memory controller data structure. The memory controller controls both
212 * page cache and RSS per cgroup. We would eventually like to provide
213 * statistics based on the statistics developed by Rik Van Riel for clock-pro,
214 * to help the administrator determine what knobs to tune.
216 * TODO: Add a water mark for the memory controller. Reclaim will begin when
217 * we hit the water mark. May be even add a low water mark, such that
218 * no reclaim occurs from a cgroup at it's low water mark, this is
219 * a feature that will be implemented much later in the future.
221 struct mem_cgroup {
222 struct cgroup_subsys_state css;
224 * the counter to account for memory usage
226 struct res_counter res;
228 * the counter to account for mem+swap usage.
230 struct res_counter memsw;
232 * the counter to account for kmem usage.
234 struct res_counter kmem;
236 * Per cgroup active and inactive list, similar to the
237 * per zone LRU lists.
239 struct mem_cgroup_lru_info info;
241 * While reclaiming in a hierarchy, we cache the last child we
242 * reclaimed from.
244 int last_scanned_child;
245 int last_scanned_node;
246 #if MAX_NUMNODES > 1
247 nodemask_t scan_nodes;
248 atomic_t numainfo_events;
249 atomic_t numainfo_updating;
250 #endif
252 * Should the accounting and control be hierarchical, per subtree?
254 bool use_hierarchy;
256 bool oom_lock;
257 atomic_t under_oom;
259 atomic_t refcnt;
261 int swappiness;
262 /* OOM-Killer disable */
263 int oom_kill_disable;
265 /* set when res.limit == memsw.limit */
266 bool memsw_is_minimum;
268 /* protect arrays of thresholds */
269 struct mutex thresholds_lock;
271 /* thresholds for memory usage. RCU-protected */
272 struct mem_cgroup_thresholds thresholds;
274 /* thresholds for mem+swap usage. RCU-protected */
275 struct mem_cgroup_thresholds memsw_thresholds;
277 /* For oom notifier event fd */
278 struct list_head oom_notify;
281 * Should we move charges of a task when a task is moved into this
282 * mem_cgroup ? And what type of charges should we move ?
284 unsigned long move_charge_at_immigrate;
286 * Should kernel memory limits be stabilished independently
287 * from user memory ?
289 int kmem_independent_accounting;
291 * percpu counter.
293 struct mem_cgroup_stat_cpu *stat;
295 * used when a cpu is offlined or other synchronizations
296 * See mem_cgroup_read_stat().
298 struct mem_cgroup_stat_cpu nocpu_base;
299 spinlock_t pcp_counter_lock;
301 #ifdef CONFIG_INET
302 struct tcp_memcontrol tcp_mem;
303 #endif
306 /* Stuffs for move charges at task migration. */
308 * Types of charges to be moved. "move_charge_at_immitgrate" is treated as a
309 * left-shifted bitmap of these types.
311 enum move_type {
312 MOVE_CHARGE_TYPE_ANON, /* private anonymous page and swap of it */
313 MOVE_CHARGE_TYPE_FILE, /* file page(including tmpfs) and swap of it */
314 NR_MOVE_TYPE,
317 /* "mc" and its members are protected by cgroup_mutex */
318 static struct move_charge_struct {
319 spinlock_t lock; /* for from, to */
320 struct mem_cgroup *from;
321 struct mem_cgroup *to;
322 unsigned long precharge;
323 unsigned long moved_charge;
324 unsigned long moved_swap;
325 struct task_struct *moving_task; /* a task moving charges */
326 wait_queue_head_t waitq; /* a waitq for other context */
327 } mc = {
328 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
329 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
332 static bool move_anon(void)
334 return test_bit(MOVE_CHARGE_TYPE_ANON,
335 &mc.to->move_charge_at_immigrate);
338 static bool move_file(void)
340 return test_bit(MOVE_CHARGE_TYPE_FILE,
341 &mc.to->move_charge_at_immigrate);
345 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
346 * limit reclaim to prevent infinite loops, if they ever occur.
348 #define MEM_CGROUP_MAX_RECLAIM_LOOPS (100)
349 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS (2)
351 enum charge_type {
352 MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
353 MEM_CGROUP_CHARGE_TYPE_MAPPED,
354 MEM_CGROUP_CHARGE_TYPE_SHMEM, /* used by page migration of shmem */
355 MEM_CGROUP_CHARGE_TYPE_FORCE, /* used by force_empty */
356 MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
357 MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
358 NR_CHARGE_TYPE,
361 /* for encoding cft->private value on file */
363 enum mem_type {
364 _MEM = 0,
365 _MEMSWAP,
366 _OOM_TYPE,
367 _KMEM,
370 #define MEMFILE_PRIVATE(x, val) (((x) << 16) | (val))
371 #define MEMFILE_TYPE(val) (((val) >> 16) & 0xffff)
372 #define MEMFILE_ATTR(val) ((val) & 0xffff)
373 /* Used for OOM nofiier */
374 #define OOM_CONTROL (0)
377 * Reclaim flags for mem_cgroup_hierarchical_reclaim
379 #define MEM_CGROUP_RECLAIM_NOSWAP_BIT 0x0
380 #define MEM_CGROUP_RECLAIM_NOSWAP (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
381 #define MEM_CGROUP_RECLAIM_SHRINK_BIT 0x1
382 #define MEM_CGROUP_RECLAIM_SHRINK (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
383 #define MEM_CGROUP_RECLAIM_SOFT_BIT 0x2
384 #define MEM_CGROUP_RECLAIM_SOFT (1 << MEM_CGROUP_RECLAIM_SOFT_BIT)
386 static void mem_cgroup_get(struct mem_cgroup *memcg);
387 static void mem_cgroup_put(struct mem_cgroup *memcg);
389 /* Writing them here to avoid exposing memcg's inner layout */
390 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_KMEM
391 #ifdef CONFIG_INET
392 #include <net/sock.h>
393 #include <net/ip.h>
395 static bool mem_cgroup_is_root(struct mem_cgroup *memcg);
396 void sock_update_memcg(struct sock *sk)
398 /* A socket spends its whole life in the same cgroup */
399 if (sk->sk_cgrp) {
400 WARN_ON(1);
401 return;
403 if (static_branch(&memcg_socket_limit_enabled)) {
404 struct mem_cgroup *memcg;
406 BUG_ON(!sk->sk_prot->proto_cgroup);
408 rcu_read_lock();
409 memcg = mem_cgroup_from_task(current);
410 if (!mem_cgroup_is_root(memcg)) {
411 mem_cgroup_get(memcg);
412 sk->sk_cgrp = sk->sk_prot->proto_cgroup(memcg);
414 rcu_read_unlock();
417 EXPORT_SYMBOL(sock_update_memcg);
419 void sock_release_memcg(struct sock *sk)
421 if (static_branch(&memcg_socket_limit_enabled) && sk->sk_cgrp) {
422 struct mem_cgroup *memcg;
423 WARN_ON(!sk->sk_cgrp->memcg);
424 memcg = sk->sk_cgrp->memcg;
425 mem_cgroup_put(memcg);
429 struct cg_proto *tcp_proto_cgroup(struct mem_cgroup *memcg)
431 if (!memcg || mem_cgroup_is_root(memcg))
432 return NULL;
434 return &memcg->tcp_mem.cg_proto;
436 EXPORT_SYMBOL(tcp_proto_cgroup);
437 #endif /* CONFIG_INET */
438 #endif /* CONFIG_CGROUP_MEM_RES_CTLR_KMEM */
440 static void drain_all_stock_async(struct mem_cgroup *memcg);
442 static struct mem_cgroup_per_zone *
443 mem_cgroup_zoneinfo(struct mem_cgroup *memcg, int nid, int zid)
445 return &memcg->info.nodeinfo[nid]->zoneinfo[zid];
448 struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *memcg)
450 return &memcg->css;
453 static struct mem_cgroup_per_zone *
454 page_cgroup_zoneinfo(struct mem_cgroup *memcg, struct page *page)
456 int nid = page_to_nid(page);
457 int zid = page_zonenum(page);
459 return mem_cgroup_zoneinfo(memcg, nid, zid);
462 static struct mem_cgroup_tree_per_zone *
463 soft_limit_tree_node_zone(int nid, int zid)
465 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
468 static struct mem_cgroup_tree_per_zone *
469 soft_limit_tree_from_page(struct page *page)
471 int nid = page_to_nid(page);
472 int zid = page_zonenum(page);
474 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
477 static void
478 __mem_cgroup_insert_exceeded(struct mem_cgroup *memcg,
479 struct mem_cgroup_per_zone *mz,
480 struct mem_cgroup_tree_per_zone *mctz,
481 unsigned long long new_usage_in_excess)
483 struct rb_node **p = &mctz->rb_root.rb_node;
484 struct rb_node *parent = NULL;
485 struct mem_cgroup_per_zone *mz_node;
487 if (mz->on_tree)
488 return;
490 mz->usage_in_excess = new_usage_in_excess;
491 if (!mz->usage_in_excess)
492 return;
493 while (*p) {
494 parent = *p;
495 mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
496 tree_node);
497 if (mz->usage_in_excess < mz_node->usage_in_excess)
498 p = &(*p)->rb_left;
500 * We can't avoid mem cgroups that are over their soft
501 * limit by the same amount
503 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
504 p = &(*p)->rb_right;
506 rb_link_node(&mz->tree_node, parent, p);
507 rb_insert_color(&mz->tree_node, &mctz->rb_root);
508 mz->on_tree = true;
511 static void
512 __mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
513 struct mem_cgroup_per_zone *mz,
514 struct mem_cgroup_tree_per_zone *mctz)
516 if (!mz->on_tree)
517 return;
518 rb_erase(&mz->tree_node, &mctz->rb_root);
519 mz->on_tree = false;
522 static void
523 mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
524 struct mem_cgroup_per_zone *mz,
525 struct mem_cgroup_tree_per_zone *mctz)
527 spin_lock(&mctz->lock);
528 __mem_cgroup_remove_exceeded(memcg, mz, mctz);
529 spin_unlock(&mctz->lock);
533 static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
535 unsigned long long excess;
536 struct mem_cgroup_per_zone *mz;
537 struct mem_cgroup_tree_per_zone *mctz;
538 int nid = page_to_nid(page);
539 int zid = page_zonenum(page);
540 mctz = soft_limit_tree_from_page(page);
543 * Necessary to update all ancestors when hierarchy is used.
544 * because their event counter is not touched.
546 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
547 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
548 excess = res_counter_soft_limit_excess(&memcg->res);
550 * We have to update the tree if mz is on RB-tree or
551 * mem is over its softlimit.
553 if (excess || mz->on_tree) {
554 spin_lock(&mctz->lock);
555 /* if on-tree, remove it */
556 if (mz->on_tree)
557 __mem_cgroup_remove_exceeded(memcg, mz, mctz);
559 * Insert again. mz->usage_in_excess will be updated.
560 * If excess is 0, no tree ops.
562 __mem_cgroup_insert_exceeded(memcg, mz, mctz, excess);
563 spin_unlock(&mctz->lock);
568 static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
570 int node, zone;
571 struct mem_cgroup_per_zone *mz;
572 struct mem_cgroup_tree_per_zone *mctz;
574 for_each_node_state(node, N_POSSIBLE) {
575 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
576 mz = mem_cgroup_zoneinfo(memcg, node, zone);
577 mctz = soft_limit_tree_node_zone(node, zone);
578 mem_cgroup_remove_exceeded(memcg, mz, mctz);
583 static struct mem_cgroup_per_zone *
584 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
586 struct rb_node *rightmost = NULL;
587 struct mem_cgroup_per_zone *mz;
589 retry:
590 mz = NULL;
591 rightmost = rb_last(&mctz->rb_root);
592 if (!rightmost)
593 goto done; /* Nothing to reclaim from */
595 mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
597 * Remove the node now but someone else can add it back,
598 * we will to add it back at the end of reclaim to its correct
599 * position in the tree.
601 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
602 if (!res_counter_soft_limit_excess(&mz->mem->res) ||
603 !css_tryget(&mz->mem->css))
604 goto retry;
605 done:
606 return mz;
609 static struct mem_cgroup_per_zone *
610 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
612 struct mem_cgroup_per_zone *mz;
614 spin_lock(&mctz->lock);
615 mz = __mem_cgroup_largest_soft_limit_node(mctz);
616 spin_unlock(&mctz->lock);
617 return mz;
621 * Implementation Note: reading percpu statistics for memcg.
623 * Both of vmstat[] and percpu_counter has threshold and do periodic
624 * synchronization to implement "quick" read. There are trade-off between
625 * reading cost and precision of value. Then, we may have a chance to implement
626 * a periodic synchronizion of counter in memcg's counter.
628 * But this _read() function is used for user interface now. The user accounts
629 * memory usage by memory cgroup and he _always_ requires exact value because
630 * he accounts memory. Even if we provide quick-and-fuzzy read, we always
631 * have to visit all online cpus and make sum. So, for now, unnecessary
632 * synchronization is not implemented. (just implemented for cpu hotplug)
634 * If there are kernel internal actions which can make use of some not-exact
635 * value, and reading all cpu value can be performance bottleneck in some
636 * common workload, threashold and synchonization as vmstat[] should be
637 * implemented.
639 static long mem_cgroup_read_stat(struct mem_cgroup *memcg,
640 enum mem_cgroup_stat_index idx)
642 long val = 0;
643 int cpu;
645 get_online_cpus();
646 for_each_online_cpu(cpu)
647 val += per_cpu(memcg->stat->count[idx], cpu);
648 #ifdef CONFIG_HOTPLUG_CPU
649 spin_lock(&memcg->pcp_counter_lock);
650 val += memcg->nocpu_base.count[idx];
651 spin_unlock(&memcg->pcp_counter_lock);
652 #endif
653 put_online_cpus();
654 return val;
657 static void mem_cgroup_swap_statistics(struct mem_cgroup *memcg,
658 bool charge)
660 int val = (charge) ? 1 : -1;
661 this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_SWAPOUT], val);
664 void mem_cgroup_pgfault(struct mem_cgroup *memcg, int val)
666 this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_PGFAULT], val);
669 void mem_cgroup_pgmajfault(struct mem_cgroup *memcg, int val)
671 this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_PGMAJFAULT], val);
674 static unsigned long mem_cgroup_read_events(struct mem_cgroup *memcg,
675 enum mem_cgroup_events_index idx)
677 unsigned long val = 0;
678 int cpu;
680 for_each_online_cpu(cpu)
681 val += per_cpu(memcg->stat->events[idx], cpu);
682 #ifdef CONFIG_HOTPLUG_CPU
683 spin_lock(&memcg->pcp_counter_lock);
684 val += memcg->nocpu_base.events[idx];
685 spin_unlock(&memcg->pcp_counter_lock);
686 #endif
687 return val;
690 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
691 bool file, int nr_pages)
693 preempt_disable();
695 if (file)
696 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_CACHE],
697 nr_pages);
698 else
699 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS],
700 nr_pages);
702 /* pagein of a big page is an event. So, ignore page size */
703 if (nr_pages > 0)
704 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGIN]);
705 else {
706 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGOUT]);
707 nr_pages = -nr_pages; /* for event */
710 __this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_COUNT], nr_pages);
712 preempt_enable();
715 unsigned long
716 mem_cgroup_zone_nr_lru_pages(struct mem_cgroup *memcg, int nid, int zid,
717 unsigned int lru_mask)
719 struct mem_cgroup_per_zone *mz;
720 enum lru_list l;
721 unsigned long ret = 0;
723 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
725 for_each_lru(l) {
726 if (BIT(l) & lru_mask)
727 ret += MEM_CGROUP_ZSTAT(mz, l);
729 return ret;
732 static unsigned long
733 mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
734 int nid, unsigned int lru_mask)
736 u64 total = 0;
737 int zid;
739 for (zid = 0; zid < MAX_NR_ZONES; zid++)
740 total += mem_cgroup_zone_nr_lru_pages(memcg,
741 nid, zid, lru_mask);
743 return total;
746 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
747 unsigned int lru_mask)
749 int nid;
750 u64 total = 0;
752 for_each_node_state(nid, N_HIGH_MEMORY)
753 total += mem_cgroup_node_nr_lru_pages(memcg, nid, lru_mask);
754 return total;
757 static bool __memcg_event_check(struct mem_cgroup *memcg, int target)
759 unsigned long val, next;
761 val = __this_cpu_read(memcg->stat->events[MEM_CGROUP_EVENTS_COUNT]);
762 next = __this_cpu_read(memcg->stat->targets[target]);
763 /* from time_after() in jiffies.h */
764 return ((long)next - (long)val < 0);
767 static void __mem_cgroup_target_update(struct mem_cgroup *memcg, int target)
769 unsigned long val, next;
771 val = __this_cpu_read(memcg->stat->events[MEM_CGROUP_EVENTS_COUNT]);
773 switch (target) {
774 case MEM_CGROUP_TARGET_THRESH:
775 next = val + THRESHOLDS_EVENTS_TARGET;
776 break;
777 case MEM_CGROUP_TARGET_SOFTLIMIT:
778 next = val + SOFTLIMIT_EVENTS_TARGET;
779 break;
780 case MEM_CGROUP_TARGET_NUMAINFO:
781 next = val + NUMAINFO_EVENTS_TARGET;
782 break;
783 default:
784 return;
787 __this_cpu_write(memcg->stat->targets[target], next);
791 * Check events in order.
794 static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
796 preempt_disable();
797 /* threshold event is triggered in finer grain than soft limit */
798 if (unlikely(__memcg_event_check(memcg, MEM_CGROUP_TARGET_THRESH))) {
799 mem_cgroup_threshold(memcg);
800 __mem_cgroup_target_update(memcg, MEM_CGROUP_TARGET_THRESH);
801 if (unlikely(__memcg_event_check(memcg,
802 MEM_CGROUP_TARGET_SOFTLIMIT))) {
803 mem_cgroup_update_tree(memcg, page);
804 __mem_cgroup_target_update(memcg,
805 MEM_CGROUP_TARGET_SOFTLIMIT);
807 #if MAX_NUMNODES > 1
808 if (unlikely(__memcg_event_check(memcg,
809 MEM_CGROUP_TARGET_NUMAINFO))) {
810 atomic_inc(&memcg->numainfo_events);
811 __mem_cgroup_target_update(memcg,
812 MEM_CGROUP_TARGET_NUMAINFO);
814 #endif
816 preempt_enable();
819 struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
821 return container_of(cgroup_subsys_state(cont,
822 mem_cgroup_subsys_id), struct mem_cgroup,
823 css);
826 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
829 * mm_update_next_owner() may clear mm->owner to NULL
830 * if it races with swapoff, page migration, etc.
831 * So this can be called with p == NULL.
833 if (unlikely(!p))
834 return NULL;
836 return container_of(task_subsys_state(p, mem_cgroup_subsys_id),
837 struct mem_cgroup, css);
840 struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
842 struct mem_cgroup *memcg = NULL;
844 if (!mm)
845 return NULL;
847 * Because we have no locks, mm->owner's may be being moved to other
848 * cgroup. We use css_tryget() here even if this looks
849 * pessimistic (rather than adding locks here).
851 rcu_read_lock();
852 do {
853 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
854 if (unlikely(!memcg))
855 break;
856 } while (!css_tryget(&memcg->css));
857 rcu_read_unlock();
858 return memcg;
861 /* The caller has to guarantee "mem" exists before calling this */
862 static struct mem_cgroup *mem_cgroup_start_loop(struct mem_cgroup *memcg)
864 struct cgroup_subsys_state *css;
865 int found;
867 if (!memcg) /* ROOT cgroup has the smallest ID */
868 return root_mem_cgroup; /*css_put/get against root is ignored*/
869 if (!memcg->use_hierarchy) {
870 if (css_tryget(&memcg->css))
871 return memcg;
872 return NULL;
874 rcu_read_lock();
876 * searching a memory cgroup which has the smallest ID under given
877 * ROOT cgroup. (ID >= 1)
879 css = css_get_next(&mem_cgroup_subsys, 1, &memcg->css, &found);
880 if (css && css_tryget(css))
881 memcg = container_of(css, struct mem_cgroup, css);
882 else
883 memcg = NULL;
884 rcu_read_unlock();
885 return memcg;
888 static struct mem_cgroup *mem_cgroup_get_next(struct mem_cgroup *iter,
889 struct mem_cgroup *root,
890 bool cond)
892 int nextid = css_id(&iter->css) + 1;
893 int found;
894 int hierarchy_used;
895 struct cgroup_subsys_state *css;
897 hierarchy_used = iter->use_hierarchy;
899 css_put(&iter->css);
900 /* If no ROOT, walk all, ignore hierarchy */
901 if (!cond || (root && !hierarchy_used))
902 return NULL;
904 if (!root)
905 root = root_mem_cgroup;
907 do {
908 iter = NULL;
909 rcu_read_lock();
911 css = css_get_next(&mem_cgroup_subsys, nextid,
912 &root->css, &found);
913 if (css && css_tryget(css))
914 iter = container_of(css, struct mem_cgroup, css);
915 rcu_read_unlock();
916 /* If css is NULL, no more cgroups will be found */
917 nextid = found + 1;
918 } while (css && !iter);
920 return iter;
923 * for_eacn_mem_cgroup_tree() for visiting all cgroup under tree. Please
924 * be careful that "break" loop is not allowed. We have reference count.
925 * Instead of that modify "cond" to be false and "continue" to exit the loop.
927 #define for_each_mem_cgroup_tree_cond(iter, root, cond) \
928 for (iter = mem_cgroup_start_loop(root);\
929 iter != NULL;\
930 iter = mem_cgroup_get_next(iter, root, cond))
932 #define for_each_mem_cgroup_tree(iter, root) \
933 for_each_mem_cgroup_tree_cond(iter, root, true)
935 #define for_each_mem_cgroup_all(iter) \
936 for_each_mem_cgroup_tree_cond(iter, NULL, true)
939 static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg)
941 return (memcg == root_mem_cgroup);
944 void mem_cgroup_count_vm_event(struct mm_struct *mm, enum vm_event_item idx)
946 struct mem_cgroup *memcg;
948 if (!mm)
949 return;
951 rcu_read_lock();
952 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
953 if (unlikely(!memcg))
954 goto out;
956 switch (idx) {
957 case PGMAJFAULT:
958 mem_cgroup_pgmajfault(memcg, 1);
959 break;
960 case PGFAULT:
961 mem_cgroup_pgfault(memcg, 1);
962 break;
963 default:
964 BUG();
966 out:
967 rcu_read_unlock();
969 EXPORT_SYMBOL(mem_cgroup_count_vm_event);
972 * Following LRU functions are allowed to be used without PCG_LOCK.
973 * Operations are called by routine of global LRU independently from memcg.
974 * What we have to take care of here is validness of pc->mem_cgroup.
976 * Changes to pc->mem_cgroup happens when
977 * 1. charge
978 * 2. moving account
979 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
980 * It is added to LRU before charge.
981 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
982 * When moving account, the page is not on LRU. It's isolated.
985 void mem_cgroup_del_lru_list(struct page *page, enum lru_list lru)
987 struct page_cgroup *pc;
988 struct mem_cgroup_per_zone *mz;
990 if (mem_cgroup_disabled())
991 return;
992 pc = lookup_page_cgroup(page);
993 /* can happen while we handle swapcache. */
994 if (!TestClearPageCgroupAcctLRU(pc))
995 return;
996 VM_BUG_ON(!pc->mem_cgroup);
998 * We don't check PCG_USED bit. It's cleared when the "page" is finally
999 * removed from global LRU.
1001 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
1002 /* huge page split is done under lru_lock. so, we have no races. */
1003 MEM_CGROUP_ZSTAT(mz, lru) -= 1 << compound_order(page);
1004 if (mem_cgroup_is_root(pc->mem_cgroup))
1005 return;
1006 VM_BUG_ON(list_empty(&pc->lru));
1007 list_del_init(&pc->lru);
1010 void mem_cgroup_del_lru(struct page *page)
1012 mem_cgroup_del_lru_list(page, page_lru(page));
1016 * Writeback is about to end against a page which has been marked for immediate
1017 * reclaim. If it still appears to be reclaimable, move it to the tail of the
1018 * inactive list.
1020 void mem_cgroup_rotate_reclaimable_page(struct page *page)
1022 struct mem_cgroup_per_zone *mz;
1023 struct page_cgroup *pc;
1024 enum lru_list lru = page_lru(page);
1026 if (mem_cgroup_disabled())
1027 return;
1029 pc = lookup_page_cgroup(page);
1030 /* unused or root page is not rotated. */
1031 if (!PageCgroupUsed(pc))
1032 return;
1033 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1034 smp_rmb();
1035 if (mem_cgroup_is_root(pc->mem_cgroup))
1036 return;
1037 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
1038 list_move_tail(&pc->lru, &mz->lists[lru]);
1041 void mem_cgroup_rotate_lru_list(struct page *page, enum lru_list lru)
1043 struct mem_cgroup_per_zone *mz;
1044 struct page_cgroup *pc;
1046 if (mem_cgroup_disabled())
1047 return;
1049 pc = lookup_page_cgroup(page);
1050 /* unused or root page is not rotated. */
1051 if (!PageCgroupUsed(pc))
1052 return;
1053 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1054 smp_rmb();
1055 if (mem_cgroup_is_root(pc->mem_cgroup))
1056 return;
1057 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
1058 list_move(&pc->lru, &mz->lists[lru]);
1061 void mem_cgroup_add_lru_list(struct page *page, enum lru_list lru)
1063 struct page_cgroup *pc;
1064 struct mem_cgroup_per_zone *mz;
1066 if (mem_cgroup_disabled())
1067 return;
1068 pc = lookup_page_cgroup(page);
1069 VM_BUG_ON(PageCgroupAcctLRU(pc));
1071 * putback: charge:
1072 * SetPageLRU SetPageCgroupUsed
1073 * smp_mb smp_mb
1074 * PageCgroupUsed && add to memcg LRU PageLRU && add to memcg LRU
1076 * Ensure that one of the two sides adds the page to the memcg
1077 * LRU during a race.
1079 smp_mb();
1080 if (!PageCgroupUsed(pc))
1081 return;
1082 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1083 smp_rmb();
1084 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
1085 /* huge page split is done under lru_lock. so, we have no races. */
1086 MEM_CGROUP_ZSTAT(mz, lru) += 1 << compound_order(page);
1087 SetPageCgroupAcctLRU(pc);
1088 if (mem_cgroup_is_root(pc->mem_cgroup))
1089 return;
1090 list_add(&pc->lru, &mz->lists[lru]);
1094 * At handling SwapCache and other FUSE stuff, pc->mem_cgroup may be changed
1095 * while it's linked to lru because the page may be reused after it's fully
1096 * uncharged. To handle that, unlink page_cgroup from LRU when charge it again.
1097 * It's done under lock_page and expected that zone->lru_lock isnever held.
1099 static void mem_cgroup_lru_del_before_commit(struct page *page)
1101 unsigned long flags;
1102 struct zone *zone = page_zone(page);
1103 struct page_cgroup *pc = lookup_page_cgroup(page);
1106 * Doing this check without taking ->lru_lock seems wrong but this
1107 * is safe. Because if page_cgroup's USED bit is unset, the page
1108 * will not be added to any memcg's LRU. If page_cgroup's USED bit is
1109 * set, the commit after this will fail, anyway.
1110 * This all charge/uncharge is done under some mutual execustion.
1111 * So, we don't need to taking care of changes in USED bit.
1113 if (likely(!PageLRU(page)))
1114 return;
1116 spin_lock_irqsave(&zone->lru_lock, flags);
1118 * Forget old LRU when this page_cgroup is *not* used. This Used bit
1119 * is guarded by lock_page() because the page is SwapCache.
1121 if (!PageCgroupUsed(pc))
1122 mem_cgroup_del_lru_list(page, page_lru(page));
1123 spin_unlock_irqrestore(&zone->lru_lock, flags);
1126 static void mem_cgroup_lru_add_after_commit(struct page *page)
1128 unsigned long flags;
1129 struct zone *zone = page_zone(page);
1130 struct page_cgroup *pc = lookup_page_cgroup(page);
1132 * putback: charge:
1133 * SetPageLRU SetPageCgroupUsed
1134 * smp_mb smp_mb
1135 * PageCgroupUsed && add to memcg LRU PageLRU && add to memcg LRU
1137 * Ensure that one of the two sides adds the page to the memcg
1138 * LRU during a race.
1140 smp_mb();
1141 /* taking care of that the page is added to LRU while we commit it */
1142 if (likely(!PageLRU(page)))
1143 return;
1144 spin_lock_irqsave(&zone->lru_lock, flags);
1145 /* link when the page is linked to LRU but page_cgroup isn't */
1146 if (PageLRU(page) && !PageCgroupAcctLRU(pc))
1147 mem_cgroup_add_lru_list(page, page_lru(page));
1148 spin_unlock_irqrestore(&zone->lru_lock, flags);
1152 void mem_cgroup_move_lists(struct page *page,
1153 enum lru_list from, enum lru_list to)
1155 if (mem_cgroup_disabled())
1156 return;
1157 mem_cgroup_del_lru_list(page, from);
1158 mem_cgroup_add_lru_list(page, to);
1162 * Checks whether given mem is same or in the root_mem_cgroup's
1163 * hierarchy subtree
1165 static bool mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
1166 struct mem_cgroup *memcg)
1168 if (root_memcg != memcg) {
1169 return (root_memcg->use_hierarchy &&
1170 css_is_ancestor(&memcg->css, &root_memcg->css));
1173 return true;
1176 int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *memcg)
1178 int ret;
1179 struct mem_cgroup *curr = NULL;
1180 struct task_struct *p;
1182 p = find_lock_task_mm(task);
1183 if (!p)
1184 return 0;
1185 curr = try_get_mem_cgroup_from_mm(p->mm);
1186 task_unlock(p);
1187 if (!curr)
1188 return 0;
1190 * We should check use_hierarchy of "memcg" not "curr". Because checking
1191 * use_hierarchy of "curr" here make this function true if hierarchy is
1192 * enabled in "curr" and "curr" is a child of "memcg" in *cgroup*
1193 * hierarchy(even if use_hierarchy is disabled in "memcg").
1195 ret = mem_cgroup_same_or_subtree(memcg, curr);
1196 css_put(&curr->css);
1197 return ret;
1200 int mem_cgroup_inactive_anon_is_low(struct mem_cgroup *memcg, struct zone *zone)
1202 unsigned long inactive_ratio;
1203 int nid = zone_to_nid(zone);
1204 int zid = zone_idx(zone);
1205 unsigned long inactive;
1206 unsigned long active;
1207 unsigned long gb;
1209 inactive = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1210 BIT(LRU_INACTIVE_ANON));
1211 active = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1212 BIT(LRU_ACTIVE_ANON));
1214 gb = (inactive + active) >> (30 - PAGE_SHIFT);
1215 if (gb)
1216 inactive_ratio = int_sqrt(10 * gb);
1217 else
1218 inactive_ratio = 1;
1220 return inactive * inactive_ratio < active;
1223 int mem_cgroup_inactive_file_is_low(struct mem_cgroup *memcg, struct zone *zone)
1225 unsigned long active;
1226 unsigned long inactive;
1227 int zid = zone_idx(zone);
1228 int nid = zone_to_nid(zone);
1230 inactive = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1231 BIT(LRU_INACTIVE_FILE));
1232 active = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1233 BIT(LRU_ACTIVE_FILE));
1235 return (active > inactive);
1238 struct zone_reclaim_stat *mem_cgroup_get_reclaim_stat(struct mem_cgroup *memcg,
1239 struct zone *zone)
1241 int nid = zone_to_nid(zone);
1242 int zid = zone_idx(zone);
1243 struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
1245 return &mz->reclaim_stat;
1248 struct zone_reclaim_stat *
1249 mem_cgroup_get_reclaim_stat_from_page(struct page *page)
1251 struct page_cgroup *pc;
1252 struct mem_cgroup_per_zone *mz;
1254 if (mem_cgroup_disabled())
1255 return NULL;
1257 pc = lookup_page_cgroup(page);
1258 if (!PageCgroupUsed(pc))
1259 return NULL;
1260 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1261 smp_rmb();
1262 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
1263 return &mz->reclaim_stat;
1266 unsigned long mem_cgroup_isolate_pages(unsigned long nr_to_scan,
1267 struct list_head *dst,
1268 unsigned long *scanned, int order,
1269 isolate_mode_t mode,
1270 struct zone *z,
1271 struct mem_cgroup *mem_cont,
1272 int active, int file)
1274 unsigned long nr_taken = 0;
1275 struct page *page;
1276 unsigned long scan;
1277 LIST_HEAD(pc_list);
1278 struct list_head *src;
1279 struct page_cgroup *pc, *tmp;
1280 int nid = zone_to_nid(z);
1281 int zid = zone_idx(z);
1282 struct mem_cgroup_per_zone *mz;
1283 int lru = LRU_FILE * file + active;
1284 int ret;
1286 BUG_ON(!mem_cont);
1287 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
1288 src = &mz->lists[lru];
1290 scan = 0;
1291 list_for_each_entry_safe_reverse(pc, tmp, src, lru) {
1292 if (scan >= nr_to_scan)
1293 break;
1295 if (unlikely(!PageCgroupUsed(pc)))
1296 continue;
1298 page = lookup_cgroup_page(pc);
1300 if (unlikely(!PageLRU(page)))
1301 continue;
1303 scan++;
1304 ret = __isolate_lru_page(page, mode, file);
1305 switch (ret) {
1306 case 0:
1307 list_move(&page->lru, dst);
1308 mem_cgroup_del_lru(page);
1309 nr_taken += hpage_nr_pages(page);
1310 break;
1311 case -EBUSY:
1312 /* we don't affect global LRU but rotate in our LRU */
1313 mem_cgroup_rotate_lru_list(page, page_lru(page));
1314 break;
1315 default:
1316 break;
1320 *scanned = scan;
1322 trace_mm_vmscan_memcg_isolate(0, nr_to_scan, scan, nr_taken,
1323 0, 0, 0, mode);
1325 return nr_taken;
1328 #define mem_cgroup_from_res_counter(counter, member) \
1329 container_of(counter, struct mem_cgroup, member)
1332 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1333 * @mem: the memory cgroup
1335 * Returns the maximum amount of memory @mem can be charged with, in
1336 * pages.
1338 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1340 unsigned long long margin;
1342 margin = res_counter_margin(&memcg->res);
1343 if (do_swap_account)
1344 margin = min(margin, res_counter_margin(&memcg->memsw));
1345 return margin >> PAGE_SHIFT;
1348 int mem_cgroup_swappiness(struct mem_cgroup *memcg)
1350 struct cgroup *cgrp = memcg->css.cgroup;
1352 /* root ? */
1353 if (cgrp->parent == NULL)
1354 return vm_swappiness;
1356 return memcg->swappiness;
1359 static void mem_cgroup_start_move(struct mem_cgroup *memcg)
1361 int cpu;
1363 get_online_cpus();
1364 spin_lock(&memcg->pcp_counter_lock);
1365 for_each_online_cpu(cpu)
1366 per_cpu(memcg->stat->count[MEM_CGROUP_ON_MOVE], cpu) += 1;
1367 memcg->nocpu_base.count[MEM_CGROUP_ON_MOVE] += 1;
1368 spin_unlock(&memcg->pcp_counter_lock);
1369 put_online_cpus();
1371 synchronize_rcu();
1374 static void mem_cgroup_end_move(struct mem_cgroup *memcg)
1376 int cpu;
1378 if (!memcg)
1379 return;
1380 get_online_cpus();
1381 spin_lock(&memcg->pcp_counter_lock);
1382 for_each_online_cpu(cpu)
1383 per_cpu(memcg->stat->count[MEM_CGROUP_ON_MOVE], cpu) -= 1;
1384 memcg->nocpu_base.count[MEM_CGROUP_ON_MOVE] -= 1;
1385 spin_unlock(&memcg->pcp_counter_lock);
1386 put_online_cpus();
1389 * 2 routines for checking "mem" is under move_account() or not.
1391 * mem_cgroup_stealed() - checking a cgroup is mc.from or not. This is used
1392 * for avoiding race in accounting. If true,
1393 * pc->mem_cgroup may be overwritten.
1395 * mem_cgroup_under_move() - checking a cgroup is mc.from or mc.to or
1396 * under hierarchy of moving cgroups. This is for
1397 * waiting at hith-memory prressure caused by "move".
1400 static bool mem_cgroup_stealed(struct mem_cgroup *memcg)
1402 VM_BUG_ON(!rcu_read_lock_held());
1403 return this_cpu_read(memcg->stat->count[MEM_CGROUP_ON_MOVE]) > 0;
1406 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1408 struct mem_cgroup *from;
1409 struct mem_cgroup *to;
1410 bool ret = false;
1412 * Unlike task_move routines, we access mc.to, mc.from not under
1413 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1415 spin_lock(&mc.lock);
1416 from = mc.from;
1417 to = mc.to;
1418 if (!from)
1419 goto unlock;
1421 ret = mem_cgroup_same_or_subtree(memcg, from)
1422 || mem_cgroup_same_or_subtree(memcg, to);
1423 unlock:
1424 spin_unlock(&mc.lock);
1425 return ret;
1428 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1430 if (mc.moving_task && current != mc.moving_task) {
1431 if (mem_cgroup_under_move(memcg)) {
1432 DEFINE_WAIT(wait);
1433 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1434 /* moving charge context might have finished. */
1435 if (mc.moving_task)
1436 schedule();
1437 finish_wait(&mc.waitq, &wait);
1438 return true;
1441 return false;
1445 * mem_cgroup_print_oom_info: Called from OOM with tasklist_lock held in read mode.
1446 * @memcg: The memory cgroup that went over limit
1447 * @p: Task that is going to be killed
1449 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1450 * enabled
1452 void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1454 struct cgroup *task_cgrp;
1455 struct cgroup *mem_cgrp;
1457 * Need a buffer in BSS, can't rely on allocations. The code relies
1458 * on the assumption that OOM is serialized for memory controller.
1459 * If this assumption is broken, revisit this code.
1461 static char memcg_name[PATH_MAX];
1462 int ret;
1464 if (!memcg || !p)
1465 return;
1468 rcu_read_lock();
1470 mem_cgrp = memcg->css.cgroup;
1471 task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
1473 ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
1474 if (ret < 0) {
1476 * Unfortunately, we are unable to convert to a useful name
1477 * But we'll still print out the usage information
1479 rcu_read_unlock();
1480 goto done;
1482 rcu_read_unlock();
1484 printk(KERN_INFO "Task in %s killed", memcg_name);
1486 rcu_read_lock();
1487 ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
1488 if (ret < 0) {
1489 rcu_read_unlock();
1490 goto done;
1492 rcu_read_unlock();
1495 * Continues from above, so we don't need an KERN_ level
1497 printk(KERN_CONT " as a result of limit of %s\n", memcg_name);
1498 done:
1500 printk(KERN_INFO "memory: usage %llukB, limit %llukB, failcnt %llu\n",
1501 res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
1502 res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
1503 res_counter_read_u64(&memcg->res, RES_FAILCNT));
1504 printk(KERN_INFO "memory+swap: usage %llukB, limit %llukB, "
1505 "failcnt %llu\n",
1506 res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
1507 res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
1508 res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
1512 * This function returns the number of memcg under hierarchy tree. Returns
1513 * 1(self count) if no children.
1515 static int mem_cgroup_count_children(struct mem_cgroup *memcg)
1517 int num = 0;
1518 struct mem_cgroup *iter;
1520 for_each_mem_cgroup_tree(iter, memcg)
1521 num++;
1522 return num;
1526 * Return the memory (and swap, if configured) limit for a memcg.
1528 u64 mem_cgroup_get_limit(struct mem_cgroup *memcg)
1530 u64 limit;
1531 u64 memsw;
1533 limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
1534 limit += total_swap_pages << PAGE_SHIFT;
1536 memsw = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
1538 * If memsw is finite and limits the amount of swap space available
1539 * to this memcg, return that limit.
1541 return min(limit, memsw);
1545 * Visit the first child (need not be the first child as per the ordering
1546 * of the cgroup list, since we track last_scanned_child) of @mem and use
1547 * that to reclaim free pages from.
1549 static struct mem_cgroup *
1550 mem_cgroup_select_victim(struct mem_cgroup *root_memcg)
1552 struct mem_cgroup *ret = NULL;
1553 struct cgroup_subsys_state *css;
1554 int nextid, found;
1556 if (!root_memcg->use_hierarchy) {
1557 css_get(&root_memcg->css);
1558 ret = root_memcg;
1561 while (!ret) {
1562 rcu_read_lock();
1563 nextid = root_memcg->last_scanned_child + 1;
1564 css = css_get_next(&mem_cgroup_subsys, nextid, &root_memcg->css,
1565 &found);
1566 if (css && css_tryget(css))
1567 ret = container_of(css, struct mem_cgroup, css);
1569 rcu_read_unlock();
1570 /* Updates scanning parameter */
1571 if (!css) {
1572 /* this means start scan from ID:1 */
1573 root_memcg->last_scanned_child = 0;
1574 } else
1575 root_memcg->last_scanned_child = found;
1578 return ret;
1582 * test_mem_cgroup_node_reclaimable
1583 * @mem: the target memcg
1584 * @nid: the node ID to be checked.
1585 * @noswap : specify true here if the user wants flle only information.
1587 * This function returns whether the specified memcg contains any
1588 * reclaimable pages on a node. Returns true if there are any reclaimable
1589 * pages in the node.
1591 static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *memcg,
1592 int nid, bool noswap)
1594 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_FILE))
1595 return true;
1596 if (noswap || !total_swap_pages)
1597 return false;
1598 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_ANON))
1599 return true;
1600 return false;
1603 #if MAX_NUMNODES > 1
1606 * Always updating the nodemask is not very good - even if we have an empty
1607 * list or the wrong list here, we can start from some node and traverse all
1608 * nodes based on the zonelist. So update the list loosely once per 10 secs.
1611 static void mem_cgroup_may_update_nodemask(struct mem_cgroup *memcg)
1613 int nid;
1615 * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
1616 * pagein/pageout changes since the last update.
1618 if (!atomic_read(&memcg->numainfo_events))
1619 return;
1620 if (atomic_inc_return(&memcg->numainfo_updating) > 1)
1621 return;
1623 /* make a nodemask where this memcg uses memory from */
1624 memcg->scan_nodes = node_states[N_HIGH_MEMORY];
1626 for_each_node_mask(nid, node_states[N_HIGH_MEMORY]) {
1628 if (!test_mem_cgroup_node_reclaimable(memcg, nid, false))
1629 node_clear(nid, memcg->scan_nodes);
1632 atomic_set(&memcg->numainfo_events, 0);
1633 atomic_set(&memcg->numainfo_updating, 0);
1637 * Selecting a node where we start reclaim from. Because what we need is just
1638 * reducing usage counter, start from anywhere is O,K. Considering
1639 * memory reclaim from current node, there are pros. and cons.
1641 * Freeing memory from current node means freeing memory from a node which
1642 * we'll use or we've used. So, it may make LRU bad. And if several threads
1643 * hit limits, it will see a contention on a node. But freeing from remote
1644 * node means more costs for memory reclaim because of memory latency.
1646 * Now, we use round-robin. Better algorithm is welcomed.
1648 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1650 int node;
1652 mem_cgroup_may_update_nodemask(memcg);
1653 node = memcg->last_scanned_node;
1655 node = next_node(node, memcg->scan_nodes);
1656 if (node == MAX_NUMNODES)
1657 node = first_node(memcg->scan_nodes);
1659 * We call this when we hit limit, not when pages are added to LRU.
1660 * No LRU may hold pages because all pages are UNEVICTABLE or
1661 * memcg is too small and all pages are not on LRU. In that case,
1662 * we use curret node.
1664 if (unlikely(node == MAX_NUMNODES))
1665 node = numa_node_id();
1667 memcg->last_scanned_node = node;
1668 return node;
1672 * Check all nodes whether it contains reclaimable pages or not.
1673 * For quick scan, we make use of scan_nodes. This will allow us to skip
1674 * unused nodes. But scan_nodes is lazily updated and may not cotain
1675 * enough new information. We need to do double check.
1677 bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
1679 int nid;
1682 * quick check...making use of scan_node.
1683 * We can skip unused nodes.
1685 if (!nodes_empty(memcg->scan_nodes)) {
1686 for (nid = first_node(memcg->scan_nodes);
1687 nid < MAX_NUMNODES;
1688 nid = next_node(nid, memcg->scan_nodes)) {
1690 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
1691 return true;
1695 * Check rest of nodes.
1697 for_each_node_state(nid, N_HIGH_MEMORY) {
1698 if (node_isset(nid, memcg->scan_nodes))
1699 continue;
1700 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
1701 return true;
1703 return false;
1706 #else
1707 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1709 return 0;
1712 bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
1714 return test_mem_cgroup_node_reclaimable(memcg, 0, noswap);
1716 #endif
1719 * Scan the hierarchy if needed to reclaim memory. We remember the last child
1720 * we reclaimed from, so that we don't end up penalizing one child extensively
1721 * based on its position in the children list.
1723 * root_memcg is the original ancestor that we've been reclaim from.
1725 * We give up and return to the caller when we visit root_memcg twice.
1726 * (other groups can be removed while we're walking....)
1728 * If shrink==true, for avoiding to free too much, this returns immedieately.
1730 static int mem_cgroup_hierarchical_reclaim(struct mem_cgroup *root_memcg,
1731 struct zone *zone,
1732 gfp_t gfp_mask,
1733 unsigned long reclaim_options,
1734 unsigned long *total_scanned)
1736 struct mem_cgroup *victim;
1737 int ret, total = 0;
1738 int loop = 0;
1739 bool noswap = reclaim_options & MEM_CGROUP_RECLAIM_NOSWAP;
1740 bool shrink = reclaim_options & MEM_CGROUP_RECLAIM_SHRINK;
1741 bool check_soft = reclaim_options & MEM_CGROUP_RECLAIM_SOFT;
1742 unsigned long excess;
1743 unsigned long nr_scanned;
1745 excess = res_counter_soft_limit_excess(&root_memcg->res) >> PAGE_SHIFT;
1747 /* If memsw_is_minimum==1, swap-out is of-no-use. */
1748 if (!check_soft && !shrink && root_memcg->memsw_is_minimum)
1749 noswap = true;
1751 while (1) {
1752 victim = mem_cgroup_select_victim(root_memcg);
1753 if (victim == root_memcg) {
1754 loop++;
1756 * We are not draining per cpu cached charges during
1757 * soft limit reclaim because global reclaim doesn't
1758 * care about charges. It tries to free some memory and
1759 * charges will not give any.
1761 if (!check_soft && loop >= 1)
1762 drain_all_stock_async(root_memcg);
1763 if (loop >= 2) {
1765 * If we have not been able to reclaim
1766 * anything, it might because there are
1767 * no reclaimable pages under this hierarchy
1769 if (!check_soft || !total) {
1770 css_put(&victim->css);
1771 break;
1774 * We want to do more targeted reclaim.
1775 * excess >> 2 is not to excessive so as to
1776 * reclaim too much, nor too less that we keep
1777 * coming back to reclaim from this cgroup
1779 if (total >= (excess >> 2) ||
1780 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS)) {
1781 css_put(&victim->css);
1782 break;
1786 if (!mem_cgroup_reclaimable(victim, noswap)) {
1787 /* this cgroup's local usage == 0 */
1788 css_put(&victim->css);
1789 continue;
1791 /* we use swappiness of local cgroup */
1792 if (check_soft) {
1793 ret = mem_cgroup_shrink_node_zone(victim, gfp_mask,
1794 noswap, zone, &nr_scanned);
1795 *total_scanned += nr_scanned;
1796 } else
1797 ret = try_to_free_mem_cgroup_pages(victim, gfp_mask,
1798 noswap);
1799 css_put(&victim->css);
1801 * At shrinking usage, we can't check we should stop here or
1802 * reclaim more. It's depends on callers. last_scanned_child
1803 * will work enough for keeping fairness under tree.
1805 if (shrink)
1806 return ret;
1807 total += ret;
1808 if (check_soft) {
1809 if (!res_counter_soft_limit_excess(&root_memcg->res))
1810 return total;
1811 } else if (mem_cgroup_margin(root_memcg))
1812 return total;
1814 return total;
1818 * Check OOM-Killer is already running under our hierarchy.
1819 * If someone is running, return false.
1820 * Has to be called with memcg_oom_lock
1822 static bool mem_cgroup_oom_lock(struct mem_cgroup *memcg)
1824 struct mem_cgroup *iter, *failed = NULL;
1825 bool cond = true;
1827 for_each_mem_cgroup_tree_cond(iter, memcg, cond) {
1828 if (iter->oom_lock) {
1830 * this subtree of our hierarchy is already locked
1831 * so we cannot give a lock.
1833 failed = iter;
1834 cond = false;
1835 } else
1836 iter->oom_lock = true;
1839 if (!failed)
1840 return true;
1843 * OK, we failed to lock the whole subtree so we have to clean up
1844 * what we set up to the failing subtree
1846 cond = true;
1847 for_each_mem_cgroup_tree_cond(iter, memcg, cond) {
1848 if (iter == failed) {
1849 cond = false;
1850 continue;
1852 iter->oom_lock = false;
1854 return false;
1858 * Has to be called with memcg_oom_lock
1860 static int mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
1862 struct mem_cgroup *iter;
1864 for_each_mem_cgroup_tree(iter, memcg)
1865 iter->oom_lock = false;
1866 return 0;
1869 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
1871 struct mem_cgroup *iter;
1873 for_each_mem_cgroup_tree(iter, memcg)
1874 atomic_inc(&iter->under_oom);
1877 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
1879 struct mem_cgroup *iter;
1882 * When a new child is created while the hierarchy is under oom,
1883 * mem_cgroup_oom_lock() may not be called. We have to use
1884 * atomic_add_unless() here.
1886 for_each_mem_cgroup_tree(iter, memcg)
1887 atomic_add_unless(&iter->under_oom, -1, 0);
1890 static DEFINE_SPINLOCK(memcg_oom_lock);
1891 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1893 struct oom_wait_info {
1894 struct mem_cgroup *mem;
1895 wait_queue_t wait;
1898 static int memcg_oom_wake_function(wait_queue_t *wait,
1899 unsigned mode, int sync, void *arg)
1901 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg,
1902 *oom_wait_memcg;
1903 struct oom_wait_info *oom_wait_info;
1905 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1906 oom_wait_memcg = oom_wait_info->mem;
1909 * Both of oom_wait_info->mem and wake_mem are stable under us.
1910 * Then we can use css_is_ancestor without taking care of RCU.
1912 if (!mem_cgroup_same_or_subtree(oom_wait_memcg, wake_memcg)
1913 && !mem_cgroup_same_or_subtree(wake_memcg, oom_wait_memcg))
1914 return 0;
1915 return autoremove_wake_function(wait, mode, sync, arg);
1918 static void memcg_wakeup_oom(struct mem_cgroup *memcg)
1920 /* for filtering, pass "memcg" as argument. */
1921 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
1924 static void memcg_oom_recover(struct mem_cgroup *memcg)
1926 if (memcg && atomic_read(&memcg->under_oom))
1927 memcg_wakeup_oom(memcg);
1931 * try to call OOM killer. returns false if we should exit memory-reclaim loop.
1933 bool mem_cgroup_handle_oom(struct mem_cgroup *memcg, gfp_t mask)
1935 struct oom_wait_info owait;
1936 bool locked, need_to_kill;
1938 owait.mem = memcg;
1939 owait.wait.flags = 0;
1940 owait.wait.func = memcg_oom_wake_function;
1941 owait.wait.private = current;
1942 INIT_LIST_HEAD(&owait.wait.task_list);
1943 need_to_kill = true;
1944 mem_cgroup_mark_under_oom(memcg);
1946 /* At first, try to OOM lock hierarchy under memcg.*/
1947 spin_lock(&memcg_oom_lock);
1948 locked = mem_cgroup_oom_lock(memcg);
1950 * Even if signal_pending(), we can't quit charge() loop without
1951 * accounting. So, UNINTERRUPTIBLE is appropriate. But SIGKILL
1952 * under OOM is always welcomed, use TASK_KILLABLE here.
1954 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
1955 if (!locked || memcg->oom_kill_disable)
1956 need_to_kill = false;
1957 if (locked)
1958 mem_cgroup_oom_notify(memcg);
1959 spin_unlock(&memcg_oom_lock);
1961 if (need_to_kill) {
1962 finish_wait(&memcg_oom_waitq, &owait.wait);
1963 mem_cgroup_out_of_memory(memcg, mask);
1964 } else {
1965 schedule();
1966 finish_wait(&memcg_oom_waitq, &owait.wait);
1968 spin_lock(&memcg_oom_lock);
1969 if (locked)
1970 mem_cgroup_oom_unlock(memcg);
1971 memcg_wakeup_oom(memcg);
1972 spin_unlock(&memcg_oom_lock);
1974 mem_cgroup_unmark_under_oom(memcg);
1976 if (test_thread_flag(TIF_MEMDIE) || fatal_signal_pending(current))
1977 return false;
1978 /* Give chance to dying process */
1979 schedule_timeout_uninterruptible(1);
1980 return true;
1984 * Currently used to update mapped file statistics, but the routine can be
1985 * generalized to update other statistics as well.
1987 * Notes: Race condition
1989 * We usually use page_cgroup_lock() for accessing page_cgroup member but
1990 * it tends to be costly. But considering some conditions, we doesn't need
1991 * to do so _always_.
1993 * Considering "charge", lock_page_cgroup() is not required because all
1994 * file-stat operations happen after a page is attached to radix-tree. There
1995 * are no race with "charge".
1997 * Considering "uncharge", we know that memcg doesn't clear pc->mem_cgroup
1998 * at "uncharge" intentionally. So, we always see valid pc->mem_cgroup even
1999 * if there are race with "uncharge". Statistics itself is properly handled
2000 * by flags.
2002 * Considering "move", this is an only case we see a race. To make the race
2003 * small, we check MEM_CGROUP_ON_MOVE percpu value and detect there are
2004 * possibility of race condition. If there is, we take a lock.
2007 void mem_cgroup_update_page_stat(struct page *page,
2008 enum mem_cgroup_page_stat_item idx, int val)
2010 struct mem_cgroup *memcg;
2011 struct page_cgroup *pc = lookup_page_cgroup(page);
2012 bool need_unlock = false;
2013 unsigned long uninitialized_var(flags);
2015 if (unlikely(!pc))
2016 return;
2018 rcu_read_lock();
2019 memcg = pc->mem_cgroup;
2020 if (unlikely(!memcg || !PageCgroupUsed(pc)))
2021 goto out;
2022 /* pc->mem_cgroup is unstable ? */
2023 if (unlikely(mem_cgroup_stealed(memcg)) || PageTransHuge(page)) {
2024 /* take a lock against to access pc->mem_cgroup */
2025 move_lock_page_cgroup(pc, &flags);
2026 need_unlock = true;
2027 memcg = pc->mem_cgroup;
2028 if (!memcg || !PageCgroupUsed(pc))
2029 goto out;
2032 switch (idx) {
2033 case MEMCG_NR_FILE_MAPPED:
2034 if (val > 0)
2035 SetPageCgroupFileMapped(pc);
2036 else if (!page_mapped(page))
2037 ClearPageCgroupFileMapped(pc);
2038 idx = MEM_CGROUP_STAT_FILE_MAPPED;
2039 break;
2040 default:
2041 BUG();
2044 this_cpu_add(memcg->stat->count[idx], val);
2046 out:
2047 if (unlikely(need_unlock))
2048 move_unlock_page_cgroup(pc, &flags);
2049 rcu_read_unlock();
2050 return;
2052 EXPORT_SYMBOL(mem_cgroup_update_page_stat);
2055 * size of first charge trial. "32" comes from vmscan.c's magic value.
2056 * TODO: maybe necessary to use big numbers in big irons.
2058 #define CHARGE_BATCH 32U
2059 struct memcg_stock_pcp {
2060 struct mem_cgroup *cached; /* this never be root cgroup */
2061 unsigned int nr_pages;
2062 struct work_struct work;
2063 unsigned long flags;
2064 #define FLUSHING_CACHED_CHARGE (0)
2066 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
2067 static DEFINE_MUTEX(percpu_charge_mutex);
2070 * Try to consume stocked charge on this cpu. If success, one page is consumed
2071 * from local stock and true is returned. If the stock is 0 or charges from a
2072 * cgroup which is not current target, returns false. This stock will be
2073 * refilled.
2075 static bool consume_stock(struct mem_cgroup *memcg)
2077 struct memcg_stock_pcp *stock;
2078 bool ret = true;
2080 stock = &get_cpu_var(memcg_stock);
2081 if (memcg == stock->cached && stock->nr_pages)
2082 stock->nr_pages--;
2083 else /* need to call res_counter_charge */
2084 ret = false;
2085 put_cpu_var(memcg_stock);
2086 return ret;
2090 * Returns stocks cached in percpu to res_counter and reset cached information.
2092 static void drain_stock(struct memcg_stock_pcp *stock)
2094 struct mem_cgroup *old = stock->cached;
2096 if (stock->nr_pages) {
2097 unsigned long bytes = stock->nr_pages * PAGE_SIZE;
2099 res_counter_uncharge(&old->res, bytes);
2100 if (do_swap_account)
2101 res_counter_uncharge(&old->memsw, bytes);
2102 stock->nr_pages = 0;
2104 stock->cached = NULL;
2108 * This must be called under preempt disabled or must be called by
2109 * a thread which is pinned to local cpu.
2111 static void drain_local_stock(struct work_struct *dummy)
2113 struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
2114 drain_stock(stock);
2115 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2119 * Cache charges(val) which is from res_counter, to local per_cpu area.
2120 * This will be consumed by consume_stock() function, later.
2122 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2124 struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
2126 if (stock->cached != memcg) { /* reset if necessary */
2127 drain_stock(stock);
2128 stock->cached = memcg;
2130 stock->nr_pages += nr_pages;
2131 put_cpu_var(memcg_stock);
2135 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2136 * of the hierarchy under it. sync flag says whether we should block
2137 * until the work is done.
2139 static void drain_all_stock(struct mem_cgroup *root_memcg, bool sync)
2141 int cpu, curcpu;
2143 /* Notify other cpus that system-wide "drain" is running */
2144 get_online_cpus();
2145 curcpu = get_cpu();
2146 for_each_online_cpu(cpu) {
2147 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2148 struct mem_cgroup *memcg;
2150 memcg = stock->cached;
2151 if (!memcg || !stock->nr_pages)
2152 continue;
2153 if (!mem_cgroup_same_or_subtree(root_memcg, memcg))
2154 continue;
2155 if (!test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2156 if (cpu == curcpu)
2157 drain_local_stock(&stock->work);
2158 else
2159 schedule_work_on(cpu, &stock->work);
2162 put_cpu();
2164 if (!sync)
2165 goto out;
2167 for_each_online_cpu(cpu) {
2168 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2169 if (test_bit(FLUSHING_CACHED_CHARGE, &stock->flags))
2170 flush_work(&stock->work);
2172 out:
2173 put_online_cpus();
2177 * Tries to drain stocked charges in other cpus. This function is asynchronous
2178 * and just put a work per cpu for draining localy on each cpu. Caller can
2179 * expects some charges will be back to res_counter later but cannot wait for
2180 * it.
2182 static void drain_all_stock_async(struct mem_cgroup *root_memcg)
2185 * If someone calls draining, avoid adding more kworker runs.
2187 if (!mutex_trylock(&percpu_charge_mutex))
2188 return;
2189 drain_all_stock(root_memcg, false);
2190 mutex_unlock(&percpu_charge_mutex);
2193 /* This is a synchronous drain interface. */
2194 static void drain_all_stock_sync(struct mem_cgroup *root_memcg)
2196 /* called when force_empty is called */
2197 mutex_lock(&percpu_charge_mutex);
2198 drain_all_stock(root_memcg, true);
2199 mutex_unlock(&percpu_charge_mutex);
2203 * This function drains percpu counter value from DEAD cpu and
2204 * move it to local cpu. Note that this function can be preempted.
2206 static void mem_cgroup_drain_pcp_counter(struct mem_cgroup *memcg, int cpu)
2208 int i;
2210 spin_lock(&memcg->pcp_counter_lock);
2211 for (i = 0; i < MEM_CGROUP_STAT_DATA; i++) {
2212 long x = per_cpu(memcg->stat->count[i], cpu);
2214 per_cpu(memcg->stat->count[i], cpu) = 0;
2215 memcg->nocpu_base.count[i] += x;
2217 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
2218 unsigned long x = per_cpu(memcg->stat->events[i], cpu);
2220 per_cpu(memcg->stat->events[i], cpu) = 0;
2221 memcg->nocpu_base.events[i] += x;
2223 /* need to clear ON_MOVE value, works as a kind of lock. */
2224 per_cpu(memcg->stat->count[MEM_CGROUP_ON_MOVE], cpu) = 0;
2225 spin_unlock(&memcg->pcp_counter_lock);
2228 static void synchronize_mem_cgroup_on_move(struct mem_cgroup *memcg, int cpu)
2230 int idx = MEM_CGROUP_ON_MOVE;
2232 spin_lock(&memcg->pcp_counter_lock);
2233 per_cpu(memcg->stat->count[idx], cpu) = memcg->nocpu_base.count[idx];
2234 spin_unlock(&memcg->pcp_counter_lock);
2237 static int __cpuinit memcg_cpu_hotplug_callback(struct notifier_block *nb,
2238 unsigned long action,
2239 void *hcpu)
2241 int cpu = (unsigned long)hcpu;
2242 struct memcg_stock_pcp *stock;
2243 struct mem_cgroup *iter;
2245 if ((action == CPU_ONLINE)) {
2246 for_each_mem_cgroup_all(iter)
2247 synchronize_mem_cgroup_on_move(iter, cpu);
2248 return NOTIFY_OK;
2251 if ((action != CPU_DEAD) || action != CPU_DEAD_FROZEN)
2252 return NOTIFY_OK;
2254 for_each_mem_cgroup_all(iter)
2255 mem_cgroup_drain_pcp_counter(iter, cpu);
2257 stock = &per_cpu(memcg_stock, cpu);
2258 drain_stock(stock);
2259 return NOTIFY_OK;
2263 /* See __mem_cgroup_try_charge() for details */
2264 enum {
2265 CHARGE_OK, /* success */
2266 CHARGE_RETRY, /* need to retry but retry is not bad */
2267 CHARGE_NOMEM, /* we can't do more. return -ENOMEM */
2268 CHARGE_WOULDBLOCK, /* GFP_WAIT wasn't set and no enough res. */
2269 CHARGE_OOM_DIE, /* the current is killed because of OOM */
2272 static int mem_cgroup_do_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2273 unsigned int nr_pages, bool oom_check)
2275 unsigned long csize = nr_pages * PAGE_SIZE;
2276 struct mem_cgroup *mem_over_limit;
2277 struct res_counter *fail_res;
2278 unsigned long flags = 0;
2279 int ret;
2281 ret = res_counter_charge(&memcg->res, csize, &fail_res);
2283 if (likely(!ret)) {
2284 if (!do_swap_account)
2285 return CHARGE_OK;
2286 ret = res_counter_charge(&memcg->memsw, csize, &fail_res);
2287 if (likely(!ret))
2288 return CHARGE_OK;
2290 res_counter_uncharge(&memcg->res, csize);
2291 mem_over_limit = mem_cgroup_from_res_counter(fail_res, memsw);
2292 flags |= MEM_CGROUP_RECLAIM_NOSWAP;
2293 } else
2294 mem_over_limit = mem_cgroup_from_res_counter(fail_res, res);
2296 * nr_pages can be either a huge page (HPAGE_PMD_NR), a batch
2297 * of regular pages (CHARGE_BATCH), or a single regular page (1).
2299 * Never reclaim on behalf of optional batching, retry with a
2300 * single page instead.
2302 if (nr_pages == CHARGE_BATCH)
2303 return CHARGE_RETRY;
2305 if (!(gfp_mask & __GFP_WAIT))
2306 return CHARGE_WOULDBLOCK;
2308 ret = mem_cgroup_hierarchical_reclaim(mem_over_limit, NULL,
2309 gfp_mask, flags, NULL);
2310 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2311 return CHARGE_RETRY;
2313 * Even though the limit is exceeded at this point, reclaim
2314 * may have been able to free some pages. Retry the charge
2315 * before killing the task.
2317 * Only for regular pages, though: huge pages are rather
2318 * unlikely to succeed so close to the limit, and we fall back
2319 * to regular pages anyway in case of failure.
2321 if (nr_pages == 1 && ret)
2322 return CHARGE_RETRY;
2325 * At task move, charge accounts can be doubly counted. So, it's
2326 * better to wait until the end of task_move if something is going on.
2328 if (mem_cgroup_wait_acct_move(mem_over_limit))
2329 return CHARGE_RETRY;
2331 /* If we don't need to call oom-killer at el, return immediately */
2332 if (!oom_check)
2333 return CHARGE_NOMEM;
2334 /* check OOM */
2335 if (!mem_cgroup_handle_oom(mem_over_limit, gfp_mask))
2336 return CHARGE_OOM_DIE;
2338 return CHARGE_RETRY;
2342 * Unlike exported interface, "oom" parameter is added. if oom==true,
2343 * oom-killer can be invoked.
2345 static int __mem_cgroup_try_charge(struct mm_struct *mm,
2346 gfp_t gfp_mask,
2347 unsigned int nr_pages,
2348 struct mem_cgroup **ptr,
2349 bool oom)
2351 unsigned int batch = max(CHARGE_BATCH, nr_pages);
2352 int nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2353 struct mem_cgroup *memcg = NULL;
2354 int ret;
2357 * Unlike gloval-vm's OOM-kill, we're not in memory shortage
2358 * in system level. So, allow to go ahead dying process in addition to
2359 * MEMDIE process.
2361 if (unlikely(test_thread_flag(TIF_MEMDIE)
2362 || fatal_signal_pending(current)))
2363 goto bypass;
2366 * We always charge the cgroup the mm_struct belongs to.
2367 * The mm_struct's mem_cgroup changes on task migration if the
2368 * thread group leader migrates. It's possible that mm is not
2369 * set, if so charge the init_mm (happens for pagecache usage).
2371 if (!*ptr && !mm)
2372 goto bypass;
2373 again:
2374 if (*ptr) { /* css should be a valid one */
2375 memcg = *ptr;
2376 VM_BUG_ON(css_is_removed(&memcg->css));
2377 if (mem_cgroup_is_root(memcg))
2378 goto done;
2379 if (nr_pages == 1 && consume_stock(memcg))
2380 goto done;
2381 css_get(&memcg->css);
2382 } else {
2383 struct task_struct *p;
2385 rcu_read_lock();
2386 p = rcu_dereference(mm->owner);
2388 * Because we don't have task_lock(), "p" can exit.
2389 * In that case, "memcg" can point to root or p can be NULL with
2390 * race with swapoff. Then, we have small risk of mis-accouning.
2391 * But such kind of mis-account by race always happens because
2392 * we don't have cgroup_mutex(). It's overkill and we allo that
2393 * small race, here.
2394 * (*) swapoff at el will charge against mm-struct not against
2395 * task-struct. So, mm->owner can be NULL.
2397 memcg = mem_cgroup_from_task(p);
2398 if (!memcg || mem_cgroup_is_root(memcg)) {
2399 rcu_read_unlock();
2400 goto done;
2402 if (nr_pages == 1 && consume_stock(memcg)) {
2404 * It seems dagerous to access memcg without css_get().
2405 * But considering how consume_stok works, it's not
2406 * necessary. If consume_stock success, some charges
2407 * from this memcg are cached on this cpu. So, we
2408 * don't need to call css_get()/css_tryget() before
2409 * calling consume_stock().
2411 rcu_read_unlock();
2412 goto done;
2414 /* after here, we may be blocked. we need to get refcnt */
2415 if (!css_tryget(&memcg->css)) {
2416 rcu_read_unlock();
2417 goto again;
2419 rcu_read_unlock();
2422 do {
2423 bool oom_check;
2425 /* If killed, bypass charge */
2426 if (fatal_signal_pending(current)) {
2427 css_put(&memcg->css);
2428 goto bypass;
2431 oom_check = false;
2432 if (oom && !nr_oom_retries) {
2433 oom_check = true;
2434 nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2437 ret = mem_cgroup_do_charge(memcg, gfp_mask, batch, oom_check);
2438 switch (ret) {
2439 case CHARGE_OK:
2440 break;
2441 case CHARGE_RETRY: /* not in OOM situation but retry */
2442 batch = nr_pages;
2443 css_put(&memcg->css);
2444 memcg = NULL;
2445 goto again;
2446 case CHARGE_WOULDBLOCK: /* !__GFP_WAIT */
2447 css_put(&memcg->css);
2448 goto nomem;
2449 case CHARGE_NOMEM: /* OOM routine works */
2450 if (!oom) {
2451 css_put(&memcg->css);
2452 goto nomem;
2454 /* If oom, we never return -ENOMEM */
2455 nr_oom_retries--;
2456 break;
2457 case CHARGE_OOM_DIE: /* Killed by OOM Killer */
2458 css_put(&memcg->css);
2459 goto bypass;
2461 } while (ret != CHARGE_OK);
2463 if (batch > nr_pages)
2464 refill_stock(memcg, batch - nr_pages);
2465 css_put(&memcg->css);
2466 done:
2467 *ptr = memcg;
2468 return 0;
2469 nomem:
2470 *ptr = NULL;
2471 return -ENOMEM;
2472 bypass:
2473 *ptr = NULL;
2474 return 0;
2478 * Somemtimes we have to undo a charge we got by try_charge().
2479 * This function is for that and do uncharge, put css's refcnt.
2480 * gotten by try_charge().
2482 static void __mem_cgroup_cancel_charge(struct mem_cgroup *memcg,
2483 unsigned int nr_pages)
2485 if (!mem_cgroup_is_root(memcg)) {
2486 unsigned long bytes = nr_pages * PAGE_SIZE;
2488 res_counter_uncharge(&memcg->res, bytes);
2489 if (do_swap_account)
2490 res_counter_uncharge(&memcg->memsw, bytes);
2495 * A helper function to get mem_cgroup from ID. must be called under
2496 * rcu_read_lock(). The caller must check css_is_removed() or some if
2497 * it's concern. (dropping refcnt from swap can be called against removed
2498 * memcg.)
2500 static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
2502 struct cgroup_subsys_state *css;
2504 /* ID 0 is unused ID */
2505 if (!id)
2506 return NULL;
2507 css = css_lookup(&mem_cgroup_subsys, id);
2508 if (!css)
2509 return NULL;
2510 return container_of(css, struct mem_cgroup, css);
2513 struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
2515 struct mem_cgroup *memcg = NULL;
2516 struct page_cgroup *pc;
2517 unsigned short id;
2518 swp_entry_t ent;
2520 VM_BUG_ON(!PageLocked(page));
2522 pc = lookup_page_cgroup(page);
2523 lock_page_cgroup(pc);
2524 if (PageCgroupUsed(pc)) {
2525 memcg = pc->mem_cgroup;
2526 if (memcg && !css_tryget(&memcg->css))
2527 memcg = NULL;
2528 } else if (PageSwapCache(page)) {
2529 ent.val = page_private(page);
2530 id = lookup_swap_cgroup(ent);
2531 rcu_read_lock();
2532 memcg = mem_cgroup_lookup(id);
2533 if (memcg && !css_tryget(&memcg->css))
2534 memcg = NULL;
2535 rcu_read_unlock();
2537 unlock_page_cgroup(pc);
2538 return memcg;
2541 static void __mem_cgroup_commit_charge(struct mem_cgroup *memcg,
2542 struct page *page,
2543 unsigned int nr_pages,
2544 struct page_cgroup *pc,
2545 enum charge_type ctype)
2547 lock_page_cgroup(pc);
2548 if (unlikely(PageCgroupUsed(pc))) {
2549 unlock_page_cgroup(pc);
2550 __mem_cgroup_cancel_charge(memcg, nr_pages);
2551 return;
2554 * we don't need page_cgroup_lock about tail pages, becase they are not
2555 * accessed by any other context at this point.
2557 pc->mem_cgroup = memcg;
2559 * We access a page_cgroup asynchronously without lock_page_cgroup().
2560 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
2561 * is accessed after testing USED bit. To make pc->mem_cgroup visible
2562 * before USED bit, we need memory barrier here.
2563 * See mem_cgroup_add_lru_list(), etc.
2565 smp_wmb();
2566 switch (ctype) {
2567 case MEM_CGROUP_CHARGE_TYPE_CACHE:
2568 case MEM_CGROUP_CHARGE_TYPE_SHMEM:
2569 SetPageCgroupCache(pc);
2570 SetPageCgroupUsed(pc);
2571 break;
2572 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
2573 ClearPageCgroupCache(pc);
2574 SetPageCgroupUsed(pc);
2575 break;
2576 default:
2577 break;
2580 mem_cgroup_charge_statistics(memcg, PageCgroupCache(pc), nr_pages);
2581 unlock_page_cgroup(pc);
2583 * "charge_statistics" updated event counter. Then, check it.
2584 * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
2585 * if they exceeds softlimit.
2587 memcg_check_events(memcg, page);
2590 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
2592 #define PCGF_NOCOPY_AT_SPLIT ((1 << PCG_LOCK) | (1 << PCG_MOVE_LOCK) |\
2593 (1 << PCG_ACCT_LRU) | (1 << PCG_MIGRATION))
2595 * Because tail pages are not marked as "used", set it. We're under
2596 * zone->lru_lock, 'splitting on pmd' and compund_lock.
2598 void mem_cgroup_split_huge_fixup(struct page *head, struct page *tail)
2600 struct page_cgroup *head_pc = lookup_page_cgroup(head);
2601 struct page_cgroup *tail_pc = lookup_page_cgroup(tail);
2602 unsigned long flags;
2604 if (mem_cgroup_disabled())
2605 return;
2607 * We have no races with charge/uncharge but will have races with
2608 * page state accounting.
2610 move_lock_page_cgroup(head_pc, &flags);
2612 tail_pc->mem_cgroup = head_pc->mem_cgroup;
2613 smp_wmb(); /* see __commit_charge() */
2614 if (PageCgroupAcctLRU(head_pc)) {
2615 enum lru_list lru;
2616 struct mem_cgroup_per_zone *mz;
2619 * LRU flags cannot be copied because we need to add tail
2620 *.page to LRU by generic call and our hook will be called.
2621 * We hold lru_lock, then, reduce counter directly.
2623 lru = page_lru(head);
2624 mz = page_cgroup_zoneinfo(head_pc->mem_cgroup, head);
2625 MEM_CGROUP_ZSTAT(mz, lru) -= 1;
2627 tail_pc->flags = head_pc->flags & ~PCGF_NOCOPY_AT_SPLIT;
2628 move_unlock_page_cgroup(head_pc, &flags);
2630 #endif
2633 * mem_cgroup_move_account - move account of the page
2634 * @page: the page
2635 * @nr_pages: number of regular pages (>1 for huge pages)
2636 * @pc: page_cgroup of the page.
2637 * @from: mem_cgroup which the page is moved from.
2638 * @to: mem_cgroup which the page is moved to. @from != @to.
2639 * @uncharge: whether we should call uncharge and css_put against @from.
2641 * The caller must confirm following.
2642 * - page is not on LRU (isolate_page() is useful.)
2643 * - compound_lock is held when nr_pages > 1
2645 * This function doesn't do "charge" nor css_get to new cgroup. It should be
2646 * done by a caller(__mem_cgroup_try_charge would be useful). If @uncharge is
2647 * true, this function does "uncharge" from old cgroup, but it doesn't if
2648 * @uncharge is false, so a caller should do "uncharge".
2650 static int mem_cgroup_move_account(struct page *page,
2651 unsigned int nr_pages,
2652 struct page_cgroup *pc,
2653 struct mem_cgroup *from,
2654 struct mem_cgroup *to,
2655 bool uncharge)
2657 unsigned long flags;
2658 int ret;
2660 VM_BUG_ON(from == to);
2661 VM_BUG_ON(PageLRU(page));
2663 * The page is isolated from LRU. So, collapse function
2664 * will not handle this page. But page splitting can happen.
2665 * Do this check under compound_page_lock(). The caller should
2666 * hold it.
2668 ret = -EBUSY;
2669 if (nr_pages > 1 && !PageTransHuge(page))
2670 goto out;
2672 lock_page_cgroup(pc);
2674 ret = -EINVAL;
2675 if (!PageCgroupUsed(pc) || pc->mem_cgroup != from)
2676 goto unlock;
2678 move_lock_page_cgroup(pc, &flags);
2680 if (PageCgroupFileMapped(pc)) {
2681 /* Update mapped_file data for mem_cgroup */
2682 preempt_disable();
2683 __this_cpu_dec(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
2684 __this_cpu_inc(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
2685 preempt_enable();
2687 mem_cgroup_charge_statistics(from, PageCgroupCache(pc), -nr_pages);
2688 if (uncharge)
2689 /* This is not "cancel", but cancel_charge does all we need. */
2690 __mem_cgroup_cancel_charge(from, nr_pages);
2692 /* caller should have done css_get */
2693 pc->mem_cgroup = to;
2694 mem_cgroup_charge_statistics(to, PageCgroupCache(pc), nr_pages);
2696 * We charges against "to" which may not have any tasks. Then, "to"
2697 * can be under rmdir(). But in current implementation, caller of
2698 * this function is just force_empty() and move charge, so it's
2699 * guaranteed that "to" is never removed. So, we don't check rmdir
2700 * status here.
2702 move_unlock_page_cgroup(pc, &flags);
2703 ret = 0;
2704 unlock:
2705 unlock_page_cgroup(pc);
2707 * check events
2709 memcg_check_events(to, page);
2710 memcg_check_events(from, page);
2711 out:
2712 return ret;
2716 * move charges to its parent.
2719 static int mem_cgroup_move_parent(struct page *page,
2720 struct page_cgroup *pc,
2721 struct mem_cgroup *child,
2722 gfp_t gfp_mask)
2724 struct cgroup *cg = child->css.cgroup;
2725 struct cgroup *pcg = cg->parent;
2726 struct mem_cgroup *parent;
2727 unsigned int nr_pages;
2728 unsigned long uninitialized_var(flags);
2729 int ret;
2731 /* Is ROOT ? */
2732 if (!pcg)
2733 return -EINVAL;
2735 ret = -EBUSY;
2736 if (!get_page_unless_zero(page))
2737 goto out;
2738 if (isolate_lru_page(page))
2739 goto put;
2741 nr_pages = hpage_nr_pages(page);
2743 parent = mem_cgroup_from_cont(pcg);
2744 ret = __mem_cgroup_try_charge(NULL, gfp_mask, nr_pages, &parent, false);
2745 if (ret || !parent)
2746 goto put_back;
2748 if (nr_pages > 1)
2749 flags = compound_lock_irqsave(page);
2751 ret = mem_cgroup_move_account(page, nr_pages, pc, child, parent, true);
2752 if (ret)
2753 __mem_cgroup_cancel_charge(parent, nr_pages);
2755 if (nr_pages > 1)
2756 compound_unlock_irqrestore(page, flags);
2757 put_back:
2758 putback_lru_page(page);
2759 put:
2760 put_page(page);
2761 out:
2762 return ret;
2766 * Charge the memory controller for page usage.
2767 * Return
2768 * 0 if the charge was successful
2769 * < 0 if the cgroup is over its limit
2771 static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
2772 gfp_t gfp_mask, enum charge_type ctype)
2774 struct mem_cgroup *memcg = NULL;
2775 unsigned int nr_pages = 1;
2776 struct page_cgroup *pc;
2777 bool oom = true;
2778 int ret;
2780 if (PageTransHuge(page)) {
2781 nr_pages <<= compound_order(page);
2782 VM_BUG_ON(!PageTransHuge(page));
2784 * Never OOM-kill a process for a huge page. The
2785 * fault handler will fall back to regular pages.
2787 oom = false;
2790 pc = lookup_page_cgroup(page);
2791 BUG_ON(!pc); /* XXX: remove this and move pc lookup into commit */
2793 ret = __mem_cgroup_try_charge(mm, gfp_mask, nr_pages, &memcg, oom);
2794 if (ret || !memcg)
2795 return ret;
2797 __mem_cgroup_commit_charge(memcg, page, nr_pages, pc, ctype);
2798 return 0;
2801 int mem_cgroup_newpage_charge(struct page *page,
2802 struct mm_struct *mm, gfp_t gfp_mask)
2804 if (mem_cgroup_disabled())
2805 return 0;
2807 * If already mapped, we don't have to account.
2808 * If page cache, page->mapping has address_space.
2809 * But page->mapping may have out-of-use anon_vma pointer,
2810 * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
2811 * is NULL.
2813 if (page_mapped(page) || (page->mapping && !PageAnon(page)))
2814 return 0;
2815 if (unlikely(!mm))
2816 mm = &init_mm;
2817 return mem_cgroup_charge_common(page, mm, gfp_mask,
2818 MEM_CGROUP_CHARGE_TYPE_MAPPED);
2821 static void
2822 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
2823 enum charge_type ctype);
2825 static void
2826 __mem_cgroup_commit_charge_lrucare(struct page *page, struct mem_cgroup *memcg,
2827 enum charge_type ctype)
2829 struct page_cgroup *pc = lookup_page_cgroup(page);
2831 * In some case, SwapCache, FUSE(splice_buf->radixtree), the page
2832 * is already on LRU. It means the page may on some other page_cgroup's
2833 * LRU. Take care of it.
2835 mem_cgroup_lru_del_before_commit(page);
2836 __mem_cgroup_commit_charge(memcg, page, 1, pc, ctype);
2837 mem_cgroup_lru_add_after_commit(page);
2838 return;
2841 int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
2842 gfp_t gfp_mask)
2844 struct mem_cgroup *memcg = NULL;
2845 int ret;
2847 if (mem_cgroup_disabled())
2848 return 0;
2849 if (PageCompound(page))
2850 return 0;
2852 if (unlikely(!mm))
2853 mm = &init_mm;
2855 if (page_is_file_cache(page)) {
2856 ret = __mem_cgroup_try_charge(mm, gfp_mask, 1, &memcg, true);
2857 if (ret || !memcg)
2858 return ret;
2861 * FUSE reuses pages without going through the final
2862 * put that would remove them from the LRU list, make
2863 * sure that they get relinked properly.
2865 __mem_cgroup_commit_charge_lrucare(page, memcg,
2866 MEM_CGROUP_CHARGE_TYPE_CACHE);
2867 return ret;
2869 /* shmem */
2870 if (PageSwapCache(page)) {
2871 ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &memcg);
2872 if (!ret)
2873 __mem_cgroup_commit_charge_swapin(page, memcg,
2874 MEM_CGROUP_CHARGE_TYPE_SHMEM);
2875 } else
2876 ret = mem_cgroup_charge_common(page, mm, gfp_mask,
2877 MEM_CGROUP_CHARGE_TYPE_SHMEM);
2879 return ret;
2883 * While swap-in, try_charge -> commit or cancel, the page is locked.
2884 * And when try_charge() successfully returns, one refcnt to memcg without
2885 * struct page_cgroup is acquired. This refcnt will be consumed by
2886 * "commit()" or removed by "cancel()"
2888 int mem_cgroup_try_charge_swapin(struct mm_struct *mm,
2889 struct page *page,
2890 gfp_t mask, struct mem_cgroup **ptr)
2892 struct mem_cgroup *memcg;
2893 int ret;
2895 *ptr = NULL;
2897 if (mem_cgroup_disabled())
2898 return 0;
2900 if (!do_swap_account)
2901 goto charge_cur_mm;
2903 * A racing thread's fault, or swapoff, may have already updated
2904 * the pte, and even removed page from swap cache: in those cases
2905 * do_swap_page()'s pte_same() test will fail; but there's also a
2906 * KSM case which does need to charge the page.
2908 if (!PageSwapCache(page))
2909 goto charge_cur_mm;
2910 memcg = try_get_mem_cgroup_from_page(page);
2911 if (!memcg)
2912 goto charge_cur_mm;
2913 *ptr = memcg;
2914 ret = __mem_cgroup_try_charge(NULL, mask, 1, ptr, true);
2915 css_put(&memcg->css);
2916 return ret;
2917 charge_cur_mm:
2918 if (unlikely(!mm))
2919 mm = &init_mm;
2920 return __mem_cgroup_try_charge(mm, mask, 1, ptr, true);
2923 static void
2924 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
2925 enum charge_type ctype)
2927 if (mem_cgroup_disabled())
2928 return;
2929 if (!ptr)
2930 return;
2931 cgroup_exclude_rmdir(&ptr->css);
2933 __mem_cgroup_commit_charge_lrucare(page, ptr, ctype);
2935 * Now swap is on-memory. This means this page may be
2936 * counted both as mem and swap....double count.
2937 * Fix it by uncharging from memsw. Basically, this SwapCache is stable
2938 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
2939 * may call delete_from_swap_cache() before reach here.
2941 if (do_swap_account && PageSwapCache(page)) {
2942 swp_entry_t ent = {.val = page_private(page)};
2943 unsigned short id;
2944 struct mem_cgroup *memcg;
2946 id = swap_cgroup_record(ent, 0);
2947 rcu_read_lock();
2948 memcg = mem_cgroup_lookup(id);
2949 if (memcg) {
2951 * This recorded memcg can be obsolete one. So, avoid
2952 * calling css_tryget
2954 if (!mem_cgroup_is_root(memcg))
2955 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
2956 mem_cgroup_swap_statistics(memcg, false);
2957 mem_cgroup_put(memcg);
2959 rcu_read_unlock();
2962 * At swapin, we may charge account against cgroup which has no tasks.
2963 * So, rmdir()->pre_destroy() can be called while we do this charge.
2964 * In that case, we need to call pre_destroy() again. check it here.
2966 cgroup_release_and_wakeup_rmdir(&ptr->css);
2969 void mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr)
2971 __mem_cgroup_commit_charge_swapin(page, ptr,
2972 MEM_CGROUP_CHARGE_TYPE_MAPPED);
2975 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *memcg)
2977 if (mem_cgroup_disabled())
2978 return;
2979 if (!memcg)
2980 return;
2981 __mem_cgroup_cancel_charge(memcg, 1);
2984 static void mem_cgroup_do_uncharge(struct mem_cgroup *memcg,
2985 unsigned int nr_pages,
2986 const enum charge_type ctype)
2988 struct memcg_batch_info *batch = NULL;
2989 bool uncharge_memsw = true;
2991 /* If swapout, usage of swap doesn't decrease */
2992 if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2993 uncharge_memsw = false;
2995 batch = &current->memcg_batch;
2997 * In usual, we do css_get() when we remember memcg pointer.
2998 * But in this case, we keep res->usage until end of a series of
2999 * uncharges. Then, it's ok to ignore memcg's refcnt.
3001 if (!batch->memcg)
3002 batch->memcg = memcg;
3004 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
3005 * In those cases, all pages freed continuously can be expected to be in
3006 * the same cgroup and we have chance to coalesce uncharges.
3007 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
3008 * because we want to do uncharge as soon as possible.
3011 if (!batch->do_batch || test_thread_flag(TIF_MEMDIE))
3012 goto direct_uncharge;
3014 if (nr_pages > 1)
3015 goto direct_uncharge;
3018 * In typical case, batch->memcg == mem. This means we can
3019 * merge a series of uncharges to an uncharge of res_counter.
3020 * If not, we uncharge res_counter ony by one.
3022 if (batch->memcg != memcg)
3023 goto direct_uncharge;
3024 /* remember freed charge and uncharge it later */
3025 batch->nr_pages++;
3026 if (uncharge_memsw)
3027 batch->memsw_nr_pages++;
3028 return;
3029 direct_uncharge:
3030 res_counter_uncharge(&memcg->res, nr_pages * PAGE_SIZE);
3031 if (uncharge_memsw)
3032 res_counter_uncharge(&memcg->memsw, nr_pages * PAGE_SIZE);
3033 if (unlikely(batch->memcg != memcg))
3034 memcg_oom_recover(memcg);
3035 return;
3039 * uncharge if !page_mapped(page)
3041 static struct mem_cgroup *
3042 __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype)
3044 struct mem_cgroup *memcg = NULL;
3045 unsigned int nr_pages = 1;
3046 struct page_cgroup *pc;
3048 if (mem_cgroup_disabled())
3049 return NULL;
3051 if (PageSwapCache(page))
3052 return NULL;
3054 if (PageTransHuge(page)) {
3055 nr_pages <<= compound_order(page);
3056 VM_BUG_ON(!PageTransHuge(page));
3059 * Check if our page_cgroup is valid
3061 pc = lookup_page_cgroup(page);
3062 if (unlikely(!pc || !PageCgroupUsed(pc)))
3063 return NULL;
3065 lock_page_cgroup(pc);
3067 memcg = pc->mem_cgroup;
3069 if (!PageCgroupUsed(pc))
3070 goto unlock_out;
3072 switch (ctype) {
3073 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
3074 case MEM_CGROUP_CHARGE_TYPE_DROP:
3075 /* See mem_cgroup_prepare_migration() */
3076 if (page_mapped(page) || PageCgroupMigration(pc))
3077 goto unlock_out;
3078 break;
3079 case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
3080 if (!PageAnon(page)) { /* Shared memory */
3081 if (page->mapping && !page_is_file_cache(page))
3082 goto unlock_out;
3083 } else if (page_mapped(page)) /* Anon */
3084 goto unlock_out;
3085 break;
3086 default:
3087 break;
3090 mem_cgroup_charge_statistics(memcg, PageCgroupCache(pc), -nr_pages);
3092 ClearPageCgroupUsed(pc);
3094 * pc->mem_cgroup is not cleared here. It will be accessed when it's
3095 * freed from LRU. This is safe because uncharged page is expected not
3096 * to be reused (freed soon). Exception is SwapCache, it's handled by
3097 * special functions.
3100 unlock_page_cgroup(pc);
3102 * even after unlock, we have memcg->res.usage here and this memcg
3103 * will never be freed.
3105 memcg_check_events(memcg, page);
3106 if (do_swap_account && ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT) {
3107 mem_cgroup_swap_statistics(memcg, true);
3108 mem_cgroup_get(memcg);
3110 if (!mem_cgroup_is_root(memcg))
3111 mem_cgroup_do_uncharge(memcg, nr_pages, ctype);
3113 return memcg;
3115 unlock_out:
3116 unlock_page_cgroup(pc);
3117 return NULL;
3120 void mem_cgroup_uncharge_page(struct page *page)
3122 /* early check. */
3123 if (page_mapped(page))
3124 return;
3125 if (page->mapping && !PageAnon(page))
3126 return;
3127 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_MAPPED);
3130 void mem_cgroup_uncharge_cache_page(struct page *page)
3132 VM_BUG_ON(page_mapped(page));
3133 VM_BUG_ON(page->mapping);
3134 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE);
3138 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
3139 * In that cases, pages are freed continuously and we can expect pages
3140 * are in the same memcg. All these calls itself limits the number of
3141 * pages freed at once, then uncharge_start/end() is called properly.
3142 * This may be called prural(2) times in a context,
3145 void mem_cgroup_uncharge_start(void)
3147 current->memcg_batch.do_batch++;
3148 /* We can do nest. */
3149 if (current->memcg_batch.do_batch == 1) {
3150 current->memcg_batch.memcg = NULL;
3151 current->memcg_batch.nr_pages = 0;
3152 current->memcg_batch.memsw_nr_pages = 0;
3156 void mem_cgroup_uncharge_end(void)
3158 struct memcg_batch_info *batch = &current->memcg_batch;
3160 if (!batch->do_batch)
3161 return;
3163 batch->do_batch--;
3164 if (batch->do_batch) /* If stacked, do nothing. */
3165 return;
3167 if (!batch->memcg)
3168 return;
3170 * This "batch->memcg" is valid without any css_get/put etc...
3171 * bacause we hide charges behind us.
3173 if (batch->nr_pages)
3174 res_counter_uncharge(&batch->memcg->res,
3175 batch->nr_pages * PAGE_SIZE);
3176 if (batch->memsw_nr_pages)
3177 res_counter_uncharge(&batch->memcg->memsw,
3178 batch->memsw_nr_pages * PAGE_SIZE);
3179 memcg_oom_recover(batch->memcg);
3180 /* forget this pointer (for sanity check) */
3181 batch->memcg = NULL;
3184 #ifdef CONFIG_SWAP
3186 * called after __delete_from_swap_cache() and drop "page" account.
3187 * memcg information is recorded to swap_cgroup of "ent"
3189 void
3190 mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
3192 struct mem_cgroup *memcg;
3193 int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
3195 if (!swapout) /* this was a swap cache but the swap is unused ! */
3196 ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
3198 memcg = __mem_cgroup_uncharge_common(page, ctype);
3201 * record memcg information, if swapout && memcg != NULL,
3202 * mem_cgroup_get() was called in uncharge().
3204 if (do_swap_account && swapout && memcg)
3205 swap_cgroup_record(ent, css_id(&memcg->css));
3207 #endif
3209 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3211 * called from swap_entry_free(). remove record in swap_cgroup and
3212 * uncharge "memsw" account.
3214 void mem_cgroup_uncharge_swap(swp_entry_t ent)
3216 struct mem_cgroup *memcg;
3217 unsigned short id;
3219 if (!do_swap_account)
3220 return;
3222 id = swap_cgroup_record(ent, 0);
3223 rcu_read_lock();
3224 memcg = mem_cgroup_lookup(id);
3225 if (memcg) {
3227 * We uncharge this because swap is freed.
3228 * This memcg can be obsolete one. We avoid calling css_tryget
3230 if (!mem_cgroup_is_root(memcg))
3231 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
3232 mem_cgroup_swap_statistics(memcg, false);
3233 mem_cgroup_put(memcg);
3235 rcu_read_unlock();
3239 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3240 * @entry: swap entry to be moved
3241 * @from: mem_cgroup which the entry is moved from
3242 * @to: mem_cgroup which the entry is moved to
3243 * @need_fixup: whether we should fixup res_counters and refcounts.
3245 * It succeeds only when the swap_cgroup's record for this entry is the same
3246 * as the mem_cgroup's id of @from.
3248 * Returns 0 on success, -EINVAL on failure.
3250 * The caller must have charged to @to, IOW, called res_counter_charge() about
3251 * both res and memsw, and called css_get().
3253 static int mem_cgroup_move_swap_account(swp_entry_t entry,
3254 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
3256 unsigned short old_id, new_id;
3258 old_id = css_id(&from->css);
3259 new_id = css_id(&to->css);
3261 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
3262 mem_cgroup_swap_statistics(from, false);
3263 mem_cgroup_swap_statistics(to, true);
3265 * This function is only called from task migration context now.
3266 * It postpones res_counter and refcount handling till the end
3267 * of task migration(mem_cgroup_clear_mc()) for performance
3268 * improvement. But we cannot postpone mem_cgroup_get(to)
3269 * because if the process that has been moved to @to does
3270 * swap-in, the refcount of @to might be decreased to 0.
3272 mem_cgroup_get(to);
3273 if (need_fixup) {
3274 if (!mem_cgroup_is_root(from))
3275 res_counter_uncharge(&from->memsw, PAGE_SIZE);
3276 mem_cgroup_put(from);
3278 * we charged both to->res and to->memsw, so we should
3279 * uncharge to->res.
3281 if (!mem_cgroup_is_root(to))
3282 res_counter_uncharge(&to->res, PAGE_SIZE);
3284 return 0;
3286 return -EINVAL;
3288 #else
3289 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
3290 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
3292 return -EINVAL;
3294 #endif
3297 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
3298 * page belongs to.
3300 int mem_cgroup_prepare_migration(struct page *page,
3301 struct page *newpage, struct mem_cgroup **ptr, gfp_t gfp_mask)
3303 struct mem_cgroup *memcg = NULL;
3304 struct page_cgroup *pc;
3305 enum charge_type ctype;
3306 int ret = 0;
3308 *ptr = NULL;
3310 VM_BUG_ON(PageTransHuge(page));
3311 if (mem_cgroup_disabled())
3312 return 0;
3314 pc = lookup_page_cgroup(page);
3315 lock_page_cgroup(pc);
3316 if (PageCgroupUsed(pc)) {
3317 memcg = pc->mem_cgroup;
3318 css_get(&memcg->css);
3320 * At migrating an anonymous page, its mapcount goes down
3321 * to 0 and uncharge() will be called. But, even if it's fully
3322 * unmapped, migration may fail and this page has to be
3323 * charged again. We set MIGRATION flag here and delay uncharge
3324 * until end_migration() is called
3326 * Corner Case Thinking
3327 * A)
3328 * When the old page was mapped as Anon and it's unmap-and-freed
3329 * while migration was ongoing.
3330 * If unmap finds the old page, uncharge() of it will be delayed
3331 * until end_migration(). If unmap finds a new page, it's
3332 * uncharged when it make mapcount to be 1->0. If unmap code
3333 * finds swap_migration_entry, the new page will not be mapped
3334 * and end_migration() will find it(mapcount==0).
3336 * B)
3337 * When the old page was mapped but migraion fails, the kernel
3338 * remaps it. A charge for it is kept by MIGRATION flag even
3339 * if mapcount goes down to 0. We can do remap successfully
3340 * without charging it again.
3342 * C)
3343 * The "old" page is under lock_page() until the end of
3344 * migration, so, the old page itself will not be swapped-out.
3345 * If the new page is swapped out before end_migraton, our
3346 * hook to usual swap-out path will catch the event.
3348 if (PageAnon(page))
3349 SetPageCgroupMigration(pc);
3351 unlock_page_cgroup(pc);
3353 * If the page is not charged at this point,
3354 * we return here.
3356 if (!memcg)
3357 return 0;
3359 *ptr = memcg;
3360 ret = __mem_cgroup_try_charge(NULL, gfp_mask, 1, ptr, false);
3361 css_put(&memcg->css);/* drop extra refcnt */
3362 if (ret || *ptr == NULL) {
3363 if (PageAnon(page)) {
3364 lock_page_cgroup(pc);
3365 ClearPageCgroupMigration(pc);
3366 unlock_page_cgroup(pc);
3368 * The old page may be fully unmapped while we kept it.
3370 mem_cgroup_uncharge_page(page);
3372 return -ENOMEM;
3375 * We charge new page before it's used/mapped. So, even if unlock_page()
3376 * is called before end_migration, we can catch all events on this new
3377 * page. In the case new page is migrated but not remapped, new page's
3378 * mapcount will be finally 0 and we call uncharge in end_migration().
3380 pc = lookup_page_cgroup(newpage);
3381 if (PageAnon(page))
3382 ctype = MEM_CGROUP_CHARGE_TYPE_MAPPED;
3383 else if (page_is_file_cache(page))
3384 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
3385 else
3386 ctype = MEM_CGROUP_CHARGE_TYPE_SHMEM;
3387 __mem_cgroup_commit_charge(memcg, page, 1, pc, ctype);
3388 return ret;
3391 /* remove redundant charge if migration failed*/
3392 void mem_cgroup_end_migration(struct mem_cgroup *memcg,
3393 struct page *oldpage, struct page *newpage, bool migration_ok)
3395 struct page *used, *unused;
3396 struct page_cgroup *pc;
3398 if (!memcg)
3399 return;
3400 /* blocks rmdir() */
3401 cgroup_exclude_rmdir(&memcg->css);
3402 if (!migration_ok) {
3403 used = oldpage;
3404 unused = newpage;
3405 } else {
3406 used = newpage;
3407 unused = oldpage;
3410 * We disallowed uncharge of pages under migration because mapcount
3411 * of the page goes down to zero, temporarly.
3412 * Clear the flag and check the page should be charged.
3414 pc = lookup_page_cgroup(oldpage);
3415 lock_page_cgroup(pc);
3416 ClearPageCgroupMigration(pc);
3417 unlock_page_cgroup(pc);
3419 __mem_cgroup_uncharge_common(unused, MEM_CGROUP_CHARGE_TYPE_FORCE);
3422 * If a page is a file cache, radix-tree replacement is very atomic
3423 * and we can skip this check. When it was an Anon page, its mapcount
3424 * goes down to 0. But because we added MIGRATION flage, it's not
3425 * uncharged yet. There are several case but page->mapcount check
3426 * and USED bit check in mem_cgroup_uncharge_page() will do enough
3427 * check. (see prepare_charge() also)
3429 if (PageAnon(used))
3430 mem_cgroup_uncharge_page(used);
3432 * At migration, we may charge account against cgroup which has no
3433 * tasks.
3434 * So, rmdir()->pre_destroy() can be called while we do this charge.
3435 * In that case, we need to call pre_destroy() again. check it here.
3437 cgroup_release_and_wakeup_rmdir(&memcg->css);
3440 #ifdef CONFIG_DEBUG_VM
3441 static struct page_cgroup *lookup_page_cgroup_used(struct page *page)
3443 struct page_cgroup *pc;
3445 pc = lookup_page_cgroup(page);
3446 if (likely(pc) && PageCgroupUsed(pc))
3447 return pc;
3448 return NULL;
3451 bool mem_cgroup_bad_page_check(struct page *page)
3453 if (mem_cgroup_disabled())
3454 return false;
3456 return lookup_page_cgroup_used(page) != NULL;
3459 void mem_cgroup_print_bad_page(struct page *page)
3461 struct page_cgroup *pc;
3463 pc = lookup_page_cgroup_used(page);
3464 if (pc) {
3465 int ret = -1;
3466 char *path;
3468 printk(KERN_ALERT "pc:%p pc->flags:%lx pc->mem_cgroup:%p",
3469 pc, pc->flags, pc->mem_cgroup);
3471 path = kmalloc(PATH_MAX, GFP_KERNEL);
3472 if (path) {
3473 rcu_read_lock();
3474 ret = cgroup_path(pc->mem_cgroup->css.cgroup,
3475 path, PATH_MAX);
3476 rcu_read_unlock();
3479 printk(KERN_CONT "(%s)\n",
3480 (ret < 0) ? "cannot get the path" : path);
3481 kfree(path);
3484 #endif
3486 static DEFINE_MUTEX(set_limit_mutex);
3488 static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
3489 unsigned long long val)
3491 int retry_count;
3492 u64 memswlimit, memlimit;
3493 int ret = 0;
3494 int children = mem_cgroup_count_children(memcg);
3495 u64 curusage, oldusage;
3496 int enlarge;
3499 * For keeping hierarchical_reclaim simple, how long we should retry
3500 * is depends on callers. We set our retry-count to be function
3501 * of # of children which we should visit in this loop.
3503 retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
3505 oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
3507 enlarge = 0;
3508 while (retry_count) {
3509 if (signal_pending(current)) {
3510 ret = -EINTR;
3511 break;
3514 * Rather than hide all in some function, I do this in
3515 * open coded manner. You see what this really does.
3516 * We have to guarantee memcg->res.limit < memcg->memsw.limit.
3518 mutex_lock(&set_limit_mutex);
3519 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3520 if (memswlimit < val) {
3521 ret = -EINVAL;
3522 mutex_unlock(&set_limit_mutex);
3523 break;
3526 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3527 if (memlimit < val)
3528 enlarge = 1;
3530 ret = res_counter_set_limit(&memcg->res, val);
3531 if (!ret) {
3532 if (memswlimit == val)
3533 memcg->memsw_is_minimum = true;
3534 else
3535 memcg->memsw_is_minimum = false;
3537 mutex_unlock(&set_limit_mutex);
3539 if (!ret)
3540 break;
3542 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
3543 MEM_CGROUP_RECLAIM_SHRINK,
3544 NULL);
3545 curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
3546 /* Usage is reduced ? */
3547 if (curusage >= oldusage)
3548 retry_count--;
3549 else
3550 oldusage = curusage;
3552 if (!ret && enlarge)
3553 memcg_oom_recover(memcg);
3555 return ret;
3558 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
3559 unsigned long long val)
3561 int retry_count;
3562 u64 memlimit, memswlimit, oldusage, curusage;
3563 int children = mem_cgroup_count_children(memcg);
3564 int ret = -EBUSY;
3565 int enlarge = 0;
3567 /* see mem_cgroup_resize_res_limit */
3568 retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
3569 oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
3570 while (retry_count) {
3571 if (signal_pending(current)) {
3572 ret = -EINTR;
3573 break;
3576 * Rather than hide all in some function, I do this in
3577 * open coded manner. You see what this really does.
3578 * We have to guarantee memcg->res.limit < memcg->memsw.limit.
3580 mutex_lock(&set_limit_mutex);
3581 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3582 if (memlimit > val) {
3583 ret = -EINVAL;
3584 mutex_unlock(&set_limit_mutex);
3585 break;
3587 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3588 if (memswlimit < val)
3589 enlarge = 1;
3590 ret = res_counter_set_limit(&memcg->memsw, val);
3591 if (!ret) {
3592 if (memlimit == val)
3593 memcg->memsw_is_minimum = true;
3594 else
3595 memcg->memsw_is_minimum = false;
3597 mutex_unlock(&set_limit_mutex);
3599 if (!ret)
3600 break;
3602 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
3603 MEM_CGROUP_RECLAIM_NOSWAP |
3604 MEM_CGROUP_RECLAIM_SHRINK,
3605 NULL);
3606 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
3607 /* Usage is reduced ? */
3608 if (curusage >= oldusage)
3609 retry_count--;
3610 else
3611 oldusage = curusage;
3613 if (!ret && enlarge)
3614 memcg_oom_recover(memcg);
3615 return ret;
3618 unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
3619 gfp_t gfp_mask,
3620 unsigned long *total_scanned)
3622 unsigned long nr_reclaimed = 0;
3623 struct mem_cgroup_per_zone *mz, *next_mz = NULL;
3624 unsigned long reclaimed;
3625 int loop = 0;
3626 struct mem_cgroup_tree_per_zone *mctz;
3627 unsigned long long excess;
3628 unsigned long nr_scanned;
3630 if (order > 0)
3631 return 0;
3633 mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone));
3635 * This loop can run a while, specially if mem_cgroup's continuously
3636 * keep exceeding their soft limit and putting the system under
3637 * pressure
3639 do {
3640 if (next_mz)
3641 mz = next_mz;
3642 else
3643 mz = mem_cgroup_largest_soft_limit_node(mctz);
3644 if (!mz)
3645 break;
3647 nr_scanned = 0;
3648 reclaimed = mem_cgroup_hierarchical_reclaim(mz->mem, zone,
3649 gfp_mask,
3650 MEM_CGROUP_RECLAIM_SOFT,
3651 &nr_scanned);
3652 nr_reclaimed += reclaimed;
3653 *total_scanned += nr_scanned;
3654 spin_lock(&mctz->lock);
3657 * If we failed to reclaim anything from this memory cgroup
3658 * it is time to move on to the next cgroup
3660 next_mz = NULL;
3661 if (!reclaimed) {
3662 do {
3664 * Loop until we find yet another one.
3666 * By the time we get the soft_limit lock
3667 * again, someone might have aded the
3668 * group back on the RB tree. Iterate to
3669 * make sure we get a different mem.
3670 * mem_cgroup_largest_soft_limit_node returns
3671 * NULL if no other cgroup is present on
3672 * the tree
3674 next_mz =
3675 __mem_cgroup_largest_soft_limit_node(mctz);
3676 if (next_mz == mz)
3677 css_put(&next_mz->mem->css);
3678 else /* next_mz == NULL or other memcg */
3679 break;
3680 } while (1);
3682 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
3683 excess = res_counter_soft_limit_excess(&mz->mem->res);
3685 * One school of thought says that we should not add
3686 * back the node to the tree if reclaim returns 0.
3687 * But our reclaim could return 0, simply because due
3688 * to priority we are exposing a smaller subset of
3689 * memory to reclaim from. Consider this as a longer
3690 * term TODO.
3692 /* If excess == 0, no tree ops */
3693 __mem_cgroup_insert_exceeded(mz->mem, mz, mctz, excess);
3694 spin_unlock(&mctz->lock);
3695 css_put(&mz->mem->css);
3696 loop++;
3698 * Could not reclaim anything and there are no more
3699 * mem cgroups to try or we seem to be looping without
3700 * reclaiming anything.
3702 if (!nr_reclaimed &&
3703 (next_mz == NULL ||
3704 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3705 break;
3706 } while (!nr_reclaimed);
3707 if (next_mz)
3708 css_put(&next_mz->mem->css);
3709 return nr_reclaimed;
3713 * This routine traverse page_cgroup in given list and drop them all.
3714 * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
3716 static int mem_cgroup_force_empty_list(struct mem_cgroup *memcg,
3717 int node, int zid, enum lru_list lru)
3719 struct zone *zone;
3720 struct mem_cgroup_per_zone *mz;
3721 struct page_cgroup *pc, *busy;
3722 unsigned long flags, loop;
3723 struct list_head *list;
3724 int ret = 0;
3726 zone = &NODE_DATA(node)->node_zones[zid];
3727 mz = mem_cgroup_zoneinfo(memcg, node, zid);
3728 list = &mz->lists[lru];
3730 loop = MEM_CGROUP_ZSTAT(mz, lru);
3731 /* give some margin against EBUSY etc...*/
3732 loop += 256;
3733 busy = NULL;
3734 while (loop--) {
3735 struct page *page;
3737 ret = 0;
3738 spin_lock_irqsave(&zone->lru_lock, flags);
3739 if (list_empty(list)) {
3740 spin_unlock_irqrestore(&zone->lru_lock, flags);
3741 break;
3743 pc = list_entry(list->prev, struct page_cgroup, lru);
3744 if (busy == pc) {
3745 list_move(&pc->lru, list);
3746 busy = NULL;
3747 spin_unlock_irqrestore(&zone->lru_lock, flags);
3748 continue;
3750 spin_unlock_irqrestore(&zone->lru_lock, flags);
3752 page = lookup_cgroup_page(pc);
3754 ret = mem_cgroup_move_parent(page, pc, memcg, GFP_KERNEL);
3755 if (ret == -ENOMEM)
3756 break;
3758 if (ret == -EBUSY || ret == -EINVAL) {
3759 /* found lock contention or "pc" is obsolete. */
3760 busy = pc;
3761 cond_resched();
3762 } else
3763 busy = NULL;
3766 if (!ret && !list_empty(list))
3767 return -EBUSY;
3768 return ret;
3772 * make mem_cgroup's charge to be 0 if there is no task.
3773 * This enables deleting this mem_cgroup.
3775 static int mem_cgroup_force_empty(struct mem_cgroup *memcg, bool free_all)
3777 int ret;
3778 int node, zid, shrink;
3779 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
3780 struct cgroup *cgrp = memcg->css.cgroup;
3782 css_get(&memcg->css);
3784 shrink = 0;
3785 /* should free all ? */
3786 if (free_all)
3787 goto try_to_free;
3788 move_account:
3789 do {
3790 ret = -EBUSY;
3791 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
3792 goto out;
3793 ret = -EINTR;
3794 if (signal_pending(current))
3795 goto out;
3796 /* This is for making all *used* pages to be on LRU. */
3797 lru_add_drain_all();
3798 drain_all_stock_sync(memcg);
3799 ret = 0;
3800 mem_cgroup_start_move(memcg);
3801 for_each_node_state(node, N_HIGH_MEMORY) {
3802 for (zid = 0; !ret && zid < MAX_NR_ZONES; zid++) {
3803 enum lru_list l;
3804 for_each_lru(l) {
3805 ret = mem_cgroup_force_empty_list(memcg,
3806 node, zid, l);
3807 if (ret)
3808 break;
3811 if (ret)
3812 break;
3814 mem_cgroup_end_move(memcg);
3815 memcg_oom_recover(memcg);
3816 /* it seems parent cgroup doesn't have enough mem */
3817 if (ret == -ENOMEM)
3818 goto try_to_free;
3819 cond_resched();
3820 /* "ret" should also be checked to ensure all lists are empty. */
3821 } while (memcg->res.usage > 0 || ret);
3822 out:
3823 css_put(&memcg->css);
3824 return ret;
3826 try_to_free:
3827 /* returns EBUSY if there is a task or if we come here twice. */
3828 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children) || shrink) {
3829 ret = -EBUSY;
3830 goto out;
3832 /* we call try-to-free pages for make this cgroup empty */
3833 lru_add_drain_all();
3834 /* try to free all pages in this cgroup */
3835 shrink = 1;
3836 while (nr_retries && memcg->res.usage > 0) {
3837 int progress;
3839 if (signal_pending(current)) {
3840 ret = -EINTR;
3841 goto out;
3843 progress = try_to_free_mem_cgroup_pages(memcg, GFP_KERNEL,
3844 false);
3845 if (!progress) {
3846 nr_retries--;
3847 /* maybe some writeback is necessary */
3848 congestion_wait(BLK_RW_ASYNC, HZ/10);
3852 lru_add_drain();
3853 /* try move_account...there may be some *locked* pages. */
3854 goto move_account;
3857 int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
3859 return mem_cgroup_force_empty(mem_cgroup_from_cont(cont), true);
3863 static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
3865 return mem_cgroup_from_cont(cont)->use_hierarchy;
3868 static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
3869 u64 val)
3871 int retval = 0;
3872 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
3873 struct cgroup *parent = cont->parent;
3874 struct mem_cgroup *parent_memcg = NULL;
3876 if (parent)
3877 parent_memcg = mem_cgroup_from_cont(parent);
3879 cgroup_lock();
3881 * If parent's use_hierarchy is set, we can't make any modifications
3882 * in the child subtrees. If it is unset, then the change can
3883 * occur, provided the current cgroup has no children.
3885 * For the root cgroup, parent_mem is NULL, we allow value to be
3886 * set if there are no children.
3888 if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
3889 (val == 1 || val == 0)) {
3890 if (list_empty(&cont->children))
3891 memcg->use_hierarchy = val;
3892 else
3893 retval = -EBUSY;
3894 } else
3895 retval = -EINVAL;
3896 cgroup_unlock();
3898 return retval;
3902 static unsigned long mem_cgroup_recursive_stat(struct mem_cgroup *memcg,
3903 enum mem_cgroup_stat_index idx)
3905 struct mem_cgroup *iter;
3906 long val = 0;
3908 /* Per-cpu values can be negative, use a signed accumulator */
3909 for_each_mem_cgroup_tree(iter, memcg)
3910 val += mem_cgroup_read_stat(iter, idx);
3912 if (val < 0) /* race ? */
3913 val = 0;
3914 return val;
3917 static inline u64 mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
3919 u64 val;
3921 if (!mem_cgroup_is_root(memcg)) {
3922 val = 0;
3923 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_KMEM
3924 if (!memcg->kmem_independent_accounting)
3925 val = res_counter_read_u64(&memcg->kmem, RES_USAGE);
3926 #endif
3927 if (!swap)
3928 val += res_counter_read_u64(&memcg->res, RES_USAGE);
3929 else
3930 val += res_counter_read_u64(&memcg->memsw, RES_USAGE);
3932 return val;
3935 val = mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_CACHE);
3936 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_RSS);
3938 if (swap)
3939 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_SWAPOUT);
3941 return val << PAGE_SHIFT;
3944 static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft)
3946 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
3947 u64 val;
3948 int type, name;
3950 type = MEMFILE_TYPE(cft->private);
3951 name = MEMFILE_ATTR(cft->private);
3952 switch (type) {
3953 case _MEM:
3954 if (name == RES_USAGE)
3955 val = mem_cgroup_usage(memcg, false);
3956 else
3957 val = res_counter_read_u64(&memcg->res, name);
3958 break;
3959 case _MEMSWAP:
3960 if (name == RES_USAGE)
3961 val = mem_cgroup_usage(memcg, true);
3962 else
3963 val = res_counter_read_u64(&memcg->memsw, name);
3964 break;
3965 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_KMEM
3966 case _KMEM:
3967 val = res_counter_read_u64(&memcg->kmem, name);
3968 break;
3969 #endif
3970 default:
3971 BUG();
3972 break;
3974 return val;
3977 * The user of this function is...
3978 * RES_LIMIT.
3980 static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
3981 const char *buffer)
3983 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
3984 int type, name;
3985 unsigned long long val;
3986 int ret;
3988 type = MEMFILE_TYPE(cft->private);
3989 name = MEMFILE_ATTR(cft->private);
3990 switch (name) {
3991 case RES_LIMIT:
3992 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3993 ret = -EINVAL;
3994 break;
3996 /* This function does all necessary parse...reuse it */
3997 ret = res_counter_memparse_write_strategy(buffer, &val);
3998 if (ret)
3999 break;
4000 if (type == _MEM)
4001 ret = mem_cgroup_resize_limit(memcg, val);
4002 else
4003 ret = mem_cgroup_resize_memsw_limit(memcg, val);
4004 break;
4005 case RES_SOFT_LIMIT:
4006 ret = res_counter_memparse_write_strategy(buffer, &val);
4007 if (ret)
4008 break;
4010 * For memsw, soft limits are hard to implement in terms
4011 * of semantics, for now, we support soft limits for
4012 * control without swap
4014 if (type == _MEM)
4015 ret = res_counter_set_soft_limit(&memcg->res, val);
4016 else
4017 ret = -EINVAL;
4018 break;
4019 default:
4020 ret = -EINVAL; /* should be BUG() ? */
4021 break;
4023 return ret;
4026 static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
4027 unsigned long long *mem_limit, unsigned long long *memsw_limit)
4029 struct cgroup *cgroup;
4030 unsigned long long min_limit, min_memsw_limit, tmp;
4032 min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
4033 min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
4034 cgroup = memcg->css.cgroup;
4035 if (!memcg->use_hierarchy)
4036 goto out;
4038 while (cgroup->parent) {
4039 cgroup = cgroup->parent;
4040 memcg = mem_cgroup_from_cont(cgroup);
4041 if (!memcg->use_hierarchy)
4042 break;
4043 tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
4044 min_limit = min(min_limit, tmp);
4045 tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
4046 min_memsw_limit = min(min_memsw_limit, tmp);
4048 out:
4049 *mem_limit = min_limit;
4050 *memsw_limit = min_memsw_limit;
4051 return;
4054 static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
4056 struct mem_cgroup *memcg;
4057 int type, name;
4059 memcg = mem_cgroup_from_cont(cont);
4060 type = MEMFILE_TYPE(event);
4061 name = MEMFILE_ATTR(event);
4062 switch (name) {
4063 case RES_MAX_USAGE:
4064 if (type == _MEM)
4065 res_counter_reset_max(&memcg->res);
4066 else
4067 res_counter_reset_max(&memcg->memsw);
4068 break;
4069 case RES_FAILCNT:
4070 if (type == _MEM)
4071 res_counter_reset_failcnt(&memcg->res);
4072 else
4073 res_counter_reset_failcnt(&memcg->memsw);
4074 break;
4077 return 0;
4080 static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp,
4081 struct cftype *cft)
4083 return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate;
4086 #ifdef CONFIG_MMU
4087 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
4088 struct cftype *cft, u64 val)
4090 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4092 if (val >= (1 << NR_MOVE_TYPE))
4093 return -EINVAL;
4095 * We check this value several times in both in can_attach() and
4096 * attach(), so we need cgroup lock to prevent this value from being
4097 * inconsistent.
4099 cgroup_lock();
4100 memcg->move_charge_at_immigrate = val;
4101 cgroup_unlock();
4103 return 0;
4105 #else
4106 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
4107 struct cftype *cft, u64 val)
4109 return -ENOSYS;
4111 #endif
4114 /* For read statistics */
4115 enum {
4116 MCS_CACHE,
4117 MCS_RSS,
4118 MCS_FILE_MAPPED,
4119 MCS_PGPGIN,
4120 MCS_PGPGOUT,
4121 MCS_SWAP,
4122 MCS_PGFAULT,
4123 MCS_PGMAJFAULT,
4124 MCS_INACTIVE_ANON,
4125 MCS_ACTIVE_ANON,
4126 MCS_INACTIVE_FILE,
4127 MCS_ACTIVE_FILE,
4128 MCS_UNEVICTABLE,
4129 NR_MCS_STAT,
4132 struct mcs_total_stat {
4133 s64 stat[NR_MCS_STAT];
4136 struct {
4137 char *local_name;
4138 char *total_name;
4139 } memcg_stat_strings[NR_MCS_STAT] = {
4140 {"cache", "total_cache"},
4141 {"rss", "total_rss"},
4142 {"mapped_file", "total_mapped_file"},
4143 {"pgpgin", "total_pgpgin"},
4144 {"pgpgout", "total_pgpgout"},
4145 {"swap", "total_swap"},
4146 {"pgfault", "total_pgfault"},
4147 {"pgmajfault", "total_pgmajfault"},
4148 {"inactive_anon", "total_inactive_anon"},
4149 {"active_anon", "total_active_anon"},
4150 {"inactive_file", "total_inactive_file"},
4151 {"active_file", "total_active_file"},
4152 {"unevictable", "total_unevictable"}
4156 static void
4157 mem_cgroup_get_local_stat(struct mem_cgroup *memcg, struct mcs_total_stat *s)
4159 s64 val;
4161 /* per cpu stat */
4162 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_CACHE);
4163 s->stat[MCS_CACHE] += val * PAGE_SIZE;
4164 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_RSS);
4165 s->stat[MCS_RSS] += val * PAGE_SIZE;
4166 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_FILE_MAPPED);
4167 s->stat[MCS_FILE_MAPPED] += val * PAGE_SIZE;
4168 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGPGIN);
4169 s->stat[MCS_PGPGIN] += val;
4170 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGPGOUT);
4171 s->stat[MCS_PGPGOUT] += val;
4172 if (do_swap_account) {
4173 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_SWAPOUT);
4174 s->stat[MCS_SWAP] += val * PAGE_SIZE;
4176 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGFAULT);
4177 s->stat[MCS_PGFAULT] += val;
4178 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGMAJFAULT);
4179 s->stat[MCS_PGMAJFAULT] += val;
4181 /* per zone stat */
4182 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_INACTIVE_ANON));
4183 s->stat[MCS_INACTIVE_ANON] += val * PAGE_SIZE;
4184 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_ACTIVE_ANON));
4185 s->stat[MCS_ACTIVE_ANON] += val * PAGE_SIZE;
4186 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_INACTIVE_FILE));
4187 s->stat[MCS_INACTIVE_FILE] += val * PAGE_SIZE;
4188 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_ACTIVE_FILE));
4189 s->stat[MCS_ACTIVE_FILE] += val * PAGE_SIZE;
4190 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_UNEVICTABLE));
4191 s->stat[MCS_UNEVICTABLE] += val * PAGE_SIZE;
4194 static void
4195 mem_cgroup_get_total_stat(struct mem_cgroup *memcg, struct mcs_total_stat *s)
4197 struct mem_cgroup *iter;
4199 for_each_mem_cgroup_tree(iter, memcg)
4200 mem_cgroup_get_local_stat(iter, s);
4203 #ifdef CONFIG_NUMA
4204 static int mem_control_numa_stat_show(struct seq_file *m, void *arg)
4206 int nid;
4207 unsigned long total_nr, file_nr, anon_nr, unevictable_nr;
4208 unsigned long node_nr;
4209 struct cgroup *cont = m->private;
4210 struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
4212 total_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL);
4213 seq_printf(m, "total=%lu", total_nr);
4214 for_each_node_state(nid, N_HIGH_MEMORY) {
4215 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid, LRU_ALL);
4216 seq_printf(m, " N%d=%lu", nid, node_nr);
4218 seq_putc(m, '\n');
4220 file_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL_FILE);
4221 seq_printf(m, "file=%lu", file_nr);
4222 for_each_node_state(nid, N_HIGH_MEMORY) {
4223 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4224 LRU_ALL_FILE);
4225 seq_printf(m, " N%d=%lu", nid, node_nr);
4227 seq_putc(m, '\n');
4229 anon_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL_ANON);
4230 seq_printf(m, "anon=%lu", anon_nr);
4231 for_each_node_state(nid, N_HIGH_MEMORY) {
4232 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4233 LRU_ALL_ANON);
4234 seq_printf(m, " N%d=%lu", nid, node_nr);
4236 seq_putc(m, '\n');
4238 unevictable_nr = mem_cgroup_nr_lru_pages(mem_cont, BIT(LRU_UNEVICTABLE));
4239 seq_printf(m, "unevictable=%lu", unevictable_nr);
4240 for_each_node_state(nid, N_HIGH_MEMORY) {
4241 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4242 BIT(LRU_UNEVICTABLE));
4243 seq_printf(m, " N%d=%lu", nid, node_nr);
4245 seq_putc(m, '\n');
4246 return 0;
4248 #endif /* CONFIG_NUMA */
4250 static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft,
4251 struct cgroup_map_cb *cb)
4253 struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
4254 struct mcs_total_stat mystat;
4255 int i;
4257 memset(&mystat, 0, sizeof(mystat));
4258 mem_cgroup_get_local_stat(mem_cont, &mystat);
4261 for (i = 0; i < NR_MCS_STAT; i++) {
4262 if (i == MCS_SWAP && !do_swap_account)
4263 continue;
4264 cb->fill(cb, memcg_stat_strings[i].local_name, mystat.stat[i]);
4267 /* Hierarchical information */
4269 unsigned long long limit, memsw_limit;
4270 memcg_get_hierarchical_limit(mem_cont, &limit, &memsw_limit);
4271 cb->fill(cb, "hierarchical_memory_limit", limit);
4272 if (do_swap_account)
4273 cb->fill(cb, "hierarchical_memsw_limit", memsw_limit);
4276 memset(&mystat, 0, sizeof(mystat));
4277 mem_cgroup_get_total_stat(mem_cont, &mystat);
4278 for (i = 0; i < NR_MCS_STAT; i++) {
4279 if (i == MCS_SWAP && !do_swap_account)
4280 continue;
4281 cb->fill(cb, memcg_stat_strings[i].total_name, mystat.stat[i]);
4284 #ifdef CONFIG_DEBUG_VM
4286 int nid, zid;
4287 struct mem_cgroup_per_zone *mz;
4288 unsigned long recent_rotated[2] = {0, 0};
4289 unsigned long recent_scanned[2] = {0, 0};
4291 for_each_online_node(nid)
4292 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
4293 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
4295 recent_rotated[0] +=
4296 mz->reclaim_stat.recent_rotated[0];
4297 recent_rotated[1] +=
4298 mz->reclaim_stat.recent_rotated[1];
4299 recent_scanned[0] +=
4300 mz->reclaim_stat.recent_scanned[0];
4301 recent_scanned[1] +=
4302 mz->reclaim_stat.recent_scanned[1];
4304 cb->fill(cb, "recent_rotated_anon", recent_rotated[0]);
4305 cb->fill(cb, "recent_rotated_file", recent_rotated[1]);
4306 cb->fill(cb, "recent_scanned_anon", recent_scanned[0]);
4307 cb->fill(cb, "recent_scanned_file", recent_scanned[1]);
4309 #endif
4311 return 0;
4314 static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
4316 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4318 return mem_cgroup_swappiness(memcg);
4321 static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
4322 u64 val)
4324 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4325 struct mem_cgroup *parent;
4327 if (val > 100)
4328 return -EINVAL;
4330 if (cgrp->parent == NULL)
4331 return -EINVAL;
4333 parent = mem_cgroup_from_cont(cgrp->parent);
4335 cgroup_lock();
4337 /* If under hierarchy, only empty-root can set this value */
4338 if ((parent->use_hierarchy) ||
4339 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
4340 cgroup_unlock();
4341 return -EINVAL;
4344 memcg->swappiness = val;
4346 cgroup_unlock();
4348 return 0;
4351 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4353 struct mem_cgroup_threshold_ary *t;
4354 u64 usage;
4355 int i;
4357 rcu_read_lock();
4358 if (!swap)
4359 t = rcu_dereference(memcg->thresholds.primary);
4360 else
4361 t = rcu_dereference(memcg->memsw_thresholds.primary);
4363 if (!t)
4364 goto unlock;
4366 usage = mem_cgroup_usage(memcg, swap);
4369 * current_threshold points to threshold just below usage.
4370 * If it's not true, a threshold was crossed after last
4371 * call of __mem_cgroup_threshold().
4373 i = t->current_threshold;
4376 * Iterate backward over array of thresholds starting from
4377 * current_threshold and check if a threshold is crossed.
4378 * If none of thresholds below usage is crossed, we read
4379 * only one element of the array here.
4381 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4382 eventfd_signal(t->entries[i].eventfd, 1);
4384 /* i = current_threshold + 1 */
4385 i++;
4388 * Iterate forward over array of thresholds starting from
4389 * current_threshold+1 and check if a threshold is crossed.
4390 * If none of thresholds above usage is crossed, we read
4391 * only one element of the array here.
4393 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4394 eventfd_signal(t->entries[i].eventfd, 1);
4396 /* Update current_threshold */
4397 t->current_threshold = i - 1;
4398 unlock:
4399 rcu_read_unlock();
4402 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4404 while (memcg) {
4405 __mem_cgroup_threshold(memcg, false);
4406 if (do_swap_account)
4407 __mem_cgroup_threshold(memcg, true);
4409 memcg = parent_mem_cgroup(memcg);
4413 static int compare_thresholds(const void *a, const void *b)
4415 const struct mem_cgroup_threshold *_a = a;
4416 const struct mem_cgroup_threshold *_b = b;
4418 return _a->threshold - _b->threshold;
4421 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
4423 struct mem_cgroup_eventfd_list *ev;
4425 list_for_each_entry(ev, &memcg->oom_notify, list)
4426 eventfd_signal(ev->eventfd, 1);
4427 return 0;
4430 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
4432 struct mem_cgroup *iter;
4434 for_each_mem_cgroup_tree(iter, memcg)
4435 mem_cgroup_oom_notify_cb(iter);
4438 static int mem_cgroup_usage_register_event(struct cgroup *cgrp,
4439 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
4441 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4442 struct mem_cgroup_thresholds *thresholds;
4443 struct mem_cgroup_threshold_ary *new;
4444 int type = MEMFILE_TYPE(cft->private);
4445 u64 threshold, usage;
4446 int i, size, ret;
4448 ret = res_counter_memparse_write_strategy(args, &threshold);
4449 if (ret)
4450 return ret;
4452 mutex_lock(&memcg->thresholds_lock);
4454 if (type == _MEM)
4455 thresholds = &memcg->thresholds;
4456 else if (type == _MEMSWAP)
4457 thresholds = &memcg->memsw_thresholds;
4458 else
4459 BUG();
4461 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
4463 /* Check if a threshold crossed before adding a new one */
4464 if (thresholds->primary)
4465 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4467 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
4469 /* Allocate memory for new array of thresholds */
4470 new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
4471 GFP_KERNEL);
4472 if (!new) {
4473 ret = -ENOMEM;
4474 goto unlock;
4476 new->size = size;
4478 /* Copy thresholds (if any) to new array */
4479 if (thresholds->primary) {
4480 memcpy(new->entries, thresholds->primary->entries, (size - 1) *
4481 sizeof(struct mem_cgroup_threshold));
4484 /* Add new threshold */
4485 new->entries[size - 1].eventfd = eventfd;
4486 new->entries[size - 1].threshold = threshold;
4488 /* Sort thresholds. Registering of new threshold isn't time-critical */
4489 sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
4490 compare_thresholds, NULL);
4492 /* Find current threshold */
4493 new->current_threshold = -1;
4494 for (i = 0; i < size; i++) {
4495 if (new->entries[i].threshold < usage) {
4497 * new->current_threshold will not be used until
4498 * rcu_assign_pointer(), so it's safe to increment
4499 * it here.
4501 ++new->current_threshold;
4505 /* Free old spare buffer and save old primary buffer as spare */
4506 kfree(thresholds->spare);
4507 thresholds->spare = thresholds->primary;
4509 rcu_assign_pointer(thresholds->primary, new);
4511 /* To be sure that nobody uses thresholds */
4512 synchronize_rcu();
4514 unlock:
4515 mutex_unlock(&memcg->thresholds_lock);
4517 return ret;
4520 static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,
4521 struct cftype *cft, struct eventfd_ctx *eventfd)
4523 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4524 struct mem_cgroup_thresholds *thresholds;
4525 struct mem_cgroup_threshold_ary *new;
4526 int type = MEMFILE_TYPE(cft->private);
4527 u64 usage;
4528 int i, j, size;
4530 mutex_lock(&memcg->thresholds_lock);
4531 if (type == _MEM)
4532 thresholds = &memcg->thresholds;
4533 else if (type == _MEMSWAP)
4534 thresholds = &memcg->memsw_thresholds;
4535 else
4536 BUG();
4539 * Something went wrong if we trying to unregister a threshold
4540 * if we don't have thresholds
4542 BUG_ON(!thresholds);
4544 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
4546 /* Check if a threshold crossed before removing */
4547 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4549 /* Calculate new number of threshold */
4550 size = 0;
4551 for (i = 0; i < thresholds->primary->size; i++) {
4552 if (thresholds->primary->entries[i].eventfd != eventfd)
4553 size++;
4556 new = thresholds->spare;
4558 /* Set thresholds array to NULL if we don't have thresholds */
4559 if (!size) {
4560 kfree(new);
4561 new = NULL;
4562 goto swap_buffers;
4565 new->size = size;
4567 /* Copy thresholds and find current threshold */
4568 new->current_threshold = -1;
4569 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4570 if (thresholds->primary->entries[i].eventfd == eventfd)
4571 continue;
4573 new->entries[j] = thresholds->primary->entries[i];
4574 if (new->entries[j].threshold < usage) {
4576 * new->current_threshold will not be used
4577 * until rcu_assign_pointer(), so it's safe to increment
4578 * it here.
4580 ++new->current_threshold;
4582 j++;
4585 swap_buffers:
4586 /* Swap primary and spare array */
4587 thresholds->spare = thresholds->primary;
4588 rcu_assign_pointer(thresholds->primary, new);
4590 /* To be sure that nobody uses thresholds */
4591 synchronize_rcu();
4593 mutex_unlock(&memcg->thresholds_lock);
4596 static int mem_cgroup_oom_register_event(struct cgroup *cgrp,
4597 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
4599 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4600 struct mem_cgroup_eventfd_list *event;
4601 int type = MEMFILE_TYPE(cft->private);
4603 BUG_ON(type != _OOM_TYPE);
4604 event = kmalloc(sizeof(*event), GFP_KERNEL);
4605 if (!event)
4606 return -ENOMEM;
4608 spin_lock(&memcg_oom_lock);
4610 event->eventfd = eventfd;
4611 list_add(&event->list, &memcg->oom_notify);
4613 /* already in OOM ? */
4614 if (atomic_read(&memcg->under_oom))
4615 eventfd_signal(eventfd, 1);
4616 spin_unlock(&memcg_oom_lock);
4618 return 0;
4621 static void mem_cgroup_oom_unregister_event(struct cgroup *cgrp,
4622 struct cftype *cft, struct eventfd_ctx *eventfd)
4624 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4625 struct mem_cgroup_eventfd_list *ev, *tmp;
4626 int type = MEMFILE_TYPE(cft->private);
4628 BUG_ON(type != _OOM_TYPE);
4630 spin_lock(&memcg_oom_lock);
4632 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
4633 if (ev->eventfd == eventfd) {
4634 list_del(&ev->list);
4635 kfree(ev);
4639 spin_unlock(&memcg_oom_lock);
4642 static int mem_cgroup_oom_control_read(struct cgroup *cgrp,
4643 struct cftype *cft, struct cgroup_map_cb *cb)
4645 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4647 cb->fill(cb, "oom_kill_disable", memcg->oom_kill_disable);
4649 if (atomic_read(&memcg->under_oom))
4650 cb->fill(cb, "under_oom", 1);
4651 else
4652 cb->fill(cb, "under_oom", 0);
4653 return 0;
4656 static int mem_cgroup_oom_control_write(struct cgroup *cgrp,
4657 struct cftype *cft, u64 val)
4659 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4660 struct mem_cgroup *parent;
4662 /* cannot set to root cgroup and only 0 and 1 are allowed */
4663 if (!cgrp->parent || !((val == 0) || (val == 1)))
4664 return -EINVAL;
4666 parent = mem_cgroup_from_cont(cgrp->parent);
4668 cgroup_lock();
4669 /* oom-kill-disable is a flag for subhierarchy. */
4670 if ((parent->use_hierarchy) ||
4671 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
4672 cgroup_unlock();
4673 return -EINVAL;
4675 memcg->oom_kill_disable = val;
4676 if (!val)
4677 memcg_oom_recover(memcg);
4678 cgroup_unlock();
4679 return 0;
4682 #ifdef CONFIG_NUMA
4683 static const struct file_operations mem_control_numa_stat_file_operations = {
4684 .read = seq_read,
4685 .llseek = seq_lseek,
4686 .release = single_release,
4689 static int mem_control_numa_stat_open(struct inode *unused, struct file *file)
4691 struct cgroup *cont = file->f_dentry->d_parent->d_fsdata;
4693 file->f_op = &mem_control_numa_stat_file_operations;
4694 return single_open(file, mem_control_numa_stat_show, cont);
4696 #endif /* CONFIG_NUMA */
4698 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_KMEM
4699 static u64 kmem_limit_independent_read(struct cgroup *cgroup, struct cftype *cft)
4701 return mem_cgroup_from_cont(cgroup)->kmem_independent_accounting;
4704 static int kmem_limit_independent_write(struct cgroup *cgroup, struct cftype *cft,
4705 u64 val)
4707 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgroup);
4708 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
4710 val = !!val;
4713 * This follows the same hierarchy restrictions than
4714 * mem_cgroup_hierarchy_write()
4716 if (!parent || !parent->use_hierarchy) {
4717 if (list_empty(&cgroup->children))
4718 memcg->kmem_independent_accounting = val;
4719 else
4720 return -EBUSY;
4722 else
4723 return -EINVAL;
4725 return 0;
4727 static struct cftype kmem_cgroup_files[] = {
4729 .name = "independent_kmem_limit",
4730 .read_u64 = kmem_limit_independent_read,
4731 .write_u64 = kmem_limit_independent_write,
4734 .name = "kmem.usage_in_bytes",
4735 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
4736 .read_u64 = mem_cgroup_read,
4739 .name = "kmem.limit_in_bytes",
4740 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
4741 .read_u64 = mem_cgroup_read,
4745 static int register_kmem_files(struct cgroup *cont, struct cgroup_subsys *ss)
4747 int ret = 0;
4749 ret = cgroup_add_files(cont, ss, kmem_cgroup_files,
4750 ARRAY_SIZE(kmem_cgroup_files));
4753 * Part of this would be better living in a separate allocation
4754 * function, leaving us with just the cgroup tree population work.
4755 * We, however, depend on state such as network's proto_list that
4756 * is only initialized after cgroup creation. I found the less
4757 * cumbersome way to deal with it to defer it all to populate time
4759 if (!ret)
4760 ret = mem_cgroup_sockets_init(cont, ss);
4761 return ret;
4764 static void kmem_cgroup_destroy(struct cgroup_subsys *ss,
4765 struct cgroup *cont)
4767 mem_cgroup_sockets_destroy(cont, ss);
4769 #else
4770 static int register_kmem_files(struct cgroup *cont, struct cgroup_subsys *ss)
4772 return 0;
4775 static void kmem_cgroup_destroy(struct cgroup_subsys *ss,
4776 struct cgroup *cont)
4779 #endif
4781 static struct cftype mem_cgroup_files[] = {
4783 .name = "usage_in_bytes",
4784 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
4785 .read_u64 = mem_cgroup_read,
4786 .register_event = mem_cgroup_usage_register_event,
4787 .unregister_event = mem_cgroup_usage_unregister_event,
4790 .name = "max_usage_in_bytes",
4791 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
4792 .trigger = mem_cgroup_reset,
4793 .read_u64 = mem_cgroup_read,
4796 .name = "limit_in_bytes",
4797 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
4798 .write_string = mem_cgroup_write,
4799 .read_u64 = mem_cgroup_read,
4802 .name = "soft_limit_in_bytes",
4803 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
4804 .write_string = mem_cgroup_write,
4805 .read_u64 = mem_cgroup_read,
4808 .name = "failcnt",
4809 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
4810 .trigger = mem_cgroup_reset,
4811 .read_u64 = mem_cgroup_read,
4814 .name = "stat",
4815 .read_map = mem_control_stat_show,
4818 .name = "force_empty",
4819 .trigger = mem_cgroup_force_empty_write,
4822 .name = "use_hierarchy",
4823 .write_u64 = mem_cgroup_hierarchy_write,
4824 .read_u64 = mem_cgroup_hierarchy_read,
4827 .name = "swappiness",
4828 .read_u64 = mem_cgroup_swappiness_read,
4829 .write_u64 = mem_cgroup_swappiness_write,
4832 .name = "move_charge_at_immigrate",
4833 .read_u64 = mem_cgroup_move_charge_read,
4834 .write_u64 = mem_cgroup_move_charge_write,
4837 .name = "oom_control",
4838 .read_map = mem_cgroup_oom_control_read,
4839 .write_u64 = mem_cgroup_oom_control_write,
4840 .register_event = mem_cgroup_oom_register_event,
4841 .unregister_event = mem_cgroup_oom_unregister_event,
4842 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
4844 #ifdef CONFIG_NUMA
4846 .name = "numa_stat",
4847 .open = mem_control_numa_stat_open,
4848 .mode = S_IRUGO,
4850 #endif
4853 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4854 static struct cftype memsw_cgroup_files[] = {
4856 .name = "memsw.usage_in_bytes",
4857 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
4858 .read_u64 = mem_cgroup_read,
4859 .register_event = mem_cgroup_usage_register_event,
4860 .unregister_event = mem_cgroup_usage_unregister_event,
4863 .name = "memsw.max_usage_in_bytes",
4864 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
4865 .trigger = mem_cgroup_reset,
4866 .read_u64 = mem_cgroup_read,
4869 .name = "memsw.limit_in_bytes",
4870 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
4871 .write_string = mem_cgroup_write,
4872 .read_u64 = mem_cgroup_read,
4875 .name = "memsw.failcnt",
4876 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
4877 .trigger = mem_cgroup_reset,
4878 .read_u64 = mem_cgroup_read,
4882 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
4884 if (!do_swap_account)
4885 return 0;
4886 return cgroup_add_files(cont, ss, memsw_cgroup_files,
4887 ARRAY_SIZE(memsw_cgroup_files));
4889 #else
4890 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
4892 return 0;
4894 #endif
4896 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
4898 struct mem_cgroup_per_node *pn;
4899 struct mem_cgroup_per_zone *mz;
4900 enum lru_list l;
4901 int zone, tmp = node;
4903 * This routine is called against possible nodes.
4904 * But it's BUG to call kmalloc() against offline node.
4906 * TODO: this routine can waste much memory for nodes which will
4907 * never be onlined. It's better to use memory hotplug callback
4908 * function.
4910 if (!node_state(node, N_NORMAL_MEMORY))
4911 tmp = -1;
4912 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
4913 if (!pn)
4914 return 1;
4916 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4917 mz = &pn->zoneinfo[zone];
4918 for_each_lru(l)
4919 INIT_LIST_HEAD(&mz->lists[l]);
4920 mz->usage_in_excess = 0;
4921 mz->on_tree = false;
4922 mz->mem = memcg;
4924 memcg->info.nodeinfo[node] = pn;
4925 return 0;
4928 static void free_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
4930 kfree(memcg->info.nodeinfo[node]);
4933 static struct mem_cgroup *mem_cgroup_alloc(void)
4935 struct mem_cgroup *mem;
4936 int size = sizeof(struct mem_cgroup);
4938 /* Can be very big if MAX_NUMNODES is very big */
4939 if (size < PAGE_SIZE)
4940 mem = kzalloc(size, GFP_KERNEL);
4941 else
4942 mem = vzalloc(size);
4944 if (!mem)
4945 return NULL;
4947 mem->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
4948 if (!mem->stat)
4949 goto out_free;
4950 spin_lock_init(&mem->pcp_counter_lock);
4951 return mem;
4953 out_free:
4954 if (size < PAGE_SIZE)
4955 kfree(mem);
4956 else
4957 vfree(mem);
4958 return NULL;
4962 * At destroying mem_cgroup, references from swap_cgroup can remain.
4963 * (scanning all at force_empty is too costly...)
4965 * Instead of clearing all references at force_empty, we remember
4966 * the number of reference from swap_cgroup and free mem_cgroup when
4967 * it goes down to 0.
4969 * Removal of cgroup itself succeeds regardless of refs from swap.
4972 static void __mem_cgroup_free(struct mem_cgroup *memcg)
4974 int node;
4976 mem_cgroup_remove_from_trees(memcg);
4977 free_css_id(&mem_cgroup_subsys, &memcg->css);
4979 for_each_node_state(node, N_POSSIBLE)
4980 free_mem_cgroup_per_zone_info(memcg, node);
4982 free_percpu(memcg->stat);
4983 if (sizeof(struct mem_cgroup) < PAGE_SIZE)
4984 kfree(memcg);
4985 else
4986 vfree(memcg);
4989 static void mem_cgroup_get(struct mem_cgroup *memcg)
4991 atomic_inc(&memcg->refcnt);
4994 static void __mem_cgroup_put(struct mem_cgroup *memcg, int count)
4996 if (atomic_sub_and_test(count, &memcg->refcnt)) {
4997 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
4998 __mem_cgroup_free(memcg);
4999 if (parent)
5000 mem_cgroup_put(parent);
5004 static void mem_cgroup_put(struct mem_cgroup *memcg)
5006 __mem_cgroup_put(memcg, 1);
5010 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
5012 struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg)
5014 if (!memcg->res.parent)
5015 return NULL;
5016 return mem_cgroup_from_res_counter(memcg->res.parent, res);
5018 EXPORT_SYMBOL(parent_mem_cgroup);
5020 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
5021 static void __init enable_swap_cgroup(void)
5023 if (!mem_cgroup_disabled() && really_do_swap_account)
5024 do_swap_account = 1;
5026 #else
5027 static void __init enable_swap_cgroup(void)
5030 #endif
5032 static int mem_cgroup_soft_limit_tree_init(void)
5034 struct mem_cgroup_tree_per_node *rtpn;
5035 struct mem_cgroup_tree_per_zone *rtpz;
5036 int tmp, node, zone;
5038 for_each_node_state(node, N_POSSIBLE) {
5039 tmp = node;
5040 if (!node_state(node, N_NORMAL_MEMORY))
5041 tmp = -1;
5042 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
5043 if (!rtpn)
5044 return 1;
5046 soft_limit_tree.rb_tree_per_node[node] = rtpn;
5048 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
5049 rtpz = &rtpn->rb_tree_per_zone[zone];
5050 rtpz->rb_root = RB_ROOT;
5051 spin_lock_init(&rtpz->lock);
5054 return 0;
5057 static struct cgroup_subsys_state * __ref
5058 mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
5060 struct mem_cgroup *memcg, *parent;
5061 long error = -ENOMEM;
5062 int node;
5064 memcg = mem_cgroup_alloc();
5065 if (!memcg)
5066 return ERR_PTR(error);
5068 for_each_node_state(node, N_POSSIBLE)
5069 if (alloc_mem_cgroup_per_zone_info(memcg, node))
5070 goto free_out;
5072 /* root ? */
5073 if (cont->parent == NULL) {
5074 int cpu;
5075 enable_swap_cgroup();
5076 parent = NULL;
5077 root_mem_cgroup = memcg;
5078 if (mem_cgroup_soft_limit_tree_init())
5079 goto free_out;
5080 for_each_possible_cpu(cpu) {
5081 struct memcg_stock_pcp *stock =
5082 &per_cpu(memcg_stock, cpu);
5083 INIT_WORK(&stock->work, drain_local_stock);
5085 hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
5086 } else {
5087 parent = mem_cgroup_from_cont(cont->parent);
5088 memcg->use_hierarchy = parent->use_hierarchy;
5089 memcg->oom_kill_disable = parent->oom_kill_disable;
5092 if (parent && parent->use_hierarchy) {
5093 res_counter_init(&memcg->res, &parent->res);
5094 res_counter_init(&memcg->memsw, &parent->memsw);
5095 res_counter_init(&memcg->kmem, &parent->kmem);
5097 * We increment refcnt of the parent to ensure that we can
5098 * safely access it on res_counter_charge/uncharge.
5099 * This refcnt will be decremented when freeing this
5100 * mem_cgroup(see mem_cgroup_put).
5102 mem_cgroup_get(parent);
5103 } else {
5104 res_counter_init(&memcg->res, NULL);
5105 res_counter_init(&memcg->memsw, NULL);
5106 res_counter_init(&memcg->kmem, NULL);
5108 memcg->last_scanned_child = 0;
5109 memcg->last_scanned_node = MAX_NUMNODES;
5110 INIT_LIST_HEAD(&memcg->oom_notify);
5112 if (parent)
5113 memcg->swappiness = mem_cgroup_swappiness(parent);
5114 atomic_set(&memcg->refcnt, 1);
5115 memcg->move_charge_at_immigrate = 0;
5116 mutex_init(&memcg->thresholds_lock);
5117 return &memcg->css;
5118 free_out:
5119 __mem_cgroup_free(memcg);
5120 root_mem_cgroup = NULL;
5121 return ERR_PTR(error);
5124 static int mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
5125 struct cgroup *cont)
5127 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5129 return mem_cgroup_force_empty(memcg, false);
5132 static void mem_cgroup_destroy(struct cgroup_subsys *ss,
5133 struct cgroup *cont)
5135 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5137 kmem_cgroup_destroy(ss, cont);
5139 mem_cgroup_put(memcg);
5142 static int mem_cgroup_populate(struct cgroup_subsys *ss,
5143 struct cgroup *cont)
5145 int ret;
5147 ret = cgroup_add_files(cont, ss, mem_cgroup_files,
5148 ARRAY_SIZE(mem_cgroup_files));
5150 if (!ret)
5151 ret = register_memsw_files(cont, ss);
5153 if (!ret)
5154 ret = register_kmem_files(cont, ss);
5156 return ret;
5159 #ifdef CONFIG_MMU
5160 /* Handlers for move charge at task migration. */
5161 #define PRECHARGE_COUNT_AT_ONCE 256
5162 static int mem_cgroup_do_precharge(unsigned long count)
5164 int ret = 0;
5165 int batch_count = PRECHARGE_COUNT_AT_ONCE;
5166 struct mem_cgroup *memcg = mc.to;
5168 if (mem_cgroup_is_root(memcg)) {
5169 mc.precharge += count;
5170 /* we don't need css_get for root */
5171 return ret;
5173 /* try to charge at once */
5174 if (count > 1) {
5175 struct res_counter *dummy;
5177 * "memcg" cannot be under rmdir() because we've already checked
5178 * by cgroup_lock_live_cgroup() that it is not removed and we
5179 * are still under the same cgroup_mutex. So we can postpone
5180 * css_get().
5182 if (res_counter_charge(&memcg->res, PAGE_SIZE * count, &dummy))
5183 goto one_by_one;
5184 if (do_swap_account && res_counter_charge(&memcg->memsw,
5185 PAGE_SIZE * count, &dummy)) {
5186 res_counter_uncharge(&memcg->res, PAGE_SIZE * count);
5187 goto one_by_one;
5189 mc.precharge += count;
5190 return ret;
5192 one_by_one:
5193 /* fall back to one by one charge */
5194 while (count--) {
5195 if (signal_pending(current)) {
5196 ret = -EINTR;
5197 break;
5199 if (!batch_count--) {
5200 batch_count = PRECHARGE_COUNT_AT_ONCE;
5201 cond_resched();
5203 ret = __mem_cgroup_try_charge(NULL,
5204 GFP_KERNEL, 1, &memcg, false);
5205 if (ret || !memcg)
5206 /* mem_cgroup_clear_mc() will do uncharge later */
5207 return -ENOMEM;
5208 mc.precharge++;
5210 return ret;
5214 * is_target_pte_for_mc - check a pte whether it is valid for move charge
5215 * @vma: the vma the pte to be checked belongs
5216 * @addr: the address corresponding to the pte to be checked
5217 * @ptent: the pte to be checked
5218 * @target: the pointer the target page or swap ent will be stored(can be NULL)
5220 * Returns
5221 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
5222 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5223 * move charge. if @target is not NULL, the page is stored in target->page
5224 * with extra refcnt got(Callers should handle it).
5225 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5226 * target for charge migration. if @target is not NULL, the entry is stored
5227 * in target->ent.
5229 * Called with pte lock held.
5231 union mc_target {
5232 struct page *page;
5233 swp_entry_t ent;
5236 enum mc_target_type {
5237 MC_TARGET_NONE, /* not used */
5238 MC_TARGET_PAGE,
5239 MC_TARGET_SWAP,
5242 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5243 unsigned long addr, pte_t ptent)
5245 struct page *page = vm_normal_page(vma, addr, ptent);
5247 if (!page || !page_mapped(page))
5248 return NULL;
5249 if (PageAnon(page)) {
5250 /* we don't move shared anon */
5251 if (!move_anon() || page_mapcount(page) > 2)
5252 return NULL;
5253 } else if (!move_file())
5254 /* we ignore mapcount for file pages */
5255 return NULL;
5256 if (!get_page_unless_zero(page))
5257 return NULL;
5259 return page;
5262 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5263 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5265 int usage_count;
5266 struct page *page = NULL;
5267 swp_entry_t ent = pte_to_swp_entry(ptent);
5269 if (!move_anon() || non_swap_entry(ent))
5270 return NULL;
5271 usage_count = mem_cgroup_count_swap_user(ent, &page);
5272 if (usage_count > 1) { /* we don't move shared anon */
5273 if (page)
5274 put_page(page);
5275 return NULL;
5277 if (do_swap_account)
5278 entry->val = ent.val;
5280 return page;
5283 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5284 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5286 struct page *page = NULL;
5287 struct inode *inode;
5288 struct address_space *mapping;
5289 pgoff_t pgoff;
5291 if (!vma->vm_file) /* anonymous vma */
5292 return NULL;
5293 if (!move_file())
5294 return NULL;
5296 inode = vma->vm_file->f_path.dentry->d_inode;
5297 mapping = vma->vm_file->f_mapping;
5298 if (pte_none(ptent))
5299 pgoff = linear_page_index(vma, addr);
5300 else /* pte_file(ptent) is true */
5301 pgoff = pte_to_pgoff(ptent);
5303 /* page is moved even if it's not RSS of this task(page-faulted). */
5304 page = find_get_page(mapping, pgoff);
5306 #ifdef CONFIG_SWAP
5307 /* shmem/tmpfs may report page out on swap: account for that too. */
5308 if (radix_tree_exceptional_entry(page)) {
5309 swp_entry_t swap = radix_to_swp_entry(page);
5310 if (do_swap_account)
5311 *entry = swap;
5312 page = find_get_page(&swapper_space, swap.val);
5314 #endif
5315 return page;
5318 static int is_target_pte_for_mc(struct vm_area_struct *vma,
5319 unsigned long addr, pte_t ptent, union mc_target *target)
5321 struct page *page = NULL;
5322 struct page_cgroup *pc;
5323 int ret = 0;
5324 swp_entry_t ent = { .val = 0 };
5326 if (pte_present(ptent))
5327 page = mc_handle_present_pte(vma, addr, ptent);
5328 else if (is_swap_pte(ptent))
5329 page = mc_handle_swap_pte(vma, addr, ptent, &ent);
5330 else if (pte_none(ptent) || pte_file(ptent))
5331 page = mc_handle_file_pte(vma, addr, ptent, &ent);
5333 if (!page && !ent.val)
5334 return 0;
5335 if (page) {
5336 pc = lookup_page_cgroup(page);
5338 * Do only loose check w/o page_cgroup lock.
5339 * mem_cgroup_move_account() checks the pc is valid or not under
5340 * the lock.
5342 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
5343 ret = MC_TARGET_PAGE;
5344 if (target)
5345 target->page = page;
5347 if (!ret || !target)
5348 put_page(page);
5350 /* There is a swap entry and a page doesn't exist or isn't charged */
5351 if (ent.val && !ret &&
5352 css_id(&mc.from->css) == lookup_swap_cgroup(ent)) {
5353 ret = MC_TARGET_SWAP;
5354 if (target)
5355 target->ent = ent;
5357 return ret;
5360 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
5361 unsigned long addr, unsigned long end,
5362 struct mm_walk *walk)
5364 struct vm_area_struct *vma = walk->private;
5365 pte_t *pte;
5366 spinlock_t *ptl;
5368 split_huge_page_pmd(walk->mm, pmd);
5370 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5371 for (; addr != end; pte++, addr += PAGE_SIZE)
5372 if (is_target_pte_for_mc(vma, addr, *pte, NULL))
5373 mc.precharge++; /* increment precharge temporarily */
5374 pte_unmap_unlock(pte - 1, ptl);
5375 cond_resched();
5377 return 0;
5380 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
5382 unsigned long precharge;
5383 struct vm_area_struct *vma;
5385 down_read(&mm->mmap_sem);
5386 for (vma = mm->mmap; vma; vma = vma->vm_next) {
5387 struct mm_walk mem_cgroup_count_precharge_walk = {
5388 .pmd_entry = mem_cgroup_count_precharge_pte_range,
5389 .mm = mm,
5390 .private = vma,
5392 if (is_vm_hugetlb_page(vma))
5393 continue;
5394 walk_page_range(vma->vm_start, vma->vm_end,
5395 &mem_cgroup_count_precharge_walk);
5397 up_read(&mm->mmap_sem);
5399 precharge = mc.precharge;
5400 mc.precharge = 0;
5402 return precharge;
5405 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
5407 unsigned long precharge = mem_cgroup_count_precharge(mm);
5409 VM_BUG_ON(mc.moving_task);
5410 mc.moving_task = current;
5411 return mem_cgroup_do_precharge(precharge);
5414 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5415 static void __mem_cgroup_clear_mc(void)
5417 struct mem_cgroup *from = mc.from;
5418 struct mem_cgroup *to = mc.to;
5420 /* we must uncharge all the leftover precharges from mc.to */
5421 if (mc.precharge) {
5422 __mem_cgroup_cancel_charge(mc.to, mc.precharge);
5423 mc.precharge = 0;
5426 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5427 * we must uncharge here.
5429 if (mc.moved_charge) {
5430 __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
5431 mc.moved_charge = 0;
5433 /* we must fixup refcnts and charges */
5434 if (mc.moved_swap) {
5435 /* uncharge swap account from the old cgroup */
5436 if (!mem_cgroup_is_root(mc.from))
5437 res_counter_uncharge(&mc.from->memsw,
5438 PAGE_SIZE * mc.moved_swap);
5439 __mem_cgroup_put(mc.from, mc.moved_swap);
5441 if (!mem_cgroup_is_root(mc.to)) {
5443 * we charged both to->res and to->memsw, so we should
5444 * uncharge to->res.
5446 res_counter_uncharge(&mc.to->res,
5447 PAGE_SIZE * mc.moved_swap);
5449 /* we've already done mem_cgroup_get(mc.to) */
5450 mc.moved_swap = 0;
5452 memcg_oom_recover(from);
5453 memcg_oom_recover(to);
5454 wake_up_all(&mc.waitq);
5457 static void mem_cgroup_clear_mc(void)
5459 struct mem_cgroup *from = mc.from;
5462 * we must clear moving_task before waking up waiters at the end of
5463 * task migration.
5465 mc.moving_task = NULL;
5466 __mem_cgroup_clear_mc();
5467 spin_lock(&mc.lock);
5468 mc.from = NULL;
5469 mc.to = NULL;
5470 spin_unlock(&mc.lock);
5471 mem_cgroup_end_move(from);
5474 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
5475 struct cgroup *cgroup,
5476 struct task_struct *p)
5478 int ret = 0;
5479 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgroup);
5481 if (memcg->move_charge_at_immigrate) {
5482 struct mm_struct *mm;
5483 struct mem_cgroup *from = mem_cgroup_from_task(p);
5485 VM_BUG_ON(from == memcg);
5487 mm = get_task_mm(p);
5488 if (!mm)
5489 return 0;
5490 /* We move charges only when we move a owner of the mm */
5491 if (mm->owner == p) {
5492 VM_BUG_ON(mc.from);
5493 VM_BUG_ON(mc.to);
5494 VM_BUG_ON(mc.precharge);
5495 VM_BUG_ON(mc.moved_charge);
5496 VM_BUG_ON(mc.moved_swap);
5497 mem_cgroup_start_move(from);
5498 spin_lock(&mc.lock);
5499 mc.from = from;
5500 mc.to = memcg;
5501 spin_unlock(&mc.lock);
5502 /* We set mc.moving_task later */
5504 ret = mem_cgroup_precharge_mc(mm);
5505 if (ret)
5506 mem_cgroup_clear_mc();
5508 mmput(mm);
5510 return ret;
5513 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
5514 struct cgroup *cgroup,
5515 struct task_struct *p)
5517 mem_cgroup_clear_mc();
5520 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
5521 unsigned long addr, unsigned long end,
5522 struct mm_walk *walk)
5524 int ret = 0;
5525 struct vm_area_struct *vma = walk->private;
5526 pte_t *pte;
5527 spinlock_t *ptl;
5529 split_huge_page_pmd(walk->mm, pmd);
5530 retry:
5531 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5532 for (; addr != end; addr += PAGE_SIZE) {
5533 pte_t ptent = *(pte++);
5534 union mc_target target;
5535 int type;
5536 struct page *page;
5537 struct page_cgroup *pc;
5538 swp_entry_t ent;
5540 if (!mc.precharge)
5541 break;
5543 type = is_target_pte_for_mc(vma, addr, ptent, &target);
5544 switch (type) {
5545 case MC_TARGET_PAGE:
5546 page = target.page;
5547 if (isolate_lru_page(page))
5548 goto put;
5549 pc = lookup_page_cgroup(page);
5550 if (!mem_cgroup_move_account(page, 1, pc,
5551 mc.from, mc.to, false)) {
5552 mc.precharge--;
5553 /* we uncharge from mc.from later. */
5554 mc.moved_charge++;
5556 putback_lru_page(page);
5557 put: /* is_target_pte_for_mc() gets the page */
5558 put_page(page);
5559 break;
5560 case MC_TARGET_SWAP:
5561 ent = target.ent;
5562 if (!mem_cgroup_move_swap_account(ent,
5563 mc.from, mc.to, false)) {
5564 mc.precharge--;
5565 /* we fixup refcnts and charges later. */
5566 mc.moved_swap++;
5568 break;
5569 default:
5570 break;
5573 pte_unmap_unlock(pte - 1, ptl);
5574 cond_resched();
5576 if (addr != end) {
5578 * We have consumed all precharges we got in can_attach().
5579 * We try charge one by one, but don't do any additional
5580 * charges to mc.to if we have failed in charge once in attach()
5581 * phase.
5583 ret = mem_cgroup_do_precharge(1);
5584 if (!ret)
5585 goto retry;
5588 return ret;
5591 static void mem_cgroup_move_charge(struct mm_struct *mm)
5593 struct vm_area_struct *vma;
5595 lru_add_drain_all();
5596 retry:
5597 if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
5599 * Someone who are holding the mmap_sem might be waiting in
5600 * waitq. So we cancel all extra charges, wake up all waiters,
5601 * and retry. Because we cancel precharges, we might not be able
5602 * to move enough charges, but moving charge is a best-effort
5603 * feature anyway, so it wouldn't be a big problem.
5605 __mem_cgroup_clear_mc();
5606 cond_resched();
5607 goto retry;
5609 for (vma = mm->mmap; vma; vma = vma->vm_next) {
5610 int ret;
5611 struct mm_walk mem_cgroup_move_charge_walk = {
5612 .pmd_entry = mem_cgroup_move_charge_pte_range,
5613 .mm = mm,
5614 .private = vma,
5616 if (is_vm_hugetlb_page(vma))
5617 continue;
5618 ret = walk_page_range(vma->vm_start, vma->vm_end,
5619 &mem_cgroup_move_charge_walk);
5620 if (ret)
5622 * means we have consumed all precharges and failed in
5623 * doing additional charge. Just abandon here.
5625 break;
5627 up_read(&mm->mmap_sem);
5630 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
5631 struct cgroup *cont,
5632 struct cgroup *old_cont,
5633 struct task_struct *p)
5635 struct mm_struct *mm = get_task_mm(p);
5637 if (mm) {
5638 if (mc.to)
5639 mem_cgroup_move_charge(mm);
5640 put_swap_token(mm);
5641 mmput(mm);
5643 if (mc.to)
5644 mem_cgroup_clear_mc();
5646 #else /* !CONFIG_MMU */
5647 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
5648 struct cgroup *cgroup,
5649 struct task_struct *p)
5651 return 0;
5653 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
5654 struct cgroup *cgroup,
5655 struct task_struct *p)
5658 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
5659 struct cgroup *cont,
5660 struct cgroup *old_cont,
5661 struct task_struct *p)
5664 #endif
5666 struct cgroup_subsys mem_cgroup_subsys = {
5667 .name = "memory",
5668 .subsys_id = mem_cgroup_subsys_id,
5669 .create = mem_cgroup_create,
5670 .pre_destroy = mem_cgroup_pre_destroy,
5671 .destroy = mem_cgroup_destroy,
5672 .populate = mem_cgroup_populate,
5673 .can_attach = mem_cgroup_can_attach,
5674 .cancel_attach = mem_cgroup_cancel_attach,
5675 .attach = mem_cgroup_move_task,
5676 .early_init = 0,
5677 .use_id = 1,
5680 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
5681 static int __init enable_swap_account(char *s)
5683 /* consider enabled if no parameter or 1 is given */
5684 if (!strcmp(s, "1"))
5685 really_do_swap_account = 1;
5686 else if (!strcmp(s, "0"))
5687 really_do_swap_account = 0;
5688 return 1;
5690 __setup("swapaccount=", enable_swap_account);
5692 #endif