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