vfio_ap_ops.c 40.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// SPDX-License-Identifier: GPL-2.0+
/*
 * Adjunct processor matrix VFIO device driver callbacks.
 *
 * Copyright IBM Corp. 2018
 *
 * Author(s): Tony Krowiak <akrowiak@linux.ibm.com>
 *	      Halil Pasic <pasic@linux.ibm.com>
 *	      Pierre Morel <pmorel@linux.ibm.com>
 */
#include <linux/string.h>
#include <linux/vfio.h>
#include <linux/device.h>
#include <linux/list.h>
#include <linux/ctype.h>
16 17 18
#include <linux/bitops.h>
#include <linux/kvm_host.h>
#include <linux/module.h>
19
#include <linux/uuid.h>
20
#include <asm/kvm.h>
21 22 23
#include <asm/zcrypt.h>

#include "vfio_ap_private.h"
24
#include "vfio_ap_debug.h"
25 26 27 28

#define VFIO_AP_MDEV_TYPE_HWVIRT "passthrough"
#define VFIO_AP_MDEV_NAME_HWVIRT "VFIO AP Passthrough Device"

29
static int vfio_ap_mdev_reset_queues(struct ap_matrix_mdev *matrix_mdev);
30
static struct vfio_ap_queue *vfio_ap_find_queue(int apqn);
31
static const struct vfio_device_ops vfio_ap_matrix_dev_ops;
32

33
static int match_apqn(struct device *dev, const void *data)
34 35 36 37 38 39 40
{
	struct vfio_ap_queue *q = dev_get_drvdata(dev);

	return (q->apqn == *(int *)(data)) ? 1 : 0;
}

/**
41
 * vfio_ap_get_queue - retrieve a queue with a specific APQN from a list
42 43 44 45 46 47 48
 * @matrix_mdev: the associated mediated matrix
 * @apqn: The queue APQN
 *
 * Retrieve a queue with a specific APQN from the list of the
 * devices of the vfio_ap_drv.
 * Verify that the APID and the APQI are set in the matrix.
 *
49
 * Return: the pointer to the associated vfio_ap_queue
50 51 52 53 54 55 56 57 58 59 60 61
 */
static struct vfio_ap_queue *vfio_ap_get_queue(
					struct ap_matrix_mdev *matrix_mdev,
					int apqn)
{
	struct vfio_ap_queue *q;

	if (!test_bit_inv(AP_QID_CARD(apqn), matrix_mdev->matrix.apm))
		return NULL;
	if (!test_bit_inv(AP_QID_QUEUE(apqn), matrix_mdev->matrix.aqm))
		return NULL;

62 63 64
	q = vfio_ap_find_queue(apqn);
	if (q)
		q->matrix_mdev = matrix_mdev;
65 66 67 68 69

	return q;
}

/**
70
 * vfio_ap_wait_for_irqclear - clears the IR bit or gives up after 5 tries
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
 * @apqn: The AP Queue number
 *
 * Checks the IRQ bit for the status of this APQN using ap_tapq.
 * Returns if the ap_tapq function succeeded and the bit is clear.
 * Returns if ap_tapq function failed with invalid, deconfigured or
 * checkstopped AP.
 * Otherwise retries up to 5 times after waiting 20ms.
 */
static void vfio_ap_wait_for_irqclear(int apqn)
{
	struct ap_queue_status status;
	int retry = 5;

	do {
		status = ap_tapq(apqn, NULL);
		switch (status.response_code) {
		case AP_RESPONSE_NORMAL:
		case AP_RESPONSE_RESET_IN_PROGRESS:
			if (!status.irq_enabled)
				return;
J
Joe Perches 已提交
91
			fallthrough;
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
		case AP_RESPONSE_BUSY:
			msleep(20);
			break;
		case AP_RESPONSE_Q_NOT_AVAIL:
		case AP_RESPONSE_DECONFIGURED:
		case AP_RESPONSE_CHECKSTOPPED:
		default:
			WARN_ONCE(1, "%s: tapq rc %02x: %04x\n", __func__,
				  status.response_code, apqn);
			return;
		}
	} while (--retry);

	WARN_ONCE(1, "%s: tapq rc %02x: %04x could not clear IR bit\n",
		  __func__, status.response_code, apqn);
}

/**
110
 * vfio_ap_free_aqic_resources - free vfio_ap_queue resources
111 112 113
 * @q: The vfio_ap_queue
 *
 * Unregisters the ISC in the GIB when the saved ISC not invalid.
114 115
 * Unpins the guest's page holding the NIB when it exists.
 * Resets the saved_pfn and saved_isc to invalid values.
116 117 118
 */
static void vfio_ap_free_aqic_resources(struct vfio_ap_queue *q)
{
119 120 121 122
	if (!q)
		return;
	if (q->saved_isc != VFIO_AP_ISC_INVALID &&
	    !WARN_ON(!(q->matrix_mdev && q->matrix_mdev->kvm))) {
123
		kvm_s390_gisc_unregister(q->matrix_mdev->kvm, q->saved_isc);
124 125 126
		q->saved_isc = VFIO_AP_ISC_INVALID;
	}
	if (q->saved_pfn && !WARN_ON(!q->matrix_mdev)) {
127
		vfio_unpin_pages(&q->matrix_mdev->vdev, &q->saved_pfn, 1);
128 129
		q->saved_pfn = 0;
	}
130 131 132
}

/**
133
 * vfio_ap_irq_disable - disables and clears an ap_queue interrupt
134 135 136 137 138 139 140 141 142 143 144 145 146
 * @q: The vfio_ap_queue
 *
 * Uses ap_aqic to disable the interruption and in case of success, reset
 * in progress or IRQ disable command already proceeded: calls
 * vfio_ap_wait_for_irqclear() to check for the IRQ bit to be clear
 * and calls vfio_ap_free_aqic_resources() to free the resources associated
 * with the AP interrupt handling.
 *
 * In the case the AP is busy, or a reset is in progress,
 * retries after 20ms, up to 5 times.
 *
 * Returns if ap_aqic function failed with invalid, deconfigured or
 * checkstopped AP.
147 148
 *
 * Return: &struct ap_queue_status
149
 */
150
static struct ap_queue_status vfio_ap_irq_disable(struct vfio_ap_queue *q)
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
{
	struct ap_qirq_ctrl aqic_gisa = {};
	struct ap_queue_status status;
	int retries = 5;

	do {
		status = ap_aqic(q->apqn, aqic_gisa, NULL);
		switch (status.response_code) {
		case AP_RESPONSE_OTHERWISE_CHANGED:
		case AP_RESPONSE_NORMAL:
			vfio_ap_wait_for_irqclear(q->apqn);
			goto end_free;
		case AP_RESPONSE_RESET_IN_PROGRESS:
		case AP_RESPONSE_BUSY:
			msleep(20);
			break;
		case AP_RESPONSE_Q_NOT_AVAIL:
		case AP_RESPONSE_DECONFIGURED:
		case AP_RESPONSE_CHECKSTOPPED:
		case AP_RESPONSE_INVALID_ADDRESS:
		default:
			/* All cases in default means AP not operational */
			WARN_ONCE(1, "%s: ap_aqic status %d\n", __func__,
				  status.response_code);
			goto end_free;
		}
	} while (retries--);

	WARN_ONCE(1, "%s: ap_aqic status %d\n", __func__,
		  status.response_code);
end_free:
	vfio_ap_free_aqic_resources(q);
183
	q->matrix_mdev = NULL;
184 185 186
	return status;
}

