fbf3542b1eb35a99f65e1d727975dadb46103592
[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 /*
68  * MAC address configuration (please change this in your project!).
69  *
70  * TODO: make this paramater user-configurable from the Wizard.
71  */
72 uint8_t mac_addr[] = { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66 };
73
74 static volatile BufDescriptor tx_buf_tab[EMAC_TX_DESCRIPTORS];
75 /*
76  * NOTE: this buffer should be declared as 'volatile' because it is read by the
77  * hardware. However, this is accessed only via memcpy() that should guarantee
78  * coherency when copying from/to buffers.
79  */
80 static uint8_t tx_buf[EMAC_TX_BUFFERS * EMAC_TX_BUFSIZ] ALIGNED(8);
81 static int tx_buf_idx = 0;
82
83 static volatile BufDescriptor rx_buf_tab[EMAC_RX_DESCRIPTORS];
84 /*
85  * NOTE: this buffer should be declared as 'volatile' because it is wrote by
86  * the hardware. However, this is accessed only via memcpy() that should
87  * guarantee coherency when copying from/to buffers.
88  */
89 static uint8_t rx_buf[EMAC_RX_BUFFERS * EMAC_RX_BUFSIZ] ALIGNED(8);
90 static int rx_buf_idx = 0;
91
92 static Event recv_wait, send_wait;
93
94 static DECLARE_ISR(emac_irqHandler)
95 {
96         /* Read interrupt status and disable interrupts. */
97         uint32_t isr = EMAC_ISR;
98
99         /* Receiver interrupt */
100         if ((isr & EMAC_RX_INTS))
101         {
102                 event_do(&recv_wait);
103                 EMAC_RSR = EMAC_RX_INTS;
104         }
105         /* Transmitter interrupt */
106         if (isr & EMAC_TX_INTS)
107         {
108                 event_do(&send_wait);
109                 EMAC_TSR = EMAC_TX_INTS;
110         }
111         AIC_EOICR = 0;
112 }
113
114 /*
115  * \brief Read contents of PHY register.
116  *
117  * \param reg PHY register number.
118  *
119  * \return Contents of the specified register.
120  */
121 static uint16_t phy_hw_read(reg8_t reg)
122 {
123         // PHY read command.
124         EMAC_MAN = EMAC_SOF | EMAC_RW_READ | (NIC_PHY_ADDR << EMAC_PHYA_SHIFT)
125                         | ((reg  << EMAC_REGA_SHIFT) & EMAC_REGA) | EMAC_CODE;
126
127         // Wait until PHY logic completed.
128         while (!(EMAC_NSR & BV(EMAC_IDLE)))
129                 cpu_relax();
130
131         // Get data from PHY maintenance register.
132         return (uint16_t)(EMAC_MAN & EMAC_DATA);
133 }
134
135 /*
136  * \brief Write value to PHY register.
137  *
138  * \param reg PHY register number.
139  * \param val Value to write.
140  */
141 static void phy_hw_write(reg8_t reg, uint16_t val)
142 {
143         // PHY write command.
144         EMAC_MAN = EMAC_SOF | EMAC_RW_WRITE | (NIC_PHY_ADDR << EMAC_PHYA_SHIFT)
145                         | ((reg  << EMAC_REGA_SHIFT) & EMAC_REGA) | EMAC_CODE | val;
146
147         // Wait until PHY logic completed.
148         while (!(EMAC_NSR & BV(EMAC_IDLE)))
149                 cpu_relax();
150 }
151
152 static int emac_reset(void)
153 {
154         uint16_t phy_cr;
155
156         // Enable devices
157         PMC_PCER = BV(PIOA_ID);
158         PMC_PCER = BV(PIOB_ID);
159         PMC_PCER = BV(EMAC_ID);
160
161         // Disable RMII and TESTMODE by disabling pull-ups.
162         PIOB_PUDR = BV(PHY_COL_RMII_BIT) | BV(PHY_RXDV_TESTMODE_BIT);
163
164         // Disable PHY power down.
165         PIOB_PER  = BV(PHY_PWRDN_BIT);
166         PIOB_OER  = BV(PHY_PWRDN_BIT);
167         PIOB_CODR = BV(PHY_PWRDN_BIT);
168
169         // Toggle external hardware reset pin.
170         RSTC_MR = RSTC_KEY | (1 << RSTC_ERSTL_SHIFT) | BV(RSTC_URSTEN);
171         RSTC_CR = RSTC_KEY | BV(RSTC_EXTRST);
172
173         while ((RSTC_SR & BV(RSTC_NRSTL)) == 0)
174                 cpu_relax();
175
176         // Configure MII port.
177         PIOB_ASR = PHY_MII_PINS;
178         PIOB_BSR = 0;
179         PIOB_PDR = PHY_MII_PINS;
180
181         // Enable receive and transmit clocks.
182         EMAC_USRIO = BV(EMAC_CLKEN);
183
184         // Enable management port.
185         EMAC_NCR |= BV(EMAC_MPE);
186         EMAC_NCFGR |= EMAC_CLK_HCLK_32;
187
188         // Set local MAC address.
189         EMAC_SA1L = (mac_addr[3] << 24) | (mac_addr[2] << 16) |
190                                 (mac_addr[1] << 8) | mac_addr[0];
191         EMAC_SA1H = (mac_addr[5] << 8) | mac_addr[4];
192
193         // Wait for PHY ready
194         timer_delay(255);
195
196         // Clear MII isolate.
197         phy_hw_read(NIC_PHY_BMCR);
198         phy_cr = phy_hw_read(NIC_PHY_BMCR);
199
200         phy_cr &= ~NIC_PHY_BMCR_ISOLATE;
201         phy_hw_write(NIC_PHY_BMCR, phy_cr);
202
203         phy_cr = phy_hw_read(NIC_PHY_BMCR);
204
205         LOG_INFO("%s: PHY ID %#04x %#04x\n",
206                 __func__,
207                 phy_hw_read(NIC_PHY_ID1), phy_hw_read(NIC_PHY_ID2));
208
209         // Wait for auto negotiation completed.
210         phy_hw_read(NIC_PHY_BMSR);
211         for (;;)
212         {
213                 if (phy_hw_read(NIC_PHY_BMSR) & NIC_PHY_BMSR_ANCOMPL)
214                         break;
215                 cpu_relax();
216         }
217
218         // Disable management port.
219         EMAC_NCR &= ~BV(EMAC_MPE);
220
221         return 0;
222 }
223
224 static int emac_start(void)
225 {
226         uint32_t addr;
227         int i;
228
229         for (i = 0; i < EMAC_RX_DESCRIPTORS; i++)
230         {
231                 addr = (uint32_t)(rx_buf + (i * EMAC_RX_BUFSIZ));
232                 rx_buf_tab[i].addr = addr & BUF_ADDRMASK;
233         }
234         rx_buf_tab[EMAC_RX_DESCRIPTORS - 1].addr |= RXBUF_WRAP;
235
236         for (i = 0; i < EMAC_TX_DESCRIPTORS; i++)
237         {
238                 addr = (uint32_t)(tx_buf + (i * EMAC_TX_BUFSIZ));
239                 tx_buf_tab[i].addr = addr & BUF_ADDRMASK;
240                 tx_buf_tab[i].stat = TXS_USED;
241         }
242         tx_buf_tab[EMAC_TX_DESCRIPTORS - 1].stat = TXS_USED | TXS_WRAP;
243
244         /* Tell the EMAC where to find the descriptors. */
245         EMAC_RBQP = (uint32_t)rx_buf_tab;
246         EMAC_TBQP = (uint32_t)tx_buf_tab;
247
248         /* Clear receiver status. */
249         EMAC_RSR = BV(EMAC_OVR) | BV(EMAC_REC) | BV(EMAC_BNA);
250
251         /* Copy all frames and discard FCS. */
252         EMAC_NCFGR |= BV(EMAC_CAF) | BV(EMAC_DRFCS);
253
254         /* Enable receiver, transmitter and statistics. */
255         EMAC_NCR |= BV(EMAC_TE) | BV(EMAC_RE) | BV(EMAC_WESTAT);
256
257         return 0;
258 }
259
260 ssize_t eth_send(const uint8_t *buf, size_t len)
261  {
262         size_t wr_len;
263         int idx;
264
265         if (UNLIKELY(!len))
266                 return -1;
267         ASSERT(len <= sizeof(tx_buf));
268
269         /* Check if the transmit buffer is available */
270         idx = tx_buf_idx;
271         while (!(tx_buf_tab[idx].stat & TXS_USED))
272                 event_wait(&send_wait);
273
274         if (++tx_buf_idx >= EMAC_TX_DESCRIPTORS)
275                 tx_buf_idx = 0;
276
277         /* Copy the data into the buffer and prepare descriptor */
278         wr_len = MIN(len, (size_t)EMAC_TX_BUFSIZ);
279         memcpy((uint8_t *)tx_buf_tab[idx].addr, buf, wr_len);
280         tx_buf_tab[idx].stat = (wr_len & RXS_LENGTH_FRAME) |
281                         ((idx == EMAC_TX_DESCRIPTORS - 1) ?
282                                 TXS_WRAP : 0) |
283                         TXS_LAST_BUFF;
284         EMAC_NCR |= BV(EMAC_TSTART);
285
286         return wr_len;
287 }
288
289 static size_t eth_getFrameLen(void)
290 {
291         int idx, n = EMAC_RX_BUFFERS;
292
293         /* Skip empty buffers */
294         while ((n > 0) && !(rx_buf_tab[rx_buf_idx].addr & RXBUF_OWNERSHIP))
295         {
296                 if (++rx_buf_idx >= EMAC_RX_BUFFERS)
297                         rx_buf_idx = 0;
298                 n--;
299         }
300         if (UNLIKELY(!n))
301         {
302                 LOG_INFO("no frame found\n");
303                 return 0;
304         }
305         /* Search the start of frame and cleanup fragments */
306         while ((n > 0) && (rx_buf_tab[rx_buf_idx].addr & RXBUF_OWNERSHIP) &&
307                         !(rx_buf_tab[rx_buf_idx].stat & RXS_SOF))
308         {
309                 rx_buf_tab[rx_buf_idx].addr &= ~RXBUF_OWNERSHIP;
310                 if (++rx_buf_idx >= EMAC_RX_BUFFERS)
311                         rx_buf_idx = 0;
312                 n--;
313         }
314         if (UNLIKELY(!(rx_buf_tab[rx_buf_idx].stat & RXS_SOF)))
315         {
316                 LOG_INFO("no SOF found\n");
317                 return 0;
318         }
319         /* Search end of frame to evaluate the total frame size */
320         idx = rx_buf_idx;
321         while ((n > 0) && (rx_buf_tab[idx].addr & RXBUF_OWNERSHIP))
322         {
323                 if (UNLIKELY((idx != rx_buf_idx) &&
324                                 (rx_buf_tab[idx].stat & RXS_SOF)))
325                 {
326                         /* Another start of frame found. Realign. */
327                         do {
328                                 rx_buf_tab[rx_buf_idx].addr &= ~RXBUF_OWNERSHIP;
329                                 if (++rx_buf_idx >= EMAC_RX_BUFFERS)
330                                         rx_buf_idx = 0;
331                         } while (idx != rx_buf_idx);
332                 }
333                 if (rx_buf_tab[idx].stat & RXS_EOF)
334                         return rx_buf_tab[idx].stat & RXS_LENGTH_FRAME;
335                 if (++idx >= EMAC_RX_BUFFERS)
336                         idx = 0;
337                 n--;
338         }
339
340         LOG_INFO("no EOF found\n");
341         return 0;
342 }
343
344 ssize_t eth_recv(uint8_t *buf, size_t len)
345 {
346         uint8_t *addr;
347         size_t rd_len = 0;
348
349         if (UNLIKELY(!len))
350                 return -1;
351         ASSERT(len <= sizeof(tx_buf));
352
353         /* Check if there is at least one available frame in the buffer */
354         while (1)
355         {
356                 size_t frame_len = MIN(len, eth_getFrameLen());
357                 if (frame_len)
358                 {
359                         len = frame_len;
360                         break;
361                 }
362                 /* Wait for RX interrupt */
363                 event_wait(&recv_wait);
364         }
365
366         /* Copy data from the RX buffer */
367         addr = (uint8_t *)(rx_buf_tab[rx_buf_idx].addr & BUF_ADDRMASK);
368         if (addr + len > &rx_buf[countof(rx_buf)])
369         {
370                 size_t count = &rx_buf[countof(rx_buf)] - addr;
371
372                 memcpy(buf, addr, count);
373                 memcpy(buf + count, rx_buf, len - count);
374         }
375         else
376         {
377                 memcpy(buf, addr, len);
378         }
379         /* Update descriptors */
380         while (rd_len < len)
381         {
382                 if (len - rd_len >= EMAC_RX_BUFSIZ)
383                         rd_len += EMAC_RX_BUFSIZ;
384                 else
385                         rd_len += len - rd_len;
386                 ASSERT(rx_buf_tab[rx_buf_idx].addr & RXBUF_OWNERSHIP);
387                 rx_buf_tab[rx_buf_idx].addr &= ~RXBUF_OWNERSHIP;
388                 if (++rx_buf_idx >= EMAC_RX_DESCRIPTORS)
389                         rx_buf_idx = 0;
390         }
391         return rd_len;
392 }
393
394 int eth_init()
395 {
396         cpu_flags_t flags;
397
398         emac_reset();
399         emac_start();
400
401         event_initGeneric(&recv_wait);
402         event_initGeneric(&send_wait);
403
404         // Register interrupt vector
405         IRQ_SAVE_DISABLE(flags);
406
407         /* Disable all emac interrupts */
408         EMAC_IDR = 0xFFFFFFFF;
409
410         /* Set the vector. */
411         AIC_SVR(EMAC_ID) = emac_irqHandler;
412         /* Initialize to edge triggered with defined priority. */
413         AIC_SMR(EMAC_ID) = AIC_SRCTYPE_INT_EDGE_TRIGGERED;
414         /* Clear pending interrupt */
415         AIC_ICCR = BV(EMAC_ID);
416         /* Enable the system IRQ */
417         AIC_IECR = BV(EMAC_ID);
418
419         /* Enable interrupts */
420         EMAC_IER = EMAC_RX_INTS | EMAC_TX_INTS;
421
422         IRQ_RESTORE(flags);
423
424         return 0;
425 }