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