187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
/**
 * vfio_ap_validate_nib - validate a notification indicator byte (nib) address.
 *
 * @vcpu: the object representing the vcpu executing the PQAP(AQIC) instruction.
 * @nib: the location for storing the nib address.
 * @g_pfn: the location for storing the page frame number of the page containing
 *	   the nib.
 *
 * When the PQAP(AQIC) instruction is executed, general register 2 contains the
 * address of the notification indicator byte (nib) used for IRQ notification.
 * This function parses the nib from gr2 and calculates the page frame
 * number for the guest of the page containing the nib. The values are
 * stored in @nib and @g_pfn respectively.
 *
 * The g_pfn of the nib is then validated to ensure the nib address is valid.
 *
 * Return: returns zero if the nib address is a valid; otherwise, returns
 *	   -EINVAL.
 */
static int vfio_ap_validate_nib(struct kvm_vcpu *vcpu, unsigned long *nib,
				unsigned long *g_pfn)
{
	*nib = vcpu->run->s.regs.gprs[2];
	*g_pfn = *nib >> PAGE_SHIFT;

	if (kvm_is_error_hva(gfn_to_hva(vcpu->kvm, *g_pfn)))
		return -EINVAL;

	return 0;
}

218
/**
219
 * vfio_ap_irq_enable - Enable Interruption for a APQN
220 221
 *
 * @q:	 the vfio_ap_queue holding AQIC parameters
222
 * @isc: the guest ISC to register with the GIB interface
223 224
 * @vcpu: the vcpu object containing the registers specifying the parameters
 *	  passed to the PQAP(AQIC) instruction.
225 226 227 228 229 230 231 232 233 234
 *
 * Pin the NIB saved in *q
 * Register the guest ISC to GIB interface and retrieve the
 * host ISC to issue the host side PQAP/AQIC
 *
 * Response.status may be set to AP_RESPONSE_INVALID_ADDRESS in case the
 * vfio_pin_pages failed.
 *
 * Otherwise return the ap_queue_status returned by the ap_aqic(),
 * all retry handling will be done by the guest.
235 236
 *
 * Return: &struct ap_queue_status
237 238 239
 */
static struct ap_queue_status vfio_ap_irq_enable(struct vfio_ap_queue *q,
						 int isc,
240
						 struct kvm_vcpu *vcpu)
241
{
242
	unsigned long nib;
243 244 245
	struct ap_qirq_ctrl aqic_gisa = {};
	struct ap_queue_status status = {};
	struct kvm_s390_gisa *gisa;
246
	int nisc;
247 248 249 250
	struct kvm *kvm;
	unsigned long h_nib, g_pfn, h_pfn;
	int ret;

251 252 253 254 255 256 257 258 259
	/* Verify that the notification indicator byte address is valid */
	if (vfio_ap_validate_nib(vcpu, &nib, &g_pfn)) {
		VFIO_AP_DBF_WARN("%s: invalid NIB address: nib=%#lx, g_pfn=%#lx, apqn=%#04x\n",
				 __func__, nib, g_pfn, q->apqn);

		status.response_code = AP_RESPONSE_INVALID_ADDRESS;
		return status;
	}

260
	ret = vfio_pin_pages(&q->matrix_mdev->vdev, &g_pfn, 1,
261 262 263 264 265
			     IOMMU_READ | IOMMU_WRITE, &h_pfn);
	switch (ret) {
	case 1:
		break;
	default:
266 267 268 269
		VFIO_AP_DBF_WARN("%s: vfio_pin_pages failed: rc=%d,"
				 "nib=%#lx, g_pfn=%#lx, apqn=%#04x\n",
				 __func__, ret, nib, g_pfn, q->apqn);

270 271 272 273 274 275 276 277 278
		status.response_code = AP_RESPONSE_INVALID_ADDRESS;
		return status;
	}

	kvm = q->matrix_mdev->kvm;
	gisa = kvm->arch.gisa_int.origin;

	h_nib = (h_pfn << PAGE_SHIFT) | (nib & ~PAGE_MASK);
	aqic_gisa.gisc = isc;
279 280 281 282 283 284 285 286 287 288 289

	nisc = kvm_s390_gisc_register(kvm, isc);
	if (nisc < 0) {
		VFIO_AP_DBF_WARN("%s: gisc registration failed: nisc=%d, isc=%d, apqn=%#04x\n",
				 __func__, nisc, isc, q->apqn);

		status.response_code = AP_RESPONSE_INVALID_GISA;
		return status;
	}

	aqic_gisa.isc = nisc;
290 291 292 293 294 295 296 297 298 299 300 301 302
	aqic_gisa.ir = 1;
	aqic_gisa.gisa = (uint64_t)gisa >> 4;

	status = ap_aqic(q->apqn, aqic_gisa, (void *)h_nib);
	switch (status.response_code) {
	case AP_RESPONSE_NORMAL:
		/* See if we did clear older IRQ configuration */
		vfio_ap_free_aqic_resources(q);
		q->saved_pfn = g_pfn;
		q->saved_isc = isc;
		break;
	case AP_RESPONSE_OTHERWISE_CHANGED:
		/* We could not modify IRQ setings: clear new configuration */
303
		vfio_unpin_pages(&q->matrix_mdev->vdev, &g_pfn, 1);
304 305 306 307 308 309 310 311 312
		kvm_s390_gisc_unregister(kvm, isc);
		break;
	default:
		pr_warn("%s: apqn %04x: response: %02x\n", __func__, q->apqn,
			status.response_code);
		vfio_ap_irq_disable(q);
		break;
	}

313 314 315 316 317 318 319 320 321 322
	if (status.response_code != AP_RESPONSE_NORMAL) {
		VFIO_AP_DBF_WARN("%s: PQAP(AQIC) failed with status=%#02x: "
				 "zone=%#x, ir=%#x, gisc=%#x, f=%#x,"
				 "gisa=%#x, isc=%#x, apqn=%#04x\n",
				 __func__, status.response_code,
				 aqic_gisa.zone, aqic_gisa.ir, aqic_gisa.gisc,
				 aqic_gisa.gf, aqic_gisa.gisa, aqic_gisa.isc,
				 q->apqn);
	}

323 324 325
	return status;
}

326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
/**
 * vfio_ap_le_guid_to_be_uuid - convert a little endian guid array into an array
 *				of big endian elements that can be passed by
 *				value to an s390dbf sprintf event function to
 *				format a UUID string.
 *
 * @guid: the object containing the little endian guid
 * @uuid: a six-element array of long values that can be passed by value as
 *	  arguments for a formatting string specifying a UUID.
 *
 * The S390 Debug Feature (s390dbf) allows the use of "%s" in the sprintf
 * event functions if the memory for the passed string is available as long as
 * the debug feature exists. Since a mediated device can be removed at any
 * time, it's name can not be used because %s passes the reference to the string
 * in memory and the reference will go stale once the device is removed .
 *
 * The s390dbf string formatting function allows a maximum of 9 arguments for a
 * message to be displayed in the 'sprintf' view. In order to use the bytes
 * comprising the mediated device's UUID to display the mediated device name,
 * they will have to be converted into an array whose elements can be passed by
 * value to sprintf. For example:
 *
 * guid array: { 83, 78, 17, 62, bb, f1, f0, 47, 91, 4d, 32, a2, 2e, 3a, 88, 04 }
 * mdev name: 62177883-f1bb-47f0-914d-32a22e3a8804
 * array returned: { 62177883, f1bb, 47f0, 914d, 32a2, 2e3a8804 }
 * formatting string: "%08lx-%04lx-%04lx-%04lx-%02lx%04lx"
 */
