e902473f76bfa17bd7bc1c1aead3aa3c4c88a7b6
[platform/adaptation/renesas_rcar/renesas_kernel.git] / kernel / cpuset.c
1 /*
2  *  kernel/cpuset.c
3  *
4  *  Processor and Memory placement constraints for sets of tasks.
5  *
6  *  Copyright (C) 2003 BULL SA.
7  *  Copyright (C) 2004-2007 Silicon Graphics, Inc.
8  *  Copyright (C) 2006 Google, Inc
9  *
10  *  Portions derived from Patrick Mochel's sysfs code.
11  *  sysfs is Copyright (c) 2001-3 Patrick Mochel
12  *
13  *  2003-10-10 Written by Simon Derr.
14  *  2003-10-22 Updates by Stephen Hemminger.
15  *  2004 May-July Rework by Paul Jackson.
16  *  2006 Rework by Paul Menage to use generic cgroups
17  *  2008 Rework of the scheduler domains and CPU hotplug handling
18  *       by Max Krasnyansky
19  *
20  *  This file is subject to the terms and conditions of the GNU General Public
21  *  License.  See the file COPYING in the main directory of the Linux
22  *  distribution for more details.
23  */
24
25 #include <linux/cpu.h>
26 #include <linux/cpumask.h>
27 #include <linux/cpuset.h>
28 #include <linux/err.h>
29 #include <linux/errno.h>
30 #include <linux/file.h>
31 #include <linux/fs.h>
32 #include <linux/init.h>
33 #include <linux/interrupt.h>
34 #include <linux/kernel.h>
35 #include <linux/kmod.h>
36 #include <linux/list.h>
37 #include <linux/mempolicy.h>
38 #include <linux/mm.h>
39 #include <linux/memory.h>
40 #include <linux/export.h>
41 #include <linux/mount.h>
42 #include <linux/namei.h>
43 #include <linux/pagemap.h>
44 #include <linux/proc_fs.h>
45 #include <linux/rcupdate.h>
46 #include <linux/sched.h>
47 #include <linux/seq_file.h>
48 #include <linux/security.h>
49 #include <linux/slab.h>
50 #include <linux/spinlock.h>
51 #include <linux/stat.h>
52 #include <linux/string.h>
53 #include <linux/time.h>
54 #include <linux/backing-dev.h>
55 #include <linux/sort.h>
56
57 #include <asm/uaccess.h>
58 #include <linux/atomic.h>
59 #include <linux/mutex.h>
60 #include <linux/workqueue.h>
61 #include <linux/cgroup.h>
62 #include <linux/wait.h>
63
64 /*
65  * Tracks how many cpusets are currently defined in system.
66  * When there is only one cpuset (the root cpuset) we can
67  * short circuit some hooks.
68  */
69 int number_of_cpusets __read_mostly;
70
71 /* Forward declare cgroup structures */
72 struct cgroup_subsys cpuset_subsys;
73 struct cpuset;
74
75 /* See "Frequency meter" comments, below. */
76
77 struct fmeter {
78         int cnt;                /* unprocessed events count */
79         int val;                /* most recent output value */
80         time_t time;            /* clock (secs) when val computed */
81         spinlock_t lock;        /* guards read or write of above */
82 };
83
84 struct cpuset {
85         struct cgroup_subsys_state css;
86
87         unsigned long flags;            /* "unsigned long" so bitops work */
88         cpumask_var_t cpus_allowed;     /* CPUs allowed to tasks in cpuset */
89         nodemask_t mems_allowed;        /* Memory Nodes allowed to tasks */
90
91         struct fmeter fmeter;           /* memory_pressure filter */
92
93         /*
94          * Tasks are being attached to this cpuset.  Used to prevent
95          * zeroing cpus/mems_allowed between ->can_attach() and ->attach().
96          */
97         int attach_in_progress;
98
99         /* partition number for rebuild_sched_domains() */
100         int pn;
101
102         /* for custom sched domain */
103         int relax_domain_level;
104
105         struct work_struct hotplug_work;
106 };
107
108 /* Retrieve the cpuset for a cgroup */
109 static inline struct cpuset *cgroup_cs(struct cgroup *cont)
110 {
111         return container_of(cgroup_subsys_state(cont, cpuset_subsys_id),
112                             struct cpuset, css);
113 }
114
115 /* Retrieve the cpuset for a task */
116 static inline struct cpuset *task_cs(struct task_struct *task)
117 {
118         return container_of(task_subsys_state(task, cpuset_subsys_id),
119                             struct cpuset, css);
120 }
121
122 static inline struct cpuset *parent_cs(const struct cpuset *cs)
123 {
124         struct cgroup *pcgrp = cs->css.cgroup->parent;
125
126         if (pcgrp)
127                 return cgroup_cs(pcgrp);
128         return NULL;
129 }
130
131 #ifdef CONFIG_NUMA
132 static inline bool task_has_mempolicy(struct task_struct *task)
133 {
134         return task->mempolicy;
135 }
136 #else
137 static inline bool task_has_mempolicy(struct task_struct *task)
138 {
139         return false;
140 }
141 #endif
142
143
144 /* bits in struct cpuset flags field */
145 typedef enum {
146         CS_ONLINE,
147         CS_CPU_EXCLUSIVE,
148         CS_MEM_EXCLUSIVE,
149         CS_MEM_HARDWALL,
150         CS_MEMORY_MIGRATE,
151         CS_SCHED_LOAD_BALANCE,
152         CS_SPREAD_PAGE,
153         CS_SPREAD_SLAB,
154 } cpuset_flagbits_t;
155
156 /* convenient tests for these bits */
157 static inline bool is_cpuset_online(const struct cpuset *cs)
158 {
159         return test_bit(CS_ONLINE, &cs->flags);
160 }
161
162 static inline int is_cpu_exclusive(const struct cpuset *cs)
163 {
164         return test_bit(CS_CPU_EXCLUSIVE, &cs->flags);
165 }
166
167 static inline int is_mem_exclusive(const struct cpuset *cs)
168 {
169         return test_bit(CS_MEM_EXCLUSIVE, &cs->flags);
170 }
171
172 static inline int is_mem_hardwall(const struct cpuset *cs)
173 {
174         return test_bit(CS_MEM_HARDWALL, &cs->flags);
175 }
176
177 static inline int is_sched_load_balance(const struct cpuset *cs)
178 {
179         return test_bit(CS_SCHED_LOAD_BALANCE, &cs->flags);
180 }
181
182 static inline int is_memory_migrate(const struct cpuset *cs)
183 {
184         return test_bit(CS_MEMORY_MIGRATE, &cs->flags);
185 }
186
187 static inline int is_spread_page(const struct cpuset *cs)
188 {
189         return test_bit(CS_SPREAD_PAGE, &cs->flags);
190 }
191
192 static inline int is_spread_slab(const struct cpuset *cs)
193 {
194         return test_bit(CS_SPREAD_SLAB, &cs->flags);
195 }
196
197 static struct cpuset top_cpuset = {
198         .flags = ((1 << CS_ONLINE) | (1 << CS_CPU_EXCLUSIVE) |
199                   (1 << CS_MEM_EXCLUSIVE)),
200 };
201
202 /**
203  * cpuset_for_each_child - traverse online children of a cpuset
204  * @child_cs: loop cursor pointing to the current child
205  * @pos_cgrp: used for iteration
206  * @parent_cs: target cpuset to walk children of
207  *
208  * Walk @child_cs through the online children of @parent_cs.  Must be used
209  * with RCU read locked.
210  */
211 #define cpuset_for_each_child(child_cs, pos_cgrp, parent_cs)            \
212         cgroup_for_each_child((pos_cgrp), (parent_cs)->css.cgroup)      \
213                 if (is_cpuset_online(((child_cs) = cgroup_cs((pos_cgrp)))))
214
215 /**
216  * cpuset_for_each_descendant_pre - pre-order walk of a cpuset's descendants
217  * @des_cs: loop cursor pointing to the current descendant
218  * @pos_cgrp: used for iteration
219  * @root_cs: target cpuset to walk ancestor of
220  *
221  * Walk @des_cs through the online descendants of @root_cs.  Must be used
222  * with RCU read locked.  The caller may modify @pos_cgrp by calling
223  * cgroup_rightmost_descendant() to skip subtree.
224  */
225 #define cpuset_for_each_descendant_pre(des_cs, pos_cgrp, root_cs)       \
226         cgroup_for_each_descendant_pre((pos_cgrp), (root_cs)->css.cgroup) \
227                 if (is_cpuset_online(((des_cs) = cgroup_cs((pos_cgrp)))))
228
229 /*
230  * There are two global mutexes guarding cpuset structures - cpuset_mutex
231  * and callback_mutex.  The latter may nest inside the former.  We also
232  * require taking task_lock() when dereferencing a task's cpuset pointer.
233  * See "The task_lock() exception", at the end of this comment.
234  *
235  * A task must hold both mutexes to modify cpusets.  If a task holds
236  * cpuset_mutex, then it blocks others wanting that mutex, ensuring that it
237  * is the only task able to also acquire callback_mutex and be able to
238  * modify cpusets.  It can perform various checks on the cpuset structure
239  * first, knowing nothing will change.  It can also allocate memory while
240  * just holding cpuset_mutex.  While it is performing these checks, various
241  * callback routines can briefly acquire callback_mutex to query cpusets.
242  * Once it is ready to make the changes, it takes callback_mutex, blocking
243  * everyone else.
244  *
245  * Calls to the kernel memory allocator can not be made while holding
246  * callback_mutex, as that would risk double tripping on callback_mutex
247  * from one of the callbacks into the cpuset code from within
248  * __alloc_pages().
249  *
250  * If a task is only holding callback_mutex, then it has read-only
251  * access to cpusets.
252  *
253  * Now, the task_struct fields mems_allowed and mempolicy may be changed
254  * by other task, we use alloc_lock in the task_struct fields to protect
255  * them.
256  *
257  * The cpuset_common_file_read() handlers only hold callback_mutex across
258  * small pieces of code, such as when reading out possibly multi-word
259  * cpumasks and nodemasks.
260  *
261  * Accessing a task's cpuset should be done in accordance with the
262  * guidelines for accessing subsystem state in kernel/cgroup.c
263  */
264
265 static DEFINE_MUTEX(cpuset_mutex);
266 static DEFINE_MUTEX(callback_mutex);
267
268 /*
269  * CPU / memory hotplug is handled asynchronously.
270  */
271 static struct workqueue_struct *cpuset_propagate_hotplug_wq;
272
273 static void cpuset_hotplug_workfn(struct work_struct *work);
274 static void cpuset_propagate_hotplug_workfn(struct work_struct *work);
275 static void schedule_cpuset_propagate_hotplug(struct cpuset *cs);
276
277 static DECLARE_WORK(cpuset_hotplug_work, cpuset_hotplug_workfn);
278
279 static DECLARE_WAIT_QUEUE_HEAD(cpuset_attach_wq);
280
281 /*
282  * This is ugly, but preserves the userspace API for existing cpuset
283  * users. If someone tries to mount the "cpuset" filesystem, we
284  * silently switch it to mount "cgroup" instead
285  */
286 static struct dentry *cpuset_mount(struct file_system_type *fs_type,
287                          int flags, const char *unused_dev_name, void *data)
288 {
289         struct file_system_type *cgroup_fs = get_fs_type("cgroup");
290         struct dentry *ret = ERR_PTR(-ENODEV);
291         if (cgroup_fs) {
292                 char mountopts[] =
293                         "cpuset,noprefix,"
294                         "release_agent=/sbin/cpuset_release_agent";
295                 ret = cgroup_fs->mount(cgroup_fs, flags,
296                                            unused_dev_name, mountopts);
297                 put_filesystem(cgroup_fs);
298         }
299         return ret;
300 }
301
302 static struct file_system_type cpuset_fs_type = {
303         .name = "cpuset",
304         .mount = cpuset_mount,
305 };
306
307 /*
308  * Return in pmask the portion of a cpusets's cpus_allowed that
309  * are online.  If none are online, walk up the cpuset hierarchy
310  * until we find one that does have some online cpus.  The top
311  * cpuset always has some cpus online.
312  *
313  * One way or another, we guarantee to return some non-empty subset
314  * of cpu_online_mask.
315  *
316  * Call with callback_mutex held.
317  */
318 static void guarantee_online_cpus(const struct cpuset *cs,
319                                   struct cpumask *pmask)
320 {
321         while (!cpumask_intersects(cs->cpus_allowed, cpu_online_mask))
322                 cs = parent_cs(cs);
323         cpumask_and(pmask, cs->cpus_allowed, cpu_online_mask);
324 }
325
326 /*
327  * Return in *pmask the portion of a cpusets's mems_allowed that
328  * are online, with memory.  If none are online with memory, walk
329  * up the cpuset hierarchy until we find one that does have some
330  * online mems.  The top cpuset always has some mems online.
331  *
332  * One way or another, we guarantee to return some non-empty subset
333  * of node_states[N_MEMORY].
334  *
335  * Call with callback_mutex held.
336  */
337 static void guarantee_online_mems(const struct cpuset *cs, nodemask_t *pmask)
338 {
339         while (!nodes_intersects(cs->mems_allowed, node_states[N_MEMORY]))
340                 cs = parent_cs(cs);
341         nodes_and(*pmask, cs->mems_allowed, node_states[N_MEMORY]);
342 }
343
344 /*
345  * update task's spread flag if cpuset's page/slab spread flag is set
346  *
347  * Called with callback_mutex/cpuset_mutex held
348  */
349 static void cpuset_update_task_spread_flag(struct cpuset *cs,
350                                         struct task_struct *tsk)
351 {
352         if (is_spread_page(cs))
353                 tsk->flags |= PF_SPREAD_PAGE;
354         else
355                 tsk->flags &= ~PF_SPREAD_PAGE;
356         if (is_spread_slab(cs))
357                 tsk->flags |= PF_SPREAD_SLAB;
358         else
359                 tsk->flags &= ~PF_SPREAD_SLAB;
360 }
361
362 /*
363  * is_cpuset_subset(p, q) - Is cpuset p a subset of cpuset q?
364  *
365  * One cpuset is a subset of another if all its allowed CPUs and
366  * Memory Nodes are a subset of the other, and its exclusive flags
367  * are only set if the other's are set.  Call holding cpuset_mutex.
368  */
369
370 static int is_cpuset_subset(const struct cpuset *p, const struct cpuset *q)
371 {
372         return  cpumask_subset(p->cpus_allowed, q->cpus_allowed) &&
373                 nodes_subset(p->mems_allowed, q->mems_allowed) &&
374                 is_cpu_exclusive(p) <= is_cpu_exclusive(q) &&
375                 is_mem_exclusive(p) <= is_mem_exclusive(q);
376 }
377
378 /**
379  * alloc_trial_cpuset - allocate a trial cpuset
380  * @cs: the cpuset that the trial cpuset duplicates
381  */
382 static struct cpuset *alloc_trial_cpuset(const struct cpuset *cs)
383 {
384         struct cpuset *trial;
385
386         trial = kmemdup(cs, sizeof(*cs), GFP_KERNEL);
387         if (!trial)
388                 return NULL;
389
390         if (!alloc_cpumask_var(&trial->cpus_allowed, GFP_KERNEL)) {
391                 kfree(trial);
392                 return NULL;
393         }
394         cpumask_copy(trial->cpus_allowed, cs->cpus_allowed);
395
396         return trial;
397 }
398
399 /**
400  * free_trial_cpuset - free the trial cpuset
401  * @trial: the trial cpuset to be freed
402  */
403 static void free_trial_cpuset(struct cpuset *trial)
404 {
405         free_cpumask_var(trial->cpus_allowed);
406         kfree(trial);
407 }
408
409 /*
410  * validate_change() - Used to validate that any proposed cpuset change
411  *                     follows the structural rules for cpusets.
412  *
413  * If we replaced the flag and mask values of the current cpuset
414  * (cur) with those values in the trial cpuset (trial), would
415  * our various subset and exclusive rules still be valid?  Presumes
416  * cpuset_mutex held.
417  *
418  * 'cur' is the address of an actual, in-use cpuset.  Operations
419  * such as list traversal that depend on the actual address of the
420  * cpuset in the list must use cur below, not trial.
421  *
422  * 'trial' is the address of bulk structure copy of cur, with
423  * perhaps one or more of the fields cpus_allowed, mems_allowed,
424  * or flags changed to new, trial values.
425  *
426  * Return 0 if valid, -errno if not.
427  */
428
429 static int validate_change(const struct cpuset *cur, const struct cpuset *trial)
430 {
431         struct cgroup *cont;
432         struct cpuset *c, *par;
433         int ret;
434
435         rcu_read_lock();
436
437         /* Each of our child cpusets must be a subset of us */
438         ret = -EBUSY;
439         cpuset_for_each_child(c, cont, cur)
440                 if (!is_cpuset_subset(c, trial))
441                         goto out;
442
443         /* Remaining checks don't apply to root cpuset */
444         ret = 0;
445         if (cur == &top_cpuset)
446                 goto out;
447
448         par = parent_cs(cur);
449
450         /* We must be a subset of our parent cpuset */
451         ret = -EACCES;
452         if (!is_cpuset_subset(trial, par))
453                 goto out;
454
455         /*
456          * If either I or some sibling (!= me) is exclusive, we can't
457          * overlap
458          */
459         ret = -EINVAL;
460         cpuset_for_each_child(c, cont, par) {
461                 if ((is_cpu_exclusive(trial) || is_cpu_exclusive(c)) &&
462                     c != cur &&
463                     cpumask_intersects(trial->cpus_allowed, c->cpus_allowed))
464                         goto out;
465                 if ((is_mem_exclusive(trial) || is_mem_exclusive(c)) &&
466                     c != cur &&
467                     nodes_intersects(trial->mems_allowed, c->mems_allowed))
468                         goto out;
469         }
470
471         /*
472          * Cpusets with tasks - existing or newly being attached - can't
473          * have empty cpus_allowed or mems_allowed.
474          */
475         ret = -ENOSPC;
476         if ((cgroup_task_count(cur->css.cgroup) || cur->attach_in_progress) &&
477             (cpumask_empty(trial->cpus_allowed) ||
478              nodes_empty(trial->mems_allowed)))
479                 goto out;
480
481         ret = 0;
482 out:
483         rcu_read_unlock();
484         return ret;
485 }
486
487 #ifdef CONFIG_SMP
488 /*
489  * Helper routine for generate_sched_domains().
490  * Do cpusets a, b have overlapping cpus_allowed masks?
491  */
492 static int cpusets_overlap(struct cpuset *a, struct cpuset *b)
493 {
494         return cpumask_intersects(a->cpus_allowed, b->cpus_allowed);
495 }
496
497 static void
498 update_domain_attr(struct sched_domain_attr *dattr, struct cpuset *c)
499 {
500         if (dattr->relax_domain_level < c->relax_domain_level)
501                 dattr->relax_domain_level = c->relax_domain_level;
502         return;
503 }
504
505 static void update_domain_attr_tree(struct sched_domain_attr *dattr,
506                                     struct cpuset *root_cs)
507 {
508         struct cpuset *cp;
509         struct cgroup *pos_cgrp;
510
511         rcu_read_lock();
512         cpuset_for_each_descendant_pre(cp, pos_cgrp, root_cs) {
513                 /* skip the whole subtree if @cp doesn't have any CPU */
514                 if (cpumask_empty(cp->cpus_allowed)) {
515                         pos_cgrp = cgroup_rightmost_descendant(pos_cgrp);
516                         continue;
517                 }
518
519                 if (is_sched_load_balance(cp))
520                         update_domain_attr(dattr, cp);
521         }
522         rcu_read_unlock();
523 }
524
525 /*
526  * generate_sched_domains()
527  *
528  * This function builds a partial partition of the systems CPUs
529  * A 'partial partition' is a set of non-overlapping subsets whose
530  * union is a subset of that set.
531  * The output of this function needs to be passed to kernel/sched.c
532  * partition_sched_domains() routine, which will rebuild the scheduler's
533  * load balancing domains (sched domains) as specified by that partial
534  * partition.
535  *
536  * See "What is sched_load_balance" in Documentation/cgroups/cpusets.txt
537  * for a background explanation of this.
538  *
539  * Does not return errors, on the theory that the callers of this
540  * routine would rather not worry about failures to rebuild sched
541  * domains when operating in the severe memory shortage situations
542  * that could cause allocation failures below.
543  *
544  * Must be called with cpuset_mutex held.
545  *
546  * The three key local variables below are:
547  *    q  - a linked-list queue of cpuset pointers, used to implement a
548  *         top-down scan of all cpusets.  This scan loads a pointer
549  *         to each cpuset marked is_sched_load_balance into the
550  *         array 'csa'.  For our purposes, rebuilding the schedulers
551  *         sched domains, we can ignore !is_sched_load_balance cpusets.
552  *  csa  - (for CpuSet Array) Array of pointers to all the cpusets
553  *         that need to be load balanced, for convenient iterative
554  *         access by the subsequent code that finds the best partition,
555  *         i.e the set of domains (subsets) of CPUs such that the
556  *         cpus_allowed of every cpuset marked is_sched_load_balance
557  *         is a subset of one of these domains, while there are as
558  *         many such domains as possible, each as small as possible.
559  * doms  - Conversion of 'csa' to an array of cpumasks, for passing to
560  *         the kernel/sched.c routine partition_sched_domains() in a
561  *         convenient format, that can be easily compared to the prior
562  *         value to determine what partition elements (sched domains)
563  *         were changed (added or removed.)
564  *
565  * Finding the best partition (set of domains):
566  *      The triple nested loops below over i, j, k scan over the
567  *      load balanced cpusets (using the array of cpuset pointers in
568  *      csa[]) looking for pairs of cpusets that have overlapping
569  *      cpus_allowed, but which don't have the same 'pn' partition
570  *      number and gives them in the same partition number.  It keeps
571  *      looping on the 'restart' label until it can no longer find
572  *      any such pairs.
573  *
574  *      The union of the cpus_allowed masks from the set of
575  *      all cpusets having the same 'pn' value then form the one
576  *      element of the partition (one sched domain) to be passed to
577  *      partition_sched_domains().
578  */
579 static int generate_sched_domains(cpumask_var_t **domains,
580                         struct sched_domain_attr **attributes)
581 {
582         struct cpuset *cp;      /* scans q */
583         struct cpuset **csa;    /* array of all cpuset ptrs */
584         int csn;                /* how many cpuset ptrs in csa so far */
585         int i, j, k;            /* indices for partition finding loops */
586         cpumask_var_t *doms;    /* resulting partition; i.e. sched domains */
587         struct sched_domain_attr *dattr;  /* attributes for custom domains */
588         int ndoms = 0;          /* number of sched domains in result */
589         int nslot;              /* next empty doms[] struct cpumask slot */
590         struct cgroup *pos_cgrp;
591
592         doms = NULL;
593         dattr = NULL;
594         csa = NULL;
595
596         /* Special case for the 99% of systems with one, full, sched domain */
597         if (is_sched_load_balance(&top_cpuset)) {
598                 ndoms = 1;
599                 doms = alloc_sched_domains(ndoms);
600                 if (!doms)
601                         goto done;
602
603                 dattr = kmalloc(sizeof(struct sched_domain_attr), GFP_KERNEL);
604                 if (dattr) {
605                         *dattr = SD_ATTR_INIT;
606                         update_domain_attr_tree(dattr, &top_cpuset);
607                 }
608                 cpumask_copy(doms[0], top_cpuset.cpus_allowed);
609
610                 goto done;
611         }
612
613         csa = kmalloc(number_of_cpusets * sizeof(cp), GFP_KERNEL);
614         if (!csa)
615                 goto done;
616         csn = 0;
617
618         rcu_read_lock();
619         cpuset_for_each_descendant_pre(cp, pos_cgrp, &top_cpuset) {
620                 /*
621                  * Continue traversing beyond @cp iff @cp has some CPUs and
622                  * isn't load balancing.  The former is obvious.  The
623                  * latter: All child cpusets contain a subset of the
624                  * parent's cpus, so just skip them, and then we call
625                  * update_domain_attr_tree() to calc relax_domain_level of
626                  * the corresponding sched domain.
627                  */
628                 if (!cpumask_empty(cp->cpus_allowed) &&
629                     !is_sched_load_balance(cp))
630                         continue;
631
632                 if (is_sched_load_balance(cp))
633                         csa[csn++] = cp;
634
635                 /* skip @cp's subtree */
636                 pos_cgrp = cgroup_rightmost_descendant(pos_cgrp);
637         }
638         rcu_read_unlock();
639
640         for (i = 0; i < csn; i++)
641                 csa[i]->pn = i;
642         ndoms = csn;
643
644 restart:
645         /* Find the best partition (set of sched domains) */
646         for (i = 0; i < csn; i++) {
647                 struct cpuset *a = csa[i];
648                 int apn = a->pn;
649
650                 for (j = 0; j < csn; j++) {
651                         struct cpuset *b = csa[j];
652                         int bpn = b->pn;
653
654                         if (apn != bpn && cpusets_overlap(a, b)) {
655                                 for (k = 0; k < csn; k++) {
656                                         struct cpuset *c = csa[k];
657
658                                         if (c->pn == bpn)
659                                                 c->pn = apn;
660                                 }
661                                 ndoms--;        /* one less element */
662                                 goto restart;
663                         }
664                 }
665         }
666
667         /*
668          * Now we know how many domains to create.
669          * Convert <csn, csa> to <ndoms, doms> and populate cpu masks.
670          */
671         doms = alloc_sched_domains(ndoms);
672         if (!doms)
673                 goto done;
674
675         /*
676          * The rest of the code, including the scheduler, can deal with
677          * dattr==NULL case. No need to abort if alloc fails.
678          */
679         dattr = kmalloc(ndoms * sizeof(struct sched_domain_attr), GFP_KERNEL);
680
681         for (nslot = 0, i = 0; i < csn; i++) {
682                 struct cpuset *a = csa[i];
683                 struct cpumask *dp;
684                 int apn = a->pn;
685
686                 if (apn < 0) {
687                         /* Skip completed partitions */
688                         continue;
689                 }
690
691                 dp = doms[nslot];
692
693                 if (nslot == ndoms) {
694                         static int warnings = 10;
695                         if (warnings) {
696                                 printk(KERN_WARNING
697                                  "rebuild_sched_domains confused:"
698                                   " nslot %d, ndoms %d, csn %d, i %d,"
699                                   " apn %d\n",
700                                   nslot, ndoms, csn, i, apn);
701                                 warnings--;
702                         }
703                         continue;
704                 }
705
706                 cpumask_clear(dp);
707                 if (dattr)
708                         *(dattr + nslot) = SD_ATTR_INIT;
709                 for (j = i; j < csn; j++) {
710                         struct cpuset *b = csa[j];
711
712                         if (apn == b->pn) {
713                                 cpumask_or(dp, dp, b->cpus_allowed);
714                                 if (dattr)
715                                         update_domain_attr_tree(dattr + nslot, b);
716
717                                 /* Done with this partition */
718                                 b->pn = -1;
719                         }
720                 }
721                 nslot++;
722         }
723         BUG_ON(nslot != ndoms);
724
725 done:
726         kfree(csa);
727
728         /*
729          * Fallback to the default domain if kmalloc() failed.
730          * See comments in partition_sched_domains().
731          */
732         if (doms == NULL)
733                 ndoms = 1;
734
735         *domains    = doms;
736         *attributes = dattr;
737         return ndoms;
738 }
739
740 /*
741  * Rebuild scheduler domains.
742  *
743  * If the flag 'sched_load_balance' of any cpuset with non-empty
744  * 'cpus' changes, or if the 'cpus' allowed changes in any cpuset
745  * which has that flag enabled, or if any cpuset with a non-empty
746  * 'cpus' is removed, then call this routine to rebuild the
747  * scheduler's dynamic sched domains.
748  *
749  * Call with cpuset_mutex held.  Takes get_online_cpus().
750  */
751 static void rebuild_sched_domains_locked(void)
752 {
753         struct sched_domain_attr *attr;
754         cpumask_var_t *doms;
755         int ndoms;
756
757         lockdep_assert_held(&cpuset_mutex);
758         get_online_cpus();
759
760         /*
761          * We have raced with CPU hotplug. Don't do anything to avoid
762          * passing doms with offlined cpu to partition_sched_domains().
763          * Anyways, hotplug work item will rebuild sched domains.
764          */
765         if (!cpumask_equal(top_cpuset.cpus_allowed, cpu_active_mask))
766                 goto out;
767
768         /* Generate domain masks and attrs */
769         ndoms = generate_sched_domains(&doms, &attr);
770
771         /* Have scheduler rebuild the domains */
772         partition_sched_domains(ndoms, doms, attr);
773 out:
774         put_online_cpus();
775 }
776 #else /* !CONFIG_SMP */
777 static void rebuild_sched_domains_locked(void)
778 {
779 }
780 #endif /* CONFIG_SMP */
781
782 void rebuild_sched_domains(void)
783 {
784         mutex_lock(&cpuset_mutex);
785         rebuild_sched_domains_locked();
786         mutex_unlock(&cpuset_mutex);
787 }
788
789 /**
790  * cpuset_change_cpumask - make a task's cpus_allowed the same as its cpuset's
791  * @tsk: task to test
792  * @scan: struct cgroup_scanner containing the cgroup of the task
793  *
794  * Called by cgroup_scan_tasks() for each task in a cgroup whose
795  * cpus_allowed mask needs to be changed.
796  *
797  * We don't need to re-check for the cgroup/cpuset membership, since we're
798  * holding cpuset_mutex at this point.
799  */
800 static void cpuset_change_cpumask(struct task_struct *tsk,
801                                   struct cgroup_scanner *scan)
802 {
803         set_cpus_allowed_ptr(tsk, ((cgroup_cs(scan->cg))->cpus_allowed));
804 }
805
806 /**
807  * update_tasks_cpumask - Update the cpumasks of tasks in the cpuset.
808  * @cs: the cpuset in which each task's cpus_allowed mask needs to be changed
809  * @heap: if NULL, defer allocating heap memory to cgroup_scan_tasks()
810  *
811  * Called with cpuset_mutex held
812  *
813  * The cgroup_scan_tasks() function will scan all the tasks in a cgroup,
814  * calling callback functions for each.
815  *
816  * No return value. It's guaranteed that cgroup_scan_tasks() always returns 0
817  * if @heap != NULL.
818  */
819 static void update_tasks_cpumask(struct cpuset *cs, struct ptr_heap *heap)
820 {
821         struct cgroup_scanner scan;
822
823         scan.cg = cs->css.cgroup;
824         scan.test_task = NULL;
825         scan.process_task = cpuset_change_cpumask;
826         scan.heap = heap;
827         cgroup_scan_tasks(&scan);
828 }
829
830 /**
831  * update_cpumask - update the cpus_allowed mask of a cpuset and all tasks in it
832  * @cs: the cpuset to consider
833  * @buf: buffer of cpu numbers written to this cpuset
834  */
835 static int update_cpumask(struct cpuset *cs, struct cpuset *trialcs,
836                           const char *buf)
837 {
838         struct ptr_heap heap;
839         int retval;
840         int is_load_balanced;
841
842         /* top_cpuset.cpus_allowed tracks cpu_online_mask; it's read-only */
843         if (cs == &top_cpuset)
844                 return -EACCES;
845
846         /*
847          * An empty cpus_allowed is ok only if the cpuset has no tasks.
848          * Since cpulist_parse() fails on an empty mask, we special case
849          * that parsing.  The validate_change() call ensures that cpusets
850          * with tasks have cpus.
851          */
852         if (!*buf) {
853                 cpumask_clear(trialcs->cpus_allowed);
854         } else {
855                 retval = cpulist_parse(buf, trialcs->cpus_allowed);
856                 if (retval < 0)
857                         return retval;
858
859                 if (!cpumask_subset(trialcs->cpus_allowed, cpu_active_mask))
860                         return -EINVAL;
861         }
862
863         /* Nothing to do if the cpus didn't change */
864         if (cpumask_equal(cs->cpus_allowed, trialcs->cpus_allowed))
865                 return 0;
866
867         retval = validate_change(cs, trialcs);
868         if (retval < 0)
869                 return retval;
870
871         retval = heap_init(&heap, PAGE_SIZE, GFP_KERNEL, NULL);
872         if (retval)
873                 return retval;
874
875         is_load_balanced = is_sched_load_balance(trialcs);
876
877         mutex_lock(&callback_mutex);
878         cpumask_copy(cs->cpus_allowed, trialcs->cpus_allowed);
879         mutex_unlock(&callback_mutex);
880
881         /*
882          * Scan tasks in the cpuset, and update the cpumasks of any
883          * that need an update.
884          */
885         update_tasks_cpumask(cs, &heap);
886
887         heap_free(&heap);
888
889         if (is_load_balanced)
890                 rebuild_sched_domains_locked();
891         return 0;
892 }
893
894 /*
895  * cpuset_migrate_mm
896  *
897  *    Migrate memory region from one set of nodes to another.
898  *
899  *    Temporarilly set tasks mems_allowed to target nodes of migration,
900  *    so that the migration code can allocate pages on these nodes.
901  *
902  *    Call holding cpuset_mutex, so current's cpuset won't change
903  *    during this call, as manage_mutex holds off any cpuset_attach()
904  *    calls.  Therefore we don't need to take task_lock around the
905  *    call to guarantee_online_mems(), as we know no one is changing
906  *    our task's cpuset.
907  *
908  *    While the mm_struct we are migrating is typically from some
909  *    other task, the task_struct mems_allowed that we are hacking
910  *    is for our current task, which must allocate new pages for that
911  *    migrating memory region.
912  */
913
914 static void cpuset_migrate_mm(struct mm_struct *mm, const nodemask_t *from,
915                                                         const nodemask_t *to)
916 {
917         struct task_struct *tsk = current;
918
919         tsk->mems_allowed = *to;
920
921         do_migrate_pages(mm, from, to, MPOL_MF_MOVE_ALL);
922
923         guarantee_online_mems(task_cs(tsk),&tsk->mems_allowed);
924 }
925
926 /*
927  * cpuset_change_task_nodemask - change task's mems_allowed and mempolicy
928  * @tsk: the task to change
929  * @newmems: new nodes that the task will be set
930  *
931  * In order to avoid seeing no nodes if the old and new nodes are disjoint,
932  * we structure updates as setting all new allowed nodes, then clearing newly
933  * disallowed ones.
934  */
935 static void cpuset_change_task_nodemask(struct task_struct *tsk,
936                                         nodemask_t *newmems)
937 {
938         bool need_loop;
939
940         /*
941          * Allow tasks that have access to memory reserves because they have
942          * been OOM killed to get memory anywhere.
943          */
944         if (unlikely(test_thread_flag(TIF_MEMDIE)))
945                 return;
946         if (current->flags & PF_EXITING) /* Let dying task have memory */
947                 return;
948
949         task_lock(tsk);
950         /*
951          * Determine if a loop is necessary if another thread is doing
952          * get_mems_allowed().  If at least one node remains unchanged and
953          * tsk does not have a mempolicy, then an empty nodemask will not be
954          * possible when mems_allowed is larger than a word.
955          */
956         need_loop = task_has_mempolicy(tsk) ||
957                         !nodes_intersects(*newmems, tsk->mems_allowed);
958
959         if (need_loop)
960                 write_seqcount_begin(&tsk->mems_allowed_seq);
961
962         nodes_or(tsk->mems_allowed, tsk->mems_allowed, *newmems);
963         mpol_rebind_task(tsk, newmems, MPOL_REBIND_STEP1);
964
965         mpol_rebind_task(tsk, newmems, MPOL_REBIND_STEP2);
966         tsk->mems_allowed = *newmems;
967
968         if (need_loop)
969                 write_seqcount_end(&tsk->mems_allowed_seq);
970
971         task_unlock(tsk);
972 }
973
974 /*
975  * Update task's mems_allowed and rebind its mempolicy and vmas' mempolicy
976  * of it to cpuset's new mems_allowed, and migrate pages to new nodes if
977  * memory_migrate flag is set. Called with cpuset_mutex held.
978  */
979 static void cpuset_change_nodemask(struct task_struct *p,
980                                    struct cgroup_scanner *scan)
981 {
982         struct mm_struct *mm;
983         struct cpuset *cs;
984         int migrate;
985         const nodemask_t *oldmem = scan->data;
986         static nodemask_t newmems;      /* protected by cpuset_mutex */
987
988         cs = cgroup_cs(scan->cg);
989         guarantee_online_mems(cs, &newmems);
990
991         cpuset_change_task_nodemask(p, &newmems);
992
993         mm = get_task_mm(p);
994         if (!mm)
995                 return;
996
997         migrate = is_memory_migrate(cs);
998
999         mpol_rebind_mm(mm, &cs->mems_allowed);
1000         if (migrate)
1001                 cpuset_migrate_mm(mm, oldmem, &cs->mems_allowed);
1002         mmput(mm);
1003 }
1004
1005 static void *cpuset_being_rebound;
1006
1007 /**
1008  * update_tasks_nodemask - Update the nodemasks of tasks in the cpuset.
1009  * @cs: the cpuset in which each task's mems_allowed mask needs to be changed
1010  * @oldmem: old mems_allowed of cpuset cs
1011  * @heap: if NULL, defer allocating heap memory to cgroup_scan_tasks()
1012  *
1013  * Called with cpuset_mutex held
1014  * No return value. It's guaranteed that cgroup_scan_tasks() always returns 0
1015  * if @heap != NULL.
1016  */
1017 static void update_tasks_nodemask(struct cpuset *cs, const nodemask_t *oldmem,
1018                                  struct ptr_heap *heap)
1019 {
1020         struct cgroup_scanner scan;
1021
1022         cpuset_being_rebound = cs;              /* causes mpol_dup() rebind */
1023
1024         scan.cg = cs->css.cgroup;
1025         scan.test_task = NULL;
1026         scan.process_task = cpuset_change_nodemask;
1027         scan.heap = heap;
1028         scan.data = (nodemask_t *)oldmem;
1029
1030         /*
1031          * The mpol_rebind_mm() call takes mmap_sem, which we couldn't
1032          * take while holding tasklist_lock.  Forks can happen - the
1033          * mpol_dup() cpuset_being_rebound check will catch such forks,
1034          * and rebind their vma mempolicies too.  Because we still hold
1035          * the global cpuset_mutex, we know that no other rebind effort
1036          * will be contending for the global variable cpuset_being_rebound.
1037          * It's ok if we rebind the same mm twice; mpol_rebind_mm()
1038          * is idempotent.  Also migrate pages in each mm to new nodes.
1039          */
1040         cgroup_scan_tasks(&scan);
1041
1042         /* We're done rebinding vmas to this cpuset's new mems_allowed. */
1043         cpuset_being_rebound = NULL;
1044 }
1045
1046 /*
1047  * Handle user request to change the 'mems' memory placement
1048  * of a cpuset.  Needs to validate the request, update the
1049  * cpusets mems_allowed, and for each task in the cpuset,
1050  * update mems_allowed and rebind task's mempolicy and any vma
1051  * mempolicies and if the cpuset is marked 'memory_migrate',
1052  * migrate the tasks pages to the new memory.
1053  *
1054  * Call with cpuset_mutex held.  May take callback_mutex during call.
1055  * Will take tasklist_lock, scan tasklist for tasks in cpuset cs,
1056  * lock each such tasks mm->mmap_sem, scan its vma's and rebind
1057  * their mempolicies to the cpusets new mems_allowed.
1058  */
1059 static int update_nodemask(struct cpuset *cs, struct cpuset *trialcs,
1060                            const char *buf)
1061 {
1062         NODEMASK_ALLOC(nodemask_t, oldmem, GFP_KERNEL);
1063         int retval;
1064         struct ptr_heap heap;
1065
1066         if (!oldmem)
1067                 return -ENOMEM;
1068
1069         /*
1070          * top_cpuset.mems_allowed tracks node_stats[N_MEMORY];
1071          * it's read-only
1072          */
1073         if (cs == &top_cpuset) {
1074                 retval = -EACCES;
1075                 goto done;
1076         }
1077
1078         /*
1079          * An empty mems_allowed is ok iff there are no tasks in the cpuset.
1080          * Since nodelist_parse() fails on an empty mask, we special case
1081          * that parsing.  The validate_change() call ensures that cpusets
1082          * with tasks have memory.
1083          */
1084         if (!*buf) {
1085                 nodes_clear(trialcs->mems_allowed);
1086         } else {
1087                 retval = nodelist_parse(buf, trialcs->mems_allowed);
1088                 if (retval < 0)
1089                         goto done;
1090
1091                 if (!nodes_subset(trialcs->mems_allowed,
1092                                 node_states[N_MEMORY])) {
1093                         retval =  -EINVAL;
1094                         goto done;
1095                 }
1096         }
1097         *oldmem = cs->mems_allowed;
1098         if (nodes_equal(*oldmem, trialcs->mems_allowed)) {
1099                 retval = 0;             /* Too easy - nothing to do */
1100                 goto done;
1101         }
1102         retval = validate_change(cs, trialcs);
1103         if (retval < 0)
1104                 goto done;
1105
1106         retval = heap_init(&heap, PAGE_SIZE, GFP_KERNEL, NULL);
1107         if (retval < 0)
1108                 goto done;
1109
1110         mutex_lock(&callback_mutex);
1111         cs->mems_allowed = trialcs->mems_allowed;
1112         mutex_unlock(&callback_mutex);
1113
1114         update_tasks_nodemask(cs, oldmem, &heap);
1115
1116         heap_free(&heap);
1117 done:
1118         NODEMASK_FREE(oldmem);
1119         return retval;
1120 }
1121
1122 int current_cpuset_is_being_rebound(void)
1123 {
1124         return task_cs(current) == cpuset_being_rebound;
1125 }
1126
1127 static int update_relax_domain_level(struct cpuset *cs, s64 val)
1128 {
1129 #ifdef CONFIG_SMP
1130         if (val < -1 || val >= sched_domain_level_max)
1131                 return -EINVAL;
1132 #endif
1133
1134         if (val != cs->relax_domain_level) {
1135                 cs->relax_domain_level = val;
1136                 if (!cpumask_empty(cs->cpus_allowed) &&
1137                     is_sched_load_balance(cs))
1138                         rebuild_sched_domains_locked();
1139         }
1140
1141         return 0;
1142 }
1143
1144 /*
1145  * cpuset_change_flag - make a task's spread flags the same as its cpuset's
1146  * @tsk: task to be updated
1147  * @scan: struct cgroup_scanner containing the cgroup of the task
1148  *
1149  * Called by cgroup_scan_tasks() for each task in a cgroup.
1150  *
1151  * We don't need to re-check for the cgroup/cpuset membership, since we're
1152  * holding cpuset_mutex at this point.
1153  */
1154 static void cpuset_change_flag(struct task_struct *tsk,
1155                                 struct cgroup_scanner *scan)
1156 {
1157         cpuset_update_task_spread_flag(cgroup_cs(scan->cg), tsk);
1158 }
1159
1160 /*
1161  * update_tasks_flags - update the spread flags of tasks in the cpuset.
1162  * @cs: the cpuset in which each task's spread flags needs to be changed
1163  * @heap: if NULL, defer allocating heap memory to cgroup_scan_tasks()
1164  *
1165  * Called with cpuset_mutex held
1166  *
1167  * The cgroup_scan_tasks() function will scan all the tasks in a cgroup,
1168  * calling callback functions for each.
1169  *
1170  * No return value. It's guaranteed that cgroup_scan_tasks() always returns 0
1171  * if @heap != NULL.
1172  */
1173 static void update_tasks_flags(struct cpuset *cs, struct ptr_heap *heap)
1174 {
1175         struct cgroup_scanner scan;
1176
1177         scan.cg = cs->css.cgroup;
1178         scan.test_task = NULL;
1179         scan.process_task = cpuset_change_flag;
1180         scan.heap = heap;
1181         cgroup_scan_tasks(&scan);
1182 }
1183
1184 /*
1185  * update_flag - read a 0 or a 1 in a file and update associated flag
1186  * bit:         the bit to update (see cpuset_flagbits_t)
1187  * cs:          the cpuset to update
1188  * turning_on:  whether the flag is being set or cleared
1189  *
1190  * Call with cpuset_mutex held.
1191  */
1192
1193 static int update_flag(cpuset_flagbits_t bit, struct cpuset *cs,
1194                        int turning_on)
1195 {
1196         struct cpuset *trialcs;
1197         int balance_flag_changed;
1198         int spread_flag_changed;
1199         struct ptr_heap heap;
1200         int err;
1201
1202         trialcs = alloc_trial_cpuset(cs);
1203         if (!trialcs)
1204                 return -ENOMEM;
1205
1206         if (turning_on)
1207                 set_bit(bit, &trialcs->flags);
1208         else
1209                 clear_bit(bit, &trialcs->flags);
1210
1211         err = validate_change(cs, trialcs);
1212         if (err < 0)
1213                 goto out;
1214
1215         err = heap_init(&heap, PAGE_SIZE, GFP_KERNEL, NULL);
1216         if (err < 0)
1217                 goto out;
1218
1219         balance_flag_changed = (is_sched_load_balance(cs) !=
1220                                 is_sched_load_balance(trialcs));
1221
1222         spread_flag_changed = ((is_spread_slab(cs) != is_spread_slab(trialcs))
1223                         || (is_spread_page(cs) != is_spread_page(trialcs)));
1224
1225         mutex_lock(&callback_mutex);
1226         cs->flags = trialcs->flags;
1227         mutex_unlock(&callback_mutex);
1228
1229         if (!cpumask_empty(trialcs->cpus_allowed) && balance_flag_changed)
1230                 rebuild_sched_domains_locked();
1231
1232         if (spread_flag_changed)
1233                 update_tasks_flags(cs, &heap);
1234         heap_free(&heap);
1235 out:
1236         free_trial_cpuset(trialcs);
1237         return err;
1238 }
1239
1240 /*
1241  * Frequency meter - How fast is some event occurring?
1242  *
1243  * These routines manage a digitally filtered, constant time based,
1244  * event frequency meter.  There are four routines:
1245  *   fmeter_init() - initialize a frequency meter.
1246  *   fmeter_markevent() - called each time the event happens.
1247  *   fmeter_getrate() - returns the recent rate of such events.
1248  *   fmeter_update() - internal routine used to update fmeter.
1249  *
1250  * A common data structure is passed to each of these routines,
1251  * which is used to keep track of the state required to manage the
1252  * frequency meter and its digital filter.
1253  *
1254  * The filter works on the number of events marked per unit time.
1255  * The filter is single-pole low-pass recursive (IIR).  The time unit
1256  * is 1 second.  Arithmetic is done using 32-bit integers scaled to
1257  * simulate 3 decimal digits of precision (multiplied by 1000).
1258  *
1259  * With an FM_COEF of 933, and a time base of 1 second, the filter
1260  * has a half-life of 10 seconds, meaning that if the events quit
1261  * happening, then the rate returned from the fmeter_getrate()
1262  * will be cut in half each 10 seconds, until it converges to zero.
1263  *
1264  * It is not worth doing a real infinitely recursive filter.  If more
1265  * than FM_MAXTICKS ticks have elapsed since the last filter event,
1266  * just compute FM_MAXTICKS ticks worth, by which point the level
1267  * will be stable.
1268  *
1269  * Limit the count of unprocessed events to FM_MAXCNT, so as to avoid
1270  * arithmetic overflow in the fmeter_update() routine.
1271  *
1272  * Given the simple 32 bit integer arithmetic used, this meter works
1273  * best for reporting rates between one per millisecond (msec) and
1274  * one per 32 (approx) seconds.  At constant rates faster than one
1275  * per msec it maxes out at values just under 1,000,000.  At constant
1276  * rates between one per msec, and one per second it will stabilize
1277  * to a value N*1000, where N is the rate of events per second.
1278  * At constant rates between one per second and one per 32 seconds,
1279  * it will be choppy, moving up on the seconds that have an event,
1280  * and then decaying until the next event.  At rates slower than
1281  * about one in 32 seconds, it decays all the way back to zero between
1282  * each event.
1283  */
1284
1285 #define FM_COEF 933             /* coefficient for half-life of 10 secs */
1286 #define FM_MAXTICKS ((time_t)99) /* useless computing more ticks than this */
1287 #define FM_MAXCNT 1000000       /* limit cnt to avoid overflow */
1288 #define FM_SCALE 1000           /* faux fixed point scale */
1289
1290 /* Initialize a frequency meter */
1291 static void fmeter_init(struct fmeter *fmp)
1292 {
1293         fmp->cnt = 0;
1294         fmp->val = 0;
1295         fmp->time = 0;
1296         spin_lock_init(&fmp->lock);
1297 }
1298
1299 /* Internal meter update - process cnt events and update value */
1300 static void fmeter_update(struct fmeter *fmp)
1301 {
1302         time_t now = get_seconds();
1303         time_t ticks = now - fmp->time;
1304
1305         if (ticks == 0)
1306                 return;
1307
1308         ticks = min(FM_MAXTICKS, ticks);
1309         while (ticks-- > 0)
1310                 fmp->val = (FM_COEF * fmp->val) / FM_SCALE;
1311         fmp->time = now;
1312
1313         fmp->val += ((FM_SCALE - FM_COEF) * fmp->cnt) / FM_SCALE;
1314         fmp->cnt = 0;
1315 }
1316
1317 /* Process any previous ticks, then bump cnt by one (times scale). */
1318 static void fmeter_markevent(struct fmeter *fmp)
1319 {
1320         spin_lock(&fmp->lock);
1321         fmeter_update(fmp);
1322         fmp->cnt = min(FM_MAXCNT, fmp->cnt + FM_SCALE);
1323         spin_unlock(&fmp->lock);
1324 }
1325
1326 /* Process any previous ticks, then return current value. */
1327 static int fmeter_getrate(struct fmeter *fmp)
1328 {
1329         int val;
1330
1331         spin_lock(&fmp->lock);
1332         fmeter_update(fmp);
1333         val = fmp->val;
1334         spin_unlock(&fmp->lock);
1335         return val;
1336 }
1337
1338 /* Called by cgroups to determine if a cpuset is usable; cpuset_mutex held */
1339 static int cpuset_can_attach(struct cgroup *cgrp, struct cgroup_taskset *tset)
1340 {
1341         struct cpuset *cs = cgroup_cs(cgrp);
1342         struct task_struct *task;
1343         int ret;
1344
1345         mutex_lock(&cpuset_mutex);
1346
1347         ret = -ENOSPC;
1348         if (cpumask_empty(cs->cpus_allowed) || nodes_empty(cs->mems_allowed))
1349                 goto out_unlock;
1350
1351         cgroup_taskset_for_each(task, cgrp, tset) {
1352                 /*
1353                  * Kthreads which disallow setaffinity shouldn't be moved
1354                  * to a new cpuset; we don't want to change their cpu
1355                  * affinity and isolating such threads by their set of
1356                  * allowed nodes is unnecessary.  Thus, cpusets are not
1357                  * applicable for such threads.  This prevents checking for
1358                  * success of set_cpus_allowed_ptr() on all attached tasks
1359                  * before cpus_allowed may be changed.
1360                  */
1361                 ret = -EINVAL;
1362                 if (task->flags & PF_NO_SETAFFINITY)
1363                         goto out_unlock;
1364                 ret = security_task_setscheduler(task);
1365                 if (ret)
1366                         goto out_unlock;
1367         }
1368
1369         /*
1370          * Mark attach is in progress.  This makes validate_change() fail
1371          * changes which zero cpus/mems_allowed.
1372          */
1373         cs->attach_in_progress++;
1374         ret = 0;
1375 out_unlock:
1376         mutex_unlock(&cpuset_mutex);
1377         return ret;
1378 }
1379
1380 static void cpuset_cancel_attach(struct cgroup *cgrp,
1381                                  struct cgroup_taskset *tset)
1382 {
1383         mutex_lock(&cpuset_mutex);
1384         cgroup_cs(cgrp)->attach_in_progress--;
1385         mutex_unlock(&cpuset_mutex);
1386 }
1387
1388 /*
1389  * Protected by cpuset_mutex.  cpus_attach is used only by cpuset_attach()
1390  * but we can't allocate it dynamically there.  Define it global and
1391  * allocate from cpuset_init().
1392  */
1393 static cpumask_var_t cpus_attach;
1394
1395 static void cpuset_attach(struct cgroup *cgrp, struct cgroup_taskset *tset)
1396 {
1397         /* static buf protected by cpuset_mutex */
1398         static nodemask_t cpuset_attach_nodemask_to;
1399         struct mm_struct *mm;
1400         struct task_struct *task;
1401         struct task_struct *leader = cgroup_taskset_first(tset);
1402         struct cgroup *oldcgrp = cgroup_taskset_cur_cgroup(tset);
1403         struct cpuset *cs = cgroup_cs(cgrp);
1404         struct cpuset *oldcs = cgroup_cs(oldcgrp);
1405
1406         mutex_lock(&cpuset_mutex);
1407
1408         /* prepare for attach */
1409         if (cs == &top_cpuset)
1410                 cpumask_copy(cpus_attach, cpu_possible_mask);
1411         else
1412                 guarantee_online_cpus(cs, cpus_attach);
1413
1414         guarantee_online_mems(cs, &cpuset_attach_nodemask_to);
1415
1416         cgroup_taskset_for_each(task, cgrp, tset) {
1417                 /*
1418                  * can_attach beforehand should guarantee that this doesn't
1419                  * fail.  TODO: have a better way to handle failure here
1420                  */
1421                 WARN_ON_ONCE(set_cpus_allowed_ptr(task, cpus_attach));
1422
1423                 cpuset_change_task_nodemask(task, &cpuset_attach_nodemask_to);
1424                 cpuset_update_task_spread_flag(cs, task);
1425         }
1426
1427         /*
1428          * Change mm, possibly for multiple threads in a threadgroup. This is
1429          * expensive and may sleep.
1430          */
1431         cpuset_attach_nodemask_to = cs->mems_allowed;
1432         mm = get_task_mm(leader);
1433         if (mm) {
1434                 mpol_rebind_mm(mm, &cpuset_attach_nodemask_to);
1435                 if (is_memory_migrate(cs))
1436                         cpuset_migrate_mm(mm, &oldcs->mems_allowed,
1437                                           &cpuset_attach_nodemask_to);
1438                 mmput(mm);
1439         }
1440
1441         cs->attach_in_progress--;
1442         if (!cs->attach_in_progress)
1443                 wake_up(&cpuset_attach_wq);
1444
1445         mutex_unlock(&cpuset_mutex);
1446 }
1447
1448 /* The various types of files and directories in a cpuset file system */
1449
1450 typedef enum {
1451         FILE_MEMORY_MIGRATE,
1452         FILE_CPULIST,
1453         FILE_MEMLIST,
1454         FILE_CPU_EXCLUSIVE,
1455         FILE_MEM_EXCLUSIVE,
1456         FILE_MEM_HARDWALL,
1457         FILE_SCHED_LOAD_BALANCE,
1458         FILE_SCHED_RELAX_DOMAIN_LEVEL,
1459         FILE_MEMORY_PRESSURE_ENABLED,
1460         FILE_MEMORY_PRESSURE,
1461         FILE_SPREAD_PAGE,
1462         FILE_SPREAD_SLAB,
1463 } cpuset_filetype_t;
1464
1465 static int cpuset_write_u64(struct cgroup *cgrp, struct cftype *cft, u64 val)
1466 {
1467         struct cpuset *cs = cgroup_cs(cgrp);
1468         cpuset_filetype_t type = cft->private;
1469         int retval = -ENODEV;
1470
1471         mutex_lock(&cpuset_mutex);
1472         if (!is_cpuset_online(cs))
1473                 goto out_unlock;
1474
1475         switch (type) {
1476         case FILE_CPU_EXCLUSIVE:
1477                 retval = update_flag(CS_CPU_EXCLUSIVE, cs, val);
1478                 break;
1479         case FILE_MEM_EXCLUSIVE:
1480                 retval = update_flag(CS_MEM_EXCLUSIVE, cs, val);
1481                 break;
1482         case FILE_MEM_HARDWALL:
1483                 retval = update_flag(CS_MEM_HARDWALL, cs, val);
1484                 break;
1485         case FILE_SCHED_LOAD_BALANCE:
1486                 retval = update_flag(CS_SCHED_LOAD_BALANCE, cs, val);
1487                 break;
1488         case FILE_MEMORY_MIGRATE:
1489                 retval = update_flag(CS_MEMORY_MIGRATE, cs, val);
1490                 break;
1491         case FILE_MEMORY_PRESSURE_ENABLED:
1492                 cpuset_memory_pressure_enabled = !!val;
1493                 break;
1494         case FILE_MEMORY_PRESSURE:
1495                 retval = -EACCES;
1496                 break;
1497         case FILE_SPREAD_PAGE:
1498                 retval = update_flag(CS_SPREAD_PAGE, cs, val);
1499                 break;
1500         case FILE_SPREAD_SLAB:
1501                 retval = update_flag(CS_SPREAD_SLAB, cs, val);
1502                 break;
1503         default:
1504                 retval = -EINVAL;
1505                 break;
1506         }
1507 out_unlock:
1508         mutex_unlock(&cpuset_mutex);
1509         return retval;
1510 }
1511
1512 static int cpuset_write_s64(struct cgroup *cgrp, struct cftype *cft, s64 val)
1513 {
1514         struct cpuset *cs = cgroup_cs(cgrp);
1515         cpuset_filetype_t type = cft->private;
1516         int retval = -ENODEV;
1517
1518         mutex_lock(&cpuset_mutex);
1519         if (!is_cpuset_online(cs))
1520                 goto out_unlock;
1521
1522         switch (type) {
1523         case FILE_SCHED_RELAX_DOMAIN_LEVEL:
1524                 retval = update_relax_domain_level(cs, val);
1525                 break;
1526         default:
1527                 retval = -EINVAL;
1528                 break;
1529         }
1530 out_unlock:
1531         mutex_unlock(&cpuset_mutex);
1532         return retval;
1533 }
1534
1535 /*
1536  * Common handling for a write to a "cpus" or "mems" file.
1537  */
1538 static int cpuset_write_resmask(struct cgroup *cgrp, struct cftype *cft,
1539                                 const char *buf)
1540 {
1541         struct cpuset *cs = cgroup_cs(cgrp);
1542         struct cpuset *trialcs;
1543         int retval = -ENODEV;
1544
1545         /*
1546          * CPU or memory hotunplug may leave @cs w/o any execution
1547          * resources, in which case the hotplug code asynchronously updates
1548          * configuration and transfers all tasks to the nearest ancestor
1549          * which can execute.
1550          *
1551          * As writes to "cpus" or "mems" may restore @cs's execution
1552          * resources, wait for the previously scheduled operations before
1553          * proceeding, so that we don't end up keep removing tasks added
1554          * after execution capability is restored.
1555          */
1556         flush_work(&cpuset_hotplug_work);
1557         flush_workqueue(cpuset_propagate_hotplug_wq);
1558
1559         mutex_lock(&cpuset_mutex);
1560         if (!is_cpuset_online(cs))
1561                 goto out_unlock;
1562
1563         trialcs = alloc_trial_cpuset(cs);
1564         if (!trialcs) {
1565                 retval = -ENOMEM;
1566                 goto out_unlock;
1567         }
1568
1569         switch (cft->private) {
1570         case FILE_CPULIST:
1571                 retval = update_cpumask(cs, trialcs, buf);
1572                 break;
1573         case FILE_MEMLIST:
1574                 retval = update_nodemask(cs, trialcs, buf);
1575                 break;
1576         default:
1577                 retval = -EINVAL;
1578                 break;
1579         }
1580
1581         free_trial_cpuset(trialcs);
1582 out_unlock:
1583         mutex_unlock(&cpuset_mutex);
1584         return retval;
1585 }
1586
1587 /*
1588  * These ascii lists should be read in a single call, by using a user
1589  * buffer large enough to hold the entire map.  If read in smaller
1590  * chunks, there is no guarantee of atomicity.  Since the display format
1591  * used, list of ranges of sequential numbers, is variable length,
1592  * and since these maps can change value dynamically, one could read
1593  * gibberish by doing partial reads while a list was changing.
1594  * A single large read to a buffer that crosses a page boundary is
1595  * ok, because the result being copied to user land is not recomputed
1596  * across a page fault.
1597  */
1598
1599 static size_t cpuset_sprintf_cpulist(char *page, struct cpuset *cs)
1600 {
1601         size_t count;
1602
1603         mutex_lock(&callback_mutex);
1604         count = cpulist_scnprintf(page, PAGE_SIZE, cs->cpus_allowed);
1605         mutex_unlock(&callback_mutex);
1606
1607         return count;
1608 }
1609
1610 static size_t cpuset_sprintf_memlist(char *page, struct cpuset *cs)
1611 {
1612         size_t count;
1613
1614         mutex_lock(&callback_mutex);
1615         count = nodelist_scnprintf(page, PAGE_SIZE, cs->mems_allowed);
1616         mutex_unlock(&callback_mutex);
1617
1618         return count;
1619 }
1620
1621 static ssize_t cpuset_common_file_read(struct cgroup *cont,
1622                                        struct cftype *cft,
1623                                        struct file *file,
1624                                        char __user *buf,
1625                                        size_t nbytes, loff_t *ppos)
1626 {
1627         struct cpuset *cs = cgroup_cs(cont);
1628         cpuset_filetype_t type = cft->private;
1629         char *page;
1630         ssize_t retval = 0;
1631         char *s;
1632
1633         if (!(page = (char *)__get_free_page(GFP_TEMPORARY)))
1634                 return -ENOMEM;
1635
1636         s = page;
1637
1638         switch (type) {
1639         case FILE_CPULIST:
1640                 s += cpuset_sprintf_cpulist(s, cs);
1641                 break;
1642         case FILE_MEMLIST:
1643                 s += cpuset_sprintf_memlist(s, cs);
1644                 break;
1645         default:
1646                 retval = -EINVAL;
1647                 goto out;
1648         }
1649         *s++ = '\n';
1650
1651         retval = simple_read_from_buffer(buf, nbytes, ppos, page, s - page);
1652 out:
1653         free_page((unsigned long)page);
1654         return retval;
1655 }
1656
1657 static u64 cpuset_read_u64(struct cgroup *cont, struct cftype *cft)
1658 {
1659         struct cpuset *cs = cgroup_cs(cont);
1660         cpuset_filetype_t type = cft->private;
1661         switch (type) {
1662         case FILE_CPU_EXCLUSIVE:
1663                 return is_cpu_exclusive(cs);
1664         case FILE_MEM_EXCLUSIVE:
1665                 return is_mem_exclusive(cs);
1666         case FILE_MEM_HARDWALL:
1667                 return is_mem_hardwall(cs);
1668         case FILE_SCHED_LOAD_BALANCE:
1669                 return is_sched_load_balance(cs);
1670         case FILE_MEMORY_MIGRATE:
1671                 return is_memory_migrate(cs);
1672         case FILE_MEMORY_PRESSURE_ENABLED:
1673                 return cpuset_memory_pressure_enabled;
1674         case FILE_MEMORY_PRESSURE:
1675                 return fmeter_getrate(&cs->fmeter);
1676         case FILE_SPREAD_PAGE:
1677                 return is_spread_page(cs);
1678         case FILE_SPREAD_SLAB:
1679                 return is_spread_slab(cs);
1680         default:
1681                 BUG();
1682         }
1683
1684         /* Unreachable but makes gcc happy */
1685         return 0;
1686 }
1687
1688 static s64 cpuset_read_s64(struct cgroup *cont, struct cftype *cft)
1689 {
1690         struct cpuset *cs = cgroup_cs(cont);
1691         cpuset_filetype_t type = cft->private;
1692         switch (type) {
1693         case FILE_SCHED_RELAX_DOMAIN_LEVEL:
1694                 return cs->relax_domain_level;
1695         default:
1696                 BUG();
1697         }
1698
1699         /* Unrechable but makes gcc happy */
1700         return 0;
1701 }
1702
1703
1704 /*
1705  * for the common functions, 'private' gives the type of file
1706  */
1707
1708 static struct cftype files[] = {
1709         {
1710                 .name = "cpus",
1711                 .read = cpuset_common_file_read,
1712                 .write_string = cpuset_write_resmask,
1713                 .max_write_len = (100U + 6 * NR_CPUS),
1714                 .private = FILE_CPULIST,
1715         },
1716
1717         {
1718                 .name = "mems",
1719                 .read = cpuset_common_file_read,
1720                 .write_string = cpuset_write_resmask,
1721                 .max_write_len = (100U + 6 * MAX_NUMNODES),
1722                 .private = FILE_MEMLIST,
1723         },
1724
1725         {
1726                 .name = "cpu_exclusive",
1727                 .read_u64 = cpuset_read_u64,
1728                 .write_u64 = cpuset_write_u64,
1729                 .private = FILE_CPU_EXCLUSIVE,
1730         },
1731
1732         {
1733                 .name = "mem_exclusive",
1734                 .read_u64 = cpuset_read_u64,
1735                 .write_u64 = cpuset_write_u64,
1736                 .private = FILE_MEM_EXCLUSIVE,
1737         },
1738
1739         {
1740                 .name = "mem_hardwall",
1741                 .read_u64 = cpuset_read_u64,
1742                 .write_u64 = cpuset_write_u64,
1743                 .private = FILE_MEM_HARDWALL,
1744         },
1745
1746         {
1747                 .name = "sched_load_balance",
1748                 .read_u64 = cpuset_read_u64,
1749                 .write_u64 = cpuset_write_u64,
1750                 .private = FILE_SCHED_LOAD_BALANCE,
1751         },
1752
1753         {
1754                 .name = "sched_relax_domain_level",
1755                 .read_s64 = cpuset_read_s64,
1756                 .write_s64 = cpuset_write_s64,
1757                 .private = FILE_SCHED_RELAX_DOMAIN_LEVEL,
1758         },
1759
1760         {
1761                 .name = "memory_migrate",
1762                 .read_u64 = cpuset_read_u64,
1763                 .write_u64 = cpuset_write_u64,
1764                 .private = FILE_MEMORY_MIGRATE,
1765         },
1766
1767         {
1768                 .name = "memory_pressure",
1769                 .read_u64 = cpuset_read_u64,
1770                 .write_u64 = cpuset_write_u64,
1771                 .private = FILE_MEMORY_PRESSURE,
1772                 .mode = S_IRUGO,
1773         },
1774
1775         {
1776                 .name = "memory_spread_page",
1777                 .read_u64 = cpuset_read_u64,
1778                 .write_u64 = cpuset_write_u64,
1779                 .private = FILE_SPREAD_PAGE,
1780         },
1781
1782         {
1783                 .name = "memory_spread_slab",
1784                 .read_u64 = cpuset_read_u64,
1785                 .write_u64 = cpuset_write_u64,
1786                 .private = FILE_SPREAD_SLAB,
1787         },
1788
1789         {
1790                 .name = "memory_pressure_enabled",
1791                 .flags = CFTYPE_ONLY_ON_ROOT,
1792                 .read_u64 = cpuset_read_u64,
1793                 .write_u64 = cpuset_write_u64,
1794                 .private = FILE_MEMORY_PRESSURE_ENABLED,
1795         },
1796
1797         { }     /* terminate */
1798 };
1799
1800 /*
1801  *      cpuset_css_alloc - allocate a cpuset css
1802  *      cont:   control group that the new cpuset will be part of
1803  */
1804
1805 static struct cgroup_subsys_state *cpuset_css_alloc(struct cgroup *cont)
1806 {
1807         struct cpuset *cs;
1808
1809         if (!cont->parent)
1810                 return &top_cpuset.css;
1811
1812         cs = kzalloc(sizeof(*cs), GFP_KERNEL);
1813         if (!cs)
1814                 return ERR_PTR(-ENOMEM);
1815         if (!alloc_cpumask_var(&cs->cpus_allowed, GFP_KERNEL)) {
1816                 kfree(cs);
1817                 return ERR_PTR(-ENOMEM);
1818         }
1819
1820         set_bit(CS_SCHED_LOAD_BALANCE, &cs->flags);
1821         cpumask_clear(cs->cpus_allowed);
1822         nodes_clear(cs->mems_allowed);
1823         fmeter_init(&cs->fmeter);
1824         INIT_WORK(&cs->hotplug_work, cpuset_propagate_hotplug_workfn);
1825         cs->relax_domain_level = -1;
1826
1827         return &cs->css;
1828 }
1829
1830 static int cpuset_css_online(struct cgroup *cgrp)
1831 {
1832         struct cpuset *cs = cgroup_cs(cgrp);
1833         struct cpuset *parent = parent_cs(cs);
1834         struct cpuset *tmp_cs;
1835         struct cgroup *pos_cg;
1836
1837         if (!parent)
1838                 return 0;
1839
1840         mutex_lock(&cpuset_mutex);
1841
1842         set_bit(CS_ONLINE, &cs->flags);
1843         if (is_spread_page(parent))
1844                 set_bit(CS_SPREAD_PAGE, &cs->flags);
1845         if (is_spread_slab(parent))
1846                 set_bit(CS_SPREAD_SLAB, &cs->flags);
1847
1848         number_of_cpusets++;
1849
1850         if (!test_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags))
1851                 goto out_unlock;
1852
1853         /*
1854          * Clone @parent's configuration if CGRP_CPUSET_CLONE_CHILDREN is
1855          * set.  This flag handling is implemented in cgroup core for
1856          * histrical reasons - the flag may be specified during mount.
1857          *
1858          * Currently, if any sibling cpusets have exclusive cpus or mem, we
1859          * refuse to clone the configuration - thereby refusing the task to
1860          * be entered, and as a result refusing the sys_unshare() or
1861          * clone() which initiated it.  If this becomes a problem for some
1862          * users who wish to allow that scenario, then this could be
1863          * changed to grant parent->cpus_allowed-sibling_cpus_exclusive
1864          * (and likewise for mems) to the new cgroup.
1865          */
1866         rcu_read_lock();
1867         cpuset_for_each_child(tmp_cs, pos_cg, parent) {
1868                 if (is_mem_exclusive(tmp_cs) || is_cpu_exclusive(tmp_cs)) {
1869                         rcu_read_unlock();
1870                         goto out_unlock;
1871                 }
1872         }
1873         rcu_read_unlock();
1874
1875         mutex_lock(&callback_mutex);
1876         cs->mems_allowed = parent->mems_allowed;
1877         cpumask_copy(cs->cpus_allowed, parent->cpus_allowed);
1878         mutex_unlock(&callback_mutex);
1879 out_unlock:
1880         mutex_unlock(&cpuset_mutex);
1881         return 0;
1882 }
1883
1884 static void cpuset_css_offline(struct cgroup *cgrp)
1885 {
1886         struct cpuset *cs = cgroup_cs(cgrp);
1887
1888         mutex_lock(&cpuset_mutex);
1889
1890         if (is_sched_load_balance(cs))
1891                 update_flag(CS_SCHED_LOAD_BALANCE, cs, 0);
1892
1893         number_of_cpusets--;
1894         clear_bit(CS_ONLINE, &cs->flags);
1895
1896         mutex_unlock(&cpuset_mutex);
1897 }
1898
1899 /*
1900  * If the cpuset being removed has its flag 'sched_load_balance'
1901  * enabled, then simulate turning sched_load_balance off, which
1902  * will call rebuild_sched_domains_locked().
1903  */
1904
1905 static void cpuset_css_free(struct cgroup *cont)
1906 {
1907         struct cpuset *cs = cgroup_cs(cont);
1908
1909         free_cpumask_var(cs->cpus_allowed);
1910         kfree(cs);
1911 }
1912
1913 struct cgroup_subsys cpuset_subsys = {
1914         .name = "cpuset",
1915         .css_alloc = cpuset_css_alloc,
1916         .css_online = cpuset_css_online,
1917         .css_offline = cpuset_css_offline,
1918         .css_free = cpuset_css_free,
1919         .can_attach = cpuset_can_attach,
1920         .cancel_attach = cpuset_cancel_attach,
1921         .attach = cpuset_attach,
1922         .subsys_id = cpuset_subsys_id,
1923         .base_cftypes = files,
1924         .early_init = 1,
1925 };
1926
1927 /**
1928  * cpuset_init - initialize cpusets at system boot
1929  *
1930  * Description: Initialize top_cpuset and the cpuset internal file system,
1931  **/
1932
1933 int __init cpuset_init(void)
1934 {
1935         int err = 0;
1936
1937         if (!alloc_cpumask_var(&top_cpuset.cpus_allowed, GFP_KERNEL))
1938                 BUG();
1939
1940         cpumask_setall(top_cpuset.cpus_allowed);
1941         nodes_setall(top_cpuset.mems_allowed);
1942
1943         fmeter_init(&top_cpuset.fmeter);
1944         set_bit(CS_SCHED_LOAD_BALANCE, &top_cpuset.flags);
1945         top_cpuset.relax_domain_level = -1;
1946
1947         err = register_filesystem(&cpuset_fs_type);
1948         if (err < 0)
1949                 return err;
1950
1951         if (!alloc_cpumask_var(&cpus_attach, GFP_KERNEL))
1952                 BUG();
1953
1954         number_of_cpusets = 1;
1955         return 0;
1956 }
1957
1958 /*
1959  * If CPU and/or memory hotplug handlers, below, unplug any CPUs
1960  * or memory nodes, we need to walk over the cpuset hierarchy,
1961  * removing that CPU or node from all cpusets.  If this removes the
1962  * last CPU or node from a cpuset, then move the tasks in the empty
1963  * cpuset to its next-highest non-empty parent.
1964  */
1965 static void remove_tasks_in_empty_cpuset(struct cpuset *cs)
1966 {
1967         struct cpuset *parent;
1968
1969         /*
1970          * Find its next-highest non-empty parent, (top cpuset
1971          * has online cpus, so can't be empty).
1972          */
1973         parent = parent_cs(cs);
1974         while (cpumask_empty(parent->cpus_allowed) ||
1975                         nodes_empty(parent->mems_allowed))
1976                 parent = parent_cs(parent);
1977
1978         if (cgroup_transfer_tasks(parent->css.cgroup, cs->css.cgroup)) {
1979                 rcu_read_lock();
1980                 printk(KERN_ERR "cpuset: failed to transfer tasks out of empty cpuset %s\n",
1981                        cgroup_name(cs->css.cgroup));
1982                 rcu_read_unlock();
1983         }
1984 }
1985
1986 /**
1987  * cpuset_propagate_hotplug_workfn - propagate CPU/memory hotplug to a cpuset
1988  * @cs: cpuset in interest
1989  *
1990  * Compare @cs's cpu and mem masks against top_cpuset and if some have gone
1991  * offline, update @cs accordingly.  If @cs ends up with no CPU or memory,
1992  * all its tasks are moved to the nearest ancestor with both resources.
1993  */
1994 static void cpuset_propagate_hotplug_workfn(struct work_struct *work)
1995 {
1996         static cpumask_t off_cpus;
1997         static nodemask_t off_mems, tmp_mems;
1998         struct cpuset *cs = container_of(work, struct cpuset, hotplug_work);
1999         bool is_empty;
2000
2001 retry:
2002         wait_event(cpuset_attach_wq, cs->attach_in_progress == 0);
2003
2004         mutex_lock(&cpuset_mutex);
2005
2006         /*
2007          * We have raced with task attaching. We wait until attaching
2008          * is finished, so we won't attach a task to an empty cpuset.
2009          */
2010         if (cs->attach_in_progress) {
2011                 mutex_unlock(&cpuset_mutex);
2012                 goto retry;
2013         }
2014
2015         cpumask_andnot(&off_cpus, cs->cpus_allowed, top_cpuset.cpus_allowed);
2016         nodes_andnot(off_mems, cs->mems_allowed, top_cpuset.mems_allowed);
2017
2018         /* remove offline cpus from @cs */
2019         if (!cpumask_empty(&off_cpus)) {
2020                 mutex_lock(&callback_mutex);
2021                 cpumask_andnot(cs->cpus_allowed, cs->cpus_allowed, &off_cpus);
2022                 mutex_unlock(&callback_mutex);
2023                 update_tasks_cpumask(cs, NULL);
2024         }
2025
2026         /* remove offline mems from @cs */
2027         if (!nodes_empty(off_mems)) {
2028                 tmp_mems = cs->mems_allowed;
2029                 mutex_lock(&callback_mutex);
2030                 nodes_andnot(cs->mems_allowed, cs->mems_allowed, off_mems);
2031                 mutex_unlock(&callback_mutex);
2032                 update_tasks_nodemask(cs, &tmp_mems, NULL);
2033         }
2034
2035         is_empty = cpumask_empty(cs->cpus_allowed) ||
2036                 nodes_empty(cs->mems_allowed);
2037
2038         mutex_unlock(&cpuset_mutex);
2039
2040         /*
2041          * If @cs became empty, move tasks to the nearest ancestor with
2042          * execution resources.  This is full cgroup operation which will
2043          * also call back into cpuset.  Should be done outside any lock.
2044          */
2045         if (is_empty)
2046                 remove_tasks_in_empty_cpuset(cs);
2047
2048         /* the following may free @cs, should be the last operation */
2049         css_put(&cs->css);
2050 }
2051
2052 /**
2053  * schedule_cpuset_propagate_hotplug - schedule hotplug propagation to a cpuset
2054  * @cs: cpuset of interest
2055  *
2056  * Schedule cpuset_propagate_hotplug_workfn() which will update CPU and
2057  * memory masks according to top_cpuset.
2058  */
2059 static void schedule_cpuset_propagate_hotplug(struct cpuset *cs)
2060 {
2061         /*
2062          * Pin @cs.  The refcnt will be released when the work item
2063          * finishes executing.
2064          */
2065         if (!css_tryget(&cs->css))
2066                 return;
2067
2068         /*
2069          * Queue @cs->hotplug_work.  If already pending, lose the css ref.
2070          * cpuset_propagate_hotplug_wq is ordered and propagation will
2071          * happen in the order this function is called.
2072          */
2073         if (!queue_work(cpuset_propagate_hotplug_wq, &cs->hotplug_work))
2074                 css_put(&cs->css);
2075 }
2076
2077 /**
2078  * cpuset_hotplug_workfn - handle CPU/memory hotunplug for a cpuset
2079  *
2080  * This function is called after either CPU or memory configuration has
2081  * changed and updates cpuset accordingly.  The top_cpuset is always
2082  * synchronized to cpu_active_mask and N_MEMORY, which is necessary in
2083  * order to make cpusets transparent (of no affect) on systems that are
2084  * actively using CPU hotplug but making no active use of cpusets.
2085  *
2086  * Non-root cpusets are only affected by offlining.  If any CPUs or memory
2087  * nodes have been taken down, cpuset_propagate_hotplug() is invoked on all
2088  * descendants.
2089  *
2090  * Note that CPU offlining during suspend is ignored.  We don't modify
2091  * cpusets across suspend/resume cycles at all.
2092  */
2093 static void cpuset_hotplug_workfn(struct work_struct *work)
2094 {
2095         static cpumask_t new_cpus, tmp_cpus;
2096         static nodemask_t new_mems, tmp_mems;
2097         bool cpus_updated, mems_updated;
2098         bool cpus_offlined, mems_offlined;
2099
2100         mutex_lock(&cpuset_mutex);
2101
2102         /* fetch the available cpus/mems and find out which changed how */
2103         cpumask_copy(&new_cpus, cpu_active_mask);
2104         new_mems = node_states[N_MEMORY];
2105
2106         cpus_updated = !cpumask_equal(top_cpuset.cpus_allowed, &new_cpus);
2107         cpus_offlined = cpumask_andnot(&tmp_cpus, top_cpuset.cpus_allowed,
2108                                        &new_cpus);
2109
2110         mems_updated = !nodes_equal(top_cpuset.mems_allowed, new_mems);
2111         nodes_andnot(tmp_mems, top_cpuset.mems_allowed, new_mems);
2112         mems_offlined = !nodes_empty(tmp_mems);
2113
2114         /* synchronize cpus_allowed to cpu_active_mask */
2115         if (cpus_updated) {
2116                 mutex_lock(&callback_mutex);
2117                 cpumask_copy(top_cpuset.cpus_allowed, &new_cpus);
2118                 mutex_unlock(&callback_mutex);
2119                 /* we don't mess with cpumasks of tasks in top_cpuset */
2120         }
2121
2122         /* synchronize mems_allowed to N_MEMORY */
2123         if (mems_updated) {
2124                 tmp_mems = top_cpuset.mems_allowed;
2125                 mutex_lock(&callback_mutex);
2126                 top_cpuset.mems_allowed = new_mems;
2127                 mutex_unlock(&callback_mutex);
2128                 update_tasks_nodemask(&top_cpuset, &tmp_mems, NULL);
2129         }
2130
2131         /* if cpus or mems went down, we need to propagate to descendants */
2132         if (cpus_offlined || mems_offlined) {
2133                 struct cpuset *cs;
2134                 struct cgroup *pos_cgrp;
2135
2136                 rcu_read_lock();
2137                 cpuset_for_each_descendant_pre(cs, pos_cgrp, &top_cpuset)
2138                         schedule_cpuset_propagate_hotplug(cs);
2139                 rcu_read_unlock();
2140         }
2141
2142         mutex_unlock(&cpuset_mutex);
2143
2144         /* wait for propagations to finish */
2145         flush_workqueue(cpuset_propagate_hotplug_wq);
2146
2147         /* rebuild sched domains if cpus_allowed has changed */
2148         if (cpus_updated)
2149                 rebuild_sched_domains();
2150 }
2151
2152 void cpuset_update_active_cpus(bool cpu_online)
2153 {
2154         /*
2155          * We're inside cpu hotplug critical region which usually nests
2156          * inside cgroup synchronization.  Bounce actual hotplug processing
2157          * to a work item to avoid reverse locking order.
2158          *
2159          * We still need to do partition_sched_domains() synchronously;
2160          * otherwise, the scheduler will get confused and put tasks to the
2161          * dead CPU.  Fall back to the default single domain.
2162          * cpuset_hotplug_workfn() will rebuild it as necessary.
2163          */
2164         partition_sched_domains(1, NULL, NULL);
2165         schedule_work(&cpuset_hotplug_work);
2166 }
2167
2168 /*
2169  * Keep top_cpuset.mems_allowed tracking node_states[N_MEMORY].
2170  * Call this routine anytime after node_states[N_MEMORY] changes.
2171  * See cpuset_update_active_cpus() for CPU hotplug handling.
2172  */
2173 static int cpuset_track_online_nodes(struct notifier_block *self,
2174                                 unsigned long action, void *arg)
2175 {
2176         schedule_work(&cpuset_hotplug_work);
2177         return NOTIFY_OK;
2178 }
2179
2180 static struct notifier_block cpuset_track_online_nodes_nb = {
2181         .notifier_call = cpuset_track_online_nodes,
2182         .priority = 10,         /* ??! */
2183 };
2184
2185 /**
2186  * cpuset_init_smp - initialize cpus_allowed
2187  *
2188  * Description: Finish top cpuset after cpu, node maps are initialized
2189  */
2190 void __init cpuset_init_smp(void)
2191 {
2192         cpumask_copy(top_cpuset.cpus_allowed, cpu_active_mask);
2193         top_cpuset.mems_allowed = node_states[N_MEMORY];
2194
2195         register_hotmemory_notifier(&cpuset_track_online_nodes_nb);
2196
2197         cpuset_propagate_hotplug_wq =
2198                 alloc_ordered_workqueue("cpuset_hotplug", 0);
2199         BUG_ON(!cpuset_propagate_hotplug_wq);
2200 }
2201
2202 /**
2203  * cpuset_cpus_allowed - return cpus_allowed mask from a tasks cpuset.
2204  * @tsk: pointer to task_struct from which to obtain cpuset->cpus_allowed.
2205  * @pmask: pointer to struct cpumask variable to receive cpus_allowed set.
2206  *
2207  * Description: Returns the cpumask_var_t cpus_allowed of the cpuset
2208  * attached to the specified @tsk.  Guaranteed to return some non-empty
2209  * subset of cpu_online_mask, even if this means going outside the
2210  * tasks cpuset.
2211  **/
2212
2213 void cpuset_cpus_allowed(struct task_struct *tsk, struct cpumask *pmask)
2214 {
2215         mutex_lock(&callback_mutex);
2216         task_lock(tsk);
2217         guarantee_online_cpus(task_cs(tsk), pmask);
2218         task_unlock(tsk);
2219         mutex_unlock(&callback_mutex);
2220 }
2221
2222 void cpuset_cpus_allowed_fallback(struct task_struct *tsk)
2223 {
2224         const struct cpuset *cs;
2225
2226         rcu_read_lock();
2227         cs = task_cs(tsk);
2228         do_set_cpus_allowed(tsk, cs->cpus_allowed);
2229         rcu_read_unlock();
2230
2231         /*
2232          * We own tsk->cpus_allowed, nobody can change it under us.
2233          *
2234          * But we used cs && cs->cpus_allowed lockless and thus can
2235          * race with cgroup_attach_task() or update_cpumask() and get
2236          * the wrong tsk->cpus_allowed. However, both cases imply the
2237          * subsequent cpuset_change_cpumask()->set_cpus_allowed_ptr()
2238          * which takes task_rq_lock().
2239          *
2240          * If we are called after it dropped the lock we must see all
2241          * changes in tsk_cs()->cpus_allowed. Otherwise we can temporary
2242          * set any mask even if it is not right from task_cs() pov,
2243          * the pending set_cpus_allowed_ptr() will fix things.
2244          *
2245          * select_fallback_rq() will fix things ups and set cpu_possible_mask
2246          * if required.
2247          */
2248 }
2249
2250 void cpuset_init_current_mems_allowed(void)
2251 {
2252         nodes_setall(current->mems_allowed);
2253 }
2254
2255 /**
2256  * cpuset_mems_allowed - return mems_allowed mask from a tasks cpuset.
2257  * @tsk: pointer to task_struct from which to obtain cpuset->mems_allowed.
2258  *
2259  * Description: Returns the nodemask_t mems_allowed of the cpuset
2260  * attached to the specified @tsk.  Guaranteed to return some non-empty
2261  * subset of node_states[N_MEMORY], even if this means going outside the
2262  * tasks cpuset.
2263  **/
2264
2265 nodemask_t cpuset_mems_allowed(struct task_struct *tsk)
2266 {
2267         nodemask_t mask;
2268
2269         mutex_lock(&callback_mutex);
2270         task_lock(tsk);
2271         guarantee_online_mems(task_cs(tsk), &mask);
2272         task_unlock(tsk);
2273         mutex_unlock(&callback_mutex);
2274
2275         return mask;
2276 }
2277
2278 /**
2279  * cpuset_nodemask_valid_mems_allowed - check nodemask vs. curremt mems_allowed
2280  * @nodemask: the nodemask to be checked
2281  *
2282  * Are any of the nodes in the nodemask allowed in current->mems_allowed?
2283  */
2284 int cpuset_nodemask_valid_mems_allowed(nodemask_t *nodemask)
2285 {
2286         return nodes_intersects(*nodemask, current->mems_allowed);
2287 }
2288
2289 /*
2290  * nearest_hardwall_ancestor() - Returns the nearest mem_exclusive or
2291  * mem_hardwall ancestor to the specified cpuset.  Call holding
2292  * callback_mutex.  If no ancestor is mem_exclusive or mem_hardwall
2293  * (an unusual configuration), then returns the root cpuset.
2294  */
2295 static const struct cpuset *nearest_hardwall_ancestor(const struct cpuset *cs)
2296 {
2297         while (!(is_mem_exclusive(cs) || is_mem_hardwall(cs)) && parent_cs(cs))
2298                 cs = parent_cs(cs);
2299         return cs;
2300 }
2301
2302 /**
2303  * cpuset_node_allowed_softwall - Can we allocate on a memory node?
2304  * @node: is this an allowed node?
2305  * @gfp_mask: memory allocation flags
2306  *
2307  * If we're in interrupt, yes, we can always allocate.  If __GFP_THISNODE is
2308  * set, yes, we can always allocate.  If node is in our task's mems_allowed,
2309  * yes.  If it's not a __GFP_HARDWALL request and this node is in the nearest
2310  * hardwalled cpuset ancestor to this task's cpuset, yes.  If the task has been
2311  * OOM killed and has access to memory reserves as specified by the TIF_MEMDIE
2312  * flag, yes.
2313  * Otherwise, no.
2314  *
2315  * If __GFP_HARDWALL is set, cpuset_node_allowed_softwall() reduces to
2316  * cpuset_node_allowed_hardwall().  Otherwise, cpuset_node_allowed_softwall()
2317  * might sleep, and might allow a node from an enclosing cpuset.
2318  *
2319  * cpuset_node_allowed_hardwall() only handles the simpler case of hardwall
2320  * cpusets, and never sleeps.
2321  *
2322  * The __GFP_THISNODE placement logic is really handled elsewhere,
2323  * by forcibly using a zonelist starting at a specified node, and by
2324  * (in get_page_from_freelist()) refusing to consider the zones for
2325  * any node on the zonelist except the first.  By the time any such
2326  * calls get to this routine, we should just shut up and say 'yes'.
2327  *
2328  * GFP_USER allocations are marked with the __GFP_HARDWALL bit,
2329  * and do not allow allocations outside the current tasks cpuset
2330  * unless the task has been OOM killed as is marked TIF_MEMDIE.
2331  * GFP_KERNEL allocations are not so marked, so can escape to the
2332  * nearest enclosing hardwalled ancestor cpuset.
2333  *
2334  * Scanning up parent cpusets requires callback_mutex.  The
2335  * __alloc_pages() routine only calls here with __GFP_HARDWALL bit
2336  * _not_ set if it's a GFP_KERNEL allocation, and all nodes in the
2337  * current tasks mems_allowed came up empty on the first pass over
2338  * the zonelist.  So only GFP_KERNEL allocations, if all nodes in the
2339  * cpuset are short of memory, might require taking the callback_mutex
2340  * mutex.
2341  *
2342  * The first call here from mm/page_alloc:get_page_from_freelist()
2343  * has __GFP_HARDWALL set in gfp_mask, enforcing hardwall cpusets,
2344  * so no allocation on a node outside the cpuset is allowed (unless
2345  * in interrupt, of course).
2346  *
2347  * The second pass through get_page_from_freelist() doesn't even call
2348  * here for GFP_ATOMIC calls.  For those calls, the __alloc_pages()
2349  * variable 'wait' is not set, and the bit ALLOC_CPUSET is not set
2350  * in alloc_flags.  That logic and the checks below have the combined
2351  * affect that:
2352  *      in_interrupt - any node ok (current task context irrelevant)
2353  *      GFP_ATOMIC   - any node ok
2354  *      TIF_MEMDIE   - any node ok
2355  *      GFP_KERNEL   - any node in enclosing hardwalled cpuset ok
2356  *      GFP_USER     - only nodes in current tasks mems allowed ok.
2357  *
2358  * Rule:
2359  *    Don't call cpuset_node_allowed_softwall if you can't sleep, unless you
2360  *    pass in the __GFP_HARDWALL flag set in gfp_flag, which disables
2361  *    the code that might scan up ancestor cpusets and sleep.
2362  */
2363 int __cpuset_node_allowed_softwall(int node, gfp_t gfp_mask)
2364 {
2365         const struct cpuset *cs;        /* current cpuset ancestors */
2366         int allowed;                    /* is allocation in zone z allowed? */
2367
2368         if (in_interrupt() || (gfp_mask & __GFP_THISNODE))
2369                 return 1;
2370         might_sleep_if(!(gfp_mask & __GFP_HARDWALL));
2371         if (node_isset(node, current->mems_allowed))
2372                 return 1;
2373         /*
2374          * Allow tasks that have access to memory reserves because they have
2375          * been OOM killed to get memory anywhere.
2376          */
2377         if (unlikely(test_thread_flag(TIF_MEMDIE)))
2378                 return 1;
2379         if (gfp_mask & __GFP_HARDWALL)  /* If hardwall request, stop here */
2380                 return 0;
2381
2382         if (current->flags & PF_EXITING) /* Let dying task have memory */
2383                 return 1;
2384
2385         /* Not hardwall and node outside mems_allowed: scan up cpusets */
2386         mutex_lock(&callback_mutex);
2387
2388         task_lock(current);
2389         cs = nearest_hardwall_ancestor(task_cs(current));
2390         task_unlock(current);
2391
2392         allowed = node_isset(node, cs->mems_allowed);
2393         mutex_unlock(&callback_mutex);
2394         return allowed;
2395 }
2396
2397 /*
2398  * cpuset_node_allowed_hardwall - Can we allocate on a memory node?
2399  * @node: is this an allowed node?
2400  * @gfp_mask: memory allocation flags
2401  *
2402  * If we're in interrupt, yes, we can always allocate.  If __GFP_THISNODE is
2403  * set, yes, we can always allocate.  If node is in our task's mems_allowed,
2404  * yes.  If the task has been OOM killed and has access to memory reserves as
2405  * specified by the TIF_MEMDIE flag, yes.
2406  * Otherwise, no.
2407  *
2408  * The __GFP_THISNODE placement logic is really handled elsewhere,
2409  * by forcibly using a zonelist starting at a specified node, and by
2410  * (in get_page_from_freelist()) refusing to consider the zones for
2411  * any node on the zonelist except the first.  By the time any such
2412  * calls get to this routine, we should just shut up and say 'yes'.
2413  *
2414  * Unlike the cpuset_node_allowed_softwall() variant, above,
2415  * this variant requires that the node be in the current task's
2416  * mems_allowed or that we're in interrupt.  It does not scan up the
2417  * cpuset hierarchy for the nearest enclosing mem_exclusive cpuset.
2418  * It never sleeps.
2419  */
2420 int __cpuset_node_allowed_hardwall(int node, gfp_t gfp_mask)
2421 {
2422         if (in_interrupt() || (gfp_mask & __GFP_THISNODE))
2423                 return 1;
2424         if (node_isset(node, current->mems_allowed))
2425                 return 1;
2426         /*
2427          * Allow tasks that have access to memory reserves because they have
2428          * been OOM killed to get memory anywhere.
2429          */
2430         if (unlikely(test_thread_flag(TIF_MEMDIE)))
2431                 return 1;
2432         return 0;
2433 }
2434
2435 /**
2436  * cpuset_mem_spread_node() - On which node to begin search for a file page
2437  * cpuset_slab_spread_node() - On which node to begin search for a slab page
2438  *
2439  * If a task is marked PF_SPREAD_PAGE or PF_SPREAD_SLAB (as for
2440  * tasks in a cpuset with is_spread_page or is_spread_slab set),
2441  * and if the memory allocation used cpuset_mem_spread_node()
2442  * to determine on which node to start looking, as it will for
2443  * certain page cache or slab cache pages such as used for file
2444  * system buffers and inode caches, then instead of starting on the
2445  * local node to look for a free page, rather spread the starting
2446  * node around the tasks mems_allowed nodes.
2447  *
2448  * We don't have to worry about the returned node being offline
2449  * because "it can't happen", and even if it did, it would be ok.
2450  *
2451  * The routines calling guarantee_online_mems() are careful to
2452  * only set nodes in task->mems_allowed that are online.  So it
2453  * should not be possible for the following code to return an
2454  * offline node.  But if it did, that would be ok, as this routine
2455  * is not returning the node where the allocation must be, only
2456  * the node where the search should start.  The zonelist passed to
2457  * __alloc_pages() will include all nodes.  If the slab allocator
2458  * is passed an offline node, it will fall back to the local node.
2459  * See kmem_cache_alloc_node().
2460  */
2461
2462 static int cpuset_spread_node(int *rotor)
2463 {
2464         int node;
2465
2466         node = next_node(*rotor, current->mems_allowed);
2467         if (node == MAX_NUMNODES)
2468                 node = first_node(current->mems_allowed);
2469         *rotor = node;
2470         return node;
2471 }
2472
2473 int cpuset_mem_spread_node(void)
2474 {
2475         if (current->cpuset_mem_spread_rotor == NUMA_NO_NODE)
2476                 current->cpuset_mem_spread_rotor =
2477                         node_random(&current->mems_allowed);
2478
2479         return cpuset_spread_node(&current->cpuset_mem_spread_rotor);
2480 }
2481
2482 int cpuset_slab_spread_node(void)
2483 {
2484         if (current->cpuset_slab_spread_rotor == NUMA_NO_NODE)
2485                 current->cpuset_slab_spread_rotor =
2486                         node_random(&current->mems_allowed);
2487
2488         return cpuset_spread_node(&current->cpuset_slab_spread_rotor);
2489 }
2490
2491 EXPORT_SYMBOL_GPL(cpuset_mem_spread_node);
2492
2493 /**
2494  * cpuset_mems_allowed_intersects - Does @tsk1's mems_allowed intersect @tsk2's?
2495  * @tsk1: pointer to task_struct of some task.
2496  * @tsk2: pointer to task_struct of some other task.
2497  *
2498  * Description: Return true if @tsk1's mems_allowed intersects the
2499  * mems_allowed of @tsk2.  Used by the OOM killer to determine if
2500  * one of the task's memory usage might impact the memory available
2501  * to the other.
2502  **/
2503
2504 int cpuset_mems_allowed_intersects(const struct task_struct *tsk1,
2505                                    const struct task_struct *tsk2)
2506 {
2507         return nodes_intersects(tsk1->mems_allowed, tsk2->mems_allowed);
2508 }
2509
2510 #define CPUSET_NODELIST_LEN     (256)
2511
2512 /**
2513  * cpuset_print_task_mems_allowed - prints task's cpuset and mems_allowed
2514  * @task: pointer to task_struct of some task.
2515  *
2516  * Description: Prints @task's name, cpuset name, and cached copy of its
2517  * mems_allowed to the kernel log.  Must hold task_lock(task) to allow
2518  * dereferencing task_cs(task).
2519  */
2520 void cpuset_print_task_mems_allowed(struct task_struct *tsk)
2521 {
2522          /* Statically allocated to prevent using excess stack. */
2523         static char cpuset_nodelist[CPUSET_NODELIST_LEN];
2524         static DEFINE_SPINLOCK(cpuset_buffer_lock);
2525
2526         struct cgroup *cgrp = task_cs(tsk)->css.cgroup;
2527
2528         rcu_read_lock();
2529         spin_lock(&cpuset_buffer_lock);
2530
2531         nodelist_scnprintf(cpuset_nodelist, CPUSET_NODELIST_LEN,
2532                            tsk->mems_allowed);
2533         printk(KERN_INFO "%s cpuset=%s mems_allowed=%s\n",
2534                tsk->comm, cgroup_name(cgrp), cpuset_nodelist);
2535
2536         spin_unlock(&cpuset_buffer_lock);
2537         rcu_read_unlock();
2538 }
2539
2540 /*
2541  * Collection of memory_pressure is suppressed unless
2542  * this flag is enabled by writing "1" to the special
2543  * cpuset file 'memory_pressure_enabled' in the root cpuset.
2544  */
2545
2546 int cpuset_memory_pressure_enabled __read_mostly;
2547
2548 /**
2549  * cpuset_memory_pressure_bump - keep stats of per-cpuset reclaims.
2550  *
2551  * Keep a running average of the rate of synchronous (direct)
2552  * page reclaim efforts initiated by tasks in each cpuset.
2553  *
2554  * This represents the rate at which some task in the cpuset
2555  * ran low on memory on all nodes it was allowed to use, and
2556  * had to enter the kernels page reclaim code in an effort to
2557  * create more free memory by tossing clean pages or swapping
2558  * or writing dirty pages.
2559  *
2560  * Display to user space in the per-cpuset read-only file
2561  * "memory_pressure".  Value displayed is an integer
2562  * representing the recent rate of entry into the synchronous
2563  * (direct) page reclaim by any task attached to the cpuset.
2564  **/
2565
2566 void __cpuset_memory_pressure_bump(void)
2567 {
2568         task_lock(current);
2569         fmeter_markevent(&task_cs(current)->fmeter);
2570         task_unlock(current);
2571 }
2572
2573 #ifdef CONFIG_PROC_PID_CPUSET
2574 /*
2575  * proc_cpuset_show()
2576  *  - Print tasks cpuset path into seq_file.
2577  *  - Used for /proc/<pid>/cpuset.
2578  *  - No need to task_lock(tsk) on this tsk->cpuset reference, as it
2579  *    doesn't really matter if tsk->cpuset changes after we read it,
2580  *    and we take cpuset_mutex, keeping cpuset_attach() from changing it
2581  *    anyway.
2582  */
2583 int proc_cpuset_show(struct seq_file *m, void *unused_v)
2584 {
2585         struct pid *pid;
2586         struct task_struct *tsk;
2587         char *buf;
2588         struct cgroup_subsys_state *css;
2589         int retval;
2590
2591         retval = -ENOMEM;
2592         buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
2593         if (!buf)
2594                 goto out;
2595
2596         retval = -ESRCH;
2597         pid = m->private;
2598         tsk = get_pid_task(pid, PIDTYPE_PID);
2599         if (!tsk)
2600                 goto out_free;
2601
2602         rcu_read_lock();
2603         css = task_subsys_state(tsk, cpuset_subsys_id);
2604         retval = cgroup_path(css->cgroup, buf, PAGE_SIZE);
2605         rcu_read_unlock();
2606         if (retval < 0)
2607                 goto out_put_task;
2608         seq_puts(m, buf);
2609         seq_putc(m, '\n');
2610 out_put_task:
2611         put_task_struct(tsk);
2612 out_free:
2613         kfree(buf);
2614 out:
2615         return retval;
2616 }
2617 #endif /* CONFIG_PROC_PID_CPUSET */
2618
2619 /* Display task mems_allowed in /proc/<pid>/status file. */
2620 void cpuset_task_status_allowed(struct seq_file *m, struct task_struct *task)
2621 {
2622         seq_printf(m, "Mems_allowed:\t");
2623         seq_nodemask(m, &task->mems_allowed);
2624         seq_printf(m, "\n");
2625         seq_printf(m, "Mems_allowed_list:\t");
2626         seq_nodemask_list(m, &task->mems_allowed);
2627         seq_printf(m, "\n");
2628 }