xref: /freebsd/sys/dev/agp/agp.c (revision 8ddb146abcdf061be9f2c0db7e391697dafad85c)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
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 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include "opt_agp.h"
33 
34 #include <sys/param.h>
35 #include <sys/systm.h>
36 #include <sys/malloc.h>
37 #include <sys/kernel.h>
38 #include <sys/module.h>
39 #include <sys/bus.h>
40 #include <sys/conf.h>
41 #include <sys/ioccom.h>
42 #include <sys/agpio.h>
43 #include <sys/lock.h>
44 #include <sys/mutex.h>
45 #include <sys/proc.h>
46 #include <sys/rwlock.h>
47 
48 #include <dev/agp/agppriv.h>
49 #include <dev/agp/agpvar.h>
50 #include <dev/agp/agpreg.h>
51 #include <dev/pci/pcivar.h>
52 #include <dev/pci/pcireg.h>
53 
54 #include <vm/vm.h>
55 #include <vm/vm_extern.h>
56 #include <vm/vm_kern.h>
57 #include <vm/vm_param.h>
58 #include <vm/vm_object.h>
59 #include <vm/vm_page.h>
60 #include <vm/vm_pageout.h>
61 #include <vm/pmap.h>
62 
63 #include <machine/bus.h>
64 #include <machine/resource.h>
65 #include <sys/rman.h>
66 
67 MODULE_VERSION(agp, 1);
68 
69 MALLOC_DEFINE(M_AGP, "agp", "AGP data structures");
70 
71 				/* agp_drv.c */
72 static d_open_t agp_open;
73 static d_close_t agp_close;
74 static d_ioctl_t agp_ioctl;
75 static d_mmap_t agp_mmap;
76 
77 static struct cdevsw agp_cdevsw = {
78 	.d_version =	D_VERSION,
79 	.d_flags =	D_NEEDGIANT,
80 	.d_open =	agp_open,
81 	.d_close =	agp_close,
82 	.d_ioctl =	agp_ioctl,
83 	.d_mmap =	agp_mmap,
84 	.d_name =	"agp",
85 };
86 
87 static devclass_t agp_devclass;
88 
89 /* Helper functions for implementing chipset mini drivers. */
90 
91 u_int8_t
92 agp_find_caps(device_t dev)
93 {
94 	int capreg;
95 
96 	if (pci_find_cap(dev, PCIY_AGP, &capreg) != 0)
97 		capreg = 0;
98 	return (capreg);
99 }
100 
101 /*
102  * Find an AGP display device (if any).
103  */
104 static device_t
105 agp_find_display(void)
106 {
107 	devclass_t pci = devclass_find("pci");
108 	device_t bus, dev = 0;
109 	device_t *kids;
110 	int busnum, numkids, i;
111 
112 	for (busnum = 0; busnum < devclass_get_maxunit(pci); busnum++) {
113 		bus = devclass_get_device(pci, busnum);
114 		if (!bus)
115 			continue;
116 		if (device_get_children(bus, &kids, &numkids) != 0)
117 			continue;
118 		for (i = 0; i < numkids; i++) {
119 			dev = kids[i];
120 			if (pci_get_class(dev) == PCIC_DISPLAY
121 			    && pci_get_subclass(dev) == PCIS_DISPLAY_VGA)
122 				if (agp_find_caps(dev)) {
123 					free(kids, M_TEMP);
124 					return dev;
125 				}
126 
127 		}
128 		free(kids, M_TEMP);
129 	}
130 
131 	return 0;
132 }
133 
134 struct agp_gatt *
135 agp_alloc_gatt(device_t dev)
136 {
137 	u_int32_t apsize = AGP_GET_APERTURE(dev);
138 	u_int32_t entries = apsize >> AGP_PAGE_SHIFT;
139 	struct agp_gatt *gatt;
140 
141 	if (bootverbose)
142 		device_printf(dev,
143 			      "allocating GATT for aperture of size %dM\n",
144 			      apsize / (1024*1024));
145 
146 	if (entries == 0) {
147 		device_printf(dev, "bad aperture size\n");
148 		return NULL;
149 	}
150 
151 	gatt = malloc(sizeof(struct agp_gatt), M_AGP, M_NOWAIT);
152 	if (!gatt)
153 		return 0;
154 
155 	gatt->ag_entries = entries;
156 	gatt->ag_virtual = (void *)kmem_alloc_contig(entries *
157 	    sizeof(u_int32_t), M_NOWAIT | M_ZERO, 0, ~0, PAGE_SIZE, 0,
158 	    VM_MEMATTR_WRITE_COMBINING);
159 	if (!gatt->ag_virtual) {
160 		if (bootverbose)
161 			device_printf(dev, "contiguous allocation failed\n");
162 		free(gatt, M_AGP);
163 		return 0;
164 	}
165 	gatt->ag_physical = vtophys((vm_offset_t) gatt->ag_virtual);
166 
167 	return gatt;
168 }
169 
170 void
171 agp_free_gatt(struct agp_gatt *gatt)
172 {
173 	kmem_free((vm_offset_t)gatt->ag_virtual, gatt->ag_entries *
174 	    sizeof(u_int32_t));
175 	free(gatt, M_AGP);
176 }
177 
178 static u_int agp_max[][2] = {
179 	{0,	0},
180 	{32,	4},
181 	{64,	28},
182 	{128,	96},
183 	{256,	204},
184 	{512,	440},
185 	{1024,	942},
186 	{2048,	1920},
187 	{4096,	3932}
188 };
189 #define	AGP_MAX_SIZE	nitems(agp_max)
190 
191 /**
192  * Sets the PCI resource which represents the AGP aperture.
193  *
194  * If not called, the default AGP aperture resource of AGP_APBASE will
195  * be used.  Must be called before agp_generic_attach().
196  */
197 void
198 agp_set_aperture_resource(device_t dev, int rid)
199 {
200 	struct agp_softc *sc = device_get_softc(dev);
201 
202 	sc->as_aperture_rid = rid;
203 }
204 
205 int
206 agp_generic_attach(device_t dev)
207 {
208 	struct make_dev_args mdargs;
209 	struct agp_softc *sc = device_get_softc(dev);
210 	int error, i, unit;
211 	u_int memsize;
212 
213 	/*
214 	 * Find and map the aperture, RF_SHAREABLE for DRM but not RF_ACTIVE
215 	 * because the kernel doesn't need to map it.
216 	 */
217 
218 	if (sc->as_aperture_rid != -1) {
219 		if (sc->as_aperture_rid == 0)
220 			sc->as_aperture_rid = AGP_APBASE;
221 
222 		sc->as_aperture = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
223 		    &sc->as_aperture_rid, RF_SHAREABLE);
224 		if (!sc->as_aperture)
225 			return ENOMEM;
226 	}
227 
228 	/*
229 	 * Work out an upper bound for agp memory allocation. This
230 	 * uses a heurisitc table from the Linux driver.
231 	 */
232 	memsize = ptoa(realmem) >> 20;
233 	for (i = 0; i < AGP_MAX_SIZE; i++) {
234 		if (memsize <= agp_max[i][0])
235 			break;
236 	}
237 	if (i == AGP_MAX_SIZE)
238 		i = AGP_MAX_SIZE - 1;
239 	sc->as_maxmem = agp_max[i][1] << 20U;
240 
241 	/*
242 	 * The lock is used to prevent re-entry to
243 	 * agp_generic_bind_memory() since that function can sleep.
244 	 */
245 	mtx_init(&sc->as_lock, "agp lock", NULL, MTX_DEF);
246 
247 	/*
248 	 * Initialise stuff for the userland device.
249 	 */
250 	agp_devclass = devclass_find("agp");
251 	TAILQ_INIT(&sc->as_memory);
252 	sc->as_nextid = 1;
253 
254 	sc->as_devalias = NULL;
255 
256 	make_dev_args_init(&mdargs);
257 	mdargs.mda_devsw = &agp_cdevsw;
258 	mdargs.mda_uid = UID_ROOT;
259 	mdargs.mda_gid = GID_WHEEL;
260 	mdargs.mda_mode = 0600;
261 	mdargs.mda_si_drv1 = sc;
262 	mdargs.mda_si_drv2 = NULL;
263 
264 	unit = device_get_unit(dev);
265 	error = make_dev_s(&mdargs, &sc->as_devnode, "agpgart%d", unit);
266 	if (error == 0) {
267 		/*
268 		 * Create an alias for the first device that shows up.
269 		 */
270 		if (unit == 0) {
271 			(void)make_dev_alias_p(MAKEDEV_CHECKNAME,
272 			    &sc->as_devalias, sc->as_devnode, "agpgart");
273 		}
274 	} else {
275 		agp_free_res(dev);
276 	}
277 
278 	return error;
279 }
280 
281 void
282 agp_free_cdev(device_t dev)
283 {
284 	struct agp_softc *sc = device_get_softc(dev);
285 
286 	destroy_dev(sc->as_devnode);
287 	if (sc->as_devalias != NULL)
288 		destroy_dev(sc->as_devalias);
289 }
290 
291 void
292 agp_free_res(device_t dev)
293 {
294 	struct agp_softc *sc = device_get_softc(dev);
295 
296 	if (sc->as_aperture != NULL)
297 		bus_release_resource(dev, SYS_RES_MEMORY, sc->as_aperture_rid,
298 		    sc->as_aperture);
299 	mtx_destroy(&sc->as_lock);
300 }
301 
302 int
303 agp_generic_detach(device_t dev)
304 {
305 
306 	agp_free_cdev(dev);
307 	agp_free_res(dev);
308 	return 0;
309 }
310 
311 /**
312  * Default AGP aperture size detection which simply returns the size of
313  * the aperture's PCI resource.
314  */
315 u_int32_t
316 agp_generic_get_aperture(device_t dev)
317 {
318 	struct agp_softc *sc = device_get_softc(dev);
319 
320 	return rman_get_size(sc->as_aperture);
321 }
322 
323 /**
324  * Default AGP aperture size setting function, which simply doesn't allow
325  * changes to resource size.
326  */
327 int
328 agp_generic_set_aperture(device_t dev, u_int32_t aperture)
329 {
330 	u_int32_t current_aperture;
331 
332 	current_aperture = AGP_GET_APERTURE(dev);
333 	if (current_aperture != aperture)
334 		return EINVAL;
335 	else
336 		return 0;
337 }
338 
339 /*
340  * This does the enable logic for v3, with the same topology
341  * restrictions as in place for v2 -- one bus, one device on the bus.
342  */
343 static int
344 agp_v3_enable(device_t dev, device_t mdev, u_int32_t mode)
345 {
346 	u_int32_t tstatus, mstatus;
347 	u_int32_t command;
348 	int rq, sba, fw, rate, arqsz, cal;
349 
350 	tstatus = pci_read_config(dev, agp_find_caps(dev) + AGP_STATUS, 4);
351 	mstatus = pci_read_config(mdev, agp_find_caps(mdev) + AGP_STATUS, 4);
352 
353 	/* Set RQ to the min of mode, tstatus and mstatus */
354 	rq = AGP_MODE_GET_RQ(mode);
355 	if (AGP_MODE_GET_RQ(tstatus) < rq)
356 		rq = AGP_MODE_GET_RQ(tstatus);
357 	if (AGP_MODE_GET_RQ(mstatus) < rq)
358 		rq = AGP_MODE_GET_RQ(mstatus);
359 
360 	/*
361 	 * ARQSZ - Set the value to the maximum one.
362 	 * Don't allow the mode register to override values.
363 	 */
364 	arqsz = AGP_MODE_GET_ARQSZ(mode);
365 	if (AGP_MODE_GET_ARQSZ(tstatus) > rq)
366 		rq = AGP_MODE_GET_ARQSZ(tstatus);
367 	if (AGP_MODE_GET_ARQSZ(mstatus) > rq)
368 		rq = AGP_MODE_GET_ARQSZ(mstatus);
369 
370 	/* Calibration cycle - don't allow override by mode register */
371 	cal = AGP_MODE_GET_CAL(tstatus);
372 	if (AGP_MODE_GET_CAL(mstatus) < cal)
373 		cal = AGP_MODE_GET_CAL(mstatus);
374 
375 	/* SBA must be supported for AGP v3. */
376 	sba = 1;
377 
378 	/* Set FW if all three support it. */
379 	fw = (AGP_MODE_GET_FW(tstatus)
380 	       & AGP_MODE_GET_FW(mstatus)
381 	       & AGP_MODE_GET_FW(mode));
382 
383 	/* Figure out the max rate */
384 	rate = (AGP_MODE_GET_RATE(tstatus)
385 		& AGP_MODE_GET_RATE(mstatus)
386 		& AGP_MODE_GET_RATE(mode));
387 	if (rate & AGP_MODE_V3_RATE_8x)
388 		rate = AGP_MODE_V3_RATE_8x;
389 	else
390 		rate = AGP_MODE_V3_RATE_4x;
391 	if (bootverbose)
392 		device_printf(dev, "Setting AGP v3 mode %d\n", rate * 4);
393 
394 	pci_write_config(dev, agp_find_caps(dev) + AGP_COMMAND, 0, 4);
395 
396 	/* Construct the new mode word and tell the hardware */
397 	command = 0;
398 	command = AGP_MODE_SET_RQ(0, rq);
399 	command = AGP_MODE_SET_ARQSZ(command, arqsz);
400 	command = AGP_MODE_SET_CAL(command, cal);
401 	command = AGP_MODE_SET_SBA(command, sba);
402 	command = AGP_MODE_SET_FW(command, fw);
403 	command = AGP_MODE_SET_RATE(command, rate);
404 	command = AGP_MODE_SET_MODE_3(command, 1);
405 	command = AGP_MODE_SET_AGP(command, 1);
406 	pci_write_config(dev, agp_find_caps(dev) + AGP_COMMAND, command, 4);
407 	pci_write_config(mdev, agp_find_caps(mdev) + AGP_COMMAND, command, 4);
408 
409 	return 0;
410 }
411 
412 static int
413 agp_v2_enable(device_t dev, device_t mdev, u_int32_t mode)
414 {
415 	u_int32_t tstatus, mstatus;
416 	u_int32_t command;
417 	int rq, sba, fw, rate;
418 
419 	tstatus = pci_read_config(dev, agp_find_caps(dev) + AGP_STATUS, 4);
420 	mstatus = pci_read_config(mdev, agp_find_caps(mdev) + AGP_STATUS, 4);
421 
422 	/* Set RQ to the min of mode, tstatus and mstatus */
423 	rq = AGP_MODE_GET_RQ(mode);
424 	if (AGP_MODE_GET_RQ(tstatus) < rq)
425 		rq = AGP_MODE_GET_RQ(tstatus);
426 	if (AGP_MODE_GET_RQ(mstatus) < rq)
427 		rq = AGP_MODE_GET_RQ(mstatus);
428 
429 	/* Set SBA if all three can deal with SBA */
430 	sba = (AGP_MODE_GET_SBA(tstatus)
431 	       & AGP_MODE_GET_SBA(mstatus)
432 	       & AGP_MODE_GET_SBA(mode));
433 
434 	/* Similar for FW */
435 	fw = (AGP_MODE_GET_FW(tstatus)
436 	       & AGP_MODE_GET_FW(mstatus)
437 	       & AGP_MODE_GET_FW(mode));
438 
439 	/* Figure out the max rate */
440 	rate = (AGP_MODE_GET_RATE(tstatus)
441 		& AGP_MODE_GET_RATE(mstatus)
442 		& AGP_MODE_GET_RATE(mode));
443 	if (rate & AGP_MODE_V2_RATE_4x)
444 		rate = AGP_MODE_V2_RATE_4x;
445 	else if (rate & AGP_MODE_V2_RATE_2x)
446 		rate = AGP_MODE_V2_RATE_2x;
447 	else
448 		rate = AGP_MODE_V2_RATE_1x;
449 	if (bootverbose)
450 		device_printf(dev, "Setting AGP v2 mode %d\n", rate);
451 
452 	/* Construct the new mode word and tell the hardware */
453 	command = 0;
454 	command = AGP_MODE_SET_RQ(0, rq);
455 	command = AGP_MODE_SET_SBA(command, sba);
456 	command = AGP_MODE_SET_FW(command, fw);
457 	command = AGP_MODE_SET_RATE(command, rate);
458 	command = AGP_MODE_SET_AGP(command, 1);
459 	pci_write_config(dev, agp_find_caps(dev) + AGP_COMMAND, command, 4);
460 	pci_write_config(mdev, agp_find_caps(mdev) + AGP_COMMAND, command, 4);
461 
462 	return 0;
463 }
464 
465 int
466 agp_generic_enable(device_t dev, u_int32_t mode)
467 {
468 	device_t mdev = agp_find_display();
469 	u_int32_t tstatus, mstatus;
470 
471 	if (!mdev) {
472 		AGP_DPF("can't find display\n");
473 		return ENXIO;
474 	}
475 
476 	tstatus = pci_read_config(dev, agp_find_caps(dev) + AGP_STATUS, 4);
477 	mstatus = pci_read_config(mdev, agp_find_caps(mdev) + AGP_STATUS, 4);
478 
479 	/*
480 	 * Check display and bridge for AGP v3 support.  AGP v3 allows
481 	 * more variety in topology than v2, e.g. multiple AGP devices
482 	 * attached to one bridge, or multiple AGP bridges in one
483 	 * system.  This doesn't attempt to address those situations,
484 	 * but should work fine for a classic single AGP slot system
485 	 * with AGP v3.
486 	 */
487 	if (AGP_MODE_GET_MODE_3(mode) &&
488 	    AGP_MODE_GET_MODE_3(tstatus) &&
489 	    AGP_MODE_GET_MODE_3(mstatus))
490 		return (agp_v3_enable(dev, mdev, mode));
491 	else
492 		return (agp_v2_enable(dev, mdev, mode));
493 }
494 
495 struct agp_memory *
496 agp_generic_alloc_memory(device_t dev, int type, vm_size_t size)
497 {
498 	struct agp_softc *sc = device_get_softc(dev);
499 	struct agp_memory *mem;
500 
501 	if ((size & (AGP_PAGE_SIZE - 1)) != 0)
502 		return 0;
503 
504 	if (size > sc->as_maxmem - sc->as_allocated)
505 		return 0;
506 
507 	if (type != 0) {
508 		printf("agp_generic_alloc_memory: unsupported type %d\n",
509 		       type);
510 		return 0;
511 	}
512 
513 	mem = malloc(sizeof *mem, M_AGP, M_WAITOK);
514 	mem->am_id = sc->as_nextid++;
515 	mem->am_size = size;
516 	mem->am_type = 0;
517 	mem->am_obj = vm_object_allocate(OBJT_SWAP, atop(round_page(size)));
518 	mem->am_physical = 0;
519 	mem->am_offset = 0;
520 	mem->am_is_bound = 0;
521 	TAILQ_INSERT_TAIL(&sc->as_memory, mem, am_link);
522 	sc->as_allocated += size;
523 
524 	return mem;
525 }
526 
527 int
528 agp_generic_free_memory(device_t dev, struct agp_memory *mem)
529 {
530 	struct agp_softc *sc = device_get_softc(dev);
531 
532 	if (mem->am_is_bound)
533 		return EBUSY;
534 
535 	sc->as_allocated -= mem->am_size;
536 	TAILQ_REMOVE(&sc->as_memory, mem, am_link);
537 	vm_object_deallocate(mem->am_obj);
538 	free(mem, M_AGP);
539 	return 0;
540 }
541 
542 int
543 agp_generic_bind_memory(device_t dev, struct agp_memory *mem,
544 			vm_offset_t offset)
545 {
546 	struct agp_softc *sc = device_get_softc(dev);
547 	vm_offset_t i, j, k;
548 	vm_page_t m;
549 	int error;
550 
551 	/* Do some sanity checks first. */
552 	if ((offset & (AGP_PAGE_SIZE - 1)) != 0 ||
553 	    offset + mem->am_size > AGP_GET_APERTURE(dev)) {
554 		device_printf(dev, "binding memory at bad offset %#x\n",
555 		    (int)offset);
556 		return EINVAL;
557 	}
558 
559 	/*
560 	 * Allocate the pages early, before acquiring the lock,
561 	 * because vm_page_grab() may sleep and we can't hold a mutex
562 	 * while sleeping.
563 	 */
564 	VM_OBJECT_WLOCK(mem->am_obj);
565 	for (i = 0; i < mem->am_size; i += PAGE_SIZE) {
566 		/*
567 		 * Find a page from the object and wire it
568 		 * down. This page will be mapped using one or more
569 		 * entries in the GATT (assuming that PAGE_SIZE >=
570 		 * AGP_PAGE_SIZE. If this is the first call to bind,
571 		 * the pages will be allocated and zeroed.
572 		 */
573 		m = vm_page_grab(mem->am_obj, OFF_TO_IDX(i),
574 		    VM_ALLOC_WIRED | VM_ALLOC_ZERO);
575 		AGP_DPF("found page pa=%#jx\n", (uintmax_t)VM_PAGE_TO_PHYS(m));
576 	}
577 	VM_OBJECT_WUNLOCK(mem->am_obj);
578 
579 	mtx_lock(&sc->as_lock);
580 
581 	if (mem->am_is_bound) {
582 		device_printf(dev, "memory already bound\n");
583 		error = EINVAL;
584 		VM_OBJECT_WLOCK(mem->am_obj);
585 		i = 0;
586 		goto bad;
587 	}
588 
589 	/*
590 	 * Bind the individual pages and flush the chipset's
591 	 * TLB.
592 	 */
593 	VM_OBJECT_WLOCK(mem->am_obj);
594 	for (i = 0; i < mem->am_size; i += PAGE_SIZE) {
595 		m = vm_page_lookup(mem->am_obj, OFF_TO_IDX(i));
596 
597 		/*
598 		 * Install entries in the GATT, making sure that if
599 		 * AGP_PAGE_SIZE < PAGE_SIZE and mem->am_size is not
600 		 * aligned to PAGE_SIZE, we don't modify too many GATT
601 		 * entries.
602 		 */
603 		for (j = 0; j < PAGE_SIZE && i + j < mem->am_size;
604 		     j += AGP_PAGE_SIZE) {
605 			vm_offset_t pa = VM_PAGE_TO_PHYS(m) + j;
606 			AGP_DPF("binding offset %#jx to pa %#jx\n",
607 				(uintmax_t)offset + i + j, (uintmax_t)pa);
608 			error = AGP_BIND_PAGE(dev, offset + i + j, pa);
609 			if (error) {
610 				/*
611 				 * Bail out. Reverse all the mappings
612 				 * and unwire the pages.
613 				 */
614 				for (k = 0; k < i + j; k += AGP_PAGE_SIZE)
615 					AGP_UNBIND_PAGE(dev, offset + k);
616 				goto bad;
617 			}
618 		}
619 		vm_page_xunbusy(m);
620 	}
621 	VM_OBJECT_WUNLOCK(mem->am_obj);
622 
623 	/*
624 	 * Make sure the chipset gets the new mappings.
625 	 */
626 	AGP_FLUSH_TLB(dev);
627 
628 	mem->am_offset = offset;
629 	mem->am_is_bound = 1;
630 
631 	mtx_unlock(&sc->as_lock);
632 
633 	return 0;
634 bad:
635 	mtx_unlock(&sc->as_lock);
636 	VM_OBJECT_ASSERT_WLOCKED(mem->am_obj);
637 	for (k = 0; k < mem->am_size; k += PAGE_SIZE) {
638 		m = vm_page_lookup(mem->am_obj, OFF_TO_IDX(k));
639 		if (k >= i)
640 			vm_page_xunbusy(m);
641 		vm_page_unwire(m, PQ_INACTIVE);
642 	}
643 	VM_OBJECT_WUNLOCK(mem->am_obj);
644 
645 	return error;
646 }
647 
648 int
649 agp_generic_unbind_memory(device_t dev, struct agp_memory *mem)
650 {
651 	struct agp_softc *sc = device_get_softc(dev);
652 	vm_page_t m;
653 	int i;
654 
655 	mtx_lock(&sc->as_lock);
656 
657 	if (!mem->am_is_bound) {
658 		device_printf(dev, "memory is not bound\n");
659 		mtx_unlock(&sc->as_lock);
660 		return EINVAL;
661 	}
662 
663 	/*
664 	 * Unbind the individual pages and flush the chipset's
665 	 * TLB. Unwire the pages so they can be swapped.
666 	 */
667 	for (i = 0; i < mem->am_size; i += AGP_PAGE_SIZE)
668 		AGP_UNBIND_PAGE(dev, mem->am_offset + i);
669 
670 	AGP_FLUSH_TLB(dev);
671 
672 	VM_OBJECT_WLOCK(mem->am_obj);
673 	for (i = 0; i < mem->am_size; i += PAGE_SIZE) {
674 		m = vm_page_lookup(mem->am_obj, atop(i));
675 		vm_page_unwire(m, PQ_INACTIVE);
676 	}
677 	VM_OBJECT_WUNLOCK(mem->am_obj);
678 
679 	mem->am_offset = 0;
680 	mem->am_is_bound = 0;
681 
682 	mtx_unlock(&sc->as_lock);
683 
684 	return 0;
685 }
686 
687 /* Helper functions for implementing user/kernel api */
688 
689 static int
690 agp_acquire_helper(device_t dev, enum agp_acquire_state state)
691 {
692 	struct agp_softc *sc = device_get_softc(dev);
693 
694 	if (sc->as_state != AGP_ACQUIRE_FREE)
695 		return EBUSY;
696 	sc->as_state = state;
697 
698 	return 0;
699 }
700 
701 static int
702 agp_release_helper(device_t dev, enum agp_acquire_state state)
703 {
704 	struct agp_softc *sc = device_get_softc(dev);
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(device_t dev, int id)
718 {
719 	struct agp_softc *sc = device_get_softc(dev);
720 	struct agp_memory *mem;
721 
722 	AGP_DPF("searching for memory block %d\n", id);
723 	TAILQ_FOREACH(mem, &sc->as_memory, am_link) {
724 		AGP_DPF("considering memory block %d\n", mem->am_id);
725 		if (mem->am_id == id)
726 			return mem;
727 	}
728 	return 0;
729 }
730 
731 /* Implementation of the userland ioctl api */
732 
733 static int
734 agp_info_user(device_t dev, agp_info *info)
735 {
736 	struct agp_softc *sc = device_get_softc(dev);
737 
738 	bzero(info, sizeof *info);
739 	info->bridge_id = pci_get_devid(dev);
740 	info->agp_mode =
741 	    pci_read_config(dev, agp_find_caps(dev) + AGP_STATUS, 4);
742 	if (sc->as_aperture)
743 		info->aper_base = rman_get_start(sc->as_aperture);
744 	else
745 		info->aper_base = 0;
746 	info->aper_size = AGP_GET_APERTURE(dev) >> 20;
747 	info->pg_total = info->pg_system = sc->as_maxmem >> AGP_PAGE_SHIFT;
748 	info->pg_used = sc->as_allocated >> AGP_PAGE_SHIFT;
749 
750 	return 0;
751 }
752 
753 static int
754 agp_setup_user(device_t dev, agp_setup *setup)
755 {
756 	return AGP_ENABLE(dev, setup->agp_mode);
757 }
758 
759 static int
760 agp_allocate_user(device_t dev, agp_allocate *alloc)
761 {
762 	struct agp_memory *mem;
763 
764 	mem = AGP_ALLOC_MEMORY(dev,
765 			       alloc->type,
766 			       alloc->pg_count << AGP_PAGE_SHIFT);
767 	if (mem) {
768 		alloc->key = mem->am_id;
769 		alloc->physical = mem->am_physical;
770 		return 0;
771 	} else {
772 		return ENOMEM;
773 	}
774 }
775 
776 static int
777 agp_deallocate_user(device_t dev, int id)
778 {
779 	struct agp_memory *mem = agp_find_memory(dev, id);
780 
781 	if (mem) {
782 		AGP_FREE_MEMORY(dev, mem);
783 		return 0;
784 	} else {
785 		return ENOENT;
786 	}
787 }
788 
789 static int
790 agp_bind_user(device_t dev, agp_bind *bind)
791 {
792 	struct agp_memory *mem = agp_find_memory(dev, bind->key);
793 
794 	if (!mem)
795 		return ENOENT;
796 
797 	return AGP_BIND_MEMORY(dev, mem, bind->pg_start << AGP_PAGE_SHIFT);
798 }
799 
800 static int
801 agp_unbind_user(device_t dev, agp_unbind *unbind)
802 {
803 	struct agp_memory *mem = agp_find_memory(dev, unbind->key);
804 
805 	if (!mem)
806 		return ENOENT;
807 
808 	return AGP_UNBIND_MEMORY(dev, mem);
809 }
810 
811 static int
812 agp_chipset_flush(device_t dev)
813 {
814 
815 	return (AGP_CHIPSET_FLUSH(dev));
816 }
817 
818 static int
819 agp_open(struct cdev *kdev, int oflags, int devtype, struct thread *td)
820 {
821 	device_t dev = kdev->si_drv1;
822 	struct agp_softc *sc = device_get_softc(dev);
823 
824 	if (!sc->as_isopen) {
825 		sc->as_isopen = 1;
826 		device_busy(dev);
827 	}
828 
829 	return 0;
830 }
831 
832 static int
833 agp_close(struct cdev *kdev, int fflag, int devtype, struct thread *td)
834 {
835 	device_t dev = kdev->si_drv1;
836 	struct agp_softc *sc = device_get_softc(dev);
837 	struct agp_memory *mem;
838 
839 	/*
840 	 * Clear the GATT and force release on last close
841 	 */
842 	while ((mem = TAILQ_FIRST(&sc->as_memory)) != NULL) {
843 		if (mem->am_is_bound)
844 			AGP_UNBIND_MEMORY(dev, mem);
845 		AGP_FREE_MEMORY(dev, mem);
846 	}
847 	if (sc->as_state == AGP_ACQUIRE_USER)
848 		agp_release_helper(dev, AGP_ACQUIRE_USER);
849 	sc->as_isopen = 0;
850 	device_unbusy(dev);
851 
852 	return 0;
853 }
854 
855 static int
856 agp_ioctl(struct cdev *kdev, u_long cmd, caddr_t data, int fflag, struct thread *td)
857 {
858 	device_t dev = kdev->si_drv1;
859 
860 	switch (cmd) {
861 	case AGPIOC_INFO:
862 		return agp_info_user(dev, (agp_info *) data);
863 
864 	case AGPIOC_ACQUIRE:
865 		return agp_acquire_helper(dev, AGP_ACQUIRE_USER);
866 
867 	case AGPIOC_RELEASE:
868 		return agp_release_helper(dev, AGP_ACQUIRE_USER);
869 
870 	case AGPIOC_SETUP:
871 		return agp_setup_user(dev, (agp_setup *)data);
872 
873 	case AGPIOC_ALLOCATE:
874 		return agp_allocate_user(dev, (agp_allocate *)data);
875 
876 	case AGPIOC_DEALLOCATE:
877 		return agp_deallocate_user(dev, *(int *) data);
878 
879 	case AGPIOC_BIND:
880 		return agp_bind_user(dev, (agp_bind *)data);
881 
882 	case AGPIOC_UNBIND:
883 		return agp_unbind_user(dev, (agp_unbind *)data);
884 
885 	case AGPIOC_CHIPSET_FLUSH:
886 		return agp_chipset_flush(dev);
887 	}
888 
889 	return EINVAL;
890 }
891 
892 static int
893 agp_mmap(struct cdev *kdev, vm_ooffset_t offset, vm_paddr_t *paddr,
894     int prot, vm_memattr_t *memattr)
895 {
896 	device_t dev = kdev->si_drv1;
897 	struct agp_softc *sc = device_get_softc(dev);
898 
899 	if (offset > AGP_GET_APERTURE(dev))
900 		return -1;
901 	if (sc->as_aperture == NULL)
902 		return -1;
903 	*paddr = rman_get_start(sc->as_aperture) + offset;
904 	return 0;
905 }
906 
907 /* Implementation of the kernel api */
908 
909 device_t
910 agp_find_device(void)
911 {
912 	device_t *children, child;
913 	int i, count;
914 
915 	if (!agp_devclass)
916 		return NULL;
917 	if (devclass_get_devices(agp_devclass, &children, &count) != 0)
918 		return NULL;
919 	child = NULL;
920 	for (i = 0; i < count; i++) {
921 		if (device_is_attached(children[i])) {
922 			child = children[i];
923 			break;
924 		}
925 	}
926 	free(children, M_TEMP);
927 	return child;
928 }
929 
930 enum agp_acquire_state
931 agp_state(device_t dev)
932 {
933 	struct agp_softc *sc = device_get_softc(dev);
934 	return sc->as_state;
935 }
936 
937 void
938 agp_get_info(device_t dev, struct agp_info *info)
939 {
940 	struct agp_softc *sc = device_get_softc(dev);
941 
942 	info->ai_mode =
943 		pci_read_config(dev, agp_find_caps(dev) + AGP_STATUS, 4);
944 	if (sc->as_aperture != NULL)
945 		info->ai_aperture_base = rman_get_start(sc->as_aperture);
946 	else
947 		info->ai_aperture_base = 0;
948 	info->ai_aperture_size = AGP_GET_APERTURE(dev);
949 	info->ai_memory_allowed = sc->as_maxmem;
950 	info->ai_memory_used = sc->as_allocated;
951 }
952 
953 int
954 agp_acquire(device_t dev)
955 {
956 	return agp_acquire_helper(dev, AGP_ACQUIRE_KERNEL);
957 }
958 
959 int
960 agp_release(device_t dev)
961 {
962 	return agp_release_helper(dev, AGP_ACQUIRE_KERNEL);
963 }
964 
965 int
966 agp_enable(device_t dev, u_int32_t mode)
967 {
968 	return AGP_ENABLE(dev, mode);
969 }
970 
971 void *agp_alloc_memory(device_t dev, int type, vm_size_t bytes)
972 {
973 	return  (void *) AGP_ALLOC_MEMORY(dev, type, bytes);
974 }
975 
976 void agp_free_memory(device_t dev, void *handle)
977 {
978 	struct agp_memory *mem = (struct agp_memory *) handle;
979 	AGP_FREE_MEMORY(dev, mem);
980 }
981 
982 int agp_bind_memory(device_t dev, void *handle, vm_offset_t offset)
983 {
984 	struct agp_memory *mem = (struct agp_memory *) handle;
985 	return AGP_BIND_MEMORY(dev, mem, offset);
986 }
987 
988 int agp_unbind_memory(device_t dev, void *handle)
989 {
990 	struct agp_memory *mem = (struct agp_memory *) handle;
991 	return AGP_UNBIND_MEMORY(dev, mem);
992 }
993 
994 void agp_memory_info(device_t dev, void *handle, struct
995 		     agp_memory_info *mi)
996 {
997 	struct agp_memory *mem = (struct agp_memory *) handle;
998 
999 	mi->ami_size = mem->am_size;
1000 	mi->ami_physical = mem->am_physical;
1001 	mi->ami_offset = mem->am_offset;
1002 	mi->ami_is_bound = mem->am_is_bound;
1003 }
1004 
1005 int
1006 agp_bind_pages(device_t dev, vm_page_t *pages, vm_size_t size,
1007     vm_offset_t offset)
1008 {
1009 	struct agp_softc *sc;
1010 	vm_offset_t i, j, k, pa;
1011 	vm_page_t m;
1012 	int error;
1013 
1014 	if ((size & (AGP_PAGE_SIZE - 1)) != 0 ||
1015 	    (offset & (AGP_PAGE_SIZE - 1)) != 0)
1016 		return (EINVAL);
1017 
1018 	sc = device_get_softc(dev);
1019 
1020 	mtx_lock(&sc->as_lock);
1021 	for (i = 0; i < size; i += PAGE_SIZE) {
1022 		m = pages[OFF_TO_IDX(i)];
1023 		KASSERT(vm_page_wired(m),
1024 		    ("agp_bind_pages: page %p hasn't been wired", m));
1025 
1026 		/*
1027 		 * Install entries in the GATT, making sure that if
1028 		 * AGP_PAGE_SIZE < PAGE_SIZE and size is not
1029 		 * aligned to PAGE_SIZE, we don't modify too many GATT
1030 		 * entries.
1031 		 */
1032 		for (j = 0; j < PAGE_SIZE && i + j < size; j += AGP_PAGE_SIZE) {
1033 			pa = VM_PAGE_TO_PHYS(m) + j;
1034 			AGP_DPF("binding offset %#jx to pa %#jx\n",
1035 				(uintmax_t)offset + i + j, (uintmax_t)pa);
1036 			error = AGP_BIND_PAGE(dev, offset + i + j, pa);
1037 			if (error) {
1038 				/*
1039 				 * Bail out. Reverse all the mappings.
1040 				 */
1041 				for (k = 0; k < i + j; k += AGP_PAGE_SIZE)
1042 					AGP_UNBIND_PAGE(dev, offset + k);
1043 
1044 				mtx_unlock(&sc->as_lock);
1045 				return (error);
1046 			}
1047 		}
1048 	}
1049 
1050 	AGP_FLUSH_TLB(dev);
1051 
1052 	mtx_unlock(&sc->as_lock);
1053 	return (0);
1054 }
1055 
1056 int
1057 agp_unbind_pages(device_t dev, vm_size_t size, vm_offset_t offset)
1058 {
1059 	struct agp_softc *sc;
1060 	vm_offset_t i;
1061 
1062 	if ((size & (AGP_PAGE_SIZE - 1)) != 0 ||
1063 	    (offset & (AGP_PAGE_SIZE - 1)) != 0)
1064 		return (EINVAL);
1065 
1066 	sc = device_get_softc(dev);
1067 
1068 	mtx_lock(&sc->as_lock);
1069 	for (i = 0; i < size; i += AGP_PAGE_SIZE)
1070 		AGP_UNBIND_PAGE(dev, offset + i);
1071 
1072 	AGP_FLUSH_TLB(dev);
1073 
1074 	mtx_unlock(&sc->as_lock);
1075 	return (0);
1076 }
1077