static void vfio_ap_le_guid_to_be_uuid(guid_t *guid, unsigned long *uuid)
{
	/*
	 * The input guid is ordered in little endian, so it needs to be
	 * reordered for displaying a UUID as a string. This specifies the
	 * guid indices in proper order.
	 */
	uuid[0] = le32_to_cpup((__le32 *)guid);
	uuid[1] = le16_to_cpup((__le16 *)&guid->b[4]);
	uuid[2] = le16_to_cpup((__le16 *)&guid->b[6]);
	uuid[3] = *((__u16 *)&guid->b[8]);
	uuid[4] = *((__u16 *)&guid->b[10]);
	uuid[5] = *((__u32 *)&guid->b[12]);
}

368
/**
369
 * handle_pqap - PQAP instruction callback
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
 *
 * @vcpu: The vcpu on which we received the PQAP instruction
 *
 * Get the general register contents to initialize internal variables.
 * REG[0]: APQN
 * REG[1]: IR and ISC
 * REG[2]: NIB
 *
 * Response.status may be set to following Response Code:
 * - AP_RESPONSE_Q_NOT_AVAIL: if the queue is not available
 * - AP_RESPONSE_DECONFIGURED: if the queue is not configured
 * - AP_RESPONSE_NORMAL (0) : in case of successs
 *   Check vfio_ap_setirq() and vfio_ap_clrirq() for other possible RC.
 * We take the matrix_dev lock to ensure serialization on queues and
 * mediated device access.
 *
386 387
 * Return: 0 if we could handle the request inside KVM.
 * Otherwise, returns -EOPNOTSUPP to let QEMU handle the fault.
388 389 390 391 392
 */
static int handle_pqap(struct kvm_vcpu *vcpu)
{
	uint64_t status;
	uint16_t apqn;
393
	unsigned long uuid[6];
394 395 396 397 398
	struct vfio_ap_queue *q;
	struct ap_queue_status qstatus = {
			       .response_code = AP_RESPONSE_Q_NOT_AVAIL, };
	struct ap_matrix_mdev *matrix_mdev;

399 400
	apqn = vcpu->run->s.regs.gprs[0] & 0xffff;

401
	/* If we do not use the AIV facility just go to userland */
402 403 404 405
	if (!(vcpu->arch.sie_block->eca & ECA_AIV)) {
		VFIO_AP_DBF_WARN("%s: AIV facility not installed: apqn=0x%04x, eca=0x%04x\n",
				 __func__, apqn, vcpu->arch.sie_block->eca);

406
		return -EOPNOTSUPP;
407
	}
408 409

	mutex_lock(&matrix_dev->lock);
410 411 412
	if (!vcpu->kvm->arch.crypto.pqap_hook) {
		VFIO_AP_DBF_WARN("%s: PQAP(AQIC) hook not registered with the vfio_ap driver: apqn=0x%04x\n",
				 __func__, apqn);
413
		goto out_unlock;
414 415
	}

416 417 418
	matrix_mdev = container_of(vcpu->kvm->arch.crypto.pqap_hook,
				   struct ap_matrix_mdev, pqap_hook);

419
	/* If the there is no guest using the mdev, there is nothing to do */
420 421 422 423 424
	if (!matrix_mdev->kvm) {
		vfio_ap_le_guid_to_be_uuid(&matrix_mdev->mdev->uuid, uuid);
		VFIO_AP_DBF_WARN("%s: mdev %08lx-%04lx-%04lx-%04lx-%04lx%08lx not in use: apqn=0x%04x\n",
				 __func__, uuid[0],  uuid[1], uuid[2],
				 uuid[3], uuid[4], uuid[5], apqn);
425
		goto out_unlock;
426
	}
427

428
	q = vfio_ap_get_queue(matrix_mdev, apqn);
429 430 431 432
	if (!q) {
		VFIO_AP_DBF_WARN("%s: Queue %02x.%04x not bound to the vfio_ap driver\n",
				 __func__, AP_QID_CARD(apqn),
				 AP_QID_QUEUE(apqn));
433
		goto out_unlock;
434
	}
435 436 437 438 439

	status = vcpu->run->s.regs.gprs[1];

	/* If IR bit(16) is set we enable the interrupt */
	if ((status >> (63 - 16)) & 0x01)
440
		qstatus = vfio_ap_irq_enable(q, status & 0x07, vcpu);
441 442 443 444 445 446 447 448 449 450
	else
		qstatus = vfio_ap_irq_disable(q);

out_unlock:
	memcpy(&vcpu->run->s.regs.gprs[1], &qstatus, sizeof(qstatus));
	vcpu->run->s.regs.gprs[1] >>= 32;
	mutex_unlock(&matrix_dev->lock);
	return 0;
}

451 452 453 454 455 456 457 458
static void vfio_ap_matrix_init(struct ap_config_info *info,
				struct ap_matrix *matrix)
{
	matrix->apm_max = info->apxa ? info->Na : 63;
	matrix->aqm_max = info->apxa ? info->Nd : 15;
	matrix->adm_max = info->apxa ? info->Nd : 15;
}

459
static int vfio_ap_mdev_probe(struct mdev_device *mdev)
460 461
{
	struct ap_matrix_mdev *matrix_mdev;
462
	int ret;
463 464 465 466 467 468

	if ((atomic_dec_if_positive(&matrix_dev->available_instances) < 0))
		return -EPERM;

	matrix_mdev = kzalloc(sizeof(*matrix_mdev), GFP_KERNEL);
	if (!matrix_mdev) {
469 470
		ret = -ENOMEM;
		goto err_dec_available;
471
	}
472 473
	vfio_init_group_dev(&matrix_mdev->vdev, &mdev->dev,
			    &vfio_ap_matrix_dev_ops);
474

475
	matrix_mdev->mdev = mdev;
476
	vfio_ap_matrix_init(&matrix_dev->info, &matrix_mdev->matrix);
477
	matrix_mdev->pqap_hook = handle_pqap;
478 479 480 481
	mutex_lock(&matrix_dev->lock);
	list_add(&matrix_mdev->node, &matrix_dev->mdev_list);
	mutex_unlock(&matrix_dev->lock);

482
	ret = vfio_register_emulated_iommu_dev(&matrix_mdev->vdev);
483 484 485
	if (ret)
		goto err_list;
	dev_set_drvdata(&mdev->dev, matrix_mdev);
486
	return 0;
487 488 489 490 491

err_list:
	mutex_lock(&matrix_dev->lock);
	list_del(&matrix_mdev->node);
	mutex_unlock(&matrix_dev->lock);
492
	vfio_uninit_group_dev(&matrix_mdev->vdev);
493 494 495 496
	kfree(matrix_mdev);
err_dec_available:
	atomic_inc(&matrix_dev->available_instances);
	return ret;
497 498
}

