xref: /openbmc/linux/drivers/s390/crypto/ap_bus.c (revision 11a163f2)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright IBM Corp. 2006, 2012
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  *
10  * Adjunct processor bus.
11  */
12 
13 #define KMSG_COMPONENT "ap"
14 #define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
15 
16 #include <linux/kernel_stat.h>
17 #include <linux/moduleparam.h>
18 #include <linux/init.h>
19 #include <linux/delay.h>
20 #include <linux/err.h>
21 #include <linux/freezer.h>
22 #include <linux/interrupt.h>
23 #include <linux/workqueue.h>
24 #include <linux/slab.h>
25 #include <linux/notifier.h>
26 #include <linux/kthread.h>
27 #include <linux/mutex.h>
28 #include <asm/airq.h>
29 #include <linux/atomic.h>
30 #include <asm/isc.h>
31 #include <linux/hrtimer.h>
32 #include <linux/ktime.h>
33 #include <asm/facility.h>
34 #include <linux/crypto.h>
35 #include <linux/mod_devicetable.h>
36 #include <linux/debugfs.h>
37 #include <linux/ctype.h>
38 
39 #include "ap_bus.h"
40 #include "ap_debug.h"
41 
42 /*
43  * Module parameters; note though this file itself isn't modular.
44  */
45 int ap_domain_index = -1;	/* Adjunct Processor Domain Index */
46 static DEFINE_SPINLOCK(ap_domain_lock);
47 module_param_named(domain, ap_domain_index, int, 0440);
48 MODULE_PARM_DESC(domain, "domain index for ap devices");
49 EXPORT_SYMBOL(ap_domain_index);
50 
51 static int ap_thread_flag;
52 module_param_named(poll_thread, ap_thread_flag, int, 0440);
53 MODULE_PARM_DESC(poll_thread, "Turn on/off poll thread, default is 0 (off).");
54 
55 static char *apm_str;
56 module_param_named(apmask, apm_str, charp, 0440);
57 MODULE_PARM_DESC(apmask, "AP bus adapter mask.");
58 
59 static char *aqm_str;
60 module_param_named(aqmask, aqm_str, charp, 0440);
61 MODULE_PARM_DESC(aqmask, "AP bus domain mask.");
62 
63 static struct device *ap_root_device;
64 
65 /* Hashtable of all queue devices on the AP bus */
66 DEFINE_HASHTABLE(ap_queues, 8);
67 /* lock used for the ap_queues hashtable */
68 DEFINE_SPINLOCK(ap_queues_lock);
69 
70 /* Default permissions (ioctl, card and domain masking) */
71 struct ap_perms ap_perms;
72 EXPORT_SYMBOL(ap_perms);
73 DEFINE_MUTEX(ap_perms_mutex);
74 EXPORT_SYMBOL(ap_perms_mutex);
75 
76 static struct ap_config_info *ap_qci_info;
77 
78 /*
79  * AP bus related debug feature things.
80  */
81 debug_info_t *ap_dbf_info;
82 
83 /*
84  * Workqueue timer for bus rescan.
85  */
86 static struct timer_list ap_config_timer;
87 static int ap_config_time = AP_CONFIG_TIME;
88 static void ap_scan_bus(struct work_struct *);
89 static DECLARE_WORK(ap_scan_work, ap_scan_bus);
90 
91 /*
92  * Tasklet & timer for AP request polling and interrupts
93  */
94 static void ap_tasklet_fn(unsigned long);
95 static DECLARE_TASKLET_OLD(ap_tasklet, ap_tasklet_fn);
96 static DECLARE_WAIT_QUEUE_HEAD(ap_poll_wait);
97 static struct task_struct *ap_poll_kthread;
98 static DEFINE_MUTEX(ap_poll_thread_mutex);
99 static DEFINE_SPINLOCK(ap_poll_timer_lock);
100 static struct hrtimer ap_poll_timer;
101 /*
102  * In LPAR poll with 4kHz frequency. Poll every 250000 nanoseconds.
103  * If z/VM change to 1500000 nanoseconds to adjust to z/VM polling.
104  */
105 static unsigned long long poll_timeout = 250000;
106 
107 /* Maximum domain id, if not given via qci */
108 static int ap_max_domain_id = 15;
109 /* Maximum adapter id, if not given via qci */
110 static int ap_max_adapter_id = 63;
111 
112 static struct bus_type ap_bus_type;
113 
114 /* Adapter interrupt definitions */
115 static void ap_interrupt_handler(struct airq_struct *airq, bool floating);
116 
117 static int ap_airq_flag;
118 
119 static struct airq_struct ap_airq = {
120 	.handler = ap_interrupt_handler,
121 	.isc = AP_ISC,
122 };
123 
124 /**
125  * ap_using_interrupts() - Returns non-zero if interrupt support is
126  * available.
127  */
128 static inline int ap_using_interrupts(void)
129 {
130 	return ap_airq_flag;
131 }
132 
133 /**
134  * ap_airq_ptr() - Get the address of the adapter interrupt indicator
135  *
136  * Returns the address of the local-summary-indicator of the adapter
137  * interrupt handler for AP, or NULL if adapter interrupts are not
138  * available.
139  */
140 void *ap_airq_ptr(void)
141 {
142 	if (ap_using_interrupts())
143 		return ap_airq.lsi_ptr;
144 	return NULL;
145 }
146 
147 /**
148  * ap_interrupts_available(): Test if AP interrupts are available.
149  *
150  * Returns 1 if AP interrupts are available.
151  */
152 static int ap_interrupts_available(void)
153 {
154 	return test_facility(65);
155 }
156 
157 /**
158  * ap_qci_available(): Test if AP configuration
159  * information can be queried via QCI subfunction.
160  *
161  * Returns 1 if subfunction PQAP(QCI) is available.
162  */
163 static int ap_qci_available(void)
164 {
165 	return test_facility(12);
166 }
167 
168 /**
169  * ap_apft_available(): Test if AP facilities test (APFT)
170  * facility is available.
171  *
172  * Returns 1 if APFT is is available.
173  */
174 static int ap_apft_available(void)
175 {
176 	return test_facility(15);
177 }
178 
179 /*
180  * ap_qact_available(): Test if the PQAP(QACT) subfunction is available.
181  *
182  * Returns 1 if the QACT subfunction is available.
183  */
184 static inline int ap_qact_available(void)
185 {
186 	if (ap_qci_info)
187 		return ap_qci_info->qact;
188 	return 0;
189 }
190 
191 /*
192  * ap_fetch_qci_info(): Fetch cryptographic config info
193  *
194  * Returns the ap configuration info fetched via PQAP(QCI).
195  * On success 0 is returned, on failure a negative errno
196  * is returned, e.g. if the PQAP(QCI) instruction is not
197  * available, the return value will be -EOPNOTSUPP.
198  */
199 static inline int ap_fetch_qci_info(struct ap_config_info *info)
200 {
201 	if (!ap_qci_available())
202 		return -EOPNOTSUPP;
203 	if (!info)
204 		return -EINVAL;
205 	return ap_qci(info);
206 }
207 
208 /**
209  * ap_init_qci_info(): Allocate and query qci config info.
210  * Does also update the static variables ap_max_domain_id
211  * and ap_max_adapter_id if this info is available.
212 
213  */
214 static void __init ap_init_qci_info(void)
215 {
216 	if (!ap_qci_available()) {
217 		AP_DBF_INFO("%s QCI not supported\n", __func__);
218 		return;
219 	}
220 
221 	ap_qci_info = kzalloc(sizeof(*ap_qci_info), GFP_KERNEL);
222 	if (!ap_qci_info)
223 		return;
224 	if (ap_fetch_qci_info(ap_qci_info) != 0) {
225 		kfree(ap_qci_info);
226 		ap_qci_info = NULL;
227 		return;
228 	}
229 	AP_DBF_INFO("%s successful fetched initial qci info\n", __func__);
230 
231 	if (ap_qci_info->apxa) {
232 		if (ap_qci_info->Na) {
233 			ap_max_adapter_id = ap_qci_info->Na;
234 			AP_DBF_INFO("%s new ap_max_adapter_id is %d\n",
235 				    __func__, ap_max_adapter_id);
236 		}
237 		if (ap_qci_info->Nd) {
238 			ap_max_domain_id = ap_qci_info->Nd;
239 			AP_DBF_INFO("%s new ap_max_domain_id is %d\n",
240 				    __func__, ap_max_domain_id);
241 		}
242 	}
243 }
244 
245 /*
246  * ap_test_config(): helper function to extract the nrth bit
247  *		     within the unsigned int array field.
248  */
249 static inline int ap_test_config(unsigned int *field, unsigned int nr)
250 {
251 	return ap_test_bit((field + (nr >> 5)), (nr & 0x1f));
252 }
253 
254 /*
255  * ap_test_config_card_id(): Test, whether an AP card ID is configured.
256  *
257  * Returns 0 if the card is not configured
258  *	   1 if the card is configured or
259  *	     if the configuration information is not available
260  */
261 static inline int ap_test_config_card_id(unsigned int id)
262 {
263 	if (id > ap_max_adapter_id)
264 		return 0;
265 	if (ap_qci_info)
266 		return ap_test_config(ap_qci_info->apm, id);
267 	return 1;
268 }
269 
270 /*
271  * ap_test_config_usage_domain(): Test, whether an AP usage domain
272  * is configured.
273  *
274  * Returns 0 if the usage domain is not configured
275  *	   1 if the usage domain is configured or
276  *	     if the configuration information is not available
277  */
278 int ap_test_config_usage_domain(unsigned int domain)
279 {
280 	if (domain > ap_max_domain_id)
281 		return 0;
282 	if (ap_qci_info)
283 		return ap_test_config(ap_qci_info->aqm, domain);
284 	return 1;
285 }
286 EXPORT_SYMBOL(ap_test_config_usage_domain);
287 
288 /*
289  * ap_test_config_ctrl_domain(): Test, whether an AP control domain
290  * is configured.
291  * @domain AP control domain ID
292  *
293  * Returns 1 if the control domain is configured
294  *	   0 in all other cases
295  */
296 int ap_test_config_ctrl_domain(unsigned int domain)
297 {
298 	if (!ap_qci_info || domain > ap_max_domain_id)
299 		return 0;
300 	return ap_test_config(ap_qci_info->adm, domain);
301 }
302 EXPORT_SYMBOL(ap_test_config_ctrl_domain);
303 
304 /*
305  * ap_queue_info(): Check and get AP queue info.
306  * Returns true if TAPQ succeeded and the info is filled or
307  * false otherwise.
308  */
309 static bool ap_queue_info(ap_qid_t qid, int *q_type,
310 			  unsigned int *q_fac, int *q_depth, bool *q_decfg)
311 {
312 	struct ap_queue_status status;
313 	unsigned long info = 0;
314 
315 	/* make sure we don't run into a specifiation exception */
316 	if (AP_QID_CARD(qid) > ap_max_adapter_id ||
317 	    AP_QID_QUEUE(qid) > ap_max_domain_id)
318 		return false;
319 
320 	/* call TAPQ on this APQN */
321 	status = ap_test_queue(qid, ap_apft_available(), &info);
322 	switch (status.response_code) {
323 	case AP_RESPONSE_NORMAL:
324 	case AP_RESPONSE_RESET_IN_PROGRESS:
325 	case AP_RESPONSE_DECONFIGURED:
326 	case AP_RESPONSE_CHECKSTOPPED:
327 	case AP_RESPONSE_BUSY:
328 		/*
329 		 * According to the architecture in all these cases the
330 		 * info should be filled. All bits 0 is not possible as
331 		 * there is at least one of the mode bits set.
332 		 */
333 		if (WARN_ON_ONCE(!info))
334 			return false;
335 		*q_type = (int)((info >> 24) & 0xff);
336 		*q_fac = (unsigned int)(info >> 32);
337 		*q_depth = (int)(info & 0xff);
338 		*q_decfg = status.response_code == AP_RESPONSE_DECONFIGURED;
339 		switch (*q_type) {
340 			/* For CEX2 and CEX3 the available functions
341 			 * are not reflected by the facilities bits.
342 			 * Instead it is coded into the type. So here
343 			 * modify the function bits based on the type.
344 			 */
345 		case AP_DEVICE_TYPE_CEX2A:
346 		case AP_DEVICE_TYPE_CEX3A:
347 			*q_fac |= 0x08000000;
348 			break;
349 		case AP_DEVICE_TYPE_CEX2C:
350 		case AP_DEVICE_TYPE_CEX3C:
351 			*q_fac |= 0x10000000;
352 			break;
353 		default:
354 			break;
355 		}
356 		return true;
357 	default:
358 		/*
359 		 * A response code which indicates, there is no info available.
360 		 */
361 		return false;
362 	}
363 }
364 
365 void ap_wait(enum ap_sm_wait wait)
366 {
367 	ktime_t hr_time;
368 
369 	switch (wait) {
370 	case AP_SM_WAIT_AGAIN:
371 	case AP_SM_WAIT_INTERRUPT:
372 		if (ap_using_interrupts())
373 			break;
374 		if (ap_poll_kthread) {
375 			wake_up(&ap_poll_wait);
376 			break;
377 		}
378 		fallthrough;
379 	case AP_SM_WAIT_TIMEOUT:
380 		spin_lock_bh(&ap_poll_timer_lock);
381 		if (!hrtimer_is_queued(&ap_poll_timer)) {
382 			hr_time = poll_timeout;
383 			hrtimer_forward_now(&ap_poll_timer, hr_time);
384 			hrtimer_restart(&ap_poll_timer);
385 		}
386 		spin_unlock_bh(&ap_poll_timer_lock);
387 		break;
388 	case AP_SM_WAIT_NONE:
389 	default:
390 		break;
391 	}
392 }
393 
394 /**
395  * ap_request_timeout(): Handling of request timeouts
396  * @t: timer making this callback
397  *
398  * Handles request timeouts.
399  */
400 void ap_request_timeout(struct timer_list *t)
401 {
402 	struct ap_queue *aq = from_timer(aq, t, timeout);
403 
404 	spin_lock_bh(&aq->lock);
405 	ap_wait(ap_sm_event(aq, AP_SM_EVENT_TIMEOUT));
406 	spin_unlock_bh(&aq->lock);
407 }
408 
409 /**
410  * ap_poll_timeout(): AP receive polling for finished AP requests.
411  * @unused: Unused pointer.
412  *
413  * Schedules the AP tasklet using a high resolution timer.
414  */
415 static enum hrtimer_restart ap_poll_timeout(struct hrtimer *unused)
416 {
417 	tasklet_schedule(&ap_tasklet);
418 	return HRTIMER_NORESTART;
419 }
420 
421 /**
422  * ap_interrupt_handler() - Schedule ap_tasklet on interrupt
423  * @airq: pointer to adapter interrupt descriptor
424  */
425 static void ap_interrupt_handler(struct airq_struct *airq, bool floating)
426 {
427 	inc_irq_stat(IRQIO_APB);
428 	tasklet_schedule(&ap_tasklet);
429 }
430 
431 /**
432  * ap_tasklet_fn(): Tasklet to poll all AP devices.
433  * @dummy: Unused variable
434  *
435  * Poll all AP devices on the bus.
436  */
437 static void ap_tasklet_fn(unsigned long dummy)
438 {
439 	int bkt;
440 	struct ap_queue *aq;
441 	enum ap_sm_wait wait = AP_SM_WAIT_NONE;
442 
443 	/* Reset the indicator if interrupts are used. Thus new interrupts can
444 	 * be received. Doing it in the beginning of the tasklet is therefor
445 	 * important that no requests on any AP get lost.
446 	 */
447 	if (ap_using_interrupts())
448 		xchg(ap_airq.lsi_ptr, 0);
449 
450 	spin_lock_bh(&ap_queues_lock);
451 	hash_for_each(ap_queues, bkt, aq, hnode) {
452 		spin_lock_bh(&aq->lock);
453 		wait = min(wait, ap_sm_event_loop(aq, AP_SM_EVENT_POLL));
454 		spin_unlock_bh(&aq->lock);
455 	}
456 	spin_unlock_bh(&ap_queues_lock);
457 
458 	ap_wait(wait);
459 }
460 
461 static int ap_pending_requests(void)
462 {
463 	int bkt;
464 	struct ap_queue *aq;
465 
466 	spin_lock_bh(&ap_queues_lock);
467 	hash_for_each(ap_queues, bkt, aq, hnode) {
468 		if (aq->queue_count == 0)
469 			continue;
470 		spin_unlock_bh(&ap_queues_lock);
471 		return 1;
472 	}
473 	spin_unlock_bh(&ap_queues_lock);
474 	return 0;
475 }
476 
477 /**
478  * ap_poll_thread(): Thread that polls for finished requests.
479  * @data: Unused pointer
480  *
481  * AP bus poll thread. The purpose of this thread is to poll for
482  * finished requests in a loop if there is a "free" cpu - that is
483  * a cpu that doesn't have anything better to do. The polling stops
484  * as soon as there is another task or if all messages have been
485  * delivered.
486  */
487 static int ap_poll_thread(void *data)
488 {
489 	DECLARE_WAITQUEUE(wait, current);
490 
491 	set_user_nice(current, MAX_NICE);
492 	set_freezable();
493 	while (!kthread_should_stop()) {
494 		add_wait_queue(&ap_poll_wait, &wait);
495 		set_current_state(TASK_INTERRUPTIBLE);
496 		if (!ap_pending_requests()) {
497 			schedule();
498 			try_to_freeze();
499 		}
500 		set_current_state(TASK_RUNNING);
501 		remove_wait_queue(&ap_poll_wait, &wait);
502 		if (need_resched()) {
503 			schedule();
504 			try_to_freeze();
505 			continue;
506 		}
507 		ap_tasklet_fn(0);
508 	}
509 
510 	return 0;
511 }
512 
513 static int ap_poll_thread_start(void)
514 {
515 	int rc;
516 
517 	if (ap_using_interrupts() || ap_poll_kthread)
518 		return 0;
519 	mutex_lock(&ap_poll_thread_mutex);
520 	ap_poll_kthread = kthread_run(ap_poll_thread, NULL, "appoll");
521 	rc = PTR_ERR_OR_ZERO(ap_poll_kthread);
522 	if (rc)
523 		ap_poll_kthread = NULL;
524 	mutex_unlock(&ap_poll_thread_mutex);
525 	return rc;
526 }
527 
528 static void ap_poll_thread_stop(void)
529 {
530 	if (!ap_poll_kthread)
531 		return;
532 	mutex_lock(&ap_poll_thread_mutex);
533 	kthread_stop(ap_poll_kthread);
534 	ap_poll_kthread = NULL;
535 	mutex_unlock(&ap_poll_thread_mutex);
536 }
537 
538 #define is_card_dev(x) ((x)->parent == ap_root_device)
539 #define is_queue_dev(x) ((x)->parent != ap_root_device)
540 
541 /**
542  * ap_bus_match()
543  * @dev: Pointer to device
544  * @drv: Pointer to device_driver
545  *
546  * AP bus driver registration/unregistration.
547  */
548 static int ap_bus_match(struct device *dev, struct device_driver *drv)
549 {
550 	struct ap_driver *ap_drv = to_ap_drv(drv);
551 	struct ap_device_id *id;
552 
553 	/*
554 	 * Compare device type of the device with the list of
555 	 * supported types of the device_driver.
556 	 */
557 	for (id = ap_drv->ids; id->match_flags; id++) {
558 		if (is_card_dev(dev) &&
559 		    id->match_flags & AP_DEVICE_ID_MATCH_CARD_TYPE &&
560 		    id->dev_type == to_ap_dev(dev)->device_type)
561 			return 1;
562 		if (is_queue_dev(dev) &&
563 		    id->match_flags & AP_DEVICE_ID_MATCH_QUEUE_TYPE &&
564 		    id->dev_type == to_ap_dev(dev)->device_type)
565 			return 1;
566 	}
567 	return 0;
568 }
569 
570 /**
571  * ap_uevent(): Uevent function for AP devices.
572  * @dev: Pointer to device
573  * @env: Pointer to kobj_uevent_env
574  *
575  * It sets up a single environment variable DEV_TYPE which contains the
576  * hardware device type.
577  */
578 static int ap_uevent(struct device *dev, struct kobj_uevent_env *env)
579 {
580 	struct ap_device *ap_dev = to_ap_dev(dev);
581 	int retval = 0;
582 
583 	if (!ap_dev)
584 		return -ENODEV;
585 
586 	/* Set up DEV_TYPE environment variable. */
587 	retval = add_uevent_var(env, "DEV_TYPE=%04X", ap_dev->device_type);
588 	if (retval)
589 		return retval;
590 
591 	/* Add MODALIAS= */
592 	retval = add_uevent_var(env, "MODALIAS=ap:t%02X", ap_dev->device_type);
593 
594 	return retval;
595 }
596 
597 static int __ap_queue_devices_with_id_unregister(struct device *dev, void *data)
598 {
599 	if (is_queue_dev(dev) &&
600 	    AP_QID_CARD(to_ap_queue(dev)->qid) == (int)(long) data)
601 		device_unregister(dev);
602 	return 0;
603 }
604 
605 static struct bus_type ap_bus_type = {
606 	.name = "ap",
607 	.match = &ap_bus_match,
608 	.uevent = &ap_uevent,
609 };
610 
611 static int __ap_revise_reserved(struct device *dev, void *dummy)
612 {
613 	int rc, card, queue, devres, drvres;
614 
615 	if (is_queue_dev(dev)) {
616 		card = AP_QID_CARD(to_ap_queue(dev)->qid);
617 		queue = AP_QID_QUEUE(to_ap_queue(dev)->qid);
618 		mutex_lock(&ap_perms_mutex);
619 		devres = test_bit_inv(card, ap_perms.apm)
620 			&& test_bit_inv(queue, ap_perms.aqm);
621 		mutex_unlock(&ap_perms_mutex);
622 		drvres = to_ap_drv(dev->driver)->flags
623 			& AP_DRIVER_FLAG_DEFAULT;
624 		if (!!devres != !!drvres) {
625 			AP_DBF_DBG("reprobing queue=%02x.%04x\n",
626 				   card, queue);
627 			rc = device_reprobe(dev);
628 		}
629 	}
630 
631 	return 0;
632 }
633 
634 static void ap_bus_revise_bindings(void)
635 {
636 	bus_for_each_dev(&ap_bus_type, NULL, NULL, __ap_revise_reserved);
637 }
638 
639 int ap_owned_by_def_drv(int card, int queue)
640 {
641 	int rc = 0;
642 
643 	if (card < 0 || card >= AP_DEVICES || queue < 0 || queue >= AP_DOMAINS)
644 		return -EINVAL;
645 
646 	mutex_lock(&ap_perms_mutex);
647 
648 	if (test_bit_inv(card, ap_perms.apm)
649 	    && test_bit_inv(queue, ap_perms.aqm))
650 		rc = 1;
651 
652 	mutex_unlock(&ap_perms_mutex);
653 
654 	return rc;
655 }
656 EXPORT_SYMBOL(ap_owned_by_def_drv);
657 
658 int ap_apqn_in_matrix_owned_by_def_drv(unsigned long *apm,
659 				       unsigned long *aqm)
660 {
661 	int card, queue, rc = 0;
662 
663 	mutex_lock(&ap_perms_mutex);
664 
665 	for (card = 0; !rc && card < AP_DEVICES; card++)
666 		if (test_bit_inv(card, apm) &&
667 		    test_bit_inv(card, ap_perms.apm))
668 			for (queue = 0; !rc && queue < AP_DOMAINS; queue++)
669 				if (test_bit_inv(queue, aqm) &&
670 				    test_bit_inv(queue, ap_perms.aqm))
671 					rc = 1;
672 
673 	mutex_unlock(&ap_perms_mutex);
674 
675 	return rc;
676 }
677 EXPORT_SYMBOL(ap_apqn_in_matrix_owned_by_def_drv);
678 
679 static int ap_device_probe(struct device *dev)
680 {
681 	struct ap_device *ap_dev = to_ap_dev(dev);
682 	struct ap_driver *ap_drv = to_ap_drv(dev->driver);
683 	int card, queue, devres, drvres, rc;
684 
685 	if (is_queue_dev(dev)) {
686 		/*
687 		 * If the apqn is marked as reserved/used by ap bus and
688 		 * default drivers, only probe with drivers with the default
689 		 * flag set. If it is not marked, only probe with drivers
690 		 * with the default flag not set.
691 		 */
692 		card = AP_QID_CARD(to_ap_queue(dev)->qid);
693 		queue = AP_QID_QUEUE(to_ap_queue(dev)->qid);
694 		mutex_lock(&ap_perms_mutex);
695 		devres = test_bit_inv(card, ap_perms.apm)
696 			&& test_bit_inv(queue, ap_perms.aqm);
697 		mutex_unlock(&ap_perms_mutex);
698 		drvres = ap_drv->flags & AP_DRIVER_FLAG_DEFAULT;
699 		if (!!devres != !!drvres)
700 			return -ENODEV;
701 	}
702 
703 	/* Add queue/card to list of active queues/cards */
704 	spin_lock_bh(&ap_queues_lock);
705 	if (is_queue_dev(dev))
706 		hash_add(ap_queues, &to_ap_queue(dev)->hnode,
707 			 to_ap_queue(dev)->qid);
708 	spin_unlock_bh(&ap_queues_lock);
709 
710 	ap_dev->drv = ap_drv;
711 	rc = ap_drv->probe ? ap_drv->probe(ap_dev) : -ENODEV;
712 
713 	if (rc) {
714 		spin_lock_bh(&ap_queues_lock);
715 		if (is_queue_dev(dev))
716 			hash_del(&to_ap_queue(dev)->hnode);
717 		spin_unlock_bh(&ap_queues_lock);
718 		ap_dev->drv = NULL;
719 	}
720 
721 	return rc;
722 }
723 
724 static int ap_device_remove(struct device *dev)
725 {
726 	struct ap_device *ap_dev = to_ap_dev(dev);
727 	struct ap_driver *ap_drv = ap_dev->drv;
728 
729 	/* prepare ap queue device removal */
730 	if (is_queue_dev(dev))
731 		ap_queue_prepare_remove(to_ap_queue(dev));
732 
733 	/* driver's chance to clean up gracefully */
734 	if (ap_drv->remove)
735 		ap_drv->remove(ap_dev);
736 
737 	/* now do the ap queue device remove */
738 	if (is_queue_dev(dev))
739 		ap_queue_remove(to_ap_queue(dev));
740 
741 	/* Remove queue/card from list of active queues/cards */
742 	spin_lock_bh(&ap_queues_lock);
743 	if (is_queue_dev(dev))
744 		hash_del(&to_ap_queue(dev)->hnode);
745 	spin_unlock_bh(&ap_queues_lock);
746 
747 	return 0;
748 }
749 
750 struct ap_queue *ap_get_qdev(ap_qid_t qid)
751 {
752 	int bkt;
753 	struct ap_queue *aq;
754 
755 	spin_lock_bh(&ap_queues_lock);
756 	hash_for_each(ap_queues, bkt, aq, hnode) {
757 		if (aq->qid == qid) {
758 			get_device(&aq->ap_dev.device);
759 			spin_unlock_bh(&ap_queues_lock);
760 			return aq;
761 		}
762 	}
763 	spin_unlock_bh(&ap_queues_lock);
764 
765 	return NULL;
766 }
767 EXPORT_SYMBOL(ap_get_qdev);
768 
769 int ap_driver_register(struct ap_driver *ap_drv, struct module *owner,
770 		       char *name)
771 {
772 	struct device_driver *drv = &ap_drv->driver;
773 
774 	drv->bus = &ap_bus_type;
775 	drv->probe = ap_device_probe;
776 	drv->remove = ap_device_remove;
777 	drv->owner = owner;
778 	drv->name = name;
779 	return driver_register(drv);
780 }
781 EXPORT_SYMBOL(ap_driver_register);
782 
783 void ap_driver_unregister(struct ap_driver *ap_drv)
784 {
785 	driver_unregister(&ap_drv->driver);
786 }
787 EXPORT_SYMBOL(ap_driver_unregister);
788 
789 void ap_bus_force_rescan(void)
790 {
791 	/* processing a asynchronous bus rescan */
792 	del_timer(&ap_config_timer);
793 	queue_work(system_long_wq, &ap_scan_work);
794 	flush_work(&ap_scan_work);
795 }
796 EXPORT_SYMBOL(ap_bus_force_rescan);
797 
798 /*
799 * A config change has happened, force an ap bus rescan.
800 */
801 void ap_bus_cfg_chg(void)
802 {
803 	AP_DBF_DBG("%s config change, forcing bus rescan\n", __func__);
804 
805 	ap_bus_force_rescan();
806 }
807 
808 /*
809  * hex2bitmap() - parse hex mask string and set bitmap.
810  * Valid strings are "0x012345678" with at least one valid hex number.
811  * Rest of the bitmap to the right is padded with 0. No spaces allowed
812  * within the string, the leading 0x may be omitted.
813  * Returns the bitmask with exactly the bits set as given by the hex
814  * string (both in big endian order).
815  */
816 static int hex2bitmap(const char *str, unsigned long *bitmap, int bits)
817 {
818 	int i, n, b;
819 
820 	/* bits needs to be a multiple of 8 */
821 	if (bits & 0x07)
822 		return -EINVAL;
823 
824 	if (str[0] == '0' && str[1] == 'x')
825 		str++;
826 	if (*str == 'x')
827 		str++;
828 
829 	for (i = 0; isxdigit(*str) && i < bits; str++) {
830 		b = hex_to_bin(*str);
831 		for (n = 0; n < 4; n++)
832 			if (b & (0x08 >> n))
833 				set_bit_inv(i + n, bitmap);
834 		i += 4;
835 	}
836 
837 	if (*str == '\n')
838 		str++;
839 	if (*str)
840 		return -EINVAL;
841 	return 0;
842 }
843 
844 /*
845  * modify_bitmap() - parse bitmask argument and modify an existing
846  * bit mask accordingly. A concatenation (done with ',') of these
847  * terms is recognized:
848  *   +<bitnr>[-<bitnr>] or -<bitnr>[-<bitnr>]
849  * <bitnr> may be any valid number (hex, decimal or octal) in the range
850  * 0...bits-1; the leading + or - is required. Here are some examples:
851  *   +0-15,+32,-128,-0xFF
852  *   -0-255,+1-16,+0x128
853  *   +1,+2,+3,+4,-5,-7-10
854  * Returns the new bitmap after all changes have been applied. Every
855  * positive value in the string will set a bit and every negative value
856  * in the string will clear a bit. As a bit may be touched more than once,
857  * the last 'operation' wins:
858  * +0-255,-128 = first bits 0-255 will be set, then bit 128 will be
859  * cleared again. All other bits are unmodified.
860  */
861 static int modify_bitmap(const char *str, unsigned long *bitmap, int bits)
862 {
863 	int a, i, z;
864 	char *np, sign;
865 
866 	/* bits needs to be a multiple of 8 */
867 	if (bits & 0x07)
868 		return -EINVAL;
869 
870 	while (*str) {
871 		sign = *str++;
872 		if (sign != '+' && sign != '-')
873 			return -EINVAL;
874 		a = z = simple_strtoul(str, &np, 0);
875 		if (str == np || a >= bits)
876 			return -EINVAL;
877 		str = np;
878 		if (*str == '-') {
879 			z = simple_strtoul(++str, &np, 0);
880 			if (str == np || a > z || z >= bits)
881 				return -EINVAL;
882 			str = np;
883 		}
884 		for (i = a; i <= z; i++)
885 			if (sign == '+')
886 				set_bit_inv(i, bitmap);
887 			else
888 				clear_bit_inv(i, bitmap);
889 		while (*str == ',' || *str == '\n')
890 			str++;
891 	}
892 
893 	return 0;
894 }
895 
896 int ap_parse_mask_str(const char *str,
897 		      unsigned long *bitmap, int bits,
898 		      struct mutex *lock)
899 {
900 	unsigned long *newmap, size;
901 	int rc;
902 
903 	/* bits needs to be a multiple of 8 */
904 	if (bits & 0x07)
905 		return -EINVAL;
906 
907 	size = BITS_TO_LONGS(bits)*sizeof(unsigned long);
908 	newmap = kmalloc(size, GFP_KERNEL);
909 	if (!newmap)
910 		return -ENOMEM;
911 	if (mutex_lock_interruptible(lock)) {
912 		kfree(newmap);
913 		return -ERESTARTSYS;
914 	}
915 
916 	if (*str == '+' || *str == '-') {
917 		memcpy(newmap, bitmap, size);
918 		rc = modify_bitmap(str, newmap, bits);
919 	} else {
920 		memset(newmap, 0, size);
921 		rc = hex2bitmap(str, newmap, bits);
922 	}
923 	if (rc == 0)
924 		memcpy(bitmap, newmap, size);
925 	mutex_unlock(lock);
926 	kfree(newmap);
927 	return rc;
928 }
929 EXPORT_SYMBOL(ap_parse_mask_str);
930 
931 /*
932  * AP bus attributes.
933  */
934 
935 static ssize_t ap_domain_show(struct bus_type *bus, char *buf)
936 {
937 	return scnprintf(buf, PAGE_SIZE, "%d\n", ap_domain_index);
938 }
939 
940 static ssize_t ap_domain_store(struct bus_type *bus,
941 			       const char *buf, size_t count)
942 {
943 	int domain;
944 
945 	if (sscanf(buf, "%i\n", &domain) != 1 ||
946 	    domain < 0 || domain > ap_max_domain_id ||
947 	    !test_bit_inv(domain, ap_perms.aqm))
948 		return -EINVAL;
949 
950 	spin_lock_bh(&ap_domain_lock);
951 	ap_domain_index = domain;
952 	spin_unlock_bh(&ap_domain_lock);
953 
954 	AP_DBF_INFO("stored new default domain=%d\n", domain);
955 
956 	return count;
957 }
958 
959 static BUS_ATTR_RW(ap_domain);
960 
961 static ssize_t ap_control_domain_mask_show(struct bus_type *bus, char *buf)
962 {
963 	if (!ap_qci_info)	/* QCI not supported */
964 		return scnprintf(buf, PAGE_SIZE, "not supported\n");
965 
966 	return scnprintf(buf, PAGE_SIZE,
967 			 "0x%08x%08x%08x%08x%08x%08x%08x%08x\n",
968 			 ap_qci_info->adm[0], ap_qci_info->adm[1],
969 			 ap_qci_info->adm[2], ap_qci_info->adm[3],
970 			 ap_qci_info->adm[4], ap_qci_info->adm[5],
971 			 ap_qci_info->adm[6], ap_qci_info->adm[7]);
972 }
973 
974 static BUS_ATTR_RO(ap_control_domain_mask);
975 
976 static ssize_t ap_usage_domain_mask_show(struct bus_type *bus, char *buf)
977 {
978 	if (!ap_qci_info)	/* QCI not supported */
979 		return scnprintf(buf, PAGE_SIZE, "not supported\n");
980 
981 	return scnprintf(buf, PAGE_SIZE,
982 			 "0x%08x%08x%08x%08x%08x%08x%08x%08x\n",
983 			 ap_qci_info->aqm[0], ap_qci_info->aqm[1],
984 			 ap_qci_info->aqm[2], ap_qci_info->aqm[3],
985 			 ap_qci_info->aqm[4], ap_qci_info->aqm[5],
986 			 ap_qci_info->aqm[6], ap_qci_info->aqm[7]);
987 }
988 
989 static BUS_ATTR_RO(ap_usage_domain_mask);
990 
991 static ssize_t ap_adapter_mask_show(struct bus_type *bus, char *buf)
992 {
993 	if (!ap_qci_info)	/* QCI not supported */
994 		return scnprintf(buf, PAGE_SIZE, "not supported\n");
995 
996 	return scnprintf(buf, PAGE_SIZE,
997 			 "0x%08x%08x%08x%08x%08x%08x%08x%08x\n",
998 			 ap_qci_info->apm[0], ap_qci_info->apm[1],
999 			 ap_qci_info->apm[2], ap_qci_info->apm[3],
1000 			 ap_qci_info->apm[4], ap_qci_info->apm[5],
1001 			 ap_qci_info->apm[6], ap_qci_info->apm[7]);
1002 }
1003 
1004 static BUS_ATTR_RO(ap_adapter_mask);
1005 
1006 static ssize_t ap_interrupts_show(struct bus_type *bus, char *buf)
1007 {
1008 	return scnprintf(buf, PAGE_SIZE, "%d\n",
1009 			 ap_using_interrupts() ? 1 : 0);
1010 }
1011 
1012 static BUS_ATTR_RO(ap_interrupts);
1013 
1014 static ssize_t config_time_show(struct bus_type *bus, char *buf)
1015 {
1016 	return scnprintf(buf, PAGE_SIZE, "%d\n", ap_config_time);
1017 }
1018 
1019 static ssize_t config_time_store(struct bus_type *bus,
1020 				 const char *buf, size_t count)
1021 {
1022 	int time;
1023 
1024 	if (sscanf(buf, "%d\n", &time) != 1 || time < 5 || time > 120)
1025 		return -EINVAL;
1026 	ap_config_time = time;
1027 	mod_timer(&ap_config_timer, jiffies + ap_config_time * HZ);
1028 	return count;
1029 }
1030 
1031 static BUS_ATTR_RW(config_time);
1032 
1033 static ssize_t poll_thread_show(struct bus_type *bus, char *buf)
1034 {
1035 	return scnprintf(buf, PAGE_SIZE, "%d\n", ap_poll_kthread ? 1 : 0);
1036 }
1037 
1038 static ssize_t poll_thread_store(struct bus_type *bus,
1039 				 const char *buf, size_t count)
1040 {
1041 	int flag, rc;
1042 
1043 	if (sscanf(buf, "%d\n", &flag) != 1)
1044 		return -EINVAL;
1045 	if (flag) {
1046 		rc = ap_poll_thread_start();
1047 		if (rc)
1048 			count = rc;
1049 	} else
1050 		ap_poll_thread_stop();
1051 	return count;
1052 }
1053 
1054 static BUS_ATTR_RW(poll_thread);
1055 
1056 static ssize_t poll_timeout_show(struct bus_type *bus, char *buf)
1057 {
1058 	return scnprintf(buf, PAGE_SIZE, "%llu\n", poll_timeout);
1059 }
1060 
1061 static ssize_t poll_timeout_store(struct bus_type *bus, const char *buf,
1062 				  size_t count)
1063 {
1064 	unsigned long long time;
1065 	ktime_t hr_time;
1066 
1067 	/* 120 seconds = maximum poll interval */
1068 	if (sscanf(buf, "%llu\n", &time) != 1 || time < 1 ||
1069 	    time > 120000000000ULL)
1070 		return -EINVAL;
1071 	poll_timeout = time;
1072 	hr_time = poll_timeout;
1073 
1074 	spin_lock_bh(&ap_poll_timer_lock);
1075 	hrtimer_cancel(&ap_poll_timer);
1076 	hrtimer_set_expires(&ap_poll_timer, hr_time);
1077 	hrtimer_start_expires(&ap_poll_timer, HRTIMER_MODE_ABS);
1078 	spin_unlock_bh(&ap_poll_timer_lock);
1079 
1080 	return count;
1081 }
1082 
1083 static BUS_ATTR_RW(poll_timeout);
1084 
1085 static ssize_t ap_max_domain_id_show(struct bus_type *bus, char *buf)
1086 {
1087 	return scnprintf(buf, PAGE_SIZE, "%d\n", ap_max_domain_id);
1088 }
1089 
1090 static BUS_ATTR_RO(ap_max_domain_id);
1091 
1092 static ssize_t ap_max_adapter_id_show(struct bus_type *bus, char *buf)
1093 {
1094 	return scnprintf(buf, PAGE_SIZE, "%d\n", ap_max_adapter_id);
1095 }
1096 
1097 static BUS_ATTR_RO(ap_max_adapter_id);
1098 
1099 static ssize_t apmask_show(struct bus_type *bus, char *buf)
1100 {
1101 	int rc;
1102 
1103 	if (mutex_lock_interruptible(&ap_perms_mutex))
1104 		return -ERESTARTSYS;
1105 	rc = scnprintf(buf, PAGE_SIZE,
1106 		       "0x%016lx%016lx%016lx%016lx\n",
1107 		       ap_perms.apm[0], ap_perms.apm[1],
1108 		       ap_perms.apm[2], ap_perms.apm[3]);
1109 	mutex_unlock(&ap_perms_mutex);
1110 
1111 	return rc;
1112 }
1113 
1114 static ssize_t apmask_store(struct bus_type *bus, const char *buf,
1115 			    size_t count)
1116 {
1117 	int rc;
1118 
1119 	rc = ap_parse_mask_str(buf, ap_perms.apm, AP_DEVICES, &ap_perms_mutex);
1120 	if (rc)
1121 		return rc;
1122 
1123 	ap_bus_revise_bindings();
1124 
1125 	return count;
1126 }
1127 
1128 static BUS_ATTR_RW(apmask);
1129 
1130 static ssize_t aqmask_show(struct bus_type *bus, char *buf)
1131 {
1132 	int rc;
1133 
1134 	if (mutex_lock_interruptible(&ap_perms_mutex))
1135 		return -ERESTARTSYS;
1136 	rc = scnprintf(buf, PAGE_SIZE,
1137 		       "0x%016lx%016lx%016lx%016lx\n",
1138 		       ap_perms.aqm[0], ap_perms.aqm[1],
1139 		       ap_perms.aqm[2], ap_perms.aqm[3]);
1140 	mutex_unlock(&ap_perms_mutex);
1141 
1142 	return rc;
1143 }
1144 
1145 static ssize_t aqmask_store(struct bus_type *bus, const char *buf,
1146 			    size_t count)
1147 {
1148 	int rc;
1149 
1150 	rc = ap_parse_mask_str(buf, ap_perms.aqm, AP_DOMAINS, &ap_perms_mutex);
1151 	if (rc)
1152 		return rc;
1153 
1154 	ap_bus_revise_bindings();
1155 
1156 	return count;
1157 }
1158 
1159 static BUS_ATTR_RW(aqmask);
1160 
1161 static struct bus_attribute *const ap_bus_attrs[] = {
1162 	&bus_attr_ap_domain,
1163 	&bus_attr_ap_control_domain_mask,
1164 	&bus_attr_ap_usage_domain_mask,
1165 	&bus_attr_ap_adapter_mask,
1166 	&bus_attr_config_time,
1167 	&bus_attr_poll_thread,
1168 	&bus_attr_ap_interrupts,
1169 	&bus_attr_poll_timeout,
1170 	&bus_attr_ap_max_domain_id,
1171 	&bus_attr_ap_max_adapter_id,
1172 	&bus_attr_apmask,
1173 	&bus_attr_aqmask,
1174 	NULL,
1175 };
1176 
1177 /**
1178  * ap_select_domain(): Select an AP domain if possible and we haven't
1179  * already done so before.
1180  */
1181 static void ap_select_domain(void)
1182 {
1183 	struct ap_queue_status status;
1184 	int card, dom;
1185 
1186 	/*
1187 	 * Choose the default domain. Either the one specified with
1188 	 * the "domain=" parameter or the first domain with at least
1189 	 * one valid APQN.
1190 	 */
1191 	spin_lock_bh(&ap_domain_lock);
1192 	if (ap_domain_index >= 0) {
1193 		/* Domain has already been selected. */
1194 		goto out;
1195 	}
1196 	for (dom = 0; dom <= ap_max_domain_id; dom++) {
1197 		if (!ap_test_config_usage_domain(dom) ||
1198 		    !test_bit_inv(dom, ap_perms.aqm))
1199 			continue;
1200 		for (card = 0; card <= ap_max_adapter_id; card++) {
1201 			if (!ap_test_config_card_id(card) ||
1202 			    !test_bit_inv(card, ap_perms.apm))
1203 				continue;
1204 			status = ap_test_queue(AP_MKQID(card, dom),
1205 					       ap_apft_available(),
1206 					       NULL);
1207 			if (status.response_code == AP_RESPONSE_NORMAL)
1208 				break;
1209 		}
1210 		if (card <= ap_max_adapter_id)
1211 			break;
1212 	}
1213 	if (dom <= ap_max_domain_id) {
1214 		ap_domain_index = dom;
1215 		AP_DBF_INFO("%s new default domain is %d\n",
1216 			    __func__, ap_domain_index);
1217 	}
1218 out:
1219 	spin_unlock_bh(&ap_domain_lock);
1220 }
1221 
1222 /*
1223  * This function checks the type and returns either 0 for not
1224  * supported or the highest compatible type value (which may
1225  * include the input type value).
1226  */
1227 static int ap_get_compatible_type(ap_qid_t qid, int rawtype, unsigned int func)
1228 {
1229 	int comp_type = 0;
1230 
1231 	/* < CEX2A is not supported */
1232 	if (rawtype < AP_DEVICE_TYPE_CEX2A) {
1233 		AP_DBF_WARN("get_comp_type queue=%02x.%04x unsupported type %d\n",
1234 			    AP_QID_CARD(qid), AP_QID_QUEUE(qid), rawtype);
1235 		return 0;
1236 	}
1237 	/* up to CEX7 known and fully supported */
1238 	if (rawtype <= AP_DEVICE_TYPE_CEX7)
1239 		return rawtype;
1240 	/*
1241 	 * unknown new type > CEX7, check for compatibility
1242 	 * to the highest known and supported type which is
1243 	 * currently CEX7 with the help of the QACT function.
1244 	 */
1245 	if (ap_qact_available()) {
1246 		struct ap_queue_status status;
1247 		union ap_qact_ap_info apinfo = {0};
1248 
1249 		apinfo.mode = (func >> 26) & 0x07;
1250 		apinfo.cat = AP_DEVICE_TYPE_CEX7;
1251 		status = ap_qact(qid, 0, &apinfo);
1252 		if (status.response_code == AP_RESPONSE_NORMAL
1253 		    && apinfo.cat >= AP_DEVICE_TYPE_CEX2A
1254 		    && apinfo.cat <= AP_DEVICE_TYPE_CEX7)
1255 			comp_type = apinfo.cat;
1256 	}
1257 	if (!comp_type)
1258 		AP_DBF_WARN("get_comp_type queue=%02x.%04x unable to map type %d\n",
1259 			    AP_QID_CARD(qid), AP_QID_QUEUE(qid), rawtype);
1260 	else if (comp_type != rawtype)
1261 		AP_DBF_INFO("get_comp_type queue=%02x.%04x map type %d to %d\n",
1262 			    AP_QID_CARD(qid), AP_QID_QUEUE(qid),
1263 			    rawtype, comp_type);
1264 	return comp_type;
1265 }
1266 
1267 /*
1268  * Helper function to be used with bus_find_dev
1269  * matches for the card device with the given id
1270  */
1271 static int __match_card_device_with_id(struct device *dev, const void *data)
1272 {
1273 	return is_card_dev(dev) && to_ap_card(dev)->id == (int)(long)(void *) data;
1274 }
1275 
1276 /*
1277  * Helper function to be used with bus_find_dev
1278  * matches for the queue device with a given qid
1279  */
1280 static int __match_queue_device_with_qid(struct device *dev, const void *data)
1281 {
1282 	return is_queue_dev(dev) && to_ap_queue(dev)->qid == (int)(long) data;
1283 }
1284 
1285 /*
1286  * Helper function to be used with bus_find_dev
1287  * matches any queue device with given queue id
1288  */
1289 static int __match_queue_device_with_queue_id(struct device *dev, const void *data)
1290 {
1291 	return is_queue_dev(dev)
1292 		&& AP_QID_QUEUE(to_ap_queue(dev)->qid) == (int)(long) data;
1293 }
1294 
1295 /*
1296  * Helper function for ap_scan_bus().
1297  * Remove card device and associated queue devices.
1298  */
1299 static inline void ap_scan_rm_card_dev_and_queue_devs(struct ap_card *ac)
1300 {
1301 	bus_for_each_dev(&ap_bus_type, NULL,
1302 			 (void *)(long) ac->id,
1303 			 __ap_queue_devices_with_id_unregister);
1304 	device_unregister(&ac->ap_dev.device);
1305 }
1306 
1307 /*
1308  * Helper function for ap_scan_bus().
1309  * Does the scan bus job for all the domains within
1310  * a valid adapter given by an ap_card ptr.
1311  */
1312 static inline void ap_scan_domains(struct ap_card *ac)
1313 {
1314 	bool decfg;
1315 	ap_qid_t qid;
1316 	unsigned int func;
1317 	struct device *dev;
1318 	struct ap_queue *aq;
1319 	int rc, dom, depth, type;
1320 
1321 	/*
1322 	 * Go through the configuration for the domains and compare them
1323 	 * to the existing queue devices. Also take care of the config
1324 	 * and error state for the queue devices.
1325 	 */
1326 
1327 	for (dom = 0; dom <= ap_max_domain_id; dom++) {
1328 		qid = AP_MKQID(ac->id, dom);
1329 		dev = bus_find_device(&ap_bus_type, NULL,
1330 				      (void *)(long) qid,
1331 				      __match_queue_device_with_qid);
1332 		aq = dev ? to_ap_queue(dev) : NULL;
1333 		if (!ap_test_config_usage_domain(dom)) {
1334 			if (dev) {
1335 				AP_DBF_INFO("%s(%d,%d) not in config any more, rm queue device\n",
1336 					    __func__, ac->id, dom);
1337 				device_unregister(dev);
1338 				put_device(dev);
1339 			}
1340 			continue;
1341 		}
1342 		/* domain is valid, get info from this APQN */
1343 		if (!ap_queue_info(qid, &type, &func, &depth, &decfg)) {
1344 			if (aq) {
1345 				AP_DBF_INFO(
1346 					"%s(%d,%d) ap_queue_info() not successful, rm queue device\n",
1347 					__func__, ac->id, dom);
1348 				device_unregister(dev);
1349 				put_device(dev);
1350 			}
1351 			continue;
1352 		}
1353 		/* if no queue device exists, create a new one */
1354 		if (!aq) {
1355 			aq = ap_queue_create(qid, ac->ap_dev.device_type);
1356 			if (!aq) {
1357 				AP_DBF_WARN("%s(%d,%d) ap_queue_create() failed\n",
1358 					    __func__, ac->id, dom);
1359 				continue;
1360 			}
1361 			aq->card = ac;
1362 			aq->config = !decfg;
1363 			dev = &aq->ap_dev.device;
1364 			dev->bus = &ap_bus_type;
1365 			dev->parent = &ac->ap_dev.device;
1366 			dev_set_name(dev, "%02x.%04x", ac->id, dom);
1367 			/* register queue device */
1368 			rc = device_register(dev);
1369 			if (rc) {
1370 				AP_DBF_WARN("%s(%d,%d) device_register() failed\n",
1371 					    __func__, ac->id, dom);
1372 				goto put_dev_and_continue;
1373 			}
1374 			if (decfg)
1375 				AP_DBF_INFO("%s(%d,%d) new (decfg) queue device created\n",
1376 					    __func__, ac->id, dom);
1377 			else
1378 				AP_DBF_INFO("%s(%d,%d) new queue device created\n",
1379 					    __func__, ac->id, dom);
1380 			goto put_dev_and_continue;
1381 		}
1382 		/* Check config state on the already existing queue device */
1383 		spin_lock_bh(&aq->lock);
1384 		if (decfg && aq->config) {
1385 			/* config off this queue device */
1386 			aq->config = false;
1387 			if (aq->dev_state > AP_DEV_STATE_UNINITIATED) {
1388 				aq->dev_state = AP_DEV_STATE_ERROR;
1389 				aq->last_err_rc = AP_RESPONSE_DECONFIGURED;
1390 			}
1391 			spin_unlock_bh(&aq->lock);
1392 			AP_DBF_INFO("%s(%d,%d) queue device config off\n",
1393 				    __func__, ac->id, dom);
1394 			/* 'receive' pending messages with -EAGAIN */
1395 			ap_flush_queue(aq);
1396 			goto put_dev_and_continue;
1397 		}
1398 		if (!decfg && !aq->config) {
1399 			/* config on this queue device */
1400 			aq->config = true;
1401 			if (aq->dev_state > AP_DEV_STATE_UNINITIATED) {
1402 				aq->dev_state = AP_DEV_STATE_OPERATING;
1403 				aq->sm_state = AP_SM_STATE_RESET_START;
1404 			}
1405 			spin_unlock_bh(&aq->lock);
1406 			AP_DBF_INFO("%s(%d,%d) queue device config on\n",
1407 				    __func__, ac->id, dom);
1408 			goto put_dev_and_continue;
1409 		}
1410 		/* handle other error states */
1411 		if (!decfg && aq->dev_state == AP_DEV_STATE_ERROR) {
1412 			spin_unlock_bh(&aq->lock);
1413 			/* 'receive' pending messages with -EAGAIN */
1414 			ap_flush_queue(aq);
1415 			/* re-init (with reset) the queue device */
1416 			ap_queue_init_state(aq);
1417 			AP_DBF_INFO("%s(%d,%d) queue device reinit enforced\n",
1418 				    __func__, ac->id, dom);
1419 			goto put_dev_and_continue;
1420 		}
1421 		spin_unlock_bh(&aq->lock);
1422 put_dev_and_continue:
1423 		put_device(dev);
1424 	}
1425 }
1426 
1427 /*
1428  * Helper function for ap_scan_bus().
1429  * Does the scan bus job for the given adapter id.
1430  */
1431 static inline void ap_scan_adapter(int ap)
1432 {
1433 	bool decfg;
1434 	ap_qid_t qid;
1435 	unsigned int func;
1436 	struct device *dev;
1437 	struct ap_card *ac;
1438 	int rc, dom, depth, type, comp_type;
1439 
1440 	/* Is there currently a card device for this adapter ? */
1441 	dev = bus_find_device(&ap_bus_type, NULL,
1442 			      (void *)(long) ap,
1443 			      __match_card_device_with_id);
1444 	ac = dev ? to_ap_card(dev) : NULL;
1445 
1446 	/* Adapter not in configuration ? */
1447 	if (!ap_test_config_card_id(ap)) {
1448 		if (ac) {
1449 			AP_DBF_INFO("%s(%d) ap not in config any more, rm card and queue devices\n",
1450 				    __func__, ap);
1451 			ap_scan_rm_card_dev_and_queue_devs(ac);
1452 			put_device(dev);
1453 		}
1454 		return;
1455 	}
1456 
1457 	/*
1458 	 * Adapter ap is valid in the current configuration. So do some checks:
1459 	 * If no card device exists, build one. If a card device exists, check
1460 	 * for type and functions changed. For all this we need to find a valid
1461 	 * APQN first.
1462 	 */
1463 
1464 	for (dom = 0; dom <= ap_max_domain_id; dom++)
1465 		if (ap_test_config_usage_domain(dom)) {
1466 			qid = AP_MKQID(ap, dom);
1467 			if (ap_queue_info(qid, &type, &func, &depth, &decfg))
1468 				break;
1469 		}
1470 	if (dom > ap_max_domain_id) {
1471 		/* Could not find a valid APQN for this adapter */
1472 		if (ac) {
1473 			AP_DBF_INFO(
1474 				"%s(%d) no type info (no APQN found), rm card and queue devices\n",
1475 				__func__, ap);
1476 			ap_scan_rm_card_dev_and_queue_devs(ac);
1477 			put_device(dev);
1478 		} else {
1479 			AP_DBF_DBG("%s(%d) no type info (no APQN found), ignored\n",
1480 				   __func__, ap);
1481 		}
1482 		return;
1483 	}
1484 	if (!type) {
1485 		/* No apdater type info available, an unusable adapter */
1486 		if (ac) {
1487 			AP_DBF_INFO("%s(%d) no valid type (0) info, rm card and queue devices\n",
1488 				    __func__, ap);
1489 			ap_scan_rm_card_dev_and_queue_devs(ac);
1490 			put_device(dev);
1491 		} else {
1492 			AP_DBF_DBG("%s(%d) no valid type (0) info, ignored\n",
1493 				   __func__, ap);
1494 		}
1495 		return;
1496 	}
1497 
1498 	if (ac) {
1499 		/* Check APQN against existing card device for changes */
1500 		if (ac->raw_hwtype != type) {
1501 			AP_DBF_INFO("%s(%d) hwtype %d changed, rm card and queue devices\n",
1502 				    __func__, ap, type);
1503 			ap_scan_rm_card_dev_and_queue_devs(ac);
1504 			put_device(dev);
1505 			ac = NULL;
1506 		} else if (ac->functions != func) {
1507 			AP_DBF_INFO("%s(%d) functions 0x%08x changed, rm card and queue devices\n",
1508 				    __func__, ap, type);
1509 			ap_scan_rm_card_dev_and_queue_devs(ac);
1510 			put_device(dev);
1511 			ac = NULL;
1512 		} else {
1513 			if (decfg && ac->config) {
1514 				ac->config = false;
1515 				AP_DBF_INFO("%s(%d) card device config off\n",
1516 					    __func__, ap);
1517 
1518 			}
1519 			if (!decfg && !ac->config) {
1520 				ac->config = true;
1521 				AP_DBF_INFO("%s(%d) card device config on\n",
1522 					    __func__, ap);
1523 			}
1524 		}
1525 	}
1526 
1527 	if (!ac) {
1528 		/* Build a new card device */
1529 		comp_type = ap_get_compatible_type(qid, type, func);
1530 		if (!comp_type) {
1531 			AP_DBF_WARN("%s(%d) type %d, can't get compatibility type\n",
1532 				    __func__, ap, type);
1533 			return;
1534 		}
1535 		ac = ap_card_create(ap, depth, type, comp_type, func);
1536 		if (!ac) {
1537 			AP_DBF_WARN("%s(%d) ap_card_create() failed\n",
1538 				    __func__, ap);
1539 			return;
1540 		}
1541 		ac->config = !decfg;
1542 		dev = &ac->ap_dev.device;
1543 		dev->bus = &ap_bus_type;
1544 		dev->parent = ap_root_device;
1545 		dev_set_name(dev, "card%02x", ap);
1546 		/* Register the new card device with AP bus */
1547 		rc = device_register(dev);
1548 		if (rc) {
1549 			AP_DBF_WARN("%s(%d) device_register() failed\n",
1550 				    __func__, ap);
1551 			put_device(dev);
1552 			return;
1553 		}
1554 		/* get it and thus adjust reference counter */
1555 		get_device(dev);
1556 		if (decfg)
1557 			AP_DBF_INFO("%s(%d) new (decfg) card device type=%d func=0x%08x created\n",
1558 				    __func__, ap, type, func);
1559 		else
1560 			AP_DBF_INFO("%s(%d) new card device type=%d func=0x%08x created\n",
1561 				    __func__, ap, type, func);
1562 	}
1563 
1564 	/* Verify the domains and the queue devices for this card */
1565 	ap_scan_domains(ac);
1566 
1567 	/* release the card device */
1568 	put_device(&ac->ap_dev.device);
1569 }
1570 
1571 /**
1572  * ap_scan_bus(): Scan the AP bus for new devices
1573  * Runs periodically, workqueue timer (ap_config_time)
1574  */
1575 static void ap_scan_bus(struct work_struct *unused)
1576 {
1577 	int ap;
1578 
1579 	ap_fetch_qci_info(ap_qci_info);
1580 	ap_select_domain();
1581 
1582 	AP_DBF_DBG("%s running\n", __func__);
1583 
1584 	/* loop over all possible adapters */
1585 	for (ap = 0; ap <= ap_max_adapter_id; ap++)
1586 		ap_scan_adapter(ap);
1587 
1588 	/* check if there is at least one queue available with default domain */
1589 	if (ap_domain_index >= 0) {
1590 		struct device *dev =
1591 			bus_find_device(&ap_bus_type, NULL,
1592 					(void *)(long) ap_domain_index,
1593 					__match_queue_device_with_queue_id);
1594 		if (dev)
1595 			put_device(dev);
1596 		else
1597 			AP_DBF_INFO("no queue device with default domain %d available\n",
1598 				    ap_domain_index);
1599 	}
1600 
1601 	mod_timer(&ap_config_timer, jiffies + ap_config_time * HZ);
1602 }
1603 
1604 static void ap_config_timeout(struct timer_list *unused)
1605 {
1606 	queue_work(system_long_wq, &ap_scan_work);
1607 }
1608 
1609 static int __init ap_debug_init(void)
1610 {
1611 	ap_dbf_info = debug_register("ap", 1, 1,
1612 				     DBF_MAX_SPRINTF_ARGS * sizeof(long));
1613 	debug_register_view(ap_dbf_info, &debug_sprintf_view);
1614 	debug_set_level(ap_dbf_info, DBF_ERR);
1615 
1616 	return 0;
1617 }
1618 
1619 static void __init ap_perms_init(void)
1620 {
1621 	/* all resources useable if no kernel parameter string given */
1622 	memset(&ap_perms.ioctlm, 0xFF, sizeof(ap_perms.ioctlm));
1623 	memset(&ap_perms.apm, 0xFF, sizeof(ap_perms.apm));
1624 	memset(&ap_perms.aqm, 0xFF, sizeof(ap_perms.aqm));
1625 
1626 	/* apm kernel parameter string */
1627 	if (apm_str) {
1628 		memset(&ap_perms.apm, 0, sizeof(ap_perms.apm));
1629 		ap_parse_mask_str(apm_str, ap_perms.apm, AP_DEVICES,
1630 				  &ap_perms_mutex);
1631 	}
1632 
1633 	/* aqm kernel parameter string */
1634 	if (aqm_str) {
1635 		memset(&ap_perms.aqm, 0, sizeof(ap_perms.aqm));
1636 		ap_parse_mask_str(aqm_str, ap_perms.aqm, AP_DOMAINS,
1637 				  &ap_perms_mutex);
1638 	}
1639 }
1640 
1641 /**
1642  * ap_module_init(): The module initialization code.
1643  *
1644  * Initializes the module.
1645  */
1646 static int __init ap_module_init(void)
1647 {
1648 	int rc, i;
1649 
1650 	rc = ap_debug_init();
1651 	if (rc)
1652 		return rc;
1653 
1654 	if (!ap_instructions_available()) {
1655 		pr_warn("The hardware system does not support AP instructions\n");
1656 		return -ENODEV;
1657 	}
1658 
1659 	/* init ap_queue hashtable */
1660 	hash_init(ap_queues);
1661 
1662 	/* set up the AP permissions (ioctls, ap and aq masks) */
1663 	ap_perms_init();
1664 
1665 	/* Get AP configuration data if available */
1666 	ap_init_qci_info();
1667 
1668 	/* check default domain setting */
1669 	if (ap_domain_index < -1 || ap_domain_index > ap_max_domain_id ||
1670 	    (ap_domain_index >= 0 &&
1671 	     !test_bit_inv(ap_domain_index, ap_perms.aqm))) {
1672 		pr_warn("%d is not a valid cryptographic domain\n",
1673 			ap_domain_index);
1674 		ap_domain_index = -1;
1675 	}
1676 
1677 	/* enable interrupts if available */
1678 	if (ap_interrupts_available()) {
1679 		rc = register_adapter_interrupt(&ap_airq);
1680 		ap_airq_flag = (rc == 0);
1681 	}
1682 
1683 	/* Create /sys/bus/ap. */
1684 	rc = bus_register(&ap_bus_type);
1685 	if (rc)
1686 		goto out;
1687 	for (i = 0; ap_bus_attrs[i]; i++) {
1688 		rc = bus_create_file(&ap_bus_type, ap_bus_attrs[i]);
1689 		if (rc)
1690 			goto out_bus;
1691 	}
1692 
1693 	/* Create /sys/devices/ap. */
1694 	ap_root_device = root_device_register("ap");
1695 	rc = PTR_ERR_OR_ZERO(ap_root_device);
1696 	if (rc)
1697 		goto out_bus;
1698 
1699 	/* Setup the AP bus rescan timer. */
1700 	timer_setup(&ap_config_timer, ap_config_timeout, 0);
1701 
1702 	/*
1703 	 * Setup the high resultion poll timer.
1704 	 * If we are running under z/VM adjust polling to z/VM polling rate.
1705 	 */
1706 	if (MACHINE_IS_VM)
1707 		poll_timeout = 1500000;
1708 	hrtimer_init(&ap_poll_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
1709 	ap_poll_timer.function = ap_poll_timeout;
1710 
1711 	/* Start the low priority AP bus poll thread. */
1712 	if (ap_thread_flag) {
1713 		rc = ap_poll_thread_start();
1714 		if (rc)
1715 			goto out_work;
1716 	}
1717 
1718 	queue_work(system_long_wq, &ap_scan_work);
1719 
1720 	return 0;
1721 
1722 out_work:
1723 	hrtimer_cancel(&ap_poll_timer);
1724 	root_device_unregister(ap_root_device);
1725 out_bus:
1726 	while (i--)
1727 		bus_remove_file(&ap_bus_type, ap_bus_attrs[i]);
1728 	bus_unregister(&ap_bus_type);
1729 out:
1730 	if (ap_using_interrupts())
1731 		unregister_adapter_interrupt(&ap_airq);
1732 	kfree(ap_qci_info);
1733 	return rc;
1734 }
1735 device_initcall(ap_module_init);
1736