Palacios Public Git Repository

To checkout Palacios execute

  git clone http://v3vee.org/palacios/palacios.web/palacios.git
This will give you the master branch. You probably want the devel branch or one of the release branches. To switch to the devel branch, simply execute
  cd palacios
  git checkout --track -b devel origin/devel
The other branches are similar.


Minor Fix for NE2000 and RTL8139 Compile error due to interface change
[palacios-OLD.git] / palacios / src / devices / rtl8139.c
1 /*
2  * This file is part of the Palacios Virtual Machine Monitor developed
3  * by the V3VEE Project with funding from the United States National 
4  * Science Foundation and the Department of Energy.  
5  *
6  * The V3VEE Project is a joint project between Northwestern University
7  * and the University of New Mexico.  You can find out more at 
8  * http://www.v3vee.org
9  *
10  * Copyright (c) 2011, Lei Xia <lxia@northwestern.edu> 
11  * Copyright (c) 2011, The V3VEE Project <http://www.v3vee.org> 
12  * All rights reserved.
13  *
14  * Author:  Lei Xia <lxia@northwestern.edu>
15  *
16  * This is free software.  You are permitted to use,
17  * redistribute, and modify it as specified in the file "V3VEE_LICENSE".
18  */
19
20 #include <devices/pci.h>
21 #include <palacios/vmm.h>
22 #include <palacios/vmm_types.h>
23 #include <palacios/vmm_io.h>
24 #include <palacios/vmm_debug.h>
25 #include <palacios/vm_guest_mem.h>
26 #include <palacios/vmm_ethernet.h>
27 #include <palacios/vmm_sprintf.h>
28
29
30
31 #ifndef V3_CONFIG_DEBUG_RTL8139
32 #undef PrintDebug
33 #define PrintDebug(fmts, args...)
34 #endif
35
36 #define RTL8139_IDR0    (0x00)  /* ID Registers start, len 6*1bytes */
37 #define RTL8139_MAR0    (0x08)  /* Mulicast Registers start, len 8*1bytes */
38
39 #define RTL8139_TSD0    (0x10)  /* Tx Status of Descriptors */
40 #define RTL8139_TSD1    (0x14)
41 #define RTL8139_TSD2    (0x18)
42 #define RTL8139_TSD3    (0x1c)
43
44 #define RTL8139_TSAD0   (0x20)  /* Tx Start Address of Descriptors */
45 #define RTL8139_TSAD1   (0x24)
46 #define RTL8139_TSAD2   (0x28)
47 #define RTL8139_TSAD3   (0x2c)
48
49 #define RTL8139_RBSTART (0x30)  /* Rx Buffer Start Address */
50 #define RTL8139_ERBCR   (0x34)  /* Early Rx Byte Count Register */
51 #define RTL8139_ERSR    (0x36)  /* Early Rx Status Register */
52 #define RTL8139_CR      (0x37)  /* Command Register */
53 #define RTL8139_CAPR    (0x38)  /* Current Address of Pkt Read */
54 #define RTL8139_CBR     (0x3a)  /* Current Buffer Address */
55 #define RTL8139_IMR     (0x3c)  /* Intrpt Mask Reg */
56 #define RTL8139_ISR     (0x3e)  /* Intrpt Status Reg */
57 #define RTL8139_TCR     (0x40)  /* Tx Config Reg */
58 #define RTL8139_RCR     (0x44)  /* Rx Config Reg */
59 #define RTL8139_TCTR    (0x48)  /* Timer Count Reg */
60 #define RTL8139_MPC     (0x4c)  /* Missed Pkt Counter */
61 #define RTL8139_9346CR  (0x50)  /* 9346 Command Reg */
62 #define RTL8139_CONFIG0 (0x51)  /* Config Reg */
63 #define RTL8139_CONFIG1 (0x52)
64 #define RTL8139_TimerInt    (0x54)      /* Timer Intrpt Reg */
65 #define RTL8139_MSR     (0x58)  /* Media Status Reg */
66 #define RTL8139_CONFIG3 (0x59)  
67 #define RTL8139_CONFIG4 (0x5a)
68 #define RTL8139_MULINT  (0x5c)  /* Multiple Intrpt Select */
69 #define RTL8139_RERID   (0x5e)  
70 #define RTL8139_TXSAD    (0x60) /* Tx Status of All Descriptors */
71 #define RTL8139_BMCR    (0x62)  /* Basic Mode Control Register */
72 #define RTL8139_BMSR    (0x64)  /* Basic Mode Status Register */
73 #define RTL8139_ANAR    (0x66)  /* Auto-Negotiation Advertisement Register */
74 #define RTL8139_ANLPAR  (0x68)  /* Auto-Negotiation Link Partner Register */
75 #define RTL8139_ANER    (0x6a)  /* Auto-Negotiation Expansion Register */
76 #define RTL8139_DIS     (0x6c)  /* Disconnect Counter */
77 #define RTL8139_FCSC    (0x6e)  /* False Carrier Sense Counter */
78 #define RTL8139_NWAYTR  (0x70)  /* N-way Test Register */
79 #define RTL8139_REC     (0x72)  /* RX ER Counter */
80 #define RTL8139_CSCR    (0x74)  /* CS Config Register */
81 #define RTL8139_PHY1_PARM   (0x78)      /* PHY parameter */
82 #define RTL8139_TW_PARM (0x7c)  /* Twister parameter */
83 #define RTL8139_PHY2_PARM   (0x80)
84
85 #define RTL8139_CRC0    (0x84)  /* Power Management CRC Reg for wakeup frame 8*1bytes */
86
87 #define RTL8139_Wakeup0 (0x8c)  /* Power Management wakeup frame */
88 #define RTL8139_Wakeup1 (0x94)
89 #define RTL8139_Wakeup2 (0x9c)
90 #define RTL8139_Wakeup3 (0xa4)
91 #define RTL8139_Wakeup4 (0xac)
92 #define RTL8139_Wakeup5 (0xb4)
93 #define RTL8139_Wakeup6 (0xbc)
94 #define RTL8139_Wakeup7 (0xc4)
95
96 #define RTL8139_LSBCRO0 (0xcc)  /* LSB of the mask byte of wakeup frame */
97 #define RTL8139_LSBCRO1 (0xcd)
98 #define RTL8139_LSBCRO2 (0xce)
99 #define RTL8139_LSBCRO3 (0xcf)
100 #define RTL8139_LSBCRO4 (0xd0)
101 #define RTL8139_LSBCRO5 (0xd1)
102 #define RTL8139_LSBCRO6 (0xd2)
103 #define RTL8139_LSBCRO7 (0xd3)
104
105 #define RTL8139_Config5 (0xd8)
106
107 /* Interrupts */
108 #define PKT_RX      0x0001
109 #define RX_ERR      0x0002
110 #define TX_OK       0x0004
111 #define TX_ERR      0x0008
112 #define RX_BUFF_OF  0x0010
113 #define RX_UNDERRUN 0x0020
114 #define RX_FIFO_OF  0x0040
115 #define CABLE_LEN_CHNG  0x2000
116 #define TIME_OUT    0x4000
117 #define SERR        0x8000
118
119 #define DESC_SIZE 2048
120 #define TX_FIFO_SIZE (DESC_SIZE * 4)
121 #define RX_FIFO_SIZE (DESC_SIZE * 4)
122
123 typedef enum {NIC_READY, NIC_REG_POSTED} nic_state_t;
124
125 enum TxStatusBits {
126     TSD_Own = 1<<13,
127     TSD_Tun = 1<<14,
128     TSD_Tok = 1<<15,
129     TSD_Cdh = 1<<28,
130     TSD_Owc = 1<<29,
131     TSD_Tabt = 1<<30,
132     TSD_Crs = 1<<31,
133 };
134
135 /* Transmit Status Register (TSD0-3) Offset: 0x10-0x1F */
136 struct tx_status_reg {
137     union {
138         uint16_t val;
139         struct {
140             uint16_t size     : 13;
141             uint8_t own     : 1;
142             uint8_t tun     : 1;
143             uint8_t tok     : 1;        
144             uint8_t er_tx_th   : 6;
145             uint8_t reserved    : 2;
146             uint8_t ncc            : 4;
147             uint8_t cdh : 1;
148             uint8_t owc : 1;
149             uint8_t tabt        : 1;
150             uint8_t crs : 1;
151         } __attribute__((packed));
152     } __attribute__((packed));
153 } __attribute__((packed));
154
155
156 enum RxStatusBits {
157     Rx_Multicast = 1<<15,
158     Rx_Physical = 1<<14,
159     Rx_Broadcast = 1<<13,
160     Rx_BadSymbol = 1<<5,
161     Rx_Runt = 1<<4,
162     Rx_TooLong = 1<<3,
163     Rx_CRCErr = 1<<2,
164     Rx_BadAlign = 1<<1,
165     Rx_OK = 1<<0,
166 };
167
168
169 /* Receive Status Register in RX Packet Header */
170 struct rx_status_reg {
171     union {
172         uint16_t val;
173         struct {
174             uint8_t rx_ok     : 1;
175             uint8_t rx_bad_align     : 1;
176             uint8_t rx_crc_err     : 1;
177             uint8_t rx_too_long     : 1;        
178             uint8_t rx_runt     : 1;
179             uint8_t rx_bad_sym  : 1;
180             uint8_t reserved    : 7;
181             uint8_t rx_brdcast  : 1;
182             uint8_t rx_phys     : 1;
183             uint8_t rx_multi    : 1;
184         } __attribute__((packed));
185     } __attribute__((packed));
186 } __attribute__((packed));
187
188
189 /* ERSR - Early Rx Status Register Offset: 0x36*/
190 struct errx_status_reg{
191     union {
192         uint8_t val;
193         struct {
194             uint8_t er_rx_ok     : 1;
195             uint8_t er_rx_ovw     : 1;
196             uint8_t er_rx_bad_pkt     : 1;
197             uint8_t er_rx_good     : 1; 
198             uint8_t reserved    : 4;
199         } __attribute__((packed));
200     } __attribute__((packed));
201 } __attribute__((packed));
202
203
204 /* Transmit Status of All Descriptors (TSAD) Register */
205 enum TSAD_bits {
206     TSAD_TOK3 = 1<<15, /* TOK bits of Descriptors*/
207     TSAD_TOK2 = 1<<14, 
208     TSAD_TOK1 = 1<<13, 
209     TSAD_TOK0 = 1<<12, 
210     TSAD_TUN3 = 1<<11, /* TUN bits of Descriptors */
211     TSAD_TUN2 = 1<<10, 
212     TSAD_TUN1 = 1<<9, 
213     TSAD_TUN0 = 1<<8,
214     TSAD_TABT3 = 1<<7, /* TABT bits of Descriptors */
215     TSAD_TABT2 = 1<<6,
216     TSAD_TABT1 = 1<<5,
217     TSAD_TABT0 = 1<<4,
218     TSAD_OWN3 = 1<<3, /* OWN bits of Descriptors */
219     TSAD_OWN2 = 1<<2,
220     TSAD_OWN1 = 1<<1, 
221     TSAD_OWN0 = 1<<0,
222 };
223
224
225 /* Transmit Status of All Descriptors (TSAD) Register Offset: 0x60-0x61*/
226 struct txsad_reg {
227     union {
228         uint16_t val;
229         struct {
230             uint8_t own0     : 1;
231             uint8_t own1     : 1;
232             uint8_t own2     : 1;
233             uint8_t own3     : 1;       
234             uint8_t tabt0       : 1;
235             uint8_t tabt1       : 1;
236             uint8_t tabt2       : 1;
237             uint8_t tabt3       : 1;
238             uint8_t tun0        : 1;
239             uint8_t tun1        : 1;
240             uint8_t tun2        : 1;
241             uint8_t tun3        : 1;
242             uint8_t tok0        : 1;
243             uint8_t tok1        : 1;
244             uint8_t tok2        : 1;
245             uint8_t tok3        : 1;
246         } __attribute__((packed));
247     } __attribute__((packed));
248 } __attribute__((packed));
249
250
251
252 enum ISRBits {
253     ISR_Rok = 1<<0,
254     ISR_Rer = 1<<1,
255     ISR_Tok = 1<<2,
256     ISR_Ter = 1<<3,
257     ISR_Rxovw = 1<<4,
258     ISR_Pun = 1<<5,
259     ISR_Fovw = 1<<6,
260     ISR_Lenchg = 1<<13,
261     ISR_Timeout = 1<<14,
262     ISR_Serr = 1<<15,
263 };
264
265 /* 
266  * Interrupt Status Register (ISR) Offset: ox3e-0x3f
267  * Interrupt Mask Register (IMR 0x3c-0x3d) shares the same structure
268  */
269 struct isr_imr_reg {
270     union {
271         uint16_t val;
272         struct {
273             uint8_t rx_ok       :1;
274             uint8_t rx_err     : 1;
275             uint8_t tx_ok        : 1;
276             uint8_t tx_err          : 1;
277             uint8_t rx_ovw          : 1;
278             uint8_t pun_linkchg          : 1;
279             uint8_t rx_fifo_ovw  : 1;
280             uint8_t reservd:     6;
281             uint8_t lenchg  :1;
282             uint8_t timeout   :1;
283             uint8_t syserr  :1;
284         } __attribute__((packed));
285     } __attribute__((packed));
286 } __attribute__((packed));
287
288 enum CMDBits {
289     CMD_Bufe = 1<<0,
290     CMD_Te = 1<<2,
291     CMD_Re = 1<<3,
292     CMD_Rst = 1<<4,
293 };
294
295
296 /* Commmand Register Offset: 0x37 */
297 struct cmd_reg {
298     union {
299         uint8_t val;
300         struct {
301             uint8_t cmd_bufe      : 1;
302             uint8_t reservd_1        : 1;
303             uint8_t cmd_te          : 1;
304             uint8_t cmd_re          : 1;
305             uint8_t cmd_rst          : 1;
306             uint8_t reservd_2  : 3;
307         } __attribute__((packed));
308     } __attribute__((packed));
309 } __attribute__((packed));
310
311
312
313
314 enum CMD9346Bits {
315     CMD9346_Lock = 0x00,
316     CMD9346_Unlock = 0xC0,
317 };
318
319
320
321 /* 93C46 Commmand Register Offset: 0x50 */
322 struct cmd9346_reg {
323     union {
324         uint8_t val;
325         struct {
326             uint8_t eedo      : 1;
327             uint8_t eedi        : 1;
328             uint8_t eesk          : 1;
329             uint8_t eecs          : 1;
330             uint8_t reserved    : 2;
331             uint8_t eem  : 2;
332         } __attribute__((packed));
333     } __attribute__((packed));
334 } __attribute__((packed));
335
336
337
338 // Bits in TxConfig.
339 enum TXConfig_bits{
340
341         /* Interframe Gap Time. Only TxIFG96 doesn't violate IEEE 802.3 */
342     TxIFGShift = 24,
343     TxIFG84 = (0 << TxIFGShift),    /* 8.4us / 840ns (10 / 100Mbps) */
344     TxIFG88 = (1 << TxIFGShift),    /* 8.8us / 880ns (10 / 100Mbps) */
345     TxIFG92 = (2 << TxIFGShift),    /* 9.2us / 920ns (10 / 100Mbps) */
346     TxIFG96 = (3 << TxIFGShift),    /* 9.6us / 960ns (10 / 100Mbps) */
347
348     TxLoopBack = (1 << 18) | (1 << 17), /* enable loopback test mode */
349     TxCRC = (1 << 16),  /* DISABLE appending CRC to end of Tx packets */
350     TxClearAbt = (1 << 0),      /* Clear abort (WO) */
351     TxDMAShift = 8,             /* DMA burst value (0-7) is shifted this many bits */
352     TxRetryShift = 4,   /* TXRR value (0-15) is shifted this many bits */
353
354     TxVersionMask = 0x7C800000, /* mask out version bits 30-26, 23 */
355 };
356
357
358 /* Transmit Configuration Register (TCR) Offset: 0x40-0x43 */
359 struct tx_config_reg {
360     union {
361         uint32_t val;
362         struct {
363             uint8_t clr_abort   :1;
364             uint8_t reserved_1     : 3;
365             uint8_t tx_retry_cnt        : 4;
366             uint8_t max_dma          : 3;
367             uint8_t reserved_2          : 5;
368             uint8_t tx_crc          : 1;
369             uint8_t loop_test  : 2;
370             uint8_t reservd_3:     3;
371             uint8_t hw_verid_b  :2;
372             uint8_t ifg   :2;
373             uint8_t hw_verid_a  :5;
374             uint8_t reservd_4  :1;
375         } __attribute__((packed));
376     } __attribute__((packed));
377 } __attribute__((packed));
378
379
380
381
382 enum CSCRBits {
383     CSCR_Testfun = 1<<15, /* 1 = Auto-neg speeds up internal timer, WO, def 0 */
384     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*/
385     CSCR_HEART_BIT = 1<<8,  /* 1 = HEART BEAT enable, 0 = HEART BEAT disable. HEART BEAT function is only valid in 10Mbps mode. def 1*/
386     CSCR_JBEN = 1<<7,  /* 1 = enable jabber function. 0 = disable jabber function, def 1*/
387     CSCR_F_LINK_100 = 1<<6, /* Used to login force good link in 100Mbps for diagnostic purposes. 1 = DISABLE, 0 = ENABLE. def 1*/
388     CSCR_F_Connect  = 1<<5,  /* Assertion of this bit forces the disconnect function to be bypassed. def 0*/
389     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*/
390     CSCR_Con_status_En = 1<<2, /* Assertion of this bit configures LED1 pin to indicate connection status. def 0*/
391     CSCR_PASS_SCR = 1<<0, /* Bypass Scramble, def 0*/
392 };
393
394
395 /* CS Configuration Register (CSCR) Offset: 0x74-0x75 */
396 struct cscr_reg {
397     union {
398         uint16_t val;
399         struct {
400             uint8_t pass_scr    :1;
401             uint8_t reserved_1     : 1;
402             uint8_t con_status_en        : 1;
403             uint8_t con_status          : 1;
404             uint8_t reserved_2          : 1;
405             uint8_t f_connect          : 1;
406             uint8_t f_link_100  : 1;
407             uint8_t jben:     1;
408             uint8_t heart_beat  :1;
409             uint8_t ld   :1;
410             uint8_t reservd_3  :5;
411             uint8_t test_fun  :1;
412         } __attribute__((packed));
413     } __attribute__((packed));
414 } __attribute__((packed));
415
416
417 /* Bits in RxConfig. */
418 enum rx_mode_bits {
419     AcceptErr = 0x20,
420     AcceptRunt = 0x10,
421     AcceptBroadcast = 0x08,
422     AcceptMulticast = 0x04,
423     AcceptMyPhys = 0x02,
424     AcceptAllPhys = 0x01,
425 };
426
427
428 /* Receive Configuration Register (RCR) Offset: 0x44-0x47 */
429 struct rx_config_reg {
430     union {
431         uint32_t val;
432         struct {
433             uint8_t all_phy   : 1;
434             uint8_t my_phy      : 1;
435             uint8_t all_multi     : 1;
436             uint8_t all_brdcast        : 1;
437             uint8_t acpt_runt          : 1;
438             uint8_t acpt_err          : 1;
439             uint8_t reserved_1          : 1;
440             uint8_t wrap  : 1;
441             uint8_t max_dma:     3;
442             uint8_t rx_buf_len  :2;
443             uint8_t rx_fifo_thresd   :3;
444             uint8_t rer8  :1;
445             uint8_t mul_er_intr  :1;
446             uint8_t reserved_2          : 6;
447             uint8_t eraly_rx_thresd   :4;
448             uint8_t reserved_3          : 4;
449         } __attribute__((packed));
450     } __attribute__((packed));
451 } __attribute__((packed));
452
453
454
455
456 #define RTL8139_PCI_REVID_8139      0x10
457
458 #define SET_MASKED(input, mask, curr) \
459     (((input) & ~(mask)) | ((curr) & (mask)))
460
461 /* arg % size for size which is a power of 2 */
462 #define MOD2(input, size) \
463     ((input) & (size - 1))
464
465
466 /* Size is 64 * 16bit words */
467 #define EEPROM_9346_ADDR_BITS 6
468 #define EEPROM_9346_SIZE  (1 << EEPROM_9346_ADDR_BITS)
469 #define EEPROM_9346_ADDR_MASK (EEPROM_9346_SIZE - 1)
470
471 enum Chip9346Operation
472 {
473     Chip9346_op_mask = 0xc0,          /* 10 zzzzzz */
474     Chip9346_op_read = 0x80,          /* 10 AAAAAA */
475     Chip9346_op_write = 0x40,         /* 01 AAAAAA D(15)..D(0) */
476     Chip9346_op_ext_mask = 0xf0,      /* 11 zzzzzz */
477     Chip9346_op_write_enable = 0x30,  /* 00 11zzzz */
478     Chip9346_op_write_all = 0x10,     /* 00 01zzzz */
479     Chip9346_op_write_disable = 0x00, /* 00 00zzzz */
480 };
481
482 enum Chip9346Mode {
483     Chip9346_none = 0,
484     Chip9346_enter_command_mode,
485     Chip9346_read_command,
486     Chip9346_data_read,      /* from output register */
487     Chip9346_data_write,     /* to input register, then to contents at specified address */
488     Chip9346_data_write_all, /* to input register, then filling contents */
489 };
490
491 struct EEprom9346 {
492     uint16_t contents[EEPROM_9346_SIZE];
493     int      mode;
494     uint32_t tick;
495     uint8_t  address;
496     uint16_t input;
497     uint16_t output;
498
499     uint8_t eecs;
500     uint8_t eesk;
501     uint8_t eedi;
502     uint8_t eedo;
503 };
504
505 struct rtl8139_regs {
506   union{
507         uint8_t mem[256];
508         
509         struct {
510             uint8_t id[6];
511             uint8_t reserved;
512             uint8_t mult[8];
513             uint32_t tsd[4];
514             uint32_t tsad[4];
515             uint32_t rbstart;
516             uint16_t erbcr;
517             uint8_t ersr;
518             uint8_t cmd;
519             uint16_t capr;
520             uint16_t cbr;
521             uint16_t imr;
522             uint16_t isr;
523             uint32_t tcr;
524             uint32_t rcr;
525             uint32_t tctr;
526             uint16_t mpc;
527             uint8_t cmd9346;
528             uint8_t config[2];
529             uint32_t timer_int;
530             uint8_t msr;
531             uint8_t config3[2];
532             uint16_t mulint;
533             uint16_t rerid;
534             uint16_t txsad;
535             uint16_t bmcr;
536             uint16_t bmsr;
537             uint16_t anar;
538             uint16_t anlpar;
539             uint16_t aner;
540             uint16_t dis;
541             uint16_t fcsc;
542             uint16_t nwaytr;
543             uint16_t rec;
544             uint32_t cscr;
545             uint32_t phy1_parm;
546             uint16_t tw_parm;
547             uint32_t  phy2_parm;
548             uint8_t crc[8];
549             uint32_t wakeup[16];
550             uint8_t isbcr[8];
551             uint8_t config5;
552         }__attribute__((packed));
553    }__attribute__((packed));
554 };
555
556
557
558 struct rtl8139_state {  
559     nic_state_t dev_state;
560
561     struct v3_vm_info * vm;
562     struct pci_device * pci_dev;
563     struct vm_device * pci_bus;
564     struct vm_device * dev;
565
566     struct nic_statistics statistic;
567
568     struct rtl8139_regs regs;
569     struct EEprom9346 eeprom; 
570
571     uint8_t tx_fifo[TX_FIFO_SIZE];
572     uint8_t rx_fifo[RX_FIFO_SIZE];
573     uint32_t rx_bufsize;
574
575     uint8_t mac[ETH_ALEN];
576
577     struct v3_dev_net_ops *net_ops;
578     void * backend_data;
579 };
580
581 static inline void rtl8139_update_irq(struct rtl8139_state * nic_state) {
582     int isr = ((nic_state->regs.isr & nic_state->regs.imr) & 0xffff);
583
584     if(isr & 0xffff){
585         v3_pci_raise_irq(nic_state->pci_bus, 0, nic_state->pci_dev);
586     }
587 }
588
589 static void prom9346_decode_command(struct EEprom9346 * eeprom, uint8_t command) {
590     PrintDebug("RTL8139: eeprom command 0x%02x\n", command);
591
592     switch (command & Chip9346_op_mask) {
593         case Chip9346_op_read:
594         {
595             eeprom->address = command & EEPROM_9346_ADDR_MASK;
596             eeprom->output = eeprom->contents[eeprom->address];
597             eeprom->eedo = 0;
598             eeprom->tick = 0;
599             eeprom->mode = Chip9346_data_read;
600             PrintDebug("RTL8139: eeprom read from address 0x%02x data=0x%04x\n",
601                    eeprom->address, eeprom->output);
602         }
603         break;
604
605         case Chip9346_op_write:
606         {
607             eeprom->address = command & EEPROM_9346_ADDR_MASK;
608             eeprom->input = 0;
609             eeprom->tick = 0;
610             eeprom->mode = Chip9346_none; /* Chip9346_data_write */
611             PrintDebug("RTL8139: eeprom begin write to address 0x%02x\n",
612                    eeprom->address);
613         }
614         break;
615         default:
616             eeprom->mode = Chip9346_none;
617             switch (command & Chip9346_op_ext_mask) {
618                 case Chip9346_op_write_enable:
619                     PrintDebug("RTL8139: eeprom write enabled\n");
620                     break;
621                 case Chip9346_op_write_all:
622                     PrintDebug("RTL8139: eeprom begin write all\n");
623                     break;
624                 case Chip9346_op_write_disable:
625                     PrintDebug("RTL8139: eeprom write disabled\n");
626                     break;
627             }
628         break;
629     }
630 }
631
632 static void prom9346_shift_clock(struct EEprom9346 * eeprom) {
633     int bit = eeprom->eedi?1:0;
634
635     ++ eeprom->tick;
636
637     PrintDebug("eeprom: tick %d eedi=%d eedo=%d\n", eeprom->tick, eeprom->eedi, eeprom->eedo);
638
639     switch (eeprom->mode) {
640         case Chip9346_enter_command_mode:
641             if (bit) {
642                 eeprom->mode = Chip9346_read_command;
643                 eeprom->tick = 0;
644                 eeprom->input = 0;
645                 PrintDebug("eeprom: +++ synchronized, begin command read\n");
646             }
647             break;
648
649         case Chip9346_read_command:
650             eeprom->input = (eeprom->input << 1) | (bit & 1);
651             if (eeprom->tick == 8) {
652                 prom9346_decode_command(eeprom, eeprom->input & 0xff);
653             }
654             break;
655
656         case Chip9346_data_read:
657             eeprom->eedo = (eeprom->output & 0x8000)?1:0;
658             eeprom->output <<= 1;
659             if (eeprom->tick == 16){
660 #if 1
661         // the FreeBSD drivers (rl and re) don't explicitly toggle
662         // CS between reads (or does setting Cfg9346 to 0 count too?),
663         // so we need to enter wait-for-command state here
664                 eeprom->mode = Chip9346_enter_command_mode;
665                 eeprom->input = 0;
666                 eeprom->tick = 0;
667
668                 PrintDebug("eeprom: +++ end of read, awaiting next command\n");
669 #else
670         // original behaviour
671                 ++eeprom->address;
672                 eeprom->address &= EEPROM_9346_ADDR_MASK;
673                 eeprom->output = eeprom->contents[eeprom->address];
674                 eeprom->tick = 0;
675
676                 DEBUG_PRINT(("eeprom: +++ read next address 0x%02x data=0x%04x\n",
677                        eeprom->address, eeprom->output));
678 #endif
679             }
680             break;
681
682         case Chip9346_data_write:
683             eeprom->input = (eeprom->input << 1) | (bit & 1);
684             if (eeprom->tick == 16) {
685                 PrintDebug("RTL8139: eeprom write to address 0x%02x data=0x%04x\n",
686                        eeprom->address, eeprom->input);
687
688                 eeprom->contents[eeprom->address] = eeprom->input;
689                 eeprom->mode = Chip9346_none; /* waiting for next command after CS cycle */
690                 eeprom->tick = 0;
691                 eeprom->input = 0;
692             }
693             break;
694
695         case Chip9346_data_write_all:
696             eeprom->input = (eeprom->input << 1) | (bit & 1);
697             if (eeprom->tick == 16) {
698                 int i;
699                 for (i = 0; i < EEPROM_9346_SIZE; i++)
700                 {
701                     eeprom->contents[i] = eeprom->input;
702                 }
703                 PrintDebug("RTL8139: eeprom filled with data=0x%04x\n",
704                        eeprom->input);
705
706                 eeprom->mode = Chip9346_enter_command_mode;
707                 eeprom->tick = 0;
708                 eeprom->input = 0;
709             }
710             break;
711
712         default:
713             break;
714     }
715 }
716
717 static int prom9346_get_wire(struct rtl8139_state * nic_state) {
718     struct EEprom9346 *eeprom = &(nic_state->eeprom);
719
720     if (eeprom->eecs == 0)
721         return 0;
722
723     return eeprom->eedo;
724 }
725
726 static void prom9346_set_wire(struct rtl8139_state * nic_state, 
727                               int eecs, 
728                               int eesk, 
729                               int eedi) {
730     struct EEprom9346 *eeprom = &(nic_state->eeprom);
731     uint8_t old_eecs = eeprom->eecs;
732     uint8_t old_eesk = eeprom->eesk;
733
734     eeprom->eecs = eecs;
735     eeprom->eesk = eesk;
736     eeprom->eedi = eedi;
737
738     PrintDebug("eeprom: +++ wires CS=%d SK=%d DI=%d DO=%d\n",
739                  eeprom->eecs, eeprom->eesk, eeprom->eedi, eeprom->eedo);
740
741     if (old_eecs == 0 && eecs) {
742         /* Synchronize start */
743         eeprom->tick = 0;
744         eeprom->input = 0;
745         eeprom->output = 0;
746         eeprom->mode = Chip9346_enter_command_mode;
747
748         PrintDebug("=== eeprom: begin access, enter command mode\n");
749     }
750
751     if (eecs == 0) {
752         PrintDebug("=== eeprom: end access\n");
753         return;
754     }
755
756     if (!old_eesk && eesk) {
757         /* SK front rules */
758         prom9346_shift_clock(eeprom);
759     }
760 }
761
762
763 static inline void rtl8139_reset_rxbuf(struct rtl8139_state * nic_state, uint32_t bufsize) {
764     nic_state->rx_bufsize = bufsize;
765     nic_state->regs.capr = 0;
766     nic_state->regs.cbr = 0;
767 }
768
769
770 static void rtl8139_reset(struct rtl8139_state *nic_state) {
771     struct rtl8139_regs *regs = &(nic_state->regs);
772     int i;
773
774     PrintDebug("Rtl8139: Reset\n");
775
776     /* restore MAC address */
777     memcpy(regs->id, nic_state->mac, ETH_ALEN);
778     memset(regs->mult, 0xff, 8);
779
780     rtl8139_update_irq(nic_state);
781
782     // prepare eeprom
783     nic_state->eeprom.contents[0] = 0x8129;
784         
785     // PCI vendor and device ID
786     nic_state->eeprom.contents[1] = 0x10ec;
787     nic_state->eeprom.contents[2] = 0x8139;
788     //Mac address
789     nic_state->eeprom.contents[7] = nic_state->mac[0] | nic_state->mac[1] << 8;
790     nic_state->eeprom.contents[8] = nic_state->mac[2] | nic_state->mac[3] << 8;
791     nic_state->eeprom.contents[9] = nic_state->mac[4] | nic_state->mac[5] << 8;
792
793     for (i = 0; i < 4; ++i) {
794         regs->tsd[i] = TSD_Own;
795     }
796
797     rtl8139_reset_rxbuf(nic_state, 1024*8);
798
799     /* ACK the reset */
800     regs->tcr = 0;
801
802     regs->tcr |= ((0x1d << 26) | (0x1 << 22)); // RTL-8139D
803     regs->rerid = RTL8139_PCI_REVID_8139;
804
805     regs->cmd = CMD_Rst; //RxBufEmpty bit is calculated on read from ChipCmd 
806
807     regs->config[0] = 0x0 | (1 << 4); // No boot ROM 
808     regs->config[1] = 0xC; //IO mapped and MEM mapped registers available
809     //regs->config[1] = 0x4; //Only IO mapped registers available
810     regs->config3[0] = 0x1; // fast back-to-back compatible
811     regs->config3[1] = 0x0;
812     regs->config5 = 0x0;
813         
814     regs->cscr = CSCR_F_LINK_100 | CSCR_HEART_BIT | CSCR_LD;
815
816     //0x3100 : 100Mbps, full duplex, autonegotiation.  0x2100 : 100Mbps, full duplex
817     regs->bmcr = 0x1000; // autonegotiation
818
819     regs->bmsr  = 0x7809;
820     regs->bmsr |= 0x0020; // autonegotiation completed
821     regs->bmsr |= 0x0004; // link is up
822
823     regs->anar = 0x05e1;     // all modes, full duplex
824     regs->anlpar = 0x05e1;   // all modes, full duplex
825     regs->aner = 0x0001;     // autonegotiation supported
826
827     // reset timer and disable timer interrupt
828     regs->tctr = 0;
829     regs->timer_int = 0;
830 }
831
832
833
834 static void rtl8139_9346cr_write(struct rtl8139_state * nic_state, uint32_t val) {
835     val &= 0xff;
836
837     PrintDebug("RTL8139: 9346CR write val=0x%02x\n", val);
838
839     /* mask unwriteable bits */
840     val = SET_MASKED(val, 0x31, nic_state->regs.cmd9346);
841
842     uint32_t opmode = val & 0xc0;
843     uint32_t eeprom_val = val & 0xf;
844
845     if (opmode == 0x80) {
846         /* eeprom access */
847         int eecs = (eeprom_val & 0x08)?1:0;
848         int eesk = (eeprom_val & 0x04)?1:0;
849         int eedi = (eeprom_val & 0x02)?1:0;
850         prom9346_set_wire(nic_state, eecs, eesk, eedi);
851     } else if (opmode == 0x40) {
852         /* Reset.  */
853         val = 0;
854         rtl8139_reset(nic_state);
855     }
856
857     nic_state->regs.cmd9346 = val;
858 }
859
860 static uint32_t rtl8139_9346cr_read(struct rtl8139_state * nic_state) {
861     uint32_t ret = nic_state->regs.cmd9346;
862     uint32_t opmode = ret & 0xc0;
863
864     if (opmode == 0x80) {
865         /* eeprom access */
866         int eedo = prom9346_get_wire(nic_state);
867         if (eedo){
868             ret |=  0x01;
869         } else {
870             ret &= ~0x01;
871         }
872     }
873
874     PrintDebug("RTL8139: 9346CR read val=0x%02x\n", ret);
875
876     return ret;
877 }
878
879
880 static inline int rtl8139_receiver_enabled(struct rtl8139_state * nic_state) {
881     return nic_state->regs.cmd & CMD_Re;
882 }
883
884 static inline int rtl8139_rxwrap(struct rtl8139_state * nic_state) {
885     // wrapping enabled; assume 1.5k more buffer space if size < 64K
886     return (nic_state->regs.rcr & (1 << 7));
887 }
888
889 static void rtl8139_rxbuf_write(struct rtl8139_state * nic_state, 
890                                 const void * buf, 
891                                 int size) {
892     struct rtl8139_regs *regs = &(nic_state->regs);
893     int wrap;
894     addr_t guestpa, host_rxbuf;
895
896     guestpa = (addr_t)regs->rbstart;
897     v3_gpa_to_hva(&(nic_state->vm->cores[0]), guestpa, &host_rxbuf);   
898
899     //wrap to the front of rx buffer
900     if (regs->cbr + size > nic_state->rx_bufsize){
901         wrap = MOD2(regs->cbr + size, nic_state->rx_bufsize);
902
903         if (wrap && !(nic_state->rx_bufsize < 64*1024 && rtl8139_rxwrap(nic_state))){
904             PrintDebug("RTL8139: rx packet wrapped in buffer at %d\n", size-wrap);
905
906             if (size > wrap){
907                 memcpy((void *)(host_rxbuf + regs->cbr), buf, size-wrap);
908             }
909
910             // reset buffer pointer
911             regs->cbr = 0;
912
913             memcpy((void *)(host_rxbuf + regs->cbr), buf + (size-wrap), wrap);
914
915             regs->cbr = wrap;
916
917             return;
918         }
919     }
920
921     memcpy((void *)(host_rxbuf + regs->cbr), buf, size);
922
923     regs->cbr += size;
924 }
925
926 #define POLYNOMIAL 0x04c11db6
927
928 /* From FreeBSD */
929 static inline int compute_mcast_idx(const uint8_t *ep) {
930     uint32_t crc;
931     int carry, i, j;
932     uint8_t b;
933
934     crc = 0xffffffff;
935     for (i = 0; i < 6; i++) {
936         b = *ep++;
937         for (j = 0; j < 8; j++) {
938             carry = ((crc & 0x80000000L) ? 1 : 0) ^ (b & 0x01);
939             crc <<= 1;
940             b >>= 1;
941             if (carry){
942                 crc = ((crc ^ POLYNOMIAL) | carry);
943             }
944         }
945     }
946     return (crc >> 26);
947 }
948
949
950 static int rx_one_pkt(struct rtl8139_state * nic_state, 
951                       uint8_t * pkt, 
952                       uint32_t len){
953     struct rtl8139_regs *regs = &(nic_state->regs);
954     uint_t rxbufsize = nic_state->rx_bufsize;
955     uint32_t header, val;
956     uint8_t bcast_addr[6] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
957
958     if (regs->rcr & AcceptAllPhys) {
959         PrintDebug("RTL8139: packet received in promiscuous mode\n");
960     } else {
961         if (!memcmp(pkt,  bcast_addr, 6)) {
962             if (!(regs->rcr & AcceptBroadcast)){
963                 PrintDebug("RTL8139: broadcast packet rejected\n");
964                 return -1;
965             }
966             header |= Rx_Broadcast;
967             PrintDebug("RTL8139: broadcast packet received\n");
968         } else if (pkt[0] & 0x01) {
969             // multicast
970             if (!(regs->rcr & AcceptMulticast)){
971                 PrintDebug("RTL8139: multicast packet rejected\n");
972                 return -1;
973             }
974
975             int mcast_idx = compute_mcast_idx(pkt);
976
977             if (!(regs->mult[mcast_idx >> 3] & (1 << (mcast_idx & 7)))){
978                 PrintDebug("RTL8139: multicast address mismatch\n");
979                 return -1;
980             }
981             header |= Rx_Multicast;
982             PrintDebug("RTL8139: multicast packet received\n");
983         } else if (!compare_ethaddr(regs->id, pkt)){
984             if (!(regs->rcr & AcceptMyPhys)){
985                 PrintDebug("RTL8139: rejecting physical address matching packet\n");
986                 return -1;
987             }
988
989             header |= Rx_Physical;
990             PrintDebug("RTL8139: physical address matching packet received\n");
991         } else {
992             PrintDebug("RTL8139: unknown packet\n");
993             return -1;
994         }
995     }
996
997     if(1){
998         PrintDebug("RTL8139: in ring Rx mode\n");
999
1000         int avail = MOD2(rxbufsize + regs->capr - regs->cbr, rxbufsize);
1001
1002         if (avail != 0 && len + 8 >= avail){
1003             PrintError("rx overflow: rx buffer length %d head 0x%04x read 0x%04x === available 0x%04x need 0x%04x\n",
1004                    rxbufsize, regs->cbr, regs->capr, avail, len + 8);
1005
1006             regs->isr |= ISR_Rxovw;
1007             ++ regs->mpc;
1008             rtl8139_update_irq(nic_state);
1009             return -1;
1010         }
1011
1012         header |= Rx_OK;
1013         header |= ((len << 16) & 0xffff0000);
1014
1015         rtl8139_rxbuf_write(nic_state, (uint8_t *)&header, 4);
1016
1017         rtl8139_rxbuf_write(nic_state, pkt, len);
1018
1019         /* CRC checksum */
1020         val = v3_crc32(0, pkt, len);
1021
1022         rtl8139_rxbuf_write(nic_state, (uint8_t *)&val, 4);
1023
1024         // correct buffer write pointer 
1025         regs->cbr = MOD2((regs->cbr + 3) & ~0x3, rxbufsize);
1026
1027         PrintDebug("RTL8139: received: rx buffer length %d CBR: 0x%04x CAPR: 0x%04x\n",
1028                         rxbufsize, regs->cbr, regs->capr);
1029     }
1030
1031     regs->isr |= ISR_Rok;
1032
1033     nic_state->statistic.rx_pkts ++;
1034     nic_state->statistic.rx_bytes += len;
1035         
1036     rtl8139_update_irq(nic_state);   
1037
1038     return 0;
1039 }
1040
1041 static int rtl8139_rx(uint8_t * pkt, uint32_t len, void * private_data) {
1042     struct rtl8139_state *nic_state = (struct rtl8139_state *)private_data;
1043
1044     if (!rtl8139_receiver_enabled(nic_state)){
1045         PrintDebug("RTL8139: receiver disabled\n");
1046         nic_state->statistic.rx_dropped ++;
1047                 
1048         return 0;
1049     }
1050         
1051     if(rx_one_pkt(nic_state, pkt, len) >= 0){
1052         nic_state->statistic.rx_pkts ++;
1053         nic_state->statistic.rx_bytes += len;
1054     }else {
1055         nic_state->statistic.rx_dropped ++;
1056     }
1057
1058     return 0;
1059 }
1060
1061 static void rtl8139_rcr_write(struct rtl8139_state * nic_state, uint32_t val) {
1062     PrintDebug("RTL8139: RCR write val=0x%08x\n", val);
1063
1064     val = SET_MASKED(val, 0xf0fc0040, nic_state->regs.rcr);
1065     nic_state->regs.rcr = val;
1066
1067 #if 0
1068     uchar_t rblen = (regs->rcr >> 11) & 0x3;
1069     switch(rblen) {
1070         case 0x0:
1071             rxbufsize = 1024 * 8 + 16;
1072             break;
1073         case 0x1:
1074             rxbufsize = 1024 * 16 + 16;
1075             break;
1076         case 0x2:
1077             rxbufsize = 1024 * 32 + 16;
1078             break;
1079         default:
1080             rxbufsize = 1024 * 64 + 16;
1081             break;
1082     }
1083 #endif
1084
1085     // reset buffer size and read/write pointers
1086     rtl8139_reset_rxbuf(nic_state, 8192 << ((nic_state->regs.rcr >> 11) & 0x3));
1087
1088     PrintDebug("RTL8139: RCR write reset buffer size to %d\n", nic_state->rx_bufsize);
1089 }
1090
1091
1092 #if 0
1093
1094 static int rtl8139_config_writeable(struct vm_device *dev)
1095 {
1096     struct nic_context *nic_state = (struct nic_context *)(dev->private_data);
1097         
1098     if (nic_state->regs.cmd9346 & CMD9346_Unlock)
1099     {
1100         return 1;
1101     }
1102
1103     PrintDebug("RTL8139: Configuration registers are unwriteable\n");
1104
1105     return 0;
1106 }
1107
1108 #endif
1109
1110 static inline int transmitter_enabled(struct rtl8139_state * nic_state){
1111     return nic_state->regs.cmd & CMD_Te;
1112 }
1113
1114 static int rxbufempty(struct rtl8139_state * nic_state){
1115     struct rtl8139_regs *regs = &(nic_state->regs);
1116     int unread;
1117
1118     unread = MOD2(regs->cbr + nic_state->rx_bufsize - regs->capr, nic_state->rx_bufsize);
1119    
1120     if (unread != 0){
1121         PrintDebug("RTL8139: receiver buffer data available 0x%04x\n", unread);
1122         return 0;
1123     }
1124
1125     PrintDebug("RTL8139: receiver buffer is empty\n");
1126
1127     return 1;
1128 }
1129
1130 static void rtl8139_cmd_write(struct rtl8139_state * nic_state, uint32_t val){
1131     val &= 0xff;
1132
1133     PrintDebug("RTL8139: Cmd write val=0x%08x\n", val);
1134
1135     if (val & CMD_Rst){
1136         PrintDebug("RTL8139: Cmd reset\n");
1137         rtl8139_reset(nic_state);
1138     }
1139     if (val & CMD_Re){
1140         PrintDebug("RTL8139: Cmd enable receiver\n");
1141     }
1142     if (val & CMD_Te){
1143         PrintDebug("RTL8139: Cmd enable transmitter\n");
1144     }
1145
1146     val = SET_MASKED(val, 0xe3, nic_state->regs.cmd);
1147     val &= ~CMD_Rst;
1148
1149     nic_state->regs.cmd = val;
1150 }
1151
1152 static int tx_one_packet(struct rtl8139_state * nic_state, int descriptor){
1153     struct rtl8139_regs *regs = &(nic_state->regs);
1154     int txsize;
1155     uint8_t *pkt;
1156     addr_t pkt_gpa = 0, hostva = 0;
1157
1158     if (!transmitter_enabled(nic_state)){
1159         PrintError("RTL8139: fail to send from descriptor %d: transmitter disabled\n", descriptor);
1160         return 0;
1161     }
1162
1163     if (regs->tsd[descriptor] & TSD_Own){
1164         PrintError("RTL8139: fail to send from descriptor %d: owned by host\n", descriptor);
1165         return 0;
1166     }
1167
1168     txsize = regs->tsd[descriptor] & 0x1fff;
1169     pkt_gpa = (addr_t) regs->tsad[descriptor];
1170
1171     PrintDebug("RTL8139: sending %d bytes from guest memory at 0x%08x\n", txsize, regs->tsad[descriptor]);
1172         
1173     v3_gpa_to_hva(&(nic_state->vm->cores[0]), (addr_t)pkt_gpa, &hostva);
1174     pkt = (uchar_t *)hostva;
1175
1176 #ifdef V3_CONFIG_DEBUG_RTL8139
1177     v3_hexdump(pkt, txsize, NULL, 0);
1178 #endif
1179
1180     if (TxLoopBack == (regs->tcr & TxLoopBack)){ /* loopback test */
1181         PrintDebug(("RTL8139: transmit loopback mode\n"));
1182         rx_one_pkt(nic_state, pkt, txsize);
1183     } else{       
1184         if (nic_state->net_ops->send(pkt, txsize, nic_state->backend_data) == 0){
1185             PrintDebug("RTL8139: Sent %d bytes from descriptor %d\n", txsize, descriptor);
1186             nic_state->statistic.tx_pkts ++;
1187             nic_state->statistic.tx_bytes += txsize;
1188         } else {
1189             PrintError("Rtl8139: Sending packet error: 0x%p\n", pkt);
1190             nic_state->statistic.tx_dropped ++;
1191         }
1192     }
1193
1194     regs->tsd[descriptor] |= TSD_Tok;
1195     regs->tsd[descriptor] |= TSD_Own;
1196
1197     nic_state->regs.isr |= ISR_Tok;
1198     rtl8139_update_irq(nic_state);
1199
1200     return 0;
1201 }
1202
1203 /*transmit status registers*/
1204 static void rtl8139_tsd_write(struct rtl8139_state * nic_state, 
1205                               uint8_t descriptor, 
1206                               uint32_t val){ 
1207     if (!transmitter_enabled(nic_state)){
1208         PrintDebug("RTL8139: TxStatus write val=0x%08x descriptor=%d, Transmitter not enabled\n", val, descriptor);
1209                 
1210         return;
1211     }
1212
1213     PrintDebug("RTL8139: TSD write val=0x%08x descriptor=%d\n", val, descriptor);
1214
1215     // mask read-only bits
1216     val &= ~0xff00c000;
1217     val = SET_MASKED(val, 0x00c00000,  nic_state->regs.tsd[descriptor]);
1218
1219     nic_state->regs.tsd[descriptor] = val;
1220
1221     tx_one_packet(nic_state, descriptor);
1222 }
1223
1224 /* transmit status of all descriptors */
1225 static uint16_t rtl8139_txsad_read(struct rtl8139_state * nic_state){
1226     uint16_t ret = 0;
1227     struct rtl8139_regs *regs = &(nic_state->regs);
1228
1229     ret = ((regs->tsd[3] & TSD_Tok)?TSAD_TOK3:0)
1230          |((regs->tsd[2] & TSD_Tok)?TSAD_TOK2:0)
1231          |((regs->tsd[1] & TSD_Tok)?TSAD_TOK1:0)
1232          |((regs->tsd[0] & TSD_Tok)?TSAD_TOK0:0)
1233
1234          |((regs->tsd[3] & TSD_Tun)?TSAD_TUN3:0)
1235          |((regs->tsd[2] & TSD_Tun)?TSAD_TUN2:0)
1236          |((regs->tsd[1] & TSD_Tun)?TSAD_TUN1:0)
1237          |((regs->tsd[0] & TSD_Tun)?TSAD_TUN0:0)
1238
1239          |((regs->tsd[3] & TSD_Tabt)?TSAD_TABT3:0)
1240          |((regs->tsd[2] & TSD_Tabt)?TSAD_TABT2:0)
1241          |((regs->tsd[1] & TSD_Tabt)?TSAD_TABT1:0)
1242          |((regs->tsd[0] & TSD_Tabt)?TSAD_TABT0:0)
1243
1244          |((regs->tsd[3] & TSD_Own)?TSAD_OWN3:0)
1245          |((regs->tsd[2] & TSD_Own)?TSAD_OWN2:0)
1246          |((regs->tsd[1] & TSD_Own)?TSAD_OWN1:0)
1247          |((regs->tsd[0] & TSD_Own)?TSAD_OWN0:0) ;
1248
1249     PrintDebug("RTL8139: txsad read val=0x%04x\n", (int)ret);
1250
1251     return ret;
1252 }
1253
1254 static inline void rtl8139_isr_write(struct rtl8139_state * nic_state, uint32_t val) {
1255     struct rtl8139_regs *regs = &(nic_state->regs);
1256
1257     PrintDebug("RTL8139: ISR write val=0x%04x\n", val);
1258
1259     uint16_t newisr = regs->isr & ~val;
1260
1261     /* mask unwriteable bits */
1262     newisr = SET_MASKED(newisr, 0x1e00, regs->isr);
1263
1264     /* writing 1 to interrupt status register bit clears it */
1265     regs->isr = 0;
1266     rtl8139_update_irq(nic_state);
1267
1268     regs->isr = newisr;
1269     rtl8139_update_irq(nic_state);
1270 }
1271
1272 static int rtl8139_mmio_write(struct guest_info * core, 
1273                               addr_t guest_addr, 
1274                               void * src,
1275                               uint_t length, 
1276                               void * priv_data) {
1277     int idx;
1278     uint32_t val;
1279     struct rtl8139_state *nic_state = (struct rtl8139_state *)(priv_data);
1280
1281     idx = guest_addr & 0xff;
1282
1283     memcpy(&val, src, length);
1284
1285     PrintDebug("rtl8139 mmio write: addr:0x%x (%u bytes): 0x%x\n", (int)guest_addr, length, val);
1286         
1287     switch(idx) {
1288         case RTL8139_IDR0 ... RTL8139_IDR0 + 5:
1289             nic_state->regs.id[idx - RTL8139_IDR0] = val & 0xff;
1290             break;
1291
1292         case RTL8139_MAR0 ... RTL8139_MAR0 + 7:
1293             nic_state->regs.mult[idx - RTL8139_MAR0] = val & 0xff;
1294             break;
1295
1296         case RTL8139_TSD0:
1297         case RTL8139_TSD1:
1298         case RTL8139_TSD2:
1299         case RTL8139_TSD3:
1300             rtl8139_tsd_write(nic_state, (idx - RTL8139_TSD0)/4, val);
1301             break;
1302                 
1303         case RTL8139_TSAD0:
1304         case RTL8139_TSAD1:
1305         case RTL8139_TSAD2:
1306         case RTL8139_TSAD3:
1307             nic_state->regs.tsad[(idx - RTL8139_TSAD0)/4] = val;
1308             break;
1309                 
1310         case RTL8139_RBSTART:
1311             nic_state->regs.rbstart = val;
1312             break;
1313         case RTL8139_ERBCR:
1314             nic_state->regs.erbcr = val & 0xffff;
1315             break;
1316         case RTL8139_ERSR:
1317             //nic_state->regs.ersr = val & 0xff;
1318             nic_state->regs.ersr &= (~val) & 0x0c;
1319             break;
1320         case RTL8139_CR:
1321             rtl8139_cmd_write(nic_state, val);
1322             break;
1323         case RTL8139_CAPR:
1324         {
1325             val &= 0xffff;
1326             /* this value is off by 16 */
1327             nic_state->regs.capr = MOD2(val + 0x10, nic_state->rx_bufsize);
1328
1329             PrintDebug("RTL 8139: CAPR write: rx buffer length %d head 0x%04x read 0x%04x\n",
1330             nic_state->rx_bufsize, nic_state->regs.cbr, nic_state->regs.capr);  
1331         }
1332             break;
1333         case RTL8139_CBR: /* read only */
1334             //nic_state->regs.cbr = val & 0xffff;
1335             break;
1336         case RTL8139_IMR:
1337         {
1338             PrintDebug("RTL8139: IMR write val=0x%04x\n", val);
1339
1340             /* mask unwriteable bits */
1341             val = SET_MASKED(val, 0x1e00, nic_state->regs.imr);
1342             nic_state->regs.imr = val;
1343             rtl8139_update_irq(nic_state);
1344         }
1345             break;
1346         case RTL8139_ISR:
1347             rtl8139_isr_write(nic_state, val);
1348             break;
1349         case RTL8139_TCR:
1350             nic_state->regs.tcr = val;
1351             break;
1352         case RTL8139_RCR:
1353             rtl8139_rcr_write(nic_state, val);
1354             break;
1355         case RTL8139_TCTR:
1356             nic_state->regs.tctr = 0; /* write clear current tick */
1357             break;
1358         case RTL8139_MPC:
1359             nic_state->regs.mpc = 0; /* clear on write */
1360             break;
1361         case RTL8139_9346CR:
1362             rtl8139_9346cr_write(nic_state, val);
1363             break;
1364         case RTL8139_CONFIG0:
1365             nic_state->regs.config[0] = val & 0xff;
1366             break;
1367         case RTL8139_CONFIG1:
1368             nic_state->regs.config[1] = val & 0xff;
1369             break;
1370         case RTL8139_TimerInt:
1371             nic_state->regs.timer_int = val;
1372             break;
1373         case RTL8139_MSR:
1374             nic_state->regs.msr = val & 0xff;
1375             break;
1376         case RTL8139_CONFIG3:
1377             nic_state->regs.config3[0] = val & 0xff;
1378             break;
1379         case RTL8139_CONFIG4:
1380             nic_state->regs.config3[1] = val & 0xff;
1381             break;
1382                 
1383         case RTL8139_MULINT:
1384             nic_state->regs.mulint = val & 0xffff;
1385             break;
1386         case RTL8139_RERID:
1387             nic_state->regs.rerid = val & 0xffff;
1388             break;
1389         case RTL8139_TXSAD:
1390             nic_state->regs.txsad = val & 0xffff;
1391             break;
1392         case RTL8139_BMCR:
1393             nic_state->regs.bmcr = val & 0xffff;
1394             break;
1395         case RTL8139_BMSR:
1396             nic_state->regs.bmsr = val & 0xffff;
1397             break;
1398         case RTL8139_ANAR:
1399             nic_state->regs.anar = val & 0xffff;
1400             break;
1401         case RTL8139_ANLPAR:
1402             nic_state->regs.anlpar = val & 0xffff;
1403             break;
1404         case RTL8139_ANER:
1405             nic_state->regs.aner = val & 0xffff;
1406             break;
1407         case RTL8139_DIS:
1408             nic_state->regs.dis = val & 0xffff;
1409             break;
1410         case RTL8139_FCSC:
1411             nic_state->regs.fcsc = val & 0xffff;
1412             break;
1413         case RTL8139_NWAYTR:
1414             nic_state->regs.nwaytr = val & 0xffff;
1415             break;
1416         case RTL8139_REC:
1417             nic_state->regs.rec = val & 0xffff;
1418             break;
1419
1420         case RTL8139_CSCR:
1421             nic_state->regs.cscr = val;
1422             break;
1423         case RTL8139_PHY1_PARM:
1424             nic_state->regs.phy1_parm = val;
1425             break;
1426         case RTL8139_TW_PARM:
1427             nic_state->regs.tw_parm = val & 0xffff;
1428             break;
1429         case RTL8139_PHY2_PARM:
1430             nic_state->regs.phy2_parm = val;
1431             break;
1432         case RTL8139_CRC0 ... RTL8139_CRC0 + 7:
1433             nic_state->regs.crc[idx - RTL8139_CRC0] = val & 0xff;
1434             break;
1435
1436         case RTL8139_Config5:
1437             nic_state->regs.config5 = val & 0xff;
1438             break;
1439         default:
1440             PrintDebug("rtl8139 write error: invalid port: 0x%x\n", idx);
1441         }
1442         
1443     return length;
1444 }
1445
1446 static int rtl8139_mmio_read(struct guest_info * core, 
1447                              addr_t guest_addr, 
1448                              void * dst, 
1449                              uint_t length, 
1450                              void * priv_data) {
1451     uint16_t idx;
1452     uint32_t val;
1453     struct rtl8139_state *nic_state = (struct rtl8139_state *)priv_data;
1454
1455     idx = guest_addr & 0xff;
1456
1457     switch(idx) {
1458         case RTL8139_IDR0 ... RTL8139_IDR0 + 5:
1459             val = nic_state->regs.id[idx - RTL8139_IDR0];
1460             break;
1461                 
1462         case RTL8139_MAR0 ... RTL8139_MAR0 + 7:
1463             val = nic_state->regs.mult[idx - RTL8139_MAR0];
1464             break;
1465
1466         case RTL8139_TSD0:
1467         case RTL8139_TSD1:
1468         case RTL8139_TSD2:
1469         case RTL8139_TSD3:
1470             val = nic_state->regs.tsd[(idx - RTL8139_TSD0)/4];
1471             break;
1472
1473         case RTL8139_TSAD0:
1474         case RTL8139_TSAD1:
1475         case RTL8139_TSAD2:
1476         case RTL8139_TSAD3:
1477             val = nic_state->regs.tsad[(idx - RTL8139_TSAD0)/4];
1478             break;
1479
1480         case RTL8139_RBSTART:
1481             val = nic_state->regs.rbstart;
1482             break;
1483         case RTL8139_ERBCR:
1484             val = nic_state->regs.erbcr;
1485             break;
1486         case RTL8139_ERSR:
1487             val = nic_state->regs.ersr;
1488             break;
1489         case RTL8139_CR:
1490         {
1491             val = nic_state->regs.cmd;
1492             if (rxbufempty(nic_state)){
1493                 val |= CMD_Bufe;
1494             }
1495         }
1496             break;
1497         case RTL8139_CAPR:
1498             /* this value is off by 16 -- don't know why - Lei*/
1499             val = nic_state->regs.capr - 0x10;
1500             break;
1501         case RTL8139_CBR:
1502             val = nic_state->regs.cbr;
1503             break;
1504         case RTL8139_IMR:
1505             val = nic_state->regs.imr;
1506             break;
1507         case RTL8139_ISR:
1508             val = (uint32_t)nic_state->regs.isr;
1509             break;
1510         case RTL8139_TCR:
1511             val = nic_state->regs.tcr;
1512             break;
1513         case RTL8139_RCR:
1514             val = nic_state->regs.rcr;
1515             break;
1516         case RTL8139_TCTR:
1517             val = nic_state->regs.tctr;
1518             break;
1519         case RTL8139_MPC:
1520             val = nic_state->regs.mpc;
1521             break;
1522         case RTL8139_9346CR:
1523             val = rtl8139_9346cr_read(nic_state);
1524             break;
1525         case RTL8139_CONFIG0:
1526             val = nic_state->regs.config[0];
1527             break;
1528         case RTL8139_CONFIG1:
1529             val = nic_state->regs.config[1];
1530             break;
1531         case RTL8139_TimerInt:
1532             val = nic_state->regs.timer_int;
1533             break;
1534         case RTL8139_MSR:
1535             val = nic_state->regs.msr;
1536             break;
1537         case RTL8139_CONFIG3:
1538             val = nic_state->regs.config3[0];
1539             break;
1540         case RTL8139_CONFIG4:
1541             val = nic_state->regs.config3[1];
1542             break;
1543         case RTL8139_MULINT:
1544             val = nic_state->regs.mulint;
1545             break;
1546         case RTL8139_RERID:
1547             val = nic_state->regs.rerid;
1548             break;
1549         case RTL8139_TXSAD: 
1550             val = rtl8139_txsad_read(nic_state);
1551             break;
1552         case RTL8139_BMCR:
1553             val = nic_state->regs.bmcr;
1554             break;
1555         case RTL8139_BMSR:
1556             val = nic_state->regs.bmsr;
1557             break;
1558         case RTL8139_ANAR:
1559             val = nic_state->regs.anar;
1560             break;
1561         case RTL8139_ANLPAR:
1562             val = nic_state->regs.anlpar;
1563             break;
1564         case RTL8139_ANER:
1565             val = nic_state->regs.aner;
1566             break;
1567         case RTL8139_DIS:
1568             val = nic_state->regs.dis;
1569             break;
1570         case RTL8139_FCSC:
1571             val = nic_state->regs.fcsc;
1572             break;
1573         case RTL8139_NWAYTR:
1574             val = nic_state->regs.nwaytr;
1575             break;
1576         case RTL8139_REC:
1577             val = nic_state->regs.rec;
1578             break;
1579         case RTL8139_CSCR:
1580             val = nic_state->regs.cscr;
1581             break;
1582         case RTL8139_PHY1_PARM:
1583             val = nic_state->regs.phy1_parm;
1584             break;
1585         case RTL8139_TW_PARM:
1586             val = nic_state->regs.tw_parm;
1587             break;
1588         case RTL8139_PHY2_PARM:
1589             val = nic_state->regs.phy2_parm;
1590             break;
1591         case RTL8139_CRC0 ... RTL8139_CRC0 + 7:
1592             val = nic_state->regs.crc[idx - RTL8139_CRC0];
1593             break;
1594         case RTL8139_Config5:
1595             val = nic_state->regs.config5;
1596             break;
1597         default:
1598             val = 0x0;
1599             break;
1600     }
1601
1602     memcpy(dst, &val, length);
1603         
1604     PrintDebug("rtl8139 mmio read: port:0x%x (%u bytes): 0x%x\n", (int)guest_addr, length, val);
1605
1606     return length;
1607 }
1608
1609
1610 static int rtl8139_ioport_write(struct guest_info * core,
1611                                 uint16_t port, 
1612                                 void *src, 
1613                                 uint_t length, 
1614                                 void * private_data) {
1615     return rtl8139_mmio_write(core, (addr_t)port, 
1616                               src, length, private_data);
1617 }
1618
1619 static int rtl8139_ioport_read(struct guest_info * core, 
1620                                uint16_t port, 
1621                                void *dst, 
1622                                uint_t length, 
1623                                void * private_data) {
1624     return rtl8139_mmio_read(core, (addr_t)port, 
1625                              dst, length, private_data);
1626 }
1627
1628
1629 static int rtl8139_init_state(struct rtl8139_state *nic_state) {
1630     PrintDebug("rtl8139: init_state\n");
1631         
1632     nic_state->regs.tsd[0] = nic_state->regs.tsd[1] = nic_state->regs.tsd[2] = nic_state->regs.tsd[3] = TSD_Own;
1633
1634     nic_state->regs.rerid = RTL8139_PCI_REVID_8139;
1635     nic_state->regs.tcr |= ((0x1d << 26) | (0x1 << 22));
1636
1637     rtl8139_reset(nic_state);
1638
1639     return 0;
1640 }
1641
1642
1643 #if 0
1644 static inline int rtl8139_reset_device(struct rtl8139_state * nic_state) {
1645     nic_state->regs.cmd |= CMD_Rst;
1646     rtl8139_init_state(nic_state);
1647     nic_state->regs.cmd &= ~CMD_Rst;
1648         
1649     return 0;
1650 }
1651
1652 static inline int rtl8139_start_device(struct rtl8139_state * nic_state) {
1653     nic_state->regs.cmd |= CMD_Re | CMD_Te;
1654         
1655     return 0;
1656 }
1657
1658 static int rtl8139_stop_device(struct rtl8139_state * nic_state) {
1659     PrintDebug("rtl8139: stop device\n");
1660
1661     nic_state->regs.cmd &= ~(CMD_Re | CMD_Te);
1662         
1663     return 0;
1664 }
1665
1666 static int rtl8139_hook_iospace(struct rtl8139_state * nic_state, 
1667                                 addr_t base_addr, 
1668                                 int size, 
1669                                 int type, 
1670                                 void *data) {
1671     int i;
1672
1673     if (base_addr <= 0){
1674         PrintError("In RTL8139: Fail to Hook IO Space, base address 0x%x\n", (int) base_addr);
1675         return -1;
1676     }
1677
1678     if (type == PCI_BAR_IO){
1679         PrintDebug("In RTL8139: Hook IO ports starting from %x, size %d\n", (int) base_addr, size);
1680
1681         for (i = 0; i < 0xff; i++){     
1682             v3_dev_hook_io(nic_state->dev, base_addr + i, &rtl8139_ioport_read, &rtl8139_ioport_write);
1683         }
1684     } else if (type == PCI_BAR_MEM32) {
1685         PrintDebug("In RTL8139: Hook memory space starting from %x, size %d\n", (int) base_addr, size);
1686         
1687         //hook memory mapped I/O        
1688         v3_hook_full_mem(nic_state->vm, nic_state->vm->cores[0].cpu_id, base_addr, base_addr + 0xff,
1689                                      &rtl8139_mmio_read, &rtl8139_mmio_write, nic_state);
1690     } else {
1691        PrintError("In RTL8139: unknown memory type: start %x, size %d\n", (int) base_addr, size);
1692     }
1693         
1694     return 0;
1695 }
1696 #endif
1697
1698 static int register_dev(struct rtl8139_state * nic_state)  {
1699     int i;
1700
1701     if (nic_state->pci_bus == NULL) {
1702         PrintError("RTL8139: Not attached to any PCI bus\n");
1703
1704         return -1;
1705     }
1706
1707     struct v3_pci_bar bars[6];
1708     struct pci_device * pci_dev = NULL;
1709
1710     for (i = 0; i < 6; i++) {
1711         bars[i].type = PCI_BAR_NONE;
1712     }
1713
1714     bars[0].type = PCI_BAR_IO;
1715     bars[0].default_base_port = 0xc100;
1716     bars[0].num_ports = 0x100;
1717
1718     bars[0].io_read = rtl8139_ioport_read;
1719     bars[0].io_write = rtl8139_ioport_write;
1720     bars[0].private_data = nic_state;
1721
1722 /*
1723     bars[1].type = PCI_BAR_MEM32;
1724     bars[1].default_base_addr = -1;
1725     bars[1].num_pages = 1;
1726
1727     bars[1].mem_read = rtl8139_mmio_read;
1728     bars[1].mem_write = rtl8139_mmio_write;
1729     bars[1].private_data = nic_state;
1730 */
1731
1732     pci_dev = v3_pci_register_device(nic_state->pci_bus, PCI_STD_DEVICE, 0, -1, 0, 
1733                                          "RTL8139", bars,
1734                                          NULL, NULL, NULL, nic_state);
1735
1736
1737     if (pci_dev == NULL) {
1738         PrintError("RTL8139: Could not register PCI Device\n");
1739         return -1;
1740     }
1741         
1742     pci_dev->config_header.vendor_id = 0x10ec;
1743     pci_dev->config_header.device_id = 0x8139;
1744     pci_dev->config_header.command = 0x05;
1745         
1746     pci_dev->config_header.revision = RTL8139_PCI_REVID_8139;
1747
1748     pci_dev->config_header.subclass = 0x00;
1749     pci_dev->config_header.class = 0x02;
1750     pci_dev->config_header.header_type = 0x00;
1751
1752     pci_dev->config_header.intr_line = 12;
1753     pci_dev->config_header.intr_pin = 1;
1754     pci_dev->config_space[0x34] = 0xdc;
1755
1756     nic_state->pci_dev = pci_dev;
1757         
1758     return 0;
1759 }
1760
1761 static int connect_fn(struct v3_vm_info * info, 
1762                       void * frontend_data, 
1763                       struct v3_dev_net_ops * ops, 
1764                       v3_cfg_tree_t * cfg, 
1765                       void * private_data) {
1766     struct rtl8139_state * nic_state = (struct rtl8139_state *)frontend_data;
1767
1768     rtl8139_init_state(nic_state);
1769     register_dev(nic_state);
1770
1771     nic_state->net_ops = ops;
1772     nic_state->backend_data = private_data;     
1773
1774     ops->recv = rtl8139_rx;
1775     ops->poll = NULL;
1776     ops->config.frontend_data = nic_state;
1777     memcpy(ops->config.fnt_mac, nic_state->mac, ETH_ALEN);
1778
1779     return 0;
1780 }
1781
1782
1783 static int rtl8139_free(void * private_data) {
1784     struct rtl8139_state * nic_state = (struct rtl8139_state *)private_data;
1785
1786     /* dettached from backend */
1787
1788     /* unregistered from PCI? */
1789
1790     V3_Free(nic_state);
1791         
1792     return 0;
1793 }
1794
1795
1796 static struct v3_device_ops dev_ops = {
1797     .free = rtl8139_free,
1798 };
1799
1800
1801 static int rtl8139_init(struct v3_vm_info * vm, v3_cfg_tree_t * cfg) {
1802     struct vm_device * pci_bus = v3_find_dev(vm, v3_cfg_val(cfg, "bus"));
1803     struct rtl8139_state * nic_state = NULL;
1804     char * dev_id = v3_cfg_val(cfg, "ID");
1805     char * macstr = v3_cfg_val(cfg, "mac");
1806
1807     nic_state  = (struct rtl8139_state *)V3_Malloc(sizeof(struct rtl8139_state));
1808     memset(nic_state, 0, sizeof(struct rtl8139_state));
1809
1810     nic_state->pci_bus = pci_bus;
1811     nic_state->vm = vm;
1812
1813     if (macstr != NULL && !str2mac(macstr, nic_state->mac)) {
1814         PrintDebug("RTL8139: Mac specified %s\n", macstr);
1815     }else {
1816         PrintDebug("RTL8139: MAC not specified\n");
1817         random_ethaddr(nic_state->mac);
1818     }
1819
1820     struct vm_device * dev = v3_add_device(vm, dev_id, &dev_ops, nic_state);
1821
1822     if (dev == NULL) {
1823         PrintError("RTL8139: Could not attach device %s\n", dev_id);
1824         V3_Free(nic_state);
1825         return -1;
1826     }
1827
1828     nic_state->dev = dev;
1829
1830     if (v3_dev_add_net_frontend(vm, dev_id, connect_fn, (void *)nic_state) == -1) {
1831         PrintError("RTL8139: Could not register %s as net frontend\n", dev_id);
1832         v3_remove_device(dev);
1833         V3_Free(nic_state);
1834         return -1;
1835     }
1836             
1837     return 0;
1838 }
1839
1840 device_register("RTL8139", rtl8139_init)