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