summaryrefslogtreecommitdiff
path: root/usr/src/cmd/bhyve/pci_e82545.c
blob: 363e203692d92f33416d2d68c857208e6c4f0d38 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
/*
 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
 *
 * Copyright (c) 2016 Alexander Motin <mav@FreeBSD.org>
 * Copyright (c) 2015 Peter Grehan <grehan@freebsd.org>
 * Copyright (c) 2013 Jeremiah Lott, Avere Systems
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer
 *    in this position and unchanged.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

#include <sys/types.h>
#ifndef WITHOUT_CAPSICUM
#include <sys/capsicum.h>
#endif
#include <sys/limits.h>
#include <sys/ioctl.h>
#include <sys/uio.h>
#include <net/ethernet.h>
#include <netinet/in.h>
#include <netinet/tcp.h>

#ifndef WITHOUT_CAPSICUM
#include <capsicum_helpers.h>
#endif

#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <md5.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sysexits.h>
#include <unistd.h>
#include <pthread.h>
#include <pthread_np.h>

#include "e1000_regs.h"
#include "e1000_defines.h"
#include "mii.h"

#include "bhyverun.h"
#include "config.h"
#include "debug.h"
#include "pci_emul.h"
#include "mevent.h"
#include "net_utils.h"
#include "net_backends.h"

/* Hardware/register definitions XXX: move some to common code. */
#define E82545_VENDOR_ID_INTEL			0x8086
#define E82545_DEV_ID_82545EM_COPPER		0x100F
#define E82545_SUBDEV_ID			0x1008

#define E82545_REVISION_4			4

#define E82545_MDIC_DATA_MASK			0x0000FFFF
#define E82545_MDIC_OP_MASK			0x0c000000
#define E82545_MDIC_IE				0x20000000

#define E82545_EECD_FWE_DIS	0x00000010 /* Flash writes disabled */
#define E82545_EECD_FWE_EN	0x00000020 /* Flash writes enabled */
#define E82545_EECD_FWE_MASK	0x00000030 /* Flash writes mask */

#define E82545_BAR_REGISTER			0
#define E82545_BAR_REGISTER_LEN			(128*1024)
#define E82545_BAR_FLASH			1
#define E82545_BAR_FLASH_LEN			(64*1024)
#define E82545_BAR_IO				2
#define E82545_BAR_IO_LEN			8

#define E82545_IOADDR				0x00000000
#define E82545_IODATA				0x00000004
#define E82545_IO_REGISTER_MAX			0x0001FFFF
#define E82545_IO_FLASH_BASE			0x00080000
#define E82545_IO_FLASH_MAX			0x000FFFFF

#define E82545_ARRAY_ENTRY(reg, offset)		(reg + (offset<<2))
#define E82545_RAR_MAX				15
#define E82545_MTA_MAX				127
#define E82545_VFTA_MAX				127

/* Slightly modified from the driver versions, hardcoded for 3 opcode bits,
 * followed by 6 address bits.
 * TODO: make opcode bits and addr bits configurable?
 * NVM Commands - Microwire */
#define E82545_NVM_OPCODE_BITS	3
#define E82545_NVM_ADDR_BITS	6
#define E82545_NVM_DATA_BITS	16
#define E82545_NVM_OPADDR_BITS	(E82545_NVM_OPCODE_BITS + E82545_NVM_ADDR_BITS)
#define E82545_NVM_ADDR_MASK	((1 << E82545_NVM_ADDR_BITS)-1)
#define E82545_NVM_OPCODE_MASK	\
    (((1 << E82545_NVM_OPCODE_BITS) - 1) << E82545_NVM_ADDR_BITS)
#define E82545_NVM_OPCODE_READ	(0x6 << E82545_NVM_ADDR_BITS)	/* read */
#define E82545_NVM_OPCODE_WRITE	(0x5 << E82545_NVM_ADDR_BITS)	/* write */
#define E82545_NVM_OPCODE_ERASE	(0x7 << E82545_NVM_ADDR_BITS)	/* erase */
#define	E82545_NVM_OPCODE_EWEN	(0x4 << E82545_NVM_ADDR_BITS)	/* wr-enable */

#define	E82545_NVM_EEPROM_SIZE	64 /* 64 * 16-bit values == 128K */

#define E1000_ICR_SRPD		0x00010000

/* This is an arbitrary number.  There is no hard limit on the chip. */
#define I82545_MAX_TXSEGS	64

/* Legacy receive descriptor */
struct e1000_rx_desc {
	uint64_t buffer_addr;	/* Address of the descriptor's data buffer */
	uint16_t length;	/* Length of data DMAed into data buffer */
	uint16_t csum;		/* Packet checksum */
	uint8_t	 status;       	/* Descriptor status */
	uint8_t  errors;	/* Descriptor Errors */
	uint16_t special;
};

/* Transmit descriptor types */
#define	E1000_TXD_MASK		(E1000_TXD_CMD_DEXT | 0x00F00000)
#define E1000_TXD_TYP_L		(0)
#define E1000_TXD_TYP_C		(E1000_TXD_CMD_DEXT | E1000_TXD_DTYP_C)
#define E1000_TXD_TYP_D		(E1000_TXD_CMD_DEXT | E1000_TXD_DTYP_D)

/* Legacy transmit descriptor */
struct e1000_tx_desc {
	uint64_t buffer_addr;   /* Address of the descriptor's data buffer */
	union {
		uint32_t data;
		struct {
			uint16_t length;  /* Data buffer length */
			uint8_t  cso;  /* Checksum offset */
			uint8_t  cmd;  /* Descriptor control */
		} flags;
	} lower;
	union {
		uint32_t data;
		struct {
			uint8_t status; /* Descriptor status */
			uint8_t css;  /* Checksum start */
			uint16_t special;
		} fields;
	} upper;
};

/* Context descriptor */
struct e1000_context_desc {
	union {
		uint32_t ip_config;
		struct {
			uint8_t ipcss;  /* IP checksum start */
			uint8_t ipcso;  /* IP checksum offset */
			uint16_t ipcse;  /* IP checksum end */
		} ip_fields;
	} lower_setup;
	union {
		uint32_t tcp_config;
		struct {
			uint8_t tucss;  /* TCP checksum start */
			uint8_t tucso;  /* TCP checksum offset */
			uint16_t tucse;  /* TCP checksum end */
		} tcp_fields;
	} upper_setup;
	uint32_t cmd_and_length;
	union {
		uint32_t data;
		struct {
			uint8_t status;  /* Descriptor status */
			uint8_t hdr_len;  /* Header length */
			uint16_t mss;  /* Maximum segment size */
		} fields;
	} tcp_seg_setup;
};

/* Data descriptor */
struct e1000_data_desc {
	uint64_t buffer_addr;  /* Address of the descriptor's buffer address */
	union {
		uint32_t data;
		struct {
			uint16_t length;  /* Data buffer length */
			uint8_t typ_len_ext;
			uint8_t cmd;
		} flags;
	} lower;
	union {
		uint32_t data;
		struct {
			uint8_t status;  /* Descriptor status */
			uint8_t popts;  /* Packet Options */
			uint16_t special;
		} fields;
	} upper;
};

union e1000_tx_udesc {
	struct e1000_tx_desc td;
	struct e1000_context_desc cd;
	struct e1000_data_desc dd;
};

/* Tx checksum info for a packet. */
struct ck_info {
	int	ck_valid;	/* ck_info is valid */
	uint8_t	ck_start;	/* start byte of cksum calcuation */
	uint8_t	ck_off;		/* offset of cksum insertion */
	uint16_t ck_len;	/* length of cksum calc: 0 is to packet-end */
};

/*
 * Debug printf
 */
static int e82545_debug = 0;
#define WPRINTF(msg,params...) PRINTLN("e82545: " msg, ##params)
#define DPRINTF(msg,params...) if (e82545_debug) WPRINTF(msg, params)

#define	MIN(a,b) (((a)<(b))?(a):(b))
#define	MAX(a,b) (((a)>(b))?(a):(b))

/* s/w representation of the RAL/RAH regs */
struct  eth_uni {
	int		eu_valid;
	int		eu_addrsel;
	struct ether_addr eu_eth;
};


struct e82545_softc {
	struct pci_devinst *esc_pi;
	struct vmctx	*esc_ctx;
	struct mevent   *esc_mevpitr;
	pthread_mutex_t	esc_mtx;
	struct ether_addr esc_mac;
	net_backend_t	*esc_be;

	/* General */
	uint32_t	esc_CTRL;	/* x0000 device ctl */
	uint32_t	esc_FCAL;	/* x0028 flow ctl addr lo */
	uint32_t	esc_FCAH;	/* x002C flow ctl addr hi */
	uint32_t	esc_FCT;	/* x0030 flow ctl type */
	uint32_t	esc_VET;	/* x0038 VLAN eth type */
	uint32_t	esc_FCTTV;	/* x0170 flow ctl tx timer */
	uint32_t	esc_LEDCTL;	/* x0E00 LED control */
	uint32_t	esc_PBA;	/* x1000 pkt buffer allocation */

	/* Interrupt control */
	int		esc_irq_asserted;
	uint32_t	esc_ICR;	/* x00C0 cause read/clear */
	uint32_t	esc_ITR;	/* x00C4 intr throttling */
	uint32_t	esc_ICS;	/* x00C8 cause set */
	uint32_t	esc_IMS;	/* x00D0 mask set/read */
	uint32_t	esc_IMC;	/* x00D8 mask clear */

	/* Transmit */
	union e1000_tx_udesc *esc_txdesc;
	struct e1000_context_desc esc_txctx;
	pthread_t	esc_tx_tid;
	pthread_cond_t	esc_tx_cond;
	int		esc_tx_enabled;
	int		esc_tx_active;
	uint32_t	esc_TXCW;	/* x0178 transmit config */
	uint32_t	esc_TCTL;	/* x0400 transmit ctl */
	uint32_t	esc_TIPG;	/* x0410 inter-packet gap */
	uint16_t	esc_AIT;	/* x0458 Adaptive Interframe Throttle */
	uint64_t	esc_tdba;      	/* verified 64-bit desc table addr */
	uint32_t	esc_TDBAL;	/* x3800 desc table addr, low bits */
	uint32_t	esc_TDBAH;	/* x3804 desc table addr, hi 32-bits */
	uint32_t	esc_TDLEN;	/* x3808 # descriptors in bytes */
	uint16_t	esc_TDH;	/* x3810 desc table head idx */
	uint16_t	esc_TDHr;	/* internal read version of TDH */
	uint16_t	esc_TDT;	/* x3818 desc table tail idx */
	uint32_t	esc_TIDV;	/* x3820 intr delay */
	uint32_t	esc_TXDCTL;	/* x3828 desc control */
	uint32_t	esc_TADV;	/* x382C intr absolute delay */

