xref: /linux/drivers/s390/crypto/vfio_ap_ops.c (revision 4e0ab192f240755ad8670f30467374a04d83709f)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Adjunct processor matrix VFIO device driver callbacks.
4  *
5  * Copyright IBM Corp. 2018
6  *
7  * Author(s): Tony Krowiak <akrowiak@linux.ibm.com>
8  *	      Halil Pasic <pasic@linux.ibm.com>
9  *	      Pierre Morel <pmorel@linux.ibm.com>
10  */
11 #include <linux/string.h>
12 #include <linux/vfio.h>
13 #include <linux/device.h>
14 #include <linux/list.h>
15 #include <linux/ctype.h>
16 #include <linux/bitops.h>
17 #include <linux/kvm_host.h>
18 #include <linux/module.h>
19 #include <linux/uuid.h>
20 #include <asm/kvm.h>
21 #include <asm/zcrypt.h>
22 
23 #include "vfio_ap_private.h"
24 #include "vfio_ap_debug.h"
25 
26 #define VFIO_AP_MDEV_TYPE_HWVIRT "passthrough"
27 #define VFIO_AP_MDEV_NAME_HWVIRT "VFIO AP Passthrough Device"
28 
29 #define AP_QUEUE_ASSIGNED "assigned"
30 #define AP_QUEUE_UNASSIGNED "unassigned"
31 #define AP_QUEUE_IN_USE "in use"
32 
33 #define AP_RESET_INTERVAL		20	/* Reset sleep interval (20ms)		*/
34 
35 static int vfio_ap_mdev_reset_queues(struct ap_matrix_mdev *matrix_mdev);
36 static int vfio_ap_mdev_reset_qlist(struct list_head *qlist);
37 static struct vfio_ap_queue *vfio_ap_find_queue(int apqn);
38 static const struct vfio_device_ops vfio_ap_matrix_dev_ops;
39 static void vfio_ap_mdev_reset_queue(struct vfio_ap_queue *q);
40 
41 /**
42  * get_update_locks_for_kvm: Acquire the locks required to dynamically update a
43  *			     KVM guest's APCB in the proper order.
44  *
45  * @kvm: a pointer to a struct kvm object containing the KVM guest's APCB.
46  *
47  * The proper locking order is:
48  * 1. matrix_dev->guests_lock: required to use the KVM pointer to update a KVM
49  *			       guest's APCB.
50  * 2. kvm->lock:	       required to update a guest's APCB
51  * 3. kvm->arch.crypto.pqap_hook_rwsem: required to update pqap_hook and
52  *					serialize against PQAP intercepts
53  * 4. matrix_dev->mdevs_lock:  required to access data stored in a matrix_mdev
54  *
55  * Note: If @kvm is NULL, the KVM lock and pqap_hook_rwsem will not be taken.
56  */
57 static inline void get_update_locks_for_kvm(struct kvm *kvm)
58 {
59 	mutex_lock(&matrix_dev->guests_lock);
60 	if (kvm) {
61 		mutex_lock(&kvm->lock);
62 		down_write(&kvm->arch.crypto.pqap_hook_rwsem);
63 	}
64 	mutex_lock(&matrix_dev->mdevs_lock);
65 }
66 
67 /**
68  * release_update_locks_for_kvm: Release the locks used to dynamically update a
69  *				 KVM guest's APCB in the proper order.
70  *
71  * @kvm: a pointer to a struct kvm object containing the KVM guest's APCB.
72  *
73  * The proper unlocking order is:
74  * 1. matrix_dev->mdevs_lock
75  * 2. kvm->arch.crypto.pqap_hook_rwsem
76  * 3. kvm->lock
77  * 4. matrix_dev->guests_lock
78  *
79  * Note: If @kvm is NULL, the KVM lock and pqap_hook_rwsem will not be released.
80  */
81 static inline void release_update_locks_for_kvm(struct kvm *kvm)
82 {
83 	mutex_unlock(&matrix_dev->mdevs_lock);
84 	if (kvm) {
85 		up_write(&kvm->arch.crypto.pqap_hook_rwsem);
86 		mutex_unlock(&kvm->lock);
87 	}
88 	mutex_unlock(&matrix_dev->guests_lock);
89 }
90 
91 /**
92  * get_update_locks_for_mdev: Acquire the locks required to dynamically update a
93  *			      KVM guest's APCB in the proper order.
94  *
95  * @matrix_mdev: a pointer to a struct ap_matrix_mdev object containing the AP
96  *		 configuration data to use to update a KVM guest's APCB.
97  *
98  * The proper locking order is:
99  * 1. matrix_dev->guests_lock: required to use the KVM pointer to update a KVM
100  *			       guest's APCB.
101  * 2. matrix_mdev->kvm->lock:  required to update a guest's APCB
102  * 3. matrix_dev->mdevs_lock:  required to access data stored in a matrix_mdev
103  *
104  * Note: If @matrix_mdev is NULL or is not attached to a KVM guest, the KVM
105  *	 lock will not be taken.
106  */
107 static inline void get_update_locks_for_mdev(struct ap_matrix_mdev *matrix_mdev)
108 {
109 	mutex_lock(&matrix_dev->guests_lock);
110 	if (matrix_mdev && matrix_mdev->kvm)
111 		mutex_lock(&matrix_mdev->kvm->lock);
112 	mutex_lock(&matrix_dev->mdevs_lock);
113 }
114 
115 /**
116  * release_update_locks_for_mdev: Release the locks used to dynamically update a
117  *				  KVM guest's APCB in the proper order.
118  *
119  * @matrix_mdev: a pointer to a struct ap_matrix_mdev object containing the AP
120  *		 configuration data to use to update a KVM guest's APCB.
121  *
122  * The proper unlocking order is:
123  * 1. matrix_dev->mdevs_lock
124  * 2. matrix_mdev->kvm->lock
125  * 3. matrix_dev->guests_lock
126  *
127  * Note: If @matrix_mdev is NULL or is not attached to a KVM guest, the KVM
128  *	 lock will not be released.
129  */
130 static inline void release_update_locks_for_mdev(struct ap_matrix_mdev *matrix_mdev)
131 {
132 	mutex_unlock(&matrix_dev->mdevs_lock);
133 	if (matrix_mdev && matrix_mdev->kvm)
134 		mutex_unlock(&matrix_mdev->kvm->lock);
135 	mutex_unlock(&matrix_dev->guests_lock);
136 }
137 
138 /**
139  * get_update_locks_by_apqn: Find the mdev to which an APQN is assigned and
140  *			     acquire the locks required to update the APCB of
141  *			     the KVM guest to which the mdev is attached.
142  *
143  * @apqn: the APQN of a queue device.
144  *
145  * The proper locking order is:
146  * 1. matrix_dev->guests_lock: required to use the KVM pointer to update a KVM
147  *			       guest's APCB.
148  * 2. matrix_mdev->kvm->lock:  required to update a guest's APCB
149  * 3. matrix_dev->mdevs_lock:  required to access data stored in a matrix_mdev
150  *
151  * Note: If @apqn is not assigned to a matrix_mdev, the matrix_mdev->kvm->lock
152  *	 will not be taken.
153  *
154  * Return: the ap_matrix_mdev object to which @apqn is assigned or NULL if @apqn
155  *	   is not assigned to an ap_matrix_mdev.
156  */
157 static struct ap_matrix_mdev *get_update_locks_by_apqn(int apqn)
158 {
159 	struct ap_matrix_mdev *matrix_mdev;
160 
161 	mutex_lock(&matrix_dev->guests_lock);
162 
163 	list_for_each_entry(matrix_mdev, &matrix_dev->mdev_list, node) {
164 		if (test_bit_inv(AP_QID_CARD(apqn), matrix_mdev->matrix.apm) &&
165 		    test_bit_inv(AP_QID_QUEUE(apqn), matrix_mdev->matrix.aqm)) {
166 			if (matrix_mdev->kvm)
167 				mutex_lock(&matrix_mdev->kvm->lock);
168 
169 			mutex_lock(&matrix_dev->mdevs_lock);
170 
171 			return matrix_mdev;
172 		}
173 	}
174 
175 	mutex_lock(&matrix_dev->mdevs_lock);
176 
177 	return NULL;
178 }
179 
180 /**
181  * get_update_locks_for_queue: get the locks required to update the APCB of the
182  *			       KVM guest to which the matrix mdev linked to a
183  *			       vfio_ap_queue object is attached.
184  *
185  * @q: a pointer to a vfio_ap_queue object.
186  *
187  * The proper locking order is:
188  * 1. q->matrix_dev->guests_lock: required to use the KVM pointer to update a
189  *				  KVM guest's APCB.
190  * 2. q->matrix_mdev->kvm->lock:  required to update a guest's APCB
191  * 3. matrix_dev->mdevs_lock:	  required to access data stored in matrix_mdev
192  *
193  * Note: if @queue is not linked to an ap_matrix_mdev object, the KVM lock
194  *	  will not be taken.
195  */
196 static inline void get_update_locks_for_queue(struct vfio_ap_queue *q)
197 {
198 	mutex_lock(&matrix_dev->guests_lock);
199 	if (q->matrix_mdev && q->matrix_mdev->kvm)
200 		mutex_lock(&q->matrix_mdev->kvm->lock);
201 	mutex_lock(&matrix_dev->mdevs_lock);
202 }
203 
204 /**
205  * vfio_ap_mdev_get_queue - retrieve a queue with a specific APQN from a
206  *			    hash table of queues assigned to a matrix mdev
207  * @matrix_mdev: the matrix mdev
208  * @apqn: The APQN of a queue device
209  *
210  * Return: the pointer to the vfio_ap_queue struct representing the queue or
211  *	   NULL if the queue is not assigned to @matrix_mdev
212  */
213 static struct vfio_ap_queue *vfio_ap_mdev_get_queue(
214 					struct ap_matrix_mdev *matrix_mdev,
215 					int apqn)
216 {
217 	struct vfio_ap_queue *q;
218 
219 	hash_for_each_possible(matrix_mdev->qtable.queues, q, mdev_qnode,
220 			       apqn) {
221 		if (q && q->apqn == apqn)
222 			return q;
223 	}
224 
225 	return NULL;
226 }
227 
228 /**
229  * vfio_ap_wait_for_irqclear - clears the IR bit or gives up after 5 tries
230  * @apqn: The AP Queue number
231  *
232  * Checks the IRQ bit for the status of this APQN using ap_tapq.
233  * Returns if the ap_tapq function succeeded and the bit is clear.
234  * Returns if ap_tapq function failed with invalid, deconfigured or
235  * checkstopped AP.
236  * Otherwise retries up to 5 times after waiting 20ms.
237  */
238 static void vfio_ap_wait_for_irqclear(int apqn)
239 {
240 	struct ap_queue_status status;
241 	int retry = 5;
242 
243 	do {
244 		status = ap_tapq(apqn, NULL);
245 		switch (status.response_code) {
246 		case AP_RESPONSE_NORMAL:
247 		case AP_RESPONSE_RESET_IN_PROGRESS:
248 			if (!status.irq_enabled)
249 				return;
250 			fallthrough;
251 		case AP_RESPONSE_BUSY:
252 			msleep(20);
253 			break;
254 		case AP_RESPONSE_Q_NOT_AVAIL:
255 		case AP_RESPONSE_DECONFIGURED:
256 		case AP_RESPONSE_CHECKSTOPPED:
257 		default:
258 			WARN_ONCE(1, "%s: tapq rc %02x: %04x\n", __func__,
259 				  status.response_code, apqn);
260 			return;
261 		}
262 	} while (--retry);
263 
264 	WARN_ONCE(1, "%s: tapq rc %02x: %04x could not clear IR bit\n",
265 		  __func__, status.response_code, apqn);
266 }
267 
268 /**
269  * vfio_ap_free_aqic_resources - free vfio_ap_queue resources
270  * @q: The vfio_ap_queue
271  *
272  * Unregisters the ISC in the GIB when the saved ISC not invalid.
273  * Unpins the guest's page holding the NIB when it exists.
274  * Resets the saved_iova and saved_isc to invalid values.
275  */
276 static void vfio_ap_free_aqic_resources(struct vfio_ap_queue *q)
277 {
278 	if (!q)
279 		return;
280 	if (q->saved_isc != VFIO_AP_ISC_INVALID) {
281 		if (!WARN_ON(!q->matrix_mdev) && q->matrix_mdev->kvm)
282 			kvm_s390_gisc_unregister(q->matrix_mdev->kvm, q->saved_isc);
283 		q->saved_isc = VFIO_AP_ISC_INVALID;
284 	}
285 	if (q->saved_iova && !WARN_ON(!q->matrix_mdev)) {
286 		vfio_unpin_pages(&q->matrix_mdev->vdev, q->saved_iova, 1);
287 		q->saved_iova = 0;
288 	}
289 }
290 
291 /**
292  * vfio_ap_irq_disable - disables and clears an ap_queue interrupt
293  * @q: The vfio_ap_queue
294  *
295  * Uses ap_aqic to disable the interruption and in case of success, reset
296  * in progress or IRQ disable command already proceeded: calls
297  * vfio_ap_wait_for_irqclear() to check for the IRQ bit to be clear
298  * and calls vfio_ap_free_aqic_resources() to free the resources associated
299  * with the AP interrupt handling.
300  *
301  * In the case the AP is busy, or a reset is in progress,
302  * retries after 20ms, up to 5 times.
303  *
304  * Returns if ap_aqic function failed with invalid, deconfigured or
305  * checkstopped AP.
306  *
307  * Return: &struct ap_queue_status
308  */
309 static struct ap_queue_status vfio_ap_irq_disable(struct vfio_ap_queue *q)
310 {
311 	union ap_qirq_ctrl aqic_gisa = { .value = 0 };
312 	struct ap_queue_status status;
313 	int retries = 5;
314 
315 	do {
316 		status = ap_aqic(q->apqn, aqic_gisa, 0);
317 		switch (status.response_code) {
318 		case AP_RESPONSE_OTHERWISE_CHANGED:
319 		case AP_RESPONSE_NORMAL:
320 			vfio_ap_wait_for_irqclear(q->apqn);
321 			goto end_free;
322 		case AP_RESPONSE_RESET_IN_PROGRESS:
323 		case AP_RESPONSE_BUSY:
324 			msleep(20);
325 			break;
326 		case AP_RESPONSE_Q_NOT_AVAIL:
327 		case AP_RESPONSE_DECONFIGURED:
328 		case AP_RESPONSE_CHECKSTOPPED:
329 		case AP_RESPONSE_INVALID_ADDRESS:
330 		default:
331 			/* All cases in default means AP not operational */
332 			WARN_ONCE(1, "%s: ap_aqic status %d\n", __func__,
333 				  status.response_code);
334 			goto end_free;
335 		}
336 	} while (retries--);
337 
338 	WARN_ONCE(1, "%s: ap_aqic status %d\n", __func__,
339 		  status.response_code);
340 end_free:
341 	vfio_ap_free_aqic_resources(q);
342 	return status;
343 }
344 
345 /**
346  * vfio_ap_validate_nib - validate a notification indicator byte (nib) address.
347  *
348  * @vcpu: the object representing the vcpu executing the PQAP(AQIC) instruction.
349  * @nib: the location for storing the nib address.
350  *
351  * When the PQAP(AQIC) instruction is executed, general register 2 contains the
352  * address of the notification indicator byte (nib) used for IRQ notification.
353  * This function parses and validates the nib from gr2.
354  *
355  * Return: returns zero if the nib address is a valid; otherwise, returns
356  *	   -EINVAL.
357  */
358 static int vfio_ap_validate_nib(struct kvm_vcpu *vcpu, dma_addr_t *nib)
359 {
360 	*nib = vcpu->run->s.regs.gprs[2];
361 
362 	if (!*nib)
363 		return -EINVAL;
364 	if (!kvm_s390_is_gpa_in_memslot(vcpu->kvm, *nib))
365 		return -EINVAL;
366 
367 	return 0;
368 }
369 
370 /**
371  * ensure_nib_shared() - Ensure the address of the NIB is secure and shared
372  * @addr: the physical (absolute) address of the NIB
373  *
374  * This function checks whether the NIB page, which has been pinned with
375  * vfio_pin_pages(), is a shared page belonging to a secure guest.
376  *
377  * It will call uv_pin_shared() on it; if the page was already pinned shared
378  * (i.e. if the NIB belongs to a secure guest and is shared), then 0
379  * (success) is returned. If the NIB was not shared, vfio_pin_pages() had
380  * exported it and now it does not belong to the secure guest anymore. In
381  * that case, an error is returned.
382  *
383  * Context: the NIB (at physical address @addr) has to be pinned with
384  *	    vfio_pin_pages() before calling this function.
385  *
386  * Return: 0 in case of success, otherwise an error < 0.
387  */
388 static int ensure_nib_shared(unsigned long addr)
389 {
390 	/*
391 	 * The nib has to be located in shared storage since guest and
392 	 * host access it. vfio_pin_pages() will do a pin shared and
393 	 * if that fails (possibly because it's not a shared page) it
394 	 * calls export. We try to do a second pin shared here so that
395 	 * the UV gives us an error code if we try to pin a non-shared
396 	 * page.
397 	 *
398 	 * If the page is already pinned shared the UV will return a success.
399 	 */
400 	return uv_pin_shared(addr);
401 }
402 
403 /**
404  * vfio_ap_irq_enable - Enable Interruption for a APQN
405  *
406  * @q:	 the vfio_ap_queue holding AQIC parameters
407  * @isc: the guest ISC to register with the GIB interface
408  * @vcpu: the vcpu object containing the registers specifying the parameters
409  *	  passed to the PQAP(AQIC) instruction.
410  *
411  * Pin the NIB saved in *q
412  * Register the guest ISC to GIB interface and retrieve the
413  * host ISC to issue the host side PQAP/AQIC
414  *
415  * status.response_code may be set to AP_RESPONSE_INVALID_ADDRESS in case the
416  * vfio_pin_pages or kvm_s390_gisc_register failed.
417  *
418  * Otherwise return the ap_queue_status returned by the ap_aqic(),
419  * all retry handling will be done by the guest.
420  *
421  * Return: &struct ap_queue_status
422  */
423 static struct ap_queue_status vfio_ap_irq_enable(struct vfio_ap_queue *q,
424 						 int isc,
425 						 struct kvm_vcpu *vcpu)
426 {
427 	union ap_qirq_ctrl aqic_gisa = { .value = 0 };
428 	struct ap_queue_status status = {};
429 	struct kvm_s390_gisa *gisa;
430 	struct page *h_page;
431 	int nisc;
432 	struct kvm *kvm;
433 	phys_addr_t h_nib;
434 	dma_addr_t nib;
435 	int ret;
436 
437 	/* Verify that the notification indicator byte address is valid */
438 	if (vfio_ap_validate_nib(vcpu, &nib)) {
439 		VFIO_AP_DBF_WARN("%s: invalid NIB address: nib=%pad, apqn=%#04x\n",
440 				 __func__, &nib, q->apqn);
441 
442 		status.response_code = AP_RESPONSE_INVALID_ADDRESS;
443 		return status;
444 	}
445 
446 	/* The pin will probably be successful even if the NIB was not shared */
447 	ret = vfio_pin_pages(&q->matrix_mdev->vdev, nib, 1,
448 			     IOMMU_READ | IOMMU_WRITE, &h_page);
449 	switch (ret) {
450 	case 1:
451 		break;
452 	default:
453 		VFIO_AP_DBF_WARN("%s: vfio_pin_pages failed: rc=%d,"
454 				 "nib=%pad, apqn=%#04x\n",
455 				 __func__, ret, &nib, q->apqn);
456 
457 		status.response_code = AP_RESPONSE_INVALID_ADDRESS;
458 		return status;
459 	}
460 
461 	kvm = q->matrix_mdev->kvm;
462 	gisa = kvm->arch.gisa_int.origin;
463 
464 	h_nib = page_to_phys(h_page) | (nib & ~PAGE_MASK);
465 	aqic_gisa.gisc = isc;
466 
467 	/* NIB in non-shared storage is a rc 6 for PV guests */
468 	if (kvm_s390_pv_cpu_is_protected(vcpu) &&
469 	    ensure_nib_shared(h_nib & PAGE_MASK)) {
470 		vfio_unpin_pages(&q->matrix_mdev->vdev, nib, 1);
471 		status.response_code = AP_RESPONSE_INVALID_ADDRESS;
472 		return status;
473 	}
474 
475 	nisc = kvm_s390_gisc_register(kvm, isc);
476 	if (nisc < 0) {
477 		VFIO_AP_DBF_WARN("%s: gisc registration failed: nisc=%d, isc=%d, apqn=%#04x\n",
478 				 __func__, nisc, isc, q->apqn);
479 
480 		vfio_unpin_pages(&q->matrix_mdev->vdev, nib, 1);
481 		status.response_code = AP_RESPONSE_INVALID_ADDRESS;
482 		return status;
483 	}
484 
485 	aqic_gisa.isc = nisc;
486 	aqic_gisa.ir = 1;
487 	aqic_gisa.gisa = virt_to_phys(gisa) >> 4;
488 
489 	status = ap_aqic(q->apqn, aqic_gisa, h_nib);
490 	switch (status.response_code) {
491 	case AP_RESPONSE_NORMAL:
492 		/* See if we did clear older IRQ configuration */
493 		vfio_ap_free_aqic_resources(q);
494 		q->saved_iova = nib;
495 		q->saved_isc = isc;
496 		break;
497 	case AP_RESPONSE_OTHERWISE_CHANGED:
498 		/* We could not modify IRQ settings: clear new configuration */
499 		ret = kvm_s390_gisc_unregister(kvm, isc);
500 		if (ret)
501 			VFIO_AP_DBF_WARN("%s: kvm_s390_gisc_unregister: rc=%d isc=%d, apqn=%#04x\n",
502 					 __func__, ret, isc, q->apqn);
503 		vfio_unpin_pages(&q->matrix_mdev->vdev, nib, 1);
504 		break;
505 	default:
506 		pr_warn("%s: apqn %04x: response: %02x\n", __func__, q->apqn,
507 			status.response_code);
508 		vfio_ap_irq_disable(q);
509 		break;
510 	}
511 
512 	if (status.response_code != AP_RESPONSE_NORMAL) {
513 		VFIO_AP_DBF_WARN("%s: PQAP(AQIC) failed with status=%#02x: "
514 				 "zone=%#x, ir=%#x, gisc=%#x, f=%#x,"
515 				 "gisa=%#x, isc=%#x, apqn=%#04x\n",
516 				 __func__, status.response_code,
517 				 aqic_gisa.zone, aqic_gisa.ir, aqic_gisa.gisc,
518 				 aqic_gisa.gf, aqic_gisa.gisa, aqic_gisa.isc,
519 				 q->apqn);
520 	}
521 
522 	return status;
523 }
524 
525 /**
526  * vfio_ap_le_guid_to_be_uuid - convert a little endian guid array into an array
527  *				of big endian elements that can be passed by
528  *				value to an s390dbf sprintf event function to
529  *				format a UUID string.
530  *
531  * @guid: the object containing the little endian guid
532  * @uuid: a six-element array of long values that can be passed by value as
533  *	  arguments for a formatting string specifying a UUID.
534  *
535  * The S390 Debug Feature (s390dbf) allows the use of "%s" in the sprintf
536  * event functions if the memory for the passed string is available as long as
537  * the debug feature exists. Since a mediated device can be removed at any
538  * time, it's name can not be used because %s passes the reference to the string
539  * in memory and the reference will go stale once the device is removed .
540  *
541  * The s390dbf string formatting function allows a maximum of 9 arguments for a
542  * message to be displayed in the 'sprintf' view. In order to use the bytes
543  * comprising the mediated device's UUID to display the mediated device name,
544  * they will have to be converted into an array whose elements can be passed by
545  * value to sprintf. For example:
546  *
547  * guid array: { 83, 78, 17, 62, bb, f1, f0, 47, 91, 4d, 32, a2, 2e, 3a, 88, 04 }
548  * mdev name: 62177883-f1bb-47f0-914d-32a22e3a8804
549  * array returned: { 62177883, f1bb, 47f0, 914d, 32a2, 2e3a8804 }
550  * formatting string: "%08lx-%04lx-%04lx-%04lx-%02lx%04lx"
551  */
552 static void vfio_ap_le_guid_to_be_uuid(guid_t *guid, unsigned long *uuid)
553 {
554 	/*
555 	 * The input guid is ordered in little endian, so it needs to be
556 	 * reordered for displaying a UUID as a string. This specifies the
557 	 * guid indices in proper order.
558 	 */
559 	uuid[0] = le32_to_cpup((__le32 *)guid);
560 	uuid[1] = le16_to_cpup((__le16 *)&guid->b[4]);
561 	uuid[2] = le16_to_cpup((__le16 *)&guid->b[6]);
562 	uuid[3] = *((__u16 *)&guid->b[8]);
563 	uuid[4] = *((__u16 *)&guid->b[10]);
564 	uuid[5] = *((__u32 *)&guid->b[12]);
565 }
566 
567 /**
568  * handle_pqap - PQAP instruction callback
569  *
570  * @vcpu: The vcpu on which we received the PQAP instruction
571  *
572  * Get the general register contents to initialize internal variables.
573  * REG[0]: APQN
574  * REG[1]: IR and ISC
575  * REG[2]: NIB
576  *
577  * Response.status may be set to following Response Code:
578  * - AP_RESPONSE_Q_NOT_AVAIL: if the queue is not available
579  * - AP_RESPONSE_DECONFIGURED: if the queue is not configured
580  * - AP_RESPONSE_NORMAL (0) : in case of success
581  *   Check vfio_ap_setirq() and vfio_ap_clrirq() for other possible RC.
582  * We take the matrix_dev lock to ensure serialization on queues and
583  * mediated device access.
584  *
585  * Return: 0 if we could handle the request inside KVM.
586  * Otherwise, returns -EOPNOTSUPP to let QEMU handle the fault.
587  */
588 static int handle_pqap(struct kvm_vcpu *vcpu)
589 {
590 	uint64_t status;
591 	uint16_t apqn;
592 	unsigned long uuid[6];
593 	struct vfio_ap_queue *q;
594 	struct ap_queue_status qstatus = {
595 			       .response_code = AP_RESPONSE_Q_NOT_AVAIL, };
596 	struct ap_matrix_mdev *matrix_mdev;
597 
598 	apqn = vcpu->run->s.regs.gprs[0] & 0xffff;
599 
600 	/* If we do not use the AIV facility just go to userland */
601 	if (!(vcpu->arch.sie_block->eca & ECA_AIV)) {
602 		VFIO_AP_DBF_WARN("%s: AIV facility not installed: apqn=0x%04x, eca=0x%04x\n",
603 				 __func__, apqn, vcpu->arch.sie_block->eca);
604 
605 		return -EOPNOTSUPP;
606 	}
607 
608 	mutex_lock(&matrix_dev->mdevs_lock);
609 
610 	if (!vcpu->kvm->arch.crypto.pqap_hook) {
611 		VFIO_AP_DBF_WARN("%s: PQAP(AQIC) hook not registered with the vfio_ap driver: apqn=0x%04x\n",
612 				 __func__, apqn);
613 
614 		goto out_unlock;
615 	}
616 
617 	matrix_mdev = container_of(vcpu->kvm->arch.crypto.pqap_hook,
618 				   struct ap_matrix_mdev, pqap_hook);
619 
620 	/* If the there is no guest using the mdev, there is nothing to do */
621 	if (!matrix_mdev->kvm) {
622 		vfio_ap_le_guid_to_be_uuid(&matrix_mdev->mdev->uuid, uuid);
623 		VFIO_AP_DBF_WARN("%s: mdev %08lx-%04lx-%04lx-%04lx-%04lx%08lx not in use: apqn=0x%04x\n",
624 				 __func__, uuid[0],  uuid[1], uuid[2],
625 				 uuid[3], uuid[4], uuid[5], apqn);
626 		goto out_unlock;
627 	}
628 
629 	q = vfio_ap_mdev_get_queue(matrix_mdev, apqn);
630 	if (!q) {
631 		VFIO_AP_DBF_WARN("%s: Queue %02x.%04x not bound to the vfio_ap driver\n",
632 				 __func__, AP_QID_CARD(apqn),
633 				 AP_QID_QUEUE(apqn));
634 		goto out_unlock;
635 	}
636 
637 	status = vcpu->run->s.regs.gprs[1];
638 
639 	/* If IR bit(16) is set we enable the interrupt */
640 	if ((status >> (63 - 16)) & 0x01)
641 		qstatus = vfio_ap_irq_enable(q, status & 0x07, vcpu);
642 	else
643 		qstatus = vfio_ap_irq_disable(q);
644 
645 out_unlock:
646 	memcpy(&vcpu->run->s.regs.gprs[1], &qstatus, sizeof(qstatus));
647 	vcpu->run->s.regs.gprs[1] >>= 32;
648 	mutex_unlock(&matrix_dev->mdevs_lock);
649 	return 0;
650 }
651 
652 static void vfio_ap_matrix_init(struct ap_config_info *info,
653 				struct ap_matrix *matrix)
654 {
655 	matrix->apm_max = info->apxa ? info->na : 63;
656 	matrix->aqm_max = info->apxa ? info->nd : 15;
657 	matrix->adm_max = info->apxa ? info->nd : 15;
658 }
659 
660 static void signal_guest_ap_cfg_changed(struct ap_matrix_mdev *matrix_mdev)
661 {
662 	if (matrix_mdev->cfg_chg_trigger)
663 		eventfd_signal(matrix_mdev->cfg_chg_trigger);
664 }
665 
666 static void vfio_ap_mdev_update_guest_apcb(struct ap_matrix_mdev *matrix_mdev)
667 {
668 	if (matrix_mdev->kvm) {
669 		kvm_arch_crypto_set_masks(matrix_mdev->kvm,
670 					  matrix_mdev->shadow_apcb.apm,
671 					  matrix_mdev->shadow_apcb.aqm,
672 					  matrix_mdev->shadow_apcb.adm);
673 
674 		signal_guest_ap_cfg_changed(matrix_mdev);
675 	}
676 }
677 
678 static bool vfio_ap_mdev_filter_cdoms(struct ap_matrix_mdev *matrix_mdev)
679 {
680 	DECLARE_BITMAP(prev_shadow_adm, AP_DOMAINS);
681 
682 	bitmap_copy(prev_shadow_adm, matrix_mdev->shadow_apcb.adm, AP_DOMAINS);
683 	bitmap_and(matrix_mdev->shadow_apcb.adm, matrix_mdev->matrix.adm,
684 		   (unsigned long *)matrix_dev->info.adm, AP_DOMAINS);
685 
686 	return !bitmap_equal(prev_shadow_adm, matrix_mdev->shadow_apcb.adm,
687 			     AP_DOMAINS);
688 }
689 
690 static bool _queue_passable(struct vfio_ap_queue *q)
691 {
692 	if (!q)
693 		return false;
694 
695 	switch (q->reset_status.response_code) {
696 	case AP_RESPONSE_NORMAL:
697 	case AP_RESPONSE_DECONFIGURED:
698 	case AP_RESPONSE_CHECKSTOPPED:
699 		return true;
700 	default:
701 		return false;
702 	}
703 }
704 
705 /*
706  * vfio_ap_mdev_filter_matrix - filter the APQNs assigned to the matrix mdev
707  *				to ensure no queue devices are passed through to
708  *				the guest that are not bound to the vfio_ap
709  *				device driver.
710  *
711  * @matrix_mdev: the matrix mdev whose matrix is to be filtered.
712  * @apm_filtered: a 256-bit bitmap for storing the APIDs filtered from the
713  *		  guest's AP configuration that are still in the host's AP
714  *		  configuration.
715  *
716  * Note: If an APQN referencing a queue device that is not bound to the vfio_ap
717  *	 driver, its APID will be filtered from the guest's APCB. The matrix
718  *	 structure precludes filtering an individual APQN, so its APID will be
719  *	 filtered. Consequently, all queues associated with the adapter that
720  *	 are in the host's AP configuration must be reset. If queues are
721  *	 subsequently made available again to the guest, they should re-appear
722  *	 in a reset state
723  *
724  * Return: a boolean value indicating whether the KVM guest's APCB was changed
725  *	   by the filtering or not.
726  */
727 static bool vfio_ap_mdev_filter_matrix(struct ap_matrix_mdev *matrix_mdev,
728 				       unsigned long *apm_filtered)
729 {
730 	unsigned long apid, apqi, apqn;
731 	DECLARE_BITMAP(prev_shadow_apm, AP_DEVICES);
732 	DECLARE_BITMAP(prev_shadow_aqm, AP_DOMAINS);
733 
734 	bitmap_copy(prev_shadow_apm, matrix_mdev->shadow_apcb.apm, AP_DEVICES);
735 	bitmap_copy(prev_shadow_aqm, matrix_mdev->shadow_apcb.aqm, AP_DOMAINS);
736 	vfio_ap_matrix_init(&matrix_dev->info, &matrix_mdev->shadow_apcb);
737 	bitmap_clear(apm_filtered, 0, AP_DEVICES);
738 
739 	/*
740 	 * Copy the adapters, domains and control domains to the shadow_apcb
741 	 * from the matrix mdev, but only those that are assigned to the host's
742 	 * AP configuration.
743 	 */
744 	bitmap_and(matrix_mdev->shadow_apcb.apm, matrix_mdev->matrix.apm,
745 		   (unsigned long *)matrix_dev->info.apm, AP_DEVICES);
746 	bitmap_and(matrix_mdev->shadow_apcb.aqm, matrix_mdev->matrix.aqm,
747 		   (unsigned long *)matrix_dev->info.aqm, AP_DOMAINS);
748 
749 	for_each_set_bit_inv(apid, matrix_mdev->shadow_apcb.apm, AP_DEVICES) {
750 		for_each_set_bit_inv(apqi, matrix_mdev->shadow_apcb.aqm,
751 				     AP_DOMAINS) {
752 			/*
753 			 * If the APQN is not bound to the vfio_ap device
754 			 * driver, then we can't assign it to the guest's
755 			 * AP configuration. The AP architecture won't
756 			 * allow filtering of a single APQN, so let's filter
757 			 * the APID since an adapter represents a physical
758 			 * hardware device.
759 			 */
760 			apqn = AP_MKQID(apid, apqi);
761 			if (!_queue_passable(vfio_ap_mdev_get_queue(matrix_mdev, apqn))) {
762 				clear_bit_inv(apid, matrix_mdev->shadow_apcb.apm);
763 
764 				/*
765 				 * If the adapter was previously plugged into
766 				 * the guest, let's let the caller know that
767 				 * the APID was filtered.
768 				 */
769 				if (test_bit_inv(apid, prev_shadow_apm))
770 					set_bit_inv(apid, apm_filtered);
771 
772 				break;
773 			}
774 		}
775 	}
776 
777 	return !bitmap_equal(prev_shadow_apm, matrix_mdev->shadow_apcb.apm,
778 			     AP_DEVICES) ||
779 	       !bitmap_equal(prev_shadow_aqm, matrix_mdev->shadow_apcb.aqm,
780 			     AP_DOMAINS);
781 }
782 
783 static int vfio_ap_mdev_init_dev(struct vfio_device *vdev)
784 {
785 	struct ap_matrix_mdev *matrix_mdev =
786 		container_of(vdev, struct ap_matrix_mdev, vdev);
787 
788 	matrix_mdev->mdev = to_mdev_device(vdev->dev);
789 	vfio_ap_matrix_init(&matrix_dev->info, &matrix_mdev->matrix);
790 	matrix_mdev->pqap_hook = handle_pqap;
791 	vfio_ap_matrix_init(&matrix_dev->info, &matrix_mdev->shadow_apcb);
792 	hash_init(matrix_mdev->qtable.queues);
793 
794 	return 0;
795 }
796 
797 static int vfio_ap_mdev_probe(struct mdev_device *mdev)
798 {
799 	struct ap_matrix_mdev *matrix_mdev;
800 	int ret;
801 
802 	matrix_mdev = vfio_alloc_device(ap_matrix_mdev, vdev, &mdev->dev,
803 					&vfio_ap_matrix_dev_ops);
804 	if (IS_ERR(matrix_mdev))
805 		return PTR_ERR(matrix_mdev);
806 
807 	ret = vfio_register_emulated_iommu_dev(&matrix_mdev->vdev);
808 	if (ret)
809 		goto err_put_vdev;
810 
811 	/*
812 	 * Take the matrix_dev->guests_lock mutex before adding the matrix_mdev
813 	 * to the mdev_list. All functions that traverse the list must also hold
814 	 * this lock to guard against additions to or removals from the list
815 	 * while it is being traversed.
816 	 */
817 	mutex_lock(&matrix_dev->guests_lock);
818 	dev_set_drvdata(&mdev->dev, matrix_mdev);
819 	list_add(&matrix_mdev->node, &matrix_dev->mdev_list);
820 	mutex_unlock(&matrix_dev->guests_lock);
821 	return 0;
822 
823 err_put_vdev:
824 	vfio_put_device(&matrix_mdev->vdev);
825 	return ret;
826 }
827 
828 static void vfio_ap_mdev_link_queue(struct ap_matrix_mdev *matrix_mdev,
829 				    struct vfio_ap_queue *q)
830 {
831 	if (!q || vfio_ap_mdev_get_queue(matrix_mdev, q->apqn))
832 		return;
833 
834 	q->matrix_mdev = matrix_mdev;
835 	hash_add(matrix_mdev->qtable.queues, &q->mdev_qnode, q->apqn);
836 }
837 
838 static void vfio_ap_mdev_link_apqn(struct ap_matrix_mdev *matrix_mdev, int apqn)
839 {
840 	struct vfio_ap_queue *q;
841 
842 	q = vfio_ap_find_queue(apqn);
843 	vfio_ap_mdev_link_queue(matrix_mdev, q);
844 }
845 
846 static void vfio_ap_unlink_queue_fr_mdev(struct vfio_ap_queue *q)
847 {
848 	hash_del(&q->mdev_qnode);
849 }
850 
851 static void vfio_ap_unlink_mdev_fr_queue(struct vfio_ap_queue *q)
852 {
853 	q->matrix_mdev = NULL;
854 }
855 
856 static void vfio_ap_mdev_unlink_fr_queues(struct ap_matrix_mdev *matrix_mdev)
857 {
858 	struct vfio_ap_queue *q;
859 	unsigned long apid, apqi;
860 
861 	for_each_set_bit_inv(apid, matrix_mdev->matrix.apm, AP_DEVICES) {
862 		for_each_set_bit_inv(apqi, matrix_mdev->matrix.aqm,
863 				     AP_DOMAINS) {
864 			q = vfio_ap_mdev_get_queue(matrix_mdev,
865 						   AP_MKQID(apid, apqi));
866 			if (q)
867 				q->matrix_mdev = NULL;
868 		}
869 	}
870 }
871 
872 static void vfio_ap_mdev_remove(struct mdev_device *mdev)
873 {
874 	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(&mdev->dev);
875 
876 	vfio_unregister_group_dev(&matrix_mdev->vdev);
877 
878 	mutex_lock(&matrix_dev->guests_lock);
879 	mutex_lock(&matrix_dev->mdevs_lock);
880 	vfio_ap_mdev_reset_queues(matrix_mdev);
881 	vfio_ap_mdev_unlink_fr_queues(matrix_mdev);
882 	list_del(&matrix_mdev->node);
883 	mutex_unlock(&matrix_dev->mdevs_lock);
884 	mutex_unlock(&matrix_dev->guests_lock);
885 	vfio_put_device(&matrix_mdev->vdev);
886 }
887 
888 #define MDEV_SHARING_ERR "Userspace may not assign queue %02lx.%04lx to mdev: already assigned to %s"
889 
890 #define MDEV_IN_USE_ERR "Can not reserve queue %02lx.%04lx for host driver: in use by mdev"
891 
892 static void vfio_ap_mdev_log_sharing_err(struct ap_matrix_mdev *assignee,
893 					 struct ap_matrix_mdev *assigned_to,
894 					 unsigned long *apm, unsigned long *aqm)
895 {
896 	unsigned long apid, apqi;
897 
898 	for_each_set_bit_inv(apid, apm, AP_DEVICES) {
899 		for_each_set_bit_inv(apqi, aqm, AP_DOMAINS) {
900 			dev_warn(mdev_dev(assignee->mdev), MDEV_SHARING_ERR,
901 				 apid, apqi, dev_name(mdev_dev(assigned_to->mdev)));
902 		}
903 	}
904 }
905 
906 static void vfio_ap_mdev_log_in_use_err(struct ap_matrix_mdev *assignee,
907 					unsigned long *apm, unsigned long *aqm)
908 {
909 	unsigned long apid, apqi;
910 
911 	for_each_set_bit_inv(apid, apm, AP_DEVICES) {
912 		for_each_set_bit_inv(apqi, aqm, AP_DOMAINS)
913 			dev_warn(mdev_dev(assignee->mdev), MDEV_IN_USE_ERR, apid, apqi);
914 	}
915 }
916 
917 /**
918  * vfio_ap_mdev_verify_no_sharing - verify APQNs are not shared by matrix mdevs
919  *
920  * @assignee: the matrix mdev to which @mdev_apm and @mdev_aqm are being
921  *	      assigned; or, NULL if this function was called by the AP bus
922  *	      driver in_use callback to verify none of the APQNs being reserved
923  *	      for the host device driver are in use by a vfio_ap mediated device
924  * @mdev_apm: mask indicating the APIDs of the APQNs to be verified
925  * @mdev_aqm: mask indicating the APQIs of the APQNs to be verified
926  *
927  * Verifies that each APQN derived from the Cartesian product of APIDs
928  * represented by the bits set in @mdev_apm and the APQIs of the bits set in
929  * @mdev_aqm is not assigned to a mediated device other than the mdev to which
930  * the APQN is being assigned (@assignee). AP queue sharing is not allowed.
931  *
932  * Return: 0 if the APQNs are not shared; otherwise return -EADDRINUSE.
933  */
934 static int vfio_ap_mdev_verify_no_sharing(struct ap_matrix_mdev *assignee,
935 					  unsigned long *mdev_apm,
936 					  unsigned long *mdev_aqm)
937 {
938 	struct ap_matrix_mdev *assigned_to;
939 	DECLARE_BITMAP(apm, AP_DEVICES);
940 	DECLARE_BITMAP(aqm, AP_DOMAINS);
941 
942 	list_for_each_entry(assigned_to, &matrix_dev->mdev_list, node) {
943 		/*
944 		 * If the mdev to which the mdev_apm and mdev_aqm is being
945 		 * assigned is the same as the mdev being verified
946 		 */
947 		if (assignee == assigned_to)
948 			continue;
949 
950 		memset(apm, 0, sizeof(apm));
951 		memset(aqm, 0, sizeof(aqm));
952 
953 		/*
954 		 * We work on full longs, as we can only exclude the leftover
955 		 * bits in non-inverse order. The leftover is all zeros.
956 		 */
957 		if (!bitmap_and(apm, mdev_apm, assigned_to->matrix.apm,	AP_DEVICES))
958 			continue;
959 
960 		if (!bitmap_and(aqm, mdev_aqm, assigned_to->matrix.aqm,	AP_DOMAINS))
961 			continue;
962 
963 		if (assignee)
964 			vfio_ap_mdev_log_sharing_err(assignee, assigned_to, apm, aqm);
965 		else
966 			vfio_ap_mdev_log_in_use_err(assigned_to, apm, aqm);
967 
968 		return -EADDRINUSE;
969 	}
970 
971 	return 0;
972 }
973 
974 /**
975  * vfio_ap_mdev_validate_masks - verify that the APQNs assigned to the mdev are
976  *				 not reserved for the default zcrypt driver and
977  *				 are not assigned to another mdev.
978  *
979  * @matrix_mdev: the mdev to which the APQNs being validated are assigned.
980  *
981  * Return: One of the following values:
982  * o the error returned from the ap_apqn_in_matrix_owned_by_def_drv() function,
983  *   most likely -EBUSY indicating the ap_attr_mutex lock is already held.
984  * o EADDRNOTAVAIL if an APQN assigned to @matrix_mdev is reserved for the
985  *		   zcrypt default driver.
986  * o EADDRINUSE if an APQN assigned to @matrix_mdev is assigned to another mdev
987  * o A zero indicating validation succeeded.
988  */
989 static int vfio_ap_mdev_validate_masks(struct ap_matrix_mdev *matrix_mdev)
990 {
991 	if (ap_apqn_in_matrix_owned_by_def_drv(matrix_mdev->matrix.apm,
992 					       matrix_mdev->matrix.aqm))
993 		return -EADDRNOTAVAIL;
994 
995 	return vfio_ap_mdev_verify_no_sharing(matrix_mdev,
996 					      matrix_mdev->matrix.apm,
997 					      matrix_mdev->matrix.aqm);
998 }
999 
1000 static void vfio_ap_mdev_link_adapter(struct ap_matrix_mdev *matrix_mdev,
1001 				      unsigned long apid)
1002 {
1003 	unsigned long apqi;
1004 
1005 	for_each_set_bit_inv(apqi, matrix_mdev->matrix.aqm, AP_DOMAINS)
1006 		vfio_ap_mdev_link_apqn(matrix_mdev,
1007 				       AP_MKQID(apid, apqi));
1008 }
1009 
1010 static void collect_queues_to_reset(struct ap_matrix_mdev *matrix_mdev,
1011 				    unsigned long apid,
1012 				    struct list_head *qlist)
1013 {
1014 	struct vfio_ap_queue *q;
1015 	unsigned long  apqi;
1016 
1017 	for_each_set_bit_inv(apqi, matrix_mdev->shadow_apcb.aqm, AP_DOMAINS) {
1018 		q = vfio_ap_mdev_get_queue(matrix_mdev, AP_MKQID(apid, apqi));
1019 		if (q)
1020 			list_add_tail(&q->reset_qnode, qlist);
1021 	}
1022 }
1023 
1024 static void reset_queues_for_apid(struct ap_matrix_mdev *matrix_mdev,
1025 				  unsigned long apid)
1026 {
1027 	struct list_head qlist;
1028 
1029 	INIT_LIST_HEAD(&qlist);
1030 	collect_queues_to_reset(matrix_mdev, apid, &qlist);
1031 	vfio_ap_mdev_reset_qlist(&qlist);
1032 }
1033 
1034 static int reset_queues_for_apids(struct ap_matrix_mdev *matrix_mdev,
1035 				  unsigned long *apm_reset)
1036 {
1037 	struct list_head qlist;
1038 	unsigned long apid;
1039 
1040 	if (bitmap_empty(apm_reset, AP_DEVICES))
1041 		return 0;
1042 
1043 	INIT_LIST_HEAD(&qlist);
1044 
1045 	for_each_set_bit_inv(apid, apm_reset, AP_DEVICES)
1046 		collect_queues_to_reset(matrix_mdev, apid, &qlist);
1047 
1048 	return vfio_ap_mdev_reset_qlist(&qlist);
1049 }
1050 
1051 /**
1052  * assign_adapter_store - parses the APID from @buf and sets the
1053  * corresponding bit in the mediated matrix device's APM
1054  *
1055  * @dev:	the matrix device
1056  * @attr:	the mediated matrix device's assign_adapter attribute
1057  * @buf:	a buffer containing the AP adapter number (APID) to
1058  *		be assigned
1059  * @count:	the number of bytes in @buf
1060  *
1061  * Return: the number of bytes processed if the APID is valid; otherwise,
1062  * returns one of the following errors:
1063  *
1064  *	1. -EINVAL
1065  *	   The APID is not a valid number
1066  *
1067  *	2. -ENODEV
1068  *	   The APID exceeds the maximum value configured for the system
1069  *
1070  *	3. -EADDRNOTAVAIL
1071  *	   An APQN derived from the cross product of the APID being assigned
1072  *	   and the APQIs previously assigned is not bound to the vfio_ap device
1073  *	   driver; or, if no APQIs have yet been assigned, the APID is not
1074  *	   contained in an APQN bound to the vfio_ap device driver.
1075  *
1076  *	4. -EADDRINUSE
1077  *	   An APQN derived from the cross product of the APID being assigned
1078  *	   and the APQIs previously assigned is being used by another mediated
1079  *	   matrix device
1080  *
1081  *	5. -EAGAIN
1082  *	   A lock required to validate the mdev's AP configuration could not
1083  *	   be obtained.
1084  */
1085 static ssize_t assign_adapter_store(struct device *dev,
1086 				    struct device_attribute *attr,
1087 				    const char *buf, size_t count)
1088 {
1089 	int ret;
1090 	unsigned long apid;
1091 	DECLARE_BITMAP(apm_filtered, AP_DEVICES);
1092 	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
1093 
1094 	mutex_lock(&ap_attr_mutex);
1095 	get_update_locks_for_mdev(matrix_mdev);
1096 
1097 	ret = kstrtoul(buf, 0, &apid);
1098 	if (ret)
1099 		goto done;
1100 
1101 	if (apid > matrix_mdev->matrix.apm_max) {
1102 		ret = -ENODEV;
1103 		goto done;
1104 	}
1105 
1106 	if (test_bit_inv(apid, matrix_mdev->matrix.apm)) {
1107 		ret = count;
1108 		goto done;
1109 	}
1110 
1111 	set_bit_inv(apid, matrix_mdev->matrix.apm);
1112 
1113 	ret = vfio_ap_mdev_validate_masks(matrix_mdev);
1114 	if (ret) {
1115 		clear_bit_inv(apid, matrix_mdev->matrix.apm);
1116 		goto done;
1117 	}
1118 
1119 	vfio_ap_mdev_link_adapter(matrix_mdev, apid);
1120 
1121 	if (vfio_ap_mdev_filter_matrix(matrix_mdev, apm_filtered)) {
1122 		vfio_ap_mdev_update_guest_apcb(matrix_mdev);
1123 		reset_queues_for_apids(matrix_mdev, apm_filtered);
1124 	}
1125 
1126 	ret = count;
1127 done:
1128 	release_update_locks_for_mdev(matrix_mdev);
1129 	mutex_unlock(&ap_attr_mutex);
1130 
1131 	return ret;
1132 }
1133 static DEVICE_ATTR_WO(assign_adapter);
1134 
1135 static struct vfio_ap_queue
1136 *vfio_ap_unlink_apqn_fr_mdev(struct ap_matrix_mdev *matrix_mdev,
1137 			     unsigned long apid, unsigned long apqi)
1138 {
1139 	struct vfio_ap_queue *q = NULL;
1140 
1141 	q = vfio_ap_mdev_get_queue(matrix_mdev, AP_MKQID(apid, apqi));
1142 	/* If the queue is assigned to the matrix mdev, unlink it. */
1143 	if (q)
1144 		vfio_ap_unlink_queue_fr_mdev(q);
1145 
1146 	return q;
1147 }
1148 
1149 /**
1150  * vfio_ap_mdev_unlink_adapter - unlink all queues associated with unassigned
1151  *				 adapter from the matrix mdev to which the
1152  *				 adapter was assigned.
1153  * @matrix_mdev: the matrix mediated device to which the adapter was assigned.
1154  * @apid: the APID of the unassigned adapter.
1155  * @qlist: list for storing queues associated with unassigned adapter that
1156  *	   need to be reset.
1157  */
1158 static void vfio_ap_mdev_unlink_adapter(struct ap_matrix_mdev *matrix_mdev,
1159 					unsigned long apid,
1160 					struct list_head *qlist)
1161 {
1162 	unsigned long apqi;
1163 	struct vfio_ap_queue *q;
1164 
1165 	for_each_set_bit_inv(apqi, matrix_mdev->matrix.aqm, AP_DOMAINS) {
1166 		q = vfio_ap_unlink_apqn_fr_mdev(matrix_mdev, apid, apqi);
1167 
1168 		if (q && qlist) {
1169 			if (test_bit_inv(apid, matrix_mdev->shadow_apcb.apm) &&
1170 			    test_bit_inv(apqi, matrix_mdev->shadow_apcb.aqm))
1171 				list_add_tail(&q->reset_qnode, qlist);
1172 		}
1173 	}
1174 }
1175 
1176 static void vfio_ap_mdev_hot_unplug_adapters(struct ap_matrix_mdev *matrix_mdev,
1177 					     unsigned long *apids)
1178 {
1179 	struct vfio_ap_queue *q, *tmpq;
1180 	struct list_head qlist;
1181 	unsigned long apid;
1182 	bool apcb_update = false;
1183 
1184 	INIT_LIST_HEAD(&qlist);
1185 
1186 	for_each_set_bit_inv(apid, apids, AP_DEVICES) {
1187 		vfio_ap_mdev_unlink_adapter(matrix_mdev, apid, &qlist);
1188 
1189 		if (test_bit_inv(apid, matrix_mdev->shadow_apcb.apm)) {
1190 			clear_bit_inv(apid, matrix_mdev->shadow_apcb.apm);
1191 			apcb_update = true;
1192 		}
1193 	}
1194 
1195 	/* Only update apcb if needed to avoid impacting guest */
1196 	if (apcb_update)
1197 		vfio_ap_mdev_update_guest_apcb(matrix_mdev);
1198 
1199 	vfio_ap_mdev_reset_qlist(&qlist);
1200 
1201 	list_for_each_entry_safe(q, tmpq, &qlist, reset_qnode) {
1202 		vfio_ap_unlink_mdev_fr_queue(q);
1203 		list_del(&q->reset_qnode);
1204 	}
1205 }
1206 
1207 static void vfio_ap_mdev_hot_unplug_adapter(struct ap_matrix_mdev *matrix_mdev,
1208 					    unsigned long apid)
1209 {
1210 	DECLARE_BITMAP(apids, AP_DEVICES);
1211 
1212 	bitmap_zero(apids, AP_DEVICES);
1213 	set_bit_inv(apid, apids);
1214 	vfio_ap_mdev_hot_unplug_adapters(matrix_mdev, apids);
1215 }
1216 
1217 /**
1218  * unassign_adapter_store - parses the APID from @buf and clears the
1219  * corresponding bit in the mediated matrix device's APM
1220  *
1221  * @dev:	the matrix device
1222  * @attr:	the mediated matrix device's unassign_adapter attribute
1223  * @buf:	a buffer containing the adapter number (APID) to be unassigned
1224  * @count:	the number of bytes in @buf
1225  *
1226  * Return: the number of bytes processed if the APID is valid; otherwise,
1227  * returns one of the following errors:
1228  *	-EINVAL if the APID is not a number
1229  *	-ENODEV if the APID it exceeds the maximum value configured for the
1230  *		system
1231  */
1232 static ssize_t unassign_adapter_store(struct device *dev,
1233 				      struct device_attribute *attr,
1234 				      const char *buf, size_t count)
1235 {
1236 	int ret;
1237 	unsigned long apid;
1238 	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
1239 
1240 	get_update_locks_for_mdev(matrix_mdev);
1241 
1242 	ret = kstrtoul(buf, 0, &apid);
1243 	if (ret)
1244 		goto done;
1245 
1246 	if (apid > matrix_mdev->matrix.apm_max) {
1247 		ret = -ENODEV;
1248 		goto done;
1249 	}
1250 
1251 	if (!test_bit_inv(apid, matrix_mdev->matrix.apm)) {
1252 		ret = count;
1253 		goto done;
1254 	}
1255 
1256 	clear_bit_inv((unsigned long)apid, matrix_mdev->matrix.apm);
1257 	vfio_ap_mdev_hot_unplug_adapter(matrix_mdev, apid);
1258 	ret = count;
1259 done:
1260 	release_update_locks_for_mdev(matrix_mdev);
1261 	return ret;
1262 }
1263 static DEVICE_ATTR_WO(unassign_adapter);
1264 
1265 static void vfio_ap_mdev_link_domain(struct ap_matrix_mdev *matrix_mdev,
1266 				     unsigned long apqi)
1267 {
1268 	unsigned long apid;
1269 
1270 	for_each_set_bit_inv(apid, matrix_mdev->matrix.apm, AP_DEVICES)
1271 		vfio_ap_mdev_link_apqn(matrix_mdev,
1272 				       AP_MKQID(apid, apqi));
1273 }
1274 
1275 /**
1276  * assign_domain_store - parses the APQI from @buf and sets the
1277  * corresponding bit in the mediated matrix device's AQM
1278  *
1279  * @dev:	the matrix device
1280  * @attr:	the mediated matrix device's assign_domain attribute
1281  * @buf:	a buffer containing the AP queue index (APQI) of the domain to
1282  *		be assigned
1283  * @count:	the number of bytes in @buf
1284  *
1285  * Return: the number of bytes processed if the APQI is valid; otherwise returns
1286  * one of the following errors:
1287  *
1288  *	1. -EINVAL
1289  *	   The APQI is not a valid number
1290  *
1291  *	2. -ENODEV
1292  *	   The APQI exceeds the maximum value configured for the system
1293  *
1294  *	3. -EADDRNOTAVAIL
1295  *	   An APQN derived from the cross product of the APQI being assigned
1296  *	   and the APIDs previously assigned is not bound to the vfio_ap device
1297  *	   driver; or, if no APIDs have yet been assigned, the APQI is not
1298  *	   contained in an APQN bound to the vfio_ap device driver.
1299  *
1300  *	4. -EADDRINUSE
1301  *	   An APQN derived from the cross product of the APQI being assigned
1302  *	   and the APIDs previously assigned is being used by another mediated
1303  *	   matrix device
1304  *
1305  *	5. -EAGAIN
1306  *	   The lock required to validate the mdev's AP configuration could not
1307  *	   be obtained.
1308  */
1309 static ssize_t assign_domain_store(struct device *dev,
1310 				   struct device_attribute *attr,
1311 				   const char *buf, size_t count)
1312 {
1313 	int ret;
1314 	unsigned long apqi;
1315 	DECLARE_BITMAP(apm_filtered, AP_DEVICES);
1316 	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
1317 
1318 	mutex_lock(&ap_attr_mutex);
1319 	get_update_locks_for_mdev(matrix_mdev);
1320 
1321 	ret = kstrtoul(buf, 0, &apqi);
1322 	if (ret)
1323 		goto done;
1324 
1325 	if (apqi > matrix_mdev->matrix.aqm_max) {
1326 		ret = -ENODEV;
1327 		goto done;
1328 	}
1329 
1330 	if (test_bit_inv(apqi, matrix_mdev->matrix.aqm)) {
1331 		ret = count;
1332 		goto done;
1333 	}
1334 
1335 	set_bit_inv(apqi, matrix_mdev->matrix.aqm);
1336 
1337 	ret = vfio_ap_mdev_validate_masks(matrix_mdev);
1338 	if (ret) {
1339 		clear_bit_inv(apqi, matrix_mdev->matrix.aqm);
1340 		goto done;
1341 	}
1342 
1343 	vfio_ap_mdev_link_domain(matrix_mdev, apqi);
1344 
1345 	if (vfio_ap_mdev_filter_matrix(matrix_mdev, apm_filtered)) {
1346 		vfio_ap_mdev_update_guest_apcb(matrix_mdev);
1347 		reset_queues_for_apids(matrix_mdev, apm_filtered);
1348 	}
1349 
1350 	ret = count;
1351 done:
1352 	release_update_locks_for_mdev(matrix_mdev);
1353 	mutex_unlock(&ap_attr_mutex);
1354 
1355 	return ret;
1356 }
1357 static DEVICE_ATTR_WO(assign_domain);
1358 
1359 static void vfio_ap_mdev_unlink_domain(struct ap_matrix_mdev *matrix_mdev,
1360 				       unsigned long apqi,
1361 				       struct list_head *qlist)
1362 {
1363 	unsigned long apid;
1364 	struct vfio_ap_queue *q;
1365 
1366 	for_each_set_bit_inv(apid, matrix_mdev->matrix.apm, AP_DEVICES) {
1367 		q = vfio_ap_unlink_apqn_fr_mdev(matrix_mdev, apid, apqi);
1368 
1369 		if (q && qlist) {
1370 			if (test_bit_inv(apid, matrix_mdev->shadow_apcb.apm) &&
1371 			    test_bit_inv(apqi, matrix_mdev->shadow_apcb.aqm))
1372 				list_add_tail(&q->reset_qnode, qlist);
1373 		}
1374 	}
1375 }
1376 
1377 static void vfio_ap_mdev_hot_unplug_domains(struct ap_matrix_mdev *matrix_mdev,
1378 					    unsigned long *apqis)
1379 {
1380 	struct vfio_ap_queue *q, *tmpq;
1381 	struct list_head qlist;
1382 	unsigned long apqi;
1383 	bool apcb_update = false;
1384 
1385 	INIT_LIST_HEAD(&qlist);
1386 
1387 	for_each_set_bit_inv(apqi, apqis, AP_DOMAINS) {
1388 		vfio_ap_mdev_unlink_domain(matrix_mdev, apqi, &qlist);
1389 
1390 		if (test_bit_inv(apqi, matrix_mdev->shadow_apcb.aqm)) {
1391 			clear_bit_inv(apqi, matrix_mdev->shadow_apcb.aqm);
1392 			apcb_update = true;
1393 		}
1394 	}
1395 
1396 	/* Only update apcb if needed to avoid impacting guest */
1397 	if (apcb_update)
1398 		vfio_ap_mdev_update_guest_apcb(matrix_mdev);
1399 
1400 	vfio_ap_mdev_reset_qlist(&qlist);
1401 
1402 	list_for_each_entry_safe(q, tmpq, &qlist, reset_qnode) {
1403 		vfio_ap_unlink_mdev_fr_queue(q);
1404 		list_del(&q->reset_qnode);
1405 	}
1406 }
1407 
1408 static void vfio_ap_mdev_hot_unplug_domain(struct ap_matrix_mdev *matrix_mdev,
1409 					   unsigned long apqi)
1410 {
1411 	DECLARE_BITMAP(apqis, AP_DOMAINS);
1412 
1413 	bitmap_zero(apqis, AP_DEVICES);
1414 	set_bit_inv(apqi, apqis);
1415 	vfio_ap_mdev_hot_unplug_domains(matrix_mdev, apqis);
1416 }
1417 
1418 /**
1419  * unassign_domain_store - parses the APQI from @buf and clears the
1420  * corresponding bit in the mediated matrix device's AQM
1421  *
1422  * @dev:	the matrix device
1423  * @attr:	the mediated matrix device's unassign_domain attribute
1424  * @buf:	a buffer containing the AP queue index (APQI) of the domain to
1425  *		be unassigned
1426  * @count:	the number of bytes in @buf
1427  *
1428  * Return: the number of bytes processed if the APQI is valid; otherwise,
1429  * returns one of the following errors:
1430  *	-EINVAL if the APQI is not a number
1431  *	-ENODEV if the APQI exceeds the maximum value configured for the system
1432  */
1433 static ssize_t unassign_domain_store(struct device *dev,
1434 				     struct device_attribute *attr,
1435 				     const char *buf, size_t count)
1436 {
1437 	int ret;
1438 	unsigned long apqi;
1439 	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
1440 
1441 	get_update_locks_for_mdev(matrix_mdev);
1442 
1443 	ret = kstrtoul(buf, 0, &apqi);
1444 	if (ret)
1445 		goto done;
1446 
1447 	if (apqi > matrix_mdev->matrix.aqm_max) {
1448 		ret = -ENODEV;
1449 		goto done;
1450 	}
1451 
1452 	if (!test_bit_inv(apqi, matrix_mdev->matrix.aqm)) {
1453 		ret = count;
1454 		goto done;
1455 	}
1456 
1457 	clear_bit_inv((unsigned long)apqi, matrix_mdev->matrix.aqm);
1458 	vfio_ap_mdev_hot_unplug_domain(matrix_mdev, apqi);
1459 	ret = count;
1460 
1461 done:
1462 	release_update_locks_for_mdev(matrix_mdev);
1463 	return ret;
1464 }
1465 static DEVICE_ATTR_WO(unassign_domain);
1466 
1467 /**
1468  * assign_control_domain_store - parses the domain ID from @buf and sets
1469  * the corresponding bit in the mediated matrix device's ADM
1470  *
1471  * @dev:	the matrix device
1472  * @attr:	the mediated matrix device's assign_control_domain attribute
1473  * @buf:	a buffer containing the domain ID to be assigned
1474  * @count:	the number of bytes in @buf
1475  *
1476  * Return: the number of bytes processed if the domain ID is valid; otherwise,
1477  * returns one of the following errors:
1478  *	-EINVAL if the ID is not a number
1479  *	-ENODEV if the ID exceeds the maximum value configured for the system
1480  */
1481 static ssize_t assign_control_domain_store(struct device *dev,
1482 					   struct device_attribute *attr,
1483 					   const char *buf, size_t count)
1484 {
1485 	int ret;
1486 	unsigned long id;
1487 	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
1488 
1489 	get_update_locks_for_mdev(matrix_mdev);
1490 
1491 	ret = kstrtoul(buf, 0, &id);
1492 	if (ret)
1493 		goto done;
1494 
1495 	if (id > matrix_mdev->matrix.adm_max) {
1496 		ret = -ENODEV;
1497 		goto done;
1498 	}
1499 
1500 	if (test_bit_inv(id, matrix_mdev->matrix.adm)) {
1501 		ret = count;
1502 		goto done;
1503 	}
1504 
1505 	/* Set the bit in the ADM (bitmask) corresponding to the AP control
1506 	 * domain number (id). The bits in the mask, from most significant to
1507 	 * least significant, correspond to IDs 0 up to the one less than the
1508 	 * number of control domains that can be assigned.
1509 	 */
1510 	set_bit_inv(id, matrix_mdev->matrix.adm);
1511 	if (vfio_ap_mdev_filter_cdoms(matrix_mdev))
1512 		vfio_ap_mdev_update_guest_apcb(matrix_mdev);
1513 
1514 	ret = count;
1515 done:
1516 	release_update_locks_for_mdev(matrix_mdev);
1517 	return ret;
1518 }
1519 static DEVICE_ATTR_WO(assign_control_domain);
1520 
1521 /**
1522  * unassign_control_domain_store - parses the domain ID from @buf and
1523  * clears the corresponding bit in the mediated matrix device's ADM
1524  *
1525  * @dev:	the matrix device
1526  * @attr:	the mediated matrix device's unassign_control_domain attribute
1527  * @buf:	a buffer containing the domain ID to be unassigned
1528  * @count:	the number of bytes in @buf
1529  *
1530  * Return: the number of bytes processed if the domain ID is valid; otherwise,
1531  * returns one of the following errors:
1532  *	-EINVAL if the ID is not a number
1533  *	-ENODEV if the ID exceeds the maximum value configured for the system
1534  */
1535 static ssize_t unassign_control_domain_store(struct device *dev,
1536 					     struct device_attribute *attr,
1537 					     const char *buf, size_t count)
1538 {
1539 	int ret;
1540 	unsigned long domid;
1541 	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
1542 
1543 	get_update_locks_for_mdev(matrix_mdev);
1544 
1545 	ret = kstrtoul(buf, 0, &domid);
1546 	if (ret)
1547 		goto done;
1548 
1549 	if (domid > matrix_mdev->matrix.adm_max) {
1550 		ret = -ENODEV;
1551 		goto done;
1552 	}
1553 
1554 	if (!test_bit_inv(domid, matrix_mdev->matrix.adm)) {
1555 		ret = count;
1556 		goto done;
1557 	}
1558 
1559 	clear_bit_inv(domid, matrix_mdev->matrix.adm);
1560 
1561 	if (test_bit_inv(domid, matrix_mdev->shadow_apcb.adm)) {
1562 		clear_bit_inv(domid, matrix_mdev->shadow_apcb.adm);
1563 		vfio_ap_mdev_update_guest_apcb(matrix_mdev);
1564 	}
1565 
1566 	ret = count;
1567 done:
1568 	release_update_locks_for_mdev(matrix_mdev);
1569 	return ret;
1570 }
1571 static DEVICE_ATTR_WO(unassign_control_domain);
1572 
1573 static ssize_t control_domains_show(struct device *dev,
1574 				    struct device_attribute *dev_attr,
1575 				    char *buf)
1576 {
1577 	unsigned long id;
1578 	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
1579 	unsigned long max_domid = matrix_mdev->matrix.adm_max;
1580 	int nchars = 0;
1581 
1582 	mutex_lock(&matrix_dev->mdevs_lock);
1583 	for_each_set_bit_inv(id, matrix_mdev->matrix.adm, max_domid + 1)
1584 		nchars += sysfs_emit_at(buf, nchars, "%04lx\n", id);
1585 	mutex_unlock(&matrix_dev->mdevs_lock);
1586 
1587 	return nchars;
1588 }
1589 static DEVICE_ATTR_RO(control_domains);
1590 
1591 static ssize_t vfio_ap_mdev_matrix_show(struct ap_matrix *matrix, char *buf)
1592 {
1593 	unsigned long apid;
1594 	unsigned long apqi;
1595 	unsigned long apid1;
1596 	unsigned long apqi1;
1597 	unsigned long napm_bits = matrix->apm_max + 1;
1598 	unsigned long naqm_bits = matrix->aqm_max + 1;
1599 	int nchars = 0;
1600 
1601 	apid1 = find_first_bit_inv(matrix->apm, napm_bits);
1602 	apqi1 = find_first_bit_inv(matrix->aqm, naqm_bits);
1603 
1604 	if ((apid1 < napm_bits) && (apqi1 < naqm_bits)) {
1605 		for_each_set_bit_inv(apid, matrix->apm, napm_bits) {
1606 			for_each_set_bit_inv(apqi, matrix->aqm, naqm_bits)
1607 				nchars += sysfs_emit_at(buf, nchars, "%02lx.%04lx\n", apid, apqi);
1608 		}
1609 	} else if (apid1 < napm_bits) {
1610 		for_each_set_bit_inv(apid, matrix->apm, napm_bits)
1611 			nchars += sysfs_emit_at(buf, nchars, "%02lx.\n", apid);
1612 	} else if (apqi1 < naqm_bits) {
1613 		for_each_set_bit_inv(apqi, matrix->aqm, naqm_bits)
1614 			nchars += sysfs_emit_at(buf, nchars, ".%04lx\n", apqi);
1615 	}
1616 
1617 	return nchars;
1618 }
1619 
1620 static ssize_t matrix_show(struct device *dev, struct device_attribute *attr,
1621 			   char *buf)
1622 {
1623 	ssize_t nchars;
1624 	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
1625 
1626 	mutex_lock(&matrix_dev->mdevs_lock);
1627 	nchars = vfio_ap_mdev_matrix_show(&matrix_mdev->matrix, buf);
1628 	mutex_unlock(&matrix_dev->mdevs_lock);
1629 
1630 	return nchars;
1631 }
1632 static DEVICE_ATTR_RO(matrix);
1633 
1634 static ssize_t guest_matrix_show(struct device *dev,
1635 				 struct device_attribute *attr, char *buf)
1636 {
1637 	ssize_t nchars;
1638 	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
1639 
1640 	mutex_lock(&matrix_dev->mdevs_lock);
1641 	nchars = vfio_ap_mdev_matrix_show(&matrix_mdev->shadow_apcb, buf);
1642 	mutex_unlock(&matrix_dev->mdevs_lock);
1643 
1644 	return nchars;
1645 }
1646 static DEVICE_ATTR_RO(guest_matrix);
1647 
1648 static ssize_t write_ap_bitmap(unsigned long *bitmap, char *buf, int offset, char sep)
1649 {
1650 	return sysfs_emit_at(buf, offset, "0x%016lx%016lx%016lx%016lx%c",
1651 			 bitmap[0], bitmap[1], bitmap[2], bitmap[3], sep);
1652 }
1653 
1654 static ssize_t ap_config_show(struct device *dev, struct device_attribute *attr,
1655 			      char *buf)
1656 {
1657 	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
1658 	int idx = 0;
1659 
1660 	idx += write_ap_bitmap(matrix_mdev->matrix.apm, buf, idx, ',');
1661 	idx += write_ap_bitmap(matrix_mdev->matrix.aqm, buf, idx, ',');
1662 	idx += write_ap_bitmap(matrix_mdev->matrix.adm, buf, idx, '\n');
1663 
1664 	return idx;
1665 }
1666 
1667 /* Number of characters needed for a complete hex mask representing the bits in ..  */
1668 #define AP_DEVICES_STRLEN	(AP_DEVICES / 4 + 3)
1669 #define AP_DOMAINS_STRLEN	(AP_DOMAINS / 4 + 3)
1670 #define AP_CONFIG_STRLEN	(AP_DEVICES_STRLEN + 2 * AP_DOMAINS_STRLEN)
1671 
1672 static int parse_bitmap(char **strbufptr, unsigned long *bitmap, int nbits)
1673 {
1674 	char *curmask;
1675 
1676 	curmask = strsep(strbufptr, ",\n");
1677 	if (!curmask)
1678 		return -EINVAL;
1679 
1680 	bitmap_clear(bitmap, 0, nbits);
1681 	return ap_hex2bitmap(curmask, bitmap, nbits);
1682 }
1683 
1684 static int ap_matrix_overflow_check(struct ap_matrix_mdev *matrix_mdev)
1685 {
1686 	unsigned long bit;
1687 
1688 	for_each_set_bit_inv(bit, matrix_mdev->matrix.apm, AP_DEVICES) {
1689 		if (bit > matrix_mdev->matrix.apm_max)
1690 			return -ENODEV;
1691 	}
1692 
1693 	for_each_set_bit_inv(bit, matrix_mdev->matrix.aqm, AP_DOMAINS) {
1694 		if (bit > matrix_mdev->matrix.aqm_max)
1695 			return -ENODEV;
1696 	}
1697 
1698 	for_each_set_bit_inv(bit, matrix_mdev->matrix.adm, AP_DOMAINS) {
1699 		if (bit > matrix_mdev->matrix.adm_max)
1700 			return -ENODEV;
1701 	}
1702 
1703 	return 0;
1704 }
1705 
1706 static void ap_matrix_copy(struct ap_matrix *dst, struct ap_matrix *src)
1707 {
1708 	/* This check works around false positive gcc -Wstringop-overread */
1709 	if (!src)
1710 		return;
1711 
1712 	bitmap_copy(dst->apm, src->apm, AP_DEVICES);
1713 	bitmap_copy(dst->aqm, src->aqm, AP_DOMAINS);
1714 	bitmap_copy(dst->adm, src->adm, AP_DOMAINS);
1715 }
1716 
1717 static ssize_t ap_config_store(struct device *dev, struct device_attribute *attr,
1718 			       const char *buf, size_t count)
1719 {
1720 	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
1721 	struct ap_matrix m_new, m_old, m_added, m_removed;
1722 	DECLARE_BITMAP(apm_filtered, AP_DEVICES);
1723 	unsigned long newbit;
1724 	char *newbuf, *rest;
1725 	int rc = count;
1726 	bool do_update;
1727 
1728 	newbuf = kstrndup(buf, AP_CONFIG_STRLEN, GFP_KERNEL);
1729 	if (!newbuf)
1730 		return -ENOMEM;
1731 	rest = newbuf;
1732 
1733 	mutex_lock(&ap_attr_mutex);
1734 	get_update_locks_for_mdev(matrix_mdev);
1735 
1736 	/* Save old state */
1737 	ap_matrix_copy(&m_old, &matrix_mdev->matrix);
1738 	if (parse_bitmap(&rest, m_new.apm, AP_DEVICES) ||
1739 	    parse_bitmap(&rest, m_new.aqm, AP_DOMAINS) ||
1740 	    parse_bitmap(&rest, m_new.adm, AP_DOMAINS)) {
1741 		rc = -EINVAL;
1742 		goto out;
1743 	}
1744 
1745 	bitmap_andnot(m_removed.apm, m_old.apm, m_new.apm, AP_DEVICES);
1746 	bitmap_andnot(m_removed.aqm, m_old.aqm, m_new.aqm, AP_DOMAINS);
1747 	bitmap_andnot(m_added.apm, m_new.apm, m_old.apm, AP_DEVICES);
1748 	bitmap_andnot(m_added.aqm, m_new.aqm, m_old.aqm, AP_DOMAINS);
1749 
1750 	/* Need new bitmaps in matrix_mdev for validation */
1751 	ap_matrix_copy(&matrix_mdev->matrix, &m_new);
1752 
1753 	/* Ensure new state is valid, else undo new state */
1754 	rc = vfio_ap_mdev_validate_masks(matrix_mdev);
1755 	if (rc) {
1756 		ap_matrix_copy(&matrix_mdev->matrix, &m_old);
1757 		goto out;
1758 	}
1759 	rc = ap_matrix_overflow_check(matrix_mdev);
1760 	if (rc) {
1761 		ap_matrix_copy(&matrix_mdev->matrix, &m_old);
1762 		goto out;
1763 	}
1764 	rc = count;
1765 
1766 	/* Need old bitmaps in matrix_mdev for unplug/unlink */
1767 	ap_matrix_copy(&matrix_mdev->matrix, &m_old);
1768 
1769 	/* Unlink removed adapters/domains */
1770 	vfio_ap_mdev_hot_unplug_adapters(matrix_mdev, m_removed.apm);
1771 	vfio_ap_mdev_hot_unplug_domains(matrix_mdev, m_removed.aqm);
1772 
1773 	/* Need new bitmaps in matrix_mdev for linking new adapters/domains */
1774 	ap_matrix_copy(&matrix_mdev->matrix, &m_new);
1775 
1776 	/* Link newly added adapters */
1777 	for_each_set_bit_inv(newbit, m_added.apm, AP_DEVICES)
1778 		vfio_ap_mdev_link_adapter(matrix_mdev, newbit);
1779 
1780 	for_each_set_bit_inv(newbit, m_added.aqm, AP_DOMAINS)
1781 		vfio_ap_mdev_link_domain(matrix_mdev, newbit);
1782 
1783 	/* filter resources not bound to vfio-ap */
1784 	do_update = vfio_ap_mdev_filter_matrix(matrix_mdev, apm_filtered);
1785 	do_update |= vfio_ap_mdev_filter_cdoms(matrix_mdev);
1786 
1787 	/* Apply changes to shadow apbc if things changed */
1788 	if (do_update) {
1789 		vfio_ap_mdev_update_guest_apcb(matrix_mdev);
1790 		reset_queues_for_apids(matrix_mdev, apm_filtered);
1791 	}
1792 out:
1793 	release_update_locks_for_mdev(matrix_mdev);
1794 	mutex_unlock(&ap_attr_mutex);
1795 	kfree(newbuf);
1796 	return rc;
1797 }
1798 static DEVICE_ATTR_RW(ap_config);
1799 
1800 static struct attribute *vfio_ap_mdev_attrs[] = {
1801 	&dev_attr_assign_adapter.attr,
1802 	&dev_attr_unassign_adapter.attr,
1803 	&dev_attr_assign_domain.attr,
1804 	&dev_attr_unassign_domain.attr,
1805 	&dev_attr_assign_control_domain.attr,
1806 	&dev_attr_unassign_control_domain.attr,
1807 	&dev_attr_ap_config.attr,
1808 	&dev_attr_control_domains.attr,
1809 	&dev_attr_matrix.attr,
1810 	&dev_attr_guest_matrix.attr,
1811 	NULL,
1812 };
1813 
1814 static struct attribute_group vfio_ap_mdev_attr_group = {
1815 	.attrs = vfio_ap_mdev_attrs
1816 };
1817 
1818 static const struct attribute_group *vfio_ap_mdev_attr_groups[] = {
1819 	&vfio_ap_mdev_attr_group,
1820 	NULL
1821 };
1822 
1823 /**
1824  * vfio_ap_mdev_set_kvm - sets all data for @matrix_mdev that are needed
1825  * to manage AP resources for the guest whose state is represented by
1826  * @kvm_file
1827  *
1828  * @matrix_mdev: a mediated matrix device
1829  * @kvm_file: the KVM VM file this vfio device is associated with
1830  *
1831  * Return: 0 if no other mediated matrix device has a reference to the VM;
1832  * otherwise, returns an -EPERM.
1833  */
1834 static int vfio_ap_mdev_set_kvm(struct ap_matrix_mdev *matrix_mdev,
1835 				struct file *kvm_file)
1836 {
1837 	struct kvm *kvm;
1838 
1839 	if (!kvm_file)
1840 		return -ENOENT;
1841 
1842 	kvm = file_to_kvm_s390(kvm_file);
1843 	if (!kvm)
1844 		return -ENOENT;
1845 
1846 	if (kvm->arch.crypto.crycbd) {
1847 		get_update_locks_for_kvm(kvm);
1848 		if (kvm->arch.crypto.pqap_hook) {
1849 			release_update_locks_for_kvm(kvm);
1850 			return -EPERM;
1851 		}
1852 		kvm->arch.crypto.pqap_hook = &matrix_mdev->pqap_hook;
1853 
1854 		matrix_mdev->kvm = kvm;
1855 		vfio_ap_mdev_update_guest_apcb(matrix_mdev);
1856 		release_update_locks_for_kvm(kvm);
1857 	}
1858 
1859 	return 0;
1860 }
1861 
1862 static void unmap_iova(struct ap_matrix_mdev *matrix_mdev, u64 iova, u64 length)
1863 {
1864 	struct ap_queue_table *qtable = &matrix_mdev->qtable;
1865 	struct vfio_ap_queue *q;
1866 	int loop_cursor;
1867 
1868 	hash_for_each(qtable->queues, loop_cursor, q, mdev_qnode) {
1869 		if (q->saved_iova >= iova && q->saved_iova < iova + length)
1870 			vfio_ap_irq_disable(q);
1871 	}
1872 }
1873 
1874 static void vfio_ap_mdev_dma_unmap(struct vfio_device *vdev, u64 iova,
1875 				   u64 length)
1876 {
1877 	struct ap_matrix_mdev *matrix_mdev =
1878 		container_of(vdev, struct ap_matrix_mdev, vdev);
1879 
1880 	mutex_lock(&matrix_dev->mdevs_lock);
1881 
1882 	unmap_iova(matrix_mdev, iova, length);
1883 
1884 	mutex_unlock(&matrix_dev->mdevs_lock);
1885 }
1886 
1887 /**
1888  * vfio_ap_mdev_unset_kvm - performs clean-up of resources no longer needed
1889  * by @matrix_mdev.
1890  *
1891  * @matrix_mdev: a matrix mediated device
1892  */
1893 static void vfio_ap_mdev_unset_kvm(struct ap_matrix_mdev *matrix_mdev)
1894 {
1895 	struct kvm *kvm = matrix_mdev->kvm;
1896 
1897 	if (kvm && kvm->arch.crypto.crycbd) {
1898 		get_update_locks_for_kvm(kvm);
1899 		kvm->arch.crypto.pqap_hook = NULL;
1900 
1901 		kvm_arch_crypto_clear_masks(kvm);
1902 		vfio_ap_mdev_reset_queues(matrix_mdev);
1903 		matrix_mdev->kvm = NULL;
1904 
1905 		release_update_locks_for_kvm(kvm);
1906 	}
1907 }
1908 
1909 static struct vfio_ap_queue *vfio_ap_find_queue(int apqn)
1910 {
1911 	struct ap_queue *queue;
1912 	struct vfio_ap_queue *q = NULL;
1913 
1914 	queue = ap_get_qdev(apqn);
1915 	if (!queue)
1916 		return NULL;
1917 
1918 	if (queue->ap_dev.device.driver == &matrix_dev->vfio_ap_drv->driver)
1919 		q = dev_get_drvdata(&queue->ap_dev.device);
1920 
1921 	put_device(&queue->ap_dev.device);
1922 
1923 	return q;
1924 }
1925 
1926 static int apq_status_check(int apqn, struct ap_queue_status *status)
1927 {
1928 	switch (status->response_code) {
1929 	case AP_RESPONSE_NORMAL:
1930 	case AP_RESPONSE_DECONFIGURED:
1931 	case AP_RESPONSE_CHECKSTOPPED:
1932 		return 0;
1933 	case AP_RESPONSE_RESET_IN_PROGRESS:
1934 	case AP_RESPONSE_BUSY:
1935 		return -EBUSY;
1936 	case AP_RESPONSE_ASSOC_SECRET_NOT_UNIQUE:
1937 	case AP_RESPONSE_ASSOC_FAILED:
1938 		/*
1939 		 * These asynchronous response codes indicate a PQAP(AAPQ)
1940 		 * instruction to associate a secret with the guest failed. All
1941 		 * subsequent AP instructions will end with the asynchronous
1942 		 * response code until the AP queue is reset; so, let's return
1943 		 * a value indicating a reset needs to be performed again.
1944 		 */
1945 		return -EAGAIN;
1946 	case AP_RESPONSE_Q_NOT_AVAIL:
1947 		return -ENODEV;
1948 	default:
1949 		WARN(true,
1950 		     "failed to verify reset of queue %02x.%04x: TAPQ rc=%u\n",
1951 		     AP_QID_CARD(apqn), AP_QID_QUEUE(apqn),
1952 		     status->response_code);
1953 		return -EIO;
1954 	}
1955 }
1956 
1957 #define WAIT_MSG "Waited %dms for reset of queue %02x.%04x (%u, %u, %u)"
1958 
1959 static void apq_reset_check(struct work_struct *reset_work)
1960 {
1961 	int ret = -EBUSY, elapsed = 0;
1962 	struct ap_queue_status status;
1963 	struct vfio_ap_queue *q;
1964 
1965 	q = container_of(reset_work, struct vfio_ap_queue, reset_work);
1966 	memcpy(&status, &q->reset_status, sizeof(status));
1967 	while (true) {
1968 		msleep(AP_RESET_INTERVAL);
1969 		elapsed += AP_RESET_INTERVAL;
1970 		status = ap_tapq(q->apqn, NULL);
1971 		ret = apq_status_check(q->apqn, &status);
1972 		if (ret == -EIO)
1973 			return;
1974 		if (ret == -ENODEV) {
1975 			vfio_ap_free_aqic_resources(q);
1976 			return;
1977 		}
1978 		if (ret == -EBUSY) {
1979 			pr_notice_ratelimited(WAIT_MSG, elapsed,
1980 					      AP_QID_CARD(q->apqn),
1981 					      AP_QID_QUEUE(q->apqn),
1982 					      status.response_code,
1983 					      status.queue_empty,
1984 					      status.irq_enabled);
1985 		} else {
1986 			if (q->reset_status.response_code == AP_RESPONSE_RESET_IN_PROGRESS ||
1987 			    q->reset_status.response_code == AP_RESPONSE_BUSY ||
1988 			    q->reset_status.response_code == AP_RESPONSE_STATE_CHANGE_IN_PROGRESS ||
1989 			    ret == -EAGAIN) {
1990 				status = ap_zapq(q->apqn, 0);
1991 				memcpy(&q->reset_status, &status, sizeof(status));
1992 				continue;
1993 			}
1994 			if (q->saved_isc != VFIO_AP_ISC_INVALID)
1995 				vfio_ap_free_aqic_resources(q);
1996 			break;
1997 		}
1998 	}
1999 }
2000 
2001 static void vfio_ap_mdev_reset_queue(struct vfio_ap_queue *q)
2002 {
2003 	struct ap_queue_status status;
2004 
2005 	if (!q)
2006 		return;
2007 	status = ap_zapq(q->apqn, 0);
2008 	memcpy(&q->reset_status, &status, sizeof(status));
2009 	switch (status.response_code) {
2010 	case AP_RESPONSE_NORMAL:
2011 	case AP_RESPONSE_RESET_IN_PROGRESS:
2012 	case AP_RESPONSE_BUSY:
2013 	case AP_RESPONSE_STATE_CHANGE_IN_PROGRESS:
2014 		/*
2015 		 * Let's verify whether the ZAPQ completed successfully on a work queue.
2016 		 */
2017 		queue_work(system_long_wq, &q->reset_work);
2018 		break;
2019 	case AP_RESPONSE_DECONFIGURED:
2020 	case AP_RESPONSE_CHECKSTOPPED:
2021 	case AP_RESPONSE_Q_NOT_AVAIL:
2022 		vfio_ap_free_aqic_resources(q);
2023 		break;
2024 	default:
2025 		WARN(true,
2026 		     "PQAP/ZAPQ for %02x.%04x failed with invalid rc=%u\n",
2027 		     AP_QID_CARD(q->apqn), AP_QID_QUEUE(q->apqn),
2028 		     status.response_code);
2029 	}
2030 }
2031 
2032 static int vfio_ap_mdev_reset_queues(struct ap_matrix_mdev *matrix_mdev)
2033 {
2034 	int ret = 0, loop_cursor;
2035 	struct vfio_ap_queue *q;
2036 
2037 	hash_for_each(matrix_mdev->qtable.queues, loop_cursor, q, mdev_qnode)
2038 		vfio_ap_mdev_reset_queue(q);
2039 
2040 	hash_for_each(matrix_mdev->qtable.queues, loop_cursor, q, mdev_qnode) {
2041 		flush_work(&q->reset_work);
2042 
2043 		if (q->reset_status.response_code)
2044 			ret = -EIO;
2045 	}
2046 
2047 	return ret;
2048 }
2049 
2050 static int vfio_ap_mdev_reset_qlist(struct list_head *qlist)
2051 {
2052 	int ret = 0;
2053 	struct vfio_ap_queue *q;
2054 
2055 	list_for_each_entry(q, qlist, reset_qnode)
2056 		vfio_ap_mdev_reset_queue(q);
2057 
2058 	list_for_each_entry(q, qlist, reset_qnode) {
2059 		flush_work(&q->reset_work);
2060 
2061 		if (q->reset_status.response_code)
2062 			ret = -EIO;
2063 	}
2064 
2065 	return ret;
2066 }
2067 
2068 static int vfio_ap_mdev_open_device(struct vfio_device *vdev)
2069 {
2070 	struct ap_matrix_mdev *matrix_mdev =
2071 		container_of(vdev, struct ap_matrix_mdev, vdev);
2072 
2073 	if (!vdev->kvm)
2074 		return -EINVAL;
2075 
2076 	return vfio_ap_mdev_set_kvm(matrix_mdev, vdev->kvm);
2077 }
2078 
2079 static void vfio_ap_mdev_close_device(struct vfio_device *vdev)
2080 {
2081 	struct ap_matrix_mdev *matrix_mdev =
2082 		container_of(vdev, struct ap_matrix_mdev, vdev);
2083 
2084 	vfio_ap_mdev_unset_kvm(matrix_mdev);
2085 }
2086 
2087 static void vfio_ap_mdev_request(struct vfio_device *vdev, unsigned int count)
2088 {
2089 	struct device *dev = vdev->dev;
2090 	struct ap_matrix_mdev *matrix_mdev;
2091 
2092 	matrix_mdev = container_of(vdev, struct ap_matrix_mdev, vdev);
2093 
2094 	get_update_locks_for_mdev(matrix_mdev);
2095 
2096 	if (matrix_mdev->kvm) {
2097 		kvm_arch_crypto_clear_masks(matrix_mdev->kvm);
2098 		signal_guest_ap_cfg_changed(matrix_mdev);
2099 	}
2100 
2101 	if (matrix_mdev->req_trigger) {
2102 		if (!(count % 10))
2103 			dev_notice_ratelimited(dev,
2104 					       "Relaying device request to user (#%u)\n",
2105 					       count);
2106 
2107 		eventfd_signal(matrix_mdev->req_trigger);
2108 	} else if (count == 0) {
2109 		dev_notice(dev,
2110 			   "No device request registered, blocked until released by user\n");
2111 	}
2112 
2113 	release_update_locks_for_mdev(matrix_mdev);
2114 }
2115 
2116 static int vfio_ap_mdev_get_device_info(unsigned long arg)
2117 {
2118 	unsigned long minsz;
2119 	struct vfio_device_info info;
2120 
2121 	minsz = offsetofend(struct vfio_device_info, num_irqs);
2122 
2123 	if (copy_from_user(&info, (void __user *)arg, minsz))
2124 		return -EFAULT;
2125 
2126 	if (info.argsz < minsz)
2127 		return -EINVAL;
2128 
2129 	info.flags = VFIO_DEVICE_FLAGS_AP | VFIO_DEVICE_FLAGS_RESET;
2130 	info.num_regions = 0;
2131 	info.num_irqs = VFIO_AP_NUM_IRQS;
2132 
2133 	return copy_to_user((void __user *)arg, &info, minsz) ? -EFAULT : 0;
2134 }
2135 
2136 static ssize_t vfio_ap_get_irq_info(unsigned long arg)
2137 {
2138 	unsigned long minsz;
2139 	struct vfio_irq_info info;
2140 
2141 	minsz = offsetofend(struct vfio_irq_info, count);
2142 
2143 	if (copy_from_user(&info, (void __user *)arg, minsz))
2144 		return -EFAULT;
2145 
2146 	if (info.argsz < minsz || info.index >= VFIO_AP_NUM_IRQS)
2147 		return -EINVAL;
2148 
2149 	switch (info.index) {
2150 	case VFIO_AP_REQ_IRQ_INDEX:
2151 		info.count = 1;
2152 		info.flags = VFIO_IRQ_INFO_EVENTFD;
2153 		break;
2154 	case VFIO_AP_CFG_CHG_IRQ_INDEX:
2155 		info.count = 1;
2156 		info.flags = VFIO_IRQ_INFO_EVENTFD;
2157 		break;
2158 	default:
2159 		return -EINVAL;
2160 	}
2161 
2162 	return copy_to_user((void __user *)arg, &info, minsz) ? -EFAULT : 0;
2163 }
2164 
2165 static int vfio_ap_irq_set_init(struct vfio_irq_set *irq_set, unsigned long arg)
2166 {
2167 	int ret;
2168 	size_t data_size;
2169 	unsigned long minsz;
2170 
2171 	minsz = offsetofend(struct vfio_irq_set, count);
2172 
2173 	if (copy_from_user(irq_set, (void __user *)arg, minsz))
2174 		return -EFAULT;
2175 
2176 	ret = vfio_set_irqs_validate_and_prepare(irq_set, 1, VFIO_AP_NUM_IRQS,
2177 						 &data_size);
2178 	if (ret)
2179 		return ret;
2180 
2181 	if (!(irq_set->flags & VFIO_IRQ_SET_ACTION_TRIGGER))
2182 		return -EINVAL;
2183 
2184 	return 0;
2185 }
2186 
2187 static int vfio_ap_set_request_irq(struct ap_matrix_mdev *matrix_mdev,
2188 				   unsigned long arg)
2189 {
2190 	s32 fd;
2191 	void __user *data;
2192 	unsigned long minsz;
2193 	struct eventfd_ctx *req_trigger;
2194 
2195 	minsz = offsetofend(struct vfio_irq_set, count);
2196 	data = (void __user *)(arg + minsz);
2197 
2198 	if (get_user(fd, (s32 __user *)data))
2199 		return -EFAULT;
2200 
2201 	if (fd == -1) {
2202 		if (matrix_mdev->req_trigger)
2203 			eventfd_ctx_put(matrix_mdev->req_trigger);
2204 		matrix_mdev->req_trigger = NULL;
2205 	} else if (fd >= 0) {
2206 		req_trigger = eventfd_ctx_fdget(fd);
2207 		if (IS_ERR(req_trigger))
2208 			return PTR_ERR(req_trigger);
2209 
2210 		if (matrix_mdev->req_trigger)
2211 			eventfd_ctx_put(matrix_mdev->req_trigger);
2212 
2213 		matrix_mdev->req_trigger = req_trigger;
2214 	} else {
2215 		return -EINVAL;
2216 	}
2217 
2218 	return 0;
2219 }
2220 
2221 static int vfio_ap_set_cfg_change_irq(struct ap_matrix_mdev *matrix_mdev, unsigned long arg)
2222 {
2223 	s32 fd;
2224 	void __user *data;
2225 	unsigned long minsz;
2226 	struct eventfd_ctx *cfg_chg_trigger;
2227 
2228 	minsz = offsetofend(struct vfio_irq_set, count);
2229 	data = (void __user *)(arg + minsz);
2230 
2231 	if (get_user(fd, (s32 __user *)data))
2232 		return -EFAULT;
2233 
2234 	if (fd == -1) {
2235 		if (matrix_mdev->cfg_chg_trigger)
2236 			eventfd_ctx_put(matrix_mdev->cfg_chg_trigger);
2237 		matrix_mdev->cfg_chg_trigger = NULL;
2238 	} else if (fd >= 0) {
2239 		cfg_chg_trigger = eventfd_ctx_fdget(fd);
2240 		if (IS_ERR(cfg_chg_trigger))
2241 			return PTR_ERR(cfg_chg_trigger);
2242 
2243 		if (matrix_mdev->cfg_chg_trigger)
2244 			eventfd_ctx_put(matrix_mdev->cfg_chg_trigger);
2245 
2246 		matrix_mdev->cfg_chg_trigger = cfg_chg_trigger;
2247 	} else {
2248 		return -EINVAL;
2249 	}
2250 
2251 	return 0;
2252 }
2253 
2254 static int vfio_ap_set_irqs(struct ap_matrix_mdev *matrix_mdev,
2255 			    unsigned long arg)
2256 {
2257 	int ret;
2258 	struct vfio_irq_set irq_set;
2259 
2260 	ret = vfio_ap_irq_set_init(&irq_set, arg);
2261 	if (ret)
2262 		return ret;
2263 
2264 	switch (irq_set.flags & VFIO_IRQ_SET_DATA_TYPE_MASK) {
2265 	case VFIO_IRQ_SET_DATA_EVENTFD:
2266 		switch (irq_set.index) {
2267 		case VFIO_AP_REQ_IRQ_INDEX:
2268 			return vfio_ap_set_request_irq(matrix_mdev, arg);
2269 		case VFIO_AP_CFG_CHG_IRQ_INDEX:
2270 			return vfio_ap_set_cfg_change_irq(matrix_mdev, arg);
2271 		default:
2272 			return -EINVAL;
2273 		}
2274 	default:
2275 		return -EINVAL;
2276 	}
2277 }
2278 
2279 static ssize_t vfio_ap_mdev_ioctl(struct vfio_device *vdev,
2280 				    unsigned int cmd, unsigned long arg)
2281 {
2282 	struct ap_matrix_mdev *matrix_mdev =
2283 		container_of(vdev, struct ap_matrix_mdev, vdev);
2284 	int ret;
2285 
2286 	mutex_lock(&matrix_dev->mdevs_lock);
2287 	switch (cmd) {
2288 	case VFIO_DEVICE_GET_INFO:
2289 		ret = vfio_ap_mdev_get_device_info(arg);
2290 		break;
2291 	case VFIO_DEVICE_RESET:
2292 		ret = vfio_ap_mdev_reset_queues(matrix_mdev);
2293 		break;
2294 	case VFIO_DEVICE_GET_IRQ_INFO:
2295 		ret = vfio_ap_get_irq_info(arg);
2296 		break;
2297 	case VFIO_DEVICE_SET_IRQS:
2298 		ret = vfio_ap_set_irqs(matrix_mdev, arg);
2299 		break;
2300 	default:
2301 		ret = -EOPNOTSUPP;
2302 		break;
2303 	}
2304 	mutex_unlock(&matrix_dev->mdevs_lock);
2305 
2306 	return ret;
2307 }
2308 
2309 static struct ap_matrix_mdev *vfio_ap_mdev_for_queue(struct vfio_ap_queue *q)
2310 {
2311 	struct ap_matrix_mdev *matrix_mdev;
2312 	unsigned long apid = AP_QID_CARD(q->apqn);
2313 	unsigned long apqi = AP_QID_QUEUE(q->apqn);
2314 
2315 	lockdep_assert_held(&matrix_dev->guests_lock);
2316 
2317 	list_for_each_entry(matrix_mdev, &matrix_dev->mdev_list, node) {
2318 		if (test_bit_inv(apid, matrix_mdev->matrix.apm) &&
2319 		    test_bit_inv(apqi, matrix_mdev->matrix.aqm))
2320 			return matrix_mdev;
2321 	}
2322 
2323 	return NULL;
2324 }
2325 
2326 static ssize_t status_show(struct device *dev,
2327 			   struct device_attribute *attr,
2328 			   char *buf)
2329 {
2330 	ssize_t nchars = 0;
2331 	struct vfio_ap_queue *q;
2332 	unsigned long apid, apqi;
2333 	struct ap_matrix_mdev *matrix_mdev;
2334 	struct ap_device *apdev = to_ap_dev(dev);
2335 
2336 	mutex_lock(&matrix_dev->guests_lock);
2337 	mutex_lock(&matrix_dev->mdevs_lock);
2338 	q = dev_get_drvdata(&apdev->device);
2339 
2340 	/*
2341 	 * Make sure the drvdata has been set before proceeding. There is a
2342 	 * possibility that the drvdata was not set if the vfio_ap_queue object
2343 	 * could not be allocated when the queue device was probed. In that case,
2344 	 * the locks used in vfio_ap_mdev_probe_queue() are released prior to
2345 	 * removing the sysfs status attribute to avoid a lockdep
2346 	 * splat. That opens a very small window where the status attribute is
2347 	 * still available without the vfio_ap_queue object having been
2348 	 * stored in the device drvdata. In that case, indicate the queue is not
2349 	 * assigned.
2350 	 */
2351 	if (!q) {
2352 		nchars = sysfs_emit(buf, "%s\n", AP_QUEUE_UNASSIGNED);
2353 		goto done;
2354 	}
2355 
2356 	matrix_mdev = vfio_ap_mdev_for_queue(q);
2357 
2358 	/* If the queue is assigned to the matrix mediated device, then
2359 	 * determine whether it is passed through to a guest; otherwise,
2360 	 * indicate that it is unassigned.
2361 	 */
2362 	if (matrix_mdev) {
2363 		apid = AP_QID_CARD(q->apqn);
2364 		apqi = AP_QID_QUEUE(q->apqn);
2365 		/*
2366 		 * If the queue is passed through to the guest, then indicate
2367 		 * that it is in use; otherwise, indicate that it is
2368 		 * merely assigned to a matrix mediated device.
2369 		 */
2370 		if (matrix_mdev->kvm &&
2371 		    test_bit_inv(apid, matrix_mdev->shadow_apcb.apm) &&
2372 		    test_bit_inv(apqi, matrix_mdev->shadow_apcb.aqm))
2373 			nchars = sysfs_emit(buf, "%s\n", AP_QUEUE_IN_USE);
2374 		else
2375 			nchars = sysfs_emit(buf, "%s\n", AP_QUEUE_ASSIGNED);
2376 	} else {
2377 		nchars = sysfs_emit(buf, "%s\n", AP_QUEUE_UNASSIGNED);
2378 	}
2379 
2380 done:
2381 	mutex_unlock(&matrix_dev->mdevs_lock);
2382 	mutex_unlock(&matrix_dev->guests_lock);
2383 
2384 	return nchars;
2385 }
2386 
2387 static DEVICE_ATTR_RO(status);
2388 
2389 static struct attribute *vfio_queue_attrs[] = {
2390 	&dev_attr_status.attr,
2391 	NULL,
2392 };
2393 
2394 static const struct attribute_group vfio_queue_attr_group = {
2395 	.attrs = vfio_queue_attrs,
2396 };
2397 
2398 static const struct vfio_device_ops vfio_ap_matrix_dev_ops = {
2399 	.init = vfio_ap_mdev_init_dev,
2400 	.open_device = vfio_ap_mdev_open_device,
2401 	.close_device = vfio_ap_mdev_close_device,
2402 	.ioctl = vfio_ap_mdev_ioctl,
2403 	.dma_unmap = vfio_ap_mdev_dma_unmap,
2404 	.bind_iommufd = vfio_iommufd_emulated_bind,
2405 	.unbind_iommufd = vfio_iommufd_emulated_unbind,
2406 	.attach_ioas = vfio_iommufd_emulated_attach_ioas,
2407 	.detach_ioas = vfio_iommufd_emulated_detach_ioas,
2408 	.request = vfio_ap_mdev_request
2409 };
2410 
2411 static struct mdev_driver vfio_ap_matrix_driver = {
2412 	.device_api = VFIO_DEVICE_API_AP_STRING,
2413 	.max_instances = MAX_ZDEV_ENTRIES_EXT,
2414 	.driver = {
2415 		.name = "vfio_ap_mdev",
2416 		.owner = THIS_MODULE,
2417 		.mod_name = KBUILD_MODNAME,
2418 		.dev_groups = vfio_ap_mdev_attr_groups,
2419 	},
2420 	.probe = vfio_ap_mdev_probe,
2421 	.remove = vfio_ap_mdev_remove,
2422 };
2423 
2424 int vfio_ap_mdev_register(void)
2425 {
2426 	int ret;
2427 
2428 	ret = mdev_register_driver(&vfio_ap_matrix_driver);
2429 	if (ret)
2430 		return ret;
2431 
2432 	matrix_dev->mdev_type.sysfs_name = VFIO_AP_MDEV_TYPE_HWVIRT;
2433 	matrix_dev->mdev_type.pretty_name = VFIO_AP_MDEV_NAME_HWVIRT;
2434 	matrix_dev->mdev_types = &matrix_dev->mdev_type;
2435 	ret = mdev_register_parent(&matrix_dev->parent, &matrix_dev->device,
2436 				   &vfio_ap_matrix_driver,
2437 				   &matrix_dev->mdev_types, 1);
2438 	if (ret)
2439 		goto err_driver;
2440 	return 0;
2441 
2442 err_driver:
2443 	mdev_unregister_driver(&vfio_ap_matrix_driver);
2444 	return ret;
2445 }
2446 
2447 void vfio_ap_mdev_unregister(void)
2448 {
2449 	mdev_unregister_parent(&matrix_dev->parent);
2450 	mdev_unregister_driver(&vfio_ap_matrix_driver);
2451 }
2452 
2453 int vfio_ap_mdev_probe_queue(struct ap_device *apdev)
2454 {
2455 	int ret, apqn;
2456 	struct vfio_ap_queue *q;
2457 	DECLARE_BITMAP(apm_filtered, AP_DEVICES);
2458 	struct ap_matrix_mdev *matrix_mdev;
2459 
2460 	apqn = to_ap_queue(&apdev->device)->qid;
2461 	matrix_mdev = get_update_locks_by_apqn(apqn);
2462 
2463 	ret = sysfs_create_group(&apdev->device.kobj, &vfio_queue_attr_group);
2464 	if (ret)
2465 		goto err_release_locks;
2466 
2467 	q = kzalloc_obj(*q);
2468 	if (!q) {
2469 		ret = -ENOMEM;
2470 		goto err_remove_group;
2471 	}
2472 
2473 	q->apqn = apqn;
2474 	q->saved_isc = VFIO_AP_ISC_INVALID;
2475 	memset(&q->reset_status, 0, sizeof(q->reset_status));
2476 	INIT_WORK(&q->reset_work, apq_reset_check);
2477 
2478 	if (matrix_mdev) {
2479 		vfio_ap_mdev_link_queue(matrix_mdev, q);
2480 
2481 		/*
2482 		 * If we're in the process of handling the adding of adapters or
2483 		 * domains to the host's AP configuration, then let the
2484 		 * vfio_ap device driver's on_scan_complete callback filter the
2485 		 * matrix and update the guest's AP configuration after all of
2486 		 * the new queue devices are probed.
2487 		 */
2488 		if (!bitmap_empty(matrix_mdev->apm_add, AP_DEVICES) ||
2489 		    !bitmap_empty(matrix_mdev->aqm_add, AP_DOMAINS))
2490 			goto done;
2491 
2492 		if (vfio_ap_mdev_filter_matrix(matrix_mdev, apm_filtered)) {
2493 			vfio_ap_mdev_update_guest_apcb(matrix_mdev);
2494 			reset_queues_for_apids(matrix_mdev, apm_filtered);
2495 		}
2496 	}
2497 
2498 done:
2499 	dev_set_drvdata(&apdev->device, q);
2500 	release_update_locks_for_mdev(matrix_mdev);
2501 
2502 	return ret;
2503 
2504 err_remove_group:
2505 	release_update_locks_for_mdev(matrix_mdev);
2506 	sysfs_remove_group(&apdev->device.kobj, &vfio_queue_attr_group);
2507 	return ret;
2508 
2509 err_release_locks:
2510 	release_update_locks_for_mdev(matrix_mdev);
2511 	return ret;
2512 }
2513 
2514 void vfio_ap_mdev_remove_queue(struct ap_device *apdev)
2515 {
2516 	unsigned long apid, apqi;
2517 	struct vfio_ap_queue *q;
2518 	struct ap_matrix_mdev *matrix_mdev;
2519 
2520 	sysfs_remove_group(&apdev->device.kobj, &vfio_queue_attr_group);
2521 	q = dev_get_drvdata(&apdev->device);
2522 	get_update_locks_for_queue(q);
2523 	matrix_mdev = q->matrix_mdev;
2524 	apid = AP_QID_CARD(q->apqn);
2525 	apqi = AP_QID_QUEUE(q->apqn);
2526 
2527 	if (matrix_mdev) {
2528 		/* If the queue is assigned to the guest's AP configuration */
2529 		if (test_bit_inv(apid, matrix_mdev->shadow_apcb.apm) &&
2530 		    test_bit_inv(apqi, matrix_mdev->shadow_apcb.aqm)) {
2531 			/*
2532 			 * Since the queues are defined via a matrix of adapters
2533 			 * and domains, it is not possible to hot unplug a
2534 			 * single queue; so, let's unplug the adapter.
2535 			 */
2536 			clear_bit_inv(apid, matrix_mdev->shadow_apcb.apm);
2537 			vfio_ap_mdev_update_guest_apcb(matrix_mdev);
2538 			reset_queues_for_apid(matrix_mdev, apid);
2539 			goto done;
2540 		}
2541 	}
2542 
2543 	/*
2544 	 * If the queue is not in the host's AP configuration, then resetting
2545 	 * it will fail with response code 01, (APQN not valid); so, let's make
2546 	 * sure it is in the host's config. If it is not, free the KVM GISC
2547 	 * resources.
2548 	 */
2549 	if (test_bit_inv(apid, (unsigned long *)matrix_dev->info.apm) &&
2550 	    test_bit_inv(apqi, (unsigned long *)matrix_dev->info.aqm)) {
2551 		vfio_ap_mdev_reset_queue(q);
2552 		flush_work(&q->reset_work);
2553 	} else {
2554 		vfio_ap_free_aqic_resources(q);
2555 	}
2556 
2557 done:
2558 	if (matrix_mdev)
2559 		vfio_ap_unlink_queue_fr_mdev(q);
2560 
2561 	dev_set_drvdata(&apdev->device, NULL);
2562 	kfree(q);
2563 	release_update_locks_for_mdev(matrix_mdev);
2564 }
2565 
2566 /**
2567  * vfio_ap_mdev_resource_in_use: check whether any of a set of APQNs is
2568  *				 assigned to a mediated device under the control
2569  *				 of the vfio_ap device driver.
2570  *
2571  * @apm: a bitmap specifying a set of APIDs comprising the APQNs to check.
2572  * @aqm: a bitmap specifying a set of APQIs comprising the APQNs to check.
2573  *
2574  * Return:
2575  *	* -EADDRINUSE if one or more of the APQNs specified via @apm/@aqm are
2576  *	  assigned to a mediated device under the control of the vfio_ap
2577  *	  device driver.
2578  *	* Otherwise, return 0.
2579  */
2580 int vfio_ap_mdev_resource_in_use(unsigned long *apm, unsigned long *aqm)
2581 {
2582 	int ret;
2583 
2584 	mutex_lock(&matrix_dev->guests_lock);
2585 	mutex_lock(&matrix_dev->mdevs_lock);
2586 	ret = vfio_ap_mdev_verify_no_sharing(NULL, apm, aqm);
2587 	mutex_unlock(&matrix_dev->mdevs_lock);
2588 	mutex_unlock(&matrix_dev->guests_lock);
2589 
2590 	return ret;
2591 }
2592 
2593 /**
2594  * vfio_ap_mdev_hot_unplug_cfg - hot unplug the adapters, domains and control
2595  *				 domains that have been removed from the host's
2596  *				 AP configuration from a guest.
2597  *
2598  * @matrix_mdev: an ap_matrix_mdev object attached to a KVM guest.
2599  * @aprem: the adapters that have been removed from the host's AP configuration
2600  * @aqrem: the domains that have been removed from the host's AP configuration
2601  * @cdrem: the control domains that have been removed from the host's AP
2602  *	   configuration.
2603  */
2604 static void vfio_ap_mdev_hot_unplug_cfg(struct ap_matrix_mdev *matrix_mdev,
2605 					unsigned long *aprem,
2606 					unsigned long *aqrem,
2607 					unsigned long *cdrem)
2608 {
2609 	bool do_hotplug = false;
2610 
2611 	if (bitmap_intersects(matrix_mdev->shadow_apcb.apm, aprem, AP_DEVICES)) {
2612 		bitmap_andnot(matrix_mdev->shadow_apcb.apm,
2613 			      matrix_mdev->shadow_apcb.apm,
2614 			      aprem, AP_DEVICES);
2615 		do_hotplug = true;
2616 	}
2617 
2618 	if (bitmap_intersects(matrix_mdev->shadow_apcb.aqm, aqrem, AP_DOMAINS)) {
2619 		bitmap_andnot(matrix_mdev->shadow_apcb.aqm,
2620 			      matrix_mdev->shadow_apcb.aqm,
2621 			      aqrem, AP_DOMAINS);
2622 		do_hotplug = true;
2623 	}
2624 
2625 	if (bitmap_intersects(matrix_mdev->shadow_apcb.adm, cdrem, AP_DOMAINS)) {
2626 		bitmap_andnot(matrix_mdev->shadow_apcb.adm,
2627 			      matrix_mdev->shadow_apcb.adm,
2628 			      cdrem, AP_DOMAINS);
2629 		do_hotplug = true;
2630 	}
2631 
2632 	if (do_hotplug)
2633 		vfio_ap_mdev_update_guest_apcb(matrix_mdev);
2634 }
2635 
2636 /**
2637  * vfio_ap_mdev_cfg_remove - determines which guests are using the adapters,
2638  *			     domains and control domains that have been removed
2639  *			     from the host AP configuration and unplugs them
2640  *			     from those guests.
2641  *
2642  * @ap_remove:	bitmap specifying which adapters have been removed from the host
2643  *		config.
2644  * @aq_remove:	bitmap specifying which domains have been removed from the host
2645  *		config.
2646  * @cd_remove:	bitmap specifying which control domains have been removed from
2647  *		the host config.
2648  */
2649 static void vfio_ap_mdev_cfg_remove(unsigned long *ap_remove,
2650 				    unsigned long *aq_remove,
2651 				    unsigned long *cd_remove)
2652 {
2653 	struct ap_matrix_mdev *matrix_mdev;
2654 	DECLARE_BITMAP(aprem, AP_DEVICES);
2655 	DECLARE_BITMAP(aqrem, AP_DOMAINS);
2656 	DECLARE_BITMAP(cdrem, AP_DOMAINS);
2657 	int do_remove;
2658 
2659 	/*
2660 	 * It is safe to traverse this list here because the
2661 	 * required guard - matrix_dev->guests_lock - is taken in the
2662 	 * vfio_ap_on_cfg_changed function prior to this function getting
2663 	 * called.
2664 	 */
2665 	list_for_each_entry(matrix_mdev, &matrix_dev->mdev_list, node) {
2666 		/*
2667 		 * The mdevs_lock must be held to access fields within matrix_mdev,
2668 		 * and kvm->lock must be taken before mdevs_lock to satisfy the lock
2669 		 * ordering requirement and prevent a lockdep splat.
2670 		 */
2671 		if (matrix_mdev->kvm)
2672 			mutex_lock(&matrix_mdev->kvm->lock);
2673 		mutex_lock(&matrix_dev->mdevs_lock);
2674 
2675 		do_remove = bitmap_and(aprem, ap_remove,
2676 				       matrix_mdev->matrix.apm,
2677 				       AP_DEVICES);
2678 		do_remove |= bitmap_and(aqrem, aq_remove,
2679 					  matrix_mdev->matrix.aqm,
2680 					  AP_DOMAINS);
2681 		do_remove |= bitmap_and(cdrem, cd_remove,
2682 					matrix_mdev->matrix.adm,
2683 					AP_DOMAINS);
2684 
2685 		if (do_remove)
2686 			vfio_ap_mdev_hot_unplug_cfg(matrix_mdev, aprem, aqrem,
2687 						    cdrem);
2688 
2689 		mutex_unlock(&matrix_dev->mdevs_lock);
2690 		if (matrix_mdev->kvm)
2691 			mutex_unlock(&matrix_mdev->kvm->lock);
2692 	}
2693 }
2694 
2695 /**
2696  * vfio_ap_mdev_on_cfg_remove - responds to the removal of adapters, domains and
2697  *				control domains from the host AP configuration
2698  *				by unplugging them from the guests that are
2699  *				using them.
2700  * @cur_config_info: the current host AP configuration information
2701  * @prev_config_info: the previous host AP configuration information
2702  */
2703 static void vfio_ap_mdev_on_cfg_remove(struct ap_config_info *cur_config_info,
2704 				       struct ap_config_info *prev_config_info)
2705 {
2706 	int do_remove;
2707 	DECLARE_BITMAP(aprem, AP_DEVICES);
2708 	DECLARE_BITMAP(aqrem, AP_DOMAINS);
2709 	DECLARE_BITMAP(cdrem, AP_DOMAINS);
2710 
2711 	do_remove = bitmap_andnot(aprem,
2712 				  (unsigned long *)prev_config_info->apm,
2713 				  (unsigned long *)cur_config_info->apm,
2714 				  AP_DEVICES);
2715 	do_remove |= bitmap_andnot(aqrem,
2716 				   (unsigned long *)prev_config_info->aqm,
2717 				   (unsigned long *)cur_config_info->aqm,
2718 				   AP_DEVICES);
2719 	do_remove |= bitmap_andnot(cdrem,
2720 				   (unsigned long *)prev_config_info->adm,
2721 				   (unsigned long *)cur_config_info->adm,
2722 				   AP_DEVICES);
2723 
2724 	if (do_remove)
2725 		vfio_ap_mdev_cfg_remove(aprem, aqrem, cdrem);
2726 }
2727 
2728 /**
2729  * vfio_ap_filter_apid_by_qtype: filter APIDs from an AP mask for adapters that
2730  *				 are older than AP type 10 (CEX4).
2731  * @apm: a bitmap of the APIDs to examine
2732  * @aqm: a bitmap of the APQIs of the queues to query for the AP type.
2733  */
2734 static void vfio_ap_filter_apid_by_qtype(unsigned long *apm, unsigned long *aqm)
2735 {
2736 	bool apid_cleared;
2737 	struct ap_queue_status status;
2738 	unsigned long apid, apqi;
2739 	struct ap_tapq_hwinfo info;
2740 
2741 	for_each_set_bit_inv(apid, apm, AP_DEVICES) {
2742 		apid_cleared = false;
2743 
2744 		for_each_set_bit_inv(apqi, aqm, AP_DOMAINS) {
2745 			status = ap_test_queue(AP_MKQID(apid, apqi), 1, &info);
2746 			switch (status.response_code) {
2747 			/*
2748 			 * According to the architecture in each case
2749 			 * below, the queue's info should be filled.
2750 			 */
2751 			case AP_RESPONSE_NORMAL:
2752 			case AP_RESPONSE_RESET_IN_PROGRESS:
2753 			case AP_RESPONSE_DECONFIGURED:
2754 			case AP_RESPONSE_CHECKSTOPPED:
2755 			case AP_RESPONSE_BUSY:
2756 				/*
2757 				 * The vfio_ap device driver only
2758 				 * supports CEX4 and newer adapters, so
2759 				 * remove the APID if the adapter is
2760 				 * older than a CEX4.
2761 				 */
2762 				if (info.at < AP_DEVICE_TYPE_CEX4) {
2763 					clear_bit_inv(apid, apm);
2764 					apid_cleared = true;
2765 				}
2766 
2767 				break;
2768 
2769 			default:
2770 				/*
2771 				 * If we don't know the adapter type,
2772 				 * clear its APID since it can't be
2773 				 * determined whether the vfio_ap
2774 				 * device driver supports it.
2775 				 */
2776 				clear_bit_inv(apid, apm);
2777 				apid_cleared = true;
2778 				break;
2779 			}
2780 
2781 			/*
2782 			 * If we've already cleared the APID from the apm, there
2783 			 * is no need to continue examining the remainin AP
2784 			 * queues to determine the type of the adapter.
2785 			 */
2786 			if (apid_cleared)
2787 				continue;
2788 		}
2789 	}
2790 }
2791 
2792 /**
2793  * vfio_ap_mdev_cfg_add - store bitmaps specifying the adapters, domains and
2794  *			  control domains that have been added to the host's
2795  *			  AP configuration for each matrix mdev to which they
2796  *			  are assigned.
2797  *
2798  * @apm_add: a bitmap specifying the adapters that have been added to the AP
2799  *	     configuration.
2800  * @aqm_add: a bitmap specifying the domains that have been added to the AP
2801  *	     configuration.
2802  * @adm_add: a bitmap specifying the control domains that have been added to the
2803  *	     AP configuration.
2804  */
2805 static void vfio_ap_mdev_cfg_add(unsigned long *apm_add, unsigned long *aqm_add,
2806 				 unsigned long *adm_add)
2807 {
2808 	struct ap_matrix_mdev *matrix_mdev;
2809 
2810 	if (list_empty(&matrix_dev->mdev_list))
2811 		return;
2812 
2813 	vfio_ap_filter_apid_by_qtype(apm_add, aqm_add);
2814 
2815 	/*
2816 	 * It is safe to traverse this list here because the
2817 	 * required guard - matrix_dev->guests_lock - is taken in the
2818 	 * vfio_ap_on_cfg_changed function prior to this function getting
2819 	 * called.
2820 	 */
2821 	list_for_each_entry(matrix_mdev, &matrix_dev->mdev_list, node) {
2822 		/*
2823 		 * The mdevs_lock must be held in order to access fields
2824 		 * within matrix_mdev
2825 		 */
2826 		mutex_lock(&matrix_dev->mdevs_lock);
2827 
2828 		bitmap_and(matrix_mdev->apm_add,
2829 			   matrix_mdev->matrix.apm, apm_add, AP_DEVICES);
2830 		bitmap_and(matrix_mdev->aqm_add,
2831 			   matrix_mdev->matrix.aqm, aqm_add, AP_DOMAINS);
2832 		bitmap_and(matrix_mdev->adm_add,
2833 			   matrix_mdev->matrix.adm, adm_add, AP_DEVICES);
2834 
2835 		mutex_unlock(&matrix_dev->mdevs_lock);
2836 	}
2837 }
2838 
2839 /**
2840  * vfio_ap_mdev_on_cfg_add - responds to the addition of adapters, domains and
2841  *			     control domains to the host AP configuration
2842  *			     by updating the bitmaps that specify what adapters,
2843  *			     domains and control domains have been added so they
2844  *			     can be hot plugged into the guest when the AP bus
2845  *			     scan completes (see vfio_ap_on_scan_complete
2846  *			     function).
2847  * @cur_config_info: the current AP configuration information
2848  * @prev_config_info: the previous AP configuration information
2849  */
2850 static void vfio_ap_mdev_on_cfg_add(struct ap_config_info *cur_config_info,
2851 				    struct ap_config_info *prev_config_info)
2852 {
2853 	bool do_add;
2854 	DECLARE_BITMAP(apm_add, AP_DEVICES);
2855 	DECLARE_BITMAP(aqm_add, AP_DOMAINS);
2856 	DECLARE_BITMAP(adm_add, AP_DOMAINS);
2857 
2858 	do_add = bitmap_andnot(apm_add,
2859 			       (unsigned long *)cur_config_info->apm,
2860 			       (unsigned long *)prev_config_info->apm,
2861 			       AP_DEVICES);
2862 	do_add |= bitmap_andnot(aqm_add,
2863 				(unsigned long *)cur_config_info->aqm,
2864 				(unsigned long *)prev_config_info->aqm,
2865 				AP_DOMAINS);
2866 	do_add |= bitmap_andnot(adm_add,
2867 				(unsigned long *)cur_config_info->adm,
2868 				(unsigned long *)prev_config_info->adm,
2869 				AP_DOMAINS);
2870 
2871 	if (do_add)
2872 		vfio_ap_mdev_cfg_add(apm_add, aqm_add, adm_add);
2873 }
2874 
2875 /**
2876  * vfio_ap_on_cfg_changed - handles notification of changes to the host AP
2877  *			    configuration.
2878  *
2879  * @cur_cfg_info: the current host AP configuration
2880  * @prev_cfg_info: the previous host AP configuration
2881  */
2882 void vfio_ap_on_cfg_changed(struct ap_config_info *cur_cfg_info,
2883 			    struct ap_config_info *prev_cfg_info)
2884 {
2885 	if (!cur_cfg_info || !prev_cfg_info)
2886 		return;
2887 
2888 	/*
2889 	 * Take the guests_lock mutex here to guard access to the
2890 	 * matrix_dev->mdev_list in the two functions called below.
2891 	 */
2892 	mutex_lock(&matrix_dev->guests_lock);
2893 
2894 	vfio_ap_mdev_on_cfg_remove(cur_cfg_info, prev_cfg_info);
2895 	vfio_ap_mdev_on_cfg_add(cur_cfg_info, prev_cfg_info);
2896 	memcpy(&matrix_dev->info, cur_cfg_info, sizeof(*cur_cfg_info));
2897 
2898 	mutex_unlock(&matrix_dev->guests_lock);
2899 }
2900 
2901 static void vfio_ap_mdev_hot_plug_cfg(struct ap_matrix_mdev *matrix_mdev)
2902 {
2903 	DECLARE_BITMAP(apm_filtered, AP_DEVICES);
2904 	bool filter_domains, filter_adapters, filter_cdoms, do_hotplug = false;
2905 
2906 	/*
2907 	 * Zero out the apm_filtered bitmap in case there are no adapters or
2908 	 * domains to be added, but only control domains. In that case,
2909 	 * vfio_ap_mdev_filter_matrix() - which initializes apm_filtered - will
2910 	 * not get called and the reset_queues_for_apids will crash because it
2911 	 * will access an uninitialized bitmap.
2912 	 */
2913 	bitmap_zero(apm_filtered, AP_DEVICES);
2914 
2915 	filter_adapters = bitmap_intersects(matrix_mdev->matrix.apm,
2916 					    matrix_mdev->apm_add, AP_DEVICES);
2917 	filter_domains = bitmap_intersects(matrix_mdev->matrix.aqm,
2918 					   matrix_mdev->aqm_add, AP_DOMAINS);
2919 	filter_cdoms = bitmap_intersects(matrix_mdev->matrix.adm,
2920 					 matrix_mdev->adm_add, AP_DOMAINS);
2921 
2922 	if (filter_adapters || filter_domains)
2923 		do_hotplug = vfio_ap_mdev_filter_matrix(matrix_mdev, apm_filtered);
2924 
2925 	if (filter_cdoms)
2926 		do_hotplug |= vfio_ap_mdev_filter_cdoms(matrix_mdev);
2927 
2928 	if (do_hotplug)
2929 		vfio_ap_mdev_update_guest_apcb(matrix_mdev);
2930 
2931 	reset_queues_for_apids(matrix_mdev, apm_filtered);
2932 }
2933 
2934 void vfio_ap_on_scan_complete(struct ap_config_info *new_config_info,
2935 			      struct ap_config_info *old_config_info)
2936 {
2937 	struct ap_matrix_mdev *matrix_mdev;
2938 
2939 	mutex_lock(&matrix_dev->guests_lock);
2940 
2941 	list_for_each_entry(matrix_mdev, &matrix_dev->mdev_list, node) {
2942 		/*
2943 		 * The mdevs_lock must be held to access fields within matrix_mdev,
2944 		 * and kvm->lock must be taken before mdevs_lock to satisfy the lock
2945 		 * ordering requirement and prevent a lockdep splat.
2946 		 */
2947 		if (matrix_mdev->kvm)
2948 			mutex_lock(&matrix_mdev->kvm->lock);
2949 		mutex_lock(&matrix_dev->mdevs_lock);
2950 
2951 		if (bitmap_empty(matrix_mdev->apm_add, AP_DEVICES) &&
2952 		    bitmap_empty(matrix_mdev->aqm_add, AP_DOMAINS) &&
2953 		    bitmap_empty(matrix_mdev->adm_add, AP_DOMAINS))
2954 			goto do_unlock;
2955 
2956 		vfio_ap_mdev_hot_plug_cfg(matrix_mdev);
2957 		bitmap_clear(matrix_mdev->apm_add, 0, AP_DEVICES);
2958 		bitmap_clear(matrix_mdev->aqm_add, 0, AP_DOMAINS);
2959 		bitmap_clear(matrix_mdev->adm_add, 0, AP_DOMAINS);
2960 
2961 do_unlock:
2962 		mutex_unlock(&matrix_dev->mdevs_lock);
2963 		if (matrix_mdev->kvm)
2964 			mutex_unlock(&matrix_mdev->kvm->lock);
2965 	}
2966 
2967 	mutex_unlock(&matrix_dev->guests_lock);
2968 }
2969