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