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