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