+// vim: set et sw=4 sts=4 :
+
+#include "debug.h"
+#include "eth.h"
+#include "dp8390.h"
+
+/** Tamaño del frame */
+byte netdev_len;
+
+// Próximo frame a obtener
+static struct
+{
+ byte next_buf;
+ byte curr_buf;
+ byte curr_off;
+}
+recv_state;
+
+/// Tamaño de la cabecera de los buffers de la placa de red
+#define BUF_HDR_SIZE 4
+
+/// Cambia de página sin modificar los demás bits del CR
+#define SELECT_REG_PAGE(page) \
+ do \
+ { \
+ write_reg(CR, read_reg(CR) & ~(PS1 | PS0)); \
+ write_reg(CR, read_reg(CR) | (page << 6)); \
+ } \
+ while (0)
+
+/// Aborta (o completa) el DMA limpiando el ISR
+#define ABORT_DMA(flags) \
+ do \
+ { \
+ write_reg(CR, flags); \
+ write_reg(ISR, RDC); \
+ } \
+ while (0)
+
+
+static void write_reg(unsigned char reg, unsigned char wr_data)
+{
+ // Select register address.
+ ADDR_PORT &= ~ADDR_PORT_MASK;
+ ADDR_PORT |= reg;
+
+ // Output register data to port.
+ DATA_PORT = wr_data;
+
+ // Clock register data into RTL8019AS.
+ // IOR & IOW are both active low.
+ NICE = 0;
+ IOW = 0;
+ IOW = 1;
+ NICE = 1;
+
+ // Set register data port as input again.
+ DATA_PORT = DATA_PORT_MASK;
+}
+
+
+static unsigned char read_reg(unsigned char reg)
+{
+ // Select register address.
+ ADDR_PORT &= ~ADDR_PORT_MASK;
+ ADDR_PORT |= reg;
+
+ // Enable register data output from RTL8019AS.
+ NICE = 0;
+ IOR = 0;
+
+ // Read register data from port.
+ reg = DATA_PORT;
+
+ // Disable register data output from RTL8019AS.
+ IOR = 1;
+ NICE = 1;
+
+ return reg;
+}
+
+/** Resetea placa de red en caso de buffer overflow */
+static void reset()
+{
+ bit retransmit = read_reg(CR) & TXP;
+
+ // If the receive buffer ring has overflowed we dump the whole
+ // thing and start over. There is no way of knowing whether the
+ // data it contains is uncorrupted, or will cause us grief.
+
+ // Stop RTL8019AS and abort DMA operation.
+ write_reg(CR, STOP);
+
+ // Wait for controller to halt after any current tx completes.
+ while(!(read_reg(ISR) & RST)) continue;
+
+ // Reset remote byte count registers.
+ write_reg(RBCR0, 0x00);
+ write_reg(RBCR1, 0x00);
+
+ // Check whether currently transmitting a packet.
+ if(retransmit)
+ {
+ // If neither a successful transmission nor a tx abort error
+ // has occured, then flag current tx packet for resend.
+ if(read_reg(ISR) & (PTX | TXE))
+ {
+ retransmit = 0;
+ }
+ }
+
+ // Set transmit configuration register to loopback internally.
+ write_reg(TCR, MODE1);
+
+ // Restart the RTL8019AS.
+ write_reg(CR, START);
+
+ // Re-initialise last receive buffer read pointer.
+ write_reg(BNRY, RX_PAGE_START);
+
+ // Select RTL8019AS register page 1.
+ SELECT_REG_PAGE(1);
+
+ // Re-initialise current packet receive buffer page pointer.
+ write_reg(CURR, RX_PAGE_START + 1);
+
+ // Select RTL8019AS register page 0.
+ SELECT_REG_PAGE(0);
+
+ // Clear rx buffer overflow & packet received interrupt flags.
+ write_reg(ISR, PRX | OVW);
+
+ // Re-itialise transmit configuration reg for normal operation.
+ write_reg(TCR, MODE0);
+
+ if(retransmit)
+ {
+ // Retransmit packet in RTL8019AS local tx buffer.
+ write_reg(CR, START | TXP);
+ }
+}
+
+
+/** Inicializa dispositivo de red
+ * @return true si se inicializó correctamente, false si no
+ */
+bool netdev_init()
+{
+ byte i;
+
+ // Set IOR & IOW as they're active low.
+ IOR = 1;
+ IOW = 1;
+ NICE = 1;
+
+ // Set register data port as input.
+ DATA_PORT = DATA_PORT_MASK;
+
+ // Configure RTL8019AS ethernet controller.
+
+ // Keil startup code takes 4ms to execute (18.432MHz, X1 mode).
+ // That leaves plenty of time for the RTL8019AS to read it's
+ // configuration in from the 9346 EEPROM before we get here.
+
+ // Select RTL8019AS register page 0.
+ SELECT_REG_PAGE(0);
+
+ // Check if RTL8019AS fully reset.
+ if(!(read_reg(ISR) & RST))
+ {
+ return 0;
+ }
+
+ // Stop RTL8019AS, select page 0 and abort DMA operation.
+ write_reg(CR, STOP);
+
+ // Initialise data configuration register.
+ // FIFO threshold 8 bytes, no loopback, don't use auto send packet.
+ write_reg(DCR, FT1 | LS);
+
+ // Reset remote byte count registers.
+ write_reg(RBCR0, 0u);
+ write_reg(RBCR1, 0u);
+
+ // Receive configuration register to monitor mode.
+ write_reg(RCR, MON);
+
+ // Initialise transmit configuration register to loopback internally.
+ write_reg(TCR, MODE1);
+
+ // Clear interrupt status register bits by writing 1 to each.
+ write_reg(ISR, ALL);
+
+ // Mask all interrupts in mask register.
+ write_reg(IMR, NONE);
+
+ // Obtengo MAC de la placa
+ write_reg(RBCR0, 12u); // Vamos a leer 12 bytes (2 x 6)
+ write_reg(RBCR1, 0u);
+ write_reg(RSAR0, 0u); // En la dirección 0x0000
+ write_reg(RSAR1, 0u);
+ write_reg(CR, READ); // Comienza lectura
+ for (i = 0; i < ETH_ADDR_SIZE; ++i)
+ {
+ eth_addr_local[i] = read_reg(RDMA);
+ read_reg(RDMA); // Ignoramos porque viene como un word
+ }
+
+ // Abort/ complete DMA operation.
+ ABORT_DMA(STOP);
+
+ // Set transmit page start.
+ write_reg(TPSR, TX_PAGE_START);
+
+ // Set receive buffer page start.
+ write_reg(PSTART, RX_PAGE_START);
+
+ // Initialise last receive buffer read pointer.
+ write_reg(BNRY, RX_PAGE_START);
+
+ // Set receive buffer page stop.
+ write_reg(PSTOP, RX_PAGE_STOP);
+
+ // Select RTL8019AS register page 1.
+ SELECT_REG_PAGE(1);
+
+ // Initialise current packet receive buffer page pointer
+ write_reg(CURR, RX_PAGE_START + 1);
+
+ // Set physical address
+ for (i = 0; i < ETH_ADDR_SIZE; ++i)
+ write_reg(PAR_BASE + i, eth_addr_local[i]);
+
+ // Restart RTL8019AS.
+ write_reg(CR, START);
+
+ // Initialise transmit configuration register for normal operation.
+ write_reg(TCR, MODE0);
+
+ // Receive configuration register to accept broadcast packets.
+ write_reg(RCR, AB);
+
+ return 1;
+}
+
+
+/** Comienza el envío de un nuevo frame */
+void netdev_send_start()
+{
+ // Wait until pending transmit operation completes.
+ while (read_reg(CR) & TXP) continue;
+ write_reg(ISR, PTX); // Limpio bit de interrupción
+
+ // Set remote DMA start address registers to indicate where to load packet.
+ write_reg(RSAR0, 0u);
+ write_reg(RSAR1, TX_PAGE_START);
+}
+
+/** Finaliza el envío del frame
+ * @precond netdev_send_start() debe haber sido ejecutada
+ * @precond se copiaron datos al dispositivo para enviar
+ * @param len Cantidad de bytes a transmitir
+ */
+void netdev_send_end(byte len)
+{
+ // Set transmit page start to indicate packet start.
+ write_reg(TPSR, TX_PAGE_START);
+
+ // Ethernet packets must be > 60 bytes, otherwise are rejected as runts.
+ if (len < MIN_PACKET_LEN)
+ len = MIN_PACKET_LEN;
+
+ // Set transmit byte count registers to indicate packet length.
+ write_reg(TBCR0, len);
+ write_reg(TBCR1, 0u);
+
+ // Issue command for RTL8019AS to transmit packet from it's local buffer.
+ write_reg(CR, START | TXP);
+}
+
+void netdev_write_start(byte len)
+{
+ // Set remote DMA byte count registers to indicate length of packet load.
+ write_reg(RBCR0, len);
+ write_reg(RBCR1, 0u);
+
+ // Initiate DMA transfer of uip_buf & uip_appdata buffers to RTL8019AS.
+ write_reg(CR, WRITE);
+}
+
+void netdev_write_start_at(byte offset, byte len)
+{
+ // Set remote DMA start address registers to packet data.
+ write_reg(RSAR0, offset);
+ write_reg(RSAR1, TX_PAGE_START);
+
+ // Set remote DMA byte count registers to indicate length of packet load.
+ write_reg(RBCR0, len);
+ write_reg(RBCR1, 0u);
+
+ // Initiate DMA transfer of uip_buf & uip_appdata buffers to RTL8019AS.
+ write_reg(CR, WRITE);
+}
+
+/** Escribe un byte al buffer de la placa de red para ser enviado
+ * @precond netdev_send_start() debe haber sido ejecutada
+ * @param b Byte a enviar
+ */
+void netdev_write_byte(byte b)
+{
+ write_reg(RDMA, b);
+}
+
+/** Escribe un word al buffer de la placa de red para ser enviado
+ * @precond netdev_send_start() debe haber sido ejecutada
+ * @param w Word a enviar
+ */
+void netdev_write_word(uint16 w)
+{
+ write_reg(RDMA, HIGH(w));
+ write_reg(RDMA, LOW(w));
+}
+
+void netdev_write_end()
+{
+ // Abort/ complete DMA operation.
+ ABORT_DMA(START);
+}
+
+/** Comienza la lectura de un nuevo frame
+ * @return Cantidad de bytes a recibir
+ */
+byte netdev_recv_start()
+{
+ // Check if the rx buffer has overflowed.
+ if (read_reg(ISR) & OVW)
+ {
+ byte current;
+
+ SELECT_REG_PAGE(1);
+ current = read_reg(CURR);
+ SELECT_REG_PAGE(0);
+
+ // Hack: a veces reporta mal el flag de OVW, así que verificamos que
+ // relamente haya habido overflow.
+ if (read_reg(BNRY) == current)
+ {
+ printb(read_reg(ISR), 0x01);
+ printb(read_reg(BNRY), 0x02);
+ printb(current, 0x04);
+ printb(0x00, 0x00);
+ reset();
+ }
+ return 0;
+ }
+ // Check if there is a packet in the rx buffer.
+ else if (read_reg(ISR) & PRX)
+ {
+ byte status;
+ byte len;
+ byte current;
+
+ // Retrieve packet header. (status, next_ptr, length_l, length_h)
+
+ // Obtiene el buffer a leer actualmente
+ recv_state.curr_buf = read_reg(BNRY) + 1;
+ if (recv_state.curr_buf >= RX_PAGE_STOP)
+ recv_state.curr_buf = RX_PAGE_START;
+
+ // Select RTL8019AS register page 1.
+ SELECT_REG_PAGE(1);
+
+ // Retrieve current receive buffer page
+ current = read_reg(CURR);
+
+ // Select RTL8019AS register page 1.
+ SELECT_REG_PAGE(0);
+
+ // Check if last packet has been removed from rx buffer.
+ if(recv_state.curr_buf == current)
+ {
+ // Clear packet received interrupt flag.
+ write_reg(ISR, PRX | RXE);
+ return 0;
+ }
+
+ // Set remote DMA byte count registers to packet header length.
+ recv_state.curr_off = 0;
+ netdev_read_start(BUF_HDR_SIZE);
+
+ // Packet status.
+ status = netdev_read_byte();
+
+ // Save next packet pointer.
+ recv_state.next_buf = netdev_read_byte() - 1;
+
+ // Retrieve packet data length and subtract CRC bytes.
+ len = netdev_read_byte() - BUF_HDR_SIZE;
+
+ // Si es muy grande, muy chico o hubo error, lo descartamos
+ if ((len < MIN_PACKET_LEN) || (len > MAX_PACKET_LEN)
+ || ((status & 0x0F) != RXSOK)
+ || netdev_read_byte()) // Parte alta del tamaño
+ {
+ // Terminamos DMA y pasamos al próximo frame
+ netdev_read_end();
+ write_reg(BNRY, recv_state.next_buf);
+ return 0;
+ }
+
+ // Abort/ complete DMA operation.
+ netdev_read_end();
+
+ return len;
+ }
+
+ return 0;
+}
+
+/** Finaliza la recepción del frame
+ * @precond netdev_recv_start() debe haber sido ejecutada
+ */
+void netdev_recv_end()
+{
+ // Pasa el próximo frame
+ write_reg(BNRY, recv_state.next_buf);
+}
+
+void netdev_read_start(byte len)
+{
+ // Set remote DMA start address registers to packet data.
+ write_reg(RSAR0, recv_state.curr_off);
+ write_reg(RSAR1, recv_state.curr_buf);
+ recv_state.curr_off += len;
+
+ // Set remote DMA byte count registers to packet data length.
+ write_reg(RBCR0, len);
+ write_reg(RBCR1, 0);
+
+ // Initiate DMA transfer of packet data.
+ write_reg(CR, READ);
+}
+
+/** Lee un byte del buffer de la placa de red
+ * @precond netdev_recv_start() debe haber sido ejecutada
+ */
+byte netdev_read_byte()
+{
+ return read_reg(RDMA);
+}
+
+/** Lee un word del buffer de la placa de red
+ * @precond netdev_recv_start() debe haber sido ejecutada
+ */
+uint16 netdev_read_word()
+{
+ uint16 w = read_reg(RDMA) << 8;
+ return w + read_reg(RDMA);
+}
+
+/** Finaliza la lectura del frame
+ * @precond netdev_recv_start() debe haber sido ejecutada
+ */
+void netdev_read_end()
+{
+ // Completa DMA
+ ABORT_DMA(START);
+}
+