1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Volume Management Device driver
4  * Copyright (c) 2015, Intel Corporation.
5  */
6 
7 #include <linux/device.h>
8 #include <linux/interrupt.h>
9 #include <linux/irq.h>
10 #include <linux/kernel.h>
11 #include <linux/module.h>
12 #include <linux/msi.h>
13 #include <linux/pci.h>
14 #include <linux/pci-acpi.h>
15 #include <linux/pci-ecam.h>
16 #include <linux/srcu.h>
17 #include <linux/rculist.h>
18 #include <linux/rcupdate.h>
19 
20 #include <xen/xen.h>
21 
22 #include <asm/irqdomain.h>
23 
24 #define VMD_CFGBAR	0
25 #define VMD_MEMBAR1	2
26 #define VMD_MEMBAR2	4
27 
28 #define PCI_REG_VMCAP		0x40
29 #define BUS_RESTRICT_CAP(vmcap)	(vmcap & 0x1)
30 #define PCI_REG_VMCONFIG	0x44
31 #define BUS_RESTRICT_CFG(vmcfg)	((vmcfg >> 8) & 0x3)
32 #define VMCONFIG_MSI_REMAP	0x2
33 #define PCI_REG_VMLOCK		0x70
34 #define MB2_SHADOW_EN(vmlock)	(vmlock & 0x2)
35 
36 #define MB2_SHADOW_OFFSET	0x2000
37 #define MB2_SHADOW_SIZE		16
38 
39 enum vmd_features {
40 	/*
41 	 * Device may contain registers which hint the physical location of the
42 	 * membars, in order to allow proper address translation during
43 	 * resource assignment to enable guest virtualization
44 	 */
45 	VMD_FEAT_HAS_MEMBAR_SHADOW		= (1 << 0),
46 
47 	/*
48 	 * Device may provide root port configuration information which limits
49 	 * bus numbering
50 	 */
51 	VMD_FEAT_HAS_BUS_RESTRICTIONS		= (1 << 1),
52 
53 	/*
54 	 * Device contains physical location shadow registers in
55 	 * vendor-specific capability space
56 	 */
57 	VMD_FEAT_HAS_MEMBAR_SHADOW_VSCAP	= (1 << 2),
58 
59 	/*
60 	 * Device may use MSI-X vector 0 for software triggering and will not
61 	 * be used for MSI remapping
62 	 */
63 	VMD_FEAT_OFFSET_FIRST_VECTOR		= (1 << 3),
64 
65 	/*
66 	 * Device can bypass remapping MSI-X transactions into its MSI-X table,
67 	 * avoiding the requirement of a VMD MSI domain for child device
68 	 * interrupt handling.
69 	 */
70 	VMD_FEAT_CAN_BYPASS_MSI_REMAP		= (1 << 4),
71 
72 	/*
73 	 * Enable ASPM on the PCIE root ports and set the default LTR of the
74 	 * storage devices on platforms where these values are not configured by
75 	 * BIOS. This is needed for laptops, which require these settings for
76 	 * proper power management of the SoC.
77 	 */
78 	VMD_FEAT_BIOS_PM_QUIRK		= (1 << 5),
79 };
80 
81 #define VMD_BIOS_PM_QUIRK_LTR	0x1003	/* 3145728 ns */
82 
83 #define VMD_FEATS_CLIENT	(VMD_FEAT_HAS_MEMBAR_SHADOW_VSCAP |	\
84 				 VMD_FEAT_HAS_BUS_RESTRICTIONS |	\
85 				 VMD_FEAT_OFFSET_FIRST_VECTOR |		\
86 				 VMD_FEAT_BIOS_PM_QUIRK)
87 
88 static DEFINE_IDA(vmd_instance_ida);
89 
90 /*
91  * Lock for manipulating VMD IRQ lists.
92  */
93 static DEFINE_RAW_SPINLOCK(list_lock);
94 
95 /**
96  * struct vmd_irq - private data to map driver IRQ to the VMD shared vector
97  * @node:	list item for parent traversal.
98  * @irq:	back pointer to parent.
99  * @enabled:	true if driver enabled IRQ
100  * @virq:	the virtual IRQ value provided to the requesting driver.
101  *
102  * Every MSI/MSI-X IRQ requested for a device in a VMD domain will be mapped to
103  * a VMD IRQ using this structure.
104  */
105 struct vmd_irq {
106 	struct list_head	node;
107 	struct vmd_irq_list	*irq;
108 	bool			enabled;
109 	unsigned int		virq;
110 };
111 
112 /**
113  * struct vmd_irq_list - list of driver requested IRQs mapping to a VMD vector
114  * @irq_list:	the list of irq's the VMD one demuxes to.
115  * @srcu:	SRCU struct for local synchronization.
116  * @count:	number of child IRQs assigned to this vector; used to track
117  *		sharing.
118  * @virq:	The underlying VMD Linux interrupt number
119  */
120 struct vmd_irq_list {
121 	struct list_head	irq_list;
122 	struct srcu_struct	srcu;
123 	unsigned int		count;
124 	unsigned int		virq;
125 };
126 
127 struct vmd_dev {
128 	struct pci_dev		*dev;
129 
130 	raw_spinlock_t		cfg_lock;
131 	void __iomem		*cfgbar;
132 
133 	int msix_count;
134 	struct vmd_irq_list	*irqs;
135 
136 	struct pci_sysdata	sysdata;
137 	struct resource		resources[3];
138 	struct irq_domain	*irq_domain;
139 	struct pci_bus		*bus;
140 	u8			busn_start;
141 	u8			first_vec;
142 	char			*name;
143 	int			instance;
144 };
145 
146 static inline struct vmd_dev *vmd_from_bus(struct pci_bus *bus)
147 {
148 	return container_of(bus->sysdata, struct vmd_dev, sysdata);
149 }
150 
151 static inline unsigned int index_from_irqs(struct vmd_dev *vmd,
152 					   struct vmd_irq_list *irqs)
153 {
154 	return irqs - vmd->irqs;
155 }
156 
157 /*
158  * Drivers managing a device in a VMD domain allocate their own IRQs as before,
159  * but the MSI entry for the hardware it's driving will be programmed with a
160  * destination ID for the VMD MSI-X table.  The VMD muxes interrupts in its
161  * domain into one of its own, and the VMD driver de-muxes these for the
162  * handlers sharing that VMD IRQ.  The vmd irq_domain provides the operations
163  * and irq_chip to set this up.
164  */
165 static void vmd_compose_msi_msg(struct irq_data *data, struct msi_msg *msg)
166 {
167 	struct vmd_irq *vmdirq = data->chip_data;
168 	struct vmd_irq_list *irq = vmdirq->irq;
169 	struct vmd_dev *vmd = irq_data_get_irq_handler_data(data);
170 
171 	memset(msg, 0, sizeof(*msg));
172 	msg->address_hi = X86_MSI_BASE_ADDRESS_HIGH;
173 	msg->arch_addr_lo.base_address = X86_MSI_BASE_ADDRESS_LOW;
174 	msg->arch_addr_lo.destid_0_7 = index_from_irqs(vmd, irq);
175 }
176 
177 /*
178  * We rely on MSI_FLAG_USE_DEF_CHIP_OPS to set the IRQ mask/unmask ops.
179  */
180 static void vmd_irq_enable(struct irq_data *data)
181 {
182 	struct vmd_irq *vmdirq = data->chip_data;
183 	unsigned long flags;
184 
185 	raw_spin_lock_irqsave(&list_lock, flags);
186 	WARN_ON(vmdirq->enabled);
187 	list_add_tail_rcu(&vmdirq->node, &vmdirq->irq->irq_list);
188 	vmdirq->enabled = true;
189 	raw_spin_unlock_irqrestore(&list_lock, flags);
190 
191 	data->chip->irq_unmask(data);
192 }
193 
194 static void vmd_irq_disable(struct irq_data *data)
195 {
196 	struct vmd_irq *vmdirq = data->chip_data;
197 	unsigned long flags;
198 
199 	data->chip->irq_mask(data);
200 
201 	raw_spin_lock_irqsave(&list_lock, flags);
202 	if (vmdirq->enabled) {
203 		list_del_rcu(&vmdirq->node);
204 		vmdirq->enabled = false;
205 	}
206 	raw_spin_unlock_irqrestore(&list_lock, flags);
207 }
208 
209 static struct irq_chip vmd_msi_controller = {
210 	.name			= "VMD-MSI",
211 	.irq_enable		= vmd_irq_enable,
212 	.irq_disable		= vmd_irq_disable,
213 	.irq_compose_msi_msg	= vmd_compose_msi_msg,
214 };
215 
216 static irq_hw_number_t vmd_get_hwirq(struct msi_domain_info *info,
217 				     msi_alloc_info_t *arg)
218 {
219 	return 0;
220 }
221 
222 /*
223  * XXX: We can be even smarter selecting the best IRQ once we solve the
224  * affinity problem.
225  */
226 static struct vmd_irq_list *vmd_next_irq(struct vmd_dev *vmd, struct msi_desc *desc)
227 {
228 	unsigned long flags;
229 	int i, best;
230 
231 	if (vmd->msix_count == 1 + vmd->first_vec)
232 		return &vmd->irqs[vmd->first_vec];
233 
234 	/*
235 	 * White list for fast-interrupt handlers. All others will share the
236 	 * "slow" interrupt vector.
237 	 */
238 	switch (msi_desc_to_pci_dev(desc)->class) {
239 	case PCI_CLASS_STORAGE_EXPRESS:
240 		break;
241 	default:
242 		return &vmd->irqs[vmd->first_vec];
243 	}
244 
245 	raw_spin_lock_irqsave(&list_lock, flags);
246 	best = vmd->first_vec + 1;
247 	for (i = best; i < vmd->msix_count; i++)
248 		if (vmd->irqs[i].count < vmd->irqs[best].count)
249 			best = i;
250 	vmd->irqs[best].count++;
251 	raw_spin_unlock_irqrestore(&list_lock, flags);
252 
253 	return &vmd->irqs[best];
254 }
255 
256 static int vmd_msi_init(struct irq_domain *domain, struct msi_domain_info *info,
257 			unsigned int virq, irq_hw_number_t hwirq,
258 			msi_alloc_info_t *arg)
259 {
260 	struct msi_desc *desc = arg->desc;
261 	struct vmd_dev *vmd = vmd_from_bus(msi_desc_to_pci_dev(desc)->bus);
262 	struct vmd_irq *vmdirq = kzalloc(sizeof(*vmdirq), GFP_KERNEL);
263 
264 	if (!vmdirq)
265 		return -ENOMEM;
266 
267 	INIT_LIST_HEAD(&vmdirq->node);
268 	vmdirq->irq = vmd_next_irq(vmd, desc);
269 	vmdirq->virq = virq;
270 
271 	irq_domain_set_info(domain, virq, vmdirq->irq->virq, info->chip, vmdirq,
272 			    handle_untracked_irq, vmd, NULL);
273 	return 0;
274 }
275 
276 static void vmd_msi_free(struct irq_domain *domain,
277 			struct msi_domain_info *info, unsigned int virq)
278 {
279 	struct vmd_irq *vmdirq = irq_get_chip_data(virq);
280 	unsigned long flags;
281 
282 	synchronize_srcu(&vmdirq->irq->srcu);
283 
284 	/* XXX: Potential optimization to rebalance */
285 	raw_spin_lock_irqsave(&list_lock, flags);
286 	vmdirq->irq->count--;
287 	raw_spin_unlock_irqrestore(&list_lock, flags);
288 
289 	kfree(vmdirq);
290 }
291 
292 static int vmd_msi_prepare(struct irq_domain *domain, struct device *dev,
293 			   int nvec, msi_alloc_info_t *arg)
294 {
295 	struct pci_dev *pdev = to_pci_dev(dev);
296 	struct vmd_dev *vmd = vmd_from_bus(pdev->bus);
297 
298 	if (nvec > vmd->msix_count)
299 		return vmd->msix_count;
300 
301 	memset(arg, 0, sizeof(*arg));
302 	return 0;
303 }
304 
305 static void vmd_set_desc(msi_alloc_info_t *arg, struct msi_desc *desc)
306 {
307 	arg->desc = desc;
308 }
309 
310 static struct msi_domain_ops vmd_msi_domain_ops = {
311 	.get_hwirq	= vmd_get_hwirq,
312 	.msi_init	= vmd_msi_init,
313 	.msi_free	= vmd_msi_free,
314 	.msi_prepare	= vmd_msi_prepare,
315 	.set_desc	= vmd_set_desc,
316 };
317 
318 static struct msi_domain_info vmd_msi_domain_info = {
319 	.flags		= MSI_FLAG_USE_DEF_DOM_OPS | MSI_FLAG_USE_DEF_CHIP_OPS |
320 			  MSI_FLAG_NO_AFFINITY | MSI_FLAG_PCI_MSIX,
321 	.ops		= &vmd_msi_domain_ops,
322 	.chip		= &vmd_msi_controller,
323 };
324 
325 static void vmd_set_msi_remapping(struct vmd_dev *vmd, bool enable)
326 {
327 	u16 reg;
328 
329 	pci_read_config_word(vmd->dev, PCI_REG_VMCONFIG, &reg);
330 	reg = enable ? (reg & ~VMCONFIG_MSI_REMAP) :
331 		       (reg | VMCONFIG_MSI_REMAP);
332 	pci_write_config_word(vmd->dev, PCI_REG_VMCONFIG, reg);
333 }
334 
335 static int vmd_create_irq_domain(struct vmd_dev *vmd)
336 {
337 	struct fwnode_handle *fn;
338 
339 	fn = irq_domain_alloc_named_id_fwnode("VMD-MSI", vmd->sysdata.domain);
340 	if (!fn)
341 		return -ENODEV;
342 
343 	vmd->irq_domain = pci_msi_create_irq_domain(fn, &vmd_msi_domain_info, NULL);
344 	if (!vmd->irq_domain) {
345 		irq_domain_free_fwnode(fn);
346 		return -ENODEV;
347 	}
348 
349 	return 0;
350 }
351 
352 static void vmd_remove_irq_domain(struct vmd_dev *vmd)
353 {
354 	/*
355 	 * Some production BIOS won't enable remapping between soft reboots.
356 	 * Ensure remapping is restored before unloading the driver.
357 	 */
358 	if (!vmd->msix_count)
359 		vmd_set_msi_remapping(vmd, true);
360 
361 	if (vmd->irq_domain) {
362 		struct fwnode_handle *fn = vmd->irq_domain->fwnode;
363 
364 		irq_domain_remove(vmd->irq_domain);
365 		irq_domain_free_fwnode(fn);
366 	}
367 }
368 
369 static void __iomem *vmd_cfg_addr(struct vmd_dev *vmd, struct pci_bus *bus,
370 				  unsigned int devfn, int reg, int len)
371 {
372 	unsigned int busnr_ecam = bus->number - vmd->busn_start;
373 	u32 offset = PCIE_ECAM_OFFSET(busnr_ecam, devfn, reg);
374 
375 	if (offset + len >= resource_size(&vmd->dev->resource[VMD_CFGBAR]))
376 		return NULL;
377 
378 	return vmd->cfgbar + offset;
379 }
380 
381 /*
382  * CPU may deadlock if config space is not serialized on some versions of this
383  * hardware, so all config space access is done under a spinlock.
384  */
385 static int vmd_pci_read(struct pci_bus *bus, unsigned int devfn, int reg,
386 			int len, u32 *value)
387 {
388 	struct vmd_dev *vmd = vmd_from_bus(bus);
389 	void __iomem *addr = vmd_cfg_addr(vmd, bus, devfn, reg, len);
390 	unsigned long flags;
391 	int ret = 0;
392 
393 	if (!addr)
394 		return -EFAULT;
395 
396 	raw_spin_lock_irqsave(&vmd->cfg_lock, flags);
397 	switch (len) {
398 	case 1:
399 		*value = readb(addr);
400 		break;
401 	case 2:
402 		*value = readw(addr);
403 		break;
404 	case 4:
405 		*value = readl(addr);
406 		break;
407 	default:
408 		ret = -EINVAL;
409 		break;
410 	}
411 	raw_spin_unlock_irqrestore(&vmd->cfg_lock, flags);
412 	return ret;
413 }
414 
415 /*
416  * VMD h/w converts non-posted config writes to posted memory writes. The
417  * read-back in this function forces the completion so it returns only after
418  * the config space was written, as expected.
419  */
420 static int vmd_pci_write(struct pci_bus *bus, unsigned int devfn, int reg,
421 			 int len, u32 value)
422 {
423 	struct vmd_dev *vmd = vmd_from_bus(bus);
424 	void __iomem *addr = vmd_cfg_addr(vmd, bus, devfn, reg, len);
425 	unsigned long flags;
426 	int ret = 0;
427 
428 	if (!addr)
429 		return -EFAULT;
430 
431 	raw_spin_lock_irqsave(&vmd->cfg_lock, flags);
432 	switch (len) {
433 	case 1:
434 		writeb(value, addr);
435 		readb(addr);
436 		break;
437 	case 2:
438 		writew(value, addr);
439 		readw(addr);
440 		break;
441 	case 4:
442 		writel(value, addr);
443 		readl(addr);
444 		break;
445 	default:
446 		ret = -EINVAL;
447 		break;
448 	}
449 	raw_spin_unlock_irqrestore(&vmd->cfg_lock, flags);
450 	return ret;
451 }
452 
453 static struct pci_ops vmd_ops = {
454 	.read		= vmd_pci_read,
455 	.write		= vmd_pci_write,
456 };
457 
458 #ifdef CONFIG_ACPI
459 static struct acpi_device *vmd_acpi_find_companion(struct pci_dev *pci_dev)
460 {
461 	struct pci_host_bridge *bridge;
462 	u32 busnr, addr;
463 
464 	if (pci_dev->bus->ops != &vmd_ops)
465 		return NULL;
466 
467 	bridge = pci_find_host_bridge(pci_dev->bus);
468 	busnr = pci_dev->bus->number - bridge->bus->number;
469 	/*
470 	 * The address computation below is only applicable to relative bus
471 	 * numbers below 32.
472 	 */
473 	if (busnr > 31)
474 		return NULL;
475 
476 	addr = (busnr << 24) | ((u32)pci_dev->devfn << 16) | 0x8000FFFFU;
477 
478 	dev_dbg(&pci_dev->dev, "Looking for ACPI companion (address 0x%x)\n",
479 		addr);
480 
481 	return acpi_find_child_device(ACPI_COMPANION(bridge->dev.parent), addr,
482 				      false);
483 }
484 
485 static bool hook_installed;
486 
487 static void vmd_acpi_begin(void)
488 {
489 	if (pci_acpi_set_companion_lookup_hook(vmd_acpi_find_companion))
490 		return;
491 
492 	hook_installed = true;
493 }
494 
495 static void vmd_acpi_end(void)
496 {
497 	if (!hook_installed)
498 		return;
499 
500 	pci_acpi_clear_companion_lookup_hook();
501 	hook_installed = false;
502 }
503 #else
504 static inline void vmd_acpi_begin(void) { }
505 static inline void vmd_acpi_end(void) { }
506 #endif /* CONFIG_ACPI */
507 
508 static void vmd_domain_reset(struct vmd_dev *vmd)
509 {
510 	u16 bus, max_buses = resource_size(&vmd->resources[0]);
511 	u8 dev, functions, fn, hdr_type;
512 	char __iomem *base;
513 
514 	for (bus = 0; bus < max_buses; bus++) {
515 		for (dev = 0; dev < 32; dev++) {
516 			base = vmd->cfgbar + PCIE_ECAM_OFFSET(bus,
517 						PCI_DEVFN(dev, 0), 0);
518 
519 			hdr_type = readb(base + PCI_HEADER_TYPE);
520 
521 			functions = (hdr_type & PCI_HEADER_TYPE_MFD) ? 8 : 1;
522 			for (fn = 0; fn < functions; fn++) {
523 				base = vmd->cfgbar + PCIE_ECAM_OFFSET(bus,
524 						PCI_DEVFN(dev, fn), 0);
525 
526 				hdr_type = readb(base + PCI_HEADER_TYPE) &
527 						PCI_HEADER_TYPE_MASK;
528 
529 				if (hdr_type != PCI_HEADER_TYPE_BRIDGE ||
530 				    (readw(base + PCI_CLASS_DEVICE) !=
531 				     PCI_CLASS_BRIDGE_PCI))
532 					continue;
533 
534 				/*
535 				 * Temporarily disable the I/O range before updating
536 				 * PCI_IO_BASE.
537 				 */
538 				writel(0x0000ffff, base + PCI_IO_BASE_UPPER16);
539 				/* Update lower 16 bits of I/O base/limit */
540 				writew(0x00f0, base + PCI_IO_BASE);
541 				/* Update upper 16 bits of I/O base/limit */
542 				writel(0, base + PCI_IO_BASE_UPPER16);
543 
544 				/* MMIO Base/Limit */
545 				writel(0x0000fff0, base + PCI_MEMORY_BASE);
546 
547 				/* Prefetchable MMIO Base/Limit */
548 				writel(0, base + PCI_PREF_LIMIT_UPPER32);
549 				writel(0x0000fff0, base + PCI_PREF_MEMORY_BASE);
550 				writel(0xffffffff, base + PCI_PREF_BASE_UPPER32);
551 			}
552 		}
553 	}
554 }
555 
556 static void vmd_attach_resources(struct vmd_dev *vmd)
557 {
558 	vmd->dev->resource[VMD_MEMBAR1].child = &vmd->resources[1];
559 	vmd->dev->resource[VMD_MEMBAR2].child = &vmd->resources[2];
560 }
561 
562 static void vmd_detach_resources(struct vmd_dev *vmd)
563 {
564 	vmd->dev->resource[VMD_MEMBAR1].child = NULL;
565 	vmd->dev->resource[VMD_MEMBAR2].child = NULL;
566 }
567 
568 /*
569  * VMD domains start at 0x10000 to not clash with ACPI _SEG domains.
570  * Per ACPI r6.0, sec 6.5.6,  _SEG returns an integer, of which the lower
571  * 16 bits are the PCI Segment Group (domain) number.  Other bits are
572  * currently reserved.
573  */
574 static int vmd_find_free_domain(void)
575 {
576 	int domain = 0xffff;
577 	struct pci_bus *bus = NULL;
578 
579 	while ((bus = pci_find_next_bus(bus)) != NULL)
580 		domain = max_t(int, domain, pci_domain_nr(bus));
581 	return domain + 1;
582 }
583 
584 static int vmd_get_phys_offsets(struct vmd_dev *vmd, bool native_hint,
585 				resource_size_t *offset1,
586 				resource_size_t *offset2)
587 {
588 	struct pci_dev *dev = vmd->dev;
589 	u64 phys1, phys2;
590 
591 	if (native_hint) {
592 		u32 vmlock;
593 		int ret;
594 
595 		ret = pci_read_config_dword(dev, PCI_REG_VMLOCK, &vmlock);
596 		if (ret || PCI_POSSIBLE_ERROR(vmlock))
597 			return -ENODEV;
598 
599 		if (MB2_SHADOW_EN(vmlock)) {
600 			void __iomem *membar2;
601 
602 			membar2 = pci_iomap(dev, VMD_MEMBAR2, 0);
603 			if (!membar2)
604 				return -ENOMEM;
605 			phys1 = readq(membar2 + MB2_SHADOW_OFFSET);
606 			phys2 = readq(membar2 + MB2_SHADOW_OFFSET + 8);
607 			pci_iounmap(dev, membar2);
608 		} else
609 			return 0;
610 	} else {
611 		/* Hypervisor-Emulated Vendor-Specific Capability */
612 		int pos = pci_find_capability(dev, PCI_CAP_ID_VNDR);
613 		u32 reg, regu;
614 
615 		pci_read_config_dword(dev, pos + 4, &reg);
616 
617 		/* "SHDW" */
618 		if (pos && reg == 0x53484457) {
619 			pci_read_config_dword(dev, pos + 8, &reg);
620 			pci_read_config_dword(dev, pos + 12, &regu);
621 			phys1 = (u64) regu << 32 | reg;
622 
623 			pci_read_config_dword(dev, pos + 16, &reg);
624 			pci_read_config_dword(dev, pos + 20, &regu);
625 			phys2 = (u64) regu << 32 | reg;
626 		} else
627 			return 0;
628 	}
629 
630 	*offset1 = dev->resource[VMD_MEMBAR1].start -
631 			(phys1 & PCI_BASE_ADDRESS_MEM_MASK);
632 	*offset2 = dev->resource[VMD_MEMBAR2].start -
633 			(phys2 & PCI_BASE_ADDRESS_MEM_MASK);
634 
635 	return 0;
636 }
637 
638 static int vmd_get_bus_number_start(struct vmd_dev *vmd)
639 {
640 	struct pci_dev *dev = vmd->dev;
641 	u16 reg;
642 
643 	pci_read_config_word(dev, PCI_REG_VMCAP, &reg);
644 	if (BUS_RESTRICT_CAP(reg)) {
645 		pci_read_config_word(dev, PCI_REG_VMCONFIG, &reg);
646 
647 		switch (BUS_RESTRICT_CFG(reg)) {
648 		case 0:
649 			vmd->busn_start = 0;
650 			break;
651 		case 1:
652 			vmd->busn_start = 128;
653 			break;
654 		case 2:
655 			vmd->busn_start = 224;
656 			break;
657 		default:
658 			pci_err(dev, "Unknown Bus Offset Setting (%d)\n",
659 				BUS_RESTRICT_CFG(reg));
660 			return -ENODEV;
661 		}
662 	}
663 
664 	return 0;
665 }
666 
667 static irqreturn_t vmd_irq(int irq, void *data)
668 {
669 	struct vmd_irq_list *irqs = data;
670 	struct vmd_irq *vmdirq;
671 	int idx;
672 
673 	idx = srcu_read_lock(&irqs->srcu);
674 	list_for_each_entry_rcu(vmdirq, &irqs->irq_list, node)
675 		generic_handle_irq(vmdirq->virq);
676 	srcu_read_unlock(&irqs->srcu, idx);
677 
678 	return IRQ_HANDLED;
679 }
680 
681 static int vmd_alloc_irqs(struct vmd_dev *vmd)
682 {
683 	struct pci_dev *dev = vmd->dev;
684 	int i, err;
685 
686 	vmd->msix_count = pci_msix_vec_count(dev);
687 	if (vmd->msix_count < 0)
688 		return -ENODEV;
689 
690 	vmd->msix_count = pci_alloc_irq_vectors(dev, vmd->first_vec + 1,
691 						vmd->msix_count, PCI_IRQ_MSIX);
692 	if (vmd->msix_count < 0)
693 		return vmd->msix_count;
694 
695 	vmd->irqs = devm_kcalloc(&dev->dev, vmd->msix_count, sizeof(*vmd->irqs),
696 				 GFP_KERNEL);
697 	if (!vmd->irqs)
698 		return -ENOMEM;
699 
700 	for (i = 0; i < vmd->msix_count; i++) {
701 		err = init_srcu_struct(&vmd->irqs[i].srcu);
702 		if (err)
703 			return err;
704 
705 		INIT_LIST_HEAD(&vmd->irqs[i].irq_list);
706 		vmd->irqs[i].virq = pci_irq_vector(dev, i);
707 		err = devm_request_irq(&dev->dev, vmd->irqs[i].virq,
708 				       vmd_irq, IRQF_NO_THREAD,
709 				       vmd->name, &vmd->irqs[i]);
710 		if (err)
711 			return err;
712 	}
713 
714 	return 0;
715 }
716 
717 /*
718  * Since VMD is an aperture to regular PCIe root ports, only allow it to
719  * control features that the OS is allowed to control on the physical PCI bus.
720  */
721 static void vmd_copy_host_bridge_flags(struct pci_host_bridge *root_bridge,
722 				       struct pci_host_bridge *vmd_bridge)
723 {
724 	vmd_bridge->native_pcie_hotplug = root_bridge->native_pcie_hotplug;
725 	vmd_bridge->native_shpc_hotplug = root_bridge->native_shpc_hotplug;
726 	vmd_bridge->native_aer = root_bridge->native_aer;
727 	vmd_bridge->native_pme = root_bridge->native_pme;
728 	vmd_bridge->native_ltr = root_bridge->native_ltr;
729 	vmd_bridge->native_dpc = root_bridge->native_dpc;
730 }
731 
732 /*
733  * Enable ASPM and LTR settings on devices that aren't configured by BIOS.
734  */
735 static int vmd_pm_enable_quirk(struct pci_dev *pdev, void *userdata)
736 {
737 	unsigned long features = *(unsigned long *)userdata;
738 	u16 ltr = VMD_BIOS_PM_QUIRK_LTR;
739 	u32 ltr_reg;
740 	int pos;
741 
742 	if (!(features & VMD_FEAT_BIOS_PM_QUIRK))
743 		return 0;
744 
745 	pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_LTR);
746 	if (!pos)
747 		goto out_state_change;
748 
749 	/*
750 	 * Skip if the max snoop LTR is non-zero, indicating BIOS has set it
751 	 * so the LTR quirk is not needed.
752 	 */
753 	pci_read_config_dword(pdev, pos + PCI_LTR_MAX_SNOOP_LAT, &ltr_reg);
754 	if (!!(ltr_reg & (PCI_LTR_VALUE_MASK | PCI_LTR_SCALE_MASK)))
755 		goto out_state_change;
756 
757 	/*
758 	 * Set the default values to the maximum required by the platform to
759 	 * allow the deepest power management savings. Write as a DWORD where
760 	 * the lower word is the max snoop latency and the upper word is the
761 	 * max non-snoop latency.
762 	 */
763 	ltr_reg = (ltr << 16) | ltr;
764 	pci_write_config_dword(pdev, pos + PCI_LTR_MAX_SNOOP_LAT, ltr_reg);
765 	pci_info(pdev, "VMD: Default LTR value set by driver\n");
766 
767 out_state_change:
768 	/*
769 	 * Ensure devices are in D0 before enabling PCI-PM L1 PM Substates, per
770 	 * PCIe r6.0, sec 5.5.4.
771 	 */
772 	pci_set_power_state_locked(pdev, PCI_D0);
773 	pci_enable_link_state_locked(pdev, PCIE_LINK_STATE_ALL);
774 	return 0;
775 }
776 
777 static int vmd_enable_domain(struct vmd_dev *vmd, unsigned long features)
778 {
779 	struct pci_sysdata *sd = &vmd->sysdata;
780 	struct resource *res;
781 	u32 upper_bits;
782 	unsigned long flags;
783 	LIST_HEAD(resources);
784 	resource_size_t offset[2] = {0};
785 	resource_size_t membar2_offset = 0x2000;
786 	struct pci_bus *child;
787 	struct pci_dev *dev;
788 	int ret;
789 
790 	/*
791 	 * Shadow registers may exist in certain VMD device ids which allow
792 	 * guests to correctly assign host physical addresses to the root ports
793 	 * and child devices. These registers will either return the host value
794 	 * or 0, depending on an enable bit in the VMD device.
795 	 */
796 	if (features & VMD_FEAT_HAS_MEMBAR_SHADOW) {
797 		membar2_offset = MB2_SHADOW_OFFSET + MB2_SHADOW_SIZE;
798 		ret = vmd_get_phys_offsets(vmd, true, &offset[0], &offset[1]);
799 		if (ret)
800 			return ret;
801 	} else if (features & VMD_FEAT_HAS_MEMBAR_SHADOW_VSCAP) {
802 		ret = vmd_get_phys_offsets(vmd, false, &offset[0], &offset[1]);
803 		if (ret)
804 			return ret;
805 	}
806 
807 	/*
808 	 * Certain VMD devices may have a root port configuration option which
809 	 * limits the bus range to between 0-127, 128-255, or 224-255
810 	 */
811 	if (features & VMD_FEAT_HAS_BUS_RESTRICTIONS) {
812 		ret = vmd_get_bus_number_start(vmd);
813 		if (ret)
814 			return ret;
815 	}
816 
817 	res = &vmd->dev->resource[VMD_CFGBAR];
818 	vmd->resources[0] = (struct resource) {
819 		.name  = "VMD CFGBAR",
820 		.start = vmd->busn_start,
821 		.end   = vmd->busn_start + (resource_size(res) >> 20) - 1,
822 		.flags = IORESOURCE_BUS | IORESOURCE_PCI_FIXED,
823 	};
824 
825 	/*
826 	 * If the window is below 4GB, clear IORESOURCE_MEM_64 so we can
827 	 * put 32-bit resources in the window.
828 	 *
829 	 * There's no hardware reason why a 64-bit window *couldn't*
830 	 * contain a 32-bit resource, but pbus_size_mem() computes the
831 	 * bridge window size assuming a 64-bit window will contain no
832 	 * 32-bit resources.  __pci_assign_resource() enforces that
833 	 * artificial restriction to make sure everything will fit.
834 	 *
835 	 * The only way we could use a 64-bit non-prefetchable MEMBAR is
836 	 * if its address is <4GB so that we can convert it to a 32-bit
837 	 * resource.  To be visible to the host OS, all VMD endpoints must
838 	 * be initially configured by platform BIOS, which includes setting
839 	 * up these resources.  We can assume the device is configured
840 	 * according to the platform needs.
841 	 */
842 	res = &vmd->dev->resource[VMD_MEMBAR1];
843 	upper_bits = upper_32_bits(res->end);
844 	flags = res->flags & ~IORESOURCE_SIZEALIGN;
845 	if (!upper_bits)
846 		flags &= ~IORESOURCE_MEM_64;
847 	vmd->resources[1] = (struct resource) {
848 		.name  = "VMD MEMBAR1",
849 		.start = res->start,
850 		.end   = res->end,
851 		.flags = flags,
852 		.parent = res,
853 	};
854 
855 	res = &vmd->dev->resource[VMD_MEMBAR2];
856 	upper_bits = upper_32_bits(res->end);
857 	flags = res->flags & ~IORESOURCE_SIZEALIGN;
858 	if (!upper_bits)
859 		flags &= ~IORESOURCE_MEM_64;
860 	vmd->resources[2] = (struct resource) {
861 		.name  = "VMD MEMBAR2",
862 		.start = res->start + membar2_offset,
863 		.end   = res->end,
864 		.flags = flags,
865 		.parent = res,
866 	};
867 
868 	sd->vmd_dev = vmd->dev;
869 	sd->domain = vmd_find_free_domain();
870 	if (sd->domain < 0)
871 		return sd->domain;
872 
873 	sd->node = pcibus_to_node(vmd->dev->bus);
874 
875 	/*
876 	 * Currently MSI remapping must be enabled in guest passthrough mode
877 	 * due to some missing interrupt remapping plumbing. This is probably
878 	 * acceptable because the guest is usually CPU-limited and MSI
879 	 * remapping doesn't become a performance bottleneck.
880 	 */
881 	if (!(features & VMD_FEAT_CAN_BYPASS_MSI_REMAP) ||
882 	    offset[0] || offset[1]) {
883 		ret = vmd_alloc_irqs(vmd);
884 		if (ret)
885 			return ret;
886 
887 		vmd_set_msi_remapping(vmd, true);
888 
889 		ret = vmd_create_irq_domain(vmd);
890 		if (ret)
891 			return ret;
892 
893 		/*
894 		 * Override the IRQ domain bus token so the domain can be
895 		 * distinguished from a regular PCI/MSI domain.
896 		 */
897 		irq_domain_update_bus_token(vmd->irq_domain, DOMAIN_BUS_VMD_MSI);
898 	} else {
899 		vmd_set_msi_remapping(vmd, false);
900 	}
901 
902 	pci_add_resource(&resources, &vmd->resources[0]);
903 	pci_add_resource_offset(&resources, &vmd->resources[1], offset[0]);
904 	pci_add_resource_offset(&resources, &vmd->resources[2], offset[1]);
905 
906 	vmd->bus = pci_create_root_bus(&vmd->dev->dev, vmd->busn_start,
907 				       &vmd_ops, sd, &resources);
908 	if (!vmd->bus) {
909 		pci_free_resource_list(&resources);
910 		vmd_remove_irq_domain(vmd);
911 		return -ENODEV;
912 	}
913 
914 	vmd_copy_host_bridge_flags(pci_find_host_bridge(vmd->dev->bus),
915 				   to_pci_host_bridge(vmd->bus->bridge));
916 
917 	vmd_attach_resources(vmd);
918 	if (vmd->irq_domain)
919 		dev_set_msi_domain(&vmd->bus->dev, vmd->irq_domain);
920 	else
921 		dev_set_msi_domain(&vmd->bus->dev,
922 				   dev_get_msi_domain(&vmd->dev->dev));
923 
924 	WARN(sysfs_create_link(&vmd->dev->dev.kobj, &vmd->bus->dev.kobj,
925 			       "domain"), "Can't create symlink to domain\n");
926 
927 	vmd_acpi_begin();
928 
929 	pci_scan_child_bus(vmd->bus);
930 	vmd_domain_reset(vmd);
931 
932 	/* When Intel VMD is enabled, the OS does not discover the Root Ports
933 	 * owned by Intel VMD within the MMCFG space. pci_reset_bus() applies
934 	 * a reset to the parent of the PCI device supplied as argument. This
935 	 * is why we pass a child device, so the reset can be triggered at
936 	 * the Intel bridge level and propagated to all the children in the
937 	 * hierarchy.
938 	 */
939 	list_for_each_entry(child, &vmd->bus->children, node) {
940 		if (!list_empty(&child->devices)) {
941 			dev = list_first_entry(&child->devices,
942 					       struct pci_dev, bus_list);
943 			ret = pci_reset_bus(dev);
944 			if (ret)
945 				pci_warn(dev, "can't reset device: %d\n", ret);
946 
947 			break;
948 		}
949 	}
950 
951 	pci_assign_unassigned_bus_resources(vmd->bus);
952 
953 	pci_walk_bus(vmd->bus, vmd_pm_enable_quirk, &features);
954 
955 	/*
956 	 * VMD root buses are virtual and don't return true on pci_is_pcie()
957 	 * and will fail pcie_bus_configure_settings() early. It can instead be
958 	 * run on each of the real root ports.
959 	 */
960 	list_for_each_entry(child, &vmd->bus->children, node)
961 		pcie_bus_configure_settings(child);
962 
963 	pci_bus_add_devices(vmd->bus);
964 
965 	vmd_acpi_end();
966 	return 0;
967 }
968 
969 static int vmd_probe(struct pci_dev *dev, const struct pci_device_id *id)
970 {
971 	unsigned long features = (unsigned long) id->driver_data;
972 	struct vmd_dev *vmd;
973 	int err;
974 
975 	if (xen_domain()) {
976 		/*
977 		 * Xen doesn't have knowledge about devices in the VMD bus
978 		 * because the config space of devices behind the VMD bridge is
979 		 * not known to Xen, and hence Xen cannot discover or configure
980 		 * them in any way.
981 		 *
982 		 * Bypass of MSI remapping won't work in that case as direct
983 		 * write by Linux to the MSI entries won't result in functional
984 		 * interrupts, as Xen is the entity that manages the host
985 		 * interrupt controller and must configure interrupts.  However
986 		 * multiplexing of interrupts by the VMD bridge will work under
987 		 * Xen, so force the usage of that mode which must always be
988 		 * supported by VMD bridges.
989 		 */
990 		features &= ~VMD_FEAT_CAN_BYPASS_MSI_REMAP;
991 	}
992 
993 	if (resource_size(&dev->resource[VMD_CFGBAR]) < (1 << 20))
994 		return -ENOMEM;
995 
996 	vmd = devm_kzalloc(&dev->dev, sizeof(*vmd), GFP_KERNEL);
997 	if (!vmd)
998 		return -ENOMEM;
999 
1000 	vmd->dev = dev;
1001 	vmd->instance = ida_alloc(&vmd_instance_ida, GFP_KERNEL);
1002 	if (vmd->instance < 0)
1003 		return vmd->instance;
1004 
1005 	vmd->name = devm_kasprintf(&dev->dev, GFP_KERNEL, "vmd%d",
1006 				   vmd->instance);
1007 	if (!vmd->name) {
1008 		err = -ENOMEM;
1009 		goto out_release_instance;
1010 	}
1011 
1012 	err = pcim_enable_device(dev);
1013 	if (err < 0)
1014 		goto out_release_instance;
1015 
1016 	vmd->cfgbar = pcim_iomap(dev, VMD_CFGBAR, 0);
1017 	if (!vmd->cfgbar) {
1018 		err = -ENOMEM;
1019 		goto out_release_instance;
1020 	}
1021 
1022 	pci_set_master(dev);
1023 	if (dma_set_mask_and_coherent(&dev->dev, DMA_BIT_MASK(64)) &&
1024 	    dma_set_mask_and_coherent(&dev->dev, DMA_BIT_MASK(32))) {
1025 		err = -ENODEV;
1026 		goto out_release_instance;
1027 	}
1028 
1029 	if (features & VMD_FEAT_OFFSET_FIRST_VECTOR)
1030 		vmd->first_vec = 1;
1031 
1032 	raw_spin_lock_init(&vmd->cfg_lock);
1033 	pci_set_drvdata(dev, vmd);
1034 	err = vmd_enable_domain(vmd, features);
1035 	if (err)
1036 		goto out_release_instance;
1037 
1038 	dev_info(&vmd->dev->dev, "Bound to PCI domain %04x\n",
1039 		 vmd->sysdata.domain);
1040 	return 0;
1041 
1042  out_release_instance:
1043 	ida_free(&vmd_instance_ida, vmd->instance);
1044 	return err;
1045 }
1046 
1047 static void vmd_cleanup_srcu(struct vmd_dev *vmd)
1048 {
1049 	int i;
1050 
1051 	for (i = 0; i < vmd->msix_count; i++)
1052 		cleanup_srcu_struct(&vmd->irqs[i].srcu);
1053 }
1054 
1055 static void vmd_remove(struct pci_dev *dev)
1056 {
1057 	struct vmd_dev *vmd = pci_get_drvdata(dev);
1058 
1059 	pci_stop_root_bus(vmd->bus);
1060 	sysfs_remove_link(&vmd->dev->dev.kobj, "domain");
1061 	pci_remove_root_bus(vmd->bus);
1062 	vmd_cleanup_srcu(vmd);
1063 	vmd_detach_resources(vmd);
1064 	vmd_remove_irq_domain(vmd);
1065 	ida_free(&vmd_instance_ida, vmd->instance);
1066 }
1067 
1068 static void vmd_shutdown(struct pci_dev *dev)
1069 {
1070 	struct vmd_dev *vmd = pci_get_drvdata(dev);
1071 
1072 	vmd_remove_irq_domain(vmd);
1073 }
1074 
1075 #ifdef CONFIG_PM_SLEEP
1076 static int vmd_suspend(struct device *dev)
1077 {
1078 	struct pci_dev *pdev = to_pci_dev(dev);
1079 	struct vmd_dev *vmd = pci_get_drvdata(pdev);
1080 	int i;
1081 
1082 	for (i = 0; i < vmd->msix_count; i++)
1083 		devm_free_irq(dev, vmd->irqs[i].virq, &vmd->irqs[i]);
1084 
1085 	return 0;
1086 }
1087 
1088 static int vmd_resume(struct device *dev)
1089 {
1090 	struct pci_dev *pdev = to_pci_dev(dev);
1091 	struct vmd_dev *vmd = pci_get_drvdata(pdev);
1092 	int err, i;
1093 
1094 	vmd_set_msi_remapping(vmd, !!vmd->irq_domain);
1095 
1096 	for (i = 0; i < vmd->msix_count; i++) {
1097 		err = devm_request_irq(dev, vmd->irqs[i].virq,
1098 				       vmd_irq, IRQF_NO_THREAD,
1099 				       vmd->name, &vmd->irqs[i]);
1100 		if (err)
1101 			return err;
1102 	}
1103 
1104 	return 0;
1105 }
1106 #endif
1107 static SIMPLE_DEV_PM_OPS(vmd_dev_pm_ops, vmd_suspend, vmd_resume);
1108 
1109 static const struct pci_device_id vmd_ids[] = {
1110 	{PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_VMD_201D),
1111 		.driver_data = VMD_FEAT_HAS_MEMBAR_SHADOW_VSCAP,},
1112 	{PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_VMD_28C0),
1113 		.driver_data = VMD_FEAT_HAS_MEMBAR_SHADOW |
1114 				VMD_FEAT_HAS_BUS_RESTRICTIONS |
1115 				VMD_FEAT_CAN_BYPASS_MSI_REMAP,},
1116 	{PCI_VDEVICE(INTEL, 0x467f),
1117 		.driver_data = VMD_FEATS_CLIENT,},
1118 	{PCI_VDEVICE(INTEL, 0x4c3d),
1119 		.driver_data = VMD_FEATS_CLIENT,},
1120 	{PCI_VDEVICE(INTEL, 0xa77f),
1121 		.driver_data = VMD_FEATS_CLIENT,},
1122 	{PCI_VDEVICE(INTEL, 0x7d0b),
1123 		.driver_data = VMD_FEATS_CLIENT,},
1124 	{PCI_VDEVICE(INTEL, 0xad0b),
1125 		.driver_data = VMD_FEATS_CLIENT,},
1126 	{PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_VMD_9A0B),
1127 		.driver_data = VMD_FEATS_CLIENT,},
1128 	{PCI_VDEVICE(INTEL, 0xb60b),
1129                 .driver_data = VMD_FEATS_CLIENT,},
1130 	{PCI_VDEVICE(INTEL, 0xb06f),
1131                 .driver_data = VMD_FEATS_CLIENT,},
1132 	{0,}
1133 };
1134 MODULE_DEVICE_TABLE(pci, vmd_ids);
1135 
1136 static struct pci_driver vmd_drv = {
1137 	.name		= "vmd",
1138 	.id_table	= vmd_ids,
1139 	.probe		= vmd_probe,
1140 	.remove		= vmd_remove,
1141 	.shutdown	= vmd_shutdown,
1142 	.driver		= {
1143 		.pm	= &vmd_dev_pm_ops,
1144 	},
1145 };
1146 module_pci_driver(vmd_drv);
1147 
1148 MODULE_AUTHOR("Intel Corporation");
1149 MODULE_DESCRIPTION("Volume Management Device driver");
1150 MODULE_LICENSE("GPL v2");
1151 MODULE_VERSION("0.6");
1152