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