sam3 eth: fix phy initialization.
[bertos.git] / bertos / cpu / cortex-m3 / drv / eth_sam3.c
1 /**
2   * \file
3   * <!--
4   * This file is part of BeRTOS.
5   *
6   * Bertos is free software; you can redistribute it and/or modify
7   * it under the terms of the GNU General Public License as published by
8   * the Free Software Foundation; either version 2 of the License, or
9   * (at your option) any later version.
10   *
11   * This program is distributed in the hope that it will be useful,
12   * but WITHOUT ANY WARRANTY; without even the implied warranty of
13   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   * GNU General Public License for more details.
15   *
16   * You should have received a copy of the GNU General Public License
17   * along with this program; if not, write to the Free Software
18   * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19   *
20   * As a special exception, you may use this file as part of a free software
21   * library without restriction.  Specifically, if other files instantiate
22   * templates or use macros or inline functions from this file, or you compile
23   * this file and link it with other files to produce an executable, this
24   * file does not by itself cause the resulting executable to be covered by
25   * the GNU General Public License.  This exception does not however
26   * invalidate any other reasons why the executable file might be covered by
27   * the GNU General Public License.
28   *
29   * Copyright 2010,2011 Develer S.r.l. (http://www.develer.com/)
30   * All Rights Reserved.
31   * -->
32   *
33   * \brief EMAC driver for AT91SAM family with Davicom 9161A phy.
34   *
35   * \author Daniele Basile <asterix@develer.com>
36   * \author Andrea Righi <arighi@develer.com>
37   * \author Stefano Fedrigo <aleph@develer.com>
38   */
39
40 #include "cfg/cfg_eth.h"
41
42 #define LOG_LEVEL  ETH_LOG_LEVEL
43 #define LOG_FORMAT ETH_LOG_FORMAT
44
45 #include <cfg/log.h>
46
47 #include <cfg/debug.h>
48 #include <cfg/log.h>
49 #include <cfg/macros.h>
50 #include <cfg/compiler.h>
51
52 // TODO: unify includes
53 //#include <io/at91sam7.h>
54 //#include <io/arm.h>
55 //#include <io/include.h>
56 #include <io/sam3.h>
57 #include <drv/irq_cm3.h>
58
59 #include <cpu/power.h>
60 #include <cpu/types.h>
61 #include <cpu/irq.h>
62
63 #include <drv/timer.h>
64 #include <drv/eth.h>
65
66 #include <mware/event.h>
67
68 #include <string.h>
69
70 #include "eth_sam3.h"
71
72 #define EMAC_RX_INTS    (BV(EMAC_RCOMP) | BV(EMAC_ROVR) | BV(EMAC_RXUBR))
73 #define EMAC_TX_INTS    (BV(EMAC_TCOMP) | BV(EMAC_TXUBR) | BV(EMAC_RLEX))
74
75 /*
76  * MAC address configuration (please change this in your project!).
77  *
78  * TODO: make this paramater user-configurable from the Wizard.
79  */
80 const uint8_t mac_addr[] = { 0x00, 0x23, 0x54, 0x6a, 0x77, 0x55 };
81
82 /* Silent Doxygen bug... */
83 #ifndef __doxygen__
84 /*
85  * NOTE: this buffer should be declared as 'volatile' because it is read by the
86  * hardware. However, this is accessed only via memcpy() that should guarantee
87  * coherency when copying from/to buffers.
88  */
89 static uint8_t tx_buf[EMAC_TX_BUFFERS * EMAC_TX_BUFSIZ] ALIGNED(8);
90 static volatile BufDescriptor tx_buf_tab[EMAC_TX_DESCRIPTORS] ALIGNED(8);
91
92 /*
93  * NOTE: this buffer should be declared as 'volatile' because it is wrote by
94  * the hardware. However, this is accessed only via memcpy() that should
95  * guarantee coherency when copying from/to buffers.
96  */
97 static uint8_t rx_buf[EMAC_RX_BUFFERS * EMAC_RX_BUFSIZ] ALIGNED(8);
98 static volatile BufDescriptor rx_buf_tab[EMAC_RX_DESCRIPTORS] ALIGNED(8);
99 #endif
100
101 static int tx_buf_idx;
102 static int tx_buf_offset;
103 static int rx_buf_idx;
104
105 static Event recv_wait, send_wait;
106
107 static DECLARE_ISR(emac_irqHandler)
108 {
109         /* Read interrupt status and disable interrupts. */
110         uint32_t isr = EMAC_ISR;
111
112         kprintf("irq: %x\n", isr);
113
114         /* Receiver interrupt */
115         if ((isr & EMAC_RX_INTS))
116         {
117                 kprintf("emac: rx %x\n", isr);
118                 if (isr & BV(EMAC_RCOMP))
119                         event_do(&recv_wait);
120                 EMAC_RSR = EMAC_RX_INTS;
121         }
122         /* Transmitter interrupt */
123         if (isr & EMAC_TX_INTS)
124         {
125                 if (isr & BV(EMAC_TCOMP))
126                 {
127                         kprintf("emac: tcomp\n");
128                         event_do(&send_wait);
129                 }
130                 if (isr & BV(EMAC_RLEX))
131                         kprintf("emac: rlex\n");
132                 EMAC_TSR = EMAC_TX_INTS;
133         }
134         //AIC_EOICR = 0;
135 }
136
137 /*
138  * \brief Read contents of PHY register.
139  *
140  * \param reg PHY register number.
141  *
142  * \return Contents of the specified register.
143  */
144 static uint16_t phy_hw_read(uint8_t phy_addr, reg8_t reg)
145 {
146         // PHY read command.
147         EMAC_MAN = EMAC_SOF | EMAC_RW_READ
148                 | ((phy_addr << EMAC_PHYA_SHIFT) & EMAC_PHYA)
149                 | ((reg  << EMAC_REGA_SHIFT) & EMAC_REGA)
150                 | EMAC_CODE;
151
152         // Wait until PHY logic completed.
153         while (!(EMAC_NSR & BV(EMAC_IDLE)))
154                 cpu_relax();
155
156         // Get data from PHY maintenance register.
157         return (uint16_t)(EMAC_MAN & EMAC_DATA);
158 }
159
160 /*
161  * \brief Write value to PHY register.
162  *
163  * \param reg PHY register number.
164  * \param val Value to write.
165  */
166 static void phy_hw_write(uint8_t phy_addr, reg8_t reg, uint16_t val)
167 {
168         // PHY write command.
169         EMAC_MAN = EMAC_SOF | EMAC_RW_WRITE
170                 | ((phy_addr << EMAC_PHYA_SHIFT) & EMAC_PHYA)
171                 | ((reg  << EMAC_REGA_SHIFT) & EMAC_REGA)
172                 | EMAC_CODE | val;
173
174         // Wait until PHY logic completed.
175         while (!(EMAC_NSR & BV(EMAC_IDLE)))
176                 cpu_relax();
177 }
178
179 static int emac_reset(void)
180 {
181         uint16_t phy_cr;
182         unsigned i;
183
184 #if CPU_ARM_AT91
185         // Enable devices
186         PMC_PCER = BV(PIOA_ID);
187         PMC_PCER = BV(PIOB_ID);
188         PMC_PCER = BV(EMAC_ID);
189
190         // Disable TESTMODE and RMII
191         PIOB_PUDR = BV(PHY_RXDV_TESTMODE_BIT);
192         PIOB_PUDR = BV(PHY_COL_RMII_BIT);
193
194         // Disable PHY power down.
195         PIOB_PER  = BV(PHY_PWRDN_BIT);
196         PIOB_OER  = BV(PHY_PWRDN_BIT);
197         PIOB_CODR = BV(PHY_PWRDN_BIT);
198 #else
199         pmc_periphEnable(PIOA_ID);
200         pmc_periphEnable(PIOB_ID);
201         pmc_periphEnable(PIOC_ID);
202         pmc_periphEnable(PIOD_ID);
203         pmc_periphEnable(EMAC_ID);
204
205         // Disable TESTMODE and RMII
206         PIOC_PUDR = BV(PHY_RXDV_TESTMODE_BIT);
207
208         // Disable PHY power down.
209         PIOD_PER  = BV(PHY_PWRDN_BIT);
210         PIOD_OER  = BV(PHY_PWRDN_BIT);
211         PIOD_CODR = BV(PHY_PWRDN_BIT);
212 #endif
213
214         // Toggle external hardware reset pin.
215         RSTC_MR = RSTC_KEY | (1 << RSTC_ERSTL_SHIFT) | BV(RSTC_URSTEN);
216         RSTC_CR = RSTC_KEY | BV(RSTC_EXTRST);
217
218         while ((RSTC_SR & BV(RSTC_NRSTL)) == 0)
219                 cpu_relax();
220
221         // Configure MII ports.
222 #if CPU_ARM_AT91
223         PIOB_ASR = PHY_MII_PINS;
224         PIOB_BSR = 0;
225         PIOB_PDR = PHY_MII_PINS;
226
227         // Enable receive and transmit clocks.
228         EMAC_USRIO = BV(EMAC_CLKEN);
229 #else
230         PIO_PERIPH_SEL(PIOB_BASE, PHY_MII_PINS_PORTB, PIO_PERIPH_A);
231         PIOB_PDR = PHY_MII_PINS_PORTB;
232
233         PIO_PERIPH_SEL(PIOC_BASE, PHY_MII_PINS_PORTC, PIO_PERIPH_A);
234         PIOC_PDR = PHY_MII_PINS_PORTC;
235
236         // Enable receive, transmit clocks and RMII mode.
237         EMAC_USRIO = BV(EMAC_CLKEN) | BV(EMAC_RMII);
238 #endif
239
240         // Enable management port.
241         EMAC_NCR |= BV(EMAC_MPE);
242         EMAC_NCFGR |= EMAC_CLK_HCLK_64;
243
244         // Set local MAC address.
245         EMAC_SA1L = (mac_addr[3] << 24) | (mac_addr[2] << 16) |
246                                 (mac_addr[1] << 8) | mac_addr[0];
247         EMAC_SA1H = (mac_addr[5] << 8) | mac_addr[4];
248
249         // Wait for PHY ready
250         timer_delay(500);
251
252 #if 0 // debug test
253         for (;;)
254         {
255                 for (i = 0; i < 32; i++)
256                 {
257                         // Clear MII isolate.
258                         phy_hw_read(i, NIC_PHY_BMCR);
259                         phy_cr = phy_hw_read(i, NIC_PHY_BMCR);
260
261                         phy_cr &= ~NIC_PHY_BMCR_ISOLATE;
262                         phy_hw_write(i, NIC_PHY_BMCR, phy_cr);
263
264                         phy_cr = phy_hw_read(i, NIC_PHY_BMCR);
265
266                         LOG_INFO("%s: PHY ID %d %#04x %#04x\n",
267                                         __func__, i,
268                                         phy_hw_read(i, NIC_PHY_ID1), phy_hw_read(i, NIC_PHY_ID2));
269                 }
270                 timer_delay(1000);
271         }
272 #endif
273
274         // Clear MII isolate.
275         //phy_hw_read(NIC_PHY_ADDR, NIC_PHY_BMCR);
276         phy_cr = phy_hw_read(NIC_PHY_ADDR, NIC_PHY_BMCR);
277
278         phy_cr &= ~NIC_PHY_BMCR_ISOLATE;
279         phy_hw_write(NIC_PHY_ADDR, NIC_PHY_BMCR, phy_cr);
280
281         //phy_cr = phy_hw_read(NIC_PHY_ADDR, NIC_PHY_BMCR);
282
283         LOG_INFO("%s: PHY ID %#04x %#04x\n",
284                 __func__,
285                 phy_hw_read(NIC_PHY_ADDR, NIC_PHY_ID1), phy_hw_read(NIC_PHY_ADDR, NIC_PHY_ID2));
286
287         // Disable management port.
288         EMAC_NCR &= ~BV(EMAC_MPE);
289
290         return 0;
291 }
292
293 static int emac_start(void)
294 {
295         uint32_t addr;
296         int i;
297
298         for (i = 0; i < EMAC_RX_DESCRIPTORS; i++)
299         {
300                 addr = (uint32_t)(rx_buf + (i * EMAC_RX_BUFSIZ));
301                 rx_buf_tab[i].addr = addr & BUF_ADDRMASK;
302         }
303         rx_buf_tab[EMAC_RX_DESCRIPTORS - 1].addr |= RXBUF_WRAP;
304
305         for (i = 0; i < EMAC_TX_DESCRIPTORS; i++)
306         {
307                 addr = (uint32_t)(tx_buf + (i * EMAC_TX_BUFSIZ));
308                 tx_buf_tab[i].addr = addr & BUF_ADDRMASK;
309                 tx_buf_tab[i].stat = TXS_USED;
310         }
311         tx_buf_tab[EMAC_TX_DESCRIPTORS - 1].stat = TXS_USED | TXS_WRAP;
312
313         /* Tell the EMAC where to find the descriptors. */
314         EMAC_RBQP = (uint32_t)rx_buf_tab;
315         EMAC_TBQP = (uint32_t)tx_buf_tab;
316
317         /* Clear receiver status. */
318         EMAC_RSR = BV(EMAC_OVR) | BV(EMAC_REC) | BV(EMAC_BNA);
319
320         /* Copy all frames and discard FCS. */
321         EMAC_NCFGR |= BV(EMAC_CAF) | BV(EMAC_DRFCS);
322
323         /* Enable receiver, transmitter and statistics. */
324         EMAC_NCR |= BV(EMAC_TE) | BV(EMAC_RE) | BV(EMAC_WESTAT);
325
326         return 0;
327 }
328
329 ssize_t eth_putFrame(const uint8_t *buf, size_t len)
330 {
331         size_t wr_len;
332
333         if (UNLIKELY(!len))
334                 return -1;
335         ASSERT(len <= sizeof(tx_buf));
336
337         /* Check if the transmit buffer is available */
338         while (!(tx_buf_tab[tx_buf_idx].stat & TXS_USED))
339                 event_wait(&send_wait);
340
341         /* Copy the data into the buffer and prepare descriptor */
342         wr_len = MIN(len, (size_t)EMAC_TX_BUFSIZ - tx_buf_offset);
343         memcpy((uint8_t *)tx_buf_tab[tx_buf_idx].addr + tx_buf_offset,
344                         buf, wr_len);
345         tx_buf_offset += wr_len;
346
347         return wr_len;
348 }
349
350 void eth_sendFrame(void)
351 {
352         tx_buf_tab[tx_buf_idx].stat = (tx_buf_offset & TXS_LENGTH_FRAME) |
353                 TXS_LAST_BUFF |
354                 ((tx_buf_idx == EMAC_TX_DESCRIPTORS - 1) ?  TXS_WRAP : 0);
355         EMAC_NCR |= BV(EMAC_TSTART);
356
357         tx_buf_offset = 0;
358         if (++tx_buf_idx >= EMAC_TX_DESCRIPTORS)
359                 tx_buf_idx = 0;
360 }
361
362 ssize_t eth_send(const uint8_t *buf, size_t len)
363  {
364         if (UNLIKELY(!len))
365                 return -1;
366
367         len = eth_putFrame(buf, len);
368         eth_sendFrame();
369
370         return len;
371 }
372
373 static void eth_buf_realign(int idx)
374 {
375         /* Empty buffer found. Realign. */
376         do {
377                 rx_buf_tab[rx_buf_idx].addr &= ~RXBUF_OWNERSHIP;
378                 if (++rx_buf_idx >= EMAC_RX_BUFFERS)
379                         rx_buf_idx = 0;
380         } while (idx != rx_buf_idx);
381 }
382
383 static size_t __eth_getFrameLen(void)
384 {
385         int idx, n = EMAC_RX_BUFFERS;
386
387 skip:
388         /* Skip empty buffers */
389         while ((n > 0) && !(rx_buf_tab[rx_buf_idx].addr & RXBUF_OWNERSHIP))
390         {
391                 if (++rx_buf_idx >= EMAC_RX_BUFFERS)
392                         rx_buf_idx = 0;
393                 n--;
394         }
395         if (UNLIKELY(!n))
396         {
397                 LOG_INFO("no frame found\n");
398                 return 0;
399         }
400         /* Search the start of frame and cleanup fragments */
401         while ((n > 0) && (rx_buf_tab[rx_buf_idx].addr & RXBUF_OWNERSHIP) &&
402                         !(rx_buf_tab[rx_buf_idx].stat & RXS_SOF))
403         {
404                 rx_buf_tab[rx_buf_idx].addr &= ~RXBUF_OWNERSHIP;
405                 if (++rx_buf_idx >= EMAC_RX_BUFFERS)
406                         rx_buf_idx = 0;
407                 n--;
408         }
409         if (UNLIKELY(!n))
410         {
411                 LOG_INFO("no SOF found\n");
412                 return 0;
413         }
414         /* Search end of frame to evaluate the total frame size */
415         idx = rx_buf_idx;
416 restart:
417         while (n > 0)
418         {
419                 if (UNLIKELY(!(rx_buf_tab[idx].addr & RXBUF_OWNERSHIP)))
420                 {
421                         /* Empty buffer found. Realign. */
422                         eth_buf_realign(idx);
423                         goto skip;
424                 }
425                 if (rx_buf_tab[idx].stat & RXS_EOF)
426                         return rx_buf_tab[idx].stat & RXS_LENGTH_FRAME;
427                 if (UNLIKELY((idx != rx_buf_idx) &&
428                                 (rx_buf_tab[idx].stat & RXS_SOF)))
429                 {
430                         /* Another start of frame found. Realign. */
431                         eth_buf_realign(idx);
432                         goto restart;
433                 }
434                 if (++idx >= EMAC_RX_BUFFERS)
435                         idx = 0;
436                 n--;
437         }
438         LOG_INFO("no EOF found\n");
439         return 0;
440 }
441
442 size_t eth_getFrameLen(void)
443 {
444         size_t len;
445
446         /* Check if there is at least one available frame in the buffer */
447         while (1)
448         {
449                 len = __eth_getFrameLen();
450                 if (LIKELY(len))
451                         break;
452                 /* Wait for RX interrupt */
453                 event_wait(&recv_wait);
454         }
455         return len;
456 }
457
458 ssize_t eth_getFrame(uint8_t *buf, size_t len)
459 {
460         uint8_t *addr;
461         size_t rd_len = 0;
462
463         if (UNLIKELY(!len))
464                 return -1;
465         ASSERT(len <= sizeof(rx_buf));
466
467         /* Copy data from the RX buffer */
468         addr = (uint8_t *)(rx_buf_tab[rx_buf_idx].addr & BUF_ADDRMASK);
469         if (addr + len > &rx_buf[countof(rx_buf)])
470         {
471                 size_t count = &rx_buf[countof(rx_buf)] - addr;
472
473                 memcpy(buf, addr, count);
474                 memcpy(buf + count, rx_buf, len - count);
475         }
476         else
477         {
478                 memcpy(buf, addr, len);
479         }
480         /* Update descriptors */
481         while (rd_len < len)
482         {
483                 if (len - rd_len >= EMAC_RX_BUFSIZ)
484                         rd_len += EMAC_RX_BUFSIZ;
485                 else
486                         rd_len += len - rd_len;
487                 if (UNLIKELY(!(rx_buf_tab[rx_buf_idx].addr & RXBUF_OWNERSHIP)))
488                 {
489                         LOG_INFO("bad frame found\n");
490                         return 0;
491                 }
492                 rx_buf_tab[rx_buf_idx].addr &= ~RXBUF_OWNERSHIP;
493                 if (++rx_buf_idx >= EMAC_RX_DESCRIPTORS)
494                         rx_buf_idx = 0;
495         }
496
497         return rd_len;
498 }
499
500 ssize_t eth_recv(uint8_t *buf, size_t len)
501 {
502         if (UNLIKELY(!len))
503                 return -1;
504         len = MIN(len, eth_getFrameLen());
505         return len ? eth_getFrame(buf, len) : 0;
506 }
507
508 int eth_init()
509 {
510         cpu_flags_t flags;
511
512         emac_reset();
513         emac_start();
514
515         event_initGeneric(&recv_wait);
516         event_initGeneric(&send_wait);
517
518         // Register interrupt vector
519         IRQ_SAVE_DISABLE(flags);
520
521         /* Disable all emac interrupts */
522         EMAC_IDR = 0xFFFFFFFF;
523
524 #if CPU_ARM_AT91
525         // TODO: define sysirq_set...
526         /* Set the vector. */
527         AIC_SVR(EMAC_ID) = emac_irqHandler;
528         /* Initialize to edge triggered with defined priority. */
529         AIC_SMR(EMAC_ID) = AIC_SRCTYPE_INT_EDGE_TRIGGERED;
530         /* Clear pending interrupt */
531         AIC_ICCR = BV(EMAC_ID);
532         /* Enable the system IRQ */
533         AIC_IECR = BV(EMAC_ID);
534 #else
535         sysirq_setHandler(INT_EMAC, emac_irqHandler);
536 #endif
537
538         /* Enable interrupts */
539         EMAC_IER = EMAC_RX_INTS | EMAC_TX_INTS;
540
541         IRQ_RESTORE(flags);
542
543         return 0;
544 }