	/* L2 frame acceptance */
	struct eth_uni	esc_uni[16];	/* 16 x unicast MAC addresses */
	uint32_t	esc_fmcast[128]; /* Multicast filter bit-match */
	uint32_t	esc_fvlan[128]; /* VLAN 4096-bit filter */

	/* Receive */
	struct e1000_rx_desc *esc_rxdesc;
	pthread_cond_t	esc_rx_cond;
	int		esc_rx_enabled;
	int		esc_rx_active;
	int		esc_rx_loopback;
	uint32_t	esc_RCTL;	/* x0100 receive ctl */
	uint32_t	esc_FCRTL;	/* x2160 flow cntl thresh, low */
	uint32_t	esc_FCRTH;	/* x2168 flow cntl thresh, hi */
	uint64_t	esc_rdba;	/* verified 64-bit desc table addr */
	uint32_t	esc_RDBAL;	/* x2800 desc table addr, low bits */
	uint32_t	esc_RDBAH;	/* x2804 desc table addr, hi 32-bits*/
	uint32_t	esc_RDLEN;	/* x2808 #descriptors */
	uint16_t	esc_RDH;	/* x2810 desc table head idx */
	uint16_t	esc_RDT;	/* x2818 desc table tail idx */
	uint32_t	esc_RDTR;	/* x2820 intr delay */
	uint32_t	esc_RXDCTL;	/* x2828 desc control */
	uint32_t	esc_RADV;	/* x282C intr absolute delay */
	uint32_t	esc_RSRPD;	/* x2C00 recv small packet detect */
	uint32_t	esc_RXCSUM;     /* x5000 receive cksum ctl */

	/* IO Port register access */
	uint32_t io_addr;

	/* Shadow copy of MDIC */
	uint32_t mdi_control;
	/* Shadow copy of EECD */
	uint32_t eeprom_control;
	/* Latest NVM in/out */
	uint16_t nvm_data;
	uint16_t nvm_opaddr;
	/* stats */
	uint32_t missed_pkt_count; /* dropped for no room in rx queue */
	uint32_t pkt_rx_by_size[6];
	uint32_t pkt_tx_by_size[6];
	uint32_t good_pkt_rx_count;
	uint32_t bcast_pkt_rx_count;
	uint32_t mcast_pkt_rx_count;
	uint32_t good_pkt_tx_count;
	uint32_t bcast_pkt_tx_count;
	uint32_t mcast_pkt_tx_count;
	uint32_t oversize_rx_count;
	uint32_t tso_tx_count;
	uint64_t good_octets_rx;
	uint64_t good_octets_tx;
	uint64_t missed_octets; /* counts missed and oversized */

	uint8_t nvm_bits:6; /* number of bits remaining in/out */
	uint8_t nvm_mode:2;
#define E82545_NVM_MODE_OPADDR  0x0
#define E82545_NVM_MODE_DATAIN  0x1
#define E82545_NVM_MODE_DATAOUT 0x2
	/* EEPROM data */
	uint16_t eeprom_data[E82545_NVM_EEPROM_SIZE];
};

static void e82545_reset(struct e82545_softc *sc, int dev);
static void e82545_rx_enable(struct e82545_softc *sc);
static void e82545_rx_disable(struct e82545_softc *sc);
static void e82545_rx_callback(int fd, enum ev_type type, void *param);
static void e82545_tx_start(struct e82545_softc *sc);
static void e82545_tx_enable(struct e82545_softc *sc);
static void e82545_tx_disable(struct e82545_softc *sc);

static inline int
e82545_size_stat_index(uint32_t size)
{
	if (size <= 64) {
		return 0;
	} else if (size >= 1024) {
		return 5;
	} else {
		/* should be 1-4 */
		return (ffs(size) - 6);
	}
}

static void
e82545_init_eeprom(struct e82545_softc *sc)
{
	uint16_t checksum, i;

        /* mac addr */
	sc->eeprom_data[NVM_MAC_ADDR] = ((uint16_t)sc->esc_mac.octet[0]) |
		(((uint16_t)sc->esc_mac.octet[1]) << 8);
	sc->eeprom_data[NVM_MAC_ADDR+1] = ((uint16_t)sc->esc_mac.octet[2]) |
		(((uint16_t)sc->esc_mac.octet[3]) << 8);
	sc->eeprom_data[NVM_MAC_ADDR+2] = ((uint16_t)sc->esc_mac.octet[4]) |
		(((uint16_t)sc->esc_mac.octet[5]) << 8);

	/* pci ids */
	sc->eeprom_data[NVM_SUB_DEV_ID] = E82545_SUBDEV_ID;
	sc->eeprom_data[NVM_SUB_VEN_ID] = E82545_VENDOR_ID_INTEL;
	sc->eeprom_data[NVM_DEV_ID] = E82545_DEV_ID_82545EM_COPPER;
	sc->eeprom_data[NVM_VEN_ID] = E82545_VENDOR_ID_INTEL;

	/* fill in the checksum */
        checksum = 0;
	for (i = 0; i < NVM_CHECKSUM_REG; i++) {
		checksum += sc->eeprom_data[i];
	}
	checksum = NVM_SUM - checksum;
	sc->eeprom_data[NVM_CHECKSUM_REG] = checksum;
	DPRINTF("eeprom checksum: 0x%x", checksum);
}

static void
e82545_write_mdi(struct e82545_softc *sc, uint8_t reg_addr,
			uint8_t phy_addr, uint32_t data)
{
	DPRINTF("Write mdi reg:0x%x phy:0x%x data: 0x%x", reg_addr, phy_addr, data);
}

static uint32_t
e82545_read_mdi(struct e82545_softc *sc, uint8_t reg_addr,
			uint8_t phy_addr)
{
	//DPRINTF("Read mdi reg:0x%x phy:0x%x", reg_addr, phy_addr);
	switch (reg_addr) {
	case PHY_STATUS:
		return (MII_SR_LINK_STATUS | MII_SR_AUTONEG_CAPS |
			MII_SR_AUTONEG_COMPLETE);
	case PHY_AUTONEG_ADV:
		return NWAY_AR_SELECTOR_FIELD;
	case PHY_LP_ABILITY:
		return 0;
	case PHY_1000T_STATUS:
		return (SR_1000T_LP_FD_CAPS | SR_1000T_REMOTE_RX_STATUS |
			SR_1000T_LOCAL_RX_STATUS);
	case PHY_ID1:
		return (M88E1011_I_PHY_ID >> 16) & 0xFFFF;
	case PHY_ID2:
		return (M88E1011_I_PHY_ID | E82545_REVISION_4) & 0xFFFF;
	default:
		DPRINTF("Unknown mdi read reg:0x%x phy:0x%x", reg_addr, phy_addr);
		return 0;
	}
	/* not reached */
}

static void
e82545_eecd_strobe(struct e82545_softc *sc)
{
	/* Microwire state machine */
	/*
	DPRINTF("eeprom state machine srtobe "
		"0x%x 0x%x 0x%x 0x%x",
		sc->nvm_mode, sc->nvm_bits,
		sc->nvm_opaddr, sc->nvm_data);*/

	if (sc->nvm_bits == 0) {
		DPRINTF("eeprom state machine not expecting data! "
			"0x%x 0x%x 0x%x 0x%x",
			sc->nvm_mode, sc->nvm_bits,
			sc->nvm_opaddr, sc->nvm_data);
		return;
	}
	sc->nvm_bits--;
	if (sc->nvm_mode == E82545_NVM_MODE_DATAOUT) {
		/* shifting out */
		if (sc->nvm_data & 0x8000) {
			sc->eeprom_control |= E1000_EECD_DO;
		} else {
			sc->eeprom_control &= ~E1000_EECD_DO;
		}
		sc->nvm_data <<= 1;
		if (sc->nvm_bits == 0) {
			/* read done, back to opcode mode. */
			sc->nvm_opaddr = 0;
			sc->nvm_mode = E82545_NVM_MODE_OPADDR;
			sc->nvm_bits = E82545_NVM_OPADDR_BITS;
		}
	} else if (sc->nvm_mode == E82545_NVM_MODE_DATAIN) {
		/* shifting in */
		sc->nvm_data <<= 1;
		if (sc->eeprom_control & E1000_EECD_DI) {
			sc->nvm_data |= 1;
		}
		if (sc->nvm_bits == 0) {
			/* eeprom write */
			uint16_t op = sc->nvm_opaddr & E82545_NVM_OPCODE_MASK;
			uint16_t addr = sc->nvm_opaddr & E82545_NVM_ADDR_MASK;
			if (op != E82545_NVM_OPCODE_WRITE) {
				DPRINTF("Illegal eeprom write op 0x%x",
					sc->nvm_opaddr);
			} else if (addr >= E82545_NVM_EEPROM_SIZE) {
				DPRINTF("Illegal eeprom write addr 0x%x",
					sc->nvm_opaddr);
			} else {
				DPRINTF("eeprom write eeprom[0x%x] = 0x%x",
				addr, sc->nvm_data);
				sc->eeprom_data[addr] = sc->nvm_data;
			}
			/* back to opcode mode */
			sc->nvm_opaddr = 0;
			sc->nvm_mode = E82545_NVM_MODE_OPADDR;
			sc->nvm_bits = E82545_NVM_OPADDR_BITS;
		}
	} else if (sc->nvm_mode == E82545_NVM_MODE_OPADDR) {
		sc->nvm_opaddr <<= 1;
		if (sc->eeprom_control & E1000_EECD_DI) {
			sc->nvm_opaddr |= 1;
		}
		if (sc->nvm_bits == 0) {
			uint16_t op = sc->nvm_opaddr & E82545_NVM_OPCODE_MASK;
			switch (op) {
			case E82545_NVM_OPCODE_EWEN:
				DPRINTF("eeprom write enable: 0x%x",
					sc->nvm_opaddr);
				/* back to opcode mode */
				sc->nvm_opaddr = 0;
				sc->nvm_mode = E82545_NVM_MODE_OPADDR;
				sc->nvm_bits = E82545_NVM_OPADDR_BITS;
				break;
			case E82545_NVM_OPCODE_READ:
			{
				uint16_t addr = sc->nvm_opaddr &
					E82545_NVM_ADDR_MASK;
				sc->nvm_mode = E82545_NVM_MODE_DATAOUT;
				sc->nvm_bits = E82545_NVM_DATA_BITS;
				if (addr < E82545_NVM_EEPROM_SIZE) {
					sc->nvm_data = sc->eeprom_data[addr];
					DPRINTF("eeprom read: eeprom[0x%x] = 0x%x",
						addr, sc->nvm_data);
				} else {
					DPRINTF("eeprom illegal read: 0x%x",
						sc->nvm_opaddr);
					sc->nvm_data = 0;
				}
				break;
			}
			case E82545_NVM_OPCODE_WRITE:
				sc->nvm_mode = E82545_NVM_MODE_DATAIN;
				sc->nvm_bits = E82545_NVM_DATA_BITS;
				sc->nvm_data = 0;
				break;
			default:
				DPRINTF("eeprom unknown op: 0x%x",
					sc->nvm_opaddr);
				/* back to opcode mode */
				sc->nvm_opaddr = 0;
				sc->nvm_mode = E82545_NVM_MODE_OPADDR;
				sc->nvm_bits = E82545_NVM_OPADDR_BITS;
			}
		}
	} else {
		DPRINTF("eeprom state machine wrong state! "
			"0x%x 0x%x 0x%x 0x%x",
			sc->nvm_mode, sc->nvm_bits,
			sc->nvm_opaddr, sc->nvm_data);
	}
}

