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/page_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/poll.h>
49 #include <linux/sort.h>
51 #include <linux/seq_file.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>
57 #include <linux/lockdep.h>
58 #include <linux/file.h>
62 #include <net/tcp_memcontrol.h>
65 #include <asm/uaccess.h>
67 #include <trace/events/vmscan.h>
69 struct cgroup_subsys memory_cgrp_subsys __read_mostly;
70 EXPORT_SYMBOL(memory_cgrp_subsys);
72 #define MEM_CGROUP_RECLAIM_RETRIES 5
73 static struct mem_cgroup *root_mem_cgroup __read_mostly;
75 #ifdef CONFIG_MEMCG_SWAP
76 /* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
77 int do_swap_account __read_mostly;
79 /* for remember boot option*/
80 #ifdef CONFIG_MEMCG_SWAP_ENABLED
81 static int really_do_swap_account __initdata = 1;
83 static int really_do_swap_account __initdata;
87 #define do_swap_account 0
91 static const char * const mem_cgroup_stat_names[] = {
100 enum mem_cgroup_events_index {
101 MEM_CGROUP_EVENTS_PGPGIN, /* # of pages paged in */
102 MEM_CGROUP_EVENTS_PGPGOUT, /* # of pages paged out */
103 MEM_CGROUP_EVENTS_PGFAULT, /* # of page-faults */
104 MEM_CGROUP_EVENTS_PGMAJFAULT, /* # of major page-faults */
105 MEM_CGROUP_EVENTS_NSTATS,
108 static const char * const mem_cgroup_events_names[] = {
115 static const char * const mem_cgroup_lru_names[] = {
124 * Per memcg event counter is incremented at every pagein/pageout. With THP,
125 * it will be incremated by the number of pages. This counter is used for
126 * for trigger some periodic events. This is straightforward and better
127 * than using jiffies etc. to handle periodic memcg event.
129 enum mem_cgroup_events_target {
130 MEM_CGROUP_TARGET_THRESH,
131 MEM_CGROUP_TARGET_SOFTLIMIT,
132 MEM_CGROUP_TARGET_NUMAINFO,
135 #define THRESHOLDS_EVENTS_TARGET 128
136 #define SOFTLIMIT_EVENTS_TARGET 1024
137 #define NUMAINFO_EVENTS_TARGET 1024
139 struct mem_cgroup_stat_cpu {
140 long count[MEM_CGROUP_STAT_NSTATS];
141 unsigned long events[MEM_CGROUP_EVENTS_NSTATS];
142 unsigned long nr_page_events;
143 unsigned long targets[MEM_CGROUP_NTARGETS];
146 struct reclaim_iter {
147 struct mem_cgroup *position;
148 /* scan generation, increased every round-trip */
149 unsigned int generation;
153 * per-zone information in memory controller.
155 struct mem_cgroup_per_zone {
156 struct lruvec lruvec;
157 unsigned long lru_size[NR_LRU_LISTS];
159 struct reclaim_iter iter[DEF_PRIORITY + 1];
161 struct rb_node tree_node; /* RB tree node */
162 unsigned long usage_in_excess;/* Set to the value by which */
163 /* the soft limit is exceeded*/
165 struct mem_cgroup *memcg; /* Back pointer, we cannot */
166 /* use container_of */
169 struct mem_cgroup_per_node {
170 struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
174 * Cgroups above their limits are maintained in a RB-Tree, independent of
175 * their hierarchy representation
178 struct mem_cgroup_tree_per_zone {
179 struct rb_root rb_root;
183 struct mem_cgroup_tree_per_node {
184 struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
187 struct mem_cgroup_tree {
188 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
191 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
193 struct mem_cgroup_threshold {
194 struct eventfd_ctx *eventfd;
195 unsigned long threshold;
199 struct mem_cgroup_threshold_ary {
200 /* An array index points to threshold just below or equal to usage. */
201 int current_threshold;
202 /* Size of entries[] */
204 /* Array of thresholds */
205 struct mem_cgroup_threshold entries[0];
208 struct mem_cgroup_thresholds {
209 /* Primary thresholds array */
210 struct mem_cgroup_threshold_ary *primary;
212 * Spare threshold array.
213 * This is needed to make mem_cgroup_unregister_event() "never fail".
214 * It must be able to store at least primary->size - 1 entries.
216 struct mem_cgroup_threshold_ary *spare;
220 struct mem_cgroup_eventfd_list {
221 struct list_head list;
222 struct eventfd_ctx *eventfd;
226 * cgroup_event represents events which userspace want to receive.
228 struct mem_cgroup_event {
230 * memcg which the event belongs to.
232 struct mem_cgroup *memcg;
234 * eventfd to signal userspace about the event.
236 struct eventfd_ctx *eventfd;
238 * Each of these stored in a list by the cgroup.
240 struct list_head list;
242 * register_event() callback will be used to add new userspace
243 * waiter for changes related to this event. Use eventfd_signal()
244 * on eventfd to send notification to userspace.
246 int (*register_event)(struct mem_cgroup *memcg,
247 struct eventfd_ctx *eventfd, const char *args);
249 * unregister_event() callback will be called when userspace closes
250 * the eventfd or on cgroup removing. This callback must be set,
251 * if you want provide notification functionality.
253 void (*unregister_event)(struct mem_cgroup *memcg,
254 struct eventfd_ctx *eventfd);
256 * All fields below needed to unregister event when
257 * userspace closes eventfd.
260 wait_queue_head_t *wqh;
262 struct work_struct remove;
265 static void mem_cgroup_threshold(struct mem_cgroup *memcg);
266 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
269 * The memory controller data structure. The memory controller controls both
270 * page cache and RSS per cgroup. We would eventually like to provide
271 * statistics based on the statistics developed by Rik Van Riel for clock-pro,
272 * to help the administrator determine what knobs to tune.
274 * TODO: Add a water mark for the memory controller. Reclaim will begin when
275 * we hit the water mark. May be even add a low water mark, such that
276 * no reclaim occurs from a cgroup at it's low water mark, this is
277 * a feature that will be implemented much later in the future.
280 struct cgroup_subsys_state css;
282 /* Accounted resources */
283 struct page_counter memory;
284 struct page_counter memsw;
285 struct page_counter kmem;
287 unsigned long soft_limit;
289 /* vmpressure notifications */
290 struct vmpressure vmpressure;
292 /* css_online() has been completed */
296 * Should the accounting and control be hierarchical, per subtree?
299 unsigned long kmem_account_flags; /* See KMEM_ACCOUNTED_*, below */
303 atomic_t oom_wakeups;
306 /* OOM-Killer disable */
307 int oom_kill_disable;
309 /* protect arrays of thresholds */
310 struct mutex thresholds_lock;
312 /* thresholds for memory usage. RCU-protected */
313 struct mem_cgroup_thresholds thresholds;
315 /* thresholds for mem+swap usage. RCU-protected */
316 struct mem_cgroup_thresholds memsw_thresholds;
318 /* For oom notifier event fd */
319 struct list_head oom_notify;
322 * Should we move charges of a task when a task is moved into this
323 * mem_cgroup ? And what type of charges should we move ?
325 unsigned long move_charge_at_immigrate;
327 * set > 0 if pages under this cgroup are moving to other cgroup.
329 atomic_t moving_account;
330 /* taken only while moving_account > 0 */
331 spinlock_t move_lock;
335 struct mem_cgroup_stat_cpu __percpu *stat;
337 * used when a cpu is offlined or other synchronizations
338 * See mem_cgroup_read_stat().
340 struct mem_cgroup_stat_cpu nocpu_base;
341 spinlock_t pcp_counter_lock;
343 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_INET)
344 struct cg_proto tcp_mem;
346 #if defined(CONFIG_MEMCG_KMEM)
347 /* analogous to slab_common's slab_caches list, but per-memcg;
348 * protected by memcg_slab_mutex */
349 struct list_head memcg_slab_caches;
350 /* Index in the kmem_cache->memcg_params->memcg_caches array */
354 int last_scanned_node;
356 nodemask_t scan_nodes;
357 atomic_t numainfo_events;
358 atomic_t numainfo_updating;
361 /* List of events which userspace want to receive */
362 struct list_head event_list;
363 spinlock_t event_list_lock;
365 struct mem_cgroup_per_node *nodeinfo[0];
366 /* WARNING: nodeinfo must be the last member here */
369 /* internal only representation about the status of kmem accounting. */
371 KMEM_ACCOUNTED_ACTIVE, /* accounted by this cgroup itself */
374 #ifdef CONFIG_MEMCG_KMEM
375 static inline void memcg_kmem_set_active(struct mem_cgroup *memcg)
377 set_bit(KMEM_ACCOUNTED_ACTIVE, &memcg->kmem_account_flags);
380 static bool memcg_kmem_is_active(struct mem_cgroup *memcg)
382 return test_bit(KMEM_ACCOUNTED_ACTIVE, &memcg->kmem_account_flags);
387 /* Stuffs for move charges at task migration. */
389 * Types of charges to be moved. "move_charge_at_immitgrate" and
390 * "immigrate_flags" are treated as a left-shifted bitmap of these types.
393 MOVE_CHARGE_TYPE_ANON, /* private anonymous page and swap of it */
394 MOVE_CHARGE_TYPE_FILE, /* file page(including tmpfs) and swap of it */
398 /* "mc" and its members are protected by cgroup_mutex */
399 static struct move_charge_struct {
400 spinlock_t lock; /* for from, to */
401 struct mem_cgroup *from;
402 struct mem_cgroup *to;
403 unsigned long immigrate_flags;
404 unsigned long precharge;
405 unsigned long moved_charge;
406 unsigned long moved_swap;
407 struct task_struct *moving_task; /* a task moving charges */
408 wait_queue_head_t waitq; /* a waitq for other context */
410 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
411 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
414 static bool move_anon(void)
416 return test_bit(MOVE_CHARGE_TYPE_ANON, &mc.immigrate_flags);
419 static bool move_file(void)
421 return test_bit(MOVE_CHARGE_TYPE_FILE, &mc.immigrate_flags);
425 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
426 * limit reclaim to prevent infinite loops, if they ever occur.
428 #define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
429 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
432 MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
433 MEM_CGROUP_CHARGE_TYPE_ANON,
434 MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
435 MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
439 /* for encoding cft->private value on file */
447 #define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
448 #define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
449 #define MEMFILE_ATTR(val) ((val) & 0xffff)
450 /* Used for OOM nofiier */
451 #define OOM_CONTROL (0)
454 * The memcg_create_mutex will be held whenever a new cgroup is created.
455 * As a consequence, any change that needs to protect against new child cgroups
456 * appearing has to hold it as well.
458 static DEFINE_MUTEX(memcg_create_mutex);
460 struct mem_cgroup *mem_cgroup_from_css(struct cgroup_subsys_state *s)
462 return s ? container_of(s, struct mem_cgroup, css) : NULL;
465 /* Some nice accessors for the vmpressure. */
466 struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
469 memcg = root_mem_cgroup;
470 return &memcg->vmpressure;
473 struct cgroup_subsys_state *vmpressure_to_css(struct vmpressure *vmpr)
475 return &container_of(vmpr, struct mem_cgroup, vmpressure)->css;
478 static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg)
480 return (memcg == root_mem_cgroup);
484 * We restrict the id in the range of [1, 65535], so it can fit into
487 #define MEM_CGROUP_ID_MAX USHRT_MAX
489 static inline unsigned short mem_cgroup_id(struct mem_cgroup *memcg)
491 return memcg->css.id;
494 static inline struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
496 struct cgroup_subsys_state *css;
498 css = css_from_id(id, &memory_cgrp_subsys);
499 return mem_cgroup_from_css(css);
502 /* Writing them here to avoid exposing memcg's inner layout */
503 #if defined(CONFIG_INET) && defined(CONFIG_MEMCG_KMEM)
505 void sock_update_memcg(struct sock *sk)
507 if (mem_cgroup_sockets_enabled) {
508 struct mem_cgroup *memcg;
509 struct cg_proto *cg_proto;
511 BUG_ON(!sk->sk_prot->proto_cgroup);
513 /* Socket cloning can throw us here with sk_cgrp already
514 * filled. It won't however, necessarily happen from
515 * process context. So the test for root memcg given
516 * the current task's memcg won't help us in this case.
518 * Respecting the original socket's memcg is a better
519 * decision in this case.
522 BUG_ON(mem_cgroup_is_root(sk->sk_cgrp->memcg));
523 css_get(&sk->sk_cgrp->memcg->css);
528 memcg = mem_cgroup_from_task(current);
529 cg_proto = sk->sk_prot->proto_cgroup(memcg);
530 if (!mem_cgroup_is_root(memcg) &&
531 memcg_proto_active(cg_proto) &&
532 css_tryget_online(&memcg->css)) {
533 sk->sk_cgrp = cg_proto;
538 EXPORT_SYMBOL(sock_update_memcg);
540 void sock_release_memcg(struct sock *sk)
542 if (mem_cgroup_sockets_enabled && sk->sk_cgrp) {
543 struct mem_cgroup *memcg;
544 WARN_ON(!sk->sk_cgrp->memcg);
545 memcg = sk->sk_cgrp->memcg;
546 css_put(&sk->sk_cgrp->memcg->css);
550 struct cg_proto *tcp_proto_cgroup(struct mem_cgroup *memcg)
552 if (!memcg || mem_cgroup_is_root(memcg))
555 return &memcg->tcp_mem;
557 EXPORT_SYMBOL(tcp_proto_cgroup);
559 static void disarm_sock_keys(struct mem_cgroup *memcg)
561 if (!memcg_proto_activated(&memcg->tcp_mem))
563 static_key_slow_dec(&memcg_socket_limit_enabled);
566 static void disarm_sock_keys(struct mem_cgroup *memcg)
571 #ifdef CONFIG_MEMCG_KMEM
573 * This will be the memcg's index in each cache's ->memcg_params->memcg_caches.
574 * The main reason for not using cgroup id for this:
575 * this works better in sparse environments, where we have a lot of memcgs,
576 * but only a few kmem-limited. Or also, if we have, for instance, 200
577 * memcgs, and none but the 200th is kmem-limited, we'd have to have a
578 * 200 entry array for that.
580 * The current size of the caches array is stored in
581 * memcg_limited_groups_array_size. It will double each time we have to
584 static DEFINE_IDA(kmem_limited_groups);
585 int memcg_limited_groups_array_size;
588 * MIN_SIZE is different than 1, because we would like to avoid going through
589 * the alloc/free process all the time. In a small machine, 4 kmem-limited
590 * cgroups is a reasonable guess. In the future, it could be a parameter or
591 * tunable, but that is strictly not necessary.
593 * MAX_SIZE should be as large as the number of cgrp_ids. Ideally, we could get
594 * this constant directly from cgroup, but it is understandable that this is
595 * better kept as an internal representation in cgroup.c. In any case, the
596 * cgrp_id space is not getting any smaller, and we don't have to necessarily
597 * increase ours as well if it increases.
599 #define MEMCG_CACHES_MIN_SIZE 4
600 #define MEMCG_CACHES_MAX_SIZE MEM_CGROUP_ID_MAX
603 * A lot of the calls to the cache allocation functions are expected to be
604 * inlined by the compiler. Since the calls to memcg_kmem_get_cache are
605 * conditional to this static branch, we'll have to allow modules that does
606 * kmem_cache_alloc and the such to see this symbol as well
608 struct static_key memcg_kmem_enabled_key;
609 EXPORT_SYMBOL(memcg_kmem_enabled_key);
611 static void memcg_free_cache_id(int id);
613 static void disarm_kmem_keys(struct mem_cgroup *memcg)
615 if (memcg_kmem_is_active(memcg)) {
616 static_key_slow_dec(&memcg_kmem_enabled_key);
617 memcg_free_cache_id(memcg->kmemcg_id);
620 * This check can't live in kmem destruction function,
621 * since the charges will outlive the cgroup
623 WARN_ON(page_counter_read(&memcg->kmem));
626 static void disarm_kmem_keys(struct mem_cgroup *memcg)
629 #endif /* CONFIG_MEMCG_KMEM */
631 static void disarm_static_keys(struct mem_cgroup *memcg)
633 disarm_sock_keys(memcg);
634 disarm_kmem_keys(memcg);
637 static void drain_all_stock_async(struct mem_cgroup *memcg);
639 static struct mem_cgroup_per_zone *
640 mem_cgroup_zone_zoneinfo(struct mem_cgroup *memcg, struct zone *zone)
642 int nid = zone_to_nid(zone);
643 int zid = zone_idx(zone);
645 return &memcg->nodeinfo[nid]->zoneinfo[zid];
648 struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *memcg)
653 static struct mem_cgroup_per_zone *
654 mem_cgroup_page_zoneinfo(struct mem_cgroup *memcg, struct page *page)
656 int nid = page_to_nid(page);
657 int zid = page_zonenum(page);
659 return &memcg->nodeinfo[nid]->zoneinfo[zid];
662 static struct mem_cgroup_tree_per_zone *
663 soft_limit_tree_node_zone(int nid, int zid)
665 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
668 static struct mem_cgroup_tree_per_zone *
669 soft_limit_tree_from_page(struct page *page)
671 int nid = page_to_nid(page);
672 int zid = page_zonenum(page);
674 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
677 static void __mem_cgroup_insert_exceeded(struct mem_cgroup_per_zone *mz,
678 struct mem_cgroup_tree_per_zone *mctz,
679 unsigned long new_usage_in_excess)
681 struct rb_node **p = &mctz->rb_root.rb_node;
682 struct rb_node *parent = NULL;
683 struct mem_cgroup_per_zone *mz_node;
688 mz->usage_in_excess = new_usage_in_excess;
689 if (!mz->usage_in_excess)
693 mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
695 if (mz->usage_in_excess < mz_node->usage_in_excess)
698 * We can't avoid mem cgroups that are over their soft
699 * limit by the same amount
701 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
704 rb_link_node(&mz->tree_node, parent, p);
705 rb_insert_color(&mz->tree_node, &mctz->rb_root);
709 static void __mem_cgroup_remove_exceeded(struct mem_cgroup_per_zone *mz,
710 struct mem_cgroup_tree_per_zone *mctz)
714 rb_erase(&mz->tree_node, &mctz->rb_root);
718 static void mem_cgroup_remove_exceeded(struct mem_cgroup_per_zone *mz,
719 struct mem_cgroup_tree_per_zone *mctz)
723 spin_lock_irqsave(&mctz->lock, flags);
724 __mem_cgroup_remove_exceeded(mz, mctz);
725 spin_unlock_irqrestore(&mctz->lock, flags);
728 static unsigned long soft_limit_excess(struct mem_cgroup *memcg)
730 unsigned long nr_pages = page_counter_read(&memcg->memory);
731 unsigned long soft_limit = ACCESS_ONCE(memcg->soft_limit);
732 unsigned long excess = 0;
734 if (nr_pages > soft_limit)
735 excess = nr_pages - soft_limit;
740 static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
742 unsigned long excess;
743 struct mem_cgroup_per_zone *mz;
744 struct mem_cgroup_tree_per_zone *mctz;
746 mctz = soft_limit_tree_from_page(page);
748 * Necessary to update all ancestors when hierarchy is used.
749 * because their event counter is not touched.
751 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
752 mz = mem_cgroup_page_zoneinfo(memcg, page);
753 excess = soft_limit_excess(memcg);
755 * We have to update the tree if mz is on RB-tree or
756 * mem is over its softlimit.
758 if (excess || mz->on_tree) {
761 spin_lock_irqsave(&mctz->lock, flags);
762 /* if on-tree, remove it */
764 __mem_cgroup_remove_exceeded(mz, mctz);
766 * Insert again. mz->usage_in_excess will be updated.
767 * If excess is 0, no tree ops.
769 __mem_cgroup_insert_exceeded(mz, mctz, excess);
770 spin_unlock_irqrestore(&mctz->lock, flags);
775 static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
777 struct mem_cgroup_tree_per_zone *mctz;
778 struct mem_cgroup_per_zone *mz;
782 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
783 mz = &memcg->nodeinfo[nid]->zoneinfo[zid];
784 mctz = soft_limit_tree_node_zone(nid, zid);
785 mem_cgroup_remove_exceeded(mz, mctz);
790 static struct mem_cgroup_per_zone *
791 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
793 struct rb_node *rightmost = NULL;
794 struct mem_cgroup_per_zone *mz;
798 rightmost = rb_last(&mctz->rb_root);
800 goto done; /* Nothing to reclaim from */
802 mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
804 * Remove the node now but someone else can add it back,
805 * we will to add it back at the end of reclaim to its correct
806 * position in the tree.
808 __mem_cgroup_remove_exceeded(mz, mctz);
809 if (!soft_limit_excess(mz->memcg) ||
810 !css_tryget_online(&mz->memcg->css))
816 static struct mem_cgroup_per_zone *
817 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
819 struct mem_cgroup_per_zone *mz;
821 spin_lock_irq(&mctz->lock);
822 mz = __mem_cgroup_largest_soft_limit_node(mctz);
823 spin_unlock_irq(&mctz->lock);
828 * Implementation Note: reading percpu statistics for memcg.
830 * Both of vmstat[] and percpu_counter has threshold and do periodic
831 * synchronization to implement "quick" read. There are trade-off between
832 * reading cost and precision of value. Then, we may have a chance to implement
833 * a periodic synchronizion of counter in memcg's counter.
835 * But this _read() function is used for user interface now. The user accounts
836 * memory usage by memory cgroup and he _always_ requires exact value because
837 * he accounts memory. Even if we provide quick-and-fuzzy read, we always
838 * have to visit all online cpus and make sum. So, for now, unnecessary
839 * synchronization is not implemented. (just implemented for cpu hotplug)
841 * If there are kernel internal actions which can make use of some not-exact
842 * value, and reading all cpu value can be performance bottleneck in some
843 * common workload, threashold and synchonization as vmstat[] should be
846 static long mem_cgroup_read_stat(struct mem_cgroup *memcg,
847 enum mem_cgroup_stat_index idx)
853 for_each_online_cpu(cpu)
854 val += per_cpu(memcg->stat->count[idx], cpu);
855 #ifdef CONFIG_HOTPLUG_CPU
856 spin_lock(&memcg->pcp_counter_lock);
857 val += memcg->nocpu_base.count[idx];
858 spin_unlock(&memcg->pcp_counter_lock);
864 static unsigned long mem_cgroup_read_events(struct mem_cgroup *memcg,
865 enum mem_cgroup_events_index idx)
867 unsigned long val = 0;
871 for_each_online_cpu(cpu)
872 val += per_cpu(memcg->stat->events[idx], cpu);
873 #ifdef CONFIG_HOTPLUG_CPU
874 spin_lock(&memcg->pcp_counter_lock);
875 val += memcg->nocpu_base.events[idx];
876 spin_unlock(&memcg->pcp_counter_lock);
882 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
887 * Here, RSS means 'mapped anon' and anon's SwapCache. Shmem/tmpfs is
888 * counted as CACHE even if it's on ANON LRU.
891 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS],
894 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_CACHE],
897 if (PageTransHuge(page))
898 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS_HUGE],
901 /* pagein of a big page is an event. So, ignore page size */
903 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGIN]);
905 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGOUT]);
906 nr_pages = -nr_pages; /* for event */
909 __this_cpu_add(memcg->stat->nr_page_events, nr_pages);
912 unsigned long mem_cgroup_get_lru_size(struct lruvec *lruvec, enum lru_list lru)
914 struct mem_cgroup_per_zone *mz;
916 mz = container_of(lruvec, struct mem_cgroup_per_zone, lruvec);
917 return mz->lru_size[lru];
920 static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
922 unsigned int lru_mask)
924 unsigned long nr = 0;
927 VM_BUG_ON((unsigned)nid >= nr_node_ids);
929 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
930 struct mem_cgroup_per_zone *mz;
934 if (!(BIT(lru) & lru_mask))
936 mz = &memcg->nodeinfo[nid]->zoneinfo[zid];
937 nr += mz->lru_size[lru];
943 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
944 unsigned int lru_mask)
946 unsigned long nr = 0;
949 for_each_node_state(nid, N_MEMORY)
950 nr += mem_cgroup_node_nr_lru_pages(memcg, nid, lru_mask);
954 static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
955 enum mem_cgroup_events_target target)
957 unsigned long val, next;
959 val = __this_cpu_read(memcg->stat->nr_page_events);
960 next = __this_cpu_read(memcg->stat->targets[target]);
961 /* from time_after() in jiffies.h */
962 if ((long)next - (long)val < 0) {
964 case MEM_CGROUP_TARGET_THRESH:
965 next = val + THRESHOLDS_EVENTS_TARGET;
967 case MEM_CGROUP_TARGET_SOFTLIMIT:
968 next = val + SOFTLIMIT_EVENTS_TARGET;
970 case MEM_CGROUP_TARGET_NUMAINFO:
971 next = val + NUMAINFO_EVENTS_TARGET;
976 __this_cpu_write(memcg->stat->targets[target], next);
983 * Check events in order.
986 static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
988 /* threshold event is triggered in finer grain than soft limit */
989 if (unlikely(mem_cgroup_event_ratelimit(memcg,
990 MEM_CGROUP_TARGET_THRESH))) {
992 bool do_numainfo __maybe_unused;
994 do_softlimit = mem_cgroup_event_ratelimit(memcg,
995 MEM_CGROUP_TARGET_SOFTLIMIT);
997 do_numainfo = mem_cgroup_event_ratelimit(memcg,
998 MEM_CGROUP_TARGET_NUMAINFO);
1000 mem_cgroup_threshold(memcg);
1001 if (unlikely(do_softlimit))
1002 mem_cgroup_update_tree(memcg, page);
1003 #if MAX_NUMNODES > 1
1004 if (unlikely(do_numainfo))
1005 atomic_inc(&memcg->numainfo_events);
1010 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
1013 * mm_update_next_owner() may clear mm->owner to NULL
1014 * if it races with swapoff, page migration, etc.
1015 * So this can be called with p == NULL.
1020 return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
1023 static struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
1025 struct mem_cgroup *memcg = NULL;
1030 * Page cache insertions can happen withou an
1031 * actual mm context, e.g. during disk probing
1032 * on boot, loopback IO, acct() writes etc.
1035 memcg = root_mem_cgroup;
1037 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
1038 if (unlikely(!memcg))
1039 memcg = root_mem_cgroup;
1041 } while (!css_tryget_online(&memcg->css));
1047 * mem_cgroup_iter - iterate over memory cgroup hierarchy
1048 * @root: hierarchy root
1049 * @prev: previously returned memcg, NULL on first invocation
1050 * @reclaim: cookie for shared reclaim walks, NULL for full walks
1052 * Returns references to children of the hierarchy below @root, or
1053 * @root itself, or %NULL after a full round-trip.
1055 * Caller must pass the return value in @prev on subsequent
1056 * invocations for reference counting, or use mem_cgroup_iter_break()
1057 * to cancel a hierarchy walk before the round-trip is complete.
1059 * Reclaimers can specify a zone and a priority level in @reclaim to
1060 * divide up the memcgs in the hierarchy among all concurrent
1061 * reclaimers operating on the same zone and priority.
1063 struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
1064 struct mem_cgroup *prev,
1065 struct mem_cgroup_reclaim_cookie *reclaim)
1067 struct reclaim_iter *uninitialized_var(iter);
1068 struct cgroup_subsys_state *css = NULL;
1069 struct mem_cgroup *memcg = NULL;
1070 struct mem_cgroup *pos = NULL;
1072 if (mem_cgroup_disabled())
1076 root = root_mem_cgroup;
1078 if (prev && !reclaim)
1081 if (!root->use_hierarchy && root != root_mem_cgroup) {
1090 struct mem_cgroup_per_zone *mz;
1092 mz = mem_cgroup_zone_zoneinfo(root, reclaim->zone);
1093 iter = &mz->iter[reclaim->priority];
1095 if (prev && reclaim->generation != iter->generation)
1099 pos = ACCESS_ONCE(iter->position);
1101 * A racing update may change the position and
1102 * put the last reference, hence css_tryget(),
1103 * or retry to see the updated position.
1105 } while (pos && !css_tryget(&pos->css));
1112 css = css_next_descendant_pre(css, &root->css);
1115 * Reclaimers share the hierarchy walk, and a
1116 * new one might jump in right at the end of
1117 * the hierarchy - make sure they see at least
1118 * one group and restart from the beginning.
1126 * Verify the css and acquire a reference. The root
1127 * is provided by the caller, so we know it's alive
1128 * and kicking, and don't take an extra reference.
1130 memcg = mem_cgroup_from_css(css);
1132 if (css == &root->css)
1135 if (css_tryget(css)) {
1137 * Make sure the memcg is initialized:
1138 * mem_cgroup_css_online() orders the the
1139 * initialization against setting the flag.
1141 if (smp_load_acquire(&memcg->initialized))
1151 if (cmpxchg(&iter->position, pos, memcg) == pos) {
1153 css_get(&memcg->css);
1159 * pairs with css_tryget when dereferencing iter->position
1168 reclaim->generation = iter->generation;
1174 if (prev && prev != root)
1175 css_put(&prev->css);
1181 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1182 * @root: hierarchy root
1183 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1185 void mem_cgroup_iter_break(struct mem_cgroup *root,
1186 struct mem_cgroup *prev)
1189 root = root_mem_cgroup;
1190 if (prev && prev != root)
1191 css_put(&prev->css);
1195 * Iteration constructs for visiting all cgroups (under a tree). If
1196 * loops are exited prematurely (break), mem_cgroup_iter_break() must
1197 * be used for reference counting.
1199 #define for_each_mem_cgroup_tree(iter, root) \
1200 for (iter = mem_cgroup_iter(root, NULL, NULL); \
1202 iter = mem_cgroup_iter(root, iter, NULL))
1204 #define for_each_mem_cgroup(iter) \
1205 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
1207 iter = mem_cgroup_iter(NULL, iter, NULL))
1209 void __mem_cgroup_count_vm_event(struct mm_struct *mm, enum vm_event_item idx)
1211 struct mem_cgroup *memcg;
1214 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
1215 if (unlikely(!memcg))
1220 this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGFAULT]);
1223 this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGMAJFAULT]);
1231 EXPORT_SYMBOL(__mem_cgroup_count_vm_event);
1234 * mem_cgroup_zone_lruvec - get the lru list vector for a zone and memcg
1235 * @zone: zone of the wanted lruvec
1236 * @memcg: memcg of the wanted lruvec
1238 * Returns the lru list vector holding pages for the given @zone and
1239 * @mem. This can be the global zone lruvec, if the memory controller
1242 struct lruvec *mem_cgroup_zone_lruvec(struct zone *zone,
1243 struct mem_cgroup *memcg)
1245 struct mem_cgroup_per_zone *mz;
1246 struct lruvec *lruvec;
1248 if (mem_cgroup_disabled()) {
1249 lruvec = &zone->lruvec;
1253 mz = mem_cgroup_zone_zoneinfo(memcg, zone);
1254 lruvec = &mz->lruvec;
1257 * Since a node can be onlined after the mem_cgroup was created,
1258 * we have to be prepared to initialize lruvec->zone here;
1259 * and if offlined then reonlined, we need to reinitialize it.
1261 if (unlikely(lruvec->zone != zone))
1262 lruvec->zone = zone;
1267 * mem_cgroup_page_lruvec - return lruvec for adding an lru page
1269 * @zone: zone of the page
1271 struct lruvec *mem_cgroup_page_lruvec(struct page *page, struct zone *zone)
1273 struct mem_cgroup_per_zone *mz;
1274 struct mem_cgroup *memcg;
1275 struct page_cgroup *pc;
1276 struct lruvec *lruvec;
1278 if (mem_cgroup_disabled()) {
1279 lruvec = &zone->lruvec;
1283 pc = lookup_page_cgroup(page);
1284 memcg = pc->mem_cgroup;
1287 * Surreptitiously switch any uncharged offlist page to root:
1288 * an uncharged page off lru does nothing to secure
1289 * its former mem_cgroup from sudden removal.
1291 * Our caller holds lru_lock, and PageCgroupUsed is updated
1292 * under page_cgroup lock: between them, they make all uses
1293 * of pc->mem_cgroup safe.
1295 if (!PageLRU(page) && !PageCgroupUsed(pc) && memcg != root_mem_cgroup)
1296 pc->mem_cgroup = memcg = root_mem_cgroup;
1298 mz = mem_cgroup_page_zoneinfo(memcg, page);
1299 lruvec = &mz->lruvec;
1302 * Since a node can be onlined after the mem_cgroup was created,
1303 * we have to be prepared to initialize lruvec->zone here;
1304 * and if offlined then reonlined, we need to reinitialize it.
1306 if (unlikely(lruvec->zone != zone))
1307 lruvec->zone = zone;
1312 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1313 * @lruvec: mem_cgroup per zone lru vector
1314 * @lru: index of lru list the page is sitting on
1315 * @nr_pages: positive when adding or negative when removing
1317 * This function must be called when a page is added to or removed from an
1320 void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
1323 struct mem_cgroup_per_zone *mz;
1324 unsigned long *lru_size;
1326 if (mem_cgroup_disabled())
1329 mz = container_of(lruvec, struct mem_cgroup_per_zone, lruvec);
1330 lru_size = mz->lru_size + lru;
1331 *lru_size += nr_pages;
1332 VM_BUG_ON((long)(*lru_size) < 0);
1336 * Checks whether given mem is same or in the root_mem_cgroup's
1339 bool __mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
1340 struct mem_cgroup *memcg)
1342 if (root_memcg == memcg)
1344 if (!root_memcg->use_hierarchy || !memcg)
1346 return cgroup_is_descendant(memcg->css.cgroup, root_memcg->css.cgroup);
1349 static bool mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
1350 struct mem_cgroup *memcg)
1355 ret = __mem_cgroup_same_or_subtree(root_memcg, memcg);
1360 bool task_in_mem_cgroup(struct task_struct *task,
1361 const struct mem_cgroup *memcg)
1363 struct mem_cgroup *curr = NULL;
1364 struct task_struct *p;
1367 p = find_lock_task_mm(task);
1369 curr = get_mem_cgroup_from_mm(p->mm);
1373 * All threads may have already detached their mm's, but the oom
1374 * killer still needs to detect if they have already been oom
1375 * killed to prevent needlessly killing additional tasks.
1378 curr = mem_cgroup_from_task(task);
1380 css_get(&curr->css);
1384 * We should check use_hierarchy of "memcg" not "curr". Because checking
1385 * use_hierarchy of "curr" here make this function true if hierarchy is
1386 * enabled in "curr" and "curr" is a child of "memcg" in *cgroup*
1387 * hierarchy(even if use_hierarchy is disabled in "memcg").
1389 ret = mem_cgroup_same_or_subtree(memcg, curr);
1390 css_put(&curr->css);
1394 int mem_cgroup_inactive_anon_is_low(struct lruvec *lruvec)
1396 unsigned long inactive_ratio;
1397 unsigned long inactive;
1398 unsigned long active;
1401 inactive = mem_cgroup_get_lru_size(lruvec, LRU_INACTIVE_ANON);
1402 active = mem_cgroup_get_lru_size(lruvec, LRU_ACTIVE_ANON);
1404 gb = (inactive + active) >> (30 - PAGE_SHIFT);
1406 inactive_ratio = int_sqrt(10 * gb);
1410 return inactive * inactive_ratio < active;
1413 #define mem_cgroup_from_counter(counter, member) \
1414 container_of(counter, struct mem_cgroup, member)
1417 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1418 * @memcg: the memory cgroup
1420 * Returns the maximum amount of memory @mem can be charged with, in
1423 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1425 unsigned long margin = 0;
1426 unsigned long count;
1427 unsigned long limit;
1429 count = page_counter_read(&memcg->memory);
1430 limit = ACCESS_ONCE(memcg->memory.limit);
1432 margin = limit - count;
1434 if (do_swap_account) {
1435 count = page_counter_read(&memcg->memsw);
1436 limit = ACCESS_ONCE(memcg->memsw.limit);
1438 margin = min(margin, limit - count);
1444 int mem_cgroup_swappiness(struct mem_cgroup *memcg)
1447 if (mem_cgroup_disabled() || !memcg->css.parent)
1448 return vm_swappiness;
1450 return memcg->swappiness;
1454 * memcg->moving_account is used for checking possibility that some thread is
1455 * calling move_account(). When a thread on CPU-A starts moving pages under
1456 * a memcg, other threads should check memcg->moving_account under
1457 * rcu_read_lock(), like this:
1461 * memcg->moving_account+1 if (memcg->mocing_account)
1463 * synchronize_rcu() update something.
1468 static void mem_cgroup_start_move(struct mem_cgroup *memcg)
1470 atomic_inc(&memcg->moving_account);
1474 static void mem_cgroup_end_move(struct mem_cgroup *memcg)
1477 * Now, mem_cgroup_clear_mc() may call this function with NULL.
1478 * We check NULL in callee rather than caller.
1481 atomic_dec(&memcg->moving_account);
1485 * A routine for checking "mem" is under move_account() or not.
1487 * Checking a cgroup is mc.from or mc.to or under hierarchy of
1488 * moving cgroups. This is for waiting at high-memory pressure
1491 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1493 struct mem_cgroup *from;
1494 struct mem_cgroup *to;
1497 * Unlike task_move routines, we access mc.to, mc.from not under
1498 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1500 spin_lock(&mc.lock);
1506 ret = mem_cgroup_same_or_subtree(memcg, from)
1507 || mem_cgroup_same_or_subtree(memcg, to);
1509 spin_unlock(&mc.lock);
1513 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1515 if (mc.moving_task && current != mc.moving_task) {
1516 if (mem_cgroup_under_move(memcg)) {
1518 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1519 /* moving charge context might have finished. */
1522 finish_wait(&mc.waitq, &wait);
1530 * Take this lock when
1531 * - a code tries to modify page's memcg while it's USED.
1532 * - a code tries to modify page state accounting in a memcg.
1534 static void move_lock_mem_cgroup(struct mem_cgroup *memcg,
1535 unsigned long *flags)
1537 spin_lock_irqsave(&memcg->move_lock, *flags);
1540 static void move_unlock_mem_cgroup(struct mem_cgroup *memcg,
1541 unsigned long *flags)
1543 spin_unlock_irqrestore(&memcg->move_lock, *flags);
1546 #define K(x) ((x) << (PAGE_SHIFT-10))
1548 * mem_cgroup_print_oom_info: Print OOM information relevant to memory controller.
1549 * @memcg: The memory cgroup that went over limit
1550 * @p: Task that is going to be killed
1552 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1555 void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1557 /* oom_info_lock ensures that parallel ooms do not interleave */
1558 static DEFINE_MUTEX(oom_info_lock);
1559 struct mem_cgroup *iter;
1565 mutex_lock(&oom_info_lock);
1568 pr_info("Task in ");
1569 pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
1570 pr_info(" killed as a result of limit of ");
1571 pr_cont_cgroup_path(memcg->css.cgroup);
1576 pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
1577 K((u64)page_counter_read(&memcg->memory)),
1578 K((u64)memcg->memory.limit), memcg->memory.failcnt);
1579 pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
1580 K((u64)page_counter_read(&memcg->memsw)),
1581 K((u64)memcg->memsw.limit), memcg->memsw.failcnt);
1582 pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
1583 K((u64)page_counter_read(&memcg->kmem)),
1584 K((u64)memcg->kmem.limit), memcg->kmem.failcnt);
1586 for_each_mem_cgroup_tree(iter, memcg) {
1587 pr_info("Memory cgroup stats for ");
1588 pr_cont_cgroup_path(iter->css.cgroup);
1591 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
1592 if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
1594 pr_cont(" %s:%ldKB", mem_cgroup_stat_names[i],
1595 K(mem_cgroup_read_stat(iter, i)));
1598 for (i = 0; i < NR_LRU_LISTS; i++)
1599 pr_cont(" %s:%luKB", mem_cgroup_lru_names[i],
1600 K(mem_cgroup_nr_lru_pages(iter, BIT(i))));
1604 mutex_unlock(&oom_info_lock);
1608 * This function returns the number of memcg under hierarchy tree. Returns
1609 * 1(self count) if no children.
1611 static int mem_cgroup_count_children(struct mem_cgroup *memcg)
1614 struct mem_cgroup *iter;
1616 for_each_mem_cgroup_tree(iter, memcg)
1622 * Return the memory (and swap, if configured) limit for a memcg.
1624 static unsigned long mem_cgroup_get_limit(struct mem_cgroup *memcg)
1626 unsigned long limit;
1628 limit = memcg->memory.limit;
1629 if (mem_cgroup_swappiness(memcg)) {
1630 unsigned long memsw_limit;
1632 memsw_limit = memcg->memsw.limit;
1633 limit = min(limit + total_swap_pages, memsw_limit);
1638 static void mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
1641 struct mem_cgroup *iter;
1642 unsigned long chosen_points = 0;
1643 unsigned long totalpages;
1644 unsigned int points = 0;
1645 struct task_struct *chosen = NULL;
1648 * If current has a pending SIGKILL or is exiting, then automatically
1649 * select it. The goal is to allow it to allocate so that it may
1650 * quickly exit and free its memory.
1652 if (fatal_signal_pending(current) || current->flags & PF_EXITING) {
1653 set_thread_flag(TIF_MEMDIE);
1657 check_panic_on_oom(CONSTRAINT_MEMCG, gfp_mask, order, NULL);
1658 totalpages = mem_cgroup_get_limit(memcg) ? : 1;
1659 for_each_mem_cgroup_tree(iter, memcg) {
1660 struct css_task_iter it;
1661 struct task_struct *task;
1663 css_task_iter_start(&iter->css, &it);
1664 while ((task = css_task_iter_next(&it))) {
1665 switch (oom_scan_process_thread(task, totalpages, NULL,
1667 case OOM_SCAN_SELECT:
1669 put_task_struct(chosen);
1671 chosen_points = ULONG_MAX;
1672 get_task_struct(chosen);
1674 case OOM_SCAN_CONTINUE:
1676 case OOM_SCAN_ABORT:
1677 css_task_iter_end(&it);
1678 mem_cgroup_iter_break(memcg, iter);
1680 put_task_struct(chosen);
1685 points = oom_badness(task, memcg, NULL, totalpages);
1686 if (!points || points < chosen_points)
1688 /* Prefer thread group leaders for display purposes */
1689 if (points == chosen_points &&
1690 thread_group_leader(chosen))
1694 put_task_struct(chosen);
1696 chosen_points = points;
1697 get_task_struct(chosen);
1699 css_task_iter_end(&it);
1704 points = chosen_points * 1000 / totalpages;
1705 oom_kill_process(chosen, gfp_mask, order, points, totalpages, memcg,
1706 NULL, "Memory cgroup out of memory");
1710 * test_mem_cgroup_node_reclaimable
1711 * @memcg: the target memcg
1712 * @nid: the node ID to be checked.
1713 * @noswap : specify true here if the user wants flle only information.
1715 * This function returns whether the specified memcg contains any
1716 * reclaimable pages on a node. Returns true if there are any reclaimable
1717 * pages in the node.
1719 static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *memcg,
1720 int nid, bool noswap)
1722 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_FILE))
1724 if (noswap || !total_swap_pages)
1726 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_ANON))
1731 #if MAX_NUMNODES > 1
1734 * Always updating the nodemask is not very good - even if we have an empty
1735 * list or the wrong list here, we can start from some node and traverse all
1736 * nodes based on the zonelist. So update the list loosely once per 10 secs.
1739 static void mem_cgroup_may_update_nodemask(struct mem_cgroup *memcg)
1743 * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
1744 * pagein/pageout changes since the last update.
1746 if (!atomic_read(&memcg->numainfo_events))
1748 if (atomic_inc_return(&memcg->numainfo_updating) > 1)
1751 /* make a nodemask where this memcg uses memory from */
1752 memcg->scan_nodes = node_states[N_MEMORY];
1754 for_each_node_mask(nid, node_states[N_MEMORY]) {
1756 if (!test_mem_cgroup_node_reclaimable(memcg, nid, false))
1757 node_clear(nid, memcg->scan_nodes);
1760 atomic_set(&memcg->numainfo_events, 0);
1761 atomic_set(&memcg->numainfo_updating, 0);
1765 * Selecting a node where we start reclaim from. Because what we need is just
1766 * reducing usage counter, start from anywhere is O,K. Considering
1767 * memory reclaim from current node, there are pros. and cons.
1769 * Freeing memory from current node means freeing memory from a node which
1770 * we'll use or we've used. So, it may make LRU bad. And if several threads
1771 * hit limits, it will see a contention on a node. But freeing from remote
1772 * node means more costs for memory reclaim because of memory latency.
1774 * Now, we use round-robin. Better algorithm is welcomed.
1776 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1780 mem_cgroup_may_update_nodemask(memcg);
1781 node = memcg->last_scanned_node;
1783 node = next_node(node, memcg->scan_nodes);
1784 if (node == MAX_NUMNODES)
1785 node = first_node(memcg->scan_nodes);
1787 * We call this when we hit limit, not when pages are added to LRU.
1788 * No LRU may hold pages because all pages are UNEVICTABLE or
1789 * memcg is too small and all pages are not on LRU. In that case,
1790 * we use curret node.
1792 if (unlikely(node == MAX_NUMNODES))
1793 node = numa_node_id();
1795 memcg->last_scanned_node = node;
1800 * Check all nodes whether it contains reclaimable pages or not.
1801 * For quick scan, we make use of scan_nodes. This will allow us to skip
1802 * unused nodes. But scan_nodes is lazily updated and may not cotain
1803 * enough new information. We need to do double check.
1805 static bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
1810 * quick check...making use of scan_node.
1811 * We can skip unused nodes.
1813 if (!nodes_empty(memcg->scan_nodes)) {
1814 for (nid = first_node(memcg->scan_nodes);
1816 nid = next_node(nid, memcg->scan_nodes)) {
1818 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
1823 * Check rest of nodes.
1825 for_each_node_state(nid, N_MEMORY) {
1826 if (node_isset(nid, memcg->scan_nodes))
1828 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
1835 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1840 static bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
1842 return test_mem_cgroup_node_reclaimable(memcg, 0, noswap);
1846 static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
1849 unsigned long *total_scanned)
1851 struct mem_cgroup *victim = NULL;
1854 unsigned long excess;
1855 unsigned long nr_scanned;
1856 struct mem_cgroup_reclaim_cookie reclaim = {
1861 excess = soft_limit_excess(root_memcg);
1864 victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
1869 * If we have not been able to reclaim
1870 * anything, it might because there are
1871 * no reclaimable pages under this hierarchy
1876 * We want to do more targeted reclaim.
1877 * excess >> 2 is not to excessive so as to
1878 * reclaim too much, nor too less that we keep
1879 * coming back to reclaim from this cgroup
1881 if (total >= (excess >> 2) ||
1882 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
1887 if (!mem_cgroup_reclaimable(victim, false))
1889 total += mem_cgroup_shrink_node_zone(victim, gfp_mask, false,
1891 *total_scanned += nr_scanned;
1892 if (!soft_limit_excess(root_memcg))
1895 mem_cgroup_iter_break(root_memcg, victim);
1899 #ifdef CONFIG_LOCKDEP
1900 static struct lockdep_map memcg_oom_lock_dep_map = {
1901 .name = "memcg_oom_lock",
1905 static DEFINE_SPINLOCK(memcg_oom_lock);
1908 * Check OOM-Killer is already running under our hierarchy.
1909 * If someone is running, return false.
1911 static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
1913 struct mem_cgroup *iter, *failed = NULL;
1915 spin_lock(&memcg_oom_lock);
1917 for_each_mem_cgroup_tree(iter, memcg) {
1918 if (iter->oom_lock) {
1920 * this subtree of our hierarchy is already locked
1921 * so we cannot give a lock.
1924 mem_cgroup_iter_break(memcg, iter);
1927 iter->oom_lock = true;
1932 * OK, we failed to lock the whole subtree so we have
1933 * to clean up what we set up to the failing subtree
1935 for_each_mem_cgroup_tree(iter, memcg) {
1936 if (iter == failed) {
1937 mem_cgroup_iter_break(memcg, iter);
1940 iter->oom_lock = false;
1943 mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_);
1945 spin_unlock(&memcg_oom_lock);
1950 static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
1952 struct mem_cgroup *iter;
1954 spin_lock(&memcg_oom_lock);
1955 mutex_release(&memcg_oom_lock_dep_map, 1, _RET_IP_);
1956 for_each_mem_cgroup_tree(iter, memcg)
1957 iter->oom_lock = false;
1958 spin_unlock(&memcg_oom_lock);
1961 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
1963 struct mem_cgroup *iter;
1965 for_each_mem_cgroup_tree(iter, memcg)
1966 atomic_inc(&iter->under_oom);
1969 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
1971 struct mem_cgroup *iter;
1974 * When a new child is created while the hierarchy is under oom,
1975 * mem_cgroup_oom_lock() may not be called. We have to use
1976 * atomic_add_unless() here.
1978 for_each_mem_cgroup_tree(iter, memcg)
1979 atomic_add_unless(&iter->under_oom, -1, 0);
1982 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1984 struct oom_wait_info {
1985 struct mem_cgroup *memcg;
1989 static int memcg_oom_wake_function(wait_queue_t *wait,
1990 unsigned mode, int sync, void *arg)
1992 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
1993 struct mem_cgroup *oom_wait_memcg;
1994 struct oom_wait_info *oom_wait_info;
1996 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1997 oom_wait_memcg = oom_wait_info->memcg;
2000 * Both of oom_wait_info->memcg and wake_memcg are stable under us.
2001 * Then we can use css_is_ancestor without taking care of RCU.
2003 if (!mem_cgroup_same_or_subtree(oom_wait_memcg, wake_memcg)
2004 && !mem_cgroup_same_or_subtree(wake_memcg, oom_wait_memcg))
2006 return autoremove_wake_function(wait, mode, sync, arg);
2009 static void memcg_wakeup_oom(struct mem_cgroup *memcg)
2011 atomic_inc(&memcg->oom_wakeups);
2012 /* for filtering, pass "memcg" as argument. */
2013 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
2016 static void memcg_oom_recover(struct mem_cgroup *memcg)
2018 if (memcg && atomic_read(&memcg->under_oom))
2019 memcg_wakeup_oom(memcg);
2022 static void mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
2024 if (!current->memcg_oom.may_oom)
2027 * We are in the middle of the charge context here, so we
2028 * don't want to block when potentially sitting on a callstack
2029 * that holds all kinds of filesystem and mm locks.
2031 * Also, the caller may handle a failed allocation gracefully
2032 * (like optional page cache readahead) and so an OOM killer
2033 * invocation might not even be necessary.
2035 * That's why we don't do anything here except remember the
2036 * OOM context and then deal with it at the end of the page
2037 * fault when the stack is unwound, the locks are released,
2038 * and when we know whether the fault was overall successful.
2040 css_get(&memcg->css);
2041 current->memcg_oom.memcg = memcg;
2042 current->memcg_oom.gfp_mask = mask;
2043 current->memcg_oom.order = order;
2047 * mem_cgroup_oom_synchronize - complete memcg OOM handling
2048 * @handle: actually kill/wait or just clean up the OOM state
2050 * This has to be called at the end of a page fault if the memcg OOM
2051 * handler was enabled.
2053 * Memcg supports userspace OOM handling where failed allocations must
2054 * sleep on a waitqueue until the userspace task resolves the
2055 * situation. Sleeping directly in the charge context with all kinds
2056 * of locks held is not a good idea, instead we remember an OOM state
2057 * in the task and mem_cgroup_oom_synchronize() has to be called at
2058 * the end of the page fault to complete the OOM handling.
2060 * Returns %true if an ongoing memcg OOM situation was detected and
2061 * completed, %false otherwise.
2063 bool mem_cgroup_oom_synchronize(bool handle)
2065 struct mem_cgroup *memcg = current->memcg_oom.memcg;
2066 struct oom_wait_info owait;
2069 /* OOM is global, do not handle */
2076 owait.memcg = memcg;
2077 owait.wait.flags = 0;
2078 owait.wait.func = memcg_oom_wake_function;
2079 owait.wait.private = current;
2080 INIT_LIST_HEAD(&owait.wait.task_list);
2082 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
2083 mem_cgroup_mark_under_oom(memcg);
2085 locked = mem_cgroup_oom_trylock(memcg);
2088 mem_cgroup_oom_notify(memcg);
2090 if (locked && !memcg->oom_kill_disable) {
2091 mem_cgroup_unmark_under_oom(memcg);
2092 finish_wait(&memcg_oom_waitq, &owait.wait);
2093 mem_cgroup_out_of_memory(memcg, current->memcg_oom.gfp_mask,
2094 current->memcg_oom.order);
2097 mem_cgroup_unmark_under_oom(memcg);
2098 finish_wait(&memcg_oom_waitq, &owait.wait);
2102 mem_cgroup_oom_unlock(memcg);
2104 * There is no guarantee that an OOM-lock contender
2105 * sees the wakeups triggered by the OOM kill
2106 * uncharges. Wake any sleepers explicitely.
2108 memcg_oom_recover(memcg);
2111 current->memcg_oom.memcg = NULL;
2112 css_put(&memcg->css);
2117 * mem_cgroup_begin_page_stat - begin a page state statistics transaction
2118 * @page: page that is going to change accounted state
2119 * @locked: &memcg->move_lock slowpath was taken
2120 * @flags: IRQ-state flags for &memcg->move_lock
2122 * This function must mark the beginning of an accounted page state
2123 * change to prevent double accounting when the page is concurrently
2124 * being moved to another memcg:
2126 * memcg = mem_cgroup_begin_page_stat(page, &locked, &flags);
2127 * if (TestClearPageState(page))
2128 * mem_cgroup_update_page_stat(memcg, state, -1);
2129 * mem_cgroup_end_page_stat(memcg, locked, flags);
2131 * The RCU lock is held throughout the transaction. The fast path can
2132 * get away without acquiring the memcg->move_lock (@locked is false)
2133 * because page moving starts with an RCU grace period.
2135 * The RCU lock also protects the memcg from being freed when the page
2136 * state that is going to change is the only thing preventing the page
2137 * from being uncharged. E.g. end-writeback clearing PageWriteback(),
2138 * which allows migration to go ahead and uncharge the page before the
2139 * account transaction might be complete.
2141 struct mem_cgroup *mem_cgroup_begin_page_stat(struct page *page,
2143 unsigned long *flags)
2145 struct mem_cgroup *memcg;
2146 struct page_cgroup *pc;
2150 if (mem_cgroup_disabled())
2153 pc = lookup_page_cgroup(page);
2155 memcg = pc->mem_cgroup;
2156 if (unlikely(!memcg || !PageCgroupUsed(pc)))
2160 if (atomic_read(&memcg->moving_account) <= 0)
2163 move_lock_mem_cgroup(memcg, flags);
2164 if (memcg != pc->mem_cgroup || !PageCgroupUsed(pc)) {
2165 move_unlock_mem_cgroup(memcg, flags);
2174 * mem_cgroup_end_page_stat - finish a page state statistics transaction
2175 * @memcg: the memcg that was accounted against
2176 * @locked: value received from mem_cgroup_begin_page_stat()
2177 * @flags: value received from mem_cgroup_begin_page_stat()
2179 void mem_cgroup_end_page_stat(struct mem_cgroup *memcg, bool locked,
2180 unsigned long flags)
2182 if (memcg && locked)
2183 move_unlock_mem_cgroup(memcg, &flags);
2189 * mem_cgroup_update_page_stat - update page state statistics
2190 * @memcg: memcg to account against
2191 * @idx: page state item to account
2192 * @val: number of pages (positive or negative)
2194 * See mem_cgroup_begin_page_stat() for locking requirements.
2196 void mem_cgroup_update_page_stat(struct mem_cgroup *memcg,
2197 enum mem_cgroup_stat_index idx, int val)
2199 VM_BUG_ON(!rcu_read_lock_held());
2202 this_cpu_add(memcg->stat->count[idx], val);
2206 * size of first charge trial. "32" comes from vmscan.c's magic value.
2207 * TODO: maybe necessary to use big numbers in big irons.
2209 #define CHARGE_BATCH 32U
2210 struct memcg_stock_pcp {
2211 struct mem_cgroup *cached; /* this never be root cgroup */
2212 unsigned int nr_pages;
2213 struct work_struct work;
2214 unsigned long flags;
2215 #define FLUSHING_CACHED_CHARGE 0
2217 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
2218 static DEFINE_MUTEX(percpu_charge_mutex);
2221 * consume_stock: Try to consume stocked charge on this cpu.
2222 * @memcg: memcg to consume from.
2223 * @nr_pages: how many pages to charge.
2225 * The charges will only happen if @memcg matches the current cpu's memcg
2226 * stock, and at least @nr_pages are available in that stock. Failure to
2227 * service an allocation will refill the stock.
2229 * returns true if successful, false otherwise.
2231 static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2233 struct memcg_stock_pcp *stock;
2236 if (nr_pages > CHARGE_BATCH)
2239 stock = &get_cpu_var(memcg_stock);
2240 if (memcg == stock->cached && stock->nr_pages >= nr_pages) {
2241 stock->nr_pages -= nr_pages;
2244 put_cpu_var(memcg_stock);
2249 * Returns stocks cached in percpu and reset cached information.
2251 static void drain_stock(struct memcg_stock_pcp *stock)
2253 struct mem_cgroup *old = stock->cached;
2255 if (stock->nr_pages) {
2256 page_counter_uncharge(&old->memory, stock->nr_pages);
2257 if (do_swap_account)
2258 page_counter_uncharge(&old->memsw, stock->nr_pages);
2259 css_put_many(&old->css, stock->nr_pages);
2260 stock->nr_pages = 0;
2262 stock->cached = NULL;
2266 * This must be called under preempt disabled or must be called by
2267 * a thread which is pinned to local cpu.
2269 static void drain_local_stock(struct work_struct *dummy)
2271 struct memcg_stock_pcp *stock = this_cpu_ptr(&memcg_stock);
2273 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2276 static void __init memcg_stock_init(void)
2280 for_each_possible_cpu(cpu) {
2281 struct memcg_stock_pcp *stock =
2282 &per_cpu(memcg_stock, cpu);
2283 INIT_WORK(&stock->work, drain_local_stock);
2288 * Cache charges(val) to local per_cpu area.
2289 * This will be consumed by consume_stock() function, later.
2291 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2293 struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
2295 if (stock->cached != memcg) { /* reset if necessary */
2297 stock->cached = memcg;
2299 stock->nr_pages += nr_pages;
2300 put_cpu_var(memcg_stock);
2304 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2305 * of the hierarchy under it. sync flag says whether we should block
2306 * until the work is done.
2308 static void drain_all_stock(struct mem_cgroup *root_memcg, bool sync)
2312 /* Notify other cpus that system-wide "drain" is running */
2315 for_each_online_cpu(cpu) {
2316 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2317 struct mem_cgroup *memcg;
2319 memcg = stock->cached;
2320 if (!memcg || !stock->nr_pages)
2322 if (!mem_cgroup_same_or_subtree(root_memcg, memcg))
2324 if (!test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2326 drain_local_stock(&stock->work);
2328 schedule_work_on(cpu, &stock->work);
2336 for_each_online_cpu(cpu) {
2337 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2338 if (test_bit(FLUSHING_CACHED_CHARGE, &stock->flags))
2339 flush_work(&stock->work);
2346 * Tries to drain stocked charges in other cpus. This function is asynchronous
2347 * and just put a work per cpu for draining localy on each cpu. Caller can
2348 * expects some charges will be back later but cannot wait for it.
2350 static void drain_all_stock_async(struct mem_cgroup *root_memcg)
2353 * If someone calls draining, avoid adding more kworker runs.
2355 if (!mutex_trylock(&percpu_charge_mutex))
2357 drain_all_stock(root_memcg, false);
2358 mutex_unlock(&percpu_charge_mutex);
2361 /* This is a synchronous drain interface. */
2362 static void drain_all_stock_sync(struct mem_cgroup *root_memcg)
2364 /* called when force_empty is called */
2365 mutex_lock(&percpu_charge_mutex);
2366 drain_all_stock(root_memcg, true);
2367 mutex_unlock(&percpu_charge_mutex);
2371 * This function drains percpu counter value from DEAD cpu and
2372 * move it to local cpu. Note that this function can be preempted.
2374 static void mem_cgroup_drain_pcp_counter(struct mem_cgroup *memcg, int cpu)
2378 spin_lock(&memcg->pcp_counter_lock);
2379 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
2380 long x = per_cpu(memcg->stat->count[i], cpu);
2382 per_cpu(memcg->stat->count[i], cpu) = 0;
2383 memcg->nocpu_base.count[i] += x;
2385 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
2386 unsigned long x = per_cpu(memcg->stat->events[i], cpu);
2388 per_cpu(memcg->stat->events[i], cpu) = 0;
2389 memcg->nocpu_base.events[i] += x;
2391 spin_unlock(&memcg->pcp_counter_lock);
2394 static int memcg_cpu_hotplug_callback(struct notifier_block *nb,
2395 unsigned long action,
2398 int cpu = (unsigned long)hcpu;
2399 struct memcg_stock_pcp *stock;
2400 struct mem_cgroup *iter;
2402 if (action == CPU_ONLINE)
2405 if (action != CPU_DEAD && action != CPU_DEAD_FROZEN)
2408 for_each_mem_cgroup(iter)
2409 mem_cgroup_drain_pcp_counter(iter, cpu);
2411 stock = &per_cpu(memcg_stock, cpu);
2416 static int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2417 unsigned int nr_pages)
2419 unsigned int batch = max(CHARGE_BATCH, nr_pages);
2420 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
2421 struct mem_cgroup *mem_over_limit;
2422 struct page_counter *counter;
2423 unsigned long nr_reclaimed;
2424 bool may_swap = true;
2425 bool drained = false;
2428 if (mem_cgroup_is_root(memcg))
2431 if (consume_stock(memcg, nr_pages))
2434 if (!do_swap_account ||
2435 !page_counter_try_charge(&memcg->memsw, batch, &counter)) {
2436 if (!page_counter_try_charge(&memcg->memory, batch, &counter))
2438 if (do_swap_account)
2439 page_counter_uncharge(&memcg->memsw, batch);
2440 mem_over_limit = mem_cgroup_from_counter(counter, memory);
2442 mem_over_limit = mem_cgroup_from_counter(counter, memsw);
2446 if (batch > nr_pages) {
2452 * Unlike in global OOM situations, memcg is not in a physical
2453 * memory shortage. Allow dying and OOM-killed tasks to
2454 * bypass the last charges so that they can exit quickly and
2455 * free their memory.
2457 if (unlikely(test_thread_flag(TIF_MEMDIE) ||
2458 fatal_signal_pending(current) ||
2459 current->flags & PF_EXITING))
2462 if (unlikely(task_in_memcg_oom(current)))
2465 if (!(gfp_mask & __GFP_WAIT))
2468 nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
2469 gfp_mask, may_swap);
2471 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2475 drain_all_stock_async(mem_over_limit);
2480 if (gfp_mask & __GFP_NORETRY)
2483 * Even though the limit is exceeded at this point, reclaim
2484 * may have been able to free some pages. Retry the charge
2485 * before killing the task.
2487 * Only for regular pages, though: huge pages are rather
2488 * unlikely to succeed so close to the limit, and we fall back
2489 * to regular pages anyway in case of failure.
2491 if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
2494 * At task move, charge accounts can be doubly counted. So, it's
2495 * better to wait until the end of task_move if something is going on.
2497 if (mem_cgroup_wait_acct_move(mem_over_limit))
2503 if (gfp_mask & __GFP_NOFAIL)
2506 if (fatal_signal_pending(current))
2509 mem_cgroup_oom(mem_over_limit, gfp_mask, get_order(nr_pages));
2511 if (!(gfp_mask & __GFP_NOFAIL))
2517 css_get_many(&memcg->css, batch);
2518 if (batch > nr_pages)
2519 refill_stock(memcg, batch - nr_pages);
2524 static void cancel_charge(struct mem_cgroup *memcg, unsigned int nr_pages)
2526 if (mem_cgroup_is_root(memcg))
2529 page_counter_uncharge(&memcg->memory, nr_pages);
2530 if (do_swap_account)
2531 page_counter_uncharge(&memcg->memsw, nr_pages);
2533 css_put_many(&memcg->css, nr_pages);
2537 * A helper function to get mem_cgroup from ID. must be called under
2538 * rcu_read_lock(). The caller is responsible for calling
2539 * css_tryget_online() if the mem_cgroup is used for charging. (dropping
2540 * refcnt from swap can be called against removed memcg.)
2542 static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
2544 /* ID 0 is unused ID */
2547 return mem_cgroup_from_id(id);
2551 * try_get_mem_cgroup_from_page - look up page's memcg association
2554 * Look up, get a css reference, and return the memcg that owns @page.
2556 * The page must be locked to prevent racing with swap-in and page
2557 * cache charges. If coming from an unlocked page table, the caller
2558 * must ensure the page is on the LRU or this can race with charging.
2560 struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
2562 struct mem_cgroup *memcg = NULL;
2563 struct page_cgroup *pc;
2567 VM_BUG_ON_PAGE(!PageLocked(page), page);
2569 pc = lookup_page_cgroup(page);
2570 if (PageCgroupUsed(pc)) {
2571 memcg = pc->mem_cgroup;
2572 if (memcg && !css_tryget_online(&memcg->css))
2574 } else if (PageSwapCache(page)) {
2575 ent.val = page_private(page);
2576 id = lookup_swap_cgroup_id(ent);
2578 memcg = mem_cgroup_lookup(id);
2579 if (memcg && !css_tryget_online(&memcg->css))
2586 static void lock_page_lru(struct page *page, int *isolated)
2588 struct zone *zone = page_zone(page);
2590 spin_lock_irq(&zone->lru_lock);
2591 if (PageLRU(page)) {
2592 struct lruvec *lruvec;
2594 lruvec = mem_cgroup_page_lruvec(page, zone);
2596 del_page_from_lru_list(page, lruvec, page_lru(page));
2602 static void unlock_page_lru(struct page *page, int isolated)
2604 struct zone *zone = page_zone(page);
2607 struct lruvec *lruvec;
2609 lruvec = mem_cgroup_page_lruvec(page, zone);
2610 VM_BUG_ON_PAGE(PageLRU(page), page);
2612 add_page_to_lru_list(page, lruvec, page_lru(page));
2614 spin_unlock_irq(&zone->lru_lock);
2617 static void commit_charge(struct page *page, struct mem_cgroup *memcg,
2620 struct page_cgroup *pc = lookup_page_cgroup(page);
2623 VM_BUG_ON_PAGE(PageCgroupUsed(pc), page);
2625 * we don't need page_cgroup_lock about tail pages, becase they are not
2626 * accessed by any other context at this point.
2630 * In some cases, SwapCache and FUSE(splice_buf->radixtree), the page
2631 * may already be on some other mem_cgroup's LRU. Take care of it.
2634 lock_page_lru(page, &isolated);
2637 * Nobody should be changing or seriously looking at
2638 * pc->mem_cgroup and pc->flags at this point:
2640 * - the page is uncharged
2642 * - the page is off-LRU
2644 * - an anonymous fault has exclusive page access, except for
2645 * a locked page table
2647 * - a page cache insertion, a swapin fault, or a migration
2648 * have the page locked
2650 pc->mem_cgroup = memcg;
2651 pc->flags = PCG_USED | PCG_MEM | (do_swap_account ? PCG_MEMSW : 0);
2654 unlock_page_lru(page, isolated);
2657 #ifdef CONFIG_MEMCG_KMEM
2659 * The memcg_slab_mutex is held whenever a per memcg kmem cache is created or
2660 * destroyed. It protects memcg_caches arrays and memcg_slab_caches lists.
2662 static DEFINE_MUTEX(memcg_slab_mutex);
2664 static DEFINE_MUTEX(activate_kmem_mutex);
2667 * This is a bit cumbersome, but it is rarely used and avoids a backpointer
2668 * in the memcg_cache_params struct.
2670 static struct kmem_cache *memcg_params_to_cache(struct memcg_cache_params *p)
2672 struct kmem_cache *cachep;
2674 VM_BUG_ON(p->is_root_cache);
2675 cachep = p->root_cache;
2676 return cache_from_memcg_idx(cachep, memcg_cache_id(p->memcg));
2679 #ifdef CONFIG_SLABINFO
2680 static int mem_cgroup_slabinfo_read(struct seq_file *m, void *v)
2682 struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
2683 struct memcg_cache_params *params;
2685 if (!memcg_kmem_is_active(memcg))
2688 print_slabinfo_header(m);
2690 mutex_lock(&memcg_slab_mutex);
2691 list_for_each_entry(params, &memcg->memcg_slab_caches, list)
2692 cache_show(memcg_params_to_cache(params), m);
2693 mutex_unlock(&memcg_slab_mutex);
2699 static int memcg_charge_kmem(struct mem_cgroup *memcg, gfp_t gfp,
2700 unsigned long nr_pages)
2702 struct page_counter *counter;
2705 ret = page_counter_try_charge(&memcg->kmem, nr_pages, &counter);
2709 ret = try_charge(memcg, gfp, nr_pages);
2710 if (ret == -EINTR) {
2712 * try_charge() chose to bypass to root due to OOM kill or
2713 * fatal signal. Since our only options are to either fail
2714 * the allocation or charge it to this cgroup, do it as a
2715 * temporary condition. But we can't fail. From a kmem/slab
2716 * perspective, the cache has already been selected, by
2717 * mem_cgroup_kmem_get_cache(), so it is too late to change
2720 * This condition will only trigger if the task entered
2721 * memcg_charge_kmem in a sane state, but was OOM-killed
2722 * during try_charge() above. Tasks that were already dying
2723 * when the allocation triggers should have been already
2724 * directed to the root cgroup in memcontrol.h
2726 page_counter_charge(&memcg->memory, nr_pages);
2727 if (do_swap_account)
2728 page_counter_charge(&memcg->memsw, nr_pages);
2729 css_get_many(&memcg->css, nr_pages);
2732 page_counter_uncharge(&memcg->kmem, nr_pages);
2737 static void memcg_uncharge_kmem(struct mem_cgroup *memcg,
2738 unsigned long nr_pages)
2740 page_counter_uncharge(&memcg->memory, nr_pages);
2741 if (do_swap_account)
2742 page_counter_uncharge(&memcg->memsw, nr_pages);
2744 page_counter_uncharge(&memcg->kmem, nr_pages);
2746 css_put_many(&memcg->css, nr_pages);
2750 * helper for acessing a memcg's index. It will be used as an index in the
2751 * child cache array in kmem_cache, and also to derive its name. This function
2752 * will return -1 when this is not a kmem-limited memcg.
2754 int memcg_cache_id(struct mem_cgroup *memcg)
2756 return memcg ? memcg->kmemcg_id : -1;
2759 static int memcg_alloc_cache_id(void)
2764 id = ida_simple_get(&kmem_limited_groups,
2765 0, MEMCG_CACHES_MAX_SIZE, GFP_KERNEL);
2769 if (id < memcg_limited_groups_array_size)
2773 * There's no space for the new id in memcg_caches arrays,
2774 * so we have to grow them.
2777 size = 2 * (id + 1);
2778 if (size < MEMCG_CACHES_MIN_SIZE)
2779 size = MEMCG_CACHES_MIN_SIZE;
2780 else if (size > MEMCG_CACHES_MAX_SIZE)
2781 size = MEMCG_CACHES_MAX_SIZE;
2783 mutex_lock(&memcg_slab_mutex);
2784 err = memcg_update_all_caches(size);
2785 mutex_unlock(&memcg_slab_mutex);
2788 ida_simple_remove(&kmem_limited_groups, id);
2794 static void memcg_free_cache_id(int id)
2796 ida_simple_remove(&kmem_limited_groups, id);
2800 * We should update the current array size iff all caches updates succeed. This
2801 * can only be done from the slab side. The slab mutex needs to be held when
2804 void memcg_update_array_size(int num)
2806 memcg_limited_groups_array_size = num;
2809 static void memcg_register_cache(struct mem_cgroup *memcg,
2810 struct kmem_cache *root_cache)
2812 static char memcg_name_buf[NAME_MAX + 1]; /* protected by
2814 struct kmem_cache *cachep;
2817 lockdep_assert_held(&memcg_slab_mutex);
2819 id = memcg_cache_id(memcg);
2822 * Since per-memcg caches are created asynchronously on first
2823 * allocation (see memcg_kmem_get_cache()), several threads can try to
2824 * create the same cache, but only one of them may succeed.
2826 if (cache_from_memcg_idx(root_cache, id))
2829 cgroup_name(memcg->css.cgroup, memcg_name_buf, NAME_MAX + 1);
2830 cachep = memcg_create_kmem_cache(memcg, root_cache, memcg_name_buf);
2832 * If we could not create a memcg cache, do not complain, because
2833 * that's not critical at all as we can always proceed with the root
2839 css_get(&memcg->css);
2840 list_add(&cachep->memcg_params->list, &memcg->memcg_slab_caches);
2843 * Since readers won't lock (see cache_from_memcg_idx()), we need a
2844 * barrier here to ensure nobody will see the kmem_cache partially
2849 BUG_ON(root_cache->memcg_params->memcg_caches[id]);
2850 root_cache->memcg_params->memcg_caches[id] = cachep;
2853 static void memcg_unregister_cache(struct kmem_cache *cachep)
2855 struct kmem_cache *root_cache;
2856 struct mem_cgroup *memcg;
2859 lockdep_assert_held(&memcg_slab_mutex);
2861 BUG_ON(is_root_cache(cachep));
2863 root_cache = cachep->memcg_params->root_cache;
2864 memcg = cachep->memcg_params->memcg;
2865 id = memcg_cache_id(memcg);
2867 BUG_ON(root_cache->memcg_params->memcg_caches[id] != cachep);
2868 root_cache->memcg_params->memcg_caches[id] = NULL;
2870 list_del(&cachep->memcg_params->list);
2872 kmem_cache_destroy(cachep);
2874 /* drop the reference taken in memcg_register_cache */
2875 css_put(&memcg->css);
2879 * During the creation a new cache, we need to disable our accounting mechanism
2880 * altogether. This is true even if we are not creating, but rather just
2881 * enqueing new caches to be created.
2883 * This is because that process will trigger allocations; some visible, like
2884 * explicit kmallocs to auxiliary data structures, name strings and internal
2885 * cache structures; some well concealed, like INIT_WORK() that can allocate
2886 * objects during debug.
2888 * If any allocation happens during memcg_kmem_get_cache, we will recurse back
2889 * to it. This may not be a bounded recursion: since the first cache creation
2890 * failed to complete (waiting on the allocation), we'll just try to create the
2891 * cache again, failing at the same point.
2893 * memcg_kmem_get_cache is prepared to abort after seeing a positive count of
2894 * memcg_kmem_skip_account. So we enclose anything that might allocate memory
2895 * inside the following two functions.
2897 static inline void memcg_stop_kmem_account(void)
2899 VM_BUG_ON(!current->mm);
2900 current->memcg_kmem_skip_account++;
2903 static inline void memcg_resume_kmem_account(void)
2905 VM_BUG_ON(!current->mm);
2906 current->memcg_kmem_skip_account--;
2909 int __memcg_cleanup_cache_params(struct kmem_cache *s)
2911 struct kmem_cache *c;
2914 mutex_lock(&memcg_slab_mutex);
2915 for_each_memcg_cache_index(i) {
2916 c = cache_from_memcg_idx(s, i);
2920 memcg_unregister_cache(c);
2922 if (cache_from_memcg_idx(s, i))
2925 mutex_unlock(&memcg_slab_mutex);
2929 static void memcg_unregister_all_caches(struct mem_cgroup *memcg)
2931 struct kmem_cache *cachep;
2932 struct memcg_cache_params *params, *tmp;
2934 if (!memcg_kmem_is_active(memcg))
2937 mutex_lock(&memcg_slab_mutex);
2938 list_for_each_entry_safe(params, tmp, &memcg->memcg_slab_caches, list) {
2939 cachep = memcg_params_to_cache(params);
2940 kmem_cache_shrink(cachep);
2941 if (atomic_read(&cachep->memcg_params->nr_pages) == 0)
2942 memcg_unregister_cache(cachep);
2944 mutex_unlock(&memcg_slab_mutex);
2947 struct memcg_register_cache_work {
2948 struct mem_cgroup *memcg;
2949 struct kmem_cache *cachep;
2950 struct work_struct work;
2953 static void memcg_register_cache_func(struct work_struct *w)
2955 struct memcg_register_cache_work *cw =
2956 container_of(w, struct memcg_register_cache_work, work);
2957 struct mem_cgroup *memcg = cw->memcg;
2958 struct kmem_cache *cachep = cw->cachep;
2960 mutex_lock(&memcg_slab_mutex);
2961 memcg_register_cache(memcg, cachep);
2962 mutex_unlock(&memcg_slab_mutex);
2964 css_put(&memcg->css);
2969 * Enqueue the creation of a per-memcg kmem_cache.
2971 static void __memcg_schedule_register_cache(struct mem_cgroup *memcg,
2972 struct kmem_cache *cachep)
2974 struct memcg_register_cache_work *cw;
2976 cw = kmalloc(sizeof(*cw), GFP_NOWAIT);
2978 css_put(&memcg->css);
2983 cw->cachep = cachep;
2985 INIT_WORK(&cw->work, memcg_register_cache_func);
2986 schedule_work(&cw->work);
2989 static void memcg_schedule_register_cache(struct mem_cgroup *memcg,
2990 struct kmem_cache *cachep)
2993 * We need to stop accounting when we kmalloc, because if the
2994 * corresponding kmalloc cache is not yet created, the first allocation
2995 * in __memcg_schedule_register_cache will recurse.
2997 * However, it is better to enclose the whole function. Depending on
2998 * the debugging options enabled, INIT_WORK(), for instance, can
2999 * trigger an allocation. This too, will make us recurse. Because at
3000 * this point we can't allow ourselves back into memcg_kmem_get_cache,
3001 * the safest choice is to do it like this, wrapping the whole function.
3003 memcg_stop_kmem_account();
3004 __memcg_schedule_register_cache(memcg, cachep);
3005 memcg_resume_kmem_account();
3008 int __memcg_charge_slab(struct kmem_cache *cachep, gfp_t gfp, int order)
3010 unsigned int nr_pages = 1 << order;
3013 res = memcg_charge_kmem(cachep->memcg_params->memcg, gfp, nr_pages);
3015 atomic_add(nr_pages, &cachep->memcg_params->nr_pages);
3019 void __memcg_uncharge_slab(struct kmem_cache *cachep, int order)
3021 unsigned int nr_pages = 1 << order;
3023 memcg_uncharge_kmem(cachep->memcg_params->memcg, nr_pages);
3024 atomic_sub(nr_pages, &cachep->memcg_params->nr_pages);
3028 * Return the kmem_cache we're supposed to use for a slab allocation.
3029 * We try to use the current memcg's version of the cache.
3031 * If the cache does not exist yet, if we are the first user of it,
3032 * we either create it immediately, if possible, or create it asynchronously
3034 * In the latter case, we will let the current allocation go through with
3035 * the original cache.
3037 * Can't be called in interrupt context or from kernel threads.
3038 * This function needs to be called with rcu_read_lock() held.
3040 struct kmem_cache *__memcg_kmem_get_cache(struct kmem_cache *cachep,
3043 struct mem_cgroup *memcg;
3044 struct kmem_cache *memcg_cachep;
3046 VM_BUG_ON(!cachep->memcg_params);
3047 VM_BUG_ON(!cachep->memcg_params->is_root_cache);
3049 if (!current->mm || current->memcg_kmem_skip_account)
3053 memcg = mem_cgroup_from_task(rcu_dereference(current->mm->owner));
3055 if (!memcg_kmem_is_active(memcg))
3058 memcg_cachep = cache_from_memcg_idx(cachep, memcg_cache_id(memcg));
3059 if (likely(memcg_cachep)) {
3060 cachep = memcg_cachep;
3064 /* The corresponding put will be done in the workqueue. */
3065 if (!css_tryget_online(&memcg->css))
3070 * If we are in a safe context (can wait, and not in interrupt
3071 * context), we could be be predictable and return right away.
3072 * This would guarantee that the allocation being performed
3073 * already belongs in the new cache.
3075 * However, there are some clashes that can arrive from locking.
3076 * For instance, because we acquire the slab_mutex while doing
3077 * memcg_create_kmem_cache, this means no further allocation
3078 * could happen with the slab_mutex held. So it's better to
3081 memcg_schedule_register_cache(memcg, cachep);
3089 * We need to verify if the allocation against current->mm->owner's memcg is
3090 * possible for the given order. But the page is not allocated yet, so we'll
3091 * need a further commit step to do the final arrangements.
3093 * It is possible for the task to switch cgroups in this mean time, so at
3094 * commit time, we can't rely on task conversion any longer. We'll then use
3095 * the handle argument to return to the caller which cgroup we should commit
3096 * against. We could also return the memcg directly and avoid the pointer
3097 * passing, but a boolean return value gives better semantics considering
3098 * the compiled-out case as well.
3100 * Returning true means the allocation is possible.
3103 __memcg_kmem_newpage_charge(gfp_t gfp, struct mem_cgroup **_memcg, int order)
3105 struct mem_cgroup *memcg;
3111 * Disabling accounting is only relevant for some specific memcg
3112 * internal allocations. Therefore we would initially not have such
3113 * check here, since direct calls to the page allocator that are
3114 * accounted to kmemcg (alloc_kmem_pages and friends) only happen
3115 * outside memcg core. We are mostly concerned with cache allocations,
3116 * and by having this test at memcg_kmem_get_cache, we are already able
3117 * to relay the allocation to the root cache and bypass the memcg cache
3120 * There is one exception, though: the SLUB allocator does not create
3121 * large order caches, but rather service large kmallocs directly from
3122 * the page allocator. Therefore, the following sequence when backed by
3123 * the SLUB allocator:
3125 * memcg_stop_kmem_account();
3126 * kmalloc(<large_number>)
3127 * memcg_resume_kmem_account();
3129 * would effectively ignore the fact that we should skip accounting,
3130 * since it will drive us directly to this function without passing
3131 * through the cache selector memcg_kmem_get_cache. Such large
3132 * allocations are extremely rare but can happen, for instance, for the
3133 * cache arrays. We bring this test here.
3135 if (!current->mm || current->memcg_kmem_skip_account)
3138 memcg = get_mem_cgroup_from_mm(current->mm);
3140 if (!memcg_kmem_is_active(memcg)) {
3141 css_put(&memcg->css);
3145 ret = memcg_charge_kmem(memcg, gfp, 1 << order);
3149 css_put(&memcg->css);
3153 void __memcg_kmem_commit_charge(struct page *page, struct mem_cgroup *memcg,
3156 struct page_cgroup *pc;
3158 VM_BUG_ON(mem_cgroup_is_root(memcg));
3160 /* The page allocation failed. Revert */
3162 memcg_uncharge_kmem(memcg, 1 << order);
3166 * The page is freshly allocated and not visible to any
3167 * outside callers yet. Set up pc non-atomically.
3169 pc = lookup_page_cgroup(page);
3170 pc->mem_cgroup = memcg;
3171 pc->flags = PCG_USED;
3174 void __memcg_kmem_uncharge_pages(struct page *page, int order)
3176 struct mem_cgroup *memcg = NULL;
3177 struct page_cgroup *pc;
3180 pc = lookup_page_cgroup(page);
3181 if (!PageCgroupUsed(pc))
3184 memcg = pc->mem_cgroup;
3188 * We trust that only if there is a memcg associated with the page, it
3189 * is a valid allocation
3194 VM_BUG_ON_PAGE(mem_cgroup_is_root(memcg), page);
3195 memcg_uncharge_kmem(memcg, 1 << order);
3198 static inline void memcg_unregister_all_caches(struct mem_cgroup *memcg)
3201 #endif /* CONFIG_MEMCG_KMEM */
3203 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3206 * Because tail pages are not marked as "used", set it. We're under
3207 * zone->lru_lock, 'splitting on pmd' and compound_lock.
3208 * charge/uncharge will be never happen and move_account() is done under
3209 * compound_lock(), so we don't have to take care of races.
3211 void mem_cgroup_split_huge_fixup(struct page *head)
3213 struct page_cgroup *head_pc = lookup_page_cgroup(head);
3214 struct page_cgroup *pc;
3215 struct mem_cgroup *memcg;
3218 if (mem_cgroup_disabled())
3221 memcg = head_pc->mem_cgroup;
3222 for (i = 1; i < HPAGE_PMD_NR; i++) {
3224 pc->mem_cgroup = memcg;
3225 pc->flags = head_pc->flags;
3227 __this_cpu_sub(memcg->stat->count[MEM_CGROUP_STAT_RSS_HUGE],
3230 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
3233 * mem_cgroup_move_account - move account of the page
3235 * @nr_pages: number of regular pages (>1 for huge pages)
3236 * @pc: page_cgroup of the page.
3237 * @from: mem_cgroup which the page is moved from.
3238 * @to: mem_cgroup which the page is moved to. @from != @to.
3240 * The caller must confirm following.
3241 * - page is not on LRU (isolate_page() is useful.)
3242 * - compound_lock is held when nr_pages > 1
3244 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
3247 static int mem_cgroup_move_account(struct page *page,
3248 unsigned int nr_pages,
3249 struct page_cgroup *pc,
3250 struct mem_cgroup *from,
3251 struct mem_cgroup *to)
3253 unsigned long flags;
3256 VM_BUG_ON(from == to);
3257 VM_BUG_ON_PAGE(PageLRU(page), page);
3259 * The page is isolated from LRU. So, collapse function
3260 * will not handle this page. But page splitting can happen.
3261 * Do this check under compound_page_lock(). The caller should
3265 if (nr_pages > 1 && !PageTransHuge(page))
3269 * Prevent mem_cgroup_migrate() from looking at pc->mem_cgroup
3270 * of its source page while we change it: page migration takes
3271 * both pages off the LRU, but page cache replacement doesn't.
3273 if (!trylock_page(page))
3277 if (!PageCgroupUsed(pc) || pc->mem_cgroup != from)
3280 move_lock_mem_cgroup(from, &flags);
3282 if (!PageAnon(page) && page_mapped(page)) {
3283 __this_cpu_sub(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED],
3285 __this_cpu_add(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED],
3289 if (PageWriteback(page)) {
3290 __this_cpu_sub(from->stat->count[MEM_CGROUP_STAT_WRITEBACK],
3292 __this_cpu_add(to->stat->count[MEM_CGROUP_STAT_WRITEBACK],
3297 * It is safe to change pc->mem_cgroup here because the page
3298 * is referenced, charged, and isolated - we can't race with
3299 * uncharging, charging, migration, or LRU putback.
3302 /* caller should have done css_get */
3303 pc->mem_cgroup = to;
3304 move_unlock_mem_cgroup(from, &flags);
3307 local_irq_disable();
3308 mem_cgroup_charge_statistics(to, page, nr_pages);
3309 memcg_check_events(to, page);
3310 mem_cgroup_charge_statistics(from, page, -nr_pages);
3311 memcg_check_events(from, page);
3319 #ifdef CONFIG_MEMCG_SWAP
3320 static void mem_cgroup_swap_statistics(struct mem_cgroup *memcg,
3323 int val = (charge) ? 1 : -1;
3324 this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_SWAP], val);
3328 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3329 * @entry: swap entry to be moved
3330 * @from: mem_cgroup which the entry is moved from
3331 * @to: mem_cgroup which the entry is moved to
3333 * It succeeds only when the swap_cgroup's record for this entry is the same
3334 * as the mem_cgroup's id of @from.
3336 * Returns 0 on success, -EINVAL on failure.
3338 * The caller must have charged to @to, IOW, called page_counter_charge() about
3339 * both res and memsw, and called css_get().
3341 static int mem_cgroup_move_swap_account(swp_entry_t entry,
3342 struct mem_cgroup *from, struct mem_cgroup *to)
3344 unsigned short old_id, new_id;
3346 old_id = mem_cgroup_id(from);
3347 new_id = mem_cgroup_id(to);
3349 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
3350 mem_cgroup_swap_statistics(from, false);
3351 mem_cgroup_swap_statistics(to, true);
3353 * This function is only called from task migration context now.
3354 * It postpones page_counter and refcount handling till the end
3355 * of task migration(mem_cgroup_clear_mc()) for performance
3356 * improvement. But we cannot postpone css_get(to) because if
3357 * the process that has been moved to @to does swap-in, the
3358 * refcount of @to might be decreased to 0.
3360 * We are in attach() phase, so the cgroup is guaranteed to be
3361 * alive, so we can just call css_get().
3369 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
3370 struct mem_cgroup *from, struct mem_cgroup *to)
3376 #ifdef CONFIG_DEBUG_VM
3377 static struct page_cgroup *lookup_page_cgroup_used(struct page *page)
3379 struct page_cgroup *pc;
3381 pc = lookup_page_cgroup(page);
3383 * Can be NULL while feeding pages into the page allocator for
3384 * the first time, i.e. during boot or memory hotplug;
3385 * or when mem_cgroup_disabled().
3387 if (likely(pc) && PageCgroupUsed(pc))
3392 bool mem_cgroup_bad_page_check(struct page *page)
3394 if (mem_cgroup_disabled())
3397 return lookup_page_cgroup_used(page) != NULL;
3400 void mem_cgroup_print_bad_page(struct page *page)
3402 struct page_cgroup *pc;
3404 pc = lookup_page_cgroup_used(page);
3406 pr_alert("pc:%p pc->flags:%lx pc->mem_cgroup:%p\n",
3407 pc, pc->flags, pc->mem_cgroup);
3412 static DEFINE_MUTEX(memcg_limit_mutex);
3414 static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
3415 unsigned long limit)
3417 unsigned long curusage;
3418 unsigned long oldusage;
3419 bool enlarge = false;
3424 * For keeping hierarchical_reclaim simple, how long we should retry
3425 * is depends on callers. We set our retry-count to be function
3426 * of # of children which we should visit in this loop.
3428 retry_count = MEM_CGROUP_RECLAIM_RETRIES *
3429 mem_cgroup_count_children(memcg);
3431 oldusage = page_counter_read(&memcg->memory);
3434 if (signal_pending(current)) {
3439 mutex_lock(&memcg_limit_mutex);
3440 if (limit > memcg->memsw.limit) {
3441 mutex_unlock(&memcg_limit_mutex);
3445 if (limit > memcg->memory.limit)
3447 ret = page_counter_limit(&memcg->memory, limit);
3448 mutex_unlock(&memcg_limit_mutex);
3453 try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL, true);
3455 curusage = page_counter_read(&memcg->memory);
3456 /* Usage is reduced ? */
3457 if (curusage >= oldusage)
3460 oldusage = curusage;
3461 } while (retry_count);
3463 if (!ret && enlarge)
3464 memcg_oom_recover(memcg);
3469 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
3470 unsigned long limit)
3472 unsigned long curusage;
3473 unsigned long oldusage;
3474 bool enlarge = false;
3478 /* see mem_cgroup_resize_res_limit */
3479 retry_count = MEM_CGROUP_RECLAIM_RETRIES *
3480 mem_cgroup_count_children(memcg);
3482 oldusage = page_counter_read(&memcg->memsw);
3485 if (signal_pending(current)) {
3490 mutex_lock(&memcg_limit_mutex);
3491 if (limit < memcg->memory.limit) {
3492 mutex_unlock(&memcg_limit_mutex);
3496 if (limit > memcg->memsw.limit)
3498 ret = page_counter_limit(&memcg->memsw, limit);
3499 mutex_unlock(&memcg_limit_mutex);
3504 try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL, false);
3506 curusage = page_counter_read(&memcg->memsw);
3507 /* Usage is reduced ? */
3508 if (curusage >= oldusage)
3511 oldusage = curusage;
3512 } while (retry_count);
3514 if (!ret && enlarge)
3515 memcg_oom_recover(memcg);
3520 unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
3522 unsigned long *total_scanned)
3524 unsigned long nr_reclaimed = 0;
3525 struct mem_cgroup_per_zone *mz, *next_mz = NULL;
3526 unsigned long reclaimed;
3528 struct mem_cgroup_tree_per_zone *mctz;
3529 unsigned long excess;
3530 unsigned long nr_scanned;
3535 mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone));
3537 * This loop can run a while, specially if mem_cgroup's continuously
3538 * keep exceeding their soft limit and putting the system under
3545 mz = mem_cgroup_largest_soft_limit_node(mctz);
3550 reclaimed = mem_cgroup_soft_reclaim(mz->memcg, zone,
3551 gfp_mask, &nr_scanned);
3552 nr_reclaimed += reclaimed;
3553 *total_scanned += nr_scanned;
3554 spin_lock_irq(&mctz->lock);
3557 * If we failed to reclaim anything from this memory cgroup
3558 * it is time to move on to the next cgroup
3564 * Loop until we find yet another one.
3566 * By the time we get the soft_limit lock
3567 * again, someone might have aded the
3568 * group back on the RB tree. Iterate to
3569 * make sure we get a different mem.
3570 * mem_cgroup_largest_soft_limit_node returns
3571 * NULL if no other cgroup is present on
3575 __mem_cgroup_largest_soft_limit_node(mctz);
3577 css_put(&next_mz->memcg->css);
3578 else /* next_mz == NULL or other memcg */
3582 __mem_cgroup_remove_exceeded(mz, mctz);
3583 excess = soft_limit_excess(mz->memcg);
3585 * One school of thought says that we should not add
3586 * back the node to the tree if reclaim returns 0.
3587 * But our reclaim could return 0, simply because due
3588 * to priority we are exposing a smaller subset of
3589 * memory to reclaim from. Consider this as a longer
3592 /* If excess == 0, no tree ops */
3593 __mem_cgroup_insert_exceeded(mz, mctz, excess);
3594 spin_unlock_irq(&mctz->lock);
3595 css_put(&mz->memcg->css);
3598 * Could not reclaim anything and there are no more
3599 * mem cgroups to try or we seem to be looping without
3600 * reclaiming anything.
3602 if (!nr_reclaimed &&
3604 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3606 } while (!nr_reclaimed);
3608 css_put(&next_mz->memcg->css);
3609 return nr_reclaimed;
3613 * Test whether @memcg has children, dead or alive. Note that this
3614 * function doesn't care whether @memcg has use_hierarchy enabled and
3615 * returns %true if there are child csses according to the cgroup
3616 * hierarchy. Testing use_hierarchy is the caller's responsiblity.
3618 static inline bool memcg_has_children(struct mem_cgroup *memcg)
3623 * The lock does not prevent addition or deletion of children, but
3624 * it prevents a new child from being initialized based on this
3625 * parent in css_online(), so it's enough to decide whether
3626 * hierarchically inherited attributes can still be changed or not.
3628 lockdep_assert_held(&memcg_create_mutex);
3631 ret = css_next_child(NULL, &memcg->css);
3637 * Reclaims as many pages from the given memcg as possible and moves
3638 * the rest to the parent.
3640 * Caller is responsible for holding css reference for memcg.
3642 static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
3644 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
3646 /* we call try-to-free pages for make this cgroup empty */
3647 lru_add_drain_all();
3648 /* try to free all pages in this cgroup */
3649 while (nr_retries && page_counter_read(&memcg->memory)) {
3652 if (signal_pending(current))
3655 progress = try_to_free_mem_cgroup_pages(memcg, 1,
3659 /* maybe some writeback is necessary */
3660 congestion_wait(BLK_RW_ASYNC, HZ/10);
3668 static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
3669 char *buf, size_t nbytes,
3672 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3674 if (mem_cgroup_is_root(memcg))
3676 return mem_cgroup_force_empty(memcg) ?: nbytes;
3679 static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
3682 return mem_cgroup_from_css(css)->use_hierarchy;
3685 static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
3686 struct cftype *cft, u64 val)
3689 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3690 struct mem_cgroup *parent_memcg = mem_cgroup_from_css(memcg->css.parent);
3692 mutex_lock(&memcg_create_mutex);
3694 if (memcg->use_hierarchy == val)
3698 * If parent's use_hierarchy is set, we can't make any modifications
3699 * in the child subtrees. If it is unset, then the change can
3700 * occur, provided the current cgroup has no children.
3702 * For the root cgroup, parent_mem is NULL, we allow value to be
3703 * set if there are no children.
3705 if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
3706 (val == 1 || val == 0)) {
3707 if (!memcg_has_children(memcg))
3708 memcg->use_hierarchy = val;
3715 mutex_unlock(&memcg_create_mutex);
3720 static unsigned long tree_stat(struct mem_cgroup *memcg,
3721 enum mem_cgroup_stat_index idx)
3723 struct mem_cgroup *iter;
3726 /* Per-cpu values can be negative, use a signed accumulator */
3727 for_each_mem_cgroup_tree(iter, memcg)
3728 val += mem_cgroup_read_stat(iter, idx);
3730 if (val < 0) /* race ? */
3735 static inline u64 mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
3739 if (mem_cgroup_is_root(memcg)) {
3740 val = tree_stat(memcg, MEM_CGROUP_STAT_CACHE);
3741 val += tree_stat(memcg, MEM_CGROUP_STAT_RSS);
3743 val += tree_stat(memcg, MEM_CGROUP_STAT_SWAP);
3746 val = page_counter_read(&memcg->memory);
3748 val = page_counter_read(&memcg->memsw);
3750 return val << PAGE_SHIFT;
3761 static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
3764 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3765 struct page_counter *counter;
3767 switch (MEMFILE_TYPE(cft->private)) {
3769 counter = &memcg->memory;
3772 counter = &memcg->memsw;
3775 counter = &memcg->kmem;
3781 switch (MEMFILE_ATTR(cft->private)) {
3783 if (counter == &memcg->memory)
3784 return mem_cgroup_usage(memcg, false);
3785 if (counter == &memcg->memsw)
3786 return mem_cgroup_usage(memcg, true);
3787 return (u64)page_counter_read(counter) * PAGE_SIZE;
3789 return (u64)counter->limit * PAGE_SIZE;
3791 return (u64)counter->watermark * PAGE_SIZE;
3793 return counter->failcnt;
3794 case RES_SOFT_LIMIT:
3795 return (u64)memcg->soft_limit * PAGE_SIZE;
3801 #ifdef CONFIG_MEMCG_KMEM
3802 /* should be called with activate_kmem_mutex held */
3803 static int __memcg_activate_kmem(struct mem_cgroup *memcg,
3804 unsigned long nr_pages)
3809 if (memcg_kmem_is_active(memcg))
3813 * We are going to allocate memory for data shared by all memory
3814 * cgroups so let's stop accounting here.
3816 memcg_stop_kmem_account();
3819 * For simplicity, we won't allow this to be disabled. It also can't
3820 * be changed if the cgroup has children already, or if tasks had
3823 * If tasks join before we set the limit, a person looking at
3824 * kmem.usage_in_bytes will have no way to determine when it took
3825 * place, which makes the value quite meaningless.
3827 * After it first became limited, changes in the value of the limit are
3828 * of course permitted.
3830 mutex_lock(&memcg_create_mutex);
3831 if (cgroup_has_tasks(memcg->css.cgroup) ||
3832 (memcg->use_hierarchy && memcg_has_children(memcg)))
3834 mutex_unlock(&memcg_create_mutex);
3838 memcg_id = memcg_alloc_cache_id();
3844 memcg->kmemcg_id = memcg_id;
3845 INIT_LIST_HEAD(&memcg->memcg_slab_caches);
3848 * We couldn't have accounted to this cgroup, because it hasn't got the
3849 * active bit set yet, so this should succeed.
3851 err = page_counter_limit(&memcg->kmem, nr_pages);
3854 static_key_slow_inc(&memcg_kmem_enabled_key);
3856 * Setting the active bit after enabling static branching will
3857 * guarantee no one starts accounting before all call sites are
3860 memcg_kmem_set_active(memcg);
3862 memcg_resume_kmem_account();
3866 static int memcg_activate_kmem(struct mem_cgroup *memcg,
3867 unsigned long nr_pages)
3871 mutex_lock(&activate_kmem_mutex);
3872 ret = __memcg_activate_kmem(memcg, nr_pages);
3873 mutex_unlock(&activate_kmem_mutex);
3877 static int memcg_update_kmem_limit(struct mem_cgroup *memcg,
3878 unsigned long limit)
3882 mutex_lock(&memcg_limit_mutex);
3883 if (!memcg_kmem_is_active(memcg))
3884 ret = memcg_activate_kmem(memcg, limit);
3886 ret = page_counter_limit(&memcg->kmem, limit);
3887 mutex_unlock(&memcg_limit_mutex);
3891 static int memcg_propagate_kmem(struct mem_cgroup *memcg)
3894 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
3899 mutex_lock(&activate_kmem_mutex);
3901 * If the parent cgroup is not kmem-active now, it cannot be activated
3902 * after this point, because it has at least one child already.
3904 if (memcg_kmem_is_active(parent))
3905 ret = __memcg_activate_kmem(memcg, PAGE_COUNTER_MAX);
3906 mutex_unlock(&activate_kmem_mutex);
3910 static int memcg_update_kmem_limit(struct mem_cgroup *memcg,
3911 unsigned long limit)
3915 #endif /* CONFIG_MEMCG_KMEM */
3918 * The user of this function is...
3921 static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
3922 char *buf, size_t nbytes, loff_t off)
3924 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3925 unsigned long nr_pages;
3928 buf = strstrip(buf);
3929 ret = page_counter_memparse(buf, &nr_pages);
3933 switch (MEMFILE_ATTR(of_cft(of)->private)) {
3935 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3939 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3941 ret = mem_cgroup_resize_limit(memcg, nr_pages);
3944 ret = mem_cgroup_resize_memsw_limit(memcg, nr_pages);
3947 ret = memcg_update_kmem_limit(memcg, nr_pages);
3951 case RES_SOFT_LIMIT:
3952 memcg->soft_limit = nr_pages;
3956 return ret ?: nbytes;
3959 static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
3960 size_t nbytes, loff_t off)
3962 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3963 struct page_counter *counter;
3965 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3967 counter = &memcg->memory;
3970 counter = &memcg->memsw;
3973 counter = &memcg->kmem;
3979 switch (MEMFILE_ATTR(of_cft(of)->private)) {
3981 page_counter_reset_watermark(counter);
3984 counter->failcnt = 0;
3993 static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
3996 return mem_cgroup_from_css(css)->move_charge_at_immigrate;
4000 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
4001 struct cftype *cft, u64 val)
4003 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4005 if (val >= (1 << NR_MOVE_TYPE))
4009 * No kind of locking is needed in here, because ->can_attach() will
4010 * check this value once in the beginning of the process, and then carry
4011 * on with stale data. This means that changes to this value will only
4012 * affect task migrations starting after the change.
4014 memcg->move_charge_at_immigrate = val;
4018 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
4019 struct cftype *cft, u64 val)
4026 static int memcg_numa_stat_show(struct seq_file *m, void *v)
4030 unsigned int lru_mask;
4033 static const struct numa_stat stats[] = {
4034 { "total", LRU_ALL },
4035 { "file", LRU_ALL_FILE },
4036 { "anon", LRU_ALL_ANON },
4037 { "unevictable", BIT(LRU_UNEVICTABLE) },
4039 const struct numa_stat *stat;
4042 struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
4044 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
4045 nr = mem_cgroup_nr_lru_pages(memcg, stat->lru_mask);
4046 seq_printf(m, "%s=%lu", stat->name, nr);
4047 for_each_node_state(nid, N_MEMORY) {
4048 nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
4050 seq_printf(m, " N%d=%lu", nid, nr);
4055 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
4056 struct mem_cgroup *iter;
4059 for_each_mem_cgroup_tree(iter, memcg)
4060 nr += mem_cgroup_nr_lru_pages(iter, stat->lru_mask);
4061 seq_printf(m, "hierarchical_%s=%lu", stat->name, nr);
4062 for_each_node_state(nid, N_MEMORY) {
4064 for_each_mem_cgroup_tree(iter, memcg)
4065 nr += mem_cgroup_node_nr_lru_pages(
4066 iter, nid, stat->lru_mask);
4067 seq_printf(m, " N%d=%lu", nid, nr);
4074 #endif /* CONFIG_NUMA */
4076 static inline void mem_cgroup_lru_names_not_uptodate(void)
4078 BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_lru_names) != NR_LRU_LISTS);
4081 static int memcg_stat_show(struct seq_file *m, void *v)
4083 struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
4084 unsigned long memory, memsw;
4085 struct mem_cgroup *mi;
4088 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
4089 if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
4091 seq_printf(m, "%s %ld\n", mem_cgroup_stat_names[i],
4092 mem_cgroup_read_stat(memcg, i) * PAGE_SIZE);
4095 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++)
4096 seq_printf(m, "%s %lu\n", mem_cgroup_events_names[i],
4097 mem_cgroup_read_events(memcg, i));
4099 for (i = 0; i < NR_LRU_LISTS; i++)
4100 seq_printf(m, "%s %lu\n", mem_cgroup_lru_names[i],
4101 mem_cgroup_nr_lru_pages(memcg, BIT(i)) * PAGE_SIZE);
4103 /* Hierarchical information */
4104 memory = memsw = PAGE_COUNTER_MAX;
4105 for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
4106 memory = min(memory, mi->memory.limit);
4107 memsw = min(memsw, mi->memsw.limit);
4109 seq_printf(m, "hierarchical_memory_limit %llu\n",
4110 (u64)memory * PAGE_SIZE);
4111 if (do_swap_account)
4112 seq_printf(m, "hierarchical_memsw_limit %llu\n",
4113 (u64)memsw * PAGE_SIZE);
4115 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
4118 if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
4120 for_each_mem_cgroup_tree(mi, memcg)
4121 val += mem_cgroup_read_stat(mi, i) * PAGE_SIZE;
4122 seq_printf(m, "total_%s %lld\n", mem_cgroup_stat_names[i], val);
4125 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
4126 unsigned long long val = 0;
4128 for_each_mem_cgroup_tree(mi, memcg)
4129 val += mem_cgroup_read_events(mi, i);
4130 seq_printf(m, "total_%s %llu\n",
4131 mem_cgroup_events_names[i], val);
4134 for (i = 0; i < NR_LRU_LISTS; i++) {
4135 unsigned long long val = 0;
4137 for_each_mem_cgroup_tree(mi, memcg)
4138 val += mem_cgroup_nr_lru_pages(mi, BIT(i)) * PAGE_SIZE;
4139 seq_printf(m, "total_%s %llu\n", mem_cgroup_lru_names[i], val);
4142 #ifdef CONFIG_DEBUG_VM
4145 struct mem_cgroup_per_zone *mz;
4146 struct zone_reclaim_stat *rstat;
4147 unsigned long recent_rotated[2] = {0, 0};
4148 unsigned long recent_scanned[2] = {0, 0};
4150 for_each_online_node(nid)
4151 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
4152 mz = &memcg->nodeinfo[nid]->zoneinfo[zid];
4153 rstat = &mz->lruvec.reclaim_stat;
4155 recent_rotated[0] += rstat->recent_rotated[0];
4156 recent_rotated[1] += rstat->recent_rotated[1];
4157 recent_scanned[0] += rstat->recent_scanned[0];
4158 recent_scanned[1] += rstat->recent_scanned[1];
4160 seq_printf(m, "recent_rotated_anon %lu\n", recent_rotated[0]);
4161 seq_printf(m, "recent_rotated_file %lu\n", recent_rotated[1]);
4162 seq_printf(m, "recent_scanned_anon %lu\n", recent_scanned[0]);
4163 seq_printf(m, "recent_scanned_file %lu\n", recent_scanned[1]);
4170 static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
4173 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4175 return mem_cgroup_swappiness(memcg);
4178 static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
4179 struct cftype *cft, u64 val)
4181 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4187 memcg->swappiness = val;
4189 vm_swappiness = val;
4194 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4196 struct mem_cgroup_threshold_ary *t;
4197 unsigned long usage;
4202 t = rcu_dereference(memcg->thresholds.primary);
4204 t = rcu_dereference(memcg->memsw_thresholds.primary);
4209 usage = mem_cgroup_usage(memcg, swap);
4212 * current_threshold points to threshold just below or equal to usage.
4213 * If it's not true, a threshold was crossed after last
4214 * call of __mem_cgroup_threshold().
4216 i = t->current_threshold;
4219 * Iterate backward over array of thresholds starting from
4220 * current_threshold and check if a threshold is crossed.
4221 * If none of thresholds below usage is crossed, we read
4222 * only one element of the array here.
4224 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4225 eventfd_signal(t->entries[i].eventfd, 1);
4227 /* i = current_threshold + 1 */
4231 * Iterate forward over array of thresholds starting from
4232 * current_threshold+1 and check if a threshold is crossed.
4233 * If none of thresholds above usage is crossed, we read
4234 * only one element of the array here.
4236 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4237 eventfd_signal(t->entries[i].eventfd, 1);
4239 /* Update current_threshold */
4240 t->current_threshold = i - 1;
4245 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4248 __mem_cgroup_threshold(memcg, false);
4249 if (do_swap_account)
4250 __mem_cgroup_threshold(memcg, true);
4252 memcg = parent_mem_cgroup(memcg);
4256 static int compare_thresholds(const void *a, const void *b)
4258 const struct mem_cgroup_threshold *_a = a;
4259 const struct mem_cgroup_threshold *_b = b;
4261 if (_a->threshold > _b->threshold)
4264 if (_a->threshold < _b->threshold)
4270 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
4272 struct mem_cgroup_eventfd_list *ev;
4274 spin_lock(&memcg_oom_lock);
4276 list_for_each_entry(ev, &memcg->oom_notify, list)
4277 eventfd_signal(ev->eventfd, 1);
4279 spin_unlock(&memcg_oom_lock);
4283 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
4285 struct mem_cgroup *iter;
4287 for_each_mem_cgroup_tree(iter, memcg)
4288 mem_cgroup_oom_notify_cb(iter);
4291 static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4292 struct eventfd_ctx *eventfd, const char *args, enum res_type type)
4294 struct mem_cgroup_thresholds *thresholds;
4295 struct mem_cgroup_threshold_ary *new;
4296 unsigned long threshold;
4297 unsigned long usage;
4300 ret = page_counter_memparse(args, &threshold);
4304 mutex_lock(&memcg->thresholds_lock);
4307 thresholds = &memcg->thresholds;
4308 usage = mem_cgroup_usage(memcg, false);
4309 } else if (type == _MEMSWAP) {
4310 thresholds = &memcg->memsw_thresholds;
4311 usage = mem_cgroup_usage(memcg, true);
4315 /* Check if a threshold crossed before adding a new one */
4316 if (thresholds->primary)
4317 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4319 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
4321 /* Allocate memory for new array of thresholds */
4322 new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
4330 /* Copy thresholds (if any) to new array */
4331 if (thresholds->primary) {
4332 memcpy(new->entries, thresholds->primary->entries, (size - 1) *
4333 sizeof(struct mem_cgroup_threshold));
4336 /* Add new threshold */
4337 new->entries[size - 1].eventfd = eventfd;
4338 new->entries[size - 1].threshold = threshold;
4340 /* Sort thresholds. Registering of new threshold isn't time-critical */
4341 sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
4342 compare_thresholds, NULL);
4344 /* Find current threshold */
4345 new->current_threshold = -1;
4346 for (i = 0; i < size; i++) {
4347 if (new->entries[i].threshold <= usage) {
4349 * new->current_threshold will not be used until
4350 * rcu_assign_pointer(), so it's safe to increment
4353 ++new->current_threshold;
4358 /* Free old spare buffer and save old primary buffer as spare */
4359 kfree(thresholds->spare);
4360 thresholds->spare = thresholds->primary;
4362 rcu_assign_pointer(thresholds->primary, new);
4364 /* To be sure that nobody uses thresholds */
4368 mutex_unlock(&memcg->thresholds_lock);
4373 static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4374 struct eventfd_ctx *eventfd, const char *args)
4376 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
4379 static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
4380 struct eventfd_ctx *eventfd, const char *args)
4382 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
4385 static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4386 struct eventfd_ctx *eventfd, enum res_type type)
4388 struct mem_cgroup_thresholds *thresholds;
4389 struct mem_cgroup_threshold_ary *new;
4390 unsigned long usage;
4393 mutex_lock(&memcg->thresholds_lock);
4396 thresholds = &memcg->thresholds;
4397 usage = mem_cgroup_usage(memcg, false);
4398 } else if (type == _MEMSWAP) {
4399 thresholds = &memcg->memsw_thresholds;
4400 usage = mem_cgroup_usage(memcg, true);
4404 if (!thresholds->primary)
4407 /* Check if a threshold crossed before removing */
4408 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4410 /* Calculate new number of threshold */
4412 for (i = 0; i < thresholds->primary->size; i++) {
4413 if (thresholds->primary->entries[i].eventfd != eventfd)
4417 new = thresholds->spare;
4419 /* Set thresholds array to NULL if we don't have thresholds */
4428 /* Copy thresholds and find current threshold */
4429 new->current_threshold = -1;
4430 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4431 if (thresholds->primary->entries[i].eventfd == eventfd)
4434 new->entries[j] = thresholds->primary->entries[i];
4435 if (new->entries[j].threshold <= usage) {
4437 * new->current_threshold will not be used
4438 * until rcu_assign_pointer(), so it's safe to increment
4441 ++new->current_threshold;
4447 /* Swap primary and spare array */
4448 thresholds->spare = thresholds->primary;
4449 /* If all events are unregistered, free the spare array */
4451 kfree(thresholds->spare);
4452 thresholds->spare = NULL;
4455 rcu_assign_pointer(thresholds->primary, new);
4457 /* To be sure that nobody uses thresholds */
4460 mutex_unlock(&memcg->thresholds_lock);
4463 static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4464 struct eventfd_ctx *eventfd)
4466 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
4469 static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4470 struct eventfd_ctx *eventfd)
4472 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
4475 static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
4476 struct eventfd_ctx *eventfd, const char *args)
4478 struct mem_cgroup_eventfd_list *event;
4480 event = kmalloc(sizeof(*event), GFP_KERNEL);
4484 spin_lock(&memcg_oom_lock);
4486 event->eventfd = eventfd;
4487 list_add(&event->list, &memcg->oom_notify);
4489 /* already in OOM ? */
4490 if (atomic_read(&memcg->under_oom))
4491 eventfd_signal(eventfd, 1);
4492 spin_unlock(&memcg_oom_lock);
4497 static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
4498 struct eventfd_ctx *eventfd)
4500 struct mem_cgroup_eventfd_list *ev, *tmp;
4502 spin_lock(&memcg_oom_lock);
4504 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
4505 if (ev->eventfd == eventfd) {
4506 list_del(&ev->list);
4511 spin_unlock(&memcg_oom_lock);
4514 static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
4516 struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(sf));
4518 seq_printf(sf, "oom_kill_disable %d\n", memcg->oom_kill_disable);
4519 seq_printf(sf, "under_oom %d\n", (bool)atomic_read(&memcg->under_oom));
4523 static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
4524 struct cftype *cft, u64 val)
4526 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4528 /* cannot set to root cgroup and only 0 and 1 are allowed */
4529 if (!css->parent || !((val == 0) || (val == 1)))
4532 memcg->oom_kill_disable = val;
4534 memcg_oom_recover(memcg);
4539 #ifdef CONFIG_MEMCG_KMEM
4540 static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
4544 memcg->kmemcg_id = -1;
4545 ret = memcg_propagate_kmem(memcg);
4549 return mem_cgroup_sockets_init(memcg, ss);
4552 static void memcg_destroy_kmem(struct mem_cgroup *memcg)
4554 mem_cgroup_sockets_destroy(memcg);
4557 static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
4562 static void memcg_destroy_kmem(struct mem_cgroup *memcg)
4568 * DO NOT USE IN NEW FILES.
4570 * "cgroup.event_control" implementation.
4572 * This is way over-engineered. It tries to support fully configurable
4573 * events for each user. Such level of flexibility is completely
4574 * unnecessary especially in the light of the planned unified hierarchy.
4576 * Please deprecate this and replace with something simpler if at all
4581 * Unregister event and free resources.
4583 * Gets called from workqueue.
4585 static void memcg_event_remove(struct work_struct *work)
4587 struct mem_cgroup_event *event =
4588 container_of(work, struct mem_cgroup_event, remove);
4589 struct mem_cgroup *memcg = event->memcg;
4591 remove_wait_queue(event->wqh, &event->wait);
4593 event->unregister_event(memcg, event->eventfd);
4595 /* Notify userspace the event is going away. */
4596 eventfd_signal(event->eventfd, 1);
4598 eventfd_ctx_put(event->eventfd);
4600 css_put(&memcg->css);
4604 * Gets called on POLLHUP on eventfd when user closes it.
4606 * Called with wqh->lock held and interrupts disabled.
4608 static int memcg_event_wake(wait_queue_t *wait, unsigned mode,
4609 int sync, void *key)
4611 struct mem_cgroup_event *event =
4612 container_of(wait, struct mem_cgroup_event, wait);
4613 struct mem_cgroup *memcg = event->memcg;
4614 unsigned long flags = (unsigned long)key;
4616 if (flags & POLLHUP) {
4618 * If the event has been detached at cgroup removal, we
4619 * can simply return knowing the other side will cleanup
4622 * We can't race against event freeing since the other
4623 * side will require wqh->lock via remove_wait_queue(),
4626 spin_lock(&memcg->event_list_lock);
4627 if (!list_empty(&event->list)) {
4628 list_del_init(&event->list);
4630 * We are in atomic context, but cgroup_event_remove()
4631 * may sleep, so we have to call it in workqueue.
4633 schedule_work(&event->remove);
4635 spin_unlock(&memcg->event_list_lock);
4641 static void memcg_event_ptable_queue_proc(struct file *file,
4642 wait_queue_head_t *wqh, poll_table *pt)
4644 struct mem_cgroup_event *event =
4645 container_of(pt, struct mem_cgroup_event, pt);
4648 add_wait_queue(wqh, &event->wait);
4652 * DO NOT USE IN NEW FILES.
4654 * Parse input and register new cgroup event handler.
4656 * Input must be in format '<event_fd> <control_fd> <args>'.
4657 * Interpretation of args is defined by control file implementation.
4659 static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
4660 char *buf, size_t nbytes, loff_t off)
4662 struct cgroup_subsys_state *css = of_css(of);
4663 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4664 struct mem_cgroup_event *event;
4665 struct cgroup_subsys_state *cfile_css;
4666 unsigned int efd, cfd;
4673 buf = strstrip(buf);
4675 efd = simple_strtoul(buf, &endp, 10);
4680 cfd = simple_strtoul(buf, &endp, 10);
4681 if ((*endp != ' ') && (*endp != '\0'))
4685 event = kzalloc(sizeof(*event), GFP_KERNEL);
4689 event->memcg = memcg;
4690 INIT_LIST_HEAD(&event->list);
4691 init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
4692 init_waitqueue_func_entry(&event->wait, memcg_event_wake);
4693 INIT_WORK(&event->remove, memcg_event_remove);
4701 event->eventfd = eventfd_ctx_fileget(efile.file);
4702 if (IS_ERR(event->eventfd)) {
4703 ret = PTR_ERR(event->eventfd);
4710 goto out_put_eventfd;
4713 /* the process need read permission on control file */
4714 /* AV: shouldn't we check that it's been opened for read instead? */
4715 ret = inode_permission(file_inode(cfile.file), MAY_READ);
4720 * Determine the event callbacks and set them in @event. This used
4721 * to be done via struct cftype but cgroup core no longer knows
4722 * about these events. The following is crude but the whole thing
4723 * is for compatibility anyway.
4725 * DO NOT ADD NEW FILES.
4727 name = cfile.file->f_dentry->d_name.name;
4729 if (!strcmp(name, "memory.usage_in_bytes")) {
4730 event->register_event = mem_cgroup_usage_register_event;
4731 event->unregister_event = mem_cgroup_usage_unregister_event;
4732 } else if (!strcmp(name, "memory.oom_control")) {
4733 event->register_event = mem_cgroup_oom_register_event;
4734 event->unregister_event = mem_cgroup_oom_unregister_event;
4735 } else if (!strcmp(name, "memory.pressure_level")) {
4736 event->register_event = vmpressure_register_event;
4737 event->unregister_event = vmpressure_unregister_event;
4738 } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
4739 event->register_event = memsw_cgroup_usage_register_event;
4740 event->unregister_event = memsw_cgroup_usage_unregister_event;
4747 * Verify @cfile should belong to @css. Also, remaining events are
4748 * automatically removed on cgroup destruction but the removal is
4749 * asynchronous, so take an extra ref on @css.
4751 cfile_css = css_tryget_online_from_dir(cfile.file->f_dentry->d_parent,
4752 &memory_cgrp_subsys);
4754 if (IS_ERR(cfile_css))
4756 if (cfile_css != css) {
4761 ret = event->register_event(memcg, event->eventfd, buf);
4765 efile.file->f_op->poll(efile.file, &event->pt);
4767 spin_lock(&memcg->event_list_lock);
4768 list_add(&event->list, &memcg->event_list);
4769 spin_unlock(&memcg->event_list_lock);
4781 eventfd_ctx_put(event->eventfd);
4790 static struct cftype mem_cgroup_files[] = {
4792 .name = "usage_in_bytes",
4793 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
4794 .read_u64 = mem_cgroup_read_u64,
4797 .name = "max_usage_in_bytes",
4798 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
4799 .write = mem_cgroup_reset,
4800 .read_u64 = mem_cgroup_read_u64,
4803 .name = "limit_in_bytes",
4804 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
4805 .write = mem_cgroup_write,
4806 .read_u64 = mem_cgroup_read_u64,
4809 .name = "soft_limit_in_bytes",
4810 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
4811 .write = mem_cgroup_write,
4812 .read_u64 = mem_cgroup_read_u64,
4816 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
4817 .write = mem_cgroup_reset,
4818 .read_u64 = mem_cgroup_read_u64,
4822 .seq_show = memcg_stat_show,
4825 .name = "force_empty",
4826 .write = mem_cgroup_force_empty_write,
4829 .name = "use_hierarchy",
4830 .write_u64 = mem_cgroup_hierarchy_write,
4831 .read_u64 = mem_cgroup_hierarchy_read,
4834 .name = "cgroup.event_control", /* XXX: for compat */
4835 .write = memcg_write_event_control,
4836 .flags = CFTYPE_NO_PREFIX,
4840 .name = "swappiness",
4841 .read_u64 = mem_cgroup_swappiness_read,
4842 .write_u64 = mem_cgroup_swappiness_write,
4845 .name = "move_charge_at_immigrate",
4846 .read_u64 = mem_cgroup_move_charge_read,
4847 .write_u64 = mem_cgroup_move_charge_write,
4850 .name = "oom_control",
4851 .seq_show = mem_cgroup_oom_control_read,
4852 .write_u64 = mem_cgroup_oom_control_write,
4853 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
4856 .name = "pressure_level",
4860 .name = "numa_stat",
4861 .seq_show = memcg_numa_stat_show,
4864 #ifdef CONFIG_MEMCG_KMEM
4866 .name = "kmem.limit_in_bytes",
4867 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
4868 .write = mem_cgroup_write,
4869 .read_u64 = mem_cgroup_read_u64,
4872 .name = "kmem.usage_in_bytes",
4873 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
4874 .read_u64 = mem_cgroup_read_u64,
4877 .name = "kmem.failcnt",
4878 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
4879 .write = mem_cgroup_reset,
4880 .read_u64 = mem_cgroup_read_u64,
4883 .name = "kmem.max_usage_in_bytes",
4884 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
4885 .write = mem_cgroup_reset,
4886 .read_u64 = mem_cgroup_read_u64,
4888 #ifdef CONFIG_SLABINFO
4890 .name = "kmem.slabinfo",
4891 .seq_show = mem_cgroup_slabinfo_read,
4895 { }, /* terminate */
4898 #ifdef CONFIG_MEMCG_SWAP
4899 static struct cftype memsw_cgroup_files[] = {
4901 .name = "memsw.usage_in_bytes",
4902 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
4903 .read_u64 = mem_cgroup_read_u64,
4906 .name = "memsw.max_usage_in_bytes",
4907 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
4908 .write = mem_cgroup_reset,
4909 .read_u64 = mem_cgroup_read_u64,
4912 .name = "memsw.limit_in_bytes",
4913 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
4914 .write = mem_cgroup_write,
4915 .read_u64 = mem_cgroup_read_u64,
4918 .name = "memsw.failcnt",
4919 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
4920 .write = mem_cgroup_reset,
4921 .read_u64 = mem_cgroup_read_u64,
4923 { }, /* terminate */
4926 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
4928 struct mem_cgroup_per_node *pn;
4929 struct mem_cgroup_per_zone *mz;
4930 int zone, tmp = node;
4932 * This routine is called against possible nodes.
4933 * But it's BUG to call kmalloc() against offline node.
4935 * TODO: this routine can waste much memory for nodes which will
4936 * never be onlined. It's better to use memory hotplug callback
4939 if (!node_state(node, N_NORMAL_MEMORY))
4941 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
4945 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4946 mz = &pn->zoneinfo[zone];
4947 lruvec_init(&mz->lruvec);
4948 mz->usage_in_excess = 0;
4949 mz->on_tree = false;
4952 memcg->nodeinfo[node] = pn;
4956 static void free_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
4958 kfree(memcg->nodeinfo[node]);
4961 static struct mem_cgroup *mem_cgroup_alloc(void)
4963 struct mem_cgroup *memcg;
4966 size = sizeof(struct mem_cgroup);
4967 size += nr_node_ids * sizeof(struct mem_cgroup_per_node *);
4969 memcg = kzalloc(size, GFP_KERNEL);
4973 memcg->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
4976 spin_lock_init(&memcg->pcp_counter_lock);
4985 * At destroying mem_cgroup, references from swap_cgroup can remain.
4986 * (scanning all at force_empty is too costly...)
4988 * Instead of clearing all references at force_empty, we remember
4989 * the number of reference from swap_cgroup and free mem_cgroup when
4990 * it goes down to 0.
4992 * Removal of cgroup itself succeeds regardless of refs from swap.
4995 static void __mem_cgroup_free(struct mem_cgroup *memcg)
4999 mem_cgroup_remove_from_trees(memcg);
5002 free_mem_cgroup_per_zone_info(memcg, node);
5004 free_percpu(memcg->stat);
5007 * We need to make sure that (at least for now), the jump label
5008 * destruction code runs outside of the cgroup lock. This is because
5009 * get_online_cpus(), which is called from the static_branch update,
5010 * can't be called inside the cgroup_lock. cpusets are the ones
5011 * enforcing this dependency, so if they ever change, we might as well.
5013 * schedule_work() will guarantee this happens. Be careful if you need
5014 * to move this code around, and make sure it is outside
5017 disarm_static_keys(memcg);
5022 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
5024 struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg)
5026 if (!memcg->memory.parent)
5028 return mem_cgroup_from_counter(memcg->memory.parent, memory);
5030 EXPORT_SYMBOL(parent_mem_cgroup);
5032 static void __init mem_cgroup_soft_limit_tree_init(void)
5034 struct mem_cgroup_tree_per_node *rtpn;
5035 struct mem_cgroup_tree_per_zone *rtpz;
5036 int tmp, node, zone;
5038 for_each_node(node) {
5040 if (!node_state(node, N_NORMAL_MEMORY))
5042 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
5045 soft_limit_tree.rb_tree_per_node[node] = rtpn;
5047 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
5048 rtpz = &rtpn->rb_tree_per_zone[zone];
5049 rtpz->rb_root = RB_ROOT;
5050 spin_lock_init(&rtpz->lock);
5055 static struct cgroup_subsys_state * __ref
5056 mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
5058 struct mem_cgroup *memcg;
5059 long error = -ENOMEM;
5062 memcg = mem_cgroup_alloc();
5064 return ERR_PTR(error);
5067 if (alloc_mem_cgroup_per_zone_info(memcg, node))
5071 if (parent_css == NULL) {
5072 root_mem_cgroup = memcg;
5073 page_counter_init(&memcg->memory, NULL);
5074 page_counter_init(&memcg->memsw, NULL);
5075 page_counter_init(&memcg->kmem, NULL);
5078 memcg->last_scanned_node = MAX_NUMNODES;
5079 INIT_LIST_HEAD(&memcg->oom_notify);
5080 memcg->move_charge_at_immigrate = 0;
5081 mutex_init(&memcg->thresholds_lock);
5082 spin_lock_init(&memcg->move_lock);
5083 vmpressure_init(&memcg->vmpressure);
5084 INIT_LIST_HEAD(&memcg->event_list);
5085 spin_lock_init(&memcg->event_list_lock);
5090 __mem_cgroup_free(memcg);
5091 return ERR_PTR(error);
5095 mem_cgroup_css_online(struct cgroup_subsys_state *css)
5097 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5098 struct mem_cgroup *parent = mem_cgroup_from_css(css->parent);
5101 if (css->id > MEM_CGROUP_ID_MAX)
5107 mutex_lock(&memcg_create_mutex);
5109 memcg->use_hierarchy = parent->use_hierarchy;
5110 memcg->oom_kill_disable = parent->oom_kill_disable;
5111 memcg->swappiness = mem_cgroup_swappiness(parent);
5113 if (parent->use_hierarchy) {
5114 page_counter_init(&memcg->memory, &parent->memory);
5115 page_counter_init(&memcg->memsw, &parent->memsw);
5116 page_counter_init(&memcg->kmem, &parent->kmem);
5119 * No need to take a reference to the parent because cgroup
5120 * core guarantees its existence.
5123 page_counter_init(&memcg->memory, NULL);
5124 page_counter_init(&memcg->memsw, NULL);
5125 page_counter_init(&memcg->kmem, NULL);
5127 * Deeper hierachy with use_hierarchy == false doesn't make
5128 * much sense so let cgroup subsystem know about this
5129 * unfortunate state in our controller.
5131 if (parent != root_mem_cgroup)
5132 memory_cgrp_subsys.broken_hierarchy = true;
5134 mutex_unlock(&memcg_create_mutex);
5136 ret = memcg_init_kmem(memcg, &memory_cgrp_subsys);
5141 * Make sure the memcg is initialized: mem_cgroup_iter()
5142 * orders reading memcg->initialized against its callers
5143 * reading the memcg members.
5145 smp_store_release(&memcg->initialized, 1);
5150 static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
5152 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5153 struct mem_cgroup_event *event, *tmp;
5156 * Unregister events and notify userspace.
5157 * Notify userspace about cgroup removing only after rmdir of cgroup
5158 * directory to avoid race between userspace and kernelspace.
5160 spin_lock(&memcg->event_list_lock);
5161 list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
5162 list_del_init(&event->list);
5163 schedule_work(&event->remove);
5165 spin_unlock(&memcg->event_list_lock);
5167 memcg_unregister_all_caches(memcg);
5168 vmpressure_cleanup(&memcg->vmpressure);
5171 static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
5173 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5175 memcg_destroy_kmem(memcg);
5176 __mem_cgroup_free(memcg);
5180 * mem_cgroup_css_reset - reset the states of a mem_cgroup
5181 * @css: the target css
5183 * Reset the states of the mem_cgroup associated with @css. This is
5184 * invoked when the userland requests disabling on the default hierarchy
5185 * but the memcg is pinned through dependency. The memcg should stop
5186 * applying policies and should revert to the vanilla state as it may be
5187 * made visible again.
5189 * The current implementation only resets the essential configurations.
5190 * This needs to be expanded to cover all the visible parts.
5192 static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
5194 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5196 mem_cgroup_resize_limit(memcg, PAGE_COUNTER_MAX);
5197 mem_cgroup_resize_memsw_limit(memcg, PAGE_COUNTER_MAX);
5198 memcg_update_kmem_limit(memcg, PAGE_COUNTER_MAX);
5199 memcg->soft_limit = 0;
5203 /* Handlers for move charge at task migration. */
5204 static int mem_cgroup_do_precharge(unsigned long count)
5208 /* Try a single bulk charge without reclaim first */
5209 ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_WAIT, count);
5211 mc.precharge += count;
5214 if (ret == -EINTR) {
5215 cancel_charge(root_mem_cgroup, count);
5219 /* Try charges one by one with reclaim */
5221 ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_NORETRY, 1);
5223 * In case of failure, any residual charges against
5224 * mc.to will be dropped by mem_cgroup_clear_mc()
5225 * later on. However, cancel any charges that are
5226 * bypassed to root right away or they'll be lost.
5229 cancel_charge(root_mem_cgroup, 1);
5239 * get_mctgt_type - get target type of moving charge
5240 * @vma: the vma the pte to be checked belongs
5241 * @addr: the address corresponding to the pte to be checked
5242 * @ptent: the pte to be checked
5243 * @target: the pointer the target page or swap ent will be stored(can be NULL)
5246 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
5247 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5248 * move charge. if @target is not NULL, the page is stored in target->page
5249 * with extra refcnt got(Callers should handle it).
5250 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5251 * target for charge migration. if @target is not NULL, the entry is stored
5254 * Called with pte lock held.
5261 enum mc_target_type {
5267 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5268 unsigned long addr, pte_t ptent)
5270 struct page *page = vm_normal_page(vma, addr, ptent);
5272 if (!page || !page_mapped(page))
5274 if (PageAnon(page)) {
5275 /* we don't move shared anon */
5278 } else if (!move_file())
5279 /* we ignore mapcount for file pages */
5281 if (!get_page_unless_zero(page))
5288 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5289 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5291 struct page *page = NULL;
5292 swp_entry_t ent = pte_to_swp_entry(ptent);
5294 if (!move_anon() || non_swap_entry(ent))
5297 * Because lookup_swap_cache() updates some statistics counter,
5298 * we call find_get_page() with swapper_space directly.
5300 page = find_get_page(swap_address_space(ent), ent.val);
5301 if (do_swap_account)
5302 entry->val = ent.val;
5307 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5308 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5314 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5315 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5317 struct page *page = NULL;
5318 struct address_space *mapping;
5321 if (!vma->vm_file) /* anonymous vma */
5326 mapping = vma->vm_file->f_mapping;
5327 if (pte_none(ptent))
5328 pgoff = linear_page_index(vma, addr);
5329 else /* pte_file(ptent) is true */
5330 pgoff = pte_to_pgoff(ptent);
5332 /* page is moved even if it's not RSS of this task(page-faulted). */
5334 /* shmem/tmpfs may report page out on swap: account for that too. */
5335 if (shmem_mapping(mapping)) {
5336 page = find_get_entry(mapping, pgoff);
5337 if (radix_tree_exceptional_entry(page)) {
5338 swp_entry_t swp = radix_to_swp_entry(page);
5339 if (do_swap_account)
5341 page = find_get_page(swap_address_space(swp), swp.val);
5344 page = find_get_page(mapping, pgoff);
5346 page = find_get_page(mapping, pgoff);
5351 static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
5352 unsigned long addr, pte_t ptent, union mc_target *target)
5354 struct page *page = NULL;
5355 struct page_cgroup *pc;
5356 enum mc_target_type ret = MC_TARGET_NONE;
5357 swp_entry_t ent = { .val = 0 };
5359 if (pte_present(ptent))
5360 page = mc_handle_present_pte(vma, addr, ptent);
5361 else if (is_swap_pte(ptent))
5362 page = mc_handle_swap_pte(vma, addr, ptent, &ent);
5363 else if (pte_none(ptent) || pte_file(ptent))
5364 page = mc_handle_file_pte(vma, addr, ptent, &ent);
5366 if (!page && !ent.val)
5369 pc = lookup_page_cgroup(page);
5371 * Do only loose check w/o serialization.
5372 * mem_cgroup_move_account() checks the pc is valid or
5373 * not under LRU exclusion.
5375 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
5376 ret = MC_TARGET_PAGE;
5378 target->page = page;
5380 if (!ret || !target)
5383 /* There is a swap entry and a page doesn't exist or isn't charged */
5384 if (ent.val && !ret &&
5385 mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
5386 ret = MC_TARGET_SWAP;
5393 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5395 * We don't consider swapping or file mapped pages because THP does not
5396 * support them for now.
5397 * Caller should make sure that pmd_trans_huge(pmd) is true.
5399 static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5400 unsigned long addr, pmd_t pmd, union mc_target *target)
5402 struct page *page = NULL;
5403 struct page_cgroup *pc;
5404 enum mc_target_type ret = MC_TARGET_NONE;
5406 page = pmd_page(pmd);
5407 VM_BUG_ON_PAGE(!page || !PageHead(page), page);
5410 pc = lookup_page_cgroup(page);
5411 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
5412 ret = MC_TARGET_PAGE;
5415 target->page = page;
5421 static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5422 unsigned long addr, pmd_t pmd, union mc_target *target)
5424 return MC_TARGET_NONE;
5428 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
5429 unsigned long addr, unsigned long end,
5430 struct mm_walk *walk)
5432 struct vm_area_struct *vma = walk->private;
5436 if (pmd_trans_huge_lock(pmd, vma, &ptl) == 1) {
5437 if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
5438 mc.precharge += HPAGE_PMD_NR;
5443 if (pmd_trans_unstable(pmd))
5445 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5446 for (; addr != end; pte++, addr += PAGE_SIZE)
5447 if (get_mctgt_type(vma, addr, *pte, NULL))
5448 mc.precharge++; /* increment precharge temporarily */
5449 pte_unmap_unlock(pte - 1, ptl);
5455 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
5457 unsigned long precharge;
5458 struct vm_area_struct *vma;
5460 down_read(&mm->mmap_sem);
5461 for (vma = mm->mmap; vma; vma = vma->vm_next) {
5462 struct mm_walk mem_cgroup_count_precharge_walk = {
5463 .pmd_entry = mem_cgroup_count_precharge_pte_range,
5467 if (is_vm_hugetlb_page(vma))
5469 walk_page_range(vma->vm_start, vma->vm_end,
5470 &mem_cgroup_count_precharge_walk);
5472 up_read(&mm->mmap_sem);
5474 precharge = mc.precharge;
5480 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
5482 unsigned long precharge = mem_cgroup_count_precharge(mm);
5484 VM_BUG_ON(mc.moving_task);
5485 mc.moving_task = current;
5486 return mem_cgroup_do_precharge(precharge);
5489 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5490 static void __mem_cgroup_clear_mc(void)
5492 struct mem_cgroup *from = mc.from;
5493 struct mem_cgroup *to = mc.to;
5495 /* we must uncharge all the leftover precharges from mc.to */
5497 cancel_charge(mc.to, mc.precharge);
5501 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5502 * we must uncharge here.
5504 if (mc.moved_charge) {
5505 cancel_charge(mc.from, mc.moved_charge);
5506 mc.moved_charge = 0;
5508 /* we must fixup refcnts and charges */
5509 if (mc.moved_swap) {
5510 /* uncharge swap account from the old cgroup */
5511 if (!mem_cgroup_is_root(mc.from))
5512 page_counter_uncharge(&mc.from->memsw, mc.moved_swap);
5515 * we charged both to->memory and to->memsw, so we
5516 * should uncharge to->memory.
5518 if (!mem_cgroup_is_root(mc.to))
5519 page_counter_uncharge(&mc.to->memory, mc.moved_swap);
5521 css_put_many(&mc.from->css, mc.moved_swap);
5523 /* we've already done css_get(mc.to) */
5526 memcg_oom_recover(from);
5527 memcg_oom_recover(to);
5528 wake_up_all(&mc.waitq);
5531 static void mem_cgroup_clear_mc(void)
5533 struct mem_cgroup *from = mc.from;
5536 * we must clear moving_task before waking up waiters at the end of
5539 mc.moving_task = NULL;
5540 __mem_cgroup_clear_mc();
5541 spin_lock(&mc.lock);
5544 spin_unlock(&mc.lock);
5545 mem_cgroup_end_move(from);
5548 static int mem_cgroup_can_attach(struct cgroup_subsys_state *css,
5549 struct cgroup_taskset *tset)
5551 struct task_struct *p = cgroup_taskset_first(tset);
5553 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5554 unsigned long move_charge_at_immigrate;
5557 * We are now commited to this value whatever it is. Changes in this
5558 * tunable will only affect upcoming migrations, not the current one.
5559 * So we need to save it, and keep it going.
5561 move_charge_at_immigrate = memcg->move_charge_at_immigrate;
5562 if (move_charge_at_immigrate) {
5563 struct mm_struct *mm;
5564 struct mem_cgroup *from = mem_cgroup_from_task(p);
5566 VM_BUG_ON(from == memcg);
5568 mm = get_task_mm(p);
5571 /* We move charges only when we move a owner of the mm */
5572 if (mm->owner == p) {
5575 VM_BUG_ON(mc.precharge);
5576 VM_BUG_ON(mc.moved_charge);
5577 VM_BUG_ON(mc.moved_swap);
5578 mem_cgroup_start_move(from);
5579 spin_lock(&mc.lock);
5582 mc.immigrate_flags = move_charge_at_immigrate;
5583 spin_unlock(&mc.lock);
5584 /* We set mc.moving_task later */
5586 ret = mem_cgroup_precharge_mc(mm);
5588 mem_cgroup_clear_mc();
5595 static void mem_cgroup_cancel_attach(struct cgroup_subsys_state *css,
5596 struct cgroup_taskset *tset)
5598 mem_cgroup_clear_mc();
5601 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
5602 unsigned long addr, unsigned long end,
5603 struct mm_walk *walk)
5606 struct vm_area_struct *vma = walk->private;
5609 enum mc_target_type target_type;
5610 union mc_target target;
5612 struct page_cgroup *pc;
5615 * We don't take compound_lock() here but no race with splitting thp
5617 * - if pmd_trans_huge_lock() returns 1, the relevant thp is not
5618 * under splitting, which means there's no concurrent thp split,
5619 * - if another thread runs into split_huge_page() just after we
5620 * entered this if-block, the thread must wait for page table lock
5621 * to be unlocked in __split_huge_page_splitting(), where the main
5622 * part of thp split is not executed yet.
5624 if (pmd_trans_huge_lock(pmd, vma, &ptl) == 1) {
5625 if (mc.precharge < HPAGE_PMD_NR) {
5629 target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
5630 if (target_type == MC_TARGET_PAGE) {
5632 if (!isolate_lru_page(page)) {
5633 pc = lookup_page_cgroup(page);
5634 if (!mem_cgroup_move_account(page, HPAGE_PMD_NR,
5635 pc, mc.from, mc.to)) {
5636 mc.precharge -= HPAGE_PMD_NR;
5637 mc.moved_charge += HPAGE_PMD_NR;
5639 putback_lru_page(page);
5647 if (pmd_trans_unstable(pmd))
5650 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5651 for (; addr != end; addr += PAGE_SIZE) {
5652 pte_t ptent = *(pte++);
5658 switch (get_mctgt_type(vma, addr, ptent, &target)) {
5659 case MC_TARGET_PAGE:
5661 if (isolate_lru_page(page))
5663 pc = lookup_page_cgroup(page);
5664 if (!mem_cgroup_move_account(page, 1, pc,
5667 /* we uncharge from mc.from later. */
5670 putback_lru_page(page);
5671 put: /* get_mctgt_type() gets the page */
5674 case MC_TARGET_SWAP:
5676 if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
5678 /* we fixup refcnts and charges later. */
5686 pte_unmap_unlock(pte - 1, ptl);
5691 * We have consumed all precharges we got in can_attach().
5692 * We try charge one by one, but don't do any additional
5693 * charges to mc.to if we have failed in charge once in attach()
5696 ret = mem_cgroup_do_precharge(1);
5704 static void mem_cgroup_move_charge(struct mm_struct *mm)
5706 struct vm_area_struct *vma;
5708 lru_add_drain_all();
5710 if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
5712 * Someone who are holding the mmap_sem might be waiting in
5713 * waitq. So we cancel all extra charges, wake up all waiters,
5714 * and retry. Because we cancel precharges, we might not be able
5715 * to move enough charges, but moving charge is a best-effort
5716 * feature anyway, so it wouldn't be a big problem.
5718 __mem_cgroup_clear_mc();
5722 for (vma = mm->mmap; vma; vma = vma->vm_next) {
5724 struct mm_walk mem_cgroup_move_charge_walk = {
5725 .pmd_entry = mem_cgroup_move_charge_pte_range,
5729 if (is_vm_hugetlb_page(vma))
5731 ret = walk_page_range(vma->vm_start, vma->vm_end,
5732 &mem_cgroup_move_charge_walk);
5735 * means we have consumed all precharges and failed in
5736 * doing additional charge. Just abandon here.
5740 up_read(&mm->mmap_sem);
5743 static void mem_cgroup_move_task(struct cgroup_subsys_state *css,
5744 struct cgroup_taskset *tset)
5746 struct task_struct *p = cgroup_taskset_first(tset);
5747 struct mm_struct *mm = get_task_mm(p);
5751 mem_cgroup_move_charge(mm);
5755 mem_cgroup_clear_mc();
5757 #else /* !CONFIG_MMU */
5758 static int mem_cgroup_can_attach(struct cgroup_subsys_state *css,
5759 struct cgroup_taskset *tset)
5763 static void mem_cgroup_cancel_attach(struct cgroup_subsys_state *css,
5764 struct cgroup_taskset *tset)
5767 static void mem_cgroup_move_task(struct cgroup_subsys_state *css,
5768 struct cgroup_taskset *tset)
5774 * Cgroup retains root cgroups across [un]mount cycles making it necessary
5775 * to verify whether we're attached to the default hierarchy on each mount
5778 static void mem_cgroup_bind(struct cgroup_subsys_state *root_css)
5781 * use_hierarchy is forced on the default hierarchy. cgroup core
5782 * guarantees that @root doesn't have any children, so turning it
5783 * on for the root memcg is enough.
5785 if (cgroup_on_dfl(root_css->cgroup))
5786 mem_cgroup_from_css(root_css)->use_hierarchy = true;
5789 struct cgroup_subsys memory_cgrp_subsys = {
5790 .css_alloc = mem_cgroup_css_alloc,
5791 .css_online = mem_cgroup_css_online,
5792 .css_offline = mem_cgroup_css_offline,
5793 .css_free = mem_cgroup_css_free,
5794 .css_reset = mem_cgroup_css_reset,
5795 .can_attach = mem_cgroup_can_attach,
5796 .cancel_attach = mem_cgroup_cancel_attach,
5797 .attach = mem_cgroup_move_task,
5798 .bind = mem_cgroup_bind,
5799 .legacy_cftypes = mem_cgroup_files,
5803 #ifdef CONFIG_MEMCG_SWAP
5804 static int __init enable_swap_account(char *s)
5806 if (!strcmp(s, "1"))
5807 really_do_swap_account = 1;
5808 else if (!strcmp(s, "0"))
5809 really_do_swap_account = 0;
5812 __setup("swapaccount=", enable_swap_account);
5814 static void __init memsw_file_init(void)
5816 WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys,
5817 memsw_cgroup_files));
5820 static void __init enable_swap_cgroup(void)
5822 if (!mem_cgroup_disabled() && really_do_swap_account) {
5823 do_swap_account = 1;
5829 static void __init enable_swap_cgroup(void)
5834 #ifdef CONFIG_MEMCG_SWAP
5836 * mem_cgroup_swapout - transfer a memsw charge to swap
5837 * @page: page whose memsw charge to transfer
5838 * @entry: swap entry to move the charge to
5840 * Transfer the memsw charge of @page to @entry.
5842 void mem_cgroup_swapout(struct page *page, swp_entry_t entry)
5844 struct page_cgroup *pc;
5845 unsigned short oldid;
5847 VM_BUG_ON_PAGE(PageLRU(page), page);
5848 VM_BUG_ON_PAGE(page_count(page), page);
5850 if (!do_swap_account)
5853 pc = lookup_page_cgroup(page);
5855 /* Readahead page, never charged */
5856 if (!PageCgroupUsed(pc))
5859 VM_BUG_ON_PAGE(!(pc->flags & PCG_MEMSW), page);
5861 oldid = swap_cgroup_record(entry, mem_cgroup_id(pc->mem_cgroup));
5862 VM_BUG_ON_PAGE(oldid, page);
5864 pc->flags &= ~PCG_MEMSW;
5865 css_get(&pc->mem_cgroup->css);
5866 mem_cgroup_swap_statistics(pc->mem_cgroup, true);
5870 * mem_cgroup_uncharge_swap - uncharge a swap entry
5871 * @entry: swap entry to uncharge
5873 * Drop the memsw charge associated with @entry.
5875 void mem_cgroup_uncharge_swap(swp_entry_t entry)
5877 struct mem_cgroup *memcg;
5880 if (!do_swap_account)
5883 id = swap_cgroup_record(entry, 0);
5885 memcg = mem_cgroup_lookup(id);
5887 if (!mem_cgroup_is_root(memcg))
5888 page_counter_uncharge(&memcg->memsw, 1);
5889 mem_cgroup_swap_statistics(memcg, false);
5890 css_put(&memcg->css);
5897 * mem_cgroup_try_charge - try charging a page
5898 * @page: page to charge
5899 * @mm: mm context of the victim
5900 * @gfp_mask: reclaim mode
5901 * @memcgp: charged memcg return
5903 * Try to charge @page to the memcg that @mm belongs to, reclaiming
5904 * pages according to @gfp_mask if necessary.
5906 * Returns 0 on success, with *@memcgp pointing to the charged memcg.
5907 * Otherwise, an error code is returned.
5909 * After page->mapping has been set up, the caller must finalize the
5910 * charge with mem_cgroup_commit_charge(). Or abort the transaction
5911 * with mem_cgroup_cancel_charge() in case page instantiation fails.
5913 int mem_cgroup_try_charge(struct page *page, struct mm_struct *mm,
5914 gfp_t gfp_mask, struct mem_cgroup **memcgp)
5916 struct mem_cgroup *memcg = NULL;
5917 unsigned int nr_pages = 1;
5920 if (mem_cgroup_disabled())
5923 if (PageSwapCache(page)) {
5924 struct page_cgroup *pc = lookup_page_cgroup(page);
5926 * Every swap fault against a single page tries to charge the
5927 * page, bail as early as possible. shmem_unuse() encounters
5928 * already charged pages, too. The USED bit is protected by
5929 * the page lock, which serializes swap cache removal, which
5930 * in turn serializes uncharging.
5932 if (PageCgroupUsed(pc))
5936 if (PageTransHuge(page)) {
5937 nr_pages <<= compound_order(page);
5938 VM_BUG_ON_PAGE(!PageTransHuge(page), page);
5941 if (do_swap_account && PageSwapCache(page))
5942 memcg = try_get_mem_cgroup_from_page(page);
5944 memcg = get_mem_cgroup_from_mm(mm);
5946 ret = try_charge(memcg, gfp_mask, nr_pages);
5948 css_put(&memcg->css);
5950 if (ret == -EINTR) {
5951 memcg = root_mem_cgroup;
5960 * mem_cgroup_commit_charge - commit a page charge
5961 * @page: page to charge
5962 * @memcg: memcg to charge the page to
5963 * @lrucare: page might be on LRU already
5965 * Finalize a charge transaction started by mem_cgroup_try_charge(),
5966 * after page->mapping has been set up. This must happen atomically
5967 * as part of the page instantiation, i.e. under the page table lock
5968 * for anonymous pages, under the page lock for page and swap cache.
5970 * In addition, the page must not be on the LRU during the commit, to
5971 * prevent racing with task migration. If it might be, use @lrucare.
5973 * Use mem_cgroup_cancel_charge() to cancel the transaction instead.
5975 void mem_cgroup_commit_charge(struct page *page, struct mem_cgroup *memcg,
5978 unsigned int nr_pages = 1;
5980 VM_BUG_ON_PAGE(!page->mapping, page);
5981 VM_BUG_ON_PAGE(PageLRU(page) && !lrucare, page);
5983 if (mem_cgroup_disabled())
5986 * Swap faults will attempt to charge the same page multiple
5987 * times. But reuse_swap_page() might have removed the page
5988 * from swapcache already, so we can't check PageSwapCache().
5993 commit_charge(page, memcg, lrucare);
5995 if (PageTransHuge(page)) {
5996 nr_pages <<= compound_order(page);
5997 VM_BUG_ON_PAGE(!PageTransHuge(page), page);
6000 local_irq_disable();
6001 mem_cgroup_charge_statistics(memcg, page, nr_pages);
6002 memcg_check_events(memcg, page);
6005 if (do_swap_account && PageSwapCache(page)) {
6006 swp_entry_t entry = { .val = page_private(page) };
6008 * The swap entry might not get freed for a long time,
6009 * let's not wait for it. The page already received a
6010 * memory+swap charge, drop the swap entry duplicate.
6012 mem_cgroup_uncharge_swap(entry);
6017 * mem_cgroup_cancel_charge - cancel a page charge
6018 * @page: page to charge
6019 * @memcg: memcg to charge the page to
6021 * Cancel a charge transaction started by mem_cgroup_try_charge().
6023 void mem_cgroup_cancel_charge(struct page *page, struct mem_cgroup *memcg)
6025 unsigned int nr_pages = 1;
6027 if (mem_cgroup_disabled())
6030 * Swap faults will attempt to charge the same page multiple
6031 * times. But reuse_swap_page() might have removed the page
6032 * from swapcache already, so we can't check PageSwapCache().
6037 if (PageTransHuge(page)) {
6038 nr_pages <<= compound_order(page);
6039 VM_BUG_ON_PAGE(!PageTransHuge(page), page);
6042 cancel_charge(memcg, nr_pages);
6045 static void uncharge_batch(struct mem_cgroup *memcg, unsigned long pgpgout,
6046 unsigned long nr_mem, unsigned long nr_memsw,
6047 unsigned long nr_anon, unsigned long nr_file,
6048 unsigned long nr_huge, struct page *dummy_page)
6050 unsigned long flags;
6052 if (!mem_cgroup_is_root(memcg)) {
6054 page_counter_uncharge(&memcg->memory, nr_mem);
6056 page_counter_uncharge(&memcg->memsw, nr_memsw);
6057 memcg_oom_recover(memcg);
6060 local_irq_save(flags);
6061 __this_cpu_sub(memcg->stat->count[MEM_CGROUP_STAT_RSS], nr_anon);
6062 __this_cpu_sub(memcg->stat->count[MEM_CGROUP_STAT_CACHE], nr_file);
6063 __this_cpu_sub(memcg->stat->count[MEM_CGROUP_STAT_RSS_HUGE], nr_huge);
6064 __this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGOUT], pgpgout);
6065 __this_cpu_add(memcg->stat->nr_page_events, nr_anon + nr_file);
6066 memcg_check_events(memcg, dummy_page);
6067 local_irq_restore(flags);
6069 if (!mem_cgroup_is_root(memcg))
6070 css_put_many(&memcg->css, max(nr_mem, nr_memsw));
6073 static void uncharge_list(struct list_head *page_list)
6075 struct mem_cgroup *memcg = NULL;
6076 unsigned long nr_memsw = 0;
6077 unsigned long nr_anon = 0;
6078 unsigned long nr_file = 0;
6079 unsigned long nr_huge = 0;
6080 unsigned long pgpgout = 0;
6081 unsigned long nr_mem = 0;
6082 struct list_head *next;
6085 next = page_list->next;
6087 unsigned int nr_pages = 1;
6088 struct page_cgroup *pc;
6090 page = list_entry(next, struct page, lru);
6091 next = page->lru.next;
6093 VM_BUG_ON_PAGE(PageLRU(page), page);
6094 VM_BUG_ON_PAGE(page_count(page), page);
6096 pc = lookup_page_cgroup(page);
6097 if (!PageCgroupUsed(pc))
6101 * Nobody should be changing or seriously looking at
6102 * pc->mem_cgroup and pc->flags at this point, we have
6103 * fully exclusive access to the page.
6106 if (memcg != pc->mem_cgroup) {
6108 uncharge_batch(memcg, pgpgout, nr_mem, nr_memsw,
6109 nr_anon, nr_file, nr_huge, page);
6110 pgpgout = nr_mem = nr_memsw = 0;
6111 nr_anon = nr_file = nr_huge = 0;
6113 memcg = pc->mem_cgroup;
6116 if (PageTransHuge(page)) {
6117 nr_pages <<= compound_order(page);
6118 VM_BUG_ON_PAGE(!PageTransHuge(page), page);
6119 nr_huge += nr_pages;
6123 nr_anon += nr_pages;
6125 nr_file += nr_pages;
6127 if (pc->flags & PCG_MEM)
6129 if (pc->flags & PCG_MEMSW)
6130 nr_memsw += nr_pages;
6134 } while (next != page_list);
6137 uncharge_batch(memcg, pgpgout, nr_mem, nr_memsw,
6138 nr_anon, nr_file, nr_huge, page);
6142 * mem_cgroup_uncharge - uncharge a page
6143 * @page: page to uncharge
6145 * Uncharge a page previously charged with mem_cgroup_try_charge() and
6146 * mem_cgroup_commit_charge().
6148 void mem_cgroup_uncharge(struct page *page)
6150 struct page_cgroup *pc;
6152 if (mem_cgroup_disabled())
6155 /* Don't touch page->lru of any random page, pre-check: */
6156 pc = lookup_page_cgroup(page);
6157 if (!PageCgroupUsed(pc))
6160 INIT_LIST_HEAD(&page->lru);
6161 uncharge_list(&page->lru);
6165 * mem_cgroup_uncharge_list - uncharge a list of page
6166 * @page_list: list of pages to uncharge
6168 * Uncharge a list of pages previously charged with
6169 * mem_cgroup_try_charge() and mem_cgroup_commit_charge().
6171 void mem_cgroup_uncharge_list(struct list_head *page_list)
6173 if (mem_cgroup_disabled())
6176 if (!list_empty(page_list))
6177 uncharge_list(page_list);
6181 * mem_cgroup_migrate - migrate a charge to another page
6182 * @oldpage: currently charged page
6183 * @newpage: page to transfer the charge to
6184 * @lrucare: both pages might be on the LRU already
6186 * Migrate the charge from @oldpage to @newpage.
6188 * Both pages must be locked, @newpage->mapping must be set up.
6190 void mem_cgroup_migrate(struct page *oldpage, struct page *newpage,
6193 struct page_cgroup *pc;
6196 VM_BUG_ON_PAGE(!PageLocked(oldpage), oldpage);
6197 VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
6198 VM_BUG_ON_PAGE(!lrucare && PageLRU(oldpage), oldpage);
6199 VM_BUG_ON_PAGE(!lrucare && PageLRU(newpage), newpage);
6200 VM_BUG_ON_PAGE(PageAnon(oldpage) != PageAnon(newpage), newpage);
6201 VM_BUG_ON_PAGE(PageTransHuge(oldpage) != PageTransHuge(newpage),
6204 if (mem_cgroup_disabled())
6207 /* Page cache replacement: new page already charged? */
6208 pc = lookup_page_cgroup(newpage);
6209 if (PageCgroupUsed(pc))
6212 /* Re-entrant migration: old page already uncharged? */
6213 pc = lookup_page_cgroup(oldpage);
6214 if (!PageCgroupUsed(pc))
6217 VM_BUG_ON_PAGE(!(pc->flags & PCG_MEM), oldpage);
6218 VM_BUG_ON_PAGE(do_swap_account && !(pc->flags & PCG_MEMSW), oldpage);
6221 lock_page_lru(oldpage, &isolated);
6226 unlock_page_lru(oldpage, isolated);
6228 commit_charge(newpage, pc->mem_cgroup, lrucare);
6232 * subsys_initcall() for memory controller.
6234 * Some parts like hotcpu_notifier() have to be initialized from this context
6235 * because of lock dependencies (cgroup_lock -> cpu hotplug) but basically
6236 * everything that doesn't depend on a specific mem_cgroup structure should
6237 * be initialized from here.
6239 static int __init mem_cgroup_init(void)
6241 hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
6242 enable_swap_cgroup();
6243 mem_cgroup_soft_limit_tree_init();
6247 subsys_initcall(mem_cgroup_init);