499
static void vfio_ap_mdev_remove(struct mdev_device *mdev)
500
{
501 502 503
	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(&mdev->dev);

	vfio_unregister_group_dev(&matrix_mdev->vdev);
504

505
	mutex_lock(&matrix_dev->lock);
506
	vfio_ap_mdev_reset_queues(matrix_mdev);
507
	list_del(&matrix_mdev->node);
508 509
	mutex_unlock(&matrix_dev->lock);
	vfio_uninit_group_dev(&matrix_mdev->vdev);
510 511 512 513
	kfree(matrix_mdev);
	atomic_inc(&matrix_dev->available_instances);
}

514 515
static ssize_t name_show(struct mdev_type *mtype,
			 struct mdev_type_attribute *attr, char *buf)
516 517 518 519
{
	return sprintf(buf, "%s\n", VFIO_AP_MDEV_NAME_HWVIRT);
}

520
static MDEV_TYPE_ATTR_RO(name);
521

522 523 524
static ssize_t available_instances_show(struct mdev_type *mtype,
					struct mdev_type_attribute *attr,
					char *buf)
525 526 527 528 529
{
	return sprintf(buf, "%d\n",
		       atomic_read(&matrix_dev->available_instances));
}

530
static MDEV_TYPE_ATTR_RO(available_instances);
531

532 533
static ssize_t device_api_show(struct mdev_type *mtype,
			       struct mdev_type_attribute *attr, char *buf)
534 535 536 537
{
	return sprintf(buf, "%s\n", VFIO_DEVICE_API_AP_STRING);
}

538
static MDEV_TYPE_ATTR_RO(device_api);
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556

static struct attribute *vfio_ap_mdev_type_attrs[] = {
	&mdev_type_attr_name.attr,
	&mdev_type_attr_device_api.attr,
	&mdev_type_attr_available_instances.attr,
	NULL,
};

static struct attribute_group vfio_ap_mdev_hwvirt_type_group = {
	.name = VFIO_AP_MDEV_TYPE_HWVIRT,
	.attrs = vfio_ap_mdev_type_attrs,
};

static struct attribute_group *vfio_ap_mdev_type_groups[] = {
	&vfio_ap_mdev_hwvirt_type_group,
	NULL,
};

557 558 559 560 561 562 563
struct vfio_ap_queue_reserved {
	unsigned long *apid;
	unsigned long *apqi;
	bool reserved;
};

/**
564
 * vfio_ap_has_queue - determines if the AP queue containing the target in @data
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
 *
 * @dev: an AP queue device
 * @data: a struct vfio_ap_queue_reserved reference
 *
 * Flags whether the AP queue device (@dev) has a queue ID containing the APQN,
 * apid or apqi specified in @data:
 *
 * - If @data contains both an apid and apqi value, then @data will be flagged
 *   as reserved if the APID and APQI fields for the AP queue device matches
 *
 * - If @data contains only an apid value, @data will be flagged as
 *   reserved if the APID field in the AP queue device matches
 *
 * - If @data contains only an apqi value, @data will be flagged as
 *   reserved if the APQI field in the AP queue device matches
 *
581
 * Return: 0 to indicate the input to function succeeded. Returns -EINVAL if
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
 * @data does not contain either an apid or apqi.
 */
static int vfio_ap_has_queue(struct device *dev, void *data)
{
	struct vfio_ap_queue_reserved *qres = data;
	struct ap_queue *ap_queue = to_ap_queue(dev);
	ap_qid_t qid;
	unsigned long id;

	if (qres->apid && qres->apqi) {
		qid = AP_MKQID(*qres->apid, *qres->apqi);
		if (qid == ap_queue->qid)
			qres->reserved = true;
	} else if (qres->apid && !qres->apqi) {
		id = AP_QID_CARD(ap_queue->qid);
		if (id == *qres->apid)
			qres->reserved = true;
	} else if (!qres->apid && qres->apqi) {
		id = AP_QID_QUEUE(ap_queue->qid);
		if (id == *qres->apqi)
			qres->reserved = true;
	} else {
		return -EINVAL;
	}

	return 0;
}

/**
611 612
 * vfio_ap_verify_queue_reserved - verifies that the AP queue containing
 * @apid or @aqpi is reserved
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
 *
 * @apid: an AP adapter ID
 * @apqi: an AP queue index
 *
 * Verifies that the AP queue with @apid/@apqi is reserved by the VFIO AP device
 * driver according to the following rules:
 *
 * - If both @apid and @apqi are not NULL, then there must be an AP queue
 *   device bound to the vfio_ap driver with the APQN identified by @apid and
 *   @apqi
 *
 * - If only @apid is not NULL, then there must be an AP queue device bound
 *   to the vfio_ap driver with an APQN containing @apid
 *
 * - If only @apqi is not NULL, then there must be an AP queue device bound
 *   to the vfio_ap driver with an APQN containing @apqi
 *
630
 * Return: 0 if the AP queue is reserved; otherwise, returns -EADDRNOTAVAIL.
631 632 633 634 635 636 637 638 639 640 641
 */
static int vfio_ap_verify_queue_reserved(unsigned long *apid,
					 unsigned long *apqi)
{
	int ret;
	struct vfio_ap_queue_reserved qres;

	qres.apid = apid;
	qres.apqi = apqi;
	qres.reserved = false;

642 643
	ret = driver_for_each_device(&matrix_dev->vfio_ap_drv->driver, NULL,
				     &qres, vfio_ap_has_queue);
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
	if (ret)
		return ret;

	if (qres.reserved)
		return 0;

	return -EADDRNOTAVAIL;
}

static int
vfio_ap_mdev_verify_queues_reserved_for_apid(struct ap_matrix_mdev *matrix_mdev,
					     unsigned long apid)
{
	int ret;
	unsigned long apqi;
	unsigned long nbits = matrix_mdev->matrix.aqm_max + 1;

	if (find_first_bit_inv(matrix_mdev->matrix.aqm, nbits) >= nbits)
		return vfio_ap_verify_queue_reserved(&apid, NULL);

	for_each_set_bit_inv(apqi, matrix_mdev->matrix.aqm, nbits) {
		ret = vfio_ap_verify_queue_reserved(&apid, &apqi);
		if (ret)
			return ret;
	}

	return 0;
}

/**
674 675 676
 * vfio_ap_mdev_verify_no_sharing - verifies that the AP matrix is not configured
 *
 * @matrix_mdev: the mediated matrix device
677 678 679 680 681
 *
 * Verifies that the APQNs derived from the cross product of the AP adapter IDs
 * and AP queue indexes comprising the AP matrix are not configured for another
 * mediated device. AP queue sharing is not allowed.
 *
682
 * Return: 0 if the APQNs are not shared; otherwise returns -EADDRINUSE.
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
 */
static int vfio_ap_mdev_verify_no_sharing(struct ap_matrix_mdev *matrix_mdev)
{
	struct ap_matrix_mdev *lstdev;
	DECLARE_BITMAP(apm, AP_DEVICES);
	DECLARE_BITMAP(aqm, AP_DOMAINS);

	list_for_each_entry(lstdev, &matrix_dev->mdev_list, node) {
		if (matrix_mdev == lstdev)
			continue;

		memset(apm, 0, sizeof(apm));
		memset(aqm, 0, sizeof(aqm));

		/*
		 * We work on full longs, as we can only exclude the leftover
		 * bits in non-inverse order. The leftover is all zeros.
		 */
		if (!bitmap_and(apm, matrix_mdev->matrix.apm,
				lstdev->matrix.apm, AP_DEVICES))
			continue;

		if (!bitmap_and(aqm, matrix_mdev->matrix.aqm,
				lstdev->matrix.aqm, AP_DOMAINS))
			continue;

		return -EADDRINUSE;
	}

	return 0;
}

