sam3 eth: consider PHY auto-negotiation results when initializing emac.
[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, 0x45, 0x56, 0x78, 0x9a, 0xbc };
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         /* Receiver interrupt */
113         if ((isr & EMAC_RX_INTS))
114         {
115                 if (isr & BV(EMAC_RCOMP))
116                         event_do(&recv_wait);
117                 EMAC_RSR = EMAC_RX_INTS;
118         }
119         /* Transmitter interrupt */
120         if (isr & EMAC_TX_INTS)
121         {
122                 if (isr & BV(EMAC_TCOMP))
123                         event_do(&send_wait);
124                 EMAC_TSR = EMAC_TX_INTS;
125         }
126         //AIC_EOICR = 0;
127 }
128
129 /*
130  * \brief Read contents of PHY register.
131  *
132  * \param reg PHY register number.
133  *
134  * \return Contents of the specified register.
135  */
136 static uint16_t phy_hw_read(uint8_t phy_addr, reg8_t reg)
137 {
138         // PHY read command.
139         EMAC_MAN = EMAC_SOF | EMAC_RW_READ
140                 | ((phy_addr << EMAC_PHYA_SHIFT) & EMAC_PHYA)
141                 | ((reg  << EMAC_REGA_SHIFT) & EMAC_REGA)
142                 | EMAC_CODE;
143
144         // Wait until PHY logic completed.
145         while (!(EMAC_NSR & BV(EMAC_IDLE)))
146                 cpu_relax();
147
148         // Get data from PHY maintenance register.
149         return (uint16_t)(EMAC_MAN & EMAC_DATA);
150 }
151
152 #if 0
153 /*
154  * \brief Write value to PHY register.
155  *
156  * \param reg PHY register number.
157  * \param val Value to write.
158  */
159 static void phy_hw_write(uint8_t phy_addr, reg8_t reg, uint16_t val)
160 {
161         // PHY write command.
162         EMAC_MAN = EMAC_SOF | EMAC_RW_WRITE
163                 | ((phy_addr << EMAC_PHYA_SHIFT) & EMAC_PHYA)
164                 | ((reg  << EMAC_REGA_SHIFT) & EMAC_REGA)
165                 | EMAC_CODE | val;
166
167         // Wait until PHY logic completed.
168         while (!(EMAC_NSR & BV(EMAC_IDLE)))
169                 cpu_relax();
170 }
171 #endif
172
173 /*
174  * Check link speed and duplex as negotiated by the PHY
175  * and configure CPU EMAC accordingly.
176  * Requires active PHY maintenance mode.
177  */
178 static void emac_autoNegotiation(void)
179 {
180         uint16_t reg;
181         time_t start;
182
183         // Wait for auto-negotation to complete
184         start = timer_clock();
185         do {
186                 reg = phy_hw_read(NIC_PHY_ADDR, NIC_PHY_BMSR);
187                 if (timer_clock() - start > 2000)
188                 {
189                         kprintf("eth error: auto-negotiation timeout\n");
190                         return;
191                 }
192         }
193         while (!(reg & NIC_PHY_BMSR_ANCOMPL));
194
195         reg = phy_hw_read(NIC_PHY_ADDR, NIC_PHY_ANLPAR);
196
197         if ((reg & NIC_PHY_ANLPAR_TX_FDX) || (reg & NIC_PHY_ANLPAR_TX_HDX))
198         {
199                 LOG_INFO("eth: 100BASE-TX\n");
200                 EMAC_NCFGR |= BV(EMAC_SPD);
201         }
202         else
203         {
204                 LOG_INFO("eth: 10BASE-T\n");
205                 EMAC_NCFGR &= ~BV(EMAC_SPD);
206         }
207
208         if ((reg & NIC_PHY_ANLPAR_TX_FDX) || (reg & NIC_PHY_ANLPAR_10_FDX))
209         {
210                 LOG_INFO("eth: full duplex\n");
211                 EMAC_NCFGR |= BV(EMAC_FD);
212         }
213         else
214         {
215                 LOG_INFO("eth: half duplex\n");
216                 EMAC_NCFGR &= ~BV(EMAC_FD);
217         }
218 }
219
220
221 static int emac_reset(void)
222 {
223 #if CPU_ARM_AT91
224         // Enable devices
225         PMC_PCER = BV(PIOA_ID);
226         PMC_PCER = BV(PIOB_ID);
227         PMC_PCER = BV(EMAC_ID);
228
229         // Disable TESTMODE and RMII
230         PIOB_PUDR = BV(PHY_RXDV_TESTMODE_BIT);
231         PIOB_PUDR = BV(PHY_COL_RMII_BIT);
232
233         // Disable PHY power down.
234         PIOB_PER  = BV(PHY_PWRDN_BIT);
235         PIOB_OER  = BV(PHY_PWRDN_BIT);
236         PIOB_CODR = BV(PHY_PWRDN_BIT);
237 #else
238         pmc_periphEnable(PIOA_ID);
239         pmc_periphEnable(PIOB_ID);
240         pmc_periphEnable(PIOC_ID);
241         pmc_periphEnable(PIOD_ID);
242         pmc_periphEnable(EMAC_ID);
243
244         // Disable TESTMODE and RMII
245         PIOC_PUDR = BV(PHY_RXDV_TESTMODE_BIT);
246
247         // Disable PHY power down.
248         PIOD_PER  = BV(PHY_PWRDN_BIT);
249         PIOD_OER  = BV(PHY_PWRDN_BIT);
250         PIOD_CODR = BV(PHY_PWRDN_BIT);
251 #endif
252
253         // Toggle external hardware reset pin.
254         RSTC_MR = RSTC_KEY | (1 << RSTC_ERSTL_SHIFT) | BV(RSTC_URSTEN);
255         RSTC_CR = RSTC_KEY | BV(RSTC_EXTRST);
256
257         while ((RSTC_SR & BV(RSTC_NRSTL)) == 0)
258                 cpu_relax();
259
260         // Configure MII ports.
261 #if CPU_ARM_AT91
262         PIOB_ASR = PHY_MII_PINS;
263         PIOB_BSR = 0;
264         PIOB_PDR = PHY_MII_PINS;
265
266         // Enable receive and transmit clocks.
267         EMAC_USRIO = BV(EMAC_CLKEN);
268 #else
269         PIO_PERIPH_SEL(PIOB_BASE, PHY_MII_PINS_PORTB, PIO_PERIPH_A);
270         PIOB_PDR = PHY_MII_PINS_PORTB;
271
272         PIO_PERIPH_SEL(PIOC_BASE, PHY_MII_PINS_PORTC, PIO_PERIPH_A);
273         PIOC_PDR = PHY_MII_PINS_PORTC;
274
275         // Enable receive, transmit clocks and RMII mode.
276         EMAC_USRIO = BV(EMAC_CLKEN) | BV(EMAC_RMII);
277 #endif
278
279         // Enable management port.
280         EMAC_NCR |= BV(EMAC_MPE);
281         EMAC_NCFGR |= EMAC_CLK_HCLK_64;
282
283         // Set local MAC address.
284         EMAC_SA1L = (mac_addr[3] << 24) | (mac_addr[2] << 16) |
285                                 (mac_addr[1] << 8) | mac_addr[0];
286         EMAC_SA1H = (mac_addr[5] << 8) | mac_addr[4];
287
288         emac_autoNegotiation();
289
290         // Disable management port.
291         EMAC_NCR &= ~BV(EMAC_MPE);
292
293         return 0;
294 }
295
296
297 static int emac_start(void)
298 {
299         uint32_t addr;
300         int i;
301
302         for (i = 0; i < EMAC_RX_DESCRIPTORS; i++)
303         {
304                 addr = (uint32_t)(rx_buf + (i * EMAC_RX_BUFSIZ));
305                 rx_buf_tab[i].addr = addr & BUF_ADDRMASK;
306         }
307         rx_buf_tab[EMAC_RX_DESCRIPTORS - 1].addr |= RXBUF_WRAP;
308
309         for (i = 0; i < EMAC_TX_DESCRIPTORS; i++)
310         {
311                 addr = (uint32_t)(tx_buf + (i * EMAC_TX_BUFSIZ));
312                 tx_buf_tab[i].addr = addr & BUF_ADDRMASK;
313                 tx_buf_tab[i].stat = TXS_USED;
314         }
315         tx_buf_tab[EMAC_TX_DESCRIPTORS - 1].stat = TXS_USED | TXS_WRAP;
316
317         /* Tell the EMAC where to find the descriptors. */
318         EMAC_RBQP = (uint32_t)rx_buf_tab;
319         EMAC_TBQP = (uint32_t)tx_buf_tab;
320
321         /* Clear receiver status. */
322         EMAC_RSR = BV(EMAC_OVR) | BV(EMAC_REC) | BV(EMAC_BNA);
323
324         /* Copy all frames and discard FCS. */
325         EMAC_NCFGR |= BV(EMAC_CAF) | BV(EMAC_DRFCS);
326
327         /* Enable receiver, transmitter and statistics. */
328         EMAC_NCR |= BV(EMAC_TE) | BV(EMAC_RE) | BV(EMAC_WESTAT);
329
330         return 0;
331 }
332
333 ssize_t eth_putFrame(const uint8_t *buf, size_t len)
334 {
335         size_t wr_len;
336
337         if (UNLIKELY(!len))
338                 return -1;
339         ASSERT(len <= sizeof(tx_buf));
340
341         /* Check if the transmit buffer is available */
342         while (!(tx_buf_tab[tx_buf_idx].stat & TXS_USED))
343                 event_wait(&send_wait);
344
345         /* Copy the data into the buffer and prepare descriptor */
346         wr_len = MIN(len, (size_t)EMAC_TX_BUFSIZ - tx_buf_offset);
347         memcpy((uint8_t *)tx_buf_tab[tx_buf_idx].addr + tx_buf_offset,
348                         buf, wr_len);
349         tx_buf_offset += wr_len;
350
351         return wr_len;
352 }
353
354 void eth_sendFrame(void)
355 {
356         tx_buf_tab[tx_buf_idx].stat = (tx_buf_offset & TXS_LENGTH_FRAME) |
357                 TXS_LAST_BUFF |
358                 ((tx_buf_idx == EMAC_TX_DESCRIPTORS - 1) ?  TXS_WRAP : 0);
359         EMAC_NCR |= BV(EMAC_TSTART);
360
361         tx_buf_offset = 0;
362         if (++tx_buf_idx >= EMAC_TX_DESCRIPTORS)
363                 tx_buf_idx = 0;
364 }
365
366 ssize_t eth_send(const uint8_t *buf, size_t len)
367  {
368         if (UNLIKELY(!len))
369                 return -1;
370
371         len = eth_putFrame(buf, len);
372         eth_sendFrame();
373
374         return len;
375 }
376
377 static void eth_buf_realign(int idx)
378 {
379         /* Empty buffer found. Realign. */
380         do {
381                 rx_buf_tab[rx_buf_idx].addr &= ~RXBUF_OWNERSHIP;
382                 if (++rx_buf_idx >= EMAC_RX_BUFFERS)
383                         rx_buf_idx = 0;
384         } while (idx != rx_buf_idx);
385 }
386
387 static size_t __eth_getFrameLen(void)
388 {
389         int idx, n = EMAC_RX_BUFFERS;
390
391 skip:
392         /* Skip empty buffers */
393         while ((n > 0) && !(rx_buf_tab[rx_buf_idx].addr & RXBUF_OWNERSHIP))
394         {
395                 if (++rx_buf_idx >= EMAC_RX_BUFFERS)
396                         rx_buf_idx = 0;
397                 n--;
398         }
399         if (UNLIKELY(!n))
400         {
401                 LOG_INFO("no frame found\n");
402                 return 0;
403         }
404         /* Search the start of frame and cleanup fragments */
405         while ((n > 0) && (rx_buf_tab[rx_buf_idx].addr & RXBUF_OWNERSHIP) &&
406                         !(rx_buf_tab[rx_buf_idx].stat & RXS_SOF))
407         {
408                 rx_buf_tab[rx_buf_idx].addr &= ~RXBUF_OWNERSHIP;
409                 if (++rx_buf_idx >= EMAC_RX_BUFFERS)
410                         rx_buf_idx = 0;
411                 n--;
412         }
413         if (UNLIKELY(!n))
414         {
415                 LOG_INFO("no SOF found\n");
416                 return 0;
417         }
418         /* Search end of frame to evaluate the total frame size */
419         idx = rx_buf_idx;
420 restart:
421         while (n > 0)
422         {
423                 if (UNLIKELY(!(rx_buf_tab[idx].addr & RXBUF_OWNERSHIP)))
424                 {
425                         /* Empty buffer found. Realign. */
426                         eth_buf_realign(idx);
427                         goto skip;
428                 }
429                 if (rx_buf_tab[idx].stat & RXS_EOF)
430                         return rx_buf_tab[idx].stat & RXS_LENGTH_FRAME;
431                 if (UNLIKELY((idx != rx_buf_idx) &&
432                                 (rx_buf_tab[idx].stat & RXS_SOF)))
433                 {
434                         /* Another start of frame found. Realign. */
435                         eth_buf_realign(idx);
436                         goto restart;
437                 }
438                 if (++idx >= EMAC_RX_BUFFERS)
439                         idx = 0;
440                 n--;
441         }
442         LOG_INFO("no EOF found\n");
443         return 0;
444 }
445
446 size_t eth_getFrameLen(void)
447 {
448         size_t len;
449
450         /* Check if there is at least one available frame in the buffer */
451         while (1)
452         {
453                 len = __eth_getFrameLen();
454                 if (LIKELY(len))
455                         break;
456                 /* Wait for RX interrupt */
457                 event_wait(&recv_wait);
458         }
459         return len;
460 }
461
462 ssize_t eth_getFrame(uint8_t *buf, size_t len)
463 {
464         uint8_t *addr;
465         size_t rd_len = 0;
466
467         if (UNLIKELY(!len))
468                 return -1;
469         ASSERT(len <= sizeof(rx_buf));
470
471         /* Copy data from the RX buffer */
472         addr = (uint8_t *)(rx_buf_tab[rx_buf_idx].addr & BUF_ADDRMASK);
473         if (addr + len > &rx_buf[countof(rx_buf)])
474         {
475                 size_t count = &rx_buf[countof(rx_buf)] - addr;
476
477                 memcpy(buf, addr, count);
478                 memcpy(buf + count, rx_buf, len - count);
479         }
480         else
481         {
482                 memcpy(buf, addr, len);
483         }
484         /* Update descriptors */
485         while (rd_len < len)
486         {
487                 if (len - rd_len >= EMAC_RX_BUFSIZ)
488                         rd_len += EMAC_RX_BUFSIZ;
489                 else
490                         rd_len += len - rd_len;
491                 if (UNLIKELY(!(rx_buf_tab[rx_buf_idx].addr & RXBUF_OWNERSHIP)))
492                 {
493                         LOG_INFO("bad frame found\n");
494                         return 0;
495                 }
496                 rx_buf_tab[rx_buf_idx].addr &= ~RXBUF_OWNERSHIP;
497                 if (++rx_buf_idx >= EMAC_RX_DESCRIPTORS)
498                         rx_buf_idx = 0;
499         }
500
501         return rd_len;
502 }
503
504 ssize_t eth_recv(uint8_t *buf, size_t len)
505 {
506         if (UNLIKELY(!len))
507                 return -1;
508         len = MIN(len, eth_getFrameLen());
509         return len ? eth_getFrame(buf, len) : 0;
510 }
511
512 int eth_init()
513 {
514         cpu_flags_t flags;
515
516         emac_reset();
517         emac_start();
518
519         event_initGeneric(&recv_wait);
520         event_initGeneric(&send_wait);
521
522         // Register interrupt vector
523         IRQ_SAVE_DISABLE(flags);
524
525         /* Disable all emac interrupts */
526         EMAC_IDR = 0xFFFFFFFF;
527
528 #if CPU_ARM_AT91
529         // TODO: define sysirq_set...
530         /* Set the vector. */
531         AIC_SVR(EMAC_ID) = emac_irqHandler;
532         /* Initialize to edge triggered with defined priority. */
533         AIC_SMR(EMAC_ID) = AIC_SRCTYPE_INT_EDGE_TRIGGERED;
534         /* Clear pending interrupt */
535         AIC_ICCR = BV(EMAC_ID);
536         /* Enable the system IRQ */
537         AIC_IECR = BV(EMAC_ID);
538 #else
539         sysirq_setHandler(INT_EMAC, emac_irqHandler);
540 #endif
541
542         /* Enable interrupts */
543         EMAC_IER = EMAC_RX_INTS | EMAC_TX_INTS;
544
545         IRQ_RESTORE(flags);
546
547         return 0;
548 }