qemu/hw/net/cadence_gem.c
<<
>>
Prefs
   1/*
   2 * QEMU Cadence GEM emulation
   3 *
   4 * Copyright (c) 2011 Xilinx, Inc.
   5 *
   6 * Permission is hereby granted, free of charge, to any person obtaining a copy
   7 * of this software and associated documentation files (the "Software"), to deal
   8 * in the Software without restriction, including without limitation the rights
   9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10 * copies of the Software, and to permit persons to whom the Software is
  11 * furnished to do so, subject to the following conditions:
  12 *
  13 * The above copyright notice and this permission notice shall be included in
  14 * all copies or substantial portions of the Software.
  15 *
  16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22 * THE SOFTWARE.
  23 */
  24
  25#include "qemu/osdep.h"
  26#include <zlib.h> /* For crc32 */
  27
  28#include "hw/irq.h"
  29#include "hw/net/cadence_gem.h"
  30#include "hw/qdev-properties.h"
  31#include "migration/vmstate.h"
  32#include "qapi/error.h"
  33#include "qemu/log.h"
  34#include "qemu/module.h"
  35#include "sysemu/dma.h"
  36#include "net/checksum.h"
  37#include "net/eth.h"
  38#include "exec/address-spaces.h"
  39
  40#define CADENCE_GEM_ERR_DEBUG 0
  41#define DB_PRINT(...) do {\
  42    if (CADENCE_GEM_ERR_DEBUG) {   \
  43        qemu_log(": %s: ", __func__); \
  44        qemu_log(__VA_ARGS__); \
  45    } \
  46} while (0);
  47
  48#define GEM_NWCTRL        (0x00000000/4) /* Network Control reg */
  49#define GEM_NWCFG         (0x00000004/4) /* Network Config reg */
  50#define GEM_NWSTATUS      (0x00000008/4) /* Network Status reg */
  51#define GEM_USERIO        (0x0000000C/4) /* User IO reg */
  52#define GEM_DMACFG        (0x00000010/4) /* DMA Control reg */
  53#define GEM_TXSTATUS      (0x00000014/4) /* TX Status reg */
  54#define GEM_RXQBASE       (0x00000018/4) /* RX Q Base address reg */
  55#define GEM_TXQBASE       (0x0000001C/4) /* TX Q Base address reg */
  56#define GEM_RXSTATUS      (0x00000020/4) /* RX Status reg */
  57#define GEM_ISR           (0x00000024/4) /* Interrupt Status reg */
  58#define GEM_IER           (0x00000028/4) /* Interrupt Enable reg */
  59#define GEM_IDR           (0x0000002C/4) /* Interrupt Disable reg */
  60#define GEM_IMR           (0x00000030/4) /* Interrupt Mask reg */
  61#define GEM_PHYMNTNC      (0x00000034/4) /* Phy Maintenance reg */
  62#define GEM_RXPAUSE       (0x00000038/4) /* RX Pause Time reg */
  63#define GEM_TXPAUSE       (0x0000003C/4) /* TX Pause Time reg */
  64#define GEM_TXPARTIALSF   (0x00000040/4) /* TX Partial Store and Forward */
  65#define GEM_RXPARTIALSF   (0x00000044/4) /* RX Partial Store and Forward */
  66#define GEM_HASHLO        (0x00000080/4) /* Hash Low address reg */
  67#define GEM_HASHHI        (0x00000084/4) /* Hash High address reg */
  68#define GEM_SPADDR1LO     (0x00000088/4) /* Specific addr 1 low reg */
  69#define GEM_SPADDR1HI     (0x0000008C/4) /* Specific addr 1 high reg */
  70#define GEM_SPADDR2LO     (0x00000090/4) /* Specific addr 2 low reg */
  71#define GEM_SPADDR2HI     (0x00000094/4) /* Specific addr 2 high reg */
  72#define GEM_SPADDR3LO     (0x00000098/4) /* Specific addr 3 low reg */
  73#define GEM_SPADDR3HI     (0x0000009C/4) /* Specific addr 3 high reg */
  74#define GEM_SPADDR4LO     (0x000000A0/4) /* Specific addr 4 low reg */
  75#define GEM_SPADDR4HI     (0x000000A4/4) /* Specific addr 4 high reg */
  76#define GEM_TIDMATCH1     (0x000000A8/4) /* Type ID1 Match reg */
  77#define GEM_TIDMATCH2     (0x000000AC/4) /* Type ID2 Match reg */
  78#define GEM_TIDMATCH3     (0x000000B0/4) /* Type ID3 Match reg */
  79#define GEM_TIDMATCH4     (0x000000B4/4) /* Type ID4 Match reg */
  80#define GEM_WOLAN         (0x000000B8/4) /* Wake on LAN reg */
  81#define GEM_IPGSTRETCH    (0x000000BC/4) /* IPG Stretch reg */
  82#define GEM_SVLAN         (0x000000C0/4) /* Stacked VLAN reg */
  83#define GEM_MODID         (0x000000FC/4) /* Module ID reg */
  84#define GEM_OCTTXLO       (0x00000100/4) /* Octects transmitted Low reg */
  85#define GEM_OCTTXHI       (0x00000104/4) /* Octects transmitted High reg */
  86#define GEM_TXCNT         (0x00000108/4) /* Error-free Frames transmitted */
  87#define GEM_TXBCNT        (0x0000010C/4) /* Error-free Broadcast Frames */
  88#define GEM_TXMCNT        (0x00000110/4) /* Error-free Multicast Frame */
  89#define GEM_TXPAUSECNT    (0x00000114/4) /* Pause Frames Transmitted */
  90#define GEM_TX64CNT       (0x00000118/4) /* Error-free 64 TX */
  91#define GEM_TX65CNT       (0x0000011C/4) /* Error-free 65-127 TX */
  92#define GEM_TX128CNT      (0x00000120/4) /* Error-free 128-255 TX */
  93#define GEM_TX256CNT      (0x00000124/4) /* Error-free 256-511 */
  94#define GEM_TX512CNT      (0x00000128/4) /* Error-free 512-1023 TX */
  95#define GEM_TX1024CNT     (0x0000012C/4) /* Error-free 1024-1518 TX */
  96#define GEM_TX1519CNT     (0x00000130/4) /* Error-free larger than 1519 TX */
  97#define GEM_TXURUNCNT     (0x00000134/4) /* TX under run error counter */
  98#define GEM_SINGLECOLLCNT (0x00000138/4) /* Single Collision Frames */
  99#define GEM_MULTCOLLCNT   (0x0000013C/4) /* Multiple Collision Frames */
 100#define GEM_EXCESSCOLLCNT (0x00000140/4) /* Excessive Collision Frames */
 101#define GEM_LATECOLLCNT   (0x00000144/4) /* Late Collision Frames */
 102#define GEM_DEFERTXCNT    (0x00000148/4) /* Deferred Transmission Frames */
 103#define GEM_CSENSECNT     (0x0000014C/4) /* Carrier Sense Error Counter */
 104#define GEM_OCTRXLO       (0x00000150/4) /* Octects Received register Low */
 105#define GEM_OCTRXHI       (0x00000154/4) /* Octects Received register High */
 106#define GEM_RXCNT         (0x00000158/4) /* Error-free Frames Received */
 107#define GEM_RXBROADCNT    (0x0000015C/4) /* Error-free Broadcast Frames RX */
 108#define GEM_RXMULTICNT    (0x00000160/4) /* Error-free Multicast Frames RX */
 109#define GEM_RXPAUSECNT    (0x00000164/4) /* Pause Frames Received Counter */
 110#define GEM_RX64CNT       (0x00000168/4) /* Error-free 64 byte Frames RX */
 111#define GEM_RX65CNT       (0x0000016C/4) /* Error-free 65-127B Frames RX */
 112#define GEM_RX128CNT      (0x00000170/4) /* Error-free 128-255B Frames RX */
 113#define GEM_RX256CNT      (0x00000174/4) /* Error-free 256-512B Frames RX */
 114#define GEM_RX512CNT      (0x00000178/4) /* Error-free 512-1023B Frames RX */
 115#define GEM_RX1024CNT     (0x0000017C/4) /* Error-free 1024-1518B Frames RX */
 116#define GEM_RX1519CNT     (0x00000180/4) /* Error-free 1519-max Frames RX */
 117#define GEM_RXUNDERCNT    (0x00000184/4) /* Undersize Frames Received */
 118#define GEM_RXOVERCNT     (0x00000188/4) /* Oversize Frames Received */
 119#define GEM_RXJABCNT      (0x0000018C/4) /* Jabbers Received Counter */
 120#define GEM_RXFCSCNT      (0x00000190/4) /* Frame Check seq. Error Counter */
 121#define GEM_RXLENERRCNT   (0x00000194/4) /* Length Field Error Counter */
 122#define GEM_RXSYMERRCNT   (0x00000198/4) /* Symbol Error Counter */
 123#define GEM_RXALIGNERRCNT (0x0000019C/4) /* Alignment Error Counter */
 124#define GEM_RXRSCERRCNT   (0x000001A0/4) /* Receive Resource Error Counter */
 125#define GEM_RXORUNCNT     (0x000001A4/4) /* Receive Overrun Counter */
 126#define GEM_RXIPCSERRCNT  (0x000001A8/4) /* IP header Checksum Error Counter */
 127#define GEM_RXTCPCCNT     (0x000001AC/4) /* TCP Checksum Error Counter */
 128#define GEM_RXUDPCCNT     (0x000001B0/4) /* UDP Checksum Error Counter */
 129
 130#define GEM_1588S         (0x000001D0/4) /* 1588 Timer Seconds */
 131#define GEM_1588NS        (0x000001D4/4) /* 1588 Timer Nanoseconds */
 132#define GEM_1588ADJ       (0x000001D8/4) /* 1588 Timer Adjust */
 133#define GEM_1588INC       (0x000001DC/4) /* 1588 Timer Increment */
 134#define GEM_PTPETXS       (0x000001E0/4) /* PTP Event Frame Transmitted (s) */
 135#define GEM_PTPETXNS      (0x000001E4/4) /* PTP Event Frame Transmitted (ns) */
 136#define GEM_PTPERXS       (0x000001E8/4) /* PTP Event Frame Received (s) */
 137#define GEM_PTPERXNS      (0x000001EC/4) /* PTP Event Frame Received (ns) */
 138#define GEM_PTPPTXS       (0x000001E0/4) /* PTP Peer Frame Transmitted (s) */
 139#define GEM_PTPPTXNS      (0x000001E4/4) /* PTP Peer Frame Transmitted (ns) */
 140#define GEM_PTPPRXS       (0x000001E8/4) /* PTP Peer Frame Received (s) */
 141#define GEM_PTPPRXNS      (0x000001EC/4) /* PTP Peer Frame Received (ns) */
 142
 143/* Design Configuration Registers */
 144#define GEM_DESCONF       (0x00000280/4)
 145#define GEM_DESCONF2      (0x00000284/4)
 146#define GEM_DESCONF3      (0x00000288/4)
 147#define GEM_DESCONF4      (0x0000028C/4)
 148#define GEM_DESCONF5      (0x00000290/4)
 149#define GEM_DESCONF6      (0x00000294/4)
 150#define GEM_DESCONF6_64B_MASK (1U << 23)
 151#define GEM_DESCONF7      (0x00000298/4)
 152
 153#define GEM_INT_Q1_STATUS               (0x00000400 / 4)
 154#define GEM_INT_Q1_MASK                 (0x00000640 / 4)
 155
 156#define GEM_TRANSMIT_Q1_PTR             (0x00000440 / 4)
 157#define GEM_TRANSMIT_Q7_PTR             (GEM_TRANSMIT_Q1_PTR + 6)
 158
 159#define GEM_RECEIVE_Q1_PTR              (0x00000480 / 4)
 160#define GEM_RECEIVE_Q7_PTR              (GEM_RECEIVE_Q1_PTR + 6)
 161
 162#define GEM_TBQPH                       (0x000004C8 / 4)
 163#define GEM_RBQPH                       (0x000004D4 / 4)
 164
 165#define GEM_INT_Q1_ENABLE               (0x00000600 / 4)
 166#define GEM_INT_Q7_ENABLE               (GEM_INT_Q1_ENABLE + 6)
 167
 168#define GEM_INT_Q1_DISABLE              (0x00000620 / 4)
 169#define GEM_INT_Q7_DISABLE              (GEM_INT_Q1_DISABLE + 6)
 170
 171#define GEM_INT_Q1_MASK                 (0x00000640 / 4)
 172#define GEM_INT_Q7_MASK                 (GEM_INT_Q1_MASK + 6)
 173
 174#define GEM_SCREENING_TYPE1_REGISTER_0  (0x00000500 / 4)
 175
 176#define GEM_ST1R_UDP_PORT_MATCH_ENABLE  (1 << 29)
 177#define GEM_ST1R_DSTC_ENABLE            (1 << 28)
 178#define GEM_ST1R_UDP_PORT_MATCH_SHIFT   (12)
 179#define GEM_ST1R_UDP_PORT_MATCH_WIDTH   (27 - GEM_ST1R_UDP_PORT_MATCH_SHIFT + 1)
 180#define GEM_ST1R_DSTC_MATCH_SHIFT       (4)
 181#define GEM_ST1R_DSTC_MATCH_WIDTH       (11 - GEM_ST1R_DSTC_MATCH_SHIFT + 1)
 182#define GEM_ST1R_QUEUE_SHIFT            (0)
 183#define GEM_ST1R_QUEUE_WIDTH            (3 - GEM_ST1R_QUEUE_SHIFT + 1)
 184
 185#define GEM_SCREENING_TYPE2_REGISTER_0  (0x00000540 / 4)
 186
 187#define GEM_ST2R_COMPARE_A_ENABLE       (1 << 18)
 188#define GEM_ST2R_COMPARE_A_SHIFT        (13)
 189#define GEM_ST2R_COMPARE_WIDTH          (17 - GEM_ST2R_COMPARE_A_SHIFT + 1)
 190#define GEM_ST2R_ETHERTYPE_ENABLE       (1 << 12)
 191#define GEM_ST2R_ETHERTYPE_INDEX_SHIFT  (9)
 192#define GEM_ST2R_ETHERTYPE_INDEX_WIDTH  (11 - GEM_ST2R_ETHERTYPE_INDEX_SHIFT \
 193                                            + 1)
 194#define GEM_ST2R_QUEUE_SHIFT            (0)
 195#define GEM_ST2R_QUEUE_WIDTH            (3 - GEM_ST2R_QUEUE_SHIFT + 1)
 196
 197#define GEM_SCREENING_TYPE2_ETHERTYPE_REG_0     (0x000006e0 / 4)
 198#define GEM_TYPE2_COMPARE_0_WORD_0              (0x00000700 / 4)
 199
 200#define GEM_T2CW1_COMPARE_OFFSET_SHIFT  (7)
 201#define GEM_T2CW1_COMPARE_OFFSET_WIDTH  (8 - GEM_T2CW1_COMPARE_OFFSET_SHIFT + 1)
 202#define GEM_T2CW1_OFFSET_VALUE_SHIFT    (0)
 203#define GEM_T2CW1_OFFSET_VALUE_WIDTH    (6 - GEM_T2CW1_OFFSET_VALUE_SHIFT + 1)
 204
 205/*****************************************/
 206#define GEM_NWCTRL_TXSTART     0x00000200 /* Transmit Enable */
 207#define GEM_NWCTRL_TXENA       0x00000008 /* Transmit Enable */
 208#define GEM_NWCTRL_RXENA       0x00000004 /* Receive Enable */
 209#define GEM_NWCTRL_LOCALLOOP   0x00000002 /* Local Loopback */
 210
 211#define GEM_NWCFG_STRIP_FCS    0x00020000 /* Strip FCS field */
 212#define GEM_NWCFG_LERR_DISC    0x00010000 /* Discard RX frames with len err */
 213#define GEM_NWCFG_BUFF_OFST_M  0x0000C000 /* Receive buffer offset mask */
 214#define GEM_NWCFG_BUFF_OFST_S  14         /* Receive buffer offset shift */
 215#define GEM_NWCFG_UCAST_HASH   0x00000080 /* accept unicast if hash match */
 216#define GEM_NWCFG_MCAST_HASH   0x00000040 /* accept multicast if hash match */
 217#define GEM_NWCFG_BCAST_REJ    0x00000020 /* Reject broadcast packets */
 218#define GEM_NWCFG_PROMISC      0x00000010 /* Accept all packets */
 219
 220#define GEM_DMACFG_ADDR_64B    (1U << 30)
 221#define GEM_DMACFG_TX_BD_EXT   (1U << 29)
 222#define GEM_DMACFG_RX_BD_EXT   (1U << 28)
 223#define GEM_DMACFG_RBUFSZ_M    0x00FF0000 /* DMA RX Buffer Size mask */
 224#define GEM_DMACFG_RBUFSZ_S    16         /* DMA RX Buffer Size shift */
 225#define GEM_DMACFG_RBUFSZ_MUL  64         /* DMA RX Buffer Size multiplier */
 226#define GEM_DMACFG_TXCSUM_OFFL 0x00000800 /* Transmit checksum offload */
 227
 228#define GEM_TXSTATUS_TXCMPL    0x00000020 /* Transmit Complete */
 229#define GEM_TXSTATUS_USED      0x00000001 /* sw owned descriptor encountered */
 230
 231#define GEM_RXSTATUS_FRMRCVD   0x00000002 /* Frame received */
 232#define GEM_RXSTATUS_NOBUF     0x00000001 /* Buffer unavailable */
 233
 234/* GEM_ISR GEM_IER GEM_IDR GEM_IMR */
 235#define GEM_INT_TXCMPL        0x00000080 /* Transmit Complete */
 236#define GEM_INT_TXUSED         0x00000008
 237#define GEM_INT_RXUSED         0x00000004
 238#define GEM_INT_RXCMPL        0x00000002
 239
 240#define GEM_PHYMNTNC_OP_R      0x20000000 /* read operation */
 241#define GEM_PHYMNTNC_OP_W      0x10000000 /* write operation */
 242#define GEM_PHYMNTNC_ADDR      0x0F800000 /* Address bits */
 243#define GEM_PHYMNTNC_ADDR_SHFT 23
 244#define GEM_PHYMNTNC_REG       0x007C0000 /* register bits */
 245#define GEM_PHYMNTNC_REG_SHIFT 18
 246
 247/* Marvell PHY definitions */
 248#define BOARD_PHY_ADDRESS    7 /* PHY address we will emulate a device at */
 249
 250#define PHY_REG_CONTROL      0
 251#define PHY_REG_STATUS       1
 252#define PHY_REG_PHYID1       2
 253#define PHY_REG_PHYID2       3
 254#define PHY_REG_ANEGADV      4
 255#define PHY_REG_LINKPABIL    5
 256#define PHY_REG_ANEGEXP      6
 257#define PHY_REG_NEXTP        7
 258#define PHY_REG_LINKPNEXTP   8
 259#define PHY_REG_100BTCTRL    9
 260#define PHY_REG_1000BTSTAT   10
 261#define PHY_REG_EXTSTAT      15
 262#define PHY_REG_PHYSPCFC_CTL 16
 263#define PHY_REG_PHYSPCFC_ST  17
 264#define PHY_REG_INT_EN       18
 265#define PHY_REG_INT_ST       19
 266#define PHY_REG_EXT_PHYSPCFC_CTL  20
 267#define PHY_REG_RXERR        21
 268#define PHY_REG_EACD         22
 269#define PHY_REG_LED          24
 270#define PHY_REG_LED_OVRD     25
 271#define PHY_REG_EXT_PHYSPCFC_CTL2 26
 272#define PHY_REG_EXT_PHYSPCFC_ST   27
 273#define PHY_REG_CABLE_DIAG   28
 274
 275#define PHY_REG_CONTROL_RST       0x8000
 276#define PHY_REG_CONTROL_LOOP      0x4000
 277#define PHY_REG_CONTROL_ANEG      0x1000
 278#define PHY_REG_CONTROL_ANRESTART 0x0200
 279
 280#define PHY_REG_STATUS_LINK     0x0004
 281#define PHY_REG_STATUS_ANEGCMPL 0x0020
 282
 283#define PHY_REG_INT_ST_ANEGCMPL 0x0800
 284#define PHY_REG_INT_ST_LINKC    0x0400
 285#define PHY_REG_INT_ST_ENERGY   0x0010
 286
 287/***********************************************************************/
 288#define GEM_RX_REJECT                   (-1)
 289#define GEM_RX_PROMISCUOUS_ACCEPT       (-2)
 290#define GEM_RX_BROADCAST_ACCEPT         (-3)
 291#define GEM_RX_MULTICAST_HASH_ACCEPT    (-4)
 292#define GEM_RX_UNICAST_HASH_ACCEPT      (-5)
 293
 294#define GEM_RX_SAR_ACCEPT               0
 295
 296/***********************************************************************/
 297
 298#define DESC_1_USED 0x80000000
 299#define DESC_1_LENGTH 0x00003FFF
 300
 301#define DESC_1_TX_WRAP 0x40000000
 302#define DESC_1_TX_LAST 0x00008000
 303
 304#define DESC_0_RX_WRAP 0x00000002
 305#define DESC_0_RX_OWNERSHIP 0x00000001
 306
 307#define R_DESC_1_RX_SAR_SHIFT           25
 308#define R_DESC_1_RX_SAR_LENGTH          2
 309#define R_DESC_1_RX_SAR_MATCH           (1 << 27)
 310#define R_DESC_1_RX_UNICAST_HASH        (1 << 29)
 311#define R_DESC_1_RX_MULTICAST_HASH      (1 << 30)
 312#define R_DESC_1_RX_BROADCAST           (1 << 31)
 313
 314#define DESC_1_RX_SOF 0x00004000
 315#define DESC_1_RX_EOF 0x00008000
 316
 317#define GEM_MODID_VALUE 0x00020118
 318
 319static inline uint64_t tx_desc_get_buffer(CadenceGEMState *s, uint32_t *desc)
 320{
 321    uint64_t ret = desc[0];
 322
 323    if (s->regs[GEM_DMACFG] & GEM_DMACFG_ADDR_64B) {
 324        ret |= (uint64_t)desc[2] << 32;
 325    }
 326    return ret;
 327}
 328
 329static inline unsigned tx_desc_get_used(uint32_t *desc)
 330{
 331    return (desc[1] & DESC_1_USED) ? 1 : 0;
 332}
 333
 334static inline void tx_desc_set_used(uint32_t *desc)
 335{
 336    desc[1] |= DESC_1_USED;
 337}
 338
 339static inline unsigned tx_desc_get_wrap(uint32_t *desc)
 340{
 341    return (desc[1] & DESC_1_TX_WRAP) ? 1 : 0;
 342}
 343
 344static inline unsigned tx_desc_get_last(uint32_t *desc)
 345{
 346    return (desc[1] & DESC_1_TX_LAST) ? 1 : 0;
 347}
 348
 349static inline unsigned tx_desc_get_length(uint32_t *desc)
 350{
 351    return desc[1] & DESC_1_LENGTH;
 352}
 353
 354static inline void print_gem_tx_desc(uint32_t *desc, uint8_t queue)
 355{
 356    DB_PRINT("TXDESC (queue %" PRId8 "):\n", queue);
 357    DB_PRINT("bufaddr: 0x%08x\n", *desc);
 358    DB_PRINT("used_hw: %d\n", tx_desc_get_used(desc));
 359    DB_PRINT("wrap:    %d\n", tx_desc_get_wrap(desc));
 360    DB_PRINT("last:    %d\n", tx_desc_get_last(desc));
 361    DB_PRINT("length:  %d\n", tx_desc_get_length(desc));
 362}
 363
 364static inline uint64_t rx_desc_get_buffer(CadenceGEMState *s, uint32_t *desc)
 365{
 366    uint64_t ret = desc[0] & ~0x3UL;
 367
 368    if (s->regs[GEM_DMACFG] & GEM_DMACFG_ADDR_64B) {
 369        ret |= (uint64_t)desc[2] << 32;
 370    }
 371    return ret;
 372}
 373
 374static inline int gem_get_desc_len(CadenceGEMState *s, bool rx_n_tx)
 375{
 376    int ret = 2;
 377
 378    if (s->regs[GEM_DMACFG] & GEM_DMACFG_ADDR_64B) {
 379        ret += 2;
 380    }
 381    if (s->regs[GEM_DMACFG] & (rx_n_tx ? GEM_DMACFG_RX_BD_EXT
 382                                       : GEM_DMACFG_TX_BD_EXT)) {
 383        ret += 2;
 384    }
 385
 386    assert(ret <= DESC_MAX_NUM_WORDS);
 387    return ret;
 388}
 389
 390static inline unsigned rx_desc_get_wrap(uint32_t *desc)
 391{
 392    return desc[0] & DESC_0_RX_WRAP ? 1 : 0;
 393}
 394
 395static inline unsigned rx_desc_get_ownership(uint32_t *desc)
 396{
 397    return desc[0] & DESC_0_RX_OWNERSHIP ? 1 : 0;
 398}
 399
 400static inline void rx_desc_set_ownership(uint32_t *desc)
 401{
 402    desc[0] |= DESC_0_RX_OWNERSHIP;
 403}
 404
 405static inline void rx_desc_set_sof(uint32_t *desc)
 406{
 407    desc[1] |= DESC_1_RX_SOF;
 408}
 409
 410static inline void rx_desc_clear_control(uint32_t *desc)
 411{
 412    desc[1]  = 0;
 413}
 414
 415static inline void rx_desc_set_eof(uint32_t *desc)
 416{
 417    desc[1] |= DESC_1_RX_EOF;
 418}
 419
 420static inline void rx_desc_set_length(uint32_t *desc, unsigned len)
 421{
 422    desc[1] &= ~DESC_1_LENGTH;
 423    desc[1] |= len;
 424}
 425
 426static inline void rx_desc_set_broadcast(uint32_t *desc)
 427{
 428    desc[1] |= R_DESC_1_RX_BROADCAST;
 429}
 430
 431static inline void rx_desc_set_unicast_hash(uint32_t *desc)
 432{
 433    desc[1] |= R_DESC_1_RX_UNICAST_HASH;
 434}
 435
 436static inline void rx_desc_set_multicast_hash(uint32_t *desc)
 437{
 438    desc[1] |= R_DESC_1_RX_MULTICAST_HASH;
 439}
 440
 441static inline void rx_desc_set_sar(uint32_t *desc, int sar_idx)
 442{
 443    desc[1] = deposit32(desc[1], R_DESC_1_RX_SAR_SHIFT, R_DESC_1_RX_SAR_LENGTH,
 444                        sar_idx);
 445    desc[1] |= R_DESC_1_RX_SAR_MATCH;
 446}
 447
 448/* The broadcast MAC address: 0xFFFFFFFFFFFF */
 449static const uint8_t broadcast_addr[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
 450
 451/*
 452 * gem_init_register_masks:
 453 * One time initialization.
 454 * Set masks to identify which register bits have magical clear properties
 455 */
 456static void gem_init_register_masks(CadenceGEMState *s)
 457{
 458    unsigned int i;
 459    /* Mask of register bits which are read only */
 460    memset(&s->regs_ro[0], 0, sizeof(s->regs_ro));
 461    s->regs_ro[GEM_NWCTRL]   = 0xFFF80000;
 462    s->regs_ro[GEM_NWSTATUS] = 0xFFFFFFFF;
 463    s->regs_ro[GEM_DMACFG]   = 0x8E00F000;
 464    s->regs_ro[GEM_TXSTATUS] = 0xFFFFFE08;
 465    s->regs_ro[GEM_RXQBASE]  = 0x00000003;
 466    s->regs_ro[GEM_TXQBASE]  = 0x00000003;
 467    s->regs_ro[GEM_RXSTATUS] = 0xFFFFFFF0;
 468    s->regs_ro[GEM_ISR]      = 0xFFFFFFFF;
 469    s->regs_ro[GEM_IMR]      = 0xFFFFFFFF;
 470    s->regs_ro[GEM_MODID]    = 0xFFFFFFFF;
 471    for (i = 0; i < s->num_priority_queues; i++) {
 472        s->regs_ro[GEM_INT_Q1_STATUS + i] = 0xFFFFFFFF;
 473        s->regs_ro[GEM_INT_Q1_ENABLE + i] = 0xFFFFE319;
 474        s->regs_ro[GEM_INT_Q1_DISABLE + i] = 0xFFFFE319;
 475        s->regs_ro[GEM_INT_Q1_MASK + i] = 0xFFFFFFFF;
 476    }
 477
 478    /* Mask of register bits which are clear on read */
 479    memset(&s->regs_rtc[0], 0, sizeof(s->regs_rtc));
 480    s->regs_rtc[GEM_ISR]      = 0xFFFFFFFF;
 481    for (i = 0; i < s->num_priority_queues; i++) {
 482        s->regs_rtc[GEM_INT_Q1_STATUS + i] = 0x00000CE6;
 483    }
 484
 485    /* Mask of register bits which are write 1 to clear */
 486    memset(&s->regs_w1c[0], 0, sizeof(s->regs_w1c));
 487    s->regs_w1c[GEM_TXSTATUS] = 0x000001F7;
 488    s->regs_w1c[GEM_RXSTATUS] = 0x0000000F;
 489
 490    /* Mask of register bits which are write only */
 491    memset(&s->regs_wo[0], 0, sizeof(s->regs_wo));
 492    s->regs_wo[GEM_NWCTRL]   = 0x00073E60;
 493    s->regs_wo[GEM_IER]      = 0x07FFFFFF;
 494    s->regs_wo[GEM_IDR]      = 0x07FFFFFF;
 495    for (i = 0; i < s->num_priority_queues; i++) {
 496        s->regs_wo[GEM_INT_Q1_ENABLE + i] = 0x00000CE6;
 497        s->regs_wo[GEM_INT_Q1_DISABLE + i] = 0x00000CE6;
 498    }
 499}
 500
 501/*
 502 * phy_update_link:
 503 * Make the emulated PHY link state match the QEMU "interface" state.
 504 */
 505static void phy_update_link(CadenceGEMState *s)
 506{
 507    DB_PRINT("down %d\n", qemu_get_queue(s->nic)->link_down);
 508
 509    /* Autonegotiation status mirrors link status.  */
 510    if (qemu_get_queue(s->nic)->link_down) {
 511        s->phy_regs[PHY_REG_STATUS] &= ~(PHY_REG_STATUS_ANEGCMPL |
 512                                         PHY_REG_STATUS_LINK);
 513        s->phy_regs[PHY_REG_INT_ST] |= PHY_REG_INT_ST_LINKC;
 514    } else {
 515        s->phy_regs[PHY_REG_STATUS] |= (PHY_REG_STATUS_ANEGCMPL |
 516                                         PHY_REG_STATUS_LINK);
 517        s->phy_regs[PHY_REG_INT_ST] |= (PHY_REG_INT_ST_LINKC |
 518                                        PHY_REG_INT_ST_ANEGCMPL |
 519                                        PHY_REG_INT_ST_ENERGY);
 520    }
 521}
 522
 523static bool gem_can_receive(NetClientState *nc)
 524{
 525    CadenceGEMState *s;
 526    int i;
 527
 528    s = qemu_get_nic_opaque(nc);
 529
 530    /* Do nothing if receive is not enabled. */
 531    if (!(s->regs[GEM_NWCTRL] & GEM_NWCTRL_RXENA)) {
 532        if (s->can_rx_state != 1) {
 533            s->can_rx_state = 1;
 534            DB_PRINT("can't receive - no enable\n");
 535        }
 536        return false;
 537    }
 538
 539    for (i = 0; i < s->num_priority_queues; i++) {
 540        if (rx_desc_get_ownership(s->rx_desc[i]) != 1) {
 541            break;
 542        }
 543    };
 544
 545    if (i == s->num_priority_queues) {
 546        if (s->can_rx_state != 2) {
 547            s->can_rx_state = 2;
 548            DB_PRINT("can't receive - all the buffer descriptors are busy\n");
 549        }
 550        return false;
 551    }
 552
 553    if (s->can_rx_state != 0) {
 554        s->can_rx_state = 0;
 555        DB_PRINT("can receive\n");
 556    }
 557    return true;
 558}
 559
 560/*
 561 * gem_update_int_status:
 562 * Raise or lower interrupt based on current status.
 563 */
 564static void gem_update_int_status(CadenceGEMState *s)
 565{
 566    int i;
 567
 568    qemu_set_irq(s->irq[0], !!s->regs[GEM_ISR]);
 569
 570    for (i = 1; i < s->num_priority_queues; ++i) {
 571        qemu_set_irq(s->irq[i], !!s->regs[GEM_INT_Q1_STATUS + i - 1]);
 572    }
 573}
 574
 575/*
 576 * gem_receive_updatestats:
 577 * Increment receive statistics.
 578 */
 579static void gem_receive_updatestats(CadenceGEMState *s, const uint8_t *packet,
 580                                    unsigned bytes)
 581{
 582    uint64_t octets;
 583
 584    /* Total octets (bytes) received */
 585    octets = ((uint64_t)(s->regs[GEM_OCTRXLO]) << 32) |
 586             s->regs[GEM_OCTRXHI];
 587    octets += bytes;
 588    s->regs[GEM_OCTRXLO] = octets >> 32;
 589    s->regs[GEM_OCTRXHI] = octets;
 590
 591    /* Error-free Frames received */
 592    s->regs[GEM_RXCNT]++;
 593
 594    /* Error-free Broadcast Frames counter */
 595    if (!memcmp(packet, broadcast_addr, 6)) {
 596        s->regs[GEM_RXBROADCNT]++;
 597    }
 598
 599    /* Error-free Multicast Frames counter */
 600    if (packet[0] == 0x01) {
 601        s->regs[GEM_RXMULTICNT]++;
 602    }
 603
 604    if (bytes <= 64) {
 605        s->regs[GEM_RX64CNT]++;
 606    } else if (bytes <= 127) {
 607        s->regs[GEM_RX65CNT]++;
 608    } else if (bytes <= 255) {
 609        s->regs[GEM_RX128CNT]++;
 610    } else if (bytes <= 511) {
 611        s->regs[GEM_RX256CNT]++;
 612    } else if (bytes <= 1023) {
 613        s->regs[GEM_RX512CNT]++;
 614    } else if (bytes <= 1518) {
 615        s->regs[GEM_RX1024CNT]++;
 616    } else {
 617        s->regs[GEM_RX1519CNT]++;
 618    }
 619}
 620
 621/*
 622 * Get the MAC Address bit from the specified position
 623 */
 624static unsigned get_bit(const uint8_t *mac, unsigned bit)
 625{
 626    unsigned byte;
 627
 628    byte = mac[bit / 8];
 629    byte >>= (bit & 0x7);
 630    byte &= 1;
 631
 632    return byte;
 633}
 634
 635/*
 636 * Calculate a GEM MAC Address hash index
 637 */
 638static unsigned calc_mac_hash(const uint8_t *mac)
 639{
 640    int index_bit, mac_bit;
 641    unsigned hash_index;
 642
 643    hash_index = 0;
 644    mac_bit = 5;
 645    for (index_bit = 5; index_bit >= 0; index_bit--) {
 646        hash_index |= (get_bit(mac,  mac_bit) ^
 647                               get_bit(mac, mac_bit + 6) ^
 648                               get_bit(mac, mac_bit + 12) ^
 649                               get_bit(mac, mac_bit + 18) ^
 650                               get_bit(mac, mac_bit + 24) ^
 651                               get_bit(mac, mac_bit + 30) ^
 652                               get_bit(mac, mac_bit + 36) ^
 653                               get_bit(mac, mac_bit + 42)) << index_bit;
 654        mac_bit--;
 655    }
 656
 657    return hash_index;
 658}
 659
 660/*
 661 * gem_mac_address_filter:
 662 * Accept or reject this destination address?
 663 * Returns:
 664 * GEM_RX_REJECT: reject
 665 * >= 0: Specific address accept (which matched SAR is returned)
 666 * others for various other modes of accept:
 667 * GEM_RM_PROMISCUOUS_ACCEPT, GEM_RX_BROADCAST_ACCEPT,
 668 * GEM_RX_MULTICAST_HASH_ACCEPT or GEM_RX_UNICAST_HASH_ACCEPT
 669 */
 670static int gem_mac_address_filter(CadenceGEMState *s, const uint8_t *packet)
 671{
 672    uint8_t *gem_spaddr;
 673    int i, is_mc;
 674
 675    /* Promiscuous mode? */
 676    if (s->regs[GEM_NWCFG] & GEM_NWCFG_PROMISC) {
 677        return GEM_RX_PROMISCUOUS_ACCEPT;
 678    }
 679
 680    if (!memcmp(packet, broadcast_addr, 6)) {
 681        /* Reject broadcast packets? */
 682        if (s->regs[GEM_NWCFG] & GEM_NWCFG_BCAST_REJ) {
 683            return GEM_RX_REJECT;
 684        }
 685        return GEM_RX_BROADCAST_ACCEPT;
 686    }
 687
 688    /* Accept packets -w- hash match? */
 689    is_mc = is_multicast_ether_addr(packet);
 690    if ((is_mc && (s->regs[GEM_NWCFG] & GEM_NWCFG_MCAST_HASH)) ||
 691        (!is_mc && (s->regs[GEM_NWCFG] & GEM_NWCFG_UCAST_HASH))) {
 692        uint64_t buckets;
 693        unsigned hash_index;
 694
 695        hash_index = calc_mac_hash(packet);
 696        buckets = ((uint64_t)s->regs[GEM_HASHHI] << 32) | s->regs[GEM_HASHLO];
 697        if ((buckets >> hash_index) & 1) {
 698            return is_mc ? GEM_RX_MULTICAST_HASH_ACCEPT
 699                         : GEM_RX_UNICAST_HASH_ACCEPT;
 700        }
 701    }
 702
 703    /* Check all 4 specific addresses */
 704    gem_spaddr = (uint8_t *)&(s->regs[GEM_SPADDR1LO]);
 705    for (i = 3; i >= 0; i--) {
 706        if (s->sar_active[i] && !memcmp(packet, gem_spaddr + 8 * i, 6)) {
 707            return GEM_RX_SAR_ACCEPT + i;
 708        }
 709    }
 710
 711    /* No address match; reject the packet */
 712    return GEM_RX_REJECT;
 713}
 714
 715/* Figure out which queue the received data should be sent to */
 716static int get_queue_from_screen(CadenceGEMState *s, uint8_t *rxbuf_ptr,
 717                                 unsigned rxbufsize)
 718{
 719    uint32_t reg;
 720    bool matched, mismatched;
 721    int i, j;
 722
 723    for (i = 0; i < s->num_type1_screeners; i++) {
 724        reg = s->regs[GEM_SCREENING_TYPE1_REGISTER_0 + i];
 725        matched = false;
 726        mismatched = false;
 727
 728        /* Screening is based on UDP Port */
 729        if (reg & GEM_ST1R_UDP_PORT_MATCH_ENABLE) {
 730            uint16_t udp_port = rxbuf_ptr[14 + 22] << 8 | rxbuf_ptr[14 + 23];
 731            if (udp_port == extract32(reg, GEM_ST1R_UDP_PORT_MATCH_SHIFT,
 732                                           GEM_ST1R_UDP_PORT_MATCH_WIDTH)) {
 733                matched = true;
 734            } else {
 735                mismatched = true;
 736            }
 737        }
 738
 739        /* Screening is based on DS/TC */
 740        if (reg & GEM_ST1R_DSTC_ENABLE) {
 741            uint8_t dscp = rxbuf_ptr[14 + 1];
 742            if (dscp == extract32(reg, GEM_ST1R_DSTC_MATCH_SHIFT,
 743                                       GEM_ST1R_DSTC_MATCH_WIDTH)) {
 744                matched = true;
 745            } else {
 746                mismatched = true;
 747            }
 748        }
 749
 750        if (matched && !mismatched) {
 751            return extract32(reg, GEM_ST1R_QUEUE_SHIFT, GEM_ST1R_QUEUE_WIDTH);
 752        }
 753    }
 754
 755    for (i = 0; i < s->num_type2_screeners; i++) {
 756        reg = s->regs[GEM_SCREENING_TYPE2_REGISTER_0 + i];
 757        matched = false;
 758        mismatched = false;
 759
 760        if (reg & GEM_ST2R_ETHERTYPE_ENABLE) {
 761            uint16_t type = rxbuf_ptr[12] << 8 | rxbuf_ptr[13];
 762            int et_idx = extract32(reg, GEM_ST2R_ETHERTYPE_INDEX_SHIFT,
 763                                        GEM_ST2R_ETHERTYPE_INDEX_WIDTH);
 764
 765            if (et_idx > s->num_type2_screeners) {
 766                qemu_log_mask(LOG_GUEST_ERROR, "Out of range ethertype "
 767                              "register index: %d\n", et_idx);
 768            }
 769            if (type == s->regs[GEM_SCREENING_TYPE2_ETHERTYPE_REG_0 +
 770                                et_idx]) {
 771                matched = true;
 772            } else {
 773                mismatched = true;
 774            }
 775        }
 776
 777        /* Compare A, B, C */
 778        for (j = 0; j < 3; j++) {
 779            uint32_t cr0, cr1, mask;
 780            uint16_t rx_cmp;
 781            int offset;
 782            int cr_idx = extract32(reg, GEM_ST2R_COMPARE_A_SHIFT + j * 6,
 783                                        GEM_ST2R_COMPARE_WIDTH);
 784
 785            if (!(reg & (GEM_ST2R_COMPARE_A_ENABLE << (j * 6)))) {
 786                continue;
 787            }
 788            if (cr_idx > s->num_type2_screeners) {
 789                qemu_log_mask(LOG_GUEST_ERROR, "Out of range compare "
 790                              "register index: %d\n", cr_idx);
 791            }
 792
 793            cr0 = s->regs[GEM_TYPE2_COMPARE_0_WORD_0 + cr_idx * 2];
 794            cr1 = s->regs[GEM_TYPE2_COMPARE_0_WORD_0 + cr_idx * 2 + 1];
 795            offset = extract32(cr1, GEM_T2CW1_OFFSET_VALUE_SHIFT,
 796                                    GEM_T2CW1_OFFSET_VALUE_WIDTH);
 797
 798            switch (extract32(cr1, GEM_T2CW1_COMPARE_OFFSET_SHIFT,
 799                                   GEM_T2CW1_COMPARE_OFFSET_WIDTH)) {
 800            case 3: /* Skip UDP header */
 801                qemu_log_mask(LOG_UNIMP, "TCP compare offsets"
 802                              "unimplemented - assuming UDP\n");
 803                offset += 8;
 804                /* Fallthrough */
 805            case 2: /* skip the IP header */
 806                offset += 20;
 807                /* Fallthrough */
 808            case 1: /* Count from after the ethertype */
 809                offset += 14;
 810                break;
 811            case 0:
 812                /* Offset from start of frame */
 813                break;
 814            }
 815
 816            rx_cmp = rxbuf_ptr[offset] << 8 | rxbuf_ptr[offset];
 817            mask = extract32(cr0, 0, 16);
 818
 819            if ((rx_cmp & mask) == (extract32(cr0, 16, 16) & mask)) {
 820                matched = true;
 821            } else {
 822                mismatched = true;
 823            }
 824        }
 825
 826        if (matched && !mismatched) {
 827            return extract32(reg, GEM_ST2R_QUEUE_SHIFT, GEM_ST2R_QUEUE_WIDTH);
 828        }
 829    }
 830
 831    /* We made it here, assume it's queue 0 */
 832    return 0;
 833}
 834
 835static uint32_t gem_get_queue_base_addr(CadenceGEMState *s, bool tx, int q)
 836{
 837    uint32_t base_addr = 0;
 838
 839    switch (q) {
 840    case 0:
 841        base_addr = s->regs[tx ? GEM_TXQBASE : GEM_RXQBASE];
 842        break;
 843    case 1 ... (MAX_PRIORITY_QUEUES - 1):
 844        base_addr = s->regs[(tx ? GEM_TRANSMIT_Q1_PTR :
 845                                 GEM_RECEIVE_Q1_PTR) + q - 1];
 846        break;
 847    default:
 848        g_assert_not_reached();
 849    };
 850
 851    return base_addr;
 852}
 853
 854static hwaddr gem_get_desc_addr(CadenceGEMState *s, bool tx, int q)
 855{
 856    hwaddr desc_addr = 0;
 857
 858    if (s->regs[GEM_DMACFG] & GEM_DMACFG_ADDR_64B) {
 859        desc_addr = s->regs[tx ? GEM_TBQPH : GEM_RBQPH];
 860    }
 861    desc_addr <<= 32;
 862    desc_addr |= tx ? s->tx_desc_addr[q] : s->rx_desc_addr[q];
 863    return desc_addr;
 864}
 865
 866static hwaddr gem_get_tx_desc_addr(CadenceGEMState *s, int q)
 867{
 868    return gem_get_desc_addr(s, true, q);
 869}
 870
 871static hwaddr gem_get_rx_desc_addr(CadenceGEMState *s, int q)
 872{
 873    return gem_get_desc_addr(s, false, q);
 874}
 875
 876static void gem_get_rx_desc(CadenceGEMState *s, int q)
 877{
 878    hwaddr desc_addr = gem_get_rx_desc_addr(s, q);
 879
 880    DB_PRINT("read descriptor 0x%" HWADDR_PRIx "\n", desc_addr);
 881
 882    /* read current descriptor */
 883    address_space_read(&s->dma_as, desc_addr, *s->attr,
 884                     (uint8_t *)s->rx_desc[q],
 885                     sizeof(uint32_t) * gem_get_desc_len(s, true));
 886
 887    /* Descriptor owned by software ? */
 888    if (rx_desc_get_ownership(s->rx_desc[q]) == 1) {
 889        DB_PRINT("descriptor 0x%" HWADDR_PRIx " owned by sw.\n", desc_addr);
 890        s->regs[GEM_RXSTATUS] |= GEM_RXSTATUS_NOBUF;
 891        if (q == 0) {
 892            s->regs[GEM_ISR] |= GEM_INT_RXUSED & ~(s->regs[GEM_IMR]);
 893        } else {
 894            s->regs[GEM_INT_Q1_STATUS + q - 1] |= GEM_INT_RXUSED &
 895                                          ~(s->regs[GEM_INT_Q1_MASK + q - 1]);
 896        }
 897
 898        /* Handle interrupt consequences */
 899        gem_update_int_status(s);
 900    }
 901}
 902
 903/*
 904 * gem_receive:
 905 * Fit a packet handed to us by QEMU into the receive descriptor ring.
 906 */
 907static ssize_t gem_receive(NetClientState *nc, const uint8_t *buf, size_t size)
 908{
 909    CadenceGEMState *s;
 910    unsigned   rxbufsize, bytes_to_copy;
 911    unsigned   rxbuf_offset;
 912    uint8_t    rxbuf[2048];
 913    uint8_t   *rxbuf_ptr;
 914    bool first_desc = true;
 915    int maf;
 916    int q = 0;
 917
 918    s = qemu_get_nic_opaque(nc);
 919
 920    /* Is this destination MAC address "for us" ? */
 921    maf = gem_mac_address_filter(s, buf);
 922    if (maf == GEM_RX_REJECT) {
 923        return size;  /* no, drop siliently b/c it's not an error */
 924    }
 925
 926    /* Discard packets with receive length error enabled ? */
 927    if (s->regs[GEM_NWCFG] & GEM_NWCFG_LERR_DISC) {
 928        unsigned type_len;
 929
 930        /* Fish the ethertype / length field out of the RX packet */
 931        type_len = buf[12] << 8 | buf[13];
 932        /* It is a length field, not an ethertype */
 933        if (type_len < 0x600) {
 934            if (size < type_len) {
 935                /* discard */
 936                return -1;
 937            }
 938        }
 939    }
 940
 941    /*
 942     * Determine configured receive buffer offset (probably 0)
 943     */
 944    rxbuf_offset = (s->regs[GEM_NWCFG] & GEM_NWCFG_BUFF_OFST_M) >>
 945                   GEM_NWCFG_BUFF_OFST_S;
 946
 947    /* The configure size of each receive buffer.  Determines how many
 948     * buffers needed to hold this packet.
 949     */
 950    rxbufsize = ((s->regs[GEM_DMACFG] & GEM_DMACFG_RBUFSZ_M) >>
 951                 GEM_DMACFG_RBUFSZ_S) * GEM_DMACFG_RBUFSZ_MUL;
 952    bytes_to_copy = size;
 953
 954    /* Hardware allows a zero value here but warns against it. To avoid QEMU
 955     * indefinite loops we enforce a minimum value here
 956     */
 957    if (rxbufsize < GEM_DMACFG_RBUFSZ_MUL) {
 958        rxbufsize = GEM_DMACFG_RBUFSZ_MUL;
 959    }
 960
 961    /* Pad to minimum length. Assume FCS field is stripped, logic
 962     * below will increment it to the real minimum of 64 when
 963     * not FCS stripping
 964     */
 965    if (size < 60) {
 966        size = 60;
 967    }
 968
 969    /* Strip of FCS field ? (usually yes) */
 970    if (s->regs[GEM_NWCFG] & GEM_NWCFG_STRIP_FCS) {
 971        rxbuf_ptr = (void *)buf;
 972    } else {
 973        unsigned crc_val;
 974
 975        if (size > sizeof(rxbuf) - sizeof(crc_val)) {
 976            size = sizeof(rxbuf) - sizeof(crc_val);
 977        }
 978        bytes_to_copy = size;
 979        /* The application wants the FCS field, which QEMU does not provide.
 980         * We must try and calculate one.
 981         */
 982
 983        memcpy(rxbuf, buf, size);
 984        memset(rxbuf + size, 0, sizeof(rxbuf) - size);
 985        rxbuf_ptr = rxbuf;
 986        crc_val = cpu_to_le32(crc32(0, rxbuf, MAX(size, 60)));
 987        memcpy(rxbuf + size, &crc_val, sizeof(crc_val));
 988
 989        bytes_to_copy += 4;
 990        size += 4;
 991    }
 992
 993    DB_PRINT("config bufsize: %d packet size: %ld\n", rxbufsize, size);
 994
 995    /* Find which queue we are targeting */
 996    q = get_queue_from_screen(s, rxbuf_ptr, rxbufsize);
 997
 998    while (bytes_to_copy) {
 999        hwaddr desc_addr;
1000
1001        /* Do nothing if receive is not enabled. */
1002        if (!gem_can_receive(nc)) {
1003            return -1;
1004        }
1005
1006        DB_PRINT("copy %u bytes to 0x%" PRIx64 "\n",
1007                 MIN(bytes_to_copy, rxbufsize),
1008                 rx_desc_get_buffer(s, s->rx_desc[q]));
1009
1010        /* Copy packet data to emulated DMA buffer */
1011        address_space_write(&s->dma_as, rx_desc_get_buffer(s, s->rx_desc[q]) +
1012                                                                  rxbuf_offset,
1013                            *s->attr, rxbuf_ptr,
1014                            MIN(bytes_to_copy, rxbufsize));
1015        rxbuf_ptr += MIN(bytes_to_copy, rxbufsize);
1016        bytes_to_copy -= MIN(bytes_to_copy, rxbufsize);
1017
1018        rx_desc_clear_control(s->rx_desc[q]);
1019
1020        /* Update the descriptor.  */
1021        if (first_desc) {
1022            rx_desc_set_sof(s->rx_desc[q]);
1023            first_desc = false;
1024        }
1025        if (bytes_to_copy == 0) {
1026            rx_desc_set_eof(s->rx_desc[q]);
1027            rx_desc_set_length(s->rx_desc[q], size);
1028        }
1029        rx_desc_set_ownership(s->rx_desc[q]);
1030
1031        switch (maf) {
1032        case GEM_RX_PROMISCUOUS_ACCEPT:
1033            break;
1034        case GEM_RX_BROADCAST_ACCEPT:
1035            rx_desc_set_broadcast(s->rx_desc[q]);
1036            break;
1037        case GEM_RX_UNICAST_HASH_ACCEPT:
1038            rx_desc_set_unicast_hash(s->rx_desc[q]);
1039            break;
1040        case GEM_RX_MULTICAST_HASH_ACCEPT:
1041            rx_desc_set_multicast_hash(s->rx_desc[q]);
1042            break;
1043        case GEM_RX_REJECT:
1044            abort();
1045        default: /* SAR */
1046            rx_desc_set_sar(s->rx_desc[q], maf);
1047        }
1048
1049        /* Descriptor write-back.  */
1050        desc_addr = gem_get_rx_desc_addr(s, q);
1051        address_space_write(&s->dma_as, desc_addr,
1052                            *s->attr,
1053                            (uint8_t *)s->rx_desc[q],
1054                            sizeof(uint32_t) * gem_get_desc_len(s, true));
1055
1056        /* Next descriptor */
1057        if (rx_desc_get_wrap(s->rx_desc[q])) {
1058            DB_PRINT("wrapping RX descriptor list\n");
1059            s->rx_desc_addr[q] = gem_get_queue_base_addr(s, false, q);
1060        } else {
1061            DB_PRINT("incrementing RX descriptor list\n");
1062            s->rx_desc_addr[q] += 4 * gem_get_desc_len(s, true);
1063        }
1064
1065        gem_get_rx_desc(s, q);
1066    }
1067
1068    /* Count it */
1069    gem_receive_updatestats(s, buf, size);
1070
1071    s->regs[GEM_RXSTATUS] |= GEM_RXSTATUS_FRMRCVD;
1072    if (q == 0) {
1073        s->regs[GEM_ISR] |= GEM_INT_RXCMPL & ~(s->regs[GEM_IMR]);
1074    } else {
1075        s->regs[GEM_INT_Q1_STATUS + q - 1] |= GEM_INT_RXCMPL &
1076                                      ~(s->regs[GEM_INT_Q1_MASK + q - 1]);
1077    }
1078    /* Handle interrupt consequences */
1079    gem_update_int_status(s);
1080
1081    return size;
1082}
1083
1084/*
1085 * gem_transmit_updatestats:
1086 * Increment transmit statistics.
1087 */
1088static void gem_transmit_updatestats(CadenceGEMState *s, const uint8_t *packet,
1089                                     unsigned bytes)
1090{
1091    uint64_t octets;
1092
1093    /* Total octets (bytes) transmitted */
1094    octets = ((uint64_t)(s->regs[GEM_OCTTXLO]) << 32) |
1095             s->regs[GEM_OCTTXHI];
1096    octets += bytes;
1097    s->regs[GEM_OCTTXLO] = octets >> 32;
1098    s->regs[GEM_OCTTXHI] = octets;
1099
1100    /* Error-free Frames transmitted */
1101    s->regs[GEM_TXCNT]++;
1102
1103    /* Error-free Broadcast Frames counter */
1104    if (!memcmp(packet, broadcast_addr, 6)) {
1105        s->regs[GEM_TXBCNT]++;
1106    }
1107
1108    /* Error-free Multicast Frames counter */
1109    if (packet[0] == 0x01) {
1110        s->regs[GEM_TXMCNT]++;
1111    }
1112
1113    if (bytes <= 64) {
1114        s->regs[GEM_TX64CNT]++;
1115    } else if (bytes <= 127) {
1116        s->regs[GEM_TX65CNT]++;
1117    } else if (bytes <= 255) {
1118        s->regs[GEM_TX128CNT]++;
1119    } else if (bytes <= 511) {
1120        s->regs[GEM_TX256CNT]++;
1121    } else if (bytes <= 1023) {
1122        s->regs[GEM_TX512CNT]++;
1123    } else if (bytes <= 1518) {
1124        s->regs[GEM_TX1024CNT]++;
1125    } else {
1126        s->regs[GEM_TX1519CNT]++;
1127    }
1128}
1129
1130/*
1131 * gem_transmit:
1132 * Fish packets out of the descriptor ring and feed them to QEMU
1133 */
1134static void gem_transmit(CadenceGEMState *s)
1135{
1136    uint32_t desc[DESC_MAX_NUM_WORDS];
1137    hwaddr packet_desc_addr;
1138    uint8_t     tx_packet[10240];
1139    uint8_t     *p;
1140    unsigned    total_bytes;
1141    int q = 0;
1142
1143    /* Do nothing if transmit is not enabled. */
1144    if (!(s->regs[GEM_NWCTRL] & GEM_NWCTRL_TXENA)) {
1145        return;
1146    }
1147
1148    DB_PRINT("\n");
1149
1150    /* The packet we will hand off to QEMU.
1151     * Packets scattered across multiple descriptors are gathered to this
1152     * one contiguous buffer first.
1153     */
1154    p = tx_packet;
1155    total_bytes = 0;
1156
1157    for (q = s->num_priority_queues - 1; q >= 0; q--) {
1158        /* read current descriptor */
1159        packet_desc_addr = gem_get_tx_desc_addr(s, q);
1160
1161        DB_PRINT("read descriptor 0x%" HWADDR_PRIx "\n", packet_desc_addr);
1162        address_space_read(&s->dma_as, packet_desc_addr,
1163                           *s->attr, (uint8_t *)desc,
1164                           sizeof(uint32_t) * gem_get_desc_len(s, false));
1165        /* Handle all descriptors owned by hardware */
1166        while (tx_desc_get_used(desc) == 0) {
1167
1168            /* Do nothing if transmit is not enabled. */
1169            if (!(s->regs[GEM_NWCTRL] & GEM_NWCTRL_TXENA)) {
1170                return;
1171            }
1172            print_gem_tx_desc(desc, q);
1173
1174            /* The real hardware would eat this (and possibly crash).
1175             * For QEMU let's lend a helping hand.
1176             */
1177            if ((tx_desc_get_buffer(s, desc) == 0) ||
1178                (tx_desc_get_length(desc) == 0)) {
1179                DB_PRINT("Invalid TX descriptor @ 0x%" HWADDR_PRIx "\n",
1180                         packet_desc_addr);
1181                break;
1182            }
1183
1184            if (tx_desc_get_length(desc) > sizeof(tx_packet) -
1185                                               (p - tx_packet)) {
1186                DB_PRINT("TX descriptor @ 0x%" HWADDR_PRIx \
1187                         " too large: size 0x%x space 0x%zx\n",
1188                         packet_desc_addr, tx_desc_get_length(desc),
1189                         sizeof(tx_packet) - (p - tx_packet));
1190                break;
1191            }
1192
1193            /* Gather this fragment of the packet from "dma memory" to our
1194             * contig buffer.
1195             */
1196            address_space_read(&s->dma_as, tx_desc_get_buffer(s, desc),
1197                               *s->attr,
1198                               p, tx_desc_get_length(desc));
1199            p += tx_desc_get_length(desc);
1200            total_bytes += tx_desc_get_length(desc);
1201
1202            /* Last descriptor for this packet; hand the whole thing off */
1203            if (tx_desc_get_last(desc)) {
1204                uint32_t desc_first[DESC_MAX_NUM_WORDS];
1205                hwaddr desc_addr = gem_get_tx_desc_addr(s, q);
1206
1207                /* Modify the 1st descriptor of this packet to be owned by
1208                 * the processor.
1209                 */
1210                address_space_read(&s->dma_as, desc_addr,
1211                                   *s->attr,
1212                                   (uint8_t *)desc_first,
1213                                   sizeof(desc_first));
1214                tx_desc_set_used(desc_first);
1215                address_space_write(&s->dma_as, desc_addr,
1216                                   *s->attr,
1217                                   (uint8_t *)desc_first,
1218                                    sizeof(desc_first));
1219                /* Advance the hardware current descriptor past this packet */
1220                if (tx_desc_get_wrap(desc)) {
1221                    s->tx_desc_addr[q] = gem_get_queue_base_addr(s,
1222                                         true, q);
1223                } else {
1224                    s->tx_desc_addr[q] = (uint32_t)packet_desc_addr +
1225                                         4 * gem_get_desc_len(s, false);
1226                }
1227                DB_PRINT("TX descriptor next: 0x%08x\n", s->tx_desc_addr[q]);
1228
1229                s->regs[GEM_TXSTATUS] |= GEM_TXSTATUS_TXCMPL;
1230                if (q == 0) {
1231                    s->regs[GEM_ISR] |= GEM_INT_TXCMPL & ~(s->regs[GEM_IMR]);
1232                } else {
1233                /* Update queue interrupt status */
1234                    s->regs[GEM_INT_Q1_STATUS + q - 1] |=
1235                            GEM_INT_TXCMPL & ~s->regs[GEM_INT_Q1_MASK + q - 1];
1236                }
1237
1238                /* Handle interrupt consequences */
1239                gem_update_int_status(s);
1240
1241                /* Is checksum offload enabled? */
1242                if (s->regs[GEM_DMACFG] & GEM_DMACFG_TXCSUM_OFFL) {
1243                    net_checksum_calculate(tx_packet, total_bytes);
1244                }
1245
1246                /* Update MAC statistics */
1247                gem_transmit_updatestats(s, tx_packet, total_bytes);
1248
1249                /* Send the packet somewhere */
1250                if (s->phy_loop || (s->regs[GEM_NWCTRL] &
1251                                    GEM_NWCTRL_LOCALLOOP)) {
1252                    gem_receive(qemu_get_queue(s->nic), tx_packet,
1253                                total_bytes);
1254                } else {
1255                    qemu_send_packet(qemu_get_queue(s->nic), tx_packet,
1256                                     total_bytes);
1257                }
1258
1259                /* Prepare for next packet */
1260                p = tx_packet;
1261                total_bytes = 0;
1262            }
1263
1264            /* read next descriptor */
1265            if (tx_desc_get_wrap(desc)) {
1266                packet_desc_addr = 0;
1267                if (s->regs[GEM_DMACFG] & GEM_DMACFG_ADDR_64B) {
1268                    packet_desc_addr = s->regs[GEM_TBQPH];
1269                    packet_desc_addr <<= 32;
1270                }
1271                packet_desc_addr |= gem_get_queue_base_addr(s, true, q);
1272            } else {
1273                packet_desc_addr += 4 * gem_get_desc_len(s, false);
1274            }
1275            DB_PRINT("read descriptor 0x%" HWADDR_PRIx "\n", packet_desc_addr);
1276            address_space_read(&s->dma_as, packet_desc_addr,
1277                               *s->attr, (uint8_t *)desc,
1278                               sizeof(uint32_t) * gem_get_desc_len(s, false));
1279        }
1280
1281        if (tx_desc_get_used(desc)) {
1282            s->regs[GEM_TXSTATUS] |= GEM_TXSTATUS_USED;
1283            /* IRQ TXUSED is defined only for queue 0 */
1284            if (q == 0) {
1285                s->regs[GEM_ISR] |= GEM_INT_TXUSED & ~(s->regs[GEM_IMR]);
1286            }
1287            gem_update_int_status(s);
1288        }
1289    }
1290}
1291
1292static void gem_phy_reset(CadenceGEMState *s)
1293{
1294    memset(&s->phy_regs[0], 0, sizeof(s->phy_regs));
1295    s->phy_regs[PHY_REG_CONTROL] = 0x1140;
1296    s->phy_regs[PHY_REG_STATUS] = 0x7969;
1297    s->phy_regs[PHY_REG_PHYID1] = 0x0141;
1298    s->phy_regs[PHY_REG_PHYID2] = 0x0CC2;
1299    s->phy_regs[PHY_REG_ANEGADV] = 0x01E1;
1300    s->phy_regs[PHY_REG_LINKPABIL] = 0xCDE1;
1301    s->phy_regs[PHY_REG_ANEGEXP] = 0x000F;
1302    s->phy_regs[PHY_REG_NEXTP] = 0x2001;
1303    s->phy_regs[PHY_REG_LINKPNEXTP] = 0x40E6;
1304    s->phy_regs[PHY_REG_100BTCTRL] = 0x0300;
1305    s->phy_regs[PHY_REG_1000BTSTAT] = 0x7C00;
1306    s->phy_regs[PHY_REG_EXTSTAT] = 0x3000;
1307    s->phy_regs[PHY_REG_PHYSPCFC_CTL] = 0x0078;
1308    s->phy_regs[PHY_REG_PHYSPCFC_ST] = 0x7C00;
1309    s->phy_regs[PHY_REG_EXT_PHYSPCFC_CTL] = 0x0C60;
1310    s->phy_regs[PHY_REG_LED] = 0x4100;
1311    s->phy_regs[PHY_REG_EXT_PHYSPCFC_CTL2] = 0x000A;
1312    s->phy_regs[PHY_REG_EXT_PHYSPCFC_ST] = 0x848B;
1313
1314    phy_update_link(s);
1315}
1316
1317static void gem_reset(DeviceState *d)
1318{
1319    int i;
1320    CadenceGEMState *s = CADENCE_GEM(d);
1321    const uint8_t *a;
1322    uint32_t queues_mask = 0;
1323
1324    DB_PRINT("\n");
1325
1326    /* Set post reset register values */
1327    memset(&s->regs[0], 0, sizeof(s->regs));
1328    s->regs[GEM_NWCFG] = 0x00080000;
1329    s->regs[GEM_NWSTATUS] = 0x00000006;
1330    s->regs[GEM_DMACFG] = 0x00020784;
1331    s->regs[GEM_IMR] = 0x07ffffff;
1332    s->regs[GEM_TXPAUSE] = 0x0000ffff;
1333    s->regs[GEM_TXPARTIALSF] = 0x000003ff;
1334    s->regs[GEM_RXPARTIALSF] = 0x000003ff;
1335    s->regs[GEM_MODID] = s->revision;
1336    s->regs[GEM_DESCONF] = 0x02D00111;
1337    s->regs[GEM_DESCONF2] = 0x2ab12800;
1338    s->regs[GEM_DESCONF5] = 0x002f2045;
1339    s->regs[GEM_DESCONF6] = GEM_DESCONF6_64B_MASK;
1340    s->regs[GEM_INT_Q1_MASK] = 0x00000CE6;
1341
1342    if (s->num_priority_queues > 1) {
1343        queues_mask = MAKE_64BIT_MASK(1, s->num_priority_queues - 1);
1344        s->regs[GEM_DESCONF6] |= queues_mask;
1345    }
1346
1347    /* Set MAC address */
1348    a = &s->conf.macaddr.a[0];
1349    s->regs[GEM_SPADDR1LO] = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24);
1350    s->regs[GEM_SPADDR1HI] = a[4] | (a[5] << 8);
1351
1352    for (i = 0; i < 4; i++) {
1353        s->sar_active[i] = false;
1354    }
1355
1356    if (s->mdio) {
1357        phy_update_link(s);
1358    } else {
1359        gem_phy_reset(s);
1360    }
1361
1362    gem_update_int_status(s);
1363}
1364
1365static uint16_t gem_phy_read(CadenceGEMState *s, unsigned reg_num)
1366{
1367    DB_PRINT("reg: %d value: 0x%04x\n", reg_num, s->phy_regs[reg_num]);
1368
1369    assert(!s->mdio);
1370
1371    return s->phy_regs[reg_num];
1372}
1373
1374static void gem_phy_write(CadenceGEMState *s, unsigned reg_num, uint16_t val)
1375{
1376    DB_PRINT("reg: %d value: 0x%04x\n", reg_num, val);
1377
1378    assert(!s->mdio);
1379
1380    switch (reg_num) {
1381    case PHY_REG_CONTROL:
1382        if (val & PHY_REG_CONTROL_RST) {
1383            /* Phy reset */
1384            gem_phy_reset(s);
1385            val &= ~(PHY_REG_CONTROL_RST | PHY_REG_CONTROL_LOOP);
1386            s->phy_loop = 0;
1387        }
1388        if (val & PHY_REG_CONTROL_ANEG) {
1389            /* Complete autonegotiation immediately */
1390            val &= ~(PHY_REG_CONTROL_ANEG | PHY_REG_CONTROL_ANRESTART);
1391            s->phy_regs[PHY_REG_STATUS] |= PHY_REG_STATUS_ANEGCMPL;
1392        }
1393        if (val & PHY_REG_CONTROL_LOOP) {
1394            DB_PRINT("PHY placed in loopback\n");
1395            s->phy_loop = 1;
1396        } else {
1397            s->phy_loop = 0;
1398        }
1399        break;
1400    }
1401    s->phy_regs[reg_num] = val;
1402}
1403
1404static void gem_phy_loopback_setup(CadenceGEMState *s, unsigned reg_num,
1405                                   uint16_t val)
1406{
1407    assert(s->mdio);
1408
1409    switch (reg_num) {
1410    case PHY_REG_CONTROL:
1411        if (val & PHY_REG_CONTROL_RST) {
1412            /* Phy reset */
1413            s->phy_loop = 0;
1414        }
1415        if (val & PHY_REG_CONTROL_LOOP) {
1416            DB_PRINT("PHY placed in loopback\n");
1417            s->phy_loop = 1;
1418        } else {
1419            s->phy_loop = 0;
1420        }
1421        break;
1422    }
1423}
1424
1425/*
1426 * gem_read32:
1427 * Read a GEM register.
1428 */
1429static uint64_t gem_read(void *opaque, hwaddr offset, unsigned size)
1430{
1431    CadenceGEMState *s;
1432    uint32_t retval;
1433    s = (CadenceGEMState *)opaque;
1434
1435    offset >>= 2;
1436    retval = s->regs[offset];
1437
1438    DB_PRINT("offset: 0x%04x read: 0x%08x\n", (unsigned)offset*4, retval);
1439
1440    switch (offset) {
1441    case GEM_ISR:
1442        DB_PRINT("lowering irqs on ISR read\n");
1443        /* The interrupts get updated at the end of the function. */
1444        break;
1445    case GEM_PHYMNTNC:
1446        if (retval & GEM_PHYMNTNC_OP_R) {
1447            uint32_t phy_addr, reg_num;
1448
1449            phy_addr = (retval & GEM_PHYMNTNC_ADDR) >> GEM_PHYMNTNC_ADDR_SHFT;
1450            if (s->mdio) {
1451                reg_num = (retval & GEM_PHYMNTNC_REG) >> GEM_PHYMNTNC_REG_SHIFT;
1452                retval &= 0xFFFF0000;
1453                retval |= s->mdio->read(s->mdio, phy_addr, reg_num);
1454            } else if (phy_addr == BOARD_PHY_ADDRESS || phy_addr == 0) {
1455                reg_num = (retval & GEM_PHYMNTNC_REG) >> GEM_PHYMNTNC_REG_SHIFT;
1456                retval &= 0xFFFF0000;
1457                retval |= gem_phy_read(s, reg_num);
1458            } else {
1459                retval |= 0xFFFF; /* No device at this address */
1460            }
1461        }
1462        break;
1463    }
1464
1465    /* Squash read to clear bits */
1466    s->regs[offset] &= ~(s->regs_rtc[offset]);
1467
1468    /* Do not provide write only bits */
1469    retval &= ~(s->regs_wo[offset]);
1470
1471    DB_PRINT("0x%08x\n", retval);
1472    gem_update_int_status(s);
1473    return retval;
1474}
1475
1476/*
1477 * gem_write32:
1478 * Write a GEM register.
1479 */
1480static void gem_write(void *opaque, hwaddr offset, uint64_t val,
1481        unsigned size)
1482{
1483    CadenceGEMState *s = (CadenceGEMState *)opaque;
1484    uint32_t readonly;
1485    int i;
1486
1487    DB_PRINT("offset: 0x%04x write: 0x%08x ", (unsigned)offset, (unsigned)val);
1488    offset >>= 2;
1489
1490    /* Squash bits which are read only in write value */
1491    val &= ~(s->regs_ro[offset]);
1492    /* Preserve (only) bits which are read only and wtc in register */
1493    readonly = s->regs[offset] & (s->regs_ro[offset] | s->regs_w1c[offset]);
1494
1495    /* Copy register write to backing store */
1496    s->regs[offset] = (val & ~s->regs_w1c[offset]) | readonly;
1497
1498    /* do w1c */
1499    s->regs[offset] &= ~(s->regs_w1c[offset] & val);
1500
1501    /* Handle register write side effects */
1502    switch (offset) {
1503    case GEM_NWCTRL:
1504        if (val & GEM_NWCTRL_RXENA) {
1505            for (i = 0; i < s->num_priority_queues; ++i) {
1506                gem_get_rx_desc(s, i);
1507            }
1508        }
1509        if (val & GEM_NWCTRL_TXSTART) {
1510            gem_transmit(s);
1511        }
1512        if (!(val & GEM_NWCTRL_TXENA)) {
1513            /* Reset to start of Q when transmit disabled. */
1514            for (i = 0; i < s->num_priority_queues; i++) {
1515                s->tx_desc_addr[i] = gem_get_queue_base_addr(s, true, i);
1516            }
1517        }
1518        if (gem_can_receive(qemu_get_queue(s->nic))) {
1519            qemu_flush_queued_packets(qemu_get_queue(s->nic));
1520        }
1521        break;
1522
1523    case GEM_TXSTATUS:
1524        gem_update_int_status(s);
1525        break;
1526    case GEM_RXQBASE:
1527        s->rx_desc_addr[0] = val;
1528        break;
1529    case GEM_RECEIVE_Q1_PTR ... GEM_RECEIVE_Q7_PTR:
1530        s->rx_desc_addr[offset - GEM_RECEIVE_Q1_PTR + 1] = val;
1531        break;
1532    case GEM_TXQBASE:
1533        s->tx_desc_addr[0] = val;
1534        break;
1535    case GEM_TRANSMIT_Q1_PTR ... GEM_TRANSMIT_Q7_PTR:
1536        s->tx_desc_addr[offset - GEM_TRANSMIT_Q1_PTR + 1] = val;
1537        break;
1538    case GEM_RXSTATUS:
1539        gem_update_int_status(s);
1540        break;
1541    case GEM_IER:
1542        s->regs[GEM_IMR] &= ~val;
1543        gem_update_int_status(s);
1544        break;
1545    case GEM_INT_Q1_ENABLE ... GEM_INT_Q7_ENABLE:
1546        s->regs[GEM_INT_Q1_MASK + offset - GEM_INT_Q1_ENABLE] &= ~val;
1547        gem_update_int_status(s);
1548        break;
1549    case GEM_IDR:
1550        s->regs[GEM_IMR] |= val;
1551        gem_update_int_status(s);
1552        break;
1553    case GEM_INT_Q1_DISABLE ... GEM_INT_Q7_DISABLE:
1554        s->regs[GEM_INT_Q1_MASK + offset - GEM_INT_Q1_DISABLE] |= val;
1555        gem_update_int_status(s);
1556        break;
1557    case GEM_SPADDR1LO:
1558    case GEM_SPADDR2LO:
1559    case GEM_SPADDR3LO:
1560    case GEM_SPADDR4LO:
1561        s->sar_active[(offset - GEM_SPADDR1LO) / 2] = false;
1562        break;
1563    case GEM_SPADDR1HI:
1564    case GEM_SPADDR2HI:
1565    case GEM_SPADDR3HI:
1566    case GEM_SPADDR4HI:
1567        s->sar_active[(offset - GEM_SPADDR1HI) / 2] = true;
1568        break;
1569    case GEM_PHYMNTNC:
1570        if (val & GEM_PHYMNTNC_OP_W) {
1571            uint32_t phy_addr, reg_num;
1572
1573            phy_addr = (val & GEM_PHYMNTNC_ADDR) >> GEM_PHYMNTNC_ADDR_SHFT;
1574            if (s->mdio) {
1575                reg_num = (val & GEM_PHYMNTNC_REG) >> GEM_PHYMNTNC_REG_SHIFT;
1576                gem_phy_loopback_setup(s, reg_num, val);
1577                s->mdio->write(s->mdio, phy_addr, reg_num, val);
1578            } else if (phy_addr == BOARD_PHY_ADDRESS || phy_addr == 0) {
1579                reg_num = (val & GEM_PHYMNTNC_REG) >> GEM_PHYMNTNC_REG_SHIFT;
1580                gem_phy_write(s, reg_num, val);
1581            }
1582        }
1583        break;
1584    }
1585
1586    DB_PRINT("newval: 0x%08x\n", s->regs[offset]);
1587}
1588
1589static const MemoryRegionOps gem_ops = {
1590    .read = gem_read,
1591    .write = gem_write,
1592    .endianness = DEVICE_LITTLE_ENDIAN,
1593};
1594
1595static void gem_set_link(NetClientState *nc)
1596{
1597    CadenceGEMState *s = qemu_get_nic_opaque(nc);
1598
1599    DB_PRINT("\n");
1600    phy_update_link(s);
1601    gem_update_int_status(s);
1602}
1603
1604static NetClientInfo net_gem_info = {
1605    .type = NET_CLIENT_DRIVER_NIC,
1606    .size = sizeof(NICState),
1607    .can_receive = gem_can_receive,
1608    .receive = gem_receive,
1609    .link_status_changed = gem_set_link,
1610};
1611
1612static void gem_realize(DeviceState *dev, Error **errp)
1613{
1614    CadenceGEMState *s = CADENCE_GEM(dev);
1615    int i;
1616
1617    address_space_init(&s->dma_as,
1618                       s->dma_mr ? s->dma_mr : get_system_memory(), "dma");
1619
1620    if (s->num_priority_queues == 0 ||
1621        s->num_priority_queues > MAX_PRIORITY_QUEUES) {
1622        error_setg(errp, "Invalid num-priority-queues value: %" PRIx8,
1623                   s->num_priority_queues);
1624        return;
1625    } else if (s->num_type1_screeners > MAX_TYPE1_SCREENERS) {
1626        error_setg(errp, "Invalid num-type1-screeners value: %" PRIx8,
1627                   s->num_type1_screeners);
1628        return;
1629    } else if (s->num_type2_screeners > MAX_TYPE2_SCREENERS) {
1630        error_setg(errp, "Invalid num-type2-screeners value: %" PRIx8,
1631                   s->num_type2_screeners);
1632        return;
1633    }
1634
1635    for (i = 0; i < s->num_priority_queues; ++i) {
1636        sysbus_init_irq(SYS_BUS_DEVICE(dev), &s->irq[i]);
1637    }
1638
1639    if (!s->attr) {
1640        s->attr = MEMORY_TRANSACTION_ATTR(
1641                      object_new(TYPE_MEMORY_TRANSACTION_ATTR));
1642    }
1643
1644    qemu_macaddr_default_if_unset(&s->conf.macaddr);
1645
1646    s->nic = qemu_new_nic(&net_gem_info, &s->conf,
1647                          object_get_typename(OBJECT(dev)), dev->id, s);
1648}
1649
1650static void gem_init(Object *obj)
1651{
1652    CadenceGEMState *s = CADENCE_GEM(obj);
1653    DeviceState *dev = DEVICE(obj);
1654
1655    DB_PRINT("\n");
1656
1657    gem_init_register_masks(s);
1658    memory_region_init_io(&s->iomem, OBJECT(s), &gem_ops, s,
1659                          "enet", sizeof(s->regs));
1660
1661    sysbus_init_mmio(SYS_BUS_DEVICE(dev), &s->iomem);
1662
1663    object_property_add_link(obj, "dma", TYPE_MEMORY_REGION,
1664                             (Object **)&s->dma_mr,
1665                             qdev_prop_allow_set_link_before_realize,
1666                             OBJ_PROP_LINK_STRONG);
1667    object_property_add_link(obj, "memattr", TYPE_MEMORY_TRANSACTION_ATTR,
1668                             (Object **)&s->attr,
1669                             qdev_prop_allow_set_link_before_realize,
1670                             OBJ_PROP_LINK_STRONG);
1671    object_property_add_link(obj, "mdio", TYPE_MDIO, (Object **)&s->mdio,
1672                             qdev_prop_allow_set_link,
1673                             OBJ_PROP_LINK_STRONG);
1674}
1675
1676static const VMStateDescription vmstate_cadence_gem = {
1677    .name = "cadence_gem",
1678    .version_id = 4,
1679    .minimum_version_id = 4,
1680    .fields = (VMStateField[]) {
1681        VMSTATE_UINT32_ARRAY(regs, CadenceGEMState, CADENCE_GEM_MAXREG),
1682        VMSTATE_UINT8(phy_loop, CadenceGEMState),
1683        VMSTATE_UINT32_ARRAY(rx_desc_addr, CadenceGEMState,
1684                             MAX_PRIORITY_QUEUES),
1685        VMSTATE_UINT32_ARRAY(tx_desc_addr, CadenceGEMState,
1686                             MAX_PRIORITY_QUEUES),
1687        VMSTATE_BOOL_ARRAY(sar_active, CadenceGEMState, 4),
1688        VMSTATE_END_OF_LIST(),
1689    }
1690};
1691
1692static Property gem_properties[] = {
1693    DEFINE_NIC_PROPERTIES(CadenceGEMState, conf),
1694    DEFINE_PROP_UINT32("revision", CadenceGEMState, revision,
1695                       GEM_MODID_VALUE),
1696    DEFINE_PROP_UINT8("num-priority-queues", CadenceGEMState,
1697                      num_priority_queues, 1),
1698    DEFINE_PROP_UINT8("num-type1-screeners", CadenceGEMState,
1699                      num_type1_screeners, 4),
1700    DEFINE_PROP_UINT8("num-type2-screeners", CadenceGEMState,
1701                      num_type2_screeners, 4),
1702    DEFINE_PROP_END_OF_LIST(),
1703};
1704
1705static void gem_class_init(ObjectClass *klass, void *data)
1706{
1707    DeviceClass *dc = DEVICE_CLASS(klass);
1708
1709    dc->realize = gem_realize;
1710    device_class_set_props(dc, gem_properties);
1711    dc->vmsd = &vmstate_cadence_gem;
1712    dc->reset = gem_reset;
1713}
1714
1715static const TypeInfo gem_info = {
1716    .name  = TYPE_CADENCE_GEM,
1717    .parent = TYPE_SYS_BUS_DEVICE,
1718    .instance_size  = sizeof(CadenceGEMState),
1719    .instance_init = gem_init,
1720    .class_init = gem_class_init,
1721};
1722
1723static void gem_register_types(void)
1724{
1725    type_register_static(&gem_info);
1726}
1727
1728type_init(gem_register_types)
1729