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