xref: /linux/kernel/padata.c (revision 0d24f1b7)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * padata.c - generic interface to process data streams in parallel
4  *
5  * See Documentation/core-api/padata.rst for more information.
6  *
7  * Copyright (C) 2008, 2009 secunet Security Networks AG
8  * Copyright (C) 2008, 2009 Steffen Klassert <steffen.klassert@secunet.com>
9  *
10  * Copyright (c) 2020 Oracle and/or its affiliates.
11  * Author: Daniel Jordan <daniel.m.jordan@oracle.com>
12  */
13 
14 #include <linux/completion.h>
15 #include <linux/export.h>
16 #include <linux/cpumask.h>
17 #include <linux/err.h>
18 #include <linux/cpu.h>
19 #include <linux/padata.h>
20 #include <linux/mutex.h>
21 #include <linux/sched.h>
22 #include <linux/slab.h>
23 #include <linux/sysfs.h>
24 #include <linux/rcupdate.h>
25 
26 #define	PADATA_WORK_ONSTACK	1	/* Work's memory is on stack */
27 
28 struct padata_work {
29 	struct work_struct	pw_work;
30 	struct list_head	pw_list;  /* padata_free_works linkage */
31 	void			*pw_data;
32 };
33 
34 static DEFINE_SPINLOCK(padata_works_lock);
35 static struct padata_work *padata_works;
36 static LIST_HEAD(padata_free_works);
37 
38 struct padata_mt_job_state {
39 	spinlock_t		lock;
40 	struct completion	completion;
41 	struct padata_mt_job	*job;
42 	int			nworks;
43 	int			nworks_fini;
44 	unsigned long		chunk_size;
45 };
46 
47 static void padata_free_pd(struct parallel_data *pd);
48 static void __init padata_mt_helper(struct work_struct *work);
49 
50 static int padata_index_to_cpu(struct parallel_data *pd, int cpu_index)
51 {
52 	int cpu, target_cpu;
53 
54 	target_cpu = cpumask_first(pd->cpumask.pcpu);
55 	for (cpu = 0; cpu < cpu_index; cpu++)
56 		target_cpu = cpumask_next(target_cpu, pd->cpumask.pcpu);
57 
58 	return target_cpu;
59 }
60 
61 static int padata_cpu_hash(struct parallel_data *pd, unsigned int seq_nr)
62 {
63 	/*
64 	 * Hash the sequence numbers to the cpus by taking
65 	 * seq_nr mod. number of cpus in use.
66 	 */
67 	int cpu_index = seq_nr % cpumask_weight(pd->cpumask.pcpu);
68 
69 	return padata_index_to_cpu(pd, cpu_index);
70 }
71 
72 static struct padata_work *padata_work_alloc(void)
73 {
74 	struct padata_work *pw;
75 
76 	lockdep_assert_held(&padata_works_lock);
77 
78 	if (list_empty(&padata_free_works))
79 		return NULL;	/* No more work items allowed to be queued. */
80 
81 	pw = list_first_entry(&padata_free_works, struct padata_work, pw_list);
82 	list_del(&pw->pw_list);
83 	return pw;
84 }
85 
86 /*
87  * This function is marked __ref because this function may be optimized in such
88  * a way that it directly refers to work_fn's address, which causes modpost to
89  * complain when work_fn is marked __init. This scenario was observed with clang
90  * LTO, where padata_work_init() was optimized to refer directly to
91  * padata_mt_helper() because the calls to padata_work_init() with other work_fn
92  * values were eliminated or inlined.
93  */
94 static void __ref padata_work_init(struct padata_work *pw, work_func_t work_fn,
95 				   void *data, int flags)
96 {
97 	if (flags & PADATA_WORK_ONSTACK)
98 		INIT_WORK_ONSTACK(&pw->pw_work, work_fn);
99 	else
100 		INIT_WORK(&pw->pw_work, work_fn);
101 	pw->pw_data = data;
102 }
103 
104 static int __init padata_work_alloc_mt(int nworks, void *data,
105 				       struct list_head *head)
106 {
107 	int i;
108 
109 	spin_lock(&padata_works_lock);
110 	/* Start at 1 because the current task participates in the job. */
111 	for (i = 1; i < nworks; ++i) {
112 		struct padata_work *pw = padata_work_alloc();
113 
114 		if (!pw)
115 			break;
116 		padata_work_init(pw, padata_mt_helper, data, 0);
117 		list_add(&pw->pw_list, head);
118 	}
119 	spin_unlock(&padata_works_lock);
120 
121 	return i;
122 }
123 
124 static void padata_work_free(struct padata_work *pw)
125 {
126 	lockdep_assert_held(&padata_works_lock);
127 	list_add(&pw->pw_list, &padata_free_works);
128 }
129 
130 static void __init padata_works_free(struct list_head *works)
131 {
132 	struct padata_work *cur, *next;
133 
134 	if (list_empty(works))
135 		return;
136 
137 	spin_lock(&padata_works_lock);
138 	list_for_each_entry_safe(cur, next, works, pw_list) {
139 		list_del(&cur->pw_list);
140 		padata_work_free(cur);
141 	}
142 	spin_unlock(&padata_works_lock);
143 }
144 
145 static void padata_parallel_worker(struct work_struct *parallel_work)
146 {
147 	struct padata_work *pw = container_of(parallel_work, struct padata_work,
148 					      pw_work);
149 	struct padata_priv *padata = pw->pw_data;
150 
151 	local_bh_disable();
152 	padata->parallel(padata);
153 	spin_lock(&padata_works_lock);
154 	padata_work_free(pw);
155 	spin_unlock(&padata_works_lock);
156 	local_bh_enable();
157 }
158 
159 /**
160  * padata_do_parallel - padata parallelization function
161  *
162  * @ps: padatashell
163  * @padata: object to be parallelized
164  * @cb_cpu: pointer to the CPU that the serialization callback function should
165  *          run on.  If it's not in the serial cpumask of @pinst
166  *          (i.e. cpumask.cbcpu), this function selects a fallback CPU and if
167  *          none found, returns -EINVAL.
168  *
169  * The parallelization callback function will run with BHs off.
170  * Note: Every object which is parallelized by padata_do_parallel
171  * must be seen by padata_do_serial.
172  *
173  * Return: 0 on success or else negative error code.
174  */
175 int padata_do_parallel(struct padata_shell *ps,
176 		       struct padata_priv *padata, int *cb_cpu)
177 {
178 	struct padata_instance *pinst = ps->pinst;
179 	int i, cpu, cpu_index, err;
180 	struct parallel_data *pd;
181 	struct padata_work *pw;
182 
183 	rcu_read_lock_bh();
184 
185 	pd = rcu_dereference_bh(ps->pd);
186 
187 	err = -EINVAL;
188 	if (!(pinst->flags & PADATA_INIT) || pinst->flags & PADATA_INVALID)
189 		goto out;
190 
191 	if (!cpumask_test_cpu(*cb_cpu, pd->cpumask.cbcpu)) {
192 		if (cpumask_empty(pd->cpumask.cbcpu))
193 			goto out;
194 
195 		/* Select an alternate fallback CPU and notify the caller. */
196 		cpu_index = *cb_cpu % cpumask_weight(pd->cpumask.cbcpu);
197 
198 		cpu = cpumask_first(pd->cpumask.cbcpu);
199 		for (i = 0; i < cpu_index; i++)
200 			cpu = cpumask_next(cpu, pd->cpumask.cbcpu);
201 
202 		*cb_cpu = cpu;
203 	}
204 
205 	err =  -EBUSY;
206 	if ((pinst->flags & PADATA_RESET))
207 		goto out;
208 
209 	refcount_inc(&pd->refcnt);
210 	padata->pd = pd;
211 	padata->cb_cpu = *cb_cpu;
212 
213 	spin_lock(&padata_works_lock);
214 	padata->seq_nr = ++pd->seq_nr;
215 	pw = padata_work_alloc();
216 	spin_unlock(&padata_works_lock);
217 
218 	rcu_read_unlock_bh();
219 
220 	if (pw) {
221 		padata_work_init(pw, padata_parallel_worker, padata, 0);
222 		queue_work(pinst->parallel_wq, &pw->pw_work);
223 	} else {
224 		/* Maximum works limit exceeded, run in the current task. */
225 		padata->parallel(padata);
226 	}
227 
228 	return 0;
229 out:
230 	rcu_read_unlock_bh();
231 
232 	return err;
233 }
234 EXPORT_SYMBOL(padata_do_parallel);
235 
236 /*
237  * padata_find_next - Find the next object that needs serialization.
238  *
239  * Return:
240  * * A pointer to the control struct of the next object that needs
241  *   serialization, if present in one of the percpu reorder queues.
242  * * NULL, if the next object that needs serialization will
243  *   be parallel processed by another cpu and is not yet present in
244  *   the cpu's reorder queue.
245  */
246 static struct padata_priv *padata_find_next(struct parallel_data *pd,
247 					    bool remove_object)
248 {
249 	struct padata_priv *padata;
250 	struct padata_list *reorder;
251 	int cpu = pd->cpu;
252 
253 	reorder = per_cpu_ptr(pd->reorder_list, cpu);
254 
255 	spin_lock(&reorder->lock);
256 	if (list_empty(&reorder->list)) {
257 		spin_unlock(&reorder->lock);
258 		return NULL;
259 	}
260 
261 	padata = list_entry(reorder->list.next, struct padata_priv, list);
262 
263 	/*
264 	 * Checks the rare case where two or more parallel jobs have hashed to
265 	 * the same CPU and one of the later ones finishes first.
266 	 */
267 	if (padata->seq_nr != pd->processed) {
268 		spin_unlock(&reorder->lock);
269 		return NULL;
270 	}
271 
272 	if (remove_object) {
273 		list_del_init(&padata->list);
274 		++pd->processed;
275 		pd->cpu = cpumask_next_wrap(cpu, pd->cpumask.pcpu, -1, false);
276 	}
277 
278 	spin_unlock(&reorder->lock);
279 	return padata;
280 }
281 
282 static void padata_reorder(struct parallel_data *pd)
283 {
284 	struct padata_instance *pinst = pd->ps->pinst;
285 	int cb_cpu;
286 	struct padata_priv *padata;
287 	struct padata_serial_queue *squeue;
288 	struct padata_list *reorder;
289 
290 	/*
291 	 * We need to ensure that only one cpu can work on dequeueing of
292 	 * the reorder queue the time. Calculating in which percpu reorder
293 	 * queue the next object will arrive takes some time. A spinlock
294 	 * would be highly contended. Also it is not clear in which order
295 	 * the objects arrive to the reorder queues. So a cpu could wait to
296 	 * get the lock just to notice that there is nothing to do at the
297 	 * moment. Therefore we use a trylock and let the holder of the lock
298 	 * care for all the objects enqueued during the holdtime of the lock.
299 	 */
300 	if (!spin_trylock_bh(&pd->lock))
301 		return;
302 
303 	while (1) {
304 		padata = padata_find_next(pd, true);
305 
306 		/*
307 		 * If the next object that needs serialization is parallel
308 		 * processed by another cpu and is still on it's way to the
309 		 * cpu's reorder queue, nothing to do for now.
310 		 */
311 		if (!padata)
312 			break;
313 
314 		cb_cpu = padata->cb_cpu;
315 		squeue = per_cpu_ptr(pd->squeue, cb_cpu);
316 
317 		spin_lock(&squeue->serial.lock);
318 		list_add_tail(&padata->list, &squeue->serial.list);
319 		spin_unlock(&squeue->serial.lock);
320 
321 		queue_work_on(cb_cpu, pinst->serial_wq, &squeue->work);
322 	}
323 
324 	spin_unlock_bh(&pd->lock);
325 
326 	/*
327 	 * The next object that needs serialization might have arrived to
328 	 * the reorder queues in the meantime.
329 	 *
330 	 * Ensure reorder queue is read after pd->lock is dropped so we see
331 	 * new objects from another task in padata_do_serial.  Pairs with
332 	 * smp_mb in padata_do_serial.
333 	 */
334 	smp_mb();
335 
336 	reorder = per_cpu_ptr(pd->reorder_list, pd->cpu);
337 	if (!list_empty(&reorder->list) && padata_find_next(pd, false))
338 		queue_work(pinst->serial_wq, &pd->reorder_work);
339 }
340 
341 static void invoke_padata_reorder(struct work_struct *work)
342 {
343 	struct parallel_data *pd;
344 
345 	local_bh_disable();
346 	pd = container_of(work, struct parallel_data, reorder_work);
347 	padata_reorder(pd);
348 	local_bh_enable();
349 }
350 
351 static void padata_serial_worker(struct work_struct *serial_work)
352 {
353 	struct padata_serial_queue *squeue;
354 	struct parallel_data *pd;
355 	LIST_HEAD(local_list);
356 	int cnt;
357 
358 	local_bh_disable();
359 	squeue = container_of(serial_work, struct padata_serial_queue, work);
360 	pd = squeue->pd;
361 
362 	spin_lock(&squeue->serial.lock);
363 	list_replace_init(&squeue->serial.list, &local_list);
364 	spin_unlock(&squeue->serial.lock);
365 
366 	cnt = 0;
367 
368 	while (!list_empty(&local_list)) {
369 		struct padata_priv *padata;
370 
371 		padata = list_entry(local_list.next,
372 				    struct padata_priv, list);
373 
374 		list_del_init(&padata->list);
375 
376 		padata->serial(padata);
377 		cnt++;
378 	}
379 	local_bh_enable();
380 
381 	if (refcount_sub_and_test(cnt, &pd->refcnt))
382 		padata_free_pd(pd);
383 }
384 
385 /**
386  * padata_do_serial - padata serialization function
387  *
388  * @padata: object to be serialized.
389  *
390  * padata_do_serial must be called for every parallelized object.
391  * The serialization callback function will run with BHs off.
392  */
393 void padata_do_serial(struct padata_priv *padata)
394 {
395 	struct parallel_data *pd = padata->pd;
396 	int hashed_cpu = padata_cpu_hash(pd, padata->seq_nr);
397 	struct padata_list *reorder = per_cpu_ptr(pd->reorder_list, hashed_cpu);
398 	struct padata_priv *cur;
399 
400 	spin_lock(&reorder->lock);
401 	/* Sort in ascending order of sequence number. */
402 	list_for_each_entry_reverse(cur, &reorder->list, list)
403 		if (cur->seq_nr < padata->seq_nr)
404 			break;
405 	list_add(&padata->list, &cur->list);
406 	spin_unlock(&reorder->lock);
407 
408 	/*
409 	 * Ensure the addition to the reorder list is ordered correctly
410 	 * with the trylock of pd->lock in padata_reorder.  Pairs with smp_mb
411 	 * in padata_reorder.
412 	 */
413 	smp_mb();
414 
415 	padata_reorder(pd);
416 }
417 EXPORT_SYMBOL(padata_do_serial);
418 
419 static int padata_setup_cpumasks(struct padata_instance *pinst)
420 {
421 	struct workqueue_attrs *attrs;
422 	int err;
423 
424 	attrs = alloc_workqueue_attrs();
425 	if (!attrs)
426 		return -ENOMEM;
427 
428 	/* Restrict parallel_wq workers to pd->cpumask.pcpu. */
429 	cpumask_copy(attrs->cpumask, pinst->cpumask.pcpu);
430 	err = apply_workqueue_attrs(pinst->parallel_wq, attrs);
431 	free_workqueue_attrs(attrs);
432 
433 	return err;
434 }
435 
436 static void __init padata_mt_helper(struct work_struct *w)
437 {
438 	struct padata_work *pw = container_of(w, struct padata_work, pw_work);
439 	struct padata_mt_job_state *ps = pw->pw_data;
440 	struct padata_mt_job *job = ps->job;
441 	bool done;
442 
443 	spin_lock(&ps->lock);
444 
445 	while (job->size > 0) {
446 		unsigned long start, size, end;
447 
448 		start = job->start;
449 		/* So end is chunk size aligned if enough work remains. */
450 		size = roundup(start + 1, ps->chunk_size) - start;
451 		size = min(size, job->size);
452 		end = start + size;
453 
454 		job->start = end;
455 		job->size -= size;
456 
457 		spin_unlock(&ps->lock);
458 		job->thread_fn(start, end, job->fn_arg);
459 		spin_lock(&ps->lock);
460 	}
461 
462 	++ps->nworks_fini;
463 	done = (ps->nworks_fini == ps->nworks);
464 	spin_unlock(&ps->lock);
465 
466 	if (done)
467 		complete(&ps->completion);
468 }
469 
470 /**
471  * padata_do_multithreaded - run a multithreaded job
472  * @job: Description of the job.
473  *
474  * See the definition of struct padata_mt_job for more details.
475  */
476 void __init padata_do_multithreaded(struct padata_mt_job *job)
477 {
478 	/* In case threads finish at different times. */
479 	static const unsigned long load_balance_factor = 4;
480 	struct padata_work my_work, *pw;
481 	struct padata_mt_job_state ps;
482 	LIST_HEAD(works);
483 	int nworks;
484 
485 	if (job->size == 0)
486 		return;
487 
488 	/* Ensure at least one thread when size < min_chunk. */
489 	nworks = max(job->size / job->min_chunk, 1ul);
490 	nworks = min(nworks, job->max_threads);
491 
492 	if (nworks == 1) {
493 		/* Single thread, no coordination needed, cut to the chase. */
494 		job->thread_fn(job->start, job->start + job->size, job->fn_arg);
495 		return;
496 	}
497 
498 	spin_lock_init(&ps.lock);
499 	init_completion(&ps.completion);
500 	ps.job	       = job;
501 	ps.nworks      = padata_work_alloc_mt(nworks, &ps, &works);
502 	ps.nworks_fini = 0;
503 
504 	/*
505 	 * Chunk size is the amount of work a helper does per call to the
506 	 * thread function.  Load balance large jobs between threads by
507 	 * increasing the number of chunks, guarantee at least the minimum
508 	 * chunk size from the caller, and honor the caller's alignment.
509 	 */
510 	ps.chunk_size = job->size / (ps.nworks * load_balance_factor);
511 	ps.chunk_size = max(ps.chunk_size, job->min_chunk);
512 	ps.chunk_size = roundup(ps.chunk_size, job->align);
513 
514 	list_for_each_entry(pw, &works, pw_list)
515 		queue_work(system_unbound_wq, &pw->pw_work);
516 
517 	/* Use the current thread, which saves starting a workqueue worker. */
518 	padata_work_init(&my_work, padata_mt_helper, &ps, PADATA_WORK_ONSTACK);
519 	padata_mt_helper(&my_work.pw_work);
520 
521 	/* Wait for all the helpers to finish. */
522 	wait_for_completion(&ps.completion);
523 
524 	destroy_work_on_stack(&my_work.pw_work);
525 	padata_works_free(&works);
526 }
527 
528 static void __padata_list_init(struct padata_list *pd_list)
529 {
530 	INIT_LIST_HEAD(&pd_list->list);
531 	spin_lock_init(&pd_list->lock);
532 }
533 
534 /* Initialize all percpu queues used by serial workers */
535 static void padata_init_squeues(struct parallel_data *pd)
536 {
537 	int cpu;
538 	struct padata_serial_queue *squeue;
539 
540 	for_each_cpu(cpu, pd->cpumask.cbcpu) {
541 		squeue = per_cpu_ptr(pd->squeue, cpu);
542 		squeue->pd = pd;
543 		__padata_list_init(&squeue->serial);
544 		INIT_WORK(&squeue->work, padata_serial_worker);
545 	}
546 }
547 
548 /* Initialize per-CPU reorder lists */
549 static void padata_init_reorder_list(struct parallel_data *pd)
550 {
551 	int cpu;
552 	struct padata_list *list;
553 
554 	for_each_cpu(cpu, pd->cpumask.pcpu) {
555 		list = per_cpu_ptr(pd->reorder_list, cpu);
556 		__padata_list_init(list);
557 	}
558 }
559 
560 /* Allocate and initialize the internal cpumask dependend resources. */
561 static struct parallel_data *padata_alloc_pd(struct padata_shell *ps)
562 {
563 	struct padata_instance *pinst = ps->pinst;
564 	struct parallel_data *pd;
565 
566 	pd = kzalloc(sizeof(struct parallel_data), GFP_KERNEL);
567 	if (!pd)
568 		goto err;
569 
570 	pd->reorder_list = alloc_percpu(struct padata_list);
571 	if (!pd->reorder_list)
572 		goto err_free_pd;
573 
574 	pd->squeue = alloc_percpu(struct padata_serial_queue);
575 	if (!pd->squeue)
576 		goto err_free_reorder_list;
577 
578 	pd->ps = ps;
579 
580 	if (!alloc_cpumask_var(&pd->cpumask.pcpu, GFP_KERNEL))
581 		goto err_free_squeue;
582 	if (!alloc_cpumask_var(&pd->cpumask.cbcpu, GFP_KERNEL))
583 		goto err_free_pcpu;
584 
585 	cpumask_and(pd->cpumask.pcpu, pinst->cpumask.pcpu, cpu_online_mask);
586 	cpumask_and(pd->cpumask.cbcpu, pinst->cpumask.cbcpu, cpu_online_mask);
587 
588 	padata_init_reorder_list(pd);
589 	padata_init_squeues(pd);
590 	pd->seq_nr = -1;
591 	refcount_set(&pd->refcnt, 1);
592 	spin_lock_init(&pd->lock);
593 	pd->cpu = cpumask_first(pd->cpumask.pcpu);
594 	INIT_WORK(&pd->reorder_work, invoke_padata_reorder);
595 
596 	return pd;
597 
598 err_free_pcpu:
599 	free_cpumask_var(pd->cpumask.pcpu);
600 err_free_squeue:
601 	free_percpu(pd->squeue);
602 err_free_reorder_list:
603 	free_percpu(pd->reorder_list);
604 err_free_pd:
605 	kfree(pd);
606 err:
607 	return NULL;
608 }
609 
610 static void padata_free_pd(struct parallel_data *pd)
611 {
612 	free_cpumask_var(pd->cpumask.pcpu);
613 	free_cpumask_var(pd->cpumask.cbcpu);
614 	free_percpu(pd->reorder_list);
615 	free_percpu(pd->squeue);
616 	kfree(pd);
617 }
618 
619 static void __padata_start(struct padata_instance *pinst)
620 {
621 	pinst->flags |= PADATA_INIT;
622 }
623 
624 static void __padata_stop(struct padata_instance *pinst)
625 {
626 	if (!(pinst->flags & PADATA_INIT))
627 		return;
628 
629 	pinst->flags &= ~PADATA_INIT;
630 
631 	synchronize_rcu();
632 }
633 
634 /* Replace the internal control structure with a new one. */
635 static int padata_replace_one(struct padata_shell *ps)
636 {
637 	struct parallel_data *pd_new;
638 
639 	pd_new = padata_alloc_pd(ps);
640 	if (!pd_new)
641 		return -ENOMEM;
642 
643 	ps->opd = rcu_dereference_protected(ps->pd, 1);
644 	rcu_assign_pointer(ps->pd, pd_new);
645 
646 	return 0;
647 }
648 
649 static int padata_replace(struct padata_instance *pinst)
650 {
651 	struct padata_shell *ps;
652 	int err = 0;
653 
654 	pinst->flags |= PADATA_RESET;
655 
656 	list_for_each_entry(ps, &pinst->pslist, list) {
657 		err = padata_replace_one(ps);
658 		if (err)
659 			break;
660 	}
661 
662 	synchronize_rcu();
663 
664 	list_for_each_entry_continue_reverse(ps, &pinst->pslist, list)
665 		if (refcount_dec_and_test(&ps->opd->refcnt))
666 			padata_free_pd(ps->opd);
667 
668 	pinst->flags &= ~PADATA_RESET;
669 
670 	return err;
671 }
672 
673 /* If cpumask contains no active cpu, we mark the instance as invalid. */
674 static bool padata_validate_cpumask(struct padata_instance *pinst,
675 				    const struct cpumask *cpumask)
676 {
677 	if (!cpumask_intersects(cpumask, cpu_online_mask)) {
678 		pinst->flags |= PADATA_INVALID;
679 		return false;
680 	}
681 
682 	pinst->flags &= ~PADATA_INVALID;
683 	return true;
684 }
685 
686 static int __padata_set_cpumasks(struct padata_instance *pinst,
687 				 cpumask_var_t pcpumask,
688 				 cpumask_var_t cbcpumask)
689 {
690 	int valid;
691 	int err;
692 
693 	valid = padata_validate_cpumask(pinst, pcpumask);
694 	if (!valid) {
695 		__padata_stop(pinst);
696 		goto out_replace;
697 	}
698 
699 	valid = padata_validate_cpumask(pinst, cbcpumask);
700 	if (!valid)
701 		__padata_stop(pinst);
702 
703 out_replace:
704 	cpumask_copy(pinst->cpumask.pcpu, pcpumask);
705 	cpumask_copy(pinst->cpumask.cbcpu, cbcpumask);
706 
707 	err = padata_setup_cpumasks(pinst) ?: padata_replace(pinst);
708 
709 	if (valid)
710 		__padata_start(pinst);
711 
712 	return err;
713 }
714 
715 /**
716  * padata_set_cpumask - Sets specified by @cpumask_type cpumask to the value
717  *                      equivalent to @cpumask.
718  * @pinst: padata instance
719  * @cpumask_type: PADATA_CPU_SERIAL or PADATA_CPU_PARALLEL corresponding
720  *                to parallel and serial cpumasks respectively.
721  * @cpumask: the cpumask to use
722  *
723  * Return: 0 on success or negative error code
724  */
725 int padata_set_cpumask(struct padata_instance *pinst, int cpumask_type,
726 		       cpumask_var_t cpumask)
727 {
728 	struct cpumask *serial_mask, *parallel_mask;
729 	int err = -EINVAL;
730 
731 	cpus_read_lock();
732 	mutex_lock(&pinst->lock);
733 
734 	switch (cpumask_type) {
735 	case PADATA_CPU_PARALLEL:
736 		serial_mask = pinst->cpumask.cbcpu;
737 		parallel_mask = cpumask;
738 		break;
739 	case PADATA_CPU_SERIAL:
740 		parallel_mask = pinst->cpumask.pcpu;
741 		serial_mask = cpumask;
742 		break;
743 	default:
744 		 goto out;
745 	}
746 
747 	err =  __padata_set_cpumasks(pinst, parallel_mask, serial_mask);
748 
749 out:
750 	mutex_unlock(&pinst->lock);
751 	cpus_read_unlock();
752 
753 	return err;
754 }
755 EXPORT_SYMBOL(padata_set_cpumask);
756 
757 #ifdef CONFIG_HOTPLUG_CPU
758 
759 static int __padata_add_cpu(struct padata_instance *pinst, int cpu)
760 {
761 	int err = 0;
762 
763 	if (cpumask_test_cpu(cpu, cpu_online_mask)) {
764 		err = padata_replace(pinst);
765 
766 		if (padata_validate_cpumask(pinst, pinst->cpumask.pcpu) &&
767 		    padata_validate_cpumask(pinst, pinst->cpumask.cbcpu))
768 			__padata_start(pinst);
769 	}
770 
771 	return err;
772 }
773 
774 static int __padata_remove_cpu(struct padata_instance *pinst, int cpu)
775 {
776 	int err = 0;
777 
778 	if (!cpumask_test_cpu(cpu, cpu_online_mask)) {
779 		if (!padata_validate_cpumask(pinst, pinst->cpumask.pcpu) ||
780 		    !padata_validate_cpumask(pinst, pinst->cpumask.cbcpu))
781 			__padata_stop(pinst);
782 
783 		err = padata_replace(pinst);
784 	}
785 
786 	return err;
787 }
788 
789 static inline int pinst_has_cpu(struct padata_instance *pinst, int cpu)
790 {
791 	return cpumask_test_cpu(cpu, pinst->cpumask.pcpu) ||
792 		cpumask_test_cpu(cpu, pinst->cpumask.cbcpu);
793 }
794 
795 static int padata_cpu_online(unsigned int cpu, struct hlist_node *node)
796 {
797 	struct padata_instance *pinst;
798 	int ret;
799 
800 	pinst = hlist_entry_safe(node, struct padata_instance, cpu_online_node);
801 	if (!pinst_has_cpu(pinst, cpu))
802 		return 0;
803 
804 	mutex_lock(&pinst->lock);
805 	ret = __padata_add_cpu(pinst, cpu);
806 	mutex_unlock(&pinst->lock);
807 	return ret;
808 }
809 
810 static int padata_cpu_dead(unsigned int cpu, struct hlist_node *node)
811 {
812 	struct padata_instance *pinst;
813 	int ret;
814 
815 	pinst = hlist_entry_safe(node, struct padata_instance, cpu_dead_node);
816 	if (!pinst_has_cpu(pinst, cpu))
817 		return 0;
818 
819 	mutex_lock(&pinst->lock);
820 	ret = __padata_remove_cpu(pinst, cpu);
821 	mutex_unlock(&pinst->lock);
822 	return ret;
823 }
824 
825 static enum cpuhp_state hp_online;
826 #endif
827 
828 static void __padata_free(struct padata_instance *pinst)
829 {
830 #ifdef CONFIG_HOTPLUG_CPU
831 	cpuhp_state_remove_instance_nocalls(CPUHP_PADATA_DEAD,
832 					    &pinst->cpu_dead_node);
833 	cpuhp_state_remove_instance_nocalls(hp_online, &pinst->cpu_online_node);
834 #endif
835 
836 	WARN_ON(!list_empty(&pinst->pslist));
837 
838 	free_cpumask_var(pinst->cpumask.pcpu);
839 	free_cpumask_var(pinst->cpumask.cbcpu);
840 	destroy_workqueue(pinst->serial_wq);
841 	destroy_workqueue(pinst->parallel_wq);
842 	kfree(pinst);
843 }
844 
845 #define kobj2pinst(_kobj)					\
846 	container_of(_kobj, struct padata_instance, kobj)
847 #define attr2pentry(_attr)					\
848 	container_of(_attr, struct padata_sysfs_entry, attr)
849 
850 static void padata_sysfs_release(struct kobject *kobj)
851 {
852 	struct padata_instance *pinst = kobj2pinst(kobj);
853 	__padata_free(pinst);
854 }
855 
856 struct padata_sysfs_entry {
857 	struct attribute attr;
858 	ssize_t (*show)(struct padata_instance *, struct attribute *, char *);
859 	ssize_t (*store)(struct padata_instance *, struct attribute *,
860 			 const char *, size_t);
861 };
862 
863 static ssize_t show_cpumask(struct padata_instance *pinst,
864 			    struct attribute *attr,  char *buf)
865 {
866 	struct cpumask *cpumask;
867 	ssize_t len;
868 
869 	mutex_lock(&pinst->lock);
870 	if (!strcmp(attr->name, "serial_cpumask"))
871 		cpumask = pinst->cpumask.cbcpu;
872 	else
873 		cpumask = pinst->cpumask.pcpu;
874 
875 	len = snprintf(buf, PAGE_SIZE, "%*pb\n",
876 		       nr_cpu_ids, cpumask_bits(cpumask));
877 	mutex_unlock(&pinst->lock);
878 	return len < PAGE_SIZE ? len : -EINVAL;
879 }
880 
881 static ssize_t store_cpumask(struct padata_instance *pinst,
882 			     struct attribute *attr,
883 			     const char *buf, size_t count)
884 {
885 	cpumask_var_t new_cpumask;
886 	ssize_t ret;
887 	int mask_type;
888 
889 	if (!alloc_cpumask_var(&new_cpumask, GFP_KERNEL))
890 		return -ENOMEM;
891 
892 	ret = bitmap_parse(buf, count, cpumask_bits(new_cpumask),
893 			   nr_cpumask_bits);
894 	if (ret < 0)
895 		goto out;
896 
897 	mask_type = !strcmp(attr->name, "serial_cpumask") ?
898 		PADATA_CPU_SERIAL : PADATA_CPU_PARALLEL;
899 	ret = padata_set_cpumask(pinst, mask_type, new_cpumask);
900 	if (!ret)
901 		ret = count;
902 
903 out:
904 	free_cpumask_var(new_cpumask);
905 	return ret;
906 }
907 
908 #define PADATA_ATTR_RW(_name, _show_name, _store_name)		\
909 	static struct padata_sysfs_entry _name##_attr =		\
910 		__ATTR(_name, 0644, _show_name, _store_name)
911 #define PADATA_ATTR_RO(_name, _show_name)		\
912 	static struct padata_sysfs_entry _name##_attr = \
913 		__ATTR(_name, 0400, _show_name, NULL)
914 
915 PADATA_ATTR_RW(serial_cpumask, show_cpumask, store_cpumask);
916 PADATA_ATTR_RW(parallel_cpumask, show_cpumask, store_cpumask);
917 
918 /*
919  * Padata sysfs provides the following objects:
920  * serial_cpumask   [RW] - cpumask for serial workers
921  * parallel_cpumask [RW] - cpumask for parallel workers
922  */
923 static struct attribute *padata_default_attrs[] = {
924 	&serial_cpumask_attr.attr,
925 	&parallel_cpumask_attr.attr,
926 	NULL,
927 };
928 ATTRIBUTE_GROUPS(padata_default);
929 
930 static ssize_t padata_sysfs_show(struct kobject *kobj,
931 				 struct attribute *attr, char *buf)
932 {
933 	struct padata_instance *pinst;
934 	struct padata_sysfs_entry *pentry;
935 	ssize_t ret = -EIO;
936 
937 	pinst = kobj2pinst(kobj);
938 	pentry = attr2pentry(attr);
939 	if (pentry->show)
940 		ret = pentry->show(pinst, attr, buf);
941 
942 	return ret;
943 }
944 
945 static ssize_t padata_sysfs_store(struct kobject *kobj, struct attribute *attr,
946 				  const char *buf, size_t count)
947 {
948 	struct padata_instance *pinst;
949 	struct padata_sysfs_entry *pentry;
950 	ssize_t ret = -EIO;
951 
952 	pinst = kobj2pinst(kobj);
953 	pentry = attr2pentry(attr);
954 	if (pentry->show)
955 		ret = pentry->store(pinst, attr, buf, count);
956 
957 	return ret;
958 }
959 
960 static const struct sysfs_ops padata_sysfs_ops = {
961 	.show = padata_sysfs_show,
962 	.store = padata_sysfs_store,
963 };
964 
965 static struct kobj_type padata_attr_type = {
966 	.sysfs_ops = &padata_sysfs_ops,
967 	.default_groups = padata_default_groups,
968 	.release = padata_sysfs_release,
969 };
970 
971 /**
972  * padata_alloc - allocate and initialize a padata instance
973  * @name: used to identify the instance
974  *
975  * Return: new instance on success, NULL on error
976  */
977 struct padata_instance *padata_alloc(const char *name)
978 {
979 	struct padata_instance *pinst;
980 
981 	pinst = kzalloc(sizeof(struct padata_instance), GFP_KERNEL);
982 	if (!pinst)
983 		goto err;
984 
985 	pinst->parallel_wq = alloc_workqueue("%s_parallel", WQ_UNBOUND, 0,
986 					     name);
987 	if (!pinst->parallel_wq)
988 		goto err_free_inst;
989 
990 	cpus_read_lock();
991 
992 	pinst->serial_wq = alloc_workqueue("%s_serial", WQ_MEM_RECLAIM |
993 					   WQ_CPU_INTENSIVE, 1, name);
994 	if (!pinst->serial_wq)
995 		goto err_put_cpus;
996 
997 	if (!alloc_cpumask_var(&pinst->cpumask.pcpu, GFP_KERNEL))
998 		goto err_free_serial_wq;
999 	if (!alloc_cpumask_var(&pinst->cpumask.cbcpu, GFP_KERNEL)) {
1000 		free_cpumask_var(pinst->cpumask.pcpu);
1001 		goto err_free_serial_wq;
1002 	}
1003 
1004 	INIT_LIST_HEAD(&pinst->pslist);
1005 
1006 	cpumask_copy(pinst->cpumask.pcpu, cpu_possible_mask);
1007 	cpumask_copy(pinst->cpumask.cbcpu, cpu_possible_mask);
1008 
1009 	if (padata_setup_cpumasks(pinst))
1010 		goto err_free_masks;
1011 
1012 	__padata_start(pinst);
1013 
1014 	kobject_init(&pinst->kobj, &padata_attr_type);
1015 	mutex_init(&pinst->lock);
1016 
1017 #ifdef CONFIG_HOTPLUG_CPU
1018 	cpuhp_state_add_instance_nocalls_cpuslocked(hp_online,
1019 						    &pinst->cpu_online_node);
1020 	cpuhp_state_add_instance_nocalls_cpuslocked(CPUHP_PADATA_DEAD,
1021 						    &pinst->cpu_dead_node);
1022 #endif
1023 
1024 	cpus_read_unlock();
1025 
1026 	return pinst;
1027 
1028 err_free_masks:
1029 	free_cpumask_var(pinst->cpumask.pcpu);
1030 	free_cpumask_var(pinst->cpumask.cbcpu);
1031 err_free_serial_wq:
1032 	destroy_workqueue(pinst->serial_wq);
1033 err_put_cpus:
1034 	cpus_read_unlock();
1035 	destroy_workqueue(pinst->parallel_wq);
1036 err_free_inst:
1037 	kfree(pinst);
1038 err:
1039 	return NULL;
1040 }
1041 EXPORT_SYMBOL(padata_alloc);
1042 
1043 /**
1044  * padata_free - free a padata instance
1045  *
1046  * @pinst: padata instance to free
1047  */
1048 void padata_free(struct padata_instance *pinst)
1049 {
1050 	kobject_put(&pinst->kobj);
1051 }
1052 EXPORT_SYMBOL(padata_free);
1053 
1054 /**
1055  * padata_alloc_shell - Allocate and initialize padata shell.
1056  *
1057  * @pinst: Parent padata_instance object.
1058  *
1059  * Return: new shell on success, NULL on error
1060  */
1061 struct padata_shell *padata_alloc_shell(struct padata_instance *pinst)
1062 {
1063 	struct parallel_data *pd;
1064 	struct padata_shell *ps;
1065 
1066 	ps = kzalloc(sizeof(*ps), GFP_KERNEL);
1067 	if (!ps)
1068 		goto out;
1069 
1070 	ps->pinst = pinst;
1071 
1072 	cpus_read_lock();
1073 	pd = padata_alloc_pd(ps);
1074 	cpus_read_unlock();
1075 
1076 	if (!pd)
1077 		goto out_free_ps;
1078 
1079 	mutex_lock(&pinst->lock);
1080 	RCU_INIT_POINTER(ps->pd, pd);
1081 	list_add(&ps->list, &pinst->pslist);
1082 	mutex_unlock(&pinst->lock);
1083 
1084 	return ps;
1085 
1086 out_free_ps:
1087 	kfree(ps);
1088 out:
1089 	return NULL;
1090 }
1091 EXPORT_SYMBOL(padata_alloc_shell);
1092 
1093 /**
1094  * padata_free_shell - free a padata shell
1095  *
1096  * @ps: padata shell to free
1097  */
1098 void padata_free_shell(struct padata_shell *ps)
1099 {
1100 	if (!ps)
1101 		return;
1102 
1103 	mutex_lock(&ps->pinst->lock);
1104 	list_del(&ps->list);
1105 	padata_free_pd(rcu_dereference_protected(ps->pd, 1));
1106 	mutex_unlock(&ps->pinst->lock);
1107 
1108 	kfree(ps);
1109 }
1110 EXPORT_SYMBOL(padata_free_shell);
1111 
1112 void __init padata_init(void)
1113 {
1114 	unsigned int i, possible_cpus;
1115 #ifdef CONFIG_HOTPLUG_CPU
1116 	int ret;
1117 
1118 	ret = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN, "padata:online",
1119 				      padata_cpu_online, NULL);
1120 	if (ret < 0)
1121 		goto err;
1122 	hp_online = ret;
1123 
1124 	ret = cpuhp_setup_state_multi(CPUHP_PADATA_DEAD, "padata:dead",
1125 				      NULL, padata_cpu_dead);
1126 	if (ret < 0)
1127 		goto remove_online_state;
1128 #endif
1129 
1130 	possible_cpus = num_possible_cpus();
1131 	padata_works = kmalloc_array(possible_cpus, sizeof(struct padata_work),
1132 				     GFP_KERNEL);
1133 	if (!padata_works)
1134 		goto remove_dead_state;
1135 
1136 	for (i = 0; i < possible_cpus; ++i)
1137 		list_add(&padata_works[i].pw_list, &padata_free_works);
1138 
1139 	return;
1140 
1141 remove_dead_state:
1142 #ifdef CONFIG_HOTPLUG_CPU
1143 	cpuhp_remove_multi_state(CPUHP_PADATA_DEAD);
1144 remove_online_state:
1145 	cpuhp_remove_multi_state(hp_online);
1146 err:
1147 #endif
1148 	pr_warn("padata: initialization failed\n");
1149 }
1150