static void
e82545_itr_callback(int fd, enum ev_type type, void *param)
{
	uint32_t new;
	struct e82545_softc *sc = param;

	pthread_mutex_lock(&sc->esc_mtx);
	new = sc->esc_ICR & sc->esc_IMS;
	if (new && !sc->esc_irq_asserted) {
		DPRINTF("itr callback: lintr assert %x", new);
		sc->esc_irq_asserted = 1;
		pci_lintr_assert(sc->esc_pi);
	} else {
		mevent_delete(sc->esc_mevpitr);
		sc->esc_mevpitr = NULL;
	}
	pthread_mutex_unlock(&sc->esc_mtx);
}

static void
e82545_icr_assert(struct e82545_softc *sc, uint32_t bits)
{
	uint32_t new;

	DPRINTF("icr assert: 0x%x", bits);

	/*
	 * An interrupt is only generated if bits are set that
	 * aren't already in the ICR, these bits are unmasked,
	 * and there isn't an interrupt already pending.
	 */
	new = bits & ~sc->esc_ICR & sc->esc_IMS;
	sc->esc_ICR |= bits;

	if (new == 0) {
		DPRINTF("icr assert: masked %x, ims %x", new, sc->esc_IMS);
	} else if (sc->esc_mevpitr != NULL) {
		DPRINTF("icr assert: throttled %x, ims %x", new, sc->esc_IMS);
	} else if (!sc->esc_irq_asserted) {
		DPRINTF("icr assert: lintr assert %x", new);
		sc->esc_irq_asserted = 1;
		pci_lintr_assert(sc->esc_pi);
		if (sc->esc_ITR != 0) {
			sc->esc_mevpitr = mevent_add(
			    (sc->esc_ITR + 3905) / 3906,  /* 256ns -> 1ms */
			    EVF_TIMER, e82545_itr_callback, sc);
		}
	}
}

static void
e82545_ims_change(struct e82545_softc *sc, uint32_t bits)
{
	uint32_t new;

	/*
	 * Changing the mask may allow previously asserted
	 * but masked interrupt requests to generate an interrupt.
	 */
	new = bits & sc->esc_ICR & ~sc->esc_IMS;
	sc->esc_IMS |= bits;

	if (new == 0) {
		DPRINTF("ims change: masked %x, ims %x", new, sc->esc_IMS);
	} else if (sc->esc_mevpitr != NULL) {
		DPRINTF("ims change: throttled %x, ims %x", new, sc->esc_IMS);
	} else if (!sc->esc_irq_asserted) {
		DPRINTF("ims change: lintr assert %x", new);
		sc->esc_irq_asserted = 1;
		pci_lintr_assert(sc->esc_pi);
		if (sc->esc_ITR != 0) {
			sc->esc_mevpitr = mevent_add(
			    (sc->esc_ITR + 3905) / 3906,  /* 256ns -> 1ms */
			    EVF_TIMER, e82545_itr_callback, sc);
		}
	}
}

static void
e82545_icr_deassert(struct e82545_softc *sc, uint32_t bits)
{

	DPRINTF("icr deassert: 0x%x", bits);
	sc->esc_ICR &= ~bits;

	/*
	 * If there are no longer any interrupt sources and there
	 * was an asserted interrupt, clear it
	 */
	if (sc->esc_irq_asserted && !(sc->esc_ICR & sc->esc_IMS)) {
		DPRINTF("icr deassert: lintr deassert %x", bits);
		pci_lintr_deassert(sc->esc_pi);
		sc->esc_irq_asserted = 0;
	}
}

static void
e82545_intr_write(struct e82545_softc *sc, uint32_t offset, uint32_t value)
{

	DPRINTF("intr_write: off %x, val %x", offset, value);

	switch (offset) {
	case E1000_ICR:
		e82545_icr_deassert(sc, value);
		break;
	case E1000_ITR:
		sc->esc_ITR = value;
		break;
	case E1000_ICS:
		sc->esc_ICS = value;	/* not used: store for debug */
		e82545_icr_assert(sc, value);
		break;
	case E1000_IMS:
		e82545_ims_change(sc, value);
		break;
	case E1000_IMC:
		sc->esc_IMC = value;	/* for debug */
		sc->esc_IMS &= ~value;
		// XXX clear interrupts if all ICR bits now masked
		// and interrupt was pending ?
		break;
	default:
		break;
	}
}

static uint32_t
e82545_intr_read(struct e82545_softc *sc, uint32_t offset)
{
	uint32_t retval;

	retval = 0;

	DPRINTF("intr_read: off %x", offset);

	switch (offset) {
	case E1000_ICR:
		retval = sc->esc_ICR;
		sc->esc_ICR = 0;
		e82545_icr_deassert(sc, ~0);
		break;
	case E1000_ITR:
		retval = sc->esc_ITR;
		break;
	case E1000_ICS:
		/* write-only register */
		break;
	case E1000_IMS:
		retval = sc->esc_IMS;
		break;
	case E1000_IMC:
		/* write-only register */
		break;
	default:
		break;
	}

	return (retval);
}

static void
e82545_devctl(struct e82545_softc *sc, uint32_t val)
{

	sc->esc_CTRL = val & ~E1000_CTRL_RST;

	if (val & E1000_CTRL_RST) {
		DPRINTF("e1k: s/w reset, ctl %x", val);
		e82545_reset(sc, 1);
	}
	/* XXX check for phy reset ? */
}

static void
e82545_rx_update_rdba(struct e82545_softc *sc)
{

	/* XXX verify desc base/len within phys mem range */
	sc->esc_rdba = (uint64_t)sc->esc_RDBAH << 32 |
	    sc->esc_RDBAL;

	/* Cache host mapping of guest descriptor array */
	sc->esc_rxdesc = paddr_guest2host(sc->esc_ctx,
	    sc->esc_rdba, sc->esc_RDLEN);
}

static void
e82545_rx_ctl(struct e82545_softc *sc, uint32_t val)
{
	int on;

	on = ((val & E1000_RCTL_EN) == E1000_RCTL_EN);

	/* Save RCTL after stripping reserved bits 31:27,24,21,14,11:10,0 */
	sc->esc_RCTL = val & ~0xF9204c01;

	DPRINTF("rx_ctl - %s RCTL %x, val %x",
		on ? "on" : "off", sc->esc_RCTL, val);

	/* state change requested */
	if (on != sc->esc_rx_enabled) {
		if (on) {
			/* Catch disallowed/unimplemented settings */
			//assert(!(val & E1000_RCTL_LBM_TCVR));

			if (sc->esc_RCTL & E1000_RCTL_LBM_TCVR) {
				sc->esc_rx_loopback = 1;
			} else {
				sc->esc_rx_loopback = 0;
			}

			e82545_rx_update_rdba(sc);
			e82545_rx_enable(sc);
		} else {
			e82545_rx_disable(sc);
			sc->esc_rx_loopback = 0;
			sc->esc_rdba = 0;
			sc->esc_rxdesc = NULL;
		}
	}
}

static void
e82545_tx_update_tdba(struct e82545_softc *sc)
{

	/* XXX verify desc base/len within phys mem range */
	sc->esc_tdba = (uint64_t)sc->esc_TDBAH << 32 | sc->esc_TDBAL;

	/* Cache host mapping of guest descriptor array */
	sc->esc_txdesc = paddr_guest2host(sc->esc_ctx, sc->esc_tdba,
            sc->esc_TDLEN);
}

static void
e82545_tx_ctl(struct e82545_softc *sc, uint32_t val)
{
	int on;

	on = ((val & E1000_TCTL_EN) == E1000_TCTL_EN);

	/* ignore TCTL_EN settings that don't change state */
	if (on == sc->esc_tx_enabled)
		return;

	if (on) {
		e82545_tx_update_tdba(sc);
		e82545_tx_enable(sc);
	} else {
		e82545_tx_disable(sc);
		sc->esc_tdba = 0;
		sc->esc_txdesc = NULL;
	}

	/* Save TCTL value after stripping reserved bits 31:25,23,2,0 */
	sc->esc_TCTL = val & ~0xFE800005;
}

static int
e82545_bufsz(uint32_t rctl)
{

	switch (rctl & (E1000_RCTL_BSEX | E1000_RCTL_SZ_256)) {
	case (E1000_RCTL_SZ_2048): return (2048);
	case (E1000_RCTL_SZ_1024): return (1024);
	case (E1000_RCTL_SZ_512): return (512);
	case (E1000_RCTL_SZ_256): return (256);
	case (E1000_RCTL_BSEX|E1000_RCTL_SZ_16384): return (16384);
	case (E1000_RCTL_BSEX|E1000_RCTL_SZ_8192): return (8192);
	case (E1000_RCTL_BSEX|E1000_RCTL_SZ_4096): return (4096);
	}
	return (256);	/* Forbidden value. */
}