/**
716 717
 * assign_adapter_store - parses the APID from @buf and sets the
 * corresponding bit in the mediated matrix device's APM
718 719 720 721 722 723 724
 *
 * @dev:	the matrix device
 * @attr:	the mediated matrix device's assign_adapter attribute
 * @buf:	a buffer containing the AP adapter number (APID) to
 *		be assigned
 * @count:	the number of bytes in @buf
 *
725
 * Return: the number of bytes processed if the APID is valid; otherwise,
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
 * returns one of the following errors:
 *
 *	1. -EINVAL
 *	   The APID is not a valid number
 *
 *	2. -ENODEV
 *	   The APID exceeds the maximum value configured for the system
 *
 *	3. -EADDRNOTAVAIL
 *	   An APQN derived from the cross product of the APID being assigned
 *	   and the APQIs previously assigned is not bound to the vfio_ap device
 *	   driver; or, if no APQIs have yet been assigned, the APID is not
 *	   contained in an APQN bound to the vfio_ap device driver.
 *
 *	4. -EADDRINUSE
 *	   An APQN derived from the cross product of the APID being assigned
 *	   and the APQIs previously assigned is being used by another mediated
 *	   matrix device
 */
static ssize_t assign_adapter_store(struct device *dev,
				    struct device_attribute *attr,
				    const char *buf, size_t count)
{
	int ret;
	unsigned long apid;
751
	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
752

753 754
	mutex_lock(&matrix_dev->lock);

755 756
	/* If the KVM guest is running, disallow assignment of adapter */
	if (matrix_mdev->kvm) {
757 758 759
		ret = -EBUSY;
		goto done;
	}
760

761 762
	ret = kstrtoul(buf, 0, &apid);
	if (ret)
763
		goto done;
764

765 766 767 768
	if (apid > matrix_mdev->matrix.apm_max) {
		ret = -ENODEV;
		goto done;
	}
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797

	/*
	 * Set the bit in the AP mask (APM) corresponding to the AP adapter
	 * number (APID). The bits in the mask, from most significant to least
	 * significant bit, correspond to APIDs 0-255.
	 */
	ret = vfio_ap_mdev_verify_queues_reserved_for_apid(matrix_mdev, apid);
	if (ret)
		goto done;

	set_bit_inv(apid, matrix_mdev->matrix.apm);

	ret = vfio_ap_mdev_verify_no_sharing(matrix_mdev);
	if (ret)
		goto share_err;

	ret = count;
	goto done;

share_err:
	clear_bit_inv(apid, matrix_mdev->matrix.apm);
done:
	mutex_unlock(&matrix_dev->lock);

	return ret;
}
static DEVICE_ATTR_WO(assign_adapter);

/**
798 799
 * unassign_adapter_store - parses the APID from @buf and clears the
 * corresponding bit in the mediated matrix device's APM
800 801 802 803 804 805
 *
 * @dev:	the matrix device
 * @attr:	the mediated matrix device's unassign_adapter attribute
 * @buf:	a buffer containing the adapter number (APID) to be unassigned
 * @count:	the number of bytes in @buf
 *
806
 * Return: the number of bytes processed if the APID is valid; otherwise,
807 808 809 810 811 812 813 814 815 816 817
 * returns one of the following errors:
 *	-EINVAL if the APID is not a number
 *	-ENODEV if the APID it exceeds the maximum value configured for the
 *		system
 */
static ssize_t unassign_adapter_store(struct device *dev,
				      struct device_attribute *attr,
				      const char *buf, size_t count)
{
	int ret;
	unsigned long apid;
818
	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
819

820 821
	mutex_lock(&matrix_dev->lock);

822 823
	/* If the KVM guest is running, disallow unassignment of adapter */
	if (matrix_mdev->kvm) {
824 825 826
		ret = -EBUSY;
		goto done;
	}
827

828 829
	ret = kstrtoul(buf, 0, &apid);
	if (ret)
830
		goto done;
831

832 833 834 835
	if (apid > matrix_mdev->matrix.apm_max) {
		ret = -ENODEV;
		goto done;
	}
836 837

	clear_bit_inv((unsigned long)apid, matrix_mdev->matrix.apm);
838 839
	ret = count;
done:
840
	mutex_unlock(&matrix_dev->lock);
841
	return ret;
842
}
843
static DEVICE_ATTR_WO(unassign_adapter);
844

845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
static int
vfio_ap_mdev_verify_queues_reserved_for_apqi(struct ap_matrix_mdev *matrix_mdev,
					     unsigned long apqi)
{
	int ret;
	unsigned long apid;
	unsigned long nbits = matrix_mdev->matrix.apm_max + 1;

	if (find_first_bit_inv(matrix_mdev->matrix.apm, nbits) >= nbits)
		return vfio_ap_verify_queue_reserved(NULL, &apqi);

	for_each_set_bit_inv(apid, matrix_mdev->matrix.apm, nbits) {
		ret = vfio_ap_verify_queue_reserved(&apid, &apqi);
		if (ret)
			return ret;
	}

	return 0;
}

/**
866 867 868
 * assign_domain_store - parses the APQI from @buf and sets the
 * corresponding bit in the mediated matrix device's AQM
 *
869 870 871 872 873 874
 * @dev:	the matrix device
 * @attr:	the mediated matrix device's assign_domain attribute
 * @buf:	a buffer containing the AP queue index (APQI) of the domain to
 *		be assigned
 * @count:	the number of bytes in @buf
 *
875
 * Return: the number of bytes processed if the APQI is valid; otherwise returns
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
 * one of the following errors:
 *
 *	1. -EINVAL
 *	   The APQI is not a valid number
 *
 *	2. -ENODEV
 *	   The APQI exceeds the maximum value configured for the system
 *
 *	3. -EADDRNOTAVAIL
 *	   An APQN derived from the cross product of the APQI being assigned
 *	   and the APIDs previously assigned is not bound to the vfio_ap device
 *	   driver; or, if no APIDs have yet been assigned, the APQI is not
 *	   contained in an APQN bound to the vfio_ap device driver.
 *
 *	4. -EADDRINUSE
 *	   An APQN derived from the cross product of the APQI being assigned
 *	   and the APIDs previously assigned is being used by another mediated
 *	   matrix device
 */
