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