list_lru: add helpers to isolate items
[linux-2.6-block.git] / mm / memcontrol.c
CommitLineData
8cdea7c0
BS
1/* memcontrol.c - Memory Controller
2 *
3 * Copyright IBM Corporation, 2007
4 * Author Balbir Singh <balbir@linux.vnet.ibm.com>
5 *
78fb7466
PE
6 * Copyright 2007 OpenVZ SWsoft Inc
7 * Author: Pavel Emelianov <xemul@openvz.org>
8 *
2e72b634
KS
9 * Memory thresholds
10 * Copyright (C) 2009 Nokia Corporation
11 * Author: Kirill A. Shutemov
12 *
7ae1e1d0
GC
13 * Kernel Memory Controller
14 * Copyright (C) 2012 Parallels Inc. and Google Inc.
15 * Authors: Glauber Costa and Suleiman Souhlal
16 *
8cdea7c0
BS
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.
21 *
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.
26 */
27
3e32cb2e 28#include <linux/page_counter.h>
8cdea7c0
BS
29#include <linux/memcontrol.h>
30#include <linux/cgroup.h>
78fb7466 31#include <linux/mm.h>
4ffef5fe 32#include <linux/hugetlb.h>
d13d1443 33#include <linux/pagemap.h>
d52aa412 34#include <linux/smp.h>
8a9f3ccd 35#include <linux/page-flags.h>
66e1707b 36#include <linux/backing-dev.h>
8a9f3ccd
BS
37#include <linux/bit_spinlock.h>
38#include <linux/rcupdate.h>
e222432b 39#include <linux/limits.h>
b9e15baf 40#include <linux/export.h>
8c7c6e34 41#include <linux/mutex.h>
bb4cc1a8 42#include <linux/rbtree.h>
b6ac57d5 43#include <linux/slab.h>
66e1707b 44#include <linux/swap.h>
02491447 45#include <linux/swapops.h>
66e1707b 46#include <linux/spinlock.h>
2e72b634 47#include <linux/eventfd.h>
79bd9814 48#include <linux/poll.h>
2e72b634 49#include <linux/sort.h>
66e1707b 50#include <linux/fs.h>
d2ceb9b7 51#include <linux/seq_file.h>
70ddf637 52#include <linux/vmpressure.h>
b69408e8 53#include <linux/mm_inline.h>
5d1ea48b 54#include <linux/swap_cgroup.h>
cdec2e42 55#include <linux/cpu.h>
158e0a2d 56#include <linux/oom.h>
0056f4e6 57#include <linux/lockdep.h>
79bd9814 58#include <linux/file.h>
08e552c6 59#include "internal.h"
d1a4c0b3 60#include <net/sock.h>
4bd2c1ee 61#include <net/ip.h>
d1a4c0b3 62#include <net/tcp_memcontrol.h>
f35c3a8e 63#include "slab.h"
8cdea7c0 64
8697d331
BS
65#include <asm/uaccess.h>
66
cc8e970c
KM
67#include <trace/events/vmscan.h>
68
073219e9
TH
69struct cgroup_subsys memory_cgrp_subsys __read_mostly;
70EXPORT_SYMBOL(memory_cgrp_subsys);
68ae564b 71
a181b0e8 72#define MEM_CGROUP_RECLAIM_RETRIES 5
6bbda35c 73static struct mem_cgroup *root_mem_cgroup __read_mostly;
8cdea7c0 74
21afa38e 75/* Whether the swap controller is active */
c255a458 76#ifdef CONFIG_MEMCG_SWAP
c077719b 77int do_swap_account __read_mostly;
c077719b 78#else
a0db00fc 79#define do_swap_account 0
c077719b
KH
80#endif
81
af7c4b0e
JW
82static const char * const mem_cgroup_stat_names[] = {
83 "cache",
84 "rss",
b070e65c 85 "rss_huge",
af7c4b0e 86 "mapped_file",
3ea67d06 87 "writeback",
af7c4b0e
JW
88 "swap",
89};
90
af7c4b0e
JW
91static const char * const mem_cgroup_events_names[] = {
92 "pgpgin",
93 "pgpgout",
94 "pgfault",
95 "pgmajfault",
96};
97
58cf188e
SZ
98static const char * const mem_cgroup_lru_names[] = {
99 "inactive_anon",
100 "active_anon",
101 "inactive_file",
102 "active_file",
103 "unevictable",
104};
105
7a159cc9
JW
106/*
107 * Per memcg event counter is incremented at every pagein/pageout. With THP,
108 * it will be incremated by the number of pages. This counter is used for
109 * for trigger some periodic events. This is straightforward and better
110 * than using jiffies etc. to handle periodic memcg event.
111 */
112enum mem_cgroup_events_target {
113 MEM_CGROUP_TARGET_THRESH,
bb4cc1a8 114 MEM_CGROUP_TARGET_SOFTLIMIT,
453a9bf3 115 MEM_CGROUP_TARGET_NUMAINFO,
7a159cc9
JW
116 MEM_CGROUP_NTARGETS,
117};
a0db00fc
KS
118#define THRESHOLDS_EVENTS_TARGET 128
119#define SOFTLIMIT_EVENTS_TARGET 1024
120#define NUMAINFO_EVENTS_TARGET 1024
e9f8974f 121
d52aa412 122struct mem_cgroup_stat_cpu {
7a159cc9 123 long count[MEM_CGROUP_STAT_NSTATS];
241994ed 124 unsigned long events[MEMCG_NR_EVENTS];
13114716 125 unsigned long nr_page_events;
7a159cc9 126 unsigned long targets[MEM_CGROUP_NTARGETS];
d52aa412
KH
127};
128
5ac8fb31
JW
129struct reclaim_iter {
130 struct mem_cgroup *position;
527a5ec9
JW
131 /* scan generation, increased every round-trip */
132 unsigned int generation;
133};
134
6d12e2d8
KH
135/*
136 * per-zone information in memory controller.
137 */
6d12e2d8 138struct mem_cgroup_per_zone {
6290df54 139 struct lruvec lruvec;
1eb49272 140 unsigned long lru_size[NR_LRU_LISTS];
3e2f41f1 141
5ac8fb31 142 struct reclaim_iter iter[DEF_PRIORITY + 1];
527a5ec9 143
bb4cc1a8 144 struct rb_node tree_node; /* RB tree node */
3e32cb2e 145 unsigned long usage_in_excess;/* Set to the value by which */
bb4cc1a8
AM
146 /* the soft limit is exceeded*/
147 bool on_tree;
d79154bb 148 struct mem_cgroup *memcg; /* Back pointer, we cannot */
4e416953 149 /* use container_of */
6d12e2d8 150};
6d12e2d8
KH
151
152struct mem_cgroup_per_node {
153 struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
154};
155
bb4cc1a8
AM
156/*
157 * Cgroups above their limits are maintained in a RB-Tree, independent of
158 * their hierarchy representation
159 */
160
161struct mem_cgroup_tree_per_zone {
162 struct rb_root rb_root;
163 spinlock_t lock;
164};
165
166struct mem_cgroup_tree_per_node {
167 struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
168};
169
170struct mem_cgroup_tree {
171 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
172};
173
174static struct mem_cgroup_tree soft_limit_tree __read_mostly;
175
2e72b634
KS
176struct mem_cgroup_threshold {
177 struct eventfd_ctx *eventfd;
3e32cb2e 178 unsigned long threshold;
2e72b634
KS
179};
180
9490ff27 181/* For threshold */
2e72b634 182struct mem_cgroup_threshold_ary {
748dad36 183 /* An array index points to threshold just below or equal to usage. */
5407a562 184 int current_threshold;
2e72b634
KS
185 /* Size of entries[] */
186 unsigned int size;
187 /* Array of thresholds */
188 struct mem_cgroup_threshold entries[0];
189};
2c488db2
KS
190
191struct mem_cgroup_thresholds {
192 /* Primary thresholds array */
193 struct mem_cgroup_threshold_ary *primary;
194 /*
195 * Spare threshold array.
196 * This is needed to make mem_cgroup_unregister_event() "never fail".
197 * It must be able to store at least primary->size - 1 entries.
198 */
199 struct mem_cgroup_threshold_ary *spare;
200};
201
9490ff27
KH
202/* for OOM */
203struct mem_cgroup_eventfd_list {
204 struct list_head list;
205 struct eventfd_ctx *eventfd;
206};
2e72b634 207
79bd9814
TH
208/*
209 * cgroup_event represents events which userspace want to receive.
210 */
3bc942f3 211struct mem_cgroup_event {
79bd9814 212 /*
59b6f873 213 * memcg which the event belongs to.
79bd9814 214 */
59b6f873 215 struct mem_cgroup *memcg;
79bd9814
TH
216 /*
217 * eventfd to signal userspace about the event.
218 */
219 struct eventfd_ctx *eventfd;
220 /*
221 * Each of these stored in a list by the cgroup.
222 */
223 struct list_head list;
fba94807
TH
224 /*
225 * register_event() callback will be used to add new userspace
226 * waiter for changes related to this event. Use eventfd_signal()
227 * on eventfd to send notification to userspace.
228 */
59b6f873 229 int (*register_event)(struct mem_cgroup *memcg,
347c4a87 230 struct eventfd_ctx *eventfd, const char *args);
fba94807
TH
231 /*
232 * unregister_event() callback will be called when userspace closes
233 * the eventfd or on cgroup removing. This callback must be set,
234 * if you want provide notification functionality.
235 */
59b6f873 236 void (*unregister_event)(struct mem_cgroup *memcg,
fba94807 237 struct eventfd_ctx *eventfd);
79bd9814
TH
238 /*
239 * All fields below needed to unregister event when
240 * userspace closes eventfd.
241 */
242 poll_table pt;
243 wait_queue_head_t *wqh;
244 wait_queue_t wait;
245 struct work_struct remove;
246};
247
c0ff4b85
R
248static void mem_cgroup_threshold(struct mem_cgroup *memcg);
249static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
2e72b634 250
8cdea7c0
BS
251/*
252 * The memory controller data structure. The memory controller controls both
253 * page cache and RSS per cgroup. We would eventually like to provide
254 * statistics based on the statistics developed by Rik Van Riel for clock-pro,
255 * to help the administrator determine what knobs to tune.
256 *
257 * TODO: Add a water mark for the memory controller. Reclaim will begin when
8a9f3ccd
BS
258 * we hit the water mark. May be even add a low water mark, such that
259 * no reclaim occurs from a cgroup at it's low water mark, this is
260 * a feature that will be implemented much later in the future.
8cdea7c0
BS
261 */
262struct mem_cgroup {
263 struct cgroup_subsys_state css;
3e32cb2e
JW
264
265 /* Accounted resources */
266 struct page_counter memory;
267 struct page_counter memsw;
268 struct page_counter kmem;
269
241994ed
JW
270 /* Normal memory consumption range */
271 unsigned long low;
272 unsigned long high;
273
3e32cb2e 274 unsigned long soft_limit;
59927fb9 275
70ddf637
AV
276 /* vmpressure notifications */
277 struct vmpressure vmpressure;
278
2f7dd7a4
JW
279 /* css_online() has been completed */
280 int initialized;
281
18f59ea7
BS
282 /*
283 * Should the accounting and control be hierarchical, per subtree?
284 */
285 bool use_hierarchy;
79dfdacc
MH
286
287 bool oom_lock;
288 atomic_t under_oom;
3812c8c8 289 atomic_t oom_wakeups;
79dfdacc 290
1f4c025b 291 int swappiness;
3c11ecf4
KH
292 /* OOM-Killer disable */
293 int oom_kill_disable;
a7885eb8 294
2e72b634
KS
295 /* protect arrays of thresholds */
296 struct mutex thresholds_lock;
297
298 /* thresholds for memory usage. RCU-protected */
2c488db2 299 struct mem_cgroup_thresholds thresholds;
907860ed 300
2e72b634 301 /* thresholds for mem+swap usage. RCU-protected */
2c488db2 302 struct mem_cgroup_thresholds memsw_thresholds;
907860ed 303
9490ff27
KH
304 /* For oom notifier event fd */
305 struct list_head oom_notify;
185efc0f 306
7dc74be0
DN
307 /*
308 * Should we move charges of a task when a task is moved into this
309 * mem_cgroup ? And what type of charges should we move ?
310 */
f894ffa8 311 unsigned long move_charge_at_immigrate;
619d094b
KH
312 /*
313 * set > 0 if pages under this cgroup are moving to other cgroup.
314 */
6de22619 315 atomic_t moving_account;
312734c0 316 /* taken only while moving_account > 0 */
6de22619
JW
317 spinlock_t move_lock;
318 struct task_struct *move_lock_task;
319 unsigned long move_lock_flags;
d52aa412 320 /*
c62b1a3b 321 * percpu counter.
d52aa412 322 */
3a7951b4 323 struct mem_cgroup_stat_cpu __percpu *stat;
711d3d2c
KH
324 /*
325 * used when a cpu is offlined or other synchronizations
326 * See mem_cgroup_read_stat().
327 */
328 struct mem_cgroup_stat_cpu nocpu_base;
329 spinlock_t pcp_counter_lock;
d1a4c0b3 330
4bd2c1ee 331#if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_INET)
2e685cad 332 struct cg_proto tcp_mem;
d1a4c0b3 333#endif
2633d7a0 334#if defined(CONFIG_MEMCG_KMEM)
f7ce3190 335 /* Index in the kmem_cache->memcg_params.memcg_caches array */
2633d7a0 336 int kmemcg_id;
2a4db7eb 337 bool kmem_acct_active;
2633d7a0 338#endif
45cf7ebd
GC
339
340 int last_scanned_node;
341#if MAX_NUMNODES > 1
342 nodemask_t scan_nodes;
343 atomic_t numainfo_events;
344 atomic_t numainfo_updating;
345#endif
70ddf637 346
fba94807
TH
347 /* List of events which userspace want to receive */
348 struct list_head event_list;
349 spinlock_t event_list_lock;
350
54f72fe0
JW
351 struct mem_cgroup_per_node *nodeinfo[0];
352 /* WARNING: nodeinfo must be the last member here */
8cdea7c0
BS
353};
354
510fc4e1 355#ifdef CONFIG_MEMCG_KMEM
cb731d6c 356bool memcg_kmem_is_active(struct mem_cgroup *memcg)
7de37682 357{
2a4db7eb 358 return memcg->kmem_acct_active;
7de37682 359}
510fc4e1
GC
360#endif
361
7dc74be0
DN
362/* Stuffs for move charges at task migration. */
363/*
1dfab5ab 364 * Types of charges to be moved.
7dc74be0 365 */
1dfab5ab
JW
366#define MOVE_ANON 0x1U
367#define MOVE_FILE 0x2U
368#define MOVE_MASK (MOVE_ANON | MOVE_FILE)
7dc74be0 369
4ffef5fe
DN
370/* "mc" and its members are protected by cgroup_mutex */
371static struct move_charge_struct {
b1dd693e 372 spinlock_t lock; /* for from, to */
4ffef5fe
DN
373 struct mem_cgroup *from;
374 struct mem_cgroup *to;
1dfab5ab 375 unsigned long flags;
4ffef5fe 376 unsigned long precharge;
854ffa8d 377 unsigned long moved_charge;
483c30b5 378 unsigned long moved_swap;
8033b97c
DN
379 struct task_struct *moving_task; /* a task moving charges */
380 wait_queue_head_t waitq; /* a waitq for other context */
381} mc = {
2bd9bb20 382 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
8033b97c
DN
383 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
384};
4ffef5fe 385
4e416953
BS
386/*
387 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
388 * limit reclaim to prevent infinite loops, if they ever occur.
389 */
a0db00fc 390#define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
bb4cc1a8 391#define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
4e416953 392
217bc319
KH
393enum charge_type {
394 MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
41326c17 395 MEM_CGROUP_CHARGE_TYPE_ANON,
d13d1443 396 MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
8a9478ca 397 MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
c05555b5
KH
398 NR_CHARGE_TYPE,
399};
400
8c7c6e34 401/* for encoding cft->private value on file */
86ae53e1
GC
402enum res_type {
403 _MEM,
404 _MEMSWAP,
405 _OOM_TYPE,
510fc4e1 406 _KMEM,
86ae53e1
GC
407};
408
a0db00fc
KS
409#define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
410#define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
8c7c6e34 411#define MEMFILE_ATTR(val) ((val) & 0xffff)
9490ff27
KH
412/* Used for OOM nofiier */
413#define OOM_CONTROL (0)
8c7c6e34 414
0999821b
GC
415/*
416 * The memcg_create_mutex will be held whenever a new cgroup is created.
417 * As a consequence, any change that needs to protect against new child cgroups
418 * appearing has to hold it as well.
419 */
420static DEFINE_MUTEX(memcg_create_mutex);
421
b2145145
WL
422struct mem_cgroup *mem_cgroup_from_css(struct cgroup_subsys_state *s)
423{
a7c6d554 424 return s ? container_of(s, struct mem_cgroup, css) : NULL;
b2145145
WL
425}
426
70ddf637
AV
427/* Some nice accessors for the vmpressure. */
428struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
429{
430 if (!memcg)
431 memcg = root_mem_cgroup;
432 return &memcg->vmpressure;
433}
434
435struct cgroup_subsys_state *vmpressure_to_css(struct vmpressure *vmpr)
436{
437 return &container_of(vmpr, struct mem_cgroup, vmpressure)->css;
438}
439
7ffc0edc
MH
440static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg)
441{
442 return (memcg == root_mem_cgroup);
443}
444
4219b2da
LZ
445/*
446 * We restrict the id in the range of [1, 65535], so it can fit into
447 * an unsigned short.
448 */
449#define MEM_CGROUP_ID_MAX USHRT_MAX
450
34c00c31
LZ
451static inline unsigned short mem_cgroup_id(struct mem_cgroup *memcg)
452{
15a4c835 453 return memcg->css.id;
34c00c31
LZ
454}
455
456static inline struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
457{
458 struct cgroup_subsys_state *css;
459
7d699ddb 460 css = css_from_id(id, &memory_cgrp_subsys);
34c00c31
LZ
461 return mem_cgroup_from_css(css);
462}
463
e1aab161 464/* Writing them here to avoid exposing memcg's inner layout */
4bd2c1ee 465#if defined(CONFIG_INET) && defined(CONFIG_MEMCG_KMEM)
e1aab161 466
e1aab161
GC
467void sock_update_memcg(struct sock *sk)
468{
376be5ff 469 if (mem_cgroup_sockets_enabled) {
e1aab161 470 struct mem_cgroup *memcg;
3f134619 471 struct cg_proto *cg_proto;
e1aab161
GC
472
473 BUG_ON(!sk->sk_prot->proto_cgroup);
474
f3f511e1
GC
475 /* Socket cloning can throw us here with sk_cgrp already
476 * filled. It won't however, necessarily happen from
477 * process context. So the test for root memcg given
478 * the current task's memcg won't help us in this case.
479 *
480 * Respecting the original socket's memcg is a better
481 * decision in this case.
482 */
483 if (sk->sk_cgrp) {
484 BUG_ON(mem_cgroup_is_root(sk->sk_cgrp->memcg));
5347e5ae 485 css_get(&sk->sk_cgrp->memcg->css);
f3f511e1
GC
486 return;
487 }
488
e1aab161
GC
489 rcu_read_lock();
490 memcg = mem_cgroup_from_task(current);
3f134619 491 cg_proto = sk->sk_prot->proto_cgroup(memcg);
5347e5ae 492 if (!mem_cgroup_is_root(memcg) &&
ec903c0c
TH
493 memcg_proto_active(cg_proto) &&
494 css_tryget_online(&memcg->css)) {
3f134619 495 sk->sk_cgrp = cg_proto;
e1aab161
GC
496 }
497 rcu_read_unlock();
498 }
499}
500EXPORT_SYMBOL(sock_update_memcg);
501
502void sock_release_memcg(struct sock *sk)
503{
376be5ff 504 if (mem_cgroup_sockets_enabled && sk->sk_cgrp) {
e1aab161
GC
505 struct mem_cgroup *memcg;
506 WARN_ON(!sk->sk_cgrp->memcg);
507 memcg = sk->sk_cgrp->memcg;
5347e5ae 508 css_put(&sk->sk_cgrp->memcg->css);
e1aab161
GC
509 }
510}
d1a4c0b3
GC
511
512struct cg_proto *tcp_proto_cgroup(struct mem_cgroup *memcg)
513{
514 if (!memcg || mem_cgroup_is_root(memcg))
515 return NULL;
516
2e685cad 517 return &memcg->tcp_mem;
d1a4c0b3
GC
518}
519EXPORT_SYMBOL(tcp_proto_cgroup);
e1aab161 520
3f134619
GC
521static void disarm_sock_keys(struct mem_cgroup *memcg)
522{
2e685cad 523 if (!memcg_proto_activated(&memcg->tcp_mem))
3f134619
GC
524 return;
525 static_key_slow_dec(&memcg_socket_limit_enabled);
526}
527#else
528static void disarm_sock_keys(struct mem_cgroup *memcg)
529{
530}
531#endif
532
a8964b9b 533#ifdef CONFIG_MEMCG_KMEM
55007d84 534/*
f7ce3190 535 * This will be the memcg's index in each cache's ->memcg_params.memcg_caches.
b8627835
LZ
536 * The main reason for not using cgroup id for this:
537 * this works better in sparse environments, where we have a lot of memcgs,
538 * but only a few kmem-limited. Or also, if we have, for instance, 200
539 * memcgs, and none but the 200th is kmem-limited, we'd have to have a
540 * 200 entry array for that.
55007d84 541 *
dbcf73e2
VD
542 * The current size of the caches array is stored in memcg_nr_cache_ids. It
543 * will double each time we have to increase it.
55007d84 544 */
dbcf73e2
VD
545static DEFINE_IDA(memcg_cache_ida);
546int memcg_nr_cache_ids;
749c5415 547
05257a1a
VD
548/* Protects memcg_nr_cache_ids */
549static DECLARE_RWSEM(memcg_cache_ids_sem);
550
551void memcg_get_cache_ids(void)
552{
553 down_read(&memcg_cache_ids_sem);
554}
555
556void memcg_put_cache_ids(void)
557{
558 up_read(&memcg_cache_ids_sem);
559}
560
55007d84
GC
561/*
562 * MIN_SIZE is different than 1, because we would like to avoid going through
563 * the alloc/free process all the time. In a small machine, 4 kmem-limited
564 * cgroups is a reasonable guess. In the future, it could be a parameter or
565 * tunable, but that is strictly not necessary.
566 *
b8627835 567 * MAX_SIZE should be as large as the number of cgrp_ids. Ideally, we could get
55007d84
GC
568 * this constant directly from cgroup, but it is understandable that this is
569 * better kept as an internal representation in cgroup.c. In any case, the
b8627835 570 * cgrp_id space is not getting any smaller, and we don't have to necessarily
55007d84
GC
571 * increase ours as well if it increases.
572 */
573#define MEMCG_CACHES_MIN_SIZE 4
b8627835 574#define MEMCG_CACHES_MAX_SIZE MEM_CGROUP_ID_MAX
55007d84 575
d7f25f8a
GC
576/*
577 * A lot of the calls to the cache allocation functions are expected to be
578 * inlined by the compiler. Since the calls to memcg_kmem_get_cache are
579 * conditional to this static branch, we'll have to allow modules that does
580 * kmem_cache_alloc and the such to see this symbol as well
581 */
a8964b9b 582struct static_key memcg_kmem_enabled_key;
d7f25f8a 583EXPORT_SYMBOL(memcg_kmem_enabled_key);
a8964b9b 584
f3bb3043
VD
585static void memcg_free_cache_id(int id);
586
a8964b9b
GC
587static void disarm_kmem_keys(struct mem_cgroup *memcg)
588{
2a4db7eb 589 if (memcg->kmemcg_id >= 0) {
a8964b9b 590 static_key_slow_dec(&memcg_kmem_enabled_key);
f3bb3043 591 memcg_free_cache_id(memcg->kmemcg_id);
55007d84 592 }
bea207c8
GC
593 /*
594 * This check can't live in kmem destruction function,
595 * since the charges will outlive the cgroup
596 */
3e32cb2e 597 WARN_ON(page_counter_read(&memcg->kmem));
a8964b9b
GC
598}
599#else
600static void disarm_kmem_keys(struct mem_cgroup *memcg)
601{
602}
603#endif /* CONFIG_MEMCG_KMEM */
604
605static void disarm_static_keys(struct mem_cgroup *memcg)
606{
607 disarm_sock_keys(memcg);
608 disarm_kmem_keys(memcg);
609}
610
f64c3f54 611static struct mem_cgroup_per_zone *
e231875b 612mem_cgroup_zone_zoneinfo(struct mem_cgroup *memcg, struct zone *zone)
f64c3f54 613{
e231875b
JZ
614 int nid = zone_to_nid(zone);
615 int zid = zone_idx(zone);
616
54f72fe0 617 return &memcg->nodeinfo[nid]->zoneinfo[zid];
f64c3f54
BS
618}
619
c0ff4b85 620struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *memcg)
d324236b 621{
c0ff4b85 622 return &memcg->css;
d324236b
WF
623}
624
f64c3f54 625static struct mem_cgroup_per_zone *
e231875b 626mem_cgroup_page_zoneinfo(struct mem_cgroup *memcg, struct page *page)
f64c3f54 627{
97a6c37b
JW
628 int nid = page_to_nid(page);
629 int zid = page_zonenum(page);
f64c3f54 630
e231875b 631 return &memcg->nodeinfo[nid]->zoneinfo[zid];
f64c3f54
BS
632}
633
bb4cc1a8
AM
634static struct mem_cgroup_tree_per_zone *
635soft_limit_tree_node_zone(int nid, int zid)
636{
637 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
638}
639
640static struct mem_cgroup_tree_per_zone *
641soft_limit_tree_from_page(struct page *page)
642{
643 int nid = page_to_nid(page);
644 int zid = page_zonenum(page);
645
646 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
647}
648
cf2c8127
JW
649static void __mem_cgroup_insert_exceeded(struct mem_cgroup_per_zone *mz,
650 struct mem_cgroup_tree_per_zone *mctz,
3e32cb2e 651 unsigned long new_usage_in_excess)
bb4cc1a8
AM
652{
653 struct rb_node **p = &mctz->rb_root.rb_node;
654 struct rb_node *parent = NULL;
655 struct mem_cgroup_per_zone *mz_node;
656
657 if (mz->on_tree)
658 return;
659
660 mz->usage_in_excess = new_usage_in_excess;
661 if (!mz->usage_in_excess)
662 return;
663 while (*p) {
664 parent = *p;
665 mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
666 tree_node);
667 if (mz->usage_in_excess < mz_node->usage_in_excess)
668 p = &(*p)->rb_left;
669 /*
670 * We can't avoid mem cgroups that are over their soft
671 * limit by the same amount
672 */
673 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
674 p = &(*p)->rb_right;
675 }
676 rb_link_node(&mz->tree_node, parent, p);
677 rb_insert_color(&mz->tree_node, &mctz->rb_root);
678 mz->on_tree = true;
679}
680
cf2c8127
JW
681static void __mem_cgroup_remove_exceeded(struct mem_cgroup_per_zone *mz,
682 struct mem_cgroup_tree_per_zone *mctz)
bb4cc1a8
AM
683{
684 if (!mz->on_tree)
685 return;
686 rb_erase(&mz->tree_node, &mctz->rb_root);
687 mz->on_tree = false;
688}
689
cf2c8127
JW
690static void mem_cgroup_remove_exceeded(struct mem_cgroup_per_zone *mz,
691 struct mem_cgroup_tree_per_zone *mctz)
bb4cc1a8 692{
0a31bc97
JW
693 unsigned long flags;
694
695 spin_lock_irqsave(&mctz->lock, flags);
cf2c8127 696 __mem_cgroup_remove_exceeded(mz, mctz);
0a31bc97 697 spin_unlock_irqrestore(&mctz->lock, flags);
bb4cc1a8
AM
698}
699
3e32cb2e
JW
700static unsigned long soft_limit_excess(struct mem_cgroup *memcg)
701{
702 unsigned long nr_pages = page_counter_read(&memcg->memory);
703 unsigned long soft_limit = ACCESS_ONCE(memcg->soft_limit);
704 unsigned long excess = 0;
705
706 if (nr_pages > soft_limit)
707 excess = nr_pages - soft_limit;
708
709 return excess;
710}
bb4cc1a8
AM
711
712static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
713{
3e32cb2e 714 unsigned long excess;
bb4cc1a8
AM
715 struct mem_cgroup_per_zone *mz;
716 struct mem_cgroup_tree_per_zone *mctz;
bb4cc1a8 717
e231875b 718 mctz = soft_limit_tree_from_page(page);
bb4cc1a8
AM
719 /*
720 * Necessary to update all ancestors when hierarchy is used.
721 * because their event counter is not touched.
722 */
723 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
e231875b 724 mz = mem_cgroup_page_zoneinfo(memcg, page);
3e32cb2e 725 excess = soft_limit_excess(memcg);
bb4cc1a8
AM
726 /*
727 * We have to update the tree if mz is on RB-tree or
728 * mem is over its softlimit.
729 */
730 if (excess || mz->on_tree) {
0a31bc97
JW
731 unsigned long flags;
732
733 spin_lock_irqsave(&mctz->lock, flags);
bb4cc1a8
AM
734 /* if on-tree, remove it */
735 if (mz->on_tree)
cf2c8127 736 __mem_cgroup_remove_exceeded(mz, mctz);
bb4cc1a8
AM
737 /*
738 * Insert again. mz->usage_in_excess will be updated.
739 * If excess is 0, no tree ops.
740 */
cf2c8127 741 __mem_cgroup_insert_exceeded(mz, mctz, excess);
0a31bc97 742 spin_unlock_irqrestore(&mctz->lock, flags);
bb4cc1a8
AM
743 }
744 }
745}
746
747static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
748{
bb4cc1a8 749 struct mem_cgroup_tree_per_zone *mctz;
e231875b
JZ
750 struct mem_cgroup_per_zone *mz;
751 int nid, zid;
bb4cc1a8 752
e231875b
JZ
753 for_each_node(nid) {
754 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
755 mz = &memcg->nodeinfo[nid]->zoneinfo[zid];
756 mctz = soft_limit_tree_node_zone(nid, zid);
cf2c8127 757 mem_cgroup_remove_exceeded(mz, mctz);
bb4cc1a8
AM
758 }
759 }
760}
761
762static struct mem_cgroup_per_zone *
763__mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
764{
765 struct rb_node *rightmost = NULL;
766 struct mem_cgroup_per_zone *mz;
767
768retry:
769 mz = NULL;
770 rightmost = rb_last(&mctz->rb_root);
771 if (!rightmost)
772 goto done; /* Nothing to reclaim from */
773
774 mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
775 /*
776 * Remove the node now but someone else can add it back,
777 * we will to add it back at the end of reclaim to its correct
778 * position in the tree.
779 */
cf2c8127 780 __mem_cgroup_remove_exceeded(mz, mctz);
3e32cb2e 781 if (!soft_limit_excess(mz->memcg) ||
ec903c0c 782 !css_tryget_online(&mz->memcg->css))
bb4cc1a8
AM
783 goto retry;
784done:
785 return mz;
786}
787
788static struct mem_cgroup_per_zone *
789mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
790{
791 struct mem_cgroup_per_zone *mz;
792
0a31bc97 793 spin_lock_irq(&mctz->lock);
bb4cc1a8 794 mz = __mem_cgroup_largest_soft_limit_node(mctz);
0a31bc97 795 spin_unlock_irq(&mctz->lock);
bb4cc1a8
AM
796 return mz;
797}
798
711d3d2c
KH
799/*
800 * Implementation Note: reading percpu statistics for memcg.
801 *
802 * Both of vmstat[] and percpu_counter has threshold and do periodic
803 * synchronization to implement "quick" read. There are trade-off between
804 * reading cost and precision of value. Then, we may have a chance to implement
805 * a periodic synchronizion of counter in memcg's counter.
806 *
807 * But this _read() function is used for user interface now. The user accounts
808 * memory usage by memory cgroup and he _always_ requires exact value because
809 * he accounts memory. Even if we provide quick-and-fuzzy read, we always
810 * have to visit all online cpus and make sum. So, for now, unnecessary
811 * synchronization is not implemented. (just implemented for cpu hotplug)
812 *
813 * If there are kernel internal actions which can make use of some not-exact
814 * value, and reading all cpu value can be performance bottleneck in some
815 * common workload, threashold and synchonization as vmstat[] should be
816 * implemented.
817 */
c0ff4b85 818static long mem_cgroup_read_stat(struct mem_cgroup *memcg,
7a159cc9 819 enum mem_cgroup_stat_index idx)
c62b1a3b 820{
7a159cc9 821 long val = 0;
c62b1a3b 822 int cpu;
c62b1a3b 823
711d3d2c
KH
824 get_online_cpus();
825 for_each_online_cpu(cpu)
c0ff4b85 826 val += per_cpu(memcg->stat->count[idx], cpu);
711d3d2c 827#ifdef CONFIG_HOTPLUG_CPU
c0ff4b85
R
828 spin_lock(&memcg->pcp_counter_lock);
829 val += memcg->nocpu_base.count[idx];
830 spin_unlock(&memcg->pcp_counter_lock);
711d3d2c
KH
831#endif
832 put_online_cpus();
c62b1a3b
KH
833 return val;
834}
835
c0ff4b85 836static unsigned long mem_cgroup_read_events(struct mem_cgroup *memcg,
e9f8974f
JW
837 enum mem_cgroup_events_index idx)
838{
839 unsigned long val = 0;
840 int cpu;
841
9c567512 842 get_online_cpus();
e9f8974f 843 for_each_online_cpu(cpu)
c0ff4b85 844 val += per_cpu(memcg->stat->events[idx], cpu);
e9f8974f 845#ifdef CONFIG_HOTPLUG_CPU
c0ff4b85
R
846 spin_lock(&memcg->pcp_counter_lock);
847 val += memcg->nocpu_base.events[idx];
848 spin_unlock(&memcg->pcp_counter_lock);
e9f8974f 849#endif
9c567512 850 put_online_cpus();
e9f8974f
JW
851 return val;
852}
853
c0ff4b85 854static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
b070e65c 855 struct page *page,
0a31bc97 856 int nr_pages)
d52aa412 857{
b2402857
KH
858 /*
859 * Here, RSS means 'mapped anon' and anon's SwapCache. Shmem/tmpfs is
860 * counted as CACHE even if it's on ANON LRU.
861 */
0a31bc97 862 if (PageAnon(page))
b2402857 863 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS],
c0ff4b85 864 nr_pages);
d52aa412 865 else
b2402857 866 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_CACHE],
c0ff4b85 867 nr_pages);
55e462b0 868
b070e65c
DR
869 if (PageTransHuge(page))
870 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS_HUGE],
871 nr_pages);
872
e401f176
KH
873 /* pagein of a big page is an event. So, ignore page size */
874 if (nr_pages > 0)
c0ff4b85 875 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGIN]);
3751d604 876 else {
c0ff4b85 877 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGOUT]);
3751d604
KH
878 nr_pages = -nr_pages; /* for event */
879 }
e401f176 880
13114716 881 __this_cpu_add(memcg->stat->nr_page_events, nr_pages);
6d12e2d8
KH
882}
883
e231875b 884unsigned long mem_cgroup_get_lru_size(struct lruvec *lruvec, enum lru_list lru)
074291fe
KK
885{
886 struct mem_cgroup_per_zone *mz;
887
888 mz = container_of(lruvec, struct mem_cgroup_per_zone, lruvec);
889 return mz->lru_size[lru];
890}
891
e231875b
JZ
892static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
893 int nid,
894 unsigned int lru_mask)
bb2a0de9 895{
e231875b 896 unsigned long nr = 0;
889976db
YH
897 int zid;
898
e231875b 899 VM_BUG_ON((unsigned)nid >= nr_node_ids);
bb2a0de9 900
e231875b
JZ
901 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
902 struct mem_cgroup_per_zone *mz;
903 enum lru_list lru;
904
905 for_each_lru(lru) {
906 if (!(BIT(lru) & lru_mask))
907 continue;
908 mz = &memcg->nodeinfo[nid]->zoneinfo[zid];
909 nr += mz->lru_size[lru];
910 }
911 }
912 return nr;
889976db 913}
bb2a0de9 914
c0ff4b85 915static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
bb2a0de9 916 unsigned int lru_mask)
6d12e2d8 917{
e231875b 918 unsigned long nr = 0;
889976db 919 int nid;
6d12e2d8 920
31aaea4a 921 for_each_node_state(nid, N_MEMORY)
e231875b
JZ
922 nr += mem_cgroup_node_nr_lru_pages(memcg, nid, lru_mask);
923 return nr;
d52aa412
KH
924}
925
f53d7ce3
JW
926static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
927 enum mem_cgroup_events_target target)
7a159cc9
JW
928{
929 unsigned long val, next;
930
13114716 931 val = __this_cpu_read(memcg->stat->nr_page_events);
4799401f 932 next = __this_cpu_read(memcg->stat->targets[target]);
7a159cc9 933 /* from time_after() in jiffies.h */
f53d7ce3
JW
934 if ((long)next - (long)val < 0) {
935 switch (target) {
936 case MEM_CGROUP_TARGET_THRESH:
937 next = val + THRESHOLDS_EVENTS_TARGET;
938 break;
bb4cc1a8
AM
939 case MEM_CGROUP_TARGET_SOFTLIMIT:
940 next = val + SOFTLIMIT_EVENTS_TARGET;
941 break;
f53d7ce3
JW
942 case MEM_CGROUP_TARGET_NUMAINFO:
943 next = val + NUMAINFO_EVENTS_TARGET;
944 break;
945 default:
946 break;
947 }
948 __this_cpu_write(memcg->stat->targets[target], next);
949 return true;
7a159cc9 950 }
f53d7ce3 951 return false;
d2265e6f
KH
952}
953
954/*
955 * Check events in order.
956 *
957 */
c0ff4b85 958static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
d2265e6f
KH
959{
960 /* threshold event is triggered in finer grain than soft limit */
f53d7ce3
JW
961 if (unlikely(mem_cgroup_event_ratelimit(memcg,
962 MEM_CGROUP_TARGET_THRESH))) {
bb4cc1a8 963 bool do_softlimit;
82b3f2a7 964 bool do_numainfo __maybe_unused;
f53d7ce3 965
bb4cc1a8
AM
966 do_softlimit = mem_cgroup_event_ratelimit(memcg,
967 MEM_CGROUP_TARGET_SOFTLIMIT);
f53d7ce3
JW
968#if MAX_NUMNODES > 1
969 do_numainfo = mem_cgroup_event_ratelimit(memcg,
970 MEM_CGROUP_TARGET_NUMAINFO);
971#endif
c0ff4b85 972 mem_cgroup_threshold(memcg);
bb4cc1a8
AM
973 if (unlikely(do_softlimit))
974 mem_cgroup_update_tree(memcg, page);
453a9bf3 975#if MAX_NUMNODES > 1
f53d7ce3 976 if (unlikely(do_numainfo))
c0ff4b85 977 atomic_inc(&memcg->numainfo_events);
453a9bf3 978#endif
0a31bc97 979 }
d2265e6f
KH
980}
981
cf475ad2 982struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
78fb7466 983{
31a78f23
BS
984 /*
985 * mm_update_next_owner() may clear mm->owner to NULL
986 * if it races with swapoff, page migration, etc.
987 * So this can be called with p == NULL.
988 */
989 if (unlikely(!p))
990 return NULL;
991
073219e9 992 return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
78fb7466
PE
993}
994
df381975 995static struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
54595fe2 996{
c0ff4b85 997 struct mem_cgroup *memcg = NULL;
0b7f569e 998
54595fe2
KH
999 rcu_read_lock();
1000 do {
6f6acb00
MH
1001 /*
1002 * Page cache insertions can happen withou an
1003 * actual mm context, e.g. during disk probing
1004 * on boot, loopback IO, acct() writes etc.
1005 */
1006 if (unlikely(!mm))
df381975 1007 memcg = root_mem_cgroup;
6f6acb00
MH
1008 else {
1009 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
1010 if (unlikely(!memcg))
1011 memcg = root_mem_cgroup;
1012 }
ec903c0c 1013 } while (!css_tryget_online(&memcg->css));
54595fe2 1014 rcu_read_unlock();
c0ff4b85 1015 return memcg;
54595fe2
KH
1016}
1017
5660048c
JW
1018/**
1019 * mem_cgroup_iter - iterate over memory cgroup hierarchy
1020 * @root: hierarchy root
1021 * @prev: previously returned memcg, NULL on first invocation
1022 * @reclaim: cookie for shared reclaim walks, NULL for full walks
1023 *
1024 * Returns references to children of the hierarchy below @root, or
1025 * @root itself, or %NULL after a full round-trip.
1026 *
1027 * Caller must pass the return value in @prev on subsequent
1028 * invocations for reference counting, or use mem_cgroup_iter_break()
1029 * to cancel a hierarchy walk before the round-trip is complete.
1030 *
1031 * Reclaimers can specify a zone and a priority level in @reclaim to
1032 * divide up the memcgs in the hierarchy among all concurrent
1033 * reclaimers operating on the same zone and priority.
1034 */
694fbc0f 1035struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
5660048c 1036 struct mem_cgroup *prev,
694fbc0f 1037 struct mem_cgroup_reclaim_cookie *reclaim)
14067bb3 1038{
5ac8fb31
JW
1039 struct reclaim_iter *uninitialized_var(iter);
1040 struct cgroup_subsys_state *css = NULL;
9f3a0d09 1041 struct mem_cgroup *memcg = NULL;
5ac8fb31 1042 struct mem_cgroup *pos = NULL;
711d3d2c 1043
694fbc0f
AM
1044 if (mem_cgroup_disabled())
1045 return NULL;
5660048c 1046
9f3a0d09
JW
1047 if (!root)
1048 root = root_mem_cgroup;
7d74b06f 1049
9f3a0d09 1050 if (prev && !reclaim)
5ac8fb31 1051 pos = prev;
14067bb3 1052
9f3a0d09
JW
1053 if (!root->use_hierarchy && root != root_mem_cgroup) {
1054 if (prev)
5ac8fb31 1055 goto out;
694fbc0f 1056 return root;
9f3a0d09 1057 }
14067bb3 1058
542f85f9 1059 rcu_read_lock();
5f578161 1060
5ac8fb31
JW
1061 if (reclaim) {
1062 struct mem_cgroup_per_zone *mz;
1063
1064 mz = mem_cgroup_zone_zoneinfo(root, reclaim->zone);
1065 iter = &mz->iter[reclaim->priority];
1066
1067 if (prev && reclaim->generation != iter->generation)
1068 goto out_unlock;
1069
1070 do {
1071 pos = ACCESS_ONCE(iter->position);
1072 /*
1073 * A racing update may change the position and
1074 * put the last reference, hence css_tryget(),
1075 * or retry to see the updated position.
1076 */
1077 } while (pos && !css_tryget(&pos->css));
1078 }
1079
1080 if (pos)
1081 css = &pos->css;
1082
1083 for (;;) {
1084 css = css_next_descendant_pre(css, &root->css);
1085 if (!css) {
1086 /*
1087 * Reclaimers share the hierarchy walk, and a
1088 * new one might jump in right at the end of
1089 * the hierarchy - make sure they see at least
1090 * one group and restart from the beginning.
1091 */
1092 if (!prev)
1093 continue;
1094 break;
527a5ec9 1095 }
7d74b06f 1096
5ac8fb31
JW
1097 /*
1098 * Verify the css and acquire a reference. The root
1099 * is provided by the caller, so we know it's alive
1100 * and kicking, and don't take an extra reference.
1101 */
1102 memcg = mem_cgroup_from_css(css);
14067bb3 1103
5ac8fb31
JW
1104 if (css == &root->css)
1105 break;
14067bb3 1106
b2052564 1107 if (css_tryget(css)) {
5ac8fb31
JW
1108 /*
1109 * Make sure the memcg is initialized:
1110 * mem_cgroup_css_online() orders the the
1111 * initialization against setting the flag.
1112 */
1113 if (smp_load_acquire(&memcg->initialized))
1114 break;
542f85f9 1115
5ac8fb31 1116 css_put(css);
527a5ec9 1117 }
9f3a0d09 1118
5ac8fb31 1119 memcg = NULL;
9f3a0d09 1120 }
5ac8fb31
JW
1121
1122 if (reclaim) {
1123 if (cmpxchg(&iter->position, pos, memcg) == pos) {
1124 if (memcg)
1125 css_get(&memcg->css);
1126 if (pos)
1127 css_put(&pos->css);
1128 }
1129
1130 /*
1131 * pairs with css_tryget when dereferencing iter->position
1132 * above.
1133 */
1134 if (pos)
1135 css_put(&pos->css);
1136
1137 if (!memcg)
1138 iter->generation++;
1139 else if (!prev)
1140 reclaim->generation = iter->generation;
9f3a0d09 1141 }
5ac8fb31 1142
542f85f9
MH
1143out_unlock:
1144 rcu_read_unlock();
5ac8fb31 1145out:
c40046f3
MH
1146 if (prev && prev != root)
1147 css_put(&prev->css);
1148
9f3a0d09 1149 return memcg;
14067bb3 1150}
7d74b06f 1151
5660048c
JW
1152/**
1153 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1154 * @root: hierarchy root
1155 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1156 */
1157void mem_cgroup_iter_break(struct mem_cgroup *root,
1158 struct mem_cgroup *prev)
9f3a0d09
JW
1159{
1160 if (!root)
1161 root = root_mem_cgroup;
1162 if (prev && prev != root)
1163 css_put(&prev->css);
1164}
7d74b06f 1165
9f3a0d09
JW
1166/*
1167 * Iteration constructs for visiting all cgroups (under a tree). If
1168 * loops are exited prematurely (break), mem_cgroup_iter_break() must
1169 * be used for reference counting.
1170 */
1171#define for_each_mem_cgroup_tree(iter, root) \
527a5ec9 1172 for (iter = mem_cgroup_iter(root, NULL, NULL); \
9f3a0d09 1173 iter != NULL; \
527a5ec9 1174 iter = mem_cgroup_iter(root, iter, NULL))
711d3d2c 1175
9f3a0d09 1176#define for_each_mem_cgroup(iter) \
527a5ec9 1177 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
9f3a0d09 1178 iter != NULL; \
527a5ec9 1179 iter = mem_cgroup_iter(NULL, iter, NULL))
14067bb3 1180
68ae564b 1181void __mem_cgroup_count_vm_event(struct mm_struct *mm, enum vm_event_item idx)
456f998e 1182{
c0ff4b85 1183 struct mem_cgroup *memcg;
456f998e 1184
456f998e 1185 rcu_read_lock();
c0ff4b85
R
1186 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
1187 if (unlikely(!memcg))
456f998e
YH
1188 goto out;
1189
1190 switch (idx) {
456f998e 1191 case PGFAULT:
0e574a93
JW
1192 this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGFAULT]);
1193 break;
1194 case PGMAJFAULT:
1195 this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGMAJFAULT]);
456f998e
YH
1196 break;
1197 default:
1198 BUG();
1199 }
1200out:
1201 rcu_read_unlock();
1202}
68ae564b 1203EXPORT_SYMBOL(__mem_cgroup_count_vm_event);
456f998e 1204
925b7673
JW
1205/**
1206 * mem_cgroup_zone_lruvec - get the lru list vector for a zone and memcg
1207 * @zone: zone of the wanted lruvec
fa9add64 1208 * @memcg: memcg of the wanted lruvec
925b7673
JW
1209 *
1210 * Returns the lru list vector holding pages for the given @zone and
1211 * @mem. This can be the global zone lruvec, if the memory controller
1212 * is disabled.
1213 */
1214struct lruvec *mem_cgroup_zone_lruvec(struct zone *zone,
1215 struct mem_cgroup *memcg)
1216{
1217 struct mem_cgroup_per_zone *mz;
bea8c150 1218 struct lruvec *lruvec;
925b7673 1219
bea8c150
HD
1220 if (mem_cgroup_disabled()) {
1221 lruvec = &zone->lruvec;
1222 goto out;
1223 }
925b7673 1224
e231875b 1225 mz = mem_cgroup_zone_zoneinfo(memcg, zone);
bea8c150
HD
1226 lruvec = &mz->lruvec;
1227out:
1228 /*
1229 * Since a node can be onlined after the mem_cgroup was created,
1230 * we have to be prepared to initialize lruvec->zone here;
1231 * and if offlined then reonlined, we need to reinitialize it.
1232 */
1233 if (unlikely(lruvec->zone != zone))
1234 lruvec->zone = zone;
1235 return lruvec;
925b7673
JW
1236}
1237
925b7673 1238/**
dfe0e773 1239 * mem_cgroup_page_lruvec - return lruvec for isolating/putting an LRU page
925b7673 1240 * @page: the page
fa9add64 1241 * @zone: zone of the page
dfe0e773
JW
1242 *
1243 * This function is only safe when following the LRU page isolation
1244 * and putback protocol: the LRU lock must be held, and the page must
1245 * either be PageLRU() or the caller must have isolated/allocated it.
925b7673 1246 */
fa9add64 1247struct lruvec *mem_cgroup_page_lruvec(struct page *page, struct zone *zone)
08e552c6 1248{
08e552c6 1249 struct mem_cgroup_per_zone *mz;
925b7673 1250 struct mem_cgroup *memcg;
bea8c150 1251 struct lruvec *lruvec;
6d12e2d8 1252
bea8c150
HD
1253 if (mem_cgroup_disabled()) {
1254 lruvec = &zone->lruvec;
1255 goto out;
1256 }
925b7673 1257
1306a85a 1258 memcg = page->mem_cgroup;
7512102c 1259 /*
dfe0e773 1260 * Swapcache readahead pages are added to the LRU - and
29833315 1261 * possibly migrated - before they are charged.
7512102c 1262 */
29833315
JW
1263 if (!memcg)
1264 memcg = root_mem_cgroup;
7512102c 1265
e231875b 1266 mz = mem_cgroup_page_zoneinfo(memcg, page);
bea8c150
HD
1267 lruvec = &mz->lruvec;
1268out:
1269 /*
1270 * Since a node can be onlined after the mem_cgroup was created,
1271 * we have to be prepared to initialize lruvec->zone here;
1272 * and if offlined then reonlined, we need to reinitialize it.
1273 */
1274 if (unlikely(lruvec->zone != zone))
1275 lruvec->zone = zone;
1276 return lruvec;
08e552c6 1277}
b69408e8 1278
925b7673 1279/**
fa9add64
HD
1280 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1281 * @lruvec: mem_cgroup per zone lru vector
1282 * @lru: index of lru list the page is sitting on
1283 * @nr_pages: positive when adding or negative when removing
925b7673 1284 *
fa9add64
HD
1285 * This function must be called when a page is added to or removed from an
1286 * lru list.
3f58a829 1287 */
fa9add64
HD
1288void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
1289 int nr_pages)
3f58a829
MK
1290{
1291 struct mem_cgroup_per_zone *mz;
fa9add64 1292 unsigned long *lru_size;
3f58a829
MK
1293
1294 if (mem_cgroup_disabled())
1295 return;
1296
fa9add64
HD
1297 mz = container_of(lruvec, struct mem_cgroup_per_zone, lruvec);
1298 lru_size = mz->lru_size + lru;
1299 *lru_size += nr_pages;
1300 VM_BUG_ON((long)(*lru_size) < 0);
08e552c6 1301}
544122e5 1302
2314b42d 1303bool mem_cgroup_is_descendant(struct mem_cgroup *memcg, struct mem_cgroup *root)
3e92041d 1304{
2314b42d 1305 if (root == memcg)
91c63734 1306 return true;
2314b42d 1307 if (!root->use_hierarchy)
91c63734 1308 return false;
2314b42d 1309 return cgroup_is_descendant(memcg->css.cgroup, root->css.cgroup);
c3ac9a8a
JW
1310}
1311
2314b42d 1312bool task_in_mem_cgroup(struct task_struct *task, struct mem_cgroup *memcg)
c3ac9a8a 1313{
2314b42d 1314 struct mem_cgroup *task_memcg;
158e0a2d 1315 struct task_struct *p;
ffbdccf5 1316 bool ret;
4c4a2214 1317
158e0a2d 1318 p = find_lock_task_mm(task);
de077d22 1319 if (p) {
2314b42d 1320 task_memcg = get_mem_cgroup_from_mm(p->mm);
de077d22
DR
1321 task_unlock(p);
1322 } else {
1323 /*
1324 * All threads may have already detached their mm's, but the oom
1325 * killer still needs to detect if they have already been oom
1326 * killed to prevent needlessly killing additional tasks.
1327 */
ffbdccf5 1328 rcu_read_lock();
2314b42d
JW
1329 task_memcg = mem_cgroup_from_task(task);
1330 css_get(&task_memcg->css);
ffbdccf5 1331 rcu_read_unlock();
de077d22 1332 }
2314b42d
JW
1333 ret = mem_cgroup_is_descendant(task_memcg, memcg);
1334 css_put(&task_memcg->css);
4c4a2214
DR
1335 return ret;
1336}
1337
c56d5c7d 1338int mem_cgroup_inactive_anon_is_low(struct lruvec *lruvec)
14797e23 1339{
9b272977 1340 unsigned long inactive_ratio;
14797e23 1341 unsigned long inactive;
9b272977 1342 unsigned long active;
c772be93 1343 unsigned long gb;
14797e23 1344
4d7dcca2
HD
1345 inactive = mem_cgroup_get_lru_size(lruvec, LRU_INACTIVE_ANON);
1346 active = mem_cgroup_get_lru_size(lruvec, LRU_ACTIVE_ANON);
14797e23 1347
c772be93
KM
1348 gb = (inactive + active) >> (30 - PAGE_SHIFT);
1349 if (gb)
1350 inactive_ratio = int_sqrt(10 * gb);
1351 else
1352 inactive_ratio = 1;
1353
9b272977 1354 return inactive * inactive_ratio < active;
14797e23
KM
1355}
1356
90cbc250
VD
1357bool mem_cgroup_lruvec_online(struct lruvec *lruvec)
1358{
1359 struct mem_cgroup_per_zone *mz;
1360 struct mem_cgroup *memcg;
1361
1362 if (mem_cgroup_disabled())
1363 return true;
1364
1365 mz = container_of(lruvec, struct mem_cgroup_per_zone, lruvec);
1366 memcg = mz->memcg;
1367
1368 return !!(memcg->css.flags & CSS_ONLINE);
1369}
1370
3e32cb2e 1371#define mem_cgroup_from_counter(counter, member) \
6d61ef40
BS
1372 container_of(counter, struct mem_cgroup, member)
1373
19942822 1374/**
9d11ea9f 1375 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
dad7557e 1376 * @memcg: the memory cgroup
19942822 1377 *
9d11ea9f 1378 * Returns the maximum amount of memory @mem can be charged with, in
7ec99d62 1379 * pages.
19942822 1380 */
c0ff4b85 1381static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
19942822 1382{
3e32cb2e
JW
1383 unsigned long margin = 0;
1384 unsigned long count;
1385 unsigned long limit;
9d11ea9f 1386
3e32cb2e
JW
1387 count = page_counter_read(&memcg->memory);
1388 limit = ACCESS_ONCE(memcg->memory.limit);
1389 if (count < limit)
1390 margin = limit - count;
1391
1392 if (do_swap_account) {
1393 count = page_counter_read(&memcg->memsw);
1394 limit = ACCESS_ONCE(memcg->memsw.limit);
1395 if (count <= limit)
1396 margin = min(margin, limit - count);
1397 }
1398
1399 return margin;
19942822
JW
1400}
1401
1f4c025b 1402int mem_cgroup_swappiness(struct mem_cgroup *memcg)
a7885eb8 1403{
a7885eb8 1404 /* root ? */
14208b0e 1405 if (mem_cgroup_disabled() || !memcg->css.parent)
a7885eb8
KM
1406 return vm_swappiness;
1407
bf1ff263 1408 return memcg->swappiness;
a7885eb8
KM
1409}
1410
32047e2a 1411/*
bdcbb659 1412 * A routine for checking "mem" is under move_account() or not.
32047e2a 1413 *
bdcbb659
QH
1414 * Checking a cgroup is mc.from or mc.to or under hierarchy of
1415 * moving cgroups. This is for waiting at high-memory pressure
1416 * caused by "move".
32047e2a 1417 */
c0ff4b85 1418static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
4b534334 1419{
2bd9bb20
KH
1420 struct mem_cgroup *from;
1421 struct mem_cgroup *to;
4b534334 1422 bool ret = false;
2bd9bb20
KH
1423 /*
1424 * Unlike task_move routines, we access mc.to, mc.from not under
1425 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1426 */
1427 spin_lock(&mc.lock);
1428 from = mc.from;
1429 to = mc.to;
1430 if (!from)
1431 goto unlock;
3e92041d 1432
2314b42d
JW
1433 ret = mem_cgroup_is_descendant(from, memcg) ||
1434 mem_cgroup_is_descendant(to, memcg);
2bd9bb20
KH
1435unlock:
1436 spin_unlock(&mc.lock);
4b534334
KH
1437 return ret;
1438}
1439
c0ff4b85 1440static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
4b534334
KH
1441{
1442 if (mc.moving_task && current != mc.moving_task) {
c0ff4b85 1443 if (mem_cgroup_under_move(memcg)) {
4b534334
KH
1444 DEFINE_WAIT(wait);
1445 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1446 /* moving charge context might have finished. */
1447 if (mc.moving_task)
1448 schedule();
1449 finish_wait(&mc.waitq, &wait);
1450 return true;
1451 }
1452 }
1453 return false;
1454}
1455
58cf188e 1456#define K(x) ((x) << (PAGE_SHIFT-10))
e222432b 1457/**
58cf188e 1458 * mem_cgroup_print_oom_info: Print OOM information relevant to memory controller.
e222432b
BS
1459 * @memcg: The memory cgroup that went over limit
1460 * @p: Task that is going to be killed
1461 *
1462 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1463 * enabled
1464 */
1465void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1466{
e61734c5 1467 /* oom_info_lock ensures that parallel ooms do not interleave */
08088cb9 1468 static DEFINE_MUTEX(oom_info_lock);
58cf188e
SZ
1469 struct mem_cgroup *iter;
1470 unsigned int i;
e222432b 1471
58cf188e 1472 if (!p)
e222432b
BS
1473 return;
1474
08088cb9 1475 mutex_lock(&oom_info_lock);
e222432b
BS
1476 rcu_read_lock();
1477
e61734c5
TH
1478 pr_info("Task in ");
1479 pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
0346dadb 1480 pr_cont(" killed as a result of limit of ");
e61734c5 1481 pr_cont_cgroup_path(memcg->css.cgroup);
0346dadb 1482 pr_cont("\n");
e222432b 1483
e222432b
BS
1484 rcu_read_unlock();
1485
3e32cb2e
JW
1486 pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
1487 K((u64)page_counter_read(&memcg->memory)),
1488 K((u64)memcg->memory.limit), memcg->memory.failcnt);
1489 pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
1490 K((u64)page_counter_read(&memcg->memsw)),
1491 K((u64)memcg->memsw.limit), memcg->memsw.failcnt);
1492 pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
1493 K((u64)page_counter_read(&memcg->kmem)),
1494 K((u64)memcg->kmem.limit), memcg->kmem.failcnt);
58cf188e
SZ
1495
1496 for_each_mem_cgroup_tree(iter, memcg) {
e61734c5
TH
1497 pr_info("Memory cgroup stats for ");
1498 pr_cont_cgroup_path(iter->css.cgroup);
58cf188e
SZ
1499 pr_cont(":");
1500
1501 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
1502 if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
1503 continue;
1504 pr_cont(" %s:%ldKB", mem_cgroup_stat_names[i],
1505 K(mem_cgroup_read_stat(iter, i)));
1506 }
1507
1508 for (i = 0; i < NR_LRU_LISTS; i++)
1509 pr_cont(" %s:%luKB", mem_cgroup_lru_names[i],
1510 K(mem_cgroup_nr_lru_pages(iter, BIT(i))));
1511
1512 pr_cont("\n");
1513 }
08088cb9 1514 mutex_unlock(&oom_info_lock);
e222432b
BS
1515}
1516
81d39c20
KH
1517/*
1518 * This function returns the number of memcg under hierarchy tree. Returns
1519 * 1(self count) if no children.
1520 */
c0ff4b85 1521static int mem_cgroup_count_children(struct mem_cgroup *memcg)
81d39c20
KH
1522{
1523 int num = 0;
7d74b06f
KH
1524 struct mem_cgroup *iter;
1525
c0ff4b85 1526 for_each_mem_cgroup_tree(iter, memcg)
7d74b06f 1527 num++;
81d39c20
KH
1528 return num;
1529}
1530
a63d83f4
DR
1531/*
1532 * Return the memory (and swap, if configured) limit for a memcg.
1533 */
3e32cb2e 1534static unsigned long mem_cgroup_get_limit(struct mem_cgroup *memcg)
a63d83f4 1535{
3e32cb2e 1536 unsigned long limit;
f3e8eb70 1537
3e32cb2e 1538 limit = memcg->memory.limit;
9a5a8f19 1539 if (mem_cgroup_swappiness(memcg)) {
3e32cb2e 1540 unsigned long memsw_limit;
9a5a8f19 1541
3e32cb2e
JW
1542 memsw_limit = memcg->memsw.limit;
1543 limit = min(limit + total_swap_pages, memsw_limit);
9a5a8f19 1544 }
9a5a8f19 1545 return limit;
a63d83f4
DR
1546}
1547
19965460
DR
1548static void mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
1549 int order)
9cbb78bb
DR
1550{
1551 struct mem_cgroup *iter;
1552 unsigned long chosen_points = 0;
1553 unsigned long totalpages;
1554 unsigned int points = 0;
1555 struct task_struct *chosen = NULL;
1556
876aafbf 1557 /*
465adcf1
DR
1558 * If current has a pending SIGKILL or is exiting, then automatically
1559 * select it. The goal is to allow it to allocate so that it may
1560 * quickly exit and free its memory.
876aafbf 1561 */
d003f371 1562 if (fatal_signal_pending(current) || task_will_free_mem(current)) {
49550b60 1563 mark_tsk_oom_victim(current);
876aafbf
DR
1564 return;
1565 }
1566
1567 check_panic_on_oom(CONSTRAINT_MEMCG, gfp_mask, order, NULL);
3e32cb2e 1568 totalpages = mem_cgroup_get_limit(memcg) ? : 1;
9cbb78bb 1569 for_each_mem_cgroup_tree(iter, memcg) {
72ec7029 1570 struct css_task_iter it;
9cbb78bb
DR
1571 struct task_struct *task;
1572
72ec7029
TH
1573 css_task_iter_start(&iter->css, &it);
1574 while ((task = css_task_iter_next(&it))) {
9cbb78bb
DR
1575 switch (oom_scan_process_thread(task, totalpages, NULL,
1576 false)) {
1577 case OOM_SCAN_SELECT:
1578 if (chosen)
1579 put_task_struct(chosen);
1580 chosen = task;
1581 chosen_points = ULONG_MAX;
1582 get_task_struct(chosen);
1583 /* fall through */
1584 case OOM_SCAN_CONTINUE:
1585 continue;
1586 case OOM_SCAN_ABORT:
72ec7029 1587 css_task_iter_end(&it);
9cbb78bb
DR
1588 mem_cgroup_iter_break(memcg, iter);
1589 if (chosen)
1590 put_task_struct(chosen);
1591 return;
1592 case OOM_SCAN_OK:
1593 break;
1594 };
1595 points = oom_badness(task, memcg, NULL, totalpages);
d49ad935
DR
1596 if (!points || points < chosen_points)
1597 continue;
1598 /* Prefer thread group leaders for display purposes */
1599 if (points == chosen_points &&
1600 thread_group_leader(chosen))
1601 continue;
1602
1603 if (chosen)
1604 put_task_struct(chosen);
1605 chosen = task;
1606 chosen_points = points;
1607 get_task_struct(chosen);
9cbb78bb 1608 }
72ec7029 1609 css_task_iter_end(&it);
9cbb78bb
DR
1610 }
1611
1612 if (!chosen)
1613 return;
1614 points = chosen_points * 1000 / totalpages;
9cbb78bb
DR
1615 oom_kill_process(chosen, gfp_mask, order, points, totalpages, memcg,
1616 NULL, "Memory cgroup out of memory");
9cbb78bb
DR
1617}
1618
ae6e71d3
MC
1619#if MAX_NUMNODES > 1
1620
4d0c066d
KH
1621/**
1622 * test_mem_cgroup_node_reclaimable
dad7557e 1623 * @memcg: the target memcg
4d0c066d
KH
1624 * @nid: the node ID to be checked.
1625 * @noswap : specify true here if the user wants flle only information.
1626 *
1627 * This function returns whether the specified memcg contains any
1628 * reclaimable pages on a node. Returns true if there are any reclaimable
1629 * pages in the node.
1630 */
c0ff4b85 1631static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *memcg,
4d0c066d
KH
1632 int nid, bool noswap)
1633{
c0ff4b85 1634 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_FILE))
4d0c066d
KH
1635 return true;
1636 if (noswap || !total_swap_pages)
1637 return false;
c0ff4b85 1638 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_ANON))
4d0c066d
KH
1639 return true;
1640 return false;
1641
1642}
889976db
YH
1643
1644/*
1645 * Always updating the nodemask is not very good - even if we have an empty
1646 * list or the wrong list here, we can start from some node and traverse all
1647 * nodes based on the zonelist. So update the list loosely once per 10 secs.
1648 *
1649 */
c0ff4b85 1650static void mem_cgroup_may_update_nodemask(struct mem_cgroup *memcg)
889976db
YH
1651{
1652 int nid;
453a9bf3
KH
1653 /*
1654 * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
1655 * pagein/pageout changes since the last update.
1656 */
c0ff4b85 1657 if (!atomic_read(&memcg->numainfo_events))
453a9bf3 1658 return;
c0ff4b85 1659 if (atomic_inc_return(&memcg->numainfo_updating) > 1)
889976db
YH
1660 return;
1661
889976db 1662 /* make a nodemask where this memcg uses memory from */
31aaea4a 1663 memcg->scan_nodes = node_states[N_MEMORY];
889976db 1664
31aaea4a 1665 for_each_node_mask(nid, node_states[N_MEMORY]) {
889976db 1666
c0ff4b85
R
1667 if (!test_mem_cgroup_node_reclaimable(memcg, nid, false))
1668 node_clear(nid, memcg->scan_nodes);
889976db 1669 }
453a9bf3 1670
c0ff4b85
R
1671 atomic_set(&memcg->numainfo_events, 0);
1672 atomic_set(&memcg->numainfo_updating, 0);
889976db
YH
1673}
1674
1675/*
1676 * Selecting a node where we start reclaim from. Because what we need is just
1677 * reducing usage counter, start from anywhere is O,K. Considering
1678 * memory reclaim from current node, there are pros. and cons.
1679 *
1680 * Freeing memory from current node means freeing memory from a node which
1681 * we'll use or we've used. So, it may make LRU bad. And if several threads
1682 * hit limits, it will see a contention on a node. But freeing from remote
1683 * node means more costs for memory reclaim because of memory latency.
1684 *
1685 * Now, we use round-robin. Better algorithm is welcomed.
1686 */
c0ff4b85 1687int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
889976db
YH
1688{
1689 int node;
1690
c0ff4b85
R
1691 mem_cgroup_may_update_nodemask(memcg);
1692 node = memcg->last_scanned_node;
889976db 1693
c0ff4b85 1694 node = next_node(node, memcg->scan_nodes);
889976db 1695 if (node == MAX_NUMNODES)
c0ff4b85 1696 node = first_node(memcg->scan_nodes);
889976db
YH
1697 /*
1698 * We call this when we hit limit, not when pages are added to LRU.
1699 * No LRU may hold pages because all pages are UNEVICTABLE or
1700 * memcg is too small and all pages are not on LRU. In that case,
1701 * we use curret node.
1702 */
1703 if (unlikely(node == MAX_NUMNODES))
1704 node = numa_node_id();
1705
c0ff4b85 1706 memcg->last_scanned_node = node;
889976db
YH
1707 return node;
1708}
889976db 1709#else
c0ff4b85 1710int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
889976db
YH
1711{
1712 return 0;
1713}
1714#endif
1715
0608f43d
AM
1716static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
1717 struct zone *zone,
1718 gfp_t gfp_mask,
1719 unsigned long *total_scanned)
1720{
1721 struct mem_cgroup *victim = NULL;
1722 int total = 0;
1723 int loop = 0;
1724 unsigned long excess;
1725 unsigned long nr_scanned;
1726 struct mem_cgroup_reclaim_cookie reclaim = {
1727 .zone = zone,
1728 .priority = 0,
1729 };
1730
3e32cb2e 1731 excess = soft_limit_excess(root_memcg);
0608f43d
AM
1732
1733 while (1) {
1734 victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
1735 if (!victim) {
1736 loop++;
1737 if (loop >= 2) {
1738 /*
1739 * If we have not been able to reclaim
1740 * anything, it might because there are
1741 * no reclaimable pages under this hierarchy
1742 */
1743 if (!total)
1744 break;
1745 /*
1746 * We want to do more targeted reclaim.
1747 * excess >> 2 is not to excessive so as to
1748 * reclaim too much, nor too less that we keep
1749 * coming back to reclaim from this cgroup
1750 */
1751 if (total >= (excess >> 2) ||
1752 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
1753 break;
1754 }
1755 continue;
1756 }
0608f43d
AM
1757 total += mem_cgroup_shrink_node_zone(victim, gfp_mask, false,
1758 zone, &nr_scanned);
1759 *total_scanned += nr_scanned;
3e32cb2e 1760 if (!soft_limit_excess(root_memcg))
0608f43d 1761 break;
6d61ef40 1762 }
0608f43d
AM
1763 mem_cgroup_iter_break(root_memcg, victim);
1764 return total;
6d61ef40
BS
1765}
1766
0056f4e6
JW
1767#ifdef CONFIG_LOCKDEP
1768static struct lockdep_map memcg_oom_lock_dep_map = {
1769 .name = "memcg_oom_lock",
1770};
1771#endif
1772
fb2a6fc5
JW
1773static DEFINE_SPINLOCK(memcg_oom_lock);
1774
867578cb
KH
1775/*
1776 * Check OOM-Killer is already running under our hierarchy.
1777 * If someone is running, return false.
1778 */
fb2a6fc5 1779static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
867578cb 1780{
79dfdacc 1781 struct mem_cgroup *iter, *failed = NULL;
a636b327 1782
fb2a6fc5
JW
1783 spin_lock(&memcg_oom_lock);
1784
9f3a0d09 1785 for_each_mem_cgroup_tree(iter, memcg) {
23751be0 1786 if (iter->oom_lock) {
79dfdacc
MH
1787 /*
1788 * this subtree of our hierarchy is already locked
1789 * so we cannot give a lock.
1790 */
79dfdacc 1791 failed = iter;
9f3a0d09
JW
1792 mem_cgroup_iter_break(memcg, iter);
1793 break;
23751be0
JW
1794 } else
1795 iter->oom_lock = true;
7d74b06f 1796 }
867578cb 1797
fb2a6fc5
JW
1798 if (failed) {
1799 /*
1800 * OK, we failed to lock the whole subtree so we have
1801 * to clean up what we set up to the failing subtree
1802 */
1803 for_each_mem_cgroup_tree(iter, memcg) {
1804 if (iter == failed) {
1805 mem_cgroup_iter_break(memcg, iter);
1806 break;
1807 }
1808 iter->oom_lock = false;
79dfdacc 1809 }
0056f4e6
JW
1810 } else
1811 mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_);
fb2a6fc5
JW
1812
1813 spin_unlock(&memcg_oom_lock);
1814
1815 return !failed;
a636b327 1816}
0b7f569e 1817
fb2a6fc5 1818static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
0b7f569e 1819{
7d74b06f
KH
1820 struct mem_cgroup *iter;
1821
fb2a6fc5 1822 spin_lock(&memcg_oom_lock);
0056f4e6 1823 mutex_release(&memcg_oom_lock_dep_map, 1, _RET_IP_);
c0ff4b85 1824 for_each_mem_cgroup_tree(iter, memcg)
79dfdacc 1825 iter->oom_lock = false;
fb2a6fc5 1826 spin_unlock(&memcg_oom_lock);
79dfdacc
MH
1827}
1828
c0ff4b85 1829static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
79dfdacc
MH
1830{
1831 struct mem_cgroup *iter;
1832
c0ff4b85 1833 for_each_mem_cgroup_tree(iter, memcg)
79dfdacc
MH
1834 atomic_inc(&iter->under_oom);
1835}
1836
c0ff4b85 1837static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
79dfdacc
MH
1838{
1839 struct mem_cgroup *iter;
1840
867578cb
KH
1841 /*
1842 * When a new child is created while the hierarchy is under oom,
1843 * mem_cgroup_oom_lock() may not be called. We have to use
1844 * atomic_add_unless() here.
1845 */
c0ff4b85 1846 for_each_mem_cgroup_tree(iter, memcg)
79dfdacc 1847 atomic_add_unless(&iter->under_oom, -1, 0);
0b7f569e
KH
1848}
1849
867578cb
KH
1850static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1851
dc98df5a 1852struct oom_wait_info {
d79154bb 1853 struct mem_cgroup *memcg;
dc98df5a
KH
1854 wait_queue_t wait;
1855};
1856
1857static int memcg_oom_wake_function(wait_queue_t *wait,
1858 unsigned mode, int sync, void *arg)
1859{
d79154bb
HD
1860 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
1861 struct mem_cgroup *oom_wait_memcg;
dc98df5a
KH
1862 struct oom_wait_info *oom_wait_info;
1863
1864 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
d79154bb 1865 oom_wait_memcg = oom_wait_info->memcg;
dc98df5a 1866
2314b42d
JW
1867 if (!mem_cgroup_is_descendant(wake_memcg, oom_wait_memcg) &&
1868 !mem_cgroup_is_descendant(oom_wait_memcg, wake_memcg))
dc98df5a 1869 return 0;
dc98df5a
KH
1870 return autoremove_wake_function(wait, mode, sync, arg);
1871}
1872
c0ff4b85 1873static void memcg_wakeup_oom(struct mem_cgroup *memcg)
dc98df5a 1874{
3812c8c8 1875 atomic_inc(&memcg->oom_wakeups);
c0ff4b85
R
1876 /* for filtering, pass "memcg" as argument. */
1877 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
dc98df5a
KH
1878}
1879
c0ff4b85 1880static void memcg_oom_recover(struct mem_cgroup *memcg)
3c11ecf4 1881{
c0ff4b85
R
1882 if (memcg && atomic_read(&memcg->under_oom))
1883 memcg_wakeup_oom(memcg);
3c11ecf4
KH
1884}
1885
3812c8c8 1886static void mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
0b7f569e 1887{
3812c8c8
JW
1888 if (!current->memcg_oom.may_oom)
1889 return;
867578cb 1890 /*
49426420
JW
1891 * We are in the middle of the charge context here, so we
1892 * don't want to block when potentially sitting on a callstack
1893 * that holds all kinds of filesystem and mm locks.
1894 *
1895 * Also, the caller may handle a failed allocation gracefully
1896 * (like optional page cache readahead) and so an OOM killer
1897 * invocation might not even be necessary.
1898 *
1899 * That's why we don't do anything here except remember the
1900 * OOM context and then deal with it at the end of the page
1901 * fault when the stack is unwound, the locks are released,
1902 * and when we know whether the fault was overall successful.
867578cb 1903 */
49426420
JW
1904 css_get(&memcg->css);
1905 current->memcg_oom.memcg = memcg;
1906 current->memcg_oom.gfp_mask = mask;
1907 current->memcg_oom.order = order;
3812c8c8
JW
1908}
1909
1910/**
1911 * mem_cgroup_oom_synchronize - complete memcg OOM handling
49426420 1912 * @handle: actually kill/wait or just clean up the OOM state
3812c8c8 1913 *
49426420
JW
1914 * This has to be called at the end of a page fault if the memcg OOM
1915 * handler was enabled.
3812c8c8 1916 *
49426420 1917 * Memcg supports userspace OOM handling where failed allocations must
3812c8c8
JW
1918 * sleep on a waitqueue until the userspace task resolves the
1919 * situation. Sleeping directly in the charge context with all kinds
1920 * of locks held is not a good idea, instead we remember an OOM state
1921 * in the task and mem_cgroup_oom_synchronize() has to be called at
49426420 1922 * the end of the page fault to complete the OOM handling.
3812c8c8
JW
1923 *
1924 * Returns %true if an ongoing memcg OOM situation was detected and
49426420 1925 * completed, %false otherwise.
3812c8c8 1926 */
49426420 1927bool mem_cgroup_oom_synchronize(bool handle)
3812c8c8 1928{
49426420 1929 struct mem_cgroup *memcg = current->memcg_oom.memcg;
3812c8c8 1930 struct oom_wait_info owait;
49426420 1931 bool locked;
3812c8c8
JW
1932
1933 /* OOM is global, do not handle */
3812c8c8 1934 if (!memcg)
49426420 1935 return false;
3812c8c8 1936
c32b3cbe 1937 if (!handle || oom_killer_disabled)
49426420 1938 goto cleanup;
3812c8c8
JW
1939
1940 owait.memcg = memcg;
1941 owait.wait.flags = 0;
1942 owait.wait.func = memcg_oom_wake_function;
1943 owait.wait.private = current;
1944 INIT_LIST_HEAD(&owait.wait.task_list);
867578cb 1945
3812c8c8 1946 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
49426420
JW
1947 mem_cgroup_mark_under_oom(memcg);
1948
1949 locked = mem_cgroup_oom_trylock(memcg);
1950
1951 if (locked)
1952 mem_cgroup_oom_notify(memcg);
1953
1954 if (locked && !memcg->oom_kill_disable) {
1955 mem_cgroup_unmark_under_oom(memcg);
1956 finish_wait(&memcg_oom_waitq, &owait.wait);
1957 mem_cgroup_out_of_memory(memcg, current->memcg_oom.gfp_mask,
1958 current->memcg_oom.order);
1959 } else {
3812c8c8 1960 schedule();
49426420
JW
1961 mem_cgroup_unmark_under_oom(memcg);
1962 finish_wait(&memcg_oom_waitq, &owait.wait);
1963 }
1964
1965 if (locked) {
fb2a6fc5
JW
1966 mem_cgroup_oom_unlock(memcg);
1967 /*
1968 * There is no guarantee that an OOM-lock contender
1969 * sees the wakeups triggered by the OOM kill
1970 * uncharges. Wake any sleepers explicitely.
1971 */
1972 memcg_oom_recover(memcg);
1973 }
49426420
JW
1974cleanup:
1975 current->memcg_oom.memcg = NULL;
3812c8c8 1976 css_put(&memcg->css);
867578cb 1977 return true;
0b7f569e
KH
1978}
1979
d7365e78
JW
1980/**
1981 * mem_cgroup_begin_page_stat - begin a page state statistics transaction
1982 * @page: page that is going to change accounted state
32047e2a 1983 *
d7365e78
JW
1984 * This function must mark the beginning of an accounted page state
1985 * change to prevent double accounting when the page is concurrently
1986 * being moved to another memcg:
32047e2a 1987 *
6de22619 1988 * memcg = mem_cgroup_begin_page_stat(page);
d7365e78
JW
1989 * if (TestClearPageState(page))
1990 * mem_cgroup_update_page_stat(memcg, state, -1);
6de22619 1991 * mem_cgroup_end_page_stat(memcg);
d69b042f 1992 */
6de22619 1993struct mem_cgroup *mem_cgroup_begin_page_stat(struct page *page)
89c06bd5
KH
1994{
1995 struct mem_cgroup *memcg;
6de22619 1996 unsigned long flags;
89c06bd5 1997
6de22619
JW
1998 /*
1999 * The RCU lock is held throughout the transaction. The fast
2000 * path can get away without acquiring the memcg->move_lock
2001 * because page moving starts with an RCU grace period.
2002 *
2003 * The RCU lock also protects the memcg from being freed when
2004 * the page state that is going to change is the only thing
2005 * preventing the page from being uncharged.
2006 * E.g. end-writeback clearing PageWriteback(), which allows
2007 * migration to go ahead and uncharge the page before the
2008 * account transaction might be complete.
2009 */
d7365e78
JW
2010 rcu_read_lock();
2011
2012 if (mem_cgroup_disabled())
2013 return NULL;
89c06bd5 2014again:
1306a85a 2015 memcg = page->mem_cgroup;
29833315 2016 if (unlikely(!memcg))
d7365e78
JW
2017 return NULL;
2018
bdcbb659 2019 if (atomic_read(&memcg->moving_account) <= 0)
d7365e78 2020 return memcg;
89c06bd5 2021
6de22619 2022 spin_lock_irqsave(&memcg->move_lock, flags);
1306a85a 2023 if (memcg != page->mem_cgroup) {
6de22619 2024 spin_unlock_irqrestore(&memcg->move_lock, flags);
89c06bd5
KH
2025 goto again;
2026 }
6de22619
JW
2027
2028 /*
2029 * When charge migration first begins, we can have locked and
2030 * unlocked page stat updates happening concurrently. Track
2031 * the task who has the lock for mem_cgroup_end_page_stat().
2032 */
2033 memcg->move_lock_task = current;
2034 memcg->move_lock_flags = flags;
d7365e78
JW
2035
2036 return memcg;
89c06bd5
KH
2037}
2038
d7365e78
JW
2039/**
2040 * mem_cgroup_end_page_stat - finish a page state statistics transaction
2041 * @memcg: the memcg that was accounted against
d7365e78 2042 */
6de22619 2043void mem_cgroup_end_page_stat(struct mem_cgroup *memcg)
89c06bd5 2044{
6de22619
JW
2045 if (memcg && memcg->move_lock_task == current) {
2046 unsigned long flags = memcg->move_lock_flags;
2047
2048 memcg->move_lock_task = NULL;
2049 memcg->move_lock_flags = 0;
2050
2051 spin_unlock_irqrestore(&memcg->move_lock, flags);
2052 }
89c06bd5 2053
d7365e78 2054 rcu_read_unlock();
89c06bd5
KH
2055}
2056
d7365e78
JW
2057/**
2058 * mem_cgroup_update_page_stat - update page state statistics
2059 * @memcg: memcg to account against
2060 * @idx: page state item to account
2061 * @val: number of pages (positive or negative)
2062 *
2063 * See mem_cgroup_begin_page_stat() for locking requirements.
2064 */
2065void mem_cgroup_update_page_stat(struct mem_cgroup *memcg,
68b4876d 2066 enum mem_cgroup_stat_index idx, int val)
d69b042f 2067{
658b72c5 2068 VM_BUG_ON(!rcu_read_lock_held());
26174efd 2069
d7365e78
JW
2070 if (memcg)
2071 this_cpu_add(memcg->stat->count[idx], val);
d69b042f 2072}
26174efd 2073
cdec2e42
KH
2074/*
2075 * size of first charge trial. "32" comes from vmscan.c's magic value.
2076 * TODO: maybe necessary to use big numbers in big irons.
2077 */
7ec99d62 2078#define CHARGE_BATCH 32U
cdec2e42
KH
2079struct memcg_stock_pcp {
2080 struct mem_cgroup *cached; /* this never be root cgroup */
11c9ea4e 2081 unsigned int nr_pages;
cdec2e42 2082 struct work_struct work;
26fe6168 2083 unsigned long flags;
a0db00fc 2084#define FLUSHING_CACHED_CHARGE 0
cdec2e42
KH
2085};
2086static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
9f50fad6 2087static DEFINE_MUTEX(percpu_charge_mutex);
cdec2e42 2088
a0956d54
SS
2089/**
2090 * consume_stock: Try to consume stocked charge on this cpu.
2091 * @memcg: memcg to consume from.
2092 * @nr_pages: how many pages to charge.
2093 *
2094 * The charges will only happen if @memcg matches the current cpu's memcg
2095 * stock, and at least @nr_pages are available in that stock. Failure to
2096 * service an allocation will refill the stock.
2097 *
2098 * returns true if successful, false otherwise.
cdec2e42 2099 */
a0956d54 2100static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
cdec2e42
KH
2101{
2102 struct memcg_stock_pcp *stock;
3e32cb2e 2103 bool ret = false;
cdec2e42 2104
a0956d54 2105 if (nr_pages > CHARGE_BATCH)
3e32cb2e 2106 return ret;
a0956d54 2107
cdec2e42 2108 stock = &get_cpu_var(memcg_stock);
3e32cb2e 2109 if (memcg == stock->cached && stock->nr_pages >= nr_pages) {
a0956d54 2110 stock->nr_pages -= nr_pages;
3e32cb2e
JW
2111 ret = true;
2112 }
cdec2e42
KH
2113 put_cpu_var(memcg_stock);
2114 return ret;
2115}
2116
2117/*
3e32cb2e 2118 * Returns stocks cached in percpu and reset cached information.
cdec2e42
KH
2119 */
2120static void drain_stock(struct memcg_stock_pcp *stock)
2121{
2122 struct mem_cgroup *old = stock->cached;
2123
11c9ea4e 2124 if (stock->nr_pages) {
3e32cb2e 2125 page_counter_uncharge(&old->memory, stock->nr_pages);
cdec2e42 2126 if (do_swap_account)
3e32cb2e 2127 page_counter_uncharge(&old->memsw, stock->nr_pages);
e8ea14cc 2128 css_put_many(&old->css, stock->nr_pages);
11c9ea4e 2129 stock->nr_pages = 0;
cdec2e42
KH
2130 }
2131 stock->cached = NULL;
cdec2e42
KH
2132}
2133
2134/*
2135 * This must be called under preempt disabled or must be called by
2136 * a thread which is pinned to local cpu.
2137 */
2138static void drain_local_stock(struct work_struct *dummy)
2139{
7c8e0181 2140 struct memcg_stock_pcp *stock = this_cpu_ptr(&memcg_stock);
cdec2e42 2141 drain_stock(stock);
26fe6168 2142 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
cdec2e42
KH
2143}
2144
2145/*
3e32cb2e 2146 * Cache charges(val) to local per_cpu area.
320cc51d 2147 * This will be consumed by consume_stock() function, later.
cdec2e42 2148 */
c0ff4b85 2149static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
cdec2e42
KH
2150{
2151 struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
2152
c0ff4b85 2153 if (stock->cached != memcg) { /* reset if necessary */
cdec2e42 2154 drain_stock(stock);
c0ff4b85 2155 stock->cached = memcg;
cdec2e42 2156 }
11c9ea4e 2157 stock->nr_pages += nr_pages;
cdec2e42
KH
2158 put_cpu_var(memcg_stock);
2159}
2160
2161/*
c0ff4b85 2162 * Drains all per-CPU charge caches for given root_memcg resp. subtree
6d3d6aa2 2163 * of the hierarchy under it.
cdec2e42 2164 */
6d3d6aa2 2165static void drain_all_stock(struct mem_cgroup *root_memcg)
cdec2e42 2166{
26fe6168 2167 int cpu, curcpu;
d38144b7 2168
6d3d6aa2
JW
2169 /* If someone's already draining, avoid adding running more workers. */
2170 if (!mutex_trylock(&percpu_charge_mutex))
2171 return;
cdec2e42 2172 /* Notify other cpus that system-wide "drain" is running */
cdec2e42 2173 get_online_cpus();
5af12d0e 2174 curcpu = get_cpu();
cdec2e42
KH
2175 for_each_online_cpu(cpu) {
2176 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
c0ff4b85 2177 struct mem_cgroup *memcg;
26fe6168 2178
c0ff4b85
R
2179 memcg = stock->cached;
2180 if (!memcg || !stock->nr_pages)
26fe6168 2181 continue;
2314b42d 2182 if (!mem_cgroup_is_descendant(memcg, root_memcg))
3e92041d 2183 continue;
d1a05b69
MH
2184 if (!test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2185 if (cpu == curcpu)
2186 drain_local_stock(&stock->work);
2187 else
2188 schedule_work_on(cpu, &stock->work);
2189 }
cdec2e42 2190 }
5af12d0e 2191 put_cpu();
f894ffa8 2192 put_online_cpus();
9f50fad6 2193 mutex_unlock(&percpu_charge_mutex);
cdec2e42
KH
2194}
2195
711d3d2c
KH
2196/*
2197 * This function drains percpu counter value from DEAD cpu and
2198 * move it to local cpu. Note that this function can be preempted.
2199 */
c0ff4b85 2200static void mem_cgroup_drain_pcp_counter(struct mem_cgroup *memcg, int cpu)
711d3d2c
KH
2201{
2202 int i;
2203
c0ff4b85 2204 spin_lock(&memcg->pcp_counter_lock);
6104621d 2205 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
c0ff4b85 2206 long x = per_cpu(memcg->stat->count[i], cpu);
711d3d2c 2207
c0ff4b85
R
2208 per_cpu(memcg->stat->count[i], cpu) = 0;
2209 memcg->nocpu_base.count[i] += x;
711d3d2c 2210 }
e9f8974f 2211 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
c0ff4b85 2212 unsigned long x = per_cpu(memcg->stat->events[i], cpu);
e9f8974f 2213
c0ff4b85
R
2214 per_cpu(memcg->stat->events[i], cpu) = 0;
2215 memcg->nocpu_base.events[i] += x;
e9f8974f 2216 }
c0ff4b85 2217 spin_unlock(&memcg->pcp_counter_lock);
711d3d2c
KH
2218}
2219
0db0628d 2220static int memcg_cpu_hotplug_callback(struct notifier_block *nb,
cdec2e42
KH
2221 unsigned long action,
2222 void *hcpu)
2223{
2224 int cpu = (unsigned long)hcpu;
2225 struct memcg_stock_pcp *stock;
711d3d2c 2226 struct mem_cgroup *iter;
cdec2e42 2227
619d094b 2228 if (action == CPU_ONLINE)
1489ebad 2229 return NOTIFY_OK;
1489ebad 2230
d833049b 2231 if (action != CPU_DEAD && action != CPU_DEAD_FROZEN)
cdec2e42 2232 return NOTIFY_OK;
711d3d2c 2233
9f3a0d09 2234 for_each_mem_cgroup(iter)
711d3d2c
KH
2235 mem_cgroup_drain_pcp_counter(iter, cpu);
2236
cdec2e42
KH
2237 stock = &per_cpu(memcg_stock, cpu);
2238 drain_stock(stock);
2239 return NOTIFY_OK;
2240}
2241
00501b53
JW
2242static int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2243 unsigned int nr_pages)
8a9f3ccd 2244{
7ec99d62 2245 unsigned int batch = max(CHARGE_BATCH, nr_pages);
9b130619 2246 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
6539cc05 2247 struct mem_cgroup *mem_over_limit;
3e32cb2e 2248 struct page_counter *counter;
6539cc05 2249 unsigned long nr_reclaimed;
b70a2a21
JW
2250 bool may_swap = true;
2251 bool drained = false;
05b84301 2252 int ret = 0;
a636b327 2253
ce00a967
JW
2254 if (mem_cgroup_is_root(memcg))
2255 goto done;
6539cc05 2256retry:
b6b6cc72
MH
2257 if (consume_stock(memcg, nr_pages))
2258 goto done;
8a9f3ccd 2259
3fbe7244 2260 if (!do_swap_account ||
3e32cb2e
JW
2261 !page_counter_try_charge(&memcg->memsw, batch, &counter)) {
2262 if (!page_counter_try_charge(&memcg->memory, batch, &counter))
6539cc05 2263 goto done_restock;
3fbe7244 2264 if (do_swap_account)
3e32cb2e
JW
2265 page_counter_uncharge(&memcg->memsw, batch);
2266 mem_over_limit = mem_cgroup_from_counter(counter, memory);
3fbe7244 2267 } else {
3e32cb2e 2268 mem_over_limit = mem_cgroup_from_counter(counter, memsw);
b70a2a21 2269 may_swap = false;
3fbe7244 2270 }
7a81b88c 2271
6539cc05
JW
2272 if (batch > nr_pages) {
2273 batch = nr_pages;
2274 goto retry;
2275 }
6d61ef40 2276
06b078fc
JW
2277 /*
2278 * Unlike in global OOM situations, memcg is not in a physical
2279 * memory shortage. Allow dying and OOM-killed tasks to
2280 * bypass the last charges so that they can exit quickly and
2281 * free their memory.
2282 */
2283 if (unlikely(test_thread_flag(TIF_MEMDIE) ||
2284 fatal_signal_pending(current) ||
2285 current->flags & PF_EXITING))
2286 goto bypass;
2287
2288 if (unlikely(task_in_memcg_oom(current)))
2289 goto nomem;
2290
6539cc05
JW
2291 if (!(gfp_mask & __GFP_WAIT))
2292 goto nomem;
4b534334 2293
241994ed
JW
2294 mem_cgroup_events(mem_over_limit, MEMCG_MAX, 1);
2295
b70a2a21
JW
2296 nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
2297 gfp_mask, may_swap);
6539cc05 2298
61e02c74 2299 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
6539cc05 2300 goto retry;
28c34c29 2301
b70a2a21 2302 if (!drained) {
6d3d6aa2 2303 drain_all_stock(mem_over_limit);
b70a2a21
JW
2304 drained = true;
2305 goto retry;
2306 }
2307
28c34c29
JW
2308 if (gfp_mask & __GFP_NORETRY)
2309 goto nomem;
6539cc05
JW
2310 /*
2311 * Even though the limit is exceeded at this point, reclaim
2312 * may have been able to free some pages. Retry the charge
2313 * before killing the task.
2314 *
2315 * Only for regular pages, though: huge pages are rather
2316 * unlikely to succeed so close to the limit, and we fall back
2317 * to regular pages anyway in case of failure.
2318 */
61e02c74 2319 if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
6539cc05
JW
2320 goto retry;
2321 /*
2322 * At task move, charge accounts can be doubly counted. So, it's
2323 * better to wait until the end of task_move if something is going on.
2324 */
2325 if (mem_cgroup_wait_acct_move(mem_over_limit))
2326 goto retry;
2327
9b130619
JW
2328 if (nr_retries--)
2329 goto retry;
2330
06b078fc
JW
2331 if (gfp_mask & __GFP_NOFAIL)
2332 goto bypass;
2333
6539cc05
JW
2334 if (fatal_signal_pending(current))
2335 goto bypass;
2336
241994ed
JW
2337 mem_cgroup_events(mem_over_limit, MEMCG_OOM, 1);
2338
61e02c74 2339 mem_cgroup_oom(mem_over_limit, gfp_mask, get_order(nr_pages));
7a81b88c 2340nomem:
6d1fdc48 2341 if (!(gfp_mask & __GFP_NOFAIL))
3168ecbe 2342 return -ENOMEM;
867578cb 2343bypass:
ce00a967 2344 return -EINTR;
6539cc05
JW
2345
2346done_restock:
e8ea14cc 2347 css_get_many(&memcg->css, batch);
6539cc05
JW
2348 if (batch > nr_pages)
2349 refill_stock(memcg, batch - nr_pages);
241994ed
JW
2350 /*
2351 * If the hierarchy is above the normal consumption range,
2352 * make the charging task trim their excess contribution.
2353 */
2354 do {
2355 if (page_counter_read(&memcg->memory) <= memcg->high)
2356 continue;
2357 mem_cgroup_events(memcg, MEMCG_HIGH, 1);
2358 try_to_free_mem_cgroup_pages(memcg, nr_pages, gfp_mask, true);
2359 } while ((memcg = parent_mem_cgroup(memcg)));
6539cc05 2360done:
05b84301 2361 return ret;
7a81b88c 2362}
8a9f3ccd 2363
00501b53 2364static void cancel_charge(struct mem_cgroup *memcg, unsigned int nr_pages)
a3032a2c 2365{
ce00a967
JW
2366 if (mem_cgroup_is_root(memcg))
2367 return;
2368
3e32cb2e 2369 page_counter_uncharge(&memcg->memory, nr_pages);
05b84301 2370 if (do_swap_account)
3e32cb2e 2371 page_counter_uncharge(&memcg->memsw, nr_pages);
ce00a967 2372
e8ea14cc 2373 css_put_many(&memcg->css, nr_pages);
d01dd17f
KH
2374}
2375
a3b2d692
KH
2376/*
2377 * A helper function to get mem_cgroup from ID. must be called under
ec903c0c
TH
2378 * rcu_read_lock(). The caller is responsible for calling
2379 * css_tryget_online() if the mem_cgroup is used for charging. (dropping
2380 * refcnt from swap can be called against removed memcg.)
a3b2d692
KH
2381 */
2382static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
2383{
a3b2d692
KH
2384 /* ID 0 is unused ID */
2385 if (!id)
2386 return NULL;
34c00c31 2387 return mem_cgroup_from_id(id);
a3b2d692
KH
2388}
2389
0a31bc97
JW
2390/*
2391 * try_get_mem_cgroup_from_page - look up page's memcg association
2392 * @page: the page
2393 *
2394 * Look up, get a css reference, and return the memcg that owns @page.
2395 *
2396 * The page must be locked to prevent racing with swap-in and page
2397 * cache charges. If coming from an unlocked page table, the caller
2398 * must ensure the page is on the LRU or this can race with charging.
2399 */
e42d9d5d 2400struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
b5a84319 2401{
29833315 2402 struct mem_cgroup *memcg;
a3b2d692 2403 unsigned short id;
b5a84319
KH
2404 swp_entry_t ent;
2405
309381fe 2406 VM_BUG_ON_PAGE(!PageLocked(page), page);
3c776e64 2407
1306a85a 2408 memcg = page->mem_cgroup;
29833315
JW
2409 if (memcg) {
2410 if (!css_tryget_online(&memcg->css))
c0ff4b85 2411 memcg = NULL;
e42d9d5d 2412 } else if (PageSwapCache(page)) {
3c776e64 2413 ent.val = page_private(page);
9fb4b7cc 2414 id = lookup_swap_cgroup_id(ent);
a3b2d692 2415 rcu_read_lock();
c0ff4b85 2416 memcg = mem_cgroup_lookup(id);
ec903c0c 2417 if (memcg && !css_tryget_online(&memcg->css))
c0ff4b85 2418 memcg = NULL;
a3b2d692 2419 rcu_read_unlock();
3c776e64 2420 }
c0ff4b85 2421 return memcg;
b5a84319
KH
2422}
2423
0a31bc97
JW
2424static void lock_page_lru(struct page *page, int *isolated)
2425{
2426 struct zone *zone = page_zone(page);
2427
2428 spin_lock_irq(&zone->lru_lock);
2429 if (PageLRU(page)) {
2430 struct lruvec *lruvec;
2431
2432 lruvec = mem_cgroup_page_lruvec(page, zone);
2433 ClearPageLRU(page);
2434 del_page_from_lru_list(page, lruvec, page_lru(page));
2435 *isolated = 1;
2436 } else
2437 *isolated = 0;
2438}
2439
2440static void unlock_page_lru(struct page *page, int isolated)
2441{
2442 struct zone *zone = page_zone(page);
2443
2444 if (isolated) {
2445 struct lruvec *lruvec;
2446
2447 lruvec = mem_cgroup_page_lruvec(page, zone);
2448 VM_BUG_ON_PAGE(PageLRU(page), page);
2449 SetPageLRU(page);
2450 add_page_to_lru_list(page, lruvec, page_lru(page));
2451 }
2452 spin_unlock_irq(&zone->lru_lock);
2453}
2454
00501b53 2455static void commit_charge(struct page *page, struct mem_cgroup *memcg,
6abb5a86 2456 bool lrucare)
7a81b88c 2457{
0a31bc97 2458 int isolated;
9ce70c02 2459
1306a85a 2460 VM_BUG_ON_PAGE(page->mem_cgroup, page);
9ce70c02
HD
2461
2462 /*
2463 * In some cases, SwapCache and FUSE(splice_buf->radixtree), the page
2464 * may already be on some other mem_cgroup's LRU. Take care of it.
2465 */
0a31bc97
JW
2466 if (lrucare)
2467 lock_page_lru(page, &isolated);
9ce70c02 2468
0a31bc97
JW
2469 /*
2470 * Nobody should be changing or seriously looking at
1306a85a 2471 * page->mem_cgroup at this point:
0a31bc97
JW
2472 *
2473 * - the page is uncharged
2474 *
2475 * - the page is off-LRU
2476 *
2477 * - an anonymous fault has exclusive page access, except for
2478 * a locked page table
2479 *
2480 * - a page cache insertion, a swapin fault, or a migration
2481 * have the page locked
2482 */
1306a85a 2483 page->mem_cgroup = memcg;
9ce70c02 2484
0a31bc97
JW
2485 if (lrucare)
2486 unlock_page_lru(page, isolated);
7a81b88c 2487}
66e1707b 2488
7ae1e1d0 2489#ifdef CONFIG_MEMCG_KMEM
dbf22eb6
VD
2490int memcg_charge_kmem(struct mem_cgroup *memcg, gfp_t gfp,
2491 unsigned long nr_pages)
7ae1e1d0 2492{
3e32cb2e 2493 struct page_counter *counter;
7ae1e1d0 2494 int ret = 0;
7ae1e1d0 2495
3e32cb2e
JW
2496 ret = page_counter_try_charge(&memcg->kmem, nr_pages, &counter);
2497 if (ret < 0)
7ae1e1d0
GC
2498 return ret;
2499
3e32cb2e 2500 ret = try_charge(memcg, gfp, nr_pages);
7ae1e1d0
GC
2501 if (ret == -EINTR) {
2502 /*
00501b53
JW
2503 * try_charge() chose to bypass to root due to OOM kill or
2504 * fatal signal. Since our only options are to either fail
2505 * the allocation or charge it to this cgroup, do it as a
2506 * temporary condition. But we can't fail. From a kmem/slab
2507 * perspective, the cache has already been selected, by
2508 * mem_cgroup_kmem_get_cache(), so it is too late to change
7ae1e1d0
GC
2509 * our minds.
2510 *
2511 * This condition will only trigger if the task entered
00501b53
JW
2512 * memcg_charge_kmem in a sane state, but was OOM-killed
2513 * during try_charge() above. Tasks that were already dying
2514 * when the allocation triggers should have been already
7ae1e1d0
GC
2515 * directed to the root cgroup in memcontrol.h
2516 */
3e32cb2e 2517 page_counter_charge(&memcg->memory, nr_pages);
7ae1e1d0 2518 if (do_swap_account)
3e32cb2e 2519 page_counter_charge(&memcg->memsw, nr_pages);
e8ea14cc 2520 css_get_many(&memcg->css, nr_pages);
7ae1e1d0
GC
2521 ret = 0;
2522 } else if (ret)
3e32cb2e 2523 page_counter_uncharge(&memcg->kmem, nr_pages);
7ae1e1d0
GC
2524
2525 return ret;
2526}
2527
dbf22eb6 2528void memcg_uncharge_kmem(struct mem_cgroup *memcg, unsigned long nr_pages)
7ae1e1d0 2529{
3e32cb2e 2530 page_counter_uncharge(&memcg->memory, nr_pages);
7ae1e1d0 2531 if (do_swap_account)
3e32cb2e 2532 page_counter_uncharge(&memcg->memsw, nr_pages);
7de37682 2533
64f21993 2534 page_counter_uncharge(&memcg->kmem, nr_pages);
7de37682 2535
e8ea14cc 2536 css_put_many(&memcg->css, nr_pages);
7ae1e1d0
GC
2537}
2538
2633d7a0
GC
2539/*
2540 * helper for acessing a memcg's index. It will be used as an index in the
2541 * child cache array in kmem_cache, and also to derive its name. This function
2542 * will return -1 when this is not a kmem-limited memcg.
2543 */
2544int memcg_cache_id(struct mem_cgroup *memcg)
2545{
2546 return memcg ? memcg->kmemcg_id : -1;
2547}
2548
f3bb3043 2549static int memcg_alloc_cache_id(void)
55007d84 2550{
f3bb3043
VD
2551 int id, size;
2552 int err;
2553
dbcf73e2 2554 id = ida_simple_get(&memcg_cache_ida,
f3bb3043
VD
2555 0, MEMCG_CACHES_MAX_SIZE, GFP_KERNEL);
2556 if (id < 0)
2557 return id;
55007d84 2558
dbcf73e2 2559 if (id < memcg_nr_cache_ids)
f3bb3043
VD
2560 return id;
2561
2562 /*
2563 * There's no space for the new id in memcg_caches arrays,
2564 * so we have to grow them.
2565 */
05257a1a 2566 down_write(&memcg_cache_ids_sem);
f3bb3043
VD
2567
2568 size = 2 * (id + 1);
55007d84
GC
2569 if (size < MEMCG_CACHES_MIN_SIZE)
2570 size = MEMCG_CACHES_MIN_SIZE;
2571 else if (size > MEMCG_CACHES_MAX_SIZE)
2572 size = MEMCG_CACHES_MAX_SIZE;
2573
f3bb3043 2574 err = memcg_update_all_caches(size);
60d3fd32
VD
2575 if (!err)
2576 err = memcg_update_all_list_lrus(size);
05257a1a
VD
2577 if (!err)
2578 memcg_nr_cache_ids = size;
2579
2580 up_write(&memcg_cache_ids_sem);
2581
f3bb3043 2582 if (err) {
dbcf73e2 2583 ida_simple_remove(&memcg_cache_ida, id);
f3bb3043
VD
2584 return err;
2585 }
2586 return id;
2587}
2588
2589static void memcg_free_cache_id(int id)
2590{
dbcf73e2 2591 ida_simple_remove(&memcg_cache_ida, id);
55007d84
GC
2592}
2593
d5b3cf71 2594struct memcg_kmem_cache_create_work {
5722d094
VD
2595 struct mem_cgroup *memcg;
2596 struct kmem_cache *cachep;
2597 struct work_struct work;
2598};
2599
d5b3cf71 2600static void memcg_kmem_cache_create_func(struct work_struct *w)
d7f25f8a 2601{
d5b3cf71
VD
2602 struct memcg_kmem_cache_create_work *cw =
2603 container_of(w, struct memcg_kmem_cache_create_work, work);
5722d094
VD
2604 struct mem_cgroup *memcg = cw->memcg;
2605 struct kmem_cache *cachep = cw->cachep;
d7f25f8a 2606
d5b3cf71 2607 memcg_create_kmem_cache(memcg, cachep);
bd673145 2608
5722d094 2609 css_put(&memcg->css);
d7f25f8a
GC
2610 kfree(cw);
2611}
2612
2613/*
2614 * Enqueue the creation of a per-memcg kmem_cache.
d7f25f8a 2615 */
d5b3cf71
VD
2616static void __memcg_schedule_kmem_cache_create(struct mem_cgroup *memcg,
2617 struct kmem_cache *cachep)
d7f25f8a 2618{
d5b3cf71 2619 struct memcg_kmem_cache_create_work *cw;
d7f25f8a 2620
776ed0f0 2621 cw = kmalloc(sizeof(*cw), GFP_NOWAIT);
8135be5a 2622 if (!cw)
d7f25f8a 2623 return;
8135be5a
VD
2624
2625 css_get(&memcg->css);
d7f25f8a
GC
2626
2627 cw->memcg = memcg;
2628 cw->cachep = cachep;
d5b3cf71 2629 INIT_WORK(&cw->work, memcg_kmem_cache_create_func);
d7f25f8a 2630
d7f25f8a
GC
2631 schedule_work(&cw->work);
2632}
2633
d5b3cf71
VD
2634static void memcg_schedule_kmem_cache_create(struct mem_cgroup *memcg,
2635 struct kmem_cache *cachep)
0e9d92f2
GC
2636{
2637 /*
2638 * We need to stop accounting when we kmalloc, because if the
2639 * corresponding kmalloc cache is not yet created, the first allocation
d5b3cf71 2640 * in __memcg_schedule_kmem_cache_create will recurse.
0e9d92f2
GC
2641 *
2642 * However, it is better to enclose the whole function. Depending on
2643 * the debugging options enabled, INIT_WORK(), for instance, can
2644 * trigger an allocation. This too, will make us recurse. Because at
2645 * this point we can't allow ourselves back into memcg_kmem_get_cache,
2646 * the safest choice is to do it like this, wrapping the whole function.
2647 */
6f185c29 2648 current->memcg_kmem_skip_account = 1;
d5b3cf71 2649 __memcg_schedule_kmem_cache_create(memcg, cachep);
6f185c29 2650 current->memcg_kmem_skip_account = 0;
0e9d92f2 2651}
c67a8a68 2652
d7f25f8a
GC
2653/*
2654 * Return the kmem_cache we're supposed to use for a slab allocation.
2655 * We try to use the current memcg's version of the cache.
2656 *
2657 * If the cache does not exist yet, if we are the first user of it,
2658 * we either create it immediately, if possible, or create it asynchronously
2659 * in a workqueue.
2660 * In the latter case, we will let the current allocation go through with
2661 * the original cache.
2662 *
2663 * Can't be called in interrupt context or from kernel threads.
2664 * This function needs to be called with rcu_read_lock() held.
2665 */
056b7cce 2666struct kmem_cache *__memcg_kmem_get_cache(struct kmem_cache *cachep)
d7f25f8a
GC
2667{
2668 struct mem_cgroup *memcg;
959c8963 2669 struct kmem_cache *memcg_cachep;
2a4db7eb 2670 int kmemcg_id;
d7f25f8a 2671
f7ce3190 2672 VM_BUG_ON(!is_root_cache(cachep));
d7f25f8a 2673
9d100c5e 2674 if (current->memcg_kmem_skip_account)
0e9d92f2
GC
2675 return cachep;
2676
8135be5a 2677 memcg = get_mem_cgroup_from_mm(current->mm);
2a4db7eb
VD
2678 kmemcg_id = ACCESS_ONCE(memcg->kmemcg_id);
2679 if (kmemcg_id < 0)
ca0dde97 2680 goto out;
d7f25f8a 2681
2a4db7eb 2682 memcg_cachep = cache_from_memcg_idx(cachep, kmemcg_id);
8135be5a
VD
2683 if (likely(memcg_cachep))
2684 return memcg_cachep;
ca0dde97
LZ
2685
2686 /*
2687 * If we are in a safe context (can wait, and not in interrupt
2688 * context), we could be be predictable and return right away.
2689 * This would guarantee that the allocation being performed
2690 * already belongs in the new cache.
2691 *
2692 * However, there are some clashes that can arrive from locking.
2693 * For instance, because we acquire the slab_mutex while doing
776ed0f0
VD
2694 * memcg_create_kmem_cache, this means no further allocation
2695 * could happen with the slab_mutex held. So it's better to
2696 * defer everything.
ca0dde97 2697 */
d5b3cf71 2698 memcg_schedule_kmem_cache_create(memcg, cachep);
ca0dde97 2699out:
8135be5a 2700 css_put(&memcg->css);
ca0dde97 2701 return cachep;
d7f25f8a 2702}
d7f25f8a 2703
8135be5a
VD
2704void __memcg_kmem_put_cache(struct kmem_cache *cachep)
2705{
2706 if (!is_root_cache(cachep))
f7ce3190 2707 css_put(&cachep->memcg_params.memcg->css);
8135be5a
VD
2708}
2709
7ae1e1d0
GC
2710/*
2711 * We need to verify if the allocation against current->mm->owner's memcg is
2712 * possible for the given order. But the page is not allocated yet, so we'll
2713 * need a further commit step to do the final arrangements.
2714 *
2715 * It is possible for the task to switch cgroups in this mean time, so at
2716 * commit time, we can't rely on task conversion any longer. We'll then use
2717 * the handle argument to return to the caller which cgroup we should commit
2718 * against. We could also return the memcg directly and avoid the pointer
2719 * passing, but a boolean return value gives better semantics considering
2720 * the compiled-out case as well.
2721 *
2722 * Returning true means the allocation is possible.
2723 */
2724bool
2725__memcg_kmem_newpage_charge(gfp_t gfp, struct mem_cgroup **_memcg, int order)
2726{
2727 struct mem_cgroup *memcg;
2728 int ret;
2729
2730 *_memcg = NULL;
6d42c232 2731
df381975 2732 memcg = get_mem_cgroup_from_mm(current->mm);
7ae1e1d0 2733
cf2b8fbf 2734 if (!memcg_kmem_is_active(memcg)) {
7ae1e1d0
GC
2735 css_put(&memcg->css);
2736 return true;
2737 }
2738
3e32cb2e 2739 ret = memcg_charge_kmem(memcg, gfp, 1 << order);
7ae1e1d0
GC
2740 if (!ret)
2741 *_memcg = memcg;
7ae1e1d0
GC
2742
2743 css_put(&memcg->css);
2744 return (ret == 0);
2745}
2746
2747void __memcg_kmem_commit_charge(struct page *page, struct mem_cgroup *memcg,
2748 int order)
2749{
7ae1e1d0
GC
2750 VM_BUG_ON(mem_cgroup_is_root(memcg));
2751
2752 /* The page allocation failed. Revert */
2753 if (!page) {
3e32cb2e 2754 memcg_uncharge_kmem(memcg, 1 << order);
7ae1e1d0
GC
2755 return;
2756 }
1306a85a 2757 page->mem_cgroup = memcg;
7ae1e1d0
GC
2758}
2759
2760void __memcg_kmem_uncharge_pages(struct page *page, int order)
2761{
1306a85a 2762 struct mem_cgroup *memcg = page->mem_cgroup;
7ae1e1d0 2763
7ae1e1d0
GC
2764 if (!memcg)
2765 return;
2766
309381fe 2767 VM_BUG_ON_PAGE(mem_cgroup_is_root(memcg), page);
29833315 2768
3e32cb2e 2769 memcg_uncharge_kmem(memcg, 1 << order);
1306a85a 2770 page->mem_cgroup = NULL;
7ae1e1d0 2771}
60d3fd32
VD
2772
2773struct mem_cgroup *__mem_cgroup_from_kmem(void *ptr)
2774{
2775 struct mem_cgroup *memcg = NULL;
2776 struct kmem_cache *cachep;
2777 struct page *page;
2778
2779 page = virt_to_head_page(ptr);
2780 if (PageSlab(page)) {
2781 cachep = page->slab_cache;
2782 if (!is_root_cache(cachep))
f7ce3190 2783 memcg = cachep->memcg_params.memcg;
60d3fd32
VD
2784 } else
2785 /* page allocated by alloc_kmem_pages */
2786 memcg = page->mem_cgroup;
2787
2788 return memcg;
2789}
7ae1e1d0
GC
2790#endif /* CONFIG_MEMCG_KMEM */
2791
ca3e0214
KH
2792#ifdef CONFIG_TRANSPARENT_HUGEPAGE
2793
ca3e0214
KH
2794/*
2795 * Because tail pages are not marked as "used", set it. We're under
e94c8a9c
KH
2796 * zone->lru_lock, 'splitting on pmd' and compound_lock.
2797 * charge/uncharge will be never happen and move_account() is done under
2798 * compound_lock(), so we don't have to take care of races.
ca3e0214 2799 */
e94c8a9c 2800void mem_cgroup_split_huge_fixup(struct page *head)
ca3e0214 2801{
e94c8a9c 2802 int i;
ca3e0214 2803
3d37c4a9
KH
2804 if (mem_cgroup_disabled())
2805 return;
b070e65c 2806
29833315 2807 for (i = 1; i < HPAGE_PMD_NR; i++)
1306a85a 2808 head[i].mem_cgroup = head->mem_cgroup;
b9982f8d 2809
1306a85a 2810 __this_cpu_sub(head->mem_cgroup->stat->count[MEM_CGROUP_STAT_RSS_HUGE],
b070e65c 2811 HPAGE_PMD_NR);
ca3e0214 2812}
12d27107 2813#endif /* CONFIG_TRANSPARENT_HUGEPAGE */
ca3e0214 2814
f817ed48 2815/**
de3638d9 2816 * mem_cgroup_move_account - move account of the page
5564e88b 2817 * @page: the page
7ec99d62 2818 * @nr_pages: number of regular pages (>1 for huge pages)
f817ed48
KH
2819 * @from: mem_cgroup which the page is moved from.
2820 * @to: mem_cgroup which the page is moved to. @from != @to.
2821 *
2822 * The caller must confirm following.
08e552c6 2823 * - page is not on LRU (isolate_page() is useful.)
7ec99d62 2824 * - compound_lock is held when nr_pages > 1
f817ed48 2825 *
2f3479b1
KH
2826 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
2827 * from old cgroup.
f817ed48 2828 */
7ec99d62
JW
2829static int mem_cgroup_move_account(struct page *page,
2830 unsigned int nr_pages,
7ec99d62 2831 struct mem_cgroup *from,
2f3479b1 2832 struct mem_cgroup *to)
f817ed48 2833{
de3638d9
JW
2834 unsigned long flags;
2835 int ret;
987eba66 2836
f817ed48 2837 VM_BUG_ON(from == to);
309381fe 2838 VM_BUG_ON_PAGE(PageLRU(page), page);
de3638d9
JW
2839 /*
2840 * The page is isolated from LRU. So, collapse function
2841 * will not handle this page. But page splitting can happen.
2842 * Do this check under compound_page_lock(). The caller should
2843 * hold it.
2844 */
2845 ret = -EBUSY;
7ec99d62 2846 if (nr_pages > 1 && !PageTransHuge(page))
de3638d9
JW
2847 goto out;
2848
0a31bc97 2849 /*
1306a85a 2850 * Prevent mem_cgroup_migrate() from looking at page->mem_cgroup
0a31bc97
JW
2851 * of its source page while we change it: page migration takes
2852 * both pages off the LRU, but page cache replacement doesn't.
2853 */
2854 if (!trylock_page(page))
2855 goto out;
de3638d9
JW
2856
2857 ret = -EINVAL;
1306a85a 2858 if (page->mem_cgroup != from)
0a31bc97 2859 goto out_unlock;
de3638d9 2860
354a4783 2861 spin_lock_irqsave(&from->move_lock, flags);
f817ed48 2862
0a31bc97 2863 if (!PageAnon(page) && page_mapped(page)) {
59d1d256
JW
2864 __this_cpu_sub(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED],
2865 nr_pages);
2866 __this_cpu_add(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED],
2867 nr_pages);
2868 }
3ea67d06 2869
59d1d256
JW
2870 if (PageWriteback(page)) {
2871 __this_cpu_sub(from->stat->count[MEM_CGROUP_STAT_WRITEBACK],
2872 nr_pages);
2873 __this_cpu_add(to->stat->count[MEM_CGROUP_STAT_WRITEBACK],
2874 nr_pages);
2875 }
3ea67d06 2876
0a31bc97 2877 /*
1306a85a 2878 * It is safe to change page->mem_cgroup here because the page
0a31bc97
JW
2879 * is referenced, charged, and isolated - we can't race with
2880 * uncharging, charging, migration, or LRU putback.
2881 */
d69b042f 2882
854ffa8d 2883 /* caller should have done css_get */
1306a85a 2884 page->mem_cgroup = to;
354a4783
JW
2885 spin_unlock_irqrestore(&from->move_lock, flags);
2886
de3638d9 2887 ret = 0;
0a31bc97
JW
2888
2889 local_irq_disable();
2890 mem_cgroup_charge_statistics(to, page, nr_pages);
5564e88b 2891 memcg_check_events(to, page);
0a31bc97 2892 mem_cgroup_charge_statistics(from, page, -nr_pages);
5564e88b 2893 memcg_check_events(from, page);
0a31bc97
JW
2894 local_irq_enable();
2895out_unlock:
2896 unlock_page(page);
de3638d9 2897out:
f817ed48
KH
2898 return ret;
2899}
2900
c255a458 2901#ifdef CONFIG_MEMCG_SWAP
0a31bc97
JW
2902static void mem_cgroup_swap_statistics(struct mem_cgroup *memcg,
2903 bool charge)
d13d1443 2904{
0a31bc97
JW
2905 int val = (charge) ? 1 : -1;
2906 this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_SWAP], val);
d13d1443 2907}
02491447
DN
2908
2909/**
2910 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
2911 * @entry: swap entry to be moved
2912 * @from: mem_cgroup which the entry is moved from
2913 * @to: mem_cgroup which the entry is moved to
2914 *
2915 * It succeeds only when the swap_cgroup's record for this entry is the same
2916 * as the mem_cgroup's id of @from.
2917 *
2918 * Returns 0 on success, -EINVAL on failure.
2919 *
3e32cb2e 2920 * The caller must have charged to @to, IOW, called page_counter_charge() about
02491447
DN
2921 * both res and memsw, and called css_get().
2922 */
2923static int mem_cgroup_move_swap_account(swp_entry_t entry,
e91cbb42 2924 struct mem_cgroup *from, struct mem_cgroup *to)
02491447
DN
2925{
2926 unsigned short old_id, new_id;
2927
34c00c31
LZ
2928 old_id = mem_cgroup_id(from);
2929 new_id = mem_cgroup_id(to);
02491447
DN
2930
2931 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
02491447 2932 mem_cgroup_swap_statistics(from, false);
483c30b5 2933 mem_cgroup_swap_statistics(to, true);
02491447
DN
2934 return 0;
2935 }
2936 return -EINVAL;
2937}
2938#else
2939static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
e91cbb42 2940 struct mem_cgroup *from, struct mem_cgroup *to)
02491447
DN
2941{
2942 return -EINVAL;
2943}
8c7c6e34 2944#endif
d13d1443 2945
3e32cb2e 2946static DEFINE_MUTEX(memcg_limit_mutex);
f212ad7c 2947
d38d2a75 2948static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
3e32cb2e 2949 unsigned long limit)
628f4235 2950{
3e32cb2e
JW
2951 unsigned long curusage;
2952 unsigned long oldusage;
2953 bool enlarge = false;
81d39c20 2954 int retry_count;
3e32cb2e 2955 int ret;
81d39c20
KH
2956
2957 /*
2958 * For keeping hierarchical_reclaim simple, how long we should retry
2959 * is depends on callers. We set our retry-count to be function
2960 * of # of children which we should visit in this loop.
2961 */
3e32cb2e
JW
2962 retry_count = MEM_CGROUP_RECLAIM_RETRIES *
2963 mem_cgroup_count_children(memcg);
81d39c20 2964
3e32cb2e 2965 oldusage = page_counter_read(&memcg->memory);
628f4235 2966
3e32cb2e 2967 do {
628f4235
KH
2968 if (signal_pending(current)) {
2969 ret = -EINTR;
2970 break;
2971 }
3e32cb2e
JW
2972
2973 mutex_lock(&memcg_limit_mutex);
2974 if (limit > memcg->memsw.limit) {
2975 mutex_unlock(&memcg_limit_mutex);
8c7c6e34 2976 ret = -EINVAL;
628f4235
KH
2977 break;
2978 }
3e32cb2e
JW
2979 if (limit > memcg->memory.limit)
2980 enlarge = true;
2981 ret = page_counter_limit(&memcg->memory, limit);
2982 mutex_unlock(&memcg_limit_mutex);
8c7c6e34
KH
2983
2984 if (!ret)
2985 break;
2986
b70a2a21
JW
2987 try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL, true);
2988
3e32cb2e 2989 curusage = page_counter_read(&memcg->memory);
81d39c20 2990 /* Usage is reduced ? */
f894ffa8 2991 if (curusage >= oldusage)
81d39c20
KH
2992 retry_count--;
2993 else
2994 oldusage = curusage;
3e32cb2e
JW
2995 } while (retry_count);
2996
3c11ecf4
KH
2997 if (!ret && enlarge)
2998 memcg_oom_recover(memcg);
14797e23 2999
8c7c6e34
KH
3000 return ret;
3001}
3002
338c8431 3003static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
3e32cb2e 3004 unsigned long limit)
8c7c6e34 3005{
3e32cb2e
JW
3006 unsigned long curusage;
3007 unsigned long oldusage;
3008 bool enlarge = false;
81d39c20 3009 int retry_count;
3e32cb2e 3010 int ret;
8c7c6e34 3011
81d39c20 3012 /* see mem_cgroup_resize_res_limit */
3e32cb2e
JW
3013 retry_count = MEM_CGROUP_RECLAIM_RETRIES *
3014 mem_cgroup_count_children(memcg);
3015
3016 oldusage = page_counter_read(&memcg->memsw);
3017
3018 do {
8c7c6e34
KH
3019 if (signal_pending(current)) {
3020 ret = -EINTR;
3021 break;
3022 }
3e32cb2e
JW
3023
3024 mutex_lock(&memcg_limit_mutex);
3025 if (limit < memcg->memory.limit) {
3026 mutex_unlock(&memcg_limit_mutex);
8c7c6e34 3027 ret = -EINVAL;
8c7c6e34
KH
3028 break;
3029 }
3e32cb2e
JW
3030 if (limit > memcg->memsw.limit)
3031 enlarge = true;
3032 ret = page_counter_limit(&memcg->memsw, limit);
3033 mutex_unlock(&memcg_limit_mutex);
8c7c6e34
KH
3034
3035 if (!ret)
3036 break;
3037
b70a2a21
JW
3038 try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL, false);
3039
3e32cb2e 3040 curusage = page_counter_read(&memcg->memsw);
81d39c20 3041 /* Usage is reduced ? */
8c7c6e34 3042 if (curusage >= oldusage)
628f4235 3043 retry_count--;
81d39c20
KH
3044 else
3045 oldusage = curusage;
3e32cb2e
JW
3046 } while (retry_count);
3047
3c11ecf4
KH
3048 if (!ret && enlarge)
3049 memcg_oom_recover(memcg);
3e32cb2e 3050
628f4235
KH
3051 return ret;
3052}
3053
0608f43d
AM
3054unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
3055 gfp_t gfp_mask,
3056 unsigned long *total_scanned)
3057{
3058 unsigned long nr_reclaimed = 0;
3059 struct mem_cgroup_per_zone *mz, *next_mz = NULL;
3060 unsigned long reclaimed;
3061 int loop = 0;
3062 struct mem_cgroup_tree_per_zone *mctz;
3e32cb2e 3063 unsigned long excess;
0608f43d
AM
3064 unsigned long nr_scanned;
3065
3066 if (order > 0)
3067 return 0;
3068
3069 mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone));
3070 /*
3071 * This loop can run a while, specially if mem_cgroup's continuously
3072 * keep exceeding their soft limit and putting the system under
3073 * pressure
3074 */
3075 do {
3076 if (next_mz)
3077 mz = next_mz;
3078 else
3079 mz = mem_cgroup_largest_soft_limit_node(mctz);
3080 if (!mz)
3081 break;
3082
3083 nr_scanned = 0;
3084 reclaimed = mem_cgroup_soft_reclaim(mz->memcg, zone,
3085 gfp_mask, &nr_scanned);
3086 nr_reclaimed += reclaimed;
3087 *total_scanned += nr_scanned;
0a31bc97 3088 spin_lock_irq(&mctz->lock);
bc2f2e7f 3089 __mem_cgroup_remove_exceeded(mz, mctz);
0608f43d
AM
3090
3091 /*
3092 * If we failed to reclaim anything from this memory cgroup
3093 * it is time to move on to the next cgroup
3094 */
3095 next_mz = NULL;
bc2f2e7f
VD
3096 if (!reclaimed)
3097 next_mz = __mem_cgroup_largest_soft_limit_node(mctz);
3098
3e32cb2e 3099 excess = soft_limit_excess(mz->memcg);
0608f43d
AM
3100 /*
3101 * One school of thought says that we should not add
3102 * back the node to the tree if reclaim returns 0.
3103 * But our reclaim could return 0, simply because due
3104 * to priority we are exposing a smaller subset of
3105 * memory to reclaim from. Consider this as a longer
3106 * term TODO.
3107 */
3108 /* If excess == 0, no tree ops */
cf2c8127 3109 __mem_cgroup_insert_exceeded(mz, mctz, excess);
0a31bc97 3110 spin_unlock_irq(&mctz->lock);
0608f43d
AM
3111 css_put(&mz->memcg->css);
3112 loop++;
3113 /*
3114 * Could not reclaim anything and there are no more
3115 * mem cgroups to try or we seem to be looping without
3116 * reclaiming anything.
3117 */
3118 if (!nr_reclaimed &&
3119 (next_mz == NULL ||
3120 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3121 break;
3122 } while (!nr_reclaimed);
3123 if (next_mz)
3124 css_put(&next_mz->memcg->css);
3125 return nr_reclaimed;
3126}
3127
ea280e7b
TH
3128/*
3129 * Test whether @memcg has children, dead or alive. Note that this
3130 * function doesn't care whether @memcg has use_hierarchy enabled and
3131 * returns %true if there are child csses according to the cgroup
3132 * hierarchy. Testing use_hierarchy is the caller's responsiblity.
3133 */
b5f99b53
GC
3134static inline bool memcg_has_children(struct mem_cgroup *memcg)
3135{
ea280e7b
TH
3136 bool ret;
3137
696ac172 3138 /*
ea280e7b
TH
3139 * The lock does not prevent addition or deletion of children, but
3140 * it prevents a new child from being initialized based on this
3141 * parent in css_online(), so it's enough to decide whether
3142 * hierarchically inherited attributes can still be changed or not.
696ac172 3143 */
ea280e7b
TH
3144 lockdep_assert_held(&memcg_create_mutex);
3145
3146 rcu_read_lock();
3147 ret = css_next_child(NULL, &memcg->css);
3148 rcu_read_unlock();
3149 return ret;
b5f99b53
GC
3150}
3151
c26251f9
MH
3152/*
3153 * Reclaims as many pages from the given memcg as possible and moves
3154 * the rest to the parent.
3155 *
3156 * Caller is responsible for holding css reference for memcg.
3157 */
3158static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
3159{
3160 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
c26251f9 3161
c1e862c1
KH
3162 /* we call try-to-free pages for make this cgroup empty */
3163 lru_add_drain_all();
f817ed48 3164 /* try to free all pages in this cgroup */
3e32cb2e 3165 while (nr_retries && page_counter_read(&memcg->memory)) {
f817ed48 3166 int progress;
c1e862c1 3167
c26251f9
MH
3168 if (signal_pending(current))
3169 return -EINTR;
3170
b70a2a21
JW
3171 progress = try_to_free_mem_cgroup_pages(memcg, 1,
3172 GFP_KERNEL, true);
c1e862c1 3173 if (!progress) {
f817ed48 3174 nr_retries--;
c1e862c1 3175 /* maybe some writeback is necessary */
8aa7e847 3176 congestion_wait(BLK_RW_ASYNC, HZ/10);
c1e862c1 3177 }
f817ed48
KH
3178
3179 }
ab5196c2
MH
3180
3181 return 0;
cc847582
KH
3182}
3183
6770c64e
TH
3184static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
3185 char *buf, size_t nbytes,
3186 loff_t off)
c1e862c1 3187{
6770c64e 3188 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
c26251f9 3189
d8423011
MH
3190 if (mem_cgroup_is_root(memcg))
3191 return -EINVAL;
6770c64e 3192 return mem_cgroup_force_empty(memcg) ?: nbytes;
c1e862c1
KH
3193}
3194
182446d0
TH
3195static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
3196 struct cftype *cft)
18f59ea7 3197{
182446d0 3198 return mem_cgroup_from_css(css)->use_hierarchy;
18f59ea7
BS
3199}
3200
182446d0
TH
3201static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
3202 struct cftype *cft, u64 val)
18f59ea7
BS
3203{
3204 int retval = 0;
182446d0 3205 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5c9d535b 3206 struct mem_cgroup *parent_memcg = mem_cgroup_from_css(memcg->css.parent);
18f59ea7 3207
0999821b 3208 mutex_lock(&memcg_create_mutex);
567fb435
GC
3209
3210 if (memcg->use_hierarchy == val)
3211 goto out;
3212
18f59ea7 3213 /*
af901ca1 3214 * If parent's use_hierarchy is set, we can't make any modifications
18f59ea7
BS
3215 * in the child subtrees. If it is unset, then the change can
3216 * occur, provided the current cgroup has no children.
3217 *
3218 * For the root cgroup, parent_mem is NULL, we allow value to be
3219 * set if there are no children.
3220 */
c0ff4b85 3221 if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
18f59ea7 3222 (val == 1 || val == 0)) {
ea280e7b 3223 if (!memcg_has_children(memcg))
c0ff4b85 3224 memcg->use_hierarchy = val;
18f59ea7
BS
3225 else
3226 retval = -EBUSY;
3227 } else
3228 retval = -EINVAL;
567fb435
GC
3229
3230out:
0999821b 3231 mutex_unlock(&memcg_create_mutex);
18f59ea7
BS
3232
3233 return retval;
3234}
3235
3e32cb2e
JW
3236static unsigned long tree_stat(struct mem_cgroup *memcg,
3237 enum mem_cgroup_stat_index idx)
ce00a967
JW
3238{
3239 struct mem_cgroup *iter;
3240 long val = 0;
3241
3242 /* Per-cpu values can be negative, use a signed accumulator */
3243 for_each_mem_cgroup_tree(iter, memcg)
3244 val += mem_cgroup_read_stat(iter, idx);
3245
3246 if (val < 0) /* race ? */
3247 val = 0;
3248 return val;
3249}
3250
3251static inline u64 mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
3252{
3253 u64 val;
3254
3e32cb2e
JW
3255 if (mem_cgroup_is_root(memcg)) {
3256 val = tree_stat(memcg, MEM_CGROUP_STAT_CACHE);
3257 val += tree_stat(memcg, MEM_CGROUP_STAT_RSS);
3258 if (swap)
3259 val += tree_stat(memcg, MEM_CGROUP_STAT_SWAP);
3260 } else {
ce00a967 3261 if (!swap)
3e32cb2e 3262 val = page_counter_read(&memcg->memory);
ce00a967 3263 else
3e32cb2e 3264 val = page_counter_read(&memcg->memsw);
ce00a967 3265 }
ce00a967
JW
3266 return val << PAGE_SHIFT;
3267}
3268
3e32cb2e
JW
3269enum {
3270 RES_USAGE,
3271 RES_LIMIT,
3272 RES_MAX_USAGE,
3273 RES_FAILCNT,
3274 RES_SOFT_LIMIT,
3275};
ce00a967 3276
791badbd 3277static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
05b84301 3278 struct cftype *cft)
8cdea7c0 3279{
182446d0 3280 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3e32cb2e 3281 struct page_counter *counter;
af36f906 3282
3e32cb2e 3283 switch (MEMFILE_TYPE(cft->private)) {
8c7c6e34 3284 case _MEM:
3e32cb2e
JW
3285 counter = &memcg->memory;
3286 break;
8c7c6e34 3287 case _MEMSWAP:
3e32cb2e
JW
3288 counter = &memcg->memsw;
3289 break;
510fc4e1 3290 case _KMEM:
3e32cb2e 3291 counter = &memcg->kmem;
510fc4e1 3292 break;
8c7c6e34
KH
3293 default:
3294 BUG();
8c7c6e34 3295 }
3e32cb2e
JW
3296
3297 switch (MEMFILE_ATTR(cft->private)) {
3298 case RES_USAGE:
3299 if (counter == &memcg->memory)
3300 return mem_cgroup_usage(memcg, false);
3301 if (counter == &memcg->memsw)
3302 return mem_cgroup_usage(memcg, true);
3303 return (u64)page_counter_read(counter) * PAGE_SIZE;
3304 case RES_LIMIT:
3305 return (u64)counter->limit * PAGE_SIZE;
3306 case RES_MAX_USAGE:
3307 return (u64)counter->watermark * PAGE_SIZE;
3308 case RES_FAILCNT:
3309 return counter->failcnt;
3310 case RES_SOFT_LIMIT:
3311 return (u64)memcg->soft_limit * PAGE_SIZE;
3312 default:
3313 BUG();
3314 }
8cdea7c0 3315}
510fc4e1 3316
510fc4e1 3317#ifdef CONFIG_MEMCG_KMEM
8c0145b6
VD
3318static int memcg_activate_kmem(struct mem_cgroup *memcg,
3319 unsigned long nr_pages)
d6441637
VD
3320{
3321 int err = 0;
3322 int memcg_id;
3323
2a4db7eb
VD
3324 BUG_ON(memcg->kmemcg_id >= 0);
3325 BUG_ON(memcg->kmem_acct_active);
d6441637 3326
510fc4e1
GC
3327 /*
3328 * For simplicity, we won't allow this to be disabled. It also can't
3329 * be changed if the cgroup has children already, or if tasks had
3330 * already joined.
3331 *
3332 * If tasks join before we set the limit, a person looking at
3333 * kmem.usage_in_bytes will have no way to determine when it took
3334 * place, which makes the value quite meaningless.
3335 *
3336 * After it first became limited, changes in the value of the limit are
3337 * of course permitted.
510fc4e1 3338 */
0999821b 3339 mutex_lock(&memcg_create_mutex);
ea280e7b
TH
3340 if (cgroup_has_tasks(memcg->css.cgroup) ||
3341 (memcg->use_hierarchy && memcg_has_children(memcg)))
d6441637
VD
3342 err = -EBUSY;
3343 mutex_unlock(&memcg_create_mutex);
3344 if (err)
3345 goto out;
510fc4e1 3346
f3bb3043 3347 memcg_id = memcg_alloc_cache_id();
d6441637
VD
3348 if (memcg_id < 0) {
3349 err = memcg_id;
3350 goto out;
3351 }
3352
d6441637 3353 /*
900a38f0
VD
3354 * We couldn't have accounted to this cgroup, because it hasn't got
3355 * activated yet, so this should succeed.
d6441637 3356 */
3e32cb2e 3357 err = page_counter_limit(&memcg->kmem, nr_pages);
d6441637
VD
3358 VM_BUG_ON(err);
3359
3360 static_key_slow_inc(&memcg_kmem_enabled_key);
3361 /*
900a38f0
VD
3362 * A memory cgroup is considered kmem-active as soon as it gets
3363 * kmemcg_id. Setting the id after enabling static branching will
d6441637
VD
3364 * guarantee no one starts accounting before all call sites are
3365 * patched.
3366 */
900a38f0 3367 memcg->kmemcg_id = memcg_id;
2a4db7eb 3368 memcg->kmem_acct_active = true;
510fc4e1 3369out:
d6441637 3370 return err;
d6441637
VD
3371}
3372
d6441637 3373static int memcg_update_kmem_limit(struct mem_cgroup *memcg,
3e32cb2e 3374 unsigned long limit)
d6441637
VD
3375{
3376 int ret;
3377
3e32cb2e 3378 mutex_lock(&memcg_limit_mutex);
d6441637 3379 if (!memcg_kmem_is_active(memcg))
3e32cb2e 3380 ret = memcg_activate_kmem(memcg, limit);
d6441637 3381 else
3e32cb2e
JW
3382 ret = page_counter_limit(&memcg->kmem, limit);
3383 mutex_unlock(&memcg_limit_mutex);
510fc4e1
GC
3384 return ret;
3385}
3386
55007d84 3387static int memcg_propagate_kmem(struct mem_cgroup *memcg)
510fc4e1 3388{
55007d84 3389 int ret = 0;
510fc4e1 3390 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
55007d84 3391
d6441637
VD
3392 if (!parent)
3393 return 0;
55007d84 3394
8c0145b6 3395 mutex_lock(&memcg_limit_mutex);
55007d84 3396 /*
d6441637
VD
3397 * If the parent cgroup is not kmem-active now, it cannot be activated
3398 * after this point, because it has at least one child already.
55007d84 3399 */
d6441637 3400 if (memcg_kmem_is_active(parent))
8c0145b6
VD
3401 ret = memcg_activate_kmem(memcg, PAGE_COUNTER_MAX);
3402 mutex_unlock(&memcg_limit_mutex);
55007d84 3403 return ret;
510fc4e1 3404}
d6441637
VD
3405#else
3406static int memcg_update_kmem_limit(struct mem_cgroup *memcg,
3e32cb2e 3407 unsigned long limit)
d6441637
VD
3408{
3409 return -EINVAL;
3410}
6d043990 3411#endif /* CONFIG_MEMCG_KMEM */
510fc4e1 3412
628f4235
KH
3413/*
3414 * The user of this function is...
3415 * RES_LIMIT.
3416 */
451af504
TH
3417static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
3418 char *buf, size_t nbytes, loff_t off)
8cdea7c0 3419{
451af504 3420 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3e32cb2e 3421 unsigned long nr_pages;
628f4235
KH
3422 int ret;
3423
451af504 3424 buf = strstrip(buf);
650c5e56 3425 ret = page_counter_memparse(buf, "-1", &nr_pages);
3e32cb2e
JW
3426 if (ret)
3427 return ret;
af36f906 3428
3e32cb2e 3429 switch (MEMFILE_ATTR(of_cft(of)->private)) {
628f4235 3430 case RES_LIMIT:
4b3bde4c
BS
3431 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3432 ret = -EINVAL;
3433 break;
3434 }
3e32cb2e
JW
3435 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3436 case _MEM:
3437 ret = mem_cgroup_resize_limit(memcg, nr_pages);
8c7c6e34 3438 break;
3e32cb2e
JW
3439 case _MEMSWAP:
3440 ret = mem_cgroup_resize_memsw_limit(memcg, nr_pages);
296c81d8 3441 break;
3e32cb2e
JW
3442 case _KMEM:
3443 ret = memcg_update_kmem_limit(memcg, nr_pages);
3444 break;
3445 }
296c81d8 3446 break;
3e32cb2e
JW
3447 case RES_SOFT_LIMIT:
3448 memcg->soft_limit = nr_pages;
3449 ret = 0;
628f4235
KH
3450 break;
3451 }
451af504 3452 return ret ?: nbytes;
8cdea7c0
BS
3453}
3454
6770c64e
TH
3455static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
3456 size_t nbytes, loff_t off)
c84872e1 3457{
6770c64e 3458 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3e32cb2e 3459 struct page_counter *counter;
c84872e1 3460
3e32cb2e
JW
3461 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3462 case _MEM:
3463 counter = &memcg->memory;
3464 break;
3465 case _MEMSWAP:
3466 counter = &memcg->memsw;
3467 break;
3468 case _KMEM:
3469 counter = &memcg->kmem;
3470 break;
3471 default:
3472 BUG();
3473 }
af36f906 3474
3e32cb2e 3475 switch (MEMFILE_ATTR(of_cft(of)->private)) {
29f2a4da 3476 case RES_MAX_USAGE:
3e32cb2e 3477 page_counter_reset_watermark(counter);
29f2a4da
PE
3478 break;
3479 case RES_FAILCNT:
3e32cb2e 3480 counter->failcnt = 0;
29f2a4da 3481 break;
3e32cb2e
JW
3482 default:
3483 BUG();
29f2a4da 3484 }
f64c3f54 3485
6770c64e 3486 return nbytes;
c84872e1
PE
3487}
3488
182446d0 3489static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
7dc74be0
DN
3490 struct cftype *cft)
3491{
182446d0 3492 return mem_cgroup_from_css(css)->move_charge_at_immigrate;
7dc74be0
DN
3493}
3494
02491447 3495#ifdef CONFIG_MMU
182446d0 3496static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
7dc74be0
DN
3497 struct cftype *cft, u64 val)
3498{
182446d0 3499 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
7dc74be0 3500
1dfab5ab 3501 if (val & ~MOVE_MASK)
7dc74be0 3502 return -EINVAL;
ee5e8472 3503
7dc74be0 3504 /*
ee5e8472
GC
3505 * No kind of locking is needed in here, because ->can_attach() will
3506 * check this value once in the beginning of the process, and then carry
3507 * on with stale data. This means that changes to this value will only
3508 * affect task migrations starting after the change.
7dc74be0 3509 */
c0ff4b85 3510 memcg->move_charge_at_immigrate = val;
7dc74be0
DN
3511 return 0;
3512}
02491447 3513#else
182446d0 3514static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
02491447
DN
3515 struct cftype *cft, u64 val)
3516{
3517 return -ENOSYS;
3518}
3519#endif
7dc74be0 3520
406eb0c9 3521#ifdef CONFIG_NUMA
2da8ca82 3522static int memcg_numa_stat_show(struct seq_file *m, void *v)
406eb0c9 3523{
25485de6
GT
3524 struct numa_stat {
3525 const char *name;
3526 unsigned int lru_mask;
3527 };
3528
3529 static const struct numa_stat stats[] = {
3530 { "total", LRU_ALL },
3531 { "file", LRU_ALL_FILE },
3532 { "anon", LRU_ALL_ANON },
3533 { "unevictable", BIT(LRU_UNEVICTABLE) },
3534 };
3535 const struct numa_stat *stat;
406eb0c9 3536 int nid;
25485de6 3537 unsigned long nr;
2da8ca82 3538 struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
406eb0c9 3539
25485de6
GT
3540 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
3541 nr = mem_cgroup_nr_lru_pages(memcg, stat->lru_mask);
3542 seq_printf(m, "%s=%lu", stat->name, nr);
3543 for_each_node_state(nid, N_MEMORY) {
3544 nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
3545 stat->lru_mask);
3546 seq_printf(m, " N%d=%lu", nid, nr);
3547 }
3548 seq_putc(m, '\n');
406eb0c9 3549 }
406eb0c9 3550
071aee13
YH
3551 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
3552 struct mem_cgroup *iter;
3553
3554 nr = 0;
3555 for_each_mem_cgroup_tree(iter, memcg)
3556 nr += mem_cgroup_nr_lru_pages(iter, stat->lru_mask);
3557 seq_printf(m, "hierarchical_%s=%lu", stat->name, nr);
3558 for_each_node_state(nid, N_MEMORY) {
3559 nr = 0;
3560 for_each_mem_cgroup_tree(iter, memcg)
3561 nr += mem_cgroup_node_nr_lru_pages(
3562 iter, nid, stat->lru_mask);
3563 seq_printf(m, " N%d=%lu", nid, nr);
3564 }
3565 seq_putc(m, '\n');
406eb0c9 3566 }
406eb0c9 3567
406eb0c9
YH
3568 return 0;
3569}
3570#endif /* CONFIG_NUMA */
3571
2da8ca82 3572static int memcg_stat_show(struct seq_file *m, void *v)
d2ceb9b7 3573{
2da8ca82 3574 struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
3e32cb2e 3575 unsigned long memory, memsw;
af7c4b0e
JW
3576 struct mem_cgroup *mi;
3577 unsigned int i;
406eb0c9 3578
0ca44b14
GT
3579 BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_stat_names) !=
3580 MEM_CGROUP_STAT_NSTATS);
3581 BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_events_names) !=
3582 MEM_CGROUP_EVENTS_NSTATS);
70bc068c
RS
3583 BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_lru_names) != NR_LRU_LISTS);
3584
af7c4b0e 3585 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
bff6bb83 3586 if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
1dd3a273 3587 continue;
af7c4b0e
JW
3588 seq_printf(m, "%s %ld\n", mem_cgroup_stat_names[i],
3589 mem_cgroup_read_stat(memcg, i) * PAGE_SIZE);
1dd3a273 3590 }
7b854121 3591
af7c4b0e
JW
3592 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++)
3593 seq_printf(m, "%s %lu\n", mem_cgroup_events_names[i],
3594 mem_cgroup_read_events(memcg, i));
3595
3596 for (i = 0; i < NR_LRU_LISTS; i++)
3597 seq_printf(m, "%s %lu\n", mem_cgroup_lru_names[i],
3598 mem_cgroup_nr_lru_pages(memcg, BIT(i)) * PAGE_SIZE);
3599
14067bb3 3600 /* Hierarchical information */
3e32cb2e
JW
3601 memory = memsw = PAGE_COUNTER_MAX;
3602 for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
3603 memory = min(memory, mi->memory.limit);
3604 memsw = min(memsw, mi->memsw.limit);
fee7b548 3605 }
3e32cb2e
JW
3606 seq_printf(m, "hierarchical_memory_limit %llu\n",
3607 (u64)memory * PAGE_SIZE);
3608 if (do_swap_account)
3609 seq_printf(m, "hierarchical_memsw_limit %llu\n",
3610 (u64)memsw * PAGE_SIZE);
7f016ee8 3611
af7c4b0e
JW
3612 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
3613 long long val = 0;
3614
bff6bb83 3615 if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
1dd3a273 3616 continue;
af7c4b0e
JW
3617 for_each_mem_cgroup_tree(mi, memcg)
3618 val += mem_cgroup_read_stat(mi, i) * PAGE_SIZE;
3619 seq_printf(m, "total_%s %lld\n", mem_cgroup_stat_names[i], val);
3620 }
3621
3622 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
3623 unsigned long long val = 0;
3624
3625 for_each_mem_cgroup_tree(mi, memcg)
3626 val += mem_cgroup_read_events(mi, i);
3627 seq_printf(m, "total_%s %llu\n",
3628 mem_cgroup_events_names[i], val);
3629 }
3630
3631 for (i = 0; i < NR_LRU_LISTS; i++) {
3632 unsigned long long val = 0;
3633
3634 for_each_mem_cgroup_tree(mi, memcg)
3635 val += mem_cgroup_nr_lru_pages(mi, BIT(i)) * PAGE_SIZE;
3636 seq_printf(m, "total_%s %llu\n", mem_cgroup_lru_names[i], val);
1dd3a273 3637 }
14067bb3 3638
7f016ee8 3639#ifdef CONFIG_DEBUG_VM
7f016ee8
KM
3640 {
3641 int nid, zid;
3642 struct mem_cgroup_per_zone *mz;
89abfab1 3643 struct zone_reclaim_stat *rstat;
7f016ee8
KM
3644 unsigned long recent_rotated[2] = {0, 0};
3645 unsigned long recent_scanned[2] = {0, 0};
3646
3647 for_each_online_node(nid)
3648 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
e231875b 3649 mz = &memcg->nodeinfo[nid]->zoneinfo[zid];
89abfab1 3650 rstat = &mz->lruvec.reclaim_stat;
7f016ee8 3651
89abfab1
HD
3652 recent_rotated[0] += rstat->recent_rotated[0];
3653 recent_rotated[1] += rstat->recent_rotated[1];
3654 recent_scanned[0] += rstat->recent_scanned[0];
3655 recent_scanned[1] += rstat->recent_scanned[1];
7f016ee8 3656 }
78ccf5b5
JW
3657 seq_printf(m, "recent_rotated_anon %lu\n", recent_rotated[0]);
3658 seq_printf(m, "recent_rotated_file %lu\n", recent_rotated[1]);
3659 seq_printf(m, "recent_scanned_anon %lu\n", recent_scanned[0]);
3660 seq_printf(m, "recent_scanned_file %lu\n", recent_scanned[1]);
7f016ee8
KM
3661 }
3662#endif
3663
d2ceb9b7
KH
3664 return 0;
3665}
3666
182446d0
TH
3667static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
3668 struct cftype *cft)
a7885eb8 3669{
182446d0 3670 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
a7885eb8 3671
1f4c025b 3672 return mem_cgroup_swappiness(memcg);
a7885eb8
KM
3673}
3674
182446d0
TH
3675static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
3676 struct cftype *cft, u64 val)
a7885eb8 3677{
182446d0 3678 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
a7885eb8 3679
3dae7fec 3680 if (val > 100)
a7885eb8
KM
3681 return -EINVAL;
3682
14208b0e 3683 if (css->parent)
3dae7fec
JW
3684 memcg->swappiness = val;
3685 else
3686 vm_swappiness = val;
068b38c1 3687
a7885eb8
KM
3688 return 0;
3689}
3690
2e72b634
KS
3691static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
3692{
3693 struct mem_cgroup_threshold_ary *t;
3e32cb2e 3694 unsigned long usage;
2e72b634
KS
3695 int i;
3696
3697 rcu_read_lock();
3698 if (!swap)
2c488db2 3699 t = rcu_dereference(memcg->thresholds.primary);
2e72b634 3700 else
2c488db2 3701 t = rcu_dereference(memcg->memsw_thresholds.primary);
2e72b634
KS
3702
3703 if (!t)
3704 goto unlock;
3705
ce00a967 3706 usage = mem_cgroup_usage(memcg, swap);
2e72b634
KS
3707
3708 /*
748dad36 3709 * current_threshold points to threshold just below or equal to usage.
2e72b634
KS
3710 * If it's not true, a threshold was crossed after last
3711 * call of __mem_cgroup_threshold().
3712 */
5407a562 3713 i = t->current_threshold;
2e72b634
KS
3714
3715 /*
3716 * Iterate backward over array of thresholds starting from
3717 * current_threshold and check if a threshold is crossed.
3718 * If none of thresholds below usage is crossed, we read
3719 * only one element of the array here.
3720 */
3721 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
3722 eventfd_signal(t->entries[i].eventfd, 1);
3723
3724 /* i = current_threshold + 1 */
3725 i++;
3726
3727 /*
3728 * Iterate forward over array of thresholds starting from
3729 * current_threshold+1 and check if a threshold is crossed.
3730 * If none of thresholds above usage is crossed, we read
3731 * only one element of the array here.
3732 */
3733 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
3734 eventfd_signal(t->entries[i].eventfd, 1);
3735
3736 /* Update current_threshold */
5407a562 3737 t->current_threshold = i - 1;
2e72b634
KS
3738unlock:
3739 rcu_read_unlock();
3740}
3741
3742static void mem_cgroup_threshold(struct mem_cgroup *memcg)
3743{
ad4ca5f4
KS
3744 while (memcg) {
3745 __mem_cgroup_threshold(memcg, false);
3746 if (do_swap_account)
3747 __mem_cgroup_threshold(memcg, true);
3748
3749 memcg = parent_mem_cgroup(memcg);
3750 }
2e72b634
KS
3751}
3752
3753static int compare_thresholds(const void *a, const void *b)
3754{
3755 const struct mem_cgroup_threshold *_a = a;
3756 const struct mem_cgroup_threshold *_b = b;
3757
2bff24a3
GT
3758 if (_a->threshold > _b->threshold)
3759 return 1;
3760
3761 if (_a->threshold < _b->threshold)
3762 return -1;
3763
3764 return 0;
2e72b634
KS
3765}
3766
c0ff4b85 3767static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
9490ff27
KH
3768{
3769 struct mem_cgroup_eventfd_list *ev;
3770
2bcf2e92
MH
3771 spin_lock(&memcg_oom_lock);
3772
c0ff4b85 3773 list_for_each_entry(ev, &memcg->oom_notify, list)
9490ff27 3774 eventfd_signal(ev->eventfd, 1);
2bcf2e92
MH
3775
3776 spin_unlock(&memcg_oom_lock);
9490ff27
KH
3777 return 0;
3778}
3779
c0ff4b85 3780static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
9490ff27 3781{
7d74b06f
KH
3782 struct mem_cgroup *iter;
3783
c0ff4b85 3784 for_each_mem_cgroup_tree(iter, memcg)
7d74b06f 3785 mem_cgroup_oom_notify_cb(iter);
9490ff27
KH
3786}
3787
59b6f873 3788static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
347c4a87 3789 struct eventfd_ctx *eventfd, const char *args, enum res_type type)
2e72b634 3790{
2c488db2
KS
3791 struct mem_cgroup_thresholds *thresholds;
3792 struct mem_cgroup_threshold_ary *new;
3e32cb2e
JW
3793 unsigned long threshold;
3794 unsigned long usage;
2c488db2 3795 int i, size, ret;
2e72b634 3796
650c5e56 3797 ret = page_counter_memparse(args, "-1", &threshold);
2e72b634
KS
3798 if (ret)
3799 return ret;
3800
3801 mutex_lock(&memcg->thresholds_lock);
2c488db2 3802
05b84301 3803 if (type == _MEM) {
2c488db2 3804 thresholds = &memcg->thresholds;
ce00a967 3805 usage = mem_cgroup_usage(memcg, false);
05b84301 3806 } else if (type == _MEMSWAP) {
2c488db2 3807 thresholds = &memcg->memsw_thresholds;
ce00a967 3808 usage = mem_cgroup_usage(memcg, true);
05b84301 3809 } else
2e72b634
KS
3810 BUG();
3811
2e72b634 3812 /* Check if a threshold crossed before adding a new one */
2c488db2 3813 if (thresholds->primary)
2e72b634
KS
3814 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
3815
2c488db2 3816 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
2e72b634
KS
3817
3818 /* Allocate memory for new array of thresholds */
2c488db2 3819 new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
2e72b634 3820 GFP_KERNEL);
2c488db2 3821 if (!new) {
2e72b634
KS
3822 ret = -ENOMEM;
3823 goto unlock;
3824 }
2c488db2 3825 new->size = size;
2e72b634
KS
3826
3827 /* Copy thresholds (if any) to new array */
2c488db2
KS
3828 if (thresholds->primary) {
3829 memcpy(new->entries, thresholds->primary->entries, (size - 1) *
2e72b634 3830 sizeof(struct mem_cgroup_threshold));
2c488db2
KS
3831 }
3832
2e72b634 3833 /* Add new threshold */
2c488db2
KS
3834 new->entries[size - 1].eventfd = eventfd;
3835 new->entries[size - 1].threshold = threshold;
2e72b634
KS
3836
3837 /* Sort thresholds. Registering of new threshold isn't time-critical */
2c488db2 3838 sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
2e72b634
KS
3839 compare_thresholds, NULL);
3840
3841 /* Find current threshold */
2c488db2 3842 new->current_threshold = -1;
2e72b634 3843 for (i = 0; i < size; i++) {
748dad36 3844 if (new->entries[i].threshold <= usage) {
2e72b634 3845 /*
2c488db2
KS
3846 * new->current_threshold will not be used until
3847 * rcu_assign_pointer(), so it's safe to increment
2e72b634
KS
3848 * it here.
3849 */
2c488db2 3850 ++new->current_threshold;
748dad36
SZ
3851 } else
3852 break;
2e72b634
KS
3853 }
3854
2c488db2
KS
3855 /* Free old spare buffer and save old primary buffer as spare */
3856 kfree(thresholds->spare);
3857 thresholds->spare = thresholds->primary;
3858
3859 rcu_assign_pointer(thresholds->primary, new);
2e72b634 3860
907860ed 3861 /* To be sure that nobody uses thresholds */
2e72b634
KS
3862 synchronize_rcu();
3863
2e72b634
KS
3864unlock:
3865 mutex_unlock(&memcg->thresholds_lock);
3866
3867 return ret;
3868}
3869
59b6f873 3870static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
347c4a87
TH
3871 struct eventfd_ctx *eventfd, const char *args)
3872{
59b6f873 3873 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
347c4a87
TH
3874}
3875
59b6f873 3876static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
347c4a87
TH
3877 struct eventfd_ctx *eventfd, const char *args)
3878{
59b6f873 3879 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
347c4a87
TH
3880}
3881
59b6f873 3882static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
347c4a87 3883 struct eventfd_ctx *eventfd, enum res_type type)
2e72b634 3884{
2c488db2
KS
3885 struct mem_cgroup_thresholds *thresholds;
3886 struct mem_cgroup_threshold_ary *new;
3e32cb2e 3887 unsigned long usage;
2c488db2 3888 int i, j, size;
2e72b634
KS
3889
3890 mutex_lock(&memcg->thresholds_lock);
05b84301
JW
3891
3892 if (type == _MEM) {
2c488db2 3893 thresholds = &memcg->thresholds;
ce00a967 3894 usage = mem_cgroup_usage(memcg, false);
05b84301 3895 } else if (type == _MEMSWAP) {
2c488db2 3896 thresholds = &memcg->memsw_thresholds;
ce00a967 3897 usage = mem_cgroup_usage(memcg, true);
05b84301 3898 } else
2e72b634
KS
3899 BUG();
3900
371528ca
AV
3901 if (!thresholds->primary)
3902 goto unlock;
3903
2e72b634
KS
3904 /* Check if a threshold crossed before removing */
3905 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
3906
3907 /* Calculate new number of threshold */
2c488db2
KS
3908 size = 0;
3909 for (i = 0; i < thresholds->primary->size; i++) {
3910 if (thresholds->primary->entries[i].eventfd != eventfd)
2e72b634
KS
3911 size++;
3912 }
3913
2c488db2 3914 new = thresholds->spare;
907860ed 3915
2e72b634
KS
3916 /* Set thresholds array to NULL if we don't have thresholds */
3917 if (!size) {
2c488db2
KS
3918 kfree(new);
3919 new = NULL;
907860ed 3920 goto swap_buffers;
2e72b634
KS
3921 }
3922
2c488db2 3923 new->size = size;
2e72b634
KS
3924
3925 /* Copy thresholds and find current threshold */
2c488db2
KS
3926 new->current_threshold = -1;
3927 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
3928 if (thresholds->primary->entries[i].eventfd == eventfd)
2e72b634
KS
3929 continue;
3930
2c488db2 3931 new->entries[j] = thresholds->primary->entries[i];
748dad36 3932 if (new->entries[j].threshold <= usage) {
2e72b634 3933 /*
2c488db2 3934 * new->current_threshold will not be used
2e72b634
KS
3935 * until rcu_assign_pointer(), so it's safe to increment
3936 * it here.
3937 */
2c488db2 3938 ++new->current_threshold;
2e72b634
KS
3939 }
3940 j++;
3941 }
3942
907860ed 3943swap_buffers:
2c488db2
KS
3944 /* Swap primary and spare array */
3945 thresholds->spare = thresholds->primary;
8c757763
SZ
3946 /* If all events are unregistered, free the spare array */
3947 if (!new) {
3948 kfree(thresholds->spare);
3949 thresholds->spare = NULL;
3950 }
3951
2c488db2 3952 rcu_assign_pointer(thresholds->primary, new);
2e72b634 3953
907860ed 3954 /* To be sure that nobody uses thresholds */
2e72b634 3955 synchronize_rcu();
371528ca 3956unlock:
2e72b634 3957 mutex_unlock(&memcg->thresholds_lock);
2e72b634 3958}
c1e862c1 3959
59b6f873 3960static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
347c4a87
TH
3961 struct eventfd_ctx *eventfd)
3962{
59b6f873 3963 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
347c4a87
TH
3964}
3965
59b6f873 3966static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
347c4a87
TH
3967 struct eventfd_ctx *eventfd)
3968{
59b6f873 3969 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
347c4a87
TH
3970}
3971
59b6f873 3972static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
347c4a87 3973 struct eventfd_ctx *eventfd, const char *args)
9490ff27 3974{
9490ff27 3975 struct mem_cgroup_eventfd_list *event;
9490ff27 3976
9490ff27
KH
3977 event = kmalloc(sizeof(*event), GFP_KERNEL);
3978 if (!event)
3979 return -ENOMEM;
3980
1af8efe9 3981 spin_lock(&memcg_oom_lock);
9490ff27
KH
3982
3983 event->eventfd = eventfd;
3984 list_add(&event->list, &memcg->oom_notify);
3985
3986 /* already in OOM ? */
79dfdacc 3987 if (atomic_read(&memcg->under_oom))
9490ff27 3988 eventfd_signal(eventfd, 1);
1af8efe9 3989 spin_unlock(&memcg_oom_lock);
9490ff27
KH
3990
3991 return 0;
3992}
3993
59b6f873 3994static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
347c4a87 3995 struct eventfd_ctx *eventfd)
9490ff27 3996{
9490ff27 3997 struct mem_cgroup_eventfd_list *ev, *tmp;
9490ff27 3998
1af8efe9 3999 spin_lock(&memcg_oom_lock);
9490ff27 4000
c0ff4b85 4001 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
9490ff27
KH
4002 if (ev->eventfd == eventfd) {
4003 list_del(&ev->list);
4004 kfree(ev);
4005 }
4006 }
4007
1af8efe9 4008 spin_unlock(&memcg_oom_lock);
9490ff27
KH
4009}
4010
2da8ca82 4011static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
3c11ecf4 4012{
2da8ca82 4013 struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(sf));
3c11ecf4 4014
791badbd
TH
4015 seq_printf(sf, "oom_kill_disable %d\n", memcg->oom_kill_disable);
4016 seq_printf(sf, "under_oom %d\n", (bool)atomic_read(&memcg->under_oom));
3c11ecf4
KH
4017 return 0;
4018}
4019
182446d0 4020static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
3c11ecf4
KH
4021 struct cftype *cft, u64 val)
4022{
182446d0 4023 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3c11ecf4
KH
4024
4025 /* cannot set to root cgroup and only 0 and 1 are allowed */
14208b0e 4026 if (!css->parent || !((val == 0) || (val == 1)))
3c11ecf4
KH
4027 return -EINVAL;
4028
c0ff4b85 4029 memcg->oom_kill_disable = val;
4d845ebf 4030 if (!val)
c0ff4b85 4031 memcg_oom_recover(memcg);
3dae7fec 4032
3c11ecf4
KH
4033 return 0;
4034}
4035
c255a458 4036#ifdef CONFIG_MEMCG_KMEM
cbe128e3 4037static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
e5671dfa 4038{
55007d84
GC
4039 int ret;
4040
55007d84
GC
4041 ret = memcg_propagate_kmem(memcg);
4042 if (ret)
4043 return ret;
2633d7a0 4044
1d62e436 4045 return mem_cgroup_sockets_init(memcg, ss);
573b400d 4046}
e5671dfa 4047
2a4db7eb
VD
4048static void memcg_deactivate_kmem(struct mem_cgroup *memcg)
4049{
4050 if (!memcg->kmem_acct_active)
4051 return;
4052
4053 /*
4054 * Clear the 'active' flag before clearing memcg_caches arrays entries.
4055 * Since we take the slab_mutex in memcg_deactivate_kmem_caches(), it
4056 * guarantees no cache will be created for this cgroup after we are
4057 * done (see memcg_create_kmem_cache()).
4058 */
4059 memcg->kmem_acct_active = false;
4060
4061 memcg_deactivate_kmem_caches(memcg);
4062}
4063
10d5ebf4 4064static void memcg_destroy_kmem(struct mem_cgroup *memcg)
d1a4c0b3 4065{
d5b3cf71 4066 memcg_destroy_kmem_caches(memcg);
1d62e436 4067 mem_cgroup_sockets_destroy(memcg);
10d5ebf4 4068}
e5671dfa 4069#else
cbe128e3 4070static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
e5671dfa
GC
4071{
4072 return 0;
4073}
d1a4c0b3 4074
2a4db7eb
VD
4075static void memcg_deactivate_kmem(struct mem_cgroup *memcg)
4076{
4077}
4078
10d5ebf4
LZ
4079static void memcg_destroy_kmem(struct mem_cgroup *memcg)
4080{
4081}
e5671dfa
GC
4082#endif
4083
3bc942f3
TH
4084/*
4085 * DO NOT USE IN NEW FILES.
4086 *
4087 * "cgroup.event_control" implementation.
4088 *
4089 * This is way over-engineered. It tries to support fully configurable
4090 * events for each user. Such level of flexibility is completely
4091 * unnecessary especially in the light of the planned unified hierarchy.
4092 *
4093 * Please deprecate this and replace with something simpler if at all
4094 * possible.
4095 */
4096
79bd9814
TH
4097/*
4098 * Unregister event and free resources.
4099 *
4100 * Gets called from workqueue.
4101 */
3bc942f3 4102static void memcg_event_remove(struct work_struct *work)
79bd9814 4103{
3bc942f3
TH
4104 struct mem_cgroup_event *event =
4105 container_of(work, struct mem_cgroup_event, remove);
59b6f873 4106 struct mem_cgroup *memcg = event->memcg;
79bd9814
TH
4107
4108 remove_wait_queue(event->wqh, &event->wait);
4109
59b6f873 4110 event->unregister_event(memcg, event->eventfd);
79bd9814
TH
4111
4112 /* Notify userspace the event is going away. */
4113 eventfd_signal(event->eventfd, 1);
4114
4115 eventfd_ctx_put(event->eventfd);
4116 kfree(event);
59b6f873 4117 css_put(&memcg->css);
79bd9814
TH
4118}
4119
4120/*
4121 * Gets called on POLLHUP on eventfd when user closes it.
4122 *
4123 * Called with wqh->lock held and interrupts disabled.
4124 */
3bc942f3
TH
4125static int memcg_event_wake(wait_queue_t *wait, unsigned mode,
4126 int sync, void *key)
79bd9814 4127{
3bc942f3
TH
4128 struct mem_cgroup_event *event =
4129 container_of(wait, struct mem_cgroup_event, wait);
59b6f873 4130 struct mem_cgroup *memcg = event->memcg;
79bd9814
TH
4131 unsigned long flags = (unsigned long)key;
4132
4133 if (flags & POLLHUP) {
4134 /*
4135 * If the event has been detached at cgroup removal, we
4136 * can simply return knowing the other side will cleanup
4137 * for us.
4138 *
4139 * We can't race against event freeing since the other
4140 * side will require wqh->lock via remove_wait_queue(),
4141 * which we hold.
4142 */
fba94807 4143 spin_lock(&memcg->event_list_lock);
79bd9814
TH
4144 if (!list_empty(&event->list)) {
4145 list_del_init(&event->list);
4146 /*
4147 * We are in atomic context, but cgroup_event_remove()
4148 * may sleep, so we have to call it in workqueue.
4149 */
4150 schedule_work(&event->remove);
4151 }
fba94807 4152 spin_unlock(&memcg->event_list_lock);
79bd9814
TH
4153 }
4154
4155 return 0;
4156}
4157
3bc942f3 4158static void memcg_event_ptable_queue_proc(struct file *file,
79bd9814
TH
4159 wait_queue_head_t *wqh, poll_table *pt)
4160{
3bc942f3
TH
4161 struct mem_cgroup_event *event =
4162 container_of(pt, struct mem_cgroup_event, pt);
79bd9814
TH
4163
4164 event->wqh = wqh;
4165 add_wait_queue(wqh, &event->wait);
4166}
4167
4168/*
3bc942f3
TH
4169 * DO NOT USE IN NEW FILES.
4170 *
79bd9814
TH
4171 * Parse input and register new cgroup event handler.
4172 *
4173 * Input must be in format '<event_fd> <control_fd> <args>'.
4174 * Interpretation of args is defined by control file implementation.
4175 */
451af504
TH
4176static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
4177 char *buf, size_t nbytes, loff_t off)
79bd9814 4178{
451af504 4179 struct cgroup_subsys_state *css = of_css(of);
fba94807 4180 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3bc942f3 4181 struct mem_cgroup_event *event;
79bd9814
TH
4182 struct cgroup_subsys_state *cfile_css;
4183 unsigned int efd, cfd;
4184 struct fd efile;
4185 struct fd cfile;
fba94807 4186 const char *name;
79bd9814
TH
4187 char *endp;
4188 int ret;
4189
451af504
TH
4190 buf = strstrip(buf);
4191
4192 efd = simple_strtoul(buf, &endp, 10);
79bd9814
TH
4193 if (*endp != ' ')
4194 return -EINVAL;
451af504 4195 buf = endp + 1;
79bd9814 4196
451af504 4197 cfd = simple_strtoul(buf, &endp, 10);
79bd9814
TH
4198 if ((*endp != ' ') && (*endp != '\0'))
4199 return -EINVAL;
451af504 4200 buf = endp + 1;
79bd9814
TH
4201
4202 event = kzalloc(sizeof(*event), GFP_KERNEL);
4203 if (!event)
4204 return -ENOMEM;
4205
59b6f873 4206 event->memcg = memcg;
79bd9814 4207 INIT_LIST_HEAD(&event->list);
3bc942f3
TH
4208 init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
4209 init_waitqueue_func_entry(&event->wait, memcg_event_wake);
4210 INIT_WORK(&event->remove, memcg_event_remove);
79bd9814
TH
4211
4212 efile = fdget(efd);
4213 if (!efile.file) {
4214 ret = -EBADF;
4215 goto out_kfree;
4216 }
4217
4218 event->eventfd = eventfd_ctx_fileget(efile.file);
4219 if (IS_ERR(event->eventfd)) {
4220 ret = PTR_ERR(event->eventfd);
4221 goto out_put_efile;
4222 }
4223
4224 cfile = fdget(cfd);
4225 if (!cfile.file) {
4226 ret = -EBADF;
4227 goto out_put_eventfd;
4228 }
4229
4230 /* the process need read permission on control file */
4231 /* AV: shouldn't we check that it's been opened for read instead? */
4232 ret = inode_permission(file_inode(cfile.file), MAY_READ);
4233 if (ret < 0)
4234 goto out_put_cfile;
4235
fba94807
TH
4236 /*
4237 * Determine the event callbacks and set them in @event. This used
4238 * to be done via struct cftype but cgroup core no longer knows
4239 * about these events. The following is crude but the whole thing
4240 * is for compatibility anyway.
3bc942f3
TH
4241 *
4242 * DO NOT ADD NEW FILES.
fba94807 4243 */
b583043e 4244 name = cfile.file->f_path.dentry->d_name.name;
fba94807
TH
4245
4246 if (!strcmp(name, "memory.usage_in_bytes")) {
4247 event->register_event = mem_cgroup_usage_register_event;
4248 event->unregister_event = mem_cgroup_usage_unregister_event;
4249 } else if (!strcmp(name, "memory.oom_control")) {
4250 event->register_event = mem_cgroup_oom_register_event;
4251 event->unregister_event = mem_cgroup_oom_unregister_event;
4252 } else if (!strcmp(name, "memory.pressure_level")) {
4253 event->register_event = vmpressure_register_event;
4254 event->unregister_event = vmpressure_unregister_event;
4255 } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
347c4a87
TH
4256 event->register_event = memsw_cgroup_usage_register_event;
4257 event->unregister_event = memsw_cgroup_usage_unregister_event;
fba94807
TH
4258 } else {
4259 ret = -EINVAL;
4260 goto out_put_cfile;
4261 }
4262
79bd9814 4263 /*
b5557c4c
TH
4264 * Verify @cfile should belong to @css. Also, remaining events are
4265 * automatically removed on cgroup destruction but the removal is
4266 * asynchronous, so take an extra ref on @css.
79bd9814 4267 */
b583043e 4268 cfile_css = css_tryget_online_from_dir(cfile.file->f_path.dentry->d_parent,
ec903c0c 4269 &memory_cgrp_subsys);
79bd9814 4270 ret = -EINVAL;
5a17f543 4271 if (IS_ERR(cfile_css))
79bd9814 4272 goto out_put_cfile;
5a17f543
TH
4273 if (cfile_css != css) {
4274 css_put(cfile_css);
79bd9814 4275 goto out_put_cfile;
5a17f543 4276 }
79bd9814 4277
451af504 4278 ret = event->register_event(memcg, event->eventfd, buf);
79bd9814
TH
4279 if (ret)
4280 goto out_put_css;
4281
4282 efile.file->f_op->poll(efile.file, &event->pt);
4283
fba94807
TH
4284 spin_lock(&memcg->event_list_lock);
4285 list_add(&event->list, &memcg->event_list);
4286 spin_unlock(&memcg->event_list_lock);
79bd9814
TH
4287
4288 fdput(cfile);
4289 fdput(efile);
4290
451af504 4291 return nbytes;
79bd9814
TH
4292
4293out_put_css:
b5557c4c 4294 css_put(css);
79bd9814
TH
4295out_put_cfile:
4296 fdput(cfile);
4297out_put_eventfd:
4298 eventfd_ctx_put(event->eventfd);
4299out_put_efile:
4300 fdput(efile);
4301out_kfree:
4302 kfree(event);
4303
4304 return ret;
4305}
4306
241994ed 4307static struct cftype mem_cgroup_legacy_files[] = {
8cdea7c0 4308 {
0eea1030 4309 .name = "usage_in_bytes",
8c7c6e34 4310 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
791badbd 4311 .read_u64 = mem_cgroup_read_u64,
8cdea7c0 4312 },
c84872e1
PE
4313 {
4314 .name = "max_usage_in_bytes",
8c7c6e34 4315 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
6770c64e 4316 .write = mem_cgroup_reset,
791badbd 4317 .read_u64 = mem_cgroup_read_u64,
c84872e1 4318 },
8cdea7c0 4319 {
0eea1030 4320 .name = "limit_in_bytes",
8c7c6e34 4321 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
451af504 4322 .write = mem_cgroup_write,
791badbd 4323 .read_u64 = mem_cgroup_read_u64,
8cdea7c0 4324 },
296c81d8
BS
4325 {
4326 .name = "soft_limit_in_bytes",
4327 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
451af504 4328 .write = mem_cgroup_write,
791badbd 4329 .read_u64 = mem_cgroup_read_u64,
296c81d8 4330 },
8cdea7c0
BS
4331 {
4332 .name = "failcnt",
8c7c6e34 4333 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
6770c64e 4334 .write = mem_cgroup_reset,
791badbd 4335 .read_u64 = mem_cgroup_read_u64,
8cdea7c0 4336 },
d2ceb9b7
KH
4337 {
4338 .name = "stat",
2da8ca82 4339 .seq_show = memcg_stat_show,
d2ceb9b7 4340 },
c1e862c1
KH
4341 {
4342 .name = "force_empty",
6770c64e 4343 .write = mem_cgroup_force_empty_write,
c1e862c1 4344 },
18f59ea7
BS
4345 {
4346 .name = "use_hierarchy",
4347 .write_u64 = mem_cgroup_hierarchy_write,
4348 .read_u64 = mem_cgroup_hierarchy_read,
4349 },
79bd9814 4350 {
3bc942f3 4351 .name = "cgroup.event_control", /* XXX: for compat */
451af504 4352 .write = memcg_write_event_control,
79bd9814
TH
4353 .flags = CFTYPE_NO_PREFIX,
4354 .mode = S_IWUGO,
4355 },
a7885eb8
KM
4356 {
4357 .name = "swappiness",
4358 .read_u64 = mem_cgroup_swappiness_read,
4359 .write_u64 = mem_cgroup_swappiness_write,
4360 },
7dc74be0
DN
4361 {
4362 .name = "move_charge_at_immigrate",
4363 .read_u64 = mem_cgroup_move_charge_read,
4364 .write_u64 = mem_cgroup_move_charge_write,
4365 },
9490ff27
KH
4366 {
4367 .name = "oom_control",
2da8ca82 4368 .seq_show = mem_cgroup_oom_control_read,
3c11ecf4 4369 .write_u64 = mem_cgroup_oom_control_write,
9490ff27
KH
4370 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
4371 },
70ddf637
AV
4372 {
4373 .name = "pressure_level",
70ddf637 4374 },
406eb0c9
YH
4375#ifdef CONFIG_NUMA
4376 {
4377 .name = "numa_stat",
2da8ca82 4378 .seq_show = memcg_numa_stat_show,
406eb0c9
YH
4379 },
4380#endif
510fc4e1
GC
4381#ifdef CONFIG_MEMCG_KMEM
4382 {
4383 .name = "kmem.limit_in_bytes",
4384 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
451af504 4385 .write = mem_cgroup_write,
791badbd 4386 .read_u64 = mem_cgroup_read_u64,
510fc4e1
GC
4387 },
4388 {
4389 .name = "kmem.usage_in_bytes",
4390 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
791badbd 4391 .read_u64 = mem_cgroup_read_u64,
510fc4e1
GC
4392 },
4393 {
4394 .name = "kmem.failcnt",
4395 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
6770c64e 4396 .write = mem_cgroup_reset,
791badbd 4397 .read_u64 = mem_cgroup_read_u64,
510fc4e1
GC
4398 },
4399 {
4400 .name = "kmem.max_usage_in_bytes",
4401 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
6770c64e 4402 .write = mem_cgroup_reset,
791badbd 4403 .read_u64 = mem_cgroup_read_u64,
510fc4e1 4404 },
749c5415
GC
4405#ifdef CONFIG_SLABINFO
4406 {
4407 .name = "kmem.slabinfo",
b047501c
VD
4408 .seq_start = slab_start,
4409 .seq_next = slab_next,
4410 .seq_stop = slab_stop,
4411 .seq_show = memcg_slab_show,
749c5415
GC
4412 },
4413#endif
8c7c6e34 4414#endif
6bc10349 4415 { }, /* terminate */
af36f906 4416};
8c7c6e34 4417
c0ff4b85 4418static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
6d12e2d8
KH
4419{
4420 struct mem_cgroup_per_node *pn;
1ecaab2b 4421 struct mem_cgroup_per_zone *mz;
41e3355d 4422 int zone, tmp = node;
1ecaab2b
KH
4423 /*
4424 * This routine is called against possible nodes.
4425 * But it's BUG to call kmalloc() against offline node.
4426 *
4427 * TODO: this routine can waste much memory for nodes which will
4428 * never be onlined. It's better to use memory hotplug callback
4429 * function.
4430 */
41e3355d
KH
4431 if (!node_state(node, N_NORMAL_MEMORY))
4432 tmp = -1;
17295c88 4433 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
6d12e2d8
KH
4434 if (!pn)
4435 return 1;
1ecaab2b 4436
1ecaab2b
KH
4437 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4438 mz = &pn->zoneinfo[zone];
bea8c150 4439 lruvec_init(&mz->lruvec);
bb4cc1a8
AM
4440 mz->usage_in_excess = 0;
4441 mz->on_tree = false;
d79154bb 4442 mz->memcg = memcg;
1ecaab2b 4443 }
54f72fe0 4444 memcg->nodeinfo[node] = pn;
6d12e2d8
KH
4445 return 0;
4446}
4447
c0ff4b85 4448static void free_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
1ecaab2b 4449{
54f72fe0 4450 kfree(memcg->nodeinfo[node]);
1ecaab2b
KH
4451}
4452
33327948
KH
4453static struct mem_cgroup *mem_cgroup_alloc(void)
4454{
d79154bb 4455 struct mem_cgroup *memcg;
8ff69e2c 4456 size_t size;
33327948 4457
8ff69e2c
VD
4458 size = sizeof(struct mem_cgroup);
4459 size += nr_node_ids * sizeof(struct mem_cgroup_per_node *);
33327948 4460
8ff69e2c 4461 memcg = kzalloc(size, GFP_KERNEL);
d79154bb 4462 if (!memcg)
e7bbcdf3
DC
4463 return NULL;
4464
d79154bb
HD
4465 memcg->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
4466 if (!memcg->stat)
d2e61b8d 4467 goto out_free;
d79154bb
HD
4468 spin_lock_init(&memcg->pcp_counter_lock);
4469 return memcg;
d2e61b8d
DC
4470
4471out_free:
8ff69e2c 4472 kfree(memcg);
d2e61b8d 4473 return NULL;
33327948
KH
4474}
4475
59927fb9 4476/*
c8b2a36f
GC
4477 * At destroying mem_cgroup, references from swap_cgroup can remain.
4478 * (scanning all at force_empty is too costly...)
4479 *
4480 * Instead of clearing all references at force_empty, we remember
4481 * the number of reference from swap_cgroup and free mem_cgroup when
4482 * it goes down to 0.
4483 *
4484 * Removal of cgroup itself succeeds regardless of refs from swap.
59927fb9 4485 */
c8b2a36f
GC
4486
4487static void __mem_cgroup_free(struct mem_cgroup *memcg)
59927fb9 4488{
c8b2a36f 4489 int node;
59927fb9 4490
bb4cc1a8 4491 mem_cgroup_remove_from_trees(memcg);
c8b2a36f
GC
4492
4493 for_each_node(node)
4494 free_mem_cgroup_per_zone_info(memcg, node);
4495
4496 free_percpu(memcg->stat);
4497
a8964b9b 4498 disarm_static_keys(memcg);
8ff69e2c 4499 kfree(memcg);
59927fb9 4500}
3afe36b1 4501
7bcc1bb1
DN
4502/*
4503 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
4504 */
e1aab161 4505struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg)
7bcc1bb1 4506{
3e32cb2e 4507 if (!memcg->memory.parent)
7bcc1bb1 4508 return NULL;
3e32cb2e 4509 return mem_cgroup_from_counter(memcg->memory.parent, memory);
7bcc1bb1 4510}
e1aab161 4511EXPORT_SYMBOL(parent_mem_cgroup);
33327948 4512
0eb253e2 4513static struct cgroup_subsys_state * __ref
eb95419b 4514mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
8cdea7c0 4515{
d142e3e6 4516 struct mem_cgroup *memcg;
04046e1a 4517 long error = -ENOMEM;
6d12e2d8 4518 int node;
8cdea7c0 4519
c0ff4b85
R
4520 memcg = mem_cgroup_alloc();
4521 if (!memcg)
04046e1a 4522 return ERR_PTR(error);
78fb7466 4523
3ed28fa1 4524 for_each_node(node)
c0ff4b85 4525 if (alloc_mem_cgroup_per_zone_info(memcg, node))
6d12e2d8 4526 goto free_out;
f64c3f54 4527
c077719b 4528 /* root ? */
eb95419b 4529 if (parent_css == NULL) {
a41c58a6 4530 root_mem_cgroup = memcg;
3e32cb2e 4531 page_counter_init(&memcg->memory, NULL);
241994ed 4532 memcg->high = PAGE_COUNTER_MAX;
24d404dc 4533 memcg->soft_limit = PAGE_COUNTER_MAX;
3e32cb2e
JW
4534 page_counter_init(&memcg->memsw, NULL);
4535 page_counter_init(&memcg->kmem, NULL);
18f59ea7 4536 }
28dbc4b6 4537
d142e3e6
GC
4538 memcg->last_scanned_node = MAX_NUMNODES;
4539 INIT_LIST_HEAD(&memcg->oom_notify);
d142e3e6
GC
4540 memcg->move_charge_at_immigrate = 0;
4541 mutex_init(&memcg->thresholds_lock);
4542 spin_lock_init(&memcg->move_lock);
70ddf637 4543 vmpressure_init(&memcg->vmpressure);
fba94807
TH
4544 INIT_LIST_HEAD(&memcg->event_list);
4545 spin_lock_init(&memcg->event_list_lock);
900a38f0
VD
4546#ifdef CONFIG_MEMCG_KMEM
4547 memcg->kmemcg_id = -1;
900a38f0 4548#endif
d142e3e6
GC
4549
4550 return &memcg->css;
4551
4552free_out:
4553 __mem_cgroup_free(memcg);
4554 return ERR_PTR(error);
4555}
4556
4557static int
eb95419b 4558mem_cgroup_css_online(struct cgroup_subsys_state *css)
d142e3e6 4559{
eb95419b 4560 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5c9d535b 4561 struct mem_cgroup *parent = mem_cgroup_from_css(css->parent);
2f7dd7a4 4562 int ret;
d142e3e6 4563
15a4c835 4564 if (css->id > MEM_CGROUP_ID_MAX)
4219b2da
LZ
4565 return -ENOSPC;
4566
63876986 4567 if (!parent)
d142e3e6
GC
4568 return 0;
4569
0999821b 4570 mutex_lock(&memcg_create_mutex);
d142e3e6
GC
4571
4572 memcg->use_hierarchy = parent->use_hierarchy;
4573 memcg->oom_kill_disable = parent->oom_kill_disable;
4574 memcg->swappiness = mem_cgroup_swappiness(parent);
4575
4576 if (parent->use_hierarchy) {
3e32cb2e 4577 page_counter_init(&memcg->memory, &parent->memory);
241994ed 4578 memcg->high = PAGE_COUNTER_MAX;
24d404dc 4579 memcg->soft_limit = PAGE_COUNTER_MAX;
3e32cb2e
JW
4580 page_counter_init(&memcg->memsw, &parent->memsw);
4581 page_counter_init(&memcg->kmem, &parent->kmem);
55007d84 4582
7bcc1bb1 4583 /*
8d76a979
LZ
4584 * No need to take a reference to the parent because cgroup
4585 * core guarantees its existence.
7bcc1bb1 4586 */
18f59ea7 4587 } else {
3e32cb2e 4588 page_counter_init(&memcg->memory, NULL);
241994ed 4589 memcg->high = PAGE_COUNTER_MAX;
24d404dc 4590 memcg->soft_limit = PAGE_COUNTER_MAX;
3e32cb2e
JW
4591 page_counter_init(&memcg->memsw, NULL);
4592 page_counter_init(&memcg->kmem, NULL);
8c7f6edb
TH
4593 /*
4594 * Deeper hierachy with use_hierarchy == false doesn't make
4595 * much sense so let cgroup subsystem know about this
4596 * unfortunate state in our controller.
4597 */
d142e3e6 4598 if (parent != root_mem_cgroup)
073219e9 4599 memory_cgrp_subsys.broken_hierarchy = true;
18f59ea7 4600 }
0999821b 4601 mutex_unlock(&memcg_create_mutex);
d6441637 4602
2f7dd7a4
JW
4603 ret = memcg_init_kmem(memcg, &memory_cgrp_subsys);
4604 if (ret)
4605 return ret;
4606
4607 /*
4608 * Make sure the memcg is initialized: mem_cgroup_iter()
4609 * orders reading memcg->initialized against its callers
4610 * reading the memcg members.
4611 */
4612 smp_store_release(&memcg->initialized, 1);
4613
4614 return 0;
8cdea7c0
BS
4615}
4616
eb95419b 4617static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
df878fb0 4618{
eb95419b 4619 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3bc942f3 4620 struct mem_cgroup_event *event, *tmp;
79bd9814
TH
4621
4622 /*
4623 * Unregister events and notify userspace.
4624 * Notify userspace about cgroup removing only after rmdir of cgroup
4625 * directory to avoid race between userspace and kernelspace.
4626 */
fba94807
TH
4627 spin_lock(&memcg->event_list_lock);
4628 list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
79bd9814
TH
4629 list_del_init(&event->list);
4630 schedule_work(&event->remove);
4631 }
fba94807 4632 spin_unlock(&memcg->event_list_lock);
ec64f515 4633
33cb876e 4634 vmpressure_cleanup(&memcg->vmpressure);
2a4db7eb
VD
4635
4636 memcg_deactivate_kmem(memcg);
df878fb0
KH
4637}
4638
eb95419b 4639static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
8cdea7c0 4640{
eb95419b 4641 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
c268e994 4642
10d5ebf4 4643 memcg_destroy_kmem(memcg);
465939a1 4644 __mem_cgroup_free(memcg);
8cdea7c0
BS
4645}
4646
1ced953b
TH
4647/**
4648 * mem_cgroup_css_reset - reset the states of a mem_cgroup
4649 * @css: the target css
4650 *
4651 * Reset the states of the mem_cgroup associated with @css. This is
4652 * invoked when the userland requests disabling on the default hierarchy
4653 * but the memcg is pinned through dependency. The memcg should stop
4654 * applying policies and should revert to the vanilla state as it may be
4655 * made visible again.
4656 *
4657 * The current implementation only resets the essential configurations.
4658 * This needs to be expanded to cover all the visible parts.
4659 */
4660static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
4661{
4662 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4663
3e32cb2e
JW
4664 mem_cgroup_resize_limit(memcg, PAGE_COUNTER_MAX);
4665 mem_cgroup_resize_memsw_limit(memcg, PAGE_COUNTER_MAX);
4666 memcg_update_kmem_limit(memcg, PAGE_COUNTER_MAX);
241994ed
JW
4667 memcg->low = 0;
4668 memcg->high = PAGE_COUNTER_MAX;
24d404dc 4669 memcg->soft_limit = PAGE_COUNTER_MAX;
1ced953b
TH
4670}
4671
02491447 4672#ifdef CONFIG_MMU
7dc74be0 4673/* Handlers for move charge at task migration. */
854ffa8d 4674static int mem_cgroup_do_precharge(unsigned long count)
7dc74be0 4675{
05b84301 4676 int ret;
9476db97
JW
4677
4678 /* Try a single bulk charge without reclaim first */
00501b53 4679 ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_WAIT, count);
9476db97 4680 if (!ret) {
854ffa8d 4681 mc.precharge += count;
854ffa8d
DN
4682 return ret;
4683 }
692e7c45 4684 if (ret == -EINTR) {
00501b53 4685 cancel_charge(root_mem_cgroup, count);
692e7c45
JW
4686 return ret;
4687 }
9476db97
JW
4688
4689 /* Try charges one by one with reclaim */
854ffa8d 4690 while (count--) {
00501b53 4691 ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_NORETRY, 1);
9476db97
JW
4692 /*
4693 * In case of failure, any residual charges against
4694 * mc.to will be dropped by mem_cgroup_clear_mc()
692e7c45
JW
4695 * later on. However, cancel any charges that are
4696 * bypassed to root right away or they'll be lost.
9476db97 4697 */
692e7c45 4698 if (ret == -EINTR)
00501b53 4699 cancel_charge(root_mem_cgroup, 1);
38c5d72f 4700 if (ret)
38c5d72f 4701 return ret;
854ffa8d 4702 mc.precharge++;
9476db97 4703 cond_resched();
854ffa8d 4704 }
9476db97 4705 return 0;
4ffef5fe
DN
4706}
4707
4708/**
8d32ff84 4709 * get_mctgt_type - get target type of moving charge
4ffef5fe
DN
4710 * @vma: the vma the pte to be checked belongs
4711 * @addr: the address corresponding to the pte to be checked
4712 * @ptent: the pte to be checked
02491447 4713 * @target: the pointer the target page or swap ent will be stored(can be NULL)
4ffef5fe
DN
4714 *
4715 * Returns
4716 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
4717 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
4718 * move charge. if @target is not NULL, the page is stored in target->page
4719 * with extra refcnt got(Callers should handle it).
02491447
DN
4720 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
4721 * target for charge migration. if @target is not NULL, the entry is stored
4722 * in target->ent.
4ffef5fe
DN
4723 *
4724 * Called with pte lock held.
4725 */
4ffef5fe
DN
4726union mc_target {
4727 struct page *page;
02491447 4728 swp_entry_t ent;
4ffef5fe
DN
4729};
4730
4ffef5fe 4731enum mc_target_type {
8d32ff84 4732 MC_TARGET_NONE = 0,
4ffef5fe 4733 MC_TARGET_PAGE,
02491447 4734 MC_TARGET_SWAP,
4ffef5fe
DN
4735};
4736
90254a65
DN
4737static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
4738 unsigned long addr, pte_t ptent)
4ffef5fe 4739{
90254a65 4740 struct page *page = vm_normal_page(vma, addr, ptent);
4ffef5fe 4741
90254a65
DN
4742 if (!page || !page_mapped(page))
4743 return NULL;
4744 if (PageAnon(page)) {
1dfab5ab 4745 if (!(mc.flags & MOVE_ANON))
90254a65 4746 return NULL;
1dfab5ab
JW
4747 } else {
4748 if (!(mc.flags & MOVE_FILE))
4749 return NULL;
4750 }
90254a65
DN
4751 if (!get_page_unless_zero(page))
4752 return NULL;
4753
4754 return page;
4755}
4756
4b91355e 4757#ifdef CONFIG_SWAP
90254a65
DN
4758static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
4759 unsigned long addr, pte_t ptent, swp_entry_t *entry)
4760{
90254a65
DN
4761 struct page *page = NULL;
4762 swp_entry_t ent = pte_to_swp_entry(ptent);
4763
1dfab5ab 4764 if (!(mc.flags & MOVE_ANON) || non_swap_entry(ent))
90254a65 4765 return NULL;
4b91355e
KH
4766 /*
4767 * Because lookup_swap_cache() updates some statistics counter,
4768 * we call find_get_page() with swapper_space directly.
4769 */
33806f06 4770 page = find_get_page(swap_address_space(ent), ent.val);
90254a65
DN
4771 if (do_swap_account)
4772 entry->val = ent.val;
4773
4774 return page;
4775}
4b91355e
KH
4776#else
4777static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
4778 unsigned long addr, pte_t ptent, swp_entry_t *entry)
4779{
4780 return NULL;
4781}
4782#endif
90254a65 4783
87946a72
DN
4784static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
4785 unsigned long addr, pte_t ptent, swp_entry_t *entry)
4786{
4787 struct page *page = NULL;
87946a72
DN
4788 struct address_space *mapping;
4789 pgoff_t pgoff;
4790
4791 if (!vma->vm_file) /* anonymous vma */
4792 return NULL;
1dfab5ab 4793 if (!(mc.flags & MOVE_FILE))
87946a72
DN
4794 return NULL;
4795
87946a72 4796 mapping = vma->vm_file->f_mapping;
0661a336 4797 pgoff = linear_page_index(vma, addr);
87946a72
DN
4798
4799 /* page is moved even if it's not RSS of this task(page-faulted). */
aa3b1895
HD
4800#ifdef CONFIG_SWAP
4801 /* shmem/tmpfs may report page out on swap: account for that too. */
139b6a6f
JW
4802 if (shmem_mapping(mapping)) {
4803 page = find_get_entry(mapping, pgoff);
4804 if (radix_tree_exceptional_entry(page)) {
4805 swp_entry_t swp = radix_to_swp_entry(page);
4806 if (do_swap_account)
4807 *entry = swp;
4808 page = find_get_page(swap_address_space(swp), swp.val);
4809 }
4810 } else
4811 page = find_get_page(mapping, pgoff);
4812#else
4813 page = find_get_page(mapping, pgoff);
aa3b1895 4814#endif
87946a72
DN
4815 return page;
4816}
4817
8d32ff84 4818static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
90254a65
DN
4819 unsigned long addr, pte_t ptent, union mc_target *target)
4820{
4821 struct page *page = NULL;
8d32ff84 4822 enum mc_target_type ret = MC_TARGET_NONE;
90254a65
DN
4823 swp_entry_t ent = { .val = 0 };
4824
4825 if (pte_present(ptent))
4826 page = mc_handle_present_pte(vma, addr, ptent);
4827 else if (is_swap_pte(ptent))
4828 page = mc_handle_swap_pte(vma, addr, ptent, &ent);
0661a336 4829 else if (pte_none(ptent))
87946a72 4830 page = mc_handle_file_pte(vma, addr, ptent, &ent);
90254a65
DN
4831
4832 if (!page && !ent.val)
8d32ff84 4833 return ret;
02491447 4834 if (page) {
02491447 4835 /*
0a31bc97 4836 * Do only loose check w/o serialization.
1306a85a 4837 * mem_cgroup_move_account() checks the page is valid or
0a31bc97 4838 * not under LRU exclusion.
02491447 4839 */
1306a85a 4840 if (page->mem_cgroup == mc.from) {
02491447
DN
4841 ret = MC_TARGET_PAGE;
4842 if (target)
4843 target->page = page;
4844 }
4845 if (!ret || !target)
4846 put_page(page);
4847 }
90254a65
DN
4848 /* There is a swap entry and a page doesn't exist or isn't charged */
4849 if (ent.val && !ret &&
34c00c31 4850 mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
7f0f1546
KH
4851 ret = MC_TARGET_SWAP;
4852 if (target)
4853 target->ent = ent;
4ffef5fe 4854 }
4ffef5fe
DN
4855 return ret;
4856}
4857
12724850
NH
4858#ifdef CONFIG_TRANSPARENT_HUGEPAGE
4859/*
4860 * We don't consider swapping or file mapped pages because THP does not
4861 * support them for now.
4862 * Caller should make sure that pmd_trans_huge(pmd) is true.
4863 */
4864static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
4865 unsigned long addr, pmd_t pmd, union mc_target *target)
4866{
4867 struct page *page = NULL;
12724850
NH
4868 enum mc_target_type ret = MC_TARGET_NONE;
4869
4870 page = pmd_page(pmd);
309381fe 4871 VM_BUG_ON_PAGE(!page || !PageHead(page), page);
1dfab5ab 4872 if (!(mc.flags & MOVE_ANON))
12724850 4873 return ret;
1306a85a 4874 if (page->mem_cgroup == mc.from) {
12724850
NH
4875 ret = MC_TARGET_PAGE;
4876 if (target) {
4877 get_page(page);
4878 target->page = page;
4879 }
4880 }
4881 return ret;
4882}
4883#else
4884static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
4885 unsigned long addr, pmd_t pmd, union mc_target *target)
4886{
4887 return MC_TARGET_NONE;
4888}
4889#endif
4890
4ffef5fe
DN
4891static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
4892 unsigned long addr, unsigned long end,
4893 struct mm_walk *walk)
4894{
26bcd64a 4895 struct vm_area_struct *vma = walk->vma;
4ffef5fe
DN
4896 pte_t *pte;
4897 spinlock_t *ptl;
4898
bf929152 4899 if (pmd_trans_huge_lock(pmd, vma, &ptl) == 1) {
12724850
NH
4900 if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
4901 mc.precharge += HPAGE_PMD_NR;
bf929152 4902 spin_unlock(ptl);
1a5a9906 4903 return 0;
12724850 4904 }
03319327 4905
45f83cef
AA
4906 if (pmd_trans_unstable(pmd))
4907 return 0;
4ffef5fe
DN
4908 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
4909 for (; addr != end; pte++, addr += PAGE_SIZE)
8d32ff84 4910 if (get_mctgt_type(vma, addr, *pte, NULL))
4ffef5fe
DN
4911 mc.precharge++; /* increment precharge temporarily */
4912 pte_unmap_unlock(pte - 1, ptl);
4913 cond_resched();
4914
7dc74be0
DN
4915 return 0;
4916}
4917
4ffef5fe
DN
4918static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
4919{
4920 unsigned long precharge;
4ffef5fe 4921
26bcd64a
NH
4922 struct mm_walk mem_cgroup_count_precharge_walk = {
4923 .pmd_entry = mem_cgroup_count_precharge_pte_range,
4924 .mm = mm,
4925 };
dfe076b0 4926 down_read(&mm->mmap_sem);
26bcd64a 4927 walk_page_range(0, ~0UL, &mem_cgroup_count_precharge_walk);
dfe076b0 4928 up_read(&mm->mmap_sem);
4ffef5fe
DN
4929
4930 precharge = mc.precharge;
4931 mc.precharge = 0;
4932
4933 return precharge;
4934}
4935
4ffef5fe
DN
4936static int mem_cgroup_precharge_mc(struct mm_struct *mm)
4937{
dfe076b0
DN
4938 unsigned long precharge = mem_cgroup_count_precharge(mm);
4939
4940 VM_BUG_ON(mc.moving_task);
4941 mc.moving_task = current;
4942 return mem_cgroup_do_precharge(precharge);
4ffef5fe
DN
4943}
4944
dfe076b0
DN
4945/* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
4946static void __mem_cgroup_clear_mc(void)
4ffef5fe 4947{
2bd9bb20
KH
4948 struct mem_cgroup *from = mc.from;
4949 struct mem_cgroup *to = mc.to;
4950
4ffef5fe 4951 /* we must uncharge all the leftover precharges from mc.to */
854ffa8d 4952 if (mc.precharge) {
00501b53 4953 cancel_charge(mc.to, mc.precharge);
854ffa8d
DN
4954 mc.precharge = 0;
4955 }
4956 /*
4957 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
4958 * we must uncharge here.
4959 */
4960 if (mc.moved_charge) {
00501b53 4961 cancel_charge(mc.from, mc.moved_charge);
854ffa8d 4962 mc.moved_charge = 0;
4ffef5fe 4963 }
483c30b5
DN
4964 /* we must fixup refcnts and charges */
4965 if (mc.moved_swap) {
483c30b5 4966 /* uncharge swap account from the old cgroup */
ce00a967 4967 if (!mem_cgroup_is_root(mc.from))
3e32cb2e 4968 page_counter_uncharge(&mc.from->memsw, mc.moved_swap);
483c30b5 4969
05b84301 4970 /*
3e32cb2e
JW
4971 * we charged both to->memory and to->memsw, so we
4972 * should uncharge to->memory.
05b84301 4973 */
ce00a967 4974 if (!mem_cgroup_is_root(mc.to))
3e32cb2e
JW
4975 page_counter_uncharge(&mc.to->memory, mc.moved_swap);
4976
e8ea14cc 4977 css_put_many(&mc.from->css, mc.moved_swap);
3e32cb2e 4978
4050377b 4979 /* we've already done css_get(mc.to) */
483c30b5
DN
4980 mc.moved_swap = 0;
4981 }
dfe076b0
DN
4982 memcg_oom_recover(from);
4983 memcg_oom_recover(to);
4984 wake_up_all(&mc.waitq);
4985}
4986
4987static void mem_cgroup_clear_mc(void)
4988{
dfe076b0
DN
4989 /*
4990 * we must clear moving_task before waking up waiters at the end of
4991 * task migration.
4992 */
4993 mc.moving_task = NULL;
4994 __mem_cgroup_clear_mc();
2bd9bb20 4995 spin_lock(&mc.lock);
4ffef5fe
DN
4996 mc.from = NULL;
4997 mc.to = NULL;
2bd9bb20 4998 spin_unlock(&mc.lock);
4ffef5fe
DN
4999}
5000
eb95419b 5001static int mem_cgroup_can_attach(struct cgroup_subsys_state *css,
761b3ef5 5002 struct cgroup_taskset *tset)
7dc74be0 5003{
2f7ee569 5004 struct task_struct *p = cgroup_taskset_first(tset);
7dc74be0 5005 int ret = 0;
eb95419b 5006 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
1dfab5ab 5007 unsigned long move_flags;
7dc74be0 5008
ee5e8472
GC
5009 /*
5010 * We are now commited to this value whatever it is. Changes in this
5011 * tunable will only affect upcoming migrations, not the current one.
5012 * So we need to save it, and keep it going.
5013 */
1dfab5ab
JW
5014 move_flags = ACCESS_ONCE(memcg->move_charge_at_immigrate);
5015 if (move_flags) {
7dc74be0
DN
5016 struct mm_struct *mm;
5017 struct mem_cgroup *from = mem_cgroup_from_task(p);
5018
c0ff4b85 5019 VM_BUG_ON(from == memcg);
7dc74be0
DN
5020
5021 mm = get_task_mm(p);
5022 if (!mm)
5023 return 0;
7dc74be0 5024 /* We move charges only when we move a owner of the mm */
4ffef5fe
DN
5025 if (mm->owner == p) {
5026 VM_BUG_ON(mc.from);
5027 VM_BUG_ON(mc.to);
5028 VM_BUG_ON(mc.precharge);
854ffa8d 5029 VM_BUG_ON(mc.moved_charge);
483c30b5 5030 VM_BUG_ON(mc.moved_swap);
247b1447 5031
2bd9bb20 5032 spin_lock(&mc.lock);
4ffef5fe 5033 mc.from = from;
c0ff4b85 5034 mc.to = memcg;
1dfab5ab 5035 mc.flags = move_flags;
2bd9bb20 5036 spin_unlock(&mc.lock);
dfe076b0 5037 /* We set mc.moving_task later */
4ffef5fe
DN
5038
5039 ret = mem_cgroup_precharge_mc(mm);
5040 if (ret)
5041 mem_cgroup_clear_mc();
dfe076b0
DN
5042 }
5043 mmput(mm);
7dc74be0
DN
5044 }
5045 return ret;
5046}
5047
eb95419b 5048static void mem_cgroup_cancel_attach(struct cgroup_subsys_state *css,
761b3ef5 5049 struct cgroup_taskset *tset)
7dc74be0 5050{
4e2f245d
JW
5051 if (mc.to)
5052 mem_cgroup_clear_mc();
7dc74be0
DN
5053}
5054
4ffef5fe
DN
5055static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
5056 unsigned long addr, unsigned long end,
5057 struct mm_walk *walk)
7dc74be0 5058{
4ffef5fe 5059 int ret = 0;
26bcd64a 5060 struct vm_area_struct *vma = walk->vma;
4ffef5fe
DN
5061 pte_t *pte;
5062 spinlock_t *ptl;
12724850
NH
5063 enum mc_target_type target_type;
5064 union mc_target target;
5065 struct page *page;
4ffef5fe 5066
12724850
NH
5067 /*
5068 * We don't take compound_lock() here but no race with splitting thp
5069 * happens because:
5070 * - if pmd_trans_huge_lock() returns 1, the relevant thp is not
5071 * under splitting, which means there's no concurrent thp split,
5072 * - if another thread runs into split_huge_page() just after we
5073 * entered this if-block, the thread must wait for page table lock
5074 * to be unlocked in __split_huge_page_splitting(), where the main
5075 * part of thp split is not executed yet.
5076 */
bf929152 5077 if (pmd_trans_huge_lock(pmd, vma, &ptl) == 1) {
62ade86a 5078 if (mc.precharge < HPAGE_PMD_NR) {
bf929152 5079 spin_unlock(ptl);
12724850
NH
5080 return 0;
5081 }
5082 target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
5083 if (target_type == MC_TARGET_PAGE) {
5084 page = target.page;
5085 if (!isolate_lru_page(page)) {
12724850 5086 if (!mem_cgroup_move_account(page, HPAGE_PMD_NR,
1306a85a 5087 mc.from, mc.to)) {
12724850
NH
5088 mc.precharge -= HPAGE_PMD_NR;
5089 mc.moved_charge += HPAGE_PMD_NR;
5090 }
5091 putback_lru_page(page);
5092 }
5093 put_page(page);
5094 }
bf929152 5095 spin_unlock(ptl);
1a5a9906 5096 return 0;
12724850
NH
5097 }
5098
45f83cef
AA
5099 if (pmd_trans_unstable(pmd))
5100 return 0;
4ffef5fe
DN
5101retry:
5102 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5103 for (; addr != end; addr += PAGE_SIZE) {
5104 pte_t ptent = *(pte++);
02491447 5105 swp_entry_t ent;
4ffef5fe
DN
5106
5107 if (!mc.precharge)
5108 break;
5109
8d32ff84 5110 switch (get_mctgt_type(vma, addr, ptent, &target)) {
4ffef5fe
DN
5111 case MC_TARGET_PAGE:
5112 page = target.page;
5113 if (isolate_lru_page(page))
5114 goto put;
1306a85a 5115 if (!mem_cgroup_move_account(page, 1, mc.from, mc.to)) {
4ffef5fe 5116 mc.precharge--;
854ffa8d
DN
5117 /* we uncharge from mc.from later. */
5118 mc.moved_charge++;
4ffef5fe
DN
5119 }
5120 putback_lru_page(page);
8d32ff84 5121put: /* get_mctgt_type() gets the page */
4ffef5fe
DN
5122 put_page(page);
5123 break;
02491447
DN
5124 case MC_TARGET_SWAP:
5125 ent = target.ent;
e91cbb42 5126 if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
02491447 5127 mc.precharge--;
483c30b5
DN
5128 /* we fixup refcnts and charges later. */
5129 mc.moved_swap++;
5130 }
02491447 5131 break;
4ffef5fe
DN
5132 default:
5133 break;
5134 }
5135 }
5136 pte_unmap_unlock(pte - 1, ptl);
5137 cond_resched();
5138
5139 if (addr != end) {
5140 /*
5141 * We have consumed all precharges we got in can_attach().
5142 * We try charge one by one, but don't do any additional
5143 * charges to mc.to if we have failed in charge once in attach()
5144 * phase.
5145 */
854ffa8d 5146 ret = mem_cgroup_do_precharge(1);
4ffef5fe
DN
5147 if (!ret)
5148 goto retry;
5149 }
5150
5151 return ret;
5152}
5153
5154static void mem_cgroup_move_charge(struct mm_struct *mm)
5155{
26bcd64a
NH
5156 struct mm_walk mem_cgroup_move_charge_walk = {
5157 .pmd_entry = mem_cgroup_move_charge_pte_range,
5158 .mm = mm,
5159 };
4ffef5fe
DN
5160
5161 lru_add_drain_all();
312722cb
JW
5162 /*
5163 * Signal mem_cgroup_begin_page_stat() to take the memcg's
5164 * move_lock while we're moving its pages to another memcg.
5165 * Then wait for already started RCU-only updates to finish.
5166 */
5167 atomic_inc(&mc.from->moving_account);
5168 synchronize_rcu();
dfe076b0
DN
5169retry:
5170 if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
5171 /*
5172 * Someone who are holding the mmap_sem might be waiting in
5173 * waitq. So we cancel all extra charges, wake up all waiters,
5174 * and retry. Because we cancel precharges, we might not be able
5175 * to move enough charges, but moving charge is a best-effort
5176 * feature anyway, so it wouldn't be a big problem.
5177 */
5178 __mem_cgroup_clear_mc();
5179 cond_resched();
5180 goto retry;
5181 }
26bcd64a
NH
5182 /*
5183 * When we have consumed all precharges and failed in doing
5184 * additional charge, the page walk just aborts.
5185 */
5186 walk_page_range(0, ~0UL, &mem_cgroup_move_charge_walk);
dfe076b0 5187 up_read(&mm->mmap_sem);
312722cb 5188 atomic_dec(&mc.from->moving_account);
7dc74be0
DN
5189}
5190
eb95419b 5191static void mem_cgroup_move_task(struct cgroup_subsys_state *css,
761b3ef5 5192 struct cgroup_taskset *tset)
67e465a7 5193{
2f7ee569 5194 struct task_struct *p = cgroup_taskset_first(tset);
a433658c 5195 struct mm_struct *mm = get_task_mm(p);
dfe076b0 5196
dfe076b0 5197 if (mm) {
a433658c
KM
5198 if (mc.to)
5199 mem_cgroup_move_charge(mm);
dfe076b0
DN
5200 mmput(mm);
5201 }
a433658c
KM
5202 if (mc.to)
5203 mem_cgroup_clear_mc();
67e465a7 5204}
5cfb80a7 5205#else /* !CONFIG_MMU */
eb95419b 5206static int mem_cgroup_can_attach(struct cgroup_subsys_state *css,
761b3ef5 5207 struct cgroup_taskset *tset)
5cfb80a7
DN
5208{
5209 return 0;
5210}
eb95419b 5211static void mem_cgroup_cancel_attach(struct cgroup_subsys_state *css,
761b3ef5 5212 struct cgroup_taskset *tset)
5cfb80a7
DN
5213{
5214}
eb95419b 5215static void mem_cgroup_move_task(struct cgroup_subsys_state *css,
761b3ef5 5216 struct cgroup_taskset *tset)
5cfb80a7
DN
5217{
5218}
5219#endif
67e465a7 5220
f00baae7
TH
5221/*
5222 * Cgroup retains root cgroups across [un]mount cycles making it necessary
aa6ec29b
TH
5223 * to verify whether we're attached to the default hierarchy on each mount
5224 * attempt.
f00baae7 5225 */
eb95419b 5226static void mem_cgroup_bind(struct cgroup_subsys_state *root_css)
f00baae7
TH
5227{
5228 /*
aa6ec29b 5229 * use_hierarchy is forced on the default hierarchy. cgroup core
f00baae7
TH
5230 * guarantees that @root doesn't have any children, so turning it
5231 * on for the root memcg is enough.
5232 */
aa6ec29b 5233 if (cgroup_on_dfl(root_css->cgroup))
eb95419b 5234 mem_cgroup_from_css(root_css)->use_hierarchy = true;
f00baae7
TH
5235}
5236
241994ed
JW
5237static u64 memory_current_read(struct cgroup_subsys_state *css,
5238 struct cftype *cft)
5239{
5240 return mem_cgroup_usage(mem_cgroup_from_css(css), false);
5241}
5242
5243static int memory_low_show(struct seq_file *m, void *v)
5244{
5245 struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
5246 unsigned long low = ACCESS_ONCE(memcg->low);
5247
5248 if (low == PAGE_COUNTER_MAX)
5249 seq_puts(m, "infinity\n");
5250 else
5251 seq_printf(m, "%llu\n", (u64)low * PAGE_SIZE);
5252
5253 return 0;
5254}
5255
5256static ssize_t memory_low_write(struct kernfs_open_file *of,
5257 char *buf, size_t nbytes, loff_t off)
5258{
5259 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
5260 unsigned long low;
5261 int err;
5262
5263 buf = strstrip(buf);
5264 err = page_counter_memparse(buf, "infinity", &low);
5265 if (err)
5266 return err;
5267
5268 memcg->low = low;
5269
5270 return nbytes;
5271}
5272
5273static int memory_high_show(struct seq_file *m, void *v)
5274{
5275 struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
5276 unsigned long high = ACCESS_ONCE(memcg->high);
5277
5278 if (high == PAGE_COUNTER_MAX)
5279 seq_puts(m, "infinity\n");
5280 else
5281 seq_printf(m, "%llu\n", (u64)high * PAGE_SIZE);
5282
5283 return 0;
5284}
5285
5286static ssize_t memory_high_write(struct kernfs_open_file *of,
5287 char *buf, size_t nbytes, loff_t off)
5288{
5289 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
5290 unsigned long high;
5291 int err;
5292
5293 buf = strstrip(buf);
5294 err = page_counter_memparse(buf, "infinity", &high);
5295 if (err)
5296 return err;
5297
5298 memcg->high = high;
5299
5300 return nbytes;
5301}
5302
5303static int memory_max_show(struct seq_file *m, void *v)
5304{
5305 struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
5306 unsigned long max = ACCESS_ONCE(memcg->memory.limit);
5307
5308 if (max == PAGE_COUNTER_MAX)
5309 seq_puts(m, "infinity\n");
5310 else
5311 seq_printf(m, "%llu\n", (u64)max * PAGE_SIZE);
5312
5313 return 0;
5314}
5315
5316static ssize_t memory_max_write(struct kernfs_open_file *of,
5317 char *buf, size_t nbytes, loff_t off)
5318{
5319 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
5320 unsigned long max;
5321 int err;
5322
5323 buf = strstrip(buf);
5324 err = page_counter_memparse(buf, "infinity", &max);
5325 if (err)
5326 return err;
5327
5328 err = mem_cgroup_resize_limit(memcg, max);
5329 if (err)
5330 return err;
5331
5332 return nbytes;
5333}
5334
5335static int memory_events_show(struct seq_file *m, void *v)
5336{
5337 struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
5338
5339 seq_printf(m, "low %lu\n", mem_cgroup_read_events(memcg, MEMCG_LOW));
5340 seq_printf(m, "high %lu\n", mem_cgroup_read_events(memcg, MEMCG_HIGH));
5341 seq_printf(m, "max %lu\n", mem_cgroup_read_events(memcg, MEMCG_MAX));
5342 seq_printf(m, "oom %lu\n", mem_cgroup_read_events(memcg, MEMCG_OOM));
5343
5344 return 0;
5345}
5346
5347static struct cftype memory_files[] = {
5348 {
5349 .name = "current",
5350 .read_u64 = memory_current_read,
5351 },
5352 {
5353 .name = "low",
5354 .flags = CFTYPE_NOT_ON_ROOT,
5355 .seq_show = memory_low_show,
5356 .write = memory_low_write,
5357 },
5358 {
5359 .name = "high",
5360 .flags = CFTYPE_NOT_ON_ROOT,
5361 .seq_show = memory_high_show,
5362 .write = memory_high_write,
5363 },
5364 {
5365 .name = "max",
5366 .flags = CFTYPE_NOT_ON_ROOT,
5367 .seq_show = memory_max_show,
5368 .write = memory_max_write,
5369 },
5370 {
5371 .name = "events",
5372 .flags = CFTYPE_NOT_ON_ROOT,
5373 .seq_show = memory_events_show,
5374 },
5375 { } /* terminate */
5376};
5377
073219e9 5378struct cgroup_subsys memory_cgrp_subsys = {
92fb9748 5379 .css_alloc = mem_cgroup_css_alloc,
d142e3e6 5380 .css_online = mem_cgroup_css_online,
92fb9748
TH
5381 .css_offline = mem_cgroup_css_offline,
5382 .css_free = mem_cgroup_css_free,
1ced953b 5383 .css_reset = mem_cgroup_css_reset,
7dc74be0
DN
5384 .can_attach = mem_cgroup_can_attach,
5385 .cancel_attach = mem_cgroup_cancel_attach,
67e465a7 5386 .attach = mem_cgroup_move_task,
f00baae7 5387 .bind = mem_cgroup_bind,
241994ed
JW
5388 .dfl_cftypes = memory_files,
5389 .legacy_cftypes = mem_cgroup_legacy_files,
6d12e2d8 5390 .early_init = 0,
8cdea7c0 5391};
c077719b 5392
241994ed
JW
5393/**
5394 * mem_cgroup_events - count memory events against a cgroup
5395 * @memcg: the memory cgroup
5396 * @idx: the event index
5397 * @nr: the number of events to account for
5398 */
5399void mem_cgroup_events(struct mem_cgroup *memcg,
5400 enum mem_cgroup_events_index idx,
5401 unsigned int nr)
5402{
5403 this_cpu_add(memcg->stat->events[idx], nr);
5404}
5405
5406/**
5407 * mem_cgroup_low - check if memory consumption is below the normal range
5408 * @root: the highest ancestor to consider
5409 * @memcg: the memory cgroup to check
5410 *
5411 * Returns %true if memory consumption of @memcg, and that of all
5412 * configurable ancestors up to @root, is below the normal range.
5413 */
5414bool mem_cgroup_low(struct mem_cgroup *root, struct mem_cgroup *memcg)
5415{
5416 if (mem_cgroup_disabled())
5417 return false;
5418
5419 /*
5420 * The toplevel group doesn't have a configurable range, so
5421 * it's never low when looked at directly, and it is not
5422 * considered an ancestor when assessing the hierarchy.
5423 */
5424
5425 if (memcg == root_mem_cgroup)
5426 return false;
5427
5428 if (page_counter_read(&memcg->memory) > memcg->low)
5429 return false;
5430
5431 while (memcg != root) {
5432 memcg = parent_mem_cgroup(memcg);
5433
5434 if (memcg == root_mem_cgroup)
5435 break;
5436
5437 if (page_counter_read(&memcg->memory) > memcg->low)
5438 return false;
5439 }
5440 return true;
5441}
5442
00501b53
JW
5443/**
5444 * mem_cgroup_try_charge - try charging a page
5445 * @page: page to charge
5446 * @mm: mm context of the victim
5447 * @gfp_mask: reclaim mode
5448 * @memcgp: charged memcg return
5449 *
5450 * Try to charge @page to the memcg that @mm belongs to, reclaiming
5451 * pages according to @gfp_mask if necessary.
5452 *
5453 * Returns 0 on success, with *@memcgp pointing to the charged memcg.
5454 * Otherwise, an error code is returned.
5455 *
5456 * After page->mapping has been set up, the caller must finalize the
5457 * charge with mem_cgroup_commit_charge(). Or abort the transaction
5458 * with mem_cgroup_cancel_charge() in case page instantiation fails.
5459 */
5460int mem_cgroup_try_charge(struct page *page, struct mm_struct *mm,
5461 gfp_t gfp_mask, struct mem_cgroup **memcgp)
5462{
5463 struct mem_cgroup *memcg = NULL;
5464 unsigned int nr_pages = 1;
5465 int ret = 0;
5466
5467 if (mem_cgroup_disabled())
5468 goto out;
5469
5470 if (PageSwapCache(page)) {
00501b53
JW
5471 /*
5472 * Every swap fault against a single page tries to charge the
5473 * page, bail as early as possible. shmem_unuse() encounters
5474 * already charged pages, too. The USED bit is protected by
5475 * the page lock, which serializes swap cache removal, which
5476 * in turn serializes uncharging.
5477 */
1306a85a 5478 if (page->mem_cgroup)
00501b53
JW
5479 goto out;
5480 }
5481
5482 if (PageTransHuge(page)) {
5483 nr_pages <<= compound_order(page);
5484 VM_BUG_ON_PAGE(!PageTransHuge(page), page);
5485 }
5486
5487 if (do_swap_account && PageSwapCache(page))
5488 memcg = try_get_mem_cgroup_from_page(page);
5489 if (!memcg)
5490 memcg = get_mem_cgroup_from_mm(mm);
5491
5492 ret = try_charge(memcg, gfp_mask, nr_pages);
5493
5494 css_put(&memcg->css);
5495
5496 if (ret == -EINTR) {
5497 memcg = root_mem_cgroup;
5498 ret = 0;
5499 }
5500out:
5501 *memcgp = memcg;
5502 return ret;
5503}
5504
5505/**
5506 * mem_cgroup_commit_charge - commit a page charge
5507 * @page: page to charge
5508 * @memcg: memcg to charge the page to
5509 * @lrucare: page might be on LRU already
5510 *
5511 * Finalize a charge transaction started by mem_cgroup_try_charge(),
5512 * after page->mapping has been set up. This must happen atomically
5513 * as part of the page instantiation, i.e. under the page table lock
5514 * for anonymous pages, under the page lock for page and swap cache.
5515 *
5516 * In addition, the page must not be on the LRU during the commit, to
5517 * prevent racing with task migration. If it might be, use @lrucare.
5518 *
5519 * Use mem_cgroup_cancel_charge() to cancel the transaction instead.
5520 */
5521void mem_cgroup_commit_charge(struct page *page, struct mem_cgroup *memcg,
5522 bool lrucare)
5523{
5524 unsigned int nr_pages = 1;
5525
5526 VM_BUG_ON_PAGE(!page->mapping, page);
5527 VM_BUG_ON_PAGE(PageLRU(page) && !lrucare, page);
5528
5529 if (mem_cgroup_disabled())
5530 return;
5531 /*
5532 * Swap faults will attempt to charge the same page multiple
5533 * times. But reuse_swap_page() might have removed the page
5534 * from swapcache already, so we can't check PageSwapCache().
5535 */
5536 if (!memcg)
5537 return;
5538
6abb5a86
JW
5539 commit_charge(page, memcg, lrucare);
5540
00501b53
JW
5541 if (PageTransHuge(page)) {
5542 nr_pages <<= compound_order(page);
5543 VM_BUG_ON_PAGE(!PageTransHuge(page), page);
5544 }
5545
6abb5a86
JW
5546 local_irq_disable();
5547 mem_cgroup_charge_statistics(memcg, page, nr_pages);
5548 memcg_check_events(memcg, page);
5549 local_irq_enable();
00501b53
JW
5550
5551 if (do_swap_account && PageSwapCache(page)) {
5552 swp_entry_t entry = { .val = page_private(page) };
5553 /*
5554 * The swap entry might not get freed for a long time,
5555 * let's not wait for it. The page already received a
5556 * memory+swap charge, drop the swap entry duplicate.
5557 */
5558 mem_cgroup_uncharge_swap(entry);
5559 }
5560}
5561
5562/**
5563 * mem_cgroup_cancel_charge - cancel a page charge
5564 * @page: page to charge
5565 * @memcg: memcg to charge the page to
5566 *
5567 * Cancel a charge transaction started by mem_cgroup_try_charge().
5568 */
5569void mem_cgroup_cancel_charge(struct page *page, struct mem_cgroup *memcg)
5570{
5571 unsigned int nr_pages = 1;
5572
5573 if (mem_cgroup_disabled())
5574 return;
5575 /*
5576 * Swap faults will attempt to charge the same page multiple
5577 * times. But reuse_swap_page() might have removed the page
5578 * from swapcache already, so we can't check PageSwapCache().
5579 */
5580 if (!memcg)
5581 return;
5582
5583 if (PageTransHuge(page)) {
5584 nr_pages <<= compound_order(page);
5585 VM_BUG_ON_PAGE(!PageTransHuge(page), page);
5586 }
5587
5588 cancel_charge(memcg, nr_pages);
5589}
5590
747db954 5591static void uncharge_batch(struct mem_cgroup *memcg, unsigned long pgpgout,
747db954
JW
5592 unsigned long nr_anon, unsigned long nr_file,
5593 unsigned long nr_huge, struct page *dummy_page)
5594{
18eca2e6 5595 unsigned long nr_pages = nr_anon + nr_file;
747db954
JW
5596 unsigned long flags;
5597
ce00a967 5598 if (!mem_cgroup_is_root(memcg)) {
18eca2e6
JW
5599 page_counter_uncharge(&memcg->memory, nr_pages);
5600 if (do_swap_account)
5601 page_counter_uncharge(&memcg->memsw, nr_pages);
ce00a967
JW
5602 memcg_oom_recover(memcg);
5603 }
747db954
JW
5604
5605 local_irq_save(flags);
5606 __this_cpu_sub(memcg->stat->count[MEM_CGROUP_STAT_RSS], nr_anon);
5607 __this_cpu_sub(memcg->stat->count[MEM_CGROUP_STAT_CACHE], nr_file);
5608 __this_cpu_sub(memcg->stat->count[MEM_CGROUP_STAT_RSS_HUGE], nr_huge);
5609 __this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGOUT], pgpgout);
18eca2e6 5610 __this_cpu_add(memcg->stat->nr_page_events, nr_pages);
747db954
JW
5611 memcg_check_events(memcg, dummy_page);
5612 local_irq_restore(flags);
e8ea14cc
JW
5613
5614 if (!mem_cgroup_is_root(memcg))
18eca2e6 5615 css_put_many(&memcg->css, nr_pages);
747db954
JW
5616}
5617
5618static void uncharge_list(struct list_head *page_list)
5619{
5620 struct mem_cgroup *memcg = NULL;
747db954
JW
5621 unsigned long nr_anon = 0;
5622 unsigned long nr_file = 0;
5623 unsigned long nr_huge = 0;
5624 unsigned long pgpgout = 0;
747db954
JW
5625 struct list_head *next;
5626 struct page *page;
5627
5628 next = page_list->next;
5629 do {
5630 unsigned int nr_pages = 1;
747db954
JW
5631
5632 page = list_entry(next, struct page, lru);
5633 next = page->lru.next;
5634
5635 VM_BUG_ON_PAGE(PageLRU(page), page);
5636 VM_BUG_ON_PAGE(page_count(page), page);
5637
1306a85a 5638 if (!page->mem_cgroup)
747db954
JW
5639 continue;
5640
5641 /*
5642 * Nobody should be changing or seriously looking at
1306a85a 5643 * page->mem_cgroup at this point, we have fully
29833315 5644 * exclusive access to the page.
747db954
JW
5645 */
5646
1306a85a 5647 if (memcg != page->mem_cgroup) {
747db954 5648 if (memcg) {
18eca2e6
JW
5649 uncharge_batch(memcg, pgpgout, nr_anon, nr_file,
5650 nr_huge, page);
5651 pgpgout = nr_anon = nr_file = nr_huge = 0;
747db954 5652 }
1306a85a 5653 memcg = page->mem_cgroup;
747db954
JW
5654 }
5655
5656 if (PageTransHuge(page)) {
5657 nr_pages <<= compound_order(page);
5658 VM_BUG_ON_PAGE(!PageTransHuge(page), page);
5659 nr_huge += nr_pages;
5660 }
5661
5662 if (PageAnon(page))
5663 nr_anon += nr_pages;
5664 else
5665 nr_file += nr_pages;
5666
1306a85a 5667 page->mem_cgroup = NULL;
747db954
JW
5668
5669 pgpgout++;
5670 } while (next != page_list);
5671
5672 if (memcg)
18eca2e6
JW
5673 uncharge_batch(memcg, pgpgout, nr_anon, nr_file,
5674 nr_huge, page);
747db954
JW
5675}
5676
0a31bc97
JW
5677/**
5678 * mem_cgroup_uncharge - uncharge a page
5679 * @page: page to uncharge
5680 *
5681 * Uncharge a page previously charged with mem_cgroup_try_charge() and
5682 * mem_cgroup_commit_charge().
5683 */
5684void mem_cgroup_uncharge(struct page *page)
5685{
0a31bc97
JW
5686 if (mem_cgroup_disabled())
5687 return;
5688
747db954 5689 /* Don't touch page->lru of any random page, pre-check: */
1306a85a 5690 if (!page->mem_cgroup)
0a31bc97
JW
5691 return;
5692
747db954
JW
5693 INIT_LIST_HEAD(&page->lru);
5694 uncharge_list(&page->lru);
5695}
0a31bc97 5696
747db954
JW
5697/**
5698 * mem_cgroup_uncharge_list - uncharge a list of page
5699 * @page_list: list of pages to uncharge
5700 *
5701 * Uncharge a list of pages previously charged with
5702 * mem_cgroup_try_charge() and mem_cgroup_commit_charge().
5703 */
5704void mem_cgroup_uncharge_list(struct list_head *page_list)
5705{
5706 if (mem_cgroup_disabled())
5707 return;
0a31bc97 5708
747db954
JW
5709 if (!list_empty(page_list))
5710 uncharge_list(page_list);
0a31bc97
JW
5711}
5712
5713/**
5714 * mem_cgroup_migrate - migrate a charge to another page
5715 * @oldpage: currently charged page
5716 * @newpage: page to transfer the charge to
f5e03a49 5717 * @lrucare: either or both pages might be on the LRU already
0a31bc97
JW
5718 *
5719 * Migrate the charge from @oldpage to @newpage.
5720 *
5721 * Both pages must be locked, @newpage->mapping must be set up.
5722 */
5723void mem_cgroup_migrate(struct page *oldpage, struct page *newpage,
5724 bool lrucare)
5725{
29833315 5726 struct mem_cgroup *memcg;
0a31bc97
JW
5727 int isolated;
5728
5729 VM_BUG_ON_PAGE(!PageLocked(oldpage), oldpage);
5730 VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
5731 VM_BUG_ON_PAGE(!lrucare && PageLRU(oldpage), oldpage);
5732 VM_BUG_ON_PAGE(!lrucare && PageLRU(newpage), newpage);
5733 VM_BUG_ON_PAGE(PageAnon(oldpage) != PageAnon(newpage), newpage);
6abb5a86
JW
5734 VM_BUG_ON_PAGE(PageTransHuge(oldpage) != PageTransHuge(newpage),
5735 newpage);
0a31bc97
JW
5736
5737 if (mem_cgroup_disabled())
5738 return;
5739
5740 /* Page cache replacement: new page already charged? */
1306a85a 5741 if (newpage->mem_cgroup)
0a31bc97
JW
5742 return;
5743
7d5e3245
JW
5744 /*
5745 * Swapcache readahead pages can get migrated before being
5746 * charged, and migration from compaction can happen to an
5747 * uncharged page when the PFN walker finds a page that
5748 * reclaim just put back on the LRU but has not released yet.
5749 */
1306a85a 5750 memcg = oldpage->mem_cgroup;
29833315 5751 if (!memcg)
0a31bc97
JW
5752 return;
5753
0a31bc97
JW
5754 if (lrucare)
5755 lock_page_lru(oldpage, &isolated);
5756
1306a85a 5757 oldpage->mem_cgroup = NULL;
0a31bc97
JW
5758
5759 if (lrucare)
5760 unlock_page_lru(oldpage, isolated);
5761
29833315 5762 commit_charge(newpage, memcg, lrucare);
0a31bc97
JW
5763}
5764
2d11085e 5765/*
1081312f
MH
5766 * subsys_initcall() for memory controller.
5767 *
5768 * Some parts like hotcpu_notifier() have to be initialized from this context
5769 * because of lock dependencies (cgroup_lock -> cpu hotplug) but basically
5770 * everything that doesn't depend on a specific mem_cgroup structure should
5771 * be initialized from here.
2d11085e
MH
5772 */
5773static int __init mem_cgroup_init(void)
5774{
95a045f6
JW
5775 int cpu, node;
5776
2d11085e 5777 hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
95a045f6
JW
5778
5779 for_each_possible_cpu(cpu)
5780 INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
5781 drain_local_stock);
5782
5783 for_each_node(node) {
5784 struct mem_cgroup_tree_per_node *rtpn;
5785 int zone;
5786
5787 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL,
5788 node_online(node) ? node : NUMA_NO_NODE);
5789
5790 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
5791 struct mem_cgroup_tree_per_zone *rtpz;
5792
5793 rtpz = &rtpn->rb_tree_per_zone[zone];
5794 rtpz->rb_root = RB_ROOT;
5795 spin_lock_init(&rtpz->lock);
5796 }
5797 soft_limit_tree.rb_tree_per_node[node] = rtpn;
5798 }
5799
2d11085e
MH
5800 return 0;
5801}
5802subsys_initcall(mem_cgroup_init);
21afa38e
JW
5803
5804#ifdef CONFIG_MEMCG_SWAP
5805/**
5806 * mem_cgroup_swapout - transfer a memsw charge to swap
5807 * @page: page whose memsw charge to transfer
5808 * @entry: swap entry to move the charge to
5809 *
5810 * Transfer the memsw charge of @page to @entry.
5811 */
5812void mem_cgroup_swapout(struct page *page, swp_entry_t entry)
5813{
5814 struct mem_cgroup *memcg;
5815 unsigned short oldid;
5816
5817 VM_BUG_ON_PAGE(PageLRU(page), page);
5818 VM_BUG_ON_PAGE(page_count(page), page);
5819
5820 if (!do_swap_account)
5821 return;
5822
5823 memcg = page->mem_cgroup;
5824
5825 /* Readahead page, never charged */
5826 if (!memcg)
5827 return;
5828
5829 oldid = swap_cgroup_record(entry, mem_cgroup_id(memcg));
5830 VM_BUG_ON_PAGE(oldid, page);
5831 mem_cgroup_swap_statistics(memcg, true);
5832
5833 page->mem_cgroup = NULL;
5834
5835 if (!mem_cgroup_is_root(memcg))
5836 page_counter_uncharge(&memcg->memory, 1);
5837
5838 /* XXX: caller holds IRQ-safe mapping->tree_lock */
5839 VM_BUG_ON(!irqs_disabled());
5840
5841 mem_cgroup_charge_statistics(memcg, page, -1);
5842 memcg_check_events(memcg, page);
5843}
5844
5845/**
5846 * mem_cgroup_uncharge_swap - uncharge a swap entry
5847 * @entry: swap entry to uncharge
5848 *
5849 * Drop the memsw charge associated with @entry.
5850 */
5851void mem_cgroup_uncharge_swap(swp_entry_t entry)
5852{
5853 struct mem_cgroup *memcg;
5854 unsigned short id;
5855
5856 if (!do_swap_account)
5857 return;
5858
5859 id = swap_cgroup_record(entry, 0);
5860 rcu_read_lock();
5861 memcg = mem_cgroup_lookup(id);
5862 if (memcg) {
5863 if (!mem_cgroup_is_root(memcg))
5864 page_counter_uncharge(&memcg->memsw, 1);
5865 mem_cgroup_swap_statistics(memcg, false);
5866 css_put(&memcg->css);
5867 }
5868 rcu_read_unlock();
5869}
5870
5871/* for remember boot option*/
5872#ifdef CONFIG_MEMCG_SWAP_ENABLED
5873static int really_do_swap_account __initdata = 1;
5874#else
5875static int really_do_swap_account __initdata;
5876#endif
5877
5878static int __init enable_swap_account(char *s)
5879{
5880 if (!strcmp(s, "1"))
5881 really_do_swap_account = 1;
5882 else if (!strcmp(s, "0"))
5883 really_do_swap_account = 0;
5884 return 1;
5885}
5886__setup("swapaccount=", enable_swap_account);
5887
5888static struct cftype memsw_cgroup_files[] = {
5889 {
5890 .name = "memsw.usage_in_bytes",
5891 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
5892 .read_u64 = mem_cgroup_read_u64,
5893 },
5894 {
5895 .name = "memsw.max_usage_in_bytes",
5896 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
5897 .write = mem_cgroup_reset,
5898 .read_u64 = mem_cgroup_read_u64,
5899 },
5900 {
5901 .name = "memsw.limit_in_bytes",
5902 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
5903 .write = mem_cgroup_write,
5904 .read_u64 = mem_cgroup_read_u64,
5905 },
5906 {
5907 .name = "memsw.failcnt",
5908 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
5909 .write = mem_cgroup_reset,
5910 .read_u64 = mem_cgroup_read_u64,
5911 },
5912 { }, /* terminate */
5913};
5914
5915static int __init mem_cgroup_swap_init(void)
5916{
5917 if (!mem_cgroup_disabled() && really_do_swap_account) {
5918 do_swap_account = 1;
5919 WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys,
5920 memsw_cgroup_files));
5921 }
5922 return 0;
5923}
5924subsys_initcall(mem_cgroup_swap_init);
5925
5926#endif /* CONFIG_MEMCG_SWAP */