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