]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/dwc/if_dwc.c
if_dwc: Use if_ function where appropriate
[FreeBSD/FreeBSD.git] / sys / dev / dwc / if_dwc.c
1 /*-
2  * Copyright (c) 2014 Ruslan Bukin <br@bsdpad.com>
3  * All rights reserved.
4  *
5  * This software was developed by SRI International and the University of
6  * Cambridge Computer Laboratory under DARPA/AFRL contract (FA8750-10-C-0237)
7  * ("CTSRD"), as part of the DARPA CRASH research programme.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  */
30
31 /*
32  * Ethernet media access controller (EMAC)
33  * Chapter 17, Altera Cyclone V Device Handbook (CV-5V2 2014.07.22)
34  *
35  * EMAC is an instance of the Synopsys DesignWare 3504-0
36  * Universal 10/100/1000 Ethernet MAC (DWC_gmac).
37  */
38
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
41
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/bus.h>
45 #include <sys/gpio.h>
46 #include <sys/kernel.h>
47 #include <sys/lock.h>
48 #include <sys/malloc.h>
49 #include <sys/mbuf.h>
50 #include <sys/module.h>
51 #include <sys/mutex.h>
52 #include <sys/rman.h>
53 #include <sys/socket.h>
54 #include <sys/sockio.h>
55
56 #include <net/bpf.h>
57 #include <net/if.h>
58 #include <net/ethernet.h>
59 #include <net/if_dl.h>
60 #include <net/if_media.h>
61 #include <net/if_types.h>
62 #include <net/if_var.h>
63
64 #include <machine/bus.h>
65
66 #include <dev/dwc/if_dwc.h>
67 #include <dev/dwc/if_dwcvar.h>
68 #include <dev/mii/mii.h>
69 #include <dev/mii/miivar.h>
70 #include <dev/ofw/ofw_bus.h>
71 #include <dev/ofw/ofw_bus_subr.h>
72
73 #ifdef EXT_RESOURCES
74 #include <dev/extres/clk/clk.h>
75 #include <dev/extres/hwreset/hwreset.h>
76 #endif
77
78 #include "if_dwc_if.h"
79 #include "gpio_if.h"
80 #include "miibus_if.h"
81
82 #define READ4(_sc, _reg) \
83         bus_read_4((_sc)->res[0], _reg)
84 #define WRITE4(_sc, _reg, _val) \
85         bus_write_4((_sc)->res[0], _reg, _val)
86
87 #define MAC_RESET_TIMEOUT       100
88 #define WATCHDOG_TIMEOUT_SECS   5
89 #define STATS_HARVEST_INTERVAL  2
90
91 #define DWC_LOCK(sc)                    mtx_lock(&(sc)->mtx)
92 #define DWC_UNLOCK(sc)                  mtx_unlock(&(sc)->mtx)
93 #define DWC_ASSERT_LOCKED(sc)           mtx_assert(&(sc)->mtx, MA_OWNED)
94 #define DWC_ASSERT_UNLOCKED(sc)         mtx_assert(&(sc)->mtx, MA_NOTOWNED)
95
96 /* TX descriptors - TDESC0 is almost unified */
97 #define TDESC0_OWN              (1U << 31)
98 #define TDESC0_IHE              (1U << 16)      /* IP Header Error */
99 #define TDESC0_ES               (1U << 15)      /* Error Summary */
100 #define TDESC0_JT               (1U << 14)      /* Jabber Timeout */
101 #define TDESC0_FF               (1U << 13)      /* Frame Flushed */
102 #define TDESC0_PCE              (1U << 12)      /* Payload Checksum Error */
103 #define TDESC0_LOC              (1U << 11)      /* Loss of Carrier */
104 #define TDESC0_NC               (1U << 10)      /* No Carrier */
105 #define TDESC0_LC               (1U <<  9)      /* Late Collision */
106 #define TDESC0_EC               (1U <<  8)      /* Excessive Collision */
107 #define TDESC0_VF               (1U <<  7)      /* VLAN Frame */
108 #define TDESC0_CC_MASK          0xf
109 #define TDESC0_CC_SHIFT         3               /* Collision Count */
110 #define TDESC0_ED               (1U <<  2)      /* Excessive Deferral */
111 #define TDESC0_UF               (1U <<  1)      /* Underflow Error */
112 #define TDESC0_DB               (1U <<  0)      /* Deferred Bit */
113 /* TX descriptors - TDESC0 extended format only */
114 #define ETDESC0_IC              (1U << 30)      /* Interrupt on Completion */
115 #define ETDESC0_LS              (1U << 29)      /* Last Segment */
116 #define ETDESC0_FS              (1U << 28)      /* First Segment */
117 #define ETDESC0_DC              (1U << 27)      /* Disable CRC */
118 #define ETDESC0_DP              (1U << 26)      /* Disable Padding */
119 #define ETDESC0_CIC_NONE        (0U << 22)      /* Checksum Insertion Control */
120 #define ETDESC0_CIC_HDR         (1U << 22)
121 #define ETDESC0_CIC_SEG         (2U << 22)
122 #define ETDESC0_CIC_FULL        (3U << 22)
123 #define ETDESC0_TER             (1U << 21)      /* Transmit End of Ring */
124 #define ETDESC0_TCH             (1U << 20)      /* Second Address Chained */
125
126 /* TX descriptors - TDESC1 normal format */
127 #define NTDESC1_IC              (1U << 31)      /* Interrupt on Completion */
128 #define NTDESC1_LS              (1U << 30)      /* Last Segment */
129 #define NTDESC1_FS              (1U << 29)      /* First Segment */
130 #define NTDESC1_CIC_NONE        (0U << 27)      /* Checksum Insertion Control */
131 #define NTDESC1_CIC_HDR         (1U << 27)
132 #define NTDESC1_CIC_SEG         (2U << 27)
133 #define NTDESC1_CIC_FULL        (3U << 27)
134 #define NTDESC1_DC              (1U << 26)      /* Disable CRC */
135 #define NTDESC1_TER             (1U << 25)      /* Transmit End of Ring */
136 #define NTDESC1_TCH             (1U << 24)      /* Second Address Chained */
137 /* TX descriptors - TDESC1 extended format */
138 #define ETDESC1_DP              (1U << 23)      /* Disable Padding */
139 #define ETDESC1_TBS2_MASK       0x7ff
140 #define ETDESC1_TBS2_SHIFT      11              /* Receive Buffer 2 Size */
141 #define ETDESC1_TBS1_MASK       0x7ff
142 #define ETDESC1_TBS1_SHIFT      0               /* Receive Buffer 1 Size */
143
144 /* RX descriptor - RDESC0 is unified */
145 #define RDESC0_OWN              (1U << 31)
146 #define RDESC0_AFM              (1U << 30)      /* Dest. Address Filter Fail */
147 #define RDESC0_FL_MASK          0x3fff
148 #define RDESC0_FL_SHIFT         16              /* Frame Length */
149 #define RDESC0_ES               (1U << 15)      /* Error Summary */
150 #define RDESC0_DE               (1U << 14)      /* Descriptor Error */
151 #define RDESC0_SAF              (1U << 13)      /* Source Address Filter Fail */
152 #define RDESC0_LE               (1U << 12)      /* Length Error */
153 #define RDESC0_OE               (1U << 11)      /* Overflow Error */
154 #define RDESC0_VLAN             (1U << 10)      /* VLAN Tag */
155 #define RDESC0_FS               (1U <<  9)      /* First Descriptor */
156 #define RDESC0_LS               (1U <<  8)      /* Last Descriptor */
157 #define RDESC0_ICE              (1U <<  7)      /* IPC Checksum Error */
158 #define RDESC0_GF               (1U <<  7)      /* Giant Frame */
159 #define RDESC0_LC               (1U <<  6)      /* Late Collision */
160 #define RDESC0_FT               (1U <<  5)      /* Frame Type */
161 #define RDESC0_RWT              (1U <<  4)      /* Receive Watchdog Timeout */
162 #define RDESC0_RE               (1U <<  3)      /* Receive Error */
163 #define RDESC0_DBE              (1U <<  2)      /* Dribble Bit Error */
164 #define RDESC0_CE               (1U <<  1)      /* CRC Error */
165 #define RDESC0_PCE              (1U <<  0)      /* Payload Checksum Error */
166 #define RDESC0_RXMA             (1U <<  0)      /* Rx MAC Address */
167
168 /* RX descriptors - RDESC1 normal format */
169 #define NRDESC1_DIC             (1U << 31)      /* Disable Intr on Completion */
170 #define NRDESC1_RER             (1U << 25)      /* Receive End of Ring */
171 #define NRDESC1_RCH             (1U << 24)      /* Second Address Chained */
172 #define NRDESC1_RBS2_MASK       0x7ff
173 #define NRDESC1_RBS2_SHIFT      11              /* Receive Buffer 2 Size */
174 #define NRDESC1_RBS1_MASK       0x7ff
175 #define NRDESC1_RBS1_SHIFT      0               /* Receive Buffer 1 Size */
176
177 /* RX descriptors - RDESC1 enhanced format */
178 #define ERDESC1_DIC             (1U << 31)      /* Disable Intr on Completion */
179 #define ERDESC1_RBS2_MASK       0x7ffff
180 #define ERDESC1_RBS2_SHIFT      16              /* Receive Buffer 2 Size */
181 #define ERDESC1_RER             (1U << 15)      /* Receive End of Ring */
182 #define ERDESC1_RCH             (1U << 14)      /* Second Address Chained */
183 #define ERDESC1_RBS1_MASK       0x7ffff
184 #define ERDESC1_RBS1_SHIFT      0               /* Receive Buffer 1 Size */
185
186 /*
187  * A hardware buffer descriptor.  Rx and Tx buffers have the same descriptor
188  * layout, but the bits in the fields have different meanings.
189  */
190 struct dwc_hwdesc
191 {
192         uint32_t desc0;
193         uint32_t desc1;
194         uint32_t addr1;         /* ptr to first buffer data */
195         uint32_t addr2;         /* ptr to next descriptor / second buffer data*/
196 };
197
198
199 struct dwc_hash_maddr_ctx {
200         struct dwc_softc *sc;
201         uint32_t hash[8];
202 };
203
204 /*
205  * The hardware imposes alignment restrictions on various objects involved in
206  * DMA transfers.  These values are expressed in bytes (not bits).
207  */
208 #define DWC_DESC_RING_ALIGN     2048
209
210 static struct resource_spec dwc_spec[] = {
211         { SYS_RES_MEMORY,       0,      RF_ACTIVE },
212         { SYS_RES_IRQ,          0,      RF_ACTIVE },
213         { -1, 0 }
214 };
215
216 static void dwc_txfinish_locked(struct dwc_softc *sc);
217 static void dwc_rxfinish_locked(struct dwc_softc *sc);
218 static void dwc_stop_locked(struct dwc_softc *sc);
219 static void dwc_setup_rxfilter(struct dwc_softc *sc);
220 static void dwc_setup_core(struct dwc_softc *sc);
221 static void dwc_enable_mac(struct dwc_softc *sc, bool enable);
222 static void dwc_init_dma(struct dwc_softc *sc);
223 static void dwc_stop_dma(struct dwc_softc *sc);
224
225 static void dwc_tick(void *arg);
226
227 /*
228  * MIIBUS functions
229  */
230
231 static int
232 dwc_miibus_read_reg(device_t dev, int phy, int reg)
233 {
234         struct dwc_softc *sc;
235         uint16_t mii;
236         size_t cnt;
237         int rv = 0;
238
239         sc = device_get_softc(dev);
240
241         mii = ((phy & GMII_ADDRESS_PA_MASK) << GMII_ADDRESS_PA_SHIFT)
242             | ((reg & GMII_ADDRESS_GR_MASK) << GMII_ADDRESS_GR_SHIFT)
243             | (sc->mii_clk << GMII_ADDRESS_CR_SHIFT)
244             | GMII_ADDRESS_GB; /* Busy flag */
245
246         WRITE4(sc, GMII_ADDRESS, mii);
247
248         for (cnt = 0; cnt < 1000; cnt++) {
249                 if (!(READ4(sc, GMII_ADDRESS) & GMII_ADDRESS_GB)) {
250                         rv = READ4(sc, GMII_DATA);
251                         break;
252                 }
253                 DELAY(10);
254         }
255
256         return rv;
257 }
258
259 static int
260 dwc_miibus_write_reg(device_t dev, int phy, int reg, int val)
261 {
262         struct dwc_softc *sc;
263         uint16_t mii;
264         size_t cnt;
265
266         sc = device_get_softc(dev);
267
268         mii = ((phy & GMII_ADDRESS_PA_MASK) << GMII_ADDRESS_PA_SHIFT)
269             | ((reg & GMII_ADDRESS_GR_MASK) << GMII_ADDRESS_GR_SHIFT)
270             | (sc->mii_clk << GMII_ADDRESS_CR_SHIFT)
271             | GMII_ADDRESS_GB | GMII_ADDRESS_GW;
272
273         WRITE4(sc, GMII_DATA, val);
274         WRITE4(sc, GMII_ADDRESS, mii);
275
276         for (cnt = 0; cnt < 1000; cnt++) {
277                 if (!(READ4(sc, GMII_ADDRESS) & GMII_ADDRESS_GB)) {
278                         break;
279                 }
280                 DELAY(10);
281         }
282
283         return (0);
284 }
285
286 static void
287 dwc_miibus_statchg(device_t dev)
288 {
289         struct dwc_softc *sc;
290         struct mii_data *mii;
291         uint32_t reg;
292
293         /*
294          * Called by the MII bus driver when the PHY establishes
295          * link to set the MAC interface registers.
296          */
297
298         sc = device_get_softc(dev);
299
300         DWC_ASSERT_LOCKED(sc);
301
302         mii = sc->mii_softc;
303
304         if (mii->mii_media_status & IFM_ACTIVE)
305                 sc->link_is_up = true;
306         else
307                 sc->link_is_up = false;
308
309         reg = READ4(sc, MAC_CONFIGURATION);
310         switch (IFM_SUBTYPE(mii->mii_media_active)) {
311         case IFM_1000_T:
312         case IFM_1000_SX:
313                 reg &= ~(CONF_FES | CONF_PS);
314                 break;
315         case IFM_100_TX:
316                 reg |= (CONF_FES | CONF_PS);
317                 break;
318         case IFM_10_T:
319                 reg &= ~(CONF_FES);
320                 reg |= (CONF_PS);
321                 break;
322         case IFM_NONE:
323                 sc->link_is_up = false;
324                 return;
325         default:
326                 sc->link_is_up = false;
327                 device_printf(dev, "Unsupported media %u\n",
328                     IFM_SUBTYPE(mii->mii_media_active));
329                 return;
330         }
331         if ((IFM_OPTIONS(mii->mii_media_active) & IFM_FDX) != 0)
332                 reg |= (CONF_DM);
333         else
334                 reg &= ~(CONF_DM);
335         WRITE4(sc, MAC_CONFIGURATION, reg);
336
337         IF_DWC_SET_SPEED(dev, IFM_SUBTYPE(mii->mii_media_active));
338
339 }
340
341 /*
342  * Media functions
343  */
344
345 static void
346 dwc_media_status(struct ifnet * ifp, struct ifmediareq *ifmr)
347 {
348         struct dwc_softc *sc;
349         struct mii_data *mii;
350
351         sc = ifp->if_softc;
352         mii = sc->mii_softc;
353         DWC_LOCK(sc);
354         mii_pollstat(mii);
355         ifmr->ifm_active = mii->mii_media_active;
356         ifmr->ifm_status = mii->mii_media_status;
357         DWC_UNLOCK(sc);
358 }
359
360 static int
361 dwc_media_change_locked(struct dwc_softc *sc)
362 {
363
364         return (mii_mediachg(sc->mii_softc));
365 }
366
367 static int
368 dwc_media_change(struct ifnet * ifp)
369 {
370         struct dwc_softc *sc;
371         int error;
372
373         sc = ifp->if_softc;
374
375         DWC_LOCK(sc);
376         error = dwc_media_change_locked(sc);
377         DWC_UNLOCK(sc);
378         return (error);
379 }
380
381 /*
382  * Core functions
383  */
384
385 static const uint8_t nibbletab[] = {
386         /* 0x0 0000 -> 0000 */  0x0,
387         /* 0x1 0001 -> 1000 */  0x8,
388         /* 0x2 0010 -> 0100 */  0x4,
389         /* 0x3 0011 -> 1100 */  0xc,
390         /* 0x4 0100 -> 0010 */  0x2,
391         /* 0x5 0101 -> 1010 */  0xa,
392         /* 0x6 0110 -> 0110 */  0x6,
393         /* 0x7 0111 -> 1110 */  0xe,
394         /* 0x8 1000 -> 0001 */  0x1,
395         /* 0x9 1001 -> 1001 */  0x9,
396         /* 0xa 1010 -> 0101 */  0x5,
397         /* 0xb 1011 -> 1101 */  0xd,
398         /* 0xc 1100 -> 0011 */  0x3,
399         /* 0xd 1101 -> 1011 */  0xb,
400         /* 0xe 1110 -> 0111 */  0x7,
401         /* 0xf 1111 -> 1111 */  0xf, };
402
403 static uint8_t
404 bitreverse(uint8_t x)
405 {
406
407         return (nibbletab[x & 0xf] << 4) | nibbletab[x >> 4];
408 }
409
410 static u_int
411 dwc_hash_maddr(void *arg, struct sockaddr_dl *sdl, u_int cnt)
412 {
413         struct dwc_hash_maddr_ctx *ctx = arg;
414         uint32_t crc, hashbit, hashreg;
415         uint8_t val;
416
417         crc = ether_crc32_le(LLADDR(sdl), ETHER_ADDR_LEN);
418         /* Take lower 8 bits and reverse it */
419         val = bitreverse(~crc & 0xff);
420         if (ctx->sc->mactype != DWC_GMAC_EXT_DESC)
421                 val >>= 2; /* Only need lower 6 bits */
422         hashreg = (val >> 5);
423         hashbit = (val & 31);
424         ctx->hash[hashreg] |= (1 << hashbit);
425
426         return (1);
427 }
428
429 static void
430 dwc_setup_rxfilter(struct dwc_softc *sc)
431 {
432         struct dwc_hash_maddr_ctx ctx;
433         struct ifnet *ifp;
434         uint8_t *eaddr;
435         uint32_t ffval, hi, lo;
436         int nhash, i;
437
438         DWC_ASSERT_LOCKED(sc);
439
440         ifp = sc->ifp;
441         nhash = sc->mactype != DWC_GMAC_EXT_DESC ? 2 : 8;
442
443         /*
444          * Set the multicast (group) filter hash.
445          */
446         if ((ifp->if_flags & IFF_ALLMULTI) != 0) {
447                 ffval = (FRAME_FILTER_PM);
448                 for (i = 0; i < nhash; i++)
449                         ctx.hash[i] = ~0;
450         } else {
451                 ffval = (FRAME_FILTER_HMC);
452                 for (i = 0; i < nhash; i++)
453                         ctx.hash[i] = 0;
454                 ctx.sc = sc;
455                 if_foreach_llmaddr(ifp, dwc_hash_maddr, &ctx);
456         }
457
458         /*
459          * Set the individual address filter hash.
460          */
461         if (ifp->if_flags & IFF_PROMISC)
462                 ffval |= (FRAME_FILTER_PR);
463
464         /*
465          * Set the primary address.
466          */
467         eaddr = IF_LLADDR(ifp);
468         lo = eaddr[0] | (eaddr[1] << 8) | (eaddr[2] << 16) |
469             (eaddr[3] << 24);
470         hi = eaddr[4] | (eaddr[5] << 8);
471         WRITE4(sc, MAC_ADDRESS_LOW(0), lo);
472         WRITE4(sc, MAC_ADDRESS_HIGH(0), hi);
473         WRITE4(sc, MAC_FRAME_FILTER, ffval);
474         if (sc->mactype != DWC_GMAC_EXT_DESC) {
475                 WRITE4(sc, GMAC_MAC_HTLOW, ctx.hash[0]);
476                 WRITE4(sc, GMAC_MAC_HTHIGH, ctx.hash[1]);
477         } else {
478                 for (i = 0; i < nhash; i++)
479                         WRITE4(sc, HASH_TABLE_REG(i), ctx.hash[i]);
480         }
481 }
482
483 static void
484 dwc_setup_core(struct dwc_softc *sc)
485 {
486         uint32_t reg;
487
488         DWC_ASSERT_LOCKED(sc);
489
490         /* Enable core */
491         reg = READ4(sc, MAC_CONFIGURATION);
492         reg |= (CONF_JD | CONF_ACS | CONF_BE);
493         WRITE4(sc, MAC_CONFIGURATION, reg);
494 }
495
496 static void
497 dwc_enable_mac(struct dwc_softc *sc, bool enable)
498 {
499         uint32_t reg;
500
501         DWC_ASSERT_LOCKED(sc);
502         reg = READ4(sc, MAC_CONFIGURATION);
503         if (enable)
504                 reg |= CONF_TE | CONF_RE;
505         else
506                 reg &= ~(CONF_TE | CONF_RE);
507         WRITE4(sc, MAC_CONFIGURATION, reg);
508 }
509
510 static void
511 dwc_get_hwaddr(struct dwc_softc *sc, uint8_t *hwaddr)
512 {
513         uint32_t hi, lo, rnd;
514
515         /*
516          * Try to recover a MAC address from the running hardware. If there's
517          * something non-zero there, assume the bootloader did the right thing
518          * and just use it.
519          *
520          * Otherwise, set the address to a convenient locally assigned address,
521          * 'bsd' + random 24 low-order bits.  'b' is 0x62, which has the locally
522          * assigned bit set, and the broadcast/multicast bit clear.
523          */
524         lo = READ4(sc, MAC_ADDRESS_LOW(0));
525         hi = READ4(sc, MAC_ADDRESS_HIGH(0)) & 0xffff;
526         if ((lo != 0xffffffff) || (hi != 0xffff)) {
527                 hwaddr[0] = (lo >>  0) & 0xff;
528                 hwaddr[1] = (lo >>  8) & 0xff;
529                 hwaddr[2] = (lo >> 16) & 0xff;
530                 hwaddr[3] = (lo >> 24) & 0xff;
531                 hwaddr[4] = (hi >>  0) & 0xff;
532                 hwaddr[5] = (hi >>  8) & 0xff;
533         } else {
534                 rnd = arc4random() & 0x00ffffff;
535                 hwaddr[0] = 'b';
536                 hwaddr[1] = 's';
537                 hwaddr[2] = 'd';
538                 hwaddr[3] = rnd >> 16;
539                 hwaddr[4] = rnd >>  8;
540                 hwaddr[5] = rnd >>  0;
541         }
542 }
543
544 /*
545  * DMA functions
546  */
547
548 static void
549 dwc_init_dma(struct dwc_softc *sc)
550 {
551         uint32_t reg;
552
553         DWC_ASSERT_LOCKED(sc);
554
555         /* Initializa DMA and enable transmitters */
556         reg = READ4(sc, OPERATION_MODE);
557         reg |= (MODE_TSF | MODE_OSF | MODE_FUF);
558         reg &= ~(MODE_RSF);
559         reg |= (MODE_RTC_LEV32 << MODE_RTC_SHIFT);
560         WRITE4(sc, OPERATION_MODE, reg);
561
562         WRITE4(sc, INTERRUPT_ENABLE, INT_EN_DEFAULT);
563
564         /* Start DMA */
565         reg = READ4(sc, OPERATION_MODE);
566         reg |= (MODE_ST | MODE_SR);
567         WRITE4(sc, OPERATION_MODE, reg);
568 }
569
570 static void
571 dwc_stop_dma(struct dwc_softc *sc)
572 {
573         uint32_t reg;
574
575         DWC_ASSERT_LOCKED(sc);
576
577         /* Stop DMA TX */
578         reg = READ4(sc, OPERATION_MODE);
579         reg &= ~(MODE_ST);
580         WRITE4(sc, OPERATION_MODE, reg);
581
582         /* Flush TX */
583         reg = READ4(sc, OPERATION_MODE);
584         reg |= (MODE_FTF);
585         WRITE4(sc, OPERATION_MODE, reg);
586
587         /* Stop DMA RX */
588         reg = READ4(sc, OPERATION_MODE);
589         reg &= ~(MODE_SR);
590         WRITE4(sc, OPERATION_MODE, reg);
591 }
592
593 static inline uint32_t
594 next_rxidx(struct dwc_softc *sc, uint32_t curidx)
595 {
596
597         return ((curidx + 1) % RX_DESC_COUNT);
598 }
599
600 static inline uint32_t
601 next_txidx(struct dwc_softc *sc, uint32_t curidx)
602 {
603
604         return ((curidx + 1) % TX_DESC_COUNT);
605 }
606
607 static void
608 dwc_get1paddr(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
609 {
610
611         if (error != 0)
612                 return;
613         *(bus_addr_t *)arg = segs[0].ds_addr;
614 }
615
616 inline static void
617 dwc_setup_txdesc(struct dwc_softc *sc, int idx, bus_addr_t paddr,
618     uint32_t len)
619 {
620         uint32_t desc0, desc1;
621
622         /* Addr/len 0 means we're clearing the descriptor after xmit done. */
623         if (paddr == 0 || len == 0) {
624                 desc0 = 0;
625                 desc1 = 0;
626                 --sc->txcount;
627         } else {
628                 if (sc->mactype != DWC_GMAC_EXT_DESC) {
629                         desc0 = 0;
630                         desc1 = NTDESC1_TCH | NTDESC1_FS | NTDESC1_LS |
631                             NTDESC1_IC | len;
632                 } else {
633                         desc0 = ETDESC0_TCH | ETDESC0_FS | ETDESC0_LS |
634                             ETDESC0_IC;
635                         desc1 = len;
636                 }
637                 ++sc->txcount;
638         }
639
640         sc->txdesc_ring[idx].addr1 = (uint32_t)(paddr);
641         sc->txdesc_ring[idx].desc0 = desc0;
642         sc->txdesc_ring[idx].desc1 = desc1;
643
644         if (paddr && len) {
645                 wmb();
646                 sc->txdesc_ring[idx].desc0 |= TDESC0_OWN;
647                 wmb();
648         }
649 }
650
651 static int
652 dwc_setup_txbuf(struct dwc_softc *sc, int idx, struct mbuf **mp)
653 {
654         struct bus_dma_segment seg;
655         int error, nsegs;
656         struct mbuf * m;
657
658         if ((m = m_defrag(*mp, M_NOWAIT)) == NULL)
659                 return (ENOMEM);
660         *mp = m;
661
662         error = bus_dmamap_load_mbuf_sg(sc->txbuf_tag, sc->txbuf_map[idx].map,
663             m, &seg, &nsegs, 0);
664         if (error != 0) {
665                 return (ENOMEM);
666         }
667
668         KASSERT(nsegs == 1, ("%s: %d segments returned!", __func__, nsegs));
669
670         bus_dmamap_sync(sc->txbuf_tag, sc->txbuf_map[idx].map,
671             BUS_DMASYNC_PREWRITE);
672
673         sc->txbuf_map[idx].mbuf = m;
674
675         dwc_setup_txdesc(sc, idx, seg.ds_addr, seg.ds_len);
676
677         return (0);
678 }
679
680 inline static uint32_t
681 dwc_setup_rxdesc(struct dwc_softc *sc, int idx, bus_addr_t paddr)
682 {
683         uint32_t nidx;
684
685         sc->rxdesc_ring[idx].addr1 = (uint32_t)paddr;
686         nidx = next_rxidx(sc, idx);
687         sc->rxdesc_ring[idx].addr2 = sc->rxdesc_ring_paddr +
688             (nidx * sizeof(struct dwc_hwdesc));
689         if (sc->mactype != DWC_GMAC_EXT_DESC)
690                 sc->rxdesc_ring[idx].desc1 = NRDESC1_RCH |
691                     MIN(MCLBYTES, NRDESC1_RBS1_MASK);
692         else
693                 sc->rxdesc_ring[idx].desc1 = ERDESC1_RCH |
694                     MIN(MCLBYTES, ERDESC1_RBS1_MASK);
695
696         wmb();
697         sc->rxdesc_ring[idx].desc0 = RDESC0_OWN;
698         wmb();
699         return (nidx);
700 }
701
702 static int
703 dwc_setup_rxbuf(struct dwc_softc *sc, int idx, struct mbuf *m)
704 {
705         struct bus_dma_segment seg;
706         int error, nsegs;
707
708         m_adj(m, ETHER_ALIGN);
709
710         error = bus_dmamap_load_mbuf_sg(sc->rxbuf_tag, sc->rxbuf_map[idx].map,
711             m, &seg, &nsegs, 0);
712         if (error != 0)
713                 return (error);
714
715         KASSERT(nsegs == 1, ("%s: %d segments returned!", __func__, nsegs));
716
717         bus_dmamap_sync(sc->rxbuf_tag, sc->rxbuf_map[idx].map,
718             BUS_DMASYNC_PREREAD);
719
720         sc->rxbuf_map[idx].mbuf = m;
721         dwc_setup_rxdesc(sc, idx, seg.ds_addr);
722
723         return (0);
724 }
725
726 static struct mbuf *
727 dwc_alloc_mbufcl(struct dwc_softc *sc)
728 {
729         struct mbuf *m;
730
731         m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
732         if (m != NULL)
733                 m->m_pkthdr.len = m->m_len = m->m_ext.ext_size;
734
735         return (m);
736 }
737
738 static struct mbuf *
739 dwc_rxfinish_one(struct dwc_softc *sc, struct dwc_hwdesc *desc,
740     struct dwc_bufmap *map)
741 {
742         struct ifnet *ifp;
743         struct mbuf *m, *m0;
744         int len;
745         uint32_t rdesc0;
746
747         m = map->mbuf;
748         ifp = sc->ifp;
749         rdesc0 = desc ->desc0;
750         /* Validate descriptor. */
751         if (rdesc0 & RDESC0_ES) {
752                 /*
753                  * Errored packet. Statistic counters are updated
754                  * globally, so do nothing
755                  */
756                 return (NULL);
757         }
758
759         if ((rdesc0 & (RDESC0_FS | RDESC0_LS)) !=
760                     (RDESC0_FS | RDESC0_LS)) {
761                 /*
762                  * Something very wrong happens. The whole packet should be
763                  * recevied in one descriptr. Report problem.
764                  */
765                 device_printf(sc->dev,
766                     "%s: RX descriptor without FIRST and LAST bit set: 0x%08X",
767                     __func__, rdesc0);
768                 return (NULL);
769         }
770
771         len = (rdesc0 >> RDESC0_FL_SHIFT) & RDESC0_FL_MASK;
772         if (len < 64) {
773                 /*
774                  * Lenght is invalid, recycle old mbuf
775                  * Probably impossible case
776                  */
777                 return (NULL);
778         }
779
780         /* Allocate new buffer */
781         m0 = dwc_alloc_mbufcl(sc);
782         if (m0 == NULL) {
783                 /* no new mbuf available, recycle old */
784                 if_inc_counter(sc->ifp, IFCOUNTER_IQDROPS, 1);
785                 return (NULL);
786         }
787         /* Do dmasync for newly received packet */
788         bus_dmamap_sync(sc->rxbuf_tag, map->map, BUS_DMASYNC_POSTREAD);
789         bus_dmamap_unload(sc->rxbuf_tag, map->map);
790
791         /* Received packet is valid, process it */
792         m->m_pkthdr.rcvif = ifp;
793         m->m_pkthdr.len = len;
794         m->m_len = len;
795         if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
796
797         /* Remove trailing FCS */
798         m_adj(m, -ETHER_CRC_LEN);
799
800         DWC_UNLOCK(sc);
801         (*ifp->if_input)(ifp, m);
802         DWC_LOCK(sc);
803         return (m0);
804 }
805
806 static int
807 setup_dma(struct dwc_softc *sc)
808 {
809         struct mbuf *m;
810         int error;
811         int nidx;
812         int idx;
813
814         /*
815          * Set up TX descriptor ring, descriptors, and dma maps.
816          */
817         error = bus_dma_tag_create(
818             bus_get_dma_tag(sc->dev),   /* Parent tag. */
819             DWC_DESC_RING_ALIGN, 0,     /* alignment, boundary */
820             BUS_SPACE_MAXADDR_32BIT,    /* lowaddr */
821             BUS_SPACE_MAXADDR,          /* highaddr */
822             NULL, NULL,                 /* filter, filterarg */
823             TX_DESC_SIZE, 1,            /* maxsize, nsegments */
824             TX_DESC_SIZE,               /* maxsegsize */
825             0,                          /* flags */
826             NULL, NULL,                 /* lockfunc, lockarg */
827             &sc->txdesc_tag);
828         if (error != 0) {
829                 device_printf(sc->dev,
830                     "could not create TX ring DMA tag.\n");
831                 goto out;
832         }
833
834         error = bus_dmamem_alloc(sc->txdesc_tag, (void**)&sc->txdesc_ring,
835             BUS_DMA_COHERENT | BUS_DMA_WAITOK | BUS_DMA_ZERO,
836             &sc->txdesc_map);
837         if (error != 0) {
838                 device_printf(sc->dev,
839                     "could not allocate TX descriptor ring.\n");
840                 goto out;
841         }
842
843         error = bus_dmamap_load(sc->txdesc_tag, sc->txdesc_map,
844             sc->txdesc_ring, TX_DESC_SIZE, dwc_get1paddr,
845             &sc->txdesc_ring_paddr, 0);
846         if (error != 0) {
847                 device_printf(sc->dev,
848                     "could not load TX descriptor ring map.\n");
849                 goto out;
850         }
851
852         for (idx = 0; idx < TX_DESC_COUNT; idx++) {
853                 nidx = next_txidx(sc, idx);
854                 sc->txdesc_ring[idx].addr2 = sc->txdesc_ring_paddr +
855                     (nidx * sizeof(struct dwc_hwdesc));
856         }
857
858         error = bus_dma_tag_create(
859             bus_get_dma_tag(sc->dev),   /* Parent tag. */
860             1, 0,                       /* alignment, boundary */
861             BUS_SPACE_MAXADDR_32BIT,    /* lowaddr */
862             BUS_SPACE_MAXADDR,          /* highaddr */
863             NULL, NULL,                 /* filter, filterarg */
864             MCLBYTES, 1,                /* maxsize, nsegments */
865             MCLBYTES,                   /* maxsegsize */
866             0,                          /* flags */
867             NULL, NULL,                 /* lockfunc, lockarg */
868             &sc->txbuf_tag);
869         if (error != 0) {
870                 device_printf(sc->dev,
871                     "could not create TX ring DMA tag.\n");
872                 goto out;
873         }
874
875         for (idx = 0; idx < TX_DESC_COUNT; idx++) {
876                 error = bus_dmamap_create(sc->txbuf_tag, BUS_DMA_COHERENT,
877                     &sc->txbuf_map[idx].map);
878                 if (error != 0) {
879                         device_printf(sc->dev,
880                             "could not create TX buffer DMA map.\n");
881                         goto out;
882                 }
883                 dwc_setup_txdesc(sc, idx, 0, 0);
884         }
885
886         /*
887          * Set up RX descriptor ring, descriptors, dma maps, and mbufs.
888          */
889         error = bus_dma_tag_create(
890             bus_get_dma_tag(sc->dev),   /* Parent tag. */
891             DWC_DESC_RING_ALIGN, 0,     /* alignment, boundary */
892             BUS_SPACE_MAXADDR_32BIT,    /* lowaddr */
893             BUS_SPACE_MAXADDR,          /* highaddr */
894             NULL, NULL,                 /* filter, filterarg */
895             RX_DESC_SIZE, 1,            /* maxsize, nsegments */
896             RX_DESC_SIZE,               /* maxsegsize */
897             0,                          /* flags */
898             NULL, NULL,                 /* lockfunc, lockarg */
899             &sc->rxdesc_tag);
900         if (error != 0) {
901                 device_printf(sc->dev,
902                     "could not create RX ring DMA tag.\n");
903                 goto out;
904         }
905
906         error = bus_dmamem_alloc(sc->rxdesc_tag, (void **)&sc->rxdesc_ring,
907             BUS_DMA_COHERENT | BUS_DMA_WAITOK | BUS_DMA_ZERO,
908             &sc->rxdesc_map);
909         if (error != 0) {
910                 device_printf(sc->dev,
911                     "could not allocate RX descriptor ring.\n");
912                 goto out;
913         }
914
915         error = bus_dmamap_load(sc->rxdesc_tag, sc->rxdesc_map,
916             sc->rxdesc_ring, RX_DESC_SIZE, dwc_get1paddr,
917             &sc->rxdesc_ring_paddr, 0);
918         if (error != 0) {
919                 device_printf(sc->dev,
920                     "could not load RX descriptor ring map.\n");
921                 goto out;
922         }
923
924         error = bus_dma_tag_create(
925             bus_get_dma_tag(sc->dev),   /* Parent tag. */
926             1, 0,                       /* alignment, boundary */
927             BUS_SPACE_MAXADDR_32BIT,    /* lowaddr */
928             BUS_SPACE_MAXADDR,          /* highaddr */
929             NULL, NULL,                 /* filter, filterarg */
930             MCLBYTES, 1,                /* maxsize, nsegments */
931             MCLBYTES,                   /* maxsegsize */
932             0,                          /* flags */
933             NULL, NULL,                 /* lockfunc, lockarg */
934             &sc->rxbuf_tag);
935         if (error != 0) {
936                 device_printf(sc->dev,
937                     "could not create RX buf DMA tag.\n");
938                 goto out;
939         }
940
941         for (idx = 0; idx < RX_DESC_COUNT; idx++) {
942                 error = bus_dmamap_create(sc->rxbuf_tag, BUS_DMA_COHERENT,
943                     &sc->rxbuf_map[idx].map);
944                 if (error != 0) {
945                         device_printf(sc->dev,
946                             "could not create RX buffer DMA map.\n");
947                         goto out;
948                 }
949                 if ((m = dwc_alloc_mbufcl(sc)) == NULL) {
950                         device_printf(sc->dev, "Could not alloc mbuf\n");
951                         error = ENOMEM;
952                         goto out;
953                 }
954                 if ((error = dwc_setup_rxbuf(sc, idx, m)) != 0) {
955                         device_printf(sc->dev,
956                             "could not create new RX buffer.\n");
957                         goto out;
958                 }
959         }
960
961 out:
962         if (error != 0)
963                 return (ENXIO);
964
965         return (0);
966 }
967
968 /*
969  * if_ functions
970  */
971
972 static void
973 dwc_txstart_locked(struct dwc_softc *sc)
974 {
975         struct ifnet *ifp;
976         struct mbuf *m;
977         int enqueued;
978
979         DWC_ASSERT_LOCKED(sc);
980
981         if (!sc->link_is_up)
982                 return;
983
984         ifp = sc->ifp;
985
986         if ((if_getdrvflags(ifp) & (IFF_DRV_RUNNING|IFF_DRV_OACTIVE)) !=
987             IFF_DRV_RUNNING)
988                 return;
989
990         enqueued = 0;
991
992         for (;;) {
993                 if (sc->txcount == (TX_DESC_COUNT - 1)) {
994                         if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, 0);
995                         break;
996                 }
997
998                 m = if_dequeue(ifp);
999                 if (m == NULL)
1000                         break;
1001                 if (dwc_setup_txbuf(sc, sc->tx_idx_head, &m) != 0) {
1002                         if_sendq_prepend(ifp, m);
1003                         break;
1004                 }
1005                 if_bpfmtap(ifp, m);
1006                 sc->tx_idx_head = next_txidx(sc, sc->tx_idx_head);
1007                 ++enqueued;
1008         }
1009
1010         if (enqueued != 0) {
1011                 WRITE4(sc, TRANSMIT_POLL_DEMAND, 0x1);
1012                 sc->tx_watchdog_count = WATCHDOG_TIMEOUT_SECS;
1013         }
1014 }
1015
1016 static void
1017 dwc_txstart(struct ifnet *ifp)
1018 {
1019         struct dwc_softc *sc = ifp->if_softc;
1020
1021         DWC_LOCK(sc);
1022         dwc_txstart_locked(sc);
1023         DWC_UNLOCK(sc);
1024 }
1025
1026 static void
1027 dwc_init_locked(struct dwc_softc *sc)
1028 {
1029         struct ifnet *ifp = sc->ifp;
1030
1031         DWC_ASSERT_LOCKED(sc);
1032
1033         if (if_getdrvflags(ifp) & IFF_DRV_RUNNING)
1034                 return;
1035
1036         dwc_setup_rxfilter(sc);
1037         dwc_setup_core(sc);
1038         dwc_enable_mac(sc, true);
1039         dwc_init_dma(sc);
1040
1041         if_setdrvflagbits(ifp, IFF_DRV_RUNNING, IFF_DRV_OACTIVE);
1042
1043         /*
1044          * Call mii_mediachg() which will call back into dwc_miibus_statchg()
1045          * to set up the remaining config registers based on current media.
1046          */
1047         mii_mediachg(sc->mii_softc);
1048         callout_reset(&sc->dwc_callout, hz, dwc_tick, sc);
1049 }
1050
1051 static void
1052 dwc_init(void *if_softc)
1053 {
1054         struct dwc_softc *sc = if_softc;
1055
1056         DWC_LOCK(sc);
1057         dwc_init_locked(sc);
1058         DWC_UNLOCK(sc);
1059 }
1060
1061 static void
1062 dwc_stop_locked(struct dwc_softc *sc)
1063 {
1064         struct ifnet *ifp;
1065
1066         DWC_ASSERT_LOCKED(sc);
1067
1068         ifp = sc->ifp;
1069         if_setdrvflagbits(ifp, 0, IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
1070         sc->tx_watchdog_count = 0;
1071         sc->stats_harvest_count = 0;
1072
1073         callout_stop(&sc->dwc_callout);
1074
1075         dwc_stop_dma(sc);
1076         dwc_enable_mac(sc, false);
1077 }
1078
1079 static int
1080 dwc_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1081 {
1082         struct dwc_softc *sc;
1083         struct mii_data *mii;
1084         struct ifreq *ifr;
1085         int flags, mask, error;
1086
1087         sc = ifp->if_softc;
1088         ifr = (struct ifreq *)data;
1089
1090         error = 0;
1091         switch (cmd) {
1092         case SIOCSIFFLAGS:
1093                 DWC_LOCK(sc);
1094                 if (if_getflags(ifp) & IFF_UP) {
1095                         if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
1096                                 flags = if_getflags(ifp) ^ sc->if_flags;
1097                                 if ((flags & (IFF_PROMISC|IFF_ALLMULTI)) != 0)
1098                                         dwc_setup_rxfilter(sc);
1099                         } else {
1100                                 if (!sc->is_detaching)
1101                                         dwc_init_locked(sc);
1102                         }
1103                 } else {
1104                         if (if_getdrvflags(ifp) & IFF_DRV_RUNNING)
1105                                 dwc_stop_locked(sc);
1106                 }
1107                 sc->if_flags = if_getflags(ifp);
1108                 DWC_UNLOCK(sc);
1109                 break;
1110         case SIOCADDMULTI:
1111         case SIOCDELMULTI:
1112                 if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
1113                         DWC_LOCK(sc);
1114                         dwc_setup_rxfilter(sc);
1115                         DWC_UNLOCK(sc);
1116                 }
1117                 break;
1118         case SIOCSIFMEDIA:
1119         case SIOCGIFMEDIA:
1120                 mii = sc->mii_softc;
1121                 error = ifmedia_ioctl(ifp, ifr, &mii->mii_media, cmd);
1122                 break;
1123         case SIOCSIFCAP:
1124                 mask = ifr->ifr_reqcap ^ if_getcapenable(ifp);
1125                 if (mask & IFCAP_VLAN_MTU) {
1126                         /* No work to do except acknowledge the change took */
1127                         if_togglecapenable(ifp, IFCAP_VLAN_MTU);
1128                 }
1129                 break;
1130
1131         default:
1132                 error = ether_ioctl(ifp, cmd, data);
1133                 break;
1134         }
1135
1136         return (error);
1137 }
1138
1139 /*
1140  * Interrupts functions
1141  */
1142
1143 static void
1144 dwc_txfinish_locked(struct dwc_softc *sc)
1145 {
1146         struct dwc_bufmap *bmap;
1147         struct dwc_hwdesc *desc;
1148         struct ifnet *ifp;
1149
1150         DWC_ASSERT_LOCKED(sc);
1151
1152         ifp = sc->ifp;
1153         while (sc->tx_idx_tail != sc->tx_idx_head) {
1154                 desc = &sc->txdesc_ring[sc->tx_idx_tail];
1155                 if ((desc->desc0 & TDESC0_OWN) != 0)
1156                         break;
1157                 bmap = &sc->txbuf_map[sc->tx_idx_tail];
1158                 bus_dmamap_sync(sc->txbuf_tag, bmap->map,
1159                     BUS_DMASYNC_POSTWRITE);
1160                 bus_dmamap_unload(sc->txbuf_tag, bmap->map);
1161                 m_freem(bmap->mbuf);
1162                 bmap->mbuf = NULL;
1163                 dwc_setup_txdesc(sc, sc->tx_idx_tail, 0, 0);
1164                 sc->tx_idx_tail = next_txidx(sc, sc->tx_idx_tail);
1165                 if_setdrvflagbits(ifp, 0, IFF_DRV_OACTIVE);
1166                 if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
1167         }
1168
1169         /* If there are no buffers outstanding, muzzle the watchdog. */
1170         if (sc->tx_idx_tail == sc->tx_idx_head) {
1171                 sc->tx_watchdog_count = 0;
1172         }
1173 }
1174
1175 static void
1176 dwc_rxfinish_locked(struct dwc_softc *sc)
1177 {
1178         struct ifnet *ifp;
1179         struct mbuf *m;
1180         int error, idx;
1181         struct dwc_hwdesc *desc;
1182
1183         DWC_ASSERT_LOCKED(sc);
1184         ifp = sc->ifp;
1185         for (;;) {
1186                 idx = sc->rx_idx;
1187                 desc = sc->rxdesc_ring + idx;
1188                 if ((desc->desc0 & RDESC0_OWN) != 0)
1189                         break;
1190
1191                 m = dwc_rxfinish_one(sc, desc, sc->rxbuf_map + idx);
1192                 if (m == NULL) {
1193                         wmb();
1194                         desc->desc0 = RDESC0_OWN;
1195                         wmb();
1196                 } else {
1197                         /* We cannot create hole in RX ring */
1198                         error = dwc_setup_rxbuf(sc, idx, m);
1199                         if (error != 0)
1200                                 panic("dwc_setup_rxbuf failed:  error %d\n",
1201                                     error);
1202                 }
1203                 sc->rx_idx = next_rxidx(sc, sc->rx_idx);
1204         }
1205 }
1206
1207 static void
1208 dwc_intr(void *arg)
1209 {
1210         struct dwc_softc *sc;
1211         uint32_t reg;
1212
1213         sc = arg;
1214
1215         DWC_LOCK(sc);
1216
1217         reg = READ4(sc, INTERRUPT_STATUS);
1218         if (reg)
1219                 READ4(sc, SGMII_RGMII_SMII_CTRL_STATUS);
1220
1221         reg = READ4(sc, DMA_STATUS);
1222         if (reg & DMA_STATUS_NIS) {
1223                 if (reg & DMA_STATUS_RI)
1224                         dwc_rxfinish_locked(sc);
1225
1226                 if (reg & DMA_STATUS_TI) {
1227                         dwc_txfinish_locked(sc);
1228                         dwc_txstart_locked(sc);
1229                 }
1230         }
1231
1232         if (reg & DMA_STATUS_AIS) {
1233                 if (reg & DMA_STATUS_FBI) {
1234                         /* Fatal bus error */
1235                         device_printf(sc->dev,
1236                             "Ethernet DMA error, restarting controller.\n");
1237                         dwc_stop_locked(sc);
1238                         dwc_init_locked(sc);
1239                 }
1240         }
1241
1242         WRITE4(sc, DMA_STATUS, reg & DMA_STATUS_INTR_MASK);
1243         DWC_UNLOCK(sc);
1244 }
1245
1246 /*
1247  * Stats
1248  */
1249
1250 static void dwc_clear_stats(struct dwc_softc *sc)
1251 {
1252         uint32_t reg;
1253
1254         reg = READ4(sc, MMC_CONTROL);
1255         reg |= (MMC_CONTROL_CNTRST);
1256         WRITE4(sc, MMC_CONTROL, reg);
1257 }
1258
1259 static void
1260 dwc_harvest_stats(struct dwc_softc *sc)
1261 {
1262         struct ifnet *ifp;
1263
1264         /* We don't need to harvest too often. */
1265         if (++sc->stats_harvest_count < STATS_HARVEST_INTERVAL)
1266                 return;
1267
1268         sc->stats_harvest_count = 0;
1269         ifp = sc->ifp;
1270
1271         if_inc_counter(ifp, IFCOUNTER_IPACKETS, READ4(sc, RXFRAMECOUNT_GB));
1272         if_inc_counter(ifp, IFCOUNTER_IMCASTS, READ4(sc, RXMULTICASTFRAMES_G));
1273         if_inc_counter(ifp, IFCOUNTER_IERRORS,
1274             READ4(sc, RXOVERSIZE_G) + READ4(sc, RXUNDERSIZE_G) +
1275             READ4(sc, RXCRCERROR) + READ4(sc, RXALIGNMENTERROR) +
1276             READ4(sc, RXRUNTERROR) + READ4(sc, RXJABBERERROR) +
1277             READ4(sc, RXLENGTHERROR));
1278
1279         if_inc_counter(ifp, IFCOUNTER_OPACKETS, READ4(sc, TXFRAMECOUNT_G));
1280         if_inc_counter(ifp, IFCOUNTER_OMCASTS, READ4(sc, TXMULTICASTFRAMES_G));
1281         if_inc_counter(ifp, IFCOUNTER_OERRORS,
1282             READ4(sc, TXOVERSIZE_G) + READ4(sc, TXEXCESSDEF) +
1283             READ4(sc, TXCARRIERERR) + READ4(sc, TXUNDERFLOWERROR));
1284
1285         if_inc_counter(ifp, IFCOUNTER_COLLISIONS,
1286             READ4(sc, TXEXESSCOL) + READ4(sc, TXLATECOL));
1287
1288         dwc_clear_stats(sc);
1289 }
1290
1291 static void
1292 dwc_tick(void *arg)
1293 {
1294         struct dwc_softc *sc;
1295         struct ifnet *ifp;
1296         int link_was_up;
1297
1298         sc = arg;
1299
1300         DWC_ASSERT_LOCKED(sc);
1301
1302         ifp = sc->ifp;
1303
1304         if ((if_getdrvflags(ifp) & IFF_DRV_RUNNING) == 0)
1305             return;
1306
1307         /*
1308          * Typical tx watchdog.  If this fires it indicates that we enqueued
1309          * packets for output and never got a txdone interrupt for them.  Maybe
1310          * it's a missed interrupt somehow, just pretend we got one.
1311          */
1312         if (sc->tx_watchdog_count > 0) {
1313                 if (--sc->tx_watchdog_count == 0) {
1314                         dwc_txfinish_locked(sc);
1315                 }
1316         }
1317
1318         /* Gather stats from hardware counters. */
1319         dwc_harvest_stats(sc);
1320
1321         /* Check the media status. */
1322         link_was_up = sc->link_is_up;
1323         mii_tick(sc->mii_softc);
1324         if (sc->link_is_up && !link_was_up)
1325                 dwc_txstart_locked(sc);
1326
1327         /* Schedule another check one second from now. */
1328         callout_reset(&sc->dwc_callout, hz, dwc_tick, sc);
1329 }
1330
1331 /*
1332  * Probe/Attach functions
1333  */
1334
1335 #define GPIO_ACTIVE_LOW 1
1336
1337 static int
1338 dwc_reset(device_t dev)
1339 {
1340         pcell_t gpio_prop[4];
1341         pcell_t delay_prop[3];
1342         phandle_t node, gpio_node;
1343         device_t gpio;
1344         uint32_t pin, flags;
1345         uint32_t pin_value;
1346
1347         node = ofw_bus_get_node(dev);
1348         if (OF_getencprop(node, "snps,reset-gpio",
1349             gpio_prop, sizeof(gpio_prop)) <= 0)
1350                 return (0);
1351
1352         if (OF_getencprop(node, "snps,reset-delays-us",
1353             delay_prop, sizeof(delay_prop)) <= 0) {
1354                 device_printf(dev,
1355                     "Wrong property for snps,reset-delays-us");
1356                 return (ENXIO);
1357         }
1358
1359         gpio_node = OF_node_from_xref(gpio_prop[0]);
1360         if ((gpio = OF_device_from_xref(gpio_prop[0])) == NULL) {
1361                 device_printf(dev,
1362                     "Can't find gpio controller for phy reset\n");
1363                 return (ENXIO);
1364         }
1365
1366         if (GPIO_MAP_GPIOS(gpio, node, gpio_node,
1367             nitems(gpio_prop) - 1,
1368             gpio_prop + 1, &pin, &flags) != 0) {
1369                 device_printf(dev, "Can't map gpio for phy reset\n");
1370                 return (ENXIO);
1371         }
1372
1373         pin_value = GPIO_PIN_LOW;
1374         if (OF_hasprop(node, "snps,reset-active-low"))
1375                 pin_value = GPIO_PIN_HIGH;
1376
1377         GPIO_PIN_SETFLAGS(gpio, pin, GPIO_PIN_OUTPUT);
1378         GPIO_PIN_SET(gpio, pin, pin_value);
1379         DELAY(delay_prop[0] * 5);
1380         GPIO_PIN_SET(gpio, pin, !pin_value);
1381         DELAY(delay_prop[1] * 5);
1382         GPIO_PIN_SET(gpio, pin, pin_value);
1383         DELAY(delay_prop[2] * 5);
1384
1385         return (0);
1386 }
1387
1388 #ifdef EXT_RESOURCES
1389 static int
1390 dwc_clock_init(device_t dev)
1391 {
1392         hwreset_t rst;
1393         clk_t clk;
1394         int error;
1395         int64_t freq;
1396
1397         /* Enable clocks */
1398         if (clk_get_by_ofw_name(dev, 0, "stmmaceth", &clk) == 0) {
1399                 error = clk_enable(clk);
1400                 if (error != 0) {
1401                         device_printf(dev, "could not enable main clock\n");
1402                         return (error);
1403                 }
1404                 if (bootverbose) {
1405                         clk_get_freq(clk, &freq);
1406                         device_printf(dev, "MAC clock(%s) freq: %jd\n",
1407                                         clk_get_name(clk), (intmax_t)freq);
1408                 }
1409         }
1410         else {
1411                 device_printf(dev, "could not find clock stmmaceth\n");
1412         }
1413
1414         /* De-assert reset */
1415         if (hwreset_get_by_ofw_name(dev, 0, "stmmaceth", &rst) == 0) {
1416                 error = hwreset_deassert(rst);
1417                 if (error != 0) {
1418                         device_printf(dev, "could not de-assert reset\n");
1419                         return (error);
1420                 }
1421         }
1422
1423         return (0);
1424 }
1425 #endif
1426
1427 static int
1428 dwc_probe(device_t dev)
1429 {
1430
1431         if (!ofw_bus_status_okay(dev))
1432                 return (ENXIO);
1433
1434         if (!ofw_bus_is_compatible(dev, "snps,dwmac"))
1435                 return (ENXIO);
1436
1437         device_set_desc(dev, "Gigabit Ethernet Controller");
1438         return (BUS_PROBE_DEFAULT);
1439 }
1440
1441 static int
1442 dwc_attach(device_t dev)
1443 {
1444         uint8_t macaddr[ETHER_ADDR_LEN];
1445         struct dwc_softc *sc;
1446         struct ifnet *ifp;
1447         int error, i;
1448         uint32_t reg;
1449         char *phy_mode;
1450         phandle_t node;
1451
1452         sc = device_get_softc(dev);
1453         sc->dev = dev;
1454         sc->rx_idx = 0;
1455         sc->txcount = TX_DESC_COUNT;
1456         sc->mii_clk = IF_DWC_MII_CLK(dev);
1457         sc->mactype = IF_DWC_MAC_TYPE(dev);
1458
1459         node = ofw_bus_get_node(dev);
1460         if (OF_getprop_alloc(node, "phy-mode", (void **)&phy_mode)) {
1461                 if (strcmp(phy_mode, "rgmii") == 0)
1462                         sc->phy_mode = PHY_MODE_RGMII;
1463                 if (strcmp(phy_mode, "rmii") == 0)
1464                         sc->phy_mode = PHY_MODE_RMII;
1465                 OF_prop_free(phy_mode);
1466         }
1467
1468         if (IF_DWC_INIT(dev) != 0)
1469                 return (ENXIO);
1470
1471 #ifdef EXT_RESOURCES
1472         if (dwc_clock_init(dev) != 0)
1473                 return (ENXIO);
1474 #endif
1475
1476         if (bus_alloc_resources(dev, dwc_spec, sc->res)) {
1477                 device_printf(dev, "could not allocate resources\n");
1478                 return (ENXIO);
1479         }
1480
1481         /* Read MAC before reset */
1482         dwc_get_hwaddr(sc, macaddr);
1483
1484         /* Reset the PHY if needed */
1485         if (dwc_reset(dev) != 0) {
1486                 device_printf(dev, "Can't reset the PHY\n");
1487                 return (ENXIO);
1488         }
1489
1490         /* Reset */
1491         reg = READ4(sc, BUS_MODE);
1492         reg |= (BUS_MODE_SWR);
1493         WRITE4(sc, BUS_MODE, reg);
1494
1495         for (i = 0; i < MAC_RESET_TIMEOUT; i++) {
1496                 if ((READ4(sc, BUS_MODE) & BUS_MODE_SWR) == 0)
1497                         break;
1498                 DELAY(10);
1499         }
1500         if (i >= MAC_RESET_TIMEOUT) {
1501                 device_printf(sc->dev, "Can't reset DWC.\n");
1502                 return (ENXIO);
1503         }
1504
1505         if (sc->mactype != DWC_GMAC_EXT_DESC) {
1506                 reg = BUS_MODE_FIXEDBURST;
1507                 reg |= (BUS_MODE_PRIORXTX_41 << BUS_MODE_PRIORXTX_SHIFT);
1508         } else
1509                 reg = (BUS_MODE_EIGHTXPBL);
1510         reg |= (BUS_MODE_PBL_BEATS_8 << BUS_MODE_PBL_SHIFT);
1511         WRITE4(sc, BUS_MODE, reg);
1512
1513         /*
1514          * DMA must be stop while changing descriptor list addresses.
1515          */
1516         reg = READ4(sc, OPERATION_MODE);
1517         reg &= ~(MODE_ST | MODE_SR);
1518         WRITE4(sc, OPERATION_MODE, reg);
1519
1520         if (setup_dma(sc))
1521                 return (ENXIO);
1522
1523         /* Setup addresses */
1524         WRITE4(sc, RX_DESCR_LIST_ADDR, sc->rxdesc_ring_paddr);
1525         WRITE4(sc, TX_DESCR_LIST_ADDR, sc->txdesc_ring_paddr);
1526
1527         mtx_init(&sc->mtx, device_get_nameunit(sc->dev),
1528             MTX_NETWORK_LOCK, MTX_DEF);
1529
1530         callout_init_mtx(&sc->dwc_callout, &sc->mtx, 0);
1531
1532         /* Setup interrupt handler. */
1533         error = bus_setup_intr(dev, sc->res[1], INTR_TYPE_NET | INTR_MPSAFE,
1534             NULL, dwc_intr, sc, &sc->intr_cookie);
1535         if (error != 0) {
1536                 device_printf(dev, "could not setup interrupt handler.\n");
1537                 return (ENXIO);
1538         }
1539
1540         /* Set up the ethernet interface. */
1541         sc->ifp = ifp = if_alloc(IFT_ETHER);
1542
1543         ifp->if_softc = sc;
1544         if_initname(ifp, device_get_name(dev), device_get_unit(dev));
1545         if_setflags(sc->ifp, IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
1546         if_setstartfn(ifp, dwc_txstart);
1547         if_setioctlfn(ifp, dwc_ioctl);
1548         if_setinitfn(ifp, dwc_init);
1549         if_setsendqlen(ifp, TX_DESC_COUNT - 1);
1550         if_setsendqready(sc->ifp);
1551         if_setcapabilities(sc->ifp, IFCAP_VLAN_MTU);
1552         if_setcapenable(sc->ifp, if_getcapabilities(sc->ifp));
1553
1554         /* Attach the mii driver. */
1555         error = mii_attach(dev, &sc->miibus, ifp, dwc_media_change,
1556             dwc_media_status, BMSR_DEFCAPMASK, MII_PHY_ANY,
1557             MII_OFFSET_ANY, 0);
1558
1559         if (error != 0) {
1560                 device_printf(dev, "PHY attach failed\n");
1561                 return (ENXIO);
1562         }
1563         sc->mii_softc = device_get_softc(sc->miibus);
1564
1565         /* All ready to run, attach the ethernet interface. */
1566         ether_ifattach(ifp, macaddr);
1567         sc->is_attached = true;
1568
1569         return (0);
1570 }
1571
1572 static device_method_t dwc_methods[] = {
1573         DEVMETHOD(device_probe,         dwc_probe),
1574         DEVMETHOD(device_attach,        dwc_attach),
1575
1576         /* MII Interface */
1577         DEVMETHOD(miibus_readreg,       dwc_miibus_read_reg),
1578         DEVMETHOD(miibus_writereg,      dwc_miibus_write_reg),
1579         DEVMETHOD(miibus_statchg,       dwc_miibus_statchg),
1580
1581         { 0, 0 }
1582 };
1583
1584 driver_t dwc_driver = {
1585         "dwc",
1586         dwc_methods,
1587         sizeof(struct dwc_softc),
1588 };
1589
1590 static devclass_t dwc_devclass;
1591
1592 DRIVER_MODULE(dwc, simplebus, dwc_driver, dwc_devclass, 0, 0);
1593 DRIVER_MODULE(miibus, dwc, miibus_driver, miibus_devclass, 0, 0);
1594
1595 MODULE_DEPEND(dwc, ether, 1, 1, 1);
1596 MODULE_DEPEND(dwc, miibus, 1, 1, 1);