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