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