if_ffec.c revision 261410
1/*-
2 * Copyright (c) 2013 Ian Lepore <ian@freebsd.org>
3 * 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 THE 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 THE 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
28#include <sys/cdefs.h>
29__FBSDID("$FreeBSD: head/sys/dev/ffec/if_ffec.c 261410 2014-02-02 19:17:28Z ian $");
30
31/*
32 * Driver for Freescale Fast Ethernet Controller, found on imx-series SoCs among
33 * others.  Also works for the ENET Gigibit controller found on imx6 and imx28,
34 * but the driver doesn't currently use any of the ENET advanced features other
35 * than enabling gigabit.
36 *
37 * The interface name 'fec' is already taken by netgraph's Fast Etherchannel
38 * (netgraph/ng_fec.c), so we use 'ffec'.
39 *
40 * Requires an FDT entry with at least these properties:
41 *   fec: ethernet@02188000 {
42 *      compatible = "fsl,imxNN-fec";
43 *      reg = <0x02188000 0x4000>;
44 *      interrupts = <150 151>;
45 *      phy-mode = "rgmii";
46 *      phy-disable-preamble; // optional
47 *   };
48 * The second interrupt number is for IEEE-1588, and is not currently used; it
49 * need not be present.  phy-mode must be one of: "mii", "rmii", "rgmii".
50 * There is also an optional property, phy-disable-preamble, which if present
51 * will disable the preamble bits, cutting the size of each mdio transaction
52 * (and thus the busy-wait time) in half.
53 */
54
55#include <sys/param.h>
56#include <sys/systm.h>
57#include <sys/bus.h>
58#include <sys/endian.h>
59#include <sys/kernel.h>
60#include <sys/lock.h>
61#include <sys/malloc.h>
62#include <sys/mbuf.h>
63#include <sys/module.h>
64#include <sys/mutex.h>
65#include <sys/rman.h>
66#include <sys/socket.h>
67#include <sys/sockio.h>
68#include <sys/sysctl.h>
69
70#include <machine/bus.h>
71
72#include <net/bpf.h>
73#include <net/if.h>
74#include <net/ethernet.h>
75#include <net/if_dl.h>
76#include <net/if_media.h>
77#include <net/if_types.h>
78#include <net/if_var.h>
79#include <net/if_vlan_var.h>
80
81#include <dev/ffec/if_ffecreg.h>
82#include <dev/ofw/ofw_bus.h>
83#include <dev/ofw/ofw_bus_subr.h>
84#include <dev/mii/mii.h>
85#include <dev/mii/miivar.h>
86#include "miibus_if.h"
87
88/*
89 * There are small differences in the hardware on various SoCs.  Not every SoC
90 * we support has its own FECTYPE; most work as GENERIC and only the ones that
91 * need different handling get their own entry.  In addition to the types in
92 * this list, there are some flags below that can be ORed into the upper bits.
93 */
94enum {
95	FECTYPE_NONE,
96	FECTYPE_GENERIC,
97	FECTYPE_IMX53,
98	FECTYPE_IMX6,
99	FECTYPE_MVF,
100};
101
102/*
103 * Flags that describe general differences between the FEC hardware in various
104 * SoCs.  These are ORed into the FECTYPE enum values.
105 */
106#define	FECTYPE_MASK		0x0000ffff
107#define	FECFLAG_GBE		(0x0001 << 16)
108
109/*
110 * Table of supported FDT compat strings and their associated FECTYPE values.
111 */
112static struct ofw_compat_data compat_data[] = {
113	{"fsl,imx51-fec",	FECTYPE_GENERIC},
114	{"fsl,imx53-fec",	FECTYPE_IMX53},
115	{"fsl,imx6q-fec",	FECTYPE_IMX6 | FECFLAG_GBE},
116	{"fsl,mvf600-fec",	FECTYPE_MVF},
117	{"fsl,mvf-fec",		FECTYPE_MVF},
118	{NULL,		 	FECTYPE_NONE},
119};
120
121/*
122 * Driver data and defines.
123 */
124#define	RX_DESC_COUNT	64
125#define	RX_DESC_SIZE	(sizeof(struct ffec_hwdesc) * RX_DESC_COUNT)
126#define	TX_DESC_COUNT	64
127#define	TX_DESC_SIZE	(sizeof(struct ffec_hwdesc) * TX_DESC_COUNT)
128
129#define	WATCHDOG_TIMEOUT_SECS	5
130#define	STATS_HARVEST_INTERVAL	3
131
132struct ffec_bufmap {
133	struct mbuf	*mbuf;
134	bus_dmamap_t	map;
135};
136
137enum {
138	PHY_CONN_UNKNOWN,
139	PHY_CONN_MII,
140	PHY_CONN_RMII,
141	PHY_CONN_RGMII
142};
143
144struct ffec_softc {
145	device_t		dev;
146	device_t		miibus;
147	struct mii_data *	mii_softc;
148	struct ifnet		*ifp;
149	int			if_flags;
150	struct mtx		mtx;
151	struct resource		*irq_res;
152	struct resource		*mem_res;
153	void *			intr_cookie;
154	struct callout		ffec_callout;
155	uint8_t			phy_conn_type;
156	uint8_t			fectype;
157	boolean_t		link_is_up;
158	boolean_t		is_attached;
159	boolean_t		is_detaching;
160	int			tx_watchdog_count;
161	int			stats_harvest_count;
162
163	bus_dma_tag_t		rxdesc_tag;
164	bus_dmamap_t		rxdesc_map;
165	struct ffec_hwdesc	*rxdesc_ring;
166	bus_addr_t		rxdesc_ring_paddr;
167	bus_dma_tag_t		rxbuf_tag;
168	struct ffec_bufmap	rxbuf_map[RX_DESC_COUNT];
169	uint32_t		rx_idx;
170
171	bus_dma_tag_t		txdesc_tag;
172	bus_dmamap_t		txdesc_map;
173	struct ffec_hwdesc	*txdesc_ring;
174	bus_addr_t		txdesc_ring_paddr;
175	bus_dma_tag_t		txbuf_tag;
176	struct ffec_bufmap	txbuf_map[RX_DESC_COUNT];
177	uint32_t		tx_idx_head;
178	uint32_t		tx_idx_tail;
179	int			txcount;
180};
181
182#define	FFEC_LOCK(sc)			mtx_lock(&(sc)->mtx)
183#define	FFEC_UNLOCK(sc)			mtx_unlock(&(sc)->mtx)
184#define	FFEC_LOCK_INIT(sc)		mtx_init(&(sc)->mtx, \
185	    device_get_nameunit((sc)->dev), MTX_NETWORK_LOCK, MTX_DEF)
186#define	FFEC_LOCK_DESTROY(sc)		mtx_destroy(&(sc)->mtx);
187#define	FFEC_ASSERT_LOCKED(sc)		mtx_assert(&(sc)->mtx, MA_OWNED);
188#define	FFEC_ASSERT_UNLOCKED(sc)	mtx_assert(&(sc)->mtx, MA_NOTOWNED);
189
190static void ffec_init_locked(struct ffec_softc *sc);
191static void ffec_stop_locked(struct ffec_softc *sc);
192static void ffec_txstart_locked(struct ffec_softc *sc);
193static void ffec_txfinish_locked(struct ffec_softc *sc);
194
195static inline uint16_t
196RD2(struct ffec_softc *sc, bus_size_t off)
197{
198
199	return (bus_read_2(sc->mem_res, off));
200}
201
202static inline void
203WR2(struct ffec_softc *sc, bus_size_t off, uint16_t val)
204{
205
206	bus_write_2(sc->mem_res, off, val);
207}
208
209static inline uint32_t
210RD4(struct ffec_softc *sc, bus_size_t off)
211{
212
213	return (bus_read_4(sc->mem_res, off));
214}
215
216static inline void
217WR4(struct ffec_softc *sc, bus_size_t off, uint32_t val)
218{
219
220	bus_write_4(sc->mem_res, off, val);
221}
222
223static inline uint32_t
224next_rxidx(struct ffec_softc *sc, uint32_t curidx)
225{
226
227	return ((curidx == RX_DESC_COUNT - 1) ? 0 : curidx + 1);
228}
229
230static inline uint32_t
231next_txidx(struct ffec_softc *sc, uint32_t curidx)
232{
233
234	return ((curidx == TX_DESC_COUNT - 1) ? 0 : curidx + 1);
235}
236
237static void
238ffec_get1paddr(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
239{
240
241	if (error != 0)
242		return;
243	*(bus_addr_t *)arg = segs[0].ds_addr;
244}
245
246static void
247ffec_miigasket_setup(struct ffec_softc *sc)
248{
249	uint32_t ifmode;
250
251	/*
252	 * We only need the gasket for MII and RMII connections on certain SoCs.
253	 */
254
255	switch (sc->fectype & FECTYPE_MASK)
256	{
257	case FECTYPE_IMX53:
258		break;
259	default:
260		return;
261	}
262
263	switch (sc->phy_conn_type)
264	{
265	case PHY_CONN_MII:
266		ifmode = 0;
267		break;
268	case PHY_CONN_RMII:
269		ifmode = FEC_MIIGSK_CFGR_IF_MODE_RMII;
270		break;
271	default:
272		return;
273	}
274
275	/*
276	 * Disable the gasket, configure for either MII or RMII, then enable.
277	 */
278
279	WR2(sc, FEC_MIIGSK_ENR, 0);
280	while (RD2(sc, FEC_MIIGSK_ENR) & FEC_MIIGSK_ENR_READY)
281		continue;
282
283	WR2(sc, FEC_MIIGSK_CFGR, ifmode);
284
285	WR2(sc, FEC_MIIGSK_ENR, FEC_MIIGSK_ENR_EN);
286	while (!(RD2(sc, FEC_MIIGSK_ENR) & FEC_MIIGSK_ENR_READY))
287		continue;
288}
289
290static boolean_t
291ffec_miibus_iowait(struct ffec_softc *sc)
292{
293	uint32_t timeout;
294
295	for (timeout = 10000; timeout != 0; --timeout)
296		if (RD4(sc, FEC_IER_REG) & FEC_IER_MII)
297			return (true);
298
299	return (false);
300}
301
302static int
303ffec_miibus_readreg(device_t dev, int phy, int reg)
304{
305	struct ffec_softc *sc;
306	int val;
307
308	sc = device_get_softc(dev);
309
310	WR4(sc, FEC_IER_REG, FEC_IER_MII);
311
312	WR4(sc, FEC_MMFR_REG, FEC_MMFR_OP_READ |
313	    FEC_MMFR_ST_VALUE | FEC_MMFR_TA_VALUE |
314	    ((phy << FEC_MMFR_PA_SHIFT) & FEC_MMFR_PA_MASK) |
315	    ((reg << FEC_MMFR_RA_SHIFT) & FEC_MMFR_RA_MASK));
316
317	if (!ffec_miibus_iowait(sc)) {
318		device_printf(dev, "timeout waiting for mii read\n");
319		return (-1); /* All-ones is a symptom of bad mdio. */
320	}
321
322	val = RD4(sc, FEC_MMFR_REG) & FEC_MMFR_DATA_MASK;
323
324	return (val);
325}
326
327static int
328ffec_miibus_writereg(device_t dev, int phy, int reg, int val)
329{
330	struct ffec_softc *sc;
331
332	sc = device_get_softc(dev);
333
334	WR4(sc, FEC_IER_REG, FEC_IER_MII);
335
336	WR4(sc, FEC_MMFR_REG, FEC_MMFR_OP_WRITE |
337	    FEC_MMFR_ST_VALUE | FEC_MMFR_TA_VALUE |
338	    ((phy << FEC_MMFR_PA_SHIFT) & FEC_MMFR_PA_MASK) |
339	    ((reg << FEC_MMFR_RA_SHIFT) & FEC_MMFR_RA_MASK) |
340	    (val & FEC_MMFR_DATA_MASK));
341
342	if (!ffec_miibus_iowait(sc)) {
343		device_printf(dev, "timeout waiting for mii write\n");
344		return (-1);
345	}
346
347	return (0);
348}
349
350static void
351ffec_miibus_statchg(device_t dev)
352{
353	struct ffec_softc *sc;
354	struct mii_data *mii;
355	uint32_t ecr, rcr, tcr;
356
357	/*
358	 * Called by the MII bus driver when the PHY establishes link to set the
359	 * MAC interface registers.
360	 */
361
362	sc = device_get_softc(dev);
363
364	FFEC_ASSERT_LOCKED(sc);
365
366	mii = sc->mii_softc;
367
368	if (mii->mii_media_status & IFM_ACTIVE)
369		sc->link_is_up = true;
370	else
371		sc->link_is_up = false;
372
373	ecr = RD4(sc, FEC_ECR_REG) & ~FEC_ECR_SPEED;
374	rcr = RD4(sc, FEC_RCR_REG) & ~(FEC_RCR_RMII_10T | FEC_RCR_RMII_MODE |
375	    FEC_RCR_RGMII_EN | FEC_RCR_DRT | FEC_RCR_FCE);
376	tcr = RD4(sc, FEC_TCR_REG) & ~FEC_TCR_FDEN;
377
378	rcr |= FEC_RCR_MII_MODE; /* Must always be on even for R[G]MII. */
379	switch (sc->phy_conn_type) {
380	case PHY_CONN_MII:
381		break;
382	case PHY_CONN_RMII:
383		rcr |= FEC_RCR_RMII_MODE;
384		break;
385	case PHY_CONN_RGMII:
386		rcr |= FEC_RCR_RGMII_EN;
387		break;
388	}
389
390	switch (IFM_SUBTYPE(mii->mii_media_active)) {
391	case IFM_1000_T:
392	case IFM_1000_SX:
393		ecr |= FEC_ECR_SPEED;
394		break;
395	case IFM_100_TX:
396		/* Not-FEC_ECR_SPEED + not-FEC_RCR_RMII_10T means 100TX */
397		break;
398	case IFM_10_T:
399		rcr |= FEC_RCR_RMII_10T;
400		break;
401	case IFM_NONE:
402		sc->link_is_up = false;
403		return;
404	default:
405		sc->link_is_up = false;
406		device_printf(dev, "Unsupported media %u\n",
407		    IFM_SUBTYPE(mii->mii_media_active));
408		return;
409	}
410
411	if ((IFM_OPTIONS(mii->mii_media_active) & IFM_FDX) != 0)
412		tcr |= FEC_TCR_FDEN;
413	else
414		rcr |= FEC_RCR_DRT;
415
416	if ((IFM_OPTIONS(mii->mii_media_active) & IFM_FLOW) != 0)
417		rcr |= FEC_RCR_FCE;
418
419	WR4(sc, FEC_RCR_REG, rcr);
420	WR4(sc, FEC_TCR_REG, tcr);
421	WR4(sc, FEC_ECR_REG, ecr);
422}
423
424static void
425ffec_media_status(struct ifnet * ifp, struct ifmediareq *ifmr)
426{
427	struct ffec_softc *sc;
428	struct mii_data *mii;
429
430
431	sc = ifp->if_softc;
432	mii = sc->mii_softc;
433	FFEC_LOCK(sc);
434	mii_pollstat(mii);
435	ifmr->ifm_active = mii->mii_media_active;
436	ifmr->ifm_status = mii->mii_media_status;
437	FFEC_UNLOCK(sc);
438}
439
440static int
441ffec_media_change_locked(struct ffec_softc *sc)
442{
443
444	return (mii_mediachg(sc->mii_softc));
445}
446
447static int
448ffec_media_change(struct ifnet * ifp)
449{
450	struct ffec_softc *sc;
451	int error;
452
453	sc = ifp->if_softc;
454
455	FFEC_LOCK(sc);
456	error = ffec_media_change_locked(sc);
457	FFEC_UNLOCK(sc);
458	return (error);
459}
460
461static void ffec_clear_stats(struct ffec_softc *sc)
462{
463
464	WR4(sc, FEC_RMON_R_PACKETS, 0);
465	WR4(sc, FEC_RMON_R_MC_PKT, 0);
466	WR4(sc, FEC_RMON_R_CRC_ALIGN, 0);
467	WR4(sc, FEC_RMON_R_UNDERSIZE, 0);
468	WR4(sc, FEC_RMON_R_OVERSIZE, 0);
469	WR4(sc, FEC_RMON_R_FRAG, 0);
470	WR4(sc, FEC_RMON_R_JAB, 0);
471	WR4(sc, FEC_RMON_T_PACKETS, 0);
472	WR4(sc, FEC_RMON_T_MC_PKT, 0);
473	WR4(sc, FEC_RMON_T_CRC_ALIGN, 0);
474	WR4(sc, FEC_RMON_T_UNDERSIZE, 0);
475	WR4(sc, FEC_RMON_T_OVERSIZE , 0);
476	WR4(sc, FEC_RMON_T_FRAG, 0);
477	WR4(sc, FEC_RMON_T_JAB, 0);
478	WR4(sc, FEC_RMON_T_COL, 0);
479}
480
481static void
482ffec_harvest_stats(struct ffec_softc *sc)
483{
484	struct ifnet *ifp;
485
486	/* We don't need to harvest too often. */
487	if (++sc->stats_harvest_count < STATS_HARVEST_INTERVAL)
488		return;
489
490	/*
491	 * Try to avoid harvesting unless the IDLE flag is on, but if it has
492	 * been too long just go ahead and do it anyway, the worst that'll
493	 * happen is we'll lose a packet count or two as we clear at the end.
494	 */
495	if (sc->stats_harvest_count < (2 * STATS_HARVEST_INTERVAL) &&
496	    ((RD4(sc, FEC_MIBC_REG) & FEC_MIBC_IDLE) == 0))
497		return;
498
499	sc->stats_harvest_count = 0;
500	ifp = sc->ifp;
501
502	ifp->if_ipackets   += RD4(sc, FEC_RMON_R_PACKETS);
503	ifp->if_imcasts    += RD4(sc, FEC_RMON_R_MC_PKT);
504	ifp->if_ierrors    += RD4(sc, FEC_RMON_R_CRC_ALIGN);
505	ifp->if_ierrors    += RD4(sc, FEC_RMON_R_UNDERSIZE);
506	ifp->if_ierrors    += RD4(sc, FEC_RMON_R_OVERSIZE);
507	ifp->if_ierrors    += RD4(sc, FEC_RMON_R_FRAG);
508	ifp->if_ierrors    += RD4(sc, FEC_RMON_R_JAB);
509
510	ifp->if_opackets   += RD4(sc, FEC_RMON_T_PACKETS);
511	ifp->if_omcasts    += RD4(sc, FEC_RMON_T_MC_PKT);
512	ifp->if_oerrors    += RD4(sc, FEC_RMON_T_CRC_ALIGN);
513	ifp->if_oerrors    += RD4(sc, FEC_RMON_T_UNDERSIZE);
514	ifp->if_oerrors    += RD4(sc, FEC_RMON_T_OVERSIZE );
515	ifp->if_oerrors    += RD4(sc, FEC_RMON_T_FRAG);
516	ifp->if_oerrors    += RD4(sc, FEC_RMON_T_JAB);
517
518	ifp->if_collisions += RD4(sc, FEC_RMON_T_COL);
519
520	ffec_clear_stats(sc);
521}
522
523static void
524ffec_tick(void *arg)
525{
526	struct ffec_softc *sc;
527	struct ifnet *ifp;
528	int link_was_up;
529
530	sc = arg;
531
532	FFEC_ASSERT_LOCKED(sc);
533
534	ifp = sc->ifp;
535
536	if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
537	    return;
538
539	/*
540	 * Typical tx watchdog.  If this fires it indicates that we enqueued
541	 * packets for output and never got a txdone interrupt for them.  Maybe
542	 * it's a missed interrupt somehow, just pretend we got one.
543	 */
544	if (sc->tx_watchdog_count > 0) {
545		if (--sc->tx_watchdog_count == 0) {
546			ffec_txfinish_locked(sc);
547		}
548	}
549
550	/* Gather stats from hardware counters. */
551	ffec_harvest_stats(sc);
552
553	/* Check the media status. */
554	link_was_up = sc->link_is_up;
555	mii_tick(sc->mii_softc);
556	if (sc->link_is_up && !link_was_up)
557		ffec_txstart_locked(sc);
558
559	/* Schedule another check one second from now. */
560	callout_reset(&sc->ffec_callout, hz, ffec_tick, sc);
561}
562
563inline static uint32_t
564ffec_setup_txdesc(struct ffec_softc *sc, int idx, bus_addr_t paddr,
565    uint32_t len)
566{
567	uint32_t nidx;
568	uint32_t flags;
569
570	nidx = next_txidx(sc, idx);
571
572	/* Addr/len 0 means we're clearing the descriptor after xmit done. */
573	if (paddr == 0 || len == 0) {
574		flags = 0;
575		--sc->txcount;
576	} else {
577		flags = FEC_TXDESC_READY | FEC_TXDESC_L | FEC_TXDESC_TC;
578		++sc->txcount;
579	}
580	if (nidx == 0)
581		flags |= FEC_TXDESC_WRAP;
582
583	/*
584	 * The hardware requires 32-bit physical addresses.  We set up the dma
585	 * tag to indicate that, so the cast to uint32_t should never lose
586	 * significant bits.
587	 */
588	sc->txdesc_ring[idx].buf_paddr = (uint32_t)paddr;
589	sc->txdesc_ring[idx].flags_len = flags | len; /* Must be set last! */
590
591	return (nidx);
592}
593
594static int
595ffec_setup_txbuf(struct ffec_softc *sc, int idx, struct mbuf **mp)
596{
597	struct mbuf * m;
598	int error, nsegs;
599	struct bus_dma_segment seg;
600
601	if ((m = m_defrag(*mp, M_NOWAIT)) == NULL)
602		return (ENOMEM);
603	*mp = m;
604
605	error = bus_dmamap_load_mbuf_sg(sc->txbuf_tag, sc->txbuf_map[idx].map,
606	    m, &seg, &nsegs, 0);
607	if (error != 0) {
608		return (ENOMEM);
609	}
610	bus_dmamap_sync(sc->txbuf_tag, sc->txbuf_map[idx].map,
611	    BUS_DMASYNC_PREWRITE);
612
613	sc->txbuf_map[idx].mbuf = m;
614	ffec_setup_txdesc(sc, idx, seg.ds_addr, seg.ds_len);
615
616	return (0);
617
618}
619
620static void
621ffec_txstart_locked(struct ffec_softc *sc)
622{
623	struct ifnet *ifp;
624	struct mbuf *m;
625	int enqueued;
626
627	FFEC_ASSERT_LOCKED(sc);
628
629	if (!sc->link_is_up)
630		return;
631
632	ifp = sc->ifp;
633
634	if (ifp->if_drv_flags & IFF_DRV_OACTIVE)
635		return;
636
637	enqueued = 0;
638
639	for (;;) {
640		if (sc->txcount == (TX_DESC_COUNT-1)) {
641			ifp->if_drv_flags |= IFF_DRV_OACTIVE;
642			break;
643		}
644		IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
645		if (m == NULL)
646			break;
647		if (ffec_setup_txbuf(sc, sc->tx_idx_head, &m) != 0) {
648			IFQ_DRV_PREPEND(&ifp->if_snd, m);
649			break;
650		}
651		BPF_MTAP(ifp, m);
652		sc->tx_idx_head = next_txidx(sc, sc->tx_idx_head);
653		++enqueued;
654	}
655
656	if (enqueued != 0) {
657		WR4(sc, FEC_TDAR_REG, FEC_TDAR_TDAR);
658		sc->tx_watchdog_count = WATCHDOG_TIMEOUT_SECS;
659	}
660}
661
662static void
663ffec_txstart(struct ifnet *ifp)
664{
665	struct ffec_softc *sc = ifp->if_softc;
666
667	FFEC_LOCK(sc);
668	ffec_txstart_locked(sc);
669	FFEC_UNLOCK(sc);
670}
671
672static void
673ffec_txfinish_locked(struct ffec_softc *sc)
674{
675	struct ifnet *ifp;
676	struct ffec_hwdesc *desc;
677	struct ffec_bufmap *bmap;
678	boolean_t retired_buffer;
679
680	FFEC_ASSERT_LOCKED(sc);
681
682	ifp = sc->ifp;
683	retired_buffer = false;
684	while (sc->tx_idx_tail != sc->tx_idx_head) {
685		desc = &sc->txdesc_ring[sc->tx_idx_tail];
686		if (desc->flags_len & FEC_TXDESC_READY)
687			break;
688		retired_buffer = true;
689		bmap = &sc->txbuf_map[sc->tx_idx_tail];
690		bus_dmamap_sync(sc->txbuf_tag, bmap->map,
691		    BUS_DMASYNC_POSTWRITE);
692		bus_dmamap_unload(sc->txbuf_tag, bmap->map);
693		m_freem(bmap->mbuf);
694		bmap->mbuf = NULL;
695		ffec_setup_txdesc(sc, sc->tx_idx_tail, 0, 0);
696		sc->tx_idx_tail = next_txidx(sc, sc->tx_idx_tail);
697	}
698
699	/*
700	 * If we retired any buffers, there will be open tx slots available in
701	 * the descriptor ring, go try to start some new output.
702	 */
703	if (retired_buffer) {
704		ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
705		ffec_txstart_locked(sc);
706	}
707
708	/* If there are no buffers outstanding, muzzle the watchdog. */
709	if (sc->tx_idx_tail == sc->tx_idx_head) {
710		sc->tx_watchdog_count = 0;
711	}
712}
713
714inline static uint32_t
715ffec_setup_rxdesc(struct ffec_softc *sc, int idx, bus_addr_t paddr)
716{
717	uint32_t nidx;
718
719	/*
720	 * The hardware requires 32-bit physical addresses.  We set up the dma
721	 * tag to indicate that, so the cast to uint32_t should never lose
722	 * significant bits.
723	 */
724	nidx = next_rxidx(sc, idx);
725	sc->rxdesc_ring[idx].buf_paddr = (uint32_t)paddr;
726	sc->rxdesc_ring[idx].flags_len = FEC_RXDESC_EMPTY |
727		((nidx == 0) ? FEC_RXDESC_WRAP : 0);
728
729	return (nidx);
730}
731
732static int
733ffec_setup_rxbuf(struct ffec_softc *sc, int idx, struct mbuf * m)
734{
735	int error, nsegs;
736	struct bus_dma_segment seg;
737
738	/*
739	 * We need to leave at least ETHER_ALIGN bytes free at the beginning of
740	 * the buffer to allow the data to be re-aligned after receiving it (by
741	 * copying it backwards ETHER_ALIGN bytes in the same buffer).  We also
742	 * have to ensure that the beginning of the buffer is aligned to the
743	 * hardware's requirements.
744	 */
745	m_adj(m, roundup(ETHER_ALIGN, FEC_RXBUF_ALIGN));
746
747	error = bus_dmamap_load_mbuf_sg(sc->rxbuf_tag, sc->rxbuf_map[idx].map,
748	    m, &seg, &nsegs, 0);
749	if (error != 0) {
750		return (error);
751	}
752
753	bus_dmamap_sync(sc->rxbuf_tag, sc->rxbuf_map[idx].map,
754	    BUS_DMASYNC_PREREAD);
755
756	sc->rxbuf_map[idx].mbuf = m;
757	ffec_setup_rxdesc(sc, idx, seg.ds_addr);
758
759	return (0);
760}
761
762static struct mbuf *
763ffec_alloc_mbufcl(struct ffec_softc *sc)
764{
765	struct mbuf *m;
766
767	m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
768	m->m_pkthdr.len = m->m_len = m->m_ext.ext_size;
769
770	return (m);
771}
772
773static void
774ffec_rxfinish_onebuf(struct ffec_softc *sc, int len)
775{
776	struct mbuf *m, *newmbuf;
777	struct ffec_bufmap *bmap;
778	uint8_t *dst, *src;
779	int error;
780
781	/*
782	 *  First try to get a new mbuf to plug into this slot in the rx ring.
783	 *  If that fails, drop the current packet and recycle the current
784	 *  mbuf, which is still mapped and loaded.
785	 */
786	if ((newmbuf = ffec_alloc_mbufcl(sc)) == NULL) {
787		++sc->ifp->if_iqdrops;
788		ffec_setup_rxdesc(sc, sc->rx_idx,
789		    sc->rxdesc_ring[sc->rx_idx].buf_paddr);
790		return;
791	}
792
793	/*
794	 *  Unfortunately, the protocol headers need to be aligned on a 32-bit
795	 *  boundary for the upper layers.  The hardware requires receive
796	 *  buffers to be 16-byte aligned.  The ethernet header is 14 bytes,
797	 *  leaving the protocol header unaligned.  We used m_adj() after
798	 *  allocating the buffer to leave empty space at the start of the
799	 *  buffer, now we'll use the alignment agnostic bcopy() routine to
800	 *  shuffle all the data backwards 2 bytes and adjust m_data.
801	 *
802	 *  XXX imx6 hardware is able to do this 2-byte alignment by setting the
803	 *  SHIFT16 bit in the RACC register.  Older hardware doesn't have that
804	 *  feature, but for them could we speed this up by copying just the
805	 *  protocol headers into their own small mbuf then chaining the cluster
806	 *  to it?  That way we'd only need to copy like 64 bytes or whatever
807	 *  the biggest header is, instead of the whole 1530ish-byte frame.
808	 */
809
810	FFEC_UNLOCK(sc);
811
812	bmap = &sc->rxbuf_map[sc->rx_idx];
813	len -= ETHER_CRC_LEN;
814	bus_dmamap_sync(sc->rxbuf_tag, bmap->map, BUS_DMASYNC_POSTREAD);
815	bus_dmamap_unload(sc->rxbuf_tag, bmap->map);
816	m = bmap->mbuf;
817	bmap->mbuf = NULL;
818	m->m_len = len;
819	m->m_pkthdr.len = len;
820	m->m_pkthdr.rcvif = sc->ifp;
821
822	src = mtod(m, uint8_t*);
823	dst = src - ETHER_ALIGN;
824	bcopy(src, dst, len);
825	m->m_data = dst;
826	sc->ifp->if_input(sc->ifp, m);
827
828	FFEC_LOCK(sc);
829
830	if ((error = ffec_setup_rxbuf(sc, sc->rx_idx, newmbuf)) != 0) {
831		device_printf(sc->dev, "ffec_setup_rxbuf error %d\n", error);
832		/* XXX Now what?  We've got a hole in the rx ring. */
833	}
834
835}
836
837static void
838ffec_rxfinish_locked(struct ffec_softc *sc)
839{
840	struct ffec_hwdesc *desc;
841	int len;
842	boolean_t produced_empty_buffer;
843
844	FFEC_ASSERT_LOCKED(sc);
845
846	produced_empty_buffer = false;
847	for (;;) {
848		desc = &sc->rxdesc_ring[sc->rx_idx];
849		if (desc->flags_len & FEC_RXDESC_EMPTY)
850			break;
851		produced_empty_buffer = true;
852		len = (desc->flags_len & FEC_RXDESC_LEN_MASK);
853		if (len < 64) {
854			/*
855			 * Just recycle the descriptor and continue.           .
856			 */
857			ffec_setup_rxdesc(sc, sc->rx_idx,
858			    sc->rxdesc_ring[sc->rx_idx].buf_paddr);
859		} else if ((desc->flags_len & FEC_RXDESC_L) == 0) {
860			/*
861			 * The entire frame is not in this buffer.  Impossible.
862			 * Recycle the descriptor and continue.
863			 *
864			 * XXX what's the right way to handle this? Probably we
865			 * should stop/init the hardware because this should
866			 * just really never happen when we have buffers bigger
867			 * than the maximum frame size.
868			 */
869			device_printf(sc->dev,
870			    "fec_rxfinish: received frame without LAST bit set");
871			ffec_setup_rxdesc(sc, sc->rx_idx,
872			    sc->rxdesc_ring[sc->rx_idx].buf_paddr);
873		} else if (desc->flags_len & FEC_RXDESC_ERROR_BITS) {
874			/*
875			 *  Something went wrong with receiving the frame, we
876			 *  don't care what (the hardware has counted the error
877			 *  in the stats registers already), we just reuse the
878			 *  same mbuf, which is still dma-mapped, by resetting
879			 *  the rx descriptor.
880			 */
881			ffec_setup_rxdesc(sc, sc->rx_idx,
882			    sc->rxdesc_ring[sc->rx_idx].buf_paddr);
883		} else {
884			/*
885			 *  Normal case: a good frame all in one buffer.
886			 */
887			ffec_rxfinish_onebuf(sc, len);
888		}
889		sc->rx_idx = next_rxidx(sc, sc->rx_idx);
890	}
891
892	if (produced_empty_buffer) {
893		WR4(sc, FEC_RDAR_REG, FEC_RDAR_RDAR);
894	}
895}
896
897static void
898ffec_get_hwaddr(struct ffec_softc *sc, uint8_t *hwaddr)
899{
900	uint32_t palr, paur, rnd;
901
902	/*
903	 * Try to recover a MAC address from the running hardware. If there's
904	 * something non-zero there, assume the bootloader did the right thing
905	 * and just use it.
906	 *
907	 * Otherwise, set the address to a convenient locally assigned address,
908	 * 'bsd' + random 24 low-order bits.  'b' is 0x62, which has the locally
909	 * assigned bit set, and the broadcast/multicast bit clear.
910	 */
911	palr = RD4(sc, FEC_PALR_REG);
912	paur = RD4(sc, FEC_PAUR_REG) & FEC_PAUR_PADDR2_MASK;
913	if ((palr | paur) != 0) {
914		hwaddr[0] = palr >> 24;
915		hwaddr[1] = palr >> 16;
916		hwaddr[2] = palr >>  8;
917		hwaddr[3] = palr >>  0;
918		hwaddr[4] = paur >> 24;
919		hwaddr[5] = paur >> 16;
920	} else {
921		rnd = arc4random() & 0x00ffffff;
922		hwaddr[0] = 'b';
923		hwaddr[1] = 's';
924		hwaddr[2] = 'd';
925		hwaddr[3] = rnd >> 16;
926		hwaddr[4] = rnd >>  8;
927		hwaddr[5] = rnd >>  0;
928	}
929
930	if (bootverbose) {
931		device_printf(sc->dev,
932		    "MAC address %02x:%02x:%02x:%02x:%02x:%02x:\n",
933		    hwaddr[0], hwaddr[1], hwaddr[2],
934		    hwaddr[3], hwaddr[4], hwaddr[5]);
935	}
936}
937
938static void
939ffec_setup_rxfilter(struct ffec_softc *sc)
940{
941	struct ifnet *ifp;
942	struct ifmultiaddr *ifma;
943	uint8_t *eaddr;
944	uint32_t crc;
945	uint64_t ghash, ihash;
946
947	FFEC_ASSERT_LOCKED(sc);
948
949	ifp = sc->ifp;
950
951	/*
952	 * Set the multicast (group) filter hash.
953	 */
954	if ((ifp->if_flags & IFF_ALLMULTI))
955		ghash = 0xffffffffffffffffLLU;
956	else {
957		ghash = 0;
958		if_maddr_rlock(ifp);
959		TAILQ_FOREACH(ifma, &sc->ifp->if_multiaddrs, ifma_link) {
960			if (ifma->ifma_addr->sa_family != AF_LINK)
961				continue;
962			crc = ether_crc32_be(LLADDR((struct sockaddr_dl *)
963			    ifma->ifma_addr), ETHER_ADDR_LEN);
964			ghash |= 1 << (crc & 0x3f);
965		}
966		if_maddr_runlock(ifp);
967	}
968	WR4(sc, FEC_GAUR_REG, (uint32_t)(ghash >> 32));
969	WR4(sc, FEC_GALR_REG, (uint32_t)ghash);
970
971	/*
972	 * Set the individual address filter hash.
973	 *
974	 * XXX Is 0 the right value when promiscuous is off?  This hw feature
975	 * seems to support the concept of MAC address aliases, does such a
976	 * thing even exist?
977	 */
978	if ((ifp->if_flags & IFF_PROMISC))
979		ihash = 0xffffffffffffffffLLU;
980	else {
981		ihash = 0;
982	}
983	WR4(sc, FEC_IAUR_REG, (uint32_t)(ihash >> 32));
984	WR4(sc, FEC_IALR_REG, (uint32_t)ihash);
985
986	/*
987	 * Set the primary address.
988	 */
989	eaddr = IF_LLADDR(ifp);
990	WR4(sc, FEC_PALR_REG, (eaddr[0] << 24) | (eaddr[1] << 16) |
991	    (eaddr[2] <<  8) | eaddr[3]);
992	WR4(sc, FEC_PAUR_REG, (eaddr[4] << 24) | (eaddr[5] << 16));
993}
994
995static void
996ffec_stop_locked(struct ffec_softc *sc)
997{
998	struct ifnet *ifp;
999	struct ffec_hwdesc *desc;
1000	struct ffec_bufmap *bmap;
1001	int idx;
1002
1003	FFEC_ASSERT_LOCKED(sc);
1004
1005	ifp = sc->ifp;
1006	ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
1007	sc->tx_watchdog_count = 0;
1008	sc->stats_harvest_count = 0;
1009
1010	/*
1011	 * Stop the hardware, mask all interrupts, and clear all current
1012	 * interrupt status bits.
1013	 */
1014	WR4(sc, FEC_ECR_REG, RD4(sc, FEC_ECR_REG) & ~FEC_ECR_ETHEREN);
1015	WR4(sc, FEC_IEM_REG, 0x00000000);
1016	WR4(sc, FEC_IER_REG, 0xffffffff);
1017
1018	/*
1019	 * Stop the media-check callout.  Do not use callout_drain() because
1020	 * we're holding a mutex the callout acquires, and if it's currently
1021	 * waiting to acquire it, we'd deadlock.  If it is waiting now, the
1022	 * ffec_tick() routine will return without doing anything when it sees
1023	 * that IFF_DRV_RUNNING is not set, so avoiding callout_drain() is safe.
1024	 */
1025	callout_stop(&sc->ffec_callout);
1026
1027	/*
1028	 * Discard all untransmitted buffers.  Each buffer is simply freed;
1029	 * it's as if the bits were transmitted and then lost on the wire.
1030	 *
1031	 * XXX Is this right?  Or should we use IFQ_DRV_PREPEND() to put them
1032	 * back on the queue for when we get restarted later?
1033	 */
1034	idx = sc->tx_idx_tail;
1035	while (idx != sc->tx_idx_head) {
1036		desc = &sc->txdesc_ring[idx];
1037		bmap = &sc->txbuf_map[idx];
1038		if (desc->buf_paddr != 0) {
1039			bus_dmamap_unload(sc->txbuf_tag, bmap->map);
1040			m_freem(bmap->mbuf);
1041			bmap->mbuf = NULL;
1042			ffec_setup_txdesc(sc, idx, 0, 0);
1043		}
1044		idx = next_txidx(sc, idx);
1045	}
1046
1047	/*
1048	 * Discard all unprocessed receive buffers.  This amounts to just
1049	 * pretending that nothing ever got received into them.  We reuse the
1050	 * mbuf already mapped for each desc, simply turning the EMPTY flags
1051	 * back on so they'll get reused when we start up again.
1052	 */
1053	for (idx = 0; idx < RX_DESC_COUNT; ++idx) {
1054		desc = &sc->rxdesc_ring[idx];
1055		ffec_setup_rxdesc(sc, idx, desc->buf_paddr);
1056	}
1057}
1058
1059static void
1060ffec_init_locked(struct ffec_softc *sc)
1061{
1062	struct ifnet *ifp = sc->ifp;
1063	uint32_t maxbuf, maxfl, regval;
1064
1065	FFEC_ASSERT_LOCKED(sc);
1066
1067	/*
1068	 * The hardware has a limit of 0x7ff as the max frame length (see
1069	 * comments for MRBR below), and we use mbuf clusters as receive
1070	 * buffers, and we currently are designed to receive an entire frame
1071	 * into a single buffer.
1072	 *
1073	 * We start with a MCLBYTES-sized cluster, but we have to offset into
1074	 * the buffer by ETHER_ALIGN to make room for post-receive re-alignment,
1075	 * and then that value has to be rounded up to the hardware's DMA
1076	 * alignment requirements, so all in all our buffer is that much smaller
1077	 * than MCLBYTES.
1078	 *
1079	 * The resulting value is used as the frame truncation length and the
1080	 * max buffer receive buffer size for now.  It'll become more complex
1081	 * when we support jumbo frames and receiving fragments of them into
1082	 * separate buffers.
1083	 */
1084	maxbuf = MCLBYTES - roundup(ETHER_ALIGN, FEC_RXBUF_ALIGN);
1085	maxfl = min(maxbuf, 0x7ff);
1086
1087	if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1088		return;
1089
1090	/* Mask all interrupts and clear all current interrupt status bits. */
1091	WR4(sc, FEC_IEM_REG, 0x00000000);
1092	WR4(sc, FEC_IER_REG, 0xffffffff);
1093
1094	/*
1095	 * Go set up palr/puar, galr/gaur, ialr/iaur.
1096	 */
1097	ffec_setup_rxfilter(sc);
1098
1099	/*
1100	 * TFWR - Transmit FIFO watermark register.
1101	 *
1102	 * Set the transmit fifo watermark register to "store and forward" mode
1103	 * and also set a threshold of 128 bytes in the fifo before transmission
1104	 * of a frame begins (to avoid dma underruns).  Recent FEC hardware
1105	 * supports STRFWD and when that bit is set, the watermark level in the
1106	 * low bits is ignored.  Older hardware doesn't have STRFWD, but writing
1107	 * to that bit is innocuous, and the TWFR bits get used instead.
1108	 */
1109	WR4(sc, FEC_TFWR_REG, FEC_TFWR_STRFWD | FEC_TFWR_TWFR_128BYTE);
1110
1111	/* RCR - Receive control register.
1112	 *
1113	 * Set max frame length + clean out anything left from u-boot.
1114	 */
1115	WR4(sc, FEC_RCR_REG, (maxfl << FEC_RCR_MAX_FL_SHIFT));
1116
1117	/*
1118	 * TCR - Transmit control register.
1119	 *
1120	 * Clean out anything left from u-boot.  Any necessary values are set in
1121	 * ffec_miibus_statchg() based on the media type.
1122	 */
1123	WR4(sc, FEC_TCR_REG, 0);
1124
1125	/*
1126	 * OPD - Opcode/pause duration.
1127	 *
1128	 * XXX These magic numbers come from u-boot.
1129	 */
1130	WR4(sc, FEC_OPD_REG, 0x00010020);
1131
1132	/*
1133	 * FRSR - Fifo receive start register.
1134	 *
1135	 * This register does not exist on imx6, it is present on earlier
1136	 * hardware. The u-boot code sets this to a non-default value that's 32
1137	 * bytes larger than the default, with no clue as to why.  The default
1138	 * value should work fine, so there's no code to init it here.
1139	 */
1140
1141	/*
1142	 *  MRBR - Max RX buffer size.
1143	 *
1144	 *  Note: For hardware prior to imx6 this value cannot exceed 0x07ff,
1145	 *  but the datasheet says no such thing for imx6.  On the imx6, setting
1146	 *  this to 2K without setting EN1588 resulted in a crazy runaway
1147	 *  receive loop in the hardware, where every rx descriptor in the ring
1148	 *  had its EMPTY flag cleared, no completion or error flags set, and a
1149	 *  length of zero.  I think maybe you can only exceed it when EN1588 is
1150	 *  set, like maybe that's what enables jumbo frames, because in general
1151	 *  the EN1588 flag seems to be the "enable new stuff" vs. "be legacy-
1152	 *  compatible" flag.
1153	 */
1154	WR4(sc, FEC_MRBR_REG, maxfl << FEC_MRBR_R_BUF_SIZE_SHIFT);
1155
1156	/*
1157	 * FTRL - Frame truncation length.
1158	 *
1159	 * Must be greater than or equal to the value set in FEC_RCR_MAXFL.
1160	 */
1161	WR4(sc, FEC_FTRL_REG, maxfl);
1162
1163	/*
1164	 * RDSR / TDSR descriptor ring pointers.
1165	 *
1166	 * When we turn on ECR_ETHEREN at the end, the hardware zeroes its
1167	 * internal current descriptor index values for both rings, so we zero
1168	 * our index values as well.
1169	 */
1170	sc->rx_idx = 0;
1171	sc->tx_idx_head = sc->tx_idx_tail = 0;
1172	sc->txcount = 0;
1173	WR4(sc, FEC_RDSR_REG, sc->rxdesc_ring_paddr);
1174	WR4(sc, FEC_TDSR_REG, sc->txdesc_ring_paddr);
1175
1176	/*
1177	 * EIM - interrupt mask register.
1178	 *
1179	 * We always enable the same set of interrupts while running; unlike
1180	 * some drivers there's no need to change the mask on the fly depending
1181	 * on what operations are in progress.
1182	 */
1183	WR4(sc, FEC_IEM_REG, FEC_IER_TXF | FEC_IER_RXF | FEC_IER_EBERR);
1184
1185	/*
1186	 * MIBC - MIB control (hardware stats).
1187	 */
1188	regval = RD4(sc, FEC_MIBC_REG);
1189	WR4(sc, FEC_MIBC_REG, regval | FEC_MIBC_DIS);
1190	ffec_clear_stats(sc);
1191	WR4(sc, FEC_MIBC_REG, regval & ~FEC_MIBC_DIS);
1192
1193	/*
1194	 * ECR - Ethernet control register.
1195	 *
1196	 * This must happen after all the other config registers are set.  If
1197	 * we're running on little-endian hardware, also set the flag for byte-
1198	 * swapping descriptor ring entries.  This flag doesn't exist on older
1199	 * hardware, but it can be safely set -- the bit position it occupies
1200	 * was unused.
1201	 */
1202	regval = RD4(sc, FEC_ECR_REG);
1203#if _BYTE_ORDER == _LITTLE_ENDIAN
1204	regval |= FEC_ECR_DBSWP;
1205#endif
1206	regval |= FEC_ECR_ETHEREN;
1207	WR4(sc, FEC_ECR_REG, regval);
1208
1209	ifp->if_drv_flags |= IFF_DRV_RUNNING;
1210
1211       /*
1212	* Call mii_mediachg() which will call back into ffec_miibus_statchg() to
1213	* set up the remaining config registers based on the current media.
1214	*/
1215	mii_mediachg(sc->mii_softc);
1216	callout_reset(&sc->ffec_callout, hz, ffec_tick, sc);
1217
1218	/*
1219	 * Tell the hardware that receive buffers are available.  They were made
1220	 * available in ffec_attach() or ffec_stop().
1221	 */
1222	WR4(sc, FEC_RDAR_REG, FEC_RDAR_RDAR);
1223}
1224
1225static void
1226ffec_init(void *if_softc)
1227{
1228	struct ffec_softc *sc = if_softc;
1229
1230	FFEC_LOCK(sc);
1231	ffec_init_locked(sc);
1232	FFEC_UNLOCK(sc);
1233}
1234
1235static void
1236ffec_intr(void *arg)
1237{
1238	struct ffec_softc *sc;
1239	uint32_t ier;
1240
1241	sc = arg;
1242
1243	FFEC_LOCK(sc);
1244
1245	ier = RD4(sc, FEC_IER_REG);
1246
1247	if (ier & FEC_IER_TXF) {
1248		WR4(sc, FEC_IER_REG, FEC_IER_TXF);
1249		ffec_txfinish_locked(sc);
1250	}
1251
1252	if (ier & FEC_IER_RXF) {
1253		WR4(sc, FEC_IER_REG, FEC_IER_RXF);
1254		ffec_rxfinish_locked(sc);
1255	}
1256
1257	/*
1258	 * We actually don't care about most errors, because the hardware copes
1259	 * with them just fine, discarding the incoming bad frame, or forcing a
1260	 * bad CRC onto an outgoing bad frame, and counting the errors in the
1261	 * stats registers.  The one that really matters is EBERR (DMA bus
1262	 * error) because the hardware automatically clears ECR[ETHEREN] and we
1263	 * have to restart it here.  It should never happen.
1264	 */
1265	if (ier & FEC_IER_EBERR) {
1266		WR4(sc, FEC_IER_REG, FEC_IER_EBERR);
1267		device_printf(sc->dev,
1268		    "Ethernet DMA error, restarting controller.\n");
1269		ffec_stop_locked(sc);
1270		ffec_init_locked(sc);
1271	}
1272
1273	FFEC_UNLOCK(sc);
1274
1275}
1276
1277static int
1278ffec_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1279{
1280	struct ffec_softc *sc;
1281	struct mii_data *mii;
1282	struct ifreq *ifr;
1283	int mask, error;
1284
1285	sc = ifp->if_softc;
1286	ifr = (struct ifreq *)data;
1287
1288	error = 0;
1289	switch (cmd) {
1290	case SIOCSIFFLAGS:
1291		FFEC_LOCK(sc);
1292		if (ifp->if_flags & IFF_UP) {
1293			if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1294				if ((ifp->if_flags ^ sc->if_flags) &
1295				    (IFF_PROMISC | IFF_ALLMULTI))
1296					ffec_setup_rxfilter(sc);
1297			} else {
1298				if (!sc->is_detaching)
1299					ffec_init_locked(sc);
1300			}
1301		} else {
1302			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1303				ffec_stop_locked(sc);
1304		}
1305		sc->if_flags = ifp->if_flags;
1306		FFEC_UNLOCK(sc);
1307		break;
1308
1309	case SIOCADDMULTI:
1310	case SIOCDELMULTI:
1311		if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1312			FFEC_LOCK(sc);
1313			ffec_setup_rxfilter(sc);
1314			FFEC_UNLOCK(sc);
1315		}
1316		break;
1317
1318	case SIOCSIFMEDIA:
1319	case SIOCGIFMEDIA:
1320		mii = sc->mii_softc;
1321		error = ifmedia_ioctl(ifp, ifr, &mii->mii_media, cmd);
1322		break;
1323
1324	case SIOCSIFCAP:
1325		mask = ifp->if_capenable ^ ifr->ifr_reqcap;
1326		if (mask & IFCAP_VLAN_MTU) {
1327			/* No work to do except acknowledge the change took. */
1328			ifp->if_capenable ^= IFCAP_VLAN_MTU;
1329		}
1330		break;
1331
1332	default:
1333		error = ether_ioctl(ifp, cmd, data);
1334		break;
1335	}
1336
1337	return (error);
1338}
1339
1340static int
1341ffec_detach(device_t dev)
1342{
1343	struct ffec_softc *sc;
1344	bus_dmamap_t map;
1345	int idx;
1346
1347	/*
1348	 * NB: This function can be called internally to unwind a failure to
1349	 * attach. Make sure a resource got allocated/created before destroying.
1350	 */
1351
1352	sc = device_get_softc(dev);
1353
1354	if (sc->is_attached) {
1355		FFEC_LOCK(sc);
1356		sc->is_detaching = true;
1357		ffec_stop_locked(sc);
1358		FFEC_UNLOCK(sc);
1359		callout_drain(&sc->ffec_callout);
1360		ether_ifdetach(sc->ifp);
1361	}
1362
1363	/* XXX no miibus detach? */
1364
1365	/* Clean up RX DMA resources and free mbufs. */
1366	for (idx = 0; idx < RX_DESC_COUNT; ++idx) {
1367		if ((map = sc->rxbuf_map[idx].map) != NULL) {
1368			bus_dmamap_unload(sc->rxbuf_tag, map);
1369			bus_dmamap_destroy(sc->rxbuf_tag, map);
1370			m_freem(sc->rxbuf_map[idx].mbuf);
1371		}
1372	}
1373	if (sc->rxbuf_tag != NULL)
1374		bus_dma_tag_destroy(sc->rxbuf_tag);
1375	if (sc->rxdesc_map != NULL) {
1376		bus_dmamap_unload(sc->rxdesc_tag, sc->rxdesc_map);
1377		bus_dmamap_destroy(sc->rxdesc_tag, sc->rxdesc_map);
1378	}
1379	if (sc->rxdesc_tag != NULL)
1380	bus_dma_tag_destroy(sc->rxdesc_tag);
1381
1382	/* Clean up TX DMA resources. */
1383	for (idx = 0; idx < TX_DESC_COUNT; ++idx) {
1384		if ((map = sc->txbuf_map[idx].map) != NULL) {
1385			/* TX maps are already unloaded. */
1386			bus_dmamap_destroy(sc->txbuf_tag, map);
1387		}
1388	}
1389	if (sc->txbuf_tag != NULL)
1390		bus_dma_tag_destroy(sc->txbuf_tag);
1391	if (sc->txdesc_map != NULL) {
1392		bus_dmamap_unload(sc->txdesc_tag, sc->txdesc_map);
1393		bus_dmamap_destroy(sc->txdesc_tag, sc->txdesc_map);
1394	}
1395	if (sc->txdesc_tag != NULL)
1396	bus_dma_tag_destroy(sc->txdesc_tag);
1397
1398	/* Release bus resources. */
1399	if (sc->intr_cookie)
1400		bus_teardown_intr(dev, sc->irq_res, sc->intr_cookie);
1401
1402	if (sc->irq_res != NULL)
1403		bus_release_resource(dev, SYS_RES_IRQ, 0, sc->irq_res);
1404
1405	if (sc->mem_res != NULL)
1406		bus_release_resource(dev, SYS_RES_MEMORY, 0, sc->mem_res);
1407
1408	FFEC_LOCK_DESTROY(sc);
1409	return (0);
1410}
1411
1412static int
1413ffec_attach(device_t dev)
1414{
1415	struct ffec_softc *sc;
1416	struct ifnet *ifp = NULL;
1417	struct mbuf *m;
1418	phandle_t ofw_node;
1419	int error, rid;
1420	uint8_t eaddr[ETHER_ADDR_LEN];
1421	char phy_conn_name[32];
1422	uint32_t idx, mscr;
1423
1424	sc = device_get_softc(dev);
1425	sc->dev = dev;
1426
1427	FFEC_LOCK_INIT(sc);
1428
1429	/*
1430	 * There are differences in the implementation and features of the FEC
1431	 * hardware on different SoCs, so figure out what type we are.
1432	 */
1433	sc->fectype = ofw_bus_search_compatible(dev, compat_data)->ocd_data;
1434
1435	/*
1436	 * We have to be told what kind of electrical connection exists between
1437	 * the MAC and PHY or we can't operate correctly.
1438	 */
1439	if ((ofw_node = ofw_bus_get_node(dev)) == -1) {
1440		device_printf(dev, "Impossible: Can't find ofw bus node\n");
1441		error = ENXIO;
1442		goto out;
1443	}
1444	if (OF_searchprop(ofw_node, "phy-mode",
1445	    phy_conn_name, sizeof(phy_conn_name)) != -1) {
1446		if (strcasecmp(phy_conn_name, "mii") == 0)
1447			sc->phy_conn_type = PHY_CONN_MII;
1448		else if (strcasecmp(phy_conn_name, "rmii") == 0)
1449			sc->phy_conn_type = PHY_CONN_RMII;
1450		else if (strcasecmp(phy_conn_name, "rgmii") == 0)
1451			sc->phy_conn_type = PHY_CONN_RGMII;
1452	}
1453	if (sc->phy_conn_type == PHY_CONN_UNKNOWN) {
1454		device_printf(sc->dev, "No valid 'phy-mode' "
1455		    "property found in FDT data for device.\n");
1456		error = ENOATTR;
1457		goto out;
1458	}
1459
1460	callout_init_mtx(&sc->ffec_callout, &sc->mtx, 0);
1461
1462	/* Allocate bus resources for accessing the hardware. */
1463	rid = 0;
1464	sc->mem_res = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid,
1465	    RF_ACTIVE);
1466	if (sc->mem_res == NULL) {
1467		device_printf(dev, "could not allocate memory resources.\n");
1468		error = ENOMEM;
1469		goto out;
1470	}
1471	rid = 0;
1472	sc->irq_res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
1473	    RF_ACTIVE);
1474	if (sc->irq_res == NULL) {
1475		device_printf(dev, "could not allocate interrupt resources.\n");
1476		error = ENOMEM;
1477		goto out;
1478	}
1479
1480	/*
1481	 * Set up TX descriptor ring, descriptors, and dma maps.
1482	 */
1483	error = bus_dma_tag_create(
1484	    bus_get_dma_tag(dev),	/* Parent tag. */
1485	    FEC_DESC_RING_ALIGN, 0,	/* alignment, boundary */
1486	    BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
1487	    BUS_SPACE_MAXADDR,		/* highaddr */
1488	    NULL, NULL,			/* filter, filterarg */
1489	    TX_DESC_SIZE, 1, 		/* maxsize, nsegments */
1490	    TX_DESC_SIZE,		/* maxsegsize */
1491	    0,				/* flags */
1492	    NULL, NULL,			/* lockfunc, lockarg */
1493	    &sc->txdesc_tag);
1494	if (error != 0) {
1495		device_printf(sc->dev,
1496		    "could not create TX ring DMA tag.\n");
1497		goto out;
1498	}
1499
1500	error = bus_dmamem_alloc(sc->txdesc_tag, (void**)&sc->txdesc_ring,
1501	    BUS_DMA_COHERENT | BUS_DMA_WAITOK | BUS_DMA_ZERO, &sc->txdesc_map);
1502	if (error != 0) {
1503		device_printf(sc->dev,
1504		    "could not allocate TX descriptor ring.\n");
1505		goto out;
1506	}
1507
1508	error = bus_dmamap_load(sc->txdesc_tag, sc->txdesc_map, sc->txdesc_ring,
1509	    TX_DESC_SIZE, ffec_get1paddr, &sc->txdesc_ring_paddr, 0);
1510	if (error != 0) {
1511		device_printf(sc->dev,
1512		    "could not load TX descriptor ring map.\n");
1513		goto out;
1514	}
1515
1516	error = bus_dma_tag_create(
1517	    bus_get_dma_tag(dev),	/* Parent tag. */
1518	    FEC_TXBUF_ALIGN, 0,		/* alignment, boundary */
1519	    BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
1520	    BUS_SPACE_MAXADDR,		/* highaddr */
1521	    NULL, NULL,			/* filter, filterarg */
1522	    MCLBYTES, 1, 		/* maxsize, nsegments */
1523	    MCLBYTES,			/* maxsegsize */
1524	    0,				/* flags */
1525	    NULL, NULL,			/* lockfunc, lockarg */
1526	    &sc->txbuf_tag);
1527	if (error != 0) {
1528		device_printf(sc->dev,
1529		    "could not create TX ring DMA tag.\n");
1530		goto out;
1531	}
1532
1533	for (idx = 0; idx < TX_DESC_COUNT; ++idx) {
1534		error = bus_dmamap_create(sc->txbuf_tag, 0,
1535		    &sc->txbuf_map[idx].map);
1536		if (error != 0) {
1537			device_printf(sc->dev,
1538			    "could not create TX buffer DMA map.\n");
1539			goto out;
1540		}
1541		ffec_setup_txdesc(sc, idx, 0, 0);
1542	}
1543
1544	/*
1545	 * Set up RX descriptor ring, descriptors, dma maps, and mbufs.
1546	 */
1547	error = bus_dma_tag_create(
1548	    bus_get_dma_tag(dev),	/* Parent tag. */
1549	    FEC_DESC_RING_ALIGN, 0,	/* alignment, boundary */
1550	    BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
1551	    BUS_SPACE_MAXADDR,		/* highaddr */
1552	    NULL, NULL,			/* filter, filterarg */
1553	    RX_DESC_SIZE, 1, 		/* maxsize, nsegments */
1554	    RX_DESC_SIZE,		/* maxsegsize */
1555	    0,				/* flags */
1556	    NULL, NULL,			/* lockfunc, lockarg */
1557	    &sc->rxdesc_tag);
1558	if (error != 0) {
1559		device_printf(sc->dev,
1560		    "could not create RX ring DMA tag.\n");
1561		goto out;
1562	}
1563
1564	error = bus_dmamem_alloc(sc->rxdesc_tag, (void **)&sc->rxdesc_ring,
1565	    BUS_DMA_COHERENT | BUS_DMA_WAITOK | BUS_DMA_ZERO, &sc->rxdesc_map);
1566	if (error != 0) {
1567		device_printf(sc->dev,
1568		    "could not allocate RX descriptor ring.\n");
1569		goto out;
1570	}
1571
1572	error = bus_dmamap_load(sc->rxdesc_tag, sc->rxdesc_map, sc->rxdesc_ring,
1573	    RX_DESC_SIZE, ffec_get1paddr, &sc->rxdesc_ring_paddr, 0);
1574	if (error != 0) {
1575		device_printf(sc->dev,
1576		    "could not load RX descriptor ring map.\n");
1577		goto out;
1578	}
1579
1580	error = bus_dma_tag_create(
1581	    bus_get_dma_tag(dev),	/* Parent tag. */
1582	    1, 0,			/* alignment, boundary */
1583	    BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
1584	    BUS_SPACE_MAXADDR,		/* highaddr */
1585	    NULL, NULL,			/* filter, filterarg */
1586	    MCLBYTES, 1, 		/* maxsize, nsegments */
1587	    MCLBYTES,			/* maxsegsize */
1588	    0,				/* flags */
1589	    NULL, NULL,			/* lockfunc, lockarg */
1590	    &sc->rxbuf_tag);
1591	if (error != 0) {
1592		device_printf(sc->dev,
1593		    "could not create RX buf DMA tag.\n");
1594		goto out;
1595	}
1596
1597	for (idx = 0; idx < RX_DESC_COUNT; ++idx) {
1598		error = bus_dmamap_create(sc->rxbuf_tag, 0,
1599		    &sc->rxbuf_map[idx].map);
1600		if (error != 0) {
1601			device_printf(sc->dev,
1602			    "could not create RX buffer DMA map.\n");
1603			goto out;
1604		}
1605		if ((m = ffec_alloc_mbufcl(sc)) == NULL) {
1606			device_printf(dev, "Could not alloc mbuf\n");
1607			error = ENOMEM;
1608			goto out;
1609		}
1610		if ((error = ffec_setup_rxbuf(sc, idx, m)) != 0) {
1611			device_printf(sc->dev,
1612			    "could not create new RX buffer.\n");
1613			goto out;
1614		}
1615	}
1616
1617	/* Try to get the MAC address from the hardware before resetting it. */
1618	ffec_get_hwaddr(sc, eaddr);
1619
1620	/* Reset the hardware.  Disables all interrupts. */
1621	WR4(sc, FEC_ECR_REG, FEC_ECR_RESET);
1622
1623	/* Setup interrupt handler. */
1624	error = bus_setup_intr(dev, sc->irq_res, INTR_TYPE_NET | INTR_MPSAFE,
1625	    NULL, ffec_intr, sc, &sc->intr_cookie);
1626	if (error != 0) {
1627		device_printf(dev, "could not setup interrupt handler.\n");
1628		goto out;
1629	}
1630
1631	/*
1632	 * Set up the PHY control register.
1633	 *
1634	 * Speed formula for ENET is md_clock = mac_clock / ((N + 1) * 2).
1635	 * Speed formula for FEC is  md_clock = mac_clock / (N * 2)
1636	 *
1637	 * XXX - Revisit this...
1638	 *
1639	 * For a Wandboard imx6 (ENET) I was originally using 4, but the uboot
1640	 * code uses 10.  Both values seem to work, but I suspect many modern
1641	 * PHY parts can do mdio at speeds far above the standard 2.5 MHz.
1642	 *
1643	 * Different imx manuals use confusingly different terminology (things
1644	 * like "system clock" and "internal module clock") with examples that
1645	 * use frequencies that have nothing to do with ethernet, giving the
1646	 * vague impression that maybe the clock in question is the periphclock
1647	 * or something.  In fact, on an imx53 development board (FEC),
1648	 * measuring the mdio clock at the pin on the PHY and playing with
1649	 * various divisors showed that the root speed was 66 MHz (clk_ipg_root
1650	 * aka periphclock) and 13 was the right divisor.
1651	 *
1652	 * All in all, it seems likely that 13 is a safe divisor for now,
1653	 * because if we really do need to base it on the peripheral clock
1654	 * speed, then we need a platform-independant get-clock-freq API.
1655	 */
1656	mscr = 13 << FEC_MSCR_MII_SPEED_SHIFT;
1657	if (OF_hasprop(ofw_node, "phy-disable-preamble")) {
1658		mscr |= FEC_MSCR_DIS_PRE;
1659		if (bootverbose)
1660			device_printf(dev, "PHY preamble disabled\n");
1661	}
1662	WR4(sc, FEC_MSCR_REG, mscr);
1663
1664	/* Set up the ethernet interface. */
1665	sc->ifp = ifp = if_alloc(IFT_ETHER);
1666
1667	ifp->if_softc = sc;
1668	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
1669	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
1670	ifp->if_capabilities = IFCAP_VLAN_MTU;
1671	ifp->if_capenable = ifp->if_capabilities;
1672	ifp->if_start = ffec_txstart;
1673	ifp->if_ioctl = ffec_ioctl;
1674	ifp->if_init = ffec_init;
1675	IFQ_SET_MAXLEN(&ifp->if_snd, TX_DESC_COUNT - 1);
1676	ifp->if_snd.ifq_drv_maxlen = TX_DESC_COUNT - 1;
1677	IFQ_SET_READY(&ifp->if_snd);
1678	ifp->if_data.ifi_hdrlen = sizeof(struct ether_vlan_header);
1679
1680#if 0 /* XXX The hardware keeps stats we could use for these. */
1681	ifp->if_linkmib = &sc->mibdata;
1682	ifp->if_linkmiblen = sizeof(sc->mibdata);
1683#endif
1684
1685	/* Set up the miigasket hardware (if any). */
1686	ffec_miigasket_setup(sc);
1687
1688	/* Attach the mii driver. */
1689	error = mii_attach(dev, &sc->miibus, ifp, ffec_media_change,
1690	    ffec_media_status, BMSR_DEFCAPMASK, MII_PHY_ANY, MII_OFFSET_ANY,
1691	    (sc->fectype & FECTYPE_MVF) ? MIIF_FORCEANEG : 0);
1692	if (error != 0) {
1693		device_printf(dev, "PHY attach failed\n");
1694		goto out;
1695	}
1696	sc->mii_softc = device_get_softc(sc->miibus);
1697
1698	/* All ready to run, attach the ethernet interface. */
1699	ether_ifattach(ifp, eaddr);
1700	sc->is_attached = true;
1701
1702	error = 0;
1703out:
1704
1705	if (error != 0)
1706		ffec_detach(dev);
1707
1708	return (error);
1709}
1710
1711static int
1712ffec_probe(device_t dev)
1713{
1714	uintptr_t fectype;
1715
1716	if (!ofw_bus_status_okay(dev))
1717		return (ENXIO);
1718
1719	fectype = ofw_bus_search_compatible(dev, compat_data)->ocd_data;
1720	if (fectype == FECTYPE_NONE)
1721		return (ENXIO);
1722
1723	device_set_desc(dev, (fectype & FECFLAG_GBE) ?
1724	    "Freescale Gigabit Ethernet Controller" :
1725	    "Freescale Fast Ethernet Controller");
1726
1727	return (BUS_PROBE_DEFAULT);
1728}
1729
1730
1731static device_method_t ffec_methods[] = {
1732	/* Device interface. */
1733	DEVMETHOD(device_probe,		ffec_probe),
1734	DEVMETHOD(device_attach,	ffec_attach),
1735	DEVMETHOD(device_detach,	ffec_detach),
1736
1737/*
1738	DEVMETHOD(device_shutdown,	ffec_shutdown),
1739	DEVMETHOD(device_suspend,	ffec_suspend),
1740	DEVMETHOD(device_resume,	ffec_resume),
1741*/
1742
1743	/* MII interface. */
1744	DEVMETHOD(miibus_readreg,	ffec_miibus_readreg),
1745	DEVMETHOD(miibus_writereg,	ffec_miibus_writereg),
1746	DEVMETHOD(miibus_statchg,	ffec_miibus_statchg),
1747
1748	DEVMETHOD_END
1749};
1750
1751static driver_t ffec_driver = {
1752	"ffec",
1753	ffec_methods,
1754	sizeof(struct ffec_softc)
1755};
1756
1757static devclass_t ffec_devclass;
1758
1759DRIVER_MODULE(ffec, simplebus, ffec_driver, ffec_devclass, 0, 0);
1760DRIVER_MODULE(miibus, ffec, miibus_driver, miibus_devclass, 0, 0);
1761
1762MODULE_DEPEND(ffec, ether, 1, 1, 1);
1763MODULE_DEPEND(ffec, miibus, 1, 1, 1);
1764