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