/* XXX one packet at a time until this is debugged */
static void
e82545_rx_callback(int fd, enum ev_type type, void *param)
{
	struct e82545_softc *sc = param;
	struct e1000_rx_desc *rxd;
	struct iovec vec[64];
	int left, len, lim, maxpktsz, maxpktdesc, bufsz, i, n, size;
	uint32_t cause = 0;
	uint16_t *tp, tag, head;

	pthread_mutex_lock(&sc->esc_mtx);
	DPRINTF("rx_run: head %x, tail %x", sc->esc_RDH, sc->esc_RDT);

	if (!sc->esc_rx_enabled || sc->esc_rx_loopback) {
		DPRINTF("rx disabled (!%d || %d) -- packet(s) dropped",
		    sc->esc_rx_enabled, sc->esc_rx_loopback);
		while (netbe_rx_discard(sc->esc_be) > 0) {
		}
		goto done1;
	}
	bufsz = e82545_bufsz(sc->esc_RCTL);
	maxpktsz = (sc->esc_RCTL & E1000_RCTL_LPE) ? 16384 : 1522;
	maxpktdesc = (maxpktsz + bufsz - 1) / bufsz;
	size = sc->esc_RDLEN / 16;
	head = sc->esc_RDH;
	left = (size + sc->esc_RDT - head) % size;
	if (left < maxpktdesc) {
		DPRINTF("rx overflow (%d < %d) -- packet(s) dropped",
		    left, maxpktdesc);
		while (netbe_rx_discard(sc->esc_be) > 0) {
		}
		goto done1;
	}

	sc->esc_rx_active = 1;
	pthread_mutex_unlock(&sc->esc_mtx);

	for (lim = size / 4; lim > 0 && left >= maxpktdesc; lim -= n) {

		/* Grab rx descriptor pointed to by the head pointer */
		for (i = 0; i < maxpktdesc; i++) {
			rxd = &sc->esc_rxdesc[(head + i) % size];
			vec[i].iov_base = paddr_guest2host(sc->esc_ctx,
			    rxd->buffer_addr, bufsz);
			vec[i].iov_len = bufsz;
		}
		len = netbe_recv(sc->esc_be, vec, maxpktdesc);
		if (len <= 0) {
			DPRINTF("netbe_recv() returned %d", len);
			goto done;
		}

		/*
		 * Adjust the packet length based on whether the CRC needs
		 * to be stripped or if the packet is less than the minimum
		 * eth packet size.
		 */
		if (len < ETHER_MIN_LEN - ETHER_CRC_LEN)
			len = ETHER_MIN_LEN - ETHER_CRC_LEN;
		if (!(sc->esc_RCTL & E1000_RCTL_SECRC))
			len += ETHER_CRC_LEN;
		n = (len + bufsz - 1) / bufsz;

		DPRINTF("packet read %d bytes, %d segs, head %d",
		    len, n, head);

		/* Apply VLAN filter. */
		tp = (uint16_t *)vec[0].iov_base + 6;
		if ((sc->esc_RCTL & E1000_RCTL_VFE) &&
		    (ntohs(tp[0]) == sc->esc_VET)) {
			tag = ntohs(tp[1]) & 0x0fff;
			if ((sc->esc_fvlan[tag >> 5] &
			    (1 << (tag & 0x1f))) != 0) {
				DPRINTF("known VLAN %d", tag);
			} else {
				DPRINTF("unknown VLAN %d", tag);
				n = 0;
				continue;
			}
		}

		/* Update all consumed descriptors. */
		for (i = 0; i < n - 1; i++) {
			rxd = &sc->esc_rxdesc[(head + i) % size];
			rxd->length = bufsz;
			rxd->csum = 0;
			rxd->errors = 0;
			rxd->special = 0;
			rxd->status = E1000_RXD_STAT_DD;
		}
		rxd = &sc->esc_rxdesc[(head + i) % size];
		rxd->length = len % bufsz;
		rxd->csum = 0;
		rxd->errors = 0;
		rxd->special = 0;
		/* XXX signal no checksum for now */
		rxd->status = E1000_RXD_STAT_PIF | E1000_RXD_STAT_IXSM |
		    E1000_RXD_STAT_EOP | E1000_RXD_STAT_DD;

		/* Schedule receive interrupts. */
		if (len <= sc->esc_RSRPD) {
			cause |= E1000_ICR_SRPD | E1000_ICR_RXT0;
		} else {
			/* XXX: RDRT and RADV timers should be here. */
			cause |= E1000_ICR_RXT0;
		}

		head = (head + n) % size;
		left -= n;
	}

done:
	pthread_mutex_lock(&sc->esc_mtx);
	sc->esc_rx_active = 0;
	if (sc->esc_rx_enabled == 0)
		pthread_cond_signal(&sc->esc_rx_cond);

	sc->esc_RDH = head;
	/* Respect E1000_RCTL_RDMTS */
	left = (size + sc->esc_RDT - head) % size;
	if (left < (size >> (((sc->esc_RCTL >> 8) & 3) + 1)))
		cause |= E1000_ICR_RXDMT0;
	/* Assert all accumulated interrupts. */
	if (cause != 0)
		e82545_icr_assert(sc, cause);
done1:
	DPRINTF("rx_run done: head %x, tail %x", sc->esc_RDH, sc->esc_RDT);
	pthread_mutex_unlock(&sc->esc_mtx);
}

static uint16_t
e82545_carry(uint32_t sum)
{

	sum = (sum & 0xFFFF) + (sum >> 16);
	if (sum > 0xFFFF)
		sum -= 0xFFFF;
	return (sum);
}

static uint16_t
e82545_buf_checksum(uint8_t *buf, int len)
{
	int i;
	uint32_t sum = 0;

	/* Checksum all the pairs of bytes first... */
	for (i = 0; i < (len & ~1U); i += 2)
		sum += *((u_int16_t *)(buf + i));

	/*
	 * If there's a single byte left over, checksum it, too.
	 * Network byte order is big-endian, so the remaining byte is
	 * the high byte.
	 */
	if (i < len)
		sum += htons(buf[i] << 8);

	return (e82545_carry(sum));
}

static uint16_t
e82545_iov_checksum(struct iovec *iov, int iovcnt, int off, int len)
{
	int now, odd;
	uint32_t sum = 0, s;

	/* Skip completely unneeded vectors. */
	while (iovcnt > 0 && iov->iov_len <= off && off > 0) {
		off -= iov->iov_len;
		iov++;
		iovcnt--;
	}

	/* Calculate checksum of requested range. */
	odd = 0;
	while (len > 0 && iovcnt > 0) {
		now = MIN(len, iov->iov_len - off);
#ifdef __FreeBSD__
		s = e82545_buf_checksum(iov->iov_base + off, now);
#else
		s = e82545_buf_checksum((uint8_t *)iov->iov_base + off, now);
#endif
		sum += odd ? (s << 8) : s;
		odd ^= (now & 1);
		len -= now;
		off = 0;
		iov++;
		iovcnt--;
	}

	return (e82545_carry(sum));
}

/*
 * Return the transmit descriptor type.
 */
static int
e82545_txdesc_type(uint32_t lower)
{
	int type;

	type = 0;

	if (lower & E1000_TXD_CMD_DEXT)
		type = lower & E1000_TXD_MASK;

	return (type);
}

static void
e82545_transmit_checksum(struct iovec *iov, int iovcnt, struct ck_info *ck)
{
	uint16_t cksum;
	int cklen;

	DPRINTF("tx cksum: iovcnt/s/off/len %d/%d/%d/%d",
	    iovcnt, ck->ck_start, ck->ck_off, ck->ck_len);
	cklen = ck->ck_len ? ck->ck_len - ck->ck_start + 1 : INT_MAX;
	cksum = e82545_iov_checksum(iov, iovcnt, ck->ck_start, cklen);
	*(uint16_t *)((uint8_t *)iov[0].iov_base + ck->ck_off) = ~cksum;
}

static void
e82545_transmit_backend(struct e82545_softc *sc, struct iovec *iov, int iovcnt)
{

	if (sc->esc_be == NULL)
		return;

	(void) netbe_send(sc->esc_be, iov, iovcnt);
}

static void
e82545_transmit_done(struct e82545_softc *sc, uint16_t head, uint16_t tail,
    uint16_t dsize, int *tdwb)
{
	union e1000_tx_udesc *dsc;

	for ( ; head != tail; head = (head + 1) % dsize) {
		dsc = &sc->esc_txdesc[head];
		if (dsc->td.lower.data & E1000_TXD_CMD_RS) {
			dsc->td.upper.data |= E1000_TXD_STAT_DD;
			*tdwb = 1;
		}
	}
}

