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 static int vfio_ap_mdev_reset_queues(struct ap_queue_table *qtable);
34 static struct vfio_ap_queue *vfio_ap_find_queue(int apqn);
35 static const struct vfio_device_ops vfio_ap_matrix_dev_ops;
36 static int vfio_ap_mdev_reset_queue(struct vfio_ap_queue *q, unsigned int retry);
37 
38 /**
39  * get_update_locks_for_kvm: Acquire the locks required to dynamically update a
40  *			     KVM guest's APCB in the proper order.
41  *
42  * @kvm: a pointer to a struct kvm object containing the KVM guest's APCB.
43  *
44  * The proper locking order is:
45  * 1. matrix_dev->guests_lock: required to use the KVM pointer to update a KVM
46  *			       guest's APCB.
47  * 2. kvm->lock:	       required to update a guest's APCB
48  * 3. matrix_dev->mdevs_lock:  required to access data stored in a matrix_mdev
49  *
50  * Note: If @kvm is NULL, the KVM lock will not be taken.
51  */
52 static inline void get_update_locks_for_kvm(struct kvm *kvm)
53 {
54 	mutex_lock(&matrix_dev->guests_lock);
55 	if (kvm)
56 		mutex_lock(&kvm->lock);
57 	mutex_lock(&matrix_dev->mdevs_lock);
58 }
59 
60 /**
61  * release_update_locks_for_kvm: Release the locks used to dynamically update a
62  *				 KVM guest's APCB in the proper order.
63  *
64  * @kvm: a pointer to a struct kvm object containing the KVM guest's APCB.
65  *
66  * The proper unlocking order is:
67  * 1. matrix_dev->mdevs_lock
68  * 2. kvm->lock
69  * 3. matrix_dev->guests_lock
70  *
71  * Note: If @kvm is NULL, the KVM lock will not be released.
72  */
73 static inline void release_update_locks_for_kvm(struct kvm *kvm)
74 {
75 	mutex_unlock(&matrix_dev->mdevs_lock);
76 	if (kvm)
77 		mutex_unlock(&kvm->lock);
78 	mutex_unlock(&matrix_dev->guests_lock);
79 }
80 
81 /**
82  * get_update_locks_for_mdev: Acquire the locks required to dynamically update a
83  *			      KVM guest's APCB in the proper order.
84  *
85  * @matrix_mdev: a pointer to a struct ap_matrix_mdev object containing the AP
86  *		 configuration data to use to update a KVM guest's APCB.
87  *
88  * The proper locking order is:
89  * 1. matrix_dev->guests_lock: required to use the KVM pointer to update a KVM
90  *			       guest's APCB.
91  * 2. matrix_mdev->kvm->lock:  required to update a guest's APCB
92  * 3. matrix_dev->mdevs_lock:  required to access data stored in a matrix_mdev
93  *
94  * Note: If @matrix_mdev is NULL or is not attached to a KVM guest, the KVM
95  *	 lock will not be taken.
96  */
97 static inline void get_update_locks_for_mdev(struct ap_matrix_mdev *matrix_mdev)
98 {
99 	mutex_lock(&matrix_dev->guests_lock);
100 	if (matrix_mdev && matrix_mdev->kvm)
101 		mutex_lock(&matrix_mdev->kvm->lock);
102 	mutex_lock(&matrix_dev->mdevs_lock);
103 }
104 
105 /**
106  * release_update_locks_for_mdev: Release the locks used to dynamically update a
107  *				  KVM guest's APCB in the proper order.
108  *
109  * @matrix_mdev: a pointer to a struct ap_matrix_mdev object containing the AP
110  *		 configuration data to use to update a KVM guest's APCB.
111  *
112  * The proper unlocking order is:
113  * 1. matrix_dev->mdevs_lock
114  * 2. matrix_mdev->kvm->lock
115  * 3. matrix_dev->guests_lock
116  *
117  * Note: If @matrix_mdev is NULL or is not attached to a KVM guest, the KVM
118  *	 lock will not be released.
119  */
120 static inline void release_update_locks_for_mdev(struct ap_matrix_mdev *matrix_mdev)
121 {
122 	mutex_unlock(&matrix_dev->mdevs_lock);
123 	if (matrix_mdev && matrix_mdev->kvm)
124 		mutex_unlock(&matrix_mdev->kvm->lock);
125 	mutex_unlock(&matrix_dev->guests_lock);
126 }
127 
128 /**
129  * get_update_locks_by_apqn: Find the mdev to which an APQN is assigned and
130  *			     acquire the locks required to update the APCB of
131  *			     the KVM guest to which the mdev is attached.
132  *
133  * @apqn: the APQN of a queue device.
134  *
135  * The proper locking order is:
136  * 1. matrix_dev->guests_lock: required to use the KVM pointer to update a KVM
137  *			       guest's APCB.
138  * 2. matrix_mdev->kvm->lock:  required to update a guest's APCB
139  * 3. matrix_dev->mdevs_lock:  required to access data stored in a matrix_mdev
140  *
141  * Note: If @apqn is not assigned to a matrix_mdev, the matrix_mdev->kvm->lock
142  *	 will not be taken.
143  *
144  * Return: the ap_matrix_mdev object to which @apqn is assigned or NULL if @apqn
145  *	   is not assigned to an ap_matrix_mdev.
146  */
147 static struct ap_matrix_mdev *get_update_locks_by_apqn(int apqn)
148 {
149 	struct ap_matrix_mdev *matrix_mdev;
150 
151 	mutex_lock(&matrix_dev->guests_lock);
152 
153 	list_for_each_entry(matrix_mdev, &matrix_dev->mdev_list, node) {
154 		if (test_bit_inv(AP_QID_CARD(apqn), matrix_mdev->matrix.apm) &&
155 		    test_bit_inv(AP_QID_QUEUE(apqn), matrix_mdev->matrix.aqm)) {
156 			if (matrix_mdev->kvm)
157 				mutex_lock(&matrix_mdev->kvm->lock);
158 
159 			mutex_lock(&matrix_dev->mdevs_lock);
160 
161 			return matrix_mdev;
162 		}
163 	}
164 
165 	mutex_lock(&matrix_dev->mdevs_lock);
166 
167 	return NULL;
168 }
169 
170 /**
171  * get_update_locks_for_queue: get the locks required to update the APCB of the
172  *			       KVM guest to which the matrix mdev linked to a
173  *			       vfio_ap_queue object is attached.
174  *
175  * @q: a pointer to a vfio_ap_queue object.
176  *
177  * The proper locking order is:
178  * 1. q->matrix_dev->guests_lock: required to use the KVM pointer to update a
179  *				  KVM guest's APCB.
180  * 2. q->matrix_mdev->kvm->lock:  required to update a guest's APCB
181  * 3. matrix_dev->mdevs_lock:	  required to access data stored in matrix_mdev
182  *
183  * Note: if @queue is not linked to an ap_matrix_mdev object, the KVM lock
184  *	  will not be taken.
185  */
186 static inline void get_update_locks_for_queue(struct vfio_ap_queue *q)
187 {
188 	mutex_lock(&matrix_dev->guests_lock);
189 	if (q->matrix_mdev && q->matrix_mdev->kvm)
190 		mutex_lock(&q->matrix_mdev->kvm->lock);
191 	mutex_lock(&matrix_dev->mdevs_lock);
192 }
193 
194 /**
195  * vfio_ap_mdev_get_queue - retrieve a queue with a specific APQN from a
196  *			    hash table of queues assigned to a matrix mdev
197  * @matrix_mdev: the matrix mdev
198  * @apqn: The APQN of a queue device
199  *
200  * Return: the pointer to the vfio_ap_queue struct representing the queue or
201  *	   NULL if the queue is not assigned to @matrix_mdev
202  */
203 static struct vfio_ap_queue *vfio_ap_mdev_get_queue(
204 					struct ap_matrix_mdev *matrix_mdev,
205 					int apqn)
206 {
207 	struct vfio_ap_queue *q;
208 
209 	hash_for_each_possible(matrix_mdev->qtable.queues, q, mdev_qnode,
210 			       apqn) {
211 		if (q && q->apqn == apqn)
212 			return q;
213 	}
214 
215 	return NULL;
216 }
217 
218 /**
219  * vfio_ap_wait_for_irqclear - clears the IR bit or gives up after 5 tries
220  * @apqn: The AP Queue number
221  *
222  * Checks the IRQ bit for the status of this APQN using ap_tapq.
223  * Returns if the ap_tapq function succeeded and the bit is clear.
224  * Returns if ap_tapq function failed with invalid, deconfigured or
225  * checkstopped AP.
226  * Otherwise retries up to 5 times after waiting 20ms.
227  */
228 static void vfio_ap_wait_for_irqclear(int apqn)
229 {
230 	struct ap_queue_status status;
231 	int retry = 5;
232 
233 	do {
234 		status = ap_tapq(apqn, NULL);
235 		switch (status.response_code) {
236 		case AP_RESPONSE_NORMAL:
237 		case AP_RESPONSE_RESET_IN_PROGRESS:
238 			if (!status.irq_enabled)
239 				return;
240 			fallthrough;
241 		case AP_RESPONSE_BUSY:
242 			msleep(20);
243 			break;
244 		case AP_RESPONSE_Q_NOT_AVAIL:
245 		case AP_RESPONSE_DECONFIGURED:
246 		case AP_RESPONSE_CHECKSTOPPED:
247 		default:
248 			WARN_ONCE(1, "%s: tapq rc %02x: %04x\n", __func__,
249 				  status.response_code, apqn);
250 			return;
251 		}
252 	} while (--retry);
253 
254 	WARN_ONCE(1, "%s: tapq rc %02x: %04x could not clear IR bit\n",
255 		  __func__, status.response_code, apqn);
256 }
257 
258 /**
259  * vfio_ap_free_aqic_resources - free vfio_ap_queue resources
260  * @q: The vfio_ap_queue
261  *
262  * Unregisters the ISC in the GIB when the saved ISC not invalid.
263  * Unpins the guest's page holding the NIB when it exists.
264  * Resets the saved_iova and saved_isc to invalid values.
265  */
266 static void vfio_ap_free_aqic_resources(struct vfio_ap_queue *q)
267 {
268 	if (!q)
269 		return;
270 	if (q->saved_isc != VFIO_AP_ISC_INVALID &&
271 	    !WARN_ON(!(q->matrix_mdev && q->matrix_mdev->kvm))) {
272 		kvm_s390_gisc_unregister(q->matrix_mdev->kvm, q->saved_isc);
273 		q->saved_isc = VFIO_AP_ISC_INVALID;
274 	}
275 	if (q->saved_iova && !WARN_ON(!q->matrix_mdev)) {
276 		vfio_unpin_pages(&q->matrix_mdev->vdev, q->saved_iova, 1);
277 		q->saved_iova = 0;
278 	}
279 }
280 
281 /**
282  * vfio_ap_irq_disable - disables and clears an ap_queue interrupt
283  * @q: The vfio_ap_queue
284  *
285  * Uses ap_aqic to disable the interruption and in case of success, reset
286  * in progress or IRQ disable command already proceeded: calls
287  * vfio_ap_wait_for_irqclear() to check for the IRQ bit to be clear
288  * and calls vfio_ap_free_aqic_resources() to free the resources associated
289  * with the AP interrupt handling.
290  *
291  * In the case the AP is busy, or a reset is in progress,
292  * retries after 20ms, up to 5 times.
293  *
294  * Returns if ap_aqic function failed with invalid, deconfigured or
295  * checkstopped AP.
296  *
297  * Return: &struct ap_queue_status
298  */
299 static struct ap_queue_status vfio_ap_irq_disable(struct vfio_ap_queue *q)
300 {
301 	struct ap_qirq_ctrl aqic_gisa = {};
302 	struct ap_queue_status status;
303 	int retries = 5;
304 
305 	do {
306 		status = ap_aqic(q->apqn, aqic_gisa, 0);
307 		switch (status.response_code) {
308 		case AP_RESPONSE_OTHERWISE_CHANGED:
309 		case AP_RESPONSE_NORMAL:
310 			vfio_ap_wait_for_irqclear(q->apqn);
311 			goto end_free;
312 		case AP_RESPONSE_RESET_IN_PROGRESS:
313 		case AP_RESPONSE_BUSY:
314 			msleep(20);
315 			break;
316 		case AP_RESPONSE_Q_NOT_AVAIL:
317 		case AP_RESPONSE_DECONFIGURED:
318 		case AP_RESPONSE_CHECKSTOPPED:
319 		case AP_RESPONSE_INVALID_ADDRESS:
320 		default:
321 			/* All cases in default means AP not operational */
322 			WARN_ONCE(1, "%s: ap_aqic status %d\n", __func__,
323 				  status.response_code);
324 			goto end_free;
325 		}
326 	} while (retries--);
327 
328 	WARN_ONCE(1, "%s: ap_aqic status %d\n", __func__,
329 		  status.response_code);
330 end_free:
331 	vfio_ap_free_aqic_resources(q);
332 	return status;
333 }
334 
335 /**
336  * vfio_ap_validate_nib - validate a notification indicator byte (nib) address.
337  *
338  * @vcpu: the object representing the vcpu executing the PQAP(AQIC) instruction.
339  * @nib: the location for storing the nib address.
340  *
341  * When the PQAP(AQIC) instruction is executed, general register 2 contains the
342  * address of the notification indicator byte (nib) used for IRQ notification.
343  * This function parses and validates the nib from gr2.
344  *
345  * Return: returns zero if the nib address is a valid; otherwise, returns
346  *	   -EINVAL.
347  */
348 static int vfio_ap_validate_nib(struct kvm_vcpu *vcpu, dma_addr_t *nib)
349 {
350 	*nib = vcpu->run->s.regs.gprs[2];
351 
352 	if (kvm_is_error_hva(gfn_to_hva(vcpu->kvm, *nib >> PAGE_SHIFT)))
353 		return -EINVAL;
354 
355 	return 0;
356 }
357 
358 /**
359  * vfio_ap_irq_enable - Enable Interruption for a APQN
360  *
361  * @q:	 the vfio_ap_queue holding AQIC parameters
362  * @isc: the guest ISC to register with the GIB interface
363  * @vcpu: the vcpu object containing the registers specifying the parameters
364  *	  passed to the PQAP(AQIC) instruction.
365  *
366  * Pin the NIB saved in *q
367  * Register the guest ISC to GIB interface and retrieve the
368  * host ISC to issue the host side PQAP/AQIC
369  *
370  * Response.status may be set to AP_RESPONSE_INVALID_ADDRESS in case the
371  * vfio_pin_pages failed.
372  *
373  * Otherwise return the ap_queue_status returned by the ap_aqic(),
374  * all retry handling will be done by the guest.
375  *
376  * Return: &struct ap_queue_status
377  */
378 static struct ap_queue_status vfio_ap_irq_enable(struct vfio_ap_queue *q,
379 						 int isc,
380 						 struct kvm_vcpu *vcpu)
381 {
382 	struct ap_qirq_ctrl aqic_gisa = {};
383 	struct ap_queue_status status = {};
384 	struct kvm_s390_gisa *gisa;
385 	struct page *h_page;
386 	int nisc;
387 	struct kvm *kvm;
388 	phys_addr_t h_nib;
389 	dma_addr_t nib;
390 	int ret;
391 
392 	/* Verify that the notification indicator byte address is valid */
393 	if (vfio_ap_validate_nib(vcpu, &nib)) {
394 		VFIO_AP_DBF_WARN("%s: invalid NIB address: nib=%pad, apqn=%#04x\n",
395 				 __func__, &nib, q->apqn);
396 
397 		status.response_code = AP_RESPONSE_INVALID_ADDRESS;
398 		return status;
399 	}
400 
401 	ret = vfio_pin_pages(&q->matrix_mdev->vdev, nib, 1,
402 			     IOMMU_READ | IOMMU_WRITE, &h_page);
403 	switch (ret) {
404 	case 1:
405 		break;
406 	default:
407 		VFIO_AP_DBF_WARN("%s: vfio_pin_pages failed: rc=%d,"
408 				 "nib=%pad, apqn=%#04x\n",
409 				 __func__, ret, &nib, q->apqn);
410 
411 		status.response_code = AP_RESPONSE_INVALID_ADDRESS;
412 		return status;
413 	}
414 
415 	kvm = q->matrix_mdev->kvm;
416 	gisa = kvm->arch.gisa_int.origin;
417 
418 	h_nib = page_to_phys(h_page) | (nib & ~PAGE_MASK);
419 	aqic_gisa.gisc = isc;
420 
421 	nisc = kvm_s390_gisc_register(kvm, isc);
422 	if (nisc < 0) {
423 		VFIO_AP_DBF_WARN("%s: gisc registration failed: nisc=%d, isc=%d, apqn=%#04x\n",
424 				 __func__, nisc, isc, q->apqn);
425 
426 		status.response_code = AP_RESPONSE_INVALID_GISA;
427 		return status;
428 	}
429 
430 	aqic_gisa.isc = nisc;
431 	aqic_gisa.ir = 1;
432 	aqic_gisa.gisa = (uint64_t)gisa >> 4;
433 
434 	status = ap_aqic(q->apqn, aqic_gisa, h_nib);
435 	switch (status.response_code) {
436 	case AP_RESPONSE_NORMAL:
437 		/* See if we did clear older IRQ configuration */
438 		vfio_ap_free_aqic_resources(q);
439 		q->saved_iova = nib;
440 		q->saved_isc = isc;
441 		break;
442 	case AP_RESPONSE_OTHERWISE_CHANGED:
443 		/* We could not modify IRQ setings: clear new configuration */
444 		vfio_unpin_pages(&q->matrix_mdev->vdev, nib, 1);
445 		kvm_s390_gisc_unregister(kvm, isc);
446 		break;
447 	default:
448 		pr_warn("%s: apqn %04x: response: %02x\n", __func__, q->apqn,
449 			status.response_code);
450 		vfio_ap_irq_disable(q);
451 		break;
452 	}
453 
454 	if (status.response_code != AP_RESPONSE_NORMAL) {
455 		VFIO_AP_DBF_WARN("%s: PQAP(AQIC) failed with status=%#02x: "
456 				 "zone=%#x, ir=%#x, gisc=%#x, f=%#x,"
457 				 "gisa=%#x, isc=%#x, apqn=%#04x\n",
458 				 __func__, status.response_code,
459 				 aqic_gisa.zone, aqic_gisa.ir, aqic_gisa.gisc,
460 				 aqic_gisa.gf, aqic_gisa.gisa, aqic_gisa.isc,
461 				 q->apqn);
462 	}
463 
464 	return status;
465 }
466 
467 /**
468  * vfio_ap_le_guid_to_be_uuid - convert a little endian guid array into an array
469  *				of big endian elements that can be passed by
470  *				value to an s390dbf sprintf event function to
471  *				format a UUID string.
472  *
473  * @guid: the object containing the little endian guid
474  * @uuid: a six-element array of long values that can be passed by value as
475  *	  arguments for a formatting string specifying a UUID.
476  *
477  * The S390 Debug Feature (s390dbf) allows the use of "%s" in the sprintf
478  * event functions if the memory for the passed string is available as long as
479  * the debug feature exists. Since a mediated device can be removed at any
480  * time, it's name can not be used because %s passes the reference to the string
481  * in memory and the reference will go stale once the device is removed .
482  *
483  * The s390dbf string formatting function allows a maximum of 9 arguments for a
484  * message to be displayed in the 'sprintf' view. In order to use the bytes
485  * comprising the mediated device's UUID to display the mediated device name,
486  * they will have to be converted into an array whose elements can be passed by
487  * value to sprintf. For example:
488  *
489  * guid array: { 83, 78, 17, 62, bb, f1, f0, 47, 91, 4d, 32, a2, 2e, 3a, 88, 04 }
490  * mdev name: 62177883-f1bb-47f0-914d-32a22e3a8804
491  * array returned: { 62177883, f1bb, 47f0, 914d, 32a2, 2e3a8804 }
492  * formatting string: "%08lx-%04lx-%04lx-%04lx-%02lx%04lx"
493  */
494 static void vfio_ap_le_guid_to_be_uuid(guid_t *guid, unsigned long *uuid)
495 {
496 	/*
497 	 * The input guid is ordered in little endian, so it needs to be
498 	 * reordered for displaying a UUID as a string. This specifies the
499 	 * guid indices in proper order.
500 	 */
501 	uuid[0] = le32_to_cpup((__le32 *)guid);
502 	uuid[1] = le16_to_cpup((__le16 *)&guid->b[4]);
503 	uuid[2] = le16_to_cpup((__le16 *)&guid->b[6]);
504 	uuid[3] = *((__u16 *)&guid->b[8]);
505 	uuid[4] = *((__u16 *)&guid->b[10]);
506 	uuid[5] = *((__u32 *)&guid->b[12]);
507 }
508 
509 /**
510  * handle_pqap - PQAP instruction callback
511  *
512  * @vcpu: The vcpu on which we received the PQAP instruction
513  *
514  * Get the general register contents to initialize internal variables.
515  * REG[0]: APQN
516  * REG[1]: IR and ISC
517  * REG[2]: NIB
518  *
519  * Response.status may be set to following Response Code:
520  * - AP_RESPONSE_Q_NOT_AVAIL: if the queue is not available
521  * - AP_RESPONSE_DECONFIGURED: if the queue is not configured
522  * - AP_RESPONSE_NORMAL (0) : in case of successs
523  *   Check vfio_ap_setirq() and vfio_ap_clrirq() for other possible RC.
524  * We take the matrix_dev lock to ensure serialization on queues and
525  * mediated device access.
526  *
527  * Return: 0 if we could handle the request inside KVM.
528  * Otherwise, returns -EOPNOTSUPP to let QEMU handle the fault.
529  */
530 static int handle_pqap(struct kvm_vcpu *vcpu)
531 {
532 	uint64_t status;
533 	uint16_t apqn;
534 	unsigned long uuid[6];
535 	struct vfio_ap_queue *q;
536 	struct ap_queue_status qstatus = {
537 			       .response_code = AP_RESPONSE_Q_NOT_AVAIL, };
538 	struct ap_matrix_mdev *matrix_mdev;
539 
540 	apqn = vcpu->run->s.regs.gprs[0] & 0xffff;
541 
542 	/* If we do not use the AIV facility just go to userland */
543 	if (!(vcpu->arch.sie_block->eca & ECA_AIV)) {
544 		VFIO_AP_DBF_WARN("%s: AIV facility not installed: apqn=0x%04x, eca=0x%04x\n",
545 				 __func__, apqn, vcpu->arch.sie_block->eca);
546 
547 		return -EOPNOTSUPP;
548 	}
549 
550 	mutex_lock(&matrix_dev->mdevs_lock);
551 
552 	if (!vcpu->kvm->arch.crypto.pqap_hook) {
553 		VFIO_AP_DBF_WARN("%s: PQAP(AQIC) hook not registered with the vfio_ap driver: apqn=0x%04x\n",
554 				 __func__, apqn);
555 
556 		goto out_unlock;
557 	}
558 
559 	matrix_mdev = container_of(vcpu->kvm->arch.crypto.pqap_hook,
560 				   struct ap_matrix_mdev, pqap_hook);
561 
562 	/* If the there is no guest using the mdev, there is nothing to do */
563 	if (!matrix_mdev->kvm) {
564 		vfio_ap_le_guid_to_be_uuid(&matrix_mdev->mdev->uuid, uuid);
565 		VFIO_AP_DBF_WARN("%s: mdev %08lx-%04lx-%04lx-%04lx-%04lx%08lx not in use: apqn=0x%04x\n",
566 				 __func__, uuid[0],  uuid[1], uuid[2],
567 				 uuid[3], uuid[4], uuid[5], apqn);
568 		goto out_unlock;
569 	}
570 
571 	q = vfio_ap_mdev_get_queue(matrix_mdev, apqn);
572 	if (!q) {
573 		VFIO_AP_DBF_WARN("%s: Queue %02x.%04x not bound to the vfio_ap driver\n",
574 				 __func__, AP_QID_CARD(apqn),
575 				 AP_QID_QUEUE(apqn));
576 		goto out_unlock;
577 	}
578 
579 	status = vcpu->run->s.regs.gprs[1];
580 
581 	/* If IR bit(16) is set we enable the interrupt */
582 	if ((status >> (63 - 16)) & 0x01)
583 		qstatus = vfio_ap_irq_enable(q, status & 0x07, vcpu);
584 	else
585 		qstatus = vfio_ap_irq_disable(q);
586 
587 out_unlock:
588 	memcpy(&vcpu->run->s.regs.gprs[1], &qstatus, sizeof(qstatus));
589 	vcpu->run->s.regs.gprs[1] >>= 32;
590 	mutex_unlock(&matrix_dev->mdevs_lock);
591 	return 0;
592 }
593 
594 static void vfio_ap_matrix_init(struct ap_config_info *info,
595 				struct ap_matrix *matrix)
596 {
597 	matrix->apm_max = info->apxa ? info->Na : 63;
598 	matrix->aqm_max = info->apxa ? info->Nd : 15;
599 	matrix->adm_max = info->apxa ? info->Nd : 15;
600 }
601 
602 static void vfio_ap_mdev_update_guest_apcb(struct ap_matrix_mdev *matrix_mdev)
603 {
604 	if (matrix_mdev->kvm)
605 		kvm_arch_crypto_set_masks(matrix_mdev->kvm,
606 					  matrix_mdev->shadow_apcb.apm,
607 					  matrix_mdev->shadow_apcb.aqm,
608 					  matrix_mdev->shadow_apcb.adm);
609 }
610 
611 static bool vfio_ap_mdev_filter_cdoms(struct ap_matrix_mdev *matrix_mdev)
612 {
613 	DECLARE_BITMAP(prev_shadow_adm, AP_DOMAINS);
614 
615 	bitmap_copy(prev_shadow_adm, matrix_mdev->shadow_apcb.adm, AP_DOMAINS);
616 	bitmap_and(matrix_mdev->shadow_apcb.adm, matrix_mdev->matrix.adm,
617 		   (unsigned long *)matrix_dev->info.adm, AP_DOMAINS);
618 
619 	return !bitmap_equal(prev_shadow_adm, matrix_mdev->shadow_apcb.adm,
620 			     AP_DOMAINS);
621 }
622 
623 /*
624  * vfio_ap_mdev_filter_matrix - filter the APQNs assigned to the matrix mdev
625  *				to ensure no queue devices are passed through to
626  *				the guest that are not bound to the vfio_ap
627  *				device driver.
628  *
629  * @matrix_mdev: the matrix mdev whose matrix is to be filtered.
630  *
631  * Note: If an APQN referencing a queue device that is not bound to the vfio_ap
632  *	 driver, its APID will be filtered from the guest's APCB. The matrix
633  *	 structure precludes filtering an individual APQN, so its APID will be
634  *	 filtered.
635  *
636  * Return: a boolean value indicating whether the KVM guest's APCB was changed
637  *	   by the filtering or not.
638  */
639 static bool vfio_ap_mdev_filter_matrix(unsigned long *apm, unsigned long *aqm,
640 				       struct ap_matrix_mdev *matrix_mdev)
641 {
642 	unsigned long apid, apqi, apqn;
643 	DECLARE_BITMAP(prev_shadow_apm, AP_DEVICES);
644 	DECLARE_BITMAP(prev_shadow_aqm, AP_DOMAINS);
645 	struct vfio_ap_queue *q;
646 
647 	bitmap_copy(prev_shadow_apm, matrix_mdev->shadow_apcb.apm, AP_DEVICES);
648 	bitmap_copy(prev_shadow_aqm, matrix_mdev->shadow_apcb.aqm, AP_DOMAINS);
649 	vfio_ap_matrix_init(&matrix_dev->info, &matrix_mdev->shadow_apcb);
650 
651 	/*
652 	 * Copy the adapters, domains and control domains to the shadow_apcb
653 	 * from the matrix mdev, but only those that are assigned to the host's
654 	 * AP configuration.
655 	 */
656 	bitmap_and(matrix_mdev->shadow_apcb.apm, matrix_mdev->matrix.apm,
657 		   (unsigned long *)matrix_dev->info.apm, AP_DEVICES);
658 	bitmap_and(matrix_mdev->shadow_apcb.aqm, matrix_mdev->matrix.aqm,
659 		   (unsigned long *)matrix_dev->info.aqm, AP_DOMAINS);
660 
661 	for_each_set_bit_inv(apid, apm, AP_DEVICES) {
662 		for_each_set_bit_inv(apqi, aqm, AP_DOMAINS) {
663 			/*
664 			 * If the APQN is not bound to the vfio_ap device
665 			 * driver, then we can't assign it to the guest's
666 			 * AP configuration. The AP architecture won't
667 			 * allow filtering of a single APQN, so let's filter
668 			 * the APID since an adapter represents a physical
669 			 * hardware device.
670 			 */
671 			apqn = AP_MKQID(apid, apqi);
672 			q = vfio_ap_mdev_get_queue(matrix_mdev, apqn);
673 			if (!q || q->reset_rc) {
674 				clear_bit_inv(apid,
675 					      matrix_mdev->shadow_apcb.apm);
676 				break;
677 			}
678 		}
679 	}
680 
681 	return !bitmap_equal(prev_shadow_apm, matrix_mdev->shadow_apcb.apm,
682 			     AP_DEVICES) ||
683 	       !bitmap_equal(prev_shadow_aqm, matrix_mdev->shadow_apcb.aqm,
684 			     AP_DOMAINS);
685 }
686 
687 static int vfio_ap_mdev_probe(struct mdev_device *mdev)
688 {
689 	struct ap_matrix_mdev *matrix_mdev;
690 	int ret;
691 
692 	if ((atomic_dec_if_positive(&matrix_dev->available_instances) < 0))
693 		return -EPERM;
694 
695 	matrix_mdev = kzalloc(sizeof(*matrix_mdev), GFP_KERNEL);
696 	if (!matrix_mdev) {
697 		ret = -ENOMEM;
698 		goto err_dec_available;
699 	}
700 	vfio_init_group_dev(&matrix_mdev->vdev, &mdev->dev,
701 			    &vfio_ap_matrix_dev_ops);
702 
703 	matrix_mdev->mdev = mdev;
704 	vfio_ap_matrix_init(&matrix_dev->info, &matrix_mdev->matrix);
705 	matrix_mdev->pqap_hook = handle_pqap;
706 	vfio_ap_matrix_init(&matrix_dev->info, &matrix_mdev->shadow_apcb);
707 	hash_init(matrix_mdev->qtable.queues);
708 
709 	ret = vfio_register_emulated_iommu_dev(&matrix_mdev->vdev);
710 	if (ret)
711 		goto err_list;
712 	dev_set_drvdata(&mdev->dev, matrix_mdev);
713 	mutex_lock(&matrix_dev->mdevs_lock);
714 	list_add(&matrix_mdev->node, &matrix_dev->mdev_list);
715 	mutex_unlock(&matrix_dev->mdevs_lock);
716 	return 0;
717 
718 err_list:
719 	vfio_uninit_group_dev(&matrix_mdev->vdev);
720 	kfree(matrix_mdev);
721 err_dec_available:
722 	atomic_inc(&matrix_dev->available_instances);
723 	return ret;
724 }
725 
726 static void vfio_ap_mdev_link_queue(struct ap_matrix_mdev *matrix_mdev,
727 				    struct vfio_ap_queue *q)
728 {
729 	if (q) {
730 		q->matrix_mdev = matrix_mdev;
731 		hash_add(matrix_mdev->qtable.queues, &q->mdev_qnode, q->apqn);
732 	}
733 }
734 
735 static void vfio_ap_mdev_link_apqn(struct ap_matrix_mdev *matrix_mdev, int apqn)
736 {
737 	struct vfio_ap_queue *q;
738 
739 	q = vfio_ap_find_queue(apqn);
740 	vfio_ap_mdev_link_queue(matrix_mdev, q);
741 }
742 
743 static void vfio_ap_unlink_queue_fr_mdev(struct vfio_ap_queue *q)
744 {
745 	hash_del(&q->mdev_qnode);
746 }
747 
748 static void vfio_ap_unlink_mdev_fr_queue(struct vfio_ap_queue *q)
749 {
750 	q->matrix_mdev = NULL;
751 }
752 
753 static void vfio_ap_mdev_unlink_fr_queues(struct ap_matrix_mdev *matrix_mdev)
754 {
755 	struct vfio_ap_queue *q;
756 	unsigned long apid, apqi;
757 
758 	for_each_set_bit_inv(apid, matrix_mdev->matrix.apm, AP_DEVICES) {
759 		for_each_set_bit_inv(apqi, matrix_mdev->matrix.aqm,
760 				     AP_DOMAINS) {
761 			q = vfio_ap_mdev_get_queue(matrix_mdev,
762 						   AP_MKQID(apid, apqi));
763 			if (q)
764 				q->matrix_mdev = NULL;
765 		}
766 	}
767 }
768 
769 static void vfio_ap_mdev_remove(struct mdev_device *mdev)
770 {
771 	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(&mdev->dev);
772 
773 	vfio_unregister_group_dev(&matrix_mdev->vdev);
774 
775 	mutex_lock(&matrix_dev->guests_lock);
776 	mutex_lock(&matrix_dev->mdevs_lock);
777 	vfio_ap_mdev_reset_queues(&matrix_mdev->qtable);
778 	vfio_ap_mdev_unlink_fr_queues(matrix_mdev);
779 	list_del(&matrix_mdev->node);
780 	mutex_unlock(&matrix_dev->mdevs_lock);
781 	mutex_unlock(&matrix_dev->guests_lock);
782 	vfio_uninit_group_dev(&matrix_mdev->vdev);
783 	kfree(matrix_mdev);
784 	atomic_inc(&matrix_dev->available_instances);
785 }
786 
787 static ssize_t name_show(struct mdev_type *mtype,
788 			 struct mdev_type_attribute *attr, char *buf)
789 {
790 	return sprintf(buf, "%s\n", VFIO_AP_MDEV_NAME_HWVIRT);
791 }
792 
793 static MDEV_TYPE_ATTR_RO(name);
794 
795 static ssize_t available_instances_show(struct mdev_type *mtype,
796 					struct mdev_type_attribute *attr,
797 					char *buf)
798 {
799 	return sprintf(buf, "%d\n",
800 		       atomic_read(&matrix_dev->available_instances));
801 }
802 
803 static MDEV_TYPE_ATTR_RO(available_instances);
804 
805 static ssize_t device_api_show(struct mdev_type *mtype,
806 			       struct mdev_type_attribute *attr, char *buf)
807 {
808 	return sprintf(buf, "%s\n", VFIO_DEVICE_API_AP_STRING);
809 }
810 
811 static MDEV_TYPE_ATTR_RO(device_api);
812 
813 static struct attribute *vfio_ap_mdev_type_attrs[] = {
814 	&mdev_type_attr_name.attr,
815 	&mdev_type_attr_device_api.attr,
816 	&mdev_type_attr_available_instances.attr,
817 	NULL,
818 };
819 
820 static struct attribute_group vfio_ap_mdev_hwvirt_type_group = {
821 	.name = VFIO_AP_MDEV_TYPE_HWVIRT,
822 	.attrs = vfio_ap_mdev_type_attrs,
823 };
824 
825 static struct attribute_group *vfio_ap_mdev_type_groups[] = {
826 	&vfio_ap_mdev_hwvirt_type_group,
827 	NULL,
828 };
829 
830 #define MDEV_SHARING_ERR "Userspace may not re-assign queue %02lx.%04lx " \
831 			 "already assigned to %s"
832 
833 static void vfio_ap_mdev_log_sharing_err(struct ap_matrix_mdev *matrix_mdev,
834 					 unsigned long *apm,
835 					 unsigned long *aqm)
836 {
837 	unsigned long apid, apqi;
838 	const struct device *dev = mdev_dev(matrix_mdev->mdev);
839 	const char *mdev_name = dev_name(dev);
840 
841 	for_each_set_bit_inv(apid, apm, AP_DEVICES)
842 		for_each_set_bit_inv(apqi, aqm, AP_DOMAINS)
843 			dev_warn(dev, MDEV_SHARING_ERR, apid, apqi, mdev_name);
844 }
845 
846 /**
847  * vfio_ap_mdev_verify_no_sharing - verify APQNs are not shared by matrix mdevs
848  *
849  * @mdev_apm: mask indicating the APIDs of the APQNs to be verified
850  * @mdev_aqm: mask indicating the APQIs of the APQNs to be verified
851  *
852  * Verifies that each APQN derived from the Cartesian product of a bitmap of
853  * AP adapter IDs and AP queue indexes is not configured for any matrix
854  * mediated device. AP queue sharing is not allowed.
855  *
856  * Return: 0 if the APQNs are not shared; otherwise return -EADDRINUSE.
857  */
858 static int vfio_ap_mdev_verify_no_sharing(unsigned long *mdev_apm,
859 					  unsigned long *mdev_aqm)
860 {
861 	struct ap_matrix_mdev *matrix_mdev;
862 	DECLARE_BITMAP(apm, AP_DEVICES);
863 	DECLARE_BITMAP(aqm, AP_DOMAINS);
864 
865 	list_for_each_entry(matrix_mdev, &matrix_dev->mdev_list, node) {
866 		/*
867 		 * If the input apm and aqm are fields of the matrix_mdev
868 		 * object, then move on to the next matrix_mdev.
869 		 */
870 		if (mdev_apm == matrix_mdev->matrix.apm &&
871 		    mdev_aqm == matrix_mdev->matrix.aqm)
872 			continue;
873 
874 		memset(apm, 0, sizeof(apm));
875 		memset(aqm, 0, sizeof(aqm));
876 
877 		/*
878 		 * We work on full longs, as we can only exclude the leftover
879 		 * bits in non-inverse order. The leftover is all zeros.
880 		 */
881 		if (!bitmap_and(apm, mdev_apm, matrix_mdev->matrix.apm,
882 				AP_DEVICES))
883 			continue;
884 
885 		if (!bitmap_and(aqm, mdev_aqm, matrix_mdev->matrix.aqm,
886 				AP_DOMAINS))
887 			continue;
888 
889 		vfio_ap_mdev_log_sharing_err(matrix_mdev, apm, aqm);
890 
891 		return -EADDRINUSE;
892 	}
893 
894 	return 0;
895 }
896 
897 /**
898  * vfio_ap_mdev_validate_masks - verify that the APQNs assigned to the mdev are
899  *				 not reserved for the default zcrypt driver and
900  *				 are not assigned to another mdev.
901  *
902  * @matrix_mdev: the mdev to which the APQNs being validated are assigned.
903  *
904  * Return: One of the following values:
905  * o the error returned from the ap_apqn_in_matrix_owned_by_def_drv() function,
906  *   most likely -EBUSY indicating the ap_perms_mutex lock is already held.
907  * o EADDRNOTAVAIL if an APQN assigned to @matrix_mdev is reserved for the
908  *		   zcrypt default driver.
909  * o EADDRINUSE if an APQN assigned to @matrix_mdev is assigned to another mdev
910  * o A zero indicating validation succeeded.
911  */
912 static int vfio_ap_mdev_validate_masks(struct ap_matrix_mdev *matrix_mdev)
913 {
914 	if (ap_apqn_in_matrix_owned_by_def_drv(matrix_mdev->matrix.apm,
915 					       matrix_mdev->matrix.aqm))
916 		return -EADDRNOTAVAIL;
917 
918 	return vfio_ap_mdev_verify_no_sharing(matrix_mdev->matrix.apm,
919 					      matrix_mdev->matrix.aqm);
920 }
921 
922 static void vfio_ap_mdev_link_adapter(struct ap_matrix_mdev *matrix_mdev,
923 				      unsigned long apid)
924 {
925 	unsigned long apqi;
926 
927 	for_each_set_bit_inv(apqi, matrix_mdev->matrix.aqm, AP_DOMAINS)
928 		vfio_ap_mdev_link_apqn(matrix_mdev,
929 				       AP_MKQID(apid, apqi));
930 }
931 
932 /**
933  * assign_adapter_store - parses the APID from @buf and sets the
934  * corresponding bit in the mediated matrix device's APM
935  *
936  * @dev:	the matrix device
937  * @attr:	the mediated matrix device's assign_adapter attribute
938  * @buf:	a buffer containing the AP adapter number (APID) to
939  *		be assigned
940  * @count:	the number of bytes in @buf
941  *
942  * Return: the number of bytes processed if the APID is valid; otherwise,
943  * returns one of the following errors:
944  *
945  *	1. -EINVAL
946  *	   The APID is not a valid number
947  *
948  *	2. -ENODEV
949  *	   The APID exceeds the maximum value configured for the system
950  *
951  *	3. -EADDRNOTAVAIL
952  *	   An APQN derived from the cross product of the APID being assigned
953  *	   and the APQIs previously assigned is not bound to the vfio_ap device
954  *	   driver; or, if no APQIs have yet been assigned, the APID is not
955  *	   contained in an APQN bound to the vfio_ap device driver.
956  *
957  *	4. -EADDRINUSE
958  *	   An APQN derived from the cross product of the APID being assigned
959  *	   and the APQIs previously assigned is being used by another mediated
960  *	   matrix device
961  *
962  *	5. -EAGAIN
963  *	   A lock required to validate the mdev's AP configuration could not
964  *	   be obtained.
965  */
966 static ssize_t assign_adapter_store(struct device *dev,
967 				    struct device_attribute *attr,
968 				    const char *buf, size_t count)
969 {
970 	int ret;
971 	unsigned long apid;
972 	DECLARE_BITMAP(apm_delta, AP_DEVICES);
973 	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
974 
975 	mutex_lock(&ap_perms_mutex);
976 	get_update_locks_for_mdev(matrix_mdev);
977 
978 	ret = kstrtoul(buf, 0, &apid);
979 	if (ret)
980 		goto done;
981 
982 	if (apid > matrix_mdev->matrix.apm_max) {
983 		ret = -ENODEV;
984 		goto done;
985 	}
986 
987 	if (test_bit_inv(apid, matrix_mdev->matrix.apm)) {
988 		ret = count;
989 		goto done;
990 	}
991 
992 	set_bit_inv(apid, matrix_mdev->matrix.apm);
993 
994 	ret = vfio_ap_mdev_validate_masks(matrix_mdev);
995 	if (ret) {
996 		clear_bit_inv(apid, matrix_mdev->matrix.apm);
997 		goto done;
998 	}
999 
1000 	vfio_ap_mdev_link_adapter(matrix_mdev, apid);
1001 	memset(apm_delta, 0, sizeof(apm_delta));
1002 	set_bit_inv(apid, apm_delta);
1003 
1004 	if (vfio_ap_mdev_filter_matrix(apm_delta,
1005 				       matrix_mdev->matrix.aqm, matrix_mdev))
1006 		vfio_ap_mdev_update_guest_apcb(matrix_mdev);
1007 
1008 	ret = count;
1009 done:
1010 	release_update_locks_for_mdev(matrix_mdev);
1011 	mutex_unlock(&ap_perms_mutex);
1012 
1013 	return ret;
1014 }
1015 static DEVICE_ATTR_WO(assign_adapter);
1016 
1017 static struct vfio_ap_queue
1018 *vfio_ap_unlink_apqn_fr_mdev(struct ap_matrix_mdev *matrix_mdev,
1019 			     unsigned long apid, unsigned long apqi)
1020 {
1021 	struct vfio_ap_queue *q = NULL;
1022 
1023 	q = vfio_ap_mdev_get_queue(matrix_mdev, AP_MKQID(apid, apqi));
1024 	/* If the queue is assigned to the matrix mdev, unlink it. */
1025 	if (q)
1026 		vfio_ap_unlink_queue_fr_mdev(q);
1027 
1028 	return q;
1029 }
1030 
1031 /**
1032  * vfio_ap_mdev_unlink_adapter - unlink all queues associated with unassigned
1033  *				 adapter from the matrix mdev to which the
1034  *				 adapter was assigned.
1035  * @matrix_mdev: the matrix mediated device to which the adapter was assigned.
1036  * @apid: the APID of the unassigned adapter.
1037  * @qtable: table for storing queues associated with unassigned adapter.
1038  */
1039 static void vfio_ap_mdev_unlink_adapter(struct ap_matrix_mdev *matrix_mdev,
1040 					unsigned long apid,
1041 					struct ap_queue_table *qtable)
1042 {
1043 	unsigned long apqi;
1044 	struct vfio_ap_queue *q;
1045 
1046 	for_each_set_bit_inv(apqi, matrix_mdev->matrix.aqm, AP_DOMAINS) {
1047 		q = vfio_ap_unlink_apqn_fr_mdev(matrix_mdev, apid, apqi);
1048 
1049 		if (q && qtable) {
1050 			if (test_bit_inv(apid, matrix_mdev->shadow_apcb.apm) &&
1051 			    test_bit_inv(apqi, matrix_mdev->shadow_apcb.aqm))
1052 				hash_add(qtable->queues, &q->mdev_qnode,
1053 					 q->apqn);
1054 		}
1055 	}
1056 }
1057 
1058 static void vfio_ap_mdev_hot_unplug_adapter(struct ap_matrix_mdev *matrix_mdev,
1059 					    unsigned long apid)
1060 {
1061 	int loop_cursor;
1062 	struct vfio_ap_queue *q;
1063 	struct ap_queue_table *qtable = kzalloc(sizeof(*qtable), GFP_KERNEL);
1064 
1065 	hash_init(qtable->queues);
1066 	vfio_ap_mdev_unlink_adapter(matrix_mdev, apid, qtable);
1067 
1068 	if (test_bit_inv(apid, matrix_mdev->shadow_apcb.apm)) {
1069 		clear_bit_inv(apid, matrix_mdev->shadow_apcb.apm);
1070 		vfio_ap_mdev_update_guest_apcb(matrix_mdev);
1071 	}
1072 
1073 	vfio_ap_mdev_reset_queues(qtable);
1074 
1075 	hash_for_each(qtable->queues, loop_cursor, q, mdev_qnode) {
1076 		vfio_ap_unlink_mdev_fr_queue(q);
1077 		hash_del(&q->mdev_qnode);
1078 	}
1079 
1080 	kfree(qtable);
1081 }
1082 
1083 /**
1084  * unassign_adapter_store - parses the APID from @buf and clears the
1085  * corresponding bit in the mediated matrix device's APM
1086  *
1087  * @dev:	the matrix device
1088  * @attr:	the mediated matrix device's unassign_adapter attribute
1089  * @buf:	a buffer containing the adapter number (APID) to be unassigned
1090  * @count:	the number of bytes in @buf
1091  *
1092  * Return: the number of bytes processed if the APID is valid; otherwise,
1093  * returns one of the following errors:
1094  *	-EINVAL if the APID is not a number
1095  *	-ENODEV if the APID it exceeds the maximum value configured for the
1096  *		system
1097  */
1098 static ssize_t unassign_adapter_store(struct device *dev,
1099 				      struct device_attribute *attr,
1100 				      const char *buf, size_t count)
1101 {
1102 	int ret;
1103 	unsigned long apid;
1104 	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
1105 
1106 	get_update_locks_for_mdev(matrix_mdev);
1107 
1108 	ret = kstrtoul(buf, 0, &apid);
1109 	if (ret)
1110 		goto done;
1111 
1112 	if (apid > matrix_mdev->matrix.apm_max) {
1113 		ret = -ENODEV;
1114 		goto done;
1115 	}
1116 
1117 	if (!test_bit_inv(apid, matrix_mdev->matrix.apm)) {
1118 		ret = count;
1119 		goto done;
1120 	}
1121 
1122 	clear_bit_inv((unsigned long)apid, matrix_mdev->matrix.apm);
1123 	vfio_ap_mdev_hot_unplug_adapter(matrix_mdev, apid);
1124 	ret = count;
1125 done:
1126 	release_update_locks_for_mdev(matrix_mdev);
1127 	return ret;
1128 }
1129 static DEVICE_ATTR_WO(unassign_adapter);
1130 
1131 static void vfio_ap_mdev_link_domain(struct ap_matrix_mdev *matrix_mdev,
1132 				     unsigned long apqi)
1133 {
1134 	unsigned long apid;
1135 
1136 	for_each_set_bit_inv(apid, matrix_mdev->matrix.apm, AP_DEVICES)
1137 		vfio_ap_mdev_link_apqn(matrix_mdev,
1138 				       AP_MKQID(apid, apqi));
1139 }
1140 
1141 /**
1142  * assign_domain_store - parses the APQI from @buf and sets the
1143  * corresponding bit in the mediated matrix device's AQM
1144  *
1145  * @dev:	the matrix device
1146  * @attr:	the mediated matrix device's assign_domain attribute
1147  * @buf:	a buffer containing the AP queue index (APQI) of the domain to
1148  *		be assigned
1149  * @count:	the number of bytes in @buf
1150  *
1151  * Return: the number of bytes processed if the APQI is valid; otherwise returns
1152  * one of the following errors:
1153  *
1154  *	1. -EINVAL
1155  *	   The APQI is not a valid number
1156  *
1157  *	2. -ENODEV
1158  *	   The APQI exceeds the maximum value configured for the system
1159  *
1160  *	3. -EADDRNOTAVAIL
1161  *	   An APQN derived from the cross product of the APQI being assigned
1162  *	   and the APIDs previously assigned is not bound to the vfio_ap device
1163  *	   driver; or, if no APIDs have yet been assigned, the APQI is not
1164  *	   contained in an APQN bound to the vfio_ap device driver.
1165  *
1166  *	4. -EADDRINUSE
1167  *	   An APQN derived from the cross product of the APQI being assigned
1168  *	   and the APIDs previously assigned is being used by another mediated
1169  *	   matrix device
1170  *
1171  *	5. -EAGAIN
1172  *	   The lock required to validate the mdev's AP configuration could not
1173  *	   be obtained.
1174  */
1175 static ssize_t assign_domain_store(struct device *dev,
1176 				   struct device_attribute *attr,
1177 				   const char *buf, size_t count)
1178 {
1179 	int ret;
1180 	unsigned long apqi;
1181 	DECLARE_BITMAP(aqm_delta, AP_DOMAINS);
1182 	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
1183 
1184 	mutex_lock(&ap_perms_mutex);
1185 	get_update_locks_for_mdev(matrix_mdev);
1186 
1187 	ret = kstrtoul(buf, 0, &apqi);
1188 	if (ret)
1189 		goto done;
1190 
1191 	if (apqi > matrix_mdev->matrix.aqm_max) {
1192 		ret = -ENODEV;
1193 		goto done;
1194 	}
1195 
1196 	if (test_bit_inv(apqi, matrix_mdev->matrix.aqm)) {
1197 		ret = count;
1198 		goto done;
1199 	}
1200 
1201 	set_bit_inv(apqi, matrix_mdev->matrix.aqm);
1202 
1203 	ret = vfio_ap_mdev_validate_masks(matrix_mdev);
1204 	if (ret) {
1205 		clear_bit_inv(apqi, matrix_mdev->matrix.aqm);
1206 		goto done;
1207 	}
1208 
1209 	vfio_ap_mdev_link_domain(matrix_mdev, apqi);
1210 	memset(aqm_delta, 0, sizeof(aqm_delta));
1211 	set_bit_inv(apqi, aqm_delta);
1212 
1213 	if (vfio_ap_mdev_filter_matrix(matrix_mdev->matrix.apm, aqm_delta,
1214 				       matrix_mdev))
1215 		vfio_ap_mdev_update_guest_apcb(matrix_mdev);
1216 
1217 	ret = count;
1218 done:
1219 	release_update_locks_for_mdev(matrix_mdev);
1220 	mutex_unlock(&ap_perms_mutex);
1221 
1222 	return ret;
1223 }
1224 static DEVICE_ATTR_WO(assign_domain);
1225 
1226 static void vfio_ap_mdev_unlink_domain(struct ap_matrix_mdev *matrix_mdev,
1227 				       unsigned long apqi,
1228 				       struct ap_queue_table *qtable)
1229 {
1230 	unsigned long apid;
1231 	struct vfio_ap_queue *q;
1232 
1233 	for_each_set_bit_inv(apid, matrix_mdev->matrix.apm, AP_DEVICES) {
1234 		q = vfio_ap_unlink_apqn_fr_mdev(matrix_mdev, apid, apqi);
1235 
1236 		if (q && qtable) {
1237 			if (test_bit_inv(apid, matrix_mdev->shadow_apcb.apm) &&
1238 			    test_bit_inv(apqi, matrix_mdev->shadow_apcb.aqm))
1239 				hash_add(qtable->queues, &q->mdev_qnode,
1240 					 q->apqn);
1241 		}
1242 	}
1243 }
1244 
1245 static void vfio_ap_mdev_hot_unplug_domain(struct ap_matrix_mdev *matrix_mdev,
1246 					   unsigned long apqi)
1247 {
1248 	int loop_cursor;
1249 	struct vfio_ap_queue *q;
1250 	struct ap_queue_table *qtable = kzalloc(sizeof(*qtable), GFP_KERNEL);
1251 
1252 	hash_init(qtable->queues);
1253 	vfio_ap_mdev_unlink_domain(matrix_mdev, apqi, qtable);
1254 
1255 	if (test_bit_inv(apqi, matrix_mdev->shadow_apcb.aqm)) {
1256 		clear_bit_inv(apqi, matrix_mdev->shadow_apcb.aqm);
1257 		vfio_ap_mdev_update_guest_apcb(matrix_mdev);
1258 	}
1259 
1260 	vfio_ap_mdev_reset_queues(qtable);
1261 
1262 	hash_for_each(qtable->queues, loop_cursor, q, mdev_qnode) {
1263 		vfio_ap_unlink_mdev_fr_queue(q);
1264 		hash_del(&q->mdev_qnode);
1265 	}
1266 
1267 	kfree(qtable);
1268 }
1269 
1270 /**
1271  * unassign_domain_store - parses the APQI from @buf and clears the
1272  * corresponding bit in the mediated matrix device's AQM
1273  *
1274  * @dev:	the matrix device
1275  * @attr:	the mediated matrix device's unassign_domain attribute
1276  * @buf:	a buffer containing the AP queue index (APQI) of the domain to
1277  *		be unassigned
1278  * @count:	the number of bytes in @buf
1279  *
1280  * Return: the number of bytes processed if the APQI is valid; otherwise,
1281  * returns one of the following errors:
1282  *	-EINVAL if the APQI is not a number
1283  *	-ENODEV if the APQI exceeds the maximum value configured for the system
1284  */
1285 static ssize_t unassign_domain_store(struct device *dev,
1286 				     struct device_attribute *attr,
1287 				     const char *buf, size_t count)
1288 {
1289 	int ret;
1290 	unsigned long apqi;
1291 	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
1292 
1293 	get_update_locks_for_mdev(matrix_mdev);
1294 
1295 	ret = kstrtoul(buf, 0, &apqi);
1296 	if (ret)
1297 		goto done;
1298 
1299 	if (apqi > matrix_mdev->matrix.aqm_max) {
1300 		ret = -ENODEV;
1301 		goto done;
1302 	}
1303 
1304 	if (!test_bit_inv(apqi, matrix_mdev->matrix.aqm)) {
1305 		ret = count;
1306 		goto done;
1307 	}
1308 
1309 	clear_bit_inv((unsigned long)apqi, matrix_mdev->matrix.aqm);
1310 	vfio_ap_mdev_hot_unplug_domain(matrix_mdev, apqi);
1311 	ret = count;
1312 
1313 done:
1314 	release_update_locks_for_mdev(matrix_mdev);
1315 	return ret;
1316 }
1317 static DEVICE_ATTR_WO(unassign_domain);
1318 
1319 /**
1320  * assign_control_domain_store - parses the domain ID from @buf and sets
1321  * the corresponding bit in the mediated matrix device's ADM
1322  *
1323  * @dev:	the matrix device
1324  * @attr:	the mediated matrix device's assign_control_domain attribute
1325  * @buf:	a buffer containing the domain ID to be assigned
1326  * @count:	the number of bytes in @buf
1327  *
1328  * Return: the number of bytes processed if the domain ID is valid; otherwise,
1329  * returns one of the following errors:
1330  *	-EINVAL if the ID is not a number
1331  *	-ENODEV if the ID exceeds the maximum value configured for the system
1332  */
1333 static ssize_t assign_control_domain_store(struct device *dev,
1334 					   struct device_attribute *attr,
1335 					   const char *buf, size_t count)
1336 {
1337 	int ret;
1338 	unsigned long id;
1339 	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
1340 
1341 	get_update_locks_for_mdev(matrix_mdev);
1342 
1343 	ret = kstrtoul(buf, 0, &id);
1344 	if (ret)
1345 		goto done;
1346 
1347 	if (id > matrix_mdev->matrix.adm_max) {
1348 		ret = -ENODEV;
1349 		goto done;
1350 	}
1351 
1352 	if (test_bit_inv(id, matrix_mdev->matrix.adm)) {
1353 		ret = count;
1354 		goto done;
1355 	}
1356 
1357 	/* Set the bit in the ADM (bitmask) corresponding to the AP control
1358 	 * domain number (id). The bits in the mask, from most significant to
1359 	 * least significant, correspond to IDs 0 up to the one less than the
1360 	 * number of control domains that can be assigned.
1361 	 */
1362 	set_bit_inv(id, matrix_mdev->matrix.adm);
1363 	if (vfio_ap_mdev_filter_cdoms(matrix_mdev))
1364 		vfio_ap_mdev_update_guest_apcb(matrix_mdev);
1365 
1366 	ret = count;
1367 done:
1368 	release_update_locks_for_mdev(matrix_mdev);
1369 	return ret;
1370 }
1371 static DEVICE_ATTR_WO(assign_control_domain);
1372 
1373 /**
1374  * unassign_control_domain_store - parses the domain ID from @buf and
1375  * clears the corresponding bit in the mediated matrix device's ADM
1376  *
1377  * @dev:	the matrix device
1378  * @attr:	the mediated matrix device's unassign_control_domain attribute
1379  * @buf:	a buffer containing the domain ID to be unassigned
1380  * @count:	the number of bytes in @buf
1381  *
1382  * Return: the number of bytes processed if the domain ID is valid; otherwise,
1383  * returns one of the following errors:
1384  *	-EINVAL if the ID is not a number
1385  *	-ENODEV if the ID exceeds the maximum value configured for the system
1386  */
1387 static ssize_t unassign_control_domain_store(struct device *dev,
1388 					     struct device_attribute *attr,
1389 					     const char *buf, size_t count)
1390 {
1391 	int ret;
1392 	unsigned long domid;
1393 	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
1394 
1395 	get_update_locks_for_mdev(matrix_mdev);
1396 
1397 	ret = kstrtoul(buf, 0, &domid);
1398 	if (ret)
1399 		goto done;
1400 
1401 	if (domid > matrix_mdev->matrix.adm_max) {
1402 		ret = -ENODEV;
1403 		goto done;
1404 	}
1405 
1406 	if (!test_bit_inv(domid, matrix_mdev->matrix.adm)) {
1407 		ret = count;
1408 		goto done;
1409 	}
1410 
1411 	clear_bit_inv(domid, matrix_mdev->matrix.adm);
1412 
1413 	if (test_bit_inv(domid, matrix_mdev->shadow_apcb.adm)) {
1414 		clear_bit_inv(domid, matrix_mdev->shadow_apcb.adm);
1415 		vfio_ap_mdev_update_guest_apcb(matrix_mdev);
1416 	}
1417 
1418 	ret = count;
1419 done:
1420 	release_update_locks_for_mdev(matrix_mdev);
1421 	return ret;
1422 }
1423 static DEVICE_ATTR_WO(unassign_control_domain);
1424 
1425 static ssize_t control_domains_show(struct device *dev,
1426 				    struct device_attribute *dev_attr,
1427 				    char *buf)
1428 {
1429 	unsigned long id;
1430 	int nchars = 0;
1431 	int n;
1432 	char *bufpos = buf;
1433 	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
1434 	unsigned long max_domid = matrix_mdev->matrix.adm_max;
1435 
1436 	mutex_lock(&matrix_dev->mdevs_lock);
1437 	for_each_set_bit_inv(id, matrix_mdev->matrix.adm, max_domid + 1) {
1438 		n = sprintf(bufpos, "%04lx\n", id);
1439 		bufpos += n;
1440 		nchars += n;
1441 	}
1442 	mutex_unlock(&matrix_dev->mdevs_lock);
1443 
1444 	return nchars;
1445 }
1446 static DEVICE_ATTR_RO(control_domains);
1447 
1448 static ssize_t vfio_ap_mdev_matrix_show(struct ap_matrix *matrix, char *buf)
1449 {
1450 	char *bufpos = buf;
1451 	unsigned long apid;
1452 	unsigned long apqi;
1453 	unsigned long apid1;
1454 	unsigned long apqi1;
1455 	unsigned long napm_bits = matrix->apm_max + 1;
1456 	unsigned long naqm_bits = matrix->aqm_max + 1;
1457 	int nchars = 0;
1458 	int n;
1459 
1460 	apid1 = find_first_bit_inv(matrix->apm, napm_bits);
1461 	apqi1 = find_first_bit_inv(matrix->aqm, naqm_bits);
1462 
1463 	if ((apid1 < napm_bits) && (apqi1 < naqm_bits)) {
1464 		for_each_set_bit_inv(apid, matrix->apm, napm_bits) {
1465 			for_each_set_bit_inv(apqi, matrix->aqm,
1466 					     naqm_bits) {
1467 				n = sprintf(bufpos, "%02lx.%04lx\n", apid,
1468 					    apqi);
1469 				bufpos += n;
1470 				nchars += n;
1471 			}
1472 		}
1473 	} else if (apid1 < napm_bits) {
1474 		for_each_set_bit_inv(apid, matrix->apm, napm_bits) {
1475 			n = sprintf(bufpos, "%02lx.\n", apid);
1476 			bufpos += n;
1477 			nchars += n;
1478 		}
1479 	} else if (apqi1 < naqm_bits) {
1480 		for_each_set_bit_inv(apqi, matrix->aqm, naqm_bits) {
1481 			n = sprintf(bufpos, ".%04lx\n", apqi);
1482 			bufpos += n;
1483 			nchars += n;
1484 		}
1485 	}
1486 
1487 	return nchars;
1488 }
1489 
1490 static ssize_t matrix_show(struct device *dev, struct device_attribute *attr,
1491 			   char *buf)
1492 {
1493 	ssize_t nchars;
1494 	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
1495 
1496 	mutex_lock(&matrix_dev->mdevs_lock);
1497 	nchars = vfio_ap_mdev_matrix_show(&matrix_mdev->matrix, buf);
1498 	mutex_unlock(&matrix_dev->mdevs_lock);
1499 
1500 	return nchars;
1501 }
1502 static DEVICE_ATTR_RO(matrix);
1503 
1504 static ssize_t guest_matrix_show(struct device *dev,
1505 				 struct device_attribute *attr, char *buf)
1506 {
1507 	ssize_t nchars;
1508 	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
1509 
1510 	mutex_lock(&matrix_dev->mdevs_lock);
1511 	nchars = vfio_ap_mdev_matrix_show(&matrix_mdev->shadow_apcb, buf);
1512 	mutex_unlock(&matrix_dev->mdevs_lock);
1513 
1514 	return nchars;
1515 }
1516 static DEVICE_ATTR_RO(guest_matrix);
1517 
1518 static struct attribute *vfio_ap_mdev_attrs[] = {
1519 	&dev_attr_assign_adapter.attr,
1520 	&dev_attr_unassign_adapter.attr,
1521 	&dev_attr_assign_domain.attr,
1522 	&dev_attr_unassign_domain.attr,
1523 	&dev_attr_assign_control_domain.attr,
1524 	&dev_attr_unassign_control_domain.attr,
1525 	&dev_attr_control_domains.attr,
1526 	&dev_attr_matrix.attr,
1527 	&dev_attr_guest_matrix.attr,
1528 	NULL,
1529 };
1530 
1531 static struct attribute_group vfio_ap_mdev_attr_group = {
1532 	.attrs = vfio_ap_mdev_attrs
1533 };
1534 
1535 static const struct attribute_group *vfio_ap_mdev_attr_groups[] = {
1536 	&vfio_ap_mdev_attr_group,
1537 	NULL
1538 };
1539 
1540 /**
1541  * vfio_ap_mdev_set_kvm - sets all data for @matrix_mdev that are needed
1542  * to manage AP resources for the guest whose state is represented by @kvm
1543  *
1544  * @matrix_mdev: a mediated matrix device
1545  * @kvm: reference to KVM instance
1546  *
1547  * Return: 0 if no other mediated matrix device has a reference to @kvm;
1548  * otherwise, returns an -EPERM.
1549  */
1550 static int vfio_ap_mdev_set_kvm(struct ap_matrix_mdev *matrix_mdev,
1551 				struct kvm *kvm)
1552 {
1553 	struct ap_matrix_mdev *m;
1554 
1555 	if (kvm->arch.crypto.crycbd) {
1556 		down_write(&kvm->arch.crypto.pqap_hook_rwsem);
1557 		kvm->arch.crypto.pqap_hook = &matrix_mdev->pqap_hook;
1558 		up_write(&kvm->arch.crypto.pqap_hook_rwsem);
1559 
1560 		get_update_locks_for_kvm(kvm);
1561 
1562 		list_for_each_entry(m, &matrix_dev->mdev_list, node) {
1563 			if (m != matrix_mdev && m->kvm == kvm) {
1564 				release_update_locks_for_kvm(kvm);
1565 				return -EPERM;
1566 			}
1567 		}
1568 
1569 		kvm_get_kvm(kvm);
1570 		matrix_mdev->kvm = kvm;
1571 		vfio_ap_mdev_update_guest_apcb(matrix_mdev);
1572 
1573 		release_update_locks_for_kvm(kvm);
1574 	}
1575 
1576 	return 0;
1577 }
1578 
1579 static void vfio_ap_mdev_dma_unmap(struct vfio_device *vdev, u64 iova,
1580 				   u64 length)
1581 {
1582 	struct ap_matrix_mdev *matrix_mdev =
1583 		container_of(vdev, struct ap_matrix_mdev, vdev);
1584 
1585 	vfio_unpin_pages(&matrix_mdev->vdev, iova, 1);
1586 }
1587 
1588 /**
1589  * vfio_ap_mdev_unset_kvm - performs clean-up of resources no longer needed
1590  * by @matrix_mdev.
1591  *
1592  * @matrix_mdev: a matrix mediated device
1593  */
1594 static void vfio_ap_mdev_unset_kvm(struct ap_matrix_mdev *matrix_mdev)
1595 {
1596 	struct kvm *kvm = matrix_mdev->kvm;
1597 
1598 	if (kvm && kvm->arch.crypto.crycbd) {
1599 		down_write(&kvm->arch.crypto.pqap_hook_rwsem);
1600 		kvm->arch.crypto.pqap_hook = NULL;
1601 		up_write(&kvm->arch.crypto.pqap_hook_rwsem);
1602 
1603 		get_update_locks_for_kvm(kvm);
1604 
1605 		kvm_arch_crypto_clear_masks(kvm);
1606 		vfio_ap_mdev_reset_queues(&matrix_mdev->qtable);
1607 		kvm_put_kvm(kvm);
1608 		matrix_mdev->kvm = NULL;
1609 
1610 		release_update_locks_for_kvm(kvm);
1611 	}
1612 }
1613 
1614 static struct vfio_ap_queue *vfio_ap_find_queue(int apqn)
1615 {
1616 	struct ap_queue *queue;
1617 	struct vfio_ap_queue *q = NULL;
1618 
1619 	queue = ap_get_qdev(apqn);
1620 	if (!queue)
1621 		return NULL;
1622 
1623 	if (queue->ap_dev.device.driver == &matrix_dev->vfio_ap_drv->driver)
1624 		q = dev_get_drvdata(&queue->ap_dev.device);
1625 
1626 	put_device(&queue->ap_dev.device);
1627 
1628 	return q;
1629 }
1630 
1631 static int vfio_ap_mdev_reset_queue(struct vfio_ap_queue *q,
1632 				    unsigned int retry)
1633 {
1634 	struct ap_queue_status status;
1635 	int ret;
1636 	int retry2 = 2;
1637 
1638 	if (!q)
1639 		return 0;
1640 retry_zapq:
1641 	status = ap_zapq(q->apqn);
1642 	q->reset_rc = status.response_code;
1643 	switch (status.response_code) {
1644 	case AP_RESPONSE_NORMAL:
1645 		ret = 0;
1646 		break;
1647 	case AP_RESPONSE_RESET_IN_PROGRESS:
1648 		if (retry--) {
1649 			msleep(20);
1650 			goto retry_zapq;
1651 		}
1652 		ret = -EBUSY;
1653 		break;
1654 	case AP_RESPONSE_Q_NOT_AVAIL:
1655 	case AP_RESPONSE_DECONFIGURED:
1656 	case AP_RESPONSE_CHECKSTOPPED:
1657 		WARN_ONCE(status.irq_enabled,
1658 			  "PQAP/ZAPQ for %02x.%04x failed with rc=%u while IRQ enabled",
1659 			  AP_QID_CARD(q->apqn), AP_QID_QUEUE(q->apqn),
1660 			  status.response_code);
1661 		ret = -EBUSY;
1662 		goto free_resources;
1663 	default:
1664 		/* things are really broken, give up */
1665 		WARN(true,
1666 		     "PQAP/ZAPQ for %02x.%04x failed with invalid rc=%u\n",
1667 		     AP_QID_CARD(q->apqn), AP_QID_QUEUE(q->apqn),
1668 		     status.response_code);
1669 		return -EIO;
1670 	}
1671 
1672 	/* wait for the reset to take effect */
1673 	while (retry2--) {
1674 		if (status.queue_empty && !status.irq_enabled)
1675 			break;
1676 		msleep(20);
1677 		status = ap_tapq(q->apqn, NULL);
1678 	}
1679 	WARN_ONCE(retry2 <= 0, "unable to verify reset of queue %02x.%04x",
1680 		  AP_QID_CARD(q->apqn), AP_QID_QUEUE(q->apqn));
1681 
1682 free_resources:
1683 	vfio_ap_free_aqic_resources(q);
1684 
1685 	return ret;
1686 }
1687 
1688 static int vfio_ap_mdev_reset_queues(struct ap_queue_table *qtable)
1689 {
1690 	int ret, loop_cursor, rc = 0;
1691 	struct vfio_ap_queue *q;
1692 
1693 	hash_for_each(qtable->queues, loop_cursor, q, mdev_qnode) {
1694 		ret = vfio_ap_mdev_reset_queue(q, 1);
1695 		/*
1696 		 * Regardless whether a queue turns out to be busy, or
1697 		 * is not operational, we need to continue resetting
1698 		 * the remaining queues.
1699 		 */
1700 		if (ret)
1701 			rc = ret;
1702 	}
1703 
1704 	return rc;
1705 }
1706 
1707 static int vfio_ap_mdev_open_device(struct vfio_device *vdev)
1708 {
1709 	struct ap_matrix_mdev *matrix_mdev =
1710 		container_of(vdev, struct ap_matrix_mdev, vdev);
1711 
1712 	if (!vdev->kvm)
1713 		return -EINVAL;
1714 
1715 	return vfio_ap_mdev_set_kvm(matrix_mdev, vdev->kvm);
1716 }
1717 
1718 static void vfio_ap_mdev_close_device(struct vfio_device *vdev)
1719 {
1720 	struct ap_matrix_mdev *matrix_mdev =
1721 		container_of(vdev, struct ap_matrix_mdev, vdev);
1722 
1723 	vfio_ap_mdev_unset_kvm(matrix_mdev);
1724 }
1725 
1726 static int vfio_ap_mdev_get_device_info(unsigned long arg)
1727 {
1728 	unsigned long minsz;
1729 	struct vfio_device_info info;
1730 
1731 	minsz = offsetofend(struct vfio_device_info, num_irqs);
1732 
1733 	if (copy_from_user(&info, (void __user *)arg, minsz))
1734 		return -EFAULT;
1735 
1736 	if (info.argsz < minsz)
1737 		return -EINVAL;
1738 
1739 	info.flags = VFIO_DEVICE_FLAGS_AP | VFIO_DEVICE_FLAGS_RESET;
1740 	info.num_regions = 0;
1741 	info.num_irqs = 0;
1742 
1743 	return copy_to_user((void __user *)arg, &info, minsz) ? -EFAULT : 0;
1744 }
1745 
1746 static ssize_t vfio_ap_mdev_ioctl(struct vfio_device *vdev,
1747 				    unsigned int cmd, unsigned long arg)
1748 {
1749 	struct ap_matrix_mdev *matrix_mdev =
1750 		container_of(vdev, struct ap_matrix_mdev, vdev);
1751 	int ret;
1752 
1753 	mutex_lock(&matrix_dev->mdevs_lock);
1754 	switch (cmd) {
1755 	case VFIO_DEVICE_GET_INFO:
1756 		ret = vfio_ap_mdev_get_device_info(arg);
1757 		break;
1758 	case VFIO_DEVICE_RESET:
1759 		ret = vfio_ap_mdev_reset_queues(&matrix_mdev->qtable);
1760 		break;
1761 	default:
1762 		ret = -EOPNOTSUPP;
1763 		break;
1764 	}
1765 	mutex_unlock(&matrix_dev->mdevs_lock);
1766 
1767 	return ret;
1768 }
1769 
1770 static struct ap_matrix_mdev *vfio_ap_mdev_for_queue(struct vfio_ap_queue *q)
1771 {
1772 	struct ap_matrix_mdev *matrix_mdev;
1773 	unsigned long apid = AP_QID_CARD(q->apqn);
1774 	unsigned long apqi = AP_QID_QUEUE(q->apqn);
1775 
1776 	list_for_each_entry(matrix_mdev, &matrix_dev->mdev_list, node) {
1777 		if (test_bit_inv(apid, matrix_mdev->matrix.apm) &&
1778 		    test_bit_inv(apqi, matrix_mdev->matrix.aqm))
1779 			return matrix_mdev;
1780 	}
1781 
1782 	return NULL;
1783 }
1784 
1785 static ssize_t status_show(struct device *dev,
1786 			   struct device_attribute *attr,
1787 			   char *buf)
1788 {
1789 	ssize_t nchars = 0;
1790 	struct vfio_ap_queue *q;
1791 	struct ap_matrix_mdev *matrix_mdev;
1792 	struct ap_device *apdev = to_ap_dev(dev);
1793 
1794 	mutex_lock(&matrix_dev->mdevs_lock);
1795 	q = dev_get_drvdata(&apdev->device);
1796 	matrix_mdev = vfio_ap_mdev_for_queue(q);
1797 
1798 	if (matrix_mdev) {
1799 		if (matrix_mdev->kvm)
1800 			nchars = scnprintf(buf, PAGE_SIZE, "%s\n",
1801 					   AP_QUEUE_IN_USE);
1802 		else
1803 			nchars = scnprintf(buf, PAGE_SIZE, "%s\n",
1804 					   AP_QUEUE_ASSIGNED);
1805 	} else {
1806 		nchars = scnprintf(buf, PAGE_SIZE, "%s\n",
1807 				   AP_QUEUE_UNASSIGNED);
1808 	}
1809 
1810 	mutex_unlock(&matrix_dev->mdevs_lock);
1811 
1812 	return nchars;
1813 }
1814 
1815 static DEVICE_ATTR_RO(status);
1816 
1817 static struct attribute *vfio_queue_attrs[] = {
1818 	&dev_attr_status.attr,
1819 	NULL,
1820 };
1821 
1822 static const struct attribute_group vfio_queue_attr_group = {
1823 	.attrs = vfio_queue_attrs,
1824 };
1825 
1826 static const struct vfio_device_ops vfio_ap_matrix_dev_ops = {
1827 	.open_device = vfio_ap_mdev_open_device,
1828 	.close_device = vfio_ap_mdev_close_device,
1829 	.ioctl = vfio_ap_mdev_ioctl,
1830 	.dma_unmap = vfio_ap_mdev_dma_unmap,
1831 };
1832 
1833 static struct mdev_driver vfio_ap_matrix_driver = {
1834 	.driver = {
1835 		.name = "vfio_ap_mdev",
1836 		.owner = THIS_MODULE,
1837 		.mod_name = KBUILD_MODNAME,
1838 		.dev_groups = vfio_ap_mdev_attr_groups,
1839 	},
1840 	.probe = vfio_ap_mdev_probe,
1841 	.remove = vfio_ap_mdev_remove,
1842 	.supported_type_groups = vfio_ap_mdev_type_groups,
1843 };
1844 
1845 int vfio_ap_mdev_register(void)
1846 {
1847 	int ret;
1848 
1849 	atomic_set(&matrix_dev->available_instances, MAX_ZDEV_ENTRIES_EXT);
1850 
1851 	ret = mdev_register_driver(&vfio_ap_matrix_driver);
1852 	if (ret)
1853 		return ret;
1854 
1855 	ret = mdev_register_device(&matrix_dev->device, &vfio_ap_matrix_driver);
1856 	if (ret)
1857 		goto err_driver;
1858 	return 0;
1859 
1860 err_driver:
1861 	mdev_unregister_driver(&vfio_ap_matrix_driver);
1862 	return ret;
1863 }
1864 
1865 void vfio_ap_mdev_unregister(void)
1866 {
1867 	mdev_unregister_device(&matrix_dev->device);
1868 	mdev_unregister_driver(&vfio_ap_matrix_driver);
1869 }
1870 
1871 int vfio_ap_mdev_probe_queue(struct ap_device *apdev)
1872 {
1873 	int ret;
1874 	struct vfio_ap_queue *q;
1875 	struct ap_matrix_mdev *matrix_mdev;
1876 
1877 	ret = sysfs_create_group(&apdev->device.kobj, &vfio_queue_attr_group);
1878 	if (ret)
1879 		return ret;
1880 
1881 	q = kzalloc(sizeof(*q), GFP_KERNEL);
1882 	if (!q)
1883 		return -ENOMEM;
1884 
1885 	q->apqn = to_ap_queue(&apdev->device)->qid;
1886 	q->saved_isc = VFIO_AP_ISC_INVALID;
1887 	matrix_mdev = get_update_locks_by_apqn(q->apqn);
1888 
1889 	if (matrix_mdev) {
1890 		vfio_ap_mdev_link_queue(matrix_mdev, q);
1891 
1892 		if (vfio_ap_mdev_filter_matrix(matrix_mdev->matrix.apm,
1893 					       matrix_mdev->matrix.aqm,
1894 					       matrix_mdev))
1895 			vfio_ap_mdev_update_guest_apcb(matrix_mdev);
1896 	}
1897 	dev_set_drvdata(&apdev->device, q);
1898 	release_update_locks_for_mdev(matrix_mdev);
1899 
1900 	return 0;
1901 }
1902 
1903 void vfio_ap_mdev_remove_queue(struct ap_device *apdev)
1904 {
1905 	unsigned long apid, apqi;
1906 	struct vfio_ap_queue *q;
1907 	struct ap_matrix_mdev *matrix_mdev;
1908 
1909 	sysfs_remove_group(&apdev->device.kobj, &vfio_queue_attr_group);
1910 	q = dev_get_drvdata(&apdev->device);
1911 	get_update_locks_for_queue(q);
1912 	matrix_mdev = q->matrix_mdev;
1913 
1914 	if (matrix_mdev) {
1915 		vfio_ap_unlink_queue_fr_mdev(q);
1916 
1917 		apid = AP_QID_CARD(q->apqn);
1918 		apqi = AP_QID_QUEUE(q->apqn);
1919 
1920 		/*
1921 		 * If the queue is assigned to the guest's APCB, then remove
1922 		 * the adapter's APID from the APCB and hot it into the guest.
1923 		 */
1924 		if (test_bit_inv(apid, matrix_mdev->shadow_apcb.apm) &&
1925 		    test_bit_inv(apqi, matrix_mdev->shadow_apcb.aqm)) {
1926 			clear_bit_inv(apid, matrix_mdev->shadow_apcb.apm);
1927 			vfio_ap_mdev_update_guest_apcb(matrix_mdev);
1928 		}
1929 	}
1930 
1931 	vfio_ap_mdev_reset_queue(q, 1);
1932 	dev_set_drvdata(&apdev->device, NULL);
1933 	kfree(q);
1934 	release_update_locks_for_mdev(matrix_mdev);
1935 }
1936 
1937 /**
1938  * vfio_ap_mdev_resource_in_use: check whether any of a set of APQNs is
1939  *				 assigned to a mediated device under the control
1940  *				 of the vfio_ap device driver.
1941  *
1942  * @apm: a bitmap specifying a set of APIDs comprising the APQNs to check.
1943  * @aqm: a bitmap specifying a set of APQIs comprising the APQNs to check.
1944  *
1945  * Return:
1946  *	* -EADDRINUSE if one or more of the APQNs specified via @apm/@aqm are
1947  *	  assigned to a mediated device under the control of the vfio_ap
1948  *	  device driver.
1949  *	* Otherwise, return 0.
1950  */
1951 int vfio_ap_mdev_resource_in_use(unsigned long *apm, unsigned long *aqm)
1952 {
1953 	int ret;
1954 
1955 	mutex_lock(&matrix_dev->guests_lock);
1956 	mutex_lock(&matrix_dev->mdevs_lock);
1957 	ret = vfio_ap_mdev_verify_no_sharing(apm, aqm);
1958 	mutex_unlock(&matrix_dev->mdevs_lock);
1959 	mutex_unlock(&matrix_dev->guests_lock);
1960 
1961 	return ret;
1962 }
1963 
1964 /**
1965  * vfio_ap_mdev_hot_unplug_cfg - hot unplug the adapters, domains and control
1966  *				 domains that have been removed from the host's
1967  *				 AP configuration from a guest.
1968  *
1969  * @matrix_mdev: an ap_matrix_mdev object attached to a KVM guest.
1970  * @aprem: the adapters that have been removed from the host's AP configuration
1971  * @aqrem: the domains that have been removed from the host's AP configuration
1972  * @cdrem: the control domains that have been removed from the host's AP
1973  *	   configuration.
1974  */
1975 static void vfio_ap_mdev_hot_unplug_cfg(struct ap_matrix_mdev *matrix_mdev,
1976 					unsigned long *aprem,
1977 					unsigned long *aqrem,
1978 					unsigned long *cdrem)
1979 {
1980 	int do_hotplug = 0;
1981 
1982 	if (!bitmap_empty(aprem, AP_DEVICES)) {
1983 		do_hotplug |= bitmap_andnot(matrix_mdev->shadow_apcb.apm,
1984 					    matrix_mdev->shadow_apcb.apm,
1985 					    aprem, AP_DEVICES);
1986 	}
1987 
1988 	if (!bitmap_empty(aqrem, AP_DOMAINS)) {
1989 		do_hotplug |= bitmap_andnot(matrix_mdev->shadow_apcb.aqm,
1990 					    matrix_mdev->shadow_apcb.aqm,
1991 					    aqrem, AP_DEVICES);
1992 	}
1993 
1994 	if (!bitmap_empty(cdrem, AP_DOMAINS))
1995 		do_hotplug |= bitmap_andnot(matrix_mdev->shadow_apcb.adm,
1996 					    matrix_mdev->shadow_apcb.adm,
1997 					    cdrem, AP_DOMAINS);
1998 
1999 	if (do_hotplug)
2000 		vfio_ap_mdev_update_guest_apcb(matrix_mdev);
2001 }
2002 
2003 /**
2004  * vfio_ap_mdev_cfg_remove - determines which guests are using the adapters,
2005  *			     domains and control domains that have been removed
2006  *			     from the host AP configuration and unplugs them
2007  *			     from those guests.
2008  *
2009  * @ap_remove:	bitmap specifying which adapters have been removed from the host
2010  *		config.
2011  * @aq_remove:	bitmap specifying which domains have been removed from the host
2012  *		config.
2013  * @cd_remove:	bitmap specifying which control domains have been removed from
2014  *		the host config.
2015  */
2016 static void vfio_ap_mdev_cfg_remove(unsigned long *ap_remove,
2017 				    unsigned long *aq_remove,
2018 				    unsigned long *cd_remove)
2019 {
2020 	struct ap_matrix_mdev *matrix_mdev;
2021 	DECLARE_BITMAP(aprem, AP_DEVICES);
2022 	DECLARE_BITMAP(aqrem, AP_DOMAINS);
2023 	DECLARE_BITMAP(cdrem, AP_DOMAINS);
2024 	int do_remove = 0;
2025 
2026 	list_for_each_entry(matrix_mdev, &matrix_dev->mdev_list, node) {
2027 		mutex_lock(&matrix_mdev->kvm->lock);
2028 		mutex_lock(&matrix_dev->mdevs_lock);
2029 
2030 		do_remove |= bitmap_and(aprem, ap_remove,
2031 					  matrix_mdev->matrix.apm,
2032 					  AP_DEVICES);
2033 		do_remove |= bitmap_and(aqrem, aq_remove,
2034 					  matrix_mdev->matrix.aqm,
2035 					  AP_DOMAINS);
2036 		do_remove |= bitmap_andnot(cdrem, cd_remove,
2037 					     matrix_mdev->matrix.adm,
2038 					     AP_DOMAINS);
2039 
2040 		if (do_remove)
2041 			vfio_ap_mdev_hot_unplug_cfg(matrix_mdev, aprem, aqrem,
2042 						    cdrem);
2043 
2044 		mutex_unlock(&matrix_dev->mdevs_lock);
2045 		mutex_unlock(&matrix_mdev->kvm->lock);
2046 	}
2047 }
2048 
2049 /**
2050  * vfio_ap_mdev_on_cfg_remove - responds to the removal of adapters, domains and
2051  *				control domains from the host AP configuration
2052  *				by unplugging them from the guests that are
2053  *				using them.
2054  * @cur_config_info: the current host AP configuration information
2055  * @prev_config_info: the previous host AP configuration information
2056  */
2057 static void vfio_ap_mdev_on_cfg_remove(struct ap_config_info *cur_config_info,
2058 				       struct ap_config_info *prev_config_info)
2059 {
2060 	int do_remove;
2061 	DECLARE_BITMAP(aprem, AP_DEVICES);
2062 	DECLARE_BITMAP(aqrem, AP_DOMAINS);
2063 	DECLARE_BITMAP(cdrem, AP_DOMAINS);
2064 
2065 	do_remove = bitmap_andnot(aprem,
2066 				  (unsigned long *)prev_config_info->apm,
2067 				  (unsigned long *)cur_config_info->apm,
2068 				  AP_DEVICES);
2069 	do_remove |= bitmap_andnot(aqrem,
2070 				   (unsigned long *)prev_config_info->aqm,
2071 				   (unsigned long *)cur_config_info->aqm,
2072 				   AP_DEVICES);
2073 	do_remove |= bitmap_andnot(cdrem,
2074 				   (unsigned long *)prev_config_info->adm,
2075 				   (unsigned long *)cur_config_info->adm,
2076 				   AP_DEVICES);
2077 
2078 	if (do_remove)
2079 		vfio_ap_mdev_cfg_remove(aprem, aqrem, cdrem);
2080 }
2081 
2082 /**
2083  * vfio_ap_filter_apid_by_qtype: filter APIDs from an AP mask for adapters that
2084  *				 are older than AP type 10 (CEX4).
2085  * @apm: a bitmap of the APIDs to examine
2086  * @aqm: a bitmap of the APQIs of the queues to query for the AP type.
2087  */
2088 static void vfio_ap_filter_apid_by_qtype(unsigned long *apm, unsigned long *aqm)
2089 {
2090 	bool apid_cleared;
2091 	struct ap_queue_status status;
2092 	unsigned long apid, apqi, info;
2093 	int qtype, qtype_mask = 0xff000000;
2094 
2095 	for_each_set_bit_inv(apid, apm, AP_DEVICES) {
2096 		apid_cleared = false;
2097 
2098 		for_each_set_bit_inv(apqi, aqm, AP_DOMAINS) {
2099 			status = ap_test_queue(AP_MKQID(apid, apqi), 1, &info);
2100 			switch (status.response_code) {
2101 			/*
2102 			 * According to the architecture in each case
2103 			 * below, the queue's info should be filled.
2104 			 */
2105 			case AP_RESPONSE_NORMAL:
2106 			case AP_RESPONSE_RESET_IN_PROGRESS:
2107 			case AP_RESPONSE_DECONFIGURED:
2108 			case AP_RESPONSE_CHECKSTOPPED:
2109 			case AP_RESPONSE_BUSY:
2110 				qtype = info & qtype_mask;
2111 
2112 				/*
2113 				 * The vfio_ap device driver only
2114 				 * supports CEX4 and newer adapters, so
2115 				 * remove the APID if the adapter is
2116 				 * older than a CEX4.
2117 				 */
2118 				if (qtype < AP_DEVICE_TYPE_CEX4) {
2119 					clear_bit_inv(apid, apm);
2120 					apid_cleared = true;
2121 				}
2122 
2123 				break;
2124 
2125 			default:
2126 				/*
2127 				 * If we don't know the adapter type,
2128 				 * clear its APID since it can't be
2129 				 * determined whether the vfio_ap
2130 				 * device driver supports it.
2131 				 */
2132 				clear_bit_inv(apid, apm);
2133 				apid_cleared = true;
2134 				break;
2135 			}
2136 
2137 			/*
2138 			 * If we've already cleared the APID from the apm, there
2139 			 * is no need to continue examining the remainin AP
2140 			 * queues to determine the type of the adapter.
2141 			 */
2142 			if (apid_cleared)
2143 				continue;
2144 		}
2145 	}
2146 }
2147 
2148 /**
2149  * vfio_ap_mdev_cfg_add - store bitmaps specifying the adapters, domains and
2150  *			  control domains that have been added to the host's
2151  *			  AP configuration for each matrix mdev to which they
2152  *			  are assigned.
2153  *
2154  * @apm_add: a bitmap specifying the adapters that have been added to the AP
2155  *	     configuration.
2156  * @aqm_add: a bitmap specifying the domains that have been added to the AP
2157  *	     configuration.
2158  * @adm_add: a bitmap specifying the control domains that have been added to the
2159  *	     AP configuration.
2160  */
2161 static void vfio_ap_mdev_cfg_add(unsigned long *apm_add, unsigned long *aqm_add,
2162 				 unsigned long *adm_add)
2163 {
2164 	struct ap_matrix_mdev *matrix_mdev;
2165 
2166 	if (list_empty(&matrix_dev->mdev_list))
2167 		return;
2168 
2169 	vfio_ap_filter_apid_by_qtype(apm_add, aqm_add);
2170 
2171 	list_for_each_entry(matrix_mdev, &matrix_dev->mdev_list, node) {
2172 		bitmap_and(matrix_mdev->apm_add,
2173 			   matrix_mdev->matrix.apm, apm_add, AP_DEVICES);
2174 		bitmap_and(matrix_mdev->aqm_add,
2175 			   matrix_mdev->matrix.aqm, aqm_add, AP_DOMAINS);
2176 		bitmap_and(matrix_mdev->adm_add,
2177 			   matrix_mdev->matrix.adm, adm_add, AP_DEVICES);
2178 	}
2179 }
2180 
2181 /**
2182  * vfio_ap_mdev_on_cfg_add - responds to the addition of adapters, domains and
2183  *			     control domains to the host AP configuration
2184  *			     by updating the bitmaps that specify what adapters,
2185  *			     domains and control domains have been added so they
2186  *			     can be hot plugged into the guest when the AP bus
2187  *			     scan completes (see vfio_ap_on_scan_complete
2188  *			     function).
2189  * @cur_config_info: the current AP configuration information
2190  * @prev_config_info: the previous AP configuration information
2191  */
2192 static void vfio_ap_mdev_on_cfg_add(struct ap_config_info *cur_config_info,
2193 				    struct ap_config_info *prev_config_info)
2194 {
2195 	bool do_add;
2196 	DECLARE_BITMAP(apm_add, AP_DEVICES);
2197 	DECLARE_BITMAP(aqm_add, AP_DOMAINS);
2198 	DECLARE_BITMAP(adm_add, AP_DOMAINS);
2199 
2200 	do_add = bitmap_andnot(apm_add,
2201 			       (unsigned long *)cur_config_info->apm,
2202 			       (unsigned long *)prev_config_info->apm,
2203 			       AP_DEVICES);
2204 	do_add |= bitmap_andnot(aqm_add,
2205 				(unsigned long *)cur_config_info->aqm,
2206 				(unsigned long *)prev_config_info->aqm,
2207 				AP_DOMAINS);
2208 	do_add |= bitmap_andnot(adm_add,
2209 				(unsigned long *)cur_config_info->adm,
2210 				(unsigned long *)prev_config_info->adm,
2211 				AP_DOMAINS);
2212 
2213 	if (do_add)
2214 		vfio_ap_mdev_cfg_add(apm_add, aqm_add, adm_add);
2215 }
2216 
2217 /**
2218  * vfio_ap_on_cfg_changed - handles notification of changes to the host AP
2219  *			    configuration.
2220  *
2221  * @cur_cfg_info: the current host AP configuration
2222  * @prev_cfg_info: the previous host AP configuration
2223  */
2224 void vfio_ap_on_cfg_changed(struct ap_config_info *cur_cfg_info,
2225 			    struct ap_config_info *prev_cfg_info)
2226 {
2227 	if (!cur_cfg_info || !prev_cfg_info)
2228 		return;
2229 
2230 	mutex_lock(&matrix_dev->guests_lock);
2231 
2232 	vfio_ap_mdev_on_cfg_remove(cur_cfg_info, prev_cfg_info);
2233 	vfio_ap_mdev_on_cfg_add(cur_cfg_info, prev_cfg_info);
2234 	memcpy(&matrix_dev->info, cur_cfg_info, sizeof(*cur_cfg_info));
2235 
2236 	mutex_unlock(&matrix_dev->guests_lock);
2237 }
2238 
2239 static void vfio_ap_mdev_hot_plug_cfg(struct ap_matrix_mdev *matrix_mdev)
2240 {
2241 	bool do_hotplug = false;
2242 	int filter_domains = 0;
2243 	int filter_adapters = 0;
2244 	DECLARE_BITMAP(apm, AP_DEVICES);
2245 	DECLARE_BITMAP(aqm, AP_DOMAINS);
2246 
2247 	mutex_lock(&matrix_mdev->kvm->lock);
2248 	mutex_lock(&matrix_dev->mdevs_lock);
2249 
2250 	filter_adapters = bitmap_and(apm, matrix_mdev->matrix.apm,
2251 				     matrix_mdev->apm_add, AP_DEVICES);
2252 	filter_domains = bitmap_and(aqm, matrix_mdev->matrix.aqm,
2253 				    matrix_mdev->aqm_add, AP_DOMAINS);
2254 
2255 	if (filter_adapters && filter_domains)
2256 		do_hotplug |= vfio_ap_mdev_filter_matrix(apm, aqm, matrix_mdev);
2257 	else if (filter_adapters)
2258 		do_hotplug |=
2259 			vfio_ap_mdev_filter_matrix(apm,
2260 						   matrix_mdev->shadow_apcb.aqm,
2261 						   matrix_mdev);
2262 	else
2263 		do_hotplug |=
2264 			vfio_ap_mdev_filter_matrix(matrix_mdev->shadow_apcb.apm,
2265 						   aqm, matrix_mdev);
2266 
2267 	if (bitmap_intersects(matrix_mdev->matrix.adm, matrix_mdev->adm_add,
2268 			      AP_DOMAINS))
2269 		do_hotplug |= vfio_ap_mdev_filter_cdoms(matrix_mdev);
2270 
2271 	if (do_hotplug)
2272 		vfio_ap_mdev_update_guest_apcb(matrix_mdev);
2273 
2274 	mutex_unlock(&matrix_dev->mdevs_lock);
2275 	mutex_unlock(&matrix_mdev->kvm->lock);
2276 }
2277 
2278 void vfio_ap_on_scan_complete(struct ap_config_info *new_config_info,
2279 			      struct ap_config_info *old_config_info)
2280 {
2281 	struct ap_matrix_mdev *matrix_mdev;
2282 
2283 	mutex_lock(&matrix_dev->guests_lock);
2284 
2285 	list_for_each_entry(matrix_mdev, &matrix_dev->mdev_list, node) {
2286 		if (bitmap_empty(matrix_mdev->apm_add, AP_DEVICES) &&
2287 		    bitmap_empty(matrix_mdev->aqm_add, AP_DOMAINS) &&
2288 		    bitmap_empty(matrix_mdev->adm_add, AP_DOMAINS))
2289 			continue;
2290 
2291 		vfio_ap_mdev_hot_plug_cfg(matrix_mdev);
2292 		bitmap_clear(matrix_mdev->apm_add, 0, AP_DEVICES);
2293 		bitmap_clear(matrix_mdev->aqm_add, 0, AP_DOMAINS);
2294 		bitmap_clear(matrix_mdev->adm_add, 0, AP_DOMAINS);
2295 	}
2296 
2297 	mutex_unlock(&matrix_dev->guests_lock);
2298 }
2299