static ssize_t assign_domain_store(struct device *dev,
				   struct device_attribute *attr,
				   const char *buf, size_t count)
{
	int ret;
	unsigned long apqi;
901
	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
902 903
	unsigned long max_apqi = matrix_mdev->matrix.aqm_max;

904 905
	mutex_lock(&matrix_dev->lock);

906 907
	/* If the KVM guest is running, disallow assignment of domain */
	if (matrix_mdev->kvm) {
908 909 910
		ret = -EBUSY;
		goto done;
	}
911

912 913
	ret = kstrtoul(buf, 0, &apqi);
	if (ret)
914 915 916 917 918
		goto done;
	if (apqi > max_apqi) {
		ret = -ENODEV;
		goto done;
	}
919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939

	ret = vfio_ap_mdev_verify_queues_reserved_for_apqi(matrix_mdev, apqi);
	if (ret)
		goto done;

	set_bit_inv(apqi, matrix_mdev->matrix.aqm);

	ret = vfio_ap_mdev_verify_no_sharing(matrix_mdev);
	if (ret)
		goto share_err;

	ret = count;
	goto done;

share_err:
	clear_bit_inv(apqi, matrix_mdev->matrix.aqm);
done:
	mutex_unlock(&matrix_dev->lock);

	return ret;
}
940
static DEVICE_ATTR_WO(assign_domain);
941 942 943


/**
944 945
 * unassign_domain_store - parses the APQI from @buf and clears the
 * corresponding bit in the mediated matrix device's AQM
946 947 948 949 950 951 952
 *
 * @dev:	the matrix device
 * @attr:	the mediated matrix device's unassign_domain attribute
 * @buf:	a buffer containing the AP queue index (APQI) of the domain to
 *		be unassigned
 * @count:	the number of bytes in @buf
 *
953
 * Return: the number of bytes processed if the APQI is valid; otherwise,
954 955 956 957 958 959 960 961 962 963
 * returns one of the following errors:
 *	-EINVAL if the APQI is not a number
 *	-ENODEV if the APQI exceeds the maximum value configured for the system
 */
static ssize_t unassign_domain_store(struct device *dev,
				     struct device_attribute *attr,
				     const char *buf, size_t count)
{
	int ret;
	unsigned long apqi;
964
	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
965

966 967
	mutex_lock(&matrix_dev->lock);

968 969
	/* If the KVM guest is running, disallow unassignment of domain */
	if (matrix_mdev->kvm) {
970 971 972
		ret = -EBUSY;
		goto done;
	}
973

974 975
	ret = kstrtoul(buf, 0, &apqi);
	if (ret)
976
		goto done;
977

978 979 980 981
	if (apqi > matrix_mdev->matrix.aqm_max) {
		ret = -ENODEV;
		goto done;
	}
982 983

	clear_bit_inv((unsigned long)apqi, matrix_mdev->matrix.aqm);
984
	ret = count;
985

986 987 988
done:
	mutex_unlock(&matrix_dev->lock);
	return ret;
989
}
990
static DEVICE_ATTR_WO(unassign_domain);
991

992
/**
993 994 995
 * assign_control_domain_store - parses the domain ID from @buf and sets
 * the corresponding bit in the mediated matrix device's ADM
 *
996 997 998 999 1000
 * @dev:	the matrix device
 * @attr:	the mediated matrix device's assign_control_domain attribute
 * @buf:	a buffer containing the domain ID to be assigned
 * @count:	the number of bytes in @buf
 *
1001
 * Return: the number of bytes processed if the domain ID is valid; otherwise,
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
 * returns one of the following errors:
 *	-EINVAL if the ID is not a number
 *	-ENODEV if the ID exceeds the maximum value configured for the system
 */
static ssize_t assign_control_domain_store(struct device *dev,
					   struct device_attribute *attr,
					   const char *buf, size_t count)
{
	int ret;
	unsigned long id;
1012
	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
1013

1014 1015
	mutex_lock(&matrix_dev->lock);

1016 1017
	/* If the KVM guest is running, disallow assignment of control domain */
	if (matrix_mdev->kvm) {
1018 1019 1020
		ret = -EBUSY;
		goto done;
	}
1021

1022 1023
	ret = kstrtoul(buf, 0, &id);
	if (ret)
1024
		goto done;
1025

1026 1027 1028 1029
	if (id > matrix_mdev->matrix.adm_max) {
		ret = -ENODEV;
		goto done;
	}
1030 1031 1032 1033 1034 1035 1036

	/* Set the bit in the ADM (bitmask) corresponding to the AP control
	 * domain number (id). The bits in the mask, from most significant to
	 * least significant, correspond to IDs 0 up to the one less than the
	 * number of control domains that can be assigned.
	 */
	set_bit_inv(id, matrix_mdev->matrix.adm);
1037 1038
	ret = count;
done:
1039
	mutex_unlock(&matrix_dev->lock);
1040
	return ret;
1041
}
1042
static DEVICE_ATTR_WO(assign_control_domain);
1043 1044

/**
1045 1046
 * unassign_control_domain_store - parses the domain ID from @buf and
 * clears the corresponding bit in the mediated matrix device's ADM
1047 1048 1049 1050 1051 1052
 *
 * @dev:	the matrix device
 * @attr:	the mediated matrix device's unassign_control_domain attribute
 * @buf:	a buffer containing the domain ID to be unassigned
 * @count:	the number of bytes in @buf
 *
1053
 * Return: the number of bytes processed if the domain ID is valid; otherwise,
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
 * returns one of the following errors:
 *	-EINVAL if the ID is not a number
 *	-ENODEV if the ID exceeds the maximum value configured for the system
 */
static ssize_t unassign_control_domain_store(struct device *dev,
					     struct device_attribute *attr,
					     const char *buf, size_t count)
{
	int ret;
	unsigned long domid;
1064
	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
1065 1066
	unsigned long max_domid =  matrix_mdev->matrix.adm_max;

1067 1068
	mutex_lock(&matrix_dev->lock);

1069 1070
	/* If a KVM guest is running, disallow unassignment of control domain */
	if (matrix_mdev->kvm) {
1071 1072 1073
		ret = -EBUSY;
		goto done;
	}
1074

1075 1076
	ret = kstrtoul(buf, 0, &domid);
	if (ret)
1077 1078 1079 1080 1081
		goto done;
	if (domid > max_domid) {
		ret = -ENODEV;
		goto done;
	}
1082 1083

	clear_bit_inv(domid, matrix_mdev->matrix.adm);
1084 1085
	ret = count;
done:
1086
	mutex_unlock(&matrix_dev->lock);
1087
	return ret;
1088
}
1089
static DEVICE_ATTR_WO(unassign_control_domain);
1090 1091 1092 1093 1094 1095 1096 1097 1098

static ssize_t control_domains_show(struct device *dev,
				    struct device_attribute *dev_attr,
				    char *buf)
{
	unsigned long id;
	int nchars = 0;
	int n;
	char *bufpos = buf;
1099
	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
	unsigned long max_domid = matrix_mdev->matrix.adm_max;

	mutex_lock(&matrix_dev->lock);
	for_each_set_bit_inv(id, matrix_mdev->matrix.adm, max_domid + 1) {
		n = sprintf(bufpos, "%04lx\n", id);
		bufpos += n;
		nchars += n;
	}
	mutex_unlock(&matrix_dev->lock);

	return nchars;
}
1112
static DEVICE_ATTR_RO(control_domains);
1113

