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