Disable uneeded assert.
[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 /* 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 reg)
125 {
126         // PHY read command.
127         EMAC_MAN = EMAC_SOF | EMAC_RW_READ | (NIC_PHY_ADDR << EMAC_PHYA_SHIFT)
128                         | ((reg  << EMAC_REGA_SHIFT) & EMAC_REGA) | EMAC_CODE;
129
130         // Wait until PHY logic completed.
131         while (!(EMAC_NSR & BV(EMAC_IDLE)))
132                 cpu_relax();
133
134         // Get data from PHY maintenance register.
135         return (uint16_t)(EMAC_MAN & EMAC_DATA);
136 }
137
138 /*
139  * \brief Write value to PHY register.
140  *
141  * \param reg PHY register number.
142  * \param val Value to write.
143  */
144 static void phy_hw_write(uint8_t reg, uint16_t val)
145 {
146         // PHY write command.
147         EMAC_MAN = EMAC_SOF | EMAC_RW_WRITE | (NIC_PHY_ADDR << EMAC_PHYA_SHIFT)
148                         | ((reg  << EMAC_REGA_SHIFT) & EMAC_REGA) | EMAC_CODE | val;
149
150         // Wait until PHY logic completed.
151         while (!(EMAC_NSR & BV(EMAC_IDLE)))
152                 cpu_relax();
153 }
154
155 INLINE void phy_manageEnable(bool en)
156 {
157                 if (en)
158                 {
159                         /* Enable management port. */
160                         EMAC_NCR |= BV(EMAC_MPE);
161                         EMAC_NCFGR |= EMAC_CLK_HCLK_32;
162                 }
163                 else
164                 {
165                         /* Disable management port */
166                         EMAC_NCR &= ~BV(EMAC_MPE);
167                 }
168 }
169
170 INLINE void phy_resetPulse(void)
171 {
172         /* Toggle external hardware reset pin. */
173         RSTC_MR = RSTC_KEY | (1 << RSTC_ERSTL_SHIFT) | BV(RSTC_URSTEN);
174         RSTC_CR = RSTC_KEY | BV(RSTC_EXTRST);
175
176         while ((RSTC_SR & BV(RSTC_NRSTL)) == 0)
177                 cpu_relax();
178 }
179
180 INLINE void phy_pinThreeState(void)
181 {
182         PIOB_PUDR = PHY_MII_PINS;
183         PIOB_ODR = PHY_MII_PINS;
184         PIOB_PER = PHY_MII_PINS;
185 }
186
187 INLINE void phy_pinGpio(void)
188 {
189         PIOB_PUDR = PHY_MII_PINS;
190         PIOB_OWER = PHY_MII_PINS;
191         PIOB_OER  = PHY_MII_PINS;
192         PIOB_PER  = PHY_MII_PINS;
193 }
194
195 INLINE void phy_pinMac(void)
196 {
197         PIOB_ODR = PHY_MII_PINS;
198         PIOB_OWDR = PHY_MII_PINS;
199         PIOB_ASR = PHY_MII_PINS;
200         PIOB_BSR = 0;
201         PIOB_PUDR = PHY_MII_PINS;
202         PIOB_PDR = PHY_MII_PINS;
203 }
204
205 INLINE void phy_pinSet(uint32_t state)
206 {
207         PIOB_ODSR = state;
208 }
209
210 #define AUTONEGOTIATION_TIMEOUT 5000
211
212 static void emac_reset(void)
213 {
214         /* Enable devices */
215         PMC_PCER = BV(EMAC_ID);
216
217         /* Enable receive and transmit clocks. */
218         EMAC_USRIO = BV(EMAC_CLKEN);
219
220         /* Set local MAC address. */
221         EMAC_SA1L = (mac_addr[3] << 24) | (mac_addr[2] << 16) |
222                                 (mac_addr[1] << 8) | mac_addr[0];
223         EMAC_SA1H = (mac_addr[5] << 8) | mac_addr[4];
224         phy_manageEnable(true);
225
226         PHY_HW_INIT();
227
228         PHY_INIT();
229         phy_pinMac();
230
231         /* Clear MII isolate. */
232         uint16_t phy_cr = phy_hw_read(NIC_PHY_BMCR);
233
234         phy_cr &= ~NIC_PHY_BMCR_ISOLATE;
235         phy_hw_write(NIC_PHY_BMCR, phy_cr);
236
237         uint32_t phy_id = phy_hw_read(NIC_PHY_ID1) << 16
238                 | phy_hw_read(NIC_PHY_ID2);
239         //ASSERT((phy_id & 0xFFFFFFF0) == (NIC_PHY_ID & 0xFFFFFFF0));
240         LOG_INFO("PHY ID %#08lx\n", phy_id);
241
242         ticks_t start = timer_clock();
243         /* Wait for auto negotiation completed. */
244         while (1)
245         {
246                 if (phy_hw_read(NIC_PHY_BMSR) & NIC_PHY_BMSR_ANCOMPL)
247                         break;
248                 cpu_relax();
249                 if (timer_clock() - start > ms_to_ticks(AUTONEGOTIATION_TIMEOUT))
250                 {
251                         LOG_ERR("Autonegotiation timeout\n");
252                         break;
253                 }
254         }
255 }
256
257 static void emac_start(void)
258 {
259         uint32_t addr;
260         int i;
261
262         for (i = 0; i < EMAC_RX_DESCRIPTORS; i++)
263         {
264                 addr = (uint32_t)(rx_buf + (i * EMAC_RX_BUFSIZ));
265                 rx_buf_tab[i].addr = addr & BUF_ADDRMASK;
266         }
267         rx_buf_tab[EMAC_RX_DESCRIPTORS - 1].addr |= RXBUF_WRAP;
268
269         for (i = 0; i < EMAC_TX_DESCRIPTORS; i++)
270         {
271                 addr = (uint32_t)(tx_buf + (i * EMAC_TX_BUFSIZ));
272                 tx_buf_tab[i].addr = addr & BUF_ADDRMASK;
273                 tx_buf_tab[i].stat = TXS_USED;
274         }
275         tx_buf_tab[EMAC_TX_DESCRIPTORS - 1].stat = TXS_USED | TXS_WRAP;
276
277         /* Tell the EMAC where to find the descriptors. */
278         EMAC_RBQP = (uint32_t)rx_buf_tab;
279         EMAC_TBQP = (uint32_t)tx_buf_tab;
280
281         /* Clear receiver status. */
282         EMAC_RSR = BV(EMAC_OVR) | BV(EMAC_REC) | BV(EMAC_BNA);
283
284         /* Copy all frames and discard FCS. */
285         EMAC_NCFGR |= BV(EMAC_CAF) | BV(EMAC_DRFCS);
286
287         /* Enable receiver, transmitter and statistics. */
288         EMAC_NCR |= BV(EMAC_TE) | BV(EMAC_RE) | BV(EMAC_WESTAT);
289 }
290
291 ssize_t eth_putFrame(const uint8_t *buf, size_t len)
292 {
293         size_t wr_len;
294
295         if (UNLIKELY(!len))
296                 return -1;
297         ASSERT(len <= sizeof(tx_buf));
298
299         /* Check if the transmit buffer is available */
300         while (!(tx_buf_tab[tx_buf_idx].stat & TXS_USED))
301                 event_wait(&send_wait);
302
303         /* Copy the data into the buffer and prepare descriptor */
304         wr_len = MIN(len, (size_t)EMAC_TX_BUFSIZ - tx_buf_offset);
305         memcpy((uint8_t *)tx_buf_tab[tx_buf_idx].addr + tx_buf_offset,
306                                 buf, wr_len);
307         tx_buf_offset += wr_len;
308
309         return wr_len;
310 }
311
312 void eth_sendFrame(void)
313 {
314         tx_buf_tab[tx_buf_idx].stat = (tx_buf_offset & TXS_LENGTH_FRAME) |
315                         TXS_LAST_BUFF |
316                         ((tx_buf_idx == EMAC_TX_DESCRIPTORS - 1) ?  TXS_WRAP : 0);
317         EMAC_NCR |= BV(EMAC_TSTART);
318
319         tx_buf_offset = 0;
320         if (++tx_buf_idx >= EMAC_TX_DESCRIPTORS)
321                 tx_buf_idx = 0;
322 }
323
324 ssize_t eth_send(const uint8_t *buf, size_t len)
325  {
326         if (UNLIKELY(!len))
327                 return -1;
328
329         len = eth_putFrame(buf, len);
330         eth_sendFrame();
331
332         return len;
333 }
334
335 static void eth_buf_realign(int idx)
336 {
337         /* Empty buffer found. Realign. */
338         do {
339                 rx_buf_tab[rx_buf_idx].addr &= ~RXBUF_OWNERSHIP;
340                 if (++rx_buf_idx >= EMAC_RX_BUFFERS)
341                         rx_buf_idx = 0;
342         } while (idx != rx_buf_idx);
343 }
344
345 static size_t __eth_getFrameLen(void)
346 {
347         int idx, n = EMAC_RX_BUFFERS;
348
349 skip:
350         /* Skip empty buffers */
351         while ((n > 0) && !(rx_buf_tab[rx_buf_idx].addr & RXBUF_OWNERSHIP))
352         {
353                 if (++rx_buf_idx >= EMAC_RX_BUFFERS)
354                         rx_buf_idx = 0;
355                 n--;
356         }
357         if (UNLIKELY(!n))
358         {
359                 LOG_INFO("no frame found\n");
360                 return 0;
361         }
362         /* Search the start of frame and cleanup fragments */
363         while ((n > 0) && (rx_buf_tab[rx_buf_idx].addr & RXBUF_OWNERSHIP) &&
364                         !(rx_buf_tab[rx_buf_idx].stat & RXS_SOF))
365         {
366                 rx_buf_tab[rx_buf_idx].addr &= ~RXBUF_OWNERSHIP;
367                 if (++rx_buf_idx >= EMAC_RX_BUFFERS)
368                         rx_buf_idx = 0;
369                 n--;
370         }
371         if (UNLIKELY(!n))
372         {
373                 LOG_INFO("no SOF found\n");
374                 return 0;
375         }
376         /* Search end of frame to evaluate the total frame size */
377         idx = rx_buf_idx;
378 restart:
379         while (n > 0)
380         {
381                 if (UNLIKELY(!(rx_buf_tab[idx].addr & RXBUF_OWNERSHIP)))
382                 {
383                         /* Empty buffer found. Realign. */
384                         eth_buf_realign(idx);
385                         goto skip;
386                 }
387                 if (rx_buf_tab[idx].stat & RXS_EOF)
388                         return rx_buf_tab[idx].stat & RXS_LENGTH_FRAME;
389                 if (UNLIKELY((idx != rx_buf_idx) &&
390                                 (rx_buf_tab[idx].stat & RXS_SOF)))
391                 {
392                         /* Another start of frame found. Realign. */
393                         eth_buf_realign(idx);
394                         goto restart;
395                 }
396                 if (++idx >= EMAC_RX_BUFFERS)
397                         idx = 0;
398                 n--;
399         }
400         LOG_INFO("no EOF found\n");
401         return 0;
402 }
403
404 size_t eth_getFrameLen(void)
405 {
406         size_t len;
407
408         /* Check if there is at least one available frame in the buffer */
409         while (1)
410         {
411                 len = __eth_getFrameLen();
412                 if (LIKELY(len))
413                         break;
414                 /* Wait for RX interrupt */
415                 event_wait(&recv_wait);
416         }
417         return len;
418 }
419
420 ssize_t eth_getFrame(uint8_t *buf, size_t len)
421 {
422         uint8_t *addr;
423         size_t rd_len = 0;
424
425         if (UNLIKELY(!len))
426                 return -1;
427         ASSERT(len <= sizeof(rx_buf));
428
429         /* Copy data from the RX buffer */
430         addr = (uint8_t *)(rx_buf_tab[rx_buf_idx].addr & BUF_ADDRMASK);
431         if (addr + len > &rx_buf[countof(rx_buf)])
432         {
433                 size_t count = &rx_buf[countof(rx_buf)] - addr;
434
435                 memcpy(buf, addr, count);
436                 memcpy(buf + count, rx_buf, len - count);
437         }
438         else
439         {
440                 memcpy(buf, addr, len);
441         }
442         /* Update descriptors */
443         while (rd_len < len)
444         {
445                 if (len - rd_len >= EMAC_RX_BUFSIZ)
446                         rd_len += EMAC_RX_BUFSIZ;
447                 else
448                         rd_len += len - rd_len;
449                 if (UNLIKELY(!(rx_buf_tab[rx_buf_idx].addr & RXBUF_OWNERSHIP)))
450                 {
451                         LOG_INFO("bad frame found\n");
452                         return 0;
453                 }
454                 rx_buf_tab[rx_buf_idx].addr &= ~RXBUF_OWNERSHIP;
455                 if (++rx_buf_idx >= EMAC_RX_DESCRIPTORS)
456                         rx_buf_idx = 0;
457         }
458
459         return rd_len;
460 }
461
462 ssize_t eth_recv(uint8_t *buf, size_t len)
463 {
464         if (UNLIKELY(!len))
465                 return -1;
466         len = MIN(len, eth_getFrameLen());
467         return len ? eth_getFrame(buf, len) : 0;
468 }
469
470 int eth_init()
471 {
472         cpu_flags_t flags;
473
474         emac_reset();
475         emac_start();
476
477         event_initGeneric(&recv_wait);
478         event_initGeneric(&send_wait);
479
480         // Register interrupt vector
481         IRQ_SAVE_DISABLE(flags);
482
483         /* Disable all emac interrupts */
484         EMAC_IDR = 0xFFFFFFFF;
485
486         /* Set the vector. */
487         AIC_SVR(EMAC_ID) = emac_irqHandler;
488         /* Initialize to edge triggered with defined priority. */
489         AIC_SMR(EMAC_ID) = AIC_SRCTYPE_INT_EDGE_TRIGGERED;
490         /* Clear pending interrupt */
491         AIC_ICCR = BV(EMAC_ID);
492         /* Enable the system IRQ */
493         AIC_IECR = BV(EMAC_ID);
494
495         /* Enable interrupts */
496         EMAC_IER = EMAC_RX_INTS | EMAC_TX_INTS;
497
498         IRQ_RESTORE(flags);
499
500         return 0;
501 }