if_ate.c revision 182477
1/*-
2 * Copyright (c) 2006 M. Warner Losh.  All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 *    notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 *    notice, this list of conditions and the following disclaimer in the
11 *    documentation and/or other materials provided with the distribution.
12 *
13 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
14 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
15 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
16 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
17 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
18 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
19 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
20 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
21 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
22 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
23 */
24
25/* TODO: (in no order)
26 *
27 * 8) Need to sync busdma goo in atestop
28 * 9) atestop should maybe free the mbufs?
29 *
30 * 1) detach
31 * 2) Free dma setup
32 * 3) Turn on the clock in pmc?  Turn off?
33 */
34
35#include <sys/cdefs.h>
36__FBSDID("$FreeBSD: head/sys/arm/at91/if_ate.c 182477 2008-08-30 15:16:40Z stas $");
37
38#include <sys/param.h>
39#include <sys/systm.h>
40#include <sys/bus.h>
41#include <sys/kernel.h>
42#include <sys/mbuf.h>
43#include <sys/malloc.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#include <machine/bus.h>
50
51#include <net/ethernet.h>
52#include <net/if.h>
53#include <net/if_arp.h>
54#include <net/if_dl.h>
55#include <net/if_media.h>
56#include <net/if_mib.h>
57#include <net/if_types.h>
58
59#ifdef INET
60#include <netinet/in.h>
61#include <netinet/in_systm.h>
62#include <netinet/in_var.h>
63#include <netinet/ip.h>
64#endif
65
66#include <net/bpf.h>
67#include <net/bpfdesc.h>
68
69#include <dev/mii/mii.h>
70#include <dev/mii/miivar.h>
71#include <arm/at91/if_atereg.h>
72
73#include "miibus_if.h"
74
75#define ATE_MAX_TX_BUFFERS 2		/* We have ping-pong tx buffers */
76#define ATE_MAX_RX_BUFFERS 64
77
78struct ate_softc
79{
80	struct ifnet *ifp;		/* ifnet pointer */
81	struct mtx sc_mtx;		/* basically a perimeter lock */
82	device_t dev;			/* Myself */
83	device_t miibus;		/* My child miibus */
84	void *intrhand;			/* Interrupt handle */
85	struct resource *irq_res;	/* IRQ resource */
86	struct resource	*mem_res;	/* Memory resource */
87	struct callout tick_ch;		/* Tick callout */
88	bus_dma_tag_t mtag;		/* bus dma tag for mbufs */
89	bus_dmamap_t tx_map[ATE_MAX_TX_BUFFERS];
90	struct mbuf *sent_mbuf[ATE_MAX_TX_BUFFERS]; /* Sent mbufs */
91	bus_dma_tag_t rxtag;
92	bus_dmamap_t rx_map[ATE_MAX_RX_BUFFERS];
93	void *rx_buf[ATE_MAX_RX_BUFFERS]; /* RX buffer space */
94	int rx_buf_ptr;
95	bus_dma_tag_t rx_desc_tag;
96	bus_dmamap_t rx_desc_map;
97	int txcur;			/* current tx map pointer */
98	bus_addr_t rx_desc_phys;
99	eth_rx_desc_t *rx_descs;
100	int use_rmii;
101	struct	ifmib_iso_8802_3 mibdata; /* stuff for network mgmt */
102};
103
104static inline uint32_t
105RD4(struct ate_softc *sc, bus_size_t off)
106{
107	return bus_read_4(sc->mem_res, off);
108}
109
110static inline void
111WR4(struct ate_softc *sc, bus_size_t off, uint32_t val)
112{
113	bus_write_4(sc->mem_res, off, val);
114}
115
116#define ATE_LOCK(_sc)		mtx_lock(&(_sc)->sc_mtx)
117#define	ATE_UNLOCK(_sc)		mtx_unlock(&(_sc)->sc_mtx)
118#define ATE_LOCK_INIT(_sc) \
119	mtx_init(&_sc->sc_mtx, device_get_nameunit(_sc->dev), \
120	    MTX_NETWORK_LOCK, MTX_DEF)
121#define ATE_LOCK_DESTROY(_sc)	mtx_destroy(&_sc->sc_mtx);
122#define ATE_ASSERT_LOCKED(_sc)	mtx_assert(&_sc->sc_mtx, MA_OWNED);
123#define ATE_ASSERT_UNLOCKED(_sc) mtx_assert(&_sc->sc_mtx, MA_NOTOWNED);
124
125static devclass_t ate_devclass;
126
127/* ifnet entry points */
128
129static void ateinit_locked(void *);
130static void atestart_locked(struct ifnet *);
131
132static void ateinit(void *);
133static void atestart(struct ifnet *);
134static void atestop(struct ate_softc *);
135static int ateioctl(struct ifnet * ifp, u_long, caddr_t);
136
137/* bus entry points */
138
139static int ate_probe(device_t dev);
140static int ate_attach(device_t dev);
141static int ate_detach(device_t dev);
142static void ate_intr(void *);
143
144/* helper routines */
145static int ate_activate(device_t dev);
146static void ate_deactivate(device_t dev);
147static int ate_ifmedia_upd(struct ifnet *ifp);
148static void ate_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr);
149static int ate_get_mac(struct ate_softc *sc, u_char *eaddr);
150static void ate_set_mac(struct ate_softc *sc, u_char *eaddr);
151
152/*
153 * The AT91 family of products has the ethernet called EMAC.  However,
154 * it isn't self identifying.  It is anticipated that the parent bus
155 * code will take care to only add ate devices where they really are.  As
156 * such, we do nothing here to identify the device and just set its name.
157 */
158static int
159ate_probe(device_t dev)
160{
161	device_set_desc(dev, "EMAC");
162	return (0);
163}
164
165static int
166ate_attach(device_t dev)
167{
168	struct ate_softc *sc = device_get_softc(dev);
169	struct ifnet *ifp = NULL;
170	struct sysctl_ctx_list *sctx;
171	struct sysctl_oid *soid;
172	int err;
173	u_char eaddr[ETHER_ADDR_LEN];
174	uint32_t rnd;
175
176	sc->dev = dev;
177	err = ate_activate(dev);
178	if (err)
179		goto out;
180
181	sc->use_rmii = (RD4(sc, ETH_CFG) & ETH_CFG_RMII) == ETH_CFG_RMII;
182
183	/* Sysctls */
184	sctx = device_get_sysctl_ctx(dev);
185	soid = device_get_sysctl_tree(dev);
186	SYSCTL_ADD_UINT(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "rmii",
187	    CTLFLAG_RD, &sc->use_rmii, 0, "rmii in use");
188
189	/* calling atestop before ifp is set is OK */
190	atestop(sc);
191	ATE_LOCK_INIT(sc);
192	callout_init_mtx(&sc->tick_ch, &sc->sc_mtx, 0);
193
194	if ((err = ate_get_mac(sc, eaddr)) != 0) {
195		/*
196		 * No MAC address configured. Generate the fake one.
197		 */
198		if  (bootverbose)
199			device_printf(dev,
200			    "Generating fake ethernet address.\n");
201		rnd = arc4random();
202
203		/*
204		 * Set OUI to Atmel.
205		 */
206		eaddr[0] = 0x00;
207		eaddr[1] = 0x04;
208		eaddr[2] = 0x25;
209		eaddr[3] = (rnd >> 16) & 0xff;
210		eaddr[4] = (rnd >> 8) & 0xff;
211		eaddr[5] = rnd & 0xff;
212	}
213	ate_set_mac(sc, eaddr);
214
215	sc->ifp = ifp = if_alloc(IFT_ETHER);
216	if (mii_phy_probe(dev, &sc->miibus, ate_ifmedia_upd, ate_ifmedia_sts)) {
217		device_printf(dev, "Cannot find my PHY.\n");
218		err = ENXIO;
219		goto out;
220	}
221
222	ifp->if_softc = sc;
223	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
224	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
225	ifp->if_capabilities |= IFCAP_VLAN_MTU;
226	ifp->if_capenable |= IFCAP_VLAN_MTU; /* the hw bits already set */
227	ifp->if_start = atestart;
228	ifp->if_ioctl = ateioctl;
229	ifp->if_init = ateinit;
230	ifp->if_baudrate = 10000000;
231	IFQ_SET_MAXLEN(&ifp->if_snd, IFQ_MAXLEN);
232	ifp->if_snd.ifq_drv_maxlen = IFQ_MAXLEN;
233	IFQ_SET_READY(&ifp->if_snd);
234	ifp->if_timer = 0;
235	ifp->if_linkmib = &sc->mibdata;
236	ifp->if_linkmiblen = sizeof(sc->mibdata);
237	sc->mibdata.dot3Compliance = DOT3COMPLIANCE_COLLS;
238
239	ether_ifattach(ifp, eaddr);
240
241	/*
242	 * Activate the interrupt
243	 */
244	err = bus_setup_intr(dev, sc->irq_res, INTR_TYPE_NET | INTR_MPSAFE,
245	    NULL, ate_intr, sc, &sc->intrhand);
246	if (err) {
247		ether_ifdetach(ifp);
248		ATE_LOCK_DESTROY(sc);
249	}
250out:;
251	if (err)
252		ate_deactivate(dev);
253	if (err && ifp)
254		if_free(ifp);
255	return (err);
256}
257
258static int
259ate_detach(device_t dev)
260{
261	return EBUSY;	/* XXX TODO(1) */
262}
263
264static void
265ate_getaddr(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
266{
267	struct ate_softc *sc;
268
269	if (error != 0)
270		return;
271	sc = (struct ate_softc *)arg;
272	sc->rx_desc_phys = segs[0].ds_addr;
273}
274
275static void
276ate_load_rx_buf(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
277{
278	struct ate_softc *sc;
279	int i;
280
281	if (error != 0)
282		return;
283	sc = (struct ate_softc *)arg;
284	i = sc->rx_buf_ptr;
285
286	/*
287	 * For the last buffer, set the wrap bit so the controller
288	 * restarts from the first descriptor.
289	 */
290	bus_dmamap_sync(sc->rx_desc_tag, sc->rx_desc_map, BUS_DMASYNC_PREWRITE);
291	if (i == ATE_MAX_RX_BUFFERS - 1)
292		sc->rx_descs[i].addr = segs[0].ds_addr | ETH_WRAP_BIT;
293	else
294		sc->rx_descs[i].addr = segs[0].ds_addr;
295	bus_dmamap_sync(sc->rx_desc_tag, sc->rx_desc_map, BUS_DMASYNC_POSTWRITE);
296	sc->rx_descs[i].status = 0;
297	/* Flush the memory in the mbuf */
298	bus_dmamap_sync(sc->rxtag, sc->rx_map[i], BUS_DMASYNC_PREREAD);
299}
300
301/*
302 * Compute the multicast filter for this device using the standard
303 * algorithm.  I wonder why this isn't in ether somewhere as a lot
304 * of different MAC chips use this method (or the reverse the bits)
305 * method.
306 */
307static void
308ate_setmcast(struct ate_softc *sc)
309{
310	uint32_t index;
311	uint32_t mcaf[2];
312	u_char *af = (u_char *) mcaf;
313	struct ifmultiaddr *ifma;
314
315	mcaf[0] = 0;
316	mcaf[1] = 0;
317
318	IF_ADDR_LOCK(sc->ifp);
319	TAILQ_FOREACH(ifma, &sc->ifp->if_multiaddrs, ifma_link) {
320		if (ifma->ifma_addr->sa_family != AF_LINK)
321			continue;
322		index = ether_crc32_be(LLADDR((struct sockaddr_dl *)
323		    ifma->ifma_addr), ETHER_ADDR_LEN) >> 26;
324		af[index >> 3] |= 1 << (index & 7);
325	}
326	IF_ADDR_UNLOCK(sc->ifp);
327
328	/*
329	 * Write the hash to the hash register.  This card can also
330	 * accept unicast packets as well as multicast packets using this
331	 * register for easier bridging operations, but we don't take
332	 * advantage of that.  Locks here are to avoid LOR with the
333	 * IF_ADDR_LOCK, but might not be strictly necessary.
334	 */
335	WR4(sc, ETH_HSL, mcaf[0]);
336	WR4(sc, ETH_HSH, mcaf[1]);
337}
338
339static int
340ate_activate(device_t dev)
341{
342	struct ate_softc *sc;
343	int rid, err, i;
344
345	sc = device_get_softc(dev);
346	rid = 0;
347	sc->mem_res = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid,
348	    RF_ACTIVE);
349	if (sc->mem_res == NULL)
350		goto errout;
351	rid = 0;
352	sc->irq_res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
353	    RF_ACTIVE);
354	if (sc->irq_res == NULL)
355		goto errout;
356
357	/*
358	 * Allocate DMA tags and maps
359	 */
360	err = bus_dma_tag_create(NULL, 1, 0, BUS_SPACE_MAXADDR_32BIT,
361	    BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES, 1, MCLBYTES, 0,
362	    busdma_lock_mutex, &sc->sc_mtx, &sc->mtag);
363	if (err != 0)
364		goto errout;
365	for (i = 0; i < ATE_MAX_TX_BUFFERS; i++) {
366		err = bus_dmamap_create(sc->mtag, 0, &sc->tx_map[i]);
367		if (err != 0)
368			goto errout;
369	}
370	 /*
371	  * Allocate our Rx buffers.  This chip has a rx structure that's filled
372	  * in
373	  */
374
375	/*
376	 * Allocate DMA tags and maps for RX.
377	 */
378	err = bus_dma_tag_create(NULL, 1, 0, BUS_SPACE_MAXADDR_32BIT,
379	    BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES, 1, MCLBYTES, 0,
380	    busdma_lock_mutex, &sc->sc_mtx, &sc->rxtag);
381	if (err != 0)
382		goto errout;
383
384	/* Dma TAG and MAP for the rx descriptors. */
385	err = bus_dma_tag_create(NULL, sizeof(eth_rx_desc_t), 0,
386	    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
387	    ATE_MAX_RX_BUFFERS * sizeof(eth_rx_desc_t), 1,
388	    ATE_MAX_RX_BUFFERS * sizeof(eth_rx_desc_t), 0, busdma_lock_mutex,
389	    &sc->sc_mtx, &sc->rx_desc_tag);
390	if (err != 0)
391		goto errout;
392	if (bus_dmamem_alloc(sc->rx_desc_tag, (void **)&sc->rx_descs,
393	    BUS_DMA_NOWAIT | BUS_DMA_COHERENT, &sc->rx_desc_map) != 0)
394		goto errout;
395	if (bus_dmamap_load(sc->rx_desc_tag, sc->rx_desc_map,
396	    sc->rx_descs, ATE_MAX_RX_BUFFERS * sizeof(eth_rx_desc_t),
397	    ate_getaddr, sc, 0) != 0)
398		goto errout;
399	/* XXX TODO(5) Put this in ateinit_locked? */
400	for (i = 0; i < ATE_MAX_RX_BUFFERS; i++) {
401		sc->rx_buf_ptr = i;
402		if (bus_dmamem_alloc(sc->rxtag, (void **)&sc->rx_buf[i],
403		      BUS_DMA_NOWAIT, &sc->rx_map[i]) != 0)
404			goto errout;
405		if (bus_dmamap_load(sc->rxtag, sc->rx_map[i], sc->rx_buf[i],
406		    MCLBYTES, ate_load_rx_buf, sc, 0) != 0)
407			goto errout;
408	}
409	sc->rx_buf_ptr = 0;
410	/* Flush the memory for the EMAC rx descriptor */
411	bus_dmamap_sync(sc->rx_desc_tag, sc->rx_desc_map, BUS_DMASYNC_PREWRITE);
412	/* Write the descriptor queue address. */
413	WR4(sc, ETH_RBQP, sc->rx_desc_phys);
414	return (0);
415errout:
416	ate_deactivate(dev);
417	return (ENOMEM);
418}
419
420static void
421ate_deactivate(device_t dev)
422{
423	struct ate_softc *sc;
424
425	sc = device_get_softc(dev);
426	/* XXX TODO(2) teardown busdma junk, below from fxp -- customize */
427#if 0
428	if (sc->fxp_mtag) {
429		for (i = 0; i < FXP_NRFABUFS; i++) {
430			rxp = &sc->fxp_desc.rx_list[i];
431			if (rxp->rx_mbuf != NULL) {
432				bus_dmamap_sync(sc->fxp_mtag, rxp->rx_map,
433				    BUS_DMASYNC_POSTREAD);
434				bus_dmamap_unload(sc->fxp_mtag, rxp->rx_map);
435				m_freem(rxp->rx_mbuf);
436			}
437			bus_dmamap_destroy(sc->fxp_mtag, rxp->rx_map);
438		}
439		bus_dmamap_destroy(sc->fxp_mtag, sc->spare_map);
440		for (i = 0; i < FXP_NTXCB; i++) {
441			txp = &sc->fxp_desc.tx_list[i];
442			if (txp->tx_mbuf != NULL) {
443				bus_dmamap_sync(sc->fxp_mtag, txp->tx_map,
444				    BUS_DMASYNC_POSTWRITE);
445				bus_dmamap_unload(sc->fxp_mtag, txp->tx_map);
446				m_freem(txp->tx_mbuf);
447			}
448			bus_dmamap_destroy(sc->fxp_mtag, txp->tx_map);
449		}
450		bus_dma_tag_destroy(sc->fxp_mtag);
451	}
452	if (sc->fxp_stag)
453		bus_dma_tag_destroy(sc->fxp_stag);
454	if (sc->cbl_tag)
455		bus_dma_tag_destroy(sc->cbl_tag);
456	if (sc->mcs_tag)
457		bus_dma_tag_destroy(sc->mcs_tag);
458#endif
459	if (sc->intrhand)
460		bus_teardown_intr(dev, sc->irq_res, sc->intrhand);
461	sc->intrhand = 0;
462	bus_generic_detach(sc->dev);
463	if (sc->miibus)
464		device_delete_child(sc->dev, sc->miibus);
465	if (sc->mem_res)
466		bus_release_resource(dev, SYS_RES_IOPORT,
467		    rman_get_rid(sc->mem_res), sc->mem_res);
468	sc->mem_res = 0;
469	if (sc->irq_res)
470		bus_release_resource(dev, SYS_RES_IRQ,
471		    rman_get_rid(sc->irq_res), sc->irq_res);
472	sc->irq_res = 0;
473	return;
474}
475
476/*
477 * Change media according to request.
478 */
479static int
480ate_ifmedia_upd(struct ifnet *ifp)
481{
482	struct ate_softc *sc = ifp->if_softc;
483	struct mii_data *mii;
484
485	mii = device_get_softc(sc->miibus);
486	ATE_LOCK(sc);
487	mii_mediachg(mii);
488	ATE_UNLOCK(sc);
489	return (0);
490}
491
492/*
493 * Notify the world which media we're using.
494 */
495static void
496ate_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr)
497{
498	struct ate_softc *sc = ifp->if_softc;
499	struct mii_data *mii;
500
501	mii = device_get_softc(sc->miibus);
502	ATE_LOCK(sc);
503	mii_pollstat(mii);
504	ifmr->ifm_active = mii->mii_media_active;
505	ifmr->ifm_status = mii->mii_media_status;
506	ATE_UNLOCK(sc);
507}
508
509static void
510ate_stat_update(struct ate_softc *sc, int active)
511{
512	/*
513	 * The speed and full/half-duplex state needs to be reflected
514	 * in the ETH_CFG register.
515	 */
516	if (IFM_SUBTYPE(active) == IFM_10_T)
517		WR4(sc, ETH_CFG, RD4(sc, ETH_CFG) & ~ETH_CFG_SPD);
518	else
519		WR4(sc, ETH_CFG, RD4(sc, ETH_CFG) | ETH_CFG_SPD);
520	if (active & IFM_FDX)
521		WR4(sc, ETH_CFG, RD4(sc, ETH_CFG) | ETH_CFG_FD);
522	else
523		WR4(sc, ETH_CFG, RD4(sc, ETH_CFG) & ~ETH_CFG_FD);
524}
525
526static void
527ate_tick(void *xsc)
528{
529	struct ate_softc *sc = xsc;
530	struct ifnet *ifp = sc->ifp;
531	struct mii_data *mii;
532	int active;
533	uint32_t c;
534
535	/*
536	 * The KB920x boot loader tests ETH_SR & ETH_SR_LINK and will ask
537	 * the MII if there's a link if this bit is clear.  Not sure if we
538	 * should do the same thing here or not.
539	 */
540	ATE_ASSERT_LOCKED(sc);
541	if (sc->miibus != NULL) {
542		mii = device_get_softc(sc->miibus);
543		active = mii->mii_media_active;
544		mii_tick(mii);
545		if (mii->mii_media_status & IFM_ACTIVE &&
546		     active != mii->mii_media_active)
547			ate_stat_update(sc, mii->mii_media_active);
548	}
549
550	/*
551	 * Update the stats as best we can.  When we're done, clear
552	 * the status counters and start over.  We're supposed to read these
553	 * registers often enough that they won't overflow.  Hopefully
554	 * once a second is often enough.  Some don't map well to
555	 * the dot3Stats mib, so for those we just count them as general
556	 * errors.  Stats for iframes, ibutes, oframes and obytes are
557	 * collected elsewhere.  These registers zero on a read to prevent
558	 * races.  For all the collision stats, also update the collision
559	 * stats for the interface.
560	 */
561	sc->mibdata.dot3StatsAlignmentErrors += RD4(sc, ETH_ALE);
562	sc->mibdata.dot3StatsFCSErrors += RD4(sc, ETH_SEQE);
563	c = RD4(sc, ETH_SCOL);
564	ifp->if_collisions += c;
565	sc->mibdata.dot3StatsSingleCollisionFrames += c;
566	c = RD4(sc, ETH_MCOL);
567	sc->mibdata.dot3StatsMultipleCollisionFrames += c;
568	ifp->if_collisions += c;
569	sc->mibdata.dot3StatsSQETestErrors += RD4(sc, ETH_SQEE);
570	sc->mibdata.dot3StatsDeferredTransmissions += RD4(sc, ETH_DTE);
571	c = RD4(sc, ETH_LCOL);
572	sc->mibdata.dot3StatsLateCollisions += c;
573	ifp->if_collisions += c;
574	c = RD4(sc, ETH_ECOL);
575	sc->mibdata.dot3StatsExcessiveCollisions += c;
576	ifp->if_collisions += c;
577	sc->mibdata.dot3StatsCarrierSenseErrors += RD4(sc, ETH_CSE);
578	sc->mibdata.dot3StatsFrameTooLongs += RD4(sc, ETH_ELR);
579	sc->mibdata.dot3StatsInternalMacReceiveErrors += RD4(sc, ETH_DRFC);
580	/*
581	 * not sure where to lump these, so count them against the errors
582	 * for the interface.
583	 */
584	sc->ifp->if_oerrors += RD4(sc, ETH_TUE);
585	sc->ifp->if_ierrors += RD4(sc, ETH_CDE) + RD4(sc, ETH_RJB) +
586	    RD4(sc, ETH_USF);
587
588	/*
589	 * Schedule another timeout one second from now.
590	 */
591	callout_reset(&sc->tick_ch, hz, ate_tick, sc);
592}
593
594static void
595ate_set_mac(struct ate_softc *sc, u_char *eaddr)
596{
597	WR4(sc, ETH_SA1L, (eaddr[3] << 24) | (eaddr[2] << 16) |
598	    (eaddr[1] << 8) | eaddr[0]);
599	WR4(sc, ETH_SA1H, (eaddr[5] << 8) | (eaddr[4]));
600}
601
602static int
603ate_get_mac(struct ate_softc *sc, u_char *eaddr)
604{
605	bus_size_t sa_low_reg[] = { ETH_SA1L, ETH_SA2L, ETH_SA3L, ETH_SA4L };
606	bus_size_t sa_high_reg[] = { ETH_SA1H, ETH_SA2H, ETH_SA3H, ETH_SA4H };
607	uint32_t low, high;
608	int i;
609
610	/*
611	 * The boot loader setup the MAC with an address, if one is set in
612	 * the loader. Grab one MAC address from the SA[1-4][HL] registers.
613	 */
614	for (i = 0; i < 4; i++) {
615		low = RD4(sc, sa_low_reg[i]);
616		high = RD4(sc, sa_high_reg[i]);
617		if ((low | (high & 0xffff)) != 0) {
618			eaddr[0] = low & 0xff;
619			eaddr[1] = (low >> 8) & 0xff;
620			eaddr[2] = (low >> 16) & 0xff;
621			eaddr[3] = (low >> 24) & 0xff;
622			eaddr[4] = high & 0xff;
623			eaddr[5] = (high >> 8) & 0xff;
624			return (0);
625		}
626	}
627	return (ENXIO);
628}
629
630static void
631ate_intr(void *xsc)
632{
633	struct ate_softc *sc = xsc;
634	struct ifnet *ifp = sc->ifp;
635	int status;
636	int i;
637	void *bp;
638	struct mbuf *mb;
639	uint32_t rx_stat;
640
641	status = RD4(sc, ETH_ISR);
642	if (status == 0)
643		return;
644	if (status & ETH_ISR_RCOM) {
645		bus_dmamap_sync(sc->rx_desc_tag, sc->rx_desc_map,
646		    BUS_DMASYNC_POSTREAD);
647		while (sc->rx_descs[sc->rx_buf_ptr].addr & ETH_CPU_OWNER) {
648			i = sc->rx_buf_ptr;
649			sc->rx_buf_ptr = (i + 1) % ATE_MAX_RX_BUFFERS;
650			bp = sc->rx_buf[i];
651			rx_stat = sc->rx_descs[i].status;
652			if ((rx_stat & ETH_LEN_MASK) == 0) {
653				printf("ignoring bogus 0 len packet\n");
654				bus_dmamap_sync(sc->rx_desc_tag, sc->rx_desc_map,
655				    BUS_DMASYNC_PREWRITE);
656				sc->rx_descs[i].addr &= ~ETH_CPU_OWNER;
657				bus_dmamap_sync(sc->rx_desc_tag, sc->rx_desc_map,
658				    BUS_DMASYNC_POSTWRITE);
659				continue;
660			}
661			/* Flush memory for mbuf so we don't get stale bytes */
662			bus_dmamap_sync(sc->rxtag, sc->rx_map[i],
663			    BUS_DMASYNC_POSTREAD);
664			WR4(sc, ETH_RSR, RD4(sc, ETH_RSR));
665
666			/*
667			 * The length returned by the device includes the
668			 * ethernet CRC calculation for the packet, but
669			 * ifnet drivers are supposed to discard it.
670			 */
671			mb = m_devget(sc->rx_buf[i],
672			    (rx_stat & ETH_LEN_MASK) - ETHER_CRC_LEN,
673			    ETHER_ALIGN, ifp, NULL);
674			bus_dmamap_sync(sc->rx_desc_tag, sc->rx_desc_map,
675			    BUS_DMASYNC_PREWRITE);
676			sc->rx_descs[i].addr &= ~ETH_CPU_OWNER;
677			bus_dmamap_sync(sc->rx_desc_tag, sc->rx_desc_map,
678			    BUS_DMASYNC_POSTWRITE);
679			bus_dmamap_sync(sc->rxtag, sc->rx_map[i],
680			    BUS_DMASYNC_PREREAD);
681			if (mb != NULL) {
682				ifp->if_ipackets++;
683				(*ifp->if_input)(ifp, mb);
684			}
685
686		}
687	}
688	if (status & ETH_ISR_TCOM) {
689		ATE_LOCK(sc);
690		/* XXX TSR register should be cleared */
691		if (sc->sent_mbuf[0]) {
692			bus_dmamap_sync(sc->mtag, sc->tx_map[0],
693			    BUS_DMASYNC_POSTWRITE);
694			m_freem(sc->sent_mbuf[0]);
695			ifp->if_opackets++;
696			sc->sent_mbuf[0] = NULL;
697		}
698		if (sc->sent_mbuf[1]) {
699			if (RD4(sc, ETH_TSR) & ETH_TSR_IDLE) {
700				bus_dmamap_sync(sc->mtag, sc->tx_map[1],
701				    BUS_DMASYNC_POSTWRITE);
702				m_freem(sc->sent_mbuf[1]);
703				ifp->if_opackets++;
704				sc->txcur = 0;
705				sc->sent_mbuf[0] = sc->sent_mbuf[1] = NULL;
706			} else {
707				sc->sent_mbuf[0] = sc->sent_mbuf[1];
708				sc->sent_mbuf[1] = NULL;
709				sc->txcur = 1;
710			}
711		} else {
712			sc->sent_mbuf[0] = NULL;
713			sc->txcur = 0;
714		}
715		/*
716		 * We're no longer busy, so clear the busy flag and call the
717		 * start routine to xmit more packets.
718		 */
719		sc->ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
720		atestart_locked(sc->ifp);
721		ATE_UNLOCK(sc);
722	}
723	if (status & ETH_ISR_RBNA) {
724		printf("RBNA workaround\n");
725		/* Workaround Errata #11 */
726		WR4(sc, ETH_CTL, RD4(sc, ETH_CTL) &~ ETH_CTL_RE);
727		WR4(sc, ETH_CTL, RD4(sc, ETH_CTL) | ETH_CTL_RE);
728	}
729}
730
731/*
732 * Reset and initialize the chip
733 */
734static void
735ateinit_locked(void *xsc)
736{
737	struct ate_softc *sc = xsc;
738	struct ifnet *ifp = sc->ifp;
739 	struct mii_data *mii;
740
741	ATE_ASSERT_LOCKED(sc);
742
743	/*
744	 * XXX TODO(3)
745	 * we need to turn on the EMAC clock in the pmc.  With the
746	 * default boot loader, this is already turned on.  However, we
747	 * need to think about how best to turn it on/off as the interface
748	 * is brought up/down, as well as dealing with the mii bus...
749	 *
750	 * We also need to multiplex the pins correctly.
751	 */
752
753	/*
754	 * There are two different ways that the mii bus is connected
755	 * to this chip.  Select the right one based on a compile-time
756	 * option.
757	 */
758	if (sc->use_rmii)
759		WR4(sc, ETH_CFG, RD4(sc, ETH_CFG) | ETH_CFG_RMII);
760	else
761		WR4(sc, ETH_CFG, RD4(sc, ETH_CFG) & ~ETH_CFG_RMII);
762
763	/*
764	 * Turn on the multicast hash, and write 0's to it.
765	 */
766	WR4(sc, ETH_CFG, RD4(sc, ETH_CFG) | ETH_CFG_MTI);
767	WR4(sc, ETH_HSH, 0);
768	WR4(sc, ETH_HSL, 0);
769
770	WR4(sc, ETH_CTL, RD4(sc, ETH_CTL) | ETH_CTL_TE | ETH_CTL_RE);
771	WR4(sc, ETH_IER, ETH_ISR_RCOM | ETH_ISR_TCOM | ETH_ISR_RBNA);
772
773	/*
774	 * Boot loader fills in MAC address.  If that's not the case, then
775	 * we should set SA1L and SA1H here to the appropriate value.  Note:
776	 * the byte order is big endian, not little endian, so we have some
777	 * swapping to do.  Again, if we need it (which I don't think we do).
778	 */
779	ate_setmcast(sc);
780
781	/* enable big packets */
782	WR4(sc, ETH_CFG, RD4(sc, ETH_CFG) | ETH_CFG_BIG);
783
784	/*
785	 * Set 'running' flag, and clear output active flag
786	 * and attempt to start the output
787	 */
788	ifp->if_drv_flags |= IFF_DRV_RUNNING;
789	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
790
791	mii = device_get_softc(sc->miibus);
792	mii_pollstat(mii);
793	ate_stat_update(sc, mii->mii_media_active);
794	atestart_locked(ifp);
795
796	callout_reset(&sc->tick_ch, hz, ate_tick, sc);
797}
798
799/*
800 * dequeu packets and transmit
801 */
802static void
803atestart_locked(struct ifnet *ifp)
804{
805	struct ate_softc *sc = ifp->if_softc;
806	struct mbuf *m, *mdefrag;
807	bus_dma_segment_t segs[1];
808	int nseg, e;
809
810	ATE_ASSERT_LOCKED(sc);
811	if (ifp->if_drv_flags & IFF_DRV_OACTIVE)
812		return;
813
814	while (sc->txcur < ATE_MAX_TX_BUFFERS) {
815		/*
816		 * check to see if there's room to put another packet into the
817		 * xmit queue.  The EMAC chip has a ping-pong buffer for xmit
818		 * packets.  We use OACTIVE to indicate "we can stuff more into
819		 * our buffers (clear) or not (set)."
820		 */
821		if (!(RD4(sc, ETH_TSR) & ETH_TSR_BNQ)) {
822			ifp->if_drv_flags |= IFF_DRV_OACTIVE;
823			return;
824		}
825		IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
826		if (m == 0) {
827			ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
828			return;
829		}
830		e = bus_dmamap_load_mbuf_sg(sc->mtag, sc->tx_map[sc->txcur], m,
831		    segs, &nseg, 0);
832		if (e == EFBIG) {
833			mdefrag = m_defrag(m, M_DONTWAIT);
834			if (mdefrag == NULL) {
835				IFQ_DRV_PREPEND(&ifp->if_snd, m);
836				return;
837			}
838			m = mdefrag;
839			e = bus_dmamap_load_mbuf_sg(sc->mtag,
840			    sc->tx_map[sc->txcur], m, segs, &nseg, 0);
841		}
842		if (e != 0) {
843			m_freem(m);
844			continue;
845		}
846		bus_dmamap_sync(sc->mtag, sc->tx_map[sc->txcur],
847		    BUS_DMASYNC_PREWRITE);
848
849		/*
850		 * tell the hardware to xmit the packet.
851		 */
852		WR4(sc, ETH_TAR, segs[0].ds_addr);
853		WR4(sc, ETH_TCR, segs[0].ds_len);
854
855		/*
856		 * Tap off here if there is a bpf listener.
857		 */
858		BPF_MTAP(ifp, m);
859
860		sc->sent_mbuf[sc->txcur] = m;
861		sc->txcur++;
862	}
863}
864
865static void
866ateinit(void *xsc)
867{
868	struct ate_softc *sc = xsc;
869	ATE_LOCK(sc);
870	ateinit_locked(sc);
871	ATE_UNLOCK(sc);
872}
873
874static void
875atestart(struct ifnet *ifp)
876{
877	struct ate_softc *sc = ifp->if_softc;
878	ATE_LOCK(sc);
879	atestart_locked(ifp);
880	ATE_UNLOCK(sc);
881}
882
883/*
884 * Turn off interrupts, and stop the nic.  Can be called with sc->ifp NULL
885 * so be careful.
886 */
887static void
888atestop(struct ate_softc *sc)
889{
890	struct ifnet *ifp = sc->ifp;
891
892	if (ifp) {
893		ifp->if_timer = 0;
894		ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
895	}
896
897	callout_stop(&sc->tick_ch);
898
899	/*
900	 * Enable some parts of the MAC that are needed always (like the
901	 * MII bus.  This turns off the RE and TE bits, which will remain
902	 * off until ateinit() is called to turn them on.  With RE and TE
903	 * turned off, there's no DMA to worry about after this write.
904	 */
905	WR4(sc, ETH_CTL, ETH_CTL_MPE);
906
907	/*
908	 * Turn off all the configured options and revert to defaults.
909	 */
910	WR4(sc, ETH_CFG, ETH_CFG_CLK_32);
911
912	/*
913	 * Turn off all the interrupts, and ack any pending ones by reading
914	 * the ISR.
915	 */
916	WR4(sc, ETH_IDR, 0xffffffff);
917	RD4(sc, ETH_ISR);
918
919	/*
920	 * Clear out the Transmit and Receiver Status registers of any
921	 * errors they may be reporting
922	 */
923	WR4(sc, ETH_TSR, 0xffffffff);
924	WR4(sc, ETH_RSR, 0xffffffff);
925
926	/*
927	 * XXX TODO(8)
928	 * need to worry about the busdma resources?  Yes, I think we need
929	 * to sync and unload them.  We may also need to release the mbufs
930	 * that are assocaited with RX and TX operations.
931	 */
932
933	/*
934	 * XXX we should power down the EMAC if it isn't in use, after
935	 * putting it into loopback mode.  This saves about 400uA according
936	 * to the datasheet.
937	 */
938}
939
940static int
941ateioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
942{
943	struct ate_softc *sc = ifp->if_softc;
944 	struct mii_data *mii;
945 	struct ifreq *ifr = (struct ifreq *)data;
946	int mask, error = 0;
947
948	switch (cmd) {
949	case SIOCSIFFLAGS:
950		ATE_LOCK(sc);
951		if ((ifp->if_flags & IFF_UP) == 0 &&
952		    ifp->if_drv_flags & IFF_DRV_RUNNING) {
953			ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
954			atestop(sc);
955		} else {
956			/* reinitialize card on any parameter change */
957			ateinit_locked(sc);
958		}
959		ATE_UNLOCK(sc);
960		break;
961
962	case SIOCADDMULTI:
963	case SIOCDELMULTI:
964		/* update multicast filter list. */
965		ATE_LOCK(sc);
966		ate_setmcast(sc);
967		ATE_UNLOCK(sc);
968		error = 0;
969		break;
970
971  	case SIOCSIFMEDIA:
972  	case SIOCGIFMEDIA:
973 		mii = device_get_softc(sc->miibus);
974 		error = ifmedia_ioctl(ifp, ifr, &mii->mii_media, cmd);
975  		break;
976	case SIOCSIFCAP:
977		mask = ifp->if_capenable ^ ifr->ifr_reqcap;
978		if (mask & IFCAP_VLAN_MTU) {
979			ATE_LOCK(sc);
980			if (ifr->ifr_reqcap & IFCAP_VLAN_MTU) {
981				WR4(sc, ETH_CFG, RD4(sc, ETH_CFG) | ETH_CFG_BIG);
982				ifp->if_capenable |= IFCAP_VLAN_MTU;
983			} else {
984				WR4(sc, ETH_CFG, RD4(sc, ETH_CFG) & ~ETH_CFG_BIG);
985				ifp->if_capenable &= ~IFCAP_VLAN_MTU;
986			}
987			ATE_UNLOCK(sc);
988		}
989	default:
990		error = ether_ioctl(ifp, cmd, data);
991		break;
992	}
993	return (error);
994}
995
996static void
997ate_child_detached(device_t dev, device_t child)
998{
999	struct ate_softc *sc;
1000
1001	sc = device_get_softc(dev);
1002	if (child == sc->miibus)
1003		sc->miibus = NULL;
1004}
1005
1006/*
1007 * MII bus support routines.
1008 */
1009static int
1010ate_miibus_readreg(device_t dev, int phy, int reg)
1011{
1012	struct ate_softc *sc;
1013	int val;
1014
1015	/*
1016	 * XXX if we implement agressive power savings, then we need
1017	 * XXX to make sure that the clock to the emac is on here
1018	 */
1019
1020	sc = device_get_softc(dev);
1021	DELAY(1);	/* Hangs w/o this delay really 30.5us atm */
1022	WR4(sc, ETH_MAN, ETH_MAN_REG_RD(phy, reg));
1023	while ((RD4(sc, ETH_SR) & ETH_SR_IDLE) == 0)
1024		continue;
1025	val = RD4(sc, ETH_MAN) & ETH_MAN_VALUE_MASK;
1026
1027	return (val);
1028}
1029
1030static void
1031ate_miibus_writereg(device_t dev, int phy, int reg, int data)
1032{
1033	struct ate_softc *sc;
1034
1035	/*
1036	 * XXX if we implement agressive power savings, then we need
1037	 * XXX to make sure that the clock to the emac is on here
1038	 */
1039
1040	sc = device_get_softc(dev);
1041	WR4(sc, ETH_MAN, ETH_MAN_REG_WR(phy, reg, data));
1042	while ((RD4(sc, ETH_SR) & ETH_SR_IDLE) == 0)
1043		continue;
1044	return;
1045}
1046
1047static device_method_t ate_methods[] = {
1048	/* Device interface */
1049	DEVMETHOD(device_probe,		ate_probe),
1050	DEVMETHOD(device_attach,	ate_attach),
1051	DEVMETHOD(device_detach,	ate_detach),
1052
1053	/* Bus interface */
1054	DEVMETHOD(bus_child_detached,	ate_child_detached),
1055
1056	/* MII interface */
1057	DEVMETHOD(miibus_readreg,	ate_miibus_readreg),
1058	DEVMETHOD(miibus_writereg,	ate_miibus_writereg),
1059
1060	{ 0, 0 }
1061};
1062
1063static driver_t ate_driver = {
1064	"ate",
1065	ate_methods,
1066	sizeof(struct ate_softc),
1067};
1068
1069DRIVER_MODULE(ate, atmelarm, ate_driver, ate_devclass, 0, 0);
1070DRIVER_MODULE(miibus, ate, miibus_driver, miibus_devclass, 0, 0);
1071MODULE_DEPEND(ate, miibus, 1, 1, 1);
1072MODULE_DEPEND(ate, ether, 1, 1, 1);
1073