xref: /openbmc/linux/drivers/iommu/amd/iommu.c (revision 06c6fad9)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2007-2010 Advanced Micro Devices, Inc.
4  * Author: Joerg Roedel <jroedel@suse.de>
5  *         Leo Duran <leo.duran@amd.com>
6  */
7 
8 #define pr_fmt(fmt)     "AMD-Vi: " fmt
9 #define dev_fmt(fmt)    pr_fmt(fmt)
10 
11 #include <linux/ratelimit.h>
12 #include <linux/pci.h>
13 #include <linux/acpi.h>
14 #include <linux/amba/bus.h>
15 #include <linux/platform_device.h>
16 #include <linux/pci-ats.h>
17 #include <linux/bitmap.h>
18 #include <linux/slab.h>
19 #include <linux/debugfs.h>
20 #include <linux/scatterlist.h>
21 #include <linux/dma-map-ops.h>
22 #include <linux/dma-direct.h>
23 #include <linux/dma-iommu.h>
24 #include <linux/iommu-helper.h>
25 #include <linux/delay.h>
26 #include <linux/amd-iommu.h>
27 #include <linux/notifier.h>
28 #include <linux/export.h>
29 #include <linux/irq.h>
30 #include <linux/msi.h>
31 #include <linux/irqdomain.h>
32 #include <linux/percpu.h>
33 #include <linux/iova.h>
34 #include <linux/io-pgtable.h>
35 #include <asm/irq_remapping.h>
36 #include <asm/io_apic.h>
37 #include <asm/apic.h>
38 #include <asm/hw_irq.h>
39 #include <asm/proto.h>
40 #include <asm/iommu.h>
41 #include <asm/gart.h>
42 #include <asm/dma.h>
43 
44 #include "amd_iommu.h"
45 #include "../irq_remapping.h"
46 
47 #define CMD_SET_TYPE(cmd, t) ((cmd)->data[1] |= ((t) << 28))
48 
49 #define LOOP_TIMEOUT	100000
50 
51 /* IO virtual address start page frame number */
52 #define IOVA_START_PFN		(1)
53 #define IOVA_PFN(addr)		((addr) >> PAGE_SHIFT)
54 
55 /* Reserved IOVA ranges */
56 #define MSI_RANGE_START		(0xfee00000)
57 #define MSI_RANGE_END		(0xfeefffff)
58 #define HT_RANGE_START		(0xfd00000000ULL)
59 #define HT_RANGE_END		(0xffffffffffULL)
60 
61 #define DEFAULT_PGTABLE_LEVEL	PAGE_MODE_3_LEVEL
62 
63 static DEFINE_SPINLOCK(pd_bitmap_lock);
64 
65 /* List of all available dev_data structures */
66 static LLIST_HEAD(dev_data_list);
67 
68 LIST_HEAD(ioapic_map);
69 LIST_HEAD(hpet_map);
70 LIST_HEAD(acpihid_map);
71 
72 /*
73  * Domain for untranslated devices - only allocated
74  * if iommu=pt passed on kernel cmd line.
75  */
76 const struct iommu_ops amd_iommu_ops;
77 
78 static ATOMIC_NOTIFIER_HEAD(ppr_notifier);
79 int amd_iommu_max_glx_val = -1;
80 
81 /*
82  * general struct to manage commands send to an IOMMU
83  */
84 struct iommu_cmd {
85 	u32 data[4];
86 };
87 
88 struct kmem_cache *amd_iommu_irq_cache;
89 
90 static void detach_device(struct device *dev);
91 
92 /****************************************************************************
93  *
94  * Helper functions
95  *
96  ****************************************************************************/
97 
98 static inline u16 get_pci_device_id(struct device *dev)
99 {
100 	struct pci_dev *pdev = to_pci_dev(dev);
101 
102 	return pci_dev_id(pdev);
103 }
104 
105 static inline int get_acpihid_device_id(struct device *dev,
106 					struct acpihid_map_entry **entry)
107 {
108 	struct acpi_device *adev = ACPI_COMPANION(dev);
109 	struct acpihid_map_entry *p;
110 
111 	if (!adev)
112 		return -ENODEV;
113 
114 	list_for_each_entry(p, &acpihid_map, list) {
115 		if (acpi_dev_hid_uid_match(adev, p->hid,
116 					   p->uid[0] ? p->uid : NULL)) {
117 			if (entry)
118 				*entry = p;
119 			return p->devid;
120 		}
121 	}
122 	return -EINVAL;
123 }
124 
125 static inline int get_device_id(struct device *dev)
126 {
127 	int devid;
128 
129 	if (dev_is_pci(dev))
130 		devid = get_pci_device_id(dev);
131 	else
132 		devid = get_acpihid_device_id(dev, NULL);
133 
134 	return devid;
135 }
136 
137 static struct protection_domain *to_pdomain(struct iommu_domain *dom)
138 {
139 	return container_of(dom, struct protection_domain, domain);
140 }
141 
142 static struct iommu_dev_data *alloc_dev_data(u16 devid)
143 {
144 	struct iommu_dev_data *dev_data;
145 
146 	dev_data = kzalloc(sizeof(*dev_data), GFP_KERNEL);
147 	if (!dev_data)
148 		return NULL;
149 
150 	spin_lock_init(&dev_data->lock);
151 	dev_data->devid = devid;
152 	ratelimit_default_init(&dev_data->rs);
153 
154 	llist_add(&dev_data->dev_data_list, &dev_data_list);
155 	return dev_data;
156 }
157 
158 static struct iommu_dev_data *search_dev_data(u16 devid)
159 {
160 	struct iommu_dev_data *dev_data;
161 	struct llist_node *node;
162 
163 	if (llist_empty(&dev_data_list))
164 		return NULL;
165 
166 	node = dev_data_list.first;
167 	llist_for_each_entry(dev_data, node, dev_data_list) {
168 		if (dev_data->devid == devid)
169 			return dev_data;
170 	}
171 
172 	return NULL;
173 }
174 
175 static int clone_alias(struct pci_dev *pdev, u16 alias, void *data)
176 {
177 	u16 devid = pci_dev_id(pdev);
178 
179 	if (devid == alias)
180 		return 0;
181 
182 	amd_iommu_rlookup_table[alias] =
183 		amd_iommu_rlookup_table[devid];
184 	memcpy(amd_iommu_dev_table[alias].data,
185 	       amd_iommu_dev_table[devid].data,
186 	       sizeof(amd_iommu_dev_table[alias].data));
187 
188 	return 0;
189 }
190 
191 static void clone_aliases(struct pci_dev *pdev)
192 {
193 	if (!pdev)
194 		return;
195 
196 	/*
197 	 * The IVRS alias stored in the alias table may not be
198 	 * part of the PCI DMA aliases if it's bus differs
199 	 * from the original device.
200 	 */
201 	clone_alias(pdev, amd_iommu_alias_table[pci_dev_id(pdev)], NULL);
202 
203 	pci_for_each_dma_alias(pdev, clone_alias, NULL);
204 }
205 
206 static struct pci_dev *setup_aliases(struct device *dev)
207 {
208 	struct pci_dev *pdev = to_pci_dev(dev);
209 	u16 ivrs_alias;
210 
211 	/* For ACPI HID devices, there are no aliases */
212 	if (!dev_is_pci(dev))
213 		return NULL;
214 
215 	/*
216 	 * Add the IVRS alias to the pci aliases if it is on the same
217 	 * bus. The IVRS table may know about a quirk that we don't.
218 	 */
219 	ivrs_alias = amd_iommu_alias_table[pci_dev_id(pdev)];
220 	if (ivrs_alias != pci_dev_id(pdev) &&
221 	    PCI_BUS_NUM(ivrs_alias) == pdev->bus->number)
222 		pci_add_dma_alias(pdev, ivrs_alias & 0xff, 1);
223 
224 	clone_aliases(pdev);
225 
226 	return pdev;
227 }
228 
229 static struct iommu_dev_data *find_dev_data(u16 devid)
230 {
231 	struct iommu_dev_data *dev_data;
232 	struct amd_iommu *iommu = amd_iommu_rlookup_table[devid];
233 
234 	dev_data = search_dev_data(devid);
235 
236 	if (dev_data == NULL) {
237 		dev_data = alloc_dev_data(devid);
238 		if (!dev_data)
239 			return NULL;
240 
241 		if (translation_pre_enabled(iommu))
242 			dev_data->defer_attach = true;
243 	}
244 
245 	return dev_data;
246 }
247 
248 /*
249 * Find or create an IOMMU group for a acpihid device.
250 */
251 static struct iommu_group *acpihid_device_group(struct device *dev)
252 {
253 	struct acpihid_map_entry *p, *entry = NULL;
254 	int devid;
255 
256 	devid = get_acpihid_device_id(dev, &entry);
257 	if (devid < 0)
258 		return ERR_PTR(devid);
259 
260 	list_for_each_entry(p, &acpihid_map, list) {
261 		if ((devid == p->devid) && p->group)
262 			entry->group = p->group;
263 	}
264 
265 	if (!entry->group)
266 		entry->group = generic_device_group(dev);
267 	else
268 		iommu_group_ref_get(entry->group);
269 
270 	return entry->group;
271 }
272 
273 static bool pci_iommuv2_capable(struct pci_dev *pdev)
274 {
275 	static const int caps[] = {
276 		PCI_EXT_CAP_ID_PRI,
277 		PCI_EXT_CAP_ID_PASID,
278 	};
279 	int i, pos;
280 
281 	if (!pci_ats_supported(pdev))
282 		return false;
283 
284 	for (i = 0; i < 2; ++i) {
285 		pos = pci_find_ext_capability(pdev, caps[i]);
286 		if (pos == 0)
287 			return false;
288 	}
289 
290 	return true;
291 }
292 
293 /*
294  * This function checks if the driver got a valid device from the caller to
295  * avoid dereferencing invalid pointers.
296  */
297 static bool check_device(struct device *dev)
298 {
299 	int devid;
300 
301 	if (!dev)
302 		return false;
303 
304 	devid = get_device_id(dev);
305 	if (devid < 0)
306 		return false;
307 
308 	/* Out of our scope? */
309 	if (devid > amd_iommu_last_bdf)
310 		return false;
311 
312 	if (amd_iommu_rlookup_table[devid] == NULL)
313 		return false;
314 
315 	return true;
316 }
317 
318 static int iommu_init_device(struct device *dev)
319 {
320 	struct iommu_dev_data *dev_data;
321 	int devid;
322 
323 	if (dev_iommu_priv_get(dev))
324 		return 0;
325 
326 	devid = get_device_id(dev);
327 	if (devid < 0)
328 		return devid;
329 
330 	dev_data = find_dev_data(devid);
331 	if (!dev_data)
332 		return -ENOMEM;
333 
334 	dev_data->pdev = setup_aliases(dev);
335 
336 	/*
337 	 * By default we use passthrough mode for IOMMUv2 capable device.
338 	 * But if amd_iommu=force_isolation is set (e.g. to debug DMA to
339 	 * invalid address), we ignore the capability for the device so
340 	 * it'll be forced to go into translation mode.
341 	 */
342 	if ((iommu_default_passthrough() || !amd_iommu_force_isolation) &&
343 	    dev_is_pci(dev) && pci_iommuv2_capable(to_pci_dev(dev))) {
344 		struct amd_iommu *iommu;
345 
346 		iommu = amd_iommu_rlookup_table[dev_data->devid];
347 		dev_data->iommu_v2 = iommu->is_iommu_v2;
348 	}
349 
350 	dev_iommu_priv_set(dev, dev_data);
351 
352 	return 0;
353 }
354 
355 static void iommu_ignore_device(struct device *dev)
356 {
357 	int devid;
358 
359 	devid = get_device_id(dev);
360 	if (devid < 0)
361 		return;
362 
363 	amd_iommu_rlookup_table[devid] = NULL;
364 	memset(&amd_iommu_dev_table[devid], 0, sizeof(struct dev_table_entry));
365 
366 	setup_aliases(dev);
367 }
368 
369 static void amd_iommu_uninit_device(struct device *dev)
370 {
371 	struct iommu_dev_data *dev_data;
372 
373 	dev_data = dev_iommu_priv_get(dev);
374 	if (!dev_data)
375 		return;
376 
377 	if (dev_data->domain)
378 		detach_device(dev);
379 
380 	dev_iommu_priv_set(dev, NULL);
381 
382 	/*
383 	 * We keep dev_data around for unplugged devices and reuse it when the
384 	 * device is re-plugged - not doing so would introduce a ton of races.
385 	 */
386 }
387 
388 /****************************************************************************
389  *
390  * Interrupt handling functions
391  *
392  ****************************************************************************/
393 
394 static void dump_dte_entry(u16 devid)
395 {
396 	int i;
397 
398 	for (i = 0; i < 4; ++i)
399 		pr_err("DTE[%d]: %016llx\n", i,
400 			amd_iommu_dev_table[devid].data[i]);
401 }
402 
403 static void dump_command(unsigned long phys_addr)
404 {
405 	struct iommu_cmd *cmd = iommu_phys_to_virt(phys_addr);
406 	int i;
407 
408 	for (i = 0; i < 4; ++i)
409 		pr_err("CMD[%d]: %08x\n", i, cmd->data[i]);
410 }
411 
412 static void amd_iommu_report_rmp_hw_error(volatile u32 *event)
413 {
414 	struct iommu_dev_data *dev_data = NULL;
415 	int devid, vmg_tag, flags;
416 	struct pci_dev *pdev;
417 	u64 spa;
418 
419 	devid   = (event[0] >> EVENT_DEVID_SHIFT) & EVENT_DEVID_MASK;
420 	vmg_tag = (event[1]) & 0xFFFF;
421 	flags   = (event[1] >> EVENT_FLAGS_SHIFT) & EVENT_FLAGS_MASK;
422 	spa     = ((u64)event[3] << 32) | (event[2] & 0xFFFFFFF8);
423 
424 	pdev = pci_get_domain_bus_and_slot(0, PCI_BUS_NUM(devid),
425 					   devid & 0xff);
426 	if (pdev)
427 		dev_data = dev_iommu_priv_get(&pdev->dev);
428 
429 	if (dev_data && __ratelimit(&dev_data->rs)) {
430 		pci_err(pdev, "Event logged [RMP_HW_ERROR vmg_tag=0x%04x, spa=0x%llx, flags=0x%04x]\n",
431 			vmg_tag, spa, flags);
432 	} else {
433 		pr_err_ratelimited("Event logged [RMP_HW_ERROR device=%02x:%02x.%x, vmg_tag=0x%04x, spa=0x%llx, flags=0x%04x]\n",
434 			PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
435 			vmg_tag, spa, flags);
436 	}
437 
438 	if (pdev)
439 		pci_dev_put(pdev);
440 }
441 
442 static void amd_iommu_report_rmp_fault(volatile u32 *event)
443 {
444 	struct iommu_dev_data *dev_data = NULL;
445 	int devid, flags_rmp, vmg_tag, flags;
446 	struct pci_dev *pdev;
447 	u64 gpa;
448 
449 	devid     = (event[0] >> EVENT_DEVID_SHIFT) & EVENT_DEVID_MASK;
450 	flags_rmp = (event[0] >> EVENT_FLAGS_SHIFT) & 0xFF;
451 	vmg_tag   = (event[1]) & 0xFFFF;
452 	flags     = (event[1] >> EVENT_FLAGS_SHIFT) & EVENT_FLAGS_MASK;
453 	gpa       = ((u64)event[3] << 32) | event[2];
454 
455 	pdev = pci_get_domain_bus_and_slot(0, PCI_BUS_NUM(devid),
456 					   devid & 0xff);
457 	if (pdev)
458 		dev_data = dev_iommu_priv_get(&pdev->dev);
459 
460 	if (dev_data && __ratelimit(&dev_data->rs)) {
461 		pci_err(pdev, "Event logged [RMP_PAGE_FAULT vmg_tag=0x%04x, gpa=0x%llx, flags_rmp=0x%04x, flags=0x%04x]\n",
462 			vmg_tag, gpa, flags_rmp, flags);
463 	} else {
464 		pr_err_ratelimited("Event logged [RMP_PAGE_FAULT device=%02x:%02x.%x, vmg_tag=0x%04x, gpa=0x%llx, flags_rmp=0x%04x, flags=0x%04x]\n",
465 			PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
466 			vmg_tag, gpa, flags_rmp, flags);
467 	}
468 
469 	if (pdev)
470 		pci_dev_put(pdev);
471 }
472 
473 static void amd_iommu_report_page_fault(u16 devid, u16 domain_id,
474 					u64 address, int flags)
475 {
476 	struct iommu_dev_data *dev_data = NULL;
477 	struct pci_dev *pdev;
478 
479 	pdev = pci_get_domain_bus_and_slot(0, PCI_BUS_NUM(devid),
480 					   devid & 0xff);
481 	if (pdev)
482 		dev_data = dev_iommu_priv_get(&pdev->dev);
483 
484 	if (dev_data && __ratelimit(&dev_data->rs)) {
485 		pci_err(pdev, "Event logged [IO_PAGE_FAULT domain=0x%04x address=0x%llx flags=0x%04x]\n",
486 			domain_id, address, flags);
487 	} else if (printk_ratelimit()) {
488 		pr_err("Event logged [IO_PAGE_FAULT device=%02x:%02x.%x domain=0x%04x address=0x%llx flags=0x%04x]\n",
489 			PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
490 			domain_id, address, flags);
491 	}
492 
493 	if (pdev)
494 		pci_dev_put(pdev);
495 }
496 
497 static void iommu_print_event(struct amd_iommu *iommu, void *__evt)
498 {
499 	struct device *dev = iommu->iommu.dev;
500 	int type, devid, flags, tag;
501 	volatile u32 *event = __evt;
502 	int count = 0;
503 	u64 address;
504 	u32 pasid;
505 
506 retry:
507 	type    = (event[1] >> EVENT_TYPE_SHIFT)  & EVENT_TYPE_MASK;
508 	devid   = (event[0] >> EVENT_DEVID_SHIFT) & EVENT_DEVID_MASK;
509 	pasid   = (event[0] & EVENT_DOMID_MASK_HI) |
510 		  (event[1] & EVENT_DOMID_MASK_LO);
511 	flags   = (event[1] >> EVENT_FLAGS_SHIFT) & EVENT_FLAGS_MASK;
512 	address = (u64)(((u64)event[3]) << 32) | event[2];
513 
514 	if (type == 0) {
515 		/* Did we hit the erratum? */
516 		if (++count == LOOP_TIMEOUT) {
517 			pr_err("No event written to event log\n");
518 			return;
519 		}
520 		udelay(1);
521 		goto retry;
522 	}
523 
524 	if (type == EVENT_TYPE_IO_FAULT) {
525 		amd_iommu_report_page_fault(devid, pasid, address, flags);
526 		return;
527 	}
528 
529 	switch (type) {
530 	case EVENT_TYPE_ILL_DEV:
531 		dev_err(dev, "Event logged [ILLEGAL_DEV_TABLE_ENTRY device=%02x:%02x.%x pasid=0x%05x address=0x%llx flags=0x%04x]\n",
532 			PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
533 			pasid, address, flags);
534 		dump_dte_entry(devid);
535 		break;
536 	case EVENT_TYPE_DEV_TAB_ERR:
537 		dev_err(dev, "Event logged [DEV_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
538 			"address=0x%llx flags=0x%04x]\n",
539 			PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
540 			address, flags);
541 		break;
542 	case EVENT_TYPE_PAGE_TAB_ERR:
543 		dev_err(dev, "Event logged [PAGE_TAB_HARDWARE_ERROR device=%02x:%02x.%x pasid=0x%04x address=0x%llx flags=0x%04x]\n",
544 			PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
545 			pasid, address, flags);
546 		break;
547 	case EVENT_TYPE_ILL_CMD:
548 		dev_err(dev, "Event logged [ILLEGAL_COMMAND_ERROR address=0x%llx]\n", address);
549 		dump_command(address);
550 		break;
551 	case EVENT_TYPE_CMD_HARD_ERR:
552 		dev_err(dev, "Event logged [COMMAND_HARDWARE_ERROR address=0x%llx flags=0x%04x]\n",
553 			address, flags);
554 		break;
555 	case EVENT_TYPE_IOTLB_INV_TO:
556 		dev_err(dev, "Event logged [IOTLB_INV_TIMEOUT device=%02x:%02x.%x address=0x%llx]\n",
557 			PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
558 			address);
559 		break;
560 	case EVENT_TYPE_INV_DEV_REQ:
561 		dev_err(dev, "Event logged [INVALID_DEVICE_REQUEST device=%02x:%02x.%x pasid=0x%05x address=0x%llx flags=0x%04x]\n",
562 			PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
563 			pasid, address, flags);
564 		break;
565 	case EVENT_TYPE_RMP_FAULT:
566 		amd_iommu_report_rmp_fault(event);
567 		break;
568 	case EVENT_TYPE_RMP_HW_ERR:
569 		amd_iommu_report_rmp_hw_error(event);
570 		break;
571 	case EVENT_TYPE_INV_PPR_REQ:
572 		pasid = PPR_PASID(*((u64 *)__evt));
573 		tag = event[1] & 0x03FF;
574 		dev_err(dev, "Event logged [INVALID_PPR_REQUEST device=%02x:%02x.%x pasid=0x%05x address=0x%llx flags=0x%04x tag=0x%03x]\n",
575 			PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
576 			pasid, address, flags, tag);
577 		break;
578 	default:
579 		dev_err(dev, "Event logged [UNKNOWN event[0]=0x%08x event[1]=0x%08x event[2]=0x%08x event[3]=0x%08x\n",
580 			event[0], event[1], event[2], event[3]);
581 	}
582 
583 	memset(__evt, 0, 4 * sizeof(u32));
584 }
585 
586 static void iommu_poll_events(struct amd_iommu *iommu)
587 {
588 	u32 head, tail;
589 
590 	head = readl(iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
591 	tail = readl(iommu->mmio_base + MMIO_EVT_TAIL_OFFSET);
592 
593 	while (head != tail) {
594 		iommu_print_event(iommu, iommu->evt_buf + head);
595 		head = (head + EVENT_ENTRY_SIZE) % EVT_BUFFER_SIZE;
596 	}
597 
598 	writel(head, iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
599 }
600 
601 static void iommu_handle_ppr_entry(struct amd_iommu *iommu, u64 *raw)
602 {
603 	struct amd_iommu_fault fault;
604 
605 	if (PPR_REQ_TYPE(raw[0]) != PPR_REQ_FAULT) {
606 		pr_err_ratelimited("Unknown PPR request received\n");
607 		return;
608 	}
609 
610 	fault.address   = raw[1];
611 	fault.pasid     = PPR_PASID(raw[0]);
612 	fault.device_id = PPR_DEVID(raw[0]);
613 	fault.tag       = PPR_TAG(raw[0]);
614 	fault.flags     = PPR_FLAGS(raw[0]);
615 
616 	atomic_notifier_call_chain(&ppr_notifier, 0, &fault);
617 }
618 
619 static void iommu_poll_ppr_log(struct amd_iommu *iommu)
620 {
621 	u32 head, tail;
622 
623 	if (iommu->ppr_log == NULL)
624 		return;
625 
626 	head = readl(iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
627 	tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
628 
629 	while (head != tail) {
630 		volatile u64 *raw;
631 		u64 entry[2];
632 		int i;
633 
634 		raw = (u64 *)(iommu->ppr_log + head);
635 
636 		/*
637 		 * Hardware bug: Interrupt may arrive before the entry is
638 		 * written to memory. If this happens we need to wait for the
639 		 * entry to arrive.
640 		 */
641 		for (i = 0; i < LOOP_TIMEOUT; ++i) {
642 			if (PPR_REQ_TYPE(raw[0]) != 0)
643 				break;
644 			udelay(1);
645 		}
646 
647 		/* Avoid memcpy function-call overhead */
648 		entry[0] = raw[0];
649 		entry[1] = raw[1];
650 
651 		/*
652 		 * To detect the hardware bug we need to clear the entry
653 		 * back to zero.
654 		 */
655 		raw[0] = raw[1] = 0UL;
656 
657 		/* Update head pointer of hardware ring-buffer */
658 		head = (head + PPR_ENTRY_SIZE) % PPR_LOG_SIZE;
659 		writel(head, iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
660 
661 		/* Handle PPR entry */
662 		iommu_handle_ppr_entry(iommu, entry);
663 
664 		/* Refresh ring-buffer information */
665 		head = readl(iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
666 		tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
667 	}
668 }
669 
670 #ifdef CONFIG_IRQ_REMAP
671 static int (*iommu_ga_log_notifier)(u32);
672 
673 int amd_iommu_register_ga_log_notifier(int (*notifier)(u32))
674 {
675 	iommu_ga_log_notifier = notifier;
676 
677 	return 0;
678 }
679 EXPORT_SYMBOL(amd_iommu_register_ga_log_notifier);
680 
681 static void iommu_poll_ga_log(struct amd_iommu *iommu)
682 {
683 	u32 head, tail, cnt = 0;
684 
685 	if (iommu->ga_log == NULL)
686 		return;
687 
688 	head = readl(iommu->mmio_base + MMIO_GA_HEAD_OFFSET);
689 	tail = readl(iommu->mmio_base + MMIO_GA_TAIL_OFFSET);
690 
691 	while (head != tail) {
692 		volatile u64 *raw;
693 		u64 log_entry;
694 
695 		raw = (u64 *)(iommu->ga_log + head);
696 		cnt++;
697 
698 		/* Avoid memcpy function-call overhead */
699 		log_entry = *raw;
700 
701 		/* Update head pointer of hardware ring-buffer */
702 		head = (head + GA_ENTRY_SIZE) % GA_LOG_SIZE;
703 		writel(head, iommu->mmio_base + MMIO_GA_HEAD_OFFSET);
704 
705 		/* Handle GA entry */
706 		switch (GA_REQ_TYPE(log_entry)) {
707 		case GA_GUEST_NR:
708 			if (!iommu_ga_log_notifier)
709 				break;
710 
711 			pr_debug("%s: devid=%#x, ga_tag=%#x\n",
712 				 __func__, GA_DEVID(log_entry),
713 				 GA_TAG(log_entry));
714 
715 			if (iommu_ga_log_notifier(GA_TAG(log_entry)) != 0)
716 				pr_err("GA log notifier failed.\n");
717 			break;
718 		default:
719 			break;
720 		}
721 	}
722 }
723 
724 static void
725 amd_iommu_set_pci_msi_domain(struct device *dev, struct amd_iommu *iommu)
726 {
727 	if (!irq_remapping_enabled || !dev_is_pci(dev) ||
728 	    pci_dev_has_special_msi_domain(to_pci_dev(dev)))
729 		return;
730 
731 	dev_set_msi_domain(dev, iommu->msi_domain);
732 }
733 
734 #else /* CONFIG_IRQ_REMAP */
735 static inline void
736 amd_iommu_set_pci_msi_domain(struct device *dev, struct amd_iommu *iommu) { }
737 #endif /* !CONFIG_IRQ_REMAP */
738 
739 #define AMD_IOMMU_INT_MASK	\
740 	(MMIO_STATUS_EVT_INT_MASK | \
741 	 MMIO_STATUS_PPR_INT_MASK | \
742 	 MMIO_STATUS_GALOG_INT_MASK)
743 
744 irqreturn_t amd_iommu_int_thread(int irq, void *data)
745 {
746 	struct amd_iommu *iommu = (struct amd_iommu *) data;
747 	u32 status = readl(iommu->mmio_base + MMIO_STATUS_OFFSET);
748 
749 	while (status & AMD_IOMMU_INT_MASK) {
750 		/* Enable EVT and PPR and GA interrupts again */
751 		writel(AMD_IOMMU_INT_MASK,
752 			iommu->mmio_base + MMIO_STATUS_OFFSET);
753 
754 		if (status & MMIO_STATUS_EVT_INT_MASK) {
755 			pr_devel("Processing IOMMU Event Log\n");
756 			iommu_poll_events(iommu);
757 		}
758 
759 		if (status & MMIO_STATUS_PPR_INT_MASK) {
760 			pr_devel("Processing IOMMU PPR Log\n");
761 			iommu_poll_ppr_log(iommu);
762 		}
763 
764 #ifdef CONFIG_IRQ_REMAP
765 		if (status & MMIO_STATUS_GALOG_INT_MASK) {
766 			pr_devel("Processing IOMMU GA Log\n");
767 			iommu_poll_ga_log(iommu);
768 		}
769 #endif
770 
771 		/*
772 		 * Hardware bug: ERBT1312
773 		 * When re-enabling interrupt (by writing 1
774 		 * to clear the bit), the hardware might also try to set
775 		 * the interrupt bit in the event status register.
776 		 * In this scenario, the bit will be set, and disable
777 		 * subsequent interrupts.
778 		 *
779 		 * Workaround: The IOMMU driver should read back the
780 		 * status register and check if the interrupt bits are cleared.
781 		 * If not, driver will need to go through the interrupt handler
782 		 * again and re-clear the bits
783 		 */
784 		status = readl(iommu->mmio_base + MMIO_STATUS_OFFSET);
785 	}
786 	return IRQ_HANDLED;
787 }
788 
789 irqreturn_t amd_iommu_int_handler(int irq, void *data)
790 {
791 	return IRQ_WAKE_THREAD;
792 }
793 
794 /****************************************************************************
795  *
796  * IOMMU command queuing functions
797  *
798  ****************************************************************************/
799 
800 static int wait_on_sem(struct amd_iommu *iommu, u64 data)
801 {
802 	int i = 0;
803 
804 	while (*iommu->cmd_sem != data && i < LOOP_TIMEOUT) {
805 		udelay(1);
806 		i += 1;
807 	}
808 
809 	if (i == LOOP_TIMEOUT) {
810 		pr_alert("Completion-Wait loop timed out\n");
811 		return -EIO;
812 	}
813 
814 	return 0;
815 }
816 
817 static void copy_cmd_to_buffer(struct amd_iommu *iommu,
818 			       struct iommu_cmd *cmd)
819 {
820 	u8 *target;
821 	u32 tail;
822 
823 	/* Copy command to buffer */
824 	tail = iommu->cmd_buf_tail;
825 	target = iommu->cmd_buf + tail;
826 	memcpy(target, cmd, sizeof(*cmd));
827 
828 	tail = (tail + sizeof(*cmd)) % CMD_BUFFER_SIZE;
829 	iommu->cmd_buf_tail = tail;
830 
831 	/* Tell the IOMMU about it */
832 	writel(tail, iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
833 }
834 
835 static void build_completion_wait(struct iommu_cmd *cmd,
836 				  struct amd_iommu *iommu,
837 				  u64 data)
838 {
839 	u64 paddr = iommu_virt_to_phys((void *)iommu->cmd_sem);
840 
841 	memset(cmd, 0, sizeof(*cmd));
842 	cmd->data[0] = lower_32_bits(paddr) | CMD_COMPL_WAIT_STORE_MASK;
843 	cmd->data[1] = upper_32_bits(paddr);
844 	cmd->data[2] = data;
845 	CMD_SET_TYPE(cmd, CMD_COMPL_WAIT);
846 }
847 
848 static void build_inv_dte(struct iommu_cmd *cmd, u16 devid)
849 {
850 	memset(cmd, 0, sizeof(*cmd));
851 	cmd->data[0] = devid;
852 	CMD_SET_TYPE(cmd, CMD_INV_DEV_ENTRY);
853 }
854 
855 /*
856  * Builds an invalidation address which is suitable for one page or multiple
857  * pages. Sets the size bit (S) as needed is more than one page is flushed.
858  */
859 static inline u64 build_inv_address(u64 address, size_t size)
860 {
861 	u64 pages, end, msb_diff;
862 
863 	pages = iommu_num_pages(address, size, PAGE_SIZE);
864 
865 	if (pages == 1)
866 		return address & PAGE_MASK;
867 
868 	end = address + size - 1;
869 
870 	/*
871 	 * msb_diff would hold the index of the most significant bit that
872 	 * flipped between the start and end.
873 	 */
874 	msb_diff = fls64(end ^ address) - 1;
875 
876 	/*
877 	 * Bits 63:52 are sign extended. If for some reason bit 51 is different
878 	 * between the start and the end, invalidate everything.
879 	 */
880 	if (unlikely(msb_diff > 51)) {
881 		address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
882 	} else {
883 		/*
884 		 * The msb-bit must be clear on the address. Just set all the
885 		 * lower bits.
886 		 */
887 		address |= 1ull << (msb_diff - 1);
888 	}
889 
890 	/* Clear bits 11:0 */
891 	address &= PAGE_MASK;
892 
893 	/* Set the size bit - we flush more than one 4kb page */
894 	return address | CMD_INV_IOMMU_PAGES_SIZE_MASK;
895 }
896 
897 static void build_inv_iommu_pages(struct iommu_cmd *cmd, u64 address,
898 				  size_t size, u16 domid, int pde)
899 {
900 	u64 inv_address = build_inv_address(address, size);
901 
902 	memset(cmd, 0, sizeof(*cmd));
903 	cmd->data[1] |= domid;
904 	cmd->data[2]  = lower_32_bits(inv_address);
905 	cmd->data[3]  = upper_32_bits(inv_address);
906 	CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
907 	if (pde) /* PDE bit - we want to flush everything, not only the PTEs */
908 		cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
909 }
910 
911 static void build_inv_iotlb_pages(struct iommu_cmd *cmd, u16 devid, int qdep,
912 				  u64 address, size_t size)
913 {
914 	u64 inv_address = build_inv_address(address, size);
915 
916 	memset(cmd, 0, sizeof(*cmd));
917 	cmd->data[0]  = devid;
918 	cmd->data[0] |= (qdep & 0xff) << 24;
919 	cmd->data[1]  = devid;
920 	cmd->data[2]  = lower_32_bits(inv_address);
921 	cmd->data[3]  = upper_32_bits(inv_address);
922 	CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
923 }
924 
925 static void build_inv_iommu_pasid(struct iommu_cmd *cmd, u16 domid, u32 pasid,
926 				  u64 address, bool size)
927 {
928 	memset(cmd, 0, sizeof(*cmd));
929 
930 	address &= ~(0xfffULL);
931 
932 	cmd->data[0]  = pasid;
933 	cmd->data[1]  = domid;
934 	cmd->data[2]  = lower_32_bits(address);
935 	cmd->data[3]  = upper_32_bits(address);
936 	cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
937 	cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
938 	if (size)
939 		cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
940 	CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
941 }
942 
943 static void build_inv_iotlb_pasid(struct iommu_cmd *cmd, u16 devid, u32 pasid,
944 				  int qdep, u64 address, bool size)
945 {
946 	memset(cmd, 0, sizeof(*cmd));
947 
948 	address &= ~(0xfffULL);
949 
950 	cmd->data[0]  = devid;
951 	cmd->data[0] |= ((pasid >> 8) & 0xff) << 16;
952 	cmd->data[0] |= (qdep  & 0xff) << 24;
953 	cmd->data[1]  = devid;
954 	cmd->data[1] |= (pasid & 0xff) << 16;
955 	cmd->data[2]  = lower_32_bits(address);
956 	cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
957 	cmd->data[3]  = upper_32_bits(address);
958 	if (size)
959 		cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
960 	CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
961 }
962 
963 static void build_complete_ppr(struct iommu_cmd *cmd, u16 devid, u32 pasid,
964 			       int status, int tag, bool gn)
965 {
966 	memset(cmd, 0, sizeof(*cmd));
967 
968 	cmd->data[0]  = devid;
969 	if (gn) {
970 		cmd->data[1]  = pasid;
971 		cmd->data[2]  = CMD_INV_IOMMU_PAGES_GN_MASK;
972 	}
973 	cmd->data[3]  = tag & 0x1ff;
974 	cmd->data[3] |= (status & PPR_STATUS_MASK) << PPR_STATUS_SHIFT;
975 
976 	CMD_SET_TYPE(cmd, CMD_COMPLETE_PPR);
977 }
978 
979 static void build_inv_all(struct iommu_cmd *cmd)
980 {
981 	memset(cmd, 0, sizeof(*cmd));
982 	CMD_SET_TYPE(cmd, CMD_INV_ALL);
983 }
984 
985 static void build_inv_irt(struct iommu_cmd *cmd, u16 devid)
986 {
987 	memset(cmd, 0, sizeof(*cmd));
988 	cmd->data[0] = devid;
989 	CMD_SET_TYPE(cmd, CMD_INV_IRT);
990 }
991 
992 /*
993  * Writes the command to the IOMMUs command buffer and informs the
994  * hardware about the new command.
995  */
996 static int __iommu_queue_command_sync(struct amd_iommu *iommu,
997 				      struct iommu_cmd *cmd,
998 				      bool sync)
999 {
1000 	unsigned int count = 0;
1001 	u32 left, next_tail;
1002 
1003 	next_tail = (iommu->cmd_buf_tail + sizeof(*cmd)) % CMD_BUFFER_SIZE;
1004 again:
1005 	left      = (iommu->cmd_buf_head - next_tail) % CMD_BUFFER_SIZE;
1006 
1007 	if (left <= 0x20) {
1008 		/* Skip udelay() the first time around */
1009 		if (count++) {
1010 			if (count == LOOP_TIMEOUT) {
1011 				pr_err("Command buffer timeout\n");
1012 				return -EIO;
1013 			}
1014 
1015 			udelay(1);
1016 		}
1017 
1018 		/* Update head and recheck remaining space */
1019 		iommu->cmd_buf_head = readl(iommu->mmio_base +
1020 					    MMIO_CMD_HEAD_OFFSET);
1021 
1022 		goto again;
1023 	}
1024 
1025 	copy_cmd_to_buffer(iommu, cmd);
1026 
1027 	/* Do we need to make sure all commands are processed? */
1028 	iommu->need_sync = sync;
1029 
1030 	return 0;
1031 }
1032 
1033 static int iommu_queue_command_sync(struct amd_iommu *iommu,
1034 				    struct iommu_cmd *cmd,
1035 				    bool sync)
1036 {
1037 	unsigned long flags;
1038 	int ret;
1039 
1040 	raw_spin_lock_irqsave(&iommu->lock, flags);
1041 	ret = __iommu_queue_command_sync(iommu, cmd, sync);
1042 	raw_spin_unlock_irqrestore(&iommu->lock, flags);
1043 
1044 	return ret;
1045 }
1046 
1047 static int iommu_queue_command(struct amd_iommu *iommu, struct iommu_cmd *cmd)
1048 {
1049 	return iommu_queue_command_sync(iommu, cmd, true);
1050 }
1051 
1052 /*
1053  * This function queues a completion wait command into the command
1054  * buffer of an IOMMU
1055  */
1056 static int iommu_completion_wait(struct amd_iommu *iommu)
1057 {
1058 	struct iommu_cmd cmd;
1059 	unsigned long flags;
1060 	int ret;
1061 	u64 data;
1062 
1063 	if (!iommu->need_sync)
1064 		return 0;
1065 
1066 	raw_spin_lock_irqsave(&iommu->lock, flags);
1067 
1068 	data = ++iommu->cmd_sem_val;
1069 	build_completion_wait(&cmd, iommu, data);
1070 
1071 	ret = __iommu_queue_command_sync(iommu, &cmd, false);
1072 	if (ret)
1073 		goto out_unlock;
1074 
1075 	ret = wait_on_sem(iommu, data);
1076 
1077 out_unlock:
1078 	raw_spin_unlock_irqrestore(&iommu->lock, flags);
1079 
1080 	return ret;
1081 }
1082 
1083 static int iommu_flush_dte(struct amd_iommu *iommu, u16 devid)
1084 {
1085 	struct iommu_cmd cmd;
1086 
1087 	build_inv_dte(&cmd, devid);
1088 
1089 	return iommu_queue_command(iommu, &cmd);
1090 }
1091 
1092 static void amd_iommu_flush_dte_all(struct amd_iommu *iommu)
1093 {
1094 	u32 devid;
1095 
1096 	for (devid = 0; devid <= 0xffff; ++devid)
1097 		iommu_flush_dte(iommu, devid);
1098 
1099 	iommu_completion_wait(iommu);
1100 }
1101 
1102 /*
1103  * This function uses heavy locking and may disable irqs for some time. But
1104  * this is no issue because it is only called during resume.
1105  */
1106 static void amd_iommu_flush_tlb_all(struct amd_iommu *iommu)
1107 {
1108 	u32 dom_id;
1109 
1110 	for (dom_id = 0; dom_id <= 0xffff; ++dom_id) {
1111 		struct iommu_cmd cmd;
1112 		build_inv_iommu_pages(&cmd, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
1113 				      dom_id, 1);
1114 		iommu_queue_command(iommu, &cmd);
1115 	}
1116 
1117 	iommu_completion_wait(iommu);
1118 }
1119 
1120 static void amd_iommu_flush_tlb_domid(struct amd_iommu *iommu, u32 dom_id)
1121 {
1122 	struct iommu_cmd cmd;
1123 
1124 	build_inv_iommu_pages(&cmd, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
1125 			      dom_id, 1);
1126 	iommu_queue_command(iommu, &cmd);
1127 
1128 	iommu_completion_wait(iommu);
1129 }
1130 
1131 static void amd_iommu_flush_all(struct amd_iommu *iommu)
1132 {
1133 	struct iommu_cmd cmd;
1134 
1135 	build_inv_all(&cmd);
1136 
1137 	iommu_queue_command(iommu, &cmd);
1138 	iommu_completion_wait(iommu);
1139 }
1140 
1141 static void iommu_flush_irt(struct amd_iommu *iommu, u16 devid)
1142 {
1143 	struct iommu_cmd cmd;
1144 
1145 	build_inv_irt(&cmd, devid);
1146 
1147 	iommu_queue_command(iommu, &cmd);
1148 }
1149 
1150 static void amd_iommu_flush_irt_all(struct amd_iommu *iommu)
1151 {
1152 	u32 devid;
1153 
1154 	for (devid = 0; devid <= MAX_DEV_TABLE_ENTRIES; devid++)
1155 		iommu_flush_irt(iommu, devid);
1156 
1157 	iommu_completion_wait(iommu);
1158 }
1159 
1160 void iommu_flush_all_caches(struct amd_iommu *iommu)
1161 {
1162 	if (iommu_feature(iommu, FEATURE_IA)) {
1163 		amd_iommu_flush_all(iommu);
1164 	} else {
1165 		amd_iommu_flush_dte_all(iommu);
1166 		amd_iommu_flush_irt_all(iommu);
1167 		amd_iommu_flush_tlb_all(iommu);
1168 	}
1169 }
1170 
1171 /*
1172  * Command send function for flushing on-device TLB
1173  */
1174 static int device_flush_iotlb(struct iommu_dev_data *dev_data,
1175 			      u64 address, size_t size)
1176 {
1177 	struct amd_iommu *iommu;
1178 	struct iommu_cmd cmd;
1179 	int qdep;
1180 
1181 	qdep     = dev_data->ats.qdep;
1182 	iommu    = amd_iommu_rlookup_table[dev_data->devid];
1183 
1184 	build_inv_iotlb_pages(&cmd, dev_data->devid, qdep, address, size);
1185 
1186 	return iommu_queue_command(iommu, &cmd);
1187 }
1188 
1189 static int device_flush_dte_alias(struct pci_dev *pdev, u16 alias, void *data)
1190 {
1191 	struct amd_iommu *iommu = data;
1192 
1193 	return iommu_flush_dte(iommu, alias);
1194 }
1195 
1196 /*
1197  * Command send function for invalidating a device table entry
1198  */
1199 static int device_flush_dte(struct iommu_dev_data *dev_data)
1200 {
1201 	struct amd_iommu *iommu;
1202 	u16 alias;
1203 	int ret;
1204 
1205 	iommu = amd_iommu_rlookup_table[dev_data->devid];
1206 
1207 	if (dev_data->pdev)
1208 		ret = pci_for_each_dma_alias(dev_data->pdev,
1209 					     device_flush_dte_alias, iommu);
1210 	else
1211 		ret = iommu_flush_dte(iommu, dev_data->devid);
1212 	if (ret)
1213 		return ret;
1214 
1215 	alias = amd_iommu_alias_table[dev_data->devid];
1216 	if (alias != dev_data->devid) {
1217 		ret = iommu_flush_dte(iommu, alias);
1218 		if (ret)
1219 			return ret;
1220 	}
1221 
1222 	if (dev_data->ats.enabled)
1223 		ret = device_flush_iotlb(dev_data, 0, ~0UL);
1224 
1225 	return ret;
1226 }
1227 
1228 /*
1229  * TLB invalidation function which is called from the mapping functions.
1230  * It invalidates a single PTE if the range to flush is within a single
1231  * page. Otherwise it flushes the whole TLB of the IOMMU.
1232  */
1233 static void __domain_flush_pages(struct protection_domain *domain,
1234 				 u64 address, size_t size, int pde)
1235 {
1236 	struct iommu_dev_data *dev_data;
1237 	struct iommu_cmd cmd;
1238 	int ret = 0, i;
1239 
1240 	build_inv_iommu_pages(&cmd, address, size, domain->id, pde);
1241 
1242 	for (i = 0; i < amd_iommu_get_num_iommus(); ++i) {
1243 		if (!domain->dev_iommu[i])
1244 			continue;
1245 
1246 		/*
1247 		 * Devices of this domain are behind this IOMMU
1248 		 * We need a TLB flush
1249 		 */
1250 		ret |= iommu_queue_command(amd_iommus[i], &cmd);
1251 	}
1252 
1253 	list_for_each_entry(dev_data, &domain->dev_list, list) {
1254 
1255 		if (!dev_data->ats.enabled)
1256 			continue;
1257 
1258 		ret |= device_flush_iotlb(dev_data, address, size);
1259 	}
1260 
1261 	WARN_ON(ret);
1262 }
1263 
1264 static void domain_flush_pages(struct protection_domain *domain,
1265 			       u64 address, size_t size)
1266 {
1267 	__domain_flush_pages(domain, address, size, 0);
1268 }
1269 
1270 /* Flush the whole IO/TLB for a given protection domain - including PDE */
1271 void amd_iommu_domain_flush_tlb_pde(struct protection_domain *domain)
1272 {
1273 	__domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 1);
1274 }
1275 
1276 void amd_iommu_domain_flush_complete(struct protection_domain *domain)
1277 {
1278 	int i;
1279 
1280 	for (i = 0; i < amd_iommu_get_num_iommus(); ++i) {
1281 		if (domain && !domain->dev_iommu[i])
1282 			continue;
1283 
1284 		/*
1285 		 * Devices of this domain are behind this IOMMU
1286 		 * We need to wait for completion of all commands.
1287 		 */
1288 		iommu_completion_wait(amd_iommus[i]);
1289 	}
1290 }
1291 
1292 /* Flush the not present cache if it exists */
1293 static void domain_flush_np_cache(struct protection_domain *domain,
1294 		dma_addr_t iova, size_t size)
1295 {
1296 	if (unlikely(amd_iommu_np_cache)) {
1297 		unsigned long flags;
1298 
1299 		spin_lock_irqsave(&domain->lock, flags);
1300 		domain_flush_pages(domain, iova, size);
1301 		amd_iommu_domain_flush_complete(domain);
1302 		spin_unlock_irqrestore(&domain->lock, flags);
1303 	}
1304 }
1305 
1306 
1307 /*
1308  * This function flushes the DTEs for all devices in domain
1309  */
1310 static void domain_flush_devices(struct protection_domain *domain)
1311 {
1312 	struct iommu_dev_data *dev_data;
1313 
1314 	list_for_each_entry(dev_data, &domain->dev_list, list)
1315 		device_flush_dte(dev_data);
1316 }
1317 
1318 /****************************************************************************
1319  *
1320  * The next functions belong to the domain allocation. A domain is
1321  * allocated for every IOMMU as the default domain. If device isolation
1322  * is enabled, every device get its own domain. The most important thing
1323  * about domains is the page table mapping the DMA address space they
1324  * contain.
1325  *
1326  ****************************************************************************/
1327 
1328 static u16 domain_id_alloc(void)
1329 {
1330 	int id;
1331 
1332 	spin_lock(&pd_bitmap_lock);
1333 	id = find_first_zero_bit(amd_iommu_pd_alloc_bitmap, MAX_DOMAIN_ID);
1334 	BUG_ON(id == 0);
1335 	if (id > 0 && id < MAX_DOMAIN_ID)
1336 		__set_bit(id, amd_iommu_pd_alloc_bitmap);
1337 	else
1338 		id = 0;
1339 	spin_unlock(&pd_bitmap_lock);
1340 
1341 	return id;
1342 }
1343 
1344 static void domain_id_free(int id)
1345 {
1346 	spin_lock(&pd_bitmap_lock);
1347 	if (id > 0 && id < MAX_DOMAIN_ID)
1348 		__clear_bit(id, amd_iommu_pd_alloc_bitmap);
1349 	spin_unlock(&pd_bitmap_lock);
1350 }
1351 
1352 static void free_gcr3_tbl_level1(u64 *tbl)
1353 {
1354 	u64 *ptr;
1355 	int i;
1356 
1357 	for (i = 0; i < 512; ++i) {
1358 		if (!(tbl[i] & GCR3_VALID))
1359 			continue;
1360 
1361 		ptr = iommu_phys_to_virt(tbl[i] & PAGE_MASK);
1362 
1363 		free_page((unsigned long)ptr);
1364 	}
1365 }
1366 
1367 static void free_gcr3_tbl_level2(u64 *tbl)
1368 {
1369 	u64 *ptr;
1370 	int i;
1371 
1372 	for (i = 0; i < 512; ++i) {
1373 		if (!(tbl[i] & GCR3_VALID))
1374 			continue;
1375 
1376 		ptr = iommu_phys_to_virt(tbl[i] & PAGE_MASK);
1377 
1378 		free_gcr3_tbl_level1(ptr);
1379 	}
1380 }
1381 
1382 static void free_gcr3_table(struct protection_domain *domain)
1383 {
1384 	if (domain->glx == 2)
1385 		free_gcr3_tbl_level2(domain->gcr3_tbl);
1386 	else if (domain->glx == 1)
1387 		free_gcr3_tbl_level1(domain->gcr3_tbl);
1388 	else
1389 		BUG_ON(domain->glx != 0);
1390 
1391 	free_page((unsigned long)domain->gcr3_tbl);
1392 }
1393 
1394 static void set_dte_entry(u16 devid, struct protection_domain *domain,
1395 			  bool ats, bool ppr)
1396 {
1397 	u64 pte_root = 0;
1398 	u64 flags = 0;
1399 	u32 old_domid;
1400 
1401 	if (domain->iop.mode != PAGE_MODE_NONE)
1402 		pte_root = iommu_virt_to_phys(domain->iop.root);
1403 
1404 	pte_root |= (domain->iop.mode & DEV_ENTRY_MODE_MASK)
1405 		    << DEV_ENTRY_MODE_SHIFT;
1406 	pte_root |= DTE_FLAG_IR | DTE_FLAG_IW | DTE_FLAG_V | DTE_FLAG_TV;
1407 
1408 	flags = amd_iommu_dev_table[devid].data[1];
1409 
1410 	if (ats)
1411 		flags |= DTE_FLAG_IOTLB;
1412 
1413 	if (ppr) {
1414 		struct amd_iommu *iommu = amd_iommu_rlookup_table[devid];
1415 
1416 		if (iommu_feature(iommu, FEATURE_EPHSUP))
1417 			pte_root |= 1ULL << DEV_ENTRY_PPR;
1418 	}
1419 
1420 	if (domain->flags & PD_IOMMUV2_MASK) {
1421 		u64 gcr3 = iommu_virt_to_phys(domain->gcr3_tbl);
1422 		u64 glx  = domain->glx;
1423 		u64 tmp;
1424 
1425 		pte_root |= DTE_FLAG_GV;
1426 		pte_root |= (glx & DTE_GLX_MASK) << DTE_GLX_SHIFT;
1427 
1428 		/* First mask out possible old values for GCR3 table */
1429 		tmp = DTE_GCR3_VAL_B(~0ULL) << DTE_GCR3_SHIFT_B;
1430 		flags    &= ~tmp;
1431 
1432 		tmp = DTE_GCR3_VAL_C(~0ULL) << DTE_GCR3_SHIFT_C;
1433 		flags    &= ~tmp;
1434 
1435 		/* Encode GCR3 table into DTE */
1436 		tmp = DTE_GCR3_VAL_A(gcr3) << DTE_GCR3_SHIFT_A;
1437 		pte_root |= tmp;
1438 
1439 		tmp = DTE_GCR3_VAL_B(gcr3) << DTE_GCR3_SHIFT_B;
1440 		flags    |= tmp;
1441 
1442 		tmp = DTE_GCR3_VAL_C(gcr3) << DTE_GCR3_SHIFT_C;
1443 		flags    |= tmp;
1444 	}
1445 
1446 	flags &= ~DEV_DOMID_MASK;
1447 	flags |= domain->id;
1448 
1449 	old_domid = amd_iommu_dev_table[devid].data[1] & DEV_DOMID_MASK;
1450 	amd_iommu_dev_table[devid].data[1]  = flags;
1451 	amd_iommu_dev_table[devid].data[0]  = pte_root;
1452 
1453 	/*
1454 	 * A kdump kernel might be replacing a domain ID that was copied from
1455 	 * the previous kernel--if so, it needs to flush the translation cache
1456 	 * entries for the old domain ID that is being overwritten
1457 	 */
1458 	if (old_domid) {
1459 		struct amd_iommu *iommu = amd_iommu_rlookup_table[devid];
1460 
1461 		amd_iommu_flush_tlb_domid(iommu, old_domid);
1462 	}
1463 }
1464 
1465 static void clear_dte_entry(u16 devid)
1466 {
1467 	/* remove entry from the device table seen by the hardware */
1468 	amd_iommu_dev_table[devid].data[0]  = DTE_FLAG_V | DTE_FLAG_TV;
1469 	amd_iommu_dev_table[devid].data[1] &= DTE_FLAG_MASK;
1470 
1471 	amd_iommu_apply_erratum_63(devid);
1472 }
1473 
1474 static void do_attach(struct iommu_dev_data *dev_data,
1475 		      struct protection_domain *domain)
1476 {
1477 	struct amd_iommu *iommu;
1478 	bool ats;
1479 
1480 	iommu = amd_iommu_rlookup_table[dev_data->devid];
1481 	ats   = dev_data->ats.enabled;
1482 
1483 	/* Update data structures */
1484 	dev_data->domain = domain;
1485 	list_add(&dev_data->list, &domain->dev_list);
1486 
1487 	/* Do reference counting */
1488 	domain->dev_iommu[iommu->index] += 1;
1489 	domain->dev_cnt                 += 1;
1490 
1491 	/* Update device table */
1492 	set_dte_entry(dev_data->devid, domain,
1493 		      ats, dev_data->iommu_v2);
1494 	clone_aliases(dev_data->pdev);
1495 
1496 	device_flush_dte(dev_data);
1497 }
1498 
1499 static void do_detach(struct iommu_dev_data *dev_data)
1500 {
1501 	struct protection_domain *domain = dev_data->domain;
1502 	struct amd_iommu *iommu;
1503 
1504 	iommu = amd_iommu_rlookup_table[dev_data->devid];
1505 
1506 	/* Update data structures */
1507 	dev_data->domain = NULL;
1508 	list_del(&dev_data->list);
1509 	clear_dte_entry(dev_data->devid);
1510 	clone_aliases(dev_data->pdev);
1511 
1512 	/* Flush the DTE entry */
1513 	device_flush_dte(dev_data);
1514 
1515 	/* Flush IOTLB */
1516 	amd_iommu_domain_flush_tlb_pde(domain);
1517 
1518 	/* Wait for the flushes to finish */
1519 	amd_iommu_domain_flush_complete(domain);
1520 
1521 	/* decrease reference counters - needs to happen after the flushes */
1522 	domain->dev_iommu[iommu->index] -= 1;
1523 	domain->dev_cnt                 -= 1;
1524 }
1525 
1526 static void pdev_iommuv2_disable(struct pci_dev *pdev)
1527 {
1528 	pci_disable_ats(pdev);
1529 	pci_disable_pri(pdev);
1530 	pci_disable_pasid(pdev);
1531 }
1532 
1533 static int pdev_iommuv2_enable(struct pci_dev *pdev)
1534 {
1535 	int ret;
1536 
1537 	/* Only allow access to user-accessible pages */
1538 	ret = pci_enable_pasid(pdev, 0);
1539 	if (ret)
1540 		goto out_err;
1541 
1542 	/* First reset the PRI state of the device */
1543 	ret = pci_reset_pri(pdev);
1544 	if (ret)
1545 		goto out_err;
1546 
1547 	/* Enable PRI */
1548 	/* FIXME: Hardcode number of outstanding requests for now */
1549 	ret = pci_enable_pri(pdev, 32);
1550 	if (ret)
1551 		goto out_err;
1552 
1553 	ret = pci_enable_ats(pdev, PAGE_SHIFT);
1554 	if (ret)
1555 		goto out_err;
1556 
1557 	return 0;
1558 
1559 out_err:
1560 	pci_disable_pri(pdev);
1561 	pci_disable_pasid(pdev);
1562 
1563 	return ret;
1564 }
1565 
1566 /*
1567  * If a device is not yet associated with a domain, this function makes the
1568  * device visible in the domain
1569  */
1570 static int attach_device(struct device *dev,
1571 			 struct protection_domain *domain)
1572 {
1573 	struct iommu_dev_data *dev_data;
1574 	struct pci_dev *pdev;
1575 	unsigned long flags;
1576 	int ret;
1577 
1578 	spin_lock_irqsave(&domain->lock, flags);
1579 
1580 	dev_data = dev_iommu_priv_get(dev);
1581 
1582 	spin_lock(&dev_data->lock);
1583 
1584 	ret = -EBUSY;
1585 	if (dev_data->domain != NULL)
1586 		goto out;
1587 
1588 	if (!dev_is_pci(dev))
1589 		goto skip_ats_check;
1590 
1591 	pdev = to_pci_dev(dev);
1592 	if (domain->flags & PD_IOMMUV2_MASK) {
1593 		struct iommu_domain *def_domain = iommu_get_dma_domain(dev);
1594 
1595 		ret = -EINVAL;
1596 		if (def_domain->type != IOMMU_DOMAIN_IDENTITY)
1597 			goto out;
1598 
1599 		if (dev_data->iommu_v2) {
1600 			if (pdev_iommuv2_enable(pdev) != 0)
1601 				goto out;
1602 
1603 			dev_data->ats.enabled = true;
1604 			dev_data->ats.qdep    = pci_ats_queue_depth(pdev);
1605 			dev_data->pri_tlp     = pci_prg_resp_pasid_required(pdev);
1606 		}
1607 	} else if (amd_iommu_iotlb_sup &&
1608 		   pci_enable_ats(pdev, PAGE_SHIFT) == 0) {
1609 		dev_data->ats.enabled = true;
1610 		dev_data->ats.qdep    = pci_ats_queue_depth(pdev);
1611 	}
1612 
1613 skip_ats_check:
1614 	ret = 0;
1615 
1616 	do_attach(dev_data, domain);
1617 
1618 	/*
1619 	 * We might boot into a crash-kernel here. The crashed kernel
1620 	 * left the caches in the IOMMU dirty. So we have to flush
1621 	 * here to evict all dirty stuff.
1622 	 */
1623 	amd_iommu_domain_flush_tlb_pde(domain);
1624 
1625 	amd_iommu_domain_flush_complete(domain);
1626 
1627 out:
1628 	spin_unlock(&dev_data->lock);
1629 
1630 	spin_unlock_irqrestore(&domain->lock, flags);
1631 
1632 	return ret;
1633 }
1634 
1635 /*
1636  * Removes a device from a protection domain (with devtable_lock held)
1637  */
1638 static void detach_device(struct device *dev)
1639 {
1640 	struct protection_domain *domain;
1641 	struct iommu_dev_data *dev_data;
1642 	unsigned long flags;
1643 
1644 	dev_data = dev_iommu_priv_get(dev);
1645 	domain   = dev_data->domain;
1646 
1647 	spin_lock_irqsave(&domain->lock, flags);
1648 
1649 	spin_lock(&dev_data->lock);
1650 
1651 	/*
1652 	 * First check if the device is still attached. It might already
1653 	 * be detached from its domain because the generic
1654 	 * iommu_detach_group code detached it and we try again here in
1655 	 * our alias handling.
1656 	 */
1657 	if (WARN_ON(!dev_data->domain))
1658 		goto out;
1659 
1660 	do_detach(dev_data);
1661 
1662 	if (!dev_is_pci(dev))
1663 		goto out;
1664 
1665 	if (domain->flags & PD_IOMMUV2_MASK && dev_data->iommu_v2)
1666 		pdev_iommuv2_disable(to_pci_dev(dev));
1667 	else if (dev_data->ats.enabled)
1668 		pci_disable_ats(to_pci_dev(dev));
1669 
1670 	dev_data->ats.enabled = false;
1671 
1672 out:
1673 	spin_unlock(&dev_data->lock);
1674 
1675 	spin_unlock_irqrestore(&domain->lock, flags);
1676 }
1677 
1678 static struct iommu_device *amd_iommu_probe_device(struct device *dev)
1679 {
1680 	struct iommu_device *iommu_dev;
1681 	struct amd_iommu *iommu;
1682 	int ret, devid;
1683 
1684 	if (!check_device(dev))
1685 		return ERR_PTR(-ENODEV);
1686 
1687 	devid = get_device_id(dev);
1688 	iommu = amd_iommu_rlookup_table[devid];
1689 
1690 	if (dev_iommu_priv_get(dev))
1691 		return &iommu->iommu;
1692 
1693 	ret = iommu_init_device(dev);
1694 	if (ret) {
1695 		if (ret != -ENOTSUPP)
1696 			dev_err(dev, "Failed to initialize - trying to proceed anyway\n");
1697 		iommu_dev = ERR_PTR(ret);
1698 		iommu_ignore_device(dev);
1699 	} else {
1700 		amd_iommu_set_pci_msi_domain(dev, iommu);
1701 		iommu_dev = &iommu->iommu;
1702 	}
1703 
1704 	iommu_completion_wait(iommu);
1705 
1706 	return iommu_dev;
1707 }
1708 
1709 static void amd_iommu_probe_finalize(struct device *dev)
1710 {
1711 	struct iommu_domain *domain;
1712 
1713 	/* Domains are initialized for this device - have a look what we ended up with */
1714 	domain = iommu_get_domain_for_dev(dev);
1715 	if (domain->type == IOMMU_DOMAIN_DMA)
1716 		iommu_setup_dma_ops(dev, IOVA_START_PFN << PAGE_SHIFT, 0);
1717 }
1718 
1719 static void amd_iommu_release_device(struct device *dev)
1720 {
1721 	int devid = get_device_id(dev);
1722 	struct amd_iommu *iommu;
1723 
1724 	if (!check_device(dev))
1725 		return;
1726 
1727 	iommu = amd_iommu_rlookup_table[devid];
1728 
1729 	amd_iommu_uninit_device(dev);
1730 	iommu_completion_wait(iommu);
1731 }
1732 
1733 static struct iommu_group *amd_iommu_device_group(struct device *dev)
1734 {
1735 	if (dev_is_pci(dev))
1736 		return pci_device_group(dev);
1737 
1738 	return acpihid_device_group(dev);
1739 }
1740 
1741 /*****************************************************************************
1742  *
1743  * The next functions belong to the dma_ops mapping/unmapping code.
1744  *
1745  *****************************************************************************/
1746 
1747 static void update_device_table(struct protection_domain *domain)
1748 {
1749 	struct iommu_dev_data *dev_data;
1750 
1751 	list_for_each_entry(dev_data, &domain->dev_list, list) {
1752 		set_dte_entry(dev_data->devid, domain,
1753 			      dev_data->ats.enabled, dev_data->iommu_v2);
1754 		clone_aliases(dev_data->pdev);
1755 	}
1756 }
1757 
1758 void amd_iommu_update_and_flush_device_table(struct protection_domain *domain)
1759 {
1760 	update_device_table(domain);
1761 	domain_flush_devices(domain);
1762 }
1763 
1764 void amd_iommu_domain_update(struct protection_domain *domain)
1765 {
1766 	/* Update device table */
1767 	amd_iommu_update_and_flush_device_table(domain);
1768 
1769 	/* Flush domain TLB(s) and wait for completion */
1770 	amd_iommu_domain_flush_tlb_pde(domain);
1771 	amd_iommu_domain_flush_complete(domain);
1772 }
1773 
1774 int __init amd_iommu_init_api(void)
1775 {
1776 	int ret, err = 0;
1777 
1778 	ret = iova_cache_get();
1779 	if (ret)
1780 		return ret;
1781 
1782 	err = bus_set_iommu(&pci_bus_type, &amd_iommu_ops);
1783 	if (err)
1784 		return err;
1785 #ifdef CONFIG_ARM_AMBA
1786 	err = bus_set_iommu(&amba_bustype, &amd_iommu_ops);
1787 	if (err)
1788 		return err;
1789 #endif
1790 	err = bus_set_iommu(&platform_bus_type, &amd_iommu_ops);
1791 	if (err)
1792 		return err;
1793 
1794 	return 0;
1795 }
1796 
1797 int __init amd_iommu_init_dma_ops(void)
1798 {
1799 	swiotlb        = (iommu_default_passthrough() || sme_me_mask) ? 1 : 0;
1800 
1801 	if (amd_iommu_unmap_flush)
1802 		pr_info("IO/TLB flush on unmap enabled\n");
1803 	else
1804 		pr_info("Lazy IO/TLB flushing enabled\n");
1805 	iommu_set_dma_strict(amd_iommu_unmap_flush);
1806 	return 0;
1807 
1808 }
1809 
1810 /*****************************************************************************
1811  *
1812  * The following functions belong to the exported interface of AMD IOMMU
1813  *
1814  * This interface allows access to lower level functions of the IOMMU
1815  * like protection domain handling and assignement of devices to domains
1816  * which is not possible with the dma_ops interface.
1817  *
1818  *****************************************************************************/
1819 
1820 static void cleanup_domain(struct protection_domain *domain)
1821 {
1822 	struct iommu_dev_data *entry;
1823 	unsigned long flags;
1824 
1825 	spin_lock_irqsave(&domain->lock, flags);
1826 
1827 	while (!list_empty(&domain->dev_list)) {
1828 		entry = list_first_entry(&domain->dev_list,
1829 					 struct iommu_dev_data, list);
1830 		BUG_ON(!entry->domain);
1831 		do_detach(entry);
1832 	}
1833 
1834 	spin_unlock_irqrestore(&domain->lock, flags);
1835 }
1836 
1837 static void protection_domain_free(struct protection_domain *domain)
1838 {
1839 	if (!domain)
1840 		return;
1841 
1842 	if (domain->id)
1843 		domain_id_free(domain->id);
1844 
1845 	if (domain->iop.pgtbl_cfg.tlb)
1846 		free_io_pgtable_ops(&domain->iop.iop.ops);
1847 
1848 	kfree(domain);
1849 }
1850 
1851 static int protection_domain_init_v1(struct protection_domain *domain, int mode)
1852 {
1853 	u64 *pt_root = NULL;
1854 
1855 	BUG_ON(mode < PAGE_MODE_NONE || mode > PAGE_MODE_6_LEVEL);
1856 
1857 	spin_lock_init(&domain->lock);
1858 	domain->id = domain_id_alloc();
1859 	if (!domain->id)
1860 		return -ENOMEM;
1861 	INIT_LIST_HEAD(&domain->dev_list);
1862 
1863 	if (mode != PAGE_MODE_NONE) {
1864 		pt_root = (void *)get_zeroed_page(GFP_KERNEL);
1865 		if (!pt_root)
1866 			return -ENOMEM;
1867 	}
1868 
1869 	amd_iommu_domain_set_pgtable(domain, pt_root, mode);
1870 
1871 	return 0;
1872 }
1873 
1874 static struct protection_domain *protection_domain_alloc(unsigned int type)
1875 {
1876 	struct io_pgtable_ops *pgtbl_ops;
1877 	struct protection_domain *domain;
1878 	int pgtable = amd_iommu_pgtable;
1879 	int mode = DEFAULT_PGTABLE_LEVEL;
1880 	int ret;
1881 
1882 	domain = kzalloc(sizeof(*domain), GFP_KERNEL);
1883 	if (!domain)
1884 		return NULL;
1885 
1886 	/*
1887 	 * Force IOMMU v1 page table when iommu=pt and
1888 	 * when allocating domain for pass-through devices.
1889 	 */
1890 	if (type == IOMMU_DOMAIN_IDENTITY) {
1891 		pgtable = AMD_IOMMU_V1;
1892 		mode = PAGE_MODE_NONE;
1893 	} else if (type == IOMMU_DOMAIN_UNMANAGED) {
1894 		pgtable = AMD_IOMMU_V1;
1895 	}
1896 
1897 	switch (pgtable) {
1898 	case AMD_IOMMU_V1:
1899 		ret = protection_domain_init_v1(domain, mode);
1900 		break;
1901 	default:
1902 		ret = -EINVAL;
1903 	}
1904 
1905 	if (ret)
1906 		goto out_err;
1907 
1908 	pgtbl_ops = alloc_io_pgtable_ops(pgtable, &domain->iop.pgtbl_cfg, domain);
1909 	if (!pgtbl_ops)
1910 		goto out_err;
1911 
1912 	return domain;
1913 out_err:
1914 	kfree(domain);
1915 	return NULL;
1916 }
1917 
1918 static struct iommu_domain *amd_iommu_domain_alloc(unsigned type)
1919 {
1920 	struct protection_domain *domain;
1921 
1922 	domain = protection_domain_alloc(type);
1923 	if (!domain)
1924 		return NULL;
1925 
1926 	domain->domain.geometry.aperture_start = 0;
1927 	domain->domain.geometry.aperture_end   = ~0ULL;
1928 	domain->domain.geometry.force_aperture = true;
1929 
1930 	if (type == IOMMU_DOMAIN_DMA &&
1931 	    iommu_get_dma_cookie(&domain->domain) == -ENOMEM)
1932 		goto free_domain;
1933 
1934 	return &domain->domain;
1935 
1936 free_domain:
1937 	protection_domain_free(domain);
1938 
1939 	return NULL;
1940 }
1941 
1942 static void amd_iommu_domain_free(struct iommu_domain *dom)
1943 {
1944 	struct protection_domain *domain;
1945 
1946 	domain = to_pdomain(dom);
1947 
1948 	if (domain->dev_cnt > 0)
1949 		cleanup_domain(domain);
1950 
1951 	BUG_ON(domain->dev_cnt != 0);
1952 
1953 	if (!dom)
1954 		return;
1955 
1956 	if (dom->type == IOMMU_DOMAIN_DMA)
1957 		iommu_put_dma_cookie(&domain->domain);
1958 
1959 	if (domain->flags & PD_IOMMUV2_MASK)
1960 		free_gcr3_table(domain);
1961 
1962 	protection_domain_free(domain);
1963 }
1964 
1965 static void amd_iommu_detach_device(struct iommu_domain *dom,
1966 				    struct device *dev)
1967 {
1968 	struct iommu_dev_data *dev_data = dev_iommu_priv_get(dev);
1969 	int devid = get_device_id(dev);
1970 	struct amd_iommu *iommu;
1971 
1972 	if (!check_device(dev))
1973 		return;
1974 
1975 	if (dev_data->domain != NULL)
1976 		detach_device(dev);
1977 
1978 	iommu = amd_iommu_rlookup_table[devid];
1979 	if (!iommu)
1980 		return;
1981 
1982 #ifdef CONFIG_IRQ_REMAP
1983 	if (AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir) &&
1984 	    (dom->type == IOMMU_DOMAIN_UNMANAGED))
1985 		dev_data->use_vapic = 0;
1986 #endif
1987 
1988 	iommu_completion_wait(iommu);
1989 }
1990 
1991 static int amd_iommu_attach_device(struct iommu_domain *dom,
1992 				   struct device *dev)
1993 {
1994 	struct protection_domain *domain = to_pdomain(dom);
1995 	struct iommu_dev_data *dev_data;
1996 	struct amd_iommu *iommu;
1997 	int ret;
1998 
1999 	if (!check_device(dev))
2000 		return -EINVAL;
2001 
2002 	dev_data = dev_iommu_priv_get(dev);
2003 	dev_data->defer_attach = false;
2004 
2005 	iommu = amd_iommu_rlookup_table[dev_data->devid];
2006 	if (!iommu)
2007 		return -EINVAL;
2008 
2009 	if (dev_data->domain)
2010 		detach_device(dev);
2011 
2012 	ret = attach_device(dev, domain);
2013 
2014 #ifdef CONFIG_IRQ_REMAP
2015 	if (AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir)) {
2016 		if (dom->type == IOMMU_DOMAIN_UNMANAGED)
2017 			dev_data->use_vapic = 1;
2018 		else
2019 			dev_data->use_vapic = 0;
2020 	}
2021 #endif
2022 
2023 	iommu_completion_wait(iommu);
2024 
2025 	return ret;
2026 }
2027 
2028 static int amd_iommu_map(struct iommu_domain *dom, unsigned long iova,
2029 			 phys_addr_t paddr, size_t page_size, int iommu_prot,
2030 			 gfp_t gfp)
2031 {
2032 	struct protection_domain *domain = to_pdomain(dom);
2033 	struct io_pgtable_ops *ops = &domain->iop.iop.ops;
2034 	int prot = 0;
2035 	int ret = -EINVAL;
2036 
2037 	if ((amd_iommu_pgtable == AMD_IOMMU_V1) &&
2038 	    (domain->iop.mode == PAGE_MODE_NONE))
2039 		return -EINVAL;
2040 
2041 	if (iommu_prot & IOMMU_READ)
2042 		prot |= IOMMU_PROT_IR;
2043 	if (iommu_prot & IOMMU_WRITE)
2044 		prot |= IOMMU_PROT_IW;
2045 
2046 	if (ops->map) {
2047 		ret = ops->map(ops, iova, paddr, page_size, prot, gfp);
2048 		domain_flush_np_cache(domain, iova, page_size);
2049 	}
2050 
2051 	return ret;
2052 }
2053 
2054 static size_t amd_iommu_unmap(struct iommu_domain *dom, unsigned long iova,
2055 			      size_t page_size,
2056 			      struct iommu_iotlb_gather *gather)
2057 {
2058 	struct protection_domain *domain = to_pdomain(dom);
2059 	struct io_pgtable_ops *ops = &domain->iop.iop.ops;
2060 
2061 	if ((amd_iommu_pgtable == AMD_IOMMU_V1) &&
2062 	    (domain->iop.mode == PAGE_MODE_NONE))
2063 		return 0;
2064 
2065 	return (ops->unmap) ? ops->unmap(ops, iova, page_size, gather) : 0;
2066 }
2067 
2068 static phys_addr_t amd_iommu_iova_to_phys(struct iommu_domain *dom,
2069 					  dma_addr_t iova)
2070 {
2071 	struct protection_domain *domain = to_pdomain(dom);
2072 	struct io_pgtable_ops *ops = &domain->iop.iop.ops;
2073 
2074 	return ops->iova_to_phys(ops, iova);
2075 }
2076 
2077 static bool amd_iommu_capable(enum iommu_cap cap)
2078 {
2079 	switch (cap) {
2080 	case IOMMU_CAP_CACHE_COHERENCY:
2081 		return true;
2082 	case IOMMU_CAP_INTR_REMAP:
2083 		return (irq_remapping_enabled == 1);
2084 	case IOMMU_CAP_NOEXEC:
2085 		return false;
2086 	default:
2087 		break;
2088 	}
2089 
2090 	return false;
2091 }
2092 
2093 static void amd_iommu_get_resv_regions(struct device *dev,
2094 				       struct list_head *head)
2095 {
2096 	struct iommu_resv_region *region;
2097 	struct unity_map_entry *entry;
2098 	int devid;
2099 
2100 	devid = get_device_id(dev);
2101 	if (devid < 0)
2102 		return;
2103 
2104 	list_for_each_entry(entry, &amd_iommu_unity_map, list) {
2105 		int type, prot = 0;
2106 		size_t length;
2107 
2108 		if (devid < entry->devid_start || devid > entry->devid_end)
2109 			continue;
2110 
2111 		type   = IOMMU_RESV_DIRECT;
2112 		length = entry->address_end - entry->address_start;
2113 		if (entry->prot & IOMMU_PROT_IR)
2114 			prot |= IOMMU_READ;
2115 		if (entry->prot & IOMMU_PROT_IW)
2116 			prot |= IOMMU_WRITE;
2117 		if (entry->prot & IOMMU_UNITY_MAP_FLAG_EXCL_RANGE)
2118 			/* Exclusion range */
2119 			type = IOMMU_RESV_RESERVED;
2120 
2121 		region = iommu_alloc_resv_region(entry->address_start,
2122 						 length, prot, type);
2123 		if (!region) {
2124 			dev_err(dev, "Out of memory allocating dm-regions\n");
2125 			return;
2126 		}
2127 		list_add_tail(&region->list, head);
2128 	}
2129 
2130 	region = iommu_alloc_resv_region(MSI_RANGE_START,
2131 					 MSI_RANGE_END - MSI_RANGE_START + 1,
2132 					 0, IOMMU_RESV_MSI);
2133 	if (!region)
2134 		return;
2135 	list_add_tail(&region->list, head);
2136 
2137 	region = iommu_alloc_resv_region(HT_RANGE_START,
2138 					 HT_RANGE_END - HT_RANGE_START + 1,
2139 					 0, IOMMU_RESV_RESERVED);
2140 	if (!region)
2141 		return;
2142 	list_add_tail(&region->list, head);
2143 }
2144 
2145 bool amd_iommu_is_attach_deferred(struct iommu_domain *domain,
2146 				  struct device *dev)
2147 {
2148 	struct iommu_dev_data *dev_data = dev_iommu_priv_get(dev);
2149 
2150 	return dev_data->defer_attach;
2151 }
2152 EXPORT_SYMBOL_GPL(amd_iommu_is_attach_deferred);
2153 
2154 static void amd_iommu_flush_iotlb_all(struct iommu_domain *domain)
2155 {
2156 	struct protection_domain *dom = to_pdomain(domain);
2157 	unsigned long flags;
2158 
2159 	spin_lock_irqsave(&dom->lock, flags);
2160 	amd_iommu_domain_flush_tlb_pde(dom);
2161 	amd_iommu_domain_flush_complete(dom);
2162 	spin_unlock_irqrestore(&dom->lock, flags);
2163 }
2164 
2165 static void amd_iommu_iotlb_sync(struct iommu_domain *domain,
2166 				 struct iommu_iotlb_gather *gather)
2167 {
2168 	amd_iommu_flush_iotlb_all(domain);
2169 }
2170 
2171 static int amd_iommu_def_domain_type(struct device *dev)
2172 {
2173 	struct iommu_dev_data *dev_data;
2174 
2175 	dev_data = dev_iommu_priv_get(dev);
2176 	if (!dev_data)
2177 		return 0;
2178 
2179 	/*
2180 	 * Do not identity map IOMMUv2 capable devices when memory encryption is
2181 	 * active, because some of those devices (AMD GPUs) don't have the
2182 	 * encryption bit in their DMA-mask and require remapping.
2183 	 */
2184 	if (!mem_encrypt_active() && dev_data->iommu_v2)
2185 		return IOMMU_DOMAIN_IDENTITY;
2186 
2187 	return 0;
2188 }
2189 
2190 const struct iommu_ops amd_iommu_ops = {
2191 	.capable = amd_iommu_capable,
2192 	.domain_alloc = amd_iommu_domain_alloc,
2193 	.domain_free  = amd_iommu_domain_free,
2194 	.attach_dev = amd_iommu_attach_device,
2195 	.detach_dev = amd_iommu_detach_device,
2196 	.map = amd_iommu_map,
2197 	.unmap = amd_iommu_unmap,
2198 	.iova_to_phys = amd_iommu_iova_to_phys,
2199 	.probe_device = amd_iommu_probe_device,
2200 	.release_device = amd_iommu_release_device,
2201 	.probe_finalize = amd_iommu_probe_finalize,
2202 	.device_group = amd_iommu_device_group,
2203 	.get_resv_regions = amd_iommu_get_resv_regions,
2204 	.put_resv_regions = generic_iommu_put_resv_regions,
2205 	.is_attach_deferred = amd_iommu_is_attach_deferred,
2206 	.pgsize_bitmap	= AMD_IOMMU_PGSIZES,
2207 	.flush_iotlb_all = amd_iommu_flush_iotlb_all,
2208 	.iotlb_sync = amd_iommu_iotlb_sync,
2209 	.def_domain_type = amd_iommu_def_domain_type,
2210 };
2211 
2212 /*****************************************************************************
2213  *
2214  * The next functions do a basic initialization of IOMMU for pass through
2215  * mode
2216  *
2217  * In passthrough mode the IOMMU is initialized and enabled but not used for
2218  * DMA-API translation.
2219  *
2220  *****************************************************************************/
2221 
2222 /* IOMMUv2 specific functions */
2223 int amd_iommu_register_ppr_notifier(struct notifier_block *nb)
2224 {
2225 	return atomic_notifier_chain_register(&ppr_notifier, nb);
2226 }
2227 EXPORT_SYMBOL(amd_iommu_register_ppr_notifier);
2228 
2229 int amd_iommu_unregister_ppr_notifier(struct notifier_block *nb)
2230 {
2231 	return atomic_notifier_chain_unregister(&ppr_notifier, nb);
2232 }
2233 EXPORT_SYMBOL(amd_iommu_unregister_ppr_notifier);
2234 
2235 void amd_iommu_domain_direct_map(struct iommu_domain *dom)
2236 {
2237 	struct protection_domain *domain = to_pdomain(dom);
2238 	unsigned long flags;
2239 
2240 	spin_lock_irqsave(&domain->lock, flags);
2241 
2242 	if (domain->iop.pgtbl_cfg.tlb)
2243 		free_io_pgtable_ops(&domain->iop.iop.ops);
2244 
2245 	spin_unlock_irqrestore(&domain->lock, flags);
2246 }
2247 EXPORT_SYMBOL(amd_iommu_domain_direct_map);
2248 
2249 int amd_iommu_domain_enable_v2(struct iommu_domain *dom, int pasids)
2250 {
2251 	struct protection_domain *domain = to_pdomain(dom);
2252 	unsigned long flags;
2253 	int levels, ret;
2254 
2255 	/* Number of GCR3 table levels required */
2256 	for (levels = 0; (pasids - 1) & ~0x1ff; pasids >>= 9)
2257 		levels += 1;
2258 
2259 	if (levels > amd_iommu_max_glx_val)
2260 		return -EINVAL;
2261 
2262 	spin_lock_irqsave(&domain->lock, flags);
2263 
2264 	/*
2265 	 * Save us all sanity checks whether devices already in the
2266 	 * domain support IOMMUv2. Just force that the domain has no
2267 	 * devices attached when it is switched into IOMMUv2 mode.
2268 	 */
2269 	ret = -EBUSY;
2270 	if (domain->dev_cnt > 0 || domain->flags & PD_IOMMUV2_MASK)
2271 		goto out;
2272 
2273 	ret = -ENOMEM;
2274 	domain->gcr3_tbl = (void *)get_zeroed_page(GFP_ATOMIC);
2275 	if (domain->gcr3_tbl == NULL)
2276 		goto out;
2277 
2278 	domain->glx      = levels;
2279 	domain->flags   |= PD_IOMMUV2_MASK;
2280 
2281 	amd_iommu_domain_update(domain);
2282 
2283 	ret = 0;
2284 
2285 out:
2286 	spin_unlock_irqrestore(&domain->lock, flags);
2287 
2288 	return ret;
2289 }
2290 EXPORT_SYMBOL(amd_iommu_domain_enable_v2);
2291 
2292 static int __flush_pasid(struct protection_domain *domain, u32 pasid,
2293 			 u64 address, bool size)
2294 {
2295 	struct iommu_dev_data *dev_data;
2296 	struct iommu_cmd cmd;
2297 	int i, ret;
2298 
2299 	if (!(domain->flags & PD_IOMMUV2_MASK))
2300 		return -EINVAL;
2301 
2302 	build_inv_iommu_pasid(&cmd, domain->id, pasid, address, size);
2303 
2304 	/*
2305 	 * IOMMU TLB needs to be flushed before Device TLB to
2306 	 * prevent device TLB refill from IOMMU TLB
2307 	 */
2308 	for (i = 0; i < amd_iommu_get_num_iommus(); ++i) {
2309 		if (domain->dev_iommu[i] == 0)
2310 			continue;
2311 
2312 		ret = iommu_queue_command(amd_iommus[i], &cmd);
2313 		if (ret != 0)
2314 			goto out;
2315 	}
2316 
2317 	/* Wait until IOMMU TLB flushes are complete */
2318 	amd_iommu_domain_flush_complete(domain);
2319 
2320 	/* Now flush device TLBs */
2321 	list_for_each_entry(dev_data, &domain->dev_list, list) {
2322 		struct amd_iommu *iommu;
2323 		int qdep;
2324 
2325 		/*
2326 		   There might be non-IOMMUv2 capable devices in an IOMMUv2
2327 		 * domain.
2328 		 */
2329 		if (!dev_data->ats.enabled)
2330 			continue;
2331 
2332 		qdep  = dev_data->ats.qdep;
2333 		iommu = amd_iommu_rlookup_table[dev_data->devid];
2334 
2335 		build_inv_iotlb_pasid(&cmd, dev_data->devid, pasid,
2336 				      qdep, address, size);
2337 
2338 		ret = iommu_queue_command(iommu, &cmd);
2339 		if (ret != 0)
2340 			goto out;
2341 	}
2342 
2343 	/* Wait until all device TLBs are flushed */
2344 	amd_iommu_domain_flush_complete(domain);
2345 
2346 	ret = 0;
2347 
2348 out:
2349 
2350 	return ret;
2351 }
2352 
2353 static int __amd_iommu_flush_page(struct protection_domain *domain, u32 pasid,
2354 				  u64 address)
2355 {
2356 	return __flush_pasid(domain, pasid, address, false);
2357 }
2358 
2359 int amd_iommu_flush_page(struct iommu_domain *dom, u32 pasid,
2360 			 u64 address)
2361 {
2362 	struct protection_domain *domain = to_pdomain(dom);
2363 	unsigned long flags;
2364 	int ret;
2365 
2366 	spin_lock_irqsave(&domain->lock, flags);
2367 	ret = __amd_iommu_flush_page(domain, pasid, address);
2368 	spin_unlock_irqrestore(&domain->lock, flags);
2369 
2370 	return ret;
2371 }
2372 EXPORT_SYMBOL(amd_iommu_flush_page);
2373 
2374 static int __amd_iommu_flush_tlb(struct protection_domain *domain, u32 pasid)
2375 {
2376 	return __flush_pasid(domain, pasid, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
2377 			     true);
2378 }
2379 
2380 int amd_iommu_flush_tlb(struct iommu_domain *dom, u32 pasid)
2381 {
2382 	struct protection_domain *domain = to_pdomain(dom);
2383 	unsigned long flags;
2384 	int ret;
2385 
2386 	spin_lock_irqsave(&domain->lock, flags);
2387 	ret = __amd_iommu_flush_tlb(domain, pasid);
2388 	spin_unlock_irqrestore(&domain->lock, flags);
2389 
2390 	return ret;
2391 }
2392 EXPORT_SYMBOL(amd_iommu_flush_tlb);
2393 
2394 static u64 *__get_gcr3_pte(u64 *root, int level, u32 pasid, bool alloc)
2395 {
2396 	int index;
2397 	u64 *pte;
2398 
2399 	while (true) {
2400 
2401 		index = (pasid >> (9 * level)) & 0x1ff;
2402 		pte   = &root[index];
2403 
2404 		if (level == 0)
2405 			break;
2406 
2407 		if (!(*pte & GCR3_VALID)) {
2408 			if (!alloc)
2409 				return NULL;
2410 
2411 			root = (void *)get_zeroed_page(GFP_ATOMIC);
2412 			if (root == NULL)
2413 				return NULL;
2414 
2415 			*pte = iommu_virt_to_phys(root) | GCR3_VALID;
2416 		}
2417 
2418 		root = iommu_phys_to_virt(*pte & PAGE_MASK);
2419 
2420 		level -= 1;
2421 	}
2422 
2423 	return pte;
2424 }
2425 
2426 static int __set_gcr3(struct protection_domain *domain, u32 pasid,
2427 		      unsigned long cr3)
2428 {
2429 	u64 *pte;
2430 
2431 	if (domain->iop.mode != PAGE_MODE_NONE)
2432 		return -EINVAL;
2433 
2434 	pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, true);
2435 	if (pte == NULL)
2436 		return -ENOMEM;
2437 
2438 	*pte = (cr3 & PAGE_MASK) | GCR3_VALID;
2439 
2440 	return __amd_iommu_flush_tlb(domain, pasid);
2441 }
2442 
2443 static int __clear_gcr3(struct protection_domain *domain, u32 pasid)
2444 {
2445 	u64 *pte;
2446 
2447 	if (domain->iop.mode != PAGE_MODE_NONE)
2448 		return -EINVAL;
2449 
2450 	pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, false);
2451 	if (pte == NULL)
2452 		return 0;
2453 
2454 	*pte = 0;
2455 
2456 	return __amd_iommu_flush_tlb(domain, pasid);
2457 }
2458 
2459 int amd_iommu_domain_set_gcr3(struct iommu_domain *dom, u32 pasid,
2460 			      unsigned long cr3)
2461 {
2462 	struct protection_domain *domain = to_pdomain(dom);
2463 	unsigned long flags;
2464 	int ret;
2465 
2466 	spin_lock_irqsave(&domain->lock, flags);
2467 	ret = __set_gcr3(domain, pasid, cr3);
2468 	spin_unlock_irqrestore(&domain->lock, flags);
2469 
2470 	return ret;
2471 }
2472 EXPORT_SYMBOL(amd_iommu_domain_set_gcr3);
2473 
2474 int amd_iommu_domain_clear_gcr3(struct iommu_domain *dom, u32 pasid)
2475 {
2476 	struct protection_domain *domain = to_pdomain(dom);
2477 	unsigned long flags;
2478 	int ret;
2479 
2480 	spin_lock_irqsave(&domain->lock, flags);
2481 	ret = __clear_gcr3(domain, pasid);
2482 	spin_unlock_irqrestore(&domain->lock, flags);
2483 
2484 	return ret;
2485 }
2486 EXPORT_SYMBOL(amd_iommu_domain_clear_gcr3);
2487 
2488 int amd_iommu_complete_ppr(struct pci_dev *pdev, u32 pasid,
2489 			   int status, int tag)
2490 {
2491 	struct iommu_dev_data *dev_data;
2492 	struct amd_iommu *iommu;
2493 	struct iommu_cmd cmd;
2494 
2495 	dev_data = dev_iommu_priv_get(&pdev->dev);
2496 	iommu    = amd_iommu_rlookup_table[dev_data->devid];
2497 
2498 	build_complete_ppr(&cmd, dev_data->devid, pasid, status,
2499 			   tag, dev_data->pri_tlp);
2500 
2501 	return iommu_queue_command(iommu, &cmd);
2502 }
2503 EXPORT_SYMBOL(amd_iommu_complete_ppr);
2504 
2505 int amd_iommu_device_info(struct pci_dev *pdev,
2506                           struct amd_iommu_device_info *info)
2507 {
2508 	int max_pasids;
2509 	int pos;
2510 
2511 	if (pdev == NULL || info == NULL)
2512 		return -EINVAL;
2513 
2514 	if (!amd_iommu_v2_supported())
2515 		return -EINVAL;
2516 
2517 	memset(info, 0, sizeof(*info));
2518 
2519 	if (pci_ats_supported(pdev))
2520 		info->flags |= AMD_IOMMU_DEVICE_FLAG_ATS_SUP;
2521 
2522 	pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
2523 	if (pos)
2524 		info->flags |= AMD_IOMMU_DEVICE_FLAG_PRI_SUP;
2525 
2526 	pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PASID);
2527 	if (pos) {
2528 		int features;
2529 
2530 		max_pasids = 1 << (9 * (amd_iommu_max_glx_val + 1));
2531 		max_pasids = min(max_pasids, (1 << 20));
2532 
2533 		info->flags |= AMD_IOMMU_DEVICE_FLAG_PASID_SUP;
2534 		info->max_pasids = min(pci_max_pasids(pdev), max_pasids);
2535 
2536 		features = pci_pasid_features(pdev);
2537 		if (features & PCI_PASID_CAP_EXEC)
2538 			info->flags |= AMD_IOMMU_DEVICE_FLAG_EXEC_SUP;
2539 		if (features & PCI_PASID_CAP_PRIV)
2540 			info->flags |= AMD_IOMMU_DEVICE_FLAG_PRIV_SUP;
2541 	}
2542 
2543 	return 0;
2544 }
2545 EXPORT_SYMBOL(amd_iommu_device_info);
2546 
2547 #ifdef CONFIG_IRQ_REMAP
2548 
2549 /*****************************************************************************
2550  *
2551  * Interrupt Remapping Implementation
2552  *
2553  *****************************************************************************/
2554 
2555 static struct irq_chip amd_ir_chip;
2556 static DEFINE_SPINLOCK(iommu_table_lock);
2557 
2558 static void set_dte_irq_entry(u16 devid, struct irq_remap_table *table)
2559 {
2560 	u64 dte;
2561 
2562 	dte	= amd_iommu_dev_table[devid].data[2];
2563 	dte	&= ~DTE_IRQ_PHYS_ADDR_MASK;
2564 	dte	|= iommu_virt_to_phys(table->table);
2565 	dte	|= DTE_IRQ_REMAP_INTCTL;
2566 	dte	|= DTE_INTTABLEN;
2567 	dte	|= DTE_IRQ_REMAP_ENABLE;
2568 
2569 	amd_iommu_dev_table[devid].data[2] = dte;
2570 }
2571 
2572 static struct irq_remap_table *get_irq_table(u16 devid)
2573 {
2574 	struct irq_remap_table *table;
2575 
2576 	if (WARN_ONCE(!amd_iommu_rlookup_table[devid],
2577 		      "%s: no iommu for devid %x\n", __func__, devid))
2578 		return NULL;
2579 
2580 	table = irq_lookup_table[devid];
2581 	if (WARN_ONCE(!table, "%s: no table for devid %x\n", __func__, devid))
2582 		return NULL;
2583 
2584 	return table;
2585 }
2586 
2587 static struct irq_remap_table *__alloc_irq_table(void)
2588 {
2589 	struct irq_remap_table *table;
2590 
2591 	table = kzalloc(sizeof(*table), GFP_KERNEL);
2592 	if (!table)
2593 		return NULL;
2594 
2595 	table->table = kmem_cache_alloc(amd_iommu_irq_cache, GFP_KERNEL);
2596 	if (!table->table) {
2597 		kfree(table);
2598 		return NULL;
2599 	}
2600 	raw_spin_lock_init(&table->lock);
2601 
2602 	if (!AMD_IOMMU_GUEST_IR_GA(amd_iommu_guest_ir))
2603 		memset(table->table, 0,
2604 		       MAX_IRQS_PER_TABLE * sizeof(u32));
2605 	else
2606 		memset(table->table, 0,
2607 		       (MAX_IRQS_PER_TABLE * (sizeof(u64) * 2)));
2608 	return table;
2609 }
2610 
2611 static void set_remap_table_entry(struct amd_iommu *iommu, u16 devid,
2612 				  struct irq_remap_table *table)
2613 {
2614 	irq_lookup_table[devid] = table;
2615 	set_dte_irq_entry(devid, table);
2616 	iommu_flush_dte(iommu, devid);
2617 }
2618 
2619 static int set_remap_table_entry_alias(struct pci_dev *pdev, u16 alias,
2620 				       void *data)
2621 {
2622 	struct irq_remap_table *table = data;
2623 
2624 	irq_lookup_table[alias] = table;
2625 	set_dte_irq_entry(alias, table);
2626 
2627 	iommu_flush_dte(amd_iommu_rlookup_table[alias], alias);
2628 
2629 	return 0;
2630 }
2631 
2632 static struct irq_remap_table *alloc_irq_table(u16 devid, struct pci_dev *pdev)
2633 {
2634 	struct irq_remap_table *table = NULL;
2635 	struct irq_remap_table *new_table = NULL;
2636 	struct amd_iommu *iommu;
2637 	unsigned long flags;
2638 	u16 alias;
2639 
2640 	spin_lock_irqsave(&iommu_table_lock, flags);
2641 
2642 	iommu = amd_iommu_rlookup_table[devid];
2643 	if (!iommu)
2644 		goto out_unlock;
2645 
2646 	table = irq_lookup_table[devid];
2647 	if (table)
2648 		goto out_unlock;
2649 
2650 	alias = amd_iommu_alias_table[devid];
2651 	table = irq_lookup_table[alias];
2652 	if (table) {
2653 		set_remap_table_entry(iommu, devid, table);
2654 		goto out_wait;
2655 	}
2656 	spin_unlock_irqrestore(&iommu_table_lock, flags);
2657 
2658 	/* Nothing there yet, allocate new irq remapping table */
2659 	new_table = __alloc_irq_table();
2660 	if (!new_table)
2661 		return NULL;
2662 
2663 	spin_lock_irqsave(&iommu_table_lock, flags);
2664 
2665 	table = irq_lookup_table[devid];
2666 	if (table)
2667 		goto out_unlock;
2668 
2669 	table = irq_lookup_table[alias];
2670 	if (table) {
2671 		set_remap_table_entry(iommu, devid, table);
2672 		goto out_wait;
2673 	}
2674 
2675 	table = new_table;
2676 	new_table = NULL;
2677 
2678 	if (pdev)
2679 		pci_for_each_dma_alias(pdev, set_remap_table_entry_alias,
2680 				       table);
2681 	else
2682 		set_remap_table_entry(iommu, devid, table);
2683 
2684 	if (devid != alias)
2685 		set_remap_table_entry(iommu, alias, table);
2686 
2687 out_wait:
2688 	iommu_completion_wait(iommu);
2689 
2690 out_unlock:
2691 	spin_unlock_irqrestore(&iommu_table_lock, flags);
2692 
2693 	if (new_table) {
2694 		kmem_cache_free(amd_iommu_irq_cache, new_table->table);
2695 		kfree(new_table);
2696 	}
2697 	return table;
2698 }
2699 
2700 static int alloc_irq_index(u16 devid, int count, bool align,
2701 			   struct pci_dev *pdev)
2702 {
2703 	struct irq_remap_table *table;
2704 	int index, c, alignment = 1;
2705 	unsigned long flags;
2706 	struct amd_iommu *iommu = amd_iommu_rlookup_table[devid];
2707 
2708 	if (!iommu)
2709 		return -ENODEV;
2710 
2711 	table = alloc_irq_table(devid, pdev);
2712 	if (!table)
2713 		return -ENODEV;
2714 
2715 	if (align)
2716 		alignment = roundup_pow_of_two(count);
2717 
2718 	raw_spin_lock_irqsave(&table->lock, flags);
2719 
2720 	/* Scan table for free entries */
2721 	for (index = ALIGN(table->min_index, alignment), c = 0;
2722 	     index < MAX_IRQS_PER_TABLE;) {
2723 		if (!iommu->irte_ops->is_allocated(table, index)) {
2724 			c += 1;
2725 		} else {
2726 			c     = 0;
2727 			index = ALIGN(index + 1, alignment);
2728 			continue;
2729 		}
2730 
2731 		if (c == count)	{
2732 			for (; c != 0; --c)
2733 				iommu->irte_ops->set_allocated(table, index - c + 1);
2734 
2735 			index -= count - 1;
2736 			goto out;
2737 		}
2738 
2739 		index++;
2740 	}
2741 
2742 	index = -ENOSPC;
2743 
2744 out:
2745 	raw_spin_unlock_irqrestore(&table->lock, flags);
2746 
2747 	return index;
2748 }
2749 
2750 static int modify_irte_ga(u16 devid, int index, struct irte_ga *irte,
2751 			  struct amd_ir_data *data)
2752 {
2753 	bool ret;
2754 	struct irq_remap_table *table;
2755 	struct amd_iommu *iommu;
2756 	unsigned long flags;
2757 	struct irte_ga *entry;
2758 
2759 	iommu = amd_iommu_rlookup_table[devid];
2760 	if (iommu == NULL)
2761 		return -EINVAL;
2762 
2763 	table = get_irq_table(devid);
2764 	if (!table)
2765 		return -ENOMEM;
2766 
2767 	raw_spin_lock_irqsave(&table->lock, flags);
2768 
2769 	entry = (struct irte_ga *)table->table;
2770 	entry = &entry[index];
2771 
2772 	ret = cmpxchg_double(&entry->lo.val, &entry->hi.val,
2773 			     entry->lo.val, entry->hi.val,
2774 			     irte->lo.val, irte->hi.val);
2775 	/*
2776 	 * We use cmpxchg16 to atomically update the 128-bit IRTE,
2777 	 * and it cannot be updated by the hardware or other processors
2778 	 * behind us, so the return value of cmpxchg16 should be the
2779 	 * same as the old value.
2780 	 */
2781 	WARN_ON(!ret);
2782 
2783 	if (data)
2784 		data->ref = entry;
2785 
2786 	raw_spin_unlock_irqrestore(&table->lock, flags);
2787 
2788 	iommu_flush_irt(iommu, devid);
2789 	iommu_completion_wait(iommu);
2790 
2791 	return 0;
2792 }
2793 
2794 static int modify_irte(u16 devid, int index, union irte *irte)
2795 {
2796 	struct irq_remap_table *table;
2797 	struct amd_iommu *iommu;
2798 	unsigned long flags;
2799 
2800 	iommu = amd_iommu_rlookup_table[devid];
2801 	if (iommu == NULL)
2802 		return -EINVAL;
2803 
2804 	table = get_irq_table(devid);
2805 	if (!table)
2806 		return -ENOMEM;
2807 
2808 	raw_spin_lock_irqsave(&table->lock, flags);
2809 	table->table[index] = irte->val;
2810 	raw_spin_unlock_irqrestore(&table->lock, flags);
2811 
2812 	iommu_flush_irt(iommu, devid);
2813 	iommu_completion_wait(iommu);
2814 
2815 	return 0;
2816 }
2817 
2818 static void free_irte(u16 devid, int index)
2819 {
2820 	struct irq_remap_table *table;
2821 	struct amd_iommu *iommu;
2822 	unsigned long flags;
2823 
2824 	iommu = amd_iommu_rlookup_table[devid];
2825 	if (iommu == NULL)
2826 		return;
2827 
2828 	table = get_irq_table(devid);
2829 	if (!table)
2830 		return;
2831 
2832 	raw_spin_lock_irqsave(&table->lock, flags);
2833 	iommu->irte_ops->clear_allocated(table, index);
2834 	raw_spin_unlock_irqrestore(&table->lock, flags);
2835 
2836 	iommu_flush_irt(iommu, devid);
2837 	iommu_completion_wait(iommu);
2838 }
2839 
2840 static void irte_prepare(void *entry,
2841 			 u32 delivery_mode, bool dest_mode,
2842 			 u8 vector, u32 dest_apicid, int devid)
2843 {
2844 	union irte *irte = (union irte *) entry;
2845 
2846 	irte->val                = 0;
2847 	irte->fields.vector      = vector;
2848 	irte->fields.int_type    = delivery_mode;
2849 	irte->fields.destination = dest_apicid;
2850 	irte->fields.dm          = dest_mode;
2851 	irte->fields.valid       = 1;
2852 }
2853 
2854 static void irte_ga_prepare(void *entry,
2855 			    u32 delivery_mode, bool dest_mode,
2856 			    u8 vector, u32 dest_apicid, int devid)
2857 {
2858 	struct irte_ga *irte = (struct irte_ga *) entry;
2859 
2860 	irte->lo.val                      = 0;
2861 	irte->hi.val                      = 0;
2862 	irte->lo.fields_remap.int_type    = delivery_mode;
2863 	irte->lo.fields_remap.dm          = dest_mode;
2864 	irte->hi.fields.vector            = vector;
2865 	irte->lo.fields_remap.destination = APICID_TO_IRTE_DEST_LO(dest_apicid);
2866 	irte->hi.fields.destination       = APICID_TO_IRTE_DEST_HI(dest_apicid);
2867 	irte->lo.fields_remap.valid       = 1;
2868 }
2869 
2870 static void irte_activate(void *entry, u16 devid, u16 index)
2871 {
2872 	union irte *irte = (union irte *) entry;
2873 
2874 	irte->fields.valid = 1;
2875 	modify_irte(devid, index, irte);
2876 }
2877 
2878 static void irte_ga_activate(void *entry, u16 devid, u16 index)
2879 {
2880 	struct irte_ga *irte = (struct irte_ga *) entry;
2881 
2882 	irte->lo.fields_remap.valid = 1;
2883 	modify_irte_ga(devid, index, irte, NULL);
2884 }
2885 
2886 static void irte_deactivate(void *entry, u16 devid, u16 index)
2887 {
2888 	union irte *irte = (union irte *) entry;
2889 
2890 	irte->fields.valid = 0;
2891 	modify_irte(devid, index, irte);
2892 }
2893 
2894 static void irte_ga_deactivate(void *entry, u16 devid, u16 index)
2895 {
2896 	struct irte_ga *irte = (struct irte_ga *) entry;
2897 
2898 	irte->lo.fields_remap.valid = 0;
2899 	modify_irte_ga(devid, index, irte, NULL);
2900 }
2901 
2902 static void irte_set_affinity(void *entry, u16 devid, u16 index,
2903 			      u8 vector, u32 dest_apicid)
2904 {
2905 	union irte *irte = (union irte *) entry;
2906 
2907 	irte->fields.vector = vector;
2908 	irte->fields.destination = dest_apicid;
2909 	modify_irte(devid, index, irte);
2910 }
2911 
2912 static void irte_ga_set_affinity(void *entry, u16 devid, u16 index,
2913 				 u8 vector, u32 dest_apicid)
2914 {
2915 	struct irte_ga *irte = (struct irte_ga *) entry;
2916 
2917 	if (!irte->lo.fields_remap.guest_mode) {
2918 		irte->hi.fields.vector = vector;
2919 		irte->lo.fields_remap.destination =
2920 					APICID_TO_IRTE_DEST_LO(dest_apicid);
2921 		irte->hi.fields.destination =
2922 					APICID_TO_IRTE_DEST_HI(dest_apicid);
2923 		modify_irte_ga(devid, index, irte, NULL);
2924 	}
2925 }
2926 
2927 #define IRTE_ALLOCATED (~1U)
2928 static void irte_set_allocated(struct irq_remap_table *table, int index)
2929 {
2930 	table->table[index] = IRTE_ALLOCATED;
2931 }
2932 
2933 static void irte_ga_set_allocated(struct irq_remap_table *table, int index)
2934 {
2935 	struct irte_ga *ptr = (struct irte_ga *)table->table;
2936 	struct irte_ga *irte = &ptr[index];
2937 
2938 	memset(&irte->lo.val, 0, sizeof(u64));
2939 	memset(&irte->hi.val, 0, sizeof(u64));
2940 	irte->hi.fields.vector = 0xff;
2941 }
2942 
2943 static bool irte_is_allocated(struct irq_remap_table *table, int index)
2944 {
2945 	union irte *ptr = (union irte *)table->table;
2946 	union irte *irte = &ptr[index];
2947 
2948 	return irte->val != 0;
2949 }
2950 
2951 static bool irte_ga_is_allocated(struct irq_remap_table *table, int index)
2952 {
2953 	struct irte_ga *ptr = (struct irte_ga *)table->table;
2954 	struct irte_ga *irte = &ptr[index];
2955 
2956 	return irte->hi.fields.vector != 0;
2957 }
2958 
2959 static void irte_clear_allocated(struct irq_remap_table *table, int index)
2960 {
2961 	table->table[index] = 0;
2962 }
2963 
2964 static void irte_ga_clear_allocated(struct irq_remap_table *table, int index)
2965 {
2966 	struct irte_ga *ptr = (struct irte_ga *)table->table;
2967 	struct irte_ga *irte = &ptr[index];
2968 
2969 	memset(&irte->lo.val, 0, sizeof(u64));
2970 	memset(&irte->hi.val, 0, sizeof(u64));
2971 }
2972 
2973 static int get_devid(struct irq_alloc_info *info)
2974 {
2975 	switch (info->type) {
2976 	case X86_IRQ_ALLOC_TYPE_IOAPIC:
2977 		return get_ioapic_devid(info->devid);
2978 	case X86_IRQ_ALLOC_TYPE_HPET:
2979 		return get_hpet_devid(info->devid);
2980 	case X86_IRQ_ALLOC_TYPE_PCI_MSI:
2981 	case X86_IRQ_ALLOC_TYPE_PCI_MSIX:
2982 		return get_device_id(msi_desc_to_dev(info->desc));
2983 	default:
2984 		WARN_ON_ONCE(1);
2985 		return -1;
2986 	}
2987 }
2988 
2989 struct irq_remap_ops amd_iommu_irq_ops = {
2990 	.prepare		= amd_iommu_prepare,
2991 	.enable			= amd_iommu_enable,
2992 	.disable		= amd_iommu_disable,
2993 	.reenable		= amd_iommu_reenable,
2994 	.enable_faulting	= amd_iommu_enable_faulting,
2995 };
2996 
2997 static void fill_msi_msg(struct msi_msg *msg, u32 index)
2998 {
2999 	msg->data = index;
3000 	msg->address_lo = 0;
3001 	msg->arch_addr_lo.base_address = X86_MSI_BASE_ADDRESS_LOW;
3002 	msg->address_hi = X86_MSI_BASE_ADDRESS_HIGH;
3003 }
3004 
3005 static void irq_remapping_prepare_irte(struct amd_ir_data *data,
3006 				       struct irq_cfg *irq_cfg,
3007 				       struct irq_alloc_info *info,
3008 				       int devid, int index, int sub_handle)
3009 {
3010 	struct irq_2_irte *irte_info = &data->irq_2_irte;
3011 	struct amd_iommu *iommu = amd_iommu_rlookup_table[devid];
3012 
3013 	if (!iommu)
3014 		return;
3015 
3016 	data->irq_2_irte.devid = devid;
3017 	data->irq_2_irte.index = index + sub_handle;
3018 	iommu->irte_ops->prepare(data->entry, apic->delivery_mode,
3019 				 apic->dest_mode_logical, irq_cfg->vector,
3020 				 irq_cfg->dest_apicid, devid);
3021 
3022 	switch (info->type) {
3023 	case X86_IRQ_ALLOC_TYPE_IOAPIC:
3024 	case X86_IRQ_ALLOC_TYPE_HPET:
3025 	case X86_IRQ_ALLOC_TYPE_PCI_MSI:
3026 	case X86_IRQ_ALLOC_TYPE_PCI_MSIX:
3027 		fill_msi_msg(&data->msi_entry, irte_info->index);
3028 		break;
3029 
3030 	default:
3031 		BUG_ON(1);
3032 		break;
3033 	}
3034 }
3035 
3036 struct amd_irte_ops irte_32_ops = {
3037 	.prepare = irte_prepare,
3038 	.activate = irte_activate,
3039 	.deactivate = irte_deactivate,
3040 	.set_affinity = irte_set_affinity,
3041 	.set_allocated = irte_set_allocated,
3042 	.is_allocated = irte_is_allocated,
3043 	.clear_allocated = irte_clear_allocated,
3044 };
3045 
3046 struct amd_irte_ops irte_128_ops = {
3047 	.prepare = irte_ga_prepare,
3048 	.activate = irte_ga_activate,
3049 	.deactivate = irte_ga_deactivate,
3050 	.set_affinity = irte_ga_set_affinity,
3051 	.set_allocated = irte_ga_set_allocated,
3052 	.is_allocated = irte_ga_is_allocated,
3053 	.clear_allocated = irte_ga_clear_allocated,
3054 };
3055 
3056 static int irq_remapping_alloc(struct irq_domain *domain, unsigned int virq,
3057 			       unsigned int nr_irqs, void *arg)
3058 {
3059 	struct irq_alloc_info *info = arg;
3060 	struct irq_data *irq_data;
3061 	struct amd_ir_data *data = NULL;
3062 	struct irq_cfg *cfg;
3063 	int i, ret, devid;
3064 	int index;
3065 
3066 	if (!info)
3067 		return -EINVAL;
3068 	if (nr_irqs > 1 && info->type != X86_IRQ_ALLOC_TYPE_PCI_MSI &&
3069 	    info->type != X86_IRQ_ALLOC_TYPE_PCI_MSIX)
3070 		return -EINVAL;
3071 
3072 	/*
3073 	 * With IRQ remapping enabled, don't need contiguous CPU vectors
3074 	 * to support multiple MSI interrupts.
3075 	 */
3076 	if (info->type == X86_IRQ_ALLOC_TYPE_PCI_MSI)
3077 		info->flags &= ~X86_IRQ_ALLOC_CONTIGUOUS_VECTORS;
3078 
3079 	devid = get_devid(info);
3080 	if (devid < 0)
3081 		return -EINVAL;
3082 
3083 	ret = irq_domain_alloc_irqs_parent(domain, virq, nr_irqs, arg);
3084 	if (ret < 0)
3085 		return ret;
3086 
3087 	if (info->type == X86_IRQ_ALLOC_TYPE_IOAPIC) {
3088 		struct irq_remap_table *table;
3089 		struct amd_iommu *iommu;
3090 
3091 		table = alloc_irq_table(devid, NULL);
3092 		if (table) {
3093 			if (!table->min_index) {
3094 				/*
3095 				 * Keep the first 32 indexes free for IOAPIC
3096 				 * interrupts.
3097 				 */
3098 				table->min_index = 32;
3099 				iommu = amd_iommu_rlookup_table[devid];
3100 				for (i = 0; i < 32; ++i)
3101 					iommu->irte_ops->set_allocated(table, i);
3102 			}
3103 			WARN_ON(table->min_index != 32);
3104 			index = info->ioapic.pin;
3105 		} else {
3106 			index = -ENOMEM;
3107 		}
3108 	} else if (info->type == X86_IRQ_ALLOC_TYPE_PCI_MSI ||
3109 		   info->type == X86_IRQ_ALLOC_TYPE_PCI_MSIX) {
3110 		bool align = (info->type == X86_IRQ_ALLOC_TYPE_PCI_MSI);
3111 
3112 		index = alloc_irq_index(devid, nr_irqs, align,
3113 					msi_desc_to_pci_dev(info->desc));
3114 	} else {
3115 		index = alloc_irq_index(devid, nr_irqs, false, NULL);
3116 	}
3117 
3118 	if (index < 0) {
3119 		pr_warn("Failed to allocate IRTE\n");
3120 		ret = index;
3121 		goto out_free_parent;
3122 	}
3123 
3124 	for (i = 0; i < nr_irqs; i++) {
3125 		irq_data = irq_domain_get_irq_data(domain, virq + i);
3126 		cfg = irq_data ? irqd_cfg(irq_data) : NULL;
3127 		if (!cfg) {
3128 			ret = -EINVAL;
3129 			goto out_free_data;
3130 		}
3131 
3132 		ret = -ENOMEM;
3133 		data = kzalloc(sizeof(*data), GFP_KERNEL);
3134 		if (!data)
3135 			goto out_free_data;
3136 
3137 		if (!AMD_IOMMU_GUEST_IR_GA(amd_iommu_guest_ir))
3138 			data->entry = kzalloc(sizeof(union irte), GFP_KERNEL);
3139 		else
3140 			data->entry = kzalloc(sizeof(struct irte_ga),
3141 						     GFP_KERNEL);
3142 		if (!data->entry) {
3143 			kfree(data);
3144 			goto out_free_data;
3145 		}
3146 
3147 		irq_data->hwirq = (devid << 16) + i;
3148 		irq_data->chip_data = data;
3149 		irq_data->chip = &amd_ir_chip;
3150 		irq_remapping_prepare_irte(data, cfg, info, devid, index, i);
3151 		irq_set_status_flags(virq + i, IRQ_MOVE_PCNTXT);
3152 	}
3153 
3154 	return 0;
3155 
3156 out_free_data:
3157 	for (i--; i >= 0; i--) {
3158 		irq_data = irq_domain_get_irq_data(domain, virq + i);
3159 		if (irq_data)
3160 			kfree(irq_data->chip_data);
3161 	}
3162 	for (i = 0; i < nr_irqs; i++)
3163 		free_irte(devid, index + i);
3164 out_free_parent:
3165 	irq_domain_free_irqs_common(domain, virq, nr_irqs);
3166 	return ret;
3167 }
3168 
3169 static void irq_remapping_free(struct irq_domain *domain, unsigned int virq,
3170 			       unsigned int nr_irqs)
3171 {
3172 	struct irq_2_irte *irte_info;
3173 	struct irq_data *irq_data;
3174 	struct amd_ir_data *data;
3175 	int i;
3176 
3177 	for (i = 0; i < nr_irqs; i++) {
3178 		irq_data = irq_domain_get_irq_data(domain, virq  + i);
3179 		if (irq_data && irq_data->chip_data) {
3180 			data = irq_data->chip_data;
3181 			irte_info = &data->irq_2_irte;
3182 			free_irte(irte_info->devid, irte_info->index);
3183 			kfree(data->entry);
3184 			kfree(data);
3185 		}
3186 	}
3187 	irq_domain_free_irqs_common(domain, virq, nr_irqs);
3188 }
3189 
3190 static void amd_ir_update_irte(struct irq_data *irqd, struct amd_iommu *iommu,
3191 			       struct amd_ir_data *ir_data,
3192 			       struct irq_2_irte *irte_info,
3193 			       struct irq_cfg *cfg);
3194 
3195 static int irq_remapping_activate(struct irq_domain *domain,
3196 				  struct irq_data *irq_data, bool reserve)
3197 {
3198 	struct amd_ir_data *data = irq_data->chip_data;
3199 	struct irq_2_irte *irte_info = &data->irq_2_irte;
3200 	struct amd_iommu *iommu = amd_iommu_rlookup_table[irte_info->devid];
3201 	struct irq_cfg *cfg = irqd_cfg(irq_data);
3202 
3203 	if (!iommu)
3204 		return 0;
3205 
3206 	iommu->irte_ops->activate(data->entry, irte_info->devid,
3207 				  irte_info->index);
3208 	amd_ir_update_irte(irq_data, iommu, data, irte_info, cfg);
3209 	return 0;
3210 }
3211 
3212 static void irq_remapping_deactivate(struct irq_domain *domain,
3213 				     struct irq_data *irq_data)
3214 {
3215 	struct amd_ir_data *data = irq_data->chip_data;
3216 	struct irq_2_irte *irte_info = &data->irq_2_irte;
3217 	struct amd_iommu *iommu = amd_iommu_rlookup_table[irte_info->devid];
3218 
3219 	if (iommu)
3220 		iommu->irte_ops->deactivate(data->entry, irte_info->devid,
3221 					    irte_info->index);
3222 }
3223 
3224 static int irq_remapping_select(struct irq_domain *d, struct irq_fwspec *fwspec,
3225 				enum irq_domain_bus_token bus_token)
3226 {
3227 	struct amd_iommu *iommu;
3228 	int devid = -1;
3229 
3230 	if (!amd_iommu_irq_remap)
3231 		return 0;
3232 
3233 	if (x86_fwspec_is_ioapic(fwspec))
3234 		devid = get_ioapic_devid(fwspec->param[0]);
3235 	else if (x86_fwspec_is_hpet(fwspec))
3236 		devid = get_hpet_devid(fwspec->param[0]);
3237 
3238 	if (devid < 0)
3239 		return 0;
3240 
3241 	iommu = amd_iommu_rlookup_table[devid];
3242 	return iommu && iommu->ir_domain == d;
3243 }
3244 
3245 static const struct irq_domain_ops amd_ir_domain_ops = {
3246 	.select = irq_remapping_select,
3247 	.alloc = irq_remapping_alloc,
3248 	.free = irq_remapping_free,
3249 	.activate = irq_remapping_activate,
3250 	.deactivate = irq_remapping_deactivate,
3251 };
3252 
3253 int amd_iommu_activate_guest_mode(void *data)
3254 {
3255 	struct amd_ir_data *ir_data = (struct amd_ir_data *)data;
3256 	struct irte_ga *entry = (struct irte_ga *) ir_data->entry;
3257 	u64 valid;
3258 
3259 	if (!AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir) ||
3260 	    !entry || entry->lo.fields_vapic.guest_mode)
3261 		return 0;
3262 
3263 	valid = entry->lo.fields_vapic.valid;
3264 
3265 	entry->lo.val = 0;
3266 	entry->hi.val = 0;
3267 
3268 	entry->lo.fields_vapic.valid       = valid;
3269 	entry->lo.fields_vapic.guest_mode  = 1;
3270 	entry->lo.fields_vapic.ga_log_intr = 1;
3271 	entry->hi.fields.ga_root_ptr       = ir_data->ga_root_ptr;
3272 	entry->hi.fields.vector            = ir_data->ga_vector;
3273 	entry->lo.fields_vapic.ga_tag      = ir_data->ga_tag;
3274 
3275 	return modify_irte_ga(ir_data->irq_2_irte.devid,
3276 			      ir_data->irq_2_irte.index, entry, ir_data);
3277 }
3278 EXPORT_SYMBOL(amd_iommu_activate_guest_mode);
3279 
3280 int amd_iommu_deactivate_guest_mode(void *data)
3281 {
3282 	struct amd_ir_data *ir_data = (struct amd_ir_data *)data;
3283 	struct irte_ga *entry = (struct irte_ga *) ir_data->entry;
3284 	struct irq_cfg *cfg = ir_data->cfg;
3285 	u64 valid;
3286 
3287 	if (!AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir) ||
3288 	    !entry || !entry->lo.fields_vapic.guest_mode)
3289 		return 0;
3290 
3291 	valid = entry->lo.fields_remap.valid;
3292 
3293 	entry->lo.val = 0;
3294 	entry->hi.val = 0;
3295 
3296 	entry->lo.fields_remap.valid       = valid;
3297 	entry->lo.fields_remap.dm          = apic->dest_mode_logical;
3298 	entry->lo.fields_remap.int_type    = apic->delivery_mode;
3299 	entry->hi.fields.vector            = cfg->vector;
3300 	entry->lo.fields_remap.destination =
3301 				APICID_TO_IRTE_DEST_LO(cfg->dest_apicid);
3302 	entry->hi.fields.destination =
3303 				APICID_TO_IRTE_DEST_HI(cfg->dest_apicid);
3304 
3305 	return modify_irte_ga(ir_data->irq_2_irte.devid,
3306 			      ir_data->irq_2_irte.index, entry, ir_data);
3307 }
3308 EXPORT_SYMBOL(amd_iommu_deactivate_guest_mode);
3309 
3310 static int amd_ir_set_vcpu_affinity(struct irq_data *data, void *vcpu_info)
3311 {
3312 	int ret;
3313 	struct amd_iommu *iommu;
3314 	struct amd_iommu_pi_data *pi_data = vcpu_info;
3315 	struct vcpu_data *vcpu_pi_info = pi_data->vcpu_data;
3316 	struct amd_ir_data *ir_data = data->chip_data;
3317 	struct irq_2_irte *irte_info = &ir_data->irq_2_irte;
3318 	struct iommu_dev_data *dev_data = search_dev_data(irte_info->devid);
3319 
3320 	/* Note:
3321 	 * This device has never been set up for guest mode.
3322 	 * we should not modify the IRTE
3323 	 */
3324 	if (!dev_data || !dev_data->use_vapic)
3325 		return 0;
3326 
3327 	ir_data->cfg = irqd_cfg(data);
3328 	pi_data->ir_data = ir_data;
3329 
3330 	/* Note:
3331 	 * SVM tries to set up for VAPIC mode, but we are in
3332 	 * legacy mode. So, we force legacy mode instead.
3333 	 */
3334 	if (!AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir)) {
3335 		pr_debug("%s: Fall back to using intr legacy remap\n",
3336 			 __func__);
3337 		pi_data->is_guest_mode = false;
3338 	}
3339 
3340 	iommu = amd_iommu_rlookup_table[irte_info->devid];
3341 	if (iommu == NULL)
3342 		return -EINVAL;
3343 
3344 	pi_data->prev_ga_tag = ir_data->cached_ga_tag;
3345 	if (pi_data->is_guest_mode) {
3346 		ir_data->ga_root_ptr = (pi_data->base >> 12);
3347 		ir_data->ga_vector = vcpu_pi_info->vector;
3348 		ir_data->ga_tag = pi_data->ga_tag;
3349 		ret = amd_iommu_activate_guest_mode(ir_data);
3350 		if (!ret)
3351 			ir_data->cached_ga_tag = pi_data->ga_tag;
3352 	} else {
3353 		ret = amd_iommu_deactivate_guest_mode(ir_data);
3354 
3355 		/*
3356 		 * This communicates the ga_tag back to the caller
3357 		 * so that it can do all the necessary clean up.
3358 		 */
3359 		if (!ret)
3360 			ir_data->cached_ga_tag = 0;
3361 	}
3362 
3363 	return ret;
3364 }
3365 
3366 
3367 static void amd_ir_update_irte(struct irq_data *irqd, struct amd_iommu *iommu,
3368 			       struct amd_ir_data *ir_data,
3369 			       struct irq_2_irte *irte_info,
3370 			       struct irq_cfg *cfg)
3371 {
3372 
3373 	/*
3374 	 * Atomically updates the IRTE with the new destination, vector
3375 	 * and flushes the interrupt entry cache.
3376 	 */
3377 	iommu->irte_ops->set_affinity(ir_data->entry, irte_info->devid,
3378 				      irte_info->index, cfg->vector,
3379 				      cfg->dest_apicid);
3380 }
3381 
3382 static int amd_ir_set_affinity(struct irq_data *data,
3383 			       const struct cpumask *mask, bool force)
3384 {
3385 	struct amd_ir_data *ir_data = data->chip_data;
3386 	struct irq_2_irte *irte_info = &ir_data->irq_2_irte;
3387 	struct irq_cfg *cfg = irqd_cfg(data);
3388 	struct irq_data *parent = data->parent_data;
3389 	struct amd_iommu *iommu = amd_iommu_rlookup_table[irte_info->devid];
3390 	int ret;
3391 
3392 	if (!iommu)
3393 		return -ENODEV;
3394 
3395 	ret = parent->chip->irq_set_affinity(parent, mask, force);
3396 	if (ret < 0 || ret == IRQ_SET_MASK_OK_DONE)
3397 		return ret;
3398 
3399 	amd_ir_update_irte(data, iommu, ir_data, irte_info, cfg);
3400 	/*
3401 	 * After this point, all the interrupts will start arriving
3402 	 * at the new destination. So, time to cleanup the previous
3403 	 * vector allocation.
3404 	 */
3405 	send_cleanup_vector(cfg);
3406 
3407 	return IRQ_SET_MASK_OK_DONE;
3408 }
3409 
3410 static void ir_compose_msi_msg(struct irq_data *irq_data, struct msi_msg *msg)
3411 {
3412 	struct amd_ir_data *ir_data = irq_data->chip_data;
3413 
3414 	*msg = ir_data->msi_entry;
3415 }
3416 
3417 static struct irq_chip amd_ir_chip = {
3418 	.name			= "AMD-IR",
3419 	.irq_ack		= apic_ack_irq,
3420 	.irq_set_affinity	= amd_ir_set_affinity,
3421 	.irq_set_vcpu_affinity	= amd_ir_set_vcpu_affinity,
3422 	.irq_compose_msi_msg	= ir_compose_msi_msg,
3423 };
3424 
3425 int amd_iommu_create_irq_domain(struct amd_iommu *iommu)
3426 {
3427 	struct fwnode_handle *fn;
3428 
3429 	fn = irq_domain_alloc_named_id_fwnode("AMD-IR", iommu->index);
3430 	if (!fn)
3431 		return -ENOMEM;
3432 	iommu->ir_domain = irq_domain_create_tree(fn, &amd_ir_domain_ops, iommu);
3433 	if (!iommu->ir_domain) {
3434 		irq_domain_free_fwnode(fn);
3435 		return -ENOMEM;
3436 	}
3437 
3438 	iommu->ir_domain->parent = arch_get_ir_parent_domain();
3439 	iommu->msi_domain = arch_create_remap_msi_irq_domain(iommu->ir_domain,
3440 							     "AMD-IR-MSI",
3441 							     iommu->index);
3442 	return 0;
3443 }
3444 
3445 int amd_iommu_update_ga(int cpu, bool is_run, void *data)
3446 {
3447 	unsigned long flags;
3448 	struct amd_iommu *iommu;
3449 	struct irq_remap_table *table;
3450 	struct amd_ir_data *ir_data = (struct amd_ir_data *)data;
3451 	int devid = ir_data->irq_2_irte.devid;
3452 	struct irte_ga *entry = (struct irte_ga *) ir_data->entry;
3453 	struct irte_ga *ref = (struct irte_ga *) ir_data->ref;
3454 
3455 	if (!AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir) ||
3456 	    !ref || !entry || !entry->lo.fields_vapic.guest_mode)
3457 		return 0;
3458 
3459 	iommu = amd_iommu_rlookup_table[devid];
3460 	if (!iommu)
3461 		return -ENODEV;
3462 
3463 	table = get_irq_table(devid);
3464 	if (!table)
3465 		return -ENODEV;
3466 
3467 	raw_spin_lock_irqsave(&table->lock, flags);
3468 
3469 	if (ref->lo.fields_vapic.guest_mode) {
3470 		if (cpu >= 0) {
3471 			ref->lo.fields_vapic.destination =
3472 						APICID_TO_IRTE_DEST_LO(cpu);
3473 			ref->hi.fields.destination =
3474 						APICID_TO_IRTE_DEST_HI(cpu);
3475 		}
3476 		ref->lo.fields_vapic.is_run = is_run;
3477 		barrier();
3478 	}
3479 
3480 	raw_spin_unlock_irqrestore(&table->lock, flags);
3481 
3482 	iommu_flush_irt(iommu, devid);
3483 	iommu_completion_wait(iommu);
3484 	return 0;
3485 }
3486 EXPORT_SYMBOL(amd_iommu_update_ga);
3487 #endif
3488