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