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