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