1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright IBM Corp. 2006, 2012
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  *
10  * Adjunct processor bus.
11  */
12 
13 #define KMSG_COMPONENT "ap"
14 #define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
15 
16 #include <linux/kernel_stat.h>
17 #include <linux/moduleparam.h>
18 #include <linux/init.h>
19 #include <linux/delay.h>
20 #include <linux/err.h>
21 #include <linux/interrupt.h>
22 #include <linux/workqueue.h>
23 #include <linux/slab.h>
24 #include <linux/notifier.h>
25 #include <linux/kthread.h>
26 #include <linux/mutex.h>
27 #include <linux/suspend.h>
28 #include <asm/airq.h>
29 #include <linux/atomic.h>
30 #include <asm/isc.h>
31 #include <linux/hrtimer.h>
32 #include <linux/ktime.h>
33 #include <asm/facility.h>
34 #include <linux/crypto.h>
35 #include <linux/mod_devicetable.h>
36 #include <linux/debugfs.h>
37 #include <linux/ctype.h>
38 
39 #include "ap_bus.h"
40 #include "ap_debug.h"
41 
42 /*
43  * Module parameters; note though this file itself isn't modular.
44  */
45 int ap_domain_index = -1;	/* Adjunct Processor Domain Index */
46 static DEFINE_SPINLOCK(ap_domain_lock);
47 module_param_named(domain, ap_domain_index, int, 0440);
48 MODULE_PARM_DESC(domain, "domain index for ap devices");
49 EXPORT_SYMBOL(ap_domain_index);
50 
51 static int ap_thread_flag;
52 module_param_named(poll_thread, ap_thread_flag, int, 0440);
53 MODULE_PARM_DESC(poll_thread, "Turn on/off poll thread, default is 0 (off).");
54 
55 static char *apm_str;
56 module_param_named(apmask, apm_str, charp, 0440);
57 MODULE_PARM_DESC(apmask, "AP bus adapter mask.");
58 
59 static char *aqm_str;
60 module_param_named(aqmask, aqm_str, charp, 0440);
61 MODULE_PARM_DESC(aqmask, "AP bus domain mask.");
62 
63 static struct device *ap_root_device;
64 
65 DEFINE_SPINLOCK(ap_list_lock);
66 LIST_HEAD(ap_card_list);
67 
68 /* Default permissions (card and domain masking) */
69 static struct ap_perms {
70 	DECLARE_BITMAP(apm, AP_DEVICES);
71 	DECLARE_BITMAP(aqm, AP_DOMAINS);
72 } ap_perms;
73 static DEFINE_MUTEX(ap_perms_mutex);
74 
75 static struct ap_config_info *ap_configuration;
76 static bool initialised;
77 
78 /*
79  * AP bus related debug feature things.
80  */
81 debug_info_t *ap_dbf_info;
82 
83 /*
84  * Workqueue timer for bus rescan.
85  */
86 static struct timer_list ap_config_timer;
87 static int ap_config_time = AP_CONFIG_TIME;
88 static void ap_scan_bus(struct work_struct *);
89 static DECLARE_WORK(ap_scan_work, ap_scan_bus);
90 
91 /*
92  * Tasklet & timer for AP request polling and interrupts
93  */
94 static void ap_tasklet_fn(unsigned long);
95 static DECLARE_TASKLET(ap_tasklet, ap_tasklet_fn, 0);
96 static DECLARE_WAIT_QUEUE_HEAD(ap_poll_wait);
97 static struct task_struct *ap_poll_kthread;
98 static DEFINE_MUTEX(ap_poll_thread_mutex);
99 static DEFINE_SPINLOCK(ap_poll_timer_lock);
100 static struct hrtimer ap_poll_timer;
101 /*
102  * In LPAR poll with 4kHz frequency. Poll every 250000 nanoseconds.
103  * If z/VM change to 1500000 nanoseconds to adjust to z/VM polling.
104  */
105 static unsigned long long poll_timeout = 250000;
106 
107 /* Suspend flag */
108 static int ap_suspend_flag;
109 /* Maximum domain id */
110 static int ap_max_domain_id;
111 /*
112  * Flag to check if domain was set through module parameter domain=. This is
113  * important when supsend and resume is done in a z/VM environment where the
114  * domain might change.
115  */
116 static int user_set_domain;
117 static struct bus_type ap_bus_type;
118 
119 /* Adapter interrupt definitions */
120 static void ap_interrupt_handler(struct airq_struct *airq);
121 
122 static int ap_airq_flag;
123 
124 static struct airq_struct ap_airq = {
125 	.handler = ap_interrupt_handler,
126 	.isc = AP_ISC,
127 };
128 
129 /**
130  * ap_using_interrupts() - Returns non-zero if interrupt support is
131  * available.
132  */
ap_using_interrupts(void)133 static inline int ap_using_interrupts(void)
134 {
135 	return ap_airq_flag;
136 }
137 
138 /**
139  * ap_airq_ptr() - Get the address of the adapter interrupt indicator
140  *
141  * Returns the address of the local-summary-indicator of the adapter
142  * interrupt handler for AP, or NULL if adapter interrupts are not
143  * available.
144  */
ap_airq_ptr(void)145 void *ap_airq_ptr(void)
146 {
147 	if (ap_using_interrupts())
148 		return ap_airq.lsi_ptr;
149 	return NULL;
150 }
151 
152 /**
153  * ap_interrupts_available(): Test if AP interrupts are available.
154  *
155  * Returns 1 if AP interrupts are available.
156  */
ap_interrupts_available(void)157 static int ap_interrupts_available(void)
158 {
159 	return test_facility(65);
160 }
161 
162 /**
163  * ap_configuration_available(): Test if AP configuration
164  * information is available.
165  *
166  * Returns 1 if AP configuration information is available.
167  */
ap_configuration_available(void)168 static int ap_configuration_available(void)
169 {
170 	return test_facility(12);
171 }
172 
173 /**
174  * ap_apft_available(): Test if AP facilities test (APFT)
175  * facility is available.
176  *
177  * Returns 1 if APFT is is available.
178  */
ap_apft_available(void)179 static int ap_apft_available(void)
180 {
181 	return test_facility(15);
182 }
183 
184 /*
185  * ap_qact_available(): Test if the PQAP(QACT) subfunction is available.
186  *
187  * Returns 1 if the QACT subfunction is available.
188  */
ap_qact_available(void)189 static inline int ap_qact_available(void)
190 {
191 	if (ap_configuration)
192 		return ap_configuration->qact;
193 	return 0;
194 }
195 
196 /*
197  * ap_query_configuration(): Fetch cryptographic config info
198  *
199  * Returns the ap configuration info fetched via PQAP(QCI).
200  * On success 0 is returned, on failure a negative errno
201  * is returned, e.g. if the PQAP(QCI) instruction is not
202  * available, the return value will be -EOPNOTSUPP.
203  */
ap_query_configuration(struct ap_config_info * info)204 static inline int ap_query_configuration(struct ap_config_info *info)
205 {
206 	if (!ap_configuration_available())
207 		return -EOPNOTSUPP;
208 	if (!info)
209 		return -EINVAL;
210 	return ap_qci(info);
211 }
212 EXPORT_SYMBOL(ap_query_configuration);
213 
214 /**
215  * ap_init_configuration(): Allocate and query configuration array.
216  */
ap_init_configuration(void)217 static void ap_init_configuration(void)
218 {
219 	if (!ap_configuration_available())
220 		return;
221 
222 	ap_configuration = kzalloc(sizeof(*ap_configuration), GFP_KERNEL);
223 	if (!ap_configuration)
224 		return;
225 	if (ap_query_configuration(ap_configuration) != 0) {
226 		kfree(ap_configuration);
227 		ap_configuration = NULL;
228 		return;
229 	}
230 }
231 
232 /*
233  * ap_test_config(): helper function to extract the nrth bit
234  *		     within the unsigned int array field.
235  */
ap_test_config(unsigned int * field,unsigned int nr)236 static inline int ap_test_config(unsigned int *field, unsigned int nr)
237 {
238 	return ap_test_bit((field + (nr >> 5)), (nr & 0x1f));
239 }
240 
241 /*
242  * ap_test_config_card_id(): Test, whether an AP card ID is configured.
243  * @id AP card ID
244  *
245  * Returns 0 if the card is not configured
246  *	   1 if the card is configured or
247  *	     if the configuration information is not available
248  */
ap_test_config_card_id(unsigned int id)249 static inline int ap_test_config_card_id(unsigned int id)
250 {
251 	if (!ap_configuration)	/* QCI not supported */
252 		/* only ids 0...3F may be probed */
253 		return id < 0x40 ? 1 : 0;
254 	return ap_test_config(ap_configuration->apm, id);
255 }
256 
257 /*
258  * ap_test_config_domain(): Test, whether an AP usage domain is configured.
259  * @domain AP usage domain ID
260  *
261  * Returns 0 if the usage domain is not configured
262  *	   1 if the usage domain is configured or
263  *	     if the configuration information is not available
264  */
ap_test_config_domain(unsigned int domain)265 static inline int ap_test_config_domain(unsigned int domain)
266 {
267 	if (!ap_configuration)	/* QCI not supported */
268 		return domain < 16;
269 	return ap_test_config(ap_configuration->aqm, domain);
270 }
271 
272 /**
273  * ap_query_queue(): Check if an AP queue is available.
274  * @qid: The AP queue number
275  * @queue_depth: Pointer to queue depth value
276  * @device_type: Pointer to device type value
277  * @facilities: Pointer to facility indicator
278  */
ap_query_queue(ap_qid_t qid,int * queue_depth,int * device_type,unsigned int * facilities)279 static int ap_query_queue(ap_qid_t qid, int *queue_depth, int *device_type,
280 			  unsigned int *facilities)
281 {
282 	struct ap_queue_status status;
283 	unsigned long info;
284 	int nd;
285 
286 	if (!ap_test_config_card_id(AP_QID_CARD(qid)))
287 		return -ENODEV;
288 
289 	status = ap_test_queue(qid, ap_apft_available(), &info);
290 	switch (status.response_code) {
291 	case AP_RESPONSE_NORMAL:
292 		*queue_depth = (int)(info & 0xff);
293 		*device_type = (int)((info >> 24) & 0xff);
294 		*facilities = (unsigned int)(info >> 32);
295 		/* Update maximum domain id */
296 		nd = (info >> 16) & 0xff;
297 		/* if N bit is available, z13 and newer */
298 		if ((info & (1UL << 57)) && nd > 0)
299 			ap_max_domain_id = nd;
300 		else /* older machine types */
301 			ap_max_domain_id = 15;
302 		switch (*device_type) {
303 			/* For CEX2 and CEX3 the available functions
304 			 * are not refrected by the facilities bits.
305 			 * Instead it is coded into the type. So here
306 			 * modify the function bits based on the type.
307 			 */
308 		case AP_DEVICE_TYPE_CEX2A:
309 		case AP_DEVICE_TYPE_CEX3A:
310 			*facilities |= 0x08000000;
311 			break;
312 		case AP_DEVICE_TYPE_CEX2C:
313 		case AP_DEVICE_TYPE_CEX3C:
314 			*facilities |= 0x10000000;
315 			break;
316 		default:
317 			break;
318 		}
319 		return 0;
320 	case AP_RESPONSE_Q_NOT_AVAIL:
321 	case AP_RESPONSE_DECONFIGURED:
322 	case AP_RESPONSE_CHECKSTOPPED:
323 	case AP_RESPONSE_INVALID_ADDRESS:
324 		return -ENODEV;
325 	case AP_RESPONSE_RESET_IN_PROGRESS:
326 	case AP_RESPONSE_OTHERWISE_CHANGED:
327 	case AP_RESPONSE_BUSY:
328 		return -EBUSY;
329 	default:
330 		BUG();
331 	}
332 }
333 
ap_wait(enum ap_wait wait)334 void ap_wait(enum ap_wait wait)
335 {
336 	ktime_t hr_time;
337 
338 	switch (wait) {
339 	case AP_WAIT_AGAIN:
340 	case AP_WAIT_INTERRUPT:
341 		if (ap_using_interrupts())
342 			break;
343 		if (ap_poll_kthread) {
344 			wake_up(&ap_poll_wait);
345 			break;
346 		}
347 		/* Fall through */
348 	case AP_WAIT_TIMEOUT:
349 		spin_lock_bh(&ap_poll_timer_lock);
350 		if (!hrtimer_is_queued(&ap_poll_timer)) {
351 			hr_time = poll_timeout;
352 			hrtimer_forward_now(&ap_poll_timer, hr_time);
353 			hrtimer_restart(&ap_poll_timer);
354 		}
355 		spin_unlock_bh(&ap_poll_timer_lock);
356 		break;
357 	case AP_WAIT_NONE:
358 	default:
359 		break;
360 	}
361 }
362 
363 /**
364  * ap_request_timeout(): Handling of request timeouts
365  * @t: timer making this callback
366  *
367  * Handles request timeouts.
368  */
ap_request_timeout(struct timer_list * t)369 void ap_request_timeout(struct timer_list *t)
370 {
371 	struct ap_queue *aq = from_timer(aq, t, timeout);
372 
373 	if (ap_suspend_flag)
374 		return;
375 	spin_lock_bh(&aq->lock);
376 	ap_wait(ap_sm_event(aq, AP_EVENT_TIMEOUT));
377 	spin_unlock_bh(&aq->lock);
378 }
379 
380 /**
381  * ap_poll_timeout(): AP receive polling for finished AP requests.
382  * @unused: Unused pointer.
383  *
384  * Schedules the AP tasklet using a high resolution timer.
385  */
ap_poll_timeout(struct hrtimer * unused)386 static enum hrtimer_restart ap_poll_timeout(struct hrtimer *unused)
387 {
388 	if (!ap_suspend_flag)
389 		tasklet_schedule(&ap_tasklet);
390 	return HRTIMER_NORESTART;
391 }
392 
393 /**
394  * ap_interrupt_handler() - Schedule ap_tasklet on interrupt
395  * @airq: pointer to adapter interrupt descriptor
396  */
ap_interrupt_handler(struct airq_struct * airq)397 static void ap_interrupt_handler(struct airq_struct *airq)
398 {
399 	inc_irq_stat(IRQIO_APB);
400 	if (!ap_suspend_flag)
401 		tasklet_schedule(&ap_tasklet);
402 }
403 
404 /**
405  * ap_tasklet_fn(): Tasklet to poll all AP devices.
406  * @dummy: Unused variable
407  *
408  * Poll all AP devices on the bus.
409  */
ap_tasklet_fn(unsigned long dummy)410 static void ap_tasklet_fn(unsigned long dummy)
411 {
412 	struct ap_card *ac;
413 	struct ap_queue *aq;
414 	enum ap_wait wait = AP_WAIT_NONE;
415 
416 	/* Reset the indicator if interrupts are used. Thus new interrupts can
417 	 * be received. Doing it in the beginning of the tasklet is therefor
418 	 * important that no requests on any AP get lost.
419 	 */
420 	if (ap_using_interrupts())
421 		xchg(ap_airq.lsi_ptr, 0);
422 
423 	spin_lock_bh(&ap_list_lock);
424 	for_each_ap_card(ac) {
425 		for_each_ap_queue(aq, ac) {
426 			spin_lock_bh(&aq->lock);
427 			wait = min(wait, ap_sm_event_loop(aq, AP_EVENT_POLL));
428 			spin_unlock_bh(&aq->lock);
429 		}
430 	}
431 	spin_unlock_bh(&ap_list_lock);
432 
433 	ap_wait(wait);
434 }
435 
ap_pending_requests(void)436 static int ap_pending_requests(void)
437 {
438 	struct ap_card *ac;
439 	struct ap_queue *aq;
440 
441 	spin_lock_bh(&ap_list_lock);
442 	for_each_ap_card(ac) {
443 		for_each_ap_queue(aq, ac) {
444 			if (aq->queue_count == 0)
445 				continue;
446 			spin_unlock_bh(&ap_list_lock);
447 			return 1;
448 		}
449 	}
450 	spin_unlock_bh(&ap_list_lock);
451 	return 0;
452 }
453 
454 /**
455  * ap_poll_thread(): Thread that polls for finished requests.
456  * @data: Unused pointer
457  *
458  * AP bus poll thread. The purpose of this thread is to poll for
459  * finished requests in a loop if there is a "free" cpu - that is
460  * a cpu that doesn't have anything better to do. The polling stops
461  * as soon as there is another task or if all messages have been
462  * delivered.
463  */
ap_poll_thread(void * data)464 static int ap_poll_thread(void *data)
465 {
466 	DECLARE_WAITQUEUE(wait, current);
467 
468 	set_user_nice(current, MAX_NICE);
469 	set_freezable();
470 	while (!kthread_should_stop()) {
471 		add_wait_queue(&ap_poll_wait, &wait);
472 		set_current_state(TASK_INTERRUPTIBLE);
473 		if (ap_suspend_flag || !ap_pending_requests()) {
474 			schedule();
475 			try_to_freeze();
476 		}
477 		set_current_state(TASK_RUNNING);
478 		remove_wait_queue(&ap_poll_wait, &wait);
479 		if (need_resched()) {
480 			schedule();
481 			try_to_freeze();
482 			continue;
483 		}
484 		ap_tasklet_fn(0);
485 	}
486 
487 	return 0;
488 }
489 
ap_poll_thread_start(void)490 static int ap_poll_thread_start(void)
491 {
492 	int rc;
493 
494 	if (ap_using_interrupts() || ap_poll_kthread)
495 		return 0;
496 	mutex_lock(&ap_poll_thread_mutex);
497 	ap_poll_kthread = kthread_run(ap_poll_thread, NULL, "appoll");
498 	rc = PTR_ERR_OR_ZERO(ap_poll_kthread);
499 	if (rc)
500 		ap_poll_kthread = NULL;
501 	mutex_unlock(&ap_poll_thread_mutex);
502 	return rc;
503 }
504 
ap_poll_thread_stop(void)505 static void ap_poll_thread_stop(void)
506 {
507 	if (!ap_poll_kthread)
508 		return;
509 	mutex_lock(&ap_poll_thread_mutex);
510 	kthread_stop(ap_poll_kthread);
511 	ap_poll_kthread = NULL;
512 	mutex_unlock(&ap_poll_thread_mutex);
513 }
514 
515 #define is_card_dev(x) ((x)->parent == ap_root_device)
516 #define is_queue_dev(x) ((x)->parent != ap_root_device)
517 
518 /**
519  * ap_bus_match()
520  * @dev: Pointer to device
521  * @drv: Pointer to device_driver
522  *
523  * AP bus driver registration/unregistration.
524  */
ap_bus_match(struct device * dev,struct device_driver * drv)525 static int ap_bus_match(struct device *dev, struct device_driver *drv)
526 {
527 	struct ap_driver *ap_drv = to_ap_drv(drv);
528 	struct ap_device_id *id;
529 
530 	/*
531 	 * Compare device type of the device with the list of
532 	 * supported types of the device_driver.
533 	 */
534 	for (id = ap_drv->ids; id->match_flags; id++) {
535 		if (is_card_dev(dev) &&
536 		    id->match_flags & AP_DEVICE_ID_MATCH_CARD_TYPE &&
537 		    id->dev_type == to_ap_dev(dev)->device_type)
538 			return 1;
539 		if (is_queue_dev(dev) &&
540 		    id->match_flags & AP_DEVICE_ID_MATCH_QUEUE_TYPE &&
541 		    id->dev_type == to_ap_dev(dev)->device_type)
542 			return 1;
543 	}
544 	return 0;
545 }
546 
547 /**
548  * ap_uevent(): Uevent function for AP devices.
549  * @dev: Pointer to device
550  * @env: Pointer to kobj_uevent_env
551  *
552  * It sets up a single environment variable DEV_TYPE which contains the
553  * hardware device type.
554  */
ap_uevent(struct device * dev,struct kobj_uevent_env * env)555 static int ap_uevent(struct device *dev, struct kobj_uevent_env *env)
556 {
557 	struct ap_device *ap_dev = to_ap_dev(dev);
558 	int retval = 0;
559 
560 	if (!ap_dev)
561 		return -ENODEV;
562 
563 	/* Set up DEV_TYPE environment variable. */
564 	retval = add_uevent_var(env, "DEV_TYPE=%04X", ap_dev->device_type);
565 	if (retval)
566 		return retval;
567 
568 	/* Add MODALIAS= */
569 	retval = add_uevent_var(env, "MODALIAS=ap:t%02X", ap_dev->device_type);
570 
571 	return retval;
572 }
573 
ap_dev_suspend(struct device * dev)574 static int ap_dev_suspend(struct device *dev)
575 {
576 	struct ap_device *ap_dev = to_ap_dev(dev);
577 
578 	if (ap_dev->drv && ap_dev->drv->suspend)
579 		ap_dev->drv->suspend(ap_dev);
580 	return 0;
581 }
582 
ap_dev_resume(struct device * dev)583 static int ap_dev_resume(struct device *dev)
584 {
585 	struct ap_device *ap_dev = to_ap_dev(dev);
586 
587 	if (ap_dev->drv && ap_dev->drv->resume)
588 		ap_dev->drv->resume(ap_dev);
589 	return 0;
590 }
591 
ap_bus_suspend(void)592 static void ap_bus_suspend(void)
593 {
594 	AP_DBF(DBF_DEBUG, "%s running\n", __func__);
595 
596 	ap_suspend_flag = 1;
597 	/*
598 	 * Disable scanning for devices, thus we do not want to scan
599 	 * for them after removing.
600 	 */
601 	flush_work(&ap_scan_work);
602 	tasklet_disable(&ap_tasklet);
603 }
604 
__ap_card_devices_unregister(struct device * dev,void * dummy)605 static int __ap_card_devices_unregister(struct device *dev, void *dummy)
606 {
607 	if (is_card_dev(dev))
608 		device_unregister(dev);
609 	return 0;
610 }
611 
__ap_queue_devices_unregister(struct device * dev,void * dummy)612 static int __ap_queue_devices_unregister(struct device *dev, void *dummy)
613 {
614 	if (is_queue_dev(dev))
615 		device_unregister(dev);
616 	return 0;
617 }
618 
__ap_queue_devices_with_id_unregister(struct device * dev,void * data)619 static int __ap_queue_devices_with_id_unregister(struct device *dev, void *data)
620 {
621 	if (is_queue_dev(dev) &&
622 	    AP_QID_CARD(to_ap_queue(dev)->qid) == (int)(long) data)
623 		device_unregister(dev);
624 	return 0;
625 }
626 
ap_bus_resume(void)627 static void ap_bus_resume(void)
628 {
629 	int rc;
630 
631 	AP_DBF(DBF_DEBUG, "%s running\n", __func__);
632 
633 	/* remove all queue devices */
634 	bus_for_each_dev(&ap_bus_type, NULL, NULL,
635 			 __ap_queue_devices_unregister);
636 	/* remove all card devices */
637 	bus_for_each_dev(&ap_bus_type, NULL, NULL,
638 			 __ap_card_devices_unregister);
639 
640 	/* Reset thin interrupt setting */
641 	if (ap_interrupts_available() && !ap_using_interrupts()) {
642 		rc = register_adapter_interrupt(&ap_airq);
643 		ap_airq_flag = (rc == 0);
644 	}
645 	if (!ap_interrupts_available() && ap_using_interrupts()) {
646 		unregister_adapter_interrupt(&ap_airq);
647 		ap_airq_flag = 0;
648 	}
649 	/* Reset domain */
650 	if (!user_set_domain)
651 		ap_domain_index = -1;
652 	/* Get things going again */
653 	ap_suspend_flag = 0;
654 	if (ap_airq_flag)
655 		xchg(ap_airq.lsi_ptr, 0);
656 	tasklet_enable(&ap_tasklet);
657 	queue_work(system_long_wq, &ap_scan_work);
658 }
659 
ap_power_event(struct notifier_block * this,unsigned long event,void * ptr)660 static int ap_power_event(struct notifier_block *this, unsigned long event,
661 			  void *ptr)
662 {
663 	switch (event) {
664 	case PM_HIBERNATION_PREPARE:
665 	case PM_SUSPEND_PREPARE:
666 		ap_bus_suspend();
667 		break;
668 	case PM_POST_HIBERNATION:
669 	case PM_POST_SUSPEND:
670 		ap_bus_resume();
671 		break;
672 	default:
673 		break;
674 	}
675 	return NOTIFY_DONE;
676 }
677 static struct notifier_block ap_power_notifier = {
678 	.notifier_call = ap_power_event,
679 };
680 
681 static SIMPLE_DEV_PM_OPS(ap_bus_pm_ops, ap_dev_suspend, ap_dev_resume);
682 
683 static struct bus_type ap_bus_type = {
684 	.name = "ap",
685 	.match = &ap_bus_match,
686 	.uevent = &ap_uevent,
687 	.pm = &ap_bus_pm_ops,
688 };
689 
__ap_revise_reserved(struct device * dev,void * dummy)690 static int __ap_revise_reserved(struct device *dev, void *dummy)
691 {
692 	int rc, card, queue, devres, drvres;
693 
694 	if (is_queue_dev(dev)) {
695 		card = AP_QID_CARD(to_ap_queue(dev)->qid);
696 		queue = AP_QID_QUEUE(to_ap_queue(dev)->qid);
697 		mutex_lock(&ap_perms_mutex);
698 		devres = test_bit_inv(card, ap_perms.apm)
699 			&& test_bit_inv(queue, ap_perms.aqm);
700 		mutex_unlock(&ap_perms_mutex);
701 		drvres = to_ap_drv(dev->driver)->flags
702 			& AP_DRIVER_FLAG_DEFAULT;
703 		if (!!devres != !!drvres) {
704 			AP_DBF(DBF_DEBUG, "reprobing queue=%02x.%04x\n",
705 			       card, queue);
706 			rc = device_reprobe(dev);
707 		}
708 	}
709 
710 	return 0;
711 }
712 
ap_bus_revise_bindings(void)713 static void ap_bus_revise_bindings(void)
714 {
715 	bus_for_each_dev(&ap_bus_type, NULL, NULL, __ap_revise_reserved);
716 }
717 
ap_owned_by_def_drv(int card,int queue)718 int ap_owned_by_def_drv(int card, int queue)
719 {
720 	int rc = 0;
721 
722 	if (card < 0 || card >= AP_DEVICES || queue < 0 || queue >= AP_DOMAINS)
723 		return -EINVAL;
724 
725 	mutex_lock(&ap_perms_mutex);
726 
727 	if (test_bit_inv(card, ap_perms.apm)
728 	    && test_bit_inv(queue, ap_perms.aqm))
729 		rc = 1;
730 
731 	mutex_unlock(&ap_perms_mutex);
732 
733 	return rc;
734 }
735 EXPORT_SYMBOL(ap_owned_by_def_drv);
736 
ap_apqn_in_matrix_owned_by_def_drv(unsigned long * apm,unsigned long * aqm)737 int ap_apqn_in_matrix_owned_by_def_drv(unsigned long *apm,
738 				       unsigned long *aqm)
739 {
740 	int card, queue, rc = 0;
741 
742 	mutex_lock(&ap_perms_mutex);
743 
744 	for (card = 0; !rc && card < AP_DEVICES; card++)
745 		if (test_bit_inv(card, apm) &&
746 		    test_bit_inv(card, ap_perms.apm))
747 			for (queue = 0; !rc && queue < AP_DOMAINS; queue++)
748 				if (test_bit_inv(queue, aqm) &&
749 				    test_bit_inv(queue, ap_perms.aqm))
750 					rc = 1;
751 
752 	mutex_unlock(&ap_perms_mutex);
753 
754 	return rc;
755 }
756 EXPORT_SYMBOL(ap_apqn_in_matrix_owned_by_def_drv);
757 
ap_device_probe(struct device * dev)758 static int ap_device_probe(struct device *dev)
759 {
760 	struct ap_device *ap_dev = to_ap_dev(dev);
761 	struct ap_driver *ap_drv = to_ap_drv(dev->driver);
762 	int card, queue, devres, drvres, rc;
763 
764 	if (is_queue_dev(dev)) {
765 		/*
766 		 * If the apqn is marked as reserved/used by ap bus and
767 		 * default drivers, only probe with drivers with the default
768 		 * flag set. If it is not marked, only probe with drivers
769 		 * with the default flag not set.
770 		 */
771 		card = AP_QID_CARD(to_ap_queue(dev)->qid);
772 		queue = AP_QID_QUEUE(to_ap_queue(dev)->qid);
773 		mutex_lock(&ap_perms_mutex);
774 		devres = test_bit_inv(card, ap_perms.apm)
775 			&& test_bit_inv(queue, ap_perms.aqm);
776 		mutex_unlock(&ap_perms_mutex);
777 		drvres = ap_drv->flags & AP_DRIVER_FLAG_DEFAULT;
778 		if (!!devres != !!drvres)
779 			return -ENODEV;
780 		/* (re-)init queue's state machine */
781 		ap_queue_reinit_state(to_ap_queue(dev));
782 	}
783 
784 	/* Add queue/card to list of active queues/cards */
785 	spin_lock_bh(&ap_list_lock);
786 	if (is_card_dev(dev))
787 		list_add(&to_ap_card(dev)->list, &ap_card_list);
788 	else
789 		list_add(&to_ap_queue(dev)->list,
790 			 &to_ap_queue(dev)->card->queues);
791 	spin_unlock_bh(&ap_list_lock);
792 
793 	ap_dev->drv = ap_drv;
794 	rc = ap_drv->probe ? ap_drv->probe(ap_dev) : -ENODEV;
795 
796 	if (rc) {
797 		spin_lock_bh(&ap_list_lock);
798 		if (is_card_dev(dev))
799 			list_del_init(&to_ap_card(dev)->list);
800 		else
801 			list_del_init(&to_ap_queue(dev)->list);
802 		spin_unlock_bh(&ap_list_lock);
803 		ap_dev->drv = NULL;
804 	}
805 
806 	return rc;
807 }
808 
ap_device_remove(struct device * dev)809 static int ap_device_remove(struct device *dev)
810 {
811 	struct ap_device *ap_dev = to_ap_dev(dev);
812 	struct ap_driver *ap_drv = ap_dev->drv;
813 
814 	if (is_queue_dev(dev))
815 		ap_queue_remove(to_ap_queue(dev));
816 	if (ap_drv->remove)
817 		ap_drv->remove(ap_dev);
818 
819 	/* Remove queue/card from list of active queues/cards */
820 	spin_lock_bh(&ap_list_lock);
821 	if (is_card_dev(dev))
822 		list_del_init(&to_ap_card(dev)->list);
823 	else
824 		list_del_init(&to_ap_queue(dev)->list);
825 	spin_unlock_bh(&ap_list_lock);
826 
827 	return 0;
828 }
829 
ap_driver_register(struct ap_driver * ap_drv,struct module * owner,char * name)830 int ap_driver_register(struct ap_driver *ap_drv, struct module *owner,
831 		       char *name)
832 {
833 	struct device_driver *drv = &ap_drv->driver;
834 
835 	if (!initialised)
836 		return -ENODEV;
837 
838 	drv->bus = &ap_bus_type;
839 	drv->probe = ap_device_probe;
840 	drv->remove = ap_device_remove;
841 	drv->owner = owner;
842 	drv->name = name;
843 	return driver_register(drv);
844 }
845 EXPORT_SYMBOL(ap_driver_register);
846 
ap_driver_unregister(struct ap_driver * ap_drv)847 void ap_driver_unregister(struct ap_driver *ap_drv)
848 {
849 	driver_unregister(&ap_drv->driver);
850 }
851 EXPORT_SYMBOL(ap_driver_unregister);
852 
ap_bus_force_rescan(void)853 void ap_bus_force_rescan(void)
854 {
855 	if (ap_suspend_flag)
856 		return;
857 	/* processing a asynchronous bus rescan */
858 	del_timer(&ap_config_timer);
859 	queue_work(system_long_wq, &ap_scan_work);
860 	flush_work(&ap_scan_work);
861 }
862 EXPORT_SYMBOL(ap_bus_force_rescan);
863 
864 /*
865  * hex2bitmap() - parse hex mask string and set bitmap.
866  * Valid strings are "0x012345678" with at least one valid hex number.
867  * Rest of the bitmap to the right is padded with 0. No spaces allowed
868  * within the string, the leading 0x may be omitted.
869  * Returns the bitmask with exactly the bits set as given by the hex
870  * string (both in big endian order).
871  */
hex2bitmap(const char * str,unsigned long * bitmap,int bits)872 static int hex2bitmap(const char *str, unsigned long *bitmap, int bits)
873 {
874 	int i, n, b;
875 
876 	/* bits needs to be a multiple of 8 */
877 	if (bits & 0x07)
878 		return -EINVAL;
879 
880 	if (str[0] == '0' && str[1] == 'x')
881 		str++;
882 	if (*str == 'x')
883 		str++;
884 
885 	for (i = 0; isxdigit(*str) && i < bits; str++) {
886 		b = hex_to_bin(*str);
887 		for (n = 0; n < 4; n++)
888 			if (b & (0x08 >> n))
889 				set_bit_inv(i + n, bitmap);
890 		i += 4;
891 	}
892 
893 	if (*str == '\n')
894 		str++;
895 	if (*str)
896 		return -EINVAL;
897 	return 0;
898 }
899 
900 /*
901  * modify_bitmap() - parse bitmask argument and modify an existing
902  * bit mask accordingly. A concatenation (done with ',') of these
903  * terms is recognized:
904  *   +<bitnr>[-<bitnr>] or -<bitnr>[-<bitnr>]
905  * <bitnr> may be any valid number (hex, decimal or octal) in the range
906  * 0...bits-1; the leading + or - is required. Here are some examples:
907  *   +0-15,+32,-128,-0xFF
908  *   -0-255,+1-16,+0x128
909  *   +1,+2,+3,+4,-5,-7-10
910  * Returns the new bitmap after all changes have been applied. Every
911  * positive value in the string will set a bit and every negative value
912  * in the string will clear a bit. As a bit may be touched more than once,
913  * the last 'operation' wins:
914  * +0-255,-128 = first bits 0-255 will be set, then bit 128 will be
915  * cleared again. All other bits are unmodified.
916  */
modify_bitmap(const char * str,unsigned long * bitmap,int bits)917 static int modify_bitmap(const char *str, unsigned long *bitmap, int bits)
918 {
919 	int a, i, z;
920 	char *np, sign;
921 
922 	/* bits needs to be a multiple of 8 */
923 	if (bits & 0x07)
924 		return -EINVAL;
925 
926 	while (*str) {
927 		sign = *str++;
928 		if (sign != '+' && sign != '-')
929 			return -EINVAL;
930 		a = z = simple_strtoul(str, &np, 0);
931 		if (str == np || a >= bits)
932 			return -EINVAL;
933 		str = np;
934 		if (*str == '-') {
935 			z = simple_strtoul(++str, &np, 0);
936 			if (str == np || a > z || z >= bits)
937 				return -EINVAL;
938 			str = np;
939 		}
940 		for (i = a; i <= z; i++)
941 			if (sign == '+')
942 				set_bit_inv(i, bitmap);
943 			else
944 				clear_bit_inv(i, bitmap);
945 		while (*str == ',' || *str == '\n')
946 			str++;
947 	}
948 
949 	return 0;
950 }
951 
952 /*
953  * process_mask_arg() - parse a bitmap string and clear/set the
954  * bits in the bitmap accordingly. The string may be given as
955  * absolute value, a hex string like 0x1F2E3D4C5B6A" simple over-
956  * writing the current content of the bitmap. Or as relative string
957  * like "+1-16,-32,-0x40,+128" where only single bits or ranges of
958  * bits are cleared or set. Distinction is done based on the very
959  * first character which may be '+' or '-' for the relative string
960  * and othewise assume to be an absolute value string. If parsing fails
961  * a negative errno value is returned. All arguments and bitmaps are
962  * big endian order.
963  */
process_mask_arg(const char * str,unsigned long * bitmap,int bits,struct mutex * lock)964 static int process_mask_arg(const char *str,
965 			    unsigned long *bitmap, int bits,
966 			    struct mutex *lock)
967 {
968 	unsigned long *newmap, size;
969 	int rc;
970 
971 	/* bits needs to be a multiple of 8 */
972 	if (bits & 0x07)
973 		return -EINVAL;
974 
975 	size = BITS_TO_LONGS(bits)*sizeof(unsigned long);
976 	newmap = kmalloc(size, GFP_KERNEL);
977 	if (!newmap)
978 		return -ENOMEM;
979 	if (mutex_lock_interruptible(lock)) {
980 		kfree(newmap);
981 		return -ERESTARTSYS;
982 	}
983 
984 	if (*str == '+' || *str == '-') {
985 		memcpy(newmap, bitmap, size);
986 		rc = modify_bitmap(str, newmap, bits);
987 	} else {
988 		memset(newmap, 0, size);
989 		rc = hex2bitmap(str, newmap, bits);
990 	}
991 	if (rc == 0)
992 		memcpy(bitmap, newmap, size);
993 	mutex_unlock(lock);
994 	kfree(newmap);
995 	return rc;
996 }
997 
998 /*
999  * AP bus attributes.
1000  */
1001 
ap_domain_show(struct bus_type * bus,char * buf)1002 static ssize_t ap_domain_show(struct bus_type *bus, char *buf)
1003 {
1004 	return snprintf(buf, PAGE_SIZE, "%d\n", ap_domain_index);
1005 }
1006 
ap_domain_store(struct bus_type * bus,const char * buf,size_t count)1007 static ssize_t ap_domain_store(struct bus_type *bus,
1008 			       const char *buf, size_t count)
1009 {
1010 	int domain;
1011 
1012 	if (sscanf(buf, "%i\n", &domain) != 1 ||
1013 	    domain < 0 || domain > ap_max_domain_id ||
1014 	    !test_bit_inv(domain, ap_perms.aqm))
1015 		return -EINVAL;
1016 	spin_lock_bh(&ap_domain_lock);
1017 	ap_domain_index = domain;
1018 	spin_unlock_bh(&ap_domain_lock);
1019 
1020 	AP_DBF(DBF_DEBUG, "stored new default domain=%d\n", domain);
1021 
1022 	return count;
1023 }
1024 
1025 static BUS_ATTR_RW(ap_domain);
1026 
ap_control_domain_mask_show(struct bus_type * bus,char * buf)1027 static ssize_t ap_control_domain_mask_show(struct bus_type *bus, char *buf)
1028 {
1029 	if (!ap_configuration)	/* QCI not supported */
1030 		return snprintf(buf, PAGE_SIZE, "not supported\n");
1031 
1032 	return snprintf(buf, PAGE_SIZE,
1033 			"0x%08x%08x%08x%08x%08x%08x%08x%08x\n",
1034 			ap_configuration->adm[0], ap_configuration->adm[1],
1035 			ap_configuration->adm[2], ap_configuration->adm[3],
1036 			ap_configuration->adm[4], ap_configuration->adm[5],
1037 			ap_configuration->adm[6], ap_configuration->adm[7]);
1038 }
1039 
1040 static BUS_ATTR_RO(ap_control_domain_mask);
1041 
ap_usage_domain_mask_show(struct bus_type * bus,char * buf)1042 static ssize_t ap_usage_domain_mask_show(struct bus_type *bus, char *buf)
1043 {
1044 	if (!ap_configuration)	/* QCI not supported */
1045 		return snprintf(buf, PAGE_SIZE, "not supported\n");
1046 
1047 	return snprintf(buf, PAGE_SIZE,
1048 			"0x%08x%08x%08x%08x%08x%08x%08x%08x\n",
1049 			ap_configuration->aqm[0], ap_configuration->aqm[1],
1050 			ap_configuration->aqm[2], ap_configuration->aqm[3],
1051 			ap_configuration->aqm[4], ap_configuration->aqm[5],
1052 			ap_configuration->aqm[6], ap_configuration->aqm[7]);
1053 }
1054 
1055 static BUS_ATTR_RO(ap_usage_domain_mask);
1056 
ap_interrupts_show(struct bus_type * bus,char * buf)1057 static ssize_t ap_interrupts_show(struct bus_type *bus, char *buf)
1058 {
1059 	return snprintf(buf, PAGE_SIZE, "%d\n",
1060 			ap_using_interrupts() ? 1 : 0);
1061 }
1062 
1063 static BUS_ATTR_RO(ap_interrupts);
1064 
config_time_show(struct bus_type * bus,char * buf)1065 static ssize_t config_time_show(struct bus_type *bus, char *buf)
1066 {
1067 	return snprintf(buf, PAGE_SIZE, "%d\n", ap_config_time);
1068 }
1069 
config_time_store(struct bus_type * bus,const char * buf,size_t count)1070 static ssize_t config_time_store(struct bus_type *bus,
1071 				 const char *buf, size_t count)
1072 {
1073 	int time;
1074 
1075 	if (sscanf(buf, "%d\n", &time) != 1 || time < 5 || time > 120)
1076 		return -EINVAL;
1077 	ap_config_time = time;
1078 	mod_timer(&ap_config_timer, jiffies + ap_config_time * HZ);
1079 	return count;
1080 }
1081 
1082 static BUS_ATTR_RW(config_time);
1083 
poll_thread_show(struct bus_type * bus,char * buf)1084 static ssize_t poll_thread_show(struct bus_type *bus, char *buf)
1085 {
1086 	return snprintf(buf, PAGE_SIZE, "%d\n", ap_poll_kthread ? 1 : 0);
1087 }
1088 
poll_thread_store(struct bus_type * bus,const char * buf,size_t count)1089 static ssize_t poll_thread_store(struct bus_type *bus,
1090 				 const char *buf, size_t count)
1091 {
1092 	int flag, rc;
1093 
1094 	if (sscanf(buf, "%d\n", &flag) != 1)
1095 		return -EINVAL;
1096 	if (flag) {
1097 		rc = ap_poll_thread_start();
1098 		if (rc)
1099 			count = rc;
1100 	} else
1101 		ap_poll_thread_stop();
1102 	return count;
1103 }
1104 
1105 static BUS_ATTR_RW(poll_thread);
1106 
poll_timeout_show(struct bus_type * bus,char * buf)1107 static ssize_t poll_timeout_show(struct bus_type *bus, char *buf)
1108 {
1109 	return snprintf(buf, PAGE_SIZE, "%llu\n", poll_timeout);
1110 }
1111 
poll_timeout_store(struct bus_type * bus,const char * buf,size_t count)1112 static ssize_t poll_timeout_store(struct bus_type *bus, const char *buf,
1113 				  size_t count)
1114 {
1115 	unsigned long long time;
1116 	ktime_t hr_time;
1117 
1118 	/* 120 seconds = maximum poll interval */
1119 	if (sscanf(buf, "%llu\n", &time) != 1 || time < 1 ||
1120 	    time > 120000000000ULL)
1121 		return -EINVAL;
1122 	poll_timeout = time;
1123 	hr_time = poll_timeout;
1124 
1125 	spin_lock_bh(&ap_poll_timer_lock);
1126 	hrtimer_cancel(&ap_poll_timer);
1127 	hrtimer_set_expires(&ap_poll_timer, hr_time);
1128 	hrtimer_start_expires(&ap_poll_timer, HRTIMER_MODE_ABS);
1129 	spin_unlock_bh(&ap_poll_timer_lock);
1130 
1131 	return count;
1132 }
1133 
1134 static BUS_ATTR_RW(poll_timeout);
1135 
ap_max_domain_id_show(struct bus_type * bus,char * buf)1136 static ssize_t ap_max_domain_id_show(struct bus_type *bus, char *buf)
1137 {
1138 	int max_domain_id;
1139 
1140 	if (ap_configuration)
1141 		max_domain_id = ap_max_domain_id ? : -1;
1142 	else
1143 		max_domain_id = 15;
1144 	return snprintf(buf, PAGE_SIZE, "%d\n", max_domain_id);
1145 }
1146 
1147 static BUS_ATTR_RO(ap_max_domain_id);
1148 
apmask_show(struct bus_type * bus,char * buf)1149 static ssize_t apmask_show(struct bus_type *bus, char *buf)
1150 {
1151 	int rc;
1152 
1153 	if (mutex_lock_interruptible(&ap_perms_mutex))
1154 		return -ERESTARTSYS;
1155 	rc = snprintf(buf, PAGE_SIZE,
1156 		      "0x%016lx%016lx%016lx%016lx\n",
1157 		      ap_perms.apm[0], ap_perms.apm[1],
1158 		      ap_perms.apm[2], ap_perms.apm[3]);
1159 	mutex_unlock(&ap_perms_mutex);
1160 
1161 	return rc;
1162 }
1163 
apmask_store(struct bus_type * bus,const char * buf,size_t count)1164 static ssize_t apmask_store(struct bus_type *bus, const char *buf,
1165 			    size_t count)
1166 {
1167 	int rc;
1168 
1169 	rc = process_mask_arg(buf, ap_perms.apm, AP_DEVICES, &ap_perms_mutex);
1170 	if (rc)
1171 		return rc;
1172 
1173 	ap_bus_revise_bindings();
1174 
1175 	return count;
1176 }
1177 
1178 static BUS_ATTR_RW(apmask);
1179 
aqmask_show(struct bus_type * bus,char * buf)1180 static ssize_t aqmask_show(struct bus_type *bus, char *buf)
1181 {
1182 	int rc;
1183 
1184 	if (mutex_lock_interruptible(&ap_perms_mutex))
1185 		return -ERESTARTSYS;
1186 	rc = snprintf(buf, PAGE_SIZE,
1187 		      "0x%016lx%016lx%016lx%016lx\n",
1188 		      ap_perms.aqm[0], ap_perms.aqm[1],
1189 		      ap_perms.aqm[2], ap_perms.aqm[3]);
1190 	mutex_unlock(&ap_perms_mutex);
1191 
1192 	return rc;
1193 }
1194 
aqmask_store(struct bus_type * bus,const char * buf,size_t count)1195 static ssize_t aqmask_store(struct bus_type *bus, const char *buf,
1196 			    size_t count)
1197 {
1198 	int rc;
1199 
1200 	rc = process_mask_arg(buf, ap_perms.aqm, AP_DOMAINS, &ap_perms_mutex);
1201 	if (rc)
1202 		return rc;
1203 
1204 	ap_bus_revise_bindings();
1205 
1206 	return count;
1207 }
1208 
1209 static BUS_ATTR_RW(aqmask);
1210 
1211 static struct bus_attribute *const ap_bus_attrs[] = {
1212 	&bus_attr_ap_domain,
1213 	&bus_attr_ap_control_domain_mask,
1214 	&bus_attr_ap_usage_domain_mask,
1215 	&bus_attr_config_time,
1216 	&bus_attr_poll_thread,
1217 	&bus_attr_ap_interrupts,
1218 	&bus_attr_poll_timeout,
1219 	&bus_attr_ap_max_domain_id,
1220 	&bus_attr_apmask,
1221 	&bus_attr_aqmask,
1222 	NULL,
1223 };
1224 
1225 /**
1226  * ap_select_domain(): Select an AP domain if possible and we haven't
1227  * already done so before.
1228  */
ap_select_domain(void)1229 static void ap_select_domain(void)
1230 {
1231 	int count, max_count, best_domain;
1232 	struct ap_queue_status status;
1233 	int i, j;
1234 
1235 	/*
1236 	 * We want to use a single domain. Either the one specified with
1237 	 * the "domain=" parameter or the domain with the maximum number
1238 	 * of devices.
1239 	 */
1240 	spin_lock_bh(&ap_domain_lock);
1241 	if (ap_domain_index >= 0) {
1242 		/* Domain has already been selected. */
1243 		spin_unlock_bh(&ap_domain_lock);
1244 		return;
1245 	}
1246 	best_domain = -1;
1247 	max_count = 0;
1248 	for (i = 0; i < AP_DOMAINS; i++) {
1249 		if (!ap_test_config_domain(i) ||
1250 		    !test_bit_inv(i, ap_perms.aqm))
1251 			continue;
1252 		count = 0;
1253 		for (j = 0; j < AP_DEVICES; j++) {
1254 			if (!ap_test_config_card_id(j))
1255 				continue;
1256 			status = ap_test_queue(AP_MKQID(j, i),
1257 					       ap_apft_available(),
1258 					       NULL);
1259 			if (status.response_code != AP_RESPONSE_NORMAL)
1260 				continue;
1261 			count++;
1262 		}
1263 		if (count > max_count) {
1264 			max_count = count;
1265 			best_domain = i;
1266 		}
1267 	}
1268 	if (best_domain >= 0) {
1269 		ap_domain_index = best_domain;
1270 		AP_DBF(DBF_DEBUG, "new ap_domain_index=%d\n", ap_domain_index);
1271 	}
1272 	spin_unlock_bh(&ap_domain_lock);
1273 }
1274 
1275 /*
1276  * This function checks the type and returns either 0 for not
1277  * supported or the highest compatible type value (which may
1278  * include the input type value).
1279  */
ap_get_compatible_type(ap_qid_t qid,int rawtype,unsigned int func)1280 static int ap_get_compatible_type(ap_qid_t qid, int rawtype, unsigned int func)
1281 {
1282 	int comp_type = 0;
1283 
1284 	/* < CEX2A is not supported */
1285 	if (rawtype < AP_DEVICE_TYPE_CEX2A)
1286 		return 0;
1287 	/* up to CEX6 known and fully supported */
1288 	if (rawtype <= AP_DEVICE_TYPE_CEX6)
1289 		return rawtype;
1290 	/*
1291 	 * unknown new type > CEX6, check for compatibility
1292 	 * to the highest known and supported type which is
1293 	 * currently CEX6 with the help of the QACT function.
1294 	 */
1295 	if (ap_qact_available()) {
1296 		struct ap_queue_status status;
1297 		union ap_qact_ap_info apinfo = {0};
1298 
1299 		apinfo.mode = (func >> 26) & 0x07;
1300 		apinfo.cat = AP_DEVICE_TYPE_CEX6;
1301 		status = ap_qact(qid, 0, &apinfo);
1302 		if (status.response_code == AP_RESPONSE_NORMAL
1303 		    && apinfo.cat >= AP_DEVICE_TYPE_CEX2A
1304 		    && apinfo.cat <= AP_DEVICE_TYPE_CEX6)
1305 			comp_type = apinfo.cat;
1306 	}
1307 	if (!comp_type)
1308 		AP_DBF(DBF_WARN, "queue=%02x.%04x unable to map type %d\n",
1309 		       AP_QID_CARD(qid), AP_QID_QUEUE(qid), rawtype);
1310 	else if (comp_type != rawtype)
1311 		AP_DBF(DBF_INFO, "queue=%02x.%04x map type %d to %d\n",
1312 		       AP_QID_CARD(qid), AP_QID_QUEUE(qid), rawtype, comp_type);
1313 	return comp_type;
1314 }
1315 
1316 /*
1317  * helper function to be used with bus_find_dev
1318  * matches for the card device with the given id
1319  */
__match_card_device_with_id(struct device * dev,void * data)1320 static int __match_card_device_with_id(struct device *dev, void *data)
1321 {
1322 	return is_card_dev(dev) && to_ap_card(dev)->id == (int)(long) data;
1323 }
1324 
1325 /* helper function to be used with bus_find_dev
1326  * matches for the queue device with a given qid
1327  */
__match_queue_device_with_qid(struct device * dev,void * data)1328 static int __match_queue_device_with_qid(struct device *dev, void *data)
1329 {
1330 	return is_queue_dev(dev) && to_ap_queue(dev)->qid == (int)(long) data;
1331 }
1332 
1333 /**
1334  * ap_scan_bus(): Scan the AP bus for new devices
1335  * Runs periodically, workqueue timer (ap_config_time)
1336  */
ap_scan_bus(struct work_struct * unused)1337 static void ap_scan_bus(struct work_struct *unused)
1338 {
1339 	struct ap_queue *aq;
1340 	struct ap_card *ac;
1341 	struct device *dev;
1342 	ap_qid_t qid;
1343 	int comp_type, depth = 0, type = 0;
1344 	unsigned int func = 0;
1345 	int rc, id, dom, borked, domains, defdomdevs = 0;
1346 
1347 	AP_DBF(DBF_DEBUG, "%s running\n", __func__);
1348 
1349 	ap_query_configuration(ap_configuration);
1350 	ap_select_domain();
1351 
1352 	for (id = 0; id < AP_DEVICES; id++) {
1353 		/* check if device is registered */
1354 		dev = bus_find_device(&ap_bus_type, NULL,
1355 				      (void *)(long) id,
1356 				      __match_card_device_with_id);
1357 		ac = dev ? to_ap_card(dev) : NULL;
1358 		if (!ap_test_config_card_id(id)) {
1359 			if (dev) {
1360 				/* Card device has been removed from
1361 				 * configuration, remove the belonging
1362 				 * queue devices.
1363 				 */
1364 				bus_for_each_dev(&ap_bus_type, NULL,
1365 					(void *)(long) id,
1366 					__ap_queue_devices_with_id_unregister);
1367 				/* now remove the card device */
1368 				device_unregister(dev);
1369 				put_device(dev);
1370 			}
1371 			continue;
1372 		}
1373 		/* According to the configuration there should be a card
1374 		 * device, so check if there is at least one valid queue
1375 		 * and maybe create queue devices and the card device.
1376 		 */
1377 		domains = 0;
1378 		for (dom = 0; dom < AP_DOMAINS; dom++) {
1379 			qid = AP_MKQID(id, dom);
1380 			dev = bus_find_device(&ap_bus_type, NULL,
1381 					      (void *)(long) qid,
1382 					      __match_queue_device_with_qid);
1383 			aq = dev ? to_ap_queue(dev) : NULL;
1384 			if (!ap_test_config_domain(dom)) {
1385 				if (dev) {
1386 					/* Queue device exists but has been
1387 					 * removed from configuration.
1388 					 */
1389 					device_unregister(dev);
1390 					put_device(dev);
1391 				}
1392 				continue;
1393 			}
1394 			rc = ap_query_queue(qid, &depth, &type, &func);
1395 			if (dev) {
1396 				spin_lock_bh(&aq->lock);
1397 				if (rc == -ENODEV ||
1398 				    /* adapter reconfiguration */
1399 				    (ac && ac->functions != func))
1400 					aq->state = AP_STATE_BORKED;
1401 				borked = aq->state == AP_STATE_BORKED;
1402 				spin_unlock_bh(&aq->lock);
1403 				if (borked)	/* Remove broken device */
1404 					device_unregister(dev);
1405 				put_device(dev);
1406 				if (!borked) {
1407 					domains++;
1408 					if (dom == ap_domain_index)
1409 						defdomdevs++;
1410 					continue;
1411 				}
1412 			}
1413 			if (rc)
1414 				continue;
1415 			/* a new queue device is needed, check out comp type */
1416 			comp_type = ap_get_compatible_type(qid, type, func);
1417 			if (!comp_type)
1418 				continue;
1419 			/* maybe a card device needs to be created first */
1420 			if (!ac) {
1421 				ac = ap_card_create(id, depth, type,
1422 						    comp_type, func);
1423 				if (!ac)
1424 					continue;
1425 				ac->ap_dev.device.bus = &ap_bus_type;
1426 				ac->ap_dev.device.parent = ap_root_device;
1427 				dev_set_name(&ac->ap_dev.device,
1428 					     "card%02x", id);
1429 				/* Register card with AP bus */
1430 				rc = device_register(&ac->ap_dev.device);
1431 				if (rc) {
1432 					put_device(&ac->ap_dev.device);
1433 					ac = NULL;
1434 					break;
1435 				}
1436 				/* get it and thus adjust reference counter */
1437 				get_device(&ac->ap_dev.device);
1438 			}
1439 			/* now create the new queue device */
1440 			aq = ap_queue_create(qid, comp_type);
1441 			if (!aq)
1442 				continue;
1443 			aq->card = ac;
1444 			aq->ap_dev.device.bus = &ap_bus_type;
1445 			aq->ap_dev.device.parent = &ac->ap_dev.device;
1446 			dev_set_name(&aq->ap_dev.device,
1447 				     "%02x.%04x", id, dom);
1448 			/* Register device */
1449 			rc = device_register(&aq->ap_dev.device);
1450 			if (rc) {
1451 				put_device(&aq->ap_dev.device);
1452 				continue;
1453 			}
1454 			domains++;
1455 			if (dom == ap_domain_index)
1456 				defdomdevs++;
1457 		} /* end domain loop */
1458 		if (ac) {
1459 			/* remove card dev if there are no queue devices */
1460 			if (!domains)
1461 				device_unregister(&ac->ap_dev.device);
1462 			put_device(&ac->ap_dev.device);
1463 		}
1464 	} /* end device loop */
1465 
1466 	if (ap_domain_index >= 0 && defdomdevs < 1)
1467 		AP_DBF(DBF_INFO,
1468 		       "no queue device with default domain %d available\n",
1469 		       ap_domain_index);
1470 
1471 	mod_timer(&ap_config_timer, jiffies + ap_config_time * HZ);
1472 }
1473 
ap_config_timeout(struct timer_list * unused)1474 static void ap_config_timeout(struct timer_list *unused)
1475 {
1476 	if (ap_suspend_flag)
1477 		return;
1478 	queue_work(system_long_wq, &ap_scan_work);
1479 }
1480 
ap_debug_init(void)1481 static int __init ap_debug_init(void)
1482 {
1483 	ap_dbf_info = debug_register("ap", 1, 1,
1484 				     DBF_MAX_SPRINTF_ARGS * sizeof(long));
1485 	debug_register_view(ap_dbf_info, &debug_sprintf_view);
1486 	debug_set_level(ap_dbf_info, DBF_ERR);
1487 
1488 	return 0;
1489 }
1490 
ap_perms_init(void)1491 static void __init ap_perms_init(void)
1492 {
1493 	/* all resources useable if no kernel parameter string given */
1494 	memset(&ap_perms.apm, 0xFF, sizeof(ap_perms.apm));
1495 	memset(&ap_perms.aqm, 0xFF, sizeof(ap_perms.aqm));
1496 
1497 	/* apm kernel parameter string */
1498 	if (apm_str) {
1499 		memset(&ap_perms.apm, 0, sizeof(ap_perms.apm));
1500 		process_mask_arg(apm_str, ap_perms.apm, AP_DEVICES,
1501 				 &ap_perms_mutex);
1502 	}
1503 
1504 	/* aqm kernel parameter string */
1505 	if (aqm_str) {
1506 		memset(&ap_perms.aqm, 0, sizeof(ap_perms.aqm));
1507 		process_mask_arg(aqm_str, ap_perms.aqm, AP_DOMAINS,
1508 				 &ap_perms_mutex);
1509 	}
1510 }
1511 
1512 /**
1513  * ap_module_init(): The module initialization code.
1514  *
1515  * Initializes the module.
1516  */
ap_module_init(void)1517 static int __init ap_module_init(void)
1518 {
1519 	int max_domain_id;
1520 	int rc, i;
1521 
1522 	rc = ap_debug_init();
1523 	if (rc)
1524 		return rc;
1525 
1526 	if (!ap_instructions_available()) {
1527 		pr_warn("The hardware system does not support AP instructions\n");
1528 		return -ENODEV;
1529 	}
1530 
1531 	/* set up the AP permissions (ap and aq masks) */
1532 	ap_perms_init();
1533 
1534 	/* Get AP configuration data if available */
1535 	ap_init_configuration();
1536 
1537 	if (ap_configuration)
1538 		max_domain_id =
1539 			ap_max_domain_id ? ap_max_domain_id : AP_DOMAINS - 1;
1540 	else
1541 		max_domain_id = 15;
1542 	if (ap_domain_index < -1 || ap_domain_index > max_domain_id ||
1543 	    (ap_domain_index >= 0 &&
1544 	     !test_bit_inv(ap_domain_index, ap_perms.aqm))) {
1545 		pr_warn("%d is not a valid cryptographic domain\n",
1546 			ap_domain_index);
1547 		ap_domain_index = -1;
1548 	}
1549 	/* In resume callback we need to know if the user had set the domain.
1550 	 * If so, we can not just reset it.
1551 	 */
1552 	if (ap_domain_index >= 0)
1553 		user_set_domain = 1;
1554 
1555 	if (ap_interrupts_available()) {
1556 		rc = register_adapter_interrupt(&ap_airq);
1557 		ap_airq_flag = (rc == 0);
1558 	}
1559 
1560 	/* Create /sys/bus/ap. */
1561 	rc = bus_register(&ap_bus_type);
1562 	if (rc)
1563 		goto out;
1564 	for (i = 0; ap_bus_attrs[i]; i++) {
1565 		rc = bus_create_file(&ap_bus_type, ap_bus_attrs[i]);
1566 		if (rc)
1567 			goto out_bus;
1568 	}
1569 
1570 	/* Create /sys/devices/ap. */
1571 	ap_root_device = root_device_register("ap");
1572 	rc = PTR_ERR_OR_ZERO(ap_root_device);
1573 	if (rc)
1574 		goto out_bus;
1575 
1576 	/* Setup the AP bus rescan timer. */
1577 	timer_setup(&ap_config_timer, ap_config_timeout, 0);
1578 
1579 	/*
1580 	 * Setup the high resultion poll timer.
1581 	 * If we are running under z/VM adjust polling to z/VM polling rate.
1582 	 */
1583 	if (MACHINE_IS_VM)
1584 		poll_timeout = 1500000;
1585 	spin_lock_init(&ap_poll_timer_lock);
1586 	hrtimer_init(&ap_poll_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
1587 	ap_poll_timer.function = ap_poll_timeout;
1588 
1589 	/* Start the low priority AP bus poll thread. */
1590 	if (ap_thread_flag) {
1591 		rc = ap_poll_thread_start();
1592 		if (rc)
1593 			goto out_work;
1594 	}
1595 
1596 	rc = register_pm_notifier(&ap_power_notifier);
1597 	if (rc)
1598 		goto out_pm;
1599 
1600 	queue_work(system_long_wq, &ap_scan_work);
1601 	initialised = true;
1602 
1603 	return 0;
1604 
1605 out_pm:
1606 	ap_poll_thread_stop();
1607 out_work:
1608 	hrtimer_cancel(&ap_poll_timer);
1609 	root_device_unregister(ap_root_device);
1610 out_bus:
1611 	while (i--)
1612 		bus_remove_file(&ap_bus_type, ap_bus_attrs[i]);
1613 	bus_unregister(&ap_bus_type);
1614 out:
1615 	if (ap_using_interrupts())
1616 		unregister_adapter_interrupt(&ap_airq);
1617 	kfree(ap_configuration);
1618 	return rc;
1619 }
1620 device_initcall(ap_module_init);
1621