Statistics
| Branch: | Revision:

root / hw / rtl8139.c @ 2507c12a

History | View | Annotate | Download (99.2 kB)

1
/**
2
 * QEMU RTL8139 emulation
3
 *
4
 * Copyright (c) 2006 Igor Kovalenko
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
 * Modifications:
25
 *  2006-Jan-28  Mark Malakanov :   TSAD and CSCR implementation (for Windows driver)
26
 *
27
 *  2006-Apr-28  Juergen Lock   :   EEPROM emulation changes for FreeBSD driver
28
 *                                  HW revision ID changes for FreeBSD driver
29
 *
30
 *  2006-Jul-01  Igor Kovalenko :   Implemented loopback mode for FreeBSD driver
31
 *                                  Corrected packet transfer reassembly routine for 8139C+ mode
32
 *                                  Rearranged debugging print statements
33
 *                                  Implemented PCI timer interrupt (disabled by default)
34
 *                                  Implemented Tally Counters, increased VM load/save version
35
 *                                  Implemented IP/TCP/UDP checksum task offloading
36
 *
37
 *  2006-Jul-04  Igor Kovalenko :   Implemented TCP segmentation offloading
38
 *                                  Fixed MTU=1500 for produced ethernet frames
39
 *
40
 *  2006-Jul-09  Igor Kovalenko :   Fixed TCP header length calculation while processing
41
 *                                  segmentation offloading
42
 *                                  Removed slirp.h dependency
43
 *                                  Added rx/tx buffer reset when enabling rx/tx operation
44
 *
45
 *  2010-Feb-04  Frediano Ziglio:   Rewrote timer support using QEMU timer only
46
 *                                  when strictly needed (required for for
47
 *                                  Darwin)
48
 */
49

    
50
#include "hw.h"
51
#include "pci.h"
52
#include "qemu-timer.h"
53
#include "net.h"
54
#include "loader.h"
55

    
56
/* debug RTL8139 card */
57
//#define DEBUG_RTL8139 1
58

    
59
#define PCI_FREQUENCY 33000000L
60

    
61
/* debug RTL8139 card C+ mode only */
62
//#define DEBUG_RTL8139CP 1
63

    
64
/* Calculate CRCs properly on Rx packets */
65
#define RTL8139_CALCULATE_RXCRC 1
66

    
67
#if defined(RTL8139_CALCULATE_RXCRC)
68
/* For crc32 */
69
#include <zlib.h>
70
#endif
71

    
72
#define SET_MASKED(input, mask, curr) \
73
    ( ( (input) & ~(mask) ) | ( (curr) & (mask) ) )
74

    
75
/* arg % size for size which is a power of 2 */
76
#define MOD2(input, size) \
77
    ( ( input ) & ( size - 1 )  )
78

    
79
#if defined (DEBUG_RTL8139)
80
#  define DEBUG_PRINT(x) do { printf x ; } while (0)
81
#else
82
#  define DEBUG_PRINT(x)
83
#endif
84

    
85
/* Symbolic offsets to registers. */
86
enum RTL8139_registers {
87
    MAC0 = 0,        /* Ethernet hardware address. */
88
    MAR0 = 8,        /* Multicast filter. */
89
    TxStatus0 = 0x10,/* Transmit status (Four 32bit registers). C mode only */
90
                     /* Dump Tally Conter control register(64bit). C+ mode only */
91
    TxAddr0 = 0x20,  /* Tx descriptors (also four 32bit). */
92
    RxBuf = 0x30,
93
    ChipCmd = 0x37,
94
    RxBufPtr = 0x38,
95
    RxBufAddr = 0x3A,
96
    IntrMask = 0x3C,
97
    IntrStatus = 0x3E,
98
    TxConfig = 0x40,
99
    RxConfig = 0x44,
100
    Timer = 0x48,        /* A general-purpose counter. */
101
    RxMissed = 0x4C,    /* 24 bits valid, write clears. */
102
    Cfg9346 = 0x50,
103
    Config0 = 0x51,
104
    Config1 = 0x52,
105
    FlashReg = 0x54,
106
    MediaStatus = 0x58,
107
    Config3 = 0x59,
108
    Config4 = 0x5A,        /* absent on RTL-8139A */
109
    HltClk = 0x5B,
110
    MultiIntr = 0x5C,
111
    PCIRevisionID = 0x5E,
112
    TxSummary = 0x60, /* TSAD register. Transmit Status of All Descriptors*/
113
    BasicModeCtrl = 0x62,
114
    BasicModeStatus = 0x64,
115
    NWayAdvert = 0x66,
116
    NWayLPAR = 0x68,
117
    NWayExpansion = 0x6A,
118
    /* Undocumented registers, but required for proper operation. */
119
    FIFOTMS = 0x70,        /* FIFO Control and test. */
120
    CSCR = 0x74,        /* Chip Status and Configuration Register. */
121
    PARA78 = 0x78,
122
    PARA7c = 0x7c,        /* Magic transceiver parameter register. */
123
    Config5 = 0xD8,        /* absent on RTL-8139A */
124
    /* C+ mode */
125
    TxPoll        = 0xD9,    /* Tell chip to check Tx descriptors for work */
126
    RxMaxSize    = 0xDA, /* Max size of an Rx packet (8169 only) */
127
    CpCmd        = 0xE0, /* C+ Command register (C+ mode only) */
128
    IntrMitigate    = 0xE2,    /* rx/tx interrupt mitigation control */
129
    RxRingAddrLO    = 0xE4, /* 64-bit start addr of Rx ring */
130
    RxRingAddrHI    = 0xE8, /* 64-bit start addr of Rx ring */
131
    TxThresh    = 0xEC, /* Early Tx threshold */
132
};
133

    
134
enum ClearBitMasks {
135
    MultiIntrClear = 0xF000,
136
    ChipCmdClear = 0xE2,
137
    Config1Clear = (1<<7)|(1<<6)|(1<<3)|(1<<2)|(1<<1),
138
};
139

    
140
enum ChipCmdBits {
141
    CmdReset = 0x10,
142
    CmdRxEnb = 0x08,
143
    CmdTxEnb = 0x04,
144
    RxBufEmpty = 0x01,
145
};
146

    
147
/* C+ mode */
148
enum CplusCmdBits {
149
    CPlusRxVLAN   = 0x0040, /* enable receive VLAN detagging */
150
    CPlusRxChkSum = 0x0020, /* enable receive checksum offloading */
151
    CPlusRxEnb    = 0x0002,
152
    CPlusTxEnb    = 0x0001,
153
};
154

    
155
/* Interrupt register bits, using my own meaningful names. */
156
enum IntrStatusBits {
157
    PCIErr = 0x8000,
158
    PCSTimeout = 0x4000,
159
    RxFIFOOver = 0x40,
160
    RxUnderrun = 0x20,
161
    RxOverflow = 0x10,
162
    TxErr = 0x08,
163
    TxOK = 0x04,
164
    RxErr = 0x02,
165
    RxOK = 0x01,
166

    
167
    RxAckBits = RxFIFOOver | RxOverflow | RxOK,
168
};
169

    
170
enum TxStatusBits {
171
    TxHostOwns = 0x2000,
172
    TxUnderrun = 0x4000,
173
    TxStatOK = 0x8000,
174
    TxOutOfWindow = 0x20000000,
175
    TxAborted = 0x40000000,
176
    TxCarrierLost = 0x80000000,
177
};
178
enum RxStatusBits {
179
    RxMulticast = 0x8000,
180
    RxPhysical = 0x4000,
181
    RxBroadcast = 0x2000,
182
    RxBadSymbol = 0x0020,
183
    RxRunt = 0x0010,
184
    RxTooLong = 0x0008,
185
    RxCRCErr = 0x0004,
186
    RxBadAlign = 0x0002,
187
    RxStatusOK = 0x0001,
188
};
189

    
190
/* Bits in RxConfig. */
191
enum rx_mode_bits {
192
    AcceptErr = 0x20,
193
    AcceptRunt = 0x10,
194
    AcceptBroadcast = 0x08,
195
    AcceptMulticast = 0x04,
196
    AcceptMyPhys = 0x02,
197
    AcceptAllPhys = 0x01,
198
};
199

    
200
/* Bits in TxConfig. */
201
enum tx_config_bits {
202

    
203
        /* Interframe Gap Time. Only TxIFG96 doesn't violate IEEE 802.3 */
204
        TxIFGShift = 24,
205
        TxIFG84 = (0 << TxIFGShift),    /* 8.4us / 840ns (10 / 100Mbps) */
206
        TxIFG88 = (1 << TxIFGShift),    /* 8.8us / 880ns (10 / 100Mbps) */
207
        TxIFG92 = (2 << TxIFGShift),    /* 9.2us / 920ns (10 / 100Mbps) */
208
        TxIFG96 = (3 << TxIFGShift),    /* 9.6us / 960ns (10 / 100Mbps) */
209

    
210
    TxLoopBack = (1 << 18) | (1 << 17), /* enable loopback test mode */
211
    TxCRC = (1 << 16),    /* DISABLE appending CRC to end of Tx packets */
212
    TxClearAbt = (1 << 0),    /* Clear abort (WO) */
213
    TxDMAShift = 8,        /* DMA burst value (0-7) is shifted this many bits */
214
    TxRetryShift = 4,    /* TXRR value (0-15) is shifted this many bits */
215

    
216
    TxVersionMask = 0x7C800000, /* mask out version bits 30-26, 23 */
217
};
218

    
219

    
220
/* Transmit Status of All Descriptors (TSAD) Register */
221
enum TSAD_bits {
222
 TSAD_TOK3 = 1<<15, // TOK bit of Descriptor 3
223
 TSAD_TOK2 = 1<<14, // TOK bit of Descriptor 2
224
 TSAD_TOK1 = 1<<13, // TOK bit of Descriptor 1
225
 TSAD_TOK0 = 1<<12, // TOK bit of Descriptor 0
226
 TSAD_TUN3 = 1<<11, // TUN bit of Descriptor 3
227
 TSAD_TUN2 = 1<<10, // TUN bit of Descriptor 2
228
 TSAD_TUN1 = 1<<9, // TUN bit of Descriptor 1
229
 TSAD_TUN0 = 1<<8, // TUN bit of Descriptor 0
230
 TSAD_TABT3 = 1<<07, // TABT bit of Descriptor 3
231
 TSAD_TABT2 = 1<<06, // TABT bit of Descriptor 2
232
 TSAD_TABT1 = 1<<05, // TABT bit of Descriptor 1
233
 TSAD_TABT0 = 1<<04, // TABT bit of Descriptor 0
234
 TSAD_OWN3 = 1<<03, // OWN bit of Descriptor 3
235
 TSAD_OWN2 = 1<<02, // OWN bit of Descriptor 2
236
 TSAD_OWN1 = 1<<01, // OWN bit of Descriptor 1
237
 TSAD_OWN0 = 1<<00, // OWN bit of Descriptor 0
238
};
239

    
240

    
241
/* Bits in Config1 */
242
enum Config1Bits {
243
    Cfg1_PM_Enable = 0x01,
244
    Cfg1_VPD_Enable = 0x02,
245
    Cfg1_PIO = 0x04,
246
    Cfg1_MMIO = 0x08,
247
    LWAKE = 0x10,        /* not on 8139, 8139A */
248
    Cfg1_Driver_Load = 0x20,
249
    Cfg1_LED0 = 0x40,
250
    Cfg1_LED1 = 0x80,
251
    SLEEP = (1 << 1),    /* only on 8139, 8139A */
252
    PWRDN = (1 << 0),    /* only on 8139, 8139A */
253
};
254

    
255
/* Bits in Config3 */
256
enum Config3Bits {
257
    Cfg3_FBtBEn    = (1 << 0), /* 1 = Fast Back to Back */
258
    Cfg3_FuncRegEn = (1 << 1), /* 1 = enable CardBus Function registers */
259
    Cfg3_CLKRUN_En = (1 << 2), /* 1 = enable CLKRUN */
260
    Cfg3_CardB_En  = (1 << 3), /* 1 = enable CardBus registers */
261
    Cfg3_LinkUp    = (1 << 4), /* 1 = wake up on link up */
262
    Cfg3_Magic     = (1 << 5), /* 1 = wake up on Magic Packet (tm) */
263
    Cfg3_PARM_En   = (1 << 6), /* 0 = software can set twister parameters */
264
    Cfg3_GNTSel    = (1 << 7), /* 1 = delay 1 clock from PCI GNT signal */
265
};
266

    
267
/* Bits in Config4 */
268
enum Config4Bits {
269
    LWPTN = (1 << 2),    /* not on 8139, 8139A */
270
};
271

    
272
/* Bits in Config5 */
273
enum Config5Bits {
274
    Cfg5_PME_STS     = (1 << 0), /* 1 = PCI reset resets PME_Status */
275
    Cfg5_LANWake     = (1 << 1), /* 1 = enable LANWake signal */
276
    Cfg5_LDPS        = (1 << 2), /* 0 = save power when link is down */
277
    Cfg5_FIFOAddrPtr = (1 << 3), /* Realtek internal SRAM testing */
278
    Cfg5_UWF         = (1 << 4), /* 1 = accept unicast wakeup frame */
279
    Cfg5_MWF         = (1 << 5), /* 1 = accept multicast wakeup frame */
280
    Cfg5_BWF         = (1 << 6), /* 1 = accept broadcast wakeup frame */
281
};
282

    
283
enum RxConfigBits {
284
    /* rx fifo threshold */
285
    RxCfgFIFOShift = 13,
286
    RxCfgFIFONone = (7 << RxCfgFIFOShift),
287

    
288
    /* Max DMA burst */
289
    RxCfgDMAShift = 8,
290
    RxCfgDMAUnlimited = (7 << RxCfgDMAShift),
291

    
292
    /* rx ring buffer length */
293
    RxCfgRcv8K = 0,
294
    RxCfgRcv16K = (1 << 11),
295
    RxCfgRcv32K = (1 << 12),
296
    RxCfgRcv64K = (1 << 11) | (1 << 12),
297

    
298
    /* Disable packet wrap at end of Rx buffer. (not possible with 64k) */
299
    RxNoWrap = (1 << 7),
300
};
301

    
302
/* Twister tuning parameters from RealTek.
303
   Completely undocumented, but required to tune bad links on some boards. */
304
/*
305
enum CSCRBits {
306
    CSCR_LinkOKBit = 0x0400,
307
    CSCR_LinkChangeBit = 0x0800,
308
    CSCR_LinkStatusBits = 0x0f000,
309
    CSCR_LinkDownOffCmd = 0x003c0,
310
    CSCR_LinkDownCmd = 0x0f3c0,
311
*/
312
enum CSCRBits {
313
    CSCR_Testfun = 1<<15, /* 1 = Auto-neg speeds up internal timer, WO, def 0 */
314
    CSCR_LD  = 1<<9,  /* Active low TPI link disable signal. When low, TPI still transmits link pulses and TPI stays in good link state. def 1*/
315
    CSCR_HEART_BIT = 1<<8,  /* 1 = HEART BEAT enable, 0 = HEART BEAT disable. HEART BEAT function is only valid in 10Mbps mode. def 1*/
316
    CSCR_JBEN = 1<<7,  /* 1 = enable jabber function. 0 = disable jabber function, def 1*/
317
    CSCR_F_LINK_100 = 1<<6, /* Used to login force good link in 100Mbps for diagnostic purposes. 1 = DISABLE, 0 = ENABLE. def 1*/
318
    CSCR_F_Connect  = 1<<5,  /* Assertion of this bit forces the disconnect function to be bypassed. def 0*/
319
    CSCR_Con_status = 1<<3, /* This bit indicates the status of the connection. 1 = valid connected link detected; 0 = disconnected link detected. RO def 0*/
320
    CSCR_Con_status_En = 1<<2, /* Assertion of this bit configures LED1 pin to indicate connection status. def 0*/
321
    CSCR_PASS_SCR = 1<<0, /* Bypass Scramble, def 0*/
322
};
323

    
324
enum Cfg9346Bits {
325
    Cfg9346_Lock = 0x00,
326
    Cfg9346_Unlock = 0xC0,
327
};
328

    
329
typedef enum {
330
    CH_8139 = 0,
331
    CH_8139_K,
332
    CH_8139A,
333
    CH_8139A_G,
334
    CH_8139B,
335
    CH_8130,
336
    CH_8139C,
337
    CH_8100,
338
    CH_8100B_8139D,
339
    CH_8101,
340
} chip_t;
341

    
342
enum chip_flags {
343
    HasHltClk = (1 << 0),
344
    HasLWake = (1 << 1),
345
};
346

    
347
#define HW_REVID(b30, b29, b28, b27, b26, b23, b22) \
348
    (b30<<30 | b29<<29 | b28<<28 | b27<<27 | b26<<26 | b23<<23 | b22<<22)
