1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * kernel/cpuset.c
4 *
5 * Processor and Memory placement constraints for sets of tasks.
6 *
7 * Copyright (C) 2003 BULL SA.
8 * Copyright (C) 2004-2007 Silicon Graphics, Inc.
9 * Copyright (C) 2006 Google, Inc
10 *
11 * Portions derived from Patrick Mochel's sysfs code.
12 * sysfs is Copyright (c) 2001-3 Patrick Mochel
13 *
14 * 2003-10-10 Written by Simon Derr.
15 * 2003-10-22 Updates by Stephen Hemminger.
16 * 2004 May-July Rework by Paul Jackson.
17 * 2006 Rework by Paul Menage to use generic cgroups
18 * 2008 Rework of the scheduler domains and CPU hotplug handling
19 * by Max Krasnyansky
20 */
21 #include "cpuset-internal.h"
22
23 #include <linux/init.h>
24 #include <linux/interrupt.h>
25 #include <linux/kernel.h>
26 #include <linux/mempolicy.h>
27 #include <linux/mm.h>
28 #include <linux/memory.h>
29 #include <linux/rcupdate.h>
30 #include <linux/sched.h>
31 #include <linux/sched/deadline.h>
32 #include <linux/sched/mm.h>
33 #include <linux/sched/task.h>
34 #include <linux/security.h>
35 #include <linux/oom.h>
36 #include <linux/sched/isolation.h>
37 #include <linux/wait.h>
38 #include <linux/workqueue.h>
39 #include <linux/task_work.h>
40 #include <linux/llist.h>
41
42 DEFINE_STATIC_KEY_FALSE(cpusets_pre_enable_key);
43 DEFINE_STATIC_KEY_FALSE(cpusets_enabled_key);
44
45 /*
46 * There could be abnormal cpuset configurations for cpu or memory
47 * node binding, add this key to provide a quick low-cost judgment
48 * of the situation.
49 */
50 DEFINE_STATIC_KEY_FALSE(cpusets_insane_config_key);
51
52 static const char * const perr_strings[] = {
53 [PERR_INVCPUS] = "Invalid cpu list in cpuset.cpus.exclusive",
54 [PERR_INVPARENT] = "Parent is an invalid partition root",
55 [PERR_NOTPART] = "Parent is not a partition root",
56 [PERR_NOTEXCL] = "Cpu list in cpuset.cpus not exclusive",
57 [PERR_NOCPUS] = "Parent unable to distribute cpu downstream",
58 [PERR_HOTPLUG] = "No cpu available due to hotplug",
59 [PERR_CPUSEMPTY] = "cpuset.cpus and cpuset.cpus.exclusive are empty",
60 [PERR_HKEEPING] = "partition config conflicts with housekeeping setup",
61 [PERR_ACCESS] = "Enable partition not permitted",
62 [PERR_REMOTE] = "Have remote partition underneath",
63 };
64
65 /*
66 * CPUSET Locking Convention
67 * -------------------------
68 *
69 * Below are the four global/local locks guarding cpuset structures in lock
70 * acquisition order:
71 * - cpuset_top_mutex
72 * - cpu_hotplug_lock (cpus_read_lock/cpus_write_lock)
73 * - cpuset_mutex
74 * - callback_lock (raw spinlock)
75 *
76 * As cpuset will now indirectly flush a number of different workqueues in
77 * housekeeping_update() to update housekeeping cpumasks when the set of
78 * isolated CPUs is going to be changed, it may be vulnerable to deadlock
79 * if we hold cpus_read_lock while calling into housekeeping_update().
80 *
81 * The first cpuset_top_mutex will be held except when calling into
82 * cpuset_handle_hotplug() from the CPU hotplug code where cpus_write_lock
83 * and cpuset_mutex will be held instead. The main purpose of this mutex
84 * is to prevent regular cpuset control file write actions from interfering
85 * with the call to housekeeping_update(), though CPU hotplug operation can
86 * still happen in parallel. This mutex also provides protection for some
87 * internal variables.
88 *
89 * A task must hold all the remaining three locks to modify externally visible
90 * or used fields of cpusets, though some of the internally used cpuset fields
91 * and internal variables can be modified without holding callback_lock. If only
92 * reliable read access of the externally used fields are needed, a task can
93 * hold either cpuset_mutex or callback_lock which are exposed to other
94 * external subsystems.
95 *
96 * If a task holds cpu_hotplug_lock and cpuset_mutex, it blocks others,
97 * ensuring that it is the only task able to also acquire callback_lock and
98 * be able to modify cpusets. It can perform various checks on the cpuset
99 * structure first, knowing nothing will change. It can also allocate memory
100 * without holding callback_lock. While it is performing these checks, various
101 * callback routines can briefly acquire callback_lock to query cpusets. Once
102 * it is ready to make the changes, it takes callback_lock, blocking everyone
103 * else.
104 *
105 * Calls to the kernel memory allocator cannot be made while holding
106 * callback_lock which is a spinlock, as the memory allocator may sleep or
107 * call back into cpuset code and acquire callback_lock.
108 *
109 * Now, the task_struct fields mems_allowed and mempolicy may be changed
110 * by other task, we use alloc_lock in the task_struct fields to protect
111 * them.
112 *
113 * The cpuset_common_seq_show() handlers only hold callback_lock across
114 * small pieces of code, such as when reading out possibly multi-word
115 * cpumasks and nodemasks.
116 */
117
118 static DEFINE_MUTEX(cpuset_top_mutex);
119 static DEFINE_MUTEX(cpuset_mutex);
120
121 /*
122 * File level internal variables below follow one of the following exclusion
123 * rules.
124 *
125 * RWCS: Read/write-able by holding either cpus_write_lock (and optionally
126 * cpuset_mutex) or both cpus_read_lock and cpuset_mutex.
127 *
128 * CSCB: Readable by holding either cpuset_mutex or callback_lock. Writable
129 * by holding both cpuset_mutex and callback_lock.
130 *
131 * T: Read/write-able by holding the cpuset_top_mutex.
132 */
133
134 /*
135 * For local partitions, update to subpartitions_cpus & isolated_cpus is done
136 * in update_parent_effective_cpumask(). For remote partitions, it is done in
137 * the remote_partition_*() and remote_cpus_update() helpers.
138 */
139 /*
140 * Exclusive CPUs distributed out to local or remote sub-partitions of
141 * top_cpuset
142 */
143 static cpumask_var_t subpartitions_cpus; /* RWCS */
144
145 /*
146 * Exclusive CPUs in isolated partitions (shown in cpuset.cpus.isolated)
147 */
148 static cpumask_var_t isolated_cpus; /* CSCB */
149
150 /*
151 * Set if housekeeping cpumasks are to be updated.
152 */
153 static bool update_housekeeping; /* RWCS */
154
155 /*
156 * Copy of isolated_cpus to be passed to housekeeping_update()
157 */
158 static cpumask_var_t isolated_hk_cpus; /* T */
159
160 /*
161 * A flag to force sched domain rebuild at the end of an operation.
162 * It can be set in
163 * - update_partition_sd_lb()
164 * - update_cpumasks_hier()
165 * - cpuset_update_flag()
166 * - cpuset_hotplug_update_tasks()
167 * - cpuset_handle_hotplug()
168 *
169 * Protected by cpuset_mutex (with cpus_read_lock held) or cpus_write_lock.
170 *
171 * Note that update_relax_domain_level() in cpuset-v1.c can still call
172 * rebuild_sched_domains_locked() directly without using this flag.
173 */
174 static bool force_sd_rebuild; /* RWCS */
175
176 /*
177 * Partition root states:
178 *
179 * 0 - member (not a partition root)
180 * 1 - partition root
181 * 2 - partition root without load balancing (isolated)
182 * -1 - invalid partition root
183 * -2 - invalid isolated partition root
184 *
185 * There are 2 types of partitions - local or remote. Local partitions are
186 * those whose parents are partition root themselves. Setting of
187 * cpuset.cpus.exclusive are optional in setting up local partitions.
188 * Remote partitions are those whose parents are not partition roots. Passing
189 * down exclusive CPUs by setting cpuset.cpus.exclusive along its ancestor
190 * nodes are mandatory in creating a remote partition.
191 *
192 * For simplicity, a local partition can be created under a local or remote
193 * partition but a remote partition cannot have any partition root in its
194 * ancestor chain except the cgroup root.
195 *
196 * A valid partition can be formed by setting exclusive_cpus or cpus_allowed
197 * if exclusive_cpus is not set. In the case of partition with empty
198 * exclusive_cpus, all the conflicting exclusive CPUs specified in the
199 * following cpumasks of sibling cpusets will be removed from its
200 * cpus_allowed in determining its effective_xcpus.
201 * - effective_xcpus
202 * - exclusive_cpus
203 *
204 * The "cpuset.cpus.exclusive" control file should be used for setting up
205 * partition if the users want to get as many CPUs as possible.
206 */
207 #define PRS_MEMBER 0
208 #define PRS_ROOT 1
209 #define PRS_ISOLATED 2
210 #define PRS_INVALID_ROOT -1
211 #define PRS_INVALID_ISOLATED -2
212
213 /*
214 * Temporary cpumasks for working with partitions that are passed among
215 * functions to avoid memory allocation in inner functions.
216 */
217 struct tmpmasks {
218 cpumask_var_t addmask, delmask; /* For partition root */
219 cpumask_var_t new_cpus; /* For update_cpumasks_hier() */
220 };
221
inc_dl_tasks_cs(struct task_struct * p)222 void inc_dl_tasks_cs(struct task_struct *p)
223 {
224 struct cpuset *cs = task_cs(p);
225
226 atomic_inc(&cs->nr_deadline_tasks);
227 }
228
dec_dl_tasks_cs(struct task_struct * p)229 void dec_dl_tasks_cs(struct task_struct *p)
230 {
231 struct cpuset *cs = task_cs(p);
232
233 atomic_dec(&cs->nr_deadline_tasks);
234 }
235
is_partition_valid(const struct cpuset * cs)236 static inline bool is_partition_valid(const struct cpuset *cs)
237 {
238 return cs->partition_root_state > 0;
239 }
240
is_partition_invalid(const struct cpuset * cs)241 static inline bool is_partition_invalid(const struct cpuset *cs)
242 {
243 return cs->partition_root_state < 0;
244 }
245
cs_is_member(const struct cpuset * cs)246 static inline bool cs_is_member(const struct cpuset *cs)
247 {
248 return cs->partition_root_state == PRS_MEMBER;
249 }
250
251 /*
252 * Callers should hold callback_lock to modify partition_root_state.
253 */
make_partition_invalid(struct cpuset * cs)254 static inline void make_partition_invalid(struct cpuset *cs)
255 {
256 if (cs->partition_root_state > 0)
257 cs->partition_root_state = -cs->partition_root_state;
258 }
259
260 /*
261 * Send notification event of whenever partition_root_state changes.
262 */
notify_partition_change(struct cpuset * cs,int old_prs)263 static inline void notify_partition_change(struct cpuset *cs, int old_prs)
264 {
265 if (old_prs == cs->partition_root_state)
266 return;
267 cgroup_file_notify(&cs->partition_file);
268
269 /* Reset prs_err if not invalid */
270 if (is_partition_valid(cs))
271 WRITE_ONCE(cs->prs_err, PERR_NONE);
272 }
273
274 /*
275 * The top_cpuset is always synchronized to cpu_active_mask and we should avoid
276 * using cpu_online_mask as much as possible. An active CPU is always an online
277 * CPU, but not vice versa. cpu_active_mask and cpu_online_mask can differ
278 * during hotplug operations. A CPU is marked active at the last stage of CPU
279 * bringup (CPUHP_AP_ACTIVE). It is also the stage where cpuset hotplug code
280 * will be called to update the sched domains so that the scheduler can move
281 * a normal task to a newly active CPU or remove tasks away from a newly
282 * inactivated CPU. The online bit is set much earlier in the CPU bringup
283 * process and cleared much later in CPU teardown.
284 *
285 * If cpu_online_mask is used while a hotunplug operation is happening in
286 * parallel, we may leave an offline CPU in cpu_allowed or some other masks.
287 */
288 struct cpuset top_cpuset = {
289 .flags = BIT(CS_CPU_EXCLUSIVE) |
290 BIT(CS_MEM_EXCLUSIVE) | BIT(CS_SCHED_LOAD_BALANCE),
291 .partition_root_state = PRS_ROOT,
292 .dl_bw_cpu = -1,
293 };
294
295 /**
296 * cpuset_lock - Acquire the global cpuset mutex
297 *
298 * This locks the global cpuset mutex to prevent modifications to cpuset
299 * hierarchy and configurations. This helper is not enough to make modification.
300 */
cpuset_lock(void)301 void cpuset_lock(void)
302 {
303 mutex_lock(&cpuset_mutex);
304 }
305
cpuset_unlock(void)306 void cpuset_unlock(void)
307 {
308 mutex_unlock(&cpuset_mutex);
309 }
310
lockdep_assert_cpuset_lock_held(void)311 void lockdep_assert_cpuset_lock_held(void)
312 {
313 lockdep_assert_held(&cpuset_mutex);
314 }
315
316 /**
317 * cpuset_full_lock - Acquire full protection for cpuset modification
318 *
319 * Takes both CPU hotplug read lock (cpus_read_lock()) and cpuset mutex
320 * to safely modify cpuset data.
321 */
cpuset_full_lock(void)322 void cpuset_full_lock(void)
323 {
324 mutex_lock(&cpuset_top_mutex);
325 cpus_read_lock();
326 mutex_lock(&cpuset_mutex);
327 }
328
cpuset_full_unlock(void)329 void cpuset_full_unlock(void)
330 {
331 mutex_unlock(&cpuset_mutex);
332 cpus_read_unlock();
333 mutex_unlock(&cpuset_top_mutex);
334 }
335
336 #ifdef CONFIG_LOCKDEP
lockdep_is_cpuset_held(void)337 bool lockdep_is_cpuset_held(void)
338 {
339 return lockdep_is_held(&cpuset_mutex) ||
340 lockdep_is_held(&cpuset_top_mutex);
341 }
342 #endif
343
344 static DEFINE_SPINLOCK(callback_lock);
345
cpuset_callback_lock_irq(void)346 void cpuset_callback_lock_irq(void)
347 {
348 spin_lock_irq(&callback_lock);
349 }
350
cpuset_callback_unlock_irq(void)351 void cpuset_callback_unlock_irq(void)
352 {
353 spin_unlock_irq(&callback_lock);
354 }
355
356 static struct workqueue_struct *cpuset_migrate_mm_wq;
357
358 static DECLARE_WAIT_QUEUE_HEAD(cpuset_attach_wq);
359
360 /*
361 * Cpuset task attach context
362 * Protected by cpuset_mutex
363 */
364 static struct {
365 int in_progress;
366 bool cpus_updated;
367 bool mems_updated;
368 bool task_work_queued;
369 bool many_dest_cs; /* Have many destination cpusets */
370 struct cpuset *old_cs; /* Source cpuset */
371 nodemask_t nodemask_to;
372 } attach_ctx;
373 static LLIST_HEAD(src_cs_head);
374 static LLIST_HEAD(dst_cs_head);
375
376 /*
377 * Wait if task attach is in progress until it is done and then acquire
378 * cpuset_mutex before returning.
379 */
wait_attach_done_lock(void)380 static void wait_attach_done_lock(void)
381 __acquires(&cpuset_mutex)
382 {
383 for (;;) {
384 mutex_lock(&cpuset_mutex);
385 if (!attach_ctx.in_progress)
386 return;
387
388 mutex_unlock(&cpuset_mutex);
389
390 /* Wait until attach operation is done to prevent racing */
391 wait_event(cpuset_attach_wq, attach_ctx.in_progress == 0);
392 }
393 }
394
check_insane_mems_config(nodemask_t * nodes)395 static inline void check_insane_mems_config(nodemask_t *nodes)
396 {
397 if (!cpusets_insane_config() &&
398 movable_only_nodes(nodes)) {
399 static_branch_enable_cpuslocked(&cpusets_insane_config_key);
400 pr_info("Unsupported (movable nodes only) cpuset configuration detected (nmask=%*pbl)!\n"
401 "Cpuset allocations might fail even with a lot of memory available.\n",
402 nodemask_pr_args(nodes));
403 }
404 }
405
406 /*
407 * decrease attach_ctx.in_progress.
408 * wake_up cpuset_attach_wq if attach_ctx.in_progress==0.
409 */
dec_attach_in_progress_locked(void)410 static inline void dec_attach_in_progress_locked(void)
411 {
412 lockdep_assert_cpuset_lock_held();
413
414 attach_ctx.in_progress--;
415 if (!attach_ctx.in_progress)
416 wake_up(&cpuset_attach_wq);
417 }
418
dec_attach_in_progress(void)419 static inline void dec_attach_in_progress(void)
420 {
421 mutex_lock(&cpuset_mutex);
422 dec_attach_in_progress_locked();
423 mutex_unlock(&cpuset_mutex);
424 }
425
cpuset_v2(void)426 static inline bool cpuset_v2(void)
427 {
428 return !IS_ENABLED(CONFIG_CPUSETS_V1) ||
429 cgroup_subsys_on_dfl(cpuset_cgrp_subsys);
430 }
431
432 /*
433 * Cgroup v2 behavior is used on the "cpus" and "mems" control files when
434 * on default hierarchy or when the cpuset_v2_mode flag is set by mounting
435 * the v1 cpuset cgroup filesystem with the "cpuset_v2_mode" mount option.
436 * With v2 behavior, "cpus" and "mems" are always what the users have
437 * requested and won't be changed by hotplug events. Only the effective
438 * cpus or mems will be affected.
439 */
is_in_v2_mode(void)440 static inline bool is_in_v2_mode(void)
441 {
442 return cpuset_v2() ||
443 (cpuset_cgrp_subsys.root->flags & CGRP_ROOT_CPUSET_V2_MODE);
444 }
445
446 /**
447 * partition_is_populated - check if partition has tasks
448 * @cs: partition root to be checked
449 * @excluded_child: a child cpuset to be excluded in task checking
450 * Return: true if there are tasks, false otherwise
451 *
452 * @cs should be a valid partition root or going to become a partition root.
453 * @excluded_child should be non-NULL when this cpuset is going to become a
454 * partition itself.
455 *
456 * Note that a remote partition is not allowed underneath a valid local
457 * or remote partition. So if a non-partition root child is populated,
458 * the whole partition is considered populated.
459 */
partition_is_populated(struct cpuset * cs,struct cpuset * excluded_child)460 static inline bool partition_is_populated(struct cpuset *cs,
461 struct cpuset *excluded_child)
462 {
463 struct cpuset *cp;
464 struct cgroup_subsys_state *pos_css;
465
466 /*
467 * We cannot call cs_is_populated(cs) directly, as
468 * nr_populated_domain_children may include populated
469 * csets from descendants that are partitions.
470 */
471 if (cgroup_has_tasks(cs->css.cgroup))
472 return true;
473
474 rcu_read_lock();
475 cpuset_for_each_descendant_pre(cp, pos_css, cs) {
476 if (cp == cs || cp == excluded_child)
477 continue;
478
479 if (is_partition_valid(cp)) {
480 pos_css = css_rightmost_descendant(pos_css);
481 continue;
482 }
483
484 if (cpuset_is_populated(cp)) {
485 rcu_read_unlock();
486 return true;
487 }
488 }
489 rcu_read_unlock();
490 return false;
491 }
492
493 /*
494 * Return in pmask the portion of a task's cpusets's cpus_allowed that
495 * are online and are capable of running the task. If none are found,
496 * walk up the cpuset hierarchy until we find one that does have some
497 * appropriate cpus.
498 *
499 * One way or another, we guarantee to return some non-empty subset
500 * of cpu_active_mask.
501 *
502 * Call with callback_lock or cpuset_mutex held.
503 */
guarantee_active_cpus(struct task_struct * tsk,struct cpumask * pmask)504 static void guarantee_active_cpus(struct task_struct *tsk,
505 struct cpumask *pmask)
506 {
507 const struct cpumask *possible_mask = task_cpu_possible_mask(tsk);
508 struct cpuset *cs;
509
510 if (WARN_ON(!cpumask_and(pmask, possible_mask, cpu_active_mask)))
511 cpumask_copy(pmask, cpu_active_mask);
512
513 rcu_read_lock();
514 cs = task_cs(tsk);
515
516 while (!cpumask_intersects(cs->effective_cpus, pmask))
517 cs = parent_cs(cs);
518
519 cpumask_and(pmask, pmask, cs->effective_cpus);
520 rcu_read_unlock();
521 }
522
523 /*
524 * Return in *pmask the portion of a cpusets's mems_allowed that
525 * are online, with memory. If none are online with memory, walk
526 * up the cpuset hierarchy until we find one that does have some
527 * online mems. The top cpuset always has some mems online. With v2,
528 * effective_mems should always contain online memory nodes except
529 * during the transition period where a memory node hotunplug operation
530 * is in progress.
531 *
532 * One way or another, we guarantee to return some non-empty subset
533 * of node_states[N_MEMORY].
534 *
535 * Call with callback_lock or cpuset_mutex held.
536 */
guarantee_online_mems(struct cpuset * cs,nodemask_t * pmask)537 static void guarantee_online_mems(struct cpuset *cs, nodemask_t *pmask)
538 {
539 while (!nodes_and(*pmask, cs->effective_mems, node_states[N_MEMORY]))
540 cs = parent_cs(cs);
541 }
542
543 /**
544 * alloc_cpumasks - Allocate an array of cpumask variables
545 * @pmasks: Pointer to array of cpumask_var_t pointers
546 * @size: Number of cpumasks to allocate
547 * Return: 0 if successful, -ENOMEM otherwise.
548 *
549 * Allocates @size cpumasks and initializes them to empty. Returns 0 on
550 * success, -ENOMEM on allocation failure. On failure, any previously
551 * allocated cpumasks are freed.
552 */
alloc_cpumasks(cpumask_var_t * pmasks[],u32 size)553 static inline int alloc_cpumasks(cpumask_var_t *pmasks[], u32 size)
554 {
555 int i;
556
557 for (i = 0; i < size; i++) {
558 if (!zalloc_cpumask_var(pmasks[i], GFP_KERNEL)) {
559 while (--i >= 0)
560 free_cpumask_var(*pmasks[i]);
561 return -ENOMEM;
562 }
563 }
564 return 0;
565 }
566
567 /**
568 * alloc_tmpmasks - Allocate temporary cpumasks for cpuset operations.
569 * @tmp: Pointer to tmpmasks structure to populate
570 * Return: 0 on success, -ENOMEM on allocation failure
571 */
alloc_tmpmasks(struct tmpmasks * tmp)572 static inline int alloc_tmpmasks(struct tmpmasks *tmp)
573 {
574 /*
575 * Array of pointers to the three cpumask_var_t fields in tmpmasks.
576 * Note: Array size must match actual number of masks (3)
577 */
578 cpumask_var_t *pmask[3] = {
579 &tmp->new_cpus,
580 &tmp->addmask,
581 &tmp->delmask
582 };
583
584 return alloc_cpumasks(pmask, ARRAY_SIZE(pmask));
585 }
586
587 /**
588 * free_tmpmasks - free cpumasks in a tmpmasks structure
589 * @tmp: the tmpmasks structure pointer
590 */
free_tmpmasks(struct tmpmasks * tmp)591 static inline void free_tmpmasks(struct tmpmasks *tmp)
592 {
593 if (!tmp)
594 return;
595
596 free_cpumask_var(tmp->new_cpus);
597 free_cpumask_var(tmp->addmask);
598 free_cpumask_var(tmp->delmask);
599 }
600
601 /**
602 * dup_or_alloc_cpuset - Duplicate or allocate a new cpuset
603 * @cs: Source cpuset to duplicate (NULL for a fresh allocation)
604 *
605 * Creates a new cpuset by either:
606 * 1. Duplicating an existing cpuset (if @cs is non-NULL), or
607 * 2. Allocating a fresh cpuset with zero-initialized masks (if @cs is NULL)
608 *
609 * Return: Pointer to newly allocated cpuset on success, NULL on failure
610 */
dup_or_alloc_cpuset(struct cpuset * cs)611 static struct cpuset *dup_or_alloc_cpuset(struct cpuset *cs)
612 {
613 struct cpuset *trial;
614
615 /* Allocate base structure */
616 trial = cs ? kmemdup(cs, sizeof(*cs), GFP_KERNEL) :
617 kzalloc_obj(*cs);
618 if (!trial)
619 return NULL;
620
621 trial->dl_bw_cpu = -1;
622 init_llist_node(&trial->attach_node);
623
624 /* Setup cpumask pointer array */
625 cpumask_var_t *pmask[4] = {
626 &trial->cpus_allowed,
627 &trial->effective_cpus,
628 &trial->effective_xcpus,
629 &trial->exclusive_cpus
630 };
631
632 if (alloc_cpumasks(pmask, ARRAY_SIZE(pmask))) {
633 kfree(trial);
634 return NULL;
635 }
636
637 /* Copy masks if duplicating */
638 if (cs) {
639 cpumask_copy(trial->cpus_allowed, cs->cpus_allowed);
640 cpumask_copy(trial->effective_cpus, cs->effective_cpus);
641 cpumask_copy(trial->effective_xcpus, cs->effective_xcpus);
642 cpumask_copy(trial->exclusive_cpus, cs->exclusive_cpus);
643 }
644
645 return trial;
646 }
647
648 /**
649 * free_cpuset - free the cpuset
650 * @cs: the cpuset to be freed
651 */
free_cpuset(struct cpuset * cs)652 static inline void free_cpuset(struct cpuset *cs)
653 {
654 free_cpumask_var(cs->cpus_allowed);
655 free_cpumask_var(cs->effective_cpus);
656 free_cpumask_var(cs->effective_xcpus);
657 free_cpumask_var(cs->exclusive_cpus);
658 kfree(cs);
659 }
660
661 /* Return user specified exclusive CPUs */
user_xcpus(struct cpuset * cs)662 static inline struct cpumask *user_xcpus(struct cpuset *cs)
663 {
664 return cpumask_empty(cs->exclusive_cpus) ? cs->cpus_allowed
665 : cs->exclusive_cpus;
666 }
667
xcpus_empty(struct cpuset * cs)668 static inline bool xcpus_empty(struct cpuset *cs)
669 {
670 return cpumask_empty(cs->cpus_allowed) &&
671 cpumask_empty(cs->exclusive_cpus);
672 }
673
674 /*
675 * cpusets_are_exclusive() - check if two cpusets are exclusive
676 *
677 * Return true if exclusive, false if not
678 */
cpusets_are_exclusive(struct cpuset * cs1,struct cpuset * cs2)679 static inline bool cpusets_are_exclusive(struct cpuset *cs1, struct cpuset *cs2)
680 {
681 struct cpumask *xcpus1 = user_xcpus(cs1);
682 struct cpumask *xcpus2 = user_xcpus(cs2);
683
684 if (cpumask_intersects(xcpus1, xcpus2))
685 return false;
686 return true;
687 }
688
689 /**
690 * cpus_excl_conflict - Check if two cpusets have exclusive CPU conflicts
691 * @trial: the trial cpuset to be checked
692 * @sibling: a sibling cpuset to be checked against
693 * @xcpus_changed: set if exclusive_cpus has been set
694 *
695 * Returns: true if CPU exclusivity conflict exists, false otherwise
696 *
697 * Conflict detection rules:
698 * o cgroup v1
699 * See cpuset1_cpus_excl_conflict()
700 * o cgroup v2
701 * - The exclusive_cpus values cannot overlap.
702 * - New exclusive_cpus cannot be a superset of a sibling's cpus_allowed.
703 */
cpus_excl_conflict(struct cpuset * trial,struct cpuset * sibling,bool xcpus_changed)704 static inline bool cpus_excl_conflict(struct cpuset *trial, struct cpuset *sibling,
705 bool xcpus_changed)
706 {
707 if (!cpuset_v2())
708 return cpuset1_cpus_excl_conflict(trial, sibling);
709
710 /* The cpus_allowed of a sibling cpuset cannot be a subset of the new exclusive_cpus */
711 if (xcpus_changed && !cpumask_empty(sibling->cpus_allowed) &&
712 cpumask_subset(sibling->cpus_allowed, trial->exclusive_cpus))
713 return true;
714
715 /* Exclusive_cpus cannot intersect */
716 return cpumask_intersects(trial->exclusive_cpus, sibling->exclusive_cpus);
717 }
718
mems_excl_conflict(struct cpuset * cs1,struct cpuset * cs2)719 static inline bool mems_excl_conflict(struct cpuset *cs1, struct cpuset *cs2)
720 {
721 if ((is_mem_exclusive(cs1) || is_mem_exclusive(cs2)))
722 return nodes_intersects(cs1->mems_allowed, cs2->mems_allowed);
723 return false;
724 }
725
726 /*
727 * validate_change() - Used to validate that any proposed cpuset change
728 * follows the structural rules for cpusets.
729 *
730 * If we replaced the flag and mask values of the current cpuset
731 * (cur) with those values in the trial cpuset (trial), would
732 * our various subset and exclusive rules still be valid? Presumes
733 * cpuset_mutex held.
734 *
735 * 'cur' is the address of an actual, in-use cpuset. Operations
736 * such as list traversal that depend on the actual address of the
737 * cpuset in the list must use cur below, not trial.
738 *
739 * 'trial' is the address of bulk structure copy of cur, with
740 * perhaps one or more of the fields cpus_allowed, mems_allowed,
741 * or flags changed to new, trial values.
742 *
743 * Return 0 if valid, -errno if not.
744 */
745
validate_change(struct cpuset * cur,struct cpuset * trial)746 static int validate_change(struct cpuset *cur, struct cpuset *trial)
747 {
748 struct cgroup_subsys_state *css;
749 struct cpuset *c, *par;
750 bool xcpus_changed;
751 int ret = 0;
752
753 rcu_read_lock();
754
755 if (!is_in_v2_mode())
756 ret = cpuset1_validate_change(cur, trial);
757 if (ret)
758 goto out;
759
760 /* Remaining checks don't apply to root cpuset */
761 if (cur == &top_cpuset)
762 goto out;
763
764 par = parent_cs(cur);
765
766 /*
767 * We can't shrink if we won't have enough room for SCHED_DEADLINE
768 * tasks. This check is not done when scheduling is disabled as the
769 * users should know what they are doing.
770 *
771 * For v1, effective_cpus == cpus_allowed & user_xcpus() returns
772 * cpus_allowed.
773 *
774 * For v2, is_cpu_exclusive() & is_sched_load_balance() are true only
775 * for non-isolated partition root. At this point, the target
776 * effective_cpus isn't computed yet. user_xcpus() is the best
777 * approximation.
778 *
779 * TBD: May need to precompute the real effective_cpus here in case
780 * incorrect scheduling of SCHED_DEADLINE tasks in a partition
781 * becomes an issue.
782 */
783 ret = -EBUSY;
784 if (is_cpu_exclusive(cur) && is_sched_load_balance(cur) &&
785 !cpuset_cpumask_can_shrink(cur->effective_cpus, user_xcpus(trial)))
786 goto out;
787
788 /*
789 * If either I or some sibling (!= me) is exclusive, we can't
790 * overlap. exclusive_cpus cannot overlap with each other if set.
791 */
792 ret = -EINVAL;
793 xcpus_changed = !cpumask_equal(cur->exclusive_cpus, trial->exclusive_cpus);
794 cpuset_for_each_child(c, css, par) {
795 if (c == cur)
796 continue;
797 if (cpus_excl_conflict(trial, c, xcpus_changed))
798 goto out;
799 if (mems_excl_conflict(trial, c))
800 goto out;
801 }
802
803 ret = 0;
804 out:
805 rcu_read_unlock();
806 return ret;
807 }
808
809 #ifdef CONFIG_SMP
810
811 /*
812 * generate_sched_domains()
813 *
814 * This function builds a partial partition of the systems CPUs
815 * A 'partial partition' is a set of non-overlapping subsets whose
816 * union is a subset of that set.
817 * The output of this function needs to be passed to kernel/sched/core.c
818 * partition_sched_domains() routine, which will rebuild the scheduler's
819 * load balancing domains (sched domains) as specified by that partial
820 * partition.
821 *
822 * See "What is sched_load_balance" in Documentation/admin-guide/cgroup-v1/cpusets.rst
823 * for a background explanation of this.
824 *
825 * Does not return errors, on the theory that the callers of this
826 * routine would rather not worry about failures to rebuild sched
827 * domains when operating in the severe memory shortage situations
828 * that could cause allocation failures below.
829 *
830 * Must be called with cpuset_mutex held.
831 *
832 * The three key local variables below are:
833 * cp - cpuset pointer, used (together with pos_css) to perform a
834 * top-down scan of all cpusets. For our purposes, rebuilding
835 * the schedulers sched domains, we can ignore !is_sched_load_
836 * balance cpusets.
837 * csa - (for CpuSet Array) Array of pointers to all the cpusets
838 * that need to be load balanced, for convenient iterative
839 * access by the subsequent code that finds the best partition,
840 * i.e the set of domains (subsets) of CPUs such that the
841 * cpus_allowed of every cpuset marked is_sched_load_balance
842 * is a subset of one of these domains, while there are as
843 * many such domains as possible, each as small as possible.
844 * doms - Conversion of 'csa' to an array of cpumasks, for passing to
845 * the kernel/sched/core.c routine partition_sched_domains() in a
846 * convenient format, that can be easily compared to the prior
847 * value to determine what partition elements (sched domains)
848 * were changed (added or removed.)
849 */
generate_sched_domains(cpumask_var_t ** domains,struct sched_domain_attr ** attributes)850 static int generate_sched_domains(cpumask_var_t **domains,
851 struct sched_domain_attr **attributes)
852 {
853 struct cpuset *cp; /* top-down scan of cpusets */
854 struct cpuset **csa; /* array of all cpuset ptrs */
855 int i, j; /* indices for partition finding loops */
856 cpumask_var_t *doms; /* resulting partition; i.e. sched domains */
857 struct sched_domain_attr *dattr; /* attributes for custom domains */
858 int ndoms = 0; /* number of sched domains in result */
859 struct cgroup_subsys_state *pos_css;
860
861 if (!cpuset_v2())
862 return cpuset1_generate_sched_domains(domains, attributes);
863
864 doms = NULL;
865 dattr = NULL;
866 csa = NULL;
867
868 /* Special case for the 99% of systems with one, full, sched domain */
869 if (cpumask_empty(subpartitions_cpus)) {
870 ndoms = 1;
871 /* !csa will be checked and can be correctly handled */
872 goto generate_doms;
873 }
874
875 csa = kmalloc_objs(cp, nr_cpusets());
876 if (!csa)
877 goto done;
878
879 /* Find how many partitions and cache them to csa[] */
880 rcu_read_lock();
881 cpuset_for_each_descendant_pre(cp, pos_css, &top_cpuset) {
882 /*
883 * Only valid partition roots that are not isolated and with
884 * non-empty effective_cpus will be saved into csa[].
885 */
886 if ((cp->partition_root_state == PRS_ROOT) &&
887 !cpumask_empty(cp->effective_cpus))
888 csa[ndoms++] = cp;
889
890 /*
891 * Skip @cp's subtree if not a partition root and has no
892 * exclusive CPUs to be granted to child cpusets.
893 */
894 if (!is_partition_valid(cp) && cpumask_empty(cp->exclusive_cpus))
895 pos_css = css_rightmost_descendant(pos_css);
896 }
897 rcu_read_unlock();
898
899 for (i = 0; i < ndoms; i++) {
900 for (j = i + 1; j < ndoms; j++) {
901 if (cpusets_overlap(csa[i], csa[j]))
902 /*
903 * Cgroup v2 shouldn't pass down overlapping
904 * partition root cpusets.
905 */
906 WARN_ON_ONCE(1);
907 }
908 }
909
910 generate_doms:
911 doms = alloc_sched_domains(ndoms);
912 if (!doms)
913 goto done;
914
915 /*
916 * The rest of the code, including the scheduler, can deal with
917 * dattr==NULL case. No need to abort if alloc fails.
918 */
919 dattr = kmalloc_objs(struct sched_domain_attr, ndoms);
920
921 /*
922 * Cgroup v2 doesn't support domain attributes, just set all of them
923 * to SD_ATTR_INIT. Also non-isolating partition root CPUs are a
924 * subset of HK_TYPE_DOMAIN_BOOT housekeeping CPUs.
925 */
926 for (i = 0; i < ndoms; i++) {
927 /*
928 * The top cpuset may contain some boot time isolated
929 * CPUs that need to be excluded from the sched domain.
930 */
931 if (!csa || csa[i] == &top_cpuset)
932 cpumask_and(doms[i], top_cpuset.effective_cpus,
933 housekeeping_cpumask(HK_TYPE_DOMAIN_BOOT));
934 else
935 cpumask_copy(doms[i], csa[i]->effective_cpus);
936 if (dattr)
937 dattr[i] = SD_ATTR_INIT;
938 }
939
940 done:
941 kfree(csa);
942
943 /*
944 * Fallback to the default domain if kmalloc() failed.
945 * See comments in partition_sched_domains().
946 */
947 if (doms == NULL)
948 ndoms = 1;
949
950 *domains = doms;
951 *attributes = dattr;
952 return ndoms;
953 }
954
dl_update_tasks_root_domain(struct cpuset * cs)955 static void dl_update_tasks_root_domain(struct cpuset *cs)
956 {
957 struct css_task_iter it;
958 struct task_struct *task;
959
960 if (atomic_read(&cs->nr_deadline_tasks) == 0)
961 return;
962
963 css_task_iter_start(&cs->css, 0, &it);
964
965 while ((task = css_task_iter_next(&it)))
966 dl_add_task_root_domain(task);
967
968 css_task_iter_end(&it);
969 }
970
dl_rebuild_rd_accounting(void)971 void dl_rebuild_rd_accounting(void)
972 {
973 struct cpuset *cs = NULL;
974 struct cgroup_subsys_state *pos_css;
975 int cpu;
976 u64 cookie = ++dl_cookie;
977
978 lockdep_assert_cpuset_lock_held();
979 lockdep_assert_cpus_held();
980 lockdep_assert_held(&sched_domains_mutex);
981
982 rcu_read_lock();
983
984 for_each_possible_cpu(cpu) {
985 if (dl_bw_visited(cpu, cookie))
986 continue;
987
988 dl_clear_root_domain_cpu(cpu);
989 }
990
991 cpuset_for_each_descendant_pre(cs, pos_css, &top_cpuset) {
992
993 if (cpumask_empty(cs->effective_cpus)) {
994 pos_css = css_rightmost_descendant(pos_css);
995 continue;
996 }
997
998 css_get(&cs->css);
999
1000 rcu_read_unlock();
1001
1002 dl_update_tasks_root_domain(cs);
1003
1004 rcu_read_lock();
1005 css_put(&cs->css);
1006 }
1007 rcu_read_unlock();
1008 }
1009
1010 /*
1011 * Rebuild scheduler domains.
1012 *
1013 * If the flag 'sched_load_balance' of any cpuset with non-empty
1014 * 'cpus' changes, or if the 'cpus' allowed changes in any cpuset
1015 * which has that flag enabled, or if any cpuset with a non-empty
1016 * 'cpus' is removed, then call this routine to rebuild the
1017 * scheduler's dynamic sched domains.
1018 *
1019 * Call with cpuset_mutex held. Takes cpus_read_lock().
1020 */
rebuild_sched_domains_locked(void)1021 void rebuild_sched_domains_locked(void)
1022 {
1023 struct sched_domain_attr *attr;
1024 cpumask_var_t *doms;
1025 int ndoms;
1026 int i;
1027
1028 lockdep_assert_cpus_held();
1029 lockdep_assert_cpuset_lock_held();
1030 force_sd_rebuild = false;
1031
1032 /* Generate domain masks and attrs */
1033 ndoms = generate_sched_domains(&doms, &attr);
1034
1035 /*
1036 * cpuset_hotplug_workfn is invoked synchronously now, thus this
1037 * function should not race with CPU hotplug. And the effective CPUs
1038 * must not include any offline CPUs. Passing an offline CPU in the
1039 * doms to partition_sched_domains() will trigger a kernel panic.
1040 *
1041 * We perform a final check here: if the doms contains any
1042 * offline CPUs, a warning is emitted and we return directly to
1043 * prevent the panic.
1044 */
1045 for (i = 0; doms && i < ndoms; i++) {
1046 if (WARN_ON_ONCE(!cpumask_subset(doms[i], cpu_active_mask))) {
1047 free_sched_domains(doms, ndoms);
1048 kfree(attr);
1049 return;
1050 }
1051 }
1052
1053 /* Have scheduler rebuild the domains */
1054 partition_sched_domains(ndoms, doms, attr);
1055 }
1056 #else /* !CONFIG_SMP */
rebuild_sched_domains_locked(void)1057 void rebuild_sched_domains_locked(void)
1058 {
1059 }
1060 #endif /* CONFIG_SMP */
1061
rebuild_sched_domains_cpuslocked(void)1062 static void rebuild_sched_domains_cpuslocked(void)
1063 {
1064 mutex_lock(&cpuset_mutex);
1065 rebuild_sched_domains_locked();
1066 mutex_unlock(&cpuset_mutex);
1067 }
1068
rebuild_sched_domains(void)1069 void rebuild_sched_domains(void)
1070 {
1071 cpus_read_lock();
1072 rebuild_sched_domains_cpuslocked();
1073 cpus_read_unlock();
1074 }
1075
cpuset_reset_sched_domains(void)1076 void cpuset_reset_sched_domains(void)
1077 {
1078 mutex_lock(&cpuset_mutex);
1079 partition_sched_domains(1, NULL, NULL);
1080 mutex_unlock(&cpuset_mutex);
1081 }
1082
1083 /**
1084 * cpuset_update_tasks_cpumask - Update the cpumasks of tasks in the cpuset.
1085 * @cs: the cpuset in which each task's cpus_allowed mask needs to be changed
1086 * @new_cpus: the temp variable for the new effective_cpus mask
1087 *
1088 * Iterate through each task of @cs updating its cpus_allowed to the
1089 * effective cpuset's. As this function is called with cpuset_mutex held,
1090 * cpuset membership stays stable.
1091 *
1092 * For top_cpuset, task_cpu_possible_mask() is used instead of effective_cpus
1093 * to make sure all offline CPUs are also included as hotplug code won't
1094 * update cpumasks for tasks in top_cpuset.
1095 *
1096 * As task_cpu_possible_mask() can be task dependent in arm64, we have to
1097 * do cpu masking per task instead of doing it once for all.
1098 */
cpuset_update_tasks_cpumask(struct cpuset * cs,struct cpumask * new_cpus)1099 void cpuset_update_tasks_cpumask(struct cpuset *cs, struct cpumask *new_cpus)
1100 {
1101 struct css_task_iter it;
1102 struct task_struct *task;
1103 bool top_cs = cs == &top_cpuset;
1104
1105 css_task_iter_start(&cs->css, 0, &it);
1106 while ((task = css_task_iter_next(&it))) {
1107 const struct cpumask *possible_mask = task_cpu_possible_mask(task);
1108
1109 if (top_cs) {
1110 /*
1111 * PF_KTHREAD tasks are handled by housekeeping.
1112 * PF_NO_SETAFFINITY tasks are ignored.
1113 */
1114 if (task->flags & (PF_KTHREAD | PF_NO_SETAFFINITY))
1115 continue;
1116 cpumask_andnot(new_cpus, possible_mask, subpartitions_cpus);
1117 } else {
1118 cpumask_and(new_cpus, possible_mask, cs->effective_cpus);
1119 }
1120 set_cpus_allowed_ptr(task, new_cpus);
1121 }
1122 css_task_iter_end(&it);
1123 }
1124
1125 /**
1126 * compute_effective_cpumask - Compute the effective cpumask of the cpuset
1127 * @new_cpus: the temp variable for the new effective_cpus mask
1128 * @cs: the cpuset the need to recompute the new effective_cpus mask
1129 * @parent: the parent cpuset
1130 *
1131 * For v2, the parent's effective_cpus is inherited if cpumask is empty.
1132 * The result is valid only if the given cpuset isn't a partition root.
1133 */
compute_effective_cpumask(struct cpumask * new_cpus,struct cpuset * cs,struct cpuset * parent)1134 static void compute_effective_cpumask(struct cpumask *new_cpus,
1135 struct cpuset *cs, struct cpuset *parent)
1136 {
1137 bool has_cpus;
1138
1139 has_cpus = cpumask_and(new_cpus, cs->cpus_allowed, parent->effective_cpus);
1140 if (!has_cpus && is_in_v2_mode())
1141 cpumask_copy(new_cpus, parent->effective_cpus);
1142 }
1143
1144 /**
1145 * compute_effective_nodemask - Compute the effective nodemask of the cpuset
1146 * @new_mems: the temp variable for the new effective_mems mask
1147 * @cs: the cpuset the need to recompute the new effective_mems mask
1148 * @parent: the parent cpuset
1149 *
1150 * For v2, the parent's effective_mems is inherited if nodemask is empty.
1151 */
compute_effective_nodemask(nodemask_t * new_mems,struct cpuset * cs,struct cpuset * parent)1152 static void compute_effective_nodemask(nodemask_t *new_mems,
1153 struct cpuset *cs, struct cpuset *parent)
1154 {
1155 bool has_mems;
1156
1157 has_mems = nodes_and(*new_mems, cs->mems_allowed, parent->effective_mems);
1158 if (!has_mems && is_in_v2_mode())
1159 nodes_copy(*new_mems, parent->effective_mems);
1160 }
1161
1162 /*
1163 * Commands for update_parent_effective_cpumask
1164 */
1165 enum partition_cmd {
1166 partcmd_enable, /* Enable partition root */
1167 partcmd_enablei, /* Enable isolated partition root */
1168 partcmd_disable, /* Disable partition root */
1169 partcmd_update, /* Update parent's effective_cpus */
1170 partcmd_invalidate, /* Make partition invalid */
1171 };
1172
1173 static void update_sibling_cpumasks(struct cpuset *parent, struct cpuset *cs,
1174 struct tmpmasks *tmp);
1175
1176 /*
1177 * Update partition exclusive flag
1178 *
1179 * Return: 0 if successful, an error code otherwise
1180 */
update_partition_exclusive_flag(struct cpuset * cs,int new_prs)1181 static int update_partition_exclusive_flag(struct cpuset *cs, int new_prs)
1182 {
1183 bool exclusive = (new_prs > PRS_MEMBER);
1184
1185 if (exclusive && !is_cpu_exclusive(cs)) {
1186 if (cpuset_update_flag(CS_CPU_EXCLUSIVE, cs, 1))
1187 return PERR_NOTEXCL;
1188 } else if (!exclusive && is_cpu_exclusive(cs)) {
1189 /* Turning off CS_CPU_EXCLUSIVE will not return error */
1190 cpuset_update_flag(CS_CPU_EXCLUSIVE, cs, 0);
1191 }
1192 return 0;
1193 }
1194
1195 /*
1196 * Update partition load balance flag and/or rebuild sched domain
1197 *
1198 * Changing load balance flag will automatically call
1199 * rebuild_sched_domains_locked().
1200 * This function is for cgroup v2 only.
1201 */
update_partition_sd_lb(struct cpuset * cs,int old_prs)1202 static void update_partition_sd_lb(struct cpuset *cs, int old_prs)
1203 {
1204 int new_prs = cs->partition_root_state;
1205 bool rebuild_domains = (new_prs > 0) || (old_prs > 0);
1206 bool new_lb;
1207
1208 /*
1209 * If cs is not a valid partition root, the load balance state
1210 * will follow its parent.
1211 */
1212 if (new_prs > 0) {
1213 new_lb = (new_prs != PRS_ISOLATED);
1214 } else {
1215 new_lb = is_sched_load_balance(parent_cs(cs));
1216 }
1217 if (new_lb != !!is_sched_load_balance(cs)) {
1218 rebuild_domains = true;
1219 if (new_lb)
1220 set_bit(CS_SCHED_LOAD_BALANCE, &cs->flags);
1221 else
1222 clear_bit(CS_SCHED_LOAD_BALANCE, &cs->flags);
1223 }
1224
1225 if (rebuild_domains)
1226 cpuset_force_rebuild();
1227 }
1228
1229 /*
1230 * tasks_nocpu_error - Return true if tasks will have no effective_cpus
1231 */
tasks_nocpu_error(struct cpuset * parent,struct cpuset * cs,struct cpumask * xcpus)1232 static bool tasks_nocpu_error(struct cpuset *parent, struct cpuset *cs,
1233 struct cpumask *xcpus)
1234 {
1235 /*
1236 * A populated partition (cs or parent) can't have empty effective_cpus
1237 */
1238 return (cpumask_subset(parent->effective_cpus, xcpus) &&
1239 partition_is_populated(parent, cs)) ||
1240 (!cpumask_intersects(xcpus, cpu_active_mask) &&
1241 partition_is_populated(cs, NULL));
1242 }
1243
reset_partition_data(struct cpuset * cs)1244 static void reset_partition_data(struct cpuset *cs)
1245 {
1246 struct cpuset *parent = parent_cs(cs);
1247
1248 if (!cpuset_v2())
1249 return;
1250
1251 lockdep_assert_held(&callback_lock);
1252
1253 if (cpumask_empty(cs->exclusive_cpus)) {
1254 cpumask_clear(cs->effective_xcpus);
1255 if (is_cpu_exclusive(cs))
1256 clear_bit(CS_CPU_EXCLUSIVE, &cs->flags);
1257 }
1258 if (!cpumask_and(cs->effective_cpus, parent->effective_cpus, cs->cpus_allowed))
1259 cpumask_copy(cs->effective_cpus, parent->effective_cpus);
1260 }
1261
1262 /* Return true if isolated_cpus changes. */
isolated_cpu_update(int new_prs,int cpu)1263 static bool isolated_cpu_update(int new_prs, int cpu)
1264 {
1265 lockdep_assert_held(&callback_lock);
1266 lockdep_assert_held(&cpuset_mutex);
1267
1268 if (new_prs == PRS_ISOLATED) {
1269 if (cpumask_test_cpu(cpu, isolated_cpus))
1270 return false;
1271 cpumask_set_cpu(cpu, isolated_cpus);
1272 return true;
1273 }
1274
1275 /* CPUs isolated at boot must remain isolated. */
1276 if (!cpumask_test_cpu(cpu,
1277 housekeeping_cpumask(HK_TYPE_DOMAIN_BOOT)) ||
1278 !cpumask_test_cpu(cpu, isolated_cpus))
1279 return false;
1280 cpumask_clear_cpu(cpu, isolated_cpus);
1281 return true;
1282 }
1283
1284 /*
1285 * isolated_cpus_update - Update the isolated_cpus mask
1286 * @old_prs: old partition_root_state
1287 * @new_prs: new partition_root_state
1288 * @xcpus: exclusive CPUs with state change
1289 */
isolated_cpus_update(int old_prs,int new_prs,struct cpumask * xcpus)1290 static void isolated_cpus_update(int old_prs, int new_prs, struct cpumask *xcpus)
1291 {
1292 bool updated = false;
1293 int cpu;
1294
1295 WARN_ON_ONCE(old_prs == new_prs);
1296 lockdep_assert_held(&callback_lock);
1297 lockdep_assert_held(&cpuset_mutex);
1298 for_each_cpu(cpu, xcpus)
1299 updated |= isolated_cpu_update(new_prs, cpu);
1300 if (updated)
1301 update_housekeeping = true;
1302 }
1303
1304 /*
1305 * partition_xcpus_add - Add new exclusive CPUs to partition
1306 * @new_prs: new partition_root_state
1307 * @parent: parent cpuset
1308 * @xcpus: exclusive CPUs to be added
1309 *
1310 * Remote partition if parent == NULL
1311 */
partition_xcpus_add(int new_prs,struct cpuset * parent,struct cpumask * xcpus)1312 static void partition_xcpus_add(int new_prs, struct cpuset *parent,
1313 struct cpumask *xcpus)
1314 {
1315 WARN_ON_ONCE(new_prs < 0);
1316 lockdep_assert_held(&callback_lock);
1317 if (!parent)
1318 parent = &top_cpuset;
1319
1320
1321 if (parent == &top_cpuset)
1322 cpumask_or(subpartitions_cpus, subpartitions_cpus, xcpus);
1323
1324 if (new_prs != parent->partition_root_state)
1325 isolated_cpus_update(parent->partition_root_state, new_prs,
1326 xcpus);
1327
1328 cpumask_andnot(parent->effective_cpus, parent->effective_cpus, xcpus);
1329 }
1330
1331 /*
1332 * partition_xcpus_del - Remove exclusive CPUs from partition
1333 * @old_prs: old partition_root_state
1334 * @parent: parent cpuset
1335 * @xcpus: exclusive CPUs to be removed
1336 *
1337 * Remote partition if parent == NULL
1338 */
partition_xcpus_del(int old_prs,struct cpuset * parent,struct cpumask * xcpus)1339 static void partition_xcpus_del(int old_prs, struct cpuset *parent,
1340 struct cpumask *xcpus)
1341 {
1342 WARN_ON_ONCE(old_prs < 0);
1343 lockdep_assert_held(&callback_lock);
1344 if (!parent)
1345 parent = &top_cpuset;
1346
1347 if (parent == &top_cpuset)
1348 cpumask_andnot(subpartitions_cpus, subpartitions_cpus, xcpus);
1349
1350 if (old_prs != parent->partition_root_state)
1351 isolated_cpus_update(old_prs, parent->partition_root_state,
1352 xcpus);
1353
1354 cpumask_or(parent->effective_cpus, parent->effective_cpus, xcpus);
1355 cpumask_and(parent->effective_cpus, parent->effective_cpus, cpu_active_mask);
1356 }
1357
1358 /*
1359 * isolated_cpus_can_update - check for isolated & nohz_full conflicts
1360 * @add_cpus: cpu mask for cpus that are going to be isolated
1361 * @del_cpus: cpu mask for cpus that are no longer isolated, can be NULL
1362 * Return: false if there is conflict, true otherwise
1363 *
1364 * If nohz_full is enabled and we have isolated CPUs, their combination must
1365 * still leave housekeeping CPUs.
1366 *
1367 * TBD: Should consider merging this function into
1368 * prstate_housekeeping_conflict().
1369 */
isolated_cpus_can_update(struct cpumask * add_cpus,struct cpumask * del_cpus)1370 static bool isolated_cpus_can_update(struct cpumask *add_cpus,
1371 struct cpumask *del_cpus)
1372 {
1373 cpumask_var_t full_hk_cpus;
1374 int res = true;
1375
1376 if (!housekeeping_enabled(HK_TYPE_KERNEL_NOISE))
1377 return true;
1378
1379 if (del_cpus && cpumask_weight_and(del_cpus,
1380 housekeeping_cpumask(HK_TYPE_KERNEL_NOISE)))
1381 return true;
1382
1383 if (!alloc_cpumask_var(&full_hk_cpus, GFP_KERNEL))
1384 return false;
1385
1386 cpumask_and(full_hk_cpus, housekeeping_cpumask(HK_TYPE_KERNEL_NOISE),
1387 housekeeping_cpumask(HK_TYPE_DOMAIN));
1388 cpumask_andnot(full_hk_cpus, full_hk_cpus, isolated_cpus);
1389 cpumask_and(full_hk_cpus, full_hk_cpus, cpu_active_mask);
1390 if (!cpumask_weight_andnot(full_hk_cpus, add_cpus))
1391 res = false;
1392
1393 free_cpumask_var(full_hk_cpus);
1394 return res;
1395 }
1396
1397 /*
1398 * prstate_housekeeping_conflict - check for partition & housekeeping conflicts
1399 * @prstate: partition root state to be checked
1400 * @new_cpus: cpu mask
1401 * Return: true if there is conflict, false otherwise
1402 *
1403 * CPUs outside of HK_TYPE_DOMAIN_BOOT, if defined, can only be used in an
1404 * isolated partition.
1405 */
prstate_housekeeping_conflict(int prstate,struct cpumask * new_cpus)1406 static bool prstate_housekeeping_conflict(int prstate, struct cpumask *new_cpus)
1407 {
1408 if (!housekeeping_enabled(HK_TYPE_DOMAIN_BOOT))
1409 return false;
1410
1411 if ((prstate != PRS_ISOLATED) &&
1412 !cpumask_subset(new_cpus, housekeeping_cpumask(HK_TYPE_DOMAIN_BOOT)))
1413 return true;
1414
1415 return false;
1416 }
1417
1418 /*
1419 * cpuset_update_sd_hk_unlock - Rebuild sched domains, update HK & unlock
1420 *
1421 * Update housekeeping cpumasks and rebuild sched domains if necessary and
1422 * then do a cpuset_full_unlock().
1423 * This should be called at the end of cpuset operation.
1424 */
cpuset_update_sd_hk_unlock(void)1425 static void cpuset_update_sd_hk_unlock(void)
1426 __releases(&cpuset_mutex)
1427 __releases(&cpuset_top_mutex)
1428 {
1429 /* force_sd_rebuild will be cleared in rebuild_sched_domains_locked() */
1430 if (force_sd_rebuild)
1431 rebuild_sched_domains_locked();
1432
1433 if (update_housekeeping) {
1434 update_housekeeping = false;
1435 cpumask_copy(isolated_hk_cpus, isolated_cpus);
1436
1437 /*
1438 * housekeeping_update() is now called without holding
1439 * cpus_read_lock and cpuset_mutex. Only cpuset_top_mutex
1440 * is still being held for mutual exclusion.
1441 */
1442 mutex_unlock(&cpuset_mutex);
1443 cpus_read_unlock();
1444 WARN_ON_ONCE(housekeeping_update(isolated_hk_cpus));
1445 mutex_unlock(&cpuset_top_mutex);
1446 } else {
1447 cpuset_full_unlock();
1448 }
1449 }
1450
1451 /*
1452 * Work function to invoke cpuset_update_sd_hk_unlock()
1453 */
hk_sd_workfn(struct work_struct * work)1454 static void hk_sd_workfn(struct work_struct *work)
1455 {
1456 cpuset_full_lock();
1457 cpuset_update_sd_hk_unlock();
1458 }
1459
1460 /**
1461 * rm_siblings_excl_cpus - Remove exclusive CPUs that are used by sibling cpusets
1462 * @parent: Parent cpuset containing all siblings
1463 * @cs: Current cpuset (will be skipped)
1464 * @excpus: exclusive effective CPU mask to modify
1465 *
1466 * This function ensures the given @excpus mask doesn't include any CPUs that
1467 * are exclusively allocated to sibling cpusets. It walks through all siblings
1468 * of @cs under @parent and removes their exclusive CPUs from @excpus.
1469 */
rm_siblings_excl_cpus(struct cpuset * parent,struct cpuset * cs,struct cpumask * excpus)1470 static int rm_siblings_excl_cpus(struct cpuset *parent, struct cpuset *cs,
1471 struct cpumask *excpus)
1472 {
1473 struct cgroup_subsys_state *css;
1474 struct cpuset *sibling;
1475 int retval = 0;
1476
1477 if (cpumask_empty(excpus))
1478 return 0;
1479
1480 /*
1481 * Remove exclusive CPUs from siblings
1482 */
1483 rcu_read_lock();
1484 cpuset_for_each_child(sibling, css, parent) {
1485 struct cpumask *sibling_xcpus;
1486
1487 if (sibling == cs)
1488 continue;
1489
1490 /*
1491 * If exclusive_cpus is defined, effective_xcpus will always
1492 * be a subset. Otherwise, effective_xcpus will only be set
1493 * in a valid partition root.
1494 */
1495 sibling_xcpus = cpumask_empty(sibling->exclusive_cpus)
1496 ? sibling->effective_xcpus
1497 : sibling->exclusive_cpus;
1498
1499 if (cpumask_intersects(excpus, sibling_xcpus)) {
1500 cpumask_andnot(excpus, excpus, sibling_xcpus);
1501 retval++;
1502 }
1503 }
1504 rcu_read_unlock();
1505
1506 return retval;
1507 }
1508
1509 /*
1510 * compute_excpus - compute effective exclusive CPUs
1511 * @cs: cpuset
1512 * @xcpus: effective exclusive CPUs value to be set
1513 * Return: 0 if there is no sibling conflict, > 0 otherwise
1514 *
1515 * If exclusive_cpus isn't explicitly set , we have to scan the sibling cpusets
1516 * and exclude their exclusive_cpus or effective_xcpus as well.
1517 */
compute_excpus(struct cpuset * cs,struct cpumask * excpus)1518 static int compute_excpus(struct cpuset *cs, struct cpumask *excpus)
1519 {
1520 struct cpuset *parent = parent_cs(cs);
1521
1522 cpumask_and(excpus, user_xcpus(cs), parent->effective_xcpus);
1523
1524 if (!cpumask_empty(cs->exclusive_cpus))
1525 return 0;
1526
1527 return rm_siblings_excl_cpus(parent, cs, excpus);
1528 }
1529
1530 /*
1531 * compute_trialcs_excpus - Compute effective exclusive CPUs for a trial cpuset
1532 * @trialcs: The trial cpuset containing the proposed new configuration
1533 * @cs: The original cpuset that the trial configuration is based on
1534 * Return: 0 if successful with no sibling conflict, >0 if a conflict is found
1535 *
1536 * Computes the effective_xcpus for a trial configuration. @cs is provided to represent
1537 * the real cs.
1538 */
compute_trialcs_excpus(struct cpuset * trialcs,struct cpuset * cs)1539 static int compute_trialcs_excpus(struct cpuset *trialcs, struct cpuset *cs)
1540 {
1541 struct cpuset *parent = parent_cs(trialcs);
1542 struct cpumask *excpus = trialcs->effective_xcpus;
1543
1544 /* trialcs is member, cpuset.cpus has no impact to excpus */
1545 if (cs_is_member(cs))
1546 cpumask_and(excpus, trialcs->exclusive_cpus,
1547 parent->effective_xcpus);
1548 else
1549 cpumask_and(excpus, user_xcpus(trialcs), parent->effective_xcpus);
1550
1551 return rm_siblings_excl_cpus(parent, cs, excpus);
1552 }
1553
is_remote_partition(struct cpuset * cs)1554 static inline bool is_remote_partition(struct cpuset *cs)
1555 {
1556 return cs->remote_partition;
1557 }
1558
is_local_partition(struct cpuset * cs)1559 static inline bool is_local_partition(struct cpuset *cs)
1560 {
1561 return is_partition_valid(cs) && !is_remote_partition(cs);
1562 }
1563
1564 /*
1565 * remote_partition_enable - Enable current cpuset as a remote partition root
1566 * @cs: the cpuset to update
1567 * @new_prs: new partition_root_state
1568 * @tmp: temporary masks
1569 * Return: 0 if successful, errcode if error
1570 *
1571 * Enable the current cpuset to become a remote partition root taking CPUs
1572 * directly from the top cpuset. cpuset_mutex must be held by the caller.
1573 */
remote_partition_enable(struct cpuset * cs,int new_prs,struct tmpmasks * tmp)1574 static int remote_partition_enable(struct cpuset *cs, int new_prs,
1575 struct tmpmasks *tmp)
1576 {
1577 /*
1578 * The user must have sysadmin privilege.
1579 */
1580 if (!capable(CAP_SYS_ADMIN))
1581 return PERR_ACCESS;
1582
1583 /*
1584 * The requested exclusive_cpus must not be allocated to other
1585 * partitions and it can't use up all the root's effective_cpus.
1586 *
1587 * The effective_xcpus mask can contain offline CPUs, but there must
1588 * be at least one or more online CPUs present before it can be enabled.
1589 *
1590 * Note that creating a remote partition with any local partition root
1591 * above it or remote partition root underneath it is not allowed.
1592 */
1593 compute_excpus(cs, tmp->new_cpus);
1594 WARN_ON_ONCE(cpumask_intersects(tmp->new_cpus, subpartitions_cpus));
1595 if (!cpumask_intersects(tmp->new_cpus, cpu_active_mask) ||
1596 cpumask_subset(top_cpuset.effective_cpus, tmp->new_cpus))
1597 return PERR_INVCPUS;
1598 if (((new_prs == PRS_ISOLATED) &&
1599 !isolated_cpus_can_update(tmp->new_cpus, NULL)) ||
1600 prstate_housekeeping_conflict(new_prs, tmp->new_cpus))
1601 return PERR_HKEEPING;
1602
1603 spin_lock_irq(&callback_lock);
1604 partition_xcpus_add(new_prs, NULL, tmp->new_cpus);
1605 cs->remote_partition = true;
1606 cpumask_copy(cs->effective_xcpus, tmp->new_cpus);
1607 spin_unlock_irq(&callback_lock);
1608 cpuset_force_rebuild();
1609 WRITE_ONCE(cs->prs_err, 0);
1610
1611 /*
1612 * Propagate changes in top_cpuset's effective_cpus down the hierarchy.
1613 */
1614 cpuset_update_tasks_cpumask(&top_cpuset, tmp->new_cpus);
1615 update_sibling_cpumasks(&top_cpuset, NULL, tmp);
1616 return 0;
1617 }
1618
1619 /*
1620 * remote_partition_disable - Remove current cpuset from remote partition list
1621 * @cs: the cpuset to update
1622 * @tmp: temporary masks
1623 *
1624 * The effective_cpus is also updated.
1625 *
1626 * cpuset_mutex must be held by the caller.
1627 */
remote_partition_disable(struct cpuset * cs,struct tmpmasks * tmp)1628 static void remote_partition_disable(struct cpuset *cs, struct tmpmasks *tmp)
1629 {
1630 WARN_ON_ONCE(!is_remote_partition(cs));
1631 /*
1632 * When a CPU is offlined, top_cpuset may end up with no available CPUs,
1633 * which should clear subpartitions_cpus. We should not emit a warning for this
1634 * scenario: the hierarchy is updated from top to bottom, so subpartitions_cpus
1635 * may already be cleared when disabling the partition.
1636 */
1637 WARN_ON_ONCE(!cpumask_subset(cs->effective_xcpus, subpartitions_cpus) &&
1638 !cpumask_empty(subpartitions_cpus));
1639
1640 spin_lock_irq(&callback_lock);
1641 cs->remote_partition = false;
1642 partition_xcpus_del(cs->partition_root_state, NULL, cs->effective_xcpus);
1643 if (cs->prs_err)
1644 cs->partition_root_state = -cs->partition_root_state;
1645 else
1646 cs->partition_root_state = PRS_MEMBER;
1647
1648 /* effective_xcpus may need to be changed */
1649 compute_excpus(cs, cs->effective_xcpus);
1650 reset_partition_data(cs);
1651 spin_unlock_irq(&callback_lock);
1652 cpuset_force_rebuild();
1653
1654 /*
1655 * Propagate changes in top_cpuset's effective_cpus down the hierarchy.
1656 */
1657 cpuset_update_tasks_cpumask(&top_cpuset, tmp->new_cpus);
1658 update_sibling_cpumasks(&top_cpuset, NULL, tmp);
1659 }
1660
1661 /*
1662 * remote_cpus_update - cpus_exclusive change of remote partition
1663 * @cs: the cpuset to be updated
1664 * @xcpus: the new exclusive_cpus mask, if non-NULL
1665 * @excpus: the new effective_xcpus mask
1666 * @tmp: temporary masks
1667 *
1668 * top_cpuset and subpartitions_cpus will be updated or partition can be
1669 * invalidated.
1670 */
remote_cpus_update(struct cpuset * cs,struct cpumask * xcpus,struct cpumask * excpus,struct tmpmasks * tmp)1671 static void remote_cpus_update(struct cpuset *cs, struct cpumask *xcpus,
1672 struct cpumask *excpus, struct tmpmasks *tmp)
1673 {
1674 bool adding, deleting;
1675 int prs = cs->partition_root_state;
1676
1677 if (WARN_ON_ONCE(!is_remote_partition(cs)))
1678 return;
1679
1680 WARN_ON_ONCE(!cpumask_subset(cs->effective_xcpus, subpartitions_cpus));
1681
1682 if (cpumask_empty(excpus)) {
1683 WRITE_ONCE(cs->prs_err, PERR_CPUSEMPTY);
1684 goto invalidate;
1685 }
1686
1687 adding = cpumask_andnot(tmp->addmask, excpus, cs->effective_xcpus);
1688 deleting = cpumask_andnot(tmp->delmask, cs->effective_xcpus, excpus);
1689
1690 /*
1691 * Additions of remote CPUs is only allowed if those CPUs are
1692 * not allocated to other partitions and there are effective_cpus
1693 * left in the top cpuset.
1694 */
1695 if (adding) {
1696 WARN_ON_ONCE(cpumask_intersects(tmp->addmask, subpartitions_cpus));
1697 if (!capable(CAP_SYS_ADMIN))
1698 WRITE_ONCE(cs->prs_err, PERR_ACCESS);
1699 else if (cpumask_intersects(tmp->addmask, subpartitions_cpus) ||
1700 cpumask_subset(top_cpuset.effective_cpus, tmp->addmask))
1701 WRITE_ONCE(cs->prs_err, PERR_NOCPUS);
1702 else if ((prs == PRS_ISOLATED) &&
1703 !isolated_cpus_can_update(tmp->addmask, tmp->delmask))
1704 WRITE_ONCE(cs->prs_err, PERR_HKEEPING);
1705 if (cs->prs_err)
1706 goto invalidate;
1707 }
1708
1709 spin_lock_irq(&callback_lock);
1710 if (adding)
1711 partition_xcpus_add(prs, NULL, tmp->addmask);
1712 if (deleting)
1713 partition_xcpus_del(prs, NULL, tmp->delmask);
1714 /*
1715 * Need to update effective_xcpus and exclusive_cpus now as
1716 * update_sibling_cpumasks() below may iterate back to the same cs.
1717 */
1718 cpumask_copy(cs->effective_xcpus, excpus);
1719 if (xcpus)
1720 cpumask_copy(cs->exclusive_cpus, xcpus);
1721 spin_unlock_irq(&callback_lock);
1722 if (adding || deleting)
1723 cpuset_force_rebuild();
1724
1725 /*
1726 * Propagate changes in top_cpuset's effective_cpus down the hierarchy.
1727 */
1728 cpuset_update_tasks_cpumask(&top_cpuset, tmp->new_cpus);
1729 update_sibling_cpumasks(&top_cpuset, NULL, tmp);
1730 return;
1731
1732 invalidate:
1733 remote_partition_disable(cs, tmp);
1734 }
1735
1736 /**
1737 * update_parent_effective_cpumask - update effective_cpus mask of parent cpuset
1738 * @cs: The cpuset that requests change in partition root state
1739 * @cmd: Partition root state change command
1740 * @newmask: Optional new cpumask for partcmd_update
1741 * @tmp: Temporary addmask and delmask
1742 * Return: 0 or a partition root state error code
1743 *
1744 * For partcmd_enable*, the cpuset is being transformed from a non-partition
1745 * root to a partition root. The effective_xcpus (cpus_allowed if
1746 * effective_xcpus not set) mask of the given cpuset will be taken away from
1747 * parent's effective_cpus. The function will return 0 if all the CPUs listed
1748 * in effective_xcpus can be granted or an error code will be returned.
1749 *
1750 * For partcmd_disable, the cpuset is being transformed from a partition
1751 * root back to a non-partition root. Any CPUs in effective_xcpus will be
1752 * given back to parent's effective_cpus. 0 will always be returned.
1753 *
1754 * For partcmd_update, if the optional newmask is specified, the cpu list is
1755 * to be changed from effective_xcpus to newmask. Otherwise, effective_xcpus is
1756 * assumed to remain the same. The cpuset should either be a valid or invalid
1757 * partition root. The partition root state may change from valid to invalid
1758 * or vice versa. An error code will be returned if transitioning from
1759 * invalid to valid violates the exclusivity rule.
1760 *
1761 * For partcmd_invalidate, the current partition will be made invalid.
1762 *
1763 * The partcmd_enable* and partcmd_disable commands are used by
1764 * update_prstate(). An error code may be returned and the caller will check
1765 * for error.
1766 *
1767 * The partcmd_update command is used by update_cpumasks_hier() with newmask
1768 * NULL and update_cpumask() with newmask set. The partcmd_invalidate is used
1769 * by update_cpumask() with NULL newmask. In both cases, the callers won't
1770 * check for error and so partition_root_state and prs_err will be updated
1771 * directly.
1772 */
update_parent_effective_cpumask(struct cpuset * cs,int cmd,struct cpumask * newmask,struct tmpmasks * tmp)1773 static int update_parent_effective_cpumask(struct cpuset *cs, int cmd,
1774 struct cpumask *newmask,
1775 struct tmpmasks *tmp)
1776 {
1777 struct cpuset *parent = parent_cs(cs);
1778 int adding; /* Adding cpus to parent's effective_cpus */
1779 int deleting; /* Deleting cpus from parent's effective_cpus */
1780 int old_prs, new_prs;
1781 int part_error = PERR_NONE; /* Partition error? */
1782 struct cpumask *xcpus = user_xcpus(cs);
1783 int parent_prs = parent->partition_root_state;
1784 bool nocpu;
1785
1786 lockdep_assert_cpuset_lock_held();
1787 WARN_ON_ONCE(is_remote_partition(cs)); /* For local partition only */
1788
1789 /*
1790 * new_prs will only be changed for the partcmd_update and
1791 * partcmd_invalidate commands.
1792 */
1793 adding = deleting = false;
1794 old_prs = new_prs = cs->partition_root_state;
1795
1796 if (cmd == partcmd_invalidate) {
1797 if (is_partition_invalid(cs))
1798 return 0;
1799
1800 /*
1801 * Make the current partition invalid.
1802 */
1803 if (is_partition_valid(parent))
1804 adding = cpumask_and(tmp->addmask,
1805 cs->effective_xcpus,
1806 parent->effective_xcpus);
1807 if (old_prs > 0)
1808 new_prs = -old_prs;
1809
1810 goto write_error;
1811 }
1812
1813 /*
1814 * The parent must be a partition root.
1815 * The new cpumask, if present, or the current cpus_allowed must
1816 * not be empty.
1817 */
1818 if (!is_partition_valid(parent)) {
1819 return is_partition_invalid(parent)
1820 ? PERR_INVPARENT : PERR_NOTPART;
1821 }
1822 if (!newmask && xcpus_empty(cs))
1823 return PERR_CPUSEMPTY;
1824
1825 nocpu = tasks_nocpu_error(parent, cs, xcpus);
1826
1827 if ((cmd == partcmd_enable) || (cmd == partcmd_enablei)) {
1828 /*
1829 * Need to call compute_excpus() in case
1830 * exclusive_cpus not set. Sibling conflict should only happen
1831 * if exclusive_cpus isn't set.
1832 */
1833 xcpus = tmp->delmask;
1834 if (compute_excpus(cs, xcpus))
1835 WARN_ON_ONCE(!cpumask_empty(cs->exclusive_cpus));
1836 new_prs = (cmd == partcmd_enable) ? PRS_ROOT : PRS_ISOLATED;
1837
1838 /*
1839 * Enabling partition root is not allowed if its
1840 * effective_xcpus is empty.
1841 */
1842 if (cpumask_empty(xcpus))
1843 return PERR_INVCPUS;
1844
1845 if (prstate_housekeeping_conflict(new_prs, xcpus))
1846 return PERR_HKEEPING;
1847
1848 if ((new_prs == PRS_ISOLATED) && (new_prs != parent_prs) &&
1849 !isolated_cpus_can_update(xcpus, NULL))
1850 return PERR_HKEEPING;
1851
1852 if (tasks_nocpu_error(parent, cs, xcpus))
1853 return PERR_NOCPUS;
1854
1855 /*
1856 * This function will only be called when all the preliminary
1857 * checks have passed. At this point, the following condition
1858 * should hold.
1859 *
1860 * (cs->effective_xcpus & cpu_active_mask) ⊆ parent->effective_cpus
1861 *
1862 * Warn if it is not the case.
1863 */
1864 cpumask_and(tmp->new_cpus, xcpus, cpu_active_mask);
1865 WARN_ON_ONCE(!cpumask_subset(tmp->new_cpus, parent->effective_cpus));
1866
1867 deleting = true;
1868 } else if (cmd == partcmd_disable) {
1869 /*
1870 * May need to add cpus back to parent's effective_cpus
1871 * (and maybe removed from subpartitions_cpus/isolated_cpus)
1872 * for valid partition root. xcpus may contain CPUs that
1873 * shouldn't be removed from the two global cpumasks.
1874 */
1875 if (is_partition_valid(cs)) {
1876 cpumask_copy(tmp->addmask, cs->effective_xcpus);
1877 adding = true;
1878 }
1879 new_prs = PRS_MEMBER;
1880 } else if (newmask) {
1881 /*
1882 * Empty cpumask is not allowed
1883 */
1884 if (cpumask_empty(newmask)) {
1885 part_error = PERR_CPUSEMPTY;
1886 goto write_error;
1887 }
1888
1889 /* Check newmask again, whether cpus are available for parent/cs */
1890 nocpu |= tasks_nocpu_error(parent, cs, newmask);
1891
1892 /*
1893 * partcmd_update with newmask:
1894 *
1895 * Compute add/delete mask to/from effective_cpus
1896 *
1897 * For valid partition:
1898 * addmask = effective_xcpus & ~newmask
1899 * & parent->effective_xcpus
1900 * delmask = newmask & ~effective_xcpus
1901 * & parent->effective_xcpus
1902 *
1903 * For invalid partition:
1904 * delmask = newmask & parent->effective_xcpus
1905 * The partition may become valid soon.
1906 */
1907 if (is_partition_invalid(cs)) {
1908 adding = false;
1909 deleting = cpumask_and(tmp->delmask,
1910 newmask, parent->effective_xcpus);
1911 } else {
1912 cpumask_andnot(tmp->addmask, cs->effective_xcpus, newmask);
1913 adding = cpumask_and(tmp->addmask, tmp->addmask,
1914 parent->effective_xcpus);
1915
1916 cpumask_andnot(tmp->delmask, newmask, cs->effective_xcpus);
1917 deleting = cpumask_and(tmp->delmask, tmp->delmask,
1918 parent->effective_xcpus);
1919 }
1920
1921 /*
1922 * TBD: Invalidate a currently valid child root partition may
1923 * still break isolated_cpus_can_update() rule if parent is an
1924 * isolated partition.
1925 */
1926 if (is_partition_valid(cs) && (old_prs != parent_prs)) {
1927 if ((parent_prs == PRS_ROOT) &&
1928 /* Adding to parent means removing isolated CPUs */
1929 !isolated_cpus_can_update(tmp->delmask, tmp->addmask))
1930 part_error = PERR_HKEEPING;
1931 if ((parent_prs == PRS_ISOLATED) &&
1932 /* Adding to parent means adding isolated CPUs */
1933 !isolated_cpus_can_update(tmp->addmask, tmp->delmask))
1934 part_error = PERR_HKEEPING;
1935 }
1936
1937 /*
1938 * The new CPUs to be removed from parent's effective CPUs
1939 * must be present.
1940 */
1941 if (deleting) {
1942 cpumask_and(tmp->new_cpus, tmp->delmask, cpu_active_mask);
1943 WARN_ON_ONCE(!cpumask_subset(tmp->new_cpus, parent->effective_cpus));
1944 }
1945
1946 /*
1947 * Make partition invalid if parent's effective_cpus could
1948 * become empty and there are tasks in the parent.
1949 */
1950 if (nocpu && (!adding ||
1951 !cpumask_intersects(tmp->addmask, cpu_active_mask))) {
1952 part_error = PERR_NOCPUS;
1953 deleting = false;
1954 adding = cpumask_and(tmp->addmask,
1955 cs->effective_xcpus, parent->effective_xcpus);
1956 }
1957 } else {
1958 /*
1959 * partcmd_update w/o newmask
1960 *
1961 * delmask = effective_xcpus & parent->effective_cpus
1962 *
1963 * This can be called from:
1964 * 1) update_cpumasks_hier()
1965 * 2) cpuset_hotplug_update_tasks()
1966 *
1967 * Check to see if it can be transitioned from valid to
1968 * invalid partition or vice versa.
1969 *
1970 * A partition error happens when parent has tasks and all
1971 * its effective CPUs will have to be distributed out.
1972 */
1973 if (nocpu) {
1974 part_error = PERR_NOCPUS;
1975 if (is_partition_valid(cs))
1976 adding = cpumask_and(tmp->addmask,
1977 cs->effective_xcpus,
1978 parent->effective_xcpus);
1979 } else if (is_partition_invalid(cs) && !cpumask_empty(xcpus) &&
1980 cpumask_subset(xcpus, parent->effective_xcpus)) {
1981 struct cgroup_subsys_state *css;
1982 struct cpuset *child;
1983 bool exclusive = true;
1984
1985 /*
1986 * Convert invalid partition to valid has to
1987 * pass the cpu exclusivity test.
1988 */
1989 rcu_read_lock();
1990 cpuset_for_each_child(child, css, parent) {
1991 if (child == cs)
1992 continue;
1993 if (!cpusets_are_exclusive(cs, child)) {
1994 exclusive = false;
1995 break;
1996 }
1997 }
1998 rcu_read_unlock();
1999 if (exclusive)
2000 deleting = cpumask_and(tmp->delmask,
2001 xcpus, parent->effective_cpus);
2002 else
2003 part_error = PERR_NOTEXCL;
2004 }
2005 }
2006
2007 write_error:
2008 if (part_error)
2009 WRITE_ONCE(cs->prs_err, part_error);
2010
2011 if (cmd == partcmd_update) {
2012 /*
2013 * Check for possible transition between valid and invalid
2014 * partition root.
2015 */
2016 switch (cs->partition_root_state) {
2017 case PRS_ROOT:
2018 case PRS_ISOLATED:
2019 if (part_error)
2020 new_prs = -old_prs;
2021 break;
2022 case PRS_INVALID_ROOT:
2023 case PRS_INVALID_ISOLATED:
2024 if (!part_error)
2025 new_prs = -old_prs;
2026 break;
2027 }
2028 }
2029
2030 if (!adding && !deleting && (new_prs == old_prs))
2031 return 0;
2032
2033 /*
2034 * Transitioning between invalid to valid or vice versa may require
2035 * changing CS_CPU_EXCLUSIVE. In the case of partcmd_update,
2036 * validate_change() has already been successfully called and
2037 * CPU lists in cs haven't been updated yet. So defer it to later.
2038 */
2039 if ((old_prs != new_prs) && (cmd != partcmd_update)) {
2040 int err = update_partition_exclusive_flag(cs, new_prs);
2041
2042 if (err)
2043 return err;
2044 }
2045
2046 /*
2047 * Change the parent's effective_cpus & effective_xcpus (top cpuset
2048 * only).
2049 *
2050 * Newly added CPUs will be removed from effective_cpus and
2051 * newly deleted ones will be added back to effective_cpus.
2052 */
2053 spin_lock_irq(&callback_lock);
2054 if (old_prs != new_prs)
2055 cs->partition_root_state = new_prs;
2056
2057 /*
2058 * Adding to parent's effective_cpus means deletion CPUs from cs
2059 * and vice versa.
2060 */
2061 if (adding)
2062 partition_xcpus_del(old_prs, parent, tmp->addmask);
2063 if (deleting)
2064 partition_xcpus_add(new_prs, parent, tmp->delmask);
2065
2066 spin_unlock_irq(&callback_lock);
2067
2068 if ((old_prs != new_prs) && (cmd == partcmd_update))
2069 update_partition_exclusive_flag(cs, new_prs);
2070
2071 if (adding || deleting) {
2072 cpuset_update_tasks_cpumask(parent, tmp->addmask);
2073 update_sibling_cpumasks(parent, cs, tmp);
2074 }
2075
2076 /*
2077 * For partcmd_update without newmask, it is being called from
2078 * cpuset_handle_hotplug(). Update the load balance flag and
2079 * scheduling domain accordingly.
2080 */
2081 if ((cmd == partcmd_update) && !newmask)
2082 update_partition_sd_lb(cs, old_prs);
2083
2084 notify_partition_change(cs, old_prs);
2085 return 0;
2086 }
2087
2088 /**
2089 * compute_partition_effective_cpumask - compute effective_cpus for partition
2090 * @cs: partition root cpuset
2091 * @new_ecpus: previously computed effective_cpus to be updated
2092 *
2093 * Compute the effective_cpus of a partition root by scanning effective_xcpus
2094 * of child partition roots and excluding their effective_xcpus.
2095 *
2096 * This has the side effect of invalidating valid child partition roots,
2097 * if necessary. Since it is called from either cpuset_hotplug_update_tasks()
2098 * or update_cpumasks_hier() where parent and children are modified
2099 * successively, we don't need to call update_parent_effective_cpumask()
2100 * and the child's effective_cpus will be updated in later iterations.
2101 *
2102 * Note that rcu_read_lock() is assumed to be held.
2103 */
compute_partition_effective_cpumask(struct cpuset * cs,struct cpumask * new_ecpus)2104 static void compute_partition_effective_cpumask(struct cpuset *cs,
2105 struct cpumask *new_ecpus)
2106 {
2107 struct cgroup_subsys_state *css;
2108 struct cpuset *child;
2109 bool populated = partition_is_populated(cs, NULL);
2110
2111 /*
2112 * Check child partition roots to see if they should be
2113 * invalidated when
2114 * 1) child effective_xcpus not a subset of new
2115 * excluisve_cpus
2116 * 2) All the effective_cpus will be used up and cp
2117 * has tasks
2118 */
2119 compute_excpus(cs, new_ecpus);
2120 cpumask_and(new_ecpus, new_ecpus, cpu_active_mask);
2121
2122 rcu_read_lock();
2123 cpuset_for_each_child(child, css, cs) {
2124 if (!is_partition_valid(child))
2125 continue;
2126
2127 /*
2128 * There shouldn't be a remote partition underneath another
2129 * partition root.
2130 */
2131 WARN_ON_ONCE(is_remote_partition(child));
2132 WRITE_ONCE(child->prs_err, 0);
2133 if (!cpumask_subset(child->effective_xcpus,
2134 cs->effective_xcpus))
2135 WRITE_ONCE(child->prs_err, PERR_INVCPUS);
2136 else if (populated &&
2137 cpumask_subset(new_ecpus, child->effective_xcpus))
2138 WRITE_ONCE(child->prs_err, PERR_NOCPUS);
2139
2140 if (child->prs_err) {
2141 int old_prs = child->partition_root_state;
2142
2143 /*
2144 * Invalidate child partition
2145 */
2146 spin_lock_irq(&callback_lock);
2147 make_partition_invalid(child);
2148 spin_unlock_irq(&callback_lock);
2149 notify_partition_change(child, old_prs);
2150 continue;
2151 }
2152 cpumask_andnot(new_ecpus, new_ecpus,
2153 child->effective_xcpus);
2154 }
2155 rcu_read_unlock();
2156 }
2157
2158 /*
2159 * update_cpumasks_hier - Update effective cpumasks and tasks in the subtree
2160 * @cs: the cpuset to consider
2161 * @tmp: temp variables for calculating effective_cpus & partition setup
2162 * @force: don't skip any descendant cpusets if set
2163 *
2164 * When configured cpumask is changed, the effective cpumasks of this cpuset
2165 * and all its descendants need to be updated.
2166 *
2167 * On legacy hierarchy, effective_cpus will be the same with cpu_allowed.
2168 *
2169 * Called with cpuset_mutex held
2170 */
update_cpumasks_hier(struct cpuset * cs,struct tmpmasks * tmp,bool force)2171 static void update_cpumasks_hier(struct cpuset *cs, struct tmpmasks *tmp,
2172 bool force)
2173 {
2174 struct cpuset *cp;
2175 struct cgroup_subsys_state *pos_css;
2176 int old_prs, new_prs;
2177
2178 rcu_read_lock();
2179 cpuset_for_each_descendant_pre(cp, pos_css, cs) {
2180 struct cpuset *parent = parent_cs(cp);
2181 bool remote = is_remote_partition(cp);
2182 bool update_parent = false;
2183
2184 old_prs = new_prs = cp->partition_root_state;
2185
2186 /*
2187 * For child remote partition root (!= cs), we need to call
2188 * remote_cpus_update() if effective_xcpus will be changed.
2189 * Otherwise, we can skip the whole subtree.
2190 *
2191 * remote_cpus_update() will reuse tmp->new_cpus only after
2192 * its value is being processed.
2193 */
2194 if (remote && (cp != cs)) {
2195 compute_excpus(cp, tmp->new_cpus);
2196 if (cpumask_equal(cp->effective_xcpus, tmp->new_cpus)) {
2197 pos_css = css_rightmost_descendant(pos_css);
2198 continue;
2199 }
2200 rcu_read_unlock();
2201 remote_cpus_update(cp, NULL, tmp->new_cpus, tmp);
2202 rcu_read_lock();
2203
2204 /* Remote partition may be invalidated */
2205 new_prs = cp->partition_root_state;
2206 remote = (new_prs == old_prs);
2207 }
2208
2209 if (remote || (is_partition_valid(parent) && is_partition_valid(cp)))
2210 compute_partition_effective_cpumask(cp, tmp->new_cpus);
2211 else
2212 compute_effective_cpumask(tmp->new_cpus, cp, parent);
2213
2214 if (remote)
2215 goto get_css; /* Ready to update cpuset data */
2216
2217 /*
2218 * A partition with no effective_cpus is allowed as long as
2219 * there is no task associated with it. Call
2220 * update_parent_effective_cpumask() to check it.
2221 */
2222 if (is_partition_valid(cp) && cpumask_empty(tmp->new_cpus)) {
2223 update_parent = true;
2224 goto update_parent_effective;
2225 }
2226
2227 /*
2228 * Skip the whole subtree if
2229 * 1) the cpumask remains the same,
2230 * 2) has no partition root state,
2231 * 3) force flag not set, and
2232 * 4) for v2 load balance state same as its parent.
2233 */
2234 if (!cp->partition_root_state && !force &&
2235 cpumask_equal(tmp->new_cpus, cp->effective_cpus) &&
2236 (!cpuset_v2() ||
2237 (is_sched_load_balance(parent) == is_sched_load_balance(cp)))) {
2238 pos_css = css_rightmost_descendant(pos_css);
2239 continue;
2240 }
2241
2242 update_parent_effective:
2243 /*
2244 * update_parent_effective_cpumask() should have been called
2245 * for cs already in update_cpumask(). We should also call
2246 * cpuset_update_tasks_cpumask() again for tasks in the parent
2247 * cpuset if the parent's effective_cpus changes.
2248 */
2249 if ((cp != cs) && old_prs) {
2250 switch (parent->partition_root_state) {
2251 case PRS_ROOT:
2252 case PRS_ISOLATED:
2253 update_parent = true;
2254 break;
2255
2256 default:
2257 /*
2258 * When parent is not a partition root or is
2259 * invalid, child partition roots become
2260 * invalid too.
2261 */
2262 if (is_partition_valid(cp))
2263 new_prs = -cp->partition_root_state;
2264 WRITE_ONCE(cp->prs_err,
2265 is_partition_invalid(parent)
2266 ? PERR_INVPARENT : PERR_NOTPART);
2267 break;
2268 }
2269 }
2270 get_css:
2271 if (!css_tryget_online(&cp->css))
2272 continue;
2273 rcu_read_unlock();
2274
2275 if (update_parent) {
2276 update_parent_effective_cpumask(cp, partcmd_update, NULL, tmp);
2277 /*
2278 * The cpuset partition_root_state may become
2279 * invalid. Capture it.
2280 */
2281 new_prs = cp->partition_root_state;
2282 }
2283
2284 spin_lock_irq(&callback_lock);
2285 cpumask_copy(cp->effective_cpus, tmp->new_cpus);
2286 cp->partition_root_state = new_prs;
2287 /*
2288 * Need to compute effective_xcpus if either exclusive_cpus
2289 * is non-empty or it is a valid partition root.
2290 */
2291 if ((new_prs > 0) || !cpumask_empty(cp->exclusive_cpus))
2292 compute_excpus(cp, cp->effective_xcpus);
2293 if (new_prs <= 0)
2294 reset_partition_data(cp);
2295 spin_unlock_irq(&callback_lock);
2296
2297 notify_partition_change(cp, old_prs);
2298
2299 WARN_ON(!is_in_v2_mode() &&
2300 !cpumask_equal(cp->cpus_allowed, cp->effective_cpus));
2301
2302 cpuset_update_tasks_cpumask(cp, tmp->new_cpus);
2303
2304 /*
2305 * On default hierarchy, inherit the CS_SCHED_LOAD_BALANCE
2306 * from parent if current cpuset isn't a valid partition root
2307 * and their load balance states differ.
2308 */
2309 if (cpuset_v2() && !is_partition_valid(cp) &&
2310 (is_sched_load_balance(parent) != is_sched_load_balance(cp))) {
2311 if (is_sched_load_balance(parent))
2312 set_bit(CS_SCHED_LOAD_BALANCE, &cp->flags);
2313 else
2314 clear_bit(CS_SCHED_LOAD_BALANCE, &cp->flags);
2315 }
2316
2317 /*
2318 * On legacy hierarchy, if the effective cpumask of any non-
2319 * empty cpuset is changed, we need to rebuild sched domains.
2320 * On default hierarchy, the cpuset needs to be a partition
2321 * root as well.
2322 */
2323 if (!cpumask_empty(cp->cpus_allowed) &&
2324 is_sched_load_balance(cp) &&
2325 (!cpuset_v2() || is_partition_valid(cp)))
2326 cpuset_force_rebuild();
2327
2328 rcu_read_lock();
2329 css_put(&cp->css);
2330 }
2331 rcu_read_unlock();
2332 }
2333
2334 /**
2335 * update_sibling_cpumasks - Update siblings cpumasks
2336 * @parent: Parent cpuset
2337 * @cs: Current cpuset
2338 * @tmp: Temp variables
2339 */
update_sibling_cpumasks(struct cpuset * parent,struct cpuset * cs,struct tmpmasks * tmp)2340 static void update_sibling_cpumasks(struct cpuset *parent, struct cpuset *cs,
2341 struct tmpmasks *tmp)
2342 {
2343 struct cpuset *sibling;
2344 struct cgroup_subsys_state *pos_css;
2345
2346 lockdep_assert_cpuset_lock_held();
2347
2348 /*
2349 * Check all its siblings and call update_cpumasks_hier()
2350 * if their effective_cpus will need to be changed.
2351 *
2352 * It is possible a change in parent's effective_cpus
2353 * due to a change in a child partition's effective_xcpus will impact
2354 * its siblings even if they do not inherit parent's effective_cpus
2355 * directly. It should not impact valid partition.
2356 *
2357 * The update_cpumasks_hier() function may sleep. So we have to
2358 * release the RCU read lock before calling it.
2359 */
2360 rcu_read_lock();
2361 cpuset_for_each_child(sibling, pos_css, parent) {
2362 if (sibling == cs || is_partition_valid(sibling))
2363 continue;
2364
2365 compute_effective_cpumask(tmp->new_cpus, sibling,
2366 parent);
2367 if (cpumask_equal(tmp->new_cpus, sibling->effective_cpus))
2368 continue;
2369
2370 if (!css_tryget_online(&sibling->css))
2371 continue;
2372
2373 rcu_read_unlock();
2374 update_cpumasks_hier(sibling, tmp, false);
2375 rcu_read_lock();
2376 css_put(&sibling->css);
2377 }
2378 rcu_read_unlock();
2379 }
2380
parse_cpuset_cpulist(const char * buf,struct cpumask * out_mask)2381 static int parse_cpuset_cpulist(const char *buf, struct cpumask *out_mask)
2382 {
2383 int retval;
2384
2385 retval = cpulist_parse(buf, out_mask);
2386 if (retval < 0)
2387 return retval;
2388 if (!cpumask_subset(out_mask, top_cpuset.cpus_allowed))
2389 return -EINVAL;
2390
2391 return 0;
2392 }
2393
2394 /**
2395 * validate_partition - Validate a cpuset partition configuration
2396 * @cs: The cpuset to validate
2397 * @trialcs: The trial cpuset containing proposed configuration changes
2398 *
2399 * If any validation check fails, the appropriate error code is set in the
2400 * cpuset's prs_err field.
2401 *
2402 * Return: PRS error code (0 if valid, non-zero error code if invalid)
2403 */
validate_partition(struct cpuset * cs,struct cpuset * trialcs)2404 static enum prs_errcode validate_partition(struct cpuset *cs, struct cpuset *trialcs)
2405 {
2406 struct cpuset *parent = parent_cs(cs);
2407
2408 if (cs_is_member(trialcs))
2409 return PERR_NONE;
2410
2411 if (cpumask_empty(trialcs->effective_xcpus))
2412 return PERR_INVCPUS;
2413
2414 if (prstate_housekeeping_conflict(trialcs->partition_root_state,
2415 trialcs->effective_xcpus))
2416 return PERR_HKEEPING;
2417
2418 if (tasks_nocpu_error(parent, cs, trialcs->effective_xcpus))
2419 return PERR_NOCPUS;
2420
2421 return PERR_NONE;
2422 }
2423
2424 /**
2425 * partition_cpus_change - Handle partition state changes due to CPU mask updates
2426 * @cs: The target cpuset being modified
2427 * @trialcs: The trial cpuset containing proposed configuration changes
2428 * @tmp: Temporary masks for intermediate calculations
2429 *
2430 * This function handles partition state transitions triggered by CPU mask changes.
2431 * CPU modifications may cause a partition to be disabled or require state updates.
2432 */
partition_cpus_change(struct cpuset * cs,struct cpuset * trialcs,struct tmpmasks * tmp)2433 static void partition_cpus_change(struct cpuset *cs, struct cpuset *trialcs,
2434 struct tmpmasks *tmp)
2435 {
2436 enum prs_errcode prs_err;
2437
2438 if (cs_is_member(cs))
2439 return;
2440
2441 prs_err = validate_partition(cs, trialcs);
2442 if (prs_err) {
2443 WRITE_ONCE(cs->prs_err, prs_err);
2444 trialcs->prs_err = prs_err;
2445 }
2446
2447 if (is_remote_partition(cs)) {
2448 if (trialcs->prs_err)
2449 remote_partition_disable(cs, tmp);
2450 else
2451 remote_cpus_update(cs, trialcs->exclusive_cpus,
2452 trialcs->effective_xcpus, tmp);
2453 } else {
2454 if (trialcs->prs_err)
2455 update_parent_effective_cpumask(cs, partcmd_invalidate,
2456 NULL, tmp);
2457 else
2458 update_parent_effective_cpumask(cs, partcmd_update,
2459 trialcs->effective_xcpus, tmp);
2460 }
2461 }
2462
2463 /**
2464 * update_cpumask - update the cpus_allowed mask of a cpuset and all tasks in it
2465 * @cs: the cpuset to consider
2466 * @trialcs: trial cpuset
2467 * @buf: buffer of cpu numbers written to this cpuset
2468 */
update_cpumask(struct cpuset * cs,struct cpuset * trialcs,const char * buf)2469 static int update_cpumask(struct cpuset *cs, struct cpuset *trialcs,
2470 const char *buf)
2471 {
2472 int retval;
2473 struct tmpmasks tmp;
2474 bool force = false;
2475 int old_prs = cs->partition_root_state;
2476
2477 retval = parse_cpuset_cpulist(buf, trialcs->cpus_allowed);
2478 if (retval < 0)
2479 return retval;
2480
2481 /* Nothing to do if the cpus didn't change */
2482 if (cpumask_equal(cs->cpus_allowed, trialcs->cpus_allowed))
2483 return 0;
2484
2485 compute_trialcs_excpus(trialcs, cs);
2486 trialcs->prs_err = PERR_NONE;
2487
2488 retval = validate_change(cs, trialcs);
2489 if (retval < 0)
2490 return retval;
2491
2492 if (alloc_tmpmasks(&tmp))
2493 return -ENOMEM;
2494
2495 /*
2496 * Check all the descendants in update_cpumasks_hier() if
2497 * effective_xcpus is to be changed.
2498 */
2499 force = !cpumask_equal(cs->effective_xcpus, trialcs->effective_xcpus);
2500
2501 partition_cpus_change(cs, trialcs, &tmp);
2502
2503 spin_lock_irq(&callback_lock);
2504 cpumask_copy(cs->cpus_allowed, trialcs->cpus_allowed);
2505 cpumask_copy(cs->effective_xcpus, trialcs->effective_xcpus);
2506 if ((old_prs > 0) && !is_partition_valid(cs))
2507 reset_partition_data(cs);
2508 spin_unlock_irq(&callback_lock);
2509
2510 /* effective_cpus/effective_xcpus will be updated here */
2511 update_cpumasks_hier(cs, &tmp, force);
2512
2513 /* Update CS_SCHED_LOAD_BALANCE and/or sched_domains, if necessary */
2514 if (cs->partition_root_state)
2515 update_partition_sd_lb(cs, old_prs);
2516
2517 free_tmpmasks(&tmp);
2518 return retval;
2519 }
2520
2521 /**
2522 * update_exclusive_cpumask - update the exclusive_cpus mask of a cpuset
2523 * @cs: the cpuset to consider
2524 * @trialcs: trial cpuset
2525 * @buf: buffer of cpu numbers written to this cpuset
2526 *
2527 * The tasks' cpumask will be updated if cs is a valid partition root.
2528 */
update_exclusive_cpumask(struct cpuset * cs,struct cpuset * trialcs,const char * buf)2529 static int update_exclusive_cpumask(struct cpuset *cs, struct cpuset *trialcs,
2530 const char *buf)
2531 {
2532 int retval;
2533 struct tmpmasks tmp;
2534 bool force = false;
2535 int old_prs = cs->partition_root_state;
2536
2537 retval = parse_cpuset_cpulist(buf, trialcs->exclusive_cpus);
2538 if (retval < 0)
2539 return retval;
2540
2541 /* Nothing to do if the CPUs didn't change */
2542 if (cpumask_equal(cs->exclusive_cpus, trialcs->exclusive_cpus))
2543 return 0;
2544
2545 /*
2546 * Reject the change if there is exclusive CPUs conflict with
2547 * the siblings.
2548 */
2549 if (compute_trialcs_excpus(trialcs, cs))
2550 return -EINVAL;
2551
2552 /*
2553 * Check all the descendants in update_cpumasks_hier() if
2554 * effective_xcpus is to be changed.
2555 */
2556 force = !cpumask_equal(cs->effective_xcpus, trialcs->effective_xcpus);
2557
2558 retval = validate_change(cs, trialcs);
2559 if (retval)
2560 return retval;
2561
2562 if (alloc_tmpmasks(&tmp))
2563 return -ENOMEM;
2564
2565 trialcs->prs_err = PERR_NONE;
2566 partition_cpus_change(cs, trialcs, &tmp);
2567
2568 spin_lock_irq(&callback_lock);
2569 cpumask_copy(cs->exclusive_cpus, trialcs->exclusive_cpus);
2570 cpumask_copy(cs->effective_xcpus, trialcs->effective_xcpus);
2571 if ((old_prs > 0) && !is_partition_valid(cs))
2572 reset_partition_data(cs);
2573 spin_unlock_irq(&callback_lock);
2574
2575 /*
2576 * Call update_cpumasks_hier() to update effective_cpus/effective_xcpus
2577 * of the subtree when it is a valid partition root or effective_xcpus
2578 * is updated.
2579 */
2580 if (is_partition_valid(cs) || force)
2581 update_cpumasks_hier(cs, &tmp, force);
2582
2583 /* Update CS_SCHED_LOAD_BALANCE and/or sched_domains, if necessary */
2584 if (cs->partition_root_state)
2585 update_partition_sd_lb(cs, old_prs);
2586
2587 free_tmpmasks(&tmp);
2588 return 0;
2589 }
2590
2591 /*
2592 * Migrate memory region from one set of nodes to another. This is
2593 * performed asynchronously as it can be called from process migration path
2594 * holding locks involved in process management. All mm migrations are
2595 * performed in the queued order and can be waited for by flushing
2596 * cpuset_migrate_mm_wq.
2597 */
2598
2599 struct cpuset_migrate_mm_work {
2600 struct work_struct work;
2601 struct mm_struct *mm;
2602 nodemask_t from;
2603 nodemask_t to;
2604 };
2605
cpuset_migrate_mm_workfn(struct work_struct * work)2606 static void cpuset_migrate_mm_workfn(struct work_struct *work)
2607 {
2608 struct cpuset_migrate_mm_work *mwork =
2609 container_of(work, struct cpuset_migrate_mm_work, work);
2610
2611 /* on a wq worker, no need to worry about %current's mems_allowed */
2612 do_migrate_pages(mwork->mm, &mwork->from, &mwork->to, MPOL_MF_MOVE_ALL);
2613 mmput(mwork->mm);
2614 kfree(mwork);
2615 }
2616
cpuset_migrate_mm(struct mm_struct * mm,const nodemask_t * from,const nodemask_t * to)2617 static void cpuset_migrate_mm(struct mm_struct *mm, const nodemask_t *from,
2618 const nodemask_t *to)
2619 {
2620 struct cpuset_migrate_mm_work *mwork;
2621
2622 if (nodes_equal(*from, *to)) {
2623 mmput(mm);
2624 return;
2625 }
2626
2627 mwork = kzalloc_obj(*mwork);
2628 if (mwork) {
2629 mwork->mm = mm;
2630 mwork->from = *from;
2631 mwork->to = *to;
2632 INIT_WORK(&mwork->work, cpuset_migrate_mm_workfn);
2633 queue_work(cpuset_migrate_mm_wq, &mwork->work);
2634 } else {
2635 mmput(mm);
2636 }
2637 }
2638
flush_migrate_mm_task_workfn(struct callback_head * head)2639 static void flush_migrate_mm_task_workfn(struct callback_head *head)
2640 {
2641 flush_workqueue(cpuset_migrate_mm_wq);
2642 kfree(head);
2643 }
2644
schedule_flush_migrate_mm(void)2645 static void schedule_flush_migrate_mm(void)
2646 {
2647 struct callback_head *flush_cb;
2648
2649 flush_cb = kzalloc_obj(struct callback_head);
2650 if (!flush_cb)
2651 return;
2652
2653 init_task_work(flush_cb, flush_migrate_mm_task_workfn);
2654
2655 if (task_work_add(current, flush_cb, TWA_RESUME))
2656 kfree(flush_cb);
2657 }
2658
2659 /*
2660 * cpuset_change_task_nodemask - change task's mems_allowed and mempolicy
2661 * @tsk: the task to change
2662 * @newmems: new nodes that the task will be set
2663 *
2664 * We use the mems_allowed_seq seqlock to safely update both tsk->mems_allowed
2665 * and rebind an eventual tasks' mempolicy. If the task is allocating in
2666 * parallel, it might temporarily see an empty intersection, which results in
2667 * a seqlock check and retry before OOM or allocation failure.
2668 */
cpuset_change_task_nodemask(struct task_struct * tsk,nodemask_t * newmems)2669 static void cpuset_change_task_nodemask(struct task_struct *tsk,
2670 nodemask_t *newmems)
2671 {
2672 task_lock(tsk);
2673
2674 local_irq_disable();
2675 write_seqcount_begin(&tsk->mems_allowed_seq);
2676
2677 nodes_or(tsk->mems_allowed, tsk->mems_allowed, *newmems);
2678 mpol_rebind_task(tsk, newmems);
2679 tsk->mems_allowed = *newmems;
2680
2681 write_seqcount_end(&tsk->mems_allowed_seq);
2682 local_irq_enable();
2683
2684 task_unlock(tsk);
2685 }
2686
2687 static void *cpuset_being_rebound;
2688
2689 /**
2690 * cpuset_update_tasks_nodemask - Update the nodemasks of tasks in the cpuset.
2691 * @cs: the cpuset in which each task's mems_allowed mask needs to be changed
2692 *
2693 * Iterate through each task of @cs updating its mems_allowed to the
2694 * effective cpuset's. As this function is called with cpuset_mutex held,
2695 * cpuset membership stays stable.
2696 *
2697 * - cpuset_change_task_nodemask(): guarantee_online_mems()
2698 * - mpol_rebind_mm(): effective_mems
2699 * - cpuset_migrate_mm(): guarantee_online_mems()
2700 * - old_mems_allowed: guarantee_online_mems()
2701 *
2702 * For v2, guarantee_online_mems() should return a node mask that is the same
2703 * as the effective_mems of current cpuset.
2704 */
cpuset_update_tasks_nodemask(struct cpuset * cs)2705 void cpuset_update_tasks_nodemask(struct cpuset *cs)
2706 {
2707 static nodemask_t newmems; /* protected by cpuset_mutex */
2708 struct css_task_iter it;
2709 struct task_struct *task;
2710
2711 cpuset_being_rebound = cs; /* causes mpol_dup() rebind */
2712 guarantee_online_mems(cs, &newmems);
2713
2714 /*
2715 * The mpol_rebind_mm() call takes mmap_lock, which we couldn't
2716 * take while holding tasklist_lock. Forks can happen - the
2717 * mpol_dup() cpuset_being_rebound check will catch such forks,
2718 * and rebind their vma mempolicies too. Because we still hold
2719 * the global cpuset_mutex, we know that no other rebind effort
2720 * will be contending for the global variable cpuset_being_rebound.
2721 * It's ok if we rebind the same mm twice; mpol_rebind_mm()
2722 * is idempotent. Also migrate pages in each mm to new nodes.
2723 */
2724 css_task_iter_start(&cs->css, 0, &it);
2725 while ((task = css_task_iter_next(&it))) {
2726 struct mm_struct *mm;
2727 bool migrate;
2728
2729 cpuset_change_task_nodemask(task, &newmems);
2730
2731 /* Rebind and migrate mm only for thread group leader */
2732 if (!thread_group_leader(task))
2733 continue;
2734
2735 mm = get_task_mm(task);
2736 if (!mm)
2737 continue;
2738
2739 migrate = is_memory_migrate(cs);
2740
2741 /*
2742 * For v1 we can have empty effective_mems, but we cannot
2743 * attach any tasks (see cpuset_can_attach_check()). For v2,
2744 * effective_mems is guaranteed to not be empty.
2745 */
2746 mpol_rebind_mm(mm, &cs->effective_mems);
2747 if (migrate)
2748 cpuset_migrate_mm(mm, &cs->old_mems_allowed, &newmems);
2749 else
2750 mmput(mm);
2751 }
2752 css_task_iter_end(&it);
2753
2754 /*
2755 * All the tasks' nodemasks have been updated, update
2756 * cs->old_mems_allowed.
2757 */
2758 cs->old_mems_allowed = newmems;
2759
2760 /* We're done rebinding vmas to this cpuset's new mems_allowed. */
2761 cpuset_being_rebound = NULL;
2762 }
2763
2764 /*
2765 * update_nodemasks_hier - Update effective nodemasks and tasks in the subtree
2766 * @cs: the cpuset to consider
2767 * @new_mems: a temp variable for calculating new effective_mems
2768 *
2769 * When configured nodemask is changed, the effective nodemasks of this cpuset
2770 * and all its descendants need to be updated.
2771 *
2772 * On legacy hierarchy, effective_mems will be the same with mems_allowed.
2773 *
2774 * Called with cpuset_mutex held
2775 */
update_nodemasks_hier(struct cpuset * cs,nodemask_t * new_mems)2776 static void update_nodemasks_hier(struct cpuset *cs, nodemask_t *new_mems)
2777 {
2778 struct cpuset *cp;
2779 struct cgroup_subsys_state *pos_css;
2780
2781 rcu_read_lock();
2782 cpuset_for_each_descendant_pre(cp, pos_css, cs) {
2783 struct cpuset *parent = parent_cs(cp);
2784
2785 compute_effective_nodemask(new_mems, cp, parent);
2786
2787 /* Skip the whole subtree if the nodemask remains the same. */
2788 if (nodes_equal(*new_mems, cp->effective_mems)) {
2789 pos_css = css_rightmost_descendant(pos_css);
2790 continue;
2791 }
2792
2793 if (!css_tryget_online(&cp->css))
2794 continue;
2795 rcu_read_unlock();
2796
2797 spin_lock_irq(&callback_lock);
2798 cp->effective_mems = *new_mems;
2799 spin_unlock_irq(&callback_lock);
2800
2801 WARN_ON(!is_in_v2_mode() &&
2802 !nodes_equal(cp->mems_allowed, cp->effective_mems));
2803
2804 cpuset_update_tasks_nodemask(cp);
2805
2806 rcu_read_lock();
2807 css_put(&cp->css);
2808 }
2809 rcu_read_unlock();
2810 }
2811
2812 /*
2813 * Handle user request to change the 'mems' memory placement
2814 * of a cpuset. Needs to validate the request, update the
2815 * cpusets mems_allowed, and for each task in the cpuset,
2816 * update mems_allowed and rebind task's mempolicy and any vma
2817 * mempolicies and if the cpuset is marked 'memory_migrate',
2818 * migrate the tasks pages to the new memory.
2819 *
2820 * Call with cpuset_mutex held. May take callback_lock during call.
2821 * Will take tasklist_lock, scan tasklist for tasks in cpuset cs,
2822 * lock each such tasks mm->mmap_lock, scan its vma's and rebind
2823 * their mempolicies to the cpusets new mems_allowed.
2824 */
update_nodemask(struct cpuset * cs,struct cpuset * trialcs,const char * buf)2825 static int update_nodemask(struct cpuset *cs, struct cpuset *trialcs,
2826 const char *buf)
2827 {
2828 int retval;
2829
2830 /*
2831 * An empty mems_allowed is ok iff there are no tasks in the cpuset.
2832 * The validate_change() call ensures that cpusets with tasks have memory.
2833 */
2834 retval = nodelist_parse(buf, trialcs->mems_allowed);
2835 if (retval < 0)
2836 return retval;
2837
2838 if (!nodes_subset(trialcs->mems_allowed,
2839 top_cpuset.mems_allowed))
2840 return -EINVAL;
2841
2842 /* No change? nothing to do */
2843 if (nodes_equal(cs->mems_allowed, trialcs->mems_allowed))
2844 return 0;
2845
2846 retval = validate_change(cs, trialcs);
2847 if (retval < 0)
2848 return retval;
2849
2850 check_insane_mems_config(&trialcs->mems_allowed);
2851
2852 spin_lock_irq(&callback_lock);
2853 cs->mems_allowed = trialcs->mems_allowed;
2854 spin_unlock_irq(&callback_lock);
2855
2856 /* use trialcs->mems_allowed as a temp variable */
2857 update_nodemasks_hier(cs, &trialcs->mems_allowed);
2858 return 0;
2859 }
2860
current_cpuset_is_being_rebound(void)2861 bool current_cpuset_is_being_rebound(void)
2862 {
2863 bool ret;
2864
2865 rcu_read_lock();
2866 ret = task_cs(current) == cpuset_being_rebound;
2867 rcu_read_unlock();
2868
2869 return ret;
2870 }
2871
2872 /*
2873 * cpuset_update_flag - read a 0 or a 1 in a file and update associated flag
2874 * bit: the bit to update (see cpuset_flagbits_t)
2875 * cs: the cpuset to update
2876 * turning_on: whether the flag is being set or cleared
2877 *
2878 * Call with cpuset_mutex held.
2879 */
2880
cpuset_update_flag(cpuset_flagbits_t bit,struct cpuset * cs,int turning_on)2881 int cpuset_update_flag(cpuset_flagbits_t bit, struct cpuset *cs,
2882 int turning_on)
2883 {
2884 struct cpuset *trialcs;
2885 int balance_flag_changed;
2886 int spread_page_changed;
2887 int err;
2888
2889 trialcs = dup_or_alloc_cpuset(cs);
2890 if (!trialcs)
2891 return -ENOMEM;
2892
2893 if (turning_on)
2894 set_bit(bit, &trialcs->flags);
2895 else
2896 clear_bit(bit, &trialcs->flags);
2897
2898 err = validate_change(cs, trialcs);
2899 if (err < 0)
2900 goto out;
2901
2902 balance_flag_changed = (is_sched_load_balance(cs) !=
2903 is_sched_load_balance(trialcs));
2904
2905 spread_page_changed = is_spread_page(cs) != is_spread_page(trialcs);
2906
2907 spin_lock_irq(&callback_lock);
2908 cs->flags = trialcs->flags;
2909 spin_unlock_irq(&callback_lock);
2910
2911 if (!cpumask_empty(trialcs->cpus_allowed) && balance_flag_changed) {
2912 if (cpuset_v2())
2913 cpuset_force_rebuild();
2914 else
2915 rebuild_sched_domains_locked();
2916 }
2917
2918 if (spread_page_changed)
2919 cpuset1_update_tasks_flags(cs);
2920 out:
2921 free_cpuset(trialcs);
2922 return err;
2923 }
2924
2925 /**
2926 * update_prstate - update partition_root_state
2927 * @cs: the cpuset to update
2928 * @new_prs: new partition root state
2929 * Return: 0 if successful, != 0 if error
2930 *
2931 * Call with cpuset_mutex held.
2932 */
update_prstate(struct cpuset * cs,int new_prs)2933 static int update_prstate(struct cpuset *cs, int new_prs)
2934 {
2935 int err = PERR_NONE, old_prs = cs->partition_root_state;
2936 struct cpuset *parent = parent_cs(cs);
2937 struct tmpmasks tmpmask;
2938 bool isolcpus_updated = false;
2939
2940 if (old_prs == new_prs)
2941 return 0;
2942
2943 /*
2944 * Treat a previously invalid partition root as if it is a "member".
2945 */
2946 if (new_prs && is_partition_invalid(cs))
2947 old_prs = PRS_MEMBER;
2948
2949 if (alloc_tmpmasks(&tmpmask))
2950 return -ENOMEM;
2951
2952 err = update_partition_exclusive_flag(cs, new_prs);
2953 if (err)
2954 goto out;
2955
2956 if (!old_prs) {
2957 /*
2958 * cpus_allowed and exclusive_cpus cannot be both empty.
2959 */
2960 if (xcpus_empty(cs)) {
2961 err = PERR_CPUSEMPTY;
2962 goto out;
2963 }
2964
2965 /*
2966 * We don't support the creation of a new local partition with
2967 * a remote partition underneath it. This unsupported
2968 * setting can happen only if parent is the top_cpuset because
2969 * a remote partition cannot be created underneath an existing
2970 * local or remote partition.
2971 */
2972 if ((parent == &top_cpuset) &&
2973 cpumask_intersects(cs->exclusive_cpus, subpartitions_cpus)) {
2974 err = PERR_REMOTE;
2975 goto out;
2976 }
2977
2978 /*
2979 * If parent is valid partition, enable local partiion.
2980 * Otherwise, enable a remote partition.
2981 */
2982 if (is_partition_valid(parent)) {
2983 enum partition_cmd cmd = (new_prs == PRS_ROOT)
2984 ? partcmd_enable : partcmd_enablei;
2985
2986 err = update_parent_effective_cpumask(cs, cmd, NULL, &tmpmask);
2987 } else {
2988 err = remote_partition_enable(cs, new_prs, &tmpmask);
2989 }
2990 } else if (old_prs && new_prs) {
2991 /*
2992 * A change in load balance state only, no change in cpumasks.
2993 * Need to update isolated_cpus.
2994 */
2995 if (((new_prs == PRS_ISOLATED) &&
2996 !isolated_cpus_can_update(cs->effective_xcpus, NULL)) ||
2997 prstate_housekeeping_conflict(new_prs, cs->effective_xcpus))
2998 err = PERR_HKEEPING;
2999 else
3000 isolcpus_updated = true;
3001 } else {
3002 /*
3003 * Switching back to member is always allowed even if it
3004 * disables child partitions.
3005 */
3006 if (is_remote_partition(cs))
3007 remote_partition_disable(cs, &tmpmask);
3008 else
3009 update_parent_effective_cpumask(cs, partcmd_disable,
3010 NULL, &tmpmask);
3011
3012 /*
3013 * Invalidation of child partitions will be done in
3014 * update_cpumasks_hier().
3015 */
3016 }
3017 out:
3018 /*
3019 * Make partition invalid & disable CS_CPU_EXCLUSIVE if an error
3020 * happens.
3021 */
3022 if (err) {
3023 new_prs = -new_prs;
3024 update_partition_exclusive_flag(cs, new_prs);
3025 }
3026
3027 spin_lock_irq(&callback_lock);
3028 cs->partition_root_state = new_prs;
3029 WRITE_ONCE(cs->prs_err, err);
3030 if (!is_partition_valid(cs))
3031 reset_partition_data(cs);
3032 else if (isolcpus_updated)
3033 isolated_cpus_update(old_prs, new_prs, cs->effective_xcpus);
3034 spin_unlock_irq(&callback_lock);
3035
3036 /* Force update if switching back to member & update effective_xcpus */
3037 update_cpumasks_hier(cs, &tmpmask, !new_prs);
3038
3039 /* A newly created partition must have effective_xcpus set */
3040 WARN_ON_ONCE(!old_prs && (new_prs > 0)
3041 && cpumask_empty(cs->effective_xcpus));
3042
3043 /* Update sched domains and load balance flag */
3044 update_partition_sd_lb(cs, old_prs);
3045
3046 notify_partition_change(cs, old_prs);
3047 if (force_sd_rebuild)
3048 rebuild_sched_domains_locked();
3049 free_tmpmasks(&tmpmask);
3050 return 0;
3051 }
3052
3053 /*
3054 * Check to see if a cpuset can accept a new task
3055 * For v1, cpus_allowed and mems_allowed can't be empty.
3056 * For v2, effective_cpus can't be empty.
3057 * Note that in v1, effective_cpus = cpus_allowed.
3058 *
3059 * Also set the boolean flag passed in by @psetsched depending on if
3060 * security_task_setscheduler() call is needed and @oldcs is not NULL.
3061 */
cpuset_can_attach_check(struct cpuset * cs,struct cpuset * oldcs,bool * psetsched)3062 static int cpuset_can_attach_check(struct cpuset *cs, struct cpuset *oldcs,
3063 bool *psetsched)
3064 {
3065 bool cpus_updated, mems_updated;
3066
3067 if (cpumask_empty(cs->effective_cpus) ||
3068 (!is_in_v2_mode() && nodes_empty(cs->mems_allowed)))
3069 return -ENOSPC;
3070
3071 if (!oldcs)
3072 return 0;
3073
3074 if (!llist_on_list(&oldcs->attach_node))
3075 llist_add(&oldcs->attach_node, &src_cs_head);
3076
3077 if (!llist_on_list(&cs->attach_node))
3078 llist_add(&cs->attach_node, &dst_cs_head);
3079
3080 cpus_updated = !cpumask_equal(cs->effective_cpus, oldcs->effective_cpus);
3081 mems_updated = !nodes_equal(cs->effective_mems, oldcs->effective_mems);
3082
3083 if (cpus_updated)
3084 attach_ctx.cpus_updated = true;
3085 if (mems_updated)
3086 attach_ctx.mems_updated = true;
3087
3088 /*
3089 * Skip rights over task setsched check in v2 when nothing changes for
3090 * the current oldcs/cs pair, migration permission derives from
3091 * hierarchy ownership in cgroup_procs_write_permission()).
3092 */
3093 *psetsched = !cpuset_v2() || cpus_updated || mems_updated;
3094
3095 /*
3096 * A v1 cpuset with tasks will have no CPU left only when CPU hotplug
3097 * brings the last online CPU offline as users are not allowed to empty
3098 * cpuset.cpus when there are active tasks inside. When that happens,
3099 * we should allow tasks to migrate out without security check to make
3100 * sure they will be able to run after migration.
3101 */
3102 if (!is_in_v2_mode() && cpumask_empty(oldcs->effective_cpus))
3103 *psetsched = false;
3104
3105 return 0;
3106 }
3107
cpuset_reserve_dl_bw(void)3108 static int cpuset_reserve_dl_bw(void)
3109 {
3110 struct cpuset *cs;
3111 int cpu, ret;
3112
3113 llist_for_each_entry(cs, dst_cs_head.first, attach_node) {
3114 if (!cs->sum_migrate_dl_bw)
3115 continue;
3116
3117 cpu = cpumask_any_and(cpu_active_mask, cs->effective_cpus);
3118 if (unlikely(cpu >= nr_cpu_ids))
3119 return -EINVAL;
3120
3121 ret = dl_bw_alloc(cpu, cs->sum_migrate_dl_bw);
3122 if (ret)
3123 return ret;
3124
3125 cs->dl_bw_cpu = cpu;
3126 }
3127 return 0;
3128 }
3129
3130 /*
3131 * Clear and optionally apply (@cancel is false) the attach related data in the
3132 * source or destination cpuset.
3133 */
clear_attach_data(struct llist_head * head,bool cancel)3134 static void clear_attach_data(struct llist_head *head, bool cancel)
3135 {
3136 struct cpuset *cs, *next;
3137 struct llist_node *lnode = __llist_del_all(head);
3138
3139 llist_for_each_entry_safe(cs, next, lnode, attach_node) {
3140 init_llist_node(&cs->attach_node);
3141 if (cs->nr_migrate_dl_tasks) {
3142 if (!cancel)
3143 atomic_add(cs->nr_migrate_dl_tasks, &cs->nr_deadline_tasks);
3144 else if (cs->dl_bw_cpu >= 0) /* && cancel */
3145 dl_bw_free(cs->dl_bw_cpu, cs->sum_migrate_dl_bw);
3146 cs->nr_migrate_dl_tasks = 0;
3147 cs->sum_migrate_dl_bw = 0;
3148 cs->dl_bw_cpu = -1;
3149 }
3150 }
3151 }
3152
3153 /* Called by cgroups to determine if a cpuset is usable; cpuset_mutex held */
cpuset_can_attach(struct cgroup_taskset * tset)3154 static int cpuset_can_attach(struct cgroup_taskset *tset)
3155 {
3156 struct cgroup_subsys_state *css;
3157 struct cpuset *cs, *oldcs;
3158 struct task_struct *task;
3159 bool setsched_check;
3160 int ret;
3161
3162 cs = oldcs = NULL;
3163 mutex_lock(&cpuset_mutex);
3164 attach_ctx.old_cs = NULL; /* Used later in cpuset_attach_task() */
3165 attach_ctx.cpus_updated = false;
3166 attach_ctx.mems_updated = false;
3167 attach_ctx.many_dest_cs = false;
3168
3169 /*
3170 * The attach_ctx.old_cs is used mainly by cpuset_migrate_mm() to get
3171 * the old_mems_allowed value. There are two ways that many-to-one
3172 * cpuset migration can happen:
3173 * 1) A multithread application with threads in different cpusets is
3174 * wholely migrated to a new cpuset.
3175 * 2) Disabling v2 cpuset controller will move all the tasks in child
3176 * cpusets to the parent cpuset.
3177 *
3178 * In the former case, it is the mm setting of the group leader that
3179 * really matters. So attach_ctx.old_cs should track the oldcs of the
3180 * group leader. It falls back to the oldcs of the first task if there
3181 * is no group leader in the taskset. In the latter case, effective_mems
3182 * of child cpusets must always be a subset of the parent. So no real
3183 * page migration will be necessary no matter which child cpuset is
3184 * selected as attach_ctx.old_cs.
3185 *
3186 * For a v2 threaded subtree where cpuset isn't enabled in some of the
3187 * cgroups, it is possible that oldcs == cs for some of the tasks.
3188 * In this case, we can skip checking on those tasks as there is no
3189 * actual migration wrt cpuset.
3190 */
3191 cgroup_taskset_for_each(task, css, tset) {
3192 struct cpuset *new_cs = css_cs(css);
3193 struct cpuset *new_oldcs = task_cs(task);
3194
3195 if ((new_oldcs != oldcs) || (new_cs != cs)) {
3196 if (cs && (new_cs != cs))
3197 attach_ctx.many_dest_cs = true;
3198 cs = new_cs;
3199 oldcs = new_oldcs;
3200 if (oldcs == cs)
3201 continue;
3202 if (!attach_ctx.old_cs)
3203 attach_ctx.old_cs = oldcs;
3204 ret = cpuset_can_attach_check(cs, oldcs, &setsched_check);
3205 if (ret)
3206 goto out_unlock;
3207 }
3208
3209 if (oldcs == cs)
3210 continue;
3211
3212 ret = task_can_attach(task);
3213 if (ret)
3214 goto out_unlock;
3215
3216 /* Update attach_ctx.old_cs to the latest group leader */
3217 if (task == task->group_leader)
3218 attach_ctx.old_cs = task_cs(task);
3219
3220 if (setsched_check) {
3221 ret = security_task_setscheduler(task);
3222 if (ret)
3223 goto out_unlock;
3224 }
3225
3226 if (dl_task(task)) {
3227 /*
3228 * Count all migrating DL tasks for cpuset task accounting.
3229 * Only tasks that need a root-domain bandwidth move
3230 * contribute to sum_migrate_dl_bw.
3231 */
3232 cs->nr_migrate_dl_tasks++;
3233 oldcs->nr_migrate_dl_tasks--;
3234 if (dl_task_needs_bw_move(task, cs->effective_cpus))
3235 cs->sum_migrate_dl_bw += task->dl.dl_bw;
3236 }
3237 }
3238
3239 /*
3240 * The only case where there are multiple destination cpusets for
3241 * task migration is when enabling a v2 cpuset controllers where
3242 * tasks will be migrated to multiple child cpusets from a parent
3243 * cpuset with the same effective CPUs and memory nodes. IOW,
3244 * both attach_cpus_updated and attach_mems_updated should be false.
3245 * If not, it is a condition that the current code cannot handle.
3246 * Print a warning and abort the attach operation as further code
3247 * change may be needed.
3248 */
3249 if (WARN_ON_ONCE(attach_ctx.many_dest_cs && (!cpuset_v2() ||
3250 attach_ctx.cpus_updated || attach_ctx.mems_updated))) {
3251 ret = -EINVAL;
3252 goto out_unlock;
3253 }
3254
3255 ret = cpuset_reserve_dl_bw();
3256
3257 out_unlock:
3258 if (ret) {
3259 clear_attach_data(&src_cs_head, true);
3260 clear_attach_data(&dst_cs_head, true);
3261 } else {
3262 attach_ctx.in_progress++;
3263 }
3264
3265 mutex_unlock(&cpuset_mutex);
3266 return ret;
3267 }
3268
cpuset_cancel_attach(struct cgroup_taskset * tset)3269 static void cpuset_cancel_attach(struct cgroup_taskset *tset)
3270 {
3271 mutex_lock(&cpuset_mutex);
3272 dec_attach_in_progress_locked();
3273 clear_attach_data(&src_cs_head, true);
3274 clear_attach_data(&dst_cs_head, true);
3275 mutex_unlock(&cpuset_mutex);
3276 }
3277
3278 /*
3279 * Protected by cpuset_mutex. cpus_attach is used only by cpuset_attach_task()
3280 * but we can't allocate it dynamically there. Define it global and
3281 * allocate from cpuset_init().
3282 */
3283 static cpumask_var_t cpus_attach;
3284
cpuset_attach_task(struct cpuset * cs,struct task_struct * task)3285 static void cpuset_attach_task(struct cpuset *cs, struct task_struct *task)
3286 {
3287 struct mm_struct *mm;
3288
3289 lockdep_assert_cpuset_lock_held();
3290
3291 if (cs != &top_cpuset)
3292 guarantee_active_cpus(task, cpus_attach);
3293 else
3294 cpumask_andnot(cpus_attach, task_cpu_possible_mask(task),
3295 subpartitions_cpus);
3296 /*
3297 * can_attach beforehand should guarantee that this doesn't
3298 * fail. TODO: have a better way to handle failure here
3299 */
3300 WARN_ON_ONCE(set_cpus_allowed_ptr(task, cpus_attach));
3301
3302 if (cpuset_v2() && !attach_ctx.mems_updated)
3303 return;
3304
3305 cpuset_change_task_nodemask(task, &attach_ctx.nodemask_to);
3306 cpuset1_update_task_spread_flags(cs, task);
3307
3308 if ((task != task->group_leader) || !attach_ctx.mems_updated)
3309 return;
3310
3311 /*
3312 * Change mm for threadgroup leader. This is expensive and may
3313 * sleep and should be moved outside migration path proper.
3314 */
3315 mm = get_task_mm(task);
3316 if (mm) {
3317 struct cpuset *oldcs = attach_ctx.old_cs;
3318
3319 mpol_rebind_mm(mm, &cs->effective_mems);
3320
3321 /*
3322 * old_mems_allowed is the same with mems_allowed
3323 * here, except if this task is being moved
3324 * automatically due to hotplug. In that case
3325 * @mems_allowed has been updated and is empty, so
3326 * @old_mems_allowed is the right nodesets that we
3327 * migrate mm from.
3328 */
3329 if (is_memory_migrate(cs)) {
3330 cpuset_migrate_mm(mm, &oldcs->old_mems_allowed,
3331 &attach_ctx.nodemask_to);
3332 attach_ctx.task_work_queued = true;
3333 } else {
3334 mmput(mm);
3335 }
3336 }
3337 }
3338
cpuset_attach(struct cgroup_taskset * tset)3339 static void cpuset_attach(struct cgroup_taskset *tset)
3340 {
3341 struct task_struct *task;
3342 struct cgroup_subsys_state *css;
3343 struct cpuset *cs;
3344
3345 cgroup_taskset_first(tset, &css);
3346 cs = css_cs(css);
3347
3348 lockdep_assert_cpus_held(); /* see cgroup_attach_lock() */
3349 mutex_lock(&cpuset_mutex);
3350 attach_ctx.task_work_queued = false;
3351 guarantee_online_mems(cs, &attach_ctx.nodemask_to);
3352
3353 /*
3354 * attach_ctx.old_cs can only be NULL if no task is actually migrating.
3355 * This is highly unlikely. If it happens at all, we can skip task
3356 * iteration and setting old_mems_allowed.
3357 */
3358 if (unlikely(!attach_ctx.old_cs))
3359 goto out;
3360
3361 /*
3362 * In the default hierarchy, enabling cpuset in the child cgroups
3363 * will trigger a cpuset_attach() call with no change in effective cpus
3364 * and mems. In that case, we can optimize out by skipping the task
3365 * iteration and the destination cpuset list is iterated to set
3366 * old_mems_allowed.
3367 */
3368 if (cpuset_v2() && !attach_ctx.cpus_updated && !attach_ctx.mems_updated) {
3369 llist_for_each_entry(cs, dst_cs_head.first, attach_node)
3370 cs->old_mems_allowed = attach_ctx.nodemask_to;
3371 goto out;
3372 }
3373
3374 cgroup_taskset_for_each(task, css, tset)
3375 cpuset_attach_task(cs, task);
3376
3377 if (attach_ctx.task_work_queued)
3378 schedule_flush_migrate_mm();
3379 cs->old_mems_allowed = attach_ctx.nodemask_to;
3380 out:
3381 clear_attach_data(&src_cs_head, false);
3382 clear_attach_data(&dst_cs_head, false);
3383 dec_attach_in_progress_locked();
3384
3385 mutex_unlock(&cpuset_mutex);
3386 }
3387
3388 /*
3389 * Common handling for a write to a "cpus" or "mems" file.
3390 */
cpuset_write_resmask(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)3391 ssize_t cpuset_write_resmask(struct kernfs_open_file *of,
3392 char *buf, size_t nbytes, loff_t off)
3393 {
3394 struct cpuset *cs = css_cs(of_css(of));
3395 struct cpuset *trialcs;
3396 int retval = -ENODEV;
3397
3398 /* root is read-only */
3399 if (cs == &top_cpuset)
3400 return -EACCES;
3401
3402 buf = strstrip(buf);
3403
3404 /* cpuset_mutex acquired in wait_attach_done_lock() */
3405 mutex_lock(&cpuset_top_mutex);
3406 cpus_read_lock();
3407 wait_attach_done_lock();
3408
3409 if (!is_cpuset_online(cs))
3410 goto out_unlock;
3411
3412 trialcs = dup_or_alloc_cpuset(cs);
3413 if (!trialcs) {
3414 retval = -ENOMEM;
3415 goto out_unlock;
3416 }
3417
3418 switch (of_cft(of)->private) {
3419 case FILE_CPULIST:
3420 retval = update_cpumask(cs, trialcs, buf);
3421 break;
3422 case FILE_EXCLUSIVE_CPULIST:
3423 retval = update_exclusive_cpumask(cs, trialcs, buf);
3424 break;
3425 case FILE_MEMLIST:
3426 retval = update_nodemask(cs, trialcs, buf);
3427 break;
3428 default:
3429 retval = -EINVAL;
3430 break;
3431 }
3432
3433 free_cpuset(trialcs);
3434 out_unlock:
3435 cpuset_update_sd_hk_unlock();
3436 if (of_cft(of)->private == FILE_MEMLIST)
3437 schedule_flush_migrate_mm();
3438 return retval ?: nbytes;
3439 }
3440
3441 /*
3442 * These ascii lists should be read in a single call, by using a user
3443 * buffer large enough to hold the entire map. If read in smaller
3444 * chunks, there is no guarantee of atomicity. Since the display format
3445 * used, list of ranges of sequential numbers, is variable length,
3446 * and since these maps can change value dynamically, one could read
3447 * gibberish by doing partial reads while a list was changing.
3448 */
cpuset_common_seq_show(struct seq_file * sf,void * v)3449 int cpuset_common_seq_show(struct seq_file *sf, void *v)
3450 {
3451 struct cpuset *cs = css_cs(seq_css(sf));
3452 cpuset_filetype_t type = seq_cft(sf)->private;
3453 int ret = 0;
3454
3455 spin_lock_irq(&callback_lock);
3456
3457 switch (type) {
3458 case FILE_CPULIST:
3459 seq_printf(sf, "%*pbl\n", cpumask_pr_args(cs->cpus_allowed));
3460 break;
3461 case FILE_MEMLIST:
3462 seq_printf(sf, "%*pbl\n", nodemask_pr_args(&cs->mems_allowed));
3463 break;
3464 case FILE_EFFECTIVE_CPULIST:
3465 seq_printf(sf, "%*pbl\n", cpumask_pr_args(cs->effective_cpus));
3466 break;
3467 case FILE_EFFECTIVE_MEMLIST:
3468 seq_printf(sf, "%*pbl\n", nodemask_pr_args(&cs->effective_mems));
3469 break;
3470 case FILE_EXCLUSIVE_CPULIST:
3471 seq_printf(sf, "%*pbl\n", cpumask_pr_args(cs->exclusive_cpus));
3472 break;
3473 case FILE_EFFECTIVE_XCPULIST:
3474 seq_printf(sf, "%*pbl\n", cpumask_pr_args(cs->effective_xcpus));
3475 break;
3476 case FILE_SUBPARTS_CPULIST:
3477 seq_printf(sf, "%*pbl\n", cpumask_pr_args(subpartitions_cpus));
3478 break;
3479 case FILE_ISOLATED_CPULIST:
3480 seq_printf(sf, "%*pbl\n", cpumask_pr_args(isolated_cpus));
3481 break;
3482 default:
3483 ret = -EINVAL;
3484 }
3485
3486 spin_unlock_irq(&callback_lock);
3487 return ret;
3488 }
3489
cpuset_partition_show(struct seq_file * seq,void * v)3490 static int cpuset_partition_show(struct seq_file *seq, void *v)
3491 {
3492 struct cpuset *cs = css_cs(seq_css(seq));
3493 const char *err, *type = NULL;
3494
3495 switch (cs->partition_root_state) {
3496 case PRS_ROOT:
3497 seq_puts(seq, "root\n");
3498 break;
3499 case PRS_ISOLATED:
3500 seq_puts(seq, "isolated\n");
3501 break;
3502 case PRS_MEMBER:
3503 seq_puts(seq, "member\n");
3504 break;
3505 case PRS_INVALID_ROOT:
3506 type = "root";
3507 fallthrough;
3508 case PRS_INVALID_ISOLATED:
3509 if (!type)
3510 type = "isolated";
3511 err = perr_strings[READ_ONCE(cs->prs_err)];
3512 if (err)
3513 seq_printf(seq, "%s invalid (%s)\n", type, err);
3514 else
3515 seq_printf(seq, "%s invalid\n", type);
3516 break;
3517 }
3518 return 0;
3519 }
3520
cpuset_partition_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)3521 static ssize_t cpuset_partition_write(struct kernfs_open_file *of, char *buf,
3522 size_t nbytes, loff_t off)
3523 {
3524 struct cpuset *cs = css_cs(of_css(of));
3525 int val;
3526 int retval = -ENODEV;
3527
3528 buf = strstrip(buf);
3529
3530 if (!strcmp(buf, "root"))
3531 val = PRS_ROOT;
3532 else if (!strcmp(buf, "member"))
3533 val = PRS_MEMBER;
3534 else if (!strcmp(buf, "isolated"))
3535 val = PRS_ISOLATED;
3536 else
3537 return -EINVAL;
3538
3539 mutex_lock(&cpuset_top_mutex);
3540 cpus_read_lock();
3541 wait_attach_done_lock();
3542
3543 if (is_cpuset_online(cs))
3544 retval = update_prstate(cs, val);
3545 cpuset_update_sd_hk_unlock();
3546 return retval ?: nbytes;
3547 }
3548
3549 /*
3550 * This is currently a minimal set for the default hierarchy. It can be
3551 * expanded later on by migrating more features and control files from v1.
3552 */
3553 static struct cftype dfl_files[] = {
3554 {
3555 .name = "cpus",
3556 .seq_show = cpuset_common_seq_show,
3557 .write = cpuset_write_resmask,
3558 .max_write_len = (100U + 6 * NR_CPUS),
3559 .private = FILE_CPULIST,
3560 .flags = CFTYPE_NOT_ON_ROOT,
3561 },
3562
3563 {
3564 .name = "mems",
3565 .seq_show = cpuset_common_seq_show,
3566 .write = cpuset_write_resmask,
3567 .max_write_len = (100U + 6 * MAX_NUMNODES),
3568 .private = FILE_MEMLIST,
3569 .flags = CFTYPE_NOT_ON_ROOT,
3570 },
3571
3572 {
3573 .name = "cpus.effective",
3574 .seq_show = cpuset_common_seq_show,
3575 .private = FILE_EFFECTIVE_CPULIST,
3576 },
3577
3578 {
3579 .name = "mems.effective",
3580 .seq_show = cpuset_common_seq_show,
3581 .private = FILE_EFFECTIVE_MEMLIST,
3582 },
3583
3584 {
3585 .name = "cpus.partition",
3586 .seq_show = cpuset_partition_show,
3587 .write = cpuset_partition_write,
3588 .private = FILE_PARTITION_ROOT,
3589 .flags = CFTYPE_NOT_ON_ROOT,
3590 .file_offset = offsetof(struct cpuset, partition_file),
3591 },
3592
3593 {
3594 .name = "cpus.exclusive",
3595 .seq_show = cpuset_common_seq_show,
3596 .write = cpuset_write_resmask,
3597 .max_write_len = (100U + 6 * NR_CPUS),
3598 .private = FILE_EXCLUSIVE_CPULIST,
3599 .flags = CFTYPE_NOT_ON_ROOT,
3600 },
3601
3602 {
3603 .name = "cpus.exclusive.effective",
3604 .seq_show = cpuset_common_seq_show,
3605 .private = FILE_EFFECTIVE_XCPULIST,
3606 .flags = CFTYPE_NOT_ON_ROOT,
3607 },
3608
3609 {
3610 .name = "cpus.subpartitions",
3611 .seq_show = cpuset_common_seq_show,
3612 .private = FILE_SUBPARTS_CPULIST,
3613 .flags = CFTYPE_ONLY_ON_ROOT | CFTYPE_DEBUG,
3614 },
3615
3616 {
3617 .name = "cpus.isolated",
3618 .seq_show = cpuset_common_seq_show,
3619 .private = FILE_ISOLATED_CPULIST,
3620 .flags = CFTYPE_ONLY_ON_ROOT,
3621 },
3622
3623 { } /* terminate */
3624 };
3625
3626
3627 /**
3628 * cpuset_css_alloc - Allocate a cpuset css
3629 * @parent_css: Parent css of the control group that the new cpuset will be
3630 * part of
3631 * Return: cpuset css on success, -ENOMEM on failure.
3632 *
3633 * Allocate and initialize a new cpuset css, for non-NULL @parent_css, return
3634 * top cpuset css otherwise.
3635 */
3636 static struct cgroup_subsys_state *
cpuset_css_alloc(struct cgroup_subsys_state * parent_css)3637 cpuset_css_alloc(struct cgroup_subsys_state *parent_css)
3638 {
3639 struct cpuset *cs;
3640
3641 if (!parent_css)
3642 return &top_cpuset.css;
3643
3644 cs = dup_or_alloc_cpuset(NULL);
3645 if (!cs)
3646 return ERR_PTR(-ENOMEM);
3647
3648 __set_bit(CS_SCHED_LOAD_BALANCE, &cs->flags);
3649 cpuset1_init(cs);
3650
3651 /* Set CS_MEMORY_MIGRATE for default hierarchy */
3652 if (cpuset_v2())
3653 __set_bit(CS_MEMORY_MIGRATE, &cs->flags);
3654
3655 return &cs->css;
3656 }
3657
cpuset_css_online(struct cgroup_subsys_state * css)3658 static int cpuset_css_online(struct cgroup_subsys_state *css)
3659 {
3660 struct cpuset *cs = css_cs(css);
3661 struct cpuset *parent = parent_cs(cs);
3662
3663 if (!parent)
3664 return 0;
3665
3666 cpuset_full_lock();
3667 /*
3668 * For v2, clear CS_SCHED_LOAD_BALANCE if parent is isolated
3669 */
3670 if (cpuset_v2() && !is_sched_load_balance(parent))
3671 clear_bit(CS_SCHED_LOAD_BALANCE, &cs->flags);
3672
3673 cpuset_inc();
3674
3675 spin_lock_irq(&callback_lock);
3676 if (is_in_v2_mode()) {
3677 cpumask_copy(cs->effective_cpus, parent->effective_cpus);
3678 cs->effective_mems = parent->effective_mems;
3679 }
3680 spin_unlock_irq(&callback_lock);
3681 cpuset1_online_css(css);
3682
3683 cpuset_full_unlock();
3684 return 0;
3685 }
3686
3687 /*
3688 * If the cpuset being removed has its flag 'sched_load_balance'
3689 * enabled, then simulate turning sched_load_balance off, which
3690 * will call rebuild_sched_domains_locked(). That is not needed
3691 * in the default hierarchy where only changes in partition
3692 * will cause repartitioning.
3693 */
cpuset_css_offline(struct cgroup_subsys_state * css)3694 static void cpuset_css_offline(struct cgroup_subsys_state *css)
3695 {
3696 struct cpuset *cs = css_cs(css);
3697
3698 cpuset_full_lock();
3699 if (!cpuset_v2() && is_sched_load_balance(cs))
3700 cpuset_update_flag(CS_SCHED_LOAD_BALANCE, cs, 0);
3701
3702 cpuset_dec();
3703 cpuset_full_unlock();
3704 }
3705
3706 /*
3707 * If a dying cpuset has the 'cpus.partition' enabled, turn it off by
3708 * changing it back to member to free its exclusive CPUs back to the pool to
3709 * be used by other online cpusets.
3710 */
cpuset_css_killed(struct cgroup_subsys_state * css)3711 static void cpuset_css_killed(struct cgroup_subsys_state *css)
3712 {
3713 struct cpuset *cs = css_cs(css);
3714
3715 cpuset_full_lock();
3716 /* Reset valid partition back to member */
3717 if (is_partition_valid(cs))
3718 update_prstate(cs, PRS_MEMBER);
3719 cpuset_update_sd_hk_unlock();
3720 }
3721
cpuset_css_free(struct cgroup_subsys_state * css)3722 static void cpuset_css_free(struct cgroup_subsys_state *css)
3723 {
3724 struct cpuset *cs = css_cs(css);
3725
3726 free_cpuset(cs);
3727 }
3728
cpuset_bind(struct cgroup_subsys_state * root_css)3729 static void cpuset_bind(struct cgroup_subsys_state *root_css)
3730 {
3731 mutex_lock(&cpuset_mutex);
3732 spin_lock_irq(&callback_lock);
3733
3734 if (is_in_v2_mode()) {
3735 cpumask_copy(top_cpuset.cpus_allowed, cpu_possible_mask);
3736 cpumask_copy(top_cpuset.effective_xcpus, cpu_possible_mask);
3737 top_cpuset.mems_allowed = node_possible_map;
3738 } else {
3739 cpumask_copy(top_cpuset.cpus_allowed,
3740 top_cpuset.effective_cpus);
3741 top_cpuset.mems_allowed = top_cpuset.effective_mems;
3742 }
3743
3744 spin_unlock_irq(&callback_lock);
3745 mutex_unlock(&cpuset_mutex);
3746 }
3747
3748 /*
3749 * In case the child is cloned into a cpuset different from its parent,
3750 * additional checks are done to see if the move is allowed.
3751 */
cpuset_can_fork(struct task_struct * task,struct css_set * cset)3752 static int cpuset_can_fork(struct task_struct *task, struct css_set *cset)
3753 {
3754 struct cpuset *cs = css_cs(cset->subsys[cpuset_cgrp_id]);
3755 bool same_cs;
3756 int ret;
3757
3758 rcu_read_lock();
3759 same_cs = (cs == task_cs(current));
3760 rcu_read_unlock();
3761
3762 if (same_cs)
3763 return 0;
3764
3765 lockdep_assert_held(&cgroup_mutex);
3766 mutex_lock(&cpuset_mutex);
3767
3768 /* Check to see if task is allowed in the cpuset */
3769 ret = cpuset_can_attach_check(cs, NULL, NULL);
3770 if (ret)
3771 goto out_unlock;
3772
3773 ret = task_can_attach(task);
3774 if (ret)
3775 goto out_unlock;
3776
3777 ret = security_task_setscheduler(task);
3778 if (ret)
3779 goto out_unlock;
3780
3781 attach_ctx.in_progress++;
3782 out_unlock:
3783 mutex_unlock(&cpuset_mutex);
3784 return ret;
3785 }
3786
cpuset_cancel_fork(struct task_struct * task,struct css_set * cset)3787 static void cpuset_cancel_fork(struct task_struct *task, struct css_set *cset)
3788 {
3789 struct cpuset *cs = css_cs(cset->subsys[cpuset_cgrp_id]);
3790 bool same_cs;
3791
3792 rcu_read_lock();
3793 same_cs = (cs == task_cs(current));
3794 rcu_read_unlock();
3795
3796 if (same_cs)
3797 return;
3798
3799 dec_attach_in_progress();
3800 }
3801
3802 /*
3803 * Make sure the new task conform to the current state of its parent,
3804 * which could have been changed by cpuset just after it inherits the
3805 * state from the parent and before it sits on the cgroup's task list.
3806 */
cpuset_fork(struct task_struct * task)3807 static void cpuset_fork(struct task_struct *task)
3808 {
3809 struct cpuset *cs, *oldcs;
3810
3811 rcu_read_lock();
3812 cs = task_cs(task);
3813 oldcs = task_cs(current);
3814 rcu_read_unlock();
3815
3816 if (cs == oldcs) {
3817 if (cs == &top_cpuset)
3818 return;
3819
3820 set_cpus_allowed_ptr(task, current->cpus_ptr);
3821 task->mems_allowed = current->mems_allowed;
3822 return;
3823 }
3824
3825 /* CLONE_INTO_CGROUP */
3826 mutex_lock(&cpuset_mutex);
3827 guarantee_online_mems(cs, &attach_ctx.nodemask_to);
3828 cs->old_mems_allowed = attach_ctx.nodemask_to;
3829
3830 /*
3831 * Assume CPUs and memory nodes are updated
3832 * A CLONE_INTO_CGROUP operation should have taken the cgroup mutex
3833 * and so there shouldn't be a competing cpuset_attach() operation.
3834 */
3835 attach_ctx.cpus_updated = attach_ctx.mems_updated = true;
3836 attach_ctx.task_work_queued = false;
3837 attach_ctx.old_cs = oldcs;
3838 cpuset_attach_task(cs, task);
3839 if (attach_ctx.task_work_queued)
3840 schedule_flush_migrate_mm();
3841
3842 dec_attach_in_progress_locked();
3843 mutex_unlock(&cpuset_mutex);
3844 }
3845
3846 struct cgroup_subsys cpuset_cgrp_subsys = {
3847 .css_alloc = cpuset_css_alloc,
3848 .css_online = cpuset_css_online,
3849 .css_offline = cpuset_css_offline,
3850 .css_killed = cpuset_css_killed,
3851 .css_free = cpuset_css_free,
3852 .can_attach = cpuset_can_attach,
3853 .cancel_attach = cpuset_cancel_attach,
3854 .attach = cpuset_attach,
3855 .bind = cpuset_bind,
3856 .can_fork = cpuset_can_fork,
3857 .cancel_fork = cpuset_cancel_fork,
3858 .fork = cpuset_fork,
3859 #ifdef CONFIG_CPUSETS_V1
3860 .legacy_cftypes = cpuset1_files,
3861 #endif
3862 .dfl_cftypes = dfl_files,
3863 .early_init = true,
3864 .threaded = true,
3865 };
3866
3867 /**
3868 * cpuset_init - initialize cpusets at system boot
3869 *
3870 * Description: Initialize top_cpuset
3871 **/
3872
cpuset_init(void)3873 int __init cpuset_init(void)
3874 {
3875 BUG_ON(!alloc_cpumask_var(&top_cpuset.cpus_allowed, GFP_KERNEL));
3876 BUG_ON(!alloc_cpumask_var(&top_cpuset.effective_cpus, GFP_KERNEL));
3877 BUG_ON(!alloc_cpumask_var(&top_cpuset.effective_xcpus, GFP_KERNEL));
3878 BUG_ON(!alloc_cpumask_var(&top_cpuset.exclusive_cpus, GFP_KERNEL));
3879 BUG_ON(!zalloc_cpumask_var(&subpartitions_cpus, GFP_KERNEL));
3880 BUG_ON(!zalloc_cpumask_var(&isolated_cpus, GFP_KERNEL));
3881 BUG_ON(!zalloc_cpumask_var(&isolated_hk_cpus, GFP_KERNEL));
3882
3883 cpumask_setall(top_cpuset.cpus_allowed);
3884 nodes_setall(top_cpuset.mems_allowed);
3885 cpumask_setall(top_cpuset.effective_cpus);
3886 cpumask_setall(top_cpuset.effective_xcpus);
3887 cpumask_setall(top_cpuset.exclusive_cpus);
3888 nodes_setall(top_cpuset.effective_mems);
3889 init_llist_node(&top_cpuset.attach_node);
3890
3891 cpuset1_init(&top_cpuset);
3892
3893 BUG_ON(!alloc_cpumask_var(&cpus_attach, GFP_KERNEL));
3894
3895 if (housekeeping_enabled(HK_TYPE_DOMAIN_BOOT))
3896 cpumask_andnot(isolated_cpus, cpu_possible_mask,
3897 housekeeping_cpumask(HK_TYPE_DOMAIN_BOOT));
3898
3899 return 0;
3900 }
3901
3902 static void
hotplug_update_tasks(struct cpuset * cs,struct cpumask * new_cpus,nodemask_t * new_mems,bool cpus_updated,bool mems_updated)3903 hotplug_update_tasks(struct cpuset *cs,
3904 struct cpumask *new_cpus, nodemask_t *new_mems,
3905 bool cpus_updated, bool mems_updated)
3906 {
3907 /* A partition root is allowed to have empty effective cpus */
3908 if (cpumask_empty(new_cpus) && !is_partition_valid(cs))
3909 cpumask_copy(new_cpus, parent_cs(cs)->effective_cpus);
3910 if (nodes_empty(*new_mems))
3911 *new_mems = parent_cs(cs)->effective_mems;
3912
3913 spin_lock_irq(&callback_lock);
3914 cpumask_copy(cs->effective_cpus, new_cpus);
3915 cs->effective_mems = *new_mems;
3916 spin_unlock_irq(&callback_lock);
3917
3918 if (cpus_updated)
3919 cpuset_update_tasks_cpumask(cs, new_cpus);
3920 if (mems_updated)
3921 cpuset_update_tasks_nodemask(cs);
3922 }
3923
cpuset_force_rebuild(void)3924 void cpuset_force_rebuild(void)
3925 {
3926 force_sd_rebuild = true;
3927 }
3928
3929 /**
3930 * cpuset_hotplug_update_tasks - update tasks in a cpuset for hotunplug
3931 * @cs: cpuset in interest
3932 * @tmp: the tmpmasks structure pointer
3933 *
3934 * Compare @cs's cpu and mem masks against top_cpuset and if some have gone
3935 * offline, update @cs accordingly. If @cs ends up with no CPU or memory,
3936 * all its tasks are moved to the nearest ancestor with both resources.
3937 */
cpuset_hotplug_update_tasks(struct cpuset * cs,struct tmpmasks * tmp)3938 static void cpuset_hotplug_update_tasks(struct cpuset *cs, struct tmpmasks *tmp)
3939 {
3940 static cpumask_t new_cpus;
3941 static nodemask_t new_mems;
3942 bool cpus_updated;
3943 bool mems_updated;
3944 bool remote;
3945 int partcmd = -1;
3946 struct cpuset *parent;
3947
3948 wait_attach_done_lock();
3949 parent = parent_cs(cs);
3950 compute_effective_cpumask(&new_cpus, cs, parent);
3951 compute_effective_nodemask(&new_mems, cs, parent);
3952
3953 if (!tmp || !cs->partition_root_state)
3954 goto update_tasks;
3955
3956 /*
3957 * Compute effective_cpus for valid partition root, may invalidate
3958 * child partition roots if necessary.
3959 */
3960 remote = is_remote_partition(cs);
3961 if (remote || (is_partition_valid(cs) && is_partition_valid(parent)))
3962 compute_partition_effective_cpumask(cs, &new_cpus);
3963
3964 if (remote && (cpumask_empty(subpartitions_cpus) ||
3965 (cpumask_empty(&new_cpus) &&
3966 partition_is_populated(cs, NULL)))) {
3967 WRITE_ONCE(cs->prs_err, PERR_HOTPLUG);
3968 remote_partition_disable(cs, tmp);
3969 compute_effective_cpumask(&new_cpus, cs, parent);
3970 remote = false;
3971 }
3972
3973 /*
3974 * Force the partition to become invalid if either one of
3975 * the following conditions hold:
3976 * 1) empty effective cpus but not valid empty partition.
3977 * 2) parent is invalid or doesn't grant any cpus to child
3978 * partitions.
3979 * 3) subpartitions_cpus is empty.
3980 */
3981 if (is_local_partition(cs) &&
3982 (!is_partition_valid(parent) ||
3983 tasks_nocpu_error(parent, cs, &new_cpus) ||
3984 cpumask_empty(subpartitions_cpus)))
3985 partcmd = partcmd_invalidate;
3986 /*
3987 * On the other hand, an invalid partition root may be transitioned
3988 * back to a regular one with a non-empty effective xcpus.
3989 */
3990 else if (is_partition_valid(parent) && is_partition_invalid(cs) &&
3991 !cpumask_empty(cs->effective_xcpus))
3992 partcmd = partcmd_update;
3993
3994 if (partcmd >= 0) {
3995 update_parent_effective_cpumask(cs, partcmd, NULL, tmp);
3996 if ((partcmd == partcmd_invalidate) || is_partition_valid(cs)) {
3997 compute_partition_effective_cpumask(cs, &new_cpus);
3998 cpuset_force_rebuild();
3999 }
4000 }
4001
4002 update_tasks:
4003 cpus_updated = !cpumask_equal(&new_cpus, cs->effective_cpus);
4004 mems_updated = !nodes_equal(new_mems, cs->effective_mems);
4005 if (!cpus_updated && !mems_updated)
4006 goto unlock; /* Hotplug doesn't affect this cpuset */
4007
4008 if (mems_updated)
4009 check_insane_mems_config(&new_mems);
4010
4011 if (is_in_v2_mode())
4012 hotplug_update_tasks(cs, &new_cpus, &new_mems,
4013 cpus_updated, mems_updated);
4014 else
4015 cpuset1_hotplug_update_tasks(cs, &new_cpus, &new_mems,
4016 cpus_updated, mems_updated);
4017
4018 unlock:
4019 mutex_unlock(&cpuset_mutex);
4020 }
4021
4022 /**
4023 * cpuset_handle_hotplug - handle CPU/memory hot{,un}plug for a cpuset
4024 *
4025 * This function is called after either CPU or memory configuration has
4026 * changed and updates cpuset accordingly. The top_cpuset is always
4027 * synchronized to cpu_active_mask and N_MEMORY, which is necessary in
4028 * order to make cpusets transparent (of no affect) on systems that are
4029 * actively using CPU hotplug but making no active use of cpusets.
4030 *
4031 * Non-root cpusets are only affected by offlining. If any CPUs or memory
4032 * nodes have been taken down, cpuset_hotplug_update_tasks() is invoked on
4033 * all descendants.
4034 *
4035 * Note that CPU offlining during suspend is ignored. We don't modify
4036 * cpusets across suspend/resume cycles at all.
4037 *
4038 * CPU / memory hotplug is handled synchronously.
4039 */
cpuset_handle_hotplug(void)4040 static void cpuset_handle_hotplug(void)
4041 {
4042 static DECLARE_WORK(hk_sd_work, hk_sd_workfn);
4043 static cpumask_t new_cpus;
4044 static nodemask_t new_mems;
4045 bool cpus_updated, mems_updated;
4046 bool on_dfl = is_in_v2_mode();
4047 struct tmpmasks tmp, *ptmp = NULL;
4048
4049 if (on_dfl && !alloc_tmpmasks(&tmp))
4050 ptmp = &tmp;
4051
4052 lockdep_assert_cpus_held();
4053 mutex_lock(&cpuset_mutex);
4054
4055 /* fetch the available cpus/mems and find out which changed how */
4056 cpumask_copy(&new_cpus, cpu_active_mask);
4057 new_mems = node_states[N_MEMORY];
4058
4059 /*
4060 * If subpartitions_cpus is populated, it is likely that the check
4061 * below will produce a false positive on cpus_updated when the cpu
4062 * list isn't changed. It is extra work, but it is better to be safe.
4063 */
4064 cpus_updated = !cpumask_equal(top_cpuset.effective_cpus, &new_cpus) ||
4065 !cpumask_empty(subpartitions_cpus);
4066 mems_updated = !nodes_equal(top_cpuset.effective_mems, new_mems);
4067
4068 /* For v1, synchronize cpus_allowed to cpu_active_mask */
4069 if (cpus_updated) {
4070 cpuset_force_rebuild();
4071 spin_lock_irq(&callback_lock);
4072 if (!on_dfl)
4073 cpumask_copy(top_cpuset.cpus_allowed, &new_cpus);
4074 /*
4075 * Make sure that CPUs allocated to child partitions
4076 * do not show up in effective_cpus. If no CPU is left,
4077 * we clear the subpartitions_cpus & let the child partitions
4078 * fight for the CPUs again.
4079 */
4080 if (!cpumask_empty(subpartitions_cpus)) {
4081 if (cpumask_subset(&new_cpus, subpartitions_cpus)) {
4082 cpumask_clear(subpartitions_cpus);
4083 } else {
4084 cpumask_andnot(&new_cpus, &new_cpus,
4085 subpartitions_cpus);
4086 }
4087 }
4088 cpumask_copy(top_cpuset.effective_cpus, &new_cpus);
4089 spin_unlock_irq(&callback_lock);
4090 /* we don't mess with cpumasks of tasks in top_cpuset */
4091 }
4092
4093 /* synchronize mems_allowed to N_MEMORY */
4094 if (mems_updated) {
4095 spin_lock_irq(&callback_lock);
4096 if (!on_dfl)
4097 top_cpuset.mems_allowed = new_mems;
4098 top_cpuset.effective_mems = new_mems;
4099 spin_unlock_irq(&callback_lock);
4100 cpuset_update_tasks_nodemask(&top_cpuset);
4101 }
4102
4103 mutex_unlock(&cpuset_mutex);
4104
4105 /* if cpus or mems changed, we need to propagate to descendants */
4106 if (cpus_updated || mems_updated) {
4107 struct cpuset *cs;
4108 struct cgroup_subsys_state *pos_css;
4109
4110 rcu_read_lock();
4111 cpuset_for_each_descendant_pre(cs, pos_css, &top_cpuset) {
4112 if (cs == &top_cpuset || !css_tryget_online(&cs->css))
4113 continue;
4114 rcu_read_unlock();
4115
4116 cpuset_hotplug_update_tasks(cs, ptmp);
4117
4118 rcu_read_lock();
4119 css_put(&cs->css);
4120 }
4121 rcu_read_unlock();
4122 }
4123
4124 /*
4125 * rebuild_sched_domains() will always be called directly if needed
4126 * to make sure that newly added or removed CPU will be reflected in
4127 * the sched domains. However, if isolated partition invalidation
4128 * or recreation is being done (update_housekeeping set), a work item
4129 * will be queued to call housekeeping_update() to update the
4130 * corresponding housekeeping cpumasks after some slight delay.
4131 *
4132 * We rely on WORK_STRUCT_PENDING_BIT to not requeue a work item that
4133 * is still pending. Before the pending bit is cleared, the work data
4134 * is copied out and work item dequeued. So it is possible to queue
4135 * the work again before the hk_sd_workfn() is invoked to process the
4136 * previously queued work. Since hk_sd_workfn() doesn't use the work
4137 * item at all, this is not a problem.
4138 */
4139 if (force_sd_rebuild)
4140 rebuild_sched_domains_cpuslocked();
4141 if (update_housekeeping)
4142 queue_work(system_dfl_wq, &hk_sd_work);
4143
4144 free_tmpmasks(ptmp);
4145 }
4146
cpuset_update_active_cpus(void)4147 void cpuset_update_active_cpus(void)
4148 {
4149 /*
4150 * We're inside cpu hotplug critical region which usually nests
4151 * inside cgroup synchronization. Bounce actual hotplug processing
4152 * to a work item to avoid reverse locking order.
4153 */
4154 cpuset_handle_hotplug();
4155 }
4156
4157 /*
4158 * Keep top_cpuset.mems_allowed tracking node_states[N_MEMORY].
4159 * Call this routine anytime after node_states[N_MEMORY] changes.
4160 * See cpuset_update_active_cpus() for CPU hotplug handling.
4161 */
cpuset_track_online_nodes(struct notifier_block * self,unsigned long action,void * arg)4162 static int cpuset_track_online_nodes(struct notifier_block *self,
4163 unsigned long action, void *arg)
4164 {
4165 cpuset_handle_hotplug();
4166 return NOTIFY_OK;
4167 }
4168
4169 /**
4170 * cpuset_init_smp - initialize cpus_allowed
4171 *
4172 * Description: Finish top cpuset after cpu, node maps are initialized
4173 */
cpuset_init_smp(void)4174 void __init cpuset_init_smp(void)
4175 {
4176 /*
4177 * cpus_allowd/mems_allowed set to v2 values in the initial
4178 * cpuset_bind() call will be reset to v1 values in another
4179 * cpuset_bind() call when v1 cpuset is mounted.
4180 */
4181 top_cpuset.old_mems_allowed = top_cpuset.mems_allowed;
4182
4183 cpumask_copy(top_cpuset.effective_cpus, cpu_active_mask);
4184 top_cpuset.effective_mems = node_states[N_MEMORY];
4185
4186 hotplug_node_notifier(cpuset_track_online_nodes, CPUSET_CALLBACK_PRI);
4187
4188 cpuset_migrate_mm_wq = alloc_ordered_workqueue("cpuset_migrate_mm", 0);
4189 BUG_ON(!cpuset_migrate_mm_wq);
4190 }
4191
4192 /*
4193 * Return cpus_allowed mask from a task's cpuset.
4194 */
__cpuset_cpus_allowed_locked(struct task_struct * tsk,struct cpumask * pmask)4195 static void __cpuset_cpus_allowed_locked(struct task_struct *tsk, struct cpumask *pmask)
4196 {
4197 struct cpuset *cs;
4198
4199 cs = task_cs(tsk);
4200 if (cs != &top_cpuset)
4201 guarantee_active_cpus(tsk, pmask);
4202 /*
4203 * Tasks in the top cpuset won't get update to their cpumasks
4204 * when a hotplug online/offline event happens. So we include all
4205 * offline cpus in the allowed cpu list.
4206 */
4207 if ((cs == &top_cpuset) || cpumask_empty(pmask)) {
4208 const struct cpumask *possible_mask = task_cpu_possible_mask(tsk);
4209
4210 /*
4211 * We first exclude cpus allocated to partitions. If there is no
4212 * allowable online cpu left, we fall back to all possible cpus.
4213 */
4214 cpumask_andnot(pmask, possible_mask, subpartitions_cpus);
4215 if (!cpumask_intersects(pmask, cpu_active_mask))
4216 cpumask_copy(pmask, possible_mask);
4217 }
4218 }
4219
4220 /**
4221 * cpuset_cpus_allowed_locked - return cpus_allowed mask from a task's cpuset.
4222 * @tsk: pointer to task_struct from which to obtain cpuset->cpus_allowed.
4223 * @pmask: pointer to struct cpumask variable to receive cpus_allowed set.
4224 *
4225 * Similir to cpuset_cpus_allowed() except that the caller must have acquired
4226 * cpuset_mutex.
4227 */
cpuset_cpus_allowed_locked(struct task_struct * tsk,struct cpumask * pmask)4228 void cpuset_cpus_allowed_locked(struct task_struct *tsk, struct cpumask *pmask)
4229 {
4230 lockdep_assert_cpuset_lock_held();
4231 __cpuset_cpus_allowed_locked(tsk, pmask);
4232 }
4233
4234 /**
4235 * cpuset_cpus_allowed - return cpus_allowed mask from a task's cpuset.
4236 * @tsk: pointer to task_struct from which to obtain cpuset->cpus_allowed.
4237 * @pmask: pointer to struct cpumask variable to receive cpus_allowed set.
4238 *
4239 * Description: Returns the cpumask_var_t cpus_allowed of the cpuset
4240 * attached to the specified @tsk. Guaranteed to return some non-empty
4241 * subset of cpu_active_mask, even if this means going outside the
4242 * tasks cpuset, except when the task is in the top cpuset.
4243 **/
4244
cpuset_cpus_allowed(struct task_struct * tsk,struct cpumask * pmask)4245 void cpuset_cpus_allowed(struct task_struct *tsk, struct cpumask *pmask)
4246 {
4247 unsigned long flags;
4248
4249 spin_lock_irqsave(&callback_lock, flags);
4250 __cpuset_cpus_allowed_locked(tsk, pmask);
4251 spin_unlock_irqrestore(&callback_lock, flags);
4252 }
4253
4254 /**
4255 * cpuset_cpus_allowed_fallback - final fallback before complete catastrophe.
4256 * @tsk: pointer to task_struct with which the scheduler is struggling
4257 *
4258 * Description: In the case that the scheduler cannot find an allowed cpu in
4259 * tsk->cpus_allowed, we fall back to task_cs(tsk)->cpus_allowed. In legacy
4260 * mode however, this value is the same as task_cs(tsk)->effective_cpus,
4261 * which will not contain a sane cpumask during cases such as cpu hotplugging.
4262 * This is the absolute last resort for the scheduler and it is only used if
4263 * _every_ other avenue has been traveled.
4264 *
4265 * Returns true if the affinity of @tsk was changed, false otherwise.
4266 **/
4267
cpuset_cpus_allowed_fallback(struct task_struct * tsk)4268 bool cpuset_cpus_allowed_fallback(struct task_struct *tsk)
4269 {
4270 const struct cpumask *possible_mask = task_cpu_possible_mask(tsk);
4271 const struct cpumask *cs_mask;
4272 bool changed = false;
4273
4274 rcu_read_lock();
4275 cs_mask = task_cs(tsk)->cpus_allowed;
4276 if (is_in_v2_mode() && cpumask_subset(cs_mask, possible_mask)) {
4277 set_cpus_allowed_force(tsk, cs_mask);
4278 changed = true;
4279 }
4280 rcu_read_unlock();
4281
4282 /*
4283 * We own tsk->cpus_allowed, nobody can change it under us.
4284 *
4285 * But we used cs && cs->cpus_allowed lockless and thus can
4286 * race with cgroup_attach_task() or update_cpumask() and get
4287 * the wrong tsk->cpus_allowed. However, both cases imply the
4288 * subsequent cpuset_change_cpumask()->set_cpus_allowed_ptr()
4289 * which takes task_rq_lock().
4290 *
4291 * If we are called after it dropped the lock we must see all
4292 * changes in tsk_cs()->cpus_allowed. Otherwise we can temporary
4293 * set any mask even if it is not right from task_cs() pov,
4294 * the pending set_cpus_allowed_ptr() will fix things.
4295 *
4296 * select_fallback_rq() will fix things ups and set cpu_possible_mask
4297 * if required.
4298 */
4299 return changed;
4300 }
4301
4302 /*
4303 * Returns the number of CPUs available for this cgroup.
4304 *
4305 * This only really works for cgroup-v2 where all the controllers are mounted
4306 * in the same hierarchy. If not cgroup-v2 or no cpuset controller is
4307 * configured it reverts to num_online_cpus().
4308 */
cpuset_num_cpus(struct cgroup * cgrp)4309 int cpuset_num_cpus(struct cgroup *cgrp)
4310 {
4311 int nr = num_online_cpus();
4312 struct cpuset *cs;
4313
4314 if (is_in_v2_mode()) {
4315 guard(rcu)();
4316 cs = css_cs(cgroup_e_css(cgrp, &cpuset_cgrp_subsys));
4317 if (cs)
4318 nr = cpumask_weight(cs->effective_cpus);
4319 }
4320
4321 return nr;
4322 }
4323
cpuset_init_current_mems_allowed(void)4324 void __init cpuset_init_current_mems_allowed(void)
4325 {
4326 nodes_setall(current->mems_allowed);
4327 }
4328
4329 /**
4330 * cpuset_mems_allowed - return mems_allowed mask from a tasks cpuset.
4331 * @tsk: pointer to task_struct from which to obtain cpuset->mems_allowed.
4332 *
4333 * Description: Returns the nodemask_t mems_allowed of the cpuset
4334 * attached to the specified @tsk. Guaranteed to return some non-empty
4335 * subset of node_states[N_MEMORY], even if this means going outside the
4336 * tasks cpuset.
4337 **/
4338
cpuset_mems_allowed(struct task_struct * tsk)4339 nodemask_t cpuset_mems_allowed(struct task_struct *tsk)
4340 {
4341 nodemask_t mask;
4342 unsigned long flags;
4343
4344 spin_lock_irqsave(&callback_lock, flags);
4345 guarantee_online_mems(task_cs(tsk), &mask);
4346 spin_unlock_irqrestore(&callback_lock, flags);
4347
4348 return mask;
4349 }
4350
4351 /**
4352 * cpuset_nodemask_valid_mems_allowed - check nodemask vs. current mems_allowed
4353 * @nodemask: the nodemask to be checked
4354 *
4355 * Are any of the nodes in the nodemask allowed in current->mems_allowed?
4356 */
cpuset_nodemask_valid_mems_allowed(const nodemask_t * nodemask)4357 int cpuset_nodemask_valid_mems_allowed(const nodemask_t *nodemask)
4358 {
4359 return nodes_intersects(*nodemask, current->mems_allowed);
4360 }
4361
4362 /*
4363 * nearest_hardwall_ancestor() - Returns the nearest mem_exclusive or
4364 * mem_hardwall ancestor to the specified cpuset. Call holding
4365 * callback_lock. If no ancestor is mem_exclusive or mem_hardwall
4366 * (an unusual configuration), then returns the root cpuset.
4367 */
nearest_hardwall_ancestor(struct cpuset * cs)4368 static struct cpuset *nearest_hardwall_ancestor(struct cpuset *cs)
4369 {
4370 while (!(is_mem_exclusive(cs) || is_mem_hardwall(cs)) && parent_cs(cs))
4371 cs = parent_cs(cs);
4372 return cs;
4373 }
4374
4375 /*
4376 * cpuset_current_node_allowed - Can current task allocate on a memory node?
4377 * @node: is this an allowed node?
4378 * @gfp_mask: memory allocation flags
4379 *
4380 * If we're in interrupt, yes, we can always allocate. If @node is set in
4381 * current's mems_allowed, yes. If it's not a __GFP_HARDWALL request and this
4382 * node is set in the nearest hardwalled cpuset ancestor to current's cpuset,
4383 * yes. If current has access to memory reserves as an oom victim, yes.
4384 * If the current task is PF_EXITING, yes. Otherwise, no.
4385 *
4386 * GFP_USER allocations are marked with the __GFP_HARDWALL bit,
4387 * and do not allow allocations outside the current tasks cpuset
4388 * unless the task has been OOM killed or is exiting.
4389 * GFP_KERNEL allocations are not so marked, so can escape to the
4390 * nearest enclosing hardwalled ancestor cpuset.
4391 *
4392 * Scanning up parent cpusets requires callback_lock. The
4393 * page allocator only calls here with __GFP_HARDWALL bit
4394 * _not_ set if it's a GFP_KERNEL allocation, and all nodes in the
4395 * current tasks mems_allowed came up empty on the first pass over
4396 * the zonelist. So only GFP_KERNEL allocations, if all nodes in the
4397 * cpuset are short of memory, might require taking the callback_lock.
4398 *
4399 * The first call here from mm/page_alloc:get_page_from_freelist()
4400 * has __GFP_HARDWALL set in gfp_mask, enforcing hardwall cpusets,
4401 * so no allocation on a node outside the cpuset is allowed (unless
4402 * in interrupt, of course). The PF_EXITING check must therefore
4403 * come before the __GFP_HARDWALL check, otherwise a dying task
4404 * would be blocked on the fast path.
4405 *
4406 * The second pass through get_page_from_freelist() doesn't even call here for
4407 * GFP_ATOMIC calls. That, and the checks below have the combined affect that:
4408 * in_interrupt - any node ok (current task context irrelevant)
4409 * GFP_ATOMIC - any node ok
4410 * tsk_is_oom_victim - any node ok
4411 * PF_EXITING - any node ok (let dying task exit quickly)
4412 * GFP_KERNEL - any node in enclosing hardwalled cpuset ok
4413 * GFP_USER - only nodes in current tasks mems allowed ok.
4414 */
cpuset_current_node_allowed(int node,gfp_t gfp_mask)4415 bool cpuset_current_node_allowed(int node, gfp_t gfp_mask)
4416 {
4417 struct cpuset *cs; /* current cpuset ancestors */
4418 bool allowed; /* is allocation in zone z allowed? */
4419 unsigned long flags;
4420
4421 if (in_interrupt())
4422 return true;
4423 if (node_isset(node, current->mems_allowed))
4424 return true;
4425 /*
4426 * Allow tasks that have access to memory reserves because they have
4427 * been OOM killed to get memory anywhere.
4428 */
4429 if (unlikely(tsk_is_oom_victim(current)))
4430 return true;
4431 if (current->flags & PF_EXITING) /* Let dying task have memory */
4432 return true;
4433 if (gfp_mask & __GFP_HARDWALL) /* If hardwall request, stop here */
4434 return false;
4435
4436 if (cpuset_v2())
4437 return true;
4438
4439 /* Not hardwall and node outside mems_allowed: scan up cpusets */
4440 spin_lock_irqsave(&callback_lock, flags);
4441
4442 cs = nearest_hardwall_ancestor(task_cs(current));
4443 allowed = node_isset(node, cs->mems_allowed);
4444
4445 spin_unlock_irqrestore(&callback_lock, flags);
4446 return allowed;
4447 }
4448
4449 /**
4450 * cpuset_nodes_allowed - return effective_mems mask from a cgroup cpuset.
4451 * @cgroup: pointer to struct cgroup.
4452 * @mask: pointer to struct nodemask_t to be returned.
4453 *
4454 * Returns effective_mems mask from a cgroup cpuset if it is cgroup v2 and
4455 * has cpuset subsys. Otherwise, returns node_states[N_MEMORY].
4456 *
4457 * This function intentionally avoids taking the cpuset_mutex or callback_lock
4458 * when accessing effective_mems. This is because the obtained effective_mems
4459 * is stale immediately after the query anyway (e.g., effective_mems is updated
4460 * immediately after releasing the lock but before returning).
4461 *
4462 * As a result, returned @mask may be empty because cs->effective_mems can be
4463 * rebound during this call. Besides, nodes in @mask are not guaranteed to be
4464 * online due to hot plugins. Callers should check the mask for validity on
4465 * return based on its subsequent use.
4466 **/
cpuset_nodes_allowed(struct cgroup * cgroup,nodemask_t * mask)4467 void cpuset_nodes_allowed(struct cgroup *cgroup, nodemask_t *mask)
4468 {
4469 struct cgroup_subsys_state *css;
4470 struct cpuset *cs;
4471
4472 /*
4473 * In v1, mem_cgroup and cpuset are unlikely in the same hierarchy
4474 * and mems_allowed is likely to be empty even if we could get to it,
4475 * so return directly to avoid taking a global lock on the empty check.
4476 */
4477 if (!cgroup || !cpuset_v2()) {
4478 nodes_copy(*mask, node_states[N_MEMORY]);
4479 return;
4480 }
4481
4482 css = cgroup_get_e_css(cgroup, &cpuset_cgrp_subsys);
4483 if (!css) {
4484 nodes_copy(*mask, node_states[N_MEMORY]);
4485 return;
4486 }
4487
4488 /*
4489 * The reference taken via cgroup_get_e_css is sufficient to
4490 * protect css, but it does not imply safe accesses to effective_mems.
4491 *
4492 * Normally, accessing effective_mems would require the cpuset_mutex
4493 * or callback_lock - but the correctness of this information is stale
4494 * immediately after the query anyway. We do not acquire the lock
4495 * during this process to save lock contention in exchange for racing
4496 * against mems_allowed rebinds.
4497 */
4498 cs = container_of(css, struct cpuset, css);
4499 nodes_copy(*mask, cs->effective_mems);
4500 css_put(css);
4501 }
4502
4503 /**
4504 * cpuset_spread_node() - On which node to begin search for a page
4505 * @rotor: round robin rotor
4506 *
4507 * If a task is marked PFA_SPREAD_PAGE and a page cache allocation uses
4508 * cpuset_mem_spread_node() to determine where to start looking, spread the
4509 * starting node around the task's mems_allowed nodes instead of starting on
4510 * the local node.
4511 *
4512 * We don't have to worry about the returned node being offline
4513 * because "it can't happen", and even if it did, it would be ok.
4514 *
4515 * The routines calling guarantee_online_mems() are careful to
4516 * only set nodes in task->mems_allowed that are online. So it
4517 * should not be possible for the following code to return an
4518 * offline node. But if it did, that would be ok, as this routine
4519 * is not returning the node where the allocation must be, only
4520 * the node where the search should start. The zonelist used by
4521 * the allocator will include all nodes. If the slab allocator
4522 * is passed an offline node, it will fall back to the local node.
4523 * See kmem_cache_alloc_node().
4524 */
cpuset_spread_node(int * rotor)4525 static int cpuset_spread_node(int *rotor)
4526 {
4527 return *rotor = next_node_in(*rotor, current->mems_allowed);
4528 }
4529
4530 /**
4531 * cpuset_mem_spread_node() - On which node to begin search for a file page
4532 */
cpuset_mem_spread_node(void)4533 int cpuset_mem_spread_node(void)
4534 {
4535 if (current->cpuset_mem_spread_rotor == NUMA_NO_NODE)
4536 current->cpuset_mem_spread_rotor =
4537 node_random(¤t->mems_allowed);
4538
4539 return cpuset_spread_node(¤t->cpuset_mem_spread_rotor);
4540 }
4541
4542 /**
4543 * cpuset_mems_allowed_intersects - Does @tsk1's mems_allowed intersect @tsk2's?
4544 * @tsk1: pointer to task_struct of some task.
4545 * @tsk2: pointer to task_struct of some other task.
4546 *
4547 * Description: Return true if @tsk1's mems_allowed intersects the
4548 * mems_allowed of @tsk2. Used by the OOM killer to determine if
4549 * one of the task's memory usage might impact the memory available
4550 * to the other.
4551 **/
4552
cpuset_mems_allowed_intersects(const struct task_struct * tsk1,const struct task_struct * tsk2)4553 int cpuset_mems_allowed_intersects(const struct task_struct *tsk1,
4554 const struct task_struct *tsk2)
4555 {
4556 return nodes_intersects(tsk1->mems_allowed, tsk2->mems_allowed);
4557 }
4558
4559 /**
4560 * cpuset_print_current_mems_allowed - prints current's cpuset and mems_allowed
4561 *
4562 * Description: Prints current's name, cpuset name, and cached copy of its
4563 * mems_allowed to the kernel log.
4564 */
cpuset_print_current_mems_allowed(void)4565 void cpuset_print_current_mems_allowed(void)
4566 {
4567 struct cgroup *cgrp;
4568
4569 rcu_read_lock();
4570
4571 cgrp = task_cs(current)->css.cgroup;
4572 pr_cont(",cpuset=");
4573 pr_cont_cgroup_name(cgrp);
4574 pr_cont(",mems_allowed=%*pbl",
4575 nodemask_pr_args(¤t->mems_allowed));
4576
4577 rcu_read_unlock();
4578 }
4579
4580 /* Display task mems_allowed in /proc/<pid>/status file. */
cpuset_task_status_allowed(struct seq_file * m,struct task_struct * task)4581 void cpuset_task_status_allowed(struct seq_file *m, struct task_struct *task)
4582 {
4583 seq_printf(m, "Mems_allowed:\t%*pb\n",
4584 nodemask_pr_args(&task->mems_allowed));
4585 seq_printf(m, "Mems_allowed_list:\t%*pbl\n",
4586 nodemask_pr_args(&task->mems_allowed));
4587 }
4588