1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * VFIO PCI config space virtualization
4  *
5  * Copyright (C) 2012 Red Hat, Inc.  All rights reserved.
6  *     Author: Alex Williamson <alex.williamson@redhat.com>
7  *
8  * Derived from original vfio:
9  * Copyright 2010 Cisco Systems, Inc.  All rights reserved.
10  * Author: Tom Lyon, pugs@cisco.com
11  */
12 
13 /*
14  * This code handles reading and writing of PCI configuration registers.
15  * This is hairy because we want to allow a lot of flexibility to the
16  * user driver, but cannot trust it with all of the config fields.
17  * Tables determine which fields can be read and written, as well as
18  * which fields are 'virtualized' - special actions and translations to
19  * make it appear to the user that he has control, when in fact things
20  * must be negotiated with the underlying OS.
21  */
22 
23 #include <linux/fs.h>
24 #include <linux/pci.h>
25 #include <linux/uaccess.h>
26 #include <linux/vfio.h>
27 #include <linux/slab.h>
28 
29 #include "vfio_pci_private.h"
30 
31 /* Fake capability ID for standard config space */
32 #define PCI_CAP_ID_BASIC	0
33 
34 #define is_bar(offset)	\
35 	((offset >= PCI_BASE_ADDRESS_0 && offset < PCI_BASE_ADDRESS_5 + 4) || \
36 	 (offset >= PCI_ROM_ADDRESS && offset < PCI_ROM_ADDRESS + 4))
37 
38 /*
39  * Lengths of PCI Config Capabilities
40  *   0: Removed from the user visible capability list
41  *   FF: Variable length
42  */
43 static const u8 pci_cap_length[PCI_CAP_ID_MAX + 1] = {
44 	[PCI_CAP_ID_BASIC]	= PCI_STD_HEADER_SIZEOF, /* pci config header */
45 	[PCI_CAP_ID_PM]		= PCI_PM_SIZEOF,
46 	[PCI_CAP_ID_AGP]	= PCI_AGP_SIZEOF,
47 	[PCI_CAP_ID_VPD]	= PCI_CAP_VPD_SIZEOF,
48 	[PCI_CAP_ID_SLOTID]	= 0,		/* bridge - don't care */
49 	[PCI_CAP_ID_MSI]	= 0xFF,		/* 10, 14, 20, or 24 */
50 	[PCI_CAP_ID_CHSWP]	= 0,		/* cpci - not yet */
51 	[PCI_CAP_ID_PCIX]	= 0xFF,		/* 8 or 24 */
52 	[PCI_CAP_ID_HT]		= 0xFF,		/* hypertransport */
53 	[PCI_CAP_ID_VNDR]	= 0xFF,		/* variable */
54 	[PCI_CAP_ID_DBG]	= 0,		/* debug - don't care */
55 	[PCI_CAP_ID_CCRC]	= 0,		/* cpci - not yet */
56 	[PCI_CAP_ID_SHPC]	= 0,		/* hotswap - not yet */
57 	[PCI_CAP_ID_SSVID]	= 0,		/* bridge - don't care */
58 	[PCI_CAP_ID_AGP3]	= 0,		/* AGP8x - not yet */
59 	[PCI_CAP_ID_SECDEV]	= 0,		/* secure device not yet */
60 	[PCI_CAP_ID_EXP]	= 0xFF,		/* 20 or 44 */
61 	[PCI_CAP_ID_MSIX]	= PCI_CAP_MSIX_SIZEOF,
62 	[PCI_CAP_ID_SATA]	= 0xFF,
63 	[PCI_CAP_ID_AF]		= PCI_CAP_AF_SIZEOF,
64 };
65 
66 /*
67  * Lengths of PCIe/PCI-X Extended Config Capabilities
68  *   0: Removed or masked from the user visible capability list
69  *   FF: Variable length
70  */
71 static const u16 pci_ext_cap_length[PCI_EXT_CAP_ID_MAX + 1] = {
72 	[PCI_EXT_CAP_ID_ERR]	=	PCI_ERR_ROOT_COMMAND,
73 	[PCI_EXT_CAP_ID_VC]	=	0xFF,
74 	[PCI_EXT_CAP_ID_DSN]	=	PCI_EXT_CAP_DSN_SIZEOF,
75 	[PCI_EXT_CAP_ID_PWR]	=	PCI_EXT_CAP_PWR_SIZEOF,
76 	[PCI_EXT_CAP_ID_RCLD]	=	0,	/* root only - don't care */
77 	[PCI_EXT_CAP_ID_RCILC]	=	0,	/* root only - don't care */
78 	[PCI_EXT_CAP_ID_RCEC]	=	0,	/* root only - don't care */
79 	[PCI_EXT_CAP_ID_MFVC]	=	0xFF,
80 	[PCI_EXT_CAP_ID_VC9]	=	0xFF,	/* same as CAP_ID_VC */
81 	[PCI_EXT_CAP_ID_RCRB]	=	0,	/* root only - don't care */
82 	[PCI_EXT_CAP_ID_VNDR]	=	0xFF,
83 	[PCI_EXT_CAP_ID_CAC]	=	0,	/* obsolete */
84 	[PCI_EXT_CAP_ID_ACS]	=	0xFF,
85 	[PCI_EXT_CAP_ID_ARI]	=	PCI_EXT_CAP_ARI_SIZEOF,
86 	[PCI_EXT_CAP_ID_ATS]	=	PCI_EXT_CAP_ATS_SIZEOF,
87 	[PCI_EXT_CAP_ID_SRIOV]	=	PCI_EXT_CAP_SRIOV_SIZEOF,
88 	[PCI_EXT_CAP_ID_MRIOV]	=	0,	/* not yet */
89 	[PCI_EXT_CAP_ID_MCAST]	=	PCI_EXT_CAP_MCAST_ENDPOINT_SIZEOF,
90 	[PCI_EXT_CAP_ID_PRI]	=	PCI_EXT_CAP_PRI_SIZEOF,
91 	[PCI_EXT_CAP_ID_AMD_XXX] =	0,	/* not yet */
92 	[PCI_EXT_CAP_ID_REBAR]	=	0xFF,
93 	[PCI_EXT_CAP_ID_DPA]	=	0xFF,
94 	[PCI_EXT_CAP_ID_TPH]	=	0xFF,
95 	[PCI_EXT_CAP_ID_LTR]	=	PCI_EXT_CAP_LTR_SIZEOF,
96 	[PCI_EXT_CAP_ID_SECPCI]	=	0,	/* not yet */
97 	[PCI_EXT_CAP_ID_PMUX]	=	0,	/* not yet */
98 	[PCI_EXT_CAP_ID_PASID]	=	0,	/* not yet */
99 };
100 
101 /*
102  * Read/Write Permission Bits - one bit for each bit in capability
103  * Any field can be read if it exists, but what is read depends on
104  * whether the field is 'virtualized', or just pass thru to the
105  * hardware.  Any virtualized field is also virtualized for writes.
106  * Writes are only permitted if they have a 1 bit here.
107  */
108 struct perm_bits {
109 	u8	*virt;		/* read/write virtual data, not hw */
110 	u8	*write;		/* writeable bits */
111 	int	(*readfn)(struct vfio_pci_device *vdev, int pos, int count,
112 			  struct perm_bits *perm, int offset, __le32 *val);
113 	int	(*writefn)(struct vfio_pci_device *vdev, int pos, int count,
114 			   struct perm_bits *perm, int offset, __le32 val);
115 };
116 
117 #define	NO_VIRT		0
118 #define	ALL_VIRT	0xFFFFFFFFU
119 #define	NO_WRITE	0
120 #define	ALL_WRITE	0xFFFFFFFFU
121 
122 static int vfio_user_config_read(struct pci_dev *pdev, int offset,
123 				 __le32 *val, int count)
124 {
125 	int ret = -EINVAL;
126 	u32 tmp_val = 0;
127 
128 	switch (count) {
129 	case 1:
130 	{
131 		u8 tmp;
132 		ret = pci_user_read_config_byte(pdev, offset, &tmp);
133 		tmp_val = tmp;
134 		break;
135 	}
136 	case 2:
137 	{
138 		u16 tmp;
139 		ret = pci_user_read_config_word(pdev, offset, &tmp);
140 		tmp_val = tmp;
141 		break;
142 	}
143 	case 4:
144 		ret = pci_user_read_config_dword(pdev, offset, &tmp_val);
145 		break;
146 	}
147 
148 	*val = cpu_to_le32(tmp_val);
149 
150 	return ret;
151 }
152 
153 static int vfio_user_config_write(struct pci_dev *pdev, int offset,
154 				  __le32 val, int count)
155 {
156 	int ret = -EINVAL;
157 	u32 tmp_val = le32_to_cpu(val);
158 
159 	switch (count) {
160 	case 1:
161 		ret = pci_user_write_config_byte(pdev, offset, tmp_val);
162 		break;
163 	case 2:
164 		ret = pci_user_write_config_word(pdev, offset, tmp_val);
165 		break;
166 	case 4:
167 		ret = pci_user_write_config_dword(pdev, offset, tmp_val);
168 		break;
169 	}
170 
171 	return ret;
172 }
173 
174 static int vfio_default_config_read(struct vfio_pci_device *vdev, int pos,
175 				    int count, struct perm_bits *perm,
176 				    int offset, __le32 *val)
177 {
178 	__le32 virt = 0;
179 
180 	memcpy(val, vdev->vconfig + pos, count);
181 
182 	memcpy(&virt, perm->virt + offset, count);
183 
184 	/* Any non-virtualized bits? */
185 	if (cpu_to_le32(~0U >> (32 - (count * 8))) != virt) {
186 		struct pci_dev *pdev = vdev->pdev;
187 		__le32 phys_val = 0;
188 		int ret;
189 
190 		ret = vfio_user_config_read(pdev, pos, &phys_val, count);
191 		if (ret)
192 			return ret;
193 
194 		*val = (phys_val & ~virt) | (*val & virt);
195 	}
196 
197 	return count;
198 }
199 
200 static int vfio_default_config_write(struct vfio_pci_device *vdev, int pos,
201 				     int count, struct perm_bits *perm,
202 				     int offset, __le32 val)
203 {
204 	__le32 virt = 0, write = 0;
205 
206 	memcpy(&write, perm->write + offset, count);
207 
208 	if (!write)
209 		return count; /* drop, no writable bits */
210 
211 	memcpy(&virt, perm->virt + offset, count);
212 
213 	/* Virtualized and writable bits go to vconfig */
214 	if (write & virt) {
215 		__le32 virt_val = 0;
216 
217 		memcpy(&virt_val, vdev->vconfig + pos, count);
218 
219 		virt_val &= ~(write & virt);
220 		virt_val |= (val & (write & virt));
221 
222 		memcpy(vdev->vconfig + pos, &virt_val, count);
223 	}
224 
225 	/* Non-virtualzed and writable bits go to hardware */
226 	if (write & ~virt) {
227 		struct pci_dev *pdev = vdev->pdev;
228 		__le32 phys_val = 0;
229 		int ret;
230 
231 		ret = vfio_user_config_read(pdev, pos, &phys_val, count);
232 		if (ret)
233 			return ret;
234 
235 		phys_val &= ~(write & ~virt);
236 		phys_val |= (val & (write & ~virt));
237 
238 		ret = vfio_user_config_write(pdev, pos, phys_val, count);
239 		if (ret)
240 			return ret;
241 	}
242 
243 	return count;
244 }
245 
246 /* Allow direct read from hardware, except for capability next pointer */
247 static int vfio_direct_config_read(struct vfio_pci_device *vdev, int pos,
248 				   int count, struct perm_bits *perm,
249 				   int offset, __le32 *val)
250 {
251 	int ret;
252 
253 	ret = vfio_user_config_read(vdev->pdev, pos, val, count);
254 	if (ret)
255 		return ret;
256 
257 	if (pos >= PCI_CFG_SPACE_SIZE) { /* Extended cap header mangling */
258 		if (offset < 4)
259 			memcpy(val, vdev->vconfig + pos, count);
260 	} else if (pos >= PCI_STD_HEADER_SIZEOF) { /* Std cap mangling */
261 		if (offset == PCI_CAP_LIST_ID && count > 1)
262 			memcpy(val, vdev->vconfig + pos,
263 			       min(PCI_CAP_FLAGS, count));
264 		else if (offset == PCI_CAP_LIST_NEXT)
265 			memcpy(val, vdev->vconfig + pos, 1);
266 	}
267 
268 	return count;
269 }
270 
271 /* Raw access skips any kind of virtualization */
272 static int vfio_raw_config_write(struct vfio_pci_device *vdev, int pos,
273 				 int count, struct perm_bits *perm,
274 				 int offset, __le32 val)
275 {
276 	int ret;
277 
278 	ret = vfio_user_config_write(vdev->pdev, pos, val, count);
279 	if (ret)
280 		return ret;
281 
282 	return count;
283 }
284 
285 static int vfio_raw_config_read(struct vfio_pci_device *vdev, int pos,
286 				int count, struct perm_bits *perm,
287 				int offset, __le32 *val)
288 {
289 	int ret;
290 
291 	ret = vfio_user_config_read(vdev->pdev, pos, val, count);
292 	if (ret)
293 		return ret;
294 
295 	return count;
296 }
297 
298 /* Virt access uses only virtualization */
299 static int vfio_virt_config_write(struct vfio_pci_device *vdev, int pos,
300 				  int count, struct perm_bits *perm,
301 				  int offset, __le32 val)
302 {
303 	memcpy(vdev->vconfig + pos, &val, count);
304 	return count;
305 }
306 
307 static int vfio_virt_config_read(struct vfio_pci_device *vdev, int pos,
308 				 int count, struct perm_bits *perm,
309 				 int offset, __le32 *val)
310 {
311 	memcpy(val, vdev->vconfig + pos, count);
312 	return count;
313 }
314 
315 /* Default capability regions to read-only, no-virtualization */
316 static struct perm_bits cap_perms[PCI_CAP_ID_MAX + 1] = {
317 	[0 ... PCI_CAP_ID_MAX] = { .readfn = vfio_direct_config_read }
318 };
319 static struct perm_bits ecap_perms[PCI_EXT_CAP_ID_MAX + 1] = {
320 	[0 ... PCI_EXT_CAP_ID_MAX] = { .readfn = vfio_direct_config_read }
321 };
322 /*
323  * Default unassigned regions to raw read-write access.  Some devices
324  * require this to function as they hide registers between the gaps in
325  * config space (be2net).  Like MMIO and I/O port registers, we have
326  * to trust the hardware isolation.
327  */
328 static struct perm_bits unassigned_perms = {
329 	.readfn = vfio_raw_config_read,
330 	.writefn = vfio_raw_config_write
331 };
332 
333 static struct perm_bits virt_perms = {
334 	.readfn = vfio_virt_config_read,
335 	.writefn = vfio_virt_config_write
336 };
337 
338 static void free_perm_bits(struct perm_bits *perm)
339 {
340 	kfree(perm->virt);
341 	kfree(perm->write);
342 	perm->virt = NULL;
343 	perm->write = NULL;
344 }
345 
346 static int alloc_perm_bits(struct perm_bits *perm, int size)
347 {
348 	/*
349 	 * Round up all permission bits to the next dword, this lets us
350 	 * ignore whether a read/write exceeds the defined capability
351 	 * structure.  We can do this because:
352 	 *  - Standard config space is already dword aligned
353 	 *  - Capabilities are all dword aligned (bits 0:1 of next reserved)
354 	 *  - Express capabilities defined as dword aligned
355 	 */
356 	size = round_up(size, 4);
357 
358 	/*
359 	 * Zero state is
360 	 * - All Readable, None Writeable, None Virtualized
361 	 */
362 	perm->virt = kzalloc(size, GFP_KERNEL);
363 	perm->write = kzalloc(size, GFP_KERNEL);
364 	if (!perm->virt || !perm->write) {
365 		free_perm_bits(perm);
366 		return -ENOMEM;
367 	}
368 
369 	perm->readfn = vfio_default_config_read;
370 	perm->writefn = vfio_default_config_write;
371 
372 	return 0;
373 }
374 
375 /*
376  * Helper functions for filling in permission tables
377  */
378 static inline void p_setb(struct perm_bits *p, int off, u8 virt, u8 write)
379 {
380 	p->virt[off] = virt;
381 	p->write[off] = write;
382 }
383 
384 /* Handle endian-ness - pci and tables are little-endian */
385 static inline void p_setw(struct perm_bits *p, int off, u16 virt, u16 write)
386 {
387 	*(__le16 *)(&p->virt[off]) = cpu_to_le16(virt);
388 	*(__le16 *)(&p->write[off]) = cpu_to_le16(write);
389 }
390 
391 /* Handle endian-ness - pci and tables are little-endian */
392 static inline void p_setd(struct perm_bits *p, int off, u32 virt, u32 write)
393 {
394 	*(__le32 *)(&p->virt[off]) = cpu_to_le32(virt);
395 	*(__le32 *)(&p->write[off]) = cpu_to_le32(write);
396 }
397 
398 /* Caller should hold memory_lock semaphore */
399 bool __vfio_pci_memory_enabled(struct vfio_pci_device *vdev)
400 {
401 	u16 cmd = le16_to_cpu(*(__le16 *)&vdev->vconfig[PCI_COMMAND]);
402 
403 	return cmd & PCI_COMMAND_MEMORY;
404 }
405 
406 /*
407  * Restore the *real* BARs after we detect a FLR or backdoor reset.
408  * (backdoor = some device specific technique that we didn't catch)
409  */
410 static void vfio_bar_restore(struct vfio_pci_device *vdev)
411 {
412 	struct pci_dev *pdev = vdev->pdev;
413 	u32 *rbar = vdev->rbar;
414 	u16 cmd;
415 	int i;
416 
417 	if (pdev->is_virtfn)
418 		return;
419 
420 	pci_info(pdev, "%s: reset recovery - restoring BARs\n", __func__);
421 
422 	for (i = PCI_BASE_ADDRESS_0; i <= PCI_BASE_ADDRESS_5; i += 4, rbar++)
423 		pci_user_write_config_dword(pdev, i, *rbar);
424 
425 	pci_user_write_config_dword(pdev, PCI_ROM_ADDRESS, *rbar);
426 
427 	if (vdev->nointx) {
428 		pci_user_read_config_word(pdev, PCI_COMMAND, &cmd);
429 		cmd |= PCI_COMMAND_INTX_DISABLE;
430 		pci_user_write_config_word(pdev, PCI_COMMAND, cmd);
431 	}
432 }
433 
434 static __le32 vfio_generate_bar_flags(struct pci_dev *pdev, int bar)
435 {
436 	unsigned long flags = pci_resource_flags(pdev, bar);
437 	u32 val;
438 
439 	if (flags & IORESOURCE_IO)
440 		return cpu_to_le32(PCI_BASE_ADDRESS_SPACE_IO);
441 
442 	val = PCI_BASE_ADDRESS_SPACE_MEMORY;
443 
444 	if (flags & IORESOURCE_PREFETCH)
445 		val |= PCI_BASE_ADDRESS_MEM_PREFETCH;
446 
447 	if (flags & IORESOURCE_MEM_64)
448 		val |= PCI_BASE_ADDRESS_MEM_TYPE_64;
449 
450 	return cpu_to_le32(val);
451 }
452 
453 /*
454  * Pretend we're hardware and tweak the values of the *virtual* PCI BARs
455  * to reflect the hardware capabilities.  This implements BAR sizing.
456  */
457 static void vfio_bar_fixup(struct vfio_pci_device *vdev)
458 {
459 	struct pci_dev *pdev = vdev->pdev;
460 	int i;
461 	__le32 *vbar;
462 	u64 mask;
463 
464 	vbar = (__le32 *)&vdev->vconfig[PCI_BASE_ADDRESS_0];
465 
466 	for (i = 0; i < PCI_STD_NUM_BARS; i++, vbar++) {
467 		int bar = i + PCI_STD_RESOURCES;
468 
469 		if (!pci_resource_start(pdev, bar)) {
470 			*vbar = 0; /* Unmapped by host = unimplemented to user */
471 			continue;
472 		}
473 
474 		mask = ~(pci_resource_len(pdev, bar) - 1);
475 
476 		*vbar &= cpu_to_le32((u32)mask);
477 		*vbar |= vfio_generate_bar_flags(pdev, bar);
478 
479 		if (*vbar & cpu_to_le32(PCI_BASE_ADDRESS_MEM_TYPE_64)) {
480 			vbar++;
481 			*vbar &= cpu_to_le32((u32)(mask >> 32));
482 			i++;
483 		}
484 	}
485 
486 	vbar = (__le32 *)&vdev->vconfig[PCI_ROM_ADDRESS];
487 
488 	/*
489 	 * NB. REGION_INFO will have reported zero size if we weren't able
490 	 * to read the ROM, but we still return the actual BAR size here if
491 	 * it exists (or the shadow ROM space).
492 	 */
493 	if (pci_resource_start(pdev, PCI_ROM_RESOURCE)) {
494 		mask = ~(pci_resource_len(pdev, PCI_ROM_RESOURCE) - 1);
495 		mask |= PCI_ROM_ADDRESS_ENABLE;
496 		*vbar &= cpu_to_le32((u32)mask);
497 	} else if (pdev->resource[PCI_ROM_RESOURCE].flags &
498 					IORESOURCE_ROM_SHADOW) {
499 		mask = ~(0x20000 - 1);
500 		mask |= PCI_ROM_ADDRESS_ENABLE;
501 		*vbar &= cpu_to_le32((u32)mask);
502 	} else
503 		*vbar = 0;
504 
505 	vdev->bardirty = false;
506 }
507 
508 static int vfio_basic_config_read(struct vfio_pci_device *vdev, int pos,
509 				  int count, struct perm_bits *perm,
510 				  int offset, __le32 *val)
511 {
512 	if (is_bar(offset)) /* pos == offset for basic config */
513 		vfio_bar_fixup(vdev);
514 
515 	count = vfio_default_config_read(vdev, pos, count, perm, offset, val);
516 
517 	/* Mask in virtual memory enable for SR-IOV devices */
518 	if (offset == PCI_COMMAND && vdev->pdev->is_virtfn) {
519 		u16 cmd = le16_to_cpu(*(__le16 *)&vdev->vconfig[PCI_COMMAND]);
520 		u32 tmp_val = le32_to_cpu(*val);
521 
522 		tmp_val |= cmd & PCI_COMMAND_MEMORY;
523 		*val = cpu_to_le32(tmp_val);
524 	}
525 
526 	return count;
527 }
528 
529 /* Test whether BARs match the value we think they should contain */
530 static bool vfio_need_bar_restore(struct vfio_pci_device *vdev)
531 {
532 	int i = 0, pos = PCI_BASE_ADDRESS_0, ret;
533 	u32 bar;
534 
535 	for (; pos <= PCI_BASE_ADDRESS_5; i++, pos += 4) {
536 		if (vdev->rbar[i]) {
537 			ret = pci_user_read_config_dword(vdev->pdev, pos, &bar);
538 			if (ret || vdev->rbar[i] != bar)
539 				return true;
540 		}
541 	}
542 
543 	return false;
544 }
545 
546 static int vfio_basic_config_write(struct vfio_pci_device *vdev, int pos,
547 				   int count, struct perm_bits *perm,
548 				   int offset, __le32 val)
549 {
550 	struct pci_dev *pdev = vdev->pdev;
551 	__le16 *virt_cmd;
552 	u16 new_cmd = 0;
553 	int ret;
554 
555 	virt_cmd = (__le16 *)&vdev->vconfig[PCI_COMMAND];
556 
557 	if (offset == PCI_COMMAND) {
558 		bool phys_mem, virt_mem, new_mem, phys_io, virt_io, new_io;
559 		u16 phys_cmd;
560 
561 		ret = pci_user_read_config_word(pdev, PCI_COMMAND, &phys_cmd);
562 		if (ret)
563 			return ret;
564 
565 		new_cmd = le32_to_cpu(val);
566 
567 		phys_io = !!(phys_cmd & PCI_COMMAND_IO);
568 		virt_io = !!(le16_to_cpu(*virt_cmd) & PCI_COMMAND_IO);
569 		new_io = !!(new_cmd & PCI_COMMAND_IO);
570 
571 		phys_mem = !!(phys_cmd & PCI_COMMAND_MEMORY);
572 		virt_mem = !!(le16_to_cpu(*virt_cmd) & PCI_COMMAND_MEMORY);
573 		new_mem = !!(new_cmd & PCI_COMMAND_MEMORY);
574 
575 		if (!new_mem)
576 			vfio_pci_zap_and_down_write_memory_lock(vdev);
577 		else
578 			down_write(&vdev->memory_lock);
579 
580 		/*
581 		 * If the user is writing mem/io enable (new_mem/io) and we
582 		 * think it's already enabled (virt_mem/io), but the hardware
583 		 * shows it disabled (phys_mem/io, then the device has
584 		 * undergone some kind of backdoor reset and needs to be
585 		 * restored before we allow it to enable the bars.
586 		 * SR-IOV devices will trigger this, but we catch them later
587 		 */
588 		if ((new_mem && virt_mem && !phys_mem) ||
589 		    (new_io && virt_io && !phys_io) ||
590 		    vfio_need_bar_restore(vdev))
591 			vfio_bar_restore(vdev);
592 	}
593 
594 	count = vfio_default_config_write(vdev, pos, count, perm, offset, val);
595 	if (count < 0) {
596 		if (offset == PCI_COMMAND)
597 			up_write(&vdev->memory_lock);
598 		return count;
599 	}
600 
601 	/*
602 	 * Save current memory/io enable bits in vconfig to allow for
603 	 * the test above next time.
604 	 */
605 	if (offset == PCI_COMMAND) {
606 		u16 mask = PCI_COMMAND_MEMORY | PCI_COMMAND_IO;
607 
608 		*virt_cmd &= cpu_to_le16(~mask);
609 		*virt_cmd |= cpu_to_le16(new_cmd & mask);
610 
611 		up_write(&vdev->memory_lock);
612 	}
613 
614 	/* Emulate INTx disable */
615 	if (offset >= PCI_COMMAND && offset <= PCI_COMMAND + 1) {
616 		bool virt_intx_disable;
617 
618 		virt_intx_disable = !!(le16_to_cpu(*virt_cmd) &
619 				       PCI_COMMAND_INTX_DISABLE);
620 
621 		if (virt_intx_disable && !vdev->virq_disabled) {
622 			vdev->virq_disabled = true;
623 			vfio_pci_intx_mask(vdev);
624 		} else if (!virt_intx_disable && vdev->virq_disabled) {
625 			vdev->virq_disabled = false;
626 			vfio_pci_intx_unmask(vdev);
627 		}
628 	}
629 
630 	if (is_bar(offset))
631 		vdev->bardirty = true;
632 
633 	return count;
634 }
635 
636 /* Permissions for the Basic PCI Header */
637 static int __init init_pci_cap_basic_perm(struct perm_bits *perm)
638 {
639 	if (alloc_perm_bits(perm, PCI_STD_HEADER_SIZEOF))
640 		return -ENOMEM;
641 
642 	perm->readfn = vfio_basic_config_read;
643 	perm->writefn = vfio_basic_config_write;
644 
645 	/* Virtualized for SR-IOV functions, which just have FFFF */
646 	p_setw(perm, PCI_VENDOR_ID, (u16)ALL_VIRT, NO_WRITE);
647 	p_setw(perm, PCI_DEVICE_ID, (u16)ALL_VIRT, NO_WRITE);
648 
649 	/*
650 	 * Virtualize INTx disable, we use it internally for interrupt
651 	 * control and can emulate it for non-PCI 2.3 devices.
652 	 */
653 	p_setw(perm, PCI_COMMAND, PCI_COMMAND_INTX_DISABLE, (u16)ALL_WRITE);
654 
655 	/* Virtualize capability list, we might want to skip/disable */
656 	p_setw(perm, PCI_STATUS, PCI_STATUS_CAP_LIST, NO_WRITE);
657 
658 	/* No harm to write */
659 	p_setb(perm, PCI_CACHE_LINE_SIZE, NO_VIRT, (u8)ALL_WRITE);
660 	p_setb(perm, PCI_LATENCY_TIMER, NO_VIRT, (u8)ALL_WRITE);
661 	p_setb(perm, PCI_BIST, NO_VIRT, (u8)ALL_WRITE);
662 
663 	/* Virtualize all bars, can't touch the real ones */
664 	p_setd(perm, PCI_BASE_ADDRESS_0, ALL_VIRT, ALL_WRITE);
665 	p_setd(perm, PCI_BASE_ADDRESS_1, ALL_VIRT, ALL_WRITE);
666 	p_setd(perm, PCI_BASE_ADDRESS_2, ALL_VIRT, ALL_WRITE);
667 	p_setd(perm, PCI_BASE_ADDRESS_3, ALL_VIRT, ALL_WRITE);
668 	p_setd(perm, PCI_BASE_ADDRESS_4, ALL_VIRT, ALL_WRITE);
669 	p_setd(perm, PCI_BASE_ADDRESS_5, ALL_VIRT, ALL_WRITE);
670 	p_setd(perm, PCI_ROM_ADDRESS, ALL_VIRT, ALL_WRITE);
671 
672 	/* Allow us to adjust capability chain */
673 	p_setb(perm, PCI_CAPABILITY_LIST, (u8)ALL_VIRT, NO_WRITE);
674 
675 	/* Sometimes used by sw, just virtualize */
676 	p_setb(perm, PCI_INTERRUPT_LINE, (u8)ALL_VIRT, (u8)ALL_WRITE);
677 
678 	/* Virtualize interrupt pin to allow hiding INTx */
679 	p_setb(perm, PCI_INTERRUPT_PIN, (u8)ALL_VIRT, (u8)NO_WRITE);
680 
681 	return 0;
682 }
683 
684 static int vfio_pm_config_write(struct vfio_pci_device *vdev, int pos,
685 				int count, struct perm_bits *perm,
686 				int offset, __le32 val)
687 {
688 	count = vfio_default_config_write(vdev, pos, count, perm, offset, val);
689 	if (count < 0)
690 		return count;
691 
692 	if (offset == PCI_PM_CTRL) {
693 		pci_power_t state;
694 
695 		switch (le32_to_cpu(val) & PCI_PM_CTRL_STATE_MASK) {
696 		case 0:
697 			state = PCI_D0;
698 			break;
699 		case 1:
700 			state = PCI_D1;
701 			break;
702 		case 2:
703 			state = PCI_D2;
704 			break;
705 		case 3:
706 			state = PCI_D3hot;
707 			break;
708 		}
709 
710 		vfio_pci_set_power_state(vdev, state);
711 	}
712 
713 	return count;
714 }
715 
716 /* Permissions for the Power Management capability */
717 static int __init init_pci_cap_pm_perm(struct perm_bits *perm)
718 {
719 	if (alloc_perm_bits(perm, pci_cap_length[PCI_CAP_ID_PM]))
720 		return -ENOMEM;
721 
722 	perm->writefn = vfio_pm_config_write;
723 
724 	/*
725 	 * We always virtualize the next field so we can remove
726 	 * capabilities from the chain if we want to.
727 	 */
728 	p_setb(perm, PCI_CAP_LIST_NEXT, (u8)ALL_VIRT, NO_WRITE);
729 
730 	/*
731 	 * Power management is defined *per function*, so we can let
732 	 * the user change power state, but we trap and initiate the
733 	 * change ourselves, so the state bits are read-only.
734 	 */
735 	p_setd(perm, PCI_PM_CTRL, NO_VIRT, ~PCI_PM_CTRL_STATE_MASK);
736 	return 0;
737 }
738 
739 static int vfio_vpd_config_write(struct vfio_pci_device *vdev, int pos,
740 				 int count, struct perm_bits *perm,
741 				 int offset, __le32 val)
742 {
743 	struct pci_dev *pdev = vdev->pdev;
744 	__le16 *paddr = (__le16 *)(vdev->vconfig + pos - offset + PCI_VPD_ADDR);
745 	__le32 *pdata = (__le32 *)(vdev->vconfig + pos - offset + PCI_VPD_DATA);
746 	u16 addr;
747 	u32 data;
748 
749 	/*
750 	 * Write through to emulation.  If the write includes the upper byte
751 	 * of PCI_VPD_ADDR, then the PCI_VPD_ADDR_F bit is written and we
752 	 * have work to do.
753 	 */
754 	count = vfio_default_config_write(vdev, pos, count, perm, offset, val);
755 	if (count < 0 || offset > PCI_VPD_ADDR + 1 ||
756 	    offset + count <= PCI_VPD_ADDR + 1)
757 		return count;
758 
759 	addr = le16_to_cpu(*paddr);
760 
761 	if (addr & PCI_VPD_ADDR_F) {
762 		data = le32_to_cpu(*pdata);
763 		if (pci_write_vpd(pdev, addr & ~PCI_VPD_ADDR_F, 4, &data) != 4)
764 			return count;
765 	} else {
766 		data = 0;
767 		if (pci_read_vpd(pdev, addr, 4, &data) < 0)
768 			return count;
769 		*pdata = cpu_to_le32(data);
770 	}
771 
772 	/*
773 	 * Toggle PCI_VPD_ADDR_F in the emulated PCI_VPD_ADDR register to
774 	 * signal completion.  If an error occurs above, we assume that not
775 	 * toggling this bit will induce a driver timeout.
776 	 */
777 	addr ^= PCI_VPD_ADDR_F;
778 	*paddr = cpu_to_le16(addr);
779 
780 	return count;
781 }
782 
783 /* Permissions for Vital Product Data capability */
784 static int __init init_pci_cap_vpd_perm(struct perm_bits *perm)
785 {
786 	if (alloc_perm_bits(perm, pci_cap_length[PCI_CAP_ID_VPD]))
787 		return -ENOMEM;
788 
789 	perm->writefn = vfio_vpd_config_write;
790 
791 	/*
792 	 * We always virtualize the next field so we can remove
793 	 * capabilities from the chain if we want to.
794 	 */
795 	p_setb(perm, PCI_CAP_LIST_NEXT, (u8)ALL_VIRT, NO_WRITE);
796 
797 	/*
798 	 * Both the address and data registers are virtualized to
799 	 * enable access through the pci_vpd_read/write functions
800 	 */
801 	p_setw(perm, PCI_VPD_ADDR, (u16)ALL_VIRT, (u16)ALL_WRITE);
802 	p_setd(perm, PCI_VPD_DATA, ALL_VIRT, ALL_WRITE);
803 
804 	return 0;
805 }
806 
807 /* Permissions for PCI-X capability */
808 static int __init init_pci_cap_pcix_perm(struct perm_bits *perm)
809 {
810 	/* Alloc 24, but only 8 are used in v0 */
811 	if (alloc_perm_bits(perm, PCI_CAP_PCIX_SIZEOF_V2))
812 		return -ENOMEM;
813 
814 	p_setb(perm, PCI_CAP_LIST_NEXT, (u8)ALL_VIRT, NO_WRITE);
815 
816 	p_setw(perm, PCI_X_CMD, NO_VIRT, (u16)ALL_WRITE);
817 	p_setd(perm, PCI_X_ECC_CSR, NO_VIRT, ALL_WRITE);
818 	return 0;
819 }
820 
821 static int vfio_exp_config_write(struct vfio_pci_device *vdev, int pos,
822 				 int count, struct perm_bits *perm,
823 				 int offset, __le32 val)
824 {
825 	__le16 *ctrl = (__le16 *)(vdev->vconfig + pos -
826 				  offset + PCI_EXP_DEVCTL);
827 	int readrq = le16_to_cpu(*ctrl) & PCI_EXP_DEVCTL_READRQ;
828 
829 	count = vfio_default_config_write(vdev, pos, count, perm, offset, val);
830 	if (count < 0)
831 		return count;
832 
833 	/*
834 	 * The FLR bit is virtualized, if set and the device supports PCIe
835 	 * FLR, issue a reset_function.  Regardless, clear the bit, the spec
836 	 * requires it to be always read as zero.  NB, reset_function might
837 	 * not use a PCIe FLR, we don't have that level of granularity.
838 	 */
839 	if (*ctrl & cpu_to_le16(PCI_EXP_DEVCTL_BCR_FLR)) {
840 		u32 cap;
841 		int ret;
842 
843 		*ctrl &= ~cpu_to_le16(PCI_EXP_DEVCTL_BCR_FLR);
844 
845 		ret = pci_user_read_config_dword(vdev->pdev,
846 						 pos - offset + PCI_EXP_DEVCAP,
847 						 &cap);
848 
849 		if (!ret && (cap & PCI_EXP_DEVCAP_FLR)) {
850 			vfio_pci_zap_and_down_write_memory_lock(vdev);
851 			pci_try_reset_function(vdev->pdev);
852 			up_write(&vdev->memory_lock);
853 		}
854 	}
855 
856 	/*
857 	 * MPS is virtualized to the user, writes do not change the physical
858 	 * register since determining a proper MPS value requires a system wide
859 	 * device view.  The MRRS is largely independent of MPS, but since the
860 	 * user does not have that system-wide view, they might set a safe, but
861 	 * inefficiently low value.  Here we allow writes through to hardware,
862 	 * but we set the floor to the physical device MPS setting, so that
863 	 * we can at least use full TLPs, as defined by the MPS value.
864 	 *
865 	 * NB, if any devices actually depend on an artificially low MRRS
866 	 * setting, this will need to be revisited, perhaps with a quirk
867 	 * though pcie_set_readrq().
868 	 */
869 	if (readrq != (le16_to_cpu(*ctrl) & PCI_EXP_DEVCTL_READRQ)) {
870 		readrq = 128 <<
871 			((le16_to_cpu(*ctrl) & PCI_EXP_DEVCTL_READRQ) >> 12);
872 		readrq = max(readrq, pcie_get_mps(vdev->pdev));
873 
874 		pcie_set_readrq(vdev->pdev, readrq);
875 	}
876 
877 	return count;
878 }
879 
880 /* Permissions for PCI Express capability */
881 static int __init init_pci_cap_exp_perm(struct perm_bits *perm)
882 {
883 	/* Alloc largest of possible sizes */
884 	if (alloc_perm_bits(perm, PCI_CAP_EXP_ENDPOINT_SIZEOF_V2))
885 		return -ENOMEM;
886 
887 	perm->writefn = vfio_exp_config_write;
888 
889 	p_setb(perm, PCI_CAP_LIST_NEXT, (u8)ALL_VIRT, NO_WRITE);
890 
891 	/*
892 	 * Allow writes to device control fields, except devctl_phantom,
893 	 * which could confuse IOMMU, MPS, which can break communication
894 	 * with other physical devices, and the ARI bit in devctl2, which
895 	 * is set at probe time.  FLR and MRRS get virtualized via our
896 	 * writefn.
897 	 */
898 	p_setw(perm, PCI_EXP_DEVCTL,
899 	       PCI_EXP_DEVCTL_BCR_FLR | PCI_EXP_DEVCTL_PAYLOAD |
900 	       PCI_EXP_DEVCTL_READRQ, ~PCI_EXP_DEVCTL_PHANTOM);
901 	p_setw(perm, PCI_EXP_DEVCTL2, NO_VIRT, ~PCI_EXP_DEVCTL2_ARI);
902 	return 0;
903 }
904 
905 static int vfio_af_config_write(struct vfio_pci_device *vdev, int pos,
906 				int count, struct perm_bits *perm,
907 				int offset, __le32 val)
908 {
909 	u8 *ctrl = vdev->vconfig + pos - offset + PCI_AF_CTRL;
910 
911 	count = vfio_default_config_write(vdev, pos, count, perm, offset, val);
912 	if (count < 0)
913 		return count;
914 
915 	/*
916 	 * The FLR bit is virtualized, if set and the device supports AF
917 	 * FLR, issue a reset_function.  Regardless, clear the bit, the spec
918 	 * requires it to be always read as zero.  NB, reset_function might
919 	 * not use an AF FLR, we don't have that level of granularity.
920 	 */
921 	if (*ctrl & PCI_AF_CTRL_FLR) {
922 		u8 cap;
923 		int ret;
924 
925 		*ctrl &= ~PCI_AF_CTRL_FLR;
926 
927 		ret = pci_user_read_config_byte(vdev->pdev,
928 						pos - offset + PCI_AF_CAP,
929 						&cap);
930 
931 		if (!ret && (cap & PCI_AF_CAP_FLR) && (cap & PCI_AF_CAP_TP)) {
932 			vfio_pci_zap_and_down_write_memory_lock(vdev);
933 			pci_try_reset_function(vdev->pdev);
934 			up_write(&vdev->memory_lock);
935 		}
936 	}
937 
938 	return count;
939 }
940 
941 /* Permissions for Advanced Function capability */
942 static int __init init_pci_cap_af_perm(struct perm_bits *perm)
943 {
944 	if (alloc_perm_bits(perm, pci_cap_length[PCI_CAP_ID_AF]))
945 		return -ENOMEM;
946 
947 	perm->writefn = vfio_af_config_write;
948 
949 	p_setb(perm, PCI_CAP_LIST_NEXT, (u8)ALL_VIRT, NO_WRITE);
950 	p_setb(perm, PCI_AF_CTRL, PCI_AF_CTRL_FLR, PCI_AF_CTRL_FLR);
951 	return 0;
952 }
953 
954 /* Permissions for Advanced Error Reporting extended capability */
955 static int __init init_pci_ext_cap_err_perm(struct perm_bits *perm)
956 {
957 	u32 mask;
958 
959 	if (alloc_perm_bits(perm, pci_ext_cap_length[PCI_EXT_CAP_ID_ERR]))
960 		return -ENOMEM;
961 
962 	/*
963 	 * Virtualize the first dword of all express capabilities
964 	 * because it includes the next pointer.  This lets us later
965 	 * remove capabilities from the chain if we need to.
966 	 */
967 	p_setd(perm, 0, ALL_VIRT, NO_WRITE);
968 
969 	/* Writable bits mask */
970 	mask =	PCI_ERR_UNC_UND |		/* Undefined */
971 		PCI_ERR_UNC_DLP |		/* Data Link Protocol */
972 		PCI_ERR_UNC_SURPDN |		/* Surprise Down */
973 		PCI_ERR_UNC_POISON_TLP |	/* Poisoned TLP */
974 		PCI_ERR_UNC_FCP |		/* Flow Control Protocol */
975 		PCI_ERR_UNC_COMP_TIME |		/* Completion Timeout */
976 		PCI_ERR_UNC_COMP_ABORT |	/* Completer Abort */
977 		PCI_ERR_UNC_UNX_COMP |		/* Unexpected Completion */
978 		PCI_ERR_UNC_RX_OVER |		/* Receiver Overflow */
979 		PCI_ERR_UNC_MALF_TLP |		/* Malformed TLP */
980 		PCI_ERR_UNC_ECRC |		/* ECRC Error Status */
981 		PCI_ERR_UNC_UNSUP |		/* Unsupported Request */
982 		PCI_ERR_UNC_ACSV |		/* ACS Violation */
983 		PCI_ERR_UNC_INTN |		/* internal error */
984 		PCI_ERR_UNC_MCBTLP |		/* MC blocked TLP */
985 		PCI_ERR_UNC_ATOMEG |		/* Atomic egress blocked */
986 		PCI_ERR_UNC_TLPPRE;		/* TLP prefix blocked */
987 	p_setd(perm, PCI_ERR_UNCOR_STATUS, NO_VIRT, mask);
988 	p_setd(perm, PCI_ERR_UNCOR_MASK, NO_VIRT, mask);
989 	p_setd(perm, PCI_ERR_UNCOR_SEVER, NO_VIRT, mask);
990 
991 	mask =	PCI_ERR_COR_RCVR |		/* Receiver Error Status */
992 		PCI_ERR_COR_BAD_TLP |		/* Bad TLP Status */
993 		PCI_ERR_COR_BAD_DLLP |		/* Bad DLLP Status */
994 		PCI_ERR_COR_REP_ROLL |		/* REPLAY_NUM Rollover */
995 		PCI_ERR_COR_REP_TIMER |		/* Replay Timer Timeout */
996 		PCI_ERR_COR_ADV_NFAT |		/* Advisory Non-Fatal */
997 		PCI_ERR_COR_INTERNAL |		/* Corrected Internal */
998 		PCI_ERR_COR_LOG_OVER;		/* Header Log Overflow */
999 	p_setd(perm, PCI_ERR_COR_STATUS, NO_VIRT, mask);
1000 	p_setd(perm, PCI_ERR_COR_MASK, NO_VIRT, mask);
1001 
1002 	mask =	PCI_ERR_CAP_ECRC_GENE |		/* ECRC Generation Enable */
1003 		PCI_ERR_CAP_ECRC_CHKE;		/* ECRC Check Enable */
1004 	p_setd(perm, PCI_ERR_CAP, NO_VIRT, mask);
1005 	return 0;
1006 }
1007 
1008 /* Permissions for Power Budgeting extended capability */
1009 static int __init init_pci_ext_cap_pwr_perm(struct perm_bits *perm)
1010 {
1011 	if (alloc_perm_bits(perm, pci_ext_cap_length[PCI_EXT_CAP_ID_PWR]))
1012 		return -ENOMEM;
1013 
1014 	p_setd(perm, 0, ALL_VIRT, NO_WRITE);
1015 
1016 	/* Writing the data selector is OK, the info is still read-only */
1017 	p_setb(perm, PCI_PWR_DATA, NO_VIRT, (u8)ALL_WRITE);
1018 	return 0;
1019 }
1020 
1021 /*
1022  * Initialize the shared permission tables
1023  */
1024 void vfio_pci_uninit_perm_bits(void)
1025 {
1026 	free_perm_bits(&cap_perms[PCI_CAP_ID_BASIC]);
1027 
1028 	free_perm_bits(&cap_perms[PCI_CAP_ID_PM]);
1029 	free_perm_bits(&cap_perms[PCI_CAP_ID_VPD]);
1030 	free_perm_bits(&cap_perms[PCI_CAP_ID_PCIX]);
1031 	free_perm_bits(&cap_perms[PCI_CAP_ID_EXP]);
1032 	free_perm_bits(&cap_perms[PCI_CAP_ID_AF]);
1033 
1034 	free_perm_bits(&ecap_perms[PCI_EXT_CAP_ID_ERR]);
1035 	free_perm_bits(&ecap_perms[PCI_EXT_CAP_ID_PWR]);
1036 }
1037 
1038 int __init vfio_pci_init_perm_bits(void)
1039 {
1040 	int ret;
1041 
1042 	/* Basic config space */
1043 	ret = init_pci_cap_basic_perm(&cap_perms[PCI_CAP_ID_BASIC]);
1044 
1045 	/* Capabilities */
1046 	ret |= init_pci_cap_pm_perm(&cap_perms[PCI_CAP_ID_PM]);
1047 	ret |= init_pci_cap_vpd_perm(&cap_perms[PCI_CAP_ID_VPD]);
1048 	ret |= init_pci_cap_pcix_perm(&cap_perms[PCI_CAP_ID_PCIX]);
1049 	cap_perms[PCI_CAP_ID_VNDR].writefn = vfio_raw_config_write;
1050 	ret |= init_pci_cap_exp_perm(&cap_perms[PCI_CAP_ID_EXP]);
1051 	ret |= init_pci_cap_af_perm(&cap_perms[PCI_CAP_ID_AF]);
1052 
1053 	/* Extended capabilities */
1054 	ret |= init_pci_ext_cap_err_perm(&ecap_perms[PCI_EXT_CAP_ID_ERR]);
1055 	ret |= init_pci_ext_cap_pwr_perm(&ecap_perms[PCI_EXT_CAP_ID_PWR]);
1056 	ecap_perms[PCI_EXT_CAP_ID_VNDR].writefn = vfio_raw_config_write;
1057 
1058 	if (ret)
1059 		vfio_pci_uninit_perm_bits();
1060 
1061 	return ret;
1062 }
1063 
1064 static int vfio_find_cap_start(struct vfio_pci_device *vdev, int pos)
1065 {
1066 	u8 cap;
1067 	int base = (pos >= PCI_CFG_SPACE_SIZE) ? PCI_CFG_SPACE_SIZE :
1068 						 PCI_STD_HEADER_SIZEOF;
1069 	cap = vdev->pci_config_map[pos];
1070 
1071 	if (cap == PCI_CAP_ID_BASIC)
1072 		return 0;
1073 
1074 	/* XXX Can we have to abutting capabilities of the same type? */
1075 	while (pos - 1 >= base && vdev->pci_config_map[pos - 1] == cap)
1076 		pos--;
1077 
1078 	return pos;
1079 }
1080 
1081 static int vfio_msi_config_read(struct vfio_pci_device *vdev, int pos,
1082 				int count, struct perm_bits *perm,
1083 				int offset, __le32 *val)
1084 {
1085 	/* Update max available queue size from msi_qmax */
1086 	if (offset <= PCI_MSI_FLAGS && offset + count >= PCI_MSI_FLAGS) {
1087 		__le16 *flags;
1088 		int start;
1089 
1090 		start = vfio_find_cap_start(vdev, pos);
1091 
1092 		flags = (__le16 *)&vdev->vconfig[start];
1093 
1094 		*flags &= cpu_to_le16(~PCI_MSI_FLAGS_QMASK);
1095 		*flags |= cpu_to_le16(vdev->msi_qmax << 1);
1096 	}
1097 
1098 	return vfio_default_config_read(vdev, pos, count, perm, offset, val);
1099 }
1100 
1101 static int vfio_msi_config_write(struct vfio_pci_device *vdev, int pos,
1102 				 int count, struct perm_bits *perm,
1103 				 int offset, __le32 val)
1104 {
1105 	count = vfio_default_config_write(vdev, pos, count, perm, offset, val);
1106 	if (count < 0)
1107 		return count;
1108 
1109 	/* Fixup and write configured queue size and enable to hardware */
1110 	if (offset <= PCI_MSI_FLAGS && offset + count >= PCI_MSI_FLAGS) {
1111 		__le16 *pflags;
1112 		u16 flags;
1113 		int start, ret;
1114 
1115 		start = vfio_find_cap_start(vdev, pos);
1116 
1117 		pflags = (__le16 *)&vdev->vconfig[start + PCI_MSI_FLAGS];
1118 
1119 		flags = le16_to_cpu(*pflags);
1120 
1121 		/* MSI is enabled via ioctl */
1122 		if  (!is_msi(vdev))
1123 			flags &= ~PCI_MSI_FLAGS_ENABLE;
1124 
1125 		/* Check queue size */
1126 		if ((flags & PCI_MSI_FLAGS_QSIZE) >> 4 > vdev->msi_qmax) {
1127 			flags &= ~PCI_MSI_FLAGS_QSIZE;
1128 			flags |= vdev->msi_qmax << 4;
1129 		}
1130 
1131 		/* Write back to virt and to hardware */
1132 		*pflags = cpu_to_le16(flags);
1133 		ret = pci_user_write_config_word(vdev->pdev,
1134 						 start + PCI_MSI_FLAGS,
1135 						 flags);
1136 		if (ret)
1137 			return ret;
1138 	}
1139 
1140 	return count;
1141 }
1142 
1143 /*
1144  * MSI determination is per-device, so this routine gets used beyond
1145  * initialization time. Don't add __init
1146  */
1147 static int init_pci_cap_msi_perm(struct perm_bits *perm, int len, u16 flags)
1148 {
1149 	if (alloc_perm_bits(perm, len))
1150 		return -ENOMEM;
1151 
1152 	perm->readfn = vfio_msi_config_read;
1153 	perm->writefn = vfio_msi_config_write;
1154 
1155 	p_setb(perm, PCI_CAP_LIST_NEXT, (u8)ALL_VIRT, NO_WRITE);
1156 
1157 	/*
1158 	 * The upper byte of the control register is reserved,
1159 	 * just setup the lower byte.
1160 	 */
1161 	p_setb(perm, PCI_MSI_FLAGS, (u8)ALL_VIRT, (u8)ALL_WRITE);
1162 	p_setd(perm, PCI_MSI_ADDRESS_LO, ALL_VIRT, ALL_WRITE);
1163 	if (flags & PCI_MSI_FLAGS_64BIT) {
1164 		p_setd(perm, PCI_MSI_ADDRESS_HI, ALL_VIRT, ALL_WRITE);
1165 		p_setw(perm, PCI_MSI_DATA_64, (u16)ALL_VIRT, (u16)ALL_WRITE);
1166 		if (flags & PCI_MSI_FLAGS_MASKBIT) {
1167 			p_setd(perm, PCI_MSI_MASK_64, NO_VIRT, ALL_WRITE);
1168 			p_setd(perm, PCI_MSI_PENDING_64, NO_VIRT, ALL_WRITE);
1169 		}
1170 	} else {
1171 		p_setw(perm, PCI_MSI_DATA_32, (u16)ALL_VIRT, (u16)ALL_WRITE);
1172 		if (flags & PCI_MSI_FLAGS_MASKBIT) {
1173 			p_setd(perm, PCI_MSI_MASK_32, NO_VIRT, ALL_WRITE);
1174 			p_setd(perm, PCI_MSI_PENDING_32, NO_VIRT, ALL_WRITE);
1175 		}
1176 	}
1177 	return 0;
1178 }
1179 
1180 /* Determine MSI CAP field length; initialize msi_perms on 1st call per vdev */
1181 static int vfio_msi_cap_len(struct vfio_pci_device *vdev, u8 pos)
1182 {
1183 	struct pci_dev *pdev = vdev->pdev;
1184 	int len, ret;
1185 	u16 flags;
1186 
1187 	ret = pci_read_config_word(pdev, pos + PCI_MSI_FLAGS, &flags);
1188 	if (ret)
1189 		return pcibios_err_to_errno(ret);
1190 
1191 	len = 10; /* Minimum size */
1192 	if (flags & PCI_MSI_FLAGS_64BIT)
1193 		len += 4;
1194 	if (flags & PCI_MSI_FLAGS_MASKBIT)
1195 		len += 10;
1196 
1197 	if (vdev->msi_perm)
1198 		return len;
1199 
1200 	vdev->msi_perm = kmalloc(sizeof(struct perm_bits), GFP_KERNEL);
1201 	if (!vdev->msi_perm)
1202 		return -ENOMEM;
1203 
1204 	ret = init_pci_cap_msi_perm(vdev->msi_perm, len, flags);
1205 	if (ret) {
1206 		kfree(vdev->msi_perm);
1207 		return ret;
1208 	}
1209 
1210 	return len;
1211 }
1212 
1213 /* Determine extended capability length for VC (2 & 9) and MFVC */
1214 static int vfio_vc_cap_len(struct vfio_pci_device *vdev, u16 pos)
1215 {
1216 	struct pci_dev *pdev = vdev->pdev;
1217 	u32 tmp;
1218 	int ret, evcc, phases, vc_arb;
1219 	int len = PCI_CAP_VC_BASE_SIZEOF;
1220 
1221 	ret = pci_read_config_dword(pdev, pos + PCI_VC_PORT_CAP1, &tmp);
1222 	if (ret)
1223 		return pcibios_err_to_errno(ret);
1224 
1225 	evcc = tmp & PCI_VC_CAP1_EVCC; /* extended vc count */
1226 	ret = pci_read_config_dword(pdev, pos + PCI_VC_PORT_CAP2, &tmp);
1227 	if (ret)
1228 		return pcibios_err_to_errno(ret);
1229 
1230 	if (tmp & PCI_VC_CAP2_128_PHASE)
1231 		phases = 128;
1232 	else if (tmp & PCI_VC_CAP2_64_PHASE)
1233 		phases = 64;
1234 	else if (tmp & PCI_VC_CAP2_32_PHASE)
1235 		phases = 32;
1236 	else
1237 		phases = 0;
1238 
1239 	vc_arb = phases * 4;
1240 
1241 	/*
1242 	 * Port arbitration tables are root & switch only;
1243 	 * function arbitration tables are function 0 only.
1244 	 * In either case, we'll never let user write them so
1245 	 * we don't care how big they are
1246 	 */
1247 	len += (1 + evcc) * PCI_CAP_VC_PER_VC_SIZEOF;
1248 	if (vc_arb) {
1249 		len = round_up(len, 16);
1250 		len += vc_arb / 8;
1251 	}
1252 	return len;
1253 }
1254 
1255 static int vfio_cap_len(struct vfio_pci_device *vdev, u8 cap, u8 pos)
1256 {
1257 	struct pci_dev *pdev = vdev->pdev;
1258 	u32 dword;
1259 	u16 word;
1260 	u8 byte;
1261 	int ret;
1262 
1263 	switch (cap) {
1264 	case PCI_CAP_ID_MSI:
1265 		return vfio_msi_cap_len(vdev, pos);
1266 	case PCI_CAP_ID_PCIX:
1267 		ret = pci_read_config_word(pdev, pos + PCI_X_CMD, &word);
1268 		if (ret)
1269 			return pcibios_err_to_errno(ret);
1270 
1271 		if (PCI_X_CMD_VERSION(word)) {
1272 			if (pdev->cfg_size > PCI_CFG_SPACE_SIZE) {
1273 				/* Test for extended capabilities */
1274 				pci_read_config_dword(pdev, PCI_CFG_SPACE_SIZE,
1275 						      &dword);
1276 				vdev->extended_caps = (dword != 0);
1277 			}
1278 			return PCI_CAP_PCIX_SIZEOF_V2;
1279 		} else
1280 			return PCI_CAP_PCIX_SIZEOF_V0;
1281 	case PCI_CAP_ID_VNDR:
1282 		/* length follows next field */
1283 		ret = pci_read_config_byte(pdev, pos + PCI_CAP_FLAGS, &byte);
1284 		if (ret)
1285 			return pcibios_err_to_errno(ret);
1286 
1287 		return byte;
1288 	case PCI_CAP_ID_EXP:
1289 		if (pdev->cfg_size > PCI_CFG_SPACE_SIZE) {
1290 			/* Test for extended capabilities */
1291 			pci_read_config_dword(pdev, PCI_CFG_SPACE_SIZE, &dword);
1292 			vdev->extended_caps = (dword != 0);
1293 		}
1294 
1295 		/* length based on version and type */
1296 		if ((pcie_caps_reg(pdev) & PCI_EXP_FLAGS_VERS) == 1) {
1297 			if (pci_pcie_type(pdev) == PCI_EXP_TYPE_RC_END)
1298 				return 0xc; /* "All Devices" only, no link */
1299 			return PCI_CAP_EXP_ENDPOINT_SIZEOF_V1;
1300 		} else {
1301 			if (pci_pcie_type(pdev) == PCI_EXP_TYPE_RC_END)
1302 				return 0x2c; /* No link */
1303 			return PCI_CAP_EXP_ENDPOINT_SIZEOF_V2;
1304 		}
1305 	case PCI_CAP_ID_HT:
1306 		ret = pci_read_config_byte(pdev, pos + 3, &byte);
1307 		if (ret)
1308 			return pcibios_err_to_errno(ret);
1309 
1310 		return (byte & HT_3BIT_CAP_MASK) ?
1311 			HT_CAP_SIZEOF_SHORT : HT_CAP_SIZEOF_LONG;
1312 	case PCI_CAP_ID_SATA:
1313 		ret = pci_read_config_byte(pdev, pos + PCI_SATA_REGS, &byte);
1314 		if (ret)
1315 			return pcibios_err_to_errno(ret);
1316 
1317 		byte &= PCI_SATA_REGS_MASK;
1318 		if (byte == PCI_SATA_REGS_INLINE)
1319 			return PCI_SATA_SIZEOF_LONG;
1320 		else
1321 			return PCI_SATA_SIZEOF_SHORT;
1322 	default:
1323 		pci_warn(pdev, "%s: unknown length for PCI cap %#x@%#x\n",
1324 			 __func__, cap, pos);
1325 	}
1326 
1327 	return 0;
1328 }
1329 
1330 static int vfio_ext_cap_len(struct vfio_pci_device *vdev, u16 ecap, u16 epos)
1331 {
1332 	struct pci_dev *pdev = vdev->pdev;
1333 	u8 byte;
1334 	u32 dword;
1335 	int ret;
1336 
1337 	switch (ecap) {
1338 	case PCI_EXT_CAP_ID_VNDR:
1339 		ret = pci_read_config_dword(pdev, epos + PCI_VSEC_HDR, &dword);
1340 		if (ret)
1341 			return pcibios_err_to_errno(ret);
1342 
1343 		return dword >> PCI_VSEC_HDR_LEN_SHIFT;
1344 	case PCI_EXT_CAP_ID_VC:
1345 	case PCI_EXT_CAP_ID_VC9:
1346 	case PCI_EXT_CAP_ID_MFVC:
1347 		return vfio_vc_cap_len(vdev, epos);
1348 	case PCI_EXT_CAP_ID_ACS:
1349 		ret = pci_read_config_byte(pdev, epos + PCI_ACS_CAP, &byte);
1350 		if (ret)
1351 			return pcibios_err_to_errno(ret);
1352 
1353 		if (byte & PCI_ACS_EC) {
1354 			int bits;
1355 
1356 			ret = pci_read_config_byte(pdev,
1357 						   epos + PCI_ACS_EGRESS_BITS,
1358 						   &byte);
1359 			if (ret)
1360 				return pcibios_err_to_errno(ret);
1361 
1362 			bits = byte ? round_up(byte, 32) : 256;
1363 			return 8 + (bits / 8);
1364 		}
1365 		return 8;
1366 
1367 	case PCI_EXT_CAP_ID_REBAR:
1368 		ret = pci_read_config_byte(pdev, epos + PCI_REBAR_CTRL, &byte);
1369 		if (ret)
1370 			return pcibios_err_to_errno(ret);
1371 
1372 		byte &= PCI_REBAR_CTRL_NBAR_MASK;
1373 		byte >>= PCI_REBAR_CTRL_NBAR_SHIFT;
1374 
1375 		return 4 + (byte * 8);
1376 	case PCI_EXT_CAP_ID_DPA:
1377 		ret = pci_read_config_byte(pdev, epos + PCI_DPA_CAP, &byte);
1378 		if (ret)
1379 			return pcibios_err_to_errno(ret);
1380 
1381 		byte &= PCI_DPA_CAP_SUBSTATE_MASK;
1382 		return PCI_DPA_BASE_SIZEOF + byte + 1;
1383 	case PCI_EXT_CAP_ID_TPH:
1384 		ret = pci_read_config_dword(pdev, epos + PCI_TPH_CAP, &dword);
1385 		if (ret)
1386 			return pcibios_err_to_errno(ret);
1387 
1388 		if ((dword & PCI_TPH_CAP_LOC_MASK) == PCI_TPH_LOC_CAP) {
1389 			int sts;
1390 
1391 			sts = dword & PCI_TPH_CAP_ST_MASK;
1392 			sts >>= PCI_TPH_CAP_ST_SHIFT;
1393 			return PCI_TPH_BASE_SIZEOF + (sts * 2) + 2;
1394 		}
1395 		return PCI_TPH_BASE_SIZEOF;
1396 	default:
1397 		pci_warn(pdev, "%s: unknown length for PCI ecap %#x@%#x\n",
1398 			 __func__, ecap, epos);
1399 	}
1400 
1401 	return 0;
1402 }
1403 
1404 static int vfio_fill_vconfig_bytes(struct vfio_pci_device *vdev,
1405 				   int offset, int size)
1406 {
1407 	struct pci_dev *pdev = vdev->pdev;
1408 	int ret = 0;
1409 
1410 	/*
1411 	 * We try to read physical config space in the largest chunks
1412 	 * we can, assuming that all of the fields support dword access.
1413 	 * pci_save_state() makes this same assumption and seems to do ok.
1414 	 */
1415 	while (size) {
1416 		int filled;
1417 
1418 		if (size >= 4 && !(offset % 4)) {
1419 			__le32 *dwordp = (__le32 *)&vdev->vconfig[offset];
1420 			u32 dword;
1421 
1422 			ret = pci_read_config_dword(pdev, offset, &dword);
1423 			if (ret)
1424 				return ret;
1425 			*dwordp = cpu_to_le32(dword);
1426 			filled = 4;
1427 		} else if (size >= 2 && !(offset % 2)) {
1428 			__le16 *wordp = (__le16 *)&vdev->vconfig[offset];
1429 			u16 word;
1430 
1431 			ret = pci_read_config_word(pdev, offset, &word);
1432 			if (ret)
1433 				return ret;
1434 			*wordp = cpu_to_le16(word);
1435 			filled = 2;
1436 		} else {
1437 			u8 *byte = &vdev->vconfig[offset];
1438 			ret = pci_read_config_byte(pdev, offset, byte);
1439 			if (ret)
1440 				return ret;
1441 			filled = 1;
1442 		}
1443 
1444 		offset += filled;
1445 		size -= filled;
1446 	}
1447 
1448 	return ret;
1449 }
1450 
1451 static int vfio_cap_init(struct vfio_pci_device *vdev)
1452 {
1453 	struct pci_dev *pdev = vdev->pdev;
1454 	u8 *map = vdev->pci_config_map;
1455 	u16 status;
1456 	u8 pos, *prev, cap;
1457 	int loops, ret, caps = 0;
1458 
1459 	/* Any capabilities? */
1460 	ret = pci_read_config_word(pdev, PCI_STATUS, &status);
1461 	if (ret)
1462 		return ret;
1463 
1464 	if (!(status & PCI_STATUS_CAP_LIST))
1465 		return 0; /* Done */
1466 
1467 	ret = pci_read_config_byte(pdev, PCI_CAPABILITY_LIST, &pos);
1468 	if (ret)
1469 		return ret;
1470 
1471 	/* Mark the previous position in case we want to skip a capability */
1472 	prev = &vdev->vconfig[PCI_CAPABILITY_LIST];
1473 
1474 	/* We can bound our loop, capabilities are dword aligned */
1475 	loops = (PCI_CFG_SPACE_SIZE - PCI_STD_HEADER_SIZEOF) / PCI_CAP_SIZEOF;
1476 	while (pos && loops--) {
1477 		u8 next;
1478 		int i, len = 0;
1479 
1480 		ret = pci_read_config_byte(pdev, pos, &cap);
1481 		if (ret)
1482 			return ret;
1483 
1484 		ret = pci_read_config_byte(pdev,
1485 					   pos + PCI_CAP_LIST_NEXT, &next);
1486 		if (ret)
1487 			return ret;
1488 
1489 		/*
1490 		 * ID 0 is a NULL capability, conflicting with our fake
1491 		 * PCI_CAP_ID_BASIC.  As it has no content, consider it
1492 		 * hidden for now.
1493 		 */
1494 		if (cap && cap <= PCI_CAP_ID_MAX) {
1495 			len = pci_cap_length[cap];
1496 			if (len == 0xFF) { /* Variable length */
1497 				len = vfio_cap_len(vdev, cap, pos);
1498 				if (len < 0)
1499 					return len;
1500 			}
1501 		}
1502 
1503 		if (!len) {
1504 			pci_info(pdev, "%s: hiding cap %#x@%#x\n", __func__,
1505 				 cap, pos);
1506 			*prev = next;
1507 			pos = next;
1508 			continue;
1509 		}
1510 
1511 		/* Sanity check, do we overlap other capabilities? */
1512 		for (i = 0; i < len; i++) {
1513 			if (likely(map[pos + i] == PCI_CAP_ID_INVALID))
1514 				continue;
1515 
1516 			pci_warn(pdev, "%s: PCI config conflict @%#x, was cap %#x now cap %#x\n",
1517 				 __func__, pos + i, map[pos + i], cap);
1518 		}
1519 
1520 		BUILD_BUG_ON(PCI_CAP_ID_MAX >= PCI_CAP_ID_INVALID_VIRT);
1521 
1522 		memset(map + pos, cap, len);
1523 		ret = vfio_fill_vconfig_bytes(vdev, pos, len);
1524 		if (ret)
1525 			return ret;
1526 
1527 		prev = &vdev->vconfig[pos + PCI_CAP_LIST_NEXT];
1528 		pos = next;
1529 		caps++;
1530 	}
1531 
1532 	/* If we didn't fill any capabilities, clear the status flag */
1533 	if (!caps) {
1534 		__le16 *vstatus = (__le16 *)&vdev->vconfig[PCI_STATUS];
1535 		*vstatus &= ~cpu_to_le16(PCI_STATUS_CAP_LIST);
1536 	}
1537 
1538 	return 0;
1539 }
1540 
1541 static int vfio_ecap_init(struct vfio_pci_device *vdev)
1542 {
1543 	struct pci_dev *pdev = vdev->pdev;
1544 	u8 *map = vdev->pci_config_map;
1545 	u16 epos;
1546 	__le32 *prev = NULL;
1547 	int loops, ret, ecaps = 0;
1548 
1549 	if (!vdev->extended_caps)
1550 		return 0;
1551 
1552 	epos = PCI_CFG_SPACE_SIZE;
1553 
1554 	loops = (pdev->cfg_size - PCI_CFG_SPACE_SIZE) / PCI_CAP_SIZEOF;
1555 
1556 	while (loops-- && epos >= PCI_CFG_SPACE_SIZE) {
1557 		u32 header;
1558 		u16 ecap;
1559 		int i, len = 0;
1560 		bool hidden = false;
1561 
1562 		ret = pci_read_config_dword(pdev, epos, &header);
1563 		if (ret)
1564 			return ret;
1565 
1566 		ecap = PCI_EXT_CAP_ID(header);
1567 
1568 		if (ecap <= PCI_EXT_CAP_ID_MAX) {
1569 			len = pci_ext_cap_length[ecap];
1570 			if (len == 0xFF) {
1571 				len = vfio_ext_cap_len(vdev, ecap, epos);
1572 				if (len < 0)
1573 					return ret;
1574 			}
1575 		}
1576 
1577 		if (!len) {
1578 			pci_info(pdev, "%s: hiding ecap %#x@%#x\n",
1579 				 __func__, ecap, epos);
1580 
1581 			/* If not the first in the chain, we can skip over it */
1582 			if (prev) {
1583 				u32 val = epos = PCI_EXT_CAP_NEXT(header);
1584 				*prev &= cpu_to_le32(~(0xffcU << 20));
1585 				*prev |= cpu_to_le32(val << 20);
1586 				continue;
1587 			}
1588 
1589 			/*
1590 			 * Otherwise, fill in a placeholder, the direct
1591 			 * readfn will virtualize this automatically
1592 			 */
1593 			len = PCI_CAP_SIZEOF;
1594 			hidden = true;
1595 		}
1596 
1597 		for (i = 0; i < len; i++) {
1598 			if (likely(map[epos + i] == PCI_CAP_ID_INVALID))
1599 				continue;
1600 
1601 			pci_warn(pdev, "%s: PCI config conflict @%#x, was ecap %#x now ecap %#x\n",
1602 				 __func__, epos + i, map[epos + i], ecap);
1603 		}
1604 
1605 		/*
1606 		 * Even though ecap is 2 bytes, we're currently a long way
1607 		 * from exceeding 1 byte capabilities.  If we ever make it
1608 		 * up to 0xFE we'll need to up this to a two-byte, byte map.
1609 		 */
1610 		BUILD_BUG_ON(PCI_EXT_CAP_ID_MAX >= PCI_CAP_ID_INVALID_VIRT);
1611 
1612 		memset(map + epos, ecap, len);
1613 		ret = vfio_fill_vconfig_bytes(vdev, epos, len);
1614 		if (ret)
1615 			return ret;
1616 
1617 		/*
1618 		 * If we're just using this capability to anchor the list,
1619 		 * hide the real ID.  Only count real ecaps.  XXX PCI spec
1620 		 * indicates to use cap id = 0, version = 0, next = 0 if
1621 		 * ecaps are absent, hope users check all the way to next.
1622 		 */
1623 		if (hidden)
1624 			*(__le32 *)&vdev->vconfig[epos] &=
1625 				cpu_to_le32((0xffcU << 20));
1626 		else
1627 			ecaps++;
1628 
1629 		prev = (__le32 *)&vdev->vconfig[epos];
1630 		epos = PCI_EXT_CAP_NEXT(header);
1631 	}
1632 
1633 	if (!ecaps)
1634 		*(u32 *)&vdev->vconfig[PCI_CFG_SPACE_SIZE] = 0;
1635 
1636 	return 0;
1637 }
1638 
1639 /*
1640  * Nag about hardware bugs, hopefully to have vendors fix them, but at least
1641  * to collect a list of dependencies for the VF INTx pin quirk below.
1642  */
1643 static const struct pci_device_id known_bogus_vf_intx_pin[] = {
1644 	{ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x270c) },
1645 	{}
1646 };
1647 
1648 /*
1649  * For each device we allocate a pci_config_map that indicates the
1650  * capability occupying each dword and thus the struct perm_bits we
1651  * use for read and write.  We also allocate a virtualized config
1652  * space which tracks reads and writes to bits that we emulate for
1653  * the user.  Initial values filled from device.
1654  *
1655  * Using shared struct perm_bits between all vfio-pci devices saves
1656  * us from allocating cfg_size buffers for virt and write for every
1657  * device.  We could remove vconfig and allocate individual buffers
1658  * for each area requiring emulated bits, but the array of pointers
1659  * would be comparable in size (at least for standard config space).
1660  */
1661 int vfio_config_init(struct vfio_pci_device *vdev)
1662 {
1663 	struct pci_dev *pdev = vdev->pdev;
1664 	u8 *map, *vconfig;
1665 	int ret;
1666 
1667 	/*
1668 	 * Config space, caps and ecaps are all dword aligned, so we could
1669 	 * use one byte per dword to record the type.  However, there are
1670 	 * no requiremenst on the length of a capability, so the gap between
1671 	 * capabilities needs byte granularity.
1672 	 */
1673 	map = kmalloc(pdev->cfg_size, GFP_KERNEL);
1674 	if (!map)
1675 		return -ENOMEM;
1676 
1677 	vconfig = kmalloc(pdev->cfg_size, GFP_KERNEL);
1678 	if (!vconfig) {
1679 		kfree(map);
1680 		return -ENOMEM;
1681 	}
1682 
1683 	vdev->pci_config_map = map;
1684 	vdev->vconfig = vconfig;
1685 
1686 	memset(map, PCI_CAP_ID_BASIC, PCI_STD_HEADER_SIZEOF);
1687 	memset(map + PCI_STD_HEADER_SIZEOF, PCI_CAP_ID_INVALID,
1688 	       pdev->cfg_size - PCI_STD_HEADER_SIZEOF);
1689 
1690 	ret = vfio_fill_vconfig_bytes(vdev, 0, PCI_STD_HEADER_SIZEOF);
1691 	if (ret)
1692 		goto out;
1693 
1694 	vdev->bardirty = true;
1695 
1696 	/*
1697 	 * XXX can we just pci_load_saved_state/pci_restore_state?
1698 	 * may need to rebuild vconfig after that
1699 	 */
1700 
1701 	/* For restore after reset */
1702 	vdev->rbar[0] = le32_to_cpu(*(__le32 *)&vconfig[PCI_BASE_ADDRESS_0]);
1703 	vdev->rbar[1] = le32_to_cpu(*(__le32 *)&vconfig[PCI_BASE_ADDRESS_1]);
1704 	vdev->rbar[2] = le32_to_cpu(*(__le32 *)&vconfig[PCI_BASE_ADDRESS_2]);
1705 	vdev->rbar[3] = le32_to_cpu(*(__le32 *)&vconfig[PCI_BASE_ADDRESS_3]);
1706 	vdev->rbar[4] = le32_to_cpu(*(__le32 *)&vconfig[PCI_BASE_ADDRESS_4]);
1707 	vdev->rbar[5] = le32_to_cpu(*(__le32 *)&vconfig[PCI_BASE_ADDRESS_5]);
1708 	vdev->rbar[6] = le32_to_cpu(*(__le32 *)&vconfig[PCI_ROM_ADDRESS]);
1709 
1710 	if (pdev->is_virtfn) {
1711 		*(__le16 *)&vconfig[PCI_VENDOR_ID] = cpu_to_le16(pdev->vendor);
1712 		*(__le16 *)&vconfig[PCI_DEVICE_ID] = cpu_to_le16(pdev->device);
1713 
1714 		/*
1715 		 * Per SR-IOV spec rev 1.1, 3.4.1.18 the interrupt pin register
1716 		 * does not apply to VFs and VFs must implement this register
1717 		 * as read-only with value zero.  Userspace is not readily able
1718 		 * to identify whether a device is a VF and thus that the pin
1719 		 * definition on the device is bogus should it violate this
1720 		 * requirement.  We already virtualize the pin register for
1721 		 * other purposes, so we simply need to replace the bogus value
1722 		 * and consider VFs when we determine INTx IRQ count.
1723 		 */
1724 		if (vconfig[PCI_INTERRUPT_PIN] &&
1725 		    !pci_match_id(known_bogus_vf_intx_pin, pdev))
1726 			pci_warn(pdev,
1727 				 "Hardware bug: VF reports bogus INTx pin %d\n",
1728 				 vconfig[PCI_INTERRUPT_PIN]);
1729 
1730 		vconfig[PCI_INTERRUPT_PIN] = 0; /* Gratuitous for good VFs */
1731 	}
1732 
1733 	if (!IS_ENABLED(CONFIG_VFIO_PCI_INTX) || vdev->nointx)
1734 		vconfig[PCI_INTERRUPT_PIN] = 0;
1735 
1736 	ret = vfio_cap_init(vdev);
1737 	if (ret)
1738 		goto out;
1739 
1740 	ret = vfio_ecap_init(vdev);
1741 	if (ret)
1742 		goto out;
1743 
1744 	return 0;
1745 
1746 out:
1747 	kfree(map);
1748 	vdev->pci_config_map = NULL;
1749 	kfree(vconfig);
1750 	vdev->vconfig = NULL;
1751 	return pcibios_err_to_errno(ret);
1752 }
1753 
1754 void vfio_config_free(struct vfio_pci_device *vdev)
1755 {
1756 	kfree(vdev->vconfig);
1757 	vdev->vconfig = NULL;
1758 	kfree(vdev->pci_config_map);
1759 	vdev->pci_config_map = NULL;
1760 	if (vdev->msi_perm) {
1761 		free_perm_bits(vdev->msi_perm);
1762 		kfree(vdev->msi_perm);
1763 		vdev->msi_perm = NULL;
1764 	}
1765 }
1766 
1767 /*
1768  * Find the remaining number of bytes in a dword that match the given
1769  * position.  Stop at either the end of the capability or the dword boundary.
1770  */
1771 static size_t vfio_pci_cap_remaining_dword(struct vfio_pci_device *vdev,
1772 					   loff_t pos)
1773 {
1774 	u8 cap = vdev->pci_config_map[pos];
1775 	size_t i;
1776 
1777 	for (i = 1; (pos + i) % 4 && vdev->pci_config_map[pos + i] == cap; i++)
1778 		/* nop */;
1779 
1780 	return i;
1781 }
1782 
1783 static ssize_t vfio_config_do_rw(struct vfio_pci_device *vdev, char __user *buf,
1784 				 size_t count, loff_t *ppos, bool iswrite)
1785 {
1786 	struct pci_dev *pdev = vdev->pdev;
1787 	struct perm_bits *perm;
1788 	__le32 val = 0;
1789 	int cap_start = 0, offset;
1790 	u8 cap_id;
1791 	ssize_t ret;
1792 
1793 	if (*ppos < 0 || *ppos >= pdev->cfg_size ||
1794 	    *ppos + count > pdev->cfg_size)
1795 		return -EFAULT;
1796 
1797 	/*
1798 	 * Chop accesses into aligned chunks containing no more than a
1799 	 * single capability.  Caller increments to the next chunk.
1800 	 */
1801 	count = min(count, vfio_pci_cap_remaining_dword(vdev, *ppos));
1802 	if (count >= 4 && !(*ppos % 4))
1803 		count = 4;
1804 	else if (count >= 2 && !(*ppos % 2))
1805 		count = 2;
1806 	else
1807 		count = 1;
1808 
1809 	ret = count;
1810 
1811 	cap_id = vdev->pci_config_map[*ppos];
1812 
1813 	if (cap_id == PCI_CAP_ID_INVALID) {
1814 		perm = &unassigned_perms;
1815 		cap_start = *ppos;
1816 	} else if (cap_id == PCI_CAP_ID_INVALID_VIRT) {
1817 		perm = &virt_perms;
1818 		cap_start = *ppos;
1819 	} else {
1820 		if (*ppos >= PCI_CFG_SPACE_SIZE) {
1821 			WARN_ON(cap_id > PCI_EXT_CAP_ID_MAX);
1822 
1823 			perm = &ecap_perms[cap_id];
1824 			cap_start = vfio_find_cap_start(vdev, *ppos);
1825 		} else {
1826 			WARN_ON(cap_id > PCI_CAP_ID_MAX);
1827 
1828 			perm = &cap_perms[cap_id];
1829 
1830 			if (cap_id == PCI_CAP_ID_MSI)
1831 				perm = vdev->msi_perm;
1832 
1833 			if (cap_id > PCI_CAP_ID_BASIC)
1834 				cap_start = vfio_find_cap_start(vdev, *ppos);
1835 		}
1836 	}
1837 
1838 	WARN_ON(!cap_start && cap_id != PCI_CAP_ID_BASIC);
1839 	WARN_ON(cap_start > *ppos);
1840 
1841 	offset = *ppos - cap_start;
1842 
1843 	if (iswrite) {
1844 		if (!perm->writefn)
1845 			return ret;
1846 
1847 		if (copy_from_user(&val, buf, count))
1848 			return -EFAULT;
1849 
1850 		ret = perm->writefn(vdev, *ppos, count, perm, offset, val);
1851 	} else {
1852 		if (perm->readfn) {
1853 			ret = perm->readfn(vdev, *ppos, count,
1854 					   perm, offset, &val);
1855 			if (ret < 0)
1856 				return ret;
1857 		}
1858 
1859 		if (copy_to_user(buf, &val, count))
1860 			return -EFAULT;
1861 	}
1862 
1863 	return ret;
1864 }
1865 
1866 ssize_t vfio_pci_config_rw(struct vfio_pci_device *vdev, char __user *buf,
1867 			   size_t count, loff_t *ppos, bool iswrite)
1868 {
1869 	size_t done = 0;
1870 	int ret = 0;
1871 	loff_t pos = *ppos;
1872 
1873 	pos &= VFIO_PCI_OFFSET_MASK;
1874 
1875 	while (count) {
1876 		ret = vfio_config_do_rw(vdev, buf, count, &pos, iswrite);
1877 		if (ret < 0)
1878 			return ret;
1879 
1880 		count -= ret;
1881 		done += ret;
1882 		buf += ret;
1883 		pos += ret;
1884 	}
1885 
1886 	*ppos += done;
1887 
1888 	return done;
1889 }
1890