349
#define HW_REVID_MASK    HW_REVID(1, 1, 1, 1, 1, 1, 1)
350

    
351
#define RTL8139_PCI_REVID_8139      0x10
352
#define RTL8139_PCI_REVID_8139CPLUS 0x20
353

    
354
#define RTL8139_PCI_REVID           RTL8139_PCI_REVID_8139CPLUS
355

    
356
/* Size is 64 * 16bit words */
357
#define EEPROM_9346_ADDR_BITS 6
358
#define EEPROM_9346_SIZE  (1 << EEPROM_9346_ADDR_BITS)
359
#define EEPROM_9346_ADDR_MASK (EEPROM_9346_SIZE - 1)
360

    
361
enum Chip9346Operation
362
{
363
    Chip9346_op_mask = 0xc0,          /* 10 zzzzzz */
364
    Chip9346_op_read = 0x80,          /* 10 AAAAAA */
365
    Chip9346_op_write = 0x40,         /* 01 AAAAAA D(15)..D(0) */
366
    Chip9346_op_ext_mask = 0xf0,      /* 11 zzzzzz */
367
    Chip9346_op_write_enable = 0x30,  /* 00 11zzzz */
368
    Chip9346_op_write_all = 0x10,     /* 00 01zzzz */
369
    Chip9346_op_write_disable = 0x00, /* 00 00zzzz */
370
};
371

    
372
enum Chip9346Mode
373
{
374
    Chip9346_none = 0,
375
    Chip9346_enter_command_mode,
376
    Chip9346_read_command,
377
    Chip9346_data_read,      /* from output register */
378
    Chip9346_data_write,     /* to input register, then to contents at specified address */
379
    Chip9346_data_write_all, /* to input register, then filling contents */
380
};
381

    
382
typedef struct EEprom9346
383
{
384
    uint16_t contents[EEPROM_9346_SIZE];
385
    int      mode;
386
    uint32_t tick;
387
    uint8_t  address;
388
    uint16_t input;
389
    uint16_t output;
390

    
391
    uint8_t eecs;
392
    uint8_t eesk;
393
    uint8_t eedi;
394
    uint8_t eedo;
395
} EEprom9346;
396

    
397
typedef struct RTL8139TallyCounters
398
{
399
    /* Tally counters */
400
    uint64_t   TxOk;
401
    uint64_t   RxOk;
402
    uint64_t   TxERR;
403
    uint32_t   RxERR;
404
    uint16_t   MissPkt;
405
    uint16_t   FAE;
406
    uint32_t   Tx1Col;
407
    uint32_t   TxMCol;
408
    uint64_t   RxOkPhy;
409
    uint64_t   RxOkBrd;
410
    uint32_t   RxOkMul;
411
    uint16_t   TxAbt;
412
    uint16_t   TxUndrn;
413
} RTL8139TallyCounters;
414

    
415
/* Clears all tally counters */
416
static void RTL8139TallyCounters_clear(RTL8139TallyCounters* counters);
417

    
418
/* Writes tally counters to specified physical memory address */
419
static void RTL8139TallyCounters_physical_memory_write(target_phys_addr_t tc_addr, RTL8139TallyCounters* counters);
420

    
421
typedef struct RTL8139State {
422
    PCIDevice dev;
423
    uint8_t phys[8]; /* mac address */
424
    uint8_t mult[8]; /* multicast mask array */
425

    
426
    uint32_t TxStatus[4]; /* TxStatus0 in C mode*/ /* also DTCCR[0] and DTCCR[1] in C+ mode */
427
    uint32_t TxAddr[4];   /* TxAddr0 */
428
    uint32_t RxBuf;       /* Receive buffer */
429
    uint32_t RxBufferSize;/* internal variable, receive ring buffer size in C mode */
430
    uint32_t RxBufPtr;
431
    uint32_t RxBufAddr;
432

    
433
    uint16_t IntrStatus;
434
    uint16_t IntrMask;
435

    
436
    uint32_t TxConfig;
437
    uint32_t RxConfig;
438
    uint32_t RxMissed;
439

    
440
    uint16_t CSCR;
441

    
442
    uint8_t  Cfg9346;
443
    uint8_t  Config0;
444
    uint8_t  Config1;
445
    uint8_t  Config3;
446
    uint8_t  Config4;
447
    uint8_t  Config5;
448

    
449
    uint8_t  clock_enabled;
450
    uint8_t  bChipCmdState;
451

    
452
    uint16_t MultiIntr;
453

    
454
    uint16_t BasicModeCtrl;
455
    uint16_t BasicModeStatus;
456
    uint16_t NWayAdvert;
457
    uint16_t NWayLPAR;
458
    uint16_t NWayExpansion;
459

    
460
    uint16_t CpCmd;
461
    uint8_t  TxThresh;
462

    
463
    NICState *nic;
464
    NICConf conf;
465
    int rtl8139_mmio_io_addr;
466

    
467
    /* C ring mode */
468
    uint32_t   currTxDesc;
469

    
470
    /* C+ mode */
471
    uint32_t   cplus_enabled;
472

    
473
    uint32_t   currCPlusRxDesc;
474
    uint32_t   currCPlusTxDesc;
475

    
476
    uint32_t   RxRingAddrLO;
477
    uint32_t   RxRingAddrHI;
478

    
479
    EEprom9346 eeprom;
480

    
481
    uint32_t   TCTR;
482
    uint32_t   TimerInt;
483
    int64_t    TCTR_base;
484

    
485
    /* Tally counters */
486
    RTL8139TallyCounters tally_counters;
487

    
488
    /* Non-persistent data */
489
    uint8_t   *cplus_txbuffer;
490
    int        cplus_txbuffer_len;
491
    int        cplus_txbuffer_offset;
492

    
493
    /* PCI interrupt timer */
494
    QEMUTimer *timer;
495
    int64_t TimerExpire;
496

    
497
} RTL8139State;
498

    
499
static void rtl8139_set_next_tctr_time(RTL8139State *s, int64_t current_time);
500

    
501
static void prom9346_decode_command(EEprom9346 *eeprom, uint8_t command)
502
{
503
    DEBUG_PRINT(("RTL8139: eeprom command 0x%02x\n", command));
504

    
505
    switch (command & Chip9346_op_mask)
506
    {
507
        case Chip9346_op_read:
508
        {
509
            eeprom->address = command & EEPROM_9346_ADDR_MASK;
510
            eeprom->output = eeprom->contents[eeprom->address];
511
            eeprom->eedo = 0;
512
            eeprom->tick = 0;
513
            eeprom->mode = Chip9346_data_read;
514
            DEBUG_PRINT(("RTL8139: eeprom read from address 0x%02x data=0x%04x\n",
515
                   eeprom->address, eeprom->output));
516
        }
517
        break;
518

    
519
        case Chip9346_op_write:
520
        {
521
            eeprom->address = command & EEPROM_9346_ADDR_MASK;
522
            eeprom->input = 0;
523
            eeprom->tick = 0;
524
            eeprom->mode = Chip9346_none; /* Chip9346_data_write */
525
            DEBUG_PRINT(("RTL8139: eeprom begin write to address 0x%02x\n",
526
                   eeprom->address));
527
        }
528
        break;
529
        default:
530
            eeprom->mode = Chip9346_none;
531
            switch (command & Chip9346_op_ext_mask)
532
            {
533
                case Chip9346_op_write_enable:
534
                    DEBUG_PRINT(("RTL8139: eeprom write enabled\n"));
535
                    break;
536
                case Chip9346_op_write_all:
537
                    DEBUG_PRINT(("RTL8139: eeprom begin write all\n"));
538
                    break;
539
                case Chip9346_op_write_disable:
540
                    DEBUG_PRINT(("RTL8139: eeprom write disabled\n"));
541
                    break;
542
            }
543
            break;
544
    }
545
}
546

    
547
static void prom9346_shift_clock(EEprom9346 *eeprom)
548
{
549
    int bit = eeprom->eedi?1:0;
550

    
551
    ++ eeprom->tick;
552

    
553
    DEBUG_PRINT(("eeprom: tick %d eedi=%d eedo=%d\n", eeprom->tick, eeprom->eedi, eeprom->eedo));
554

    
555
    switch (eeprom->mode)
556
    {
557
        case Chip9346_enter_command_mode:
558
            if (bit)
559
            {
560
                eeprom->mode = Chip9346_read_command;
561
                eeprom->tick = 0;
562
                eeprom->input = 0;
563
                DEBUG_PRINT(("eeprom: +++ synchronized, begin command read\n"));
564
            }
565
            break;
566

    
567
        case Chip9346_read_command:
568
            eeprom->input = (eeprom->input << 1) | (bit & 1);
569
            if (eeprom->tick == 8)
570
            {
571
                prom9346_decode_command(eeprom, eeprom->input & 0xff);
572
            }
573
            break;
574

    
575
        case Chip9346_data_read:
576
            eeprom->eedo = (eeprom->output & 0x8000)?1:0;
577
            eeprom->output <<= 1;
578
            if (eeprom->tick == 16)
579
            {
580
#if 1
581
        // the FreeBSD drivers (rl and re) don't explicitly toggle
582
        // CS between reads (or does setting Cfg9346 to 0 count too?),
583
        // so we need to enter wait-for-command state here
584
                eeprom->mode = Chip9346_enter_command_mode;
585
                eeprom->input = 0;
586
                eeprom->tick = 0;
587

    
588
                DEBUG_PRINT(("eeprom: +++ end of read, awaiting next command\n"));
589
#else
590
        // original behaviour
591
                ++eeprom->address;
592
                eeprom->address &= EEPROM_9346_ADDR_MASK;
593
                eeprom->output = eeprom->contents[eeprom->address];
594
                eeprom->tick = 0;
595

    
596
                DEBUG_PRINT(("eeprom: +++ read next address 0x%02x data=0x%04x\n",
597
                       eeprom->address, eeprom->output));
598
#endif
599
            }
600
            break;
601

    
602
        case Chip9346_data_write:
603
            eeprom->input = (eeprom->input << 1) | (bit & 1);
604
            if (eeprom->tick == 16)
605
            {
606
                DEBUG_PRINT(("RTL8139: eeprom write to address 0x%02x data=0x%04x\n",
607
                       eeprom->address, eeprom->input));
608

    
609
                eeprom->contents[eeprom->address] = eeprom->input;
610
                eeprom->mode = Chip9346_none; /* waiting for next command after CS cycle */
611
                eeprom->tick = 0;
612
                eeprom->input = 0;
613
            }
614
            break;
615

    
616
        case Chip9346_data_write_all:
617
            eeprom->input = (eeprom->input << 1) | (bit & 1);
618
            if (eeprom->tick == 16)
619
            {
620
                int i;
621
                for (i = 0; i < EEPROM_9346_SIZE; i++)
622
                {
623
                    eeprom->contents[i] = eeprom->input;
624
                }
625
                DEBUG_PRINT(("RTL8139: eeprom filled with data=0x%04x\n",
626
                       eeprom->input));
627

    
628
                eeprom->mode = Chip9346_enter_command_mode;
629
                eeprom->tick = 0;
630
                eeprom->input = 0;
631
            }
632
            break;
633

    
634
        default:
635
            break;
636
    }
637
}
638

    
639
static int prom9346_get_wire(RTL8139State *s)
640
{
641
    EEprom9346 *eeprom = &s->eeprom;
642
    if (!eeprom->eecs)
643
        return 0;
644

    
645
    return eeprom->eedo;
646
}
647

    
648
/* FIXME: This should be merged into/replaced by eeprom93xx.c.  */
649
static void prom9346_set_wire(RTL8139State *s, int eecs, int eesk, int eedi)
650
{
651
    EEprom9346 *eeprom = &s->eeprom;
652
    uint8_t old_eecs = eeprom->eecs;
653
    uint8_t old_eesk = eeprom->eesk;
654

    
655
    eeprom->eecs = eecs;
656
    eeprom->eesk = eesk;
657
    eeprom->eedi = eedi;
658

    
659
    DEBUG_PRINT(("eeprom: +++ wires CS=%d SK=%d DI=%d DO=%d\n",
660
                 eeprom->eecs, eeprom->eesk, eeprom->eedi, eeprom->eedo));
661

    
662
    if (!old_eecs && eecs)
663
    {
664
        /* Synchronize start */
665
        eeprom->tick = 0;
666
        eeprom->input = 0;
667
        eeprom->output = 0;
668
        eeprom->mode = Chip9346_enter_command_mode;
669

    
670
        DEBUG_PRINT(("=== eeprom: begin access, enter command mode\n"));
671
    }
672

    
673
    if (!eecs)
674
    {
675
        DEBUG_PRINT(("=== eeprom: end access\n"));
676
        return;
677
    }
678

    
679
    if (!old_eesk && eesk)
680
    {
681
        /* SK front rules */
682
        prom9346_shift_clock(eeprom);
683
    }
684
}
685

    
686
static void rtl8139_update_irq(RTL8139State *s)
687
{
688
    int isr;
689
    isr = (s->IntrStatus & s->IntrMask) & 0xffff;
690

    
691
    DEBUG_PRINT(("RTL8139: Set IRQ to %d (%04x %04x)\n",
692
       isr ? 1 : 0, s->IntrStatus, s->IntrMask));
693

    
694
    qemu_set_irq(s->dev.irq[0], (isr != 0));
695
}
696

    
697
#define POLYNOMIAL 0x04c11db6
698

    
699
/* From FreeBSD */
700
/* XXX: optimize */
701
static int compute_mcast_idx(const uint8_t *ep)
702
{
703
    uint32_t crc;
704
    int carry, i, j;
705
    uint8_t b;
706

    
707
    crc = 0xffffffff;
708
    for (i = 0; i < 6; i++) {
709
        b = *ep++;
710
        for (j = 0; j < 8; j++) {
711
            carry = ((crc & 0x80000000L) ? 1 : 0) ^ (b & 0x01);
712
            crc <<= 1;
713
            b >>= 1;
714
            if (carry)
715
                crc = ((crc ^ POLYNOMIAL) | carry);
716
        }
717
    }
718
    return (crc >> 26);
719
}
720

    
721
static int rtl8139_RxWrap(RTL8139State *s)
722
{
723
    /* wrapping enabled; assume 1.5k more buffer space if size < 65536 */
724
    return (s->RxConfig & (1 << 7));
725
}
726

    
727
static int rtl8139_receiver_enabled(RTL8139State *s)
728
{
729
    return s->bChipCmdState & CmdRxEnb;
730
}
731

    
732
static int rtl8139_transmitter_enabled(RTL8139State *s)
733
{
734
    return s->bChipCmdState & CmdTxEnb;
735
}
736

    
737
static int rtl8139_cp_receiver_enabled(RTL8139State *s)
738
{
739
    return s->CpCmd & CPlusRxEnb;
740
}
741

    
742
static int rtl8139_cp_transmitter_enabled(RTL8139State *s)
743
{
744
    return s->CpCmd & CPlusTxEnb;
745
}
746

    
747
static void rtl8139_write_buffer(RTL8139State *s, const void *buf, int size)
748
{
749
    if (s->RxBufAddr + size > s->RxBufferSize)
750
    {
751
        int wrapped = MOD2(s->RxBufAddr + size, s->RxBufferSize);
752

    
753
        /* write packet data */
754
        if (wrapped && !(s->RxBufferSize < 65536 && rtl8139_RxWrap(s)))
755
        {
756
            DEBUG_PRINT((">>> RTL8139: rx packet wrapped in buffer at %d\n", size-wrapped));
757

    
758
            if (size > wrapped)
759
            {
760
                cpu_physical_memory_write( s->RxBuf + s->RxBufAddr,
761
                                           buf, size-wrapped );
762
            }
763

    
764
            /* reset buffer pointer */
765
            s->RxBufAddr = 0;
766

    
767
            cpu_physical_memory_write( s->RxBuf + s->RxBufAddr,
768
                                       buf + (size-wrapped), wrapped );
769

    
770
            s->RxBufAddr = wrapped;
771

    
772
            return;
773
        }
774
    }
775

    
776
    /* non-wrapping path or overwrapping enabled */
777
    cpu_physical_memory_write( s->RxBuf + s->RxBufAddr, buf, size );
778

    
779
    s->RxBufAddr += size;
780
}
781

    
782
#define MIN_BUF_SIZE 60
783
static inline target_phys_addr_t rtl8139_addr64(uint32_t low, uint32_t high)
784
{
785
#if TARGET_PHYS_ADDR_BITS > 32
786
    return low | ((target_phys_addr_t)high << 32);
787
#else
788
    return low;
789
#endif
790
}
791

    
792
static int rtl8139_can_receive(VLANClientState *nc)
793
{
794
    RTL8139State *s = DO_UPCAST(NICState, nc, nc)->opaque;
795
    int avail;
796

    
797
    /* Receive (drop) packets if card is disabled.  */
798
    if (!s->clock_enabled)
799
      return 1;
800
    if (!rtl8139_receiver_enabled(s))
801
      return 1;
802

    
803
    if (rtl8139_cp_receiver_enabled(s)) {
804
        /* ??? Flow control not implemented in c+ mode.
805
           This is a hack to work around slirp deficiencies anyway.  */
806
        return 1;
807
    } else {
808
        avail = MOD2(s->RxBufferSize + s->RxBufPtr - s->RxBufAddr,
809
                     s->RxBufferSize);
810
        return (avail == 0 || avail >= 1514);
811
    }
812
}
813

    
814
static ssize_t rtl8139_do_receive(VLANClientState *nc, const uint8_t *buf, size_t size_, int do_interrupt)
815
{
816
    RTL8139State *s = DO_UPCAST(NICState, nc, nc)->opaque;
817
    int size = size_;
818

    
819
    uint32_t packet_header = 0;
820

    
821
    uint8_t buf1[60];
822
    static const uint8_t broadcast_macaddr[6] =
823
        { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
824

    
825
    DEBUG_PRINT((">>> RTL8139: received len=%d\n", size));
826

    
827
    /* test if board clock is stopped */
828
    if (!s->clock_enabled)
829
    {
830
        DEBUG_PRINT(("RTL8139: stopped ==========================\n"));
831
        return -1;
832
    }
833

    
834
    /* first check if receiver is enabled */
835

    
836
    if (!rtl8139_receiver_enabled(s))
837
    {
838
        DEBUG_PRINT(("RTL8139: receiver disabled ================\n"));
839
        return -1;
840
    }
841

    
842
    /* XXX: check this */
843
    if (s->RxConfig & AcceptAllPhys) {
844
        /* promiscuous: receive all */
845
        DEBUG_PRINT((">>> RTL8139: packet received in promiscuous mode\n"));
846

    
847
    } else {
848
        if (!memcmp(buf,  broadcast_macaddr, 6)) {
849
            /* broadcast address */
850
            if (!(s->RxConfig & AcceptBroadcast))
851
            {
852
                DEBUG_PRINT((">>> RTL8139: broadcast packet rejected\n"));
853

    
854
                /* update tally counter */
855
                ++s->tally_counters.RxERR;
856

    
857
                return size;
858
            }
859

    
860
            packet_header |= RxBroadcast;
861

    
862
            DEBUG_PRINT((">>> RTL8139: broadcast packet received\n"));
863

    
864
            /* update tally counter */
865
            ++s->tally_counters.RxOkBrd;
866

    
867
        } else if (buf[0] & 0x01) {
868
            /* multicast */
869
            if (!(s->RxConfig & AcceptMulticast))
870
            {
871
                DEBUG_PRINT((">>> RTL8139: multicast packet rejected\n"));
872

    
873
                /* update tally counter */
874
                ++s->tally_counters.RxERR;
875

    
876
                return size;
877
            }
878

    
879
            int mcast_idx = compute_mcast_idx(buf);
880

    
881
            if (!(s->mult[mcast_idx >> 3] & (1 << (mcast_idx & 7))))
882
            {
883
                DEBUG_PRINT((">>> RTL8139: multicast address mismatch\n"));
884

    
885
                /* update tally counter */
886
                ++s->tally_counters.RxERR;
887

    
888
                return size;
889
            }
890

    
891
            packet_header |= RxMulticast;
892

    
893
            DEBUG_PRINT((">>> RTL8139: multicast packet received\n"));
894

    
895
            /* update tally counter */
896
            ++s->tally_counters.RxOkMul;
897

    
898
        } else if (s->phys[0] == buf[0] &&
899
                   s->phys[1] == buf[1] &&
900
                   s->phys[2] == buf[2] &&
901
                   s->phys[3] == buf[3] &&
902
                   s->phys[4] == buf[4] &&
903
                   s->phys[5] == buf[5]) {
904
            /* match */
905
            if (!(s->RxConfig & AcceptMyPhys))
906
            {
907
                DEBUG_PRINT((">>> RTL8139: rejecting physical address matching packet\n"));
908

    
909
                /* update tally counter */
910
                ++s->tally_counters.RxERR;
911

    
912
                return size;
913
            }
914

    
915
            packet_header |= RxPhysical;
916

    
917
            DEBUG_PRINT((">>> RTL8139: physical address matching packet received\n"));
918

    
919
            /* update tally counter */
920
            ++s->tally_counters.RxOkPhy;
921

    
922
        } else {
923

    
924
            DEBUG_PRINT((">>> RTL8139: unknown packet\n"));
925

    
926
            /* update tally counter */
927
            ++s->tally_counters.RxERR;
928

    
929
            return size;
930
        }
931
    }
932

    
933
    /* if too small buffer, then expand it */
934
    if (size < MIN_BUF_SIZE) {
935
        memcpy(buf1, buf, size);
936
        memset(buf1 + size, 0, MIN_BUF_SIZE - size);
937
        buf = buf1;
938
        size = MIN_BUF_SIZE;
939
    }
940

    
941
    if (rtl8139_cp_receiver_enabled(s))
942
    {
943
        DEBUG_PRINT(("RTL8139: in C+ Rx mode ================\n"));
944

    
945
        /* begin C+ receiver mode */
946

    
947
/* w0 ownership flag */
948
#define CP_RX_OWN (1<<31)
949
/* w0 end of ring flag */
950
#define CP_RX_EOR (1<<30)
951
/* w0 bits 0...12 : buffer size */
952
#define CP_RX_BUFFER_SIZE_MASK ((1<<13) - 1)
953
/* w1 tag available flag */
954
#define CP_RX_TAVA (1<<16)
955
/* w1 bits 0...15 : VLAN tag */
956
#define CP_RX_VLAN_TAG_MASK ((1<<16) - 1)
957
/* w2 low  32bit of Rx buffer ptr */
958
/* w3 high 32bit of Rx buffer ptr */
959

    
960
        int descriptor = s->currCPlusRxDesc;
961
        target_phys_addr_t cplus_rx_ring_desc;
962

    
963
        cplus_rx_ring_desc = rtl8139_addr64(s->RxRingAddrLO, s->RxRingAddrHI);
964
        cplus_rx_ring_desc += 16 * descriptor;
965

    
966
        DEBUG_PRINT(("RTL8139: +++ C+ mode reading RX descriptor %d from host memory at %08x %08x = %016" PRIx64 "\n",
967
               descriptor, s->RxRingAddrHI, s->RxRingAddrLO, (uint64_t)cplus_rx_ring_desc));
968

    
969
        uint32_t val, rxdw0,rxdw1,rxbufLO,rxbufHI;
970

    
971
        cpu_physical_memory_read(cplus_rx_ring_desc,    (uint8_t *)&val, 4);
972
        rxdw0 = le32_to_cpu(val);
973
        cpu_physical_memory_read(cplus_rx_ring_desc+4,  (uint8_t *)&val, 4);
974
        rxdw1 = le32_to_cpu(val);
975
        cpu_physical_memory_read(cplus_rx_ring_desc+8,  (uint8_t *)&val, 4);
976
        rxbufLO = le32_to_cpu(val);
977
        cpu_physical_memory_read(cplus_rx_ring_desc+12, (uint8_t *)&val, 4);
978
        rxbufHI = le32_to_cpu(val);
979

    
980
        DEBUG_PRINT(("RTL8139: +++ C+ mode RX descriptor %d %08x %08x %08x %08x\n",
981
               descriptor,
982
               rxdw0, rxdw1, rxbufLO, rxbufHI));
983

    
984
        if (!(rxdw0 & CP_RX_OWN))
985
        {
986
            DEBUG_PRINT(("RTL8139: C+ Rx mode : descriptor %d is owned by host\n", descriptor));
987

    
988
            s->IntrStatus |= RxOverflow;
989
            ++s->RxMissed;
990

    
991
            /* update tally counter */
992
            ++s->tally_counters.RxERR;
993
            ++s->tally_counters.MissPkt;
994

    
995
            rtl8139_update_irq(s);
996
            return size_;
997
        }
998

    
999
        uint32_t rx_space = rxdw0 & CP_RX_BUFFER_SIZE_MASK;
1000

    
1001
        /* TODO: scatter the packet over available receive ring descriptors space */
1002

    
1003
        if (size+4 > rx_space)
1004
        {
1005
            DEBUG_PRINT(("RTL8139: C+ Rx mode : descriptor %d size %d received %d + 4\n",
1006
                   descriptor, rx_space, size));
1007

    
1008
            s->IntrStatus |= RxOverflow;
1009
            ++s->RxMissed;
1010

    
1011
            /* update tally counter */
1012
            ++s->tally_counters.RxERR;
1013
            ++s->tally_counters.MissPkt;
1014

    
1015
            rtl8139_update_irq(s);
1016
            return size_;
1017
        }
1018

    
1019
        target_phys_addr_t rx_addr = rtl8139_addr64(rxbufLO, rxbufHI);
1020

    
1021
        /* receive/copy to target memory */
1022
        cpu_physical_memory_write( rx_addr, buf, size );
1023

    
1024
        if (s->CpCmd & CPlusRxChkSum)
1025
        {
1026
            /* do some packet checksumming */
1027
        }
1028

    
1029
        /* write checksum */
1030
#if defined (RTL8139_CALCULATE_RXCRC)
1031
        val = cpu_to_le32(crc32(0, buf, size));
1032
#else
1033
        val = 0;
1034
#endif
1035
        cpu_physical_memory_write( rx_addr+size, (uint8_t *)&val, 4);
1036

    
1037
/* first segment of received packet flag */
1038
#define CP_RX_STATUS_FS (1<<29)
1039
/* last segment of received packet flag */
1040
#define CP_RX_STATUS_LS (1<<28)
1041
/* multicast packet flag */
1042
#define CP_RX_STATUS_MAR (1<<26)
1043
/* physical-matching packet flag */
1044
#define CP_RX_STATUS_PAM (1<<25)
1045
/* broadcast packet flag */
1046
#define CP_RX_STATUS_BAR (1<<24)
1047
/* runt packet flag */
1048
#define CP_RX_STATUS_RUNT (1<<19)
1049
/* crc error flag */
1050
#define CP_RX_STATUS_CRC (1<<18)
1051
/* IP checksum error flag */
1052
#define CP_RX_STATUS_IPF (1<<15)
1053
/* UDP checksum error flag */
1054
#define CP_RX_STATUS_UDPF (1<<14)
1055
/* TCP checksum error flag */
1056
#define CP_RX_STATUS_TCPF (1<<13)
1057

    
1058
        /* transfer ownership to target */
1059
        rxdw0 &= ~CP_RX_OWN;
1060

    
1061
        /* set first segment bit */
1062
        rxdw0 |= CP_RX_STATUS_FS;
1063

    
1064
        /* set last segment bit */
1065
        rxdw0 |= CP_RX_STATUS_LS;
1066

    
1067
        /* set received packet type flags */
1068
        if (packet_header & RxBroadcast)
1069
            rxdw0 |= CP_RX_STATUS_BAR;
1070
        if (packet_header & RxMulticast)
1071
            rxdw0 |= CP_RX_STATUS_MAR;
1072
        if (packet_header & RxPhysical)
1073
            rxdw0 |= CP_RX_STATUS_PAM;
1074

    
1075
        /* set received size */
1076
        rxdw0 &= ~CP_RX_BUFFER_SIZE_MASK;
1077
        rxdw0 |= (size+4);
1078

    
1079
        /* reset VLAN tag flag */
1080
        rxdw1 &= ~CP_RX_TAVA;
1081

    
1082
        /* update ring data */
1083
        val = cpu_to_le32(rxdw0);
1084
        cpu_physical_memory_write(cplus_rx_ring_desc,    (uint8_t *)&val, 4);
1085
        val = cpu_to_le32(rxdw1);
1086
        cpu_physical_memory_write(cplus_rx_ring_desc+4,  (uint8_t *)&val, 4);
1087

    
1088
        /* update tally counter */
1089
        ++s->tally_counters.RxOk;
1090

    
1091
        /* seek to next Rx descriptor */
1092
        if (rxdw0 & CP_RX_EOR)
1093
        {
1094
            s->currCPlusRxDesc = 0;
1095
        }
1096
        else
1097
        {
1098
            ++s->currCPlusRxDesc;
1099
        }
1100

    
1101
        DEBUG_PRINT(("RTL8139: done C+ Rx mode ----------------\n"));
1102

    
1103
    }
1104
    else
1105
    {
1106
        DEBUG_PRINT(("RTL8139: in ring Rx mode ================\n"));
1107

    
1108
        /* begin ring receiver mode */
1109
        int avail = MOD2(s->RxBufferSize + s->RxBufPtr - s->RxBufAddr, s->RxBufferSize);
1110

    
1111
        /* if receiver buffer is empty then avail == 0 */
1112

    
1113
        if (avail != 0 && size + 8 >= avail)
1114
        {
1115
            DEBUG_PRINT(("rx overflow: rx buffer length %d head 0x%04x read 0x%04x === available 0x%04x need 0x%04x\n",
1116
                   s->RxBufferSize, s->RxBufAddr, s->RxBufPtr, avail, size + 8));
1117

    
1118
            s->IntrStatus |= RxOverflow;
1119
            ++s->RxMissed;
1120
            rtl8139_update_irq(s);
1121
            return size_;
1122
        }
1123

    
1124
        packet_header |= RxStatusOK;
1125

    
1126
        packet_header |= (((size+4) << 16) & 0xffff0000);
1127

    
1128
        /* write header */
1129
        uint32_t val = cpu_to_le32(packet_header);
1130

    
1131
        rtl8139_write_buffer(s, (uint8_t *)&val, 4);
1132

    
1133
        rtl8139_write_buffer(s, buf, size);
1134

    
1135
        /* write checksum */
1136
#if defined (RTL8139_CALCULATE_RXCRC)
1137
        val = cpu_to_le32(crc32(0, buf, size));
1138
#else
1139
        val = 0;
1140
#endif
1141

    
1142
        rtl8139_write_buffer(s, (uint8_t *)&val, 4);
1143

    
1144
        /* correct buffer write pointer */
1145
        s->RxBufAddr = MOD2((s->RxBufAddr + 3) & ~0x3, s->RxBufferSize);
1146

    
1147
        /* now we can signal we have received something */
1148

    
1149
        DEBUG_PRINT(("   received: rx buffer length %d head 0x%04x read 0x%04x\n",
1150
               s->RxBufferSize, s->RxBufAddr, s->RxBufPtr));
1151
    }
1152

    
1153
    s->IntrStatus |= RxOK;
1154

    
1155
    if (do_interrupt)
1156
    {
1157
        rtl8139_update_irq(s);
1158
    }
1159

    
1160
    return size_;
1161
}
1162

    
1163
static ssize_t rtl8139_receive(VLANClientState *nc, const uint8_t *buf, size_t size)
1164
{
1165
    return rtl8139_do_receive(nc, buf, size, 1);
1166
}
1167

    
1168
static void rtl8139_reset_rxring(RTL8139State *s, uint32_t bufferSize)
1169
{
1170
    s->RxBufferSize = bufferSize;
1171
    s->RxBufPtr  = 0;
1172
    s->RxBufAddr = 0;
1173
}
1174

    
1175
static void rtl8139_reset(DeviceState *d)
1176
{
1177
    RTL8139State *s = container_of(d, RTL8139State, dev.qdev);
1178
    int i;
1179

    
1180
    /* restore MAC address */
1181
    memcpy(s->phys, s->conf.macaddr.a, 6);
1182

    
1183
    /* reset interrupt mask */
1184
    s->IntrStatus = 0;
1185
    s->IntrMask = 0;
1186

    
1187
    rtl8139_update_irq(s);
1188

    
1189
    /* prepare eeprom */
1190
    s->eeprom.contents[0] = 0x8129;
1191
#if 1
1192
    // PCI vendor and device ID should be mirrored here
1193
    s->eeprom.contents[1] = PCI_VENDOR_ID_REALTEK;
1194
    s->eeprom.contents[2] = PCI_DEVICE_ID_REALTEK_8139;
1195
#endif
1196

    
1197
    s->eeprom.contents[7] = s->conf.macaddr.a[0] | s->conf.macaddr.a[1] << 8;
1198
    s->eeprom.contents[8] = s->conf.macaddr.a[2] | s->conf.macaddr.a[3] << 8;
1199
    s->eeprom.contents[9] = s->conf.macaddr.a[4] | s->conf.macaddr.a[5] << 8;
1200

    
1201
    /* mark all status registers as owned by host */
1202
    for (i = 0; i < 4; ++i)
1203
    {
1204
        s->TxStatus[i] = TxHostOwns;
1205
    }
1206

    
1207
    s->currTxDesc = 0;
1208
    s->currCPlusRxDesc = 0;
1209
    s->currCPlusTxDesc = 0;
1210

    
1211
    s->RxRingAddrLO = 0;
1212
    s->RxRingAddrHI = 0;
1213

    
1214
    s->RxBuf = 0;
1215

    
1216
    rtl8139_reset_rxring(s, 8192);
1217

    
1218
    /* ACK the reset */
1219
    s->TxConfig = 0;
1220

    
1221
#if 0
1222
//    s->TxConfig |= HW_REVID(1, 0, 0, 0, 0, 0, 0); // RTL-8139  HasHltClk
1223
    s->clock_enabled = 0;
1224
#else
1225
    s->TxConfig |= HW_REVID(1, 1, 1, 0, 1, 1, 0); // RTL-8139C+ HasLWake
1226
    s->clock_enabled = 1;
1227
#endif
1228

    
1229
    s->bChipCmdState = CmdReset; /* RxBufEmpty bit is calculated on read from ChipCmd */;
1230

    
1231
    /* set initial state data */
1232
    s->Config0 = 0x0; /* No boot ROM */
1233
    s->Config1 = 0xC; /* IO mapped and MEM mapped registers available */
1234
    s->Config3 = 0x1; /* fast back-to-back compatible */
1235
    s->Config5 = 0x0;
1236

    
1237
    s->CSCR = CSCR_F_LINK_100 | CSCR_HEART_BIT | CSCR_LD;
1238

    
1239
    s->CpCmd   = 0x0; /* reset C+ mode */
1240
    s->cplus_enabled = 0;
1241

    
1242

    
1243
//    s->BasicModeCtrl = 0x3100; // 100Mbps, full duplex, autonegotiation
1244
//    s->BasicModeCtrl = 0x2100; // 100Mbps, full duplex
1245
    s->BasicModeCtrl = 0x1000; // autonegotiation
1246

    
1247
    s->BasicModeStatus  = 0x7809;
1248
    //s->BasicModeStatus |= 0x0040; /* UTP medium */
1249
    s->BasicModeStatus |= 0x0020; /* autonegotiation completed */
1250
    s->BasicModeStatus |= 0x0004; /* link is up */
1251

    
1252
    s->NWayAdvert    = 0x05e1; /* all modes, full duplex */
1253
    s->NWayLPAR      = 0x05e1; /* all modes, full duplex */
1254
    s->NWayExpansion = 0x0001; /* autonegotiation supported */
1255

    
1256
    /* also reset timer and disable timer interrupt */
1257
    s->TCTR = 0;
1258
    s->TimerInt = 0;
1259
    s->TCTR_base = 0;
1260

    
1261
    /* reset tally counters */
1262
    RTL8139TallyCounters_clear(&s->tally_counters);
1263
}
1264

    
1265
static void RTL8139TallyCounters_clear(RTL8139TallyCounters* counters)
1266
{
1267
    counters->TxOk = 0;
1268
    counters->RxOk = 0;
1269
    counters->TxERR = 0;
1270
    counters->RxERR = 0;
1271
    counters->MissPkt = 0;
1272
    counters->FAE = 0;
1273
    counters->Tx1Col = 0;
1274
    counters->TxMCol = 0;
1275
    counters->RxOkPhy = 0;
1276
    counters->RxOkBrd = 0;
1277
    counters->RxOkMul = 0;
1278
    counters->TxAbt = 0;
1279
    counters->TxUndrn = 0;
1280
}
1281

    
1282
static void RTL8139TallyCounters_physical_memory_write(target_phys_addr_t tc_addr, RTL8139TallyCounters* tally_counters)
1283
{
1284
    uint16_t val16;
1285
    uint32_t val32;
1286
    uint64_t val64;
1287

    
1288
    val64 = cpu_to_le64(tally_counters->TxOk);
1289
    cpu_physical_memory_write(tc_addr + 0,    (uint8_t *)&val64, 8);
1290

    
1291
    val64 = cpu_to_le64(tally_counters->RxOk);
1292
    cpu_physical_memory_write(tc_addr + 8,    (uint8_t *)&val64, 8);
1293

    
1294
    val64 = cpu_to_le64(tally_counters->TxERR);
1295
    cpu_physical_memory_write(tc_addr + 16,    (uint8_t *)&val64, 8);
1296

    
1297
    val32 = cpu_to_le32(tally_counters->RxERR);
1298
    cpu_physical_memory_write(tc_addr + 24,    (uint8_t *)&val32, 4);
1299

    
1300
    val16 = cpu_to_le16(tally_counters->MissPkt);
1301
    cpu_physical_memory_write(tc_addr + 28,    (uint8_t *)&val16, 2);
1302

    
1303
    val16 = cpu_to_le16(tally_counters->FAE);
1304
    cpu_physical_memory_write(tc_addr + 30,    (uint8_t *)&val16, 2);
1305

    
1306
    val32 = cpu_to_le32(tally_counters->Tx1Col);
1307
    cpu_physical_memory_write(tc_addr + 32,    (uint8_t *)&val32, 4);
1308

    
1309
    val32 = cpu_to_le32(tally_counters->TxMCol);
1310
    cpu_physical_memory_write(tc_addr + 36,    (uint8_t *)&val32, 4);
1311

    
1312
    val64 = cpu_to_le64(tally_counters->RxOkPhy);
1313
    cpu_physical_memory_write(tc_addr + 40,    (uint8_t *)&val64, 8);
1314

    
1315
    val64 = cpu_to_le64(tally_counters->RxOkBrd);
1316
    cpu_physical_memory_write(tc_addr + 48,    (uint8_t *)&val64, 8);
1317

    
1318
    val32 = cpu_to_le32(tally_counters->RxOkMul);
1319
    cpu_physical_memory_write(tc_addr + 56,    (uint8_t *)&val32, 4);
1320

    
1321
    val16 = cpu_to_le16(tally_counters->TxAbt);
1322
    cpu_physical_memory_write(tc_addr + 60,    (uint8_t *)&val16, 2);
1323

    
1324
    val16 = cpu_to_le16(tally_counters->TxUndrn);
1325
    cpu_physical_memory_write(tc_addr + 62,    (uint8_t *)&val16, 2);
1326
}
1327

    
1328
/* Loads values of tally counters from VM state file */
1329

    
1330
static const VMStateDescription vmstate_tally_counters = {
1331
    .name = "tally_counters",
1332
    .version_id = 1,
1333
    .minimum_version_id = 1,
1334
    .minimum_version_id_old = 1,
1335
    .fields      = (VMStateField []) {
1336
        VMSTATE_UINT64(TxOk, RTL8139TallyCounters),
1337
        VMSTATE_UINT64(RxOk, RTL8139TallyCounters),
1338
        VMSTATE_UINT64(TxERR, RTL8139TallyCounters),
1339
        VMSTATE_UINT32(RxERR, RTL8139TallyCounters),
1340
        VMSTATE_UINT16(MissPkt, RTL8139TallyCounters),
1341
        VMSTATE_UINT16(FAE, RTL8139TallyCounters),
1342
        VMSTATE_UINT32(Tx1Col, RTL8139TallyCounters),
1343
        VMSTATE_UINT32(TxMCol, RTL8139TallyCounters),
1344
        VMSTATE_UINT64(RxOkPhy, RTL8139TallyCounters),
1345
        VMSTATE_UINT64(RxOkBrd, RTL8139TallyCounters),
1346
        VMSTATE_UINT16(TxAbt, RTL8139TallyCounters),
1347
        VMSTATE_UINT16(TxUndrn, RTL8139TallyCounters),
1348
        VMSTATE_END_OF_LIST()
1349
    }
1350
};
1351

    
1352
static void rtl8139_ChipCmd_write(RTL8139State *s, uint32_t val)
1353
{
1354
    val &= 0xff;
1355

    
1356
    DEBUG_PRINT(("RTL8139: ChipCmd write val=0x%08x\n", val));
1357

    
1358
    if (val & CmdReset)
1359
    {
1360
        DEBUG_PRINT(("RTL8139: ChipCmd reset\n"));
1361
        rtl8139_reset(&s->dev.qdev);
1362
    }
1363
    if (val & CmdRxEnb)
1364
    {
1365
        DEBUG_PRINT(("RTL8139: ChipCmd enable receiver\n"));
1366

    
1367
        s->currCPlusRxDesc = 0;
1368
    }
1369
    if (val & CmdTxEnb)
1370
    {
1371
        DEBUG_PRINT(("RTL8139: ChipCmd enable transmitter\n"));
1372

    
1373
        s->currCPlusTxDesc = 0;
1374
    }
1375

    
1376
    /* mask unwriteable bits */
1377
    val = SET_MASKED(val, 0xe3, s->bChipCmdState);
1378

    
1379
    /* Deassert reset pin before next read */
1380
    val &= ~CmdReset;
1381

    
1382
    s->bChipCmdState = val;
1383
}
1384

    
1385
static int rtl8139_RxBufferEmpty(RTL8139State *s)
1386
{
1387
    int unread = MOD2(s->RxBufferSize + s->RxBufAddr - s->RxBufPtr, s->RxBufferSize);
1388

    
1389
    if (unread != 0)
1390
    {
1391
        DEBUG_PRINT(("RTL8139: receiver buffer data available 0x%04x\n", unread));
1392
        return 0;
1393
    }
1394

    
1395
    DEBUG_PRINT(("RTL8139: receiver buffer is empty\n"));
1396

    
1397
    return 1;
1398
}
1399

    
1400
static uint32_t rtl8139_ChipCmd_read(RTL8139State *s)
1401
{
1402
    uint32_t ret = s->bChipCmdState;
1403

    
1404
    if (rtl8139_RxBufferEmpty(s))
1405
        ret |= RxBufEmpty;
1406

    
1407
    DEBUG_PRINT(("RTL8139: ChipCmd read val=0x%04x\n", ret));
1408

    
1409
    return ret;
1410
}
1411

    
1412
static void rtl8139_CpCmd_write(RTL8139State *s, uint32_t val)
1413
{
1414
    val &= 0xffff;
1415

    
1416
    DEBUG_PRINT(("RTL8139C+ command register write(w) val=0x%04x\n", val));
1417

    
1418
    s->cplus_enabled = 1;
1419

    
1420
    /* mask unwriteable bits */
1421
    val = SET_MASKED(val, 0xff84, s->CpCmd);
1422

    
1423
    s->CpCmd = val;
1424
}
1425

    
1426
static uint32_t rtl8139_CpCmd_read(RTL8139State *s)
1427
{
1428
    uint32_t ret = s->CpCmd;
1429

    
1430
    DEBUG_PRINT(("RTL8139C+ command register read(w) val=0x%04x\n", ret));
1431

    
1432
    return ret;
1433
}
1434

    
1435
static void rtl8139_IntrMitigate_write(RTL8139State *s, uint32_t val)
1436
{
1437
    DEBUG_PRINT(("RTL8139C+ IntrMitigate register write(w) val=0x%04x\n", val));
1438
}
1439

    
1440
static uint32_t rtl8139_IntrMitigate_read(RTL8139State *s)
1441
{
1442
    uint32_t ret = 0;
1443

    
1444
    DEBUG_PRINT(("RTL8139C+ IntrMitigate register read(w) val=0x%04x\n", ret));
1445

    
1446
    return ret;
1447
}
1448

    
1449
static int rtl8139_config_writeable(RTL8139State *s)
1450
{
1451
    if (s->Cfg9346 & Cfg9346_Unlock)
1452
    {
1453
        return 1;
1454
    }
1455

    
1456
    DEBUG_PRINT(("RTL8139: Configuration registers are write-protected\n"));
1457

    
1458
    return 0;
1459
}
1460

    
1461
static void rtl8139_BasicModeCtrl_write(RTL8139State *s, uint32_t val)
1462
{
1463
    val &= 0xffff;
1464

    
1465
    DEBUG_PRINT(("RTL8139: BasicModeCtrl register write(w) val=0x%04x\n", val));
1466

    
1467
    /* mask unwriteable bits */
1468
    uint32_t mask = 0x4cff;
1469

    
1470
    if (1 || !rtl8139_config_writeable(s))
1471
    {
1472
        /* Speed setting and autonegotiation enable bits are read-only */
1473
        mask |= 0x3000;
1474
        /* Duplex mode setting is read-only */
1475
        mask |= 0x0100;
1476
    }
1477

    
1478
    val = SET_MASKED(val, mask, s->BasicModeCtrl);
1479

    
1480
    s->BasicModeCtrl = val;
1481
}
1482

    
1483
static uint32_t rtl8139_BasicModeCtrl_read(RTL8139State *s)
1484
{
1485
    uint32_t ret = s->BasicModeCtrl;
1486

    
1487
    DEBUG_PRINT(("RTL8139: BasicModeCtrl register read(w) val=0x%04x\n", ret));
1488

    
1489
    return ret;
1490
}
1491

    
1492
static void rtl8139_BasicModeStatus_write(RTL8139State *s, uint32_t val)
1493
{
1494
    val &= 0xffff;
1495

    
1496
    DEBUG_PRINT(("RTL8139: BasicModeStatus register write(w) val=0x%04x\n", val));
1497

    
1498
    /* mask unwriteable bits */
1499
    val = SET_MASKED(val, 0xff3f, s->BasicModeStatus);
1500

    
1501
    s->BasicModeStatus = val;
1502
}
1503

    
1504
static uint32_t rtl8139_BasicModeStatus_read(RTL8139State *s)
1505
{
1506
    uint32_t ret = s->BasicModeStatus;
1507

    
1508
    DEBUG_PRINT(("RTL8139: BasicModeStatus register read(w) val=0x%04x\n", ret));
1509

    
1510
    return ret;
1511
}
1512

    
1513
static void rtl8139_Cfg9346_write(RTL8139State *s, uint32_t val)
1514
{
1515
    val &= 0xff;
1516

    
1517
    DEBUG_PRINT(("RTL8139: Cfg9346 write val=0x%02x\n", val));
1518

    
1519
    /* mask unwriteable bits */
1520
    val = SET_MASKED(val, 0x31, s->Cfg9346);
1521

    
1522
    uint32_t opmode = val & 0xc0;
1523
    uint32_t eeprom_val = val & 0xf;
1524

    
1525
    if (opmode == 0x80) {
1526
        /* eeprom access */
1527
        int eecs = (eeprom_val & 0x08)?1:0;
1528
        int eesk = (eeprom_val & 0x04)?1:0;
1529
        int eedi = (eeprom_val & 0x02)?1:0;
1530
        prom9346_set_wire(s, eecs, eesk, eedi);
1531
    } else if (opmode == 0x40) {
1532
        /* Reset.  */
1533
        val = 0;
1534
        rtl8139_reset(&s->dev.qdev);
1535
    }
1536

    
1537
    s->Cfg9346 = val;
1538
}
1539

    
1540
static uint32_t rtl8139_Cfg9346_read(RTL8139State *s)
1541
{
1542
    uint32_t ret = s->Cfg9346;
1543

    
1544
    uint32_t opmode = ret & 0xc0;
1545

    
1546
    if (opmode == 0x80)
1547
    {
1548
        /* eeprom access */
1549
        int eedo = prom9346_get_wire(s);
1550
        if (eedo)
1551
        {
1552
            ret |=  0x01;
1553
        }
1554
        else
1555
        {
1556
            ret &= ~0x01;
1557
        }
1558
    }
1559

    
1560
    DEBUG_PRINT(("RTL8139: Cfg9346 read val=0x%02x\n", ret));
1561

    
1562
    return ret;
1563
}
1564

    
1565
static void rtl8139_Config0_write(RTL8139State *s, uint32_t val)
1566
{
1567
    val &= 0xff;
1568

    
1569
    DEBUG_PRINT(("RTL8139: Config0 write val=0x%02x\n", val));
1570

    
1571
    if (!rtl8139_config_writeable(s))
1572
        return;
1573

    
1574
    /* mask unwriteable bits */
1575
    val = SET_MASKED(val, 0xf8, s->Config0);
1576

    
1577
    s->Config0 = val;
1578
}
1579

    
1580
static uint32_t rtl8139_Config0_read(RTL8139State *s)
1581
{
1582
    uint32_t ret = s->Config0;
1583

    
1584
    DEBUG_PRINT(("RTL8139: Config0 read val=0x%02x\n", ret));
1585

    
1586
    return ret;
1587
}
1588

    
1589
static void rtl8139_Config1_write(RTL8139State *s, uint32_t val)
1590
{
1591
    val &= 0xff;
1592

    
1593
    DEBUG_PRINT(("RTL8139: Config1 write val=0x%02x\n", val));
1594

    
1595
    if (!rtl8139_config_writeable(s))
1596
        return;
1597

    
1598
    /* mask unwriteable bits */
1599
    val = SET_MASKED(val, 0xC, s->Config1);
1600

    
1601
    s->Config1 = val;
1602
}
1603

    
1604
static uint32_t rtl8139_Config1_read(RTL8139State *s)
1605
{
1606
    uint32_t ret = s->Config1;
1607

    
1608
    DEBUG_PRINT(("RTL8139: Config1 read val=0x%02x\n", ret));
1609

    
1610
    return ret;
1611
}
1612

    
1613
static void rtl8139_Config3_write(RTL8139State *s, uint32_t val)
1614
{
1615
    val &= 0xff;
1616

    
1617
    DEBUG_PRINT(("RTL8139: Config3 write val=0x%02x\n", val));
1618

    
1619
    if (!rtl8139_config_writeable(s))
1620
        return;
1621

    
1622
    /* mask unwriteable bits */
1623
    val = SET_MASKED(val, 0x8F, s->Config3);
1624

    
1625
    s->Config3 = val;
1626
}
1627

    
1628
static uint32_t rtl8139_Config3_read(RTL8139State *s)
1629
{
1630
    uint32_t ret = s->Config3;
1631

    
1632
    DEBUG_PRINT(("RTL8139: Config3 read val=0x%02x\n", ret));
1633

    
1634
    return ret;
1635
}
1636

    
1637
static void rtl8139_Config4_write(RTL8139State *s, uint32_t val)
1638
{
1639
    val &= 0xff;
1640

    
1641
    DEBUG_PRINT(("RTL8139: Config4 write val=0x%02x\n", val));
1642

    
1643
    if (!rtl8139_config_writeable(s))
1644
        return;
1645

    
1646
    /* mask unwriteable bits */
1647
    val = SET_MASKED(val, 0x0a, s->Config4);
1648

    
1649
    s->Config4 = val;
1650
}
1651

    
1652
static uint32_t rtl8139_Config4_read(RTL8139State *s)
1653
{
1654
    uint32_t ret = s->Config4;
1655

    
1656
    DEBUG_PRINT(("RTL8139: Config4 read val=0x%02x\n", ret));
1657

    
1658
    return ret;
1659
}
1660

    
1661
static void rtl8139_Config5_write(RTL8139State *s, uint32_t val)
1662
{
1663
    val &= 0xff;
1664

    
1665
    DEBUG_PRINT(("RTL8139: Config5 write val=0x%02x\n", val));
1666

    
1667
    /* mask unwriteable bits */
1668
    val = SET_MASKED(val, 0x80, s->Config5);
1669

    
1670
    s->Config5 = val;
1671
}
1672

    
1673
static uint32_t rtl8139_Config5_read(RTL8139State *s)
1674
{
1675
    uint32_t ret = s->Config5;
1676

    
1677
    DEBUG_PRINT(("RTL8139: Config5 read val=0x%02x\n", ret));
1678

    
1679
    return ret;
1680
}
1681

    
1682
static void rtl8139_TxConfig_write(RTL8139State *s, uint32_t val)
1683
{
1684
    if (!rtl8139_transmitter_enabled(s))
1685
    {
1686
        DEBUG_PRINT(("RTL8139: transmitter disabled; no TxConfig write val=0x%08x\n", val));
1687
        return;
1688
    }
1689

    
1690
    DEBUG_PRINT(("RTL8139: TxConfig write val=0x%08x\n", val));
1691

    
1692
    val = SET_MASKED(val, TxVersionMask | 0x8070f80f, s->TxConfig);
1693

    
1694
    s->TxConfig = val;
1695
}
1696

    
1697
static void rtl8139_TxConfig_writeb(RTL8139State *s, uint32_t val)
1698
{
1699
    DEBUG_PRINT(("RTL8139C TxConfig via write(b) val=0x%02x\n", val));
1700

    
1701
    uint32_t tc = s->TxConfig;
1702
    tc &= 0xFFFFFF00;
1703
    tc |= (val & 0x000000FF);
1704
    rtl8139_TxConfig_write(s, tc);
1705
}
1706

    
1707
static uint32_t rtl8139_TxConfig_read(RTL8139State *s)
1708
{
1709
    uint32_t ret = s->TxConfig;
1710

    
1711
    DEBUG_PRINT(("RTL8139: TxConfig read val=0x%04x\n", ret));
1712

    
1713
    return ret;
1714
}
1715

    
1716
static void rtl8139_RxConfig_write(RTL8139State *s, uint32_t val)
1717
{
1718
    DEBUG_PRINT(("RTL8139: RxConfig write val=0x%08x\n", val));
1719

    
1720
    /* mask unwriteable bits */
1721
    val = SET_MASKED(val, 0xf0fc0040, s->RxConfig);
1722

    
1723
    s->RxConfig = val;
1724

    
1725
    /* reset buffer size and read/write pointers */
1726
    rtl8139_reset_rxring(s, 8192 << ((s->RxConfig >> 11) & 0x3));
1727

    
1728
    DEBUG_PRINT(("RTL8139: RxConfig write reset buffer size to %d\n", s->RxBufferSize));
1729
}
1730

    
1731
static uint32_t rtl8139_RxConfig_read(RTL8139State *s)
1732
{
1733
    uint32_t ret = s->RxConfig;
1734

    
1735
    DEBUG_PRINT(("RTL8139: RxConfig read val=0x%08x\n", ret));
1736

    
1737
    return ret;
1738
}
1739

    
1740
static void rtl8139_transfer_frame(RTL8139State *s, const uint8_t *buf, int size, int do_interrupt)
1741
{
1742
    if (!size)
1743
    {
1744
        DEBUG_PRINT(("RTL8139: +++ empty ethernet frame\n"));
1745
        return;
1746
    }
1747

    
1748
    if (TxLoopBack == (s->TxConfig & TxLoopBack))
1749
    {
1750
        DEBUG_PRINT(("RTL8139: +++ transmit loopback mode\n"));
1751
        rtl8139_do_receive(&s->nic->nc, buf, size, do_interrupt);
1752
    }
1753
    else
1754
    {
1755
        qemu_send_packet(&s->nic->nc, buf, size);
1756
    }
1757
}
1758

    
1759
static int rtl8139_transmit_one(RTL8139State *s, int descriptor)
1760
{
1761
    if (!rtl8139_transmitter_enabled(s))
1762
    {
1763
        DEBUG_PRINT(("RTL8139: +++ cannot transmit from descriptor %d: transmitter disabled\n",
1764
                     descriptor));
1765
        return 0;
1766
    }
1767

    
1768
    if (s->TxStatus[descriptor] & TxHostOwns)
1769
    {
1770
        DEBUG_PRINT(("RTL8139: +++ cannot transmit from descriptor %d: owned by host (%08x)\n",
1771
                     descriptor, s->TxStatus[descriptor]));
1772
        return 0;
1773
    }
1774

    
1775
    DEBUG_PRINT(("RTL8139: +++ transmitting from descriptor %d\n", descriptor));
1776

    
1777
    int txsize = s->TxStatus[descriptor] & 0x1fff;
1778
    uint8_t txbuffer[0x2000];
1779

    
1780
    DEBUG_PRINT(("RTL8139: +++ transmit reading %d bytes from host memory at 0x%08x\n",
1781
                 txsize, s->TxAddr[descriptor]));
1782

    
1783
    cpu_physical_memory_read(s->TxAddr[descriptor], txbuffer, txsize);
1784

    
1785
    /* Mark descriptor as transferred */
1786
    s->TxStatus[descriptor] |= TxHostOwns;
1787
    s->TxStatus[descriptor] |= TxStatOK;
1788

    
1789
    rtl8139_transfer_frame(s, txbuffer, txsize, 0);
1790

    
1791
    DEBUG_PRINT(("RTL8139: +++ transmitted %d bytes from descriptor %d\n", txsize, descriptor));
1792

    
1793
    /* update interrupt */
1794
    s->IntrStatus |= TxOK;
1795
    rtl8139_update_irq(s);
1796

    
1797
    return 1;
1798
}
1799

    
1800
/* structures and macros for task offloading */
1801
typedef struct ip_header
1802
{
1803
    uint8_t  ip_ver_len;    /* version and header length */
1804
    uint8_t  ip_tos;        /* type of service */
1805
    uint16_t ip_len;        /* total length */
1806
    uint16_t ip_id;         /* identification */
1807
    uint16_t ip_off;        /* fragment offset field */
1808
    uint8_t  ip_ttl;        /* time to live */
1809
    uint8_t  ip_p;          /* protocol */
1810
    uint16_t ip_sum;        /* checksum */
1811
    uint32_t ip_src,ip_dst; /* source and dest address */
1812
} ip_header;
1813

    
1814
#define IP_HEADER_VERSION_4 4
1815
#define IP_HEADER_VERSION(ip) ((ip->ip_ver_len >> 4)&0xf)
1816
#define IP_HEADER_LENGTH(ip) (((ip->ip_ver_len)&0xf) << 2)
1817

    
1818
typedef struct tcp_header
1819
{
1820
    uint16_t th_sport;                /* source port */
1821
    uint16_t th_dport;                /* destination port */
1822
    uint32_t th_seq;                        /* sequence number */
1823
    uint32_t th_ack;                        /* acknowledgement number */
1824
    uint16_t th_offset_flags; /* data offset, reserved 6 bits, TCP protocol flags */
1825
    uint16_t th_win;                        /* window */
1826
    uint16_t th_sum;                        /* checksum */
1827
    uint16_t th_urp;                        /* urgent pointer */
1828
} tcp_header;
1829

    
1830
typedef struct udp_header
1831
{
1832
    uint16_t uh_sport; /* source port */
1833
    uint16_t uh_dport; /* destination port */
1834
    uint16_t uh_ulen;  /* udp length */
1835
    uint16_t uh_sum;   /* udp checksum */
1836
} udp_header;
1837

    
1838
typedef struct ip_pseudo_header
1839
{
1840
    uint32_t ip_src;
1841
    uint32_t ip_dst;
1842
    uint8_t  zeros;
1843
    uint8_t  ip_proto;
1844
    uint16_t ip_payload;
1845
} ip_pseudo_header;
1846

    
1847
#define IP_PROTO_TCP 6
1848
#define IP_PROTO_UDP 17
1849

    
1850
#define TCP_HEADER_DATA_OFFSET(tcp) (((be16_to_cpu(tcp->th_offset_flags) >> 12)&0xf) << 2)
1851
#define TCP_FLAGS_ONLY(flags) ((flags)&0x3f)
1852
#define TCP_HEADER_FLAGS(tcp) TCP_FLAGS_ONLY(be16_to_cpu(tcp->th_offset_flags))
1853

    
1854
#define TCP_HEADER_CLEAR_FLAGS(tcp, off) ((tcp)->th_offset_flags &= cpu_to_be16(~TCP_FLAGS_ONLY(off)))
1855

    
1856
#define TCP_FLAG_FIN  0x01
1857
#define TCP_FLAG_PUSH 0x08
1858

    
1859
/* produces ones' complement sum of data */
1860
static uint16_t ones_complement_sum(uint8_t *data, size_t len)
1861
{
1862
    uint32_t result = 0;
1863

    
1864
    for (; len > 1; data+=2, len-=2)
1865
    {
1866
        result += *(uint16_t*)data;
1867
    }
1868

    
1869
    /* add the remainder byte */
1870
    if (len)
1871
    {
1872
        uint8_t odd[2] = {*data, 0};
1873
        result += *(uint16_t*)odd;
1874
    }
1875

    
1876
    while (result>>16)
1877
        result = (result & 0xffff) + (result >> 16);
1878

    
1879
    return result;
1880
}
1881

    
1882
static uint16_t ip_checksum(void *data, size_t len)
1883
{
1884
    return ~ones_complement_sum((uint8_t*)data, len);
1885
}
1886

    
1887
static int rtl8139_cplus_transmit_one(RTL8139State *s)
1888
{
1889
    if (!rtl8139_transmitter_enabled(s))
1890
    {
1891
        DEBUG_PRINT(("RTL8139: +++ C+ mode: transmitter disabled\n"));
1892
        return 0;
1893
    }
1894

    
1895
    if (!rtl8139_cp_transmitter_enabled(s))
1896
    {
1897
        DEBUG_PRINT(("RTL8139: +++ C+ mode: C+ transmitter disabled\n"));
1898
        return 0 ;
1899
    }
1900

    
1901
    int descriptor = s->currCPlusTxDesc;
1902

    
1903
    target_phys_addr_t cplus_tx_ring_desc =
1904
        rtl8139_addr64(s->TxAddr[0], s->TxAddr[1]);
1905

    
1906
    /* Normal priority ring */
1907
    cplus_tx_ring_desc += 16 * descriptor;
1908

    
1909
    DEBUG_PRINT(("RTL8139: +++ C+ mode reading TX descriptor %d from host memory at %08x0x%08x = 0x%8lx\n",
1910
           descriptor, s->TxAddr[1], s->TxAddr[0], cplus_tx_ring_desc));
1911

    
1912
    uint32_t val, txdw0,txdw1,txbufLO,txbufHI;
1913

    
1914
    cpu_physical_memory_read(cplus_tx_ring_desc,    (uint8_t *)&val, 4);
1915
    txdw0 = le32_to_cpu(val);
1916
    /* TODO: implement VLAN tagging support, VLAN tag data is read to txdw1 */
1917
    cpu_physical_memory_read(cplus_tx_ring_desc+4,  (uint8_t *)&val, 4);
1918
    txdw1 = le32_to_cpu(val);
1919
    cpu_physical_memory_read(cplus_tx_ring_desc+8,  (uint8_t *)&val, 4);
1920
    txbufLO = le32_to_cpu(val);
1921
    cpu_physical_memory_read(cplus_tx_ring_desc+12, (uint8_t *)&val, 4);
1922
    txbufHI = le32_to_cpu(val);
1923

    
1924
    DEBUG_PRINT(("RTL8139: +++ C+ mode TX descriptor %d %08x %08x %08x %08x\n",
1925
           descriptor,
1926
           txdw0, txdw1, txbufLO, txbufHI));
1927

    
1928
    /* TODO: the following discard cast should clean clang analyzer output */
1929
    (void)txdw1;
1930

    
1931
/* w0 ownership flag */
1932
#define CP_TX_OWN (1<<31)
1933
/* w0 end of ring flag */
1934
#define CP_TX_EOR (1<<30)
1935
/* first segment of received packet flag */
1936
#define CP_TX_FS (1<<29)
1937
/* last segment of received packet flag */
1938
#define CP_TX_LS (1<<28)
1939
/* large send packet flag */
1940
#define CP_TX_LGSEN (1<<27)
1941
/* large send MSS mask, bits 16...25 */
1942
#define CP_TC_LGSEN_MSS_MASK ((1 << 12) - 1)
1943

    
1944
/* IP checksum offload flag */
1945
#define CP_TX_IPCS (1<<18)
1946
/* UDP checksum offload flag */
1947
#define CP_TX_UDPCS (1<<17)
1948
/* TCP checksum offload flag */
1949
#define CP_TX_TCPCS (1<<16)
1950

    
1951
/* w0 bits 0...15 : buffer size */
1952
#define CP_TX_BUFFER_SIZE (1<<16)
1953
#define CP_TX_BUFFER_SIZE_MASK (CP_TX_BUFFER_SIZE - 1)
1954
/* w1 tag available flag */
1955
#define CP_RX_TAGC (1<<17)
1956
/* w1 bits 0...15 : VLAN tag */
1957
#define CP_TX_VLAN_TAG_MASK ((1<<16) - 1)
1958
/* w2 low  32bit of Rx buffer ptr */
1959
/* w3 high 32bit of Rx buffer ptr */
1960

    
1961
/* set after transmission */
1962
/* FIFO underrun flag */
1963
#define CP_TX_STATUS_UNF (1<<25)
1964
/* transmit error summary flag, valid if set any of three below */
1965
#define CP_TX_STATUS_TES (1<<23)
1966
/* out-of-window collision flag */
1967
#define CP_TX_STATUS_OWC (1<<22)
1968
/* link failure flag */
1969
#define CP_TX_STATUS_LNKF (1<<21)
1970
/* excessive collisions flag */
1971
#define CP_TX_STATUS_EXC (1<<20)
1972

    
1973
    if (!(txdw0 & CP_TX_OWN))
1974
    {
1975
        DEBUG_PRINT(("RTL8139: C+ Tx mode : descriptor %d is owned by host\n", descriptor));
1976
        return 0 ;
1977
    }
1978

    
1979
    DEBUG_PRINT(("RTL8139: +++ C+ Tx mode : transmitting from descriptor %d\n", descriptor));
1980

    
1981
    if (txdw0 & CP_TX_FS)
1982
    {
1983
        DEBUG_PRINT(("RTL8139: +++ C+ Tx mode : descriptor %d is first segment descriptor\n", descriptor));
1984

    
1985
        /* reset internal buffer offset */
1986
        s->cplus_txbuffer_offset = 0;
1987
    }
1988

    
1989
    int txsize = txdw0 & CP_TX_BUFFER_SIZE_MASK;
1990
    target_phys_addr_t tx_addr = rtl8139_addr64(txbufLO, txbufHI);
1991

    
1992
    /* make sure we have enough space to assemble the packet */
1993
    if (!s->cplus_txbuffer)
1994
    {
1995
        s->cplus_txbuffer_len = CP_TX_BUFFER_SIZE;
1996
        s->cplus_txbuffer = qemu_malloc(s->cplus_txbuffer_len);
1997
        s->cplus_txbuffer_offset = 0;
1998

    
1999
        DEBUG_PRINT(("RTL8139: +++ C+ mode transmission buffer allocated space %d\n", s->cplus_txbuffer_len));
2000
    }
2001

    
2002
    while (s->cplus_txbuffer && s->cplus_txbuffer_offset + txsize >= s->cplus_txbuffer_len)
2003
    {
2004
        s->cplus_txbuffer_len += CP_TX_BUFFER_SIZE;
2005
        s->cplus_txbuffer = qemu_realloc(s->cplus_txbuffer, s->cplus_txbuffer_len);
2006

    
2007
        DEBUG_PRINT(("RTL8139: +++ C+ mode transmission buffer space changed to %d\n", s->cplus_txbuffer_len));
2008
    }
2009

    
2010
    if (!s->cplus_txbuffer)
2011
    {
2012
        /* out of memory */
2013

    
2014
        DEBUG_PRINT(("RTL8139: +++ C+ mode transmiter failed to reallocate %d bytes\n", s->cplus_txbuffer_len));
2015

    
2016
        /* update tally counter */
2017
        ++s->tally_counters.TxERR;
2018
        ++s->tally_counters.TxAbt;
2019

    
2020
        return 0;
2021
    }
2022

    
2023
    /* append more data to the packet */
2024

    
2025
    DEBUG_PRINT(("RTL8139: +++ C+ mode transmit reading %d bytes from host memory at %016" PRIx64 " to offset %d\n",
2026
                 txsize, (uint64_t)tx_addr, s->cplus_txbuffer_offset));
2027

    
2028
    cpu_physical_memory_read(tx_addr, s->cplus_txbuffer + s->cplus_txbuffer_offset, txsize);
2029
    s->cplus_txbuffer_offset += txsize;
2030

    
2031
    /* seek to next Rx descriptor */
2032
    if (txdw0 & CP_TX_EOR)
2033
    {
2034
        s->currCPlusTxDesc = 0;
2035
    }
2036
    else
2037
    {
2038
        ++s->currCPlusTxDesc;
2039
        if (s->currCPlusTxDesc >= 64)
2040
            s->currCPlusTxDesc = 0;
2041
    }
2042

    
2043
    /* transfer ownership to target */
2044
    txdw0 &= ~CP_RX_OWN;
2045

    
2046
    /* reset error indicator bits */
2047
    txdw0 &= ~CP_TX_STATUS_UNF;
2048
    txdw0 &= ~CP_TX_STATUS_TES;
2049
    txdw0 &= ~CP_TX_STATUS_OWC;
2050
    txdw0 &= ~CP_TX_STATUS_LNKF;
2051
    txdw0 &= ~CP_TX_STATUS_EXC;
2052

    
2053
    /* update ring data */
2054
    val = cpu_to_le32(txdw0);
2055
    cpu_physical_memory_write(cplus_tx_ring_desc,    (uint8_t *)&val, 4);
2056
    /* TODO: implement VLAN tagging support, VLAN tag data is read to txdw1 */
2057
//    val = cpu_to_le32(txdw1);
2058
//    cpu_physical_memory_write(cplus_tx_ring_desc+4,  &val, 4);
2059

    
2060
    /* Now decide if descriptor being processed is holding the last segment of packet */
2061
    if (txdw0 & CP_TX_LS)
2062
    {
2063
        DEBUG_PRINT(("RTL8139: +++ C+ Tx mode : descriptor %d is last segment descriptor\n", descriptor));
2064

    
2065
        /* can transfer fully assembled packet */
2066

    
2067
        uint8_t *saved_buffer  = s->cplus_txbuffer;
2068
        int      saved_size    = s->cplus_txbuffer_offset;
2069
        int      saved_buffer_len = s->cplus_txbuffer_len;
2070

    
2071
        /* reset the card space to protect from recursive call */
2072
        s->cplus_txbuffer = NULL;
2073
        s->cplus_txbuffer_offset = 0;
2074
        s->cplus_txbuffer_len = 0;
2075

    
2076
        if (txdw0 & (CP_TX_IPCS | CP_TX_UDPCS | CP_TX_TCPCS | CP_TX_LGSEN))
2077
        {
2078
            DEBUG_PRINT(("RTL8139: +++ C+ mode offloaded task checksum\n"));
2079

    
2080
            #define ETH_P_IP        0x0800                /* Internet Protocol packet        */
2081
            #define ETH_HLEN    14
2082
            #define ETH_MTU     1500
2083

    
2084
            /* ip packet header */
2085
            ip_header *ip = NULL;
2086
            int hlen = 0;
2087
            uint8_t  ip_protocol = 0;
2088
            uint16_t ip_data_len = 0;
2089

    
2090
            uint8_t *eth_payload_data = NULL;
2091
            size_t   eth_payload_len  = 0;
2092

    
2093
            int proto = be16_to_cpu(*(uint16_t *)(saved_buffer + 12));
2094
            if (proto == ETH_P_IP)
2095
            {
2096
                DEBUG_PRINT(("RTL8139: +++ C+ mode has IP packet\n"));
2097

    
2098
                /* not aligned */
2099
                eth_payload_data = saved_buffer + ETH_HLEN;
2100
                eth_payload_len  = saved_size   - ETH_HLEN;
2101

    
2102
                ip = (ip_header*)eth_payload_data;
2103

    
2104
                if (IP_HEADER_VERSION(ip) != IP_HEADER_VERSION_4) {
2105
                    DEBUG_PRINT(("RTL8139: +++ C+ mode packet has bad IP version %d expected %d\n", IP_HEADER_VERSION(ip), IP_HEADER_VERSION_4));
2106
                    ip = NULL;
2107
                } else {
2108
                    hlen = IP_HEADER_LENGTH(ip);
2109
                    ip_protocol = ip->ip_p;
2110
                    ip_data_len = be16_to_cpu(ip->ip_len) - hlen;
2111
                }
2112
            }
2113

    
2114
            if (ip)
2115
            {
2116
                if (txdw0 & CP_TX_IPCS)
2117
                {
2118
                    DEBUG_PRINT(("RTL8139: +++ C+ mode need IP checksum\n"));
2119

    
2120
                    if (hlen<sizeof(ip_header) || hlen>eth_payload_len) {/* min header length */
2121
                        /* bad packet header len */
2122
                        /* or packet too short */
2123
                    }
2124
                    else
2125
                    {
2126
                        ip->ip_sum = 0;
2127
                        ip->ip_sum = ip_checksum(ip, hlen);
2128
                        DEBUG_PRINT(("RTL8139: +++ C+ mode IP header len=%d checksum=%04x\n", hlen, ip->ip_sum));
2129
                    }
2130
                }
2131

    
2132
                if ((txdw0 & CP_TX_LGSEN) && ip_protocol == IP_PROTO_TCP)
2133
                {
2134
#if defined (DEBUG_RTL8139)
2135
                    int large_send_mss = (txdw0 >> 16) & CP_TC_LGSEN_MSS_MASK;
2136
#endif
2137
                    DEBUG_PRINT(("RTL8139: +++ C+ mode offloaded task TSO MTU=%d IP data %d frame data %d specified MSS=%d\n",
2138
                                 ETH_MTU, ip_data_len, saved_size - ETH_HLEN, large_send_mss));
2139

    
2140
                    int tcp_send_offset = 0;
2141
                    int send_count = 0;
2142

    
2143
                    /* maximum IP header length is 60 bytes */
2144
                    uint8_t saved_ip_header[60];
2145

    
2146
                    /* save IP header template; data area is used in tcp checksum calculation */
2147
                    memcpy(saved_ip_header, eth_payload_data, hlen);
2148

    
2149
                    /* a placeholder for checksum calculation routine in tcp case */
2150
                    uint8_t *data_to_checksum     = eth_payload_data + hlen - 12;
2151
                    //                    size_t   data_to_checksum_len = eth_payload_len  - hlen + 12;
2152

    
2153
                    /* pointer to TCP header */
2154
                    tcp_header *p_tcp_hdr = (tcp_header*)(eth_payload_data + hlen);
2155

    
2156
                    int tcp_hlen = TCP_HEADER_DATA_OFFSET(p_tcp_hdr);
2157

    
2158
                    /* ETH_MTU = ip header len + tcp header len + payload */
2159
                    int tcp_data_len = ip_data_len - tcp_hlen;
2160
                    int tcp_chunk_size = ETH_MTU - hlen - tcp_hlen;
2161

    
2162
                    DEBUG_PRINT(("RTL8139: +++ C+ mode TSO IP data len %d TCP hlen %d TCP data len %d TCP chunk size %d\n",
2163
                                 ip_data_len, tcp_hlen, tcp_data_len, tcp_chunk_size));
2164

    
2165
                    /* note the cycle below overwrites IP header data,
2166
                       but restores it from saved_ip_header before sending packet */
2167

    
2168
                    int is_last_frame = 0;
2169

    
2170
                    for (tcp_send_offset = 0; tcp_send_offset < tcp_data_len; tcp_send_offset += tcp_chunk_size)
2171
                    {
2172
                        uint16_t chunk_size = tcp_chunk_size;
2173

    
2174
                        /* check if this is the last frame */
2175
                        if (tcp_send_offset + tcp_chunk_size >= tcp_data_len)
2176
                        {
2177
                            is_last_frame = 1;
2178
                            chunk_size = tcp_data_len - tcp_send_offset;
2179
                        }
2180

    
2181
                        DEBUG_PRINT(("RTL8139: +++ C+ mode TSO TCP seqno %08x\n", be32_to_cpu(p_tcp_hdr->th_seq)));
2182

    
2183
                        /* add 4 TCP pseudoheader fields */
2184
                        /* copy IP source and destination fields */
2185
                        memcpy(data_to_checksum, saved_ip_header + 12, 8);
2186

    
2187
                        DEBUG_PRINT(("RTL8139: +++ C+ mode TSO calculating TCP checksum for packet with %d bytes data\n", tcp_hlen + chunk_size));
2188

    
2189
                        if (tcp_send_offset)
2190
                        {
2191
                            memcpy((uint8_t*)p_tcp_hdr + tcp_hlen, (uint8_t*)p_tcp_hdr + tcp_hlen + tcp_send_offset, chunk_size);
2192
                        }
2193

    
2194
                        /* keep PUSH and FIN flags only for the last frame */
2195
                        if (!is_last_frame)
2196
                        {
2197
                            TCP_HEADER_CLEAR_FLAGS(p_tcp_hdr, TCP_FLAG_PUSH|TCP_FLAG_FIN);
2198
                        }
2199

    
2200
                        /* recalculate TCP checksum */
2201
                        ip_pseudo_header *p_tcpip_hdr = (ip_pseudo_header *)data_to_checksum;
2202
                        p_tcpip_hdr->zeros      = 0;
2203
                        p_tcpip_hdr->ip_proto   = IP_PROTO_TCP;
2204
                        p_tcpip_hdr->ip_payload = cpu_to_be16(tcp_hlen + chunk_size);
2205

    
2206
                        p_tcp_hdr->th_sum = 0;
2207

    
2208
                        int tcp_checksum = ip_checksum(data_to_checksum, tcp_hlen + chunk_size + 12);
2209
                        DEBUG_PRINT(("RTL8139: +++ C+ mode TSO TCP checksum %04x\n", tcp_checksum));
2210

    
2211
                        p_tcp_hdr->th_sum = tcp_checksum;
2212

    
2213
                        /* restore IP header */
2214
                        memcpy(eth_payload_data, saved_ip_header, hlen);
2215

    
2216
                        /* set IP data length and recalculate IP checksum */
2217
                        ip->ip_len = cpu_to_be16(hlen + tcp_hlen + chunk_size);
2218

    
2219
                        /* increment IP id for subsequent frames */
2220
                        ip->ip_id = cpu_to_be16(tcp_send_offset/tcp_chunk_size + be16_to_cpu(ip->ip_id));
2221

    
2222
                        ip->ip_sum = 0;
2223
                        ip->ip_sum = ip_checksum(eth_payload_data, hlen);
2224
                        DEBUG_PRINT(("RTL8139: +++ C+ mode TSO IP header len=%d checksum=%04x\n", hlen, ip->ip_sum));
2225

    
2226
                        int tso_send_size = ETH_HLEN + hlen + tcp_hlen + chunk_size;
2227
                        DEBUG_PRINT(("RTL8139: +++ C+ mode TSO transferring packet size %d\n", tso_send_size));
2228
                        rtl8139_transfer_frame(s, saved_buffer, tso_send_size, 0);
2229

    
2230
                        /* add transferred count to TCP sequence number */
2231
                        p_tcp_hdr->th_seq = cpu_to_be32(chunk_size + be32_to_cpu(p_tcp_hdr->th_seq));
2232
                        ++send_count;
2233
                    }
2234

    
2235
                    /* Stop sending this frame */
2236
                    saved_size = 0;
2237
                }
2238
                else if (txdw0 & (CP_TX_TCPCS|CP_TX_UDPCS))
2239
                {
2240
                    DEBUG_PRINT(("RTL8139: +++ C+ mode need TCP or UDP checksum\n"));
2241

    
2242
                    /* maximum IP header length is 60 bytes */
2243
                    uint8_t saved_ip_header[60];
2244
                    memcpy(saved_ip_header, eth_payload_data, hlen);
2245

    
2246
                    uint8_t *data_to_checksum     = eth_payload_data + hlen - 12;
2247
                    //                    size_t   data_to_checksum_len = eth_payload_len  - hlen + 12;
2248

    
2249
                    /* add 4 TCP pseudoheader fields */
2250
                    /* copy IP source and destination fields */
2251
                    memcpy(data_to_checksum, saved_ip_header + 12, 8);
2252

    
2253
                    if ((txdw0 & CP_TX_TCPCS) && ip_protocol == IP_PROTO_TCP)
2254
                    {
2255
                        DEBUG_PRINT(("RTL8139: +++ C+ mode calculating TCP checksum for packet with %d bytes data\n", ip_data_len));
2256

    
2257
                        ip_pseudo_header *p_tcpip_hdr = (ip_pseudo_header *)data_to_checksum;
2258
                        p_tcpip_hdr->zeros      = 0;
2259
                        p_tcpip_hdr->ip_proto   = IP_PROTO_TCP;
2260
                        p_tcpip_hdr->ip_payload = cpu_to_be16(ip_data_len);
2261

    
2262
                        tcp_header* p_tcp_hdr = (tcp_header *) (data_to_checksum+12);
2263

    
2264
                        p_tcp_hdr->th_sum = 0;
2265

    
2266
                        int tcp_checksum = ip_checksum(data_to_checksum, ip_data_len + 12);
2267
                        DEBUG_PRINT(("RTL8139: +++ C+ mode TCP checksum %04x\n", tcp_checksum));
2268

    
2269
                        p_tcp_hdr->th_sum = tcp_checksum;
2270
                    }
2271
                    else if ((txdw0 & CP_TX_UDPCS) && ip_protocol == IP_PROTO_UDP)
2272
                    {
2273
                        DEBUG_PRINT(("RTL8139: +++ C+ mode calculating UDP checksum for packet with %d bytes data\n", ip_data_len));
2274

    
2275
                        ip_pseudo_header *p_udpip_hdr = (ip_pseudo_header *)data_to_checksum;
2276
                        p_udpip_hdr->zeros      = 0;
2277
                        p_udpip_hdr->ip_proto   = IP_PROTO_UDP;
2278
                        p_udpip_hdr->ip_payload = cpu_to_be16(ip_data_len);
2279

    
2280
                        udp_header *p_udp_hdr = (udp_header *) (data_to_checksum+12);
2281

    
2282
                        p_udp_hdr->uh_sum = 0;
2283

    
2284
                        int udp_checksum = ip_checksum(data_to_checksum, ip_data_len + 12);
2285
                        DEBUG_PRINT(("RTL8139: +++ C+ mode UDP checksum %04x\n", udp_checksum));
2286

    
2287
                        p_udp_hdr->uh_sum = udp_checksum;
2288
                    }
2289

    
2290
                    /* restore IP header */
2291
                    memcpy(eth_payload_data, saved_ip_header, hlen);
2292
                }
2293
            }
2294
        }
2295

    
2296
        /* update tally counter */
2297
        ++s->tally_counters.TxOk;
2298

    
2299
        DEBUG_PRINT(("RTL8139: +++ C+ mode transmitting %d bytes packet\n", saved_size));
2300

    
2301
        rtl8139_transfer_frame(s, saved_buffer, saved_size, 1);
2302

    
2303
        /* restore card space if there was no recursion and reset offset */
2304
        if (!s->cplus_txbuffer)
2305
        {
2306
            s->cplus_txbuffer        = saved_buffer;
2307
            s->cplus_txbuffer_len    = saved_buffer_len;
2308
            s->cplus_txbuffer_offset = 0;
2309
        }
2310
        else
2311
        {
2312
            qemu_free(saved_buffer);
2313
        }
2314
    }
2315
    else
2316
    {
2317
        DEBUG_PRINT(("RTL8139: +++ C+ mode transmission continue to next descriptor\n"));
2318
    }
2319

    
2320
    return 1;
2321
}
2322

    
2323
static void rtl8139_cplus_transmit(RTL8139State *s)
2324
{
2325
    int txcount = 0;
2326

    
2327
    while (rtl8139_cplus_transmit_one(s))
2328
    {
2329
        ++txcount;
2330
    }
2331

    
2332
    /* Mark transfer completed */
2333
    if (!txcount)
2334
    {
2335
        DEBUG_PRINT(("RTL8139: C+ mode : transmitter queue stalled, current TxDesc = %d\n",
2336
                     s->currCPlusTxDesc));
2337
    }
2338
    else
2339
    {
2340
        /* update interrupt status */
2341
        s->IntrStatus |= TxOK;
2342
        rtl8139_update_irq(s);
2343
    }
2344
}
2345

    
2346
static void rtl8139_transmit(RTL8139State *s)
2347
{
2348
    int descriptor = s->currTxDesc, txcount = 0;
2349

    
2350
    /*while*/
2351
    if (rtl8139_transmit_one(s, descriptor))
2352
    {
2353
        ++s->currTxDesc;
2354
        s->currTxDesc %= 4;
2355
        ++txcount;
2356
    }
2357

    
2358
    /* Mark transfer completed */
2359
    if (!txcount)
2360
    {
2361
        DEBUG_PRINT(("RTL8139: transmitter queue stalled, current TxDesc = %d\n", s->currTxDesc));
2362
    }
2363
}
2364

    
2365
static void rtl8139_TxStatus_write(RTL8139State *s, uint32_t txRegOffset, uint32_t val)
2366
{
2367

    
2368
    int descriptor = txRegOffset/4;
2369

    
2370
    /* handle C+ transmit mode register configuration */
2371

    
2372
    if (s->cplus_enabled)
2373
    {
2374
        DEBUG_PRINT(("RTL8139C+ DTCCR write offset=0x%x val=0x%08x descriptor=%d\n", txRegOffset, val, descriptor));
2375

    
2376
        /* handle Dump Tally Counters command */
2377
        s->TxStatus[descriptor] = val;
2378

    
2379
        if (descriptor == 0 && (val & 0x8))
2380
        {
2381
            target_phys_addr_t tc_addr = rtl8139_addr64(s->TxStatus[0] & ~0x3f, s->TxStatus[1]);
2382

    
2383
            /* dump tally counters to specified memory location */
2384
            RTL8139TallyCounters_physical_memory_write( tc_addr, &s->tally_counters);
2385

    
2386
            /* mark dump completed */
2387
            s->TxStatus[0] &= ~0x8;
2388
        }
2389

    
2390
        return;
2391
    }
2392

    
2393
    DEBUG_PRINT(("RTL8139: TxStatus write offset=0x%x val=0x%08x descriptor=%d\n", txRegOffset, val, descriptor));
2394

    
2395
    /* mask only reserved bits */
2396
    val &= ~0xff00c000; /* these bits are reset on write */
2397
    val = SET_MASKED(val, 0x00c00000, s->TxStatus[descriptor]);
2398

    
2399
    s->TxStatus[descriptor] = val;
2400

    
2401
    /* attempt to start transmission */
2402
    rtl8139_transmit(s);
2403
}
2404

    
2405
static uint32_t rtl8139_TxStatus_read(RTL8139State *s, uint32_t txRegOffset)
2406
{
2407
    uint32_t ret = s->TxStatus[txRegOffset/4];
2408

    
2409
    DEBUG_PRINT(("RTL8139: TxStatus read offset=0x%x val=0x%08x\n", txRegOffset, ret));
2410

    
2411
    return ret;
2412
}
2413

    
2414
static uint16_t rtl8139_TSAD_read(RTL8139State *s)
2415
{
2416
    uint16_t ret = 0;
2417

    
2418
    /* Simulate TSAD, it is read only anyway */
2419

    
2420
    ret = ((s->TxStatus[3] & TxStatOK  )?TSAD_TOK3:0)
2421
         |((s->TxStatus[2] & TxStatOK  )?TSAD_TOK2:0)
2422
         |((s->TxStatus[1] & TxStatOK  )?TSAD_TOK1:0)
2423
         |((s->TxStatus[0] & TxStatOK  )?TSAD_TOK0:0)
2424

    
2425
         |((s->TxStatus[3] & TxUnderrun)?TSAD_TUN3:0)
2426
         |((s->TxStatus[2] & TxUnderrun)?TSAD_TUN2:0)
2427
         |((s->TxStatus[1] & TxUnderrun)?TSAD_TUN1:0)
2428
         |((s->TxStatus[0] & TxUnderrun)?TSAD_TUN0:0)
2429

    
2430
         |((s->TxStatus[3] & TxAborted )?TSAD_TABT3:0)
2431
         |((s->TxStatus[2] & TxAborted )?TSAD_TABT2:0)
2432
         |((s->TxStatus[1] & TxAborted )?TSAD_TABT1:0)
2433
         |((s->TxStatus[0] & TxAborted )?TSAD_TABT0:0)
2434

    
2435
         |((s->TxStatus[3] & TxHostOwns )?TSAD_OWN3:0)
2436
         |((s->TxStatus[2] & TxHostOwns )?TSAD_OWN2:0)
2437
         |((s->TxStatus[1] & TxHostOwns )?TSAD_OWN1:0)
2438
         |((s->TxStatus[0] & TxHostOwns )?TSAD_OWN0:0) ;
2439

    
2440

    
2441
    DEBUG_PRINT(("RTL8139: TSAD read val=0x%04x\n", ret));
2442

    
2443
    return ret;
2444
}
2445

    
2446
static uint16_t rtl8139_CSCR_read(RTL8139State *s)
2447
{
2448
    uint16_t ret = s->CSCR;
2449

    
2450
    DEBUG_PRINT(("RTL8139: CSCR read val=0x%04x\n", ret));
2451

    
2452
    return ret;
2453
}
2454

    
2455
static void rtl8139_TxAddr_write(RTL8139State *s, uint32_t txAddrOffset, uint32_t val)
2456
{
2457
    DEBUG_PRINT(("RTL8139: TxAddr write offset=0x%x val=0x%08x\n", txAddrOffset, val));
2458

    
2459
    s->TxAddr[txAddrOffset/4] = val;
2460
}
2461

    
2462
static uint32_t rtl8139_TxAddr_read(RTL8139State *s, uint32_t txAddrOffset)
2463
{
2464
    uint32_t ret = s->TxAddr[txAddrOffset/4];
2465

    
2466
    DEBUG_PRINT(("RTL8139: TxAddr read offset=0x%x val=0x%08x\n", txAddrOffset, ret));
2467

    
2468
    return ret;
2469
}
2470

    
2471
static void rtl8139_RxBufPtr_write(RTL8139State *s, uint32_t val)
2472
{
2473
    DEBUG_PRINT(("RTL8139: RxBufPtr write val=0x%04x\n", val));
2474

    
2475
    /* this value is off by 16 */
2476
    s->RxBufPtr = MOD2(val + 0x10, s->RxBufferSize);
2477

    
2478
    DEBUG_PRINT((" CAPR write: rx buffer length %d head 0x%04x read 0x%04x\n",
2479
           s->RxBufferSize, s->RxBufAddr, s->RxBufPtr));
2480
}
2481

    
2482
static uint32_t rtl8139_RxBufPtr_read(RTL8139State *s)
2483
{
2484
    /* this value is off by 16 */
2485
    uint32_t ret = s->RxBufPtr - 0x10;
2486

    
2487
    DEBUG_PRINT(("RTL8139: RxBufPtr read val=0x%04x\n", ret));
2488

    
2489
    return ret;
2490
}
2491

    
2492
static uint32_t rtl8139_RxBufAddr_read(RTL8139State *s)
2493
{
2494
    /* this value is NOT off by 16 */
2495
    uint32_t ret = s->RxBufAddr;
2496

    
2497
    DEBUG_PRINT(("RTL8139: RxBufAddr read val=0x%04x\n", ret));
2498

    
2499
    return ret;
2500
}
2501

    
2502
static void rtl8139_RxBuf_write(RTL8139State *s, uint32_t val)
2503
{
2504
    DEBUG_PRINT(("RTL8139: RxBuf write val=0x%08x\n", val));
2505

    
2506
    s->RxBuf = val;
2507

    
2508
    /* may need to reset rxring here */
2509
}
2510

    
2511
static uint32_t rtl8139_RxBuf_read(RTL8139State *s)
2512
{
2513
    uint32_t ret = s->RxBuf;
2514

    
2515
    DEBUG_PRINT(("RTL8139: RxBuf read val=0x%08x\n", ret));
2516

    
2517
    return ret;
2518
}
2519

    
2520
static void rtl8139_IntrMask_write(RTL8139State *s, uint32_t val)
2521
{
2522
    DEBUG_PRINT(("RTL8139: IntrMask write(w) val=0x%04x\n", val));
2523

    
2524
    /* mask unwriteable bits */
2525
    val = SET_MASKED(val, 0x1e00, s->IntrMask);
2526

    
2527
    s->IntrMask = val;
2528

    
2529
    rtl8139_set_next_tctr_time(s, qemu_get_clock(vm_clock));
2530
    rtl8139_update_irq(s);
2531

    
2532
}
2533

    
2534
static uint32_t rtl8139_IntrMask_read(RTL8139State *s)
2535
{
2536
    uint32_t ret = s->IntrMask;
2537

    
2538
    DEBUG_PRINT(("RTL8139: IntrMask read(w) val=0x%04x\n", ret));
2539

    
2540
    return ret;
2541
}
2542

    
2543
static void rtl8139_IntrStatus_write(RTL8139State *s, uint32_t val)
2544
{
2545
    DEBUG_PRINT(("RTL8139: IntrStatus write(w) val=0x%04x\n", val));
2546

    
2547
#if 0
2548

2549
    /* writing to ISR has no effect */
2550

2551
    return;
2552

2553
#else
2554
    uint16_t newStatus = s->IntrStatus & ~val;
2555

    
2556
    /* mask unwriteable bits */
2557
    newStatus = SET_MASKED(newStatus, 0x1e00, s->IntrStatus);
2558

    
2559
    /* writing 1 to interrupt status register bit clears it */
2560
    s->IntrStatus = 0;
2561
    rtl8139_update_irq(s);
2562

    
2563
    s->IntrStatus = newStatus;
2564
    /*
2565
     * Computing if we miss an interrupt here is not that correct but
2566
     * considered that we should have had already an interrupt
2567
     * and probably emulated is slower is better to assume this resetting was
2568
     * done before testing on previous rtl8139_update_irq lead to IRQ loosing
2569
     */
2570
    rtl8139_set_next_tctr_time(s, qemu_get_clock(vm_clock));
2571
    rtl8139_update_irq(s);
2572

    
2573
#endif
2574
}
2575

    
2576
static uint32_t rtl8139_IntrStatus_read(RTL8139State *s)
2577
{
2578
    rtl8139_set_next_tctr_time(s, qemu_get_clock(vm_clock));
2579

    
2580
    uint32_t ret = s->IntrStatus;
2581

    
2582
    DEBUG_PRINT(("RTL8139: IntrStatus read(w) val=0x%04x\n", ret));
2583

    
2584
#if 0
2585

2586
    /* reading ISR clears all interrupts */
2587
    s->IntrStatus = 0;
2588

2589
    rtl8139_update_irq(s);
2590

2591
#endif
2592

    
2593
    return ret;
2594
}
2595

    
2596
static void rtl8139_MultiIntr_write(RTL8139State *s, uint32_t val)
2597
{
2598
    DEBUG_PRINT(("RTL8139: MultiIntr write(w) val=0x%04x\n", val));
2599

    
2600
    /* mask unwriteable bits */
2601
    val = SET_MASKED(val, 0xf000, s->MultiIntr);
2602

    
2603
    s->MultiIntr = val;
2604
}
2605

    
2606
static uint32_t rtl8139_MultiIntr_read(RTL8139State *s)
2607
{
2608
    uint32_t ret = s->MultiIntr;
2609

    
2610
    DEBUG_PRINT(("RTL8139: MultiIntr read(w) val=0x%04x\n", ret));
2611

    
2612
    return ret;
2613
}
2614

    
2615
static void rtl8139_io_writeb(void *opaque, uint8_t addr, uint32_t val)
2616
{
2617
    RTL8139State *s = opaque;
2618

    
2619
    addr &= 0xff;
2620

    
2621
    switch (addr)
2622
    {
2623
        case MAC0 ... MAC0+5:
2624
            s->phys[addr - MAC0] = val;
2625
            break;
2626
        case MAC0+6 ... MAC0+7:
2627
            /* reserved */
2628
            break;
2629
        case MAR0 ... MAR0+7:
2630
            s->mult[addr - MAR0] = val;
2631
            break;
2632
        case ChipCmd:
2633
            rtl8139_ChipCmd_write(s, val);
2634
            break;
2635
        case Cfg9346:
2636
            rtl8139_Cfg9346_write(s, val);
2637
            break;
2638
        case TxConfig: /* windows driver sometimes writes using byte-lenth call */
2639
            rtl8139_TxConfig_writeb(s, val);
2640
            break;
2641
        case Config0:
2642
            rtl8139_Config0_write(s, val);
2643
            break;
2644
        case Config1:
2645
            rtl8139_Config1_write(s, val);
2646
            break;
2647
        case Config3:
2648
            rtl8139_Config3_write(s, val);
2649
            break;
2650
        case Config4:
2651
            rtl8139_Config4_write(s, val);
2652
            break;
2653
        case Config5:
2654
            rtl8139_Config5_write(s, val);
2655
            break;
2656
        case MediaStatus:
2657
            /* ignore */
2658
            DEBUG_PRINT(("RTL8139: not implemented write(b) to MediaStatus val=0x%02x\n", val));
2659
            break;
2660

    
2661
        case HltClk:
2662
            DEBUG_PRINT(("RTL8139: HltClk write val=0x%08x\n", val));
2663
            if (val == 'R')
2664
            {
2665
                s->clock_enabled = 1;
2666
            }
2667
            else if (val == 'H')
2668
            {
2669
                s->clock_enabled = 0;
2670
            }
2671
            break;
2672

    
2673
        case TxThresh:
2674
            DEBUG_PRINT(("RTL8139C+ TxThresh write(b) val=0x%02x\n", val));
2675
            s->TxThresh = val;
2676
            break;
2677

    
2678
        case TxPoll:
2679
            DEBUG_PRINT(("RTL8139C+ TxPoll write(b) val=0x%02x\n", val));
2680
            if (val & (1 << 7))
2681
            {
2682
                DEBUG_PRINT(("RTL8139C+ TxPoll high priority transmission (not implemented)\n"));
2683
                //rtl8139_cplus_transmit(s);
2684
            }
2685
            if (val & (1 << 6))
2686
            {
2687
                DEBUG_PRINT(("RTL8139C+ TxPoll normal priority transmission\n"));
2688
                rtl8139_cplus_transmit(s);
2689
            }
2690

    
2691
            break;
2692

    
2693
        default:
2694
            DEBUG_PRINT(("RTL8139: not implemented write(b) addr=0x%x val=0x%02x\n", addr, val));
2695
            break;
2696
    }
2697
}
2698

    
2699
static void rtl8139_io_writew(void *opaque, uint8_t addr, uint32_t val)
2700
{
2701
    RTL8139State *s = opaque;
2702

    
2703
    addr &= 0xfe;
2704

    
2705
    switch (addr)
2706
    {
2707
        case IntrMask:
2708
            rtl8139_IntrMask_write(s, val);
2709
            break;
2710

    
2711
        case IntrStatus:
2712
            rtl8139_IntrStatus_write(s, val);
2713
            break;
2714

    
2715
        case MultiIntr:
2716
            rtl8139_MultiIntr_write(s, val);
2717
            break;
2718

    
2719
        case RxBufPtr:
2720
            rtl8139_RxBufPtr_write(s, val);
2721
            break;
2722

    
2723
        case BasicModeCtrl:
2724
            rtl8139_BasicModeCtrl_write(s, val);
2725
            break;
2726
        case BasicModeStatus:
2727
            rtl8139_BasicModeStatus_write(s, val);
2728
            break;
2729
        case NWayAdvert:
2730
            DEBUG_PRINT(("RTL8139: NWayAdvert write(w) val=0x%04x\n", val));
2731
            s->NWayAdvert = val;
2732
            break;
2733
        case NWayLPAR:
2734
            DEBUG_PRINT(("RTL8139: forbidden NWayLPAR write(w) val=0x%04x\n", val));
2735
            break;
2736
        case NWayExpansion:
2737
            DEBUG_PRINT(("RTL8139: NWayExpansion write(w) val=0x%04x\n", val));
2738
            s->NWayExpansion = val;
2739
            break;
2740

    
2741
        case CpCmd:
2742
            rtl8139_CpCmd_write(s, val);
2743
            break;
2744

    
2745
        case IntrMitigate:
2746
            rtl8139_IntrMitigate_write(s, val);
2747
            break;
2748

    
2749
        default:
2750
            DEBUG_PRINT(("RTL8139: ioport write(w) addr=0x%x val=0x%04x via write(b)\n", addr, val));
2751

    
2752
            rtl8139_io_writeb(opaque, addr, val & 0xff);
2753
            rtl8139_io_writeb(opaque, addr + 1, (val >> 8) & 0xff);
2754
            break;
2755
    }
2756
}
2757

    
2758
static void rtl8139_set_next_tctr_time(RTL8139State *s, int64_t current_time)
2759
{
2760
    int64_t pci_time, next_time;
2761
    uint32_t low_pci;
2762

    
2763
    DEBUG_PRINT(("RTL8139: entered rtl8139_set_next_tctr_time\n"));
2764

    
2765
    if (s->TimerExpire && current_time >= s->TimerExpire) {
2766
        s->IntrStatus |= PCSTimeout;
2767
        rtl8139_update_irq(s);
2768
    }
2769

    
2770
    /* Set QEMU timer only if needed that is
2771
     * - TimerInt <> 0 (we have a timer)
2772
     * - mask = 1 (we want an interrupt timer)
2773
     * - irq = 0  (irq is not already active)
2774
     * If any of above change we need to compute timer again
2775
     * Also we must check if timer is passed without QEMU timer
2776
     */
2777
    s->TimerExpire = 0;
2778
    if (!s->TimerInt) {
2779
        return;
2780
    }
2781

    
2782
    pci_time = muldiv64(current_time - s->TCTR_base, PCI_FREQUENCY,
2783
                                get_ticks_per_sec());
2784
    low_pci = pci_time & 0xffffffff;
2785
    pci_time = pci_time - low_pci + s->TimerInt;
2786
    if (low_pci >= s->TimerInt) {
2787
        pci_time += 0x100000000LL;
2788
    }
2789
    next_time = s->TCTR_base + muldiv64(pci_time, get_ticks_per_sec(),
2790
                                                PCI_FREQUENCY);
2791
    s->TimerExpire = next_time;
2792

    
2793
    if ((s->IntrMask & PCSTimeout) != 0 && (s->IntrStatus & PCSTimeout) == 0) {
2794
        qemu_mod_timer(s->timer, next_time);
2795
    }
2796
}
2797

    
2798
static void rtl8139_io_writel(void *opaque, uint8_t addr, uint32_t val)
2799
{
2800
    RTL8139State *s = opaque;
2801

    
2802
    addr &= 0xfc;
2803

    
2804
    switch (addr)
2805
    {
2806
        case RxMissed:
2807
            DEBUG_PRINT(("RTL8139: RxMissed clearing on write\n"));
2808
            s->RxMissed = 0;
2809
            break;
2810

    
2811
        case TxConfig:
2812
            rtl8139_TxConfig_write(s, val);
2813
            break;
2814

    
2815
        case RxConfig:
2816
            rtl8139_RxConfig_write(s, val);
2817
            break;
2818

    
2819
        case TxStatus0 ... TxStatus0+4*4-1:
2820
            rtl8139_TxStatus_write(s, addr-TxStatus0, val);
2821
            break;
2822

    
2823
        case TxAddr0 ... TxAddr0+4*4-1:
2824
            rtl8139_TxAddr_write(s, addr-TxAddr0, val);
2825
            break;
2826

    
2827
        case RxBuf:
2828
            rtl8139_RxBuf_write(s, val);
2829
            break;
2830

    
2831
        case RxRingAddrLO:
2832
            DEBUG_PRINT(("RTL8139: C+ RxRing low bits write val=0x%08x\n", val));
2833
            s->RxRingAddrLO = val;
2834
            break;
2835

    
2836
        case RxRingAddrHI:
2837
            DEBUG_PRINT(("RTL8139: C+ RxRing high bits write val=0x%08x\n", val));
2838
            s->RxRingAddrHI = val;
2839
            break;
2840

    
2841
        case Timer:
2842
            DEBUG_PRINT(("RTL8139: TCTR Timer reset on write\n"));
2843
            s->TCTR_base = qemu_get_clock(vm_clock);
2844
            rtl8139_set_next_tctr_time(s, s->TCTR_base);
2845
            break;
2846

    
2847
        case FlashReg:
2848
            DEBUG_PRINT(("RTL8139: FlashReg TimerInt write val=0x%08x\n", val));
2849
            if (s->TimerInt != val) {
2850
                s->TimerInt = val;
2851
                rtl8139_set_next_tctr_time(s, qemu_get_clock(vm_clock));
2852
            }
2853
            break;
2854

    
2855
        default:
2856
            DEBUG_PRINT(("RTL8139: ioport write(l) addr=0x%x val=0x%08x via write(b)\n", addr, val));
2857
            rtl8139_io_writeb(opaque, addr, val & 0xff);
2858
            rtl8139_io_writeb(opaque, addr + 1, (val >> 8) & 0xff);
2859
            rtl8139_io_writeb(opaque, addr + 2, (val >> 16) & 0xff);
2860
            rtl8139_io_writeb(opaque, addr + 3, (val >> 24) & 0xff);
2861
            break;
2862
    }
2863
}
2864

    
2865
static uint32_t rtl8139_io_readb(void *opaque, uint8_t addr)
2866
{
2867
    RTL8139State *s = opaque;
2868
    int ret;
2869

    
2870
    addr &= 0xff;
2871

    
2872
    switch (addr)
2873
    {
2874
        case MAC0 ... MAC0+5:
2875
            ret = s->phys[addr - MAC0];
2876
            break;
2877
        case MAC0+6 ... MAC0+7:
2878
            ret = 0;
2879
            break;
2880
        case MAR0 ... MAR0+7:
2881
            ret = s->mult[addr - MAR0];
2882
            break;
2883
        case ChipCmd:
2884
            ret = rtl8139_ChipCmd_read(s);
2885
            break;
2886
        case Cfg9346:
2887
            ret = rtl8139_Cfg9346_read(s);
2888
            break;
2889
        case Config0:
2890
            ret = rtl8139_Config0_read(s);
2891
            break;
2892
        case Config1:
2893
            ret = rtl8139_Config1_read(s);
2894
            break;
2895
        case Config3:
2896
            ret = rtl8139_Config3_read(s);
2897
            break;
2898
        case Config4:
2899
            ret = rtl8139_Config4_read(s);
2900
            break;
2901
        case Config5:
2902
            ret = rtl8139_Config5_read(s);
2903
            break;
2904

    
2905
        case MediaStatus:
2906
            ret = 0xd0;
2907
            DEBUG_PRINT(("RTL8139: MediaStatus read 0x%x\n", ret));
2908
            break;
2909

    
2910
        case HltClk:
2911
            ret = s->clock_enabled;
2912
            DEBUG_PRINT(("RTL8139: HltClk read 0x%x\n", ret));
2913
            break;
2914

    
2915
        case PCIRevisionID:
2916
            ret = RTL8139_PCI_REVID;
2917
            DEBUG_PRINT(("RTL8139: PCI Revision ID read 0x%x\n", ret));
2918
            break;
2919

    
2920
        case TxThresh:
2921
            ret = s->TxThresh;
2922
            DEBUG_PRINT(("RTL8139C+ TxThresh read(b) val=0x%02x\n", ret));
2923
            break;
2924

    
2925
        case 0x43: /* Part of TxConfig register. Windows driver tries to read it */
2926
            ret = s->TxConfig >> 24;
2927
            DEBUG_PRINT(("RTL8139C TxConfig at 0x43 read(b) val=0x%02x\n", ret));
2928
            break;
2929

    
2930
        default:
2931
            DEBUG_PRINT(("RTL8139: not implemented read(b) addr=0x%x\n", addr));
2932
            ret = 0;
2933
            break;
2934
    }
2935

    
2936
    return ret;
2937
}
2938

    
2939
static uint32_t rtl8139_io_readw(void *opaque, uint8_t addr)
2940
{
2941
    RTL8139State *s = opaque;
2942
    uint32_t ret;
2943

    
2944
    addr &= 0xfe; /* mask lower bit */
2945

    
2946
    switch (addr)
2947
    {
2948
        case IntrMask:
2949
            ret = rtl8139_IntrMask_read(s);
2950
            break;
2951

    
2952
        case IntrStatus:
2953
            ret = rtl8139_IntrStatus_read(s);
2954
            break;
2955

    
2956
        case MultiIntr:
2957
            ret = rtl8139_MultiIntr_read(s);
2958
            break;
2959

    
2960
        case RxBufPtr:
2961
            ret = rtl8139_RxBufPtr_read(s);
2962
            break;
2963

    
2964
        case RxBufAddr:
2965
            ret = rtl8139_RxBufAddr_read(s);
2966
            break;
2967

    
2968
        case BasicModeCtrl:
2969
            ret = rtl8139_BasicModeCtrl_read(s);
2970
            break;
2971
        case BasicModeStatus:
2972
            ret = rtl8139_BasicModeStatus_read(s);
2973
            break;
2974
        case NWayAdvert:
2975
            ret = s->NWayAdvert;
2976
            DEBUG_PRINT(("RTL8139: NWayAdvert read(w) val=0x%04x\n", ret));
2977
            break;
2978
        case NWayLPAR:
2979
            ret = s->NWayLPAR;
2980
            DEBUG_PRINT(("RTL8139: NWayLPAR read(w) val=0x%04x\n", ret));
2981
            break;
2982
        case NWayExpansion:
2983
            ret = s->NWayExpansion;
2984
            DEBUG_PRINT(("RTL8139: NWayExpansion read(w) val=0x%04x\n", ret));
2985
            break;
2986

    
2987
        case CpCmd:
2988
            ret = rtl8139_CpCmd_read(s);
2989
            break;
2990

    
2991
        case IntrMitigate:
2992
            ret = rtl8139_IntrMitigate_read(s);
2993
            break;
2994

    
2995
        case TxSummary:
2996
            ret = rtl8139_TSAD_read(s);
2997
            break;
2998

    
2999
        case CSCR:
3000
            ret = rtl8139_CSCR_read(s);
3001
            break;
3002

    
3003
        default:
3004
            DEBUG_PRINT(("RTL8139: ioport read(w) addr=0x%x via read(b)\n", addr));
3005

    
3006
            ret  = rtl8139_io_readb(opaque, addr);
3007
            ret |= rtl8139_io_readb(opaque, addr + 1) << 8;
3008

    
3009
            DEBUG_PRINT(("RTL8139: ioport read(w) addr=0x%x val=0x%04x\n", addr, ret));
3010
            break;
3011
    }
3012

    
3013
    return ret;
3014
}
3015

    
3016
static uint32_t rtl8139_io_readl(void *opaque, uint8_t addr)
3017
{
3018
    RTL8139State *s = opaque;
3019
    uint32_t ret;
3020

    
3021
    addr &= 0xfc; /* also mask low 2 bits */
3022

    
3023
    switch (addr)
3024
    {
3025
        case RxMissed:
3026
            ret = s->RxMissed;
3027

    
3028
            DEBUG_PRINT(("RTL8139: RxMissed read val=0x%08x\n", ret));
3029
            break;
3030

    
3031
        case TxConfig:
3032
            ret = rtl8139_TxConfig_read(s);
3033
            break;
3034

    
3035
        case RxConfig:
3036
            ret = rtl8139_RxConfig_read(s);
3037
            break;
3038

    
3039
        case TxStatus0 ... TxStatus0+4*4-1:
3040
            ret = rtl8139_TxStatus_read(s, addr-TxStatus0);
3041
            break;
3042

    
3043
        case TxAddr0 ... TxAddr0+4*4-1:
3044
            ret = rtl8139_TxAddr_read(s, addr-TxAddr0);
3045
            break;
3046

    
3047
        case RxBuf:
3048
            ret = rtl8139_RxBuf_read(s);
3049
            break;
3050

    
3051
        case RxRingAddrLO:
3052
            ret = s->RxRingAddrLO;
3053
            DEBUG_PRINT(("RTL8139: C+ RxRing low bits read val=0x%08x\n", ret));
3054
            break;
3055

    
3056
        case RxRingAddrHI:
3057
            ret = s->RxRingAddrHI;
3058
            DEBUG_PRINT(("RTL8139: C+ RxRing high bits read val=0x%08x\n", ret));
3059
            break;
3060

    
3061
        case Timer:
3062
            ret = muldiv64(qemu_get_clock(vm_clock) - s->TCTR_base,
3063
                           PCI_FREQUENCY, get_ticks_per_sec());
3064
            DEBUG_PRINT(("RTL8139: TCTR Timer read val=0x%08x\n", ret));
3065
            break;
3066

    
3067
        case FlashReg:
3068
            ret = s->TimerInt;
3069
            DEBUG_PRINT(("RTL8139: FlashReg TimerInt read val=0x%08x\n", ret));
3070
            break;
3071

    
3072
        default:
3073
            DEBUG_PRINT(("RTL8139: ioport read(l) addr=0x%x via read(b)\n", addr));
3074

    
3075
            ret  = rtl8139_io_readb(opaque, addr);
3076
            ret |= rtl8139_io_readb(opaque, addr + 1) << 8;
3077
            ret |= rtl8139_io_readb(opaque, addr + 2) << 16;
3078
            ret |= rtl8139_io_readb(opaque, addr + 3) << 24;
3079

    
3080
            DEBUG_PRINT(("RTL8139: read(l) addr=0x%x val=%08x\n", addr, ret));
3081
            break;
3082
    }
3083

    
3084
    return ret;
3085
}
3086

    
3087
/* */
3088

    
3089
static void rtl8139_ioport_writeb(void *opaque, uint32_t addr, uint32_t val)
3090
{
3091
    rtl8139_io_writeb(opaque, addr & 0xFF, val);
3092
}
3093

    
3094
static void rtl8139_ioport_writew(void *opaque, uint32_t addr, uint32_t val)
3095
{
3096
    rtl8139_io_writew(opaque, addr & 0xFF, val);
3097
}
3098

    
3099
static void rtl8139_ioport_writel(void *opaque, uint32_t addr, uint32_t val)
3100
{
3101
    rtl8139_io_writel(opaque, addr & 0xFF, val);
3102
}
3103

    
3104
static uint32_t rtl8139_ioport_readb(void *opaque, uint32_t addr)
3105
{
3106
    return rtl8139_io_readb(opaque, addr & 0xFF);
3107
}
3108

    
3109
static uint32_t rtl8139_ioport_readw(void *opaque, uint32_t addr)
3110
{
3111
    return rtl8139_io_readw(opaque, addr & 0xFF);
3112
}
3113

    
3114
static uint32_t rtl8139_ioport_readl(void *opaque, uint32_t addr)
3115
{
3116
    return rtl8139_io_readl(opaque, addr & 0xFF);
3117
}
3118

    
3119
/* */
3120

    
3121
static void rtl8139_mmio_writeb(void *opaque, target_phys_addr_t addr, uint32_t val)
3122
{
3123
    rtl8139_io_writeb(opaque, addr & 0xFF, val);
3124
}
3125

    
3126
static void rtl8139_mmio_writew(void *opaque, target_phys_addr_t addr, uint32_t val)
3127
{
3128
#ifdef TARGET_WORDS_BIGENDIAN
3129
    val = bswap16(val);
3130
#endif
3131
    rtl8139_io_writew(opaque, addr & 0xFF, val);
3132
}
3133

    
3134
static void rtl8139_mmio_writel(void *opaque, target_phys_addr_t addr, uint32_t val)
3135
{
3136
#ifdef TARGET_WORDS_BIGENDIAN
3137
    val = bswap32(val);
3138
#endif
3139
    rtl8139_io_writel(opaque, addr & 0xFF, val);
3140
}
3141

    
3142
static uint32_t rtl8139_mmio_readb(void *opaque, target_phys_addr_t addr)
3143
{
3144
    return rtl8139_io_readb(opaque, addr & 0xFF);
3145
}
3146

    
3147
static uint32_t rtl8139_mmio_readw(void *opaque, target_phys_addr_t addr)
3148
{
3149
    uint32_t val = rtl8139_io_readw(opaque, addr & 0xFF);
3150
#ifdef TARGET_WORDS_BIGENDIAN
3151
    val = bswap16(val);
3152
#endif
3153
    return val;
3154
}
3155

    
3156
static uint32_t rtl8139_mmio_readl(void *opaque, target_phys_addr_t addr)
3157
{
3158
    uint32_t val = rtl8139_io_readl(opaque, addr & 0xFF);
3159
#ifdef TARGET_WORDS_BIGENDIAN
3160
    val = bswap32(val);
3161
#endif
3162
    return val;
3163
}
3164

    
3165
static int rtl8139_post_load(void *opaque, int version_id)
3166
{
3167
    RTL8139State* s = opaque;
3168
    rtl8139_set_next_tctr_time(s, qemu_get_clock(vm_clock));
3169
    if (version_id < 4) {
3170
        s->cplus_enabled = s->CpCmd != 0;
3171
    }
3172

    
3173
    return 0;
3174
}
3175

    
3176
static void rtl8139_pre_save(void *opaque)
3177
{
3178
    RTL8139State* s = opaque;
3179
    int64_t current_time = qemu_get_clock(vm_clock);
3180

    
3181
    /* set IntrStatus correctly */
3182
    rtl8139_set_next_tctr_time(s, current_time);
3183
    s->TCTR = muldiv64(current_time - s->TCTR_base, PCI_FREQUENCY,
3184
                       get_ticks_per_sec());
3185
}
3186

    
3187
static const VMStateDescription vmstate_rtl8139 = {
3188
    .name = "rtl8139",
3189
    .version_id = 4,
3190
    .minimum_version_id = 3,
3191
    .minimum_version_id_old = 3,
3192
    .post_load = rtl8139_post_load,
3193
    .pre_save  = rtl8139_pre_save,
3194
    .fields      = (VMStateField []) {
3195
        VMSTATE_PCI_DEVICE(dev, RTL8139State),
3196
        VMSTATE_PARTIAL_BUFFER(phys, RTL8139State, 6),
3197
        VMSTATE_BUFFER(mult, RTL8139State),
3198
        VMSTATE_UINT32_ARRAY(TxStatus, RTL8139State, 4),
3199
        VMSTATE_UINT32_ARRAY(TxAddr, RTL8139State, 4),
3200

    
3201
        VMSTATE_UINT32(RxBuf, RTL8139State),
3202
        VMSTATE_UINT32(RxBufferSize, RTL8139State),
3203
        VMSTATE_UINT32(RxBufPtr, RTL8139State),
3204
        VMSTATE_UINT32(RxBufAddr, RTL8139State),
3205

    
3206
        VMSTATE_UINT16(IntrStatus, RTL8139State),
3207
        VMSTATE_UINT16(IntrMask, RTL8139State),
3208

    
3209
        VMSTATE_UINT32(TxConfig, RTL8139State),
3210
        VMSTATE_UINT32(RxConfig, RTL8139State),
3211
        VMSTATE_UINT32(RxMissed, RTL8139State),
3212
        VMSTATE_UINT16(CSCR, RTL8139State),
3213

    
3214
        VMSTATE_UINT8(Cfg9346, RTL8139State),
3215
        VMSTATE_UINT8(Config0, RTL8139State),
3216
        VMSTATE_UINT8(Config1, RTL8139State),
3217
        VMSTATE_UINT8(Config3, RTL8139State),
3218
        VMSTATE_UINT8(Config4, RTL8139State),
3219
        VMSTATE_UINT8(Config5, RTL8139State),
3220

    
3221
        VMSTATE_UINT8(clock_enabled, RTL8139State),
3222
        VMSTATE_UINT8(bChipCmdState, RTL8139State),
3223

    
3224
        VMSTATE_UINT16(MultiIntr, RTL8139State),
3225

    
3226
        VMSTATE_UINT16(BasicModeCtrl, RTL8139State),
3227
        VMSTATE_UINT16(BasicModeStatus, RTL8139State),
3228
        VMSTATE_UINT16(NWayAdvert, RTL8139State),
3229
        VMSTATE_UINT16(NWayLPAR, RTL8139State),
3230
        VMSTATE_UINT16(NWayExpansion, RTL8139State),
3231

    
3232
        VMSTATE_UINT16(CpCmd, RTL8139State),
3233
        VMSTATE_UINT8(TxThresh, RTL8139State),
3234

    
3235
        VMSTATE_UNUSED(4),
3236
        VMSTATE_MACADDR(conf.macaddr, RTL8139State),
3237
        VMSTATE_INT32(rtl8139_mmio_io_addr, RTL8139State),
3238

    
3239
        VMSTATE_UINT32(currTxDesc, RTL8139State),
3240
        VMSTATE_UINT32(currCPlusRxDesc, RTL8139State),
3241
        VMSTATE_UINT32(currCPlusTxDesc, RTL8139State),
3242
        VMSTATE_UINT32(RxRingAddrLO, RTL8139State),
3243
        VMSTATE_UINT32(RxRingAddrHI, RTL8139State),
3244

    
3245
        VMSTATE_UINT16_ARRAY(eeprom.contents, RTL8139State, EEPROM_9346_SIZE),
3246
        VMSTATE_INT32(eeprom.mode, RTL8139State),
3247
        VMSTATE_UINT32(eeprom.tick, RTL8139State),
3248
        VMSTATE_UINT8(eeprom.address, RTL8139State),
3249
        VMSTATE_UINT16(eeprom.input, RTL8139State),
3250
        VMSTATE_UINT16(eeprom.output, RTL8139State),
3251

    
3252
        VMSTATE_UINT8(eeprom.eecs, RTL8139State),
3253
        VMSTATE_UINT8(eeprom.eesk, RTL8139State),
3254
        VMSTATE_UINT8(eeprom.eedi, RTL8139State),
3255
        VMSTATE_UINT8(eeprom.eedo, RTL8139State),
3256

    
3257
        VMSTATE_UINT32(TCTR, RTL8139State),
3258
        VMSTATE_UINT32(TimerInt, RTL8139State),
3259
        VMSTATE_INT64(TCTR_base, RTL8139State),
3260

    
3261
        VMSTATE_STRUCT(tally_counters, RTL8139State, 0,
3262
                       vmstate_tally_counters, RTL8139TallyCounters),
3263

    
3264
        VMSTATE_UINT32_V(cplus_enabled, RTL8139State, 4),
3265
        VMSTATE_END_OF_LIST()
3266
    }
3267
};
3268

    
3269
/***********************************************************/
3270
/* PCI RTL8139 definitions */
3271

    
3272
static void rtl8139_mmio_map(PCIDevice *pci_dev, int region_num,
3273
                       pcibus_t addr, pcibus_t size, int type)
3274
{
3275
    RTL8139State *s = DO_UPCAST(RTL8139State, dev, pci_dev);
3276

    
3277
    cpu_register_physical_memory(addr + 0, 0x100, s->rtl8139_mmio_io_addr);
3278
}
3279

    
3280
static void rtl8139_ioport_map(PCIDevice *pci_dev, int region_num,
3281
                       pcibus_t addr, pcibus_t size, int type)
3282
{
3283
    RTL8139State *s = DO_UPCAST(RTL8139State, dev, pci_dev);
3284

    
3285
    register_ioport_write(addr, 0x100, 1, rtl8139_ioport_writeb, s);
3286
    register_ioport_read( addr, 0x100, 1, rtl8139_ioport_readb,  s);
3287

    
3288
    register_ioport_write(addr, 0x100, 2, rtl8139_ioport_writew, s);
3289
    register_ioport_read( addr, 0x100, 2, rtl8139_ioport_readw,  s);
3290

    
3291
    register_ioport_write(addr, 0x100, 4, rtl8139_ioport_writel, s);
3292
    register_ioport_read( addr, 0x100, 4, rtl8139_ioport_readl,  s);
3293
}
3294

    
3295
static CPUReadMemoryFunc * const rtl8139_mmio_read[3] = {
3296
    rtl8139_mmio_readb,
3297
    rtl8139_mmio_readw,
3298
    rtl8139_mmio_readl,
3299
};
3300

    
3301
static CPUWriteMemoryFunc * const rtl8139_mmio_write[3] = {
3302
    rtl8139_mmio_writeb,
3303
    rtl8139_mmio_writew,
3304
    rtl8139_mmio_writel,
3305
};
3306

    
3307
static void rtl8139_timer(void *opaque)
3308
{
3309
    RTL8139State *s = opaque;
3310

    
3311
    if (!s->clock_enabled)
3312
    {
3313
        DEBUG_PRINT(("RTL8139: >>> timer: clock is not running\n"));
3314
        return;
3315
    }
3316

    
3317
    s->IntrStatus |= PCSTimeout;
3318
    rtl8139_update_irq(s);
3319
    rtl8139_set_next_tctr_time(s, qemu_get_clock(vm_clock));
3320
}
3321

    
3322
static void rtl8139_cleanup(VLANClientState *nc)
3323
{
3324
    RTL8139State *s = DO_UPCAST(NICState, nc, nc)->opaque;
3325

    
3326
    s->nic = NULL;
3327
}
3328

    
3329
static int pci_rtl8139_uninit(PCIDevice *dev)
3330
{
3331
    RTL8139State *s = DO_UPCAST(RTL8139State, dev, dev);
3332

    
3333
    cpu_unregister_io_memory(s->rtl8139_mmio_io_addr);
3334
    if (s->cplus_txbuffer) {
3335
        qemu_free(s->cplus_txbuffer);
3336
        s->cplus_txbuffer = NULL;
3337
    }
3338
    qemu_del_timer(s->timer);
3339
    qemu_free_timer(s->timer);
3340
    qemu_del_vlan_client(&s->nic->nc);
3341
    return 0;
3342
}
3343

    
3344
static NetClientInfo net_rtl8139_info = {
3345
    .type = NET_CLIENT_TYPE_NIC,
3346
    .size = sizeof(NICState),
3347
    .can_receive = rtl8139_can_receive,
3348
    .receive = rtl8139_receive,
3349
    .cleanup = rtl8139_cleanup,
3350
};
3351

    
3352
static int pci_rtl8139_init(PCIDevice *dev)
3353
{
3354
    RTL8139State * s = DO_UPCAST(RTL8139State, dev, dev);
3355
    uint8_t *pci_conf;
3356

    
3357
    pci_conf = s->dev.config;
3358
    pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_REALTEK);
3359
    pci_config_set_device_id(pci_conf, PCI_DEVICE_ID_REALTEK_8139);
3360
    pci_conf[PCI_REVISION_ID] = RTL8139_PCI_REVID; /* >=0x20 is for 8139C+ */
3361
    pci_config_set_class(pci_conf, PCI_CLASS_NETWORK_ETHERNET);
3362
    pci_conf[PCI_INTERRUPT_PIN] = 1;    /* interrupt pin 0 */
3363
    /* TODO: start of capability list, but no capability
3364
     * list bit in status register, and offset 0xdc seems unused. */
3365
    pci_conf[PCI_CAPABILITY_LIST] = 0xdc;
3366

    
3367
    /* I/O handler for memory-mapped I/O */
3368
    s->rtl8139_mmio_io_addr =
3369
        cpu_register_io_memory(rtl8139_mmio_read, rtl8139_mmio_write, s,
3370
                               DEVICE_NATIVE_ENDIAN);
3371

    
3372
    pci_register_bar(&s->dev, 0, 0x100,
3373
                           PCI_BASE_ADDRESS_SPACE_IO,  rtl8139_ioport_map);
3374

    
3375
    pci_register_bar(&s->dev, 1, 0x100,
3376
                           PCI_BASE_ADDRESS_SPACE_MEMORY, rtl8139_mmio_map);
3377

    
3378
    qemu_macaddr_default_if_unset(&s->conf.macaddr);
3379

    
3380
    s->nic = qemu_new_nic(&net_rtl8139_info, &s->conf,
3381
                          dev->qdev.info->name, dev->qdev.id, s);
3382
    qemu_format_nic_info_str(&s->nic->nc, s->conf.macaddr.a);
3383

    
3384
    s->cplus_txbuffer = NULL;
3385
    s->cplus_txbuffer_len = 0;
3386
    s->cplus_txbuffer_offset = 0;
3387

    
3388
    s->TimerExpire = 0;
3389
    s->timer = qemu_new_timer(vm_clock, rtl8139_timer, s);
3390
    rtl8139_set_next_tctr_time(s, qemu_get_clock(vm_clock));
3391
    return 0;
3392
}
3393

    
3394
static PCIDeviceInfo rtl8139_info = {
3395
    .qdev.name  = "rtl8139",
3396
    .qdev.size  = sizeof(RTL8139State),
3397
    .qdev.reset = rtl8139_reset,
3398
    .qdev.vmsd  = &vmstate_rtl8139,
3399
    .init       = pci_rtl8139_init,
3400
    .exit       = pci_rtl8139_uninit,
3401
    .romfile    = "pxe-rtl8139.bin",
3402
    .qdev.props = (Property[]) {
3403
        DEFINE_NIC_PROPERTIES(RTL8139State, conf),
3404
        DEFINE_PROP_END_OF_LIST(),
3405
    }
3406
};
3407

    
3408
static void rtl8139_register_devices(void)
3409
{
3410
    pci_qdev_register(&rtl8139_info);
3411
}
3412

    
3413
device_init(rtl8139_register_devices)