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