static int
e82545_transmit(struct e82545_softc *sc, uint16_t head, uint16_t tail,
    uint16_t dsize, uint16_t *rhead, int *tdwb)
{
	uint8_t *hdr, *hdrp;
	struct iovec iovb[I82545_MAX_TXSEGS + 2];
	struct iovec tiov[I82545_MAX_TXSEGS + 2];
	struct e1000_context_desc *cd;
	struct ck_info ckinfo[2];
	struct iovec *iov;
	union  e1000_tx_udesc *dsc;
	int desc, dtype, len, ntype, iovcnt, tcp, tso;
	int mss, paylen, seg, tiovcnt, left, now, nleft, nnow, pv, pvoff;
	unsigned hdrlen, vlen, pktlen;
	uint32_t tcpsum, tcpseq;
	uint16_t ipcs, tcpcs, ipid, ohead;
	bool invalid;

	ckinfo[0].ck_valid = ckinfo[1].ck_valid = 0;
	iovcnt = 0;
	ntype = 0;
	tso = 0;
	pktlen = 0;
	ohead = head;
	invalid = false;

	/* iovb[0/1] may be used for writable copy of headers. */
	iov = &iovb[2];

	for (desc = 0; ; desc++, head = (head + 1) % dsize) {
		if (head == tail) {
			*rhead = head;
			return (0);
		}
		dsc = &sc->esc_txdesc[head];
		dtype = e82545_txdesc_type(dsc->td.lower.data);

		if (desc == 0) {
			switch (dtype) {
			case E1000_TXD_TYP_C:
				DPRINTF("tx ctxt desc idx %d: %016jx "
				    "%08x%08x",
				    head, dsc->td.buffer_addr,
				    dsc->td.upper.data, dsc->td.lower.data);
				/* Save context and return */
				sc->esc_txctx = dsc->cd;
				goto done;
			case E1000_TXD_TYP_L:
				DPRINTF("tx legacy desc idx %d: %08x%08x",
				    head, dsc->td.upper.data, dsc->td.lower.data);
				/*
				 * legacy cksum start valid in first descriptor
				 */
				ntype = dtype;
				ckinfo[0].ck_start = dsc->td.upper.fields.css;
				break;
			case E1000_TXD_TYP_D:
				DPRINTF("tx data desc idx %d: %08x%08x",
				    head, dsc->td.upper.data, dsc->td.lower.data);
				ntype = dtype;
				break;
			default:
				break;
			}
		} else {
			/* Descriptor type must be consistent */
			assert(dtype == ntype);
			DPRINTF("tx next desc idx %d: %08x%08x",
			    head, dsc->td.upper.data, dsc->td.lower.data);
		}

		len = (dtype == E1000_TXD_TYP_L) ? dsc->td.lower.flags.length :
		    dsc->dd.lower.data & 0xFFFFF;

		/* Strip checksum supplied by guest. */
		if ((dsc->td.lower.data & E1000_TXD_CMD_EOP) != 0 &&
		    (dsc->td.lower.data & E1000_TXD_CMD_IFCS) == 0) {
			if (len <= 2) {
				WPRINTF("final descriptor too short (%d) -- dropped",
				    len);
				invalid = true;
			} else
				len -= 2;
		}

		if (len > 0 && iovcnt < I82545_MAX_TXSEGS) {
			iov[iovcnt].iov_base = paddr_guest2host(sc->esc_ctx,
			    dsc->td.buffer_addr, len);
			iov[iovcnt].iov_len = len;
			iovcnt++;
			pktlen += len;
		}

		/*
		 * Pull out info that is valid in the final descriptor
		 * and exit descriptor loop.
		 */
		if (dsc->td.lower.data & E1000_TXD_CMD_EOP) {
			if (dtype == E1000_TXD_TYP_L) {
				if (dsc->td.lower.data & E1000_TXD_CMD_IC) {
					ckinfo[0].ck_valid = 1;
					ckinfo[0].ck_off =
					    dsc->td.lower.flags.cso;
					ckinfo[0].ck_len = 0;
				}
			} else {
				cd = &sc->esc_txctx;
				if (dsc->dd.lower.data & E1000_TXD_CMD_TSE)
					tso = 1;
				if (dsc->dd.upper.fields.popts &
				    E1000_TXD_POPTS_IXSM)
					ckinfo[0].ck_valid = 1;
				if (dsc->dd.upper.fields.popts &
				    E1000_TXD_POPTS_IXSM || tso) {
					ckinfo[0].ck_start =
					    cd->lower_setup.ip_fields.ipcss;
					ckinfo[0].ck_off =
					    cd->lower_setup.ip_fields.ipcso;
					ckinfo[0].ck_len =
					    cd->lower_setup.ip_fields.ipcse;
				}
				if (dsc->dd.upper.fields.popts &
				    E1000_TXD_POPTS_TXSM)
					ckinfo[1].ck_valid = 1;
				if (dsc->dd.upper.fields.popts &
				    E1000_TXD_POPTS_TXSM || tso) {
					ckinfo[1].ck_start =
					    cd->upper_setup.tcp_fields.tucss;
					ckinfo[1].ck_off =
					    cd->upper_setup.tcp_fields.tucso;
					ckinfo[1].ck_len =
					    cd->upper_setup.tcp_fields.tucse;
				}
			}
			break;
		}
	}

	if (invalid)
		goto done;

	if (iovcnt > I82545_MAX_TXSEGS) {
		WPRINTF("tx too many descriptors (%d > %d) -- dropped",
		    iovcnt, I82545_MAX_TXSEGS);
		goto done;
	}

	hdrlen = vlen = 0;
	/* Estimate writable space for VLAN header insertion. */
	if ((sc->esc_CTRL & E1000_CTRL_VME) &&
	    (dsc->td.lower.data & E1000_TXD_CMD_VLE)) {
		hdrlen = ETHER_ADDR_LEN*2;
		vlen = ETHER_VLAN_ENCAP_LEN;
	}
	if (!tso) {
		/* Estimate required writable space for checksums. */
		if (ckinfo[0].ck_valid)
			hdrlen = MAX(hdrlen, ckinfo[0].ck_off + 2);
		if (ckinfo[1].ck_valid)
			hdrlen = MAX(hdrlen, ckinfo[1].ck_off + 2);
		/* Round up writable space to the first vector. */
		if (hdrlen != 0 && iov[0].iov_len > hdrlen &&
		    iov[0].iov_len < hdrlen + 100)
			hdrlen = iov[0].iov_len;
	} else {
		/* In case of TSO header length provided by software. */
		hdrlen = sc->esc_txctx.tcp_seg_setup.fields.hdr_len;

		/*
		 * Cap the header length at 240 based on 7.2.4.5 of
		 * the Intel 82576EB (Rev 2.63) datasheet.
		 */
		if (hdrlen > 240) {
			WPRINTF("TSO hdrlen too large: %d", hdrlen);
			goto done;
		}

		/*
		 * If VLAN insertion is requested, ensure the header
		 * at least holds the amount of data copied during
		 * VLAN insertion below.
		 *
		 * XXX: Realistic packets will include a full Ethernet
		 * header before the IP header at ckinfo[0].ck_start,
		 * but this check is sufficient to prevent
		 * out-of-bounds access below.
		 */
		if (vlen != 0 && hdrlen < ETHER_ADDR_LEN*2) {
			WPRINTF("TSO hdrlen too small for vlan insertion "
			    "(%d vs %d) -- dropped", hdrlen,
			    ETHER_ADDR_LEN*2);
			goto done;
		}

		/*
		 * Ensure that the header length covers the used fields
		 * in the IP and TCP headers as well as the IP and TCP
		 * checksums.  The following fields are accessed below:
		 *
		 * Header | Field | Offset | Length
		 * -------+-------+--------+-------
		 * IPv4   | len   | 2      | 2
		 * IPv4   | ID    | 4      | 2
		 * IPv6   | len   | 4      | 2
		 * TCP    | seq # | 4      | 4
		 * TCP    | flags | 13     | 1
		 * UDP    | len   | 4      | 4
		 */
		if (hdrlen < ckinfo[0].ck_start + 6 ||
		    hdrlen < ckinfo[0].ck_off + 2) {
			WPRINTF("TSO hdrlen too small for IP fields (%d) "
			    "-- dropped", hdrlen);
			goto done;
		}
		if (sc->esc_txctx.cmd_and_length & E1000_TXD_CMD_TCP) {
			if (hdrlen < ckinfo[1].ck_start + 14) {
				WPRINTF("TSO hdrlen too small for TCP fields "
				    "(%d) -- dropped", hdrlen);
				goto done;
			}
		} else {
			if (hdrlen < ckinfo[1].ck_start + 8) {
				WPRINTF("TSO hdrlen too small for UDP fields "
				    "(%d) -- dropped", hdrlen);
				goto done;
			}
		}
		if (ckinfo[1].ck_valid && hdrlen < ckinfo[1].ck_off + 2) {
			WPRINTF("TSO hdrlen too small for TCP/UDP fields "
			    "(%d) -- dropped", hdrlen);
			goto done;
		}
		if (ckinfo[1].ck_valid && hdrlen < ckinfo[1].ck_off + 2) {
			WPRINTF("TSO hdrlen too small for TCP/UDP fields "
			    "(%d) -- dropped", hdrlen);
			goto done;
		}
	}

	if (pktlen < hdrlen + vlen) {
		WPRINTF("packet too small for writable header");
		goto done;
	}

	/* Allocate, fill and prepend writable header vector. */
	if (hdrlen + vlen != 0) {
		hdr = __builtin_alloca(hdrlen + vlen);
		hdr += vlen;
		for (left = hdrlen, hdrp = hdr; left > 0;
		    left -= now, hdrp += now) {
			now = MIN(left, iov->iov_len);
			memcpy(hdrp, iov->iov_base, now);
			iov->iov_base += now;
			iov->iov_len -= now;
			if (iov->iov_len == 0) {
				iov++;
				iovcnt--;
			}
		}
		iov--;
		iovcnt++;
#ifdef __FreeBSD__
		iov->iov_base = hdr;
#else
		iov->iov_base = (caddr_t)hdr;
#endif
		iov->iov_len = hdrlen;
	} else
		hdr = NULL;

	/* Insert VLAN tag. */
	if (vlen != 0) {
		hdr -= ETHER_VLAN_ENCAP_LEN;
		memmove(hdr, hdr + ETHER_VLAN_ENCAP_LEN, ETHER_ADDR_LEN*2);
		hdrlen += ETHER_VLAN_ENCAP_LEN;
		hdr[ETHER_ADDR_LEN*2 + 0] = sc->esc_VET >> 8;
		hdr[ETHER_ADDR_LEN*2 + 1] = sc->esc_VET & 0xff;
		hdr[ETHER_ADDR_LEN*2 + 2] = dsc->td.upper.fields.special >> 8;
		hdr[ETHER_ADDR_LEN*2 + 3] = dsc->td.upper.fields.special & 0xff;
#ifdef __FreeBSD__
		iov->iov_base = hdr;
#else
		iov->iov_base = (caddr_t)hdr;
#endif
		iov->iov_len += ETHER_VLAN_ENCAP_LEN;
		/* Correct checksum offsets after VLAN tag insertion. */
		ckinfo[0].ck_start += ETHER_VLAN_ENCAP_LEN;
		ckinfo[0].ck_off += ETHER_VLAN_ENCAP_LEN;
		if (ckinfo[0].ck_len != 0)
			ckinfo[0].ck_len += ETHER_VLAN_ENCAP_LEN;
		ckinfo[1].ck_start += ETHER_VLAN_ENCAP_LEN;
		ckinfo[1].ck_off += ETHER_VLAN_ENCAP_LEN;
		if (ckinfo[1].ck_len != 0)
			ckinfo[1].ck_len += ETHER_VLAN_ENCAP_LEN;
	}

	/* Simple non-TSO case. */
	if (!tso) {
		/* Calculate checksums and transmit. */
		if (ckinfo[0].ck_valid)
			e82545_transmit_checksum(iov, iovcnt, &ckinfo[0]);
		if (ckinfo[1].ck_valid)
			e82545_transmit_checksum(iov, iovcnt, &ckinfo[1]);
		e82545_transmit_backend(sc, iov, iovcnt);
		goto done;
	}

	/* Doing TSO. */
	tcp = (sc->esc_txctx.cmd_and_length & E1000_TXD_CMD_TCP) != 0;
	mss = sc->esc_txctx.tcp_seg_setup.fields.mss;
	paylen = (sc->esc_txctx.cmd_and_length & 0x000fffff);
	DPRINTF("tx %s segmentation offload %d+%d/%d bytes %d iovs",
	    tcp ? "TCP" : "UDP", hdrlen, paylen, mss, iovcnt);
	ipid = ntohs(*(uint16_t *)&hdr[ckinfo[0].ck_start + 4]);
	tcpseq = 0;
	if (tcp)
		tcpseq = ntohl(*(uint32_t *)&hdr[ckinfo[1].ck_start + 4]);
	ipcs = *(uint16_t *)&hdr[ckinfo[0].ck_off];
	tcpcs = 0;
	if (ckinfo[1].ck_valid)	/* Save partial pseudo-header checksum. */
		tcpcs = *(uint16_t *)&hdr[ckinfo[1].ck_off];
	pv = 1;
	pvoff = 0;
	for (seg = 0, left = paylen; left > 0; seg++, left -= now) {
		now = MIN(left, mss);

		/* Construct IOVs for the segment. */
		/* Include whole original header. */
#ifdef __FreeBSD__
		tiov[0].iov_base = hdr;
#else
		tiov[0].iov_base = (caddr_t)hdr;
#endif
		tiov[0].iov_len = hdrlen;
		tiovcnt = 1;
		/* Include respective part of payload IOV. */
		for (nleft = now; pv < iovcnt && nleft > 0; nleft -= nnow) {
			nnow = MIN(nleft, iov[pv].iov_len - pvoff);
			tiov[tiovcnt].iov_base = iov[pv].iov_base + pvoff;
			tiov[tiovcnt++].iov_len = nnow;
			if (pvoff + nnow == iov[pv].iov_len) {
				pv++;
				pvoff = 0;
			} else
				pvoff += nnow;
		}
		DPRINTF("tx segment %d %d+%d bytes %d iovs",
		    seg, hdrlen, now, tiovcnt);

		/* Update IP header. */
		if (sc->esc_txctx.cmd_and_length & E1000_TXD_CMD_IP) {
			/* IPv4 -- set length and ID */
			*(uint16_t *)&hdr[ckinfo[0].ck_start + 2] =
			    htons(hdrlen - ckinfo[0].ck_start + now);
			*(uint16_t *)&hdr[ckinfo[0].ck_start + 4] =
			    htons(ipid + seg);
		} else {
			/* IPv6 -- set length */
			*(uint16_t *)&hdr[ckinfo[0].ck_start + 4] =
			    htons(hdrlen - ckinfo[0].ck_start - 40 +
				  now);
		}

		/* Update pseudo-header checksum. */
		tcpsum = tcpcs;
		tcpsum += htons(hdrlen - ckinfo[1].ck_start + now);

		/* Update TCP/UDP headers. */
		if (tcp) {
			/* Update sequence number and FIN/PUSH flags. */
			*(uint32_t *)&hdr[ckinfo[1].ck_start + 4] =
			    htonl(tcpseq + paylen - left);
			if (now < left) {
				hdr[ckinfo[1].ck_start + 13] &=
				    ~(TH_FIN | TH_PUSH);
			}
		} else {
			/* Update payload length. */
			*(uint32_t *)&hdr[ckinfo[1].ck_start + 4] =
			    hdrlen - ckinfo[1].ck_start + now;
		}

		/* Calculate checksums and transmit. */
		if (ckinfo[0].ck_valid) {
			*(uint16_t *)&hdr[ckinfo[0].ck_off] = ipcs;
			e82545_transmit_checksum(tiov, tiovcnt, &ckinfo[0]);
		}
		if (ckinfo[1].ck_valid) {
			*(uint16_t *)&hdr[ckinfo[1].ck_off] =
			    e82545_carry(tcpsum);
			e82545_transmit_checksum(tiov, tiovcnt, &ckinfo[1]);
		}
		e82545_transmit_backend(sc, tiov, tiovcnt);
	}

done:
	head = (head + 1) % dsize;
	e82545_transmit_done(sc, ohead, head, dsize, tdwb);

	*rhead = head;
	return (desc + 1);
}

