xref: /linux/drivers/s390/crypto/ap_bus.c (revision d30aca3eeffc18452e5cc5c4e59f1a4da2bd2f12)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright IBM Corp. 2006, 2023
4  * Author(s): Cornelia Huck <cornelia.huck@de.ibm.com>
5  *	      Martin Schwidefsky <schwidefsky@de.ibm.com>
6  *	      Ralph Wuerthner <rwuerthn@de.ibm.com>
7  *	      Felix Beck <felix.beck@de.ibm.com>
8  *	      Holger Dengler <hd@linux.vnet.ibm.com>
9  *	      Harald Freudenberger <freude@linux.ibm.com>
10  *
11  * Adjunct processor bus.
12  */
13 
14 #define pr_fmt(fmt) "ap: " fmt
15 
16 #include <linux/kernel_stat.h>
17 #include <linux/moduleparam.h>
18 #include <linux/export.h>
19 #include <linux/hex.h>
20 #include <linux/init.h>
21 #include <linux/delay.h>
22 #include <linux/err.h>
23 #include <linux/freezer.h>
24 #include <linux/interrupt.h>
25 #include <linux/workqueue.h>
26 #include <linux/slab.h>
27 #include <linux/notifier.h>
28 #include <linux/kthread.h>
29 #include <linux/mutex.h>
30 #include <asm/machine.h>
31 #include <asm/airq.h>
32 #include <asm/tpi.h>
33 #include <linux/atomic.h>
34 #include <asm/isc.h>
35 #include <linux/hrtimer.h>
36 #include <linux/ktime.h>
37 #include <asm/facility.h>
38 #include <linux/crypto.h>
39 #include <linux/mod_devicetable.h>
40 #include <linux/debugfs.h>
41 #include <linux/ctype.h>
42 #include <linux/module.h>
43 #include <asm/uv.h>
44 #include <asm/chsc.h>
45 #include <linux/mempool.h>
46 
47 #include "ap_bus.h"
48 #include "ap_debug.h"
49 
50 MODULE_AUTHOR("IBM Corporation");
51 MODULE_DESCRIPTION("Adjunct Processor Bus driver");
52 MODULE_LICENSE("GPL");
53 
54 int ap_domain_index = -1;	/* Adjunct Processor Domain Index */
55 static DEFINE_SPINLOCK(ap_domain_lock);
56 module_param_named(domain, ap_domain_index, int, 0440);
57 MODULE_PARM_DESC(domain, "domain index for ap devices");
58 EXPORT_SYMBOL(ap_domain_index);
59 
60 static int ap_thread_flag;
61 module_param_named(poll_thread, ap_thread_flag, int, 0440);
62 MODULE_PARM_DESC(poll_thread, "Turn on/off poll thread, default is 0 (off).");
63 
64 static char *apm_str;
65 module_param_named(apmask, apm_str, charp, 0440);
66 MODULE_PARM_DESC(apmask, "AP bus adapter mask.");
67 
68 static char *aqm_str;
69 module_param_named(aqmask, aqm_str, charp, 0440);
70 MODULE_PARM_DESC(aqmask, "AP bus domain mask.");
71 
72 static int ap_useirq = 1;
73 module_param_named(useirq, ap_useirq, int, 0440);
74 MODULE_PARM_DESC(useirq, "Use interrupt if available, default is 1 (on).");
75 
76 atomic_t ap_max_msg_size = ATOMIC_INIT(AP_DEFAULT_MAX_MSG_SIZE);
77 EXPORT_SYMBOL(ap_max_msg_size);
78 
79 static struct device *ap_root_device;
80 
81 /* Hashtable of all queue devices on the AP bus */
82 DEFINE_HASHTABLE(ap_queues, 8);
83 /* lock used for the ap_queues hashtable */
84 DEFINE_SPINLOCK(ap_queues_lock);
85 
86 /* Default permissions (ioctl, card and domain masking) */
87 struct ap_perms ap_perms;
88 EXPORT_SYMBOL(ap_perms);
89 /* true if apmask and/or aqmask are NOT default */
90 bool ap_apmask_aqmask_in_use;
91 /* counter for how many driver_overrides are currently active */
92 int ap_driver_override_ctr;
93 /*
94  * Mutex for consistent read and write of the ap_perms struct,
95  * ap_apmask_aqmask_in_use, ap_driver_override_ctr
96  * and the ap bus sysfs attributes apmask and aqmask.
97  */
98 DEFINE_MUTEX(ap_attr_mutex);
99 EXPORT_SYMBOL(ap_attr_mutex);
100 
101 /* # of bindings complete since init */
102 static atomic64_t ap_bindings_complete_count = ATOMIC64_INIT(0);
103 
104 /* completion for APQN bindings complete */
105 static DECLARE_COMPLETION(ap_apqn_bindings_complete);
106 
107 static struct ap_config_info qci[2];
108 static struct ap_config_info *const ap_qci_info = &qci[0];
109 static struct ap_config_info *const ap_qci_info_old = &qci[1];
110 
111 /*
112  * AP bus related debug feature things.
113  */
114 debug_info_t *ap_dbf_info;
115 
116 /*
117  * There is a need for a do-not-allocate-memory path through the AP bus
118  * layer. The pkey layer may be triggered via the in-kernel interface from
119  * a protected key crypto algorithm (namely PAES) to convert a secure key
120  * into a protected key. This happens in a workqueue context, so sleeping
121  * is allowed but memory allocations causing IO operations are not permitted.
122  * To accomplish this, an AP message memory pool with pre-allocated space
123  * is established. When ap_init_apmsg() with use_mempool set to true is
124  * called, instead of kmalloc() the ap message buffer is allocated from
125  * the ap_msg_pool. This pool only holds a limited amount of buffers:
126  * ap_msg_pool_min_items with the item size AP_DEFAULT_MAX_MSG_SIZE and
127  * exactly one of these items (if available) is returned if ap_init_apmsg()
128  * with the use_mempool arg set to true is called. When this pool is exhausted
129  * and use_mempool is set true, ap_init_apmsg() returns -ENOMEM without
130  * any attempt to allocate memory and the caller has to deal with that.
131  */
132 static mempool_t *ap_msg_pool;
133 static unsigned int ap_msg_pool_min_items = 8;
134 module_param_named(msgpool_min_items, ap_msg_pool_min_items, uint, 0440);
135 MODULE_PARM_DESC(msgpool_min_items, "AP message pool minimal items");
136 
137 /*
138  * AP bus rescan related things.
139  */
140 static bool ap_scan_bus(void);
141 static bool ap_scan_bus_result; /* result of last ap_scan_bus() */
142 static DEFINE_MUTEX(ap_scan_bus_mutex); /* mutex ap_scan_bus() invocations */
143 static struct task_struct *ap_scan_bus_task; /* thread holding the scan mutex */
144 static atomic64_t ap_scan_bus_count; /* counter ap_scan_bus() invocations */
145 static int ap_scan_bus_time = AP_CONFIG_TIME;
146 static struct timer_list ap_scan_bus_timer;
147 static void ap_scan_bus_wq_callback(struct work_struct *);
148 static DECLARE_WORK(ap_scan_bus_work, ap_scan_bus_wq_callback);
149 
150 /*
151  * Tasklet & timer for AP request polling and interrupts
152  */
153 static void ap_tasklet_fn(unsigned long);
154 static DECLARE_TASKLET_OLD(ap_tasklet, ap_tasklet_fn);
155 static DECLARE_WAIT_QUEUE_HEAD(ap_poll_wait);
156 static struct task_struct *ap_poll_kthread;
157 static DEFINE_MUTEX(ap_poll_thread_mutex);
158 static DEFINE_SPINLOCK(ap_poll_timer_lock);
159 static struct hrtimer ap_poll_timer;
160 /*
161  * In LPAR poll with 4kHz frequency. Poll every 250000 nanoseconds.
162  * If z/VM change to 1500000 nanoseconds to adjust to z/VM polling.
163  */
164 static unsigned long poll_high_timeout = 250000UL;
165 
166 /*
167  * Some state machine states only require a low frequency polling.
168  * We use 25 Hz frequency for these.
169  */
170 static unsigned long poll_low_timeout = 40000000UL;
171 
172 /* Maximum domain id, if not given via qci */
173 static int ap_max_domain_id = 15;
174 /* Maximum adapter id, if not given via qci */
175 static int ap_max_adapter_id = 63;
176 
177 static const struct bus_type ap_bus_type;
178 
179 /* Adapter interrupt definitions */
180 static void ap_interrupt_handler(struct airq_struct *airq,
181 				 struct tpi_info *tpi_info);
182 
183 static bool ap_irq_flag;
184 
185 static struct airq_struct ap_airq = {
186 	.handler = ap_interrupt_handler,
187 	.isc = AP_ISC,
188 };
189 
190 /**
191  * ap_airq_ptr() - Get the address of the adapter interrupt indicator
192  *
193  * Returns the address of the local-summary-indicator of the adapter
194  * interrupt handler for AP, or NULL if adapter interrupts are not
195  * available.
196  */
197 void *ap_airq_ptr(void)
198 {
199 	if (ap_irq_flag)
200 		return ap_airq.lsi_ptr;
201 	return NULL;
202 }
203 
204 /**
205  * ap_interrupts_available(): Test if AP interrupts are available.
206  *
207  * Returns 1 if AP interrupts are available.
208  */
209 static int ap_interrupts_available(void)
210 {
211 	return test_facility(65);
212 }
213 
214 /**
215  * ap_qci_available(): Test if AP configuration
216  * information can be queried via QCI subfunction.
217  *
218  * Returns 1 if subfunction PQAP(QCI) is available.
219  */
220 static int ap_qci_available(void)
221 {
222 	return test_facility(12);
223 }
224 
225 /**
226  * ap_apft_available(): Test if AP facilities test (APFT)
227  * facility is available.
228  *
229  * Returns 1 if APFT is available.
230  */
231 static int ap_apft_available(void)
232 {
233 	return test_facility(15);
234 }
235 
236 /*
237  * ap_qact_available(): Test if the PQAP(QACT) subfunction is available.
238  *
239  * Returns 1 if the QACT subfunction is available.
240  */
241 static inline int ap_qact_available(void)
242 {
243 	return ap_qci_info->qact;
244 }
245 
246 /*
247  * ap_sb_available(): Test if the AP secure binding facility is available.
248  *
249  * Returns 1 if secure binding facility is available.
250  */
251 int ap_sb_available(void)
252 {
253 	return ap_qci_info->apsb;
254 }
255 
256 /*
257  * ap_is_se_guest(): Check for SE guest with AP pass-through support.
258  */
259 bool ap_is_se_guest(void)
260 {
261 	return is_prot_virt_guest() && ap_sb_available();
262 }
263 EXPORT_SYMBOL(ap_is_se_guest);
264 
265 /**
266  * ap_init_qci_info(): Allocate and query qci config info.
267  * Does also update the static variables ap_max_domain_id
268  * and ap_max_adapter_id if this info is available.
269  */
270 static void __init ap_init_qci_info(void)
271 {
272 	if (!ap_qci_available() ||
273 	    ap_qci(ap_qci_info)) {
274 		AP_DBF_INFO("%s QCI not supported\n", __func__);
275 		return;
276 	}
277 	memcpy(ap_qci_info_old, ap_qci_info, sizeof(*ap_qci_info));
278 	AP_DBF_INFO("%s successful fetched initial qci info\n", __func__);
279 
280 	if (ap_qci_info->apxa) {
281 		if (ap_qci_info->na) {
282 			ap_max_adapter_id = ap_qci_info->na;
283 			AP_DBF_INFO("%s new ap_max_adapter_id is %d\n",
284 				    __func__, ap_max_adapter_id);
285 		}
286 		if (ap_qci_info->nd) {
287 			ap_max_domain_id = ap_qci_info->nd;
288 			AP_DBF_INFO("%s new ap_max_domain_id is %d\n",
289 				    __func__, ap_max_domain_id);
290 		}
291 	}
292 }
293 
294 /*
295  * ap_test_config(): helper function to extract the nrth bit
296  *		     within the unsigned int array field.
297  */
298 static inline int ap_test_config(unsigned int *field, unsigned int nr)
299 {
300 	return ap_test_bit((field + (nr >> 5)), (nr & 0x1f));
301 }
302 
303 /*
304  * ap_test_config_card_id(): Test, whether an AP card ID is configured.
305  *
306  * Returns 0 if the card is not configured
307  *	   1 if the card is configured or
308  *	     if the configuration information is not available
309  */
310 static inline int ap_test_config_card_id(unsigned int id)
311 {
312 	if (id > ap_max_adapter_id)
313 		return 0;
314 	if (ap_qci_info->flags)
315 		return ap_test_config(ap_qci_info->apm, id);
316 	return 1;
317 }
318 
319 /*
320  * ap_test_config_usage_domain(): Test, whether an AP usage domain
321  * is configured.
322  *
323  * Returns 0 if the usage domain is not configured
324  *	   1 if the usage domain is configured or
325  *	     if the configuration information is not available
326  */
327 int ap_test_config_usage_domain(unsigned int domain)
328 {
329 	if (domain > ap_max_domain_id)
330 		return 0;
331 	if (ap_qci_info->flags)
332 		return ap_test_config(ap_qci_info->aqm, domain);
333 	return 1;
334 }
335 EXPORT_SYMBOL(ap_test_config_usage_domain);
336 
337 /*
338  * ap_test_config_ctrl_domain(): Test, whether an AP control domain
339  * is configured.
340  * @domain AP control domain ID
341  *
342  * Returns 1 if the control domain is configured
343  *	   0 in all other cases
344  */
345 int ap_test_config_ctrl_domain(unsigned int domain)
346 {
347 	if (!ap_qci_info || domain > ap_max_domain_id)
348 		return 0;
349 	return ap_test_config(ap_qci_info->adm, domain);
350 }
351 EXPORT_SYMBOL(ap_test_config_ctrl_domain);
352 
353 /*
354  * ap_queue_info(): Check and get AP queue info.
355  * Returns: 1 if APQN exists and info is filled,
356  *	    0 if APQN seems to exist but there is no info
357  *	      available (eg. caused by an asynch pending error)
358  *	   -1 invalid APQN, TAPQ error or AP queue status which
359  *	      indicates there is no APQN.
360  */
361 static int ap_queue_info(ap_qid_t qid, struct ap_tapq_hwinfo *hwinfo,
362 			 bool *decfg, bool *cstop)
363 {
364 	struct ap_queue_status status;
365 
366 	hwinfo->value = 0;
367 
368 	/* make sure we don't run into a specifiation exception */
369 	if (AP_QID_CARD(qid) > ap_max_adapter_id ||
370 	    AP_QID_QUEUE(qid) > ap_max_domain_id)
371 		return -1;
372 
373 	/* call TAPQ on this APQN */
374 	status = ap_test_queue(qid, ap_apft_available(), hwinfo);
375 
376 	switch (status.response_code) {
377 	case AP_RESPONSE_NORMAL:
378 	case AP_RESPONSE_RESET_IN_PROGRESS:
379 	case AP_RESPONSE_DECONFIGURED:
380 	case AP_RESPONSE_CHECKSTOPPED:
381 	case AP_RESPONSE_BUSY:
382 		/* For all these RCs the tapq info should be available */
383 		break;
384 	default:
385 		/* On a pending async error the info should be available */
386 		if (!status.async)
387 			return -1;
388 		break;
389 	}
390 
391 	/* There should be at least one of the mode bits set */
392 	if (WARN_ON_ONCE(!hwinfo->value))
393 		return 0;
394 
395 	*decfg = status.response_code == AP_RESPONSE_DECONFIGURED;
396 	*cstop = status.response_code == AP_RESPONSE_CHECKSTOPPED;
397 
398 	return 1;
399 }
400 
401 void ap_wait(enum ap_sm_wait wait)
402 {
403 	ktime_t hr_time;
404 
405 	switch (wait) {
406 	case AP_SM_WAIT_AGAIN:
407 	case AP_SM_WAIT_INTERRUPT:
408 		if (ap_irq_flag)
409 			break;
410 		if (ap_poll_kthread) {
411 			wake_up(&ap_poll_wait);
412 			break;
413 		}
414 		fallthrough;
415 	case AP_SM_WAIT_LOW_TIMEOUT:
416 	case AP_SM_WAIT_HIGH_TIMEOUT:
417 		spin_lock_bh(&ap_poll_timer_lock);
418 		if (!hrtimer_is_queued(&ap_poll_timer)) {
419 			hr_time =
420 				wait == AP_SM_WAIT_LOW_TIMEOUT ?
421 				poll_low_timeout : poll_high_timeout;
422 			hrtimer_forward_now(&ap_poll_timer, hr_time);
423 			hrtimer_restart(&ap_poll_timer);
424 		}
425 		spin_unlock_bh(&ap_poll_timer_lock);
426 		break;
427 	case AP_SM_WAIT_NONE:
428 	default:
429 		break;
430 	}
431 }
432 
433 /**
434  * ap_request_timeout(): Handling of request timeouts
435  * @t: timer making this callback
436  *
437  * Handles request timeouts.
438  */
439 void ap_request_timeout(struct timer_list *t)
440 {
441 	struct ap_queue *aq = timer_container_of(aq, t, timeout);
442 
443 	spin_lock_bh(&aq->lock);
444 	ap_wait(ap_sm_event(aq, AP_SM_EVENT_TIMEOUT));
445 	spin_unlock_bh(&aq->lock);
446 }
447 
448 /**
449  * ap_poll_timeout(): AP receive polling for finished AP requests.
450  * @unused: Unused pointer.
451  *
452  * Schedules the AP tasklet using a high resolution timer.
453  */
454 static enum hrtimer_restart ap_poll_timeout(struct hrtimer *unused)
455 {
456 	tasklet_schedule(&ap_tasklet);
457 	return HRTIMER_NORESTART;
458 }
459 
460 /**
461  * ap_interrupt_handler() - Schedule ap_tasklet on interrupt
462  * @airq: pointer to adapter interrupt descriptor
463  * @tpi_info: ignored
464  */
465 static void ap_interrupt_handler(struct airq_struct *airq,
466 				 struct tpi_info *tpi_info)
467 {
468 	inc_irq_stat(IRQIO_APB);
469 	tasklet_schedule(&ap_tasklet);
470 }
471 
472 /**
473  * ap_tasklet_fn(): Tasklet to poll all AP devices.
474  * @dummy: Unused variable
475  *
476  * Poll all AP devices on the bus.
477  */
478 static void ap_tasklet_fn(unsigned long dummy)
479 {
480 	int bkt;
481 	struct ap_queue *aq;
482 	enum ap_sm_wait wait = AP_SM_WAIT_NONE;
483 
484 	/* Reset the indicator if interrupts are used. Thus new interrupts can
485 	 * be received. Doing it in the beginning of the tasklet is therefore
486 	 * important that no requests on any AP get lost.
487 	 */
488 	if (ap_irq_flag)
489 		WRITE_ONCE(*ap_airq.lsi_ptr, 0);
490 
491 	spin_lock_bh(&ap_queues_lock);
492 	hash_for_each(ap_queues, bkt, aq, hnode) {
493 		spin_lock_bh(&aq->lock);
494 		wait = min(wait, ap_sm_event_loop(aq, AP_SM_EVENT_POLL));
495 		spin_unlock_bh(&aq->lock);
496 	}
497 	spin_unlock_bh(&ap_queues_lock);
498 
499 	ap_wait(wait);
500 }
501 
502 static int ap_pending_requests(void)
503 {
504 	int bkt;
505 	struct ap_queue *aq;
506 
507 	spin_lock_bh(&ap_queues_lock);
508 	hash_for_each(ap_queues, bkt, aq, hnode) {
509 		if (aq->queue_count == 0)
510 			continue;
511 		spin_unlock_bh(&ap_queues_lock);
512 		return 1;
513 	}
514 	spin_unlock_bh(&ap_queues_lock);
515 	return 0;
516 }
517 
518 /**
519  * ap_poll_thread(): Thread that polls for finished requests.
520  * @data: Unused pointer
521  *
522  * AP bus poll thread. The purpose of this thread is to poll for
523  * finished requests in a loop if there is a "free" cpu - that is
524  * a cpu that doesn't have anything better to do. The polling stops
525  * as soon as there is another task or if all messages have been
526  * delivered.
527  */
528 static int ap_poll_thread(void *data)
529 {
530 	DECLARE_WAITQUEUE(wait, current);
531 
532 	set_user_nice(current, MAX_NICE);
533 	set_freezable();
534 	while (!kthread_should_stop()) {
535 		add_wait_queue(&ap_poll_wait, &wait);
536 		set_current_state(TASK_INTERRUPTIBLE);
537 		if (!ap_pending_requests()) {
538 			schedule();
539 			try_to_freeze();
540 		}
541 		set_current_state(TASK_RUNNING);
542 		remove_wait_queue(&ap_poll_wait, &wait);
543 		if (need_resched()) {
544 			schedule();
545 			try_to_freeze();
546 			continue;
547 		}
548 		ap_tasklet_fn(0);
549 	}
550 
551 	return 0;
552 }
553 
554 static int ap_poll_thread_start(void)
555 {
556 	int rc;
557 
558 	if (ap_irq_flag || ap_poll_kthread)
559 		return 0;
560 	mutex_lock(&ap_poll_thread_mutex);
561 	ap_poll_kthread = kthread_run(ap_poll_thread, NULL, "appoll");
562 	rc = PTR_ERR_OR_ZERO(ap_poll_kthread);
563 	if (rc)
564 		ap_poll_kthread = NULL;
565 	mutex_unlock(&ap_poll_thread_mutex);
566 	return rc;
567 }
568 
569 static void ap_poll_thread_stop(void)
570 {
571 	if (!ap_poll_kthread)
572 		return;
573 	mutex_lock(&ap_poll_thread_mutex);
574 	kthread_stop(ap_poll_kthread);
575 	ap_poll_kthread = NULL;
576 	mutex_unlock(&ap_poll_thread_mutex);
577 }
578 
579 #define is_card_dev(x) ((x)->parent == ap_root_device)
580 #define is_queue_dev(x) ((x)->parent != ap_root_device)
581 
582 /*
583  * ap_init_apmsg() - Initialize ap_message.
584  */
585 int ap_init_apmsg(struct ap_message *ap_msg, u32 flags)
586 {
587 	unsigned int maxmsgsize;
588 
589 	memset(ap_msg, 0, sizeof(*ap_msg));
590 	ap_msg->flags = flags;
591 
592 	if (flags & AP_MSG_FLAG_MEMPOOL) {
593 		ap_msg->msg = mempool_alloc_preallocated(ap_msg_pool);
594 		if (!ap_msg->msg)
595 			return -ENOMEM;
596 		ap_msg->bufsize = AP_DEFAULT_MAX_MSG_SIZE;
597 		return 0;
598 	}
599 
600 	maxmsgsize = atomic_read(&ap_max_msg_size);
601 	ap_msg->msg = kmalloc(maxmsgsize, GFP_KERNEL);
602 	if (!ap_msg->msg)
603 		return -ENOMEM;
604 	ap_msg->bufsize = maxmsgsize;
605 
606 	return 0;
607 }
608 EXPORT_SYMBOL(ap_init_apmsg);
609 
610 /*
611  * ap_release_apmsg() - Release ap_message.
612  */
613 void ap_release_apmsg(struct ap_message *ap_msg)
614 {
615 	if (ap_msg->flags & AP_MSG_FLAG_MEMPOOL) {
616 		memzero_explicit(ap_msg->msg, ap_msg->bufsize);
617 		mempool_free(ap_msg->msg, ap_msg_pool);
618 	} else {
619 		kfree_sensitive(ap_msg->msg);
620 	}
621 }
622 EXPORT_SYMBOL(ap_release_apmsg);
623 
624 /**
625  * ap_bus_match()
626  * @dev: Pointer to device
627  * @drv: Pointer to device_driver
628  *
629  * AP bus driver registration/unregistration.
630  */
631 static int ap_bus_match(struct device *dev, const struct device_driver *drv)
632 {
633 	const struct ap_driver *ap_drv = to_ap_drv(drv);
634 	struct ap_device_id *id;
635 
636 	/*
637 	 * Compare device type of the device with the list of
638 	 * supported types of the device_driver.
639 	 */
640 	for (id = ap_drv->ids; id->match_flags; id++) {
641 		if (is_card_dev(dev) &&
642 		    id->match_flags & AP_DEVICE_ID_MATCH_CARD_TYPE &&
643 		    id->dev_type == to_ap_dev(dev)->device_type)
644 			return 1;
645 		if (is_queue_dev(dev) &&
646 		    id->match_flags & AP_DEVICE_ID_MATCH_QUEUE_TYPE &&
647 		    id->dev_type == to_ap_dev(dev)->device_type)
648 			return 1;
649 	}
650 	return 0;
651 }
652 
653 /**
654  * ap_uevent(): Uevent function for AP devices.
655  * @dev: Pointer to device
656  * @env: Pointer to kobj_uevent_env
657  *
658  * It sets up a single environment variable DEV_TYPE which contains the
659  * hardware device type.
660  */
661 static int ap_uevent(const struct device *dev, struct kobj_uevent_env *env)
662 {
663 	int rc = 0;
664 	const struct ap_device *ap_dev = to_ap_dev(dev);
665 
666 	/* Uevents from ap bus core don't need extensions to the env */
667 	if (dev == ap_root_device)
668 		return 0;
669 
670 	if (is_card_dev(dev)) {
671 		struct ap_card *ac = to_ap_card(&ap_dev->device);
672 
673 		/* Set up DEV_TYPE environment variable. */
674 		rc = add_uevent_var(env, "DEV_TYPE=%04X", ap_dev->device_type);
675 		if (rc)
676 			return rc;
677 		/* Add MODALIAS= */
678 		rc = add_uevent_var(env, "MODALIAS=ap:t%02X", ap_dev->device_type);
679 		if (rc)
680 			return rc;
681 
682 		/* Add MODE=<accel|cca|ep11> */
683 		if (ac->hwinfo.accel)
684 			rc = add_uevent_var(env, "MODE=accel");
685 		else if (ac->hwinfo.cca)
686 			rc = add_uevent_var(env, "MODE=cca");
687 		else if (ac->hwinfo.ep11)
688 			rc = add_uevent_var(env, "MODE=ep11");
689 		if (rc)
690 			return rc;
691 	} else {
692 		struct ap_queue *aq = to_ap_queue(&ap_dev->device);
693 
694 		/* Add MODE=<accel|cca|ep11> */
695 		if (aq->card->hwinfo.accel)
696 			rc = add_uevent_var(env, "MODE=accel");
697 		else if (aq->card->hwinfo.cca)
698 			rc = add_uevent_var(env, "MODE=cca");
699 		else if (aq->card->hwinfo.ep11)
700 			rc = add_uevent_var(env, "MODE=ep11");
701 		if (rc)
702 			return rc;
703 	}
704 
705 	return 0;
706 }
707 
708 static void ap_send_init_scan_done_uevent(void)
709 {
710 	char *envp[] = { "INITSCAN=done", NULL };
711 
712 	kobject_uevent_env(&ap_root_device->kobj, KOBJ_CHANGE, envp);
713 }
714 
715 static void ap_send_bindings_complete_uevent(void)
716 {
717 	char buf[32];
718 	char *envp[] = { "BINDINGS=complete", buf, NULL };
719 
720 	snprintf(buf, sizeof(buf), "COMPLETECOUNT=%llu",
721 		 atomic64_inc_return(&ap_bindings_complete_count));
722 	kobject_uevent_env(&ap_root_device->kobj, KOBJ_CHANGE, envp);
723 }
724 
725 void ap_send_config_uevent(struct ap_device *ap_dev, bool cfg)
726 {
727 	char buf[16];
728 	char *envp[] = { buf, NULL };
729 
730 	snprintf(buf, sizeof(buf), "CONFIG=%d", cfg ? 1 : 0);
731 
732 	kobject_uevent_env(&ap_dev->device.kobj, KOBJ_CHANGE, envp);
733 }
734 EXPORT_SYMBOL(ap_send_config_uevent);
735 
736 void ap_send_online_uevent(struct ap_device *ap_dev, int online)
737 {
738 	char buf[16];
739 	char *envp[] = { buf, NULL };
740 
741 	snprintf(buf, sizeof(buf), "ONLINE=%d", online ? 1 : 0);
742 
743 	kobject_uevent_env(&ap_dev->device.kobj, KOBJ_CHANGE, envp);
744 }
745 EXPORT_SYMBOL(ap_send_online_uevent);
746 
747 static void ap_send_mask_changed_uevent(unsigned long *newapm,
748 					unsigned long *newaqm)
749 {
750 	char buf[100];
751 	char *envp[] = { buf, NULL };
752 
753 	if (newapm)
754 		snprintf(buf, sizeof(buf),
755 			 "APMASK=0x%016lx%016lx%016lx%016lx\n",
756 			 newapm[0], newapm[1], newapm[2], newapm[3]);
757 	else
758 		snprintf(buf, sizeof(buf),
759 			 "AQMASK=0x%016lx%016lx%016lx%016lx\n",
760 			 newaqm[0], newaqm[1], newaqm[2], newaqm[3]);
761 
762 	kobject_uevent_env(&ap_root_device->kobj, KOBJ_CHANGE, envp);
763 }
764 
765 /*
766  * calc # of bound APQNs
767  */
768 
769 struct __ap_calc_ctrs {
770 	unsigned int apqns;
771 	unsigned int bound;
772 };
773 
774 static int __ap_calc_helper(struct device *dev, void *arg)
775 {
776 	struct __ap_calc_ctrs *pctrs = (struct __ap_calc_ctrs *)arg;
777 
778 	if (is_queue_dev(dev)) {
779 		pctrs->apqns++;
780 		if (dev->driver)
781 			pctrs->bound++;
782 	}
783 
784 	return 0;
785 }
786 
787 static void ap_calc_bound_apqns(unsigned int *apqns, unsigned int *bound)
788 {
789 	struct __ap_calc_ctrs ctrs;
790 
791 	memset(&ctrs, 0, sizeof(ctrs));
792 	bus_for_each_dev(&ap_bus_type, NULL, (void *)&ctrs, __ap_calc_helper);
793 
794 	*apqns = ctrs.apqns;
795 	*bound = ctrs.bound;
796 }
797 
798 /*
799  * After ap bus scan do check if all existing APQNs are
800  * bound to device drivers.
801  */
802 static void ap_check_bindings_complete(void)
803 {
804 	unsigned int apqns, bound;
805 
806 	if (atomic64_read(&ap_scan_bus_count) >= 1) {
807 		ap_calc_bound_apqns(&apqns, &bound);
808 		if (bound == apqns) {
809 			if (!completion_done(&ap_apqn_bindings_complete)) {
810 				complete_all(&ap_apqn_bindings_complete);
811 				ap_send_bindings_complete_uevent();
812 				pr_debug("all apqn bindings complete\n");
813 			}
814 		}
815 	}
816 }
817 
818 /*
819  * Interface to wait for the AP bus to have done one initial ap bus
820  * scan and all detected APQNs have been bound to device drivers.
821  * If these both conditions are not fulfilled, this function blocks
822  * on a condition with wait_for_completion_interruptible_timeout().
823  * If these both conditions are fulfilled (before the timeout hits)
824  * the return value is 0. If the timeout (in jiffies) hits instead
825  * -ETIME is returned. On failures negative return values are
826  * returned to the caller.
827  */
828 int ap_wait_apqn_bindings_complete(unsigned long timeout)
829 {
830 	int rc = 0;
831 	long l;
832 
833 	if (completion_done(&ap_apqn_bindings_complete))
834 		return 0;
835 
836 	if (timeout)
837 		l = wait_for_completion_interruptible_timeout(
838 			&ap_apqn_bindings_complete, timeout);
839 	else
840 		l = wait_for_completion_interruptible(
841 			&ap_apqn_bindings_complete);
842 	if (l < 0)
843 		rc = l == -ERESTARTSYS ? -EINTR : l;
844 	else if (l == 0 && timeout)
845 		rc = -ETIME;
846 
847 	pr_debug("rc=%d\n", rc);
848 	return rc;
849 }
850 EXPORT_SYMBOL(ap_wait_apqn_bindings_complete);
851 
852 static int __ap_queue_devices_with_id_unregister(struct device *dev, void *data)
853 {
854 	if (is_queue_dev(dev) &&
855 	    AP_QID_CARD(to_ap_queue(dev)->qid) == (int)(long)data)
856 		device_unregister(dev);
857 	return 0;
858 }
859 
860 static int __ap_revise_reserved(struct device *dev, void *dummy)
861 {
862 	int rc, card, queue, devres, drvres;
863 
864 	if (is_queue_dev(dev)) {
865 		struct ap_driver *ap_drv = to_ap_drv(dev->driver);
866 		struct ap_queue *aq = to_ap_queue(dev);
867 		struct ap_device *ap_dev = &aq->ap_dev;
868 
869 		card = AP_QID_CARD(aq->qid);
870 		queue = AP_QID_QUEUE(aq->qid);
871 
872 		if (ap_dev->driver_override) {
873 			if (strcmp(ap_dev->driver_override,
874 				   ap_drv->driver.name)) {
875 				pr_debug("reprobing queue=%02x.%04x\n", card, queue);
876 				rc = device_reprobe(dev);
877 				if (rc) {
878 					AP_DBF_WARN("%s reprobing queue=%02x.%04x failed\n",
879 						    __func__, card, queue);
880 				}
881 			}
882 		} else {
883 			mutex_lock(&ap_attr_mutex);
884 			devres = test_bit_inv(card, ap_perms.apm) &&
885 				test_bit_inv(queue, ap_perms.aqm);
886 			mutex_unlock(&ap_attr_mutex);
887 			drvres = to_ap_drv(dev->driver)->flags
888 				& AP_DRIVER_FLAG_DEFAULT;
889 			if (!!devres != !!drvres) {
890 				pr_debug("reprobing queue=%02x.%04x\n", card, queue);
891 				rc = device_reprobe(dev);
892 				if (rc) {
893 					AP_DBF_WARN("%s reprobing queue=%02x.%04x failed\n",
894 						    __func__, card, queue);
895 				}
896 			}
897 		}
898 	}
899 
900 	return 0;
901 }
902 
903 static void ap_bus_revise_bindings(void)
904 {
905 	bus_for_each_dev(&ap_bus_type, NULL, NULL, __ap_revise_reserved);
906 }
907 
908 /**
909  * ap_owned_by_def_drv: indicates whether an AP adapter is reserved for the
910  *			default host driver or not.
911  * @card: the APID of the adapter card to check
912  * @queue: the APQI of the queue to check
913  *
914  * Note: the ap_attr_mutex must be locked by the caller of this function.
915  *
916  * Return: an int specifying whether the AP adapter is reserved for the host (1)
917  *	   or not (0).
918  */
919 int ap_owned_by_def_drv(int card, int queue)
920 {
921 	struct ap_queue *aq;
922 	int rc = 0;
923 
924 	if (card < 0 || card >= AP_DEVICES || queue < 0 || queue >= AP_DOMAINS)
925 		return -EINVAL;
926 
927 	aq = ap_get_qdev(AP_MKQID(card, queue));
928 	if (aq) {
929 		const struct device_driver *drv = aq->ap_dev.device.driver;
930 		const struct ap_driver *ap_drv = to_ap_drv(drv);
931 		bool override = !!aq->ap_dev.driver_override;
932 
933 		if (override && drv && ap_drv->flags & AP_DRIVER_FLAG_DEFAULT)
934 			rc = 1;
935 		put_device(&aq->ap_dev.device);
936 		if (override)
937 			goto out;
938 	}
939 
940 	if (test_bit_inv(card, ap_perms.apm) &&
941 	    test_bit_inv(queue, ap_perms.aqm))
942 		rc = 1;
943 
944 out:
945 	return rc;
946 }
947 EXPORT_SYMBOL(ap_owned_by_def_drv);
948 
949 /**
950  * ap_apqn_in_matrix_owned_by_def_drv: indicates whether every APQN contained in
951  *				       a set is reserved for the host drivers
952  *				       or not.
953  * @apm: a bitmap specifying a set of APIDs comprising the APQNs to check
954  * @aqm: a bitmap specifying a set of APQIs comprising the APQNs to check
955  *
956  * Note: the ap_attr_mutex must be locked by the caller of this function.
957  *
958  * Return: an int specifying whether each APQN is reserved for the host (1) or
959  *	   not (0)
960  */
961 int ap_apqn_in_matrix_owned_by_def_drv(unsigned long *apm,
962 				       unsigned long *aqm)
963 {
964 	int card, queue, rc = 0;
965 
966 	for (card = 0; !rc && card < AP_DEVICES; card++)
967 		if (test_bit_inv(card, apm))
968 			for (queue = 0; !rc && queue < AP_DOMAINS; queue++)
969 				if (test_bit_inv(queue, aqm))
970 					rc = ap_owned_by_def_drv(card, queue);
971 
972 	return rc;
973 }
974 EXPORT_SYMBOL(ap_apqn_in_matrix_owned_by_def_drv);
975 
976 static int ap_device_probe(struct device *dev)
977 {
978 	struct ap_device *ap_dev = to_ap_dev(dev);
979 	struct ap_driver *ap_drv = to_ap_drv(dev->driver);
980 	int card, queue, devres, drvres, rc = -ENODEV;
981 
982 	if (!get_device(dev))
983 		return rc;
984 
985 	if (is_queue_dev(dev)) {
986 		/*
987 		 * If the apqn is marked as reserved/used by ap bus and
988 		 * default drivers, only probe with drivers with the default
989 		 * flag set. If it is not marked, only probe with drivers
990 		 * with the default flag not set.
991 		 */
992 		card = AP_QID_CARD(to_ap_queue(dev)->qid);
993 		queue = AP_QID_QUEUE(to_ap_queue(dev)->qid);
994 		if (ap_dev->driver_override) {
995 			if (strcmp(ap_dev->driver_override,
996 				   ap_drv->driver.name))
997 				goto out;
998 		} else {
999 			mutex_lock(&ap_attr_mutex);
1000 			devres = test_bit_inv(card, ap_perms.apm) &&
1001 				test_bit_inv(queue, ap_perms.aqm);
1002 			mutex_unlock(&ap_attr_mutex);
1003 			drvres = ap_drv->flags & AP_DRIVER_FLAG_DEFAULT;
1004 			if (!!devres != !!drvres)
1005 				goto out;
1006 		}
1007 	}
1008 
1009 	/*
1010 	 * Rearm the bindings complete completion to trigger
1011 	 * bindings complete when all devices are bound again
1012 	 */
1013 	reinit_completion(&ap_apqn_bindings_complete);
1014 
1015 	/* Add queue/card to list of active queues/cards */
1016 	spin_lock_bh(&ap_queues_lock);
1017 	if (is_queue_dev(dev))
1018 		hash_add(ap_queues, &to_ap_queue(dev)->hnode,
1019 			 to_ap_queue(dev)->qid);
1020 	spin_unlock_bh(&ap_queues_lock);
1021 
1022 	rc = ap_drv->probe ? ap_drv->probe(ap_dev) : -ENODEV;
1023 
1024 	if (rc) {
1025 		spin_lock_bh(&ap_queues_lock);
1026 		if (is_queue_dev(dev))
1027 			hash_del(&to_ap_queue(dev)->hnode);
1028 		spin_unlock_bh(&ap_queues_lock);
1029 	}
1030 
1031 out:
1032 	if (rc) {
1033 		put_device(dev);
1034 	} else {
1035 		if (is_queue_dev(dev)) {
1036 			pr_debug("queue=%02x.%04x new driver=%s\n",
1037 				 card, queue, ap_drv->driver.name);
1038 		} else {
1039 			pr_debug("card=%02x new driver=%s\n",
1040 				 to_ap_card(dev)->id, ap_drv->driver.name);
1041 		}
1042 	}
1043 	return rc;
1044 }
1045 
1046 static void ap_device_remove(struct device *dev)
1047 {
1048 	struct ap_device *ap_dev = to_ap_dev(dev);
1049 	struct ap_driver *ap_drv = to_ap_drv(dev->driver);
1050 
1051 	/* prepare ap queue device removal */
1052 	if (is_queue_dev(dev))
1053 		ap_queue_prepare_remove(to_ap_queue(dev));
1054 
1055 	/* driver's chance to clean up gracefully */
1056 	if (ap_drv->remove)
1057 		ap_drv->remove(ap_dev);
1058 
1059 	/* now do the ap queue device remove */
1060 	if (is_queue_dev(dev))
1061 		ap_queue_remove(to_ap_queue(dev));
1062 
1063 	/* Remove queue/card from list of active queues/cards */
1064 	spin_lock_bh(&ap_queues_lock);
1065 	if (is_queue_dev(dev))
1066 		hash_del(&to_ap_queue(dev)->hnode);
1067 	spin_unlock_bh(&ap_queues_lock);
1068 
1069 	put_device(dev);
1070 }
1071 
1072 struct ap_queue *ap_get_qdev(ap_qid_t qid)
1073 {
1074 	int bkt;
1075 	struct ap_queue *aq;
1076 
1077 	spin_lock_bh(&ap_queues_lock);
1078 	hash_for_each(ap_queues, bkt, aq, hnode) {
1079 		if (aq->qid == qid) {
1080 			get_device(&aq->ap_dev.device);
1081 			spin_unlock_bh(&ap_queues_lock);
1082 			return aq;
1083 		}
1084 	}
1085 	spin_unlock_bh(&ap_queues_lock);
1086 
1087 	return NULL;
1088 }
1089 EXPORT_SYMBOL(ap_get_qdev);
1090 
1091 int ap_driver_register(struct ap_driver *ap_drv, struct module *owner,
1092 		       char *name)
1093 {
1094 	struct device_driver *drv = &ap_drv->driver;
1095 	int rc;
1096 
1097 	drv->bus = &ap_bus_type;
1098 	drv->owner = owner;
1099 	drv->name = name;
1100 	rc = driver_register(drv);
1101 
1102 	ap_check_bindings_complete();
1103 
1104 	return rc;
1105 }
1106 EXPORT_SYMBOL(ap_driver_register);
1107 
1108 void ap_driver_unregister(struct ap_driver *ap_drv)
1109 {
1110 	driver_unregister(&ap_drv->driver);
1111 }
1112 EXPORT_SYMBOL(ap_driver_unregister);
1113 
1114 /*
1115  * Enforce a synchronous AP bus rescan.
1116  * Returns true if the bus scan finds a change in the AP configuration
1117  * and AP devices have been added or deleted when this function returns.
1118  */
1119 bool ap_bus_force_rescan(void)
1120 {
1121 	unsigned long scan_counter = atomic64_read(&ap_scan_bus_count);
1122 	bool rc = false;
1123 
1124 	pr_debug("> scan counter=%lu\n", scan_counter);
1125 
1126 	/* Only trigger AP bus scans after the initial scan is done */
1127 	if (scan_counter <= 0)
1128 		goto out;
1129 
1130 	/*
1131 	 * There is one unlikely but nevertheless valid scenario where the
1132 	 * thread holding the mutex may try to send some crypto load but
1133 	 * all cards are offline so a rescan is triggered which causes
1134 	 * a recursive call of ap_bus_force_rescan(). A simple return if
1135 	 * the mutex is already locked by this thread solves this.
1136 	 */
1137 	if (mutex_is_locked(&ap_scan_bus_mutex)) {
1138 		if (ap_scan_bus_task == current)
1139 			goto out;
1140 	}
1141 
1142 	/* Try to acquire the AP scan bus mutex */
1143 	if (mutex_trylock(&ap_scan_bus_mutex)) {
1144 		/* mutex acquired, run the AP bus scan */
1145 		ap_scan_bus_task = current;
1146 		ap_scan_bus_result = ap_scan_bus();
1147 		rc = ap_scan_bus_result;
1148 		ap_scan_bus_task = NULL;
1149 		mutex_unlock(&ap_scan_bus_mutex);
1150 		goto out;
1151 	}
1152 
1153 	/*
1154 	 * Mutex acquire failed. So there is currently another task
1155 	 * already running the AP bus scan. Then let's simple wait
1156 	 * for the lock which means the other task has finished and
1157 	 * stored the result in ap_scan_bus_result.
1158 	 */
1159 	if (mutex_lock_interruptible(&ap_scan_bus_mutex)) {
1160 		/* some error occurred, ignore and go out */
1161 		goto out;
1162 	}
1163 	rc = ap_scan_bus_result;
1164 	mutex_unlock(&ap_scan_bus_mutex);
1165 
1166 out:
1167 	pr_debug("rc=%d\n", rc);
1168 	return rc;
1169 }
1170 EXPORT_SYMBOL(ap_bus_force_rescan);
1171 
1172 /*
1173  * A config change has happened, force an ap bus rescan.
1174  */
1175 static int ap_bus_cfg_chg(struct notifier_block *nb,
1176 			  unsigned long action, void *data)
1177 {
1178 	if (action != CHSC_NOTIFY_AP_CFG)
1179 		return NOTIFY_DONE;
1180 
1181 	pr_debug("config change, forcing bus rescan\n");
1182 
1183 	ap_bus_force_rescan();
1184 
1185 	return NOTIFY_OK;
1186 }
1187 
1188 static struct notifier_block ap_bus_nb = {
1189 	.notifier_call = ap_bus_cfg_chg,
1190 };
1191 
1192 int ap_hex2bitmap(const char *str, unsigned long *bitmap, int bits)
1193 {
1194 	int i, n, b;
1195 
1196 	/* bits needs to be a multiple of 8 */
1197 	if (bits & 0x07)
1198 		return -EINVAL;
1199 
1200 	if (str[0] == '0' && str[1] == 'x')
1201 		str++;
1202 	if (*str == 'x')
1203 		str++;
1204 
1205 	for (i = 0; isxdigit(*str) && i < bits; str++) {
1206 		b = hex_to_bin(*str);
1207 		for (n = 0; n < 4; n++)
1208 			if (b & (0x08 >> n))
1209 				set_bit_inv(i + n, bitmap);
1210 		i += 4;
1211 	}
1212 
1213 	if (*str == '\n')
1214 		str++;
1215 	if (*str)
1216 		return -EINVAL;
1217 	return 0;
1218 }
1219 EXPORT_SYMBOL(ap_hex2bitmap);
1220 
1221 /*
1222  * modify_bitmap() - parse bitmask argument and modify an existing
1223  * bit mask accordingly. A concatenation (done with ',') of these
1224  * terms is recognized:
1225  *   +<bitnr>[-<bitnr>] or -<bitnr>[-<bitnr>]
1226  * <bitnr> may be any valid number (hex, decimal or octal) in the range
1227  * 0...bits-1; the leading + or - is required. Here are some examples:
1228  *   +0-15,+32,-128,-0xFF
1229  *   -0-255,+1-16,+0x128
1230  *   +1,+2,+3,+4,-5,-7-10
1231  * Returns the new bitmap after all changes have been applied. Every
1232  * positive value in the string will set a bit and every negative value
1233  * in the string will clear a bit. As a bit may be touched more than once,
1234  * the last 'operation' wins:
1235  * +0-255,-128 = first bits 0-255 will be set, then bit 128 will be
1236  * cleared again. All other bits are unmodified.
1237  */
1238 static int modify_bitmap(const char *str, unsigned long *bitmap, int bits)
1239 {
1240 	unsigned long a, i, z;
1241 	char *np, sign;
1242 
1243 	/* bits needs to be a multiple of 8 */
1244 	if (bits & 0x07)
1245 		return -EINVAL;
1246 
1247 	while (*str) {
1248 		sign = *str++;
1249 		if (sign != '+' && sign != '-')
1250 			return -EINVAL;
1251 		a = z = simple_strtoul(str, &np, 0);
1252 		if (str == np || a >= bits)
1253 			return -EINVAL;
1254 		str = np;
1255 		if (*str == '-') {
1256 			z = simple_strtoul(++str, &np, 0);
1257 			if (str == np || a > z || z >= bits)
1258 				return -EINVAL;
1259 			str = np;
1260 		}
1261 		for (i = a; i <= z; i++)
1262 			if (sign == '+')
1263 				set_bit_inv(i, bitmap);
1264 			else
1265 				clear_bit_inv(i, bitmap);
1266 		while (*str == ',' || *str == '\n')
1267 			str++;
1268 	}
1269 
1270 	return 0;
1271 }
1272 
1273 static int ap_parse_bitmap_str(const char *str, unsigned long *bitmap, int bits,
1274 			       unsigned long *newmap)
1275 {
1276 	unsigned long size;
1277 	int rc;
1278 
1279 	size = BITS_TO_LONGS(bits) * sizeof(unsigned long);
1280 	if (*str == '+' || *str == '-') {
1281 		memcpy(newmap, bitmap, size);
1282 		rc = modify_bitmap(str, newmap, bits);
1283 	} else {
1284 		memset(newmap, 0, size);
1285 		rc = ap_hex2bitmap(str, newmap, bits);
1286 	}
1287 	return rc;
1288 }
1289 
1290 int ap_parse_mask_str(const char *str,
1291 		      unsigned long *bitmap, int bits,
1292 		      struct mutex *lock)
1293 {
1294 	unsigned long *newmap, size;
1295 	int rc;
1296 
1297 	/* bits needs to be a multiple of 8 */
1298 	if (bits & 0x07)
1299 		return -EINVAL;
1300 
1301 	size = BITS_TO_LONGS(bits) * sizeof(unsigned long);
1302 	newmap = kmalloc(size, GFP_KERNEL);
1303 	if (!newmap)
1304 		return -ENOMEM;
1305 	if (mutex_lock_interruptible(lock)) {
1306 		kfree(newmap);
1307 		return -ERESTARTSYS;
1308 	}
1309 	rc = ap_parse_bitmap_str(str, bitmap, bits, newmap);
1310 	if (rc == 0)
1311 		memcpy(bitmap, newmap, size);
1312 	mutex_unlock(lock);
1313 	kfree(newmap);
1314 	return rc;
1315 }
1316 EXPORT_SYMBOL(ap_parse_mask_str);
1317 
1318 /*
1319  * AP bus attributes.
1320  */
1321 
1322 static ssize_t ap_domain_show(const struct bus_type *bus, char *buf)
1323 {
1324 	return sysfs_emit(buf, "%d\n", ap_domain_index);
1325 }
1326 
1327 static ssize_t ap_domain_store(const struct bus_type *bus,
1328 			       const char *buf, size_t count)
1329 {
1330 	int domain;
1331 
1332 	if (sscanf(buf, "%i\n", &domain) != 1 ||
1333 	    domain < 0 || domain > ap_max_domain_id ||
1334 	    !test_bit_inv(domain, ap_perms.aqm))
1335 		return -EINVAL;
1336 
1337 	spin_lock_bh(&ap_domain_lock);
1338 	ap_domain_index = domain;
1339 	spin_unlock_bh(&ap_domain_lock);
1340 
1341 	AP_DBF_INFO("%s stored new default domain=%d\n",
1342 		    __func__, domain);
1343 
1344 	return count;
1345 }
1346 
1347 static BUS_ATTR_RW(ap_domain);
1348 
1349 static ssize_t ap_control_domain_mask_show(const struct bus_type *bus, char *buf)
1350 {
1351 	if (!ap_qci_info->flags)	/* QCI not supported */
1352 		return sysfs_emit(buf, "not supported\n");
1353 
1354 	return sysfs_emit(buf, "0x%08x%08x%08x%08x%08x%08x%08x%08x\n",
1355 			  ap_qci_info->adm[0], ap_qci_info->adm[1],
1356 			  ap_qci_info->adm[2], ap_qci_info->adm[3],
1357 			  ap_qci_info->adm[4], ap_qci_info->adm[5],
1358 			  ap_qci_info->adm[6], ap_qci_info->adm[7]);
1359 }
1360 
1361 static BUS_ATTR_RO(ap_control_domain_mask);
1362 
1363 static ssize_t ap_usage_domain_mask_show(const struct bus_type *bus, char *buf)
1364 {
1365 	if (!ap_qci_info->flags)	/* QCI not supported */
1366 		return sysfs_emit(buf, "not supported\n");
1367 
1368 	return sysfs_emit(buf, "0x%08x%08x%08x%08x%08x%08x%08x%08x\n",
1369 			  ap_qci_info->aqm[0], ap_qci_info->aqm[1],
1370 			  ap_qci_info->aqm[2], ap_qci_info->aqm[3],
1371 			  ap_qci_info->aqm[4], ap_qci_info->aqm[5],
1372 			  ap_qci_info->aqm[6], ap_qci_info->aqm[7]);
1373 }
1374 
1375 static BUS_ATTR_RO(ap_usage_domain_mask);
1376 
1377 static ssize_t ap_adapter_mask_show(const struct bus_type *bus, char *buf)
1378 {
1379 	if (!ap_qci_info->flags)	/* QCI not supported */
1380 		return sysfs_emit(buf, "not supported\n");
1381 
1382 	return sysfs_emit(buf, "0x%08x%08x%08x%08x%08x%08x%08x%08x\n",
1383 			  ap_qci_info->apm[0], ap_qci_info->apm[1],
1384 			  ap_qci_info->apm[2], ap_qci_info->apm[3],
1385 			  ap_qci_info->apm[4], ap_qci_info->apm[5],
1386 			  ap_qci_info->apm[6], ap_qci_info->apm[7]);
1387 }
1388 
1389 static BUS_ATTR_RO(ap_adapter_mask);
1390 
1391 static ssize_t ap_interrupts_show(const struct bus_type *bus, char *buf)
1392 {
1393 	return sysfs_emit(buf, "%d\n", ap_irq_flag ? 1 : 0);
1394 }
1395 
1396 static BUS_ATTR_RO(ap_interrupts);
1397 
1398 static ssize_t config_time_show(const struct bus_type *bus, char *buf)
1399 {
1400 	return sysfs_emit(buf, "%d\n", ap_scan_bus_time);
1401 }
1402 
1403 static ssize_t config_time_store(const struct bus_type *bus,
1404 				 const char *buf, size_t count)
1405 {
1406 	int time;
1407 
1408 	if (sscanf(buf, "%d\n", &time) != 1 || time < 5 || time > 120)
1409 		return -EINVAL;
1410 	ap_scan_bus_time = time;
1411 	mod_timer(&ap_scan_bus_timer, jiffies + ap_scan_bus_time * HZ);
1412 	return count;
1413 }
1414 
1415 static BUS_ATTR_RW(config_time);
1416 
1417 static ssize_t poll_thread_show(const struct bus_type *bus, char *buf)
1418 {
1419 	return sysfs_emit(buf, "%d\n", ap_poll_kthread ? 1 : 0);
1420 }
1421 
1422 static ssize_t poll_thread_store(const struct bus_type *bus,
1423 				 const char *buf, size_t count)
1424 {
1425 	bool value;
1426 	int rc;
1427 
1428 	rc = kstrtobool(buf, &value);
1429 	if (rc)
1430 		return rc;
1431 
1432 	if (value) {
1433 		rc = ap_poll_thread_start();
1434 		if (rc)
1435 			count = rc;
1436 	} else {
1437 		ap_poll_thread_stop();
1438 	}
1439 	return count;
1440 }
1441 
1442 static BUS_ATTR_RW(poll_thread);
1443 
1444 static ssize_t poll_timeout_show(const struct bus_type *bus, char *buf)
1445 {
1446 	return sysfs_emit(buf, "%lu\n", poll_high_timeout);
1447 }
1448 
1449 static ssize_t poll_timeout_store(const struct bus_type *bus, const char *buf,
1450 				  size_t count)
1451 {
1452 	unsigned long value;
1453 	ktime_t hr_time;
1454 	int rc;
1455 
1456 	rc = kstrtoul(buf, 0, &value);
1457 	if (rc)
1458 		return rc;
1459 
1460 	/* 120 seconds = maximum poll interval */
1461 	if (value > 120000000000UL)
1462 		return -EINVAL;
1463 	poll_high_timeout = value;
1464 	hr_time = poll_high_timeout;
1465 
1466 	spin_lock_bh(&ap_poll_timer_lock);
1467 	hrtimer_cancel(&ap_poll_timer);
1468 	hrtimer_set_expires(&ap_poll_timer, hr_time);
1469 	hrtimer_start_expires(&ap_poll_timer, HRTIMER_MODE_ABS);
1470 	spin_unlock_bh(&ap_poll_timer_lock);
1471 
1472 	return count;
1473 }
1474 
1475 static BUS_ATTR_RW(poll_timeout);
1476 
1477 static ssize_t ap_max_domain_id_show(const struct bus_type *bus, char *buf)
1478 {
1479 	return sysfs_emit(buf, "%d\n", ap_max_domain_id);
1480 }
1481 
1482 static BUS_ATTR_RO(ap_max_domain_id);
1483 
1484 static ssize_t ap_max_adapter_id_show(const struct bus_type *bus, char *buf)
1485 {
1486 	return sysfs_emit(buf, "%d\n", ap_max_adapter_id);
1487 }
1488 
1489 static BUS_ATTR_RO(ap_max_adapter_id);
1490 
1491 static ssize_t apmask_show(const struct bus_type *bus, char *buf)
1492 {
1493 	int rc;
1494 
1495 	if (mutex_lock_interruptible(&ap_attr_mutex))
1496 		return -ERESTARTSYS;
1497 	rc = sysfs_emit(buf, "0x%016lx%016lx%016lx%016lx\n",
1498 			ap_perms.apm[0], ap_perms.apm[1],
1499 			ap_perms.apm[2], ap_perms.apm[3]);
1500 	mutex_unlock(&ap_attr_mutex);
1501 
1502 	return rc;
1503 }
1504 
1505 static int __verify_card_reservations(struct device_driver *drv, void *data)
1506 {
1507 	int rc = 0;
1508 	struct ap_driver *ap_drv = to_ap_drv(drv);
1509 	unsigned long *newapm = (unsigned long *)data;
1510 	unsigned long aqm_any[BITS_TO_LONGS(AP_DOMAINS)];
1511 
1512 	/*
1513 	 * increase the driver's module refcounter to be sure it is not
1514 	 * going away when we invoke the callback function.
1515 	 */
1516 	if (!try_module_get(drv->owner))
1517 		return 0;
1518 
1519 	if (ap_drv->in_use) {
1520 		bitmap_fill(aqm_any, AP_DOMAINS);
1521 		rc = ap_drv->in_use(newapm, aqm_any);
1522 		if (rc)
1523 			rc = -EBUSY;
1524 	}
1525 
1526 	/* release the driver's module */
1527 	module_put(drv->owner);
1528 
1529 	return rc;
1530 }
1531 
1532 static int apmask_commit(unsigned long *newapm)
1533 {
1534 	int rc;
1535 	unsigned long reserved[BITS_TO_LONGS(AP_DEVICES)];
1536 
1537 	/*
1538 	 * Check if any bits in the apmask have been set which will
1539 	 * result in queues being removed from non-default drivers
1540 	 */
1541 	if (bitmap_andnot(reserved, newapm, ap_perms.apm, AP_DEVICES)) {
1542 		rc = bus_for_each_drv(&ap_bus_type, NULL, reserved,
1543 				      __verify_card_reservations);
1544 		if (rc)
1545 			return rc;
1546 	}
1547 
1548 	memcpy(ap_perms.apm, newapm, APMASKSIZE);
1549 
1550 	/*
1551 	 * Update ap_apmask_aqmask_in_use. Note that the
1552 	 * ap_attr_mutex has to be obtained here.
1553 	 */
1554 	ap_apmask_aqmask_in_use =
1555 		bitmap_full(ap_perms.apm, AP_DEVICES) &&
1556 		bitmap_full(ap_perms.aqm, AP_DOMAINS) ?
1557 		false : true;
1558 
1559 	return 0;
1560 }
1561 
1562 static ssize_t apmask_store(const struct bus_type *bus, const char *buf,
1563 			    size_t count)
1564 {
1565 	DECLARE_BITMAP(newapm, AP_DEVICES);
1566 	int rc = -EINVAL, changes = 0;
1567 
1568 	if (mutex_lock_interruptible(&ap_attr_mutex))
1569 		return -ERESTARTSYS;
1570 
1571 	/* Do not allow apmask/aqmask if driver override is active */
1572 	if (ap_driver_override_ctr)
1573 		goto done;
1574 
1575 	rc = ap_parse_bitmap_str(buf, ap_perms.apm, AP_DEVICES, newapm);
1576 	if (rc)
1577 		goto done;
1578 
1579 	changes = memcmp(ap_perms.apm, newapm, APMASKSIZE);
1580 	if (changes)
1581 		rc = apmask_commit(newapm);
1582 
1583 done:
1584 	mutex_unlock(&ap_attr_mutex);
1585 	if (rc)
1586 		return rc;
1587 
1588 	if (changes) {
1589 		ap_bus_revise_bindings();
1590 		ap_send_mask_changed_uevent(newapm, NULL);
1591 	}
1592 
1593 	return count;
1594 }
1595 
1596 static BUS_ATTR_RW(apmask);
1597 
1598 static ssize_t aqmask_show(const struct bus_type *bus, char *buf)
1599 {
1600 	int rc;
1601 
1602 	if (mutex_lock_interruptible(&ap_attr_mutex))
1603 		return -ERESTARTSYS;
1604 	rc = sysfs_emit(buf, "0x%016lx%016lx%016lx%016lx\n",
1605 			ap_perms.aqm[0], ap_perms.aqm[1],
1606 			ap_perms.aqm[2], ap_perms.aqm[3]);
1607 	mutex_unlock(&ap_attr_mutex);
1608 
1609 	return rc;
1610 }
1611 
1612 static int __verify_queue_reservations(struct device_driver *drv, void *data)
1613 {
1614 	int rc = 0;
1615 	struct ap_driver *ap_drv = to_ap_drv(drv);
1616 	unsigned long *newaqm = (unsigned long *)data;
1617 	unsigned long apm_any[BITS_TO_LONGS(AP_DEVICES)];
1618 
1619 	/*
1620 	 * increase the driver's module refcounter to be sure it is not
1621 	 * going away when we invoke the callback function.
1622 	 */
1623 	if (!try_module_get(drv->owner))
1624 		return 0;
1625 
1626 	if (ap_drv->in_use) {
1627 		bitmap_fill(apm_any, AP_DEVICES);
1628 		rc = ap_drv->in_use(apm_any, newaqm);
1629 		if (rc)
1630 			rc = -EBUSY;
1631 	}
1632 
1633 	/* release the driver's module */
1634 	module_put(drv->owner);
1635 
1636 	return rc;
1637 }
1638 
1639 static int aqmask_commit(unsigned long *newaqm)
1640 {
1641 	int rc;
1642 	unsigned long reserved[BITS_TO_LONGS(AP_DOMAINS)];
1643 
1644 	/*
1645 	 * Check if any bits in the aqmask have been set which will
1646 	 * result in queues being removed from non-default drivers
1647 	 */
1648 	if (bitmap_andnot(reserved, newaqm, ap_perms.aqm, AP_DOMAINS)) {
1649 		rc = bus_for_each_drv(&ap_bus_type, NULL, reserved,
1650 				      __verify_queue_reservations);
1651 		if (rc)
1652 			return rc;
1653 	}
1654 
1655 	memcpy(ap_perms.aqm, newaqm, AQMASKSIZE);
1656 
1657 	/*
1658 	 * Update ap_apmask_aqmask_in_use. Note that the
1659 	 * ap_attr_mutex has to be obtained here.
1660 	 */
1661 	ap_apmask_aqmask_in_use =
1662 		bitmap_full(ap_perms.apm, AP_DEVICES) &&
1663 		bitmap_full(ap_perms.aqm, AP_DOMAINS) ?
1664 		false : true;
1665 
1666 	return 0;
1667 }
1668 
1669 static ssize_t aqmask_store(const struct bus_type *bus, const char *buf,
1670 			    size_t count)
1671 {
1672 	DECLARE_BITMAP(newaqm, AP_DOMAINS);
1673 	int rc = -EINVAL, changes = 0;
1674 
1675 	if (mutex_lock_interruptible(&ap_attr_mutex))
1676 		return -ERESTARTSYS;
1677 
1678 	/* Do not allow apmask/aqmask if driver override is active */
1679 	if (ap_driver_override_ctr)
1680 		goto done;
1681 
1682 	rc = ap_parse_bitmap_str(buf, ap_perms.aqm, AP_DOMAINS, newaqm);
1683 	if (rc)
1684 		goto done;
1685 
1686 	changes = memcmp(ap_perms.aqm, newaqm, APMASKSIZE);
1687 	if (changes)
1688 		rc = aqmask_commit(newaqm);
1689 
1690 done:
1691 	mutex_unlock(&ap_attr_mutex);
1692 	if (rc)
1693 		return rc;
1694 
1695 	if (changes) {
1696 		ap_bus_revise_bindings();
1697 		ap_send_mask_changed_uevent(NULL, newaqm);
1698 	}
1699 
1700 	return count;
1701 }
1702 
1703 static BUS_ATTR_RW(aqmask);
1704 
1705 static ssize_t scans_show(const struct bus_type *bus, char *buf)
1706 {
1707 	return sysfs_emit(buf, "%llu\n", atomic64_read(&ap_scan_bus_count));
1708 }
1709 
1710 static ssize_t scans_store(const struct bus_type *bus, const char *buf,
1711 			   size_t count)
1712 {
1713 	AP_DBF_INFO("%s force AP bus rescan\n", __func__);
1714 
1715 	ap_bus_force_rescan();
1716 
1717 	return count;
1718 }
1719 
1720 static BUS_ATTR_RW(scans);
1721 
1722 static ssize_t bindings_show(const struct bus_type *bus, char *buf)
1723 {
1724 	int rc;
1725 	unsigned int apqns, n;
1726 
1727 	ap_calc_bound_apqns(&apqns, &n);
1728 	if (atomic64_read(&ap_scan_bus_count) >= 1 && n == apqns)
1729 		rc = sysfs_emit(buf, "%u/%u (complete)\n", n, apqns);
1730 	else
1731 		rc = sysfs_emit(buf, "%u/%u\n", n, apqns);
1732 
1733 	return rc;
1734 }
1735 
1736 static BUS_ATTR_RO(bindings);
1737 
1738 static ssize_t bindings_complete_count_show(const struct bus_type *bus,
1739 					    char *buf)
1740 {
1741 	return sysfs_emit(buf, "%llu\n",
1742 			  atomic64_read(&ap_bindings_complete_count));
1743 }
1744 
1745 static BUS_ATTR_RO(bindings_complete_count);
1746 
1747 static ssize_t features_show(const struct bus_type *bus, char *buf)
1748 {
1749 	int n = 0;
1750 
1751 	if (!ap_qci_info->flags)	/* QCI not supported */
1752 		return sysfs_emit(buf, "-\n");
1753 
1754 	if (ap_qci_info->apsc)
1755 		n += sysfs_emit_at(buf, n, "APSC ");
1756 	if (ap_qci_info->apxa)
1757 		n += sysfs_emit_at(buf, n, "APXA ");
1758 	if (ap_qci_info->qact)
1759 		n += sysfs_emit_at(buf, n, "QACT ");
1760 	if (ap_qci_info->rc8a)
1761 		n += sysfs_emit_at(buf, n, "RC8A ");
1762 	if (ap_qci_info->apsb)
1763 		n += sysfs_emit_at(buf, n, "APSB ");
1764 
1765 	sysfs_emit_at(buf, n == 0 ? 0 : n - 1, "\n");
1766 
1767 	return n;
1768 }
1769 
1770 static BUS_ATTR_RO(features);
1771 
1772 static struct attribute *ap_bus_attrs[] = {
1773 	&bus_attr_ap_domain.attr,
1774 	&bus_attr_ap_control_domain_mask.attr,
1775 	&bus_attr_ap_usage_domain_mask.attr,
1776 	&bus_attr_ap_adapter_mask.attr,
1777 	&bus_attr_config_time.attr,
1778 	&bus_attr_poll_thread.attr,
1779 	&bus_attr_ap_interrupts.attr,
1780 	&bus_attr_poll_timeout.attr,
1781 	&bus_attr_ap_max_domain_id.attr,
1782 	&bus_attr_ap_max_adapter_id.attr,
1783 	&bus_attr_apmask.attr,
1784 	&bus_attr_aqmask.attr,
1785 	&bus_attr_scans.attr,
1786 	&bus_attr_bindings.attr,
1787 	&bus_attr_bindings_complete_count.attr,
1788 	&bus_attr_features.attr,
1789 	NULL,
1790 };
1791 ATTRIBUTE_GROUPS(ap_bus);
1792 
1793 static const struct bus_type ap_bus_type = {
1794 	.name = "ap",
1795 	.bus_groups = ap_bus_groups,
1796 	.match = &ap_bus_match,
1797 	.uevent = &ap_uevent,
1798 	.probe = ap_device_probe,
1799 	.remove = ap_device_remove,
1800 };
1801 
1802 /**
1803  * ap_select_domain(): Select an AP domain if possible and we haven't
1804  * already done so before.
1805  */
1806 static void ap_select_domain(void)
1807 {
1808 	struct ap_queue_status status;
1809 	int card, dom;
1810 
1811 	/*
1812 	 * Choose the default domain. Either the one specified with
1813 	 * the "domain=" parameter or the first domain with at least
1814 	 * one valid APQN.
1815 	 */
1816 	spin_lock_bh(&ap_domain_lock);
1817 	if (ap_domain_index >= 0) {
1818 		/* Domain has already been selected. */
1819 		goto out;
1820 	}
1821 	for (dom = 0; dom <= ap_max_domain_id; dom++) {
1822 		if (!ap_test_config_usage_domain(dom) ||
1823 		    !test_bit_inv(dom, ap_perms.aqm))
1824 			continue;
1825 		for (card = 0; card <= ap_max_adapter_id; card++) {
1826 			if (!ap_test_config_card_id(card) ||
1827 			    !test_bit_inv(card, ap_perms.apm))
1828 				continue;
1829 			status = ap_test_queue(AP_MKQID(card, dom),
1830 					       ap_apft_available(),
1831 					       NULL);
1832 			if (status.response_code == AP_RESPONSE_NORMAL)
1833 				break;
1834 		}
1835 		if (card <= ap_max_adapter_id)
1836 			break;
1837 	}
1838 	if (dom <= ap_max_domain_id) {
1839 		ap_domain_index = dom;
1840 		AP_DBF_INFO("%s new default domain is %d\n",
1841 			    __func__, ap_domain_index);
1842 	}
1843 out:
1844 	spin_unlock_bh(&ap_domain_lock);
1845 }
1846 
1847 /*
1848  * This function checks the type and returns either 0 for not
1849  * supported or the highest compatible type value (which may
1850  * include the input type value).
1851  */
1852 static int ap_get_compatible_type(ap_qid_t qid, int rawtype, unsigned int func)
1853 {
1854 	int comp_type = 0;
1855 
1856 	/* < CEX4 is not supported */
1857 	if (rawtype < AP_DEVICE_TYPE_CEX4) {
1858 		AP_DBF_WARN("%s queue=%02x.%04x unsupported type %d\n",
1859 			    __func__, AP_QID_CARD(qid),
1860 			    AP_QID_QUEUE(qid), rawtype);
1861 		return 0;
1862 	}
1863 	/* up to CEX8 known and fully supported */
1864 	if (rawtype <= AP_DEVICE_TYPE_CEX8)
1865 		return rawtype;
1866 	/*
1867 	 * unknown new type > CEX8, check for compatibility
1868 	 * to the highest known and supported type which is
1869 	 * currently CEX8 with the help of the QACT function.
1870 	 */
1871 	if (ap_qact_available()) {
1872 		struct ap_queue_status status;
1873 		union ap_qact_ap_info apinfo = {0};
1874 
1875 		apinfo.mode = (func >> 26) & 0x07;
1876 		apinfo.cat = AP_DEVICE_TYPE_CEX8;
1877 		status = ap_qact(qid, 0, &apinfo);
1878 		if (status.response_code == AP_RESPONSE_NORMAL &&
1879 		    apinfo.cat >= AP_DEVICE_TYPE_CEX4 &&
1880 		    apinfo.cat <= AP_DEVICE_TYPE_CEX8)
1881 			comp_type = apinfo.cat;
1882 	}
1883 	if (!comp_type)
1884 		AP_DBF_WARN("%s queue=%02x.%04x unable to map type %d\n",
1885 			    __func__, AP_QID_CARD(qid),
1886 			    AP_QID_QUEUE(qid), rawtype);
1887 	else if (comp_type != rawtype)
1888 		AP_DBF_INFO("%s queue=%02x.%04x map type %d to %d\n",
1889 			    __func__, AP_QID_CARD(qid), AP_QID_QUEUE(qid),
1890 			    rawtype, comp_type);
1891 	return comp_type;
1892 }
1893 
1894 /*
1895  * Helper function to be used with bus_find_dev
1896  * matches for the card device with the given id
1897  */
1898 static int __match_card_device_with_id(struct device *dev, const void *data)
1899 {
1900 	return is_card_dev(dev) && to_ap_card(dev)->id == (int)(long)(void *)data;
1901 }
1902 
1903 /*
1904  * Helper function to be used with bus_find_dev
1905  * matches for the queue device with a given qid
1906  */
1907 static int __match_queue_device_with_qid(struct device *dev, const void *data)
1908 {
1909 	return is_queue_dev(dev) && to_ap_queue(dev)->qid == (int)(long)data;
1910 }
1911 
1912 /*
1913  * Helper function to be used with bus_find_dev
1914  * matches any queue device with given queue id
1915  */
1916 static int __match_queue_device_with_queue_id(struct device *dev, const void *data)
1917 {
1918 	return is_queue_dev(dev) &&
1919 		AP_QID_QUEUE(to_ap_queue(dev)->qid) == (int)(long)data;
1920 }
1921 
1922 /* Helper function for notify_config_changed */
1923 static int __drv_notify_config_changed(struct device_driver *drv, void *data)
1924 {
1925 	struct ap_driver *ap_drv = to_ap_drv(drv);
1926 
1927 	if (try_module_get(drv->owner)) {
1928 		if (ap_drv->on_config_changed)
1929 			ap_drv->on_config_changed(ap_qci_info, ap_qci_info_old);
1930 		module_put(drv->owner);
1931 	}
1932 
1933 	return 0;
1934 }
1935 
1936 /* Notify all drivers about an qci config change */
1937 static inline void notify_config_changed(void)
1938 {
1939 	bus_for_each_drv(&ap_bus_type, NULL, NULL,
1940 			 __drv_notify_config_changed);
1941 }
1942 
1943 /* Helper function for notify_scan_complete */
1944 static int __drv_notify_scan_complete(struct device_driver *drv, void *data)
1945 {
1946 	struct ap_driver *ap_drv = to_ap_drv(drv);
1947 
1948 	if (try_module_get(drv->owner)) {
1949 		if (ap_drv->on_scan_complete)
1950 			ap_drv->on_scan_complete(ap_qci_info,
1951 						 ap_qci_info_old);
1952 		module_put(drv->owner);
1953 	}
1954 
1955 	return 0;
1956 }
1957 
1958 /* Notify all drivers about bus scan complete */
1959 static inline void notify_scan_complete(void)
1960 {
1961 	bus_for_each_drv(&ap_bus_type, NULL, NULL,
1962 			 __drv_notify_scan_complete);
1963 }
1964 
1965 /*
1966  * Helper function for ap_scan_bus().
1967  * Remove card device and associated queue devices.
1968  */
1969 static inline void ap_scan_rm_card_dev_and_queue_devs(struct ap_card *ac)
1970 {
1971 	bus_for_each_dev(&ap_bus_type, NULL,
1972 			 (void *)(long)ac->id,
1973 			 __ap_queue_devices_with_id_unregister);
1974 	device_unregister(&ac->ap_dev.device);
1975 }
1976 
1977 /*
1978  * Helper function for ap_scan_bus().
1979  * Does the scan bus job for all the domains within
1980  * a valid adapter given by an ap_card ptr.
1981  */
1982 static inline void ap_scan_domains(struct ap_card *ac)
1983 {
1984 	struct ap_tapq_hwinfo hwinfo;
1985 	bool decfg, chkstop;
1986 	struct ap_queue *aq;
1987 	struct device *dev;
1988 	ap_qid_t qid;
1989 	int rc, dom;
1990 
1991 	/*
1992 	 * Go through the configuration for the domains and compare them
1993 	 * to the existing queue devices. Also take care of the config
1994 	 * and error state for the queue devices.
1995 	 */
1996 
1997 	for (dom = 0; dom <= ap_max_domain_id; dom++) {
1998 		qid = AP_MKQID(ac->id, dom);
1999 		dev = bus_find_device(&ap_bus_type, NULL,
2000 				      (void *)(long)qid,
2001 				      __match_queue_device_with_qid);
2002 		aq = dev ? to_ap_queue(dev) : NULL;
2003 		if (!ap_test_config_usage_domain(dom)) {
2004 			if (dev) {
2005 				AP_DBF_INFO("%s(%d,%d) not in config anymore, rm queue dev\n",
2006 					    __func__, ac->id, dom);
2007 				device_unregister(dev);
2008 			}
2009 			goto put_dev_and_continue;
2010 		}
2011 		/* domain is valid, get info from this APQN */
2012 		rc = ap_queue_info(qid, &hwinfo, &decfg, &chkstop);
2013 		switch (rc) {
2014 		case -1:
2015 			if (dev) {
2016 				AP_DBF_INFO("%s(%d,%d) queue_info() failed, rm queue dev\n",
2017 					    __func__, ac->id, dom);
2018 				device_unregister(dev);
2019 			}
2020 			fallthrough;
2021 		case 0:
2022 			goto put_dev_and_continue;
2023 		default:
2024 			break;
2025 		}
2026 		/* if no queue device exists, create a new one */
2027 		if (!aq) {
2028 			aq = ap_queue_create(qid, ac);
2029 			if (!aq) {
2030 				AP_DBF_WARN("%s(%d,%d) ap_queue_create() failed\n",
2031 					    __func__, ac->id, dom);
2032 				continue;
2033 			}
2034 			aq->config = !decfg;
2035 			aq->chkstop = chkstop;
2036 			aq->se_bstate = hwinfo.bs;
2037 			dev = &aq->ap_dev.device;
2038 			dev->bus = &ap_bus_type;
2039 			dev->parent = &ac->ap_dev.device;
2040 			dev_set_name(dev, "%02x.%04x", ac->id, dom);
2041 			/* register queue device */
2042 			rc = device_register(dev);
2043 			if (rc) {
2044 				AP_DBF_WARN("%s(%d,%d) device_register() failed\n",
2045 					    __func__, ac->id, dom);
2046 				goto put_dev_and_continue;
2047 			}
2048 			/* get it and thus adjust reference counter */
2049 			get_device(dev);
2050 			if (decfg) {
2051 				AP_DBF_INFO("%s(%d,%d) new (decfg) queue dev created\n",
2052 					    __func__, ac->id, dom);
2053 			} else if (chkstop) {
2054 				AP_DBF_INFO("%s(%d,%d) new (chkstop) queue dev created\n",
2055 					    __func__, ac->id, dom);
2056 			} else {
2057 				/* nudge the queue's state machine */
2058 				ap_queue_init_state(aq);
2059 				AP_DBF_INFO("%s(%d,%d) new queue dev created\n",
2060 					    __func__, ac->id, dom);
2061 			}
2062 			goto put_dev_and_continue;
2063 		}
2064 		/* handle state changes on already existing queue device */
2065 		spin_lock_bh(&aq->lock);
2066 		/* SE bind state */
2067 		aq->se_bstate = hwinfo.bs;
2068 		/* checkstop state */
2069 		if (chkstop && !aq->chkstop) {
2070 			/* checkstop on */
2071 			aq->chkstop = true;
2072 			if (aq->dev_state > AP_DEV_STATE_UNINITIATED) {
2073 				aq->dev_state = AP_DEV_STATE_ERROR;
2074 				aq->last_err_rc = AP_RESPONSE_CHECKSTOPPED;
2075 			}
2076 			spin_unlock_bh(&aq->lock);
2077 			pr_debug("(%d,%d) queue dev checkstop on\n",
2078 				 ac->id, dom);
2079 			/* 'receive' pending messages with -EAGAIN */
2080 			ap_flush_queue(aq);
2081 			goto put_dev_and_continue;
2082 		} else if (!chkstop && aq->chkstop) {
2083 			/* checkstop off */
2084 			aq->chkstop = false;
2085 			if (aq->dev_state > AP_DEV_STATE_UNINITIATED)
2086 				_ap_queue_init_state(aq);
2087 			spin_unlock_bh(&aq->lock);
2088 			pr_debug("(%d,%d) queue dev checkstop off\n",
2089 				 ac->id, dom);
2090 			goto put_dev_and_continue;
2091 		}
2092 		/* config state change */
2093 		if (decfg && aq->config) {
2094 			/* config off this queue device */
2095 			aq->config = false;
2096 			if (aq->dev_state > AP_DEV_STATE_UNINITIATED) {
2097 				aq->dev_state = AP_DEV_STATE_ERROR;
2098 				aq->last_err_rc = AP_RESPONSE_DECONFIGURED;
2099 			}
2100 			spin_unlock_bh(&aq->lock);
2101 			pr_debug("(%d,%d) queue dev config off\n",
2102 				 ac->id, dom);
2103 			ap_send_config_uevent(&aq->ap_dev, aq->config);
2104 			/* 'receive' pending messages with -EAGAIN */
2105 			ap_flush_queue(aq);
2106 			goto put_dev_and_continue;
2107 		} else if (!decfg && !aq->config) {
2108 			/* config on this queue device */
2109 			aq->config = true;
2110 			if (aq->dev_state > AP_DEV_STATE_UNINITIATED)
2111 				_ap_queue_init_state(aq);
2112 			spin_unlock_bh(&aq->lock);
2113 			pr_debug("(%d,%d) queue dev config on\n",
2114 				 ac->id, dom);
2115 			ap_send_config_uevent(&aq->ap_dev, aq->config);
2116 			goto put_dev_and_continue;
2117 		}
2118 		/* handle other error states */
2119 		if (!decfg && aq->dev_state == AP_DEV_STATE_ERROR) {
2120 			spin_unlock_bh(&aq->lock);
2121 			/* 'receive' pending messages with -EAGAIN */
2122 			ap_flush_queue(aq);
2123 			/* re-init (with reset) the queue device */
2124 			ap_queue_init_state(aq);
2125 			AP_DBF_INFO("%s(%d,%d) queue dev reinit enforced\n",
2126 				    __func__, ac->id, dom);
2127 			goto put_dev_and_continue;
2128 		}
2129 		spin_unlock_bh(&aq->lock);
2130 put_dev_and_continue:
2131 		put_device(dev);
2132 	}
2133 }
2134 
2135 /*
2136  * Helper function for ap_scan_bus().
2137  * Does the scan bus job for the given adapter id.
2138  */
2139 static inline void ap_scan_adapter(int ap)
2140 {
2141 	struct ap_tapq_hwinfo hwinfo;
2142 	int rc, dom, comp_type;
2143 	bool decfg, chkstop;
2144 	struct ap_card *ac;
2145 	struct device *dev;
2146 	ap_qid_t qid;
2147 
2148 	/* Is there currently a card device for this adapter ? */
2149 	dev = bus_find_device(&ap_bus_type, NULL,
2150 			      (void *)(long)ap,
2151 			      __match_card_device_with_id);
2152 	ac = dev ? to_ap_card(dev) : NULL;
2153 
2154 	/* Adapter not in configuration ? */
2155 	if (!ap_test_config_card_id(ap)) {
2156 		if (ac) {
2157 			AP_DBF_INFO("%s(%d) ap not in config any more, rm card and queue devs\n",
2158 				    __func__, ap);
2159 			ap_scan_rm_card_dev_and_queue_devs(ac);
2160 			put_device(dev);
2161 		}
2162 		return;
2163 	}
2164 
2165 	/*
2166 	 * Adapter ap is valid in the current configuration. So do some checks:
2167 	 * If no card device exists, build one. If a card device exists, check
2168 	 * for type and functions changed. For all this we need to find a valid
2169 	 * APQN first.
2170 	 */
2171 
2172 	for (dom = 0; dom <= ap_max_domain_id; dom++)
2173 		if (ap_test_config_usage_domain(dom)) {
2174 			qid = AP_MKQID(ap, dom);
2175 			if (ap_queue_info(qid, &hwinfo, &decfg, &chkstop) > 0)
2176 				break;
2177 		}
2178 	if (dom > ap_max_domain_id) {
2179 		/* Could not find one valid APQN for this adapter */
2180 		if (ac) {
2181 			AP_DBF_INFO("%s(%d) no type info (no APQN found), rm card and queue devs\n",
2182 				    __func__, ap);
2183 			ap_scan_rm_card_dev_and_queue_devs(ac);
2184 			put_device(dev);
2185 		} else {
2186 			pr_debug("(%d) no type info (no APQN found), ignored\n",
2187 				 ap);
2188 		}
2189 		return;
2190 	}
2191 	if (!hwinfo.at) {
2192 		/* No apdater type info available, an unusable adapter */
2193 		if (ac) {
2194 			AP_DBF_INFO("%s(%d) no valid type (0) info, rm card and queue devs\n",
2195 				    __func__, ap);
2196 			ap_scan_rm_card_dev_and_queue_devs(ac);
2197 			put_device(dev);
2198 		} else {
2199 			pr_debug("(%d) no valid type (0) info, ignored\n", ap);
2200 		}
2201 		return;
2202 	}
2203 	hwinfo.value &= TAPQ_CARD_HWINFO_MASK; /* filter card specific hwinfo */
2204 	if (ac) {
2205 		/* Check APQN against existing card device for changes */
2206 		if (ac->hwinfo.at != hwinfo.at) {
2207 			AP_DBF_INFO("%s(%d) hwtype %d changed, rm card and queue devs\n",
2208 				    __func__, ap, hwinfo.at);
2209 			ap_scan_rm_card_dev_and_queue_devs(ac);
2210 			put_device(dev);
2211 			ac = NULL;
2212 		} else if (ac->hwinfo.fac != hwinfo.fac) {
2213 			AP_DBF_INFO("%s(%d) functions 0x%08x changed, rm card and queue devs\n",
2214 				    __func__, ap, hwinfo.fac);
2215 			ap_scan_rm_card_dev_and_queue_devs(ac);
2216 			put_device(dev);
2217 			ac = NULL;
2218 		} else {
2219 			/* handle checkstop state change */
2220 			if (chkstop && !ac->chkstop) {
2221 				/* checkstop on */
2222 				ac->chkstop = true;
2223 				AP_DBF_INFO("%s(%d) card dev checkstop on\n",
2224 					    __func__, ap);
2225 			} else if (!chkstop && ac->chkstop) {
2226 				/* checkstop off */
2227 				ac->chkstop = false;
2228 				AP_DBF_INFO("%s(%d) card dev checkstop off\n",
2229 					    __func__, ap);
2230 			}
2231 			/* handle config state change */
2232 			if (decfg && ac->config) {
2233 				ac->config = false;
2234 				AP_DBF_INFO("%s(%d) card dev config off\n",
2235 					    __func__, ap);
2236 				ap_send_config_uevent(&ac->ap_dev, ac->config);
2237 			} else if (!decfg && !ac->config) {
2238 				ac->config = true;
2239 				AP_DBF_INFO("%s(%d) card dev config on\n",
2240 					    __func__, ap);
2241 				ap_send_config_uevent(&ac->ap_dev, ac->config);
2242 			}
2243 		}
2244 	}
2245 
2246 	if (!ac) {
2247 		/* Build a new card device */
2248 		comp_type = ap_get_compatible_type(qid, hwinfo.at, hwinfo.fac);
2249 		if (!comp_type) {
2250 			AP_DBF_WARN("%s(%d) type %d, can't get compatibility type\n",
2251 				    __func__, ap, hwinfo.at);
2252 			return;
2253 		}
2254 		ac = ap_card_create(ap, hwinfo, comp_type);
2255 		if (!ac) {
2256 			AP_DBF_WARN("%s(%d) ap_card_create() failed\n",
2257 				    __func__, ap);
2258 			return;
2259 		}
2260 		ac->config = !decfg;
2261 		ac->chkstop = chkstop;
2262 		dev = &ac->ap_dev.device;
2263 		dev->bus = &ap_bus_type;
2264 		dev->parent = ap_root_device;
2265 		dev_set_name(dev, "card%02x", ap);
2266 		/* maybe enlarge ap_max_msg_size to support this card */
2267 		if (ac->maxmsgsize > atomic_read(&ap_max_msg_size)) {
2268 			atomic_set(&ap_max_msg_size, ac->maxmsgsize);
2269 			AP_DBF_INFO("%s(%d) ap_max_msg_size update to %d byte\n",
2270 				    __func__, ap,
2271 				    atomic_read(&ap_max_msg_size));
2272 		}
2273 		/* Register the new card device with AP bus */
2274 		rc = device_register(dev);
2275 		if (rc) {
2276 			AP_DBF_WARN("%s(%d) device_register() failed\n",
2277 				    __func__, ap);
2278 			put_device(dev);
2279 			return;
2280 		}
2281 		/* get it and thus adjust reference counter */
2282 		get_device(dev);
2283 		if (decfg)
2284 			AP_DBF_INFO("%s(%d) new (decfg) card dev type=%d func=0x%08x created\n",
2285 				    __func__, ap, hwinfo.at, hwinfo.fac);
2286 		else if (chkstop)
2287 			AP_DBF_INFO("%s(%d) new (chkstop) card dev type=%d func=0x%08x created\n",
2288 				    __func__, ap, hwinfo.at, hwinfo.fac);
2289 		else
2290 			AP_DBF_INFO("%s(%d) new card dev type=%d func=0x%08x created\n",
2291 				    __func__, ap, hwinfo.at, hwinfo.fac);
2292 	}
2293 
2294 	/* Verify the domains and the queue devices for this card */
2295 	ap_scan_domains(ac);
2296 
2297 	/* release the card device */
2298 	put_device(&ac->ap_dev.device);
2299 }
2300 
2301 /**
2302  * ap_get_configuration - get the host AP configuration
2303  *
2304  * Stores the host AP configuration information returned from the previous call
2305  * to Query Configuration Information (QCI), then retrieves and stores the
2306  * current AP configuration returned from QCI.
2307  *
2308  * Return: true if the host AP configuration changed between calls to QCI;
2309  * otherwise, return false.
2310  */
2311 static bool ap_get_configuration(void)
2312 {
2313 	if (!ap_qci_info->flags)	/* QCI not supported */
2314 		return false;
2315 
2316 	memcpy(ap_qci_info_old, ap_qci_info, sizeof(*ap_qci_info));
2317 	ap_qci(ap_qci_info);
2318 
2319 	return memcmp(ap_qci_info, ap_qci_info_old,
2320 		      sizeof(struct ap_config_info)) != 0;
2321 }
2322 
2323 /*
2324  * ap_config_has_new_aps - Check current against old qci info if
2325  * new adapters have appeared. Returns true if at least one new
2326  * adapter in the apm mask is showing up. Existing adapters or
2327  * receding adapters are not counted.
2328  */
2329 static bool ap_config_has_new_aps(void)
2330 {
2331 
2332 	unsigned long m[BITS_TO_LONGS(AP_DEVICES)];
2333 
2334 	if (!ap_qci_info->flags)
2335 		return false;
2336 
2337 	bitmap_andnot(m, (unsigned long *)ap_qci_info->apm,
2338 		      (unsigned long *)ap_qci_info_old->apm, AP_DEVICES);
2339 	if (!bitmap_empty(m, AP_DEVICES))
2340 		return true;
2341 
2342 	return false;
2343 }
2344 
2345 /*
2346  * ap_config_has_new_doms - Check current against old qci info if
2347  * new (usage) domains have appeared. Returns true if at least one
2348  * new domain in the aqm mask is showing up. Existing domains or
2349  * receding domains are not counted.
2350  */
2351 static bool ap_config_has_new_doms(void)
2352 {
2353 	unsigned long m[BITS_TO_LONGS(AP_DOMAINS)];
2354 
2355 	if (!ap_qci_info->flags)
2356 		return false;
2357 
2358 	bitmap_andnot(m, (unsigned long *)ap_qci_info->aqm,
2359 		      (unsigned long *)ap_qci_info_old->aqm, AP_DOMAINS);
2360 	if (!bitmap_empty(m, AP_DOMAINS))
2361 		return true;
2362 
2363 	return false;
2364 }
2365 
2366 /**
2367  * ap_scan_bus(): Scan the AP bus for new devices
2368  * Always run under mutex ap_scan_bus_mutex protection
2369  * which needs to get locked/unlocked by the caller!
2370  * Returns true if any config change has been detected
2371  * during the scan, otherwise false.
2372  */
2373 static bool ap_scan_bus(void)
2374 {
2375 	bool config_changed;
2376 	int ap;
2377 
2378 	pr_debug(">\n");
2379 
2380 	/* (re-)fetch configuration via QCI */
2381 	config_changed = ap_get_configuration();
2382 	if (config_changed) {
2383 		if (ap_config_has_new_aps() || ap_config_has_new_doms()) {
2384 			/*
2385 			 * Appearance of new adapters and/or domains need to
2386 			 * build new ap devices which need to get bound to an
2387 			 * device driver. Thus reset the APQN bindings complete
2388 			 * completion.
2389 			 */
2390 			reinit_completion(&ap_apqn_bindings_complete);
2391 		}
2392 		/* post a config change notify */
2393 		notify_config_changed();
2394 	}
2395 	ap_select_domain();
2396 
2397 	/* loop over all possible adapters */
2398 	for (ap = 0; ap <= ap_max_adapter_id; ap++)
2399 		ap_scan_adapter(ap);
2400 
2401 	/* scan complete notify */
2402 	if (config_changed)
2403 		notify_scan_complete();
2404 
2405 	/* check if there is at least one queue available with default domain */
2406 	if (ap_domain_index >= 0) {
2407 		struct device *dev =
2408 			bus_find_device(&ap_bus_type, NULL,
2409 					(void *)(long)ap_domain_index,
2410 					__match_queue_device_with_queue_id);
2411 		if (dev)
2412 			put_device(dev);
2413 		else
2414 			AP_DBF_INFO("%s no queue device with default domain %d available\n",
2415 				    __func__, ap_domain_index);
2416 	}
2417 
2418 	if (atomic64_inc_return(&ap_scan_bus_count) == 1) {
2419 		pr_debug("init scan complete\n");
2420 		ap_send_init_scan_done_uevent();
2421 	}
2422 
2423 	ap_check_bindings_complete();
2424 
2425 	mod_timer(&ap_scan_bus_timer, jiffies + ap_scan_bus_time * HZ);
2426 
2427 	pr_debug("< config_changed=%d\n", config_changed);
2428 
2429 	return config_changed;
2430 }
2431 
2432 /*
2433  * Callback for the ap_scan_bus_timer
2434  * Runs periodically, workqueue timer (ap_scan_bus_time)
2435  */
2436 static void ap_scan_bus_timer_callback(struct timer_list *unused)
2437 {
2438 	/*
2439 	 * schedule work into the system long wq which when
2440 	 * the work is finally executed, calls the AP bus scan.
2441 	 */
2442 	queue_work(system_long_wq, &ap_scan_bus_work);
2443 }
2444 
2445 /*
2446  * Callback for the ap_scan_bus_work
2447  */
2448 static void ap_scan_bus_wq_callback(struct work_struct *unused)
2449 {
2450 	/*
2451 	 * Try to invoke an ap_scan_bus(). If the mutex acquisition
2452 	 * fails there is currently another task already running the
2453 	 * AP scan bus and there is no need to wait and re-trigger the
2454 	 * scan again. Please note at the end of the scan bus function
2455 	 * the AP scan bus timer is re-armed which triggers then the
2456 	 * ap_scan_bus_timer_callback which enqueues a work into the
2457 	 * system_long_wq which invokes this function here again.
2458 	 */
2459 	if (mutex_trylock(&ap_scan_bus_mutex)) {
2460 		ap_scan_bus_task = current;
2461 		ap_scan_bus_result = ap_scan_bus();
2462 		ap_scan_bus_task = NULL;
2463 		mutex_unlock(&ap_scan_bus_mutex);
2464 	}
2465 }
2466 
2467 static inline void __exit ap_async_exit(void)
2468 {
2469 	if (ap_thread_flag)
2470 		ap_poll_thread_stop();
2471 	chsc_notifier_unregister(&ap_bus_nb);
2472 	cancel_work(&ap_scan_bus_work);
2473 	hrtimer_cancel(&ap_poll_timer);
2474 	timer_delete(&ap_scan_bus_timer);
2475 }
2476 
2477 static inline int __init ap_async_init(void)
2478 {
2479 	int rc;
2480 
2481 	/* Setup the AP bus rescan timer. */
2482 	timer_setup(&ap_scan_bus_timer, ap_scan_bus_timer_callback, 0);
2483 
2484 	/*
2485 	 * Setup the high resolution poll timer.
2486 	 * If we are running under z/VM adjust polling to z/VM polling rate.
2487 	 */
2488 	if (machine_is_vm())
2489 		poll_high_timeout = 1500000;
2490 	hrtimer_setup(&ap_poll_timer, ap_poll_timeout, CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
2491 
2492 	queue_work(system_long_wq, &ap_scan_bus_work);
2493 
2494 	rc = chsc_notifier_register(&ap_bus_nb);
2495 	if (rc)
2496 		goto out;
2497 
2498 	/* Start the low priority AP bus poll thread. */
2499 	if (!ap_thread_flag)
2500 		return 0;
2501 
2502 	rc = ap_poll_thread_start();
2503 	if (rc)
2504 		goto out_notifier;
2505 
2506 	return 0;
2507 
2508 out_notifier:
2509 	chsc_notifier_unregister(&ap_bus_nb);
2510 out:
2511 	cancel_work(&ap_scan_bus_work);
2512 	hrtimer_cancel(&ap_poll_timer);
2513 	timer_delete(&ap_scan_bus_timer);
2514 	return rc;
2515 }
2516 
2517 static inline void ap_irq_exit(void)
2518 {
2519 	if (ap_irq_flag)
2520 		unregister_adapter_interrupt(&ap_airq);
2521 }
2522 
2523 static inline int __init ap_irq_init(void)
2524 {
2525 	int rc;
2526 
2527 	if (!ap_interrupts_available() || !ap_useirq)
2528 		return 0;
2529 
2530 	rc = register_adapter_interrupt(&ap_airq);
2531 	ap_irq_flag = (rc == 0);
2532 
2533 	return rc;
2534 }
2535 
2536 static inline void ap_debug_exit(void)
2537 {
2538 	debug_unregister(ap_dbf_info);
2539 }
2540 
2541 static inline int __init ap_debug_init(void)
2542 {
2543 	ap_dbf_info = debug_register("ap", 2, 1,
2544 				     AP_DBF_MAX_SPRINTF_ARGS * sizeof(long));
2545 	debug_register_view(ap_dbf_info, &debug_sprintf_view);
2546 	debug_set_level(ap_dbf_info, DBF_ERR);
2547 
2548 	return 0;
2549 }
2550 
2551 static void __init ap_perms_init(void)
2552 {
2553 	/* all resources usable if no kernel parameter string given */
2554 	memset(&ap_perms.ioctlm, 0xFF, sizeof(ap_perms.ioctlm));
2555 	memset(&ap_perms.apm, 0xFF, sizeof(ap_perms.apm));
2556 	memset(&ap_perms.aqm, 0xFF, sizeof(ap_perms.aqm));
2557 
2558 	/* apm kernel parameter string */
2559 	if (apm_str) {
2560 		memset(&ap_perms.apm, 0, sizeof(ap_perms.apm));
2561 		ap_parse_mask_str(apm_str, ap_perms.apm, AP_DEVICES,
2562 				  &ap_attr_mutex);
2563 	}
2564 
2565 	/* aqm kernel parameter string */
2566 	if (aqm_str) {
2567 		memset(&ap_perms.aqm, 0, sizeof(ap_perms.aqm));
2568 		ap_parse_mask_str(aqm_str, ap_perms.aqm, AP_DOMAINS,
2569 				  &ap_attr_mutex);
2570 	}
2571 }
2572 
2573 /**
2574  * ap_module_init(): The module initialization code.
2575  *
2576  * Initializes the module.
2577  */
2578 static int __init ap_module_init(void)
2579 {
2580 	int rc;
2581 
2582 	if (!ap_instructions_available()) {
2583 		pr_warn("The hardware system does not support AP instructions\n");
2584 		return -ENODEV;
2585 	}
2586 
2587 	rc = ap_debug_init();
2588 	if (rc)
2589 		return rc;
2590 
2591 	/* init ap_queue hashtable */
2592 	hash_init(ap_queues);
2593 
2594 	/* create ap msg buffer memory pool */
2595 	ap_msg_pool = mempool_create_kmalloc_pool(ap_msg_pool_min_items,
2596 						  AP_DEFAULT_MAX_MSG_SIZE);
2597 	if (!ap_msg_pool) {
2598 		rc = -ENOMEM;
2599 		goto out;
2600 	}
2601 
2602 	/* set up the AP permissions (ioctls, ap and aq masks) */
2603 	ap_perms_init();
2604 
2605 	/* Get AP configuration data if available */
2606 	ap_init_qci_info();
2607 
2608 	/* check default domain setting */
2609 	if (ap_domain_index < -1 || ap_domain_index > ap_max_domain_id ||
2610 	    (ap_domain_index >= 0 &&
2611 	     !test_bit_inv(ap_domain_index, ap_perms.aqm))) {
2612 		pr_warn("%d is not a valid cryptographic domain\n",
2613 			ap_domain_index);
2614 		ap_domain_index = -1;
2615 	}
2616 
2617 	/* Create /sys/bus/ap. */
2618 	rc = bus_register(&ap_bus_type);
2619 	if (rc)
2620 		goto out;
2621 
2622 	/* Create /sys/devices/ap. */
2623 	ap_root_device = root_device_register("ap");
2624 	rc = PTR_ERR_OR_ZERO(ap_root_device);
2625 	if (rc)
2626 		goto out_bus;
2627 	ap_root_device->bus = &ap_bus_type;
2628 
2629 	/* enable interrupts if available */
2630 	rc = ap_irq_init();
2631 	if (rc)
2632 		goto out_device;
2633 
2634 	/* Setup asynchronous work (timers, workqueue, etc). */
2635 	rc = ap_async_init();
2636 	if (rc)
2637 		goto out_irq;
2638 
2639 	return 0;
2640 
2641 out_irq:
2642 	ap_irq_exit();
2643 out_device:
2644 	root_device_unregister(ap_root_device);
2645 out_bus:
2646 	bus_unregister(&ap_bus_type);
2647 out:
2648 	mempool_destroy(ap_msg_pool);
2649 	ap_debug_exit();
2650 	return rc;
2651 }
2652 
2653 static void __exit ap_module_exit(void)
2654 {
2655 	ap_async_exit();
2656 	ap_irq_exit();
2657 	root_device_unregister(ap_root_device);
2658 	bus_unregister(&ap_bus_type);
2659 	mempool_destroy(ap_msg_pool);
2660 	ap_debug_exit();
2661 }
2662 
2663 module_init(ap_module_init);
2664 module_exit(ap_module_exit);
2665