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/kthread.h>
37 #include <linux/list.h>
38 #include <linux/mempolicy.h>
39 #include <linux/mm.h>
40 #include <linux/memory.h>
41 #include <linux/export.h>
42 #include <linux/mount.h>
43 #include <linux/fs_context.h>
44 #include <linux/namei.h>
45 #include <linux/pagemap.h>
46 #include <linux/proc_fs.h>
47 #include <linux/rcupdate.h>
48 #include <linux/sched.h>
49 #include <linux/sched/deadline.h>
50 #include <linux/sched/mm.h>
51 #include <linux/sched/task.h>
52 #include <linux/seq_file.h>
53 #include <linux/security.h>
54 #include <linux/slab.h>
55 #include <linux/spinlock.h>
56 #include <linux/stat.h>
57 #include <linux/string.h>
58 #include <linux/time.h>
59 #include <linux/time64.h>
60 #include <linux/backing-dev.h>
61 #include <linux/sort.h>
62 #include <linux/oom.h>
63 #include <linux/sched/isolation.h>
64 #include <linux/uaccess.h>
65 #include <linux/atomic.h>
66 #include <linux/mutex.h>
67 #include <linux/cgroup.h>
68 #include <linux/wait.h>
69
70 DEFINE_STATIC_KEY_FALSE(cpusets_pre_enable_key);
71 DEFINE_STATIC_KEY_FALSE(cpusets_enabled_key);
72
73 /* See "Frequency meter" comments, below. */
74
75 struct fmeter {
76 int cnt; /* unprocessed events count */
77 int val; /* most recent output value */
78 time64_t time; /* clock (secs) when val computed */
79 spinlock_t lock; /* guards read or write of above */
80 };
81
82 struct cpuset {
83 struct cgroup_subsys_state css;
84
85 unsigned long flags; /* "unsigned long" so bitops work */
86
87 /*
88 * On default hierarchy:
89 *
90 * The user-configured masks can only be changed by writing to
91 * cpuset.cpus and cpuset.mems, and won't be limited by the
92 * parent masks.
93 *
94 * The effective masks is the real masks that apply to the tasks
95 * in the cpuset. They may be changed if the configured masks are
96 * changed or hotplug happens.
97 *
98 * effective_mask == configured_mask & parent's effective_mask,
99 * and if it ends up empty, it will inherit the parent's mask.
100 *
101 *
102 * On legacy hierachy:
103 *
104 * The user-configured masks are always the same with effective masks.
105 */
106
107 /* user-configured CPUs and Memory Nodes allow to tasks */
108 cpumask_var_t cpus_allowed;
109 cpumask_var_t cpus_requested;
110 nodemask_t mems_allowed;
111
112 /* effective CPUs and Memory Nodes allow to tasks */
113 cpumask_var_t effective_cpus;
114 nodemask_t effective_mems;
115
116 /*
117 * CPUs allocated to child sub-partitions (default hierarchy only)
118 * - CPUs granted by the parent = effective_cpus U subparts_cpus
119 * - effective_cpus and subparts_cpus are mutually exclusive.
120 *
121 * effective_cpus contains only onlined CPUs, but subparts_cpus
122 * may have offlined ones.
123 */
124 cpumask_var_t subparts_cpus;
125
126 /*
127 * This is old Memory Nodes tasks took on.
128 *
129 * - top_cpuset.old_mems_allowed is initialized to mems_allowed.
130 * - A new cpuset's old_mems_allowed is initialized when some
131 * task is moved into it.
132 * - old_mems_allowed is used in cpuset_migrate_mm() when we change
133 * cpuset.mems_allowed and have tasks' nodemask updated, and
134 * then old_mems_allowed is updated to mems_allowed.
135 */
136 nodemask_t old_mems_allowed;
137
138 struct fmeter fmeter; /* memory_pressure filter */
139
140 /*
141 * Tasks are being attached to this cpuset. Used to prevent
142 * zeroing cpus/mems_allowed between ->can_attach() and ->attach().
143 */
144 int attach_in_progress;
145
146 /* partition number for rebuild_sched_domains() */
147 int pn;
148
149 /* for custom sched domain */
150 int relax_domain_level;
151
152 /* number of CPUs in subparts_cpus */
153 int nr_subparts_cpus;
154
155 /* partition root state */
156 int partition_root_state;
157
158 /*
159 * Default hierarchy only:
160 * use_parent_ecpus - set if using parent's effective_cpus
161 * child_ecpus_count - # of children with use_parent_ecpus set
162 */
163 int use_parent_ecpus;
164 int child_ecpus_count;
165 };
166
167 /*
168 * Partition root states:
169 *
170 * 0 - not a partition root
171 *
172 * 1 - partition root
173 *
174 * -1 - invalid partition root
175 * None of the cpus in cpus_allowed can be put into the parent's
176 * subparts_cpus. In this case, the cpuset is not a real partition
177 * root anymore. However, the CPU_EXCLUSIVE bit will still be set
178 * and the cpuset can be restored back to a partition root if the
179 * parent cpuset can give more CPUs back to this child cpuset.
180 */
181 #define PRS_DISABLED 0
182 #define PRS_ENABLED 1
183 #define PRS_ERROR -1
184
185 /*
186 * Temporary cpumasks for working with partitions that are passed among
187 * functions to avoid memory allocation in inner functions.
188 */
189 struct tmpmasks {
190 cpumask_var_t addmask, delmask; /* For partition root */
191 cpumask_var_t new_cpus; /* For update_cpumasks_hier() */
192 };
193
css_cs(struct cgroup_subsys_state * css)194 static inline struct cpuset *css_cs(struct cgroup_subsys_state *css)
195 {
196 return css ? container_of(css, struct cpuset, css) : NULL;
197 }
198
199 /* Retrieve the cpuset for a task */
task_cs(struct task_struct * task)200 static inline struct cpuset *task_cs(struct task_struct *task)
201 {
202 return css_cs(task_css(task, cpuset_cgrp_id));
203 }
204
parent_cs(struct cpuset * cs)205 static inline struct cpuset *parent_cs(struct cpuset *cs)
206 {
207 return css_cs(cs->css.parent);
208 }
209
210 /* bits in struct cpuset flags field */
211 typedef enum {
212 CS_ONLINE,
213 CS_CPU_EXCLUSIVE,
214 CS_MEM_EXCLUSIVE,
215 CS_MEM_HARDWALL,
216 CS_MEMORY_MIGRATE,
217 CS_SCHED_LOAD_BALANCE,
218 CS_SPREAD_PAGE,
219 CS_SPREAD_SLAB,
220 } cpuset_flagbits_t;
221
222 /* convenient tests for these bits */
is_cpuset_online(struct cpuset * cs)223 static inline bool is_cpuset_online(struct cpuset *cs)
224 {
225 return test_bit(CS_ONLINE, &cs->flags) && !css_is_dying(&cs->css);
226 }
227
is_cpu_exclusive(const struct cpuset * cs)228 static inline int is_cpu_exclusive(const struct cpuset *cs)
229 {
230 return test_bit(CS_CPU_EXCLUSIVE, &cs->flags);
231 }
232
is_mem_exclusive(const struct cpuset * cs)233 static inline int is_mem_exclusive(const struct cpuset *cs)
234 {
235 return test_bit(CS_MEM_EXCLUSIVE, &cs->flags);
236 }
237
is_mem_hardwall(const struct cpuset * cs)238 static inline int is_mem_hardwall(const struct cpuset *cs)
239 {
240 return test_bit(CS_MEM_HARDWALL, &cs->flags);
241 }
242
is_sched_load_balance(const struct cpuset * cs)243 static inline int is_sched_load_balance(const struct cpuset *cs)
244 {
245 return test_bit(CS_SCHED_LOAD_BALANCE, &cs->flags);
246 }
247
is_memory_migrate(const struct cpuset * cs)248 static inline int is_memory_migrate(const struct cpuset *cs)
249 {
250 return test_bit(CS_MEMORY_MIGRATE, &cs->flags);
251 }
252
is_spread_page(const struct cpuset * cs)253 static inline int is_spread_page(const struct cpuset *cs)
254 {
255 return test_bit(CS_SPREAD_PAGE, &cs->flags);
256 }
257
is_spread_slab(const struct cpuset * cs)258 static inline int is_spread_slab(const struct cpuset *cs)
259 {
260 return test_bit(CS_SPREAD_SLAB, &cs->flags);
261 }
262
is_partition_root(const struct cpuset * cs)263 static inline int is_partition_root(const struct cpuset *cs)
264 {
265 return cs->partition_root_state > 0;
266 }
267
268 static struct cpuset top_cpuset = {
269 .flags = ((1 << CS_ONLINE) | (1 << CS_CPU_EXCLUSIVE) |
270 (1 << CS_MEM_EXCLUSIVE)),
271 .partition_root_state = PRS_ENABLED,
272 };
273
274 /**
275 * cpuset_for_each_child - traverse online children of a cpuset
276 * @child_cs: loop cursor pointing to the current child
277 * @pos_css: used for iteration
278 * @parent_cs: target cpuset to walk children of
279 *
280 * Walk @child_cs through the online children of @parent_cs. Must be used
281 * with RCU read locked.
282 */
283 #define cpuset_for_each_child(child_cs, pos_css, parent_cs) \
284 css_for_each_child((pos_css), &(parent_cs)->css) \
285 if (is_cpuset_online(((child_cs) = css_cs((pos_css)))))
286
287 /**
288 * cpuset_for_each_descendant_pre - pre-order walk of a cpuset's descendants
289 * @des_cs: loop cursor pointing to the current descendant
290 * @pos_css: used for iteration
291 * @root_cs: target cpuset to walk ancestor of
292 *
293 * Walk @des_cs through the online descendants of @root_cs. Must be used
294 * with RCU read locked. The caller may modify @pos_css by calling
295 * css_rightmost_descendant() to skip subtree. @root_cs is included in the
296 * iteration and the first node to be visited.
297 */
298 #define cpuset_for_each_descendant_pre(des_cs, pos_css, root_cs) \
299 css_for_each_descendant_pre((pos_css), &(root_cs)->css) \
300 if (is_cpuset_online(((des_cs) = css_cs((pos_css)))))
301
302 /*
303 * There are two global locks guarding cpuset structures - cpuset_mutex and
304 * callback_lock. We also require taking task_lock() when dereferencing a
305 * task's cpuset pointer. See "The task_lock() exception", at the end of this
306 * comment.
307 *
308 * A task must hold both locks to modify cpusets. If a task holds
309 * cpuset_mutex, then it blocks others wanting that mutex, ensuring that it
310 * is the only task able to also acquire callback_lock and be able to
311 * modify cpusets. It can perform various checks on the cpuset structure
312 * first, knowing nothing will change. It can also allocate memory while
313 * just holding cpuset_mutex. While it is performing these checks, various
314 * callback routines can briefly acquire callback_lock to query cpusets.
315 * Once it is ready to make the changes, it takes callback_lock, blocking
316 * everyone else.
317 *
318 * Calls to the kernel memory allocator can not be made while holding
319 * callback_lock, as that would risk double tripping on callback_lock
320 * from one of the callbacks into the cpuset code from within
321 * __alloc_pages().
322 *
323 * If a task is only holding callback_lock, then it has read-only
324 * access to cpusets.
325 *
326 * Now, the task_struct fields mems_allowed and mempolicy may be changed
327 * by other task, we use alloc_lock in the task_struct fields to protect
328 * them.
329 *
330 * The cpuset_common_file_read() handlers only hold callback_lock across
331 * small pieces of code, such as when reading out possibly multi-word
332 * cpumasks and nodemasks.
333 *
334 * Accessing a task's cpuset should be done in accordance with the
335 * guidelines for accessing subsystem state in kernel/cgroup.c
336 */
337
338 DEFINE_STATIC_PERCPU_RWSEM(cpuset_rwsem);
339
cpuset_read_lock(void)340 void cpuset_read_lock(void)
341 {
342 percpu_down_read(&cpuset_rwsem);
343 }
344
cpuset_read_unlock(void)345 void cpuset_read_unlock(void)
346 {
347 percpu_up_read(&cpuset_rwsem);
348 }
349
350 static DEFINE_SPINLOCK(callback_lock);
351
352 static struct workqueue_struct *cpuset_migrate_mm_wq;
353
354 /*
355 * CPU / memory hotplug is handled asynchronously.
356 */
357 static void cpuset_hotplug_workfn(struct work_struct *work);
358 static DECLARE_WORK(cpuset_hotplug_work, cpuset_hotplug_workfn);
359
360 static DECLARE_WAIT_QUEUE_HEAD(cpuset_attach_wq);
361
362 /*
363 * Cgroup v2 behavior is used on the "cpus" and "mems" control files when
364 * on default hierarchy or when the cpuset_v2_mode flag is set by mounting
365 * the v1 cpuset cgroup filesystem with the "cpuset_v2_mode" mount option.
366 * With v2 behavior, "cpus" and "mems" are always what the users have
367 * requested and won't be changed by hotplug events. Only the effective
368 * cpus or mems will be affected.
369 */
is_in_v2_mode(void)370 static inline bool is_in_v2_mode(void)
371 {
372 return cgroup_subsys_on_dfl(cpuset_cgrp_subsys) ||
373 (cpuset_cgrp_subsys.root->flags & CGRP_ROOT_CPUSET_V2_MODE);
374 }
375
376 /*
377 * Return in pmask the portion of a cpusets's cpus_allowed that
378 * are online. If none are online, walk up the cpuset hierarchy
379 * until we find one that does have some online cpus.
380 *
381 * One way or another, we guarantee to return some non-empty subset
382 * of cpu_online_mask.
383 *
384 * Call with callback_lock or cpuset_mutex held.
385 */
guarantee_online_cpus(struct cpuset * cs,struct cpumask * pmask)386 static void guarantee_online_cpus(struct cpuset *cs, struct cpumask *pmask)
387 {
388 while (!cpumask_intersects(cs->effective_cpus, cpu_online_mask)) {
389 cs = parent_cs(cs);
390 if (unlikely(!cs)) {
391 /*
392 * The top cpuset doesn't have any online cpu as a
393 * consequence of a race between cpuset_hotplug_work
394 * and cpu hotplug notifier. But we know the top
395 * cpuset's effective_cpus is on its way to be
396 * identical to cpu_online_mask.
397 */
398 cpumask_copy(pmask, cpu_online_mask);
399 return;
400 }
401 }
402 cpumask_and(pmask, cs->effective_cpus, cpu_online_mask);
403 }
404
405 /*
406 * Return in *pmask the portion of a cpusets's mems_allowed that
407 * are online, with memory. If none are online with memory, walk
408 * up the cpuset hierarchy until we find one that does have some
409 * online mems. The top cpuset always has some mems online.
410 *
411 * One way or another, we guarantee to return some non-empty subset
412 * of node_states[N_MEMORY].
413 *
414 * Call with callback_lock or cpuset_mutex held.
415 */
guarantee_online_mems(struct cpuset * cs,nodemask_t * pmask)416 static void guarantee_online_mems(struct cpuset *cs, nodemask_t *pmask)
417 {
418 while (!nodes_intersects(cs->effective_mems, node_states[N_MEMORY]))
419 cs = parent_cs(cs);
420 nodes_and(*pmask, cs->effective_mems, node_states[N_MEMORY]);
421 }
422
423 /*
424 * update task's spread flag if cpuset's page/slab spread flag is set
425 *
426 * Call with callback_lock or cpuset_mutex held.
427 */
cpuset_update_task_spread_flag(struct cpuset * cs,struct task_struct * tsk)428 static void cpuset_update_task_spread_flag(struct cpuset *cs,
429 struct task_struct *tsk)
430 {
431 if (is_spread_page(cs))
432 task_set_spread_page(tsk);
433 else
434 task_clear_spread_page(tsk);
435
436 if (is_spread_slab(cs))
437 task_set_spread_slab(tsk);
438 else
439 task_clear_spread_slab(tsk);
440 }
441
442 /*
443 * is_cpuset_subset(p, q) - Is cpuset p a subset of cpuset q?
444 *
445 * One cpuset is a subset of another if all its allowed CPUs and
446 * Memory Nodes are a subset of the other, and its exclusive flags
447 * are only set if the other's are set. Call holding cpuset_mutex.
448 */
449
is_cpuset_subset(const struct cpuset * p,const struct cpuset * q)450 static int is_cpuset_subset(const struct cpuset *p, const struct cpuset *q)
451 {
452 return cpumask_subset(p->cpus_requested, q->cpus_requested) &&
453 nodes_subset(p->mems_allowed, q->mems_allowed) &&
454 is_cpu_exclusive(p) <= is_cpu_exclusive(q) &&
455 is_mem_exclusive(p) <= is_mem_exclusive(q);
456 }
457
458 /**
459 * alloc_cpumasks - allocate three cpumasks for cpuset
460 * @cs: the cpuset that have cpumasks to be allocated.
461 * @tmp: the tmpmasks structure pointer
462 * Return: 0 if successful, -ENOMEM otherwise.
463 *
464 * Only one of the two input arguments should be non-NULL.
465 */
alloc_cpumasks(struct cpuset * cs,struct tmpmasks * tmp)466 static inline int alloc_cpumasks(struct cpuset *cs, struct tmpmasks *tmp)
467 {
468 cpumask_var_t *pmask1, *pmask2, *pmask3, *pmask4;
469
470 if (cs) {
471 pmask1 = &cs->cpus_allowed;
472 pmask2 = &cs->effective_cpus;
473 pmask3 = &cs->subparts_cpus;
474 pmask4 = &cs->cpus_requested;
475 } else {
476 pmask1 = &tmp->new_cpus;
477 pmask2 = &tmp->addmask;
478 pmask3 = &tmp->delmask;
479 }
480
481 if (!zalloc_cpumask_var(pmask1, GFP_KERNEL))
482 return -ENOMEM;
483
484 if (!zalloc_cpumask_var(pmask2, GFP_KERNEL))
485 goto free_one;
486
487 if (!zalloc_cpumask_var(pmask3, GFP_KERNEL))
488 goto free_two;
489
490 if (cs && !zalloc_cpumask_var(pmask4, GFP_KERNEL))
491 goto free_three;
492
493 return 0;
494
495 free_three:
496 free_cpumask_var(*pmask3);
497 free_two:
498 free_cpumask_var(*pmask2);
499 free_one:
500 free_cpumask_var(*pmask1);
501 return -ENOMEM;
502 }
503
504 /**
505 * free_cpumasks - free cpumasks in a tmpmasks structure
506 * @cs: the cpuset that have cpumasks to be free.
507 * @tmp: the tmpmasks structure pointer
508 */
free_cpumasks(struct cpuset * cs,struct tmpmasks * tmp)509 static inline void free_cpumasks(struct cpuset *cs, struct tmpmasks *tmp)
510 {
511 if (cs) {
512 free_cpumask_var(cs->cpus_allowed);
513 free_cpumask_var(cs->cpus_requested);
514 free_cpumask_var(cs->effective_cpus);
515 free_cpumask_var(cs->subparts_cpus);
516 }
517 if (tmp) {
518 free_cpumask_var(tmp->new_cpus);
519 free_cpumask_var(tmp->addmask);
520 free_cpumask_var(tmp->delmask);
521 }
522 }
523
524 /**
525 * alloc_trial_cpuset - allocate a trial cpuset
526 * @cs: the cpuset that the trial cpuset duplicates
527 */
alloc_trial_cpuset(struct cpuset * cs)528 static struct cpuset *alloc_trial_cpuset(struct cpuset *cs)
529 {
530 struct cpuset *trial;
531
532 trial = kmemdup(cs, sizeof(*cs), GFP_KERNEL);
533 if (!trial)
534 return NULL;
535
536 if (alloc_cpumasks(trial, NULL)) {
537 kfree(trial);
538 return NULL;
539 }
540
541 cpumask_copy(trial->cpus_allowed, cs->cpus_allowed);
542 cpumask_copy(trial->cpus_requested, cs->cpus_requested);
543 cpumask_copy(trial->effective_cpus, cs->effective_cpus);
544 return trial;
545 }
546
547 /**
548 * free_cpuset - free the cpuset
549 * @cs: the cpuset to be freed
550 */
free_cpuset(struct cpuset * cs)551 static inline void free_cpuset(struct cpuset *cs)
552 {
553 free_cpumasks(cs, NULL);
554 kfree(cs);
555 }
556
557 /*
558 * validate_change() - Used to validate that any proposed cpuset change
559 * follows the structural rules for cpusets.
560 *
561 * If we replaced the flag and mask values of the current cpuset
562 * (cur) with those values in the trial cpuset (trial), would
563 * our various subset and exclusive rules still be valid? Presumes
564 * cpuset_mutex held.
565 *
566 * 'cur' is the address of an actual, in-use cpuset. Operations
567 * such as list traversal that depend on the actual address of the
568 * cpuset in the list must use cur below, not trial.
569 *
570 * 'trial' is the address of bulk structure copy of cur, with
571 * perhaps one or more of the fields cpus_allowed, mems_allowed,
572 * or flags changed to new, trial values.
573 *
574 * Return 0 if valid, -errno if not.
575 */
576
validate_change(struct cpuset * cur,struct cpuset * trial)577 static int validate_change(struct cpuset *cur, struct cpuset *trial)
578 {
579 struct cgroup_subsys_state *css;
580 struct cpuset *c, *par;
581 int ret;
582
583 rcu_read_lock();
584
585 /* Each of our child cpusets must be a subset of us */
586 ret = -EBUSY;
587 cpuset_for_each_child(c, css, cur)
588 if (!is_cpuset_subset(c, trial))
589 goto out;
590
591 /* Remaining checks don't apply to root cpuset */
592 ret = 0;
593 if (cur == &top_cpuset)
594 goto out;
595
596 par = parent_cs(cur);
597
598 /* On legacy hiearchy, we must be a subset of our parent cpuset. */
599 ret = -EACCES;
600 if (!is_in_v2_mode() && !is_cpuset_subset(trial, par))
601 goto out;
602
603 /*
604 * If either I or some sibling (!= me) is exclusive, we can't
605 * overlap
606 */
607 ret = -EINVAL;
608 cpuset_for_each_child(c, css, par) {
609 if ((is_cpu_exclusive(trial) || is_cpu_exclusive(c)) &&
610 c != cur &&
611 cpumask_intersects(trial->cpus_requested,
612 c->cpus_requested))
613 goto out;
614 if ((is_mem_exclusive(trial) || is_mem_exclusive(c)) &&
615 c != cur &&
616 nodes_intersects(trial->mems_allowed, c->mems_allowed))
617 goto out;
618 }
619
620 /*
621 * Cpusets with tasks - existing or newly being attached - can't
622 * be changed to have empty cpus_allowed or mems_allowed.
623 */
624 ret = -ENOSPC;
625 if ((cgroup_is_populated(cur->css.cgroup) || cur->attach_in_progress)) {
626 if (!cpumask_empty(cur->cpus_allowed) &&
627 cpumask_empty(trial->cpus_allowed))
628 goto out;
629 if (!nodes_empty(cur->mems_allowed) &&
630 nodes_empty(trial->mems_allowed))
631 goto out;
632 }
633
634 /*
635 * We can't shrink if we won't have enough room for SCHED_DEADLINE
636 * tasks.
637 */
638 ret = -EBUSY;
639 if (is_cpu_exclusive(cur) &&
640 !cpuset_cpumask_can_shrink(cur->cpus_allowed,
641 trial->cpus_allowed))
642 goto out;
643
644 ret = 0;
645 out:
646 rcu_read_unlock();
647 return ret;
648 }
649
650 #ifdef CONFIG_SMP
651 /*
652 * Helper routine for generate_sched_domains().
653 * Do cpusets a, b have overlapping effective cpus_allowed masks?
654 */
cpusets_overlap(struct cpuset * a,struct cpuset * b)655 static int cpusets_overlap(struct cpuset *a, struct cpuset *b)
656 {
657 return cpumask_intersects(a->effective_cpus, b->effective_cpus);
658 }
659
660 static void
update_domain_attr(struct sched_domain_attr * dattr,struct cpuset * c)661 update_domain_attr(struct sched_domain_attr *dattr, struct cpuset *c)
662 {
663 if (dattr->relax_domain_level < c->relax_domain_level)
664 dattr->relax_domain_level = c->relax_domain_level;
665 return;
666 }
667
update_domain_attr_tree(struct sched_domain_attr * dattr,struct cpuset * root_cs)668 static void update_domain_attr_tree(struct sched_domain_attr *dattr,
669 struct cpuset *root_cs)
670 {
671 struct cpuset *cp;
672 struct cgroup_subsys_state *pos_css;
673
674 rcu_read_lock();
675 cpuset_for_each_descendant_pre(cp, pos_css, root_cs) {
676 /* skip the whole subtree if @cp doesn't have any CPU */
677 if (cpumask_empty(cp->cpus_allowed)) {
678 pos_css = css_rightmost_descendant(pos_css);
679 continue;
680 }
681
682 if (is_sched_load_balance(cp))
683 update_domain_attr(dattr, cp);
684 }
685 rcu_read_unlock();
686 }
687
688 /* Must be called with cpuset_mutex held. */
nr_cpusets(void)689 static inline int nr_cpusets(void)
690 {
691 /* jump label reference count + the top-level cpuset */
692 return static_key_count(&cpusets_enabled_key.key) + 1;
693 }
694
695 /*
696 * generate_sched_domains()
697 *
698 * This function builds a partial partition of the systems CPUs
699 * A 'partial partition' is a set of non-overlapping subsets whose
700 * union is a subset of that set.
701 * The output of this function needs to be passed to kernel/sched/core.c
702 * partition_sched_domains() routine, which will rebuild the scheduler's
703 * load balancing domains (sched domains) as specified by that partial
704 * partition.
705 *
706 * See "What is sched_load_balance" in Documentation/admin-guide/cgroup-v1/cpusets.rst
707 * for a background explanation of this.
708 *
709 * Does not return errors, on the theory that the callers of this
710 * routine would rather not worry about failures to rebuild sched
711 * domains when operating in the severe memory shortage situations
712 * that could cause allocation failures below.
713 *
714 * Must be called with cpuset_mutex held.
715 *
716 * The three key local variables below are:
717 * cp - cpuset pointer, used (together with pos_css) to perform a
718 * top-down scan of all cpusets. For our purposes, rebuilding
719 * the schedulers sched domains, we can ignore !is_sched_load_
720 * balance cpusets.
721 * csa - (for CpuSet Array) Array of pointers to all the cpusets
722 * that need to be load balanced, for convenient iterative
723 * access by the subsequent code that finds the best partition,
724 * i.e the set of domains (subsets) of CPUs such that the
725 * cpus_allowed of every cpuset marked is_sched_load_balance
726 * is a subset of one of these domains, while there are as
727 * many such domains as possible, each as small as possible.
728 * doms - Conversion of 'csa' to an array of cpumasks, for passing to
729 * the kernel/sched/core.c routine partition_sched_domains() in a
730 * convenient format, that can be easily compared to the prior
731 * value to determine what partition elements (sched domains)
732 * were changed (added or removed.)
733 *
734 * Finding the best partition (set of domains):
735 * The triple nested loops below over i, j, k scan over the
736 * load balanced cpusets (using the array of cpuset pointers in
737 * csa[]) looking for pairs of cpusets that have overlapping
738 * cpus_allowed, but which don't have the same 'pn' partition
739 * number and gives them in the same partition number. It keeps
740 * looping on the 'restart' label until it can no longer find
741 * any such pairs.
742 *
743 * The union of the cpus_allowed masks from the set of
744 * all cpusets having the same 'pn' value then form the one
745 * element of the partition (one sched domain) to be passed to
746 * partition_sched_domains().
747 */
generate_sched_domains(cpumask_var_t ** domains,struct sched_domain_attr ** attributes)748 static int generate_sched_domains(cpumask_var_t **domains,
749 struct sched_domain_attr **attributes)
750 {
751 struct cpuset *cp; /* top-down scan of cpusets */
752 struct cpuset **csa; /* array of all cpuset ptrs */
753 int csn; /* how many cpuset ptrs in csa so far */
754 int i, j, k; /* indices for partition finding loops */
755 cpumask_var_t *doms; /* resulting partition; i.e. sched domains */
756 struct sched_domain_attr *dattr; /* attributes for custom domains */
757 int ndoms = 0; /* number of sched domains in result */
758 int nslot; /* next empty doms[] struct cpumask slot */
759 struct cgroup_subsys_state *pos_css;
760 bool root_load_balance = is_sched_load_balance(&top_cpuset);
761
762 doms = NULL;
763 dattr = NULL;
764 csa = NULL;
765
766 /* Special case for the 99% of systems with one, full, sched domain */
767 if (root_load_balance && !top_cpuset.nr_subparts_cpus) {
768 ndoms = 1;
769 doms = alloc_sched_domains(ndoms);
770 if (!doms)
771 goto done;
772
773 dattr = kmalloc(sizeof(struct sched_domain_attr), GFP_KERNEL);
774 if (dattr) {
775 *dattr = SD_ATTR_INIT;
776 update_domain_attr_tree(dattr, &top_cpuset);
777 }
778 cpumask_and(doms[0], top_cpuset.effective_cpus,
779 housekeeping_cpumask(HK_FLAG_DOMAIN));
780
781 goto done;
782 }
783
784 csa = kmalloc_array(nr_cpusets(), sizeof(cp), GFP_KERNEL);
785 if (!csa)
786 goto done;
787 csn = 0;
788
789 rcu_read_lock();
790 if (root_load_balance)
791 csa[csn++] = &top_cpuset;
792 cpuset_for_each_descendant_pre(cp, pos_css, &top_cpuset) {
793 if (cp == &top_cpuset)
794 continue;
795 /*
796 * Continue traversing beyond @cp iff @cp has some CPUs and
797 * isn't load balancing. The former is obvious. The
798 * latter: All child cpusets contain a subset of the
799 * parent's cpus, so just skip them, and then we call
800 * update_domain_attr_tree() to calc relax_domain_level of
801 * the corresponding sched domain.
802 *
803 * If root is load-balancing, we can skip @cp if it
804 * is a subset of the root's effective_cpus.
805 */
806 if (!cpumask_empty(cp->cpus_allowed) &&
807 !(is_sched_load_balance(cp) &&
808 cpumask_intersects(cp->cpus_allowed,
809 housekeeping_cpumask(HK_FLAG_DOMAIN))))
810 continue;
811
812 if (root_load_balance &&
813 cpumask_subset(cp->cpus_allowed, top_cpuset.effective_cpus))
814 continue;
815
816 if (is_sched_load_balance(cp) &&
817 !cpumask_empty(cp->effective_cpus))
818 csa[csn++] = cp;
819
820 /* skip @cp's subtree if not a partition root */
821 if (!is_partition_root(cp))
822 pos_css = css_rightmost_descendant(pos_css);
823 }
824 rcu_read_unlock();
825
826 for (i = 0; i < csn; i++)
827 csa[i]->pn = i;
828 ndoms = csn;
829
830 restart:
831 /* Find the best partition (set of sched domains) */
832 for (i = 0; i < csn; i++) {
833 struct cpuset *a = csa[i];
834 int apn = a->pn;
835
836 for (j = 0; j < csn; j++) {
837 struct cpuset *b = csa[j];
838 int bpn = b->pn;
839
840 if (apn != bpn && cpusets_overlap(a, b)) {
841 for (k = 0; k < csn; k++) {
842 struct cpuset *c = csa[k];
843
844 if (c->pn == bpn)
845 c->pn = apn;
846 }
847 ndoms--; /* one less element */
848 goto restart;
849 }
850 }
851 }
852
853 /*
854 * Now we know how many domains to create.
855 * Convert <csn, csa> to <ndoms, doms> and populate cpu masks.
856 */
857 doms = alloc_sched_domains(ndoms);
858 if (!doms)
859 goto done;
860
861 /*
862 * The rest of the code, including the scheduler, can deal with
863 * dattr==NULL case. No need to abort if alloc fails.
864 */
865 dattr = kmalloc_array(ndoms, sizeof(struct sched_domain_attr),
866 GFP_KERNEL);
867
868 for (nslot = 0, i = 0; i < csn; i++) {
869 struct cpuset *a = csa[i];
870 struct cpumask *dp;
871 int apn = a->pn;
872
873 if (apn < 0) {
874 /* Skip completed partitions */
875 continue;
876 }
877
878 dp = doms[nslot];
879
880 if (nslot == ndoms) {
881 static int warnings = 10;
882 if (warnings) {
883 pr_warn("rebuild_sched_domains confused: nslot %d, ndoms %d, csn %d, i %d, apn %d\n",
884 nslot, ndoms, csn, i, apn);
885 warnings--;
886 }
887 continue;
888 }
889
890 cpumask_clear(dp);
891 if (dattr)
892 *(dattr + nslot) = SD_ATTR_INIT;
893 for (j = i; j < csn; j++) {
894 struct cpuset *b = csa[j];
895
896 if (apn == b->pn) {
897 cpumask_or(dp, dp, b->effective_cpus);
898 cpumask_and(dp, dp, housekeeping_cpumask(HK_FLAG_DOMAIN));
899 if (dattr)
900 update_domain_attr_tree(dattr + nslot, b);
901
902 /* Done with this partition */
903 b->pn = -1;
904 }
905 }
906 nslot++;
907 }
908 BUG_ON(nslot != ndoms);
909
910 done:
911 kfree(csa);
912
913 /*
914 * Fallback to the default domain if kmalloc() failed.
915 * See comments in partition_sched_domains().
916 */
917 if (doms == NULL)
918 ndoms = 1;
919
920 *domains = doms;
921 *attributes = dattr;
922 return ndoms;
923 }
924
update_tasks_root_domain(struct cpuset * cs)925 static void update_tasks_root_domain(struct cpuset *cs)
926 {
927 struct css_task_iter it;
928 struct task_struct *task;
929
930 css_task_iter_start(&cs->css, 0, &it);
931
932 while ((task = css_task_iter_next(&it)))
933 dl_add_task_root_domain(task);
934
935 css_task_iter_end(&it);
936 }
937
rebuild_root_domains(void)938 static void rebuild_root_domains(void)
939 {
940 struct cpuset *cs = NULL;
941 struct cgroup_subsys_state *pos_css;
942
943 percpu_rwsem_assert_held(&cpuset_rwsem);
944 lockdep_assert_cpus_held();
945 lockdep_assert_held(&sched_domains_mutex);
946
947 rcu_read_lock();
948
949 /*
950 * Clear default root domain DL accounting, it will be computed again
951 * if a task belongs to it.
952 */
953 dl_clear_root_domain(&def_root_domain);
954
955 cpuset_for_each_descendant_pre(cs, pos_css, &top_cpuset) {
956
957 if (cpumask_empty(cs->effective_cpus)) {
958 pos_css = css_rightmost_descendant(pos_css);
959 continue;
960 }
961
962 css_get(&cs->css);
963
964 rcu_read_unlock();
965
966 update_tasks_root_domain(cs);
967
968 rcu_read_lock();
969 css_put(&cs->css);
970 }
971 rcu_read_unlock();
972 }
973
974 static void
partition_and_rebuild_sched_domains(int ndoms_new,cpumask_var_t doms_new[],struct sched_domain_attr * dattr_new)975 partition_and_rebuild_sched_domains(int ndoms_new, cpumask_var_t doms_new[],
976 struct sched_domain_attr *dattr_new)
977 {
978 mutex_lock(&sched_domains_mutex);
979 partition_sched_domains_locked(ndoms_new, doms_new, dattr_new);
980 rebuild_root_domains();
981 mutex_unlock(&sched_domains_mutex);
982 }
983
984 /*
985 * Rebuild scheduler domains.
986 *
987 * If the flag 'sched_load_balance' of any cpuset with non-empty
988 * 'cpus' changes, or if the 'cpus' allowed changes in any cpuset
989 * which has that flag enabled, or if any cpuset with a non-empty
990 * 'cpus' is removed, then call this routine to rebuild the
991 * scheduler's dynamic sched domains.
992 *
993 * Call with cpuset_mutex held. Takes get_online_cpus().
994 */
rebuild_sched_domains_locked(void)995 static void rebuild_sched_domains_locked(void)
996 {
997 struct cgroup_subsys_state *pos_css;
998 struct sched_domain_attr *attr;
999 cpumask_var_t *doms;
1000 struct cpuset *cs;
1001 int ndoms;
1002
1003 lockdep_assert_cpus_held();
1004 percpu_rwsem_assert_held(&cpuset_rwsem);
1005
1006 /*
1007 * If we have raced with CPU hotplug, return early to avoid
1008 * passing doms with offlined cpu to partition_sched_domains().
1009 * Anyways, cpuset_hotplug_workfn() will rebuild sched domains.
1010 *
1011 * With no CPUs in any subpartitions, top_cpuset's effective CPUs
1012 * should be the same as the active CPUs, so checking only top_cpuset
1013 * is enough to detect racing CPU offlines.
1014 */
1015 if (!top_cpuset.nr_subparts_cpus &&
1016 !cpumask_equal(top_cpuset.effective_cpus, cpu_active_mask))
1017 return;
1018
1019 /*
1020 * With subpartition CPUs, however, the effective CPUs of a partition
1021 * root should be only a subset of the active CPUs. Since a CPU in any
1022 * partition root could be offlined, all must be checked.
1023 */
1024 if (top_cpuset.nr_subparts_cpus) {
1025 rcu_read_lock();
1026 cpuset_for_each_descendant_pre(cs, pos_css, &top_cpuset) {
1027 if (!is_partition_root(cs)) {
1028 pos_css = css_rightmost_descendant(pos_css);
1029 continue;
1030 }
1031 if (!cpumask_subset(cs->effective_cpus,
1032 cpu_active_mask)) {
1033 rcu_read_unlock();
1034 return;
1035 }
1036 }
1037 rcu_read_unlock();
1038 }
1039
1040 /* Generate domain masks and attrs */
1041 ndoms = generate_sched_domains(&doms, &attr);
1042
1043 /* Have scheduler rebuild the domains */
1044 partition_and_rebuild_sched_domains(ndoms, doms, attr);
1045 }
1046 #else /* !CONFIG_SMP */
rebuild_sched_domains_locked(void)1047 static void rebuild_sched_domains_locked(void)
1048 {
1049 }
1050 #endif /* CONFIG_SMP */
1051
rebuild_sched_domains(void)1052 void rebuild_sched_domains(void)
1053 {
1054 get_online_cpus();
1055 percpu_down_write(&cpuset_rwsem);
1056 rebuild_sched_domains_locked();
1057 percpu_up_write(&cpuset_rwsem);
1058 put_online_cpus();
1059 }
1060
1061 /**
1062 * update_tasks_cpumask - Update the cpumasks of tasks in the cpuset.
1063 * @cs: the cpuset in which each task's cpus_allowed mask needs to be changed
1064 *
1065 * Iterate through each task of @cs updating its cpus_allowed to the
1066 * effective cpuset's. As this function is called with cpuset_mutex held,
1067 * cpuset membership stays stable.
1068 */
update_tasks_cpumask(struct cpuset * cs)1069 static void update_tasks_cpumask(struct cpuset *cs)
1070 {
1071 struct css_task_iter it;
1072 struct task_struct *task;
1073 bool top_cs = cs == &top_cpuset;
1074
1075 css_task_iter_start(&cs->css, 0, &it);
1076 while ((task = css_task_iter_next(&it))) {
1077 /*
1078 * Percpu kthreads in top_cpuset are ignored
1079 */
1080 if (top_cs && (task->flags & PF_KTHREAD) &&
1081 kthread_is_per_cpu(task))
1082 continue;
1083 set_cpus_allowed_ptr(task, cs->effective_cpus);
1084 }
1085 css_task_iter_end(&it);
1086 }
1087
1088 /**
1089 * compute_effective_cpumask - Compute the effective cpumask of the cpuset
1090 * @new_cpus: the temp variable for the new effective_cpus mask
1091 * @cs: the cpuset the need to recompute the new effective_cpus mask
1092 * @parent: the parent cpuset
1093 *
1094 * If the parent has subpartition CPUs, include them in the list of
1095 * allowable CPUs in computing the new effective_cpus mask. Since offlined
1096 * CPUs are not removed from subparts_cpus, we have to use cpu_active_mask
1097 * to mask those out.
1098 */
compute_effective_cpumask(struct cpumask * new_cpus,struct cpuset * cs,struct cpuset * parent)1099 static void compute_effective_cpumask(struct cpumask *new_cpus,
1100 struct cpuset *cs, struct cpuset *parent)
1101 {
1102 if (parent->nr_subparts_cpus) {
1103 cpumask_or(new_cpus, parent->effective_cpus,
1104 parent->subparts_cpus);
1105 cpumask_and(new_cpus, new_cpus, cs->cpus_requested);
1106 cpumask_and(new_cpus, new_cpus, cpu_active_mask);
1107 } else {
1108 cpumask_and(new_cpus, cs->cpus_requested,
1109 parent->effective_cpus);
1110 }
1111 }
1112
1113 /*
1114 * Commands for update_parent_subparts_cpumask
1115 */
1116 enum subparts_cmd {
1117 partcmd_enable, /* Enable partition root */
1118 partcmd_disable, /* Disable partition root */
1119 partcmd_update, /* Update parent's subparts_cpus */
1120 };
1121
1122 /**
1123 * update_parent_subparts_cpumask - update subparts_cpus mask of parent cpuset
1124 * @cpuset: The cpuset that requests change in partition root state
1125 * @cmd: Partition root state change command
1126 * @newmask: Optional new cpumask for partcmd_update
1127 * @tmp: Temporary addmask and delmask
1128 * Return: 0, 1 or an error code
1129 *
1130 * For partcmd_enable, the cpuset is being transformed from a non-partition
1131 * root to a partition root. The cpus_allowed mask of the given cpuset will
1132 * be put into parent's subparts_cpus and taken away from parent's
1133 * effective_cpus. The function will return 0 if all the CPUs listed in
1134 * cpus_allowed can be granted or an error code will be returned.
1135 *
1136 * For partcmd_disable, the cpuset is being transofrmed from a partition
1137 * root back to a non-partition root. Any CPUs in cpus_allowed that are in
1138 * parent's subparts_cpus will be taken away from that cpumask and put back
1139 * into parent's effective_cpus. 0 should always be returned.
1140 *
1141 * For partcmd_update, if the optional newmask is specified, the cpu
1142 * list is to be changed from cpus_allowed to newmask. Otherwise,
1143 * cpus_allowed is assumed to remain the same. The cpuset should either
1144 * be a partition root or an invalid partition root. The partition root
1145 * state may change if newmask is NULL and none of the requested CPUs can
1146 * be granted by the parent. The function will return 1 if changes to
1147 * parent's subparts_cpus and effective_cpus happen or 0 otherwise.
1148 * Error code should only be returned when newmask is non-NULL.
1149 *
1150 * The partcmd_enable and partcmd_disable commands are used by
1151 * update_prstate(). The partcmd_update command is used by
1152 * update_cpumasks_hier() with newmask NULL and update_cpumask() with
1153 * newmask set.
1154 *
1155 * The checking is more strict when enabling partition root than the
1156 * other two commands.
1157 *
1158 * Because of the implicit cpu exclusive nature of a partition root,
1159 * cpumask changes that violates the cpu exclusivity rule will not be
1160 * permitted when checked by validate_change(). The validate_change()
1161 * function will also prevent any changes to the cpu list if it is not
1162 * a superset of children's cpu lists.
1163 */
update_parent_subparts_cpumask(struct cpuset * cpuset,int cmd,struct cpumask * newmask,struct tmpmasks * tmp)1164 static int update_parent_subparts_cpumask(struct cpuset *cpuset, int cmd,
1165 struct cpumask *newmask,
1166 struct tmpmasks *tmp)
1167 {
1168 struct cpuset *parent = parent_cs(cpuset);
1169 int adding; /* Moving cpus from effective_cpus to subparts_cpus */
1170 int deleting; /* Moving cpus from subparts_cpus to effective_cpus */
1171 int new_prs;
1172 bool part_error = false; /* Partition error? */
1173
1174 percpu_rwsem_assert_held(&cpuset_rwsem);
1175
1176 /*
1177 * The parent must be a partition root.
1178 * The new cpumask, if present, or the current cpus_allowed must
1179 * not be empty.
1180 */
1181 if (!is_partition_root(parent) ||
1182 (newmask && cpumask_empty(newmask)) ||
1183 (!newmask && cpumask_empty(cpuset->cpus_allowed)))
1184 return -EINVAL;
1185
1186 /*
1187 * Enabling/disabling partition root is not allowed if there are
1188 * online children.
1189 */
1190 if ((cmd != partcmd_update) && css_has_online_children(&cpuset->css))
1191 return -EBUSY;
1192
1193 /*
1194 * Enabling partition root is not allowed if not all the CPUs
1195 * can be granted from parent's effective_cpus or at least one
1196 * CPU will be left after that.
1197 */
1198 if ((cmd == partcmd_enable) &&
1199 (!cpumask_subset(cpuset->cpus_allowed, parent->effective_cpus) ||
1200 cpumask_equal(cpuset->cpus_allowed, parent->effective_cpus)))
1201 return -EINVAL;
1202
1203 /*
1204 * A cpumask update cannot make parent's effective_cpus become empty.
1205 */
1206 adding = deleting = false;
1207 new_prs = cpuset->partition_root_state;
1208 if (cmd == partcmd_enable) {
1209 cpumask_copy(tmp->addmask, cpuset->cpus_allowed);
1210 adding = true;
1211 } else if (cmd == partcmd_disable) {
1212 deleting = cpumask_and(tmp->delmask, cpuset->cpus_allowed,
1213 parent->subparts_cpus);
1214 } else if (newmask) {
1215 /*
1216 * partcmd_update with newmask:
1217 *
1218 * delmask = cpus_allowed & ~newmask & parent->subparts_cpus
1219 * addmask = newmask & parent->effective_cpus
1220 * & ~parent->subparts_cpus
1221 */
1222 cpumask_andnot(tmp->delmask, cpuset->cpus_allowed, newmask);
1223 deleting = cpumask_and(tmp->delmask, tmp->delmask,
1224 parent->subparts_cpus);
1225
1226 cpumask_and(tmp->addmask, newmask, parent->effective_cpus);
1227 adding = cpumask_andnot(tmp->addmask, tmp->addmask,
1228 parent->subparts_cpus);
1229 /*
1230 * Return error if the new effective_cpus could become empty.
1231 */
1232 if (adding &&
1233 cpumask_equal(parent->effective_cpus, tmp->addmask)) {
1234 if (!deleting)
1235 return -EINVAL;
1236 /*
1237 * As some of the CPUs in subparts_cpus might have
1238 * been offlined, we need to compute the real delmask
1239 * to confirm that.
1240 */
1241 if (!cpumask_and(tmp->addmask, tmp->delmask,
1242 cpu_active_mask))
1243 return -EINVAL;
1244 cpumask_copy(tmp->addmask, parent->effective_cpus);
1245 }
1246 } else {
1247 /*
1248 * partcmd_update w/o newmask:
1249 *
1250 * addmask = cpus_allowed & parent->effective_cpus
1251 *
1252 * Note that parent's subparts_cpus may have been
1253 * pre-shrunk in case there is a change in the cpu list.
1254 * So no deletion is needed.
1255 */
1256 adding = cpumask_and(tmp->addmask, cpuset->cpus_allowed,
1257 parent->effective_cpus);
1258 part_error = cpumask_equal(tmp->addmask,
1259 parent->effective_cpus);
1260 }
1261
1262 if (cmd == partcmd_update) {
1263 int prev_prs = cpuset->partition_root_state;
1264
1265 /*
1266 * Check for possible transition between PRS_ENABLED
1267 * and PRS_ERROR.
1268 */
1269 switch (cpuset->partition_root_state) {
1270 case PRS_ENABLED:
1271 if (part_error)
1272 new_prs = PRS_ERROR;
1273 break;
1274 case PRS_ERROR:
1275 if (!part_error)
1276 new_prs = PRS_ENABLED;
1277 break;
1278 }
1279 /*
1280 * Set part_error if previously in invalid state.
1281 */
1282 part_error = (prev_prs == PRS_ERROR);
1283 }
1284
1285 if (!part_error && (new_prs == PRS_ERROR))
1286 return 0; /* Nothing need to be done */
1287
1288 if (new_prs == PRS_ERROR) {
1289 /*
1290 * Remove all its cpus from parent's subparts_cpus.
1291 */
1292 adding = false;
1293 deleting = cpumask_and(tmp->delmask, cpuset->cpus_allowed,
1294 parent->subparts_cpus);
1295 }
1296
1297 if (!adding && !deleting && (new_prs == cpuset->partition_root_state))
1298 return 0;
1299
1300 /*
1301 * Change the parent's subparts_cpus.
1302 * Newly added CPUs will be removed from effective_cpus and
1303 * newly deleted ones will be added back to effective_cpus.
1304 */
1305 spin_lock_irq(&callback_lock);
1306 if (adding) {
1307 cpumask_or(parent->subparts_cpus,
1308 parent->subparts_cpus, tmp->addmask);
1309 cpumask_andnot(parent->effective_cpus,
1310 parent->effective_cpus, tmp->addmask);
1311 }
1312 if (deleting) {
1313 cpumask_andnot(parent->subparts_cpus,
1314 parent->subparts_cpus, tmp->delmask);
1315 /*
1316 * Some of the CPUs in subparts_cpus might have been offlined.
1317 */
1318 cpumask_and(tmp->delmask, tmp->delmask, cpu_active_mask);
1319 cpumask_or(parent->effective_cpus,
1320 parent->effective_cpus, tmp->delmask);
1321 }
1322
1323 parent->nr_subparts_cpus = cpumask_weight(parent->subparts_cpus);
1324
1325 if (cpuset->partition_root_state != new_prs)
1326 cpuset->partition_root_state = new_prs;
1327 spin_unlock_irq(&callback_lock);
1328
1329 return cmd == partcmd_update;
1330 }
1331
1332 /*
1333 * update_cpumasks_hier - Update effective cpumasks and tasks in the subtree
1334 * @cs: the cpuset to consider
1335 * @tmp: temp variables for calculating effective_cpus & partition setup
1336 *
1337 * When congifured cpumask is changed, the effective cpumasks of this cpuset
1338 * and all its descendants need to be updated.
1339 *
1340 * On legacy hierachy, effective_cpus will be the same with cpu_allowed.
1341 *
1342 * Called with cpuset_mutex held
1343 */
update_cpumasks_hier(struct cpuset * cs,struct tmpmasks * tmp)1344 static void update_cpumasks_hier(struct cpuset *cs, struct tmpmasks *tmp)
1345 {
1346 struct cpuset *cp;
1347 struct cgroup_subsys_state *pos_css;
1348 bool need_rebuild_sched_domains = false;
1349 int new_prs;
1350
1351 rcu_read_lock();
1352 cpuset_for_each_descendant_pre(cp, pos_css, cs) {
1353 struct cpuset *parent = parent_cs(cp);
1354
1355 compute_effective_cpumask(tmp->new_cpus, cp, parent);
1356
1357 /*
1358 * If it becomes empty, inherit the effective mask of the
1359 * parent, which is guaranteed to have some CPUs.
1360 */
1361 if (is_in_v2_mode() && cpumask_empty(tmp->new_cpus)) {
1362 cpumask_copy(tmp->new_cpus, parent->effective_cpus);
1363 if (!cp->use_parent_ecpus) {
1364 cp->use_parent_ecpus = true;
1365 parent->child_ecpus_count++;
1366 }
1367 } else if (cp->use_parent_ecpus) {
1368 cp->use_parent_ecpus = false;
1369 WARN_ON_ONCE(!parent->child_ecpus_count);
1370 parent->child_ecpus_count--;
1371 }
1372
1373 /*
1374 * Skip the whole subtree if the cpumask remains the same
1375 * and has no partition root state.
1376 */
1377 if (!cp->partition_root_state &&
1378 cpumask_equal(tmp->new_cpus, cp->effective_cpus)) {
1379 pos_css = css_rightmost_descendant(pos_css);
1380 continue;
1381 }
1382
1383 /*
1384 * update_parent_subparts_cpumask() should have been called
1385 * for cs already in update_cpumask(). We should also call
1386 * update_tasks_cpumask() again for tasks in the parent
1387 * cpuset if the parent's subparts_cpus changes.
1388 */
1389 new_prs = cp->partition_root_state;
1390 if ((cp != cs) && new_prs) {
1391 switch (parent->partition_root_state) {
1392 case PRS_DISABLED:
1393 /*
1394 * If parent is not a partition root or an
1395 * invalid partition root, clear its state
1396 * and its CS_CPU_EXCLUSIVE flag.
1397 */
1398 WARN_ON_ONCE(cp->partition_root_state
1399 != PRS_ERROR);
1400 new_prs = PRS_DISABLED;
1401
1402 /*
1403 * clear_bit() is an atomic operation and
1404 * readers aren't interested in the state
1405 * of CS_CPU_EXCLUSIVE anyway. So we can
1406 * just update the flag without holding
1407 * the callback_lock.
1408 */
1409 clear_bit(CS_CPU_EXCLUSIVE, &cp->flags);
1410 break;
1411
1412 case PRS_ENABLED:
1413 if (update_parent_subparts_cpumask(cp, partcmd_update, NULL, tmp))
1414 update_tasks_cpumask(parent);
1415 break;
1416
1417 case PRS_ERROR:
1418 /*
1419 * When parent is invalid, it has to be too.
1420 */
1421 new_prs = PRS_ERROR;
1422 break;
1423 }
1424 }
1425
1426 if (!css_tryget_online(&cp->css))
1427 continue;
1428 rcu_read_unlock();
1429
1430 spin_lock_irq(&callback_lock);
1431
1432 cpumask_copy(cp->effective_cpus, tmp->new_cpus);
1433 if (cp->nr_subparts_cpus && (new_prs != PRS_ENABLED)) {
1434 cp->nr_subparts_cpus = 0;
1435 cpumask_clear(cp->subparts_cpus);
1436 } else if (cp->nr_subparts_cpus) {
1437 /*
1438 * Make sure that effective_cpus & subparts_cpus
1439 * are mutually exclusive.
1440 *
1441 * In the unlikely event that effective_cpus
1442 * becomes empty. we clear cp->nr_subparts_cpus and
1443 * let its child partition roots to compete for
1444 * CPUs again.
1445 */
1446 cpumask_andnot(cp->effective_cpus, cp->effective_cpus,
1447 cp->subparts_cpus);
1448 if (cpumask_empty(cp->effective_cpus)) {
1449 cpumask_copy(cp->effective_cpus, tmp->new_cpus);
1450 cpumask_clear(cp->subparts_cpus);
1451 cp->nr_subparts_cpus = 0;
1452 } else if (!cpumask_subset(cp->subparts_cpus,
1453 tmp->new_cpus)) {
1454 cpumask_andnot(cp->subparts_cpus,
1455 cp->subparts_cpus, tmp->new_cpus);
1456 cp->nr_subparts_cpus
1457 = cpumask_weight(cp->subparts_cpus);
1458 }
1459 }
1460
1461 if (new_prs != cp->partition_root_state)
1462 cp->partition_root_state = new_prs;
1463
1464 spin_unlock_irq(&callback_lock);
1465
1466 WARN_ON(!is_in_v2_mode() &&
1467 !cpumask_equal(cp->cpus_allowed, cp->effective_cpus));
1468
1469 update_tasks_cpumask(cp);
1470
1471 /*
1472 * On legacy hierarchy, if the effective cpumask of any non-
1473 * empty cpuset is changed, we need to rebuild sched domains.
1474 * On default hierarchy, the cpuset needs to be a partition
1475 * root as well.
1476 */
1477 if (!cpumask_empty(cp->cpus_allowed) &&
1478 is_sched_load_balance(cp) &&
1479 (!cgroup_subsys_on_dfl(cpuset_cgrp_subsys) ||
1480 is_partition_root(cp)))
1481 need_rebuild_sched_domains = true;
1482
1483 rcu_read_lock();
1484 css_put(&cp->css);
1485 }
1486 rcu_read_unlock();
1487
1488 if (need_rebuild_sched_domains)
1489 rebuild_sched_domains_locked();
1490 }
1491
1492 /**
1493 * update_sibling_cpumasks - Update siblings cpumasks
1494 * @parent: Parent cpuset
1495 * @cs: Current cpuset
1496 * @tmp: Temp variables
1497 */
update_sibling_cpumasks(struct cpuset * parent,struct cpuset * cs,struct tmpmasks * tmp)1498 static void update_sibling_cpumasks(struct cpuset *parent, struct cpuset *cs,
1499 struct tmpmasks *tmp)
1500 {
1501 struct cpuset *sibling;
1502 struct cgroup_subsys_state *pos_css;
1503
1504 percpu_rwsem_assert_held(&cpuset_rwsem);
1505
1506 /*
1507 * Check all its siblings and call update_cpumasks_hier()
1508 * if their use_parent_ecpus flag is set in order for them
1509 * to use the right effective_cpus value.
1510 *
1511 * The update_cpumasks_hier() function may sleep. So we have to
1512 * release the RCU read lock before calling it.
1513 */
1514 rcu_read_lock();
1515 cpuset_for_each_child(sibling, pos_css, parent) {
1516 if (sibling == cs)
1517 continue;
1518 if (!sibling->use_parent_ecpus)
1519 continue;
1520 if (!css_tryget_online(&sibling->css))
1521 continue;
1522
1523 rcu_read_unlock();
1524 update_cpumasks_hier(sibling, tmp);
1525 rcu_read_lock();
1526 css_put(&sibling->css);
1527 }
1528 rcu_read_unlock();
1529 }
1530
1531 /**
1532 * update_cpumask - update the cpus_allowed mask of a cpuset and all tasks in it
1533 * @cs: the cpuset to consider
1534 * @trialcs: trial cpuset
1535 * @buf: buffer of cpu numbers written to this cpuset
1536 */
update_cpumask(struct cpuset * cs,struct cpuset * trialcs,const char * buf)1537 static int update_cpumask(struct cpuset *cs, struct cpuset *trialcs,
1538 const char *buf)
1539 {
1540 int retval;
1541 struct tmpmasks tmp;
1542
1543 /* top_cpuset.cpus_allowed tracks cpu_online_mask; it's read-only */
1544 if (cs == &top_cpuset)
1545 return -EACCES;
1546
1547 /*
1548 * An empty cpus_requested is ok only if the cpuset has no tasks.
1549 * Since cpulist_parse() fails on an empty mask, we special case
1550 * that parsing. The validate_change() call ensures that cpusets
1551 * with tasks have cpus.
1552 */
1553 if (!*buf) {
1554 cpumask_clear(trialcs->cpus_requested);
1555 } else {
1556 retval = cpulist_parse(buf, trialcs->cpus_requested);
1557 if (retval < 0)
1558 return retval;
1559 }
1560
1561 if (!cpumask_subset(trialcs->cpus_requested, cpu_present_mask))
1562 return -EINVAL;
1563
1564 cpumask_and(trialcs->cpus_allowed, trialcs->cpus_requested,
1565 cpu_active_mask);
1566
1567 /* Nothing to do if the cpus didn't change */
1568 if (cpumask_equal(cs->cpus_requested, trialcs->cpus_requested))
1569 return 0;
1570
1571 retval = validate_change(cs, trialcs);
1572 if (retval < 0)
1573 return retval;
1574
1575 #ifdef CONFIG_CPUMASK_OFFSTACK
1576 /*
1577 * Use the cpumasks in trialcs for tmpmasks when they are pointers
1578 * to allocated cpumasks.
1579 */
1580 tmp.addmask = trialcs->subparts_cpus;
1581 tmp.delmask = trialcs->effective_cpus;
1582 tmp.new_cpus = trialcs->cpus_allowed;
1583 #endif
1584
1585 if (cs->partition_root_state) {
1586 /* Cpumask of a partition root cannot be empty */
1587 if (cpumask_empty(trialcs->cpus_allowed))
1588 return -EINVAL;
1589 if (update_parent_subparts_cpumask(cs, partcmd_update,
1590 trialcs->cpus_allowed, &tmp) < 0)
1591 return -EINVAL;
1592 }
1593
1594 spin_lock_irq(&callback_lock);
1595 cpumask_copy(cs->cpus_allowed, trialcs->cpus_allowed);
1596 cpumask_copy(cs->cpus_requested, trialcs->cpus_requested);
1597
1598 /*
1599 * Make sure that subparts_cpus is a subset of cpus_allowed.
1600 */
1601 if (cs->nr_subparts_cpus) {
1602 cpumask_and(cs->subparts_cpus, cs->subparts_cpus, cs->cpus_allowed);
1603 cs->nr_subparts_cpus = cpumask_weight(cs->subparts_cpus);
1604 }
1605 spin_unlock_irq(&callback_lock);
1606
1607 update_cpumasks_hier(cs, &tmp);
1608
1609 if (cs->partition_root_state) {
1610 struct cpuset *parent = parent_cs(cs);
1611
1612 /*
1613 * For partition root, update the cpumasks of sibling
1614 * cpusets if they use parent's effective_cpus.
1615 */
1616 if (parent->child_ecpus_count)
1617 update_sibling_cpumasks(parent, cs, &tmp);
1618 }
1619 return 0;
1620 }
1621
1622 /*
1623 * Migrate memory region from one set of nodes to another. This is
1624 * performed asynchronously as it can be called from process migration path
1625 * holding locks involved in process management. All mm migrations are
1626 * performed in the queued order and can be waited for by flushing
1627 * cpuset_migrate_mm_wq.
1628 */
1629
1630 struct cpuset_migrate_mm_work {
1631 struct work_struct work;
1632 struct mm_struct *mm;
1633 nodemask_t from;
1634 nodemask_t to;
1635 };
1636
cpuset_migrate_mm_workfn(struct work_struct * work)1637 static void cpuset_migrate_mm_workfn(struct work_struct *work)
1638 {
1639 struct cpuset_migrate_mm_work *mwork =
1640 container_of(work, struct cpuset_migrate_mm_work, work);
1641
1642 /* on a wq worker, no need to worry about %current's mems_allowed */
1643 do_migrate_pages(mwork->mm, &mwork->from, &mwork->to, MPOL_MF_MOVE_ALL);
1644 mmput(mwork->mm);
1645 kfree(mwork);
1646 }
1647
cpuset_migrate_mm(struct mm_struct * mm,const nodemask_t * from,const nodemask_t * to)1648 static void cpuset_migrate_mm(struct mm_struct *mm, const nodemask_t *from,
1649 const nodemask_t *to)
1650 {
1651 struct cpuset_migrate_mm_work *mwork;
1652
1653 mwork = kzalloc(sizeof(*mwork), GFP_KERNEL);
1654 if (mwork) {
1655 mwork->mm = mm;
1656 mwork->from = *from;
1657 mwork->to = *to;
1658 INIT_WORK(&mwork->work, cpuset_migrate_mm_workfn);
1659 queue_work(cpuset_migrate_mm_wq, &mwork->work);
1660 } else {
1661 mmput(mm);
1662 }
1663 }
1664
cpuset_post_attach(void)1665 static void cpuset_post_attach(void)
1666 {
1667 flush_workqueue(cpuset_migrate_mm_wq);
1668 }
1669
1670 /*
1671 * cpuset_change_task_nodemask - change task's mems_allowed and mempolicy
1672 * @tsk: the task to change
1673 * @newmems: new nodes that the task will be set
1674 *
1675 * We use the mems_allowed_seq seqlock to safely update both tsk->mems_allowed
1676 * and rebind an eventual tasks' mempolicy. If the task is allocating in
1677 * parallel, it might temporarily see an empty intersection, which results in
1678 * a seqlock check and retry before OOM or allocation failure.
1679 */
cpuset_change_task_nodemask(struct task_struct * tsk,nodemask_t * newmems)1680 static void cpuset_change_task_nodemask(struct task_struct *tsk,
1681 nodemask_t *newmems)
1682 {
1683 task_lock(tsk);
1684
1685 local_irq_disable();
1686 write_seqcount_begin(&tsk->mems_allowed_seq);
1687
1688 nodes_or(tsk->mems_allowed, tsk->mems_allowed, *newmems);
1689 mpol_rebind_task(tsk, newmems);
1690 tsk->mems_allowed = *newmems;
1691
1692 write_seqcount_end(&tsk->mems_allowed_seq);
1693 local_irq_enable();
1694
1695 task_unlock(tsk);
1696 }
1697
1698 static void *cpuset_being_rebound;
1699
1700 /**
1701 * update_tasks_nodemask - Update the nodemasks of tasks in the cpuset.
1702 * @cs: the cpuset in which each task's mems_allowed mask needs to be changed
1703 *
1704 * Iterate through each task of @cs updating its mems_allowed to the
1705 * effective cpuset's. As this function is called with cpuset_mutex held,
1706 * cpuset membership stays stable.
1707 */
update_tasks_nodemask(struct cpuset * cs)1708 static void update_tasks_nodemask(struct cpuset *cs)
1709 {
1710 static nodemask_t newmems; /* protected by cpuset_mutex */
1711 struct css_task_iter it;
1712 struct task_struct *task;
1713
1714 cpuset_being_rebound = cs; /* causes mpol_dup() rebind */
1715
1716 guarantee_online_mems(cs, &newmems);
1717
1718 /*
1719 * The mpol_rebind_mm() call takes mmap_lock, which we couldn't
1720 * take while holding tasklist_lock. Forks can happen - the
1721 * mpol_dup() cpuset_being_rebound check will catch such forks,
1722 * and rebind their vma mempolicies too. Because we still hold
1723 * the global cpuset_mutex, we know that no other rebind effort
1724 * will be contending for the global variable cpuset_being_rebound.
1725 * It's ok if we rebind the same mm twice; mpol_rebind_mm()
1726 * is idempotent. Also migrate pages in each mm to new nodes.
1727 */
1728 css_task_iter_start(&cs->css, 0, &it);
1729 while ((task = css_task_iter_next(&it))) {
1730 struct mm_struct *mm;
1731 bool migrate;
1732
1733 cpuset_change_task_nodemask(task, &newmems);
1734
1735 mm = get_task_mm(task);
1736 if (!mm)
1737 continue;
1738
1739 migrate = is_memory_migrate(cs);
1740
1741 mpol_rebind_mm(mm, &cs->mems_allowed);
1742 if (migrate)
1743 cpuset_migrate_mm(mm, &cs->old_mems_allowed, &newmems);
1744 else
1745 mmput(mm);
1746 }
1747 css_task_iter_end(&it);
1748
1749 /*
1750 * All the tasks' nodemasks have been updated, update
1751 * cs->old_mems_allowed.
1752 */
1753 cs->old_mems_allowed = newmems;
1754
1755 /* We're done rebinding vmas to this cpuset's new mems_allowed. */
1756 cpuset_being_rebound = NULL;
1757 }
1758
1759 /*
1760 * update_nodemasks_hier - Update effective nodemasks and tasks in the subtree
1761 * @cs: the cpuset to consider
1762 * @new_mems: a temp variable for calculating new effective_mems
1763 *
1764 * When configured nodemask is changed, the effective nodemasks of this cpuset
1765 * and all its descendants need to be updated.
1766 *
1767 * On legacy hiearchy, effective_mems will be the same with mems_allowed.
1768 *
1769 * Called with cpuset_mutex held
1770 */
update_nodemasks_hier(struct cpuset * cs,nodemask_t * new_mems)1771 static void update_nodemasks_hier(struct cpuset *cs, nodemask_t *new_mems)
1772 {
1773 struct cpuset *cp;
1774 struct cgroup_subsys_state *pos_css;
1775
1776 rcu_read_lock();
1777 cpuset_for_each_descendant_pre(cp, pos_css, cs) {
1778 struct cpuset *parent = parent_cs(cp);
1779
1780 nodes_and(*new_mems, cp->mems_allowed, parent->effective_mems);
1781
1782 /*
1783 * If it becomes empty, inherit the effective mask of the
1784 * parent, which is guaranteed to have some MEMs.
1785 */
1786 if (is_in_v2_mode() && nodes_empty(*new_mems))
1787 *new_mems = parent->effective_mems;
1788
1789 /* Skip the whole subtree if the nodemask remains the same. */
1790 if (nodes_equal(*new_mems, cp->effective_mems)) {
1791 pos_css = css_rightmost_descendant(pos_css);
1792 continue;
1793 }
1794
1795 if (!css_tryget_online(&cp->css))
1796 continue;
1797 rcu_read_unlock();
1798
1799 spin_lock_irq(&callback_lock);
1800 cp->effective_mems = *new_mems;
1801 spin_unlock_irq(&callback_lock);
1802
1803 WARN_ON(!is_in_v2_mode() &&
1804 !nodes_equal(cp->mems_allowed, cp->effective_mems));
1805
1806 update_tasks_nodemask(cp);
1807
1808 rcu_read_lock();
1809 css_put(&cp->css);
1810 }
1811 rcu_read_unlock();
1812 }
1813
1814 /*
1815 * Handle user request to change the 'mems' memory placement
1816 * of a cpuset. Needs to validate the request, update the
1817 * cpusets mems_allowed, and for each task in the cpuset,
1818 * update mems_allowed and rebind task's mempolicy and any vma
1819 * mempolicies and if the cpuset is marked 'memory_migrate',
1820 * migrate the tasks pages to the new memory.
1821 *
1822 * Call with cpuset_mutex held. May take callback_lock during call.
1823 * Will take tasklist_lock, scan tasklist for tasks in cpuset cs,
1824 * lock each such tasks mm->mmap_lock, scan its vma's and rebind
1825 * their mempolicies to the cpusets new mems_allowed.
1826 */
update_nodemask(struct cpuset * cs,struct cpuset * trialcs,const char * buf)1827 static int update_nodemask(struct cpuset *cs, struct cpuset *trialcs,
1828 const char *buf)
1829 {
1830 int retval;
1831
1832 /*
1833 * top_cpuset.mems_allowed tracks node_stats[N_MEMORY];
1834 * it's read-only
1835 */
1836 if (cs == &top_cpuset) {
1837 retval = -EACCES;
1838 goto done;
1839 }
1840
1841 /*
1842 * An empty mems_allowed is ok iff there are no tasks in the cpuset.
1843 * Since nodelist_parse() fails on an empty mask, we special case
1844 * that parsing. The validate_change() call ensures that cpusets
1845 * with tasks have memory.
1846 */
1847 if (!*buf) {
1848 nodes_clear(trialcs->mems_allowed);
1849 } else {
1850 retval = nodelist_parse(buf, trialcs->mems_allowed);
1851 if (retval < 0)
1852 goto done;
1853
1854 if (!nodes_subset(trialcs->mems_allowed,
1855 top_cpuset.mems_allowed)) {
1856 retval = -EINVAL;
1857 goto done;
1858 }
1859 }
1860
1861 if (nodes_equal(cs->mems_allowed, trialcs->mems_allowed)) {
1862 retval = 0; /* Too easy - nothing to do */
1863 goto done;
1864 }
1865 retval = validate_change(cs, trialcs);
1866 if (retval < 0)
1867 goto done;
1868
1869 spin_lock_irq(&callback_lock);
1870 cs->mems_allowed = trialcs->mems_allowed;
1871 spin_unlock_irq(&callback_lock);
1872
1873 /* use trialcs->mems_allowed as a temp variable */
1874 update_nodemasks_hier(cs, &trialcs->mems_allowed);
1875 done:
1876 return retval;
1877 }
1878
current_cpuset_is_being_rebound(void)1879 bool current_cpuset_is_being_rebound(void)
1880 {
1881 bool ret;
1882
1883 rcu_read_lock();
1884 ret = task_cs(current) == cpuset_being_rebound;
1885 rcu_read_unlock();
1886
1887 return ret;
1888 }
1889
update_relax_domain_level(struct cpuset * cs,s64 val)1890 static int update_relax_domain_level(struct cpuset *cs, s64 val)
1891 {
1892 #ifdef CONFIG_SMP
1893 if (val < -1 || val >= sched_domain_level_max)
1894 return -EINVAL;
1895 #endif
1896
1897 if (val != cs->relax_domain_level) {
1898 cs->relax_domain_level = val;
1899 if (!cpumask_empty(cs->cpus_allowed) &&
1900 is_sched_load_balance(cs))
1901 rebuild_sched_domains_locked();
1902 }
1903
1904 return 0;
1905 }
1906
1907 /**
1908 * update_tasks_flags - update the spread flags of tasks in the cpuset.
1909 * @cs: the cpuset in which each task's spread flags needs to be changed
1910 *
1911 * Iterate through each task of @cs updating its spread flags. As this
1912 * function is called with cpuset_mutex held, cpuset membership stays
1913 * stable.
1914 */
update_tasks_flags(struct cpuset * cs)1915 static void update_tasks_flags(struct cpuset *cs)
1916 {
1917 struct css_task_iter it;
1918 struct task_struct *task;
1919
1920 css_task_iter_start(&cs->css, 0, &it);
1921 while ((task = css_task_iter_next(&it)))
1922 cpuset_update_task_spread_flag(cs, task);
1923 css_task_iter_end(&it);
1924 }
1925
1926 /*
1927 * update_flag - read a 0 or a 1 in a file and update associated flag
1928 * bit: the bit to update (see cpuset_flagbits_t)
1929 * cs: the cpuset to update
1930 * turning_on: whether the flag is being set or cleared
1931 *
1932 * Call with cpuset_mutex held.
1933 */
1934
update_flag(cpuset_flagbits_t bit,struct cpuset * cs,int turning_on)1935 static int update_flag(cpuset_flagbits_t bit, struct cpuset *cs,
1936 int turning_on)
1937 {
1938 struct cpuset *trialcs;
1939 int balance_flag_changed;
1940 int spread_flag_changed;
1941 int err;
1942
1943 trialcs = alloc_trial_cpuset(cs);
1944 if (!trialcs)
1945 return -ENOMEM;
1946
1947 if (turning_on)
1948 set_bit(bit, &trialcs->flags);
1949 else
1950 clear_bit(bit, &trialcs->flags);
1951
1952 err = validate_change(cs, trialcs);
1953 if (err < 0)
1954 goto out;
1955
1956 balance_flag_changed = (is_sched_load_balance(cs) !=
1957 is_sched_load_balance(trialcs));
1958
1959 spread_flag_changed = ((is_spread_slab(cs) != is_spread_slab(trialcs))
1960 || (is_spread_page(cs) != is_spread_page(trialcs)));
1961
1962 spin_lock_irq(&callback_lock);
1963 cs->flags = trialcs->flags;
1964 spin_unlock_irq(&callback_lock);
1965
1966 if (!cpumask_empty(trialcs->cpus_allowed) && balance_flag_changed)
1967 rebuild_sched_domains_locked();
1968
1969 if (spread_flag_changed)
1970 update_tasks_flags(cs);
1971 out:
1972 free_cpuset(trialcs);
1973 return err;
1974 }
1975
1976 /*
1977 * update_prstate - update partititon_root_state
1978 * cs: the cpuset to update
1979 * new_prs: new partition root state
1980 *
1981 * Call with cpuset_mutex held.
1982 */
update_prstate(struct cpuset * cs,int new_prs)1983 static int update_prstate(struct cpuset *cs, int new_prs)
1984 {
1985 int err, old_prs = cs->partition_root_state;
1986 struct cpuset *parent = parent_cs(cs);
1987 struct tmpmasks tmpmask;
1988
1989 if (old_prs == new_prs)
1990 return 0;
1991
1992 /*
1993 * Cannot force a partial or invalid partition root to a full
1994 * partition root.
1995 */
1996 if (new_prs && (old_prs == PRS_ERROR))
1997 return -EINVAL;
1998
1999 if (alloc_cpumasks(NULL, &tmpmask))
2000 return -ENOMEM;
2001
2002 err = -EINVAL;
2003 if (!old_prs) {
2004 /*
2005 * Turning on partition root requires setting the
2006 * CS_CPU_EXCLUSIVE bit implicitly as well and cpus_allowed
2007 * cannot be NULL.
2008 */
2009 if (cpumask_empty(cs->cpus_allowed))
2010 goto out;
2011
2012 err = update_flag(CS_CPU_EXCLUSIVE, cs, 1);
2013 if (err)
2014 goto out;
2015
2016 err = update_parent_subparts_cpumask(cs, partcmd_enable,
2017 NULL, &tmpmask);
2018 if (err) {
2019 update_flag(CS_CPU_EXCLUSIVE, cs, 0);
2020 goto out;
2021 }
2022 } else {
2023 /*
2024 * Turning off partition root will clear the
2025 * CS_CPU_EXCLUSIVE bit.
2026 */
2027 if (old_prs == PRS_ERROR) {
2028 update_flag(CS_CPU_EXCLUSIVE, cs, 0);
2029 err = 0;
2030 goto out;
2031 }
2032
2033 err = update_parent_subparts_cpumask(cs, partcmd_disable,
2034 NULL, &tmpmask);
2035 if (err)
2036 goto out;
2037
2038 /* Turning off CS_CPU_EXCLUSIVE will not return error */
2039 update_flag(CS_CPU_EXCLUSIVE, cs, 0);
2040 }
2041
2042 update_tasks_cpumask(parent);
2043
2044 if (parent->child_ecpus_count)
2045 update_sibling_cpumasks(parent, cs, &tmpmask);
2046
2047 rebuild_sched_domains_locked();
2048 out:
2049 if (!err) {
2050 spin_lock_irq(&callback_lock);
2051 cs->partition_root_state = new_prs;
2052 spin_unlock_irq(&callback_lock);
2053 }
2054
2055 free_cpumasks(NULL, &tmpmask);
2056 return err;
2057 }
2058
2059 /*
2060 * Frequency meter - How fast is some event occurring?
2061 *
2062 * These routines manage a digitally filtered, constant time based,
2063 * event frequency meter. There are four routines:
2064 * fmeter_init() - initialize a frequency meter.
2065 * fmeter_markevent() - called each time the event happens.
2066 * fmeter_getrate() - returns the recent rate of such events.
2067 * fmeter_update() - internal routine used to update fmeter.
2068 *
2069 * A common data structure is passed to each of these routines,
2070 * which is used to keep track of the state required to manage the
2071 * frequency meter and its digital filter.
2072 *
2073 * The filter works on the number of events marked per unit time.
2074 * The filter is single-pole low-pass recursive (IIR). The time unit
2075 * is 1 second. Arithmetic is done using 32-bit integers scaled to
2076 * simulate 3 decimal digits of precision (multiplied by 1000).
2077 *
2078 * With an FM_COEF of 933, and a time base of 1 second, the filter
2079 * has a half-life of 10 seconds, meaning that if the events quit
2080 * happening, then the rate returned from the fmeter_getrate()
2081 * will be cut in half each 10 seconds, until it converges to zero.
2082 *
2083 * It is not worth doing a real infinitely recursive filter. If more
2084 * than FM_MAXTICKS ticks have elapsed since the last filter event,
2085 * just compute FM_MAXTICKS ticks worth, by which point the level
2086 * will be stable.
2087 *
2088 * Limit the count of unprocessed events to FM_MAXCNT, so as to avoid
2089 * arithmetic overflow in the fmeter_update() routine.
2090 *
2091 * Given the simple 32 bit integer arithmetic used, this meter works
2092 * best for reporting rates between one per millisecond (msec) and
2093 * one per 32 (approx) seconds. At constant rates faster than one
2094 * per msec it maxes out at values just under 1,000,000. At constant
2095 * rates between one per msec, and one per second it will stabilize
2096 * to a value N*1000, where N is the rate of events per second.
2097 * At constant rates between one per second and one per 32 seconds,
2098 * it will be choppy, moving up on the seconds that have an event,
2099 * and then decaying until the next event. At rates slower than
2100 * about one in 32 seconds, it decays all the way back to zero between
2101 * each event.
2102 */
2103
2104 #define FM_COEF 933 /* coefficient for half-life of 10 secs */
2105 #define FM_MAXTICKS ((u32)99) /* useless computing more ticks than this */
2106 #define FM_MAXCNT 1000000 /* limit cnt to avoid overflow */
2107 #define FM_SCALE 1000 /* faux fixed point scale */
2108
2109 /* Initialize a frequency meter */
fmeter_init(struct fmeter * fmp)2110 static void fmeter_init(struct fmeter *fmp)
2111 {
2112 fmp->cnt = 0;
2113 fmp->val = 0;
2114 fmp->time = 0;
2115 spin_lock_init(&fmp->lock);
2116 }
2117
2118 /* Internal meter update - process cnt events and update value */
fmeter_update(struct fmeter * fmp)2119 static void fmeter_update(struct fmeter *fmp)
2120 {
2121 time64_t now;
2122 u32 ticks;
2123
2124 now = ktime_get_seconds();
2125 ticks = now - fmp->time;
2126
2127 if (ticks == 0)
2128 return;
2129
2130 ticks = min(FM_MAXTICKS, ticks);
2131 while (ticks-- > 0)
2132 fmp->val = (FM_COEF * fmp->val) / FM_SCALE;
2133 fmp->time = now;
2134
2135 fmp->val += ((FM_SCALE - FM_COEF) * fmp->cnt) / FM_SCALE;
2136 fmp->cnt = 0;
2137 }
2138
2139 /* Process any previous ticks, then bump cnt by one (times scale). */
fmeter_markevent(struct fmeter * fmp)2140 static void fmeter_markevent(struct fmeter *fmp)
2141 {
2142 spin_lock(&fmp->lock);
2143 fmeter_update(fmp);
2144 fmp->cnt = min(FM_MAXCNT, fmp->cnt + FM_SCALE);
2145 spin_unlock(&fmp->lock);
2146 }
2147
2148 /* Process any previous ticks, then return current value. */
fmeter_getrate(struct fmeter * fmp)2149 static int fmeter_getrate(struct fmeter *fmp)
2150 {
2151 int val;
2152
2153 spin_lock(&fmp->lock);
2154 fmeter_update(fmp);
2155 val = fmp->val;
2156 spin_unlock(&fmp->lock);
2157 return val;
2158 }
2159
2160 static struct cpuset *cpuset_attach_old_cs;
2161
2162 /* Called by cgroups to determine if a cpuset is usable; cpuset_mutex held */
cpuset_can_attach(struct cgroup_taskset * tset)2163 static int cpuset_can_attach(struct cgroup_taskset *tset)
2164 {
2165 struct cgroup_subsys_state *css;
2166 struct cpuset *cs;
2167 struct task_struct *task;
2168 int ret;
2169
2170 /* used later by cpuset_attach() */
2171 cpuset_attach_old_cs = task_cs(cgroup_taskset_first(tset, &css));
2172 cs = css_cs(css);
2173
2174 percpu_down_write(&cpuset_rwsem);
2175
2176 /* allow moving tasks into an empty cpuset if on default hierarchy */
2177 ret = -ENOSPC;
2178 if (!is_in_v2_mode() &&
2179 (cpumask_empty(cs->cpus_allowed) || nodes_empty(cs->mems_allowed)))
2180 goto out_unlock;
2181
2182 cgroup_taskset_for_each(task, css, tset) {
2183 ret = task_can_attach(task, cs->effective_cpus);
2184 if (ret)
2185 goto out_unlock;
2186 ret = security_task_setscheduler(task);
2187 if (ret)
2188 goto out_unlock;
2189 }
2190
2191 /*
2192 * Mark attach is in progress. This makes validate_change() fail
2193 * changes which zero cpus/mems_allowed.
2194 */
2195 cs->attach_in_progress++;
2196 ret = 0;
2197 out_unlock:
2198 percpu_up_write(&cpuset_rwsem);
2199 return ret;
2200 }
2201
cpuset_cancel_attach(struct cgroup_taskset * tset)2202 static void cpuset_cancel_attach(struct cgroup_taskset *tset)
2203 {
2204 struct cgroup_subsys_state *css;
2205
2206 cgroup_taskset_first(tset, &css);
2207
2208 percpu_down_write(&cpuset_rwsem);
2209 css_cs(css)->attach_in_progress--;
2210 percpu_up_write(&cpuset_rwsem);
2211 }
2212
2213 /*
2214 * Protected by cpuset_mutex. cpus_attach is used only by cpuset_attach()
2215 * but we can't allocate it dynamically there. Define it global and
2216 * allocate from cpuset_init().
2217 */
2218 static cpumask_var_t cpus_attach;
2219
cpuset_attach(struct cgroup_taskset * tset)2220 static void cpuset_attach(struct cgroup_taskset *tset)
2221 {
2222 /* static buf protected by cpuset_mutex */
2223 static nodemask_t cpuset_attach_nodemask_to;
2224 struct task_struct *task;
2225 struct task_struct *leader;
2226 struct cgroup_subsys_state *css;
2227 struct cpuset *cs;
2228 struct cpuset *oldcs = cpuset_attach_old_cs;
2229
2230 cgroup_taskset_first(tset, &css);
2231 cs = css_cs(css);
2232
2233 lockdep_assert_cpus_held(); /* see cgroup_attach_lock() */
2234 percpu_down_write(&cpuset_rwsem);
2235
2236 /* prepare for attach */
2237 if (cs == &top_cpuset)
2238 cpumask_copy(cpus_attach, cpu_possible_mask);
2239 else
2240 guarantee_online_cpus(cs, cpus_attach);
2241
2242 guarantee_online_mems(cs, &cpuset_attach_nodemask_to);
2243
2244 cgroup_taskset_for_each(task, css, tset) {
2245 /*
2246 * can_attach beforehand should guarantee that this doesn't
2247 * fail. TODO: have a better way to handle failure here
2248 */
2249 WARN_ON_ONCE(set_cpus_allowed_ptr(task, cpus_attach));
2250
2251 cpuset_change_task_nodemask(task, &cpuset_attach_nodemask_to);
2252 cpuset_update_task_spread_flag(cs, task);
2253 }
2254
2255 /*
2256 * Change mm for all threadgroup leaders. This is expensive and may
2257 * sleep and should be moved outside migration path proper.
2258 */
2259 cpuset_attach_nodemask_to = cs->effective_mems;
2260 cgroup_taskset_for_each_leader(leader, css, tset) {
2261 struct mm_struct *mm = get_task_mm(leader);
2262
2263 if (mm) {
2264 mpol_rebind_mm(mm, &cpuset_attach_nodemask_to);
2265
2266 /*
2267 * old_mems_allowed is the same with mems_allowed
2268 * here, except if this task is being moved
2269 * automatically due to hotplug. In that case
2270 * @mems_allowed has been updated and is empty, so
2271 * @old_mems_allowed is the right nodesets that we
2272 * migrate mm from.
2273 */
2274 if (is_memory_migrate(cs))
2275 cpuset_migrate_mm(mm, &oldcs->old_mems_allowed,
2276 &cpuset_attach_nodemask_to);
2277 else
2278 mmput(mm);
2279 }
2280 }
2281
2282 cs->old_mems_allowed = cpuset_attach_nodemask_to;
2283
2284 cs->attach_in_progress--;
2285 if (!cs->attach_in_progress)
2286 wake_up(&cpuset_attach_wq);
2287
2288 percpu_up_write(&cpuset_rwsem);
2289 }
2290
2291 /* The various types of files and directories in a cpuset file system */
2292
2293 typedef enum {
2294 FILE_MEMORY_MIGRATE,
2295 FILE_CPULIST,
2296 FILE_MEMLIST,
2297 FILE_EFFECTIVE_CPULIST,
2298 FILE_EFFECTIVE_MEMLIST,
2299 FILE_SUBPARTS_CPULIST,
2300 FILE_CPU_EXCLUSIVE,
2301 FILE_MEM_EXCLUSIVE,
2302 FILE_MEM_HARDWALL,
2303 FILE_SCHED_LOAD_BALANCE,
2304 FILE_PARTITION_ROOT,
2305 FILE_SCHED_RELAX_DOMAIN_LEVEL,
2306 FILE_MEMORY_PRESSURE_ENABLED,
2307 FILE_MEMORY_PRESSURE,
2308 FILE_SPREAD_PAGE,
2309 FILE_SPREAD_SLAB,
2310 } cpuset_filetype_t;
2311
cpuset_write_u64(struct cgroup_subsys_state * css,struct cftype * cft,u64 val)2312 static int cpuset_write_u64(struct cgroup_subsys_state *css, struct cftype *cft,
2313 u64 val)
2314 {
2315 struct cpuset *cs = css_cs(css);
2316 cpuset_filetype_t type = cft->private;
2317 int retval = 0;
2318
2319 get_online_cpus();
2320 percpu_down_write(&cpuset_rwsem);
2321 if (!is_cpuset_online(cs)) {
2322 retval = -ENODEV;
2323 goto out_unlock;
2324 }
2325
2326 switch (type) {
2327 case FILE_CPU_EXCLUSIVE:
2328 retval = update_flag(CS_CPU_EXCLUSIVE, cs, val);
2329 break;
2330 case FILE_MEM_EXCLUSIVE:
2331 retval = update_flag(CS_MEM_EXCLUSIVE, cs, val);
2332 break;
2333 case FILE_MEM_HARDWALL:
2334 retval = update_flag(CS_MEM_HARDWALL, cs, val);
2335 break;
2336 case FILE_SCHED_LOAD_BALANCE:
2337 retval = update_flag(CS_SCHED_LOAD_BALANCE, cs, val);
2338 break;
2339 case FILE_MEMORY_MIGRATE:
2340 retval = update_flag(CS_MEMORY_MIGRATE, cs, val);
2341 break;
2342 case FILE_MEMORY_PRESSURE_ENABLED:
2343 cpuset_memory_pressure_enabled = !!val;
2344 break;
2345 case FILE_SPREAD_PAGE:
2346 retval = update_flag(CS_SPREAD_PAGE, cs, val);
2347 break;
2348 case FILE_SPREAD_SLAB:
2349 retval = update_flag(CS_SPREAD_SLAB, cs, val);
2350 break;
2351 default:
2352 retval = -EINVAL;
2353 break;
2354 }
2355 out_unlock:
2356 percpu_up_write(&cpuset_rwsem);
2357 put_online_cpus();
2358 return retval;
2359 }
2360
cpuset_write_s64(struct cgroup_subsys_state * css,struct cftype * cft,s64 val)2361 static int cpuset_write_s64(struct cgroup_subsys_state *css, struct cftype *cft,
2362 s64 val)
2363 {
2364 struct cpuset *cs = css_cs(css);
2365 cpuset_filetype_t type = cft->private;
2366 int retval = -ENODEV;
2367
2368 get_online_cpus();
2369 percpu_down_write(&cpuset_rwsem);
2370 if (!is_cpuset_online(cs))
2371 goto out_unlock;
2372
2373 switch (type) {
2374 case FILE_SCHED_RELAX_DOMAIN_LEVEL:
2375 retval = update_relax_domain_level(cs, val);
2376 break;
2377 default:
2378 retval = -EINVAL;
2379 break;
2380 }
2381 out_unlock:
2382 percpu_up_write(&cpuset_rwsem);
2383 put_online_cpus();
2384 return retval;
2385 }
2386
2387 /*
2388 * Common handling for a write to a "cpus" or "mems" file.
2389 */
cpuset_write_resmask(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)2390 static ssize_t cpuset_write_resmask(struct kernfs_open_file *of,
2391 char *buf, size_t nbytes, loff_t off)
2392 {
2393 struct cpuset *cs = css_cs(of_css(of));
2394 struct cpuset *trialcs;
2395 int retval = -ENODEV;
2396
2397 buf = strstrip(buf);
2398
2399 /*
2400 * CPU or memory hotunplug may leave @cs w/o any execution
2401 * resources, in which case the hotplug code asynchronously updates
2402 * configuration and transfers all tasks to the nearest ancestor
2403 * which can execute.
2404 *
2405 * As writes to "cpus" or "mems" may restore @cs's execution
2406 * resources, wait for the previously scheduled operations before
2407 * proceeding, so that we don't end up keep removing tasks added
2408 * after execution capability is restored.
2409 *
2410 * cpuset_hotplug_work calls back into cgroup core via
2411 * cgroup_transfer_tasks() and waiting for it from a cgroupfs
2412 * operation like this one can lead to a deadlock through kernfs
2413 * active_ref protection. Let's break the protection. Losing the
2414 * protection is okay as we check whether @cs is online after
2415 * grabbing cpuset_mutex anyway. This only happens on the legacy
2416 * hierarchies.
2417 */
2418 css_get(&cs->css);
2419 kernfs_break_active_protection(of->kn);
2420 flush_work(&cpuset_hotplug_work);
2421
2422 get_online_cpus();
2423 percpu_down_write(&cpuset_rwsem);
2424 if (!is_cpuset_online(cs))
2425 goto out_unlock;
2426
2427 trialcs = alloc_trial_cpuset(cs);
2428 if (!trialcs) {
2429 retval = -ENOMEM;
2430 goto out_unlock;
2431 }
2432
2433 switch (of_cft(of)->private) {
2434 case FILE_CPULIST:
2435 retval = update_cpumask(cs, trialcs, buf);
2436 break;
2437 case FILE_MEMLIST:
2438 retval = update_nodemask(cs, trialcs, buf);
2439 break;
2440 default:
2441 retval = -EINVAL;
2442 break;
2443 }
2444
2445 free_cpuset(trialcs);
2446 out_unlock:
2447 percpu_up_write(&cpuset_rwsem);
2448 put_online_cpus();
2449 kernfs_unbreak_active_protection(of->kn);
2450 css_put(&cs->css);
2451 flush_workqueue(cpuset_migrate_mm_wq);
2452 return retval ?: nbytes;
2453 }
2454
2455 /*
2456 * These ascii lists should be read in a single call, by using a user
2457 * buffer large enough to hold the entire map. If read in smaller
2458 * chunks, there is no guarantee of atomicity. Since the display format
2459 * used, list of ranges of sequential numbers, is variable length,
2460 * and since these maps can change value dynamically, one could read
2461 * gibberish by doing partial reads while a list was changing.
2462 */
cpuset_common_seq_show(struct seq_file * sf,void * v)2463 static int cpuset_common_seq_show(struct seq_file *sf, void *v)
2464 {
2465 struct cpuset *cs = css_cs(seq_css(sf));
2466 cpuset_filetype_t type = seq_cft(sf)->private;
2467 int ret = 0;
2468
2469 spin_lock_irq(&callback_lock);
2470
2471 switch (type) {
2472 case FILE_CPULIST:
2473 seq_printf(sf, "%*pbl\n", cpumask_pr_args(cs->cpus_requested));
2474 break;
2475 case FILE_MEMLIST:
2476 seq_printf(sf, "%*pbl\n", nodemask_pr_args(&cs->mems_allowed));
2477 break;
2478 case FILE_EFFECTIVE_CPULIST:
2479 seq_printf(sf, "%*pbl\n", cpumask_pr_args(cs->effective_cpus));
2480 break;
2481 case FILE_EFFECTIVE_MEMLIST:
2482 seq_printf(sf, "%*pbl\n", nodemask_pr_args(&cs->effective_mems));
2483 break;
2484 case FILE_SUBPARTS_CPULIST:
2485 seq_printf(sf, "%*pbl\n", cpumask_pr_args(cs->subparts_cpus));
2486 break;
2487 default:
2488 ret = -EINVAL;
2489 }
2490
2491 spin_unlock_irq(&callback_lock);
2492 return ret;
2493 }
2494
cpuset_read_u64(struct cgroup_subsys_state * css,struct cftype * cft)2495 static u64 cpuset_read_u64(struct cgroup_subsys_state *css, struct cftype *cft)
2496 {
2497 struct cpuset *cs = css_cs(css);
2498 cpuset_filetype_t type = cft->private;
2499 switch (type) {
2500 case FILE_CPU_EXCLUSIVE:
2501 return is_cpu_exclusive(cs);
2502 case FILE_MEM_EXCLUSIVE:
2503 return is_mem_exclusive(cs);
2504 case FILE_MEM_HARDWALL:
2505 return is_mem_hardwall(cs);
2506 case FILE_SCHED_LOAD_BALANCE:
2507 return is_sched_load_balance(cs);
2508 case FILE_MEMORY_MIGRATE:
2509 return is_memory_migrate(cs);
2510 case FILE_MEMORY_PRESSURE_ENABLED:
2511 return cpuset_memory_pressure_enabled;
2512 case FILE_MEMORY_PRESSURE:
2513 return fmeter_getrate(&cs->fmeter);
2514 case FILE_SPREAD_PAGE:
2515 return is_spread_page(cs);
2516 case FILE_SPREAD_SLAB:
2517 return is_spread_slab(cs);
2518 default:
2519 BUG();
2520 }
2521
2522 /* Unreachable but makes gcc happy */
2523 return 0;
2524 }
2525
cpuset_read_s64(struct cgroup_subsys_state * css,struct cftype * cft)2526 static s64 cpuset_read_s64(struct cgroup_subsys_state *css, struct cftype *cft)
2527 {
2528 struct cpuset *cs = css_cs(css);
2529 cpuset_filetype_t type = cft->private;
2530 switch (type) {
2531 case FILE_SCHED_RELAX_DOMAIN_LEVEL:
2532 return cs->relax_domain_level;
2533 default:
2534 BUG();
2535 }
2536
2537 /* Unrechable but makes gcc happy */
2538 return 0;
2539 }
2540
sched_partition_show(struct seq_file * seq,void * v)2541 static int sched_partition_show(struct seq_file *seq, void *v)
2542 {
2543 struct cpuset *cs = css_cs(seq_css(seq));
2544
2545 switch (cs->partition_root_state) {
2546 case PRS_ENABLED:
2547 seq_puts(seq, "root\n");
2548 break;
2549 case PRS_DISABLED:
2550 seq_puts(seq, "member\n");
2551 break;
2552 case PRS_ERROR:
2553 seq_puts(seq, "root invalid\n");
2554 break;
2555 }
2556 return 0;
2557 }
2558
sched_partition_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)2559 static ssize_t sched_partition_write(struct kernfs_open_file *of, char *buf,
2560 size_t nbytes, loff_t off)
2561 {
2562 struct cpuset *cs = css_cs(of_css(of));
2563 int val;
2564 int retval = -ENODEV;
2565
2566 buf = strstrip(buf);
2567
2568 /*
2569 * Convert "root" to ENABLED, and convert "member" to DISABLED.
2570 */
2571 if (!strcmp(buf, "root"))
2572 val = PRS_ENABLED;
2573 else if (!strcmp(buf, "member"))
2574 val = PRS_DISABLED;
2575 else
2576 return -EINVAL;
2577
2578 css_get(&cs->css);
2579 get_online_cpus();
2580 percpu_down_write(&cpuset_rwsem);
2581 if (!is_cpuset_online(cs))
2582 goto out_unlock;
2583
2584 retval = update_prstate(cs, val);
2585 out_unlock:
2586 percpu_up_write(&cpuset_rwsem);
2587 put_online_cpus();
2588 css_put(&cs->css);
2589 return retval ?: nbytes;
2590 }
2591
2592 /*
2593 * for the common functions, 'private' gives the type of file
2594 */
2595
2596 static struct cftype legacy_files[] = {
2597 {
2598 .name = "cpus",
2599 .seq_show = cpuset_common_seq_show,
2600 .write = cpuset_write_resmask,
2601 .max_write_len = (100U + 6 * NR_CPUS),
2602 .private = FILE_CPULIST,
2603 },
2604
2605 {
2606 .name = "mems",
2607 .seq_show = cpuset_common_seq_show,
2608 .write = cpuset_write_resmask,
2609 .max_write_len = (100U + 6 * MAX_NUMNODES),
2610 .private = FILE_MEMLIST,
2611 },
2612
2613 {
2614 .name = "effective_cpus",
2615 .seq_show = cpuset_common_seq_show,
2616 .private = FILE_EFFECTIVE_CPULIST,
2617 },
2618
2619 {
2620 .name = "effective_mems",
2621 .seq_show = cpuset_common_seq_show,
2622 .private = FILE_EFFECTIVE_MEMLIST,
2623 },
2624
2625 {
2626 .name = "cpu_exclusive",
2627 .read_u64 = cpuset_read_u64,
2628 .write_u64 = cpuset_write_u64,
2629 .private = FILE_CPU_EXCLUSIVE,
2630 },
2631
2632 {
2633 .name = "mem_exclusive",
2634 .read_u64 = cpuset_read_u64,
2635 .write_u64 = cpuset_write_u64,
2636 .private = FILE_MEM_EXCLUSIVE,
2637 },
2638
2639 {
2640 .name = "mem_hardwall",
2641 .read_u64 = cpuset_read_u64,
2642 .write_u64 = cpuset_write_u64,
2643 .private = FILE_MEM_HARDWALL,
2644 },
2645
2646 {
2647 .name = "sched_load_balance",
2648 .read_u64 = cpuset_read_u64,
2649 .write_u64 = cpuset_write_u64,
2650 .private = FILE_SCHED_LOAD_BALANCE,
2651 },
2652
2653 {
2654 .name = "sched_relax_domain_level",
2655 .read_s64 = cpuset_read_s64,
2656 .write_s64 = cpuset_write_s64,
2657 .private = FILE_SCHED_RELAX_DOMAIN_LEVEL,
2658 },
2659
2660 {
2661 .name = "memory_migrate",
2662 .read_u64 = cpuset_read_u64,
2663 .write_u64 = cpuset_write_u64,
2664 .private = FILE_MEMORY_MIGRATE,
2665 },
2666
2667 {
2668 .name = "memory_pressure",
2669 .read_u64 = cpuset_read_u64,
2670 .private = FILE_MEMORY_PRESSURE,
2671 },
2672
2673 {
2674 .name = "memory_spread_page",
2675 .read_u64 = cpuset_read_u64,
2676 .write_u64 = cpuset_write_u64,
2677 .private = FILE_SPREAD_PAGE,
2678 },
2679
2680 {
2681 .name = "memory_spread_slab",
2682 .read_u64 = cpuset_read_u64,
2683 .write_u64 = cpuset_write_u64,
2684 .private = FILE_SPREAD_SLAB,
2685 },
2686
2687 {
2688 .name = "memory_pressure_enabled",
2689 .flags = CFTYPE_ONLY_ON_ROOT,
2690 .read_u64 = cpuset_read_u64,
2691 .write_u64 = cpuset_write_u64,
2692 .private = FILE_MEMORY_PRESSURE_ENABLED,
2693 },
2694
2695 { } /* terminate */
2696 };
2697
2698 /*
2699 * This is currently a minimal set for the default hierarchy. It can be
2700 * expanded later on by migrating more features and control files from v1.
2701 */
2702 static struct cftype dfl_files[] = {
2703 {
2704 .name = "cpus",
2705 .seq_show = cpuset_common_seq_show,
2706 .write = cpuset_write_resmask,
2707 .max_write_len = (100U + 6 * NR_CPUS),
2708 .private = FILE_CPULIST,
2709 .flags = CFTYPE_NOT_ON_ROOT,
2710 },
2711
2712 {
2713 .name = "mems",
2714 .seq_show = cpuset_common_seq_show,
2715 .write = cpuset_write_resmask,
2716 .max_write_len = (100U + 6 * MAX_NUMNODES),
2717 .private = FILE_MEMLIST,
2718 .flags = CFTYPE_NOT_ON_ROOT,
2719 },
2720
2721 {
2722 .name = "cpus.effective",
2723 .seq_show = cpuset_common_seq_show,
2724 .private = FILE_EFFECTIVE_CPULIST,
2725 },
2726
2727 {
2728 .name = "mems.effective",
2729 .seq_show = cpuset_common_seq_show,
2730 .private = FILE_EFFECTIVE_MEMLIST,
2731 },
2732
2733 {
2734 .name = "cpus.partition",
2735 .seq_show = sched_partition_show,
2736 .write = sched_partition_write,
2737 .private = FILE_PARTITION_ROOT,
2738 .flags = CFTYPE_NOT_ON_ROOT,
2739 },
2740
2741 {
2742 .name = "cpus.subpartitions",
2743 .seq_show = cpuset_common_seq_show,
2744 .private = FILE_SUBPARTS_CPULIST,
2745 .flags = CFTYPE_DEBUG,
2746 },
2747
2748 { } /* terminate */
2749 };
2750
2751
2752 /*
2753 * cpuset_css_alloc - allocate a cpuset css
2754 * cgrp: control group that the new cpuset will be part of
2755 */
2756
2757 static struct cgroup_subsys_state *
cpuset_css_alloc(struct cgroup_subsys_state * parent_css)2758 cpuset_css_alloc(struct cgroup_subsys_state *parent_css)
2759 {
2760 struct cpuset *cs;
2761
2762 if (!parent_css)
2763 return &top_cpuset.css;
2764
2765 cs = kzalloc(sizeof(*cs), GFP_KERNEL);
2766 if (!cs)
2767 return ERR_PTR(-ENOMEM);
2768
2769 if (alloc_cpumasks(cs, NULL)) {
2770 kfree(cs);
2771 return ERR_PTR(-ENOMEM);
2772 }
2773
2774 set_bit(CS_SCHED_LOAD_BALANCE, &cs->flags);
2775 nodes_clear(cs->mems_allowed);
2776 nodes_clear(cs->effective_mems);
2777 fmeter_init(&cs->fmeter);
2778 cs->relax_domain_level = -1;
2779
2780 return &cs->css;
2781 }
2782
cpuset_css_online(struct cgroup_subsys_state * css)2783 static int cpuset_css_online(struct cgroup_subsys_state *css)
2784 {
2785 struct cpuset *cs = css_cs(css);
2786 struct cpuset *parent = parent_cs(cs);
2787 struct cpuset *tmp_cs;
2788 struct cgroup_subsys_state *pos_css;
2789
2790 if (!parent)
2791 return 0;
2792
2793 get_online_cpus();
2794 percpu_down_write(&cpuset_rwsem);
2795
2796 set_bit(CS_ONLINE, &cs->flags);
2797 if (is_spread_page(parent))
2798 set_bit(CS_SPREAD_PAGE, &cs->flags);
2799 if (is_spread_slab(parent))
2800 set_bit(CS_SPREAD_SLAB, &cs->flags);
2801
2802 cpuset_inc();
2803
2804 spin_lock_irq(&callback_lock);
2805 if (is_in_v2_mode()) {
2806 cpumask_copy(cs->effective_cpus, parent->effective_cpus);
2807 cs->effective_mems = parent->effective_mems;
2808 cs->use_parent_ecpus = true;
2809 parent->child_ecpus_count++;
2810 }
2811 spin_unlock_irq(&callback_lock);
2812
2813 if (!test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags))
2814 goto out_unlock;
2815
2816 /*
2817 * Clone @parent's configuration if CGRP_CPUSET_CLONE_CHILDREN is
2818 * set. This flag handling is implemented in cgroup core for
2819 * histrical reasons - the flag may be specified during mount.
2820 *
2821 * Currently, if any sibling cpusets have exclusive cpus or mem, we
2822 * refuse to clone the configuration - thereby refusing the task to
2823 * be entered, and as a result refusing the sys_unshare() or
2824 * clone() which initiated it. If this becomes a problem for some
2825 * users who wish to allow that scenario, then this could be
2826 * changed to grant parent->cpus_allowed-sibling_cpus_exclusive
2827 * (and likewise for mems) to the new cgroup.
2828 */
2829 rcu_read_lock();
2830 cpuset_for_each_child(tmp_cs, pos_css, parent) {
2831 if (is_mem_exclusive(tmp_cs) || is_cpu_exclusive(tmp_cs)) {
2832 rcu_read_unlock();
2833 goto out_unlock;
2834 }
2835 }
2836 rcu_read_unlock();
2837
2838 spin_lock_irq(&callback_lock);
2839 cs->mems_allowed = parent->mems_allowed;
2840 cs->effective_mems = parent->mems_allowed;
2841 cpumask_copy(cs->cpus_allowed, parent->cpus_allowed);
2842 cpumask_copy(cs->cpus_requested, parent->cpus_requested);
2843 cpumask_copy(cs->effective_cpus, parent->cpus_allowed);
2844 spin_unlock_irq(&callback_lock);
2845 out_unlock:
2846 percpu_up_write(&cpuset_rwsem);
2847 put_online_cpus();
2848 return 0;
2849 }
2850
2851 /*
2852 * If the cpuset being removed has its flag 'sched_load_balance'
2853 * enabled, then simulate turning sched_load_balance off, which
2854 * will call rebuild_sched_domains_locked(). That is not needed
2855 * in the default hierarchy where only changes in partition
2856 * will cause repartitioning.
2857 *
2858 * If the cpuset has the 'sched.partition' flag enabled, simulate
2859 * turning 'sched.partition" off.
2860 */
2861
cpuset_css_offline(struct cgroup_subsys_state * css)2862 static void cpuset_css_offline(struct cgroup_subsys_state *css)
2863 {
2864 struct cpuset *cs = css_cs(css);
2865
2866 get_online_cpus();
2867 percpu_down_write(&cpuset_rwsem);
2868
2869 if (is_partition_root(cs))
2870 update_prstate(cs, 0);
2871
2872 if (!cgroup_subsys_on_dfl(cpuset_cgrp_subsys) &&
2873 is_sched_load_balance(cs))
2874 update_flag(CS_SCHED_LOAD_BALANCE, cs, 0);
2875
2876 if (cs->use_parent_ecpus) {
2877 struct cpuset *parent = parent_cs(cs);
2878
2879 cs->use_parent_ecpus = false;
2880 parent->child_ecpus_count--;
2881 }
2882
2883 cpuset_dec();
2884 clear_bit(CS_ONLINE, &cs->flags);
2885
2886 percpu_up_write(&cpuset_rwsem);
2887 put_online_cpus();
2888 }
2889
cpuset_css_free(struct cgroup_subsys_state * css)2890 static void cpuset_css_free(struct cgroup_subsys_state *css)
2891 {
2892 struct cpuset *cs = css_cs(css);
2893
2894 free_cpuset(cs);
2895 }
2896
cpuset_bind(struct cgroup_subsys_state * root_css)2897 static void cpuset_bind(struct cgroup_subsys_state *root_css)
2898 {
2899 percpu_down_write(&cpuset_rwsem);
2900 spin_lock_irq(&callback_lock);
2901
2902 if (is_in_v2_mode()) {
2903 cpumask_copy(top_cpuset.cpus_allowed, cpu_possible_mask);
2904 top_cpuset.mems_allowed = node_possible_map;
2905 } else {
2906 cpumask_copy(top_cpuset.cpus_allowed,
2907 top_cpuset.effective_cpus);
2908 top_cpuset.mems_allowed = top_cpuset.effective_mems;
2909 }
2910
2911 spin_unlock_irq(&callback_lock);
2912 percpu_up_write(&cpuset_rwsem);
2913 }
2914
2915 /*
2916 * Make sure the new task conform to the current state of its parent,
2917 * which could have been changed by cpuset just after it inherits the
2918 * state from the parent and before it sits on the cgroup's task list.
2919 */
cpuset_fork(struct task_struct * task)2920 static void cpuset_fork(struct task_struct *task)
2921 {
2922 if (task_css_is_root(task, cpuset_cgrp_id))
2923 return;
2924
2925 set_cpus_allowed_ptr(task, current->cpus_ptr);
2926 task->mems_allowed = current->mems_allowed;
2927 }
2928
2929 struct cgroup_subsys cpuset_cgrp_subsys = {
2930 .css_alloc = cpuset_css_alloc,
2931 .css_online = cpuset_css_online,
2932 .css_offline = cpuset_css_offline,
2933 .css_free = cpuset_css_free,
2934 .can_attach = cpuset_can_attach,
2935 .cancel_attach = cpuset_cancel_attach,
2936 .attach = cpuset_attach,
2937 .post_attach = cpuset_post_attach,
2938 .bind = cpuset_bind,
2939 .fork = cpuset_fork,
2940 .legacy_cftypes = legacy_files,
2941 .dfl_cftypes = dfl_files,
2942 .early_init = true,
2943 .threaded = true,
2944 };
2945
2946 /**
2947 * cpuset_init - initialize cpusets at system boot
2948 *
2949 * Description: Initialize top_cpuset
2950 **/
2951
cpuset_init(void)2952 int __init cpuset_init(void)
2953 {
2954 BUG_ON(percpu_init_rwsem(&cpuset_rwsem));
2955
2956 BUG_ON(!alloc_cpumask_var(&top_cpuset.cpus_allowed, GFP_KERNEL));
2957 BUG_ON(!alloc_cpumask_var(&top_cpuset.cpus_requested, GFP_KERNEL));
2958 BUG_ON(!alloc_cpumask_var(&top_cpuset.effective_cpus, GFP_KERNEL));
2959 BUG_ON(!zalloc_cpumask_var(&top_cpuset.subparts_cpus, GFP_KERNEL));
2960
2961 cpumask_setall(top_cpuset.cpus_allowed);
2962 cpumask_setall(top_cpuset.cpus_requested);
2963 nodes_setall(top_cpuset.mems_allowed);
2964 cpumask_setall(top_cpuset.effective_cpus);
2965 nodes_setall(top_cpuset.effective_mems);
2966
2967 fmeter_init(&top_cpuset.fmeter);
2968 set_bit(CS_SCHED_LOAD_BALANCE, &top_cpuset.flags);
2969 top_cpuset.relax_domain_level = -1;
2970
2971 BUG_ON(!alloc_cpumask_var(&cpus_attach, GFP_KERNEL));
2972
2973 return 0;
2974 }
2975
2976 /*
2977 * If CPU and/or memory hotplug handlers, below, unplug any CPUs
2978 * or memory nodes, we need to walk over the cpuset hierarchy,
2979 * removing that CPU or node from all cpusets. If this removes the
2980 * last CPU or node from a cpuset, then move the tasks in the empty
2981 * cpuset to its next-highest non-empty parent.
2982 */
remove_tasks_in_empty_cpuset(struct cpuset * cs)2983 static void remove_tasks_in_empty_cpuset(struct cpuset *cs)
2984 {
2985 struct cpuset *parent;
2986
2987 /*
2988 * Find its next-highest non-empty parent, (top cpuset
2989 * has online cpus, so can't be empty).
2990 */
2991 parent = parent_cs(cs);
2992 while (cpumask_empty(parent->cpus_allowed) ||
2993 nodes_empty(parent->mems_allowed))
2994 parent = parent_cs(parent);
2995
2996 if (cgroup_transfer_tasks(parent->css.cgroup, cs->css.cgroup)) {
2997 pr_err("cpuset: failed to transfer tasks out of empty cpuset ");
2998 pr_cont_cgroup_name(cs->css.cgroup);
2999 pr_cont("\n");
3000 }
3001 }
3002
3003 static void
hotplug_update_tasks_legacy(struct cpuset * cs,struct cpumask * new_cpus,nodemask_t * new_mems,bool cpus_updated,bool mems_updated)3004 hotplug_update_tasks_legacy(struct cpuset *cs,
3005 struct cpumask *new_cpus, nodemask_t *new_mems,
3006 bool cpus_updated, bool mems_updated)
3007 {
3008 bool is_empty;
3009
3010 spin_lock_irq(&callback_lock);
3011 cpumask_copy(cs->cpus_allowed, new_cpus);
3012 cpumask_copy(cs->effective_cpus, new_cpus);
3013 cs->mems_allowed = *new_mems;
3014 cs->effective_mems = *new_mems;
3015 spin_unlock_irq(&callback_lock);
3016
3017 /*
3018 * Don't call update_tasks_cpumask() if the cpuset becomes empty,
3019 * as the tasks will be migratecd to an ancestor.
3020 */
3021 if (cpus_updated && !cpumask_empty(cs->cpus_allowed))
3022 update_tasks_cpumask(cs);
3023 if (mems_updated && !nodes_empty(cs->mems_allowed))
3024 update_tasks_nodemask(cs);
3025
3026 is_empty = cpumask_empty(cs->cpus_allowed) ||
3027 nodes_empty(cs->mems_allowed);
3028
3029 percpu_up_write(&cpuset_rwsem);
3030
3031 /*
3032 * Move tasks to the nearest ancestor with execution resources,
3033 * This is full cgroup operation which will also call back into
3034 * cpuset. Should be done outside any lock.
3035 */
3036 if (is_empty)
3037 remove_tasks_in_empty_cpuset(cs);
3038
3039 percpu_down_write(&cpuset_rwsem);
3040 }
3041
3042 static void
hotplug_update_tasks(struct cpuset * cs,struct cpumask * new_cpus,nodemask_t * new_mems,bool cpus_updated,bool mems_updated)3043 hotplug_update_tasks(struct cpuset *cs,
3044 struct cpumask *new_cpus, nodemask_t *new_mems,
3045 bool cpus_updated, bool mems_updated)
3046 {
3047 if (cpumask_empty(new_cpus))
3048 cpumask_copy(new_cpus, parent_cs(cs)->effective_cpus);
3049 if (nodes_empty(*new_mems))
3050 *new_mems = parent_cs(cs)->effective_mems;
3051
3052 spin_lock_irq(&callback_lock);
3053 cpumask_copy(cs->effective_cpus, new_cpus);
3054 cs->effective_mems = *new_mems;
3055 spin_unlock_irq(&callback_lock);
3056
3057 if (cpus_updated)
3058 update_tasks_cpumask(cs);
3059 if (mems_updated)
3060 update_tasks_nodemask(cs);
3061 }
3062
3063 static bool force_rebuild;
3064
cpuset_force_rebuild(void)3065 void cpuset_force_rebuild(void)
3066 {
3067 force_rebuild = true;
3068 }
3069
3070 /**
3071 * cpuset_hotplug_update_tasks - update tasks in a cpuset for hotunplug
3072 * @cs: cpuset in interest
3073 * @tmp: the tmpmasks structure pointer
3074 *
3075 * Compare @cs's cpu and mem masks against top_cpuset and if some have gone
3076 * offline, update @cs accordingly. If @cs ends up with no CPU or memory,
3077 * all its tasks are moved to the nearest ancestor with both resources.
3078 */
cpuset_hotplug_update_tasks(struct cpuset * cs,struct tmpmasks * tmp)3079 static void cpuset_hotplug_update_tasks(struct cpuset *cs, struct tmpmasks *tmp)
3080 {
3081 static cpumask_t new_cpus;
3082 static nodemask_t new_mems;
3083 bool cpus_updated;
3084 bool mems_updated;
3085 struct cpuset *parent;
3086 retry:
3087 wait_event(cpuset_attach_wq, cs->attach_in_progress == 0);
3088
3089 percpu_down_write(&cpuset_rwsem);
3090
3091 /*
3092 * We have raced with task attaching. We wait until attaching
3093 * is finished, so we won't attach a task to an empty cpuset.
3094 */
3095 if (cs->attach_in_progress) {
3096 percpu_up_write(&cpuset_rwsem);
3097 goto retry;
3098 }
3099
3100 parent = parent_cs(cs);
3101 compute_effective_cpumask(&new_cpus, cs, parent);
3102 nodes_and(new_mems, cs->mems_allowed, parent->effective_mems);
3103
3104 if (cs->nr_subparts_cpus)
3105 /*
3106 * Make sure that CPUs allocated to child partitions
3107 * do not show up in effective_cpus.
3108 */
3109 cpumask_andnot(&new_cpus, &new_cpus, cs->subparts_cpus);
3110
3111 if (!tmp || !cs->partition_root_state)
3112 goto update_tasks;
3113
3114 /*
3115 * In the unlikely event that a partition root has empty
3116 * effective_cpus or its parent becomes erroneous, we have to
3117 * transition it to the erroneous state.
3118 */
3119 if (is_partition_root(cs) && (cpumask_empty(&new_cpus) ||
3120 (parent->partition_root_state == PRS_ERROR))) {
3121 if (cs->nr_subparts_cpus) {
3122 spin_lock_irq(&callback_lock);
3123 cs->nr_subparts_cpus = 0;
3124 cpumask_clear(cs->subparts_cpus);
3125 spin_unlock_irq(&callback_lock);
3126 compute_effective_cpumask(&new_cpus, cs, parent);
3127 }
3128
3129 /*
3130 * If the effective_cpus is empty because the child
3131 * partitions take away all the CPUs, we can keep
3132 * the current partition and let the child partitions
3133 * fight for available CPUs.
3134 */
3135 if ((parent->partition_root_state == PRS_ERROR) ||
3136 cpumask_empty(&new_cpus)) {
3137 update_parent_subparts_cpumask(cs, partcmd_disable,
3138 NULL, tmp);
3139 spin_lock_irq(&callback_lock);
3140 cs->partition_root_state = PRS_ERROR;
3141 spin_unlock_irq(&callback_lock);
3142 }
3143 cpuset_force_rebuild();
3144 }
3145
3146 /*
3147 * On the other hand, an erroneous partition root may be transitioned
3148 * back to a regular one or a partition root with no CPU allocated
3149 * from the parent may change to erroneous.
3150 */
3151 if (is_partition_root(parent) &&
3152 ((cs->partition_root_state == PRS_ERROR) ||
3153 !cpumask_intersects(&new_cpus, parent->subparts_cpus)) &&
3154 update_parent_subparts_cpumask(cs, partcmd_update, NULL, tmp))
3155 cpuset_force_rebuild();
3156
3157 update_tasks:
3158 cpus_updated = !cpumask_equal(&new_cpus, cs->effective_cpus);
3159 mems_updated = !nodes_equal(new_mems, cs->effective_mems);
3160
3161 if (is_in_v2_mode())
3162 hotplug_update_tasks(cs, &new_cpus, &new_mems,
3163 cpus_updated, mems_updated);
3164 else
3165 hotplug_update_tasks_legacy(cs, &new_cpus, &new_mems,
3166 cpus_updated, mems_updated);
3167
3168 percpu_up_write(&cpuset_rwsem);
3169 }
3170
3171 /**
3172 * cpuset_hotplug_workfn - handle CPU/memory hotunplug for a cpuset
3173 *
3174 * This function is called after either CPU or memory configuration has
3175 * changed and updates cpuset accordingly. The top_cpuset is always
3176 * synchronized to cpu_active_mask and N_MEMORY, which is necessary in
3177 * order to make cpusets transparent (of no affect) on systems that are
3178 * actively using CPU hotplug but making no active use of cpusets.
3179 *
3180 * Non-root cpusets are only affected by offlining. If any CPUs or memory
3181 * nodes have been taken down, cpuset_hotplug_update_tasks() is invoked on
3182 * all descendants.
3183 *
3184 * Note that CPU offlining during suspend is ignored. We don't modify
3185 * cpusets across suspend/resume cycles at all.
3186 */
cpuset_hotplug_workfn(struct work_struct * work)3187 static void cpuset_hotplug_workfn(struct work_struct *work)
3188 {
3189 static cpumask_t new_cpus;
3190 static nodemask_t new_mems;
3191 bool cpus_updated, mems_updated;
3192 bool on_dfl = is_in_v2_mode();
3193 struct tmpmasks tmp, *ptmp = NULL;
3194
3195 if (on_dfl && !alloc_cpumasks(NULL, &tmp))
3196 ptmp = &tmp;
3197
3198 percpu_down_write(&cpuset_rwsem);
3199
3200 /* fetch the available cpus/mems and find out which changed how */
3201 cpumask_copy(&new_cpus, cpu_active_mask);
3202 new_mems = node_states[N_MEMORY];
3203
3204 /*
3205 * If subparts_cpus is populated, it is likely that the check below
3206 * will produce a false positive on cpus_updated when the cpu list
3207 * isn't changed. It is extra work, but it is better to be safe.
3208 */
3209 cpus_updated = !cpumask_equal(top_cpuset.effective_cpus, &new_cpus);
3210 mems_updated = !nodes_equal(top_cpuset.effective_mems, new_mems);
3211
3212 /*
3213 * In the rare case that hotplug removes all the cpus in subparts_cpus,
3214 * we assumed that cpus are updated.
3215 */
3216 if (!cpus_updated && top_cpuset.nr_subparts_cpus)
3217 cpus_updated = true;
3218
3219 /* synchronize cpus_allowed to cpu_active_mask */
3220 if (cpus_updated) {
3221 spin_lock_irq(&callback_lock);
3222 if (!on_dfl)
3223 cpumask_copy(top_cpuset.cpus_allowed, &new_cpus);
3224 /*
3225 * Make sure that CPUs allocated to child partitions
3226 * do not show up in effective_cpus. If no CPU is left,
3227 * we clear the subparts_cpus & let the child partitions
3228 * fight for the CPUs again.
3229 */
3230 if (top_cpuset.nr_subparts_cpus) {
3231 if (cpumask_subset(&new_cpus,
3232 top_cpuset.subparts_cpus)) {
3233 top_cpuset.nr_subparts_cpus = 0;
3234 cpumask_clear(top_cpuset.subparts_cpus);
3235 } else {
3236 cpumask_andnot(&new_cpus, &new_cpus,
3237 top_cpuset.subparts_cpus);
3238 }
3239 }
3240 cpumask_copy(top_cpuset.effective_cpus, &new_cpus);
3241 spin_unlock_irq(&callback_lock);
3242 /* we don't mess with cpumasks of tasks in top_cpuset */
3243 }
3244
3245 /* synchronize mems_allowed to N_MEMORY */
3246 if (mems_updated) {
3247 spin_lock_irq(&callback_lock);
3248 if (!on_dfl)
3249 top_cpuset.mems_allowed = new_mems;
3250 top_cpuset.effective_mems = new_mems;
3251 spin_unlock_irq(&callback_lock);
3252 update_tasks_nodemask(&top_cpuset);
3253 }
3254
3255 percpu_up_write(&cpuset_rwsem);
3256
3257 /* if cpus or mems changed, we need to propagate to descendants */
3258 if (cpus_updated || mems_updated) {
3259 struct cpuset *cs;
3260 struct cgroup_subsys_state *pos_css;
3261
3262 rcu_read_lock();
3263 cpuset_for_each_descendant_pre(cs, pos_css, &top_cpuset) {
3264 if (cs == &top_cpuset || !css_tryget_online(&cs->css))
3265 continue;
3266 rcu_read_unlock();
3267
3268 cpuset_hotplug_update_tasks(cs, ptmp);
3269
3270 rcu_read_lock();
3271 css_put(&cs->css);
3272 }
3273 rcu_read_unlock();
3274 }
3275
3276 /* rebuild sched domains if cpus_allowed has changed */
3277 if (cpus_updated || force_rebuild) {
3278 force_rebuild = false;
3279 rebuild_sched_domains();
3280 }
3281
3282 free_cpumasks(NULL, ptmp);
3283 }
3284
cpuset_update_active_cpus(void)3285 void cpuset_update_active_cpus(void)
3286 {
3287 /*
3288 * We're inside cpu hotplug critical region which usually nests
3289 * inside cgroup synchronization. Bounce actual hotplug processing
3290 * to a work item to avoid reverse locking order.
3291 */
3292 schedule_work(&cpuset_hotplug_work);
3293 }
3294
cpuset_wait_for_hotplug(void)3295 void cpuset_wait_for_hotplug(void)
3296 {
3297 flush_work(&cpuset_hotplug_work);
3298 }
3299
3300 /*
3301 * Keep top_cpuset.mems_allowed tracking node_states[N_MEMORY].
3302 * Call this routine anytime after node_states[N_MEMORY] changes.
3303 * See cpuset_update_active_cpus() for CPU hotplug handling.
3304 */
cpuset_track_online_nodes(struct notifier_block * self,unsigned long action,void * arg)3305 static int cpuset_track_online_nodes(struct notifier_block *self,
3306 unsigned long action, void *arg)
3307 {
3308 schedule_work(&cpuset_hotplug_work);
3309 return NOTIFY_OK;
3310 }
3311
3312 static struct notifier_block cpuset_track_online_nodes_nb = {
3313 .notifier_call = cpuset_track_online_nodes,
3314 .priority = 10, /* ??! */
3315 };
3316
3317 /**
3318 * cpuset_init_smp - initialize cpus_allowed
3319 *
3320 * Description: Finish top cpuset after cpu, node maps are initialized
3321 */
cpuset_init_smp(void)3322 void __init cpuset_init_smp(void)
3323 {
3324 /*
3325 * cpus_allowd/mems_allowed set to v2 values in the initial
3326 * cpuset_bind() call will be reset to v1 values in another
3327 * cpuset_bind() call when v1 cpuset is mounted.
3328 */
3329 top_cpuset.old_mems_allowed = top_cpuset.mems_allowed;
3330
3331 cpumask_copy(top_cpuset.effective_cpus, cpu_active_mask);
3332 top_cpuset.effective_mems = node_states[N_MEMORY];
3333
3334 register_hotmemory_notifier(&cpuset_track_online_nodes_nb);
3335
3336 cpuset_migrate_mm_wq = alloc_ordered_workqueue("cpuset_migrate_mm", 0);
3337 BUG_ON(!cpuset_migrate_mm_wq);
3338 }
3339
3340 /**
3341 * cpuset_cpus_allowed - return cpus_allowed mask from a tasks cpuset.
3342 * @tsk: pointer to task_struct from which to obtain cpuset->cpus_allowed.
3343 * @pmask: pointer to struct cpumask variable to receive cpus_allowed set.
3344 *
3345 * Description: Returns the cpumask_var_t cpus_allowed of the cpuset
3346 * attached to the specified @tsk. Guaranteed to return some non-empty
3347 * subset of cpu_online_mask, even if this means going outside the
3348 * tasks cpuset.
3349 **/
3350
cpuset_cpus_allowed(struct task_struct * tsk,struct cpumask * pmask)3351 void cpuset_cpus_allowed(struct task_struct *tsk, struct cpumask *pmask)
3352 {
3353 unsigned long flags;
3354
3355 spin_lock_irqsave(&callback_lock, flags);
3356 rcu_read_lock();
3357 guarantee_online_cpus(task_cs(tsk), pmask);
3358 rcu_read_unlock();
3359 spin_unlock_irqrestore(&callback_lock, flags);
3360 }
3361
3362 /**
3363 * cpuset_cpus_allowed_fallback - final fallback before complete catastrophe.
3364 * @tsk: pointer to task_struct with which the scheduler is struggling
3365 *
3366 * Description: In the case that the scheduler cannot find an allowed cpu in
3367 * tsk->cpus_allowed, we fall back to task_cs(tsk)->cpus_allowed. In legacy
3368 * mode however, this value is the same as task_cs(tsk)->effective_cpus,
3369 * which will not contain a sane cpumask during cases such as cpu hotplugging.
3370 * This is the absolute last resort for the scheduler and it is only used if
3371 * _every_ other avenue has been traveled.
3372 **/
3373
cpuset_cpus_allowed_fallback(struct task_struct * tsk)3374 void cpuset_cpus_allowed_fallback(struct task_struct *tsk)
3375 {
3376 rcu_read_lock();
3377 do_set_cpus_allowed(tsk, is_in_v2_mode() ?
3378 task_cs(tsk)->cpus_allowed : cpu_possible_mask);
3379 rcu_read_unlock();
3380
3381 /*
3382 * We own tsk->cpus_allowed, nobody can change it under us.
3383 *
3384 * But we used cs && cs->cpus_allowed lockless and thus can
3385 * race with cgroup_attach_task() or update_cpumask() and get
3386 * the wrong tsk->cpus_allowed. However, both cases imply the
3387 * subsequent cpuset_change_cpumask()->set_cpus_allowed_ptr()
3388 * which takes task_rq_lock().
3389 *
3390 * If we are called after it dropped the lock we must see all
3391 * changes in tsk_cs()->cpus_allowed. Otherwise we can temporary
3392 * set any mask even if it is not right from task_cs() pov,
3393 * the pending set_cpus_allowed_ptr() will fix things.
3394 *
3395 * select_fallback_rq() will fix things ups and set cpu_possible_mask
3396 * if required.
3397 */
3398 }
3399
cpuset_init_current_mems_allowed(void)3400 void __init cpuset_init_current_mems_allowed(void)
3401 {
3402 nodes_setall(current->mems_allowed);
3403 }
3404
3405 /**
3406 * cpuset_mems_allowed - return mems_allowed mask from a tasks cpuset.
3407 * @tsk: pointer to task_struct from which to obtain cpuset->mems_allowed.
3408 *
3409 * Description: Returns the nodemask_t mems_allowed of the cpuset
3410 * attached to the specified @tsk. Guaranteed to return some non-empty
3411 * subset of node_states[N_MEMORY], even if this means going outside the
3412 * tasks cpuset.
3413 **/
3414
cpuset_mems_allowed(struct task_struct * tsk)3415 nodemask_t cpuset_mems_allowed(struct task_struct *tsk)
3416 {
3417 nodemask_t mask;
3418 unsigned long flags;
3419
3420 spin_lock_irqsave(&callback_lock, flags);
3421 rcu_read_lock();
3422 guarantee_online_mems(task_cs(tsk), &mask);
3423 rcu_read_unlock();
3424 spin_unlock_irqrestore(&callback_lock, flags);
3425
3426 return mask;
3427 }
3428
3429 /**
3430 * cpuset_nodemask_valid_mems_allowed - check nodemask vs. curremt mems_allowed
3431 * @nodemask: the nodemask to be checked
3432 *
3433 * Are any of the nodes in the nodemask allowed in current->mems_allowed?
3434 */
cpuset_nodemask_valid_mems_allowed(nodemask_t * nodemask)3435 int cpuset_nodemask_valid_mems_allowed(nodemask_t *nodemask)
3436 {
3437 return nodes_intersects(*nodemask, current->mems_allowed);
3438 }
3439
3440 /*
3441 * nearest_hardwall_ancestor() - Returns the nearest mem_exclusive or
3442 * mem_hardwall ancestor to the specified cpuset. Call holding
3443 * callback_lock. If no ancestor is mem_exclusive or mem_hardwall
3444 * (an unusual configuration), then returns the root cpuset.
3445 */
nearest_hardwall_ancestor(struct cpuset * cs)3446 static struct cpuset *nearest_hardwall_ancestor(struct cpuset *cs)
3447 {
3448 while (!(is_mem_exclusive(cs) || is_mem_hardwall(cs)) && parent_cs(cs))
3449 cs = parent_cs(cs);
3450 return cs;
3451 }
3452
3453 /**
3454 * cpuset_node_allowed - Can we allocate on a memory node?
3455 * @node: is this an allowed node?
3456 * @gfp_mask: memory allocation flags
3457 *
3458 * If we're in interrupt, yes, we can always allocate. If @node is set in
3459 * current's mems_allowed, yes. If it's not a __GFP_HARDWALL request and this
3460 * node is set in the nearest hardwalled cpuset ancestor to current's cpuset,
3461 * yes. If current has access to memory reserves as an oom victim, yes.
3462 * Otherwise, no.
3463 *
3464 * GFP_USER allocations are marked with the __GFP_HARDWALL bit,
3465 * and do not allow allocations outside the current tasks cpuset
3466 * unless the task has been OOM killed.
3467 * GFP_KERNEL allocations are not so marked, so can escape to the
3468 * nearest enclosing hardwalled ancestor cpuset.
3469 *
3470 * Scanning up parent cpusets requires callback_lock. The
3471 * __alloc_pages() routine only calls here with __GFP_HARDWALL bit
3472 * _not_ set if it's a GFP_KERNEL allocation, and all nodes in the
3473 * current tasks mems_allowed came up empty on the first pass over
3474 * the zonelist. So only GFP_KERNEL allocations, if all nodes in the
3475 * cpuset are short of memory, might require taking the callback_lock.
3476 *
3477 * The first call here from mm/page_alloc:get_page_from_freelist()
3478 * has __GFP_HARDWALL set in gfp_mask, enforcing hardwall cpusets,
3479 * so no allocation on a node outside the cpuset is allowed (unless
3480 * in interrupt, of course).
3481 *
3482 * The second pass through get_page_from_freelist() doesn't even call
3483 * here for GFP_ATOMIC calls. For those calls, the __alloc_pages()
3484 * variable 'wait' is not set, and the bit ALLOC_CPUSET is not set
3485 * in alloc_flags. That logic and the checks below have the combined
3486 * affect that:
3487 * in_interrupt - any node ok (current task context irrelevant)
3488 * GFP_ATOMIC - any node ok
3489 * tsk_is_oom_victim - any node ok
3490 * GFP_KERNEL - any node in enclosing hardwalled cpuset ok
3491 * GFP_USER - only nodes in current tasks mems allowed ok.
3492 */
__cpuset_node_allowed(int node,gfp_t gfp_mask)3493 bool __cpuset_node_allowed(int node, gfp_t gfp_mask)
3494 {
3495 struct cpuset *cs; /* current cpuset ancestors */
3496 int allowed; /* is allocation in zone z allowed? */
3497 unsigned long flags;
3498
3499 if (in_interrupt())
3500 return true;
3501 if (node_isset(node, current->mems_allowed))
3502 return true;
3503 /*
3504 * Allow tasks that have access to memory reserves because they have
3505 * been OOM killed to get memory anywhere.
3506 */
3507 if (unlikely(tsk_is_oom_victim(current)))
3508 return true;
3509 if (gfp_mask & __GFP_HARDWALL) /* If hardwall request, stop here */
3510 return false;
3511
3512 if (current->flags & PF_EXITING) /* Let dying task have memory */
3513 return true;
3514
3515 /* Not hardwall and node outside mems_allowed: scan up cpusets */
3516 spin_lock_irqsave(&callback_lock, flags);
3517
3518 rcu_read_lock();
3519 cs = nearest_hardwall_ancestor(task_cs(current));
3520 allowed = node_isset(node, cs->mems_allowed);
3521 rcu_read_unlock();
3522
3523 spin_unlock_irqrestore(&callback_lock, flags);
3524 return allowed;
3525 }
3526
3527 /**
3528 * cpuset_mem_spread_node() - On which node to begin search for a file page
3529 * cpuset_slab_spread_node() - On which node to begin search for a slab page
3530 *
3531 * If a task is marked PF_SPREAD_PAGE or PF_SPREAD_SLAB (as for
3532 * tasks in a cpuset with is_spread_page or is_spread_slab set),
3533 * and if the memory allocation used cpuset_mem_spread_node()
3534 * to determine on which node to start looking, as it will for
3535 * certain page cache or slab cache pages such as used for file
3536 * system buffers and inode caches, then instead of starting on the
3537 * local node to look for a free page, rather spread the starting
3538 * node around the tasks mems_allowed nodes.
3539 *
3540 * We don't have to worry about the returned node being offline
3541 * because "it can't happen", and even if it did, it would be ok.
3542 *
3543 * The routines calling guarantee_online_mems() are careful to
3544 * only set nodes in task->mems_allowed that are online. So it
3545 * should not be possible for the following code to return an
3546 * offline node. But if it did, that would be ok, as this routine
3547 * is not returning the node where the allocation must be, only
3548 * the node where the search should start. The zonelist passed to
3549 * __alloc_pages() will include all nodes. If the slab allocator
3550 * is passed an offline node, it will fall back to the local node.
3551 * See kmem_cache_alloc_node().
3552 */
3553
cpuset_spread_node(int * rotor)3554 static int cpuset_spread_node(int *rotor)
3555 {
3556 return *rotor = next_node_in(*rotor, current->mems_allowed);
3557 }
3558
cpuset_mem_spread_node(void)3559 int cpuset_mem_spread_node(void)
3560 {
3561 if (current->cpuset_mem_spread_rotor == NUMA_NO_NODE)
3562 current->cpuset_mem_spread_rotor =
3563 node_random(¤t->mems_allowed);
3564
3565 return cpuset_spread_node(¤t->cpuset_mem_spread_rotor);
3566 }
3567
cpuset_slab_spread_node(void)3568 int cpuset_slab_spread_node(void)
3569 {
3570 if (current->cpuset_slab_spread_rotor == NUMA_NO_NODE)
3571 current->cpuset_slab_spread_rotor =
3572 node_random(¤t->mems_allowed);
3573
3574 return cpuset_spread_node(¤t->cpuset_slab_spread_rotor);
3575 }
3576
3577 EXPORT_SYMBOL_GPL(cpuset_mem_spread_node);
3578
3579 /**
3580 * cpuset_mems_allowed_intersects - Does @tsk1's mems_allowed intersect @tsk2's?
3581 * @tsk1: pointer to task_struct of some task.
3582 * @tsk2: pointer to task_struct of some other task.
3583 *
3584 * Description: Return true if @tsk1's mems_allowed intersects the
3585 * mems_allowed of @tsk2. Used by the OOM killer to determine if
3586 * one of the task's memory usage might impact the memory available
3587 * to the other.
3588 **/
3589
cpuset_mems_allowed_intersects(const struct task_struct * tsk1,const struct task_struct * tsk2)3590 int cpuset_mems_allowed_intersects(const struct task_struct *tsk1,
3591 const struct task_struct *tsk2)
3592 {
3593 return nodes_intersects(tsk1->mems_allowed, tsk2->mems_allowed);
3594 }
3595
3596 /**
3597 * cpuset_print_current_mems_allowed - prints current's cpuset and mems_allowed
3598 *
3599 * Description: Prints current's name, cpuset name, and cached copy of its
3600 * mems_allowed to the kernel log.
3601 */
cpuset_print_current_mems_allowed(void)3602 void cpuset_print_current_mems_allowed(void)
3603 {
3604 struct cgroup *cgrp;
3605
3606 rcu_read_lock();
3607
3608 cgrp = task_cs(current)->css.cgroup;
3609 pr_cont(",cpuset=");
3610 pr_cont_cgroup_name(cgrp);
3611 pr_cont(",mems_allowed=%*pbl",
3612 nodemask_pr_args(¤t->mems_allowed));
3613
3614 rcu_read_unlock();
3615 }
3616
3617 /*
3618 * Collection of memory_pressure is suppressed unless
3619 * this flag is enabled by writing "1" to the special
3620 * cpuset file 'memory_pressure_enabled' in the root cpuset.
3621 */
3622
3623 int cpuset_memory_pressure_enabled __read_mostly;
3624
3625 /**
3626 * cpuset_memory_pressure_bump - keep stats of per-cpuset reclaims.
3627 *
3628 * Keep a running average of the rate of synchronous (direct)
3629 * page reclaim efforts initiated by tasks in each cpuset.
3630 *
3631 * This represents the rate at which some task in the cpuset
3632 * ran low on memory on all nodes it was allowed to use, and
3633 * had to enter the kernels page reclaim code in an effort to
3634 * create more free memory by tossing clean pages or swapping
3635 * or writing dirty pages.
3636 *
3637 * Display to user space in the per-cpuset read-only file
3638 * "memory_pressure". Value displayed is an integer
3639 * representing the recent rate of entry into the synchronous
3640 * (direct) page reclaim by any task attached to the cpuset.
3641 **/
3642
__cpuset_memory_pressure_bump(void)3643 void __cpuset_memory_pressure_bump(void)
3644 {
3645 rcu_read_lock();
3646 fmeter_markevent(&task_cs(current)->fmeter);
3647 rcu_read_unlock();
3648 }
3649
3650 #ifdef CONFIG_PROC_PID_CPUSET
3651 /*
3652 * proc_cpuset_show()
3653 * - Print tasks cpuset path into seq_file.
3654 * - Used for /proc/<pid>/cpuset.
3655 * - No need to task_lock(tsk) on this tsk->cpuset reference, as it
3656 * doesn't really matter if tsk->cpuset changes after we read it,
3657 * and we take cpuset_mutex, keeping cpuset_attach() from changing it
3658 * anyway.
3659 */
proc_cpuset_show(struct seq_file * m,struct pid_namespace * ns,struct pid * pid,struct task_struct * tsk)3660 int proc_cpuset_show(struct seq_file *m, struct pid_namespace *ns,
3661 struct pid *pid, struct task_struct *tsk)
3662 {
3663 char *buf;
3664 struct cgroup_subsys_state *css;
3665 int retval;
3666
3667 retval = -ENOMEM;
3668 buf = kmalloc(PATH_MAX, GFP_KERNEL);
3669 if (!buf)
3670 goto out;
3671
3672 css = task_get_css(tsk, cpuset_cgrp_id);
3673 retval = cgroup_path_ns(css->cgroup, buf, PATH_MAX,
3674 current->nsproxy->cgroup_ns);
3675 css_put(css);
3676 if (retval >= PATH_MAX)
3677 retval = -ENAMETOOLONG;
3678 if (retval < 0)
3679 goto out_free;
3680 seq_puts(m, buf);
3681 seq_putc(m, '\n');
3682 retval = 0;
3683 out_free:
3684 kfree(buf);
3685 out:
3686 return retval;
3687 }
3688 #endif /* CONFIG_PROC_PID_CPUSET */
3689
3690 /* Display task mems_allowed in /proc/<pid>/status file. */
cpuset_task_status_allowed(struct seq_file * m,struct task_struct * task)3691 void cpuset_task_status_allowed(struct seq_file *m, struct task_struct *task)
3692 {
3693 seq_printf(m, "Mems_allowed:\t%*pb\n",
3694 nodemask_pr_args(&task->mems_allowed));
3695 seq_printf(m, "Mems_allowed_list:\t%*pbl\n",
3696 nodemask_pr_args(&task->mems_allowed));
3697 }
3698