xref: /linux/drivers/iommu/intel/dmar.c (revision b77e0ce62d63a761ffb7f7245a215a49f5921c2f)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (c) 2006, Intel Corporation.
4  *
5  * Copyright (C) 2006-2008 Intel Corporation
6  * Author: Ashok Raj <ashok.raj@intel.com>
7  * Author: Shaohua Li <shaohua.li@intel.com>
8  * Author: Anil S Keshavamurthy <anil.s.keshavamurthy@intel.com>
9  *
10  * This file implements early detection/parsing of Remapping Devices
11  * reported to OS through BIOS via DMA remapping reporting (DMAR) ACPI
12  * tables.
13  *
14  * These routines are used by both DMA-remapping and Interrupt-remapping
15  */
16 
17 #define pr_fmt(fmt)     "DMAR: " fmt
18 
19 #include <linux/pci.h>
20 #include <linux/dmar.h>
21 #include <linux/iova.h>
22 #include <linux/intel-iommu.h>
23 #include <linux/timer.h>
24 #include <linux/irq.h>
25 #include <linux/interrupt.h>
26 #include <linux/tboot.h>
27 #include <linux/dmi.h>
28 #include <linux/slab.h>
29 #include <linux/iommu.h>
30 #include <linux/numa.h>
31 #include <linux/limits.h>
32 #include <asm/irq_remapping.h>
33 #include <asm/iommu_table.h>
34 #include <trace/events/intel_iommu.h>
35 
36 #include "../irq_remapping.h"
37 
38 typedef int (*dmar_res_handler_t)(struct acpi_dmar_header *, void *);
39 struct dmar_res_callback {
40 	dmar_res_handler_t	cb[ACPI_DMAR_TYPE_RESERVED];
41 	void			*arg[ACPI_DMAR_TYPE_RESERVED];
42 	bool			ignore_unhandled;
43 	bool			print_entry;
44 };
45 
46 /*
47  * Assumptions:
48  * 1) The hotplug framework guarentees that DMAR unit will be hot-added
49  *    before IO devices managed by that unit.
50  * 2) The hotplug framework guarantees that DMAR unit will be hot-removed
51  *    after IO devices managed by that unit.
52  * 3) Hotplug events are rare.
53  *
54  * Locking rules for DMA and interrupt remapping related global data structures:
55  * 1) Use dmar_global_lock in process context
56  * 2) Use RCU in interrupt context
57  */
58 DECLARE_RWSEM(dmar_global_lock);
59 LIST_HEAD(dmar_drhd_units);
60 
61 struct acpi_table_header * __initdata dmar_tbl;
62 static int dmar_dev_scope_status = 1;
63 static unsigned long dmar_seq_ids[BITS_TO_LONGS(DMAR_UNITS_SUPPORTED)];
64 
65 static int alloc_iommu(struct dmar_drhd_unit *drhd);
66 static void free_iommu(struct intel_iommu *iommu);
67 
68 extern const struct iommu_ops intel_iommu_ops;
69 
70 static void dmar_register_drhd_unit(struct dmar_drhd_unit *drhd)
71 {
72 	/*
73 	 * add INCLUDE_ALL at the tail, so scan the list will find it at
74 	 * the very end.
75 	 */
76 	if (drhd->include_all)
77 		list_add_tail_rcu(&drhd->list, &dmar_drhd_units);
78 	else
79 		list_add_rcu(&drhd->list, &dmar_drhd_units);
80 }
81 
82 void *dmar_alloc_dev_scope(void *start, void *end, int *cnt)
83 {
84 	struct acpi_dmar_device_scope *scope;
85 
86 	*cnt = 0;
87 	while (start < end) {
88 		scope = start;
89 		if (scope->entry_type == ACPI_DMAR_SCOPE_TYPE_NAMESPACE ||
90 		    scope->entry_type == ACPI_DMAR_SCOPE_TYPE_ENDPOINT ||
91 		    scope->entry_type == ACPI_DMAR_SCOPE_TYPE_BRIDGE)
92 			(*cnt)++;
93 		else if (scope->entry_type != ACPI_DMAR_SCOPE_TYPE_IOAPIC &&
94 			scope->entry_type != ACPI_DMAR_SCOPE_TYPE_HPET) {
95 			pr_warn("Unsupported device scope\n");
96 		}
97 		start += scope->length;
98 	}
99 	if (*cnt == 0)
100 		return NULL;
101 
102 	return kcalloc(*cnt, sizeof(struct dmar_dev_scope), GFP_KERNEL);
103 }
104 
105 void dmar_free_dev_scope(struct dmar_dev_scope **devices, int *cnt)
106 {
107 	int i;
108 	struct device *tmp_dev;
109 
110 	if (*devices && *cnt) {
111 		for_each_active_dev_scope(*devices, *cnt, i, tmp_dev)
112 			put_device(tmp_dev);
113 		kfree(*devices);
114 	}
115 
116 	*devices = NULL;
117 	*cnt = 0;
118 }
119 
120 /* Optimize out kzalloc()/kfree() for normal cases */
121 static char dmar_pci_notify_info_buf[64];
122 
123 static struct dmar_pci_notify_info *
124 dmar_alloc_pci_notify_info(struct pci_dev *dev, unsigned long event)
125 {
126 	int level = 0;
127 	size_t size;
128 	struct pci_dev *tmp;
129 	struct dmar_pci_notify_info *info;
130 
131 	BUG_ON(dev->is_virtfn);
132 
133 	/*
134 	 * Ignore devices that have a domain number higher than what can
135 	 * be looked up in DMAR, e.g. VMD subdevices with domain 0x10000
136 	 */
137 	if (pci_domain_nr(dev->bus) > U16_MAX)
138 		return NULL;
139 
140 	/* Only generate path[] for device addition event */
141 	if (event == BUS_NOTIFY_ADD_DEVICE)
142 		for (tmp = dev; tmp; tmp = tmp->bus->self)
143 			level++;
144 
145 	size = struct_size(info, path, level);
146 	if (size <= sizeof(dmar_pci_notify_info_buf)) {
147 		info = (struct dmar_pci_notify_info *)dmar_pci_notify_info_buf;
148 	} else {
149 		info = kzalloc(size, GFP_KERNEL);
150 		if (!info) {
151 			pr_warn("Out of memory when allocating notify_info "
152 				"for %s.\n", pci_name(dev));
153 			if (dmar_dev_scope_status == 0)
154 				dmar_dev_scope_status = -ENOMEM;
155 			return NULL;
156 		}
157 	}
158 
159 	info->event = event;
160 	info->dev = dev;
161 	info->seg = pci_domain_nr(dev->bus);
162 	info->level = level;
163 	if (event == BUS_NOTIFY_ADD_DEVICE) {
164 		for (tmp = dev; tmp; tmp = tmp->bus->self) {
165 			level--;
166 			info->path[level].bus = tmp->bus->number;
167 			info->path[level].device = PCI_SLOT(tmp->devfn);
168 			info->path[level].function = PCI_FUNC(tmp->devfn);
169 			if (pci_is_root_bus(tmp->bus))
170 				info->bus = tmp->bus->number;
171 		}
172 	}
173 
174 	return info;
175 }
176 
177 static inline void dmar_free_pci_notify_info(struct dmar_pci_notify_info *info)
178 {
179 	if ((void *)info != dmar_pci_notify_info_buf)
180 		kfree(info);
181 }
182 
183 static bool dmar_match_pci_path(struct dmar_pci_notify_info *info, int bus,
184 				struct acpi_dmar_pci_path *path, int count)
185 {
186 	int i;
187 
188 	if (info->bus != bus)
189 		goto fallback;
190 	if (info->level != count)
191 		goto fallback;
192 
193 	for (i = 0; i < count; i++) {
194 		if (path[i].device != info->path[i].device ||
195 		    path[i].function != info->path[i].function)
196 			goto fallback;
197 	}
198 
199 	return true;
200 
201 fallback:
202 
203 	if (count != 1)
204 		return false;
205 
206 	i = info->level - 1;
207 	if (bus              == info->path[i].bus &&
208 	    path[0].device   == info->path[i].device &&
209 	    path[0].function == info->path[i].function) {
210 		pr_info(FW_BUG "RMRR entry for device %02x:%02x.%x is broken - applying workaround\n",
211 			bus, path[0].device, path[0].function);
212 		return true;
213 	}
214 
215 	return false;
216 }
217 
218 /* Return: > 0 if match found, 0 if no match found, < 0 if error happens */
219 int dmar_insert_dev_scope(struct dmar_pci_notify_info *info,
220 			  void *start, void*end, u16 segment,
221 			  struct dmar_dev_scope *devices,
222 			  int devices_cnt)
223 {
224 	int i, level;
225 	struct device *tmp, *dev = &info->dev->dev;
226 	struct acpi_dmar_device_scope *scope;
227 	struct acpi_dmar_pci_path *path;
228 
229 	if (segment != info->seg)
230 		return 0;
231 
232 	for (; start < end; start += scope->length) {
233 		scope = start;
234 		if (scope->entry_type != ACPI_DMAR_SCOPE_TYPE_ENDPOINT &&
235 		    scope->entry_type != ACPI_DMAR_SCOPE_TYPE_BRIDGE)
236 			continue;
237 
238 		path = (struct acpi_dmar_pci_path *)(scope + 1);
239 		level = (scope->length - sizeof(*scope)) / sizeof(*path);
240 		if (!dmar_match_pci_path(info, scope->bus, path, level))
241 			continue;
242 
243 		/*
244 		 * We expect devices with endpoint scope to have normal PCI
245 		 * headers, and devices with bridge scope to have bridge PCI
246 		 * headers.  However PCI NTB devices may be listed in the
247 		 * DMAR table with bridge scope, even though they have a
248 		 * normal PCI header.  NTB devices are identified by class
249 		 * "BRIDGE_OTHER" (0680h) - we don't declare a socpe mismatch
250 		 * for this special case.
251 		 */
252 		if ((scope->entry_type == ACPI_DMAR_SCOPE_TYPE_ENDPOINT &&
253 		     info->dev->hdr_type != PCI_HEADER_TYPE_NORMAL) ||
254 		    (scope->entry_type == ACPI_DMAR_SCOPE_TYPE_BRIDGE &&
255 		     (info->dev->hdr_type == PCI_HEADER_TYPE_NORMAL &&
256 		      info->dev->class >> 16 != PCI_BASE_CLASS_BRIDGE))) {
257 			pr_warn("Device scope type does not match for %s\n",
258 				pci_name(info->dev));
259 			return -EINVAL;
260 		}
261 
262 		for_each_dev_scope(devices, devices_cnt, i, tmp)
263 			if (tmp == NULL) {
264 				devices[i].bus = info->dev->bus->number;
265 				devices[i].devfn = info->dev->devfn;
266 				rcu_assign_pointer(devices[i].dev,
267 						   get_device(dev));
268 				return 1;
269 			}
270 		BUG_ON(i >= devices_cnt);
271 	}
272 
273 	return 0;
274 }
275 
276 int dmar_remove_dev_scope(struct dmar_pci_notify_info *info, u16 segment,
277 			  struct dmar_dev_scope *devices, int count)
278 {
279 	int index;
280 	struct device *tmp;
281 
282 	if (info->seg != segment)
283 		return 0;
284 
285 	for_each_active_dev_scope(devices, count, index, tmp)
286 		if (tmp == &info->dev->dev) {
287 			RCU_INIT_POINTER(devices[index].dev, NULL);
288 			synchronize_rcu();
289 			put_device(tmp);
290 			return 1;
291 		}
292 
293 	return 0;
294 }
295 
296 static int dmar_pci_bus_add_dev(struct dmar_pci_notify_info *info)
297 {
298 	int ret = 0;
299 	struct dmar_drhd_unit *dmaru;
300 	struct acpi_dmar_hardware_unit *drhd;
301 
302 	for_each_drhd_unit(dmaru) {
303 		if (dmaru->include_all)
304 			continue;
305 
306 		drhd = container_of(dmaru->hdr,
307 				    struct acpi_dmar_hardware_unit, header);
308 		ret = dmar_insert_dev_scope(info, (void *)(drhd + 1),
309 				((void *)drhd) + drhd->header.length,
310 				dmaru->segment,
311 				dmaru->devices, dmaru->devices_cnt);
312 		if (ret)
313 			break;
314 	}
315 	if (ret >= 0)
316 		ret = dmar_iommu_notify_scope_dev(info);
317 	if (ret < 0 && dmar_dev_scope_status == 0)
318 		dmar_dev_scope_status = ret;
319 
320 	if (ret >= 0)
321 		intel_irq_remap_add_device(info);
322 
323 	return ret;
324 }
325 
326 static void  dmar_pci_bus_del_dev(struct dmar_pci_notify_info *info)
327 {
328 	struct dmar_drhd_unit *dmaru;
329 
330 	for_each_drhd_unit(dmaru)
331 		if (dmar_remove_dev_scope(info, dmaru->segment,
332 			dmaru->devices, dmaru->devices_cnt))
333 			break;
334 	dmar_iommu_notify_scope_dev(info);
335 }
336 
337 static inline void vf_inherit_msi_domain(struct pci_dev *pdev)
338 {
339 	struct pci_dev *physfn = pci_physfn(pdev);
340 
341 	dev_set_msi_domain(&pdev->dev, dev_get_msi_domain(&physfn->dev));
342 }
343 
344 static int dmar_pci_bus_notifier(struct notifier_block *nb,
345 				 unsigned long action, void *data)
346 {
347 	struct pci_dev *pdev = to_pci_dev(data);
348 	struct dmar_pci_notify_info *info;
349 
350 	/* Only care about add/remove events for physical functions.
351 	 * For VFs we actually do the lookup based on the corresponding
352 	 * PF in device_to_iommu() anyway. */
353 	if (pdev->is_virtfn) {
354 		/*
355 		 * Ensure that the VF device inherits the irq domain of the
356 		 * PF device. Ideally the device would inherit the domain
357 		 * from the bus, but DMAR can have multiple units per bus
358 		 * which makes this impossible. The VF 'bus' could inherit
359 		 * from the PF device, but that's yet another x86'sism to
360 		 * inflict on everybody else.
361 		 */
362 		if (action == BUS_NOTIFY_ADD_DEVICE)
363 			vf_inherit_msi_domain(pdev);
364 		return NOTIFY_DONE;
365 	}
366 
367 	if (action != BUS_NOTIFY_ADD_DEVICE &&
368 	    action != BUS_NOTIFY_REMOVED_DEVICE)
369 		return NOTIFY_DONE;
370 
371 	info = dmar_alloc_pci_notify_info(pdev, action);
372 	if (!info)
373 		return NOTIFY_DONE;
374 
375 	down_write(&dmar_global_lock);
376 	if (action == BUS_NOTIFY_ADD_DEVICE)
377 		dmar_pci_bus_add_dev(info);
378 	else if (action == BUS_NOTIFY_REMOVED_DEVICE)
379 		dmar_pci_bus_del_dev(info);
380 	up_write(&dmar_global_lock);
381 
382 	dmar_free_pci_notify_info(info);
383 
384 	return NOTIFY_OK;
385 }
386 
387 static struct notifier_block dmar_pci_bus_nb = {
388 	.notifier_call = dmar_pci_bus_notifier,
389 	.priority = INT_MIN,
390 };
391 
392 static struct dmar_drhd_unit *
393 dmar_find_dmaru(struct acpi_dmar_hardware_unit *drhd)
394 {
395 	struct dmar_drhd_unit *dmaru;
396 
397 	list_for_each_entry_rcu(dmaru, &dmar_drhd_units, list,
398 				dmar_rcu_check())
399 		if (dmaru->segment == drhd->segment &&
400 		    dmaru->reg_base_addr == drhd->address)
401 			return dmaru;
402 
403 	return NULL;
404 }
405 
406 /*
407  * dmar_parse_one_drhd - parses exactly one DMA remapping hardware definition
408  * structure which uniquely represent one DMA remapping hardware unit
409  * present in the platform
410  */
411 static int dmar_parse_one_drhd(struct acpi_dmar_header *header, void *arg)
412 {
413 	struct acpi_dmar_hardware_unit *drhd;
414 	struct dmar_drhd_unit *dmaru;
415 	int ret;
416 
417 	drhd = (struct acpi_dmar_hardware_unit *)header;
418 	dmaru = dmar_find_dmaru(drhd);
419 	if (dmaru)
420 		goto out;
421 
422 	dmaru = kzalloc(sizeof(*dmaru) + header->length, GFP_KERNEL);
423 	if (!dmaru)
424 		return -ENOMEM;
425 
426 	/*
427 	 * If header is allocated from slab by ACPI _DSM method, we need to
428 	 * copy the content because the memory buffer will be freed on return.
429 	 */
430 	dmaru->hdr = (void *)(dmaru + 1);
431 	memcpy(dmaru->hdr, header, header->length);
432 	dmaru->reg_base_addr = drhd->address;
433 	dmaru->segment = drhd->segment;
434 	dmaru->include_all = drhd->flags & 0x1; /* BIT0: INCLUDE_ALL */
435 	dmaru->devices = dmar_alloc_dev_scope((void *)(drhd + 1),
436 					      ((void *)drhd) + drhd->header.length,
437 					      &dmaru->devices_cnt);
438 	if (dmaru->devices_cnt && dmaru->devices == NULL) {
439 		kfree(dmaru);
440 		return -ENOMEM;
441 	}
442 
443 	ret = alloc_iommu(dmaru);
444 	if (ret) {
445 		dmar_free_dev_scope(&dmaru->devices,
446 				    &dmaru->devices_cnt);
447 		kfree(dmaru);
448 		return ret;
449 	}
450 	dmar_register_drhd_unit(dmaru);
451 
452 out:
453 	if (arg)
454 		(*(int *)arg)++;
455 
456 	return 0;
457 }
458 
459 static void dmar_free_drhd(struct dmar_drhd_unit *dmaru)
460 {
461 	if (dmaru->devices && dmaru->devices_cnt)
462 		dmar_free_dev_scope(&dmaru->devices, &dmaru->devices_cnt);
463 	if (dmaru->iommu)
464 		free_iommu(dmaru->iommu);
465 	kfree(dmaru);
466 }
467 
468 static int __init dmar_parse_one_andd(struct acpi_dmar_header *header,
469 				      void *arg)
470 {
471 	struct acpi_dmar_andd *andd = (void *)header;
472 
473 	/* Check for NUL termination within the designated length */
474 	if (strnlen(andd->device_name, header->length - 8) == header->length - 8) {
475 		pr_warn(FW_BUG
476 			   "Your BIOS is broken; ANDD object name is not NUL-terminated\n"
477 			   "BIOS vendor: %s; Ver: %s; Product Version: %s\n",
478 			   dmi_get_system_info(DMI_BIOS_VENDOR),
479 			   dmi_get_system_info(DMI_BIOS_VERSION),
480 			   dmi_get_system_info(DMI_PRODUCT_VERSION));
481 		add_taint(TAINT_FIRMWARE_WORKAROUND, LOCKDEP_STILL_OK);
482 		return -EINVAL;
483 	}
484 	pr_info("ANDD device: %x name: %s\n", andd->device_number,
485 		andd->device_name);
486 
487 	return 0;
488 }
489 
490 #ifdef CONFIG_ACPI_NUMA
491 static int dmar_parse_one_rhsa(struct acpi_dmar_header *header, void *arg)
492 {
493 	struct acpi_dmar_rhsa *rhsa;
494 	struct dmar_drhd_unit *drhd;
495 
496 	rhsa = (struct acpi_dmar_rhsa *)header;
497 	for_each_drhd_unit(drhd) {
498 		if (drhd->reg_base_addr == rhsa->base_address) {
499 			int node = pxm_to_node(rhsa->proximity_domain);
500 
501 			if (!node_online(node))
502 				node = NUMA_NO_NODE;
503 			drhd->iommu->node = node;
504 			return 0;
505 		}
506 	}
507 	pr_warn(FW_BUG
508 		"Your BIOS is broken; RHSA refers to non-existent DMAR unit at %llx\n"
509 		"BIOS vendor: %s; Ver: %s; Product Version: %s\n",
510 		rhsa->base_address,
511 		dmi_get_system_info(DMI_BIOS_VENDOR),
512 		dmi_get_system_info(DMI_BIOS_VERSION),
513 		dmi_get_system_info(DMI_PRODUCT_VERSION));
514 	add_taint(TAINT_FIRMWARE_WORKAROUND, LOCKDEP_STILL_OK);
515 
516 	return 0;
517 }
518 #else
519 #define	dmar_parse_one_rhsa		dmar_res_noop
520 #endif
521 
522 static void
523 dmar_table_print_dmar_entry(struct acpi_dmar_header *header)
524 {
525 	struct acpi_dmar_hardware_unit *drhd;
526 	struct acpi_dmar_reserved_memory *rmrr;
527 	struct acpi_dmar_atsr *atsr;
528 	struct acpi_dmar_rhsa *rhsa;
529 	struct acpi_dmar_satc *satc;
530 
531 	switch (header->type) {
532 	case ACPI_DMAR_TYPE_HARDWARE_UNIT:
533 		drhd = container_of(header, struct acpi_dmar_hardware_unit,
534 				    header);
535 		pr_info("DRHD base: %#016Lx flags: %#x\n",
536 			(unsigned long long)drhd->address, drhd->flags);
537 		break;
538 	case ACPI_DMAR_TYPE_RESERVED_MEMORY:
539 		rmrr = container_of(header, struct acpi_dmar_reserved_memory,
540 				    header);
541 		pr_info("RMRR base: %#016Lx end: %#016Lx\n",
542 			(unsigned long long)rmrr->base_address,
543 			(unsigned long long)rmrr->end_address);
544 		break;
545 	case ACPI_DMAR_TYPE_ROOT_ATS:
546 		atsr = container_of(header, struct acpi_dmar_atsr, header);
547 		pr_info("ATSR flags: %#x\n", atsr->flags);
548 		break;
549 	case ACPI_DMAR_TYPE_HARDWARE_AFFINITY:
550 		rhsa = container_of(header, struct acpi_dmar_rhsa, header);
551 		pr_info("RHSA base: %#016Lx proximity domain: %#x\n",
552 		       (unsigned long long)rhsa->base_address,
553 		       rhsa->proximity_domain);
554 		break;
555 	case ACPI_DMAR_TYPE_NAMESPACE:
556 		/* We don't print this here because we need to sanity-check
557 		   it first. So print it in dmar_parse_one_andd() instead. */
558 		break;
559 	case ACPI_DMAR_TYPE_SATC:
560 		satc = container_of(header, struct acpi_dmar_satc, header);
561 		pr_info("SATC flags: 0x%x\n", satc->flags);
562 		break;
563 	}
564 }
565 
566 /**
567  * dmar_table_detect - checks to see if the platform supports DMAR devices
568  */
569 static int __init dmar_table_detect(void)
570 {
571 	acpi_status status = AE_OK;
572 
573 	/* if we could find DMAR table, then there are DMAR devices */
574 	status = acpi_get_table(ACPI_SIG_DMAR, 0, &dmar_tbl);
575 
576 	if (ACPI_SUCCESS(status) && !dmar_tbl) {
577 		pr_warn("Unable to map DMAR\n");
578 		status = AE_NOT_FOUND;
579 	}
580 
581 	return ACPI_SUCCESS(status) ? 0 : -ENOENT;
582 }
583 
584 static int dmar_walk_remapping_entries(struct acpi_dmar_header *start,
585 				       size_t len, struct dmar_res_callback *cb)
586 {
587 	struct acpi_dmar_header *iter, *next;
588 	struct acpi_dmar_header *end = ((void *)start) + len;
589 
590 	for (iter = start; iter < end; iter = next) {
591 		next = (void *)iter + iter->length;
592 		if (iter->length == 0) {
593 			/* Avoid looping forever on bad ACPI tables */
594 			pr_debug(FW_BUG "Invalid 0-length structure\n");
595 			break;
596 		} else if (next > end) {
597 			/* Avoid passing table end */
598 			pr_warn(FW_BUG "Record passes table end\n");
599 			return -EINVAL;
600 		}
601 
602 		if (cb->print_entry)
603 			dmar_table_print_dmar_entry(iter);
604 
605 		if (iter->type >= ACPI_DMAR_TYPE_RESERVED) {
606 			/* continue for forward compatibility */
607 			pr_debug("Unknown DMAR structure type %d\n",
608 				 iter->type);
609 		} else if (cb->cb[iter->type]) {
610 			int ret;
611 
612 			ret = cb->cb[iter->type](iter, cb->arg[iter->type]);
613 			if (ret)
614 				return ret;
615 		} else if (!cb->ignore_unhandled) {
616 			pr_warn("No handler for DMAR structure type %d\n",
617 				iter->type);
618 			return -EINVAL;
619 		}
620 	}
621 
622 	return 0;
623 }
624 
625 static inline int dmar_walk_dmar_table(struct acpi_table_dmar *dmar,
626 				       struct dmar_res_callback *cb)
627 {
628 	return dmar_walk_remapping_entries((void *)(dmar + 1),
629 			dmar->header.length - sizeof(*dmar), cb);
630 }
631 
632 /**
633  * parse_dmar_table - parses the DMA reporting table
634  */
635 static int __init
636 parse_dmar_table(void)
637 {
638 	struct acpi_table_dmar *dmar;
639 	int drhd_count = 0;
640 	int ret;
641 	struct dmar_res_callback cb = {
642 		.print_entry = true,
643 		.ignore_unhandled = true,
644 		.arg[ACPI_DMAR_TYPE_HARDWARE_UNIT] = &drhd_count,
645 		.cb[ACPI_DMAR_TYPE_HARDWARE_UNIT] = &dmar_parse_one_drhd,
646 		.cb[ACPI_DMAR_TYPE_RESERVED_MEMORY] = &dmar_parse_one_rmrr,
647 		.cb[ACPI_DMAR_TYPE_ROOT_ATS] = &dmar_parse_one_atsr,
648 		.cb[ACPI_DMAR_TYPE_HARDWARE_AFFINITY] = &dmar_parse_one_rhsa,
649 		.cb[ACPI_DMAR_TYPE_NAMESPACE] = &dmar_parse_one_andd,
650 		.cb[ACPI_DMAR_TYPE_SATC] = &dmar_parse_one_satc,
651 	};
652 
653 	/*
654 	 * Do it again, earlier dmar_tbl mapping could be mapped with
655 	 * fixed map.
656 	 */
657 	dmar_table_detect();
658 
659 	/*
660 	 * ACPI tables may not be DMA protected by tboot, so use DMAR copy
661 	 * SINIT saved in SinitMleData in TXT heap (which is DMA protected)
662 	 */
663 	dmar_tbl = tboot_get_dmar_table(dmar_tbl);
664 
665 	dmar = (struct acpi_table_dmar *)dmar_tbl;
666 	if (!dmar)
667 		return -ENODEV;
668 
669 	if (dmar->width < PAGE_SHIFT - 1) {
670 		pr_warn("Invalid DMAR haw\n");
671 		return -EINVAL;
672 	}
673 
674 	pr_info("Host address width %d\n", dmar->width + 1);
675 	ret = dmar_walk_dmar_table(dmar, &cb);
676 	if (ret == 0 && drhd_count == 0)
677 		pr_warn(FW_BUG "No DRHD structure found in DMAR table\n");
678 
679 	return ret;
680 }
681 
682 static int dmar_pci_device_match(struct dmar_dev_scope devices[],
683 				 int cnt, struct pci_dev *dev)
684 {
685 	int index;
686 	struct device *tmp;
687 
688 	while (dev) {
689 		for_each_active_dev_scope(devices, cnt, index, tmp)
690 			if (dev_is_pci(tmp) && dev == to_pci_dev(tmp))
691 				return 1;
692 
693 		/* Check our parent */
694 		dev = dev->bus->self;
695 	}
696 
697 	return 0;
698 }
699 
700 struct dmar_drhd_unit *
701 dmar_find_matched_drhd_unit(struct pci_dev *dev)
702 {
703 	struct dmar_drhd_unit *dmaru;
704 	struct acpi_dmar_hardware_unit *drhd;
705 
706 	dev = pci_physfn(dev);
707 
708 	rcu_read_lock();
709 	for_each_drhd_unit(dmaru) {
710 		drhd = container_of(dmaru->hdr,
711 				    struct acpi_dmar_hardware_unit,
712 				    header);
713 
714 		if (dmaru->include_all &&
715 		    drhd->segment == pci_domain_nr(dev->bus))
716 			goto out;
717 
718 		if (dmar_pci_device_match(dmaru->devices,
719 					  dmaru->devices_cnt, dev))
720 			goto out;
721 	}
722 	dmaru = NULL;
723 out:
724 	rcu_read_unlock();
725 
726 	return dmaru;
727 }
728 
729 static void __init dmar_acpi_insert_dev_scope(u8 device_number,
730 					      struct acpi_device *adev)
731 {
732 	struct dmar_drhd_unit *dmaru;
733 	struct acpi_dmar_hardware_unit *drhd;
734 	struct acpi_dmar_device_scope *scope;
735 	struct device *tmp;
736 	int i;
737 	struct acpi_dmar_pci_path *path;
738 
739 	for_each_drhd_unit(dmaru) {
740 		drhd = container_of(dmaru->hdr,
741 				    struct acpi_dmar_hardware_unit,
742 				    header);
743 
744 		for (scope = (void *)(drhd + 1);
745 		     (unsigned long)scope < ((unsigned long)drhd) + drhd->header.length;
746 		     scope = ((void *)scope) + scope->length) {
747 			if (scope->entry_type != ACPI_DMAR_SCOPE_TYPE_NAMESPACE)
748 				continue;
749 			if (scope->enumeration_id != device_number)
750 				continue;
751 
752 			path = (void *)(scope + 1);
753 			pr_info("ACPI device \"%s\" under DMAR at %llx as %02x:%02x.%d\n",
754 				dev_name(&adev->dev), dmaru->reg_base_addr,
755 				scope->bus, path->device, path->function);
756 			for_each_dev_scope(dmaru->devices, dmaru->devices_cnt, i, tmp)
757 				if (tmp == NULL) {
758 					dmaru->devices[i].bus = scope->bus;
759 					dmaru->devices[i].devfn = PCI_DEVFN(path->device,
760 									    path->function);
761 					rcu_assign_pointer(dmaru->devices[i].dev,
762 							   get_device(&adev->dev));
763 					return;
764 				}
765 			BUG_ON(i >= dmaru->devices_cnt);
766 		}
767 	}
768 	pr_warn("No IOMMU scope found for ANDD enumeration ID %d (%s)\n",
769 		device_number, dev_name(&adev->dev));
770 }
771 
772 static int __init dmar_acpi_dev_scope_init(void)
773 {
774 	struct acpi_dmar_andd *andd;
775 
776 	if (dmar_tbl == NULL)
777 		return -ENODEV;
778 
779 	for (andd = (void *)dmar_tbl + sizeof(struct acpi_table_dmar);
780 	     ((unsigned long)andd) < ((unsigned long)dmar_tbl) + dmar_tbl->length;
781 	     andd = ((void *)andd) + andd->header.length) {
782 		if (andd->header.type == ACPI_DMAR_TYPE_NAMESPACE) {
783 			acpi_handle h;
784 			struct acpi_device *adev;
785 
786 			if (!ACPI_SUCCESS(acpi_get_handle(ACPI_ROOT_OBJECT,
787 							  andd->device_name,
788 							  &h))) {
789 				pr_err("Failed to find handle for ACPI object %s\n",
790 				       andd->device_name);
791 				continue;
792 			}
793 			if (acpi_bus_get_device(h, &adev)) {
794 				pr_err("Failed to get device for ACPI object %s\n",
795 				       andd->device_name);
796 				continue;
797 			}
798 			dmar_acpi_insert_dev_scope(andd->device_number, adev);
799 		}
800 	}
801 	return 0;
802 }
803 
804 int __init dmar_dev_scope_init(void)
805 {
806 	struct pci_dev *dev = NULL;
807 	struct dmar_pci_notify_info *info;
808 
809 	if (dmar_dev_scope_status != 1)
810 		return dmar_dev_scope_status;
811 
812 	if (list_empty(&dmar_drhd_units)) {
813 		dmar_dev_scope_status = -ENODEV;
814 	} else {
815 		dmar_dev_scope_status = 0;
816 
817 		dmar_acpi_dev_scope_init();
818 
819 		for_each_pci_dev(dev) {
820 			if (dev->is_virtfn)
821 				continue;
822 
823 			info = dmar_alloc_pci_notify_info(dev,
824 					BUS_NOTIFY_ADD_DEVICE);
825 			if (!info) {
826 				return dmar_dev_scope_status;
827 			} else {
828 				dmar_pci_bus_add_dev(info);
829 				dmar_free_pci_notify_info(info);
830 			}
831 		}
832 	}
833 
834 	return dmar_dev_scope_status;
835 }
836 
837 void __init dmar_register_bus_notifier(void)
838 {
839 	bus_register_notifier(&pci_bus_type, &dmar_pci_bus_nb);
840 }
841 
842 
843 int __init dmar_table_init(void)
844 {
845 	static int dmar_table_initialized;
846 	int ret;
847 
848 	if (dmar_table_initialized == 0) {
849 		ret = parse_dmar_table();
850 		if (ret < 0) {
851 			if (ret != -ENODEV)
852 				pr_info("Parse DMAR table failure.\n");
853 		} else  if (list_empty(&dmar_drhd_units)) {
854 			pr_info("No DMAR devices found\n");
855 			ret = -ENODEV;
856 		}
857 
858 		if (ret < 0)
859 			dmar_table_initialized = ret;
860 		else
861 			dmar_table_initialized = 1;
862 	}
863 
864 	return dmar_table_initialized < 0 ? dmar_table_initialized : 0;
865 }
866 
867 static void warn_invalid_dmar(u64 addr, const char *message)
868 {
869 	pr_warn_once(FW_BUG
870 		"Your BIOS is broken; DMAR reported at address %llx%s!\n"
871 		"BIOS vendor: %s; Ver: %s; Product Version: %s\n",
872 		addr, message,
873 		dmi_get_system_info(DMI_BIOS_VENDOR),
874 		dmi_get_system_info(DMI_BIOS_VERSION),
875 		dmi_get_system_info(DMI_PRODUCT_VERSION));
876 	add_taint(TAINT_FIRMWARE_WORKAROUND, LOCKDEP_STILL_OK);
877 }
878 
879 static int __ref
880 dmar_validate_one_drhd(struct acpi_dmar_header *entry, void *arg)
881 {
882 	struct acpi_dmar_hardware_unit *drhd;
883 	void __iomem *addr;
884 	u64 cap, ecap;
885 
886 	drhd = (void *)entry;
887 	if (!drhd->address) {
888 		warn_invalid_dmar(0, "");
889 		return -EINVAL;
890 	}
891 
892 	if (arg)
893 		addr = ioremap(drhd->address, VTD_PAGE_SIZE);
894 	else
895 		addr = early_ioremap(drhd->address, VTD_PAGE_SIZE);
896 	if (!addr) {
897 		pr_warn("Can't validate DRHD address: %llx\n", drhd->address);
898 		return -EINVAL;
899 	}
900 
901 	cap = dmar_readq(addr + DMAR_CAP_REG);
902 	ecap = dmar_readq(addr + DMAR_ECAP_REG);
903 
904 	if (arg)
905 		iounmap(addr);
906 	else
907 		early_iounmap(addr, VTD_PAGE_SIZE);
908 
909 	if (cap == (uint64_t)-1 && ecap == (uint64_t)-1) {
910 		warn_invalid_dmar(drhd->address, " returns all ones");
911 		return -EINVAL;
912 	}
913 
914 	return 0;
915 }
916 
917 int __init detect_intel_iommu(void)
918 {
919 	int ret;
920 	struct dmar_res_callback validate_drhd_cb = {
921 		.cb[ACPI_DMAR_TYPE_HARDWARE_UNIT] = &dmar_validate_one_drhd,
922 		.ignore_unhandled = true,
923 	};
924 
925 	down_write(&dmar_global_lock);
926 	ret = dmar_table_detect();
927 	if (!ret)
928 		ret = dmar_walk_dmar_table((struct acpi_table_dmar *)dmar_tbl,
929 					   &validate_drhd_cb);
930 	if (!ret && !no_iommu && !iommu_detected &&
931 	    (!dmar_disabled || dmar_platform_optin())) {
932 		iommu_detected = 1;
933 		/* Make sure ACS will be enabled */
934 		pci_request_acs();
935 	}
936 
937 #ifdef CONFIG_X86
938 	if (!ret) {
939 		x86_init.iommu.iommu_init = intel_iommu_init;
940 		x86_platform.iommu_shutdown = intel_iommu_shutdown;
941 	}
942 
943 #endif
944 
945 	if (dmar_tbl) {
946 		acpi_put_table(dmar_tbl);
947 		dmar_tbl = NULL;
948 	}
949 	up_write(&dmar_global_lock);
950 
951 	return ret ? ret : 1;
952 }
953 
954 static void unmap_iommu(struct intel_iommu *iommu)
955 {
956 	iounmap(iommu->reg);
957 	release_mem_region(iommu->reg_phys, iommu->reg_size);
958 }
959 
960 /**
961  * map_iommu: map the iommu's registers
962  * @iommu: the iommu to map
963  * @phys_addr: the physical address of the base resgister
964  *
965  * Memory map the iommu's registers.  Start w/ a single page, and
966  * possibly expand if that turns out to be insufficent.
967  */
968 static int map_iommu(struct intel_iommu *iommu, u64 phys_addr)
969 {
970 	int map_size, err=0;
971 
972 	iommu->reg_phys = phys_addr;
973 	iommu->reg_size = VTD_PAGE_SIZE;
974 
975 	if (!request_mem_region(iommu->reg_phys, iommu->reg_size, iommu->name)) {
976 		pr_err("Can't reserve memory\n");
977 		err = -EBUSY;
978 		goto out;
979 	}
980 
981 	iommu->reg = ioremap(iommu->reg_phys, iommu->reg_size);
982 	if (!iommu->reg) {
983 		pr_err("Can't map the region\n");
984 		err = -ENOMEM;
985 		goto release;
986 	}
987 
988 	iommu->cap = dmar_readq(iommu->reg + DMAR_CAP_REG);
989 	iommu->ecap = dmar_readq(iommu->reg + DMAR_ECAP_REG);
990 
991 	if (iommu->cap == (uint64_t)-1 && iommu->ecap == (uint64_t)-1) {
992 		err = -EINVAL;
993 		warn_invalid_dmar(phys_addr, " returns all ones");
994 		goto unmap;
995 	}
996 	if (ecap_vcs(iommu->ecap))
997 		iommu->vccap = dmar_readq(iommu->reg + DMAR_VCCAP_REG);
998 
999 	/* the registers might be more than one page */
1000 	map_size = max_t(int, ecap_max_iotlb_offset(iommu->ecap),
1001 			 cap_max_fault_reg_offset(iommu->cap));
1002 	map_size = VTD_PAGE_ALIGN(map_size);
1003 	if (map_size > iommu->reg_size) {
1004 		iounmap(iommu->reg);
1005 		release_mem_region(iommu->reg_phys, iommu->reg_size);
1006 		iommu->reg_size = map_size;
1007 		if (!request_mem_region(iommu->reg_phys, iommu->reg_size,
1008 					iommu->name)) {
1009 			pr_err("Can't reserve memory\n");
1010 			err = -EBUSY;
1011 			goto out;
1012 		}
1013 		iommu->reg = ioremap(iommu->reg_phys, iommu->reg_size);
1014 		if (!iommu->reg) {
1015 			pr_err("Can't map the region\n");
1016 			err = -ENOMEM;
1017 			goto release;
1018 		}
1019 	}
1020 	err = 0;
1021 	goto out;
1022 
1023 unmap:
1024 	iounmap(iommu->reg);
1025 release:
1026 	release_mem_region(iommu->reg_phys, iommu->reg_size);
1027 out:
1028 	return err;
1029 }
1030 
1031 static int dmar_alloc_seq_id(struct intel_iommu *iommu)
1032 {
1033 	iommu->seq_id = find_first_zero_bit(dmar_seq_ids,
1034 					    DMAR_UNITS_SUPPORTED);
1035 	if (iommu->seq_id >= DMAR_UNITS_SUPPORTED) {
1036 		iommu->seq_id = -1;
1037 	} else {
1038 		set_bit(iommu->seq_id, dmar_seq_ids);
1039 		sprintf(iommu->name, "dmar%d", iommu->seq_id);
1040 	}
1041 
1042 	return iommu->seq_id;
1043 }
1044 
1045 static void dmar_free_seq_id(struct intel_iommu *iommu)
1046 {
1047 	if (iommu->seq_id >= 0) {
1048 		clear_bit(iommu->seq_id, dmar_seq_ids);
1049 		iommu->seq_id = -1;
1050 	}
1051 }
1052 
1053 static int alloc_iommu(struct dmar_drhd_unit *drhd)
1054 {
1055 	struct intel_iommu *iommu;
1056 	u32 ver, sts;
1057 	int agaw = -1;
1058 	int msagaw = -1;
1059 	int err;
1060 
1061 	if (!drhd->reg_base_addr) {
1062 		warn_invalid_dmar(0, "");
1063 		return -EINVAL;
1064 	}
1065 
1066 	iommu = kzalloc(sizeof(*iommu), GFP_KERNEL);
1067 	if (!iommu)
1068 		return -ENOMEM;
1069 
1070 	if (dmar_alloc_seq_id(iommu) < 0) {
1071 		pr_err("Failed to allocate seq_id\n");
1072 		err = -ENOSPC;
1073 		goto error;
1074 	}
1075 
1076 	err = map_iommu(iommu, drhd->reg_base_addr);
1077 	if (err) {
1078 		pr_err("Failed to map %s\n", iommu->name);
1079 		goto error_free_seq_id;
1080 	}
1081 
1082 	err = -EINVAL;
1083 	if (cap_sagaw(iommu->cap) == 0) {
1084 		pr_info("%s: No supported address widths. Not attempting DMA translation.\n",
1085 			iommu->name);
1086 		drhd->ignored = 1;
1087 	}
1088 
1089 	if (!drhd->ignored) {
1090 		agaw = iommu_calculate_agaw(iommu);
1091 		if (agaw < 0) {
1092 			pr_err("Cannot get a valid agaw for iommu (seq_id = %d)\n",
1093 			       iommu->seq_id);
1094 			drhd->ignored = 1;
1095 		}
1096 	}
1097 	if (!drhd->ignored) {
1098 		msagaw = iommu_calculate_max_sagaw(iommu);
1099 		if (msagaw < 0) {
1100 			pr_err("Cannot get a valid max agaw for iommu (seq_id = %d)\n",
1101 			       iommu->seq_id);
1102 			drhd->ignored = 1;
1103 			agaw = -1;
1104 		}
1105 	}
1106 	iommu->agaw = agaw;
1107 	iommu->msagaw = msagaw;
1108 	iommu->segment = drhd->segment;
1109 
1110 	iommu->node = NUMA_NO_NODE;
1111 
1112 	ver = readl(iommu->reg + DMAR_VER_REG);
1113 	pr_info("%s: reg_base_addr %llx ver %d:%d cap %llx ecap %llx\n",
1114 		iommu->name,
1115 		(unsigned long long)drhd->reg_base_addr,
1116 		DMAR_VER_MAJOR(ver), DMAR_VER_MINOR(ver),
1117 		(unsigned long long)iommu->cap,
1118 		(unsigned long long)iommu->ecap);
1119 
1120 	/* Reflect status in gcmd */
1121 	sts = readl(iommu->reg + DMAR_GSTS_REG);
1122 	if (sts & DMA_GSTS_IRES)
1123 		iommu->gcmd |= DMA_GCMD_IRE;
1124 	if (sts & DMA_GSTS_TES)
1125 		iommu->gcmd |= DMA_GCMD_TE;
1126 	if (sts & DMA_GSTS_QIES)
1127 		iommu->gcmd |= DMA_GCMD_QIE;
1128 
1129 	raw_spin_lock_init(&iommu->register_lock);
1130 
1131 	/*
1132 	 * This is only for hotplug; at boot time intel_iommu_enabled won't
1133 	 * be set yet. When intel_iommu_init() runs, it registers the units
1134 	 * present at boot time, then sets intel_iommu_enabled.
1135 	 */
1136 	if (intel_iommu_enabled && !drhd->ignored) {
1137 		err = iommu_device_sysfs_add(&iommu->iommu, NULL,
1138 					     intel_iommu_groups,
1139 					     "%s", iommu->name);
1140 		if (err)
1141 			goto err_unmap;
1142 
1143 		iommu_device_set_ops(&iommu->iommu, &intel_iommu_ops);
1144 
1145 		err = iommu_device_register(&iommu->iommu);
1146 		if (err)
1147 			goto err_unmap;
1148 	}
1149 
1150 	drhd->iommu = iommu;
1151 	iommu->drhd = drhd;
1152 
1153 	return 0;
1154 
1155 err_unmap:
1156 	unmap_iommu(iommu);
1157 error_free_seq_id:
1158 	dmar_free_seq_id(iommu);
1159 error:
1160 	kfree(iommu);
1161 	return err;
1162 }
1163 
1164 static void free_iommu(struct intel_iommu *iommu)
1165 {
1166 	if (intel_iommu_enabled && !iommu->drhd->ignored) {
1167 		iommu_device_unregister(&iommu->iommu);
1168 		iommu_device_sysfs_remove(&iommu->iommu);
1169 	}
1170 
1171 	if (iommu->irq) {
1172 		if (iommu->pr_irq) {
1173 			free_irq(iommu->pr_irq, iommu);
1174 			dmar_free_hwirq(iommu->pr_irq);
1175 			iommu->pr_irq = 0;
1176 		}
1177 		free_irq(iommu->irq, iommu);
1178 		dmar_free_hwirq(iommu->irq);
1179 		iommu->irq = 0;
1180 	}
1181 
1182 	if (iommu->qi) {
1183 		free_page((unsigned long)iommu->qi->desc);
1184 		kfree(iommu->qi->desc_status);
1185 		kfree(iommu->qi);
1186 	}
1187 
1188 	if (iommu->reg)
1189 		unmap_iommu(iommu);
1190 
1191 	dmar_free_seq_id(iommu);
1192 	kfree(iommu);
1193 }
1194 
1195 /*
1196  * Reclaim all the submitted descriptors which have completed its work.
1197  */
1198 static inline void reclaim_free_desc(struct q_inval *qi)
1199 {
1200 	while (qi->desc_status[qi->free_tail] == QI_DONE ||
1201 	       qi->desc_status[qi->free_tail] == QI_ABORT) {
1202 		qi->desc_status[qi->free_tail] = QI_FREE;
1203 		qi->free_tail = (qi->free_tail + 1) % QI_LENGTH;
1204 		qi->free_cnt++;
1205 	}
1206 }
1207 
1208 static int qi_check_fault(struct intel_iommu *iommu, int index, int wait_index)
1209 {
1210 	u32 fault;
1211 	int head, tail;
1212 	struct q_inval *qi = iommu->qi;
1213 	int shift = qi_shift(iommu);
1214 
1215 	if (qi->desc_status[wait_index] == QI_ABORT)
1216 		return -EAGAIN;
1217 
1218 	fault = readl(iommu->reg + DMAR_FSTS_REG);
1219 
1220 	/*
1221 	 * If IQE happens, the head points to the descriptor associated
1222 	 * with the error. No new descriptors are fetched until the IQE
1223 	 * is cleared.
1224 	 */
1225 	if (fault & DMA_FSTS_IQE) {
1226 		head = readl(iommu->reg + DMAR_IQH_REG);
1227 		if ((head >> shift) == index) {
1228 			struct qi_desc *desc = qi->desc + head;
1229 
1230 			/*
1231 			 * desc->qw2 and desc->qw3 are either reserved or
1232 			 * used by software as private data. We won't print
1233 			 * out these two qw's for security consideration.
1234 			 */
1235 			pr_err("VT-d detected invalid descriptor: qw0 = %llx, qw1 = %llx\n",
1236 			       (unsigned long long)desc->qw0,
1237 			       (unsigned long long)desc->qw1);
1238 			memcpy(desc, qi->desc + (wait_index << shift),
1239 			       1 << shift);
1240 			writel(DMA_FSTS_IQE, iommu->reg + DMAR_FSTS_REG);
1241 			return -EINVAL;
1242 		}
1243 	}
1244 
1245 	/*
1246 	 * If ITE happens, all pending wait_desc commands are aborted.
1247 	 * No new descriptors are fetched until the ITE is cleared.
1248 	 */
1249 	if (fault & DMA_FSTS_ITE) {
1250 		head = readl(iommu->reg + DMAR_IQH_REG);
1251 		head = ((head >> shift) - 1 + QI_LENGTH) % QI_LENGTH;
1252 		head |= 1;
1253 		tail = readl(iommu->reg + DMAR_IQT_REG);
1254 		tail = ((tail >> shift) - 1 + QI_LENGTH) % QI_LENGTH;
1255 
1256 		writel(DMA_FSTS_ITE, iommu->reg + DMAR_FSTS_REG);
1257 
1258 		do {
1259 			if (qi->desc_status[head] == QI_IN_USE)
1260 				qi->desc_status[head] = QI_ABORT;
1261 			head = (head - 2 + QI_LENGTH) % QI_LENGTH;
1262 		} while (head != tail);
1263 
1264 		if (qi->desc_status[wait_index] == QI_ABORT)
1265 			return -EAGAIN;
1266 	}
1267 
1268 	if (fault & DMA_FSTS_ICE)
1269 		writel(DMA_FSTS_ICE, iommu->reg + DMAR_FSTS_REG);
1270 
1271 	return 0;
1272 }
1273 
1274 /*
1275  * Function to submit invalidation descriptors of all types to the queued
1276  * invalidation interface(QI). Multiple descriptors can be submitted at a
1277  * time, a wait descriptor will be appended to each submission to ensure
1278  * hardware has completed the invalidation before return. Wait descriptors
1279  * can be part of the submission but it will not be polled for completion.
1280  */
1281 int qi_submit_sync(struct intel_iommu *iommu, struct qi_desc *desc,
1282 		   unsigned int count, unsigned long options)
1283 {
1284 	struct q_inval *qi = iommu->qi;
1285 	struct qi_desc wait_desc;
1286 	int wait_index, index;
1287 	unsigned long flags;
1288 	int offset, shift;
1289 	int rc, i;
1290 
1291 	if (!qi)
1292 		return 0;
1293 
1294 restart:
1295 	rc = 0;
1296 
1297 	raw_spin_lock_irqsave(&qi->q_lock, flags);
1298 	/*
1299 	 * Check if we have enough empty slots in the queue to submit,
1300 	 * the calculation is based on:
1301 	 * # of desc + 1 wait desc + 1 space between head and tail
1302 	 */
1303 	while (qi->free_cnt < count + 2) {
1304 		raw_spin_unlock_irqrestore(&qi->q_lock, flags);
1305 		cpu_relax();
1306 		raw_spin_lock_irqsave(&qi->q_lock, flags);
1307 	}
1308 
1309 	index = qi->free_head;
1310 	wait_index = (index + count) % QI_LENGTH;
1311 	shift = qi_shift(iommu);
1312 
1313 	for (i = 0; i < count; i++) {
1314 		offset = ((index + i) % QI_LENGTH) << shift;
1315 		memcpy(qi->desc + offset, &desc[i], 1 << shift);
1316 		qi->desc_status[(index + i) % QI_LENGTH] = QI_IN_USE;
1317 		trace_qi_submit(iommu, desc[i].qw0, desc[i].qw1,
1318 				desc[i].qw2, desc[i].qw3);
1319 	}
1320 	qi->desc_status[wait_index] = QI_IN_USE;
1321 
1322 	wait_desc.qw0 = QI_IWD_STATUS_DATA(QI_DONE) |
1323 			QI_IWD_STATUS_WRITE | QI_IWD_TYPE;
1324 	if (options & QI_OPT_WAIT_DRAIN)
1325 		wait_desc.qw0 |= QI_IWD_PRQ_DRAIN;
1326 	wait_desc.qw1 = virt_to_phys(&qi->desc_status[wait_index]);
1327 	wait_desc.qw2 = 0;
1328 	wait_desc.qw3 = 0;
1329 
1330 	offset = wait_index << shift;
1331 	memcpy(qi->desc + offset, &wait_desc, 1 << shift);
1332 
1333 	qi->free_head = (qi->free_head + count + 1) % QI_LENGTH;
1334 	qi->free_cnt -= count + 1;
1335 
1336 	/*
1337 	 * update the HW tail register indicating the presence of
1338 	 * new descriptors.
1339 	 */
1340 	writel(qi->free_head << shift, iommu->reg + DMAR_IQT_REG);
1341 
1342 	while (qi->desc_status[wait_index] != QI_DONE) {
1343 		/*
1344 		 * We will leave the interrupts disabled, to prevent interrupt
1345 		 * context to queue another cmd while a cmd is already submitted
1346 		 * and waiting for completion on this cpu. This is to avoid
1347 		 * a deadlock where the interrupt context can wait indefinitely
1348 		 * for free slots in the queue.
1349 		 */
1350 		rc = qi_check_fault(iommu, index, wait_index);
1351 		if (rc)
1352 			break;
1353 
1354 		raw_spin_unlock(&qi->q_lock);
1355 		cpu_relax();
1356 		raw_spin_lock(&qi->q_lock);
1357 	}
1358 
1359 	for (i = 0; i < count; i++)
1360 		qi->desc_status[(index + i) % QI_LENGTH] = QI_DONE;
1361 
1362 	reclaim_free_desc(qi);
1363 	raw_spin_unlock_irqrestore(&qi->q_lock, flags);
1364 
1365 	if (rc == -EAGAIN)
1366 		goto restart;
1367 
1368 	return rc;
1369 }
1370 
1371 /*
1372  * Flush the global interrupt entry cache.
1373  */
1374 void qi_global_iec(struct intel_iommu *iommu)
1375 {
1376 	struct qi_desc desc;
1377 
1378 	desc.qw0 = QI_IEC_TYPE;
1379 	desc.qw1 = 0;
1380 	desc.qw2 = 0;
1381 	desc.qw3 = 0;
1382 
1383 	/* should never fail */
1384 	qi_submit_sync(iommu, &desc, 1, 0);
1385 }
1386 
1387 void qi_flush_context(struct intel_iommu *iommu, u16 did, u16 sid, u8 fm,
1388 		      u64 type)
1389 {
1390 	struct qi_desc desc;
1391 
1392 	desc.qw0 = QI_CC_FM(fm) | QI_CC_SID(sid) | QI_CC_DID(did)
1393 			| QI_CC_GRAN(type) | QI_CC_TYPE;
1394 	desc.qw1 = 0;
1395 	desc.qw2 = 0;
1396 	desc.qw3 = 0;
1397 
1398 	qi_submit_sync(iommu, &desc, 1, 0);
1399 }
1400 
1401 void qi_flush_iotlb(struct intel_iommu *iommu, u16 did, u64 addr,
1402 		    unsigned int size_order, u64 type)
1403 {
1404 	u8 dw = 0, dr = 0;
1405 
1406 	struct qi_desc desc;
1407 	int ih = 0;
1408 
1409 	if (cap_write_drain(iommu->cap))
1410 		dw = 1;
1411 
1412 	if (cap_read_drain(iommu->cap))
1413 		dr = 1;
1414 
1415 	desc.qw0 = QI_IOTLB_DID(did) | QI_IOTLB_DR(dr) | QI_IOTLB_DW(dw)
1416 		| QI_IOTLB_GRAN(type) | QI_IOTLB_TYPE;
1417 	desc.qw1 = QI_IOTLB_ADDR(addr) | QI_IOTLB_IH(ih)
1418 		| QI_IOTLB_AM(size_order);
1419 	desc.qw2 = 0;
1420 	desc.qw3 = 0;
1421 
1422 	qi_submit_sync(iommu, &desc, 1, 0);
1423 }
1424 
1425 void qi_flush_dev_iotlb(struct intel_iommu *iommu, u16 sid, u16 pfsid,
1426 			u16 qdep, u64 addr, unsigned mask)
1427 {
1428 	struct qi_desc desc;
1429 
1430 	if (mask) {
1431 		addr |= (1ULL << (VTD_PAGE_SHIFT + mask - 1)) - 1;
1432 		desc.qw1 = QI_DEV_IOTLB_ADDR(addr) | QI_DEV_IOTLB_SIZE;
1433 	} else
1434 		desc.qw1 = QI_DEV_IOTLB_ADDR(addr);
1435 
1436 	if (qdep >= QI_DEV_IOTLB_MAX_INVS)
1437 		qdep = 0;
1438 
1439 	desc.qw0 = QI_DEV_IOTLB_SID(sid) | QI_DEV_IOTLB_QDEP(qdep) |
1440 		   QI_DIOTLB_TYPE | QI_DEV_IOTLB_PFSID(pfsid);
1441 	desc.qw2 = 0;
1442 	desc.qw3 = 0;
1443 
1444 	qi_submit_sync(iommu, &desc, 1, 0);
1445 }
1446 
1447 /* PASID-based IOTLB invalidation */
1448 void qi_flush_piotlb(struct intel_iommu *iommu, u16 did, u32 pasid, u64 addr,
1449 		     unsigned long npages, bool ih)
1450 {
1451 	struct qi_desc desc = {.qw2 = 0, .qw3 = 0};
1452 
1453 	/*
1454 	 * npages == -1 means a PASID-selective invalidation, otherwise,
1455 	 * a positive value for Page-selective-within-PASID invalidation.
1456 	 * 0 is not a valid input.
1457 	 */
1458 	if (WARN_ON(!npages)) {
1459 		pr_err("Invalid input npages = %ld\n", npages);
1460 		return;
1461 	}
1462 
1463 	if (npages == -1) {
1464 		desc.qw0 = QI_EIOTLB_PASID(pasid) |
1465 				QI_EIOTLB_DID(did) |
1466 				QI_EIOTLB_GRAN(QI_GRAN_NONG_PASID) |
1467 				QI_EIOTLB_TYPE;
1468 		desc.qw1 = 0;
1469 	} else {
1470 		int mask = ilog2(__roundup_pow_of_two(npages));
1471 		unsigned long align = (1ULL << (VTD_PAGE_SHIFT + mask));
1472 
1473 		if (WARN_ON_ONCE(!IS_ALIGNED(addr, align)))
1474 			addr = ALIGN_DOWN(addr, align);
1475 
1476 		desc.qw0 = QI_EIOTLB_PASID(pasid) |
1477 				QI_EIOTLB_DID(did) |
1478 				QI_EIOTLB_GRAN(QI_GRAN_PSI_PASID) |
1479 				QI_EIOTLB_TYPE;
1480 		desc.qw1 = QI_EIOTLB_ADDR(addr) |
1481 				QI_EIOTLB_IH(ih) |
1482 				QI_EIOTLB_AM(mask);
1483 	}
1484 
1485 	qi_submit_sync(iommu, &desc, 1, 0);
1486 }
1487 
1488 /* PASID-based device IOTLB Invalidate */
1489 void qi_flush_dev_iotlb_pasid(struct intel_iommu *iommu, u16 sid, u16 pfsid,
1490 			      u32 pasid,  u16 qdep, u64 addr, unsigned int size_order)
1491 {
1492 	unsigned long mask = 1UL << (VTD_PAGE_SHIFT + size_order - 1);
1493 	struct qi_desc desc = {.qw1 = 0, .qw2 = 0, .qw3 = 0};
1494 
1495 	desc.qw0 = QI_DEV_EIOTLB_PASID(pasid) | QI_DEV_EIOTLB_SID(sid) |
1496 		QI_DEV_EIOTLB_QDEP(qdep) | QI_DEIOTLB_TYPE |
1497 		QI_DEV_IOTLB_PFSID(pfsid);
1498 
1499 	/*
1500 	 * If S bit is 0, we only flush a single page. If S bit is set,
1501 	 * The least significant zero bit indicates the invalidation address
1502 	 * range. VT-d spec 6.5.2.6.
1503 	 * e.g. address bit 12[0] indicates 8KB, 13[0] indicates 16KB.
1504 	 * size order = 0 is PAGE_SIZE 4KB
1505 	 * Max Invs Pending (MIP) is set to 0 for now until we have DIT in
1506 	 * ECAP.
1507 	 */
1508 	if (!IS_ALIGNED(addr, VTD_PAGE_SIZE << size_order))
1509 		pr_warn_ratelimited("Invalidate non-aligned address %llx, order %d\n",
1510 				    addr, size_order);
1511 
1512 	/* Take page address */
1513 	desc.qw1 = QI_DEV_EIOTLB_ADDR(addr);
1514 
1515 	if (size_order) {
1516 		/*
1517 		 * Existing 0s in address below size_order may be the least
1518 		 * significant bit, we must set them to 1s to avoid having
1519 		 * smaller size than desired.
1520 		 */
1521 		desc.qw1 |= GENMASK_ULL(size_order + VTD_PAGE_SHIFT - 1,
1522 					VTD_PAGE_SHIFT);
1523 		/* Clear size_order bit to indicate size */
1524 		desc.qw1 &= ~mask;
1525 		/* Set the S bit to indicate flushing more than 1 page */
1526 		desc.qw1 |= QI_DEV_EIOTLB_SIZE;
1527 	}
1528 
1529 	qi_submit_sync(iommu, &desc, 1, 0);
1530 }
1531 
1532 void qi_flush_pasid_cache(struct intel_iommu *iommu, u16 did,
1533 			  u64 granu, u32 pasid)
1534 {
1535 	struct qi_desc desc = {.qw1 = 0, .qw2 = 0, .qw3 = 0};
1536 
1537 	desc.qw0 = QI_PC_PASID(pasid) | QI_PC_DID(did) |
1538 			QI_PC_GRAN(granu) | QI_PC_TYPE;
1539 	qi_submit_sync(iommu, &desc, 1, 0);
1540 }
1541 
1542 /*
1543  * Disable Queued Invalidation interface.
1544  */
1545 void dmar_disable_qi(struct intel_iommu *iommu)
1546 {
1547 	unsigned long flags;
1548 	u32 sts;
1549 	cycles_t start_time = get_cycles();
1550 
1551 	if (!ecap_qis(iommu->ecap))
1552 		return;
1553 
1554 	raw_spin_lock_irqsave(&iommu->register_lock, flags);
1555 
1556 	sts =  readl(iommu->reg + DMAR_GSTS_REG);
1557 	if (!(sts & DMA_GSTS_QIES))
1558 		goto end;
1559 
1560 	/*
1561 	 * Give a chance to HW to complete the pending invalidation requests.
1562 	 */
1563 	while ((readl(iommu->reg + DMAR_IQT_REG) !=
1564 		readl(iommu->reg + DMAR_IQH_REG)) &&
1565 		(DMAR_OPERATION_TIMEOUT > (get_cycles() - start_time)))
1566 		cpu_relax();
1567 
1568 	iommu->gcmd &= ~DMA_GCMD_QIE;
1569 	writel(iommu->gcmd, iommu->reg + DMAR_GCMD_REG);
1570 
1571 	IOMMU_WAIT_OP(iommu, DMAR_GSTS_REG, readl,
1572 		      !(sts & DMA_GSTS_QIES), sts);
1573 end:
1574 	raw_spin_unlock_irqrestore(&iommu->register_lock, flags);
1575 }
1576 
1577 /*
1578  * Enable queued invalidation.
1579  */
1580 static void __dmar_enable_qi(struct intel_iommu *iommu)
1581 {
1582 	u32 sts;
1583 	unsigned long flags;
1584 	struct q_inval *qi = iommu->qi;
1585 	u64 val = virt_to_phys(qi->desc);
1586 
1587 	qi->free_head = qi->free_tail = 0;
1588 	qi->free_cnt = QI_LENGTH;
1589 
1590 	/*
1591 	 * Set DW=1 and QS=1 in IQA_REG when Scalable Mode capability
1592 	 * is present.
1593 	 */
1594 	if (ecap_smts(iommu->ecap))
1595 		val |= (1 << 11) | 1;
1596 
1597 	raw_spin_lock_irqsave(&iommu->register_lock, flags);
1598 
1599 	/* write zero to the tail reg */
1600 	writel(0, iommu->reg + DMAR_IQT_REG);
1601 
1602 	dmar_writeq(iommu->reg + DMAR_IQA_REG, val);
1603 
1604 	iommu->gcmd |= DMA_GCMD_QIE;
1605 	writel(iommu->gcmd, iommu->reg + DMAR_GCMD_REG);
1606 
1607 	/* Make sure hardware complete it */
1608 	IOMMU_WAIT_OP(iommu, DMAR_GSTS_REG, readl, (sts & DMA_GSTS_QIES), sts);
1609 
1610 	raw_spin_unlock_irqrestore(&iommu->register_lock, flags);
1611 }
1612 
1613 /*
1614  * Enable Queued Invalidation interface. This is a must to support
1615  * interrupt-remapping. Also used by DMA-remapping, which replaces
1616  * register based IOTLB invalidation.
1617  */
1618 int dmar_enable_qi(struct intel_iommu *iommu)
1619 {
1620 	struct q_inval *qi;
1621 	struct page *desc_page;
1622 
1623 	if (!ecap_qis(iommu->ecap))
1624 		return -ENOENT;
1625 
1626 	/*
1627 	 * queued invalidation is already setup and enabled.
1628 	 */
1629 	if (iommu->qi)
1630 		return 0;
1631 
1632 	iommu->qi = kmalloc(sizeof(*qi), GFP_ATOMIC);
1633 	if (!iommu->qi)
1634 		return -ENOMEM;
1635 
1636 	qi = iommu->qi;
1637 
1638 	/*
1639 	 * Need two pages to accommodate 256 descriptors of 256 bits each
1640 	 * if the remapping hardware supports scalable mode translation.
1641 	 */
1642 	desc_page = alloc_pages_node(iommu->node, GFP_ATOMIC | __GFP_ZERO,
1643 				     !!ecap_smts(iommu->ecap));
1644 	if (!desc_page) {
1645 		kfree(qi);
1646 		iommu->qi = NULL;
1647 		return -ENOMEM;
1648 	}
1649 
1650 	qi->desc = page_address(desc_page);
1651 
1652 	qi->desc_status = kcalloc(QI_LENGTH, sizeof(int), GFP_ATOMIC);
1653 	if (!qi->desc_status) {
1654 		free_page((unsigned long) qi->desc);
1655 		kfree(qi);
1656 		iommu->qi = NULL;
1657 		return -ENOMEM;
1658 	}
1659 
1660 	raw_spin_lock_init(&qi->q_lock);
1661 
1662 	__dmar_enable_qi(iommu);
1663 
1664 	return 0;
1665 }
1666 
1667 /* iommu interrupt handling. Most stuff are MSI-like. */
1668 
1669 enum faulttype {
1670 	DMA_REMAP,
1671 	INTR_REMAP,
1672 	UNKNOWN,
1673 };
1674 
1675 static const char *dma_remap_fault_reasons[] =
1676 {
1677 	"Software",
1678 	"Present bit in root entry is clear",
1679 	"Present bit in context entry is clear",
1680 	"Invalid context entry",
1681 	"Access beyond MGAW",
1682 	"PTE Write access is not set",
1683 	"PTE Read access is not set",
1684 	"Next page table ptr is invalid",
1685 	"Root table address invalid",
1686 	"Context table ptr is invalid",
1687 	"non-zero reserved fields in RTP",
1688 	"non-zero reserved fields in CTP",
1689 	"non-zero reserved fields in PTE",
1690 	"PCE for translation request specifies blocking",
1691 };
1692 
1693 static const char * const dma_remap_sm_fault_reasons[] = {
1694 	"SM: Invalid Root Table Address",
1695 	"SM: TTM 0 for request with PASID",
1696 	"SM: TTM 0 for page group request",
1697 	"Unknown", "Unknown", "Unknown", "Unknown", "Unknown", /* 0x33-0x37 */
1698 	"SM: Error attempting to access Root Entry",
1699 	"SM: Present bit in Root Entry is clear",
1700 	"SM: Non-zero reserved field set in Root Entry",
1701 	"Unknown", "Unknown", "Unknown", "Unknown", "Unknown", /* 0x3B-0x3F */
1702 	"SM: Error attempting to access Context Entry",
1703 	"SM: Present bit in Context Entry is clear",
1704 	"SM: Non-zero reserved field set in the Context Entry",
1705 	"SM: Invalid Context Entry",
1706 	"SM: DTE field in Context Entry is clear",
1707 	"SM: PASID Enable field in Context Entry is clear",
1708 	"SM: PASID is larger than the max in Context Entry",
1709 	"SM: PRE field in Context-Entry is clear",
1710 	"SM: RID_PASID field error in Context-Entry",
1711 	"Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", /* 0x49-0x4F */
1712 	"SM: Error attempting to access the PASID Directory Entry",
1713 	"SM: Present bit in Directory Entry is clear",
1714 	"SM: Non-zero reserved field set in PASID Directory Entry",
1715 	"Unknown", "Unknown", "Unknown", "Unknown", "Unknown", /* 0x53-0x57 */
1716 	"SM: Error attempting to access PASID Table Entry",
1717 	"SM: Present bit in PASID Table Entry is clear",
1718 	"SM: Non-zero reserved field set in PASID Table Entry",
1719 	"SM: Invalid Scalable-Mode PASID Table Entry",
1720 	"SM: ERE field is clear in PASID Table Entry",
1721 	"SM: SRE field is clear in PASID Table Entry",
1722 	"Unknown", "Unknown",/* 0x5E-0x5F */
1723 	"Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", /* 0x60-0x67 */
1724 	"Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", /* 0x68-0x6F */
1725 	"SM: Error attempting to access first-level paging entry",
1726 	"SM: Present bit in first-level paging entry is clear",
1727 	"SM: Non-zero reserved field set in first-level paging entry",
1728 	"SM: Error attempting to access FL-PML4 entry",
1729 	"SM: First-level entry address beyond MGAW in Nested translation",
1730 	"SM: Read permission error in FL-PML4 entry in Nested translation",
1731 	"SM: Read permission error in first-level paging entry in Nested translation",
1732 	"SM: Write permission error in first-level paging entry in Nested translation",
1733 	"SM: Error attempting to access second-level paging entry",
1734 	"SM: Read/Write permission error in second-level paging entry",
1735 	"SM: Non-zero reserved field set in second-level paging entry",
1736 	"SM: Invalid second-level page table pointer",
1737 	"SM: A/D bit update needed in second-level entry when set up in no snoop",
1738 	"Unknown", "Unknown", "Unknown", /* 0x7D-0x7F */
1739 	"SM: Address in first-level translation is not canonical",
1740 	"SM: U/S set 0 for first-level translation with user privilege",
1741 	"SM: No execute permission for request with PASID and ER=1",
1742 	"SM: Address beyond the DMA hardware max",
1743 	"SM: Second-level entry address beyond the max",
1744 	"SM: No write permission for Write/AtomicOp request",
1745 	"SM: No read permission for Read/AtomicOp request",
1746 	"SM: Invalid address-interrupt address",
1747 	"Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", /* 0x88-0x8F */
1748 	"SM: A/D bit update needed in first-level entry when set up in no snoop",
1749 };
1750 
1751 static const char *irq_remap_fault_reasons[] =
1752 {
1753 	"Detected reserved fields in the decoded interrupt-remapped request",
1754 	"Interrupt index exceeded the interrupt-remapping table size",
1755 	"Present field in the IRTE entry is clear",
1756 	"Error accessing interrupt-remapping table pointed by IRTA_REG",
1757 	"Detected reserved fields in the IRTE entry",
1758 	"Blocked a compatibility format interrupt request",
1759 	"Blocked an interrupt request due to source-id verification failure",
1760 };
1761 
1762 static const char *dmar_get_fault_reason(u8 fault_reason, int *fault_type)
1763 {
1764 	if (fault_reason >= 0x20 && (fault_reason - 0x20 <
1765 					ARRAY_SIZE(irq_remap_fault_reasons))) {
1766 		*fault_type = INTR_REMAP;
1767 		return irq_remap_fault_reasons[fault_reason - 0x20];
1768 	} else if (fault_reason >= 0x30 && (fault_reason - 0x30 <
1769 			ARRAY_SIZE(dma_remap_sm_fault_reasons))) {
1770 		*fault_type = DMA_REMAP;
1771 		return dma_remap_sm_fault_reasons[fault_reason - 0x30];
1772 	} else if (fault_reason < ARRAY_SIZE(dma_remap_fault_reasons)) {
1773 		*fault_type = DMA_REMAP;
1774 		return dma_remap_fault_reasons[fault_reason];
1775 	} else {
1776 		*fault_type = UNKNOWN;
1777 		return "Unknown";
1778 	}
1779 }
1780 
1781 
1782 static inline int dmar_msi_reg(struct intel_iommu *iommu, int irq)
1783 {
1784 	if (iommu->irq == irq)
1785 		return DMAR_FECTL_REG;
1786 	else if (iommu->pr_irq == irq)
1787 		return DMAR_PECTL_REG;
1788 	else
1789 		BUG();
1790 }
1791 
1792 void dmar_msi_unmask(struct irq_data *data)
1793 {
1794 	struct intel_iommu *iommu = irq_data_get_irq_handler_data(data);
1795 	int reg = dmar_msi_reg(iommu, data->irq);
1796 	unsigned long flag;
1797 
1798 	/* unmask it */
1799 	raw_spin_lock_irqsave(&iommu->register_lock, flag);
1800 	writel(0, iommu->reg + reg);
1801 	/* Read a reg to force flush the post write */
1802 	readl(iommu->reg + reg);
1803 	raw_spin_unlock_irqrestore(&iommu->register_lock, flag);
1804 }
1805 
1806 void dmar_msi_mask(struct irq_data *data)
1807 {
1808 	struct intel_iommu *iommu = irq_data_get_irq_handler_data(data);
1809 	int reg = dmar_msi_reg(iommu, data->irq);
1810 	unsigned long flag;
1811 
1812 	/* mask it */
1813 	raw_spin_lock_irqsave(&iommu->register_lock, flag);
1814 	writel(DMA_FECTL_IM, iommu->reg + reg);
1815 	/* Read a reg to force flush the post write */
1816 	readl(iommu->reg + reg);
1817 	raw_spin_unlock_irqrestore(&iommu->register_lock, flag);
1818 }
1819 
1820 void dmar_msi_write(int irq, struct msi_msg *msg)
1821 {
1822 	struct intel_iommu *iommu = irq_get_handler_data(irq);
1823 	int reg = dmar_msi_reg(iommu, irq);
1824 	unsigned long flag;
1825 
1826 	raw_spin_lock_irqsave(&iommu->register_lock, flag);
1827 	writel(msg->data, iommu->reg + reg + 4);
1828 	writel(msg->address_lo, iommu->reg + reg + 8);
1829 	writel(msg->address_hi, iommu->reg + reg + 12);
1830 	raw_spin_unlock_irqrestore(&iommu->register_lock, flag);
1831 }
1832 
1833 void dmar_msi_read(int irq, struct msi_msg *msg)
1834 {
1835 	struct intel_iommu *iommu = irq_get_handler_data(irq);
1836 	int reg = dmar_msi_reg(iommu, irq);
1837 	unsigned long flag;
1838 
1839 	raw_spin_lock_irqsave(&iommu->register_lock, flag);
1840 	msg->data = readl(iommu->reg + reg + 4);
1841 	msg->address_lo = readl(iommu->reg + reg + 8);
1842 	msg->address_hi = readl(iommu->reg + reg + 12);
1843 	raw_spin_unlock_irqrestore(&iommu->register_lock, flag);
1844 }
1845 
1846 static int dmar_fault_do_one(struct intel_iommu *iommu, int type,
1847 		u8 fault_reason, u32 pasid, u16 source_id,
1848 		unsigned long long addr)
1849 {
1850 	const char *reason;
1851 	int fault_type;
1852 
1853 	reason = dmar_get_fault_reason(fault_reason, &fault_type);
1854 
1855 	if (fault_type == INTR_REMAP)
1856 		pr_err("[INTR-REMAP] Request device [%02x:%02x.%d] fault index %llx [fault reason %02d] %s\n",
1857 			source_id >> 8, PCI_SLOT(source_id & 0xFF),
1858 			PCI_FUNC(source_id & 0xFF), addr >> 48,
1859 			fault_reason, reason);
1860 	else
1861 		pr_err("[%s] Request device [%02x:%02x.%d] PASID %x fault addr %llx [fault reason %02d] %s\n",
1862 		       type ? "DMA Read" : "DMA Write",
1863 		       source_id >> 8, PCI_SLOT(source_id & 0xFF),
1864 		       PCI_FUNC(source_id & 0xFF), pasid, addr,
1865 		       fault_reason, reason);
1866 	return 0;
1867 }
1868 
1869 #define PRIMARY_FAULT_REG_LEN (16)
1870 irqreturn_t dmar_fault(int irq, void *dev_id)
1871 {
1872 	struct intel_iommu *iommu = dev_id;
1873 	int reg, fault_index;
1874 	u32 fault_status;
1875 	unsigned long flag;
1876 	static DEFINE_RATELIMIT_STATE(rs,
1877 				      DEFAULT_RATELIMIT_INTERVAL,
1878 				      DEFAULT_RATELIMIT_BURST);
1879 
1880 	raw_spin_lock_irqsave(&iommu->register_lock, flag);
1881 	fault_status = readl(iommu->reg + DMAR_FSTS_REG);
1882 	if (fault_status && __ratelimit(&rs))
1883 		pr_err("DRHD: handling fault status reg %x\n", fault_status);
1884 
1885 	/* TBD: ignore advanced fault log currently */
1886 	if (!(fault_status & DMA_FSTS_PPF))
1887 		goto unlock_exit;
1888 
1889 	fault_index = dma_fsts_fault_record_index(fault_status);
1890 	reg = cap_fault_reg_offset(iommu->cap);
1891 	while (1) {
1892 		/* Disable printing, simply clear the fault when ratelimited */
1893 		bool ratelimited = !__ratelimit(&rs);
1894 		u8 fault_reason;
1895 		u16 source_id;
1896 		u64 guest_addr;
1897 		u32 pasid;
1898 		int type;
1899 		u32 data;
1900 		bool pasid_present;
1901 
1902 		/* highest 32 bits */
1903 		data = readl(iommu->reg + reg +
1904 				fault_index * PRIMARY_FAULT_REG_LEN + 12);
1905 		if (!(data & DMA_FRCD_F))
1906 			break;
1907 
1908 		if (!ratelimited) {
1909 			fault_reason = dma_frcd_fault_reason(data);
1910 			type = dma_frcd_type(data);
1911 
1912 			pasid = dma_frcd_pasid_value(data);
1913 			data = readl(iommu->reg + reg +
1914 				     fault_index * PRIMARY_FAULT_REG_LEN + 8);
1915 			source_id = dma_frcd_source_id(data);
1916 
1917 			pasid_present = dma_frcd_pasid_present(data);
1918 			guest_addr = dmar_readq(iommu->reg + reg +
1919 					fault_index * PRIMARY_FAULT_REG_LEN);
1920 			guest_addr = dma_frcd_page_addr(guest_addr);
1921 		}
1922 
1923 		/* clear the fault */
1924 		writel(DMA_FRCD_F, iommu->reg + reg +
1925 			fault_index * PRIMARY_FAULT_REG_LEN + 12);
1926 
1927 		raw_spin_unlock_irqrestore(&iommu->register_lock, flag);
1928 
1929 		if (!ratelimited)
1930 			/* Using pasid -1 if pasid is not present */
1931 			dmar_fault_do_one(iommu, type, fault_reason,
1932 					  pasid_present ? pasid : -1,
1933 					  source_id, guest_addr);
1934 
1935 		fault_index++;
1936 		if (fault_index >= cap_num_fault_regs(iommu->cap))
1937 			fault_index = 0;
1938 		raw_spin_lock_irqsave(&iommu->register_lock, flag);
1939 	}
1940 
1941 	writel(DMA_FSTS_PFO | DMA_FSTS_PPF | DMA_FSTS_PRO,
1942 	       iommu->reg + DMAR_FSTS_REG);
1943 
1944 unlock_exit:
1945 	raw_spin_unlock_irqrestore(&iommu->register_lock, flag);
1946 	return IRQ_HANDLED;
1947 }
1948 
1949 int dmar_set_interrupt(struct intel_iommu *iommu)
1950 {
1951 	int irq, ret;
1952 
1953 	/*
1954 	 * Check if the fault interrupt is already initialized.
1955 	 */
1956 	if (iommu->irq)
1957 		return 0;
1958 
1959 	irq = dmar_alloc_hwirq(iommu->seq_id, iommu->node, iommu);
1960 	if (irq > 0) {
1961 		iommu->irq = irq;
1962 	} else {
1963 		pr_err("No free IRQ vectors\n");
1964 		return -EINVAL;
1965 	}
1966 
1967 	ret = request_irq(irq, dmar_fault, IRQF_NO_THREAD, iommu->name, iommu);
1968 	if (ret)
1969 		pr_err("Can't request irq\n");
1970 	return ret;
1971 }
1972 
1973 int __init enable_drhd_fault_handling(void)
1974 {
1975 	struct dmar_drhd_unit *drhd;
1976 	struct intel_iommu *iommu;
1977 
1978 	/*
1979 	 * Enable fault control interrupt.
1980 	 */
1981 	for_each_iommu(iommu, drhd) {
1982 		u32 fault_status;
1983 		int ret = dmar_set_interrupt(iommu);
1984 
1985 		if (ret) {
1986 			pr_err("DRHD %Lx: failed to enable fault, interrupt, ret %d\n",
1987 			       (unsigned long long)drhd->reg_base_addr, ret);
1988 			return -1;
1989 		}
1990 
1991 		/*
1992 		 * Clear any previous faults.
1993 		 */
1994 		dmar_fault(iommu->irq, iommu);
1995 		fault_status = readl(iommu->reg + DMAR_FSTS_REG);
1996 		writel(fault_status, iommu->reg + DMAR_FSTS_REG);
1997 	}
1998 
1999 	return 0;
2000 }
2001 
2002 /*
2003  * Re-enable Queued Invalidation interface.
2004  */
2005 int dmar_reenable_qi(struct intel_iommu *iommu)
2006 {
2007 	if (!ecap_qis(iommu->ecap))
2008 		return -ENOENT;
2009 
2010 	if (!iommu->qi)
2011 		return -ENOENT;
2012 
2013 	/*
2014 	 * First disable queued invalidation.
2015 	 */
2016 	dmar_disable_qi(iommu);
2017 	/*
2018 	 * Then enable queued invalidation again. Since there is no pending
2019 	 * invalidation requests now, it's safe to re-enable queued
2020 	 * invalidation.
2021 	 */
2022 	__dmar_enable_qi(iommu);
2023 
2024 	return 0;
2025 }
2026 
2027 /*
2028  * Check interrupt remapping support in DMAR table description.
2029  */
2030 int __init dmar_ir_support(void)
2031 {
2032 	struct acpi_table_dmar *dmar;
2033 	dmar = (struct acpi_table_dmar *)dmar_tbl;
2034 	if (!dmar)
2035 		return 0;
2036 	return dmar->flags & 0x1;
2037 }
2038 
2039 /* Check whether DMAR units are in use */
2040 static inline bool dmar_in_use(void)
2041 {
2042 	return irq_remapping_enabled || intel_iommu_enabled;
2043 }
2044 
2045 static int __init dmar_free_unused_resources(void)
2046 {
2047 	struct dmar_drhd_unit *dmaru, *dmaru_n;
2048 
2049 	if (dmar_in_use())
2050 		return 0;
2051 
2052 	if (dmar_dev_scope_status != 1 && !list_empty(&dmar_drhd_units))
2053 		bus_unregister_notifier(&pci_bus_type, &dmar_pci_bus_nb);
2054 
2055 	down_write(&dmar_global_lock);
2056 	list_for_each_entry_safe(dmaru, dmaru_n, &dmar_drhd_units, list) {
2057 		list_del(&dmaru->list);
2058 		dmar_free_drhd(dmaru);
2059 	}
2060 	up_write(&dmar_global_lock);
2061 
2062 	return 0;
2063 }
2064 
2065 late_initcall(dmar_free_unused_resources);
2066 IOMMU_INIT_POST(detect_intel_iommu);
2067 
2068 /*
2069  * DMAR Hotplug Support
2070  * For more details, please refer to Intel(R) Virtualization Technology
2071  * for Directed-IO Architecture Specifiction, Rev 2.2, Section 8.8
2072  * "Remapping Hardware Unit Hot Plug".
2073  */
2074 static guid_t dmar_hp_guid =
2075 	GUID_INIT(0xD8C1A3A6, 0xBE9B, 0x4C9B,
2076 		  0x91, 0xBF, 0xC3, 0xCB, 0x81, 0xFC, 0x5D, 0xAF);
2077 
2078 /*
2079  * Currently there's only one revision and BIOS will not check the revision id,
2080  * so use 0 for safety.
2081  */
2082 #define	DMAR_DSM_REV_ID			0
2083 #define	DMAR_DSM_FUNC_DRHD		1
2084 #define	DMAR_DSM_FUNC_ATSR		2
2085 #define	DMAR_DSM_FUNC_RHSA		3
2086 #define	DMAR_DSM_FUNC_SATC		4
2087 
2088 static inline bool dmar_detect_dsm(acpi_handle handle, int func)
2089 {
2090 	return acpi_check_dsm(handle, &dmar_hp_guid, DMAR_DSM_REV_ID, 1 << func);
2091 }
2092 
2093 static int dmar_walk_dsm_resource(acpi_handle handle, int func,
2094 				  dmar_res_handler_t handler, void *arg)
2095 {
2096 	int ret = -ENODEV;
2097 	union acpi_object *obj;
2098 	struct acpi_dmar_header *start;
2099 	struct dmar_res_callback callback;
2100 	static int res_type[] = {
2101 		[DMAR_DSM_FUNC_DRHD] = ACPI_DMAR_TYPE_HARDWARE_UNIT,
2102 		[DMAR_DSM_FUNC_ATSR] = ACPI_DMAR_TYPE_ROOT_ATS,
2103 		[DMAR_DSM_FUNC_RHSA] = ACPI_DMAR_TYPE_HARDWARE_AFFINITY,
2104 		[DMAR_DSM_FUNC_SATC] = ACPI_DMAR_TYPE_SATC,
2105 	};
2106 
2107 	if (!dmar_detect_dsm(handle, func))
2108 		return 0;
2109 
2110 	obj = acpi_evaluate_dsm_typed(handle, &dmar_hp_guid, DMAR_DSM_REV_ID,
2111 				      func, NULL, ACPI_TYPE_BUFFER);
2112 	if (!obj)
2113 		return -ENODEV;
2114 
2115 	memset(&callback, 0, sizeof(callback));
2116 	callback.cb[res_type[func]] = handler;
2117 	callback.arg[res_type[func]] = arg;
2118 	start = (struct acpi_dmar_header *)obj->buffer.pointer;
2119 	ret = dmar_walk_remapping_entries(start, obj->buffer.length, &callback);
2120 
2121 	ACPI_FREE(obj);
2122 
2123 	return ret;
2124 }
2125 
2126 static int dmar_hp_add_drhd(struct acpi_dmar_header *header, void *arg)
2127 {
2128 	int ret;
2129 	struct dmar_drhd_unit *dmaru;
2130 
2131 	dmaru = dmar_find_dmaru((struct acpi_dmar_hardware_unit *)header);
2132 	if (!dmaru)
2133 		return -ENODEV;
2134 
2135 	ret = dmar_ir_hotplug(dmaru, true);
2136 	if (ret == 0)
2137 		ret = dmar_iommu_hotplug(dmaru, true);
2138 
2139 	return ret;
2140 }
2141 
2142 static int dmar_hp_remove_drhd(struct acpi_dmar_header *header, void *arg)
2143 {
2144 	int i, ret;
2145 	struct device *dev;
2146 	struct dmar_drhd_unit *dmaru;
2147 
2148 	dmaru = dmar_find_dmaru((struct acpi_dmar_hardware_unit *)header);
2149 	if (!dmaru)
2150 		return 0;
2151 
2152 	/*
2153 	 * All PCI devices managed by this unit should have been destroyed.
2154 	 */
2155 	if (!dmaru->include_all && dmaru->devices && dmaru->devices_cnt) {
2156 		for_each_active_dev_scope(dmaru->devices,
2157 					  dmaru->devices_cnt, i, dev)
2158 			return -EBUSY;
2159 	}
2160 
2161 	ret = dmar_ir_hotplug(dmaru, false);
2162 	if (ret == 0)
2163 		ret = dmar_iommu_hotplug(dmaru, false);
2164 
2165 	return ret;
2166 }
2167 
2168 static int dmar_hp_release_drhd(struct acpi_dmar_header *header, void *arg)
2169 {
2170 	struct dmar_drhd_unit *dmaru;
2171 
2172 	dmaru = dmar_find_dmaru((struct acpi_dmar_hardware_unit *)header);
2173 	if (dmaru) {
2174 		list_del_rcu(&dmaru->list);
2175 		synchronize_rcu();
2176 		dmar_free_drhd(dmaru);
2177 	}
2178 
2179 	return 0;
2180 }
2181 
2182 static int dmar_hotplug_insert(acpi_handle handle)
2183 {
2184 	int ret;
2185 	int drhd_count = 0;
2186 
2187 	ret = dmar_walk_dsm_resource(handle, DMAR_DSM_FUNC_DRHD,
2188 				     &dmar_validate_one_drhd, (void *)1);
2189 	if (ret)
2190 		goto out;
2191 
2192 	ret = dmar_walk_dsm_resource(handle, DMAR_DSM_FUNC_DRHD,
2193 				     &dmar_parse_one_drhd, (void *)&drhd_count);
2194 	if (ret == 0 && drhd_count == 0) {
2195 		pr_warn(FW_BUG "No DRHD structures in buffer returned by _DSM method\n");
2196 		goto out;
2197 	} else if (ret) {
2198 		goto release_drhd;
2199 	}
2200 
2201 	ret = dmar_walk_dsm_resource(handle, DMAR_DSM_FUNC_RHSA,
2202 				     &dmar_parse_one_rhsa, NULL);
2203 	if (ret)
2204 		goto release_drhd;
2205 
2206 	ret = dmar_walk_dsm_resource(handle, DMAR_DSM_FUNC_ATSR,
2207 				     &dmar_parse_one_atsr, NULL);
2208 	if (ret)
2209 		goto release_atsr;
2210 
2211 	ret = dmar_walk_dsm_resource(handle, DMAR_DSM_FUNC_DRHD,
2212 				     &dmar_hp_add_drhd, NULL);
2213 	if (!ret)
2214 		return 0;
2215 
2216 	dmar_walk_dsm_resource(handle, DMAR_DSM_FUNC_DRHD,
2217 			       &dmar_hp_remove_drhd, NULL);
2218 release_atsr:
2219 	dmar_walk_dsm_resource(handle, DMAR_DSM_FUNC_ATSR,
2220 			       &dmar_release_one_atsr, NULL);
2221 release_drhd:
2222 	dmar_walk_dsm_resource(handle, DMAR_DSM_FUNC_DRHD,
2223 			       &dmar_hp_release_drhd, NULL);
2224 out:
2225 	return ret;
2226 }
2227 
2228 static int dmar_hotplug_remove(acpi_handle handle)
2229 {
2230 	int ret;
2231 
2232 	ret = dmar_walk_dsm_resource(handle, DMAR_DSM_FUNC_ATSR,
2233 				     &dmar_check_one_atsr, NULL);
2234 	if (ret)
2235 		return ret;
2236 
2237 	ret = dmar_walk_dsm_resource(handle, DMAR_DSM_FUNC_DRHD,
2238 				     &dmar_hp_remove_drhd, NULL);
2239 	if (ret == 0) {
2240 		WARN_ON(dmar_walk_dsm_resource(handle, DMAR_DSM_FUNC_ATSR,
2241 					       &dmar_release_one_atsr, NULL));
2242 		WARN_ON(dmar_walk_dsm_resource(handle, DMAR_DSM_FUNC_DRHD,
2243 					       &dmar_hp_release_drhd, NULL));
2244 	} else {
2245 		dmar_walk_dsm_resource(handle, DMAR_DSM_FUNC_DRHD,
2246 				       &dmar_hp_add_drhd, NULL);
2247 	}
2248 
2249 	return ret;
2250 }
2251 
2252 static acpi_status dmar_get_dsm_handle(acpi_handle handle, u32 lvl,
2253 				       void *context, void **retval)
2254 {
2255 	acpi_handle *phdl = retval;
2256 
2257 	if (dmar_detect_dsm(handle, DMAR_DSM_FUNC_DRHD)) {
2258 		*phdl = handle;
2259 		return AE_CTRL_TERMINATE;
2260 	}
2261 
2262 	return AE_OK;
2263 }
2264 
2265 static int dmar_device_hotplug(acpi_handle handle, bool insert)
2266 {
2267 	int ret;
2268 	acpi_handle tmp = NULL;
2269 	acpi_status status;
2270 
2271 	if (!dmar_in_use())
2272 		return 0;
2273 
2274 	if (dmar_detect_dsm(handle, DMAR_DSM_FUNC_DRHD)) {
2275 		tmp = handle;
2276 	} else {
2277 		status = acpi_walk_namespace(ACPI_TYPE_DEVICE, handle,
2278 					     ACPI_UINT32_MAX,
2279 					     dmar_get_dsm_handle,
2280 					     NULL, NULL, &tmp);
2281 		if (ACPI_FAILURE(status)) {
2282 			pr_warn("Failed to locate _DSM method.\n");
2283 			return -ENXIO;
2284 		}
2285 	}
2286 	if (tmp == NULL)
2287 		return 0;
2288 
2289 	down_write(&dmar_global_lock);
2290 	if (insert)
2291 		ret = dmar_hotplug_insert(tmp);
2292 	else
2293 		ret = dmar_hotplug_remove(tmp);
2294 	up_write(&dmar_global_lock);
2295 
2296 	return ret;
2297 }
2298 
2299 int dmar_device_add(acpi_handle handle)
2300 {
2301 	return dmar_device_hotplug(handle, true);
2302 }
2303 
2304 int dmar_device_remove(acpi_handle handle)
2305 {
2306 	return dmar_device_hotplug(handle, false);
2307 }
2308 
2309 /*
2310  * dmar_platform_optin - Is %DMA_CTRL_PLATFORM_OPT_IN_FLAG set in DMAR table
2311  *
2312  * Returns true if the platform has %DMA_CTRL_PLATFORM_OPT_IN_FLAG set in
2313  * the ACPI DMAR table. This means that the platform boot firmware has made
2314  * sure no device can issue DMA outside of RMRR regions.
2315  */
2316 bool dmar_platform_optin(void)
2317 {
2318 	struct acpi_table_dmar *dmar;
2319 	acpi_status status;
2320 	bool ret;
2321 
2322 	status = acpi_get_table(ACPI_SIG_DMAR, 0,
2323 				(struct acpi_table_header **)&dmar);
2324 	if (ACPI_FAILURE(status))
2325 		return false;
2326 
2327 	ret = !!(dmar->flags & DMAR_PLATFORM_OPT_IN);
2328 	acpi_put_table((struct acpi_table_header *)dmar);
2329 
2330 	return ret;
2331 }
2332 EXPORT_SYMBOL_GPL(dmar_platform_optin);
2333