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