source: rtems-libbsd/freebsd/sys/dev/ffec/if_ffec.c @ 9c34735

55-freebsd-126-freebsd-12
Last change on this file since 9c34735 was 9c34735, checked in by Sebastian Huber <sebastian.huber@…>, on 09/27/17 at 07:38:28

ffec: Use explicit cache synchronization

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