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