static void
e82545_tx_run(struct e82545_softc *sc)
{
	uint32_t cause;
	uint16_t head, rhead, tail, size;
	int lim, tdwb, sent;

	head = sc->esc_TDH;
	tail = sc->esc_TDT;
	size = sc->esc_TDLEN / 16;
	DPRINTF("tx_run: head %x, rhead %x, tail %x",
	    sc->esc_TDH, sc->esc_TDHr, sc->esc_TDT);

	pthread_mutex_unlock(&sc->esc_mtx);
	rhead = head;
	tdwb = 0;
	for (lim = size / 4; sc->esc_tx_enabled && lim > 0; lim -= sent) {
		sent = e82545_transmit(sc, head, tail, size, &rhead, &tdwb);
		if (sent == 0)
			break;
		head = rhead;
	}
	pthread_mutex_lock(&sc->esc_mtx);

	sc->esc_TDH = head;
	sc->esc_TDHr = rhead;
	cause = 0;
	if (tdwb)
		cause |= E1000_ICR_TXDW;
	if (lim != size / 4 && sc->esc_TDH == sc->esc_TDT)
		cause |= E1000_ICR_TXQE;
	if (cause)
		e82545_icr_assert(sc, cause);

	DPRINTF("tx_run done: head %x, rhead %x, tail %x",
	    sc->esc_TDH, sc->esc_TDHr, sc->esc_TDT);
}

static _Noreturn void *
e82545_tx_thread(void *param)
{
	struct e82545_softc *sc = param;

	pthread_mutex_lock(&sc->esc_mtx);
	for (;;) {
		while (!sc->esc_tx_enabled || sc->esc_TDHr == sc->esc_TDT) {
			if (sc->esc_tx_enabled && sc->esc_TDHr != sc->esc_TDT)
				break;
			sc->esc_tx_active = 0;
			if (sc->esc_tx_enabled == 0)
				pthread_cond_signal(&sc->esc_tx_cond);
			pthread_cond_wait(&sc->esc_tx_cond, &sc->esc_mtx);
		}
		sc->esc_tx_active = 1;

		/* Process some tx descriptors.  Lock dropped inside. */
		e82545_tx_run(sc);
	}
}

static void
e82545_tx_start(struct e82545_softc *sc)
{

	if (sc->esc_tx_active == 0)
		pthread_cond_signal(&sc->esc_tx_cond);
}

static void
e82545_tx_enable(struct e82545_softc *sc)
{

	sc->esc_tx_enabled = 1;
}

static void
e82545_tx_disable(struct e82545_softc *sc)
{

	sc->esc_tx_enabled = 0;
	while (sc->esc_tx_active)
		pthread_cond_wait(&sc->esc_tx_cond, &sc->esc_mtx);
}

static void
e82545_rx_enable(struct e82545_softc *sc)
{

	sc->esc_rx_enabled = 1;
}

static void
e82545_rx_disable(struct e82545_softc *sc)
{

	sc->esc_rx_enabled = 0;
	while (sc->esc_rx_active)
		pthread_cond_wait(&sc->esc_rx_cond, &sc->esc_mtx);
}

static void
e82545_write_ra(struct e82545_softc *sc, int reg, uint32_t wval)
{
	struct eth_uni *eu;
	int idx;

	idx = reg >> 1;
	assert(idx < 15);

	eu = &sc->esc_uni[idx];

	if (reg & 0x1) {
		/* RAH */
		eu->eu_valid = ((wval & E1000_RAH_AV) == E1000_RAH_AV);
		eu->eu_addrsel = (wval >> 16) & 0x3;
		eu->eu_eth.octet[5] = wval >> 8;
		eu->eu_eth.octet[4] = wval;
	} else {
		/* RAL */
		eu->eu_eth.octet[3] = wval >> 24;
		eu->eu_eth.octet[2] = wval >> 16;
		eu->eu_eth.octet[1] = wval >> 8;
		eu->eu_eth.octet[0] = wval;
	}
}

static uint32_t
e82545_read_ra(struct e82545_softc *sc, int reg)
{
	struct eth_uni *eu;
	uint32_t retval;
	int idx;

	idx = reg >> 1;
	assert(idx < 15);

	eu = &sc->esc_uni[idx];

	if (reg & 0x1) {
		/* RAH */
		retval = (eu->eu_valid << 31) |
			 (eu->eu_addrsel << 16) |
			 (eu->eu_eth.octet[5] << 8) |
			 eu->eu_eth.octet[4];
	} else {
		/* RAL */
		retval = (eu->eu_eth.octet[3] << 24) |
			 (eu->eu_eth.octet[2] << 16) |
			 (eu->eu_eth.octet[1] << 8) |
			 eu->eu_eth.octet[0];
	}

	return (retval);
}

static void
e82545_write_register(struct e82545_softc *sc, uint32_t offset, uint32_t value)
{
	int ridx;

	if (offset & 0x3) {
		DPRINTF("Unaligned register write offset:0x%x value:0x%x", offset, value);
		return;
	}
	DPRINTF("Register write: 0x%x value: 0x%x", offset, value);

	switch (offset) {
	case E1000_CTRL:
	case E1000_CTRL_DUP:
		e82545_devctl(sc, value);
		break;
	case E1000_FCAL:
		sc->esc_FCAL = value;
		break;
	case E1000_FCAH:
		sc->esc_FCAH = value & ~0xFFFF0000;
		break;
	case E1000_FCT:
		sc->esc_FCT = value & ~0xFFFF0000;
		break;
	case E1000_VET:
		sc->esc_VET = value & ~0xFFFF0000;
		break;
	case E1000_FCTTV:
		sc->esc_FCTTV = value & ~0xFFFF0000;
		break;
	case E1000_LEDCTL:
		sc->esc_LEDCTL = value & ~0x30303000;
		break;
	case E1000_PBA:
		sc->esc_PBA = value & 0x0000FF80;
		break;
	case E1000_ICR:
	case E1000_ITR:
	case E1000_ICS:
	case E1000_IMS:
	case E1000_IMC:
		e82545_intr_write(sc, offset, value);
		break;
	case E1000_RCTL:
		e82545_rx_ctl(sc, value);
		break;
	case E1000_FCRTL:
		sc->esc_FCRTL = value & ~0xFFFF0007;
		break;
	case E1000_FCRTH:
		sc->esc_FCRTH = value & ~0xFFFF0007;
		break;
	case E1000_RDBAL(0):
		sc->esc_RDBAL = value & ~0xF;
		if (sc->esc_rx_enabled) {
			/* Apparently legal: update cached address */
			e82545_rx_update_rdba(sc);
		}
		break;
	case E1000_RDBAH(0):
		assert(!sc->esc_rx_enabled);
		sc->esc_RDBAH = value;
		break;
	case E1000_RDLEN(0):
		assert(!sc->esc_rx_enabled);
		sc->esc_RDLEN = value & ~0xFFF0007F;
		break;
	case E1000_RDH(0):
		/* XXX should only ever be zero ? Range check ? */
		sc->esc_RDH = value;
		break;
	case E1000_RDT(0):
		/* XXX if this opens up the rx ring, do something ? */
		sc->esc_RDT = value;
		break;
	case E1000_RDTR:
		/* ignore FPD bit 31 */
		sc->esc_RDTR = value & ~0xFFFF0000;
		break;
	case E1000_RXDCTL(0):
		sc->esc_RXDCTL = value & ~0xFEC0C0C0;
		break;
	case E1000_RADV:
		sc->esc_RADV = value & ~0xFFFF0000;
		break;
	case E1000_RSRPD:
		sc->esc_RSRPD = value & ~0xFFFFF000;
		break;
	case E1000_RXCSUM:
		sc->esc_RXCSUM = value & ~0xFFFFF800;
		break;
	case E1000_TXCW:
		sc->esc_TXCW = value & ~0x3FFF0000;
		break;
	case E1000_TCTL:
		e82545_tx_ctl(sc, value);
		break;
	case E1000_TIPG:
		sc->esc_TIPG = value;
		break;
	case E1000_AIT:
		sc->esc_AIT = value;
		break;
	case E1000_TDBAL(0):
		sc->esc_TDBAL = value & ~0xF;
		if (sc->esc_tx_enabled)
			e82545_tx_update_tdba(sc);
		break;
	case E1000_TDBAH(0):
		sc->esc_TDBAH = value;
		if (sc->esc_tx_enabled)
			e82545_tx_update_tdba(sc);
		break;
	case E1000_TDLEN(0):
		sc->esc_TDLEN = value & ~0xFFF0007F;
		if (sc->esc_tx_enabled)
			e82545_tx_update_tdba(sc);
		break;
	case E1000_TDH(0):
		//assert(!sc->esc_tx_enabled);
		/* XXX should only ever be zero ? Range check ? */
		sc->esc_TDHr = sc->esc_TDH = value;
		break;
	case E1000_TDT(0):
		/* XXX range check ? */
		sc->esc_TDT = value;
		if (sc->esc_tx_enabled)
			e82545_tx_start(sc);
		break;
	case E1000_TIDV:
		sc->esc_TIDV = value & ~0xFFFF0000;
		break;
	case E1000_TXDCTL(0):
		//assert(!sc->esc_tx_enabled);
		sc->esc_TXDCTL = value & ~0xC0C0C0;
		break;
	case E1000_TADV:
		sc->esc_TADV = value & ~0xFFFF0000;
		break;
	case E1000_RAL(0) ... E1000_RAH(15):
		/* convert to u32 offset */
		ridx = (offset - E1000_RAL(0)) >> 2;
		e82545_write_ra(sc, ridx, value);
		break;
	case E1000_MTA ... (E1000_MTA + (127*4)):
		sc->esc_fmcast[(offset - E1000_MTA) >> 2] = value;
		break;
	case E1000_VFTA ... (E1000_VFTA + (127*4)):
		sc->esc_fvlan[(offset - E1000_VFTA) >> 2] = value;
		break;
	case E1000_EECD:
	{
		//DPRINTF("EECD write 0x%x -> 0x%x", sc->eeprom_control, value);
		/* edge triggered low->high */
		uint32_t eecd_strobe = ((sc->eeprom_control & E1000_EECD_SK) ?
			0 : (value & E1000_EECD_SK));
		uint32_t eecd_mask = (E1000_EECD_SK|E1000_EECD_CS|
					E1000_EECD_DI|E1000_EECD_REQ);
		sc->eeprom_control &= ~eecd_mask;
		sc->eeprom_control |= (value & eecd_mask);
		/* grant/revoke immediately */
		if (value & E1000_EECD_REQ) {
			sc->eeprom_control |= E1000_EECD_GNT;
		} else {
                        sc->eeprom_control &= ~E1000_EECD_GNT;
		}
		if (eecd_strobe && (sc->eeprom_control & E1000_EECD_CS)) {
			e82545_eecd_strobe(sc);
		}
		return;
	}
	case E1000_MDIC:
	{
		uint8_t reg_addr = (uint8_t)((value & E1000_MDIC_REG_MASK) >>
						E1000_MDIC_REG_SHIFT);
		uint8_t phy_addr = (uint8_t)((value & E1000_MDIC_PHY_MASK) >>
						E1000_MDIC_PHY_SHIFT);
		sc->mdi_control =
			(value & ~(E1000_MDIC_ERROR|E1000_MDIC_DEST));
		if ((value & E1000_MDIC_READY) != 0) {
			DPRINTF("Incorrect MDIC ready bit: 0x%x", value);
			return;
		}
		switch (value & E82545_MDIC_OP_MASK) {
		case E1000_MDIC_OP_READ:
			sc->mdi_control &= ~E82545_MDIC_DATA_MASK;
			sc->mdi_control |= e82545_read_mdi(sc, reg_addr, phy_addr);
			break;
		case E1000_MDIC_OP_WRITE:
			e82545_write_mdi(sc, reg_addr, phy_addr,
				value & E82545_MDIC_DATA_MASK);
			break;
		default:
			DPRINTF("Unknown MDIC op: 0x%x", value);
			return;
		}
		/* TODO: barrier? */
		sc->mdi_control |= E1000_MDIC_READY;
		if (value & E82545_MDIC_IE) {
			// TODO: generate interrupt
		}
		return;
	}
	case E1000_MANC:
	case E1000_STATUS:
		return;
	default:
		DPRINTF("Unknown write register: 0x%x value:%x", offset, value);
		return;
	}
}

