xref: /titanic_44/usr/src/uts/sun4u/io/pci/pci_dma.c (revision 1a7c1b724419d3cb5fa6eea75123c6b2060ba31b)
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, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 /*
30  * PCI nexus DVMA and DMA core routines:
31  *	dma_map/dma_bind_handle implementation
32  *	bypass and peer-to-peer support
33  *	fast track DVMA space allocation
34  *	runtime DVMA debug
35  */
36 #include <sys/types.h>
37 #include <sys/kmem.h>
38 #include <sys/async.h>
39 #include <sys/sysmacros.h>
40 #include <sys/sunddi.h>
41 #include <sys/machsystm.h>	/* lddphys() */
42 #include <sys/ddi_impldefs.h>
43 #include <vm/hat.h>
44 #include <sys/pci/pci_obj.h>
45 
46 /*LINTLIBRARY*/
47 
48 static void
49 pci_sc_pg_inv(dev_info_t *dip, sc_t *sc_p, ddi_dma_impl_t *mp, off_t off,
50 	size_t len)
51 {
52 	dvma_addr_t dvma_addr, pg_off;
53 	volatile uint64_t *invl_va = sc_p->sc_invl_reg;
54 
55 	if (!len)
56 		len = mp->dmai_size;
57 
58 	pg_off = mp->dmai_offset;			/* start min */
59 	dvma_addr = MAX(off, pg_off);			/* lo */
60 	pg_off += mp->dmai_size;			/* end max */
61 	pg_off = MIN(off + len, pg_off);		/* hi */
62 	if (dvma_addr >= pg_off) {			/* lo >= hi ? */
63 		DEBUG4(DBG_SC, dip, "%x+%x out of window [%x,%x)\n",
64 			off, len, mp->dmai_offset,
65 			mp->dmai_offset + mp->dmai_size);
66 		return;
67 	}
68 
69 	len = pg_off - dvma_addr;			/* sz = hi - lo */
70 	dvma_addr += mp->dmai_mapping;			/* start addr */
71 	pg_off = dvma_addr & IOMMU_PAGE_OFFSET;		/* offset in 1st pg */
72 	len = IOMMU_BTOPR(len + pg_off);		/* # of pages */
73 	dvma_addr ^= pg_off;
74 
75 	DEBUG2(DBG_SC, dip, "addr=%x+%x pages: \n", dvma_addr, len);
76 	for (; len; len--, dvma_addr += IOMMU_PAGE_SIZE) {
77 		DEBUG1(DBG_SC|DBG_CONT, dip, " %x", dvma_addr);
78 		*invl_va = (uint64_t)dvma_addr;
79 	}
80 	DEBUG0(DBG_SC|DBG_CONT, dip, "\n");
81 }
82 
83 static void
84 pci_dma_sync_flag_wait(ddi_dma_impl_t *mp, sc_t *sc_p, uint32_t onstack)
85 {
86 	hrtime_t start_time;
87 	uint64_t loops = 0;
88 	uint64_t sync_flag_pa = SYNC_BUF_PA(mp);
89 	uint64_t sync_reg_pa = sc_p->sc_sync_reg_pa;
90 	uint8_t stack_buf[128];
91 
92 	stack_buf[0] = DDI_SUCCESS;
93 
94 	/* check for handle specific sync flag */
95 	if (sync_flag_pa)
96 		goto start;
97 
98 	sync_flag_pa = sc_p->sc_sync_flag_pa;
99 
100 	if (onstack) {
101 		sync_flag_pa = va_to_pa(stack_buf);
102 		sync_flag_pa += PCI_SYNC_FLAG_SIZE;
103 		sync_flag_pa >>= PCI_SYNC_FLAG_SZSHIFT;
104 		sync_flag_pa <<= PCI_SYNC_FLAG_SZSHIFT;
105 		goto start;
106 	}
107 	stack_buf[0] |= PCI_SYNC_FLAG_LOCKED;
108 	mutex_enter(&sc_p->sc_sync_mutex);
109 start:
110 	ASSERT(!(sync_flag_pa & PCI_SYNC_FLAG_SIZE - 1));
111 	stdphys(sync_flag_pa, 0);	/* reset sync flag to 0 */
112 					/* membar  #LoadStore|#StoreStore */
113 	stdphysio(sync_reg_pa, sync_flag_pa);
114 	start_time = gethrtime();
115 
116 	for (; gethrtime() - start_time < pci_sync_buf_timeout; loops++)
117 		if (lddphys(sync_flag_pa))
118 			goto done;
119 
120 	if (!lddphys(sync_flag_pa))
121 		stack_buf[0] |= PCI_SYNC_FLAG_FAILED;
122 done:
123 	DEBUG3(DBG_SC|DBG_CONT, 0, "flag wait loops=%lu ticks=%lu status=%x\n",
124 		loops, gethrtime() - start_time, stack_buf[0]);
125 
126 	if (stack_buf[0] & PCI_SYNC_FLAG_LOCKED)
127 		mutex_exit(&sc_p->sc_sync_mutex);
128 
129 	if (stack_buf[0] & PCI_SYNC_FLAG_FAILED)
130 		cmn_err(CE_PANIC, "%p pci dma sync %llx %llx timeout!",
131 		    mp, sync_flag_pa, loops);
132 }
133 
134 /*
135  * Cache	RW	Before	During		After
136  *
137  * STREAMING	read	no/no	pg/no		ctx,pg/no
138  * STREAMING	write	no/no	pg/yes		ctx,pg/yes
139  * CONSISTENT	read	no/no	yes,no/no	yes,no/no
140  * CONSISTENT	write	no/no	yes,yes/yes	yes,yes/yes
141  *
142  * STREAMING	read	ctx,pg/no
143  * STREAMING	write	ctx,pg/yes
144  * CONSISTENT	read	yes,no/no
145  * CONSISTENT	write	yes,yes/yes
146  */
147 int
148 pci_dma_sync(dev_info_t *dip, dev_info_t *rdip, ddi_dma_handle_t handle,
149 	off_t off, size_t len, uint32_t sync_flag)
150 {
151 	ddi_dma_impl_t *mp = (ddi_dma_impl_t *)handle;
152 	int ret = ddi_get_instance(dip);
153 	pci_t *pci_p = get_pci_soft_state(ret);
154 	pbm_t *pbm_p = pci_p->pci_pbm_p;
155 	uint32_t dev_flag = mp->dmai_rflags;
156 	sc_t *sc_p;
157 
158 	DEBUG4(DBG_DMA_SYNC, dip, "%s%d flags=%x,%x\n", ddi_driver_name(rdip),
159 		ddi_get_instance(rdip), dev_flag, sync_flag);
160 	DEBUG4(DBG_SC, dip, "dmai_mapping=%x, dmai_sz=%x off=%x len=%x\n",
161 		mp->dmai_mapping, mp->dmai_size, off, len);
162 	DEBUG2(DBG_SC, dip, "mp=%p, ctx=%x\n", mp, MP2CTX(mp));
163 
164 	if (!(mp->dmai_flags & DMAI_FLAGS_INUSE)) {
165 		cmn_err(CE_WARN, "Unbound dma handle %p from %s%d", mp,
166 		    ddi_driver_name(rdip), ddi_get_instance(rdip));
167 		return (DDI_FAILURE);
168 	}
169 
170 	if (mp->dmai_flags & DMAI_FLAGS_NOSYNC)
171 		return (DDI_SUCCESS);
172 
173 	if (!(dev_flag & DDI_DMA_CONSISTENT))
174 		goto streaming;
175 
176 	if (sync_flag & PCI_DMA_SYNC_EXT) {
177 		if (sync_flag & (PCI_DMA_SYNC_BEFORE | PCI_DMA_SYNC_POST) ||
178 		    !(sync_flag & PCI_DMA_SYNC_WRITE))
179 			return (DDI_SUCCESS);
180 	} else {
181 		if (!(dev_flag & DDI_DMA_READ) ||
182 		    ((sync_flag & PCI_DMA_SYNC_DDI_FLAGS) ==
183 		    DDI_DMA_SYNC_FORDEV))
184 			return (DDI_SUCCESS);
185 	}
186 
187 	pci_pbm_dma_sync(pbm_p, pbm_p->pbm_sync_ino);
188 	return (DDI_SUCCESS);
189 
190 streaming:
191 	ASSERT(pci_stream_buf_exists && (pci_stream_buf_enable & 1 << ret));
192 	sc_p = pci_p->pci_sc_p;
193 	ret = DDI_FAILURE;
194 
195 	if (sync_flag & PCI_DMA_SYNC_EXT)
196 		goto ext;
197 
198 	if (mp->dmai_flags & DMAI_FLAGS_CONTEXT && pci_sc_use_contexts)
199 		ret = pci_sc_ctx_inv(dip, sc_p, mp);
200 	if (ret)
201 		pci_sc_pg_inv(dip, sc_p, mp, off, len);
202 
203 	if ((dev_flag & DDI_DMA_READ) &&
204 	    ((sync_flag & PCI_DMA_SYNC_DDI_FLAGS) != DDI_DMA_SYNC_FORDEV))
205 		goto wait;
206 
207 	return (DDI_SUCCESS);
208 ext:
209 	if (sync_flag & PCI_DMA_SYNC_BEFORE)
210 		return (DDI_SUCCESS);
211 	if (sync_flag & PCI_DMA_SYNC_BAR)
212 		goto wait_check;
213 	if (sync_flag & PCI_DMA_SYNC_AFTER &&
214 		mp->dmai_flags & DMAI_FLAGS_CONTEXT && pci_sc_use_contexts)
215 		ret = pci_sc_ctx_inv(dip, sc_p, mp);
216 	if (ret)
217 		pci_sc_pg_inv(dip, sc_p, mp, off, len);
218 wait_check:
219 	if (sync_flag & PCI_DMA_SYNC_POST || !(sync_flag & PCI_DMA_SYNC_WRITE))
220 		return (DDI_SUCCESS);
221 wait:
222 	pci_dma_sync_flag_wait(mp, sc_p, sync_flag & PCI_DMA_SYNC_PRIVATE);
223 	return (DDI_SUCCESS);
224 }
225 
226 int
227 pci_dma_handle_clean(dev_info_t *rdip, ddi_dma_handle_t h)
228 {
229 	ddi_dma_impl_t *mp = (ddi_dma_impl_t *)h;
230 	if ((mp->dmai_flags & DMAI_FLAGS_INUSE) == 0)
231 		return (DDI_FAILURE);
232 	mp->dmai_rflags |= DMP_NOSYNC;
233 	mp->dmai_flags |= DMAI_FLAGS_NOSYNC;
234 	return (DDI_SUCCESS);
235 }
236 
237 /*
238  * pci_dma_allocmp - Allocate a pci dma implementation structure
239  *
240  * An extra ddi_dma_attr structure is bundled with the usual ddi_dma_impl
241  * to hold unmodified device limits. The ddi_dma_attr inside the
242  * ddi_dma_impl structure is augumented with system limits to enhance
243  * DVMA performance at runtime. The unaugumented device limits saved
244  * right after (accessed through the DEV_ATTR macro) is used
245  * strictly for peer-to-peer transfers which do not obey system limits.
246  *
247  * return: DDI_SUCCESS DDI_DMA_NORESOURCES
248  */
249 ddi_dma_impl_t *
250 pci_dma_allocmp(dev_info_t *dip, dev_info_t *rdip, int (*waitfp)(caddr_t),
251 	caddr_t arg)
252 {
253 	ddi_dma_impl_t *mp;
254 	int sleep = (waitfp == DDI_DMA_SLEEP) ? KM_SLEEP : KM_NOSLEEP;
255 
256 	/* Caution: we don't use zalloc to enhance performance! */
257 	if ((mp = kmem_alloc(sizeof (pci_dma_hdl_t), sleep)) == 0) {
258 		DEBUG0(DBG_DMA_MAP, dip, "can't alloc dma_handle\n");
259 		if (waitfp != DDI_DMA_DONTWAIT) {
260 			DEBUG0(DBG_DMA_MAP, dip, "alloc_mp kmem cb\n");
261 			ddi_set_callback(waitfp, arg, &pci_kmem_clid);
262 		}
263 		return (mp);
264 	}
265 
266 	mp->dmai_rdip = rdip;
267 	mp->dmai_flags = 0;
268 	mp->dmai_pfnlst = NULL;
269 	mp->dmai_winlst = NULL;
270 
271 	/*
272 	 * kmem_alloc debug: the following fields are not zero-ed
273 	 * mp->dmai_mapping = 0;
274 	 * mp->dmai_size = 0;
275 	 * mp->dmai_offset = 0;
276 	 * mp->dmai_minxfer = 0;
277 	 * mp->dmai_burstsizes = 0;
278 	 * mp->dmai_ndvmapages = 0;
279 	 * mp->dmai_pool/roffset = 0;
280 	 * mp->dmai_rflags = 0;
281 	 * mp->dmai_inuse/flags
282 	 * mp->dmai_nwin = 0;
283 	 * mp->dmai_winsize = 0;
284 	 * mp->dmai_nexus_private/tte = 0;
285 	 * mp->dmai_iopte/pfnlst
286 	 * mp->dmai_sbi/pfn0 = 0;
287 	 * mp->dmai_minfo/winlst/fdvma
288 	 * mp->dmai_rdip
289 	 * bzero(&mp->dmai_object, sizeof (ddi_dma_obj_t));
290 	 * mp->dmai_cookie = 0;
291 	 */
292 
293 	mp->dmai_attr.dma_attr_version = (uint_t)DMA_ATTR_VERSION;
294 	mp->dmai_attr.dma_attr_flags = (uint_t)0;
295 	mp->dmai_fault = 0;
296 	mp->dmai_fault_check = NULL;
297 	mp->dmai_fault_notify = NULL;
298 
299 	mp->dmai_error.err_ena = 0;
300 	mp->dmai_error.err_status = DDI_FM_OK;
301 	mp->dmai_error.err_expected = DDI_FM_ERR_UNEXPECTED;
302 	mp->dmai_error.err_ontrap = NULL;
303 	mp->dmai_error.err_fep = NULL;
304 
305 	SYNC_BUF_PA(mp) = 0ull;
306 	return (mp);
307 }
308 
309 void
310 pci_dma_freemp(ddi_dma_impl_t *mp)
311 {
312 	if (mp->dmai_ndvmapages > 1)
313 		pci_dma_freepfn(mp);
314 	if (mp->dmai_winlst)
315 		pci_dma_freewin(mp);
316 	kmem_free(mp, sizeof (pci_dma_hdl_t));
317 }
318 
319 void
320 pci_dma_freepfn(ddi_dma_impl_t *mp)
321 {
322 	void *addr = mp->dmai_pfnlst;
323 	ASSERT(!PCI_DMA_CANRELOC(mp));
324 	if (addr) {
325 		size_t npages = mp->dmai_ndvmapages;
326 		if (npages > 1)
327 			kmem_free(addr, npages * sizeof (iopfn_t));
328 		mp->dmai_pfnlst = NULL;
329 	}
330 	mp->dmai_ndvmapages = 0;
331 }
332 
333 /*
334  * pci_dma_lmts2hdl - alloate a ddi_dma_impl_t, validate practical limits
335  *			and convert dmareq->dmar_limits to mp->dmai_attr
336  *
337  * ddi_dma_impl_t member modified     input
338  * ------------------------------------------------------------------------
339  * mp->dmai_minxfer		    - dev
340  * mp->dmai_burstsizes		    - dev
341  * mp->dmai_flags		    - no limit? peer-to-peer only?
342  *
343  * ddi_dma_attr member modified       input
344  * ------------------------------------------------------------------------
345  * mp->dmai_attr.dma_attr_addr_lo   - dev lo, sys lo
346  * mp->dmai_attr.dma_attr_addr_hi   - dev hi, sys hi
347  * mp->dmai_attr.dma_attr_count_max - dev count max, dev/sys lo/hi delta
348  * mp->dmai_attr.dma_attr_seg       - 0         (no nocross   restriction)
349  * mp->dmai_attr.dma_attr_align     - 1		(no alignment restriction)
350  *
351  * The dlim_dmaspeed member of dmareq->dmar_limits is ignored.
352  */
353 ddi_dma_impl_t *
354 pci_dma_lmts2hdl(dev_info_t *dip, dev_info_t *rdip, iommu_t *iommu_p,
355 	ddi_dma_req_t *dmareq)
356 {
357 	ddi_dma_impl_t *mp;
358 	ddi_dma_attr_t *attr_p;
359 	uint64_t syslo		= iommu_p->iommu_dvma_base;
360 	uint64_t syshi		= iommu_p->iommu_dvma_end;
361 	uint64_t fasthi		= iommu_p->iommu_dvma_fast_end;
362 	ddi_dma_lim_t *lim_p	= dmareq->dmar_limits;
363 	uint32_t count_max	= lim_p->dlim_cntr_max;
364 	uint64_t lo		= lim_p->dlim_addr_lo;
365 	uint64_t hi		= lim_p->dlim_addr_hi;
366 	if (hi <= lo) {
367 		DEBUG0(DBG_DMA_MAP, dip, "Bad limits\n");
368 		return ((ddi_dma_impl_t *)DDI_DMA_NOMAPPING);
369 	}
370 	if (!count_max)
371 		count_max--;
372 
373 	if (!(mp = pci_dma_allocmp(dip, rdip, dmareq->dmar_fp,
374 		dmareq->dmar_arg)))
375 		return (NULL);
376 
377 	/* store original dev input at the 2nd ddi_dma_attr */
378 	attr_p = DEV_ATTR(mp);
379 	SET_DMAATTR(attr_p, lo, hi, -1, count_max);
380 	SET_DMAALIGN(attr_p, 1);
381 
382 	lo = MAX(lo, syslo);
383 	hi = MIN(hi, syshi);
384 	if (hi <= lo)
385 		mp->dmai_flags |= DMAI_FLAGS_PEER_ONLY;
386 	count_max = MIN(count_max, hi - lo);
387 
388 	if (DEV_NOSYSLIMIT(lo, hi, syslo, fasthi, 1))
389 		mp->dmai_flags |= DMAI_FLAGS_NOFASTLIMIT |
390 			DMAI_FLAGS_NOSYSLIMIT;
391 	else {
392 		if (DEV_NOFASTLIMIT(lo, hi, syslo, syshi, 1))
393 			mp->dmai_flags |= DMAI_FLAGS_NOFASTLIMIT;
394 	}
395 	if (PCI_DMA_NOCTX(rdip))
396 		mp->dmai_flags |= DMAI_FLAGS_NOCTX;
397 
398 	/* store augumented dev input to mp->dmai_attr */
399 	mp->dmai_minxfer	= lim_p->dlim_minxfer;
400 	mp->dmai_burstsizes	= lim_p->dlim_burstsizes;
401 	attr_p = &mp->dmai_attr;
402 	SET_DMAATTR(attr_p, lo, hi, -1, count_max);
403 	SET_DMAALIGN(attr_p, 1);
404 	return (mp);
405 }
406 
407 /*
408  * pci_dma_attr2hdl
409  *
410  * This routine is called from the alloc handle entry point to sanity check the
411  * dma attribute structure.
412  *
413  * use by: pci_dma_allochdl()
414  *
415  * return value:
416  *
417  *	DDI_SUCCESS		- on success
418  *	DDI_DMA_BADATTR		- attribute has invalid version number
419  *				  or address limits exclude dvma space
420  */
421 int
422 pci_dma_attr2hdl(pci_t *pci_p, ddi_dma_impl_t *mp)
423 {
424 	iommu_t *iommu_p = pci_p->pci_iommu_p;
425 	uint64_t syslo, syshi;
426 	ddi_dma_attr_t *attrp		= DEV_ATTR(mp);
427 	uint64_t hi		= attrp->dma_attr_addr_hi;
428 	uint64_t lo		= attrp->dma_attr_addr_lo;
429 	uint64_t align		= attrp->dma_attr_align;
430 	uint64_t nocross	= attrp->dma_attr_seg;
431 	uint64_t count_max	= attrp->dma_attr_count_max;
432 
433 	DEBUG3(DBG_DMA_ALLOCH, pci_p->pci_dip, "attrp=%p cntr_max=%x.%08x\n",
434 		attrp, HI32(count_max), LO32(count_max));
435 	DEBUG4(DBG_DMA_ALLOCH, pci_p->pci_dip, "hi=%x.%08x lo=%x.%08x\n",
436 		HI32(hi), LO32(hi), HI32(lo), LO32(lo));
437 	DEBUG4(DBG_DMA_ALLOCH, pci_p->pci_dip, "seg=%x.%08x align=%x.%08x\n",
438 		HI32(nocross), LO32(nocross), HI32(align), LO32(align));
439 
440 	if (!nocross)
441 		nocross--;
442 	if (attrp->dma_attr_flags & DDI_DMA_FORCE_PHYSICAL) { /* BYPASS */
443 
444 		DEBUG0(DBG_DMA_ALLOCH, pci_p->pci_dip, "bypass mode\n");
445 		/* if tomatillo ver <= 2.3 don't allow bypass */
446 		if (tomatillo_disallow_bypass)
447 			return (DDI_DMA_BADATTR);
448 
449 		mp->dmai_flags |= DMAI_FLAGS_BYPASSREQ;
450 		if (nocross != UINT64_MAX)
451 			return (DDI_DMA_BADATTR);
452 		if (align && (align > IOMMU_PAGE_SIZE))
453 			return (DDI_DMA_BADATTR);
454 		align = 1; /* align on 1 page boundary */
455 		syslo = iommu_p->iommu_dma_bypass_base;
456 		syshi = iommu_p->iommu_dma_bypass_end;
457 
458 	} else { /* IOMMU_XLATE or PEER_TO_PEER */
459 		align = MAX(align, IOMMU_PAGE_SIZE) - 1;
460 		if ((align & nocross) != align) {
461 			dev_info_t *rdip = mp->dmai_rdip;
462 			cmn_err(CE_WARN, "%s%d dma_attr_seg not aligned",
463 				NAMEINST(rdip));
464 			return (DDI_DMA_BADATTR);
465 		}
466 		align = IOMMU_BTOP(align + 1);
467 		syslo = iommu_p->iommu_dvma_base;
468 		syshi = iommu_p->iommu_dvma_end;
469 	}
470 	if (hi <= lo) {
471 		dev_info_t *rdip = mp->dmai_rdip;
472 		cmn_err(CE_WARN, "%s%d limits out of range", NAMEINST(rdip));
473 		return (DDI_DMA_BADATTR);
474 	}
475 	lo = MAX(lo, syslo);
476 	hi = MIN(hi, syshi);
477 	if (!count_max)
478 		count_max--;
479 
480 	DEBUG4(DBG_DMA_ALLOCH, pci_p->pci_dip, "hi=%x.%08x, lo=%x.%08x\n",
481 		HI32(hi), LO32(hi), HI32(lo), LO32(lo));
482 	if (hi <= lo) { /* peer transfers cannot have alignment & nocross */
483 		dev_info_t *rdip = mp->dmai_rdip;
484 		cmn_err(CE_WARN, "%s%d peer only dev %p", NAMEINST(rdip), mp);
485 		if ((nocross < UINT32_MAX) || (align > 1)) {
486 			cmn_err(CE_WARN, "%s%d peer only device bad attr",
487 				NAMEINST(rdip));
488 			return (DDI_DMA_BADATTR);
489 		}
490 		mp->dmai_flags |= DMAI_FLAGS_PEER_ONLY;
491 	} else /* set practical counter_max value */
492 		count_max = MIN(count_max, hi - lo);
493 
494 	if (DEV_NOSYSLIMIT(lo, hi, syslo, syshi, align))
495 		mp->dmai_flags |= DMAI_FLAGS_NOSYSLIMIT |
496 			DMAI_FLAGS_NOFASTLIMIT;
497 	else {
498 		syshi = iommu_p->iommu_dvma_fast_end;
499 		if (DEV_NOFASTLIMIT(lo, hi, syslo, syshi, align))
500 			mp->dmai_flags |= DMAI_FLAGS_NOFASTLIMIT;
501 	}
502 	if (PCI_DMA_NOCTX(mp->dmai_rdip))
503 		mp->dmai_flags |= DMAI_FLAGS_NOCTX;
504 
505 	mp->dmai_minxfer	= attrp->dma_attr_minxfer;
506 	mp->dmai_burstsizes	= attrp->dma_attr_burstsizes;
507 	attrp = &mp->dmai_attr;
508 	SET_DMAATTR(attrp, lo, hi, nocross, count_max);
509 	return (DDI_SUCCESS);
510 }
511 
512 /*
513  * set up consistent dma flags according to hardware capability
514  */
515 uint32_t
516 pci_dma_consist_check(uint32_t req_flags, pbm_t *pbm_p)
517 {
518 	if (!pci_stream_buf_enable || !pci_stream_buf_exists)
519 		req_flags |= DDI_DMA_CONSISTENT;
520 	if (req_flags & DDI_DMA_CONSISTENT && !pbm_p->pbm_sync_reg_pa)
521 		req_flags |= DMP_NOSYNC;
522 	return (req_flags);
523 }
524 
525 #define	TGT_PFN_INBETWEEN(pfn, bgn, end) ((pfn >= bgn) && (pfn <= end))
526 
527 /*
528  * pci_dma_type - determine which of the three types DMA (peer-to-peer,
529  *		iommu bypass, or iommu translate) we are asked to do.
530  *		Also checks pfn0 and rejects any non-peer-to-peer
531  *		requests for peer-only devices.
532  *
533  *	return values:
534  *		DDI_DMA_NOMAPPING - can't get valid pfn0, or bad dma type
535  *		DDI_SUCCESS
536  *
537  *	dma handle members affected (set on exit):
538  *	mp->dmai_object		- dmareq->dmar_object
539  *	mp->dmai_rflags		- consistent?, nosync?, dmareq->dmar_flags
540  *	mp->dmai_flags   	- DMA type
541  *	mp->dmai_pfn0   	- 1st page pfn (if va/size pair and not shadow)
542  *	mp->dmai_roffset 	- initialized to starting IOMMU page offset
543  *	mp->dmai_ndvmapages	- # of total IOMMU pages of entire object
544  *	mp->pdh_sync_buf_pa	- dma sync buffer PA is DMA flow is supported
545  */
546 int
547 pci_dma_type(pci_t *pci_p, ddi_dma_req_t *dmareq, ddi_dma_impl_t *mp)
548 {
549 	dev_info_t *dip = pci_p->pci_dip;
550 	ddi_dma_obj_t *dobj_p = &dmareq->dmar_object;
551 	pbm_t *pbm_p = pci_p->pci_pbm_p;
552 	page_t **pplist;
553 	struct as *as_p;
554 	uint32_t offset;
555 	caddr_t vaddr;
556 	pfn_t pfn0;
557 
558 	mp->dmai_rflags = pci_dma_consist_check(dmareq->dmar_flags, pbm_p);
559 	mp->dmai_flags |= mp->dmai_rflags & DMP_NOSYNC ? DMAI_FLAGS_NOSYNC : 0;
560 
561 	switch (dobj_p->dmao_type) {
562 	case DMA_OTYP_BUFVADDR:
563 	case DMA_OTYP_VADDR: {
564 		vaddr = dobj_p->dmao_obj.virt_obj.v_addr;
565 		pplist = dobj_p->dmao_obj.virt_obj.v_priv;
566 		as_p = dobj_p->dmao_obj.virt_obj.v_as;
567 		if (as_p == NULL)
568 			as_p = &kas;
569 
570 		DEBUG2(DBG_DMA_MAP, dip, "vaddr=%p pplist=%p\n", vaddr, pplist);
571 		offset = (ulong_t)vaddr & IOMMU_PAGE_OFFSET;
572 
573 		if (pplist) {				/* shadow list */
574 			mp->dmai_flags |= DMAI_FLAGS_PGPFN;
575 			ASSERT(PAGE_LOCKED(*pplist));
576 			pfn0 = page_pptonum(*pplist);
577 		} else if (pci_dvma_remap_enabled && as_p == &kas &&
578 			dobj_p->dmao_type != DMA_OTYP_BUFVADDR) {
579 			int (*waitfp)(caddr_t) = dmareq->dmar_fp;
580 			uint_t flags = ((waitfp == DDI_DMA_SLEEP)?
581 				    HAC_SLEEP : HAC_NOSLEEP) | HAC_PAGELOCK;
582 			int ret;
583 
584 			ret = hat_add_callback(pci_dvma_cbid, vaddr,
585 			    IOMMU_PAGE_SIZE - offset, flags, mp, &pfn0);
586 
587 			if (pfn0 == PFN_INVALID && ret == ENOMEM) {
588 				ASSERT(waitfp != DDI_DMA_SLEEP);
589 				if (waitfp != DDI_DMA_DONTWAIT) {
590 					ddi_set_callback(waitfp,
591 					    dmareq->dmar_arg,
592 					    &pci_kmem_clid);
593 					return (DDI_DMA_NORESOURCES);
594 					}
595 			}
596 			mp->dmai_flags |= DMAI_FLAGS_RELOC;
597 		} else
598 			pfn0 = hat_getpfnum(as_p->a_hat, vaddr);
599 		}
600 		break;
601 
602 	case DMA_OTYP_PAGES:
603 		offset = dobj_p->dmao_obj.pp_obj.pp_offset;
604 		mp->dmai_flags |= DMAI_FLAGS_PGPFN;
605 		pfn0 = page_pptonum(dobj_p->dmao_obj.pp_obj.pp_pp);
606 		ASSERT(PAGE_LOCKED(dobj_p->dmao_obj.pp_obj.pp_pp));
607 		break;
608 
609 	case DMA_OTYP_PADDR:
610 	default:
611 		cmn_err(CE_WARN, "%s%d requested unsupported dma type %x",
612 			NAMEINST(mp->dmai_rdip), dobj_p->dmao_type);
613 		return (DDI_DMA_NOMAPPING);
614 	}
615 	if (pfn0 == PFN_INVALID) {
616 		cmn_err(CE_WARN, "%s%d: invalid pfn0 for DMA object %p",
617 			NAMEINST(dip), dobj_p);
618 		return (DDI_DMA_NOMAPPING);
619 	}
620 	if (TGT_PFN_INBETWEEN(pfn0, pbm_p->pbm_base_pfn, pbm_p->pbm_last_pfn)) {
621 		mp->dmai_flags |= DMAI_FLAGS_PEER_TO_PEER;
622 		goto done;	/* leave bypass and dvma flag as 0 */
623 	}
624 	if (PCI_DMA_ISPEERONLY(mp)) {
625 		dev_info_t *rdip = mp->dmai_rdip;
626 		cmn_err(CE_WARN, "Bad peer-to-peer req %s%d", NAMEINST(rdip));
627 		return (DDI_DMA_NOMAPPING);
628 	}
629 	mp->dmai_flags |= (mp->dmai_flags & DMAI_FLAGS_BYPASSREQ) ?
630 		DMAI_FLAGS_BYPASS : DMAI_FLAGS_DVMA;
631 done:
632 	mp->dmai_object	 = *dobj_p;			/* whole object    */
633 	mp->dmai_pfn0	 = (void *)pfn0;		/* cache pfn0	   */
634 	mp->dmai_roffset = offset;			/* win0 pg0 offset */
635 	mp->dmai_ndvmapages = IOMMU_BTOPR(offset + mp->dmai_object.dmao_size);
636 
637 	return (DDI_SUCCESS);
638 }
639 
640 /*
641  * pci_dma_pgpfn - set up pfnlst array according to pages
642  *	VA/size pair: <shadow IO, bypass, peer-to-peer>, or OTYP_PAGES
643  */
644 /*ARGSUSED*/
645 static int
646 pci_dma_pgpfn(pci_t *pci_p, ddi_dma_impl_t *mp, uint_t npages)
647 {
648 	int i;
649 #ifdef DEBUG
650 	dev_info_t *dip = pci_p->pci_dip;
651 #endif
652 	switch (mp->dmai_object.dmao_type) {
653 	case DMA_OTYP_BUFVADDR:
654 	case DMA_OTYP_VADDR: {
655 		page_t **pplist = mp->dmai_object.dmao_obj.virt_obj.v_priv;
656 		DEBUG2(DBG_DMA_MAP, dip, "shadow pplist=%p, %x pages, pfns=",
657 			pplist, npages);
658 		for (i = 1; i < npages; i++) {
659 			iopfn_t pfn = page_pptonum(pplist[i]);
660 			ASSERT(PAGE_LOCKED(pplist[i]));
661 			PCI_SET_MP_PFN1(mp, i, pfn);
662 			DEBUG1(DBG_DMA_MAP|DBG_CONT, dip, "%x ", pfn);
663 		}
664 		DEBUG0(DBG_DMA_MAP|DBG_CONT, dip, "\n");
665 		}
666 		break;
667 
668 	case DMA_OTYP_PAGES: {
669 		page_t *pp = mp->dmai_object.dmao_obj.pp_obj.pp_pp->p_next;
670 		DEBUG1(DBG_DMA_MAP, dip, "pp=%p pfns=", pp);
671 		for (i = 1; i < npages; i++, pp = pp->p_next) {
672 			iopfn_t pfn = page_pptonum(pp);
673 			ASSERT(PAGE_LOCKED(pp));
674 			PCI_SET_MP_PFN1(mp, i, pfn);
675 			DEBUG1(DBG_DMA_MAP|DBG_CONT, dip, "%x ", pfn);
676 		}
677 		DEBUG0(DBG_DMA_MAP|DBG_CONT, dip, "\n");
678 		}
679 		break;
680 
681 	default:	/* check is already done by pci_dma_type */
682 		ASSERT(0);
683 		break;
684 	}
685 	return (DDI_SUCCESS);
686 }
687 
688 /*
689  * pci_dma_vapfn - set up pfnlst array according to VA
690  *	VA/size pair: <normal, bypass, peer-to-peer>
691  *	pfn0 is skipped as it is already done.
692  *	In this case, the cached pfn0 is used to fill pfnlst[0]
693  */
694 static int
695 pci_dma_vapfn(pci_t *pci_p, ddi_dma_req_t *dmareq, ddi_dma_impl_t *mp,
696 	uint_t npages)
697 {
698 	dev_info_t *dip = pci_p->pci_dip;
699 	int i;
700 	caddr_t vaddr = (caddr_t)mp->dmai_object.dmao_obj.virt_obj.v_as;
701 	struct hat *hat_p = vaddr ? ((struct as *)vaddr)->a_hat : kas.a_hat;
702 	caddr_t sva;
703 	int needcb = 0;
704 
705 	sva = (caddr_t)(((uintptr_t)mp->dmai_object.dmao_obj.virt_obj.v_addr +
706 	    IOMMU_PAGE_SIZE) & IOMMU_PAGE_MASK);
707 
708 	if (pci_dvma_remap_enabled && hat_p == kas.a_hat &&
709 		mp->dmai_object.dmao_type != DMA_OTYP_BUFVADDR)
710 		needcb = 1;
711 
712 	for (vaddr = sva, i = 1; i < npages; i++, vaddr += IOMMU_PAGE_SIZE) {
713 		pfn_t pfn;
714 
715 		if (needcb) {
716 			int (*waitfp)(caddr_t) = dmareq->dmar_fp;
717 			uint_t flags = ((waitfp == DDI_DMA_SLEEP)?
718 			    HAC_SLEEP : HAC_NOSLEEP) | HAC_PAGELOCK;
719 			int ret;
720 
721 			ret = hat_add_callback(pci_dvma_cbid, vaddr,
722 			    IOMMU_PAGE_SIZE, flags, mp, &pfn);
723 			if (pfn == PFN_INVALID && ret == ENOMEM) {
724 				ASSERT(waitfp != DDI_DMA_SLEEP);
725 				if (waitfp != DDI_DMA_DONTWAIT)
726 					ddi_set_callback(waitfp,
727 					    dmareq->dmar_arg, &pci_kmem_clid);
728 				return (DDI_DMA_NORESOURCES);
729 			}
730 		} else
731 			pfn = hat_getpfnum(hat_p, vaddr);
732 		if (pfn == PFN_INVALID)
733 			goto err_badpfn;
734 		PCI_SET_MP_PFN1(mp, i, (iopfn_t)pfn);
735 		DEBUG3(DBG_DMA_MAP, dip, "pci_dma_vapfn: mp=%p pfnlst[%x]=%x\n",
736 			mp, i, (iopfn_t)pfn);
737 	}
738 	return (DDI_SUCCESS);
739 err_badpfn:
740 	cmn_err(CE_WARN, "%s%d: bad page frame vaddr=%p", NAMEINST(dip), vaddr);
741 	return (DDI_DMA_NOMAPPING);
742 }
743 
744 /*
745  * pci_dma_pfn - Fills pfn list for all pages being DMA-ed.
746  *
747  * dependencies:
748  *	mp->dmai_ndvmapages	- set to total # of dma pages
749  *
750  * return value:
751  *	DDI_SUCCESS
752  *	DDI_DMA_NOMAPPING
753  */
754 int
755 pci_dma_pfn(pci_t *pci_p, ddi_dma_req_t *dmareq, ddi_dma_impl_t *mp)
756 {
757 	uint32_t npages = mp->dmai_ndvmapages;
758 	int (*waitfp)(caddr_t) = dmareq->dmar_fp;
759 	int i, ret, peer = PCI_DMA_ISPTP(mp);
760 
761 	pbm_t *pbm_p = pci_p->pci_pbm_p;
762 	iopfn_t pfn_base = pbm_p->pbm_base_pfn;
763 	iopfn_t pfn_last = pbm_p->pbm_last_pfn;
764 	iopfn_t pfn_adj = peer ? pfn_base : 0;
765 
766 	DEBUG2(DBG_DMA_MAP, pci_p->pci_dip, "pci_dma_pfn: mp=%p pfn0=%x\n",
767 		mp, MP_PFN0(mp) - pfn_adj);
768 	/* 1 page: no array alloc/fill, no mixed mode check */
769 	if (npages == 1) {
770 		PCI_SET_MP_PFN(mp, 0, MP_PFN0(mp) - pfn_adj);
771 		return (DDI_SUCCESS);
772 	}
773 	/* allocate pfn array */
774 	if (!(mp->dmai_pfnlst = kmem_alloc(npages * sizeof (iopfn_t),
775 		waitfp == DDI_DMA_SLEEP ? KM_SLEEP : KM_NOSLEEP))) {
776 		if (waitfp != DDI_DMA_DONTWAIT)
777 			ddi_set_callback(waitfp, dmareq->dmar_arg,
778 				&pci_kmem_clid);
779 		return (DDI_DMA_NORESOURCES);
780 	}
781 	/* fill pfn array */
782 	PCI_SET_MP_PFN(mp, 0, MP_PFN0(mp) - pfn_adj);	/* pfnlst[0] */
783 	if ((ret = PCI_DMA_ISPGPFN(mp) ? pci_dma_pgpfn(pci_p, mp, npages) :
784 		pci_dma_vapfn(pci_p, dmareq, mp, npages)) != DDI_SUCCESS)
785 		goto err;
786 
787 	/* skip pfn0, check mixed mode and adjust peer to peer pfn */
788 	for (i = 1; i < npages; i++) {
789 		iopfn_t pfn = PCI_GET_MP_PFN1(mp, i);
790 		if (peer ^ TGT_PFN_INBETWEEN(pfn, pfn_base, pfn_last)) {
791 			cmn_err(CE_WARN, "%s%d mixed mode DMA %x %x",
792 				NAMEINST(mp->dmai_rdip), MP_PFN0(mp), pfn);
793 			ret = DDI_DMA_NOMAPPING;	/* mixed mode */
794 			goto err;
795 		}
796 		DEBUG3(DBG_DMA_MAP, pci_p->pci_dip,
797 			"pci_dma_pfn: pfnlst[%x]=%x-%x\n", i, pfn, pfn_adj);
798 		if (pfn_adj)
799 			PCI_SET_MP_PFN1(mp, i, pfn - pfn_adj);
800 	}
801 	return (DDI_SUCCESS);
802 err:
803 	pci_dvma_unregister_callbacks(pci_p, mp);
804 	pci_dma_freepfn(mp);
805 	return (ret);
806 }
807 
808 /*
809  * pci_dvma_win() - trim requested DVMA size down to window size
810  *	The 1st window starts from offset and ends at page-aligned boundary.
811  *	From the 2nd window on, each window starts and ends at page-aligned
812  *	boundary except the last window ends at wherever requested.
813  *
814  *	accesses the following mp-> members:
815  *	mp->dmai_attr.dma_attr_count_max
816  *	mp->dmai_attr.dma_attr_seg
817  *	mp->dmai_roffset   - start offset of 1st window
818  *	mp->dmai_rflags (redzone)
819  *	mp->dmai_ndvmapages (for 1 page fast path)
820  *
821  *	sets the following mp-> members:
822  *	mp->dmai_size	   - xfer size, != winsize if 1st/last win  (not fixed)
823  *	mp->dmai_winsize   - window size (no redzone), n * page size    (fixed)
824  *	mp->dmai_nwin	   - # of DMA windows of entire object		(fixed)
825  *	mp->dmai_rflags	   - remove partial flag if nwin == 1		(fixed)
826  *	mp->dmai_winlst	   - NULL, window objects not used for DVMA	(fixed)
827  *
828  *	fixed - not changed across different DMA windows
829  */
830 /*ARGSUSED*/
831 int
832 pci_dvma_win(pci_t *pci_p, ddi_dma_req_t *dmareq, ddi_dma_impl_t *mp)
833 {
834 	uint32_t redzone_sz	= HAS_REDZONE(mp) ? IOMMU_PAGE_SIZE : 0;
835 	size_t obj_sz	= mp->dmai_object.dmao_size;
836 	size_t xfer_sz;
837 	ulong_t pg_off;
838 
839 	if ((mp->dmai_ndvmapages == 1) && !redzone_sz) {
840 		mp->dmai_rflags &= ~DDI_DMA_PARTIAL;
841 		mp->dmai_size = obj_sz;
842 		mp->dmai_winsize = IOMMU_PAGE_SIZE;
843 		mp->dmai_nwin = 1;
844 		goto done;
845 	}
846 
847 	pg_off	= mp->dmai_roffset;
848 	xfer_sz	= obj_sz + redzone_sz;
849 
850 	/* include redzone in nocross check */ {
851 		uint64_t nocross = mp->dmai_attr.dma_attr_seg;
852 		if (xfer_sz + pg_off - 1 > nocross)
853 			xfer_sz = nocross - pg_off + 1;
854 		if (redzone_sz && (xfer_sz <= redzone_sz)) {
855 			DEBUG5(DBG_DMA_MAP, pci_p->pci_dip,
856 			    "nocross too small %lx(%lx)+%lx+%x < %" PRIx64 "\n",
857 			    xfer_sz, obj_sz, pg_off, redzone_sz, nocross);
858 			return (DDI_DMA_TOOBIG);
859 		}
860 	}
861 	xfer_sz -= redzone_sz;		/* restore transfer size  */
862 	/* check counter max */ {
863 		uint32_t count_max = mp->dmai_attr.dma_attr_count_max;
864 		if (xfer_sz - 1 > count_max)
865 			xfer_sz = count_max + 1;
866 	}
867 	if (xfer_sz >= obj_sz) {
868 		mp->dmai_rflags &= ~DDI_DMA_PARTIAL;
869 		mp->dmai_size = xfer_sz;
870 		mp->dmai_winsize = P2ROUNDUP(xfer_sz + pg_off, IOMMU_PAGE_SIZE);
871 		mp->dmai_nwin = 1;
872 		goto done;
873 	}
874 	if (!(dmareq->dmar_flags & DDI_DMA_PARTIAL)) {
875 		DEBUG4(DBG_DMA_MAP, pci_p->pci_dip,
876 		    "too big: %lx+%lx+%x > %lx\n",
877 		    obj_sz, pg_off, redzone_sz, xfer_sz);
878 		return (DDI_DMA_TOOBIG);
879 	}
880 
881 	xfer_sz = IOMMU_PTOB(IOMMU_BTOP(xfer_sz + pg_off)); /* page align */
882 	mp->dmai_size = xfer_sz - pg_off;	/* 1st window xferrable size */
883 	mp->dmai_winsize = xfer_sz;		/* redzone not in winsize */
884 	mp->dmai_nwin = (obj_sz + pg_off + xfer_sz - 1) / xfer_sz;
885 done:
886 	mp->dmai_winlst = NULL;
887 	dump_dma_handle(DBG_DMA_MAP, pci_p->pci_dip, mp);
888 	return (DDI_SUCCESS);
889 }
890 
891 /*
892  * fast track cache entry to iommu context, inserts 3 0 bits between
893  * upper 6-bits and lower 3-bits of the 9-bit cache entry
894  */
895 #define	IOMMU_FCE_TO_CTX(i)	(((i) << 3) | ((i) & 0x7) | 0x38)
896 
897 /*
898  * pci_dvma_map_fast - attempts to map fast trackable DVMA
899  */
900 int
901 pci_dvma_map_fast(iommu_t *iommu_p, ddi_dma_impl_t *mp)
902 {
903 	uint_t clustsz = pci_dvma_page_cache_clustsz;
904 	uint_t entries = pci_dvma_page_cache_entries;
905 	uint64_t *tte_addr;
906 	uint64_t tte = GET_TTE_TEMPLATE(mp);
907 	int i = iommu_p->iommu_dvma_addr_scan_start;
908 	uint8_t *lock_addr = iommu_p->iommu_dvma_cache_locks + i;
909 	iopfn_t *pfn_addr;
910 	dvma_addr_t dvma_pg;
911 	size_t npages = IOMMU_BTOP(mp->dmai_winsize);
912 #ifdef DEBUG
913 	dev_info_t *dip = mp->dmai_rdip;
914 #endif
915 	extern uint8_t ldstub(uint8_t *);
916 	ASSERT(IOMMU_PTOB(npages) == mp->dmai_winsize);
917 	ASSERT(npages + HAS_REDZONE(mp) <= clustsz);
918 
919 	for (; i < entries && ldstub(lock_addr); i++, lock_addr++);
920 	if (i >= entries) {
921 		lock_addr = iommu_p->iommu_dvma_cache_locks;
922 		i = 0;
923 		for (; i < entries && ldstub(lock_addr); i++, lock_addr++);
924 		if (i >= entries) {
925 #ifdef PCI_DMA_PROF
926 			pci_dvmaft_exhaust++;
927 #endif
928 			return (DDI_DMA_NORESOURCES);
929 		}
930 	}
931 	iommu_p->iommu_dvma_addr_scan_start = (i + 1) & (entries - 1);
932 	if (PCI_DMA_USECTX(mp)) {
933 		dvma_context_t ctx = IOMMU_FCE_TO_CTX(i);
934 		tte |= IOMMU_CTX2TTE(ctx);
935 		mp->dmai_flags |= DMAI_FLAGS_CONTEXT;
936 		DEBUG1(DBG_DMA_MAP, dip, "fast: ctx=0x%x\n", ctx);
937 	}
938 	i *= clustsz;
939 	tte_addr = iommu_p->iommu_tsb_vaddr + i;
940 	dvma_pg = iommu_p->dvma_base_pg + i;
941 #ifdef DEBUG
942 	for (i = 0; i < clustsz; i++)
943 		ASSERT(TTE_IS_INVALID(tte_addr[i]));
944 #endif
945 	*tte_addr = tte | IOMMU_PTOB(MP_PFN0(mp)); /* map page 0 */
946 	DEBUG5(DBG_DMA_MAP, dip, "fast %p:dvma_pg=%x tte0(%p)=%08x.%08x\n", mp,
947 		dvma_pg, tte_addr, HI32(*tte_addr), LO32(*tte_addr));
948 	if (npages == 1)
949 		goto tte_done;
950 	pfn_addr = PCI_GET_MP_PFN1_ADDR(mp); /* short iommu_map_pages() */
951 	for (tte_addr++, i = 1; i < npages; i++, tte_addr++, pfn_addr++) {
952 		*tte_addr = tte | IOMMU_PTOB(*pfn_addr);
953 		DEBUG5(DBG_DMA_MAP, dip, "fast %p:tte(%p, %p)=%08x.%08x\n", mp,
954 			tte_addr, pfn_addr, HI32(*tte_addr), LO32(*tte_addr));
955 	}
956 tte_done:
957 #ifdef PCI_DMA_PROF
958 	pci_dvmaft_success++;
959 #endif
960 	mp->dmai_mapping = mp->dmai_roffset | IOMMU_PTOB(dvma_pg);
961 	mp->dmai_offset = 0;
962 	mp->dmai_flags |= DMAI_FLAGS_FASTTRACK;
963 	PCI_SAVE_MP_TTE(mp, tte);	/* save TTE template for unmapping */
964 	if (DVMA_DBG_ON(iommu_p))
965 		pci_dvma_alloc_debug(iommu_p, (char *)mp->dmai_mapping,
966 			mp->dmai_size, mp);
967 	return (DDI_SUCCESS);
968 }
969 
970 /*
971  * pci_dvma_map: map non-fasttrack DMA
972  *		Use quantum cache if single page DMA.
973  */
974 int
975 pci_dvma_map(ddi_dma_impl_t *mp, ddi_dma_req_t *dmareq, iommu_t *iommu_p)
976 {
977 	uint_t npages = PCI_DMA_WINNPGS(mp);
978 	dvma_addr_t dvma_pg, dvma_pg_index;
979 	void *dvma_addr;
980 	uint64_t tte = GET_TTE_TEMPLATE(mp);
981 	int sleep = dmareq->dmar_fp == DDI_DMA_SLEEP ? VM_SLEEP : VM_NOSLEEP;
982 #ifdef DEBUG
983 	dev_info_t *dip = mp->dmai_rdip;
984 #endif
985 	/*
986 	 * allocate dvma space resource and map in the first window.
987 	 * (vmem_t *vmp, size_t size,
988 	 *	size_t align, size_t phase, size_t nocross,
989 	 *	void *minaddr, void *maxaddr, int vmflag)
990 	 */
991 	if ((npages == 1) && HAS_NOSYSLIMIT(mp)) {
992 		dvma_addr = vmem_alloc(iommu_p->iommu_dvma_map,
993 			IOMMU_PAGE_SIZE, sleep);
994 		mp->dmai_flags |= DMAI_FLAGS_VMEMCACHE;
995 #ifdef PCI_DMA_PROF
996 		pci_dvma_vmem_alloc++;
997 #endif
998 	} else {
999 		dvma_addr = vmem_xalloc(iommu_p->iommu_dvma_map,
1000 			IOMMU_PTOB(npages + HAS_REDZONE(mp)),
1001 			MAX(mp->dmai_attr.dma_attr_align, IOMMU_PAGE_SIZE),
1002 			0,
1003 			mp->dmai_attr.dma_attr_seg + 1,
1004 			(void *)mp->dmai_attr.dma_attr_addr_lo,
1005 			(void *)(mp->dmai_attr.dma_attr_addr_hi + 1),
1006 			sleep);
1007 #ifdef PCI_DMA_PROF
1008 		pci_dvma_vmem_xalloc++;
1009 #endif
1010 	}
1011 	dvma_pg = IOMMU_BTOP((ulong_t)dvma_addr);
1012 	dvma_pg_index = dvma_pg - iommu_p->dvma_base_pg;
1013 	DEBUG2(DBG_DMA_MAP, dip, "fallback dvma_pages: dvma_pg=%x index=%x\n",
1014 		dvma_pg, dvma_pg_index);
1015 	if (dvma_pg == 0)
1016 		goto noresource;
1017 
1018 	/* allocate DVMA context */
1019 	if ((npages >= pci_context_minpages) && PCI_DMA_USECTX(mp)) {
1020 		dvma_context_t ctx;
1021 		if (ctx = pci_iommu_get_dvma_context(iommu_p, dvma_pg_index)) {
1022 			tte |= IOMMU_CTX2TTE(ctx);
1023 			mp->dmai_flags |= DMAI_FLAGS_CONTEXT;
1024 		}
1025 	}
1026 	mp->dmai_mapping = mp->dmai_roffset | IOMMU_PTOB(dvma_pg);
1027 	mp->dmai_offset = 0;
1028 	PCI_SAVE_MP_TTE(mp, tte);	/* mp->dmai_tte = tte */
1029 	iommu_map_pages(iommu_p, mp, dvma_pg, npages, 0);
1030 	return (DDI_SUCCESS);
1031 noresource:
1032 	if (dmareq->dmar_fp != DDI_DMA_DONTWAIT) {
1033 		DEBUG0(DBG_DMA_MAP, dip, "dvma_pg 0 - set callback\n");
1034 		ddi_set_callback(dmareq->dmar_fp, dmareq->dmar_arg,
1035 			&iommu_p->iommu_dvma_clid);
1036 	}
1037 	DEBUG0(DBG_DMA_MAP, dip, "vmem_xalloc - DDI_DMA_NORESOURCES\n");
1038 	return (DDI_DMA_NORESOURCES);
1039 }
1040 
1041 void
1042 pci_dvma_unmap(iommu_t *iommu_p, ddi_dma_impl_t *mp)
1043 {
1044 	size_t npages;
1045 	dvma_addr_t dvma_addr = (dvma_addr_t)mp->dmai_mapping;
1046 	dvma_addr_t dvma_pg = IOMMU_BTOP(dvma_addr);
1047 	dvma_addr = IOMMU_PTOB(dvma_pg);
1048 
1049 	if (mp->dmai_flags & DMAI_FLAGS_FASTTRACK) {
1050 		iopfn_t index = dvma_pg - iommu_p->dvma_base_pg;
1051 		ASSERT(index % pci_dvma_page_cache_clustsz == 0);
1052 		index /= pci_dvma_page_cache_clustsz;
1053 		ASSERT(index < pci_dvma_page_cache_entries);
1054 		iommu_p->iommu_dvma_cache_locks[index] = 0;
1055 #ifdef PCI_DMA_PROF
1056 		pci_dvmaft_free++;
1057 #endif
1058 		return;
1059 	}
1060 	npages = IOMMU_BTOP(mp->dmai_winsize) + HAS_REDZONE(mp);
1061 	pci_vmem_free(iommu_p, mp, (void *)dvma_addr, npages);
1062 
1063 	if (mp->dmai_flags & DMAI_FLAGS_CONTEXT)
1064 		pci_iommu_free_dvma_context(iommu_p, MP2CTX(mp));
1065 }
1066 
1067 void
1068 pci_dma_sync_unmap(dev_info_t *dip, dev_info_t *rdip, ddi_dma_impl_t *mp)
1069 {
1070 	pci_t *pci_p = get_pci_soft_state(ddi_get_instance(dip));
1071 	iommu_t *iommu_p = pci_p->pci_iommu_p;
1072 	uint64_t sync_buf_save = SYNC_BUF_PA(mp);
1073 	uint32_t fast_track = mp->dmai_flags & DMAI_FLAGS_FASTTRACK;
1074 
1075 	if (fast_track) {
1076 		dvma_addr_t dvma_pg = IOMMU_BTOP(mp->dmai_mapping);
1077 
1078 		SYNC_BUF_PA(mp) = IOMMU_PAGE_TTEPA(iommu_p, dvma_pg);
1079 		ASSERT(!(SYNC_BUF_PA(mp) & PCI_SYNC_FLAG_SIZE - 1));
1080 	}
1081 
1082 	if (pci_dvma_sync_before_unmap) {
1083 		pci_dma_sync(dip, rdip, (ddi_dma_handle_t)mp, 0, 0, 0);
1084 		iommu_unmap_window(iommu_p, mp);
1085 	} else {
1086 		iommu_unmap_window(iommu_p, mp);
1087 		pci_dma_sync(dip, rdip, (ddi_dma_handle_t)mp, 0, 0, 0);
1088 	}
1089 
1090 	if (fast_track)
1091 		SYNC_BUF_PA(mp) = sync_buf_save;
1092 }
1093 
1094 /*
1095  * DVMA mappings may have multiple windows, but each window always have
1096  * one segment.
1097  */
1098 int
1099 pci_dvma_ctl(dev_info_t *dip, dev_info_t *rdip, ddi_dma_impl_t *mp,
1100 	enum ddi_dma_ctlops cmd, off_t *offp, size_t *lenp, caddr_t *objp,
1101 	uint_t cache_flags)
1102 {
1103 	switch (cmd) {
1104 	case DDI_DMA_SYNC:
1105 		return (pci_dma_sync(dip, rdip, (ddi_dma_handle_t)mp,
1106 		    *offp, *lenp, cache_flags));
1107 
1108 	case DDI_DMA_HTOC: {
1109 		int ret;
1110 		off_t wo_off, off = *offp;	/* wo_off: wnd's obj offset */
1111 		uint_t win_size = mp->dmai_winsize;
1112 		ddi_dma_cookie_t *cp = (ddi_dma_cookie_t *)objp;
1113 
1114 		if (off >= mp->dmai_object.dmao_size) {
1115 			cmn_err(CE_WARN, "%s%d invalid dma_htoc offset %lx",
1116 				NAMEINST(mp->dmai_rdip), off);
1117 			return (DDI_FAILURE);
1118 		}
1119 		off += mp->dmai_roffset;
1120 		ret = pci_dma_win(dip, rdip, (ddi_dma_handle_t)mp,
1121 		    off / win_size, &wo_off, NULL, cp, NULL); /* lenp == NULL */
1122 		if (ret)
1123 			return (ret);
1124 		DEBUG4(DBG_DMA_CTL, dip, "HTOC:cookie=%x+%lx off=%lx,%lx\n",
1125 			cp->dmac_address, cp->dmac_size, off, *offp);
1126 
1127 		/* adjust cookie addr/len if we are not on window boundary */
1128 		ASSERT((off % win_size) == (off -
1129 			(PCI_DMA_CURWIN(mp) ? mp->dmai_roffset : 0) - wo_off));
1130 		off = PCI_DMA_CURWIN(mp) ? off % win_size : *offp;
1131 		ASSERT(cp->dmac_size > off);
1132 		cp->dmac_laddress += off;
1133 		cp->dmac_size -= off;
1134 		DEBUG5(DBG_DMA_CTL, dip,
1135 			"HTOC:mp=%p cookie=%x+%lx off=%lx,%lx\n",
1136 			mp, cp->dmac_address, cp->dmac_size, off, wo_off);
1137 		}
1138 		return (DDI_SUCCESS);
1139 
1140 	case DDI_DMA_REPWIN:
1141 		*offp = mp->dmai_offset;
1142 		*lenp = mp->dmai_size;
1143 		return (DDI_SUCCESS);
1144 
1145 	case DDI_DMA_MOVWIN: {
1146 		off_t off = *offp;
1147 		if (off >= mp->dmai_object.dmao_size)
1148 			return (DDI_FAILURE);
1149 		off += mp->dmai_roffset;
1150 		return (pci_dma_win(dip, rdip, (ddi_dma_handle_t)mp,
1151 		    off / mp->dmai_winsize, offp, lenp,
1152 		    (ddi_dma_cookie_t *)objp, NULL));
1153 		}
1154 
1155 	case DDI_DMA_NEXTWIN: {
1156 		window_t win = PCI_DMA_CURWIN(mp);
1157 		if (offp) {
1158 			if (*(window_t *)offp != win) {  /* window not active */
1159 				*(window_t *)objp = win; /* return cur win */
1160 				return (DDI_DMA_STALE);
1161 			}
1162 			win++;
1163 		} else	/* map win 0 */
1164 			win = 0;
1165 		if (win >= mp->dmai_nwin) {
1166 			*(window_t *)objp = win - 1;
1167 			return (DDI_DMA_DONE);
1168 		}
1169 		if (pci_dma_win(dip, rdip, (ddi_dma_handle_t)mp,
1170 		    win, 0, 0, 0, 0)) {
1171 			*(window_t *)objp = win - 1;
1172 			return (DDI_FAILURE);
1173 		}
1174 		*(window_t *)objp = win;
1175 		}
1176 		return (DDI_SUCCESS);
1177 
1178 	case DDI_DMA_NEXTSEG:
1179 		if (*(window_t *)offp != PCI_DMA_CURWIN(mp))
1180 			return (DDI_DMA_STALE);
1181 		if (lenp)				/* only 1 seg allowed */
1182 			return (DDI_DMA_DONE);
1183 							/* return mp as seg 0 */
1184 		*(ddi_dma_seg_t *)objp = (ddi_dma_seg_t)mp;
1185 		return (DDI_SUCCESS);
1186 
1187 	case DDI_DMA_SEGTOC:
1188 		MAKE_DMA_COOKIE((ddi_dma_cookie_t *)objp, mp->dmai_mapping,
1189 			mp->dmai_size);
1190 		*offp = mp->dmai_offset;
1191 		*lenp = mp->dmai_size;
1192 		return (DDI_SUCCESS);
1193 
1194 	case DDI_DMA_COFF: {
1195 		ddi_dma_cookie_t *cp = (ddi_dma_cookie_t *)offp;
1196 		if (cp->dmac_address < mp->dmai_mapping ||
1197 		    (cp->dmac_address + cp->dmac_size) >
1198 		    (mp->dmai_mapping + mp->dmai_size))
1199 			return (DDI_FAILURE);
1200 		*objp = (caddr_t)(cp->dmac_address - mp->dmai_mapping +
1201 			mp->dmai_offset);
1202 		}
1203 		return (DDI_SUCCESS);
1204 
1205 	case DDI_DMA_REMAP:
1206 		if (pci_dvma_remap_enabled)
1207 			return (pci_dvma_remap(dip, rdip, mp, *offp, *lenp));
1208 		return (DDI_FAILURE);
1209 
1210 	default:
1211 		DEBUG3(DBG_DMA_CTL, dip, "unknown command (%x): rdip=%s%d\n",
1212 			cmd, ddi_driver_name(rdip), ddi_get_instance(rdip));
1213 		break;
1214 	}
1215 	return (DDI_FAILURE);
1216 }
1217 
1218 void
1219 pci_dma_freewin(ddi_dma_impl_t *mp)
1220 {
1221 	pci_dma_win_t *win_p = mp->dmai_winlst, *win2_p;
1222 	for (win2_p = win_p; win_p; win2_p = win_p) {
1223 		win_p = win2_p->win_next;
1224 		kmem_free(win2_p, sizeof (pci_dma_win_t) +
1225 			sizeof (ddi_dma_cookie_t) * win2_p->win_ncookies);
1226 	}
1227 	mp->dmai_nwin = 0;
1228 	mp->dmai_winlst = NULL;
1229 }
1230 
1231 /*
1232  * pci_dma_newwin - create a dma window object and cookies
1233  *
1234  *	After the initial scan in pci_dma_physwin(), which identifies
1235  *	a portion of the pfn array that belongs to a dma window,
1236  *	we are called to allocate and initialize representing memory
1237  *	resources. We know from the 1st scan the number of cookies
1238  *	or dma segment in this window so we can allocate a contiguous
1239  *	memory array for the dma cookies (The implementation of
1240  *	ddi_dma_nextcookie(9f) dictates dma cookies be contiguous).
1241  *
1242  *	A second round scan is done on the pfn array to identify
1243  *	each dma segment and initialize its corresponding dma cookie.
1244  *	We don't need to do all the safety checking and we know they
1245  *	all belong to the same dma window.
1246  *
1247  *	Input:	cookie_no - # of cookies identified by the 1st scan
1248  *		start_idx - subscript of the pfn array for the starting pfn
1249  *		end_idx   - subscript of the last pfn in dma window
1250  *		win_pp    - pointer to win_next member of previous window
1251  *	Return:	DDI_SUCCESS - with **win_pp as newly created window object
1252  *		DDI_DMA_NORESROUCE - caller frees all previous window objs
1253  *	Note:	Each cookie and window size are all initialized on page
1254  *		boundary. This is not true for the 1st cookie of the 1st
1255  *		window and the last cookie of the last window.
1256  *		We fix that later in upper layer which has access to size
1257  *		and offset info.
1258  *
1259  */
1260 static int
1261 pci_dma_newwin(ddi_dma_req_t *dmareq, ddi_dma_impl_t *mp, uint32_t cookie_no,
1262 	uint32_t start_idx, uint32_t end_idx, pci_dma_win_t **win_pp,
1263 	uint64_t count_max, uint64_t bypass_prefix)
1264 {
1265 	int (*waitfp)(caddr_t) = dmareq->dmar_fp;
1266 	ddi_dma_cookie_t *cookie_p;
1267 	uint32_t pfn_no = 1;
1268 	iopfn_t pfn = PCI_GET_MP_PFN(mp, start_idx);
1269 	iopfn_t prev_pfn = pfn;
1270 	uint64_t seg_pfn0 = pfn;
1271 	size_t sz = cookie_no * sizeof (ddi_dma_cookie_t);
1272 	pci_dma_win_t *win_p = kmem_alloc(sizeof (pci_dma_win_t) + sz,
1273 		waitfp == DDI_DMA_SLEEP ? KM_SLEEP : KM_NOSLEEP);
1274 	if (!win_p)
1275 		goto noresource;
1276 
1277 	win_p->win_next = NULL;
1278 	win_p->win_ncookies = cookie_no;
1279 	win_p->win_curseg = 0;	/* start from segment 0 */
1280 	win_p->win_size = IOMMU_PTOB(end_idx - start_idx + 1);
1281 	/* win_p->win_offset is left uninitialized */
1282 
1283 	cookie_p = (ddi_dma_cookie_t *)(win_p + 1);
1284 	start_idx++;
1285 	for (; start_idx <= end_idx; start_idx++, prev_pfn = pfn, pfn_no++) {
1286 		pfn = PCI_GET_MP_PFN1(mp, start_idx);
1287 		if ((pfn == prev_pfn + 1) &&
1288 			(IOMMU_PTOB(pfn_no + 1) - 1 <= count_max))
1289 			continue;
1290 
1291 		/* close up the cookie up to (including) prev_pfn */
1292 		MAKE_DMA_COOKIE(cookie_p, IOMMU_PTOB(seg_pfn0) | bypass_prefix,
1293 			IOMMU_PTOB(pfn_no));
1294 		DEBUG2(DBG_BYPASS, mp->dmai_rdip, "cookie %p (%x pages)\n",
1295 			IOMMU_PTOB(seg_pfn0) | bypass_prefix, pfn_no);
1296 
1297 		cookie_p++;	/* advance to next available cookie cell */
1298 		pfn_no = 0;
1299 		seg_pfn0 = pfn;	/* start a new segment from current pfn */
1300 	}
1301 	MAKE_DMA_COOKIE(cookie_p, IOMMU_PTOB(seg_pfn0) | bypass_prefix,
1302 		IOMMU_PTOB(pfn_no));
1303 	DEBUG3(DBG_BYPASS, mp->dmai_rdip, "cookie %p (%x pages) of total %x\n",
1304 		IOMMU_PTOB(seg_pfn0) | bypass_prefix, pfn_no, cookie_no);
1305 #ifdef DEBUG
1306 	cookie_p++;
1307 	ASSERT((cookie_p - (ddi_dma_cookie_t *)(win_p + 1)) == cookie_no);
1308 #endif
1309 	*win_pp = win_p;
1310 	return (DDI_SUCCESS);
1311 noresource:
1312 	if (waitfp != DDI_DMA_DONTWAIT)
1313 		ddi_set_callback(waitfp, dmareq->dmar_arg, &pci_kmem_clid);
1314 	return (DDI_DMA_NORESOURCES);
1315 }
1316 
1317 /*
1318  * pci_dma_adjust - adjust 1st and last cookie and window sizes
1319  *	remove initial dma page offset from 1st cookie and window size
1320  *	remove last dma page remainder from last cookie and window size
1321  *	fill win_offset of each dma window according to just fixed up
1322  *		each window sizes
1323  *	pci_dma_win_t members modified:
1324  *	win_p->win_offset - this window's offset within entire DMA object
1325  *	win_p->win_size	  - xferrable size (in bytes) for this window
1326  *
1327  *	ddi_dma_impl_t members modified:
1328  *	mp->dmai_size	  - 1st window xferrable size
1329  *	mp->dmai_offset   - 0, which is the dma offset of the 1st window
1330  *
1331  *	ddi_dma_cookie_t members modified:
1332  *	cookie_p->dmac_size - 1st and last cookie remove offset or remainder
1333  *	cookie_p->dmac_laddress - 1st cookie add page offset
1334  */
1335 static void
1336 pci_dma_adjust(ddi_dma_req_t *dmareq, ddi_dma_impl_t *mp, pci_dma_win_t *win_p)
1337 {
1338 	ddi_dma_cookie_t *cookie_p = (ddi_dma_cookie_t *)(win_p + 1);
1339 	size_t pg_offset = mp->dmai_roffset;
1340 	size_t win_offset = 0;
1341 
1342 	cookie_p->dmac_size -= pg_offset;
1343 	cookie_p->dmac_laddress |= pg_offset;
1344 	win_p->win_size -= pg_offset;
1345 	DEBUG1(DBG_BYPASS, mp->dmai_rdip, "pg0 adjust %lx\n", pg_offset);
1346 
1347 	mp->dmai_size = win_p->win_size;
1348 	mp->dmai_offset = 0;
1349 
1350 	pg_offset += mp->dmai_object.dmao_size;
1351 	pg_offset &= IOMMU_PAGE_OFFSET;
1352 	if (pg_offset)
1353 		pg_offset = IOMMU_PAGE_SIZE - pg_offset;
1354 	DEBUG1(DBG_BYPASS, mp->dmai_rdip, "last pg adjust %lx\n", pg_offset);
1355 
1356 	for (; win_p->win_next; win_p = win_p->win_next) {
1357 		DEBUG1(DBG_BYPASS, mp->dmai_rdip, "win off %p\n", win_offset);
1358 		win_p->win_offset = win_offset;
1359 		win_offset += win_p->win_size;
1360 	}
1361 	/* last window */
1362 	win_p->win_offset = win_offset;
1363 	cookie_p = (ddi_dma_cookie_t *)(win_p + 1);
1364 	cookie_p[win_p->win_ncookies - 1].dmac_size -= pg_offset;
1365 	win_p->win_size -= pg_offset;
1366 	ASSERT((win_offset + win_p->win_size) == mp->dmai_object.dmao_size);
1367 }
1368 
1369 /*
1370  * pci_dma_physwin() - carve up dma windows using physical addresses.
1371  *	Called to handle iommu bypass and pci peer-to-peer transfers.
1372  *	Calls pci_dma_newwin() to allocate window objects.
1373  *
1374  * Dependency: mp->dmai_pfnlst points to an array of pfns
1375  *
1376  * 1. Each dma window is represented by a pci_dma_win_t object.
1377  *	The object will be casted to ddi_dma_win_t and returned
1378  *	to leaf driver through the DDI interface.
1379  * 2. Each dma window can have several dma segments with each
1380  *	segment representing a physically contiguous either memory
1381  *	space (if we are doing an iommu bypass transfer) or pci address
1382  *	space (if we are doing a peer-to-peer transfer).
1383  * 3. Each segment has a DMA cookie to program the DMA engine.
1384  *	The cookies within each DMA window must be located in a
1385  *	contiguous array per ddi_dma_nextcookie(9f).
1386  * 4. The number of DMA segments within each DMA window cannot exceed
1387  *	mp->dmai_attr.dma_attr_sgllen. If the transfer size is
1388  *	too large to fit in the sgllen, the rest needs to be
1389  *	relocated to the next dma window.
1390  * 5. Peer-to-peer DMA segment follows device hi, lo, count_max,
1391  *	and nocross restrictions while bypass DMA follows the set of
1392  *	restrictions with system limits factored in.
1393  *
1394  * Return:
1395  *	mp->dmai_winlst	 - points to a link list of pci_dma_win_t objects.
1396  *		Each pci_dma_win_t object on the link list contains
1397  *		infomation such as its window size (# of pages),
1398  *		starting offset (also see Restriction), an array of
1399  *		DMA cookies, and # of cookies in the array.
1400  *	mp->dmai_pfnlst	 - NULL, the pfn list is freed to conserve memory.
1401  *	mp->dmai_nwin	 - # of total DMA windows on mp->dmai_winlst.
1402  *	mp->dmai_mapping - starting cookie address
1403  *	mp->dmai_rflags	 - consistent, nosync, no redzone
1404  *	mp->dmai_cookie	 - start of cookie table of the 1st DMA window
1405  *
1406  * Restriction:
1407  *	Each pci_dma_win_t object can theoratically start from any offset
1408  *	since the iommu is not involved. However, this implementation
1409  *	always make windows start from page aligned offset (except
1410  *	the 1st window, which follows the requested offset) due to the
1411  *	fact that we are handed a pfn list. This does require device's
1412  *	count_max and attr_seg to be at least IOMMU_PAGE_SIZE aligned.
1413  */
1414 int
1415 pci_dma_physwin(pci_t *pci_p, ddi_dma_req_t *dmareq, ddi_dma_impl_t *mp)
1416 {
1417 	uint_t npages = mp->dmai_ndvmapages;
1418 	int ret, sgllen = mp->dmai_attr.dma_attr_sgllen;
1419 	iopfn_t pfn_lo, pfn_hi, prev_pfn, bypass_pfn;
1420 	iopfn_t pfn = PCI_GET_MP_PFN(mp, 0);
1421 	uint32_t i, win_no = 0, pfn_no = 1, win_pfn0_index = 0, cookie_no = 0;
1422 	uint64_t count_max, bypass = PCI_DMA_BYPASS_PREFIX(mp, pfn);
1423 	pci_dma_win_t **win_pp = (pci_dma_win_t **)&mp->dmai_winlst;
1424 	ddi_dma_cookie_t *cookie0_p;
1425 
1426 	if (PCI_DMA_ISPTP(mp)) { /* ignore sys limits for peer-to-peer */
1427 		ddi_dma_attr_t *dev_attr_p = DEV_ATTR(mp);
1428 		iopfn_t pfn_base = pci_p->pci_pbm_p->pbm_base_pfn;
1429 		iopfn_t pfn_last = pci_p->pci_pbm_p->pbm_last_pfn - pfn_base;
1430 		uint64_t nocross = dev_attr_p->dma_attr_seg;
1431 		if (nocross && (nocross < UINT32_MAX))
1432 			return (DDI_DMA_NOMAPPING);
1433 		if (dev_attr_p->dma_attr_align > IOMMU_PAGE_SIZE)
1434 			return (DDI_DMA_NOMAPPING);
1435 		pfn_lo = IOMMU_BTOP(dev_attr_p->dma_attr_addr_lo);
1436 		pfn_hi = IOMMU_BTOP(dev_attr_p->dma_attr_addr_hi);
1437 		pfn_hi = MIN(pfn_hi, pfn_last);
1438 		if ((pfn_lo > pfn_hi) || (pfn < pfn_lo))
1439 			return (DDI_DMA_NOMAPPING);
1440 		count_max = dev_attr_p->dma_attr_count_max;
1441 		count_max = MIN(count_max, nocross);
1442 		/*
1443 		 * the following count_max trim is not done because we are
1444 		 * making sure pfn_lo <= pfn <= pfn_hi inside the loop
1445 		 * count_max=MIN(count_max, IOMMU_PTOB(pfn_hi - pfn_lo + 1)-1);
1446 		 */
1447 	} else { /* bypass hi/lo/count_max have been processed by attr2hdl() */
1448 		count_max = mp->dmai_attr.dma_attr_count_max;
1449 		pfn_lo = IOMMU_BTOP(mp->dmai_attr.dma_attr_addr_lo);
1450 		pfn_hi = IOMMU_BTOP(mp->dmai_attr.dma_attr_addr_hi);
1451 	}
1452 
1453 	bypass_pfn = IOMMU_BTOP(bypass);
1454 
1455 	for (prev_pfn = (bypass_pfn | pfn), i = 1; i < npages;
1456 	    i++, prev_pfn = pfn, pfn_no++) {
1457 		pfn = bypass_pfn | PCI_GET_MP_PFN1(mp, i);
1458 		if ((pfn == prev_pfn + 1) &&
1459 			(IOMMU_PTOB(pfn_no + 1) - 1 <= count_max))
1460 			continue;
1461 		if ((pfn < pfn_lo) || (prev_pfn > pfn_hi)) {
1462 			ret = DDI_DMA_NOMAPPING;
1463 			goto err;
1464 		}
1465 		cookie_no++;
1466 		pfn_no = 0;
1467 		if (cookie_no < sgllen)
1468 			continue;
1469 
1470 		DEBUG3(DBG_BYPASS, mp->dmai_rdip, "newwin pfn[%x-%x] %x cks\n",
1471 			win_pfn0_index, i - 1, cookie_no);
1472 		if (ret = pci_dma_newwin(dmareq, mp, cookie_no,
1473 			win_pfn0_index, i - 1, win_pp, count_max, bypass))
1474 			goto err;
1475 
1476 		win_pp = &(*win_pp)->win_next;	/* win_pp = *(win_pp) */
1477 		win_no++;
1478 		win_pfn0_index = i;
1479 		cookie_no = 0;
1480 	}
1481 	if (pfn > pfn_hi) {
1482 		ret = DDI_DMA_NOMAPPING;
1483 		goto err;
1484 	}
1485 	cookie_no++;
1486 	DEBUG3(DBG_BYPASS, mp->dmai_rdip, "newwin pfn[%x-%x] %x cks\n",
1487 		win_pfn0_index, i - 1, cookie_no);
1488 	if (ret = pci_dma_newwin(dmareq, mp, cookie_no, win_pfn0_index,
1489 		i - 1, win_pp, count_max, bypass))
1490 		goto err;
1491 	win_no++;
1492 	pci_dma_adjust(dmareq, mp, mp->dmai_winlst);
1493 	mp->dmai_nwin = win_no;
1494 	mp->dmai_rflags |= DDI_DMA_CONSISTENT;
1495 	if (!pci_p->pci_pbm_p->pbm_sync_reg_pa) {
1496 		mp->dmai_rflags |= DMP_NOSYNC;
1497 		mp->dmai_flags |= DMAI_FLAGS_NOSYNC;
1498 	}
1499 	mp->dmai_rflags &= ~DDI_DMA_REDZONE;
1500 	cookie0_p = (ddi_dma_cookie_t *)(WINLST(mp) + 1);
1501 	mp->dmai_cookie = WINLST(mp)->win_ncookies > 1 ? cookie0_p + 1 : 0;
1502 	mp->dmai_mapping = cookie0_p->dmac_laddress;
1503 
1504 	pci_dma_freepfn(mp);
1505 	return (DDI_DMA_MAPPED);
1506 err:
1507 	pci_dma_freewin(mp);
1508 	return (ret);
1509 }
1510 
1511 /*ARGSUSED*/
1512 int
1513 pci_dma_ctl(dev_info_t *dip, dev_info_t *rdip, ddi_dma_impl_t *mp,
1514 	enum ddi_dma_ctlops cmd, off_t *offp, size_t *lenp, caddr_t *objp,
1515 	uint_t cache_flags)
1516 {
1517 	switch (cmd) {
1518 	case DDI_DMA_SYNC: /* XXX */
1519 		return (DDI_SUCCESS);
1520 
1521 	case DDI_DMA_HTOC: {
1522 		off_t off = *offp;
1523 		ddi_dma_cookie_t *loop_cp, *cp;
1524 		pci_dma_win_t *win_p = mp->dmai_winlst;
1525 
1526 		if (off >= mp->dmai_object.dmao_size)
1527 			return (DDI_FAILURE);
1528 
1529 		/* locate window */
1530 		while (win_p->win_offset + win_p->win_size <= off)
1531 			win_p = win_p->win_next;
1532 
1533 		loop_cp = cp = (ddi_dma_cookie_t *)(win_p + 1);
1534 		mp->dmai_offset = win_p->win_offset;
1535 		mp->dmai_size   = win_p->win_size;
1536 		mp->dmai_mapping = cp->dmac_laddress; /* cookie0 start addr */
1537 
1538 		/* adjust cookie addr/len if we are not on cookie boundary */
1539 		off -= win_p->win_offset;	   /* offset within window */
1540 		for (; off >= loop_cp->dmac_size; loop_cp++)
1541 			off -= loop_cp->dmac_size; /* offset within cookie */
1542 
1543 		mp->dmai_cookie = loop_cp + 1;
1544 		win_p->win_curseg = loop_cp - cp;
1545 		cp = (ddi_dma_cookie_t *)objp;
1546 		MAKE_DMA_COOKIE(cp, loop_cp->dmac_laddress + off,
1547 			loop_cp->dmac_size - off);
1548 
1549 		DEBUG2(DBG_DMA_CTL, dip,
1550 			"HTOC: cookie - dmac_laddress=%p dmac_size=%x\n",
1551 			cp->dmac_laddress, cp->dmac_size);
1552 		}
1553 		return (DDI_SUCCESS);
1554 
1555 	case DDI_DMA_REPWIN:
1556 		*offp = mp->dmai_offset;
1557 		*lenp = mp->dmai_size;
1558 		return (DDI_SUCCESS);
1559 
1560 	case DDI_DMA_MOVWIN: {
1561 		off_t off = *offp;
1562 		ddi_dma_cookie_t *cp;
1563 		pci_dma_win_t *win_p = mp->dmai_winlst;
1564 
1565 		if (off >= mp->dmai_object.dmao_size)
1566 			return (DDI_FAILURE);
1567 
1568 		/* locate window */
1569 		while (win_p->win_offset + win_p->win_size <= off)
1570 			win_p = win_p->win_next;
1571 
1572 		cp = (ddi_dma_cookie_t *)(win_p + 1);
1573 		mp->dmai_offset = win_p->win_offset;
1574 		mp->dmai_size   = win_p->win_size;
1575 		mp->dmai_mapping = cp->dmac_laddress;	/* cookie0 star addr */
1576 		mp->dmai_cookie = cp + 1;
1577 		win_p->win_curseg = 0;
1578 
1579 		*(ddi_dma_cookie_t *)objp = *cp;
1580 		*offp = win_p->win_offset;
1581 		*lenp = win_p->win_size;
1582 		DEBUG2(DBG_DMA_CTL, dip,
1583 			"HTOC: cookie - dmac_laddress=%p dmac_size=%x\n",
1584 			cp->dmac_laddress, cp->dmac_size);
1585 		}
1586 		return (DDI_SUCCESS);
1587 
1588 	case DDI_DMA_NEXTWIN: {
1589 		pci_dma_win_t *win_p = *(pci_dma_win_t **)offp;
1590 		pci_dma_win_t **nw_pp = (pci_dma_win_t **)objp;
1591 		ddi_dma_cookie_t *cp;
1592 		if (!win_p) {
1593 			*nw_pp = mp->dmai_winlst;
1594 			return (DDI_SUCCESS);
1595 		}
1596 
1597 		if (win_p->win_offset != mp->dmai_offset)
1598 			return (DDI_DMA_STALE);
1599 		if (!win_p->win_next)
1600 			return (DDI_DMA_DONE);
1601 		win_p = win_p->win_next;
1602 		cp = (ddi_dma_cookie_t *)(win_p + 1);
1603 		mp->dmai_offset = win_p->win_offset;
1604 		mp->dmai_size   = win_p->win_size;
1605 		mp->dmai_mapping = cp->dmac_laddress;   /* cookie0 star addr */
1606 		mp->dmai_cookie = cp + 1;
1607 		win_p->win_curseg = 0;
1608 		*nw_pp = win_p;
1609 		}
1610 		return (DDI_SUCCESS);
1611 
1612 	case DDI_DMA_NEXTSEG: {
1613 		pci_dma_win_t *w_p = *(pci_dma_win_t **)offp;
1614 		if (w_p->win_offset != mp->dmai_offset)
1615 			return (DDI_DMA_STALE);
1616 		if (w_p->win_curseg + 1 >= w_p->win_ncookies)
1617 			return (DDI_DMA_DONE);
1618 		w_p->win_curseg++;
1619 		}
1620 		*(ddi_dma_seg_t *)objp = (ddi_dma_seg_t)mp;
1621 		return (DDI_SUCCESS);
1622 
1623 	case DDI_DMA_SEGTOC: {
1624 		pci_dma_win_t *win_p = mp->dmai_winlst;
1625 		off_t off = mp->dmai_offset;
1626 		ddi_dma_cookie_t *cp;
1627 		int i;
1628 
1629 		/* locate active window */
1630 		for (; win_p->win_offset != off; win_p = win_p->win_next);
1631 		cp = (ddi_dma_cookie_t *)(win_p + 1);
1632 		for (i = 0; i < win_p->win_curseg; i++, cp++)
1633 			off += cp->dmac_size;
1634 		*offp = off;
1635 		*lenp = cp->dmac_size;
1636 		*(ddi_dma_cookie_t *)objp = *cp;	/* copy cookie */
1637 		}
1638 		return (DDI_SUCCESS);
1639 
1640 	case DDI_DMA_COFF: {
1641 		pci_dma_win_t *win_p;
1642 		ddi_dma_cookie_t *cp;
1643 		uint64_t addr, key = ((ddi_dma_cookie_t *)offp)->dmac_laddress;
1644 		size_t win_off;
1645 
1646 		for (win_p = mp->dmai_winlst; win_p; win_p = win_p->win_next) {
1647 			int i;
1648 			win_off = 0;
1649 			cp = (ddi_dma_cookie_t *)(win_p + 1);
1650 			for (i = 0; i < win_p->win_ncookies; i++, cp++) {
1651 				size_t sz = cp->dmac_size;
1652 
1653 				addr = cp->dmac_laddress;
1654 				if ((addr <= key) && (addr + sz >= key))
1655 					goto found;
1656 				win_off += sz;
1657 			}
1658 		}
1659 		return (DDI_FAILURE);
1660 found:
1661 		*objp = (caddr_t)(win_p->win_offset + win_off + (key - addr));
1662 		return (DDI_SUCCESS);
1663 		}
1664 
1665 	case DDI_DMA_REMAP:
1666 		return (DDI_FAILURE);
1667 
1668 	default:
1669 		DEBUG3(DBG_DMA_CTL, dip, "unknown command (%x): rdip=%s%d\n",
1670 			cmd, ddi_driver_name(rdip), ddi_get_instance(rdip));
1671 		break;
1672 	}
1673 	return (DDI_FAILURE);
1674 }
1675 
1676 static void
1677 pci_dvma_debug_init(iommu_t *iommu_p)
1678 {
1679 	size_t sz = sizeof (struct dvma_rec) * pci_dvma_debug_rec;
1680 	ASSERT(MUTEX_HELD(&iommu_p->dvma_debug_lock));
1681 	cmn_err(CE_NOTE, "PCI DVMA %p stat ON", iommu_p);
1682 
1683 	iommu_p->dvma_alloc_rec = kmem_zalloc(sz, KM_SLEEP);
1684 	iommu_p->dvma_free_rec = kmem_zalloc(sz, KM_SLEEP);
1685 
1686 	iommu_p->dvma_active_list = NULL;
1687 	iommu_p->dvma_alloc_rec_index = 0;
1688 	iommu_p->dvma_free_rec_index = 0;
1689 	iommu_p->dvma_active_count = 0;
1690 }
1691 
1692 void
1693 pci_dvma_debug_fini(iommu_t *iommu_p)
1694 {
1695 	struct dvma_rec *prev, *ptr;
1696 	size_t sz = sizeof (struct dvma_rec) * pci_dvma_debug_rec;
1697 	uint64_t mask = ~(1ull << iommu_p->iommu_inst);
1698 	cmn_err(CE_NOTE, "PCI DVMA %p stat OFF", iommu_p);
1699 
1700 	kmem_free(iommu_p->dvma_alloc_rec, sz);
1701 	kmem_free(iommu_p->dvma_free_rec, sz);
1702 	iommu_p->dvma_alloc_rec = iommu_p->dvma_free_rec = NULL;
1703 
1704 	prev = iommu_p->dvma_active_list;
1705 	if (!prev)
1706 		return;
1707 	for (ptr = prev->next; ptr; prev = ptr, ptr = ptr->next)
1708 		kmem_free(prev, sizeof (struct dvma_rec));
1709 	kmem_free(prev, sizeof (struct dvma_rec));
1710 
1711 	iommu_p->dvma_active_list = NULL;
1712 	iommu_p->dvma_alloc_rec_index = 0;
1713 	iommu_p->dvma_free_rec_index = 0;
1714 	iommu_p->dvma_active_count = 0;
1715 
1716 	pci_dvma_debug_on  &= mask;
1717 	pci_dvma_debug_off &= mask;
1718 }
1719 
1720 void
1721 pci_dvma_alloc_debug(iommu_t *iommu_p, char *address, uint_t len,
1722 	ddi_dma_impl_t *mp)
1723 {
1724 	struct dvma_rec *ptr;
1725 	mutex_enter(&iommu_p->dvma_debug_lock);
1726 
1727 	if (!iommu_p->dvma_alloc_rec)
1728 		pci_dvma_debug_init(iommu_p);
1729 	if (DVMA_DBG_OFF(iommu_p)) {
1730 		pci_dvma_debug_fini(iommu_p);
1731 		goto done;
1732 	}
1733 
1734 	ptr = &iommu_p->dvma_alloc_rec[iommu_p->dvma_alloc_rec_index];
1735 	ptr->dvma_addr = address;
1736 	ptr->len = len;
1737 	ptr->mp = mp;
1738 	if (++iommu_p->dvma_alloc_rec_index == pci_dvma_debug_rec)
1739 		iommu_p->dvma_alloc_rec_index = 0;
1740 
1741 	ptr = kmem_alloc(sizeof (struct dvma_rec), KM_SLEEP);
1742 	ptr->dvma_addr = address;
1743 	ptr->len = len;
1744 	ptr->mp = mp;
1745 
1746 	ptr->next = iommu_p->dvma_active_list;
1747 	iommu_p->dvma_active_list = ptr;
1748 	iommu_p->dvma_active_count++;
1749 done:
1750 	mutex_exit(&iommu_p->dvma_debug_lock);
1751 }
1752 
1753 void
1754 pci_dvma_free_debug(iommu_t *iommu_p, char *address, uint_t len,
1755 	ddi_dma_impl_t *mp)
1756 {
1757 	struct dvma_rec *ptr, *ptr_save;
1758 	mutex_enter(&iommu_p->dvma_debug_lock);
1759 
1760 	if (!iommu_p->dvma_alloc_rec)
1761 		pci_dvma_debug_init(iommu_p);
1762 	if (DVMA_DBG_OFF(iommu_p)) {
1763 		pci_dvma_debug_fini(iommu_p);
1764 		goto done;
1765 	}
1766 
1767 	ptr = &iommu_p->dvma_free_rec[iommu_p->dvma_free_rec_index];
1768 	ptr->dvma_addr = address;
1769 	ptr->len = len;
1770 	ptr->mp = mp;
1771 	if (++iommu_p->dvma_free_rec_index == pci_dvma_debug_rec)
1772 		iommu_p->dvma_free_rec_index = 0;
1773 
1774 	ptr_save = iommu_p->dvma_active_list;
1775 	for (ptr = ptr_save; ptr; ptr = ptr->next) {
1776 		if ((ptr->dvma_addr == address) && (ptr->len = len))
1777 			break;
1778 		ptr_save = ptr;
1779 	}
1780 	if (!ptr) {
1781 		cmn_err(CE_WARN, "bad dvma free addr=%lx len=%x",
1782 			(long)address, len);
1783 		goto done;
1784 	}
1785 	if (ptr == iommu_p->dvma_active_list)
1786 		iommu_p->dvma_active_list = ptr->next;
1787 	else
1788 		ptr_save->next = ptr->next;
1789 	kmem_free(ptr, sizeof (struct dvma_rec));
1790 	iommu_p->dvma_active_count--;
1791 done:
1792 	mutex_exit(&iommu_p->dvma_debug_lock);
1793 }
1794 
1795 #ifdef DEBUG
1796 void
1797 dump_dma_handle(uint64_t flag, dev_info_t *dip, ddi_dma_impl_t *hp)
1798 {
1799 	DEBUG4(flag, dip, "mp(%p): flags=%x mapping=%lx xfer_size=%x\n",
1800 		hp, hp->dmai_inuse, hp->dmai_mapping, hp->dmai_size);
1801 	DEBUG4(flag|DBG_CONT, dip, "\tnpages=%x roffset=%x rflags=%x nwin=%x\n",
1802 		hp->dmai_ndvmapages, hp->dmai_roffset, hp->dmai_rflags,
1803 		hp->dmai_nwin);
1804 	DEBUG4(flag|DBG_CONT, dip, "\twinsize=%x tte=%p pfnlst=%p pfn0=%p\n",
1805 		hp->dmai_winsize, hp->dmai_tte, hp->dmai_pfnlst, hp->dmai_pfn0);
1806 	DEBUG4(flag|DBG_CONT, dip, "\twinlst=%x obj=%p attr=%p ckp=%p\n",
1807 		hp->dmai_winlst, &hp->dmai_object, &hp->dmai_attr,
1808 		hp->dmai_cookie);
1809 }
1810 #endif
1811 
1812 void
1813 pci_vmem_do_free(iommu_t *iommu_p, void *base_addr, size_t npages,
1814     int vmemcache)
1815 {
1816 	vmem_t *map_p = iommu_p->iommu_dvma_map;
1817 
1818 	if (vmemcache) {
1819 		vmem_free(map_p, base_addr, IOMMU_PAGE_SIZE);
1820 #ifdef PCI_DMA_PROF
1821 		pci_dvma_vmem_free++;
1822 #endif
1823 		return;
1824 	}
1825 
1826 	vmem_xfree(map_p, base_addr, IOMMU_PTOB(npages));
1827 #ifdef PCI_DMA_PROF
1828 		pci_dvma_vmem_xfree++;
1829 #endif
1830 }
1831