Merge from vendor branch DHCP:
[dragonfly.git] / sys / dev / netif / nv / if_nv.c
1 /*
2  * Copyright (c) 2003 by Quinton Dolan <q@onthenet.com.au>. 
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 ANY
15  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
16  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
17  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
18  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
20  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
21  * 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  * $Id: if_nv.c,v 1.9 2003/12/13 15:27:40 q Exp $
27  * $DragonFly: src/sys/dev/netif/nv/Attic/if_nv.c,v 1.7 2004/11/05 17:13:44 dillon Exp $
28  */
29
30 /*
31  * NVIDIA nForce MCP Networking Adapter driver
32  * 
33  * This is a port of the NVIDIA MCP Linux ethernet driver distributed by NVIDIA
34  * through their web site.
35  * 
36  * All mainstream nForce and nForce2 motherboards are supported. This module
37  * is as stable, sometimes more stable, than the linux version. (This seems to 
38  * be related to some issues with newer distributions using GCC 3.2, however 
39  * this don't appear to effect FreeBSD 5.x).
40  * 
41  * In accordance with the NVIDIA distribution license it is necessary to link
42  * this module against the nvlibnet.o binary object included in the Linux
43  * driver source distribution. The binary component is not modified in any
44  * way and is simply linked against a FreeBSD equivalent of the nvnet.c linux
45  * kernel module "wrapper".
46  * 
47  * The Linux driver uses a common code API that is shared between Win32 and
48  * Linux. This abstracts the low level driver functions and uses callbacks
49  * and hooks to access the underlying hardware device. By using this same API
50  * in a FreeBSD kernel module it is possible to support the hardware without
51  * breaching the Linux source distributions licensing requirements, or
52  * obtaining the hardware programming specifications.
53  * 
54  * Although not conventional, it works, and given the relatively small amount of
55  * hardware centric code, it's hopefully no more buggy than its linux
56  * counterpart.
57  *
58  * Written by Quinton Dolan <q@onthenet.com.au> 
59  * Portions based on existing FreeBSD network drivers. 
60  * NVIDIA API usage derived from distributed NVIDIA NVNET driver source files.
61  * 
62  * $Id: if_nv.c,v 1.9 2003/12/13 15:27:40 q Exp $
63  */
64
65 #include <sys/param.h>
66 #include <sys/systm.h>
67 #include <sys/sockio.h>
68 #include <sys/mbuf.h>
69 #include <sys/malloc.h>
70 #include <sys/kernel.h>
71 #include <sys/socket.h>
72 #include <sys/sysctl.h>
73 #include <sys/queue.h>
74 #include <sys/module.h>
75
76 #include <net/if.h>
77 #include <net/if_arp.h>
78 #include <net/ethernet.h>
79 #include <net/if_dl.h>
80 #include <net/if_media.h>
81
82 #include <net/bpf.h>
83
84 #include <net/vlan/if_vlan_var.h>
85
86 #include <machine/bus_memio.h>
87 #include <machine/bus.h>
88 #include <machine/resource.h>
89
90 #include <vm/vm.h>              /* for vtophys */
91 #include <vm/pmap.h>            /* for vtophys */
92 #include <machine/clock.h>      /* for DELAY */
93 #include <sys/bus.h>
94 #include <sys/rman.h>
95
96 #include <bus/pci/pcireg.h>
97 #include <bus/pci/pcivar.h>
98
99 #include <dev/netif/mii_layer/mii.h>
100 #include <dev/netif/mii_layer/miivar.h>
101
102 MODULE_DEPEND(nv, pci, 1, 1, 1);
103 MODULE_DEPEND(nv, miibus, 1, 1, 1);
104
105 #include "if_nvreg.h"
106 #include "miibus_if.h"
107
108 static int      nv_probe(device_t);
109 static int      nv_attach(device_t);
110 static int      nv_detach(device_t);
111 static void     nv_init(void *);
112 static void     nv_stop(struct nv_softc *);
113 static void     nv_shutdown(device_t);
114 static int      nv_init_rings(struct nv_softc *);
115 static void     nv_free_rings(struct nv_softc *);
116
117 static void     nv_ifstart(struct ifnet *);
118 static int      nv_ioctl(struct ifnet *, u_long, caddr_t, struct ucred *);
119 static void     nv_intr(void *);
120 static void     nv_tick(void *);
121 static void     nv_setmulti(struct nv_softc *);
122 static void     nv_watchdog(struct ifnet *);
123 static void     nv_update_stats(struct nv_softc *);
124
125 static int      nv_ifmedia_upd(struct ifnet *);
126 static void     nv_ifmedia_sts(struct ifnet *, struct ifmediareq *);
127 static int      nv_miibus_readreg(device_t, int, int);
128 static void     nv_miibus_writereg(device_t, int, int, int);
129
130 static void     nv_dmamap_cb(void *, bus_dma_segment_t *, int, int);
131 static void     nv_dmamap_tx_cb(void *, bus_dma_segment_t *, int, bus_size_t, int);
132
133 static int      nv_osalloc(void *, MEMORY_BLOCK *);
134 static int      nv_osfree(void *, MEMORY_BLOCK *);
135 static int      nv_osallocex(void *, MEMORY_BLOCKEX *);
136 static int      nv_osfreeex(void *, MEMORY_BLOCKEX *);
137 static int      nv_osclear(void *, void *, int);
138 static int      nv_osdelay(void *, unsigned long);
139 static int      nv_osallocrxbuf(void *, MEMORY_BLOCK *, void **);
140 static int      nv_osfreerxbuf(void *, MEMORY_BLOCK *, void *);
141 static int      nv_ospackettx(void *, void *, unsigned long);
142 static int      nv_ospacketrx(void *, void *, unsigned long, unsigned char *, unsigned char);
143 static int      nv_oslinkchg(void *, int);
144 static int      nv_osalloctimer(void *, void **);
145 static int      nv_osfreetimer(void *, void *);
146 static int      nv_osinittimer(void *, void *, PTIMER_FUNC, void *);
147 static int      nv_ossettimer(void *, void *, unsigned long);
148 static int      nv_oscanceltimer(void *, void *);
149 static int      nv_ospreprocpkt(void *, void *, void **, unsigned char *, unsigned char);
150 static void    *nv_ospreprocpktnopq(void *, void *);
151 static int      nv_osindicatepkt(void *, void **, unsigned long);
152 static int      nv_oslockalloc(void *, int, void **);
153 static int      nv_oslockacquire(void *, int, void *);
154 static int      nv_oslockrelease(void *, int, void *);
155 static void    *nv_osreturnbufvirt(void *, void *);
156
157 static device_method_t nv_methods[] = {
158         /* Device interface */
159         DEVMETHOD(device_probe, nv_probe),
160         DEVMETHOD(device_attach, nv_attach),
161         DEVMETHOD(device_detach, nv_detach),
162         DEVMETHOD(device_shutdown, nv_shutdown),
163
164         /* Bus interface */
165         DEVMETHOD(bus_print_child, bus_generic_print_child),
166         DEVMETHOD(bus_driver_added, bus_generic_driver_added),
167
168         /* MII interface */
169         DEVMETHOD(miibus_readreg, nv_miibus_readreg),
170         DEVMETHOD(miibus_writereg, nv_miibus_writereg),
171
172         {0, 0}
173 };
174
175 static driver_t nv_driver = {
176         "nv",
177         nv_methods,
178         sizeof(struct nv_softc)
179 };
180
181 static devclass_t nv_devclass;
182
183 static int      nv_pollinterval = 0;
184 SYSCTL_INT(_hw, OID_AUTO, nv_pollinterval, CTLFLAG_RW,
185            &nv_pollinterval, 0, "delay between interface polls");
186
187 DRIVER_MODULE(nv, pci, nv_driver, nv_devclass, 0, 0);
188 DRIVER_MODULE(miibus, nv, miibus_driver, miibus_devclass, 0, 0);
189
190 static struct nv_type nv_devs[] = {
191         {NVIDIA_VENDORID, NFORCE_MCPNET1_DEVICEID,
192                 "NVIDIA nForce MCP Networking Adapter"},
193         {NVIDIA_VENDORID, NFORCE_MCPNET2_DEVICEID,
194                 "NVIDIA nForce MCP2 Networking Adapter"},
195         {NVIDIA_VENDORID, NFORCE_MCPNET3_DEVICEID,
196                 "NVIDIA nForce MCP3 Networking Adapter"},
197         {NVIDIA_VENDORID, NFORCE_MCPNET4_DEVICEID,
198                 "NVIDIA nForce MCP4 Networking Adapter"},
199         {NVIDIA_VENDORID, NFORCE_MCPNET5_DEVICEID,
200                 "NVIDIA nForce MCP5 Networking Adapter"},
201         {NVIDIA_VENDORID, NFORCE_MCPNET6_DEVICEID,
202                 "NVIDIA nForce MCP6 Networking Adapter"},
203         {NVIDIA_VENDORID, NFORCE_MCPNET7_DEVICEID,
204                 "NVIDIA nForce MCP7 Networking Adapter"},
205         {0, 0, NULL}
206 };
207
208 /* DMA MEM map callback function to get data segment physical address */
209 static void
210 nv_dmamap_cb(void *arg, bus_dma_segment_t * segs, int nsegs, int error)
211 {
212         if (error)
213                 return;
214
215         KASSERT(nsegs == 1,
216                 ("Too many DMA segments returned when mapping DMA memory"));
217         *(bus_addr_t *)arg = segs->ds_addr;
218 }
219
220 /* DMA RX map callback function to get data segment physical address */
221 static void
222 nv_dmamap_rx_cb(void *arg, bus_dma_segment_t * segs, int nsegs, bus_size_t mapsize, int error)
223 {
224         if (error)
225                 return;
226         *(bus_addr_t *)arg = segs->ds_addr;
227 }
228
229 /*
230  * DMA TX buffer callback function to allocate fragment data segment
231  * addresses
232  */
233 static void
234 nv_dmamap_tx_cb(void *arg, bus_dma_segment_t * segs, int nsegs, bus_size_t mapsize, int error)
235 {
236         struct nv_tx_desc *info = arg;
237
238         if (error)
239                 return;
240         KASSERT(nsegs < NV_MAX_FRAGS,
241                 ("Too many DMA segments returned when mapping mbuf"));
242         info->numfrags = nsegs;
243         bcopy(segs, info->frags, nsegs * sizeof(bus_dma_segment_t));
244 }
245
246 /* Probe for supported hardware ID's */
247 static int
248 nv_probe(device_t dev)
249 {
250         struct nv_type *t = nv_devs;
251
252         /* Check for matching PCI DEVICE ID's */
253         while (t->name != NULL) {
254                 if ((pci_get_vendor(dev) == t->vid_id) &&
255                     (pci_get_device(dev) == t->dev_id)) {
256                         device_set_desc(dev, t->name);
257                         return (0);
258                 }
259                 t++;
260         }
261
262         return (ENXIO);
263 }
264
265 /* Attach driver and initialise hardware for use */
266 static int
267 nv_attach(device_t dev)
268 {
269         u_char          eaddr[ETHER_ADDR_LEN];
270         struct nv_softc *sc;
271         struct ifnet   *ifp;
272         OS_API         *osapi;
273         ADAPTER_OPEN_PARAMS OpenParams;
274         int             error = 0, i, rid;
275
276         DEBUGOUT(NV_DEBUG_INIT, "nv: nv_attach - entry\n");
277
278         sc = device_get_softc(dev);
279
280         sc->dev = dev;
281         callout_init(&sc->nv_stat_timer);
282
283         /* Preinitialize data structures */
284         bzero(&OpenParams, sizeof(ADAPTER_OPEN_PARAMS));
285
286         /* Enable bus mastering */
287         pci_enable_busmaster(dev);
288
289         /* Allocate memory mapped address space */
290         rid = NV_RID;
291         sc->res = bus_alloc_resource(dev, SYS_RES_MEMORY, &rid,
292                                      0, ~0, 1, RF_ACTIVE);
293
294         if (sc->res == NULL) {
295                 device_printf(dev, "couldn't map memory\n");
296                 error = ENXIO;
297                 goto fail;
298         }
299         sc->sc_st = rman_get_bustag(sc->res);
300         sc->sc_sh = rman_get_bushandle(sc->res);
301
302         /* Allocate interrupt */
303         rid = 0;
304         sc->irq = bus_alloc_resource(dev, SYS_RES_IRQ, &rid, 0, ~0, 1,
305                                      RF_SHAREABLE | RF_ACTIVE);
306
307         if (sc->irq == NULL) {
308                 device_printf(dev, "couldn't map interrupt\n");
309                 error = ENXIO;
310                 goto fail;
311         }
312         /* Allocate DMA tags */
313         error = bus_dma_tag_create(NULL, 4, 0, BUS_SPACE_MAXADDR_32BIT,
314                      BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES * NV_MAX_FRAGS,
315                                    NV_MAX_FRAGS, MCLBYTES, 0,
316                                    &sc->mtag);
317         if (error) {
318                 device_printf(dev, "couldn't allocate dma tag\n");
319                 goto fail;
320         }
321         error = bus_dma_tag_create(NULL, 4, 0, BUS_SPACE_MAXADDR_32BIT,
322                                    BUS_SPACE_MAXADDR, NULL, NULL,
323                                 sizeof(struct nv_rx_desc) * RX_RING_SIZE, 1,
324                                 sizeof(struct nv_rx_desc) * RX_RING_SIZE, 0,
325                                    &sc->rtag);
326         if (error) {
327                 device_printf(dev, "couldn't allocate dma tag\n");
328                 goto fail;
329         }
330         error = bus_dma_tag_create(NULL, 4, 0, BUS_SPACE_MAXADDR_32BIT,
331                                    BUS_SPACE_MAXADDR, NULL, NULL,
332                                 sizeof(struct nv_tx_desc) * TX_RING_SIZE, 1,
333                                 sizeof(struct nv_tx_desc) * TX_RING_SIZE, 0,
334                                    &sc->ttag);
335         if (error) {
336                 device_printf(dev, "couldn't allocate dma tag\n");
337                 goto fail;
338         }
339
340         error = bus_dmamap_create(sc->ttag, 0, &sc->tmap);
341         if (error) {
342                 device_printf(dev, "couldn't create dma map\n");
343                 goto fail;
344         }
345
346         /* Allocate DMA safe memory and get the DMA addresses. */
347         error = bus_dmamem_alloc(sc->ttag, (void **)&sc->tx_desc,
348                                  BUS_DMA_WAITOK | BUS_DMA_ZERO, &sc->tmap);
349         if (error) {
350                 device_printf(dev, "couldn't allocate dma memory\n");
351                 goto fail;
352         }
353         error = bus_dmamap_load(sc->ttag, sc->tmap, sc->tx_desc,
354                      sizeof(struct nv_tx_desc) * TX_RING_SIZE, nv_dmamap_cb,
355                                 &sc->tx_addr, 0);
356         if (error) {
357                 device_printf(dev, "couldn't map dma memory\n");
358                 goto fail;
359         }
360
361         error = bus_dmamap_create(sc->rtag, 0, &sc->rmap);
362         if (error) {
363                 device_printf(dev, "couldn't create dma map\n");
364                 goto fail;
365         }
366
367         error = bus_dmamem_alloc(sc->rtag, (void **)&sc->rx_desc,
368                                  BUS_DMA_WAITOK | BUS_DMA_ZERO, &sc->rmap);
369         if (error) {
370                 device_printf(dev, "couldn't allocate dma memory\n");
371                 goto fail;
372         }
373         error = bus_dmamap_load(sc->rtag, sc->rmap, sc->rx_desc,
374                      sizeof(struct nv_rx_desc) * RX_RING_SIZE, nv_dmamap_cb,
375                                 &sc->rx_addr, 0);
376         if (error) {
377                 device_printf(dev, "couldn't map dma memory\n");
378                 goto fail;
379         }
380         /* Initialize rings. */
381         if (nv_init_rings(sc)) {
382                 device_printf(dev, "failed to init rings\n");
383                 error = ENXIO;
384                 goto fail;
385         }
386         /* Setup NVIDIA API callback routines */
387         osapi = &sc->osapi;
388         osapi->pOSCX = sc;
389         osapi->pfnAllocMemory = nv_osalloc;
390         osapi->pfnFreeMemory = nv_osfree;
391         osapi->pfnAllocMemoryEx = nv_osallocex;
392         osapi->pfnFreeMemoryEx = nv_osfreeex;
393         osapi->pfnClearMemory = nv_osclear;
394         osapi->pfnStallExecution = nv_osdelay;
395         osapi->pfnAllocReceiveBuffer = nv_osallocrxbuf;
396         osapi->pfnFreeReceiveBuffer = nv_osfreerxbuf;
397         osapi->pfnPacketWasSent = nv_ospackettx;
398         osapi->pfnPacketWasReceived = nv_ospacketrx;
399         osapi->pfnLinkStateHasChanged = nv_oslinkchg;
400         osapi->pfnAllocTimer = nv_osalloctimer;
401         osapi->pfnFreeTimer = nv_osfreetimer;
402         osapi->pfnInitializeTimer = nv_osinittimer;
403         osapi->pfnSetTimer = nv_ossettimer;
404         osapi->pfnCancelTimer = nv_oscanceltimer;
405         osapi->pfnPreprocessPacket = nv_ospreprocpkt;
406         osapi->pfnPreprocessPacketNopq = nv_ospreprocpktnopq;
407         osapi->pfnIndicatePackets = nv_osindicatepkt;
408         osapi->pfnLockAlloc = nv_oslockalloc;
409         osapi->pfnLockAcquire = nv_oslockacquire;
410         osapi->pfnLockRelease = nv_oslockrelease;
411         osapi->pfnReturnBufferVirtual = nv_osreturnbufvirt;
412
413         /* Set NVIDIA API startup parameters */
414         OpenParams.MaxDpcLoop = 2;
415         OpenParams.MaxRxPkt = RX_RING_SIZE;
416         OpenParams.MaxTxPkt = TX_RING_SIZE;
417         OpenParams.SentPacketStatusSuccess = 1;
418         OpenParams.SentPacketStatusFailure = 0;
419         OpenParams.MaxRxPktToAccumulate = 6;
420         OpenParams.ulPollInterval = nv_pollinterval;
421         OpenParams.SetForcedModeEveryNthRxPacket = 0;
422         OpenParams.SetForcedModeEveryNthTxPacket = 0;
423         OpenParams.RxForcedInterrupt = 0;
424         OpenParams.TxForcedInterrupt = 0;
425         OpenParams.pOSApi = osapi;
426         OpenParams.pvHardwareBaseAddress = rman_get_virtual(sc->res);
427         sc->linkup = 0;
428
429         /* Open NVIDIA Hardware API */
430         error = ADAPTER_Open(&OpenParams, (void **)&(sc->hwapi), &sc->phyaddr);
431         if (error) {
432                 device_printf(dev, "failed to open NVIDIA Hardware API: 0x%x\n", error);
433                 goto fail;
434         }
435         /* MAC is loaded backwards into h/w reg */
436         sc->hwapi->pfnGetNodeAddress(sc->hwapi->pADCX, sc->original_mac_addr);
437         for (i = 0; i < 6; i++) {
438                 eaddr[i] = sc->original_mac_addr[5 - i];
439         }
440         sc->hwapi->pfnSetNodeAddress(sc->hwapi->pADCX, eaddr);
441         bcopy(eaddr, (char *)&sc->sc_macaddr, ETHER_ADDR_LEN);
442
443         /* Display ethernet address ,... */
444         device_printf(dev, "Ethernet address %6D\n", sc->sc_macaddr, ":");
445
446         DEBUGOUT(NV_DEBUG_INIT, "nv: do mii_phy_probe\n");
447
448         /* Probe device for MII interface to PHY */
449         if (mii_phy_probe(dev, &sc->miibus,
450                           nv_ifmedia_upd, nv_ifmedia_sts)) {
451                 device_printf(dev, "MII without any phy!\n");
452                 error = ENXIO;
453                 goto fail;
454         }
455         /* Setup interface parameters */
456         ifp = &sc->sc_if;
457         ifp->if_softc = sc;
458         if_initname(ifp, device_get_name(dev), device_get_unit(dev));
459         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
460         ifp->if_ioctl = nv_ioctl;
461         ifp->if_start = nv_ifstart;
462         ifp->if_watchdog = nv_watchdog;
463         ifp->if_timer = 0;
464         ifp->if_init = nv_init;
465         ifp->if_mtu = ETHERMTU;
466         ifp->if_baudrate = IF_Mbps(100);
467         ifp->if_snd.ifq_maxlen = IFQ_MAXLEN;
468
469         /* Attach to OS's managers. */
470         ether_ifattach(ifp, sc->sc_macaddr);
471
472         /* Activate our interrupt handler. - attach last to avoid lock */
473         error = bus_setup_intr(sc->dev, sc->irq, INTR_TYPE_NET,
474                                nv_intr, sc, &sc->sc_ih);
475         if (error) {
476                 device_printf(sc->dev, "couldn't set up interrupt handler\n");
477                 goto fail;
478         }
479         DEBUGOUT(NV_DEBUG_INIT, "nv: nv_attach - exit\n");
480
481 fail:
482         if (error)
483                 nv_detach(dev);
484
485         return (error);
486 }
487
488 /* Detach interface for module unload */
489 static int
490 nv_detach(device_t dev)
491 {
492         struct nv_softc *sc = device_get_softc(dev);
493         struct ifnet   *ifp;
494
495         NV_LOCK(sc);
496
497         DEBUGOUT(NV_DEBUG_DEINIT, "nv: nv_detach - entry\n");
498
499         ifp = &sc->arpcom.ac_if;
500
501         if (device_is_attached(dev)) {
502                 nv_stop(sc);
503                 ether_ifdetach(ifp);
504         }
505
506         if (sc->miibus)
507                 device_delete_child(dev, sc->miibus);
508         bus_generic_detach(dev);
509
510         /* Reload unreversed address back into MAC in original state */
511         if (sc->original_mac_addr)
512                 sc->hwapi->pfnSetNodeAddress(sc->hwapi->pADCX, sc->original_mac_addr);
513
514         DEBUGOUT(NV_DEBUG_DEINIT, "nv: do pfnClose\n");
515         /* Detach from NVIDIA hardware API */
516         if (sc->hwapi->pfnClose)
517                 sc->hwapi->pfnClose(sc->hwapi->pADCX);
518         /* Release resources */
519         if (sc->sc_ih)
520                 bus_teardown_intr(sc->dev, sc->irq, sc->sc_ih);
521         if (sc->irq)
522                 bus_release_resource(sc->dev, SYS_RES_IRQ, 0, sc->irq);
523         if (sc->res)
524                 bus_release_resource(sc->dev, SYS_RES_MEMORY, NV_RID, sc->res);
525
526         nv_free_rings(sc);
527
528         if (sc->tx_desc) {
529                 bus_dmamap_unload(sc->rtag, sc->rmap);
530                 bus_dmamem_free(sc->rtag, sc->rx_desc, sc->rmap);
531                 bus_dmamap_destroy(sc->rtag, sc->rmap);
532         }
533         if (sc->mtag)
534                 bus_dma_tag_destroy(sc->mtag);
535         if (sc->ttag)
536                 bus_dma_tag_destroy(sc->ttag);
537         if (sc->rtag)
538                 bus_dma_tag_destroy(sc->rtag);
539
540         NV_UNLOCK(sc);
541
542         DEBUGOUT(NV_DEBUG_DEINIT, "nv: nv_detach - exit\n");
543
544         return (0);
545 }
546
547 /* Initialise interface and start it "RUNNING" */
548 static void
549 nv_init(void *xsc)
550 {
551         struct nv_softc *sc = xsc;
552         struct ifnet   *ifp;
553         int             error;
554
555         NV_LOCK(sc);
556
557         DEBUGOUT(NV_DEBUG_INIT, "nv: nv_init - entry (%d)\n", sc->linkup);
558
559         ifp = &sc->sc_if;
560
561         /* Do nothing if already running */
562         if (ifp->if_flags & IFF_RUNNING)
563                 goto fail;
564
565         nv_stop(sc);
566
567         DEBUGOUT(NV_DEBUG_INIT, "nv: do pfnInit\n");
568         /* Setup Hardware interface and allocate memory structures */
569         error = sc->hwapi->pfnInit(sc->hwapi->pADCX, 0, 0, 0, &sc->linkup);
570         if (error) {
571                 device_printf(sc->dev, "failed to start NVIDIA Hardware interface\n");
572                 goto fail;
573         }
574         /* Set the MAC address */
575         sc->hwapi->pfnSetNodeAddress(sc->hwapi->pADCX, sc->sc_macaddr);
576         sc->hwapi->pfnEnableInterrupts(sc->hwapi->pADCX);
577         sc->hwapi->pfnStart(sc->hwapi->pADCX);
578
579         /* Setup multicast filter */
580         nv_setmulti(sc);
581         nv_ifmedia_upd(ifp);
582
583         /* Update interface parameters */
584         ifp->if_flags |= IFF_RUNNING;
585         ifp->if_flags &= ~IFF_OACTIVE;
586
587         callout_reset(&sc->nv_stat_timer, hz, nv_tick, sc);
588
589         DEBUGOUT(NV_DEBUG_INIT, "nv: nv_init - exit\n");
590
591 fail:
592         NV_UNLOCK(sc);
593
594         return;
595 }
596
597 /* Stop interface activity ie. not "RUNNING" */
598 static void
599 nv_stop(struct nv_softc *sc)
600 {
601         struct ifnet   *ifp;
602
603         NV_LOCK(sc);
604
605         DEBUGOUT(NV_DEBUG_RUNNING, "nv: nv_stop - entry\n");
606
607         ifp = &sc->sc_if;
608         ifp->if_timer = 0;
609
610         /* Cancel tick timer */
611         callout_stop(&sc->nv_stat_timer);
612
613         /* Stop hardware activity */
614         sc->hwapi->pfnDisableInterrupts(sc->hwapi->pADCX);
615         sc->hwapi->pfnStop(sc->hwapi->pADCX, 0);
616
617         DEBUGOUT(NV_DEBUG_DEINIT, "nv: do pfnDeinit\n");
618         /* Shutdown interface and deallocate memory buffers */
619         if (sc->hwapi->pfnDeinit)
620                 sc->hwapi->pfnDeinit(sc->hwapi->pADCX, 0);
621
622         sc->linkup = 0;
623         sc->cur_rx = 0;
624
625         ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
626
627         DEBUGOUT(NV_DEBUG_RUNNING, "nv: nv_stop - exit\n");
628
629         NV_UNLOCK(sc);
630
631         return;
632 }
633
634 /* Shutdown interface for unload/reboot */
635 static void
636 nv_shutdown(device_t dev)
637 {
638         struct nv_softc *sc;
639
640         DEBUGOUT(NV_DEBUG_DEINIT, "nv: nv_shutdown\n");
641
642         sc = device_get_softc(dev);
643
644         /* Stop hardware activity */
645         nv_stop(sc);
646 }
647
648 /* Allocate TX ring buffers */
649 static int
650 nv_init_rings(struct nv_softc *sc)
651 {
652         int             error, i;
653
654         NV_LOCK(sc);
655
656         DEBUGOUT(NV_DEBUG_INIT, "nv: nv_init_rings - entry\n");
657
658         sc->cur_rx = sc->cur_tx = sc->pending_rxs = sc->pending_txs = 0;
659         /* Initialise RX ring */
660         for (i = 0; i < RX_RING_SIZE; i++) {
661                 struct nv_rx_desc *desc = sc->rx_desc + i;
662                 struct nv_map_buffer *buf = &desc->buf;
663
664                 buf->mbuf = m_getcl(MB_DONTWAIT, MT_DATA, M_PKTHDR);
665                 if (buf->mbuf == NULL) {
666                         device_printf(sc->dev, "couldn't allocate mbuf\n");
667                         nv_free_rings(sc);
668                         error = ENOBUFS;
669                         goto fail;
670                 }
671                 buf->mbuf->m_len = buf->mbuf->m_pkthdr.len = MCLBYTES;
672                 m_adj(buf->mbuf, ETHER_ALIGN);
673
674                 error = bus_dmamap_create(sc->mtag, 0, &buf->map);
675                 if (error) {
676                         device_printf(sc->dev, "couldn't create dma map\n");
677                         nv_free_rings(sc);
678                         goto fail;
679                 }
680                 error = bus_dmamap_load_mbuf(sc->mtag, buf->map, buf->mbuf,
681                                           nv_dmamap_rx_cb, &desc->paddr, 0);
682                 if (error) {
683                         device_printf(sc->dev, "couldn't dma map mbuf\n");
684                         nv_free_rings(sc);
685                         goto fail;
686                 }
687                 bus_dmamap_sync(sc->mtag, buf->map, BUS_DMASYNC_PREREAD);
688
689                 desc->buflength = buf->mbuf->m_len;
690                 desc->vaddr = mtod(buf->mbuf, PVOID);
691         }
692         bus_dmamap_sync(sc->rtag, sc->rmap,
693                         BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
694
695         /* Initialize TX ring */
696         for (i = 0; i < TX_RING_SIZE; i++) {
697                 struct nv_tx_desc *desc = sc->tx_desc + i;
698                 struct nv_map_buffer *buf = &desc->buf;
699
700                 buf->mbuf = NULL;
701
702                 error = bus_dmamap_create(sc->mtag, 0, &buf->map);
703                 if (error) {
704                         device_printf(sc->dev, "couldn't create dma map\n");
705                         nv_free_rings(sc);
706                         goto fail;
707                 }
708         }
709         bus_dmamap_sync(sc->ttag, sc->tmap,
710                         BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
711
712         DEBUGOUT(NV_DEBUG_INIT, "nv: nv_init_rings - exit\n");
713
714 fail:
715         NV_UNLOCK(sc);
716
717         return (error);
718 }
719
720 /* Free the TX ring buffers */
721 static void
722 nv_free_rings(struct nv_softc *sc)
723 {
724         int             i;
725
726         NV_LOCK(sc);
727
728         DEBUGOUT(NV_DEBUG_DEINIT, "nv: nv_free_rings - entry\n");
729
730         for (i = 0; i < RX_RING_SIZE; i++) {
731                 struct nv_rx_desc *desc = sc->rx_desc + i;
732                 struct nv_map_buffer *buf = &desc->buf;
733
734                 if (buf->mbuf) {
735                         bus_dmamap_unload(sc->mtag, buf->map);
736                         bus_dmamap_destroy(sc->mtag, buf->map);
737                         m_freem(buf->mbuf);
738                 }
739                 buf->mbuf = NULL;
740         }
741
742         for (i = 0; i < TX_RING_SIZE; i++) {
743                 struct nv_tx_desc *desc = sc->tx_desc + i;
744                 struct nv_map_buffer *buf = &desc->buf;
745
746                 if (buf->mbuf) {
747                         bus_dmamap_unload(sc->mtag, buf->map);
748                         bus_dmamap_destroy(sc->mtag, buf->map);
749                         m_freem(buf->mbuf);
750                 }
751                 buf->mbuf = NULL;
752         }
753
754         DEBUGOUT(NV_DEBUG_DEINIT, "nv: nv_free_rings - exit\n");
755
756         NV_UNLOCK(sc);
757 }
758
759 /* Main loop for sending packets from OS to interface */
760 static void
761 nv_ifstart(struct ifnet *ifp)
762 {
763         struct nv_softc *sc = ifp->if_softc;
764         struct nv_map_buffer *buf;
765         struct mbuf    *m0, *m;
766         struct nv_tx_desc *desc;
767         ADAPTER_WRITE_DATA txdata;
768         int             error, i;
769
770         DEBUGOUT(NV_DEBUG_RUNNING, "nv: nv_ifstart - entry\n");
771
772         /* If link is down/busy or queue is empty do nothing */
773         if (ifp->if_flags & IFF_OACTIVE || ifp->if_snd.ifq_head == NULL)
774                 return;
775
776         /* Transmit queued packets until sent or TX ring is full */
777         while (sc->pending_txs < TX_RING_SIZE) {
778                 desc = sc->tx_desc + sc->cur_tx;
779                 buf = &desc->buf;
780
781                 /* Get next packet to send. */
782                 IF_DEQUEUE(&ifp->if_snd, m0);
783
784                 /* If nothing to send, return. */
785                 if (m0 == NULL)
786                         return;
787
788                 /* Map MBUF for DMA access */
789                 error = bus_dmamap_load_mbuf(sc->mtag, buf->map, m0,
790                                      nv_dmamap_tx_cb, desc, BUS_DMA_NOWAIT);
791
792                 if (error && error != EFBIG) {
793                         m_freem(m0);
794                         sc->tx_errors++;
795                         continue;
796                 }
797                 /*
798                  * Packet has too many fragments - defrag into new mbuf
799                  * cluster
800                  */
801                 if (error) {
802                         m = m_defrag(m0, MB_DONTWAIT);
803                         if (m == NULL) {
804                                 m_freem(m0);
805                                 sc->tx_errors++;
806                                 continue;
807                         }
808                         m_freem(m0);
809                         m0 = m;
810
811                         error = bus_dmamap_load_mbuf(sc->mtag, buf->map, m,
812                                      nv_dmamap_tx_cb, desc, BUS_DMA_NOWAIT);
813                         if (error) {
814                                 m_freem(m);
815                                 sc->tx_errors++;
816                                 continue;
817                         }
818                 }
819                 /* Do sync on DMA bounce buffer */
820                 bus_dmamap_sync(sc->mtag, buf->map, BUS_DMASYNC_PREWRITE);
821
822                 buf->mbuf = m0;
823                 txdata.ulNumberOfElements = desc->numfrags;
824                 txdata.pvID = (PVOID)desc;
825
826                 /* Put fragments into API element list */
827                 txdata.ulTotalLength = buf->mbuf->m_len;
828                 for (i = 0; i < desc->numfrags; i++) {
829                         txdata.sElement[i].ulLength = (ulong)desc->frags[i].ds_len;
830                         txdata.sElement[i].pPhysical = (PVOID)desc->frags[i].ds_addr;
831                 }
832
833                 /* Send packet to Nvidia API for transmission */
834                 error = sc->hwapi->pfnWrite(sc->hwapi->pADCX, &txdata);
835
836                 switch (error) {
837                 case ADAPTERERR_NONE:
838                         /* Packet was queued in API TX queue successfully */
839                         sc->pending_txs++;
840                         sc->cur_tx = (sc->cur_tx + 1) % TX_RING_SIZE;
841                         break;
842
843                 case ADAPTERERR_TRANSMIT_QUEUE_FULL:
844                         /* The API TX queue is full - requeue the packet */
845                         device_printf(sc->dev, "nv_ifstart: transmit queue is full\n");
846                         ifp->if_flags |= IFF_OACTIVE;
847                         bus_dmamap_unload(sc->mtag, buf->map);
848                         IF_PREPEND(&ifp->if_snd, buf->mbuf);
849                         buf->mbuf = NULL;
850                         return;
851
852                 default:
853                         /* The API failed to queue/send the packet so dump it */
854                         device_printf(sc->dev, "nv_ifstart: transmit error\n");
855                         bus_dmamap_unload(sc->mtag, buf->map);
856                         m_freem(buf->mbuf);
857                         buf->mbuf = NULL;
858                         sc->tx_errors++;
859                         return;
860                 }
861                 /* Set watchdog timer. */
862                 ifp->if_timer = 8;
863
864                 /* Copy packet to BPF tap */
865                 BPF_MTAP(ifp, m0);
866         }
867         ifp->if_flags |= IFF_OACTIVE;
868
869         DEBUGOUT(NV_DEBUG_RUNNING, "nv: nv_ifstart - exit\n");
870 }
871
872 /* Handle IOCTL events */
873 static int
874 nv_ioctl(struct ifnet *ifp, u_long command, caddr_t data, struct ucred *cr)
875 {
876         struct nv_softc *sc = ifp->if_softc;
877         struct ifreq   *ifr = (struct ifreq *) data;
878         struct mii_data *mii;
879         int             error = 0;
880
881         NV_LOCK(sc);
882
883         DEBUGOUT(NV_DEBUG_IOCTL, "nv: nv_ioctl - entry\n");
884
885         switch (command) {
886         case SIOCSIFMTU:
887                 /* Set MTU size */
888                 if (ifp->if_mtu == ifr->ifr_mtu)
889                         break;
890                 if (ifr->ifr_mtu + ifp->if_hdrlen <= MAX_PACKET_SIZE) {
891                         ifp->if_mtu = ifr->ifr_mtu;
892                         nv_stop(sc);
893                         nv_init(sc);
894                 } else
895                         error = EINVAL;
896                 break;
897
898         case SIOCSIFFLAGS:
899                 /* Setup interface flags */
900                 if (ifp->if_flags & IFF_UP) {
901                         if ((ifp->if_flags & IFF_RUNNING) == 0) {
902                                 nv_init(sc);
903                                 break;
904                         }
905                 } else {
906                         if (ifp->if_flags & IFF_RUNNING) {
907                                 nv_stop(sc);
908                                 break;
909                         }
910                 }
911
912                 /* Handle IFF_PROMISC and IFF_ALLMULTI flags. */
913                 nv_setmulti(sc);
914                 break;
915
916         case SIOCADDMULTI:
917         case SIOCDELMULTI:
918                 /* Setup multicast filter */
919                 if (ifp->if_flags & IFF_RUNNING) {
920                         nv_setmulti(sc);
921                 }
922                 break;
923         case SIOCGIFMEDIA:
924         case SIOCSIFMEDIA:
925                 /* Get/Set interface media parameters */
926                 mii = device_get_softc(sc->miibus);
927                 error = ifmedia_ioctl(ifp, ifr, &mii->mii_media, command);
928                 break;
929
930         default:
931                 /* Everything else we forward to generic ether ioctl */
932                 error = ether_ioctl(ifp, (int)command, data);
933                 break;
934         }
935
936         DEBUGOUT(NV_DEBUG_IOCTL, "nv: nv_ioctl - exit\n");
937
938         NV_UNLOCK(sc);
939
940         return (error);
941 }
942
943 /* Interrupt service routine */
944 static void
945 nv_intr(void *arg)
946 {
947         struct nv_softc *sc = arg;
948         struct ifnet   *ifp = &sc->sc_if;
949
950         DEBUGOUT(NV_DEBUG_INTERRUPT, "nv: nv_intr - entry\n");
951
952         if (!ifp->if_flags & IFF_UP) {
953                 nv_stop(sc);
954                 return;
955         }
956         /* Handle interrupt event */
957         if (sc->hwapi->pfnQueryInterrupt(sc->hwapi->pADCX)) {
958                 sc->hwapi->pfnHandleInterrupt(sc->hwapi->pADCX);
959                 sc->hwapi->pfnEnableInterrupts(sc->hwapi->pADCX);
960         }
961         if (ifp->if_snd.ifq_head != NULL)
962                 nv_ifstart(ifp);
963
964         /* If no pending packets we don't need a timeout */
965         if (sc->pending_txs == 0)
966                 sc->sc_if.if_timer = 0;
967
968         DEBUGOUT(NV_DEBUG_INTERRUPT, "nv: nv_intr - exit\n");
969
970         return;
971 }
972
973 /* Setup multicast filters */
974 static void
975 nv_setmulti(struct nv_softc *sc)
976 {
977         struct ifnet   *ifp;
978         struct ifmultiaddr *ifma;
979         PACKET_FILTER   hwfilter;
980         int             i;
981         u_int8_t        oraddr[6];
982         u_int8_t        andaddr[6];
983
984         NV_LOCK(sc);
985
986         DEBUGOUT(NV_DEBUG_RUNNING, "nv: nv_setmulti - entry\n");
987
988         ifp = &sc->sc_if;
989
990         /* Initialize filter */
991         hwfilter.ulFilterFlags = 0;
992         for (i = 0; i < 6; i++) {
993                 hwfilter.acMulticastAddress[i] = 0;
994                 hwfilter.acMulticastMask[i] = 0;
995         }
996
997         if (ifp->if_flags & (IFF_PROMISC | IFF_ALLMULTI)) {
998                 /* Accept all packets */
999                 hwfilter.ulFilterFlags |= ACCEPT_ALL_PACKETS;
1000                 sc->hwapi->pfnSetPacketFilter(sc->hwapi->pADCX, &hwfilter);
1001                 NV_UNLOCK(sc);
1002                 return;
1003         }
1004         /* Setup multicast filter */
1005         LIST_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
1006                 u_char         *addrp;
1007
1008                 if (ifma->ifma_addr->sa_family != AF_LINK)
1009                         continue;
1010
1011                 addrp = LLADDR((struct sockaddr_dl *) ifma->ifma_addr);
1012                 for (i = 0; i < 6; i++) {
1013                         u_int8_t        mcaddr = addrp[i];
1014                         andaddr[i] &= mcaddr;
1015                         oraddr[i] |= mcaddr;
1016                 }
1017         }
1018         for (i = 0; i < 6; i++) {
1019                 hwfilter.acMulticastAddress[i] = andaddr[i] & oraddr[i];
1020                 hwfilter.acMulticastMask[i] = andaddr[i] | (~oraddr[i]);
1021         }
1022
1023         /* Send filter to NVIDIA API */
1024         sc->hwapi->pfnSetPacketFilter(sc->hwapi->pADCX, &hwfilter);
1025
1026         NV_UNLOCK(sc);
1027
1028         DEBUGOUT(NV_DEBUG_RUNNING, "nv: nv_setmulti - exit\n");
1029
1030         return;
1031 }
1032
1033 /* Change the current media/mediaopts */
1034 static int
1035 nv_ifmedia_upd(struct ifnet *ifp)
1036 {
1037         struct nv_softc *sc = ifp->if_softc;
1038         struct mii_data *mii;
1039
1040         DEBUGOUT(NV_DEBUG_MII, "nv: nv_ifmedia_upd\n");
1041
1042         mii = device_get_softc(sc->miibus);
1043
1044         if (mii->mii_instance) {
1045                 struct mii_softc *miisc;
1046                 for (miisc = LIST_FIRST(&mii->mii_phys); miisc != NULL;
1047                      miisc = LIST_NEXT(miisc, mii_list)) {
1048                         mii_phy_reset(miisc);
1049                 }
1050         }
1051         mii_mediachg(mii);
1052
1053         return (0);
1054 }
1055
1056 /* Update current miibus PHY status of media */
1057 static void
1058 nv_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr)
1059 {
1060         struct nv_softc *sc;
1061         struct mii_data *mii;
1062
1063         DEBUGOUT(NV_DEBUG_MII, "nv: nv_ifmedia_sts\n");
1064
1065         sc = ifp->if_softc;
1066         mii = device_get_softc(sc->miibus);
1067         mii_pollstat(mii);
1068
1069         ifmr->ifm_active = mii->mii_media_active;
1070         ifmr->ifm_status = mii->mii_media_status;
1071
1072         return;
1073 }
1074
1075 /* miibus tick timer - maintain link status */
1076 static void
1077 nv_tick(void *xsc)
1078 {
1079         struct nv_softc *sc = xsc;
1080         struct mii_data *mii;
1081         struct ifnet   *ifp;
1082
1083         NV_LOCK(sc);
1084
1085         ifp = &sc->sc_if;
1086         nv_update_stats(sc);
1087
1088         mii = device_get_softc(sc->miibus);
1089         mii_tick(mii);
1090
1091         if (mii->mii_media_status & IFM_ACTIVE &&
1092             IFM_SUBTYPE(mii->mii_media_active) != IFM_NONE) {
1093                 if (ifp->if_snd.ifq_head != NULL)
1094                         nv_ifstart(ifp);
1095         }
1096         callout_reset(&sc->nv_stat_timer, hz, nv_tick, sc);
1097
1098         NV_UNLOCK(sc);
1099
1100         return;
1101 }
1102
1103 /* Update ifnet data structure with collected interface stats from API */
1104 static void
1105 nv_update_stats(struct nv_softc *sc)
1106 {
1107         struct ifnet   *ifp = &sc->sc_if;
1108         ADAPTER_STATS   stats;
1109
1110         NV_LOCK(sc);
1111
1112         if (sc->hwapi) {
1113                 sc->hwapi->pfnGetStatistics(sc->hwapi->pADCX, &stats);
1114
1115                 ifp->if_ipackets = stats.ulSuccessfulReceptions;
1116                 ifp->if_ierrors = stats.ulMissedFrames +
1117                         stats.ulFailedReceptions +
1118                         stats.ulCRCErrors +
1119                         stats.ulFramingErrors +
1120                         stats.ulOverFlowErrors;
1121
1122                 ifp->if_opackets = stats.ulSuccessfulTransmissions;
1123                 ifp->if_oerrors = sc->tx_errors +
1124                         stats.ulFailedTransmissions +
1125                         stats.ulRetryErrors +
1126                         stats.ulUnderflowErrors +
1127                         stats.ulLossOfCarrierErrors +
1128                         stats.ulLateCollisionErrors;
1129
1130                 ifp->if_collisions = stats.ulLateCollisionErrors;
1131         }
1132         NV_UNLOCK(sc);
1133
1134         return;
1135 }
1136
1137 /* miibus Read PHY register wrapper - calls Nvidia API entry point */
1138 static int
1139 nv_miibus_readreg(device_t dev, int phy, int reg)
1140 {
1141         struct nv_softc *sc = device_get_softc(dev);
1142         ulong           data;
1143
1144         DEBUGOUT(NV_DEBUG_MII, "nv: nv_miibus_readreg - entry\n");
1145
1146         ADAPTER_ReadPhy(sc->hwapi->pADCX, phy, reg, &data);
1147
1148         DEBUGOUT(NV_DEBUG_MII, "nv: nv_miibus_readreg - exit\n");
1149
1150         return (data);
1151 }
1152
1153 /* miibus Write PHY register wrapper - calls Nvidia API entry point */
1154 static void
1155 nv_miibus_writereg(device_t dev, int phy, int reg, int data)
1156 {
1157         struct nv_softc *sc = device_get_softc(dev);
1158
1159         DEBUGOUT(NV_DEBUG_MII, "nv: nv_miibus_writereg - entry\n");
1160
1161         ADAPTER_WritePhy(sc->hwapi->pADCX, phy, reg, (ulong)data);
1162
1163         DEBUGOUT(NV_DEBUG_MII, "nv: nv_miibus_writereg - exit\n");
1164
1165         return;
1166 }
1167
1168 /* Watchdog timer to prevent PHY lockups */
1169 static void
1170 nv_watchdog(struct ifnet *ifp)
1171 {
1172         struct nv_softc *sc = ifp->if_softc;
1173
1174         device_printf(sc->dev, "device timeout\n");
1175
1176         sc->tx_errors++;
1177
1178         nv_stop(sc);
1179         ifp->if_flags &= ~IFF_RUNNING;
1180         nv_init(sc);
1181
1182         if (ifp->if_snd.ifq_head != NULL)
1183                 nv_ifstart(ifp);
1184
1185         return;
1186 }
1187
1188 /* --- Start of NVOSAPI interface --- */
1189
1190 /* Allocate DMA enabled general use memory for API */
1191 static int
1192 nv_osalloc(void *ctx, MEMORY_BLOCK *mem)
1193 {
1194         struct nv_softc *sc;
1195         bus_addr_t      mem_physical;
1196
1197         DEBUGOUT(NV_DEBUG_API, "nv: nv_osalloc - %d\n", mem->uiLength);
1198
1199         sc = (struct nv_softc *)ctx;
1200
1201         mem->pLogical = (PVOID)contigmalloc(mem->uiLength, M_DEVBUF,
1202                                     M_NOWAIT | M_ZERO, 0, ~0, PAGE_SIZE, 0);
1203
1204         if (!mem->pLogical) {
1205                 device_printf(sc->dev, "memory allocation failed\n");
1206                 return (0);
1207         }
1208         memset(mem->pLogical, 0, (ulong)mem->uiLength);
1209         mem_physical = vtophys(mem->pLogical);
1210         mem->pPhysical = (PVOID)mem_physical;
1211
1212         DEBUGOUT(NV_DEBUG_API, "nv: nv_osalloc 0x%x/0x%x - %d\n",
1213                  (u_int32_t) mem->pLogical,
1214                  (u_int32_t) mem->pPhysical, mem->uiLength);
1215
1216         return (1);
1217 }
1218
1219 /* Free allocated memory */
1220 static int
1221 nv_osfree(void *ctx, MEMORY_BLOCK *mem)
1222 {
1223         DEBUGOUT(NV_DEBUG_API, "nv: nv_osfree - 0x%x - %d\n",
1224                  (u_int32_t) mem->pLogical, mem->uiLength);
1225
1226         contigfree(mem->pLogical, PAGE_SIZE, M_DEVBUF);
1227         return (1);
1228 }
1229
1230 /* Copied directly from nvnet.c */
1231 static int
1232 nv_osallocex(void *ctx, MEMORY_BLOCKEX *mem_block_ex)
1233 {
1234         MEMORY_BLOCK    mem_block;
1235
1236         DEBUGOUT(NV_DEBUG_API, "nv: nv_osallocex\n");
1237
1238         mem_block_ex->pLogical = NULL;
1239         mem_block_ex->uiLengthOrig = mem_block_ex->uiLength;
1240
1241         if ((mem_block_ex->AllocFlags & ALLOC_MEMORY_ALIGNED) &&
1242             (mem_block_ex->AlignmentSize > 1)) {
1243                 DEBUGOUT(NV_DEBUG_API, "     aligning on %d\n",
1244                          mem_block_ex->AlignmentSize);
1245                 mem_block_ex->uiLengthOrig += mem_block_ex->AlignmentSize;
1246         }
1247         mem_block.uiLength = mem_block_ex->uiLengthOrig;
1248
1249         if (nv_osalloc(ctx, &mem_block) == 0) {
1250                 return (0);
1251         }
1252         mem_block_ex->pLogicalOrig = mem_block.pLogical;
1253         mem_block_ex->pPhysicalOrigLow = (ULONG)mem_block.pPhysical;
1254         mem_block_ex->pPhysicalOrigHigh = 0;
1255
1256         mem_block_ex->pPhysical = mem_block.pPhysical;
1257         mem_block_ex->pLogical = mem_block.pLogical;
1258
1259         if (mem_block_ex->uiLength != mem_block_ex->uiLengthOrig) {
1260                 unsigned int    offset;
1261                 offset = mem_block_ex->pPhysicalOrigLow & (mem_block_ex->AlignmentSize - 1);
1262
1263                 if (offset) {
1264                         mem_block_ex->pPhysical = (PVOID)((ULONG)mem_block_ex->pPhysical +
1265                                       mem_block_ex->AlignmentSize - offset);
1266                         mem_block_ex->pLogical = (PVOID)((ULONG)mem_block_ex->pLogical +
1267                                       mem_block_ex->AlignmentSize - offset);
1268                 }               /* if (offset) */
1269         }                       /* if (mem_block_ex->uiLength !=
1270                                  * mem_block_ex->uiLengthOrig) */
1271         return (1);
1272 }
1273
1274 /* Copied directly from nvnet.c */
1275 static int
1276 nv_osfreeex(void *ctx, MEMORY_BLOCKEX *mem_block_ex)
1277 {
1278         MEMORY_BLOCK    mem_block;
1279
1280         DEBUGOUT(NV_DEBUG_API, "nv: nv_osfreeex\n");
1281
1282         mem_block.pLogical = mem_block_ex->pLogicalOrig;
1283         mem_block.pPhysical = (PVOID)mem_block_ex->pPhysicalOrigLow;
1284         mem_block.uiLength = mem_block_ex->uiLengthOrig;
1285
1286         return (nv_osfree(ctx, &mem_block));
1287 }
1288
1289 /* Clear memory region */
1290 static int
1291 nv_osclear(void *ctx, void *mem, int length)
1292 {
1293         DEBUGOUT(NV_DEBUG_API, "nv: nv_osclear\n");
1294         memset(mem, 0, length);
1295         return (1);
1296 }
1297
1298 /* Sleep for a tick */
1299 static int
1300 nv_osdelay(void *ctx, unsigned long usec)
1301 {
1302         DELAY(usec);
1303         return (1);
1304 }
1305
1306 /* Allocate memory for rx buffer */
1307 static int
1308 nv_osallocrxbuf(void *ctx, MEMORY_BLOCK *mem, void **id)
1309 {
1310         struct nv_softc *sc = ctx;
1311         struct nv_rx_desc *desc;
1312         struct nv_map_buffer *buf;
1313         int             error;
1314
1315         NV_LOCK(sc);
1316
1317         DEBUGOUT(NV_DEBUG_API, "nv: nv_osallocrxbuf\n");
1318
1319         if (sc->pending_rxs == RX_RING_SIZE) {
1320                 device_printf(sc->dev, "rx ring buffer is full\n");
1321                 goto fail;
1322         }
1323         desc = sc->rx_desc + sc->cur_rx;
1324         buf = &desc->buf;
1325
1326         if (buf->mbuf == NULL) {
1327                 buf->mbuf = m_getcl(MB_DONTWAIT, MT_DATA, M_PKTHDR);
1328                 if (buf->mbuf == NULL) {
1329                         device_printf(sc->dev, "failed to allocate memory\n");
1330                         goto fail;
1331                 }
1332                 buf->mbuf->m_len = buf->mbuf->m_pkthdr.len = MCLBYTES;
1333                 m_adj(buf->mbuf, ETHER_ALIGN);
1334
1335                 error = bus_dmamap_load_mbuf(sc->mtag, buf->map, buf->mbuf,
1336                                           nv_dmamap_rx_cb, &desc->paddr, 0);
1337                 if (error) {
1338                         device_printf(sc->dev, "failed to dmamap mbuf\n");
1339                         m_freem(buf->mbuf);
1340                         buf->mbuf = NULL;
1341                         goto fail;
1342                 }
1343                 bus_dmamap_sync(sc->mtag, buf->map, BUS_DMASYNC_PREREAD);
1344                 desc->buflength = buf->mbuf->m_len;
1345                 desc->vaddr = mtod(buf->mbuf, PVOID);
1346         }
1347         sc->pending_rxs++;
1348         sc->cur_rx = (sc->cur_rx + 1) % RX_RING_SIZE;
1349
1350         mem->pLogical = (void *)desc->vaddr;
1351         mem->pPhysical = (void *)desc->paddr;
1352         mem->uiLength = desc->buflength;
1353         *id = (void *)desc;
1354
1355 fail:
1356         NV_UNLOCK(sc);
1357
1358         return (1);
1359 }
1360
1361
1362 /* Free the rx buffer */
1363 static int
1364 nv_osfreerxbuf(void *ctx, MEMORY_BLOCK *mem, void *id)
1365 {
1366         struct nv_softc *sc = ctx;
1367         struct nv_rx_desc *desc;
1368         struct nv_map_buffer *buf;
1369
1370         NV_LOCK(sc);
1371
1372         DEBUGOUT(NV_DEBUG_API, "nv: nv_osfreerxbuf\n");
1373
1374         desc = (struct nv_rx_desc *) id;
1375         buf = &desc->buf;
1376
1377         if (buf->mbuf) {
1378                 bus_dmamap_unload(sc->mtag, buf->map);
1379                 bus_dmamap_destroy(sc->mtag, buf->map);
1380                 m_freem(buf->mbuf);
1381         }
1382         sc->pending_rxs--;
1383         buf->mbuf = NULL;
1384
1385         NV_UNLOCK(sc);
1386
1387         return (1);
1388 }
1389
1390 /* This gets called by the Nvidia API after our TX packet has been sent */
1391 static int
1392 nv_ospackettx(void *ctx, void *id, unsigned long success)
1393 {
1394         struct nv_softc *sc = ctx;
1395         struct nv_map_buffer *buf;
1396         struct nv_tx_desc *desc = (struct nv_tx_desc *) id;
1397         struct ifnet   *ifp;
1398
1399         NV_LOCK(sc);
1400
1401         DEBUGOUT(NV_DEBUG_API, "nv: nv_ospackettx\n");
1402
1403         ifp = &sc->sc_if;
1404
1405         buf = &desc->buf;
1406
1407         if (buf->mbuf == NULL)
1408                 goto fail;
1409
1410         bus_dmamap_sync(sc->mtag, buf->map, BUS_DMASYNC_POSTWRITE);
1411         bus_dmamap_unload(sc->mtag, buf->map);
1412         m_freem(buf->mbuf);
1413         buf->mbuf = NULL;
1414
1415         sc->pending_txs--;
1416
1417         if (ifp->if_snd.ifq_head != NULL && sc->pending_txs < TX_RING_SIZE)
1418                 nv_ifstart(ifp);
1419
1420 fail:
1421         NV_UNLOCK(sc);
1422
1423         return (1);
1424 }
1425
1426 /* This gets called by the Nvidia API when a new packet has been received */
1427 /* XXX What is newbuf used for? XXX */
1428 static int
1429 nv_ospacketrx(void *ctx, void *data, unsigned long success,
1430               unsigned char *newbuf, unsigned char priority)
1431 {
1432         struct nv_softc *sc = ctx;
1433         struct ifnet   *ifp;
1434         struct nv_rx_desc *desc;
1435         struct nv_map_buffer *buf;
1436         ADAPTER_READ_DATA *readdata;
1437         NV_LOCK(sc);
1438
1439         DEBUGOUT(NV_DEBUG_API, "nv: nv_ospacketrx\n");
1440
1441         ifp = &sc->sc_if;
1442
1443         readdata = (ADAPTER_READ_DATA *) data;
1444         desc = readdata->pvID;
1445         buf = &desc->buf;
1446         bus_dmamap_sync(sc->mtag, buf->map, BUS_DMASYNC_POSTREAD);
1447
1448         if (success) {
1449                 /* Sync DMA bounce buffer. */
1450                 bus_dmamap_sync(sc->mtag, buf->map, BUS_DMASYNC_POSTREAD);
1451
1452                 /* First mbuf in packet holds the ethernet and packet headers */
1453                 buf->mbuf->m_pkthdr.rcvif = ifp;
1454                 buf->mbuf->m_pkthdr.len = buf->mbuf->m_len = readdata->ulTotalLength;
1455
1456                 bus_dmamap_unload(sc->mtag, buf->map);
1457
1458                 /* Give mbuf to OS. */
1459                 (*ifp->if_input) (ifp, buf->mbuf);
1460                 if (readdata->ulFilterMatch & ADREADFL_MULTICAST_MATCH)
1461                         ifp->if_imcasts++;
1462
1463                 /* Blat the mbuf pointer, kernel will free the mbuf cluster */
1464                 buf->mbuf = NULL;
1465         } else {
1466                 bus_dmamap_sync(sc->mtag, buf->map, BUS_DMASYNC_POSTREAD);
1467                 bus_dmamap_unload(sc->mtag, buf->map);
1468                 m_freem(buf->mbuf);
1469                 buf->mbuf = NULL;
1470         }
1471
1472         sc->cur_rx = desc - sc->rx_desc;
1473         sc->pending_rxs--;
1474
1475         NV_UNLOCK(sc);
1476
1477         return (1);
1478 }
1479
1480 /* This gets called by NVIDIA API when the PHY link state changes */
1481 static int
1482 nv_oslinkchg(void *ctx, int enabled)
1483 {
1484         struct nv_softc *sc = (struct nv_softc *)ctx;
1485         struct ifnet   *ifp;
1486
1487         DEBUGOUT(NV_DEBUG_API, "nv: nv_oslinkchg\n");
1488
1489         ifp = &sc->sc_if;
1490
1491         if (enabled)
1492                 ifp->if_flags |= IFF_UP;
1493         else
1494                 ifp->if_flags &= ~IFF_UP;
1495
1496
1497         return (1);
1498 }
1499
1500
1501 /* Setup a watchdog timer */
1502 static int
1503 nv_osalloctimer(void *ctx, void **timer)
1504 {
1505         struct nv_softc *sc = (struct nv_softc *)ctx;
1506
1507         DEBUGOUT(NV_DEBUG_BROKEN, "nv: nv_osalloctimer\n");
1508
1509         callout_init(&sc->ostimer);
1510         *timer = &sc->ostimer;
1511
1512         return (1);
1513 }
1514
1515 /* Free the timer */
1516 static int
1517 nv_osfreetimer(void *ctx, void *timer)
1518 {
1519         DEBUGOUT(NV_DEBUG_BROKEN, "nv: nv_osfreetimer\n");
1520
1521         return (1);
1522 }
1523
1524 /* Setup timer parameters */
1525 static int
1526 nv_osinittimer(void *ctx, void *timer, PTIMER_FUNC func, void *parameters)
1527 {
1528         struct nv_softc *sc = (struct nv_softc *)ctx;
1529
1530         DEBUGOUT(NV_DEBUG_BROKEN, "nv: nv_osinittimer\n");
1531
1532         sc->ostimer_func = func;
1533         sc->ostimer_params = parameters;
1534
1535         return (1);
1536 }
1537
1538 /* Set the timer to go off */
1539 static int
1540 nv_ossettimer(void *ctx, void *timer, unsigned long delay)
1541 {
1542         struct nv_softc *sc = ctx;
1543
1544         DEBUGOUT(NV_DEBUG_BROKEN, "nv: nv_ossettimer\n");
1545
1546         callout_reset(&sc->ostimer, delay, sc->ostimer_func,
1547                       sc->ostimer_params);
1548
1549         return (1);
1550 }
1551
1552 /* Cancel the timer */
1553 static int
1554 nv_oscanceltimer(void *ctx, void *timer)
1555 {
1556         struct nv_softc *sc = ctx;
1557
1558         DEBUGOUT(NV_DEBUG_BROKEN, "nv: nv_oscanceltimer\n");
1559
1560         callout_stop(&sc->ostimer);
1561
1562         return (1);
1563 }
1564
1565 static int
1566 nv_ospreprocpkt(void *ctx, void *readdata, void **id, unsigned char *newbuffer,
1567                 unsigned char priority)
1568 {
1569         /* Not implemented */
1570         DEBUGOUT(NV_DEBUG_BROKEN, "nv: nv_ospreprocpkt\n");
1571
1572         return (1);
1573 }
1574
1575 static void
1576                *
1577 nv_ospreprocpktnopq(void *ctx, void *readdata)
1578 {
1579         /* Not implemented */
1580         DEBUGOUT(NV_DEBUG_BROKEN, "nv: nv_ospreprocpkt\n");
1581
1582         return (NULL);
1583 }
1584
1585 static int
1586 nv_osindicatepkt(void *ctx, void **id, unsigned long pktno)
1587 {
1588         /* Not implemented */
1589         DEBUGOUT(NV_DEBUG_BROKEN, "nv: nv_osindicatepkt\n");
1590
1591         return (1);
1592 }
1593
1594 /* Allocate mutex context (already done in nv_attach) */
1595 static int
1596 nv_oslockalloc(void *ctx, int type, void **pLock)
1597 {
1598         struct nv_softc *sc = (struct nv_softc *)ctx;
1599
1600         DEBUGOUT(NV_DEBUG_LOCK, "nv: nv_oslockalloc\n");
1601
1602         *pLock = (void **)sc;
1603
1604         return (1);
1605 }
1606
1607 /* Obtain a spin lock */
1608 static int
1609 nv_oslockacquire(void *ctx, int type, void *lock)
1610 {
1611         DEBUGOUT(NV_DEBUG_LOCK, "nv: nv_oslockacquire\n");
1612
1613         NV_OSLOCK((struct nv_softc *)lock);
1614
1615         return (1);
1616 }
1617
1618 /* Release lock */
1619 static int
1620 nv_oslockrelease(void *ctx, int type, void *lock)
1621 {
1622         DEBUGOUT(NV_DEBUG_LOCK, "nv: nv_oslockrelease\n");
1623
1624         NV_OSUNLOCK((struct nv_softc *)lock);
1625
1626         return (1);
1627 }
1628
1629 /* I have no idea what this is for */
1630 static void    *
1631 nv_osreturnbufvirt(void *ctx, void *readdata)
1632 {
1633         /* Not implemented */
1634         DEBUGOUT(NV_DEBUG_LOCK, "nv: nv_osreturnbufvirt\n");
1635         panic("nv: nv_osreturnbufvirtual not implemented\n");
1636
1637         return (NULL);
1638 }
1639
1640
1641 /* --- End on NVOSAPI interface --- */