xref: /illumos-gate/usr/src/uts/i86pc/io/immu_dvma.c (revision 89b42a211fa7d3527b9615260f495d22e430c5c5)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Portions Copyright (c) 2010, Oracle and/or its affiliates.
23  * All rights reserved.
24  */
25 /*
26  * Copyright (c) 2009, Intel Corporation.
27  * All rights reserved.
28  */
29 
30 /*
31  * DVMA code
32  * This file contains Intel IOMMU code that deals with DVMA
33  * i.e. DMA remapping.
34  */
35 
36 #include <sys/sysmacros.h>
37 #include <sys/pcie.h>
38 #include <sys/pci_cfgspace.h>
39 #include <vm/hat_i86.h>
40 #include <sys/memlist.h>
41 #include <sys/acpi/acpi.h>
42 #include <sys/acpica.h>
43 #include <sys/modhash.h>
44 #include <sys/immu.h>
45 
46 #undef	TEST
47 
48 /*
49  * Macros based on PCI spec
50  */
51 #define	IMMU_PCI_REV2CLASS(r)   ((r) >> 8)  /* classcode from revid */
52 #define	IMMU_PCI_CLASS2BASE(c)  ((c) >> 16) /* baseclass from classcode */
53 #define	IMMU_PCI_CLASS2SUB(c)   (((c) >> 8) & 0xff); /* classcode */
54 
55 #define	IMMU_CONTIG_PADDR(d, p) \
56 	((d).dck_paddr && ((d).dck_paddr + IMMU_PAGESIZE) == (p))
57 
58 typedef struct dvma_arg {
59 	immu_t *dva_immu;
60 	dev_info_t *dva_rdip;
61 	dev_info_t *dva_ddip;
62 	domain_t *dva_domain;
63 	int dva_level;
64 	immu_flags_t dva_flags;
65 	list_t *dva_list;
66 	int dva_error;
67 } dvma_arg_t;
68 
69 static domain_t *domain_create(immu_t *immu, dev_info_t *ddip,
70     dev_info_t *rdip, immu_flags_t immu_flags);
71 static immu_devi_t *create_immu_devi(dev_info_t *rdip, int bus,
72     int dev, int func, immu_flags_t immu_flags);
73 static void destroy_immu_devi(immu_devi_t *immu_devi);
74 static boolean_t dvma_map(immu_t *immu, domain_t *domain, uint64_t sdvma,
75     uint64_t nvpages, dcookie_t *dcookies, int dcount, dev_info_t *rdip,
76     immu_flags_t immu_flags);
77 
78 /* Extern globals */
79 extern struct memlist  *phys_install;
80 
81 
82 /* static Globals */
83 
84 /*
85  * Used to setup DMA objects (memory regions)
86  * for DMA reads by IOMMU units
87  */
88 static ddi_dma_attr_t immu_dma_attr = {
89 	DMA_ATTR_V0,
90 	0U,
91 	0xffffffffU,
92 	0xffffffffU,
93 	MMU_PAGESIZE, /* MMU page aligned */
94 	0x1,
95 	0x1,
96 	0xffffffffU,
97 	0xffffffffU,
98 	1,
99 	4,
100 	0
101 };
102 
103 static ddi_device_acc_attr_t immu_acc_attr = {
104 	DDI_DEVICE_ATTR_V0,
105 	DDI_NEVERSWAP_ACC,
106 	DDI_STRICTORDER_ACC
107 };
108 
109 
110 /* globals private to this file */
111 static kmutex_t immu_domain_lock;
112 static list_t immu_unity_domain_list;
113 static list_t immu_xlate_domain_list;
114 
115 /* structure used to store idx into each level of the page tables */
116 typedef struct xlate {
117 	int xlt_level;
118 	uint_t xlt_idx;
119 	pgtable_t *xlt_pgtable;
120 } xlate_t;
121 
122 /* 0 is reserved by Vt-d spec. Solaris reserves 1 */
123 #define	IMMU_UNITY_DID   1
124 
125 static mod_hash_t *bdf_domain_hash;
126 
127 static domain_t *
128 bdf_domain_lookup(immu_devi_t *immu_devi)
129 {
130 	domain_t *domain;
131 	int16_t seg = immu_devi->imd_seg;
132 	int16_t bus = immu_devi->imd_bus;
133 	int16_t devfunc = immu_devi->imd_devfunc;
134 	uintptr_t bdf = (seg << 16 | bus << 8 | devfunc);
135 
136 	if (seg < 0 || bus < 0 || devfunc < 0) {
137 		return (NULL);
138 	}
139 
140 	domain = NULL;
141 	if (mod_hash_find(bdf_domain_hash,
142 	    (void *)bdf, (void *)&domain) == 0) {
143 		ASSERT(domain);
144 		ASSERT(domain->dom_did > 0);
145 		return (domain);
146 	} else {
147 		return (NULL);
148 	}
149 }
150 
151 static void
152 bdf_domain_insert(immu_devi_t *immu_devi, domain_t *domain)
153 {
154 	int16_t seg = immu_devi->imd_seg;
155 	int16_t bus = immu_devi->imd_bus;
156 	int16_t devfunc = immu_devi->imd_devfunc;
157 	uintptr_t bdf = (seg << 16 | bus << 8 | devfunc);
158 	int r;
159 
160 	if (seg < 0 || bus < 0 || devfunc < 0) {
161 		return;
162 	}
163 
164 	r = mod_hash_insert(bdf_domain_hash, (void *)bdf, (void *)domain);
165 	ASSERT(r != MH_ERR_DUPLICATE);
166 	ASSERT(r == 0);
167 }
168 
169 static int
170 match_lpc(dev_info_t *pdip, void *arg)
171 {
172 	immu_devi_t *immu_devi;
173 	dvma_arg_t *dvap = (dvma_arg_t *)arg;
174 
175 	ASSERT(dvap->dva_error == DDI_FAILURE);
176 	ASSERT(dvap->dva_ddip == NULL);
177 	ASSERT(dvap->dva_list);
178 
179 	if (list_is_empty(dvap->dva_list)) {
180 		return (DDI_WALK_TERMINATE);
181 	}
182 
183 	immu_devi = list_head(dvap->dva_list);
184 	for (; immu_devi; immu_devi = list_next(dvap->dva_list,
185 	    immu_devi)) {
186 		ASSERT(immu_devi->imd_dip);
187 		if (immu_devi->imd_dip == pdip) {
188 			dvap->dva_ddip = pdip;
189 			dvap->dva_error = DDI_SUCCESS;
190 			return (DDI_WALK_TERMINATE);
191 		}
192 	}
193 
194 	return (DDI_WALK_CONTINUE);
195 }
196 
197 static void
198 immu_devi_set_spclist(dev_info_t *dip, immu_t *immu)
199 {
200 	list_t *spclist = NULL;
201 	immu_devi_t *immu_devi;
202 
203 	ASSERT(MUTEX_HELD(&(DEVI(dip)->devi_lock)));
204 
205 	immu_devi = IMMU_DEVI(dip);
206 	if (immu_devi->imd_display == B_TRUE) {
207 		spclist = &(immu->immu_dvma_gfx_list);
208 	} else if (immu_devi->imd_lpc == B_TRUE) {
209 		spclist = &(immu->immu_dvma_lpc_list);
210 	}
211 
212 	if (spclist) {
213 		mutex_enter(&(immu->immu_lock));
214 		list_insert_head(spclist, immu_devi);
215 		mutex_exit(&(immu->immu_lock));
216 	}
217 }
218 
219 /*
220  * Set the immu_devi struct in the immu_devi field of a devinfo node
221  */
222 int
223 immu_devi_set(dev_info_t *dip, immu_flags_t immu_flags)
224 {
225 	int bus, dev, func;
226 	immu_devi_t *new_imd;
227 	immu_devi_t *immu_devi;
228 
229 	ASSERT(root_devinfo);
230 	ASSERT(dip);
231 	ASSERT(dip != root_devinfo);
232 
233 	immu_devi = immu_devi_get(dip);
234 	if (immu_devi != NULL) {
235 		return (DDI_SUCCESS);
236 	}
237 
238 	bus = dev = func = -1;
239 
240 	/*
241 	 * Assume a new immu_devi struct is needed
242 	 */
243 	if (!DEVI_IS_PCI(dip) || acpica_get_bdf(dip, &bus, &dev, &func) != 0) {
244 		/*
245 		 * No BDF. Set bus = -1 to indicate this.
246 		 * We still need to create a immu_devi struct
247 		 * though
248 		 */
249 		bus = -1;
250 		dev = 0;
251 		func = 0;
252 	}
253 
254 	new_imd = create_immu_devi(dip, bus, dev, func, immu_flags);
255 	if (new_imd  == NULL) {
256 		ddi_err(DER_WARN, dip, "Failed to create immu_devi "
257 		    "structure");
258 		return (DDI_FAILURE);
259 	}
260 
261 	/*
262 	 * Check if some other thread allocated a immu_devi while we
263 	 * didn't own the lock.
264 	 */
265 	mutex_enter(&(DEVI(dip)->devi_lock));
266 	if (IMMU_DEVI(dip) == NULL) {
267 		IMMU_DEVI_SET(dip, new_imd);
268 	} else {
269 		destroy_immu_devi(new_imd);
270 	}
271 	mutex_exit(&(DEVI(dip)->devi_lock));
272 
273 	return (DDI_SUCCESS);
274 }
275 
276 static dev_info_t *
277 get_lpc_devinfo(immu_t *immu, dev_info_t *rdip, immu_flags_t immu_flags)
278 {
279 	dvma_arg_t dvarg = {0};
280 	dvarg.dva_list = &(immu->immu_dvma_lpc_list);
281 	dvarg.dva_rdip = rdip;
282 	dvarg.dva_error = DDI_FAILURE;
283 
284 	if (immu_walk_ancestor(rdip, NULL, match_lpc,
285 	    &dvarg, NULL, immu_flags) != DDI_SUCCESS) {
286 		ddi_err(DER_MODE, rdip, "Could not walk ancestors to "
287 		    "find lpc_devinfo for ISA device");
288 		return (NULL);
289 	}
290 
291 	if (dvarg.dva_error != DDI_SUCCESS || dvarg.dva_ddip == NULL) {
292 		ddi_err(DER_MODE, rdip, "Could not find lpc_devinfo for "
293 		    "ISA device");
294 		return (NULL);
295 	}
296 
297 	return (dvarg.dva_ddip);
298 }
299 
300 static dev_info_t *
301 get_gfx_devinfo(dev_info_t *rdip)
302 {
303 	immu_t *immu;
304 	immu_devi_t *immu_devi;
305 	list_t *list_gfx;
306 
307 	/*
308 	 * The GFX device may not be on the same IMMU unit as "agpgart"
309 	 * so search globally
310 	 */
311 	immu_devi = NULL;
312 	immu = list_head(&immu_list);
313 	for (; immu; immu = list_next(&immu_list, immu)) {
314 		list_gfx = &(immu->immu_dvma_gfx_list);
315 		if (!list_is_empty(list_gfx)) {
316 			immu_devi = list_head(list_gfx);
317 			break;
318 		}
319 	}
320 
321 	if (immu_devi == NULL) {
322 		ddi_err(DER_WARN, rdip, "IMMU: No GFX device. "
323 		    "Cannot redirect agpgart");
324 		return (NULL);
325 	}
326 
327 	/* list is not empty we checked above */
328 	ASSERT(immu_devi);
329 	ASSERT(immu_devi->imd_dip);
330 
331 	ddi_err(DER_LOG, rdip, "IMMU: GFX redirect to %s",
332 	    ddi_node_name(immu_devi->imd_dip));
333 
334 	return (immu_devi->imd_dip);
335 }
336 
337 static immu_flags_t
338 dma_to_immu_flags(struct ddi_dma_req *dmareq)
339 {
340 	immu_flags_t flags = 0;
341 
342 	if (dmareq->dmar_fp == DDI_DMA_SLEEP) {
343 		flags |= IMMU_FLAGS_SLEEP;
344 	} else {
345 		flags |= IMMU_FLAGS_NOSLEEP;
346 	}
347 
348 #ifdef BUGGY_DRIVERS
349 
350 	flags |= (IMMU_FLAGS_READ | IMMU_FLAGS_WRITE);
351 
352 #else
353 	/*
354 	 * Read and write flags need to be reversed.
355 	 * DMA_READ means read from device and write
356 	 * to memory. So DMA read means DVMA write.
357 	 */
358 	if (dmareq->dmar_flags & DDI_DMA_READ)
359 		flags |= IMMU_FLAGS_WRITE;
360 
361 	if (dmareq->dmar_flags & DDI_DMA_WRITE)
362 		flags |= IMMU_FLAGS_READ;
363 
364 	/*
365 	 * Some buggy drivers specify neither READ or WRITE
366 	 * For such drivers set both read and write permissions
367 	 */
368 	if ((dmareq->dmar_flags & (DDI_DMA_READ | DDI_DMA_WRITE)) == 0) {
369 		flags |= (IMMU_FLAGS_READ | IMMU_FLAGS_WRITE);
370 	}
371 #endif
372 
373 	return (flags);
374 }
375 
376 int
377 pgtable_ctor(void *buf, void *arg, int kmflag)
378 {
379 	size_t actual_size = 0;
380 	pgtable_t *pgtable;
381 	int (*dmafp)(caddr_t);
382 	caddr_t vaddr;
383 	void *next;
384 
385 	ASSERT(buf);
386 	ASSERT(arg == NULL);
387 
388 	pgtable = (pgtable_t *)buf;
389 
390 	dmafp = (kmflag & KM_NOSLEEP) ? DDI_DMA_DONTWAIT : DDI_DMA_SLEEP;
391 
392 	next = kmem_zalloc(IMMU_PAGESIZE, kmflag);
393 	if (next == NULL) {
394 		return (-1);
395 	}
396 
397 	ASSERT(root_devinfo);
398 	if (ddi_dma_alloc_handle(root_devinfo, &immu_dma_attr,
399 	    dmafp, NULL, &pgtable->hwpg_dmahdl) != DDI_SUCCESS) {
400 		kmem_free(next, IMMU_PAGESIZE);
401 		return (-1);
402 	}
403 
404 	if (ddi_dma_mem_alloc(pgtable->hwpg_dmahdl, IMMU_PAGESIZE,
405 	    &immu_acc_attr, DDI_DMA_CONSISTENT | IOMEM_DATA_UNCACHED,
406 	    dmafp, NULL, &vaddr, &actual_size,
407 	    &pgtable->hwpg_memhdl) != DDI_SUCCESS) {
408 		ddi_dma_free_handle(&pgtable->hwpg_dmahdl);
409 		kmem_free(next, IMMU_PAGESIZE);
410 		return (-1);
411 	}
412 
413 	/*
414 	 * Memory allocation failure. Maybe a temporary condition
415 	 * so return error rather than panic, so we can try again
416 	 */
417 	if (actual_size < IMMU_PAGESIZE) {
418 		ddi_dma_mem_free(&pgtable->hwpg_memhdl);
419 		ddi_dma_free_handle(&pgtable->hwpg_dmahdl);
420 		kmem_free(next, IMMU_PAGESIZE);
421 		return (-1);
422 	}
423 
424 	pgtable->hwpg_paddr = pfn_to_pa(hat_getpfnum(kas.a_hat, vaddr));
425 	pgtable->hwpg_vaddr = vaddr;
426 	pgtable->swpg_next_array = next;
427 
428 	rw_init(&(pgtable->swpg_rwlock), NULL, RW_DEFAULT, NULL);
429 
430 	return (0);
431 }
432 
433 void
434 pgtable_dtor(void *buf, void *arg)
435 {
436 	pgtable_t *pgtable;
437 
438 	ASSERT(buf);
439 	ASSERT(arg == NULL);
440 
441 	pgtable = (pgtable_t *)buf;
442 	ASSERT(pgtable->swpg_next_array);
443 
444 	/* destroy will panic if lock is held. */
445 	rw_destroy(&(pgtable->swpg_rwlock));
446 
447 	ddi_dma_mem_free(&pgtable->hwpg_memhdl);
448 	ddi_dma_free_handle(&pgtable->hwpg_dmahdl);
449 	kmem_free(pgtable->swpg_next_array, IMMU_PAGESIZE);
450 
451 	/* don't zero out hwpg_vaddr and swpg_next_array for debugging */
452 }
453 
454 /*
455  * pgtable_alloc()
456  *	alloc a IOMMU pgtable structure.
457  *	This same struct is used for root and context tables as well.
458  *	This routine allocs the f/ollowing:
459  *	- a pgtable_t struct
460  *	- a HW page which holds PTEs/entries which is accesssed by HW
461  *        so we set up DMA for this page
462  *	- a SW page which is only for our bookeeping
463  *        (for example to  hold pointers to the next level pgtable).
464  *        So a simple kmem_alloc suffices
465  */
466 static pgtable_t *
467 pgtable_alloc(immu_t *immu, immu_flags_t immu_flags)
468 {
469 	pgtable_t *pgtable;
470 	int kmflags;
471 
472 	ASSERT(immu);
473 
474 	kmflags = (immu_flags & IMMU_FLAGS_NOSLEEP) ? KM_NOSLEEP : KM_SLEEP;
475 
476 	pgtable = kmem_cache_alloc(immu_pgtable_cache, kmflags);
477 	if (pgtable == NULL) {
478 		return (NULL);
479 	}
480 	return (pgtable);
481 }
482 
483 static void
484 pgtable_zero(immu_t *immu, pgtable_t *pgtable)
485 {
486 	bzero(pgtable->hwpg_vaddr, IMMU_PAGESIZE);
487 	bzero(pgtable->swpg_next_array, IMMU_PAGESIZE);
488 
489 	/* Dont need to flush the write we will flush when we use the entry */
490 	immu_regs_cpu_flush(immu, pgtable->hwpg_vaddr, IMMU_PAGESIZE);
491 }
492 
493 static void
494 pgtable_free(immu_t *immu, pgtable_t *pgtable)
495 {
496 	ASSERT(immu);
497 	ASSERT(pgtable);
498 
499 	kmem_cache_free(immu_pgtable_cache, pgtable);
500 }
501 
502 /*
503  * Function to identify a display device from the PCI class code
504  */
505 static boolean_t
506 device_is_display(uint_t classcode)
507 {
508 	static uint_t disp_classes[] = {
509 		0x000100,
510 		0x030000,
511 		0x030001
512 	};
513 	int i, nclasses = sizeof (disp_classes) / sizeof (uint_t);
514 
515 	for (i = 0; i < nclasses; i++) {
516 		if (classcode == disp_classes[i])
517 			return (B_TRUE);
518 	}
519 	return (B_FALSE);
520 }
521 
522 /*
523  * Function that determines if device is PCIEX and/or PCIEX bridge
524  */
525 static boolean_t
526 device_is_pciex(
527 	uchar_t bus, uchar_t dev, uchar_t func, boolean_t *is_pcib)
528 {
529 	ushort_t cap;
530 	ushort_t capsp;
531 	ushort_t cap_count = PCI_CAP_MAX_PTR;
532 	ushort_t status;
533 	boolean_t is_pciex = B_FALSE;
534 
535 	*is_pcib = B_FALSE;
536 
537 	status = pci_getw_func(bus, dev, func, PCI_CONF_STAT);
538 	if (!(status & PCI_STAT_CAP))
539 		return (B_FALSE);
540 
541 	capsp = pci_getb_func(bus, dev, func, PCI_CONF_CAP_PTR);
542 	while (cap_count-- && capsp >= PCI_CAP_PTR_OFF) {
543 		capsp &= PCI_CAP_PTR_MASK;
544 		cap = pci_getb_func(bus, dev, func, capsp);
545 
546 		if (cap == PCI_CAP_ID_PCI_E) {
547 			status = pci_getw_func(bus, dev, func, capsp + 2);
548 			/*
549 			 * See section 7.8.2 of PCI-Express Base Spec v1.0a
550 			 * for Device/Port Type.
551 			 * PCIE_PCIECAP_DEV_TYPE_PCIE2PCI implies that the
552 			 * device is a PCIE2PCI bridge
553 			 */
554 			*is_pcib =
555 			    ((status & PCIE_PCIECAP_DEV_TYPE_MASK) ==
556 			    PCIE_PCIECAP_DEV_TYPE_PCIE2PCI) ? B_TRUE : B_FALSE;
557 			is_pciex = B_TRUE;
558 		}
559 
560 		capsp = (*pci_getb_func)(bus, dev, func,
561 		    capsp + PCI_CAP_NEXT_PTR);
562 	}
563 
564 	return (is_pciex);
565 }
566 
567 
568 /*
569  * immu_dvma_get_immu()
570  *   get the immu unit structure for a dev_info node
571  */
572 immu_t *
573 immu_dvma_get_immu(dev_info_t *dip, immu_flags_t immu_flags)
574 {
575 	immu_devi_t *immu_devi;
576 	immu_t *immu;
577 
578 	/*
579 	 * check if immu unit was already found earlier.
580 	 * If yes, then it will be stashed in immu_devi struct.
581 	 */
582 	immu_devi = immu_devi_get(dip);
583 	if (immu_devi == NULL) {
584 		if (immu_devi_set(dip, immu_flags) != DDI_SUCCESS) {
585 			/*
586 			 * May fail because of low memory. Return error rather
587 			 * than panic as we want driver to rey again later
588 			 */
589 			ddi_err(DER_PANIC, dip, "immu_dvma_get_immu: "
590 			    "No immu_devi structure");
591 			/*NOTREACHED*/
592 		}
593 		immu_devi = immu_devi_get(dip);
594 		ASSERT(immu_devi);
595 	}
596 
597 	mutex_enter(&(DEVI(dip)->devi_lock));
598 	if (immu_devi->imd_immu) {
599 		immu = immu_devi->imd_immu;
600 		mutex_exit(&(DEVI(dip)->devi_lock));
601 		return (immu);
602 	}
603 	mutex_exit(&(DEVI(dip)->devi_lock));
604 
605 	immu = immu_dmar_get_immu(dip);
606 	if (immu == NULL) {
607 		ddi_err(DER_PANIC, dip, "immu_dvma_get_immu: "
608 		    "Cannot find immu_t for device");
609 		/*NOTREACHED*/
610 	}
611 
612 	/*
613 	 * Check if some other thread found immu
614 	 * while lock was not held
615 	 */
616 	immu_devi = immu_devi_get(dip);
617 	/* immu_devi should be present as we found it earlier */
618 	if (immu_devi == NULL) {
619 		ddi_err(DER_PANIC, dip,
620 		    "immu_dvma_get_immu: No immu_devi structure");
621 		/*NOTREACHED*/
622 	}
623 
624 	mutex_enter(&(DEVI(dip)->devi_lock));
625 	if (immu_devi->imd_immu == NULL) {
626 		/* nobody else set it, so we should do it */
627 		immu_devi->imd_immu = immu;
628 		immu_devi_set_spclist(dip, immu);
629 	} else {
630 		/*
631 		 * if some other thread got immu before
632 		 * us, it should get the same results
633 		 */
634 		if (immu_devi->imd_immu != immu) {
635 			ddi_err(DER_PANIC, dip, "Multiple "
636 			    "immu units found for device. Expected (%p), "
637 			    "actual (%p)", (void *)immu,
638 			    (void *)immu_devi->imd_immu);
639 			mutex_exit(&(DEVI(dip)->devi_lock));
640 			/*NOTREACHED*/
641 		}
642 	}
643 	mutex_exit(&(DEVI(dip)->devi_lock));
644 
645 	return (immu);
646 }
647 
648 
649 /* ############################# IMMU_DEVI code ############################ */
650 
651 /*
652  * Allocate a immu_devi structure and initialize it
653  */
654 static immu_devi_t *
655 create_immu_devi(dev_info_t *rdip, int bus, int dev, int func,
656     immu_flags_t immu_flags)
657 {
658 	uchar_t baseclass, subclass;
659 	uint_t classcode, revclass;
660 	immu_devi_t *immu_devi;
661 	boolean_t pciex = B_FALSE;
662 	int kmflags;
663 	boolean_t is_pcib = B_FALSE;
664 
665 	/* bus ==  -1 indicate non-PCI device (no BDF) */
666 	ASSERT(bus == -1 || bus >= 0);
667 	ASSERT(dev >= 0);
668 	ASSERT(func >= 0);
669 
670 	kmflags = (immu_flags & IMMU_FLAGS_NOSLEEP) ? KM_NOSLEEP : KM_SLEEP;
671 	immu_devi = kmem_zalloc(sizeof (immu_devi_t), kmflags);
672 	if (immu_devi == NULL) {
673 		ddi_err(DER_WARN, rdip, "Failed to allocate memory for "
674 		    "Intel IOMMU immu_devi structure");
675 		return (NULL);
676 	}
677 	immu_devi->imd_dip = rdip;
678 	immu_devi->imd_seg = 0; /* Currently seg can only be 0 */
679 	immu_devi->imd_bus = bus;
680 	immu_devi->imd_pcib_type = IMMU_PCIB_BAD;
681 
682 	if (bus == -1) {
683 		immu_devi->imd_pcib_type = IMMU_PCIB_NOBDF;
684 		return (immu_devi);
685 	}
686 
687 	immu_devi->imd_devfunc = IMMU_PCI_DEVFUNC(dev, func);
688 	immu_devi->imd_sec = 0;
689 	immu_devi->imd_sub = 0;
690 
691 	revclass = pci_getl_func(bus, dev, func, PCI_CONF_REVID);
692 
693 	classcode = IMMU_PCI_REV2CLASS(revclass);
694 	baseclass = IMMU_PCI_CLASS2BASE(classcode);
695 	subclass = IMMU_PCI_CLASS2SUB(classcode);
696 
697 	if (baseclass == PCI_CLASS_BRIDGE && subclass == PCI_BRIDGE_PCI) {
698 
699 		immu_devi->imd_sec = pci_getb_func(bus, dev, func,
700 		    PCI_BCNF_SECBUS);
701 		immu_devi->imd_sub = pci_getb_func(bus, dev, func,
702 		    PCI_BCNF_SUBBUS);
703 
704 		pciex = device_is_pciex(bus, dev, func, &is_pcib);
705 		if (pciex  == B_TRUE && is_pcib == B_TRUE) {
706 			immu_devi->imd_pcib_type = IMMU_PCIB_PCIE_PCI;
707 		} else if (pciex == B_TRUE) {
708 			immu_devi->imd_pcib_type = IMMU_PCIB_PCIE_PCIE;
709 		} else {
710 			immu_devi->imd_pcib_type = IMMU_PCIB_PCI_PCI;
711 		}
712 	} else {
713 		immu_devi->imd_pcib_type = IMMU_PCIB_ENDPOINT;
714 	}
715 
716 	/* check for certain special devices */
717 	immu_devi->imd_display = device_is_display(classcode);
718 
719 	immu_devi->imd_lpc = ((baseclass == PCI_CLASS_BRIDGE) &&
720 	    (subclass == PCI_BRIDGE_ISA)) ? B_TRUE : B_FALSE;
721 
722 	immu_devi->imd_domain = NULL;
723 
724 	immu_devi->imd_dvma_flags = immu_global_dvma_flags;
725 
726 	return (immu_devi);
727 }
728 
729 static void
730 destroy_immu_devi(immu_devi_t *immu_devi)
731 {
732 	kmem_free(immu_devi, sizeof (immu_devi_t));
733 }
734 
735 static domain_t *
736 immu_devi_domain(dev_info_t *rdip, dev_info_t **ddipp)
737 {
738 	immu_devi_t *immu_devi;
739 	domain_t *domain;
740 	dev_info_t *ddip;
741 
742 	ASSERT(rdip);
743 	ASSERT(ddipp);
744 
745 	*ddipp = NULL;
746 
747 	immu_devi = immu_devi_get(rdip);
748 	if (immu_devi == NULL) {
749 		return (NULL);
750 	}
751 
752 	mutex_enter(&(DEVI(rdip)->devi_lock));
753 	domain = immu_devi->imd_domain;
754 	ddip = immu_devi->imd_ddip;
755 	mutex_exit(&(DEVI(rdip)->devi_lock));
756 
757 	if (domain) {
758 		ASSERT(domain->dom_did > 0);
759 		ASSERT(ddip);
760 		*ddipp = ddip;
761 	}
762 
763 	return (domain);
764 
765 }
766 
767 /* ############################# END IMMU_DEVI code ######################## */
768 /* ############################# DOMAIN code ############################### */
769 
770 /*
771  * This routine always succeeds
772  */
773 static int
774 did_alloc(immu_t *immu, dev_info_t *rdip,
775     dev_info_t *ddip, immu_flags_t immu_flags)
776 {
777 	int did;
778 
779 	ASSERT(immu);
780 	ASSERT(rdip);
781 	ASSERT(rdip != root_devinfo);
782 
783 	did = (uintptr_t)vmem_alloc(immu->immu_did_arena, 1,
784 	    (immu_flags & IMMU_FLAGS_NOSLEEP) ? VM_NOSLEEP : VM_SLEEP);
785 
786 	if (did == 0) {
787 		ASSERT(immu->immu_unity_domain);
788 		ASSERT(immu->immu_unity_domain->dom_did > 0);
789 		ddi_err(DER_WARN, rdip, "device domain-id alloc error"
790 		    " domain-device: %s%d. immu unit is %s. Using "
791 		    "unity domain with domain-id (%d)",
792 		    ddi_driver_name(ddip), ddi_get_instance(ddip),
793 		    immu->immu_name, immu->immu_unity_domain->dom_did);
794 		did = immu->immu_unity_domain->dom_did;
795 	}
796 
797 	return (did);
798 }
799 
800 static int
801 get_branch_domain(dev_info_t *pdip, void *arg)
802 {
803 	immu_devi_t *immu_devi;
804 	domain_t *domain;
805 	dev_info_t *ddip;
806 	immu_t *immu;
807 	dvma_arg_t *dvp = (dvma_arg_t *)arg;
808 
809 	ASSERT(pdip);
810 	ASSERT(dvp);
811 	ASSERT(dvp->dva_rdip);
812 
813 	/*
814 	 * The field dvp->dva_rdip is a work-in-progress
815 	 * and gets updated as we walk up the ancestor
816 	 * tree. The final ddip is set only when we reach
817 	 * the top of the tree. So the dvp->dva_ddip field cannot
818 	 * be relied on until we reach the top of the field.
819 	 */
820 
821 	/* immu_devi may not be set. */
822 	immu_devi = immu_devi_get(pdip);
823 	if (immu_devi == NULL) {
824 		if (immu_devi_set(pdip, dvp->dva_flags) != DDI_SUCCESS) {
825 			dvp->dva_error = DDI_FAILURE;
826 			return (DDI_WALK_TERMINATE);
827 		}
828 	}
829 
830 	immu_devi = immu_devi_get(pdip);
831 	ASSERT(immu_devi);
832 	immu = immu_devi->imd_immu;
833 	if (immu == NULL) {
834 		immu = immu_dvma_get_immu(pdip, dvp->dva_flags);
835 		ASSERT(immu);
836 	}
837 
838 	/*
839 	 * If we encounter a PCIE_PCIE bridge *ANCESTOR* we need to
840 	 * terminate the walk (since the device under the PCIE bridge
841 	 * is a PCIE device and has an independent entry in the
842 	 * root/context table)
843 	 */
844 	if (dvp->dva_rdip != pdip &&
845 	    immu_devi->imd_pcib_type == IMMU_PCIB_PCIE_PCIE) {
846 		return (DDI_WALK_TERMINATE);
847 	}
848 
849 	/*
850 	 * In order to be a domain-dim, it must be a PCI device i.e.
851 	 * must have valid BDF. This also eliminates the root complex.
852 	 */
853 	if (immu_devi->imd_pcib_type != IMMU_PCIB_BAD &&
854 	    immu_devi->imd_pcib_type != IMMU_PCIB_NOBDF) {
855 		ASSERT(immu_devi->imd_bus >= 0);
856 		ASSERT(immu_devi->imd_devfunc >= 0);
857 		dvp->dva_ddip = pdip;
858 	}
859 
860 	if (immu_devi->imd_display == B_TRUE ||
861 	    (dvp->dva_flags & IMMU_FLAGS_UNITY)) {
862 		dvp->dva_domain = immu->immu_unity_domain;
863 		/* continue walking to find ddip */
864 		return (DDI_WALK_CONTINUE);
865 	}
866 
867 	mutex_enter(&(DEVI(pdip)->devi_lock));
868 	domain = immu_devi->imd_domain;
869 	ddip = immu_devi->imd_ddip;
870 	mutex_exit(&(DEVI(pdip)->devi_lock));
871 
872 	if (domain && ddip) {
873 		/* if domain is set, it must be the same */
874 		if (dvp->dva_domain) {
875 			ASSERT(domain == dvp->dva_domain);
876 		}
877 		dvp->dva_domain = domain;
878 		dvp->dva_ddip = ddip;
879 		return (DDI_WALK_TERMINATE);
880 	}
881 
882 	/* immu_devi either has both set or both clear */
883 	ASSERT(domain == NULL);
884 	ASSERT(ddip == NULL);
885 
886 	/* Domain may already be set, continue walking so that ddip gets set */
887 	if (dvp->dva_domain) {
888 		return (DDI_WALK_CONTINUE);
889 	}
890 
891 	/* domain is not set in either immu_devi or dvp */
892 	domain = bdf_domain_lookup(immu_devi);
893 	if (domain == NULL) {
894 		return (DDI_WALK_CONTINUE);
895 	}
896 
897 	/* ok, the BDF hash had a domain for this BDF. */
898 
899 	/* Grab lock again to check if something else set immu_devi fields */
900 	mutex_enter(&(DEVI(pdip)->devi_lock));
901 	if (immu_devi->imd_domain != NULL) {
902 		ASSERT(immu_devi->imd_domain == domain);
903 		dvp->dva_domain = domain;
904 	} else {
905 		dvp->dva_domain = domain;
906 	}
907 	mutex_exit(&(DEVI(pdip)->devi_lock));
908 
909 	/*
910 	 * walk upwards until the topmost PCI bridge is found
911 	 */
912 	return (DDI_WALK_CONTINUE);
913 
914 }
915 
916 static void
917 map_unity_domain(domain_t *domain)
918 {
919 	struct memlist *mp;
920 	uint64_t start;
921 	uint64_t npages;
922 	dcookie_t dcookies[1] = {0};
923 	int dcount = 0;
924 
925 	ASSERT(domain);
926 	ASSERT(domain->dom_did == IMMU_UNITY_DID);
927 
928 	/*
929 	 * We call into routines that grab the lock so we should
930 	 * not be called with the lock held. This does not matter
931 	 * much since, no else has a reference to this domain
932 	 */
933 	ASSERT(!rw_lock_held(&(domain->dom_pgtable_rwlock)));
934 
935 	/*
936 	 * UNITY arenas are a mirror of the physical memory
937 	 * installed on the system.
938 	 */
939 
940 #ifdef BUGGY_DRIVERS
941 	/*
942 	 * Dont skip page0. Some broken HW/FW access it.
943 	 */
944 	dcookies[0].dck_paddr = 0;
945 	dcookies[0].dck_npages = 1;
946 	dcount = 1;
947 	(void) dvma_map(domain->dom_immu, domain, 0, 1, dcookies, dcount, NULL,
948 	    IMMU_FLAGS_READ | IMMU_FLAGS_WRITE | IMMU_FLAGS_PAGE1);
949 #endif
950 
951 	memlist_read_lock();
952 
953 	mp = phys_install;
954 
955 	if (mp->ml_address == 0) {
956 		/* since we already mapped page1 above */
957 		start = IMMU_PAGESIZE;
958 	} else {
959 		start = mp->ml_address;
960 	}
961 	npages = mp->ml_size/IMMU_PAGESIZE + 1;
962 
963 	dcookies[0].dck_paddr = start;
964 	dcookies[0].dck_npages = npages;
965 	dcount = 1;
966 	(void) dvma_map(domain->dom_immu, domain, start, npages, dcookies,
967 	    dcount, NULL, IMMU_FLAGS_READ | IMMU_FLAGS_WRITE);
968 
969 	ddi_err(DER_LOG, NULL, "IMMU: mapping PHYS span [0x%" PRIx64
970 	    " - 0x%" PRIx64 "]", start, start + mp->ml_size);
971 
972 	mp = mp->ml_next;
973 	while (mp) {
974 		ddi_err(DER_LOG, NULL, "IMMU: mapping PHYS span [0x%" PRIx64
975 		    " - 0x%" PRIx64 "]", mp->ml_address,
976 		    mp->ml_address + mp->ml_size);
977 
978 		start = mp->ml_address;
979 		npages = mp->ml_size/IMMU_PAGESIZE + 1;
980 
981 		dcookies[0].dck_paddr = start;
982 		dcookies[0].dck_npages = npages;
983 		dcount = 1;
984 		(void) dvma_map(domain->dom_immu, domain, start, npages,
985 		    dcookies, dcount, NULL, IMMU_FLAGS_READ | IMMU_FLAGS_WRITE);
986 		mp = mp->ml_next;
987 	}
988 
989 	mp = bios_rsvd;
990 	while (mp) {
991 		ddi_err(DER_LOG, NULL, "IMMU: mapping PHYS span [0x%" PRIx64
992 		    " - 0x%" PRIx64 "]", mp->ml_address,
993 		    mp->ml_address + mp->ml_size);
994 
995 		start = mp->ml_address;
996 		npages = mp->ml_size/IMMU_PAGESIZE + 1;
997 
998 		dcookies[0].dck_paddr = start;
999 		dcookies[0].dck_npages = npages;
1000 		dcount = 1;
1001 		(void) dvma_map(domain->dom_immu, domain, start, npages,
1002 		    dcookies, dcount, NULL, IMMU_FLAGS_READ | IMMU_FLAGS_WRITE);
1003 
1004 		mp = mp->ml_next;
1005 	}
1006 
1007 	memlist_read_unlock();
1008 }
1009 
1010 /*
1011  * create_xlate_arena()
1012  * 	Create the dvma arena for a domain with translation
1013  *	mapping
1014  */
1015 static void
1016 create_xlate_arena(immu_t *immu, domain_t *domain,
1017     dev_info_t *rdip, immu_flags_t immu_flags)
1018 {
1019 	char *arena_name;
1020 	struct memlist *mp;
1021 	int vmem_flags;
1022 	uint64_t start;
1023 	uint_t mgaw;
1024 	uint64_t size;
1025 	uint64_t maxaddr;
1026 	void *vmem_ret;
1027 
1028 	arena_name = domain->dom_dvma_arena_name;
1029 
1030 	/* Note, don't do sizeof (arena_name) - it is just a pointer */
1031 	(void) snprintf(arena_name,
1032 	    sizeof (domain->dom_dvma_arena_name),
1033 	    "%s-domain-%d-xlate-DVMA-arena", immu->immu_name,
1034 	    domain->dom_did);
1035 
1036 	vmem_flags = (immu_flags & IMMU_FLAGS_NOSLEEP) ? VM_NOSLEEP : VM_SLEEP;
1037 
1038 	/*
1039 	 * No one else has access to this domain.
1040 	 * So no domain locks needed
1041 	 */
1042 	ASSERT(!rw_lock_held(&(domain->dom_pgtable_rwlock)));
1043 
1044 	/* Restrict mgaddr (max guest addr) to MGAW */
1045 	mgaw = IMMU_CAP_MGAW(immu->immu_regs_cap);
1046 
1047 	/*
1048 	 * To ensure we avoid ioapic and PCI MMIO ranges we just
1049 	 * use the physical memory address range of the system as the
1050 	 * range
1051 	 */
1052 	maxaddr = ((uint64_t)1 << mgaw);
1053 
1054 	memlist_read_lock();
1055 
1056 	mp = phys_install;
1057 
1058 	if (mp->ml_address == 0)
1059 		start = MMU_PAGESIZE;
1060 	else
1061 		start = mp->ml_address;
1062 
1063 	if (start + mp->ml_size > maxaddr)
1064 		size = maxaddr - start;
1065 	else
1066 		size = mp->ml_size;
1067 
1068 	ddi_err(DER_VERB, rdip,
1069 	    "%s: Creating dvma vmem arena [0x%" PRIx64
1070 	    " - 0x%" PRIx64 "]", arena_name, start, start + size);
1071 
1072 	ASSERT(domain->dom_dvma_arena == NULL);
1073 
1074 	/*
1075 	 * We always allocate in quanta of IMMU_PAGESIZE
1076 	 */
1077 	domain->dom_dvma_arena = vmem_create(arena_name,
1078 	    (void *)(uintptr_t)start,	/* start addr */
1079 	    size,			/* size */
1080 	    IMMU_PAGESIZE,		/* quantum */
1081 	    NULL,			/* afunc */
1082 	    NULL,			/* ffunc */
1083 	    NULL,			/* source */
1084 	    0,				/* qcache_max */
1085 	    vmem_flags);
1086 
1087 	if (domain->dom_dvma_arena == NULL) {
1088 		ddi_err(DER_PANIC, rdip,
1089 		    "Failed to allocate DVMA arena(%s) "
1090 		    "for domain ID (%d)", arena_name, domain->dom_did);
1091 		/*NOTREACHED*/
1092 	}
1093 
1094 	mp = mp->ml_next;
1095 	while (mp) {
1096 
1097 		if (mp->ml_address == 0)
1098 			start = MMU_PAGESIZE;
1099 		else
1100 			start = mp->ml_address;
1101 
1102 		if (start + mp->ml_size > maxaddr)
1103 			size = maxaddr - start;
1104 		else
1105 			size = mp->ml_size;
1106 
1107 		ddi_err(DER_VERB, rdip,
1108 		    "%s: Adding dvma vmem span [0x%" PRIx64
1109 		    " - 0x%" PRIx64 "]", arena_name, start,
1110 		    start + size);
1111 
1112 		vmem_ret = vmem_add(domain->dom_dvma_arena,
1113 		    (void *)(uintptr_t)start, size,  vmem_flags);
1114 
1115 		if (vmem_ret == NULL) {
1116 			ddi_err(DER_PANIC, rdip,
1117 			    "Failed to allocate DVMA arena(%s) "
1118 			    "for domain ID (%d)",
1119 			    arena_name, domain->dom_did);
1120 			/*NOTREACHED*/
1121 		}
1122 		mp = mp->ml_next;
1123 	}
1124 	memlist_read_unlock();
1125 }
1126 
1127 /* ################################### DOMAIN CODE ######################### */
1128 
1129 /*
1130  * Set the domain and domain-dip for a dip
1131  */
1132 static void
1133 set_domain(
1134 	dev_info_t *dip,
1135 	dev_info_t *ddip,
1136 	domain_t *domain)
1137 {
1138 	immu_devi_t *immu_devi;
1139 	domain_t *fdomain;
1140 	dev_info_t *fddip;
1141 
1142 	ASSERT(dip);
1143 	ASSERT(ddip);
1144 	ASSERT(domain);
1145 	ASSERT(domain->dom_did > 0); /* must be an initialized domain */
1146 
1147 	immu_devi = immu_devi_get(dip);
1148 	ASSERT(immu_devi);
1149 
1150 	mutex_enter(&(DEVI(dip)->devi_lock));
1151 	fddip = immu_devi->imd_ddip;
1152 	fdomain = immu_devi->imd_domain;
1153 
1154 	if (fddip) {
1155 		ASSERT(fddip == ddip);
1156 	} else {
1157 		immu_devi->imd_ddip = ddip;
1158 	}
1159 
1160 	if (fdomain) {
1161 		ASSERT(fdomain == domain);
1162 	} else {
1163 		immu_devi->imd_domain = domain;
1164 	}
1165 	mutex_exit(&(DEVI(dip)->devi_lock));
1166 }
1167 
1168 /*
1169  * device_domain()
1170  * 	Get domain for a device. The domain may be global in which case it
1171  *	is shared between all IOMMU units. Due to potential AGAW differences
1172  *      between IOMMU units, such global domains *have to be* UNITY mapping
1173  *      domains. Alternatively, the domain may be local to a IOMMU unit.
1174  *	Local domains may be shared or immu_devi, although the
1175  *      scope of sharing
1176  *	is restricted to devices controlled by the IOMMU unit to
1177  *      which the domain
1178  *	belongs. If shared, they (currently) have to be UNITY domains. If
1179  *      immu_devi a domain may be either UNITY or translation (XLATE) domain.
1180  */
1181 static domain_t *
1182 device_domain(dev_info_t *rdip, dev_info_t **ddipp, immu_flags_t immu_flags)
1183 {
1184 	dev_info_t *ddip; /* topmost dip in domain i.e. domain owner */
1185 	immu_t *immu;
1186 	domain_t *domain;
1187 	dvma_arg_t dvarg = {0};
1188 	int level;
1189 
1190 	ASSERT(rdip);
1191 
1192 	*ddipp = NULL;
1193 
1194 	/*
1195 	 * Check if the domain is already set. This is usually true
1196 	 * if this is not the first DVMA transaction.
1197 	 */
1198 	ddip = NULL;
1199 	domain = immu_devi_domain(rdip, &ddip);
1200 	if (domain) {
1201 		ASSERT(domain->dom_did > 0);
1202 		ASSERT(ddip);
1203 		*ddipp = ddip;
1204 		return (domain);
1205 	}
1206 
1207 	immu = immu_dvma_get_immu(rdip, immu_flags);
1208 	if (immu == NULL) {
1209 		/*
1210 		 * possible that there is no IOMMU unit for this device
1211 		 * - BIOS bugs are one example.
1212 		 */
1213 		ddi_err(DER_WARN, rdip, "No IMMU unit found for device");
1214 		return (NULL);
1215 	}
1216 
1217 	immu_flags |= immu_devi_get(rdip)->imd_dvma_flags;
1218 
1219 	dvarg.dva_rdip = rdip;
1220 	dvarg.dva_ddip = NULL;
1221 	dvarg.dva_domain = NULL;
1222 	dvarg.dva_flags = immu_flags;
1223 	level = 0;
1224 	if (immu_walk_ancestor(rdip, NULL, get_branch_domain,
1225 	    &dvarg, &level, immu_flags) != DDI_SUCCESS) {
1226 		/*
1227 		 * maybe low memory. return error,
1228 		 * so driver tries again later
1229 		 */
1230 		return (NULL);
1231 	}
1232 
1233 	/* should have walked at least 1 dip (i.e. edip) */
1234 	ASSERT(level > 0);
1235 
1236 	ddip = dvarg.dva_ddip;	/* must be present */
1237 	domain = dvarg.dva_domain;	/* may be NULL */
1238 
1239 	/*
1240 	 * We may find the domain during our ancestor walk on any one of our
1241 	 * ancestor dips, If the domain is found then the domain-dip
1242 	 * (i.e. ddip) will also be found in the same immu_devi struct.
1243 	 * The domain-dip is the highest ancestor dip which shares the
1244 	 * same domain with edip.
1245 	 * The domain may or may not be found, but the domain dip must
1246 	 * be found.
1247 	 */
1248 	if (ddip == NULL) {
1249 		ddi_err(DER_MODE, rdip, "Cannot find domain dip for device.");
1250 		return (NULL);
1251 	}
1252 
1253 	/*
1254 	 * Did we find a domain ?
1255 	 */
1256 	if (domain) {
1257 		goto found;
1258 	}
1259 
1260 	/* nope, so allocate */
1261 	domain = domain_create(immu, ddip, rdip, immu_flags);
1262 	if (domain == NULL) {
1263 		return (NULL);
1264 	}
1265 	ASSERT(domain->dom_did > 0);
1266 
1267 	/*FALLTHROUGH*/
1268 found:
1269 	/*
1270 	 * We know *domain *is* the right domain, so panic if
1271 	 * another domain is set for either the request-dip or
1272 	 * effective dip.
1273 	 */
1274 	set_domain(ddip, ddip, domain);
1275 	set_domain(rdip, ddip, domain);
1276 
1277 	*ddipp = ddip;
1278 	return (domain);
1279 }
1280 
1281 static void
1282 create_unity_domain(immu_t *immu)
1283 {
1284 	domain_t *domain;
1285 
1286 	/* 0 is reserved by Vt-d */
1287 	/*LINTED*/
1288 	ASSERT(IMMU_UNITY_DID > 0);
1289 
1290 	/* domain created during boot and always use sleep flag */
1291 	domain = kmem_zalloc(sizeof (domain_t), KM_SLEEP);
1292 
1293 	rw_init(&(domain->dom_pgtable_rwlock), NULL, RW_DEFAULT, NULL);
1294 
1295 	domain->dom_did = IMMU_UNITY_DID;
1296 	domain->dom_maptype = IMMU_MAPTYPE_UNITY;
1297 
1298 	domain->dom_immu = immu;
1299 	immu->immu_unity_domain = domain;
1300 
1301 	/*
1302 	 * Setup the domain's initial page table
1303 	 * should never fail.
1304 	 */
1305 	domain->dom_pgtable_root = pgtable_alloc(immu, IMMU_FLAGS_SLEEP);
1306 	ASSERT(domain->dom_pgtable_root);
1307 	pgtable_zero(immu, domain->dom_pgtable_root);
1308 
1309 	map_unity_domain(domain);
1310 
1311 	/*
1312 	 * put it on the system-wide UNITY domain list
1313 	 */
1314 	mutex_enter(&(immu_domain_lock));
1315 	list_insert_tail(&immu_unity_domain_list, domain);
1316 	mutex_exit(&(immu_domain_lock));
1317 }
1318 
1319 /*
1320  * ddip is the domain-dip - the topmost dip in a domain
1321  * rdip is the requesting-dip - the device which is
1322  * requesting DVMA setup
1323  * if domain is a non-shared domain rdip == ddip
1324  */
1325 static domain_t *
1326 domain_create(immu_t *immu, dev_info_t *ddip, dev_info_t *rdip,
1327     immu_flags_t immu_flags)
1328 {
1329 	int kmflags;
1330 	domain_t *domain;
1331 	char mod_hash_name[128];
1332 	immu_devi_t *immu_devi;
1333 	int did;
1334 	dcookie_t dcookies[1] = {0};
1335 	int dcount = 0;
1336 
1337 	ASSERT(immu);
1338 	ASSERT(ddip);
1339 
1340 	immu_devi = immu_devi_get(rdip);
1341 
1342 	ASSERT(immu_devi);
1343 
1344 	/*
1345 	 * First allocate a domainid.
1346 	 * This routine will never fail, since if we run out
1347 	 * of domains the unity domain will be allocated.
1348 	 */
1349 	did = did_alloc(immu, rdip, ddip, immu_flags);
1350 	ASSERT(did > 0);
1351 	if (did == IMMU_UNITY_DID) {
1352 		/* domain overflow */
1353 		ASSERT(immu->immu_unity_domain);
1354 		return (immu->immu_unity_domain);
1355 	}
1356 
1357 	kmflags = (immu_flags & IMMU_FLAGS_NOSLEEP) ? KM_NOSLEEP : KM_SLEEP;
1358 	domain = kmem_zalloc(sizeof (domain_t), kmflags);
1359 	if (domain == NULL) {
1360 		ddi_err(DER_PANIC, rdip, "Failed to alloc DVMA domain "
1361 		    "structure for device. IOMMU unit: %s", immu->immu_name);
1362 		/*NOTREACHED*/
1363 	}
1364 
1365 	rw_init(&(domain->dom_pgtable_rwlock), NULL, RW_DEFAULT, NULL);
1366 
1367 	(void) snprintf(mod_hash_name, sizeof (mod_hash_name),
1368 	    "immu%s-domain%d-pava-hash", immu->immu_name, did);
1369 
1370 	domain->dom_did = did;
1371 	domain->dom_immu = immu;
1372 	domain->dom_maptype = IMMU_MAPTYPE_XLATE;
1373 
1374 	/*
1375 	 * Create xlate DVMA arena for this domain.
1376 	 */
1377 	create_xlate_arena(immu, domain, rdip, immu_flags);
1378 
1379 	/*
1380 	 * Setup the domain's initial page table
1381 	 */
1382 	domain->dom_pgtable_root = pgtable_alloc(immu, immu_flags);
1383 	if (domain->dom_pgtable_root == NULL) {
1384 		ddi_err(DER_PANIC, rdip, "Failed to alloc root "
1385 		    "pgtable for domain (%d). IOMMU unit: %s",
1386 		    domain->dom_did, immu->immu_name);
1387 		/*NOTREACHED*/
1388 	}
1389 	pgtable_zero(immu, domain->dom_pgtable_root);
1390 
1391 	/*
1392 	 * Since this is a immu unit-specific domain, put it on
1393 	 * the per-immu domain list.
1394 	 */
1395 	mutex_enter(&(immu->immu_lock));
1396 	list_insert_head(&immu->immu_domain_list, domain);
1397 	mutex_exit(&(immu->immu_lock));
1398 
1399 	/*
1400 	 * Also put it on the system-wide xlate domain list
1401 	 */
1402 	mutex_enter(&(immu_domain_lock));
1403 	list_insert_head(&immu_xlate_domain_list, domain);
1404 	mutex_exit(&(immu_domain_lock));
1405 
1406 	bdf_domain_insert(immu_devi, domain);
1407 
1408 #ifdef BUGGY_DRIVERS
1409 	/*
1410 	 * Map page0. Some broken HW/FW access it.
1411 	 */
1412 	dcookies[0].dck_paddr = 0;
1413 	dcookies[0].dck_npages = 1;
1414 	dcount = 1;
1415 	(void) dvma_map(domain->dom_immu, domain, 0, 1, dcookies, dcount, NULL,
1416 	    IMMU_FLAGS_READ | IMMU_FLAGS_WRITE | IMMU_FLAGS_PAGE1);
1417 #endif
1418 	return (domain);
1419 }
1420 
1421 /*
1422  * Create domainid arena.
1423  * Domainid 0 is reserved by Vt-d spec and cannot be used by
1424  * system software.
1425  * Domainid 1 is reserved by solaris and used for *all* of the following:
1426  *	as the "uninitialized" domain - For devices not yet controlled
1427  *	by Solaris
1428  *	as the "unity" domain - For devices that will always belong
1429  *	to the unity domain
1430  *	as the "overflow" domain - Used for any new device after we
1431  *	run out of domains
1432  * All of the above domains map into a single domain with
1433  * domainid 1 and UNITY DVMA mapping
1434  * Each IMMU unity has its own unity/uninit/overflow domain
1435  */
1436 static void
1437 did_init(immu_t *immu)
1438 {
1439 	(void) snprintf(immu->immu_did_arena_name,
1440 	    sizeof (immu->immu_did_arena_name),
1441 	    "%s_domainid_arena", immu->immu_name);
1442 
1443 	ddi_err(DER_VERB, NULL, "%s: Creating domainid arena %s",
1444 	    immu->immu_name, immu->immu_did_arena_name);
1445 
1446 	immu->immu_did_arena = vmem_create(
1447 	    immu->immu_did_arena_name,
1448 	    (void *)(uintptr_t)(IMMU_UNITY_DID + 1),   /* start addr */
1449 	    immu->immu_max_domains - IMMU_UNITY_DID,
1450 	    1,				/* quantum */
1451 	    NULL,			/* afunc */
1452 	    NULL,			/* ffunc */
1453 	    NULL,			/* source */
1454 	    0,				/* qcache_max */
1455 	    VM_SLEEP);
1456 
1457 	/* Even with SLEEP flag, vmem_create() can fail */
1458 	if (immu->immu_did_arena == NULL) {
1459 		ddi_err(DER_PANIC, NULL, "%s: Failed to create Intel "
1460 		    "IOMMU domainid allocator: %s", immu->immu_name,
1461 		    immu->immu_did_arena_name);
1462 	}
1463 }
1464 
1465 /* #########################  CONTEXT CODE ################################# */
1466 
1467 static void
1468 context_set(immu_t *immu, domain_t *domain, pgtable_t *root_table,
1469     int bus, int devfunc)
1470 {
1471 	pgtable_t *context;
1472 	pgtable_t *pgtable_root;
1473 	pgtable_t *unity_pgtable_root;
1474 	hw_rce_t *hw_rent;
1475 	hw_rce_t *hw_cent;
1476 	hw_rce_t *ctxp;
1477 	int sid;
1478 	krw_t rwtype;
1479 	boolean_t fill_root;
1480 	boolean_t fill_ctx;
1481 
1482 	ASSERT(immu);
1483 	ASSERT(domain);
1484 	ASSERT(root_table);
1485 	ASSERT(bus >= 0);
1486 	ASSERT(devfunc >= 0);
1487 	ASSERT(domain->dom_pgtable_root);
1488 
1489 	pgtable_root = domain->dom_pgtable_root;
1490 
1491 	ctxp = (hw_rce_t *)(root_table->swpg_next_array);
1492 	context = *(pgtable_t **)(ctxp + bus);
1493 	hw_rent = (hw_rce_t *)(root_table->hwpg_vaddr) + bus;
1494 
1495 	fill_root = B_FALSE;
1496 	fill_ctx = B_FALSE;
1497 
1498 	/* Check the most common case first with reader lock */
1499 	rw_enter(&(immu->immu_ctx_rwlock), RW_READER);
1500 	rwtype = RW_READER;
1501 again:
1502 	if (ROOT_GET_P(hw_rent)) {
1503 		ASSERT(ROOT_GET_CONT(hw_rent) == context->hwpg_paddr);
1504 		hw_cent = (hw_rce_t *)(context->hwpg_vaddr) + devfunc;
1505 		if (CONT_GET_AVAIL(hw_cent) == IMMU_CONT_INITED) {
1506 			ASSERT(CONT_GET_P(hw_cent));
1507 			ASSERT(CONT_GET_DID(hw_cent) == domain->dom_did);
1508 			ASSERT(CONT_GET_AW(hw_cent) == immu->immu_dvma_agaw);
1509 			ASSERT(CONT_GET_TTYPE(hw_cent) == TTYPE_XLATE_ONLY);
1510 			ASSERT(CONT_GET_ASR(hw_cent) ==
1511 			    pgtable_root->hwpg_paddr);
1512 			rw_exit(&(immu->immu_ctx_rwlock));
1513 			return;
1514 		} else {
1515 			fill_ctx = B_TRUE;
1516 		}
1517 	} else {
1518 		fill_root = B_TRUE;
1519 		fill_ctx = B_TRUE;
1520 	}
1521 
1522 	if (rwtype == RW_READER &&
1523 	    rw_tryupgrade(&(immu->immu_ctx_rwlock)) == 0) {
1524 		rw_exit(&(immu->immu_ctx_rwlock));
1525 		rw_enter(&(immu->immu_ctx_rwlock), RW_WRITER);
1526 		rwtype = RW_WRITER;
1527 		goto again;
1528 	}
1529 	rwtype = RW_WRITER;
1530 
1531 	if (fill_root == B_TRUE) {
1532 		ROOT_SET_CONT(hw_rent, context->hwpg_paddr);
1533 		ROOT_SET_P(hw_rent);
1534 		immu_regs_cpu_flush(immu, (caddr_t)hw_rent, sizeof (hw_rce_t));
1535 	}
1536 
1537 	if (fill_ctx == B_TRUE) {
1538 		hw_cent = (hw_rce_t *)(context->hwpg_vaddr) + devfunc;
1539 		unity_pgtable_root = immu->immu_unity_domain->dom_pgtable_root;
1540 		ASSERT(CONT_GET_AVAIL(hw_cent) == IMMU_CONT_UNINITED);
1541 		ASSERT(CONT_GET_P(hw_cent));
1542 		ASSERT(CONT_GET_DID(hw_cent) ==
1543 		    immu->immu_unity_domain->dom_did);
1544 		ASSERT(CONT_GET_AW(hw_cent) == immu->immu_dvma_agaw);
1545 		ASSERT(CONT_GET_TTYPE(hw_cent) == TTYPE_XLATE_ONLY);
1546 		ASSERT(CONT_GET_ASR(hw_cent) ==
1547 		    unity_pgtable_root->hwpg_paddr);
1548 
1549 		/* need to disable context entry before reprogramming it */
1550 		bzero(hw_cent, sizeof (hw_rce_t));
1551 
1552 		/* flush caches */
1553 		immu_regs_cpu_flush(immu, (caddr_t)hw_cent, sizeof (hw_rce_t));
1554 		ASSERT(rw_write_held(&(immu->immu_ctx_rwlock)));
1555 
1556 		sid = ((bus << 8) | devfunc);
1557 		immu_flush_context_fsi(immu, 0, sid, domain->dom_did);
1558 
1559 		immu_regs_wbf_flush(immu);
1560 
1561 		CONT_SET_AVAIL(hw_cent, IMMU_CONT_INITED);
1562 		CONT_SET_DID(hw_cent, domain->dom_did);
1563 		CONT_SET_AW(hw_cent, immu->immu_dvma_agaw);
1564 		CONT_SET_ASR(hw_cent, pgtable_root->hwpg_paddr);
1565 		/*LINTED*/
1566 		CONT_SET_TTYPE(hw_cent, TTYPE_XLATE_ONLY);
1567 		CONT_SET_P(hw_cent);
1568 		immu_regs_cpu_flush(immu, (caddr_t)hw_cent, sizeof (hw_rce_t));
1569 	}
1570 	rw_exit(&(immu->immu_ctx_rwlock));
1571 }
1572 
1573 static pgtable_t *
1574 context_create(immu_t *immu)
1575 {
1576 	int	bus;
1577 	int	devfunc;
1578 	pgtable_t *root_table;
1579 	pgtable_t *context;
1580 	pgtable_t *pgtable_root;
1581 	hw_rce_t *ctxp;
1582 	hw_rce_t *hw_rent;
1583 	hw_rce_t *hw_cent;
1584 
1585 	/* Allocate a zeroed root table (4K 256b entries) */
1586 	root_table = pgtable_alloc(immu, IMMU_FLAGS_SLEEP);
1587 	pgtable_zero(immu, root_table);
1588 
1589 	/*
1590 	 * Setup context tables for all possible root table entries.
1591 	 * Start out with unity domains for all entries.
1592 	 */
1593 	ctxp = (hw_rce_t *)(root_table->swpg_next_array);
1594 	hw_rent = (hw_rce_t *)(root_table->hwpg_vaddr);
1595 	for (bus = 0; bus < IMMU_ROOT_NUM; bus++, ctxp++, hw_rent++) {
1596 		context = pgtable_alloc(immu, IMMU_FLAGS_SLEEP);
1597 		pgtable_zero(immu, context);
1598 		ASSERT(ROOT_GET_P(hw_rent) == 0);
1599 		ROOT_SET_P(hw_rent);
1600 		ROOT_SET_CONT(hw_rent, context->hwpg_paddr);
1601 		hw_cent = (hw_rce_t *)(context->hwpg_vaddr);
1602 		for (devfunc = 0; devfunc < IMMU_CONT_NUM;
1603 		    devfunc++, hw_cent++) {
1604 			ASSERT(CONT_GET_P(hw_cent) == 0);
1605 			pgtable_root =
1606 			    immu->immu_unity_domain->dom_pgtable_root;
1607 			CONT_SET_DID(hw_cent,
1608 			    immu->immu_unity_domain->dom_did);
1609 			CONT_SET_AW(hw_cent, immu->immu_dvma_agaw);
1610 			CONT_SET_ASR(hw_cent, pgtable_root->hwpg_paddr);
1611 			/*LINTED*/
1612 			CONT_SET_TTYPE(hw_cent, TTYPE_XLATE_ONLY);
1613 			CONT_SET_AVAIL(hw_cent, IMMU_CONT_UNINITED);
1614 			CONT_SET_P(hw_cent);
1615 		}
1616 		immu_regs_cpu_flush(immu, context->hwpg_vaddr, IMMU_PAGESIZE);
1617 		*((pgtable_t **)ctxp) = context;
1618 	}
1619 	immu_regs_cpu_flush(immu, root_table->hwpg_vaddr, IMMU_PAGESIZE);
1620 
1621 	return (root_table);
1622 }
1623 
1624 /*
1625  * Called during rootnex attach, so no locks needed
1626  */
1627 static void
1628 context_init(immu_t *immu)
1629 {
1630 	ASSERT(immu);
1631 	ASSERT(immu->immu_ctx_root == NULL);
1632 
1633 	rw_init(&(immu->immu_ctx_rwlock), NULL, RW_DEFAULT, NULL);
1634 
1635 	immu_regs_wbf_flush(immu);
1636 
1637 	immu->immu_ctx_root = context_create(immu);
1638 
1639 	immu_regs_set_root_table(immu);
1640 
1641 	rw_enter(&(immu->immu_ctx_rwlock), RW_WRITER);
1642 	immu_flush_context_gbl(immu);
1643 	rw_exit(&(immu->immu_ctx_rwlock));
1644 	immu_flush_iotlb_gbl(immu);
1645 	immu_regs_wbf_flush(immu);
1646 }
1647 
1648 
1649 /*
1650  * Find top pcib
1651  */
1652 static int
1653 find_top_pcib(dev_info_t *dip, void *arg)
1654 {
1655 	immu_devi_t *immu_devi;
1656 	dev_info_t **pcibdipp = (dev_info_t **)arg;
1657 
1658 	ASSERT(dip);
1659 
1660 	immu_devi = immu_devi_get(dip);
1661 	ASSERT(immu_devi);
1662 
1663 	if (immu_devi->imd_pcib_type == IMMU_PCIB_PCI_PCI) {
1664 		*pcibdipp = dip;
1665 	}
1666 
1667 	return (DDI_WALK_CONTINUE);
1668 }
1669 
1670 static int
1671 immu_context_update(immu_t *immu, domain_t *domain, dev_info_t *ddip,
1672     dev_info_t *rdip, immu_flags_t immu_flags)
1673 {
1674 	immu_devi_t *r_immu_devi;
1675 	immu_devi_t *d_immu_devi;
1676 	int r_bus;
1677 	int d_bus;
1678 	int r_devfunc;
1679 	int d_devfunc;
1680 	immu_pcib_t d_pcib_type;
1681 	immu_pcib_t r_pcib_type;
1682 	dev_info_t *pcibdip;
1683 
1684 	if (ddip == NULL || rdip == NULL ||
1685 	    ddip == root_devinfo || rdip == root_devinfo) {
1686 		ddi_err(DER_MODE, rdip, "immu_contexts_update: domain-dip or "
1687 		    "request-dip are NULL or are root devinfo");
1688 		return (DDI_FAILURE);
1689 	}
1690 
1691 	/*
1692 	 * We need to set the context fields
1693 	 * based on what type of device rdip and ddip are.
1694 	 * To do that we need the immu_devi field.
1695 	 * Set the immu_devi field (if not already set)
1696 	 */
1697 	if (immu_devi_set(ddip, immu_flags) == DDI_FAILURE) {
1698 		ddi_err(DER_MODE, rdip,
1699 		    "immu_context_update: failed to set immu_devi for ddip");
1700 		return (DDI_FAILURE);
1701 	}
1702 
1703 	if (immu_devi_set(rdip, immu_flags) == DDI_FAILURE) {
1704 		ddi_err(DER_MODE, rdip,
1705 		    "immu_context_update: failed to set immu_devi for rdip");
1706 		return (DDI_FAILURE);
1707 	}
1708 
1709 	d_immu_devi = immu_devi_get(ddip);
1710 	r_immu_devi = immu_devi_get(rdip);
1711 	ASSERT(r_immu_devi);
1712 	ASSERT(d_immu_devi);
1713 
1714 	d_bus = d_immu_devi->imd_bus;
1715 	d_devfunc = d_immu_devi->imd_devfunc;
1716 	d_pcib_type = d_immu_devi->imd_pcib_type;
1717 	r_bus = r_immu_devi->imd_bus;
1718 	r_devfunc = r_immu_devi->imd_devfunc;
1719 	r_pcib_type = r_immu_devi->imd_pcib_type;
1720 
1721 	ASSERT(d_bus >= 0);
1722 
1723 	if (rdip == ddip) {
1724 		ASSERT(d_pcib_type == IMMU_PCIB_ENDPOINT ||
1725 		    d_pcib_type == IMMU_PCIB_PCIE_PCIE);
1726 		ASSERT(r_bus >= 0);
1727 		ASSERT(r_devfunc >= 0);
1728 		/* rdip is a PCIE device. set context for it only */
1729 		context_set(immu, domain, immu->immu_ctx_root, r_bus,
1730 		    r_devfunc);
1731 #ifdef BUGGY_DRIVERS
1732 	} else if (r_immu_devi == d_immu_devi) {
1733 #ifdef TEST
1734 		ddi_err(DER_WARN, rdip, "Driver bug: Devices 0x%lx and "
1735 		    "0x%lx are identical", rdip, ddip);
1736 #endif
1737 		ASSERT(d_pcib_type == IMMU_PCIB_ENDPOINT);
1738 		ASSERT(r_bus >= 0);
1739 		ASSERT(r_devfunc >= 0);
1740 		/* rdip is a PCIE device. set context for it only */
1741 		context_set(immu, domain, immu->immu_ctx_root, r_bus,
1742 		    r_devfunc);
1743 #endif
1744 	} else if (d_pcib_type == IMMU_PCIB_PCIE_PCI) {
1745 		/*
1746 		 * ddip is a PCIE_PCI bridge. Set context for ddip's
1747 		 * secondary bus. If rdip is on ddip's secondary
1748 		 * bus, set context for rdip. Else, set context
1749 		 * for rdip's PCI bridge on ddip's secondary bus.
1750 		 */
1751 		context_set(immu, domain, immu->immu_ctx_root,
1752 		    d_immu_devi->imd_sec, 0);
1753 		if (d_immu_devi->imd_sec == r_bus) {
1754 			context_set(immu, domain, immu->immu_ctx_root,
1755 			    r_bus, r_devfunc);
1756 		} else {
1757 			pcibdip = NULL;
1758 			if (immu_walk_ancestor(rdip, ddip, find_top_pcib,
1759 			    &pcibdip, NULL, immu_flags) == DDI_SUCCESS &&
1760 			    pcibdip != NULL) {
1761 				ASSERT(pcibdip);
1762 				r_immu_devi = immu_devi_get(pcibdip);
1763 				ASSERT(d_immu_devi);
1764 				ASSERT(d_immu_devi->imd_pcib_type ==
1765 				    IMMU_PCIB_PCI_PCI);
1766 				r_bus = r_immu_devi->imd_bus;
1767 				r_devfunc = r_immu_devi->imd_devfunc;
1768 				context_set(immu, domain, immu->immu_ctx_root,
1769 				    r_bus, r_devfunc);
1770 			} else {
1771 				ddi_err(DER_PANIC, rdip, "Failed to find PCI "
1772 				    " bridge for PCI device");
1773 				/*NOTREACHED*/
1774 			}
1775 		}
1776 	} else if (d_pcib_type == IMMU_PCIB_PCI_PCI) {
1777 		context_set(immu, domain, immu->immu_ctx_root, d_bus,
1778 		    d_devfunc);
1779 	} else if (d_pcib_type == IMMU_PCIB_ENDPOINT) {
1780 		ASSERT(r_pcib_type == IMMU_PCIB_NOBDF);
1781 		/*
1782 		 * ddip is a PCIE device which has a non-PCI device under it
1783 		 * i.e. it is a PCI-nonPCI bridge. Example: pciicde-ata
1784 		 */
1785 		context_set(immu, domain, immu->immu_ctx_root, d_bus,
1786 		    d_devfunc);
1787 	} else {
1788 		ddi_err(DER_PANIC, rdip, "unknown device type. Cannot "
1789 		    "set IMMU context.");
1790 		/*NOTREACHED*/
1791 	}
1792 
1793 	/* XXX do we need a membar_producer() here */
1794 	return (DDI_SUCCESS);
1795 }
1796 
1797 /* ##################### END CONTEXT CODE ################################## */
1798 /* ##################### MAPPING CODE ################################## */
1799 
1800 
1801 static boolean_t
1802 PDTE_check(immu_t *immu, hw_pdte_t pdte, pgtable_t *next, paddr_t paddr,
1803     dev_info_t *rdip, immu_flags_t immu_flags)
1804 {
1805 	if (immu_flags & IMMU_FLAGS_PAGE1) {
1806 		ASSERT(paddr == 0);
1807 	} else {
1808 		ASSERT((next == NULL) ^ (paddr == 0));
1809 	}
1810 
1811 	/* The PDTE must be set i.e. present bit is set */
1812 	if (!PDTE_P(pdte)) {
1813 		ddi_err(DER_MODE, rdip, "No present flag");
1814 		return (B_FALSE);
1815 	}
1816 
1817 	/*
1818 	 * Just assert to check most significant system software field
1819 	 * (PDTE_SW4) as it is same as present bit and we
1820 	 * checked that above
1821 	 */
1822 	ASSERT(PDTE_SW4(pdte));
1823 
1824 	/*
1825 	 * TM field should be clear if not reserved.
1826 	 * non-leaf is always reserved
1827 	 */
1828 	if (next == NULL && immu->immu_TM_reserved == B_FALSE) {
1829 		if (PDTE_TM(pdte)) {
1830 			ddi_err(DER_MODE, rdip, "TM flag set");
1831 			return (B_FALSE);
1832 		}
1833 	}
1834 
1835 	/*
1836 	 * The SW3 field is not used and must be clear
1837 	 */
1838 	if (PDTE_SW3(pdte)) {
1839 		ddi_err(DER_MODE, rdip, "SW3 set");
1840 		return (B_FALSE);
1841 	}
1842 
1843 	/*
1844 	 * PFN (for PTE) or next level pgtable-paddr (for PDE) must be set
1845 	 */
1846 	if (next == NULL) {
1847 		ASSERT(paddr % IMMU_PAGESIZE == 0);
1848 		if (PDTE_PADDR(pdte) != paddr) {
1849 			ddi_err(DER_MODE, rdip,
1850 			    "PTE paddr mismatch: %lx != %lx",
1851 			    PDTE_PADDR(pdte), paddr);
1852 			return (B_FALSE);
1853 		}
1854 	} else {
1855 		if (PDTE_PADDR(pdte) != next->hwpg_paddr) {
1856 			ddi_err(DER_MODE, rdip,
1857 			    "PDE paddr mismatch: %lx != %lx",
1858 			    PDTE_PADDR(pdte), next->hwpg_paddr);
1859 			return (B_FALSE);
1860 		}
1861 	}
1862 
1863 	/*
1864 	 * SNP field should be clear if not reserved.
1865 	 * non-leaf is always reserved
1866 	 */
1867 	if (next == NULL && immu->immu_SNP_reserved == B_FALSE) {
1868 		if (PDTE_SNP(pdte)) {
1869 			ddi_err(DER_MODE, rdip, "SNP set");
1870 			return (B_FALSE);
1871 		}
1872 	}
1873 
1874 	/* second field available for system software should be clear */
1875 	if (PDTE_SW2(pdte)) {
1876 		ddi_err(DER_MODE, rdip, "SW2 set");
1877 		return (B_FALSE);
1878 	}
1879 
1880 	/* Super pages field should be clear */
1881 	if (PDTE_SP(pdte)) {
1882 		ddi_err(DER_MODE, rdip, "SP set");
1883 		return (B_FALSE);
1884 	}
1885 
1886 	/*
1887 	 * least significant field available for
1888 	 * system software should be clear
1889 	 */
1890 	if (PDTE_SW1(pdte)) {
1891 		ddi_err(DER_MODE, rdip, "SW1 set");
1892 		return (B_FALSE);
1893 	}
1894 
1895 	if ((immu_flags & IMMU_FLAGS_READ) && !PDTE_READ(pdte)) {
1896 		ddi_err(DER_MODE, rdip, "READ not set");
1897 		return (B_FALSE);
1898 	}
1899 
1900 	if ((immu_flags & IMMU_FLAGS_WRITE) && !PDTE_WRITE(pdte)) {
1901 		ddi_err(DER_MODE, rdip, "WRITE not set");
1902 		return (B_FALSE);
1903 	}
1904 
1905 	return (B_TRUE);
1906 }
1907 /*ARGSUSED*/
1908 static void
1909 PTE_clear_all(immu_t *immu, domain_t *domain, xlate_t *xlate,
1910     uint64_t *dvma_ptr, uint64_t *npages_ptr, dev_info_t *rdip)
1911 {
1912 	uint64_t npages;
1913 	uint64_t dvma;
1914 	pgtable_t *pgtable;
1915 	hw_pdte_t *hwp;
1916 	hw_pdte_t *shwp;
1917 	int idx;
1918 	hw_pdte_t pte;
1919 
1920 	ASSERT(xlate->xlt_level == 1);
1921 
1922 	pgtable = xlate->xlt_pgtable;
1923 	idx = xlate->xlt_idx;
1924 
1925 	ASSERT(pgtable);
1926 	ASSERT(idx <= IMMU_PGTABLE_MAXIDX);
1927 
1928 	dvma = *dvma_ptr;
1929 	npages = *npages_ptr;
1930 
1931 	ASSERT(dvma);
1932 	ASSERT(dvma % IMMU_PAGESIZE == 0);
1933 	ASSERT(npages);
1934 
1935 	/*
1936 	 * since a caller gets a unique dvma for a physical address,
1937 	 * no other concurrent thread will be writing to the same
1938 	 * PTE even if it has the same paddr. So no locks needed.
1939 	 */
1940 	shwp = (hw_pdte_t *)(pgtable->hwpg_vaddr) + idx;
1941 
1942 	hwp = shwp;
1943 	for (; npages > 0 && idx <= IMMU_PGTABLE_MAXIDX; idx++, hwp++) {
1944 
1945 		pte = *hwp;
1946 
1947 		/* Cannot clear a HW PTE that is aleady clear */
1948 		ASSERT(PDTE_P(pte));
1949 		PDTE_CLEAR_P(pte);
1950 		*hwp = pte;
1951 
1952 		dvma += IMMU_PAGESIZE;
1953 		npages--;
1954 	}
1955 
1956 
1957 #ifdef TEST
1958 	/* dont need to flush write during unmap */
1959 	immu_regs_cpu_flush(immu, (caddr_t)shwp,
1960 	    (hwp - shwp) * sizeof (hw_pdte_t));
1961 #endif
1962 
1963 	*dvma_ptr = dvma;
1964 	*npages_ptr = npages;
1965 
1966 	xlate->xlt_idx = idx;
1967 }
1968 
1969 /*ARGSUSED*/
1970 static void
1971 xlate_setup(immu_t *immu, uint64_t dvma, xlate_t *xlate,
1972     int nlevels, dev_info_t *rdip)
1973 {
1974 	int level;
1975 	uint64_t offbits;
1976 
1977 	/* level 0 is never used. Sanity check */
1978 	ASSERT(xlate->xlt_level == 0);
1979 	ASSERT(xlate->xlt_idx == 0);
1980 	ASSERT(xlate->xlt_pgtable == NULL);
1981 	ASSERT(dvma % IMMU_PAGESIZE == 0);
1982 
1983 	/*
1984 	 * Skip the first 12 bits which is the offset into
1985 	 * 4K PFN (phys page frame based on IMMU_PAGESIZE)
1986 	 */
1987 	offbits = dvma >> IMMU_PAGESHIFT;
1988 
1989 	/* skip to level 1 i.e. leaf PTE */
1990 	for (level = 1, xlate++; level <= nlevels; level++, xlate++) {
1991 		xlate->xlt_level = level;
1992 		xlate->xlt_idx = (offbits & IMMU_PGTABLE_LEVEL_MASK);
1993 		ASSERT(xlate->xlt_idx <= IMMU_PGTABLE_MAXIDX);
1994 		xlate->xlt_pgtable = NULL;
1995 		offbits >>= IMMU_PGTABLE_LEVEL_STRIDE;
1996 	}
1997 }
1998 
1999 /*
2000  * Read the pgtables
2001  */
2002 static void
2003 PDE_lookup(immu_t *immu, domain_t *domain, xlate_t *xlate, int nlevels,
2004     dev_info_t *rdip)
2005 {
2006 	pgtable_t *pgtable;
2007 	pgtable_t *next;
2008 	hw_pdte_t pde;
2009 	uint_t idx;
2010 
2011 	/* xlate should be at level 0 */
2012 	ASSERT(xlate->xlt_level == 0);
2013 	ASSERT(xlate->xlt_idx == 0);
2014 
2015 	/* start with highest level pgtable i.e. root */
2016 	xlate += nlevels;
2017 	ASSERT(xlate->xlt_level == nlevels);
2018 
2019 	if (xlate->xlt_pgtable == NULL) {
2020 		xlate->xlt_pgtable = domain->dom_pgtable_root;
2021 	}
2022 
2023 	for (; xlate->xlt_level > 1; xlate--) {
2024 
2025 		idx = xlate->xlt_idx;
2026 		pgtable = xlate->xlt_pgtable;
2027 
2028 		ASSERT(pgtable);
2029 		ASSERT(idx <= IMMU_PGTABLE_MAXIDX);
2030 
2031 		if ((xlate - 1)->xlt_pgtable) {
2032 			continue;
2033 		}
2034 
2035 		/* xlate's leafier level is not set, set it now */
2036 
2037 		/* Lock the pgtable in read mode */
2038 		rw_enter(&(pgtable->swpg_rwlock), RW_READER);
2039 
2040 		/*
2041 		 * since we are unmapping, the pgtable should
2042 		 * already point to a leafier pgtable.
2043 		 */
2044 		next = *(pgtable->swpg_next_array + idx);
2045 		ASSERT(next);
2046 
2047 		pde = *((hw_pdte_t *)(pgtable->hwpg_vaddr) + idx);
2048 
2049 		ASSERT(PDTE_check(immu, pde, next, 0, rdip, 0) == B_TRUE);
2050 
2051 		(xlate - 1)->xlt_pgtable = next;
2052 
2053 		rw_exit(&(pgtable->swpg_rwlock));
2054 	}
2055 }
2056 
2057 /*ARGSUSED*/
2058 static void
2059 PTE_set_one(immu_t *immu, hw_pdte_t *hwp, paddr_t paddr,
2060     dev_info_t *rdip, immu_flags_t immu_flags)
2061 {
2062 	hw_pdte_t pte;
2063 
2064 	pte = *hwp;
2065 
2066 #ifndef DEBUG
2067 	/* Set paddr */
2068 	ASSERT(paddr % IMMU_PAGESIZE == 0);
2069 	pte = 0;
2070 	PDTE_SET_PADDR(pte, paddr);
2071 	PDTE_SET_READ(pte);
2072 	PDTE_SET_WRITE(pte);
2073 	*hwp = pte;
2074 #else
2075 
2076 	if (PDTE_P(pte)) {
2077 		if (PDTE_PADDR(pte) != paddr) {
2078 			ddi_err(DER_MODE, rdip, "PTE paddr %lx != paddr %lx",
2079 			    PDTE_PADDR(pte), paddr);
2080 		}
2081 #ifdef BUGGY_DRIVERS
2082 		return;
2083 #else
2084 		goto out;
2085 #endif
2086 	}
2087 
2088 	/* Don't touch SW4. It is the present field */
2089 
2090 	/* clear TM field if not reserved */
2091 	if (immu->immu_TM_reserved == B_FALSE) {
2092 		PDTE_CLEAR_TM(pte);
2093 	}
2094 
2095 #ifdef DEBUG
2096 	/* Clear 3rd field for system software  - not used */
2097 	PDTE_CLEAR_SW3(pte);
2098 #endif
2099 
2100 	/* Set paddr */
2101 	ASSERT(paddr % IMMU_PAGESIZE == 0);
2102 	PDTE_CLEAR_PADDR(pte);
2103 	PDTE_SET_PADDR(pte, paddr);
2104 
2105 	/*  clear SNP field if not reserved. */
2106 	if (immu->immu_SNP_reserved == B_FALSE) {
2107 		PDTE_CLEAR_SNP(pte);
2108 	}
2109 
2110 #ifdef DEBUG
2111 	/* Clear SW2 field available for software */
2112 	PDTE_CLEAR_SW2(pte);
2113 #endif
2114 
2115 
2116 #ifdef DEBUG
2117 	/* SP is don't care for PTEs. Clear it for cleanliness */
2118 	PDTE_CLEAR_SP(pte);
2119 #endif
2120 
2121 #ifdef DEBUG
2122 	/* Clear SW1 field available for software */
2123 	PDTE_CLEAR_SW1(pte);
2124 #endif
2125 
2126 	/*
2127 	 * Now that we are done writing the PTE
2128 	 * set the "present" flag. Note this present
2129 	 * flag is a bit in the PDE/PTE that the
2130 	 * spec says is available for system software.
2131 	 * This is an implementation detail of Solaris
2132 	 * bare-metal Intel IOMMU.
2133 	 * The present field in a PDE/PTE is not defined
2134 	 * by the Vt-d spec
2135 	 */
2136 
2137 	PDTE_SET_P(pte);
2138 
2139 out:
2140 #ifdef BUGGY_DRIVERS
2141 	PDTE_SET_READ(pte);
2142 	PDTE_SET_WRITE(pte);
2143 #else
2144 	if (immu_flags & IMMU_FLAGS_READ)
2145 		PDTE_SET_READ(pte);
2146 	if (immu_flags & IMMU_FLAGS_WRITE)
2147 		PDTE_SET_WRITE(pte);
2148 #endif
2149 
2150 	*hwp = pte;
2151 #endif
2152 }
2153 
2154 /*ARGSUSED*/
2155 static void
2156 PTE_set_all(immu_t *immu, domain_t *domain, xlate_t *xlate,
2157     uint64_t *dvma_ptr, uint64_t *nvpages_ptr, dcookie_t *dcookies,
2158     int dcount, dev_info_t *rdip, immu_flags_t immu_flags)
2159 {
2160 	paddr_t paddr;
2161 	uint64_t nvpages;
2162 	uint64_t nppages;
2163 	uint64_t dvma;
2164 	pgtable_t *pgtable;
2165 	hw_pdte_t *hwp;
2166 	hw_pdte_t *shwp;
2167 	int idx;
2168 	int j;
2169 
2170 	ASSERT(xlate->xlt_level == 1);
2171 
2172 	pgtable = xlate->xlt_pgtable;
2173 	idx = xlate->xlt_idx;
2174 
2175 	ASSERT(idx <= IMMU_PGTABLE_MAXIDX);
2176 	ASSERT(pgtable);
2177 
2178 	dvma = *dvma_ptr;
2179 	nvpages = *nvpages_ptr;
2180 
2181 	ASSERT(dvma || (immu_flags & IMMU_FLAGS_PAGE1));
2182 	ASSERT(nvpages);
2183 
2184 	/*
2185 	 * since a caller gets a unique dvma for a physical address,
2186 	 * no other concurrent thread will be writing to the same
2187 	 * PTE even if it has the same paddr. So no locks needed.
2188 	 */
2189 	shwp = (hw_pdte_t *)(pgtable->hwpg_vaddr) + idx;
2190 
2191 	hwp = shwp;
2192 	for (j = dcount - 1; j >= 0; j--) {
2193 		if (nvpages <= dcookies[j].dck_npages)
2194 			break;
2195 		nvpages -= dcookies[j].dck_npages;
2196 	}
2197 
2198 	ASSERT(j >= 0);
2199 	ASSERT(nvpages);
2200 	ASSERT(nvpages <= dcookies[j].dck_npages);
2201 	nppages = nvpages;
2202 	paddr = dcookies[j].dck_paddr +
2203 	    (dcookies[j].dck_npages - nppages) * IMMU_PAGESIZE;
2204 
2205 	nvpages = *nvpages_ptr;
2206 	for (; nvpages > 0 && idx <= IMMU_PGTABLE_MAXIDX; idx++, hwp++) {
2207 
2208 		ASSERT(paddr || (immu_flags & IMMU_FLAGS_PAGE1));
2209 
2210 		PTE_set_one(immu, hwp, paddr, rdip, immu_flags);
2211 
2212 		ASSERT(PDTE_check(immu, *hwp, NULL, paddr, rdip, immu_flags)
2213 		    == B_TRUE);
2214 		nppages--;
2215 		nvpages--;
2216 		paddr += IMMU_PAGESIZE;
2217 		dvma += IMMU_PAGESIZE;
2218 
2219 		if (nppages == 0) {
2220 			j++;
2221 		}
2222 
2223 		if (j == dcount) {
2224 			ASSERT(nvpages == 0);
2225 			break;
2226 		}
2227 
2228 		ASSERT(nvpages);
2229 		if (nppages == 0) {
2230 			nppages = dcookies[j].dck_npages;
2231 			paddr = dcookies[j].dck_paddr;
2232 		}
2233 	}
2234 
2235 	/* flush writes to HW PTE table */
2236 	immu_regs_cpu_flush(immu, (caddr_t)shwp, (hwp - shwp) *
2237 	    sizeof (hw_pdte_t));
2238 
2239 	if (nvpages) {
2240 		*dvma_ptr = dvma;
2241 		*nvpages_ptr = nvpages;
2242 	} else {
2243 		*dvma_ptr = 0;
2244 		*nvpages_ptr = 0;
2245 	}
2246 
2247 	xlate->xlt_idx = idx;
2248 }
2249 
2250 /*ARGSUSED*/
2251 static void
2252 PDE_set_one(immu_t *immu, hw_pdte_t *hwp, pgtable_t *next,
2253     dev_info_t *rdip, immu_flags_t immu_flags)
2254 {
2255 	hw_pdte_t pde;
2256 
2257 	pde = *hwp;
2258 
2259 	/* if PDE is already set, make sure it is correct */
2260 	if (PDTE_P(pde)) {
2261 		ASSERT(PDTE_PADDR(pde) == next->hwpg_paddr);
2262 #ifdef BUGGY_DRIVERS
2263 		return;
2264 #else
2265 		goto out;
2266 #endif
2267 	}
2268 
2269 	/* Dont touch SW4, it is the present bit */
2270 
2271 	/* don't touch TM field it is reserved for PDEs */
2272 
2273 	/* 3rd field available for system software is not used */
2274 	PDTE_CLEAR_SW3(pde);
2275 
2276 	/* Set next level pgtable-paddr for PDE */
2277 	ASSERT(next->hwpg_paddr % IMMU_PAGESIZE == 0);
2278 	PDTE_CLEAR_PADDR(pde);
2279 	PDTE_SET_PADDR(pde, next->hwpg_paddr);
2280 
2281 	/* don't touch SNP field it is reserved for PDEs */
2282 
2283 	/* Clear second field available for system software */
2284 	PDTE_CLEAR_SW2(pde);
2285 
2286 	/* No super pages for PDEs */
2287 	PDTE_CLEAR_SP(pde);
2288 
2289 	/* Clear SW1 for software */
2290 	PDTE_CLEAR_SW1(pde);
2291 
2292 	/*
2293 	 * Now that we are done writing the PDE
2294 	 * set the "present" flag. Note this present
2295 	 * flag is a bit in the PDE/PTE that the
2296 	 * spec says is available for system software.
2297 	 * This is an implementation detail of Solaris
2298 	 * base-metal Intel IOMMU.
2299 	 * The present field in a PDE/PTE is not defined
2300 	 * by the Vt-d spec
2301 	 */
2302 
2303 out:
2304 #ifdef  BUGGY_DRIVERS
2305 	PDTE_SET_READ(pde);
2306 	PDTE_SET_WRITE(pde);
2307 #else
2308 	if (immu_flags & IMMU_FLAGS_READ)
2309 		PDTE_SET_READ(pde);
2310 	if (immu_flags & IMMU_FLAGS_WRITE)
2311 		PDTE_SET_WRITE(pde);
2312 #endif
2313 
2314 	PDTE_SET_P(pde);
2315 
2316 	*hwp = pde;
2317 
2318 	immu_regs_cpu_flush(immu, (caddr_t)hwp, sizeof (hw_pdte_t));
2319 }
2320 
2321 /*
2322  * Used to set PDEs
2323  */
2324 static boolean_t
2325 PDE_set_all(immu_t *immu, domain_t *domain, xlate_t *xlate, int nlevels,
2326     dev_info_t *rdip, immu_flags_t immu_flags)
2327 {
2328 	pgtable_t *pgtable;
2329 	pgtable_t *new;
2330 	pgtable_t *next;
2331 	hw_pdte_t *hwp;
2332 	int level;
2333 	uint_t idx;
2334 	krw_t rwtype;
2335 	boolean_t set = B_FALSE;
2336 
2337 	/* xlate should be at level 0 */
2338 	ASSERT(xlate->xlt_level == 0);
2339 	ASSERT(xlate->xlt_idx == 0);
2340 
2341 	/* start with highest level pgtable i.e. root */
2342 	xlate += nlevels;
2343 	ASSERT(xlate->xlt_level == nlevels);
2344 
2345 	new = NULL;
2346 	xlate->xlt_pgtable = domain->dom_pgtable_root;
2347 	for (level = nlevels; level > 1; level--, xlate--) {
2348 
2349 		ASSERT(xlate->xlt_level == level);
2350 
2351 		idx = xlate->xlt_idx;
2352 		pgtable = xlate->xlt_pgtable;
2353 
2354 		ASSERT(pgtable);
2355 		ASSERT(idx <= IMMU_PGTABLE_MAXIDX);
2356 
2357 		/* speculative alloc */
2358 		if (new == NULL) {
2359 			new = pgtable_alloc(immu, immu_flags);
2360 			if (new == NULL) {
2361 				ddi_err(DER_PANIC, rdip, "pgtable alloc err");
2362 			}
2363 		}
2364 
2365 		/* Lock the pgtable in READ mode first */
2366 		rw_enter(&(pgtable->swpg_rwlock), RW_READER);
2367 		rwtype = RW_READER;
2368 again:
2369 		hwp = (hw_pdte_t *)(pgtable->hwpg_vaddr) + idx;
2370 
2371 		ASSERT(pgtable->swpg_next_array);
2372 
2373 		next = (pgtable->swpg_next_array)[idx];
2374 
2375 		/*
2376 		 * check if leafier level already has a pgtable
2377 		 * if yes, verify
2378 		 */
2379 		if (next == NULL) {
2380 			/* Change to a write lock */
2381 			if (rwtype == RW_READER &&
2382 			    rw_tryupgrade(&(pgtable->swpg_rwlock)) == 0) {
2383 				rw_exit(&(pgtable->swpg_rwlock));
2384 				rw_enter(&(pgtable->swpg_rwlock), RW_WRITER);
2385 				rwtype = RW_WRITER;
2386 				goto again;
2387 			}
2388 			rwtype = RW_WRITER;
2389 			pgtable_zero(immu, new);
2390 			next = new;
2391 			new = NULL;
2392 			(pgtable->swpg_next_array)[idx] = next;
2393 			PDE_set_one(immu, hwp, next, rdip, immu_flags);
2394 			set = B_TRUE;
2395 			rw_downgrade(&(pgtable->swpg_rwlock));
2396 			rwtype = RW_READER;
2397 		} else {
2398 			hw_pdte_t pde = *hwp;
2399 
2400 #ifndef  BUGGY_DRIVERS
2401 			/*
2402 			 * If buggy driver we already set permission
2403 			 * READ+WRITE so nothing to do for that case
2404 			 * XXX Check that read writer perms change before
2405 			 * actually setting perms. Also need to hold lock
2406 			 */
2407 			if (immu_flags & IMMU_FLAGS_READ)
2408 				PDTE_SET_READ(pde);
2409 			if (immu_flags & IMMU_FLAGS_WRITE)
2410 				PDTE_SET_WRITE(pde);
2411 
2412 #endif
2413 
2414 			*hwp = pde;
2415 		}
2416 
2417 		ASSERT(PDTE_check(immu, *hwp, next, 0, rdip, immu_flags)
2418 		    == B_TRUE);
2419 
2420 		(xlate - 1)->xlt_pgtable = next;
2421 		ASSERT(rwtype == RW_READER);
2422 		rw_exit(&(pgtable->swpg_rwlock));
2423 	}
2424 
2425 	if (new) {
2426 		pgtable_free(immu, new);
2427 	}
2428 
2429 	return (set);
2430 }
2431 
2432 /*
2433  * dvma_map()
2434  *     map a contiguous range of DVMA pages
2435  *
2436  *     immu: IOMMU unit for which we are generating DVMA cookies
2437  *   domain: domain
2438  *    sdvma: Starting dvma
2439  *   spaddr: Starting paddr
2440  *   npages: Number of pages
2441  *     rdip: requesting device
2442  *     immu_flags: flags
2443  */
2444 static boolean_t
2445 dvma_map(immu_t *immu, domain_t *domain, uint64_t sdvma, uint64_t snvpages,
2446     dcookie_t *dcookies, int dcount, dev_info_t *rdip, immu_flags_t immu_flags)
2447 {
2448 	uint64_t dvma;
2449 	uint64_t n;
2450 	int nlevels = immu->immu_dvma_nlevels;
2451 	xlate_t xlate[IMMU_PGTABLE_MAX_LEVELS + 1] = {0};
2452 	boolean_t pde_set = B_FALSE;
2453 
2454 	ASSERT(nlevels <= IMMU_PGTABLE_MAX_LEVELS);
2455 	ASSERT(sdvma % IMMU_PAGESIZE == 0);
2456 	ASSERT(snvpages);
2457 
2458 	n = snvpages;
2459 	dvma = sdvma;
2460 
2461 	while (n > 0) {
2462 		xlate_setup(immu, dvma, xlate, nlevels, rdip);
2463 
2464 		/* Lookup or allocate PGDIRs and PGTABLEs if necessary */
2465 		if (PDE_set_all(immu, domain, xlate, nlevels, rdip, immu_flags)
2466 		    == B_TRUE) {
2467 			pde_set = B_TRUE;
2468 		}
2469 
2470 		/* set all matching ptes that fit into this leaf pgtable */
2471 		PTE_set_all(immu, domain, &xlate[1], &dvma, &n, dcookies,
2472 		    dcount, rdip, immu_flags);
2473 	}
2474 
2475 	return (pde_set);
2476 }
2477 
2478 /*
2479  * dvma_unmap()
2480  *   unmap a range of DVMAs
2481  *
2482  * immu: IOMMU unit state
2483  * domain: domain for requesting device
2484  * ddip: domain-dip
2485  * dvma: starting DVMA
2486  * npages: Number of IMMU pages to be unmapped
2487  * rdip: requesting device
2488  */
2489 static void
2490 dvma_unmap(immu_t *immu, domain_t *domain, uint64_t sdvma, uint64_t snpages,
2491     dev_info_t *rdip)
2492 {
2493 	int nlevels = immu->immu_dvma_nlevels;
2494 	xlate_t xlate[IMMU_PGTABLE_MAX_LEVELS + 1] = {0};
2495 	uint64_t n;
2496 	uint64_t dvma;
2497 
2498 	ASSERT(nlevels <= IMMU_PGTABLE_MAX_LEVELS);
2499 	ASSERT(sdvma != 0);
2500 	ASSERT(sdvma % IMMU_PAGESIZE == 0);
2501 	ASSERT(snpages);
2502 
2503 	dvma = sdvma;
2504 	n = snpages;
2505 
2506 	while (n > 0) {
2507 		/* setup the xlate array */
2508 		xlate_setup(immu, dvma, xlate, nlevels, rdip);
2509 
2510 		/* just lookup existing pgtables. Should never fail */
2511 		PDE_lookup(immu, domain, xlate, nlevels, rdip);
2512 
2513 		/* clear all matching ptes that fit into this leaf pgtable */
2514 		PTE_clear_all(immu, domain, &xlate[1], &dvma, &n, rdip);
2515 	}
2516 
2517 	/* No need to flush IOTLB after unmap */
2518 }
2519 
2520 static uint64_t
2521 dvma_alloc(ddi_dma_impl_t *hp, domain_t *domain, uint_t npages)
2522 {
2523 	ddi_dma_attr_t *dma_attr;
2524 	uint64_t dvma;
2525 	size_t xsize, align;
2526 	uint64_t minaddr, maxaddr;
2527 
2528 	ASSERT(domain->dom_maptype != IMMU_MAPTYPE_UNITY);
2529 
2530 	/* shotcuts */
2531 	dma_attr = &(hp->dmai_attr);
2532 
2533 	/* parameters */
2534 	xsize = npages * IMMU_PAGESIZE;
2535 	align = MAX((size_t)(dma_attr->dma_attr_align), IMMU_PAGESIZE);
2536 	minaddr = dma_attr->dma_attr_addr_lo;
2537 	maxaddr = dma_attr->dma_attr_addr_hi + 1;
2538 	/* nocross is checked in cookie_update() */
2539 
2540 	/* handle the rollover cases */
2541 	if (maxaddr < dma_attr->dma_attr_addr_hi) {
2542 		maxaddr = dma_attr->dma_attr_addr_hi;
2543 	}
2544 
2545 	/*
2546 	 * allocate from vmem arena.
2547 	 */
2548 	dvma = (uint64_t)(uintptr_t)vmem_xalloc(domain->dom_dvma_arena,
2549 	    xsize, align, 0, 0, (void *)(uintptr_t)minaddr,
2550 	    (void *)(uintptr_t)maxaddr, VM_NOSLEEP);
2551 
2552 	ASSERT(dvma);
2553 	ASSERT(dvma >= minaddr);
2554 	ASSERT(dvma + xsize - 1 < maxaddr);
2555 
2556 	return (dvma);
2557 }
2558 
2559 static void
2560 dvma_free(domain_t *domain, uint64_t dvma, uint64_t npages)
2561 {
2562 	uint64_t size = npages * IMMU_PAGESIZE;
2563 
2564 	ASSERT(domain);
2565 	ASSERT(domain->dom_did > 0);
2566 	ASSERT(dvma);
2567 	ASSERT(npages);
2568 
2569 	if (domain->dom_maptype != IMMU_MAPTYPE_XLATE) {
2570 		ASSERT(domain->dom_maptype == IMMU_MAPTYPE_UNITY);
2571 		return;
2572 	}
2573 
2574 	vmem_free(domain->dom_dvma_arena, (void *)(uintptr_t)dvma, size);
2575 }
2576 /*ARGSUSED*/
2577 static void
2578 cookie_free(rootnex_dma_t *dma, immu_t *immu, domain_t *domain,
2579     dev_info_t *rdip)
2580 {
2581 	int i;
2582 	uint64_t dvma;
2583 	uint64_t npages;
2584 	dvcookie_t  *dvcookies = dma->dp_dvcookies;
2585 
2586 	ASSERT(dma->dp_max_cookies);
2587 	ASSERT(dma->dp_max_dcookies);
2588 	ASSERT(dma->dp_dvmax < dma->dp_max_cookies);
2589 	ASSERT(dma->dp_dmax < dma->dp_max_dcookies);
2590 
2591 	/*
2592 	 * we allocated DVMA in a single chunk. Calculate total number
2593 	 * of pages
2594 	 */
2595 	for (i = 0, npages = 0; i <= dma->dp_dvmax; i++) {
2596 		npages += dvcookies[i].dvck_npages;
2597 	}
2598 	dvma = dvcookies[0].dvck_dvma;
2599 #ifdef DEBUG
2600 	/* Unmap only in DEBUG mode */
2601 	dvma_unmap(immu, domain, dvma, npages, rdip);
2602 #endif
2603 	dvma_free(domain, dvma, npages);
2604 
2605 	kmem_free(dma->dp_dvcookies, sizeof (dvcookie_t) * dma->dp_max_cookies);
2606 	dma->dp_dvcookies = NULL;
2607 	kmem_free(dma->dp_dcookies, sizeof (dcookie_t) * dma->dp_max_dcookies);
2608 	dma->dp_dcookies = NULL;
2609 	if (dma->dp_need_to_free_cookie == B_TRUE) {
2610 		kmem_free(dma->dp_cookies, sizeof (ddi_dma_cookie_t) *
2611 		    dma->dp_max_cookies);
2612 		dma->dp_dcookies = NULL;
2613 		dma->dp_need_to_free_cookie = B_FALSE;
2614 	}
2615 
2616 	dma->dp_max_cookies = 0;
2617 	dma->dp_max_dcookies = 0;
2618 	dma->dp_cookie_size = 0;
2619 	dma->dp_dvmax = 0;
2620 	dma->dp_dmax = 0;
2621 }
2622 
2623 /*
2624  * cookie_alloc()
2625  */
2626 static int
2627 cookie_alloc(rootnex_dma_t *dma, struct ddi_dma_req *dmareq,
2628     ddi_dma_attr_t *attr, uint_t prealloc)
2629 {
2630 	int kmflag;
2631 	rootnex_sglinfo_t *sinfo = &(dma->dp_sglinfo);
2632 	dvcookie_t *dvcookies = dma->dp_dvcookies;
2633 	dcookie_t *dcookies = dma->dp_dcookies;
2634 	ddi_dma_cookie_t *cookies = dma->dp_cookies;
2635 	uint64_t max_cookies;
2636 	uint64_t max_dcookies;
2637 	uint64_t cookie_size;
2638 
2639 	/* we need to allocate new array */
2640 	if (dmareq->dmar_fp == DDI_DMA_SLEEP) {
2641 		kmflag =  KM_SLEEP;
2642 	} else {
2643 		kmflag =  KM_NOSLEEP;
2644 	}
2645 
2646 	/*
2647 	 * XXX make sure cookies size doen't exceed sinfo->si_max_cookie_size;
2648 	 */
2649 
2650 	/*
2651 	 * figure out the rough estimate of array size
2652 	 * At a minimum, each cookie must hold 1 page.
2653 	 * At a maximum, it cannot exceed dma_attr_sgllen
2654 	 */
2655 	max_dcookies = dmareq->dmar_object.dmao_size + IMMU_PAGEOFFSET;
2656 	max_dcookies /= IMMU_PAGESIZE;
2657 	max_dcookies++;
2658 	max_cookies = MIN(max_dcookies, attr->dma_attr_sgllen);
2659 
2660 	/* allocate the dvma cookie array */
2661 	dvcookies = kmem_zalloc(sizeof (dvcookie_t) * max_cookies, kmflag);
2662 	if (dvcookies == NULL) {
2663 		return (DDI_FAILURE);
2664 	}
2665 
2666 	/* allocate the "phys" cookie array */
2667 	dcookies = kmem_zalloc(sizeof (dcookie_t) * max_dcookies, kmflag);
2668 	if (dcookies == NULL) {
2669 		kmem_free(dvcookies, sizeof (dvcookie_t) * max_cookies);
2670 		dvcookies = NULL;
2671 		return (DDI_FAILURE);
2672 	}
2673 
2674 	/* allocate the "real" cookie array  - the one given to users */
2675 	cookie_size = sizeof (ddi_dma_cookie_t) * max_cookies;
2676 	if (max_cookies > prealloc) {
2677 		cookies = kmem_zalloc(cookie_size, kmflag);
2678 		if (cookies == NULL) {
2679 			kmem_free(dvcookies, sizeof (dvcookie_t) * max_cookies);
2680 			kmem_free(dcookies, sizeof (dcookie_t) * max_dcookies);
2681 			goto fail;
2682 		}
2683 		dma->dp_need_to_free_cookie = B_TRUE;
2684 	} else {
2685 		/* the preallocated buffer fits this size */
2686 		cookies = (ddi_dma_cookie_t *)dma->dp_prealloc_buffer;
2687 		bzero(cookies, sizeof (ddi_dma_cookie_t)* max_cookies);
2688 		dma->dp_need_to_free_cookie = B_FALSE;
2689 	}
2690 
2691 	dma->dp_dvcookies = dvcookies;
2692 	dma->dp_dcookies = dcookies;
2693 	dma->dp_cookies = cookies;
2694 	dma->dp_cookie_size = cookie_size;
2695 	dma->dp_max_cookies = max_cookies;
2696 	dma->dp_max_dcookies = max_dcookies;
2697 	dma->dp_dvmax = 0;
2698 	dma->dp_dmax = 0;
2699 	sinfo->si_max_pages = dma->dp_max_cookies;
2700 
2701 	return (DDI_SUCCESS);
2702 
2703 fail:
2704 	dma->dp_dvcookies = NULL;
2705 	dma->dp_dcookies = NULL;
2706 	dma->dp_cookies = NULL;
2707 	dma->dp_cookie_size = 0;
2708 	dma->dp_max_cookies = 0;
2709 	dma->dp_max_dcookies = 0;
2710 	dma->dp_dvmax = 0;
2711 	dma->dp_dmax = 0;
2712 	dma->dp_need_to_free_cookie = B_FALSE;
2713 	sinfo->si_max_pages = 0;
2714 
2715 	return (DDI_FAILURE);
2716 }
2717 
2718 /*ARGSUSED*/
2719 static void
2720 cookie_update(domain_t *domain, rootnex_dma_t *dma, paddr_t paddr,
2721     int64_t psize, uint64_t maxseg, size_t nocross)
2722 {
2723 	dvcookie_t *dvcookies = dma->dp_dvcookies;
2724 	dcookie_t *dcookies = dma->dp_dcookies;
2725 	ddi_dma_cookie_t *cookies = dma->dp_cookies;
2726 	uint64_t dvmax = dma->dp_dvmax;
2727 	uint64_t dmax = dma->dp_dmax;
2728 
2729 	ASSERT(dvmax < dma->dp_max_cookies);
2730 	ASSERT(dmax < dma->dp_max_dcookies);
2731 
2732 	paddr &= IMMU_PAGEMASK;
2733 
2734 	ASSERT(paddr);
2735 	ASSERT(psize);
2736 	ASSERT(maxseg);
2737 
2738 	/*
2739 	 * check to see if this page would put us
2740 	 * over the max cookie size.
2741 	 */
2742 	if (cookies[dvmax].dmac_size + psize > maxseg) {
2743 		dvmax++;    /* use the next dvcookie */
2744 		dmax++;    /* also means we use the next dcookie */
2745 		ASSERT(dvmax < dma->dp_max_cookies);
2746 		ASSERT(dmax < dma->dp_max_dcookies);
2747 	}
2748 
2749 	/*
2750 	 * check to see if this page would make us larger than
2751 	 * the nocross boundary. If yes, create a new cookie
2752 	 * otherwise we will fail later with vmem_xalloc()
2753 	 * due to overconstrained alloc requests
2754 	 * nocross == 0 implies no nocross constraint.
2755 	 */
2756 	if (nocross > 0) {
2757 		ASSERT((dvcookies[dvmax].dvck_npages) * IMMU_PAGESIZE
2758 		    <= nocross);
2759 		if ((dvcookies[dvmax].dvck_npages + 1) * IMMU_PAGESIZE
2760 		    > nocross) {
2761 			dvmax++;    /* use the next dvcookie */
2762 			dmax++;    /* also means we use the next dcookie */
2763 			ASSERT(dvmax < dma->dp_max_cookies);
2764 			ASSERT(dmax < dma->dp_max_dcookies);
2765 		}
2766 		ASSERT((dvcookies[dvmax].dvck_npages) * IMMU_PAGESIZE
2767 		    <= nocross);
2768 	}
2769 
2770 	/*
2771 	 * If the cookie is empty
2772 	 */
2773 	if (dvcookies[dvmax].dvck_npages == 0) {
2774 		ASSERT(cookies[dvmax].dmac_size == 0);
2775 		ASSERT(dvcookies[dvmax].dvck_dvma == 0);
2776 		ASSERT(dvcookies[dvmax].dvck_npages
2777 		    == 0);
2778 		ASSERT(dcookies[dmax].dck_paddr == 0);
2779 		ASSERT(dcookies[dmax].dck_npages == 0);
2780 
2781 		dvcookies[dvmax].dvck_dvma = 0;
2782 		dvcookies[dvmax].dvck_npages = 1;
2783 		dcookies[dmax].dck_paddr = paddr;
2784 		dcookies[dmax].dck_npages = 1;
2785 		cookies[dvmax].dmac_size = psize;
2786 	} else {
2787 		/* Cookie not empty. Add to it */
2788 		cookies[dma->dp_dvmax].dmac_size += psize;
2789 		ASSERT(dvcookies[dma->dp_dvmax].dvck_dvma == 0);
2790 		dvcookies[dma->dp_dvmax].dvck_npages++;
2791 		ASSERT(dcookies[dmax].dck_paddr != 0);
2792 		ASSERT(dcookies[dmax].dck_npages != 0);
2793 
2794 		/* Check if this paddr is contiguous */
2795 		if (IMMU_CONTIG_PADDR(dcookies[dmax], paddr)) {
2796 			dcookies[dmax].dck_npages++;
2797 		} else {
2798 			/* No, we need a new dcookie */
2799 			dmax++;
2800 			ASSERT(dcookies[dmax].dck_paddr == 0);
2801 			ASSERT(dcookies[dmax].dck_npages == 0);
2802 			dcookies[dmax].dck_paddr = paddr;
2803 			dcookies[dmax].dck_npages = 1;
2804 		}
2805 	}
2806 
2807 	dma->dp_dvmax = dvmax;
2808 	dma->dp_dmax = dmax;
2809 }
2810 
2811 static void
2812 cookie_finalize(ddi_dma_impl_t *hp, immu_t *immu, domain_t *domain,
2813     dev_info_t *rdip, immu_flags_t immu_flags)
2814 {
2815 	int i;
2816 	rootnex_dma_t *dma = (rootnex_dma_t *)hp->dmai_private;
2817 	dvcookie_t *dvcookies = dma->dp_dvcookies;
2818 	dcookie_t *dcookies = dma->dp_dcookies;
2819 	ddi_dma_cookie_t *cookies = dma->dp_cookies;
2820 	uint64_t npages;
2821 	uint64_t dvma;
2822 	boolean_t pde_set;
2823 
2824 	/* First calculate the total number of pages required */
2825 	for (i = 0, npages = 0; i <= dma->dp_dvmax; i++) {
2826 		npages += dvcookies[i].dvck_npages;
2827 	}
2828 
2829 	/* Now allocate dvma */
2830 	dvma = dvma_alloc(hp, domain, npages);
2831 
2832 	/* Now map the dvma */
2833 	pde_set = dvma_map(immu, domain, dvma, npages, dcookies,
2834 	    dma->dp_dmax + 1, rdip, immu_flags);
2835 
2836 	/* Invalidate the IOTLB */
2837 	immu_flush_iotlb_psi(immu, domain->dom_did, dvma, npages,
2838 	    pde_set == B_TRUE ? TLB_IVA_WHOLE : TLB_IVA_LEAF);
2839 
2840 	/* Now setup dvcookies and real cookie addresses */
2841 	for (i = 0; i <= dma->dp_dvmax; i++) {
2842 		dvcookies[i].dvck_dvma = dvma;
2843 		cookies[i].dmac_laddress = dvma;
2844 		ASSERT(cookies[i].dmac_size != 0);
2845 		cookies[i].dmac_type = 0;
2846 		dvma += (dvcookies[i].dvck_npages * IMMU_PAGESIZE);
2847 	}
2848 
2849 #ifdef TEST
2850 	immu_flush_iotlb_dsi(immu, domain->dom_did);
2851 #endif
2852 }
2853 
2854 /*
2855  * cookie_create()
2856  */
2857 static int
2858 cookie_create(ddi_dma_impl_t *hp, struct ddi_dma_req *dmareq,
2859     ddi_dma_attr_t *a, immu_t *immu, domain_t *domain, dev_info_t *rdip,
2860     uint_t prealloc_count, immu_flags_t immu_flags)
2861 {
2862 	ddi_dma_atyp_t buftype;
2863 	uint64_t offset;
2864 	page_t **pparray;
2865 	uint64_t paddr;
2866 	uint_t psize;
2867 	uint_t size;
2868 	uint64_t maxseg;
2869 	caddr_t vaddr;
2870 	uint_t pcnt;
2871 	page_t *page;
2872 	rootnex_sglinfo_t *sglinfo;
2873 	ddi_dma_obj_t *dmar_object;
2874 	rootnex_dma_t *dma;
2875 	size_t nocross;
2876 
2877 	dma = (rootnex_dma_t *)hp->dmai_private;
2878 	sglinfo = &(dma->dp_sglinfo);
2879 	dmar_object = &(dmareq->dmar_object);
2880 	maxseg = sglinfo->si_max_cookie_size;
2881 	pparray = dmar_object->dmao_obj.virt_obj.v_priv;
2882 	vaddr = dmar_object->dmao_obj.virt_obj.v_addr;
2883 	buftype = dmar_object->dmao_type;
2884 	size = dmar_object->dmao_size;
2885 	nocross = (size_t)(a->dma_attr_seg + 1);
2886 
2887 	/*
2888 	 * Allocate cookie, dvcookie and dcookie
2889 	 */
2890 	if (cookie_alloc(dma, dmareq, a, prealloc_count) != DDI_SUCCESS) {
2891 		return (DDI_FAILURE);
2892 	}
2893 	hp->dmai_cookie = dma->dp_cookies;
2894 
2895 	pcnt = 0;
2896 
2897 	/* retrieve paddr, psize, offset from dmareq */
2898 	if (buftype == DMA_OTYP_PAGES) {
2899 		page = dmar_object->dmao_obj.pp_obj.pp_pp;
2900 		ASSERT(!PP_ISFREE(page) && PAGE_LOCKED(page));
2901 		offset =  dmar_object->dmao_obj.pp_obj.pp_offset &
2902 		    MMU_PAGEOFFSET;
2903 		paddr = pfn_to_pa(page->p_pagenum) + offset;
2904 		psize = MIN((MMU_PAGESIZE - offset), size);
2905 		sglinfo->si_asp = NULL;
2906 		page = page->p_next;
2907 	} else {
2908 		ASSERT((buftype == DMA_OTYP_VADDR) ||
2909 		    (buftype == DMA_OTYP_BUFVADDR));
2910 		sglinfo->si_asp = dmar_object->dmao_obj.virt_obj.v_as;
2911 		if (sglinfo->si_asp == NULL) {
2912 			sglinfo->si_asp = &kas;
2913 		}
2914 		offset = (uintptr_t)vaddr & MMU_PAGEOFFSET;
2915 		if (pparray != NULL) {
2916 			ASSERT(!PP_ISFREE(pparray[pcnt]));
2917 			paddr = pfn_to_pa(pparray[pcnt]->p_pagenum) + offset;
2918 			psize = MIN((MMU_PAGESIZE - offset), size);
2919 			pcnt++;
2920 		} else {
2921 			paddr = pfn_to_pa(hat_getpfnum(sglinfo->si_asp->a_hat,
2922 			    vaddr)) + offset;
2923 			psize = MIN(size, (MMU_PAGESIZE - offset));
2924 			vaddr += psize;
2925 		}
2926 	}
2927 
2928 	/* save the iommu page offset */
2929 	sglinfo->si_buf_offset = offset & IMMU_PAGEOFFSET;
2930 
2931 	/*
2932 	 * setup dvcookie and dcookie for [paddr, paddr+psize)
2933 	 */
2934 	cookie_update(domain, dma, paddr, psize, maxseg, nocross);
2935 
2936 	size -= psize;
2937 	while (size > 0) {
2938 		/* get the size for this page (i.e. partial or full page) */
2939 		psize = MIN(size, MMU_PAGESIZE);
2940 		if (buftype == DMA_OTYP_PAGES) {
2941 			/* get the paddr from the page_t */
2942 			ASSERT(!PP_ISFREE(page) && PAGE_LOCKED(page));
2943 			paddr = pfn_to_pa(page->p_pagenum);
2944 			page = page->p_next;
2945 		} else if (pparray != NULL) {
2946 			/* index into the array of page_t's to get the paddr */
2947 			ASSERT(!PP_ISFREE(pparray[pcnt]));
2948 			paddr = pfn_to_pa(pparray[pcnt]->p_pagenum);
2949 			pcnt++;
2950 		} else {
2951 			/* call into the VM to get the paddr */
2952 			paddr = pfn_to_pa(hat_getpfnum
2953 			    (sglinfo->si_asp->a_hat, vaddr));
2954 			vaddr += psize;
2955 		}
2956 		/*
2957 		 * set dvcookie and dcookie for [paddr, paddr+psize)
2958 		 */
2959 		cookie_update(domain, dma, paddr, psize, maxseg, nocross);
2960 		size -= psize;
2961 	}
2962 
2963 	cookie_finalize(hp, immu, domain, rdip, immu_flags);
2964 
2965 	/* take account in the offset into the first page */
2966 	dma->dp_cookies[0].dmac_laddress += sglinfo->si_buf_offset;
2967 
2968 	/* save away how many cookies we have */
2969 	sglinfo->si_sgl_size = dma->dp_dvmax + 1;
2970 
2971 	return (DDI_SUCCESS);
2972 }
2973 
2974 /* ############################# Functions exported ######################## */
2975 
2976 /*
2977  * setup the DVMA subsystem
2978  * this code runs only for the first IOMMU unit
2979  */
2980 void
2981 immu_dvma_setup(list_t *listp)
2982 {
2983 	immu_t *immu;
2984 	uint_t kval;
2985 	size_t nchains;
2986 
2987 	/* locks */
2988 	mutex_init(&immu_domain_lock, NULL, MUTEX_DEFAULT, NULL);
2989 
2990 	/* Create lists */
2991 	list_create(&immu_unity_domain_list, sizeof (domain_t),
2992 	    offsetof(domain_t, dom_maptype_node));
2993 	list_create(&immu_xlate_domain_list, sizeof (domain_t),
2994 	    offsetof(domain_t, dom_maptype_node));
2995 
2996 	/* Setup BDF domain hash */
2997 	nchains = 0xff;
2998 	kval = mod_hash_iddata_gen(nchains);
2999 
3000 	bdf_domain_hash = mod_hash_create_extended("BDF-DOMAIN_HASH",
3001 	    nchains, mod_hash_null_keydtor, mod_hash_null_valdtor,
3002 	    mod_hash_byid, (void *)(uintptr_t)kval, mod_hash_idkey_cmp,
3003 	    KM_NOSLEEP);
3004 	ASSERT(bdf_domain_hash);
3005 
3006 	immu = list_head(listp);
3007 	for (; immu; immu = list_next(listp, immu)) {
3008 		create_unity_domain(immu);
3009 		did_init(immu);
3010 		context_init(immu);
3011 		immu->immu_dvma_setup = B_TRUE;
3012 	}
3013 }
3014 
3015 /*
3016  * Startup up one DVMA unit
3017  */
3018 void
3019 immu_dvma_startup(immu_t *immu)
3020 {
3021 	ASSERT(immu);
3022 	ASSERT(immu->immu_dvma_running == B_FALSE);
3023 
3024 	if (immu_gfxdvma_enable == B_FALSE &&
3025 	    immu->immu_dvma_gfx_only == B_TRUE) {
3026 		return;
3027 	}
3028 
3029 	/*
3030 	 * DVMA will start once IOMMU is "running"
3031 	 */
3032 	ASSERT(immu->immu_dvma_running == B_FALSE);
3033 	immu->immu_dvma_running = B_TRUE;
3034 }
3035 
3036 /*
3037  * immu_dvma_physmem_update()
3038  *       called when the installed memory on a
3039  *       system increases, to expand domain DVMA
3040  *       for domains with UNITY mapping
3041  */
3042 void
3043 immu_dvma_physmem_update(uint64_t addr, uint64_t size)
3044 {
3045 	uint64_t start;
3046 	uint64_t npages;
3047 	int dcount;
3048 	dcookie_t dcookies[1] = {0};
3049 	domain_t *domain;
3050 
3051 	/*
3052 	 * Just walk the system-wide list of domains with
3053 	 * UNITY mapping. Both the list of *all* domains
3054 	 * and *UNITY* domains is protected by the same
3055 	 * single lock
3056 	 */
3057 	mutex_enter(&immu_domain_lock);
3058 	domain = list_head(&immu_unity_domain_list);
3059 	for (; domain; domain = list_next(&immu_unity_domain_list, domain)) {
3060 
3061 		/* There is no vmem_arena for unity domains. Just map it */
3062 		ddi_err(DER_LOG, NULL, "IMMU: unity-domain: Adding map "
3063 		    "[0x%" PRIx64 " - 0x%" PRIx64 "]", addr, addr + size);
3064 
3065 		start = IMMU_ROUNDOWN(addr);
3066 		npages = (IMMU_ROUNDUP(size) / IMMU_PAGESIZE) + 1;
3067 
3068 		dcookies[0].dck_paddr = start;
3069 		dcookies[0].dck_npages = npages;
3070 		dcount = 1;
3071 		(void) dvma_map(domain->dom_immu, domain, start, npages,
3072 		    dcookies, dcount, NULL, IMMU_FLAGS_READ | IMMU_FLAGS_WRITE);
3073 
3074 	}
3075 	mutex_exit(&immu_domain_lock);
3076 }
3077 
3078 
3079 int
3080 immu_dvma_map(ddi_dma_impl_t *hp, struct ddi_dma_req *dmareq, memrng_t *mrng,
3081     uint_t prealloc_count, dev_info_t *rdip, immu_flags_t immu_flags)
3082 {
3083 	ddi_dma_attr_t *attr;
3084 	dev_info_t *ddip;
3085 	domain_t *domain;
3086 	immu_t *immu;
3087 	dcookie_t dcookies[1] = {0};
3088 	int dcount = 0;
3089 	boolean_t pde_set = B_TRUE;
3090 	int r = DDI_FAILURE;
3091 
3092 	ASSERT(immu_enable == B_TRUE);
3093 	ASSERT(immu_running == B_TRUE || !(immu_flags & IMMU_FLAGS_DMAHDL));
3094 	ASSERT(hp || !(immu_flags & IMMU_FLAGS_DMAHDL));
3095 
3096 	/*
3097 	 * Intel IOMMU will only be turned on if IOMMU
3098 	 * page size is a multiple of IOMMU page size
3099 	 */
3100 
3101 	/*LINTED*/
3102 	ASSERT(MMU_PAGESIZE % IMMU_PAGESIZE == 0);
3103 
3104 	/* Can only do DVMA if dip is attached */
3105 	if (rdip == NULL) {
3106 		ddi_err(DER_PANIC, rdip, "DVMA map: No device specified");
3107 		/*NOTREACHED*/
3108 	}
3109 
3110 	immu_flags |= dma_to_immu_flags(dmareq);
3111 
3112 	immu = immu_dvma_get_immu(rdip, immu_flags);
3113 	if (immu == NULL) {
3114 		/*
3115 		 * possible that there is no IOMMU unit for this device
3116 		 * - BIOS bugs are one example.
3117 		 */
3118 		ddi_err(DER_WARN, rdip, "No IMMU unit found for device");
3119 		return (DDI_DMA_NORESOURCES);
3120 	}
3121 
3122 	/*
3123 	 * redirect isa devices attached under lpc to lpc dip
3124 	 */
3125 	if (strcmp(ddi_node_name(ddi_get_parent(rdip)), "isa") == 0) {
3126 		rdip = get_lpc_devinfo(immu, rdip, immu_flags);
3127 		if (rdip == NULL) {
3128 			ddi_err(DER_PANIC, rdip, "IMMU redirect failed");
3129 			/*NOTREACHED*/
3130 		}
3131 	}
3132 
3133 	/* Reset immu, as redirection can change IMMU */
3134 	immu = NULL;
3135 
3136 	/*
3137 	 * for gart, redirect to the real graphic devinfo
3138 	 */
3139 	if (strcmp(ddi_node_name(rdip), "agpgart") == 0) {
3140 		rdip = get_gfx_devinfo(rdip);
3141 		if (rdip == NULL) {
3142 			ddi_err(DER_PANIC, rdip, "IMMU redirect failed");
3143 			/*NOTREACHED*/
3144 		}
3145 	}
3146 
3147 	/*
3148 	 * Setup DVMA domain for the device. This does
3149 	 * work only the first time we do DVMA for a
3150 	 * device.
3151 	 */
3152 	ddip = NULL;
3153 	domain = device_domain(rdip, &ddip, immu_flags);
3154 	if (domain == NULL) {
3155 		ASSERT(ddip == NULL);
3156 		ddi_err(DER_MODE, rdip, "Intel IOMMU setup failed for device");
3157 		return (DDI_DMA_NORESOURCES);
3158 	}
3159 
3160 	/*
3161 	 * If a domain is found, we must also have a domain dip
3162 	 * which is the topmost ancestor dip of rdip that shares
3163 	 * the same domain with rdip.
3164 	 */
3165 	if (domain->dom_did == 0 || ddip == NULL) {
3166 		ddi_err(DER_MODE, rdip, "domain did 0(%d) or ddip NULL(%p)",
3167 		    domain->dom_did, ddip);
3168 		return (DDI_DMA_NORESOURCES);
3169 	}
3170 
3171 	immu = domain->dom_immu;
3172 	ASSERT(immu);
3173 	if (domain->dom_did == IMMU_UNITY_DID) {
3174 		ASSERT(domain == immu->immu_unity_domain);
3175 		/* mapping already done. Let rootnex create cookies */
3176 		r = DDI_DMA_USE_PHYSICAL;
3177 	} else  if (immu_flags & IMMU_FLAGS_DMAHDL) {
3178 
3179 		/* if we have a DMA handle, the IOMMUs must be running */
3180 		ASSERT(immu->immu_regs_running == B_TRUE);
3181 		ASSERT(immu->immu_dvma_running == B_TRUE);
3182 
3183 		attr = &hp->dmai_attr;
3184 		if (attr == NULL) {
3185 			ddi_err(DER_PANIC, rdip,
3186 			    "DMA handle (%p): NULL attr", hp);
3187 			/*NOTREACHED*/
3188 		}
3189 
3190 		if (cookie_create(hp, dmareq, attr, immu, domain, rdip,
3191 		    prealloc_count, immu_flags) != DDI_SUCCESS) {
3192 			ddi_err(DER_MODE, rdip, "dvcookie_alloc: failed");
3193 			return (DDI_DMA_NORESOURCES);
3194 		}
3195 		r = DDI_DMA_MAPPED;
3196 	} else if (immu_flags & IMMU_FLAGS_MEMRNG) {
3197 		dcookies[0].dck_paddr = mrng->mrng_start;
3198 		dcookies[0].dck_npages = mrng->mrng_npages;
3199 		dcount = 1;
3200 		pde_set = dvma_map(immu, domain, mrng->mrng_start,
3201 		    mrng->mrng_npages, dcookies, dcount, rdip, immu_flags);
3202 		immu_flush_iotlb_psi(immu, domain->dom_did, mrng->mrng_start,
3203 		    mrng->mrng_npages, pde_set == B_TRUE ?
3204 		    TLB_IVA_WHOLE : TLB_IVA_LEAF);
3205 		r = DDI_DMA_MAPPED;
3206 	} else {
3207 		ddi_err(DER_PANIC, rdip, "invalid flags for immu_dvma_map()");
3208 		/*NOTREACHED*/
3209 	}
3210 
3211 	/*
3212 	 * Update the root and context entries
3213 	 */
3214 	if (immu_context_update(immu, domain, ddip, rdip, immu_flags)
3215 	    != DDI_SUCCESS) {
3216 		ddi_err(DER_MODE, rdip, "DVMA map: context update failed");
3217 		return (DDI_DMA_NORESOURCES);
3218 	}
3219 
3220 	immu_regs_wbf_flush(immu);
3221 
3222 	return (r);
3223 }
3224 
3225 int
3226 immu_dvma_unmap(ddi_dma_impl_t *hp, dev_info_t *rdip)
3227 {
3228 	ddi_dma_attr_t *attr;
3229 	rootnex_dma_t *dma;
3230 	domain_t *domain;
3231 	immu_t *immu;
3232 	dev_info_t *ddip;
3233 	immu_flags_t immu_flags;
3234 
3235 	ASSERT(immu_enable == B_TRUE);
3236 	ASSERT(immu_running == B_TRUE);
3237 	ASSERT(hp);
3238 
3239 	/*
3240 	 * Intel IOMMU will only be turned on if IOMMU
3241 	 * page size is same as MMU page size
3242 	 */
3243 	/*LINTED*/
3244 	ASSERT(MMU_PAGESIZE == IMMU_PAGESIZE);
3245 
3246 	/* rdip need not be attached */
3247 	if (rdip == NULL) {
3248 		ddi_err(DER_PANIC, rdip, "DVMA unmap: No device specified");
3249 		return (DDI_DMA_NORESOURCES);
3250 	}
3251 
3252 	/*
3253 	 * Get the device domain, this should always
3254 	 * succeed since there had to be a domain to
3255 	 * setup DVMA.
3256 	 */
3257 	dma = (rootnex_dma_t *)hp->dmai_private;
3258 	attr = &hp->dmai_attr;
3259 	if (attr == NULL) {
3260 		ddi_err(DER_PANIC, rdip, "DMA handle (%p) has NULL attr", hp);
3261 		/*NOTREACHED*/
3262 	}
3263 	immu_flags = dma->dp_sleep_flags;
3264 
3265 	immu = immu_dvma_get_immu(rdip, immu_flags);
3266 	if (immu == NULL) {
3267 		/*
3268 		 * possible that there is no IOMMU unit for this device
3269 		 * - BIOS bugs are one example.
3270 		 */
3271 		ddi_err(DER_WARN, rdip, "No IMMU unit found for device");
3272 		return (DDI_DMA_NORESOURCES);
3273 	}
3274 
3275 
3276 	/*
3277 	 * redirect isa devices attached under lpc to lpc dip
3278 	 */
3279 	if (strcmp(ddi_node_name(ddi_get_parent(rdip)), "isa") == 0) {
3280 		rdip = get_lpc_devinfo(immu, rdip, immu_flags);
3281 		if (rdip == NULL) {
3282 			ddi_err(DER_PANIC, rdip, "IMMU redirect failed");
3283 			/*NOTREACHED*/
3284 		}
3285 	}
3286 
3287 	/* Reset immu, as redirection can change IMMU */
3288 	immu = NULL;
3289 
3290 	/*
3291 	 * for gart, redirect to the real graphic devinfo
3292 	 */
3293 	if (strcmp(ddi_node_name(rdip), "agpgart") == 0) {
3294 		rdip = get_gfx_devinfo(rdip);
3295 		if (rdip == NULL) {
3296 			ddi_err(DER_PANIC, rdip, "IMMU redirect failed");
3297 			/*NOTREACHED*/
3298 		}
3299 	}
3300 
3301 	ddip = NULL;
3302 	domain = device_domain(rdip, &ddip, immu_flags);
3303 	if (domain == NULL || domain->dom_did == 0 || ddip == NULL) {
3304 		ddi_err(DER_MODE, rdip, "Attempt to unmap DVMA for "
3305 		    "a device without domain or with an uninitialized "
3306 		    "domain");
3307 		return (DDI_DMA_NORESOURCES);
3308 	}
3309 
3310 	/*
3311 	 * immu must be set in the domain.
3312 	 */
3313 	immu = domain->dom_immu;
3314 	ASSERT(immu);
3315 	if (domain->dom_did == IMMU_UNITY_DID) {
3316 		ASSERT(domain == immu->immu_unity_domain);
3317 		/*
3318 		 * domain is unity, nothing to do here, let the rootnex
3319 		 * code free the cookies.
3320 		 */
3321 		return (DDI_DMA_USE_PHYSICAL);
3322 	}
3323 
3324 	dma = hp->dmai_private;
3325 	if (dma == NULL) {
3326 		ddi_err(DER_PANIC, rdip, "DVMA unmap: DMA handle (%p) has "
3327 		    "no private dma structure", hp);
3328 		/*NOTREACHED*/
3329 	}
3330 
3331 	cookie_free(dma, immu, domain, rdip);
3332 
3333 	/* No invalidation needed for unmap */
3334 	immu_regs_wbf_flush(immu);
3335 
3336 	return (DDI_SUCCESS);
3337 }
3338 
3339 immu_devi_t *
3340 immu_devi_get(dev_info_t *rdip)
3341 {
3342 	immu_devi_t *immu_devi;
3343 	volatile uintptr_t *vptr = (uintptr_t *)&(DEVI(rdip)->devi_iommu);
3344 
3345 	/* Just want atomic reads. No need for lock */
3346 	immu_devi = (immu_devi_t *)(uintptr_t)atomic_or_64_nv((uint64_t *)vptr,
3347 	    0);
3348 	return (immu_devi);
3349 }
3350