xref: /linux/drivers/s390/crypto/vfio_ap_ops.c (revision 7db28abbea0f7dc1ec4fdfdc149db5fbd9e4c994)
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 	    !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 @kvm
1826  *
1827  * @matrix_mdev: a mediated matrix device
1828  * @kvm: reference to KVM instance
1829  *
1830  * Return: 0 if no other mediated matrix device has a reference to @kvm;
1831  * otherwise, returns an -EPERM.
1832  */
1833 static int vfio_ap_mdev_set_kvm(struct ap_matrix_mdev *matrix_mdev,
1834 				struct kvm *kvm)
1835 {
1836 	if (kvm->arch.crypto.crycbd) {
1837 		get_update_locks_for_kvm(kvm);
1838 		if (kvm->arch.crypto.pqap_hook) {
1839 			release_update_locks_for_kvm(kvm);
1840 			return -EPERM;
1841 		}
1842 		kvm->arch.crypto.pqap_hook = &matrix_mdev->pqap_hook;
1843 
1844 		kvm_get_kvm(kvm);
1845 		matrix_mdev->kvm = kvm;
1846 		vfio_ap_mdev_update_guest_apcb(matrix_mdev);
1847 		release_update_locks_for_kvm(kvm);
1848 	}
1849 
1850 	return 0;
1851 }
1852 
1853 static void unmap_iova(struct ap_matrix_mdev *matrix_mdev, u64 iova, u64 length)
1854 {
1855 	struct ap_queue_table *qtable = &matrix_mdev->qtable;
1856 	struct vfio_ap_queue *q;
1857 	int loop_cursor;
1858 
1859 	hash_for_each(qtable->queues, loop_cursor, q, mdev_qnode) {
1860 		if (q->saved_iova >= iova && q->saved_iova < iova + length)
1861 			vfio_ap_irq_disable(q);
1862 	}
1863 }
1864 
1865 static void vfio_ap_mdev_dma_unmap(struct vfio_device *vdev, u64 iova,
1866 				   u64 length)
1867 {
1868 	struct ap_matrix_mdev *matrix_mdev =
1869 		container_of(vdev, struct ap_matrix_mdev, vdev);
1870 
1871 	mutex_lock(&matrix_dev->mdevs_lock);
1872 
1873 	unmap_iova(matrix_mdev, iova, length);
1874 
1875 	mutex_unlock(&matrix_dev->mdevs_lock);
1876 }
1877 
1878 /**
1879  * vfio_ap_mdev_unset_kvm - performs clean-up of resources no longer needed
1880  * by @matrix_mdev.
1881  *
1882  * @matrix_mdev: a matrix mediated device
1883  */
1884 static void vfio_ap_mdev_unset_kvm(struct ap_matrix_mdev *matrix_mdev)
1885 {
1886 	struct kvm *kvm = matrix_mdev->kvm;
1887 
1888 	if (kvm && kvm->arch.crypto.crycbd) {
1889 		get_update_locks_for_kvm(kvm);
1890 		kvm->arch.crypto.pqap_hook = NULL;
1891 
1892 		kvm_arch_crypto_clear_masks(kvm);
1893 		vfio_ap_mdev_reset_queues(matrix_mdev);
1894 		matrix_mdev->kvm = NULL;
1895 
1896 		release_update_locks_for_kvm(kvm);
1897 		kvm_put_kvm(kvm);
1898 	}
1899 }
1900 
1901 static struct vfio_ap_queue *vfio_ap_find_queue(int apqn)
1902 {
1903 	struct ap_queue *queue;
1904 	struct vfio_ap_queue *q = NULL;
1905 
1906 	queue = ap_get_qdev(apqn);
1907 	if (!queue)
1908 		return NULL;
1909 
1910 	if (queue->ap_dev.device.driver == &matrix_dev->vfio_ap_drv->driver)
1911 		q = dev_get_drvdata(&queue->ap_dev.device);
1912 
1913 	put_device(&queue->ap_dev.device);
1914 
1915 	return q;
1916 }
1917 
1918 static int apq_status_check(int apqn, struct ap_queue_status *status)
1919 {
1920 	switch (status->response_code) {
1921 	case AP_RESPONSE_NORMAL:
1922 	case AP_RESPONSE_DECONFIGURED:
1923 	case AP_RESPONSE_CHECKSTOPPED:
1924 		return 0;
1925 	case AP_RESPONSE_RESET_IN_PROGRESS:
1926 	case AP_RESPONSE_BUSY:
1927 		return -EBUSY;
1928 	case AP_RESPONSE_ASSOC_SECRET_NOT_UNIQUE:
1929 	case AP_RESPONSE_ASSOC_FAILED:
1930 		/*
1931 		 * These asynchronous response codes indicate a PQAP(AAPQ)
1932 		 * instruction to associate a secret with the guest failed. All
1933 		 * subsequent AP instructions will end with the asynchronous
1934 		 * response code until the AP queue is reset; so, let's return
1935 		 * a value indicating a reset needs to be performed again.
1936 		 */
1937 		return -EAGAIN;
1938 	default:
1939 		WARN(true,
1940 		     "failed to verify reset of queue %02x.%04x: TAPQ rc=%u\n",
1941 		     AP_QID_CARD(apqn), AP_QID_QUEUE(apqn),
1942 		     status->response_code);
1943 		return -EIO;
1944 	}
1945 }
1946 
1947 #define WAIT_MSG "Waited %dms for reset of queue %02x.%04x (%u, %u, %u)"
1948 
1949 static void apq_reset_check(struct work_struct *reset_work)
1950 {
1951 	int ret = -EBUSY, elapsed = 0;
1952 	struct ap_queue_status status;
1953 	struct vfio_ap_queue *q;
1954 
1955 	q = container_of(reset_work, struct vfio_ap_queue, reset_work);
1956 	memcpy(&status, &q->reset_status, sizeof(status));
1957 	while (true) {
1958 		msleep(AP_RESET_INTERVAL);
1959 		elapsed += AP_RESET_INTERVAL;
1960 		status = ap_tapq(q->apqn, NULL);
1961 		ret = apq_status_check(q->apqn, &status);
1962 		if (ret == -EIO)
1963 			return;
1964 		if (ret == -EBUSY) {
1965 			pr_notice_ratelimited(WAIT_MSG, elapsed,
1966 					      AP_QID_CARD(q->apqn),
1967 					      AP_QID_QUEUE(q->apqn),
1968 					      status.response_code,
1969 					      status.queue_empty,
1970 					      status.irq_enabled);
1971 		} else {
1972 			if (q->reset_status.response_code == AP_RESPONSE_RESET_IN_PROGRESS ||
1973 			    q->reset_status.response_code == AP_RESPONSE_BUSY ||
1974 			    q->reset_status.response_code == AP_RESPONSE_STATE_CHANGE_IN_PROGRESS ||
1975 			    ret == -EAGAIN) {
1976 				status = ap_zapq(q->apqn, 0);
1977 				memcpy(&q->reset_status, &status, sizeof(status));
1978 				continue;
1979 			}
1980 			if (q->saved_isc != VFIO_AP_ISC_INVALID)
1981 				vfio_ap_free_aqic_resources(q);
1982 			break;
1983 		}
1984 	}
1985 }
1986 
1987 static void vfio_ap_mdev_reset_queue(struct vfio_ap_queue *q)
1988 {
1989 	struct ap_queue_status status;
1990 
1991 	if (!q)
1992 		return;
1993 	status = ap_zapq(q->apqn, 0);
1994 	memcpy(&q->reset_status, &status, sizeof(status));
1995 	switch (status.response_code) {
1996 	case AP_RESPONSE_NORMAL:
1997 	case AP_RESPONSE_RESET_IN_PROGRESS:
1998 	case AP_RESPONSE_BUSY:
1999 	case AP_RESPONSE_STATE_CHANGE_IN_PROGRESS:
2000 		/*
2001 		 * Let's verify whether the ZAPQ completed successfully on a work queue.
2002 		 */
2003 		queue_work(system_long_wq, &q->reset_work);
2004 		break;
2005 	case AP_RESPONSE_DECONFIGURED:
2006 	case AP_RESPONSE_CHECKSTOPPED:
2007 		vfio_ap_free_aqic_resources(q);
2008 		break;
2009 	default:
2010 		WARN(true,
2011 		     "PQAP/ZAPQ for %02x.%04x failed with invalid rc=%u\n",
2012 		     AP_QID_CARD(q->apqn), AP_QID_QUEUE(q->apqn),
2013 		     status.response_code);
2014 	}
2015 }
2016 
2017 static int vfio_ap_mdev_reset_queues(struct ap_matrix_mdev *matrix_mdev)
2018 {
2019 	int ret = 0, loop_cursor;
2020 	struct vfio_ap_queue *q;
2021 
2022 	hash_for_each(matrix_mdev->qtable.queues, loop_cursor, q, mdev_qnode)
2023 		vfio_ap_mdev_reset_queue(q);
2024 
2025 	hash_for_each(matrix_mdev->qtable.queues, loop_cursor, q, mdev_qnode) {
2026 		flush_work(&q->reset_work);
2027 
2028 		if (q->reset_status.response_code)
2029 			ret = -EIO;
2030 	}
2031 
2032 	return ret;
2033 }
2034 
2035 static int vfio_ap_mdev_reset_qlist(struct list_head *qlist)
2036 {
2037 	int ret = 0;
2038 	struct vfio_ap_queue *q;
2039 
2040 	list_for_each_entry(q, qlist, reset_qnode)
2041 		vfio_ap_mdev_reset_queue(q);
2042 
2043 	list_for_each_entry(q, qlist, reset_qnode) {
2044 		flush_work(&q->reset_work);
2045 
2046 		if (q->reset_status.response_code)
2047 			ret = -EIO;
2048 	}
2049 
2050 	return ret;
2051 }
2052 
2053 static int vfio_ap_mdev_open_device(struct vfio_device *vdev)
2054 {
2055 	struct ap_matrix_mdev *matrix_mdev =
2056 		container_of(vdev, struct ap_matrix_mdev, vdev);
2057 
2058 	if (!vdev->kvm)
2059 		return -EINVAL;
2060 
2061 	return vfio_ap_mdev_set_kvm(matrix_mdev, vdev->kvm);
2062 }
2063 
2064 static void vfio_ap_mdev_close_device(struct vfio_device *vdev)
2065 {
2066 	struct ap_matrix_mdev *matrix_mdev =
2067 		container_of(vdev, struct ap_matrix_mdev, vdev);
2068 
2069 	vfio_ap_mdev_unset_kvm(matrix_mdev);
2070 }
2071 
2072 static void vfio_ap_mdev_request(struct vfio_device *vdev, unsigned int count)
2073 {
2074 	struct device *dev = vdev->dev;
2075 	struct ap_matrix_mdev *matrix_mdev;
2076 
2077 	matrix_mdev = container_of(vdev, struct ap_matrix_mdev, vdev);
2078 
2079 	get_update_locks_for_mdev(matrix_mdev);
2080 
2081 	if (matrix_mdev->kvm) {
2082 		kvm_arch_crypto_clear_masks(matrix_mdev->kvm);
2083 		signal_guest_ap_cfg_changed(matrix_mdev);
2084 	}
2085 
2086 	if (matrix_mdev->req_trigger) {
2087 		if (!(count % 10))
2088 			dev_notice_ratelimited(dev,
2089 					       "Relaying device request to user (#%u)\n",
2090 					       count);
2091 
2092 		eventfd_signal(matrix_mdev->req_trigger);
2093 	} else if (count == 0) {
2094 		dev_notice(dev,
2095 			   "No device request registered, blocked until released by user\n");
2096 	}
2097 
2098 	release_update_locks_for_mdev(matrix_mdev);
2099 }
2100 
2101 static int vfio_ap_mdev_get_device_info(unsigned long arg)
2102 {
2103 	unsigned long minsz;
2104 	struct vfio_device_info info;
2105 
2106 	minsz = offsetofend(struct vfio_device_info, num_irqs);
2107 
2108 	if (copy_from_user(&info, (void __user *)arg, minsz))
2109 		return -EFAULT;
2110 
2111 	if (info.argsz < minsz)
2112 		return -EINVAL;
2113 
2114 	info.flags = VFIO_DEVICE_FLAGS_AP | VFIO_DEVICE_FLAGS_RESET;
2115 	info.num_regions = 0;
2116 	info.num_irqs = VFIO_AP_NUM_IRQS;
2117 
2118 	return copy_to_user((void __user *)arg, &info, minsz) ? -EFAULT : 0;
2119 }
2120 
2121 static ssize_t vfio_ap_get_irq_info(unsigned long arg)
2122 {
2123 	unsigned long minsz;
2124 	struct vfio_irq_info info;
2125 
2126 	minsz = offsetofend(struct vfio_irq_info, count);
2127 
2128 	if (copy_from_user(&info, (void __user *)arg, minsz))
2129 		return -EFAULT;
2130 
2131 	if (info.argsz < minsz || info.index >= VFIO_AP_NUM_IRQS)
2132 		return -EINVAL;
2133 
2134 	switch (info.index) {
2135 	case VFIO_AP_REQ_IRQ_INDEX:
2136 		info.count = 1;
2137 		info.flags = VFIO_IRQ_INFO_EVENTFD;
2138 		break;
2139 	case VFIO_AP_CFG_CHG_IRQ_INDEX:
2140 		info.count = 1;
2141 		info.flags = VFIO_IRQ_INFO_EVENTFD;
2142 		break;
2143 	default:
2144 		return -EINVAL;
2145 	}
2146 
2147 	return copy_to_user((void __user *)arg, &info, minsz) ? -EFAULT : 0;
2148 }
2149 
2150 static int vfio_ap_irq_set_init(struct vfio_irq_set *irq_set, unsigned long arg)
2151 {
2152 	int ret;
2153 	size_t data_size;
2154 	unsigned long minsz;
2155 
2156 	minsz = offsetofend(struct vfio_irq_set, count);
2157 
2158 	if (copy_from_user(irq_set, (void __user *)arg, minsz))
2159 		return -EFAULT;
2160 
2161 	ret = vfio_set_irqs_validate_and_prepare(irq_set, 1, VFIO_AP_NUM_IRQS,
2162 						 &data_size);
2163 	if (ret)
2164 		return ret;
2165 
2166 	if (!(irq_set->flags & VFIO_IRQ_SET_ACTION_TRIGGER))
2167 		return -EINVAL;
2168 
2169 	return 0;
2170 }
2171 
2172 static int vfio_ap_set_request_irq(struct ap_matrix_mdev *matrix_mdev,
2173 				   unsigned long arg)
2174 {
2175 	s32 fd;
2176 	void __user *data;
2177 	unsigned long minsz;
2178 	struct eventfd_ctx *req_trigger;
2179 
2180 	minsz = offsetofend(struct vfio_irq_set, count);
2181 	data = (void __user *)(arg + minsz);
2182 
2183 	if (get_user(fd, (s32 __user *)data))
2184 		return -EFAULT;
2185 
2186 	if (fd == -1) {
2187 		if (matrix_mdev->req_trigger)
2188 			eventfd_ctx_put(matrix_mdev->req_trigger);
2189 		matrix_mdev->req_trigger = NULL;
2190 	} else if (fd >= 0) {
2191 		req_trigger = eventfd_ctx_fdget(fd);
2192 		if (IS_ERR(req_trigger))
2193 			return PTR_ERR(req_trigger);
2194 
2195 		if (matrix_mdev->req_trigger)
2196 			eventfd_ctx_put(matrix_mdev->req_trigger);
2197 
2198 		matrix_mdev->req_trigger = req_trigger;
2199 	} else {
2200 		return -EINVAL;
2201 	}
2202 
2203 	return 0;
2204 }
2205 
2206 static int vfio_ap_set_cfg_change_irq(struct ap_matrix_mdev *matrix_mdev, unsigned long arg)
2207 {
2208 	s32 fd;
2209 	void __user *data;
2210 	unsigned long minsz;
2211 	struct eventfd_ctx *cfg_chg_trigger;
2212 
2213 	minsz = offsetofend(struct vfio_irq_set, count);
2214 	data = (void __user *)(arg + minsz);
2215 
2216 	if (get_user(fd, (s32 __user *)data))
2217 		return -EFAULT;
2218 
2219 	if (fd == -1) {
2220 		if (matrix_mdev->cfg_chg_trigger)
2221 			eventfd_ctx_put(matrix_mdev->cfg_chg_trigger);
2222 		matrix_mdev->cfg_chg_trigger = NULL;
2223 	} else if (fd >= 0) {
2224 		cfg_chg_trigger = eventfd_ctx_fdget(fd);
2225 		if (IS_ERR(cfg_chg_trigger))
2226 			return PTR_ERR(cfg_chg_trigger);
2227 
2228 		if (matrix_mdev->cfg_chg_trigger)
2229 			eventfd_ctx_put(matrix_mdev->cfg_chg_trigger);
2230 
2231 		matrix_mdev->cfg_chg_trigger = cfg_chg_trigger;
2232 	} else {
2233 		return -EINVAL;
2234 	}
2235 
2236 	return 0;
2237 }
2238 
2239 static int vfio_ap_set_irqs(struct ap_matrix_mdev *matrix_mdev,
2240 			    unsigned long arg)
2241 {
2242 	int ret;
2243 	struct vfio_irq_set irq_set;
2244 
2245 	ret = vfio_ap_irq_set_init(&irq_set, arg);
2246 	if (ret)
2247 		return ret;
2248 
2249 	switch (irq_set.flags & VFIO_IRQ_SET_DATA_TYPE_MASK) {
2250 	case VFIO_IRQ_SET_DATA_EVENTFD:
2251 		switch (irq_set.index) {
2252 		case VFIO_AP_REQ_IRQ_INDEX:
2253 			return vfio_ap_set_request_irq(matrix_mdev, arg);
2254 		case VFIO_AP_CFG_CHG_IRQ_INDEX:
2255 			return vfio_ap_set_cfg_change_irq(matrix_mdev, arg);
2256 		default:
2257 			return -EINVAL;
2258 		}
2259 	default:
2260 		return -EINVAL;
2261 	}
2262 }
2263 
2264 static ssize_t vfio_ap_mdev_ioctl(struct vfio_device *vdev,
2265 				    unsigned int cmd, unsigned long arg)
2266 {
2267 	struct ap_matrix_mdev *matrix_mdev =
2268 		container_of(vdev, struct ap_matrix_mdev, vdev);
2269 	int ret;
2270 
2271 	mutex_lock(&matrix_dev->mdevs_lock);
2272 	switch (cmd) {
2273 	case VFIO_DEVICE_GET_INFO:
2274 		ret = vfio_ap_mdev_get_device_info(arg);
2275 		break;
2276 	case VFIO_DEVICE_RESET:
2277 		ret = vfio_ap_mdev_reset_queues(matrix_mdev);
2278 		break;
2279 	case VFIO_DEVICE_GET_IRQ_INFO:
2280 		ret = vfio_ap_get_irq_info(arg);
2281 		break;
2282 	case VFIO_DEVICE_SET_IRQS:
2283 		ret = vfio_ap_set_irqs(matrix_mdev, arg);
2284 		break;
2285 	default:
2286 		ret = -EOPNOTSUPP;
2287 		break;
2288 	}
2289 	mutex_unlock(&matrix_dev->mdevs_lock);
2290 
2291 	return ret;
2292 }
2293 
2294 static struct ap_matrix_mdev *vfio_ap_mdev_for_queue(struct vfio_ap_queue *q)
2295 {
2296 	struct ap_matrix_mdev *matrix_mdev;
2297 	unsigned long apid = AP_QID_CARD(q->apqn);
2298 	unsigned long apqi = AP_QID_QUEUE(q->apqn);
2299 
2300 	lockdep_assert_held(&matrix_dev->guests_lock);
2301 
2302 	list_for_each_entry(matrix_mdev, &matrix_dev->mdev_list, node) {
2303 		if (test_bit_inv(apid, matrix_mdev->matrix.apm) &&
2304 		    test_bit_inv(apqi, matrix_mdev->matrix.aqm))
2305 			return matrix_mdev;
2306 	}
2307 
2308 	return NULL;
2309 }
2310 
2311 static ssize_t status_show(struct device *dev,
2312 			   struct device_attribute *attr,
2313 			   char *buf)
2314 {
2315 	ssize_t nchars = 0;
2316 	struct vfio_ap_queue *q;
2317 	unsigned long apid, apqi;
2318 	struct ap_matrix_mdev *matrix_mdev;
2319 	struct ap_device *apdev = to_ap_dev(dev);
2320 
2321 	mutex_lock(&matrix_dev->guests_lock);
2322 	mutex_lock(&matrix_dev->mdevs_lock);
2323 	q = dev_get_drvdata(&apdev->device);
2324 
2325 	/*
2326 	 * Make sure the drvdata has been set before proceeding. There is a
2327 	 * possibility that the drvdata was not set if the vfio_ap_queue object
2328 	 * could not be allocated when the queue device was probed. In that case,
2329 	 * the locks used in vfio_ap_mdev_probe_queue() are released prior to
2330 	 * removing the sysfs status attribute to avoid a lockdep
2331 	 * splat. That opens a very small window where the status attribute is
2332 	 * still available without the vfio_ap_queue object having been
2333 	 * stored in the device drvdata. In that case, indicate the queue is not
2334 	 * assigned.
2335 	 */
2336 	if (!q) {
2337 		nchars = sysfs_emit(buf, "%s\n", AP_QUEUE_UNASSIGNED);
2338 		goto done;
2339 	}
2340 
2341 	matrix_mdev = vfio_ap_mdev_for_queue(q);
2342 
2343 	/* If the queue is assigned to the matrix mediated device, then
2344 	 * determine whether it is passed through to a guest; otherwise,
2345 	 * indicate that it is unassigned.
2346 	 */
2347 	if (matrix_mdev) {
2348 		apid = AP_QID_CARD(q->apqn);
2349 		apqi = AP_QID_QUEUE(q->apqn);
2350 		/*
2351 		 * If the queue is passed through to the guest, then indicate
2352 		 * that it is in use; otherwise, indicate that it is
2353 		 * merely assigned to a matrix mediated device.
2354 		 */
2355 		if (matrix_mdev->kvm &&
2356 		    test_bit_inv(apid, matrix_mdev->shadow_apcb.apm) &&
2357 		    test_bit_inv(apqi, matrix_mdev->shadow_apcb.aqm))
2358 			nchars = sysfs_emit(buf, "%s\n", AP_QUEUE_IN_USE);
2359 		else
2360 			nchars = sysfs_emit(buf, "%s\n", AP_QUEUE_ASSIGNED);
2361 	} else {
2362 		nchars = sysfs_emit(buf, "%s\n", AP_QUEUE_UNASSIGNED);
2363 	}
2364 
2365 done:
2366 	mutex_unlock(&matrix_dev->mdevs_lock);
2367 	mutex_unlock(&matrix_dev->guests_lock);
2368 
2369 	return nchars;
2370 }
2371 
2372 static DEVICE_ATTR_RO(status);
2373 
2374 static struct attribute *vfio_queue_attrs[] = {
2375 	&dev_attr_status.attr,
2376 	NULL,
2377 };
2378 
2379 static const struct attribute_group vfio_queue_attr_group = {
2380 	.attrs = vfio_queue_attrs,
2381 };
2382 
2383 static const struct vfio_device_ops vfio_ap_matrix_dev_ops = {
2384 	.init = vfio_ap_mdev_init_dev,
2385 	.open_device = vfio_ap_mdev_open_device,
2386 	.close_device = vfio_ap_mdev_close_device,
2387 	.ioctl = vfio_ap_mdev_ioctl,
2388 	.dma_unmap = vfio_ap_mdev_dma_unmap,
2389 	.bind_iommufd = vfio_iommufd_emulated_bind,
2390 	.unbind_iommufd = vfio_iommufd_emulated_unbind,
2391 	.attach_ioas = vfio_iommufd_emulated_attach_ioas,
2392 	.detach_ioas = vfio_iommufd_emulated_detach_ioas,
2393 	.request = vfio_ap_mdev_request
2394 };
2395 
2396 static struct mdev_driver vfio_ap_matrix_driver = {
2397 	.device_api = VFIO_DEVICE_API_AP_STRING,
2398 	.max_instances = MAX_ZDEV_ENTRIES_EXT,
2399 	.driver = {
2400 		.name = "vfio_ap_mdev",
2401 		.owner = THIS_MODULE,
2402 		.mod_name = KBUILD_MODNAME,
2403 		.dev_groups = vfio_ap_mdev_attr_groups,
2404 	},
2405 	.probe = vfio_ap_mdev_probe,
2406 	.remove = vfio_ap_mdev_remove,
2407 };
2408 
2409 int vfio_ap_mdev_register(void)
2410 {
2411 	int ret;
2412 
2413 	ret = mdev_register_driver(&vfio_ap_matrix_driver);
2414 	if (ret)
2415 		return ret;
2416 
2417 	matrix_dev->mdev_type.sysfs_name = VFIO_AP_MDEV_TYPE_HWVIRT;
2418 	matrix_dev->mdev_type.pretty_name = VFIO_AP_MDEV_NAME_HWVIRT;
2419 	matrix_dev->mdev_types = &matrix_dev->mdev_type;
2420 	ret = mdev_register_parent(&matrix_dev->parent, &matrix_dev->device,
2421 				   &vfio_ap_matrix_driver,
2422 				   &matrix_dev->mdev_types, 1);
2423 	if (ret)
2424 		goto err_driver;
2425 	return 0;
2426 
2427 err_driver:
2428 	mdev_unregister_driver(&vfio_ap_matrix_driver);
2429 	return ret;
2430 }
2431 
2432 void vfio_ap_mdev_unregister(void)
2433 {
2434 	mdev_unregister_parent(&matrix_dev->parent);
2435 	mdev_unregister_driver(&vfio_ap_matrix_driver);
2436 }
2437 
2438 int vfio_ap_mdev_probe_queue(struct ap_device *apdev)
2439 {
2440 	int ret, apqn;
2441 	struct vfio_ap_queue *q;
2442 	DECLARE_BITMAP(apm_filtered, AP_DEVICES);
2443 	struct ap_matrix_mdev *matrix_mdev;
2444 
2445 	apqn = to_ap_queue(&apdev->device)->qid;
2446 	matrix_mdev = get_update_locks_by_apqn(apqn);
2447 
2448 	ret = sysfs_create_group(&apdev->device.kobj, &vfio_queue_attr_group);
2449 	if (ret)
2450 		goto err_release_locks;
2451 
2452 	q = kzalloc_obj(*q);
2453 	if (!q) {
2454 		ret = -ENOMEM;
2455 		goto err_remove_group;
2456 	}
2457 
2458 	q->apqn = apqn;
2459 	q->saved_isc = VFIO_AP_ISC_INVALID;
2460 	memset(&q->reset_status, 0, sizeof(q->reset_status));
2461 	INIT_WORK(&q->reset_work, apq_reset_check);
2462 
2463 	if (matrix_mdev) {
2464 		vfio_ap_mdev_link_queue(matrix_mdev, q);
2465 
2466 		/*
2467 		 * If we're in the process of handling the adding of adapters or
2468 		 * domains to the host's AP configuration, then let the
2469 		 * vfio_ap device driver's on_scan_complete callback filter the
2470 		 * matrix and update the guest's AP configuration after all of
2471 		 * the new queue devices are probed.
2472 		 */
2473 		if (!bitmap_empty(matrix_mdev->apm_add, AP_DEVICES) ||
2474 		    !bitmap_empty(matrix_mdev->aqm_add, AP_DOMAINS))
2475 			goto done;
2476 
2477 		if (vfio_ap_mdev_filter_matrix(matrix_mdev, apm_filtered)) {
2478 			vfio_ap_mdev_update_guest_apcb(matrix_mdev);
2479 			reset_queues_for_apids(matrix_mdev, apm_filtered);
2480 		}
2481 	}
2482 
2483 done:
2484 	dev_set_drvdata(&apdev->device, q);
2485 	release_update_locks_for_mdev(matrix_mdev);
2486 
2487 	return ret;
2488 
2489 err_remove_group:
2490 	release_update_locks_for_mdev(matrix_mdev);
2491 	sysfs_remove_group(&apdev->device.kobj, &vfio_queue_attr_group);
2492 	return ret;
2493 
2494 err_release_locks:
2495 	release_update_locks_for_mdev(matrix_mdev);
2496 	return ret;
2497 }
2498 
2499 void vfio_ap_mdev_remove_queue(struct ap_device *apdev)
2500 {
2501 	unsigned long apid, apqi;
2502 	struct vfio_ap_queue *q;
2503 	struct ap_matrix_mdev *matrix_mdev;
2504 
2505 	sysfs_remove_group(&apdev->device.kobj, &vfio_queue_attr_group);
2506 	q = dev_get_drvdata(&apdev->device);
2507 	get_update_locks_for_queue(q);
2508 	matrix_mdev = q->matrix_mdev;
2509 	apid = AP_QID_CARD(q->apqn);
2510 	apqi = AP_QID_QUEUE(q->apqn);
2511 
2512 	if (matrix_mdev) {
2513 		/* If the queue is assigned to the guest's AP configuration */
2514 		if (test_bit_inv(apid, matrix_mdev->shadow_apcb.apm) &&
2515 		    test_bit_inv(apqi, matrix_mdev->shadow_apcb.aqm)) {
2516 			/*
2517 			 * Since the queues are defined via a matrix of adapters
2518 			 * and domains, it is not possible to hot unplug a
2519 			 * single queue; so, let's unplug the adapter.
2520 			 */
2521 			clear_bit_inv(apid, matrix_mdev->shadow_apcb.apm);
2522 			vfio_ap_mdev_update_guest_apcb(matrix_mdev);
2523 			reset_queues_for_apid(matrix_mdev, apid);
2524 			goto done;
2525 		}
2526 	}
2527 
2528 	/*
2529 	 * If the queue is not in the host's AP configuration, then resetting
2530 	 * it will fail with response code 01, (APQN not valid); so, let's make
2531 	 * sure it is in the host's config.
2532 	 */
2533 	if (test_bit_inv(apid, (unsigned long *)matrix_dev->info.apm) &&
2534 	    test_bit_inv(apqi, (unsigned long *)matrix_dev->info.aqm)) {
2535 		vfio_ap_mdev_reset_queue(q);
2536 		flush_work(&q->reset_work);
2537 	}
2538 
2539 done:
2540 	if (matrix_mdev)
2541 		vfio_ap_unlink_queue_fr_mdev(q);
2542 
2543 	dev_set_drvdata(&apdev->device, NULL);
2544 	kfree(q);
2545 	release_update_locks_for_mdev(matrix_mdev);
2546 }
2547 
2548 /**
2549  * vfio_ap_mdev_resource_in_use: check whether any of a set of APQNs is
2550  *				 assigned to a mediated device under the control
2551  *				 of the vfio_ap device driver.
2552  *
2553  * @apm: a bitmap specifying a set of APIDs comprising the APQNs to check.
2554  * @aqm: a bitmap specifying a set of APQIs comprising the APQNs to check.
2555  *
2556  * Return:
2557  *	* -EADDRINUSE if one or more of the APQNs specified via @apm/@aqm are
2558  *	  assigned to a mediated device under the control of the vfio_ap
2559  *	  device driver.
2560  *	* Otherwise, return 0.
2561  */
2562 int vfio_ap_mdev_resource_in_use(unsigned long *apm, unsigned long *aqm)
2563 {
2564 	int ret;
2565 
2566 	mutex_lock(&matrix_dev->guests_lock);
2567 	mutex_lock(&matrix_dev->mdevs_lock);
2568 	ret = vfio_ap_mdev_verify_no_sharing(NULL, apm, aqm);
2569 	mutex_unlock(&matrix_dev->mdevs_lock);
2570 	mutex_unlock(&matrix_dev->guests_lock);
2571 
2572 	return ret;
2573 }
2574 
2575 /**
2576  * vfio_ap_mdev_hot_unplug_cfg - hot unplug the adapters, domains and control
2577  *				 domains that have been removed from the host's
2578  *				 AP configuration from a guest.
2579  *
2580  * @matrix_mdev: an ap_matrix_mdev object attached to a KVM guest.
2581  * @aprem: the adapters that have been removed from the host's AP configuration
2582  * @aqrem: the domains that have been removed from the host's AP configuration
2583  * @cdrem: the control domains that have been removed from the host's AP
2584  *	   configuration.
2585  */
2586 static void vfio_ap_mdev_hot_unplug_cfg(struct ap_matrix_mdev *matrix_mdev,
2587 					unsigned long *aprem,
2588 					unsigned long *aqrem,
2589 					unsigned long *cdrem)
2590 {
2591 	bool do_hotplug = false;
2592 
2593 	if (bitmap_intersects(matrix_mdev->shadow_apcb.apm, aprem, AP_DEVICES)) {
2594 		bitmap_andnot(matrix_mdev->shadow_apcb.apm,
2595 			      matrix_mdev->shadow_apcb.apm,
2596 			      aprem, AP_DEVICES);
2597 		do_hotplug = true;
2598 	}
2599 
2600 	if (bitmap_intersects(matrix_mdev->shadow_apcb.aqm, aqrem, AP_DOMAINS)) {
2601 		bitmap_andnot(matrix_mdev->shadow_apcb.aqm,
2602 			      matrix_mdev->shadow_apcb.aqm,
2603 			      aqrem, AP_DOMAINS);
2604 		do_hotplug = true;
2605 	}
2606 
2607 	if (bitmap_intersects(matrix_mdev->shadow_apcb.adm, cdrem, AP_DOMAINS)) {
2608 		bitmap_andnot(matrix_mdev->shadow_apcb.adm,
2609 			      matrix_mdev->shadow_apcb.adm,
2610 			      cdrem, AP_DOMAINS);
2611 		do_hotplug = true;
2612 	}
2613 
2614 	if (do_hotplug)
2615 		vfio_ap_mdev_update_guest_apcb(matrix_mdev);
2616 }
2617 
2618 /**
2619  * vfio_ap_mdev_cfg_remove - determines which guests are using the adapters,
2620  *			     domains and control domains that have been removed
2621  *			     from the host AP configuration and unplugs them
2622  *			     from those guests.
2623  *
2624  * @ap_remove:	bitmap specifying which adapters have been removed from the host
2625  *		config.
2626  * @aq_remove:	bitmap specifying which domains have been removed from the host
2627  *		config.
2628  * @cd_remove:	bitmap specifying which control domains have been removed from
2629  *		the host config.
2630  */
2631 static void vfio_ap_mdev_cfg_remove(unsigned long *ap_remove,
2632 				    unsigned long *aq_remove,
2633 				    unsigned long *cd_remove)
2634 {
2635 	struct ap_matrix_mdev *matrix_mdev;
2636 	DECLARE_BITMAP(aprem, AP_DEVICES);
2637 	DECLARE_BITMAP(aqrem, AP_DOMAINS);
2638 	DECLARE_BITMAP(cdrem, AP_DOMAINS);
2639 	int do_remove;
2640 
2641 	/*
2642 	 * It is safe to traverse this list here because the
2643 	 * required guard - matrix_dev->guests_lock - is taken in the
2644 	 * vfio_ap_on_cfg_changed function prior to this function getting
2645 	 * called.
2646 	 */
2647 	list_for_each_entry(matrix_mdev, &matrix_dev->mdev_list, node) {
2648 		/*
2649 		 * The mdevs_lock must be held to access fields within matrix_mdev,
2650 		 * and kvm->lock must be taken before mdevs_lock to satisfy the lock
2651 		 * ordering requirement and prevent a lockdep splat.
2652 		 */
2653 		if (matrix_mdev->kvm)
2654 			mutex_lock(&matrix_mdev->kvm->lock);
2655 		mutex_lock(&matrix_dev->mdevs_lock);
2656 
2657 		do_remove = bitmap_and(aprem, ap_remove,
2658 				       matrix_mdev->matrix.apm,
2659 				       AP_DEVICES);
2660 		do_remove |= bitmap_and(aqrem, aq_remove,
2661 					  matrix_mdev->matrix.aqm,
2662 					  AP_DOMAINS);
2663 		do_remove |= bitmap_and(cdrem, cd_remove,
2664 					matrix_mdev->matrix.adm,
2665 					AP_DOMAINS);
2666 
2667 		if (do_remove)
2668 			vfio_ap_mdev_hot_unplug_cfg(matrix_mdev, aprem, aqrem,
2669 						    cdrem);
2670 
2671 		mutex_unlock(&matrix_dev->mdevs_lock);
2672 		if (matrix_mdev->kvm)
2673 			mutex_unlock(&matrix_mdev->kvm->lock);
2674 	}
2675 }
2676 
2677 /**
2678  * vfio_ap_mdev_on_cfg_remove - responds to the removal of adapters, domains and
2679  *				control domains from the host AP configuration
2680  *				by unplugging them from the guests that are
2681  *				using them.
2682  * @cur_config_info: the current host AP configuration information
2683  * @prev_config_info: the previous host AP configuration information
2684  */
2685 static void vfio_ap_mdev_on_cfg_remove(struct ap_config_info *cur_config_info,
2686 				       struct ap_config_info *prev_config_info)
2687 {
2688 	int do_remove;
2689 	DECLARE_BITMAP(aprem, AP_DEVICES);
2690 	DECLARE_BITMAP(aqrem, AP_DOMAINS);
2691 	DECLARE_BITMAP(cdrem, AP_DOMAINS);
2692 
2693 	do_remove = bitmap_andnot(aprem,
2694 				  (unsigned long *)prev_config_info->apm,
2695 				  (unsigned long *)cur_config_info->apm,
2696 				  AP_DEVICES);
2697 	do_remove |= bitmap_andnot(aqrem,
2698 				   (unsigned long *)prev_config_info->aqm,
2699 				   (unsigned long *)cur_config_info->aqm,
2700 				   AP_DEVICES);
2701 	do_remove |= bitmap_andnot(cdrem,
2702 				   (unsigned long *)prev_config_info->adm,
2703 				   (unsigned long *)cur_config_info->adm,
2704 				   AP_DEVICES);
2705 
2706 	if (do_remove)
2707 		vfio_ap_mdev_cfg_remove(aprem, aqrem, cdrem);
2708 }
2709 
2710 /**
2711  * vfio_ap_filter_apid_by_qtype: filter APIDs from an AP mask for adapters that
2712  *				 are older than AP type 10 (CEX4).
2713  * @apm: a bitmap of the APIDs to examine
2714  * @aqm: a bitmap of the APQIs of the queues to query for the AP type.
2715  */
2716 static void vfio_ap_filter_apid_by_qtype(unsigned long *apm, unsigned long *aqm)
2717 {
2718 	bool apid_cleared;
2719 	struct ap_queue_status status;
2720 	unsigned long apid, apqi;
2721 	struct ap_tapq_hwinfo info;
2722 
2723 	for_each_set_bit_inv(apid, apm, AP_DEVICES) {
2724 		apid_cleared = false;
2725 
2726 		for_each_set_bit_inv(apqi, aqm, AP_DOMAINS) {
2727 			status = ap_test_queue(AP_MKQID(apid, apqi), 1, &info);
2728 			switch (status.response_code) {
2729 			/*
2730 			 * According to the architecture in each case
2731 			 * below, the queue's info should be filled.
2732 			 */
2733 			case AP_RESPONSE_NORMAL:
2734 			case AP_RESPONSE_RESET_IN_PROGRESS:
2735 			case AP_RESPONSE_DECONFIGURED:
2736 			case AP_RESPONSE_CHECKSTOPPED:
2737 			case AP_RESPONSE_BUSY:
2738 				/*
2739 				 * The vfio_ap device driver only
2740 				 * supports CEX4 and newer adapters, so
2741 				 * remove the APID if the adapter is
2742 				 * older than a CEX4.
2743 				 */
2744 				if (info.at < AP_DEVICE_TYPE_CEX4) {
2745 					clear_bit_inv(apid, apm);
2746 					apid_cleared = true;
2747 				}
2748 
2749 				break;
2750 
2751 			default:
2752 				/*
2753 				 * If we don't know the adapter type,
2754 				 * clear its APID since it can't be
2755 				 * determined whether the vfio_ap
2756 				 * device driver supports it.
2757 				 */
2758 				clear_bit_inv(apid, apm);
2759 				apid_cleared = true;
2760 				break;
2761 			}
2762 
2763 			/*
2764 			 * If we've already cleared the APID from the apm, there
2765 			 * is no need to continue examining the remainin AP
2766 			 * queues to determine the type of the adapter.
2767 			 */
2768 			if (apid_cleared)
2769 				continue;
2770 		}
2771 	}
2772 }
2773 
2774 /**
2775  * vfio_ap_mdev_cfg_add - store bitmaps specifying the adapters, domains and
2776  *			  control domains that have been added to the host's
2777  *			  AP configuration for each matrix mdev to which they
2778  *			  are assigned.
2779  *
2780  * @apm_add: a bitmap specifying the adapters that have been added to the AP
2781  *	     configuration.
2782  * @aqm_add: a bitmap specifying the domains that have been added to the AP
2783  *	     configuration.
2784  * @adm_add: a bitmap specifying the control domains that have been added to the
2785  *	     AP configuration.
2786  */
2787 static void vfio_ap_mdev_cfg_add(unsigned long *apm_add, unsigned long *aqm_add,
2788 				 unsigned long *adm_add)
2789 {
2790 	struct ap_matrix_mdev *matrix_mdev;
2791 
2792 	if (list_empty(&matrix_dev->mdev_list))
2793 		return;
2794 
2795 	vfio_ap_filter_apid_by_qtype(apm_add, aqm_add);
2796 
2797 	/*
2798 	 * It is safe to traverse this list here because the
2799 	 * required guard - matrix_dev->guests_lock - is taken in the
2800 	 * vfio_ap_on_cfg_changed function prior to this function getting
2801 	 * called.
2802 	 */
2803 	list_for_each_entry(matrix_mdev, &matrix_dev->mdev_list, node) {
2804 		/*
2805 		 * The mdevs_lock must be held in order to access fields
2806 		 * within matrix_mdev
2807 		 */
2808 		mutex_lock(&matrix_dev->mdevs_lock);
2809 
2810 		bitmap_and(matrix_mdev->apm_add,
2811 			   matrix_mdev->matrix.apm, apm_add, AP_DEVICES);
2812 		bitmap_and(matrix_mdev->aqm_add,
2813 			   matrix_mdev->matrix.aqm, aqm_add, AP_DOMAINS);
2814 		bitmap_and(matrix_mdev->adm_add,
2815 			   matrix_mdev->matrix.adm, adm_add, AP_DEVICES);
2816 
2817 		mutex_unlock(&matrix_dev->mdevs_lock);
2818 	}
2819 }
2820 
2821 /**
2822  * vfio_ap_mdev_on_cfg_add - responds to the addition of adapters, domains and
2823  *			     control domains to the host AP configuration
2824  *			     by updating the bitmaps that specify what adapters,
2825  *			     domains and control domains have been added so they
2826  *			     can be hot plugged into the guest when the AP bus
2827  *			     scan completes (see vfio_ap_on_scan_complete
2828  *			     function).
2829  * @cur_config_info: the current AP configuration information
2830  * @prev_config_info: the previous AP configuration information
2831  */
2832 static void vfio_ap_mdev_on_cfg_add(struct ap_config_info *cur_config_info,
2833 				    struct ap_config_info *prev_config_info)
2834 {
2835 	bool do_add;
2836 	DECLARE_BITMAP(apm_add, AP_DEVICES);
2837 	DECLARE_BITMAP(aqm_add, AP_DOMAINS);
2838 	DECLARE_BITMAP(adm_add, AP_DOMAINS);
2839 
2840 	do_add = bitmap_andnot(apm_add,
2841 			       (unsigned long *)cur_config_info->apm,
2842 			       (unsigned long *)prev_config_info->apm,
2843 			       AP_DEVICES);
2844 	do_add |= bitmap_andnot(aqm_add,
2845 				(unsigned long *)cur_config_info->aqm,
2846 				(unsigned long *)prev_config_info->aqm,
2847 				AP_DOMAINS);
2848 	do_add |= bitmap_andnot(adm_add,
2849 				(unsigned long *)cur_config_info->adm,
2850 				(unsigned long *)prev_config_info->adm,
2851 				AP_DOMAINS);
2852 
2853 	if (do_add)
2854 		vfio_ap_mdev_cfg_add(apm_add, aqm_add, adm_add);
2855 }
2856 
2857 /**
2858  * vfio_ap_on_cfg_changed - handles notification of changes to the host AP
2859  *			    configuration.
2860  *
2861  * @cur_cfg_info: the current host AP configuration
2862  * @prev_cfg_info: the previous host AP configuration
2863  */
2864 void vfio_ap_on_cfg_changed(struct ap_config_info *cur_cfg_info,
2865 			    struct ap_config_info *prev_cfg_info)
2866 {
2867 	if (!cur_cfg_info || !prev_cfg_info)
2868 		return;
2869 
2870 	/*
2871 	 * Take the guests_lock mutex here to guard access to the
2872 	 * matrix_dev->mdev_list in the two functions called below.
2873 	 */
2874 	mutex_lock(&matrix_dev->guests_lock);
2875 
2876 	vfio_ap_mdev_on_cfg_remove(cur_cfg_info, prev_cfg_info);
2877 	vfio_ap_mdev_on_cfg_add(cur_cfg_info, prev_cfg_info);
2878 	memcpy(&matrix_dev->info, cur_cfg_info, sizeof(*cur_cfg_info));
2879 
2880 	mutex_unlock(&matrix_dev->guests_lock);
2881 }
2882 
2883 static void vfio_ap_mdev_hot_plug_cfg(struct ap_matrix_mdev *matrix_mdev)
2884 {
2885 	DECLARE_BITMAP(apm_filtered, AP_DEVICES);
2886 	bool filter_domains, filter_adapters, filter_cdoms, do_hotplug = false;
2887 
2888 	/*
2889 	 * Zero out the apm_filtered bitmap in case there are no adapters or
2890 	 * domains to be added, but only control domains. In that case,
2891 	 * vfio_ap_mdev_filter_matrix() - which initializes apm_filtered - will
2892 	 * not get called and the reset_queues_for_apids will crash because it
2893 	 * will access an uninitialized bitmap.
2894 	 */
2895 	bitmap_zero(apm_filtered, AP_DEVICES);
2896 
2897 	filter_adapters = bitmap_intersects(matrix_mdev->matrix.apm,
2898 					    matrix_mdev->apm_add, AP_DEVICES);
2899 	filter_domains = bitmap_intersects(matrix_mdev->matrix.aqm,
2900 					   matrix_mdev->aqm_add, AP_DOMAINS);
2901 	filter_cdoms = bitmap_intersects(matrix_mdev->matrix.adm,
2902 					 matrix_mdev->adm_add, AP_DOMAINS);
2903 
2904 	if (filter_adapters || filter_domains)
2905 		do_hotplug = vfio_ap_mdev_filter_matrix(matrix_mdev, apm_filtered);
2906 
2907 	if (filter_cdoms)
2908 		do_hotplug |= vfio_ap_mdev_filter_cdoms(matrix_mdev);
2909 
2910 	if (do_hotplug)
2911 		vfio_ap_mdev_update_guest_apcb(matrix_mdev);
2912 
2913 	reset_queues_for_apids(matrix_mdev, apm_filtered);
2914 }
2915 
2916 void vfio_ap_on_scan_complete(struct ap_config_info *new_config_info,
2917 			      struct ap_config_info *old_config_info)
2918 {
2919 	struct ap_matrix_mdev *matrix_mdev;
2920 
2921 	mutex_lock(&matrix_dev->guests_lock);
2922 
2923 	list_for_each_entry(matrix_mdev, &matrix_dev->mdev_list, node) {
2924 		/*
2925 		 * The mdevs_lock must be held to access fields within matrix_mdev,
2926 		 * and kvm->lock must be taken before mdevs_lock to satisfy the lock
2927 		 * ordering requirement and prevent a lockdep splat.
2928 		 */
2929 		if (matrix_mdev->kvm)
2930 			mutex_lock(&matrix_mdev->kvm->lock);
2931 		mutex_lock(&matrix_dev->mdevs_lock);
2932 
2933 		if (bitmap_empty(matrix_mdev->apm_add, AP_DEVICES) &&
2934 		    bitmap_empty(matrix_mdev->aqm_add, AP_DOMAINS) &&
2935 		    bitmap_empty(matrix_mdev->adm_add, AP_DOMAINS))
2936 			goto do_unlock;
2937 
2938 		vfio_ap_mdev_hot_plug_cfg(matrix_mdev);
2939 		bitmap_clear(matrix_mdev->apm_add, 0, AP_DEVICES);
2940 		bitmap_clear(matrix_mdev->aqm_add, 0, AP_DOMAINS);
2941 		bitmap_clear(matrix_mdev->adm_add, 0, AP_DOMAINS);
2942 
2943 do_unlock:
2944 		mutex_unlock(&matrix_dev->mdevs_lock);
2945 		if (matrix_mdev->kvm)
2946 			mutex_unlock(&matrix_mdev->kvm->lock);
2947 	}
2948 
2949 	mutex_unlock(&matrix_dev->guests_lock);
2950 }
2951