static uint32_t
e82545_read_register(struct e82545_softc *sc, uint32_t offset)
{
	uint32_t retval;
	int ridx;

	if (offset & 0x3) {
		DPRINTF("Unaligned register read offset:0x%x", offset);
		return 0;
	}

	DPRINTF("Register read: 0x%x", offset);

	switch (offset) {
	case E1000_CTRL:
		retval = sc->esc_CTRL;
		break;
	case E1000_STATUS:
		retval = E1000_STATUS_FD | E1000_STATUS_LU |
		    E1000_STATUS_SPEED_1000;
		break;
	case E1000_FCAL:
		retval = sc->esc_FCAL;
		break;
	case E1000_FCAH:
		retval = sc->esc_FCAH;
		break;
	case E1000_FCT:
		retval = sc->esc_FCT;
		break;
	case E1000_VET:
		retval = sc->esc_VET;
		break;
	case E1000_FCTTV:
		retval = sc->esc_FCTTV;
		break;
	case E1000_LEDCTL:
		retval = sc->esc_LEDCTL;
		break;
	case E1000_PBA:
		retval = sc->esc_PBA;
		break;
	case E1000_ICR:
	case E1000_ITR:
	case E1000_ICS:
	case E1000_IMS:
	case E1000_IMC:
		retval = e82545_intr_read(sc, offset);
		break;
	case E1000_RCTL:
		retval = sc->esc_RCTL;
		break;
	case E1000_FCRTL:
		retval = sc->esc_FCRTL;
		break;
	case E1000_FCRTH:
		retval = sc->esc_FCRTH;
		break;
	case E1000_RDBAL(0):
		retval = sc->esc_RDBAL;
		break;
	case E1000_RDBAH(0):
		retval = sc->esc_RDBAH;
		break;
	case E1000_RDLEN(0):
		retval = sc->esc_RDLEN;
		break;
	case E1000_RDH(0):
		retval = sc->esc_RDH;
		break;
	case E1000_RDT(0):
		retval = sc->esc_RDT;
		break;
	case E1000_RDTR:
		retval = sc->esc_RDTR;
		break;
	case E1000_RXDCTL(0):
		retval = sc->esc_RXDCTL;
		break;
	case E1000_RADV:
		retval = sc->esc_RADV;
		break;
	case E1000_RSRPD:
		retval = sc->esc_RSRPD;
		break;
	case E1000_RXCSUM:
		retval = sc->esc_RXCSUM;
		break;
	case E1000_TXCW:
		retval = sc->esc_TXCW;
		break;
	case E1000_TCTL:
		retval = sc->esc_TCTL;
		break;
	case E1000_TIPG:
		retval = sc->esc_TIPG;
		break;
	case E1000_AIT:
		retval = sc->esc_AIT;
		break;
	case E1000_TDBAL(0):
		retval = sc->esc_TDBAL;
		break;
	case E1000_TDBAH(0):
		retval = sc->esc_TDBAH;
		break;
	case E1000_TDLEN(0):
		retval = sc->esc_TDLEN;
		break;
	case E1000_TDH(0):
		retval = sc->esc_TDH;
		break;
	case E1000_TDT(0):
		retval = sc->esc_TDT;
		break;
	case E1000_TIDV:
		retval = sc->esc_TIDV;
		break;
	case E1000_TXDCTL(0):
		retval = sc->esc_TXDCTL;
		break;
	case E1000_TADV:
		retval = sc->esc_TADV;
		break;
	case E1000_RAL(0) ... E1000_RAH(15):
		/* convert to u32 offset */
		ridx = (offset - E1000_RAL(0)) >> 2;
		retval = e82545_read_ra(sc, ridx);
		break;
	case E1000_MTA ... (E1000_MTA + (127*4)):
		retval = sc->esc_fmcast[(offset - E1000_MTA) >> 2];
		break;
	case E1000_VFTA ... (E1000_VFTA + (127*4)):
		retval = sc->esc_fvlan[(offset - E1000_VFTA) >> 2];
		break;
	case E1000_EECD:
		//DPRINTF("EECD read %x", sc->eeprom_control);
		retval = sc->eeprom_control;
		break;
	case E1000_MDIC:
		retval = sc->mdi_control;
		break;
	case E1000_MANC:
		retval = 0;
		break;
	/* stats that we emulate. */
	case E1000_MPC:
		retval = sc->missed_pkt_count;
		break;
	case E1000_PRC64:
		retval = sc->pkt_rx_by_size[0];
		break;
	case E1000_PRC127:
		retval = sc->pkt_rx_by_size[1];
		break;
	case E1000_PRC255:
		retval = sc->pkt_rx_by_size[2];
		break;
	case E1000_PRC511:
		retval = sc->pkt_rx_by_size[3];
		break;
	case E1000_PRC1023:
		retval = sc->pkt_rx_by_size[4];
		break;
	case E1000_PRC1522:
		retval = sc->pkt_rx_by_size[5];
		break;
	case E1000_GPRC:
		retval = sc->good_pkt_rx_count;
		break;
	case E1000_BPRC:
		retval = sc->bcast_pkt_rx_count;
		break;
	case E1000_MPRC:
		retval = sc->mcast_pkt_rx_count;
		break;
	case E1000_GPTC:
	case E1000_TPT:
		retval = sc->good_pkt_tx_count;
		break;
	case E1000_GORCL:
		retval = (uint32_t)sc->good_octets_rx;
		break;
	case E1000_GORCH:
		retval = (uint32_t)(sc->good_octets_rx >> 32);
		break;
	case E1000_TOTL:
	case E1000_GOTCL:
		retval = (uint32_t)sc->good_octets_tx;
		break;
	case E1000_TOTH:
	case E1000_GOTCH:
		retval = (uint32_t)(sc->good_octets_tx >> 32);
		break;
	case E1000_ROC:
		retval = sc->oversize_rx_count;
		break;
	case E1000_TORL:
		retval = (uint32_t)(sc->good_octets_rx + sc->missed_octets);
		break;
	case E1000_TORH:
		retval = (uint32_t)((sc->good_octets_rx +
		    sc->missed_octets) >> 32);
		break;
	case E1000_TPR:
		retval = sc->good_pkt_rx_count + sc->missed_pkt_count +
		    sc->oversize_rx_count;
		break;
	case E1000_PTC64:
		retval = sc->pkt_tx_by_size[0];
		break;
	case E1000_PTC127:
		retval = sc->pkt_tx_by_size[1];
		break;
	case E1000_PTC255:
		retval = sc->pkt_tx_by_size[2];
		break;
	case E1000_PTC511:
		retval = sc->pkt_tx_by_size[3];
		break;
	case E1000_PTC1023:
		retval = sc->pkt_tx_by_size[4];
		break;
	case E1000_PTC1522:
		retval = sc->pkt_tx_by_size[5];
		break;
	case E1000_MPTC:
		retval = sc->mcast_pkt_tx_count;
		break;
	case E1000_BPTC:
		retval = sc->bcast_pkt_tx_count;
		break;
	case E1000_TSCTC:
		retval = sc->tso_tx_count;
		break;
	/* stats that are always 0. */
	case E1000_CRCERRS:
	case E1000_ALGNERRC:
	case E1000_SYMERRS:
	case E1000_RXERRC:
	case E1000_SCC:
	case E1000_ECOL:
	case E1000_MCC:
	case E1000_LATECOL:
	case E1000_COLC:
	case E1000_DC:
	case E1000_TNCRS:
	case E1000_SEC:
	case E1000_CEXTERR:
	case E1000_RLEC:
	case E1000_XONRXC:
	case E1000_XONTXC:
	case E1000_XOFFRXC:
	case E1000_XOFFTXC:
	case E1000_FCRUC:
	case E1000_RNBC:
	case E1000_RUC:
	case E1000_RFC:
	case E1000_RJC:
	case E1000_MGTPRC:
	case E1000_MGTPDC:
	case E1000_MGTPTC:
	case E1000_TSCTFC:
		retval = 0;
		break;
	default:
		DPRINTF("Unknown read register: 0x%x", offset);
		retval = 0;
		break;
	}

	return (retval);
}

