xref: /kvmtool/vfio/pci.c (revision 465edc9d0fab23f46e9b83af1403577ba98e1937)
1 #include "kvm/irq.h"
2 #include "kvm/kvm.h"
3 #include "kvm/kvm-cpu.h"
4 #include "kvm/vfio.h"
5 
6 #include <assert.h>
7 
8 #include <sys/ioctl.h>
9 #include <sys/eventfd.h>
10 #include <sys/resource.h>
11 #include <sys/time.h>
12 
13 #include <assert.h>
14 
15 /* Wrapper around UAPI vfio_irq_set */
16 union vfio_irq_eventfd {
17 	struct vfio_irq_set	irq;
18 	u8 buffer[sizeof(struct vfio_irq_set) + sizeof(int)];
19 };
20 
21 static void set_vfio_irq_eventd_payload(union vfio_irq_eventfd *evfd, int fd)
22 {
23 	memcpy(&evfd->irq.data, &fd, sizeof(fd));
24 }
25 
26 #define msi_is_enabled(state)		((state) & VFIO_PCI_MSI_STATE_ENABLED)
27 #define msi_is_masked(state)		((state) & VFIO_PCI_MSI_STATE_MASKED)
28 #define msi_is_empty(state)		((state) & VFIO_PCI_MSI_STATE_EMPTY)
29 
30 #define msi_update_state(state, val, bit)				\
31 	(state) = (val) ? (state) | bit : (state) & ~bit;
32 #define msi_set_enabled(state, val)					\
33 	msi_update_state(state, val, VFIO_PCI_MSI_STATE_ENABLED)
34 #define msi_set_masked(state, val)					\
35 	msi_update_state(state, val, VFIO_PCI_MSI_STATE_MASKED)
36 #define msi_set_empty(state, val)					\
37 	msi_update_state(state, val, VFIO_PCI_MSI_STATE_EMPTY)
38 
39 static void vfio_pci_disable_intx(struct kvm *kvm, struct vfio_device *vdev);
40 static int vfio_pci_enable_intx(struct kvm *kvm, struct vfio_device *vdev);
41 
42 static int vfio_pci_enable_msis(struct kvm *kvm, struct vfio_device *vdev,
43 				bool msix)
44 {
45 	size_t i;
46 	int ret = 0;
47 	int *eventfds;
48 	struct vfio_pci_device *pdev = &vdev->pci;
49 	struct vfio_pci_msi_common *msis = msix ? &pdev->msix : &pdev->msi;
50 	union vfio_irq_eventfd single = {
51 		.irq = {
52 			.argsz	= sizeof(single),
53 			.flags	= VFIO_IRQ_SET_DATA_EVENTFD |
54 				  VFIO_IRQ_SET_ACTION_TRIGGER,
55 			.index	= msis->info.index,
56 			.count	= 1,
57 		},
58 	};
59 
60 	if (!msi_is_enabled(msis->virt_state))
61 		return 0;
62 
63 	if (pdev->irq_modes & VFIO_PCI_IRQ_MODE_INTX)
64 		/*
65 		 * PCI (and VFIO) forbids enabling INTx, MSI or MSIX at the same
66 		 * time. Since INTx has to be enabled from the start (we don't
67 		 * have a reliable way to know when the guest starts using it),
68 		 * disable it now.
69 		 */
70 		vfio_pci_disable_intx(kvm, vdev);
71 
72 	eventfds = (void *)msis->irq_set + sizeof(struct vfio_irq_set);
73 
74 	/*
75 	 * Initial registration of the full range. This enables the physical
76 	 * MSI/MSI-X capability, which might have desired side effects. For
77 	 * instance when assigning virtio legacy devices, enabling the MSI
78 	 * capability modifies the config space layout!
79 	 *
80 	 * As an optimization, only update MSIs when guest unmasks the
81 	 * capability. This greatly reduces the initialization time for Linux
82 	 * guest with 2048+ MSIs. Linux guest starts by enabling the MSI-X cap
83 	 * masked, then fills individual vectors, then unmasks the whole
84 	 * function. So we only do one VFIO ioctl when enabling for the first
85 	 * time, and then one when unmasking.
86 	 *
87 	 * phys_state is empty when it is enabled but no vector has been
88 	 * registered via SET_IRQS yet.
89 	 */
90 	if (!msi_is_enabled(msis->phys_state) ||
91 	    (!msi_is_masked(msis->virt_state) &&
92 	     msi_is_empty(msis->phys_state))) {
93 		bool empty = true;
94 
95 		for (i = 0; i < msis->nr_entries; i++) {
96 			eventfds[i] = msis->entries[i].gsi >= 0 ?
97 				      msis->entries[i].eventfd : -1;
98 
99 			if (eventfds[i] >= 0)
100 				empty = false;
101 		}
102 
103 		ret = ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, msis->irq_set);
104 		if (ret < 0) {
105 			perror("VFIO_DEVICE_SET_IRQS(multi)");
106 			return ret;
107 		}
108 
109 		msi_set_enabled(msis->phys_state, true);
110 		msi_set_empty(msis->phys_state, empty);
111 
112 		return 0;
113 	}
114 
115 	if (msi_is_masked(msis->virt_state)) {
116 		/* TODO: if phys_state is not empty nor masked, mask all vectors */
117 		return 0;
118 	}
119 
120 	/* Update individual vectors to avoid breaking those in use */
121 	for (i = 0; i < msis->nr_entries; i++) {
122 		struct vfio_pci_msi_entry *entry = &msis->entries[i];
123 		int fd = entry->gsi >= 0 ? entry->eventfd : -1;
124 
125 		if (fd == eventfds[i])
126 			continue;
127 
128 		single.irq.start = i;
129 		set_vfio_irq_eventd_payload(&single, fd);
130 
131 		ret = ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, &single);
132 		if (ret < 0) {
133 			perror("VFIO_DEVICE_SET_IRQS(single)");
134 			break;
135 		}
136 
137 		eventfds[i] = fd;
138 
139 		if (msi_is_empty(msis->phys_state) && fd >= 0)
140 			msi_set_empty(msis->phys_state, false);
141 	}
142 
143 	return ret;
144 }
145 
146 static int vfio_pci_disable_msis(struct kvm *kvm, struct vfio_device *vdev,
147 				 bool msix)
148 {
149 	int ret;
150 	struct vfio_pci_device *pdev = &vdev->pci;
151 	struct vfio_pci_msi_common *msis = msix ? &pdev->msix : &pdev->msi;
152 	struct vfio_irq_set irq_set = {
153 		.argsz	= sizeof(irq_set),
154 		.flags 	= VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_TRIGGER,
155 		.index 	= msis->info.index,
156 		.start 	= 0,
157 		.count	= 0,
158 	};
159 
160 	if (!msi_is_enabled(msis->phys_state))
161 		return 0;
162 
163 	ret = ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, &irq_set);
164 	if (ret < 0) {
165 		perror("VFIO_DEVICE_SET_IRQS(NONE)");
166 		return ret;
167 	}
168 
169 	msi_set_enabled(msis->phys_state, false);
170 	msi_set_empty(msis->phys_state, true);
171 
172 	/*
173 	 * When MSI or MSIX is disabled, this might be called when
174 	 * PCI driver detects the MSI interrupt failure and wants to
175 	 * rollback to INTx mode.  Thus enable INTx if the device
176 	 * supports INTx mode in this case.
177 	 */
178 	if (pdev->irq_modes & VFIO_PCI_IRQ_MODE_INTX)
179 		ret = vfio_pci_enable_intx(kvm, vdev);
180 
181 	return ret >= 0 ? 0 : ret;
182 }
183 
184 static int vfio_pci_update_msi_entry(struct kvm *kvm, struct vfio_device *vdev,
185 				     struct vfio_pci_msi_entry *entry)
186 {
187 	int ret;
188 
189 	if (entry->eventfd < 0) {
190 		entry->eventfd = eventfd(0, 0);
191 		if (entry->eventfd < 0) {
192 			ret = -errno;
193 			vfio_dev_err(vdev, "cannot create eventfd");
194 			return ret;
195 		}
196 	}
197 
198 	/* Allocate IRQ if necessary */
199 	if (entry->gsi < 0) {
200 		int ret = irq__add_msix_route(kvm, &entry->config.msg,
201 					      vdev->dev_hdr.dev_num << 3);
202 		if (ret < 0) {
203 			vfio_dev_err(vdev, "cannot create MSI-X route");
204 			return ret;
205 		}
206 		entry->gsi = ret;
207 	} else {
208 		irq__update_msix_route(kvm, entry->gsi, &entry->config.msg);
209 	}
210 
211 	/*
212 	 * MSI masking is unimplemented in VFIO, so we have to handle it by
213 	 * disabling/enabling IRQ route instead. We do it on the KVM side rather
214 	 * than VFIO, because:
215 	 * - it is 8x faster
216 	 * - it allows to decouple masking logic from capability state.
217 	 * - in masked state, after removing irqfd route, we could easily plug
218 	 *   the eventfd in a local handler, in order to serve Pending Bit reads
219 	 *   to the guest.
220 	 *
221 	 * So entry->phys_state is masked when there is no active irqfd route.
222 	 */
223 	if (msi_is_masked(entry->virt_state) == msi_is_masked(entry->phys_state))
224 		return 0;
225 
226 	if (msi_is_masked(entry->phys_state)) {
227 		ret = irq__add_irqfd(kvm, entry->gsi, entry->eventfd, -1);
228 		if (ret < 0) {
229 			vfio_dev_err(vdev, "cannot setup irqfd");
230 			return ret;
231 		}
232 	} else {
233 		irq__del_irqfd(kvm, entry->gsi, entry->eventfd);
234 	}
235 
236 	msi_set_masked(entry->phys_state, msi_is_masked(entry->virt_state));
237 
238 	return 0;
239 }
240 
241 static void vfio_pci_msix_pba_access(struct kvm_cpu *vcpu, u64 addr, u8 *data,
242 				     u32 len, u8 is_write, void *ptr)
243 {
244 	struct vfio_pci_device *pdev = ptr;
245 	struct vfio_pci_msix_pba *pba = &pdev->msix_pba;
246 	u64 offset = addr - pba->guest_phys_addr;
247 	struct vfio_device *vdev = container_of(pdev, struct vfio_device, pci);
248 
249 	if (is_write)
250 		return;
251 
252 	/*
253 	 * TODO: emulate PBA. Hardware MSI-X is never masked, so reading the PBA
254 	 * is completely useless here. Note that Linux doesn't use PBA.
255 	 */
256 	if (pread(vdev->fd, data, len, pba->offset + offset) != (ssize_t)len)
257 		vfio_dev_err(vdev, "cannot access MSIX PBA\n");
258 }
259 
260 static void vfio_pci_msix_table_access(struct kvm_cpu *vcpu, u64 addr, u8 *data,
261 				       u32 len, u8 is_write, void *ptr)
262 {
263 	struct kvm *kvm = vcpu->kvm;
264 	struct vfio_pci_msi_entry *entry;
265 	struct vfio_pci_device *pdev = ptr;
266 	struct vfio_device *vdev = container_of(pdev, struct vfio_device, pci);
267 
268 	u64 offset = addr - pdev->msix_table.guest_phys_addr;
269 
270 	size_t vector = offset / PCI_MSIX_ENTRY_SIZE;
271 	off_t field = offset % PCI_MSIX_ENTRY_SIZE;
272 
273 	/*
274 	 * PCI spec says that software must use aligned 4 or 8 bytes accesses
275 	 * for the MSI-X tables.
276 	 */
277 	if ((len != 4 && len != 8) || addr & (len - 1)) {
278 		vfio_dev_warn(vdev, "invalid MSI-X table access");
279 		return;
280 	}
281 
282 	entry = &pdev->msix.entries[vector];
283 
284 	mutex_lock(&pdev->msix.mutex);
285 
286 	if (!is_write) {
287 		memcpy(data, (void *)&entry->config + field, len);
288 		goto out_unlock;
289 	}
290 
291 	memcpy((void *)&entry->config + field, data, len);
292 
293 	/*
294 	 * Check if access touched the vector control register, which is at the
295 	 * end of the MSI-X entry.
296 	 */
297 	if (field + len <= PCI_MSIX_ENTRY_VECTOR_CTRL)
298 		goto out_unlock;
299 
300 	msi_set_masked(entry->virt_state, entry->config.ctrl &
301 		       PCI_MSIX_ENTRY_CTRL_MASKBIT);
302 
303 	if (vfio_pci_update_msi_entry(kvm, vdev, entry) < 0)
304 		/* Not much we can do here. */
305 		vfio_dev_err(vdev, "failed to configure MSIX vector %zu", vector);
306 
307 	/* Update the physical capability if necessary */
308 	if (vfio_pci_enable_msis(kvm, vdev, true))
309 		vfio_dev_err(vdev, "cannot enable MSIX");
310 
311 out_unlock:
312 	mutex_unlock(&pdev->msix.mutex);
313 }
314 
315 static void vfio_pci_msix_cap_write(struct kvm *kvm,
316 				    struct vfio_device *vdev, u8 off,
317 				    void *data, int sz)
318 {
319 	struct vfio_pci_device *pdev = &vdev->pci;
320 	off_t enable_pos = PCI_MSIX_FLAGS + 1;
321 	bool enable;
322 	u16 flags;
323 
324 	off -= pdev->msix.pos;
325 
326 	/* Check if access intersects with the MSI-X Enable bit */
327 	if (off > enable_pos || off + sz <= enable_pos)
328 		return;
329 
330 	/* Read byte that contains the Enable bit */
331 	flags = *(u8 *)(data + enable_pos - off) << 8;
332 
333 	mutex_lock(&pdev->msix.mutex);
334 
335 	msi_set_masked(pdev->msix.virt_state, flags & PCI_MSIX_FLAGS_MASKALL);
336 	enable = flags & PCI_MSIX_FLAGS_ENABLE;
337 	msi_set_enabled(pdev->msix.virt_state, enable);
338 
339 	if (enable && vfio_pci_enable_msis(kvm, vdev, true))
340 		vfio_dev_err(vdev, "cannot enable MSIX");
341 	else if (!enable && vfio_pci_disable_msis(kvm, vdev, true))
342 		vfio_dev_err(vdev, "cannot disable MSIX");
343 
344 	mutex_unlock(&pdev->msix.mutex);
345 }
346 
347 static int vfio_pci_msi_vector_write(struct kvm *kvm, struct vfio_device *vdev,
348 				     u8 off, u8 *data, u32 sz)
349 {
350 	size_t i;
351 	u32 mask = 0;
352 	size_t mask_pos, start, limit;
353 	struct vfio_pci_msi_entry *entry;
354 	struct vfio_pci_device *pdev = &vdev->pci;
355 	struct msi_cap_64 *msi_cap_64 = PCI_CAP(&pdev->hdr, pdev->msi.pos);
356 
357 	if (!(msi_cap_64->ctrl & PCI_MSI_FLAGS_MASKBIT))
358 		return 0;
359 
360 	if (msi_cap_64->ctrl & PCI_MSI_FLAGS_64BIT)
361 		mask_pos = PCI_MSI_MASK_64;
362 	else
363 		mask_pos = PCI_MSI_MASK_32;
364 
365 	if (off >= mask_pos + 4 || off + sz <= mask_pos)
366 		return 0;
367 
368 	/* Set mask to current state */
369 	for (i = 0; i < pdev->msi.nr_entries; i++) {
370 		entry = &pdev->msi.entries[i];
371 		mask |= !!msi_is_masked(entry->virt_state) << i;
372 	}
373 
374 	/* Update mask following the intersection of access and register */
375 	start = max_t(size_t, off, mask_pos);
376 	limit = min_t(size_t, off + sz, mask_pos + 4);
377 
378 	memcpy((void *)&mask + start - mask_pos, data + start - off,
379 	       limit - start);
380 
381 	/* Update states if necessary */
382 	for (i = 0; i < pdev->msi.nr_entries; i++) {
383 		bool masked = mask & (1 << i);
384 
385 		entry = &pdev->msi.entries[i];
386 		if (masked != msi_is_masked(entry->virt_state)) {
387 			msi_set_masked(entry->virt_state, masked);
388 			vfio_pci_update_msi_entry(kvm, vdev, entry);
389 		}
390 	}
391 
392 	return 1;
393 }
394 
395 static void vfio_pci_msi_cap_write(struct kvm *kvm, struct vfio_device *vdev,
396 				   u8 off, u8 *data, u32 sz)
397 {
398 	u8 ctrl;
399 	struct msi_msg msg;
400 	size_t i, nr_vectors;
401 	struct vfio_pci_msi_entry *entry;
402 	struct vfio_pci_device *pdev = &vdev->pci;
403 	struct msi_cap_64 *msi_cap_64 = PCI_CAP(&pdev->hdr, pdev->msi.pos);
404 
405 	off -= pdev->msi.pos;
406 
407 	mutex_lock(&pdev->msi.mutex);
408 
409 	/* Check if the guest is trying to update mask bits */
410 	if (vfio_pci_msi_vector_write(kvm, vdev, off, data, sz))
411 		goto out_unlock;
412 
413 	/* Only modify routes when guest pokes the enable bit */
414 	if (off > PCI_MSI_FLAGS || off + sz <= PCI_MSI_FLAGS)
415 		goto out_unlock;
416 
417 	ctrl = *(u8 *)(data + PCI_MSI_FLAGS - off);
418 
419 	msi_set_enabled(pdev->msi.virt_state, ctrl & PCI_MSI_FLAGS_ENABLE);
420 
421 	if (!msi_is_enabled(pdev->msi.virt_state)) {
422 		vfio_pci_disable_msis(kvm, vdev, false);
423 		goto out_unlock;
424 	}
425 
426 	/* Create routes for the requested vectors */
427 	nr_vectors = 1 << ((ctrl & PCI_MSI_FLAGS_QSIZE) >> 4);
428 
429 	msg.address_lo = msi_cap_64->address_lo;
430 	if (msi_cap_64->ctrl & PCI_MSI_FLAGS_64BIT) {
431 		msg.address_hi = msi_cap_64->address_hi;
432 		msg.data = msi_cap_64->data;
433 	} else {
434 		struct msi_cap_32 *msi_cap_32 = (void *)msi_cap_64;
435 		msg.address_hi = 0;
436 		msg.data = msi_cap_32->data;
437 	}
438 
439 	for (i = 0; i < nr_vectors; i++) {
440 		entry = &pdev->msi.entries[i];
441 
442 		/*
443 		 * Set the MSI data value as required by the PCI local
444 		 * bus specifications, MSI capability, "Message Data".
445 		 */
446 		msg.data &= ~(nr_vectors - 1);
447 		msg.data |= i;
448 
449 		entry->config.msg = msg;
450 		vfio_pci_update_msi_entry(kvm, vdev, entry);
451 	}
452 
453 	/* Update the physical capability if necessary */
454 	if (vfio_pci_enable_msis(kvm, vdev, false))
455 		vfio_dev_err(vdev, "cannot enable MSI");
456 
457 out_unlock:
458 	mutex_unlock(&pdev->msi.mutex);
459 }
460 
461 static int vfio_pci_bar_activate(struct kvm *kvm,
462 				 struct pci_device_header *pci_hdr,
463 				 int bar_num, void *data)
464 {
465 	struct vfio_device *vdev = data;
466 	struct vfio_pci_device *pdev = &vdev->pci;
467 	struct vfio_pci_msix_pba *pba = &pdev->msix_pba;
468 	struct vfio_pci_msix_table *table = &pdev->msix_table;
469 	struct vfio_region *region;
470 	u32 bar_addr;
471 	bool has_msix;
472 	int ret;
473 
474 	assert((u32)bar_num < vdev->info.num_regions);
475 
476 	region = &vdev->regions[bar_num];
477 	has_msix = pdev->irq_modes & VFIO_PCI_IRQ_MODE_MSIX;
478 
479 	bar_addr = pci__bar_address(pci_hdr, bar_num);
480 	if (pci__bar_is_io(pci_hdr, bar_num))
481 		region->port_base = bar_addr;
482 	else
483 		region->guest_phys_addr = bar_addr;
484 
485 	if (has_msix && (u32)bar_num == table->bar) {
486 		table->guest_phys_addr = region->guest_phys_addr;
487 		ret = kvm__register_mmio(kvm, table->guest_phys_addr,
488 					 table->size, false,
489 					 vfio_pci_msix_table_access, pdev);
490 		/*
491 		 * The MSIX table and the PBA structure can share the same BAR,
492 		 * but for convenience we register different regions for mmio
493 		 * emulation. We want to we update both if they share the same
494 		 * BAR.
495 		 */
496 		if (ret < 0 || table->bar != pba->bar)
497 			goto out;
498 	}
499 
500 	if (has_msix && (u32)bar_num == pba->bar) {
501 		if (pba->bar == table->bar)
502 			pba->guest_phys_addr = table->guest_phys_addr + table->size;
503 		else
504 			pba->guest_phys_addr = region->guest_phys_addr;
505 		ret = kvm__register_mmio(kvm, pba->guest_phys_addr,
506 					 pba->size, false,
507 					 vfio_pci_msix_pba_access, pdev);
508 		goto out;
509 	}
510 
511 	ret = vfio_map_region(kvm, vdev, region);
512 out:
513 	return ret;
514 }
515 
516 static int vfio_pci_bar_deactivate(struct kvm *kvm,
517 				   struct pci_device_header *pci_hdr,
518 				   int bar_num, void *data)
519 {
520 	struct vfio_device *vdev = data;
521 	struct vfio_pci_device *pdev = &vdev->pci;
522 	struct vfio_pci_msix_pba *pba = &pdev->msix_pba;
523 	struct vfio_pci_msix_table *table = &pdev->msix_table;
524 	struct vfio_region *region;
525 	bool has_msix, success;
526 	int ret;
527 
528 	assert((u32)bar_num < vdev->info.num_regions);
529 
530 	region = &vdev->regions[bar_num];
531 	has_msix = pdev->irq_modes & VFIO_PCI_IRQ_MODE_MSIX;
532 
533 	if (has_msix && (u32)bar_num == table->bar) {
534 		success = kvm__deregister_mmio(kvm, table->guest_phys_addr);
535 		/* kvm__deregister_mmio fails when the region is not found. */
536 		ret = (success ? 0 : -ENOENT);
537 		/* See vfio_pci_bar_activate(). */
538 		if (ret < 0 || table->bar!= pba->bar)
539 			goto out;
540 	}
541 
542 	if (has_msix && (u32)bar_num == pba->bar) {
543 		success = kvm__deregister_mmio(kvm, pba->guest_phys_addr);
544 		ret = (success ? 0 : -ENOENT);
545 		goto out;
546 	}
547 
548 	vfio_unmap_region(kvm, region);
549 	ret = 0;
550 
551 out:
552 	return ret;
553 }
554 
555 static void vfio_pci_cfg_read(struct kvm *kvm, struct pci_device_header *pci_hdr,
556 			      u8 offset, void *data, int sz)
557 {
558 	struct vfio_region_info *info;
559 	struct vfio_pci_device *pdev;
560 	struct vfio_device *vdev;
561 	char base[sz];
562 
563 	pdev = container_of(pci_hdr, struct vfio_pci_device, hdr);
564 	vdev = container_of(pdev, struct vfio_device, pci);
565 	info = &vdev->regions[VFIO_PCI_CONFIG_REGION_INDEX].info;
566 
567 	/* Dummy read in case of side-effects */
568 	if (pread(vdev->fd, base, sz, info->offset + offset) != sz)
569 		vfio_dev_warn(vdev, "failed to read %d bytes from Configuration Space at 0x%x",
570 			      sz, offset);
571 }
572 
573 static void vfio_pci_cfg_write(struct kvm *kvm, struct pci_device_header *pci_hdr,
574 			       u8 offset, void *data, int sz)
575 {
576 	struct vfio_region_info *info;
577 	struct vfio_pci_device *pdev;
578 	struct vfio_device *vdev;
579 	u32 tmp;
580 
581 	/* Make sure a larger size will not overrun tmp on the stack. */
582 	assert(sz <= 4);
583 
584 	if (offset == PCI_ROM_ADDRESS)
585 		return;
586 
587 	pdev = container_of(pci_hdr, struct vfio_pci_device, hdr);
588 	vdev = container_of(pdev, struct vfio_device, pci);
589 	info = &vdev->regions[VFIO_PCI_CONFIG_REGION_INDEX].info;
590 
591 	if (pwrite(vdev->fd, data, sz, info->offset + offset) != sz)
592 		vfio_dev_warn(vdev, "Failed to write %d bytes to Configuration Space at 0x%x",
593 			      sz, offset);
594 
595 	/* Handle MSI write now, since it might update the hardware capability */
596 	if (pdev->irq_modes & VFIO_PCI_IRQ_MODE_MSIX)
597 		vfio_pci_msix_cap_write(kvm, vdev, offset, data, sz);
598 
599 	if (pdev->irq_modes & VFIO_PCI_IRQ_MODE_MSI)
600 		vfio_pci_msi_cap_write(kvm, vdev, offset, data, sz);
601 
602 	if (pread(vdev->fd, &tmp, sz, info->offset + offset) != sz)
603 		vfio_dev_warn(vdev, "Failed to read %d bytes from Configuration Space at 0x%x",
604 			      sz, offset);
605 }
606 
607 static ssize_t vfio_pci_msi_cap_size(struct msi_cap_64 *cap_hdr)
608 {
609 	size_t size = 10;
610 
611 	if (cap_hdr->ctrl & PCI_MSI_FLAGS_64BIT)
612 		size += 4;
613 	if (cap_hdr->ctrl & PCI_MSI_FLAGS_MASKBIT)
614 		size += 10;
615 
616 	return size;
617 }
618 
619 static ssize_t vfio_pci_cap_size(struct pci_cap_hdr *cap_hdr)
620 {
621 	switch (cap_hdr->type) {
622 	case PCI_CAP_ID_MSIX:
623 		return PCI_CAP_MSIX_SIZEOF;
624 	case PCI_CAP_ID_MSI:
625 		return vfio_pci_msi_cap_size((void *)cap_hdr);
626 	default:
627 		pr_err("unknown PCI capability 0x%x", cap_hdr->type);
628 		return 0;
629 	}
630 }
631 
632 static int vfio_pci_add_cap(struct vfio_device *vdev, u8 *virt_hdr,
633 			    struct pci_cap_hdr *cap, off_t pos)
634 {
635 	struct pci_cap_hdr *last;
636 	struct pci_device_header *hdr = &vdev->pci.hdr;
637 
638 	cap->next = 0;
639 
640 	if (!hdr->capabilities) {
641 		hdr->capabilities = pos;
642 		hdr->status |= PCI_STATUS_CAP_LIST;
643 	} else {
644 		last = PCI_CAP(virt_hdr, hdr->capabilities);
645 
646 		while (last->next)
647 			last = PCI_CAP(virt_hdr, last->next);
648 
649 		last->next = pos;
650 	}
651 
652 	memcpy(virt_hdr + pos, cap, vfio_pci_cap_size(cap));
653 
654 	return 0;
655 }
656 
657 static int vfio_pci_parse_caps(struct vfio_device *vdev)
658 {
659 	int ret;
660 	size_t size;
661 	u8 pos, next;
662 	struct pci_cap_hdr *cap;
663 	u8 virt_hdr[PCI_DEV_CFG_SIZE];
664 	struct vfio_pci_device *pdev = &vdev->pci;
665 
666 	if (!(pdev->hdr.status & PCI_STATUS_CAP_LIST))
667 		return 0;
668 
669 	memset(virt_hdr, 0, PCI_DEV_CFG_SIZE);
670 
671 	pos = pdev->hdr.capabilities & ~3;
672 
673 	pdev->hdr.status &= ~PCI_STATUS_CAP_LIST;
674 	pdev->hdr.capabilities = 0;
675 
676 	for (; pos; pos = next) {
677 		cap = PCI_CAP(&pdev->hdr, pos);
678 		next = cap->next;
679 
680 		switch (cap->type) {
681 		case PCI_CAP_ID_MSIX:
682 			ret = vfio_pci_add_cap(vdev, virt_hdr, cap, pos);
683 			if (ret)
684 				return ret;
685 
686 			pdev->msix.pos = pos;
687 			pdev->irq_modes |= VFIO_PCI_IRQ_MODE_MSIX;
688 			break;
689 		case PCI_CAP_ID_MSI:
690 			ret = vfio_pci_add_cap(vdev, virt_hdr, cap, pos);
691 			if (ret)
692 				return ret;
693 
694 			pdev->msi.pos = pos;
695 			pdev->irq_modes |= VFIO_PCI_IRQ_MODE_MSI;
696 			break;
697 		}
698 	}
699 
700 	/* Wipe remaining capabilities */
701 	pos = PCI_STD_HEADER_SIZEOF;
702 	size = PCI_DEV_CFG_SIZE - PCI_STD_HEADER_SIZEOF;
703 	memcpy((void *)&pdev->hdr + pos, virt_hdr + pos, size);
704 
705 	return 0;
706 }
707 
708 static int vfio_pci_parse_cfg_space(struct vfio_device *vdev)
709 {
710 	ssize_t sz = PCI_DEV_CFG_SIZE;
711 	struct vfio_region_info *info;
712 	struct vfio_pci_device *pdev = &vdev->pci;
713 
714 	if (vdev->info.num_regions < VFIO_PCI_CONFIG_REGION_INDEX) {
715 		vfio_dev_err(vdev, "Config Space not found");
716 		return -ENODEV;
717 	}
718 
719 	info = &vdev->regions[VFIO_PCI_CONFIG_REGION_INDEX].info;
720 	*info = (struct vfio_region_info) {
721 			.argsz = sizeof(*info),
722 			.index = VFIO_PCI_CONFIG_REGION_INDEX,
723 	};
724 
725 	ioctl(vdev->fd, VFIO_DEVICE_GET_REGION_INFO, info);
726 	if (!info->size) {
727 		vfio_dev_err(vdev, "Config Space has size zero?!");
728 		return -EINVAL;
729 	}
730 
731 	/* Read standard headers and capabilities */
732 	if (pread(vdev->fd, &pdev->hdr, sz, info->offset) != sz) {
733 		vfio_dev_err(vdev, "failed to read %zd bytes of Config Space", sz);
734 		return -EIO;
735 	}
736 
737 	/* Strip bit 7, that indicates multifunction */
738 	pdev->hdr.header_type &= 0x7f;
739 
740 	if (pdev->hdr.header_type != PCI_HEADER_TYPE_NORMAL) {
741 		vfio_dev_err(vdev, "unsupported header type %u",
742 			     pdev->hdr.header_type);
743 		return -EOPNOTSUPP;
744 	}
745 
746 	if (pdev->hdr.irq_pin)
747 		pdev->irq_modes |= VFIO_PCI_IRQ_MODE_INTX;
748 
749 	vfio_pci_parse_caps(vdev);
750 
751 	return 0;
752 }
753 
754 static int vfio_pci_fixup_cfg_space(struct vfio_device *vdev)
755 {
756 	int i;
757 	u64 base;
758 	ssize_t hdr_sz;
759 	struct msix_cap *msix;
760 	struct vfio_region_info *info;
761 	struct vfio_pci_device *pdev = &vdev->pci;
762 	struct vfio_region *region;
763 
764 	/* Initialise the BARs */
765 	for (i = VFIO_PCI_BAR0_REGION_INDEX; i <= VFIO_PCI_BAR5_REGION_INDEX; ++i) {
766 		if ((u32)i == vdev->info.num_regions)
767 			break;
768 
769 		region = &vdev->regions[i];
770 		/* Construct a fake reg to match what we've mapped. */
771 		if (region->is_ioport) {
772 			base = (region->port_base & PCI_BASE_ADDRESS_IO_MASK) |
773 				PCI_BASE_ADDRESS_SPACE_IO;
774 		} else {
775 			base = (region->guest_phys_addr &
776 				PCI_BASE_ADDRESS_MEM_MASK) |
777 				PCI_BASE_ADDRESS_SPACE_MEMORY;
778 		}
779 
780 		pdev->hdr.bar[i] = base;
781 
782 		if (!base)
783 			continue;
784 
785 		pdev->hdr.bar_size[i] = region->info.size;
786 	}
787 
788 	/* I really can't be bothered to support cardbus. */
789 	pdev->hdr.card_bus = 0;
790 
791 	/*
792 	 * Nuke the expansion ROM for now. If we want to do this properly,
793 	 * we need to save its size somewhere and map into the guest.
794 	 */
795 	pdev->hdr.exp_rom_bar = 0;
796 
797 	/* Plumb in our fake MSI-X capability, if we have it. */
798 	msix = pci_find_cap(&pdev->hdr, PCI_CAP_ID_MSIX);
799 	if (msix) {
800 		/* Add a shortcut to the PBA region for the MMIO handler */
801 		int pba_index = VFIO_PCI_BAR0_REGION_INDEX + pdev->msix_pba.bar;
802 		pdev->msix_pba.offset = vdev->regions[pba_index].info.offset +
803 					(msix->pba_offset & PCI_MSIX_PBA_OFFSET);
804 
805 		/* Tidy up the capability */
806 		msix->table_offset &= PCI_MSIX_TABLE_BIR;
807 		msix->pba_offset &= PCI_MSIX_PBA_BIR;
808 		if (pdev->msix_table.bar == pdev->msix_pba.bar)
809 			msix->pba_offset |= pdev->msix_table.size &
810 					    PCI_MSIX_PBA_OFFSET;
811 	}
812 
813 	/* Install our fake Configuration Space */
814 	info = &vdev->regions[VFIO_PCI_CONFIG_REGION_INDEX].info;
815 	hdr_sz = PCI_DEV_CFG_SIZE;
816 	if (pwrite(vdev->fd, &pdev->hdr, hdr_sz, info->offset) != hdr_sz) {
817 		vfio_dev_err(vdev, "failed to write %zd bytes to Config Space",
818 			     hdr_sz);
819 		return -EIO;
820 	}
821 
822 	/* Register callbacks for cfg accesses */
823 	pdev->hdr.cfg_ops = (struct pci_config_operations) {
824 		.read	= vfio_pci_cfg_read,
825 		.write	= vfio_pci_cfg_write,
826 	};
827 
828 	pdev->hdr.irq_type = IRQ_TYPE_LEVEL_HIGH;
829 
830 	return 0;
831 }
832 
833 static int vfio_pci_get_region_info(struct vfio_device *vdev, u32 index,
834 				    struct vfio_region_info *info)
835 {
836 	int ret;
837 
838 	*info = (struct vfio_region_info) {
839 		.argsz = sizeof(*info),
840 		.index = index,
841 	};
842 
843 	ret = ioctl(vdev->fd, VFIO_DEVICE_GET_REGION_INFO, info);
844 	if (ret) {
845 		ret = -errno;
846 		vfio_dev_err(vdev, "cannot get info for BAR %u", index);
847 		return ret;
848 	}
849 
850 	if (info->size && !is_power_of_two(info->size)) {
851 		vfio_dev_err(vdev, "region is not power of two: 0x%llx",
852 				info->size);
853 		return -EINVAL;
854 	}
855 
856 	return 0;
857 }
858 
859 static int vfio_pci_create_msix_table(struct kvm *kvm, struct vfio_device *vdev)
860 {
861 	int ret;
862 	size_t i;
863 	size_t map_size;
864 	size_t nr_entries;
865 	struct vfio_pci_msi_entry *entries;
866 	struct vfio_pci_device *pdev = &vdev->pci;
867 	struct vfio_pci_msix_pba *pba = &pdev->msix_pba;
868 	struct vfio_pci_msix_table *table = &pdev->msix_table;
869 	struct msix_cap *msix = PCI_CAP(&pdev->hdr, pdev->msix.pos);
870 	struct vfio_region_info info;
871 
872 	table->bar = msix->table_offset & PCI_MSIX_TABLE_BIR;
873 	pba->bar = msix->pba_offset & PCI_MSIX_TABLE_BIR;
874 
875 	/*
876 	 * KVM needs memory regions to be multiple of and aligned on PAGE_SIZE.
877 	 */
878 	nr_entries = (msix->ctrl & PCI_MSIX_FLAGS_QSIZE) + 1;
879 	table->size = ALIGN(nr_entries * PCI_MSIX_ENTRY_SIZE, PAGE_SIZE);
880 	pba->size = ALIGN(DIV_ROUND_UP(nr_entries, 64), PAGE_SIZE);
881 
882 	entries = calloc(nr_entries, sizeof(struct vfio_pci_msi_entry));
883 	if (!entries)
884 		return -ENOMEM;
885 
886 	for (i = 0; i < nr_entries; i++)
887 		entries[i].config.ctrl = PCI_MSIX_ENTRY_CTRL_MASKBIT;
888 
889 	ret = vfio_pci_get_region_info(vdev, table->bar, &info);
890 	if (ret)
891 		return ret;
892 	if (!info.size)
893 		return -EINVAL;
894 	map_size = info.size;
895 
896 	if (table->bar != pba->bar) {
897 		ret = vfio_pci_get_region_info(vdev, pba->bar, &info);
898 		if (ret)
899 			return ret;
900 		if (!info.size)
901 			return -EINVAL;
902 		map_size += info.size;
903 	}
904 
905 	/*
906 	 * To ease MSI-X cap configuration in case they share the same BAR,
907 	 * collapse table and pending array. The size of the BAR regions must be
908 	 * powers of two.
909 	 */
910 	map_size = ALIGN(map_size, PAGE_SIZE);
911 	table->guest_phys_addr = pci_get_mmio_block(map_size);
912 	if (!table->guest_phys_addr) {
913 		pr_err("cannot allocate MMIO space");
914 		ret = -ENOMEM;
915 		goto out_free;
916 	}
917 
918 	/*
919 	 * We could map the physical PBA directly into the guest, but it's
920 	 * likely smaller than a page, and we can only hand full pages to the
921 	 * guest. Even though the PCI spec disallows sharing a page used for
922 	 * MSI-X with any other resource, it allows to share the same page
923 	 * between MSI-X table and PBA. For the sake of isolation, create a
924 	 * virtual PBA.
925 	 */
926 	pba->guest_phys_addr = table->guest_phys_addr + table->size;
927 
928 	pdev->msix.entries = entries;
929 	pdev->msix.nr_entries = nr_entries;
930 
931 	return 0;
932 
933 out_free:
934 	free(entries);
935 
936 	return ret;
937 }
938 
939 static int vfio_pci_create_msi_cap(struct kvm *kvm, struct vfio_pci_device *pdev)
940 {
941 	struct msi_cap_64 *cap = PCI_CAP(&pdev->hdr, pdev->msi.pos);
942 
943 	pdev->msi.nr_entries = 1 << ((cap->ctrl & PCI_MSI_FLAGS_QMASK) >> 1),
944 	pdev->msi.entries = calloc(pdev->msi.nr_entries,
945 				   sizeof(struct vfio_pci_msi_entry));
946 	if (!pdev->msi.entries)
947 		return -ENOMEM;
948 
949 	return 0;
950 }
951 
952 static int vfio_pci_configure_bar(struct kvm *kvm, struct vfio_device *vdev,
953 				  size_t nr)
954 {
955 	int ret;
956 	u32 bar;
957 	size_t map_size;
958 	struct vfio_pci_device *pdev = &vdev->pci;
959 	struct vfio_region *region;
960 
961 	if (nr >= vdev->info.num_regions)
962 		return 0;
963 
964 	region = &vdev->regions[nr];
965 	bar = pdev->hdr.bar[nr];
966 
967 	region->vdev = vdev;
968 	region->is_ioport = !!(bar & PCI_BASE_ADDRESS_SPACE_IO);
969 
970 	ret = vfio_pci_get_region_info(vdev, nr, &region->info);
971 	if (ret)
972 		return ret;
973 
974 	/* Ignore invalid or unimplemented regions */
975 	if (!region->info.size)
976 		return 0;
977 
978 	if (pdev->irq_modes & VFIO_PCI_IRQ_MODE_MSIX) {
979 		/* Trap and emulate MSI-X table */
980 		if (nr == pdev->msix_table.bar) {
981 			region->guest_phys_addr = pdev->msix_table.guest_phys_addr;
982 			return 0;
983 		} else if (nr == pdev->msix_pba.bar) {
984 			region->guest_phys_addr = pdev->msix_pba.guest_phys_addr;
985 			return 0;
986 		}
987 	}
988 
989 	if (region->is_ioport) {
990 		region->port_base = pci_get_io_port_block(region->info.size);
991 	} else {
992 		/* Grab some MMIO space in the guest */
993 		map_size = ALIGN(region->info.size, PAGE_SIZE);
994 		region->guest_phys_addr = pci_get_mmio_block(map_size);
995 	}
996 
997 	return 0;
998 }
999 
1000 static int vfio_pci_configure_dev_regions(struct kvm *kvm,
1001 					  struct vfio_device *vdev)
1002 {
1003 	int ret;
1004 	u32 bar;
1005 	size_t i;
1006 	bool is_64bit = false;
1007 	struct vfio_pci_device *pdev = &vdev->pci;
1008 
1009 	ret = vfio_pci_parse_cfg_space(vdev);
1010 	if (ret)
1011 		return ret;
1012 
1013 	if (pdev->irq_modes & VFIO_PCI_IRQ_MODE_MSIX) {
1014 		ret = vfio_pci_create_msix_table(kvm, vdev);
1015 		if (ret)
1016 			return ret;
1017 	}
1018 
1019 	if (pdev->irq_modes & VFIO_PCI_IRQ_MODE_MSI) {
1020 		ret = vfio_pci_create_msi_cap(kvm, pdev);
1021 		if (ret)
1022 			return ret;
1023 	}
1024 
1025 	for (i = VFIO_PCI_BAR0_REGION_INDEX; i <= VFIO_PCI_BAR5_REGION_INDEX; ++i) {
1026 		/* Ignore top half of 64-bit BAR */
1027 		if (is_64bit) {
1028 			is_64bit = false;
1029 			continue;
1030 		}
1031 
1032 		ret = vfio_pci_configure_bar(kvm, vdev, i);
1033 		if (ret)
1034 			return ret;
1035 
1036 		bar = pdev->hdr.bar[i];
1037 		is_64bit = (bar & PCI_BASE_ADDRESS_SPACE) ==
1038 			   PCI_BASE_ADDRESS_SPACE_MEMORY &&
1039 			   bar & PCI_BASE_ADDRESS_MEM_TYPE_64;
1040 	}
1041 
1042 	/* We've configured the BARs, fake up a Configuration Space */
1043 	ret = vfio_pci_fixup_cfg_space(vdev);
1044 	if (ret)
1045 		return ret;
1046 
1047 	return pci__register_bar_regions(kvm, &pdev->hdr, vfio_pci_bar_activate,
1048 					 vfio_pci_bar_deactivate, vdev);
1049 }
1050 
1051 /*
1052  * Attempt to update the FD limit, if opening an eventfd for each IRQ vector
1053  * would hit the limit. Which is likely to happen when a device uses 2048 MSIs.
1054  */
1055 static int vfio_pci_reserve_irq_fds(size_t num)
1056 {
1057 	/*
1058 	 * I counted around 27 fds under normal load. Let's add 100 for good
1059 	 * measure.
1060 	 */
1061 	static size_t needed = 128;
1062 	struct rlimit fd_limit, new_limit;
1063 
1064 	needed += num;
1065 
1066 	if (getrlimit(RLIMIT_NOFILE, &fd_limit)) {
1067 		perror("getrlimit(RLIMIT_NOFILE)");
1068 		return 0;
1069 	}
1070 
1071 	if (fd_limit.rlim_cur >= needed)
1072 		return 0;
1073 
1074 	new_limit.rlim_cur = needed;
1075 
1076 	if (fd_limit.rlim_max < needed)
1077 		/* Try to bump hard limit (root only) */
1078 		new_limit.rlim_max = needed;
1079 	else
1080 		new_limit.rlim_max = fd_limit.rlim_max;
1081 
1082 	if (setrlimit(RLIMIT_NOFILE, &new_limit)) {
1083 		perror("setrlimit(RLIMIT_NOFILE)");
1084 		pr_warning("not enough FDs for full MSI-X support (estimated need: %zu)",
1085 			   (size_t)(needed - fd_limit.rlim_cur));
1086 	}
1087 
1088 	return 0;
1089 }
1090 
1091 static int vfio_pci_init_msis(struct kvm *kvm, struct vfio_device *vdev,
1092 			     struct vfio_pci_msi_common *msis)
1093 {
1094 	int ret;
1095 	size_t i;
1096 	int *eventfds;
1097 	size_t irq_set_size;
1098 	struct vfio_pci_msi_entry *entry;
1099 	size_t nr_entries = msis->nr_entries;
1100 
1101 	ret = ioctl(vdev->fd, VFIO_DEVICE_GET_IRQ_INFO, &msis->info);
1102 	if (ret || msis->info.count == 0) {
1103 		vfio_dev_err(vdev, "no MSI reported by VFIO");
1104 		return -ENODEV;
1105 	}
1106 
1107 	if (!(msis->info.flags & VFIO_IRQ_INFO_EVENTFD)) {
1108 		vfio_dev_err(vdev, "interrupt not EVENTFD capable");
1109 		return -EINVAL;
1110 	}
1111 
1112 	if (msis->info.count != nr_entries) {
1113 		vfio_dev_err(vdev, "invalid number of MSIs reported by VFIO");
1114 		return -EINVAL;
1115 	}
1116 
1117 	mutex_init(&msis->mutex);
1118 
1119 	vfio_pci_reserve_irq_fds(nr_entries);
1120 
1121 	irq_set_size = sizeof(struct vfio_irq_set) + nr_entries * sizeof(int);
1122 	msis->irq_set = malloc(irq_set_size);
1123 	if (!msis->irq_set)
1124 		return -ENOMEM;
1125 
1126 	*msis->irq_set = (struct vfio_irq_set) {
1127 		.argsz	= irq_set_size,
1128 		.flags 	= VFIO_IRQ_SET_DATA_EVENTFD |
1129 			  VFIO_IRQ_SET_ACTION_TRIGGER,
1130 		.index 	= msis->info.index,
1131 		.start 	= 0,
1132 		.count 	= nr_entries,
1133 	};
1134 
1135 	eventfds = (void *)msis->irq_set + sizeof(struct vfio_irq_set);
1136 
1137 	for (i = 0; i < nr_entries; i++) {
1138 		entry = &msis->entries[i];
1139 		entry->gsi = -1;
1140 		entry->eventfd = -1;
1141 		msi_set_masked(entry->virt_state, true);
1142 		msi_set_masked(entry->phys_state, true);
1143 		eventfds[i] = -1;
1144 	}
1145 
1146 	return 0;
1147 }
1148 
1149 static void vfio_pci_disable_intx(struct kvm *kvm, struct vfio_device *vdev)
1150 {
1151 	struct vfio_pci_device *pdev = &vdev->pci;
1152 	int gsi = pdev->intx_gsi;
1153 	struct vfio_irq_set irq_set = {
1154 		.argsz	= sizeof(irq_set),
1155 		.flags	= VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_TRIGGER,
1156 		.index	= VFIO_PCI_INTX_IRQ_INDEX,
1157 	};
1158 
1159 	if (pdev->intx_fd == -1)
1160 		return;
1161 
1162 	pr_debug("user requested MSI, disabling INTx %d", gsi);
1163 
1164 	ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, &irq_set);
1165 	irq__del_irqfd(kvm, gsi, pdev->intx_fd);
1166 
1167 	close(pdev->intx_fd);
1168 	close(pdev->unmask_fd);
1169 	pdev->intx_fd = -1;
1170 }
1171 
1172 static int vfio_pci_enable_intx(struct kvm *kvm, struct vfio_device *vdev)
1173 {
1174 	int ret;
1175 	int trigger_fd, unmask_fd;
1176 	union vfio_irq_eventfd	trigger;
1177 	union vfio_irq_eventfd	unmask;
1178 	struct vfio_pci_device *pdev = &vdev->pci;
1179 	int gsi = pdev->intx_gsi;
1180 
1181 	if (pdev->intx_fd != -1)
1182 		return 0;
1183 
1184 	/*
1185 	 * PCI IRQ is level-triggered, so we use two eventfds. trigger_fd
1186 	 * signals an interrupt from host to guest, and unmask_fd signals the
1187 	 * deassertion of the line from guest to host.
1188 	 */
1189 	trigger_fd = eventfd(0, 0);
1190 	if (trigger_fd < 0) {
1191 		vfio_dev_err(vdev, "failed to create trigger eventfd");
1192 		return trigger_fd;
1193 	}
1194 
1195 	unmask_fd = eventfd(0, 0);
1196 	if (unmask_fd < 0) {
1197 		vfio_dev_err(vdev, "failed to create unmask eventfd");
1198 		close(trigger_fd);
1199 		return unmask_fd;
1200 	}
1201 
1202 	ret = irq__add_irqfd(kvm, gsi, trigger_fd, unmask_fd);
1203 	if (ret)
1204 		goto err_close;
1205 
1206 	trigger.irq = (struct vfio_irq_set) {
1207 		.argsz	= sizeof(trigger),
1208 		.flags	= VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_TRIGGER,
1209 		.index	= VFIO_PCI_INTX_IRQ_INDEX,
1210 		.start	= 0,
1211 		.count	= 1,
1212 	};
1213 	set_vfio_irq_eventd_payload(&trigger, trigger_fd);
1214 
1215 	ret = ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, &trigger);
1216 	if (ret < 0) {
1217 		vfio_dev_err(vdev, "failed to setup VFIO IRQ");
1218 		goto err_delete_line;
1219 	}
1220 
1221 	unmask.irq = (struct vfio_irq_set) {
1222 		.argsz	= sizeof(unmask),
1223 		.flags	= VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_UNMASK,
1224 		.index	= VFIO_PCI_INTX_IRQ_INDEX,
1225 		.start	= 0,
1226 		.count	= 1,
1227 	};
1228 	set_vfio_irq_eventd_payload(&unmask, unmask_fd);
1229 
1230 	ret = ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, &unmask);
1231 	if (ret < 0) {
1232 		vfio_dev_err(vdev, "failed to setup unmask IRQ");
1233 		goto err_remove_event;
1234 	}
1235 
1236 	pdev->intx_fd = trigger_fd;
1237 	pdev->unmask_fd = unmask_fd;
1238 
1239 	return 0;
1240 
1241 err_remove_event:
1242 	/* Remove trigger event */
1243 	trigger.irq.flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_TRIGGER;
1244 	trigger.irq.count = 0;
1245 	ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, &trigger);
1246 
1247 err_delete_line:
1248 	irq__del_irqfd(kvm, gsi, trigger_fd);
1249 
1250 err_close:
1251 	close(trigger_fd);
1252 	close(unmask_fd);
1253 	return ret;
1254 }
1255 
1256 static int vfio_pci_init_intx(struct kvm *kvm, struct vfio_device *vdev)
1257 {
1258 	int ret;
1259 	struct vfio_pci_device *pdev = &vdev->pci;
1260 	struct vfio_irq_info irq_info = {
1261 		.argsz = sizeof(irq_info),
1262 		.index = VFIO_PCI_INTX_IRQ_INDEX,
1263 	};
1264 
1265 	vfio_pci_reserve_irq_fds(2);
1266 
1267 	ret = ioctl(vdev->fd, VFIO_DEVICE_GET_IRQ_INFO, &irq_info);
1268 	if (ret || irq_info.count == 0) {
1269 		vfio_dev_err(vdev, "no INTx reported by VFIO");
1270 		return -ENODEV;
1271 	}
1272 
1273 	if (!(irq_info.flags & VFIO_IRQ_INFO_EVENTFD)) {
1274 		vfio_dev_err(vdev, "interrupt not eventfd capable");
1275 		return -EINVAL;
1276 	}
1277 
1278 	if (!(irq_info.flags & VFIO_IRQ_INFO_AUTOMASKED)) {
1279 		vfio_dev_err(vdev, "INTx interrupt not AUTOMASKED");
1280 		return -EINVAL;
1281 	}
1282 
1283 	/* Guest is going to ovewrite our irq_line... */
1284 	pdev->intx_gsi = pdev->hdr.irq_line - KVM_IRQ_OFFSET;
1285 
1286 	pdev->intx_fd = -1;
1287 
1288 	return 0;
1289 }
1290 
1291 static int vfio_pci_configure_dev_irqs(struct kvm *kvm, struct vfio_device *vdev)
1292 {
1293 	int ret = 0;
1294 	struct vfio_pci_device *pdev = &vdev->pci;
1295 
1296 	if (pdev->irq_modes & VFIO_PCI_IRQ_MODE_MSIX) {
1297 		pdev->msix.info = (struct vfio_irq_info) {
1298 			.argsz = sizeof(pdev->msix.info),
1299 			.index = VFIO_PCI_MSIX_IRQ_INDEX,
1300 		};
1301 		ret = vfio_pci_init_msis(kvm, vdev, &pdev->msix);
1302 		if (ret)
1303 			return ret;
1304 	}
1305 
1306 	if (pdev->irq_modes & VFIO_PCI_IRQ_MODE_MSI) {
1307 		pdev->msi.info = (struct vfio_irq_info) {
1308 			.argsz = sizeof(pdev->msi.info),
1309 			.index = VFIO_PCI_MSI_IRQ_INDEX,
1310 		};
1311 		ret = vfio_pci_init_msis(kvm, vdev, &pdev->msi);
1312 		if (ret)
1313 			return ret;
1314 	}
1315 
1316 	if (pdev->irq_modes & VFIO_PCI_IRQ_MODE_INTX) {
1317 		pci__assign_irq(&vdev->pci.hdr);
1318 
1319 		ret = vfio_pci_init_intx(kvm, vdev);
1320 		if (ret)
1321 			return ret;
1322 
1323 		ret = vfio_pci_enable_intx(kvm, vdev);
1324 	}
1325 
1326 	return ret;
1327 }
1328 
1329 int vfio_pci_setup_device(struct kvm *kvm, struct vfio_device *vdev)
1330 {
1331 	int ret;
1332 
1333 	ret = vfio_pci_configure_dev_regions(kvm, vdev);
1334 	if (ret) {
1335 		vfio_dev_err(vdev, "failed to configure regions");
1336 		return ret;
1337 	}
1338 
1339 	vdev->dev_hdr = (struct device_header) {
1340 		.bus_type	= DEVICE_BUS_PCI,
1341 		.data		= &vdev->pci.hdr,
1342 	};
1343 
1344 	ret = device__register(&vdev->dev_hdr);
1345 	if (ret) {
1346 		vfio_dev_err(vdev, "failed to register VFIO device");
1347 		return ret;
1348 	}
1349 
1350 	ret = vfio_pci_configure_dev_irqs(kvm, vdev);
1351 	if (ret) {
1352 		vfio_dev_err(vdev, "failed to configure IRQs");
1353 		return ret;
1354 	}
1355 
1356 	return 0;
1357 }
1358 
1359 void vfio_pci_teardown_device(struct kvm *kvm, struct vfio_device *vdev)
1360 {
1361 	size_t i;
1362 	struct vfio_pci_device *pdev = &vdev->pci;
1363 
1364 	for (i = 0; i < vdev->info.num_regions; i++)
1365 		vfio_unmap_region(kvm, &vdev->regions[i]);
1366 
1367 	device__unregister(&vdev->dev_hdr);
1368 
1369 	free(pdev->msix.irq_set);
1370 	free(pdev->msix.entries);
1371 	free(pdev->msi.irq_set);
1372 	free(pdev->msi.entries);
1373 }
1374