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