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