c3413431ec49b596ad573fc790dac607ded2a78f
[oweals/u-boot.git] / drivers / net / rtl8169.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * rtl8169.c : U-Boot driver for the RealTek RTL8169
4  *
5  * Masami Komiya (mkomiya@sonare.it)
6  *
7  * Most part is taken from r8169.c of etherboot
8  *
9  */
10
11 /**************************************************************************
12 *    r8169.c: Etherboot device driver for the RealTek RTL-8169 Gigabit
13 *    Written 2003 by Timothy Legge <tlegge@rogers.com>
14 *
15 *    Portions of this code based on:
16 *       r8169.c: A RealTek RTL-8169 Gigabit Ethernet driver
17 *               for Linux kernel 2.4.x.
18 *
19 *    Written 2002 ShuChen <shuchen@realtek.com.tw>
20 *         See Linux Driver for full information
21 *
22 *    Linux Driver Version 1.27a, 10.02.2002
23 *
24 *    Thanks to:
25 *       Jean Chen of RealTek Semiconductor Corp. for
26 *       providing the evaluation NIC used to develop
27 *       this driver.  RealTek's support for Etherboot
28 *       is appreciated.
29 *
30 *    REVISION HISTORY:
31 *    ================
32 *
33 *    v1.0       11-26-2003      timlegge        Initial port of Linux driver
34 *    v1.5       01-17-2004      timlegge        Initial driver output cleanup
35 *
36 *    Indent Options: indent -kr -i8
37 ***************************************************************************/
38 /*
39  * 26 August 2006 Mihai Georgian <u-boot@linuxnotincluded.org.uk>
40  * Modified to use le32_to_cpu and cpu_to_le32 properly
41  */
42 #include <common.h>
43 #include <cpu_func.h>
44 #include <dm.h>
45 #include <errno.h>
46 #include <log.h>
47 #include <malloc.h>
48 #include <memalign.h>
49 #include <net.h>
50 #ifndef CONFIG_DM_ETH
51 #include <netdev.h>
52 #endif
53 #include <asm/cache.h>
54 #include <asm/io.h>
55 #include <pci.h>
56
57 #undef DEBUG_RTL8169
58 #undef DEBUG_RTL8169_TX
59 #undef DEBUG_RTL8169_RX
60
61 #define drv_version "v1.5"
62 #define drv_date "01-17-2004"
63
64 static unsigned long ioaddr;
65
66 /* Condensed operations for readability. */
67 #define currticks()     get_timer(0)
68
69 /* media options */
70 #define MAX_UNITS 8
71 static int media[MAX_UNITS] = { -1, -1, -1, -1, -1, -1, -1, -1 };
72
73 /* MAC address length*/
74 #define MAC_ADDR_LEN    6
75
76 /* max supported gigabit ethernet frame size -- must be at least (dev->mtu+14+4).*/
77 #define MAX_ETH_FRAME_SIZE      1536
78
79 #define TX_FIFO_THRESH 256      /* In bytes */
80
81 #define RX_FIFO_THRESH  7       /* 7 means NO threshold, Rx buffer level before first PCI xfer.  */
82 #define RX_DMA_BURST    6       /* Maximum PCI burst, '6' is 1024 */
83 #define TX_DMA_BURST    6       /* Maximum PCI burst, '6' is 1024 */
84 #define EarlyTxThld     0x3F    /* 0x3F means NO early transmit */
85 #define RxPacketMaxSize 0x0800  /* Maximum size supported is 16K-1 */
86 #define InterFrameGap   0x03    /* 3 means InterFrameGap = the shortest one */
87
88 #define NUM_TX_DESC     1       /* Number of Tx descriptor registers */
89 #ifdef CONFIG_SYS_RX_ETH_BUFFER
90   #define NUM_RX_DESC   CONFIG_SYS_RX_ETH_BUFFER
91 #else
92   #define NUM_RX_DESC   4       /* Number of Rx descriptor registers */
93 #endif
94 #define RX_BUF_SIZE     1536    /* Rx Buffer size */
95 #define RX_BUF_LEN      8192
96
97 #define RTL_MIN_IO_SIZE 0x80
98 #define TX_TIMEOUT  (6*HZ)
99
100 /* write/read MMIO register. Notice: {read,write}[wl] do the necessary swapping */
101 #define RTL_W8(reg, val8)       writeb((val8), ioaddr + (reg))
102 #define RTL_W16(reg, val16)     writew((val16), ioaddr + (reg))
103 #define RTL_W32(reg, val32)     writel((val32), ioaddr + (reg))
104 #define RTL_R8(reg)             readb(ioaddr + (reg))
105 #define RTL_R16(reg)            readw(ioaddr + (reg))
106 #define RTL_R32(reg)            readl(ioaddr + (reg))
107
108 #define bus_to_phys(a)  pci_mem_to_phys((pci_dev_t)(unsigned long)dev->priv, \
109         (pci_addr_t)(unsigned long)a)
110 #define phys_to_bus(a)  pci_phys_to_mem((pci_dev_t)(unsigned long)dev->priv, \
111         (phys_addr_t)a)
112
113 enum RTL8169_registers {
114         MAC0 = 0,               /* Ethernet hardware address. */
115         MAR0 = 8,               /* Multicast filter. */
116         TxDescStartAddrLow = 0x20,
117         TxDescStartAddrHigh = 0x24,
118         TxHDescStartAddrLow = 0x28,
119         TxHDescStartAddrHigh = 0x2c,
120         FLASH = 0x30,
121         ERSR = 0x36,
122         ChipCmd = 0x37,
123         TxPoll = 0x38,
124         IntrMask = 0x3C,
125         IntrStatus = 0x3E,
126         TxConfig = 0x40,
127         RxConfig = 0x44,
128         RxMissed = 0x4C,
129         Cfg9346 = 0x50,
130         Config0 = 0x51,
131         Config1 = 0x52,
132         Config2 = 0x53,
133         Config3 = 0x54,
134         Config4 = 0x55,
135         Config5 = 0x56,
136         MultiIntr = 0x5C,
137         PHYAR = 0x60,
138         TBICSR = 0x64,
139         TBI_ANAR = 0x68,
140         TBI_LPAR = 0x6A,
141         PHYstatus = 0x6C,
142         RxMaxSize = 0xDA,
143         CPlusCmd = 0xE0,
144         RxDescStartAddrLow = 0xE4,
145         RxDescStartAddrHigh = 0xE8,
146         EarlyTxThres = 0xEC,
147         FuncEvent = 0xF0,
148         FuncEventMask = 0xF4,
149         FuncPresetState = 0xF8,
150         FuncForceEvent = 0xFC,
151 };
152
153 enum RTL8169_register_content {
154         /*InterruptStatusBits */
155         SYSErr = 0x8000,
156         PCSTimeout = 0x4000,
157         SWInt = 0x0100,
158         TxDescUnavail = 0x80,
159         RxFIFOOver = 0x40,
160         RxUnderrun = 0x20,
161         RxOverflow = 0x10,
162         TxErr = 0x08,
163         TxOK = 0x04,
164         RxErr = 0x02,
165         RxOK = 0x01,
166
167         /*RxStatusDesc */
168         RxRES = 0x00200000,
169         RxCRC = 0x00080000,
170         RxRUNT = 0x00100000,
171         RxRWT = 0x00400000,
172
173         /*ChipCmdBits */
174         CmdReset = 0x10,
175         CmdRxEnb = 0x08,
176         CmdTxEnb = 0x04,
177         RxBufEmpty = 0x01,
178
179         /*Cfg9346Bits */
180         Cfg9346_Lock = 0x00,
181         Cfg9346_Unlock = 0xC0,
182
183         /*rx_mode_bits */
184         AcceptErr = 0x20,
185         AcceptRunt = 0x10,
186         AcceptBroadcast = 0x08,
187         AcceptMulticast = 0x04,
188         AcceptMyPhys = 0x02,
189         AcceptAllPhys = 0x01,
190
191         /*RxConfigBits */
192         RxCfgFIFOShift = 13,
193         RxCfgDMAShift = 8,
194
195         /*TxConfigBits */
196         TxInterFrameGapShift = 24,
197         TxDMAShift = 8,         /* DMA burst value (0-7) is shift this many bits */
198
199         /*rtl8169_PHYstatus */
200         TBI_Enable = 0x80,
201         TxFlowCtrl = 0x40,
202         RxFlowCtrl = 0x20,
203         _1000bpsF = 0x10,
204         _100bps = 0x08,
205         _10bps = 0x04,
206         LinkStatus = 0x02,
207         FullDup = 0x01,
208
209         /*GIGABIT_PHY_registers */
210         PHY_CTRL_REG = 0,
211         PHY_STAT_REG = 1,
212         PHY_AUTO_NEGO_REG = 4,
213         PHY_1000_CTRL_REG = 9,
214
215         /*GIGABIT_PHY_REG_BIT */
216         PHY_Restart_Auto_Nego = 0x0200,
217         PHY_Enable_Auto_Nego = 0x1000,
218
219         /* PHY_STAT_REG = 1; */
220         PHY_Auto_Nego_Comp = 0x0020,
221
222         /* PHY_AUTO_NEGO_REG = 4; */
223         PHY_Cap_10_Half = 0x0020,
224         PHY_Cap_10_Full = 0x0040,
225         PHY_Cap_100_Half = 0x0080,
226         PHY_Cap_100_Full = 0x0100,
227
228         /* PHY_1000_CTRL_REG = 9; */
229         PHY_Cap_1000_Full = 0x0200,
230
231         PHY_Cap_Null = 0x0,
232
233         /*_MediaType*/
234         _10_Half = 0x01,
235         _10_Full = 0x02,
236         _100_Half = 0x04,
237         _100_Full = 0x08,
238         _1000_Full = 0x10,
239
240         /*_TBICSRBit*/
241         TBILinkOK = 0x02000000,
242 };
243
244 static struct {
245         const char *name;
246         u8 version;             /* depend on RTL8169 docs */
247         u32 RxConfigMask;       /* should clear the bits supported by this chip */
248 } rtl_chip_info[] = {
249         {"RTL-8169", 0x00, 0xff7e1880,},
250         {"RTL-8169", 0x04, 0xff7e1880,},
251         {"RTL-8169", 0x00, 0xff7e1880,},
252         {"RTL-8169s/8110s",     0x02, 0xff7e1880,},
253         {"RTL-8169s/8110s",     0x04, 0xff7e1880,},
254         {"RTL-8169sb/8110sb",   0x10, 0xff7e1880,},
255         {"RTL-8169sc/8110sc",   0x18, 0xff7e1880,},
256         {"RTL-8168b/8111sb",    0x30, 0xff7e1880,},
257         {"RTL-8168b/8111sb",    0x38, 0xff7e1880,},
258         {"RTL-8168c/8111c",     0x3c, 0xff7e1880,},
259         {"RTL-8168d/8111d",     0x28, 0xff7e1880,},
260         {"RTL-8168evl/8111evl", 0x2e, 0xff7e1880,},
261         {"RTL-8168/8111g",      0x4c, 0xff7e1880,},
262         {"RTL-8101e",           0x34, 0xff7e1880,},
263         {"RTL-8100e",           0x32, 0xff7e1880,},
264         {"RTL-8168h/8111h",     0x54, 0xff7e1880,},
265 };
266
267 enum _DescStatusBit {
268         OWNbit = 0x80000000,
269         EORbit = 0x40000000,
270         FSbit = 0x20000000,
271         LSbit = 0x10000000,
272 };
273
274 struct TxDesc {
275         u32 status;
276         u32 vlan_tag;
277         u32 buf_addr;
278         u32 buf_Haddr;
279 };
280
281 struct RxDesc {
282         u32 status;
283         u32 vlan_tag;
284         u32 buf_addr;
285         u32 buf_Haddr;
286 };
287
288 static unsigned char rxdata[RX_BUF_LEN];
289
290 #define RTL8169_DESC_SIZE 16
291
292 #if ARCH_DMA_MINALIGN > 256
293 #  define RTL8169_ALIGN ARCH_DMA_MINALIGN
294 #else
295 #  define RTL8169_ALIGN 256
296 #endif
297
298 /*
299  * Warn if the cache-line size is larger than the descriptor size. In such
300  * cases the driver will likely fail because the CPU needs to flush the cache
301  * when requeuing RX buffers, therefore descriptors written by the hardware
302  * may be discarded.
303  *
304  * This can be fixed by defining CONFIG_SYS_NONCACHED_MEMORY which will cause
305  * the driver to allocate descriptors from a pool of non-cached memory.
306  */
307 #if RTL8169_DESC_SIZE < ARCH_DMA_MINALIGN
308 #if !defined(CONFIG_SYS_NONCACHED_MEMORY) && \
309         !CONFIG_IS_ENABLED(SYS_DCACHE_OFF) && !defined(CONFIG_X86)
310 #warning cache-line size is larger than descriptor size
311 #endif
312 #endif
313
314 /*
315  * Create a static buffer of size RX_BUF_SZ for each TX Descriptor. All
316  * descriptors point to a part of this buffer.
317  */
318 DEFINE_ALIGN_BUFFER(u8, txb, NUM_TX_DESC * RX_BUF_SIZE, RTL8169_ALIGN);
319
320 /*
321  * Create a static buffer of size RX_BUF_SZ for each RX Descriptor. All
322  * descriptors point to a part of this buffer.
323  */
324 DEFINE_ALIGN_BUFFER(u8, rxb, NUM_RX_DESC * RX_BUF_SIZE, RTL8169_ALIGN);
325
326 struct rtl8169_private {
327         ulong iobase;
328         void *mmio_addr;        /* memory map physical address */
329         int chipset;
330         unsigned long cur_rx;   /* Index into the Rx descriptor buffer of next Rx pkt. */
331         unsigned long cur_tx;   /* Index into the Tx descriptor buffer of next Rx pkt. */
332         unsigned long dirty_tx;
333         struct TxDesc *TxDescArray;     /* Index of 256-alignment Tx Descriptor buffer */
334         struct RxDesc *RxDescArray;     /* Index of 256-alignment Rx Descriptor buffer */
335         unsigned char *RxBufferRings;   /* Index of Rx Buffer  */
336         unsigned char *RxBufferRing[NUM_RX_DESC];       /* Index of Rx Buffer array */
337         unsigned char *Tx_skbuff[NUM_TX_DESC];
338 } tpx;
339
340 static struct rtl8169_private *tpc;
341
342 static const unsigned int rtl8169_rx_config =
343     (RX_FIFO_THRESH << RxCfgFIFOShift) | (RX_DMA_BURST << RxCfgDMAShift);
344
345 static struct pci_device_id supported[] = {
346         { PCI_DEVICE(PCI_VENDOR_ID_REALTEK, 0x8167) },
347         { PCI_DEVICE(PCI_VENDOR_ID_REALTEK, 0x8168) },
348         { PCI_DEVICE(PCI_VENDOR_ID_REALTEK, 0x8169) },
349         {}
350 };
351
352 void mdio_write(int RegAddr, int value)
353 {
354         int i;
355
356         RTL_W32(PHYAR, 0x80000000 | (RegAddr & 0xFF) << 16 | value);
357         udelay(1000);
358
359         for (i = 2000; i > 0; i--) {
360                 /* Check if the RTL8169 has completed writing to the specified MII register */
361                 if (!(RTL_R32(PHYAR) & 0x80000000)) {
362                         break;
363                 } else {
364                         udelay(100);
365                 }
366         }
367 }
368
369 int mdio_read(int RegAddr)
370 {
371         int i, value = -1;
372
373         RTL_W32(PHYAR, 0x0 | (RegAddr & 0xFF) << 16);
374         udelay(1000);
375
376         for (i = 2000; i > 0; i--) {
377                 /* Check if the RTL8169 has completed retrieving data from the specified MII register */
378                 if (RTL_R32(PHYAR) & 0x80000000) {
379                         value = (int) (RTL_R32(PHYAR) & 0xFFFF);
380                         break;
381                 } else {
382                         udelay(100);
383                 }
384         }
385         return value;
386 }
387
388 static int rtl8169_init_board(unsigned long dev_iobase, const char *name)
389 {
390         int i;
391         u32 tmp;
392
393 #ifdef DEBUG_RTL8169
394         printf ("%s\n", __FUNCTION__);
395 #endif
396         ioaddr = dev_iobase;
397
398         /* Soft reset the chip. */
399         RTL_W8(ChipCmd, CmdReset);
400
401         /* Check that the chip has finished the reset. */
402         for (i = 1000; i > 0; i--)
403                 if ((RTL_R8(ChipCmd) & CmdReset) == 0)
404                         break;
405                 else
406                         udelay(10);
407
408         /* identify chip attached to board */
409         tmp = RTL_R32(TxConfig);
410         tmp = ((tmp & 0x7c000000) + ((tmp & 0x00800000) << 2)) >> 24;
411
412         for (i = ARRAY_SIZE(rtl_chip_info) - 1; i >= 0; i--){
413                 if (tmp == rtl_chip_info[i].version) {
414                         tpc->chipset = i;
415                         goto match;
416                 }
417         }
418
419         /* if unknown chip, assume array element #0, original RTL-8169 in this case */
420         printf("PCI device %s: unknown chip version, assuming RTL-8169\n",
421                name);
422         printf("PCI device: TxConfig = 0x%lX\n", (unsigned long) RTL_R32(TxConfig));
423         tpc->chipset = 0;
424
425 match:
426         return 0;
427 }
428
429 /*
430  * TX and RX descriptors are 16 bytes. This causes problems with the cache
431  * maintenance on CPUs where the cache-line size exceeds the size of these
432  * descriptors. What will happen is that when the driver receives a packet
433  * it will be immediately requeued for the hardware to reuse. The CPU will
434  * therefore need to flush the cache-line containing the descriptor, which
435  * will cause all other descriptors in the same cache-line to be flushed
436  * along with it. If one of those descriptors had been written to by the
437  * device those changes (and the associated packet) will be lost.
438  *
439  * To work around this, we make use of non-cached memory if available. If
440  * descriptors are mapped uncached there's no need to manually flush them
441  * or invalidate them.
442  *
443  * Note that this only applies to descriptors. The packet data buffers do
444  * not have the same constraints since they are 1536 bytes large, so they
445  * are unlikely to share cache-lines.
446  */
447 static void *rtl_alloc_descs(unsigned int num)
448 {
449         size_t size = num * RTL8169_DESC_SIZE;
450
451 #ifdef CONFIG_SYS_NONCACHED_MEMORY
452         return (void *)noncached_alloc(size, RTL8169_ALIGN);
453 #else
454         return memalign(RTL8169_ALIGN, size);
455 #endif
456 }
457
458 /*
459  * Cache maintenance functions. These are simple wrappers around the more
460  * general purpose flush_cache() and invalidate_dcache_range() functions.
461  */
462
463 static void rtl_inval_rx_desc(struct RxDesc *desc)
464 {
465 #ifndef CONFIG_SYS_NONCACHED_MEMORY
466         unsigned long start = (unsigned long)desc & ~(ARCH_DMA_MINALIGN - 1);
467         unsigned long end = ALIGN(start + sizeof(*desc), ARCH_DMA_MINALIGN);
468
469         invalidate_dcache_range(start, end);
470 #endif
471 }
472
473 static void rtl_flush_rx_desc(struct RxDesc *desc)
474 {
475 #ifndef CONFIG_SYS_NONCACHED_MEMORY
476         flush_cache((unsigned long)desc, sizeof(*desc));
477 #endif
478 }
479
480 static void rtl_inval_tx_desc(struct TxDesc *desc)
481 {
482 #ifndef CONFIG_SYS_NONCACHED_MEMORY
483         unsigned long start = (unsigned long)desc & ~(ARCH_DMA_MINALIGN - 1);
484         unsigned long end = ALIGN(start + sizeof(*desc), ARCH_DMA_MINALIGN);
485
486         invalidate_dcache_range(start, end);
487 #endif
488 }
489
490 static void rtl_flush_tx_desc(struct TxDesc *desc)
491 {
492 #ifndef CONFIG_SYS_NONCACHED_MEMORY
493         flush_cache((unsigned long)desc, sizeof(*desc));
494 #endif
495 }
496
497 static void rtl_inval_buffer(void *buf, size_t size)
498 {
499         unsigned long start = (unsigned long)buf & ~(ARCH_DMA_MINALIGN - 1);
500         unsigned long end = ALIGN(start + size, ARCH_DMA_MINALIGN);
501
502         invalidate_dcache_range(start, end);
503 }
504
505 static void rtl_flush_buffer(void *buf, size_t size)
506 {
507         flush_cache((unsigned long)buf, size);
508 }
509
510 /**************************************************************************
511 RECV - Receive a frame
512 ***************************************************************************/
513 #ifdef CONFIG_DM_ETH
514 static int rtl_recv_common(struct udevice *dev, unsigned long dev_iobase,
515                            uchar **packetp)
516 #else
517 static int rtl_recv_common(pci_dev_t dev, unsigned long dev_iobase,
518                            uchar **packetp)
519 #endif
520 {
521         /* return true if there's an ethernet packet ready to read */
522         /* nic->packet should contain data on return */
523         /* nic->packetlen should contain length of data */
524         int cur_rx;
525         int length = 0;
526
527 #ifdef DEBUG_RTL8169_RX
528         printf ("%s\n", __FUNCTION__);
529 #endif
530         ioaddr = dev_iobase;
531
532         cur_rx = tpc->cur_rx;
533
534         rtl_inval_rx_desc(&tpc->RxDescArray[cur_rx]);
535
536         if ((le32_to_cpu(tpc->RxDescArray[cur_rx].status) & OWNbit) == 0) {
537                 if (!(le32_to_cpu(tpc->RxDescArray[cur_rx].status) & RxRES)) {
538                         length = (int) (le32_to_cpu(tpc->RxDescArray[cur_rx].
539                                                 status) & 0x00001FFF) - 4;
540
541                         rtl_inval_buffer(tpc->RxBufferRing[cur_rx], length);
542                         memcpy(rxdata, tpc->RxBufferRing[cur_rx], length);
543
544                         if (cur_rx == NUM_RX_DESC - 1)
545                                 tpc->RxDescArray[cur_rx].status =
546                                         cpu_to_le32((OWNbit | EORbit) + RX_BUF_SIZE);
547                         else
548                                 tpc->RxDescArray[cur_rx].status =
549                                         cpu_to_le32(OWNbit + RX_BUF_SIZE);
550 #ifdef CONFIG_DM_ETH
551                         tpc->RxDescArray[cur_rx].buf_addr = cpu_to_le32(
552                                 dm_pci_mem_to_phys(dev,
553                                         (pci_addr_t)(unsigned long)
554                                         tpc->RxBufferRing[cur_rx]));
555 #else
556                         tpc->RxDescArray[cur_rx].buf_addr = cpu_to_le32(
557                                 pci_mem_to_phys(dev, (pci_addr_t)(unsigned long)
558                                 tpc->RxBufferRing[cur_rx]));
559 #endif
560                         rtl_flush_rx_desc(&tpc->RxDescArray[cur_rx]);
561 #ifdef CONFIG_DM_ETH
562                         *packetp = rxdata;
563 #else
564                         net_process_received_packet(rxdata, length);
565 #endif
566                 } else {
567                         puts("Error Rx");
568                         length = -EIO;
569                 }
570                 cur_rx = (cur_rx + 1) % NUM_RX_DESC;
571                 tpc->cur_rx = cur_rx;
572                 return length;
573
574         } else {
575                 ushort sts = RTL_R8(IntrStatus);
576                 RTL_W8(IntrStatus, sts & ~(TxErr | RxErr | SYSErr));
577                 udelay(100);    /* wait */
578         }
579         tpc->cur_rx = cur_rx;
580         return (0);             /* initially as this is called to flush the input */
581 }
582
583 #ifdef CONFIG_DM_ETH
584 int rtl8169_eth_recv(struct udevice *dev, int flags, uchar **packetp)
585 {
586         struct rtl8169_private *priv = dev_get_priv(dev);
587
588         return rtl_recv_common(dev, priv->iobase, packetp);
589 }
590 #else
591 static int rtl_recv(struct eth_device *dev)
592 {
593         return rtl_recv_common((pci_dev_t)(unsigned long)dev->priv,
594                                dev->iobase, NULL);
595 }
596 #endif /* nCONFIG_DM_ETH */
597
598 #define HZ 1000
599 /**************************************************************************
600 SEND - Transmit a frame
601 ***************************************************************************/
602 #ifdef CONFIG_DM_ETH
603 static int rtl_send_common(struct udevice *dev, unsigned long dev_iobase,
604                            void *packet, int length)
605 #else
606 static int rtl_send_common(pci_dev_t dev, unsigned long dev_iobase,
607                            void *packet, int length)
608 #endif
609 {
610         /* send the packet to destination */
611
612         u32 to;
613         u8 *ptxb;
614         int entry = tpc->cur_tx % NUM_TX_DESC;
615         u32 len = length;
616         int ret;
617
618 #ifdef DEBUG_RTL8169_TX
619         int stime = currticks();
620         printf ("%s\n", __FUNCTION__);
621         printf("sending %d bytes\n", len);
622 #endif
623
624         ioaddr = dev_iobase;
625
626         /* point to the current txb incase multiple tx_rings are used */
627         ptxb = tpc->Tx_skbuff[entry * MAX_ETH_FRAME_SIZE];
628         memcpy(ptxb, (char *)packet, (int)length);
629
630         while (len < ETH_ZLEN)
631                 ptxb[len++] = '\0';
632
633         rtl_flush_buffer(ptxb, ALIGN(len, RTL8169_ALIGN));
634
635         tpc->TxDescArray[entry].buf_Haddr = 0;
636 #ifdef CONFIG_DM_ETH
637         tpc->TxDescArray[entry].buf_addr = cpu_to_le32(
638                 dm_pci_mem_to_phys(dev, (pci_addr_t)(unsigned long)ptxb));
639 #else
640         tpc->TxDescArray[entry].buf_addr = cpu_to_le32(
641                 pci_mem_to_phys(dev, (pci_addr_t)(unsigned long)ptxb));
642 #endif
643         if (entry != (NUM_TX_DESC - 1)) {
644                 tpc->TxDescArray[entry].status =
645                         cpu_to_le32((OWNbit | FSbit | LSbit) |
646                                     ((len > ETH_ZLEN) ? len : ETH_ZLEN));
647         } else {
648                 tpc->TxDescArray[entry].status =
649                         cpu_to_le32((OWNbit | EORbit | FSbit | LSbit) |
650                                     ((len > ETH_ZLEN) ? len : ETH_ZLEN));
651         }
652         rtl_flush_tx_desc(&tpc->TxDescArray[entry]);
653         RTL_W8(TxPoll, 0x40);   /* set polling bit */
654
655         tpc->cur_tx++;
656         to = currticks() + TX_TIMEOUT;
657         do {
658                 rtl_inval_tx_desc(&tpc->TxDescArray[entry]);
659         } while ((le32_to_cpu(tpc->TxDescArray[entry].status) & OWNbit)
660                                 && (currticks() < to)); /* wait */
661
662         if (currticks() >= to) {
663 #ifdef DEBUG_RTL8169_TX
664                 puts("tx timeout/error\n");
665                 printf("%s elapsed time : %lu\n", __func__, currticks()-stime);
666 #endif
667                 ret = -ETIMEDOUT;
668         } else {
669 #ifdef DEBUG_RTL8169_TX
670                 puts("tx done\n");
671 #endif
672                 ret = 0;
673         }
674         /* Delay to make net console (nc) work properly */
675         udelay(20);
676         return ret;
677 }
678
679 #ifdef CONFIG_DM_ETH
680 int rtl8169_eth_send(struct udevice *dev, void *packet, int length)
681 {
682         struct rtl8169_private *priv = dev_get_priv(dev);
683
684         return rtl_send_common(dev, priv->iobase, packet, length);
685 }
686
687 #else
688 static int rtl_send(struct eth_device *dev, void *packet, int length)
689 {
690         return rtl_send_common((pci_dev_t)(unsigned long)dev->priv,
691                                dev->iobase, packet, length);
692 }
693 #endif
694
695 static void rtl8169_set_rx_mode(void)
696 {
697         u32 mc_filter[2];       /* Multicast hash filter */
698         int rx_mode;
699         u32 tmp = 0;
700
701 #ifdef DEBUG_RTL8169
702         printf ("%s\n", __FUNCTION__);
703 #endif
704
705         /* IFF_ALLMULTI */
706         /* Too many to filter perfectly -- accept all multicasts. */
707         rx_mode = AcceptBroadcast | AcceptMulticast | AcceptMyPhys;
708         mc_filter[1] = mc_filter[0] = 0xffffffff;
709
710         tmp = rtl8169_rx_config | rx_mode | (RTL_R32(RxConfig) &
711                                    rtl_chip_info[tpc->chipset].RxConfigMask);
712
713         RTL_W32(RxConfig, tmp);
714         RTL_W32(MAR0 + 0, mc_filter[0]);
715         RTL_W32(MAR0 + 4, mc_filter[1]);
716 }
717
718 #ifdef CONFIG_DM_ETH
719 static void rtl8169_hw_start(struct udevice *dev)
720 #else
721 static void rtl8169_hw_start(pci_dev_t dev)
722 #endif
723 {
724         u32 i;
725
726 #ifdef DEBUG_RTL8169
727         int stime = currticks();
728         printf ("%s\n", __FUNCTION__);
729 #endif
730
731 #if 0
732         /* Soft reset the chip. */
733         RTL_W8(ChipCmd, CmdReset);
734
735         /* Check that the chip has finished the reset. */
736         for (i = 1000; i > 0; i--) {
737                 if ((RTL_R8(ChipCmd) & CmdReset) == 0)
738                         break;
739                 else
740                         udelay(10);
741         }
742 #endif
743
744         RTL_W8(Cfg9346, Cfg9346_Unlock);
745
746         /* RTL-8169sb/8110sb or previous version */
747         if (tpc->chipset <= 5)
748                 RTL_W8(ChipCmd, CmdTxEnb | CmdRxEnb);
749
750         RTL_W8(EarlyTxThres, EarlyTxThld);
751
752         /* For gigabit rtl8169 */
753         RTL_W16(RxMaxSize, RxPacketMaxSize);
754
755         /* Set Rx Config register */
756         i = rtl8169_rx_config | (RTL_R32(RxConfig) &
757                                  rtl_chip_info[tpc->chipset].RxConfigMask);
758         RTL_W32(RxConfig, i);
759
760         /* Set DMA burst size and Interframe Gap Time */
761         RTL_W32(TxConfig, (TX_DMA_BURST << TxDMAShift) |
762                                 (InterFrameGap << TxInterFrameGapShift));
763
764
765         tpc->cur_rx = 0;
766
767 #ifdef CONFIG_DM_ETH
768         RTL_W32(TxDescStartAddrLow, dm_pci_mem_to_phys(dev,
769                         (pci_addr_t)(unsigned long)tpc->TxDescArray));
770 #else
771         RTL_W32(TxDescStartAddrLow, pci_mem_to_phys(dev,
772                         (pci_addr_t)(unsigned long)tpc->TxDescArray));
773 #endif
774         RTL_W32(TxDescStartAddrHigh, (unsigned long)0);
775 #ifdef CONFIG_DM_ETH
776         RTL_W32(RxDescStartAddrLow, dm_pci_mem_to_phys(
777                         dev, (pci_addr_t)(unsigned long)tpc->RxDescArray));
778 #else
779         RTL_W32(RxDescStartAddrLow, pci_mem_to_phys(
780                         dev, (pci_addr_t)(unsigned long)tpc->RxDescArray));
781 #endif
782         RTL_W32(RxDescStartAddrHigh, (unsigned long)0);
783
784         /* RTL-8169sc/8110sc or later version */
785         if (tpc->chipset > 5)
786                 RTL_W8(ChipCmd, CmdTxEnb | CmdRxEnb);
787
788         RTL_W8(Cfg9346, Cfg9346_Lock);
789         udelay(10);
790
791         RTL_W32(RxMissed, 0);
792
793         rtl8169_set_rx_mode();
794
795         /* no early-rx interrupts */
796         RTL_W16(MultiIntr, RTL_R16(MultiIntr) & 0xF000);
797
798 #ifdef DEBUG_RTL8169
799         printf("%s elapsed time : %lu\n", __func__, currticks()-stime);
800 #endif
801 }
802
803 #ifdef CONFIG_DM_ETH
804 static void rtl8169_init_ring(struct udevice *dev)
805 #else
806 static void rtl8169_init_ring(pci_dev_t dev)
807 #endif
808 {
809         int i;
810
811 #ifdef DEBUG_RTL8169
812         int stime = currticks();
813         printf ("%s\n", __FUNCTION__);
814 #endif
815
816         tpc->cur_rx = 0;
817         tpc->cur_tx = 0;
818         tpc->dirty_tx = 0;
819         memset(tpc->TxDescArray, 0x0, NUM_TX_DESC * sizeof(struct TxDesc));
820         memset(tpc->RxDescArray, 0x0, NUM_RX_DESC * sizeof(struct RxDesc));
821
822         for (i = 0; i < NUM_TX_DESC; i++) {
823                 tpc->Tx_skbuff[i] = &txb[i];
824         }
825
826         for (i = 0; i < NUM_RX_DESC; i++) {
827                 if (i == (NUM_RX_DESC - 1))
828                         tpc->RxDescArray[i].status =
829                                 cpu_to_le32((OWNbit | EORbit) + RX_BUF_SIZE);
830                 else
831                         tpc->RxDescArray[i].status =
832                                 cpu_to_le32(OWNbit + RX_BUF_SIZE);
833
834                 tpc->RxBufferRing[i] = &rxb[i * RX_BUF_SIZE];
835 #ifdef CONFIG_DM_ETH
836                 tpc->RxDescArray[i].buf_addr = cpu_to_le32(dm_pci_mem_to_phys(
837                         dev, (pci_addr_t)(unsigned long)tpc->RxBufferRing[i]));
838 #else
839                 tpc->RxDescArray[i].buf_addr = cpu_to_le32(pci_mem_to_phys(
840                         dev, (pci_addr_t)(unsigned long)tpc->RxBufferRing[i]));
841 #endif
842                 rtl_flush_rx_desc(&tpc->RxDescArray[i]);
843         }
844
845 #ifdef DEBUG_RTL8169
846         printf("%s elapsed time : %lu\n", __func__, currticks()-stime);
847 #endif
848 }
849
850 #ifdef CONFIG_DM_ETH
851 static void rtl8169_common_start(struct udevice *dev, unsigned char *enetaddr,
852                                  unsigned long dev_iobase)
853 #else
854 static void rtl8169_common_start(pci_dev_t dev, unsigned char *enetaddr,
855                                  unsigned long dev_iobase)
856 #endif
857 {
858         int i;
859
860 #ifdef DEBUG_RTL8169
861         int stime = currticks();
862         printf ("%s\n", __FUNCTION__);
863 #endif
864
865         ioaddr = dev_iobase;
866
867         rtl8169_init_ring(dev);
868         rtl8169_hw_start(dev);
869         /* Construct a perfect filter frame with the mac address as first match
870          * and broadcast for all others */
871         for (i = 0; i < 192; i++)
872                 txb[i] = 0xFF;
873
874         txb[0] = enetaddr[0];
875         txb[1] = enetaddr[1];
876         txb[2] = enetaddr[2];
877         txb[3] = enetaddr[3];
878         txb[4] = enetaddr[4];
879         txb[5] = enetaddr[5];
880
881 #ifdef DEBUG_RTL8169
882         printf("%s elapsed time : %lu\n", __func__, currticks()-stime);
883 #endif
884 }
885
886 #ifdef CONFIG_DM_ETH
887 static int rtl8169_eth_start(struct udevice *dev)
888 {
889         struct eth_pdata *plat = dev_get_platdata(dev);
890         struct rtl8169_private *priv = dev_get_priv(dev);
891
892         rtl8169_common_start(dev, plat->enetaddr, priv->iobase);
893
894         return 0;
895 }
896 #else
897 /**************************************************************************
898 RESET - Finish setting up the ethernet interface
899 ***************************************************************************/
900 static int rtl_reset(struct eth_device *dev, bd_t *bis)
901 {
902         rtl8169_common_start((pci_dev_t)(unsigned long)dev->priv,
903                              dev->enetaddr, dev->iobase);
904
905         return 0;
906 }
907 #endif /* nCONFIG_DM_ETH */
908
909 static void rtl_halt_common(unsigned long dev_iobase)
910 {
911         int i;
912
913 #ifdef DEBUG_RTL8169
914         printf ("%s\n", __FUNCTION__);
915 #endif
916
917         ioaddr = dev_iobase;
918
919         /* Stop the chip's Tx and Rx DMA processes. */
920         RTL_W8(ChipCmd, 0x00);
921
922         /* Disable interrupts by clearing the interrupt mask. */
923         RTL_W16(IntrMask, 0x0000);
924
925         RTL_W32(RxMissed, 0);
926
927         for (i = 0; i < NUM_RX_DESC; i++) {
928                 tpc->RxBufferRing[i] = NULL;
929         }
930 }
931
932 #ifdef CONFIG_DM_ETH
933 void rtl8169_eth_stop(struct udevice *dev)
934 {
935         struct rtl8169_private *priv = dev_get_priv(dev);
936
937         rtl_halt_common(priv->iobase);
938 }
939 #else
940 /**************************************************************************
941 HALT - Turn off ethernet interface
942 ***************************************************************************/
943 static void rtl_halt(struct eth_device *dev)
944 {
945         rtl_halt_common(dev->iobase);
946 }
947 #endif
948
949 #ifdef CONFIG_DM_ETH
950 static int rtl8169_write_hwaddr(struct udevice *dev)
951 {
952         struct eth_pdata *plat = dev_get_platdata(dev);
953         unsigned int i;
954
955         RTL_W8(Cfg9346, Cfg9346_Unlock);
956
957         for (i = 0; i < MAC_ADDR_LEN; i++)
958                 RTL_W8(MAC0 + i, plat->enetaddr[i]);
959
960         RTL_W8(Cfg9346, Cfg9346_Lock);
961
962         return 0;
963 }
964 #endif
965
966 /**************************************************************************
967 INIT - Look for an adapter, this routine's visible to the outside
968 ***************************************************************************/
969
970 #define board_found 1
971 #define valid_link 0
972 static int rtl_init(unsigned long dev_ioaddr, const char *name,
973                     unsigned char *enetaddr)
974 {
975         static int board_idx = -1;
976         int i, rc;
977         int option = -1, Cap10_100 = 0, Cap1000 = 0;
978
979 #ifdef DEBUG_RTL8169
980         printf ("%s\n", __FUNCTION__);
981 #endif
982         ioaddr = dev_ioaddr;
983
984         board_idx++;
985
986         /* point to private storage */
987         tpc = &tpx;
988
989         rc = rtl8169_init_board(ioaddr, name);
990         if (rc)
991                 return rc;
992
993         /* Get MAC address.  FIXME: read EEPROM */
994         for (i = 0; i < MAC_ADDR_LEN; i++)
995                 enetaddr[i] = RTL_R8(MAC0 + i);
996
997 #ifdef DEBUG_RTL8169
998         printf("chipset = %d\n", tpc->chipset);
999         printf("MAC Address");
1000         for (i = 0; i < MAC_ADDR_LEN; i++)
1001                 printf(":%02x", enetaddr[i]);
1002         putc('\n');
1003 #endif
1004
1005 #ifdef DEBUG_RTL8169
1006         /* Print out some hardware info */
1007         printf("%s: at ioaddr 0x%lx\n", name, ioaddr);
1008 #endif
1009
1010         /* if TBI is not endbled */
1011         if (!(RTL_R8(PHYstatus) & TBI_Enable)) {
1012                 int val = mdio_read(PHY_AUTO_NEGO_REG);
1013
1014                 option = (board_idx >= MAX_UNITS) ? 0 : media[board_idx];
1015                 /* Force RTL8169 in 10/100/1000 Full/Half mode. */
1016                 if (option > 0) {
1017 #ifdef DEBUG_RTL8169
1018                         printf("%s: Force-mode Enabled.\n", name);
1019 #endif
1020                         Cap10_100 = 0, Cap1000 = 0;
1021                         switch (option) {
1022                         case _10_Half:
1023                                 Cap10_100 = PHY_Cap_10_Half;
1024                                 Cap1000 = PHY_Cap_Null;
1025                                 break;
1026                         case _10_Full:
1027                                 Cap10_100 = PHY_Cap_10_Full;
1028                                 Cap1000 = PHY_Cap_Null;
1029                                 break;
1030                         case _100_Half:
1031                                 Cap10_100 = PHY_Cap_100_Half;
1032                                 Cap1000 = PHY_Cap_Null;
1033                                 break;
1034                         case _100_Full:
1035                                 Cap10_100 = PHY_Cap_100_Full;
1036                                 Cap1000 = PHY_Cap_Null;
1037                                 break;
1038                         case _1000_Full:
1039                                 Cap10_100 = PHY_Cap_Null;
1040                                 Cap1000 = PHY_Cap_1000_Full;
1041                                 break;
1042                         default:
1043                                 break;
1044                         }
1045                         mdio_write(PHY_AUTO_NEGO_REG, Cap10_100 | (val & 0x1F));        /* leave PHY_AUTO_NEGO_REG bit4:0 unchanged */
1046                         mdio_write(PHY_1000_CTRL_REG, Cap1000);
1047                 } else {
1048 #ifdef DEBUG_RTL8169
1049                         printf("%s: Auto-negotiation Enabled.\n",
1050                                name);
1051 #endif
1052                         /* enable 10/100 Full/Half Mode, leave PHY_AUTO_NEGO_REG bit4:0 unchanged */
1053                         mdio_write(PHY_AUTO_NEGO_REG,
1054                                    PHY_Cap_10_Half | PHY_Cap_10_Full |
1055                                    PHY_Cap_100_Half | PHY_Cap_100_Full |
1056                                    (val & 0x1F));
1057
1058                         /* enable 1000 Full Mode */
1059                         mdio_write(PHY_1000_CTRL_REG, PHY_Cap_1000_Full);
1060
1061                 }
1062
1063                 /* Enable auto-negotiation and restart auto-nigotiation */
1064                 mdio_write(PHY_CTRL_REG,
1065                            PHY_Enable_Auto_Nego | PHY_Restart_Auto_Nego);
1066                 udelay(100);
1067
1068                 /* wait for auto-negotiation process */
1069                 for (i = 10000; i > 0; i--) {
1070                         /* check if auto-negotiation complete */
1071                         if (mdio_read(PHY_STAT_REG) & PHY_Auto_Nego_Comp) {
1072                                 udelay(100);
1073                                 option = RTL_R8(PHYstatus);
1074                                 if (option & _1000bpsF) {
1075 #ifdef DEBUG_RTL8169
1076                                         printf("%s: 1000Mbps Full-duplex operation.\n",
1077                                                name);
1078 #endif
1079                                 } else {
1080 #ifdef DEBUG_RTL8169
1081                                         printf("%s: %sMbps %s-duplex operation.\n",
1082                                                name,
1083                                                (option & _100bps) ? "100" :
1084                                                "10",
1085                                                (option & FullDup) ? "Full" :
1086                                                "Half");
1087 #endif
1088                                 }
1089                                 break;
1090                         } else {
1091                                 udelay(100);
1092                         }
1093                 }               /* end for-loop to wait for auto-negotiation process */
1094
1095         } else {
1096                 udelay(100);
1097 #ifdef DEBUG_RTL8169
1098                 printf
1099                     ("%s: 1000Mbps Full-duplex operation, TBI Link %s!\n",
1100                      name,
1101                      (RTL_R32(TBICSR) & TBILinkOK) ? "OK" : "Failed");
1102 #endif
1103         }
1104
1105
1106         tpc->RxDescArray = rtl_alloc_descs(NUM_RX_DESC);
1107         if (!tpc->RxDescArray)
1108                 return -ENOMEM;
1109
1110         tpc->TxDescArray = rtl_alloc_descs(NUM_TX_DESC);
1111         if (!tpc->TxDescArray)
1112                 return -ENOMEM;
1113
1114         return 0;
1115 }
1116
1117 #ifndef CONFIG_DM_ETH
1118 int rtl8169_initialize(bd_t *bis)
1119 {
1120         pci_dev_t devno;
1121         int card_number = 0;
1122         struct eth_device *dev;
1123         u32 iobase;
1124         int idx=0;
1125
1126         while(1){
1127                 unsigned int region;
1128                 u16 device;
1129                 int err;
1130
1131                 /* Find RTL8169 */
1132                 if ((devno = pci_find_devices(supported, idx++)) < 0)
1133                         break;
1134
1135                 pci_read_config_word(devno, PCI_DEVICE_ID, &device);
1136                 switch (device) {
1137                 case 0x8168:
1138                         region = 2;
1139                         break;
1140
1141                 default:
1142                         region = 1;
1143                         break;
1144                 }
1145
1146                 pci_read_config_dword(devno, PCI_BASE_ADDRESS_0 + (region * 4), &iobase);
1147                 iobase &= ~0xf;
1148
1149                 debug ("rtl8169: REALTEK RTL8169 @0x%x\n", iobase);
1150
1151                 dev = (struct eth_device *)malloc(sizeof *dev);
1152                 if (!dev) {
1153                         printf("Can not allocate memory of rtl8169\n");
1154                         break;
1155                 }
1156
1157                 memset(dev, 0, sizeof(*dev));
1158                 sprintf (dev->name, "RTL8169#%d", card_number);
1159
1160                 dev->priv = (void *)(unsigned long)devno;
1161                 dev->iobase = (int)pci_mem_to_phys(devno, iobase);
1162
1163                 dev->init = rtl_reset;
1164                 dev->halt = rtl_halt;
1165                 dev->send = rtl_send;
1166                 dev->recv = rtl_recv;
1167
1168                 err = rtl_init(dev->iobase, dev->name, dev->enetaddr);
1169                 if (err < 0) {
1170                         printf(pr_fmt("failed to initialize card: %d\n"), err);
1171                         free(dev);
1172                         continue;
1173                 }
1174
1175                 eth_register (dev);
1176
1177                 card_number++;
1178         }
1179         return card_number;
1180 }
1181 #endif
1182
1183 #ifdef CONFIG_DM_ETH
1184 static int rtl8169_eth_probe(struct udevice *dev)
1185 {
1186         struct pci_child_platdata *pplat = dev_get_parent_platdata(dev);
1187         struct rtl8169_private *priv = dev_get_priv(dev);
1188         struct eth_pdata *plat = dev_get_platdata(dev);
1189         u32 iobase;
1190         int region;
1191         int ret;
1192
1193         debug("rtl8169: REALTEK RTL8169 @0x%x\n", iobase);
1194         switch (pplat->device) {
1195         case 0x8168:
1196                 region = 2;
1197                 break;
1198         default:
1199                 region = 1;
1200                 break;
1201         }
1202         dm_pci_read_config32(dev, PCI_BASE_ADDRESS_0 + region * 4, &iobase);
1203         iobase &= ~0xf;
1204         priv->iobase = (int)dm_pci_mem_to_phys(dev, iobase);
1205
1206         ret = rtl_init(priv->iobase, dev->name, plat->enetaddr);
1207         if (ret < 0) {
1208                 printf(pr_fmt("failed to initialize card: %d\n"), ret);
1209                 return ret;
1210         }
1211
1212         return 0;
1213 }
1214
1215 static const struct eth_ops rtl8169_eth_ops = {
1216         .start  = rtl8169_eth_start,
1217         .send   = rtl8169_eth_send,
1218         .recv   = rtl8169_eth_recv,
1219         .stop   = rtl8169_eth_stop,
1220         .write_hwaddr = rtl8169_write_hwaddr,
1221 };
1222
1223 static const struct udevice_id rtl8169_eth_ids[] = {
1224         { .compatible = "realtek,rtl8169" },
1225         { }
1226 };
1227
1228 U_BOOT_DRIVER(eth_rtl8169) = {
1229         .name   = "eth_rtl8169",
1230         .id     = UCLASS_ETH,
1231         .of_match = rtl8169_eth_ids,
1232         .probe  = rtl8169_eth_probe,
1233         .ops    = &rtl8169_eth_ops,
1234         .priv_auto_alloc_size = sizeof(struct rtl8169_private),
1235         .platdata_auto_alloc_size = sizeof(struct eth_pdata),
1236 };
1237
1238 U_BOOT_PCI_DEVICE(eth_rtl8169, supported);
1239 #endif