Use bus_alloc_resource_any when possible.
[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.11 2005/05/24 09:52:14 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_any(dev, SYS_RES_MEMORY, &rid, RF_ACTIVE);
306
307         if (sc->res == NULL) {
308                 device_printf(dev, "couldn't map memory\n");
309                 error = ENXIO;
310                 goto fail;
311         }
312         sc->sc_st = rman_get_bustag(sc->res);
313         sc->sc_sh = rman_get_bushandle(sc->res);
314
315         /* Allocate interrupt */
316         rid = 0;
317         sc->irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
318             RF_SHAREABLE | RF_ACTIVE);
319
320         if (sc->irq == NULL) {
321                 device_printf(dev, "couldn't map interrupt\n");
322                 error = ENXIO;
323                 goto fail;
324         }
325         /* Allocate DMA tags */
326         error = bus_dma_tag_create(NULL, 4, 0, BUS_SPACE_MAXADDR_32BIT,
327                      BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES * NV_MAX_FRAGS,
328                                    NV_MAX_FRAGS, MCLBYTES, 0,
329                                    &sc->mtag);
330         if (error) {
331                 device_printf(dev, "couldn't allocate dma tag\n");
332                 goto fail;
333         }
334         error = bus_dma_tag_create(NULL, 4, 0, BUS_SPACE_MAXADDR_32BIT,
335                                    BUS_SPACE_MAXADDR, NULL, NULL,
336                                 sizeof(struct nv_rx_desc) * RX_RING_SIZE, 1,
337                                 sizeof(struct nv_rx_desc) * RX_RING_SIZE, 0,
338                                    &sc->rtag);
339         if (error) {
340                 device_printf(dev, "couldn't allocate dma tag\n");
341                 goto fail;
342         }
343         error = bus_dma_tag_create(NULL, 4, 0, BUS_SPACE_MAXADDR_32BIT,
344                                    BUS_SPACE_MAXADDR, NULL, NULL,
345                                 sizeof(struct nv_tx_desc) * TX_RING_SIZE, 1,
346                                 sizeof(struct nv_tx_desc) * TX_RING_SIZE, 0,
347                                    &sc->ttag);
348         if (error) {
349                 device_printf(dev, "couldn't allocate dma tag\n");
350                 goto fail;
351         }
352
353         error = bus_dmamap_create(sc->ttag, 0, &sc->tmap);
354         if (error) {
355                 device_printf(dev, "couldn't create dma map\n");
356                 goto fail;
357         }
358
359         /* Allocate DMA safe memory and get the DMA addresses. */
360         error = bus_dmamem_alloc(sc->ttag, (void **)&sc->tx_desc,
361                                  BUS_DMA_WAITOK | BUS_DMA_ZERO, &sc->tmap);
362         if (error) {
363                 device_printf(dev, "couldn't allocate dma memory\n");
364                 goto fail;
365         }
366         error = bus_dmamap_load(sc->ttag, sc->tmap, sc->tx_desc,
367                      sizeof(struct nv_tx_desc) * TX_RING_SIZE, nv_dmamap_cb,
368                                 &sc->tx_addr, 0);
369         if (error) {
370                 device_printf(dev, "couldn't map dma memory\n");
371                 goto fail;
372         }
373
374         error = bus_dmamap_create(sc->rtag, 0, &sc->rmap);
375         if (error) {
376                 device_printf(dev, "couldn't create dma map\n");
377                 goto fail;
378         }
379
380         error = bus_dmamem_alloc(sc->rtag, (void **)&sc->rx_desc,
381                                  BUS_DMA_WAITOK | BUS_DMA_ZERO, &sc->rmap);
382         if (error) {
383                 device_printf(dev, "couldn't allocate dma memory\n");
384                 goto fail;
385         }
386         error = bus_dmamap_load(sc->rtag, sc->rmap, sc->rx_desc,
387                      sizeof(struct nv_rx_desc) * RX_RING_SIZE, nv_dmamap_cb,
388                                 &sc->rx_addr, 0);
389         if (error) {
390                 device_printf(dev, "couldn't map dma memory\n");
391                 goto fail;
392         }
393         /* Initialize rings. */
394         if (nv_init_rings(sc)) {
395                 device_printf(dev, "failed to init rings\n");
396                 error = ENXIO;
397                 goto fail;
398         }
399         /* Setup NVIDIA API callback routines */
400         osapi = &sc->osapi;
401         osapi->pOSCX = sc;
402         osapi->pfnAllocMemory = nv_osalloc;
403         osapi->pfnFreeMemory = nv_osfree;
404         osapi->pfnAllocMemoryEx = nv_osallocex;
405         osapi->pfnFreeMemoryEx = nv_osfreeex;
406         osapi->pfnClearMemory = nv_osclear;
407         osapi->pfnStallExecution = nv_osdelay;
408         osapi->pfnAllocReceiveBuffer = nv_osallocrxbuf;
409         osapi->pfnFreeReceiveBuffer = nv_osfreerxbuf;
410         osapi->pfnPacketWasSent = nv_ospackettx;
411         osapi->pfnPacketWasReceived = nv_ospacketrx;
412         osapi->pfnLinkStateHasChanged = nv_oslinkchg;
413         osapi->pfnAllocTimer = nv_osalloctimer;
414         osapi->pfnFreeTimer = nv_osfreetimer;
415         osapi->pfnInitializeTimer = nv_osinittimer;
416         osapi->pfnSetTimer = nv_ossettimer;
417         osapi->pfnCancelTimer = nv_oscanceltimer;
418         osapi->pfnPreprocessPacket = nv_ospreprocpkt;
419         osapi->pfnPreprocessPacketNopq = nv_ospreprocpktnopq;
420         osapi->pfnIndicatePackets = nv_osindicatepkt;
421         osapi->pfnLockAlloc = nv_oslockalloc;
422         osapi->pfnLockAcquire = nv_oslockacquire;
423         osapi->pfnLockRelease = nv_oslockrelease;
424         osapi->pfnReturnBufferVirtual = nv_osreturnbufvirt;
425
426         sc->linkup = FALSE;
427         sc->max_frame_size = ETHERMTU + ETHER_HDR_LEN + FCS_LEN;
428
429         /* TODO - We don't support hardware offload yet */
430         sc->hwmode = 1;
431         sc->media = 0;
432
433         /* Set NVIDIA API startup parameters */
434         OpenParams.MaxDpcLoop = 2;
435         OpenParams.MaxRxPkt = RX_RING_SIZE;
436         OpenParams.MaxTxPkt = TX_RING_SIZE;
437         OpenParams.SentPacketStatusSuccess = 1;
438         OpenParams.SentPacketStatusFailure = 0;
439         OpenParams.MaxRxPktToAccumulate = 6;
440         OpenParams.ulPollInterval = nv_pollinterval;
441         OpenParams.SetForcedModeEveryNthRxPacket = 0;
442         OpenParams.SetForcedModeEveryNthTxPacket = 0;
443         OpenParams.RxForcedInterrupt = 0;
444         OpenParams.TxForcedInterrupt = 0;
445         OpenParams.pOSApi = osapi;
446         OpenParams.pvHardwareBaseAddress = rman_get_virtual(sc->res);
447         OpenParams.bASFEnabled = 0;
448         OpenParams.ulDescriptorVersion = sc->hwmode;
449         OpenParams.ulMaxPacketSize = sc->max_frame_size;
450         OpenParams.DeviceId = pci_get_device(dev);
451
452         /* Open NVIDIA Hardware API */
453         error = ADAPTER_Open(&OpenParams, (void **)&(sc->hwapi), &sc->phyaddr);
454         if (error) {
455                 device_printf(dev, "failed to open NVIDIA Hardware API: 0x%x\n", error);
456                 goto fail;
457         }
458         
459         /* TODO - Add support for MODE2 hardware offload */ 
460
461         bzero(&sc->adapterdata, sizeof(sc->adapterdata));
462
463         sc->adapterdata.ulMediaIF = sc->media;
464         sc->adapterdata.ulModeRegTxReadCompleteEnable = 1;
465         sc->hwapi->pfnSetCommonData(sc->hwapi->pADCX, &sc->adapterdata);
466
467         /* MAC is loaded backwards into h/w reg */
468         sc->hwapi->pfnGetNodeAddress(sc->hwapi->pADCX, sc->original_mac_addr);
469         for (i = 0; i < 6; i++) {
470                 eaddr[i] = sc->original_mac_addr[5 - i];
471         }
472         sc->hwapi->pfnSetNodeAddress(sc->hwapi->pADCX, eaddr);
473         bcopy(eaddr, (char *)&sc->sc_macaddr, ETHER_ADDR_LEN);
474
475         DEBUGOUT(NV_DEBUG_INIT, "nv: do mii_phy_probe\n");
476
477         /* Probe device for MII interface to PHY */
478         if (mii_phy_probe(dev, &sc->miibus,
479                           nv_ifmedia_upd, nv_ifmedia_sts)) {
480                 device_printf(dev, "MII without any phy!\n");
481                 error = ENXIO;
482                 goto fail;
483         }
484         /* Setup interface parameters */
485         ifp = &sc->sc_if;
486         ifp->if_softc = sc;
487         if_initname(ifp, device_get_name(dev), device_get_unit(dev));
488         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
489         ifp->if_ioctl = nv_ioctl;
490         ifp->if_start = nv_ifstart;
491         ifp->if_watchdog = nv_watchdog;
492         ifp->if_timer = 0;
493         ifp->if_init = nv_init;
494         ifp->if_mtu = ETHERMTU;
495         ifp->if_baudrate = IF_Mbps(100);
496         ifp->if_capabilities |= IFCAP_VLAN_MTU;
497         ifq_set_maxlen(&ifp->if_snd, TX_RING_SIZE - 1);
498         ifq_set_ready(&ifp->if_snd);
499
500         /* Attach to OS's managers. */
501         ether_ifattach(ifp, sc->sc_macaddr);
502
503         /* Activate our interrupt handler. - attach last to avoid lock */
504         error = bus_setup_intr(sc->dev, sc->irq, INTR_TYPE_NET,
505                                nv_intr, sc, &sc->sc_ih);
506         if (error) {
507                 device_printf(sc->dev, "couldn't set up interrupt handler\n");
508                 goto fail;
509         }
510         DEBUGOUT(NV_DEBUG_INIT, "nv: nv_attach - exit\n");
511
512 fail:
513         if (error)
514                 nv_detach(dev);
515
516         return (error);
517 }
518
519 /* Detach interface for module unload */
520 static int
521 nv_detach(device_t dev)
522 {
523         struct nv_softc *sc = device_get_softc(dev);
524         struct ifnet   *ifp;
525
526         NV_LOCK(sc);
527
528         DEBUGOUT(NV_DEBUG_DEINIT, "nv: nv_detach - entry\n");
529
530         ifp = &sc->arpcom.ac_if;
531
532         if (device_is_attached(dev)) {
533                 nv_stop(sc);
534                 ether_ifdetach(ifp);
535         }
536
537         if (sc->miibus)
538                 device_delete_child(dev, sc->miibus);
539         bus_generic_detach(dev);
540
541         /* Reload unreversed address back into MAC in original state */
542         if (sc->original_mac_addr)
543                 sc->hwapi->pfnSetNodeAddress(sc->hwapi->pADCX, sc->original_mac_addr);
544
545         DEBUGOUT(NV_DEBUG_DEINIT, "nv: do pfnClose\n");
546         /* Detach from NVIDIA hardware API */
547         if (sc->hwapi->pfnClose)
548                 sc->hwapi->pfnClose(sc->hwapi->pADCX, FALSE);
549         /* Release resources */
550         if (sc->sc_ih)
551                 bus_teardown_intr(sc->dev, sc->irq, sc->sc_ih);
552         if (sc->irq)
553                 bus_release_resource(sc->dev, SYS_RES_IRQ, 0, sc->irq);
554         if (sc->res)
555                 bus_release_resource(sc->dev, SYS_RES_MEMORY, NV_RID, sc->res);
556
557         nv_free_rings(sc);
558
559         if (sc->tx_desc) {
560                 bus_dmamap_unload(sc->rtag, sc->rmap);
561                 bus_dmamem_free(sc->rtag, sc->rx_desc, sc->rmap);
562                 bus_dmamap_destroy(sc->rtag, sc->rmap);
563         }
564         if (sc->mtag)
565                 bus_dma_tag_destroy(sc->mtag);
566         if (sc->ttag)
567                 bus_dma_tag_destroy(sc->ttag);
568         if (sc->rtag)
569                 bus_dma_tag_destroy(sc->rtag);
570
571         NV_UNLOCK(sc);
572
573         DEBUGOUT(NV_DEBUG_DEINIT, "nv: nv_detach - exit\n");
574
575         return (0);
576 }
577
578 /* Initialise interface and start it "RUNNING" */
579 static void
580 nv_init(void *xsc)
581 {
582         struct nv_softc *sc = xsc;
583         struct ifnet   *ifp;
584         int             error;
585
586         NV_LOCK(sc);
587
588         DEBUGOUT(NV_DEBUG_INIT, "nv: nv_init - entry (%d)\n", sc->linkup);
589
590         ifp = &sc->sc_if;
591
592         /* Do nothing if already running */
593         if (ifp->if_flags & IFF_RUNNING)
594                 goto fail;
595
596         nv_stop(sc);
597
598         DEBUGOUT(NV_DEBUG_INIT, "nv: do pfnInit\n");
599         /* Setup Hardware interface and allocate memory structures */
600         error = sc->hwapi->pfnInit(sc->hwapi->pADCX, 
601                                    0, /* force speed */ 
602                                    0, /* force full duplex */
603                                    0, /* force mode */
604                                    0, /* force async mode */
605                                    &sc->linkup);
606
607         if (error) {
608                 device_printf(sc->dev, "failed to start NVIDIA Hardware interface\n");
609                 goto fail;
610         }
611         /* Set the MAC address */
612         sc->hwapi->pfnSetNodeAddress(sc->hwapi->pADCX, sc->sc_macaddr);
613         sc->hwapi->pfnEnableInterrupts(sc->hwapi->pADCX);
614         sc->hwapi->pfnStart(sc->hwapi->pADCX);
615
616         /* Setup multicast filter */
617         nv_setmulti(sc);
618         nv_ifmedia_upd(ifp);
619
620         /* Update interface parameters */
621         ifp->if_flags |= IFF_RUNNING;
622         ifp->if_flags &= ~IFF_OACTIVE;
623
624         callout_reset(&sc->nv_stat_timer, hz, nv_tick, sc);
625
626         DEBUGOUT(NV_DEBUG_INIT, "nv: nv_init - exit\n");
627
628 fail:
629         NV_UNLOCK(sc);
630
631         return;
632 }
633
634 /* Stop interface activity ie. not "RUNNING" */
635 static void
636 nv_stop(struct nv_softc *sc)
637 {
638         struct ifnet   *ifp;
639
640         NV_LOCK(sc);
641
642         DEBUGOUT(NV_DEBUG_RUNNING, "nv: nv_stop - entry\n");
643
644         ifp = &sc->sc_if;
645         ifp->if_timer = 0;
646
647         /* Cancel tick timer */
648         callout_stop(&sc->nv_stat_timer);
649
650         /* Stop hardware activity */
651         sc->hwapi->pfnDisableInterrupts(sc->hwapi->pADCX);
652         sc->hwapi->pfnStop(sc->hwapi->pADCX, 0);
653
654         DEBUGOUT(NV_DEBUG_DEINIT, "nv: do pfnDeinit\n");
655         /* Shutdown interface and deallocate memory buffers */
656         if (sc->hwapi->pfnDeinit)
657                 sc->hwapi->pfnDeinit(sc->hwapi->pADCX, 0);
658
659         sc->linkup = 0;
660         sc->cur_rx = 0;
661         sc->pending_rxs = 0;
662
663         ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
664
665         DEBUGOUT(NV_DEBUG_RUNNING, "nv: nv_stop - exit\n");
666
667         NV_UNLOCK(sc);
668
669         return;
670 }
671
672 /* Shutdown interface for unload/reboot */
673 static void
674 nv_shutdown(device_t dev)
675 {
676         struct nv_softc *sc;
677
678         DEBUGOUT(NV_DEBUG_DEINIT, "nv: nv_shutdown\n");
679
680         sc = device_get_softc(dev);
681
682         /* Stop hardware activity */
683         nv_stop(sc);
684 }
685
686 /* Allocate TX ring buffers */
687 static int
688 nv_init_rings(struct nv_softc *sc)
689 {
690         int             error, i;
691
692         NV_LOCK(sc);
693
694         DEBUGOUT(NV_DEBUG_INIT, "nv: nv_init_rings - entry\n");
695
696         sc->cur_rx = sc->cur_tx = sc->pending_rxs = sc->pending_txs = 0;
697         /* Initialise RX ring */
698         for (i = 0; i < RX_RING_SIZE; i++) {
699                 struct nv_rx_desc *desc = sc->rx_desc + i;
700                 struct nv_map_buffer *buf = &desc->buf;
701
702                 buf->mbuf = m_getcl(MB_DONTWAIT, MT_DATA, M_PKTHDR);
703                 if (buf->mbuf == NULL) {
704                         device_printf(sc->dev, "couldn't allocate mbuf\n");
705                         nv_free_rings(sc);
706                         error = ENOBUFS;
707                         goto fail;
708                 }
709                 buf->mbuf->m_len = buf->mbuf->m_pkthdr.len = MCLBYTES;
710                 m_adj(buf->mbuf, ETHER_ALIGN);
711
712                 error = bus_dmamap_create(sc->mtag, 0, &buf->map);
713                 if (error) {
714                         device_printf(sc->dev, "couldn't create dma map\n");
715                         nv_free_rings(sc);
716                         goto fail;
717                 }
718                 error = bus_dmamap_load_mbuf(sc->mtag, buf->map, buf->mbuf,
719                                           nv_dmamap_rx_cb, &desc->paddr, 0);
720                 if (error) {
721                         device_printf(sc->dev, "couldn't dma map mbuf\n");
722                         nv_free_rings(sc);
723                         goto fail;
724                 }
725                 bus_dmamap_sync(sc->mtag, buf->map, BUS_DMASYNC_PREREAD);
726
727                 desc->buflength = buf->mbuf->m_len;
728                 desc->vaddr = mtod(buf->mbuf, caddr_t);
729         }
730         bus_dmamap_sync(sc->rtag, sc->rmap,
731                         BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
732
733         /* Initialize TX ring */
734         for (i = 0; i < TX_RING_SIZE; i++) {
735                 struct nv_tx_desc *desc = sc->tx_desc + i;
736                 struct nv_map_buffer *buf = &desc->buf;
737
738                 buf->mbuf = NULL;
739
740                 error = bus_dmamap_create(sc->mtag, 0, &buf->map);
741                 if (error) {
742                         device_printf(sc->dev, "couldn't create dma map\n");
743                         nv_free_rings(sc);
744                         goto fail;
745                 }
746         }
747         bus_dmamap_sync(sc->ttag, sc->tmap,
748                         BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
749
750         DEBUGOUT(NV_DEBUG_INIT, "nv: nv_init_rings - exit\n");
751
752 fail:
753         NV_UNLOCK(sc);
754
755         return (error);
756 }
757
758 /* Free the TX ring buffers */
759 static void
760 nv_free_rings(struct nv_softc *sc)
761 {
762         int             i;
763
764         NV_LOCK(sc);
765
766         DEBUGOUT(NV_DEBUG_DEINIT, "nv: nv_free_rings - entry\n");
767
768         for (i = 0; i < RX_RING_SIZE; i++) {
769                 struct nv_rx_desc *desc = sc->rx_desc + i;
770                 struct nv_map_buffer *buf = &desc->buf;
771
772                 if (buf->mbuf) {
773                         bus_dmamap_unload(sc->mtag, buf->map);
774                         bus_dmamap_destroy(sc->mtag, buf->map);
775                         m_freem(buf->mbuf);
776                 }
777                 buf->mbuf = NULL;
778         }
779
780         for (i = 0; i < TX_RING_SIZE; i++) {
781                 struct nv_tx_desc *desc = sc->tx_desc + i;
782                 struct nv_map_buffer *buf = &desc->buf;
783
784                 if (buf->mbuf) {
785                         bus_dmamap_unload(sc->mtag, buf->map);
786                         bus_dmamap_destroy(sc->mtag, buf->map);
787                         m_freem(buf->mbuf);
788                 }
789                 buf->mbuf = NULL;
790         }
791
792         DEBUGOUT(NV_DEBUG_DEINIT, "nv: nv_free_rings - exit\n");
793
794         NV_UNLOCK(sc);
795 }
796
797 /* Main loop for sending packets from OS to interface */
798 static void
799 nv_ifstart(struct ifnet *ifp)
800 {
801         struct nv_softc *sc = ifp->if_softc;
802         struct nv_map_buffer *buf;
803         struct mbuf    *m0, *m;
804         struct nv_tx_desc *desc;
805         ADAPTER_WRITE_DATA txdata;
806         int             error, i;
807
808         DEBUGOUT(NV_DEBUG_RUNNING, "nv: nv_ifstart - entry\n");
809
810         /* If link is down/busy or queue is empty do nothing */
811         if (ifp->if_flags & IFF_OACTIVE || ifq_is_empty(&ifp->if_snd))
812                 return;
813
814         /* Transmit queued packets until sent or TX ring is full */
815         while (sc->pending_txs < TX_RING_SIZE) {
816                 desc = sc->tx_desc + sc->cur_tx;
817                 buf = &desc->buf;
818
819                 /* Get next packet to send. */
820                 m0 = ifq_dequeue(&ifp->if_snd);
821
822                 /* If nothing to send, return. */
823                 if (m0 == NULL)
824                         return;
825
826                 /* Map MBUF for DMA access */
827                 error = bus_dmamap_load_mbuf(sc->mtag, buf->map, m0,
828                                      nv_dmamap_tx_cb, desc, BUS_DMA_NOWAIT);
829
830                 if (error && error != EFBIG) {
831                         m_freem(m0);
832                         sc->tx_errors++;
833                         continue;
834                 }
835                 /*
836                  * Packet has too many fragments - defrag into new mbuf
837                  * cluster
838                  */
839                 if (error) {
840                         m = m_defrag(m0, MB_DONTWAIT);
841                         if (m == NULL) {
842                                 m_freem(m0);
843                                 sc->tx_errors++;
844                                 continue;
845                         }
846                         m_freem(m0);
847                         m0 = m;
848
849                         error = bus_dmamap_load_mbuf(sc->mtag, buf->map, m,
850                                      nv_dmamap_tx_cb, desc, BUS_DMA_NOWAIT);
851                         if (error) {
852                                 m_freem(m);
853                                 sc->tx_errors++;
854                                 continue;
855                         }
856                 }
857                 /* Do sync on DMA bounce buffer */
858                 bus_dmamap_sync(sc->mtag, buf->map, BUS_DMASYNC_PREWRITE);
859
860                 buf->mbuf = m0;
861                 txdata.ulNumberOfElements = desc->numfrags;
862                 txdata.pvID = (PVOID)desc;
863
864                 /* Put fragments into API element list */
865                 txdata.ulTotalLength = buf->mbuf->m_len;
866                 for (i = 0; i < desc->numfrags; i++) {
867                         txdata.sElement[i].ulLength = (ulong)desc->frags[i].ds_len;
868                         txdata.sElement[i].pPhysical = (PVOID)desc->frags[i].ds_addr;
869                 }
870
871                 /* Send packet to Nvidia API for transmission */
872                 error = sc->hwapi->pfnWrite(sc->hwapi->pADCX, &txdata);
873
874                 switch (error) {
875                 case ADAPTERERR_NONE:
876                         /* Packet was queued in API TX queue successfully */
877                         sc->pending_txs++;
878                         sc->cur_tx = (sc->cur_tx + 1) % TX_RING_SIZE;
879                         break;
880
881                 case ADAPTERERR_TRANSMIT_QUEUE_FULL:
882                         /* The API TX queue is full - requeue the packet */
883                         device_printf(sc->dev, "nv_ifstart: transmit queue is full\n");
884                         ifp->if_flags |= IFF_OACTIVE;
885                         bus_dmamap_unload(sc->mtag, buf->map);
886                         buf->mbuf = NULL;
887                         return;
888
889                 default:
890                         /* The API failed to queue/send the packet so dump it */
891                         device_printf(sc->dev, "nv_ifstart: transmit error\n");
892                         bus_dmamap_unload(sc->mtag, buf->map);
893                         m_freem(buf->mbuf);
894                         buf->mbuf = NULL;
895                         sc->tx_errors++;
896                         return;
897                 }
898                 /* Set watchdog timer. */
899                 ifp->if_timer = 8;
900
901                 /* Copy packet to BPF tap */
902                 BPF_MTAP(ifp, m0);
903         }
904         ifp->if_flags |= IFF_OACTIVE;
905
906         DEBUGOUT(NV_DEBUG_RUNNING, "nv: nv_ifstart - exit\n");
907 }
908
909 /* Handle IOCTL events */
910 static int
911 nv_ioctl(struct ifnet *ifp, u_long command, caddr_t data, struct ucred *cr)
912 {
913         struct nv_softc *sc = ifp->if_softc;
914         struct ifreq   *ifr = (struct ifreq *) data;
915         struct mii_data *mii;
916         int             error = 0;
917
918         NV_LOCK(sc);
919
920         DEBUGOUT(NV_DEBUG_IOCTL, "nv: nv_ioctl - entry\n");
921
922         switch (command) {
923         case SIOCSIFMTU:
924                 /* Set MTU size */
925                 if (ifp->if_mtu == ifr->ifr_mtu)
926                         break;
927                 if (ifr->ifr_mtu + ifp->if_hdrlen <= MAX_PACKET_SIZE_1518) {
928                         ifp->if_mtu = ifr->ifr_mtu;
929                         nv_stop(sc);
930                         nv_init(sc);
931                 } else
932                         error = EINVAL;
933                 break;
934
935         case SIOCSIFFLAGS:
936                 /* Setup interface flags */
937                 if (ifp->if_flags & IFF_UP) {
938                         if ((ifp->if_flags & IFF_RUNNING) == 0) {
939                                 nv_init(sc);
940                                 break;
941                         }
942                 } else {
943                         if (ifp->if_flags & IFF_RUNNING) {
944                                 nv_stop(sc);
945                                 break;
946                         }
947                 }
948
949                 /* Handle IFF_PROMISC and IFF_ALLMULTI flags. */
950                 nv_setmulti(sc);
951                 break;
952
953         case SIOCADDMULTI:
954         case SIOCDELMULTI:
955                 /* Setup multicast filter */
956                 if (ifp->if_flags & IFF_RUNNING) {
957                         nv_setmulti(sc);
958                 }
959                 break;
960         case SIOCGIFMEDIA:
961         case SIOCSIFMEDIA:
962                 /* Get/Set interface media parameters */
963                 mii = device_get_softc(sc->miibus);
964                 error = ifmedia_ioctl(ifp, ifr, &mii->mii_media, command);
965                 break;
966
967         default:
968                 /* Everything else we forward to generic ether ioctl */
969                 error = ether_ioctl(ifp, (int)command, data);
970                 break;
971         }
972
973         DEBUGOUT(NV_DEBUG_IOCTL, "nv: nv_ioctl - exit\n");
974
975         NV_UNLOCK(sc);
976
977         return (error);
978 }
979
980 /* Interrupt service routine */
981 static void
982 nv_intr(void *arg)
983 {
984         struct nv_softc *sc = arg;
985         struct ifnet   *ifp = &sc->sc_if;
986
987         DEBUGOUT(NV_DEBUG_INTERRUPT, "nv: nv_intr - entry\n");
988
989         if (!ifp->if_flags & IFF_UP) {
990                 nv_stop(sc);
991                 return;
992         }
993         /* Handle interrupt event */
994         if (sc->hwapi->pfnQueryInterrupt(sc->hwapi->pADCX)) {
995                 sc->hwapi->pfnHandleInterrupt(sc->hwapi->pADCX);
996                 sc->hwapi->pfnEnableInterrupts(sc->hwapi->pADCX);
997         }
998         if (!ifq_is_empty(&ifp->if_snd))
999                 nv_ifstart(ifp);
1000
1001         /* If no pending packets we don't need a timeout */
1002         if (sc->pending_txs == 0)
1003                 sc->sc_if.if_timer = 0;
1004
1005         DEBUGOUT(NV_DEBUG_INTERRUPT, "nv: nv_intr - exit\n");
1006
1007         return;
1008 }
1009
1010 /* Setup multicast filters */
1011 static void
1012 nv_setmulti(struct nv_softc *sc)
1013 {
1014         struct ifnet   *ifp;
1015         struct ifmultiaddr *ifma;
1016         PACKET_FILTER   hwfilter;
1017         int             i;
1018         u_int8_t        oraddr[6];
1019         u_int8_t        andaddr[6];
1020
1021         NV_LOCK(sc);
1022
1023         DEBUGOUT(NV_DEBUG_RUNNING, "nv: nv_setmulti - entry\n");
1024
1025         ifp = &sc->sc_if;
1026
1027         /* Initialize filter */
1028         hwfilter.ulFilterFlags = 0;
1029         for (i = 0; i < 6; i++) {
1030                 hwfilter.acMulticastAddress[i] = 0;
1031                 hwfilter.acMulticastMask[i] = 0;
1032         }
1033
1034         if (ifp->if_flags & (IFF_PROMISC | IFF_ALLMULTI)) {
1035                 /* Accept all packets */
1036                 hwfilter.ulFilterFlags |= ACCEPT_ALL_PACKETS;
1037                 sc->hwapi->pfnSetPacketFilter(sc->hwapi->pADCX, &hwfilter);
1038                 NV_UNLOCK(sc);
1039                 return;
1040         }
1041         /* Setup multicast filter */
1042         LIST_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
1043                 u_char         *addrp;
1044
1045                 if (ifma->ifma_addr->sa_family != AF_LINK)
1046                         continue;
1047
1048                 addrp = LLADDR((struct sockaddr_dl *) ifma->ifma_addr);
1049                 for (i = 0; i < 6; i++) {
1050                         u_int8_t        mcaddr = addrp[i];
1051                         andaddr[i] &= mcaddr;
1052                         oraddr[i] |= mcaddr;
1053                 }
1054         }
1055         for (i = 0; i < 6; i++) {
1056                 hwfilter.acMulticastAddress[i] = andaddr[i] & oraddr[i];
1057                 hwfilter.acMulticastMask[i] = andaddr[i] | (~oraddr[i]);
1058         }
1059
1060         /* Send filter to NVIDIA API */
1061         sc->hwapi->pfnSetPacketFilter(sc->hwapi->pADCX, &hwfilter);
1062
1063         NV_UNLOCK(sc);
1064
1065         DEBUGOUT(NV_DEBUG_RUNNING, "nv: nv_setmulti - exit\n");
1066
1067         return;
1068 }
1069
1070 /* Change the current media/mediaopts */
1071 static int
1072 nv_ifmedia_upd(struct ifnet *ifp)
1073 {
1074         struct nv_softc *sc = ifp->if_softc;
1075         struct mii_data *mii;
1076
1077         DEBUGOUT(NV_DEBUG_MII, "nv: nv_ifmedia_upd\n");
1078
1079         mii = device_get_softc(sc->miibus);
1080
1081         if (mii->mii_instance) {
1082                 struct mii_softc *miisc;
1083                 for (miisc = LIST_FIRST(&mii->mii_phys); miisc != NULL;
1084                      miisc = LIST_NEXT(miisc, mii_list)) {
1085                         mii_phy_reset(miisc);
1086                 }
1087         }
1088         mii_mediachg(mii);
1089
1090         return (0);
1091 }
1092
1093 /* Update current miibus PHY status of media */
1094 static void
1095 nv_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr)
1096 {
1097         struct nv_softc *sc;
1098         struct mii_data *mii;
1099
1100         DEBUGOUT(NV_DEBUG_MII, "nv: nv_ifmedia_sts\n");
1101
1102         sc = ifp->if_softc;
1103         mii = device_get_softc(sc->miibus);
1104         mii_pollstat(mii);
1105
1106         ifmr->ifm_active = mii->mii_media_active;
1107         ifmr->ifm_status = mii->mii_media_status;
1108
1109         return;
1110 }
1111
1112 /* miibus tick timer - maintain link status */
1113 static void
1114 nv_tick(void *xsc)
1115 {
1116         struct nv_softc *sc = xsc;
1117         struct mii_data *mii;
1118         struct ifnet   *ifp;
1119
1120         NV_LOCK(sc);
1121
1122         ifp = &sc->sc_if;
1123         nv_update_stats(sc);
1124
1125         mii = device_get_softc(sc->miibus);
1126         mii_tick(mii);
1127
1128         if (mii->mii_media_status & IFM_ACTIVE &&
1129             IFM_SUBTYPE(mii->mii_media_active) != IFM_NONE) {
1130                 if (!ifq_is_empty(&ifp->if_snd))
1131                         nv_ifstart(ifp);
1132         }
1133         callout_reset(&sc->nv_stat_timer, hz, nv_tick, sc);
1134
1135         NV_UNLOCK(sc);
1136
1137         return;
1138 }
1139
1140 /* Update ifnet data structure with collected interface stats from API */
1141 static void
1142 nv_update_stats(struct nv_softc *sc)
1143 {
1144         struct ifnet   *ifp = &sc->sc_if;
1145         ADAPTER_STATS   stats;
1146
1147         NV_LOCK(sc);
1148
1149         if (sc->hwapi) {
1150                 sc->hwapi->pfnGetStatistics(sc->hwapi->pADCX, &stats);
1151
1152                 ifp->if_ipackets = stats.ulSuccessfulReceptions;
1153                 ifp->if_ierrors = stats.ulMissedFrames +
1154                         stats.ulFailedReceptions +
1155                         stats.ulCRCErrors +
1156                         stats.ulFramingErrors +
1157                         stats.ulOverFlowErrors;
1158
1159                 ifp->if_opackets = stats.ulSuccessfulTransmissions;
1160                 ifp->if_oerrors = sc->tx_errors +
1161                         stats.ulFailedTransmissions +
1162                         stats.ulRetryErrors +
1163                         stats.ulUnderflowErrors +
1164                         stats.ulLossOfCarrierErrors +
1165                         stats.ulLateCollisionErrors;
1166
1167                 ifp->if_collisions = stats.ulLateCollisionErrors;
1168         }
1169         NV_UNLOCK(sc);
1170
1171         return;
1172 }
1173
1174 /* miibus Read PHY register wrapper - calls Nvidia API entry point */
1175 static int
1176 nv_miibus_readreg(device_t dev, int phy, int reg)
1177 {
1178         struct nv_softc *sc = device_get_softc(dev);
1179         ULONG           data;
1180
1181         DEBUGOUT(NV_DEBUG_MII, "nv: nv_miibus_readreg - entry\n");
1182
1183         ADAPTER_ReadPhy(sc->hwapi->pADCX, phy, reg, &data);
1184
1185         DEBUGOUT(NV_DEBUG_MII, "nv: nv_miibus_readreg - exit\n");
1186
1187         return (data);
1188 }
1189
1190 /* miibus Write PHY register wrapper - calls Nvidia API entry point */
1191 static void
1192 nv_miibus_writereg(device_t dev, int phy, int reg, int data)
1193 {
1194         struct nv_softc *sc = device_get_softc(dev);
1195
1196         DEBUGOUT(NV_DEBUG_MII, "nv: nv_miibus_writereg - entry\n");
1197
1198         ADAPTER_WritePhy(sc->hwapi->pADCX, phy, reg, (ulong)data);
1199
1200         DEBUGOUT(NV_DEBUG_MII, "nv: nv_miibus_writereg - exit\n");
1201
1202         return;
1203 }
1204
1205 /* Watchdog timer to prevent PHY lockups */
1206 static void
1207 nv_watchdog(struct ifnet *ifp)
1208 {
1209         struct nv_softc *sc = ifp->if_softc;
1210
1211         device_printf(sc->dev, "device timeout (%d)\n", sc->pending_txs);
1212
1213         sc->tx_errors++;
1214
1215         nv_stop(sc);
1216         ifp->if_flags &= ~IFF_RUNNING;
1217         nv_init(sc);
1218
1219         if (!ifq_is_empty(&ifp->if_snd))
1220                 nv_ifstart(ifp);
1221
1222         return;
1223 }
1224
1225 /* --- Start of NVOSAPI interface --- */
1226
1227 /* Allocate DMA enabled general use memory for API */
1228 static NV_SINT32
1229 nv_osalloc(PNV_VOID ctx, PMEMORY_BLOCK mem)
1230 {
1231         struct nv_softc *sc;
1232         bus_addr_t      mem_physical;
1233
1234         DEBUGOUT(NV_DEBUG_API, "nv: nv_osalloc - %d\n", mem->uiLength);
1235
1236         sc = (struct nv_softc *)ctx;
1237
1238         mem->pLogical = (PVOID)contigmalloc(mem->uiLength, M_DEVBUF,
1239                                     M_NOWAIT | M_ZERO, 0, ~0, PAGE_SIZE, 0);
1240
1241         if (!mem->pLogical) {
1242                 device_printf(sc->dev, "memory allocation failed\n");
1243                 return (0);
1244         }
1245         memset(mem->pLogical, 0, (ulong)mem->uiLength);
1246         mem_physical = vtophys(mem->pLogical);
1247         mem->pPhysical = (PVOID)mem_physical;
1248
1249         DEBUGOUT(NV_DEBUG_API, "nv: nv_osalloc %p/%p - %d\n",
1250                  mem->pLogical, mem->pPhysical, mem->uiLength);
1251
1252         return (1);
1253 }
1254
1255 /* Free allocated memory */
1256 static NV_SINT32
1257 nv_osfree(PNV_VOID ctx, PMEMORY_BLOCK mem)
1258 {
1259         DEBUGOUT(NV_DEBUG_API, "nv: nv_osfree - %p - %d\n",
1260                  mem->pLogical, mem->uiLength);
1261
1262         contigfree(mem->pLogical, PAGE_SIZE, M_DEVBUF);
1263         return (1);
1264 }
1265
1266 /* Copied directly from nvnet.c */
1267 static NV_SINT32
1268 nv_osallocex(PNV_VOID ctx, PMEMORY_BLOCKEX mem_block_ex)
1269 {
1270         MEMORY_BLOCK    mem_block;
1271
1272         DEBUGOUT(NV_DEBUG_API, "nv: nv_osallocex\n");
1273
1274         mem_block_ex->pLogical = NULL;
1275         mem_block_ex->uiLengthOrig = mem_block_ex->uiLength;
1276
1277         if ((mem_block_ex->AllocFlags & ALLOC_MEMORY_ALIGNED) &&
1278             (mem_block_ex->AlignmentSize > 1)) {
1279                 DEBUGOUT(NV_DEBUG_API, "     aligning on %d\n",
1280                          mem_block_ex->AlignmentSize);
1281                 mem_block_ex->uiLengthOrig += mem_block_ex->AlignmentSize;
1282         }
1283         mem_block.uiLength = mem_block_ex->uiLengthOrig;
1284
1285         if (nv_osalloc(ctx, &mem_block) == 0) {
1286                 return (0);
1287         }
1288         mem_block_ex->pLogicalOrig = mem_block.pLogical;
1289         mem_block_ex->pPhysicalOrigLow = (uintptr_t)mem_block.pPhysical;
1290         mem_block_ex->pPhysicalOrigHigh = 0;
1291
1292         mem_block_ex->pPhysical = mem_block.pPhysical;
1293         mem_block_ex->pLogical = mem_block.pLogical;
1294
1295         if (mem_block_ex->uiLength != mem_block_ex->uiLengthOrig) {
1296                 unsigned int    offset;
1297                 offset = mem_block_ex->pPhysicalOrigLow & (mem_block_ex->AlignmentSize - 1);
1298
1299                 if (offset) {
1300                         mem_block_ex->pPhysical = (PVOID)((uintptr_t)mem_block_ex->pPhysical +
1301                                       mem_block_ex->AlignmentSize - offset);
1302                         mem_block_ex->pLogical = (PVOID)((uintptr_t)mem_block_ex->pLogical +
1303                                       mem_block_ex->AlignmentSize - offset);
1304                 }               /* if (offset) */
1305         }                       /* if (mem_block_ex->uiLength !=
1306                                  * mem_block_ex->uiLengthOrig) */
1307         return (1);
1308 }
1309
1310 /* Copied directly from nvnet.c */
1311 static NV_SINT32
1312 nv_osfreeex(PNV_VOID ctx, PMEMORY_BLOCKEX mem_block_ex)
1313 {
1314         MEMORY_BLOCK    mem_block;
1315
1316         DEBUGOUT(NV_DEBUG_API, "nv: nv_osfreeex\n");
1317
1318         mem_block.pLogical = mem_block_ex->pLogicalOrig;
1319         mem_block.pPhysical = (PVOID)((uintptr_t)mem_block_ex->pPhysicalOrigLow);
1320         mem_block.uiLength = mem_block_ex->uiLengthOrig;
1321
1322         return (nv_osfree(ctx, &mem_block));
1323 }
1324
1325 /* Clear memory region */
1326 static NV_SINT32
1327 nv_osclear(PNV_VOID ctx, PNV_VOID mem, NV_SINT32 length)
1328 {
1329         DEBUGOUT(NV_DEBUG_API, "nv: nv_osclear\n");
1330         memset(mem, 0, length);
1331         return (1);
1332 }
1333
1334 /* Sleep for a tick */
1335 static NV_SINT32
1336 nv_osdelay(PNV_VOID ctx, NV_UINT32 usec)
1337 {
1338         DELAY(usec);
1339         return (1);
1340 }
1341
1342 /* Allocate memory for rx buffer */
1343 static NV_SINT32
1344 nv_osallocrxbuf(PNV_VOID ctx, PMEMORY_BLOCK mem, PNV_VOID *id)
1345 {
1346         struct nv_softc *sc = ctx;
1347         struct nv_rx_desc *desc;
1348         struct nv_map_buffer *buf;
1349         int             error;
1350
1351         NV_LOCK(sc);
1352
1353         DEBUGOUT(NV_DEBUG_API, "nv: nv_osallocrxbuf\n");
1354
1355         if (sc->pending_rxs == RX_RING_SIZE) {
1356                 device_printf(sc->dev, "rx ring buffer is full\n");
1357                 goto fail;
1358         }
1359         desc = sc->rx_desc + sc->cur_rx;
1360         buf = &desc->buf;
1361
1362         if (buf->mbuf == NULL) {
1363                 buf->mbuf = m_getcl(MB_DONTWAIT, MT_DATA, M_PKTHDR);
1364                 if (buf->mbuf == NULL) {
1365                         device_printf(sc->dev, "failed to allocate memory\n");
1366                         goto fail;
1367                 }
1368                 buf->mbuf->m_len = buf->mbuf->m_pkthdr.len = MCLBYTES;
1369                 m_adj(buf->mbuf, ETHER_ALIGN);
1370
1371                 error = bus_dmamap_load_mbuf(sc->mtag, buf->map, buf->mbuf,
1372                                           nv_dmamap_rx_cb, &desc->paddr, 0);
1373                 if (error) {
1374                         device_printf(sc->dev, "failed to dmamap mbuf\n");
1375                         m_freem(buf->mbuf);
1376                         buf->mbuf = NULL;
1377                         goto fail;
1378                 }
1379                 bus_dmamap_sync(sc->mtag, buf->map, BUS_DMASYNC_PREREAD);
1380                 desc->buflength = buf->mbuf->m_len;
1381                 desc->vaddr = mtod(buf->mbuf, PVOID);
1382         }
1383         sc->pending_rxs++;
1384         sc->cur_rx = (sc->cur_rx + 1) % RX_RING_SIZE;
1385
1386         mem->pLogical = (void *)desc->vaddr;
1387         mem->pPhysical = (void *)desc->paddr;
1388         mem->uiLength = desc->buflength;
1389         *id = (void *)desc;
1390
1391         NV_UNLOCK(sc);
1392         return (1);
1393
1394 fail:
1395         NV_UNLOCK(sc);
1396         return (0);
1397 }
1398
1399
1400 /* Free the rx buffer */
1401 static NV_SINT32
1402 nv_osfreerxbuf(PNV_VOID ctx, PMEMORY_BLOCK mem, PNV_VOID id)
1403 {
1404         struct nv_softc *sc = ctx;
1405         struct nv_rx_desc *desc;
1406         struct nv_map_buffer *buf;
1407
1408         NV_LOCK(sc);
1409
1410         DEBUGOUT(NV_DEBUG_API, "nv: nv_osfreerxbuf\n");
1411
1412         desc = (struct nv_rx_desc *) id;
1413         buf = &desc->buf;
1414
1415         if (buf->mbuf) {
1416                 bus_dmamap_unload(sc->mtag, buf->map);
1417                 bus_dmamap_destroy(sc->mtag, buf->map);
1418                 m_freem(buf->mbuf);
1419         }
1420         sc->pending_rxs--;
1421         buf->mbuf = NULL;
1422
1423         NV_UNLOCK(sc);
1424
1425         return (1);
1426 }
1427
1428 /* This gets called by the Nvidia API after our TX packet has been sent */
1429 static NV_SINT32
1430 nv_ospackettx(PNV_VOID ctx, PNV_VOID id, NV_UINT32 success)
1431 {
1432         struct nv_softc *sc = ctx;
1433         struct nv_map_buffer *buf;
1434         struct nv_tx_desc *desc = (struct nv_tx_desc *) id;
1435         struct ifnet   *ifp;
1436
1437         NV_LOCK(sc);
1438
1439         DEBUGOUT(NV_DEBUG_API, "nv: nv_ospackettx\n");
1440
1441         ifp = &sc->sc_if;
1442         buf = &desc->buf;
1443         sc->pending_txs--;
1444
1445         /* Unload and free mbuf cluster */
1446         if (buf->mbuf == NULL)
1447                 goto fail;
1448
1449         bus_dmamap_sync(sc->mtag, buf->map, BUS_DMASYNC_POSTWRITE);
1450         bus_dmamap_unload(sc->mtag, buf->map);
1451         m_freem(buf->mbuf);
1452         buf->mbuf = NULL;
1453
1454         if (!ifq_is_empty(&ifp->if_snd) && sc->pending_txs < TX_RING_SIZE)
1455                 nv_ifstart(ifp);
1456
1457 fail:
1458         NV_UNLOCK(sc);
1459
1460         return (1);
1461 }
1462
1463 /* This gets called by the Nvidia API when a new packet has been received */
1464 /* XXX What is newbuf used for? XXX */
1465 static NV_SINT32
1466 nv_ospacketrx(PNV_VOID ctx, PNV_VOID data, NV_UINT32 success,
1467               NV_UINT8 *newbuf, NV_UINT8 priority)
1468 {
1469         struct nv_softc *sc = ctx;
1470         struct ifnet   *ifp;
1471         struct nv_rx_desc *desc;
1472         struct nv_map_buffer *buf;
1473         ADAPTER_READ_DATA *readdata;
1474         NV_LOCK(sc);
1475
1476         DEBUGOUT(NV_DEBUG_API, "nv: nv_ospacketrx\n");
1477
1478         ifp = &sc->sc_if;
1479
1480         readdata = (ADAPTER_READ_DATA *) data;
1481         desc = readdata->pvID;
1482         buf = &desc->buf;
1483         bus_dmamap_sync(sc->mtag, buf->map, BUS_DMASYNC_POSTREAD);
1484
1485         if (success) {
1486                 /* Sync DMA bounce buffer. */
1487                 bus_dmamap_sync(sc->mtag, buf->map, BUS_DMASYNC_POSTREAD);
1488
1489                 /* First mbuf in packet holds the ethernet and packet headers */
1490                 buf->mbuf->m_pkthdr.rcvif = ifp;
1491                 buf->mbuf->m_pkthdr.len = buf->mbuf->m_len = readdata->ulTotalLength;
1492
1493                 bus_dmamap_unload(sc->mtag, buf->map);
1494
1495                 /* Give mbuf to OS. */
1496                 (*ifp->if_input) (ifp, buf->mbuf);
1497                 if (readdata->ulFilterMatch & ADREADFL_MULTICAST_MATCH)
1498                         ifp->if_imcasts++;
1499
1500                 /* Blat the mbuf pointer, kernel will free the mbuf cluster */
1501                 buf->mbuf = NULL;
1502         } else {
1503                 bus_dmamap_sync(sc->mtag, buf->map, BUS_DMASYNC_POSTREAD);
1504                 bus_dmamap_unload(sc->mtag, buf->map);
1505                 m_freem(buf->mbuf);
1506                 buf->mbuf = NULL;
1507         }
1508
1509         sc->cur_rx = desc - sc->rx_desc;
1510         sc->pending_rxs--;
1511
1512         NV_UNLOCK(sc);
1513
1514         return (1);
1515 }
1516
1517 /* This gets called by NVIDIA API when the PHY link state changes */
1518 static NV_SINT32
1519 nv_oslinkchg(PNV_VOID ctx, NV_SINT32 enabled)
1520 {
1521         struct nv_softc *sc = (struct nv_softc *)ctx;
1522         struct ifnet   *ifp;
1523
1524         DEBUGOUT(NV_DEBUG_API, "nv: nv_oslinkchg\n");
1525
1526         ifp = &sc->sc_if;
1527
1528         if (enabled)
1529                 ifp->if_flags |= IFF_UP;
1530         else
1531                 ifp->if_flags &= ~IFF_UP;
1532
1533
1534         return (1);
1535 }
1536
1537
1538 /* Setup a watchdog timer */
1539 static NV_SINT32
1540 nv_osalloctimer(PNV_VOID ctx, PNV_VOID *timer)
1541 {
1542         struct nv_softc *sc = (struct nv_softc *)ctx;
1543
1544         DEBUGOUT(NV_DEBUG_BROKEN, "nv: nv_osalloctimer\n");
1545
1546         callout_init(&sc->ostimer);
1547         *timer = &sc->ostimer;
1548
1549         return (1);
1550 }
1551
1552 /* Free the timer */
1553 static NV_SINT32
1554 nv_osfreetimer(PNV_VOID ctx, PNV_VOID timer)
1555 {
1556         DEBUGOUT(NV_DEBUG_BROKEN, "nv: nv_osfreetimer\n");
1557
1558         return (1);
1559 }
1560
1561 /* Setup timer parameters */
1562 static NV_SINT32
1563 nv_osinittimer(PNV_VOID ctx, PNV_VOID timer, PTIMER_FUNC func, PNV_VOID parameters)
1564 {
1565         struct nv_softc *sc = (struct nv_softc *)ctx;
1566
1567         DEBUGOUT(NV_DEBUG_BROKEN, "nv: nv_osinittimer\n");
1568
1569         sc->ostimer_func = func;
1570         sc->ostimer_params = parameters;
1571
1572         return (1);
1573 }
1574
1575 /* Set the timer to go off */
1576 static NV_SINT32
1577 nv_ossettimer(PNV_VOID ctx, PNV_VOID timer, NV_UINT32 delay)
1578 {
1579         struct nv_softc *sc = ctx;
1580
1581         DEBUGOUT(NV_DEBUG_BROKEN, "nv: nv_ossettimer\n");
1582
1583         callout_reset(&sc->ostimer, delay, sc->ostimer_func,
1584                       sc->ostimer_params);
1585
1586         return (1);
1587 }
1588
1589 /* Cancel the timer */
1590 static NV_SINT32
1591 nv_oscanceltimer(PNV_VOID ctx, PNV_VOID timer)
1592 {
1593         struct nv_softc *sc = ctx;
1594
1595         DEBUGOUT(NV_DEBUG_BROKEN, "nv: nv_oscanceltimer\n");
1596
1597         callout_stop(&sc->ostimer);
1598
1599         return (1);
1600 }
1601
1602 static NV_SINT32
1603 nv_ospreprocpkt(PNV_VOID ctx, PNV_VOID readdata, PNV_VOID *id, NV_UINT8 *newbuffer,
1604                 NV_UINT8 priority)
1605 {
1606         /* Not implemented */
1607         DEBUGOUT(NV_DEBUG_BROKEN, "nv: nv_ospreprocpkt\n");
1608
1609         return (1);
1610 }
1611
1612 static PNV_VOID
1613 nv_ospreprocpktnopq(PNV_VOID ctx, PNV_VOID readdata)
1614 {
1615         /* Not implemented */
1616         DEBUGOUT(NV_DEBUG_BROKEN, "nv: nv_ospreprocpkt\n");
1617
1618         return (NULL);
1619 }
1620
1621 static NV_SINT32
1622 nv_osindicatepkt(PNV_VOID ctx, PNV_VOID *id, NV_UINT32 pktno)
1623 {
1624         /* Not implemented */
1625         DEBUGOUT(NV_DEBUG_BROKEN, "nv: nv_osindicatepkt\n");
1626
1627         return (1);
1628 }
1629
1630 /* Allocate mutex context (already done in nv_attach) */
1631 static NV_SINT32
1632 nv_oslockalloc(PNV_VOID ctx, NV_SINT32 type, PNV_VOID *pLock)
1633 {
1634         struct nv_softc *sc = (struct nv_softc *)ctx;
1635
1636         DEBUGOUT(NV_DEBUG_LOCK, "nv: nv_oslockalloc\n");
1637
1638         *pLock = (void **)sc;
1639
1640         return (1);
1641 }
1642
1643 /* Obtain a spin lock */
1644 static NV_SINT32
1645 nv_oslockacquire(PNV_VOID ctx, NV_SINT32 type, PNV_VOID lock)
1646 {
1647         DEBUGOUT(NV_DEBUG_LOCK, "nv: nv_oslockacquire\n");
1648
1649         NV_OSLOCK((struct nv_softc *)lock);
1650
1651         return (1);
1652 }
1653
1654 /* Release lock */
1655 static NV_SINT32
1656 nv_oslockrelease(PNV_VOID ctx, NV_SINT32 type, PNV_VOID lock)
1657 {
1658         DEBUGOUT(NV_DEBUG_LOCK, "nv: nv_oslockrelease\n");
1659
1660         NV_OSUNLOCK((struct nv_softc *)lock);
1661
1662         return (1);
1663 }
1664
1665 /* I have no idea what this is for */
1666 static PNV_VOID
1667 nv_osreturnbufvirt(PNV_VOID ctx, PNV_VOID readdata)
1668 {
1669         /* Not implemented */
1670         DEBUGOUT(NV_DEBUG_LOCK, "nv: nv_osreturnbufvirt\n");
1671         panic("nv: nv_osreturnbufvirtual not implemented\n");
1672
1673         return (NULL);
1674 }
1675
1676
1677 /* --- End on NVOSAPI interface --- */