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