]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/arm/at91/if_ate.c
MFV r308954:
[FreeBSD/FreeBSD.git] / sys / arm / at91 / if_ate.c
1 /*-
2  * Copyright (c) 2006 M. Warner Losh.  All rights reserved.
3  * Copyright (c) 2009 Greg Ansley.  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 AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER 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
27 /* TODO
28  *
29  * 1) Turn on the clock in pmc?  Turn off?
30  * 2) GPIO initializtion in board setup code.
31  */
32
33 #include "opt_platform.h"
34
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37
38 #include <sys/param.h>
39 #include <sys/systm.h>
40 #include <sys/bus.h>
41 #include <sys/kernel.h>
42 #include <sys/malloc.h>
43 #include <sys/mbuf.h>
44 #include <sys/module.h>
45 #include <sys/rman.h>
46 #include <sys/socket.h>
47 #include <sys/sockio.h>
48 #include <sys/sysctl.h>
49
50 #include <machine/bus.h>
51
52 #include <net/ethernet.h>
53 #include <net/if.h>
54 #include <net/if_arp.h>
55 #include <net/if_dl.h>
56 #include <net/if_media.h>
57 #include <net/if_mib.h>
58 #include <net/if_types.h>
59 #include <net/if_var.h>
60
61 #ifdef INET
62 #include <netinet/in.h>
63 #include <netinet/in_systm.h>
64 #include <netinet/in_var.h>
65 #include <netinet/ip.h>
66 #endif
67
68 #include <net/bpf.h>
69 #include <net/bpfdesc.h>
70
71 #include <dev/mii/mii.h>
72 #include <dev/mii/miivar.h>
73
74 #include "opt_at91.h"
75 #include <arm/at91/at91reg.h>
76 #include <arm/at91/at91var.h>
77 #include <arm/at91/if_atereg.h>
78
79 #ifdef FDT
80 #include <dev/ofw/ofw_bus.h>
81 #include <dev/ofw/ofw_bus_subr.h>
82 #endif
83
84 #include "miibus_if.h"
85
86 /*
87  * Driver-specific flags.
88  */
89 #define ATE_FLAG_DETACHING      0x01
90 #define ATE_FLAG_MULTICAST      0x02
91
92 /*
93  * Old EMAC assumes whole packet fits in one buffer;
94  * new EBACB assumes all receive buffers are 128 bytes
95  */
96 #define RX_BUF_SIZE(sc) (sc->is_emacb ? 128 : MCLBYTES)
97
98 /*
99  * EMACB has an 11 bit counter for Rx/Tx Descriptors
100  * for max total of 1024 decriptors each.
101  */
102 #define ATE_MAX_RX_DESCR        1024
103 #define ATE_MAX_TX_DESCR        1024
104
105 /* How many buffers to allocate */
106 #define ATE_MAX_TX_BUFFERS      4       /* We have ping-pong tx buffers */
107
108 /* How much memory to use for rx buffers */
109 #define ATE_RX_MEMORY           (ATE_MAX_RX_DESCR * 128)
110
111 /* Actual number of descriptors we allocate */
112 #define ATE_NUM_RX_DESCR        ATE_MAX_RX_DESCR
113 #define ATE_NUM_TX_DESCR        ATE_MAX_TX_BUFFERS
114
115 #if ATE_NUM_TX_DESCR > ATE_MAX_TX_DESCR
116 #error "Can't have more TX buffers that descriptors"
117 #endif
118 #if ATE_NUM_RX_DESCR > ATE_MAX_RX_DESCR
119 #error "Can't have more RX buffers that descriptors"
120 #endif
121
122 /* Wrap indexes the same way the hardware does */
123 #define NEXT_RX_IDX(sc, cur)    \
124     ((sc->rx_descs[cur].addr & ETH_WRAP_BIT) ? 0 : (cur + 1))
125
126 #define NEXT_TX_IDX(sc, cur)    \
127     ((sc->tx_descs[cur].status & ETHB_TX_WRAP) ? 0 : (cur + 1))
128
129 struct ate_softc
130 {
131         struct ifnet    *ifp;           /* ifnet pointer */
132         struct mtx      sc_mtx;         /* Basically a perimeter lock */
133         device_t        dev;            /* Myself */
134         device_t        miibus;         /* My child miibus */
135         struct resource *irq_res;       /* IRQ resource */
136         struct resource *mem_res;       /* Memory resource */
137         struct callout  tick_ch;        /* Tick callout */
138         struct ifmib_iso_8802_3 mibdata; /* Stuff for network mgmt */
139         bus_dma_tag_t   mtag;           /* bus dma tag for mbufs */
140         bus_dma_tag_t   rx_tag;
141         bus_dma_tag_t   rx_desc_tag;
142         bus_dmamap_t    rx_desc_map;
143         bus_dmamap_t    rx_map[ATE_MAX_RX_DESCR];
144         bus_addr_t      rx_desc_phys;   /* PA of rx descriptors */
145         eth_rx_desc_t   *rx_descs;      /* VA of rx descriptors */
146         void            *rx_buf[ATE_NUM_RX_DESCR]; /* RX buffer space */
147         int             rxhead;         /* Current RX map/desc index */
148         uint32_t        rx_buf_size;    /* Size of Rx buffers */
149
150         bus_dma_tag_t   tx_desc_tag;
151         bus_dmamap_t    tx_desc_map;
152         bus_dmamap_t    tx_map[ATE_MAX_TX_BUFFERS];
153         bus_addr_t      tx_desc_phys;   /* PA of tx descriptors */
154         eth_tx_desc_t   *tx_descs;      /* VA of tx descriptors */
155         int             txhead;         /* Current TX map/desc index */
156         int             txtail;         /* Current TX map/desc index */
157         struct mbuf     *sent_mbuf[ATE_MAX_TX_BUFFERS]; /* Sent mbufs */
158         void            *intrhand;      /* Interrupt handle */
159         int             flags;
160         int             if_flags;
161         int             use_rmii;
162         int             is_emacb;       /* SAM9x hardware version */
163 };
164
165 static inline uint32_t
166 RD4(struct ate_softc *sc, bus_size_t off)
167 {
168
169         return (bus_read_4(sc->mem_res, off));
170 }
171
172 static inline void
173 WR4(struct ate_softc *sc, bus_size_t off, uint32_t val)
174 {
175
176         bus_write_4(sc->mem_res, off, val);
177 }
178
179 static inline void
180 BARRIER(struct ate_softc *sc, bus_size_t off, bus_size_t len, int flags)
181 {
182
183         bus_barrier(sc->mem_res, off, len, flags);
184 }
185
186 #define ATE_LOCK(_sc)           mtx_lock(&(_sc)->sc_mtx)
187 #define ATE_UNLOCK(_sc)         mtx_unlock(&(_sc)->sc_mtx)
188 #define ATE_LOCK_INIT(_sc)                                      \
189         mtx_init(&_sc->sc_mtx, device_get_nameunit(_sc->dev),   \
190             MTX_NETWORK_LOCK, MTX_DEF)
191 #define ATE_LOCK_DESTROY(_sc)   mtx_destroy(&_sc->sc_mtx);
192 #define ATE_ASSERT_LOCKED(_sc)  mtx_assert(&_sc->sc_mtx, MA_OWNED);
193 #define ATE_ASSERT_UNLOCKED(_sc) mtx_assert(&_sc->sc_mtx, MA_NOTOWNED);
194
195 static devclass_t ate_devclass;
196
197 /*
198  * ifnet entry points.
199  */
200 static void     ateinit_locked(void *);
201 static void     atestart_locked(struct ifnet *);
202
203 static void     ateinit(void *);
204 static void     atestart(struct ifnet *);
205 static void     atestop(struct ate_softc *);
206 static int      ateioctl(struct ifnet * ifp, u_long, caddr_t);
207
208 /*
209  * Bus entry points.
210  */
211 static int      ate_probe(device_t dev);
212 static int      ate_attach(device_t dev);
213 static int      ate_detach(device_t dev);
214 static void     ate_intr(void *);
215
216 /*
217  * Helper routines.
218  */
219 static int      ate_activate(device_t dev);
220 static void     ate_deactivate(struct ate_softc *sc);
221 static int      ate_ifmedia_upd(struct ifnet *ifp);
222 static void     ate_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr);
223 static int      ate_get_mac(struct ate_softc *sc, u_char *eaddr);
224 static void     ate_set_mac(struct ate_softc *sc, u_char *eaddr);
225 static void     ate_rxfilter(struct ate_softc *sc);
226
227 static int      ate_miibus_readreg(device_t dev, int phy, int reg);
228
229 static int      ate_miibus_writereg(device_t dev, int phy, int reg, int data);
230
231 /*
232  * The AT91 family of products has the ethernet interface called EMAC.
233  * However, it isn't self identifying.  It is anticipated that the parent bus
234  * code will take care to only add ate devices where they really are.  As
235  * such, we do nothing here to identify the device and just set its name.
236  * However, FDT makes it self-identifying.
237  */
238 static int
239 ate_probe(device_t dev)
240 {
241 #ifdef FDT
242         if (!ofw_bus_is_compatible(dev, "cdns,at91rm9200-emac") &&
243             !ofw_bus_is_compatible(dev, "cdns,emac") &&
244             !ofw_bus_is_compatible(dev, "cdns,at32ap7000-macb"))
245                 return (ENXIO);
246 #endif
247         device_set_desc(dev, "EMAC");
248         return (0);
249 }
250
251 #ifdef FDT
252 /*
253  * We have to know if we're using MII or RMII attachment
254  * for the MACB to talk to the PHY correctly. With FDT,
255  * we must use rmii if there's a proprety phy-mode
256  * equal to "rmii". Otherwise we MII mode is used.
257  */
258 static void
259 ate_set_rmii(struct ate_softc *sc)
260 {
261         phandle_t node;
262         char prop[10];
263         ssize_t len;
264
265         node = ofw_bus_get_node(sc->dev);
266         memset(prop, 0 ,sizeof(prop));
267         len = OF_getproplen(node, "phy-mode");
268         if (len != 4)
269                 return;
270         if (OF_getprop(node, "phy-mode", prop, len) != len)
271                 return;
272         if (strncmp(prop, "rmii", 4) == 0)
273                 sc->use_rmii = 1;
274 }
275
276 #else
277 /*
278  * We have to know if we're using MII or RMII attachment
279  * for the MACB to talk to the PHY correctly. Without FDT,
280  * there's no good way to do this. So, if the config file
281  * has 'option AT91_ATE_USE_RMII', then we'll force RMII.
282  * Otherwise, we'll use what the bootloader setup. Either
283  * it setup RMII or MII, in which case we'll get it right,
284  * or it did nothing, and we'll fall back to MII and the
285  * option would override if present.
286  */
287 static void
288 ate_set_rmii(struct ate_softc *sc)
289 {
290
291         /* Default to what boot rom did */
292         if (!sc->is_emacb)
293                 sc->use_rmii =
294                     (RD4(sc, ETH_CFG) & ETH_CFG_RMII) == ETH_CFG_RMII;
295         else
296                 sc->use_rmii =
297                     (RD4(sc, ETHB_UIO) & ETHB_UIO_RMII) == ETHB_UIO_RMII;
298
299 #ifdef AT91_ATE_USE_RMII
300         /* Compile time override */
301         sc->use_rmii = 1;
302 #endif
303 }
304 #endif
305
306 static int
307 ate_attach(device_t dev)
308 {
309         struct ate_softc *sc;
310         struct ifnet *ifp = NULL;
311         struct sysctl_ctx_list *sctx;
312         struct sysctl_oid *soid;
313         u_char eaddr[ETHER_ADDR_LEN];
314         uint32_t rnd;
315         int rid, err;
316
317         sc = device_get_softc(dev);
318         sc->dev = dev;
319         ATE_LOCK_INIT(sc);
320
321         rid = 0;
322         sc->mem_res = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid,
323             RF_ACTIVE);
324         if (sc->mem_res == NULL) {
325                 device_printf(dev, "could not allocate memory resources.\n");
326                 err = ENOMEM;
327                 goto out;
328         }
329         rid = 0;
330         sc->irq_res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
331             RF_ACTIVE);
332         if (sc->irq_res == NULL) {
333                 device_printf(dev, "could not allocate interrupt resources.\n");
334                 err = ENOMEM;
335                 goto out;
336         }
337
338         /* New or old version, chooses buffer size. */
339 #ifdef FDT
340         sc->is_emacb = ofw_bus_is_compatible(dev, "cdns,at32ap7000-macb");
341 #else
342         sc->is_emacb = at91_is_sam9() || at91_is_sam9xe();
343 #endif
344         sc->rx_buf_size = RX_BUF_SIZE(sc);
345
346         err = ate_activate(dev);
347         if (err)
348                 goto out;
349
350         ate_set_rmii(sc);
351
352         /* Sysctls */
353         sctx = device_get_sysctl_ctx(dev);
354         soid = device_get_sysctl_tree(dev);
355         SYSCTL_ADD_UINT(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "rmii",
356             CTLFLAG_RW, &sc->use_rmii, 0, "rmii in use");
357
358         /* Calling atestop before ifp is set is OK. */
359         ATE_LOCK(sc);
360         atestop(sc);
361         ATE_UNLOCK(sc);
362         callout_init_mtx(&sc->tick_ch, &sc->sc_mtx, 0);
363
364         if ((err = ate_get_mac(sc, eaddr)) != 0) {
365                 /* No MAC address configured. Generate the random one. */
366                 if (bootverbose)
367                         device_printf(dev,
368                             "Generating random ethernet address.\n");
369                 rnd = arc4random();
370
371                 /*
372                  * Set OUI to convenient locally assigned address.  'b'
373                  * is 0x62, which has the locally assigned bit set, and
374                  * the broadcast/multicast bit clear.
375                  */
376                 eaddr[0] = 'b';
377                 eaddr[1] = 's';
378                 eaddr[2] = 'd';
379                 eaddr[3] = (rnd >> 16) & 0xff;
380                 eaddr[4] = (rnd >>  8) & 0xff;
381                 eaddr[5] = (rnd >>  0) & 0xff;
382         }
383
384         sc->ifp = ifp = if_alloc(IFT_ETHER);
385         err = mii_attach(dev, &sc->miibus, ifp, ate_ifmedia_upd,
386             ate_ifmedia_sts, BMSR_DEFCAPMASK, MII_PHY_ANY, MII_OFFSET_ANY, 0);
387         if (err != 0) {
388                 device_printf(dev, "attaching PHYs failed\n");
389                 goto out;
390         }
391         /*
392          * XXX: Clear the isolate bit, or we won't get up,
393          * at least on the HL201
394          */
395         ate_miibus_writereg(dev, 0, 0, 0x3000);
396
397         ifp->if_softc = sc;
398         if_initname(ifp, device_get_name(dev), device_get_unit(dev));
399         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
400         ifp->if_capabilities |= IFCAP_VLAN_MTU;
401         ifp->if_capenable |= IFCAP_VLAN_MTU;    /* The hw bits already set. */
402         ifp->if_start = atestart;
403         ifp->if_ioctl = ateioctl;
404         ifp->if_init = ateinit;
405         ifp->if_baudrate = 10000000;
406         IFQ_SET_MAXLEN(&ifp->if_snd, IFQ_MAXLEN);
407         ifp->if_snd.ifq_drv_maxlen = IFQ_MAXLEN;
408         IFQ_SET_READY(&ifp->if_snd);
409         ifp->if_linkmib = &sc->mibdata;
410         ifp->if_linkmiblen = sizeof(sc->mibdata);
411         sc->mibdata.dot3Compliance = DOT3COMPLIANCE_COLLS;
412         sc->if_flags = ifp->if_flags;
413
414         ether_ifattach(ifp, eaddr);
415
416         /* Activate the interrupt. */
417         err = bus_setup_intr(dev, sc->irq_res, INTR_TYPE_NET | INTR_MPSAFE,
418             NULL, ate_intr, sc, &sc->intrhand);
419         if (err) {
420                 device_printf(dev, "could not establish interrupt handler.\n");
421                 ether_ifdetach(ifp);
422                 goto out;
423         }
424
425 out:
426         if (err)
427                 ate_detach(dev);
428         return (err);
429 }
430
431 static int
432 ate_detach(device_t dev)
433 {
434         struct ate_softc *sc;
435         struct ifnet *ifp;
436
437         sc = device_get_softc(dev);
438         KASSERT(sc != NULL, ("[ate: %d]: sc is NULL", __LINE__));
439         ifp = sc->ifp;
440         if (device_is_attached(dev)) {
441                 ATE_LOCK(sc);
442                         sc->flags |= ATE_FLAG_DETACHING;
443                         atestop(sc);
444                 ATE_UNLOCK(sc);
445                 callout_drain(&sc->tick_ch);
446                 ether_ifdetach(ifp);
447         }
448         if (sc->miibus != NULL) {
449                 device_delete_child(dev, sc->miibus);
450                 sc->miibus = NULL;
451         }
452         bus_generic_detach(sc->dev);
453         ate_deactivate(sc);
454         if (sc->intrhand != NULL) {
455                 bus_teardown_intr(dev, sc->irq_res, sc->intrhand);
456                 sc->intrhand = NULL;
457         }
458         if (ifp != NULL) {
459                 if_free(ifp);
460                 sc->ifp = NULL;
461         }
462         if (sc->mem_res != NULL) {
463                 bus_release_resource(dev, SYS_RES_IOPORT,
464                     rman_get_rid(sc->mem_res), sc->mem_res);
465                 sc->mem_res = NULL;
466         }
467         if (sc->irq_res != NULL) {
468                 bus_release_resource(dev, SYS_RES_IRQ,
469                     rman_get_rid(sc->irq_res), sc->irq_res);
470                 sc->irq_res = NULL;
471         }
472         ATE_LOCK_DESTROY(sc);
473         return (0);
474 }
475
476 static void
477 ate_getaddr(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
478 {
479
480         if (error != 0)
481                 return;
482         *(bus_addr_t *)arg = segs[0].ds_addr;
483 }
484
485 static void
486 ate_load_rx_buf(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
487 {
488         struct ate_softc *sc;
489
490         if (error != 0)
491                 return;
492         sc = (struct ate_softc *)arg;
493
494         bus_dmamap_sync(sc->rx_desc_tag, sc->rx_desc_map, BUS_DMASYNC_PREWRITE);
495         sc->rx_descs[sc->rxhead].addr = segs[0].ds_addr;
496         sc->rx_descs[sc->rxhead].status = 0;
497         bus_dmamap_sync(sc->rx_desc_tag, sc->rx_desc_map, BUS_DMASYNC_POSTWRITE);
498 }
499
500 static uint32_t
501 ate_mac_hash(const uint8_t *buf)
502 {
503         uint32_t index = 0;
504         for (int i = 0; i < 48; i++) {
505                 index ^= ((buf[i >> 3] >> (i & 7)) & 1) << (i % 6);
506         }
507         return (index);
508 }
509
510 /*
511  * Compute the multicast filter for this device.
512  */
513 static int
514 ate_setmcast(struct ate_softc *sc)
515 {
516         uint32_t index;
517         uint32_t mcaf[2];
518         u_char *af = (u_char *) mcaf;
519         struct ifmultiaddr *ifma;
520         struct ifnet *ifp;
521
522         ifp = sc->ifp;
523
524         if ((ifp->if_flags & IFF_PROMISC) != 0)
525                 return (0);
526         if ((ifp->if_flags & IFF_ALLMULTI) != 0) {
527                 WR4(sc, ETH_HSL, 0xffffffff);
528                 WR4(sc, ETH_HSH, 0xffffffff);
529                 return (1);
530         }
531
532         /* Compute the multicast hash. */
533         mcaf[0] = 0;
534         mcaf[1] = 0;
535         if_maddr_rlock(ifp);
536         TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
537                 if (ifma->ifma_addr->sa_family != AF_LINK)
538                         continue;
539                 index = ate_mac_hash(LLADDR((struct sockaddr_dl *)
540                     ifma->ifma_addr));
541                 af[index >> 3] |= 1 << (index & 7);
542         }
543         if_maddr_runlock(ifp);
544
545         /*
546          * Write the hash to the hash register.  This card can also
547          * accept unicast packets as well as multicast packets using this
548          * register for easier bridging operations, but we don't take
549          * advantage of that.  Locks here are to avoid LOR with the
550          * if_maddr_rlock, but might not be strictly necessary.
551          */
552         WR4(sc, ETH_HSL, mcaf[0]);
553         WR4(sc, ETH_HSH, mcaf[1]);
554         return (mcaf[0] || mcaf[1]);
555 }
556
557 static int
558 ate_activate(device_t dev)
559 {
560         struct ate_softc *sc;
561         int i;
562
563         sc = device_get_softc(dev);
564
565         /* Allocate DMA tags and maps for TX mbufs */
566         if (bus_dma_tag_create(bus_get_dma_tag(dev), 1, 0,
567             BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES,
568             1, MCLBYTES, 0, busdma_lock_mutex, &sc->sc_mtx, &sc->mtag))
569                 goto errout;
570         for (i = 0; i < ATE_MAX_TX_BUFFERS; i++) {
571                 if ( bus_dmamap_create(sc->mtag, 0, &sc->tx_map[i]))
572                         goto errout;
573         }
574
575
576         /* DMA tag and map for the RX descriptors. */
577         if (bus_dma_tag_create(bus_get_dma_tag(dev), sizeof(eth_rx_desc_t),
578             0, BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
579             ATE_NUM_RX_DESCR * sizeof(eth_rx_desc_t), 1,
580             ATE_NUM_RX_DESCR * sizeof(eth_rx_desc_t), 0, busdma_lock_mutex,
581             &sc->sc_mtx, &sc->rx_desc_tag))
582                 goto errout;
583         if (bus_dmamem_alloc(sc->rx_desc_tag, (void **)&sc->rx_descs,
584             BUS_DMA_NOWAIT | BUS_DMA_COHERENT, &sc->rx_desc_map) != 0)
585                 goto errout;
586         if (bus_dmamap_load(sc->rx_desc_tag, sc->rx_desc_map,
587             sc->rx_descs, ATE_NUM_RX_DESCR * sizeof(eth_rx_desc_t),
588             ate_getaddr, &sc->rx_desc_phys, 0) != 0)
589                 goto errout;
590
591         /* Allocate DMA tags and maps for RX. buffers */
592         if (bus_dma_tag_create(bus_get_dma_tag(dev), 1, 0,
593             BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
594             sc->rx_buf_size, 1, sc->rx_buf_size, 0,
595             busdma_lock_mutex, &sc->sc_mtx, &sc->rx_tag))
596                 goto errout;
597
598         /*
599          * Allocate our RX buffers.
600          * This chip has a RX structure that's filled in.
601          * XXX On MACB (SAM9 part) we should receive directly into mbuf
602          * to avoid the copy.  XXX
603          */
604         sc->rxhead = 0;
605         for (sc->rxhead = 0; sc->rxhead < ATE_RX_MEMORY/sc->rx_buf_size;
606             sc->rxhead++) {
607                 if (bus_dmamem_alloc(sc->rx_tag,
608                     (void **)&sc->rx_buf[sc->rxhead], BUS_DMA_NOWAIT,
609                     &sc->rx_map[sc->rxhead]) != 0)
610                         goto errout;
611
612                 if (bus_dmamap_load(sc->rx_tag, sc->rx_map[sc->rxhead],
613                     sc->rx_buf[sc->rxhead], sc->rx_buf_size,
614                     ate_load_rx_buf, sc, 0) != 0) {
615                         printf("bus_dmamem_load\n");
616                         goto errout;
617                 }
618                 bus_dmamap_sync(sc->rx_tag, sc->rx_map[sc->rxhead], BUS_DMASYNC_PREREAD);
619         }
620
621         /*
622          * For the last buffer, set the wrap bit so the controller
623          * restarts from the first descriptor.
624          */
625         sc->rx_descs[--sc->rxhead].addr |= ETH_WRAP_BIT;
626         sc->rxhead = 0;
627
628         /* Flush the memory for the EMAC rx descriptor. */
629         bus_dmamap_sync(sc->rx_desc_tag, sc->rx_desc_map, BUS_DMASYNC_PREWRITE);
630
631         /* Write the descriptor queue address. */
632         WR4(sc, ETH_RBQP, sc->rx_desc_phys);
633
634         /*
635          * DMA tag and map for the TX descriptors.
636          */
637         if (bus_dma_tag_create(bus_get_dma_tag(dev), sizeof(eth_tx_desc_t),
638             0, BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
639             ATE_MAX_TX_BUFFERS * sizeof(eth_tx_desc_t), 1,
640             ATE_MAX_TX_BUFFERS * sizeof(eth_tx_desc_t), 0, busdma_lock_mutex,
641             &sc->sc_mtx, &sc->tx_desc_tag) != 0)
642                 goto errout;
643
644         if (bus_dmamem_alloc(sc->tx_desc_tag, (void **)&sc->tx_descs,
645             BUS_DMA_NOWAIT | BUS_DMA_COHERENT, &sc->tx_desc_map) != 0)
646                 goto errout;
647
648         if (bus_dmamap_load(sc->tx_desc_tag, sc->tx_desc_map,
649             sc->tx_descs, ATE_MAX_TX_BUFFERS * sizeof(eth_tx_desc_t),
650             ate_getaddr, &sc->tx_desc_phys, 0) != 0)
651                 goto errout;
652
653         /* Initialize descriptors; mark all empty */
654         for (i = 0; i < ATE_MAX_TX_BUFFERS; i++) {
655                 sc->tx_descs[i].addr =0;
656                 sc->tx_descs[i].status = ETHB_TX_USED;
657                 sc->sent_mbuf[i] = NULL;
658         }
659
660         /* Mark last entry to cause wrap when indexing through */
661         sc->tx_descs[ATE_MAX_TX_BUFFERS - 1].status =
662             ETHB_TX_WRAP | ETHB_TX_USED;
663
664         /* Flush the memory for the EMAC tx descriptor. */
665         bus_dmamap_sync(sc->tx_desc_tag, sc->tx_desc_map, BUS_DMASYNC_PREWRITE);
666
667         sc->txhead = sc->txtail = 0;
668         if (sc->is_emacb) {
669                 /* Write the descriptor queue address. */
670                 WR4(sc, ETHB_TBQP, sc->tx_desc_phys);
671
672                 /* EMACB: Enable transceiver input clock */
673                 WR4(sc, ETHB_UIO, RD4(sc, ETHB_UIO) | ETHB_UIO_CLKE);
674         }
675
676         return (0);
677
678 errout:
679         return (ENOMEM);
680 }
681
682 static void
683 ate_deactivate(struct ate_softc *sc)
684 {
685         int i;
686
687         KASSERT(sc != NULL, ("[ate, %d]: sc is NULL!", __LINE__));
688         if (sc->mtag != NULL) {
689                 for (i = 0; i < ATE_MAX_TX_BUFFERS; i++) {
690                         if (sc->sent_mbuf[i] != NULL) {
691                                 bus_dmamap_sync(sc->mtag, sc->tx_map[i],
692                                     BUS_DMASYNC_POSTWRITE);
693                                 bus_dmamap_unload(sc->mtag, sc->tx_map[i]);
694                                 m_freem(sc->sent_mbuf[i]);
695                         }
696                         bus_dmamap_destroy(sc->mtag, sc->tx_map[i]);
697                         sc->sent_mbuf[i] = NULL;
698                         sc->tx_map[i] = NULL;
699                 }
700                 bus_dma_tag_destroy(sc->mtag);
701         }
702         if (sc->rx_desc_tag != NULL) {
703                 if (sc->rx_descs != NULL) {
704                         if (sc->rx_desc_phys != 0) {
705                                 bus_dmamap_sync(sc->rx_desc_tag,
706                                     sc->rx_desc_map, BUS_DMASYNC_POSTREAD);
707                                 bus_dmamap_unload(sc->rx_desc_tag,
708                                     sc->rx_desc_map);
709                                 sc->rx_desc_phys = 0;
710                         }
711                 }
712         }
713         if (sc->rx_tag != NULL) {
714                 for (i = 0; sc->rx_buf[i] != NULL; i++) {
715                         if (sc->rx_descs[i].addr != 0) {
716                                 bus_dmamap_sync(sc->rx_tag,
717                                     sc->rx_map[i],
718                                     BUS_DMASYNC_POSTREAD);
719                                 bus_dmamap_unload(sc->rx_tag,
720                                     sc->rx_map[i]);
721                                 sc->rx_descs[i].addr = 0;
722                         }
723                         bus_dmamem_free(sc->rx_tag, sc->rx_buf[i],
724                             sc->rx_map[i]);
725                         sc->rx_buf[i] = NULL;
726                 }
727                 bus_dma_tag_destroy(sc->rx_tag);
728         }
729         if (sc->rx_desc_tag != NULL) {
730                 if (sc->rx_descs != NULL)
731                         bus_dmamem_free(sc->rx_desc_tag, sc->rx_descs,
732                             sc->rx_desc_map);
733                 bus_dma_tag_destroy(sc->rx_desc_tag);
734                 sc->rx_descs = NULL;
735                 sc->rx_desc_tag = NULL;
736         }
737
738         if (sc->is_emacb)
739                 WR4(sc, ETHB_UIO, RD4(sc, ETHB_UIO) & ~ETHB_UIO_CLKE);
740 }
741
742 /*
743  * Change media according to request.
744  */
745 static int
746 ate_ifmedia_upd(struct ifnet *ifp)
747 {
748         struct ate_softc *sc = ifp->if_softc;
749         struct mii_data *mii;
750
751         mii = device_get_softc(sc->miibus);
752         ATE_LOCK(sc);
753         mii_mediachg(mii);
754         ATE_UNLOCK(sc);
755         return (0);
756 }
757
758 /*
759  * Notify the world which media we're using.
760  */
761 static void
762 ate_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr)
763 {
764         struct ate_softc *sc = ifp->if_softc;
765         struct mii_data *mii;
766
767         mii = device_get_softc(sc->miibus);
768         ATE_LOCK(sc);
769         mii_pollstat(mii);
770         ifmr->ifm_active = mii->mii_media_active;
771         ifmr->ifm_status = mii->mii_media_status;
772         ATE_UNLOCK(sc);
773 }
774
775 static void
776 ate_stat_update(struct ate_softc *sc, int active)
777 {
778         uint32_t reg;
779
780         /*
781          * The speed and full/half-duplex state needs to be reflected
782          * in the ETH_CFG register.
783          */
784         reg = RD4(sc, ETH_CFG);
785         reg &= ~(ETH_CFG_SPD | ETH_CFG_FD);
786         if (IFM_SUBTYPE(active) != IFM_10_T)
787                 reg |= ETH_CFG_SPD;
788         if (active & IFM_FDX)
789                 reg |= ETH_CFG_FD;
790         WR4(sc, ETH_CFG, reg);
791 }
792
793 static void
794 ate_tick(void *xsc)
795 {
796         struct ate_softc *sc = xsc;
797         struct ifnet *ifp = sc->ifp;
798         struct mii_data *mii;
799         int active;
800         uint32_t c;
801
802         /*
803          * The KB920x boot loader tests ETH_SR & ETH_SR_LINK and will ask
804          * the MII if there's a link if this bit is clear.  Not sure if we
805          * should do the same thing here or not.
806          */
807         ATE_ASSERT_LOCKED(sc);
808         if (sc->miibus != NULL) {
809                 mii = device_get_softc(sc->miibus);
810                 active = mii->mii_media_active;
811                 mii_tick(mii);
812                 if (mii->mii_media_status & IFM_ACTIVE &&
813                     active != mii->mii_media_active)
814                         ate_stat_update(sc, mii->mii_media_active);
815         }
816
817         /*
818          * Update the stats as best we can.  When we're done, clear
819          * the status counters and start over.  We're supposed to read these
820          * registers often enough that they won't overflow.  Hopefully
821          * once a second is often enough.  Some don't map well to
822          * the dot3Stats mib, so for those we just count them as general
823          * errors.  Stats for iframes, ibutes, oframes and obytes are
824          * collected elsewhere.  These registers zero on a read to prevent
825          * races.  For all the collision stats, also update the collision
826          * stats for the interface.
827          */
828         sc->mibdata.dot3StatsAlignmentErrors += RD4(sc, ETH_ALE);
829         sc->mibdata.dot3StatsFCSErrors += RD4(sc, ETH_SEQE);
830         c = RD4(sc, ETH_SCOL);
831         if_inc_counter(ifp, IFCOUNTER_COLLISIONS, c);
832         sc->mibdata.dot3StatsSingleCollisionFrames += c;
833         c = RD4(sc, ETH_MCOL);
834         sc->mibdata.dot3StatsMultipleCollisionFrames += c;
835         if_inc_counter(ifp, IFCOUNTER_COLLISIONS, c);
836         sc->mibdata.dot3StatsSQETestErrors += RD4(sc, ETH_SQEE);
837         sc->mibdata.dot3StatsDeferredTransmissions += RD4(sc, ETH_DTE);
838         c = RD4(sc, ETH_LCOL);
839         sc->mibdata.dot3StatsLateCollisions += c;
840         if_inc_counter(ifp, IFCOUNTER_COLLISIONS, c);
841         c = RD4(sc, ETH_ECOL);
842         sc->mibdata.dot3StatsExcessiveCollisions += c;
843         if_inc_counter(ifp, IFCOUNTER_COLLISIONS, c);
844         sc->mibdata.dot3StatsCarrierSenseErrors += RD4(sc, ETH_CSE);
845         sc->mibdata.dot3StatsFrameTooLongs += RD4(sc, ETH_ELR);
846         sc->mibdata.dot3StatsInternalMacReceiveErrors += RD4(sc, ETH_DRFC);
847
848         /*
849          * Not sure where to lump these, so count them against the errors
850          * for the interface.
851          */
852         if_inc_counter(sc->ifp, IFCOUNTER_OERRORS, RD4(sc, ETH_TUE));
853         if_inc_counter(sc->ifp, IFCOUNTER_IERRORS,
854             RD4(sc, ETH_CDE) + RD4(sc, ETH_RJB) + RD4(sc, ETH_USF));
855
856         /* Schedule another timeout one second from now. */
857         callout_reset(&sc->tick_ch, hz, ate_tick, sc);
858 }
859
860 static void
861 ate_set_mac(struct ate_softc *sc, u_char *eaddr)
862 {
863
864         WR4(sc, ETH_SA1L, (eaddr[3] << 24) | (eaddr[2] << 16) |
865             (eaddr[1] << 8) | eaddr[0]);
866         WR4(sc, ETH_SA1H, (eaddr[5] << 8) | (eaddr[4]));
867 }
868
869 static int
870 ate_get_mac(struct ate_softc *sc, u_char *eaddr)
871 {
872         bus_size_t sa_low_reg[] = { ETH_SA1L, ETH_SA2L, ETH_SA3L, ETH_SA4L };
873         bus_size_t sa_high_reg[] = { ETH_SA1H, ETH_SA2H, ETH_SA3H, ETH_SA4H };
874         uint32_t low, high;
875         int i;
876
877         /*
878          * The boot loader may setup the MAC with an address(es), grab the
879          * first MAC address from the SA[1-4][HL] registers.
880          */
881         for (i = 0; i < 4; i++) {
882                 low = RD4(sc, sa_low_reg[i]);
883                 high = RD4(sc, sa_high_reg[i]);
884                 if ((low | (high & 0xffff)) != 0) {
885                         eaddr[0] = low & 0xff;
886                         eaddr[1] = (low >> 8) & 0xff;
887                         eaddr[2] = (low >> 16) & 0xff;
888                         eaddr[3] = (low >> 24) & 0xff;
889                         eaddr[4] = high & 0xff;
890                         eaddr[5] = (high >> 8) & 0xff;
891                         return (0);
892                 }
893         }
894         return (ENXIO);
895 }
896
897 static void
898 ate_intr(void *xsc)
899 {
900         struct ate_softc *sc = xsc;
901         struct ifnet *ifp = sc->ifp;
902         struct mbuf *mb;
903         eth_rx_desc_t   *rxdhead;
904         uint32_t status, reg, idx;
905         int remain, count, done;
906
907         status = RD4(sc, ETH_ISR);
908         if (status == 0)
909                 return;
910
911         if (status & ETH_ISR_RCOM) {
912                 bus_dmamap_sync(sc->rx_desc_tag, sc->rx_desc_map,
913                     BUS_DMASYNC_POSTREAD);
914
915                 rxdhead = &sc->rx_descs[sc->rxhead];
916                 while (rxdhead->addr & ETH_CPU_OWNER) {
917                         if (!sc->is_emacb) {
918                                 /*
919                                  * Simulate SAM9 FIRST/LAST bits for RM9200.
920                                  * RM9200 EMAC has only on Rx buffer per packet.
921                                  * But sometime we are handed a zero length packet.
922                                  */
923                                 if ((rxdhead->status & ETH_LEN_MASK) == 0)
924                                         rxdhead->status = 0; /* Mark error */
925                                 else
926                                         rxdhead->status |= ETH_BUF_FIRST | ETH_BUF_LAST;
927                         }
928
929                         if ((rxdhead->status & ETH_BUF_FIRST) == 0) {
930                                 /* Something went wrong during RX so
931                                    release back to EMAC all buffers of invalid packets.
932                                 */
933                                 rxdhead->status = 0;
934                                 rxdhead->addr &= ~ETH_CPU_OWNER;
935                                 sc->rxhead = NEXT_RX_IDX(sc, sc->rxhead);
936                                 rxdhead = &sc->rx_descs[sc->rxhead];
937                                 continue;
938                         }
939
940                         /* Find end of packet or start of next */
941                         idx = sc->rxhead;
942                         if ((sc->rx_descs[idx].status & ETH_BUF_LAST) == 0) {
943                                 idx = NEXT_RX_IDX(sc, idx);
944
945                                 while ((sc->rx_descs[idx].addr & ETH_CPU_OWNER) &&
946                                         ((sc->rx_descs[idx].status &
947                                             (ETH_BUF_FIRST|ETH_BUF_LAST))== 0))
948                                         idx = NEXT_RX_IDX(sc, idx);
949                         }
950
951                         /* Packet NOT yet completely in memory; we are done */
952                         if ((sc->rx_descs[idx].addr & ETH_CPU_OWNER) == 0 ||
953                             ((sc->rx_descs[idx].status & (ETH_BUF_FIRST|ETH_BUF_LAST))== 0))
954                                         break;
955
956                         /* Packets with no end descriptor are invalid. */
957                         if ((sc->rx_descs[idx].status & ETH_BUF_LAST) == 0) {
958                                         rxdhead->status &= ~ETH_BUF_FIRST;
959                                         continue;
960                         }
961
962                         /* FCS is not coppied into mbuf. */
963                         remain = (sc->rx_descs[idx].status & ETH_LEN_MASK) - 4;
964
965                         /* Get an appropriately sized mbuf. */
966                         mb = m_get2(remain + ETHER_ALIGN, M_NOWAIT, MT_DATA,
967                             M_PKTHDR);
968                         if (mb == NULL) {
969                                 if_inc_counter(sc->ifp, IFCOUNTER_IQDROPS, 1);
970                                 rxdhead->status = 0;
971                                 continue;
972                         }
973                         mb->m_data += ETHER_ALIGN;
974                         mb->m_pkthdr.rcvif = ifp;
975
976                         WR4(sc, ETH_RSR, RD4(sc, ETH_RSR));     /* Reset status */
977
978                         /* Now we process the buffers that make up the packet */
979                         do {
980
981                                 /* Last buffer may just be 1-4 bytes of FCS so remain
982                                  * may be zero for last descriptor.  */
983                                 if (remain > 0) {
984                                                 /* Make sure we get the current bytes */
985                                                 bus_dmamap_sync(sc->rx_tag, sc->rx_map[sc->rxhead],
986                                                     BUS_DMASYNC_POSTREAD);
987
988                                                 count = MIN(remain, sc->rx_buf_size);
989
990                                                 /* XXX Performance robbing copy. Could
991                                                  * receive directly to mbufs if not an
992                                                  * RM9200. And even then we could likely
993                                                  * copy just the protocol headers. XXX  */
994                                                 m_append(mb, count, sc->rx_buf[sc->rxhead]);
995                                                 remain -= count;
996                                 }
997
998                                 done = (rxdhead->status & ETH_BUF_LAST) != 0;
999
1000                                 /* Return the descriptor to the EMAC */
1001                                 rxdhead->status = 0;
1002                                 rxdhead->addr &= ~ETH_CPU_OWNER;
1003                                 bus_dmamap_sync(sc->rx_desc_tag, sc->rx_desc_map,
1004                                     BUS_DMASYNC_PREWRITE);
1005
1006                                 /* Move on to next descriptor with wrap */
1007                                 sc->rxhead = NEXT_RX_IDX(sc, sc->rxhead);
1008                                 rxdhead = &sc->rx_descs[sc->rxhead];
1009
1010                         } while (!done);
1011
1012                         if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
1013                         (*ifp->if_input)(ifp, mb);
1014                 }
1015         }
1016
1017
1018         if (status & ETH_ISR_TCOM) {
1019                 bus_dmamap_sync(sc->tx_desc_tag, sc->tx_desc_map,
1020                     BUS_DMASYNC_POSTREAD);
1021
1022                 ATE_LOCK(sc);
1023                 /* XXX TSR register should be cleared */
1024                 if (!sc->is_emacb) {
1025                         /* Simulate Transmit descriptor table */
1026
1027                         /* First packet done */
1028                         if (sc->txtail < sc->txhead)
1029                                 sc->tx_descs[sc->txtail].status |= ETHB_TX_USED;
1030
1031                         /* Second Packet done */
1032                         if (sc->txtail + 1 < sc->txhead &&
1033                             RD4(sc, ETH_TSR) & ETH_TSR_IDLE)
1034                                 sc->tx_descs[sc->txtail + 1].status |= ETHB_TX_USED;
1035                 }
1036
1037                 while ((sc->tx_descs[sc->txtail].status & ETHB_TX_USED) &&
1038                     sc->sent_mbuf[sc->txtail] != NULL) {
1039                         bus_dmamap_sync(sc->mtag, sc->tx_map[sc->txtail],
1040                             BUS_DMASYNC_POSTWRITE);
1041                         bus_dmamap_unload(sc->mtag, sc->tx_map[sc->txtail]);
1042                         m_freem(sc->sent_mbuf[sc->txtail]);
1043                         sc->tx_descs[sc->txtail].addr = 0;
1044                         sc->sent_mbuf[sc->txtail] = NULL;
1045                         if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
1046                         sc->txtail = NEXT_TX_IDX(sc, sc->txtail);
1047                 }
1048
1049                 /* Flush descriptors to EMAC */
1050                 bus_dmamap_sync(sc->tx_desc_tag, sc->tx_desc_map, BUS_DMASYNC_PREWRITE);
1051
1052                 /*
1053                  * We're no longer busy, so clear the busy flag and call the
1054                  * start routine to xmit more packets.
1055                  */
1056                 sc->ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1057                 atestart_locked(sc->ifp);
1058                 ATE_UNLOCK(sc);
1059         }
1060
1061         if (status & ETH_ISR_RBNA) {
1062                 /* Workaround RM9200 Errata #11 */
1063                 if (bootverbose)
1064                         device_printf(sc->dev, "RBNA workaround\n");
1065                 reg = RD4(sc, ETH_CTL);
1066                 WR4(sc, ETH_CTL, reg & ~ETH_CTL_RE);
1067                 BARRIER(sc, ETH_CTL, 4, BUS_SPACE_BARRIER_WRITE);
1068                 WR4(sc, ETH_CTL, reg | ETH_CTL_RE);
1069         }
1070
1071         /* XXX need to work around SAM9260 errata 43.2.4.1:
1072          * disable the mac, reset tx buffer, enable mac on TUND */
1073 }
1074
1075 /*
1076  * Reset and initialize the chip.
1077  */
1078 static void
1079 ateinit_locked(void *xsc)
1080 {
1081         struct ate_softc *sc = xsc;
1082         struct ifnet *ifp = sc->ifp;
1083         struct mii_data *mii;
1084         uint8_t eaddr[ETHER_ADDR_LEN];
1085         uint32_t reg;
1086
1087         ATE_ASSERT_LOCKED(sc);
1088
1089         /*
1090          * XXX TODO(3)
1091          * we need to turn on the EMAC clock in the pmc.  With the
1092          * default boot loader, this is already turned on.  However, we
1093          * need to think about how best to turn it on/off as the interface
1094          * is brought up/down, as well as dealing with the mii bus...
1095          *
1096          * We also need to multiplex the pins correctly (in board_xxx.c).
1097          */
1098
1099         /*
1100          * There are two different ways that the mii bus is connected
1101          * to this chip mii or rmii.
1102          */
1103         if (!sc->is_emacb) {
1104                 /* RM9200 */
1105                 reg = RD4(sc, ETH_CFG);
1106                 if (sc->use_rmii)
1107                         reg |= ETH_CFG_RMII;
1108                 else
1109                         reg &= ~ETH_CFG_RMII;
1110                 WR4(sc, ETH_CFG, reg);
1111         } else  {
1112                 /* SAM9 */
1113                 reg = ETHB_UIO_CLKE;
1114                 reg |= (sc->use_rmii) ? ETHB_UIO_RMII : 0;
1115                 WR4(sc, ETHB_UIO, reg);
1116         }
1117
1118         ate_rxfilter(sc);
1119
1120         /*
1121          * Set the chip MAC address.
1122          */
1123         bcopy(IF_LLADDR(ifp), eaddr, ETHER_ADDR_LEN);
1124         ate_set_mac(sc, eaddr);
1125
1126         /* Make sure we know state of TX queue */
1127         sc->txhead = sc->txtail = 0;
1128         if (sc->is_emacb) {
1129                 /* Write the descriptor queue address. */
1130                 WR4(sc, ETHB_TBQP, sc->tx_desc_phys);
1131         }
1132
1133         /*
1134          * Turn on MACs and interrupt processing.
1135          */
1136         WR4(sc, ETH_CTL, RD4(sc, ETH_CTL) | ETH_CTL_TE | ETH_CTL_RE);
1137         WR4(sc, ETH_IER, ETH_ISR_RCOM | ETH_ISR_TCOM | ETH_ISR_RBNA);
1138
1139         /* Enable big packets. */
1140         WR4(sc, ETH_CFG, RD4(sc, ETH_CFG) | ETH_CFG_BIG);
1141
1142         /*
1143          * Set 'running' flag, and clear output active flag
1144          * and attempt to start the output.
1145          */
1146         ifp->if_drv_flags |= IFF_DRV_RUNNING;
1147         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1148
1149         mii = device_get_softc(sc->miibus);
1150         mii_pollstat(mii);
1151         ate_stat_update(sc, mii->mii_media_active);
1152         atestart_locked(ifp);
1153
1154         callout_reset(&sc->tick_ch, hz, ate_tick, sc);
1155 }
1156
1157 /*
1158  * Dequeue packets and transmit.
1159  */
1160 static void
1161 atestart_locked(struct ifnet *ifp)
1162 {
1163         struct ate_softc *sc = ifp->if_softc;
1164         struct mbuf *m, *mdefrag;
1165         bus_dma_segment_t segs[1];
1166         int nseg, e;
1167
1168         ATE_ASSERT_LOCKED(sc);
1169         if (ifp->if_drv_flags & IFF_DRV_OACTIVE)
1170                 return;
1171
1172         while (sc->tx_descs[sc->txhead].status & ETHB_TX_USED) {
1173                 /*
1174                  * Check to see if there's room to put another packet into the
1175                  * xmit queue. The old EMAC version has a ping-pong buffer for
1176                  * xmit packets.  We use OACTIVE to indicate "we can stuff more
1177                  * into our buffers (clear) or not (set)."
1178                  */
1179                 /* RM9200 has only two hardware entries */
1180                 if (!sc->is_emacb && (RD4(sc, ETH_TSR) & ETH_TSR_BNQ) == 0) {
1181                         ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1182                         return;
1183                 }
1184
1185                 IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
1186                 if (m == NULL)
1187                         break;
1188
1189                 e = bus_dmamap_load_mbuf_sg(sc->mtag, sc->tx_map[sc->txhead], m,
1190                     segs, &nseg, 0);
1191                 if (e == EFBIG) {
1192                         mdefrag = m_defrag(m, M_NOWAIT);
1193                         if (mdefrag == NULL) {
1194                                 IFQ_DRV_PREPEND(&ifp->if_snd, m);
1195                                 return;
1196                         }
1197                         m = mdefrag;
1198                         e = bus_dmamap_load_mbuf_sg(sc->mtag,
1199                             sc->tx_map[sc->txhead], m, segs, &nseg, 0);
1200                 }
1201                 if (e != 0) {
1202                         m_freem(m);
1203                         continue;
1204                 }
1205
1206                 /*
1207                  * There's a small race between the loop in ate_intr finishing
1208                  * and the check above to see if the packet was finished, as well
1209                  * as when atestart gets called via other paths. Lose the race
1210                  * gracefully and free the mbuf...
1211                  */
1212                 if (sc->sent_mbuf[sc->txhead] != NULL) {
1213                         bus_dmamap_sync(sc->mtag, sc->tx_map[sc->txtail],
1214                             BUS_DMASYNC_POSTWRITE);
1215                         bus_dmamap_unload(sc->mtag, sc->tx_map[sc->txtail]);
1216                         m_free(sc->sent_mbuf[sc->txhead]);
1217                         if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
1218                 }
1219                 
1220                 sc->sent_mbuf[sc->txhead] = m;
1221
1222                 bus_dmamap_sync(sc->mtag, sc->tx_map[sc->txhead],
1223                     BUS_DMASYNC_PREWRITE);
1224
1225                 /* Tell the hardware to xmit the packet. */
1226                 if (!sc->is_emacb) {
1227                         WR4(sc, ETH_TAR, segs[0].ds_addr);
1228                         BARRIER(sc, ETH_TAR, 4, BUS_SPACE_BARRIER_WRITE);
1229                         WR4(sc, ETH_TCR, segs[0].ds_len);
1230                 } else {
1231                         bus_dmamap_sync(sc->tx_desc_tag, sc->tx_desc_map,
1232                             BUS_DMASYNC_POSTWRITE);
1233                         sc->tx_descs[sc->txhead].addr = segs[0].ds_addr;
1234                         sc->tx_descs[sc->txhead].status = segs[0].ds_len |
1235                             (sc->tx_descs[sc->txhead].status & ETHB_TX_WRAP) |
1236                             ETHB_TX_BUF_LAST;
1237                         bus_dmamap_sync(sc->tx_desc_tag, sc->tx_desc_map,
1238                             BUS_DMASYNC_PREWRITE);
1239                         WR4(sc, ETH_CTL, RD4(sc, ETH_CTL) | ETHB_CTL_TGO);
1240                 }
1241                 sc->txhead = NEXT_TX_IDX(sc, sc->txhead);
1242
1243                 /* Tap off here if there is a bpf listener. */
1244                 BPF_MTAP(ifp, m);
1245         }
1246
1247         if ((sc->tx_descs[sc->txhead].status & ETHB_TX_USED) == 0)
1248             ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1249 }
1250
1251 static void
1252 ateinit(void *xsc)
1253 {
1254         struct ate_softc *sc = xsc;
1255
1256         ATE_LOCK(sc);
1257         ateinit_locked(sc);
1258         ATE_UNLOCK(sc);
1259 }
1260
1261 static void
1262 atestart(struct ifnet *ifp)
1263 {
1264         struct ate_softc *sc = ifp->if_softc;
1265
1266         ATE_LOCK(sc);
1267         atestart_locked(ifp);
1268         ATE_UNLOCK(sc);
1269 }
1270
1271 /*
1272  * Turn off interrupts, and stop the NIC.  Can be called with sc->ifp NULL,
1273  * so be careful.
1274  */
1275 static void
1276 atestop(struct ate_softc *sc)
1277 {
1278         struct ifnet *ifp;
1279         int i;
1280
1281         ATE_ASSERT_LOCKED(sc);
1282         ifp = sc->ifp;
1283         if (ifp) {
1284                 //ifp->if_timer = 0;
1285                 ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
1286         }
1287
1288         callout_stop(&sc->tick_ch);
1289
1290         /*
1291          * Enable some parts of the MAC that are needed always (like the
1292          * MII bus.  This turns off the RE and TE bits, which will remain
1293          * off until ateinit() is called to turn them on.  With RE and TE
1294          * turned off, there's no DMA to worry about after this write.
1295          */
1296         WR4(sc, ETH_CTL, ETH_CTL_MPE);
1297
1298         /*
1299          * Turn off all the configured options and revert to defaults.
1300          */
1301
1302         /* Make sure thate the MDIO clk is less than
1303          * 2.5 Mhz. Can no longer default to /32 since
1304          * SAM9 family may have MCK > 80 Mhz */
1305         if (at91_master_clock <= 2000000)
1306                 WR4(sc, ETH_CFG, ETH_CFG_CLK_8);
1307         else if (at91_master_clock <= 4000000)
1308                 WR4(sc, ETH_CFG, ETH_CFG_CLK_16);
1309         else if (at91_master_clock <= 800000)
1310                 WR4(sc, ETH_CFG, ETH_CFG_CLK_32);
1311         else
1312                 WR4(sc, ETH_CFG, ETH_CFG_CLK_64);
1313
1314         /*
1315          * Turn off all the interrupts, and ack any pending ones by reading
1316          * the ISR.
1317          */
1318         WR4(sc, ETH_IDR, 0xffffffff);
1319         RD4(sc, ETH_ISR);
1320
1321         /*
1322          * Clear out the Transmit and Receiver Status registers of any
1323          * errors they may be reporting
1324          */
1325         WR4(sc, ETH_TSR, 0xffffffff);
1326         WR4(sc, ETH_RSR, 0xffffffff);
1327
1328         /* Release TX resources. */
1329         for (i = 0; i < ATE_MAX_TX_BUFFERS; i++) {
1330                 if (sc->sent_mbuf[i] != NULL) {
1331                         bus_dmamap_sync(sc->mtag, sc->tx_map[i],
1332                             BUS_DMASYNC_POSTWRITE);
1333                         bus_dmamap_unload(sc->mtag, sc->tx_map[i]);
1334                         m_freem(sc->sent_mbuf[i]);
1335                         sc->sent_mbuf[i] = NULL;
1336                 }
1337         }
1338
1339         /* Turn off transeiver input clock */
1340         if (sc->is_emacb)
1341                 WR4(sc, ETHB_UIO, RD4(sc, ETHB_UIO) & ~ETHB_UIO_CLKE);
1342
1343         /*
1344          * XXX we should power down the EMAC if it isn't in use, after
1345          * putting it into loopback mode.  This saves about 400uA according
1346          * to the datasheet.
1347          */
1348 }
1349
1350 static void
1351 ate_rxfilter(struct ate_softc *sc)
1352 {
1353         struct ifnet *ifp;
1354         uint32_t reg;
1355         int enabled;
1356
1357         KASSERT(sc != NULL, ("[ate, %d]: sc is NULL!", __LINE__));
1358         ATE_ASSERT_LOCKED(sc);
1359         ifp = sc->ifp;
1360
1361         /* Wipe out old filter settings. */
1362         reg = RD4(sc, ETH_CFG);
1363         reg &= ~(ETH_CFG_CAF | ETH_CFG_MTI | ETH_CFG_UNI);
1364         reg |= ETH_CFG_NBC;
1365         sc->flags &= ~ATE_FLAG_MULTICAST;
1366
1367         /* Set new parameters. */
1368         if ((ifp->if_flags & IFF_BROADCAST) != 0)
1369                 reg &= ~ETH_CFG_NBC;
1370         if ((ifp->if_flags & IFF_PROMISC) != 0) {
1371                 reg |= ETH_CFG_CAF;
1372         } else {
1373                 enabled = ate_setmcast(sc);
1374                 if (enabled != 0) {
1375                         reg |= ETH_CFG_MTI;
1376                         sc->flags |= ATE_FLAG_MULTICAST;
1377                 }
1378         }
1379         WR4(sc, ETH_CFG, reg);
1380 }
1381
1382 static int
1383 ateioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1384 {
1385         struct ate_softc *sc = ifp->if_softc;
1386         struct mii_data *mii;
1387         struct ifreq *ifr = (struct ifreq *)data;
1388         int drv_flags, flags;
1389         int mask, error, enabled;
1390
1391         error = 0;
1392         flags = ifp->if_flags;
1393         drv_flags = ifp->if_drv_flags;
1394         switch (cmd) {
1395         case SIOCSIFFLAGS:
1396                 ATE_LOCK(sc);
1397                 if ((flags & IFF_UP) != 0) {
1398                         if ((drv_flags & IFF_DRV_RUNNING) != 0) {
1399                                 if (((flags ^ sc->if_flags)
1400                                     & (IFF_PROMISC | IFF_ALLMULTI)) != 0)
1401                                         ate_rxfilter(sc);
1402                         } else {
1403                                 if ((sc->flags & ATE_FLAG_DETACHING) == 0)
1404                                         ateinit_locked(sc);
1405                         }
1406                 } else if ((drv_flags & IFF_DRV_RUNNING) != 0) {
1407                         ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
1408                         atestop(sc);
1409                 }
1410                 sc->if_flags = flags;
1411                 ATE_UNLOCK(sc);
1412                 break;
1413
1414         case SIOCADDMULTI:
1415         case SIOCDELMULTI:
1416                 if ((drv_flags & IFF_DRV_RUNNING) != 0) {
1417                         ATE_LOCK(sc);
1418                         enabled = ate_setmcast(sc);
1419                         if (enabled != (sc->flags & ATE_FLAG_MULTICAST))
1420                                 ate_rxfilter(sc);
1421                         ATE_UNLOCK(sc);
1422                 }
1423                 break;
1424
1425         case SIOCSIFMEDIA:
1426         case SIOCGIFMEDIA:
1427                 mii = device_get_softc(sc->miibus);
1428                 error = ifmedia_ioctl(ifp, ifr, &mii->mii_media, cmd);
1429                 break;
1430         case SIOCSIFCAP:
1431                 mask = ifp->if_capenable ^ ifr->ifr_reqcap;
1432                 if (mask & IFCAP_VLAN_MTU) {
1433                         ATE_LOCK(sc);
1434                         if (ifr->ifr_reqcap & IFCAP_VLAN_MTU) {
1435                                 WR4(sc, ETH_CFG, RD4(sc, ETH_CFG) | ETH_CFG_BIG);
1436                                 ifp->if_capenable |= IFCAP_VLAN_MTU;
1437                         } else {
1438                                 WR4(sc, ETH_CFG, RD4(sc, ETH_CFG) & ~ETH_CFG_BIG);
1439                                 ifp->if_capenable &= ~IFCAP_VLAN_MTU;
1440                         }
1441                         ATE_UNLOCK(sc);
1442                 }
1443         default:
1444                 error = ether_ioctl(ifp, cmd, data);
1445                 break;
1446         }
1447         return (error);
1448 }
1449
1450 static void
1451 ate_child_detached(device_t dev, device_t child)
1452 {
1453         struct ate_softc *sc;
1454
1455         sc = device_get_softc(dev);
1456         if (child == sc->miibus)
1457                 sc->miibus = NULL;
1458 }
1459
1460 /*
1461  * MII bus support routines.
1462  */
1463 static int
1464 ate_miibus_readreg(device_t dev, int phy, int reg)
1465 {
1466         struct ate_softc *sc;
1467         int val;
1468
1469         /*
1470          * XXX if we implement aggressive power savings, then we need
1471          * XXX to make sure that the clock to the emac is on here
1472          */
1473
1474         sc = device_get_softc(dev);
1475         DELAY(1);       /* Hangs w/o this delay really 30.5us atm */
1476         WR4(sc, ETH_MAN, ETH_MAN_REG_RD(phy, reg));
1477         while ((RD4(sc, ETH_SR) & ETH_SR_IDLE) == 0)
1478                 continue;
1479         val = RD4(sc, ETH_MAN) & ETH_MAN_VALUE_MASK;
1480
1481         return (val);
1482 }
1483
1484 static int
1485 ate_miibus_writereg(device_t dev, int phy, int reg, int data)
1486 {
1487         struct ate_softc *sc;
1488
1489         /*
1490          * XXX if we implement aggressive power savings, then we need
1491          * XXX to make sure that the clock to the emac is on here
1492          */
1493
1494         sc = device_get_softc(dev);
1495         WR4(sc, ETH_MAN, ETH_MAN_REG_WR(phy, reg, data));
1496         while ((RD4(sc, ETH_SR) & ETH_SR_IDLE) == 0)
1497                 continue;
1498         return (0);
1499 }
1500
1501 static device_method_t ate_methods[] = {
1502         /* Device interface */
1503         DEVMETHOD(device_probe,         ate_probe),
1504         DEVMETHOD(device_attach,        ate_attach),
1505         DEVMETHOD(device_detach,        ate_detach),
1506
1507         /* Bus interface */
1508         DEVMETHOD(bus_child_detached,   ate_child_detached),
1509
1510         /* MII interface */
1511         DEVMETHOD(miibus_readreg,       ate_miibus_readreg),
1512         DEVMETHOD(miibus_writereg,      ate_miibus_writereg),
1513
1514         DEVMETHOD_END
1515 };
1516
1517 static driver_t ate_driver = {
1518         "ate",
1519         ate_methods,
1520         sizeof(struct ate_softc),
1521 };
1522
1523 #ifdef FDT
1524 DRIVER_MODULE(ate, simplebus, ate_driver, ate_devclass, NULL, NULL);
1525 #else
1526 DRIVER_MODULE(ate, atmelarm, ate_driver, ate_devclass, NULL, NULL);
1527 #endif
1528 DRIVER_MODULE(miibus, ate, miibus_driver, miibus_devclass, NULL, NULL);
1529 MODULE_DEPEND(ate, miibus, 1, 1, 1);
1530 MODULE_DEPEND(ate, ether, 1, 1, 1);