xref: /openbmc/linux/drivers/s390/crypto/ap_bus.c (revision 29c37341)
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(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(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(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(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)
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 		/*
326 		 * According to the architecture in all these cases the
327 		 * info should be filled. All bits 0 is not possible as
328 		 * there is at least one of the mode bits set.
329 		 */
330 		if (WARN_ON_ONCE(!info))
331 			return false;
332 		*q_type = (int)((info >> 24) & 0xff);
333 		*q_fac = (unsigned int)(info >> 32);
334 		*q_depth = (int)(info & 0xff);
335 		switch (*q_type) {
336 			/* For CEX2 and CEX3 the available functions
337 			 * are not reflected by the facilities bits.
338 			 * Instead it is coded into the type. So here
339 			 * modify the function bits based on the type.
340 			 */
341 		case AP_DEVICE_TYPE_CEX2A:
342 		case AP_DEVICE_TYPE_CEX3A:
343 			*q_fac |= 0x08000000;
344 			break;
345 		case AP_DEVICE_TYPE_CEX2C:
346 		case AP_DEVICE_TYPE_CEX3C:
347 			*q_fac |= 0x10000000;
348 			break;
349 		default:
350 			break;
351 		}
352 		return true;
353 	default:
354 		/*
355 		 * A response code which indicates, there is no info available.
356 		 */
357 		return false;
358 	}
359 }
360 
361 void ap_wait(enum ap_sm_wait wait)
362 {
363 	ktime_t hr_time;
364 
365 	switch (wait) {
366 	case AP_SM_WAIT_AGAIN:
367 	case AP_SM_WAIT_INTERRUPT:
368 		if (ap_using_interrupts())
369 			break;
370 		if (ap_poll_kthread) {
371 			wake_up(&ap_poll_wait);
372 			break;
373 		}
374 		fallthrough;
375 	case AP_SM_WAIT_TIMEOUT:
376 		spin_lock_bh(&ap_poll_timer_lock);
377 		if (!hrtimer_is_queued(&ap_poll_timer)) {
378 			hr_time = poll_timeout;
379 			hrtimer_forward_now(&ap_poll_timer, hr_time);
380 			hrtimer_restart(&ap_poll_timer);
381 		}
382 		spin_unlock_bh(&ap_poll_timer_lock);
383 		break;
384 	case AP_SM_WAIT_NONE:
385 	default:
386 		break;
387 	}
388 }
389 
390 /**
391  * ap_request_timeout(): Handling of request timeouts
392  * @t: timer making this callback
393  *
394  * Handles request timeouts.
395  */
396 void ap_request_timeout(struct timer_list *t)
397 {
398 	struct ap_queue *aq = from_timer(aq, t, timeout);
399 
400 	spin_lock_bh(&aq->lock);
401 	ap_wait(ap_sm_event(aq, AP_SM_EVENT_TIMEOUT));
402 	spin_unlock_bh(&aq->lock);
403 }
404 
405 /**
406  * ap_poll_timeout(): AP receive polling for finished AP requests.
407  * @unused: Unused pointer.
408  *
409  * Schedules the AP tasklet using a high resolution timer.
410  */
411 static enum hrtimer_restart ap_poll_timeout(struct hrtimer *unused)
412 {
413 	tasklet_schedule(&ap_tasklet);
414 	return HRTIMER_NORESTART;
415 }
416 
417 /**
418  * ap_interrupt_handler() - Schedule ap_tasklet on interrupt
419  * @airq: pointer to adapter interrupt descriptor
420  */
421 static void ap_interrupt_handler(struct airq_struct *airq, bool floating)
422 {
423 	inc_irq_stat(IRQIO_APB);
424 	tasklet_schedule(&ap_tasklet);
425 }
426 
427 /**
428  * ap_tasklet_fn(): Tasklet to poll all AP devices.
429  * @dummy: Unused variable
430  *
431  * Poll all AP devices on the bus.
432  */
433 static void ap_tasklet_fn(unsigned long dummy)
434 {
435 	int bkt;
436 	struct ap_queue *aq;
437 	enum ap_sm_wait wait = AP_SM_WAIT_NONE;
438 
439 	/* Reset the indicator if interrupts are used. Thus new interrupts can
440 	 * be received. Doing it in the beginning of the tasklet is therefor
441 	 * important that no requests on any AP get lost.
442 	 */
443 	if (ap_using_interrupts())
444 		xchg(ap_airq.lsi_ptr, 0);
445 
446 	spin_lock_bh(&ap_queues_lock);
447 	hash_for_each(ap_queues, bkt, aq, hnode) {
448 		spin_lock_bh(&aq->lock);
449 		wait = min(wait, ap_sm_event_loop(aq, AP_SM_EVENT_POLL));
450 		spin_unlock_bh(&aq->lock);
451 	}
452 	spin_unlock_bh(&ap_queues_lock);
453 
454 	ap_wait(wait);
455 }
456 
457 static int ap_pending_requests(void)
458 {
459 	int bkt;
460 	struct ap_queue *aq;
461 
462 	spin_lock_bh(&ap_queues_lock);
463 	hash_for_each(ap_queues, bkt, aq, hnode) {
464 		if (aq->queue_count == 0)
465 			continue;
466 		spin_unlock_bh(&ap_queues_lock);
467 		return 1;
468 	}
469 	spin_unlock_bh(&ap_queues_lock);
470 	return 0;
471 }
472 
473 /**
474  * ap_poll_thread(): Thread that polls for finished requests.
475  * @data: Unused pointer
476  *
477  * AP bus poll thread. The purpose of this thread is to poll for
478  * finished requests in a loop if there is a "free" cpu - that is
479  * a cpu that doesn't have anything better to do. The polling stops
480  * as soon as there is another task or if all messages have been
481  * delivered.
482  */
483 static int ap_poll_thread(void *data)
484 {
485 	DECLARE_WAITQUEUE(wait, current);
486 
487 	set_user_nice(current, MAX_NICE);
488 	set_freezable();
489 	while (!kthread_should_stop()) {
490 		add_wait_queue(&ap_poll_wait, &wait);
491 		set_current_state(TASK_INTERRUPTIBLE);
492 		if (!ap_pending_requests()) {
493 			schedule();
494 			try_to_freeze();
495 		}
496 		set_current_state(TASK_RUNNING);
497 		remove_wait_queue(&ap_poll_wait, &wait);
498 		if (need_resched()) {
499 			schedule();
500 			try_to_freeze();
501 			continue;
502 		}
503 		ap_tasklet_fn(0);
504 	}
505 
506 	return 0;
507 }
508 
509 static int ap_poll_thread_start(void)
510 {
511 	int rc;
512 
513 	if (ap_using_interrupts() || ap_poll_kthread)
514 		return 0;
515 	mutex_lock(&ap_poll_thread_mutex);
516 	ap_poll_kthread = kthread_run(ap_poll_thread, NULL, "appoll");
517 	rc = PTR_ERR_OR_ZERO(ap_poll_kthread);
518 	if (rc)
519 		ap_poll_kthread = NULL;
520 	mutex_unlock(&ap_poll_thread_mutex);
521 	return rc;
522 }
523 
524 static void ap_poll_thread_stop(void)
525 {
526 	if (!ap_poll_kthread)
527 		return;
528 	mutex_lock(&ap_poll_thread_mutex);
529 	kthread_stop(ap_poll_kthread);
530 	ap_poll_kthread = NULL;
531 	mutex_unlock(&ap_poll_thread_mutex);
532 }
533 
534 #define is_card_dev(x) ((x)->parent == ap_root_device)
535 #define is_queue_dev(x) ((x)->parent != ap_root_device)
536 
537 /**
538  * ap_bus_match()
539  * @dev: Pointer to device
540  * @drv: Pointer to device_driver
541  *
542  * AP bus driver registration/unregistration.
543  */
544 static int ap_bus_match(struct device *dev, struct device_driver *drv)
545 {
546 	struct ap_driver *ap_drv = to_ap_drv(drv);
547 	struct ap_device_id *id;
548 
549 	/*
550 	 * Compare device type of the device with the list of
551 	 * supported types of the device_driver.
552 	 */
553 	for (id = ap_drv->ids; id->match_flags; id++) {
554 		if (is_card_dev(dev) &&
555 		    id->match_flags & AP_DEVICE_ID_MATCH_CARD_TYPE &&
556 		    id->dev_type == to_ap_dev(dev)->device_type)
557 			return 1;
558 		if (is_queue_dev(dev) &&
559 		    id->match_flags & AP_DEVICE_ID_MATCH_QUEUE_TYPE &&
560 		    id->dev_type == to_ap_dev(dev)->device_type)
561 			return 1;
562 	}
563 	return 0;
564 }
565 
566 /**
567  * ap_uevent(): Uevent function for AP devices.
568  * @dev: Pointer to device
569  * @env: Pointer to kobj_uevent_env
570  *
571  * It sets up a single environment variable DEV_TYPE which contains the
572  * hardware device type.
573  */
574 static int ap_uevent(struct device *dev, struct kobj_uevent_env *env)
575 {
576 	struct ap_device *ap_dev = to_ap_dev(dev);
577 	int retval = 0;
578 
579 	if (!ap_dev)
580 		return -ENODEV;
581 
582 	/* Set up DEV_TYPE environment variable. */
583 	retval = add_uevent_var(env, "DEV_TYPE=%04X", ap_dev->device_type);
584 	if (retval)
585 		return retval;
586 
587 	/* Add MODALIAS= */
588 	retval = add_uevent_var(env, "MODALIAS=ap:t%02X", ap_dev->device_type);
589 
590 	return retval;
591 }
592 
593 static int __ap_queue_devices_with_id_unregister(struct device *dev, void *data)
594 {
595 	if (is_queue_dev(dev) &&
596 	    AP_QID_CARD(to_ap_queue(dev)->qid) == (int)(long) data)
597 		device_unregister(dev);
598 	return 0;
599 }
600 
601 static struct bus_type ap_bus_type = {
602 	.name = "ap",
603 	.match = &ap_bus_match,
604 	.uevent = &ap_uevent,
605 };
606 
607 static int __ap_revise_reserved(struct device *dev, void *dummy)
608 {
609 	int rc, card, queue, devres, drvres;
610 
611 	if (is_queue_dev(dev)) {
612 		card = AP_QID_CARD(to_ap_queue(dev)->qid);
613 		queue = AP_QID_QUEUE(to_ap_queue(dev)->qid);
614 		mutex_lock(&ap_perms_mutex);
615 		devres = test_bit_inv(card, ap_perms.apm)
616 			&& test_bit_inv(queue, ap_perms.aqm);
617 		mutex_unlock(&ap_perms_mutex);
618 		drvres = to_ap_drv(dev->driver)->flags
619 			& AP_DRIVER_FLAG_DEFAULT;
620 		if (!!devres != !!drvres) {
621 			AP_DBF(DBF_DEBUG, "reprobing queue=%02x.%04x\n",
622 			       card, queue);
623 			rc = device_reprobe(dev);
624 		}
625 	}
626 
627 	return 0;
628 }
629 
630 static void ap_bus_revise_bindings(void)
631 {
632 	bus_for_each_dev(&ap_bus_type, NULL, NULL, __ap_revise_reserved);
633 }
634 
635 int ap_owned_by_def_drv(int card, int queue)
636 {
637 	int rc = 0;
638 
639 	if (card < 0 || card >= AP_DEVICES || queue < 0 || queue >= AP_DOMAINS)
640 		return -EINVAL;
641 
642 	mutex_lock(&ap_perms_mutex);
643 
644 	if (test_bit_inv(card, ap_perms.apm)
645 	    && test_bit_inv(queue, ap_perms.aqm))
646 		rc = 1;
647 
648 	mutex_unlock(&ap_perms_mutex);
649 
650 	return rc;
651 }
652 EXPORT_SYMBOL(ap_owned_by_def_drv);
653 
654 int ap_apqn_in_matrix_owned_by_def_drv(unsigned long *apm,
655 				       unsigned long *aqm)
656 {
657 	int card, queue, rc = 0;
658 
659 	mutex_lock(&ap_perms_mutex);
660 
661 	for (card = 0; !rc && card < AP_DEVICES; card++)
662 		if (test_bit_inv(card, apm) &&
663 		    test_bit_inv(card, ap_perms.apm))
664 			for (queue = 0; !rc && queue < AP_DOMAINS; queue++)
665 				if (test_bit_inv(queue, aqm) &&
666 				    test_bit_inv(queue, ap_perms.aqm))
667 					rc = 1;
668 
669 	mutex_unlock(&ap_perms_mutex);
670 
671 	return rc;
672 }
673 EXPORT_SYMBOL(ap_apqn_in_matrix_owned_by_def_drv);
674 
675 static int ap_device_probe(struct device *dev)
676 {
677 	struct ap_device *ap_dev = to_ap_dev(dev);
678 	struct ap_driver *ap_drv = to_ap_drv(dev->driver);
679 	int card, queue, devres, drvres, rc;
680 
681 	if (is_queue_dev(dev)) {
682 		/*
683 		 * If the apqn is marked as reserved/used by ap bus and
684 		 * default drivers, only probe with drivers with the default
685 		 * flag set. If it is not marked, only probe with drivers
686 		 * with the default flag not set.
687 		 */
688 		card = AP_QID_CARD(to_ap_queue(dev)->qid);
689 		queue = AP_QID_QUEUE(to_ap_queue(dev)->qid);
690 		mutex_lock(&ap_perms_mutex);
691 		devres = test_bit_inv(card, ap_perms.apm)
692 			&& test_bit_inv(queue, ap_perms.aqm);
693 		mutex_unlock(&ap_perms_mutex);
694 		drvres = ap_drv->flags & AP_DRIVER_FLAG_DEFAULT;
695 		if (!!devres != !!drvres)
696 			return -ENODEV;
697 	}
698 
699 	/* Add queue/card to list of active queues/cards */
700 	spin_lock_bh(&ap_queues_lock);
701 	if (is_queue_dev(dev))
702 		hash_add(ap_queues, &to_ap_queue(dev)->hnode,
703 			 to_ap_queue(dev)->qid);
704 	spin_unlock_bh(&ap_queues_lock);
705 
706 	ap_dev->drv = ap_drv;
707 	rc = ap_drv->probe ? ap_drv->probe(ap_dev) : -ENODEV;
708 
709 	if (rc) {
710 		spin_lock_bh(&ap_queues_lock);
711 		if (is_queue_dev(dev))
712 			hash_del(&to_ap_queue(dev)->hnode);
713 		spin_unlock_bh(&ap_queues_lock);
714 		ap_dev->drv = NULL;
715 	}
716 
717 	return rc;
718 }
719 
720 static int ap_device_remove(struct device *dev)
721 {
722 	struct ap_device *ap_dev = to_ap_dev(dev);
723 	struct ap_driver *ap_drv = ap_dev->drv;
724 
725 	/* prepare ap queue device removal */
726 	if (is_queue_dev(dev))
727 		ap_queue_prepare_remove(to_ap_queue(dev));
728 
729 	/* driver's chance to clean up gracefully */
730 	if (ap_drv->remove)
731 		ap_drv->remove(ap_dev);
732 
733 	/* now do the ap queue device remove */
734 	if (is_queue_dev(dev))
735 		ap_queue_remove(to_ap_queue(dev));
736 
737 	/* Remove queue/card from list of active queues/cards */
738 	spin_lock_bh(&ap_queues_lock);
739 	if (is_queue_dev(dev))
740 		hash_del(&to_ap_queue(dev)->hnode);
741 	spin_unlock_bh(&ap_queues_lock);
742 
743 	return 0;
744 }
745 
746 struct ap_queue *ap_get_qdev(ap_qid_t qid)
747 {
748 	int bkt;
749 	struct ap_queue *aq;
750 
751 	spin_lock_bh(&ap_queues_lock);
752 	hash_for_each(ap_queues, bkt, aq, hnode) {
753 		if (aq->qid == qid) {
754 			get_device(&aq->ap_dev.device);
755 			spin_unlock_bh(&ap_queues_lock);
756 			return aq;
757 		}
758 	}
759 	spin_unlock_bh(&ap_queues_lock);
760 
761 	return NULL;
762 }
763 EXPORT_SYMBOL(ap_get_qdev);
764 
765 int ap_driver_register(struct ap_driver *ap_drv, struct module *owner,
766 		       char *name)
767 {
768 	struct device_driver *drv = &ap_drv->driver;
769 
770 	drv->bus = &ap_bus_type;
771 	drv->probe = ap_device_probe;
772 	drv->remove = ap_device_remove;
773 	drv->owner = owner;
774 	drv->name = name;
775 	return driver_register(drv);
776 }
777 EXPORT_SYMBOL(ap_driver_register);
778 
779 void ap_driver_unregister(struct ap_driver *ap_drv)
780 {
781 	driver_unregister(&ap_drv->driver);
782 }
783 EXPORT_SYMBOL(ap_driver_unregister);
784 
785 void ap_bus_force_rescan(void)
786 {
787 	/* processing a asynchronous bus rescan */
788 	del_timer(&ap_config_timer);
789 	queue_work(system_long_wq, &ap_scan_work);
790 	flush_work(&ap_scan_work);
791 }
792 EXPORT_SYMBOL(ap_bus_force_rescan);
793 
794 /*
795 * A config change has happened, force an ap bus rescan.
796 */
797 void ap_bus_cfg_chg(void)
798 {
799 	AP_DBF(DBF_INFO, "%s config change, forcing bus rescan\n", __func__);
800 
801 	ap_bus_force_rescan();
802 }
803 
804 /*
805  * hex2bitmap() - parse hex mask string and set bitmap.
806  * Valid strings are "0x012345678" with at least one valid hex number.
807  * Rest of the bitmap to the right is padded with 0. No spaces allowed
808  * within the string, the leading 0x may be omitted.
809  * Returns the bitmask with exactly the bits set as given by the hex
810  * string (both in big endian order).
811  */
812 static int hex2bitmap(const char *str, unsigned long *bitmap, int bits)
813 {
814 	int i, n, b;
815 
816 	/* bits needs to be a multiple of 8 */
817 	if (bits & 0x07)
818 		return -EINVAL;
819 
820 	if (str[0] == '0' && str[1] == 'x')
821 		str++;
822 	if (*str == 'x')
823 		str++;
824 
825 	for (i = 0; isxdigit(*str) && i < bits; str++) {
826 		b = hex_to_bin(*str);
827 		for (n = 0; n < 4; n++)
828 			if (b & (0x08 >> n))
829 				set_bit_inv(i + n, bitmap);
830 		i += 4;
831 	}
832 
833 	if (*str == '\n')
834 		str++;
835 	if (*str)
836 		return -EINVAL;
837 	return 0;
838 }
839 
840 /*
841  * modify_bitmap() - parse bitmask argument and modify an existing
842  * bit mask accordingly. A concatenation (done with ',') of these
843  * terms is recognized:
844  *   +<bitnr>[-<bitnr>] or -<bitnr>[-<bitnr>]
845  * <bitnr> may be any valid number (hex, decimal or octal) in the range
846  * 0...bits-1; the leading + or - is required. Here are some examples:
847  *   +0-15,+32,-128,-0xFF
848  *   -0-255,+1-16,+0x128
849  *   +1,+2,+3,+4,-5,-7-10
850  * Returns the new bitmap after all changes have been applied. Every
851  * positive value in the string will set a bit and every negative value
852  * in the string will clear a bit. As a bit may be touched more than once,
853  * the last 'operation' wins:
854  * +0-255,-128 = first bits 0-255 will be set, then bit 128 will be
855  * cleared again. All other bits are unmodified.
856  */
857 static int modify_bitmap(const char *str, unsigned long *bitmap, int bits)
858 {
859 	int a, i, z;
860 	char *np, sign;
861 
862 	/* bits needs to be a multiple of 8 */
863 	if (bits & 0x07)
864 		return -EINVAL;
865 
866 	while (*str) {
867 		sign = *str++;
868 		if (sign != '+' && sign != '-')
869 			return -EINVAL;
870 		a = z = simple_strtoul(str, &np, 0);
871 		if (str == np || a >= bits)
872 			return -EINVAL;
873 		str = np;
874 		if (*str == '-') {
875 			z = simple_strtoul(++str, &np, 0);
876 			if (str == np || a > z || z >= bits)
877 				return -EINVAL;
878 			str = np;
879 		}
880 		for (i = a; i <= z; i++)
881 			if (sign == '+')
882 				set_bit_inv(i, bitmap);
883 			else
884 				clear_bit_inv(i, bitmap);
885 		while (*str == ',' || *str == '\n')
886 			str++;
887 	}
888 
889 	return 0;
890 }
891 
892 int ap_parse_mask_str(const char *str,
893 		      unsigned long *bitmap, int bits,
894 		      struct mutex *lock)
895 {
896 	unsigned long *newmap, size;
897 	int rc;
898 
899 	/* bits needs to be a multiple of 8 */
900 	if (bits & 0x07)
901 		return -EINVAL;
902 
903 	size = BITS_TO_LONGS(bits)*sizeof(unsigned long);
904 	newmap = kmalloc(size, GFP_KERNEL);
905 	if (!newmap)
906 		return -ENOMEM;
907 	if (mutex_lock_interruptible(lock)) {
908 		kfree(newmap);
909 		return -ERESTARTSYS;
910 	}
911 
912 	if (*str == '+' || *str == '-') {
913 		memcpy(newmap, bitmap, size);
914 		rc = modify_bitmap(str, newmap, bits);
915 	} else {
916 		memset(newmap, 0, size);
917 		rc = hex2bitmap(str, newmap, bits);
918 	}
919 	if (rc == 0)
920 		memcpy(bitmap, newmap, size);
921 	mutex_unlock(lock);
922 	kfree(newmap);
923 	return rc;
924 }
925 EXPORT_SYMBOL(ap_parse_mask_str);
926 
927 /*
928  * AP bus attributes.
929  */
930 
931 static ssize_t ap_domain_show(struct bus_type *bus, char *buf)
932 {
933 	return scnprintf(buf, PAGE_SIZE, "%d\n", ap_domain_index);
934 }
935 
936 static ssize_t ap_domain_store(struct bus_type *bus,
937 			       const char *buf, size_t count)
938 {
939 	int domain;
940 
941 	if (sscanf(buf, "%i\n", &domain) != 1 ||
942 	    domain < 0 || domain > ap_max_domain_id ||
943 	    !test_bit_inv(domain, ap_perms.aqm))
944 		return -EINVAL;
945 
946 	spin_lock_bh(&ap_domain_lock);
947 	ap_domain_index = domain;
948 	spin_unlock_bh(&ap_domain_lock);
949 
950 	AP_DBF(DBF_INFO, "stored new default domain=%d\n", domain);
951 
952 	return count;
953 }
954 
955 static BUS_ATTR_RW(ap_domain);
956 
957 static ssize_t ap_control_domain_mask_show(struct bus_type *bus, char *buf)
958 {
959 	if (!ap_qci_info)	/* QCI not supported */
960 		return scnprintf(buf, PAGE_SIZE, "not supported\n");
961 
962 	return scnprintf(buf, PAGE_SIZE,
963 			 "0x%08x%08x%08x%08x%08x%08x%08x%08x\n",
964 			 ap_qci_info->adm[0], ap_qci_info->adm[1],
965 			 ap_qci_info->adm[2], ap_qci_info->adm[3],
966 			 ap_qci_info->adm[4], ap_qci_info->adm[5],
967 			 ap_qci_info->adm[6], ap_qci_info->adm[7]);
968 }
969 
970 static BUS_ATTR_RO(ap_control_domain_mask);
971 
972 static ssize_t ap_usage_domain_mask_show(struct bus_type *bus, char *buf)
973 {
974 	if (!ap_qci_info)	/* QCI not supported */
975 		return scnprintf(buf, PAGE_SIZE, "not supported\n");
976 
977 	return scnprintf(buf, PAGE_SIZE,
978 			 "0x%08x%08x%08x%08x%08x%08x%08x%08x\n",
979 			 ap_qci_info->aqm[0], ap_qci_info->aqm[1],
980 			 ap_qci_info->aqm[2], ap_qci_info->aqm[3],
981 			 ap_qci_info->aqm[4], ap_qci_info->aqm[5],
982 			 ap_qci_info->aqm[6], ap_qci_info->aqm[7]);
983 }
984 
985 static BUS_ATTR_RO(ap_usage_domain_mask);
986 
987 static ssize_t ap_adapter_mask_show(struct bus_type *bus, char *buf)
988 {
989 	if (!ap_qci_info)	/* QCI not supported */
990 		return scnprintf(buf, PAGE_SIZE, "not supported\n");
991 
992 	return scnprintf(buf, PAGE_SIZE,
993 			 "0x%08x%08x%08x%08x%08x%08x%08x%08x\n",
994 			 ap_qci_info->apm[0], ap_qci_info->apm[1],
995 			 ap_qci_info->apm[2], ap_qci_info->apm[3],
996 			 ap_qci_info->apm[4], ap_qci_info->apm[5],
997 			 ap_qci_info->apm[6], ap_qci_info->apm[7]);
998 }
999 
1000 static BUS_ATTR_RO(ap_adapter_mask);
1001 
1002 static ssize_t ap_interrupts_show(struct bus_type *bus, char *buf)
1003 {
1004 	return scnprintf(buf, PAGE_SIZE, "%d\n",
1005 			 ap_using_interrupts() ? 1 : 0);
1006 }
1007 
1008 static BUS_ATTR_RO(ap_interrupts);
1009 
1010 static ssize_t config_time_show(struct bus_type *bus, char *buf)
1011 {
1012 	return scnprintf(buf, PAGE_SIZE, "%d\n", ap_config_time);
1013 }
1014 
1015 static ssize_t config_time_store(struct bus_type *bus,
1016 				 const char *buf, size_t count)
1017 {
1018 	int time;
1019 
1020 	if (sscanf(buf, "%d\n", &time) != 1 || time < 5 || time > 120)
1021 		return -EINVAL;
1022 	ap_config_time = time;
1023 	mod_timer(&ap_config_timer, jiffies + ap_config_time * HZ);
1024 	return count;
1025 }
1026 
1027 static BUS_ATTR_RW(config_time);
1028 
1029 static ssize_t poll_thread_show(struct bus_type *bus, char *buf)
1030 {
1031 	return scnprintf(buf, PAGE_SIZE, "%d\n", ap_poll_kthread ? 1 : 0);
1032 }
1033 
1034 static ssize_t poll_thread_store(struct bus_type *bus,
1035 				 const char *buf, size_t count)
1036 {
1037 	int flag, rc;
1038 
1039 	if (sscanf(buf, "%d\n", &flag) != 1)
1040 		return -EINVAL;
1041 	if (flag) {
1042 		rc = ap_poll_thread_start();
1043 		if (rc)
1044 			count = rc;
1045 	} else
1046 		ap_poll_thread_stop();
1047 	return count;
1048 }
1049 
1050 static BUS_ATTR_RW(poll_thread);
1051 
1052 static ssize_t poll_timeout_show(struct bus_type *bus, char *buf)
1053 {
1054 	return scnprintf(buf, PAGE_SIZE, "%llu\n", poll_timeout);
1055 }
1056 
1057 static ssize_t poll_timeout_store(struct bus_type *bus, const char *buf,
1058 				  size_t count)
1059 {
1060 	unsigned long long time;
1061 	ktime_t hr_time;
1062 
1063 	/* 120 seconds = maximum poll interval */
1064 	if (sscanf(buf, "%llu\n", &time) != 1 || time < 1 ||
1065 	    time > 120000000000ULL)
1066 		return -EINVAL;
1067 	poll_timeout = time;
1068 	hr_time = poll_timeout;
1069 
1070 	spin_lock_bh(&ap_poll_timer_lock);
1071 	hrtimer_cancel(&ap_poll_timer);
1072 	hrtimer_set_expires(&ap_poll_timer, hr_time);
1073 	hrtimer_start_expires(&ap_poll_timer, HRTIMER_MODE_ABS);
1074 	spin_unlock_bh(&ap_poll_timer_lock);
1075 
1076 	return count;
1077 }
1078 
1079 static BUS_ATTR_RW(poll_timeout);
1080 
1081 static ssize_t ap_max_domain_id_show(struct bus_type *bus, char *buf)
1082 {
1083 	return scnprintf(buf, PAGE_SIZE, "%d\n", ap_max_domain_id);
1084 }
1085 
1086 static BUS_ATTR_RO(ap_max_domain_id);
1087 
1088 static ssize_t ap_max_adapter_id_show(struct bus_type *bus, char *buf)
1089 {
1090 	return scnprintf(buf, PAGE_SIZE, "%d\n", ap_max_adapter_id);
1091 }
1092 
1093 static BUS_ATTR_RO(ap_max_adapter_id);
1094 
1095 static ssize_t apmask_show(struct bus_type *bus, char *buf)
1096 {
1097 	int rc;
1098 
1099 	if (mutex_lock_interruptible(&ap_perms_mutex))
1100 		return -ERESTARTSYS;
1101 	rc = scnprintf(buf, PAGE_SIZE,
1102 		       "0x%016lx%016lx%016lx%016lx\n",
1103 		       ap_perms.apm[0], ap_perms.apm[1],
1104 		       ap_perms.apm[2], ap_perms.apm[3]);
1105 	mutex_unlock(&ap_perms_mutex);
1106 
1107 	return rc;
1108 }
1109 
1110 static ssize_t apmask_store(struct bus_type *bus, const char *buf,
1111 			    size_t count)
1112 {
1113 	int rc;
1114 
1115 	rc = ap_parse_mask_str(buf, ap_perms.apm, AP_DEVICES, &ap_perms_mutex);
1116 	if (rc)
1117 		return rc;
1118 
1119 	ap_bus_revise_bindings();
1120 
1121 	return count;
1122 }
1123 
1124 static BUS_ATTR_RW(apmask);
1125 
1126 static ssize_t aqmask_show(struct bus_type *bus, char *buf)
1127 {
1128 	int rc;
1129 
1130 	if (mutex_lock_interruptible(&ap_perms_mutex))
1131 		return -ERESTARTSYS;
1132 	rc = scnprintf(buf, PAGE_SIZE,
1133 		       "0x%016lx%016lx%016lx%016lx\n",
1134 		       ap_perms.aqm[0], ap_perms.aqm[1],
1135 		       ap_perms.aqm[2], ap_perms.aqm[3]);
1136 	mutex_unlock(&ap_perms_mutex);
1137 
1138 	return rc;
1139 }
1140 
1141 static ssize_t aqmask_store(struct bus_type *bus, const char *buf,
1142 			    size_t count)
1143 {
1144 	int rc;
1145 
1146 	rc = ap_parse_mask_str(buf, ap_perms.aqm, AP_DOMAINS, &ap_perms_mutex);
1147 	if (rc)
1148 		return rc;
1149 
1150 	ap_bus_revise_bindings();
1151 
1152 	return count;
1153 }
1154 
1155 static BUS_ATTR_RW(aqmask);
1156 
1157 static struct bus_attribute *const ap_bus_attrs[] = {
1158 	&bus_attr_ap_domain,
1159 	&bus_attr_ap_control_domain_mask,
1160 	&bus_attr_ap_usage_domain_mask,
1161 	&bus_attr_ap_adapter_mask,
1162 	&bus_attr_config_time,
1163 	&bus_attr_poll_thread,
1164 	&bus_attr_ap_interrupts,
1165 	&bus_attr_poll_timeout,
1166 	&bus_attr_ap_max_domain_id,
1167 	&bus_attr_ap_max_adapter_id,
1168 	&bus_attr_apmask,
1169 	&bus_attr_aqmask,
1170 	NULL,
1171 };
1172 
1173 /**
1174  * ap_select_domain(): Select an AP domain if possible and we haven't
1175  * already done so before.
1176  */
1177 static void ap_select_domain(void)
1178 {
1179 	struct ap_queue_status status;
1180 	int card, dom;
1181 
1182 	/*
1183 	 * Choose the default domain. Either the one specified with
1184 	 * the "domain=" parameter or the first domain with at least
1185 	 * one valid APQN.
1186 	 */
1187 	spin_lock_bh(&ap_domain_lock);
1188 	if (ap_domain_index >= 0) {
1189 		/* Domain has already been selected. */
1190 		goto out;
1191 	}
1192 	for (dom = 0; dom <= ap_max_domain_id; dom++) {
1193 		if (!ap_test_config_usage_domain(dom) ||
1194 		    !test_bit_inv(dom, ap_perms.aqm))
1195 			continue;
1196 		for (card = 0; card <= ap_max_adapter_id; card++) {
1197 			if (!ap_test_config_card_id(card) ||
1198 			    !test_bit_inv(card, ap_perms.apm))
1199 				continue;
1200 			status = ap_test_queue(AP_MKQID(card, dom),
1201 					       ap_apft_available(),
1202 					       NULL);
1203 			if (status.response_code == AP_RESPONSE_NORMAL)
1204 				break;
1205 		}
1206 		if (card <= ap_max_adapter_id)
1207 			break;
1208 	}
1209 	if (dom <= ap_max_domain_id) {
1210 		ap_domain_index = dom;
1211 		AP_DBF(DBF_DEBUG, "%s new default domain is %d\n",
1212 		       __func__, ap_domain_index);
1213 	}
1214 out:
1215 	spin_unlock_bh(&ap_domain_lock);
1216 }
1217 
1218 /*
1219  * This function checks the type and returns either 0 for not
1220  * supported or the highest compatible type value (which may
1221  * include the input type value).
1222  */
1223 static int ap_get_compatible_type(ap_qid_t qid, int rawtype, unsigned int func)
1224 {
1225 	int comp_type = 0;
1226 
1227 	/* < CEX2A is not supported */
1228 	if (rawtype < AP_DEVICE_TYPE_CEX2A)
1229 		return 0;
1230 	/* up to CEX7 known and fully supported */
1231 	if (rawtype <= AP_DEVICE_TYPE_CEX7)
1232 		return rawtype;
1233 	/*
1234 	 * unknown new type > CEX7, check for compatibility
1235 	 * to the highest known and supported type which is
1236 	 * currently CEX7 with the help of the QACT function.
1237 	 */
1238 	if (ap_qact_available()) {
1239 		struct ap_queue_status status;
1240 		union ap_qact_ap_info apinfo = {0};
1241 
1242 		apinfo.mode = (func >> 26) & 0x07;
1243 		apinfo.cat = AP_DEVICE_TYPE_CEX7;
1244 		status = ap_qact(qid, 0, &apinfo);
1245 		if (status.response_code == AP_RESPONSE_NORMAL
1246 		    && apinfo.cat >= AP_DEVICE_TYPE_CEX2A
1247 		    && apinfo.cat <= AP_DEVICE_TYPE_CEX7)
1248 			comp_type = apinfo.cat;
1249 	}
1250 	if (!comp_type)
1251 		AP_DBF(DBF_WARN, "queue=%02x.%04x unable to map type %d\n",
1252 		       AP_QID_CARD(qid), AP_QID_QUEUE(qid), rawtype);
1253 	else if (comp_type != rawtype)
1254 		AP_DBF(DBF_INFO, "queue=%02x.%04x map type %d to %d\n",
1255 		       AP_QID_CARD(qid), AP_QID_QUEUE(qid), rawtype, comp_type);
1256 	return comp_type;
1257 }
1258 
1259 /*
1260  * Helper function to be used with bus_find_dev
1261  * matches for the card device with the given id
1262  */
1263 static int __match_card_device_with_id(struct device *dev, const void *data)
1264 {
1265 	return is_card_dev(dev) && to_ap_card(dev)->id == (int)(long)(void *) data;
1266 }
1267 
1268 /*
1269  * Helper function to be used with bus_find_dev
1270  * matches for the queue device with a given qid
1271  */
1272 static int __match_queue_device_with_qid(struct device *dev, const void *data)
1273 {
1274 	return is_queue_dev(dev) && to_ap_queue(dev)->qid == (int)(long) data;
1275 }
1276 
1277 /*
1278  * Helper function to be used with bus_find_dev
1279  * matches any queue device with given queue id
1280  */
1281 static int __match_queue_device_with_queue_id(struct device *dev, const void *data)
1282 {
1283 	return is_queue_dev(dev)
1284 		&& AP_QID_QUEUE(to_ap_queue(dev)->qid) == (int)(long) data;
1285 }
1286 
1287 /*
1288  * Helper function for ap_scan_bus().
1289  * Does the scan bus job for the given adapter id.
1290  */
1291 static void _ap_scan_bus_adapter(int id)
1292 {
1293 	bool broken;
1294 	ap_qid_t qid;
1295 	unsigned int func;
1296 	struct ap_card *ac;
1297 	struct device *dev;
1298 	struct ap_queue *aq;
1299 	int rc, dom, depth, type, comp_type;
1300 
1301 	/* check if there is a card device registered with this id */
1302 	dev = bus_find_device(&ap_bus_type, NULL,
1303 			      (void *)(long) id,
1304 			      __match_card_device_with_id);
1305 	ac = dev ? to_ap_card(dev) : NULL;
1306 	if (!ap_test_config_card_id(id)) {
1307 		if (dev) {
1308 			/* Card device has been removed from configuration */
1309 			bus_for_each_dev(&ap_bus_type, NULL,
1310 					 (void *)(long) id,
1311 					 __ap_queue_devices_with_id_unregister);
1312 			device_unregister(dev);
1313 			put_device(dev);
1314 		}
1315 		return;
1316 	}
1317 
1318 	/*
1319 	 * This card id is enabled in the configuration. If we already have
1320 	 * a card device with this id, check if type and functions are still
1321 	 * the very same. Also verify that at least one queue is available.
1322 	 */
1323 	if (ac) {
1324 		/* find the first valid queue */
1325 		for (dom = 0; dom < AP_DOMAINS; dom++) {
1326 			qid = AP_MKQID(id, dom);
1327 			if (ap_queue_info(qid, &type, &func, &depth))
1328 				break;
1329 		}
1330 		broken = false;
1331 		if (dom >= AP_DOMAINS) {
1332 			/* no accessible queue on this card */
1333 			broken = true;
1334 		} else if (ac->raw_hwtype != type) {
1335 			/* card type has changed */
1336 			AP_DBF(DBF_INFO, "card=%02x type changed.\n", id);
1337 			broken = true;
1338 		} else if (ac->functions != func) {
1339 			/* card functions have changed */
1340 			AP_DBF(DBF_INFO, "card=%02x functions changed.\n", id);
1341 			broken = true;
1342 		}
1343 		if (broken) {
1344 			/* unregister card device and associated queues */
1345 			bus_for_each_dev(&ap_bus_type, NULL,
1346 					 (void *)(long) id,
1347 					 __ap_queue_devices_with_id_unregister);
1348 			device_unregister(dev);
1349 			put_device(dev);
1350 			/* go back if there is no valid queue on this card */
1351 			if (dom >= AP_DOMAINS)
1352 				return;
1353 			ac = NULL;
1354 		}
1355 	}
1356 
1357 	/*
1358 	 * Go through all possible queue ids. Check and maybe create or release
1359 	 * queue devices for this card. If there exists no card device yet,
1360 	 * create a card device also.
1361 	 */
1362 	for (dom = 0; dom < AP_DOMAINS; dom++) {
1363 		qid = AP_MKQID(id, dom);
1364 		dev = bus_find_device(&ap_bus_type, NULL,
1365 				      (void *)(long) qid,
1366 				      __match_queue_device_with_qid);
1367 		aq = dev ? to_ap_queue(dev) : NULL;
1368 		if (!ap_test_config_usage_domain(dom)) {
1369 			if (dev) {
1370 				/* Queue device exists but has been
1371 				 * removed from configuration.
1372 				 */
1373 				device_unregister(dev);
1374 				put_device(dev);
1375 			}
1376 			continue;
1377 		}
1378 		/* try to fetch infos about this queue */
1379 		broken = !ap_queue_info(qid, &type, &func, &depth);
1380 		if (dev) {
1381 			if (!broken) {
1382 				spin_lock_bh(&aq->lock);
1383 				broken = aq->sm_state == AP_SM_STATE_BORKED;
1384 				spin_unlock_bh(&aq->lock);
1385 			}
1386 			if (broken) {
1387 				/* Remove broken device */
1388 				AP_DBF(DBF_DEBUG,
1389 				       "removing broken queue=%02x.%04x\n",
1390 				       id, dom);
1391 				device_unregister(dev);
1392 			}
1393 			put_device(dev);
1394 			continue;
1395 		}
1396 		if (broken)
1397 			continue;
1398 		/* a new queue device is needed, check out comp type */
1399 		comp_type = ap_get_compatible_type(qid, type, func);
1400 		if (!comp_type)
1401 			continue;
1402 		/* maybe a card device needs to be created first */
1403 		if (!ac) {
1404 			ac = ap_card_create(id, depth, type, comp_type, func);
1405 			if (!ac)
1406 				continue;
1407 			ac->ap_dev.device.bus = &ap_bus_type;
1408 			ac->ap_dev.device.parent = ap_root_device;
1409 			dev_set_name(&ac->ap_dev.device, "card%02x", id);
1410 			/* Register card device with AP bus */
1411 			rc = device_register(&ac->ap_dev.device);
1412 			if (rc) {
1413 				put_device(&ac->ap_dev.device);
1414 				ac = NULL;
1415 				break;
1416 			}
1417 			/* get it and thus adjust reference counter */
1418 			get_device(&ac->ap_dev.device);
1419 		}
1420 		/* now create the new queue device */
1421 		aq = ap_queue_create(qid, comp_type);
1422 		if (!aq)
1423 			continue;
1424 		aq->card = ac;
1425 		aq->ap_dev.device.bus = &ap_bus_type;
1426 		aq->ap_dev.device.parent = &ac->ap_dev.device;
1427 		dev_set_name(&aq->ap_dev.device, "%02x.%04x", id, dom);
1428 		/* Register queue device */
1429 		rc = device_register(&aq->ap_dev.device);
1430 		if (rc) {
1431 			put_device(&aq->ap_dev.device);
1432 			continue;
1433 		}
1434 	} /* end domain loop */
1435 
1436 	if (ac)
1437 		put_device(&ac->ap_dev.device);
1438 }
1439 
1440 /**
1441  * ap_scan_bus(): Scan the AP bus for new devices
1442  * Runs periodically, workqueue timer (ap_config_time)
1443  */
1444 static void ap_scan_bus(struct work_struct *unused)
1445 {
1446 	int id;
1447 
1448 	ap_fetch_qci_info(ap_qci_info);
1449 	ap_select_domain();
1450 
1451 	AP_DBF(DBF_DEBUG, "%s running\n", __func__);
1452 
1453 	/* loop over all possible adapters */
1454 	for (id = 0; id < AP_DEVICES; id++)
1455 		_ap_scan_bus_adapter(id);
1456 
1457 	/* check if there is at least one queue available with default domain */
1458 	if (ap_domain_index >= 0) {
1459 		struct device *dev =
1460 			bus_find_device(&ap_bus_type, NULL,
1461 					(void *)(long) ap_domain_index,
1462 					__match_queue_device_with_queue_id);
1463 		if (dev)
1464 			put_device(dev);
1465 		else
1466 			AP_DBF(DBF_INFO,
1467 			       "no queue device with default domain %d available\n",
1468 			       ap_domain_index);
1469 	}
1470 
1471 	mod_timer(&ap_config_timer, jiffies + ap_config_time * HZ);
1472 }
1473 
1474 static void ap_config_timeout(struct timer_list *unused)
1475 {
1476 	queue_work(system_long_wq, &ap_scan_work);
1477 }
1478 
1479 static int __init ap_debug_init(void)
1480 {
1481 	ap_dbf_info = debug_register("ap", 1, 1,
1482 				     DBF_MAX_SPRINTF_ARGS * sizeof(long));
1483 	debug_register_view(ap_dbf_info, &debug_sprintf_view);
1484 	debug_set_level(ap_dbf_info, DBF_ERR);
1485 
1486 	return 0;
1487 }
1488 
1489 static void __init ap_perms_init(void)
1490 {
1491 	/* all resources useable if no kernel parameter string given */
1492 	memset(&ap_perms.ioctlm, 0xFF, sizeof(ap_perms.ioctlm));
1493 	memset(&ap_perms.apm, 0xFF, sizeof(ap_perms.apm));
1494 	memset(&ap_perms.aqm, 0xFF, sizeof(ap_perms.aqm));
1495 
1496 	/* apm kernel parameter string */
1497 	if (apm_str) {
1498 		memset(&ap_perms.apm, 0, sizeof(ap_perms.apm));
1499 		ap_parse_mask_str(apm_str, ap_perms.apm, AP_DEVICES,
1500 				  &ap_perms_mutex);
1501 	}
1502 
1503 	/* aqm kernel parameter string */
1504 	if (aqm_str) {
1505 		memset(&ap_perms.aqm, 0, sizeof(ap_perms.aqm));
1506 		ap_parse_mask_str(aqm_str, ap_perms.aqm, AP_DOMAINS,
1507 				  &ap_perms_mutex);
1508 	}
1509 }
1510 
1511 /**
1512  * ap_module_init(): The module initialization code.
1513  *
1514  * Initializes the module.
1515  */
1516 static int __init ap_module_init(void)
1517 {
1518 	int rc, i;
1519 
1520 	rc = ap_debug_init();
1521 	if (rc)
1522 		return rc;
1523 
1524 	if (!ap_instructions_available()) {
1525 		pr_warn("The hardware system does not support AP instructions\n");
1526 		return -ENODEV;
1527 	}
1528 
1529 	/* init ap_queue hashtable */
1530 	hash_init(ap_queues);
1531 
1532 	/* set up the AP permissions (ioctls, ap and aq masks) */
1533 	ap_perms_init();
1534 
1535 	/* Get AP configuration data if available */
1536 	ap_init_qci_info();
1537 
1538 	/* check default domain setting */
1539 	if (ap_domain_index < -1 || ap_domain_index > ap_max_domain_id ||
1540 	    (ap_domain_index >= 0 &&
1541 	     !test_bit_inv(ap_domain_index, ap_perms.aqm))) {
1542 		pr_warn("%d is not a valid cryptographic domain\n",
1543 			ap_domain_index);
1544 		ap_domain_index = -1;
1545 	}
1546 
1547 	/* enable interrupts if available */
1548 	if (ap_interrupts_available()) {
1549 		rc = register_adapter_interrupt(&ap_airq);
1550 		ap_airq_flag = (rc == 0);
1551 	}
1552 
1553 	/* Create /sys/bus/ap. */
1554 	rc = bus_register(&ap_bus_type);
1555 	if (rc)
1556 		goto out;
1557 	for (i = 0; ap_bus_attrs[i]; i++) {
1558 		rc = bus_create_file(&ap_bus_type, ap_bus_attrs[i]);
1559 		if (rc)
1560 			goto out_bus;
1561 	}
1562 
1563 	/* Create /sys/devices/ap. */
1564 	ap_root_device = root_device_register("ap");
1565 	rc = PTR_ERR_OR_ZERO(ap_root_device);
1566 	if (rc)
1567 		goto out_bus;
1568 
1569 	/* Setup the AP bus rescan timer. */
1570 	timer_setup(&ap_config_timer, ap_config_timeout, 0);
1571 
1572 	/*
1573 	 * Setup the high resultion poll timer.
1574 	 * If we are running under z/VM adjust polling to z/VM polling rate.
1575 	 */
1576 	if (MACHINE_IS_VM)
1577 		poll_timeout = 1500000;
1578 	spin_lock_init(&ap_poll_timer_lock);
1579 	hrtimer_init(&ap_poll_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
1580 	ap_poll_timer.function = ap_poll_timeout;
1581 
1582 	/* Start the low priority AP bus poll thread. */
1583 	if (ap_thread_flag) {
1584 		rc = ap_poll_thread_start();
1585 		if (rc)
1586 			goto out_work;
1587 	}
1588 
1589 	queue_work(system_long_wq, &ap_scan_work);
1590 
1591 	return 0;
1592 
1593 out_work:
1594 	hrtimer_cancel(&ap_poll_timer);
1595 	root_device_unregister(ap_root_device);
1596 out_bus:
1597 	while (i--)
1598 		bus_remove_file(&ap_bus_type, ap_bus_attrs[i]);
1599 	bus_unregister(&ap_bus_type);
1600 out:
1601 	if (ap_using_interrupts())
1602 		unregister_adapter_interrupt(&ap_airq);
1603 	kfree(ap_qci_info);
1604 	return rc;
1605 }
1606 device_initcall(ap_module_init);
1607