]> git.proxmox.com Git - mirror_ubuntu-artful-kernel.git/blame - mm/memcontrol.c
memcg: close race between charge and putback
[mirror_ubuntu-artful-kernel.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 *
8cdea7c0
BS
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
17 *
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
22 */
23
24#include <linux/res_counter.h>
25#include <linux/memcontrol.h>
26#include <linux/cgroup.h>
78fb7466 27#include <linux/mm.h>
4ffef5fe 28#include <linux/hugetlb.h>
d13d1443 29#include <linux/pagemap.h>
d52aa412 30#include <linux/smp.h>
8a9f3ccd 31#include <linux/page-flags.h>
66e1707b 32#include <linux/backing-dev.h>
8a9f3ccd
BS
33#include <linux/bit_spinlock.h>
34#include <linux/rcupdate.h>
e222432b 35#include <linux/limits.h>
8c7c6e34 36#include <linux/mutex.h>
f64c3f54 37#include <linux/rbtree.h>
b6ac57d5 38#include <linux/slab.h>
66e1707b 39#include <linux/swap.h>
02491447 40#include <linux/swapops.h>
66e1707b 41#include <linux/spinlock.h>
2e72b634
KS
42#include <linux/eventfd.h>
43#include <linux/sort.h>
66e1707b 44#include <linux/fs.h>
d2ceb9b7 45#include <linux/seq_file.h>
33327948 46#include <linux/vmalloc.h>
b69408e8 47#include <linux/mm_inline.h>
52d4b9ac 48#include <linux/page_cgroup.h>
cdec2e42 49#include <linux/cpu.h>
158e0a2d 50#include <linux/oom.h>
08e552c6 51#include "internal.h"
8cdea7c0 52
8697d331
BS
53#include <asm/uaccess.h>
54
cc8e970c
KM
55#include <trace/events/vmscan.h>
56
a181b0e8 57struct cgroup_subsys mem_cgroup_subsys __read_mostly;
a181b0e8 58#define MEM_CGROUP_RECLAIM_RETRIES 5
4b3bde4c 59struct mem_cgroup *root_mem_cgroup __read_mostly;
8cdea7c0 60
c077719b 61#ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
338c8431 62/* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
c077719b 63int do_swap_account __read_mostly;
a42c390c
MH
64
65/* for remember boot option*/
66#ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP_ENABLED
67static int really_do_swap_account __initdata = 1;
68#else
69static int really_do_swap_account __initdata = 0;
70#endif
71
c077719b
KH
72#else
73#define do_swap_account (0)
74#endif
75
76
d52aa412
KH
77/*
78 * Statistics for memory cgroup.
79 */
80enum mem_cgroup_stat_index {
81 /*
82 * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
83 */
84 MEM_CGROUP_STAT_CACHE, /* # of pages charged as cache */
d69b042f 85 MEM_CGROUP_STAT_RSS, /* # of pages charged as anon rss */
d8046582 86 MEM_CGROUP_STAT_FILE_MAPPED, /* # of pages charged as file rss */
0c3e73e8 87 MEM_CGROUP_STAT_SWAPOUT, /* # of pages, swapped out */
711d3d2c 88 MEM_CGROUP_STAT_DATA, /* end of data requires synchronization */
32047e2a 89 MEM_CGROUP_ON_MOVE, /* someone is moving account between groups */
d52aa412
KH
90 MEM_CGROUP_STAT_NSTATS,
91};
92
e9f8974f
JW
93enum mem_cgroup_events_index {
94 MEM_CGROUP_EVENTS_PGPGIN, /* # of pages paged in */
95 MEM_CGROUP_EVENTS_PGPGOUT, /* # of pages paged out */
96 MEM_CGROUP_EVENTS_COUNT, /* # of pages paged in/out */
456f998e
YH
97 MEM_CGROUP_EVENTS_PGFAULT, /* # of page-faults */
98 MEM_CGROUP_EVENTS_PGMAJFAULT, /* # of major page-faults */
e9f8974f
JW
99 MEM_CGROUP_EVENTS_NSTATS,
100};
7a159cc9
JW
101/*
102 * Per memcg event counter is incremented at every pagein/pageout. With THP,
103 * it will be incremated by the number of pages. This counter is used for
104 * for trigger some periodic events. This is straightforward and better
105 * than using jiffies etc. to handle periodic memcg event.
106 */
107enum mem_cgroup_events_target {
108 MEM_CGROUP_TARGET_THRESH,
109 MEM_CGROUP_TARGET_SOFTLIMIT,
453a9bf3 110 MEM_CGROUP_TARGET_NUMAINFO,
7a159cc9
JW
111 MEM_CGROUP_NTARGETS,
112};
113#define THRESHOLDS_EVENTS_TARGET (128)
114#define SOFTLIMIT_EVENTS_TARGET (1024)
453a9bf3 115#define NUMAINFO_EVENTS_TARGET (1024)
e9f8974f 116
d52aa412 117struct mem_cgroup_stat_cpu {
7a159cc9 118 long count[MEM_CGROUP_STAT_NSTATS];
e9f8974f 119 unsigned long events[MEM_CGROUP_EVENTS_NSTATS];
7a159cc9 120 unsigned long targets[MEM_CGROUP_NTARGETS];
d52aa412
KH
121};
122
6d12e2d8
KH
123/*
124 * per-zone information in memory controller.
125 */
6d12e2d8 126struct mem_cgroup_per_zone {
072c56c1
KH
127 /*
128 * spin_lock to protect the per cgroup LRU
129 */
b69408e8
CL
130 struct list_head lists[NR_LRU_LISTS];
131 unsigned long count[NR_LRU_LISTS];
3e2f41f1
KM
132
133 struct zone_reclaim_stat reclaim_stat;
f64c3f54
BS
134 struct rb_node tree_node; /* RB tree node */
135 unsigned long long usage_in_excess;/* Set to the value by which */
136 /* the soft limit is exceeded*/
137 bool on_tree;
4e416953
BS
138 struct mem_cgroup *mem; /* Back pointer, we cannot */
139 /* use container_of */
6d12e2d8
KH
140};
141/* Macro for accessing counter */
142#define MEM_CGROUP_ZSTAT(mz, idx) ((mz)->count[(idx)])
143
144struct mem_cgroup_per_node {
145 struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
146};
147
148struct mem_cgroup_lru_info {
149 struct mem_cgroup_per_node *nodeinfo[MAX_NUMNODES];
150};
151
f64c3f54
BS
152/*
153 * Cgroups above their limits are maintained in a RB-Tree, independent of
154 * their hierarchy representation
155 */
156
157struct mem_cgroup_tree_per_zone {
158 struct rb_root rb_root;
159 spinlock_t lock;
160};
161
162struct mem_cgroup_tree_per_node {
163 struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
164};
165
166struct mem_cgroup_tree {
167 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
168};
169
170static struct mem_cgroup_tree soft_limit_tree __read_mostly;
171
2e72b634
KS
172struct mem_cgroup_threshold {
173 struct eventfd_ctx *eventfd;
174 u64 threshold;
175};
176
9490ff27 177/* For threshold */
2e72b634
KS
178struct mem_cgroup_threshold_ary {
179 /* An array index points to threshold just below usage. */
5407a562 180 int current_threshold;
2e72b634
KS
181 /* Size of entries[] */
182 unsigned int size;
183 /* Array of thresholds */
184 struct mem_cgroup_threshold entries[0];
185};
2c488db2
KS
186
187struct mem_cgroup_thresholds {
188 /* Primary thresholds array */
189 struct mem_cgroup_threshold_ary *primary;
190 /*
191 * Spare threshold array.
192 * This is needed to make mem_cgroup_unregister_event() "never fail".
193 * It must be able to store at least primary->size - 1 entries.
194 */
195 struct mem_cgroup_threshold_ary *spare;
196};
197
9490ff27
KH
198/* for OOM */
199struct mem_cgroup_eventfd_list {
200 struct list_head list;
201 struct eventfd_ctx *eventfd;
202};
2e72b634 203
c0ff4b85
R
204static void mem_cgroup_threshold(struct mem_cgroup *memcg);
205static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
2e72b634 206
8cdea7c0
BS
207/*
208 * The memory controller data structure. The memory controller controls both
209 * page cache and RSS per cgroup. We would eventually like to provide
210 * statistics based on the statistics developed by Rik Van Riel for clock-pro,
211 * to help the administrator determine what knobs to tune.
212 *
213 * TODO: Add a water mark for the memory controller. Reclaim will begin when
8a9f3ccd
BS
214 * we hit the water mark. May be even add a low water mark, such that
215 * no reclaim occurs from a cgroup at it's low water mark, this is
216 * a feature that will be implemented much later in the future.
8cdea7c0
BS
217 */
218struct mem_cgroup {
219 struct cgroup_subsys_state css;
220 /*
221 * the counter to account for memory usage
222 */
223 struct res_counter res;
8c7c6e34
KH
224 /*
225 * the counter to account for mem+swap usage.
226 */
227 struct res_counter memsw;
78fb7466
PE
228 /*
229 * Per cgroup active and inactive list, similar to the
230 * per zone LRU lists.
78fb7466 231 */
6d12e2d8 232 struct mem_cgroup_lru_info info;
6d61ef40 233 /*
af901ca1 234 * While reclaiming in a hierarchy, we cache the last child we
04046e1a 235 * reclaimed from.
6d61ef40 236 */
04046e1a 237 int last_scanned_child;
889976db
YH
238 int last_scanned_node;
239#if MAX_NUMNODES > 1
240 nodemask_t scan_nodes;
453a9bf3
KH
241 atomic_t numainfo_events;
242 atomic_t numainfo_updating;
889976db 243#endif
18f59ea7
BS
244 /*
245 * Should the accounting and control be hierarchical, per subtree?
246 */
247 bool use_hierarchy;
79dfdacc
MH
248
249 bool oom_lock;
250 atomic_t under_oom;
251
8c7c6e34 252 atomic_t refcnt;
14797e23 253
1f4c025b 254 int swappiness;
3c11ecf4
KH
255 /* OOM-Killer disable */
256 int oom_kill_disable;
a7885eb8 257
22a668d7
KH
258 /* set when res.limit == memsw.limit */
259 bool memsw_is_minimum;
260
2e72b634
KS
261 /* protect arrays of thresholds */
262 struct mutex thresholds_lock;
263
264 /* thresholds for memory usage. RCU-protected */
2c488db2 265 struct mem_cgroup_thresholds thresholds;
907860ed 266
2e72b634 267 /* thresholds for mem+swap usage. RCU-protected */
2c488db2 268 struct mem_cgroup_thresholds memsw_thresholds;
907860ed 269
9490ff27
KH
270 /* For oom notifier event fd */
271 struct list_head oom_notify;
185efc0f 272
7dc74be0
DN
273 /*
274 * Should we move charges of a task when a task is moved into this
275 * mem_cgroup ? And what type of charges should we move ?
276 */
277 unsigned long move_charge_at_immigrate;
d52aa412 278 /*
c62b1a3b 279 * percpu counter.
d52aa412 280 */
c62b1a3b 281 struct mem_cgroup_stat_cpu *stat;
711d3d2c
KH
282 /*
283 * used when a cpu is offlined or other synchronizations
284 * See mem_cgroup_read_stat().
285 */
286 struct mem_cgroup_stat_cpu nocpu_base;
287 spinlock_t pcp_counter_lock;
8cdea7c0
BS
288};
289
7dc74be0
DN
290/* Stuffs for move charges at task migration. */
291/*
292 * Types of charges to be moved. "move_charge_at_immitgrate" is treated as a
293 * left-shifted bitmap of these types.
294 */
295enum move_type {
4ffef5fe 296 MOVE_CHARGE_TYPE_ANON, /* private anonymous page and swap of it */
87946a72 297 MOVE_CHARGE_TYPE_FILE, /* file page(including tmpfs) and swap of it */
7dc74be0
DN
298 NR_MOVE_TYPE,
299};
300
4ffef5fe
DN
301/* "mc" and its members are protected by cgroup_mutex */
302static struct move_charge_struct {
b1dd693e 303 spinlock_t lock; /* for from, to */
4ffef5fe
DN
304 struct mem_cgroup *from;
305 struct mem_cgroup *to;
306 unsigned long precharge;
854ffa8d 307 unsigned long moved_charge;
483c30b5 308 unsigned long moved_swap;
8033b97c
DN
309 struct task_struct *moving_task; /* a task moving charges */
310 wait_queue_head_t waitq; /* a waitq for other context */
311} mc = {
2bd9bb20 312 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
8033b97c
DN
313 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
314};
4ffef5fe 315
90254a65
DN
316static bool move_anon(void)
317{
318 return test_bit(MOVE_CHARGE_TYPE_ANON,
319 &mc.to->move_charge_at_immigrate);
320}
321
87946a72
DN
322static bool move_file(void)
323{
324 return test_bit(MOVE_CHARGE_TYPE_FILE,
325 &mc.to->move_charge_at_immigrate);
326}
327
4e416953
BS
328/*
329 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
330 * limit reclaim to prevent infinite loops, if they ever occur.
331 */
332#define MEM_CGROUP_MAX_RECLAIM_LOOPS (100)
333#define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS (2)
334
217bc319
KH
335enum charge_type {
336 MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
337 MEM_CGROUP_CHARGE_TYPE_MAPPED,
4f98a2fe 338 MEM_CGROUP_CHARGE_TYPE_SHMEM, /* used by page migration of shmem */
c05555b5 339 MEM_CGROUP_CHARGE_TYPE_FORCE, /* used by force_empty */
d13d1443 340 MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
8a9478ca 341 MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
c05555b5
KH
342 NR_CHARGE_TYPE,
343};
344
8c7c6e34
KH
345/* for encoding cft->private value on file */
346#define _MEM (0)
347#define _MEMSWAP (1)
9490ff27 348#define _OOM_TYPE (2)
8c7c6e34
KH
349#define MEMFILE_PRIVATE(x, val) (((x) << 16) | (val))
350#define MEMFILE_TYPE(val) (((val) >> 16) & 0xffff)
351#define MEMFILE_ATTR(val) ((val) & 0xffff)
9490ff27
KH
352/* Used for OOM nofiier */
353#define OOM_CONTROL (0)
8c7c6e34 354
75822b44
BS
355/*
356 * Reclaim flags for mem_cgroup_hierarchical_reclaim
357 */
358#define MEM_CGROUP_RECLAIM_NOSWAP_BIT 0x0
359#define MEM_CGROUP_RECLAIM_NOSWAP (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
360#define MEM_CGROUP_RECLAIM_SHRINK_BIT 0x1
361#define MEM_CGROUP_RECLAIM_SHRINK (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
4e416953
BS
362#define MEM_CGROUP_RECLAIM_SOFT_BIT 0x2
363#define MEM_CGROUP_RECLAIM_SOFT (1 << MEM_CGROUP_RECLAIM_SOFT_BIT)
75822b44 364
c0ff4b85
R
365static void mem_cgroup_get(struct mem_cgroup *memcg);
366static void mem_cgroup_put(struct mem_cgroup *memcg);
367static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg);
368static void drain_all_stock_async(struct mem_cgroup *memcg);
8c7c6e34 369
f64c3f54 370static struct mem_cgroup_per_zone *
c0ff4b85 371mem_cgroup_zoneinfo(struct mem_cgroup *memcg, int nid, int zid)
f64c3f54 372{
c0ff4b85 373 return &memcg->info.nodeinfo[nid]->zoneinfo[zid];
f64c3f54
BS
374}
375
c0ff4b85 376struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *memcg)
d324236b 377{
c0ff4b85 378 return &memcg->css;
d324236b
WF
379}
380
f64c3f54 381static struct mem_cgroup_per_zone *
c0ff4b85 382page_cgroup_zoneinfo(struct mem_cgroup *memcg, struct page *page)
f64c3f54 383{
97a6c37b
JW
384 int nid = page_to_nid(page);
385 int zid = page_zonenum(page);
f64c3f54 386
c0ff4b85 387 return mem_cgroup_zoneinfo(memcg, nid, zid);
f64c3f54
BS
388}
389
390static struct mem_cgroup_tree_per_zone *
391soft_limit_tree_node_zone(int nid, int zid)
392{
393 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
394}
395
396static struct mem_cgroup_tree_per_zone *
397soft_limit_tree_from_page(struct page *page)
398{
399 int nid = page_to_nid(page);
400 int zid = page_zonenum(page);
401
402 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
403}
404
405static void
c0ff4b85 406__mem_cgroup_insert_exceeded(struct mem_cgroup *memcg,
f64c3f54 407 struct mem_cgroup_per_zone *mz,
ef8745c1
KH
408 struct mem_cgroup_tree_per_zone *mctz,
409 unsigned long long new_usage_in_excess)
f64c3f54
BS
410{
411 struct rb_node **p = &mctz->rb_root.rb_node;
412 struct rb_node *parent = NULL;
413 struct mem_cgroup_per_zone *mz_node;
414
415 if (mz->on_tree)
416 return;
417
ef8745c1
KH
418 mz->usage_in_excess = new_usage_in_excess;
419 if (!mz->usage_in_excess)
420 return;
f64c3f54
BS
421 while (*p) {
422 parent = *p;
423 mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
424 tree_node);
425 if (mz->usage_in_excess < mz_node->usage_in_excess)
426 p = &(*p)->rb_left;
427 /*
428 * We can't avoid mem cgroups that are over their soft
429 * limit by the same amount
430 */
431 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
432 p = &(*p)->rb_right;
433 }
434 rb_link_node(&mz->tree_node, parent, p);
435 rb_insert_color(&mz->tree_node, &mctz->rb_root);
436 mz->on_tree = true;
4e416953
BS
437}
438
439static void
c0ff4b85 440__mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
4e416953
BS
441 struct mem_cgroup_per_zone *mz,
442 struct mem_cgroup_tree_per_zone *mctz)
443{
444 if (!mz->on_tree)
445 return;
446 rb_erase(&mz->tree_node, &mctz->rb_root);
447 mz->on_tree = false;
448}
449
f64c3f54 450static void
c0ff4b85 451mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
f64c3f54
BS
452 struct mem_cgroup_per_zone *mz,
453 struct mem_cgroup_tree_per_zone *mctz)
454{
455 spin_lock(&mctz->lock);
c0ff4b85 456 __mem_cgroup_remove_exceeded(memcg, mz, mctz);
f64c3f54
BS
457 spin_unlock(&mctz->lock);
458}
459
f64c3f54 460
c0ff4b85 461static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
f64c3f54 462{
ef8745c1 463 unsigned long long excess;
f64c3f54
BS
464 struct mem_cgroup_per_zone *mz;
465 struct mem_cgroup_tree_per_zone *mctz;
4e649152
KH
466 int nid = page_to_nid(page);
467 int zid = page_zonenum(page);
f64c3f54
BS
468 mctz = soft_limit_tree_from_page(page);
469
470 /*
4e649152
KH
471 * Necessary to update all ancestors when hierarchy is used.
472 * because their event counter is not touched.
f64c3f54 473 */
c0ff4b85
R
474 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
475 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
476 excess = res_counter_soft_limit_excess(&memcg->res);
4e649152
KH
477 /*
478 * We have to update the tree if mz is on RB-tree or
479 * mem is over its softlimit.
480 */
ef8745c1 481 if (excess || mz->on_tree) {
4e649152
KH
482 spin_lock(&mctz->lock);
483 /* if on-tree, remove it */
484 if (mz->on_tree)
c0ff4b85 485 __mem_cgroup_remove_exceeded(memcg, mz, mctz);
4e649152 486 /*
ef8745c1
KH
487 * Insert again. mz->usage_in_excess will be updated.
488 * If excess is 0, no tree ops.
4e649152 489 */
c0ff4b85 490 __mem_cgroup_insert_exceeded(memcg, mz, mctz, excess);
4e649152
KH
491 spin_unlock(&mctz->lock);
492 }
f64c3f54
BS
493 }
494}
495
c0ff4b85 496static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
f64c3f54
BS
497{
498 int node, zone;
499 struct mem_cgroup_per_zone *mz;
500 struct mem_cgroup_tree_per_zone *mctz;
501
502 for_each_node_state(node, N_POSSIBLE) {
503 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
c0ff4b85 504 mz = mem_cgroup_zoneinfo(memcg, node, zone);
f64c3f54 505 mctz = soft_limit_tree_node_zone(node, zone);
c0ff4b85 506 mem_cgroup_remove_exceeded(memcg, mz, mctz);
f64c3f54
BS
507 }
508 }
509}
510
4e416953
BS
511static struct mem_cgroup_per_zone *
512__mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
513{
514 struct rb_node *rightmost = NULL;
26251eaf 515 struct mem_cgroup_per_zone *mz;
4e416953
BS
516
517retry:
26251eaf 518 mz = NULL;
4e416953
BS
519 rightmost = rb_last(&mctz->rb_root);
520 if (!rightmost)
521 goto done; /* Nothing to reclaim from */
522
523 mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
524 /*
525 * Remove the node now but someone else can add it back,
526 * we will to add it back at the end of reclaim to its correct
527 * position in the tree.
528 */
529 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
530 if (!res_counter_soft_limit_excess(&mz->mem->res) ||
531 !css_tryget(&mz->mem->css))
532 goto retry;
533done:
534 return mz;
535}
536
537static struct mem_cgroup_per_zone *
538mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
539{
540 struct mem_cgroup_per_zone *mz;
541
542 spin_lock(&mctz->lock);
543 mz = __mem_cgroup_largest_soft_limit_node(mctz);
544 spin_unlock(&mctz->lock);
545 return mz;
546}
547
711d3d2c
KH
548/*
549 * Implementation Note: reading percpu statistics for memcg.
550 *
551 * Both of vmstat[] and percpu_counter has threshold and do periodic
552 * synchronization to implement "quick" read. There are trade-off between
553 * reading cost and precision of value. Then, we may have a chance to implement
554 * a periodic synchronizion of counter in memcg's counter.
555 *
556 * But this _read() function is used for user interface now. The user accounts
557 * memory usage by memory cgroup and he _always_ requires exact value because
558 * he accounts memory. Even if we provide quick-and-fuzzy read, we always
559 * have to visit all online cpus and make sum. So, for now, unnecessary
560 * synchronization is not implemented. (just implemented for cpu hotplug)
561 *
562 * If there are kernel internal actions which can make use of some not-exact
563 * value, and reading all cpu value can be performance bottleneck in some
564 * common workload, threashold and synchonization as vmstat[] should be
565 * implemented.
566 */
c0ff4b85 567static long mem_cgroup_read_stat(struct mem_cgroup *memcg,
7a159cc9 568 enum mem_cgroup_stat_index idx)
c62b1a3b 569{
7a159cc9 570 long val = 0;
c62b1a3b 571 int cpu;
c62b1a3b 572
711d3d2c
KH
573 get_online_cpus();
574 for_each_online_cpu(cpu)
c0ff4b85 575 val += per_cpu(memcg->stat->count[idx], cpu);
711d3d2c 576#ifdef CONFIG_HOTPLUG_CPU
c0ff4b85
R
577 spin_lock(&memcg->pcp_counter_lock);
578 val += memcg->nocpu_base.count[idx];
579 spin_unlock(&memcg->pcp_counter_lock);
711d3d2c
KH
580#endif
581 put_online_cpus();
c62b1a3b
KH
582 return val;
583}
584
c0ff4b85 585static void mem_cgroup_swap_statistics(struct mem_cgroup *memcg,
0c3e73e8
BS
586 bool charge)
587{
588 int val = (charge) ? 1 : -1;
c0ff4b85 589 this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_SWAPOUT], val);
0c3e73e8
BS
590}
591
c0ff4b85 592void mem_cgroup_pgfault(struct mem_cgroup *memcg, int val)
456f998e 593{
c0ff4b85 594 this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_PGFAULT], val);
456f998e
YH
595}
596
c0ff4b85 597void mem_cgroup_pgmajfault(struct mem_cgroup *memcg, int val)
456f998e 598{
c0ff4b85 599 this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_PGMAJFAULT], val);
456f998e
YH
600}
601
c0ff4b85 602static unsigned long mem_cgroup_read_events(struct mem_cgroup *memcg,
e9f8974f
JW
603 enum mem_cgroup_events_index idx)
604{
605 unsigned long val = 0;
606 int cpu;
607
608 for_each_online_cpu(cpu)
c0ff4b85 609 val += per_cpu(memcg->stat->events[idx], cpu);
e9f8974f 610#ifdef CONFIG_HOTPLUG_CPU
c0ff4b85
R
611 spin_lock(&memcg->pcp_counter_lock);
612 val += memcg->nocpu_base.events[idx];
613 spin_unlock(&memcg->pcp_counter_lock);
e9f8974f
JW
614#endif
615 return val;
616}
617
c0ff4b85 618static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
e401f176 619 bool file, int nr_pages)
d52aa412 620{
c62b1a3b
KH
621 preempt_disable();
622
e401f176 623 if (file)
c0ff4b85
R
624 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_CACHE],
625 nr_pages);
d52aa412 626 else
c0ff4b85
R
627 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS],
628 nr_pages);
55e462b0 629
e401f176
KH
630 /* pagein of a big page is an event. So, ignore page size */
631 if (nr_pages > 0)
c0ff4b85 632 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGIN]);
3751d604 633 else {
c0ff4b85 634 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGOUT]);
3751d604
KH
635 nr_pages = -nr_pages; /* for event */
636 }
e401f176 637
c0ff4b85 638 __this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_COUNT], nr_pages);
2e72b634 639
c62b1a3b 640 preempt_enable();
6d12e2d8
KH
641}
642
bb2a0de9 643unsigned long
c0ff4b85 644mem_cgroup_zone_nr_lru_pages(struct mem_cgroup *memcg, int nid, int zid,
bb2a0de9 645 unsigned int lru_mask)
889976db
YH
646{
647 struct mem_cgroup_per_zone *mz;
bb2a0de9
KH
648 enum lru_list l;
649 unsigned long ret = 0;
650
c0ff4b85 651 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
bb2a0de9
KH
652
653 for_each_lru(l) {
654 if (BIT(l) & lru_mask)
655 ret += MEM_CGROUP_ZSTAT(mz, l);
656 }
657 return ret;
658}
659
660static unsigned long
c0ff4b85 661mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
bb2a0de9
KH
662 int nid, unsigned int lru_mask)
663{
889976db
YH
664 u64 total = 0;
665 int zid;
666
bb2a0de9 667 for (zid = 0; zid < MAX_NR_ZONES; zid++)
c0ff4b85
R
668 total += mem_cgroup_zone_nr_lru_pages(memcg,
669 nid, zid, lru_mask);
bb2a0de9 670
889976db
YH
671 return total;
672}
bb2a0de9 673
c0ff4b85 674static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
bb2a0de9 675 unsigned int lru_mask)
6d12e2d8 676{
889976db 677 int nid;
6d12e2d8
KH
678 u64 total = 0;
679
bb2a0de9 680 for_each_node_state(nid, N_HIGH_MEMORY)
c0ff4b85 681 total += mem_cgroup_node_nr_lru_pages(memcg, nid, lru_mask);
6d12e2d8 682 return total;
d52aa412
KH
683}
684
c0ff4b85 685static bool __memcg_event_check(struct mem_cgroup *memcg, int target)
7a159cc9
JW
686{
687 unsigned long val, next;
688
c0ff4b85
R
689 val = this_cpu_read(memcg->stat->events[MEM_CGROUP_EVENTS_COUNT]);
690 next = this_cpu_read(memcg->stat->targets[target]);
7a159cc9
JW
691 /* from time_after() in jiffies.h */
692 return ((long)next - (long)val < 0);
693}
694
c0ff4b85 695static void __mem_cgroup_target_update(struct mem_cgroup *memcg, int target)
d2265e6f 696{
7a159cc9 697 unsigned long val, next;
d2265e6f 698
c0ff4b85 699 val = this_cpu_read(memcg->stat->events[MEM_CGROUP_EVENTS_COUNT]);
d2265e6f 700
7a159cc9
JW
701 switch (target) {
702 case MEM_CGROUP_TARGET_THRESH:
703 next = val + THRESHOLDS_EVENTS_TARGET;
704 break;
705 case MEM_CGROUP_TARGET_SOFTLIMIT:
706 next = val + SOFTLIMIT_EVENTS_TARGET;
707 break;
453a9bf3
KH
708 case MEM_CGROUP_TARGET_NUMAINFO:
709 next = val + NUMAINFO_EVENTS_TARGET;
710 break;
7a159cc9
JW
711 default:
712 return;
713 }
714
c0ff4b85 715 this_cpu_write(memcg->stat->targets[target], next);
d2265e6f
KH
716}
717
718/*
719 * Check events in order.
720 *
721 */
c0ff4b85 722static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
d2265e6f
KH
723{
724 /* threshold event is triggered in finer grain than soft limit */
c0ff4b85
R
725 if (unlikely(__memcg_event_check(memcg, MEM_CGROUP_TARGET_THRESH))) {
726 mem_cgroup_threshold(memcg);
727 __mem_cgroup_target_update(memcg, MEM_CGROUP_TARGET_THRESH);
728 if (unlikely(__memcg_event_check(memcg,
453a9bf3 729 MEM_CGROUP_TARGET_SOFTLIMIT))) {
c0ff4b85
R
730 mem_cgroup_update_tree(memcg, page);
731 __mem_cgroup_target_update(memcg,
453a9bf3
KH
732 MEM_CGROUP_TARGET_SOFTLIMIT);
733 }
734#if MAX_NUMNODES > 1
c0ff4b85 735 if (unlikely(__memcg_event_check(memcg,
453a9bf3 736 MEM_CGROUP_TARGET_NUMAINFO))) {
c0ff4b85
R
737 atomic_inc(&memcg->numainfo_events);
738 __mem_cgroup_target_update(memcg,
453a9bf3 739 MEM_CGROUP_TARGET_NUMAINFO);
7a159cc9 740 }
453a9bf3 741#endif
d2265e6f
KH
742 }
743}
744
d5b69e38 745static struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
8cdea7c0
BS
746{
747 return container_of(cgroup_subsys_state(cont,
748 mem_cgroup_subsys_id), struct mem_cgroup,
749 css);
750}
751
cf475ad2 752struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
78fb7466 753{
31a78f23
BS
754 /*
755 * mm_update_next_owner() may clear mm->owner to NULL
756 * if it races with swapoff, page migration, etc.
757 * So this can be called with p == NULL.
758 */
759 if (unlikely(!p))
760 return NULL;
761
78fb7466
PE
762 return container_of(task_subsys_state(p, mem_cgroup_subsys_id),
763 struct mem_cgroup, css);
764}
765
a433658c 766struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
54595fe2 767{
c0ff4b85 768 struct mem_cgroup *memcg = NULL;
0b7f569e
KH
769
770 if (!mm)
771 return NULL;
54595fe2
KH
772 /*
773 * Because we have no locks, mm->owner's may be being moved to other
774 * cgroup. We use css_tryget() here even if this looks
775 * pessimistic (rather than adding locks here).
776 */
777 rcu_read_lock();
778 do {
c0ff4b85
R
779 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
780 if (unlikely(!memcg))
54595fe2 781 break;
c0ff4b85 782 } while (!css_tryget(&memcg->css));
54595fe2 783 rcu_read_unlock();
c0ff4b85 784 return memcg;
54595fe2
KH
785}
786
7d74b06f 787/* The caller has to guarantee "mem" exists before calling this */
c0ff4b85 788static struct mem_cgroup *mem_cgroup_start_loop(struct mem_cgroup *memcg)
14067bb3 789{
711d3d2c
KH
790 struct cgroup_subsys_state *css;
791 int found;
792
c0ff4b85 793 if (!memcg) /* ROOT cgroup has the smallest ID */
711d3d2c 794 return root_mem_cgroup; /*css_put/get against root is ignored*/
c0ff4b85
R
795 if (!memcg->use_hierarchy) {
796 if (css_tryget(&memcg->css))
797 return memcg;
711d3d2c
KH
798 return NULL;
799 }
800 rcu_read_lock();
801 /*
802 * searching a memory cgroup which has the smallest ID under given
803 * ROOT cgroup. (ID >= 1)
804 */
c0ff4b85 805 css = css_get_next(&mem_cgroup_subsys, 1, &memcg->css, &found);
711d3d2c 806 if (css && css_tryget(css))
c0ff4b85 807 memcg = container_of(css, struct mem_cgroup, css);
711d3d2c 808 else
c0ff4b85 809 memcg = NULL;
711d3d2c 810 rcu_read_unlock();
c0ff4b85 811 return memcg;
7d74b06f
KH
812}
813
814static struct mem_cgroup *mem_cgroup_get_next(struct mem_cgroup *iter,
815 struct mem_cgroup *root,
816 bool cond)
817{
818 int nextid = css_id(&iter->css) + 1;
819 int found;
820 int hierarchy_used;
14067bb3 821 struct cgroup_subsys_state *css;
14067bb3 822
7d74b06f 823 hierarchy_used = iter->use_hierarchy;
14067bb3 824
7d74b06f 825 css_put(&iter->css);
711d3d2c
KH
826 /* If no ROOT, walk all, ignore hierarchy */
827 if (!cond || (root && !hierarchy_used))
7d74b06f 828 return NULL;
14067bb3 829
711d3d2c
KH
830 if (!root)
831 root = root_mem_cgroup;
832
7d74b06f
KH
833 do {
834 iter = NULL;
14067bb3 835 rcu_read_lock();
7d74b06f
KH
836
837 css = css_get_next(&mem_cgroup_subsys, nextid,
838 &root->css, &found);
14067bb3 839 if (css && css_tryget(css))
7d74b06f 840 iter = container_of(css, struct mem_cgroup, css);
14067bb3 841 rcu_read_unlock();
7d74b06f 842 /* If css is NULL, no more cgroups will be found */
14067bb3 843 nextid = found + 1;
7d74b06f 844 } while (css && !iter);
14067bb3 845
7d74b06f 846 return iter;
14067bb3 847}
7d74b06f
KH
848/*
849 * for_eacn_mem_cgroup_tree() for visiting all cgroup under tree. Please
850 * be careful that "break" loop is not allowed. We have reference count.
851 * Instead of that modify "cond" to be false and "continue" to exit the loop.
852 */
853#define for_each_mem_cgroup_tree_cond(iter, root, cond) \
854 for (iter = mem_cgroup_start_loop(root);\
855 iter != NULL;\
856 iter = mem_cgroup_get_next(iter, root, cond))
857
858#define for_each_mem_cgroup_tree(iter, root) \
859 for_each_mem_cgroup_tree_cond(iter, root, true)
860
711d3d2c
KH
861#define for_each_mem_cgroup_all(iter) \
862 for_each_mem_cgroup_tree_cond(iter, NULL, true)
863
14067bb3 864
c0ff4b85 865static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg)
4b3bde4c 866{
c0ff4b85 867 return (memcg == root_mem_cgroup);
4b3bde4c
BS
868}
869
456f998e
YH
870void mem_cgroup_count_vm_event(struct mm_struct *mm, enum vm_event_item idx)
871{
c0ff4b85 872 struct mem_cgroup *memcg;
456f998e
YH
873
874 if (!mm)
875 return;
876
877 rcu_read_lock();
c0ff4b85
R
878 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
879 if (unlikely(!memcg))
456f998e
YH
880 goto out;
881
882 switch (idx) {
883 case PGMAJFAULT:
c0ff4b85 884 mem_cgroup_pgmajfault(memcg, 1);
456f998e
YH
885 break;
886 case PGFAULT:
c0ff4b85 887 mem_cgroup_pgfault(memcg, 1);
456f998e
YH
888 break;
889 default:
890 BUG();
891 }
892out:
893 rcu_read_unlock();
894}
895EXPORT_SYMBOL(mem_cgroup_count_vm_event);
896
08e552c6
KH
897/*
898 * Following LRU functions are allowed to be used without PCG_LOCK.
899 * Operations are called by routine of global LRU independently from memcg.
900 * What we have to take care of here is validness of pc->mem_cgroup.
901 *
902 * Changes to pc->mem_cgroup happens when
903 * 1. charge
904 * 2. moving account
905 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
906 * It is added to LRU before charge.
907 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
908 * When moving account, the page is not on LRU. It's isolated.
909 */
4f98a2fe 910
08e552c6
KH
911void mem_cgroup_del_lru_list(struct page *page, enum lru_list lru)
912{
913 struct page_cgroup *pc;
08e552c6 914 struct mem_cgroup_per_zone *mz;
6d12e2d8 915
f8d66542 916 if (mem_cgroup_disabled())
08e552c6
KH
917 return;
918 pc = lookup_page_cgroup(page);
919 /* can happen while we handle swapcache. */
4b3bde4c 920 if (!TestClearPageCgroupAcctLRU(pc))
08e552c6 921 return;
4b3bde4c 922 VM_BUG_ON(!pc->mem_cgroup);
544122e5
KH
923 /*
924 * We don't check PCG_USED bit. It's cleared when the "page" is finally
925 * removed from global LRU.
926 */
97a6c37b 927 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
ece35ca8
KH
928 /* huge page split is done under lru_lock. so, we have no races. */
929 MEM_CGROUP_ZSTAT(mz, lru) -= 1 << compound_order(page);
4b3bde4c
BS
930 if (mem_cgroup_is_root(pc->mem_cgroup))
931 return;
932 VM_BUG_ON(list_empty(&pc->lru));
08e552c6 933 list_del_init(&pc->lru);
6d12e2d8
KH
934}
935
08e552c6 936void mem_cgroup_del_lru(struct page *page)
6d12e2d8 937{
08e552c6
KH
938 mem_cgroup_del_lru_list(page, page_lru(page));
939}
b69408e8 940
3f58a829
MK
941/*
942 * Writeback is about to end against a page which has been marked for immediate
943 * reclaim. If it still appears to be reclaimable, move it to the tail of the
944 * inactive list.
945 */
946void mem_cgroup_rotate_reclaimable_page(struct page *page)
947{
948 struct mem_cgroup_per_zone *mz;
949 struct page_cgroup *pc;
950 enum lru_list lru = page_lru(page);
951
952 if (mem_cgroup_disabled())
953 return;
954
955 pc = lookup_page_cgroup(page);
956 /* unused or root page is not rotated. */
957 if (!PageCgroupUsed(pc))
958 return;
959 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
960 smp_rmb();
961 if (mem_cgroup_is_root(pc->mem_cgroup))
962 return;
97a6c37b 963 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
3f58a829
MK
964 list_move_tail(&pc->lru, &mz->lists[lru]);
965}
966
08e552c6
KH
967void mem_cgroup_rotate_lru_list(struct page *page, enum lru_list lru)
968{
969 struct mem_cgroup_per_zone *mz;
970 struct page_cgroup *pc;
b69408e8 971
f8d66542 972 if (mem_cgroup_disabled())
08e552c6 973 return;
6d12e2d8 974
08e552c6 975 pc = lookup_page_cgroup(page);
4b3bde4c 976 /* unused or root page is not rotated. */
713735b4
JW
977 if (!PageCgroupUsed(pc))
978 return;
979 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
980 smp_rmb();
981 if (mem_cgroup_is_root(pc->mem_cgroup))
08e552c6 982 return;
97a6c37b 983 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
08e552c6 984 list_move(&pc->lru, &mz->lists[lru]);
6d12e2d8
KH
985}
986
08e552c6 987void mem_cgroup_add_lru_list(struct page *page, enum lru_list lru)
66e1707b 988{
08e552c6
KH
989 struct page_cgroup *pc;
990 struct mem_cgroup_per_zone *mz;
6d12e2d8 991
f8d66542 992 if (mem_cgroup_disabled())
08e552c6
KH
993 return;
994 pc = lookup_page_cgroup(page);
4b3bde4c 995 VM_BUG_ON(PageCgroupAcctLRU(pc));
a61ed3ce
JW
996 /*
997 * putback: charge:
998 * SetPageLRU SetPageCgroupUsed
999 * smp_mb smp_mb
1000 * PageCgroupUsed && add to memcg LRU PageLRU && add to memcg LRU
1001 *
1002 * Ensure that one of the two sides adds the page to the memcg
1003 * LRU during a race.
1004 */
1005 smp_mb();
08e552c6 1006 if (!PageCgroupUsed(pc))
894bc310 1007 return;
713735b4
JW
1008 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1009 smp_rmb();
97a6c37b 1010 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
ece35ca8
KH
1011 /* huge page split is done under lru_lock. so, we have no races. */
1012 MEM_CGROUP_ZSTAT(mz, lru) += 1 << compound_order(page);
4b3bde4c
BS
1013 SetPageCgroupAcctLRU(pc);
1014 if (mem_cgroup_is_root(pc->mem_cgroup))
1015 return;
08e552c6
KH
1016 list_add(&pc->lru, &mz->lists[lru]);
1017}
544122e5 1018
08e552c6 1019/*
5a6475a4
KH
1020 * At handling SwapCache and other FUSE stuff, pc->mem_cgroup may be changed
1021 * while it's linked to lru because the page may be reused after it's fully
1022 * uncharged. To handle that, unlink page_cgroup from LRU when charge it again.
1023 * It's done under lock_page and expected that zone->lru_lock isnever held.
08e552c6 1024 */
5a6475a4 1025static void mem_cgroup_lru_del_before_commit(struct page *page)
08e552c6 1026{
544122e5
KH
1027 unsigned long flags;
1028 struct zone *zone = page_zone(page);
1029 struct page_cgroup *pc = lookup_page_cgroup(page);
1030
5a6475a4
KH
1031 /*
1032 * Doing this check without taking ->lru_lock seems wrong but this
1033 * is safe. Because if page_cgroup's USED bit is unset, the page
1034 * will not be added to any memcg's LRU. If page_cgroup's USED bit is
1035 * set, the commit after this will fail, anyway.
1036 * This all charge/uncharge is done under some mutual execustion.
1037 * So, we don't need to taking care of changes in USED bit.
1038 */
1039 if (likely(!PageLRU(page)))
1040 return;
1041
544122e5
KH
1042 spin_lock_irqsave(&zone->lru_lock, flags);
1043 /*
1044 * Forget old LRU when this page_cgroup is *not* used. This Used bit
1045 * is guarded by lock_page() because the page is SwapCache.
1046 */
1047 if (!PageCgroupUsed(pc))
1048 mem_cgroup_del_lru_list(page, page_lru(page));
1049 spin_unlock_irqrestore(&zone->lru_lock, flags);
08e552c6
KH
1050}
1051
5a6475a4 1052static void mem_cgroup_lru_add_after_commit(struct page *page)
544122e5
KH
1053{
1054 unsigned long flags;
1055 struct zone *zone = page_zone(page);
1056 struct page_cgroup *pc = lookup_page_cgroup(page);
a61ed3ce
JW
1057 /*
1058 * putback: charge:
1059 * SetPageLRU SetPageCgroupUsed
1060 * smp_mb smp_mb
1061 * PageCgroupUsed && add to memcg LRU PageLRU && add to memcg LRU
1062 *
1063 * Ensure that one of the two sides adds the page to the memcg
1064 * LRU during a race.
1065 */
1066 smp_mb();
5a6475a4
KH
1067 /* taking care of that the page is added to LRU while we commit it */
1068 if (likely(!PageLRU(page)))
1069 return;
544122e5
KH
1070 spin_lock_irqsave(&zone->lru_lock, flags);
1071 /* link when the page is linked to LRU but page_cgroup isn't */
4b3bde4c 1072 if (PageLRU(page) && !PageCgroupAcctLRU(pc))
544122e5
KH
1073 mem_cgroup_add_lru_list(page, page_lru(page));
1074 spin_unlock_irqrestore(&zone->lru_lock, flags);
1075}
1076
1077
08e552c6
KH
1078void mem_cgroup_move_lists(struct page *page,
1079 enum lru_list from, enum lru_list to)
1080{
f8d66542 1081 if (mem_cgroup_disabled())
08e552c6
KH
1082 return;
1083 mem_cgroup_del_lru_list(page, from);
1084 mem_cgroup_add_lru_list(page, to);
66e1707b
BS
1085}
1086
3e92041d 1087/*
c0ff4b85 1088 * Checks whether given mem is same or in the root_mem_cgroup's
3e92041d
MH
1089 * hierarchy subtree
1090 */
c0ff4b85
R
1091static bool mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
1092 struct mem_cgroup *memcg)
3e92041d 1093{
c0ff4b85
R
1094 if (root_memcg != memcg) {
1095 return (root_memcg->use_hierarchy &&
1096 css_is_ancestor(&memcg->css, &root_memcg->css));
3e92041d
MH
1097 }
1098
1099 return true;
1100}
1101
c0ff4b85 1102int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *memcg)
4c4a2214
DR
1103{
1104 int ret;
0b7f569e 1105 struct mem_cgroup *curr = NULL;
158e0a2d 1106 struct task_struct *p;
4c4a2214 1107
158e0a2d
KH
1108 p = find_lock_task_mm(task);
1109 if (!p)
1110 return 0;
1111 curr = try_get_mem_cgroup_from_mm(p->mm);
1112 task_unlock(p);
0b7f569e
KH
1113 if (!curr)
1114 return 0;
d31f56db 1115 /*
c0ff4b85 1116 * We should check use_hierarchy of "memcg" not "curr". Because checking
d31f56db 1117 * use_hierarchy of "curr" here make this function true if hierarchy is
c0ff4b85
R
1118 * enabled in "curr" and "curr" is a child of "memcg" in *cgroup*
1119 * hierarchy(even if use_hierarchy is disabled in "memcg").
d31f56db 1120 */
c0ff4b85 1121 ret = mem_cgroup_same_or_subtree(memcg, curr);
0b7f569e 1122 css_put(&curr->css);
4c4a2214
DR
1123 return ret;
1124}
1125
9b272977 1126int mem_cgroup_inactive_anon_is_low(struct mem_cgroup *memcg, struct zone *zone)
14797e23 1127{
9b272977
JW
1128 unsigned long inactive_ratio;
1129 int nid = zone_to_nid(zone);
1130 int zid = zone_idx(zone);
14797e23 1131 unsigned long inactive;
9b272977 1132 unsigned long active;
c772be93 1133 unsigned long gb;
14797e23 1134
9b272977
JW
1135 inactive = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1136 BIT(LRU_INACTIVE_ANON));
1137 active = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1138 BIT(LRU_ACTIVE_ANON));
14797e23 1139
c772be93
KM
1140 gb = (inactive + active) >> (30 - PAGE_SHIFT);
1141 if (gb)
1142 inactive_ratio = int_sqrt(10 * gb);
1143 else
1144 inactive_ratio = 1;
1145
9b272977 1146 return inactive * inactive_ratio < active;
14797e23
KM
1147}
1148
9b272977 1149int mem_cgroup_inactive_file_is_low(struct mem_cgroup *memcg, struct zone *zone)
56e49d21
RR
1150{
1151 unsigned long active;
1152 unsigned long inactive;
9b272977
JW
1153 int zid = zone_idx(zone);
1154 int nid = zone_to_nid(zone);
56e49d21 1155
9b272977
JW
1156 inactive = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1157 BIT(LRU_INACTIVE_FILE));
1158 active = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1159 BIT(LRU_ACTIVE_FILE));
56e49d21
RR
1160
1161 return (active > inactive);
1162}
1163
3e2f41f1
KM
1164struct zone_reclaim_stat *mem_cgroup_get_reclaim_stat(struct mem_cgroup *memcg,
1165 struct zone *zone)
1166{
13d7e3a2 1167 int nid = zone_to_nid(zone);
3e2f41f1
KM
1168 int zid = zone_idx(zone);
1169 struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
1170
1171 return &mz->reclaim_stat;
1172}
1173
1174struct zone_reclaim_stat *
1175mem_cgroup_get_reclaim_stat_from_page(struct page *page)
1176{
1177 struct page_cgroup *pc;
1178 struct mem_cgroup_per_zone *mz;
1179
1180 if (mem_cgroup_disabled())
1181 return NULL;
1182
1183 pc = lookup_page_cgroup(page);
bd112db8
DN
1184 if (!PageCgroupUsed(pc))
1185 return NULL;
713735b4
JW
1186 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1187 smp_rmb();
97a6c37b 1188 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
3e2f41f1
KM
1189 return &mz->reclaim_stat;
1190}
1191
66e1707b
BS
1192unsigned long mem_cgroup_isolate_pages(unsigned long nr_to_scan,
1193 struct list_head *dst,
1194 unsigned long *scanned, int order,
4356f21d
MK
1195 isolate_mode_t mode,
1196 struct zone *z,
66e1707b 1197 struct mem_cgroup *mem_cont,
4f98a2fe 1198 int active, int file)
66e1707b
BS
1199{
1200 unsigned long nr_taken = 0;
1201 struct page *page;
1202 unsigned long scan;
1203 LIST_HEAD(pc_list);
1204 struct list_head *src;
ff7283fa 1205 struct page_cgroup *pc, *tmp;
13d7e3a2 1206 int nid = zone_to_nid(z);
1ecaab2b
KH
1207 int zid = zone_idx(z);
1208 struct mem_cgroup_per_zone *mz;
b7c46d15 1209 int lru = LRU_FILE * file + active;
2ffebca6 1210 int ret;
66e1707b 1211
cf475ad2 1212 BUG_ON(!mem_cont);
1ecaab2b 1213 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
b69408e8 1214 src = &mz->lists[lru];
66e1707b 1215
ff7283fa
KH
1216 scan = 0;
1217 list_for_each_entry_safe_reverse(pc, tmp, src, lru) {
436c6541 1218 if (scan >= nr_to_scan)
ff7283fa 1219 break;
08e552c6 1220
52d4b9ac
KH
1221 if (unlikely(!PageCgroupUsed(pc)))
1222 continue;
5564e88b 1223
6b3ae58e 1224 page = lookup_cgroup_page(pc);
5564e88b 1225
436c6541 1226 if (unlikely(!PageLRU(page)))
ff7283fa 1227 continue;
ff7283fa 1228
436c6541 1229 scan++;
2ffebca6
KH
1230 ret = __isolate_lru_page(page, mode, file);
1231 switch (ret) {
1232 case 0:
66e1707b 1233 list_move(&page->lru, dst);
2ffebca6 1234 mem_cgroup_del_lru(page);
2c888cfb 1235 nr_taken += hpage_nr_pages(page);
2ffebca6
KH
1236 break;
1237 case -EBUSY:
1238 /* we don't affect global LRU but rotate in our LRU */
1239 mem_cgroup_rotate_lru_list(page, page_lru(page));
1240 break;
1241 default:
1242 break;
66e1707b
BS
1243 }
1244 }
1245
66e1707b 1246 *scanned = scan;
cc8e970c
KM
1247
1248 trace_mm_vmscan_memcg_isolate(0, nr_to_scan, scan, nr_taken,
1249 0, 0, 0, mode);
1250
66e1707b
BS
1251 return nr_taken;
1252}
1253
6d61ef40
BS
1254#define mem_cgroup_from_res_counter(counter, member) \
1255 container_of(counter, struct mem_cgroup, member)
1256
19942822 1257/**
9d11ea9f
JW
1258 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1259 * @mem: the memory cgroup
19942822 1260 *
9d11ea9f 1261 * Returns the maximum amount of memory @mem can be charged with, in
7ec99d62 1262 * pages.
19942822 1263 */
c0ff4b85 1264static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
19942822 1265{
9d11ea9f
JW
1266 unsigned long long margin;
1267
c0ff4b85 1268 margin = res_counter_margin(&memcg->res);
9d11ea9f 1269 if (do_swap_account)
c0ff4b85 1270 margin = min(margin, res_counter_margin(&memcg->memsw));
7ec99d62 1271 return margin >> PAGE_SHIFT;
19942822
JW
1272}
1273
1f4c025b 1274int mem_cgroup_swappiness(struct mem_cgroup *memcg)
a7885eb8
KM
1275{
1276 struct cgroup *cgrp = memcg->css.cgroup;
a7885eb8
KM
1277
1278 /* root ? */
1279 if (cgrp->parent == NULL)
1280 return vm_swappiness;
1281
bf1ff263 1282 return memcg->swappiness;
a7885eb8
KM
1283}
1284
c0ff4b85 1285static void mem_cgroup_start_move(struct mem_cgroup *memcg)
32047e2a
KH
1286{
1287 int cpu;
1489ebad
KH
1288
1289 get_online_cpus();
c0ff4b85 1290 spin_lock(&memcg->pcp_counter_lock);
1489ebad 1291 for_each_online_cpu(cpu)
c0ff4b85
R
1292 per_cpu(memcg->stat->count[MEM_CGROUP_ON_MOVE], cpu) += 1;
1293 memcg->nocpu_base.count[MEM_CGROUP_ON_MOVE] += 1;
1294 spin_unlock(&memcg->pcp_counter_lock);
1489ebad 1295 put_online_cpus();
32047e2a
KH
1296
1297 synchronize_rcu();
1298}
1299
c0ff4b85 1300static void mem_cgroup_end_move(struct mem_cgroup *memcg)
32047e2a
KH
1301{
1302 int cpu;
1303
c0ff4b85 1304 if (!memcg)
32047e2a 1305 return;
1489ebad 1306 get_online_cpus();
c0ff4b85 1307 spin_lock(&memcg->pcp_counter_lock);
1489ebad 1308 for_each_online_cpu(cpu)
c0ff4b85
R
1309 per_cpu(memcg->stat->count[MEM_CGROUP_ON_MOVE], cpu) -= 1;
1310 memcg->nocpu_base.count[MEM_CGROUP_ON_MOVE] -= 1;
1311 spin_unlock(&memcg->pcp_counter_lock);
1489ebad 1312 put_online_cpus();
32047e2a
KH
1313}
1314/*
1315 * 2 routines for checking "mem" is under move_account() or not.
1316 *
1317 * mem_cgroup_stealed() - checking a cgroup is mc.from or not. This is used
1318 * for avoiding race in accounting. If true,
1319 * pc->mem_cgroup may be overwritten.
1320 *
1321 * mem_cgroup_under_move() - checking a cgroup is mc.from or mc.to or
1322 * under hierarchy of moving cgroups. This is for
1323 * waiting at hith-memory prressure caused by "move".
1324 */
1325
c0ff4b85 1326static bool mem_cgroup_stealed(struct mem_cgroup *memcg)
32047e2a
KH
1327{
1328 VM_BUG_ON(!rcu_read_lock_held());
c0ff4b85 1329 return this_cpu_read(memcg->stat->count[MEM_CGROUP_ON_MOVE]) > 0;
32047e2a 1330}
4b534334 1331
c0ff4b85 1332static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
4b534334 1333{
2bd9bb20
KH
1334 struct mem_cgroup *from;
1335 struct mem_cgroup *to;
4b534334 1336 bool ret = false;
2bd9bb20
KH
1337 /*
1338 * Unlike task_move routines, we access mc.to, mc.from not under
1339 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1340 */
1341 spin_lock(&mc.lock);
1342 from = mc.from;
1343 to = mc.to;
1344 if (!from)
1345 goto unlock;
3e92041d 1346
c0ff4b85
R
1347 ret = mem_cgroup_same_or_subtree(memcg, from)
1348 || mem_cgroup_same_or_subtree(memcg, to);
2bd9bb20
KH
1349unlock:
1350 spin_unlock(&mc.lock);
4b534334
KH
1351 return ret;
1352}
1353
c0ff4b85 1354static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
4b534334
KH
1355{
1356 if (mc.moving_task && current != mc.moving_task) {
c0ff4b85 1357 if (mem_cgroup_under_move(memcg)) {
4b534334
KH
1358 DEFINE_WAIT(wait);
1359 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1360 /* moving charge context might have finished. */
1361 if (mc.moving_task)
1362 schedule();
1363 finish_wait(&mc.waitq, &wait);
1364 return true;
1365 }
1366 }
1367 return false;
1368}
1369
e222432b 1370/**
6a6135b6 1371 * mem_cgroup_print_oom_info: Called from OOM with tasklist_lock held in read mode.
e222432b
BS
1372 * @memcg: The memory cgroup that went over limit
1373 * @p: Task that is going to be killed
1374 *
1375 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1376 * enabled
1377 */
1378void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1379{
1380 struct cgroup *task_cgrp;
1381 struct cgroup *mem_cgrp;
1382 /*
1383 * Need a buffer in BSS, can't rely on allocations. The code relies
1384 * on the assumption that OOM is serialized for memory controller.
1385 * If this assumption is broken, revisit this code.
1386 */
1387 static char memcg_name[PATH_MAX];
1388 int ret;
1389
d31f56db 1390 if (!memcg || !p)
e222432b
BS
1391 return;
1392
1393
1394 rcu_read_lock();
1395
1396 mem_cgrp = memcg->css.cgroup;
1397 task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
1398
1399 ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
1400 if (ret < 0) {
1401 /*
1402 * Unfortunately, we are unable to convert to a useful name
1403 * But we'll still print out the usage information
1404 */
1405 rcu_read_unlock();
1406 goto done;
1407 }
1408 rcu_read_unlock();
1409
1410 printk(KERN_INFO "Task in %s killed", memcg_name);
1411
1412 rcu_read_lock();
1413 ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
1414 if (ret < 0) {
1415 rcu_read_unlock();
1416 goto done;
1417 }
1418 rcu_read_unlock();
1419
1420 /*
1421 * Continues from above, so we don't need an KERN_ level
1422 */
1423 printk(KERN_CONT " as a result of limit of %s\n", memcg_name);
1424done:
1425
1426 printk(KERN_INFO "memory: usage %llukB, limit %llukB, failcnt %llu\n",
1427 res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
1428 res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
1429 res_counter_read_u64(&memcg->res, RES_FAILCNT));
1430 printk(KERN_INFO "memory+swap: usage %llukB, limit %llukB, "
1431 "failcnt %llu\n",
1432 res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
1433 res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
1434 res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
1435}
1436
81d39c20
KH
1437/*
1438 * This function returns the number of memcg under hierarchy tree. Returns
1439 * 1(self count) if no children.
1440 */
c0ff4b85 1441static int mem_cgroup_count_children(struct mem_cgroup *memcg)
81d39c20
KH
1442{
1443 int num = 0;
7d74b06f
KH
1444 struct mem_cgroup *iter;
1445
c0ff4b85 1446 for_each_mem_cgroup_tree(iter, memcg)
7d74b06f 1447 num++;
81d39c20
KH
1448 return num;
1449}
1450
a63d83f4
DR
1451/*
1452 * Return the memory (and swap, if configured) limit for a memcg.
1453 */
1454u64 mem_cgroup_get_limit(struct mem_cgroup *memcg)
1455{
1456 u64 limit;
1457 u64 memsw;
1458
f3e8eb70
JW
1459 limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
1460 limit += total_swap_pages << PAGE_SHIFT;
1461
a63d83f4
DR
1462 memsw = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
1463 /*
1464 * If memsw is finite and limits the amount of swap space available
1465 * to this memcg, return that limit.
1466 */
1467 return min(limit, memsw);
1468}
1469
6d61ef40 1470/*
04046e1a
KH
1471 * Visit the first child (need not be the first child as per the ordering
1472 * of the cgroup list, since we track last_scanned_child) of @mem and use
1473 * that to reclaim free pages from.
1474 */
1475static struct mem_cgroup *
c0ff4b85 1476mem_cgroup_select_victim(struct mem_cgroup *root_memcg)
04046e1a
KH
1477{
1478 struct mem_cgroup *ret = NULL;
1479 struct cgroup_subsys_state *css;
1480 int nextid, found;
1481
c0ff4b85
R
1482 if (!root_memcg->use_hierarchy) {
1483 css_get(&root_memcg->css);
1484 ret = root_memcg;
04046e1a
KH
1485 }
1486
1487 while (!ret) {
1488 rcu_read_lock();
c0ff4b85
R
1489 nextid = root_memcg->last_scanned_child + 1;
1490 css = css_get_next(&mem_cgroup_subsys, nextid, &root_memcg->css,
04046e1a
KH
1491 &found);
1492 if (css && css_tryget(css))
1493 ret = container_of(css, struct mem_cgroup, css);
1494
1495 rcu_read_unlock();
1496 /* Updates scanning parameter */
04046e1a
KH
1497 if (!css) {
1498 /* this means start scan from ID:1 */
c0ff4b85 1499 root_memcg->last_scanned_child = 0;
04046e1a 1500 } else
c0ff4b85 1501 root_memcg->last_scanned_child = found;
04046e1a
KH
1502 }
1503
1504 return ret;
1505}
1506
4d0c066d
KH
1507/**
1508 * test_mem_cgroup_node_reclaimable
1509 * @mem: the target memcg
1510 * @nid: the node ID to be checked.
1511 * @noswap : specify true here if the user wants flle only information.
1512 *
1513 * This function returns whether the specified memcg contains any
1514 * reclaimable pages on a node. Returns true if there are any reclaimable
1515 * pages in the node.
1516 */
c0ff4b85 1517static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *memcg,
4d0c066d
KH
1518 int nid, bool noswap)
1519{
c0ff4b85 1520 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_FILE))
4d0c066d
KH
1521 return true;
1522 if (noswap || !total_swap_pages)
1523 return false;
c0ff4b85 1524 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_ANON))
4d0c066d
KH
1525 return true;
1526 return false;
1527
1528}
889976db
YH
1529#if MAX_NUMNODES > 1
1530
1531/*
1532 * Always updating the nodemask is not very good - even if we have an empty
1533 * list or the wrong list here, we can start from some node and traverse all
1534 * nodes based on the zonelist. So update the list loosely once per 10 secs.
1535 *
1536 */
c0ff4b85 1537static void mem_cgroup_may_update_nodemask(struct mem_cgroup *memcg)
889976db
YH
1538{
1539 int nid;
453a9bf3
KH
1540 /*
1541 * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
1542 * pagein/pageout changes since the last update.
1543 */
c0ff4b85 1544 if (!atomic_read(&memcg->numainfo_events))
453a9bf3 1545 return;
c0ff4b85 1546 if (atomic_inc_return(&memcg->numainfo_updating) > 1)
889976db
YH
1547 return;
1548
889976db 1549 /* make a nodemask where this memcg uses memory from */
c0ff4b85 1550 memcg->scan_nodes = node_states[N_HIGH_MEMORY];
889976db
YH
1551
1552 for_each_node_mask(nid, node_states[N_HIGH_MEMORY]) {
1553
c0ff4b85
R
1554 if (!test_mem_cgroup_node_reclaimable(memcg, nid, false))
1555 node_clear(nid, memcg->scan_nodes);
889976db 1556 }
453a9bf3 1557
c0ff4b85
R
1558 atomic_set(&memcg->numainfo_events, 0);
1559 atomic_set(&memcg->numainfo_updating, 0);
889976db
YH
1560}
1561
1562/*
1563 * Selecting a node where we start reclaim from. Because what we need is just
1564 * reducing usage counter, start from anywhere is O,K. Considering
1565 * memory reclaim from current node, there are pros. and cons.
1566 *
1567 * Freeing memory from current node means freeing memory from a node which
1568 * we'll use or we've used. So, it may make LRU bad. And if several threads
1569 * hit limits, it will see a contention on a node. But freeing from remote
1570 * node means more costs for memory reclaim because of memory latency.
1571 *
1572 * Now, we use round-robin. Better algorithm is welcomed.
1573 */
c0ff4b85 1574int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
889976db
YH
1575{
1576 int node;
1577
c0ff4b85
R
1578 mem_cgroup_may_update_nodemask(memcg);
1579 node = memcg->last_scanned_node;
889976db 1580
c0ff4b85 1581 node = next_node(node, memcg->scan_nodes);
889976db 1582 if (node == MAX_NUMNODES)
c0ff4b85 1583 node = first_node(memcg->scan_nodes);
889976db
YH
1584 /*
1585 * We call this when we hit limit, not when pages are added to LRU.
1586 * No LRU may hold pages because all pages are UNEVICTABLE or
1587 * memcg is too small and all pages are not on LRU. In that case,
1588 * we use curret node.
1589 */
1590 if (unlikely(node == MAX_NUMNODES))
1591 node = numa_node_id();
1592
c0ff4b85 1593 memcg->last_scanned_node = node;
889976db
YH
1594 return node;
1595}
1596
4d0c066d
KH
1597/*
1598 * Check all nodes whether it contains reclaimable pages or not.
1599 * For quick scan, we make use of scan_nodes. This will allow us to skip
1600 * unused nodes. But scan_nodes is lazily updated and may not cotain
1601 * enough new information. We need to do double check.
1602 */
c0ff4b85 1603bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
4d0c066d
KH
1604{
1605 int nid;
1606
1607 /*
1608 * quick check...making use of scan_node.
1609 * We can skip unused nodes.
1610 */
c0ff4b85
R
1611 if (!nodes_empty(memcg->scan_nodes)) {
1612 for (nid = first_node(memcg->scan_nodes);
4d0c066d 1613 nid < MAX_NUMNODES;
c0ff4b85 1614 nid = next_node(nid, memcg->scan_nodes)) {
4d0c066d 1615
c0ff4b85 1616 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
4d0c066d
KH
1617 return true;
1618 }
1619 }
1620 /*
1621 * Check rest of nodes.
1622 */
1623 for_each_node_state(nid, N_HIGH_MEMORY) {
c0ff4b85 1624 if (node_isset(nid, memcg->scan_nodes))
4d0c066d 1625 continue;
c0ff4b85 1626 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
4d0c066d
KH
1627 return true;
1628 }
1629 return false;
1630}
1631
889976db 1632#else
c0ff4b85 1633int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
889976db
YH
1634{
1635 return 0;
1636}
4d0c066d 1637
c0ff4b85 1638bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
4d0c066d 1639{
c0ff4b85 1640 return test_mem_cgroup_node_reclaimable(memcg, 0, noswap);
4d0c066d 1641}
889976db
YH
1642#endif
1643
04046e1a
KH
1644/*
1645 * Scan the hierarchy if needed to reclaim memory. We remember the last child
1646 * we reclaimed from, so that we don't end up penalizing one child extensively
1647 * based on its position in the children list.
6d61ef40 1648 *
c0ff4b85 1649 * root_memcg is the original ancestor that we've been reclaim from.
04046e1a 1650 *
c0ff4b85 1651 * We give up and return to the caller when we visit root_memcg twice.
04046e1a 1652 * (other groups can be removed while we're walking....)
81d39c20
KH
1653 *
1654 * If shrink==true, for avoiding to free too much, this returns immedieately.
6d61ef40 1655 */
c0ff4b85 1656static int mem_cgroup_hierarchical_reclaim(struct mem_cgroup *root_memcg,
4e416953 1657 struct zone *zone,
75822b44 1658 gfp_t gfp_mask,
0ae5e89c
YH
1659 unsigned long reclaim_options,
1660 unsigned long *total_scanned)
6d61ef40 1661{
04046e1a
KH
1662 struct mem_cgroup *victim;
1663 int ret, total = 0;
1664 int loop = 0;
75822b44
BS
1665 bool noswap = reclaim_options & MEM_CGROUP_RECLAIM_NOSWAP;
1666 bool shrink = reclaim_options & MEM_CGROUP_RECLAIM_SHRINK;
4e416953 1667 bool check_soft = reclaim_options & MEM_CGROUP_RECLAIM_SOFT;
9d11ea9f 1668 unsigned long excess;
185efc0f 1669 unsigned long nr_scanned;
9d11ea9f 1670
c0ff4b85 1671 excess = res_counter_soft_limit_excess(&root_memcg->res) >> PAGE_SHIFT;
04046e1a 1672
22a668d7 1673 /* If memsw_is_minimum==1, swap-out is of-no-use. */
c0ff4b85 1674 if (!check_soft && !shrink && root_memcg->memsw_is_minimum)
22a668d7
KH
1675 noswap = true;
1676
4e416953 1677 while (1) {
c0ff4b85
R
1678 victim = mem_cgroup_select_victim(root_memcg);
1679 if (victim == root_memcg) {
04046e1a 1680 loop++;
fbc29a25
KH
1681 /*
1682 * We are not draining per cpu cached charges during
1683 * soft limit reclaim because global reclaim doesn't
1684 * care about charges. It tries to free some memory and
1685 * charges will not give any.
1686 */
1687 if (!check_soft && loop >= 1)
c0ff4b85 1688 drain_all_stock_async(root_memcg);
4e416953
BS
1689 if (loop >= 2) {
1690 /*
1691 * If we have not been able to reclaim
1692 * anything, it might because there are
1693 * no reclaimable pages under this hierarchy
1694 */
1695 if (!check_soft || !total) {
1696 css_put(&victim->css);
1697 break;
1698 }
1699 /*
25985edc 1700 * We want to do more targeted reclaim.
4e416953
BS
1701 * excess >> 2 is not to excessive so as to
1702 * reclaim too much, nor too less that we keep
1703 * coming back to reclaim from this cgroup
1704 */
1705 if (total >= (excess >> 2) ||
1706 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS)) {
1707 css_put(&victim->css);
1708 break;
1709 }
1710 }
1711 }
4d0c066d 1712 if (!mem_cgroup_reclaimable(victim, noswap)) {
04046e1a
KH
1713 /* this cgroup's local usage == 0 */
1714 css_put(&victim->css);
6d61ef40
BS
1715 continue;
1716 }
04046e1a 1717 /* we use swappiness of local cgroup */
0ae5e89c 1718 if (check_soft) {
4e416953 1719 ret = mem_cgroup_shrink_node_zone(victim, gfp_mask,
185efc0f
JW
1720 noswap, zone, &nr_scanned);
1721 *total_scanned += nr_scanned;
0ae5e89c 1722 } else
4e416953 1723 ret = try_to_free_mem_cgroup_pages(victim, gfp_mask,
185efc0f 1724 noswap);
04046e1a 1725 css_put(&victim->css);
81d39c20
KH
1726 /*
1727 * At shrinking usage, we can't check we should stop here or
1728 * reclaim more. It's depends on callers. last_scanned_child
1729 * will work enough for keeping fairness under tree.
1730 */
1731 if (shrink)
1732 return ret;
04046e1a 1733 total += ret;
4e416953 1734 if (check_soft) {
c0ff4b85 1735 if (!res_counter_soft_limit_excess(&root_memcg->res))
4e416953 1736 return total;
c0ff4b85 1737 } else if (mem_cgroup_margin(root_memcg))
4fd14ebf 1738 return total;
6d61ef40 1739 }
04046e1a 1740 return total;
6d61ef40
BS
1741}
1742
867578cb
KH
1743/*
1744 * Check OOM-Killer is already running under our hierarchy.
1745 * If someone is running, return false.
1af8efe9 1746 * Has to be called with memcg_oom_lock
867578cb 1747 */
c0ff4b85 1748static bool mem_cgroup_oom_lock(struct mem_cgroup *memcg)
867578cb 1749{
79dfdacc
MH
1750 struct mem_cgroup *iter, *failed = NULL;
1751 bool cond = true;
a636b327 1752
c0ff4b85 1753 for_each_mem_cgroup_tree_cond(iter, memcg, cond) {
23751be0 1754 if (iter->oom_lock) {
79dfdacc
MH
1755 /*
1756 * this subtree of our hierarchy is already locked
1757 * so we cannot give a lock.
1758 */
79dfdacc
MH
1759 failed = iter;
1760 cond = false;
23751be0
JW
1761 } else
1762 iter->oom_lock = true;
7d74b06f 1763 }
867578cb 1764
79dfdacc 1765 if (!failed)
23751be0 1766 return true;
79dfdacc
MH
1767
1768 /*
1769 * OK, we failed to lock the whole subtree so we have to clean up
1770 * what we set up to the failing subtree
1771 */
1772 cond = true;
c0ff4b85 1773 for_each_mem_cgroup_tree_cond(iter, memcg, cond) {
79dfdacc
MH
1774 if (iter == failed) {
1775 cond = false;
1776 continue;
1777 }
1778 iter->oom_lock = false;
1779 }
23751be0 1780 return false;
a636b327 1781}
0b7f569e 1782
79dfdacc 1783/*
1af8efe9 1784 * Has to be called with memcg_oom_lock
79dfdacc 1785 */
c0ff4b85 1786static int mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
0b7f569e 1787{
7d74b06f
KH
1788 struct mem_cgroup *iter;
1789
c0ff4b85 1790 for_each_mem_cgroup_tree(iter, memcg)
79dfdacc
MH
1791 iter->oom_lock = false;
1792 return 0;
1793}
1794
c0ff4b85 1795static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
79dfdacc
MH
1796{
1797 struct mem_cgroup *iter;
1798
c0ff4b85 1799 for_each_mem_cgroup_tree(iter, memcg)
79dfdacc
MH
1800 atomic_inc(&iter->under_oom);
1801}
1802
c0ff4b85 1803static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
79dfdacc
MH
1804{
1805 struct mem_cgroup *iter;
1806
867578cb
KH
1807 /*
1808 * When a new child is created while the hierarchy is under oom,
1809 * mem_cgroup_oom_lock() may not be called. We have to use
1810 * atomic_add_unless() here.
1811 */
c0ff4b85 1812 for_each_mem_cgroup_tree(iter, memcg)
79dfdacc 1813 atomic_add_unless(&iter->under_oom, -1, 0);
0b7f569e
KH
1814}
1815
1af8efe9 1816static DEFINE_SPINLOCK(memcg_oom_lock);
867578cb
KH
1817static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1818
dc98df5a
KH
1819struct oom_wait_info {
1820 struct mem_cgroup *mem;
1821 wait_queue_t wait;
1822};
1823
1824static int memcg_oom_wake_function(wait_queue_t *wait,
1825 unsigned mode, int sync, void *arg)
1826{
c0ff4b85
R
1827 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg,
1828 *oom_wait_memcg;
dc98df5a
KH
1829 struct oom_wait_info *oom_wait_info;
1830
1831 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
c0ff4b85 1832 oom_wait_memcg = oom_wait_info->mem;
dc98df5a 1833
dc98df5a
KH
1834 /*
1835 * Both of oom_wait_info->mem and wake_mem are stable under us.
1836 * Then we can use css_is_ancestor without taking care of RCU.
1837 */
c0ff4b85
R
1838 if (!mem_cgroup_same_or_subtree(oom_wait_memcg, wake_memcg)
1839 && !mem_cgroup_same_or_subtree(wake_memcg, oom_wait_memcg))
dc98df5a 1840 return 0;
dc98df5a
KH
1841 return autoremove_wake_function(wait, mode, sync, arg);
1842}
1843
c0ff4b85 1844static void memcg_wakeup_oom(struct mem_cgroup *memcg)
dc98df5a 1845{
c0ff4b85
R
1846 /* for filtering, pass "memcg" as argument. */
1847 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
dc98df5a
KH
1848}
1849
c0ff4b85 1850static void memcg_oom_recover(struct mem_cgroup *memcg)
3c11ecf4 1851{
c0ff4b85
R
1852 if (memcg && atomic_read(&memcg->under_oom))
1853 memcg_wakeup_oom(memcg);
3c11ecf4
KH
1854}
1855
867578cb
KH
1856/*
1857 * try to call OOM killer. returns false if we should exit memory-reclaim loop.
1858 */
c0ff4b85 1859bool mem_cgroup_handle_oom(struct mem_cgroup *memcg, gfp_t mask)
0b7f569e 1860{
dc98df5a 1861 struct oom_wait_info owait;
3c11ecf4 1862 bool locked, need_to_kill;
867578cb 1863
c0ff4b85 1864 owait.mem = memcg;
dc98df5a
KH
1865 owait.wait.flags = 0;
1866 owait.wait.func = memcg_oom_wake_function;
1867 owait.wait.private = current;
1868 INIT_LIST_HEAD(&owait.wait.task_list);
3c11ecf4 1869 need_to_kill = true;
c0ff4b85 1870 mem_cgroup_mark_under_oom(memcg);
79dfdacc 1871
c0ff4b85 1872 /* At first, try to OOM lock hierarchy under memcg.*/
1af8efe9 1873 spin_lock(&memcg_oom_lock);
c0ff4b85 1874 locked = mem_cgroup_oom_lock(memcg);
867578cb
KH
1875 /*
1876 * Even if signal_pending(), we can't quit charge() loop without
1877 * accounting. So, UNINTERRUPTIBLE is appropriate. But SIGKILL
1878 * under OOM is always welcomed, use TASK_KILLABLE here.
1879 */
3c11ecf4 1880 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
c0ff4b85 1881 if (!locked || memcg->oom_kill_disable)
3c11ecf4
KH
1882 need_to_kill = false;
1883 if (locked)
c0ff4b85 1884 mem_cgroup_oom_notify(memcg);
1af8efe9 1885 spin_unlock(&memcg_oom_lock);
867578cb 1886
3c11ecf4
KH
1887 if (need_to_kill) {
1888 finish_wait(&memcg_oom_waitq, &owait.wait);
c0ff4b85 1889 mem_cgroup_out_of_memory(memcg, mask);
3c11ecf4 1890 } else {
867578cb 1891 schedule();
dc98df5a 1892 finish_wait(&memcg_oom_waitq, &owait.wait);
867578cb 1893 }
1af8efe9 1894 spin_lock(&memcg_oom_lock);
79dfdacc 1895 if (locked)
c0ff4b85
R
1896 mem_cgroup_oom_unlock(memcg);
1897 memcg_wakeup_oom(memcg);
1af8efe9 1898 spin_unlock(&memcg_oom_lock);
867578cb 1899
c0ff4b85 1900 mem_cgroup_unmark_under_oom(memcg);
79dfdacc 1901
867578cb
KH
1902 if (test_thread_flag(TIF_MEMDIE) || fatal_signal_pending(current))
1903 return false;
1904 /* Give chance to dying process */
715a5ee8 1905 schedule_timeout_uninterruptible(1);
867578cb 1906 return true;
0b7f569e
KH
1907}
1908
d69b042f
BS
1909/*
1910 * Currently used to update mapped file statistics, but the routine can be
1911 * generalized to update other statistics as well.
32047e2a
KH
1912 *
1913 * Notes: Race condition
1914 *
1915 * We usually use page_cgroup_lock() for accessing page_cgroup member but
1916 * it tends to be costly. But considering some conditions, we doesn't need
1917 * to do so _always_.
1918 *
1919 * Considering "charge", lock_page_cgroup() is not required because all
1920 * file-stat operations happen after a page is attached to radix-tree. There
1921 * are no race with "charge".
1922 *
1923 * Considering "uncharge", we know that memcg doesn't clear pc->mem_cgroup
1924 * at "uncharge" intentionally. So, we always see valid pc->mem_cgroup even
1925 * if there are race with "uncharge". Statistics itself is properly handled
1926 * by flags.
1927 *
1928 * Considering "move", this is an only case we see a race. To make the race
1929 * small, we check MEM_CGROUP_ON_MOVE percpu value and detect there are
1930 * possibility of race condition. If there is, we take a lock.
d69b042f 1931 */
26174efd 1932
2a7106f2
GT
1933void mem_cgroup_update_page_stat(struct page *page,
1934 enum mem_cgroup_page_stat_item idx, int val)
d69b042f 1935{
c0ff4b85 1936 struct mem_cgroup *memcg;
32047e2a
KH
1937 struct page_cgroup *pc = lookup_page_cgroup(page);
1938 bool need_unlock = false;
dbd4ea78 1939 unsigned long uninitialized_var(flags);
d69b042f 1940
d69b042f
BS
1941 if (unlikely(!pc))
1942 return;
1943
32047e2a 1944 rcu_read_lock();
c0ff4b85
R
1945 memcg = pc->mem_cgroup;
1946 if (unlikely(!memcg || !PageCgroupUsed(pc)))
32047e2a
KH
1947 goto out;
1948 /* pc->mem_cgroup is unstable ? */
c0ff4b85 1949 if (unlikely(mem_cgroup_stealed(memcg)) || PageTransHuge(page)) {
32047e2a 1950 /* take a lock against to access pc->mem_cgroup */
dbd4ea78 1951 move_lock_page_cgroup(pc, &flags);
32047e2a 1952 need_unlock = true;
c0ff4b85
R
1953 memcg = pc->mem_cgroup;
1954 if (!memcg || !PageCgroupUsed(pc))
32047e2a
KH
1955 goto out;
1956 }
26174efd 1957
26174efd 1958 switch (idx) {
2a7106f2 1959 case MEMCG_NR_FILE_MAPPED:
26174efd
KH
1960 if (val > 0)
1961 SetPageCgroupFileMapped(pc);
1962 else if (!page_mapped(page))
0c270f8f 1963 ClearPageCgroupFileMapped(pc);
2a7106f2 1964 idx = MEM_CGROUP_STAT_FILE_MAPPED;
26174efd
KH
1965 break;
1966 default:
1967 BUG();
8725d541 1968 }
d69b042f 1969
c0ff4b85 1970 this_cpu_add(memcg->stat->count[idx], val);
2a7106f2 1971
32047e2a
KH
1972out:
1973 if (unlikely(need_unlock))
dbd4ea78 1974 move_unlock_page_cgroup(pc, &flags);
32047e2a
KH
1975 rcu_read_unlock();
1976 return;
d69b042f 1977}
2a7106f2 1978EXPORT_SYMBOL(mem_cgroup_update_page_stat);
26174efd 1979
cdec2e42
KH
1980/*
1981 * size of first charge trial. "32" comes from vmscan.c's magic value.
1982 * TODO: maybe necessary to use big numbers in big irons.
1983 */
7ec99d62 1984#define CHARGE_BATCH 32U
cdec2e42
KH
1985struct memcg_stock_pcp {
1986 struct mem_cgroup *cached; /* this never be root cgroup */
11c9ea4e 1987 unsigned int nr_pages;
cdec2e42 1988 struct work_struct work;
26fe6168
KH
1989 unsigned long flags;
1990#define FLUSHING_CACHED_CHARGE (0)
cdec2e42
KH
1991};
1992static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
9f50fad6 1993static DEFINE_MUTEX(percpu_charge_mutex);
cdec2e42
KH
1994
1995/*
11c9ea4e 1996 * Try to consume stocked charge on this cpu. If success, one page is consumed
cdec2e42
KH
1997 * from local stock and true is returned. If the stock is 0 or charges from a
1998 * cgroup which is not current target, returns false. This stock will be
1999 * refilled.
2000 */
c0ff4b85 2001static bool consume_stock(struct mem_cgroup *memcg)
cdec2e42
KH
2002{
2003 struct memcg_stock_pcp *stock;
2004 bool ret = true;
2005
2006 stock = &get_cpu_var(memcg_stock);
c0ff4b85 2007 if (memcg == stock->cached && stock->nr_pages)
11c9ea4e 2008 stock->nr_pages--;
cdec2e42
KH
2009 else /* need to call res_counter_charge */
2010 ret = false;
2011 put_cpu_var(memcg_stock);
2012 return ret;
2013}
2014
2015/*
2016 * Returns stocks cached in percpu to res_counter and reset cached information.
2017 */
2018static void drain_stock(struct memcg_stock_pcp *stock)
2019{
2020 struct mem_cgroup *old = stock->cached;
2021
11c9ea4e
JW
2022 if (stock->nr_pages) {
2023 unsigned long bytes = stock->nr_pages * PAGE_SIZE;
2024
2025 res_counter_uncharge(&old->res, bytes);
cdec2e42 2026 if (do_swap_account)
11c9ea4e
JW
2027 res_counter_uncharge(&old->memsw, bytes);
2028 stock->nr_pages = 0;
cdec2e42
KH
2029 }
2030 stock->cached = NULL;
cdec2e42
KH
2031}
2032
2033/*
2034 * This must be called under preempt disabled or must be called by
2035 * a thread which is pinned to local cpu.
2036 */
2037static void drain_local_stock(struct work_struct *dummy)
2038{
2039 struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
2040 drain_stock(stock);
26fe6168 2041 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
cdec2e42
KH
2042}
2043
2044/*
2045 * Cache charges(val) which is from res_counter, to local per_cpu area.
320cc51d 2046 * This will be consumed by consume_stock() function, later.
cdec2e42 2047 */
c0ff4b85 2048static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
cdec2e42
KH
2049{
2050 struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
2051
c0ff4b85 2052 if (stock->cached != memcg) { /* reset if necessary */
cdec2e42 2053 drain_stock(stock);
c0ff4b85 2054 stock->cached = memcg;
cdec2e42 2055 }
11c9ea4e 2056 stock->nr_pages += nr_pages;
cdec2e42
KH
2057 put_cpu_var(memcg_stock);
2058}
2059
2060/*
c0ff4b85 2061 * Drains all per-CPU charge caches for given root_memcg resp. subtree
d38144b7
MH
2062 * of the hierarchy under it. sync flag says whether we should block
2063 * until the work is done.
cdec2e42 2064 */
c0ff4b85 2065static void drain_all_stock(struct mem_cgroup *root_memcg, bool sync)
cdec2e42 2066{
26fe6168 2067 int cpu, curcpu;
d38144b7 2068
cdec2e42 2069 /* Notify other cpus that system-wide "drain" is running */
cdec2e42 2070 get_online_cpus();
5af12d0e 2071 curcpu = get_cpu();
cdec2e42
KH
2072 for_each_online_cpu(cpu) {
2073 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
c0ff4b85 2074 struct mem_cgroup *memcg;
26fe6168 2075
c0ff4b85
R
2076 memcg = stock->cached;
2077 if (!memcg || !stock->nr_pages)
26fe6168 2078 continue;
c0ff4b85 2079 if (!mem_cgroup_same_or_subtree(root_memcg, memcg))
3e92041d 2080 continue;
d1a05b69
MH
2081 if (!test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2082 if (cpu == curcpu)
2083 drain_local_stock(&stock->work);
2084 else
2085 schedule_work_on(cpu, &stock->work);
2086 }
cdec2e42 2087 }
5af12d0e 2088 put_cpu();
d38144b7
MH
2089
2090 if (!sync)
2091 goto out;
2092
2093 for_each_online_cpu(cpu) {
2094 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
9f50fad6 2095 if (test_bit(FLUSHING_CACHED_CHARGE, &stock->flags))
d38144b7
MH
2096 flush_work(&stock->work);
2097 }
2098out:
cdec2e42 2099 put_online_cpus();
d38144b7
MH
2100}
2101
2102/*
2103 * Tries to drain stocked charges in other cpus. This function is asynchronous
2104 * and just put a work per cpu for draining localy on each cpu. Caller can
2105 * expects some charges will be back to res_counter later but cannot wait for
2106 * it.
2107 */
c0ff4b85 2108static void drain_all_stock_async(struct mem_cgroup *root_memcg)
d38144b7 2109{
9f50fad6
MH
2110 /*
2111 * If someone calls draining, avoid adding more kworker runs.
2112 */
2113 if (!mutex_trylock(&percpu_charge_mutex))
2114 return;
c0ff4b85 2115 drain_all_stock(root_memcg, false);
9f50fad6 2116 mutex_unlock(&percpu_charge_mutex);
cdec2e42
KH
2117}
2118
2119/* This is a synchronous drain interface. */
c0ff4b85 2120static void drain_all_stock_sync(struct mem_cgroup *root_memcg)
cdec2e42
KH
2121{
2122 /* called when force_empty is called */
9f50fad6 2123 mutex_lock(&percpu_charge_mutex);
c0ff4b85 2124 drain_all_stock(root_memcg, true);
9f50fad6 2125 mutex_unlock(&percpu_charge_mutex);
cdec2e42
KH
2126}
2127
711d3d2c
KH
2128/*
2129 * This function drains percpu counter value from DEAD cpu and
2130 * move it to local cpu. Note that this function can be preempted.
2131 */
c0ff4b85 2132static void mem_cgroup_drain_pcp_counter(struct mem_cgroup *memcg, int cpu)
711d3d2c
KH
2133{
2134 int i;
2135
c0ff4b85 2136 spin_lock(&memcg->pcp_counter_lock);
711d3d2c 2137 for (i = 0; i < MEM_CGROUP_STAT_DATA; i++) {
c0ff4b85 2138 long x = per_cpu(memcg->stat->count[i], cpu);
711d3d2c 2139
c0ff4b85
R
2140 per_cpu(memcg->stat->count[i], cpu) = 0;
2141 memcg->nocpu_base.count[i] += x;
711d3d2c 2142 }
e9f8974f 2143 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
c0ff4b85 2144 unsigned long x = per_cpu(memcg->stat->events[i], cpu);
e9f8974f 2145
c0ff4b85
R
2146 per_cpu(memcg->stat->events[i], cpu) = 0;
2147 memcg->nocpu_base.events[i] += x;
e9f8974f 2148 }
1489ebad 2149 /* need to clear ON_MOVE value, works as a kind of lock. */
c0ff4b85
R
2150 per_cpu(memcg->stat->count[MEM_CGROUP_ON_MOVE], cpu) = 0;
2151 spin_unlock(&memcg->pcp_counter_lock);
1489ebad
KH
2152}
2153
c0ff4b85 2154static void synchronize_mem_cgroup_on_move(struct mem_cgroup *memcg, int cpu)
1489ebad
KH
2155{
2156 int idx = MEM_CGROUP_ON_MOVE;
2157
c0ff4b85
R
2158 spin_lock(&memcg->pcp_counter_lock);
2159 per_cpu(memcg->stat->count[idx], cpu) = memcg->nocpu_base.count[idx];
2160 spin_unlock(&memcg->pcp_counter_lock);
711d3d2c
KH
2161}
2162
2163static int __cpuinit memcg_cpu_hotplug_callback(struct notifier_block *nb,
cdec2e42
KH
2164 unsigned long action,
2165 void *hcpu)
2166{
2167 int cpu = (unsigned long)hcpu;
2168 struct memcg_stock_pcp *stock;
711d3d2c 2169 struct mem_cgroup *iter;
cdec2e42 2170
1489ebad
KH
2171 if ((action == CPU_ONLINE)) {
2172 for_each_mem_cgroup_all(iter)
2173 synchronize_mem_cgroup_on_move(iter, cpu);
2174 return NOTIFY_OK;
2175 }
2176
711d3d2c 2177 if ((action != CPU_DEAD) || action != CPU_DEAD_FROZEN)
cdec2e42 2178 return NOTIFY_OK;
711d3d2c
KH
2179
2180 for_each_mem_cgroup_all(iter)
2181 mem_cgroup_drain_pcp_counter(iter, cpu);
2182
cdec2e42
KH
2183 stock = &per_cpu(memcg_stock, cpu);
2184 drain_stock(stock);
2185 return NOTIFY_OK;
2186}
2187
4b534334
KH
2188
2189/* See __mem_cgroup_try_charge() for details */
2190enum {
2191 CHARGE_OK, /* success */
2192 CHARGE_RETRY, /* need to retry but retry is not bad */
2193 CHARGE_NOMEM, /* we can't do more. return -ENOMEM */
2194 CHARGE_WOULDBLOCK, /* GFP_WAIT wasn't set and no enough res. */
2195 CHARGE_OOM_DIE, /* the current is killed because of OOM */
2196};
2197
c0ff4b85 2198static int mem_cgroup_do_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
7ec99d62 2199 unsigned int nr_pages, bool oom_check)
4b534334 2200{
7ec99d62 2201 unsigned long csize = nr_pages * PAGE_SIZE;
4b534334
KH
2202 struct mem_cgroup *mem_over_limit;
2203 struct res_counter *fail_res;
2204 unsigned long flags = 0;
2205 int ret;
2206
c0ff4b85 2207 ret = res_counter_charge(&memcg->res, csize, &fail_res);
4b534334
KH
2208
2209 if (likely(!ret)) {
2210 if (!do_swap_account)
2211 return CHARGE_OK;
c0ff4b85 2212 ret = res_counter_charge(&memcg->memsw, csize, &fail_res);
4b534334
KH
2213 if (likely(!ret))
2214 return CHARGE_OK;
2215
c0ff4b85 2216 res_counter_uncharge(&memcg->res, csize);
4b534334
KH
2217 mem_over_limit = mem_cgroup_from_res_counter(fail_res, memsw);
2218 flags |= MEM_CGROUP_RECLAIM_NOSWAP;
2219 } else
2220 mem_over_limit = mem_cgroup_from_res_counter(fail_res, res);
9221edb7 2221 /*
7ec99d62
JW
2222 * nr_pages can be either a huge page (HPAGE_PMD_NR), a batch
2223 * of regular pages (CHARGE_BATCH), or a single regular page (1).
9221edb7
JW
2224 *
2225 * Never reclaim on behalf of optional batching, retry with a
2226 * single page instead.
2227 */
7ec99d62 2228 if (nr_pages == CHARGE_BATCH)
4b534334
KH
2229 return CHARGE_RETRY;
2230
2231 if (!(gfp_mask & __GFP_WAIT))
2232 return CHARGE_WOULDBLOCK;
2233
2234 ret = mem_cgroup_hierarchical_reclaim(mem_over_limit, NULL,
0ae5e89c 2235 gfp_mask, flags, NULL);
7ec99d62 2236 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
19942822 2237 return CHARGE_RETRY;
4b534334 2238 /*
19942822
JW
2239 * Even though the limit is exceeded at this point, reclaim
2240 * may have been able to free some pages. Retry the charge
2241 * before killing the task.
2242 *
2243 * Only for regular pages, though: huge pages are rather
2244 * unlikely to succeed so close to the limit, and we fall back
2245 * to regular pages anyway in case of failure.
4b534334 2246 */
7ec99d62 2247 if (nr_pages == 1 && ret)
4b534334
KH
2248 return CHARGE_RETRY;
2249
2250 /*
2251 * At task move, charge accounts can be doubly counted. So, it's
2252 * better to wait until the end of task_move if something is going on.
2253 */
2254 if (mem_cgroup_wait_acct_move(mem_over_limit))
2255 return CHARGE_RETRY;
2256
2257 /* If we don't need to call oom-killer at el, return immediately */
2258 if (!oom_check)
2259 return CHARGE_NOMEM;
2260 /* check OOM */
2261 if (!mem_cgroup_handle_oom(mem_over_limit, gfp_mask))
2262 return CHARGE_OOM_DIE;
2263
2264 return CHARGE_RETRY;
2265}
2266
f817ed48
KH
2267/*
2268 * Unlike exported interface, "oom" parameter is added. if oom==true,
2269 * oom-killer can be invoked.
8a9f3ccd 2270 */
f817ed48 2271static int __mem_cgroup_try_charge(struct mm_struct *mm,
ec168510 2272 gfp_t gfp_mask,
7ec99d62 2273 unsigned int nr_pages,
c0ff4b85 2274 struct mem_cgroup **ptr,
7ec99d62 2275 bool oom)
8a9f3ccd 2276{
7ec99d62 2277 unsigned int batch = max(CHARGE_BATCH, nr_pages);
4b534334 2278 int nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
c0ff4b85 2279 struct mem_cgroup *memcg = NULL;
4b534334 2280 int ret;
a636b327 2281
867578cb
KH
2282 /*
2283 * Unlike gloval-vm's OOM-kill, we're not in memory shortage
2284 * in system level. So, allow to go ahead dying process in addition to
2285 * MEMDIE process.
2286 */
2287 if (unlikely(test_thread_flag(TIF_MEMDIE)
2288 || fatal_signal_pending(current)))
2289 goto bypass;
a636b327 2290
8a9f3ccd 2291 /*
3be91277
HD
2292 * We always charge the cgroup the mm_struct belongs to.
2293 * The mm_struct's mem_cgroup changes on task migration if the
8a9f3ccd
BS
2294 * thread group leader migrates. It's possible that mm is not
2295 * set, if so charge the init_mm (happens for pagecache usage).
2296 */
c0ff4b85 2297 if (!*ptr && !mm)
f75ca962
KH
2298 goto bypass;
2299again:
c0ff4b85
R
2300 if (*ptr) { /* css should be a valid one */
2301 memcg = *ptr;
2302 VM_BUG_ON(css_is_removed(&memcg->css));
2303 if (mem_cgroup_is_root(memcg))
f75ca962 2304 goto done;
c0ff4b85 2305 if (nr_pages == 1 && consume_stock(memcg))
f75ca962 2306 goto done;
c0ff4b85 2307 css_get(&memcg->css);
4b534334 2308 } else {
f75ca962 2309 struct task_struct *p;
54595fe2 2310
f75ca962
KH
2311 rcu_read_lock();
2312 p = rcu_dereference(mm->owner);
f75ca962 2313 /*
ebb76ce1 2314 * Because we don't have task_lock(), "p" can exit.
c0ff4b85 2315 * In that case, "memcg" can point to root or p can be NULL with
ebb76ce1
KH
2316 * race with swapoff. Then, we have small risk of mis-accouning.
2317 * But such kind of mis-account by race always happens because
2318 * we don't have cgroup_mutex(). It's overkill and we allo that
2319 * small race, here.
2320 * (*) swapoff at el will charge against mm-struct not against
2321 * task-struct. So, mm->owner can be NULL.
f75ca962 2322 */
c0ff4b85
R
2323 memcg = mem_cgroup_from_task(p);
2324 if (!memcg || mem_cgroup_is_root(memcg)) {
f75ca962
KH
2325 rcu_read_unlock();
2326 goto done;
2327 }
c0ff4b85 2328 if (nr_pages == 1 && consume_stock(memcg)) {
f75ca962
KH
2329 /*
2330 * It seems dagerous to access memcg without css_get().
2331 * But considering how consume_stok works, it's not
2332 * necessary. If consume_stock success, some charges
2333 * from this memcg are cached on this cpu. So, we
2334 * don't need to call css_get()/css_tryget() before
2335 * calling consume_stock().
2336 */
2337 rcu_read_unlock();
2338 goto done;
2339 }
2340 /* after here, we may be blocked. we need to get refcnt */
c0ff4b85 2341 if (!css_tryget(&memcg->css)) {
f75ca962
KH
2342 rcu_read_unlock();
2343 goto again;
2344 }
2345 rcu_read_unlock();
2346 }
8a9f3ccd 2347
4b534334
KH
2348 do {
2349 bool oom_check;
7a81b88c 2350
4b534334 2351 /* If killed, bypass charge */
f75ca962 2352 if (fatal_signal_pending(current)) {
c0ff4b85 2353 css_put(&memcg->css);
4b534334 2354 goto bypass;
f75ca962 2355 }
6d61ef40 2356
4b534334
KH
2357 oom_check = false;
2358 if (oom && !nr_oom_retries) {
2359 oom_check = true;
2360 nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
cdec2e42 2361 }
66e1707b 2362
c0ff4b85 2363 ret = mem_cgroup_do_charge(memcg, gfp_mask, batch, oom_check);
4b534334
KH
2364 switch (ret) {
2365 case CHARGE_OK:
2366 break;
2367 case CHARGE_RETRY: /* not in OOM situation but retry */
7ec99d62 2368 batch = nr_pages;
c0ff4b85
R
2369 css_put(&memcg->css);
2370 memcg = NULL;
f75ca962 2371 goto again;
4b534334 2372 case CHARGE_WOULDBLOCK: /* !__GFP_WAIT */
c0ff4b85 2373 css_put(&memcg->css);
4b534334
KH
2374 goto nomem;
2375 case CHARGE_NOMEM: /* OOM routine works */
f75ca962 2376 if (!oom) {
c0ff4b85 2377 css_put(&memcg->css);
867578cb 2378 goto nomem;
f75ca962 2379 }
4b534334
KH
2380 /* If oom, we never return -ENOMEM */
2381 nr_oom_retries--;
2382 break;
2383 case CHARGE_OOM_DIE: /* Killed by OOM Killer */
c0ff4b85 2384 css_put(&memcg->css);
867578cb 2385 goto bypass;
66e1707b 2386 }
4b534334
KH
2387 } while (ret != CHARGE_OK);
2388
7ec99d62 2389 if (batch > nr_pages)
c0ff4b85
R
2390 refill_stock(memcg, batch - nr_pages);
2391 css_put(&memcg->css);
0c3e73e8 2392done:
c0ff4b85 2393 *ptr = memcg;
7a81b88c
KH
2394 return 0;
2395nomem:
c0ff4b85 2396 *ptr = NULL;
7a81b88c 2397 return -ENOMEM;
867578cb 2398bypass:
c0ff4b85 2399 *ptr = NULL;
867578cb 2400 return 0;
7a81b88c 2401}
8a9f3ccd 2402
a3032a2c
DN
2403/*
2404 * Somemtimes we have to undo a charge we got by try_charge().
2405 * This function is for that and do uncharge, put css's refcnt.
2406 * gotten by try_charge().
2407 */
c0ff4b85 2408static void __mem_cgroup_cancel_charge(struct mem_cgroup *memcg,
e7018b8d 2409 unsigned int nr_pages)
a3032a2c 2410{
c0ff4b85 2411 if (!mem_cgroup_is_root(memcg)) {
e7018b8d
JW
2412 unsigned long bytes = nr_pages * PAGE_SIZE;
2413
c0ff4b85 2414 res_counter_uncharge(&memcg->res, bytes);
a3032a2c 2415 if (do_swap_account)
c0ff4b85 2416 res_counter_uncharge(&memcg->memsw, bytes);
a3032a2c 2417 }
854ffa8d
DN
2418}
2419
a3b2d692
KH
2420/*
2421 * A helper function to get mem_cgroup from ID. must be called under
2422 * rcu_read_lock(). The caller must check css_is_removed() or some if
2423 * it's concern. (dropping refcnt from swap can be called against removed
2424 * memcg.)
2425 */
2426static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
2427{
2428 struct cgroup_subsys_state *css;
2429
2430 /* ID 0 is unused ID */
2431 if (!id)
2432 return NULL;
2433 css = css_lookup(&mem_cgroup_subsys, id);
2434 if (!css)
2435 return NULL;
2436 return container_of(css, struct mem_cgroup, css);
2437}
2438
e42d9d5d 2439struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
b5a84319 2440{
c0ff4b85 2441 struct mem_cgroup *memcg = NULL;
3c776e64 2442 struct page_cgroup *pc;
a3b2d692 2443 unsigned short id;
b5a84319
KH
2444 swp_entry_t ent;
2445
3c776e64
DN
2446 VM_BUG_ON(!PageLocked(page));
2447
3c776e64 2448 pc = lookup_page_cgroup(page);
c0bd3f63 2449 lock_page_cgroup(pc);
a3b2d692 2450 if (PageCgroupUsed(pc)) {
c0ff4b85
R
2451 memcg = pc->mem_cgroup;
2452 if (memcg && !css_tryget(&memcg->css))
2453 memcg = NULL;
e42d9d5d 2454 } else if (PageSwapCache(page)) {
3c776e64 2455 ent.val = page_private(page);
a3b2d692
KH
2456 id = lookup_swap_cgroup(ent);
2457 rcu_read_lock();
c0ff4b85
R
2458 memcg = mem_cgroup_lookup(id);
2459 if (memcg && !css_tryget(&memcg->css))
2460 memcg = NULL;
a3b2d692 2461 rcu_read_unlock();
3c776e64 2462 }
c0bd3f63 2463 unlock_page_cgroup(pc);
c0ff4b85 2464 return memcg;
b5a84319
KH
2465}
2466
c0ff4b85 2467static void __mem_cgroup_commit_charge(struct mem_cgroup *memcg,
5564e88b 2468 struct page *page,
7ec99d62 2469 unsigned int nr_pages,
ca3e0214 2470 struct page_cgroup *pc,
7ec99d62 2471 enum charge_type ctype)
7a81b88c 2472{
ca3e0214
KH
2473 lock_page_cgroup(pc);
2474 if (unlikely(PageCgroupUsed(pc))) {
2475 unlock_page_cgroup(pc);
c0ff4b85 2476 __mem_cgroup_cancel_charge(memcg, nr_pages);
ca3e0214
KH
2477 return;
2478 }
2479 /*
2480 * we don't need page_cgroup_lock about tail pages, becase they are not
2481 * accessed by any other context at this point.
2482 */
c0ff4b85 2483 pc->mem_cgroup = memcg;
261fb61a
KH
2484 /*
2485 * We access a page_cgroup asynchronously without lock_page_cgroup().
2486 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
2487 * is accessed after testing USED bit. To make pc->mem_cgroup visible
2488 * before USED bit, we need memory barrier here.
2489 * See mem_cgroup_add_lru_list(), etc.
2490 */
08e552c6 2491 smp_wmb();
4b3bde4c
BS
2492 switch (ctype) {
2493 case MEM_CGROUP_CHARGE_TYPE_CACHE:
2494 case MEM_CGROUP_CHARGE_TYPE_SHMEM:
2495 SetPageCgroupCache(pc);
2496 SetPageCgroupUsed(pc);
2497 break;
2498 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
2499 ClearPageCgroupCache(pc);
2500 SetPageCgroupUsed(pc);
2501 break;
2502 default:
2503 break;
2504 }
3be91277 2505
c0ff4b85 2506 mem_cgroup_charge_statistics(memcg, PageCgroupCache(pc), nr_pages);
52d4b9ac 2507 unlock_page_cgroup(pc);
430e4863
KH
2508 /*
2509 * "charge_statistics" updated event counter. Then, check it.
2510 * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
2511 * if they exceeds softlimit.
2512 */
c0ff4b85 2513 memcg_check_events(memcg, page);
7a81b88c 2514}
66e1707b 2515
ca3e0214
KH
2516#ifdef CONFIG_TRANSPARENT_HUGEPAGE
2517
2518#define PCGF_NOCOPY_AT_SPLIT ((1 << PCG_LOCK) | (1 << PCG_MOVE_LOCK) |\
2519 (1 << PCG_ACCT_LRU) | (1 << PCG_MIGRATION))
2520/*
2521 * Because tail pages are not marked as "used", set it. We're under
2522 * zone->lru_lock, 'splitting on pmd' and compund_lock.
2523 */
2524void mem_cgroup_split_huge_fixup(struct page *head, struct page *tail)
2525{
2526 struct page_cgroup *head_pc = lookup_page_cgroup(head);
2527 struct page_cgroup *tail_pc = lookup_page_cgroup(tail);
2528 unsigned long flags;
2529
3d37c4a9
KH
2530 if (mem_cgroup_disabled())
2531 return;
ca3e0214 2532 /*
ece35ca8 2533 * We have no races with charge/uncharge but will have races with
ca3e0214
KH
2534 * page state accounting.
2535 */
2536 move_lock_page_cgroup(head_pc, &flags);
2537
2538 tail_pc->mem_cgroup = head_pc->mem_cgroup;
2539 smp_wmb(); /* see __commit_charge() */
ece35ca8
KH
2540 if (PageCgroupAcctLRU(head_pc)) {
2541 enum lru_list lru;
2542 struct mem_cgroup_per_zone *mz;
2543
2544 /*
2545 * LRU flags cannot be copied because we need to add tail
2546 *.page to LRU by generic call and our hook will be called.
2547 * We hold lru_lock, then, reduce counter directly.
2548 */
2549 lru = page_lru(head);
97a6c37b 2550 mz = page_cgroup_zoneinfo(head_pc->mem_cgroup, head);
ece35ca8
KH
2551 MEM_CGROUP_ZSTAT(mz, lru) -= 1;
2552 }
ca3e0214
KH
2553 tail_pc->flags = head_pc->flags & ~PCGF_NOCOPY_AT_SPLIT;
2554 move_unlock_page_cgroup(head_pc, &flags);
2555}
2556#endif
2557
f817ed48 2558/**
de3638d9 2559 * mem_cgroup_move_account - move account of the page
5564e88b 2560 * @page: the page
7ec99d62 2561 * @nr_pages: number of regular pages (>1 for huge pages)
f817ed48
KH
2562 * @pc: page_cgroup of the page.
2563 * @from: mem_cgroup which the page is moved from.
2564 * @to: mem_cgroup which the page is moved to. @from != @to.
854ffa8d 2565 * @uncharge: whether we should call uncharge and css_put against @from.
f817ed48
KH
2566 *
2567 * The caller must confirm following.
08e552c6 2568 * - page is not on LRU (isolate_page() is useful.)
7ec99d62 2569 * - compound_lock is held when nr_pages > 1
f817ed48 2570 *
854ffa8d 2571 * This function doesn't do "charge" nor css_get to new cgroup. It should be
25985edc 2572 * done by a caller(__mem_cgroup_try_charge would be useful). If @uncharge is
854ffa8d
DN
2573 * true, this function does "uncharge" from old cgroup, but it doesn't if
2574 * @uncharge is false, so a caller should do "uncharge".
f817ed48 2575 */
7ec99d62
JW
2576static int mem_cgroup_move_account(struct page *page,
2577 unsigned int nr_pages,
2578 struct page_cgroup *pc,
2579 struct mem_cgroup *from,
2580 struct mem_cgroup *to,
2581 bool uncharge)
f817ed48 2582{
de3638d9
JW
2583 unsigned long flags;
2584 int ret;
987eba66 2585
f817ed48 2586 VM_BUG_ON(from == to);
5564e88b 2587 VM_BUG_ON(PageLRU(page));
de3638d9
JW
2588 /*
2589 * The page is isolated from LRU. So, collapse function
2590 * will not handle this page. But page splitting can happen.
2591 * Do this check under compound_page_lock(). The caller should
2592 * hold it.
2593 */
2594 ret = -EBUSY;
7ec99d62 2595 if (nr_pages > 1 && !PageTransHuge(page))
de3638d9
JW
2596 goto out;
2597
2598 lock_page_cgroup(pc);
2599
2600 ret = -EINVAL;
2601 if (!PageCgroupUsed(pc) || pc->mem_cgroup != from)
2602 goto unlock;
2603
2604 move_lock_page_cgroup(pc, &flags);
f817ed48 2605
8725d541 2606 if (PageCgroupFileMapped(pc)) {
c62b1a3b
KH
2607 /* Update mapped_file data for mem_cgroup */
2608 preempt_disable();
2609 __this_cpu_dec(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
2610 __this_cpu_inc(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
2611 preempt_enable();
d69b042f 2612 }
987eba66 2613 mem_cgroup_charge_statistics(from, PageCgroupCache(pc), -nr_pages);
854ffa8d
DN
2614 if (uncharge)
2615 /* This is not "cancel", but cancel_charge does all we need. */
e7018b8d 2616 __mem_cgroup_cancel_charge(from, nr_pages);
d69b042f 2617
854ffa8d 2618 /* caller should have done css_get */
08e552c6 2619 pc->mem_cgroup = to;
987eba66 2620 mem_cgroup_charge_statistics(to, PageCgroupCache(pc), nr_pages);
88703267
KH
2621 /*
2622 * We charges against "to" which may not have any tasks. Then, "to"
2623 * can be under rmdir(). But in current implementation, caller of
4ffef5fe 2624 * this function is just force_empty() and move charge, so it's
25985edc 2625 * guaranteed that "to" is never removed. So, we don't check rmdir
4ffef5fe 2626 * status here.
88703267 2627 */
de3638d9
JW
2628 move_unlock_page_cgroup(pc, &flags);
2629 ret = 0;
2630unlock:
57f9fd7d 2631 unlock_page_cgroup(pc);
d2265e6f
KH
2632 /*
2633 * check events
2634 */
5564e88b
JW
2635 memcg_check_events(to, page);
2636 memcg_check_events(from, page);
de3638d9 2637out:
f817ed48
KH
2638 return ret;
2639}
2640
2641/*
2642 * move charges to its parent.
2643 */
2644
5564e88b
JW
2645static int mem_cgroup_move_parent(struct page *page,
2646 struct page_cgroup *pc,
f817ed48
KH
2647 struct mem_cgroup *child,
2648 gfp_t gfp_mask)
2649{
2650 struct cgroup *cg = child->css.cgroup;
2651 struct cgroup *pcg = cg->parent;
2652 struct mem_cgroup *parent;
7ec99d62 2653 unsigned int nr_pages;
4be4489f 2654 unsigned long uninitialized_var(flags);
f817ed48
KH
2655 int ret;
2656
2657 /* Is ROOT ? */
2658 if (!pcg)
2659 return -EINVAL;
2660
57f9fd7d
DN
2661 ret = -EBUSY;
2662 if (!get_page_unless_zero(page))
2663 goto out;
2664 if (isolate_lru_page(page))
2665 goto put;
52dbb905 2666
7ec99d62 2667 nr_pages = hpage_nr_pages(page);
08e552c6 2668
f817ed48 2669 parent = mem_cgroup_from_cont(pcg);
7ec99d62 2670 ret = __mem_cgroup_try_charge(NULL, gfp_mask, nr_pages, &parent, false);
a636b327 2671 if (ret || !parent)
57f9fd7d 2672 goto put_back;
f817ed48 2673
7ec99d62 2674 if (nr_pages > 1)
987eba66
KH
2675 flags = compound_lock_irqsave(page);
2676
7ec99d62 2677 ret = mem_cgroup_move_account(page, nr_pages, pc, child, parent, true);
854ffa8d 2678 if (ret)
7ec99d62 2679 __mem_cgroup_cancel_charge(parent, nr_pages);
8dba474f 2680
7ec99d62 2681 if (nr_pages > 1)
987eba66 2682 compound_unlock_irqrestore(page, flags);
8dba474f 2683put_back:
08e552c6 2684 putback_lru_page(page);
57f9fd7d 2685put:
40d58138 2686 put_page(page);
57f9fd7d 2687out:
f817ed48
KH
2688 return ret;
2689}
2690
7a81b88c
KH
2691/*
2692 * Charge the memory controller for page usage.
2693 * Return
2694 * 0 if the charge was successful
2695 * < 0 if the cgroup is over its limit
2696 */
2697static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
73045c47 2698 gfp_t gfp_mask, enum charge_type ctype)
7a81b88c 2699{
c0ff4b85 2700 struct mem_cgroup *memcg = NULL;
7ec99d62 2701 unsigned int nr_pages = 1;
7a81b88c 2702 struct page_cgroup *pc;
8493ae43 2703 bool oom = true;
7a81b88c 2704 int ret;
ec168510 2705
37c2ac78 2706 if (PageTransHuge(page)) {
7ec99d62 2707 nr_pages <<= compound_order(page);
37c2ac78 2708 VM_BUG_ON(!PageTransHuge(page));
8493ae43
JW
2709 /*
2710 * Never OOM-kill a process for a huge page. The
2711 * fault handler will fall back to regular pages.
2712 */
2713 oom = false;
37c2ac78 2714 }
7a81b88c
KH
2715
2716 pc = lookup_page_cgroup(page);
af4a6621 2717 BUG_ON(!pc); /* XXX: remove this and move pc lookup into commit */
7a81b88c 2718
c0ff4b85
R
2719 ret = __mem_cgroup_try_charge(mm, gfp_mask, nr_pages, &memcg, oom);
2720 if (ret || !memcg)
7a81b88c
KH
2721 return ret;
2722
c0ff4b85 2723 __mem_cgroup_commit_charge(memcg, page, nr_pages, pc, ctype);
8a9f3ccd 2724 return 0;
8a9f3ccd
BS
2725}
2726
7a81b88c
KH
2727int mem_cgroup_newpage_charge(struct page *page,
2728 struct mm_struct *mm, gfp_t gfp_mask)
217bc319 2729{
f8d66542 2730 if (mem_cgroup_disabled())
cede86ac 2731 return 0;
69029cd5
KH
2732 /*
2733 * If already mapped, we don't have to account.
2734 * If page cache, page->mapping has address_space.
2735 * But page->mapping may have out-of-use anon_vma pointer,
2736 * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
2737 * is NULL.
2738 */
2739 if (page_mapped(page) || (page->mapping && !PageAnon(page)))
2740 return 0;
2741 if (unlikely(!mm))
2742 mm = &init_mm;
217bc319 2743 return mem_cgroup_charge_common(page, mm, gfp_mask,
73045c47 2744 MEM_CGROUP_CHARGE_TYPE_MAPPED);
217bc319
KH
2745}
2746
83aae4c7
DN
2747static void
2748__mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
2749 enum charge_type ctype);
2750
5a6475a4 2751static void
c0ff4b85 2752__mem_cgroup_commit_charge_lrucare(struct page *page, struct mem_cgroup *memcg,
5a6475a4
KH
2753 enum charge_type ctype)
2754{
2755 struct page_cgroup *pc = lookup_page_cgroup(page);
2756 /*
2757 * In some case, SwapCache, FUSE(splice_buf->radixtree), the page
2758 * is already on LRU. It means the page may on some other page_cgroup's
2759 * LRU. Take care of it.
2760 */
2761 mem_cgroup_lru_del_before_commit(page);
c0ff4b85 2762 __mem_cgroup_commit_charge(memcg, page, 1, pc, ctype);
5a6475a4
KH
2763 mem_cgroup_lru_add_after_commit(page);
2764 return;
2765}
2766
e1a1cd59
BS
2767int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
2768 gfp_t gfp_mask)
8697d331 2769{
c0ff4b85 2770 struct mem_cgroup *memcg = NULL;
b5a84319
KH
2771 int ret;
2772
f8d66542 2773 if (mem_cgroup_disabled())
cede86ac 2774 return 0;
52d4b9ac
KH
2775 if (PageCompound(page))
2776 return 0;
accf163e 2777
73045c47 2778 if (unlikely(!mm))
8697d331 2779 mm = &init_mm;
accf163e 2780
5a6475a4 2781 if (page_is_file_cache(page)) {
c0ff4b85
R
2782 ret = __mem_cgroup_try_charge(mm, gfp_mask, 1, &memcg, true);
2783 if (ret || !memcg)
5a6475a4 2784 return ret;
b5a84319 2785
5a6475a4
KH
2786 /*
2787 * FUSE reuses pages without going through the final
2788 * put that would remove them from the LRU list, make
2789 * sure that they get relinked properly.
2790 */
c0ff4b85 2791 __mem_cgroup_commit_charge_lrucare(page, memcg,
5a6475a4
KH
2792 MEM_CGROUP_CHARGE_TYPE_CACHE);
2793 return ret;
2794 }
83aae4c7
DN
2795 /* shmem */
2796 if (PageSwapCache(page)) {
c0ff4b85 2797 ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &memcg);
83aae4c7 2798 if (!ret)
c0ff4b85 2799 __mem_cgroup_commit_charge_swapin(page, memcg,
83aae4c7
DN
2800 MEM_CGROUP_CHARGE_TYPE_SHMEM);
2801 } else
2802 ret = mem_cgroup_charge_common(page, mm, gfp_mask,
73045c47 2803 MEM_CGROUP_CHARGE_TYPE_SHMEM);
b5a84319 2804
b5a84319 2805 return ret;
e8589cc1
KH
2806}
2807
54595fe2
KH
2808/*
2809 * While swap-in, try_charge -> commit or cancel, the page is locked.
2810 * And when try_charge() successfully returns, one refcnt to memcg without
21ae2956 2811 * struct page_cgroup is acquired. This refcnt will be consumed by
54595fe2
KH
2812 * "commit()" or removed by "cancel()"
2813 */
8c7c6e34
KH
2814int mem_cgroup_try_charge_swapin(struct mm_struct *mm,
2815 struct page *page,
2816 gfp_t mask, struct mem_cgroup **ptr)
2817{
c0ff4b85 2818 struct mem_cgroup *memcg;
54595fe2 2819 int ret;
8c7c6e34 2820
56039efa
KH
2821 *ptr = NULL;
2822
f8d66542 2823 if (mem_cgroup_disabled())
8c7c6e34
KH
2824 return 0;
2825
2826 if (!do_swap_account)
2827 goto charge_cur_mm;
8c7c6e34
KH
2828 /*
2829 * A racing thread's fault, or swapoff, may have already updated
407f9c8b
HD
2830 * the pte, and even removed page from swap cache: in those cases
2831 * do_swap_page()'s pte_same() test will fail; but there's also a
2832 * KSM case which does need to charge the page.
8c7c6e34
KH
2833 */
2834 if (!PageSwapCache(page))
407f9c8b 2835 goto charge_cur_mm;
c0ff4b85
R
2836 memcg = try_get_mem_cgroup_from_page(page);
2837 if (!memcg)
54595fe2 2838 goto charge_cur_mm;
c0ff4b85 2839 *ptr = memcg;
7ec99d62 2840 ret = __mem_cgroup_try_charge(NULL, mask, 1, ptr, true);
c0ff4b85 2841 css_put(&memcg->css);
54595fe2 2842 return ret;
8c7c6e34
KH
2843charge_cur_mm:
2844 if (unlikely(!mm))
2845 mm = &init_mm;
7ec99d62 2846 return __mem_cgroup_try_charge(mm, mask, 1, ptr, true);
8c7c6e34
KH
2847}
2848
83aae4c7
DN
2849static void
2850__mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
2851 enum charge_type ctype)
7a81b88c 2852{
f8d66542 2853 if (mem_cgroup_disabled())
7a81b88c
KH
2854 return;
2855 if (!ptr)
2856 return;
88703267 2857 cgroup_exclude_rmdir(&ptr->css);
5a6475a4
KH
2858
2859 __mem_cgroup_commit_charge_lrucare(page, ptr, ctype);
8c7c6e34
KH
2860 /*
2861 * Now swap is on-memory. This means this page may be
2862 * counted both as mem and swap....double count.
03f3c433
KH
2863 * Fix it by uncharging from memsw. Basically, this SwapCache is stable
2864 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
2865 * may call delete_from_swap_cache() before reach here.
8c7c6e34 2866 */
03f3c433 2867 if (do_swap_account && PageSwapCache(page)) {
8c7c6e34 2868 swp_entry_t ent = {.val = page_private(page)};
a3b2d692 2869 unsigned short id;
8c7c6e34 2870 struct mem_cgroup *memcg;
a3b2d692
KH
2871
2872 id = swap_cgroup_record(ent, 0);
2873 rcu_read_lock();
2874 memcg = mem_cgroup_lookup(id);
8c7c6e34 2875 if (memcg) {
a3b2d692
KH
2876 /*
2877 * This recorded memcg can be obsolete one. So, avoid
2878 * calling css_tryget
2879 */
0c3e73e8 2880 if (!mem_cgroup_is_root(memcg))
4e649152 2881 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
0c3e73e8 2882 mem_cgroup_swap_statistics(memcg, false);
8c7c6e34
KH
2883 mem_cgroup_put(memcg);
2884 }
a3b2d692 2885 rcu_read_unlock();
8c7c6e34 2886 }
88703267
KH
2887 /*
2888 * At swapin, we may charge account against cgroup which has no tasks.
2889 * So, rmdir()->pre_destroy() can be called while we do this charge.
2890 * In that case, we need to call pre_destroy() again. check it here.
2891 */
2892 cgroup_release_and_wakeup_rmdir(&ptr->css);
7a81b88c
KH
2893}
2894
83aae4c7
DN
2895void mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr)
2896{
2897 __mem_cgroup_commit_charge_swapin(page, ptr,
2898 MEM_CGROUP_CHARGE_TYPE_MAPPED);
2899}
2900
c0ff4b85 2901void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *memcg)
7a81b88c 2902{
f8d66542 2903 if (mem_cgroup_disabled())
7a81b88c 2904 return;
c0ff4b85 2905 if (!memcg)
7a81b88c 2906 return;
c0ff4b85 2907 __mem_cgroup_cancel_charge(memcg, 1);
7a81b88c
KH
2908}
2909
c0ff4b85 2910static void mem_cgroup_do_uncharge(struct mem_cgroup *memcg,
7ec99d62
JW
2911 unsigned int nr_pages,
2912 const enum charge_type ctype)
569b846d
KH
2913{
2914 struct memcg_batch_info *batch = NULL;
2915 bool uncharge_memsw = true;
7ec99d62 2916
569b846d
KH
2917 /* If swapout, usage of swap doesn't decrease */
2918 if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2919 uncharge_memsw = false;
569b846d
KH
2920
2921 batch = &current->memcg_batch;
2922 /*
2923 * In usual, we do css_get() when we remember memcg pointer.
2924 * But in this case, we keep res->usage until end of a series of
2925 * uncharges. Then, it's ok to ignore memcg's refcnt.
2926 */
2927 if (!batch->memcg)
c0ff4b85 2928 batch->memcg = memcg;
3c11ecf4
KH
2929 /*
2930 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
25985edc 2931 * In those cases, all pages freed continuously can be expected to be in
3c11ecf4
KH
2932 * the same cgroup and we have chance to coalesce uncharges.
2933 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
2934 * because we want to do uncharge as soon as possible.
2935 */
2936
2937 if (!batch->do_batch || test_thread_flag(TIF_MEMDIE))
2938 goto direct_uncharge;
2939
7ec99d62 2940 if (nr_pages > 1)
ec168510
AA
2941 goto direct_uncharge;
2942
569b846d
KH
2943 /*
2944 * In typical case, batch->memcg == mem. This means we can
2945 * merge a series of uncharges to an uncharge of res_counter.
2946 * If not, we uncharge res_counter ony by one.
2947 */
c0ff4b85 2948 if (batch->memcg != memcg)
569b846d
KH
2949 goto direct_uncharge;
2950 /* remember freed charge and uncharge it later */
7ffd4ca7 2951 batch->nr_pages++;
569b846d 2952 if (uncharge_memsw)
7ffd4ca7 2953 batch->memsw_nr_pages++;
569b846d
KH
2954 return;
2955direct_uncharge:
c0ff4b85 2956 res_counter_uncharge(&memcg->res, nr_pages * PAGE_SIZE);
569b846d 2957 if (uncharge_memsw)
c0ff4b85
R
2958 res_counter_uncharge(&memcg->memsw, nr_pages * PAGE_SIZE);
2959 if (unlikely(batch->memcg != memcg))
2960 memcg_oom_recover(memcg);
569b846d
KH
2961 return;
2962}
7a81b88c 2963
8a9f3ccd 2964/*
69029cd5 2965 * uncharge if !page_mapped(page)
8a9f3ccd 2966 */
8c7c6e34 2967static struct mem_cgroup *
69029cd5 2968__mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype)
8a9f3ccd 2969{
c0ff4b85 2970 struct mem_cgroup *memcg = NULL;
7ec99d62
JW
2971 unsigned int nr_pages = 1;
2972 struct page_cgroup *pc;
8a9f3ccd 2973
f8d66542 2974 if (mem_cgroup_disabled())
8c7c6e34 2975 return NULL;
4077960e 2976
d13d1443 2977 if (PageSwapCache(page))
8c7c6e34 2978 return NULL;
d13d1443 2979
37c2ac78 2980 if (PageTransHuge(page)) {
7ec99d62 2981 nr_pages <<= compound_order(page);
37c2ac78
AA
2982 VM_BUG_ON(!PageTransHuge(page));
2983 }
8697d331 2984 /*
3c541e14 2985 * Check if our page_cgroup is valid
8697d331 2986 */
52d4b9ac
KH
2987 pc = lookup_page_cgroup(page);
2988 if (unlikely(!pc || !PageCgroupUsed(pc)))
8c7c6e34 2989 return NULL;
b9c565d5 2990
52d4b9ac 2991 lock_page_cgroup(pc);
d13d1443 2992
c0ff4b85 2993 memcg = pc->mem_cgroup;
8c7c6e34 2994
d13d1443
KH
2995 if (!PageCgroupUsed(pc))
2996 goto unlock_out;
2997
2998 switch (ctype) {
2999 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
8a9478ca 3000 case MEM_CGROUP_CHARGE_TYPE_DROP:
ac39cf8c
AM
3001 /* See mem_cgroup_prepare_migration() */
3002 if (page_mapped(page) || PageCgroupMigration(pc))
d13d1443
KH
3003 goto unlock_out;
3004 break;
3005 case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
3006 if (!PageAnon(page)) { /* Shared memory */
3007 if (page->mapping && !page_is_file_cache(page))
3008 goto unlock_out;
3009 } else if (page_mapped(page)) /* Anon */
3010 goto unlock_out;
3011 break;
3012 default:
3013 break;
52d4b9ac 3014 }
d13d1443 3015
c0ff4b85 3016 mem_cgroup_charge_statistics(memcg, PageCgroupCache(pc), -nr_pages);
04046e1a 3017
52d4b9ac 3018 ClearPageCgroupUsed(pc);
544122e5
KH
3019 /*
3020 * pc->mem_cgroup is not cleared here. It will be accessed when it's
3021 * freed from LRU. This is safe because uncharged page is expected not
3022 * to be reused (freed soon). Exception is SwapCache, it's handled by
3023 * special functions.
3024 */
b9c565d5 3025
52d4b9ac 3026 unlock_page_cgroup(pc);
f75ca962 3027 /*
c0ff4b85 3028 * even after unlock, we have memcg->res.usage here and this memcg
f75ca962
KH
3029 * will never be freed.
3030 */
c0ff4b85 3031 memcg_check_events(memcg, page);
f75ca962 3032 if (do_swap_account && ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT) {
c0ff4b85
R
3033 mem_cgroup_swap_statistics(memcg, true);
3034 mem_cgroup_get(memcg);
f75ca962 3035 }
c0ff4b85
R
3036 if (!mem_cgroup_is_root(memcg))
3037 mem_cgroup_do_uncharge(memcg, nr_pages, ctype);
6d12e2d8 3038
c0ff4b85 3039 return memcg;
d13d1443
KH
3040
3041unlock_out:
3042 unlock_page_cgroup(pc);
8c7c6e34 3043 return NULL;
3c541e14
BS
3044}
3045
69029cd5
KH
3046void mem_cgroup_uncharge_page(struct page *page)
3047{
52d4b9ac
KH
3048 /* early check. */
3049 if (page_mapped(page))
3050 return;
3051 if (page->mapping && !PageAnon(page))
3052 return;
69029cd5
KH
3053 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_MAPPED);
3054}
3055
3056void mem_cgroup_uncharge_cache_page(struct page *page)
3057{
3058 VM_BUG_ON(page_mapped(page));
b7abea96 3059 VM_BUG_ON(page->mapping);
69029cd5
KH
3060 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE);
3061}
3062
569b846d
KH
3063/*
3064 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
3065 * In that cases, pages are freed continuously and we can expect pages
3066 * are in the same memcg. All these calls itself limits the number of
3067 * pages freed at once, then uncharge_start/end() is called properly.
3068 * This may be called prural(2) times in a context,
3069 */
3070
3071void mem_cgroup_uncharge_start(void)
3072{
3073 current->memcg_batch.do_batch++;
3074 /* We can do nest. */
3075 if (current->memcg_batch.do_batch == 1) {
3076 current->memcg_batch.memcg = NULL;
7ffd4ca7
JW
3077 current->memcg_batch.nr_pages = 0;
3078 current->memcg_batch.memsw_nr_pages = 0;
569b846d
KH
3079 }
3080}
3081
3082void mem_cgroup_uncharge_end(void)
3083{
3084 struct memcg_batch_info *batch = &current->memcg_batch;
3085
3086 if (!batch->do_batch)
3087 return;
3088
3089 batch->do_batch--;
3090 if (batch->do_batch) /* If stacked, do nothing. */
3091 return;
3092
3093 if (!batch->memcg)
3094 return;
3095 /*
3096 * This "batch->memcg" is valid without any css_get/put etc...
3097 * bacause we hide charges behind us.
3098 */
7ffd4ca7
JW
3099 if (batch->nr_pages)
3100 res_counter_uncharge(&batch->memcg->res,
3101 batch->nr_pages * PAGE_SIZE);
3102 if (batch->memsw_nr_pages)
3103 res_counter_uncharge(&batch->memcg->memsw,
3104 batch->memsw_nr_pages * PAGE_SIZE);
3c11ecf4 3105 memcg_oom_recover(batch->memcg);
569b846d
KH
3106 /* forget this pointer (for sanity check) */
3107 batch->memcg = NULL;
3108}
3109
e767e056 3110#ifdef CONFIG_SWAP
8c7c6e34 3111/*
e767e056 3112 * called after __delete_from_swap_cache() and drop "page" account.
8c7c6e34
KH
3113 * memcg information is recorded to swap_cgroup of "ent"
3114 */
8a9478ca
KH
3115void
3116mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
8c7c6e34
KH
3117{
3118 struct mem_cgroup *memcg;
8a9478ca
KH
3119 int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
3120
3121 if (!swapout) /* this was a swap cache but the swap is unused ! */
3122 ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
3123
3124 memcg = __mem_cgroup_uncharge_common(page, ctype);
8c7c6e34 3125
f75ca962
KH
3126 /*
3127 * record memcg information, if swapout && memcg != NULL,
3128 * mem_cgroup_get() was called in uncharge().
3129 */
3130 if (do_swap_account && swapout && memcg)
a3b2d692 3131 swap_cgroup_record(ent, css_id(&memcg->css));
8c7c6e34 3132}
e767e056 3133#endif
8c7c6e34
KH
3134
3135#ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3136/*
3137 * called from swap_entry_free(). remove record in swap_cgroup and
3138 * uncharge "memsw" account.
3139 */
3140void mem_cgroup_uncharge_swap(swp_entry_t ent)
d13d1443 3141{
8c7c6e34 3142 struct mem_cgroup *memcg;
a3b2d692 3143 unsigned short id;
8c7c6e34
KH
3144
3145 if (!do_swap_account)
3146 return;
3147
a3b2d692
KH
3148 id = swap_cgroup_record(ent, 0);
3149 rcu_read_lock();
3150 memcg = mem_cgroup_lookup(id);
8c7c6e34 3151 if (memcg) {
a3b2d692
KH
3152 /*
3153 * We uncharge this because swap is freed.
3154 * This memcg can be obsolete one. We avoid calling css_tryget
3155 */
0c3e73e8 3156 if (!mem_cgroup_is_root(memcg))
4e649152 3157 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
0c3e73e8 3158 mem_cgroup_swap_statistics(memcg, false);
8c7c6e34
KH
3159 mem_cgroup_put(memcg);
3160 }
a3b2d692 3161 rcu_read_unlock();
d13d1443 3162}
02491447
DN
3163
3164/**
3165 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3166 * @entry: swap entry to be moved
3167 * @from: mem_cgroup which the entry is moved from
3168 * @to: mem_cgroup which the entry is moved to
483c30b5 3169 * @need_fixup: whether we should fixup res_counters and refcounts.
02491447
DN
3170 *
3171 * It succeeds only when the swap_cgroup's record for this entry is the same
3172 * as the mem_cgroup's id of @from.
3173 *
3174 * Returns 0 on success, -EINVAL on failure.
3175 *
3176 * The caller must have charged to @to, IOW, called res_counter_charge() about
3177 * both res and memsw, and called css_get().
3178 */
3179static int mem_cgroup_move_swap_account(swp_entry_t entry,
483c30b5 3180 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
02491447
DN
3181{
3182 unsigned short old_id, new_id;
3183
3184 old_id = css_id(&from->css);
3185 new_id = css_id(&to->css);
3186
3187 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
02491447 3188 mem_cgroup_swap_statistics(from, false);
483c30b5 3189 mem_cgroup_swap_statistics(to, true);
02491447 3190 /*
483c30b5
DN
3191 * This function is only called from task migration context now.
3192 * It postpones res_counter and refcount handling till the end
3193 * of task migration(mem_cgroup_clear_mc()) for performance
3194 * improvement. But we cannot postpone mem_cgroup_get(to)
3195 * because if the process that has been moved to @to does
3196 * swap-in, the refcount of @to might be decreased to 0.
02491447 3197 */
02491447 3198 mem_cgroup_get(to);
483c30b5
DN
3199 if (need_fixup) {
3200 if (!mem_cgroup_is_root(from))
3201 res_counter_uncharge(&from->memsw, PAGE_SIZE);
3202 mem_cgroup_put(from);
3203 /*
3204 * we charged both to->res and to->memsw, so we should
3205 * uncharge to->res.
3206 */
3207 if (!mem_cgroup_is_root(to))
3208 res_counter_uncharge(&to->res, PAGE_SIZE);
483c30b5 3209 }
02491447
DN
3210 return 0;
3211 }
3212 return -EINVAL;
3213}
3214#else
3215static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
483c30b5 3216 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
02491447
DN
3217{
3218 return -EINVAL;
3219}
8c7c6e34 3220#endif
d13d1443 3221
ae41be37 3222/*
01b1ae63
KH
3223 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
3224 * page belongs to.
ae41be37 3225 */
ac39cf8c 3226int mem_cgroup_prepare_migration(struct page *page,
ef6a3c63 3227 struct page *newpage, struct mem_cgroup **ptr, gfp_t gfp_mask)
ae41be37 3228{
c0ff4b85 3229 struct mem_cgroup *memcg = NULL;
7ec99d62 3230 struct page_cgroup *pc;
ac39cf8c 3231 enum charge_type ctype;
e8589cc1 3232 int ret = 0;
8869b8f6 3233
56039efa
KH
3234 *ptr = NULL;
3235
ec168510 3236 VM_BUG_ON(PageTransHuge(page));
f8d66542 3237 if (mem_cgroup_disabled())
4077960e
BS
3238 return 0;
3239
52d4b9ac
KH
3240 pc = lookup_page_cgroup(page);
3241 lock_page_cgroup(pc);
3242 if (PageCgroupUsed(pc)) {
c0ff4b85
R
3243 memcg = pc->mem_cgroup;
3244 css_get(&memcg->css);
ac39cf8c
AM
3245 /*
3246 * At migrating an anonymous page, its mapcount goes down
3247 * to 0 and uncharge() will be called. But, even if it's fully
3248 * unmapped, migration may fail and this page has to be
3249 * charged again. We set MIGRATION flag here and delay uncharge
3250 * until end_migration() is called
3251 *
3252 * Corner Case Thinking
3253 * A)
3254 * When the old page was mapped as Anon and it's unmap-and-freed
3255 * while migration was ongoing.
3256 * If unmap finds the old page, uncharge() of it will be delayed
3257 * until end_migration(). If unmap finds a new page, it's
3258 * uncharged when it make mapcount to be 1->0. If unmap code
3259 * finds swap_migration_entry, the new page will not be mapped
3260 * and end_migration() will find it(mapcount==0).
3261 *
3262 * B)
3263 * When the old page was mapped but migraion fails, the kernel
3264 * remaps it. A charge for it is kept by MIGRATION flag even
3265 * if mapcount goes down to 0. We can do remap successfully
3266 * without charging it again.
3267 *
3268 * C)
3269 * The "old" page is under lock_page() until the end of
3270 * migration, so, the old page itself will not be swapped-out.
3271 * If the new page is swapped out before end_migraton, our
3272 * hook to usual swap-out path will catch the event.
3273 */
3274 if (PageAnon(page))
3275 SetPageCgroupMigration(pc);
e8589cc1 3276 }
52d4b9ac 3277 unlock_page_cgroup(pc);
ac39cf8c
AM
3278 /*
3279 * If the page is not charged at this point,
3280 * we return here.
3281 */
c0ff4b85 3282 if (!memcg)
ac39cf8c 3283 return 0;
01b1ae63 3284
c0ff4b85 3285 *ptr = memcg;
7ec99d62 3286 ret = __mem_cgroup_try_charge(NULL, gfp_mask, 1, ptr, false);
c0ff4b85 3287 css_put(&memcg->css);/* drop extra refcnt */
ac39cf8c
AM
3288 if (ret || *ptr == NULL) {
3289 if (PageAnon(page)) {
3290 lock_page_cgroup(pc);
3291 ClearPageCgroupMigration(pc);
3292 unlock_page_cgroup(pc);
3293 /*
3294 * The old page may be fully unmapped while we kept it.
3295 */
3296 mem_cgroup_uncharge_page(page);
3297 }
3298 return -ENOMEM;
e8589cc1 3299 }
ac39cf8c
AM
3300 /*
3301 * We charge new page before it's used/mapped. So, even if unlock_page()
3302 * is called before end_migration, we can catch all events on this new
3303 * page. In the case new page is migrated but not remapped, new page's
3304 * mapcount will be finally 0 and we call uncharge in end_migration().
3305 */
3306 pc = lookup_page_cgroup(newpage);
3307 if (PageAnon(page))
3308 ctype = MEM_CGROUP_CHARGE_TYPE_MAPPED;
3309 else if (page_is_file_cache(page))
3310 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
3311 else
3312 ctype = MEM_CGROUP_CHARGE_TYPE_SHMEM;
c0ff4b85 3313 __mem_cgroup_commit_charge(memcg, page, 1, pc, ctype);
e8589cc1 3314 return ret;
ae41be37 3315}
8869b8f6 3316
69029cd5 3317/* remove redundant charge if migration failed*/
c0ff4b85 3318void mem_cgroup_end_migration(struct mem_cgroup *memcg,
50de1dd9 3319 struct page *oldpage, struct page *newpage, bool migration_ok)
ae41be37 3320{
ac39cf8c 3321 struct page *used, *unused;
01b1ae63 3322 struct page_cgroup *pc;
01b1ae63 3323
c0ff4b85 3324 if (!memcg)
01b1ae63 3325 return;
ac39cf8c 3326 /* blocks rmdir() */
c0ff4b85 3327 cgroup_exclude_rmdir(&memcg->css);
50de1dd9 3328 if (!migration_ok) {
ac39cf8c
AM
3329 used = oldpage;
3330 unused = newpage;
01b1ae63 3331 } else {
ac39cf8c 3332 used = newpage;
01b1ae63
KH
3333 unused = oldpage;
3334 }
69029cd5 3335 /*
ac39cf8c
AM
3336 * We disallowed uncharge of pages under migration because mapcount
3337 * of the page goes down to zero, temporarly.
3338 * Clear the flag and check the page should be charged.
01b1ae63 3339 */
ac39cf8c
AM
3340 pc = lookup_page_cgroup(oldpage);
3341 lock_page_cgroup(pc);
3342 ClearPageCgroupMigration(pc);
3343 unlock_page_cgroup(pc);
01b1ae63 3344
ac39cf8c
AM
3345 __mem_cgroup_uncharge_common(unused, MEM_CGROUP_CHARGE_TYPE_FORCE);
3346
01b1ae63 3347 /*
ac39cf8c
AM
3348 * If a page is a file cache, radix-tree replacement is very atomic
3349 * and we can skip this check. When it was an Anon page, its mapcount
3350 * goes down to 0. But because we added MIGRATION flage, it's not
3351 * uncharged yet. There are several case but page->mapcount check
3352 * and USED bit check in mem_cgroup_uncharge_page() will do enough
3353 * check. (see prepare_charge() also)
69029cd5 3354 */
ac39cf8c
AM
3355 if (PageAnon(used))
3356 mem_cgroup_uncharge_page(used);
88703267 3357 /*
ac39cf8c
AM
3358 * At migration, we may charge account against cgroup which has no
3359 * tasks.
88703267
KH
3360 * So, rmdir()->pre_destroy() can be called while we do this charge.
3361 * In that case, we need to call pre_destroy() again. check it here.
3362 */
c0ff4b85 3363 cgroup_release_and_wakeup_rmdir(&memcg->css);
ae41be37 3364}
78fb7466 3365
f212ad7c
DN
3366#ifdef CONFIG_DEBUG_VM
3367static struct page_cgroup *lookup_page_cgroup_used(struct page *page)
3368{
3369 struct page_cgroup *pc;
3370
3371 pc = lookup_page_cgroup(page);
3372 if (likely(pc) && PageCgroupUsed(pc))
3373 return pc;
3374 return NULL;
3375}
3376
3377bool mem_cgroup_bad_page_check(struct page *page)
3378{
3379 if (mem_cgroup_disabled())
3380 return false;
3381
3382 return lookup_page_cgroup_used(page) != NULL;
3383}
3384
3385void mem_cgroup_print_bad_page(struct page *page)
3386{
3387 struct page_cgroup *pc;
3388
3389 pc = lookup_page_cgroup_used(page);
3390 if (pc) {
3391 int ret = -1;
3392 char *path;
3393
3394 printk(KERN_ALERT "pc:%p pc->flags:%lx pc->mem_cgroup:%p",
3395 pc, pc->flags, pc->mem_cgroup);
3396
3397 path = kmalloc(PATH_MAX, GFP_KERNEL);
3398 if (path) {
3399 rcu_read_lock();
3400 ret = cgroup_path(pc->mem_cgroup->css.cgroup,
3401 path, PATH_MAX);
3402 rcu_read_unlock();
3403 }
3404
3405 printk(KERN_CONT "(%s)\n",
3406 (ret < 0) ? "cannot get the path" : path);
3407 kfree(path);
3408 }
3409}
3410#endif
3411
8c7c6e34
KH
3412static DEFINE_MUTEX(set_limit_mutex);
3413
d38d2a75 3414static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
8c7c6e34 3415 unsigned long long val)
628f4235 3416{
81d39c20 3417 int retry_count;
3c11ecf4 3418 u64 memswlimit, memlimit;
628f4235 3419 int ret = 0;
81d39c20
KH
3420 int children = mem_cgroup_count_children(memcg);
3421 u64 curusage, oldusage;
3c11ecf4 3422 int enlarge;
81d39c20
KH
3423
3424 /*
3425 * For keeping hierarchical_reclaim simple, how long we should retry
3426 * is depends on callers. We set our retry-count to be function
3427 * of # of children which we should visit in this loop.
3428 */
3429 retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
3430
3431 oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
628f4235 3432
3c11ecf4 3433 enlarge = 0;
8c7c6e34 3434 while (retry_count) {
628f4235
KH
3435 if (signal_pending(current)) {
3436 ret = -EINTR;
3437 break;
3438 }
8c7c6e34
KH
3439 /*
3440 * Rather than hide all in some function, I do this in
3441 * open coded manner. You see what this really does.
c0ff4b85 3442 * We have to guarantee memcg->res.limit < memcg->memsw.limit.
8c7c6e34
KH
3443 */
3444 mutex_lock(&set_limit_mutex);
3445 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3446 if (memswlimit < val) {
3447 ret = -EINVAL;
3448 mutex_unlock(&set_limit_mutex);
628f4235
KH
3449 break;
3450 }
3c11ecf4
KH
3451
3452 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3453 if (memlimit < val)
3454 enlarge = 1;
3455
8c7c6e34 3456 ret = res_counter_set_limit(&memcg->res, val);
22a668d7
KH
3457 if (!ret) {
3458 if (memswlimit == val)
3459 memcg->memsw_is_minimum = true;
3460 else
3461 memcg->memsw_is_minimum = false;
3462 }
8c7c6e34
KH
3463 mutex_unlock(&set_limit_mutex);
3464
3465 if (!ret)
3466 break;
3467
aa20d489 3468 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
0ae5e89c
YH
3469 MEM_CGROUP_RECLAIM_SHRINK,
3470 NULL);
81d39c20
KH
3471 curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
3472 /* Usage is reduced ? */
3473 if (curusage >= oldusage)
3474 retry_count--;
3475 else
3476 oldusage = curusage;
8c7c6e34 3477 }
3c11ecf4
KH
3478 if (!ret && enlarge)
3479 memcg_oom_recover(memcg);
14797e23 3480
8c7c6e34
KH
3481 return ret;
3482}
3483
338c8431
LZ
3484static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
3485 unsigned long long val)
8c7c6e34 3486{
81d39c20 3487 int retry_count;
3c11ecf4 3488 u64 memlimit, memswlimit, oldusage, curusage;
81d39c20
KH
3489 int children = mem_cgroup_count_children(memcg);
3490 int ret = -EBUSY;
3c11ecf4 3491 int enlarge = 0;
8c7c6e34 3492
81d39c20
KH
3493 /* see mem_cgroup_resize_res_limit */
3494 retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
3495 oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
8c7c6e34
KH
3496 while (retry_count) {
3497 if (signal_pending(current)) {
3498 ret = -EINTR;
3499 break;
3500 }
3501 /*
3502 * Rather than hide all in some function, I do this in
3503 * open coded manner. You see what this really does.
c0ff4b85 3504 * We have to guarantee memcg->res.limit < memcg->memsw.limit.
8c7c6e34
KH
3505 */
3506 mutex_lock(&set_limit_mutex);
3507 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3508 if (memlimit > val) {
3509 ret = -EINVAL;
3510 mutex_unlock(&set_limit_mutex);
3511 break;
3512 }
3c11ecf4
KH
3513 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3514 if (memswlimit < val)
3515 enlarge = 1;
8c7c6e34 3516 ret = res_counter_set_limit(&memcg->memsw, val);
22a668d7
KH
3517 if (!ret) {
3518 if (memlimit == val)
3519 memcg->memsw_is_minimum = true;
3520 else
3521 memcg->memsw_is_minimum = false;
3522 }
8c7c6e34
KH
3523 mutex_unlock(&set_limit_mutex);
3524
3525 if (!ret)
3526 break;
3527
4e416953 3528 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
75822b44 3529 MEM_CGROUP_RECLAIM_NOSWAP |
0ae5e89c
YH
3530 MEM_CGROUP_RECLAIM_SHRINK,
3531 NULL);
8c7c6e34 3532 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
81d39c20 3533 /* Usage is reduced ? */
8c7c6e34 3534 if (curusage >= oldusage)
628f4235 3535 retry_count--;
81d39c20
KH
3536 else
3537 oldusage = curusage;
628f4235 3538 }
3c11ecf4
KH
3539 if (!ret && enlarge)
3540 memcg_oom_recover(memcg);
628f4235
KH
3541 return ret;
3542}
3543
4e416953 3544unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
0ae5e89c
YH
3545 gfp_t gfp_mask,
3546 unsigned long *total_scanned)
4e416953
BS
3547{
3548 unsigned long nr_reclaimed = 0;
3549 struct mem_cgroup_per_zone *mz, *next_mz = NULL;
3550 unsigned long reclaimed;
3551 int loop = 0;
3552 struct mem_cgroup_tree_per_zone *mctz;
ef8745c1 3553 unsigned long long excess;
0ae5e89c 3554 unsigned long nr_scanned;
4e416953
BS
3555
3556 if (order > 0)
3557 return 0;
3558
00918b6a 3559 mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone));
4e416953
BS
3560 /*
3561 * This loop can run a while, specially if mem_cgroup's continuously
3562 * keep exceeding their soft limit and putting the system under
3563 * pressure
3564 */
3565 do {
3566 if (next_mz)
3567 mz = next_mz;
3568 else
3569 mz = mem_cgroup_largest_soft_limit_node(mctz);
3570 if (!mz)
3571 break;
3572
0ae5e89c 3573 nr_scanned = 0;
4e416953
BS
3574 reclaimed = mem_cgroup_hierarchical_reclaim(mz->mem, zone,
3575 gfp_mask,
0ae5e89c
YH
3576 MEM_CGROUP_RECLAIM_SOFT,
3577 &nr_scanned);
4e416953 3578 nr_reclaimed += reclaimed;
0ae5e89c 3579 *total_scanned += nr_scanned;
4e416953
BS
3580 spin_lock(&mctz->lock);
3581
3582 /*
3583 * If we failed to reclaim anything from this memory cgroup
3584 * it is time to move on to the next cgroup
3585 */
3586 next_mz = NULL;
3587 if (!reclaimed) {
3588 do {
3589 /*
3590 * Loop until we find yet another one.
3591 *
3592 * By the time we get the soft_limit lock
3593 * again, someone might have aded the
3594 * group back on the RB tree. Iterate to
3595 * make sure we get a different mem.
3596 * mem_cgroup_largest_soft_limit_node returns
3597 * NULL if no other cgroup is present on
3598 * the tree
3599 */
3600 next_mz =
3601 __mem_cgroup_largest_soft_limit_node(mctz);
39cc98f1 3602 if (next_mz == mz)
4e416953 3603 css_put(&next_mz->mem->css);
39cc98f1 3604 else /* next_mz == NULL or other memcg */
4e416953
BS
3605 break;
3606 } while (1);
3607 }
4e416953 3608 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
ef8745c1 3609 excess = res_counter_soft_limit_excess(&mz->mem->res);
4e416953
BS
3610 /*
3611 * One school of thought says that we should not add
3612 * back the node to the tree if reclaim returns 0.
3613 * But our reclaim could return 0, simply because due
3614 * to priority we are exposing a smaller subset of
3615 * memory to reclaim from. Consider this as a longer
3616 * term TODO.
3617 */
ef8745c1
KH
3618 /* If excess == 0, no tree ops */
3619 __mem_cgroup_insert_exceeded(mz->mem, mz, mctz, excess);
4e416953
BS
3620 spin_unlock(&mctz->lock);
3621 css_put(&mz->mem->css);
3622 loop++;
3623 /*
3624 * Could not reclaim anything and there are no more
3625 * mem cgroups to try or we seem to be looping without
3626 * reclaiming anything.
3627 */
3628 if (!nr_reclaimed &&
3629 (next_mz == NULL ||
3630 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3631 break;
3632 } while (!nr_reclaimed);
3633 if (next_mz)
3634 css_put(&next_mz->mem->css);
3635 return nr_reclaimed;
3636}
3637
cc847582
KH
3638/*
3639 * This routine traverse page_cgroup in given list and drop them all.
cc847582
KH
3640 * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
3641 */
c0ff4b85 3642static int mem_cgroup_force_empty_list(struct mem_cgroup *memcg,
08e552c6 3643 int node, int zid, enum lru_list lru)
cc847582 3644{
08e552c6
KH
3645 struct zone *zone;
3646 struct mem_cgroup_per_zone *mz;
f817ed48 3647 struct page_cgroup *pc, *busy;
08e552c6 3648 unsigned long flags, loop;
072c56c1 3649 struct list_head *list;
f817ed48 3650 int ret = 0;
072c56c1 3651
08e552c6 3652 zone = &NODE_DATA(node)->node_zones[zid];
c0ff4b85 3653 mz = mem_cgroup_zoneinfo(memcg, node, zid);
b69408e8 3654 list = &mz->lists[lru];
cc847582 3655
f817ed48
KH
3656 loop = MEM_CGROUP_ZSTAT(mz, lru);
3657 /* give some margin against EBUSY etc...*/
3658 loop += 256;
3659 busy = NULL;
3660 while (loop--) {
5564e88b
JW
3661 struct page *page;
3662
f817ed48 3663 ret = 0;
08e552c6 3664 spin_lock_irqsave(&zone->lru_lock, flags);
f817ed48 3665 if (list_empty(list)) {
08e552c6 3666 spin_unlock_irqrestore(&zone->lru_lock, flags);
52d4b9ac 3667 break;
f817ed48
KH
3668 }
3669 pc = list_entry(list->prev, struct page_cgroup, lru);
3670 if (busy == pc) {
3671 list_move(&pc->lru, list);
648bcc77 3672 busy = NULL;
08e552c6 3673 spin_unlock_irqrestore(&zone->lru_lock, flags);
f817ed48
KH
3674 continue;
3675 }
08e552c6 3676 spin_unlock_irqrestore(&zone->lru_lock, flags);
f817ed48 3677
6b3ae58e 3678 page = lookup_cgroup_page(pc);
5564e88b 3679
c0ff4b85 3680 ret = mem_cgroup_move_parent(page, pc, memcg, GFP_KERNEL);
f817ed48 3681 if (ret == -ENOMEM)
52d4b9ac 3682 break;
f817ed48
KH
3683
3684 if (ret == -EBUSY || ret == -EINVAL) {
3685 /* found lock contention or "pc" is obsolete. */
3686 busy = pc;
3687 cond_resched();
3688 } else
3689 busy = NULL;
cc847582 3690 }
08e552c6 3691
f817ed48
KH
3692 if (!ret && !list_empty(list))
3693 return -EBUSY;
3694 return ret;
cc847582
KH
3695}
3696
3697/*
3698 * make mem_cgroup's charge to be 0 if there is no task.
3699 * This enables deleting this mem_cgroup.
3700 */
c0ff4b85 3701static int mem_cgroup_force_empty(struct mem_cgroup *memcg, bool free_all)
cc847582 3702{
f817ed48
KH
3703 int ret;
3704 int node, zid, shrink;
3705 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
c0ff4b85 3706 struct cgroup *cgrp = memcg->css.cgroup;
8869b8f6 3707
c0ff4b85 3708 css_get(&memcg->css);
f817ed48
KH
3709
3710 shrink = 0;
c1e862c1
KH
3711 /* should free all ? */
3712 if (free_all)
3713 goto try_to_free;
f817ed48 3714move_account:
fce66477 3715 do {
f817ed48 3716 ret = -EBUSY;
c1e862c1
KH
3717 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
3718 goto out;
3719 ret = -EINTR;
3720 if (signal_pending(current))
cc847582 3721 goto out;
52d4b9ac
KH
3722 /* This is for making all *used* pages to be on LRU. */
3723 lru_add_drain_all();
c0ff4b85 3724 drain_all_stock_sync(memcg);
f817ed48 3725 ret = 0;
c0ff4b85 3726 mem_cgroup_start_move(memcg);
299b4eaa 3727 for_each_node_state(node, N_HIGH_MEMORY) {
f817ed48 3728 for (zid = 0; !ret && zid < MAX_NR_ZONES; zid++) {
b69408e8 3729 enum lru_list l;
f817ed48 3730 for_each_lru(l) {
c0ff4b85 3731 ret = mem_cgroup_force_empty_list(memcg,
08e552c6 3732 node, zid, l);
f817ed48
KH
3733 if (ret)
3734 break;
3735 }
1ecaab2b 3736 }
f817ed48
KH
3737 if (ret)
3738 break;
3739 }
c0ff4b85
R
3740 mem_cgroup_end_move(memcg);
3741 memcg_oom_recover(memcg);
f817ed48
KH
3742 /* it seems parent cgroup doesn't have enough mem */
3743 if (ret == -ENOMEM)
3744 goto try_to_free;
52d4b9ac 3745 cond_resched();
fce66477 3746 /* "ret" should also be checked to ensure all lists are empty. */
c0ff4b85 3747 } while (memcg->res.usage > 0 || ret);
cc847582 3748out:
c0ff4b85 3749 css_put(&memcg->css);
cc847582 3750 return ret;
f817ed48
KH
3751
3752try_to_free:
c1e862c1
KH
3753 /* returns EBUSY if there is a task or if we come here twice. */
3754 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children) || shrink) {
f817ed48
KH
3755 ret = -EBUSY;
3756 goto out;
3757 }
c1e862c1
KH
3758 /* we call try-to-free pages for make this cgroup empty */
3759 lru_add_drain_all();
f817ed48
KH
3760 /* try to free all pages in this cgroup */
3761 shrink = 1;
c0ff4b85 3762 while (nr_retries && memcg->res.usage > 0) {
f817ed48 3763 int progress;
c1e862c1
KH
3764
3765 if (signal_pending(current)) {
3766 ret = -EINTR;
3767 goto out;
3768 }
c0ff4b85 3769 progress = try_to_free_mem_cgroup_pages(memcg, GFP_KERNEL,
185efc0f 3770 false);
c1e862c1 3771 if (!progress) {
f817ed48 3772 nr_retries--;
c1e862c1 3773 /* maybe some writeback is necessary */
8aa7e847 3774 congestion_wait(BLK_RW_ASYNC, HZ/10);
c1e862c1 3775 }
f817ed48
KH
3776
3777 }
08e552c6 3778 lru_add_drain();
f817ed48 3779 /* try move_account...there may be some *locked* pages. */
fce66477 3780 goto move_account;
cc847582
KH
3781}
3782
c1e862c1
KH
3783int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
3784{
3785 return mem_cgroup_force_empty(mem_cgroup_from_cont(cont), true);
3786}
3787
3788
18f59ea7
BS
3789static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
3790{
3791 return mem_cgroup_from_cont(cont)->use_hierarchy;
3792}
3793
3794static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
3795 u64 val)
3796{
3797 int retval = 0;
c0ff4b85 3798 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
18f59ea7 3799 struct cgroup *parent = cont->parent;
c0ff4b85 3800 struct mem_cgroup *parent_memcg = NULL;
18f59ea7
BS
3801
3802 if (parent)
c0ff4b85 3803 parent_memcg = mem_cgroup_from_cont(parent);
18f59ea7
BS
3804
3805 cgroup_lock();
3806 /*
af901ca1 3807 * If parent's use_hierarchy is set, we can't make any modifications
18f59ea7
BS
3808 * in the child subtrees. If it is unset, then the change can
3809 * occur, provided the current cgroup has no children.
3810 *
3811 * For the root cgroup, parent_mem is NULL, we allow value to be
3812 * set if there are no children.
3813 */
c0ff4b85 3814 if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
18f59ea7
BS
3815 (val == 1 || val == 0)) {
3816 if (list_empty(&cont->children))
c0ff4b85 3817 memcg->use_hierarchy = val;
18f59ea7
BS
3818 else
3819 retval = -EBUSY;
3820 } else
3821 retval = -EINVAL;
3822 cgroup_unlock();
3823
3824 return retval;
3825}
3826
0c3e73e8 3827
c0ff4b85 3828static unsigned long mem_cgroup_recursive_stat(struct mem_cgroup *memcg,
7a159cc9 3829 enum mem_cgroup_stat_index idx)
0c3e73e8 3830{
7d74b06f 3831 struct mem_cgroup *iter;
7a159cc9 3832 long val = 0;
0c3e73e8 3833
7a159cc9 3834 /* Per-cpu values can be negative, use a signed accumulator */
c0ff4b85 3835 for_each_mem_cgroup_tree(iter, memcg)
7d74b06f
KH
3836 val += mem_cgroup_read_stat(iter, idx);
3837
3838 if (val < 0) /* race ? */
3839 val = 0;
3840 return val;
0c3e73e8
BS
3841}
3842
c0ff4b85 3843static inline u64 mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
104f3928 3844{
7d74b06f 3845 u64 val;
104f3928 3846
c0ff4b85 3847 if (!mem_cgroup_is_root(memcg)) {
104f3928 3848 if (!swap)
c0ff4b85 3849 return res_counter_read_u64(&memcg->res, RES_USAGE);
104f3928 3850 else
c0ff4b85 3851 return res_counter_read_u64(&memcg->memsw, RES_USAGE);
104f3928
KS
3852 }
3853
c0ff4b85
R
3854 val = mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_CACHE);
3855 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_RSS);
104f3928 3856
7d74b06f 3857 if (swap)
c0ff4b85 3858 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_SWAPOUT);
104f3928
KS
3859
3860 return val << PAGE_SHIFT;
3861}
3862
2c3daa72 3863static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft)
8cdea7c0 3864{
c0ff4b85 3865 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
104f3928 3866 u64 val;
8c7c6e34
KH
3867 int type, name;
3868
3869 type = MEMFILE_TYPE(cft->private);
3870 name = MEMFILE_ATTR(cft->private);
3871 switch (type) {
3872 case _MEM:
104f3928 3873 if (name == RES_USAGE)
c0ff4b85 3874 val = mem_cgroup_usage(memcg, false);
104f3928 3875 else
c0ff4b85 3876 val = res_counter_read_u64(&memcg->res, name);
8c7c6e34
KH
3877 break;
3878 case _MEMSWAP:
104f3928 3879 if (name == RES_USAGE)
c0ff4b85 3880 val = mem_cgroup_usage(memcg, true);
104f3928 3881 else
c0ff4b85 3882 val = res_counter_read_u64(&memcg->memsw, name);
8c7c6e34
KH
3883 break;
3884 default:
3885 BUG();
3886 break;
3887 }
3888 return val;
8cdea7c0 3889}
628f4235
KH
3890/*
3891 * The user of this function is...
3892 * RES_LIMIT.
3893 */
856c13aa
PM
3894static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
3895 const char *buffer)
8cdea7c0 3896{
628f4235 3897 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
8c7c6e34 3898 int type, name;
628f4235
KH
3899 unsigned long long val;
3900 int ret;
3901
8c7c6e34
KH
3902 type = MEMFILE_TYPE(cft->private);
3903 name = MEMFILE_ATTR(cft->private);
3904 switch (name) {
628f4235 3905 case RES_LIMIT:
4b3bde4c
BS
3906 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3907 ret = -EINVAL;
3908 break;
3909 }
628f4235
KH
3910 /* This function does all necessary parse...reuse it */
3911 ret = res_counter_memparse_write_strategy(buffer, &val);
8c7c6e34
KH
3912 if (ret)
3913 break;
3914 if (type == _MEM)
628f4235 3915 ret = mem_cgroup_resize_limit(memcg, val);
8c7c6e34
KH
3916 else
3917 ret = mem_cgroup_resize_memsw_limit(memcg, val);
628f4235 3918 break;
296c81d8
BS
3919 case RES_SOFT_LIMIT:
3920 ret = res_counter_memparse_write_strategy(buffer, &val);
3921 if (ret)
3922 break;
3923 /*
3924 * For memsw, soft limits are hard to implement in terms
3925 * of semantics, for now, we support soft limits for
3926 * control without swap
3927 */
3928 if (type == _MEM)
3929 ret = res_counter_set_soft_limit(&memcg->res, val);
3930 else
3931 ret = -EINVAL;
3932 break;
628f4235
KH
3933 default:
3934 ret = -EINVAL; /* should be BUG() ? */
3935 break;
3936 }
3937 return ret;
8cdea7c0
BS
3938}
3939
fee7b548
KH
3940static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
3941 unsigned long long *mem_limit, unsigned long long *memsw_limit)
3942{
3943 struct cgroup *cgroup;
3944 unsigned long long min_limit, min_memsw_limit, tmp;
3945
3946 min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3947 min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3948 cgroup = memcg->css.cgroup;
3949 if (!memcg->use_hierarchy)
3950 goto out;
3951
3952 while (cgroup->parent) {
3953 cgroup = cgroup->parent;
3954 memcg = mem_cgroup_from_cont(cgroup);
3955 if (!memcg->use_hierarchy)
3956 break;
3957 tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
3958 min_limit = min(min_limit, tmp);
3959 tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3960 min_memsw_limit = min(min_memsw_limit, tmp);
3961 }
3962out:
3963 *mem_limit = min_limit;
3964 *memsw_limit = min_memsw_limit;
3965 return;
3966}
3967
29f2a4da 3968static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
c84872e1 3969{
c0ff4b85 3970 struct mem_cgroup *memcg;
8c7c6e34 3971 int type, name;
c84872e1 3972
c0ff4b85 3973 memcg = mem_cgroup_from_cont(cont);
8c7c6e34
KH
3974 type = MEMFILE_TYPE(event);
3975 name = MEMFILE_ATTR(event);
3976 switch (name) {
29f2a4da 3977 case RES_MAX_USAGE:
8c7c6e34 3978 if (type == _MEM)
c0ff4b85 3979 res_counter_reset_max(&memcg->res);
8c7c6e34 3980 else
c0ff4b85 3981 res_counter_reset_max(&memcg->memsw);
29f2a4da
PE
3982 break;
3983 case RES_FAILCNT:
8c7c6e34 3984 if (type == _MEM)
c0ff4b85 3985 res_counter_reset_failcnt(&memcg->res);
8c7c6e34 3986 else
c0ff4b85 3987 res_counter_reset_failcnt(&memcg->memsw);
29f2a4da
PE
3988 break;
3989 }
f64c3f54 3990
85cc59db 3991 return 0;
c84872e1
PE
3992}
3993
7dc74be0
DN
3994static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp,
3995 struct cftype *cft)
3996{
3997 return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate;
3998}
3999
02491447 4000#ifdef CONFIG_MMU
7dc74be0
DN
4001static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
4002 struct cftype *cft, u64 val)
4003{
c0ff4b85 4004 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
7dc74be0
DN
4005
4006 if (val >= (1 << NR_MOVE_TYPE))
4007 return -EINVAL;
4008 /*
4009 * We check this value several times in both in can_attach() and
4010 * attach(), so we need cgroup lock to prevent this value from being
4011 * inconsistent.
4012 */
4013 cgroup_lock();
c0ff4b85 4014 memcg->move_charge_at_immigrate = val;
7dc74be0
DN
4015 cgroup_unlock();
4016
4017 return 0;
4018}
02491447
DN
4019#else
4020static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
4021 struct cftype *cft, u64 val)
4022{
4023 return -ENOSYS;
4024}
4025#endif
7dc74be0 4026
14067bb3
KH
4027
4028/* For read statistics */
4029enum {
4030 MCS_CACHE,
4031 MCS_RSS,
d8046582 4032 MCS_FILE_MAPPED,
14067bb3
KH
4033 MCS_PGPGIN,
4034 MCS_PGPGOUT,
1dd3a273 4035 MCS_SWAP,
456f998e
YH
4036 MCS_PGFAULT,
4037 MCS_PGMAJFAULT,
14067bb3
KH
4038 MCS_INACTIVE_ANON,
4039 MCS_ACTIVE_ANON,
4040 MCS_INACTIVE_FILE,
4041 MCS_ACTIVE_FILE,
4042 MCS_UNEVICTABLE,
4043 NR_MCS_STAT,
4044};
4045
4046struct mcs_total_stat {
4047 s64 stat[NR_MCS_STAT];
d2ceb9b7
KH
4048};
4049
14067bb3
KH
4050struct {
4051 char *local_name;
4052 char *total_name;
4053} memcg_stat_strings[NR_MCS_STAT] = {
4054 {"cache", "total_cache"},
4055 {"rss", "total_rss"},
d69b042f 4056 {"mapped_file", "total_mapped_file"},
14067bb3
KH
4057 {"pgpgin", "total_pgpgin"},
4058 {"pgpgout", "total_pgpgout"},
1dd3a273 4059 {"swap", "total_swap"},
456f998e
YH
4060 {"pgfault", "total_pgfault"},
4061 {"pgmajfault", "total_pgmajfault"},
14067bb3
KH
4062 {"inactive_anon", "total_inactive_anon"},
4063 {"active_anon", "total_active_anon"},
4064 {"inactive_file", "total_inactive_file"},
4065 {"active_file", "total_active_file"},
4066 {"unevictable", "total_unevictable"}
4067};
4068
4069
7d74b06f 4070static void
c0ff4b85 4071mem_cgroup_get_local_stat(struct mem_cgroup *memcg, struct mcs_total_stat *s)
14067bb3 4072{
14067bb3
KH
4073 s64 val;
4074
4075 /* per cpu stat */
c0ff4b85 4076 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_CACHE);
14067bb3 4077 s->stat[MCS_CACHE] += val * PAGE_SIZE;
c0ff4b85 4078 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_RSS);
14067bb3 4079 s->stat[MCS_RSS] += val * PAGE_SIZE;
c0ff4b85 4080 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_FILE_MAPPED);
d8046582 4081 s->stat[MCS_FILE_MAPPED] += val * PAGE_SIZE;
c0ff4b85 4082 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGPGIN);
14067bb3 4083 s->stat[MCS_PGPGIN] += val;
c0ff4b85 4084 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGPGOUT);
14067bb3 4085 s->stat[MCS_PGPGOUT] += val;
1dd3a273 4086 if (do_swap_account) {
c0ff4b85 4087 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_SWAPOUT);
1dd3a273
DN
4088 s->stat[MCS_SWAP] += val * PAGE_SIZE;
4089 }
c0ff4b85 4090 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGFAULT);
456f998e 4091 s->stat[MCS_PGFAULT] += val;
c0ff4b85 4092 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGMAJFAULT);
456f998e 4093 s->stat[MCS_PGMAJFAULT] += val;
14067bb3
KH
4094
4095 /* per zone stat */
c0ff4b85 4096 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_INACTIVE_ANON));
14067bb3 4097 s->stat[MCS_INACTIVE_ANON] += val * PAGE_SIZE;
c0ff4b85 4098 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_ACTIVE_ANON));
14067bb3 4099 s->stat[MCS_ACTIVE_ANON] += val * PAGE_SIZE;
c0ff4b85 4100 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_INACTIVE_FILE));
14067bb3 4101 s->stat[MCS_INACTIVE_FILE] += val * PAGE_SIZE;
c0ff4b85 4102 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_ACTIVE_FILE));
14067bb3 4103 s->stat[MCS_ACTIVE_FILE] += val * PAGE_SIZE;
c0ff4b85 4104 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_UNEVICTABLE));
14067bb3 4105 s->stat[MCS_UNEVICTABLE] += val * PAGE_SIZE;
14067bb3
KH
4106}
4107
4108static void
c0ff4b85 4109mem_cgroup_get_total_stat(struct mem_cgroup *memcg, struct mcs_total_stat *s)
14067bb3 4110{
7d74b06f
KH
4111 struct mem_cgroup *iter;
4112
c0ff4b85 4113 for_each_mem_cgroup_tree(iter, memcg)
7d74b06f 4114 mem_cgroup_get_local_stat(iter, s);
14067bb3
KH
4115}
4116
406eb0c9
YH
4117#ifdef CONFIG_NUMA
4118static int mem_control_numa_stat_show(struct seq_file *m, void *arg)
4119{
4120 int nid;
4121 unsigned long total_nr, file_nr, anon_nr, unevictable_nr;
4122 unsigned long node_nr;
4123 struct cgroup *cont = m->private;
4124 struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
4125
bb2a0de9 4126 total_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL);
406eb0c9
YH
4127 seq_printf(m, "total=%lu", total_nr);
4128 for_each_node_state(nid, N_HIGH_MEMORY) {
bb2a0de9 4129 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid, LRU_ALL);
406eb0c9
YH
4130 seq_printf(m, " N%d=%lu", nid, node_nr);
4131 }
4132 seq_putc(m, '\n');
4133
bb2a0de9 4134 file_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL_FILE);
406eb0c9
YH
4135 seq_printf(m, "file=%lu", file_nr);
4136 for_each_node_state(nid, N_HIGH_MEMORY) {
bb2a0de9
KH
4137 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4138 LRU_ALL_FILE);
406eb0c9
YH
4139 seq_printf(m, " N%d=%lu", nid, node_nr);
4140 }
4141 seq_putc(m, '\n');
4142
bb2a0de9 4143 anon_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL_ANON);
406eb0c9
YH
4144 seq_printf(m, "anon=%lu", anon_nr);
4145 for_each_node_state(nid, N_HIGH_MEMORY) {
bb2a0de9
KH
4146 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4147 LRU_ALL_ANON);
406eb0c9
YH
4148 seq_printf(m, " N%d=%lu", nid, node_nr);
4149 }
4150 seq_putc(m, '\n');
4151
bb2a0de9 4152 unevictable_nr = mem_cgroup_nr_lru_pages(mem_cont, BIT(LRU_UNEVICTABLE));
406eb0c9
YH
4153 seq_printf(m, "unevictable=%lu", unevictable_nr);
4154 for_each_node_state(nid, N_HIGH_MEMORY) {
bb2a0de9
KH
4155 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4156 BIT(LRU_UNEVICTABLE));
406eb0c9
YH
4157 seq_printf(m, " N%d=%lu", nid, node_nr);
4158 }
4159 seq_putc(m, '\n');
4160 return 0;
4161}
4162#endif /* CONFIG_NUMA */
4163
c64745cf
PM
4164static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft,
4165 struct cgroup_map_cb *cb)
d2ceb9b7 4166{
d2ceb9b7 4167 struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
14067bb3 4168 struct mcs_total_stat mystat;
d2ceb9b7
KH
4169 int i;
4170
14067bb3
KH
4171 memset(&mystat, 0, sizeof(mystat));
4172 mem_cgroup_get_local_stat(mem_cont, &mystat);
d2ceb9b7 4173
406eb0c9 4174
1dd3a273
DN
4175 for (i = 0; i < NR_MCS_STAT; i++) {
4176 if (i == MCS_SWAP && !do_swap_account)
4177 continue;
14067bb3 4178 cb->fill(cb, memcg_stat_strings[i].local_name, mystat.stat[i]);
1dd3a273 4179 }
7b854121 4180
14067bb3 4181 /* Hierarchical information */
fee7b548
KH
4182 {
4183 unsigned long long limit, memsw_limit;
4184 memcg_get_hierarchical_limit(mem_cont, &limit, &memsw_limit);
4185 cb->fill(cb, "hierarchical_memory_limit", limit);
4186 if (do_swap_account)
4187 cb->fill(cb, "hierarchical_memsw_limit", memsw_limit);
4188 }
7f016ee8 4189
14067bb3
KH
4190 memset(&mystat, 0, sizeof(mystat));
4191 mem_cgroup_get_total_stat(mem_cont, &mystat);
1dd3a273
DN
4192 for (i = 0; i < NR_MCS_STAT; i++) {
4193 if (i == MCS_SWAP && !do_swap_account)
4194 continue;
14067bb3 4195 cb->fill(cb, memcg_stat_strings[i].total_name, mystat.stat[i]);
1dd3a273 4196 }
14067bb3 4197
7f016ee8 4198#ifdef CONFIG_DEBUG_VM
7f016ee8
KM
4199 {
4200 int nid, zid;
4201 struct mem_cgroup_per_zone *mz;
4202 unsigned long recent_rotated[2] = {0, 0};
4203 unsigned long recent_scanned[2] = {0, 0};
4204
4205 for_each_online_node(nid)
4206 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
4207 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
4208
4209 recent_rotated[0] +=
4210 mz->reclaim_stat.recent_rotated[0];
4211 recent_rotated[1] +=
4212 mz->reclaim_stat.recent_rotated[1];
4213 recent_scanned[0] +=
4214 mz->reclaim_stat.recent_scanned[0];
4215 recent_scanned[1] +=
4216 mz->reclaim_stat.recent_scanned[1];
4217 }
4218 cb->fill(cb, "recent_rotated_anon", recent_rotated[0]);
4219 cb->fill(cb, "recent_rotated_file", recent_rotated[1]);
4220 cb->fill(cb, "recent_scanned_anon", recent_scanned[0]);
4221 cb->fill(cb, "recent_scanned_file", recent_scanned[1]);
4222 }
4223#endif
4224
d2ceb9b7
KH
4225 return 0;
4226}
4227
a7885eb8
KM
4228static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
4229{
4230 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4231
1f4c025b 4232 return mem_cgroup_swappiness(memcg);
a7885eb8
KM
4233}
4234
4235static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
4236 u64 val)
4237{
4238 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4239 struct mem_cgroup *parent;
068b38c1 4240
a7885eb8
KM
4241 if (val > 100)
4242 return -EINVAL;
4243
4244 if (cgrp->parent == NULL)
4245 return -EINVAL;
4246
4247 parent = mem_cgroup_from_cont(cgrp->parent);
068b38c1
LZ
4248
4249 cgroup_lock();
4250
a7885eb8
KM
4251 /* If under hierarchy, only empty-root can set this value */
4252 if ((parent->use_hierarchy) ||
068b38c1
LZ
4253 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
4254 cgroup_unlock();
a7885eb8 4255 return -EINVAL;
068b38c1 4256 }
a7885eb8 4257
a7885eb8 4258 memcg->swappiness = val;
a7885eb8 4259
068b38c1
LZ
4260 cgroup_unlock();
4261
a7885eb8
KM
4262 return 0;
4263}
4264
2e72b634
KS
4265static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4266{
4267 struct mem_cgroup_threshold_ary *t;
4268 u64 usage;
4269 int i;
4270
4271 rcu_read_lock();
4272 if (!swap)
2c488db2 4273 t = rcu_dereference(memcg->thresholds.primary);
2e72b634 4274 else
2c488db2 4275 t = rcu_dereference(memcg->memsw_thresholds.primary);
2e72b634
KS
4276
4277 if (!t)
4278 goto unlock;
4279
4280 usage = mem_cgroup_usage(memcg, swap);
4281
4282 /*
4283 * current_threshold points to threshold just below usage.
4284 * If it's not true, a threshold was crossed after last
4285 * call of __mem_cgroup_threshold().
4286 */
5407a562 4287 i = t->current_threshold;
2e72b634
KS
4288
4289 /*
4290 * Iterate backward over array of thresholds starting from
4291 * current_threshold and check if a threshold is crossed.
4292 * If none of thresholds below usage is crossed, we read
4293 * only one element of the array here.
4294 */
4295 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4296 eventfd_signal(t->entries[i].eventfd, 1);
4297
4298 /* i = current_threshold + 1 */
4299 i++;
4300
4301 /*
4302 * Iterate forward over array of thresholds starting from
4303 * current_threshold+1 and check if a threshold is crossed.
4304 * If none of thresholds above usage is crossed, we read
4305 * only one element of the array here.
4306 */
4307 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4308 eventfd_signal(t->entries[i].eventfd, 1);
4309
4310 /* Update current_threshold */
5407a562 4311 t->current_threshold = i - 1;
2e72b634
KS
4312unlock:
4313 rcu_read_unlock();
4314}
4315
4316static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4317{
ad4ca5f4
KS
4318 while (memcg) {
4319 __mem_cgroup_threshold(memcg, false);
4320 if (do_swap_account)
4321 __mem_cgroup_threshold(memcg, true);
4322
4323 memcg = parent_mem_cgroup(memcg);
4324 }
2e72b634
KS
4325}
4326
4327static int compare_thresholds(const void *a, const void *b)
4328{
4329 const struct mem_cgroup_threshold *_a = a;
4330 const struct mem_cgroup_threshold *_b = b;
4331
4332 return _a->threshold - _b->threshold;
4333}
4334
c0ff4b85 4335static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
9490ff27
KH
4336{
4337 struct mem_cgroup_eventfd_list *ev;
4338
c0ff4b85 4339 list_for_each_entry(ev, &memcg->oom_notify, list)
9490ff27
KH
4340 eventfd_signal(ev->eventfd, 1);
4341 return 0;
4342}
4343
c0ff4b85 4344static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
9490ff27 4345{
7d74b06f
KH
4346 struct mem_cgroup *iter;
4347
c0ff4b85 4348 for_each_mem_cgroup_tree(iter, memcg)
7d74b06f 4349 mem_cgroup_oom_notify_cb(iter);
9490ff27
KH
4350}
4351
4352static int mem_cgroup_usage_register_event(struct cgroup *cgrp,
4353 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
2e72b634
KS
4354{
4355 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
2c488db2
KS
4356 struct mem_cgroup_thresholds *thresholds;
4357 struct mem_cgroup_threshold_ary *new;
2e72b634
KS
4358 int type = MEMFILE_TYPE(cft->private);
4359 u64 threshold, usage;
2c488db2 4360 int i, size, ret;
2e72b634
KS
4361
4362 ret = res_counter_memparse_write_strategy(args, &threshold);
4363 if (ret)
4364 return ret;
4365
4366 mutex_lock(&memcg->thresholds_lock);
2c488db2 4367
2e72b634 4368 if (type == _MEM)
2c488db2 4369 thresholds = &memcg->thresholds;
2e72b634 4370 else if (type == _MEMSWAP)
2c488db2 4371 thresholds = &memcg->memsw_thresholds;
2e72b634
KS
4372 else
4373 BUG();
4374
4375 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
4376
4377 /* Check if a threshold crossed before adding a new one */
2c488db2 4378 if (thresholds->primary)
2e72b634
KS
4379 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4380
2c488db2 4381 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
2e72b634
KS
4382
4383 /* Allocate memory for new array of thresholds */
2c488db2 4384 new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
2e72b634 4385 GFP_KERNEL);
2c488db2 4386 if (!new) {
2e72b634
KS
4387 ret = -ENOMEM;
4388 goto unlock;
4389 }
2c488db2 4390 new->size = size;
2e72b634
KS
4391
4392 /* Copy thresholds (if any) to new array */
2c488db2
KS
4393 if (thresholds->primary) {
4394 memcpy(new->entries, thresholds->primary->entries, (size - 1) *
2e72b634 4395 sizeof(struct mem_cgroup_threshold));
2c488db2
KS
4396 }
4397
2e72b634 4398 /* Add new threshold */
2c488db2
KS
4399 new->entries[size - 1].eventfd = eventfd;
4400 new->entries[size - 1].threshold = threshold;
2e72b634
KS
4401
4402 /* Sort thresholds. Registering of new threshold isn't time-critical */
2c488db2 4403 sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
2e72b634
KS
4404 compare_thresholds, NULL);
4405
4406 /* Find current threshold */
2c488db2 4407 new->current_threshold = -1;
2e72b634 4408 for (i = 0; i < size; i++) {
2c488db2 4409 if (new->entries[i].threshold < usage) {
2e72b634 4410 /*
2c488db2
KS
4411 * new->current_threshold will not be used until
4412 * rcu_assign_pointer(), so it's safe to increment
2e72b634
KS
4413 * it here.
4414 */
2c488db2 4415 ++new->current_threshold;
2e72b634
KS
4416 }
4417 }
4418
2c488db2
KS
4419 /* Free old spare buffer and save old primary buffer as spare */
4420 kfree(thresholds->spare);
4421 thresholds->spare = thresholds->primary;
4422
4423 rcu_assign_pointer(thresholds->primary, new);
2e72b634 4424
907860ed 4425 /* To be sure that nobody uses thresholds */
2e72b634
KS
4426 synchronize_rcu();
4427
2e72b634
KS
4428unlock:
4429 mutex_unlock(&memcg->thresholds_lock);
4430
4431 return ret;
4432}
4433
907860ed 4434static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,
9490ff27 4435 struct cftype *cft, struct eventfd_ctx *eventfd)
2e72b634
KS
4436{
4437 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
2c488db2
KS
4438 struct mem_cgroup_thresholds *thresholds;
4439 struct mem_cgroup_threshold_ary *new;
2e72b634
KS
4440 int type = MEMFILE_TYPE(cft->private);
4441 u64 usage;
2c488db2 4442 int i, j, size;
2e72b634
KS
4443
4444 mutex_lock(&memcg->thresholds_lock);
4445 if (type == _MEM)
2c488db2 4446 thresholds = &memcg->thresholds;
2e72b634 4447 else if (type == _MEMSWAP)
2c488db2 4448 thresholds = &memcg->memsw_thresholds;
2e72b634
KS
4449 else
4450 BUG();
4451
4452 /*
4453 * Something went wrong if we trying to unregister a threshold
4454 * if we don't have thresholds
4455 */
4456 BUG_ON(!thresholds);
4457
4458 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
4459
4460 /* Check if a threshold crossed before removing */
4461 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4462
4463 /* Calculate new number of threshold */
2c488db2
KS
4464 size = 0;
4465 for (i = 0; i < thresholds->primary->size; i++) {
4466 if (thresholds->primary->entries[i].eventfd != eventfd)
2e72b634
KS
4467 size++;
4468 }
4469
2c488db2 4470 new = thresholds->spare;
907860ed 4471
2e72b634
KS
4472 /* Set thresholds array to NULL if we don't have thresholds */
4473 if (!size) {
2c488db2
KS
4474 kfree(new);
4475 new = NULL;
907860ed 4476 goto swap_buffers;
2e72b634
KS
4477 }
4478
2c488db2 4479 new->size = size;
2e72b634
KS
4480
4481 /* Copy thresholds and find current threshold */
2c488db2
KS
4482 new->current_threshold = -1;
4483 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4484 if (thresholds->primary->entries[i].eventfd == eventfd)
2e72b634
KS
4485 continue;
4486
2c488db2
KS
4487 new->entries[j] = thresholds->primary->entries[i];
4488 if (new->entries[j].threshold < usage) {
2e72b634 4489 /*
2c488db2 4490 * new->current_threshold will not be used
2e72b634
KS
4491 * until rcu_assign_pointer(), so it's safe to increment
4492 * it here.
4493 */
2c488db2 4494 ++new->current_threshold;
2e72b634
KS
4495 }
4496 j++;
4497 }
4498
907860ed 4499swap_buffers:
2c488db2
KS
4500 /* Swap primary and spare array */
4501 thresholds->spare = thresholds->primary;
4502 rcu_assign_pointer(thresholds->primary, new);
2e72b634 4503
907860ed 4504 /* To be sure that nobody uses thresholds */
2e72b634
KS
4505 synchronize_rcu();
4506
2e72b634 4507 mutex_unlock(&memcg->thresholds_lock);
2e72b634 4508}
c1e862c1 4509
9490ff27
KH
4510static int mem_cgroup_oom_register_event(struct cgroup *cgrp,
4511 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
4512{
4513 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4514 struct mem_cgroup_eventfd_list *event;
4515 int type = MEMFILE_TYPE(cft->private);
4516
4517 BUG_ON(type != _OOM_TYPE);
4518 event = kmalloc(sizeof(*event), GFP_KERNEL);
4519 if (!event)
4520 return -ENOMEM;
4521
1af8efe9 4522 spin_lock(&memcg_oom_lock);
9490ff27
KH
4523
4524 event->eventfd = eventfd;
4525 list_add(&event->list, &memcg->oom_notify);
4526
4527 /* already in OOM ? */
79dfdacc 4528 if (atomic_read(&memcg->under_oom))
9490ff27 4529 eventfd_signal(eventfd, 1);
1af8efe9 4530 spin_unlock(&memcg_oom_lock);
9490ff27
KH
4531
4532 return 0;
4533}
4534
907860ed 4535static void mem_cgroup_oom_unregister_event(struct cgroup *cgrp,
9490ff27
KH
4536 struct cftype *cft, struct eventfd_ctx *eventfd)
4537{
c0ff4b85 4538 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
9490ff27
KH
4539 struct mem_cgroup_eventfd_list *ev, *tmp;
4540 int type = MEMFILE_TYPE(cft->private);
4541
4542 BUG_ON(type != _OOM_TYPE);
4543
1af8efe9 4544 spin_lock(&memcg_oom_lock);
9490ff27 4545
c0ff4b85 4546 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
9490ff27
KH
4547 if (ev->eventfd == eventfd) {
4548 list_del(&ev->list);
4549 kfree(ev);
4550 }
4551 }
4552
1af8efe9 4553 spin_unlock(&memcg_oom_lock);
9490ff27
KH
4554}
4555
3c11ecf4
KH
4556static int mem_cgroup_oom_control_read(struct cgroup *cgrp,
4557 struct cftype *cft, struct cgroup_map_cb *cb)
4558{
c0ff4b85 4559 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3c11ecf4 4560
c0ff4b85 4561 cb->fill(cb, "oom_kill_disable", memcg->oom_kill_disable);
3c11ecf4 4562
c0ff4b85 4563 if (atomic_read(&memcg->under_oom))
3c11ecf4
KH
4564 cb->fill(cb, "under_oom", 1);
4565 else
4566 cb->fill(cb, "under_oom", 0);
4567 return 0;
4568}
4569
3c11ecf4
KH
4570static int mem_cgroup_oom_control_write(struct cgroup *cgrp,
4571 struct cftype *cft, u64 val)
4572{
c0ff4b85 4573 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3c11ecf4
KH
4574 struct mem_cgroup *parent;
4575
4576 /* cannot set to root cgroup and only 0 and 1 are allowed */
4577 if (!cgrp->parent || !((val == 0) || (val == 1)))
4578 return -EINVAL;
4579
4580 parent = mem_cgroup_from_cont(cgrp->parent);
4581
4582 cgroup_lock();
4583 /* oom-kill-disable is a flag for subhierarchy. */
4584 if ((parent->use_hierarchy) ||
c0ff4b85 4585 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
3c11ecf4
KH
4586 cgroup_unlock();
4587 return -EINVAL;
4588 }
c0ff4b85 4589 memcg->oom_kill_disable = val;
4d845ebf 4590 if (!val)
c0ff4b85 4591 memcg_oom_recover(memcg);
3c11ecf4
KH
4592 cgroup_unlock();
4593 return 0;
4594}
4595
406eb0c9
YH
4596#ifdef CONFIG_NUMA
4597static const struct file_operations mem_control_numa_stat_file_operations = {
4598 .read = seq_read,
4599 .llseek = seq_lseek,
4600 .release = single_release,
4601};
4602
4603static int mem_control_numa_stat_open(struct inode *unused, struct file *file)
4604{
4605 struct cgroup *cont = file->f_dentry->d_parent->d_fsdata;
4606
4607 file->f_op = &mem_control_numa_stat_file_operations;
4608 return single_open(file, mem_control_numa_stat_show, cont);
4609}
4610#endif /* CONFIG_NUMA */
4611
8cdea7c0
BS
4612static struct cftype mem_cgroup_files[] = {
4613 {
0eea1030 4614 .name = "usage_in_bytes",
8c7c6e34 4615 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
2c3daa72 4616 .read_u64 = mem_cgroup_read,
9490ff27
KH
4617 .register_event = mem_cgroup_usage_register_event,
4618 .unregister_event = mem_cgroup_usage_unregister_event,
8cdea7c0 4619 },
c84872e1
PE
4620 {
4621 .name = "max_usage_in_bytes",
8c7c6e34 4622 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
29f2a4da 4623 .trigger = mem_cgroup_reset,
c84872e1
PE
4624 .read_u64 = mem_cgroup_read,
4625 },
8cdea7c0 4626 {
0eea1030 4627 .name = "limit_in_bytes",
8c7c6e34 4628 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
856c13aa 4629 .write_string = mem_cgroup_write,
2c3daa72 4630 .read_u64 = mem_cgroup_read,
8cdea7c0 4631 },
296c81d8
BS
4632 {
4633 .name = "soft_limit_in_bytes",
4634 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
4635 .write_string = mem_cgroup_write,
4636 .read_u64 = mem_cgroup_read,
4637 },
8cdea7c0
BS
4638 {
4639 .name = "failcnt",
8c7c6e34 4640 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
29f2a4da 4641 .trigger = mem_cgroup_reset,
2c3daa72 4642 .read_u64 = mem_cgroup_read,
8cdea7c0 4643 },
d2ceb9b7
KH
4644 {
4645 .name = "stat",
c64745cf 4646 .read_map = mem_control_stat_show,
d2ceb9b7 4647 },
c1e862c1
KH
4648 {
4649 .name = "force_empty",
4650 .trigger = mem_cgroup_force_empty_write,
4651 },
18f59ea7
BS
4652 {
4653 .name = "use_hierarchy",
4654 .write_u64 = mem_cgroup_hierarchy_write,
4655 .read_u64 = mem_cgroup_hierarchy_read,
4656 },
a7885eb8
KM
4657 {
4658 .name = "swappiness",
4659 .read_u64 = mem_cgroup_swappiness_read,
4660 .write_u64 = mem_cgroup_swappiness_write,
4661 },
7dc74be0
DN
4662 {
4663 .name = "move_charge_at_immigrate",
4664 .read_u64 = mem_cgroup_move_charge_read,
4665 .write_u64 = mem_cgroup_move_charge_write,
4666 },
9490ff27
KH
4667 {
4668 .name = "oom_control",
3c11ecf4
KH
4669 .read_map = mem_cgroup_oom_control_read,
4670 .write_u64 = mem_cgroup_oom_control_write,
9490ff27
KH
4671 .register_event = mem_cgroup_oom_register_event,
4672 .unregister_event = mem_cgroup_oom_unregister_event,
4673 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
4674 },
406eb0c9
YH
4675#ifdef CONFIG_NUMA
4676 {
4677 .name = "numa_stat",
4678 .open = mem_control_numa_stat_open,
89577127 4679 .mode = S_IRUGO,
406eb0c9
YH
4680 },
4681#endif
8cdea7c0
BS
4682};
4683
8c7c6e34
KH
4684#ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4685static struct cftype memsw_cgroup_files[] = {
4686 {
4687 .name = "memsw.usage_in_bytes",
4688 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
4689 .read_u64 = mem_cgroup_read,
9490ff27
KH
4690 .register_event = mem_cgroup_usage_register_event,
4691 .unregister_event = mem_cgroup_usage_unregister_event,
8c7c6e34
KH
4692 },
4693 {
4694 .name = "memsw.max_usage_in_bytes",
4695 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
4696 .trigger = mem_cgroup_reset,
4697 .read_u64 = mem_cgroup_read,
4698 },
4699 {
4700 .name = "memsw.limit_in_bytes",
4701 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
4702 .write_string = mem_cgroup_write,
4703 .read_u64 = mem_cgroup_read,
4704 },
4705 {
4706 .name = "memsw.failcnt",
4707 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
4708 .trigger = mem_cgroup_reset,
4709 .read_u64 = mem_cgroup_read,
4710 },
4711};
4712
4713static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
4714{
4715 if (!do_swap_account)
4716 return 0;
4717 return cgroup_add_files(cont, ss, memsw_cgroup_files,
4718 ARRAY_SIZE(memsw_cgroup_files));
4719};
4720#else
4721static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
4722{
4723 return 0;
4724}
4725#endif
4726
c0ff4b85 4727static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
6d12e2d8
KH
4728{
4729 struct mem_cgroup_per_node *pn;
1ecaab2b 4730 struct mem_cgroup_per_zone *mz;
b69408e8 4731 enum lru_list l;
41e3355d 4732 int zone, tmp = node;
1ecaab2b
KH
4733 /*
4734 * This routine is called against possible nodes.
4735 * But it's BUG to call kmalloc() against offline node.
4736 *
4737 * TODO: this routine can waste much memory for nodes which will
4738 * never be onlined. It's better to use memory hotplug callback
4739 * function.
4740 */
41e3355d
KH
4741 if (!node_state(node, N_NORMAL_MEMORY))
4742 tmp = -1;
17295c88 4743 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
6d12e2d8
KH
4744 if (!pn)
4745 return 1;
1ecaab2b 4746
1ecaab2b
KH
4747 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4748 mz = &pn->zoneinfo[zone];
b69408e8
CL
4749 for_each_lru(l)
4750 INIT_LIST_HEAD(&mz->lists[l]);
f64c3f54 4751 mz->usage_in_excess = 0;
4e416953 4752 mz->on_tree = false;
c0ff4b85 4753 mz->mem = memcg;
1ecaab2b 4754 }
0a619e58 4755 memcg->info.nodeinfo[node] = pn;
6d12e2d8
KH
4756 return 0;
4757}
4758
c0ff4b85 4759static void free_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
1ecaab2b 4760{
c0ff4b85 4761 kfree(memcg->info.nodeinfo[node]);
1ecaab2b
KH
4762}
4763
33327948
KH
4764static struct mem_cgroup *mem_cgroup_alloc(void)
4765{
4766 struct mem_cgroup *mem;
c62b1a3b 4767 int size = sizeof(struct mem_cgroup);
33327948 4768
c62b1a3b 4769 /* Can be very big if MAX_NUMNODES is very big */
c8dad2bb 4770 if (size < PAGE_SIZE)
17295c88 4771 mem = kzalloc(size, GFP_KERNEL);
33327948 4772 else
17295c88 4773 mem = vzalloc(size);
33327948 4774
e7bbcdf3
DC
4775 if (!mem)
4776 return NULL;
4777
c62b1a3b 4778 mem->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
d2e61b8d
DC
4779 if (!mem->stat)
4780 goto out_free;
711d3d2c 4781 spin_lock_init(&mem->pcp_counter_lock);
33327948 4782 return mem;
d2e61b8d
DC
4783
4784out_free:
4785 if (size < PAGE_SIZE)
4786 kfree(mem);
4787 else
4788 vfree(mem);
4789 return NULL;
33327948
KH
4790}
4791
8c7c6e34
KH
4792/*
4793 * At destroying mem_cgroup, references from swap_cgroup can remain.
4794 * (scanning all at force_empty is too costly...)
4795 *
4796 * Instead of clearing all references at force_empty, we remember
4797 * the number of reference from swap_cgroup and free mem_cgroup when
4798 * it goes down to 0.
4799 *
8c7c6e34
KH
4800 * Removal of cgroup itself succeeds regardless of refs from swap.
4801 */
4802
c0ff4b85 4803static void __mem_cgroup_free(struct mem_cgroup *memcg)
33327948 4804{
08e552c6
KH
4805 int node;
4806
c0ff4b85
R
4807 mem_cgroup_remove_from_trees(memcg);
4808 free_css_id(&mem_cgroup_subsys, &memcg->css);
04046e1a 4809
08e552c6 4810 for_each_node_state(node, N_POSSIBLE)
c0ff4b85 4811 free_mem_cgroup_per_zone_info(memcg, node);
08e552c6 4812
c0ff4b85 4813 free_percpu(memcg->stat);
c62b1a3b 4814 if (sizeof(struct mem_cgroup) < PAGE_SIZE)
c0ff4b85 4815 kfree(memcg);
33327948 4816 else
c0ff4b85 4817 vfree(memcg);
33327948
KH
4818}
4819
c0ff4b85 4820static void mem_cgroup_get(struct mem_cgroup *memcg)
8c7c6e34 4821{
c0ff4b85 4822 atomic_inc(&memcg->refcnt);
8c7c6e34
KH
4823}
4824
c0ff4b85 4825static void __mem_cgroup_put(struct mem_cgroup *memcg, int count)
8c7c6e34 4826{
c0ff4b85
R
4827 if (atomic_sub_and_test(count, &memcg->refcnt)) {
4828 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
4829 __mem_cgroup_free(memcg);
7bcc1bb1
DN
4830 if (parent)
4831 mem_cgroup_put(parent);
4832 }
8c7c6e34
KH
4833}
4834
c0ff4b85 4835static void mem_cgroup_put(struct mem_cgroup *memcg)
483c30b5 4836{
c0ff4b85 4837 __mem_cgroup_put(memcg, 1);
483c30b5
DN
4838}
4839
7bcc1bb1
DN
4840/*
4841 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
4842 */
c0ff4b85 4843static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg)
7bcc1bb1 4844{
c0ff4b85 4845 if (!memcg->res.parent)
7bcc1bb1 4846 return NULL;
c0ff4b85 4847 return mem_cgroup_from_res_counter(memcg->res.parent, res);
7bcc1bb1 4848}
33327948 4849
c077719b
KH
4850#ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4851static void __init enable_swap_cgroup(void)
4852{
f8d66542 4853 if (!mem_cgroup_disabled() && really_do_swap_account)
c077719b
KH
4854 do_swap_account = 1;
4855}
4856#else
4857static void __init enable_swap_cgroup(void)
4858{
4859}
4860#endif
4861
f64c3f54
BS
4862static int mem_cgroup_soft_limit_tree_init(void)
4863{
4864 struct mem_cgroup_tree_per_node *rtpn;
4865 struct mem_cgroup_tree_per_zone *rtpz;
4866 int tmp, node, zone;
4867
4868 for_each_node_state(node, N_POSSIBLE) {
4869 tmp = node;
4870 if (!node_state(node, N_NORMAL_MEMORY))
4871 tmp = -1;
4872 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
4873 if (!rtpn)
4874 return 1;
4875
4876 soft_limit_tree.rb_tree_per_node[node] = rtpn;
4877
4878 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4879 rtpz = &rtpn->rb_tree_per_zone[zone];
4880 rtpz->rb_root = RB_ROOT;
4881 spin_lock_init(&rtpz->lock);
4882 }
4883 }
4884 return 0;
4885}
4886
0eb253e2 4887static struct cgroup_subsys_state * __ref
8cdea7c0
BS
4888mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
4889{
c0ff4b85 4890 struct mem_cgroup *memcg, *parent;
04046e1a 4891 long error = -ENOMEM;
6d12e2d8 4892 int node;
8cdea7c0 4893
c0ff4b85
R
4894 memcg = mem_cgroup_alloc();
4895 if (!memcg)
04046e1a 4896 return ERR_PTR(error);
78fb7466 4897
6d12e2d8 4898 for_each_node_state(node, N_POSSIBLE)
c0ff4b85 4899 if (alloc_mem_cgroup_per_zone_info(memcg, node))
6d12e2d8 4900 goto free_out;
f64c3f54 4901
c077719b 4902 /* root ? */
28dbc4b6 4903 if (cont->parent == NULL) {
cdec2e42 4904 int cpu;
c077719b 4905 enable_swap_cgroup();
28dbc4b6 4906 parent = NULL;
c0ff4b85 4907 root_mem_cgroup = memcg;
f64c3f54
BS
4908 if (mem_cgroup_soft_limit_tree_init())
4909 goto free_out;
cdec2e42
KH
4910 for_each_possible_cpu(cpu) {
4911 struct memcg_stock_pcp *stock =
4912 &per_cpu(memcg_stock, cpu);
4913 INIT_WORK(&stock->work, drain_local_stock);
4914 }
711d3d2c 4915 hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
18f59ea7 4916 } else {
28dbc4b6 4917 parent = mem_cgroup_from_cont(cont->parent);
c0ff4b85
R
4918 memcg->use_hierarchy = parent->use_hierarchy;
4919 memcg->oom_kill_disable = parent->oom_kill_disable;
18f59ea7 4920 }
28dbc4b6 4921
18f59ea7 4922 if (parent && parent->use_hierarchy) {
c0ff4b85
R
4923 res_counter_init(&memcg->res, &parent->res);
4924 res_counter_init(&memcg->memsw, &parent->memsw);
7bcc1bb1
DN
4925 /*
4926 * We increment refcnt of the parent to ensure that we can
4927 * safely access it on res_counter_charge/uncharge.
4928 * This refcnt will be decremented when freeing this
4929 * mem_cgroup(see mem_cgroup_put).
4930 */
4931 mem_cgroup_get(parent);
18f59ea7 4932 } else {
c0ff4b85
R
4933 res_counter_init(&memcg->res, NULL);
4934 res_counter_init(&memcg->memsw, NULL);
18f59ea7 4935 }
c0ff4b85
R
4936 memcg->last_scanned_child = 0;
4937 memcg->last_scanned_node = MAX_NUMNODES;
4938 INIT_LIST_HEAD(&memcg->oom_notify);
6d61ef40 4939
a7885eb8 4940 if (parent)
c0ff4b85
R
4941 memcg->swappiness = mem_cgroup_swappiness(parent);
4942 atomic_set(&memcg->refcnt, 1);
4943 memcg->move_charge_at_immigrate = 0;
4944 mutex_init(&memcg->thresholds_lock);
4945 return &memcg->css;
6d12e2d8 4946free_out:
c0ff4b85 4947 __mem_cgroup_free(memcg);
4b3bde4c 4948 root_mem_cgroup = NULL;
04046e1a 4949 return ERR_PTR(error);
8cdea7c0
BS
4950}
4951
ec64f515 4952static int mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
df878fb0
KH
4953 struct cgroup *cont)
4954{
c0ff4b85 4955 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
ec64f515 4956
c0ff4b85 4957 return mem_cgroup_force_empty(memcg, false);
df878fb0
KH
4958}
4959
8cdea7c0
BS
4960static void mem_cgroup_destroy(struct cgroup_subsys *ss,
4961 struct cgroup *cont)
4962{
c0ff4b85 4963 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
c268e994 4964
c0ff4b85 4965 mem_cgroup_put(memcg);
8cdea7c0
BS
4966}
4967
4968static int mem_cgroup_populate(struct cgroup_subsys *ss,
4969 struct cgroup *cont)
4970{
8c7c6e34
KH
4971 int ret;
4972
4973 ret = cgroup_add_files(cont, ss, mem_cgroup_files,
4974 ARRAY_SIZE(mem_cgroup_files));
4975
4976 if (!ret)
4977 ret = register_memsw_files(cont, ss);
4978 return ret;
8cdea7c0
BS
4979}
4980
02491447 4981#ifdef CONFIG_MMU
7dc74be0 4982/* Handlers for move charge at task migration. */
854ffa8d
DN
4983#define PRECHARGE_COUNT_AT_ONCE 256
4984static int mem_cgroup_do_precharge(unsigned long count)
7dc74be0 4985{
854ffa8d
DN
4986 int ret = 0;
4987 int batch_count = PRECHARGE_COUNT_AT_ONCE;
c0ff4b85 4988 struct mem_cgroup *memcg = mc.to;
4ffef5fe 4989
c0ff4b85 4990 if (mem_cgroup_is_root(memcg)) {
854ffa8d
DN
4991 mc.precharge += count;
4992 /* we don't need css_get for root */
4993 return ret;
4994 }
4995 /* try to charge at once */
4996 if (count > 1) {
4997 struct res_counter *dummy;
4998 /*
c0ff4b85 4999 * "memcg" cannot be under rmdir() because we've already checked
854ffa8d
DN
5000 * by cgroup_lock_live_cgroup() that it is not removed and we
5001 * are still under the same cgroup_mutex. So we can postpone
5002 * css_get().
5003 */
c0ff4b85 5004 if (res_counter_charge(&memcg->res, PAGE_SIZE * count, &dummy))
854ffa8d 5005 goto one_by_one;
c0ff4b85 5006 if (do_swap_account && res_counter_charge(&memcg->memsw,
854ffa8d 5007 PAGE_SIZE * count, &dummy)) {
c0ff4b85 5008 res_counter_uncharge(&memcg->res, PAGE_SIZE * count);
854ffa8d
DN
5009 goto one_by_one;
5010 }
5011 mc.precharge += count;
854ffa8d
DN
5012 return ret;
5013 }
5014one_by_one:
5015 /* fall back to one by one charge */
5016 while (count--) {
5017 if (signal_pending(current)) {
5018 ret = -EINTR;
5019 break;
5020 }
5021 if (!batch_count--) {
5022 batch_count = PRECHARGE_COUNT_AT_ONCE;
5023 cond_resched();
5024 }
c0ff4b85
R
5025 ret = __mem_cgroup_try_charge(NULL,
5026 GFP_KERNEL, 1, &memcg, false);
5027 if (ret || !memcg)
854ffa8d
DN
5028 /* mem_cgroup_clear_mc() will do uncharge later */
5029 return -ENOMEM;
5030 mc.precharge++;
5031 }
4ffef5fe
DN
5032 return ret;
5033}
5034
5035/**
5036 * is_target_pte_for_mc - check a pte whether it is valid for move charge
5037 * @vma: the vma the pte to be checked belongs
5038 * @addr: the address corresponding to the pte to be checked
5039 * @ptent: the pte to be checked
02491447 5040 * @target: the pointer the target page or swap ent will be stored(can be NULL)
4ffef5fe
DN
5041 *
5042 * Returns
5043 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
5044 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5045 * move charge. if @target is not NULL, the page is stored in target->page
5046 * with extra refcnt got(Callers should handle it).
02491447
DN
5047 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5048 * target for charge migration. if @target is not NULL, the entry is stored
5049 * in target->ent.
4ffef5fe
DN
5050 *
5051 * Called with pte lock held.
5052 */
4ffef5fe
DN
5053union mc_target {
5054 struct page *page;
02491447 5055 swp_entry_t ent;
4ffef5fe
DN
5056};
5057
4ffef5fe
DN
5058enum mc_target_type {
5059 MC_TARGET_NONE, /* not used */
5060 MC_TARGET_PAGE,
02491447 5061 MC_TARGET_SWAP,
4ffef5fe
DN
5062};
5063
90254a65
DN
5064static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5065 unsigned long addr, pte_t ptent)
4ffef5fe 5066{
90254a65 5067 struct page *page = vm_normal_page(vma, addr, ptent);
4ffef5fe 5068
90254a65
DN
5069 if (!page || !page_mapped(page))
5070 return NULL;
5071 if (PageAnon(page)) {
5072 /* we don't move shared anon */
5073 if (!move_anon() || page_mapcount(page) > 2)
5074 return NULL;
87946a72
DN
5075 } else if (!move_file())
5076 /* we ignore mapcount for file pages */
90254a65
DN
5077 return NULL;
5078 if (!get_page_unless_zero(page))
5079 return NULL;
5080
5081 return page;
5082}
5083
5084static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5085 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5086{
5087 int usage_count;
5088 struct page *page = NULL;
5089 swp_entry_t ent = pte_to_swp_entry(ptent);
5090
5091 if (!move_anon() || non_swap_entry(ent))
5092 return NULL;
5093 usage_count = mem_cgroup_count_swap_user(ent, &page);
5094 if (usage_count > 1) { /* we don't move shared anon */
02491447
DN
5095 if (page)
5096 put_page(page);
90254a65 5097 return NULL;
02491447 5098 }
90254a65
DN
5099 if (do_swap_account)
5100 entry->val = ent.val;
5101
5102 return page;
5103}
5104
87946a72
DN
5105static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5106 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5107{
5108 struct page *page = NULL;
5109 struct inode *inode;
5110 struct address_space *mapping;
5111 pgoff_t pgoff;
5112
5113 if (!vma->vm_file) /* anonymous vma */
5114 return NULL;
5115 if (!move_file())
5116 return NULL;
5117
5118 inode = vma->vm_file->f_path.dentry->d_inode;
5119 mapping = vma->vm_file->f_mapping;
5120 if (pte_none(ptent))
5121 pgoff = linear_page_index(vma, addr);
5122 else /* pte_file(ptent) is true */
5123 pgoff = pte_to_pgoff(ptent);
5124
5125 /* page is moved even if it's not RSS of this task(page-faulted). */
aa3b1895
HD
5126 page = find_get_page(mapping, pgoff);
5127
5128#ifdef CONFIG_SWAP
5129 /* shmem/tmpfs may report page out on swap: account for that too. */
5130 if (radix_tree_exceptional_entry(page)) {
5131 swp_entry_t swap = radix_to_swp_entry(page);
87946a72 5132 if (do_swap_account)
aa3b1895
HD
5133 *entry = swap;
5134 page = find_get_page(&swapper_space, swap.val);
87946a72 5135 }
aa3b1895 5136#endif
87946a72
DN
5137 return page;
5138}
5139
90254a65
DN
5140static int is_target_pte_for_mc(struct vm_area_struct *vma,
5141 unsigned long addr, pte_t ptent, union mc_target *target)
5142{
5143 struct page *page = NULL;
5144 struct page_cgroup *pc;
5145 int ret = 0;
5146 swp_entry_t ent = { .val = 0 };
5147
5148 if (pte_present(ptent))
5149 page = mc_handle_present_pte(vma, addr, ptent);
5150 else if (is_swap_pte(ptent))
5151 page = mc_handle_swap_pte(vma, addr, ptent, &ent);
87946a72
DN
5152 else if (pte_none(ptent) || pte_file(ptent))
5153 page = mc_handle_file_pte(vma, addr, ptent, &ent);
90254a65
DN
5154
5155 if (!page && !ent.val)
5156 return 0;
02491447
DN
5157 if (page) {
5158 pc = lookup_page_cgroup(page);
5159 /*
5160 * Do only loose check w/o page_cgroup lock.
5161 * mem_cgroup_move_account() checks the pc is valid or not under
5162 * the lock.
5163 */
5164 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
5165 ret = MC_TARGET_PAGE;
5166 if (target)
5167 target->page = page;
5168 }
5169 if (!ret || !target)
5170 put_page(page);
5171 }
90254a65
DN
5172 /* There is a swap entry and a page doesn't exist or isn't charged */
5173 if (ent.val && !ret &&
7f0f1546
KH
5174 css_id(&mc.from->css) == lookup_swap_cgroup(ent)) {
5175 ret = MC_TARGET_SWAP;
5176 if (target)
5177 target->ent = ent;
4ffef5fe 5178 }
4ffef5fe
DN
5179 return ret;
5180}
5181
5182static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
5183 unsigned long addr, unsigned long end,
5184 struct mm_walk *walk)
5185{
5186 struct vm_area_struct *vma = walk->private;
5187 pte_t *pte;
5188 spinlock_t *ptl;
5189
03319327
DH
5190 split_huge_page_pmd(walk->mm, pmd);
5191
4ffef5fe
DN
5192 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5193 for (; addr != end; pte++, addr += PAGE_SIZE)
5194 if (is_target_pte_for_mc(vma, addr, *pte, NULL))
5195 mc.precharge++; /* increment precharge temporarily */
5196 pte_unmap_unlock(pte - 1, ptl);
5197 cond_resched();
5198
7dc74be0
DN
5199 return 0;
5200}
5201
4ffef5fe
DN
5202static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
5203{
5204 unsigned long precharge;
5205 struct vm_area_struct *vma;
5206
dfe076b0 5207 down_read(&mm->mmap_sem);
4ffef5fe
DN
5208 for (vma = mm->mmap; vma; vma = vma->vm_next) {
5209 struct mm_walk mem_cgroup_count_precharge_walk = {
5210 .pmd_entry = mem_cgroup_count_precharge_pte_range,
5211 .mm = mm,
5212 .private = vma,
5213 };
5214 if (is_vm_hugetlb_page(vma))
5215 continue;
4ffef5fe
DN
5216 walk_page_range(vma->vm_start, vma->vm_end,
5217 &mem_cgroup_count_precharge_walk);
5218 }
dfe076b0 5219 up_read(&mm->mmap_sem);
4ffef5fe
DN
5220
5221 precharge = mc.precharge;
5222 mc.precharge = 0;
5223
5224 return precharge;
5225}
5226
4ffef5fe
DN
5227static int mem_cgroup_precharge_mc(struct mm_struct *mm)
5228{
dfe076b0
DN
5229 unsigned long precharge = mem_cgroup_count_precharge(mm);
5230
5231 VM_BUG_ON(mc.moving_task);
5232 mc.moving_task = current;
5233 return mem_cgroup_do_precharge(precharge);
4ffef5fe
DN
5234}
5235
dfe076b0
DN
5236/* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5237static void __mem_cgroup_clear_mc(void)
4ffef5fe 5238{
2bd9bb20
KH
5239 struct mem_cgroup *from = mc.from;
5240 struct mem_cgroup *to = mc.to;
5241
4ffef5fe 5242 /* we must uncharge all the leftover precharges from mc.to */
854ffa8d
DN
5243 if (mc.precharge) {
5244 __mem_cgroup_cancel_charge(mc.to, mc.precharge);
5245 mc.precharge = 0;
5246 }
5247 /*
5248 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5249 * we must uncharge here.
5250 */
5251 if (mc.moved_charge) {
5252 __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
5253 mc.moved_charge = 0;
4ffef5fe 5254 }
483c30b5
DN
5255 /* we must fixup refcnts and charges */
5256 if (mc.moved_swap) {
483c30b5
DN
5257 /* uncharge swap account from the old cgroup */
5258 if (!mem_cgroup_is_root(mc.from))
5259 res_counter_uncharge(&mc.from->memsw,
5260 PAGE_SIZE * mc.moved_swap);
5261 __mem_cgroup_put(mc.from, mc.moved_swap);
5262
5263 if (!mem_cgroup_is_root(mc.to)) {
5264 /*
5265 * we charged both to->res and to->memsw, so we should
5266 * uncharge to->res.
5267 */
5268 res_counter_uncharge(&mc.to->res,
5269 PAGE_SIZE * mc.moved_swap);
483c30b5
DN
5270 }
5271 /* we've already done mem_cgroup_get(mc.to) */
483c30b5
DN
5272 mc.moved_swap = 0;
5273 }
dfe076b0
DN
5274 memcg_oom_recover(from);
5275 memcg_oom_recover(to);
5276 wake_up_all(&mc.waitq);
5277}
5278
5279static void mem_cgroup_clear_mc(void)
5280{
5281 struct mem_cgroup *from = mc.from;
5282
5283 /*
5284 * we must clear moving_task before waking up waiters at the end of
5285 * task migration.
5286 */
5287 mc.moving_task = NULL;
5288 __mem_cgroup_clear_mc();
2bd9bb20 5289 spin_lock(&mc.lock);
4ffef5fe
DN
5290 mc.from = NULL;
5291 mc.to = NULL;
2bd9bb20 5292 spin_unlock(&mc.lock);
32047e2a 5293 mem_cgroup_end_move(from);
4ffef5fe
DN
5294}
5295
7dc74be0
DN
5296static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
5297 struct cgroup *cgroup,
f780bdb7 5298 struct task_struct *p)
7dc74be0
DN
5299{
5300 int ret = 0;
c0ff4b85 5301 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgroup);
7dc74be0 5302
c0ff4b85 5303 if (memcg->move_charge_at_immigrate) {
7dc74be0
DN
5304 struct mm_struct *mm;
5305 struct mem_cgroup *from = mem_cgroup_from_task(p);
5306
c0ff4b85 5307 VM_BUG_ON(from == memcg);
7dc74be0
DN
5308
5309 mm = get_task_mm(p);
5310 if (!mm)
5311 return 0;
7dc74be0 5312 /* We move charges only when we move a owner of the mm */
4ffef5fe
DN
5313 if (mm->owner == p) {
5314 VM_BUG_ON(mc.from);
5315 VM_BUG_ON(mc.to);
5316 VM_BUG_ON(mc.precharge);
854ffa8d 5317 VM_BUG_ON(mc.moved_charge);
483c30b5 5318 VM_BUG_ON(mc.moved_swap);
32047e2a 5319 mem_cgroup_start_move(from);
2bd9bb20 5320 spin_lock(&mc.lock);
4ffef5fe 5321 mc.from = from;
c0ff4b85 5322 mc.to = memcg;
2bd9bb20 5323 spin_unlock(&mc.lock);
dfe076b0 5324 /* We set mc.moving_task later */
4ffef5fe
DN
5325
5326 ret = mem_cgroup_precharge_mc(mm);
5327 if (ret)
5328 mem_cgroup_clear_mc();
dfe076b0
DN
5329 }
5330 mmput(mm);
7dc74be0
DN
5331 }
5332 return ret;
5333}
5334
5335static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
5336 struct cgroup *cgroup,
f780bdb7 5337 struct task_struct *p)
7dc74be0 5338{
4ffef5fe 5339 mem_cgroup_clear_mc();
7dc74be0
DN
5340}
5341
4ffef5fe
DN
5342static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
5343 unsigned long addr, unsigned long end,
5344 struct mm_walk *walk)
7dc74be0 5345{
4ffef5fe
DN
5346 int ret = 0;
5347 struct vm_area_struct *vma = walk->private;
5348 pte_t *pte;
5349 spinlock_t *ptl;
5350
03319327 5351 split_huge_page_pmd(walk->mm, pmd);
4ffef5fe
DN
5352retry:
5353 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5354 for (; addr != end; addr += PAGE_SIZE) {
5355 pte_t ptent = *(pte++);
5356 union mc_target target;
5357 int type;
5358 struct page *page;
5359 struct page_cgroup *pc;
02491447 5360 swp_entry_t ent;
4ffef5fe
DN
5361
5362 if (!mc.precharge)
5363 break;
5364
5365 type = is_target_pte_for_mc(vma, addr, ptent, &target);
5366 switch (type) {
5367 case MC_TARGET_PAGE:
5368 page = target.page;
5369 if (isolate_lru_page(page))
5370 goto put;
5371 pc = lookup_page_cgroup(page);
7ec99d62
JW
5372 if (!mem_cgroup_move_account(page, 1, pc,
5373 mc.from, mc.to, false)) {
4ffef5fe 5374 mc.precharge--;
854ffa8d
DN
5375 /* we uncharge from mc.from later. */
5376 mc.moved_charge++;
4ffef5fe
DN
5377 }
5378 putback_lru_page(page);
5379put: /* is_target_pte_for_mc() gets the page */
5380 put_page(page);
5381 break;
02491447
DN
5382 case MC_TARGET_SWAP:
5383 ent = target.ent;
483c30b5
DN
5384 if (!mem_cgroup_move_swap_account(ent,
5385 mc.from, mc.to, false)) {
02491447 5386 mc.precharge--;
483c30b5
DN
5387 /* we fixup refcnts and charges later. */
5388 mc.moved_swap++;
5389 }
02491447 5390 break;
4ffef5fe
DN
5391 default:
5392 break;
5393 }
5394 }
5395 pte_unmap_unlock(pte - 1, ptl);
5396 cond_resched();
5397
5398 if (addr != end) {
5399 /*
5400 * We have consumed all precharges we got in can_attach().
5401 * We try charge one by one, but don't do any additional
5402 * charges to mc.to if we have failed in charge once in attach()
5403 * phase.
5404 */
854ffa8d 5405 ret = mem_cgroup_do_precharge(1);
4ffef5fe
DN
5406 if (!ret)
5407 goto retry;
5408 }
5409
5410 return ret;
5411}
5412
5413static void mem_cgroup_move_charge(struct mm_struct *mm)
5414{
5415 struct vm_area_struct *vma;
5416
5417 lru_add_drain_all();
dfe076b0
DN
5418retry:
5419 if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
5420 /*
5421 * Someone who are holding the mmap_sem might be waiting in
5422 * waitq. So we cancel all extra charges, wake up all waiters,
5423 * and retry. Because we cancel precharges, we might not be able
5424 * to move enough charges, but moving charge is a best-effort
5425 * feature anyway, so it wouldn't be a big problem.
5426 */
5427 __mem_cgroup_clear_mc();
5428 cond_resched();
5429 goto retry;
5430 }
4ffef5fe
DN
5431 for (vma = mm->mmap; vma; vma = vma->vm_next) {
5432 int ret;
5433 struct mm_walk mem_cgroup_move_charge_walk = {
5434 .pmd_entry = mem_cgroup_move_charge_pte_range,
5435 .mm = mm,
5436 .private = vma,
5437 };
5438 if (is_vm_hugetlb_page(vma))
5439 continue;
4ffef5fe
DN
5440 ret = walk_page_range(vma->vm_start, vma->vm_end,
5441 &mem_cgroup_move_charge_walk);
5442 if (ret)
5443 /*
5444 * means we have consumed all precharges and failed in
5445 * doing additional charge. Just abandon here.
5446 */
5447 break;
5448 }
dfe076b0 5449 up_read(&mm->mmap_sem);
7dc74be0
DN
5450}
5451
67e465a7
BS
5452static void mem_cgroup_move_task(struct cgroup_subsys *ss,
5453 struct cgroup *cont,
5454 struct cgroup *old_cont,
f780bdb7 5455 struct task_struct *p)
67e465a7 5456{
a433658c 5457 struct mm_struct *mm = get_task_mm(p);
dfe076b0 5458
dfe076b0 5459 if (mm) {
a433658c
KM
5460 if (mc.to)
5461 mem_cgroup_move_charge(mm);
5462 put_swap_token(mm);
dfe076b0
DN
5463 mmput(mm);
5464 }
a433658c
KM
5465 if (mc.to)
5466 mem_cgroup_clear_mc();
67e465a7 5467}
5cfb80a7
DN
5468#else /* !CONFIG_MMU */
5469static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
5470 struct cgroup *cgroup,
f780bdb7 5471 struct task_struct *p)
5cfb80a7
DN
5472{
5473 return 0;
5474}
5475static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
5476 struct cgroup *cgroup,
f780bdb7 5477 struct task_struct *p)
5cfb80a7
DN
5478{
5479}
5480static void mem_cgroup_move_task(struct cgroup_subsys *ss,
5481 struct cgroup *cont,
5482 struct cgroup *old_cont,
f780bdb7 5483 struct task_struct *p)
5cfb80a7
DN
5484{
5485}
5486#endif
67e465a7 5487
8cdea7c0
BS
5488struct cgroup_subsys mem_cgroup_subsys = {
5489 .name = "memory",
5490 .subsys_id = mem_cgroup_subsys_id,
5491 .create = mem_cgroup_create,
df878fb0 5492 .pre_destroy = mem_cgroup_pre_destroy,
8cdea7c0
BS
5493 .destroy = mem_cgroup_destroy,
5494 .populate = mem_cgroup_populate,
7dc74be0
DN
5495 .can_attach = mem_cgroup_can_attach,
5496 .cancel_attach = mem_cgroup_cancel_attach,
67e465a7 5497 .attach = mem_cgroup_move_task,
6d12e2d8 5498 .early_init = 0,
04046e1a 5499 .use_id = 1,
8cdea7c0 5500};
c077719b
KH
5501
5502#ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
a42c390c
MH
5503static int __init enable_swap_account(char *s)
5504{
5505 /* consider enabled if no parameter or 1 is given */
a2c8990a 5506 if (!strcmp(s, "1"))
a42c390c 5507 really_do_swap_account = 1;
a2c8990a 5508 else if (!strcmp(s, "0"))
a42c390c
MH
5509 really_do_swap_account = 0;
5510 return 1;
5511}
a2c8990a 5512__setup("swapaccount=", enable_swap_account);
c077719b 5513
c077719b 5514#endif