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