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