static void
e82545_write(struct vmctx *ctx, int vcpu, struct pci_devinst *pi, int baridx,
	     uint64_t offset, int size, uint64_t value)
{
	struct e82545_softc *sc;

	//DPRINTF("Write bar:%d offset:0x%lx value:0x%lx size:%d", baridx, offset, value, size);

	sc = pi->pi_arg;

	pthread_mutex_lock(&sc->esc_mtx);

	switch (baridx) {
	case E82545_BAR_IO:
		switch (offset) {
		case E82545_IOADDR:
			if (size != 4) {
				DPRINTF("Wrong io addr write sz:%d value:0x%lx", size, value);
			} else
				sc->io_addr = (uint32_t)value;
			break;
		case E82545_IODATA:
			if (size != 4) {
				DPRINTF("Wrong io data write size:%d value:0x%lx", size, value);
			} else if (sc->io_addr > E82545_IO_REGISTER_MAX) {
				DPRINTF("Non-register io write addr:0x%x value:0x%lx", sc->io_addr, value);
			} else
				e82545_write_register(sc, sc->io_addr,
						      (uint32_t)value);
			break;
		default:
			DPRINTF("Unknown io bar write offset:0x%lx value:0x%lx size:%d", offset, value, size);
			break;
		}
		break;
	case E82545_BAR_REGISTER:
		if (size != 4) {
			DPRINTF("Wrong register write size:%d offset:0x%lx value:0x%lx", size, offset, value);
		} else
			e82545_write_register(sc, (uint32_t)offset,
					      (uint32_t)value);
		break;
	default:
		DPRINTF("Unknown write bar:%d off:0x%lx val:0x%lx size:%d",
			baridx, offset, value, size);
	}

	pthread_mutex_unlock(&sc->esc_mtx);
}

static uint64_t
e82545_read(struct vmctx *ctx, int vcpu, struct pci_devinst *pi, int baridx,
	    uint64_t offset, int size)
{
	struct e82545_softc *sc;
	uint64_t retval;

	//DPRINTF("Read  bar:%d offset:0x%lx size:%d", baridx, offset, size);
	sc = pi->pi_arg;
	retval = 0;

	pthread_mutex_lock(&sc->esc_mtx);

	switch (baridx) {
	case E82545_BAR_IO:
		switch (offset) {
		case E82545_IOADDR:
			if (size != 4) {
				DPRINTF("Wrong io addr read sz:%d", size);
			} else
				retval = sc->io_addr;
			break;
		case E82545_IODATA:
			if (size != 4) {
				DPRINTF("Wrong io data read sz:%d", size);
			}
			if (sc->io_addr > E82545_IO_REGISTER_MAX) {
				DPRINTF("Non-register io read addr:0x%x",
					sc->io_addr);
			} else
				retval = e82545_read_register(sc, sc->io_addr);
			break;
		default:
			DPRINTF("Unknown io bar read offset:0x%lx size:%d",
				offset, size);
			break;
		}
		break;
	case E82545_BAR_REGISTER:
		if (size != 4) {
			DPRINTF("Wrong register read size:%d offset:0x%lx",
				size, offset);
		} else
			retval = e82545_read_register(sc, (uint32_t)offset);
		break;
	default:
		DPRINTF("Unknown read bar:%d offset:0x%lx size:%d",
			baridx, offset, size);
		break;
	}

	pthread_mutex_unlock(&sc->esc_mtx);

	return (retval);
}

static void
e82545_reset(struct e82545_softc *sc, int drvr)
{
	int i;

	e82545_rx_disable(sc);
	e82545_tx_disable(sc);

	/* clear outstanding interrupts */
	if (sc->esc_irq_asserted)
		pci_lintr_deassert(sc->esc_pi);

	/* misc */
	if (!drvr) {
		sc->esc_FCAL = 0;
		sc->esc_FCAH = 0;
		sc->esc_FCT = 0;
		sc->esc_VET = 0;
		sc->esc_FCTTV = 0;
	}
	sc->esc_LEDCTL = 0x07061302;
	sc->esc_PBA = 0x00100030;

	/* start nvm in opcode mode. */
	sc->nvm_opaddr = 0;
	sc->nvm_mode = E82545_NVM_MODE_OPADDR;
	sc->nvm_bits = E82545_NVM_OPADDR_BITS;
	sc->eeprom_control = E1000_EECD_PRES | E82545_EECD_FWE_EN;
	e82545_init_eeprom(sc);

	/* interrupt */
	sc->esc_ICR = 0;
	sc->esc_ITR = 250;
	sc->esc_ICS = 0;
	sc->esc_IMS = 0;
	sc->esc_IMC = 0;

	/* L2 filters */
	if (!drvr) {
		memset(sc->esc_fvlan, 0, sizeof(sc->esc_fvlan));
		memset(sc->esc_fmcast, 0, sizeof(sc->esc_fmcast));
		memset(sc->esc_uni, 0, sizeof(sc->esc_uni));

		/* XXX not necessary on 82545 ?? */
		sc->esc_uni[0].eu_valid = 1;
		memcpy(sc->esc_uni[0].eu_eth.octet, sc->esc_mac.octet,
		    ETHER_ADDR_LEN);
	} else {
		/* Clear RAH valid bits */
		for (i = 0; i < 16; i++)
			sc->esc_uni[i].eu_valid = 0;
	}

	/* receive */
	if (!drvr) {
		sc->esc_RDBAL = 0;
		sc->esc_RDBAH = 0;
	}
	sc->esc_RCTL = 0;
	sc->esc_FCRTL = 0;
	sc->esc_FCRTH = 0;
	sc->esc_RDLEN = 0;
	sc->esc_RDH = 0;
	sc->esc_RDT = 0;
	sc->esc_RDTR = 0;
	sc->esc_RXDCTL = (1 << 24) | (1 << 16); /* default GRAN/WTHRESH */
	sc->esc_RADV = 0;
	sc->esc_RXCSUM = 0;

	/* transmit */
	if (!drvr) {
		sc->esc_TDBAL = 0;
		sc->esc_TDBAH = 0;
		sc->esc_TIPG = 0;
		sc->esc_AIT = 0;
		sc->esc_TIDV = 0;
		sc->esc_TADV = 0;
	}
	sc->esc_tdba = 0;
	sc->esc_txdesc = NULL;
	sc->esc_TXCW = 0;
	sc->esc_TCTL = 0;
	sc->esc_TDLEN = 0;
	sc->esc_TDT = 0;
	sc->esc_TDHr = sc->esc_TDH = 0;
	sc->esc_TXDCTL = 0;
}

static int
e82545_init(struct vmctx *ctx, struct pci_devinst *pi, nvlist_t *nvl)
{
	char nstr[80];
	struct e82545_softc *sc;
	const char *mac;
	int err;

	/* Setup our softc */
	sc = calloc(1, sizeof(*sc));

	pi->pi_arg = sc;
	sc->esc_pi = pi;
	sc->esc_ctx = ctx;

	pthread_mutex_init(&sc->esc_mtx, NULL);
	pthread_cond_init(&sc->esc_rx_cond, NULL);
	pthread_cond_init(&sc->esc_tx_cond, NULL);
	pthread_create(&sc->esc_tx_tid, NULL, e82545_tx_thread, sc);
	snprintf(nstr, sizeof(nstr), "e82545-%d:%d tx", pi->pi_slot,
	    pi->pi_func);
        pthread_set_name_np(sc->esc_tx_tid, nstr);

	pci_set_cfgdata16(pi, PCIR_DEVICE, E82545_DEV_ID_82545EM_COPPER);
	pci_set_cfgdata16(pi, PCIR_VENDOR, E82545_VENDOR_ID_INTEL);
	pci_set_cfgdata8(pi,  PCIR_CLASS, PCIC_NETWORK);
	pci_set_cfgdata8(pi, PCIR_SUBCLASS, PCIS_NETWORK_ETHERNET);
	pci_set_cfgdata16(pi, PCIR_SUBDEV_0, E82545_SUBDEV_ID);
	pci_set_cfgdata16(pi, PCIR_SUBVEND_0, E82545_VENDOR_ID_INTEL);

	pci_set_cfgdata8(pi,  PCIR_HDRTYPE, PCIM_HDRTYPE_NORMAL);
	pci_set_cfgdata8(pi,  PCIR_INTPIN, 0x1);

	/* TODO: this card also supports msi, but the freebsd driver for it
	 * does not, so I have not implemented it. */
	pci_lintr_request(pi);

	pci_emul_alloc_bar(pi, E82545_BAR_REGISTER, PCIBAR_MEM32,
		E82545_BAR_REGISTER_LEN);
	pci_emul_alloc_bar(pi, E82545_BAR_FLASH, PCIBAR_MEM32,
		E82545_BAR_FLASH_LEN);
	pci_emul_alloc_bar(pi, E82545_BAR_IO, PCIBAR_IO,
		E82545_BAR_IO_LEN);

	mac = get_config_value_node(nvl, "mac");
	if (mac != NULL) {
		err = net_parsemac(mac, sc->esc_mac.octet);
		if (err) {
			free(sc);
			return (err);
		}
	} else
		net_genmac(pi, sc->esc_mac.octet);

	err = netbe_init(&sc->esc_be, nvl, e82545_rx_callback, sc);
	if (err) {
		free(sc);
		return (err);
	}

#ifndef __FreeBSD__
	size_t buflen = sizeof (sc->esc_mac.octet);

	err = netbe_get_mac(sc->esc_be, sc->esc_mac.octet, &buflen);
	if (err != 0) {
		free(sc);
		return (err);
	}
#endif

	netbe_rx_enable(sc->esc_be);

	/* H/w initiated reset */
	e82545_reset(sc, 0);

	return (0);
}

static const struct pci_devemu pci_de_e82545 = {
	.pe_emu = 	"e1000",
	.pe_init =	e82545_init,
	.pe_legacy_config = netbe_legacy_config,
	.pe_barwrite =	e82545_write,
	.pe_barread =	e82545_read,
};
PCI_EMUL_SET(pci_de_e82545);