Commit a278ca04ceca6e7e73f981e5304ff43877c47e39

Paul Sheppard 2012-06-14T00:03:08

Merge branch 'master' of https://github.com/pshep/cgminer.git

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
diff --git a/Makefile.am b/Makefile.am
index 20db8a2..f4e5898 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -68,6 +68,10 @@ endif # HAVE_x86_64
 endif # HAS_YASM
 endif # HAS_CPUMINE
 
+if NEED_FPGAUTILS
+cgminer_SOURCES += fpgautils.c
+endif
+
 if HAS_BITFORCE
 cgminer_SOURCES += driver-bitforce.c
 endif
@@ -76,6 +80,12 @@ if HAS_ICARUS
 cgminer_SOURCES += driver-icarus.c
 endif
 
+if HAS_MODMINER
+cgminer_SOURCES += driver-modminer.c
+bitstreamsdir = $(bindir)/bitstreams
+dist_bitstreams_DATA = bitstreams/*
+endif
+
 if HAS_ZTEX
 cgminer_SOURCES += driver-ztex.c libztex.c libztex.h
 bitstreamsdir = $(bindir)/bitstreams
diff --git a/README b/README
index af78af1..fac8e6f 100644
--- a/README
+++ b/README
@@ -55,6 +55,7 @@ CGMiner specific configuration options:
 	--disable-adl           Override detection and disable building with adl
 	--enable-bitforce       Compile support for BitForce FPGAs(default disabled)
 	--enable-icarus         Compile support for Icarus Board(default disabled)
+	--enable-modminer       Compile support for ModMiner FPGAs(default disabled)
 	--enable-ztex           Compile support for Ztex Board(default disabled)
 
 Basic *nix build instructions:
@@ -129,6 +130,7 @@ Options for both config file and command line:
 --debug|-D          Enable debug output
 --expiry|-E <arg>   Upper bound on how many seconds after getting work we consider a share from it stale (default: 120)
 --failover-only     Don't leak work to backup pools when primary pool is lagging
+--kernel-path|-K <arg> Specify a path to where bitstream and kernel files are (default: "/usr/local/bin")
 --load-balance      Change multipool strategy from failover to even load balance
 --log|-l <arg>      Interval in seconds between log output (default: 5)
 --monitor|-m <arg>  Use custom pipe cmd for output messages
@@ -184,7 +186,6 @@ GPU only options:
 --gpu-vddc <arg>    Set the GPU voltage in Volts - one value for all or separate by commas for per card.
 --intensity|-I <arg> Intensity of GPU scanning (d or -10 -> 10, default: d to maintain desktop interactivity)
 --kernel|-k <arg>   Override kernel to use (diablo, poclbm, phatk or diakgcn) - one value or comma separated
---kernel-path|-K <arg> Specify a path to where the kernel .cl files are (default: "/usr/local/bin")
 --ndevs|-n          Enumerate number of detected GPUs and exit
 --no-restart        Do not attempt to restart GPUs that hang
 --temp-hysteresis <arg> Set how much the temperature can fluctuate outside limits when automanaging speeds (default: 3)
@@ -194,7 +195,7 @@ GPU only options:
 --worksize|-w <arg> Override detected optimal worksize - one value or comma separated list
 
 
-FPGA mining boards(BitForce, Icarus, Ztex) only options:
+FPGA mining boards(BitForce, Icarus, ModMiner, Ztex) only options:
 
 --scan-serial|-S <arg> Serial port to probe for FPGA mining device
 
@@ -797,7 +798,7 @@ working in the logs?
 A: http://us.php.net/manual/en/sockets.installation.php
 
 Q: What is a PGA?
-A: At the moment, cgminer supports 3 FPGA's: Icarus, Ztex and BitForce.
+A: At the moment, cgminer supports 4 FPGAs: BitForce, Icarus, ModMiner, and Ztex.
 They are Field-Programmable Gate Arrays that have been programmed to do Bitcoin
 mining. Since the acronym needs to be only 3 characters, the "Field-" part has
 been skipped.
diff --git a/adl.c b/adl.c
index 6ed6a18..a920d95 100644
--- a/adl.c
+++ b/adl.c
@@ -1009,8 +1009,10 @@ static int set_powertune(int gpu, int iPercentage)
 	return ret;
 }
 
-/* Returns whether the fanspeed is optimal already or not */
-static bool fan_autotune(int gpu, int temp, int fanpercent, int lasttemp)
+/* Returns whether the fanspeed is optimal already or not. The fan_window bool
+ * tells us whether the current fanspeed is in the target range for fanspeeds.
+ */
+static bool fan_autotune(int gpu, int temp, int fanpercent, int lasttemp, bool *fan_window)
 {
 	struct cgpu_info *cgpu = &gpus[gpu];
 	struct gpu_adl *ga = &cgpu->adl;
@@ -1054,6 +1056,12 @@ static bool fan_autotune(int gpu, int temp, int fanpercent, int lasttemp)
 		newpercent = iMax;
 	else if (newpercent < iMin)
 		newpercent = iMin;
+
+	if (newpercent <= top)
+		*fan_window = true;
+	else
+		*fan_window = false;
+
 	if (newpercent != fanpercent) {
 		applog(LOG_INFO, "Setting GPU %d fan percentage to %d", gpu, newpercent);
 		set_fanspeed(gpu, newpercent);
@@ -1065,7 +1073,7 @@ static bool fan_autotune(int gpu, int temp, int fanpercent, int lasttemp)
 void gpu_autotune(int gpu, enum dev_enable *denable)
 {
 	int temp, fanpercent, engine, newengine, twintemp = 0;
-	bool fan_optimal = true;
+	bool fan_optimal = true, fan_window = true;
 	struct cgpu_info *cgpu;
 	struct gpu_adl *ga;
 
@@ -1084,7 +1092,7 @@ void gpu_autotune(int gpu, enum dev_enable *denable)
 
 	if (temp && fanpercent >= 0 && ga->autofan) {
 		if (!ga->twin)
-			fan_optimal = fan_autotune(gpu, temp, fanpercent, ga->lasttemp);
+			fan_optimal = fan_autotune(gpu, temp, fanpercent, ga->lasttemp, &fan_window);
 		else if (ga->autofan && (ga->has_fanspeed || !ga->twin->autofan)) {
 			/* On linked GPUs, we autotune the fan only once, based
 			 * on the highest temperature from either GPUs */
@@ -1102,7 +1110,7 @@ void gpu_autotune(int gpu, enum dev_enable *denable)
 				fan_gpu = gpu;
 			else
 				fan_gpu = ga->twin->gpu;
-			fan_optimal = fan_autotune(fan_gpu, hightemp, fanpercent, lasttemp);
+			fan_optimal = fan_autotune(fan_gpu, hightemp, fanpercent, lasttemp, &fan_window);
 		}
 	}
 
@@ -1126,7 +1134,7 @@ void gpu_autotune(int gpu, enum dev_enable *denable)
 			applog(LOG_DEBUG, "Temperature %d degrees over target, decreasing clock speed", opt_hysteresis);
 			newengine = engine - ga->lpOdParameters.sEngineClock.iStep;
 			/* Only try to tune engine speed up if this GPU is not disabled */
-		} else if (temp < ga->targettemp && engine < ga->maxspeed && *denable == DEV_ENABLED) {
+		} else if (temp < ga->targettemp && engine < ga->maxspeed && fan_window && *denable == DEV_ENABLED) {
 			applog(LOG_DEBUG, "Temperature below target, increasing clock speed");
 			if (temp < ga->targettemp - opt_hysteresis)
 				newengine = ga->maxspeed;
diff --git a/adl.h b/adl.h
index f48c420..ca67550 100644
--- a/adl.h
+++ b/adl.h
@@ -21,8 +21,8 @@ void gpu_autotune(int gpu, enum dev_enable *denable);
 void clear_adl(int nDevs);
 #else /* HAVE_ADL */
 #define adl_active (0)
-static inline void init_adl(int nDevs) {}
-static inline void change_gpusettings(int gpu) { }
-static inline void clear_adl(int nDevs) {}
+static inline void init_adl(__maybe_unused int nDevs) {}
+static inline void change_gpusettings(__maybe_unused int gpu) { }
+static inline void clear_adl(__maybe_unused int nDevs) {}
 #endif
 #endif
diff --git a/api.c b/api.c
index ea6dc04..f18f7f7 100644
--- a/api.c
+++ b/api.c
@@ -456,16 +456,16 @@ struct CODES {
  { SEVERITY_INFO,  MSG_GPUINT,	PARAM_BOTH,	"GPU %d set new intensity to %s" },
  { SEVERITY_SUCC,  MSG_MINECON, PARAM_NONE,	"CGMiner config" },
  { SEVERITY_ERR,   MSG_GPUMERR,	PARAM_BOTH,	"Setting GPU %d memoryclock to (%s) reported failure" },
- { SEVERITY_SUCC,  MSG_GPUMEM,	PARAM_BOTH,	"Setting GPU %d memoryclock to (%s) reported succeess" },
+ { SEVERITY_SUCC,  MSG_GPUMEM,	PARAM_BOTH,	"Setting GPU %d memoryclock to (%s) reported success" },
  { SEVERITY_ERR,   MSG_GPUEERR,	PARAM_BOTH,	"Setting GPU %d clock to (%s) reported failure" },
- { SEVERITY_SUCC,  MSG_GPUENG,	PARAM_BOTH,	"Setting GPU %d clock to (%s) reported succeess" },
+ { SEVERITY_SUCC,  MSG_GPUENG,	PARAM_BOTH,	"Setting GPU %d clock to (%s) reported success" },
  { SEVERITY_ERR,   MSG_GPUVERR,	PARAM_BOTH,	"Setting GPU %d vddc to (%s) reported failure" },
- { SEVERITY_SUCC,  MSG_GPUVDDC,	PARAM_BOTH,	"Setting GPU %d vddc to (%s) reported succeess" },
+ { SEVERITY_SUCC,  MSG_GPUVDDC,	PARAM_BOTH,	"Setting GPU %d vddc to (%s) reported success" },
  { SEVERITY_ERR,   MSG_GPUFERR,	PARAM_BOTH,	"Setting GPU %d fan to (%s) reported failure" },
- { SEVERITY_SUCC,  MSG_GPUFAN,	PARAM_BOTH,	"Setting GPU %d fan to (%s) reported succeess" },
+ { SEVERITY_SUCC,  MSG_GPUFAN,	PARAM_BOTH,	"Setting GPU %d fan to (%s) reported success" },
  { SEVERITY_ERR,   MSG_MISFN,	PARAM_NONE,	"Missing save filename parameter" },
  { SEVERITY_ERR,   MSG_BADFN,	PARAM_STR,	"Can't open or create save file '%s'" },
- { SEVERITY_ERR,   MSG_SAVED,	PARAM_STR,	"Configuration saved to file '%s'" },
+ { SEVERITY_SUCC,  MSG_SAVED,	PARAM_STR,	"Configuration saved to file '%s'" },
  { SEVERITY_ERR,   MSG_ACCDENY,	PARAM_STR,	"Access denied to '%s' command" },
  { SEVERITY_SUCC,  MSG_ACCOK,	PARAM_NONE,	"Privileged access OK" },
  { SEVERITY_SUCC,  MSG_ENAPOOL,	PARAM_POOL,	"Enabling pool %d:'%s'" },
@@ -1979,12 +1979,13 @@ static void devdetails(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, 
 
 void dosave(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
 {
+	char filename[PATH_MAX];
 	FILE *fcfg;
 	char *ptr;
 
 	if (param == NULL || *param == '\0') {
-		strcpy(io_buffer, message(MSG_MISFN, 0, NULL, isjson));
-		return;
+		default_save_file(filename);
+		param = filename;
 	}
 
 	fcfg = fopen(param, "w");
@@ -2584,4 +2585,3 @@ die:
 
 	mutex_unlock(&quit_restart_lock);
 }
-
diff --git a/bitstreams/COPYING_fpgaminer b/bitstreams/COPYING_fpgaminer
new file mode 100644
index 0000000..9db2c5f
--- /dev/null
+++ b/bitstreams/COPYING_fpgaminer
@@ -0,0 +1,23 @@
+All the bitstream files included in this directory that follow the name pattern fpgaminer_*.ncd are:
+
+----
+
+Copyright (c) 2011-2012 fpgaminer@bitcoin-mining.com
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+----
+
+You can find the original sources at the Open Source FPGA Bitcoin Miner project GitHub repository:
+https://github.com/progranism/Open-Source-FPGA-Bitcoin-Miner/tree/master/projects/X6000_ztex_comm4/hdl
diff --git a/bitstreams/COPYING_ztex b/bitstreams/COPYING_ztex
new file mode 100644
index 0000000..99cd2ed
--- /dev/null
+++ b/bitstreams/COPYING_ztex
@@ -0,0 +1,24 @@
+All the bitstream files included in this directory that follow the name pattern ztex_*.bit are:
+
+----
+
+Copyright (C) 2009-2011 ZTEX GmbH.
+http://www.ztex.de
+
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License version 3 as
+published by the Free Software Foundation.
+
+This program is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, see http://www.gnu.org/licenses/.
+
+----
+
+You can find the original sources at the BTCMiner project home page: http://www.ztex.de/btcminer/
+
diff --git a/bitstreams/LICENSE.txt b/bitstreams/LICENSE.txt
deleted file mode 100644
index 99cd2ed..0000000
--- a/bitstreams/LICENSE.txt
+++ /dev/null
@@ -1,24 +0,0 @@
-All the bitstream files included in this directory that follow the name pattern ztex_*.bit are:
-
-----
-
-Copyright (C) 2009-2011 ZTEX GmbH.
-http://www.ztex.de
-
-
-This program is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License version 3 as
-published by the Free Software Foundation.
-
-This program is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with this program; if not, see http://www.gnu.org/licenses/.
-
-----
-
-You can find the original sources at the BTCMiner project home page: http://www.ztex.de/btcminer/
-
diff --git a/bitstreams/fpgaminer_top_fixed7_197MHz.ncd b/bitstreams/fpgaminer_top_fixed7_197MHz.ncd
new file mode 100644
index 0000000..1df4e1d
Binary files /dev/null and b/bitstreams/fpgaminer_top_fixed7_197MHz.ncd differ
diff --git a/cgminer.c b/cgminer.c
index e89cc3d..f0b9924 100644
--- a/cgminer.c
+++ b/cgminer.c
@@ -54,6 +54,13 @@
 	#include <sys/wait.h>
 #endif
 
+#if defined(USE_BITFORCE) || defined(USE_ICARUS) || defined(USE_MODMINER)
+#	define USE_FPGA
+#	define USE_FPGA_SERIAL
+#elif defined(USE_ZTEX)
+#	define USE_FPGA
+#endif
+
 enum workio_commands {
 	WC_GET_WORK,
 	WC_SUBMIT_WORK,
@@ -468,7 +475,7 @@ static char *set_int_1_to_10(const char *arg, int *i)
 	return set_int_range(arg, i, 1, 10);
 }
 
-#if defined(USE_BITFORCE) || defined(USE_ICARUS)
+#ifdef USE_FPGA_SERIAL
 static char *add_serial(char *arg)
 {
 	string_elist_add(arg, &scan_devices);
@@ -657,8 +664,12 @@ static void load_temp_cutoffs()
 			devices[device]->cutofftemp = val;
 		}
 	}
-	else
-		val = opt_cutofftemp;
+	else {
+		for (i = device; i < total_devices; ++i)
+			if (!devices[i]->cutofftemp)
+				devices[i]->cutofftemp = opt_cutofftemp;
+		return;
+	}
 	if (device <= 1) {
 		for (i = device; i < total_devices; ++i)
 			devices[i]->cutofftemp = val;
@@ -768,7 +779,7 @@ static struct opt_table opt_config_table[] = {
 			opt_hidden
 #endif
 	),
-#if defined(WANT_CPUMINE) && (defined(HAVE_OPENCL) || defined(USE_BITFORCE) || defined(USE_ICARUS))
+#if defined(WANT_CPUMINE) && (defined(HAVE_OPENCL) || defined(USE_FPGA))
 	OPT_WITHOUT_ARG("--enable-cpu|-C",
 			opt_set_bool, &opt_usecpu,
 			"Enable CPU mining with other mining (default: no CPU mining if other devices exist)"),
@@ -818,9 +829,13 @@ static struct opt_table opt_config_table[] = {
 	OPT_WITH_ARG("--intensity|-I",
 		     set_intensity, NULL, NULL,
 		     "Intensity of GPU scanning (d or " _MIN_INTENSITY_STR " -> " _MAX_INTENSITY_STR ", default: d to maintain desktop interactivity)"),
+#endif
+#if defined(HAVE_OPENCL) || defined(HAVE_MODMINER)
 	OPT_WITH_ARG("--kernel-path|-K",
 		     opt_set_charp, opt_show_charp, &opt_kernel_path,
-	             "Specify a path to where the kernel .cl files are"),
+	             "Specify a path to where bitstream and kernel files are"),
+#endif
+#ifdef HAVE_OPENCL
 	OPT_WITH_ARG("--kernel|-k",
 		     set_kernel, NULL, NULL,
 		     "Override kernel to use (diablo, poclbm, phatk or diakgcn) - one value or comma separated"),
@@ -899,7 +914,7 @@ static struct opt_table opt_config_table[] = {
 	OPT_WITHOUT_ARG("--round-robin",
 		     set_rr, &pool_strategy,
 		     "Change multipool strategy from failover to round robin on failure"),
-#if defined(USE_BITFORCE) || defined(USE_ICARUS)
+#ifdef USE_FPGA_SERIAL
 	OPT_WITH_ARG("--scan-serial|-S",
 		     add_serial, NULL, NULL,
 		     "Serial port to probe for FPGA Mining device"),
@@ -927,7 +942,7 @@ static struct opt_table opt_config_table[] = {
 			opt_set_bool, &use_syslog,
 			"Use system log for output messages (default: standard error)"),
 #endif
-#if defined(HAVE_ADL) || defined(USE_BITFORCE)
+#if defined(HAVE_ADL) || defined(USE_BITFORCE) || defined(USE_MODMINER)
 	OPT_WITH_ARG("--temp-cutoff",
 		     set_temp_cutoff, opt_show_intval, &opt_cutofftemp,
 		     "Temperature where a device will be automatically disabled, one value or comma separated list"),
@@ -1126,6 +1141,9 @@ static char *opt_verusage_and_exit(const char *extra)
 #ifdef USE_ICARUS
 		"icarus "
 #endif
+#ifdef USE_MODMINER
+		"modminer "
+#endif
 #ifdef USE_ZTEX
 		"ztex "
 #endif
@@ -3729,15 +3747,21 @@ bool hashtest(const struct work *work)
 
 }
 
-bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
+bool test_nonce(struct work *work, uint32_t nonce)
 {
 	work->data[64 + 12 + 0] = (nonce >> 0) & 0xff;
 	work->data[64 + 12 + 1] = (nonce >> 8) & 0xff;
 	work->data[64 + 12 + 2] = (nonce >> 16) & 0xff;
 	work->data[64 + 12 + 3] = (nonce >> 24) & 0xff;
 
+	return hashtest(work);
+}
+
+bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
+{
 	/* Do one last check before attempting to submit the work */
-	if (!hashtest(work)) {
+	/* Side effect: sets work->data for us */
+	if (!test_nonce(work, nonce)) {
 		applog(LOG_INFO, "Share below target");
 		return true;
 	}
@@ -3773,7 +3797,7 @@ void *miner_thread(void *userdata)
 	unsigned long long hashes_done = 0;
 	unsigned long long hashes;
 	struct work *work = make_work();
-	unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
+	const time_t request_interval = opt_scantime * 2 / 3 ? : 1;
 	unsigned const long request_nonce = MAXTHREADS / 3 * 2;
 	bool requested = false;
 	pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
@@ -3944,6 +3968,7 @@ disabled:
 				tq_pop(mythr->q, NULL); /* Ignore ping that's popped */
 				thread_reportin(mythr);
 				applog(LOG_WARNING, "Thread %d being re-enabled", thr_id);
+				if (api->thread_enable) api->thread_enable(mythr);
 			}
 
 			sdiff.tv_sec = sdiff.tv_usec = 0;
@@ -4293,7 +4318,7 @@ static void *watchdog_thread(void __maybe_unused *userdata)
 
 		for (i = 0; i < total_devices; ++i) {
 			struct cgpu_info *cgpu = devices[i];
-			struct thr_info *thr = cgpu->thread;
+			struct thr_info *thr = cgpu->thr[0];
 			enum dev_enable *denable;
 			int gpu;
 			
@@ -4719,6 +4744,10 @@ extern struct device_api bitforce_api;
 extern struct device_api icarus_api;
 #endif
 
+#ifdef USE_MODMINER
+extern struct device_api modminer_api;
+#endif
+
 #ifdef USE_ZTEX
 extern struct device_api ztex_api;
 #endif
@@ -4961,6 +4990,10 @@ int main(int argc, char *argv[])
 	bitforce_api.api_detect();
 #endif
 
+#ifdef USE_MODMINER
+	modminer_api.api_detect();
+#endif
+
 #ifdef USE_ZTEX
 	ztex_api.api_detect();
 #endif
@@ -5174,6 +5207,8 @@ begin_bench:
 	k = 0;
 	for (i = 0; i < total_devices; ++i) {
 		struct cgpu_info *cgpu = devices[i];
+		cgpu->thr = malloc(sizeof(*cgpu->thr) * (cgpu->threads+1));
+		cgpu->thr[cgpu->threads] = NULL;
 
 		for (j = 0; j < cgpu->threads; ++j, ++k) {
 			thr = &thr_info[k];
@@ -5201,7 +5236,7 @@ begin_bench:
 			if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
 				quit(1, "thread %d create failed", thr->id);
 
-			cgpu->thread = thr;
+			cgpu->thr[j] = thr;
 		}
 	}
 
diff --git a/configure.ac b/configure.ac
index 685deac..5cfb9ff 100644
--- a/configure.ac
+++ b/configure.ac
@@ -209,6 +209,17 @@ if test "x$icarus" = xyes; then
 fi
 AM_CONDITIONAL([HAS_ICARUS], [test x$icarus = xyes])
 
+modminer="no"
+
+AC_ARG_ENABLE([modminer],
+	[AC_HELP_STRING([--enable-modminer],[Compile support for ModMiner FPGAs(default disabled)])],
+	[modminer=$enableval]
+	)
+if test "x$modminer" = xyes; then
+	AC_DEFINE([USE_MODMINER], [1], [Defined to 1 if ModMiner support is wanted])
+fi
+AM_CONDITIONAL([HAS_MODMINER], [test x$modminer = xyes])
+
 ztex="no"
 
 AC_ARG_ENABLE([ztex],
@@ -245,6 +256,7 @@ else
 fi
 
 
+AM_CONDITIONAL([NEED_FPGAUTILS], [test x$icarus$bitforce$modminer$ztex != xnononono])
 AM_CONDITIONAL([HAVE_CURSES], [test x$curses = xyes])
 AM_CONDITIONAL([WANT_JANSSON], [test x$request_jansson = xtrue])
 AM_CONDITIONAL([HAVE_WINDOWS], [test x$have_win32 = xtrue])
@@ -293,7 +305,7 @@ fi
 
 AM_CONDITIONAL([HAS_YASM], [test x$has_yasm = xtrue])
 
-if test "x$bitforce" != xno; then
+if test "x$bitforce$modminer" != xnono; then
 	AC_ARG_WITH([libudev], [AC_HELP_STRING([--without-libudev], [Autodetect FPGAs using libudev (default enabled)])],
 		[libudev=$withval],
 		[libudev=auto]
@@ -415,13 +427,13 @@ if test "x$opencl" != xno; then
 		echo "  OpenCL...............: FOUND. GPU mining support enabled"
 	else
 		echo "  OpenCL...............: NOT FOUND. GPU mining support DISABLED"
-		if test "x$cpumining$bitforce$icarus$ztex" = xnononono; then
+		if test "x$cpumining$bitforce$icarus$ztex$modminer" = xnonononono; then
 			AC_MSG_ERROR([No mining configured in])
 		fi
 	fi
 else
 	echo "  OpenCL...............: Detection overrided. GPU mining support DISABLED"
-	if test "x$cpumining$bitforce$icarus$ztex" = xnononono; then
+	if test "x$cpumining$bitforce$icarus$ztex$modminer" = xnonononono; then
 		AC_MSG_ERROR([No mining configured in])
 	fi
 fi
@@ -449,13 +461,19 @@ else
 	echo "  Icarus.FPGAs.........: Disabled"
 fi
 
+if test "x$modminer" = xyes; then
+	echo "  ModMiner.FPGAs.......: Enabled"
+else
+	echo "  ModMiner.FPGAs.......: Disabled"
+fi
+
 if test "x$ztex" = xyes; then
 	echo "  Ztex.FPGAs...........: Enabled"
 else
 	echo "  Ztex.FPGAs...........: Disabled"
 fi
 
-if test "x$bitforce" != xno; then
+if test "x$bitforce$modminer" != xnono; then
 	echo "  libudev.detection....: $libudev"
 fi
 
diff --git a/driver-bitforce.c b/driver-bitforce.c
index e930d14..61d7c0c 100644
--- a/driver-bitforce.c
+++ b/driver-bitforce.c
@@ -13,65 +13,22 @@
 #include <stdio.h>
 #include <strings.h>
 #include <sys/time.h>
-#include <sys/types.h>
-#include <dirent.h>
-#ifndef WIN32
-#include <termios.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#ifndef O_CLOEXEC
-#define O_CLOEXEC 0
-#endif
-#else
-#include <windows.h>
-#include <io.h>
-#endif
 #include <unistd.h>
 
 #include "config.h"
 
-#ifdef HAVE_LIBUDEV
-#include <libudev.h>
-#endif
-
-#include "elist.h"
+#include "fpgautils.h"
 #include "miner.h"
 
-#define BITFORCE_SLEEP_US 4500000
-#define BITFORCE_SLEEP_MS (BITFORCE_SLEEP_US/1000)
-#define BITFORCE_TIMEOUT_MS 30000
+#define BITFORCE_SLEEP_MS 2000
+#define BITFORCE_TIMEOUT_MS 15000
+#define BITFORCE_CHECK_INTERVAL_MS 10
+#define WORK_CHECK_INTERVAL_MS 50
+#define MAX_START_DELAY_US 100000
 
 struct device_api bitforce_api;
 
-static int BFopen(const char *devpath)
-{
-#ifdef WIN32
-	HANDLE hSerial = CreateFile(devpath, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
-	if (unlikely(hSerial == INVALID_HANDLE_VALUE))
-		return -1;
-	
-	COMMTIMEOUTS cto = {30000, 0, 30000, 0, 30000};
-	SetCommTimeouts(hSerial, &cto);
-	
-	return _open_osfhandle((LONG)hSerial, 0);
-#else
-	int fdDev = open(devpath, O_RDWR | O_CLOEXEC | O_NOCTTY);
-	if (likely(fdDev != -1)) {
-		struct termios pattr;
-		
-		tcgetattr(fdDev, &pattr);
-		pattr.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
-		pattr.c_oflag &= ~OPOST;
-		pattr.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
-		pattr.c_cflag &= ~(CSIZE | PARENB);
-		pattr.c_cflag |= CS8;
-		tcsetattr(fdDev, TCSANOW, &pattr);
-	}
-	tcflush(fdDev, TCOFLUSH);
-	tcflush(fdDev, TCIFLUSH);
-	return fdDev;
-#endif
-}
+#define BFopen(devpath)  serial_open(devpath, 0, -1, true)
 
 static void BFgets(char *buf, size_t bufLen, int fd)
 {
@@ -89,7 +46,7 @@ static ssize_t BFwrite2(int fd, const void *buf, ssize_t bufLen)
 
 #define BFwrite(fd, buf, bufLen)  do {  \
 	if ((bufLen) != BFwrite2(fd, buf, bufLen)) {  \
-		applog(LOG_ERR, "Error writing to BitForce (" #buf ")");  \
+		applog(LOG_ERR, "BFL: Error writing (" #buf ")");  \
 		return 0;  \
 	}  \
 } while(0)
@@ -101,23 +58,20 @@ static bool bitforce_detect_one(const char *devpath)
 	char *s;
 	char pdevbuf[0x100];
 
-	if (total_devices == MAX_DEVICES)
-		return false;
-
 	int fdDev = BFopen(devpath);
 	if (unlikely(fdDev == -1)) {
-		applog(LOG_ERR, "BitForce Detect: Failed to open %s", devpath);
+		applog(LOG_ERR, "BFL: Failed to open %s", devpath);
 		return false;
 	}
 	BFwrite(fdDev, "ZGX", 3);
 	BFgets(pdevbuf, sizeof(pdevbuf), fdDev);
 	if (unlikely(!pdevbuf[0])) {
-		applog(LOG_ERR, "Error reading from BitForce (ZGX)");
+		applog(LOG_ERR, "BFL: Error reading (ZGX)");
 		return 0;
 	}
 	BFclose(fdDev);
 	if (unlikely(!strstr(pdevbuf, "SHA256"))) {
-		applog(LOG_ERR, "BitForce Detect: Didn't recognise BitForce on %s", devpath);
+		applog(LOG_ERR, "BFL: Didn't recognise BitForce on %s", devpath);
 		return false;
 	}
 
@@ -128,114 +82,29 @@ static bool bitforce_detect_one(const char *devpath)
 	bitforce->device_path = strdup(devpath);
 	bitforce->deven = DEV_ENABLED;
 	bitforce->threads = 1;
+	bitforce->sleep_ms = BITFORCE_SLEEP_MS;
 	if (likely((!memcmp(pdevbuf, ">>>ID: ", 7)) && (s = strstr(pdevbuf + 3, ">>>"))))
 	{
 		s[0] = '\0';
 		bitforce->name = strdup(pdevbuf + 7);
 	}
 	
-	mutex_init(&bitforce->dev_lock);
+	mutex_init(&bitforce->device_mutex);
 
 	return add_cgpu(bitforce);
 }
 
-static bool bitforce_detect_auto_udev()
-{
-#ifdef HAVE_LIBUDEV
-	struct udev *udev = udev_new();
-	struct udev_enumerate *enumerate = udev_enumerate_new(udev);
-	struct udev_list_entry *list_entry;
-	bool foundany = false;
-	
-	udev_enumerate_add_match_subsystem(enumerate, "tty");
-	udev_enumerate_add_match_property(enumerate, "ID_MODEL", "BitFORCE*SHA256");
-	udev_enumerate_scan_devices(enumerate);
-	udev_list_entry_foreach(list_entry, udev_enumerate_get_list_entry(enumerate)) {
-		struct udev_device *device = udev_device_new_from_syspath(
-			udev_enumerate_get_udev(enumerate),
-			udev_list_entry_get_name(list_entry)
-		);
-		if (!device)
-			continue;
-		
-		const char *devpath = udev_device_get_devnode(device);
-		if (devpath) {
-			foundany = true;
-			bitforce_detect_one(devpath);
-		}
-		
-		udev_device_unref(device);
-	}
-	udev_enumerate_unref(enumerate);
-	udev_unref(udev);
-	
-	return foundany;
-#else
-	return false;
-#endif
-}
-
-static bool bitforce_detect_auto_devserial()
+static char bitforce_detect_auto()
 {
-#ifndef WIN32
-	DIR *D;
-	struct dirent *de;
-	const char udevdir[] = "/dev/serial/by-id";
-	char devpath[sizeof(udevdir) + 1 + NAME_MAX];
-	char *devfile = devpath + sizeof(udevdir);
-	bool foundany = false;
-	
-	D = opendir(udevdir);
-	if (!D)
-		return false;
-	memcpy(devpath, udevdir, sizeof(udevdir) - 1);
-	devpath[sizeof(udevdir) - 1] = '/';
-	while ( (de = readdir(D)) ) {
-		if (!strstr(de->d_name, "BitFORCE_SHA256"))
-			continue;
-		foundany = true;
-		strcpy(devfile, de->d_name);
-		bitforce_detect_one(devpath);
-	}
-	closedir(D);
-	
-	return foundany;
-#else
-	return false;
-#endif
-}
-
-static void bitforce_detect_auto()
-{
-	bitforce_detect_auto_udev() ?:
-	bitforce_detect_auto_devserial() ?:
+	return
+	serial_autodetect_udev     (bitforce_detect_one, "BitFORCE*SHA256") ?:
+	serial_autodetect_devserial(bitforce_detect_one, "BitFORCE_SHA256") ?:
 	0;
 }
 
 static void bitforce_detect()
 {
-	struct string_elist *iter, *tmp;
-	const char*s;
-	bool found = false;
-	bool autoscan = false;
-
-	list_for_each_entry_safe(iter, tmp, &scan_devices, list) {
-		s = iter->string;
-		if (!strncmp("bitforce:", iter->string, 9))
-			s += 9;
-		if (!strcmp(s, "auto"))
-			autoscan = true;
-		else
-		if (!strcmp(s, "noauto"))
-			found = true;
-		else if (bitforce_detect_one(s)) {
-			string_elist_del(iter);
-			found = true;
-		}
-	}
-
-	if (autoscan || !found)
-		bitforce_detect_auto();
+	serial_detect_auto("bitforce", bitforce_detect_one, bitforce_detect_auto);
 }
 
 static void get_bitforce_statline_before(char *buf, struct cgpu_info *bitforce)
@@ -256,13 +125,13 @@ static bool bitforce_thread_prepare(struct thr_info *thr)
 
 	int fdDev = BFopen(bitforce->device_path);
 	if (unlikely(-1 == fdDev)) {
-		applog(LOG_ERR, "Failed to open BitForce on %s", bitforce->device_path);
+		applog(LOG_ERR, "BFL%i: Failed to open %s", bitforce->device_id, bitforce->device_path);
 		return false;
 	}
 
 	bitforce->device_fd = fdDev;
 
-	applog(LOG_INFO, "Opened BitForce on %s", bitforce->device_path);
+	applog(LOG_INFO, "BFL%i: Opened %s", bitforce->device_id, bitforce->device_path);
 	gettimeofday(&now, NULL);
 	get_datestamp(bitforce->init, &now);
 
@@ -276,28 +145,33 @@ static bool bitforce_init(struct cgpu_info *bitforce)
 	char pdevbuf[0x100];
 	char *s;
 
-	BFclose(fdDev);
+	applog(LOG_INFO, "BFL%i: Re-initalizing", bitforce->device_id);
+
+	if (fdDev) {
+		BFclose(fdDev);
+		bitforce->device_fd = 0;
+	}
 
 	fdDev = BFopen(devpath);
 	if (unlikely(fdDev == -1)) {
-		applog(LOG_ERR, "BitForce init: Failed to open %s", devpath);
+		applog(LOG_ERR, "BFL%i: Failed to open %s", bitforce->device_id, devpath);
 		return false;
 	}
 
 	bitforce->device_fd = fdDev;
 
-	mutex_lock(&bitforce->dev_lock);
+	mutex_lock(&bitforce->device_mutex);
 	BFwrite(fdDev, "ZGX", 3);
 	BFgets(pdevbuf, sizeof(pdevbuf), fdDev);
-	mutex_unlock(&bitforce->dev_lock);
+	mutex_unlock(&bitforce->device_mutex);
 	
 	if (unlikely(!pdevbuf[0])) {
-		applog(LOG_ERR, "Error reading from BitForce (ZGX)");
+		applog(LOG_ERR, "BFL%i: Error reading (ZGX)", bitforce->device_id);
 		return false;
 	}
 
 	if (unlikely(!strstr(pdevbuf, "SHA256"))) {
-		applog(LOG_ERR, "BitForce init: Didn't recognise BitForce on %s", devpath);
+		applog(LOG_ERR, "BFL%i: Didn't recognise BitForce on %s", bitforce->device_id, devpath);
 		return false;
 	}
 	
@@ -316,13 +190,13 @@ static bool bitforce_get_temp(struct cgpu_info *bitforce)
 	char pdevbuf[0x100];
 	char *s;
 
-	mutex_lock(&bitforce->dev_lock);
+	mutex_lock(&bitforce->device_mutex);
 	BFwrite(fdDev, "ZLX", 3);
 	BFgets(pdevbuf, sizeof(pdevbuf), fdDev);
-	mutex_unlock(&bitforce->dev_lock);
+	mutex_unlock(&bitforce->device_mutex);
 	
 	if (unlikely(!pdevbuf[0])) {
-		applog(LOG_ERR, "Error reading temp from BitForce (ZLX)");
+		applog(LOG_ERR, "BFL%i: Error reading (ZLX)", bitforce->device_id);
 		return false;
 	}
 	if ((!strncasecmp(pdevbuf, "TEMP", 4)) && (s = strchr(pdevbuf + 4, ':'))) {
@@ -330,7 +204,7 @@ static bool bitforce_get_temp(struct cgpu_info *bitforce)
 		if (temp > 0) {
 			bitforce->temp = temp;
 			if (temp > bitforce->cutofftemp) {
-				applog(LOG_WARNING, "Hit thermal cutoff limit on %s %d, disabling!", bitforce->api->name, bitforce->device_id);
+				applog(LOG_WARNING, "BFL%i: Hit thermal cutoff limit, disabling!", bitforce->device_id);
 				bitforce->deven = DEV_RECOVER;
 
 				bitforce->device_last_not_well = time(NULL);
@@ -350,17 +224,22 @@ static bool bitforce_send_work(struct thr_info *thr, struct work *work)
 	unsigned char ob[61] = ">>>>>>>>12345678901234567890123456789012123456789012>>>>>>>>";
 	char *s;
 
-	mutex_lock(&bitforce->dev_lock);
+	mutex_lock(&bitforce->device_mutex);
 	BFwrite(fdDev, "ZDX", 3);
 	BFgets(pdevbuf, sizeof(pdevbuf), fdDev);
 	if (unlikely(!pdevbuf[0])) {
-		applog(LOG_ERR, "Error reading from BitForce (ZDX)");
-		mutex_unlock(&bitforce->dev_lock);
+		applog(LOG_ERR, "BFL%i: Error reading (ZDX)", bitforce->device_id);
+		mutex_unlock(&bitforce->device_mutex);
 		return false;
 	}
-	if (unlikely(pdevbuf[0] != 'O' || pdevbuf[1] != 'K')) {
-		applog(LOG_ERR, "BitForce ZDX reports: %s", pdevbuf);
-		mutex_unlock(&bitforce->dev_lock);
+	if (pdevbuf[0] == 'B'){
+		applog(LOG_WARNING, "BFL%i: Throttling", bitforce->device_id);
+		mutex_unlock(&bitforce->device_mutex);
+		return true;
+	}
+	else if (unlikely(pdevbuf[0] != 'O' || pdevbuf[1] != 'K')) {
+		applog(LOG_ERR, "BFL%i: ZDX reports: %s", bitforce->device_id, pdevbuf);
+		mutex_unlock(&bitforce->device_mutex);
 		return false;
 	}
 	memcpy(ob + 8, work->midstate, 32);
@@ -369,17 +248,17 @@ static bool bitforce_send_work(struct thr_info *thr, struct work *work)
 	BFwrite(fdDev, ob, 60);
 	if (opt_debug) {
 		s = bin2hex(ob + 8, 44);
-		applog(LOG_DEBUG, "BitForce block data: %s", s);
+		applog(LOG_DEBUG, "BFL%i: block data: %s", bitforce->device_id, s);
 		free(s);
 	}
 	BFgets(pdevbuf, sizeof(pdevbuf), fdDev);
-	mutex_unlock(&bitforce->dev_lock);
+	mutex_unlock(&bitforce->device_mutex);
 	if (unlikely(!pdevbuf[0])) {
-		applog(LOG_ERR, "Error reading from BitForce (block data)");
+		applog(LOG_ERR, "BFL%i: Error reading (block data)", bitforce->device_id);
 		return false;
 	}
 	if (unlikely(pdevbuf[0] != 'O' || pdevbuf[1] != 'K')) {
-		applog(LOG_ERR, "BitForce block data reports: %s", pdevbuf);
+		applog(LOG_ERR, "BFL%i: block data reports: %s", bitforce->device_id, pdevbuf);
 		return false;
 	}
 	return true;
@@ -393,41 +272,45 @@ static uint64_t bitforce_get_result(struct thr_info *thr, struct work *work)
 	char pdevbuf[0x100];
 	char *pnoncebuf;
 	uint32_t nonce;
-	int i;
 
-	i = BITFORCE_SLEEP_MS;
-	while (i < BITFORCE_TIMEOUT_MS) {
-    	mutex_lock(&bitforce->dev_lock);
+	while (bitforce->wait_ms < BITFORCE_TIMEOUT_MS) {
+		mutex_lock(&bitforce->device_mutex);
 		BFwrite(fdDev, "ZFX", 3);
 		BFgets(pdevbuf, sizeof(pdevbuf), fdDev);
-	    mutex_unlock(&bitforce->dev_lock);
+		mutex_unlock(&bitforce->device_mutex);
 		if (unlikely(!pdevbuf[0])) {
-			applog(LOG_ERR, "Error reading from BitForce (ZFX)");
-	    	mutex_unlock(&bitforce->dev_lock);
+			applog(LOG_ERR, "BFL%i: Error reading (ZFX)", bitforce->device_id);
+			mutex_unlock(&bitforce->device_mutex);
 			return 0;
 		}
 		if (pdevbuf[0] != 'B')
 			break;
-		usleep(10000);
-		i += 10;
+		usleep(BITFORCE_CHECK_INTERVAL_MS*1000);
+		bitforce->wait_ms += BITFORCE_CHECK_INTERVAL_MS;
 	}
-
-	if (i >= BITFORCE_TIMEOUT_MS) {
-		applog(LOG_ERR, "BitForce took longer than 30s");
+	if (bitforce->wait_ms >= BITFORCE_TIMEOUT_MS) {
+		applog(LOG_ERR, "BFL%i took longer than 15s");
 		bitforce->device_last_not_well = time(NULL);
 		bitforce->device_not_well_reason = REASON_THREAD_ZERO_HASH;
 		bitforce->thread_zero_hash_count++;
 		return 1;
+	} else {
+	    /* Simple timing adjustment */
+		// applog(LOG_WARNING, "BFL%i: Waited: %ums, sleep is:%ums", bitforce->device_id, bitforce->wait_ms, bitforce->sleep_ms);
+		if (bitforce->wait_ms > (bitforce->sleep_ms + WORK_CHECK_INTERVAL_MS))
+			bitforce->sleep_ms += WORK_CHECK_INTERVAL_MS;
+		else if (bitforce->wait_ms == bitforce->sleep_ms)
+			bitforce->sleep_ms -= WORK_CHECK_INTERVAL_MS;		
 	}
 
-	applog(LOG_DEBUG, "BitForce waited %dms until %s\n", i, pdevbuf);
+	applog(LOG_DEBUG, "BFL%i: waited %dms until %s", bitforce->device_id, bitforce->wait_ms, pdevbuf);
 	work->blk.nonce = 0xffffffff;
 	if (pdevbuf[2] == '-') 
 		return 0xffffffff;   /* No valid nonce found */
 	else if (pdevbuf[0] == 'I') 
 		return 1;          /* Device idle */
 	else if (strncasecmp(pdevbuf, "NONCE-FOUND", 11)) {
-		applog(LOG_WARNING, "BitForce result reports: %s", pdevbuf);
+		applog(LOG_WARNING, "BFL%i: result reports: %s", bitforce->device_id, pdevbuf);
 		return 1;
 	}
 
@@ -451,36 +334,35 @@ static uint64_t bitforce_get_result(struct thr_info *thr, struct work *work)
 static void bitforce_shutdown(struct thr_info *thr)
 {
 	struct cgpu_info *bitforce = thr->cgpu;
-	int fdDev = bitforce->device_fd;
 
-	BFclose(fdDev);
+	BFclose(bitforce->device_fd);
+	bitforce->device_fd = 0;
 }
 
-static uint64_t bitforce_scanhash(struct thr_info *thr, struct work *work, uint64_t __maybe_unused max_nonce)
+static void biforce_thread_enable(struct thr_info *thr)
 {
 	struct cgpu_info *bitforce = thr->cgpu;
-	bool dev_enabled = (bitforce->deven == DEV_ENABLED);
-	static enum dev_enable last_dev_state = DEV_ENABLED;
-	
-	if (bitforce->deven == DEV_DISABLED) {
-		bitforce_shutdown(thr);
-		return 1;
-	}
-	
-	// if device has just gone from disabled to enabled, re-initialise it
-	if (last_dev_state == DEV_DISABLED && dev_enabled)
-		bitforce_init(bitforce);
 
-	if (dev_enabled)
-		if (!bitforce_send_work(thr, work))
-			return 0;
+	bitforce_init(bitforce);
+}
 
-	usleep(BITFORCE_SLEEP_US);
+static uint64_t bitforce_scanhash(struct thr_info *thr, struct work *work, uint64_t __maybe_unused max_nonce)
+{
+	struct cgpu_info *bitforce = thr->cgpu;
+	bitforce->wait_ms = 0;
 
-	if (dev_enabled)
-		return bitforce_get_result(thr, work);
-	else
-		return 1;
+	if (!bitforce_send_work(thr, work))
+		return 0;
+	
+	while (bitforce->wait_ms < bitforce->sleep_ms) {
+		usleep(WORK_CHECK_INTERVAL_MS*1000);
+		bitforce->wait_ms += WORK_CHECK_INTERVAL_MS;
+		if (work_restart[thr->id].restart) {
+			applog(LOG_DEBUG, "BFL%i: Work restart, discarding after %dms", bitforce->device_id, bitforce->wait_ms);
+			return 1; //we have discarded all work; equivilent to 0 hashes done.
+		}
+	}
+	return bitforce_get_result(thr, work);
 }
 
 static bool bitforce_get_stats(struct cgpu_info *bitforce)
@@ -488,13 +370,29 @@ static bool bitforce_get_stats(struct cgpu_info *bitforce)
 	return bitforce_get_temp(bitforce);
 }
 
+static bool bitforce_thread_init(struct thr_info *thr)
+{
+	unsigned int wait;
+	thr;
+	/* Pause each new thread a random time between 0-100ms 
+	so the devices aren't making calls all at the same time. */
+	wait = (rand() * MAX_START_DELAY_US)/RAND_MAX;
+	applog(LOG_DEBUG, "BFL%i: Delaying start by %dms", bitforce->device_id, wait/1000);
+	usleep(wait);
+
+	return true;
+}
+
 struct device_api bitforce_api = {
 	.dname = "bitforce",
 	.name = "BFL",
 	.api_detect = bitforce_detect,
+	.reinit_device = bitforce_init,
 	.get_statline_before = get_bitforce_statline_before,
 	.get_stats = bitforce_get_stats,
 	.thread_prepare = bitforce_thread_prepare,
+	.thread_init = bitforce_thread_init,
 	.scanhash = bitforce_scanhash,
-	.thread_shutdown = bitforce_shutdown
+	.thread_shutdown = bitforce_shutdown,
+	.thread_enable = biforce_thread_enable
 };
diff --git a/driver-icarus.c b/driver-icarus.c
index 75ab5e3..ee9800c 100644
--- a/driver-icarus.c
+++ b/driver-icarus.c
@@ -49,6 +49,7 @@
 #endif
 
 #include "elist.h"
+#include "fpgautils.h"
 #include "miner.h"
 
 // The serial I/O speed - Linux uses a define 'B115200' in bits/termios.h
@@ -69,10 +70,8 @@ ASSERT1(sizeof(uint32_t) == 4);
 // Fraction of a second, USB timeout is measured in
 // i.e. 10 means 1/10 of a second
 #define TIME_FACTOR 10
-// In Linux it's 10 per second, thus value = 10/TIME_FACTOR =
-#define LINUX_TIMEOUT_VALUE 1
-// In Windows it's 1000 per second, thus value = 1000/TIME_FACTOR =
-#define WINDOWS_TIMEOUT_VALUE 100
+// It's 10 per second, thus value = 10/TIME_FACTOR =
+#define ICARUS_READ_FAULT_DECISECONDS 1
 
 // In timing mode: Default starting value until an estimate can be obtained
 // 5 seconds allows for up to a ~840MH/s device
@@ -196,63 +195,8 @@ static void rev(unsigned char *s, size_t l)
 	}
 }
 
-static int icarus_open(const char *devpath)
-{
-#ifndef WIN32
-	struct termios my_termios;
-
-	int serialfd = open(devpath, O_RDWR | O_CLOEXEC | O_NOCTTY);
-
-	if (serialfd == -1)
-		return -1;
-
-	tcgetattr(serialfd, &my_termios);
-	my_termios.c_cflag = B115200;
-	my_termios.c_cflag |= CS8;
-	my_termios.c_cflag |= CREAD;
-	my_termios.c_cflag |= CLOCAL;
-	my_termios.c_cflag &= ~(CSIZE | PARENB);
-
-	my_termios.c_iflag &= ~(IGNBRK | BRKINT | PARMRK |
-				ISTRIP | INLCR | IGNCR | ICRNL | IXON);
-	my_termios.c_oflag &= ~OPOST;
-	my_termios.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
-	my_termios.c_cc[VTIME] = LINUX_TIMEOUT_VALUE; /* how long to block */
-	my_termios.c_cc[VMIN] = 0;
-	tcsetattr(serialfd, TCSANOW, &my_termios);
-
-	tcflush(serialfd, TCOFLUSH);
-	tcflush(serialfd, TCIFLUSH);
-
-	return serialfd;
-#else
-	COMMCONFIG comCfg;
-
-	HANDLE hSerial = CreateFile(devpath, GENERIC_READ | GENERIC_WRITE, 0,
-				    NULL, OPEN_EXISTING, 0, NULL);
-	if (unlikely(hSerial == INVALID_HANDLE_VALUE))
-		return -1;
-
-	// thanks to af_newbie for pointers about this
-	memset(&comCfg, 0 , sizeof(comCfg));
-	comCfg.dwSize = sizeof(COMMCONFIG);
-	comCfg.wVersion = 1;
-	comCfg.dcb.DCBlength = sizeof(DCB);
-	comCfg.dcb.BaudRate = ICARUS_IO_SPEED;
-	comCfg.dcb.fBinary = 1;
-	comCfg.dcb.fDtrControl = DTR_CONTROL_ENABLE;
-	comCfg.dcb.fRtsControl = RTS_CONTROL_ENABLE;
-	comCfg.dcb.ByteSize = 8;
-
-	SetCommConfig(hSerial, &comCfg, sizeof(comCfg));
-
-	// How long to block
-	COMMTIMEOUTS cto = {WINDOWS_TIMEOUT_VALUE, 0, WINDOWS_TIMEOUT_VALUE, 0, WINDOWS_TIMEOUT_VALUE};
-	SetCommTimeouts(hSerial, &cto);
-
-	return _open_osfhandle((LONG)hSerial, 0);
-#endif
-}
+#define icarus_open2(devpath, purge)  serial_open(devpath, 115200, ICARUS_READ_FAULT_DECISECONDS, purge)
+#define icarus_open(devpath)  icarus_open2(devpath, false)
 
 static int icarus_gets(unsigned char *buf, int fd, struct timeval *tv_finish, int thr_id, int read_count)
 {
@@ -435,10 +379,7 @@ static bool icarus_detect_one(const char *devpath)
 	unsigned char ob_bin[64], nonce_bin[ICARUS_READ_SIZE];
 	char *nonce_hex;
 
-	if (total_devices == MAX_DEVICES)
-		return false;
-
-	fd = icarus_open(devpath);
+	fd = icarus_open2(devpath, true);
 	if (unlikely(fd == -1)) {
 		applog(LOG_ERR, "Icarus Detect: Failed to open %s", devpath);
 		return false;
@@ -503,18 +444,7 @@ static bool icarus_detect_one(const char *devpath)
 
 static void icarus_detect()
 {
-	struct string_elist *iter, *tmp;
-	const char*s;
-
-	list_for_each_entry_safe(iter, tmp, &scan_devices, list) {
-		s = iter->string;
-		if (!strncmp("icarus:", iter->string, 7))
-			s += 7;
-		if (!strcmp(s, "auto") || !strcmp(s, "noauto"))
-			continue;
-		if (icarus_detect_one(s))
-			string_elist_del(iter);
-	}
+	serial_detect("icarus", icarus_detect_one);
 }
 
 static bool icarus_prepare(struct thr_info *thr)
diff --git a/driver-modminer.c b/driver-modminer.c
new file mode 100644
index 0000000..d139091
--- /dev/null
+++ b/driver-modminer.c
@@ -0,0 +1,541 @@
+/*
+ * Copyright 2012 Luke Dashjr
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 3 of the License, or (at your option)
+ * any later version.  See COPYING for more details.
+ */
+
+#include "config.h"
+
+#include <stdarg.h>
+#include <stdio.h>
+#include <unistd.h>
+
+#include "fpgautils.h"
+#include "logging.h"
+#include "miner.h"
+
+#define BITSTREAM_FILENAME "fpgaminer_top_fixed7_197MHz.ncd"
+#define BISTREAM_USER_ID "\2\4$B"
+
+struct device_api modminer_api;
+
+static inline bool
+_bailout(int fd, struct cgpu_info*modminer, int prio, const char *fmt, ...)
+{
+	if (fd != -1)
+		serial_close(fd);
+	if (modminer) {
+		modminer->device_fd = -1;
+		mutex_unlock(&modminer->device_mutex);
+	}
+
+	va_list ap;
+	va_start(ap, fmt);
+	vapplog(prio, fmt, ap);
+	va_end(ap);
+	return false;
+}
+#define bailout(...)  return _bailout(fd, NULL, __VA_ARGS__);
+
+static bool
+modminer_detect_one(const char *devpath)
+{
+	int fd = serial_open(devpath, 0, 10, true);
+	if (unlikely(fd == -1))
+		bailout(LOG_DEBUG, "ModMiner detect: failed to open %s", devpath);
+
+	char buf[0x100];
+	size_t len;
+
+	// Sending 45 noops, just in case the device was left in "start job" reading
+	(void)(write(fd, "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff", 45) ?:0);
+	while (serial_read(fd, buf, sizeof(buf)) > 0)
+		;
+
+	if (1 != write(fd, "\x01", 1))  // Get version
+		bailout(LOG_DEBUG, "ModMiner detect: write failed on %s (get version)", devpath);
+	len = serial_read(fd, buf, sizeof(buf)-1);
+	if (len < 1)
+		bailout(LOG_DEBUG, "ModMiner detect: no response to version request from %s", devpath);
+	buf[len] = '\0';
+	char*devname = strdup(buf);
+	applog(LOG_DEBUG, "ModMiner identified as: %s", devname);
+
+	if (1 != write(fd, "\x02", 1))  // Get FPGA count
+		bailout(LOG_DEBUG, "ModMiner detect: write failed on %s (get FPGA count)", devpath);
+	len = read(fd, buf, 1);
+	if (len < 1)
+		bailout(LOG_ERR, "ModMiner detect: timeout waiting for FPGA count from %s", devpath);
+	if (!buf[0])
+		bailout(LOG_ERR, "ModMiner detect: zero FPGAs reported on %s", devpath);
+	applog(LOG_DEBUG, "ModMiner %s has %u FPGAs", devname, buf[0]);
+
+	serial_close(fd);
+
+	struct cgpu_info *modminer;
+	modminer = calloc(1, sizeof(*modminer));
+	modminer->api = &modminer_api;
+	mutex_init(&modminer->device_mutex);
+	modminer->device_path = strdup(devpath);
+	modminer->device_fd = -1;
+	modminer->deven = DEV_ENABLED;
+	modminer->threads = buf[0];
+	modminer->name = devname;
+	modminer->cutofftemp = 85;
+
+	return add_cgpu(modminer);
+}
+
+#undef bailout
+
+static char
+modminer_detect_auto()
+{
+	return
+	serial_autodetect_udev     (modminer_detect_one, "BTCFPGA*ModMiner") ?:
+	serial_autodetect_devserial(modminer_detect_one, "BTCFPGA_ModMiner") ?:
+	0;
+}
+
+static void
+modminer_detect()
+{
+	serial_detect_auto("modminer", modminer_detect_one, modminer_detect_auto);
+}
+
+#define bailout(...)  return _bailout(-1, modminer, __VA_ARGS__);
+#define bailout2(...)  return _bailout(fd, modminer, __VA_ARGS__);
+
+#define check_magic(L)  do {  \
+	if (1 != fread(buf, 1, 1, f))  \
+		bailout(LOG_ERR, "Error reading ModMiner firmware ('%c')", L);  \
+	if (buf[0] != L)  \
+		bailout(LOG_ERR, "ModMiner firmware has wrong magic ('%c')", L);  \
+} while(0)
+
+#define read_str(eng)  do {  \
+	if (1 != fread(buf, 2, 1, f))  \
+		bailout(LOG_ERR, "Error reading ModMiner firmware (" eng " len)");  \
+	len = (ubuf[0] << 8) | ubuf[1];  \
+	if (len >= sizeof(buf))  \
+		bailout(LOG_ERR, "ModMiner firmware " eng " too long");  \
+	if (1 != fread(buf, len, 1, f))  \
+		bailout(LOG_ERR, "Error reading ModMiner firmware (" eng ")");  \
+	buf[len] = '\0';  \
+} while(0)
+
+#define status_read(eng)  do {  \
+FD_SET(fd, &fds);  \
+select(fd+1, &fds, NULL, NULL, NULL);  \
+	if (1 != read(fd, buf, 1))  \
+		bailout2(LOG_ERR, "%s %u: Error programming %s (" eng ")", modminer->api->name, modminer->device_id, modminer->device_path);  \
+	if (buf[0] != 1)  \
+		bailout2(LOG_ERR, "%s %u: Wrong " eng " programming %s", modminer->api->name, modminer->device_id, modminer->device_path);  \
+} while(0)
+
+static bool
+modminer_fpga_upload_bitstream(struct cgpu_info*modminer)
+{
+fd_set fds;
+	char buf[0x100];
+	unsigned char *ubuf = (unsigned char*)buf;
+	unsigned long len;
+	char *p;
+	const char *fwfile = BITSTREAM_FILENAME;
+	char fpgaid = 4;  // "all FPGAs"
+
+	FILE *f = open_bitstream("modminer", fwfile);
+	if (!f)
+		bailout(LOG_ERR, "Error opening ModMiner firmware file %s", fwfile);
+	if (1 != fread(buf, 2, 1, f))
+		bailout(LOG_ERR, "Error reading ModMiner firmware (magic)");
+	if (buf[0] || buf[1] != 9)
+		bailout(LOG_ERR, "ModMiner firmware has wrong magic (9)");
+	if (-1 == fseek(f, 11, SEEK_CUR))
+		bailout(LOG_ERR, "ModMiner firmware seek failed");
+	check_magic('a');
+	read_str("design name");
+	applog(LOG_DEBUG, "ModMiner firmware file %s info:", fwfile);
+	applog(LOG_DEBUG, "  Design name: %s", buf);
+	p = strrchr(buf, ';') ?: buf;
+	p = strrchr(buf, '=') ?: p;
+	if (p[0] == '=')
+		++p;
+	unsigned long fwusercode = (unsigned long)strtoll(p, &p, 16);
+	if (p[0] != '\0')
+		bailout(LOG_ERR, "Bad usercode in ModMiner firmware file");
+	if (fwusercode == 0xffffffff)
+		bailout(LOG_ERR, "ModMiner firmware doesn't support user code");
+	applog(LOG_DEBUG, "  Version: %u, build %u", (fwusercode >> 8) & 0xff, fwusercode & 0xff);
+	check_magic('b');
+	read_str("part number");
+	applog(LOG_DEBUG, "  Part number: %s", buf);
+	check_magic('c');
+	read_str("build date");
+	applog(LOG_DEBUG, "  Build date: %s", buf);
+	check_magic('d');
+	read_str("build time");
+	applog(LOG_DEBUG, "  Build time: %s", buf);
+	check_magic('e');
+	if (1 != fread(buf, 4, 1, f))
+		bailout(LOG_ERR, "Error reading ModMiner firmware (data len)");
+	len = ((unsigned long)ubuf[0] << 24) | ((unsigned long)ubuf[1] << 16) | (ubuf[2] << 8) | ubuf[3];
+	applog(LOG_DEBUG, "  Bitstream size: %lu", len);
+
+	int fd = modminer->device_fd;
+
+	applog(LOG_WARNING, "%s %u: Programming %s... DO NOT EXIT CGMINER UNTIL COMPLETE", modminer->api->name, modminer->device_id, modminer->device_path);
+	buf[0] = '\x05';  // Program Bitstream
+	buf[1] = fpgaid;
+	buf[2] = (len >>  0) & 0xff;
+	buf[3] = (len >>  8) & 0xff;
+	buf[4] = (len >> 16) & 0xff;
+	buf[5] = (len >> 24) & 0xff;
+	if (6 != write(fd, buf, 6))
+		bailout2(LOG_ERR, "%s %u: Error programming %s (cmd)", modminer->api->name, modminer->device_id, modminer->device_path);
+	status_read("cmd reply");
+	ssize_t buflen;
+	while (len) {
+		buflen = len < 32 ? len : 32;
+		if (fread(buf, buflen, 1, f) != 1)
+			bailout2(LOG_ERR, "%s %u: File underrun programming %s (%d bytes left)", modminer->api->name, modminer->device_id, modminer->device_path, len);
+		if (write(fd, buf, buflen) != buflen)
+			bailout2(LOG_ERR, "%s %u: Error programming %s (data)", modminer->api->name, modminer->device_id,  modminer->device_path);
+		status_read("status");
+		len -= buflen;
+	}
+	status_read("final status");
+	applog(LOG_WARNING, "%s %u: Done programming %s", modminer->api->name, modminer->device_id, modminer->device_path);
+
+	return true;
+}
+
+static bool
+modminer_device_prepare(struct cgpu_info *modminer)
+{
+	int fd = serial_open(modminer->device_path, 0, /*FIXME=-1*/3000, true);
+	if (unlikely(-1 == fd))
+		bailout(LOG_ERR, "%s %u: Failed to open %s", modminer->api->name, modminer->device_id, modminer->device_path);
+
+	modminer->device_fd = fd;
+	applog(LOG_INFO, "%s %u: Opened %s", modminer->api->name, modminer->device_id, modminer->device_path);
+
+	struct timeval now;
+	gettimeofday(&now, NULL);
+	get_datestamp(modminer->init, &now);
+
+	return true;
+}
+
+#undef bailout
+
+struct modminer_fpga_state {
+	bool work_running;
+	struct work running_work;
+	struct timeval tv_workstart;
+	uint32_t hashes;
+
+	char next_work_cmd[46];
+
+	unsigned char clock;
+	int no_nonce_counter;
+	int good_share_counter;
+	time_t last_cutoff_reduced;
+
+	unsigned char temp;
+};
+
+static bool
+modminer_fpga_prepare(struct thr_info *thr)
+{
+	struct cgpu_info *modminer = thr->cgpu;
+
+	// Don't need to lock the mutex here, since prepare runs from the main thread before the miner threads start
+	if (modminer->device_fd == -1 && !modminer_device_prepare(modminer))
+		return false;
+
+	struct modminer_fpga_state *state;
+	state = thr->cgpu_data = calloc(1, sizeof(struct modminer_fpga_state));
+	state->next_work_cmd[0] = '\x08';  // Send Job
+	state->next_work_cmd[1] = thr->device_thread;  // FPGA id
+
+	return true;
+}
+
+static bool
+modminer_reduce_clock(struct thr_info*thr, bool needlock)
+{
+	struct cgpu_info*modminer = thr->cgpu;
+	struct modminer_fpga_state *state = thr->cgpu_data;
+	char fpgaid = thr->device_thread;
+	int fd = modminer->device_fd;
+	unsigned char cmd[6], buf[1];
+
+	if (state->clock <= 100)
+		return false;
+
+	cmd[0] = '\x06';  // set clock speed
+	cmd[1] = fpgaid;
+	cmd[2] = state->clock -= 2;
+	cmd[3] = cmd[4] = cmd[5] = '\0';
+
+	if (needlock)
+		mutex_lock(&modminer->device_mutex);
+	if (6 != write(fd, cmd, 6))
+		bailout2(LOG_ERR, "%s %u.%u: Error writing (set clock speed)", modminer->api->name, modminer->device_id, fpgaid);
+	if (serial_read(fd, &buf, 1) != 1)
+		bailout2(LOG_ERR, "%s %u.%u: Error reading (set clock speed)", modminer->api->name, modminer->device_id, fpgaid);
+	if (needlock)
+		mutex_unlock(&modminer->device_mutex);
+
+	applog(LOG_WARNING, "%s %u.%u: Setting clock speed to %u", modminer->api->name, modminer->device_id, fpgaid, state->clock);
+
+	return true;
+}
+
+static bool
+modminer_fpga_init(struct thr_info *thr)
+{
+	struct cgpu_info *modminer = thr->cgpu;
+	struct modminer_fpga_state *state = thr->cgpu_data;
+	int fd;
+	char fpgaid = thr->device_thread;
+
+	unsigned char cmd[2], buf[4];
+
+	mutex_lock(&modminer->device_mutex);
+	fd = modminer->device_fd;
+	if (fd == -1) {
+		// Died in another thread...
+		mutex_unlock(&modminer->device_mutex);
+		return false;
+	}
+
+	cmd[0] = '\x04';  // Read USER code (bitstream id)
+	cmd[1] = fpgaid;
+	if (write(fd, cmd, 2) != 2)
+		bailout2(LOG_ERR, "%s %u.%u: Error writing (read USER code)", modminer->api->name, modminer->device_id, fpgaid);
+	if (serial_read(fd, buf, 4) != 4)
+		bailout2(LOG_ERR, "%s %u.%u: Error reading (read USER code)", modminer->api->name, modminer->device_id, fpgaid);
+
+	if (memcmp(buf, BISTREAM_USER_ID, 4)) {
+		applog(LOG_ERR, "%s %u.%u: FPGA not programmed", modminer->api->name, modminer->device_id, fpgaid);
+		if (!modminer_fpga_upload_bitstream(modminer))
+			return false;
+	}
+	else
+		applog(LOG_DEBUG, "%s %u.%u: FPGA is already programmed :)", modminer->api->name, modminer->device_id, fpgaid);
+
+	state->clock = 212;  // Will be reduced to 210 by modminer_reduce_clock
+	modminer_reduce_clock(thr, false);
+
+	mutex_unlock(&modminer->device_mutex);
+
+	return true;
+}
+
+static void
+get_modminer_statline_before(char *buf, struct cgpu_info *modminer)
+{
+	char info[18] = "               | ";
+	int tc = modminer->threads;
+	bool havetemp = false;
+	int i;
+
+	if (tc > 4)
+		tc = 4;
+
+	for (i = tc - 1; i >= 0; --i) {
+		struct thr_info*thr = modminer->thr[i];
+		struct modminer_fpga_state *state = thr->cgpu_data;
+		unsigned char temp = state->temp;
+
+		info[i*3+2] = '/';
+		if (temp) {
+			havetemp = true;
+			if (temp > 9)
+				info[i*3+0] = 0x30 + (temp / 10);
+			info[i*3+1] = 0x30 + (temp % 10);
+		}
+	}
+	if (havetemp) {
+		info[tc*3-1] = ' ';
+		info[tc*3] = 'C';
+		strcat(buf, info);
+	}
+	else
+		strcat(buf, "               | ");
+}
+
+static bool
+modminer_prepare_next_work(struct modminer_fpga_state*state, struct work*work)
+{
+	char *midstate = state->next_work_cmd + 2;
+	char *taildata = midstate + 32;
+	if (!(memcmp(midstate, work->midstate, 32) || memcmp(taildata, work->data + 64, 12)))
+		return false;
+	memcpy(midstate, work->midstate, 32);
+	memcpy(taildata, work->data + 64, 12);
+	return true;
+}
+
+static bool
+modminer_start_work(struct thr_info*thr)
+{
+fd_set fds;
+	struct cgpu_info*modminer = thr->cgpu;
+	struct modminer_fpga_state *state = thr->cgpu_data;
+	char fpgaid = thr->device_thread;
+	int fd = modminer->device_fd;
+
+	char buf[1];
+
+	mutex_lock(&modminer->device_mutex);
+	if (46 != write(fd, state->next_work_cmd, 46))
+		bailout2(LOG_ERR, "%s %u.%u: Error writing (start work)", modminer->api->name, modminer->device_id, fpgaid);
+	gettimeofday(&state->tv_workstart, NULL);
+	state->hashes = 0;
+	status_read("start work");
+	mutex_unlock(&modminer->device_mutex);
+
+	return true;
+}
+
+#define work_restart(thr)  work_restart[thr->id].restart
+
+static uint64_t
+modminer_process_results(struct thr_info*thr)
+{
+	struct cgpu_info*modminer = thr->cgpu;
+	struct modminer_fpga_state *state = thr->cgpu_data;
+	char fpgaid = thr->device_thread;
+	int fd = modminer->device_fd;
+	struct work *work = &state->running_work;
+
+	char cmd[2], temperature;
+	uint32_t nonce;
+	long iter;
+	bool bad;
+	cmd[0] = '\x0a';
+	cmd[1] = fpgaid;
+
+	mutex_lock(&modminer->device_mutex);
+	if (2 == write(fd, cmd, 2) && read(fd, &temperature, 1) == 1)
+	{
+		state->temp = temperature;
+		if (!fpgaid)
+			modminer->temp = (float)temperature;
+		if (temperature > modminer->cutofftemp - 2) {
+			if (temperature > modminer->cutofftemp) {
+				applog(LOG_WARNING, "%s %u.%u: Hit thermal cutoff limit, disabling device!", modminer->api->name, modminer->device_id, fpgaid);
+				modminer->deven = DEV_RECOVER;
+
+				modminer->device_last_not_well = time(NULL);
+				modminer->device_not_well_reason = REASON_DEV_THERMAL_CUTOFF;
+				++modminer->dev_thermal_cutoff_count;
+			} else {
+				time_t now = time(NULL);
+				if (state->last_cutoff_reduced != now) {
+					state->last_cutoff_reduced = now;
+					modminer_reduce_clock(thr, false);
+				}
+			}
+		}
+	}
+
+	cmd[0] = '\x09';
+	iter = 200;
+	while (1) {
+		if (write(fd, cmd, 2) != 2)
+			bailout2(LOG_ERR, "%s %u.%u: Error reading (get nonce)", modminer->api->name, modminer->device_id, fpgaid);
+		serial_read(fd, &nonce, 4);
+		mutex_unlock(&modminer->device_mutex);
+		if (memcmp(&nonce, "\xff\xff\xff\xff", 4)) {
+			state->no_nonce_counter = 0;
+			bad = !test_nonce(work, nonce);
+			if (!bad)
+				submit_nonce(thr, work, nonce);
+			else {
+				++hw_errors;
+				if (++modminer->hw_errors * 100 > 1000 + state->good_share_counter)
+					// Only reduce clocks if hardware errors are more than ~1% of results
+					modminer_reduce_clock(thr, true);
+			}
+		}
+		else
+		if (++state->no_nonce_counter > 18000) {
+			state->no_nonce_counter = 0;
+			modminer_reduce_clock(thr, true);
+		}
+		if (work_restart(thr))
+			break;
+		usleep(10000);
+		if (work_restart(thr) || !--iter)
+			break;
+		mutex_lock(&modminer->device_mutex);
+	}
+
+	struct timeval tv_workend, elapsed;
+	gettimeofday(&tv_workend, NULL);
+	timeval_subtract(&elapsed, &tv_workend, &state->tv_workstart);
+
+	uint64_t hashes = (uint64_t)state->clock * (((uint64_t)elapsed.tv_sec * 1000000) + elapsed.tv_usec);
+	if (hashes > 0xffffffff)
+		hashes = 0xffffffff;
+	else
+	if (hashes <= state->hashes)
+		hashes = 1;
+	else
+		hashes -= state->hashes;
+	state->hashes += hashes;
+	return hashes;
+}
+
+static uint64_t
+modminer_scanhash(struct thr_info*thr, struct work*work, uint64_t __maybe_unused max_nonce)
+{
+	struct modminer_fpga_state *state = thr->cgpu_data;
+	uint64_t hashes = 1;
+	bool startwork;
+
+	startwork = modminer_prepare_next_work(state, work);
+	if (state->work_running) {
+		hashes = modminer_process_results(thr);
+		if (work_restart(thr)) {
+			state->work_running = false;
+			return 1;
+		}
+	}
+	else
+		state->work_running = true;
+
+	if (startwork) {
+		if (!modminer_start_work(thr))
+			return 0;
+		memcpy(&state->running_work, work, sizeof(state->running_work));
+	}
+
+	// This is intentionally early
+	work->blk.nonce += hashes;
+	return hashes;
+}
+
+static void
+modminer_fpga_shutdown(struct thr_info *thr)
+{
+	free(thr->cgpu_data);
+}
+
+struct device_api modminer_api = {
+	.dname = "modminer",
+	.name = "MMQ",
+	.api_detect = modminer_detect,
+	.get_statline_before = get_modminer_statline_before,
+	.thread_prepare = modminer_fpga_prepare,
+	.thread_init = modminer_fpga_init,
+	.scanhash = modminer_scanhash,
+	.thread_shutdown = modminer_fpga_shutdown,
+};
diff --git a/driver-opencl.c b/driver-opencl.c
index dd15687..521a063 100644
--- a/driver-opencl.c
+++ b/driver-opencl.c
@@ -1110,7 +1110,7 @@ out:
 	return NULL;
 }
 #else
-void *reinit_gpu(void *userdata)
+void *reinit_gpu(__maybe_unused void *userdata)
 {
 	return NULL;
 }
diff --git a/fpgautils.c b/fpgautils.c
new file mode 100644
index 0000000..783015a
--- /dev/null
+++ b/fpgautils.c
@@ -0,0 +1,276 @@
+/*
+ * Copyright 2012 Luke Dashjr
+ * Copyright 2012 Andrew Smith
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 3 of the License, or (at your option)
+ * any later version.  See COPYING for more details.
+ */
+
+#include "config.h"
+
+#include <sys/types.h>
+#include <dirent.h>
+#include <string.h>
+
+#ifndef WIN32
+#include <termios.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include <fcntl.h>
+#ifndef O_CLOEXEC
+#define O_CLOEXEC 0
+#endif
+#else
+#include <windows.h>
+#include <io.h>
+#endif
+
+#ifdef HAVE_LIBUDEV
+#include <libudev.h>
+#endif
+
+#include "elist.h"
+#include "fpgautils.h"
+#include "logging.h"
+#include "miner.h"
+
+#ifdef HAVE_LIBUDEV
+char
+serial_autodetect_udev(detectone_func_t detectone, const char*prodname)
+{
+	if (total_devices == MAX_DEVICES)
+		return 0;
+
+	struct udev *udev = udev_new();
+	struct udev_enumerate *enumerate = udev_enumerate_new(udev);
+	struct udev_list_entry *list_entry;
+	char found = 0;
+
+	udev_enumerate_add_match_subsystem(enumerate, "tty");
+	udev_enumerate_add_match_property(enumerate, "ID_MODEL", prodname);
+	udev_enumerate_scan_devices(enumerate);
+	udev_list_entry_foreach(list_entry, udev_enumerate_get_list_entry(enumerate)) {
+		struct udev_device *device = udev_device_new_from_syspath(
+			udev_enumerate_get_udev(enumerate),
+			udev_list_entry_get_name(list_entry)
+		);
+		if (!device)
+			continue;
+
+		const char *devpath = udev_device_get_devnode(device);
+		if (devpath && detectone(devpath))
+			++found;
+
+		udev_device_unref(device);
+
+		if (total_devices == MAX_DEVICES)
+			break;
+	}
+	udev_enumerate_unref(enumerate);
+	udev_unref(udev);
+
+	return found;
+}
+#else
+char
+serial_autodetect_udev(__maybe_unused detectone_func_t detectone, __maybe_unused const char*prodname)
+{
+	return 0;
+}
+#endif
+
+char
+serial_autodetect_devserial(detectone_func_t detectone, const char*prodname)
+{
+#ifndef WIN32
+	if (total_devices == MAX_DEVICES)
+		return 0;
+
+	DIR *D;
+	struct dirent *de;
+	const char udevdir[] = "/dev/serial/by-id";
+	char devpath[sizeof(udevdir) + 1 + NAME_MAX];
+	char *devfile = devpath + sizeof(udevdir);
+	char found = 0;
+
+	D = opendir(udevdir);
+	if (!D)
+		return 0;
+	memcpy(devpath, udevdir, sizeof(udevdir) - 1);
+	devpath[sizeof(udevdir) - 1] = '/';
+	while ( (de = readdir(D)) ) {
+		if (!strstr(de->d_name, prodname))
+			continue;
+		strcpy(devfile, de->d_name);
+		if (detectone(devpath)) {
+			++found;
+			if (total_devices == MAX_DEVICES)
+				break;
+		}
+	}
+	closedir(D);
+
+	return found;
+#else
+	return 0;
+#endif
+}
+
+char
+_serial_detect(const char*dnamec, size_t dnamel, detectone_func_t detectone, autoscan_func_t autoscan, bool forceauto)
+{
+	if (total_devices == MAX_DEVICES)
+		return 0;
+
+	struct string_elist *iter, *tmp;
+	const char*s;
+	bool inhibitauto = false;
+	char found = 0;
+
+	list_for_each_entry_safe(iter, tmp, &scan_devices, list) {
+		s = iter->string;
+		if (!strncmp(dnamec, iter->string, dnamel))
+			s += dnamel;
+		if (!strcmp(s, "auto"))
+			forceauto = true;
+		else
+		if (!strcmp(s, "noauto"))
+			inhibitauto = true;
+		else
+		if (detectone(s)) {
+			string_elist_del(iter);
+			inhibitauto = true;
+			++found;
+			if (total_devices == MAX_DEVICES)
+				break;
+		}
+	}
+
+	if ((forceauto || !inhibitauto) && autoscan && total_devices < MAX_DEVICES)
+		found += autoscan();
+
+	return found;
+}
+
+int
+serial_open(const char*devpath, unsigned long baud, signed short timeout, bool purge)
+{
+#ifdef WIN32
+	HANDLE hSerial = CreateFile(devpath, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
+	if (unlikely(hSerial == INVALID_HANDLE_VALUE))
+		return -1;
+
+	// thanks to af_newbie for pointers about this
+	COMMCONFIG comCfg = {0};
+	comCfg.dwSize = sizeof(COMMCONFIG);
+	comCfg.wVersion = 1;
+	comCfg.dcb.DCBlength = sizeof(DCB);
+	comCfg.dcb.BaudRate = baud;
+	comCfg.dcb.fBinary = 1;
+	comCfg.dcb.fDtrControl = DTR_CONTROL_ENABLE;
+	comCfg.dcb.fRtsControl = RTS_CONTROL_ENABLE;
+	comCfg.dcb.ByteSize = 8;
+
+	SetCommConfig(hSerial, &comCfg, sizeof(comCfg));
+
+	const DWORD ctoms = (timeout == -1) ? 30000 : (timeout * 100);
+	COMMTIMEOUTS cto = {ctoms, 0, ctoms, 0, ctoms};
+	SetCommTimeouts(hSerial, &cto);
+
+	if (purge) {
+		PurgeComm(hSerial, PURGE_RXABORT);
+		PurgeComm(hSerial, PURGE_TXABORT);
+		PurgeComm(hSerial, PURGE_RXCLEAR);
+		PurgeComm(hSerial, PURGE_TXCLEAR);
+	}
+
+	return _open_osfhandle((LONG)hSerial, 0);
+#else
+	int fdDev = open(devpath, O_RDWR | O_CLOEXEC | O_NOCTTY);
+
+	if (unlikely(fdDev == -1))
+		return -1;
+
+	struct termios pattr;
+	tcgetattr(fdDev, &pattr);
+	pattr.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
+	pattr.c_oflag &= ~OPOST;
+	pattr.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
+	pattr.c_cflag &= ~(CSIZE | PARENB);
+	pattr.c_cflag |= CS8;
+
+	switch (baud) {
+	case 0: break;
+	case 115200: pattr.c_cflag = B115200; break;
+	default:
+		applog(LOG_WARNING, "Unrecognized baud rate: %lu", baud);
+	}
+	pattr.c_cflag |= CREAD | CLOCAL;
+
+	if (timeout >= 0) {
+		pattr.c_cc[VTIME] = (cc_t)timeout;
+		pattr.c_cc[VMIN] = 0;
+	}
+
+	tcsetattr(fdDev, TCSANOW, &pattr);
+	if (purge)
+		tcflush(fdDev, TCIOFLUSH);
+	return fdDev;
+#endif
+}
+
+ssize_t
+_serial_read(int fd, char *buf, size_t bufsiz, char *eol)
+{
+	ssize_t len, tlen = 0;
+	while (bufsiz) {
+		len = read(fd, buf, eol ? 1 : bufsiz);
+		if (len < 1)
+			break;
+		tlen += len;
+		if (eol && *eol == buf[0])
+			break;
+		buf += len;
+		bufsiz -= len;
+	}
+	return tlen;
+}
+
+static FILE*
+_open_bitstream(const char*path, const char*subdir, const char*filename)
+{
+	char fullpath[PATH_MAX];
+	strcpy(fullpath, path);
+	strcat(fullpath, "/");
+	if (subdir) {
+		strcat(fullpath, subdir);
+		strcat(fullpath, "/");
+	}
+	strcat(fullpath, filename);
+	return fopen(fullpath, "rb");
+}
+#define _open_bitstream(path, subdir)  do {  \
+	f = _open_bitstream(path, subdir, filename);  \
+	if (f)  \
+		return f;  \
+} while(0)
+
+#define _open_bitstream3(path)  do {  \
+	_open_bitstream(path, dname);  \
+	_open_bitstream(path, "bitstreams");  \
+	_open_bitstream(path, NULL);  \
+} while(0)
+
+FILE*
+open_bitstream(const char*dname, const char*filename)
+{
+	FILE *f;
+
+	_open_bitstream3(opt_kernel_path);
+	_open_bitstream3(cgminer_path);
+	_open_bitstream3(".");
+
+	return NULL;
+}
diff --git a/fpgautils.h b/fpgautils.h
new file mode 100644
index 0000000..7b8b331
--- /dev/null
+++ b/fpgautils.h
@@ -0,0 +1,39 @@
+/*
+ * Copyright 2012 Luke Dashjr
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 3 of the License, or (at your option)
+ * any later version.  See COPYING for more details.
+ */
+
+#ifndef FPGAUTILS_H
+#define FPGAUTILS_H
+
+#include <stdbool.h>
+#include <stdio.h>
+
+typedef bool(*detectone_func_t)(const char*);
+typedef char(*autoscan_func_t)();
+
+extern char _serial_detect(const char*dnamec, size_t dnamel, detectone_func_t, autoscan_func_t, bool force_autoscan);
+#define serial_detect_fauto(dname, detectone, autoscan)  \
+	_serial_detect(dname ":", sizeof(dname)+1, detectone, autoscan, true)
+#define serial_detect_auto(dname, detectone, autoscan)  \
+	_serial_detect(dname ":", sizeof(dname)+1, detectone, autoscan, false)
+#define serial_detect(dname, detectone)  \
+	_serial_detect(dname ":", sizeof(dname)+1, detectone,     NULL, false)
+extern char serial_autodetect_devserial(detectone_func_t, const char*prodname);
+extern char serial_autodetect_udev     (detectone_func_t, const char*prodname);
+
+extern int serial_open(const char*devpath, unsigned long baud, signed short timeout, bool purge);
+extern ssize_t _serial_read(int fd, char *buf, size_t buflen, char*eol);
+#define serial_read(fd, buf, count)  \
+	_serial_read(fd, (char*)(buf), count, NULL)
+#define serial_read_line(fd, buf, bufsiz, eol)  \
+	_serial_read(fd, buf, count, &eol)
+#define serial_close(fd)  close(fd)
+
+extern FILE*open_bitstream(const char*dname, const char*filename);
+
+#endif
diff --git a/libztex.c b/libztex.c
index ffc2e67..636c12c 100644
--- a/libztex.c
+++ b/libztex.c
@@ -22,6 +22,8 @@
 
 #include <stdio.h>
 #include <unistd.h>
+
+#include "fpgautils.h"
 #include "miner.h"
 #include "libztex.h"
 
@@ -150,7 +152,7 @@ static int libztex_configureFpgaHS(struct libztex_device *ztex, const char* firm
 	libusb_claim_interface(ztex->hndl, settings[1]);
 
 	for (tries = 3; tries > 0; tries--) {
-		fp = fopen(firmware, "rb");
+		fp = open_bitstream("ztex", firmware);
 		if (!fp) {
 			applog(LOG_ERR, "%s: failed to read firmware '%s'", ztex->repr, firmware);
 			return -2;
@@ -245,7 +247,7 @@ static int libztex_configureFpgaLS(struct libztex_device *ztex, const char* firm
 	}
 
 	for (tries = 10; tries > 0; tries--) {
-		fp = fopen(firmware, "rb");
+		fp = open_bitstream("ztex", firmware);
 		if (!fp) {
 			applog(LOG_ERR, "%s: failed to read firmware '%s'", ztex->repr, firmware);
 			return -2;
@@ -316,12 +318,11 @@ static int libztex_configureFpgaLS(struct libztex_device *ztex, const char* firm
 
 int libztex_configureFpga(struct libztex_device *ztex)
 {
-	char buf[256] = "bitstreams/";
+	char buf[256];
 	int rv;
 
-	memset(&buf[11], 0, 245);
-	strcpy(&buf[11], ztex->bitFileName);
-	strcpy(&buf[strlen(buf)], ".bit");
+	strcpy(buf, ztex->bitFileName);
+	strcat(buf, ".bit");
 	rv = libztex_configureFpgaHS(ztex, buf, true, 2); 
 	if (rv != 0)
 		rv = libztex_configureFpgaLS(ztex, buf, true, 2); 
diff --git a/miner.h b/miner.h
index 605ad1d..4e65f22 100644
--- a/miner.h
+++ b/miner.h
@@ -245,6 +245,7 @@ struct device_api {
 	bool (*prepare_work)(struct thr_info*, struct work*);
 	uint64_t (*scanhash)(struct thr_info*, struct work*, uint64_t);
 	void (*thread_shutdown)(struct thr_info*);
+	void (*thread_enable)(struct thr_info*);
 };
 
 enum dev_enable {
@@ -314,6 +315,11 @@ struct cgpu_info {
 #endif
 		int device_fd;
 	};
+#ifdef USE_BITFORCE
+	unsigned int wait_ms;
+	unsigned int sleep_ms;
+#endif
+	pthread_mutex_t		device_mutex;
 
 	enum dev_enable deven;
 	int accepted;
@@ -327,7 +333,7 @@ struct cgpu_info {
 	struct timeval last_message_tv;
 
 	int threads;
-	struct thr_info *thread;
+	struct thr_info **thr;
 
 	unsigned int max_hashes;
 
@@ -336,7 +342,7 @@ struct cgpu_info {
 	int virtual_adl;
 	int intensity;
 	bool dynamic;
-	char *kname;
+	const char *kname;
 #ifdef HAVE_OPENCL
 	cl_uint vwidth;
 	size_t work_size;
@@ -375,8 +381,6 @@ struct cgpu_info {
 	int dev_thermal_cutoff_count;
 
 	struct cgminer_stats cgminer_stats;
-	
-	pthread_mutex_t dev_lock;
 };
 
 extern bool add_cgpu(struct cgpu_info*);
@@ -746,6 +750,7 @@ struct work {
 };
 
 extern void get_datestamp(char *, struct timeval *);
+extern bool test_nonce(struct work *work, uint32_t nonce);
 bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce);
 extern void tailsprintf(char *f, const char *fmt, ...);
 extern void wlogprint(const char *f, ...);