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