1 // SPDX-License-Identifier: GPL-2.0
2 
3 #define pr_fmt(fmt)     "DMAR-IR: " fmt
4 
5 #include <linux/interrupt.h>
6 #include <linux/dmar.h>
7 #include <linux/spinlock.h>
8 #include <linux/slab.h>
9 #include <linux/jiffies.h>
10 #include <linux/hpet.h>
11 #include <linux/pci.h>
12 #include <linux/irq.h>
13 #include <linux/acpi.h>
14 #include <linux/irqdomain.h>
15 #include <linux/crash_dump.h>
16 #include <asm/io_apic.h>
17 #include <asm/apic.h>
18 #include <asm/smp.h>
19 #include <asm/cpu.h>
20 #include <asm/irq_remapping.h>
21 #include <asm/pci-direct.h>
22 
23 #include "iommu.h"
24 #include "../irq_remapping.h"
25 #include "cap_audit.h"
26 
27 enum irq_mode {
28 	IRQ_REMAPPING,
29 	IRQ_POSTING,
30 };
31 
32 struct ioapic_scope {
33 	struct intel_iommu *iommu;
34 	unsigned int id;
35 	unsigned int bus;	/* PCI bus number */
36 	unsigned int devfn;	/* PCI devfn number */
37 };
38 
39 struct hpet_scope {
40 	struct intel_iommu *iommu;
41 	u8 id;
42 	unsigned int bus;
43 	unsigned int devfn;
44 };
45 
46 struct irq_2_iommu {
47 	struct intel_iommu *iommu;
48 	u16 irte_index;
49 	u16 sub_handle;
50 	u8  irte_mask;
51 	enum irq_mode mode;
52 };
53 
54 struct intel_ir_data {
55 	struct irq_2_iommu			irq_2_iommu;
56 	struct irte				irte_entry;
57 	union {
58 		struct msi_msg			msi_entry;
59 	};
60 };
61 
62 #define IR_X2APIC_MODE(mode) (mode ? (1 << 11) : 0)
63 #define IRTE_DEST(dest) ((eim_mode) ? dest : dest << 8)
64 
65 static int __read_mostly eim_mode;
66 static struct ioapic_scope ir_ioapic[MAX_IO_APICS];
67 static struct hpet_scope ir_hpet[MAX_HPET_TBS];
68 
69 /*
70  * Lock ordering:
71  * ->dmar_global_lock
72  *	->irq_2_ir_lock
73  *		->qi->q_lock
74  *	->iommu->register_lock
75  * Note:
76  * intel_irq_remap_ops.{supported,prepare,enable,disable,reenable} are called
77  * in single-threaded environment with interrupt disabled, so no need to tabke
78  * the dmar_global_lock.
79  */
80 DEFINE_RAW_SPINLOCK(irq_2_ir_lock);
81 static const struct irq_domain_ops intel_ir_domain_ops;
82 
83 static void iommu_disable_irq_remapping(struct intel_iommu *iommu);
84 static int __init parse_ioapics_under_ir(void);
85 static const struct msi_parent_ops dmar_msi_parent_ops, virt_dmar_msi_parent_ops;
86 
87 static bool ir_pre_enabled(struct intel_iommu *iommu)
88 {
89 	return (iommu->flags & VTD_FLAG_IRQ_REMAP_PRE_ENABLED);
90 }
91 
92 static void clear_ir_pre_enabled(struct intel_iommu *iommu)
93 {
94 	iommu->flags &= ~VTD_FLAG_IRQ_REMAP_PRE_ENABLED;
95 }
96 
97 static void init_ir_status(struct intel_iommu *iommu)
98 {
99 	u32 gsts;
100 
101 	gsts = readl(iommu->reg + DMAR_GSTS_REG);
102 	if (gsts & DMA_GSTS_IRES)
103 		iommu->flags |= VTD_FLAG_IRQ_REMAP_PRE_ENABLED;
104 }
105 
106 static int alloc_irte(struct intel_iommu *iommu,
107 		      struct irq_2_iommu *irq_iommu, u16 count)
108 {
109 	struct ir_table *table = iommu->ir_table;
110 	unsigned int mask = 0;
111 	unsigned long flags;
112 	int index;
113 
114 	if (!count || !irq_iommu)
115 		return -1;
116 
117 	if (count > 1) {
118 		count = __roundup_pow_of_two(count);
119 		mask = ilog2(count);
120 	}
121 
122 	if (mask > ecap_max_handle_mask(iommu->ecap)) {
123 		pr_err("Requested mask %x exceeds the max invalidation handle"
124 		       " mask value %Lx\n", mask,
125 		       ecap_max_handle_mask(iommu->ecap));
126 		return -1;
127 	}
128 
129 	raw_spin_lock_irqsave(&irq_2_ir_lock, flags);
130 	index = bitmap_find_free_region(table->bitmap,
131 					INTR_REMAP_TABLE_ENTRIES, mask);
132 	if (index < 0) {
133 		pr_warn("IR%d: can't allocate an IRTE\n", iommu->seq_id);
134 	} else {
135 		irq_iommu->iommu = iommu;
136 		irq_iommu->irte_index =  index;
137 		irq_iommu->sub_handle = 0;
138 		irq_iommu->irte_mask = mask;
139 		irq_iommu->mode = IRQ_REMAPPING;
140 	}
141 	raw_spin_unlock_irqrestore(&irq_2_ir_lock, flags);
142 
143 	return index;
144 }
145 
146 static int qi_flush_iec(struct intel_iommu *iommu, int index, int mask)
147 {
148 	struct qi_desc desc;
149 
150 	desc.qw0 = QI_IEC_IIDEX(index) | QI_IEC_TYPE | QI_IEC_IM(mask)
151 		   | QI_IEC_SELECTIVE;
152 	desc.qw1 = 0;
153 	desc.qw2 = 0;
154 	desc.qw3 = 0;
155 
156 	return qi_submit_sync(iommu, &desc, 1, 0);
157 }
158 
159 static int modify_irte(struct irq_2_iommu *irq_iommu,
160 		       struct irte *irte_modified)
161 {
162 	struct intel_iommu *iommu;
163 	unsigned long flags;
164 	struct irte *irte;
165 	int rc, index;
166 
167 	if (!irq_iommu)
168 		return -1;
169 
170 	raw_spin_lock_irqsave(&irq_2_ir_lock, flags);
171 
172 	iommu = irq_iommu->iommu;
173 
174 	index = irq_iommu->irte_index + irq_iommu->sub_handle;
175 	irte = &iommu->ir_table->base[index];
176 
177 	if ((irte->pst == 1) || (irte_modified->pst == 1)) {
178 		bool ret;
179 
180 		ret = cmpxchg_double(&irte->low, &irte->high,
181 				     irte->low, irte->high,
182 				     irte_modified->low, irte_modified->high);
183 		/*
184 		 * We use cmpxchg16 to atomically update the 128-bit IRTE,
185 		 * and it cannot be updated by the hardware or other processors
186 		 * behind us, so the return value of cmpxchg16 should be the
187 		 * same as the old value.
188 		 */
189 		WARN_ON(!ret);
190 	} else {
191 		WRITE_ONCE(irte->low, irte_modified->low);
192 		WRITE_ONCE(irte->high, irte_modified->high);
193 	}
194 	__iommu_flush_cache(iommu, irte, sizeof(*irte));
195 
196 	rc = qi_flush_iec(iommu, index, 0);
197 
198 	/* Update iommu mode according to the IRTE mode */
199 	irq_iommu->mode = irte->pst ? IRQ_POSTING : IRQ_REMAPPING;
200 	raw_spin_unlock_irqrestore(&irq_2_ir_lock, flags);
201 
202 	return rc;
203 }
204 
205 static struct intel_iommu *map_hpet_to_iommu(u8 hpet_id)
206 {
207 	int i;
208 
209 	for (i = 0; i < MAX_HPET_TBS; i++) {
210 		if (ir_hpet[i].id == hpet_id && ir_hpet[i].iommu)
211 			return ir_hpet[i].iommu;
212 	}
213 	return NULL;
214 }
215 
216 static struct intel_iommu *map_ioapic_to_iommu(int apic)
217 {
218 	int i;
219 
220 	for (i = 0; i < MAX_IO_APICS; i++) {
221 		if (ir_ioapic[i].id == apic && ir_ioapic[i].iommu)
222 			return ir_ioapic[i].iommu;
223 	}
224 	return NULL;
225 }
226 
227 static struct irq_domain *map_dev_to_ir(struct pci_dev *dev)
228 {
229 	struct dmar_drhd_unit *drhd = dmar_find_matched_drhd_unit(dev);
230 
231 	return drhd ? drhd->iommu->ir_domain : NULL;
232 }
233 
234 static int clear_entries(struct irq_2_iommu *irq_iommu)
235 {
236 	struct irte *start, *entry, *end;
237 	struct intel_iommu *iommu;
238 	int index;
239 
240 	if (irq_iommu->sub_handle)
241 		return 0;
242 
243 	iommu = irq_iommu->iommu;
244 	index = irq_iommu->irte_index;
245 
246 	start = iommu->ir_table->base + index;
247 	end = start + (1 << irq_iommu->irte_mask);
248 
249 	for (entry = start; entry < end; entry++) {
250 		WRITE_ONCE(entry->low, 0);
251 		WRITE_ONCE(entry->high, 0);
252 	}
253 	bitmap_release_region(iommu->ir_table->bitmap, index,
254 			      irq_iommu->irte_mask);
255 
256 	return qi_flush_iec(iommu, index, irq_iommu->irte_mask);
257 }
258 
259 /*
260  * source validation type
261  */
262 #define SVT_NO_VERIFY		0x0  /* no verification is required */
263 #define SVT_VERIFY_SID_SQ	0x1  /* verify using SID and SQ fields */
264 #define SVT_VERIFY_BUS		0x2  /* verify bus of request-id */
265 
266 /*
267  * source-id qualifier
268  */
269 #define SQ_ALL_16	0x0  /* verify all 16 bits of request-id */
270 #define SQ_13_IGNORE_1	0x1  /* verify most significant 13 bits, ignore
271 			      * the third least significant bit
272 			      */
273 #define SQ_13_IGNORE_2	0x2  /* verify most significant 13 bits, ignore
274 			      * the second and third least significant bits
275 			      */
276 #define SQ_13_IGNORE_3	0x3  /* verify most significant 13 bits, ignore
277 			      * the least three significant bits
278 			      */
279 
280 /*
281  * set SVT, SQ and SID fields of irte to verify
282  * source ids of interrupt requests
283  */
284 static void set_irte_sid(struct irte *irte, unsigned int svt,
285 			 unsigned int sq, unsigned int sid)
286 {
287 	if (disable_sourceid_checking)
288 		svt = SVT_NO_VERIFY;
289 	irte->svt = svt;
290 	irte->sq = sq;
291 	irte->sid = sid;
292 }
293 
294 /*
295  * Set an IRTE to match only the bus number. Interrupt requests that reference
296  * this IRTE must have a requester-id whose bus number is between or equal
297  * to the start_bus and end_bus arguments.
298  */
299 static void set_irte_verify_bus(struct irte *irte, unsigned int start_bus,
300 				unsigned int end_bus)
301 {
302 	set_irte_sid(irte, SVT_VERIFY_BUS, SQ_ALL_16,
303 		     (start_bus << 8) | end_bus);
304 }
305 
306 static int set_ioapic_sid(struct irte *irte, int apic)
307 {
308 	int i;
309 	u16 sid = 0;
310 
311 	if (!irte)
312 		return -1;
313 
314 	for (i = 0; i < MAX_IO_APICS; i++) {
315 		if (ir_ioapic[i].iommu && ir_ioapic[i].id == apic) {
316 			sid = (ir_ioapic[i].bus << 8) | ir_ioapic[i].devfn;
317 			break;
318 		}
319 	}
320 
321 	if (sid == 0) {
322 		pr_warn("Failed to set source-id of IOAPIC (%d)\n", apic);
323 		return -1;
324 	}
325 
326 	set_irte_sid(irte, SVT_VERIFY_SID_SQ, SQ_ALL_16, sid);
327 
328 	return 0;
329 }
330 
331 static int set_hpet_sid(struct irte *irte, u8 id)
332 {
333 	int i;
334 	u16 sid = 0;
335 
336 	if (!irte)
337 		return -1;
338 
339 	for (i = 0; i < MAX_HPET_TBS; i++) {
340 		if (ir_hpet[i].iommu && ir_hpet[i].id == id) {
341 			sid = (ir_hpet[i].bus << 8) | ir_hpet[i].devfn;
342 			break;
343 		}
344 	}
345 
346 	if (sid == 0) {
347 		pr_warn("Failed to set source-id of HPET block (%d)\n", id);
348 		return -1;
349 	}
350 
351 	/*
352 	 * Should really use SQ_ALL_16. Some platforms are broken.
353 	 * While we figure out the right quirks for these broken platforms, use
354 	 * SQ_13_IGNORE_3 for now.
355 	 */
356 	set_irte_sid(irte, SVT_VERIFY_SID_SQ, SQ_13_IGNORE_3, sid);
357 
358 	return 0;
359 }
360 
361 struct set_msi_sid_data {
362 	struct pci_dev *pdev;
363 	u16 alias;
364 	int count;
365 	int busmatch_count;
366 };
367 
368 static int set_msi_sid_cb(struct pci_dev *pdev, u16 alias, void *opaque)
369 {
370 	struct set_msi_sid_data *data = opaque;
371 
372 	if (data->count == 0 || PCI_BUS_NUM(alias) == PCI_BUS_NUM(data->alias))
373 		data->busmatch_count++;
374 
375 	data->pdev = pdev;
376 	data->alias = alias;
377 	data->count++;
378 
379 	return 0;
380 }
381 
382 static int set_msi_sid(struct irte *irte, struct pci_dev *dev)
383 {
384 	struct set_msi_sid_data data;
385 
386 	if (!irte || !dev)
387 		return -1;
388 
389 	data.count = 0;
390 	data.busmatch_count = 0;
391 	pci_for_each_dma_alias(dev, set_msi_sid_cb, &data);
392 
393 	/*
394 	 * DMA alias provides us with a PCI device and alias.  The only case
395 	 * where the it will return an alias on a different bus than the
396 	 * device is the case of a PCIe-to-PCI bridge, where the alias is for
397 	 * the subordinate bus.  In this case we can only verify the bus.
398 	 *
399 	 * If there are multiple aliases, all with the same bus number,
400 	 * then all we can do is verify the bus. This is typical in NTB
401 	 * hardware which use proxy IDs where the device will generate traffic
402 	 * from multiple devfn numbers on the same bus.
403 	 *
404 	 * If the alias device is on a different bus than our source device
405 	 * then we have a topology based alias, use it.
406 	 *
407 	 * Otherwise, the alias is for a device DMA quirk and we cannot
408 	 * assume that MSI uses the same requester ID.  Therefore use the
409 	 * original device.
410 	 */
411 	if (PCI_BUS_NUM(data.alias) != data.pdev->bus->number)
412 		set_irte_verify_bus(irte, PCI_BUS_NUM(data.alias),
413 				    dev->bus->number);
414 	else if (data.count >= 2 && data.busmatch_count == data.count)
415 		set_irte_verify_bus(irte, dev->bus->number, dev->bus->number);
416 	else if (data.pdev->bus->number != dev->bus->number)
417 		set_irte_sid(irte, SVT_VERIFY_SID_SQ, SQ_ALL_16, data.alias);
418 	else
419 		set_irte_sid(irte, SVT_VERIFY_SID_SQ, SQ_ALL_16,
420 			     pci_dev_id(dev));
421 
422 	return 0;
423 }
424 
425 static int iommu_load_old_irte(struct intel_iommu *iommu)
426 {
427 	struct irte *old_ir_table;
428 	phys_addr_t irt_phys;
429 	unsigned int i;
430 	size_t size;
431 	u64 irta;
432 
433 	/* Check whether the old ir-table has the same size as ours */
434 	irta = dmar_readq(iommu->reg + DMAR_IRTA_REG);
435 	if ((irta & INTR_REMAP_TABLE_REG_SIZE_MASK)
436 	     != INTR_REMAP_TABLE_REG_SIZE)
437 		return -EINVAL;
438 
439 	irt_phys = irta & VTD_PAGE_MASK;
440 	size     = INTR_REMAP_TABLE_ENTRIES*sizeof(struct irte);
441 
442 	/* Map the old IR table */
443 	old_ir_table = memremap(irt_phys, size, MEMREMAP_WB);
444 	if (!old_ir_table)
445 		return -ENOMEM;
446 
447 	/* Copy data over */
448 	memcpy(iommu->ir_table->base, old_ir_table, size);
449 
450 	__iommu_flush_cache(iommu, iommu->ir_table->base, size);
451 
452 	/*
453 	 * Now check the table for used entries and mark those as
454 	 * allocated in the bitmap
455 	 */
456 	for (i = 0; i < INTR_REMAP_TABLE_ENTRIES; i++) {
457 		if (iommu->ir_table->base[i].present)
458 			bitmap_set(iommu->ir_table->bitmap, i, 1);
459 	}
460 
461 	memunmap(old_ir_table);
462 
463 	return 0;
464 }
465 
466 
467 static void iommu_set_irq_remapping(struct intel_iommu *iommu, int mode)
468 {
469 	unsigned long flags;
470 	u64 addr;
471 	u32 sts;
472 
473 	addr = virt_to_phys((void *)iommu->ir_table->base);
474 
475 	raw_spin_lock_irqsave(&iommu->register_lock, flags);
476 
477 	dmar_writeq(iommu->reg + DMAR_IRTA_REG,
478 		    (addr) | IR_X2APIC_MODE(mode) | INTR_REMAP_TABLE_REG_SIZE);
479 
480 	/* Set interrupt-remapping table pointer */
481 	writel(iommu->gcmd | DMA_GCMD_SIRTP, iommu->reg + DMAR_GCMD_REG);
482 
483 	IOMMU_WAIT_OP(iommu, DMAR_GSTS_REG,
484 		      readl, (sts & DMA_GSTS_IRTPS), sts);
485 	raw_spin_unlock_irqrestore(&iommu->register_lock, flags);
486 
487 	/*
488 	 * Global invalidation of interrupt entry cache to make sure the
489 	 * hardware uses the new irq remapping table.
490 	 */
491 	if (!cap_esirtps(iommu->cap))
492 		qi_global_iec(iommu);
493 }
494 
495 static void iommu_enable_irq_remapping(struct intel_iommu *iommu)
496 {
497 	unsigned long flags;
498 	u32 sts;
499 
500 	raw_spin_lock_irqsave(&iommu->register_lock, flags);
501 
502 	/* Enable interrupt-remapping */
503 	iommu->gcmd |= DMA_GCMD_IRE;
504 	writel(iommu->gcmd, iommu->reg + DMAR_GCMD_REG);
505 	IOMMU_WAIT_OP(iommu, DMAR_GSTS_REG,
506 		      readl, (sts & DMA_GSTS_IRES), sts);
507 
508 	/* Block compatibility-format MSIs */
509 	if (sts & DMA_GSTS_CFIS) {
510 		iommu->gcmd &= ~DMA_GCMD_CFI;
511 		writel(iommu->gcmd, iommu->reg + DMAR_GCMD_REG);
512 		IOMMU_WAIT_OP(iommu, DMAR_GSTS_REG,
513 			      readl, !(sts & DMA_GSTS_CFIS), sts);
514 	}
515 
516 	/*
517 	 * With CFI clear in the Global Command register, we should be
518 	 * protected from dangerous (i.e. compatibility) interrupts
519 	 * regardless of x2apic status.  Check just to be sure.
520 	 */
521 	if (sts & DMA_GSTS_CFIS)
522 		WARN(1, KERN_WARNING
523 			"Compatibility-format IRQs enabled despite intr remapping;\n"
524 			"you are vulnerable to IRQ injection.\n");
525 
526 	raw_spin_unlock_irqrestore(&iommu->register_lock, flags);
527 }
528 
529 static int intel_setup_irq_remapping(struct intel_iommu *iommu)
530 {
531 	struct ir_table *ir_table;
532 	struct fwnode_handle *fn;
533 	unsigned long *bitmap;
534 	struct page *pages;
535 
536 	if (iommu->ir_table)
537 		return 0;
538 
539 	ir_table = kzalloc(sizeof(struct ir_table), GFP_KERNEL);
540 	if (!ir_table)
541 		return -ENOMEM;
542 
543 	pages = alloc_pages_node(iommu->node, GFP_KERNEL | __GFP_ZERO,
544 				 INTR_REMAP_PAGE_ORDER);
545 	if (!pages) {
546 		pr_err("IR%d: failed to allocate pages of order %d\n",
547 		       iommu->seq_id, INTR_REMAP_PAGE_ORDER);
548 		goto out_free_table;
549 	}
550 
551 	bitmap = bitmap_zalloc(INTR_REMAP_TABLE_ENTRIES, GFP_KERNEL);
552 	if (bitmap == NULL) {
553 		pr_err("IR%d: failed to allocate bitmap\n", iommu->seq_id);
554 		goto out_free_pages;
555 	}
556 
557 	fn = irq_domain_alloc_named_id_fwnode("INTEL-IR", iommu->seq_id);
558 	if (!fn)
559 		goto out_free_bitmap;
560 
561 	iommu->ir_domain =
562 		irq_domain_create_hierarchy(arch_get_ir_parent_domain(),
563 					    0, INTR_REMAP_TABLE_ENTRIES,
564 					    fn, &intel_ir_domain_ops,
565 					    iommu);
566 	if (!iommu->ir_domain) {
567 		pr_err("IR%d: failed to allocate irqdomain\n", iommu->seq_id);
568 		goto out_free_fwnode;
569 	}
570 
571 	irq_domain_update_bus_token(iommu->ir_domain,  DOMAIN_BUS_DMAR);
572 	iommu->ir_domain->flags |= IRQ_DOMAIN_FLAG_MSI_PARENT |
573 				   IRQ_DOMAIN_FLAG_ISOLATED_MSI;
574 
575 	if (cap_caching_mode(iommu->cap))
576 		iommu->ir_domain->msi_parent_ops = &virt_dmar_msi_parent_ops;
577 	else
578 		iommu->ir_domain->msi_parent_ops = &dmar_msi_parent_ops;
579 
580 	ir_table->base = page_address(pages);
581 	ir_table->bitmap = bitmap;
582 	iommu->ir_table = ir_table;
583 
584 	/*
585 	 * If the queued invalidation is already initialized,
586 	 * shouldn't disable it.
587 	 */
588 	if (!iommu->qi) {
589 		/*
590 		 * Clear previous faults.
591 		 */
592 		dmar_fault(-1, iommu);
593 		dmar_disable_qi(iommu);
594 
595 		if (dmar_enable_qi(iommu)) {
596 			pr_err("Failed to enable queued invalidation\n");
597 			goto out_free_ir_domain;
598 		}
599 	}
600 
601 	init_ir_status(iommu);
602 
603 	if (ir_pre_enabled(iommu)) {
604 		if (!is_kdump_kernel()) {
605 			pr_warn("IRQ remapping was enabled on %s but we are not in kdump mode\n",
606 				iommu->name);
607 			clear_ir_pre_enabled(iommu);
608 			iommu_disable_irq_remapping(iommu);
609 		} else if (iommu_load_old_irte(iommu))
610 			pr_err("Failed to copy IR table for %s from previous kernel\n",
611 			       iommu->name);
612 		else
613 			pr_info("Copied IR table for %s from previous kernel\n",
614 				iommu->name);
615 	}
616 
617 	iommu_set_irq_remapping(iommu, eim_mode);
618 
619 	return 0;
620 
621 out_free_ir_domain:
622 	irq_domain_remove(iommu->ir_domain);
623 	iommu->ir_domain = NULL;
624 out_free_fwnode:
625 	irq_domain_free_fwnode(fn);
626 out_free_bitmap:
627 	bitmap_free(bitmap);
628 out_free_pages:
629 	__free_pages(pages, INTR_REMAP_PAGE_ORDER);
630 out_free_table:
631 	kfree(ir_table);
632 
633 	iommu->ir_table  = NULL;
634 
635 	return -ENOMEM;
636 }
637 
638 static void intel_teardown_irq_remapping(struct intel_iommu *iommu)
639 {
640 	struct fwnode_handle *fn;
641 
642 	if (iommu && iommu->ir_table) {
643 		if (iommu->ir_domain) {
644 			fn = iommu->ir_domain->fwnode;
645 
646 			irq_domain_remove(iommu->ir_domain);
647 			irq_domain_free_fwnode(fn);
648 			iommu->ir_domain = NULL;
649 		}
650 		free_pages((unsigned long)iommu->ir_table->base,
651 			   INTR_REMAP_PAGE_ORDER);
652 		bitmap_free(iommu->ir_table->bitmap);
653 		kfree(iommu->ir_table);
654 		iommu->ir_table = NULL;
655 	}
656 }
657 
658 /*
659  * Disable Interrupt Remapping.
660  */
661 static void iommu_disable_irq_remapping(struct intel_iommu *iommu)
662 {
663 	unsigned long flags;
664 	u32 sts;
665 
666 	if (!ecap_ir_support(iommu->ecap))
667 		return;
668 
669 	/*
670 	 * global invalidation of interrupt entry cache before disabling
671 	 * interrupt-remapping.
672 	 */
673 	if (!cap_esirtps(iommu->cap))
674 		qi_global_iec(iommu);
675 
676 	raw_spin_lock_irqsave(&iommu->register_lock, flags);
677 
678 	sts = readl(iommu->reg + DMAR_GSTS_REG);
679 	if (!(sts & DMA_GSTS_IRES))
680 		goto end;
681 
682 	iommu->gcmd &= ~DMA_GCMD_IRE;
683 	writel(iommu->gcmd, iommu->reg + DMAR_GCMD_REG);
684 
685 	IOMMU_WAIT_OP(iommu, DMAR_GSTS_REG,
686 		      readl, !(sts & DMA_GSTS_IRES), sts);
687 
688 end:
689 	raw_spin_unlock_irqrestore(&iommu->register_lock, flags);
690 }
691 
692 static int __init dmar_x2apic_optout(void)
693 {
694 	struct acpi_table_dmar *dmar;
695 	dmar = (struct acpi_table_dmar *)dmar_tbl;
696 	if (!dmar || no_x2apic_optout)
697 		return 0;
698 	return dmar->flags & DMAR_X2APIC_OPT_OUT;
699 }
700 
701 static void __init intel_cleanup_irq_remapping(void)
702 {
703 	struct dmar_drhd_unit *drhd;
704 	struct intel_iommu *iommu;
705 
706 	for_each_iommu(iommu, drhd) {
707 		if (ecap_ir_support(iommu->ecap)) {
708 			iommu_disable_irq_remapping(iommu);
709 			intel_teardown_irq_remapping(iommu);
710 		}
711 	}
712 
713 	if (x2apic_supported())
714 		pr_warn("Failed to enable irq remapping. You are vulnerable to irq-injection attacks.\n");
715 }
716 
717 static int __init intel_prepare_irq_remapping(void)
718 {
719 	struct dmar_drhd_unit *drhd;
720 	struct intel_iommu *iommu;
721 	int eim = 0;
722 
723 	if (irq_remap_broken) {
724 		pr_warn("This system BIOS has enabled interrupt remapping\n"
725 			"on a chipset that contains an erratum making that\n"
726 			"feature unstable.  To maintain system stability\n"
727 			"interrupt remapping is being disabled.  Please\n"
728 			"contact your BIOS vendor for an update\n");
729 		add_taint(TAINT_FIRMWARE_WORKAROUND, LOCKDEP_STILL_OK);
730 		return -ENODEV;
731 	}
732 
733 	if (dmar_table_init() < 0)
734 		return -ENODEV;
735 
736 	if (intel_cap_audit(CAP_AUDIT_STATIC_IRQR, NULL))
737 		return -ENODEV;
738 
739 	if (!dmar_ir_support())
740 		return -ENODEV;
741 
742 	if (parse_ioapics_under_ir()) {
743 		pr_info("Not enabling interrupt remapping\n");
744 		goto error;
745 	}
746 
747 	/* First make sure all IOMMUs support IRQ remapping */
748 	for_each_iommu(iommu, drhd)
749 		if (!ecap_ir_support(iommu->ecap))
750 			goto error;
751 
752 	/* Detect remapping mode: lapic or x2apic */
753 	if (x2apic_supported()) {
754 		eim = !dmar_x2apic_optout();
755 		if (!eim) {
756 			pr_info("x2apic is disabled because BIOS sets x2apic opt out bit.");
757 			pr_info("Use 'intremap=no_x2apic_optout' to override the BIOS setting.\n");
758 		}
759 	}
760 
761 	for_each_iommu(iommu, drhd) {
762 		if (eim && !ecap_eim_support(iommu->ecap)) {
763 			pr_info("%s does not support EIM\n", iommu->name);
764 			eim = 0;
765 		}
766 	}
767 
768 	eim_mode = eim;
769 	if (eim)
770 		pr_info("Queued invalidation will be enabled to support x2apic and Intr-remapping.\n");
771 
772 	/* Do the initializations early */
773 	for_each_iommu(iommu, drhd) {
774 		if (intel_setup_irq_remapping(iommu)) {
775 			pr_err("Failed to setup irq remapping for %s\n",
776 			       iommu->name);
777 			goto error;
778 		}
779 	}
780 
781 	return 0;
782 
783 error:
784 	intel_cleanup_irq_remapping();
785 	return -ENODEV;
786 }
787 
788 /*
789  * Set Posted-Interrupts capability.
790  */
791 static inline void set_irq_posting_cap(void)
792 {
793 	struct dmar_drhd_unit *drhd;
794 	struct intel_iommu *iommu;
795 
796 	if (!disable_irq_post) {
797 		/*
798 		 * If IRTE is in posted format, the 'pda' field goes across the
799 		 * 64-bit boundary, we need use cmpxchg16b to atomically update
800 		 * it. We only expose posted-interrupt when X86_FEATURE_CX16
801 		 * is supported. Actually, hardware platforms supporting PI
802 		 * should have X86_FEATURE_CX16 support, this has been confirmed
803 		 * with Intel hardware guys.
804 		 */
805 		if (boot_cpu_has(X86_FEATURE_CX16))
806 			intel_irq_remap_ops.capability |= 1 << IRQ_POSTING_CAP;
807 
808 		for_each_iommu(iommu, drhd)
809 			if (!cap_pi_support(iommu->cap)) {
810 				intel_irq_remap_ops.capability &=
811 						~(1 << IRQ_POSTING_CAP);
812 				break;
813 			}
814 	}
815 }
816 
817 static int __init intel_enable_irq_remapping(void)
818 {
819 	struct dmar_drhd_unit *drhd;
820 	struct intel_iommu *iommu;
821 	bool setup = false;
822 
823 	/*
824 	 * Setup Interrupt-remapping for all the DRHD's now.
825 	 */
826 	for_each_iommu(iommu, drhd) {
827 		if (!ir_pre_enabled(iommu))
828 			iommu_enable_irq_remapping(iommu);
829 		setup = true;
830 	}
831 
832 	if (!setup)
833 		goto error;
834 
835 	irq_remapping_enabled = 1;
836 
837 	set_irq_posting_cap();
838 
839 	pr_info("Enabled IRQ remapping in %s mode\n", eim_mode ? "x2apic" : "xapic");
840 
841 	return eim_mode ? IRQ_REMAP_X2APIC_MODE : IRQ_REMAP_XAPIC_MODE;
842 
843 error:
844 	intel_cleanup_irq_remapping();
845 	return -1;
846 }
847 
848 static int ir_parse_one_hpet_scope(struct acpi_dmar_device_scope *scope,
849 				   struct intel_iommu *iommu,
850 				   struct acpi_dmar_hardware_unit *drhd)
851 {
852 	struct acpi_dmar_pci_path *path;
853 	u8 bus;
854 	int count, free = -1;
855 
856 	bus = scope->bus;
857 	path = (struct acpi_dmar_pci_path *)(scope + 1);
858 	count = (scope->length - sizeof(struct acpi_dmar_device_scope))
859 		/ sizeof(struct acpi_dmar_pci_path);
860 
861 	while (--count > 0) {
862 		/*
863 		 * Access PCI directly due to the PCI
864 		 * subsystem isn't initialized yet.
865 		 */
866 		bus = read_pci_config_byte(bus, path->device, path->function,
867 					   PCI_SECONDARY_BUS);
868 		path++;
869 	}
870 
871 	for (count = 0; count < MAX_HPET_TBS; count++) {
872 		if (ir_hpet[count].iommu == iommu &&
873 		    ir_hpet[count].id == scope->enumeration_id)
874 			return 0;
875 		else if (ir_hpet[count].iommu == NULL && free == -1)
876 			free = count;
877 	}
878 	if (free == -1) {
879 		pr_warn("Exceeded Max HPET blocks\n");
880 		return -ENOSPC;
881 	}
882 
883 	ir_hpet[free].iommu = iommu;
884 	ir_hpet[free].id    = scope->enumeration_id;
885 	ir_hpet[free].bus   = bus;
886 	ir_hpet[free].devfn = PCI_DEVFN(path->device, path->function);
887 	pr_info("HPET id %d under DRHD base 0x%Lx\n",
888 		scope->enumeration_id, drhd->address);
889 
890 	return 0;
891 }
892 
893 static int ir_parse_one_ioapic_scope(struct acpi_dmar_device_scope *scope,
894 				     struct intel_iommu *iommu,
895 				     struct acpi_dmar_hardware_unit *drhd)
896 {
897 	struct acpi_dmar_pci_path *path;
898 	u8 bus;
899 	int count, free = -1;
900 
901 	bus = scope->bus;
902 	path = (struct acpi_dmar_pci_path *)(scope + 1);
903 	count = (scope->length - sizeof(struct acpi_dmar_device_scope))
904 		/ sizeof(struct acpi_dmar_pci_path);
905 
906 	while (--count > 0) {
907 		/*
908 		 * Access PCI directly due to the PCI
909 		 * subsystem isn't initialized yet.
910 		 */
911 		bus = read_pci_config_byte(bus, path->device, path->function,
912 					   PCI_SECONDARY_BUS);
913 		path++;
914 	}
915 
916 	for (count = 0; count < MAX_IO_APICS; count++) {
917 		if (ir_ioapic[count].iommu == iommu &&
918 		    ir_ioapic[count].id == scope->enumeration_id)
919 			return 0;
920 		else if (ir_ioapic[count].iommu == NULL && free == -1)
921 			free = count;
922 	}
923 	if (free == -1) {
924 		pr_warn("Exceeded Max IO APICS\n");
925 		return -ENOSPC;
926 	}
927 
928 	ir_ioapic[free].bus   = bus;
929 	ir_ioapic[free].devfn = PCI_DEVFN(path->device, path->function);
930 	ir_ioapic[free].iommu = iommu;
931 	ir_ioapic[free].id    = scope->enumeration_id;
932 	pr_info("IOAPIC id %d under DRHD base  0x%Lx IOMMU %d\n",
933 		scope->enumeration_id, drhd->address, iommu->seq_id);
934 
935 	return 0;
936 }
937 
938 static int ir_parse_ioapic_hpet_scope(struct acpi_dmar_header *header,
939 				      struct intel_iommu *iommu)
940 {
941 	int ret = 0;
942 	struct acpi_dmar_hardware_unit *drhd;
943 	struct acpi_dmar_device_scope *scope;
944 	void *start, *end;
945 
946 	drhd = (struct acpi_dmar_hardware_unit *)header;
947 	start = (void *)(drhd + 1);
948 	end = ((void *)drhd) + header->length;
949 
950 	while (start < end && ret == 0) {
951 		scope = start;
952 		if (scope->entry_type == ACPI_DMAR_SCOPE_TYPE_IOAPIC)
953 			ret = ir_parse_one_ioapic_scope(scope, iommu, drhd);
954 		else if (scope->entry_type == ACPI_DMAR_SCOPE_TYPE_HPET)
955 			ret = ir_parse_one_hpet_scope(scope, iommu, drhd);
956 		start += scope->length;
957 	}
958 
959 	return ret;
960 }
961 
962 static void ir_remove_ioapic_hpet_scope(struct intel_iommu *iommu)
963 {
964 	int i;
965 
966 	for (i = 0; i < MAX_HPET_TBS; i++)
967 		if (ir_hpet[i].iommu == iommu)
968 			ir_hpet[i].iommu = NULL;
969 
970 	for (i = 0; i < MAX_IO_APICS; i++)
971 		if (ir_ioapic[i].iommu == iommu)
972 			ir_ioapic[i].iommu = NULL;
973 }
974 
975 /*
976  * Finds the assocaition between IOAPIC's and its Interrupt-remapping
977  * hardware unit.
978  */
979 static int __init parse_ioapics_under_ir(void)
980 {
981 	struct dmar_drhd_unit *drhd;
982 	struct intel_iommu *iommu;
983 	bool ir_supported = false;
984 	int ioapic_idx;
985 
986 	for_each_iommu(iommu, drhd) {
987 		int ret;
988 
989 		if (!ecap_ir_support(iommu->ecap))
990 			continue;
991 
992 		ret = ir_parse_ioapic_hpet_scope(drhd->hdr, iommu);
993 		if (ret)
994 			return ret;
995 
996 		ir_supported = true;
997 	}
998 
999 	if (!ir_supported)
1000 		return -ENODEV;
1001 
1002 	for (ioapic_idx = 0; ioapic_idx < nr_ioapics; ioapic_idx++) {
1003 		int ioapic_id = mpc_ioapic_id(ioapic_idx);
1004 		if (!map_ioapic_to_iommu(ioapic_id)) {
1005 			pr_err(FW_BUG "ioapic %d has no mapping iommu, "
1006 			       "interrupt remapping will be disabled\n",
1007 			       ioapic_id);
1008 			return -1;
1009 		}
1010 	}
1011 
1012 	return 0;
1013 }
1014 
1015 static int __init ir_dev_scope_init(void)
1016 {
1017 	int ret;
1018 
1019 	if (!irq_remapping_enabled)
1020 		return 0;
1021 
1022 	down_write(&dmar_global_lock);
1023 	ret = dmar_dev_scope_init();
1024 	up_write(&dmar_global_lock);
1025 
1026 	return ret;
1027 }
1028 rootfs_initcall(ir_dev_scope_init);
1029 
1030 static void disable_irq_remapping(void)
1031 {
1032 	struct dmar_drhd_unit *drhd;
1033 	struct intel_iommu *iommu = NULL;
1034 
1035 	/*
1036 	 * Disable Interrupt-remapping for all the DRHD's now.
1037 	 */
1038 	for_each_iommu(iommu, drhd) {
1039 		if (!ecap_ir_support(iommu->ecap))
1040 			continue;
1041 
1042 		iommu_disable_irq_remapping(iommu);
1043 	}
1044 
1045 	/*
1046 	 * Clear Posted-Interrupts capability.
1047 	 */
1048 	if (!disable_irq_post)
1049 		intel_irq_remap_ops.capability &= ~(1 << IRQ_POSTING_CAP);
1050 }
1051 
1052 static int reenable_irq_remapping(int eim)
1053 {
1054 	struct dmar_drhd_unit *drhd;
1055 	bool setup = false;
1056 	struct intel_iommu *iommu = NULL;
1057 
1058 	for_each_iommu(iommu, drhd)
1059 		if (iommu->qi)
1060 			dmar_reenable_qi(iommu);
1061 
1062 	/*
1063 	 * Setup Interrupt-remapping for all the DRHD's now.
1064 	 */
1065 	for_each_iommu(iommu, drhd) {
1066 		if (!ecap_ir_support(iommu->ecap))
1067 			continue;
1068 
1069 		/* Set up interrupt remapping for iommu.*/
1070 		iommu_set_irq_remapping(iommu, eim);
1071 		iommu_enable_irq_remapping(iommu);
1072 		setup = true;
1073 	}
1074 
1075 	if (!setup)
1076 		goto error;
1077 
1078 	set_irq_posting_cap();
1079 
1080 	return 0;
1081 
1082 error:
1083 	/*
1084 	 * handle error condition gracefully here!
1085 	 */
1086 	return -1;
1087 }
1088 
1089 /*
1090  * Store the MSI remapping domain pointer in the device if enabled.
1091  *
1092  * This is called from dmar_pci_bus_add_dev() so it works even when DMA
1093  * remapping is disabled. Only update the pointer if the device is not
1094  * already handled by a non default PCI/MSI interrupt domain. This protects
1095  * e.g. VMD devices.
1096  */
1097 void intel_irq_remap_add_device(struct dmar_pci_notify_info *info)
1098 {
1099 	if (!irq_remapping_enabled || !pci_dev_has_default_msi_parent_domain(info->dev))
1100 		return;
1101 
1102 	dev_set_msi_domain(&info->dev->dev, map_dev_to_ir(info->dev));
1103 }
1104 
1105 static void prepare_irte(struct irte *irte, int vector, unsigned int dest)
1106 {
1107 	memset(irte, 0, sizeof(*irte));
1108 
1109 	irte->present = 1;
1110 	irte->dst_mode = apic->dest_mode_logical;
1111 	/*
1112 	 * Trigger mode in the IRTE will always be edge, and for IO-APIC, the
1113 	 * actual level or edge trigger will be setup in the IO-APIC
1114 	 * RTE. This will help simplify level triggered irq migration.
1115 	 * For more details, see the comments (in io_apic.c) explainig IO-APIC
1116 	 * irq migration in the presence of interrupt-remapping.
1117 	*/
1118 	irte->trigger_mode = 0;
1119 	irte->dlvry_mode = apic->delivery_mode;
1120 	irte->vector = vector;
1121 	irte->dest_id = IRTE_DEST(dest);
1122 	irte->redir_hint = 1;
1123 }
1124 
1125 struct irq_remap_ops intel_irq_remap_ops = {
1126 	.prepare		= intel_prepare_irq_remapping,
1127 	.enable			= intel_enable_irq_remapping,
1128 	.disable		= disable_irq_remapping,
1129 	.reenable		= reenable_irq_remapping,
1130 	.enable_faulting	= enable_drhd_fault_handling,
1131 };
1132 
1133 static void intel_ir_reconfigure_irte(struct irq_data *irqd, bool force)
1134 {
1135 	struct intel_ir_data *ir_data = irqd->chip_data;
1136 	struct irte *irte = &ir_data->irte_entry;
1137 	struct irq_cfg *cfg = irqd_cfg(irqd);
1138 
1139 	/*
1140 	 * Atomically updates the IRTE with the new destination, vector
1141 	 * and flushes the interrupt entry cache.
1142 	 */
1143 	irte->vector = cfg->vector;
1144 	irte->dest_id = IRTE_DEST(cfg->dest_apicid);
1145 
1146 	/* Update the hardware only if the interrupt is in remapped mode. */
1147 	if (force || ir_data->irq_2_iommu.mode == IRQ_REMAPPING)
1148 		modify_irte(&ir_data->irq_2_iommu, irte);
1149 }
1150 
1151 /*
1152  * Migrate the IO-APIC irq in the presence of intr-remapping.
1153  *
1154  * For both level and edge triggered, irq migration is a simple atomic
1155  * update(of vector and cpu destination) of IRTE and flush the hardware cache.
1156  *
1157  * For level triggered, we eliminate the io-apic RTE modification (with the
1158  * updated vector information), by using a virtual vector (io-apic pin number).
1159  * Real vector that is used for interrupting cpu will be coming from
1160  * the interrupt-remapping table entry.
1161  *
1162  * As the migration is a simple atomic update of IRTE, the same mechanism
1163  * is used to migrate MSI irq's in the presence of interrupt-remapping.
1164  */
1165 static int
1166 intel_ir_set_affinity(struct irq_data *data, const struct cpumask *mask,
1167 		      bool force)
1168 {
1169 	struct irq_data *parent = data->parent_data;
1170 	struct irq_cfg *cfg = irqd_cfg(data);
1171 	int ret;
1172 
1173 	ret = parent->chip->irq_set_affinity(parent, mask, force);
1174 	if (ret < 0 || ret == IRQ_SET_MASK_OK_DONE)
1175 		return ret;
1176 
1177 	intel_ir_reconfigure_irte(data, false);
1178 	/*
1179 	 * After this point, all the interrupts will start arriving
1180 	 * at the new destination. So, time to cleanup the previous
1181 	 * vector allocation.
1182 	 */
1183 	send_cleanup_vector(cfg);
1184 
1185 	return IRQ_SET_MASK_OK_DONE;
1186 }
1187 
1188 static void intel_ir_compose_msi_msg(struct irq_data *irq_data,
1189 				     struct msi_msg *msg)
1190 {
1191 	struct intel_ir_data *ir_data = irq_data->chip_data;
1192 
1193 	*msg = ir_data->msi_entry;
1194 }
1195 
1196 static int intel_ir_set_vcpu_affinity(struct irq_data *data, void *info)
1197 {
1198 	struct intel_ir_data *ir_data = data->chip_data;
1199 	struct vcpu_data *vcpu_pi_info = info;
1200 
1201 	/* stop posting interrupts, back to remapping mode */
1202 	if (!vcpu_pi_info) {
1203 		modify_irte(&ir_data->irq_2_iommu, &ir_data->irte_entry);
1204 	} else {
1205 		struct irte irte_pi;
1206 
1207 		/*
1208 		 * We are not caching the posted interrupt entry. We
1209 		 * copy the data from the remapped entry and modify
1210 		 * the fields which are relevant for posted mode. The
1211 		 * cached remapped entry is used for switching back to
1212 		 * remapped mode.
1213 		 */
1214 		memset(&irte_pi, 0, sizeof(irte_pi));
1215 		dmar_copy_shared_irte(&irte_pi, &ir_data->irte_entry);
1216 
1217 		/* Update the posted mode fields */
1218 		irte_pi.p_pst = 1;
1219 		irte_pi.p_urgent = 0;
1220 		irte_pi.p_vector = vcpu_pi_info->vector;
1221 		irte_pi.pda_l = (vcpu_pi_info->pi_desc_addr >>
1222 				(32 - PDA_LOW_BIT)) & ~(-1UL << PDA_LOW_BIT);
1223 		irte_pi.pda_h = (vcpu_pi_info->pi_desc_addr >> 32) &
1224 				~(-1UL << PDA_HIGH_BIT);
1225 
1226 		modify_irte(&ir_data->irq_2_iommu, &irte_pi);
1227 	}
1228 
1229 	return 0;
1230 }
1231 
1232 static struct irq_chip intel_ir_chip = {
1233 	.name			= "INTEL-IR",
1234 	.irq_ack		= apic_ack_irq,
1235 	.irq_set_affinity	= intel_ir_set_affinity,
1236 	.irq_compose_msi_msg	= intel_ir_compose_msi_msg,
1237 	.irq_set_vcpu_affinity	= intel_ir_set_vcpu_affinity,
1238 };
1239 
1240 static void fill_msi_msg(struct msi_msg *msg, u32 index, u32 subhandle)
1241 {
1242 	memset(msg, 0, sizeof(*msg));
1243 
1244 	msg->arch_addr_lo.dmar_base_address = X86_MSI_BASE_ADDRESS_LOW;
1245 	msg->arch_addr_lo.dmar_subhandle_valid = true;
1246 	msg->arch_addr_lo.dmar_format = true;
1247 	msg->arch_addr_lo.dmar_index_0_14 = index & 0x7FFF;
1248 	msg->arch_addr_lo.dmar_index_15 = !!(index & 0x8000);
1249 
1250 	msg->address_hi = X86_MSI_BASE_ADDRESS_HIGH;
1251 
1252 	msg->arch_data.dmar_subhandle = subhandle;
1253 }
1254 
1255 static void intel_irq_remapping_prepare_irte(struct intel_ir_data *data,
1256 					     struct irq_cfg *irq_cfg,
1257 					     struct irq_alloc_info *info,
1258 					     int index, int sub_handle)
1259 {
1260 	struct irte *irte = &data->irte_entry;
1261 
1262 	prepare_irte(irte, irq_cfg->vector, irq_cfg->dest_apicid);
1263 
1264 	switch (info->type) {
1265 	case X86_IRQ_ALLOC_TYPE_IOAPIC:
1266 		/* Set source-id of interrupt request */
1267 		set_ioapic_sid(irte, info->devid);
1268 		apic_printk(APIC_VERBOSE, KERN_DEBUG "IOAPIC[%d]: Set IRTE entry (P:%d FPD:%d Dst_Mode:%d Redir_hint:%d Trig_Mode:%d Dlvry_Mode:%X Avail:%X Vector:%02X Dest:%08X SID:%04X SQ:%X SVT:%X)\n",
1269 			info->devid, irte->present, irte->fpd,
1270 			irte->dst_mode, irte->redir_hint,
1271 			irte->trigger_mode, irte->dlvry_mode,
1272 			irte->avail, irte->vector, irte->dest_id,
1273 			irte->sid, irte->sq, irte->svt);
1274 		sub_handle = info->ioapic.pin;
1275 		break;
1276 	case X86_IRQ_ALLOC_TYPE_HPET:
1277 		set_hpet_sid(irte, info->devid);
1278 		break;
1279 	case X86_IRQ_ALLOC_TYPE_PCI_MSI:
1280 	case X86_IRQ_ALLOC_TYPE_PCI_MSIX:
1281 		set_msi_sid(irte,
1282 			    pci_real_dma_dev(msi_desc_to_pci_dev(info->desc)));
1283 		break;
1284 	default:
1285 		BUG_ON(1);
1286 		break;
1287 	}
1288 	fill_msi_msg(&data->msi_entry, index, sub_handle);
1289 }
1290 
1291 static void intel_free_irq_resources(struct irq_domain *domain,
1292 				     unsigned int virq, unsigned int nr_irqs)
1293 {
1294 	struct irq_data *irq_data;
1295 	struct intel_ir_data *data;
1296 	struct irq_2_iommu *irq_iommu;
1297 	unsigned long flags;
1298 	int i;
1299 	for (i = 0; i < nr_irqs; i++) {
1300 		irq_data = irq_domain_get_irq_data(domain, virq  + i);
1301 		if (irq_data && irq_data->chip_data) {
1302 			data = irq_data->chip_data;
1303 			irq_iommu = &data->irq_2_iommu;
1304 			raw_spin_lock_irqsave(&irq_2_ir_lock, flags);
1305 			clear_entries(irq_iommu);
1306 			raw_spin_unlock_irqrestore(&irq_2_ir_lock, flags);
1307 			irq_domain_reset_irq_data(irq_data);
1308 			kfree(data);
1309 		}
1310 	}
1311 }
1312 
1313 static int intel_irq_remapping_alloc(struct irq_domain *domain,
1314 				     unsigned int virq, unsigned int nr_irqs,
1315 				     void *arg)
1316 {
1317 	struct intel_iommu *iommu = domain->host_data;
1318 	struct irq_alloc_info *info = arg;
1319 	struct intel_ir_data *data, *ird;
1320 	struct irq_data *irq_data;
1321 	struct irq_cfg *irq_cfg;
1322 	int i, ret, index;
1323 
1324 	if (!info || !iommu)
1325 		return -EINVAL;
1326 	if (nr_irqs > 1 && info->type != X86_IRQ_ALLOC_TYPE_PCI_MSI)
1327 		return -EINVAL;
1328 
1329 	ret = irq_domain_alloc_irqs_parent(domain, virq, nr_irqs, arg);
1330 	if (ret < 0)
1331 		return ret;
1332 
1333 	ret = -ENOMEM;
1334 	data = kzalloc(sizeof(*data), GFP_KERNEL);
1335 	if (!data)
1336 		goto out_free_parent;
1337 
1338 	index = alloc_irte(iommu, &data->irq_2_iommu, nr_irqs);
1339 	if (index < 0) {
1340 		pr_warn("Failed to allocate IRTE\n");
1341 		kfree(data);
1342 		goto out_free_parent;
1343 	}
1344 
1345 	for (i = 0; i < nr_irqs; i++) {
1346 		irq_data = irq_domain_get_irq_data(domain, virq + i);
1347 		irq_cfg = irqd_cfg(irq_data);
1348 		if (!irq_data || !irq_cfg) {
1349 			if (!i)
1350 				kfree(data);
1351 			ret = -EINVAL;
1352 			goto out_free_data;
1353 		}
1354 
1355 		if (i > 0) {
1356 			ird = kzalloc(sizeof(*ird), GFP_KERNEL);
1357 			if (!ird)
1358 				goto out_free_data;
1359 			/* Initialize the common data */
1360 			ird->irq_2_iommu = data->irq_2_iommu;
1361 			ird->irq_2_iommu.sub_handle = i;
1362 		} else {
1363 			ird = data;
1364 		}
1365 
1366 		irq_data->hwirq = (index << 16) + i;
1367 		irq_data->chip_data = ird;
1368 		irq_data->chip = &intel_ir_chip;
1369 		intel_irq_remapping_prepare_irte(ird, irq_cfg, info, index, i);
1370 		irq_set_status_flags(virq + i, IRQ_MOVE_PCNTXT);
1371 	}
1372 	return 0;
1373 
1374 out_free_data:
1375 	intel_free_irq_resources(domain, virq, i);
1376 out_free_parent:
1377 	irq_domain_free_irqs_common(domain, virq, nr_irqs);
1378 	return ret;
1379 }
1380 
1381 static void intel_irq_remapping_free(struct irq_domain *domain,
1382 				     unsigned int virq, unsigned int nr_irqs)
1383 {
1384 	intel_free_irq_resources(domain, virq, nr_irqs);
1385 	irq_domain_free_irqs_common(domain, virq, nr_irqs);
1386 }
1387 
1388 static int intel_irq_remapping_activate(struct irq_domain *domain,
1389 					struct irq_data *irq_data, bool reserve)
1390 {
1391 	intel_ir_reconfigure_irte(irq_data, true);
1392 	return 0;
1393 }
1394 
1395 static void intel_irq_remapping_deactivate(struct irq_domain *domain,
1396 					   struct irq_data *irq_data)
1397 {
1398 	struct intel_ir_data *data = irq_data->chip_data;
1399 	struct irte entry;
1400 
1401 	memset(&entry, 0, sizeof(entry));
1402 	modify_irte(&data->irq_2_iommu, &entry);
1403 }
1404 
1405 static int intel_irq_remapping_select(struct irq_domain *d,
1406 				      struct irq_fwspec *fwspec,
1407 				      enum irq_domain_bus_token bus_token)
1408 {
1409 	struct intel_iommu *iommu = NULL;
1410 
1411 	if (x86_fwspec_is_ioapic(fwspec))
1412 		iommu = map_ioapic_to_iommu(fwspec->param[0]);
1413 	else if (x86_fwspec_is_hpet(fwspec))
1414 		iommu = map_hpet_to_iommu(fwspec->param[0]);
1415 
1416 	return iommu && d == iommu->ir_domain;
1417 }
1418 
1419 static const struct irq_domain_ops intel_ir_domain_ops = {
1420 	.select = intel_irq_remapping_select,
1421 	.alloc = intel_irq_remapping_alloc,
1422 	.free = intel_irq_remapping_free,
1423 	.activate = intel_irq_remapping_activate,
1424 	.deactivate = intel_irq_remapping_deactivate,
1425 };
1426 
1427 static const struct msi_parent_ops dmar_msi_parent_ops = {
1428 	.supported_flags	= X86_VECTOR_MSI_FLAGS_SUPPORTED |
1429 				  MSI_FLAG_MULTI_PCI_MSI |
1430 				  MSI_FLAG_PCI_IMS,
1431 	.prefix			= "IR-",
1432 	.init_dev_msi_info	= msi_parent_init_dev_msi_info,
1433 };
1434 
1435 static const struct msi_parent_ops virt_dmar_msi_parent_ops = {
1436 	.supported_flags	= X86_VECTOR_MSI_FLAGS_SUPPORTED |
1437 				  MSI_FLAG_MULTI_PCI_MSI,
1438 	.prefix			= "vIR-",
1439 	.init_dev_msi_info	= msi_parent_init_dev_msi_info,
1440 };
1441 
1442 /*
1443  * Support of Interrupt Remapping Unit Hotplug
1444  */
1445 static int dmar_ir_add(struct dmar_drhd_unit *dmaru, struct intel_iommu *iommu)
1446 {
1447 	int ret;
1448 	int eim = x2apic_enabled();
1449 
1450 	ret = intel_cap_audit(CAP_AUDIT_HOTPLUG_IRQR, iommu);
1451 	if (ret)
1452 		return ret;
1453 
1454 	if (eim && !ecap_eim_support(iommu->ecap)) {
1455 		pr_info("DRHD %Lx: EIM not supported by DRHD, ecap %Lx\n",
1456 			iommu->reg_phys, iommu->ecap);
1457 		return -ENODEV;
1458 	}
1459 
1460 	if (ir_parse_ioapic_hpet_scope(dmaru->hdr, iommu)) {
1461 		pr_warn("DRHD %Lx: failed to parse managed IOAPIC/HPET\n",
1462 			iommu->reg_phys);
1463 		return -ENODEV;
1464 	}
1465 
1466 	/* TODO: check all IOAPICs are covered by IOMMU */
1467 
1468 	/* Setup Interrupt-remapping now. */
1469 	ret = intel_setup_irq_remapping(iommu);
1470 	if (ret) {
1471 		pr_err("Failed to setup irq remapping for %s\n",
1472 		       iommu->name);
1473 		intel_teardown_irq_remapping(iommu);
1474 		ir_remove_ioapic_hpet_scope(iommu);
1475 	} else {
1476 		iommu_enable_irq_remapping(iommu);
1477 	}
1478 
1479 	return ret;
1480 }
1481 
1482 int dmar_ir_hotplug(struct dmar_drhd_unit *dmaru, bool insert)
1483 {
1484 	int ret = 0;
1485 	struct intel_iommu *iommu = dmaru->iommu;
1486 
1487 	if (!irq_remapping_enabled)
1488 		return 0;
1489 	if (iommu == NULL)
1490 		return -EINVAL;
1491 	if (!ecap_ir_support(iommu->ecap))
1492 		return 0;
1493 	if (irq_remapping_cap(IRQ_POSTING_CAP) &&
1494 	    !cap_pi_support(iommu->cap))
1495 		return -EBUSY;
1496 
1497 	if (insert) {
1498 		if (!iommu->ir_table)
1499 			ret = dmar_ir_add(dmaru, iommu);
1500 	} else {
1501 		if (iommu->ir_table) {
1502 			if (!bitmap_empty(iommu->ir_table->bitmap,
1503 					  INTR_REMAP_TABLE_ENTRIES)) {
1504 				ret = -EBUSY;
1505 			} else {
1506 				iommu_disable_irq_remapping(iommu);
1507 				intel_teardown_irq_remapping(iommu);
1508 				ir_remove_ioapic_hpet_scope(iommu);
1509 			}
1510 		}
1511 	}
1512 
1513 	return ret;
1514 }
1515