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>
10 * Copyright (C) 2009 Nokia Corporation
11 * Author: Kirill A. Shutemov
13 * Kernel Memory Controller
14 * Copyright (C) 2012 Parallels Inc. and Google Inc.
15 * Authors: Glauber Costa and Suleiman Souhlal
17 * This program is free software; you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation; either version 2 of the License, or
20 * (at your option) any later version.
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
28 #include <linux/res_counter.h>
29 #include <linux/memcontrol.h>
30 #include <linux/cgroup.h>
32 #include <linux/hugetlb.h>
33 #include <linux/pagemap.h>
34 #include <linux/smp.h>
35 #include <linux/page-flags.h>
36 #include <linux/backing-dev.h>
37 #include <linux/bit_spinlock.h>
38 #include <linux/rcupdate.h>
39 #include <linux/limits.h>
40 #include <linux/export.h>
41 #include <linux/mutex.h>
42 #include <linux/rbtree.h>
43 #include <linux/slab.h>
44 #include <linux/swap.h>
45 #include <linux/swapops.h>
46 #include <linux/spinlock.h>
47 #include <linux/eventfd.h>
48 #include <linux/sort.h>
50 #include <linux/seq_file.h>
51 #include <linux/vmalloc.h>
52 #include <linux/vmpressure.h>
53 #include <linux/mm_inline.h>
54 #include <linux/page_cgroup.h>
55 #include <linux/cpu.h>
56 #include <linux/oom.h>
60 #include <net/tcp_memcontrol.h>
62 #include <asm/uaccess.h>
64 #include <trace/events/vmscan.h>
66 struct cgroup_subsys mem_cgroup_subsys __read_mostly;
67 EXPORT_SYMBOL(mem_cgroup_subsys);
69 #define MEM_CGROUP_RECLAIM_RETRIES 5
70 static struct mem_cgroup *root_mem_cgroup __read_mostly;
72 #ifdef CONFIG_MEMCG_SWAP
73 /* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
74 int do_swap_account __read_mostly;
76 /* for remember boot option*/
77 #ifdef CONFIG_MEMCG_SWAP_ENABLED
78 static int really_do_swap_account __initdata = 1;
80 static int really_do_swap_account __initdata = 0;
84 #define do_swap_account 0
89 * Statistics for memory cgroup.
91 enum mem_cgroup_stat_index {
93 * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
95 MEM_CGROUP_STAT_CACHE, /* # of pages charged as cache */
96 MEM_CGROUP_STAT_RSS, /* # of pages charged as anon rss */
97 MEM_CGROUP_STAT_RSS_HUGE, /* # of pages charged as anon huge */
98 MEM_CGROUP_STAT_FILE_MAPPED, /* # of pages charged as file rss */
99 MEM_CGROUP_STAT_SWAP, /* # of pages, swapped out */
100 MEM_CGROUP_STAT_NSTATS,
103 static const char * const mem_cgroup_stat_names[] = {
111 enum mem_cgroup_events_index {
112 MEM_CGROUP_EVENTS_PGPGIN, /* # of pages paged in */
113 MEM_CGROUP_EVENTS_PGPGOUT, /* # of pages paged out */
114 MEM_CGROUP_EVENTS_PGFAULT, /* # of page-faults */
115 MEM_CGROUP_EVENTS_PGMAJFAULT, /* # of major page-faults */
116 MEM_CGROUP_EVENTS_NSTATS,
119 static const char * const mem_cgroup_events_names[] = {
126 static const char * const mem_cgroup_lru_names[] = {
135 * Per memcg event counter is incremented at every pagein/pageout. With THP,
136 * it will be incremated by the number of pages. This counter is used for
137 * for trigger some periodic events. This is straightforward and better
138 * than using jiffies etc. to handle periodic memcg event.
140 enum mem_cgroup_events_target {
141 MEM_CGROUP_TARGET_THRESH,
142 MEM_CGROUP_TARGET_SOFTLIMIT,
143 MEM_CGROUP_TARGET_NUMAINFO,
146 #define THRESHOLDS_EVENTS_TARGET 128
147 #define SOFTLIMIT_EVENTS_TARGET 1024
148 #define NUMAINFO_EVENTS_TARGET 1024
150 struct mem_cgroup_stat_cpu {
151 long count[MEM_CGROUP_STAT_NSTATS];
152 unsigned long events[MEM_CGROUP_EVENTS_NSTATS];
153 unsigned long nr_page_events;
154 unsigned long targets[MEM_CGROUP_NTARGETS];
157 struct mem_cgroup_reclaim_iter {
159 * last scanned hierarchy member. Valid only if last_dead_count
160 * matches memcg->dead_count of the hierarchy root group.
162 struct mem_cgroup *last_visited;
163 unsigned long last_dead_count;
165 /* scan generation, increased every round-trip */
166 unsigned int generation;
170 * per-zone information in memory controller.
172 struct mem_cgroup_per_zone {
173 struct lruvec lruvec;
174 unsigned long lru_size[NR_LRU_LISTS];
176 struct mem_cgroup_reclaim_iter reclaim_iter[DEF_PRIORITY + 1];
178 struct rb_node tree_node; /* RB tree node */
179 unsigned long long usage_in_excess;/* Set to the value by which */
180 /* the soft limit is exceeded*/
182 struct mem_cgroup *memcg; /* Back pointer, we cannot */
183 /* use container_of */
186 struct mem_cgroup_per_node {
187 struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
190 struct mem_cgroup_lru_info {
191 struct mem_cgroup_per_node *nodeinfo[0];
195 * Cgroups above their limits are maintained in a RB-Tree, independent of
196 * their hierarchy representation
199 struct mem_cgroup_tree_per_zone {
200 struct rb_root rb_root;
204 struct mem_cgroup_tree_per_node {
205 struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
208 struct mem_cgroup_tree {
209 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
212 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
214 struct mem_cgroup_threshold {
215 struct eventfd_ctx *eventfd;
220 struct mem_cgroup_threshold_ary {
221 /* An array index points to threshold just below or equal to usage. */
222 int current_threshold;
223 /* Size of entries[] */
225 /* Array of thresholds */
226 struct mem_cgroup_threshold entries[0];
229 struct mem_cgroup_thresholds {
230 /* Primary thresholds array */
231 struct mem_cgroup_threshold_ary *primary;
233 * Spare threshold array.
234 * This is needed to make mem_cgroup_unregister_event() "never fail".
235 * It must be able to store at least primary->size - 1 entries.
237 struct mem_cgroup_threshold_ary *spare;
241 struct mem_cgroup_eventfd_list {
242 struct list_head list;
243 struct eventfd_ctx *eventfd;
246 static void mem_cgroup_threshold(struct mem_cgroup *memcg);
247 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
250 * The memory controller data structure. The memory controller controls both
251 * page cache and RSS per cgroup. We would eventually like to provide
252 * statistics based on the statistics developed by Rik Van Riel for clock-pro,
253 * to help the administrator determine what knobs to tune.
255 * TODO: Add a water mark for the memory controller. Reclaim will begin when
256 * we hit the water mark. May be even add a low water mark, such that
257 * no reclaim occurs from a cgroup at it's low water mark, this is
258 * a feature that will be implemented much later in the future.
261 struct cgroup_subsys_state css;
263 * the counter to account for memory usage
265 struct res_counter res;
267 /* vmpressure notifications */
268 struct vmpressure vmpressure;
272 * the counter to account for mem+swap usage.
274 struct res_counter memsw;
277 * rcu_freeing is used only when freeing struct mem_cgroup,
278 * so put it into a union to avoid wasting more memory.
279 * It must be disjoint from the css field. It could be
280 * in a union with the res field, but res plays a much
281 * larger part in mem_cgroup life than memsw, and might
282 * be of interest, even at time of free, when debugging.
283 * So share rcu_head with the less interesting memsw.
285 struct rcu_head rcu_freeing;
287 * We also need some space for a worker in deferred freeing.
288 * By the time we call it, rcu_freeing is no longer in use.
290 struct work_struct work_freeing;
294 * the counter to account for kernel memory usage.
296 struct res_counter kmem;
298 * Should the accounting and control be hierarchical, per subtree?
301 unsigned long kmem_account_flags; /* See KMEM_ACCOUNTED_*, below */
305 atomic_t oom_wakeups;
310 /* OOM-Killer disable */
311 int oom_kill_disable;
313 /* set when res.limit == memsw.limit */
314 bool memsw_is_minimum;
316 /* protect arrays of thresholds */
317 struct mutex thresholds_lock;
319 /* thresholds for memory usage. RCU-protected */
320 struct mem_cgroup_thresholds thresholds;
322 /* thresholds for mem+swap usage. RCU-protected */
323 struct mem_cgroup_thresholds memsw_thresholds;
325 /* For oom notifier event fd */
326 struct list_head oom_notify;
329 * Should we move charges of a task when a task is moved into this
330 * mem_cgroup ? And what type of charges should we move ?
332 unsigned long move_charge_at_immigrate;
334 * set > 0 if pages under this cgroup are moving to other cgroup.
336 atomic_t moving_account;
337 /* taken only while moving_account > 0 */
338 spinlock_t move_lock;
342 struct mem_cgroup_stat_cpu __percpu *stat;
344 * used when a cpu is offlined or other synchronizations
345 * See mem_cgroup_read_stat().
347 struct mem_cgroup_stat_cpu nocpu_base;
348 spinlock_t pcp_counter_lock;
351 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_INET)
352 struct tcp_memcontrol tcp_mem;
354 #if defined(CONFIG_MEMCG_KMEM)
355 /* analogous to slab_common's slab_caches list. per-memcg */
356 struct list_head memcg_slab_caches;
357 /* Not a spinlock, we can take a lot of time walking the list */
358 struct mutex slab_caches_mutex;
359 /* Index in the kmem_cache->memcg_params->memcg_caches array */
363 int last_scanned_node;
365 nodemask_t scan_nodes;
366 atomic_t numainfo_events;
367 atomic_t numainfo_updating;
371 * Per cgroup active and inactive list, similar to the
372 * per zone LRU lists.
374 * WARNING: This has to be the last element of the struct. Don't
375 * add new fields after this point.
377 struct mem_cgroup_lru_info info;
380 static size_t memcg_size(void)
382 return sizeof(struct mem_cgroup) +
383 nr_node_ids * sizeof(struct mem_cgroup_per_node *);
386 /* internal only representation about the status of kmem accounting. */
388 KMEM_ACCOUNTED_ACTIVE = 0, /* accounted by this cgroup itself */
389 KMEM_ACCOUNTED_ACTIVATED, /* static key enabled. */
390 KMEM_ACCOUNTED_DEAD, /* dead memcg with pending kmem charges */
393 /* We account when limit is on, but only after call sites are patched */
394 #define KMEM_ACCOUNTED_MASK \
395 ((1 << KMEM_ACCOUNTED_ACTIVE) | (1 << KMEM_ACCOUNTED_ACTIVATED))
397 #ifdef CONFIG_MEMCG_KMEM
398 static inline void memcg_kmem_set_active(struct mem_cgroup *memcg)
400 set_bit(KMEM_ACCOUNTED_ACTIVE, &memcg->kmem_account_flags);
403 static bool memcg_kmem_is_active(struct mem_cgroup *memcg)
405 return test_bit(KMEM_ACCOUNTED_ACTIVE, &memcg->kmem_account_flags);
408 static void memcg_kmem_set_activated(struct mem_cgroup *memcg)
410 set_bit(KMEM_ACCOUNTED_ACTIVATED, &memcg->kmem_account_flags);
413 static void memcg_kmem_clear_activated(struct mem_cgroup *memcg)
415 clear_bit(KMEM_ACCOUNTED_ACTIVATED, &memcg->kmem_account_flags);
418 static void memcg_kmem_mark_dead(struct mem_cgroup *memcg)
420 if (test_bit(KMEM_ACCOUNTED_ACTIVE, &memcg->kmem_account_flags))
421 set_bit(KMEM_ACCOUNTED_DEAD, &memcg->kmem_account_flags);
424 static bool memcg_kmem_test_and_clear_dead(struct mem_cgroup *memcg)
426 return test_and_clear_bit(KMEM_ACCOUNTED_DEAD,
427 &memcg->kmem_account_flags);
431 /* Stuffs for move charges at task migration. */
433 * Types of charges to be moved. "move_charge_at_immitgrate" and
434 * "immigrate_flags" are treated as a left-shifted bitmap of these types.
437 MOVE_CHARGE_TYPE_ANON, /* private anonymous page and swap of it */
438 MOVE_CHARGE_TYPE_FILE, /* file page(including tmpfs) and swap of it */
442 /* "mc" and its members are protected by cgroup_mutex */
443 static struct move_charge_struct {
444 spinlock_t lock; /* for from, to */
445 struct mem_cgroup *from;
446 struct mem_cgroup *to;
447 unsigned long immigrate_flags;
448 unsigned long precharge;
449 unsigned long moved_charge;
450 unsigned long moved_swap;
451 struct task_struct *moving_task; /* a task moving charges */
452 wait_queue_head_t waitq; /* a waitq for other context */
454 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
455 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
458 static bool move_anon(void)
460 return test_bit(MOVE_CHARGE_TYPE_ANON, &mc.immigrate_flags);
463 static bool move_file(void)
465 return test_bit(MOVE_CHARGE_TYPE_FILE, &mc.immigrate_flags);
469 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
470 * limit reclaim to prevent infinite loops, if they ever occur.
472 #define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
473 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
476 MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
477 MEM_CGROUP_CHARGE_TYPE_ANON,
478 MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
479 MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
483 /* for encoding cft->private value on file */
491 #define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
492 #define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
493 #define MEMFILE_ATTR(val) ((val) & 0xffff)
494 /* Used for OOM nofiier */
495 #define OOM_CONTROL (0)
498 * Reclaim flags for mem_cgroup_hierarchical_reclaim
500 #define MEM_CGROUP_RECLAIM_NOSWAP_BIT 0x0
501 #define MEM_CGROUP_RECLAIM_NOSWAP (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
502 #define MEM_CGROUP_RECLAIM_SHRINK_BIT 0x1
503 #define MEM_CGROUP_RECLAIM_SHRINK (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
506 * The memcg_create_mutex will be held whenever a new cgroup is created.
507 * As a consequence, any change that needs to protect against new child cgroups
508 * appearing has to hold it as well.
510 static DEFINE_MUTEX(memcg_create_mutex);
512 static void mem_cgroup_get(struct mem_cgroup *memcg);
513 static void mem_cgroup_put(struct mem_cgroup *memcg);
516 struct mem_cgroup *mem_cgroup_from_css(struct cgroup_subsys_state *s)
518 return container_of(s, struct mem_cgroup, css);
521 /* Some nice accessors for the vmpressure. */
522 struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
525 memcg = root_mem_cgroup;
526 return &memcg->vmpressure;
529 struct cgroup_subsys_state *vmpressure_to_css(struct vmpressure *vmpr)
531 return &container_of(vmpr, struct mem_cgroup, vmpressure)->css;
534 struct vmpressure *css_to_vmpressure(struct cgroup_subsys_state *css)
536 return &mem_cgroup_from_css(css)->vmpressure;
539 static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg)
541 return (memcg == root_mem_cgroup);
544 /* Writing them here to avoid exposing memcg's inner layout */
545 #if defined(CONFIG_INET) && defined(CONFIG_MEMCG_KMEM)
547 void sock_update_memcg(struct sock *sk)
549 if (mem_cgroup_sockets_enabled) {
550 struct mem_cgroup *memcg;
551 struct cg_proto *cg_proto;
553 BUG_ON(!sk->sk_prot->proto_cgroup);
555 /* Socket cloning can throw us here with sk_cgrp already
556 * filled. It won't however, necessarily happen from
557 * process context. So the test for root memcg given
558 * the current task's memcg won't help us in this case.
560 * Respecting the original socket's memcg is a better
561 * decision in this case.
564 BUG_ON(mem_cgroup_is_root(sk->sk_cgrp->memcg));
565 mem_cgroup_get(sk->sk_cgrp->memcg);
570 memcg = mem_cgroup_from_task(current);
571 cg_proto = sk->sk_prot->proto_cgroup(memcg);
572 if (!mem_cgroup_is_root(memcg) && memcg_proto_active(cg_proto)) {
573 mem_cgroup_get(memcg);
574 sk->sk_cgrp = cg_proto;
579 EXPORT_SYMBOL(sock_update_memcg);
581 void sock_release_memcg(struct sock *sk)
583 if (mem_cgroup_sockets_enabled && sk->sk_cgrp) {
584 struct mem_cgroup *memcg;
585 WARN_ON(!sk->sk_cgrp->memcg);
586 memcg = sk->sk_cgrp->memcg;
587 mem_cgroup_put(memcg);
591 struct cg_proto *tcp_proto_cgroup(struct mem_cgroup *memcg)
593 if (!memcg || mem_cgroup_is_root(memcg))
596 return &memcg->tcp_mem.cg_proto;
598 EXPORT_SYMBOL(tcp_proto_cgroup);
600 static void disarm_sock_keys(struct mem_cgroup *memcg)
602 if (!memcg_proto_activated(&memcg->tcp_mem.cg_proto))
604 static_key_slow_dec(&memcg_socket_limit_enabled);
607 static void disarm_sock_keys(struct mem_cgroup *memcg)
612 #ifdef CONFIG_MEMCG_KMEM
614 * This will be the memcg's index in each cache's ->memcg_params->memcg_caches.
615 * There are two main reasons for not using the css_id for this:
616 * 1) this works better in sparse environments, where we have a lot of memcgs,
617 * but only a few kmem-limited. Or also, if we have, for instance, 200
618 * memcgs, and none but the 200th is kmem-limited, we'd have to have a
619 * 200 entry array for that.
621 * 2) In order not to violate the cgroup API, we would like to do all memory
622 * allocation in ->create(). At that point, we haven't yet allocated the
623 * css_id. Having a separate index prevents us from messing with the cgroup
626 * The current size of the caches array is stored in
627 * memcg_limited_groups_array_size. It will double each time we have to
630 static DEFINE_IDA(kmem_limited_groups);
631 int memcg_limited_groups_array_size;
634 * MIN_SIZE is different than 1, because we would like to avoid going through
635 * the alloc/free process all the time. In a small machine, 4 kmem-limited
636 * cgroups is a reasonable guess. In the future, it could be a parameter or
637 * tunable, but that is strictly not necessary.
639 * MAX_SIZE should be as large as the number of css_ids. Ideally, we could get
640 * this constant directly from cgroup, but it is understandable that this is
641 * better kept as an internal representation in cgroup.c. In any case, the
642 * css_id space is not getting any smaller, and we don't have to necessarily
643 * increase ours as well if it increases.
645 #define MEMCG_CACHES_MIN_SIZE 4
646 #define MEMCG_CACHES_MAX_SIZE 65535
649 * A lot of the calls to the cache allocation functions are expected to be
650 * inlined by the compiler. Since the calls to memcg_kmem_get_cache are
651 * conditional to this static branch, we'll have to allow modules that does
652 * kmem_cache_alloc and the such to see this symbol as well
654 struct static_key memcg_kmem_enabled_key;
655 EXPORT_SYMBOL(memcg_kmem_enabled_key);
657 static void disarm_kmem_keys(struct mem_cgroup *memcg)
659 if (memcg_kmem_is_active(memcg)) {
660 static_key_slow_dec(&memcg_kmem_enabled_key);
661 ida_simple_remove(&kmem_limited_groups, memcg->kmemcg_id);
664 * This check can't live in kmem destruction function,
665 * since the charges will outlive the cgroup
667 WARN_ON(res_counter_read_u64(&memcg->kmem, RES_USAGE) != 0);
670 static void disarm_kmem_keys(struct mem_cgroup *memcg)
673 #endif /* CONFIG_MEMCG_KMEM */
675 static void disarm_static_keys(struct mem_cgroup *memcg)
677 disarm_sock_keys(memcg);
678 disarm_kmem_keys(memcg);
681 static void drain_all_stock_async(struct mem_cgroup *memcg);
683 static struct mem_cgroup_per_zone *
684 mem_cgroup_zoneinfo(struct mem_cgroup *memcg, int nid, int zid)
686 VM_BUG_ON((unsigned)nid >= nr_node_ids);
687 return &memcg->info.nodeinfo[nid]->zoneinfo[zid];
690 struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *memcg)
695 static struct mem_cgroup_per_zone *
696 page_cgroup_zoneinfo(struct mem_cgroup *memcg, struct page *page)
698 int nid = page_to_nid(page);
699 int zid = page_zonenum(page);
701 return mem_cgroup_zoneinfo(memcg, nid, zid);
704 static struct mem_cgroup_tree_per_zone *
705 soft_limit_tree_node_zone(int nid, int zid)
707 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
710 static struct mem_cgroup_tree_per_zone *
711 soft_limit_tree_from_page(struct page *page)
713 int nid = page_to_nid(page);
714 int zid = page_zonenum(page);
716 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
720 __mem_cgroup_insert_exceeded(struct mem_cgroup *memcg,
721 struct mem_cgroup_per_zone *mz,
722 struct mem_cgroup_tree_per_zone *mctz,
723 unsigned long long new_usage_in_excess)
725 struct rb_node **p = &mctz->rb_root.rb_node;
726 struct rb_node *parent = NULL;
727 struct mem_cgroup_per_zone *mz_node;
732 mz->usage_in_excess = new_usage_in_excess;
733 if (!mz->usage_in_excess)
737 mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
739 if (mz->usage_in_excess < mz_node->usage_in_excess)
742 * We can't avoid mem cgroups that are over their soft
743 * limit by the same amount
745 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
748 rb_link_node(&mz->tree_node, parent, p);
749 rb_insert_color(&mz->tree_node, &mctz->rb_root);
754 __mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
755 struct mem_cgroup_per_zone *mz,
756 struct mem_cgroup_tree_per_zone *mctz)
760 rb_erase(&mz->tree_node, &mctz->rb_root);
765 mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
766 struct mem_cgroup_per_zone *mz,
767 struct mem_cgroup_tree_per_zone *mctz)
769 spin_lock(&mctz->lock);
770 __mem_cgroup_remove_exceeded(memcg, mz, mctz);
771 spin_unlock(&mctz->lock);
775 static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
777 unsigned long long excess;
778 struct mem_cgroup_per_zone *mz;
779 struct mem_cgroup_tree_per_zone *mctz;
780 int nid = page_to_nid(page);
781 int zid = page_zonenum(page);
782 mctz = soft_limit_tree_from_page(page);
785 * Necessary to update all ancestors when hierarchy is used.
786 * because their event counter is not touched.
788 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
789 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
790 excess = res_counter_soft_limit_excess(&memcg->res);
792 * We have to update the tree if mz is on RB-tree or
793 * mem is over its softlimit.
795 if (excess || mz->on_tree) {
796 spin_lock(&mctz->lock);
797 /* if on-tree, remove it */
799 __mem_cgroup_remove_exceeded(memcg, mz, mctz);
801 * Insert again. mz->usage_in_excess will be updated.
802 * If excess is 0, no tree ops.
804 __mem_cgroup_insert_exceeded(memcg, mz, mctz, excess);
805 spin_unlock(&mctz->lock);
810 static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
813 struct mem_cgroup_per_zone *mz;
814 struct mem_cgroup_tree_per_zone *mctz;
816 for_each_node(node) {
817 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
818 mz = mem_cgroup_zoneinfo(memcg, node, zone);
819 mctz = soft_limit_tree_node_zone(node, zone);
820 mem_cgroup_remove_exceeded(memcg, mz, mctz);
825 static struct mem_cgroup_per_zone *
826 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
828 struct rb_node *rightmost = NULL;
829 struct mem_cgroup_per_zone *mz;
833 rightmost = rb_last(&mctz->rb_root);
835 goto done; /* Nothing to reclaim from */
837 mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
839 * Remove the node now but someone else can add it back,
840 * we will to add it back at the end of reclaim to its correct
841 * position in the tree.
843 __mem_cgroup_remove_exceeded(mz->memcg, mz, mctz);
844 if (!res_counter_soft_limit_excess(&mz->memcg->res) ||
845 !css_tryget(&mz->memcg->css))
851 static struct mem_cgroup_per_zone *
852 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
854 struct mem_cgroup_per_zone *mz;
856 spin_lock(&mctz->lock);
857 mz = __mem_cgroup_largest_soft_limit_node(mctz);
858 spin_unlock(&mctz->lock);
863 * Implementation Note: reading percpu statistics for memcg.
865 * Both of vmstat[] and percpu_counter has threshold and do periodic
866 * synchronization to implement "quick" read. There are trade-off between
867 * reading cost and precision of value. Then, we may have a chance to implement
868 * a periodic synchronizion of counter in memcg's counter.
870 * But this _read() function is used for user interface now. The user accounts
871 * memory usage by memory cgroup and he _always_ requires exact value because
872 * he accounts memory. Even if we provide quick-and-fuzzy read, we always
873 * have to visit all online cpus and make sum. So, for now, unnecessary
874 * synchronization is not implemented. (just implemented for cpu hotplug)
876 * If there are kernel internal actions which can make use of some not-exact
877 * value, and reading all cpu value can be performance bottleneck in some
878 * common workload, threashold and synchonization as vmstat[] should be
881 static long mem_cgroup_read_stat(struct mem_cgroup *memcg,
882 enum mem_cgroup_stat_index idx)
888 for_each_online_cpu(cpu)
889 val += per_cpu(memcg->stat->count[idx], cpu);
890 #ifdef CONFIG_HOTPLUG_CPU
891 spin_lock(&memcg->pcp_counter_lock);
892 val += memcg->nocpu_base.count[idx];
893 spin_unlock(&memcg->pcp_counter_lock);
899 static void mem_cgroup_swap_statistics(struct mem_cgroup *memcg,
902 int val = (charge) ? 1 : -1;
903 this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_SWAP], val);
906 static unsigned long mem_cgroup_read_events(struct mem_cgroup *memcg,
907 enum mem_cgroup_events_index idx)
909 unsigned long val = 0;
912 for_each_online_cpu(cpu)
913 val += per_cpu(memcg->stat->events[idx], cpu);
914 #ifdef CONFIG_HOTPLUG_CPU
915 spin_lock(&memcg->pcp_counter_lock);
916 val += memcg->nocpu_base.events[idx];
917 spin_unlock(&memcg->pcp_counter_lock);
922 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
924 bool anon, int nr_pages)
929 * Here, RSS means 'mapped anon' and anon's SwapCache. Shmem/tmpfs is
930 * counted as CACHE even if it's on ANON LRU.
933 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS],
936 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_CACHE],
939 if (PageTransHuge(page))
940 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS_HUGE],
943 /* pagein of a big page is an event. So, ignore page size */
945 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGIN]);
947 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGOUT]);
948 nr_pages = -nr_pages; /* for event */
951 __this_cpu_add(memcg->stat->nr_page_events, nr_pages);
957 mem_cgroup_get_lru_size(struct lruvec *lruvec, enum lru_list lru)
959 struct mem_cgroup_per_zone *mz;
961 mz = container_of(lruvec, struct mem_cgroup_per_zone, lruvec);
962 return mz->lru_size[lru];
966 mem_cgroup_zone_nr_lru_pages(struct mem_cgroup *memcg, int nid, int zid,
967 unsigned int lru_mask)
969 struct mem_cgroup_per_zone *mz;
971 unsigned long ret = 0;
973 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
976 if (BIT(lru) & lru_mask)
977 ret += mz->lru_size[lru];
983 mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
984 int nid, unsigned int lru_mask)
989 for (zid = 0; zid < MAX_NR_ZONES; zid++)
990 total += mem_cgroup_zone_nr_lru_pages(memcg,
996 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
997 unsigned int lru_mask)
1002 for_each_node_state(nid, N_MEMORY)
1003 total += mem_cgroup_node_nr_lru_pages(memcg, nid, lru_mask);
1007 static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
1008 enum mem_cgroup_events_target target)
1010 unsigned long val, next;
1012 val = __this_cpu_read(memcg->stat->nr_page_events);
1013 next = __this_cpu_read(memcg->stat->targets[target]);
1014 /* from time_after() in jiffies.h */
1015 if ((long)next - (long)val < 0) {
1017 case MEM_CGROUP_TARGET_THRESH:
1018 next = val + THRESHOLDS_EVENTS_TARGET;
1020 case MEM_CGROUP_TARGET_SOFTLIMIT:
1021 next = val + SOFTLIMIT_EVENTS_TARGET;
1023 case MEM_CGROUP_TARGET_NUMAINFO:
1024 next = val + NUMAINFO_EVENTS_TARGET;
1029 __this_cpu_write(memcg->stat->targets[target], next);
1036 * Check events in order.
1039 static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
1042 /* threshold event is triggered in finer grain than soft limit */
1043 if (unlikely(mem_cgroup_event_ratelimit(memcg,
1044 MEM_CGROUP_TARGET_THRESH))) {
1046 bool do_numainfo __maybe_unused;
1048 do_softlimit = mem_cgroup_event_ratelimit(memcg,
1049 MEM_CGROUP_TARGET_SOFTLIMIT);
1050 #if MAX_NUMNODES > 1
1051 do_numainfo = mem_cgroup_event_ratelimit(memcg,
1052 MEM_CGROUP_TARGET_NUMAINFO);
1056 mem_cgroup_threshold(memcg);
1057 if (unlikely(do_softlimit))
1058 mem_cgroup_update_tree(memcg, page);
1059 #if MAX_NUMNODES > 1
1060 if (unlikely(do_numainfo))
1061 atomic_inc(&memcg->numainfo_events);
1067 struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
1069 return mem_cgroup_from_css(
1070 cgroup_subsys_state(cont, mem_cgroup_subsys_id));
1073 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
1076 * mm_update_next_owner() may clear mm->owner to NULL
1077 * if it races with swapoff, page migration, etc.
1078 * So this can be called with p == NULL.
1083 return mem_cgroup_from_css(task_subsys_state(p, mem_cgroup_subsys_id));
1086 struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
1088 struct mem_cgroup *memcg = NULL;
1093 * Because we have no locks, mm->owner's may be being moved to other
1094 * cgroup. We use css_tryget() here even if this looks
1095 * pessimistic (rather than adding locks here).
1099 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
1100 if (unlikely(!memcg))
1102 } while (!css_tryget(&memcg->css));
1108 * Returns a next (in a pre-order walk) alive memcg (with elevated css
1109 * ref. count) or NULL if the whole root's subtree has been visited.
1111 * helper function to be used by mem_cgroup_iter
1113 static struct mem_cgroup *__mem_cgroup_iter_next(struct mem_cgroup *root,
1114 struct mem_cgroup *last_visited)
1116 struct cgroup *prev_cgroup, *next_cgroup;
1119 * Root is not visited by cgroup iterators so it needs an
1125 prev_cgroup = (last_visited == root) ? NULL
1126 : last_visited->css.cgroup;
1128 next_cgroup = cgroup_next_descendant_pre(
1129 prev_cgroup, root->css.cgroup);
1132 * Even if we found a group we have to make sure it is
1133 * alive. css && !memcg means that the groups should be
1134 * skipped and we should continue the tree walk.
1135 * last_visited css is safe to use because it is
1136 * protected by css_get and the tree walk is rcu safe.
1139 struct mem_cgroup *mem = mem_cgroup_from_cont(
1141 if (css_tryget(&mem->css))
1144 prev_cgroup = next_cgroup;
1153 * mem_cgroup_iter - iterate over memory cgroup hierarchy
1154 * @root: hierarchy root
1155 * @prev: previously returned memcg, NULL on first invocation
1156 * @reclaim: cookie for shared reclaim walks, NULL for full walks
1158 * Returns references to children of the hierarchy below @root, or
1159 * @root itself, or %NULL after a full round-trip.
1161 * Caller must pass the return value in @prev on subsequent
1162 * invocations for reference counting, or use mem_cgroup_iter_break()
1163 * to cancel a hierarchy walk before the round-trip is complete.
1165 * Reclaimers can specify a zone and a priority level in @reclaim to
1166 * divide up the memcgs in the hierarchy among all concurrent
1167 * reclaimers operating on the same zone and priority.
1169 struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
1170 struct mem_cgroup *prev,
1171 struct mem_cgroup_reclaim_cookie *reclaim)
1173 struct mem_cgroup *memcg = NULL;
1174 struct mem_cgroup *last_visited = NULL;
1175 unsigned long uninitialized_var(dead_count);
1177 if (mem_cgroup_disabled())
1181 root = root_mem_cgroup;
1183 if (prev && !reclaim)
1184 last_visited = prev;
1186 if (!root->use_hierarchy && root != root_mem_cgroup) {
1194 struct mem_cgroup_reclaim_iter *uninitialized_var(iter);
1197 int nid = zone_to_nid(reclaim->zone);
1198 int zid = zone_idx(reclaim->zone);
1199 struct mem_cgroup_per_zone *mz;
1201 mz = mem_cgroup_zoneinfo(root, nid, zid);
1202 iter = &mz->reclaim_iter[reclaim->priority];
1203 if (prev && reclaim->generation != iter->generation) {
1204 iter->last_visited = NULL;
1209 * If the dead_count mismatches, a destruction
1210 * has happened or is happening concurrently.
1211 * If the dead_count matches, a destruction
1212 * might still happen concurrently, but since
1213 * we checked under RCU, that destruction
1214 * won't free the object until we release the
1215 * RCU reader lock. Thus, the dead_count
1216 * check verifies the pointer is still valid,
1217 * css_tryget() verifies the cgroup pointed to
1220 dead_count = atomic_read(&root->dead_count);
1221 if (dead_count == iter->last_dead_count) {
1223 last_visited = iter->last_visited;
1224 if (last_visited && last_visited != root &&
1225 !css_tryget(&last_visited->css))
1226 last_visited = NULL;
1230 memcg = __mem_cgroup_iter_next(root, last_visited);
1233 if (last_visited && last_visited != root)
1234 css_put(&last_visited->css);
1236 iter->last_visited = memcg;
1238 iter->last_dead_count = dead_count;
1242 else if (!prev && memcg)
1243 reclaim->generation = iter->generation;
1252 if (prev && prev != root)
1253 css_put(&prev->css);
1259 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1260 * @root: hierarchy root
1261 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1263 void mem_cgroup_iter_break(struct mem_cgroup *root,
1264 struct mem_cgroup *prev)
1267 root = root_mem_cgroup;
1268 if (prev && prev != root)
1269 css_put(&prev->css);
1273 * Iteration constructs for visiting all cgroups (under a tree). If
1274 * loops are exited prematurely (break), mem_cgroup_iter_break() must
1275 * be used for reference counting.
1277 #define for_each_mem_cgroup_tree(iter, root) \
1278 for (iter = mem_cgroup_iter(root, NULL, NULL); \
1280 iter = mem_cgroup_iter(root, iter, NULL))
1282 #define for_each_mem_cgroup(iter) \
1283 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
1285 iter = mem_cgroup_iter(NULL, iter, NULL))
1287 void __mem_cgroup_count_vm_event(struct mm_struct *mm, enum vm_event_item idx)
1289 struct mem_cgroup *memcg;
1292 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
1293 if (unlikely(!memcg))
1298 this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGFAULT]);
1301 this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGMAJFAULT]);
1309 EXPORT_SYMBOL(__mem_cgroup_count_vm_event);
1312 * mem_cgroup_zone_lruvec - get the lru list vector for a zone and memcg
1313 * @zone: zone of the wanted lruvec
1314 * @memcg: memcg of the wanted lruvec
1316 * Returns the lru list vector holding pages for the given @zone and
1317 * @mem. This can be the global zone lruvec, if the memory controller
1320 struct lruvec *mem_cgroup_zone_lruvec(struct zone *zone,
1321 struct mem_cgroup *memcg)
1323 struct mem_cgroup_per_zone *mz;
1324 struct lruvec *lruvec;
1326 if (mem_cgroup_disabled()) {
1327 lruvec = &zone->lruvec;
1331 mz = mem_cgroup_zoneinfo(memcg, zone_to_nid(zone), zone_idx(zone));
1332 lruvec = &mz->lruvec;
1335 * Since a node can be onlined after the mem_cgroup was created,
1336 * we have to be prepared to initialize lruvec->zone here;
1337 * and if offlined then reonlined, we need to reinitialize it.
1339 if (unlikely(lruvec->zone != zone))
1340 lruvec->zone = zone;
1345 * Following LRU functions are allowed to be used without PCG_LOCK.
1346 * Operations are called by routine of global LRU independently from memcg.
1347 * What we have to take care of here is validness of pc->mem_cgroup.
1349 * Changes to pc->mem_cgroup happens when
1352 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
1353 * It is added to LRU before charge.
1354 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
1355 * When moving account, the page is not on LRU. It's isolated.
1359 * mem_cgroup_page_lruvec - return lruvec for adding an lru page
1361 * @zone: zone of the page
1363 struct lruvec *mem_cgroup_page_lruvec(struct page *page, struct zone *zone)
1365 struct mem_cgroup_per_zone *mz;
1366 struct mem_cgroup *memcg;
1367 struct page_cgroup *pc;
1368 struct lruvec *lruvec;
1370 if (mem_cgroup_disabled()) {
1371 lruvec = &zone->lruvec;
1375 pc = lookup_page_cgroup(page);
1376 memcg = pc->mem_cgroup;
1379 * Surreptitiously switch any uncharged offlist page to root:
1380 * an uncharged page off lru does nothing to secure
1381 * its former mem_cgroup from sudden removal.
1383 * Our caller holds lru_lock, and PageCgroupUsed is updated
1384 * under page_cgroup lock: between them, they make all uses
1385 * of pc->mem_cgroup safe.
1387 if (!PageLRU(page) && !PageCgroupUsed(pc) && memcg != root_mem_cgroup)
1388 pc->mem_cgroup = memcg = root_mem_cgroup;
1390 mz = page_cgroup_zoneinfo(memcg, page);
1391 lruvec = &mz->lruvec;
1394 * Since a node can be onlined after the mem_cgroup was created,
1395 * we have to be prepared to initialize lruvec->zone here;
1396 * and if offlined then reonlined, we need to reinitialize it.
1398 if (unlikely(lruvec->zone != zone))
1399 lruvec->zone = zone;
1404 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1405 * @lruvec: mem_cgroup per zone lru vector
1406 * @lru: index of lru list the page is sitting on
1407 * @nr_pages: positive when adding or negative when removing
1409 * This function must be called when a page is added to or removed from an
1412 void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
1415 struct mem_cgroup_per_zone *mz;
1416 unsigned long *lru_size;
1418 if (mem_cgroup_disabled())
1421 mz = container_of(lruvec, struct mem_cgroup_per_zone, lruvec);
1422 lru_size = mz->lru_size + lru;
1423 *lru_size += nr_pages;
1424 VM_BUG_ON((long)(*lru_size) < 0);
1428 * Checks whether given mem is same or in the root_mem_cgroup's
1431 bool __mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
1432 struct mem_cgroup *memcg)
1434 if (root_memcg == memcg)
1436 if (!root_memcg->use_hierarchy || !memcg)
1438 return css_is_ancestor(&memcg->css, &root_memcg->css);
1441 static bool mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
1442 struct mem_cgroup *memcg)
1447 ret = __mem_cgroup_same_or_subtree(root_memcg, memcg);
1452 int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *memcg)
1455 struct mem_cgroup *curr = NULL;
1456 struct task_struct *p;
1458 p = find_lock_task_mm(task);
1460 curr = try_get_mem_cgroup_from_mm(p->mm);
1464 * All threads may have already detached their mm's, but the oom
1465 * killer still needs to detect if they have already been oom
1466 * killed to prevent needlessly killing additional tasks.
1469 curr = mem_cgroup_from_task(task);
1471 css_get(&curr->css);
1477 * We should check use_hierarchy of "memcg" not "curr". Because checking
1478 * use_hierarchy of "curr" here make this function true if hierarchy is
1479 * enabled in "curr" and "curr" is a child of "memcg" in *cgroup*
1480 * hierarchy(even if use_hierarchy is disabled in "memcg").
1482 ret = mem_cgroup_same_or_subtree(memcg, curr);
1483 css_put(&curr->css);
1487 int mem_cgroup_inactive_anon_is_low(struct lruvec *lruvec)
1489 unsigned long inactive_ratio;
1490 unsigned long inactive;
1491 unsigned long active;
1494 inactive = mem_cgroup_get_lru_size(lruvec, LRU_INACTIVE_ANON);
1495 active = mem_cgroup_get_lru_size(lruvec, LRU_ACTIVE_ANON);
1497 gb = (inactive + active) >> (30 - PAGE_SHIFT);
1499 inactive_ratio = int_sqrt(10 * gb);
1503 return inactive * inactive_ratio < active;
1506 #define mem_cgroup_from_res_counter(counter, member) \
1507 container_of(counter, struct mem_cgroup, member)
1510 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1511 * @memcg: the memory cgroup
1513 * Returns the maximum amount of memory @mem can be charged with, in
1516 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1518 unsigned long long margin;
1520 margin = res_counter_margin(&memcg->res);
1521 if (do_swap_account)
1522 margin = min(margin, res_counter_margin(&memcg->memsw));
1523 return margin >> PAGE_SHIFT;
1526 int mem_cgroup_swappiness(struct mem_cgroup *memcg)
1528 struct cgroup *cgrp = memcg->css.cgroup;
1531 if (cgrp->parent == NULL)
1532 return vm_swappiness;
1534 return memcg->swappiness;
1538 * memcg->moving_account is used for checking possibility that some thread is
1539 * calling move_account(). When a thread on CPU-A starts moving pages under
1540 * a memcg, other threads should check memcg->moving_account under
1541 * rcu_read_lock(), like this:
1545 * memcg->moving_account+1 if (memcg->mocing_account)
1547 * synchronize_rcu() update something.
1552 /* for quick checking without looking up memcg */
1553 atomic_t memcg_moving __read_mostly;
1555 static void mem_cgroup_start_move(struct mem_cgroup *memcg)
1557 atomic_inc(&memcg_moving);
1558 atomic_inc(&memcg->moving_account);
1562 static void mem_cgroup_end_move(struct mem_cgroup *memcg)
1565 * Now, mem_cgroup_clear_mc() may call this function with NULL.
1566 * We check NULL in callee rather than caller.
1569 atomic_dec(&memcg_moving);
1570 atomic_dec(&memcg->moving_account);
1575 * 2 routines for checking "mem" is under move_account() or not.
1577 * mem_cgroup_stolen() - checking whether a cgroup is mc.from or not. This
1578 * is used for avoiding races in accounting. If true,
1579 * pc->mem_cgroup may be overwritten.
1581 * mem_cgroup_under_move() - checking a cgroup is mc.from or mc.to or
1582 * under hierarchy of moving cgroups. This is for
1583 * waiting at hith-memory prressure caused by "move".
1586 static bool mem_cgroup_stolen(struct mem_cgroup *memcg)
1588 VM_BUG_ON(!rcu_read_lock_held());
1589 return atomic_read(&memcg->moving_account) > 0;
1592 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1594 struct mem_cgroup *from;
1595 struct mem_cgroup *to;
1598 * Unlike task_move routines, we access mc.to, mc.from not under
1599 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1601 spin_lock(&mc.lock);
1607 ret = mem_cgroup_same_or_subtree(memcg, from)
1608 || mem_cgroup_same_or_subtree(memcg, to);
1610 spin_unlock(&mc.lock);
1614 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1616 if (mc.moving_task && current != mc.moving_task) {
1617 if (mem_cgroup_under_move(memcg)) {
1619 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1620 /* moving charge context might have finished. */
1623 finish_wait(&mc.waitq, &wait);
1631 * Take this lock when
1632 * - a code tries to modify page's memcg while it's USED.
1633 * - a code tries to modify page state accounting in a memcg.
1634 * see mem_cgroup_stolen(), too.
1636 static void move_lock_mem_cgroup(struct mem_cgroup *memcg,
1637 unsigned long *flags)
1639 spin_lock_irqsave(&memcg->move_lock, *flags);
1642 static void move_unlock_mem_cgroup(struct mem_cgroup *memcg,
1643 unsigned long *flags)
1645 spin_unlock_irqrestore(&memcg->move_lock, *flags);
1648 #define K(x) ((x) << (PAGE_SHIFT-10))
1650 * mem_cgroup_print_oom_info: Print OOM information relevant to memory controller.
1651 * @memcg: The memory cgroup that went over limit
1652 * @p: Task that is going to be killed
1654 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1657 void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1659 struct cgroup *task_cgrp;
1660 struct cgroup *mem_cgrp;
1662 * Need a buffer in BSS, can't rely on allocations. The code relies
1663 * on the assumption that OOM is serialized for memory controller.
1664 * If this assumption is broken, revisit this code.
1666 static char memcg_name[PATH_MAX];
1668 struct mem_cgroup *iter;
1676 mem_cgrp = memcg->css.cgroup;
1677 task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
1679 ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
1682 * Unfortunately, we are unable to convert to a useful name
1683 * But we'll still print out the usage information
1690 pr_info("Task in %s killed", memcg_name);
1693 ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
1701 * Continues from above, so we don't need an KERN_ level
1703 pr_cont(" as a result of limit of %s\n", memcg_name);
1706 pr_info("memory: usage %llukB, limit %llukB, failcnt %llu\n",
1707 res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
1708 res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
1709 res_counter_read_u64(&memcg->res, RES_FAILCNT));
1710 pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %llu\n",
1711 res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
1712 res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
1713 res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
1714 pr_info("kmem: usage %llukB, limit %llukB, failcnt %llu\n",
1715 res_counter_read_u64(&memcg->kmem, RES_USAGE) >> 10,
1716 res_counter_read_u64(&memcg->kmem, RES_LIMIT) >> 10,
1717 res_counter_read_u64(&memcg->kmem, RES_FAILCNT));
1719 for_each_mem_cgroup_tree(iter, memcg) {
1720 pr_info("Memory cgroup stats");
1723 ret = cgroup_path(iter->css.cgroup, memcg_name, PATH_MAX);
1725 pr_cont(" for %s", memcg_name);
1729 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
1730 if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
1732 pr_cont(" %s:%ldKB", mem_cgroup_stat_names[i],
1733 K(mem_cgroup_read_stat(iter, i)));
1736 for (i = 0; i < NR_LRU_LISTS; i++)
1737 pr_cont(" %s:%luKB", mem_cgroup_lru_names[i],
1738 K(mem_cgroup_nr_lru_pages(iter, BIT(i))));
1745 * This function returns the number of memcg under hierarchy tree. Returns
1746 * 1(self count) if no children.
1748 static int mem_cgroup_count_children(struct mem_cgroup *memcg)
1751 struct mem_cgroup *iter;
1753 for_each_mem_cgroup_tree(iter, memcg)
1759 * Return the memory (and swap, if configured) limit for a memcg.
1761 static u64 mem_cgroup_get_limit(struct mem_cgroup *memcg)
1765 limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
1768 * Do not consider swap space if we cannot swap due to swappiness
1770 if (mem_cgroup_swappiness(memcg)) {
1773 limit += total_swap_pages << PAGE_SHIFT;
1774 memsw = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
1777 * If memsw is finite and limits the amount of swap space
1778 * available to this memcg, return that limit.
1780 limit = min(limit, memsw);
1786 static void mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
1789 struct mem_cgroup *iter;
1790 unsigned long chosen_points = 0;
1791 unsigned long totalpages;
1792 unsigned int points = 0;
1793 struct task_struct *chosen = NULL;
1796 * If current has a pending SIGKILL or is exiting, then automatically
1797 * select it. The goal is to allow it to allocate so that it may
1798 * quickly exit and free its memory.
1800 if (fatal_signal_pending(current) || current->flags & PF_EXITING) {
1801 set_thread_flag(TIF_MEMDIE);
1805 check_panic_on_oom(CONSTRAINT_MEMCG, gfp_mask, order, NULL);
1806 totalpages = mem_cgroup_get_limit(memcg) >> PAGE_SHIFT ? : 1;
1807 for_each_mem_cgroup_tree(iter, memcg) {
1808 struct cgroup *cgroup = iter->css.cgroup;
1809 struct cgroup_iter it;
1810 struct task_struct *task;
1812 cgroup_iter_start(cgroup, &it);
1813 while ((task = cgroup_iter_next(cgroup, &it))) {
1814 switch (oom_scan_process_thread(task, totalpages, NULL,
1816 case OOM_SCAN_SELECT:
1818 put_task_struct(chosen);
1820 chosen_points = ULONG_MAX;
1821 get_task_struct(chosen);
1823 case OOM_SCAN_CONTINUE:
1825 case OOM_SCAN_ABORT:
1826 cgroup_iter_end(cgroup, &it);
1827 mem_cgroup_iter_break(memcg, iter);
1829 put_task_struct(chosen);
1834 points = oom_badness(task, memcg, NULL, totalpages);
1835 if (points > chosen_points) {
1837 put_task_struct(chosen);
1839 chosen_points = points;
1840 get_task_struct(chosen);
1843 cgroup_iter_end(cgroup, &it);
1848 points = chosen_points * 1000 / totalpages;
1849 oom_kill_process(chosen, gfp_mask, order, points, totalpages, memcg,
1850 NULL, "Memory cgroup out of memory");
1853 static unsigned long mem_cgroup_reclaim(struct mem_cgroup *memcg,
1855 unsigned long flags)
1857 unsigned long total = 0;
1858 bool noswap = false;
1861 if (flags & MEM_CGROUP_RECLAIM_NOSWAP)
1863 if (!(flags & MEM_CGROUP_RECLAIM_SHRINK) && memcg->memsw_is_minimum)
1866 for (loop = 0; loop < MEM_CGROUP_MAX_RECLAIM_LOOPS; loop++) {
1868 drain_all_stock_async(memcg);
1869 total += try_to_free_mem_cgroup_pages(memcg, gfp_mask, noswap);
1871 * Allow limit shrinkers, which are triggered directly
1872 * by userspace, to catch signals and stop reclaim
1873 * after minimal progress, regardless of the margin.
1875 if (total && (flags & MEM_CGROUP_RECLAIM_SHRINK))
1877 if (mem_cgroup_margin(memcg))
1880 * If nothing was reclaimed after two attempts, there
1881 * may be no reclaimable pages in this hierarchy.
1890 * test_mem_cgroup_node_reclaimable
1891 * @memcg: the target memcg
1892 * @nid: the node ID to be checked.
1893 * @noswap : specify true here if the user wants flle only information.
1895 * This function returns whether the specified memcg contains any
1896 * reclaimable pages on a node. Returns true if there are any reclaimable
1897 * pages in the node.
1899 static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *memcg,
1900 int nid, bool noswap)
1902 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_FILE))
1904 if (noswap || !total_swap_pages)
1906 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_ANON))
1911 #if MAX_NUMNODES > 1
1914 * Always updating the nodemask is not very good - even if we have an empty
1915 * list or the wrong list here, we can start from some node and traverse all
1916 * nodes based on the zonelist. So update the list loosely once per 10 secs.
1919 static void mem_cgroup_may_update_nodemask(struct mem_cgroup *memcg)
1923 * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
1924 * pagein/pageout changes since the last update.
1926 if (!atomic_read(&memcg->numainfo_events))
1928 if (atomic_inc_return(&memcg->numainfo_updating) > 1)
1931 /* make a nodemask where this memcg uses memory from */
1932 memcg->scan_nodes = node_states[N_MEMORY];
1934 for_each_node_mask(nid, node_states[N_MEMORY]) {
1936 if (!test_mem_cgroup_node_reclaimable(memcg, nid, false))
1937 node_clear(nid, memcg->scan_nodes);
1940 atomic_set(&memcg->numainfo_events, 0);
1941 atomic_set(&memcg->numainfo_updating, 0);
1945 * Selecting a node where we start reclaim from. Because what we need is just
1946 * reducing usage counter, start from anywhere is O,K. Considering
1947 * memory reclaim from current node, there are pros. and cons.
1949 * Freeing memory from current node means freeing memory from a node which
1950 * we'll use or we've used. So, it may make LRU bad. And if several threads
1951 * hit limits, it will see a contention on a node. But freeing from remote
1952 * node means more costs for memory reclaim because of memory latency.
1954 * Now, we use round-robin. Better algorithm is welcomed.
1956 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1960 mem_cgroup_may_update_nodemask(memcg);
1961 node = memcg->last_scanned_node;
1963 node = next_node(node, memcg->scan_nodes);
1964 if (node == MAX_NUMNODES)
1965 node = first_node(memcg->scan_nodes);
1967 * We call this when we hit limit, not when pages are added to LRU.
1968 * No LRU may hold pages because all pages are UNEVICTABLE or
1969 * memcg is too small and all pages are not on LRU. In that case,
1970 * we use curret node.
1972 if (unlikely(node == MAX_NUMNODES))
1973 node = numa_node_id();
1975 memcg->last_scanned_node = node;
1980 * Check all nodes whether it contains reclaimable pages or not.
1981 * For quick scan, we make use of scan_nodes. This will allow us to skip
1982 * unused nodes. But scan_nodes is lazily updated and may not cotain
1983 * enough new information. We need to do double check.
1985 static bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
1990 * quick check...making use of scan_node.
1991 * We can skip unused nodes.
1993 if (!nodes_empty(memcg->scan_nodes)) {
1994 for (nid = first_node(memcg->scan_nodes);
1996 nid = next_node(nid, memcg->scan_nodes)) {
1998 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
2003 * Check rest of nodes.
2005 for_each_node_state(nid, N_MEMORY) {
2006 if (node_isset(nid, memcg->scan_nodes))
2008 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
2015 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
2020 static bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
2022 return test_mem_cgroup_node_reclaimable(memcg, 0, noswap);
2026 static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
2029 unsigned long *total_scanned)
2031 struct mem_cgroup *victim = NULL;
2034 unsigned long excess;
2035 unsigned long nr_scanned;
2036 struct mem_cgroup_reclaim_cookie reclaim = {
2041 excess = res_counter_soft_limit_excess(&root_memcg->res) >> PAGE_SHIFT;
2044 victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
2049 * If we have not been able to reclaim
2050 * anything, it might because there are
2051 * no reclaimable pages under this hierarchy
2056 * We want to do more targeted reclaim.
2057 * excess >> 2 is not to excessive so as to
2058 * reclaim too much, nor too less that we keep
2059 * coming back to reclaim from this cgroup
2061 if (total >= (excess >> 2) ||
2062 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
2067 if (!mem_cgroup_reclaimable(victim, false))
2069 total += mem_cgroup_shrink_node_zone(victim, gfp_mask, false,
2071 *total_scanned += nr_scanned;
2072 if (!res_counter_soft_limit_excess(&root_memcg->res))
2075 mem_cgroup_iter_break(root_memcg, victim);
2079 static DEFINE_SPINLOCK(memcg_oom_lock);
2082 * Check OOM-Killer is already running under our hierarchy.
2083 * If someone is running, return false.
2085 static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
2087 struct mem_cgroup *iter, *failed = NULL;
2089 spin_lock(&memcg_oom_lock);
2091 for_each_mem_cgroup_tree(iter, memcg) {
2092 if (iter->oom_lock) {
2094 * this subtree of our hierarchy is already locked
2095 * so we cannot give a lock.
2098 mem_cgroup_iter_break(memcg, iter);
2101 iter->oom_lock = true;
2106 * OK, we failed to lock the whole subtree so we have
2107 * to clean up what we set up to the failing subtree
2109 for_each_mem_cgroup_tree(iter, memcg) {
2110 if (iter == failed) {
2111 mem_cgroup_iter_break(memcg, iter);
2114 iter->oom_lock = false;
2118 spin_unlock(&memcg_oom_lock);
2123 static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
2125 struct mem_cgroup *iter;
2127 spin_lock(&memcg_oom_lock);
2128 for_each_mem_cgroup_tree(iter, memcg)
2129 iter->oom_lock = false;
2130 spin_unlock(&memcg_oom_lock);
2133 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
2135 struct mem_cgroup *iter;
2137 for_each_mem_cgroup_tree(iter, memcg)
2138 atomic_inc(&iter->under_oom);
2141 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
2143 struct mem_cgroup *iter;
2146 * When a new child is created while the hierarchy is under oom,
2147 * mem_cgroup_oom_lock() may not be called. We have to use
2148 * atomic_add_unless() here.
2150 for_each_mem_cgroup_tree(iter, memcg)
2151 atomic_add_unless(&iter->under_oom, -1, 0);
2154 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
2156 struct oom_wait_info {
2157 struct mem_cgroup *memcg;
2161 static int memcg_oom_wake_function(wait_queue_t *wait,
2162 unsigned mode, int sync, void *arg)
2164 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
2165 struct mem_cgroup *oom_wait_memcg;
2166 struct oom_wait_info *oom_wait_info;
2168 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
2169 oom_wait_memcg = oom_wait_info->memcg;
2172 * Both of oom_wait_info->memcg and wake_memcg are stable under us.
2173 * Then we can use css_is_ancestor without taking care of RCU.
2175 if (!mem_cgroup_same_or_subtree(oom_wait_memcg, wake_memcg)
2176 && !mem_cgroup_same_or_subtree(wake_memcg, oom_wait_memcg))
2178 return autoremove_wake_function(wait, mode, sync, arg);
2181 static void memcg_wakeup_oom(struct mem_cgroup *memcg)
2183 atomic_inc(&memcg->oom_wakeups);
2184 /* for filtering, pass "memcg" as argument. */
2185 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
2188 static void memcg_oom_recover(struct mem_cgroup *memcg)
2190 if (memcg && atomic_read(&memcg->under_oom))
2191 memcg_wakeup_oom(memcg);
2195 * try to call OOM killer
2197 static void mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
2202 if (!current->memcg_oom.may_oom)
2205 current->memcg_oom.in_memcg_oom = 1;
2208 * As with any blocking lock, a contender needs to start
2209 * listening for wakeups before attempting the trylock,
2210 * otherwise it can miss the wakeup from the unlock and sleep
2211 * indefinitely. This is just open-coded because our locking
2212 * is so particular to memcg hierarchies.
2214 wakeups = atomic_read(&memcg->oom_wakeups);
2215 mem_cgroup_mark_under_oom(memcg);
2217 locked = mem_cgroup_oom_trylock(memcg);
2220 mem_cgroup_oom_notify(memcg);
2222 if (locked && !memcg->oom_kill_disable) {
2223 mem_cgroup_unmark_under_oom(memcg);
2224 mem_cgroup_out_of_memory(memcg, mask, order);
2225 mem_cgroup_oom_unlock(memcg);
2227 * There is no guarantee that an OOM-lock contender
2228 * sees the wakeups triggered by the OOM kill
2229 * uncharges. Wake any sleepers explicitely.
2231 memcg_oom_recover(memcg);
2234 * A system call can just return -ENOMEM, but if this
2235 * is a page fault and somebody else is handling the
2236 * OOM already, we need to sleep on the OOM waitqueue
2237 * for this memcg until the situation is resolved.
2238 * Which can take some time because it might be
2239 * handled by a userspace task.
2241 * However, this is the charge context, which means
2242 * that we may sit on a large call stack and hold
2243 * various filesystem locks, the mmap_sem etc. and we
2244 * don't want the OOM handler to deadlock on them
2245 * while we sit here and wait. Store the current OOM
2246 * context in the task_struct, then return -ENOMEM.
2247 * At the end of the page fault handler, with the
2248 * stack unwound, pagefault_out_of_memory() will check
2249 * back with us by calling
2250 * mem_cgroup_oom_synchronize(), possibly putting the
2253 current->memcg_oom.oom_locked = locked;
2254 current->memcg_oom.wakeups = wakeups;
2255 css_get(&memcg->css);
2256 current->memcg_oom.wait_on_memcg = memcg;
2261 * mem_cgroup_oom_synchronize - complete memcg OOM handling
2263 * This has to be called at the end of a page fault if the the memcg
2264 * OOM handler was enabled and the fault is returning %VM_FAULT_OOM.
2266 * Memcg supports userspace OOM handling, so failed allocations must
2267 * sleep on a waitqueue until the userspace task resolves the
2268 * situation. Sleeping directly in the charge context with all kinds
2269 * of locks held is not a good idea, instead we remember an OOM state
2270 * in the task and mem_cgroup_oom_synchronize() has to be called at
2271 * the end of the page fault to put the task to sleep and clean up the
2274 * Returns %true if an ongoing memcg OOM situation was detected and
2275 * finalized, %false otherwise.
2277 bool mem_cgroup_oom_synchronize(void)
2279 struct oom_wait_info owait;
2280 struct mem_cgroup *memcg;
2282 /* OOM is global, do not handle */
2283 if (!current->memcg_oom.in_memcg_oom)
2287 * We invoked the OOM killer but there is a chance that a kill
2288 * did not free up any charges. Everybody else might already
2289 * be sleeping, so restart the fault and keep the rampage
2290 * going until some charges are released.
2292 memcg = current->memcg_oom.wait_on_memcg;
2296 if (test_thread_flag(TIF_MEMDIE) || fatal_signal_pending(current))
2299 owait.memcg = memcg;
2300 owait.wait.flags = 0;
2301 owait.wait.func = memcg_oom_wake_function;
2302 owait.wait.private = current;
2303 INIT_LIST_HEAD(&owait.wait.task_list);
2305 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
2306 /* Only sleep if we didn't miss any wakeups since OOM */
2307 if (atomic_read(&memcg->oom_wakeups) == current->memcg_oom.wakeups)
2309 finish_wait(&memcg_oom_waitq, &owait.wait);
2311 mem_cgroup_unmark_under_oom(memcg);
2312 if (current->memcg_oom.oom_locked) {
2313 mem_cgroup_oom_unlock(memcg);
2315 * There is no guarantee that an OOM-lock contender
2316 * sees the wakeups triggered by the OOM kill
2317 * uncharges. Wake any sleepers explicitely.
2319 memcg_oom_recover(memcg);
2321 css_put(&memcg->css);
2322 current->memcg_oom.wait_on_memcg = NULL;
2324 current->memcg_oom.in_memcg_oom = 0;
2329 * Currently used to update mapped file statistics, but the routine can be
2330 * generalized to update other statistics as well.
2332 * Notes: Race condition
2334 * We usually use page_cgroup_lock() for accessing page_cgroup member but
2335 * it tends to be costly. But considering some conditions, we doesn't need
2336 * to do so _always_.
2338 * Considering "charge", lock_page_cgroup() is not required because all
2339 * file-stat operations happen after a page is attached to radix-tree. There
2340 * are no race with "charge".
2342 * Considering "uncharge", we know that memcg doesn't clear pc->mem_cgroup
2343 * at "uncharge" intentionally. So, we always see valid pc->mem_cgroup even
2344 * if there are race with "uncharge". Statistics itself is properly handled
2347 * Considering "move", this is an only case we see a race. To make the race
2348 * small, we check mm->moving_account and detect there are possibility of race
2349 * If there is, we take a lock.
2352 void __mem_cgroup_begin_update_page_stat(struct page *page,
2353 bool *locked, unsigned long *flags)
2355 struct mem_cgroup *memcg;
2356 struct page_cgroup *pc;
2358 pc = lookup_page_cgroup(page);
2360 memcg = pc->mem_cgroup;
2361 if (unlikely(!memcg || !PageCgroupUsed(pc)))
2364 * If this memory cgroup is not under account moving, we don't
2365 * need to take move_lock_mem_cgroup(). Because we already hold
2366 * rcu_read_lock(), any calls to move_account will be delayed until
2367 * rcu_read_unlock() if mem_cgroup_stolen() == true.
2369 if (!mem_cgroup_stolen(memcg))
2372 move_lock_mem_cgroup(memcg, flags);
2373 if (memcg != pc->mem_cgroup || !PageCgroupUsed(pc)) {
2374 move_unlock_mem_cgroup(memcg, flags);
2380 void __mem_cgroup_end_update_page_stat(struct page *page, unsigned long *flags)
2382 struct page_cgroup *pc = lookup_page_cgroup(page);
2385 * It's guaranteed that pc->mem_cgroup never changes while
2386 * lock is held because a routine modifies pc->mem_cgroup
2387 * should take move_lock_mem_cgroup().
2389 move_unlock_mem_cgroup(pc->mem_cgroup, flags);
2392 void mem_cgroup_update_page_stat(struct page *page,
2393 enum mem_cgroup_page_stat_item idx, int val)
2395 struct mem_cgroup *memcg;
2396 struct page_cgroup *pc = lookup_page_cgroup(page);
2397 unsigned long uninitialized_var(flags);
2399 if (mem_cgroup_disabled())
2402 memcg = pc->mem_cgroup;
2403 if (unlikely(!memcg || !PageCgroupUsed(pc)))
2407 case MEMCG_NR_FILE_MAPPED:
2408 idx = MEM_CGROUP_STAT_FILE_MAPPED;
2414 this_cpu_add(memcg->stat->count[idx], val);
2418 * size of first charge trial. "32" comes from vmscan.c's magic value.
2419 * TODO: maybe necessary to use big numbers in big irons.
2421 #define CHARGE_BATCH 32U
2422 struct memcg_stock_pcp {
2423 struct mem_cgroup *cached; /* this never be root cgroup */
2424 unsigned int nr_pages;
2425 struct work_struct work;
2426 unsigned long flags;
2427 #define FLUSHING_CACHED_CHARGE 0
2429 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
2430 static DEFINE_MUTEX(percpu_charge_mutex);
2433 * consume_stock: Try to consume stocked charge on this cpu.
2434 * @memcg: memcg to consume from.
2435 * @nr_pages: how many pages to charge.
2437 * The charges will only happen if @memcg matches the current cpu's memcg
2438 * stock, and at least @nr_pages are available in that stock. Failure to
2439 * service an allocation will refill the stock.
2441 * returns true if successful, false otherwise.
2443 static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2445 struct memcg_stock_pcp *stock;
2448 if (nr_pages > CHARGE_BATCH)
2451 stock = &get_cpu_var(memcg_stock);
2452 if (memcg == stock->cached && stock->nr_pages >= nr_pages)
2453 stock->nr_pages -= nr_pages;
2454 else /* need to call res_counter_charge */
2456 put_cpu_var(memcg_stock);
2461 * Returns stocks cached in percpu to res_counter and reset cached information.
2463 static void drain_stock(struct memcg_stock_pcp *stock)
2465 struct mem_cgroup *old = stock->cached;
2467 if (stock->nr_pages) {
2468 unsigned long bytes = stock->nr_pages * PAGE_SIZE;
2470 res_counter_uncharge(&old->res, bytes);
2471 if (do_swap_account)
2472 res_counter_uncharge(&old->memsw, bytes);
2473 stock->nr_pages = 0;
2475 stock->cached = NULL;
2479 * This must be called under preempt disabled or must be called by
2480 * a thread which is pinned to local cpu.
2482 static void drain_local_stock(struct work_struct *dummy)
2484 struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
2486 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2489 static void __init memcg_stock_init(void)
2493 for_each_possible_cpu(cpu) {
2494 struct memcg_stock_pcp *stock =
2495 &per_cpu(memcg_stock, cpu);
2496 INIT_WORK(&stock->work, drain_local_stock);
2501 * Cache charges(val) which is from res_counter, to local per_cpu area.
2502 * This will be consumed by consume_stock() function, later.
2504 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2506 struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
2508 if (stock->cached != memcg) { /* reset if necessary */
2510 stock->cached = memcg;
2512 stock->nr_pages += nr_pages;
2513 put_cpu_var(memcg_stock);
2517 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2518 * of the hierarchy under it. sync flag says whether we should block
2519 * until the work is done.
2521 static void drain_all_stock(struct mem_cgroup *root_memcg, bool sync)
2525 /* Notify other cpus that system-wide "drain" is running */
2528 for_each_online_cpu(cpu) {
2529 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2530 struct mem_cgroup *memcg;
2532 memcg = stock->cached;
2533 if (!memcg || !stock->nr_pages)
2535 if (!mem_cgroup_same_or_subtree(root_memcg, memcg))
2537 if (!test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2539 drain_local_stock(&stock->work);
2541 schedule_work_on(cpu, &stock->work);
2549 for_each_online_cpu(cpu) {
2550 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2551 if (test_bit(FLUSHING_CACHED_CHARGE, &stock->flags))
2552 flush_work(&stock->work);
2559 * Tries to drain stocked charges in other cpus. This function is asynchronous
2560 * and just put a work per cpu for draining localy on each cpu. Caller can
2561 * expects some charges will be back to res_counter later but cannot wait for
2564 static void drain_all_stock_async(struct mem_cgroup *root_memcg)
2567 * If someone calls draining, avoid adding more kworker runs.
2569 if (!mutex_trylock(&percpu_charge_mutex))
2571 drain_all_stock(root_memcg, false);
2572 mutex_unlock(&percpu_charge_mutex);
2575 /* This is a synchronous drain interface. */
2576 static void drain_all_stock_sync(struct mem_cgroup *root_memcg)
2578 /* called when force_empty is called */
2579 mutex_lock(&percpu_charge_mutex);
2580 drain_all_stock(root_memcg, true);
2581 mutex_unlock(&percpu_charge_mutex);
2585 * This function drains percpu counter value from DEAD cpu and
2586 * move it to local cpu. Note that this function can be preempted.
2588 static void mem_cgroup_drain_pcp_counter(struct mem_cgroup *memcg, int cpu)
2592 spin_lock(&memcg->pcp_counter_lock);
2593 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
2594 long x = per_cpu(memcg->stat->count[i], cpu);
2596 per_cpu(memcg->stat->count[i], cpu) = 0;
2597 memcg->nocpu_base.count[i] += x;
2599 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
2600 unsigned long x = per_cpu(memcg->stat->events[i], cpu);
2602 per_cpu(memcg->stat->events[i], cpu) = 0;
2603 memcg->nocpu_base.events[i] += x;
2605 spin_unlock(&memcg->pcp_counter_lock);
2608 static int __cpuinit memcg_cpu_hotplug_callback(struct notifier_block *nb,
2609 unsigned long action,
2612 int cpu = (unsigned long)hcpu;
2613 struct memcg_stock_pcp *stock;
2614 struct mem_cgroup *iter;
2616 if (action == CPU_ONLINE)
2619 if (action != CPU_DEAD && action != CPU_DEAD_FROZEN)
2622 for_each_mem_cgroup(iter)
2623 mem_cgroup_drain_pcp_counter(iter, cpu);
2625 stock = &per_cpu(memcg_stock, cpu);
2631 /* See __mem_cgroup_try_charge() for details */
2633 CHARGE_OK, /* success */
2634 CHARGE_RETRY, /* need to retry but retry is not bad */
2635 CHARGE_NOMEM, /* we can't do more. return -ENOMEM */
2636 CHARGE_WOULDBLOCK, /* GFP_WAIT wasn't set and no enough res. */
2639 static int mem_cgroup_do_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2640 unsigned int nr_pages, unsigned int min_pages,
2643 unsigned long csize = nr_pages * PAGE_SIZE;
2644 struct mem_cgroup *mem_over_limit;
2645 struct res_counter *fail_res;
2646 unsigned long flags = 0;
2649 ret = res_counter_charge(&memcg->res, csize, &fail_res);
2652 if (!do_swap_account)
2654 ret = res_counter_charge(&memcg->memsw, csize, &fail_res);
2658 res_counter_uncharge(&memcg->res, csize);
2659 mem_over_limit = mem_cgroup_from_res_counter(fail_res, memsw);
2660 flags |= MEM_CGROUP_RECLAIM_NOSWAP;
2662 mem_over_limit = mem_cgroup_from_res_counter(fail_res, res);
2664 * Never reclaim on behalf of optional batching, retry with a
2665 * single page instead.
2667 if (nr_pages > min_pages)
2668 return CHARGE_RETRY;
2670 if (!(gfp_mask & __GFP_WAIT))
2671 return CHARGE_WOULDBLOCK;
2673 if (gfp_mask & __GFP_NORETRY)
2674 return CHARGE_NOMEM;
2676 ret = mem_cgroup_reclaim(mem_over_limit, gfp_mask, flags);
2677 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2678 return CHARGE_RETRY;
2680 * Even though the limit is exceeded at this point, reclaim
2681 * may have been able to free some pages. Retry the charge
2682 * before killing the task.
2684 * Only for regular pages, though: huge pages are rather
2685 * unlikely to succeed so close to the limit, and we fall back
2686 * to regular pages anyway in case of failure.
2688 if (nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER) && ret)
2689 return CHARGE_RETRY;
2692 * At task move, charge accounts can be doubly counted. So, it's
2693 * better to wait until the end of task_move if something is going on.
2695 if (mem_cgroup_wait_acct_move(mem_over_limit))
2696 return CHARGE_RETRY;
2699 mem_cgroup_oom(mem_over_limit, gfp_mask, get_order(csize));
2701 return CHARGE_NOMEM;
2705 * __mem_cgroup_try_charge() does
2706 * 1. detect memcg to be charged against from passed *mm and *ptr,
2707 * 2. update res_counter
2708 * 3. call memory reclaim if necessary.
2710 * In some special case, if the task is fatal, fatal_signal_pending() or
2711 * has TIF_MEMDIE, this function returns -EINTR while writing root_mem_cgroup
2712 * to *ptr. There are two reasons for this. 1: fatal threads should quit as soon
2713 * as possible without any hazards. 2: all pages should have a valid
2714 * pc->mem_cgroup. If mm is NULL and the caller doesn't pass a valid memcg
2715 * pointer, that is treated as a charge to root_mem_cgroup.
2717 * So __mem_cgroup_try_charge() will return
2718 * 0 ... on success, filling *ptr with a valid memcg pointer.
2719 * -ENOMEM ... charge failure because of resource limits.
2720 * -EINTR ... if thread is fatal. *ptr is filled with root_mem_cgroup.
2722 * Unlike the exported interface, an "oom" parameter is added. if oom==true,
2723 * the oom-killer can be invoked.
2725 static int __mem_cgroup_try_charge(struct mm_struct *mm,
2727 unsigned int nr_pages,
2728 struct mem_cgroup **ptr,
2731 unsigned int batch = max(CHARGE_BATCH, nr_pages);
2732 int nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2733 struct mem_cgroup *memcg = NULL;
2737 * Unlike gloval-vm's OOM-kill, we're not in memory shortage
2738 * in system level. So, allow to go ahead dying process in addition to
2741 if (unlikely(test_thread_flag(TIF_MEMDIE)
2742 || fatal_signal_pending(current)))
2746 * We always charge the cgroup the mm_struct belongs to.
2747 * The mm_struct's mem_cgroup changes on task migration if the
2748 * thread group leader migrates. It's possible that mm is not
2749 * set, if so charge the root memcg (happens for pagecache usage).
2752 *ptr = root_mem_cgroup;
2754 if (*ptr) { /* css should be a valid one */
2756 if (mem_cgroup_is_root(memcg))
2758 if (consume_stock(memcg, nr_pages))
2760 css_get(&memcg->css);
2762 struct task_struct *p;
2765 p = rcu_dereference(mm->owner);
2767 * Because we don't have task_lock(), "p" can exit.
2768 * In that case, "memcg" can point to root or p can be NULL with
2769 * race with swapoff. Then, we have small risk of mis-accouning.
2770 * But such kind of mis-account by race always happens because
2771 * we don't have cgroup_mutex(). It's overkill and we allo that
2773 * (*) swapoff at el will charge against mm-struct not against
2774 * task-struct. So, mm->owner can be NULL.
2776 memcg = mem_cgroup_from_task(p);
2778 memcg = root_mem_cgroup;
2779 if (mem_cgroup_is_root(memcg)) {
2783 if (consume_stock(memcg, nr_pages)) {
2785 * It seems dagerous to access memcg without css_get().
2786 * But considering how consume_stok works, it's not
2787 * necessary. If consume_stock success, some charges
2788 * from this memcg are cached on this cpu. So, we
2789 * don't need to call css_get()/css_tryget() before
2790 * calling consume_stock().
2795 /* after here, we may be blocked. we need to get refcnt */
2796 if (!css_tryget(&memcg->css)) {
2804 bool invoke_oom = oom && !nr_oom_retries;
2806 /* If killed, bypass charge */
2807 if (fatal_signal_pending(current)) {
2808 css_put(&memcg->css);
2812 ret = mem_cgroup_do_charge(memcg, gfp_mask, batch,
2813 nr_pages, invoke_oom);
2817 case CHARGE_RETRY: /* not in OOM situation but retry */
2819 css_put(&memcg->css);
2822 case CHARGE_WOULDBLOCK: /* !__GFP_WAIT */
2823 css_put(&memcg->css);
2825 case CHARGE_NOMEM: /* OOM routine works */
2826 if (!oom || invoke_oom) {
2827 css_put(&memcg->css);
2833 } while (ret != CHARGE_OK);
2835 if (batch > nr_pages)
2836 refill_stock(memcg, batch - nr_pages);
2837 css_put(&memcg->css);
2845 *ptr = root_mem_cgroup;
2850 * Somemtimes we have to undo a charge we got by try_charge().
2851 * This function is for that and do uncharge, put css's refcnt.
2852 * gotten by try_charge().
2854 static void __mem_cgroup_cancel_charge(struct mem_cgroup *memcg,
2855 unsigned int nr_pages)
2857 if (!mem_cgroup_is_root(memcg)) {
2858 unsigned long bytes = nr_pages * PAGE_SIZE;
2860 res_counter_uncharge(&memcg->res, bytes);
2861 if (do_swap_account)
2862 res_counter_uncharge(&memcg->memsw, bytes);
2867 * Cancel chrages in this cgroup....doesn't propagate to parent cgroup.
2868 * This is useful when moving usage to parent cgroup.
2870 static void __mem_cgroup_cancel_local_charge(struct mem_cgroup *memcg,
2871 unsigned int nr_pages)
2873 unsigned long bytes = nr_pages * PAGE_SIZE;
2875 if (mem_cgroup_is_root(memcg))
2878 res_counter_uncharge_until(&memcg->res, memcg->res.parent, bytes);
2879 if (do_swap_account)
2880 res_counter_uncharge_until(&memcg->memsw,
2881 memcg->memsw.parent, bytes);
2885 * A helper function to get mem_cgroup from ID. must be called under
2886 * rcu_read_lock(). The caller is responsible for calling css_tryget if
2887 * the mem_cgroup is used for charging. (dropping refcnt from swap can be
2888 * called against removed memcg.)
2890 static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
2892 struct cgroup_subsys_state *css;
2894 /* ID 0 is unused ID */
2897 css = css_lookup(&mem_cgroup_subsys, id);
2900 return mem_cgroup_from_css(css);
2903 struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
2905 struct mem_cgroup *memcg = NULL;
2906 struct page_cgroup *pc;
2910 VM_BUG_ON(!PageLocked(page));
2912 pc = lookup_page_cgroup(page);
2913 lock_page_cgroup(pc);
2914 if (PageCgroupUsed(pc)) {
2915 memcg = pc->mem_cgroup;
2916 if (memcg && !css_tryget(&memcg->css))
2918 } else if (PageSwapCache(page)) {
2919 ent.val = page_private(page);
2920 id = lookup_swap_cgroup_id(ent);
2922 memcg = mem_cgroup_lookup(id);
2923 if (memcg && !css_tryget(&memcg->css))
2927 unlock_page_cgroup(pc);
2931 static void __mem_cgroup_commit_charge(struct mem_cgroup *memcg,
2933 unsigned int nr_pages,
2934 enum charge_type ctype,
2937 struct page_cgroup *pc = lookup_page_cgroup(page);
2938 struct zone *uninitialized_var(zone);
2939 struct lruvec *lruvec;
2940 bool was_on_lru = false;
2943 lock_page_cgroup(pc);
2944 VM_BUG_ON(PageCgroupUsed(pc));
2946 * we don't need page_cgroup_lock about tail pages, becase they are not
2947 * accessed by any other context at this point.
2951 * In some cases, SwapCache and FUSE(splice_buf->radixtree), the page
2952 * may already be on some other mem_cgroup's LRU. Take care of it.
2955 zone = page_zone(page);
2956 spin_lock_irq(&zone->lru_lock);
2957 if (PageLRU(page)) {
2958 lruvec = mem_cgroup_zone_lruvec(zone, pc->mem_cgroup);
2960 del_page_from_lru_list(page, lruvec, page_lru(page));
2965 pc->mem_cgroup = memcg;
2967 * We access a page_cgroup asynchronously without lock_page_cgroup().
2968 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
2969 * is accessed after testing USED bit. To make pc->mem_cgroup visible
2970 * before USED bit, we need memory barrier here.
2971 * See mem_cgroup_add_lru_list(), etc.
2974 SetPageCgroupUsed(pc);
2978 lruvec = mem_cgroup_zone_lruvec(zone, pc->mem_cgroup);
2979 VM_BUG_ON(PageLRU(page));
2981 add_page_to_lru_list(page, lruvec, page_lru(page));
2983 spin_unlock_irq(&zone->lru_lock);
2986 if (ctype == MEM_CGROUP_CHARGE_TYPE_ANON)
2991 mem_cgroup_charge_statistics(memcg, page, anon, nr_pages);
2992 unlock_page_cgroup(pc);
2995 * "charge_statistics" updated event counter. Then, check it.
2996 * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
2997 * if they exceeds softlimit.
2999 memcg_check_events(memcg, page);
3002 static DEFINE_MUTEX(set_limit_mutex);
3004 #ifdef CONFIG_MEMCG_KMEM
3005 static inline bool memcg_can_account_kmem(struct mem_cgroup *memcg)
3007 return !mem_cgroup_disabled() && !mem_cgroup_is_root(memcg) &&
3008 (memcg->kmem_account_flags & KMEM_ACCOUNTED_MASK);
3012 * This is a bit cumbersome, but it is rarely used and avoids a backpointer
3013 * in the memcg_cache_params struct.
3015 static struct kmem_cache *memcg_params_to_cache(struct memcg_cache_params *p)
3017 struct kmem_cache *cachep;
3019 VM_BUG_ON(p->is_root_cache);
3020 cachep = p->root_cache;
3021 return cachep->memcg_params->memcg_caches[memcg_cache_id(p->memcg)];
3024 #ifdef CONFIG_SLABINFO
3025 static int mem_cgroup_slabinfo_read(struct cgroup *cont, struct cftype *cft,
3028 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
3029 struct memcg_cache_params *params;
3031 if (!memcg_can_account_kmem(memcg))
3034 print_slabinfo_header(m);
3036 mutex_lock(&memcg->slab_caches_mutex);
3037 list_for_each_entry(params, &memcg->memcg_slab_caches, list)
3038 cache_show(memcg_params_to_cache(params), m);
3039 mutex_unlock(&memcg->slab_caches_mutex);
3045 static int memcg_charge_kmem(struct mem_cgroup *memcg, gfp_t gfp, u64 size)
3047 struct res_counter *fail_res;
3048 struct mem_cgroup *_memcg;
3052 ret = res_counter_charge(&memcg->kmem, size, &fail_res);
3057 * Conditions under which we can wait for the oom_killer. Those are
3058 * the same conditions tested by the core page allocator
3060 may_oom = (gfp & __GFP_FS) && !(gfp & __GFP_NORETRY);
3063 ret = __mem_cgroup_try_charge(NULL, gfp, size >> PAGE_SHIFT,
3066 if (ret == -EINTR) {
3068 * __mem_cgroup_try_charge() chosed to bypass to root due to
3069 * OOM kill or fatal signal. Since our only options are to
3070 * either fail the allocation or charge it to this cgroup, do
3071 * it as a temporary condition. But we can't fail. From a
3072 * kmem/slab perspective, the cache has already been selected,
3073 * by mem_cgroup_kmem_get_cache(), so it is too late to change
3076 * This condition will only trigger if the task entered
3077 * memcg_charge_kmem in a sane state, but was OOM-killed during
3078 * __mem_cgroup_try_charge() above. Tasks that were already
3079 * dying when the allocation triggers should have been already
3080 * directed to the root cgroup in memcontrol.h
3082 res_counter_charge_nofail(&memcg->res, size, &fail_res);
3083 if (do_swap_account)
3084 res_counter_charge_nofail(&memcg->memsw, size,
3088 res_counter_uncharge(&memcg->kmem, size);
3093 static void memcg_uncharge_kmem(struct mem_cgroup *memcg, u64 size)
3095 res_counter_uncharge(&memcg->res, size);
3096 if (do_swap_account)
3097 res_counter_uncharge(&memcg->memsw, size);
3100 if (res_counter_uncharge(&memcg->kmem, size))
3103 if (memcg_kmem_test_and_clear_dead(memcg))
3104 mem_cgroup_put(memcg);
3107 void memcg_cache_list_add(struct mem_cgroup *memcg, struct kmem_cache *cachep)
3112 mutex_lock(&memcg->slab_caches_mutex);
3113 list_add(&cachep->memcg_params->list, &memcg->memcg_slab_caches);
3114 mutex_unlock(&memcg->slab_caches_mutex);
3118 * helper for acessing a memcg's index. It will be used as an index in the
3119 * child cache array in kmem_cache, and also to derive its name. This function
3120 * will return -1 when this is not a kmem-limited memcg.
3122 int memcg_cache_id(struct mem_cgroup *memcg)
3124 return memcg ? memcg->kmemcg_id : -1;
3128 * This ends up being protected by the set_limit mutex, during normal
3129 * operation, because that is its main call site.
3131 * But when we create a new cache, we can call this as well if its parent
3132 * is kmem-limited. That will have to hold set_limit_mutex as well.
3134 int memcg_update_cache_sizes(struct mem_cgroup *memcg)
3138 num = ida_simple_get(&kmem_limited_groups,
3139 0, MEMCG_CACHES_MAX_SIZE, GFP_KERNEL);
3143 * After this point, kmem_accounted (that we test atomically in
3144 * the beginning of this conditional), is no longer 0. This
3145 * guarantees only one process will set the following boolean
3146 * to true. We don't need test_and_set because we're protected
3147 * by the set_limit_mutex anyway.
3149 memcg_kmem_set_activated(memcg);
3151 ret = memcg_update_all_caches(num+1);
3153 ida_simple_remove(&kmem_limited_groups, num);
3154 memcg_kmem_clear_activated(memcg);
3158 memcg->kmemcg_id = num;
3159 INIT_LIST_HEAD(&memcg->memcg_slab_caches);
3160 mutex_init(&memcg->slab_caches_mutex);
3164 static size_t memcg_caches_array_size(int num_groups)
3167 if (num_groups <= 0)
3170 size = 2 * num_groups;
3171 if (size < MEMCG_CACHES_MIN_SIZE)
3172 size = MEMCG_CACHES_MIN_SIZE;
3173 else if (size > MEMCG_CACHES_MAX_SIZE)
3174 size = MEMCG_CACHES_MAX_SIZE;
3180 * We should update the current array size iff all caches updates succeed. This
3181 * can only be done from the slab side. The slab mutex needs to be held when
3184 void memcg_update_array_size(int num)
3186 if (num > memcg_limited_groups_array_size)
3187 memcg_limited_groups_array_size = memcg_caches_array_size(num);
3190 static void kmem_cache_destroy_work_func(struct work_struct *w);
3192 int memcg_update_cache_size(struct kmem_cache *s, int num_groups)
3194 struct memcg_cache_params *cur_params = s->memcg_params;
3196 VM_BUG_ON(s->memcg_params && !s->memcg_params->is_root_cache);
3198 if (num_groups > memcg_limited_groups_array_size) {
3200 ssize_t size = memcg_caches_array_size(num_groups);
3202 size *= sizeof(void *);
3203 size += sizeof(struct memcg_cache_params);
3205 s->memcg_params = kzalloc(size, GFP_KERNEL);
3206 if (!s->memcg_params) {
3207 s->memcg_params = cur_params;
3211 s->memcg_params->is_root_cache = true;
3214 * There is the chance it will be bigger than
3215 * memcg_limited_groups_array_size, if we failed an allocation
3216 * in a cache, in which case all caches updated before it, will
3217 * have a bigger array.
3219 * But if that is the case, the data after
3220 * memcg_limited_groups_array_size is certainly unused
3222 for (i = 0; i < memcg_limited_groups_array_size; i++) {
3223 if (!cur_params->memcg_caches[i])
3225 s->memcg_params->memcg_caches[i] =
3226 cur_params->memcg_caches[i];
3230 * Ideally, we would wait until all caches succeed, and only
3231 * then free the old one. But this is not worth the extra
3232 * pointer per-cache we'd have to have for this.
3234 * It is not a big deal if some caches are left with a size
3235 * bigger than the others. And all updates will reset this
3243 int memcg_register_cache(struct mem_cgroup *memcg, struct kmem_cache *s,
3244 struct kmem_cache *root_cache)
3246 size_t size = sizeof(struct memcg_cache_params);
3248 if (!memcg_kmem_enabled())
3252 size += memcg_limited_groups_array_size * sizeof(void *);
3254 s->memcg_params = kzalloc(size, GFP_KERNEL);
3255 if (!s->memcg_params)
3259 s->memcg_params->memcg = memcg;
3260 s->memcg_params->root_cache = root_cache;
3261 INIT_WORK(&s->memcg_params->destroy,
3262 kmem_cache_destroy_work_func);
3264 s->memcg_params->is_root_cache = true;
3269 void memcg_release_cache(struct kmem_cache *s)
3271 struct kmem_cache *root;
3272 struct mem_cgroup *memcg;
3276 * This happens, for instance, when a root cache goes away before we
3279 if (!s->memcg_params)
3282 if (s->memcg_params->is_root_cache)
3285 memcg = s->memcg_params->memcg;
3286 id = memcg_cache_id(memcg);
3288 root = s->memcg_params->root_cache;
3289 root->memcg_params->memcg_caches[id] = NULL;
3291 mutex_lock(&memcg->slab_caches_mutex);
3292 list_del(&s->memcg_params->list);
3293 mutex_unlock(&memcg->slab_caches_mutex);
3295 mem_cgroup_put(memcg);
3297 kfree(s->memcg_params);
3301 * During the creation a new cache, we need to disable our accounting mechanism
3302 * altogether. This is true even if we are not creating, but rather just
3303 * enqueing new caches to be created.
3305 * This is because that process will trigger allocations; some visible, like
3306 * explicit kmallocs to auxiliary data structures, name strings and internal
3307 * cache structures; some well concealed, like INIT_WORK() that can allocate
3308 * objects during debug.
3310 * If any allocation happens during memcg_kmem_get_cache, we will recurse back
3311 * to it. This may not be a bounded recursion: since the first cache creation
3312 * failed to complete (waiting on the allocation), we'll just try to create the
3313 * cache again, failing at the same point.
3315 * memcg_kmem_get_cache is prepared to abort after seeing a positive count of
3316 * memcg_kmem_skip_account. So we enclose anything that might allocate memory
3317 * inside the following two functions.
3319 static inline void memcg_stop_kmem_account(void)
3321 VM_BUG_ON(!current->mm);
3322 current->memcg_kmem_skip_account++;
3325 static inline void memcg_resume_kmem_account(void)
3327 VM_BUG_ON(!current->mm);
3328 current->memcg_kmem_skip_account--;
3331 static void kmem_cache_destroy_work_func(struct work_struct *w)
3333 struct kmem_cache *cachep;
3334 struct memcg_cache_params *p;
3336 p = container_of(w, struct memcg_cache_params, destroy);
3338 cachep = memcg_params_to_cache(p);
3341 * If we get down to 0 after shrink, we could delete right away.
3342 * However, memcg_release_pages() already puts us back in the workqueue
3343 * in that case. If we proceed deleting, we'll get a dangling
3344 * reference, and removing the object from the workqueue in that case
3345 * is unnecessary complication. We are not a fast path.
3347 * Note that this case is fundamentally different from racing with
3348 * shrink_slab(): if memcg_cgroup_destroy_cache() is called in
3349 * kmem_cache_shrink, not only we would be reinserting a dead cache
3350 * into the queue, but doing so from inside the worker racing to
3353 * So if we aren't down to zero, we'll just schedule a worker and try
3356 if (atomic_read(&cachep->memcg_params->nr_pages) != 0) {
3357 kmem_cache_shrink(cachep);
3358 if (atomic_read(&cachep->memcg_params->nr_pages) == 0)
3361 kmem_cache_destroy(cachep);
3364 void mem_cgroup_destroy_cache(struct kmem_cache *cachep)
3366 if (!cachep->memcg_params->dead)
3370 * There are many ways in which we can get here.
3372 * We can get to a memory-pressure situation while the delayed work is
3373 * still pending to run. The vmscan shrinkers can then release all
3374 * cache memory and get us to destruction. If this is the case, we'll
3375 * be executed twice, which is a bug (the second time will execute over
3376 * bogus data). In this case, cancelling the work should be fine.
3378 * But we can also get here from the worker itself, if
3379 * kmem_cache_shrink is enough to shake all the remaining objects and
3380 * get the page count to 0. In this case, we'll deadlock if we try to
3381 * cancel the work (the worker runs with an internal lock held, which
3382 * is the same lock we would hold for cancel_work_sync().)
3384 * Since we can't possibly know who got us here, just refrain from
3385 * running if there is already work pending
3387 if (work_pending(&cachep->memcg_params->destroy))
3390 * We have to defer the actual destroying to a workqueue, because
3391 * we might currently be in a context that cannot sleep.
3393 schedule_work(&cachep->memcg_params->destroy);
3397 * This lock protects updaters, not readers. We want readers to be as fast as
3398 * they can, and they will either see NULL or a valid cache value. Our model
3399 * allow them to see NULL, in which case the root memcg will be selected.
3401 * We need this lock because multiple allocations to the same cache from a non
3402 * will span more than one worker. Only one of them can create the cache.
3404 static DEFINE_MUTEX(memcg_cache_mutex);
3407 * Called with memcg_cache_mutex held
3409 static struct kmem_cache *kmem_cache_dup(struct mem_cgroup *memcg,
3410 struct kmem_cache *s)
3412 struct kmem_cache *new;
3413 static char *tmp_name = NULL;
3415 lockdep_assert_held(&memcg_cache_mutex);
3418 * kmem_cache_create_memcg duplicates the given name and
3419 * cgroup_name for this name requires RCU context.
3420 * This static temporary buffer is used to prevent from
3421 * pointless shortliving allocation.
3424 tmp_name = kmalloc(PATH_MAX, GFP_KERNEL);
3430 snprintf(tmp_name, PATH_MAX, "%s(%d:%s)", s->name,
3431 memcg_cache_id(memcg), cgroup_name(memcg->css.cgroup));
3434 new = kmem_cache_create_memcg(memcg, tmp_name, s->object_size, s->align,
3435 (s->flags & ~SLAB_PANIC), s->ctor, s);
3438 new->allocflags |= __GFP_KMEMCG;
3443 static struct kmem_cache *memcg_create_kmem_cache(struct mem_cgroup *memcg,
3444 struct kmem_cache *cachep)
3446 struct kmem_cache *new_cachep;
3449 BUG_ON(!memcg_can_account_kmem(memcg));
3451 idx = memcg_cache_id(memcg);
3453 mutex_lock(&memcg_cache_mutex);
3454 new_cachep = cachep->memcg_params->memcg_caches[idx];
3458 new_cachep = kmem_cache_dup(memcg, cachep);
3459 if (new_cachep == NULL) {
3460 new_cachep = cachep;
3464 mem_cgroup_get(memcg);
3465 atomic_set(&new_cachep->memcg_params->nr_pages , 0);
3467 cachep->memcg_params->memcg_caches[idx] = new_cachep;
3469 * the readers won't lock, make sure everybody sees the updated value,
3470 * so they won't put stuff in the queue again for no reason
3474 mutex_unlock(&memcg_cache_mutex);
3478 void kmem_cache_destroy_memcg_children(struct kmem_cache *s)
3480 struct kmem_cache *c;
3483 if (!s->memcg_params)
3485 if (!s->memcg_params->is_root_cache)
3489 * If the cache is being destroyed, we trust that there is no one else
3490 * requesting objects from it. Even if there are, the sanity checks in
3491 * kmem_cache_destroy should caught this ill-case.
3493 * Still, we don't want anyone else freeing memcg_caches under our
3494 * noses, which can happen if a new memcg comes to life. As usual,
3495 * we'll take the set_limit_mutex to protect ourselves against this.
3497 mutex_lock(&set_limit_mutex);
3498 for (i = 0; i < memcg_limited_groups_array_size; i++) {
3499 c = s->memcg_params->memcg_caches[i];
3504 * We will now manually delete the caches, so to avoid races
3505 * we need to cancel all pending destruction workers and
3506 * proceed with destruction ourselves.
3508 * kmem_cache_destroy() will call kmem_cache_shrink internally,
3509 * and that could spawn the workers again: it is likely that
3510 * the cache still have active pages until this very moment.
3511 * This would lead us back to mem_cgroup_destroy_cache.
3513 * But that will not execute at all if the "dead" flag is not
3514 * set, so flip it down to guarantee we are in control.
3516 c->memcg_params->dead = false;
3517 cancel_work_sync(&c->memcg_params->destroy);
3518 kmem_cache_destroy(c);
3520 mutex_unlock(&set_limit_mutex);
3523 struct create_work {
3524 struct mem_cgroup *memcg;
3525 struct kmem_cache *cachep;
3526 struct work_struct work;
3529 static void mem_cgroup_destroy_all_caches(struct mem_cgroup *memcg)
3531 struct kmem_cache *cachep;
3532 struct memcg_cache_params *params;
3534 if (!memcg_kmem_is_active(memcg))
3537 mutex_lock(&memcg->slab_caches_mutex);
3538 list_for_each_entry(params, &memcg->memcg_slab_caches, list) {
3539 cachep = memcg_params_to_cache(params);
3540 cachep->memcg_params->dead = true;
3541 schedule_work(&cachep->memcg_params->destroy);
3543 mutex_unlock(&memcg->slab_caches_mutex);
3546 static void memcg_create_cache_work_func(struct work_struct *w)
3548 struct create_work *cw;
3550 cw = container_of(w, struct create_work, work);
3551 memcg_create_kmem_cache(cw->memcg, cw->cachep);
3552 /* Drop the reference gotten when we enqueued. */
3553 css_put(&cw->memcg->css);
3558 * Enqueue the creation of a per-memcg kmem_cache.
3560 static void __memcg_create_cache_enqueue(struct mem_cgroup *memcg,
3561 struct kmem_cache *cachep)
3563 struct create_work *cw;
3565 cw = kmalloc(sizeof(struct create_work), GFP_NOWAIT);
3567 css_put(&memcg->css);
3572 cw->cachep = cachep;
3574 INIT_WORK(&cw->work, memcg_create_cache_work_func);
3575 schedule_work(&cw->work);
3578 static void memcg_create_cache_enqueue(struct mem_cgroup *memcg,
3579 struct kmem_cache *cachep)
3582 * We need to stop accounting when we kmalloc, because if the
3583 * corresponding kmalloc cache is not yet created, the first allocation
3584 * in __memcg_create_cache_enqueue will recurse.
3586 * However, it is better to enclose the whole function. Depending on
3587 * the debugging options enabled, INIT_WORK(), for instance, can
3588 * trigger an allocation. This too, will make us recurse. Because at
3589 * this point we can't allow ourselves back into memcg_kmem_get_cache,
3590 * the safest choice is to do it like this, wrapping the whole function.
3592 memcg_stop_kmem_account();
3593 __memcg_create_cache_enqueue(memcg, cachep);
3594 memcg_resume_kmem_account();
3597 * Return the kmem_cache we're supposed to use for a slab allocation.
3598 * We try to use the current memcg's version of the cache.
3600 * If the cache does not exist yet, if we are the first user of it,
3601 * we either create it immediately, if possible, or create it asynchronously
3603 * In the latter case, we will let the current allocation go through with
3604 * the original cache.
3606 * Can't be called in interrupt context or from kernel threads.
3607 * This function needs to be called with rcu_read_lock() held.
3609 struct kmem_cache *__memcg_kmem_get_cache(struct kmem_cache *cachep,
3612 struct mem_cgroup *memcg;
3615 VM_BUG_ON(!cachep->memcg_params);
3616 VM_BUG_ON(!cachep->memcg_params->is_root_cache);
3618 if (!current->mm || current->memcg_kmem_skip_account)
3622 memcg = mem_cgroup_from_task(rcu_dereference(current->mm->owner));
3624 if (!memcg_can_account_kmem(memcg))
3627 idx = memcg_cache_id(memcg);
3630 * barrier to mare sure we're always seeing the up to date value. The
3631 * code updating memcg_caches will issue a write barrier to match this.
3633 read_barrier_depends();
3634 if (likely(cachep->memcg_params->memcg_caches[idx])) {
3635 cachep = cachep->memcg_params->memcg_caches[idx];
3639 /* The corresponding put will be done in the workqueue. */
3640 if (!css_tryget(&memcg->css))
3645 * If we are in a safe context (can wait, and not in interrupt
3646 * context), we could be be predictable and return right away.
3647 * This would guarantee that the allocation being performed
3648 * already belongs in the new cache.
3650 * However, there are some clashes that can arrive from locking.
3651 * For instance, because we acquire the slab_mutex while doing
3652 * kmem_cache_dup, this means no further allocation could happen
3653 * with the slab_mutex held.
3655 * Also, because cache creation issue get_online_cpus(), this
3656 * creates a lock chain: memcg_slab_mutex -> cpu_hotplug_mutex,
3657 * that ends up reversed during cpu hotplug. (cpuset allocates
3658 * a bunch of GFP_KERNEL memory during cpuup). Due to all that,
3659 * better to defer everything.
3661 memcg_create_cache_enqueue(memcg, cachep);
3667 EXPORT_SYMBOL(__memcg_kmem_get_cache);
3670 * We need to verify if the allocation against current->mm->owner's memcg is
3671 * possible for the given order. But the page is not allocated yet, so we'll
3672 * need a further commit step to do the final arrangements.
3674 * It is possible for the task to switch cgroups in this mean time, so at
3675 * commit time, we can't rely on task conversion any longer. We'll then use
3676 * the handle argument to return to the caller which cgroup we should commit
3677 * against. We could also return the memcg directly and avoid the pointer
3678 * passing, but a boolean return value gives better semantics considering
3679 * the compiled-out case as well.
3681 * Returning true means the allocation is possible.
3684 __memcg_kmem_newpage_charge(gfp_t gfp, struct mem_cgroup **_memcg, int order)
3686 struct mem_cgroup *memcg;
3690 memcg = try_get_mem_cgroup_from_mm(current->mm);
3693 * very rare case described in mem_cgroup_from_task. Unfortunately there
3694 * isn't much we can do without complicating this too much, and it would
3695 * be gfp-dependent anyway. Just let it go
3697 if (unlikely(!memcg))
3700 if (!memcg_can_account_kmem(memcg)) {
3701 css_put(&memcg->css);
3705 ret = memcg_charge_kmem(memcg, gfp, PAGE_SIZE << order);
3709 css_put(&memcg->css);
3713 void __memcg_kmem_commit_charge(struct page *page, struct mem_cgroup *memcg,
3716 struct page_cgroup *pc;
3718 VM_BUG_ON(mem_cgroup_is_root(memcg));
3720 /* The page allocation failed. Revert */
3722 memcg_uncharge_kmem(memcg, PAGE_SIZE << order);
3726 pc = lookup_page_cgroup(page);
3727 lock_page_cgroup(pc);
3728 pc->mem_cgroup = memcg;
3729 SetPageCgroupUsed(pc);
3730 unlock_page_cgroup(pc);
3733 void __memcg_kmem_uncharge_pages(struct page *page, int order)
3735 struct mem_cgroup *memcg = NULL;
3736 struct page_cgroup *pc;
3739 pc = lookup_page_cgroup(page);
3741 * Fast unlocked return. Theoretically might have changed, have to
3742 * check again after locking.
3744 if (!PageCgroupUsed(pc))
3747 lock_page_cgroup(pc);
3748 if (PageCgroupUsed(pc)) {
3749 memcg = pc->mem_cgroup;
3750 ClearPageCgroupUsed(pc);
3752 unlock_page_cgroup(pc);
3755 * We trust that only if there is a memcg associated with the page, it
3756 * is a valid allocation
3761 VM_BUG_ON(mem_cgroup_is_root(memcg));
3762 memcg_uncharge_kmem(memcg, PAGE_SIZE << order);
3765 static inline void mem_cgroup_destroy_all_caches(struct mem_cgroup *memcg)
3768 #endif /* CONFIG_MEMCG_KMEM */
3770 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3772 #define PCGF_NOCOPY_AT_SPLIT (1 << PCG_LOCK | 1 << PCG_MIGRATION)
3774 * Because tail pages are not marked as "used", set it. We're under
3775 * zone->lru_lock, 'splitting on pmd' and compound_lock.
3776 * charge/uncharge will be never happen and move_account() is done under
3777 * compound_lock(), so we don't have to take care of races.
3779 void mem_cgroup_split_huge_fixup(struct page *head)
3781 struct page_cgroup *head_pc = lookup_page_cgroup(head);
3782 struct page_cgroup *pc;
3783 struct mem_cgroup *memcg;
3786 if (mem_cgroup_disabled())
3789 memcg = head_pc->mem_cgroup;
3790 for (i = 1; i < HPAGE_PMD_NR; i++) {
3792 pc->mem_cgroup = memcg;
3793 smp_wmb();/* see __commit_charge() */
3794 pc->flags = head_pc->flags & ~PCGF_NOCOPY_AT_SPLIT;
3796 __this_cpu_sub(memcg->stat->count[MEM_CGROUP_STAT_RSS_HUGE],
3799 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
3802 * mem_cgroup_move_account - move account of the page
3804 * @nr_pages: number of regular pages (>1 for huge pages)
3805 * @pc: page_cgroup of the page.
3806 * @from: mem_cgroup which the page is moved from.
3807 * @to: mem_cgroup which the page is moved to. @from != @to.
3809 * The caller must confirm following.
3810 * - page is not on LRU (isolate_page() is useful.)
3811 * - compound_lock is held when nr_pages > 1
3813 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
3816 static int mem_cgroup_move_account(struct page *page,
3817 unsigned int nr_pages,
3818 struct page_cgroup *pc,
3819 struct mem_cgroup *from,
3820 struct mem_cgroup *to)
3822 unsigned long flags;
3824 bool anon = PageAnon(page);
3826 VM_BUG_ON(from == to);
3827 VM_BUG_ON(PageLRU(page));
3829 * The page is isolated from LRU. So, collapse function
3830 * will not handle this page. But page splitting can happen.
3831 * Do this check under compound_page_lock(). The caller should
3835 if (nr_pages > 1 && !PageTransHuge(page))
3838 lock_page_cgroup(pc);
3841 if (!PageCgroupUsed(pc) || pc->mem_cgroup != from)
3844 move_lock_mem_cgroup(from, &flags);
3846 if (!anon && page_mapped(page)) {
3847 /* Update mapped_file data for mem_cgroup */
3849 __this_cpu_dec(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
3850 __this_cpu_inc(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
3853 mem_cgroup_charge_statistics(from, page, anon, -nr_pages);
3855 /* caller should have done css_get */
3856 pc->mem_cgroup = to;
3857 mem_cgroup_charge_statistics(to, page, anon, nr_pages);
3858 move_unlock_mem_cgroup(from, &flags);
3861 unlock_page_cgroup(pc);
3865 memcg_check_events(to, page);
3866 memcg_check_events(from, page);
3872 * mem_cgroup_move_parent - moves page to the parent group
3873 * @page: the page to move
3874 * @pc: page_cgroup of the page
3875 * @child: page's cgroup
3877 * move charges to its parent or the root cgroup if the group has no
3878 * parent (aka use_hierarchy==0).
3879 * Although this might fail (get_page_unless_zero, isolate_lru_page or
3880 * mem_cgroup_move_account fails) the failure is always temporary and
3881 * it signals a race with a page removal/uncharge or migration. In the
3882 * first case the page is on the way out and it will vanish from the LRU
3883 * on the next attempt and the call should be retried later.
3884 * Isolation from the LRU fails only if page has been isolated from
3885 * the LRU since we looked at it and that usually means either global
3886 * reclaim or migration going on. The page will either get back to the
3888 * Finaly mem_cgroup_move_account fails only if the page got uncharged
3889 * (!PageCgroupUsed) or moved to a different group. The page will
3890 * disappear in the next attempt.
3892 static int mem_cgroup_move_parent(struct page *page,
3893 struct page_cgroup *pc,
3894 struct mem_cgroup *child)
3896 struct mem_cgroup *parent;
3897 unsigned int nr_pages;
3898 unsigned long uninitialized_var(flags);
3901 VM_BUG_ON(mem_cgroup_is_root(child));
3904 if (!get_page_unless_zero(page))
3906 if (isolate_lru_page(page))
3909 nr_pages = hpage_nr_pages(page);
3911 parent = parent_mem_cgroup(child);
3913 * If no parent, move charges to root cgroup.
3916 parent = root_mem_cgroup;
3919 VM_BUG_ON(!PageTransHuge(page));
3920 flags = compound_lock_irqsave(page);
3923 ret = mem_cgroup_move_account(page, nr_pages,
3926 __mem_cgroup_cancel_local_charge(child, nr_pages);
3929 compound_unlock_irqrestore(page, flags);
3930 putback_lru_page(page);
3938 * Charge the memory controller for page usage.
3940 * 0 if the charge was successful
3941 * < 0 if the cgroup is over its limit
3943 static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
3944 gfp_t gfp_mask, enum charge_type ctype)
3946 struct mem_cgroup *memcg = NULL;
3947 unsigned int nr_pages = 1;
3951 if (PageTransHuge(page)) {
3952 nr_pages <<= compound_order(page);
3953 VM_BUG_ON(!PageTransHuge(page));
3955 * Never OOM-kill a process for a huge page. The
3956 * fault handler will fall back to regular pages.
3961 ret = __mem_cgroup_try_charge(mm, gfp_mask, nr_pages, &memcg, oom);
3964 __mem_cgroup_commit_charge(memcg, page, nr_pages, ctype, false);
3968 int mem_cgroup_newpage_charge(struct page *page,
3969 struct mm_struct *mm, gfp_t gfp_mask)
3971 if (mem_cgroup_disabled())
3973 VM_BUG_ON(page_mapped(page));
3974 VM_BUG_ON(page->mapping && !PageAnon(page));
3976 return mem_cgroup_charge_common(page, mm, gfp_mask,
3977 MEM_CGROUP_CHARGE_TYPE_ANON);
3981 * While swap-in, try_charge -> commit or cancel, the page is locked.
3982 * And when try_charge() successfully returns, one refcnt to memcg without
3983 * struct page_cgroup is acquired. This refcnt will be consumed by
3984 * "commit()" or removed by "cancel()"
3986 static int __mem_cgroup_try_charge_swapin(struct mm_struct *mm,
3989 struct mem_cgroup **memcgp)
3991 struct mem_cgroup *memcg;
3992 struct page_cgroup *pc;
3995 pc = lookup_page_cgroup(page);
3997 * Every swap fault against a single page tries to charge the
3998 * page, bail as early as possible. shmem_unuse() encounters
3999 * already charged pages, too. The USED bit is protected by
4000 * the page lock, which serializes swap cache removal, which
4001 * in turn serializes uncharging.
4003 if (PageCgroupUsed(pc))
4005 if (!do_swap_account)
4007 memcg = try_get_mem_cgroup_from_page(page);
4011 ret = __mem_cgroup_try_charge(NULL, mask, 1, memcgp, true);
4012 css_put(&memcg->css);
4017 ret = __mem_cgroup_try_charge(mm, mask, 1, memcgp, true);
4023 int mem_cgroup_try_charge_swapin(struct mm_struct *mm, struct page *page,
4024 gfp_t gfp_mask, struct mem_cgroup **memcgp)
4027 if (mem_cgroup_disabled())
4030 * A racing thread's fault, or swapoff, may have already
4031 * updated the pte, and even removed page from swap cache: in
4032 * those cases unuse_pte()'s pte_same() test will fail; but
4033 * there's also a KSM case which does need to charge the page.
4035 if (!PageSwapCache(page)) {
4038 ret = __mem_cgroup_try_charge(mm, gfp_mask, 1, memcgp, true);
4043 return __mem_cgroup_try_charge_swapin(mm, page, gfp_mask, memcgp);
4046 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *memcg)
4048 if (mem_cgroup_disabled())
4052 __mem_cgroup_cancel_charge(memcg, 1);
4056 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *memcg,
4057 enum charge_type ctype)
4059 if (mem_cgroup_disabled())
4064 __mem_cgroup_commit_charge(memcg, page, 1, ctype, true);
4066 * Now swap is on-memory. This means this page may be
4067 * counted both as mem and swap....double count.
4068 * Fix it by uncharging from memsw. Basically, this SwapCache is stable
4069 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
4070 * may call delete_from_swap_cache() before reach here.
4072 if (do_swap_account && PageSwapCache(page)) {
4073 swp_entry_t ent = {.val = page_private(page)};
4074 mem_cgroup_uncharge_swap(ent);
4078 void mem_cgroup_commit_charge_swapin(struct page *page,
4079 struct mem_cgroup *memcg)
4081 __mem_cgroup_commit_charge_swapin(page, memcg,
4082 MEM_CGROUP_CHARGE_TYPE_ANON);
4085 int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
4088 struct mem_cgroup *memcg = NULL;
4089 enum charge_type type = MEM_CGROUP_CHARGE_TYPE_CACHE;
4092 if (mem_cgroup_disabled())
4094 if (PageCompound(page))
4097 if (!PageSwapCache(page))
4098 ret = mem_cgroup_charge_common(page, mm, gfp_mask, type);
4099 else { /* page is swapcache/shmem */
4100 ret = __mem_cgroup_try_charge_swapin(mm, page,
4103 __mem_cgroup_commit_charge_swapin(page, memcg, type);
4108 static void mem_cgroup_do_uncharge(struct mem_cgroup *memcg,
4109 unsigned int nr_pages,
4110 const enum charge_type ctype)
4112 struct memcg_batch_info *batch = NULL;
4113 bool uncharge_memsw = true;
4115 /* If swapout, usage of swap doesn't decrease */
4116 if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
4117 uncharge_memsw = false;
4119 batch = ¤t->memcg_batch;
4121 * In usual, we do css_get() when we remember memcg pointer.
4122 * But in this case, we keep res->usage until end of a series of
4123 * uncharges. Then, it's ok to ignore memcg's refcnt.
4126 batch->memcg = memcg;
4128 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
4129 * In those cases, all pages freed continuously can be expected to be in
4130 * the same cgroup and we have chance to coalesce uncharges.
4131 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
4132 * because we want to do uncharge as soon as possible.
4135 if (!batch->do_batch || test_thread_flag(TIF_MEMDIE))
4136 goto direct_uncharge;
4139 goto direct_uncharge;
4142 * In typical case, batch->memcg == mem. This means we can
4143 * merge a series of uncharges to an uncharge of res_counter.
4144 * If not, we uncharge res_counter ony by one.
4146 if (batch->memcg != memcg)
4147 goto direct_uncharge;
4148 /* remember freed charge and uncharge it later */
4151 batch->memsw_nr_pages++;
4154 res_counter_uncharge(&memcg->res, nr_pages * PAGE_SIZE);
4156 res_counter_uncharge(&memcg->memsw, nr_pages * PAGE_SIZE);
4157 if (unlikely(batch->memcg != memcg))
4158 memcg_oom_recover(memcg);
4162 * uncharge if !page_mapped(page)
4164 static struct mem_cgroup *
4165 __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype,
4168 struct mem_cgroup *memcg = NULL;
4169 unsigned int nr_pages = 1;
4170 struct page_cgroup *pc;
4173 if (mem_cgroup_disabled())
4176 if (PageTransHuge(page)) {
4177 nr_pages <<= compound_order(page);
4178 VM_BUG_ON(!PageTransHuge(page));
4181 * Check if our page_cgroup is valid
4183 pc = lookup_page_cgroup(page);
4184 if (unlikely(!PageCgroupUsed(pc)))
4187 lock_page_cgroup(pc);
4189 memcg = pc->mem_cgroup;
4191 if (!PageCgroupUsed(pc))
4194 anon = PageAnon(page);
4197 case MEM_CGROUP_CHARGE_TYPE_ANON:
4199 * Generally PageAnon tells if it's the anon statistics to be
4200 * updated; but sometimes e.g. mem_cgroup_uncharge_page() is
4201 * used before page reached the stage of being marked PageAnon.
4205 case MEM_CGROUP_CHARGE_TYPE_DROP:
4206 /* See mem_cgroup_prepare_migration() */
4207 if (page_mapped(page))
4210 * Pages under migration may not be uncharged. But
4211 * end_migration() /must/ be the one uncharging the
4212 * unused post-migration page and so it has to call
4213 * here with the migration bit still set. See the
4214 * res_counter handling below.
4216 if (!end_migration && PageCgroupMigration(pc))
4219 case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
4220 if (!PageAnon(page)) { /* Shared memory */
4221 if (page->mapping && !page_is_file_cache(page))
4223 } else if (page_mapped(page)) /* Anon */
4230 mem_cgroup_charge_statistics(memcg, page, anon, -nr_pages);
4232 ClearPageCgroupUsed(pc);
4234 * pc->mem_cgroup is not cleared here. It will be accessed when it's
4235 * freed from LRU. This is safe because uncharged page is expected not
4236 * to be reused (freed soon). Exception is SwapCache, it's handled by
4237 * special functions.
4240 unlock_page_cgroup(pc);
4242 * even after unlock, we have memcg->res.usage here and this memcg
4243 * will never be freed.
4245 memcg_check_events(memcg, page);
4246 if (do_swap_account && ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT) {
4247 mem_cgroup_swap_statistics(memcg, true);
4248 mem_cgroup_get(memcg);
4251 * Migration does not charge the res_counter for the
4252 * replacement page, so leave it alone when phasing out the
4253 * page that is unused after the migration.
4255 if (!end_migration && !mem_cgroup_is_root(memcg))
4256 mem_cgroup_do_uncharge(memcg, nr_pages, ctype);
4261 unlock_page_cgroup(pc);
4265 void mem_cgroup_uncharge_page(struct page *page)
4268 if (page_mapped(page))
4270 VM_BUG_ON(page->mapping && !PageAnon(page));
4272 * If the page is in swap cache, uncharge should be deferred
4273 * to the swap path, which also properly accounts swap usage
4274 * and handles memcg lifetime.
4276 * Note that this check is not stable and reclaim may add the
4277 * page to swap cache at any time after this. However, if the
4278 * page is not in swap cache by the time page->mapcount hits
4279 * 0, there won't be any page table references to the swap
4280 * slot, and reclaim will free it and not actually write the
4283 if (PageSwapCache(page))
4285 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_ANON, false);
4288 void mem_cgroup_uncharge_cache_page(struct page *page)
4290 VM_BUG_ON(page_mapped(page));
4291 VM_BUG_ON(page->mapping);
4292 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE, false);
4296 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
4297 * In that cases, pages are freed continuously and we can expect pages
4298 * are in the same memcg. All these calls itself limits the number of
4299 * pages freed at once, then uncharge_start/end() is called properly.
4300 * This may be called prural(2) times in a context,
4303 void mem_cgroup_uncharge_start(void)
4305 current->memcg_batch.do_batch++;
4306 /* We can do nest. */
4307 if (current->memcg_batch.do_batch == 1) {
4308 current->memcg_batch.memcg = NULL;
4309 current->memcg_batch.nr_pages = 0;
4310 current->memcg_batch.memsw_nr_pages = 0;
4314 void mem_cgroup_uncharge_end(void)
4316 struct memcg_batch_info *batch = ¤t->memcg_batch;
4318 if (!batch->do_batch)
4322 if (batch->do_batch) /* If stacked, do nothing. */
4328 * This "batch->memcg" is valid without any css_get/put etc...
4329 * bacause we hide charges behind us.
4331 if (batch->nr_pages)
4332 res_counter_uncharge(&batch->memcg->res,
4333 batch->nr_pages * PAGE_SIZE);
4334 if (batch->memsw_nr_pages)
4335 res_counter_uncharge(&batch->memcg->memsw,
4336 batch->memsw_nr_pages * PAGE_SIZE);
4337 memcg_oom_recover(batch->memcg);
4338 /* forget this pointer (for sanity check) */
4339 batch->memcg = NULL;
4344 * called after __delete_from_swap_cache() and drop "page" account.
4345 * memcg information is recorded to swap_cgroup of "ent"
4348 mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
4350 struct mem_cgroup *memcg;
4351 int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
4353 if (!swapout) /* this was a swap cache but the swap is unused ! */
4354 ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
4356 memcg = __mem_cgroup_uncharge_common(page, ctype, false);
4359 * record memcg information, if swapout && memcg != NULL,
4360 * mem_cgroup_get() was called in uncharge().
4362 if (do_swap_account && swapout && memcg)
4363 swap_cgroup_record(ent, css_id(&memcg->css));
4367 #ifdef CONFIG_MEMCG_SWAP
4369 * called from swap_entry_free(). remove record in swap_cgroup and
4370 * uncharge "memsw" account.
4372 void mem_cgroup_uncharge_swap(swp_entry_t ent)
4374 struct mem_cgroup *memcg;
4377 if (!do_swap_account)
4380 id = swap_cgroup_record(ent, 0);
4382 memcg = mem_cgroup_lookup(id);
4385 * We uncharge this because swap is freed.
4386 * This memcg can be obsolete one. We avoid calling css_tryget
4388 if (!mem_cgroup_is_root(memcg))
4389 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
4390 mem_cgroup_swap_statistics(memcg, false);
4391 mem_cgroup_put(memcg);
4397 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
4398 * @entry: swap entry to be moved
4399 * @from: mem_cgroup which the entry is moved from
4400 * @to: mem_cgroup which the entry is moved to
4402 * It succeeds only when the swap_cgroup's record for this entry is the same
4403 * as the mem_cgroup's id of @from.
4405 * Returns 0 on success, -EINVAL on failure.
4407 * The caller must have charged to @to, IOW, called res_counter_charge() about
4408 * both res and memsw, and called css_get().
4410 static int mem_cgroup_move_swap_account(swp_entry_t entry,
4411 struct mem_cgroup *from, struct mem_cgroup *to)
4413 unsigned short old_id, new_id;
4415 old_id = css_id(&from->css);
4416 new_id = css_id(&to->css);
4418 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
4419 mem_cgroup_swap_statistics(from, false);
4420 mem_cgroup_swap_statistics(to, true);
4422 * This function is only called from task migration context now.
4423 * It postpones res_counter and refcount handling till the end
4424 * of task migration(mem_cgroup_clear_mc()) for performance
4425 * improvement. But we cannot postpone mem_cgroup_get(to)
4426 * because if the process that has been moved to @to does
4427 * swap-in, the refcount of @to might be decreased to 0.
4435 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
4436 struct mem_cgroup *from, struct mem_cgroup *to)
4443 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
4446 void mem_cgroup_prepare_migration(struct page *page, struct page *newpage,
4447 struct mem_cgroup **memcgp)
4449 struct mem_cgroup *memcg = NULL;
4450 unsigned int nr_pages = 1;
4451 struct page_cgroup *pc;
4452 enum charge_type ctype;
4456 if (mem_cgroup_disabled())
4459 if (PageTransHuge(page))
4460 nr_pages <<= compound_order(page);
4462 pc = lookup_page_cgroup(page);
4463 lock_page_cgroup(pc);
4464 if (PageCgroupUsed(pc)) {
4465 memcg = pc->mem_cgroup;
4466 css_get(&memcg->css);
4468 * At migrating an anonymous page, its mapcount goes down
4469 * to 0 and uncharge() will be called. But, even if it's fully
4470 * unmapped, migration may fail and this page has to be
4471 * charged again. We set MIGRATION flag here and delay uncharge
4472 * until end_migration() is called
4474 * Corner Case Thinking
4476 * When the old page was mapped as Anon and it's unmap-and-freed
4477 * while migration was ongoing.
4478 * If unmap finds the old page, uncharge() of it will be delayed
4479 * until end_migration(). If unmap finds a new page, it's
4480 * uncharged when it make mapcount to be 1->0. If unmap code
4481 * finds swap_migration_entry, the new page will not be mapped
4482 * and end_migration() will find it(mapcount==0).
4485 * When the old page was mapped but migraion fails, the kernel
4486 * remaps it. A charge for it is kept by MIGRATION flag even
4487 * if mapcount goes down to 0. We can do remap successfully
4488 * without charging it again.
4491 * The "old" page is under lock_page() until the end of
4492 * migration, so, the old page itself will not be swapped-out.
4493 * If the new page is swapped out before end_migraton, our
4494 * hook to usual swap-out path will catch the event.
4497 SetPageCgroupMigration(pc);
4499 unlock_page_cgroup(pc);
4501 * If the page is not charged at this point,
4509 * We charge new page before it's used/mapped. So, even if unlock_page()
4510 * is called before end_migration, we can catch all events on this new
4511 * page. In the case new page is migrated but not remapped, new page's
4512 * mapcount will be finally 0 and we call uncharge in end_migration().
4515 ctype = MEM_CGROUP_CHARGE_TYPE_ANON;
4517 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
4519 * The page is committed to the memcg, but it's not actually
4520 * charged to the res_counter since we plan on replacing the
4521 * old one and only one page is going to be left afterwards.
4523 __mem_cgroup_commit_charge(memcg, newpage, nr_pages, ctype, false);
4526 /* remove redundant charge if migration failed*/
4527 void mem_cgroup_end_migration(struct mem_cgroup *memcg,
4528 struct page *oldpage, struct page *newpage, bool migration_ok)
4530 struct page *used, *unused;
4531 struct page_cgroup *pc;
4537 if (!migration_ok) {
4544 anon = PageAnon(used);
4545 __mem_cgroup_uncharge_common(unused,
4546 anon ? MEM_CGROUP_CHARGE_TYPE_ANON
4547 : MEM_CGROUP_CHARGE_TYPE_CACHE,
4549 css_put(&memcg->css);
4551 * We disallowed uncharge of pages under migration because mapcount
4552 * of the page goes down to zero, temporarly.
4553 * Clear the flag and check the page should be charged.
4555 pc = lookup_page_cgroup(oldpage);
4556 lock_page_cgroup(pc);
4557 ClearPageCgroupMigration(pc);
4558 unlock_page_cgroup(pc);
4561 * If a page is a file cache, radix-tree replacement is very atomic
4562 * and we can skip this check. When it was an Anon page, its mapcount
4563 * goes down to 0. But because we added MIGRATION flage, it's not
4564 * uncharged yet. There are several case but page->mapcount check
4565 * and USED bit check in mem_cgroup_uncharge_page() will do enough
4566 * check. (see prepare_charge() also)
4569 mem_cgroup_uncharge_page(used);
4573 * At replace page cache, newpage is not under any memcg but it's on
4574 * LRU. So, this function doesn't touch res_counter but handles LRU
4575 * in correct way. Both pages are locked so we cannot race with uncharge.
4577 void mem_cgroup_replace_page_cache(struct page *oldpage,
4578 struct page *newpage)
4580 struct mem_cgroup *memcg = NULL;
4581 struct page_cgroup *pc;
4582 enum charge_type type = MEM_CGROUP_CHARGE_TYPE_CACHE;
4584 if (mem_cgroup_disabled())
4587 pc = lookup_page_cgroup(oldpage);
4588 /* fix accounting on old pages */
4589 lock_page_cgroup(pc);
4590 if (PageCgroupUsed(pc)) {
4591 memcg = pc->mem_cgroup;
4592 mem_cgroup_charge_statistics(memcg, oldpage, false, -1);
4593 ClearPageCgroupUsed(pc);
4595 unlock_page_cgroup(pc);
4598 * When called from shmem_replace_page(), in some cases the
4599 * oldpage has already been charged, and in some cases not.
4604 * Even if newpage->mapping was NULL before starting replacement,
4605 * the newpage may be on LRU(or pagevec for LRU) already. We lock
4606 * LRU while we overwrite pc->mem_cgroup.
4608 __mem_cgroup_commit_charge(memcg, newpage, 1, type, true);
4611 #ifdef CONFIG_DEBUG_VM
4612 static struct page_cgroup *lookup_page_cgroup_used(struct page *page)
4614 struct page_cgroup *pc;
4616 pc = lookup_page_cgroup(page);
4618 * Can be NULL while feeding pages into the page allocator for
4619 * the first time, i.e. during boot or memory hotplug;
4620 * or when mem_cgroup_disabled().
4622 if (likely(pc) && PageCgroupUsed(pc))
4627 bool mem_cgroup_bad_page_check(struct page *page)
4629 if (mem_cgroup_disabled())
4632 return lookup_page_cgroup_used(page) != NULL;
4635 void mem_cgroup_print_bad_page(struct page *page)
4637 struct page_cgroup *pc;
4639 pc = lookup_page_cgroup_used(page);
4641 pr_alert("pc:%p pc->flags:%lx pc->mem_cgroup:%p\n",
4642 pc, pc->flags, pc->mem_cgroup);
4647 static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
4648 unsigned long long val)
4651 u64 memswlimit, memlimit;
4653 int children = mem_cgroup_count_children(memcg);
4654 u64 curusage, oldusage;
4658 * For keeping hierarchical_reclaim simple, how long we should retry
4659 * is depends on callers. We set our retry-count to be function
4660 * of # of children which we should visit in this loop.
4662 retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
4664 oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
4667 while (retry_count) {
4668 if (signal_pending(current)) {
4673 * Rather than hide all in some function, I do this in
4674 * open coded manner. You see what this really does.
4675 * We have to guarantee memcg->res.limit <= memcg->memsw.limit.
4677 mutex_lock(&set_limit_mutex);
4678 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
4679 if (memswlimit < val) {
4681 mutex_unlock(&set_limit_mutex);
4685 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
4689 ret = res_counter_set_limit(&memcg->res, val);
4691 if (memswlimit == val)
4692 memcg->memsw_is_minimum = true;
4694 memcg->memsw_is_minimum = false;
4696 mutex_unlock(&set_limit_mutex);
4701 mem_cgroup_reclaim(memcg, GFP_KERNEL,
4702 MEM_CGROUP_RECLAIM_SHRINK);
4703 curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
4704 /* Usage is reduced ? */
4705 if (curusage >= oldusage)
4708 oldusage = curusage;
4710 if (!ret && enlarge)
4711 memcg_oom_recover(memcg);
4716 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
4717 unsigned long long val)
4720 u64 memlimit, memswlimit, oldusage, curusage;
4721 int children = mem_cgroup_count_children(memcg);
4725 /* see mem_cgroup_resize_res_limit */
4726 retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
4727 oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
4728 while (retry_count) {
4729 if (signal_pending(current)) {
4734 * Rather than hide all in some function, I do this in
4735 * open coded manner. You see what this really does.
4736 * We have to guarantee memcg->res.limit <= memcg->memsw.limit.
4738 mutex_lock(&set_limit_mutex);
4739 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
4740 if (memlimit > val) {
4742 mutex_unlock(&set_limit_mutex);
4745 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
4746 if (memswlimit < val)
4748 ret = res_counter_set_limit(&memcg->memsw, val);
4750 if (memlimit == val)
4751 memcg->memsw_is_minimum = true;
4753 memcg->memsw_is_minimum = false;
4755 mutex_unlock(&set_limit_mutex);
4760 mem_cgroup_reclaim(memcg, GFP_KERNEL,
4761 MEM_CGROUP_RECLAIM_NOSWAP |
4762 MEM_CGROUP_RECLAIM_SHRINK);
4763 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
4764 /* Usage is reduced ? */
4765 if (curusage >= oldusage)
4768 oldusage = curusage;
4770 if (!ret && enlarge)
4771 memcg_oom_recover(memcg);
4775 unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
4777 unsigned long *total_scanned)
4779 unsigned long nr_reclaimed = 0;
4780 struct mem_cgroup_per_zone *mz, *next_mz = NULL;
4781 unsigned long reclaimed;
4783 struct mem_cgroup_tree_per_zone *mctz;
4784 unsigned long long excess;
4785 unsigned long nr_scanned;
4790 mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone));
4792 * This loop can run a while, specially if mem_cgroup's continuously
4793 * keep exceeding their soft limit and putting the system under
4800 mz = mem_cgroup_largest_soft_limit_node(mctz);
4805 reclaimed = mem_cgroup_soft_reclaim(mz->memcg, zone,
4806 gfp_mask, &nr_scanned);
4807 nr_reclaimed += reclaimed;
4808 *total_scanned += nr_scanned;
4809 spin_lock(&mctz->lock);
4812 * If we failed to reclaim anything from this memory cgroup
4813 * it is time to move on to the next cgroup
4819 * Loop until we find yet another one.
4821 * By the time we get the soft_limit lock
4822 * again, someone might have aded the
4823 * group back on the RB tree. Iterate to
4824 * make sure we get a different mem.
4825 * mem_cgroup_largest_soft_limit_node returns
4826 * NULL if no other cgroup is present on
4830 __mem_cgroup_largest_soft_limit_node(mctz);
4832 css_put(&next_mz->memcg->css);
4833 else /* next_mz == NULL or other memcg */
4837 __mem_cgroup_remove_exceeded(mz->memcg, mz, mctz);
4838 excess = res_counter_soft_limit_excess(&mz->memcg->res);
4840 * One school of thought says that we should not add
4841 * back the node to the tree if reclaim returns 0.
4842 * But our reclaim could return 0, simply because due
4843 * to priority we are exposing a smaller subset of
4844 * memory to reclaim from. Consider this as a longer
4847 /* If excess == 0, no tree ops */
4848 __mem_cgroup_insert_exceeded(mz->memcg, mz, mctz, excess);
4849 spin_unlock(&mctz->lock);
4850 css_put(&mz->memcg->css);
4853 * Could not reclaim anything and there are no more
4854 * mem cgroups to try or we seem to be looping without
4855 * reclaiming anything.
4857 if (!nr_reclaimed &&
4859 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
4861 } while (!nr_reclaimed);
4863 css_put(&next_mz->memcg->css);
4864 return nr_reclaimed;
4868 * mem_cgroup_force_empty_list - clears LRU of a group
4869 * @memcg: group to clear
4872 * @lru: lru to to clear
4874 * Traverse a specified page_cgroup list and try to drop them all. This doesn't
4875 * reclaim the pages page themselves - pages are moved to the parent (or root)
4878 static void mem_cgroup_force_empty_list(struct mem_cgroup *memcg,
4879 int node, int zid, enum lru_list lru)
4881 struct lruvec *lruvec;
4882 unsigned long flags;
4883 struct list_head *list;
4887 zone = &NODE_DATA(node)->node_zones[zid];
4888 lruvec = mem_cgroup_zone_lruvec(zone, memcg);
4889 list = &lruvec->lists[lru];
4893 struct page_cgroup *pc;
4896 spin_lock_irqsave(&zone->lru_lock, flags);
4897 if (list_empty(list)) {
4898 spin_unlock_irqrestore(&zone->lru_lock, flags);
4901 page = list_entry(list->prev, struct page, lru);
4903 list_move(&page->lru, list);
4905 spin_unlock_irqrestore(&zone->lru_lock, flags);
4908 spin_unlock_irqrestore(&zone->lru_lock, flags);
4910 pc = lookup_page_cgroup(page);
4912 if (mem_cgroup_move_parent(page, pc, memcg)) {
4913 /* found lock contention or "pc" is obsolete. */
4918 } while (!list_empty(list));
4922 * make mem_cgroup's charge to be 0 if there is no task by moving
4923 * all the charges and pages to the parent.
4924 * This enables deleting this mem_cgroup.
4926 * Caller is responsible for holding css reference on the memcg.
4928 static void mem_cgroup_reparent_charges(struct mem_cgroup *memcg)
4934 /* This is for making all *used* pages to be on LRU. */
4935 lru_add_drain_all();
4936 drain_all_stock_sync(memcg);
4937 mem_cgroup_start_move(memcg);
4938 for_each_node_state(node, N_MEMORY) {
4939 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
4942 mem_cgroup_force_empty_list(memcg,
4947 mem_cgroup_end_move(memcg);
4948 memcg_oom_recover(memcg);
4952 * Kernel memory may not necessarily be trackable to a specific
4953 * process. So they are not migrated, and therefore we can't
4954 * expect their value to drop to 0 here.
4955 * Having res filled up with kmem only is enough.
4957 * This is a safety check because mem_cgroup_force_empty_list
4958 * could have raced with mem_cgroup_replace_page_cache callers
4959 * so the lru seemed empty but the page could have been added
4960 * right after the check. RES_USAGE should be safe as we always
4961 * charge before adding to the LRU.
4963 usage = res_counter_read_u64(&memcg->res, RES_USAGE) -
4964 res_counter_read_u64(&memcg->kmem, RES_USAGE);
4965 } while (usage > 0);
4969 * This mainly exists for tests during the setting of set of use_hierarchy.
4970 * Since this is the very setting we are changing, the current hierarchy value
4973 static inline bool __memcg_has_children(struct mem_cgroup *memcg)
4977 /* bounce at first found */
4978 cgroup_for_each_child(pos, memcg->css.cgroup)
4984 * Must be called with memcg_create_mutex held, unless the cgroup is guaranteed
4985 * to be already dead (as in mem_cgroup_force_empty, for instance). This is
4986 * from mem_cgroup_count_children(), in the sense that we don't really care how
4987 * many children we have; we only need to know if we have any. It also counts
4988 * any memcg without hierarchy as infertile.
4990 static inline bool memcg_has_children(struct mem_cgroup *memcg)
4992 return memcg->use_hierarchy && __memcg_has_children(memcg);
4996 * Reclaims as many pages from the given memcg as possible and moves
4997 * the rest to the parent.
4999 * Caller is responsible for holding css reference for memcg.
5001 static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
5003 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
5004 struct cgroup *cgrp = memcg->css.cgroup;
5006 /* returns EBUSY if there is a task or if we come here twice. */
5007 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
5010 /* we call try-to-free pages for make this cgroup empty */
5011 lru_add_drain_all();
5012 /* try to free all pages in this cgroup */
5013 while (nr_retries && res_counter_read_u64(&memcg->res, RES_USAGE) > 0) {
5016 if (signal_pending(current))
5019 progress = try_to_free_mem_cgroup_pages(memcg, GFP_KERNEL,
5023 /* maybe some writeback is necessary */
5024 congestion_wait(BLK_RW_ASYNC, HZ/10);
5029 mem_cgroup_reparent_charges(memcg);
5034 static int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
5036 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5039 if (mem_cgroup_is_root(memcg))
5041 css_get(&memcg->css);
5042 ret = mem_cgroup_force_empty(memcg);
5043 css_put(&memcg->css);
5049 static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
5051 return mem_cgroup_from_cont(cont)->use_hierarchy;
5054 static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
5058 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5059 struct cgroup *parent = cont->parent;
5060 struct mem_cgroup *parent_memcg = NULL;
5063 parent_memcg = mem_cgroup_from_cont(parent);
5065 mutex_lock(&memcg_create_mutex);
5067 if (memcg->use_hierarchy == val)
5071 * If parent's use_hierarchy is set, we can't make any modifications
5072 * in the child subtrees. If it is unset, then the change can
5073 * occur, provided the current cgroup has no children.
5075 * For the root cgroup, parent_mem is NULL, we allow value to be
5076 * set if there are no children.
5078 if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
5079 (val == 1 || val == 0)) {
5080 if (!__memcg_has_children(memcg))
5081 memcg->use_hierarchy = val;
5088 mutex_unlock(&memcg_create_mutex);
5094 static unsigned long mem_cgroup_recursive_stat(struct mem_cgroup *memcg,
5095 enum mem_cgroup_stat_index idx)
5097 struct mem_cgroup *iter;
5100 /* Per-cpu values can be negative, use a signed accumulator */
5101 for_each_mem_cgroup_tree(iter, memcg)
5102 val += mem_cgroup_read_stat(iter, idx);
5104 if (val < 0) /* race ? */
5109 static inline u64 mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
5113 if (!mem_cgroup_is_root(memcg)) {
5115 return res_counter_read_u64(&memcg->res, RES_USAGE);
5117 return res_counter_read_u64(&memcg->memsw, RES_USAGE);
5121 * Transparent hugepages are still accounted for in MEM_CGROUP_STAT_RSS
5122 * as well as in MEM_CGROUP_STAT_RSS_HUGE.
5124 val = mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_CACHE);
5125 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_RSS);
5128 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_SWAP);
5130 return val << PAGE_SHIFT;
5133 static ssize_t mem_cgroup_read(struct cgroup *cont, struct cftype *cft,
5134 struct file *file, char __user *buf,
5135 size_t nbytes, loff_t *ppos)
5137 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5143 type = MEMFILE_TYPE(cft->private);
5144 name = MEMFILE_ATTR(cft->private);
5148 if (name == RES_USAGE)
5149 val = mem_cgroup_usage(memcg, false);
5151 val = res_counter_read_u64(&memcg->res, name);
5154 if (name == RES_USAGE)
5155 val = mem_cgroup_usage(memcg, true);
5157 val = res_counter_read_u64(&memcg->memsw, name);
5160 val = res_counter_read_u64(&memcg->kmem, name);
5166 len = scnprintf(str, sizeof(str), "%llu\n", (unsigned long long)val);
5167 return simple_read_from_buffer(buf, nbytes, ppos, str, len);
5170 static int memcg_update_kmem_limit(struct cgroup *cont, u64 val)
5173 #ifdef CONFIG_MEMCG_KMEM
5174 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5176 * For simplicity, we won't allow this to be disabled. It also can't
5177 * be changed if the cgroup has children already, or if tasks had
5180 * If tasks join before we set the limit, a person looking at
5181 * kmem.usage_in_bytes will have no way to determine when it took
5182 * place, which makes the value quite meaningless.
5184 * After it first became limited, changes in the value of the limit are
5185 * of course permitted.
5187 mutex_lock(&memcg_create_mutex);
5188 mutex_lock(&set_limit_mutex);
5189 if (!memcg->kmem_account_flags && val != RESOURCE_MAX) {
5190 if (cgroup_task_count(cont) || memcg_has_children(memcg)) {
5194 ret = res_counter_set_limit(&memcg->kmem, val);
5197 ret = memcg_update_cache_sizes(memcg);
5199 res_counter_set_limit(&memcg->kmem, RESOURCE_MAX);
5202 static_key_slow_inc(&memcg_kmem_enabled_key);
5204 * setting the active bit after the inc will guarantee no one
5205 * starts accounting before all call sites are patched
5207 memcg_kmem_set_active(memcg);
5210 * kmem charges can outlive the cgroup. In the case of slab
5211 * pages, for instance, a page contain objects from various
5212 * processes, so it is unfeasible to migrate them away. We
5213 * need to reference count the memcg because of that.
5215 mem_cgroup_get(memcg);
5217 ret = res_counter_set_limit(&memcg->kmem, val);
5219 mutex_unlock(&set_limit_mutex);
5220 mutex_unlock(&memcg_create_mutex);
5225 #ifdef CONFIG_MEMCG_KMEM
5226 static int memcg_propagate_kmem(struct mem_cgroup *memcg)
5229 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
5233 memcg->kmem_account_flags = parent->kmem_account_flags;
5235 * When that happen, we need to disable the static branch only on those
5236 * memcgs that enabled it. To achieve this, we would be forced to
5237 * complicate the code by keeping track of which memcgs were the ones
5238 * that actually enabled limits, and which ones got it from its
5241 * It is a lot simpler just to do static_key_slow_inc() on every child
5242 * that is accounted.
5244 if (!memcg_kmem_is_active(memcg))
5248 * destroy(), called if we fail, will issue static_key_slow_inc() and
5249 * mem_cgroup_put() if kmem is enabled. We have to either call them
5250 * unconditionally, or clear the KMEM_ACTIVE flag. I personally find
5251 * this more consistent, since it always leads to the same destroy path
5253 mem_cgroup_get(memcg);
5254 static_key_slow_inc(&memcg_kmem_enabled_key);
5256 mutex_lock(&set_limit_mutex);
5257 ret = memcg_update_cache_sizes(memcg);
5258 mutex_unlock(&set_limit_mutex);
5262 #endif /* CONFIG_MEMCG_KMEM */
5265 * The user of this function is...
5268 static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
5271 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5274 unsigned long long val;
5277 type = MEMFILE_TYPE(cft->private);
5278 name = MEMFILE_ATTR(cft->private);
5282 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
5286 /* This function does all necessary parse...reuse it */
5287 ret = res_counter_memparse_write_strategy(buffer, &val);
5291 ret = mem_cgroup_resize_limit(memcg, val);
5292 else if (type == _MEMSWAP)
5293 ret = mem_cgroup_resize_memsw_limit(memcg, val);
5294 else if (type == _KMEM)
5295 ret = memcg_update_kmem_limit(cont, val);
5299 case RES_SOFT_LIMIT:
5300 ret = res_counter_memparse_write_strategy(buffer, &val);
5304 * For memsw, soft limits are hard to implement in terms
5305 * of semantics, for now, we support soft limits for
5306 * control without swap
5309 ret = res_counter_set_soft_limit(&memcg->res, val);
5314 ret = -EINVAL; /* should be BUG() ? */
5320 static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
5321 unsigned long long *mem_limit, unsigned long long *memsw_limit)
5323 struct cgroup *cgroup;
5324 unsigned long long min_limit, min_memsw_limit, tmp;
5326 min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
5327 min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
5328 cgroup = memcg->css.cgroup;
5329 if (!memcg->use_hierarchy)
5332 while (cgroup->parent) {
5333 cgroup = cgroup->parent;
5334 memcg = mem_cgroup_from_cont(cgroup);
5335 if (!memcg->use_hierarchy)
5337 tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
5338 min_limit = min(min_limit, tmp);
5339 tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
5340 min_memsw_limit = min(min_memsw_limit, tmp);
5343 *mem_limit = min_limit;
5344 *memsw_limit = min_memsw_limit;
5347 static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
5349 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5353 type = MEMFILE_TYPE(event);
5354 name = MEMFILE_ATTR(event);
5359 res_counter_reset_max(&memcg->res);
5360 else if (type == _MEMSWAP)
5361 res_counter_reset_max(&memcg->memsw);
5362 else if (type == _KMEM)
5363 res_counter_reset_max(&memcg->kmem);
5369 res_counter_reset_failcnt(&memcg->res);
5370 else if (type == _MEMSWAP)
5371 res_counter_reset_failcnt(&memcg->memsw);
5372 else if (type == _KMEM)
5373 res_counter_reset_failcnt(&memcg->kmem);
5382 static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp,
5385 return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate;
5389 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
5390 struct cftype *cft, u64 val)
5392 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5394 if (val >= (1 << NR_MOVE_TYPE))
5398 * No kind of locking is needed in here, because ->can_attach() will
5399 * check this value once in the beginning of the process, and then carry
5400 * on with stale data. This means that changes to this value will only
5401 * affect task migrations starting after the change.
5403 memcg->move_charge_at_immigrate = val;
5407 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
5408 struct cftype *cft, u64 val)
5415 static int memcg_numa_stat_show(struct cgroup *cont, struct cftype *cft,
5419 unsigned long total_nr, file_nr, anon_nr, unevictable_nr;
5420 unsigned long node_nr;
5421 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5423 total_nr = mem_cgroup_nr_lru_pages(memcg, LRU_ALL);
5424 seq_printf(m, "total=%lu", total_nr);
5425 for_each_node_state(nid, N_MEMORY) {
5426 node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL);
5427 seq_printf(m, " N%d=%lu", nid, node_nr);
5431 file_nr = mem_cgroup_nr_lru_pages(memcg, LRU_ALL_FILE);
5432 seq_printf(m, "file=%lu", file_nr);
5433 for_each_node_state(nid, N_MEMORY) {
5434 node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
5436 seq_printf(m, " N%d=%lu", nid, node_nr);
5440 anon_nr = mem_cgroup_nr_lru_pages(memcg, LRU_ALL_ANON);
5441 seq_printf(m, "anon=%lu", anon_nr);
5442 for_each_node_state(nid, N_MEMORY) {
5443 node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
5445 seq_printf(m, " N%d=%lu", nid, node_nr);
5449 unevictable_nr = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_UNEVICTABLE));
5450 seq_printf(m, "unevictable=%lu", unevictable_nr);
5451 for_each_node_state(nid, N_MEMORY) {
5452 node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
5453 BIT(LRU_UNEVICTABLE));
5454 seq_printf(m, " N%d=%lu", nid, node_nr);
5459 #endif /* CONFIG_NUMA */
5461 static inline void mem_cgroup_lru_names_not_uptodate(void)
5463 BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_lru_names) != NR_LRU_LISTS);
5466 static int memcg_stat_show(struct cgroup *cont, struct cftype *cft,
5469 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5470 struct mem_cgroup *mi;
5473 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
5474 if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
5476 seq_printf(m, "%s %ld\n", mem_cgroup_stat_names[i],
5477 mem_cgroup_read_stat(memcg, i) * PAGE_SIZE);
5480 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++)
5481 seq_printf(m, "%s %lu\n", mem_cgroup_events_names[i],
5482 mem_cgroup_read_events(memcg, i));
5484 for (i = 0; i < NR_LRU_LISTS; i++)
5485 seq_printf(m, "%s %lu\n", mem_cgroup_lru_names[i],
5486 mem_cgroup_nr_lru_pages(memcg, BIT(i)) * PAGE_SIZE);
5488 /* Hierarchical information */
5490 unsigned long long limit, memsw_limit;
5491 memcg_get_hierarchical_limit(memcg, &limit, &memsw_limit);
5492 seq_printf(m, "hierarchical_memory_limit %llu\n", limit);
5493 if (do_swap_account)
5494 seq_printf(m, "hierarchical_memsw_limit %llu\n",
5498 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
5501 if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
5503 for_each_mem_cgroup_tree(mi, memcg)
5504 val += mem_cgroup_read_stat(mi, i) * PAGE_SIZE;
5505 seq_printf(m, "total_%s %lld\n", mem_cgroup_stat_names[i], val);
5508 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
5509 unsigned long long val = 0;
5511 for_each_mem_cgroup_tree(mi, memcg)
5512 val += mem_cgroup_read_events(mi, i);
5513 seq_printf(m, "total_%s %llu\n",
5514 mem_cgroup_events_names[i], val);
5517 for (i = 0; i < NR_LRU_LISTS; i++) {
5518 unsigned long long val = 0;
5520 for_each_mem_cgroup_tree(mi, memcg)
5521 val += mem_cgroup_nr_lru_pages(mi, BIT(i)) * PAGE_SIZE;
5522 seq_printf(m, "total_%s %llu\n", mem_cgroup_lru_names[i], val);
5525 #ifdef CONFIG_DEBUG_VM
5528 struct mem_cgroup_per_zone *mz;
5529 struct zone_reclaim_stat *rstat;
5530 unsigned long recent_rotated[2] = {0, 0};
5531 unsigned long recent_scanned[2] = {0, 0};
5533 for_each_online_node(nid)
5534 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
5535 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
5536 rstat = &mz->lruvec.reclaim_stat;
5538 recent_rotated[0] += rstat->recent_rotated[0];
5539 recent_rotated[1] += rstat->recent_rotated[1];
5540 recent_scanned[0] += rstat->recent_scanned[0];
5541 recent_scanned[1] += rstat->recent_scanned[1];
5543 seq_printf(m, "recent_rotated_anon %lu\n", recent_rotated[0]);
5544 seq_printf(m, "recent_rotated_file %lu\n", recent_rotated[1]);
5545 seq_printf(m, "recent_scanned_anon %lu\n", recent_scanned[0]);
5546 seq_printf(m, "recent_scanned_file %lu\n", recent_scanned[1]);
5553 static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
5555 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5557 return mem_cgroup_swappiness(memcg);
5560 static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
5563 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5564 struct mem_cgroup *parent;
5569 if (cgrp->parent == NULL)
5572 parent = mem_cgroup_from_cont(cgrp->parent);
5574 mutex_lock(&memcg_create_mutex);
5576 /* If under hierarchy, only empty-root can set this value */
5577 if ((parent->use_hierarchy) || memcg_has_children(memcg)) {
5578 mutex_unlock(&memcg_create_mutex);
5582 memcg->swappiness = val;
5584 mutex_unlock(&memcg_create_mutex);
5589 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
5591 struct mem_cgroup_threshold_ary *t;
5597 t = rcu_dereference(memcg->thresholds.primary);
5599 t = rcu_dereference(memcg->memsw_thresholds.primary);
5604 usage = mem_cgroup_usage(memcg, swap);
5607 * current_threshold points to threshold just below or equal to usage.
5608 * If it's not true, a threshold was crossed after last
5609 * call of __mem_cgroup_threshold().
5611 i = t->current_threshold;
5614 * Iterate backward over array of thresholds starting from
5615 * current_threshold and check if a threshold is crossed.
5616 * If none of thresholds below usage is crossed, we read
5617 * only one element of the array here.
5619 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
5620 eventfd_signal(t->entries[i].eventfd, 1);
5622 /* i = current_threshold + 1 */
5626 * Iterate forward over array of thresholds starting from
5627 * current_threshold+1 and check if a threshold is crossed.
5628 * If none of thresholds above usage is crossed, we read
5629 * only one element of the array here.
5631 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
5632 eventfd_signal(t->entries[i].eventfd, 1);
5634 /* Update current_threshold */
5635 t->current_threshold = i - 1;
5640 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
5643 __mem_cgroup_threshold(memcg, false);
5644 if (do_swap_account)
5645 __mem_cgroup_threshold(memcg, true);
5647 memcg = parent_mem_cgroup(memcg);
5651 static int compare_thresholds(const void *a, const void *b)
5653 const struct mem_cgroup_threshold *_a = a;
5654 const struct mem_cgroup_threshold *_b = b;
5656 if (_a->threshold > _b->threshold)
5659 if (_a->threshold < _b->threshold)
5665 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
5667 struct mem_cgroup_eventfd_list *ev;
5669 list_for_each_entry(ev, &memcg->oom_notify, list)
5670 eventfd_signal(ev->eventfd, 1);
5674 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
5676 struct mem_cgroup *iter;
5678 for_each_mem_cgroup_tree(iter, memcg)
5679 mem_cgroup_oom_notify_cb(iter);
5682 static int mem_cgroup_usage_register_event(struct cgroup *cgrp,
5683 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
5685 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5686 struct mem_cgroup_thresholds *thresholds;
5687 struct mem_cgroup_threshold_ary *new;
5688 enum res_type type = MEMFILE_TYPE(cft->private);
5689 u64 threshold, usage;
5692 ret = res_counter_memparse_write_strategy(args, &threshold);
5696 mutex_lock(&memcg->thresholds_lock);
5699 thresholds = &memcg->thresholds;
5700 else if (type == _MEMSWAP)
5701 thresholds = &memcg->memsw_thresholds;
5705 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
5707 /* Check if a threshold crossed before adding a new one */
5708 if (thresholds->primary)
5709 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
5711 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
5713 /* Allocate memory for new array of thresholds */
5714 new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
5722 /* Copy thresholds (if any) to new array */
5723 if (thresholds->primary) {
5724 memcpy(new->entries, thresholds->primary->entries, (size - 1) *
5725 sizeof(struct mem_cgroup_threshold));
5728 /* Add new threshold */
5729 new->entries[size - 1].eventfd = eventfd;
5730 new->entries[size - 1].threshold = threshold;
5732 /* Sort thresholds. Registering of new threshold isn't time-critical */
5733 sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
5734 compare_thresholds, NULL);
5736 /* Find current threshold */
5737 new->current_threshold = -1;
5738 for (i = 0; i < size; i++) {
5739 if (new->entries[i].threshold <= usage) {
5741 * new->current_threshold will not be used until
5742 * rcu_assign_pointer(), so it's safe to increment
5745 ++new->current_threshold;
5750 /* Free old spare buffer and save old primary buffer as spare */
5751 kfree(thresholds->spare);
5752 thresholds->spare = thresholds->primary;
5754 rcu_assign_pointer(thresholds->primary, new);
5756 /* To be sure that nobody uses thresholds */
5760 mutex_unlock(&memcg->thresholds_lock);
5765 static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,
5766 struct cftype *cft, struct eventfd_ctx *eventfd)
5768 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5769 struct mem_cgroup_thresholds *thresholds;
5770 struct mem_cgroup_threshold_ary *new;
5771 enum res_type type = MEMFILE_TYPE(cft->private);
5775 mutex_lock(&memcg->thresholds_lock);
5777 thresholds = &memcg->thresholds;
5778 else if (type == _MEMSWAP)
5779 thresholds = &memcg->memsw_thresholds;
5783 if (!thresholds->primary)
5786 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
5788 /* Check if a threshold crossed before removing */
5789 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
5791 /* Calculate new number of threshold */
5793 for (i = 0; i < thresholds->primary->size; i++) {
5794 if (thresholds->primary->entries[i].eventfd != eventfd)
5798 new = thresholds->spare;
5800 /* Set thresholds array to NULL if we don't have thresholds */
5809 /* Copy thresholds and find current threshold */
5810 new->current_threshold = -1;
5811 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
5812 if (thresholds->primary->entries[i].eventfd == eventfd)
5815 new->entries[j] = thresholds->primary->entries[i];
5816 if (new->entries[j].threshold <= usage) {
5818 * new->current_threshold will not be used
5819 * until rcu_assign_pointer(), so it's safe to increment
5822 ++new->current_threshold;
5828 /* Swap primary and spare array */
5829 thresholds->spare = thresholds->primary;
5830 /* If all events are unregistered, free the spare array */
5832 kfree(thresholds->spare);
5833 thresholds->spare = NULL;
5836 rcu_assign_pointer(thresholds->primary, new);
5838 /* To be sure that nobody uses thresholds */
5841 mutex_unlock(&memcg->thresholds_lock);
5844 static int mem_cgroup_oom_register_event(struct cgroup *cgrp,
5845 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
5847 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5848 struct mem_cgroup_eventfd_list *event;
5849 enum res_type type = MEMFILE_TYPE(cft->private);
5851 BUG_ON(type != _OOM_TYPE);
5852 event = kmalloc(sizeof(*event), GFP_KERNEL);
5856 spin_lock(&memcg_oom_lock);
5858 event->eventfd = eventfd;
5859 list_add(&event->list, &memcg->oom_notify);
5861 /* already in OOM ? */
5862 if (atomic_read(&memcg->under_oom))
5863 eventfd_signal(eventfd, 1);
5864 spin_unlock(&memcg_oom_lock);
5869 static void mem_cgroup_oom_unregister_event(struct cgroup *cgrp,
5870 struct cftype *cft, struct eventfd_ctx *eventfd)
5872 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5873 struct mem_cgroup_eventfd_list *ev, *tmp;
5874 enum res_type type = MEMFILE_TYPE(cft->private);
5876 BUG_ON(type != _OOM_TYPE);
5878 spin_lock(&memcg_oom_lock);
5880 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
5881 if (ev->eventfd == eventfd) {
5882 list_del(&ev->list);
5887 spin_unlock(&memcg_oom_lock);
5890 static int mem_cgroup_oom_control_read(struct cgroup *cgrp,
5891 struct cftype *cft, struct cgroup_map_cb *cb)
5893 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5895 cb->fill(cb, "oom_kill_disable", memcg->oom_kill_disable);
5897 if (atomic_read(&memcg->under_oom))
5898 cb->fill(cb, "under_oom", 1);
5900 cb->fill(cb, "under_oom", 0);
5904 static int mem_cgroup_oom_control_write(struct cgroup *cgrp,
5905 struct cftype *cft, u64 val)
5907 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5908 struct mem_cgroup *parent;
5910 /* cannot set to root cgroup and only 0 and 1 are allowed */
5911 if (!cgrp->parent || !((val == 0) || (val == 1)))
5914 parent = mem_cgroup_from_cont(cgrp->parent);
5916 mutex_lock(&memcg_create_mutex);
5917 /* oom-kill-disable is a flag for subhierarchy. */
5918 if ((parent->use_hierarchy) || memcg_has_children(memcg)) {
5919 mutex_unlock(&memcg_create_mutex);
5922 memcg->oom_kill_disable = val;
5924 memcg_oom_recover(memcg);
5925 mutex_unlock(&memcg_create_mutex);
5929 #ifdef CONFIG_MEMCG_KMEM
5930 static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
5934 memcg->kmemcg_id = -1;
5935 ret = memcg_propagate_kmem(memcg);
5939 return mem_cgroup_sockets_init(memcg, ss);
5942 static void kmem_cgroup_destroy(struct mem_cgroup *memcg)
5944 mem_cgroup_sockets_destroy(memcg);
5946 memcg_kmem_mark_dead(memcg);
5948 if (res_counter_read_u64(&memcg->kmem, RES_USAGE) != 0)
5952 * Charges already down to 0, undo mem_cgroup_get() done in the charge
5953 * path here, being careful not to race with memcg_uncharge_kmem: it is
5954 * possible that the charges went down to 0 between mark_dead and the
5955 * res_counter read, so in that case, we don't need the put
5957 if (memcg_kmem_test_and_clear_dead(memcg))
5958 mem_cgroup_put(memcg);
5961 static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
5966 static void kmem_cgroup_destroy(struct mem_cgroup *memcg)
5971 static struct cftype mem_cgroup_files[] = {
5973 .name = "usage_in_bytes",
5974 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
5975 .read = mem_cgroup_read,
5976 .register_event = mem_cgroup_usage_register_event,
5977 .unregister_event = mem_cgroup_usage_unregister_event,
5980 .name = "max_usage_in_bytes",
5981 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
5982 .trigger = mem_cgroup_reset,
5983 .read = mem_cgroup_read,
5986 .name = "limit_in_bytes",
5987 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
5988 .write_string = mem_cgroup_write,
5989 .read = mem_cgroup_read,
5992 .name = "soft_limit_in_bytes",
5993 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
5994 .write_string = mem_cgroup_write,
5995 .read = mem_cgroup_read,
5999 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
6000 .trigger = mem_cgroup_reset,
6001 .read = mem_cgroup_read,
6005 .read_seq_string = memcg_stat_show,
6008 .name = "force_empty",
6009 .trigger = mem_cgroup_force_empty_write,
6012 .name = "use_hierarchy",
6013 .flags = CFTYPE_INSANE,
6014 .write_u64 = mem_cgroup_hierarchy_write,
6015 .read_u64 = mem_cgroup_hierarchy_read,
6018 .name = "swappiness",
6019 .read_u64 = mem_cgroup_swappiness_read,
6020 .write_u64 = mem_cgroup_swappiness_write,
6023 .name = "move_charge_at_immigrate",
6024 .read_u64 = mem_cgroup_move_charge_read,
6025 .write_u64 = mem_cgroup_move_charge_write,
6028 .name = "oom_control",
6029 .read_map = mem_cgroup_oom_control_read,
6030 .write_u64 = mem_cgroup_oom_control_write,
6031 .register_event = mem_cgroup_oom_register_event,
6032 .unregister_event = mem_cgroup_oom_unregister_event,
6033 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
6036 .name = "pressure_level",
6037 .register_event = vmpressure_register_event,
6038 .unregister_event = vmpressure_unregister_event,
6042 .name = "numa_stat",
6043 .read_seq_string = memcg_numa_stat_show,
6046 #ifdef CONFIG_MEMCG_KMEM
6048 .name = "kmem.limit_in_bytes",
6049 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
6050 .write_string = mem_cgroup_write,
6051 .read = mem_cgroup_read,
6054 .name = "kmem.usage_in_bytes",
6055 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
6056 .read = mem_cgroup_read,
6059 .name = "kmem.failcnt",
6060 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
6061 .trigger = mem_cgroup_reset,
6062 .read = mem_cgroup_read,
6065 .name = "kmem.max_usage_in_bytes",
6066 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
6067 .trigger = mem_cgroup_reset,
6068 .read = mem_cgroup_read,
6070 #ifdef CONFIG_SLABINFO
6072 .name = "kmem.slabinfo",
6073 .read_seq_string = mem_cgroup_slabinfo_read,
6077 { }, /* terminate */
6080 #ifdef CONFIG_MEMCG_SWAP
6081 static struct cftype memsw_cgroup_files[] = {
6083 .name = "memsw.usage_in_bytes",
6084 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
6085 .read = mem_cgroup_read,
6086 .register_event = mem_cgroup_usage_register_event,
6087 .unregister_event = mem_cgroup_usage_unregister_event,
6090 .name = "memsw.max_usage_in_bytes",
6091 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
6092 .trigger = mem_cgroup_reset,
6093 .read = mem_cgroup_read,
6096 .name = "memsw.limit_in_bytes",
6097 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
6098 .write_string = mem_cgroup_write,
6099 .read = mem_cgroup_read,
6102 .name = "memsw.failcnt",
6103 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
6104 .trigger = mem_cgroup_reset,
6105 .read = mem_cgroup_read,
6107 { }, /* terminate */
6110 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
6112 struct mem_cgroup_per_node *pn;
6113 struct mem_cgroup_per_zone *mz;
6114 int zone, tmp = node;
6116 * This routine is called against possible nodes.
6117 * But it's BUG to call kmalloc() against offline node.
6119 * TODO: this routine can waste much memory for nodes which will
6120 * never be onlined. It's better to use memory hotplug callback
6123 if (!node_state(node, N_NORMAL_MEMORY))
6125 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
6129 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
6130 mz = &pn->zoneinfo[zone];
6131 lruvec_init(&mz->lruvec);
6132 mz->usage_in_excess = 0;
6133 mz->on_tree = false;
6136 memcg->info.nodeinfo[node] = pn;
6140 static void free_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
6142 kfree(memcg->info.nodeinfo[node]);
6145 static struct mem_cgroup *mem_cgroup_alloc(void)
6147 struct mem_cgroup *memcg;
6148 size_t size = memcg_size();
6150 /* Can be very big if nr_node_ids is very big */
6151 if (size < PAGE_SIZE)
6152 memcg = kzalloc(size, GFP_KERNEL);
6154 memcg = vzalloc(size);
6159 memcg->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
6162 spin_lock_init(&memcg->pcp_counter_lock);
6166 if (size < PAGE_SIZE)
6174 * At destroying mem_cgroup, references from swap_cgroup can remain.
6175 * (scanning all at force_empty is too costly...)
6177 * Instead of clearing all references at force_empty, we remember
6178 * the number of reference from swap_cgroup and free mem_cgroup when
6179 * it goes down to 0.
6181 * Removal of cgroup itself succeeds regardless of refs from swap.
6184 static void __mem_cgroup_free(struct mem_cgroup *memcg)
6187 size_t size = memcg_size();
6189 mem_cgroup_remove_from_trees(memcg);
6190 free_css_id(&mem_cgroup_subsys, &memcg->css);
6193 free_mem_cgroup_per_zone_info(memcg, node);
6195 free_percpu(memcg->stat);
6198 * We need to make sure that (at least for now), the jump label
6199 * destruction code runs outside of the cgroup lock. This is because
6200 * get_online_cpus(), which is called from the static_branch update,
6201 * can't be called inside the cgroup_lock. cpusets are the ones
6202 * enforcing this dependency, so if they ever change, we might as well.
6204 * schedule_work() will guarantee this happens. Be careful if you need
6205 * to move this code around, and make sure it is outside
6208 disarm_static_keys(memcg);
6209 if (size < PAGE_SIZE)
6217 * Helpers for freeing a kmalloc()ed/vzalloc()ed mem_cgroup by RCU,
6218 * but in process context. The work_freeing structure is overlaid
6219 * on the rcu_freeing structure, which itself is overlaid on memsw.
6221 static void free_work(struct work_struct *work)
6223 struct mem_cgroup *memcg;
6225 memcg = container_of(work, struct mem_cgroup, work_freeing);
6226 __mem_cgroup_free(memcg);
6229 static void free_rcu(struct rcu_head *rcu_head)
6231 struct mem_cgroup *memcg;
6233 memcg = container_of(rcu_head, struct mem_cgroup, rcu_freeing);
6234 INIT_WORK(&memcg->work_freeing, free_work);
6235 schedule_work(&memcg->work_freeing);
6238 static void mem_cgroup_get(struct mem_cgroup *memcg)
6240 atomic_inc(&memcg->refcnt);
6243 static void __mem_cgroup_put(struct mem_cgroup *memcg, int count)
6245 if (atomic_sub_and_test(count, &memcg->refcnt)) {
6246 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
6247 call_rcu(&memcg->rcu_freeing, free_rcu);
6249 mem_cgroup_put(parent);
6253 static void mem_cgroup_put(struct mem_cgroup *memcg)
6255 __mem_cgroup_put(memcg, 1);
6259 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
6261 struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg)
6263 if (!memcg->res.parent)
6265 return mem_cgroup_from_res_counter(memcg->res.parent, res);
6267 EXPORT_SYMBOL(parent_mem_cgroup);
6269 static void __init mem_cgroup_soft_limit_tree_init(void)
6271 struct mem_cgroup_tree_per_node *rtpn;
6272 struct mem_cgroup_tree_per_zone *rtpz;
6273 int tmp, node, zone;
6275 for_each_node(node) {
6277 if (!node_state(node, N_NORMAL_MEMORY))
6279 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
6282 soft_limit_tree.rb_tree_per_node[node] = rtpn;
6284 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
6285 rtpz = &rtpn->rb_tree_per_zone[zone];
6286 rtpz->rb_root = RB_ROOT;
6287 spin_lock_init(&rtpz->lock);
6292 static struct cgroup_subsys_state * __ref
6293 mem_cgroup_css_alloc(struct cgroup *cont)
6295 struct mem_cgroup *memcg;
6296 long error = -ENOMEM;
6299 memcg = mem_cgroup_alloc();
6301 return ERR_PTR(error);
6304 if (alloc_mem_cgroup_per_zone_info(memcg, node))
6308 if (cont->parent == NULL) {
6309 root_mem_cgroup = memcg;
6310 res_counter_init(&memcg->res, NULL);
6311 res_counter_init(&memcg->memsw, NULL);
6312 res_counter_init(&memcg->kmem, NULL);
6315 memcg->last_scanned_node = MAX_NUMNODES;
6316 INIT_LIST_HEAD(&memcg->oom_notify);
6317 atomic_set(&memcg->refcnt, 1);
6318 memcg->move_charge_at_immigrate = 0;
6319 mutex_init(&memcg->thresholds_lock);
6320 spin_lock_init(&memcg->move_lock);
6321 vmpressure_init(&memcg->vmpressure);
6326 __mem_cgroup_free(memcg);
6327 return ERR_PTR(error);
6331 mem_cgroup_css_online(struct cgroup *cont)
6333 struct mem_cgroup *memcg, *parent;
6339 mutex_lock(&memcg_create_mutex);
6340 memcg = mem_cgroup_from_cont(cont);
6341 parent = mem_cgroup_from_cont(cont->parent);
6343 memcg->use_hierarchy = parent->use_hierarchy;
6344 memcg->oom_kill_disable = parent->oom_kill_disable;
6345 memcg->swappiness = mem_cgroup_swappiness(parent);
6347 if (parent->use_hierarchy) {
6348 res_counter_init(&memcg->res, &parent->res);
6349 res_counter_init(&memcg->memsw, &parent->memsw);
6350 res_counter_init(&memcg->kmem, &parent->kmem);
6353 * We increment refcnt of the parent to ensure that we can
6354 * safely access it on res_counter_charge/uncharge.
6355 * This refcnt will be decremented when freeing this
6356 * mem_cgroup(see mem_cgroup_put).
6358 mem_cgroup_get(parent);
6360 res_counter_init(&memcg->res, NULL);
6361 res_counter_init(&memcg->memsw, NULL);
6362 res_counter_init(&memcg->kmem, NULL);
6364 * Deeper hierachy with use_hierarchy == false doesn't make
6365 * much sense so let cgroup subsystem know about this
6366 * unfortunate state in our controller.
6368 if (parent != root_mem_cgroup)
6369 mem_cgroup_subsys.broken_hierarchy = true;
6372 error = memcg_init_kmem(memcg, &mem_cgroup_subsys);
6373 mutex_unlock(&memcg_create_mutex);
6378 * Announce all parents that a group from their hierarchy is gone.
6380 static void mem_cgroup_invalidate_reclaim_iterators(struct mem_cgroup *memcg)
6382 struct mem_cgroup *parent = memcg;
6384 while ((parent = parent_mem_cgroup(parent)))
6385 atomic_inc(&parent->dead_count);
6388 * if the root memcg is not hierarchical we have to check it
6391 if (!root_mem_cgroup->use_hierarchy)
6392 atomic_inc(&root_mem_cgroup->dead_count);
6395 static void mem_cgroup_css_offline(struct cgroup *cont)
6397 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
6398 struct cgroup *iter;
6400 mem_cgroup_invalidate_reclaim_iterators(memcg);
6403 * This requires that offlining is serialized. Right now that is
6404 * guaranteed because css_killed_work_fn() holds the cgroup_mutex.
6407 cgroup_for_each_descendant_post(iter, cont) {
6409 mem_cgroup_reparent_charges(mem_cgroup_from_cont(iter));
6413 mem_cgroup_reparent_charges(memcg);
6415 mem_cgroup_destroy_all_caches(memcg);
6418 static void mem_cgroup_css_free(struct cgroup *cont)
6420 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
6422 kmem_cgroup_destroy(memcg);
6424 mem_cgroup_put(memcg);
6428 /* Handlers for move charge at task migration. */
6429 #define PRECHARGE_COUNT_AT_ONCE 256
6430 static int mem_cgroup_do_precharge(unsigned long count)
6433 int batch_count = PRECHARGE_COUNT_AT_ONCE;
6434 struct mem_cgroup *memcg = mc.to;
6436 if (mem_cgroup_is_root(memcg)) {
6437 mc.precharge += count;
6438 /* we don't need css_get for root */
6441 /* try to charge at once */
6443 struct res_counter *dummy;
6445 * "memcg" cannot be under rmdir() because we've already checked
6446 * by cgroup_lock_live_cgroup() that it is not removed and we
6447 * are still under the same cgroup_mutex. So we can postpone
6450 if (res_counter_charge(&memcg->res, PAGE_SIZE * count, &dummy))
6452 if (do_swap_account && res_counter_charge(&memcg->memsw,
6453 PAGE_SIZE * count, &dummy)) {
6454 res_counter_uncharge(&memcg->res, PAGE_SIZE * count);
6457 mc.precharge += count;
6461 /* fall back to one by one charge */
6463 if (signal_pending(current)) {
6467 if (!batch_count--) {
6468 batch_count = PRECHARGE_COUNT_AT_ONCE;
6471 ret = __mem_cgroup_try_charge(NULL,
6472 GFP_KERNEL, 1, &memcg, false);
6474 /* mem_cgroup_clear_mc() will do uncharge later */
6482 * get_mctgt_type - get target type of moving charge
6483 * @vma: the vma the pte to be checked belongs
6484 * @addr: the address corresponding to the pte to be checked
6485 * @ptent: the pte to be checked
6486 * @target: the pointer the target page or swap ent will be stored(can be NULL)
6489 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
6490 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
6491 * move charge. if @target is not NULL, the page is stored in target->page
6492 * with extra refcnt got(Callers should handle it).
6493 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
6494 * target for charge migration. if @target is not NULL, the entry is stored
6497 * Called with pte lock held.
6504 enum mc_target_type {
6510 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
6511 unsigned long addr, pte_t ptent)
6513 struct page *page = vm_normal_page(vma, addr, ptent);
6515 if (!page || !page_mapped(page))
6517 if (PageAnon(page)) {
6518 /* we don't move shared anon */
6521 } else if (!move_file())
6522 /* we ignore mapcount for file pages */
6524 if (!get_page_unless_zero(page))
6531 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
6532 unsigned long addr, pte_t ptent, swp_entry_t *entry)
6534 struct page *page = NULL;
6535 swp_entry_t ent = pte_to_swp_entry(ptent);
6537 if (!move_anon() || non_swap_entry(ent))
6540 * Because lookup_swap_cache() updates some statistics counter,
6541 * we call find_get_page() with swapper_space directly.
6543 page = find_get_page(swap_address_space(ent), ent.val);
6544 if (do_swap_account)
6545 entry->val = ent.val;
6550 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
6551 unsigned long addr, pte_t ptent, swp_entry_t *entry)
6557 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
6558 unsigned long addr, pte_t ptent, swp_entry_t *entry)
6560 struct page *page = NULL;
6561 struct address_space *mapping;
6564 if (!vma->vm_file) /* anonymous vma */
6569 mapping = vma->vm_file->f_mapping;
6570 if (pte_none(ptent))
6571 pgoff = linear_page_index(vma, addr);
6572 else /* pte_file(ptent) is true */
6573 pgoff = pte_to_pgoff(ptent);
6575 /* page is moved even if it's not RSS of this task(page-faulted). */
6576 page = find_get_page(mapping, pgoff);
6579 /* shmem/tmpfs may report page out on swap: account for that too. */
6580 if (radix_tree_exceptional_entry(page)) {
6581 swp_entry_t swap = radix_to_swp_entry(page);
6582 if (do_swap_account)
6584 page = find_get_page(swap_address_space(swap), swap.val);
6590 static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
6591 unsigned long addr, pte_t ptent, union mc_target *target)
6593 struct page *page = NULL;
6594 struct page_cgroup *pc;
6595 enum mc_target_type ret = MC_TARGET_NONE;
6596 swp_entry_t ent = { .val = 0 };
6598 if (pte_present(ptent))
6599 page = mc_handle_present_pte(vma, addr, ptent);
6600 else if (is_swap_pte(ptent))
6601 page = mc_handle_swap_pte(vma, addr, ptent, &ent);
6602 else if (pte_none(ptent) || pte_file(ptent))
6603 page = mc_handle_file_pte(vma, addr, ptent, &ent);
6605 if (!page && !ent.val)
6608 pc = lookup_page_cgroup(page);
6610 * Do only loose check w/o page_cgroup lock.
6611 * mem_cgroup_move_account() checks the pc is valid or not under
6614 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
6615 ret = MC_TARGET_PAGE;
6617 target->page = page;
6619 if (!ret || !target)
6622 /* There is a swap entry and a page doesn't exist or isn't charged */
6623 if (ent.val && !ret &&
6624 css_id(&mc.from->css) == lookup_swap_cgroup_id(ent)) {
6625 ret = MC_TARGET_SWAP;
6632 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
6634 * We don't consider swapping or file mapped pages because THP does not
6635 * support them for now.
6636 * Caller should make sure that pmd_trans_huge(pmd) is true.
6638 static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
6639 unsigned long addr, pmd_t pmd, union mc_target *target)
6641 struct page *page = NULL;
6642 struct page_cgroup *pc;
6643 enum mc_target_type ret = MC_TARGET_NONE;
6645 page = pmd_page(pmd);
6646 VM_BUG_ON(!page || !PageHead(page));
6649 pc = lookup_page_cgroup(page);
6650 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
6651 ret = MC_TARGET_PAGE;
6654 target->page = page;
6660 static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
6661 unsigned long addr, pmd_t pmd, union mc_target *target)
6663 return MC_TARGET_NONE;
6667 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
6668 unsigned long addr, unsigned long end,
6669 struct mm_walk *walk)
6671 struct vm_area_struct *vma = walk->private;
6675 if (pmd_trans_huge_lock(pmd, vma) == 1) {
6676 if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
6677 mc.precharge += HPAGE_PMD_NR;
6678 spin_unlock(&vma->vm_mm->page_table_lock);
6682 if (pmd_trans_unstable(pmd))
6684 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6685 for (; addr != end; pte++, addr += PAGE_SIZE)
6686 if (get_mctgt_type(vma, addr, *pte, NULL))
6687 mc.precharge++; /* increment precharge temporarily */
6688 pte_unmap_unlock(pte - 1, ptl);
6694 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
6696 unsigned long precharge;
6697 struct vm_area_struct *vma;
6699 down_read(&mm->mmap_sem);
6700 for (vma = mm->mmap; vma; vma = vma->vm_next) {
6701 struct mm_walk mem_cgroup_count_precharge_walk = {
6702 .pmd_entry = mem_cgroup_count_precharge_pte_range,
6706 if (is_vm_hugetlb_page(vma))
6708 walk_page_range(vma->vm_start, vma->vm_end,
6709 &mem_cgroup_count_precharge_walk);
6711 up_read(&mm->mmap_sem);
6713 precharge = mc.precharge;
6719 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
6721 unsigned long precharge = mem_cgroup_count_precharge(mm);
6723 VM_BUG_ON(mc.moving_task);
6724 mc.moving_task = current;
6725 return mem_cgroup_do_precharge(precharge);
6728 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
6729 static void __mem_cgroup_clear_mc(void)
6731 struct mem_cgroup *from = mc.from;
6732 struct mem_cgroup *to = mc.to;
6734 /* we must uncharge all the leftover precharges from mc.to */
6736 __mem_cgroup_cancel_charge(mc.to, mc.precharge);
6740 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
6741 * we must uncharge here.
6743 if (mc.moved_charge) {
6744 __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
6745 mc.moved_charge = 0;
6747 /* we must fixup refcnts and charges */
6748 if (mc.moved_swap) {
6749 /* uncharge swap account from the old cgroup */
6750 if (!mem_cgroup_is_root(mc.from))
6751 res_counter_uncharge(&mc.from->memsw,
6752 PAGE_SIZE * mc.moved_swap);
6753 __mem_cgroup_put(mc.from, mc.moved_swap);
6755 if (!mem_cgroup_is_root(mc.to)) {
6757 * we charged both to->res and to->memsw, so we should
6760 res_counter_uncharge(&mc.to->res,
6761 PAGE_SIZE * mc.moved_swap);
6763 /* we've already done mem_cgroup_get(mc.to) */
6766 memcg_oom_recover(from);
6767 memcg_oom_recover(to);
6768 wake_up_all(&mc.waitq);
6771 static void mem_cgroup_clear_mc(void)
6773 struct mem_cgroup *from = mc.from;
6776 * we must clear moving_task before waking up waiters at the end of
6779 mc.moving_task = NULL;
6780 __mem_cgroup_clear_mc();
6781 spin_lock(&mc.lock);
6784 spin_unlock(&mc.lock);
6785 mem_cgroup_end_move(from);
6788 static int mem_cgroup_can_attach(struct cgroup *cgroup,
6789 struct cgroup_taskset *tset)
6791 struct task_struct *p = cgroup_taskset_first(tset);
6793 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgroup);
6794 unsigned long move_charge_at_immigrate;
6797 * We are now commited to this value whatever it is. Changes in this
6798 * tunable will only affect upcoming migrations, not the current one.
6799 * So we need to save it, and keep it going.
6801 move_charge_at_immigrate = memcg->move_charge_at_immigrate;
6802 if (move_charge_at_immigrate) {
6803 struct mm_struct *mm;
6804 struct mem_cgroup *from = mem_cgroup_from_task(p);
6806 VM_BUG_ON(from == memcg);
6808 mm = get_task_mm(p);
6811 /* We move charges only when we move a owner of the mm */
6812 if (mm->owner == p) {
6815 VM_BUG_ON(mc.precharge);
6816 VM_BUG_ON(mc.moved_charge);
6817 VM_BUG_ON(mc.moved_swap);
6818 mem_cgroup_start_move(from);
6819 spin_lock(&mc.lock);
6822 mc.immigrate_flags = move_charge_at_immigrate;
6823 spin_unlock(&mc.lock);
6824 /* We set mc.moving_task later */
6826 ret = mem_cgroup_precharge_mc(mm);
6828 mem_cgroup_clear_mc();
6835 static void mem_cgroup_cancel_attach(struct cgroup *cgroup,
6836 struct cgroup_taskset *tset)
6838 mem_cgroup_clear_mc();
6841 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
6842 unsigned long addr, unsigned long end,
6843 struct mm_walk *walk)
6846 struct vm_area_struct *vma = walk->private;
6849 enum mc_target_type target_type;
6850 union mc_target target;
6852 struct page_cgroup *pc;
6855 * We don't take compound_lock() here but no race with splitting thp
6857 * - if pmd_trans_huge_lock() returns 1, the relevant thp is not
6858 * under splitting, which means there's no concurrent thp split,
6859 * - if another thread runs into split_huge_page() just after we
6860 * entered this if-block, the thread must wait for page table lock
6861 * to be unlocked in __split_huge_page_splitting(), where the main
6862 * part of thp split is not executed yet.
6864 if (pmd_trans_huge_lock(pmd, vma) == 1) {
6865 if (mc.precharge < HPAGE_PMD_NR) {
6866 spin_unlock(&vma->vm_mm->page_table_lock);
6869 target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
6870 if (target_type == MC_TARGET_PAGE) {
6872 if (!isolate_lru_page(page)) {
6873 pc = lookup_page_cgroup(page);
6874 if (!mem_cgroup_move_account(page, HPAGE_PMD_NR,
6875 pc, mc.from, mc.to)) {
6876 mc.precharge -= HPAGE_PMD_NR;
6877 mc.moved_charge += HPAGE_PMD_NR;
6879 putback_lru_page(page);
6883 spin_unlock(&vma->vm_mm->page_table_lock);
6887 if (pmd_trans_unstable(pmd))
6890 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6891 for (; addr != end; addr += PAGE_SIZE) {
6892 pte_t ptent = *(pte++);
6898 switch (get_mctgt_type(vma, addr, ptent, &target)) {
6899 case MC_TARGET_PAGE:
6901 if (isolate_lru_page(page))
6903 pc = lookup_page_cgroup(page);
6904 if (!mem_cgroup_move_account(page, 1, pc,
6907 /* we uncharge from mc.from later. */
6910 putback_lru_page(page);
6911 put: /* get_mctgt_type() gets the page */
6914 case MC_TARGET_SWAP:
6916 if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
6918 /* we fixup refcnts and charges later. */
6926 pte_unmap_unlock(pte - 1, ptl);
6931 * We have consumed all precharges we got in can_attach().
6932 * We try charge one by one, but don't do any additional
6933 * charges to mc.to if we have failed in charge once in attach()
6936 ret = mem_cgroup_do_precharge(1);
6944 static void mem_cgroup_move_charge(struct mm_struct *mm)
6946 struct vm_area_struct *vma;
6948 lru_add_drain_all();
6950 if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
6952 * Someone who are holding the mmap_sem might be waiting in
6953 * waitq. So we cancel all extra charges, wake up all waiters,
6954 * and retry. Because we cancel precharges, we might not be able
6955 * to move enough charges, but moving charge is a best-effort
6956 * feature anyway, so it wouldn't be a big problem.
6958 __mem_cgroup_clear_mc();
6962 for (vma = mm->mmap; vma; vma = vma->vm_next) {
6964 struct mm_walk mem_cgroup_move_charge_walk = {
6965 .pmd_entry = mem_cgroup_move_charge_pte_range,
6969 if (is_vm_hugetlb_page(vma))
6971 ret = walk_page_range(vma->vm_start, vma->vm_end,
6972 &mem_cgroup_move_charge_walk);
6975 * means we have consumed all precharges and failed in
6976 * doing additional charge. Just abandon here.
6980 up_read(&mm->mmap_sem);
6983 static void mem_cgroup_move_task(struct cgroup *cont,
6984 struct cgroup_taskset *tset)
6986 struct task_struct *p = cgroup_taskset_first(tset);
6987 struct mm_struct *mm = get_task_mm(p);
6991 mem_cgroup_move_charge(mm);
6995 mem_cgroup_clear_mc();
6997 #else /* !CONFIG_MMU */
6998 static int mem_cgroup_can_attach(struct cgroup *cgroup,
6999 struct cgroup_taskset *tset)
7003 static void mem_cgroup_cancel_attach(struct cgroup *cgroup,
7004 struct cgroup_taskset *tset)
7007 static void mem_cgroup_move_task(struct cgroup *cont,
7008 struct cgroup_taskset *tset)
7014 * Cgroup retains root cgroups across [un]mount cycles making it necessary
7015 * to verify sane_behavior flag on each mount attempt.
7017 static void mem_cgroup_bind(struct cgroup *root)
7020 * use_hierarchy is forced with sane_behavior. cgroup core
7021 * guarantees that @root doesn't have any children, so turning it
7022 * on for the root memcg is enough.
7024 if (cgroup_sane_behavior(root))
7025 mem_cgroup_from_cont(root)->use_hierarchy = true;
7028 struct cgroup_subsys mem_cgroup_subsys = {
7030 .subsys_id = mem_cgroup_subsys_id,
7031 .css_alloc = mem_cgroup_css_alloc,
7032 .css_online = mem_cgroup_css_online,
7033 .css_offline = mem_cgroup_css_offline,
7034 .css_free = mem_cgroup_css_free,
7035 .can_attach = mem_cgroup_can_attach,
7036 .cancel_attach = mem_cgroup_cancel_attach,
7037 .attach = mem_cgroup_move_task,
7038 .bind = mem_cgroup_bind,
7039 .base_cftypes = mem_cgroup_files,
7044 #ifdef CONFIG_MEMCG_SWAP
7045 static int __init enable_swap_account(char *s)
7047 /* consider enabled if no parameter or 1 is given */
7048 if (!strcmp(s, "1"))
7049 really_do_swap_account = 1;
7050 else if (!strcmp(s, "0"))
7051 really_do_swap_account = 0;
7054 __setup("swapaccount=", enable_swap_account);
7056 static void __init memsw_file_init(void)
7058 WARN_ON(cgroup_add_cftypes(&mem_cgroup_subsys, memsw_cgroup_files));
7061 static void __init enable_swap_cgroup(void)
7063 if (!mem_cgroup_disabled() && really_do_swap_account) {
7064 do_swap_account = 1;
7070 static void __init enable_swap_cgroup(void)
7076 * subsys_initcall() for memory controller.
7078 * Some parts like hotcpu_notifier() have to be initialized from this context
7079 * because of lock dependencies (cgroup_lock -> cpu hotplug) but basically
7080 * everything that doesn't depend on a specific mem_cgroup structure should
7081 * be initialized from here.
7083 static int __init mem_cgroup_init(void)
7085 hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
7086 enable_swap_cgroup();
7087 mem_cgroup_soft_limit_tree_init();
7091 subsys_initcall(mem_cgroup_init);