1114 1115 1116
static ssize_t matrix_show(struct device *dev, struct device_attribute *attr,
			   char *buf)
{
1117
	struct ap_matrix_mdev *matrix_mdev = dev_get_drvdata(dev);
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
	char *bufpos = buf;
	unsigned long apid;
	unsigned long apqi;
	unsigned long apid1;
	unsigned long apqi1;
	unsigned long napm_bits = matrix_mdev->matrix.apm_max + 1;
	unsigned long naqm_bits = matrix_mdev->matrix.aqm_max + 1;
	int nchars = 0;
	int n;

	apid1 = find_first_bit_inv(matrix_mdev->matrix.apm, napm_bits);
	apqi1 = find_first_bit_inv(matrix_mdev->matrix.aqm, naqm_bits);

	mutex_lock(&matrix_dev->lock);

	if ((apid1 < napm_bits) && (apqi1 < naqm_bits)) {
		for_each_set_bit_inv(apid, matrix_mdev->matrix.apm, napm_bits) {
			for_each_set_bit_inv(apqi, matrix_mdev->matrix.aqm,
					     naqm_bits) {
				n = sprintf(bufpos, "%02lx.%04lx\n", apid,
					    apqi);
				bufpos += n;
				nchars += n;
			}
		}
	} else if (apid1 < napm_bits) {
		for_each_set_bit_inv(apid, matrix_mdev->matrix.apm, napm_bits) {
			n = sprintf(bufpos, "%02lx.\n", apid);
			bufpos += n;
			nchars += n;
		}
	} else if (apqi1 < naqm_bits) {
		for_each_set_bit_inv(apqi, matrix_mdev->matrix.aqm, naqm_bits) {
			n = sprintf(bufpos, ".%04lx\n", apqi);
			bufpos += n;
			nchars += n;
		}
	}

	mutex_unlock(&matrix_dev->lock);

	return nchars;
}
1161
static DEVICE_ATTR_RO(matrix);
1162

1163 1164 1165
static struct attribute *vfio_ap_mdev_attrs[] = {
	&dev_attr_assign_adapter.attr,
	&dev_attr_unassign_adapter.attr,
1166 1167
	&dev_attr_assign_domain.attr,
	&dev_attr_unassign_domain.attr,
1168 1169 1170
	&dev_attr_assign_control_domain.attr,
	&dev_attr_unassign_control_domain.attr,
	&dev_attr_control_domains.attr,
1171
	&dev_attr_matrix.attr,
1172
	NULL,
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
};

static struct attribute_group vfio_ap_mdev_attr_group = {
	.attrs = vfio_ap_mdev_attrs
};

static const struct attribute_group *vfio_ap_mdev_attr_groups[] = {
	&vfio_ap_mdev_attr_group,
	NULL
};

1184
/**
1185 1186
 * vfio_ap_mdev_set_kvm - sets all data for @matrix_mdev that are needed
 * to manage AP resources for the guest whose state is represented by @kvm
1187 1188 1189 1190
 *
 * @matrix_mdev: a mediated matrix device
 * @kvm: reference to KVM instance
 *
1191
 * Return: 0 if no other mediated matrix device has a reference to @kvm;
1192 1193 1194 1195 1196 1197 1198
 * otherwise, returns an -EPERM.
 */
static int vfio_ap_mdev_set_kvm(struct ap_matrix_mdev *matrix_mdev,
				struct kvm *kvm)
{
	struct ap_matrix_mdev *m;

1199
	if (kvm->arch.crypto.crycbd) {
1200 1201 1202 1203 1204 1205 1206
		down_write(&kvm->arch.crypto.pqap_hook_rwsem);
		kvm->arch.crypto.pqap_hook = &matrix_mdev->pqap_hook;
		up_write(&kvm->arch.crypto.pqap_hook_rwsem);

		mutex_lock(&kvm->lock);
		mutex_lock(&matrix_dev->lock);

1207
		list_for_each_entry(m, &matrix_dev->mdev_list, node) {
1208 1209 1210
			if (m != matrix_mdev && m->kvm == kvm) {
				mutex_unlock(&kvm->lock);
				mutex_unlock(&matrix_dev->lock);
1211
				return -EPERM;
1212
			}
1213
		}
1214

1215
		kvm_get_kvm(kvm);
1216
		matrix_mdev->kvm = kvm;
1217 1218 1219 1220
		kvm_arch_crypto_set_masks(kvm,
					  matrix_mdev->matrix.apm,
					  matrix_mdev->matrix.aqm,
					  matrix_mdev->matrix.adm);
1221

1222 1223
		mutex_unlock(&kvm->lock);
		mutex_unlock(&matrix_dev->lock);
1224
	}
1225 1226 1227 1228

	return 0;
}

1229 1230
/**
 * vfio_ap_mdev_iommu_notifier - IOMMU notifier callback
1231 1232 1233 1234 1235 1236 1237 1238
 *
 * @nb: The notifier block
 * @action: Action to be taken
 * @data: data associated with the request
 *
 * For an UNMAP request, unpin the guest IOVA (the NIB guest address we
 * pinned before). Other requests are ignored.
 *
1239
 * Return: for an UNMAP request, NOFITY_OK; otherwise NOTIFY_DONE.
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
 */
static int vfio_ap_mdev_iommu_notifier(struct notifier_block *nb,
				       unsigned long action, void *data)
{
	struct ap_matrix_mdev *matrix_mdev;

	matrix_mdev = container_of(nb, struct ap_matrix_mdev, iommu_notifier);

	if (action == VFIO_IOMMU_NOTIFY_DMA_UNMAP) {
		struct vfio_iommu_type1_dma_unmap *unmap = data;
		unsigned long g_pfn = unmap->iova >> PAGE_SHIFT;

1252
		vfio_unpin_pages(&matrix_mdev->vdev, &g_pfn, 1);
1253 1254 1255 1256 1257 1258
		return NOTIFY_OK;
	}

	return NOTIFY_DONE;
}

1259
/**
1260 1261
 * vfio_ap_mdev_unset_kvm - performs clean-up of resources no longer needed
 * by @matrix_mdev.
1262 1263 1264
 *
 * @matrix_mdev: a matrix mediated device
 */
1265
static void vfio_ap_mdev_unset_kvm(struct ap_matrix_mdev *matrix_mdev)
1266
{
1267 1268
	struct kvm *kvm = matrix_mdev->kvm;

1269 1270 1271 1272
	if (kvm && kvm->arch.crypto.crycbd) {
		down_write(&kvm->arch.crypto.pqap_hook_rwsem);
		kvm->arch.crypto.pqap_hook = NULL;
		up_write(&kvm->arch.crypto.pqap_hook_rwsem);
1273

1274
		mutex_lock(&kvm->lock);
1275
		mutex_lock(&matrix_dev->lock);
1276 1277

		kvm_arch_crypto_clear_masks(kvm);
1278
		vfio_ap_mdev_reset_queues(matrix_mdev);
1279
		kvm_put_kvm(kvm);
1280
		matrix_mdev->kvm = NULL;
1281 1282 1283

		mutex_unlock(&kvm->lock);
		mutex_unlock(&matrix_dev->lock);
1284
	}
1285 1286
}

1287
static struct vfio_ap_queue *vfio_ap_find_queue(int apqn)
1288 1289
{
	struct device *dev;
1290
	struct vfio_ap_queue *q = NULL;
1291 1292 1293 1294 1295 1296 1297

	dev = driver_find_device(&matrix_dev->vfio_ap_drv->driver, NULL,
				 &apqn, match_apqn);
	if (dev) {
		q = dev_get_drvdata(dev);
		put_device(dev);
	}
1298 1299

	return q;
1300 1301
}

1302
int vfio_ap_mdev_reset_queue(struct vfio_ap_queue *q,
1303
			     unsigned int retry)
