529d7af4e5473b51045ef1ec435e108abc9edc7a
[bertos.git] / bertos / cpu / arm / drv / eth_at91.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 Develer S.r.l. (http://www.develer.com/)
30   * All Rights Reserved.
31   * -->
32   *
33   * \brief EMAC driver for AT91SAM7X Family.
34   *
35   * \author Daniele Basile <asterix@develer.com>
36   * \author Andrea Righi <arighi@develer.com>
37   */
38
39 #include "cfg/cfg_eth.h"
40
41 #define LOG_LEVEL  ETH_LOG_LEVEL
42 #define LOG_FORMAT ETH_LOG_FORMAT
43
44 #include <cfg/log.h>
45
46 #include <cfg/debug.h>
47 #include <cfg/log.h>
48 #include <cfg/macros.h>
49 #include <cfg/compiler.h>
50
51 #include <io/at91sam7.h>
52 #include <io/arm.h>
53
54 #include <cpu/power.h>
55 #include <cpu/types.h>
56 #include <cpu/irq.h>
57
58 #include <drv/timer.h>
59 #include <drv/eth.h>
60
61 #include <mware/event.h>
62
63 #include <string.h>
64
65 #include "eth_at91.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 /*
71  * MAC address configuration (please change this in your project!).
72  *
73  * TODO: make this paramater user-configurable from the Wizard.
74  */
75 const uint8_t mac_addr[] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55 };
76
77 /* Silent Doxygen bug... */
78 #ifndef __doxygen__
79 /*
80  * NOTE: this buffer should be declared as 'volatile' because it is read by the
81  * hardware. However, this is accessed only via memcpy() that should guarantee
82  * coherency when copying from/to buffers.
83  */
84 static uint8_t tx_buf[EMAC_TX_BUFFERS * EMAC_TX_BUFSIZ] ALIGNED(8);
85 static volatile BufDescriptor tx_buf_tab[EMAC_TX_DESCRIPTORS] ALIGNED(8);
86
87 /*
88  * NOTE: this buffer should be declared as 'volatile' because it is wrote by
89  * the hardware. However, this is accessed only via memcpy() that should
90  * guarantee coherency when copying from/to buffers.
91  */
92 static uint8_t rx_buf[EMAC_RX_BUFFERS * EMAC_RX_BUFSIZ] ALIGNED(8);
93 static volatile BufDescriptor rx_buf_tab[EMAC_RX_DESCRIPTORS] ALIGNED(8);
94 #endif
95
96 static int tx_buf_idx;
97 static int tx_buf_offset;
98 static int rx_buf_idx;
99
100 static Event recv_wait, send_wait;
101
102 static DECLARE_ISR(emac_irqHandler)
103 {
104         /* Read interrupt status and disable interrupts. */
105         uint32_t isr = EMAC_ISR;
106
107         /* Receiver interrupt */
108         if ((isr & EMAC_RX_INTS))
109         {
110                 if (isr & BV(EMAC_RCOMP))
111                         event_do(&recv_wait);
112                 EMAC_RSR = EMAC_RX_INTS;
113         }
114         /* Transmitter interrupt */
115         if (isr & EMAC_TX_INTS)
116         {
117                 if (isr & BV(EMAC_TCOMP))
118                         event_do(&send_wait);
119                 EMAC_TSR = EMAC_TX_INTS;
120         }
121         AIC_EOICR = 0;
122 }
123
124 /*
125  * \brief Read contents of PHY register.
126  *
127  * \param reg PHY register number.
128  *
129  * \return Contents of the specified register.
130  */
131 static uint16_t phy_hw_read(reg8_t reg)
132 {
133         // PHY read command.
134         EMAC_MAN = EMAC_SOF | EMAC_RW_READ | (NIC_PHY_ADDR << EMAC_PHYA_SHIFT)
135                         | ((reg  << EMAC_REGA_SHIFT) & EMAC_REGA) | 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 /*
146  * \brief Write value to PHY register.
147  *
148  * \param reg PHY register number.
149  * \param val Value to write.
150  */
151 static void phy_hw_write(reg8_t reg, uint16_t val)
152 {
153         // PHY write command.
154         EMAC_MAN = EMAC_SOF | EMAC_RW_WRITE | (NIC_PHY_ADDR << EMAC_PHYA_SHIFT)
155                         | ((reg  << EMAC_REGA_SHIFT) & EMAC_REGA) | EMAC_CODE | val;
156
157         // Wait until PHY logic completed.
158         while (!(EMAC_NSR & BV(EMAC_IDLE)))
159                 cpu_relax();
160 }
161
162 static int emac_reset(void)
163 {
164         uint16_t phy_cr;
165
166         // Enable devices
167         PMC_PCER = BV(PIOA_ID);
168         PMC_PCER = BV(PIOB_ID);
169         PMC_PCER = BV(EMAC_ID);
170
171         // Disable RMII and TESTMODE by disabling pull-ups.
172         PIOB_PUDR = BV(PHY_COL_RMII_BIT) | BV(PHY_RXDV_TESTMODE_BIT);
173
174         // Disable PHY power down.
175         PIOB_PER  = BV(PHY_PWRDN_BIT);
176         PIOB_OER  = BV(PHY_PWRDN_BIT);
177         PIOB_CODR = BV(PHY_PWRDN_BIT);
178
179         // Toggle external hardware reset pin.
180         RSTC_MR = RSTC_KEY | (1 << RSTC_ERSTL_SHIFT) | BV(RSTC_URSTEN);
181         RSTC_CR = RSTC_KEY | BV(RSTC_EXTRST);
182
183         while ((RSTC_SR & BV(RSTC_NRSTL)) == 0)
184                 cpu_relax();
185
186         // Configure MII port.
187         PIOB_ASR = PHY_MII_PINS;
188         PIOB_BSR = 0;
189         PIOB_PDR = PHY_MII_PINS;
190
191         // Enable receive and transmit clocks.
192         EMAC_USRIO = BV(EMAC_CLKEN);
193
194         // Enable management port.
195         EMAC_NCR |= BV(EMAC_MPE);
196         EMAC_NCFGR |= EMAC_CLK_HCLK_32;
197
198         // Set local MAC address.
199         EMAC_SA1L = (mac_addr[3] << 24) | (mac_addr[2] << 16) |
200                                 (mac_addr[1] << 8) | mac_addr[0];
201         EMAC_SA1H = (mac_addr[5] << 8) | mac_addr[4];
202
203         // Wait for PHY ready
204         timer_delay(255);
205
206         // Clear MII isolate.
207         phy_hw_read(NIC_PHY_BMCR);
208         phy_cr = phy_hw_read(NIC_PHY_BMCR);
209
210         phy_cr &= ~NIC_PHY_BMCR_ISOLATE;
211         phy_hw_write(NIC_PHY_BMCR, phy_cr);
212
213         phy_cr = phy_hw_read(NIC_PHY_BMCR);
214
215         LOG_INFO("%s: PHY ID %#04x %#04x\n",
216                 __func__,
217                 phy_hw_read(NIC_PHY_ID1), phy_hw_read(NIC_PHY_ID2));
218
219         // Wait for auto negotiation completed.
220         phy_hw_read(NIC_PHY_BMSR);
221         for (;;)
222         {
223                 if (phy_hw_read(NIC_PHY_BMSR) & NIC_PHY_BMSR_ANCOMPL)
224                         break;
225                 cpu_relax();
226         }
227
228         // Disable management port.
229         EMAC_NCR &= ~BV(EMAC_MPE);
230
231         return 0;
232 }
233
234 static int emac_start(void)
235 {
236         uint32_t addr;
237         int i;
238
239         for (i = 0; i < EMAC_RX_DESCRIPTORS; i++)
240         {
241                 addr = (uint32_t)(rx_buf + (i * EMAC_RX_BUFSIZ));
242                 rx_buf_tab[i].addr = addr & BUF_ADDRMASK;
243         }
244         rx_buf_tab[EMAC_RX_DESCRIPTORS - 1].addr |= RXBUF_WRAP;
245
246         for (i = 0; i < EMAC_TX_DESCRIPTORS; i++)
247         {
248                 addr = (uint32_t)(tx_buf + (i * EMAC_TX_BUFSIZ));
249                 tx_buf_tab[i].addr = addr & BUF_ADDRMASK;
250                 tx_buf_tab[i].stat = TXS_USED;
251         }
252         tx_buf_tab[EMAC_TX_DESCRIPTORS - 1].stat = TXS_USED | TXS_WRAP;
253
254         /* Tell the EMAC where to find the descriptors. */
255         EMAC_RBQP = (uint32_t)rx_buf_tab;
256         EMAC_TBQP = (uint32_t)tx_buf_tab;
257
258         /* Clear receiver status. */
259         EMAC_RSR = BV(EMAC_OVR) | BV(EMAC_REC) | BV(EMAC_BNA);
260
261         /* Copy all frames and discard FCS. */
262         EMAC_NCFGR |= BV(EMAC_CAF) | BV(EMAC_DRFCS);
263
264         /* Enable receiver, transmitter and statistics. */
265         EMAC_NCR |= BV(EMAC_TE) | BV(EMAC_RE) | BV(EMAC_WESTAT);
266
267         return 0;
268 }
269
270 ssize_t eth_putFrame(const uint8_t *buf, size_t len)
271 {
272         size_t wr_len;
273
274         if (UNLIKELY(!len))
275                 return -1;
276         ASSERT(len <= sizeof(tx_buf));
277
278         /* Check if the transmit buffer is available */
279         while (!(tx_buf_tab[tx_buf_idx].stat & TXS_USED))
280                 event_wait(&send_wait);
281
282         /* Copy the data into the buffer and prepare descriptor */
283         wr_len = MIN(len, (size_t)EMAC_TX_BUFSIZ - tx_buf_offset);
284         memcpy((uint8_t *)tx_buf_tab[tx_buf_idx].addr + tx_buf_offset,
285                                 buf, wr_len);
286         tx_buf_offset += wr_len;
287
288         return wr_len;
289 }
290
291 void eth_sendFrame(void)
292 {
293         tx_buf_tab[tx_buf_idx].stat = (tx_buf_offset & TXS_LENGTH_FRAME) |
294                         TXS_LAST_BUFF |
295                         ((tx_buf_idx == EMAC_TX_DESCRIPTORS - 1) ?  TXS_WRAP : 0);
296         EMAC_NCR |= BV(EMAC_TSTART);
297
298         tx_buf_offset = 0;
299         if (++tx_buf_idx >= EMAC_TX_DESCRIPTORS)
300                 tx_buf_idx = 0;
301 }
302
303 ssize_t eth_send(const uint8_t *buf, size_t len)
304  {
305         if (UNLIKELY(!len))
306                 return -1;
307
308         len = eth_putFrame(buf, len);
309         eth_sendFrame();
310
311         return len;
312 }
313
314 static void eth_buf_realign(int idx)
315 {
316         /* Empty buffer found. Realign. */
317         do {
318                 rx_buf_tab[rx_buf_idx].addr &= ~RXBUF_OWNERSHIP;
319                 if (++rx_buf_idx >= EMAC_RX_BUFFERS)
320                         rx_buf_idx = 0;
321         } while (idx != rx_buf_idx);
322 }
323
324 static size_t __eth_getFrameLen(void)
325 {
326         int idx, n = EMAC_RX_BUFFERS;
327
328 skip:
329         /* Skip empty buffers */
330         while ((n > 0) && !(rx_buf_tab[rx_buf_idx].addr & RXBUF_OWNERSHIP))
331         {
332                 if (++rx_buf_idx >= EMAC_RX_BUFFERS)
333                         rx_buf_idx = 0;
334                 n--;
335         }
336         if (UNLIKELY(!n))
337         {
338                 LOG_INFO("no frame found\n");
339                 return 0;
340         }
341         /* Search the start of frame and cleanup fragments */
342         while ((n > 0) && (rx_buf_tab[rx_buf_idx].addr & RXBUF_OWNERSHIP) &&
343                         !(rx_buf_tab[rx_buf_idx].stat & RXS_SOF))
344         {
345                 rx_buf_tab[rx_buf_idx].addr &= ~RXBUF_OWNERSHIP;
346                 if (++rx_buf_idx >= EMAC_RX_BUFFERS)
347                         rx_buf_idx = 0;
348                 n--;
349         }
350         if (UNLIKELY(!n))
351         {
352                 LOG_INFO("no SOF found\n");
353                 return 0;
354         }
355         /* Search end of frame to evaluate the total frame size */
356         idx = rx_buf_idx;
357 restart:
358         while (n > 0)
359         {
360                 if (UNLIKELY(!(rx_buf_tab[idx].addr & RXBUF_OWNERSHIP)))
361                 {
362                         /* Empty buffer found. Realign. */
363                         eth_buf_realign(idx);
364                         goto skip;
365                 }
366                 if (rx_buf_tab[idx].stat & RXS_EOF)
367                         return rx_buf_tab[idx].stat & RXS_LENGTH_FRAME;
368                 if (UNLIKELY((idx != rx_buf_idx) &&
369                                 (rx_buf_tab[idx].stat & RXS_SOF)))
370                 {
371                         /* Another start of frame found. Realign. */
372                         eth_buf_realign(idx);
373                         goto restart;
374                 }
375                 if (++idx >= EMAC_RX_BUFFERS)
376                         idx = 0;
377                 n--;
378         }
379         LOG_INFO("no EOF found\n");
380         return 0;
381 }
382
383 size_t eth_getFrameLen(void)
384 {
385         size_t len;
386
387         /* Check if there is at least one available frame in the buffer */
388         while (1)
389         {
390                 len = __eth_getFrameLen();
391                 if (LIKELY(len))
392                         break;
393                 /* Wait for RX interrupt */
394                 event_wait(&recv_wait);
395         }
396         return len;
397 }
398
399 ssize_t eth_getFrame(uint8_t *buf, size_t len)
400 {
401         uint8_t *addr;
402         size_t rd_len = 0;
403
404         if (UNLIKELY(!len))
405                 return -1;
406         ASSERT(len <= sizeof(rx_buf));
407
408         /* Copy data from the RX buffer */
409         addr = (uint8_t *)(rx_buf_tab[rx_buf_idx].addr & BUF_ADDRMASK);
410         if (addr + len > &rx_buf[countof(rx_buf)])
411         {
412                 size_t count = &rx_buf[countof(rx_buf)] - addr;
413
414                 memcpy(buf, addr, count);
415                 memcpy(buf + count, rx_buf, len - count);
416         }
417         else
418         {
419                 memcpy(buf, addr, len);
420         }
421         /* Update descriptors */
422         while (rd_len < len)
423         {
424                 if (len - rd_len >= EMAC_RX_BUFSIZ)
425                         rd_len += EMAC_RX_BUFSIZ;
426                 else
427                         rd_len += len - rd_len;
428                 if (UNLIKELY(!(rx_buf_tab[rx_buf_idx].addr & RXBUF_OWNERSHIP)))
429                 {
430                         LOG_INFO("bad frame found\n");
431                         return 0;
432                 }
433                 rx_buf_tab[rx_buf_idx].addr &= ~RXBUF_OWNERSHIP;
434                 if (++rx_buf_idx >= EMAC_RX_DESCRIPTORS)
435                         rx_buf_idx = 0;
436         }
437
438         return rd_len;
439 }
440
441 ssize_t eth_recv(uint8_t *buf, size_t len)
442 {
443         if (UNLIKELY(!len))
444                 return -1;
445         len = MIN(len, eth_getFrameLen());
446         return len ? eth_getFrame(buf, len) : 0;
447 }
448
449 int eth_init()
450 {
451         cpu_flags_t flags;
452
453         emac_reset();
454         emac_start();
455
456         event_initGeneric(&recv_wait);
457         event_initGeneric(&send_wait);
458
459         // Register interrupt vector
460         IRQ_SAVE_DISABLE(flags);
461
462         /* Disable all emac interrupts */
463         EMAC_IDR = 0xFFFFFFFF;
464
465         /* Set the vector. */
466         AIC_SVR(EMAC_ID) = emac_irqHandler;
467         /* Initialize to edge triggered with defined priority. */
468         AIC_SMR(EMAC_ID) = AIC_SRCTYPE_INT_EDGE_TRIGGERED;
469         /* Clear pending interrupt */
470         AIC_ICCR = BV(EMAC_ID);
471         /* Enable the system IRQ */
472         AIC_IECR = BV(EMAC_ID);
473
474         /* Enable interrupts */
475         EMAC_IER = EMAC_RX_INTS | EMAC_TX_INTS;
476
477         IRQ_RESTORE(flags);
478
479         return 0;
480 }