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