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