]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/arm/xscale/ixp425/if_npe.c
Update for the new prototype of bus_setup_intr().
[FreeBSD/FreeBSD.git] / sys / arm / xscale / ixp425 / if_npe.c
1 /*-
2  * Copyright (c) 2006 Sam Leffler.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
14  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
15  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
16  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
17  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
18  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
19  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
20  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
21  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
22  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
23  */
24
25 #include <sys/cdefs.h>
26 __FBSDID("$FreeBSD$");
27
28 /*
29  * Intel XScale NPE Ethernet driver.
30  *
31  * This driver handles the two ports present on the IXP425.
32  * Packet processing is done by the Network Processing Engines
33  * (NPE's) that work together with a MAC and PHY. The MAC
34  * is also mapped to the XScale cpu; the PHY is accessed via
35  * the MAC. NPE-XScale communication happens through h/w
36  * queues managed by the Q Manager block.
37  *
38  * The code here replaces the ethAcc, ethMii, and ethDB classes
39  * in the Intel Access Library (IAL) and the OS-specific driver.
40  *
41  * XXX add vlan support
42  * XXX NPE-C port doesn't work yet
43  */
44 #ifdef HAVE_KERNEL_OPTION_HEADERS
45 #include "opt_device_polling.h"
46 #endif
47
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/bus.h>
51 #include <sys/kernel.h>
52 #include <sys/mbuf.h>
53 #include <sys/malloc.h>
54 #include <sys/module.h>
55 #include <sys/rman.h>
56 #include <sys/socket.h>
57 #include <sys/sockio.h>
58 #include <sys/sysctl.h>
59 #include <sys/endian.h>
60 #include <machine/bus.h>
61
62 #include <net/ethernet.h>
63 #include <net/if.h>
64 #include <net/if_arp.h>
65 #include <net/if_dl.h>
66 #include <net/if_media.h>
67 #include <net/if_mib.h>
68 #include <net/if_types.h>
69
70 #ifdef INET
71 #include <netinet/in.h>
72 #include <netinet/in_systm.h>
73 #include <netinet/in_var.h>
74 #include <netinet/ip.h>
75 #endif
76
77 #include <net/bpf.h>
78 #include <net/bpfdesc.h>
79
80 #include <arm/xscale/ixp425/ixp425reg.h>
81 #include <arm/xscale/ixp425/ixp425var.h>
82 #include <arm/xscale/ixp425/ixp425_qmgr.h>
83 #include <arm/xscale/ixp425/ixp425_npevar.h>
84
85 #include <dev/mii/mii.h>
86 #include <dev/mii/miivar.h>
87 #include <arm/xscale/ixp425/if_npereg.h>
88
89 #include "miibus_if.h"
90
91 /* 
92  * XXX: For the main bus dma tag. Can go away if the new method to get the 
93  * dma tag from the parent got MFC'd into RELENG_6.
94  */
95 extern struct ixp425_softc *ixp425_softc;
96
97 struct npebuf {
98         struct npebuf   *ix_next;       /* chain to next buffer */
99         void            *ix_m;          /* backpointer to mbuf */
100         bus_dmamap_t    ix_map;         /* bus dma map for associated data */
101         struct npehwbuf *ix_hw;         /* associated h/w block */
102         uint32_t        ix_neaddr;      /* phys address of ix_hw */
103 };
104
105 struct npedma {
106         const char*     name;
107         int             nbuf;           /* # npebuf's allocated */
108         bus_dma_tag_t   mtag;           /* bus dma tag for mbuf data */
109         struct npehwbuf *hwbuf;         /* NPE h/w buffers */
110         bus_dma_tag_t   buf_tag;        /* tag+map for NPE buffers */
111         bus_dmamap_t    buf_map;
112         bus_addr_t      buf_phys;       /* phys addr of buffers */
113         struct npebuf   *buf;           /* s/w buffers (1-1 w/ h/w) */
114 };
115
116 struct npe_softc {
117         /* XXX mii requires this be first; do not move! */
118         struct ifnet    *sc_ifp;        /* ifnet pointer */
119         struct mtx      sc_mtx;         /* basically a perimeter lock */
120         device_t        sc_dev;
121         bus_space_tag_t sc_iot;         
122         bus_space_handle_t sc_ioh;      /* MAC register window */
123         device_t        sc_mii;         /* child miibus */
124         bus_space_handle_t sc_miih;     /* MII register window */
125         struct ixpnpe_softc *sc_npe;    /* NPE support */
126         int             sc_debug;       /* DPRINTF* control */
127         int             sc_tickinterval;
128         struct callout  tick_ch;        /* Tick callout */
129         int             npe_watchdog_timer;
130         struct npedma   txdma;
131         struct npebuf   *tx_free;       /* list of free tx buffers */
132         struct npedma   rxdma;
133         bus_addr_t      buf_phys;       /* XXX for returning a value */
134         int             rx_qid;         /* rx qid */
135         int             rx_freeqid;     /* rx free buffers qid */
136         int             tx_qid;         /* tx qid */
137         int             tx_doneqid;     /* tx completed qid */
138         struct ifmib_iso_8802_3 mibdata;
139         bus_dma_tag_t   sc_stats_tag;   /* bus dma tag for stats block */
140         struct npestats *sc_stats;
141         bus_dmamap_t    sc_stats_map;
142         bus_addr_t      sc_stats_phys;  /* phys addr of sc_stats */
143 };
144
145 /*
146  * Per-unit static configuration for IXP425.  The tx and
147  * rx free Q id's are fixed by the NPE microcode.  The
148  * rx Q id's are programmed to be separate to simplify
149  * multi-port processing.  It may be better to handle
150  * all traffic through one Q (as done by the Intel drivers).
151  *
152  * Note that the PHY's are accessible only from MAC A
153  * on the IXP425.  This and other platform-specific
154  * assumptions probably need to be handled through hints.
155  */
156 static const struct {
157         const char      *desc;          /* device description */
158         int             npeid;          /* NPE assignment */
159         uint32_t        imageid;        /* NPE firmware image id */
160         uint32_t        regbase;
161         int             regsize;
162         uint32_t        miibase;
163         int             miisize;
164         uint8_t         rx_qid;
165         uint8_t         rx_freeqid;
166         uint8_t         tx_qid;
167         uint8_t         tx_doneqid;
168 } npeconfig[NPE_PORTS_MAX] = {
169         { .desc         = "IXP NPE-B",
170           .npeid        = NPE_B,
171           .imageid      = IXP425_NPE_B_IMAGEID,
172           .regbase      = IXP425_MAC_A_HWBASE,
173           .regsize      = IXP425_MAC_A_SIZE,
174           .miibase      = IXP425_MAC_A_HWBASE,
175           .miisize      = IXP425_MAC_A_SIZE,
176           .rx_qid       = 4,
177           .rx_freeqid   = 27,
178           .tx_qid       = 24,
179           .tx_doneqid   = 31
180         },
181         { .desc         = "IXP NPE-C",
182           .npeid        = NPE_C,
183           .imageid      = IXP425_NPE_C_IMAGEID,
184           .regbase      = IXP425_MAC_B_HWBASE,
185           .regsize      = IXP425_MAC_B_SIZE,
186           .miibase      = IXP425_MAC_A_HWBASE,
187           .miisize      = IXP425_MAC_A_SIZE,
188           .rx_qid       = 12,
189           .rx_freeqid   = 28,
190           .tx_qid       = 25,
191           .tx_doneqid   = 31
192         },
193 };
194 static struct npe_softc *npes[NPE_MAX]; /* NB: indexed by npeid */
195
196 static __inline uint32_t
197 RD4(struct npe_softc *sc, bus_size_t off)
198 {
199         return bus_space_read_4(sc->sc_iot, sc->sc_ioh, off);
200 }
201
202 static __inline void
203 WR4(struct npe_softc *sc, bus_size_t off, uint32_t val)
204 {
205         bus_space_write_4(sc->sc_iot, sc->sc_ioh, off, val);
206 }
207
208 #define NPE_LOCK(_sc)           mtx_lock(&(_sc)->sc_mtx)
209 #define NPE_UNLOCK(_sc)         mtx_unlock(&(_sc)->sc_mtx)
210 #define NPE_LOCK_INIT(_sc) \
211         mtx_init(&_sc->sc_mtx, device_get_nameunit(_sc->sc_dev), \
212             MTX_NETWORK_LOCK, MTX_DEF)
213 #define NPE_LOCK_DESTROY(_sc)   mtx_destroy(&_sc->sc_mtx);
214 #define NPE_ASSERT_LOCKED(_sc)  mtx_assert(&_sc->sc_mtx, MA_OWNED);
215 #define NPE_ASSERT_UNLOCKED(_sc) mtx_assert(&_sc->sc_mtx, MA_NOTOWNED);
216
217 static devclass_t npe_devclass;
218
219 static int      npe_activate(device_t dev);
220 static void     npe_deactivate(device_t dev);
221 static int      npe_ifmedia_update(struct ifnet *ifp);
222 static void     npe_ifmedia_status(struct ifnet *ifp, struct ifmediareq *ifmr);
223 static void     npe_setmac(struct npe_softc *sc, u_char *eaddr);
224 static void     npe_getmac(struct npe_softc *sc, u_char *eaddr);
225 static void     npe_txdone(int qid, void *arg);
226 static int      npe_rxbuf_init(struct npe_softc *, struct npebuf *,
227                         struct mbuf *);
228 static void     npe_rxdone(int qid, void *arg);
229 static void     npeinit(void *);
230 static void     npestart_locked(struct ifnet *);
231 static void     npestart(struct ifnet *);
232 static void     npestop(struct npe_softc *);
233 static void     npewatchdog(struct npe_softc *);
234 static int      npeioctl(struct ifnet * ifp, u_long, caddr_t);
235
236 static int      npe_setrxqosentry(struct npe_softc *, int classix,
237                         int trafclass, int qid);
238 static int      npe_updatestats(struct npe_softc *);
239 #if 0
240 static int      npe_getstats(struct npe_softc *);
241 static uint32_t npe_getimageid(struct npe_softc *);
242 static int      npe_setloopback(struct npe_softc *, int ena);
243 #endif
244
245 /* NB: all tx done processing goes through one queue */
246 static int tx_doneqid = -1;
247
248 SYSCTL_NODE(_hw, OID_AUTO, npe, CTLFLAG_RD, 0, "IXP425 NPE driver parameters");
249
250 static int npe_debug = 0;
251 SYSCTL_INT(_hw_npe, OID_AUTO, debug, CTLFLAG_RW, &npe_debug,
252            0, "IXP425 NPE network interface debug msgs");
253 TUNABLE_INT("hw.npe.npe", &npe_debug);
254 #define DPRINTF(sc, fmt, ...) do {                                      \
255         if (sc->sc_debug) device_printf(sc->sc_dev, fmt, __VA_ARGS__);  \
256 } while (0)
257 #define DPRINTFn(n, sc, fmt, ...) do {                                  \
258         if (sc->sc_debug >= n) device_printf(sc->sc_dev, fmt, __VA_ARGS__);\
259 } while (0)
260 static int npe_tickinterval = 3;                /* npe_tick frequency (secs) */
261 SYSCTL_INT(_hw_npe, OID_AUTO, tickinterval, CTLFLAG_RD, &npe_tickinterval,
262             0, "periodic work interval (secs)");
263 TUNABLE_INT("hw.npe.tickinterval", &npe_tickinterval);
264
265 static  int npe_rxbuf = 64;             /* # rx buffers to allocate */
266 SYSCTL_INT(_hw_npe, OID_AUTO, rxbuf, CTLFLAG_RD, &npe_rxbuf,
267             0, "rx buffers allocated");
268 TUNABLE_INT("hw.npe.rxbuf", &npe_rxbuf);
269 static  int npe_txbuf = 128;            /* # tx buffers to allocate */
270 SYSCTL_INT(_hw_npe, OID_AUTO, txbuf, CTLFLAG_RD, &npe_txbuf,
271             0, "tx buffers allocated");
272 TUNABLE_INT("hw.npe.txbuf", &npe_txbuf);
273
274 static int
275 npe_probe(device_t dev)
276 {
277         int unit = device_get_unit(dev);
278
279         if (unit >= NPE_PORTS_MAX) {
280                 device_printf(dev, "unit %d not supported\n", unit);
281                 return EINVAL;
282         }
283         /* XXX check feature register to see if enabled */
284         device_set_desc(dev, npeconfig[unit].desc);
285         return 0;
286 }
287
288 static int
289 npe_attach(device_t dev)
290 {
291         struct npe_softc *sc = device_get_softc(dev);
292         struct ixp425_softc *sa = device_get_softc(device_get_parent(dev));
293         struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(dev);
294         struct sysctl_oid *tree = device_get_sysctl_tree(dev);
295         struct ifnet *ifp = NULL;
296         int error;
297         u_char eaddr[6];
298
299         sc->sc_dev = dev;
300         sc->sc_iot = sa->sc_iot;
301         NPE_LOCK_INIT(sc);
302         callout_init_mtx(&sc->tick_ch, &sc->sc_mtx, 0);
303         sc->sc_debug = npe_debug;
304         sc->sc_tickinterval = npe_tickinterval;
305
306         sc->sc_npe = ixpnpe_attach(dev);
307         if (sc->sc_npe == NULL) {
308                 error = EIO;            /* XXX */
309                 goto out;
310         }
311
312         error = npe_activate(dev);
313         if (error)
314                 goto out;
315
316         npe_getmac(sc, eaddr);
317
318         /* NB: must be setup prior to invoking mii code */
319         sc->sc_ifp = ifp = if_alloc(IFT_ETHER);
320         if (mii_phy_probe(dev, &sc->sc_mii, npe_ifmedia_update, npe_ifmedia_status)) {
321                 device_printf(dev, "Cannot find my PHY.\n");
322                 error = ENXIO;
323                 goto out;
324         }
325
326         ifp->if_softc = sc;
327         if_initname(ifp, device_get_name(dev), device_get_unit(dev));
328         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
329         ifp->if_start = npestart;
330         ifp->if_ioctl = npeioctl;
331         ifp->if_init = npeinit;
332         IFQ_SET_MAXLEN(&ifp->if_snd, sc->txdma.nbuf - 1);
333         ifp->if_snd.ifq_drv_maxlen = IFQ_MAXLEN;
334         IFQ_SET_READY(&ifp->if_snd);
335         ifp->if_linkmib = &sc->mibdata;
336         ifp->if_linkmiblen = sizeof(sc->mibdata);
337         sc->mibdata.dot3Compliance = DOT3COMPLIANCE_STATS;
338 #ifdef DEVICE_POLLING
339         ifp->if_capabilities |= IFCAP_POLLING;
340 #endif
341
342         SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "debug",
343             CTLFLAG_RW, &sc->sc_debug, 0, "control debugging printfs");
344         SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "tickinterval",
345             CTLFLAG_RW, &sc->sc_tickinterval, 0, "periodic work frequency");
346
347         ether_ifattach(ifp, eaddr);
348         return 0;
349 out:
350         npe_deactivate(dev);
351         if (ifp != NULL)
352                 if_free(ifp);
353         return error;
354 }
355
356 static int
357 npe_detach(device_t dev)
358 {
359         struct npe_softc *sc = device_get_softc(dev);
360         struct ifnet *ifp = sc->sc_ifp;
361
362 #ifdef DEVICE_POLLING
363         if (ifp->if_capenable & IFCAP_POLLING)
364                 ether_poll_deregister(ifp);
365 #endif
366         npestop(sc);
367         if (ifp != NULL) {
368                 ether_ifdetach(ifp);
369                 if_free(ifp);
370         }
371         NPE_LOCK_DESTROY(sc);
372         npe_deactivate(dev);
373         if (sc->sc_npe != NULL)
374                 ixpnpe_detach(sc->sc_npe);
375         return 0;
376 }
377
378 /*
379  * Compute and install the multicast filter.
380  */
381 static void
382 npe_setmcast(struct npe_softc *sc)
383 {
384         struct ifnet *ifp = sc->sc_ifp;
385         uint8_t mask[ETHER_ADDR_LEN], addr[ETHER_ADDR_LEN];
386         int i;
387
388         if (ifp->if_flags & IFF_PROMISC) {
389                 memset(mask, 0, ETHER_ADDR_LEN);
390                 memset(addr, 0, ETHER_ADDR_LEN);
391         } else if (ifp->if_flags & IFF_ALLMULTI) {
392                 static const uint8_t allmulti[ETHER_ADDR_LEN] =
393                     { 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 };
394                 memcpy(mask, allmulti, ETHER_ADDR_LEN);
395                 memcpy(addr, allmulti, ETHER_ADDR_LEN);
396         } else {
397                 uint8_t clr[ETHER_ADDR_LEN], set[ETHER_ADDR_LEN];
398                 struct ifmultiaddr *ifma;
399                 const uint8_t *mac;
400
401                 memset(clr, 0, ETHER_ADDR_LEN);
402                 memset(set, 0xff, ETHER_ADDR_LEN);
403
404                 IF_ADDR_LOCK(ifp);
405                 TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
406                         if (ifma->ifma_addr->sa_family != AF_LINK)
407                                 continue;
408                         mac = LLADDR((struct sockaddr_dl *) ifma->ifma_addr);
409                         for (i = 0; i < ETHER_ADDR_LEN; i++) {
410                                 clr[i] |= mac[i];
411                                 set[i] &= mac[i];
412                         }
413                 }
414                 IF_ADDR_UNLOCK(ifp);
415
416                 for (i = 0; i < ETHER_ADDR_LEN; i++) {
417                         mask[i] = set[i] | ~clr[i];
418                         addr[i] = set[i];
419                 }
420         }
421
422         /*
423          * Write the mask and address registers.
424          */
425         for (i = 0; i < ETHER_ADDR_LEN; i++) {
426                 WR4(sc, NPE_MAC_ADDR_MASK(i), mask[i]);
427                 WR4(sc, NPE_MAC_ADDR(i), addr[i]);
428         }
429 }
430
431 static void
432 npe_getaddr(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
433 {
434         struct npe_softc *sc;
435
436         if (error != 0)
437                 return;
438         sc = (struct npe_softc *)arg;
439         sc->buf_phys = segs[0].ds_addr;
440 }
441
442 static int
443 npe_dma_setup(struct npe_softc *sc, struct npedma *dma,
444         const char *name, int nbuf, int maxseg)
445 {
446         int error, i;
447
448         memset(dma, 0, sizeof(dma));
449
450         dma->name = name;
451         dma->nbuf = nbuf;
452
453         /* DMA tag for mapped mbufs  */
454         error = bus_dma_tag_create(ixp425_softc->sc_dmat, 1, 0,
455             BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
456             MCLBYTES, maxseg, MCLBYTES, 0,
457             busdma_lock_mutex, &sc->sc_mtx, &dma->mtag);
458         if (error != 0) {
459                 device_printf(sc->sc_dev, "unable to create %s mbuf dma tag, "
460                      "error %u\n", dma->name, error);
461                 return error;
462         }
463
464         /* DMA tag and map for the NPE buffers */
465         error = bus_dma_tag_create(ixp425_softc->sc_dmat, sizeof(uint32_t), 0, 
466             BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
467             nbuf * sizeof(struct npehwbuf), 1,
468             nbuf * sizeof(struct npehwbuf), 0,
469             busdma_lock_mutex, &sc->sc_mtx, &dma->buf_tag);
470         if (error != 0) {
471                 device_printf(sc->sc_dev,
472                     "unable to create %s npebuf dma tag, error %u\n",
473                     dma->name, error);
474                 return error;
475         }
476         /* XXX COHERENT for now */
477         if (bus_dmamem_alloc(dma->buf_tag, (void **)&dma->hwbuf,
478             BUS_DMA_NOWAIT | BUS_DMA_ZERO | BUS_DMA_COHERENT,
479             &dma->buf_map) != 0) {
480                 device_printf(sc->sc_dev,
481                      "unable to allocate memory for %s h/w buffers, error %u\n",
482                      dma->name, error);
483                 return error;
484         }
485         /* XXX M_TEMP */
486         dma->buf = malloc(nbuf * sizeof(struct npebuf), M_TEMP, M_NOWAIT | M_ZERO);
487         if (dma->buf == NULL) {
488                 device_printf(sc->sc_dev,
489                      "unable to allocate memory for %s s/w buffers\n",
490                      dma->name);
491                 return error;
492         }
493         if (bus_dmamap_load(dma->buf_tag, dma->buf_map,
494             dma->hwbuf, nbuf*sizeof(struct npehwbuf), npe_getaddr, sc, 0) != 0) {
495                 device_printf(sc->sc_dev,
496                      "unable to map memory for %s h/w buffers, error %u\n",
497                      dma->name, error);
498                 return error;
499         }
500         dma->buf_phys = sc->buf_phys;
501         for (i = 0; i < dma->nbuf; i++) {
502                 struct npebuf *npe = &dma->buf[i];
503                 struct npehwbuf *hw = &dma->hwbuf[i];
504
505                 /* calculate offset to shared area */
506                 npe->ix_neaddr = dma->buf_phys +
507                         ((uintptr_t)hw - (uintptr_t)dma->hwbuf);
508                 KASSERT((npe->ix_neaddr & 0x1f) == 0,
509                     ("ixpbuf misaligned, PA 0x%x", npe->ix_neaddr));
510                 error = bus_dmamap_create(dma->mtag, BUS_DMA_NOWAIT,
511                                 &npe->ix_map);
512                 if (error != 0) {
513                         device_printf(sc->sc_dev,
514                              "unable to create dmamap for %s buffer %u, "
515                              "error %u\n", dma->name, i, error);
516                         return error;
517                 }
518                 npe->ix_hw = hw;
519         }
520         bus_dmamap_sync(dma->buf_tag, dma->buf_map, BUS_DMASYNC_PREWRITE);
521         return 0;
522 }
523
524 static void
525 npe_dma_destroy(struct npe_softc *sc, struct npedma *dma)
526 {
527         int i;
528
529         if (dma->hwbuf != NULL) {
530                 for (i = 0; i < dma->nbuf; i++) {
531                         struct npebuf *npe = &dma->buf[i];
532                         bus_dmamap_destroy(dma->mtag, npe->ix_map);
533                 }
534                 bus_dmamap_unload(dma->buf_tag, dma->buf_map);
535                 bus_dmamem_free(dma->buf_tag, dma->hwbuf, dma->buf_map);
536                 bus_dmamap_destroy(dma->buf_tag, dma->buf_map);
537         }
538         if (dma->buf != NULL)
539                 free(dma->buf, M_TEMP);
540         if (dma->buf_tag)
541                 bus_dma_tag_destroy(dma->buf_tag);
542         if (dma->mtag)
543                 bus_dma_tag_destroy(dma->mtag);
544         memset(dma, 0, sizeof(*dma));
545 }
546
547 static int
548 npe_activate(device_t dev)
549 {
550         struct npe_softc * sc = device_get_softc(dev);
551         int unit = device_get_unit(dev);
552         int error, i;
553
554         /* load NPE firmware and start it running */
555         error = ixpnpe_init(sc->sc_npe, "npe_fw", npeconfig[unit].imageid);
556         if (error != 0)
557                 return error;
558
559         if (bus_space_map(sc->sc_iot, npeconfig[unit].regbase,
560             npeconfig[unit].regsize, 0, &sc->sc_ioh)) {
561                 device_printf(dev, "Cannot map registers 0x%x:0x%x\n",
562                     npeconfig[unit].regbase, npeconfig[unit].regsize);
563                 return ENOMEM;
564         }
565
566         if (npeconfig[unit].miibase != npeconfig[unit].regbase) {
567                 /*
568                  * The PHY's are only accessible from one MAC (it appears)
569                  * so for other MAC's setup an additional mapping for
570                  * frobbing the PHY registers.
571                  */
572                 if (bus_space_map(sc->sc_iot, npeconfig[unit].miibase,
573                     npeconfig[unit].miisize, 0, &sc->sc_miih)) {
574                         device_printf(dev,
575                             "Cannot map MII registers 0x%x:0x%x\n",
576                             npeconfig[unit].miibase, npeconfig[unit].miisize);
577                         return ENOMEM;
578                 }
579         } else
580                 sc->sc_miih = sc->sc_ioh;
581         error = npe_dma_setup(sc, &sc->txdma, "tx", npe_txbuf, NPE_MAXSEG);
582         if (error != 0)
583                 return error;
584         error = npe_dma_setup(sc, &sc->rxdma, "rx", npe_rxbuf, 1);
585         if (error != 0)
586                 return error;
587
588         /* setup statistics block */
589         error = bus_dma_tag_create(ixp425_softc->sc_dmat, sizeof(uint32_t), 0,
590             BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
591             sizeof(struct npestats), 1, sizeof(struct npestats), 0,
592             busdma_lock_mutex, &sc->sc_mtx, &sc->sc_stats_tag);
593         if (error != 0) {
594                 device_printf(sc->sc_dev, "unable to create stats tag, "
595                      "error %u\n", error);
596                 return error;
597         }
598         if (bus_dmamem_alloc(sc->sc_stats_tag, (void **)&sc->sc_stats,
599             BUS_DMA_NOWAIT, &sc->sc_stats_map) != 0) {
600                 device_printf(sc->sc_dev,
601                      "unable to allocate memory for stats block, error %u\n",
602                      error);
603                 return error;
604         }
605         if (bus_dmamap_load(sc->sc_stats_tag, sc->sc_stats_map,
606             sc->sc_stats, sizeof(struct npestats), npe_getaddr, sc, 0) != 0) {
607                 device_printf(sc->sc_dev,
608                      "unable to load memory for stats block, error %u\n",
609                      error);
610                 return error;
611         }
612         sc->sc_stats_phys = sc->buf_phys;
613
614         /* XXX disable half-bridge LEARNING+FILTERING feature */
615
616         /*
617          * Setup h/w rx/tx queues.  There are four q's:
618          *   rx         inbound q of rx'd frames
619          *   rx_free    pool of ixpbuf's for receiving frames
620          *   tx         outbound q of frames to send
621          *   tx_done    q of tx frames that have been processed
622          *
623          * The NPE handles the actual tx/rx process and the q manager
624          * handles the queues.  The driver just writes entries to the
625          * q manager mailbox's and gets callbacks when there are rx'd
626          * frames to process or tx'd frames to reap.  These callbacks
627          * are controlled by the q configurations; e.g. we get a
628          * callback when tx_done has 2 or more frames to process and
629          * when the rx q has at least one frame.  These setings can
630          * changed at the time the q is configured.
631          */
632         sc->rx_qid = npeconfig[unit].rx_qid;
633         ixpqmgr_qconfig(sc->rx_qid, npe_rxbuf, 0,  1,
634                 IX_QMGR_Q_SOURCE_ID_NOT_E, npe_rxdone, sc);
635         sc->rx_freeqid = npeconfig[unit].rx_freeqid;
636         ixpqmgr_qconfig(sc->rx_freeqid, npe_rxbuf, 0, npe_rxbuf/2, 0, NULL, sc);
637         /* tell the NPE to direct all traffic to rx_qid */
638 #if 0
639         for (i = 0; i < 8; i++)
640 #else
641 device_printf(sc->sc_dev, "remember to fix rx q setup\n");
642         for (i = 0; i < 4; i++)
643 #endif
644                 npe_setrxqosentry(sc, i, 0, sc->rx_qid);
645
646         sc->tx_qid = npeconfig[unit].tx_qid;
647         sc->tx_doneqid = npeconfig[unit].tx_doneqid;
648         ixpqmgr_qconfig(sc->tx_qid, npe_txbuf, 0, npe_txbuf, 0, NULL, sc);
649         if (tx_doneqid == -1) {
650                 ixpqmgr_qconfig(sc->tx_doneqid, npe_txbuf, 0,  2,
651                         IX_QMGR_Q_SOURCE_ID_NOT_E, npe_txdone, sc);
652                 tx_doneqid = sc->tx_doneqid;
653         }
654
655         KASSERT(npes[npeconfig[unit].npeid] == NULL,
656             ("npe %u already setup", npeconfig[unit].npeid));
657         npes[npeconfig[unit].npeid] = sc;
658
659         return 0;
660 }
661
662 static void
663 npe_deactivate(device_t dev)
664 {
665         struct npe_softc *sc = device_get_softc(dev);
666         int unit = device_get_unit(dev);
667
668         npes[npeconfig[unit].npeid] = NULL;
669
670         /* XXX disable q's */
671         if (sc->sc_npe != NULL)
672                 ixpnpe_stop(sc->sc_npe);
673         if (sc->sc_stats != NULL) {
674                 bus_dmamap_unload(sc->sc_stats_tag, sc->sc_stats_map);
675                 bus_dmamem_free(sc->sc_stats_tag, sc->sc_stats,
676                         sc->sc_stats_map);
677                 bus_dmamap_destroy(sc->sc_stats_tag, sc->sc_stats_map);
678         }
679         if (sc->sc_stats_tag != NULL)
680                 bus_dma_tag_destroy(sc->sc_stats_tag);
681         npe_dma_destroy(sc, &sc->txdma);
682         npe_dma_destroy(sc, &sc->rxdma);
683         bus_generic_detach(sc->sc_dev);
684         if (sc->sc_mii)
685                 device_delete_child(sc->sc_dev, sc->sc_mii);
686 #if 0
687         /* XXX sc_ioh and sc_miih */
688         if (sc->mem_res)
689                 bus_release_resource(dev, SYS_RES_IOPORT,
690                     rman_get_rid(sc->mem_res), sc->mem_res);
691         sc->mem_res = 0;
692 #endif
693 }
694
695 /*
696  * Change media according to request.
697  */
698 static int
699 npe_ifmedia_update(struct ifnet *ifp)
700 {
701         struct npe_softc *sc = ifp->if_softc;
702         struct mii_data *mii;
703
704         mii = device_get_softc(sc->sc_mii);
705         NPE_LOCK(sc);
706         mii_mediachg(mii);
707         /* XXX push state ourself? */
708         NPE_UNLOCK(sc);
709         return (0);
710 }
711
712 /*
713  * Notify the world which media we're using.
714  */
715 static void
716 npe_ifmedia_status(struct ifnet *ifp, struct ifmediareq *ifmr)
717 {
718         struct npe_softc *sc = ifp->if_softc;
719         struct mii_data *mii;
720
721         mii = device_get_softc(sc->sc_mii);
722         NPE_LOCK(sc);
723         mii_pollstat(mii);
724         ifmr->ifm_active = mii->mii_media_active;
725         ifmr->ifm_status = mii->mii_media_status;
726         NPE_UNLOCK(sc);
727 }
728
729 static void
730 npe_addstats(struct npe_softc *sc)
731 {
732 #define MIBADD(x)       sc->mibdata.x += be32toh(ns->x)
733         struct ifnet *ifp = sc->sc_ifp;
734         struct npestats *ns = sc->sc_stats;
735
736         MIBADD(dot3StatsAlignmentErrors);
737         MIBADD(dot3StatsFCSErrors);
738         MIBADD(dot3StatsSingleCollisionFrames);
739         MIBADD(dot3StatsMultipleCollisionFrames);
740         MIBADD(dot3StatsDeferredTransmissions);
741         MIBADD(dot3StatsLateCollisions);
742         MIBADD(dot3StatsExcessiveCollisions);
743         MIBADD(dot3StatsInternalMacTransmitErrors);
744         MIBADD(dot3StatsCarrierSenseErrors);
745         sc->mibdata.dot3StatsFrameTooLongs +=
746               be32toh(ns->RxLargeFramesDiscards)
747             + be32toh(ns->TxLargeFrameDiscards);
748         MIBADD(dot3StatsInternalMacReceiveErrors);
749         sc->mibdata.dot3StatsMissedFrames +=
750               be32toh(ns->RxOverrunDiscards)
751             + be32toh(ns->RxUnderflowEntryDiscards);
752
753         ifp->if_oerrors +=
754                   be32toh(ns->dot3StatsInternalMacTransmitErrors)
755                 + be32toh(ns->dot3StatsCarrierSenseErrors)
756                 + be32toh(ns->TxVLANIdFilterDiscards)
757                 ;
758         ifp->if_ierrors += be32toh(ns->dot3StatsFCSErrors)
759                 + be32toh(ns->dot3StatsInternalMacReceiveErrors)
760                 + be32toh(ns->RxOverrunDiscards)
761                 + be32toh(ns->RxUnderflowEntryDiscards)
762                 ;
763         ifp->if_collisions +=
764                   be32toh(ns->dot3StatsSingleCollisionFrames)
765                 + be32toh(ns->dot3StatsMultipleCollisionFrames)
766                 ;
767 #undef MIBADD
768 }
769
770 static void
771 npe_tick(void *xsc)
772 {
773 #define ACK     (NPE_RESETSTATS << NPE_MAC_MSGID_SHL)
774         struct npe_softc *sc = xsc;
775         struct mii_data *mii = device_get_softc(sc->sc_mii);
776         uint32_t msg[2];
777
778         NPE_ASSERT_LOCKED(sc);
779
780         /*
781          * NB: to avoid sleeping with the softc lock held we
782          * split the NPE msg processing into two parts.  The
783          * request for statistics is sent w/o waiting for a
784          * reply and then on the next tick we retrieve the
785          * results.  This works because npe_tick is the only
786          * code that talks via the mailbox's (except at setup).
787          * This likely can be handled better.
788          */
789         if (ixpnpe_recvmsg(sc->sc_npe, msg) == 0 && msg[0] == ACK) {
790                 bus_dmamap_sync(sc->sc_stats_tag, sc->sc_stats_map,
791                     BUS_DMASYNC_POSTREAD);
792                 npe_addstats(sc);
793         }
794         npe_updatestats(sc);
795         mii_tick(mii);
796
797         npewatchdog(sc);
798
799         /* schedule next poll */
800         callout_reset(&sc->tick_ch, sc->sc_tickinterval * hz, npe_tick, sc);
801 #undef ACK
802 }
803
804 static void
805 npe_setmac(struct npe_softc *sc, u_char *eaddr)
806 {
807         WR4(sc, NPE_MAC_UNI_ADDR_1, eaddr[0]);
808         WR4(sc, NPE_MAC_UNI_ADDR_2, eaddr[1]);
809         WR4(sc, NPE_MAC_UNI_ADDR_3, eaddr[2]);
810         WR4(sc, NPE_MAC_UNI_ADDR_4, eaddr[3]);
811         WR4(sc, NPE_MAC_UNI_ADDR_5, eaddr[4]);
812         WR4(sc, NPE_MAC_UNI_ADDR_6, eaddr[5]);
813
814 }
815
816 static void
817 npe_getmac(struct npe_softc *sc, u_char *eaddr)
818 {
819         /* NB: the unicast address appears to be loaded from EEPROM on reset */
820         eaddr[0] = RD4(sc, NPE_MAC_UNI_ADDR_1) & 0xff;
821         eaddr[1] = RD4(sc, NPE_MAC_UNI_ADDR_2) & 0xff;
822         eaddr[2] = RD4(sc, NPE_MAC_UNI_ADDR_3) & 0xff;
823         eaddr[3] = RD4(sc, NPE_MAC_UNI_ADDR_4) & 0xff;
824         eaddr[4] = RD4(sc, NPE_MAC_UNI_ADDR_5) & 0xff;
825         eaddr[5] = RD4(sc, NPE_MAC_UNI_ADDR_6) & 0xff;
826 }
827
828 struct txdone {
829         struct npebuf *head;
830         struct npebuf **tail;
831         int count;
832 };
833
834 static __inline void
835 npe_txdone_finish(struct npe_softc *sc, const struct txdone *td)
836 {
837         struct ifnet *ifp = sc->sc_ifp;
838
839         NPE_LOCK(sc);
840         *td->tail = sc->tx_free;
841         sc->tx_free = td->head;
842         /*
843          * We're no longer busy, so clear the busy flag and call the
844          * start routine to xmit more packets.
845          */
846         ifp->if_opackets += td->count;
847         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
848         sc->npe_watchdog_timer = 0;
849         npestart_locked(ifp);
850         NPE_UNLOCK(sc);
851 }
852
853 /*
854  * Q manager callback on tx done queue.  Reap mbufs
855  * and return tx buffers to the free list.  Finally
856  * restart output.  Note the microcode has only one
857  * txdone q wired into it so we must use the NPE ID
858  * returned with each npehwbuf to decide where to
859  * send buffers.
860  */
861 static void
862 npe_txdone(int qid, void *arg)
863 {
864 #define P2V(a, dma) \
865         &(dma)->buf[((a) - (dma)->buf_phys) / sizeof(struct npehwbuf)]
866         struct npe_softc *sc0 = arg;
867         struct npe_softc *sc;
868         struct npebuf *npe;
869         struct txdone *td, q[NPE_MAX];
870         uint32_t entry;
871
872         /* XXX no NPE-A support */
873         q[NPE_B].tail = &q[NPE_B].head; q[NPE_B].count = 0;
874         q[NPE_C].tail = &q[NPE_C].head; q[NPE_C].count = 0;
875         /* XXX max # at a time? */
876         while (ixpqmgr_qread(qid, &entry) == 0) {
877                 DPRINTF(sc0, "%s: entry 0x%x NPE %u port %u\n",
878                     __func__, entry, NPE_QM_Q_NPE(entry), NPE_QM_Q_PORT(entry));
879
880                 sc = npes[NPE_QM_Q_NPE(entry)];
881                 npe = P2V(NPE_QM_Q_ADDR(entry), &sc->txdma);
882                 m_freem(npe->ix_m);
883                 npe->ix_m = NULL;
884
885                 td = &q[NPE_QM_Q_NPE(entry)];
886                 *td->tail = npe;
887                 td->tail = &npe->ix_next;
888                 td->count++;
889         }
890
891         if (q[NPE_B].count)
892                 npe_txdone_finish(npes[NPE_B], &q[NPE_B]);
893         if (q[NPE_C].count)
894                 npe_txdone_finish(npes[NPE_C], &q[NPE_C]);
895 #undef P2V
896 }
897
898 static int
899 npe_rxbuf_init(struct npe_softc *sc, struct npebuf *npe, struct mbuf *m)
900 {
901         bus_dma_segment_t segs[1];
902         struct npedma *dma = &sc->rxdma;
903         struct npehwbuf *hw;
904         int error, nseg;
905
906         if (m == NULL) {
907                 m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
908                 if (m == NULL)
909                         return ENOBUFS;
910         }
911         KASSERT(m->m_ext.ext_size >= 1536 + ETHER_ALIGN,
912                 ("ext_size %d", m->m_ext.ext_size));
913         m->m_pkthdr.len = m->m_len = 1536;
914         /* backload payload and align ip hdr */
915         m->m_data = m->m_ext.ext_buf + (m->m_ext.ext_size - (1536+ETHER_ALIGN));
916         error = bus_dmamap_load_mbuf_sg(dma->mtag, npe->ix_map, m,
917                         segs, &nseg, 0);
918         if (error != 0) {
919                 m_freem(m);
920                 return error;
921         }
922         hw = npe->ix_hw;
923         hw->ix_ne[0].data = htobe32(segs[0].ds_addr);
924         /* NB: NPE requires length be a multiple of 64 */
925         /* NB: buffer length is shifted in word */
926         hw->ix_ne[0].len = htobe32(segs[0].ds_len << 16);
927         hw->ix_ne[0].next = 0;
928         npe->ix_m = m;
929         /* Flush the memory in the mbuf */
930         bus_dmamap_sync(dma->mtag, npe->ix_map, BUS_DMASYNC_PREREAD);
931         return 0;
932 }
933
934 /*
935  * RX q processing for a specific NPE.  Claim entries
936  * from the hardware queue and pass the frames up the
937  * stack. Pass the rx buffers to the free list.
938  */
939 static void
940 npe_rxdone(int qid, void *arg)
941 {
942 #define P2V(a, dma) \
943         &(dma)->buf[((a) - (dma)->buf_phys) / sizeof(struct npehwbuf)]
944         struct npe_softc *sc = arg;
945         struct npedma *dma = &sc->rxdma;
946         uint32_t entry;
947
948         while (ixpqmgr_qread(qid, &entry) == 0) {
949                 struct npebuf *npe = P2V(NPE_QM_Q_ADDR(entry), dma);
950                 struct mbuf *m;
951
952                 DPRINTF(sc, "%s: entry 0x%x neaddr 0x%x ne_len 0x%x\n",
953                     __func__, entry, npe->ix_neaddr, npe->ix_hw->ix_ne[0].len);
954                 /*
955                  * Allocate a new mbuf to replenish the rx buffer.
956                  * If doing so fails we drop the rx'd frame so we
957                  * can reuse the previous mbuf.  When we're able to
958                  * allocate a new mbuf dispatch the mbuf w/ rx'd
959                  * data up the stack and replace it with the newly
960                  * allocated one.
961                  */
962                 m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
963                 if (m != NULL) {
964                         struct mbuf *mrx = npe->ix_m;
965                         struct npehwbuf *hw = npe->ix_hw;
966                         struct ifnet *ifp = sc->sc_ifp;
967
968                         /* Flush mbuf memory for rx'd data */
969                         bus_dmamap_sync(dma->mtag, npe->ix_map,
970                             BUS_DMASYNC_POSTREAD);
971
972                         /* XXX flush hw buffer; works now 'cuz coherent */
973                         /* set m_len etc. per rx frame size */
974                         mrx->m_len = be32toh(hw->ix_ne[0].len) & 0xffff;
975                         mrx->m_pkthdr.len = mrx->m_len;
976                         mrx->m_pkthdr.rcvif = ifp;
977                         mrx->m_flags |= M_HASFCS;
978
979                         ifp->if_ipackets++;
980                         ifp->if_input(ifp, mrx);
981                 } else {
982                         /* discard frame and re-use mbuf */
983                         m = npe->ix_m;
984                 }
985                 if (npe_rxbuf_init(sc, npe, m) == 0) {
986                         /* return npe buf to rx free list */
987                         ixpqmgr_qwrite(sc->rx_freeqid, npe->ix_neaddr);
988                 } else {
989                         /* XXX should not happen */
990                 }
991         }
992 #undef P2V
993 }
994
995 #ifdef DEVICE_POLLING
996 static void
997 npe_poll(struct ifnet *ifp, enum poll_cmd cmd, int count)
998 {
999         struct npe_softc *sc = ifp->if_softc;
1000
1001         if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1002                 npe_rxdone(sc->rx_qid, sc);
1003                 npe_txdone(sc->tx_doneqid, sc); /* XXX polls both NPE's */
1004         }
1005 }
1006 #endif /* DEVICE_POLLING */
1007
1008 static void
1009 npe_startxmit(struct npe_softc *sc)
1010 {
1011         struct npedma *dma = &sc->txdma;
1012         int i;
1013
1014         NPE_ASSERT_LOCKED(sc);
1015         sc->tx_free = NULL;
1016         for (i = 0; i < dma->nbuf; i++) {
1017                 struct npebuf *npe = &dma->buf[i];
1018                 if (npe->ix_m != NULL) {
1019                         /* NB: should not happen */
1020                         device_printf(sc->sc_dev,
1021                             "%s: free mbuf at entry %u\n", __func__, i);
1022                         m_freem(npe->ix_m);
1023                 }
1024                 npe->ix_m = NULL;
1025                 npe->ix_next = sc->tx_free;
1026                 sc->tx_free = npe;
1027         }
1028 }
1029
1030 static void
1031 npe_startrecv(struct npe_softc *sc)
1032 {
1033         struct npedma *dma = &sc->rxdma;
1034         struct npebuf *npe;
1035         int i;
1036
1037         NPE_ASSERT_LOCKED(sc);
1038         for (i = 0; i < dma->nbuf; i++) {
1039                 npe = &dma->buf[i];
1040                 npe_rxbuf_init(sc, npe, npe->ix_m);
1041                 /* set npe buf on rx free list */
1042                 ixpqmgr_qwrite(sc->rx_freeqid, npe->ix_neaddr);
1043         }
1044 }
1045
1046 /*
1047  * Reset and initialize the chip
1048  */
1049 static void
1050 npeinit_locked(void *xsc)
1051 {
1052         struct npe_softc *sc = xsc;
1053         struct ifnet *ifp = sc->sc_ifp;
1054
1055         NPE_ASSERT_LOCKED(sc);
1056 if (ifp->if_drv_flags & IFF_DRV_RUNNING) return;/*XXX*/
1057
1058         /*
1059          * Reset MAC core.
1060          */
1061         WR4(sc, NPE_MAC_CORE_CNTRL, NPE_CORE_RESET);
1062         DELAY(NPE_MAC_RESET_DELAY);
1063         /* configure MAC to generate MDC clock */
1064         WR4(sc, NPE_MAC_CORE_CNTRL, NPE_CORE_MDC_EN);
1065
1066         /* disable transmitter and reciver in the MAC */
1067         WR4(sc, NPE_MAC_RX_CNTRL1,
1068             RD4(sc, NPE_MAC_RX_CNTRL1) &~ NPE_RX_CNTRL1_RX_EN);
1069         WR4(sc, NPE_MAC_TX_CNTRL1,
1070             RD4(sc, NPE_MAC_TX_CNTRL1) &~ NPE_TX_CNTRL1_TX_EN);
1071
1072         /*
1073          * Set the MAC core registers.
1074          */
1075         WR4(sc, NPE_MAC_INT_CLK_THRESH, 0x1);   /* clock ratio: for ipx4xx */
1076         WR4(sc, NPE_MAC_TX_CNTRL2,      0xf);   /* max retries */
1077         WR4(sc, NPE_MAC_RANDOM_SEED,    0x8);   /* LFSR back-off seed */
1078         /* thresholds determined by NPE firmware FS */
1079         WR4(sc, NPE_MAC_THRESH_P_EMPTY, 0x12);
1080         WR4(sc, NPE_MAC_THRESH_P_FULL,  0x30);
1081         WR4(sc, NPE_MAC_BUF_SIZE_TX,    0x8);   /* tx fifo threshold (bytes) */
1082         WR4(sc, NPE_MAC_TX_DEFER,       0x15);  /* for single deferral */
1083         WR4(sc, NPE_MAC_RX_DEFER,       0x16);  /* deferral on inter-frame gap*/
1084         WR4(sc, NPE_MAC_TX_TWO_DEFER_1, 0x8);   /* for 2-part deferral */
1085         WR4(sc, NPE_MAC_TX_TWO_DEFER_2, 0x7);   /* for 2-part deferral */
1086         WR4(sc, NPE_MAC_SLOT_TIME,      0x80);  /* assumes MII mode */
1087
1088         WR4(sc, NPE_MAC_TX_CNTRL1,
1089                   NPE_TX_CNTRL1_RETRY           /* retry failed xmits */
1090                 | NPE_TX_CNTRL1_FCS_EN          /* append FCS */
1091                 | NPE_TX_CNTRL1_2DEFER          /* 2-part deferal */
1092                 | NPE_TX_CNTRL1_PAD_EN);        /* pad runt frames */
1093         /* XXX pad strip? */
1094         WR4(sc, NPE_MAC_RX_CNTRL1,
1095                   NPE_RX_CNTRL1_CRC_EN          /* include CRC/FCS */
1096                 | NPE_RX_CNTRL1_PAUSE_EN);      /* ena pause frame handling */
1097         WR4(sc, NPE_MAC_RX_CNTRL2, 0);
1098
1099         npe_setmac(sc, IF_LLADDR(ifp));
1100         npe_setmcast(sc);
1101
1102         npe_startxmit(sc);
1103         npe_startrecv(sc);
1104
1105         ifp->if_drv_flags |= IFF_DRV_RUNNING;
1106         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1107         sc->npe_watchdog_timer = 0;             /* just in case */
1108
1109         /* enable transmitter and reciver in the MAC */
1110         WR4(sc, NPE_MAC_RX_CNTRL1,
1111             RD4(sc, NPE_MAC_RX_CNTRL1) | NPE_RX_CNTRL1_RX_EN);
1112         WR4(sc, NPE_MAC_TX_CNTRL1,
1113             RD4(sc, NPE_MAC_TX_CNTRL1) | NPE_TX_CNTRL1_TX_EN);
1114
1115         callout_reset(&sc->tick_ch, sc->sc_tickinterval * hz, npe_tick, sc);
1116 }
1117
1118 static void
1119 npeinit(void *xsc)
1120 {
1121         struct npe_softc *sc = xsc;
1122         NPE_LOCK(sc);
1123         npeinit_locked(sc);
1124         NPE_UNLOCK(sc);
1125 }
1126
1127 /*
1128  * Defragment an mbuf chain, returning at most maxfrags separate
1129  * mbufs+clusters.  If this is not possible NULL is returned and
1130  * the original mbuf chain is left in it's present (potentially
1131  * modified) state.  We use two techniques: collapsing consecutive
1132  * mbufs and replacing consecutive mbufs by a cluster.
1133  */
1134 static struct mbuf *
1135 npe_defrag(struct mbuf *m0, int how, int maxfrags)
1136 {
1137         struct mbuf *m, *n, *n2, **prev;
1138         u_int curfrags;
1139
1140         /*
1141          * Calculate the current number of frags.
1142          */
1143         curfrags = 0;
1144         for (m = m0; m != NULL; m = m->m_next)
1145                 curfrags++;
1146         /*
1147          * First, try to collapse mbufs.  Note that we always collapse
1148          * towards the front so we don't need to deal with moving the
1149          * pkthdr.  This may be suboptimal if the first mbuf has much
1150          * less data than the following.
1151          */
1152         m = m0;
1153 again:
1154         for (;;) {
1155                 n = m->m_next;
1156                 if (n == NULL)
1157                         break;
1158                 if ((m->m_flags & M_RDONLY) == 0 &&
1159                     n->m_len < M_TRAILINGSPACE(m)) {
1160                         bcopy(mtod(n, void *), mtod(m, char *) + m->m_len,
1161                                 n->m_len);
1162                         m->m_len += n->m_len;
1163                         m->m_next = n->m_next;
1164                         m_free(n);
1165                         if (--curfrags <= maxfrags)
1166                                 return m0;
1167                 } else
1168                         m = n;
1169         }
1170         KASSERT(maxfrags > 1,
1171                 ("maxfrags %u, but normal collapse failed", maxfrags));
1172         /*
1173          * Collapse consecutive mbufs to a cluster.
1174          */
1175         prev = &m0->m_next;             /* NB: not the first mbuf */
1176         while ((n = *prev) != NULL) {
1177                 if ((n2 = n->m_next) != NULL &&
1178                     n->m_len + n2->m_len < MCLBYTES) {
1179                         m = m_getcl(how, MT_DATA, 0);
1180                         if (m == NULL)
1181                                 goto bad;
1182                         bcopy(mtod(n, void *), mtod(m, void *), n->m_len);
1183                         bcopy(mtod(n2, void *), mtod(m, char *) + n->m_len,
1184                                 n2->m_len);
1185                         m->m_len = n->m_len + n2->m_len;
1186                         m->m_next = n2->m_next;
1187                         *prev = m;
1188                         m_free(n);
1189                         m_free(n2);
1190                         if (--curfrags <= maxfrags)     /* +1 cl -2 mbufs */
1191                                 return m0;
1192                         /*
1193                          * Still not there, try the normal collapse
1194                          * again before we allocate another cluster.
1195                          */
1196                         goto again;
1197                 }
1198                 prev = &n->m_next;
1199         }
1200         /*
1201          * No place where we can collapse to a cluster; punt.
1202          * This can occur if, for example, you request 2 frags
1203          * but the packet requires that both be clusters (we
1204          * never reallocate the first mbuf to avoid moving the
1205          * packet header).
1206          */
1207 bad:
1208         return NULL;
1209 }
1210
1211 /*
1212  * Dequeue packets and place on the h/w transmit queue.
1213  */
1214 static void
1215 npestart_locked(struct ifnet *ifp)
1216 {
1217         struct npe_softc *sc = ifp->if_softc;
1218         struct npebuf *npe;
1219         struct npehwbuf *hw;
1220         struct mbuf *m, *n;
1221         struct npedma *dma = &sc->txdma;
1222         bus_dma_segment_t segs[NPE_MAXSEG];
1223         int nseg, len, error, i;
1224         uint32_t next;
1225
1226         NPE_ASSERT_LOCKED(sc);
1227         /* XXX can this happen? */
1228         if (ifp->if_drv_flags & IFF_DRV_OACTIVE)
1229                 return;
1230
1231         while (sc->tx_free != NULL) {
1232                 IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
1233                 if (m == NULL) {
1234                         /* XXX? */
1235                         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1236                         return;
1237                 }
1238                 npe = sc->tx_free;
1239                 error = bus_dmamap_load_mbuf_sg(dma->mtag, npe->ix_map,
1240                     m, segs, &nseg, 0);
1241                 if (error == EFBIG) {
1242                         n = npe_defrag(m, M_DONTWAIT, NPE_MAXSEG);
1243                         if (n == NULL) {
1244                                 if_printf(ifp, "%s: too many fragments %u\n",
1245                                     __func__, nseg);
1246                                 m_freem(m);
1247                                 return; /* XXX? */
1248                         }
1249                         m = n;
1250                         error = bus_dmamap_load_mbuf_sg(dma->mtag, npe->ix_map,
1251                             m, segs, &nseg, 0);
1252                 }
1253                 if (error != 0 || nseg == 0) {
1254                         if_printf(ifp, "%s: error %u nseg %u\n",
1255                             __func__, error, nseg);
1256                         m_freem(m);
1257                         return; /* XXX? */
1258                 }
1259                 sc->tx_free = npe->ix_next;
1260
1261                 bus_dmamap_sync(dma->mtag, npe->ix_map, BUS_DMASYNC_PREWRITE);
1262         
1263                 /*
1264                  * Tap off here if there is a bpf listener.
1265                  */
1266                 BPF_MTAP(ifp, m);
1267
1268                 npe->ix_m = m;
1269                 hw = npe->ix_hw;
1270                 len = m->m_pkthdr.len;
1271                 next = npe->ix_neaddr + sizeof(hw->ix_ne[0]);
1272                 for (i = 0; i < nseg; i++) {
1273                         hw->ix_ne[i].data = htobe32(segs[i].ds_addr);
1274                         hw->ix_ne[i].len = htobe32((segs[i].ds_len<<16) | len);
1275                         hw->ix_ne[i].next = htobe32(next);
1276
1277                         len = 0;                /* zero for segments > 1 */
1278                         next += sizeof(hw->ix_ne[0]);
1279                 }
1280                 hw->ix_ne[i-1].next = 0;        /* zero last in chain */
1281                 /* XXX flush descriptor instead of using uncached memory */
1282
1283                 DPRINTF(sc, "%s: qwrite(%u, 0x%x) ne_data %x ne_len 0x%x\n",
1284                     __func__, sc->tx_qid, npe->ix_neaddr,
1285                     hw->ix_ne[0].data, hw->ix_ne[0].len);
1286                 /* stick it on the tx q */
1287                 /* XXX add vlan priority */
1288                 ixpqmgr_qwrite(sc->tx_qid, npe->ix_neaddr);
1289
1290                 sc->npe_watchdog_timer = 5;
1291         }
1292         if (sc->tx_free == NULL)
1293                 ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1294 }
1295
1296 void
1297 npestart(struct ifnet *ifp)
1298 {
1299         struct npe_softc *sc = ifp->if_softc;
1300         NPE_LOCK(sc);
1301         npestart_locked(ifp);
1302         NPE_UNLOCK(sc);
1303 }
1304
1305 static void
1306 npe_stopxmit(struct npe_softc *sc)
1307 {
1308         struct npedma *dma = &sc->txdma;
1309         int i;
1310
1311         NPE_ASSERT_LOCKED(sc);
1312
1313         /* XXX qmgr */
1314         for (i = 0; i < dma->nbuf; i++) {
1315                 struct npebuf *npe = &dma->buf[i];
1316
1317                 if (npe->ix_m != NULL) {
1318                         bus_dmamap_unload(dma->mtag, npe->ix_map);
1319                         m_freem(npe->ix_m);
1320                         npe->ix_m = NULL;
1321                 }
1322         }
1323 }
1324
1325 static void
1326 npe_stoprecv(struct npe_softc *sc)
1327 {
1328         struct npedma *dma = &sc->rxdma;
1329         int i;
1330
1331         NPE_ASSERT_LOCKED(sc);
1332
1333         /* XXX qmgr */
1334         for (i = 0; i < dma->nbuf; i++) {
1335                 struct npebuf *npe = &dma->buf[i];
1336
1337                 if (npe->ix_m != NULL) {
1338                         bus_dmamap_unload(dma->mtag, npe->ix_map);
1339                         m_freem(npe->ix_m);
1340                         npe->ix_m = NULL;
1341                 }
1342         }
1343 }
1344
1345 /*
1346  * Turn off interrupts, and stop the nic.
1347  */
1348 void
1349 npestop(struct npe_softc *sc)
1350 {
1351         struct ifnet *ifp = sc->sc_ifp;
1352
1353         /*  disable transmitter and reciver in the MAC  */
1354         WR4(sc, NPE_MAC_RX_CNTRL1,
1355             RD4(sc, NPE_MAC_RX_CNTRL1) &~ NPE_RX_CNTRL1_RX_EN);
1356         WR4(sc, NPE_MAC_TX_CNTRL1,
1357             RD4(sc, NPE_MAC_TX_CNTRL1) &~ NPE_TX_CNTRL1_TX_EN);
1358
1359         sc->npe_watchdog_timer = 0;
1360         ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
1361
1362         callout_stop(&sc->tick_ch);
1363
1364         npe_stopxmit(sc);
1365         npe_stoprecv(sc);
1366         /* XXX go into loopback & drain q's? */
1367         /* XXX but beware of disabling tx above */
1368
1369         /*
1370          * The MAC core rx/tx disable may leave the MAC hardware in an
1371          * unpredictable state. A hw reset is executed before resetting 
1372          * all the MAC parameters to a known value.
1373          */
1374         WR4(sc, NPE_MAC_CORE_CNTRL, NPE_CORE_RESET);
1375         DELAY(NPE_MAC_RESET_DELAY);
1376         WR4(sc, NPE_MAC_INT_CLK_THRESH, NPE_MAC_INT_CLK_THRESH_DEFAULT);
1377         WR4(sc, NPE_MAC_CORE_CNTRL, NPE_CORE_MDC_EN);
1378 }
1379
1380 void
1381 npewatchdog(struct npe_softc *sc)
1382 {
1383         NPE_ASSERT_LOCKED(sc);
1384
1385         if (sc->npe_watchdog_timer == 0 || --sc->npe_watchdog_timer != 0)
1386                 return;
1387
1388         device_printf(sc->sc_dev, "watchdog timeout\n");
1389         sc->sc_ifp->if_oerrors++;
1390
1391         npeinit_locked(sc);
1392 }
1393
1394 static int
1395 npeioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1396 {
1397         struct npe_softc *sc = ifp->if_softc;
1398         struct mii_data *mii;
1399         struct ifreq *ifr = (struct ifreq *)data;       
1400         int error = 0;
1401 #ifdef DEVICE_POLLING
1402         int mask;
1403 #endif
1404
1405         switch (cmd) {
1406         case SIOCSIFFLAGS:
1407                 NPE_LOCK(sc);
1408                 if ((ifp->if_flags & IFF_UP) == 0 &&
1409                     ifp->if_drv_flags & IFF_DRV_RUNNING) {
1410                         ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
1411                         npestop(sc);
1412                 } else {
1413                         /* reinitialize card on any parameter change */
1414                         npeinit_locked(sc);
1415                 }
1416                 NPE_UNLOCK(sc);
1417                 break;
1418
1419         case SIOCADDMULTI:
1420         case SIOCDELMULTI:
1421                 /* update multicast filter list. */
1422                 NPE_LOCK(sc);
1423                 npe_setmcast(sc);
1424                 NPE_UNLOCK(sc);
1425                 error = 0;
1426                 break;
1427
1428         case SIOCSIFMEDIA:
1429         case SIOCGIFMEDIA:
1430                 mii = device_get_softc(sc->sc_mii);
1431                 error = ifmedia_ioctl(ifp, ifr, &mii->mii_media, cmd);
1432                 break;
1433
1434 #ifdef DEVICE_POLLING
1435         case SIOCSIFCAP:
1436                 mask = ifp->if_capenable ^ ifr->ifr_reqcap;
1437                 if (mask & IFCAP_POLLING) {
1438                         if (ifr->ifr_reqcap & IFCAP_POLLING) {
1439                                 error = ether_poll_register(npe_poll, ifp);
1440                                 if (error)
1441                                         return error;
1442                                 NPE_LOCK(sc);
1443                                 /* disable callbacks XXX txdone is shared */
1444                                 ixpqmgr_notify_disable(sc->rx_qid);
1445                                 ixpqmgr_notify_disable(sc->tx_doneqid);
1446                                 ifp->if_capenable |= IFCAP_POLLING;
1447                                 NPE_UNLOCK(sc);
1448                         } else {
1449                                 error = ether_poll_deregister(ifp);
1450                                 /* NB: always enable qmgr callbacks */
1451                                 NPE_LOCK(sc);
1452                                 /* enable qmgr callbacks */
1453                                 ixpqmgr_notify_enable(sc->rx_qid,
1454                                     IX_QMGR_Q_SOURCE_ID_NOT_E);
1455                                 ixpqmgr_notify_enable(sc->tx_doneqid,
1456                                     IX_QMGR_Q_SOURCE_ID_NOT_E);
1457                                 ifp->if_capenable &= ~IFCAP_POLLING;
1458                                 NPE_UNLOCK(sc);
1459                         }
1460                 }
1461                 break;
1462 #endif
1463         default:
1464                 error = ether_ioctl(ifp, cmd, data);
1465                 break;
1466         }
1467         return error;
1468 }
1469
1470 /*
1471  * Setup a traffic class -> rx queue mapping.
1472  */
1473 static int
1474 npe_setrxqosentry(struct npe_softc *sc, int classix, int trafclass, int qid)
1475 {
1476         int npeid = npeconfig[device_get_unit(sc->sc_dev)].npeid;
1477         uint32_t msg[2];
1478
1479         msg[0] = (NPE_SETRXQOSENTRY << 24) | (npeid << 20) | classix;
1480         msg[1] = (trafclass << 24) | (1 << 23) | (qid << 16) | (qid << 4);
1481         return ixpnpe_sendandrecvmsg(sc->sc_npe, msg, msg);
1482 }
1483
1484 /*
1485  * Update and reset the statistics in the NPE.
1486  */
1487 static int
1488 npe_updatestats(struct npe_softc *sc)
1489 {
1490         uint32_t msg[2];
1491
1492         msg[0] = NPE_RESETSTATS << NPE_MAC_MSGID_SHL;
1493         msg[1] = sc->sc_stats_phys;     /* physical address of stat block */
1494         return ixpnpe_sendmsg(sc->sc_npe, msg);         /* NB: no recv */
1495 }
1496
1497 #if 0
1498 /*
1499  * Get the current statistics block.
1500  */
1501 static int
1502 npe_getstats(struct npe_softc *sc)
1503 {
1504         uint32_t msg[2];
1505
1506         msg[0] = NPE_GETSTATS << NPE_MAC_MSGID_SHL;
1507         msg[1] = sc->sc_stats_phys;     /* physical address of stat block */
1508         return ixpnpe_sendandrecvmsg(sc->sc_npe, msg, msg);
1509 }
1510
1511 /*
1512  * Query the image id of the loaded firmware.
1513  */
1514 static uint32_t
1515 npe_getimageid(struct npe_softc *sc)
1516 {
1517         uint32_t msg[2];
1518
1519         msg[0] = NPE_GETSTATUS << NPE_MAC_MSGID_SHL;
1520         msg[1] = 0;
1521         return ixpnpe_sendandrecvmsg(sc->sc_npe, msg, msg) == 0 ? msg[1] : 0;
1522 }
1523
1524 /*
1525  * Enable/disable loopback.
1526  */
1527 static int
1528 npe_setloopback(struct npe_softc *sc, int ena)
1529 {
1530         uint32_t msg[2];
1531
1532         msg[0] = (NPE_SETLOOPBACK << NPE_MAC_MSGID_SHL) | (ena != 0);
1533         msg[1] = 0;
1534         return ixpnpe_sendandrecvmsg(sc->sc_npe, msg, msg);
1535 }
1536 #endif
1537
1538 static void
1539 npe_child_detached(device_t dev, device_t child)
1540 {
1541         struct npe_softc *sc;
1542
1543         sc = device_get_softc(dev);
1544         if (child == sc->sc_mii)
1545                 sc->sc_mii = NULL;
1546 }
1547
1548 /*
1549  * MII bus support routines.
1550  *
1551  * NB: ixp425 has one PHY per NPE
1552  */
1553 static uint32_t
1554 npe_mii_mdio_read(struct npe_softc *sc, int reg)
1555 {
1556 #define MII_RD4(sc, reg)        bus_space_read_4(sc->sc_iot, sc->sc_miih, reg)
1557         uint32_t v;
1558
1559         /* NB: registers are known to be sequential */
1560         v =  (MII_RD4(sc, reg+0) & 0xff) << 0;
1561         v |= (MII_RD4(sc, reg+4) & 0xff) << 8;
1562         v |= (MII_RD4(sc, reg+8) & 0xff) << 16;
1563         v |= (MII_RD4(sc, reg+12) & 0xff) << 24;
1564         return v;
1565 #undef MII_RD4
1566 }
1567
1568 static void
1569 npe_mii_mdio_write(struct npe_softc *sc, int reg, uint32_t cmd)
1570 {
1571 #define MII_WR4(sc, reg, v) \
1572         bus_space_write_4(sc->sc_iot, sc->sc_miih, reg, v)
1573
1574         /* NB: registers are known to be sequential */
1575         MII_WR4(sc, reg+0, cmd & 0xff);
1576         MII_WR4(sc, reg+4, (cmd >> 8) & 0xff);
1577         MII_WR4(sc, reg+8, (cmd >> 16) & 0xff);
1578         MII_WR4(sc, reg+12, (cmd >> 24) & 0xff);
1579 #undef MII_WR4
1580 }
1581
1582 static int
1583 npe_mii_mdio_wait(struct npe_softc *sc)
1584 {
1585 #define MAXTRIES        100     /* XXX */
1586         uint32_t v;
1587         int i;
1588
1589         for (i = 0; i < MAXTRIES; i++) {
1590                 v = npe_mii_mdio_read(sc, NPE_MAC_MDIO_CMD);
1591                 if ((v & NPE_MII_GO) == 0)
1592                         return 1;
1593         }
1594         return 0;               /* NB: timeout */
1595 #undef MAXTRIES
1596 }
1597
1598 static int
1599 npe_miibus_readreg(device_t dev, int phy, int reg)
1600 {
1601         struct npe_softc *sc = device_get_softc(dev);
1602         uint32_t v;
1603
1604         if (phy != device_get_unit(dev))        /* XXX */
1605                 return 0xffff;
1606         v = (phy << NPE_MII_ADDR_SHL) | (reg << NPE_MII_REG_SHL)
1607           | NPE_MII_GO;
1608         npe_mii_mdio_write(sc, NPE_MAC_MDIO_CMD, v);
1609         if (npe_mii_mdio_wait(sc))
1610                 v = npe_mii_mdio_read(sc, NPE_MAC_MDIO_STS);
1611         else
1612                 v = 0xffff | NPE_MII_READ_FAIL;
1613         return (v & NPE_MII_READ_FAIL) ? 0xffff : (v & 0xffff);
1614 #undef MAXTRIES
1615 }
1616
1617 static void
1618 npe_miibus_writereg(device_t dev, int phy, int reg, int data)
1619 {
1620         struct npe_softc *sc = device_get_softc(dev);
1621         uint32_t v;
1622
1623         if (phy != device_get_unit(dev))        /* XXX */
1624                 return;
1625         v = (phy << NPE_MII_ADDR_SHL) | (reg << NPE_MII_REG_SHL)
1626           | data | NPE_MII_WRITE
1627           | NPE_MII_GO;
1628         npe_mii_mdio_write(sc, NPE_MAC_MDIO_CMD, v);
1629         /* XXX complain about timeout */
1630         (void) npe_mii_mdio_wait(sc);
1631 }
1632
1633 static void
1634 npe_miibus_statchg(device_t dev)
1635 {
1636         struct npe_softc *sc = device_get_softc(dev);
1637         struct mii_data *mii = device_get_softc(sc->sc_mii);
1638         uint32_t tx1, rx1;
1639
1640         /* sync MAC duplex state */
1641         tx1 = RD4(sc, NPE_MAC_TX_CNTRL1);
1642         rx1 = RD4(sc, NPE_MAC_RX_CNTRL1);
1643         if ((mii->mii_media_active & IFM_GMASK) == IFM_FDX) {
1644                 tx1 &= ~NPE_TX_CNTRL1_DUPLEX;
1645                 rx1 |= NPE_RX_CNTRL1_PAUSE_EN;
1646         } else {
1647                 tx1 |= NPE_TX_CNTRL1_DUPLEX;
1648                 rx1 &= ~NPE_RX_CNTRL1_PAUSE_EN;
1649         }
1650         WR4(sc, NPE_MAC_RX_CNTRL1, rx1);
1651         WR4(sc, NPE_MAC_TX_CNTRL1, tx1);
1652 }
1653
1654 static device_method_t npe_methods[] = {
1655         /* Device interface */
1656         DEVMETHOD(device_probe,         npe_probe),
1657         DEVMETHOD(device_attach,        npe_attach),
1658         DEVMETHOD(device_detach,        npe_detach),
1659
1660         /* Bus interface */
1661         DEVMETHOD(bus_child_detached,   npe_child_detached),
1662
1663         /* MII interface */
1664         DEVMETHOD(miibus_readreg,       npe_miibus_readreg),
1665         DEVMETHOD(miibus_writereg,      npe_miibus_writereg),
1666         DEVMETHOD(miibus_statchg,       npe_miibus_statchg),
1667
1668         { 0, 0 }
1669 };
1670
1671 static driver_t npe_driver = {
1672         "npe",
1673         npe_methods,
1674         sizeof(struct npe_softc),
1675 };
1676
1677 DRIVER_MODULE(npe, ixp, npe_driver, npe_devclass, 0, 0);
1678 DRIVER_MODULE(miibus, npe, miibus_driver, miibus_devclass, 0, 0);
1679 MODULE_DEPEND(npe, ixpqmgr, 1, 1, 1);
1680 MODULE_DEPEND(npe, miibus, 1, 1, 1);
1681 MODULE_DEPEND(npe, ether, 1, 1, 1);