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