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_init_dev(struct vfio_device *vdev)
688 {
689 	struct ap_matrix_mdev *matrix_mdev =
690 		container_of(vdev, struct ap_matrix_mdev, vdev);
691 
692 	if ((atomic_dec_if_positive(&matrix_dev->available_instances) < 0))
693 		return -EPERM;
694 
695 	matrix_mdev->mdev = to_mdev_device(vdev->dev);
696 	vfio_ap_matrix_init(&matrix_dev->info, &matrix_mdev->matrix);
697 	matrix_mdev->pqap_hook = handle_pqap;
698 	vfio_ap_matrix_init(&matrix_dev->info, &matrix_mdev->shadow_apcb);
699 	hash_init(matrix_mdev->qtable.queues);
700 
701 	return 0;
702 }
703 
704 static int vfio_ap_mdev_probe(struct mdev_device *mdev)
705 {
706 	struct ap_matrix_mdev *matrix_mdev;
707 	int ret;
708 
709 	matrix_mdev = vfio_alloc_device(ap_matrix_mdev, vdev, &mdev->dev,
710 					&vfio_ap_matrix_dev_ops);
711 	if (IS_ERR(matrix_mdev))
712 		return PTR_ERR(matrix_mdev);
713 
714 	ret = vfio_register_emulated_iommu_dev(&matrix_mdev->vdev);
715 	if (ret)
716 		goto err_put_vdev;
717 	dev_set_drvdata(&mdev->dev, matrix_mdev);
718 	mutex_lock(&matrix_dev->mdevs_lock);
719 	list_add(&matrix_mdev->node, &matrix_dev->mdev_list);
720 	mutex_unlock(&matrix_dev->mdevs_lock);
721 	return 0;
722 
723 err_put_vdev:
724 	vfio_put_device(&matrix_mdev->vdev);
725 	return ret;
726 }
727 
728 static void vfio_ap_mdev_link_queue(struct ap_matrix_mdev *matrix_mdev,
729 				    struct vfio_ap_queue *q)
730 {
731 	if (q) {
732 		q->matrix_mdev = matrix_mdev;
733 		hash_add(matrix_mdev->qtable.queues, &q->mdev_qnode, q->apqn);
734 	}
735 }
736 
737 static void vfio_ap_mdev_link_apqn(struct ap_matrix_mdev *matrix_mdev, int apqn)
738 {
739 	struct vfio_ap_queue *q;
740 
741 	q = vfio_ap_find_queue(apqn);
742 	vfio_ap_mdev_link_queue(matrix_mdev, q);
743 }
744 
745 static void vfio_ap_unlink_queue_fr_mdev(struct vfio_ap_queue *q)
746 {
747 	hash_del(&q->mdev_qnode);
748 }
749 
750 static void vfio_ap_unlink_mdev_fr_queue(struct vfio_ap_queue *q)
751 {
752 	q->matrix_mdev = NULL;
753 }
754 
755 static void vfio_ap_mdev_unlink_fr_queues(struct ap_matrix_mdev *matrix_mdev)
756 {
757 	struct vfio_ap_queue *q;
758 	unsigned long apid, apqi;
759 
760 	for_each_set_bit_inv(apid, matrix_mdev->matrix.apm, AP_DEVICES) {
761 		for_each_set_bit_inv(apqi, matrix_mdev->matrix.aqm,
762 				     AP_DOMAINS) {
763 			q = vfio_ap_mdev_get_queue(matrix_mdev,
764 						   AP_MKQID(apid, apqi));
765 			if (q)
766 				q->matrix_mdev = NULL;
767 		}
768 	}
769 }
770 
771 static void vfio_ap_mdev_release_dev(struct vfio_device *vdev)
772 {
773 	atomic_inc(&matrix_dev->available_instances);
774 	vfio_free_device(vdev);
775 }
776 
777 static void vfio_ap_mdev_remove(struct mdev_device *mdev)
778 {
779 	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(&mdev->dev);
780 
781 	vfio_unregister_group_dev(&matrix_mdev->vdev);
782 
783 	mutex_lock(&matrix_dev->guests_lock);
784 	mutex_lock(&matrix_dev->mdevs_lock);
785 	vfio_ap_mdev_reset_queues(&matrix_mdev->qtable);
786 	vfio_ap_mdev_unlink_fr_queues(matrix_mdev);
787 	list_del(&matrix_mdev->node);
788 	mutex_unlock(&matrix_dev->mdevs_lock);
789 	mutex_unlock(&matrix_dev->guests_lock);
790 	vfio_put_device(&matrix_mdev->vdev);
791 }
792 
793 static ssize_t name_show(struct mdev_type *mtype,
794 			 struct mdev_type_attribute *attr, char *buf)
795 {
796 	return sprintf(buf, "%s\n", VFIO_AP_MDEV_NAME_HWVIRT);
797 }
798 
799 static MDEV_TYPE_ATTR_RO(name);
800 
801 static ssize_t available_instances_show(struct mdev_type *mtype,
802 					struct mdev_type_attribute *attr,
803 					char *buf)
804 {
805 	return sprintf(buf, "%d\n",
806 		       atomic_read(&matrix_dev->available_instances));
807 }
808 
809 static MDEV_TYPE_ATTR_RO(available_instances);
810 
811 static ssize_t device_api_show(struct mdev_type *mtype,
812 			       struct mdev_type_attribute *attr, char *buf)
813 {
814 	return sprintf(buf, "%s\n", VFIO_DEVICE_API_AP_STRING);
815 }
816 
817 static MDEV_TYPE_ATTR_RO(device_api);
818 
819 static struct attribute *vfio_ap_mdev_type_attrs[] = {
820 	&mdev_type_attr_name.attr,
821 	&mdev_type_attr_device_api.attr,
822 	&mdev_type_attr_available_instances.attr,
823 	NULL,
824 };
825 
826 static struct attribute_group vfio_ap_mdev_hwvirt_type_group = {
827 	.name = VFIO_AP_MDEV_TYPE_HWVIRT,
828 	.attrs = vfio_ap_mdev_type_attrs,
829 };
830 
831 static struct attribute_group *vfio_ap_mdev_type_groups[] = {
832 	&vfio_ap_mdev_hwvirt_type_group,
833 	NULL,
834 };
835 
836 #define MDEV_SHARING_ERR "Userspace may not re-assign queue %02lx.%04lx " \
837 			 "already assigned to %s"
838 
839 static void vfio_ap_mdev_log_sharing_err(struct ap_matrix_mdev *matrix_mdev,
840 					 unsigned long *apm,
841 					 unsigned long *aqm)
842 {
843 	unsigned long apid, apqi;
844 	const struct device *dev = mdev_dev(matrix_mdev->mdev);
845 	const char *mdev_name = dev_name(dev);
846 
847 	for_each_set_bit_inv(apid, apm, AP_DEVICES)
848 		for_each_set_bit_inv(apqi, aqm, AP_DOMAINS)
849 			dev_warn(dev, MDEV_SHARING_ERR, apid, apqi, mdev_name);
850 }
851 
852 /**
853  * vfio_ap_mdev_verify_no_sharing - verify APQNs are not shared by matrix mdevs
854  *
855  * @mdev_apm: mask indicating the APIDs of the APQNs to be verified
856  * @mdev_aqm: mask indicating the APQIs of the APQNs to be verified
857  *
858  * Verifies that each APQN derived from the Cartesian product of a bitmap of
859  * AP adapter IDs and AP queue indexes is not configured for any matrix
860  * mediated device. AP queue sharing is not allowed.
861  *
862  * Return: 0 if the APQNs are not shared; otherwise return -EADDRINUSE.
863  */
864 static int vfio_ap_mdev_verify_no_sharing(unsigned long *mdev_apm,
865 					  unsigned long *mdev_aqm)
866 {
867 	struct ap_matrix_mdev *matrix_mdev;
868 	DECLARE_BITMAP(apm, AP_DEVICES);
869 	DECLARE_BITMAP(aqm, AP_DOMAINS);
870 
871 	list_for_each_entry(matrix_mdev, &matrix_dev->mdev_list, node) {
872 		/*
873 		 * If the input apm and aqm are fields of the matrix_mdev
874 		 * object, then move on to the next matrix_mdev.
875 		 */
876 		if (mdev_apm == matrix_mdev->matrix.apm &&
877 		    mdev_aqm == matrix_mdev->matrix.aqm)
878 			continue;
879 
880 		memset(apm, 0, sizeof(apm));
881 		memset(aqm, 0, sizeof(aqm));
882 
883 		/*
884 		 * We work on full longs, as we can only exclude the leftover
885 		 * bits in non-inverse order. The leftover is all zeros.
886 		 */
887 		if (!bitmap_and(apm, mdev_apm, matrix_mdev->matrix.apm,
888 				AP_DEVICES))
889 			continue;
890 
891 		if (!bitmap_and(aqm, mdev_aqm, matrix_mdev->matrix.aqm,
892 				AP_DOMAINS))
893 			continue;
894 
895 		vfio_ap_mdev_log_sharing_err(matrix_mdev, apm, aqm);
896 
897 		return -EADDRINUSE;
898 	}
899 
900 	return 0;
901 }
902 
903 /**
904  * vfio_ap_mdev_validate_masks - verify that the APQNs assigned to the mdev are
905  *				 not reserved for the default zcrypt driver and
906  *				 are not assigned to another mdev.
907  *
908  * @matrix_mdev: the mdev to which the APQNs being validated are assigned.
909  *
910  * Return: One of the following values:
911  * o the error returned from the ap_apqn_in_matrix_owned_by_def_drv() function,
912  *   most likely -EBUSY indicating the ap_perms_mutex lock is already held.
913  * o EADDRNOTAVAIL if an APQN assigned to @matrix_mdev is reserved for the
914  *		   zcrypt default driver.
915  * o EADDRINUSE if an APQN assigned to @matrix_mdev is assigned to another mdev
916  * o A zero indicating validation succeeded.
917  */
918 static int vfio_ap_mdev_validate_masks(struct ap_matrix_mdev *matrix_mdev)
919 {
920 	if (ap_apqn_in_matrix_owned_by_def_drv(matrix_mdev->matrix.apm,
921 					       matrix_mdev->matrix.aqm))
922 		return -EADDRNOTAVAIL;
923 
924 	return vfio_ap_mdev_verify_no_sharing(matrix_mdev->matrix.apm,
925 					      matrix_mdev->matrix.aqm);
926 }
927 
928 static void vfio_ap_mdev_link_adapter(struct ap_matrix_mdev *matrix_mdev,
929 				      unsigned long apid)
930 {
931 	unsigned long apqi;
932 
933 	for_each_set_bit_inv(apqi, matrix_mdev->matrix.aqm, AP_DOMAINS)
934 		vfio_ap_mdev_link_apqn(matrix_mdev,
935 				       AP_MKQID(apid, apqi));
936 }
937 
938 /**
939  * assign_adapter_store - parses the APID from @buf and sets the
940  * corresponding bit in the mediated matrix device's APM
941  *
942  * @dev:	the matrix device
943  * @attr:	the mediated matrix device's assign_adapter attribute
944  * @buf:	a buffer containing the AP adapter number (APID) to
945  *		be assigned
946  * @count:	the number of bytes in @buf
947  *
948  * Return: the number of bytes processed if the APID is valid; otherwise,
949  * returns one of the following errors:
950  *
951  *	1. -EINVAL
952  *	   The APID is not a valid number
953  *
954  *	2. -ENODEV
955  *	   The APID exceeds the maximum value configured for the system
956  *
957  *	3. -EADDRNOTAVAIL
958  *	   An APQN derived from the cross product of the APID being assigned
959  *	   and the APQIs previously assigned is not bound to the vfio_ap device
960  *	   driver; or, if no APQIs have yet been assigned, the APID is not
961  *	   contained in an APQN bound to the vfio_ap device driver.
962  *
963  *	4. -EADDRINUSE
964  *	   An APQN derived from the cross product of the APID being assigned
965  *	   and the APQIs previously assigned is being used by another mediated
966  *	   matrix device
967  *
968  *	5. -EAGAIN
969  *	   A lock required to validate the mdev's AP configuration could not
970  *	   be obtained.
971  */
972 static ssize_t assign_adapter_store(struct device *dev,
973 				    struct device_attribute *attr,
974 				    const char *buf, size_t count)
975 {
976 	int ret;
977 	unsigned long apid;
978 	DECLARE_BITMAP(apm_delta, AP_DEVICES);
979 	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
980 
981 	mutex_lock(&ap_perms_mutex);
982 	get_update_locks_for_mdev(matrix_mdev);
983 
984 	ret = kstrtoul(buf, 0, &apid);
985 	if (ret)
986 		goto done;
987 
988 	if (apid > matrix_mdev->matrix.apm_max) {
989 		ret = -ENODEV;
990 		goto done;
991 	}
992 
993 	set_bit_inv(apid, matrix_mdev->matrix.apm);
994 
995 	ret = vfio_ap_mdev_validate_masks(matrix_mdev);
996 	if (ret) {
997 		clear_bit_inv(apid, matrix_mdev->matrix.apm);
998 		goto done;
999 	}
1000 
1001 	vfio_ap_mdev_link_adapter(matrix_mdev, apid);
1002 	memset(apm_delta, 0, sizeof(apm_delta));
1003 	set_bit_inv(apid, apm_delta);
1004 
1005 	if (vfio_ap_mdev_filter_matrix(apm_delta,
1006 				       matrix_mdev->matrix.aqm, matrix_mdev))
1007 		vfio_ap_mdev_update_guest_apcb(matrix_mdev);
1008 
1009 	ret = count;
1010 done:
1011 	release_update_locks_for_mdev(matrix_mdev);
1012 	mutex_unlock(&ap_perms_mutex);
1013 
1014 	return ret;
1015 }
1016 static DEVICE_ATTR_WO(assign_adapter);
1017 
1018 static struct vfio_ap_queue
1019 *vfio_ap_unlink_apqn_fr_mdev(struct ap_matrix_mdev *matrix_mdev,
1020 			     unsigned long apid, unsigned long apqi)
1021 {
1022 	struct vfio_ap_queue *q = NULL;
1023 
1024 	q = vfio_ap_mdev_get_queue(matrix_mdev, AP_MKQID(apid, apqi));
1025 	/* If the queue is assigned to the matrix mdev, unlink it. */
1026 	if (q)
1027 		vfio_ap_unlink_queue_fr_mdev(q);
1028 
1029 	return q;
1030 }
1031 
1032 /**
1033  * vfio_ap_mdev_unlink_adapter - unlink all queues associated with unassigned
1034  *				 adapter from the matrix mdev to which the
1035  *				 adapter was assigned.
1036  * @matrix_mdev: the matrix mediated device to which the adapter was assigned.
1037  * @apid: the APID of the unassigned adapter.
1038  * @qtable: table for storing queues associated with unassigned adapter.
1039  */
1040 static void vfio_ap_mdev_unlink_adapter(struct ap_matrix_mdev *matrix_mdev,
1041 					unsigned long apid,
1042 					struct ap_queue_table *qtable)
1043 {
1044 	unsigned long apqi;
1045 	struct vfio_ap_queue *q;
1046 
1047 	for_each_set_bit_inv(apqi, matrix_mdev->matrix.aqm, AP_DOMAINS) {
1048 		q = vfio_ap_unlink_apqn_fr_mdev(matrix_mdev, apid, apqi);
1049 
1050 		if (q && qtable) {
1051 			if (test_bit_inv(apid, matrix_mdev->shadow_apcb.apm) &&
1052 			    test_bit_inv(apqi, matrix_mdev->shadow_apcb.aqm))
1053 				hash_add(qtable->queues, &q->mdev_qnode,
1054 					 q->apqn);
1055 		}
1056 	}
1057 }
1058 
1059 static void vfio_ap_mdev_hot_unplug_adapter(struct ap_matrix_mdev *matrix_mdev,
1060 					    unsigned long apid)
1061 {
1062 	int loop_cursor;
1063 	struct vfio_ap_queue *q;
1064 	struct ap_queue_table *qtable = kzalloc(sizeof(*qtable), GFP_KERNEL);
1065 
1066 	hash_init(qtable->queues);
1067 	vfio_ap_mdev_unlink_adapter(matrix_mdev, apid, qtable);
1068 
1069 	if (test_bit_inv(apid, matrix_mdev->shadow_apcb.apm)) {
1070 		clear_bit_inv(apid, matrix_mdev->shadow_apcb.apm);
1071 		vfio_ap_mdev_update_guest_apcb(matrix_mdev);
1072 	}
1073 
1074 	vfio_ap_mdev_reset_queues(qtable);
1075 
1076 	hash_for_each(qtable->queues, loop_cursor, q, mdev_qnode) {
1077 		vfio_ap_unlink_mdev_fr_queue(q);
1078 		hash_del(&q->mdev_qnode);
1079 	}
1080 
1081 	kfree(qtable);
1082 }
1083 
1084 /**
1085  * unassign_adapter_store - parses the APID from @buf and clears the
1086  * corresponding bit in the mediated matrix device's APM
1087  *
1088  * @dev:	the matrix device
1089  * @attr:	the mediated matrix device's unassign_adapter attribute
1090  * @buf:	a buffer containing the adapter number (APID) to be unassigned
1091  * @count:	the number of bytes in @buf
1092  *
1093  * Return: the number of bytes processed if the APID is valid; otherwise,
1094  * returns one of the following errors:
1095  *	-EINVAL if the APID is not a number
1096  *	-ENODEV if the APID it exceeds the maximum value configured for the
1097  *		system
1098  */
1099 static ssize_t unassign_adapter_store(struct device *dev,
1100 				      struct device_attribute *attr,
1101 				      const char *buf, size_t count)
1102 {
1103 	int ret;
1104 	unsigned long apid;
1105 	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
1106 
1107 	get_update_locks_for_mdev(matrix_mdev);
1108 
1109 	ret = kstrtoul(buf, 0, &apid);
1110 	if (ret)
1111 		goto done;
1112 
1113 	if (apid > matrix_mdev->matrix.apm_max) {
1114 		ret = -ENODEV;
1115 		goto done;
1116 	}
1117 
1118 	clear_bit_inv((unsigned long)apid, matrix_mdev->matrix.apm);
1119 	vfio_ap_mdev_hot_unplug_adapter(matrix_mdev, apid);
1120 	ret = count;
1121 done:
1122 	release_update_locks_for_mdev(matrix_mdev);
1123 	return ret;
1124 }
1125 static DEVICE_ATTR_WO(unassign_adapter);
1126 
1127 static void vfio_ap_mdev_link_domain(struct ap_matrix_mdev *matrix_mdev,
1128 				     unsigned long apqi)
1129 {
1130 	unsigned long apid;
1131 
1132 	for_each_set_bit_inv(apid, matrix_mdev->matrix.apm, AP_DEVICES)
1133 		vfio_ap_mdev_link_apqn(matrix_mdev,
1134 				       AP_MKQID(apid, apqi));
1135 }
1136 
1137 /**
1138  * assign_domain_store - parses the APQI from @buf and sets the
1139  * corresponding bit in the mediated matrix device's AQM
1140  *
1141  * @dev:	the matrix device
1142  * @attr:	the mediated matrix device's assign_domain attribute
1143  * @buf:	a buffer containing the AP queue index (APQI) of the domain to
1144  *		be assigned
1145  * @count:	the number of bytes in @buf
1146  *
1147  * Return: the number of bytes processed if the APQI is valid; otherwise returns
1148  * one of the following errors:
1149  *
1150  *	1. -EINVAL
1151  *	   The APQI is not a valid number
1152  *
1153  *	2. -ENODEV
1154  *	   The APQI exceeds the maximum value configured for the system
1155  *
1156  *	3. -EADDRNOTAVAIL
1157  *	   An APQN derived from the cross product of the APQI being assigned
1158  *	   and the APIDs previously assigned is not bound to the vfio_ap device
1159  *	   driver; or, if no APIDs have yet been assigned, the APQI is not
1160  *	   contained in an APQN bound to the vfio_ap device driver.
1161  *
1162  *	4. -EADDRINUSE
1163  *	   An APQN derived from the cross product of the APQI being assigned
1164  *	   and the APIDs previously assigned is being used by another mediated
1165  *	   matrix device
1166  *
1167  *	5. -EAGAIN
1168  *	   The lock required to validate the mdev's AP configuration could not
1169  *	   be obtained.
1170  */
1171 static ssize_t assign_domain_store(struct device *dev,
1172 				   struct device_attribute *attr,
1173 				   const char *buf, size_t count)
1174 {
1175 	int ret;
1176 	unsigned long apqi;
1177 	DECLARE_BITMAP(aqm_delta, AP_DOMAINS);
1178 	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
1179 
1180 	mutex_lock(&ap_perms_mutex);
1181 	get_update_locks_for_mdev(matrix_mdev);
1182 
1183 	ret = kstrtoul(buf, 0, &apqi);
1184 	if (ret)
1185 		goto done;
1186 
1187 	if (apqi > matrix_mdev->matrix.aqm_max) {
1188 		ret = -ENODEV;
1189 		goto done;
1190 	}
1191 
1192 	set_bit_inv(apqi, matrix_mdev->matrix.aqm);
1193 
1194 	ret = vfio_ap_mdev_validate_masks(matrix_mdev);
1195 	if (ret) {
1196 		clear_bit_inv(apqi, matrix_mdev->matrix.aqm);
1197 		goto done;
1198 	}
1199 
1200 	vfio_ap_mdev_link_domain(matrix_mdev, apqi);
1201 	memset(aqm_delta, 0, sizeof(aqm_delta));
1202 	set_bit_inv(apqi, aqm_delta);
1203 
1204 	if (vfio_ap_mdev_filter_matrix(matrix_mdev->matrix.apm, aqm_delta,
1205 				       matrix_mdev))
1206 		vfio_ap_mdev_update_guest_apcb(matrix_mdev);
1207 
1208 	ret = count;
1209 done:
1210 	release_update_locks_for_mdev(matrix_mdev);
1211 	mutex_unlock(&ap_perms_mutex);
1212 
1213 	return ret;
1214 }
1215 static DEVICE_ATTR_WO(assign_domain);
1216 
1217 static void vfio_ap_mdev_unlink_domain(struct ap_matrix_mdev *matrix_mdev,
1218 				       unsigned long apqi,
1219 				       struct ap_queue_table *qtable)
1220 {
1221 	unsigned long apid;
1222 	struct vfio_ap_queue *q;
1223 
1224 	for_each_set_bit_inv(apid, matrix_mdev->matrix.apm, AP_DEVICES) {
1225 		q = vfio_ap_unlink_apqn_fr_mdev(matrix_mdev, apid, apqi);
1226 
1227 		if (q && qtable) {
1228 			if (test_bit_inv(apid, matrix_mdev->shadow_apcb.apm) &&
1229 			    test_bit_inv(apqi, matrix_mdev->shadow_apcb.aqm))
1230 				hash_add(qtable->queues, &q->mdev_qnode,
1231 					 q->apqn);
1232 		}
1233 	}
1234 }
1235 
1236 static void vfio_ap_mdev_hot_unplug_domain(struct ap_matrix_mdev *matrix_mdev,
1237 					   unsigned long apqi)
1238 {
1239 	int loop_cursor;
1240 	struct vfio_ap_queue *q;
1241 	struct ap_queue_table *qtable = kzalloc(sizeof(*qtable), GFP_KERNEL);
1242 
1243 	hash_init(qtable->queues);
1244 	vfio_ap_mdev_unlink_domain(matrix_mdev, apqi, qtable);
1245 
1246 	if (test_bit_inv(apqi, matrix_mdev->shadow_apcb.aqm)) {
1247 		clear_bit_inv(apqi, matrix_mdev->shadow_apcb.aqm);
1248 		vfio_ap_mdev_update_guest_apcb(matrix_mdev);
1249 	}
1250 
1251 	vfio_ap_mdev_reset_queues(qtable);
1252 
1253 	hash_for_each(qtable->queues, loop_cursor, q, mdev_qnode) {
1254 		vfio_ap_unlink_mdev_fr_queue(q);
1255 		hash_del(&q->mdev_qnode);
1256 	}
1257 
1258 	kfree(qtable);
1259 }
1260 
1261 /**
1262  * unassign_domain_store - parses the APQI from @buf and clears the
1263  * corresponding bit in the mediated matrix device's AQM
1264  *
1265  * @dev:	the matrix device
1266  * @attr:	the mediated matrix device's unassign_domain attribute
1267  * @buf:	a buffer containing the AP queue index (APQI) of the domain to
1268  *		be unassigned
1269  * @count:	the number of bytes in @buf
1270  *
1271  * Return: the number of bytes processed if the APQI is valid; otherwise,
1272  * returns one of the following errors:
1273  *	-EINVAL if the APQI is not a number
1274  *	-ENODEV if the APQI exceeds the maximum value configured for the system
1275  */
1276 static ssize_t unassign_domain_store(struct device *dev,
1277 				     struct device_attribute *attr,
1278 				     const char *buf, size_t count)
1279 {
1280 	int ret;
1281 	unsigned long apqi;
1282 	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
1283 
1284 	get_update_locks_for_mdev(matrix_mdev);
1285 
1286 	ret = kstrtoul(buf, 0, &apqi);
1287 	if (ret)
1288 		goto done;
1289 
1290 	if (apqi > matrix_mdev->matrix.aqm_max) {
1291 		ret = -ENODEV;
1292 		goto done;
1293 	}
1294 
1295 	clear_bit_inv((unsigned long)apqi, matrix_mdev->matrix.aqm);
1296 	vfio_ap_mdev_hot_unplug_domain(matrix_mdev, apqi);
1297 	ret = count;
1298 
1299 done:
1300 	release_update_locks_for_mdev(matrix_mdev);
1301 	return ret;
1302 }
1303 static DEVICE_ATTR_WO(unassign_domain);
1304 
1305 /**
1306  * assign_control_domain_store - parses the domain ID from @buf and sets
1307  * the corresponding bit in the mediated matrix device's ADM
1308  *
1309  * @dev:	the matrix device
1310  * @attr:	the mediated matrix device's assign_control_domain attribute
1311  * @buf:	a buffer containing the domain ID to be assigned
1312  * @count:	the number of bytes in @buf
1313  *
1314  * Return: the number of bytes processed if the domain ID is valid; otherwise,
1315  * returns one of the following errors:
1316  *	-EINVAL if the ID is not a number
1317  *	-ENODEV if the ID exceeds the maximum value configured for the system
1318  */
1319 static ssize_t assign_control_domain_store(struct device *dev,
1320 					   struct device_attribute *attr,
1321 					   const char *buf, size_t count)
1322 {
1323 	int ret;
1324 	unsigned long id;
1325 	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
1326 
1327 	get_update_locks_for_mdev(matrix_mdev);
1328 
1329 	ret = kstrtoul(buf, 0, &id);
1330 	if (ret)
1331 		goto done;
1332 
1333 	if (id > matrix_mdev->matrix.adm_max) {
1334 		ret = -ENODEV;
1335 		goto done;
1336 	}
1337 
1338 	/* Set the bit in the ADM (bitmask) corresponding to the AP control
1339 	 * domain number (id). The bits in the mask, from most significant to
1340 	 * least significant, correspond to IDs 0 up to the one less than the
1341 	 * number of control domains that can be assigned.
1342 	 */
1343 	set_bit_inv(id, matrix_mdev->matrix.adm);
1344 	if (vfio_ap_mdev_filter_cdoms(matrix_mdev))
1345 		vfio_ap_mdev_update_guest_apcb(matrix_mdev);
1346 
1347 	ret = count;
1348 done:
1349 	release_update_locks_for_mdev(matrix_mdev);
1350 	return ret;
1351 }
1352 static DEVICE_ATTR_WO(assign_control_domain);
1353 
1354 /**
1355  * unassign_control_domain_store - parses the domain ID from @buf and
1356  * clears the corresponding bit in the mediated matrix device's ADM
1357  *
1358  * @dev:	the matrix device
1359  * @attr:	the mediated matrix device's unassign_control_domain attribute
1360  * @buf:	a buffer containing the domain ID to be unassigned
1361  * @count:	the number of bytes in @buf
1362  *
1363  * Return: the number of bytes processed if the domain ID is valid; otherwise,
1364  * returns one of the following errors:
1365  *	-EINVAL if the ID is not a number
1366  *	-ENODEV if the ID exceeds the maximum value configured for the system
1367  */
1368 static ssize_t unassign_control_domain_store(struct device *dev,
1369 					     struct device_attribute *attr,
1370 					     const char *buf, size_t count)
1371 {
1372 	int ret;
1373 	unsigned long domid;
1374 	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
1375 
1376 	get_update_locks_for_mdev(matrix_mdev);
1377 
1378 	ret = kstrtoul(buf, 0, &domid);
1379 	if (ret)
1380 		goto done;
1381 
1382 	if (domid > matrix_mdev->matrix.adm_max) {
1383 		ret = -ENODEV;
1384 		goto done;
1385 	}
1386 
1387 	clear_bit_inv(domid, matrix_mdev->matrix.adm);
1388 
1389 	if (test_bit_inv(domid, matrix_mdev->shadow_apcb.adm)) {
1390 		clear_bit_inv(domid, matrix_mdev->shadow_apcb.adm);
1391 		vfio_ap_mdev_update_guest_apcb(matrix_mdev);
1392 	}
1393 
1394 	ret = count;
1395 done:
1396 	release_update_locks_for_mdev(matrix_mdev);
1397 	return ret;
1398 }
1399 static DEVICE_ATTR_WO(unassign_control_domain);
1400 
1401 static ssize_t control_domains_show(struct device *dev,
1402 				    struct device_attribute *dev_attr,
1403 				    char *buf)
1404 {
1405 	unsigned long id;
1406 	int nchars = 0;
1407 	int n;
1408 	char *bufpos = buf;
1409 	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
1410 	unsigned long max_domid = matrix_mdev->matrix.adm_max;
1411 
1412 	mutex_lock(&matrix_dev->mdevs_lock);
1413 	for_each_set_bit_inv(id, matrix_mdev->matrix.adm, max_domid + 1) {
1414 		n = sprintf(bufpos, "%04lx\n", id);
1415 		bufpos += n;
1416 		nchars += n;
1417 	}
1418 	mutex_unlock(&matrix_dev->mdevs_lock);
1419 
1420 	return nchars;
1421 }
1422 static DEVICE_ATTR_RO(control_domains);
1423 
1424 static ssize_t vfio_ap_mdev_matrix_show(struct ap_matrix *matrix, char *buf)
1425 {
1426 	char *bufpos = buf;
1427 	unsigned long apid;
1428 	unsigned long apqi;
1429 	unsigned long apid1;
1430 	unsigned long apqi1;
1431 	unsigned long napm_bits = matrix->apm_max + 1;
1432 	unsigned long naqm_bits = matrix->aqm_max + 1;
1433 	int nchars = 0;
1434 	int n;
1435 
1436 	apid1 = find_first_bit_inv(matrix->apm, napm_bits);
1437 	apqi1 = find_first_bit_inv(matrix->aqm, naqm_bits);
1438 
1439 	if ((apid1 < napm_bits) && (apqi1 < naqm_bits)) {
1440 		for_each_set_bit_inv(apid, matrix->apm, napm_bits) {
1441 			for_each_set_bit_inv(apqi, matrix->aqm,
1442 					     naqm_bits) {
1443 				n = sprintf(bufpos, "%02lx.%04lx\n", apid,
1444 					    apqi);
1445 				bufpos += n;
1446 				nchars += n;
1447 			}
1448 		}
1449 	} else if (apid1 < napm_bits) {
1450 		for_each_set_bit_inv(apid, matrix->apm, napm_bits) {
1451 			n = sprintf(bufpos, "%02lx.\n", apid);
1452 			bufpos += n;
1453 			nchars += n;
1454 		}
1455 	} else if (apqi1 < naqm_bits) {
1456 		for_each_set_bit_inv(apqi, matrix->aqm, naqm_bits) {
1457 			n = sprintf(bufpos, ".%04lx\n", apqi);
1458 			bufpos += n;
1459 			nchars += n;
1460 		}
1461 	}
1462 
1463 	return nchars;
1464 }
1465 
1466 static ssize_t matrix_show(struct device *dev, struct device_attribute *attr,
1467 			   char *buf)
1468 {
1469 	ssize_t nchars;
1470 	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
1471 
1472 	mutex_lock(&matrix_dev->mdevs_lock);
1473 	nchars = vfio_ap_mdev_matrix_show(&matrix_mdev->matrix, buf);
1474 	mutex_unlock(&matrix_dev->mdevs_lock);
1475 
1476 	return nchars;
1477 }
1478 static DEVICE_ATTR_RO(matrix);
1479 
1480 static ssize_t guest_matrix_show(struct device *dev,
1481 				 struct device_attribute *attr, char *buf)
1482 {
1483 	ssize_t nchars;
1484 	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
1485 
1486 	mutex_lock(&matrix_dev->mdevs_lock);
1487 	nchars = vfio_ap_mdev_matrix_show(&matrix_mdev->shadow_apcb, buf);
1488 	mutex_unlock(&matrix_dev->mdevs_lock);
1489 
1490 	return nchars;
1491 }
1492 static DEVICE_ATTR_RO(guest_matrix);
1493 
1494 static struct attribute *vfio_ap_mdev_attrs[] = {
1495 	&dev_attr_assign_adapter.attr,
1496 	&dev_attr_unassign_adapter.attr,
1497 	&dev_attr_assign_domain.attr,
1498 	&dev_attr_unassign_domain.attr,
1499 	&dev_attr_assign_control_domain.attr,
1500 	&dev_attr_unassign_control_domain.attr,
1501 	&dev_attr_control_domains.attr,
1502 	&dev_attr_matrix.attr,
1503 	&dev_attr_guest_matrix.attr,
1504 	NULL,
1505 };
1506 
1507 static struct attribute_group vfio_ap_mdev_attr_group = {
1508 	.attrs = vfio_ap_mdev_attrs
1509 };
1510 
1511 static const struct attribute_group *vfio_ap_mdev_attr_groups[] = {
1512 	&vfio_ap_mdev_attr_group,
1513 	NULL
1514 };
1515 
1516 /**
1517  * vfio_ap_mdev_set_kvm - sets all data for @matrix_mdev that are needed
1518  * to manage AP resources for the guest whose state is represented by @kvm
1519  *
1520  * @matrix_mdev: a mediated matrix device
1521  * @kvm: reference to KVM instance
1522  *
1523  * Return: 0 if no other mediated matrix device has a reference to @kvm;
1524  * otherwise, returns an -EPERM.
1525  */
1526 static int vfio_ap_mdev_set_kvm(struct ap_matrix_mdev *matrix_mdev,
1527 				struct kvm *kvm)
1528 {
1529 	struct ap_matrix_mdev *m;
1530 
1531 	if (kvm->arch.crypto.crycbd) {
1532 		down_write(&kvm->arch.crypto.pqap_hook_rwsem);
1533 		kvm->arch.crypto.pqap_hook = &matrix_mdev->pqap_hook;
1534 		up_write(&kvm->arch.crypto.pqap_hook_rwsem);
1535 
1536 		get_update_locks_for_kvm(kvm);
1537 
1538 		list_for_each_entry(m, &matrix_dev->mdev_list, node) {
1539 			if (m != matrix_mdev && m->kvm == kvm) {
1540 				release_update_locks_for_kvm(kvm);
1541 				return -EPERM;
1542 			}
1543 		}
1544 
1545 		kvm_get_kvm(kvm);
1546 		matrix_mdev->kvm = kvm;
1547 		vfio_ap_mdev_update_guest_apcb(matrix_mdev);
1548 
1549 		release_update_locks_for_kvm(kvm);
1550 	}
1551 
1552 	return 0;
1553 }
1554 
1555 static void vfio_ap_mdev_dma_unmap(struct vfio_device *vdev, u64 iova,
1556 				   u64 length)
1557 {
1558 	struct ap_matrix_mdev *matrix_mdev =
1559 		container_of(vdev, struct ap_matrix_mdev, vdev);
1560 
1561 	vfio_unpin_pages(&matrix_mdev->vdev, iova, 1);
1562 }
1563 
1564 /**
1565  * vfio_ap_mdev_unset_kvm - performs clean-up of resources no longer needed
1566  * by @matrix_mdev.
1567  *
1568  * @matrix_mdev: a matrix mediated device
1569  */
1570 static void vfio_ap_mdev_unset_kvm(struct ap_matrix_mdev *matrix_mdev)
1571 {
1572 	struct kvm *kvm = matrix_mdev->kvm;
1573 
1574 	if (kvm && kvm->arch.crypto.crycbd) {
1575 		down_write(&kvm->arch.crypto.pqap_hook_rwsem);
1576 		kvm->arch.crypto.pqap_hook = NULL;
1577 		up_write(&kvm->arch.crypto.pqap_hook_rwsem);
1578 
1579 		get_update_locks_for_kvm(kvm);
1580 
1581 		kvm_arch_crypto_clear_masks(kvm);
1582 		vfio_ap_mdev_reset_queues(&matrix_mdev->qtable);
1583 		kvm_put_kvm(kvm);
1584 		matrix_mdev->kvm = NULL;
1585 
1586 		release_update_locks_for_kvm(kvm);
1587 	}
1588 }
1589 
1590 static struct vfio_ap_queue *vfio_ap_find_queue(int apqn)
1591 {
1592 	struct ap_queue *queue;
1593 	struct vfio_ap_queue *q = NULL;
1594 
1595 	queue = ap_get_qdev(apqn);
1596 	if (!queue)
1597 		return NULL;
1598 
1599 	if (queue->ap_dev.device.driver == &matrix_dev->vfio_ap_drv->driver)
1600 		q = dev_get_drvdata(&queue->ap_dev.device);
1601 
1602 	put_device(&queue->ap_dev.device);
1603 
1604 	return q;
1605 }
1606 
1607 static int vfio_ap_mdev_reset_queue(struct vfio_ap_queue *q,
1608 				    unsigned int retry)
1609 {
1610 	struct ap_queue_status status;
1611 	int ret;
1612 	int retry2 = 2;
1613 
1614 	if (!q)
1615 		return 0;
1616 retry_zapq:
1617 	status = ap_zapq(q->apqn);
1618 	q->reset_rc = status.response_code;
1619 	switch (status.response_code) {
1620 	case AP_RESPONSE_NORMAL:
1621 		ret = 0;
1622 		break;
1623 	case AP_RESPONSE_RESET_IN_PROGRESS:
1624 		if (retry--) {
1625 			msleep(20);
1626 			goto retry_zapq;
1627 		}
1628 		ret = -EBUSY;
1629 		break;
1630 	case AP_RESPONSE_Q_NOT_AVAIL:
1631 	case AP_RESPONSE_DECONFIGURED:
1632 	case AP_RESPONSE_CHECKSTOPPED:
1633 		WARN_ONCE(status.irq_enabled,
1634 			  "PQAP/ZAPQ for %02x.%04x failed with rc=%u while IRQ enabled",
1635 			  AP_QID_CARD(q->apqn), AP_QID_QUEUE(q->apqn),
1636 			  status.response_code);
1637 		ret = -EBUSY;
1638 		goto free_resources;
1639 	default:
1640 		/* things are really broken, give up */
1641 		WARN(true,
1642 		     "PQAP/ZAPQ for %02x.%04x failed with invalid rc=%u\n",
1643 		     AP_QID_CARD(q->apqn), AP_QID_QUEUE(q->apqn),
1644 		     status.response_code);
1645 		return -EIO;
1646 	}
1647 
1648 	/* wait for the reset to take effect */
1649 	while (retry2--) {
1650 		if (status.queue_empty && !status.irq_enabled)
1651 			break;
1652 		msleep(20);
1653 		status = ap_tapq(q->apqn, NULL);
1654 	}
1655 	WARN_ONCE(retry2 <= 0, "unable to verify reset of queue %02x.%04x",
1656 		  AP_QID_CARD(q->apqn), AP_QID_QUEUE(q->apqn));
1657 
1658 free_resources:
1659 	vfio_ap_free_aqic_resources(q);
1660 
1661 	return ret;
1662 }
1663 
1664 static int vfio_ap_mdev_reset_queues(struct ap_queue_table *qtable)
1665 {
1666 	int ret, loop_cursor, rc = 0;
1667 	struct vfio_ap_queue *q;
1668 
1669 	hash_for_each(qtable->queues, loop_cursor, q, mdev_qnode) {
1670 		ret = vfio_ap_mdev_reset_queue(q, 1);
1671 		/*
1672 		 * Regardless whether a queue turns out to be busy, or
1673 		 * is not operational, we need to continue resetting
1674 		 * the remaining queues.
1675 		 */
1676 		if (ret)
1677 			rc = ret;
1678 	}
1679 
1680 	return rc;
1681 }
1682 
1683 static int vfio_ap_mdev_open_device(struct vfio_device *vdev)
1684 {
1685 	struct ap_matrix_mdev *matrix_mdev =
1686 		container_of(vdev, struct ap_matrix_mdev, vdev);
1687 
1688 	if (!vdev->kvm)
1689 		return -EINVAL;
1690 
1691 	return vfio_ap_mdev_set_kvm(matrix_mdev, vdev->kvm);
1692 }
1693 
1694 static void vfio_ap_mdev_close_device(struct vfio_device *vdev)
1695 {
1696 	struct ap_matrix_mdev *matrix_mdev =
1697 		container_of(vdev, struct ap_matrix_mdev, vdev);
1698 
1699 	vfio_ap_mdev_unset_kvm(matrix_mdev);
1700 }
1701 
1702 static int vfio_ap_mdev_get_device_info(unsigned long arg)
1703 {
1704 	unsigned long minsz;
1705 	struct vfio_device_info info;
1706 
1707 	minsz = offsetofend(struct vfio_device_info, num_irqs);
1708 
1709 	if (copy_from_user(&info, (void __user *)arg, minsz))
1710 		return -EFAULT;
1711 
1712 	if (info.argsz < minsz)
1713 		return -EINVAL;
1714 
1715 	info.flags = VFIO_DEVICE_FLAGS_AP | VFIO_DEVICE_FLAGS_RESET;
1716 	info.num_regions = 0;
1717 	info.num_irqs = 0;
1718 
1719 	return copy_to_user((void __user *)arg, &info, minsz) ? -EFAULT : 0;
1720 }
1721 
1722 static ssize_t vfio_ap_mdev_ioctl(struct vfio_device *vdev,
1723 				    unsigned int cmd, unsigned long arg)
1724 {
1725 	struct ap_matrix_mdev *matrix_mdev =
1726 		container_of(vdev, struct ap_matrix_mdev, vdev);
1727 	int ret;
1728 
1729 	mutex_lock(&matrix_dev->mdevs_lock);
1730 	switch (cmd) {
1731 	case VFIO_DEVICE_GET_INFO:
1732 		ret = vfio_ap_mdev_get_device_info(arg);
1733 		break;
1734 	case VFIO_DEVICE_RESET:
1735 		ret = vfio_ap_mdev_reset_queues(&matrix_mdev->qtable);
1736 		break;
1737 	default:
1738 		ret = -EOPNOTSUPP;
1739 		break;
1740 	}
1741 	mutex_unlock(&matrix_dev->mdevs_lock);
1742 
1743 	return ret;
1744 }
1745 
1746 static struct ap_matrix_mdev *vfio_ap_mdev_for_queue(struct vfio_ap_queue *q)
1747 {
1748 	struct ap_matrix_mdev *matrix_mdev;
1749 	unsigned long apid = AP_QID_CARD(q->apqn);
1750 	unsigned long apqi = AP_QID_QUEUE(q->apqn);
1751 
1752 	list_for_each_entry(matrix_mdev, &matrix_dev->mdev_list, node) {
1753 		if (test_bit_inv(apid, matrix_mdev->matrix.apm) &&
1754 		    test_bit_inv(apqi, matrix_mdev->matrix.aqm))
1755 			return matrix_mdev;
1756 	}
1757 
1758 	return NULL;
1759 }
1760 
1761 static ssize_t status_show(struct device *dev,
1762 			   struct device_attribute *attr,
1763 			   char *buf)
1764 {
1765 	ssize_t nchars = 0;
1766 	struct vfio_ap_queue *q;
1767 	struct ap_matrix_mdev *matrix_mdev;
1768 	struct ap_device *apdev = to_ap_dev(dev);
1769 
1770 	mutex_lock(&matrix_dev->mdevs_lock);
1771 	q = dev_get_drvdata(&apdev->device);
1772 	matrix_mdev = vfio_ap_mdev_for_queue(q);
1773 
1774 	if (matrix_mdev) {
1775 		if (matrix_mdev->kvm)
1776 			nchars = scnprintf(buf, PAGE_SIZE, "%s\n",
1777 					   AP_QUEUE_IN_USE);
1778 		else
1779 			nchars = scnprintf(buf, PAGE_SIZE, "%s\n",
1780 					   AP_QUEUE_ASSIGNED);
1781 	} else {
1782 		nchars = scnprintf(buf, PAGE_SIZE, "%s\n",
1783 				   AP_QUEUE_UNASSIGNED);
1784 	}
1785 
1786 	mutex_unlock(&matrix_dev->mdevs_lock);
1787 
1788 	return nchars;
1789 }
1790 
1791 static DEVICE_ATTR_RO(status);
1792 
1793 static struct attribute *vfio_queue_attrs[] = {
1794 	&dev_attr_status.attr,
1795 	NULL,
1796 };
1797 
1798 static const struct attribute_group vfio_queue_attr_group = {
1799 	.attrs = vfio_queue_attrs,
1800 };
1801 
1802 static const struct vfio_device_ops vfio_ap_matrix_dev_ops = {
1803 	.init = vfio_ap_mdev_init_dev,
1804 	.release = vfio_ap_mdev_release_dev,
1805 	.open_device = vfio_ap_mdev_open_device,
1806 	.close_device = vfio_ap_mdev_close_device,
1807 	.ioctl = vfio_ap_mdev_ioctl,
1808 	.dma_unmap = vfio_ap_mdev_dma_unmap,
1809 };
1810 
1811 static struct mdev_driver vfio_ap_matrix_driver = {
1812 	.driver = {
1813 		.name = "vfio_ap_mdev",
1814 		.owner = THIS_MODULE,
1815 		.mod_name = KBUILD_MODNAME,
1816 		.dev_groups = vfio_ap_mdev_attr_groups,
1817 	},
1818 	.probe = vfio_ap_mdev_probe,
1819 	.remove = vfio_ap_mdev_remove,
1820 	.supported_type_groups = vfio_ap_mdev_type_groups,
1821 };
1822 
1823 int vfio_ap_mdev_register(void)
1824 {
1825 	int ret;
1826 
1827 	atomic_set(&matrix_dev->available_instances, MAX_ZDEV_ENTRIES_EXT);
1828 
1829 	ret = mdev_register_driver(&vfio_ap_matrix_driver);
1830 	if (ret)
1831 		return ret;
1832 
1833 	ret = mdev_register_device(&matrix_dev->device, &vfio_ap_matrix_driver);
1834 	if (ret)
1835 		goto err_driver;
1836 	return 0;
1837 
1838 err_driver:
1839 	mdev_unregister_driver(&vfio_ap_matrix_driver);
1840 	return ret;
1841 }
1842 
1843 void vfio_ap_mdev_unregister(void)
1844 {
1845 	mdev_unregister_device(&matrix_dev->device);
1846 	mdev_unregister_driver(&vfio_ap_matrix_driver);
1847 }
1848 
1849 int vfio_ap_mdev_probe_queue(struct ap_device *apdev)
1850 {
1851 	int ret;
1852 	struct vfio_ap_queue *q;
1853 	struct ap_matrix_mdev *matrix_mdev;
1854 
1855 	ret = sysfs_create_group(&apdev->device.kobj, &vfio_queue_attr_group);
1856 	if (ret)
1857 		return ret;
1858 
1859 	q = kzalloc(sizeof(*q), GFP_KERNEL);
1860 	if (!q)
1861 		return -ENOMEM;
1862 
1863 	q->apqn = to_ap_queue(&apdev->device)->qid;
1864 	q->saved_isc = VFIO_AP_ISC_INVALID;
1865 	matrix_mdev = get_update_locks_by_apqn(q->apqn);
1866 
1867 	if (matrix_mdev) {
1868 		vfio_ap_mdev_link_queue(matrix_mdev, q);
1869 
1870 		if (vfio_ap_mdev_filter_matrix(matrix_mdev->matrix.apm,
1871 					       matrix_mdev->matrix.aqm,
1872 					       matrix_mdev))
1873 			vfio_ap_mdev_update_guest_apcb(matrix_mdev);
1874 	}
1875 	dev_set_drvdata(&apdev->device, q);
1876 	release_update_locks_for_mdev(matrix_mdev);
1877 
1878 	return 0;
1879 }
1880 
1881 void vfio_ap_mdev_remove_queue(struct ap_device *apdev)
1882 {
1883 	unsigned long apid, apqi;
1884 	struct vfio_ap_queue *q;
1885 	struct ap_matrix_mdev *matrix_mdev;
1886 
1887 	sysfs_remove_group(&apdev->device.kobj, &vfio_queue_attr_group);
1888 	q = dev_get_drvdata(&apdev->device);
1889 	get_update_locks_for_queue(q);
1890 	matrix_mdev = q->matrix_mdev;
1891 
1892 	if (matrix_mdev) {
1893 		vfio_ap_unlink_queue_fr_mdev(q);
1894 
1895 		apid = AP_QID_CARD(q->apqn);
1896 		apqi = AP_QID_QUEUE(q->apqn);
1897 
1898 		/*
1899 		 * If the queue is assigned to the guest's APCB, then remove
1900 		 * the adapter's APID from the APCB and hot it into the guest.
1901 		 */
1902 		if (test_bit_inv(apid, matrix_mdev->shadow_apcb.apm) &&
1903 		    test_bit_inv(apqi, matrix_mdev->shadow_apcb.aqm)) {
1904 			clear_bit_inv(apid, matrix_mdev->shadow_apcb.apm);
1905 			vfio_ap_mdev_update_guest_apcb(matrix_mdev);
1906 		}
1907 	}
1908 
1909 	vfio_ap_mdev_reset_queue(q, 1);
1910 	dev_set_drvdata(&apdev->device, NULL);
1911 	kfree(q);
1912 	release_update_locks_for_mdev(matrix_mdev);
1913 }
1914 
1915 /**
1916  * vfio_ap_mdev_resource_in_use: check whether any of a set of APQNs is
1917  *				 assigned to a mediated device under the control
1918  *				 of the vfio_ap device driver.
1919  *
1920  * @apm: a bitmap specifying a set of APIDs comprising the APQNs to check.
1921  * @aqm: a bitmap specifying a set of APQIs comprising the APQNs to check.
1922  *
1923  * Return:
1924  *	* -EADDRINUSE if one or more of the APQNs specified via @apm/@aqm are
1925  *	  assigned to a mediated device under the control of the vfio_ap
1926  *	  device driver.
1927  *	* Otherwise, return 0.
1928  */
1929 int vfio_ap_mdev_resource_in_use(unsigned long *apm, unsigned long *aqm)
1930 {
1931 	int ret;
1932 
1933 	mutex_lock(&matrix_dev->guests_lock);
1934 	mutex_lock(&matrix_dev->mdevs_lock);
1935 	ret = vfio_ap_mdev_verify_no_sharing(apm, aqm);
1936 	mutex_unlock(&matrix_dev->mdevs_lock);
1937 	mutex_unlock(&matrix_dev->guests_lock);
1938 
1939 	return ret;
1940 }
1941 
1942 /**
1943  * vfio_ap_mdev_hot_unplug_cfg - hot unplug the adapters, domains and control
1944  *				 domains that have been removed from the host's
1945  *				 AP configuration from a guest.
1946  *
1947  * @matrix_mdev: an ap_matrix_mdev object attached to a KVM guest.
1948  * @aprem: the adapters that have been removed from the host's AP configuration
1949  * @aqrem: the domains that have been removed from the host's AP configuration
1950  * @cdrem: the control domains that have been removed from the host's AP
1951  *	   configuration.
1952  */
1953 static void vfio_ap_mdev_hot_unplug_cfg(struct ap_matrix_mdev *matrix_mdev,
1954 					unsigned long *aprem,
1955 					unsigned long *aqrem,
1956 					unsigned long *cdrem)
1957 {
1958 	int do_hotplug = 0;
1959 
1960 	if (!bitmap_empty(aprem, AP_DEVICES)) {
1961 		do_hotplug |= bitmap_andnot(matrix_mdev->shadow_apcb.apm,
1962 					    matrix_mdev->shadow_apcb.apm,
1963 					    aprem, AP_DEVICES);
1964 	}
1965 
1966 	if (!bitmap_empty(aqrem, AP_DOMAINS)) {
1967 		do_hotplug |= bitmap_andnot(matrix_mdev->shadow_apcb.aqm,
1968 					    matrix_mdev->shadow_apcb.aqm,
1969 					    aqrem, AP_DEVICES);
1970 	}
1971 
1972 	if (!bitmap_empty(cdrem, AP_DOMAINS))
1973 		do_hotplug |= bitmap_andnot(matrix_mdev->shadow_apcb.adm,
1974 					    matrix_mdev->shadow_apcb.adm,
1975 					    cdrem, AP_DOMAINS);
1976 
1977 	if (do_hotplug)
1978 		vfio_ap_mdev_update_guest_apcb(matrix_mdev);
1979 }
1980 
1981 /**
1982  * vfio_ap_mdev_cfg_remove - determines which guests are using the adapters,
1983  *			     domains and control domains that have been removed
1984  *			     from the host AP configuration and unplugs them
1985  *			     from those guests.
1986  *
1987  * @ap_remove:	bitmap specifying which adapters have been removed from the host
1988  *		config.
1989  * @aq_remove:	bitmap specifying which domains have been removed from the host
1990  *		config.
1991  * @cd_remove:	bitmap specifying which control domains have been removed from
1992  *		the host config.
1993  */
1994 static void vfio_ap_mdev_cfg_remove(unsigned long *ap_remove,
1995 				    unsigned long *aq_remove,
1996 				    unsigned long *cd_remove)
1997 {
1998 	struct ap_matrix_mdev *matrix_mdev;
1999 	DECLARE_BITMAP(aprem, AP_DEVICES);
2000 	DECLARE_BITMAP(aqrem, AP_DOMAINS);
2001 	DECLARE_BITMAP(cdrem, AP_DOMAINS);
2002 	int do_remove = 0;
2003 
2004 	list_for_each_entry(matrix_mdev, &matrix_dev->mdev_list, node) {
2005 		mutex_lock(&matrix_mdev->kvm->lock);
2006 		mutex_lock(&matrix_dev->mdevs_lock);
2007 
2008 		do_remove |= bitmap_and(aprem, ap_remove,
2009 					  matrix_mdev->matrix.apm,
2010 					  AP_DEVICES);
2011 		do_remove |= bitmap_and(aqrem, aq_remove,
2012 					  matrix_mdev->matrix.aqm,
2013 					  AP_DOMAINS);
2014 		do_remove |= bitmap_andnot(cdrem, cd_remove,
2015 					     matrix_mdev->matrix.adm,
2016 					     AP_DOMAINS);
2017 
2018 		if (do_remove)
2019 			vfio_ap_mdev_hot_unplug_cfg(matrix_mdev, aprem, aqrem,
2020 						    cdrem);
2021 
2022 		mutex_unlock(&matrix_dev->mdevs_lock);
2023 		mutex_unlock(&matrix_mdev->kvm->lock);
2024 	}
2025 }
2026 
2027 /**
2028  * vfio_ap_mdev_on_cfg_remove - responds to the removal of adapters, domains and
2029  *				control domains from the host AP configuration
2030  *				by unplugging them from the guests that are
2031  *				using them.
2032  * @cur_config_info: the current host AP configuration information
2033  * @prev_config_info: the previous host AP configuration information
2034  */
2035 static void vfio_ap_mdev_on_cfg_remove(struct ap_config_info *cur_config_info,
2036 				       struct ap_config_info *prev_config_info)
2037 {
2038 	int do_remove;
2039 	DECLARE_BITMAP(aprem, AP_DEVICES);
2040 	DECLARE_BITMAP(aqrem, AP_DOMAINS);
2041 	DECLARE_BITMAP(cdrem, AP_DOMAINS);
2042 
2043 	do_remove = bitmap_andnot(aprem,
2044 				  (unsigned long *)prev_config_info->apm,
2045 				  (unsigned long *)cur_config_info->apm,
2046 				  AP_DEVICES);
2047 	do_remove |= bitmap_andnot(aqrem,
2048 				   (unsigned long *)prev_config_info->aqm,
2049 				   (unsigned long *)cur_config_info->aqm,
2050 				   AP_DEVICES);
2051 	do_remove |= bitmap_andnot(cdrem,
2052 				   (unsigned long *)prev_config_info->adm,
2053 				   (unsigned long *)cur_config_info->adm,
2054 				   AP_DEVICES);
2055 
2056 	if (do_remove)
2057 		vfio_ap_mdev_cfg_remove(aprem, aqrem, cdrem);
2058 }
2059 
2060 /**
2061  * vfio_ap_filter_apid_by_qtype: filter APIDs from an AP mask for adapters that
2062  *				 are older than AP type 10 (CEX4).
2063  * @apm: a bitmap of the APIDs to examine
2064  * @aqm: a bitmap of the APQIs of the queues to query for the AP type.
2065  */
2066 static void vfio_ap_filter_apid_by_qtype(unsigned long *apm, unsigned long *aqm)
2067 {
2068 	bool apid_cleared;
2069 	struct ap_queue_status status;
2070 	unsigned long apid, apqi, info;
2071 	int qtype, qtype_mask = 0xff000000;
2072 
2073 	for_each_set_bit_inv(apid, apm, AP_DEVICES) {
2074 		apid_cleared = false;
2075 
2076 		for_each_set_bit_inv(apqi, aqm, AP_DOMAINS) {
2077 			status = ap_test_queue(AP_MKQID(apid, apqi), 1, &info);
2078 			switch (status.response_code) {
2079 			/*
2080 			 * According to the architecture in each case
2081 			 * below, the queue's info should be filled.
2082 			 */
2083 			case AP_RESPONSE_NORMAL:
2084 			case AP_RESPONSE_RESET_IN_PROGRESS:
2085 			case AP_RESPONSE_DECONFIGURED:
2086 			case AP_RESPONSE_CHECKSTOPPED:
2087 			case AP_RESPONSE_BUSY:
2088 				qtype = info & qtype_mask;
2089 
2090 				/*
2091 				 * The vfio_ap device driver only
2092 				 * supports CEX4 and newer adapters, so
2093 				 * remove the APID if the adapter is
2094 				 * older than a CEX4.
2095 				 */
2096 				if (qtype < AP_DEVICE_TYPE_CEX4) {
2097 					clear_bit_inv(apid, apm);
2098 					apid_cleared = true;
2099 				}
2100 
2101 				break;
2102 
2103 			default:
2104 				/*
2105 				 * If we don't know the adapter type,
2106 				 * clear its APID since it can't be
2107 				 * determined whether the vfio_ap
2108 				 * device driver supports it.
2109 				 */
2110 				clear_bit_inv(apid, apm);
2111 				apid_cleared = true;
2112 				break;
2113 			}
2114 
2115 			/*
2116 			 * If we've already cleared the APID from the apm, there
2117 			 * is no need to continue examining the remainin AP
2118 			 * queues to determine the type of the adapter.
2119 			 */
2120 			if (apid_cleared)
2121 				continue;
2122 		}
2123 	}
2124 }
2125 
2126 /**
2127  * vfio_ap_mdev_cfg_add - store bitmaps specifying the adapters, domains and
2128  *			  control domains that have been added to the host's
2129  *			  AP configuration for each matrix mdev to which they
2130  *			  are assigned.
2131  *
2132  * @apm_add: a bitmap specifying the adapters that have been added to the AP
2133  *	     configuration.
2134  * @aqm_add: a bitmap specifying the domains that have been added to the AP
2135  *	     configuration.
2136  * @adm_add: a bitmap specifying the control domains that have been added to the
2137  *	     AP configuration.
2138  */
2139 static void vfio_ap_mdev_cfg_add(unsigned long *apm_add, unsigned long *aqm_add,
2140 				 unsigned long *adm_add)
2141 {
2142 	struct ap_matrix_mdev *matrix_mdev;
2143 
2144 	if (list_empty(&matrix_dev->mdev_list))
2145 		return;
2146 
2147 	vfio_ap_filter_apid_by_qtype(apm_add, aqm_add);
2148 
2149 	list_for_each_entry(matrix_mdev, &matrix_dev->mdev_list, node) {
2150 		bitmap_and(matrix_mdev->apm_add,
2151 			   matrix_mdev->matrix.apm, apm_add, AP_DEVICES);
2152 		bitmap_and(matrix_mdev->aqm_add,
2153 			   matrix_mdev->matrix.aqm, aqm_add, AP_DOMAINS);
2154 		bitmap_and(matrix_mdev->adm_add,
2155 			   matrix_mdev->matrix.adm, adm_add, AP_DEVICES);
2156 	}
2157 }
2158 
2159 /**
2160  * vfio_ap_mdev_on_cfg_add - responds to the addition of adapters, domains and
2161  *			     control domains to the host AP configuration
2162  *			     by updating the bitmaps that specify what adapters,
2163  *			     domains and control domains have been added so they
2164  *			     can be hot plugged into the guest when the AP bus
2165  *			     scan completes (see vfio_ap_on_scan_complete
2166  *			     function).
2167  * @cur_config_info: the current AP configuration information
2168  * @prev_config_info: the previous AP configuration information
2169  */
2170 static void vfio_ap_mdev_on_cfg_add(struct ap_config_info *cur_config_info,
2171 				    struct ap_config_info *prev_config_info)
2172 {
2173 	bool do_add;
2174 	DECLARE_BITMAP(apm_add, AP_DEVICES);
2175 	DECLARE_BITMAP(aqm_add, AP_DOMAINS);
2176 	DECLARE_BITMAP(adm_add, AP_DOMAINS);
2177 
2178 	do_add = bitmap_andnot(apm_add,
2179 			       (unsigned long *)cur_config_info->apm,
2180 			       (unsigned long *)prev_config_info->apm,
2181 			       AP_DEVICES);
2182 	do_add |= bitmap_andnot(aqm_add,
2183 				(unsigned long *)cur_config_info->aqm,
2184 				(unsigned long *)prev_config_info->aqm,
2185 				AP_DOMAINS);
2186 	do_add |= bitmap_andnot(adm_add,
2187 				(unsigned long *)cur_config_info->adm,
2188 				(unsigned long *)prev_config_info->adm,
2189 				AP_DOMAINS);
2190 
2191 	if (do_add)
2192 		vfio_ap_mdev_cfg_add(apm_add, aqm_add, adm_add);
2193 }
2194 
2195 /**
2196  * vfio_ap_on_cfg_changed - handles notification of changes to the host AP
2197  *			    configuration.
2198  *
2199  * @cur_cfg_info: the current host AP configuration
2200  * @prev_cfg_info: the previous host AP configuration
2201  */
2202 void vfio_ap_on_cfg_changed(struct ap_config_info *cur_cfg_info,
2203 			    struct ap_config_info *prev_cfg_info)
2204 {
2205 	if (!cur_cfg_info || !prev_cfg_info)
2206 		return;
2207 
2208 	mutex_lock(&matrix_dev->guests_lock);
2209 
2210 	vfio_ap_mdev_on_cfg_remove(cur_cfg_info, prev_cfg_info);
2211 	vfio_ap_mdev_on_cfg_add(cur_cfg_info, prev_cfg_info);
2212 	memcpy(&matrix_dev->info, cur_cfg_info, sizeof(*cur_cfg_info));
2213 
2214 	mutex_unlock(&matrix_dev->guests_lock);
2215 }
2216 
2217 static void vfio_ap_mdev_hot_plug_cfg(struct ap_matrix_mdev *matrix_mdev)
2218 {
2219 	bool do_hotplug = false;
2220 	int filter_domains = 0;
2221 	int filter_adapters = 0;
2222 	DECLARE_BITMAP(apm, AP_DEVICES);
2223 	DECLARE_BITMAP(aqm, AP_DOMAINS);
2224 
2225 	mutex_lock(&matrix_mdev->kvm->lock);
2226 	mutex_lock(&matrix_dev->mdevs_lock);
2227 
2228 	filter_adapters = bitmap_and(apm, matrix_mdev->matrix.apm,
2229 				     matrix_mdev->apm_add, AP_DEVICES);
2230 	filter_domains = bitmap_and(aqm, matrix_mdev->matrix.aqm,
2231 				    matrix_mdev->aqm_add, AP_DOMAINS);
2232 
2233 	if (filter_adapters && filter_domains)
2234 		do_hotplug |= vfio_ap_mdev_filter_matrix(apm, aqm, matrix_mdev);
2235 	else if (filter_adapters)
2236 		do_hotplug |=
2237 			vfio_ap_mdev_filter_matrix(apm,
2238 						   matrix_mdev->shadow_apcb.aqm,
2239 						   matrix_mdev);
2240 	else
2241 		do_hotplug |=
2242 			vfio_ap_mdev_filter_matrix(matrix_mdev->shadow_apcb.apm,
2243 						   aqm, matrix_mdev);
2244 
2245 	if (bitmap_intersects(matrix_mdev->matrix.adm, matrix_mdev->adm_add,
2246 			      AP_DOMAINS))
2247 		do_hotplug |= vfio_ap_mdev_filter_cdoms(matrix_mdev);
2248 
2249 	if (do_hotplug)
2250 		vfio_ap_mdev_update_guest_apcb(matrix_mdev);
2251 
2252 	mutex_unlock(&matrix_dev->mdevs_lock);
2253 	mutex_unlock(&matrix_mdev->kvm->lock);
2254 }
2255 
2256 void vfio_ap_on_scan_complete(struct ap_config_info *new_config_info,
2257 			      struct ap_config_info *old_config_info)
2258 {
2259 	struct ap_matrix_mdev *matrix_mdev;
2260 
2261 	mutex_lock(&matrix_dev->guests_lock);
2262 
2263 	list_for_each_entry(matrix_mdev, &matrix_dev->mdev_list, node) {
2264 		if (bitmap_empty(matrix_mdev->apm_add, AP_DEVICES) &&
2265 		    bitmap_empty(matrix_mdev->aqm_add, AP_DOMAINS) &&
2266 		    bitmap_empty(matrix_mdev->adm_add, AP_DOMAINS))
2267 			continue;
2268 
2269 		vfio_ap_mdev_hot_plug_cfg(matrix_mdev);
2270 		bitmap_clear(matrix_mdev->apm_add, 0, AP_DEVICES);
2271 		bitmap_clear(matrix_mdev->aqm_add, 0, AP_DOMAINS);
2272 		bitmap_clear(matrix_mdev->adm_add, 0, AP_DOMAINS);
2273 	}
2274 
2275 	mutex_unlock(&matrix_dev->guests_lock);
2276 }
2277