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