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