Merge branch 'vendor/LIBARCHIVE' (early part)
[dragonfly.git] / sys / dev / agp / agp.c
1 /*-
2  * Copyright (c) 2000 Doug Rabson
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  *      $FreeBSD: src/sys/dev/agp/agp.c,v 1.58 2007/11/12 21:51:36 jhb Exp $
27  *      $DragonFly: src/sys/dev/agp/agp.c,v 1.30 2008/01/07 01:34:58 corecode Exp $
28  */
29
30 #include "opt_bus.h"
31 #include "opt_pci.h"
32
33 #include <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/device.h>
36 #include <sys/conf.h>
37 #include <sys/malloc.h>
38 #include <sys/kernel.h>
39 #include <sys/bus.h>
40 #include <sys/agpio.h>
41 #include <sys/lock.h>
42 #include <sys/proc.h>
43 #include <sys/rman.h>
44
45 #include <bus/pci/pcivar.h>
46 #include <bus/pci/pcireg.h>
47 #include "agppriv.h"
48 #include "agpvar.h"
49 #include "agpreg.h"
50
51 #include <vm/vm.h>
52 #include <vm/vm_object.h>
53 #include <vm/vm_page.h>
54 #include <vm/vm_pageout.h>
55 #include <vm/pmap.h>
56
57 #include <machine/md_var.h>
58
59 MODULE_VERSION(agp, 1);
60
61 MALLOC_DEFINE(M_AGP, "agp", "AGP data structures");
62
63 #define CDEV_MAJOR      148
64                                 /* agp_drv.c */
65 static d_open_t agp_open;
66 static d_close_t agp_close;
67 static d_ioctl_t agp_ioctl;
68 static d_mmap_t agp_mmap;
69
70 static struct dev_ops agp_ops = {
71         { "agp", CDEV_MAJOR, D_TTY },
72         .d_open =       agp_open,
73         .d_close =      agp_close,
74         .d_ioctl =      agp_ioctl,
75         .d_mmap =       agp_mmap,
76 };
77
78 static devclass_t agp_devclass;
79 #define KDEV2DEV(kdev)  devclass_get_device(agp_devclass, minor(kdev))
80
81 /* Helper functions for implementing chipset mini drivers. */
82
83 void
84 agp_flush_cache(void)
85 {
86 #if defined(__i386__) || defined(__amd64__)
87         wbinvd();
88 #endif
89 }
90
91 u_int8_t
92 agp_find_caps(device_t dev)
93 {
94         u_int32_t status;
95         u_int8_t ptr, next;
96
97         /*
98          * Check the CAP_LIST bit of the PCI status register first.
99          */
100         status = pci_read_config(dev, PCIR_STATUS, 2);
101         if (!(status & 0x10))
102                 return 0;
103
104         /*
105          * Traverse the capabilities list.
106          */
107         for (ptr = pci_read_config(dev, AGP_CAPPTR, 1);
108              ptr != 0;
109              ptr = next) {
110                 u_int32_t capid = pci_read_config(dev, ptr, 4);
111                 next = AGP_CAPID_GET_NEXT_PTR(capid);
112
113                 /*
114                  * If this capability entry ID is 2, then we are done.
115                  */
116                 if (AGP_CAPID_GET_CAP_ID(capid) == 2)
117                         return ptr;
118         }
119
120         return 0;
121 }
122
123 /*
124  * Find an AGP display device (if any).
125  */
126 static device_t
127 agp_find_display(void)
128 {
129         devclass_t pci = devclass_find("pci");
130         device_t bus, dev = 0;
131         device_t *kids;
132         int busnum, numkids, i;
133
134         for (busnum = 0; busnum < devclass_get_maxunit(pci); busnum++) {
135                 bus = devclass_get_device(pci, busnum);
136                 if (!bus)
137                         continue;
138                 device_get_children(bus, &kids, &numkids);
139                 for (i = 0; i < numkids; i++) {
140                         dev = kids[i];
141                         if (pci_get_class(dev) == PCIC_DISPLAY
142                             && pci_get_subclass(dev) == PCIS_DISPLAY_VGA)
143                                 if (agp_find_caps(dev)) {
144                                         kfree(kids, M_TEMP);
145                                         return dev;
146                                 }
147                                         
148                 }
149                 kfree(kids, M_TEMP);
150         }
151
152         return 0;
153 }
154
155 struct agp_gatt *
156 agp_alloc_gatt(device_t dev)
157 {
158         u_int32_t apsize = AGP_GET_APERTURE(dev);
159         u_int32_t entries = apsize >> AGP_PAGE_SHIFT;
160         struct agp_gatt *gatt;
161
162         if (bootverbose)
163                 device_printf(dev,
164                               "allocating GATT for aperture of size %dM\n",
165                               apsize / (1024*1024));
166
167         if (entries == 0) {
168                 device_printf(dev, "bad aperture size\n");
169                 return NULL;
170         }
171
172         gatt = kmalloc(sizeof(struct agp_gatt), M_AGP, M_INTWAIT);
173         gatt->ag_entries = entries;
174         gatt->ag_virtual = contigmalloc(entries * sizeof(u_int32_t), M_AGP,
175                                         M_WAITOK|M_ZERO, 0, ~0, PAGE_SIZE, 0);
176         if (!gatt->ag_virtual) {
177                 if (bootverbose)
178                         device_printf(dev, "contiguous allocation failed\n");
179                 kfree(gatt, M_AGP);
180                 return 0;
181         }
182         gatt->ag_physical = vtophys((vm_offset_t) gatt->ag_virtual);
183         agp_flush_cache();
184
185         return gatt;
186 }
187
188 void
189 agp_free_gatt(struct agp_gatt *gatt)
190 {
191         contigfree(gatt->ag_virtual,
192                    gatt->ag_entries * sizeof(u_int32_t), M_AGP);
193         kfree(gatt, M_AGP);
194 }
195
196 static u_int agp_max[][2] = {
197         {0,     0},
198         {32,    4},
199         {64,    28},
200         {128,   96},
201         {256,   204},
202         {512,   440},
203         {1024,  942},
204         {2048,  1920},
205         {4096,  3932}
206 };
207 #define agp_max_size    (sizeof(agp_max) / sizeof(agp_max[0]))
208
209 /**
210  * Sets the PCI resource which represents the AGP aperture.
211  *
212  * If not called, the default AGP aperture resource of AGP_APBASE will
213  * be used.  Must be called before agp_generic_attach().
214  */
215 void
216 agp_set_aperture_resource(device_t dev, int rid)
217 {
218         struct agp_softc *sc = device_get_softc(dev);
219
220         sc->as_aperture_rid = rid;
221 }
222
223 int
224 agp_generic_attach(device_t dev)
225 {
226         struct agp_softc *sc = device_get_softc(dev);
227         int i;
228         u_int memsize;
229
230         /*
231          * Find and map the aperture, RF_SHAREABLE for DRM but not RF_ACTIVE
232          * because the kernel doesn't need to map it.
233          */
234         if (sc->as_aperture_rid == 0)
235                 sc->as_aperture_rid = AGP_APBASE;
236
237         sc->as_aperture = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
238             &sc->as_aperture_rid, RF_SHAREABLE);
239         if (!sc->as_aperture)
240                 return ENOMEM;
241
242         /*
243          * Work out an upper bound for agp memory allocation. This
244          * uses a heurisitc table from the Linux driver.
245          */
246         memsize = ptoa(Maxmem) >> 20;
247         for (i = 0; i < agp_max_size; i++) {
248                 if (memsize <= agp_max[i][0])
249                         break;
250         }
251         if (i == agp_max_size) i = agp_max_size - 1;
252         sc->as_maxmem = agp_max[i][1] << 20U;
253
254         /*
255          * The lock is used to prevent re-entry to
256          * agp_generic_bind_memory() since that function can sleep.
257          */
258         lockinit(&sc->as_lock, "agplk", 0, 0);
259
260         /*
261          * Initialise stuff for the userland device.
262          */
263         agp_devclass = devclass_find("agp");
264         TAILQ_INIT(&sc->as_memory);
265         sc->as_nextid = 1;
266
267         dev_ops_add(&agp_ops, -1, device_get_unit(dev));
268         make_dev(&agp_ops, device_get_unit(dev), UID_ROOT, GID_WHEEL,
269                   0600, "agpgart");
270
271         return 0;
272 }
273
274 void
275 agp_free_cdev(device_t dev)
276 {
277         dev_ops_remove(&agp_ops, -1, device_get_unit(dev));
278 }
279
280 void
281 agp_free_res(device_t dev)
282 {
283         struct agp_softc *sc = device_get_softc(dev);
284
285         bus_release_resource(dev, SYS_RES_MEMORY, sc->as_aperture_rid,
286                              sc->as_aperture);
287         agp_flush_cache();
288 }
289
290 int
291 agp_generic_detach(device_t dev)
292 {
293         agp_free_cdev(dev);
294         agp_free_res(dev);
295         return 0;
296 }
297
298 /**
299  * Default AGP aperture size detection which simply returns the size of
300  * the aperture's PCI resource.
301  */
302 int
303 agp_generic_get_aperture(device_t dev)
304 {
305         struct agp_softc *sc = device_get_softc(dev);
306
307         return rman_get_size(sc->as_aperture);
308 }
309
310 /**
311  * Default AGP aperture size setting function, which simply doesn't allow
312  * changes to resource size.
313  */
314 int
315 agp_generic_set_aperture(device_t dev, u_int32_t aperture)
316 {
317         u_int32_t current_aperture;
318
319         current_aperture = AGP_GET_APERTURE(dev);
320         if (current_aperture != aperture)
321                 return EINVAL;
322         else
323                 return 0;
324 }
325
326 /*
327  * This does the enable logic for v3, with the same topology
328  * restrictions as in place for v2 -- one bus, one device on the bus.
329  */
330 static int
331 agp_v3_enable(device_t dev, device_t mdev, u_int32_t mode)
332 {
333         u_int32_t tstatus, mstatus;
334         u_int32_t command;
335         int rq, sba, fw, rate, arqsz, cal;
336
337         tstatus = pci_read_config(dev, agp_find_caps(dev) + AGP_STATUS, 4);
338         mstatus = pci_read_config(mdev, agp_find_caps(mdev) + AGP_STATUS, 4);
339
340         /* Set RQ to the min of mode, tstatus and mstatus */
341         rq = AGP_MODE_GET_RQ(mode);
342         if (AGP_MODE_GET_RQ(tstatus) < rq)
343                 rq = AGP_MODE_GET_RQ(tstatus);
344         if (AGP_MODE_GET_RQ(mstatus) < rq)
345                 rq = AGP_MODE_GET_RQ(mstatus);
346
347         /*
348          * ARQSZ - Set the value to the maximum one.
349          * Don't allow the mode register to override values.
350          */
351         arqsz = AGP_MODE_GET_ARQSZ(mode);
352         if (AGP_MODE_GET_ARQSZ(tstatus) > rq)
353                 rq = AGP_MODE_GET_ARQSZ(tstatus);
354         if (AGP_MODE_GET_ARQSZ(mstatus) > rq)
355                 rq = AGP_MODE_GET_ARQSZ(mstatus);
356
357         /* Calibration cycle - don't allow override by mode register */
358         cal = AGP_MODE_GET_CAL(tstatus);
359         if (AGP_MODE_GET_CAL(mstatus) < cal)
360                 cal = AGP_MODE_GET_CAL(mstatus);
361
362         /* SBA must be supported for AGP v3. */
363         sba = 1;
364
365         /* Set FW if all three support it. */
366         fw = (AGP_MODE_GET_FW(tstatus)
367                & AGP_MODE_GET_FW(mstatus)
368                & AGP_MODE_GET_FW(mode));
369         
370         /* Figure out the max rate */
371         rate = (AGP_MODE_GET_RATE(tstatus)
372                 & AGP_MODE_GET_RATE(mstatus)
373                 & AGP_MODE_GET_RATE(mode));
374         if (rate & AGP_MODE_V3_RATE_8x)
375                 rate = AGP_MODE_V3_RATE_8x;
376         else
377                 rate = AGP_MODE_V3_RATE_4x;
378         if (bootverbose)
379                 device_printf(dev, "Setting AGP v3 mode %d\n", rate * 4);
380
381         pci_write_config(dev, agp_find_caps(dev) + AGP_COMMAND, 0, 4);
382
383         /* Construct the new mode word and tell the hardware */
384         command = 0;
385         command = AGP_MODE_SET_RQ(0, rq);
386         command = AGP_MODE_SET_ARQSZ(command, arqsz);
387         command = AGP_MODE_SET_CAL(command, cal);
388         command = AGP_MODE_SET_SBA(command, sba);
389         command = AGP_MODE_SET_FW(command, fw);
390         command = AGP_MODE_SET_RATE(command, rate);
391         command = AGP_MODE_SET_MODE_3(command, 1);
392         command = AGP_MODE_SET_AGP(command, 1);
393         pci_write_config(dev, agp_find_caps(dev) + AGP_COMMAND, command, 4);
394         pci_write_config(mdev, agp_find_caps(mdev) + AGP_COMMAND, command, 4);
395
396         return 0;
397 }
398
399 static int
400 agp_v2_enable(device_t dev, device_t mdev, u_int32_t mode)
401 {
402         u_int32_t tstatus, mstatus;
403         u_int32_t command;
404         int rq, sba, fw, rate;
405
406         tstatus = pci_read_config(dev, agp_find_caps(dev) + AGP_STATUS, 4);
407         mstatus = pci_read_config(mdev, agp_find_caps(mdev) + AGP_STATUS, 4);
408
409         /* Set RQ to the min of mode, tstatus and mstatus */
410         rq = AGP_MODE_GET_RQ(mode);
411         if (AGP_MODE_GET_RQ(tstatus) < rq)
412                 rq = AGP_MODE_GET_RQ(tstatus);
413         if (AGP_MODE_GET_RQ(mstatus) < rq)
414                 rq = AGP_MODE_GET_RQ(mstatus);
415
416         /* Set SBA if all three can deal with SBA */
417         sba = (AGP_MODE_GET_SBA(tstatus)
418                & AGP_MODE_GET_SBA(mstatus)
419                & AGP_MODE_GET_SBA(mode));
420
421         /* Similar for FW */
422         fw = (AGP_MODE_GET_FW(tstatus)
423                & AGP_MODE_GET_FW(mstatus)
424                & AGP_MODE_GET_FW(mode));
425
426         /* Figure out the max rate */
427         rate = (AGP_MODE_GET_RATE(tstatus)
428                 & AGP_MODE_GET_RATE(mstatus)
429                 & AGP_MODE_GET_RATE(mode));
430         if (rate & AGP_MODE_V2_RATE_4x)
431                 rate = AGP_MODE_V2_RATE_4x;
432         else if (rate & AGP_MODE_V2_RATE_2x)
433                 rate = AGP_MODE_V2_RATE_2x;
434         else
435                 rate = AGP_MODE_V2_RATE_1x;
436         if (bootverbose)
437                 device_printf(dev, "Setting AGP v2 mode %d\n", rate);
438
439         /* Construct the new mode word and tell the hardware */
440         command = 0;
441         command = AGP_MODE_SET_RQ(0, rq);
442         command = AGP_MODE_SET_SBA(command, sba);
443         command = AGP_MODE_SET_FW(command, fw);
444         command = AGP_MODE_SET_RATE(command, rate);
445         command = AGP_MODE_SET_AGP(command, 1);
446         pci_write_config(dev, agp_find_caps(dev) + AGP_COMMAND, command, 4);
447         pci_write_config(mdev, agp_find_caps(mdev) + AGP_COMMAND, command, 4);
448
449         return 0;
450 }
451
452 int
453 agp_generic_enable(device_t dev, u_int32_t mode)
454 {
455         device_t mdev = agp_find_display();
456         u_int32_t tstatus, mstatus;
457
458         if (!mdev) {
459                 AGP_DPF("can't find display\n");
460                 return ENXIO;
461         }
462
463         tstatus = pci_read_config(dev, agp_find_caps(dev) + AGP_STATUS, 4);
464         mstatus = pci_read_config(mdev, agp_find_caps(mdev) + AGP_STATUS, 4);
465
466         /*
467          * Check display and bridge for AGP v3 support.  AGP v3 allows
468          * more variety in topology than v2, e.g. multiple AGP devices
469          * attached to one bridge, or multiple AGP bridges in one
470          * system.  This doesn't attempt to address those situations,
471          * but should work fine for a classic single AGP slot system
472          * with AGP v3.
473          */
474         if (AGP_MODE_GET_MODE_3(mode) &&
475             AGP_MODE_GET_MODE_3(tstatus) &&
476             AGP_MODE_GET_MODE_3(mstatus))
477                 return (agp_v3_enable(dev, mdev, mode));
478         else
479                 return (agp_v2_enable(dev, mdev, mode));            
480 }
481
482 struct agp_memory *
483 agp_generic_alloc_memory(device_t dev, int type, vm_size_t size)
484 {
485         struct agp_softc *sc = device_get_softc(dev);
486         struct agp_memory *mem;
487
488         if ((size & (AGP_PAGE_SIZE - 1)) != 0)
489                 return 0;
490
491         if (sc->as_allocated + size > sc->as_maxmem)
492                 return 0;
493
494         if (type != 0) {
495                 kprintf("agp_generic_alloc_memory: unsupported type %d\n",
496                         type);
497                 return 0;
498         }
499
500         mem = kmalloc(sizeof *mem, M_AGP, M_INTWAIT);
501         mem->am_id = sc->as_nextid++;
502         mem->am_size = size;
503         mem->am_type = 0;
504         mem->am_obj = vm_object_allocate(OBJT_DEFAULT, atop(round_page(size)));
505         mem->am_physical = 0;
506         mem->am_offset = 0;
507         mem->am_is_bound = 0;
508         TAILQ_INSERT_TAIL(&sc->as_memory, mem, am_link);
509         sc->as_allocated += size;
510
511         return mem;
512 }
513
514 int
515 agp_generic_free_memory(device_t dev, struct agp_memory *mem)
516 {
517         struct agp_softc *sc = device_get_softc(dev);
518
519         if (mem->am_is_bound)
520                 return EBUSY;
521
522         sc->as_allocated -= mem->am_size;
523         TAILQ_REMOVE(&sc->as_memory, mem, am_link);
524         vm_object_deallocate(mem->am_obj);
525         kfree(mem, M_AGP);
526         return 0;
527 }
528
529 int
530 agp_generic_bind_memory(device_t dev, struct agp_memory *mem,
531                         vm_offset_t offset)
532 {
533         struct agp_softc *sc = device_get_softc(dev);
534         vm_offset_t i, j, k;
535         vm_page_t m;
536         int error;
537
538         lockmgr(&sc->as_lock, LK_EXCLUSIVE);
539
540         if (mem->am_is_bound) {
541                 device_printf(dev, "memory already bound\n");
542                 lockmgr(&sc->as_lock, LK_RELEASE);
543                 return EINVAL;
544         }
545         
546         if (offset < 0
547             || (offset & (AGP_PAGE_SIZE - 1)) != 0
548             || offset + mem->am_size > AGP_GET_APERTURE(dev)) {
549                 device_printf(dev, "binding memory at bad offset %#x,%#x,%#x\n",
550                               (int) offset, (int)mem->am_size,
551                               (int)AGP_GET_APERTURE(dev));
552                 kprintf("Check BIOS's aperature size vs X\n");
553                 lockmgr(&sc->as_lock, LK_RELEASE);
554                 return EINVAL;
555         }
556
557         /*
558          * Bind the individual pages and flush the chipset's
559          * TLB.
560          */
561         for (i = 0; i < mem->am_size; i += PAGE_SIZE) {
562                 /*
563                  * Find a page from the object and wire it
564                  * down. This page will be mapped using one or more
565                  * entries in the GATT (assuming that PAGE_SIZE >=
566                  * AGP_PAGE_SIZE. If this is the first call to bind,
567                  * the pages will be allocated and zeroed.
568                  */
569                 m = vm_page_grab(mem->am_obj, OFF_TO_IDX(i),
570                          VM_ALLOC_NORMAL | VM_ALLOC_ZERO | VM_ALLOC_RETRY);
571                 if ((m->flags & PG_ZERO) == 0)
572                         vm_page_zero_fill(m);
573                 AGP_DPF("found page pa=%#x\n", VM_PAGE_TO_PHYS(m));
574                 vm_page_wire(m);
575
576                 /*
577                  * Install entries in the GATT, making sure that if
578                  * AGP_PAGE_SIZE < PAGE_SIZE and mem->am_size is not
579                  * aligned to PAGE_SIZE, we don't modify too many GATT 
580                  * entries.
581                  */
582                 for (j = 0; j < PAGE_SIZE && i + j < mem->am_size;
583                      j += AGP_PAGE_SIZE) {
584                         vm_offset_t pa = VM_PAGE_TO_PHYS(m) + j;
585                         AGP_DPF("binding offset %#x to pa %#x\n",
586                                 offset + i + j, pa);
587                         error = AGP_BIND_PAGE(dev, offset + i + j, pa);
588                         if (error) {
589                                 /*
590                                  * Bail out. Reverse all the mappings
591                                  * and unwire the pages.
592                                  */
593                                 vm_page_wakeup(m);
594                                 for (k = 0; k < i + j; k += AGP_PAGE_SIZE)
595                                         AGP_UNBIND_PAGE(dev, offset + k);
596                                 for (k = 0; k <= i; k += PAGE_SIZE) {
597                                         m = vm_page_lookup(mem->am_obj,
598                                                            OFF_TO_IDX(k));
599                                         vm_page_unwire(m, 0);
600                                 }
601                                 lockmgr(&sc->as_lock, LK_RELEASE);
602                                 return error;
603                         }
604                 }
605                 vm_page_wakeup(m);
606         }
607
608         /*
609          * Flush the cpu cache since we are providing a new mapping
610          * for these pages.
611          */
612         agp_flush_cache();
613
614         /*
615          * Make sure the chipset gets the new mappings.
616          */
617         AGP_FLUSH_TLB(dev);
618
619         mem->am_offset = offset;
620         mem->am_is_bound = 1;
621
622         lockmgr(&sc->as_lock, LK_RELEASE);
623
624         return 0;
625 }
626
627 int
628 agp_generic_unbind_memory(device_t dev, struct agp_memory *mem)
629 {
630         struct agp_softc *sc = device_get_softc(dev);
631         vm_page_t m;
632         int i;
633
634         lockmgr(&sc->as_lock, LK_EXCLUSIVE);
635
636         if (!mem->am_is_bound) {
637                 device_printf(dev, "memory is not bound\n");
638                 lockmgr(&sc->as_lock, LK_RELEASE);
639                 return EINVAL;
640         }
641
642
643         /*
644          * Unbind the individual pages and flush the chipset's
645          * TLB. Unwire the pages so they can be swapped.
646          */
647         for (i = 0; i < mem->am_size; i += AGP_PAGE_SIZE)
648                 AGP_UNBIND_PAGE(dev, mem->am_offset + i);
649         for (i = 0; i < mem->am_size; i += PAGE_SIZE) {
650                 m = vm_page_lookup(mem->am_obj, atop(i));
651                 vm_page_unwire(m, 0);
652         }
653                 
654         agp_flush_cache();
655         AGP_FLUSH_TLB(dev);
656
657         mem->am_offset = 0;
658         mem->am_is_bound = 0;
659
660         lockmgr(&sc->as_lock, LK_RELEASE);
661
662         return 0;
663 }
664
665 /* Helper functions for implementing user/kernel api */
666
667 static int
668 agp_acquire_helper(device_t dev, enum agp_acquire_state state)
669 {
670         struct agp_softc *sc = device_get_softc(dev);
671
672         if (sc->as_state != AGP_ACQUIRE_FREE)
673                 return EBUSY;
674         sc->as_state = state;
675
676         return 0;
677 }
678
679 static int
680 agp_release_helper(device_t dev, enum agp_acquire_state state)
681 {
682         struct agp_softc *sc = device_get_softc(dev);
683
684         if (sc->as_state == AGP_ACQUIRE_FREE)
685                 return 0;
686
687         if (sc->as_state != state)
688                 return EBUSY;
689
690         sc->as_state = AGP_ACQUIRE_FREE;
691         return 0;
692 }
693
694 static struct agp_memory *
695 agp_find_memory(device_t dev, int id)
696 {
697         struct agp_softc *sc = device_get_softc(dev);
698         struct agp_memory *mem;
699
700         AGP_DPF("searching for memory block %d\n", id);
701         TAILQ_FOREACH(mem, &sc->as_memory, am_link) {
702                 AGP_DPF("considering memory block %d\n", mem->am_id);
703                 if (mem->am_id == id)
704                         return mem;
705         }
706         return 0;
707 }
708
709 /* Implementation of the userland ioctl api */
710
711 static int
712 agp_info_user(device_t dev, agp_info *info)
713 {
714         struct agp_softc *sc = device_get_softc(dev);
715
716         bzero(info, sizeof *info);
717         info->bridge_id = pci_get_devid(dev);
718         info->agp_mode = 
719             pci_read_config(dev, agp_find_caps(dev) + AGP_STATUS, 4);
720         info->aper_base = rman_get_start(sc->as_aperture);
721         info->aper_size = AGP_GET_APERTURE(dev) >> 20;
722         info->pg_total = info->pg_system = sc->as_maxmem >> AGP_PAGE_SHIFT;
723         info->pg_used = sc->as_allocated >> AGP_PAGE_SHIFT;
724
725         return 0;
726 }
727
728 static int
729 agp_setup_user(device_t dev, agp_setup *setup)
730 {
731         return AGP_ENABLE(dev, setup->agp_mode);
732 }
733
734 static int
735 agp_allocate_user(device_t dev, agp_allocate *alloc)
736 {
737         struct agp_memory *mem;
738
739         mem = AGP_ALLOC_MEMORY(dev,
740                                alloc->type,
741                                alloc->pg_count << AGP_PAGE_SHIFT);
742         if (mem) {
743                 alloc->key = mem->am_id;
744                 alloc->physical = mem->am_physical;
745                 return 0;
746         } else {
747                 return ENOMEM;
748         }
749 }
750
751 static int
752 agp_deallocate_user(device_t dev, int id)
753 {
754         struct agp_memory *mem = agp_find_memory(dev, id);
755
756         if (mem) {
757                 AGP_FREE_MEMORY(dev, mem);
758                 return 0;
759         } else {
760                 return ENOENT;
761         }
762 }
763
764 static int
765 agp_bind_user(device_t dev, agp_bind *bind)
766 {
767         struct agp_memory *mem = agp_find_memory(dev, bind->key);
768
769         if (!mem)
770                 return ENOENT;
771
772         return AGP_BIND_MEMORY(dev, mem, bind->pg_start << AGP_PAGE_SHIFT);
773 }
774
775 static int
776 agp_unbind_user(device_t dev, agp_unbind *unbind)
777 {
778         struct agp_memory *mem = agp_find_memory(dev, unbind->key);
779
780         if (!mem)
781                 return ENOENT;
782
783         return AGP_UNBIND_MEMORY(dev, mem);
784 }
785
786 static int
787 agp_open(struct dev_open_args *ap)
788 {
789         cdev_t kdev = ap->a_head.a_dev;
790         device_t dev = KDEV2DEV(kdev);
791         struct agp_softc *sc = device_get_softc(dev);
792
793         if (!sc->as_isopen) {
794                 sc->as_isopen = 1;
795                 device_busy(dev);
796         }
797
798         return 0;
799 }
800
801 static int
802 agp_close(struct dev_close_args *ap)
803 {
804         cdev_t kdev = ap->a_head.a_dev;
805         device_t dev = KDEV2DEV(kdev);
806         struct agp_softc *sc = device_get_softc(dev);
807         struct agp_memory *mem;
808
809         /*
810          * Clear the GATT and force release on last close
811          */
812         while ((mem = TAILQ_FIRST(&sc->as_memory)) != 0) {
813                 if (mem->am_is_bound)
814                         AGP_UNBIND_MEMORY(dev, mem);
815                 AGP_FREE_MEMORY(dev, mem);
816         }
817         if (sc->as_state == AGP_ACQUIRE_USER)
818                 agp_release_helper(dev, AGP_ACQUIRE_USER);
819         sc->as_isopen = 0;
820         device_unbusy(dev);
821
822         return 0;
823 }
824
825 static int
826 agp_ioctl(struct dev_ioctl_args *ap)
827 {
828         cdev_t kdev = ap->a_head.a_dev;
829         device_t dev = KDEV2DEV(kdev);
830
831         switch (ap->a_cmd) {
832         case AGPIOC_INFO:
833                 return agp_info_user(dev, (agp_info *)ap->a_data);
834
835         case AGPIOC_ACQUIRE:
836                 return agp_acquire_helper(dev, AGP_ACQUIRE_USER);
837
838         case AGPIOC_RELEASE:
839                 return agp_release_helper(dev, AGP_ACQUIRE_USER);
840
841         case AGPIOC_SETUP:
842                 return agp_setup_user(dev, (agp_setup *)ap->a_data);
843
844         case AGPIOC_ALLOCATE:
845                 return agp_allocate_user(dev, (agp_allocate *)ap->a_data);
846
847         case AGPIOC_DEALLOCATE:
848                 return agp_deallocate_user(dev, *(int *)ap->a_data);
849
850         case AGPIOC_BIND:
851                 return agp_bind_user(dev, (agp_bind *)ap->a_data);
852
853         case AGPIOC_UNBIND:
854                 return agp_unbind_user(dev, (agp_unbind *)ap->a_data);
855
856         }
857
858         return EINVAL;
859 }
860
861 static int
862 agp_mmap(struct dev_mmap_args *ap)
863 {
864         cdev_t kdev = ap->a_head.a_dev;
865         device_t dev = KDEV2DEV(kdev);
866         struct agp_softc *sc = device_get_softc(dev);
867
868         if (ap->a_offset > AGP_GET_APERTURE(dev))
869                 return EINVAL;
870         ap->a_result = atop(rman_get_start(sc->as_aperture) + ap->a_offset);
871         return 0;
872 }
873
874 /* Implementation of the kernel api */
875
876 device_t
877 agp_find_device(void)
878 {
879         device_t *children, child;
880         int i, count;
881
882         if (!agp_devclass)
883                 return NULL;
884         if (devclass_get_devices(agp_devclass, &children, &count) != 0)
885                 return NULL;
886         child = NULL;
887         for (i = 0; i < count; i++) {
888                 if (device_is_attached(children[i])) {
889                         child = children[i];
890                         break;
891                 }
892         }
893         kfree(children, M_TEMP);
894         return child;
895 }
896
897 enum agp_acquire_state
898 agp_state(device_t dev)
899 {
900         struct agp_softc *sc = device_get_softc(dev);
901         return sc->as_state;
902 }
903
904 void
905 agp_get_info(device_t dev, struct agp_info *info)
906 {
907         struct agp_softc *sc = device_get_softc(dev);
908
909         info->ai_mode =
910                 pci_read_config(dev, agp_find_caps(dev) + AGP_STATUS, 4);
911         info->ai_aperture_base = rman_get_start(sc->as_aperture);
912         info->ai_aperture_size = rman_get_size(sc->as_aperture);
913         info->ai_memory_allowed = sc->as_maxmem;
914         info->ai_memory_used = sc->as_allocated;
915 }
916
917 int
918 agp_acquire(device_t dev)
919 {
920         return agp_acquire_helper(dev, AGP_ACQUIRE_KERNEL);
921 }
922
923 int
924 agp_release(device_t dev)
925 {
926         return agp_release_helper(dev, AGP_ACQUIRE_KERNEL);
927 }
928
929 int
930 agp_enable(device_t dev, u_int32_t mode)
931 {
932         return AGP_ENABLE(dev, mode);
933 }
934
935 void *agp_alloc_memory(device_t dev, int type, vm_size_t bytes)
936 {
937         return  (void *) AGP_ALLOC_MEMORY(dev, type, bytes);
938 }
939
940 void agp_free_memory(device_t dev, void *handle)
941 {
942         struct agp_memory *mem = (struct agp_memory *) handle;
943         AGP_FREE_MEMORY(dev, mem);
944 }
945
946 int agp_bind_memory(device_t dev, void *handle, vm_offset_t offset)
947 {
948         struct agp_memory *mem = (struct agp_memory *) handle;
949         return AGP_BIND_MEMORY(dev, mem, offset);
950 }
951
952 int agp_unbind_memory(device_t dev, void *handle)
953 {
954         struct agp_memory *mem = (struct agp_memory *) handle;
955         return AGP_UNBIND_MEMORY(dev, mem);
956 }
957
958 void agp_memory_info(device_t dev, void *handle, struct
959                      agp_memory_info *mi)
960 {
961         struct agp_memory *mem = (struct agp_memory *) handle;
962
963         mi->ami_size = mem->am_size;
964         mi->ami_physical = mem->am_physical;
965         mi->ami_offset = mem->am_offset;
966         mi->ami_is_bound = mem->am_is_bound;
967 }