xref: /netbsd-src/sys/dev/pci/agp.c (revision 001c68bd94f75ce9270b69227c4199fbf34ee396)
1 /*	$NetBSD: agp.c,v 1.28 2003/06/29 22:30:23 fvdl Exp $	*/
2 
3 /*-
4  * Copyright (c) 2000 Doug Rabson
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  *	$FreeBSD: src/sys/pci/agp.c,v 1.12 2001/05/19 01:28:07 alfred Exp $
29  */
30 
31 /*
32  * Copyright (c) 2001 Wasabi Systems, Inc.
33  * All rights reserved.
34  *
35  * Written by Frank van der Linden for Wasabi Systems, Inc.
36  *
37  * Redistribution and use in source and binary forms, with or without
38  * modification, are permitted provided that the following conditions
39  * are met:
40  * 1. Redistributions of source code must retain the above copyright
41  *    notice, this list of conditions and the following disclaimer.
42  * 2. Redistributions in binary form must reproduce the above copyright
43  *    notice, this list of conditions and the following disclaimer in the
44  *    documentation and/or other materials provided with the distribution.
45  * 3. All advertising materials mentioning features or use of this software
46  *    must display the following acknowledgement:
47  *      This product includes software developed for the NetBSD Project by
48  *      Wasabi Systems, Inc.
49  * 4. The name of Wasabi Systems, Inc. may not be used to endorse
50  *    or promote products derived from this software without specific prior
51  *    written permission.
52  *
53  * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``AS IS'' AND
54  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
55  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
56  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL WASABI SYSTEMS, INC
57  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
58  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
59  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
60  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
61  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
62  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
63  * POSSIBILITY OF SUCH DAMAGE.
64  */
65 
66 
67 #include <sys/cdefs.h>
68 __KERNEL_RCSID(0, "$NetBSD: agp.c,v 1.28 2003/06/29 22:30:23 fvdl Exp $");
69 
70 #include <sys/param.h>
71 #include <sys/systm.h>
72 #include <sys/malloc.h>
73 #include <sys/kernel.h>
74 #include <sys/device.h>
75 #include <sys/conf.h>
76 #include <sys/ioctl.h>
77 #include <sys/fcntl.h>
78 #include <sys/agpio.h>
79 #include <sys/proc.h>
80 
81 #include <uvm/uvm_extern.h>
82 
83 #include <dev/pci/pcireg.h>
84 #include <dev/pci/pcivar.h>
85 #include <dev/pci/agpvar.h>
86 #include <dev/pci/agpreg.h>
87 #include <dev/pci/pcidevs.h>
88 
89 #include <machine/bus.h>
90 
91 MALLOC_DEFINE(M_AGP, "AGP", "AGP memory");
92 
93 /* Helper functions for implementing chipset mini drivers. */
94 /* XXXfvdl get rid of this one. */
95 
96 extern struct cfdriver agp_cd;
97 
98 dev_type_open(agpopen);
99 dev_type_close(agpclose);
100 dev_type_ioctl(agpioctl);
101 dev_type_mmap(agpmmap);
102 
103 const struct cdevsw agp_cdevsw = {
104 	agpopen, agpclose, noread, nowrite, agpioctl,
105 	nostop, notty, nopoll, agpmmap, nokqfilter,
106 };
107 
108 int agpmatch(struct device *, struct cfdata *, void *);
109 void agpattach(struct device *, struct device *, void *);
110 
111 CFATTACH_DECL(agp, sizeof(struct agp_softc),
112     agpmatch, agpattach, NULL, NULL);
113 
114 static int agp_info_user(struct agp_softc *, agp_info *);
115 static int agp_setup_user(struct agp_softc *, agp_setup *);
116 static int agp_allocate_user(struct agp_softc *, agp_allocate *);
117 static int agp_deallocate_user(struct agp_softc *, int);
118 static int agp_bind_user(struct agp_softc *, agp_bind *);
119 static int agp_unbind_user(struct agp_softc *, agp_unbind *);
120 static int agpdev_match(struct pci_attach_args *);
121 
122 #include "agp_ali.h"
123 #include "agp_amd.h"
124 #include "agp_i810.h"
125 #include "agp_intel.h"
126 #include "agp_sis.h"
127 #include "agp_via.h"
128 
129 const struct agp_product {
130 	uint32_t	ap_vendor;
131 	uint32_t	ap_product;
132 	int		(*ap_match)(const struct pci_attach_args *);
133 	int		(*ap_attach)(struct device *, struct device *, void *);
134 } agp_products[] = {
135 #if NAGP_ALI > 0
136 	{ PCI_VENDOR_ALI,	-1,
137 	  NULL,			agp_ali_attach },
138 #endif
139 
140 #if NAGP_AMD > 0
141 	{ PCI_VENDOR_AMD,	-1,
142 	  agp_amd_match,	agp_amd_attach },
143 #endif
144 
145 #if NAGP_I810 > 0
146 	{ PCI_VENDOR_INTEL,	PCI_PRODUCT_INTEL_82810_MCH,
147 	  NULL,			agp_i810_attach },
148 	{ PCI_VENDOR_INTEL,	PCI_PRODUCT_INTEL_82810_DC100_MCH,
149 	  NULL,			agp_i810_attach },
150 	{ PCI_VENDOR_INTEL,	PCI_PRODUCT_INTEL_82810E_MCH,
151 	  NULL,			agp_i810_attach },
152 	{ PCI_VENDOR_INTEL,	PCI_PRODUCT_INTEL_82815_FULL_HUB,
153 	  NULL,			agp_i810_attach },
154 	{ PCI_VENDOR_INTEL,	PCI_PRODUCT_INTEL_82840_HB,
155 	  NULL,			agp_i810_attach },
156 	{ PCI_VENDOR_INTEL,	PCI_PRODUCT_INTEL_82830MP_IO_1,
157 	  NULL,			agp_i810_attach },
158 	{ PCI_VENDOR_INTEL,	PCI_PRODUCT_INTEL_82845G_DRAM,
159 	  NULL,			agp_i810_attach },
160 #endif
161 
162 #if NAGP_INTEL > 0
163 	{ PCI_VENDOR_INTEL,	-1,
164 	  NULL,			agp_intel_attach },
165 #endif
166 
167 #if NAGP_SIS > 0
168 	{ PCI_VENDOR_SIS,	-1,
169 	  NULL,			agp_sis_attach },
170 #endif
171 
172 #if NAGP_VIA > 0
173 	{ PCI_VENDOR_VIATECH,	-1,
174 	  NULL,			agp_via_attach },
175 #endif
176 
177 	{ 0,			0,
178 	  NULL,			NULL },
179 };
180 
181 static const struct agp_product *
182 agp_lookup(const struct pci_attach_args *pa)
183 {
184 	const struct agp_product *ap;
185 
186 	/* First find the vendor. */
187 	for (ap = agp_products; ap->ap_attach != NULL; ap++) {
188 		if (PCI_VENDOR(pa->pa_id) == ap->ap_vendor)
189 			break;
190 	}
191 
192 	if (ap->ap_attach == NULL)
193 		return (NULL);
194 
195 	/* Now find the product within the vendor's domain. */
196 	for (; ap->ap_attach != NULL; ap++) {
197 		if (PCI_VENDOR(pa->pa_id) != ap->ap_vendor) {
198 			/* Ran out of this vendor's section of the table. */
199 			return (NULL);
200 		}
201 		if (ap->ap_product == PCI_PRODUCT(pa->pa_id)) {
202 			/* Exact match. */
203 			break;
204 		}
205 		if (ap->ap_product == (uint32_t) -1) {
206 			/* Wildcard match. */
207 			break;
208 		}
209 	}
210 
211 	if (ap->ap_attach == NULL)
212 		return (NULL);
213 
214 	/* Now let the product-specific driver filter the match. */
215 	if (ap->ap_match != NULL && (*ap->ap_match)(pa) == 0)
216 		return (NULL);
217 
218 	return (ap);
219 }
220 
221 int
222 agpmatch(struct device *parent, struct cfdata *match, void *aux)
223 {
224 	struct agpbus_attach_args *apa = aux;
225 	struct pci_attach_args *pa = &apa->apa_pci_args;
226 
227 	if (strcmp(apa->apa_busname, "agp") != 0)
228 		return (0);
229 
230 	if (agp_lookup(pa) == NULL)
231 		return (0);
232 
233 	return (1);
234 }
235 
236 static int agp_max[][2] = {
237 	{0,	0},
238 	{32,	4},
239 	{64,	28},
240 	{128,	96},
241 	{256,	204},
242 	{512,	440},
243 	{1024,	942},
244 	{2048,	1920},
245 	{4096,	3932}
246 };
247 #define agp_max_size	(sizeof(agp_max) / sizeof(agp_max[0]))
248 
249 void
250 agpattach(struct device *parent, struct device *self, void *aux)
251 {
252 	struct agpbus_attach_args *apa = aux;
253 	struct pci_attach_args *pa = &apa->apa_pci_args;
254 	struct agp_softc *sc = (void *)self;
255 	const struct agp_product *ap;
256 	int memsize, i, ret;
257 
258 	ap = agp_lookup(pa);
259 	if (ap == NULL) {
260 		printf("\n");
261 		panic("agpattach: impossible");
262 	}
263 
264 	aprint_naive(": AGP controller\n");
265 
266 	sc->as_dmat = pa->pa_dmat;
267 	sc->as_pc = pa->pa_pc;
268 	sc->as_tag = pa->pa_tag;
269 	sc->as_id = pa->pa_id;
270 
271 	/*
272 	 * Work out an upper bound for agp memory allocation. This
273 	 * uses a heurisitc table from the Linux driver.
274 	 */
275 	memsize = ptoa(physmem) >> 20;
276 	for (i = 0; i < agp_max_size; i++) {
277 		if (memsize <= agp_max[i][0])
278 			break;
279 	}
280 	if (i == agp_max_size)
281 		i = agp_max_size - 1;
282 	sc->as_maxmem = agp_max[i][1] << 20U;
283 
284 	/*
285 	 * The lock is used to prevent re-entry to
286 	 * agp_generic_bind_memory() since that function can sleep.
287 	 */
288 	lockinit(&sc->as_lock, PZERO|PCATCH, "agplk", 0, 0);
289 
290 	TAILQ_INIT(&sc->as_memory);
291 
292 	ret = (*ap->ap_attach)(parent, self, pa);
293 	if (ret == 0)
294 		aprint_normal(": aperture at 0x%lx, size 0x%lx\n",
295 		    (unsigned long)sc->as_apaddr,
296 		    (unsigned long)AGP_GET_APERTURE(sc));
297 	else
298 		sc->as_chipc = NULL;
299 }
300 int
301 agp_map_aperture(struct pci_attach_args *pa, struct agp_softc *sc)
302 {
303 	/*
304 	 * Find the aperture. Don't map it (yet), this would
305 	 * eat KVA.
306 	 */
307 	if (pci_mapreg_info(pa->pa_pc, pa->pa_tag, AGP_APBASE,
308 	    PCI_MAPREG_TYPE_MEM, &sc->as_apaddr, &sc->as_apsize,
309 	    &sc->as_apflags) != 0)
310 		return ENXIO;
311 
312 	sc->as_apt = pa->pa_memt;
313 
314 	return 0;
315 }
316 
317 struct agp_gatt *
318 agp_alloc_gatt(struct agp_softc *sc)
319 {
320 	u_int32_t apsize = AGP_GET_APERTURE(sc);
321 	u_int32_t entries = apsize >> AGP_PAGE_SHIFT;
322 	struct agp_gatt *gatt;
323 	int dummyseg;
324 
325 	gatt = malloc(sizeof(struct agp_gatt), M_AGP, M_NOWAIT);
326 	if (!gatt)
327 		return NULL;
328 	gatt->ag_entries = entries;
329 
330 	if (agp_alloc_dmamem(sc->as_dmat, entries * sizeof(u_int32_t),
331 	    0, &gatt->ag_dmamap, (caddr_t *)&gatt->ag_virtual,
332 	    &gatt->ag_physical, &gatt->ag_dmaseg, 1, &dummyseg) != 0)
333 		return NULL;
334 
335 	gatt->ag_size = entries * sizeof(u_int32_t);
336 	memset(gatt->ag_virtual, 0, gatt->ag_size);
337 	agp_flush_cache();
338 
339 	return gatt;
340 }
341 
342 void
343 agp_free_gatt(struct agp_softc *sc, struct agp_gatt *gatt)
344 {
345 	agp_free_dmamem(sc->as_dmat, gatt->ag_size, gatt->ag_dmamap,
346 	    (caddr_t)gatt->ag_virtual, &gatt->ag_dmaseg, 1);
347 	free(gatt, M_AGP);
348 }
349 
350 
351 int
352 agp_generic_detach(struct agp_softc *sc)
353 {
354 	lockmgr(&sc->as_lock, LK_DRAIN, 0);
355 	agp_flush_cache();
356 	return 0;
357 }
358 
359 static int
360 agpdev_match(struct pci_attach_args *pa)
361 {
362 	if (PCI_CLASS(pa->pa_class) == PCI_CLASS_DISPLAY &&
363 	    PCI_SUBCLASS(pa->pa_class) == PCI_SUBCLASS_DISPLAY_VGA)
364 		if (pci_get_capability(pa->pa_pc, pa->pa_tag, PCI_CAP_AGP,
365 		    NULL, NULL))
366 		return 1;
367 
368 	return 0;
369 }
370 
371 int
372 agp_generic_enable(struct agp_softc *sc, u_int32_t mode)
373 {
374 	struct pci_attach_args pa;
375 	pcireg_t tstatus, mstatus;
376 	pcireg_t command;
377 	int rq, sba, fw, rate, capoff;
378 
379 	if (pci_find_device(&pa, agpdev_match) == 0 ||
380 	    pci_get_capability(pa.pa_pc, pa.pa_tag, PCI_CAP_AGP,
381 	     &capoff, NULL) == 0) {
382 		printf("%s: can't find display\n", sc->as_dev.dv_xname);
383 		return ENXIO;
384 	}
385 
386 	tstatus = pci_conf_read(sc->as_pc, sc->as_tag,
387 	    sc->as_capoff + AGP_STATUS);
388 	mstatus = pci_conf_read(pa.pa_pc, pa.pa_tag,
389 	    capoff + AGP_STATUS);
390 
391 	/* Set RQ to the min of mode, tstatus and mstatus */
392 	rq = AGP_MODE_GET_RQ(mode);
393 	if (AGP_MODE_GET_RQ(tstatus) < rq)
394 		rq = AGP_MODE_GET_RQ(tstatus);
395 	if (AGP_MODE_GET_RQ(mstatus) < rq)
396 		rq = AGP_MODE_GET_RQ(mstatus);
397 
398 	/* Set SBA if all three can deal with SBA */
399 	sba = (AGP_MODE_GET_SBA(tstatus)
400 	       & AGP_MODE_GET_SBA(mstatus)
401 	       & AGP_MODE_GET_SBA(mode));
402 
403 	/* Similar for FW */
404 	fw = (AGP_MODE_GET_FW(tstatus)
405 	       & AGP_MODE_GET_FW(mstatus)
406 	       & AGP_MODE_GET_FW(mode));
407 
408 	/* Figure out the max rate */
409 	rate = (AGP_MODE_GET_RATE(tstatus)
410 		& AGP_MODE_GET_RATE(mstatus)
411 		& AGP_MODE_GET_RATE(mode));
412 	if (rate & AGP_MODE_RATE_4x)
413 		rate = AGP_MODE_RATE_4x;
414 	else if (rate & AGP_MODE_RATE_2x)
415 		rate = AGP_MODE_RATE_2x;
416 	else
417 		rate = AGP_MODE_RATE_1x;
418 
419 	/* Construct the new mode word and tell the hardware */
420 	command = AGP_MODE_SET_RQ(0, rq);
421 	command = AGP_MODE_SET_SBA(command, sba);
422 	command = AGP_MODE_SET_FW(command, fw);
423 	command = AGP_MODE_SET_RATE(command, rate);
424 	command = AGP_MODE_SET_AGP(command, 1);
425 	pci_conf_write(sc->as_pc, sc->as_tag,
426 	    sc->as_capoff + AGP_COMMAND, command);
427 	pci_conf_write(pa.pa_pc, pa.pa_tag, capoff + AGP_COMMAND, command);
428 
429 	return 0;
430 }
431 
432 struct agp_memory *
433 agp_generic_alloc_memory(struct agp_softc *sc, int type, vsize_t size)
434 {
435 	struct agp_memory *mem;
436 
437 	if ((size & (AGP_PAGE_SIZE - 1)) != 0)
438 		return 0;
439 
440 	if (sc->as_allocated + size > sc->as_maxmem)
441 		return 0;
442 
443 	if (type != 0) {
444 		printf("agp_generic_alloc_memory: unsupported type %d\n",
445 		       type);
446 		return 0;
447 	}
448 
449 	mem = malloc(sizeof *mem, M_AGP, M_WAITOK);
450 	if (mem == NULL)
451 		return NULL;
452 
453 	if (bus_dmamap_create(sc->as_dmat, size, size / PAGE_SIZE + 1,
454 			      size, 0, BUS_DMA_NOWAIT, &mem->am_dmamap) != 0) {
455 		free(mem, M_AGP);
456 		return NULL;
457 	}
458 
459 	mem->am_id = sc->as_nextid++;
460 	mem->am_size = size;
461 	mem->am_type = 0;
462 	mem->am_physical = 0;
463 	mem->am_offset = 0;
464 	mem->am_is_bound = 0;
465 	TAILQ_INSERT_TAIL(&sc->as_memory, mem, am_link);
466 	sc->as_allocated += size;
467 
468 	return mem;
469 }
470 
471 int
472 agp_generic_free_memory(struct agp_softc *sc, struct agp_memory *mem)
473 {
474 	if (mem->am_is_bound)
475 		return EBUSY;
476 
477 	sc->as_allocated -= mem->am_size;
478 	TAILQ_REMOVE(&sc->as_memory, mem, am_link);
479 	bus_dmamap_destroy(sc->as_dmat, mem->am_dmamap);
480 	free(mem, M_AGP);
481 	return 0;
482 }
483 
484 int
485 agp_generic_bind_memory(struct agp_softc *sc, struct agp_memory *mem,
486 			off_t offset)
487 {
488 	off_t i, k;
489 	bus_size_t done, j;
490 	int error;
491 	bus_dma_segment_t *segs, *seg;
492 	bus_addr_t pa;
493 	int contigpages, nseg;
494 
495 	lockmgr(&sc->as_lock, LK_EXCLUSIVE, 0);
496 
497 	if (mem->am_is_bound) {
498 		printf("%s: memory already bound\n", sc->as_dev.dv_xname);
499 		lockmgr(&sc->as_lock, LK_RELEASE, 0);
500 		return EINVAL;
501 	}
502 
503 	if (offset < 0
504 	    || (offset & (AGP_PAGE_SIZE - 1)) != 0
505 	    || offset + mem->am_size > AGP_GET_APERTURE(sc)) {
506 		printf("%s: binding memory at bad offset %#lx\n",
507 			      sc->as_dev.dv_xname, (unsigned long) offset);
508 		lockmgr(&sc->as_lock, LK_RELEASE, 0);
509 		return EINVAL;
510 	}
511 
512 	/*
513 	 * XXXfvdl
514 	 * The memory here needs to be directly accessable from the
515 	 * AGP video card, so it should be allocated using bus_dma.
516 	 * However, it need not be contiguous, since individual pages
517 	 * are translated using the GATT.
518 	 *
519 	 * Using a large chunk of contiguous memory may get in the way
520 	 * of other subsystems that may need one, so we try to be friendly
521 	 * and ask for allocation in chunks of a minimum of 8 pages
522 	 * of contiguous memory on average, falling back to 4, 2 and 1
523 	 * if really needed. Larger chunks are preferred, since allocating
524 	 * a bus_dma_segment per page would be overkill.
525 	 */
526 
527 	for (contigpages = 8; contigpages > 0; contigpages >>= 1) {
528 		nseg = (mem->am_size / (contigpages * PAGE_SIZE)) + 1;
529 		segs = malloc(nseg * sizeof *segs, M_AGP, M_WAITOK);
530 		if (segs == NULL) {
531 			lockmgr(&sc->as_lock, LK_RELEASE, 0);
532 			return ENOMEM;
533 		}
534 		if (bus_dmamem_alloc(sc->as_dmat, mem->am_size, PAGE_SIZE, 0,
535 				     segs, nseg, &mem->am_nseg,
536 				     contigpages > 1 ?
537 				     BUS_DMA_NOWAIT : BUS_DMA_WAITOK) != 0) {
538 			free(segs, M_AGP);
539 			continue;
540 		}
541 		if (bus_dmamem_map(sc->as_dmat, segs, mem->am_nseg,
542 		    mem->am_size, &mem->am_virtual, BUS_DMA_WAITOK) != 0) {
543 			bus_dmamem_free(sc->as_dmat, segs, mem->am_nseg);
544 			free(segs, M_AGP);
545 			continue;
546 		}
547 		if (bus_dmamap_load(sc->as_dmat, mem->am_dmamap,
548 		    mem->am_virtual, mem->am_size, NULL, BUS_DMA_WAITOK) != 0) {
549 			bus_dmamem_unmap(sc->as_dmat, mem->am_virtual,
550 			    mem->am_size);
551 			bus_dmamem_free(sc->as_dmat, segs, mem->am_nseg);
552 			free(segs, M_AGP);
553 			continue;
554 		}
555 		mem->am_dmaseg = segs;
556 		break;
557 	}
558 
559 	if (contigpages == 0) {
560 		lockmgr(&sc->as_lock, LK_RELEASE, 0);
561 		return ENOMEM;
562 	}
563 
564 
565 	/*
566 	 * Bind the individual pages and flush the chipset's
567 	 * TLB.
568 	 */
569 	done = 0;
570 	for (i = 0; i < mem->am_dmamap->dm_nsegs; i++) {
571 		seg = &mem->am_dmamap->dm_segs[i];
572 		/*
573 		 * Install entries in the GATT, making sure that if
574 		 * AGP_PAGE_SIZE < PAGE_SIZE and mem->am_size is not
575 		 * aligned to PAGE_SIZE, we don't modify too many GATT
576 		 * entries.
577 		 */
578 		for (j = 0; j < seg->ds_len && (done + j) < mem->am_size;
579 		     j += AGP_PAGE_SIZE) {
580 			pa = seg->ds_addr + j;
581 			AGP_DPF("binding offset %#lx to pa %#lx\n",
582 				(unsigned long)(offset + done + j),
583 				(unsigned long)pa);
584 			error = AGP_BIND_PAGE(sc, offset + done + j, pa);
585 			if (error) {
586 				/*
587 				 * Bail out. Reverse all the mappings
588 				 * and unwire the pages.
589 				 */
590 				for (k = 0; k < done + j; k += AGP_PAGE_SIZE)
591 					AGP_UNBIND_PAGE(sc, offset + k);
592 
593 				bus_dmamap_unload(sc->as_dmat, mem->am_dmamap);
594 				bus_dmamem_unmap(sc->as_dmat, mem->am_virtual,
595 						 mem->am_size);
596 				bus_dmamem_free(sc->as_dmat, mem->am_dmaseg,
597 						mem->am_nseg);
598 				free(mem->am_dmaseg, M_AGP);
599 				lockmgr(&sc->as_lock, LK_RELEASE, 0);
600 				return error;
601 			}
602 		}
603 		done += seg->ds_len;
604 	}
605 
606 	/*
607 	 * Flush the cpu cache since we are providing a new mapping
608 	 * for these pages.
609 	 */
610 	agp_flush_cache();
611 
612 	/*
613 	 * Make sure the chipset gets the new mappings.
614 	 */
615 	AGP_FLUSH_TLB(sc);
616 
617 	mem->am_offset = offset;
618 	mem->am_is_bound = 1;
619 
620 	lockmgr(&sc->as_lock, LK_RELEASE, 0);
621 
622 	return 0;
623 }
624 
625 int
626 agp_generic_unbind_memory(struct agp_softc *sc, struct agp_memory *mem)
627 {
628 	int i;
629 
630 	lockmgr(&sc->as_lock, LK_EXCLUSIVE, 0);
631 
632 	if (!mem->am_is_bound) {
633 		printf("%s: memory is not bound\n", sc->as_dev.dv_xname);
634 		lockmgr(&sc->as_lock, LK_RELEASE, 0);
635 		return EINVAL;
636 	}
637 
638 
639 	/*
640 	 * Unbind the individual pages and flush the chipset's
641 	 * TLB. Unwire the pages so they can be swapped.
642 	 */
643 	for (i = 0; i < mem->am_size; i += AGP_PAGE_SIZE)
644 		AGP_UNBIND_PAGE(sc, mem->am_offset + i);
645 
646 	agp_flush_cache();
647 	AGP_FLUSH_TLB(sc);
648 
649 	bus_dmamap_unload(sc->as_dmat, mem->am_dmamap);
650 	bus_dmamem_unmap(sc->as_dmat, mem->am_virtual, mem->am_size);
651 	bus_dmamem_free(sc->as_dmat, mem->am_dmaseg, mem->am_nseg);
652 
653 	free(mem->am_dmaseg, M_AGP);
654 
655 	mem->am_offset = 0;
656 	mem->am_is_bound = 0;
657 
658 	lockmgr(&sc->as_lock, LK_RELEASE, 0);
659 
660 	return 0;
661 }
662 
663 /* Helper functions for implementing user/kernel api */
664 
665 static int
666 agp_acquire_helper(struct agp_softc *sc, enum agp_acquire_state state)
667 {
668 	if (sc->as_state != AGP_ACQUIRE_FREE)
669 		return EBUSY;
670 	sc->as_state = state;
671 
672 	return 0;
673 }
674 
675 static int
676 agp_release_helper(struct agp_softc *sc, enum agp_acquire_state state)
677 {
678 	struct agp_memory *mem;
679 
680 	if (sc->as_state == AGP_ACQUIRE_FREE)
681 		return 0;
682 
683 	if (sc->as_state != state)
684 		return EBUSY;
685 
686 	/*
687 	 * Clear out outstanding aperture mappings.
688 	 * (should not be necessary, done by caller)
689 	 */
690 	TAILQ_FOREACH(mem, &sc->as_memory, am_link) {
691 		if (mem->am_is_bound) {
692 			printf("agp_release_helper: mem %d is bound\n",
693 			       mem->am_id);
694 			AGP_UNBIND_MEMORY(sc, mem);
695 		}
696 	}
697 
698 	sc->as_state = AGP_ACQUIRE_FREE;
699 	return 0;
700 }
701 
702 static struct agp_memory *
703 agp_find_memory(struct agp_softc *sc, int id)
704 {
705 	struct agp_memory *mem;
706 
707 	AGP_DPF("searching for memory block %d\n", id);
708 	TAILQ_FOREACH(mem, &sc->as_memory, am_link) {
709 		AGP_DPF("considering memory block %d\n", mem->am_id);
710 		if (mem->am_id == id)
711 			return mem;
712 	}
713 	return 0;
714 }
715 
716 /* Implementation of the userland ioctl api */
717 
718 static int
719 agp_info_user(struct agp_softc *sc, agp_info *info)
720 {
721 	memset(info, 0, sizeof *info);
722 	info->bridge_id = sc->as_id;
723 	if (sc->as_capoff != 0)
724 		info->agp_mode = pci_conf_read(sc->as_pc, sc->as_tag,
725 					       sc->as_capoff + AGP_STATUS);
726 	else
727 		info->agp_mode = 0; /* i810 doesn't have real AGP */
728 	info->aper_base = sc->as_apaddr;
729 	info->aper_size = AGP_GET_APERTURE(sc) >> 20;
730 	info->pg_total = info->pg_system = sc->as_maxmem >> AGP_PAGE_SHIFT;
731 	info->pg_used = sc->as_allocated >> AGP_PAGE_SHIFT;
732 
733 	return 0;
734 }
735 
736 static int
737 agp_setup_user(struct agp_softc *sc, agp_setup *setup)
738 {
739 	return AGP_ENABLE(sc, setup->agp_mode);
740 }
741 
742 static int
743 agp_allocate_user(struct agp_softc *sc, agp_allocate *alloc)
744 {
745 	struct agp_memory *mem;
746 
747 	mem = AGP_ALLOC_MEMORY(sc,
748 			       alloc->type,
749 			       alloc->pg_count << AGP_PAGE_SHIFT);
750 	if (mem) {
751 		alloc->key = mem->am_id;
752 		alloc->physical = mem->am_physical;
753 		return 0;
754 	} else {
755 		return ENOMEM;
756 	}
757 }
758 
759 static int
760 agp_deallocate_user(struct agp_softc *sc, int id)
761 {
762 	struct agp_memory *mem = agp_find_memory(sc, id);
763 
764 	if (mem) {
765 		AGP_FREE_MEMORY(sc, mem);
766 		return 0;
767 	} else {
768 		return ENOENT;
769 	}
770 }
771 
772 static int
773 agp_bind_user(struct agp_softc *sc, agp_bind *bind)
774 {
775 	struct agp_memory *mem = agp_find_memory(sc, bind->key);
776 
777 	if (!mem)
778 		return ENOENT;
779 
780 	return AGP_BIND_MEMORY(sc, mem, bind->pg_start << AGP_PAGE_SHIFT);
781 }
782 
783 static int
784 agp_unbind_user(struct agp_softc *sc, agp_unbind *unbind)
785 {
786 	struct agp_memory *mem = agp_find_memory(sc, unbind->key);
787 
788 	if (!mem)
789 		return ENOENT;
790 
791 	return AGP_UNBIND_MEMORY(sc, mem);
792 }
793 
794 int
795 agpopen(dev_t dev, int oflags, int devtype, struct proc *p)
796 {
797 	struct agp_softc *sc = device_lookup(&agp_cd, AGPUNIT(dev));
798 
799 	if (sc == NULL)
800 		return ENXIO;
801 
802 	if (sc->as_chipc == NULL)
803 		return ENXIO;
804 
805 	if (!sc->as_isopen)
806 		sc->as_isopen = 1;
807 	else
808 		return EBUSY;
809 
810 	return 0;
811 }
812 
813 int
814 agpclose(dev_t dev, int fflag, int devtype, struct proc *p)
815 {
816 	struct agp_softc *sc = device_lookup(&agp_cd, AGPUNIT(dev));
817 	struct agp_memory *mem;
818 
819 	/*
820 	 * Clear the GATT and force release on last close
821 	 */
822 	if (sc->as_state == AGP_ACQUIRE_USER) {
823 		while ((mem = TAILQ_FIRST(&sc->as_memory))) {
824 			if (mem->am_is_bound) {
825 				printf("agpclose: mem %d is bound\n",
826 				       mem->am_id);
827 				AGP_UNBIND_MEMORY(sc, mem);
828 			}
829 			/*
830 			 * XXX it is not documented, but if the protocol allows
831 			 * allocate->acquire->bind, it would be possible that
832 			 * memory ranges are allocated by the kernel here,
833 			 * which we shouldn't free. We'd have to keep track of
834 			 * the memory range's owner.
835 			 * The kernel API is unsed yet, so we get away with
836 			 * freeing all.
837 			 */
838 			AGP_FREE_MEMORY(sc, mem);
839 		}
840 		agp_release_helper(sc, AGP_ACQUIRE_USER);
841 	}
842 	sc->as_isopen = 0;
843 
844 	return 0;
845 }
846 
847 int
848 agpioctl(dev_t dev, u_long cmd, caddr_t data, int fflag, struct proc *p)
849 {
850 	struct agp_softc *sc = device_lookup(&agp_cd, AGPUNIT(dev));
851 
852 	if (sc == NULL)
853 		return ENODEV;
854 
855 	if ((fflag & FWRITE) == 0 && cmd != AGPIOC_INFO)
856 		return EPERM;
857 
858 	switch (cmd) {
859 	case AGPIOC_INFO:
860 		return agp_info_user(sc, (agp_info *) data);
861 
862 	case AGPIOC_ACQUIRE:
863 		return agp_acquire_helper(sc, AGP_ACQUIRE_USER);
864 
865 	case AGPIOC_RELEASE:
866 		return agp_release_helper(sc, AGP_ACQUIRE_USER);
867 
868 	case AGPIOC_SETUP:
869 		return agp_setup_user(sc, (agp_setup *)data);
870 
871 	case AGPIOC_ALLOCATE:
872 		return agp_allocate_user(sc, (agp_allocate *)data);
873 
874 	case AGPIOC_DEALLOCATE:
875 		return agp_deallocate_user(sc, *(int *) data);
876 
877 	case AGPIOC_BIND:
878 		return agp_bind_user(sc, (agp_bind *)data);
879 
880 	case AGPIOC_UNBIND:
881 		return agp_unbind_user(sc, (agp_unbind *)data);
882 
883 	}
884 
885 	return EINVAL;
886 }
887 
888 paddr_t
889 agpmmap(dev_t dev, off_t offset, int prot)
890 {
891 	struct agp_softc *sc = device_lookup(&agp_cd, AGPUNIT(dev));
892 
893 	if (offset > AGP_GET_APERTURE(sc))
894 		return -1;
895 
896 	return (bus_space_mmap(sc->as_apt, sc->as_apaddr, offset, prot,
897 	    BUS_SPACE_MAP_LINEAR));
898 }
899 
900 /* Implementation of the kernel api */
901 
902 void *
903 agp_find_device(int unit)
904 {
905 	return device_lookup(&agp_cd, unit);
906 }
907 
908 enum agp_acquire_state
909 agp_state(void *devcookie)
910 {
911 	struct agp_softc *sc = devcookie;
912 	return sc->as_state;
913 }
914 
915 void
916 agp_get_info(void *devcookie, struct agp_info *info)
917 {
918 	struct agp_softc *sc = devcookie;
919 
920 	info->ai_mode = pci_conf_read(sc->as_pc, sc->as_tag,
921 	    sc->as_capoff + AGP_STATUS);
922 	info->ai_aperture_base = sc->as_apaddr;
923 	info->ai_aperture_size = sc->as_apsize;	/* XXXfvdl inconsistent */
924 	info->ai_memory_allowed = sc->as_maxmem;
925 	info->ai_memory_used = sc->as_allocated;
926 }
927 
928 int
929 agp_acquire(void *dev)
930 {
931 	return agp_acquire_helper(dev, AGP_ACQUIRE_KERNEL);
932 }
933 
934 int
935 agp_release(void *dev)
936 {
937 	return agp_release_helper(dev, AGP_ACQUIRE_KERNEL);
938 }
939 
940 int
941 agp_enable(void *dev, u_int32_t mode)
942 {
943 	struct agp_softc *sc = dev;
944 
945 	return AGP_ENABLE(sc, mode);
946 }
947 
948 void *agp_alloc_memory(void *dev, int type, vsize_t bytes)
949 {
950 	struct agp_softc *sc = dev;
951 
952 	return (void *)AGP_ALLOC_MEMORY(sc, type, bytes);
953 }
954 
955 void agp_free_memory(void *dev, void *handle)
956 {
957 	struct agp_softc *sc = dev;
958 	struct agp_memory *mem = (struct agp_memory *) handle;
959 	AGP_FREE_MEMORY(sc, mem);
960 }
961 
962 int agp_bind_memory(void *dev, void *handle, off_t offset)
963 {
964 	struct agp_softc *sc = dev;
965 	struct agp_memory *mem = (struct agp_memory *) handle;
966 
967 	return AGP_BIND_MEMORY(sc, mem, offset);
968 }
969 
970 int agp_unbind_memory(void *dev, void *handle)
971 {
972 	struct agp_softc *sc = dev;
973 	struct agp_memory *mem = (struct agp_memory *) handle;
974 
975 	return AGP_UNBIND_MEMORY(sc, mem);
976 }
977 
978 void agp_memory_info(void *dev, void *handle, struct agp_memory_info *mi)
979 {
980 	struct agp_memory *mem = (struct agp_memory *) handle;
981 
982 	mi->ami_size = mem->am_size;
983 	mi->ami_physical = mem->am_physical;
984 	mi->ami_offset = mem->am_offset;
985 	mi->ami_is_bound = mem->am_is_bound;
986 }
987 
988 int
989 agp_alloc_dmamem(bus_dma_tag_t tag, size_t size, int flags,
990 		 bus_dmamap_t *mapp, caddr_t *vaddr, bus_addr_t *baddr,
991 		 bus_dma_segment_t *seg, int nseg, int *rseg)
992 
993 {
994 	int error, level = 0;
995 
996 	if ((error = bus_dmamem_alloc(tag, size, PAGE_SIZE, 0,
997 			seg, nseg, rseg, BUS_DMA_NOWAIT)) != 0)
998 		goto out;
999 	level++;
1000 
1001 	if ((error = bus_dmamem_map(tag, seg, *rseg, size, vaddr,
1002 			BUS_DMA_NOWAIT | flags)) != 0)
1003 		goto out;
1004 	level++;
1005 
1006 	if ((error = bus_dmamap_create(tag, size, *rseg, size, 0,
1007 			BUS_DMA_NOWAIT, mapp)) != 0)
1008 		goto out;
1009 	level++;
1010 
1011 	if ((error = bus_dmamap_load(tag, *mapp, *vaddr, size, NULL,
1012 			BUS_DMA_NOWAIT)) != 0)
1013 		goto out;
1014 
1015 	*baddr = (*mapp)->dm_segs[0].ds_addr;
1016 
1017 	return 0;
1018 out:
1019 	switch (level) {
1020 	case 3:
1021 		bus_dmamap_destroy(tag, *mapp);
1022 		/* FALLTHROUGH */
1023 	case 2:
1024 		bus_dmamem_unmap(tag, *vaddr, size);
1025 		/* FALLTHROUGH */
1026 	case 1:
1027 		bus_dmamem_free(tag, seg, *rseg);
1028 		break;
1029 	default:
1030 		break;
1031 	}
1032 
1033 	return error;
1034 }
1035 
1036 void
1037 agp_free_dmamem(bus_dma_tag_t tag, size_t size, bus_dmamap_t map,
1038 		caddr_t vaddr, bus_dma_segment_t *seg, int nseg)
1039 {
1040 
1041 	bus_dmamap_unload(tag, map);
1042 	bus_dmamap_destroy(tag, map);
1043 	bus_dmamem_unmap(tag, vaddr, size);
1044 	bus_dmamem_free(tag, seg, nseg);
1045 }
1046