1304 1305
{
	struct ap_queue_status status;
1306
	int ret;
1307
	int retry2 = 2;
1308

1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
	if (!q)
		return 0;

retry_zapq:
	status = ap_zapq(q->apqn);
	switch (status.response_code) {
	case AP_RESPONSE_NORMAL:
		ret = 0;
		break;
	case AP_RESPONSE_RESET_IN_PROGRESS:
		if (retry--) {
1320
			msleep(20);
1321
			goto retry_zapq;
1322
		}
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
		ret = -EBUSY;
		break;
	case AP_RESPONSE_Q_NOT_AVAIL:
	case AP_RESPONSE_DECONFIGURED:
	case AP_RESPONSE_CHECKSTOPPED:
		WARN_ON_ONCE(status.irq_enabled);
		ret = -EBUSY;
		goto free_resources;
	default:
		/* things are really broken, give up */
		WARN(true, "PQAP/ZAPQ completed with invalid rc (%x)\n",
		     status.response_code);
		return -EIO;
	}

	/* wait for the reset to take effect */
	while (retry2--) {
		if (status.queue_empty && !status.irq_enabled)
			break;
		msleep(20);
		status = ap_tapq(q->apqn, NULL);
	}
	WARN_ON_ONCE(retry2 <= 0);
1346

1347 1348 1349 1350
free_resources:
	vfio_ap_free_aqic_resources(q);

	return ret;
1351 1352
}

1353
static int vfio_ap_mdev_reset_queues(struct ap_matrix_mdev *matrix_mdev)
1354 1355 1356 1357
{
	int ret;
	int rc = 0;
	unsigned long apid, apqi;
1358
	struct vfio_ap_queue *q;
1359 1360 1361 1362 1363

	for_each_set_bit_inv(apid, matrix_mdev->matrix.apm,
			     matrix_mdev->matrix.apm_max + 1) {
		for_each_set_bit_inv(apqi, matrix_mdev->matrix.aqm,
				     matrix_mdev->matrix.aqm_max + 1) {
1364 1365
			q = vfio_ap_find_queue(AP_MKQID(apid, apqi));
			ret = vfio_ap_mdev_reset_queue(q, 1);
1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
			/*
			 * Regardless whether a queue turns out to be busy, or
			 * is not operational, we need to continue resetting
			 * the remaining queues.
			 */
			if (ret)
				rc = ret;
		}
	}

	return rc;
}

1379
static int vfio_ap_mdev_open_device(struct vfio_device *vdev)
1380
{
1381 1382
	struct ap_matrix_mdev *matrix_mdev =
		container_of(vdev, struct ap_matrix_mdev, vdev);
1383 1384 1385
	unsigned long events;
	int ret;

1386 1387
	if (!vdev->kvm)
		return -EINVAL;
1388

1389
	ret = vfio_ap_mdev_set_kvm(matrix_mdev, vdev->kvm);
1390
	if (ret)
1391 1392
		return ret;

1393 1394
	matrix_mdev->iommu_notifier.notifier_call = vfio_ap_mdev_iommu_notifier;
	events = VFIO_IOMMU_NOTIFY_DMA_UNMAP;
1395 1396
	ret = vfio_register_notifier(vdev, VFIO_IOMMU_NOTIFY, &events,
				     &matrix_mdev->iommu_notifier);
1397
	if (ret)
1398
		goto err_kvm;
1399
	return 0;
1400

1401 1402
err_kvm:
	vfio_ap_mdev_unset_kvm(matrix_mdev);
1403
	return ret;
1404 1405
}

1406
static void vfio_ap_mdev_close_device(struct vfio_device *vdev)
1407
{
1408 1409
	struct ap_matrix_mdev *matrix_mdev =
		container_of(vdev, struct ap_matrix_mdev, vdev);
1410

1411
	vfio_unregister_notifier(vdev, VFIO_IOMMU_NOTIFY,
1412
				 &matrix_mdev->iommu_notifier);
1413
	vfio_ap_mdev_unset_kvm(matrix_mdev);
1414 1415
}

1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
static int vfio_ap_mdev_get_device_info(unsigned long arg)
{
	unsigned long minsz;
	struct vfio_device_info info;

	minsz = offsetofend(struct vfio_device_info, num_irqs);

	if (copy_from_user(&info, (void __user *)arg, minsz))
		return -EFAULT;

	if (info.argsz < minsz)
		return -EINVAL;

1429
	info.flags = VFIO_DEVICE_FLAGS_AP | VFIO_DEVICE_FLAGS_RESET;
1430 1431 1432
	info.num_regions = 0;
	info.num_irqs = 0;

1433
	return copy_to_user((void __user *)arg, &info, minsz) ? -EFAULT : 0;
1434 1435
}

1436
static ssize_t vfio_ap_mdev_ioctl(struct vfio_device *vdev,
1437 1438
				    unsigned int cmd, unsigned long arg)
{
1439 1440
	struct ap_matrix_mdev *matrix_mdev =
		container_of(vdev, struct ap_matrix_mdev, vdev);
1441 1442
	int ret;

1443
	mutex_lock(&matrix_dev->lock);
1444 1445 1446 1447
	switch (cmd) {
	case VFIO_DEVICE_GET_INFO:
		ret = vfio_ap_mdev_get_device_info(arg);
		break;
1448
	case VFIO_DEVICE_RESET:
1449
		ret = vfio_ap_mdev_reset_queues(matrix_mdev);
1450
		break;
1451 1452 1453 1454
	default:
		ret = -EOPNOTSUPP;
		break;
	}
1455
	mutex_unlock(&matrix_dev->lock);
1456 1457 1458 1459

	return ret;
}

1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474
static const struct vfio_device_ops vfio_ap_matrix_dev_ops = {
	.open_device = vfio_ap_mdev_open_device,
	.close_device = vfio_ap_mdev_close_device,
	.ioctl = vfio_ap_mdev_ioctl,
};

static struct mdev_driver vfio_ap_matrix_driver = {
	.driver = {
		.name = "vfio_ap_mdev",
		.owner = THIS_MODULE,
		.mod_name = KBUILD_MODNAME,
		.dev_groups = vfio_ap_mdev_attr_groups,
	},
	.probe = vfio_ap_mdev_probe,
	.remove = vfio_ap_mdev_remove,
1475
	.supported_type_groups = vfio_ap_mdev_type_groups,
1476 1477 1478 1479
};

int vfio_ap_mdev_register(void)
{
1480 1481
	int ret;

1482 1483
	atomic_set(&matrix_dev->available_instances, MAX_ZDEV_ENTRIES_EXT);

1484 1485 1486 1487
	ret = mdev_register_driver(&vfio_ap_matrix_driver);
	if (ret)
		return ret;

1488
	ret = mdev_register_device(&matrix_dev->device, &vfio_ap_matrix_driver);
1489 1490 1491 1492 1493 1494 1495
	if (ret)
		goto err_driver;
	return 0;

err_driver:
	mdev_unregister_driver(&vfio_ap_matrix_driver);
	return ret;
1496 1497 1498 1499 1500
}

void vfio_ap_mdev_unregister(void)
{
	mdev_unregister_device(&matrix_dev->device);
1501
	mdev_unregister_driver(&vfio_ap_matrix_driver);
1502
}