memcg: add memory.numastat api for numa statistics
[GitHub/mt8127/android_kernel_alcatel_ttab.git] / mm / memcontrol.c
1 /* memcontrol.c - Memory Controller
2 *
3 * Copyright IBM Corporation, 2007
4 * Author Balbir Singh <balbir@linux.vnet.ibm.com>
5 *
6 * Copyright 2007 OpenVZ SWsoft Inc
7 * Author: Pavel Emelianov <xemul@openvz.org>
8 *
9 * Memory thresholds
10 * Copyright (C) 2009 Nokia Corporation
11 * Author: Kirill A. Shutemov
12 *
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>
27 #include <linux/mm.h>
28 #include <linux/hugetlb.h>
29 #include <linux/pagemap.h>
30 #include <linux/smp.h>
31 #include <linux/page-flags.h>
32 #include <linux/backing-dev.h>
33 #include <linux/bit_spinlock.h>
34 #include <linux/rcupdate.h>
35 #include <linux/limits.h>
36 #include <linux/mutex.h>
37 #include <linux/rbtree.h>
38 #include <linux/slab.h>
39 #include <linux/swap.h>
40 #include <linux/swapops.h>
41 #include <linux/spinlock.h>
42 #include <linux/eventfd.h>
43 #include <linux/sort.h>
44 #include <linux/fs.h>
45 #include <linux/seq_file.h>
46 #include <linux/vmalloc.h>
47 #include <linux/mm_inline.h>
48 #include <linux/page_cgroup.h>
49 #include <linux/cpu.h>
50 #include <linux/oom.h>
51 #include "internal.h"
52
53 #include <asm/uaccess.h>
54
55 #include <trace/events/vmscan.h>
56
57 struct cgroup_subsys mem_cgroup_subsys __read_mostly;
58 #define MEM_CGROUP_RECLAIM_RETRIES 5
59 struct mem_cgroup *root_mem_cgroup __read_mostly;
60
61 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
62 /* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
63 int do_swap_account __read_mostly;
64
65 /* for remember boot option*/
66 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP_ENABLED
67 static int really_do_swap_account __initdata = 1;
68 #else
69 static int really_do_swap_account __initdata = 0;
70 #endif
71
72 #else
73 #define do_swap_account (0)
74 #endif
75
76
77 /*
78 * Statistics for memory cgroup.
79 */
80 enum 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 */
85 MEM_CGROUP_STAT_RSS, /* # of pages charged as anon rss */
86 MEM_CGROUP_STAT_FILE_MAPPED, /* # of pages charged as file rss */
87 MEM_CGROUP_STAT_SWAPOUT, /* # of pages, swapped out */
88 MEM_CGROUP_STAT_DATA, /* end of data requires synchronization */
89 MEM_CGROUP_ON_MOVE, /* someone is moving account between groups */
90 MEM_CGROUP_STAT_NSTATS,
91 };
92
93 enum 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 };
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 */
105 enum 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)
112
113 struct mem_cgroup_stat_cpu {
114 long count[MEM_CGROUP_STAT_NSTATS];
115 unsigned long events[MEM_CGROUP_EVENTS_NSTATS];
116 unsigned long targets[MEM_CGROUP_NTARGETS];
117 };
118
119 /*
120 * per-zone information in memory controller.
121 */
122 struct mem_cgroup_per_zone {
123 /*
124 * spin_lock to protect the per cgroup LRU
125 */
126 struct list_head lists[NR_LRU_LISTS];
127 unsigned long count[NR_LRU_LISTS];
128
129 struct zone_reclaim_stat reclaim_stat;
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;
134 struct mem_cgroup *mem; /* Back pointer, we cannot */
135 /* use container_of */
136 };
137 /* Macro for accessing counter */
138 #define MEM_CGROUP_ZSTAT(mz, idx) ((mz)->count[(idx)])
139
140 struct mem_cgroup_per_node {
141 struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
142 };
143
144 struct mem_cgroup_lru_info {
145 struct mem_cgroup_per_node *nodeinfo[MAX_NUMNODES];
146 };
147
148 /*
149 * Cgroups above their limits are maintained in a RB-Tree, independent of
150 * their hierarchy representation
151 */
152
153 struct mem_cgroup_tree_per_zone {
154 struct rb_root rb_root;
155 spinlock_t lock;
156 };
157
158 struct mem_cgroup_tree_per_node {
159 struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
160 };
161
162 struct mem_cgroup_tree {
163 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
164 };
165
166 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
167
168 struct mem_cgroup_threshold {
169 struct eventfd_ctx *eventfd;
170 u64 threshold;
171 };
172
173 /* For threshold */
174 struct mem_cgroup_threshold_ary {
175 /* An array index points to threshold just below usage. */
176 int current_threshold;
177 /* Size of entries[] */
178 unsigned int size;
179 /* Array of thresholds */
180 struct mem_cgroup_threshold entries[0];
181 };
182
183 struct 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
194 /* for OOM */
195 struct mem_cgroup_eventfd_list {
196 struct list_head list;
197 struct eventfd_ctx *eventfd;
198 };
199
200 static void mem_cgroup_threshold(struct mem_cgroup *mem);
201 static void mem_cgroup_oom_notify(struct mem_cgroup *mem);
202
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
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.
213 */
214 struct mem_cgroup {
215 struct cgroup_subsys_state css;
216 /*
217 * the counter to account for memory usage
218 */
219 struct res_counter res;
220 /*
221 * the counter to account for mem+swap usage.
222 */
223 struct res_counter memsw;
224 /*
225 * Per cgroup active and inactive list, similar to the
226 * per zone LRU lists.
227 */
228 struct mem_cgroup_lru_info info;
229 /*
230 * While reclaiming in a hierarchy, we cache the last child we
231 * reclaimed from.
232 */
233 int last_scanned_child;
234 int last_scanned_node;
235 #if MAX_NUMNODES > 1
236 nodemask_t scan_nodes;
237 unsigned long next_scan_node_update;
238 #endif
239 /*
240 * Should the accounting and control be hierarchical, per subtree?
241 */
242 bool use_hierarchy;
243 atomic_t oom_lock;
244 atomic_t refcnt;
245
246 unsigned int swappiness;
247 /* OOM-Killer disable */
248 int oom_kill_disable;
249
250 /* set when res.limit == memsw.limit */
251 bool memsw_is_minimum;
252
253 /* protect arrays of thresholds */
254 struct mutex thresholds_lock;
255
256 /* thresholds for memory usage. RCU-protected */
257 struct mem_cgroup_thresholds thresholds;
258
259 /* thresholds for mem+swap usage. RCU-protected */
260 struct mem_cgroup_thresholds memsw_thresholds;
261
262 /* For oom notifier event fd */
263 struct list_head oom_notify;
264
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;
270 /*
271 * percpu counter.
272 */
273 struct mem_cgroup_stat_cpu *stat;
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;
280 };
281
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 */
287 enum move_type {
288 MOVE_CHARGE_TYPE_ANON, /* private anonymous page and swap of it */
289 MOVE_CHARGE_TYPE_FILE, /* file page(including tmpfs) and swap of it */
290 NR_MOVE_TYPE,
291 };
292
293 /* "mc" and its members are protected by cgroup_mutex */
294 static struct move_charge_struct {
295 spinlock_t lock; /* for from, to */
296 struct mem_cgroup *from;
297 struct mem_cgroup *to;
298 unsigned long precharge;
299 unsigned long moved_charge;
300 unsigned long moved_swap;
301 struct task_struct *moving_task; /* a task moving charges */
302 wait_queue_head_t waitq; /* a waitq for other context */
303 } mc = {
304 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
305 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
306 };
307
308 static bool move_anon(void)
309 {
310 return test_bit(MOVE_CHARGE_TYPE_ANON,
311 &mc.to->move_charge_at_immigrate);
312 }
313
314 static bool move_file(void)
315 {
316 return test_bit(MOVE_CHARGE_TYPE_FILE,
317 &mc.to->move_charge_at_immigrate);
318 }
319
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
327 enum charge_type {
328 MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
329 MEM_CGROUP_CHARGE_TYPE_MAPPED,
330 MEM_CGROUP_CHARGE_TYPE_SHMEM, /* used by page migration of shmem */
331 MEM_CGROUP_CHARGE_TYPE_FORCE, /* used by force_empty */
332 MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
333 MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
334 NR_CHARGE_TYPE,
335 };
336
337 /* for encoding cft->private value on file */
338 #define _MEM (0)
339 #define _MEMSWAP (1)
340 #define _OOM_TYPE (2)
341 #define MEMFILE_PRIVATE(x, val) (((x) << 16) | (val))
342 #define MEMFILE_TYPE(val) (((val) >> 16) & 0xffff)
343 #define MEMFILE_ATTR(val) ((val) & 0xffff)
344 /* Used for OOM nofiier */
345 #define OOM_CONTROL (0)
346
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)
354 #define MEM_CGROUP_RECLAIM_SOFT_BIT 0x2
355 #define MEM_CGROUP_RECLAIM_SOFT (1 << MEM_CGROUP_RECLAIM_SOFT_BIT)
356
357 static void mem_cgroup_get(struct mem_cgroup *mem);
358 static void mem_cgroup_put(struct mem_cgroup *mem);
359 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem);
360 static void drain_all_stock_async(void);
361
362 static struct mem_cgroup_per_zone *
363 mem_cgroup_zoneinfo(struct mem_cgroup *mem, int nid, int zid)
364 {
365 return &mem->info.nodeinfo[nid]->zoneinfo[zid];
366 }
367
368 struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *mem)
369 {
370 return &mem->css;
371 }
372
373 static struct mem_cgroup_per_zone *
374 page_cgroup_zoneinfo(struct mem_cgroup *mem, struct page *page)
375 {
376 int nid = page_to_nid(page);
377 int zid = page_zonenum(page);
378
379 return mem_cgroup_zoneinfo(mem, nid, zid);
380 }
381
382 static struct mem_cgroup_tree_per_zone *
383 soft_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
388 static struct mem_cgroup_tree_per_zone *
389 soft_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
397 static void
398 __mem_cgroup_insert_exceeded(struct mem_cgroup *mem,
399 struct mem_cgroup_per_zone *mz,
400 struct mem_cgroup_tree_per_zone *mctz,
401 unsigned long long new_usage_in_excess)
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
410 mz->usage_in_excess = new_usage_in_excess;
411 if (!mz->usage_in_excess)
412 return;
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;
429 }
430
431 static 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
442 static void
443 mem_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);
448 __mem_cgroup_remove_exceeded(mem, mz, mctz);
449 spin_unlock(&mctz->lock);
450 }
451
452
453 static void mem_cgroup_update_tree(struct mem_cgroup *mem, struct page *page)
454 {
455 unsigned long long excess;
456 struct mem_cgroup_per_zone *mz;
457 struct mem_cgroup_tree_per_zone *mctz;
458 int nid = page_to_nid(page);
459 int zid = page_zonenum(page);
460 mctz = soft_limit_tree_from_page(page);
461
462 /*
463 * Necessary to update all ancestors when hierarchy is used.
464 * because their event counter is not touched.
465 */
466 for (; mem; mem = parent_mem_cgroup(mem)) {
467 mz = mem_cgroup_zoneinfo(mem, nid, zid);
468 excess = res_counter_soft_limit_excess(&mem->res);
469 /*
470 * We have to update the tree if mz is on RB-tree or
471 * mem is over its softlimit.
472 */
473 if (excess || mz->on_tree) {
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 /*
479 * Insert again. mz->usage_in_excess will be updated.
480 * If excess is 0, no tree ops.
481 */
482 __mem_cgroup_insert_exceeded(mem, mz, mctz, excess);
483 spin_unlock(&mctz->lock);
484 }
485 }
486 }
487
488 static 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
503 static 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;
507 struct mem_cgroup_per_zone *mz;
508
509 retry:
510 mz = NULL;
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;
525 done:
526 return mz;
527 }
528
529 static struct mem_cgroup_per_zone *
530 mem_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
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 */
559 static long mem_cgroup_read_stat(struct mem_cgroup *mem,
560 enum mem_cgroup_stat_index idx)
561 {
562 long val = 0;
563 int cpu;
564
565 get_online_cpus();
566 for_each_online_cpu(cpu)
567 val += per_cpu(mem->stat->count[idx], cpu);
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();
574 return val;
575 }
576
577 static long mem_cgroup_local_usage(struct mem_cgroup *mem)
578 {
579 long ret;
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
586 static void mem_cgroup_swap_statistics(struct mem_cgroup *mem,
587 bool charge)
588 {
589 int val = (charge) ? 1 : -1;
590 this_cpu_add(mem->stat->count[MEM_CGROUP_STAT_SWAPOUT], val);
591 }
592
593 static 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
609 static void mem_cgroup_charge_statistics(struct mem_cgroup *mem,
610 bool file, int nr_pages)
611 {
612 preempt_disable();
613
614 if (file)
615 __this_cpu_add(mem->stat->count[MEM_CGROUP_STAT_CACHE], nr_pages);
616 else
617 __this_cpu_add(mem->stat->count[MEM_CGROUP_STAT_RSS], nr_pages);
618
619 /* pagein of a big page is an event. So, ignore page size */
620 if (nr_pages > 0)
621 __this_cpu_inc(mem->stat->events[MEM_CGROUP_EVENTS_PGPGIN]);
622 else {
623 __this_cpu_inc(mem->stat->events[MEM_CGROUP_EVENTS_PGPGOUT]);
624 nr_pages = -nr_pages; /* for event */
625 }
626
627 __this_cpu_add(mem->stat->events[MEM_CGROUP_EVENTS_COUNT], nr_pages);
628
629 preempt_enable();
630 }
631
632 static unsigned long
633 mem_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 }
645 static unsigned long mem_cgroup_get_local_zonestat(struct mem_cgroup *mem,
646 enum lru_list idx)
647 {
648 int nid;
649 u64 total = 0;
650
651 for_each_online_node(nid)
652 total += mem_cgroup_get_zonestat_node(mem, nid, idx);
653 return total;
654 }
655
656 static 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
666 static void __mem_cgroup_target_update(struct mem_cgroup *mem, int target)
667 {
668 unsigned long val, next;
669
670 val = this_cpu_read(mem->stat->events[MEM_CGROUP_EVENTS_COUNT]);
671
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);
684 }
685
686 /*
687 * Check events in order.
688 *
689 */
690 static void memcg_check_events(struct mem_cgroup *mem, struct page *page)
691 {
692 /* threshold event is triggered in finer grain than soft limit */
693 if (unlikely(__memcg_event_check(mem, MEM_CGROUP_TARGET_THRESH))) {
694 mem_cgroup_threshold(mem);
695 __mem_cgroup_target_update(mem, MEM_CGROUP_TARGET_THRESH);
696 if (unlikely(__memcg_event_check(mem,
697 MEM_CGROUP_TARGET_SOFTLIMIT))){
698 mem_cgroup_update_tree(mem, page);
699 __mem_cgroup_target_update(mem,
700 MEM_CGROUP_TARGET_SOFTLIMIT);
701 }
702 }
703 }
704
705 static struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
706 {
707 return container_of(cgroup_subsys_state(cont,
708 mem_cgroup_subsys_id), struct mem_cgroup,
709 css);
710 }
711
712 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
713 {
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
722 return container_of(task_subsys_state(p, mem_cgroup_subsys_id),
723 struct mem_cgroup, css);
724 }
725
726 static struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
727 {
728 struct mem_cgroup *mem = NULL;
729
730 if (!mm)
731 return NULL;
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
747 /* The caller has to guarantee "mem" exists before calling this */
748 static struct mem_cgroup *mem_cgroup_start_loop(struct mem_cgroup *mem)
749 {
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;
772 }
773
774 static 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;
781 struct cgroup_subsys_state *css;
782
783 hierarchy_used = iter->use_hierarchy;
784
785 css_put(&iter->css);
786 /* If no ROOT, walk all, ignore hierarchy */
787 if (!cond || (root && !hierarchy_used))
788 return NULL;
789
790 if (!root)
791 root = root_mem_cgroup;
792
793 do {
794 iter = NULL;
795 rcu_read_lock();
796
797 css = css_get_next(&mem_cgroup_subsys, nextid,
798 &root->css, &found);
799 if (css && css_tryget(css))
800 iter = container_of(css, struct mem_cgroup, css);
801 rcu_read_unlock();
802 /* If css is NULL, no more cgroups will be found */
803 nextid = found + 1;
804 } while (css && !iter);
805
806 return iter;
807 }
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
821 #define for_each_mem_cgroup_all(iter) \
822 for_each_mem_cgroup_tree_cond(iter, NULL, true)
823
824
825 static inline bool mem_cgroup_is_root(struct mem_cgroup *mem)
826 {
827 return (mem == root_mem_cgroup);
828 }
829
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 */
843
844 void mem_cgroup_del_lru_list(struct page *page, enum lru_list lru)
845 {
846 struct page_cgroup *pc;
847 struct mem_cgroup_per_zone *mz;
848
849 if (mem_cgroup_disabled())
850 return;
851 pc = lookup_page_cgroup(page);
852 /* can happen while we handle swapcache. */
853 if (!TestClearPageCgroupAcctLRU(pc))
854 return;
855 VM_BUG_ON(!pc->mem_cgroup);
856 /*
857 * We don't check PCG_USED bit. It's cleared when the "page" is finally
858 * removed from global LRU.
859 */
860 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
861 /* huge page split is done under lru_lock. so, we have no races. */
862 MEM_CGROUP_ZSTAT(mz, lru) -= 1 << compound_order(page);
863 if (mem_cgroup_is_root(pc->mem_cgroup))
864 return;
865 VM_BUG_ON(list_empty(&pc->lru));
866 list_del_init(&pc->lru);
867 }
868
869 void mem_cgroup_del_lru(struct page *page)
870 {
871 mem_cgroup_del_lru_list(page, page_lru(page));
872 }
873
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 */
879 void 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;
896 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
897 list_move_tail(&pc->lru, &mz->lists[lru]);
898 }
899
900 void 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;
904
905 if (mem_cgroup_disabled())
906 return;
907
908 pc = lookup_page_cgroup(page);
909 /* unused or root page is not rotated. */
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))
915 return;
916 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
917 list_move(&pc->lru, &mz->lists[lru]);
918 }
919
920 void mem_cgroup_add_lru_list(struct page *page, enum lru_list lru)
921 {
922 struct page_cgroup *pc;
923 struct mem_cgroup_per_zone *mz;
924
925 if (mem_cgroup_disabled())
926 return;
927 pc = lookup_page_cgroup(page);
928 VM_BUG_ON(PageCgroupAcctLRU(pc));
929 if (!PageCgroupUsed(pc))
930 return;
931 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
932 smp_rmb();
933 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
934 /* huge page split is done under lru_lock. so, we have no races. */
935 MEM_CGROUP_ZSTAT(mz, lru) += 1 << compound_order(page);
936 SetPageCgroupAcctLRU(pc);
937 if (mem_cgroup_is_root(pc->mem_cgroup))
938 return;
939 list_add(&pc->lru, &mz->lists[lru]);
940 }
941
942 /*
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.
947 */
948 static void mem_cgroup_lru_del_before_commit(struct page *page)
949 {
950 unsigned long flags;
951 struct zone *zone = page_zone(page);
952 struct page_cgroup *pc = lookup_page_cgroup(page);
953
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
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);
973 }
974
975 static void mem_cgroup_lru_add_after_commit(struct page *page)
976 {
977 unsigned long flags;
978 struct zone *zone = page_zone(page);
979 struct page_cgroup *pc = lookup_page_cgroup(page);
980
981 /* taking care of that the page is added to LRU while we commit it */
982 if (likely(!PageLRU(page)))
983 return;
984 spin_lock_irqsave(&zone->lru_lock, flags);
985 /* link when the page is linked to LRU but page_cgroup isn't */
986 if (PageLRU(page) && !PageCgroupAcctLRU(pc))
987 mem_cgroup_add_lru_list(page, page_lru(page));
988 spin_unlock_irqrestore(&zone->lru_lock, flags);
989 }
990
991
992 void mem_cgroup_move_lists(struct page *page,
993 enum lru_list from, enum lru_list to)
994 {
995 if (mem_cgroup_disabled())
996 return;
997 mem_cgroup_del_lru_list(page, from);
998 mem_cgroup_add_lru_list(page, to);
999 }
1000
1001 int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *mem)
1002 {
1003 int ret;
1004 struct mem_cgroup *curr = NULL;
1005 struct task_struct *p;
1006
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);
1012 if (!curr)
1013 return 0;
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)
1021 ret = css_is_ancestor(&curr->css, &mem->css);
1022 else
1023 ret = (curr == mem);
1024 css_put(&curr->css);
1025 return ret;
1026 }
1027
1028 static int calc_inactive_ratio(struct mem_cgroup *memcg, unsigned long *present_pages)
1029 {
1030 unsigned long active;
1031 unsigned long inactive;
1032 unsigned long gb;
1033 unsigned long inactive_ratio;
1034
1035 inactive = mem_cgroup_get_local_zonestat(memcg, LRU_INACTIVE_ANON);
1036 active = mem_cgroup_get_local_zonestat(memcg, LRU_ACTIVE_ANON);
1037
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
1052 int 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)
1065 return 1;
1066
1067 return 0;
1068 }
1069
1070 int 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
1081 unsigned long mem_cgroup_zone_nr_lru_pages(struct mem_cgroup *memcg,
1082 struct zone *zone,
1083 enum lru_list lru)
1084 {
1085 int nid = zone_to_nid(zone);
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
1092 #ifdef CONFIG_NUMA
1093 static 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
1104 static 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
1115 static 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
1126 static 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
1137 static unsigned long
1138 mem_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
1143 static unsigned long
1144 mem_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
1155 static 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
1167 static 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
1179 struct zone_reclaim_stat *mem_cgroup_get_reclaim_stat(struct mem_cgroup *memcg,
1180 struct zone *zone)
1181 {
1182 int nid = zone_to_nid(zone);
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
1189 struct zone_reclaim_stat *
1190 mem_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);
1199 if (!PageCgroupUsed(pc))
1200 return NULL;
1201 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1202 smp_rmb();
1203 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
1204 return &mz->reclaim_stat;
1205 }
1206
1207 unsigned 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,
1212 int active, int file)
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;
1219 struct page_cgroup *pc, *tmp;
1220 int nid = zone_to_nid(z);
1221 int zid = zone_idx(z);
1222 struct mem_cgroup_per_zone *mz;
1223 int lru = LRU_FILE * file + active;
1224 int ret;
1225
1226 BUG_ON(!mem_cont);
1227 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
1228 src = &mz->lists[lru];
1229
1230 scan = 0;
1231 list_for_each_entry_safe_reverse(pc, tmp, src, lru) {
1232 if (scan >= nr_to_scan)
1233 break;
1234
1235 if (unlikely(!PageCgroupUsed(pc)))
1236 continue;
1237
1238 page = lookup_cgroup_page(pc);
1239
1240 if (unlikely(!PageLRU(page)))
1241 continue;
1242
1243 scan++;
1244 ret = __isolate_lru_page(page, mode, file);
1245 switch (ret) {
1246 case 0:
1247 list_move(&page->lru, dst);
1248 mem_cgroup_del_lru(page);
1249 nr_taken += hpage_nr_pages(page);
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;
1257 }
1258 }
1259
1260 *scanned = scan;
1261
1262 trace_mm_vmscan_memcg_isolate(0, nr_to_scan, scan, nr_taken,
1263 0, 0, 0, mode);
1264
1265 return nr_taken;
1266 }
1267
1268 #define mem_cgroup_from_res_counter(counter, member) \
1269 container_of(counter, struct mem_cgroup, member)
1270
1271 /**
1272 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1273 * @mem: the memory cgroup
1274 *
1275 * Returns the maximum amount of memory @mem can be charged with, in
1276 * pages.
1277 */
1278 static unsigned long mem_cgroup_margin(struct mem_cgroup *mem)
1279 {
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));
1285 return margin >> PAGE_SHIFT;
1286 }
1287
1288 static unsigned int get_swappiness(struct mem_cgroup *memcg)
1289 {
1290 struct cgroup *cgrp = memcg->css.cgroup;
1291
1292 /* root ? */
1293 if (cgrp->parent == NULL)
1294 return vm_swappiness;
1295
1296 return memcg->swappiness;
1297 }
1298
1299 static void mem_cgroup_start_move(struct mem_cgroup *mem)
1300 {
1301 int cpu;
1302
1303 get_online_cpus();
1304 spin_lock(&mem->pcp_counter_lock);
1305 for_each_online_cpu(cpu)
1306 per_cpu(mem->stat->count[MEM_CGROUP_ON_MOVE], cpu) += 1;
1307 mem->nocpu_base.count[MEM_CGROUP_ON_MOVE] += 1;
1308 spin_unlock(&mem->pcp_counter_lock);
1309 put_online_cpus();
1310
1311 synchronize_rcu();
1312 }
1313
1314 static void mem_cgroup_end_move(struct mem_cgroup *mem)
1315 {
1316 int cpu;
1317
1318 if (!mem)
1319 return;
1320 get_online_cpus();
1321 spin_lock(&mem->pcp_counter_lock);
1322 for_each_online_cpu(cpu)
1323 per_cpu(mem->stat->count[MEM_CGROUP_ON_MOVE], cpu) -= 1;
1324 mem->nocpu_base.count[MEM_CGROUP_ON_MOVE] -= 1;
1325 spin_unlock(&mem->pcp_counter_lock);
1326 put_online_cpus();
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
1340 static 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 }
1345
1346 static bool mem_cgroup_under_move(struct mem_cgroup *mem)
1347 {
1348 struct mem_cgroup *from;
1349 struct mem_cgroup *to;
1350 bool ret = false;
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;
1364 unlock:
1365 spin_unlock(&mc.lock);
1366 return ret;
1367 }
1368
1369 static 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
1385 /**
1386 * mem_cgroup_print_oom_info: Called from OOM with tasklist_lock held in read mode.
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 */
1393 void 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
1405 if (!memcg || !p)
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);
1439 done:
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
1452 /*
1453 * This function returns the number of memcg under hierarchy tree. Returns
1454 * 1(self count) if no children.
1455 */
1456 static int mem_cgroup_count_children(struct mem_cgroup *mem)
1457 {
1458 int num = 0;
1459 struct mem_cgroup *iter;
1460
1461 for_each_mem_cgroup_tree(iter, mem)
1462 num++;
1463 return num;
1464 }
1465
1466 /*
1467 * Return the memory (and swap, if configured) limit for a memcg.
1468 */
1469 u64 mem_cgroup_get_limit(struct mem_cgroup *memcg)
1470 {
1471 u64 limit;
1472 u64 memsw;
1473
1474 limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
1475 limit += total_swap_pages << PAGE_SHIFT;
1476
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
1485 /*
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 */
1490 static struct mem_cgroup *
1491 mem_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 */
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;
1517 }
1518
1519 return ret;
1520 }
1521
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 */
1530 static 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 */
1567 int 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
1591 int mem_cgroup_select_victim_node(struct mem_cgroup *mem)
1592 {
1593 return 0;
1594 }
1595 #endif
1596
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.
1601 *
1602 * root_mem is the original ancestor that we've been reclaim from.
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....)
1606 *
1607 * If shrink==true, for avoiding to free too much, this returns immedieately.
1608 */
1609 static int mem_cgroup_hierarchical_reclaim(struct mem_cgroup *root_mem,
1610 struct zone *zone,
1611 gfp_t gfp_mask,
1612 unsigned long reclaim_options,
1613 unsigned long *total_scanned)
1614 {
1615 struct mem_cgroup *victim;
1616 int ret, total = 0;
1617 int loop = 0;
1618 bool noswap = reclaim_options & MEM_CGROUP_RECLAIM_NOSWAP;
1619 bool shrink = reclaim_options & MEM_CGROUP_RECLAIM_SHRINK;
1620 bool check_soft = reclaim_options & MEM_CGROUP_RECLAIM_SOFT;
1621 unsigned long excess;
1622 unsigned long nr_scanned;
1623
1624 excess = res_counter_soft_limit_excess(&root_mem->res) >> PAGE_SHIFT;
1625
1626 /* If memsw_is_minimum==1, swap-out is of-no-use. */
1627 if (root_mem->memsw_is_minimum)
1628 noswap = true;
1629
1630 while (1) {
1631 victim = mem_cgroup_select_victim(root_mem);
1632 if (victim == root_mem) {
1633 loop++;
1634 if (loop >= 1)
1635 drain_all_stock_async();
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 /*
1647 * We want to do more targeted reclaim.
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 }
1659 if (!mem_cgroup_local_usage(victim)) {
1660 /* this cgroup's local usage == 0 */
1661 css_put(&victim->css);
1662 continue;
1663 }
1664 /* we use swappiness of local cgroup */
1665 if (check_soft) {
1666 ret = mem_cgroup_shrink_node_zone(victim, gfp_mask,
1667 noswap, get_swappiness(victim), zone,
1668 &nr_scanned);
1669 *total_scanned += nr_scanned;
1670 } else
1671 ret = try_to_free_mem_cgroup_pages(victim, gfp_mask,
1672 noswap, get_swappiness(victim));
1673 css_put(&victim->css);
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;
1681 total += ret;
1682 if (check_soft) {
1683 if (!res_counter_soft_limit_excess(&root_mem->res))
1684 return total;
1685 } else if (mem_cgroup_margin(root_mem))
1686 return total;
1687 }
1688 return total;
1689 }
1690
1691 /*
1692 * Check OOM-Killer is already running under our hierarchy.
1693 * If someone is running, return false.
1694 */
1695 static bool mem_cgroup_oom_lock(struct mem_cgroup *mem)
1696 {
1697 int x, lock_count = 0;
1698 struct mem_cgroup *iter;
1699
1700 for_each_mem_cgroup_tree(iter, mem) {
1701 x = atomic_inc_return(&iter->oom_lock);
1702 lock_count = max(x, lock_count);
1703 }
1704
1705 if (lock_count == 1)
1706 return true;
1707 return false;
1708 }
1709
1710 static int mem_cgroup_oom_unlock(struct mem_cgroup *mem)
1711 {
1712 struct mem_cgroup *iter;
1713
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 */
1719 for_each_mem_cgroup_tree(iter, mem)
1720 atomic_add_unless(&iter->oom_lock, -1, 0);
1721 return 0;
1722 }
1723
1724
1725 static DEFINE_MUTEX(memcg_oom_mutex);
1726 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1727
1728 struct oom_wait_info {
1729 struct mem_cgroup *mem;
1730 wait_queue_t wait;
1731 };
1732
1733 static 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
1754 wakeup:
1755 return autoremove_wake_function(wait, mode, sync, arg);
1756 }
1757
1758 static 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
1764 static void memcg_oom_recover(struct mem_cgroup *mem)
1765 {
1766 if (mem && atomic_read(&mem->oom_lock))
1767 memcg_wakeup_oom(mem);
1768 }
1769
1770 /*
1771 * try to call OOM killer. returns false if we should exit memory-reclaim loop.
1772 */
1773 bool mem_cgroup_handle_oom(struct mem_cgroup *mem, gfp_t mask)
1774 {
1775 struct oom_wait_info owait;
1776 bool locked, need_to_kill;
1777
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);
1783 need_to_kill = true;
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 */
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)
1796 mem_cgroup_oom_notify(mem);
1797 mutex_unlock(&memcg_oom_mutex);
1798
1799 if (need_to_kill) {
1800 finish_wait(&memcg_oom_waitq, &owait.wait);
1801 mem_cgroup_out_of_memory(mem, mask);
1802 } else {
1803 schedule();
1804 finish_wait(&memcg_oom_waitq, &owait.wait);
1805 }
1806 mutex_lock(&memcg_oom_mutex);
1807 mem_cgroup_oom_unlock(mem);
1808 memcg_wakeup_oom(mem);
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;
1816 }
1817
1818 /*
1819 * Currently used to update mapped file statistics, but the routine can be
1820 * generalized to update other statistics as well.
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.
1840 */
1841
1842 void mem_cgroup_update_page_stat(struct page *page,
1843 enum mem_cgroup_page_stat_item idx, int val)
1844 {
1845 struct mem_cgroup *mem;
1846 struct page_cgroup *pc = lookup_page_cgroup(page);
1847 bool need_unlock = false;
1848 unsigned long uninitialized_var(flags);
1849
1850 if (unlikely(!pc))
1851 return;
1852
1853 rcu_read_lock();
1854 mem = pc->mem_cgroup;
1855 if (unlikely(!mem || !PageCgroupUsed(pc)))
1856 goto out;
1857 /* pc->mem_cgroup is unstable ? */
1858 if (unlikely(mem_cgroup_stealed(mem)) || PageTransHuge(page)) {
1859 /* take a lock against to access pc->mem_cgroup */
1860 move_lock_page_cgroup(pc, &flags);
1861 need_unlock = true;
1862 mem = pc->mem_cgroup;
1863 if (!mem || !PageCgroupUsed(pc))
1864 goto out;
1865 }
1866
1867 switch (idx) {
1868 case MEMCG_NR_FILE_MAPPED:
1869 if (val > 0)
1870 SetPageCgroupFileMapped(pc);
1871 else if (!page_mapped(page))
1872 ClearPageCgroupFileMapped(pc);
1873 idx = MEM_CGROUP_STAT_FILE_MAPPED;
1874 break;
1875 default:
1876 BUG();
1877 }
1878
1879 this_cpu_add(mem->stat->count[idx], val);
1880
1881 out:
1882 if (unlikely(need_unlock))
1883 move_unlock_page_cgroup(pc, &flags);
1884 rcu_read_unlock();
1885 return;
1886 }
1887 EXPORT_SYMBOL(mem_cgroup_update_page_stat);
1888
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 */
1893 #define CHARGE_BATCH 32U
1894 struct memcg_stock_pcp {
1895 struct mem_cgroup *cached; /* this never be root cgroup */
1896 unsigned int nr_pages;
1897 struct work_struct work;
1898 };
1899 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
1900 static atomic_t memcg_drain_count;
1901
1902 /*
1903 * Try to consume stocked charge on this cpu. If success, one page is consumed
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 */
1908 static 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);
1914 if (mem == stock->cached && stock->nr_pages)
1915 stock->nr_pages--;
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 */
1925 static void drain_stock(struct memcg_stock_pcp *stock)
1926 {
1927 struct mem_cgroup *old = stock->cached;
1928
1929 if (stock->nr_pages) {
1930 unsigned long bytes = stock->nr_pages * PAGE_SIZE;
1931
1932 res_counter_uncharge(&old->res, bytes);
1933 if (do_swap_account)
1934 res_counter_uncharge(&old->memsw, bytes);
1935 stock->nr_pages = 0;
1936 }
1937 stock->cached = NULL;
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 */
1944 static 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.
1952 * This will be consumed by consume_stock() function, later.
1953 */
1954 static void refill_stock(struct mem_cgroup *mem, unsigned int nr_pages)
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 }
1962 stock->nr_pages += nr_pages;
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 */
1972 static 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. */
1996 static 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
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 */
2008 static 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++) {
2014 long x = per_cpu(mem->stat->count[i], cpu);
2015
2016 per_cpu(mem->stat->count[i], cpu) = 0;
2017 mem->nocpu_base.count[i] += x;
2018 }
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 }
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
2030 static 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];
2036 spin_unlock(&mem->pcp_counter_lock);
2037 }
2038
2039 static int __cpuinit memcg_cpu_hotplug_callback(struct notifier_block *nb,
2040 unsigned long action,
2041 void *hcpu)
2042 {
2043 int cpu = (unsigned long)hcpu;
2044 struct memcg_stock_pcp *stock;
2045 struct mem_cgroup *iter;
2046
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
2053 if ((action != CPU_DEAD) || action != CPU_DEAD_FROZEN)
2054 return NOTIFY_OK;
2055
2056 for_each_mem_cgroup_all(iter)
2057 mem_cgroup_drain_pcp_counter(iter, cpu);
2058
2059 stock = &per_cpu(memcg_stock, cpu);
2060 drain_stock(stock);
2061 return NOTIFY_OK;
2062 }
2063
2064
2065 /* See __mem_cgroup_try_charge() for details */
2066 enum {
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
2074 static int mem_cgroup_do_charge(struct mem_cgroup *mem, gfp_t gfp_mask,
2075 unsigned int nr_pages, bool oom_check)
2076 {
2077 unsigned long csize = nr_pages * PAGE_SIZE;
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
2092 res_counter_uncharge(&mem->res, csize);
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);
2097 /*
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).
2100 *
2101 * Never reclaim on behalf of optional batching, retry with a
2102 * single page instead.
2103 */
2104 if (nr_pages == CHARGE_BATCH)
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,
2111 gfp_mask, flags, NULL);
2112 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2113 return CHARGE_RETRY;
2114 /*
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.
2122 */
2123 if (nr_pages == 1 && ret)
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
2143 /*
2144 * Unlike exported interface, "oom" parameter is added. if oom==true,
2145 * oom-killer can be invoked.
2146 */
2147 static int __mem_cgroup_try_charge(struct mm_struct *mm,
2148 gfp_t gfp_mask,
2149 unsigned int nr_pages,
2150 struct mem_cgroup **memcg,
2151 bool oom)
2152 {
2153 unsigned int batch = max(CHARGE_BATCH, nr_pages);
2154 int nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2155 struct mem_cgroup *mem = NULL;
2156 int ret;
2157
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;
2166
2167 /*
2168 * We always charge the cgroup the mm_struct belongs to.
2169 * The mm_struct's mem_cgroup changes on task migration if the
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 */
2173 if (!*memcg && !mm)
2174 goto bypass;
2175 again:
2176 if (*memcg) { /* css should be a valid one */
2177 mem = *memcg;
2178 VM_BUG_ON(css_is_removed(&mem->css));
2179 if (mem_cgroup_is_root(mem))
2180 goto done;
2181 if (nr_pages == 1 && consume_stock(mem))
2182 goto done;
2183 css_get(&mem->css);
2184 } else {
2185 struct task_struct *p;
2186
2187 rcu_read_lock();
2188 p = rcu_dereference(mm->owner);
2189 /*
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.
2198 */
2199 mem = mem_cgroup_from_task(p);
2200 if (!mem || mem_cgroup_is_root(mem)) {
2201 rcu_read_unlock();
2202 goto done;
2203 }
2204 if (nr_pages == 1 && consume_stock(mem)) {
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 }
2223
2224 do {
2225 bool oom_check;
2226
2227 /* If killed, bypass charge */
2228 if (fatal_signal_pending(current)) {
2229 css_put(&mem->css);
2230 goto bypass;
2231 }
2232
2233 oom_check = false;
2234 if (oom && !nr_oom_retries) {
2235 oom_check = true;
2236 nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2237 }
2238
2239 ret = mem_cgroup_do_charge(mem, gfp_mask, batch, oom_check);
2240 switch (ret) {
2241 case CHARGE_OK:
2242 break;
2243 case CHARGE_RETRY: /* not in OOM situation but retry */
2244 batch = nr_pages;
2245 css_put(&mem->css);
2246 mem = NULL;
2247 goto again;
2248 case CHARGE_WOULDBLOCK: /* !__GFP_WAIT */
2249 css_put(&mem->css);
2250 goto nomem;
2251 case CHARGE_NOMEM: /* OOM routine works */
2252 if (!oom) {
2253 css_put(&mem->css);
2254 goto nomem;
2255 }
2256 /* If oom, we never return -ENOMEM */
2257 nr_oom_retries--;
2258 break;
2259 case CHARGE_OOM_DIE: /* Killed by OOM Killer */
2260 css_put(&mem->css);
2261 goto bypass;
2262 }
2263 } while (ret != CHARGE_OK);
2264
2265 if (batch > nr_pages)
2266 refill_stock(mem, batch - nr_pages);
2267 css_put(&mem->css);
2268 done:
2269 *memcg = mem;
2270 return 0;
2271 nomem:
2272 *memcg = NULL;
2273 return -ENOMEM;
2274 bypass:
2275 *memcg = NULL;
2276 return 0;
2277 }
2278
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 */
2284 static void __mem_cgroup_cancel_charge(struct mem_cgroup *mem,
2285 unsigned int nr_pages)
2286 {
2287 if (!mem_cgroup_is_root(mem)) {
2288 unsigned long bytes = nr_pages * PAGE_SIZE;
2289
2290 res_counter_uncharge(&mem->res, bytes);
2291 if (do_swap_account)
2292 res_counter_uncharge(&mem->memsw, bytes);
2293 }
2294 }
2295
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 */
2302 static 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
2315 struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
2316 {
2317 struct mem_cgroup *mem = NULL;
2318 struct page_cgroup *pc;
2319 unsigned short id;
2320 swp_entry_t ent;
2321
2322 VM_BUG_ON(!PageLocked(page));
2323
2324 pc = lookup_page_cgroup(page);
2325 lock_page_cgroup(pc);
2326 if (PageCgroupUsed(pc)) {
2327 mem = pc->mem_cgroup;
2328 if (mem && !css_tryget(&mem->css))
2329 mem = NULL;
2330 } else if (PageSwapCache(page)) {
2331 ent.val = page_private(page);
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();
2338 }
2339 unlock_page_cgroup(pc);
2340 return mem;
2341 }
2342
2343 static void __mem_cgroup_commit_charge(struct mem_cgroup *mem,
2344 struct page *page,
2345 unsigned int nr_pages,
2346 struct page_cgroup *pc,
2347 enum charge_type ctype)
2348 {
2349 lock_page_cgroup(pc);
2350 if (unlikely(PageCgroupUsed(pc))) {
2351 unlock_page_cgroup(pc);
2352 __mem_cgroup_cancel_charge(mem, nr_pages);
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 */
2359 pc->mem_cgroup = mem;
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 */
2367 smp_wmb();
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 }
2381
2382 mem_cgroup_charge_statistics(mem, PageCgroupCache(pc), nr_pages);
2383 unlock_page_cgroup(pc);
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 */
2389 memcg_check_events(mem, page);
2390 }
2391
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 */
2400 void 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
2406 if (mem_cgroup_disabled())
2407 return;
2408 /*
2409 * We have no races with charge/uncharge but will have races with
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() */
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);
2426 mz = page_cgroup_zoneinfo(head_pc->mem_cgroup, head);
2427 MEM_CGROUP_ZSTAT(mz, lru) -= 1;
2428 }
2429 tail_pc->flags = head_pc->flags & ~PCGF_NOCOPY_AT_SPLIT;
2430 move_unlock_page_cgroup(head_pc, &flags);
2431 }
2432 #endif
2433
2434 /**
2435 * mem_cgroup_move_account - move account of the page
2436 * @page: the page
2437 * @nr_pages: number of regular pages (>1 for huge pages)
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.
2441 * @uncharge: whether we should call uncharge and css_put against @from.
2442 *
2443 * The caller must confirm following.
2444 * - page is not on LRU (isolate_page() is useful.)
2445 * - compound_lock is held when nr_pages > 1
2446 *
2447 * This function doesn't do "charge" nor css_get to new cgroup. It should be
2448 * done by a caller(__mem_cgroup_try_charge would be useful). If @uncharge is
2449 * true, this function does "uncharge" from old cgroup, but it doesn't if
2450 * @uncharge is false, so a caller should do "uncharge".
2451 */
2452 static 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)
2458 {
2459 unsigned long flags;
2460 int ret;
2461
2462 VM_BUG_ON(from == to);
2463 VM_BUG_ON(PageLRU(page));
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;
2471 if (nr_pages > 1 && !PageTransHuge(page))
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);
2481
2482 if (PageCgroupFileMapped(pc)) {
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();
2488 }
2489 mem_cgroup_charge_statistics(from, PageCgroupCache(pc), -nr_pages);
2490 if (uncharge)
2491 /* This is not "cancel", but cancel_charge does all we need. */
2492 __mem_cgroup_cancel_charge(from, nr_pages);
2493
2494 /* caller should have done css_get */
2495 pc->mem_cgroup = to;
2496 mem_cgroup_charge_statistics(to, PageCgroupCache(pc), nr_pages);
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
2500 * this function is just force_empty() and move charge, so it's
2501 * guaranteed that "to" is never removed. So, we don't check rmdir
2502 * status here.
2503 */
2504 move_unlock_page_cgroup(pc, &flags);
2505 ret = 0;
2506 unlock:
2507 unlock_page_cgroup(pc);
2508 /*
2509 * check events
2510 */
2511 memcg_check_events(to, page);
2512 memcg_check_events(from, page);
2513 out:
2514 return ret;
2515 }
2516
2517 /*
2518 * move charges to its parent.
2519 */
2520
2521 static int mem_cgroup_move_parent(struct page *page,
2522 struct page_cgroup *pc,
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;
2529 unsigned int nr_pages;
2530 unsigned long uninitialized_var(flags);
2531 int ret;
2532
2533 /* Is ROOT ? */
2534 if (!pcg)
2535 return -EINVAL;
2536
2537 ret = -EBUSY;
2538 if (!get_page_unless_zero(page))
2539 goto out;
2540 if (isolate_lru_page(page))
2541 goto put;
2542
2543 nr_pages = hpage_nr_pages(page);
2544
2545 parent = mem_cgroup_from_cont(pcg);
2546 ret = __mem_cgroup_try_charge(NULL, gfp_mask, nr_pages, &parent, false);
2547 if (ret || !parent)
2548 goto put_back;
2549
2550 if (nr_pages > 1)
2551 flags = compound_lock_irqsave(page);
2552
2553 ret = mem_cgroup_move_account(page, nr_pages, pc, child, parent, true);
2554 if (ret)
2555 __mem_cgroup_cancel_charge(parent, nr_pages);
2556
2557 if (nr_pages > 1)
2558 compound_unlock_irqrestore(page, flags);
2559 put_back:
2560 putback_lru_page(page);
2561 put:
2562 put_page(page);
2563 out:
2564 return ret;
2565 }
2566
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 */
2573 static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
2574 gfp_t gfp_mask, enum charge_type ctype)
2575 {
2576 struct mem_cgroup *mem = NULL;
2577 unsigned int nr_pages = 1;
2578 struct page_cgroup *pc;
2579 bool oom = true;
2580 int ret;
2581
2582 if (PageTransHuge(page)) {
2583 nr_pages <<= compound_order(page);
2584 VM_BUG_ON(!PageTransHuge(page));
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;
2590 }
2591
2592 pc = lookup_page_cgroup(page);
2593 BUG_ON(!pc); /* XXX: remove this and move pc lookup into commit */
2594
2595 ret = __mem_cgroup_try_charge(mm, gfp_mask, nr_pages, &mem, oom);
2596 if (ret || !mem)
2597 return ret;
2598
2599 __mem_cgroup_commit_charge(mem, page, nr_pages, pc, ctype);
2600 return 0;
2601 }
2602
2603 int mem_cgroup_newpage_charge(struct page *page,
2604 struct mm_struct *mm, gfp_t gfp_mask)
2605 {
2606 if (mem_cgroup_disabled())
2607 return 0;
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;
2619 return mem_cgroup_charge_common(page, mm, gfp_mask,
2620 MEM_CGROUP_CHARGE_TYPE_MAPPED);
2621 }
2622
2623 static void
2624 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
2625 enum charge_type ctype);
2626
2627 static 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
2643 int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
2644 gfp_t gfp_mask)
2645 {
2646 struct mem_cgroup *mem = NULL;
2647 int ret;
2648
2649 if (mem_cgroup_disabled())
2650 return 0;
2651 if (PageCompound(page))
2652 return 0;
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.)
2661 * And when the page is SwapCache, it should take swap information
2662 * into account. This is under lock_page() now.
2663 */
2664 if (!(gfp_mask & __GFP_WAIT)) {
2665 struct page_cgroup *pc;
2666
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);
2673 return 0;
2674 }
2675 unlock_page_cgroup(pc);
2676 }
2677
2678 if (unlikely(!mm))
2679 mm = &init_mm;
2680
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;
2685
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 }
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,
2703 MEM_CGROUP_CHARGE_TYPE_SHMEM);
2704
2705 return ret;
2706 }
2707
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
2711 * struct page_cgroup is acquired. This refcnt will be consumed by
2712 * "commit()" or removed by "cancel()"
2713 */
2714 int 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;
2719 int ret;
2720
2721 *ptr = NULL;
2722
2723 if (mem_cgroup_disabled())
2724 return 0;
2725
2726 if (!do_swap_account)
2727 goto charge_cur_mm;
2728 /*
2729 * A racing thread's fault, or swapoff, may have already updated
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.
2733 */
2734 if (!PageSwapCache(page))
2735 goto charge_cur_mm;
2736 mem = try_get_mem_cgroup_from_page(page);
2737 if (!mem)
2738 goto charge_cur_mm;
2739 *ptr = mem;
2740 ret = __mem_cgroup_try_charge(NULL, mask, 1, ptr, true);
2741 css_put(&mem->css);
2742 return ret;
2743 charge_cur_mm:
2744 if (unlikely(!mm))
2745 mm = &init_mm;
2746 return __mem_cgroup_try_charge(mm, mask, 1, ptr, true);
2747 }
2748
2749 static void
2750 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
2751 enum charge_type ctype)
2752 {
2753 if (mem_cgroup_disabled())
2754 return;
2755 if (!ptr)
2756 return;
2757 cgroup_exclude_rmdir(&ptr->css);
2758
2759 __mem_cgroup_commit_charge_lrucare(page, ptr, ctype);
2760 /*
2761 * Now swap is on-memory. This means this page may be
2762 * counted both as mem and swap....double count.
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.
2766 */
2767 if (do_swap_account && PageSwapCache(page)) {
2768 swp_entry_t ent = {.val = page_private(page)};
2769 unsigned short id;
2770 struct mem_cgroup *memcg;
2771
2772 id = swap_cgroup_record(ent, 0);
2773 rcu_read_lock();
2774 memcg = mem_cgroup_lookup(id);
2775 if (memcg) {
2776 /*
2777 * This recorded memcg can be obsolete one. So, avoid
2778 * calling css_tryget
2779 */
2780 if (!mem_cgroup_is_root(memcg))
2781 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
2782 mem_cgroup_swap_statistics(memcg, false);
2783 mem_cgroup_put(memcg);
2784 }
2785 rcu_read_unlock();
2786 }
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);
2793 }
2794
2795 void 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
2801 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *mem)
2802 {
2803 if (mem_cgroup_disabled())
2804 return;
2805 if (!mem)
2806 return;
2807 __mem_cgroup_cancel_charge(mem, 1);
2808 }
2809
2810 static void mem_cgroup_do_uncharge(struct mem_cgroup *mem,
2811 unsigned int nr_pages,
2812 const enum charge_type ctype)
2813 {
2814 struct memcg_batch_info *batch = NULL;
2815 bool uncharge_memsw = true;
2816
2817 /* If swapout, usage of swap doesn't decrease */
2818 if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2819 uncharge_memsw = false;
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;
2829 /*
2830 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
2831 * In those cases, all pages freed continuously can be expected to be in
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
2840 if (nr_pages > 1)
2841 goto direct_uncharge;
2842
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 */
2851 batch->nr_pages++;
2852 if (uncharge_memsw)
2853 batch->memsw_nr_pages++;
2854 return;
2855 direct_uncharge:
2856 res_counter_uncharge(&mem->res, nr_pages * PAGE_SIZE);
2857 if (uncharge_memsw)
2858 res_counter_uncharge(&mem->memsw, nr_pages * PAGE_SIZE);
2859 if (unlikely(batch->memcg != mem))
2860 memcg_oom_recover(mem);
2861 return;
2862 }
2863
2864 /*
2865 * uncharge if !page_mapped(page)
2866 */
2867 static struct mem_cgroup *
2868 __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype)
2869 {
2870 struct mem_cgroup *mem = NULL;
2871 unsigned int nr_pages = 1;
2872 struct page_cgroup *pc;
2873
2874 if (mem_cgroup_disabled())
2875 return NULL;
2876
2877 if (PageSwapCache(page))
2878 return NULL;
2879
2880 if (PageTransHuge(page)) {
2881 nr_pages <<= compound_order(page);
2882 VM_BUG_ON(!PageTransHuge(page));
2883 }
2884 /*
2885 * Check if our page_cgroup is valid
2886 */
2887 pc = lookup_page_cgroup(page);
2888 if (unlikely(!pc || !PageCgroupUsed(pc)))
2889 return NULL;
2890
2891 lock_page_cgroup(pc);
2892
2893 mem = pc->mem_cgroup;
2894
2895 if (!PageCgroupUsed(pc))
2896 goto unlock_out;
2897
2898 switch (ctype) {
2899 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
2900 case MEM_CGROUP_CHARGE_TYPE_DROP:
2901 /* See mem_cgroup_prepare_migration() */
2902 if (page_mapped(page) || PageCgroupMigration(pc))
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;
2914 }
2915
2916 mem_cgroup_charge_statistics(mem, PageCgroupCache(pc), -nr_pages);
2917
2918 ClearPageCgroupUsed(pc);
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 */
2925
2926 unlock_page_cgroup(pc);
2927 /*
2928 * even after unlock, we have mem->res.usage here and this memcg
2929 * will never be freed.
2930 */
2931 memcg_check_events(mem, page);
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))
2937 mem_cgroup_do_uncharge(mem, nr_pages, ctype);
2938
2939 return mem;
2940
2941 unlock_out:
2942 unlock_page_cgroup(pc);
2943 return NULL;
2944 }
2945
2946 void mem_cgroup_uncharge_page(struct page *page)
2947 {
2948 /* early check. */
2949 if (page_mapped(page))
2950 return;
2951 if (page->mapping && !PageAnon(page))
2952 return;
2953 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_MAPPED);
2954 }
2955
2956 void mem_cgroup_uncharge_cache_page(struct page *page)
2957 {
2958 VM_BUG_ON(page_mapped(page));
2959 VM_BUG_ON(page->mapping);
2960 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE);
2961 }
2962
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
2971 void 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;
2977 current->memcg_batch.nr_pages = 0;
2978 current->memcg_batch.memsw_nr_pages = 0;
2979 }
2980 }
2981
2982 void 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 */
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);
3005 memcg_oom_recover(batch->memcg);
3006 /* forget this pointer (for sanity check) */
3007 batch->memcg = NULL;
3008 }
3009
3010 #ifdef CONFIG_SWAP
3011 /*
3012 * called after __delete_from_swap_cache() and drop "page" account.
3013 * memcg information is recorded to swap_cgroup of "ent"
3014 */
3015 void
3016 mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
3017 {
3018 struct mem_cgroup *memcg;
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);
3025
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)
3031 swap_cgroup_record(ent, css_id(&memcg->css));
3032 }
3033 #endif
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 */
3040 void mem_cgroup_uncharge_swap(swp_entry_t ent)
3041 {
3042 struct mem_cgroup *memcg;
3043 unsigned short id;
3044
3045 if (!do_swap_account)
3046 return;
3047
3048 id = swap_cgroup_record(ent, 0);
3049 rcu_read_lock();
3050 memcg = mem_cgroup_lookup(id);
3051 if (memcg) {
3052 /*
3053 * We uncharge this because swap is freed.
3054 * This memcg can be obsolete one. We avoid calling css_tryget
3055 */
3056 if (!mem_cgroup_is_root(memcg))
3057 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
3058 mem_cgroup_swap_statistics(memcg, false);
3059 mem_cgroup_put(memcg);
3060 }
3061 rcu_read_unlock();
3062 }
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
3069 * @need_fixup: whether we should fixup res_counters and refcounts.
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 */
3079 static int mem_cgroup_move_swap_account(swp_entry_t entry,
3080 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
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) {
3088 mem_cgroup_swap_statistics(from, false);
3089 mem_cgroup_swap_statistics(to, true);
3090 /*
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.
3097 */
3098 mem_cgroup_get(to);
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);
3109 }
3110 return 0;
3111 }
3112 return -EINVAL;
3113 }
3114 #else
3115 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
3116 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
3117 {
3118 return -EINVAL;
3119 }
3120 #endif
3121
3122 /*
3123 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
3124 * page belongs to.
3125 */
3126 int mem_cgroup_prepare_migration(struct page *page,
3127 struct page *newpage, struct mem_cgroup **ptr, gfp_t gfp_mask)
3128 {
3129 struct mem_cgroup *mem = NULL;
3130 struct page_cgroup *pc;
3131 enum charge_type ctype;
3132 int ret = 0;
3133
3134 *ptr = NULL;
3135
3136 VM_BUG_ON(PageTransHuge(page));
3137 if (mem_cgroup_disabled())
3138 return 0;
3139
3140 pc = lookup_page_cgroup(page);
3141 lock_page_cgroup(pc);
3142 if (PageCgroupUsed(pc)) {
3143 mem = pc->mem_cgroup;
3144 css_get(&mem->css);
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);
3176 }
3177 unlock_page_cgroup(pc);
3178 /*
3179 * If the page is not charged at this point,
3180 * we return here.
3181 */
3182 if (!mem)
3183 return 0;
3184
3185 *ptr = mem;
3186 ret = __mem_cgroup_try_charge(NULL, gfp_mask, 1, ptr, false);
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;
3199 }
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;
3213 __mem_cgroup_commit_charge(mem, page, 1, pc, ctype);
3214 return ret;
3215 }
3216
3217 /* remove redundant charge if migration failed*/
3218 void mem_cgroup_end_migration(struct mem_cgroup *mem,
3219 struct page *oldpage, struct page *newpage, bool migration_ok)
3220 {
3221 struct page *used, *unused;
3222 struct page_cgroup *pc;
3223
3224 if (!mem)
3225 return;
3226 /* blocks rmdir() */
3227 cgroup_exclude_rmdir(&mem->css);
3228 if (!migration_ok) {
3229 used = oldpage;
3230 unused = newpage;
3231 } else {
3232 used = newpage;
3233 unused = oldpage;
3234 }
3235 /*
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.
3239 */
3240 pc = lookup_page_cgroup(oldpage);
3241 lock_page_cgroup(pc);
3242 ClearPageCgroupMigration(pc);
3243 unlock_page_cgroup(pc);
3244
3245 __mem_cgroup_uncharge_common(unused, MEM_CGROUP_CHARGE_TYPE_FORCE);
3246
3247 /*
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)
3254 */
3255 if (PageAnon(used))
3256 mem_cgroup_uncharge_page(used);
3257 /*
3258 * At migration, we may charge account against cgroup which has no
3259 * tasks.
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);
3264 }
3265
3266 /*
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.
3273 */
3274 int mem_cgroup_shmem_charge_fallback(struct page *page,
3275 struct mm_struct *mm,
3276 gfp_t gfp_mask)
3277 {
3278 struct mem_cgroup *mem;
3279 int ret;
3280
3281 if (mem_cgroup_disabled())
3282 return 0;
3283
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 */
3287
3288 return ret;
3289 }
3290
3291 #ifdef CONFIG_DEBUG_VM
3292 static 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
3302 bool 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
3310 void 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
3337 static DEFINE_MUTEX(set_limit_mutex);
3338
3339 static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
3340 unsigned long long val)
3341 {
3342 int retry_count;
3343 u64 memswlimit, memlimit;
3344 int ret = 0;
3345 int children = mem_cgroup_count_children(memcg);
3346 u64 curusage, oldusage;
3347 int enlarge;
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);
3357
3358 enlarge = 0;
3359 while (retry_count) {
3360 if (signal_pending(current)) {
3361 ret = -EINTR;
3362 break;
3363 }
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);
3374 break;
3375 }
3376
3377 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3378 if (memlimit < val)
3379 enlarge = 1;
3380
3381 ret = res_counter_set_limit(&memcg->res, val);
3382 if (!ret) {
3383 if (memswlimit == val)
3384 memcg->memsw_is_minimum = true;
3385 else
3386 memcg->memsw_is_minimum = false;
3387 }
3388 mutex_unlock(&set_limit_mutex);
3389
3390 if (!ret)
3391 break;
3392
3393 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
3394 MEM_CGROUP_RECLAIM_SHRINK,
3395 NULL);
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;
3402 }
3403 if (!ret && enlarge)
3404 memcg_oom_recover(memcg);
3405
3406 return ret;
3407 }
3408
3409 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
3410 unsigned long long val)
3411 {
3412 int retry_count;
3413 u64 memlimit, memswlimit, oldusage, curusage;
3414 int children = mem_cgroup_count_children(memcg);
3415 int ret = -EBUSY;
3416 int enlarge = 0;
3417
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);
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 }
3438 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3439 if (memswlimit < val)
3440 enlarge = 1;
3441 ret = res_counter_set_limit(&memcg->memsw, val);
3442 if (!ret) {
3443 if (memlimit == val)
3444 memcg->memsw_is_minimum = true;
3445 else
3446 memcg->memsw_is_minimum = false;
3447 }
3448 mutex_unlock(&set_limit_mutex);
3449
3450 if (!ret)
3451 break;
3452
3453 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
3454 MEM_CGROUP_RECLAIM_NOSWAP |
3455 MEM_CGROUP_RECLAIM_SHRINK,
3456 NULL);
3457 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
3458 /* Usage is reduced ? */
3459 if (curusage >= oldusage)
3460 retry_count--;
3461 else
3462 oldusage = curusage;
3463 }
3464 if (!ret && enlarge)
3465 memcg_oom_recover(memcg);
3466 return ret;
3467 }
3468
3469 unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
3470 gfp_t gfp_mask,
3471 unsigned long *total_scanned)
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;
3478 unsigned long long excess;
3479 unsigned long nr_scanned;
3480
3481 if (order > 0)
3482 return 0;
3483
3484 mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone));
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
3498 nr_scanned = 0;
3499 reclaimed = mem_cgroup_hierarchical_reclaim(mz->mem, zone,
3500 gfp_mask,
3501 MEM_CGROUP_RECLAIM_SOFT,
3502 &nr_scanned);
3503 nr_reclaimed += reclaimed;
3504 *total_scanned += nr_scanned;
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);
3527 if (next_mz == mz)
3528 css_put(&next_mz->mem->css);
3529 else /* next_mz == NULL or other memcg */
3530 break;
3531 } while (1);
3532 }
3533 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
3534 excess = res_counter_soft_limit_excess(&mz->mem->res);
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 */
3543 /* If excess == 0, no tree ops */
3544 __mem_cgroup_insert_exceeded(mz->mem, mz, mctz, excess);
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
3563 /*
3564 * This routine traverse page_cgroup in given list and drop them all.
3565 * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
3566 */
3567 static int mem_cgroup_force_empty_list(struct mem_cgroup *mem,
3568 int node, int zid, enum lru_list lru)
3569 {
3570 struct zone *zone;
3571 struct mem_cgroup_per_zone *mz;
3572 struct page_cgroup *pc, *busy;
3573 unsigned long flags, loop;
3574 struct list_head *list;
3575 int ret = 0;
3576
3577 zone = &NODE_DATA(node)->node_zones[zid];
3578 mz = mem_cgroup_zoneinfo(mem, node, zid);
3579 list = &mz->lists[lru];
3580
3581 loop = MEM_CGROUP_ZSTAT(mz, lru);
3582 /* give some margin against EBUSY etc...*/
3583 loop += 256;
3584 busy = NULL;
3585 while (loop--) {
3586 struct page *page;
3587
3588 ret = 0;
3589 spin_lock_irqsave(&zone->lru_lock, flags);
3590 if (list_empty(list)) {
3591 spin_unlock_irqrestore(&zone->lru_lock, flags);
3592 break;
3593 }
3594 pc = list_entry(list->prev, struct page_cgroup, lru);
3595 if (busy == pc) {
3596 list_move(&pc->lru, list);
3597 busy = NULL;
3598 spin_unlock_irqrestore(&zone->lru_lock, flags);
3599 continue;
3600 }
3601 spin_unlock_irqrestore(&zone->lru_lock, flags);
3602
3603 page = lookup_cgroup_page(pc);
3604
3605 ret = mem_cgroup_move_parent(page, pc, mem, GFP_KERNEL);
3606 if (ret == -ENOMEM)
3607 break;
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;
3615 }
3616
3617 if (!ret && !list_empty(list))
3618 return -EBUSY;
3619 return ret;
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 */
3626 static int mem_cgroup_force_empty(struct mem_cgroup *mem, bool free_all)
3627 {
3628 int ret;
3629 int node, zid, shrink;
3630 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
3631 struct cgroup *cgrp = mem->css.cgroup;
3632
3633 css_get(&mem->css);
3634
3635 shrink = 0;
3636 /* should free all ? */
3637 if (free_all)
3638 goto try_to_free;
3639 move_account:
3640 do {
3641 ret = -EBUSY;
3642 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
3643 goto out;
3644 ret = -EINTR;
3645 if (signal_pending(current))
3646 goto out;
3647 /* This is for making all *used* pages to be on LRU. */
3648 lru_add_drain_all();
3649 drain_all_stock_sync();
3650 ret = 0;
3651 mem_cgroup_start_move(mem);
3652 for_each_node_state(node, N_HIGH_MEMORY) {
3653 for (zid = 0; !ret && zid < MAX_NR_ZONES; zid++) {
3654 enum lru_list l;
3655 for_each_lru(l) {
3656 ret = mem_cgroup_force_empty_list(mem,
3657 node, zid, l);
3658 if (ret)
3659 break;
3660 }
3661 }
3662 if (ret)
3663 break;
3664 }
3665 mem_cgroup_end_move(mem);
3666 memcg_oom_recover(mem);
3667 /* it seems parent cgroup doesn't have enough mem */
3668 if (ret == -ENOMEM)
3669 goto try_to_free;
3670 cond_resched();
3671 /* "ret" should also be checked to ensure all lists are empty. */
3672 } while (mem->res.usage > 0 || ret);
3673 out:
3674 css_put(&mem->css);
3675 return ret;
3676
3677 try_to_free:
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) {
3680 ret = -EBUSY;
3681 goto out;
3682 }
3683 /* we call try-to-free pages for make this cgroup empty */
3684 lru_add_drain_all();
3685 /* try to free all pages in this cgroup */
3686 shrink = 1;
3687 while (nr_retries && mem->res.usage > 0) {
3688 int progress;
3689
3690 if (signal_pending(current)) {
3691 ret = -EINTR;
3692 goto out;
3693 }
3694 progress = try_to_free_mem_cgroup_pages(mem, GFP_KERNEL,
3695 false, get_swappiness(mem));
3696 if (!progress) {
3697 nr_retries--;
3698 /* maybe some writeback is necessary */
3699 congestion_wait(BLK_RW_ASYNC, HZ/10);
3700 }
3701
3702 }
3703 lru_add_drain();
3704 /* try move_account...there may be some *locked* pages. */
3705 goto move_account;
3706 }
3707
3708 int 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
3714 static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
3715 {
3716 return mem_cgroup_from_cont(cont)->use_hierarchy;
3717 }
3718
3719 static 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 /*
3732 * If parent's use_hierarchy is set, we can't make any modifications
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
3752
3753 static unsigned long mem_cgroup_recursive_stat(struct mem_cgroup *mem,
3754 enum mem_cgroup_stat_index idx)
3755 {
3756 struct mem_cgroup *iter;
3757 long val = 0;
3758
3759 /* Per-cpu values can be negative, use a signed accumulator */
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;
3766 }
3767
3768 static inline u64 mem_cgroup_usage(struct mem_cgroup *mem, bool swap)
3769 {
3770 u64 val;
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
3779 val = mem_cgroup_recursive_stat(mem, MEM_CGROUP_STAT_CACHE);
3780 val += mem_cgroup_recursive_stat(mem, MEM_CGROUP_STAT_RSS);
3781
3782 if (swap)
3783 val += mem_cgroup_recursive_stat(mem, MEM_CGROUP_STAT_SWAPOUT);
3784
3785 return val << PAGE_SHIFT;
3786 }
3787
3788 static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft)
3789 {
3790 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
3791 u64 val;
3792 int type, name;
3793
3794 type = MEMFILE_TYPE(cft->private);
3795 name = MEMFILE_ATTR(cft->private);
3796 switch (type) {
3797 case _MEM:
3798 if (name == RES_USAGE)
3799 val = mem_cgroup_usage(mem, false);
3800 else
3801 val = res_counter_read_u64(&mem->res, name);
3802 break;
3803 case _MEMSWAP:
3804 if (name == RES_USAGE)
3805 val = mem_cgroup_usage(mem, true);
3806 else
3807 val = res_counter_read_u64(&mem->memsw, name);
3808 break;
3809 default:
3810 BUG();
3811 break;
3812 }
3813 return val;
3814 }
3815 /*
3816 * The user of this function is...
3817 * RES_LIMIT.
3818 */
3819 static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
3820 const char *buffer)
3821 {
3822 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
3823 int type, name;
3824 unsigned long long val;
3825 int ret;
3826
3827 type = MEMFILE_TYPE(cft->private);
3828 name = MEMFILE_ATTR(cft->private);
3829 switch (name) {
3830 case RES_LIMIT:
3831 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3832 ret = -EINVAL;
3833 break;
3834 }
3835 /* This function does all necessary parse...reuse it */
3836 ret = res_counter_memparse_write_strategy(buffer, &val);
3837 if (ret)
3838 break;
3839 if (type == _MEM)
3840 ret = mem_cgroup_resize_limit(memcg, val);
3841 else
3842 ret = mem_cgroup_resize_memsw_limit(memcg, val);
3843 break;
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;
3858 default:
3859 ret = -EINVAL; /* should be BUG() ? */
3860 break;
3861 }
3862 return ret;
3863 }
3864
3865 static 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 }
3887 out:
3888 *mem_limit = min_limit;
3889 *memsw_limit = min_memsw_limit;
3890 return;
3891 }
3892
3893 static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
3894 {
3895 struct mem_cgroup *mem;
3896 int type, name;
3897
3898 mem = mem_cgroup_from_cont(cont);
3899 type = MEMFILE_TYPE(event);
3900 name = MEMFILE_ATTR(event);
3901 switch (name) {
3902 case RES_MAX_USAGE:
3903 if (type == _MEM)
3904 res_counter_reset_max(&mem->res);
3905 else
3906 res_counter_reset_max(&mem->memsw);
3907 break;
3908 case RES_FAILCNT:
3909 if (type == _MEM)
3910 res_counter_reset_failcnt(&mem->res);
3911 else
3912 res_counter_reset_failcnt(&mem->memsw);
3913 break;
3914 }
3915
3916 return 0;
3917 }
3918
3919 static 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
3925 #ifdef CONFIG_MMU
3926 static 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 }
3944 #else
3945 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
3946 struct cftype *cft, u64 val)
3947 {
3948 return -ENOSYS;
3949 }
3950 #endif
3951
3952
3953 /* For read statistics */
3954 enum {
3955 MCS_CACHE,
3956 MCS_RSS,
3957 MCS_FILE_MAPPED,
3958 MCS_PGPGIN,
3959 MCS_PGPGOUT,
3960 MCS_SWAP,
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
3969 struct mcs_total_stat {
3970 s64 stat[NR_MCS_STAT];
3971 };
3972
3973 struct {
3974 char *local_name;
3975 char *total_name;
3976 } memcg_stat_strings[NR_MCS_STAT] = {
3977 {"cache", "total_cache"},
3978 {"rss", "total_rss"},
3979 {"mapped_file", "total_mapped_file"},
3980 {"pgpgin", "total_pgpgin"},
3981 {"pgpgout", "total_pgpgout"},
3982 {"swap", "total_swap"},
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
3991 static void
3992 mem_cgroup_get_local_stat(struct mem_cgroup *mem, struct mcs_total_stat *s)
3993 {
3994 s64 val;
3995
3996 /* per cpu stat */
3997 val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_CACHE);
3998 s->stat[MCS_CACHE] += val * PAGE_SIZE;
3999 val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_RSS);
4000 s->stat[MCS_RSS] += val * PAGE_SIZE;
4001 val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_FILE_MAPPED);
4002 s->stat[MCS_FILE_MAPPED] += val * PAGE_SIZE;
4003 val = mem_cgroup_read_events(mem, MEM_CGROUP_EVENTS_PGPGIN);
4004 s->stat[MCS_PGPGIN] += val;
4005 val = mem_cgroup_read_events(mem, MEM_CGROUP_EVENTS_PGPGOUT);
4006 s->stat[MCS_PGPGOUT] += val;
4007 if (do_swap_account) {
4008 val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_SWAPOUT);
4009 s->stat[MCS_SWAP] += val * PAGE_SIZE;
4010 }
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;
4023 }
4024
4025 static void
4026 mem_cgroup_get_total_stat(struct mem_cgroup *mem, struct mcs_total_stat *s)
4027 {
4028 struct mem_cgroup *iter;
4029
4030 for_each_mem_cgroup_tree(iter, mem)
4031 mem_cgroup_get_local_stat(iter, s);
4032 }
4033
4034 #ifdef CONFIG_NUMA
4035 static 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
4079 static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft,
4080 struct cgroup_map_cb *cb)
4081 {
4082 struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
4083 struct mcs_total_stat mystat;
4084 int i;
4085
4086 memset(&mystat, 0, sizeof(mystat));
4087 mem_cgroup_get_local_stat(mem_cont, &mystat);
4088
4089
4090 for (i = 0; i < NR_MCS_STAT; i++) {
4091 if (i == MCS_SWAP && !do_swap_account)
4092 continue;
4093 cb->fill(cb, memcg_stat_strings[i].local_name, mystat.stat[i]);
4094 }
4095
4096 /* Hierarchical information */
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 }
4104
4105 memset(&mystat, 0, sizeof(mystat));
4106 mem_cgroup_get_total_stat(mem_cont, &mystat);
4107 for (i = 0; i < NR_MCS_STAT; i++) {
4108 if (i == MCS_SWAP && !do_swap_account)
4109 continue;
4110 cb->fill(cb, memcg_stat_strings[i].total_name, mystat.stat[i]);
4111 }
4112
4113 #ifdef CONFIG_DEBUG_VM
4114 cb->fill(cb, "inactive_ratio", calc_inactive_ratio(mem_cont, NULL));
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
4142 return 0;
4143 }
4144
4145 static 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
4152 static 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;
4157
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);
4165
4166 cgroup_lock();
4167
4168 /* If under hierarchy, only empty-root can set this value */
4169 if ((parent->use_hierarchy) ||
4170 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
4171 cgroup_unlock();
4172 return -EINVAL;
4173 }
4174
4175 memcg->swappiness = val;
4176
4177 cgroup_unlock();
4178
4179 return 0;
4180 }
4181
4182 static 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)
4190 t = rcu_dereference(memcg->thresholds.primary);
4191 else
4192 t = rcu_dereference(memcg->memsw_thresholds.primary);
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 */
4204 i = t->current_threshold;
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 */
4228 t->current_threshold = i - 1;
4229 unlock:
4230 rcu_read_unlock();
4231 }
4232
4233 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4234 {
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 }
4242 }
4243
4244 static 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
4252 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *mem)
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
4261 static void mem_cgroup_oom_notify(struct mem_cgroup *mem)
4262 {
4263 struct mem_cgroup *iter;
4264
4265 for_each_mem_cgroup_tree(iter, mem)
4266 mem_cgroup_oom_notify_cb(iter);
4267 }
4268
4269 static int mem_cgroup_usage_register_event(struct cgroup *cgrp,
4270 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
4271 {
4272 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4273 struct mem_cgroup_thresholds *thresholds;
4274 struct mem_cgroup_threshold_ary *new;
4275 int type = MEMFILE_TYPE(cft->private);
4276 u64 threshold, usage;
4277 int i, size, ret;
4278
4279 ret = res_counter_memparse_write_strategy(args, &threshold);
4280 if (ret)
4281 return ret;
4282
4283 mutex_lock(&memcg->thresholds_lock);
4284
4285 if (type == _MEM)
4286 thresholds = &memcg->thresholds;
4287 else if (type == _MEMSWAP)
4288 thresholds = &memcg->memsw_thresholds;
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 */
4295 if (thresholds->primary)
4296 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4297
4298 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
4299
4300 /* Allocate memory for new array of thresholds */
4301 new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
4302 GFP_KERNEL);
4303 if (!new) {
4304 ret = -ENOMEM;
4305 goto unlock;
4306 }
4307 new->size = size;
4308
4309 /* Copy thresholds (if any) to new array */
4310 if (thresholds->primary) {
4311 memcpy(new->entries, thresholds->primary->entries, (size - 1) *
4312 sizeof(struct mem_cgroup_threshold));
4313 }
4314
4315 /* Add new threshold */
4316 new->entries[size - 1].eventfd = eventfd;
4317 new->entries[size - 1].threshold = threshold;
4318
4319 /* Sort thresholds. Registering of new threshold isn't time-critical */
4320 sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
4321 compare_thresholds, NULL);
4322
4323 /* Find current threshold */
4324 new->current_threshold = -1;
4325 for (i = 0; i < size; i++) {
4326 if (new->entries[i].threshold < usage) {
4327 /*
4328 * new->current_threshold will not be used until
4329 * rcu_assign_pointer(), so it's safe to increment
4330 * it here.
4331 */
4332 ++new->current_threshold;
4333 }
4334 }
4335
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);
4341
4342 /* To be sure that nobody uses thresholds */
4343 synchronize_rcu();
4344
4345 unlock:
4346 mutex_unlock(&memcg->thresholds_lock);
4347
4348 return ret;
4349 }
4350
4351 static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,
4352 struct cftype *cft, struct eventfd_ctx *eventfd)
4353 {
4354 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4355 struct mem_cgroup_thresholds *thresholds;
4356 struct mem_cgroup_threshold_ary *new;
4357 int type = MEMFILE_TYPE(cft->private);
4358 u64 usage;
4359 int i, j, size;
4360
4361 mutex_lock(&memcg->thresholds_lock);
4362 if (type == _MEM)
4363 thresholds = &memcg->thresholds;
4364 else if (type == _MEMSWAP)
4365 thresholds = &memcg->memsw_thresholds;
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 */
4381 size = 0;
4382 for (i = 0; i < thresholds->primary->size; i++) {
4383 if (thresholds->primary->entries[i].eventfd != eventfd)
4384 size++;
4385 }
4386
4387 new = thresholds->spare;
4388
4389 /* Set thresholds array to NULL if we don't have thresholds */
4390 if (!size) {
4391 kfree(new);
4392 new = NULL;
4393 goto swap_buffers;
4394 }
4395
4396 new->size = size;
4397
4398 /* Copy thresholds and find current threshold */
4399 new->current_threshold = -1;
4400 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4401 if (thresholds->primary->entries[i].eventfd == eventfd)
4402 continue;
4403
4404 new->entries[j] = thresholds->primary->entries[i];
4405 if (new->entries[j].threshold < usage) {
4406 /*
4407 * new->current_threshold will not be used
4408 * until rcu_assign_pointer(), so it's safe to increment
4409 * it here.
4410 */
4411 ++new->current_threshold;
4412 }
4413 j++;
4414 }
4415
4416 swap_buffers:
4417 /* Swap primary and spare array */
4418 thresholds->spare = thresholds->primary;
4419 rcu_assign_pointer(thresholds->primary, new);
4420
4421 /* To be sure that nobody uses thresholds */
4422 synchronize_rcu();
4423
4424 mutex_unlock(&memcg->thresholds_lock);
4425 }
4426
4427 static 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
4452 static void mem_cgroup_oom_unregister_event(struct cgroup *cgrp,
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);
4471 }
4472
4473 static 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
4487 static 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;
4507 if (!val)
4508 memcg_oom_recover(mem);
4509 cgroup_unlock();
4510 return 0;
4511 }
4512
4513 #ifdef CONFIG_NUMA
4514 static const struct file_operations mem_control_numa_stat_file_operations = {
4515 .read = seq_read,
4516 .llseek = seq_lseek,
4517 .release = single_release,
4518 };
4519
4520 static 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
4529 static struct cftype mem_cgroup_files[] = {
4530 {
4531 .name = "usage_in_bytes",
4532 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
4533 .read_u64 = mem_cgroup_read,
4534 .register_event = mem_cgroup_usage_register_event,
4535 .unregister_event = mem_cgroup_usage_unregister_event,
4536 },
4537 {
4538 .name = "max_usage_in_bytes",
4539 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
4540 .trigger = mem_cgroup_reset,
4541 .read_u64 = mem_cgroup_read,
4542 },
4543 {
4544 .name = "limit_in_bytes",
4545 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
4546 .write_string = mem_cgroup_write,
4547 .read_u64 = mem_cgroup_read,
4548 },
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 },
4555 {
4556 .name = "failcnt",
4557 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
4558 .trigger = mem_cgroup_reset,
4559 .read_u64 = mem_cgroup_read,
4560 },
4561 {
4562 .name = "stat",
4563 .read_map = mem_control_stat_show,
4564 },
4565 {
4566 .name = "force_empty",
4567 .trigger = mem_cgroup_force_empty_write,
4568 },
4569 {
4570 .name = "use_hierarchy",
4571 .write_u64 = mem_cgroup_hierarchy_write,
4572 .read_u64 = mem_cgroup_hierarchy_read,
4573 },
4574 {
4575 .name = "swappiness",
4576 .read_u64 = mem_cgroup_swappiness_read,
4577 .write_u64 = mem_cgroup_swappiness_write,
4578 },
4579 {
4580 .name = "move_charge_at_immigrate",
4581 .read_u64 = mem_cgroup_move_charge_read,
4582 .write_u64 = mem_cgroup_move_charge_write,
4583 },
4584 {
4585 .name = "oom_control",
4586 .read_map = mem_cgroup_oom_control_read,
4587 .write_u64 = mem_cgroup_oom_control_write,
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 },
4592 #ifdef CONFIG_NUMA
4593 {
4594 .name = "numa_stat",
4595 .open = mem_control_numa_stat_open,
4596 },
4597 #endif
4598 };
4599
4600 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4601 static 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,
4606 .register_event = mem_cgroup_usage_register_event,
4607 .unregister_event = mem_cgroup_usage_unregister_event,
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
4629 static 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
4637 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
4638 {
4639 return 0;
4640 }
4641 #endif
4642
4643 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
4644 {
4645 struct mem_cgroup_per_node *pn;
4646 struct mem_cgroup_per_zone *mz;
4647 enum lru_list l;
4648 int zone, tmp = node;
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 */
4657 if (!node_state(node, N_NORMAL_MEMORY))
4658 tmp = -1;
4659 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
4660 if (!pn)
4661 return 1;
4662
4663 mem->info.nodeinfo[node] = pn;
4664 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4665 mz = &pn->zoneinfo[zone];
4666 for_each_lru(l)
4667 INIT_LIST_HEAD(&mz->lists[l]);
4668 mz->usage_in_excess = 0;
4669 mz->on_tree = false;
4670 mz->mem = mem;
4671 }
4672 return 0;
4673 }
4674
4675 static void free_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
4676 {
4677 kfree(mem->info.nodeinfo[node]);
4678 }
4679
4680 static struct mem_cgroup *mem_cgroup_alloc(void)
4681 {
4682 struct mem_cgroup *mem;
4683 int size = sizeof(struct mem_cgroup);
4684
4685 /* Can be very big if MAX_NUMNODES is very big */
4686 if (size < PAGE_SIZE)
4687 mem = kzalloc(size, GFP_KERNEL);
4688 else
4689 mem = vzalloc(size);
4690
4691 if (!mem)
4692 return NULL;
4693
4694 mem->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
4695 if (!mem->stat)
4696 goto out_free;
4697 spin_lock_init(&mem->pcp_counter_lock);
4698 return mem;
4699
4700 out_free:
4701 if (size < PAGE_SIZE)
4702 kfree(mem);
4703 else
4704 vfree(mem);
4705 return NULL;
4706 }
4707
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 *
4716 * Removal of cgroup itself succeeds regardless of refs from swap.
4717 */
4718
4719 static void __mem_cgroup_free(struct mem_cgroup *mem)
4720 {
4721 int node;
4722
4723 mem_cgroup_remove_from_trees(mem);
4724 free_css_id(&mem_cgroup_subsys, &mem->css);
4725
4726 for_each_node_state(node, N_POSSIBLE)
4727 free_mem_cgroup_per_zone_info(mem, node);
4728
4729 free_percpu(mem->stat);
4730 if (sizeof(struct mem_cgroup) < PAGE_SIZE)
4731 kfree(mem);
4732 else
4733 vfree(mem);
4734 }
4735
4736 static void mem_cgroup_get(struct mem_cgroup *mem)
4737 {
4738 atomic_inc(&mem->refcnt);
4739 }
4740
4741 static void __mem_cgroup_put(struct mem_cgroup *mem, int count)
4742 {
4743 if (atomic_sub_and_test(count, &mem->refcnt)) {
4744 struct mem_cgroup *parent = parent_mem_cgroup(mem);
4745 __mem_cgroup_free(mem);
4746 if (parent)
4747 mem_cgroup_put(parent);
4748 }
4749 }
4750
4751 static void mem_cgroup_put(struct mem_cgroup *mem)
4752 {
4753 __mem_cgroup_put(mem, 1);
4754 }
4755
4756 /*
4757 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
4758 */
4759 static 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 }
4765
4766 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4767 static void __init enable_swap_cgroup(void)
4768 {
4769 if (!mem_cgroup_disabled() && really_do_swap_account)
4770 do_swap_account = 1;
4771 }
4772 #else
4773 static void __init enable_swap_cgroup(void)
4774 {
4775 }
4776 #endif
4777
4778 static 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
4803 static struct cgroup_subsys_state * __ref
4804 mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
4805 {
4806 struct mem_cgroup *mem, *parent;
4807 long error = -ENOMEM;
4808 int node;
4809
4810 mem = mem_cgroup_alloc();
4811 if (!mem)
4812 return ERR_PTR(error);
4813
4814 for_each_node_state(node, N_POSSIBLE)
4815 if (alloc_mem_cgroup_per_zone_info(mem, node))
4816 goto free_out;
4817
4818 /* root ? */
4819 if (cont->parent == NULL) {
4820 int cpu;
4821 enable_swap_cgroup();
4822 parent = NULL;
4823 root_mem_cgroup = mem;
4824 if (mem_cgroup_soft_limit_tree_init())
4825 goto free_out;
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 }
4831 hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
4832 } else {
4833 parent = mem_cgroup_from_cont(cont->parent);
4834 mem->use_hierarchy = parent->use_hierarchy;
4835 mem->oom_kill_disable = parent->oom_kill_disable;
4836 }
4837
4838 if (parent && parent->use_hierarchy) {
4839 res_counter_init(&mem->res, &parent->res);
4840 res_counter_init(&mem->memsw, &parent->memsw);
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);
4848 } else {
4849 res_counter_init(&mem->res, NULL);
4850 res_counter_init(&mem->memsw, NULL);
4851 }
4852 mem->last_scanned_child = 0;
4853 mem->last_scanned_node = MAX_NUMNODES;
4854 INIT_LIST_HEAD(&mem->oom_notify);
4855
4856 if (parent)
4857 mem->swappiness = get_swappiness(parent);
4858 atomic_set(&mem->refcnt, 1);
4859 mem->move_charge_at_immigrate = 0;
4860 mutex_init(&mem->thresholds_lock);
4861 return &mem->css;
4862 free_out:
4863 __mem_cgroup_free(mem);
4864 root_mem_cgroup = NULL;
4865 return ERR_PTR(error);
4866 }
4867
4868 static int mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
4869 struct cgroup *cont)
4870 {
4871 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
4872
4873 return mem_cgroup_force_empty(mem, false);
4874 }
4875
4876 static void mem_cgroup_destroy(struct cgroup_subsys *ss,
4877 struct cgroup *cont)
4878 {
4879 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
4880
4881 mem_cgroup_put(mem);
4882 }
4883
4884 static int mem_cgroup_populate(struct cgroup_subsys *ss,
4885 struct cgroup *cont)
4886 {
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;
4895 }
4896
4897 #ifdef CONFIG_MMU
4898 /* Handlers for move charge at task migration. */
4899 #define PRECHARGE_COUNT_AT_ONCE 256
4900 static int mem_cgroup_do_precharge(unsigned long count)
4901 {
4902 int ret = 0;
4903 int batch_count = PRECHARGE_COUNT_AT_ONCE;
4904 struct mem_cgroup *mem = mc.to;
4905
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;
4928 return ret;
4929 }
4930 one_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 }
4941 ret = __mem_cgroup_try_charge(NULL, GFP_KERNEL, 1, &mem, false);
4942 if (ret || !mem)
4943 /* mem_cgroup_clear_mc() will do uncharge later */
4944 return -ENOMEM;
4945 mc.precharge++;
4946 }
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
4955 * @target: the pointer the target page or swap ent will be stored(can be NULL)
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).
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.
4965 *
4966 * Called with pte lock held.
4967 */
4968 union mc_target {
4969 struct page *page;
4970 swp_entry_t ent;
4971 };
4972
4973 enum mc_target_type {
4974 MC_TARGET_NONE, /* not used */
4975 MC_TARGET_PAGE,
4976 MC_TARGET_SWAP,
4977 };
4978
4979 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
4980 unsigned long addr, pte_t ptent)
4981 {
4982 struct page *page = vm_normal_page(vma, addr, ptent);
4983
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;
4990 } else if (!move_file())
4991 /* we ignore mapcount for file pages */
4992 return NULL;
4993 if (!get_page_unless_zero(page))
4994 return NULL;
4995
4996 return page;
4997 }
4998
4999 static 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 */
5010 if (page)
5011 put_page(page);
5012 return NULL;
5013 }
5014 if (do_swap_account)
5015 entry->val = ent.val;
5016
5017 return page;
5018 }
5019
5020 static 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
5053 static 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);
5065 else if (pte_none(ptent) || pte_file(ptent))
5066 page = mc_handle_file_pte(vma, addr, ptent, &ent);
5067
5068 if (!page && !ent.val)
5069 return 0;
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 }
5085 /* There is a swap entry and a page doesn't exist or isn't charged */
5086 if (ent.val && !ret &&
5087 css_id(&mc.from->css) == lookup_swap_cgroup(ent)) {
5088 ret = MC_TARGET_SWAP;
5089 if (target)
5090 target->ent = ent;
5091 }
5092 return ret;
5093 }
5094
5095 static 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
5103 split_huge_page_pmd(walk->mm, pmd);
5104
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
5112 return 0;
5113 }
5114
5115 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
5116 {
5117 unsigned long precharge;
5118 struct vm_area_struct *vma;
5119
5120 down_read(&mm->mmap_sem);
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;
5129 walk_page_range(vma->vm_start, vma->vm_end,
5130 &mem_cgroup_count_precharge_walk);
5131 }
5132 up_read(&mm->mmap_sem);
5133
5134 precharge = mc.precharge;
5135 mc.precharge = 0;
5136
5137 return precharge;
5138 }
5139
5140 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
5141 {
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);
5147 }
5148
5149 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5150 static void __mem_cgroup_clear_mc(void)
5151 {
5152 struct mem_cgroup *from = mc.from;
5153 struct mem_cgroup *to = mc.to;
5154
5155 /* we must uncharge all the leftover precharges from mc.to */
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;
5167 }
5168 /* we must fixup refcnts and charges */
5169 if (mc.moved_swap) {
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);
5183 }
5184 /* we've already done mem_cgroup_get(mc.to) */
5185 mc.moved_swap = 0;
5186 }
5187 memcg_oom_recover(from);
5188 memcg_oom_recover(to);
5189 wake_up_all(&mc.waitq);
5190 }
5191
5192 static 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();
5202 spin_lock(&mc.lock);
5203 mc.from = NULL;
5204 mc.to = NULL;
5205 spin_unlock(&mc.lock);
5206 mem_cgroup_end_move(from);
5207 }
5208
5209 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
5210 struct cgroup *cgroup,
5211 struct task_struct *p)
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;
5225 /* We move charges only when we move a owner of the mm */
5226 if (mm->owner == p) {
5227 VM_BUG_ON(mc.from);
5228 VM_BUG_ON(mc.to);
5229 VM_BUG_ON(mc.precharge);
5230 VM_BUG_ON(mc.moved_charge);
5231 VM_BUG_ON(mc.moved_swap);
5232 mem_cgroup_start_move(from);
5233 spin_lock(&mc.lock);
5234 mc.from = from;
5235 mc.to = mem;
5236 spin_unlock(&mc.lock);
5237 /* We set mc.moving_task later */
5238
5239 ret = mem_cgroup_precharge_mc(mm);
5240 if (ret)
5241 mem_cgroup_clear_mc();
5242 }
5243 mmput(mm);
5244 }
5245 return ret;
5246 }
5247
5248 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
5249 struct cgroup *cgroup,
5250 struct task_struct *p)
5251 {
5252 mem_cgroup_clear_mc();
5253 }
5254
5255 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
5256 unsigned long addr, unsigned long end,
5257 struct mm_walk *walk)
5258 {
5259 int ret = 0;
5260 struct vm_area_struct *vma = walk->private;
5261 pte_t *pte;
5262 spinlock_t *ptl;
5263
5264 split_huge_page_pmd(walk->mm, pmd);
5265 retry:
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;
5273 swp_entry_t ent;
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);
5285 if (!mem_cgroup_move_account(page, 1, pc,
5286 mc.from, mc.to, false)) {
5287 mc.precharge--;
5288 /* we uncharge from mc.from later. */
5289 mc.moved_charge++;
5290 }
5291 putback_lru_page(page);
5292 put: /* is_target_pte_for_mc() gets the page */
5293 put_page(page);
5294 break;
5295 case MC_TARGET_SWAP:
5296 ent = target.ent;
5297 if (!mem_cgroup_move_swap_account(ent,
5298 mc.from, mc.to, false)) {
5299 mc.precharge--;
5300 /* we fixup refcnts and charges later. */
5301 mc.moved_swap++;
5302 }
5303 break;
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 */
5318 ret = mem_cgroup_do_precharge(1);
5319 if (!ret)
5320 goto retry;
5321 }
5322
5323 return ret;
5324 }
5325
5326 static void mem_cgroup_move_charge(struct mm_struct *mm)
5327 {
5328 struct vm_area_struct *vma;
5329
5330 lru_add_drain_all();
5331 retry:
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 }
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;
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 }
5362 up_read(&mm->mmap_sem);
5363 }
5364
5365 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
5366 struct cgroup *cont,
5367 struct cgroup *old_cont,
5368 struct task_struct *p)
5369 {
5370 struct mm_struct *mm;
5371
5372 if (!mc.to)
5373 /* no need to move charge */
5374 return;
5375
5376 mm = get_task_mm(p);
5377 if (mm) {
5378 mem_cgroup_move_charge(mm);
5379 mmput(mm);
5380 }
5381 mem_cgroup_clear_mc();
5382 }
5383 #else /* !CONFIG_MMU */
5384 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
5385 struct cgroup *cgroup,
5386 struct task_struct *p)
5387 {
5388 return 0;
5389 }
5390 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
5391 struct cgroup *cgroup,
5392 struct task_struct *p)
5393 {
5394 }
5395 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
5396 struct cgroup *cont,
5397 struct cgroup *old_cont,
5398 struct task_struct *p)
5399 {
5400 }
5401 #endif
5402
5403 struct cgroup_subsys mem_cgroup_subsys = {
5404 .name = "memory",
5405 .subsys_id = mem_cgroup_subsys_id,
5406 .create = mem_cgroup_create,
5407 .pre_destroy = mem_cgroup_pre_destroy,
5408 .destroy = mem_cgroup_destroy,
5409 .populate = mem_cgroup_populate,
5410 .can_attach = mem_cgroup_can_attach,
5411 .cancel_attach = mem_cgroup_cancel_attach,
5412 .attach = mem_cgroup_move_task,
5413 .early_init = 0,
5414 .use_id = 1,
5415 };
5416
5417 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
5418 static int __init enable_swap_account(char *s)
5419 {
5420 /* consider enabled if no parameter or 1 is given */
5421 if (!strcmp(s, "1"))
5422 really_do_swap_account = 1;
5423 else if (!strcmp(s, "0"))
5424 really_do_swap_account = 0;
5425 return 1;
5426 }
5427 __setup("swapaccount=", enable_swap_account);
5428
5429 #endif