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