Commit f066ca6860e7d693f3ef559ad3b6f48bd9a42c57

Angus Gratton 2013-11-05T10:19:11

Merge branch 'master' of github.com:ckolivas/cgminer into new_protocol Conflicts: configure.ac miner.h usbutils.c usbutils.h

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
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
diff --git a/01-cgminer.rules b/01-cgminer.rules
index 89443ad..972468c 100644
--- a/01-cgminer.rules
+++ b/01-cgminer.rules
@@ -27,3 +27,6 @@ ATTRS{idVendor}=="03eb", ATTRS{idProduct}=="204b", SUBSYSTEMS=="usb", ACTION=="a
 
 #Klondike
 ATTRS{idVendor}=="04d8", ATTRS{idProduct}=="f60a", SUBSYSTEMS=="usb", ACTION=="add", MODE="0666", GROUP="plugdev"
+
+#HashFast
+ATTRS{idVendor}=="297c", ATTRS{idProduct}=="0001", SUBSYSTEMS=="usb", ACTION=="add", MODE="0666", GROUP="plugdev", ENV{ID_MM_DEVICE_IGNORE}="1"
diff --git a/ASIC-README b/ASIC-README
index 55b76d8..5d71f05 100644
--- a/ASIC-README
+++ b/ASIC-README
@@ -2,11 +2,12 @@ SUPPORTED DEVICES
 
 Currently supported devices include the Avalon (including BitBurner and
 Klondike), the Butterfly Labs SC range of devices, the ASICMINER block
-erupters and the BPMC BF1 (bitfury) USB devices. No COM ports on windows or
-TTY devices will be used by cgminer as it communicates directly with them
-via USB so it is normal for them to not exist or be disconnected when
-cgminer is running.
+erupters, the BF1 (bitfury) USB (red and blue) devices, KnCminer Mercury,
+Saturn and Jupiter devices, and upcoming Hashfast devices.
 
+No COM ports on windows or TTY devices will be used by cgminer as it
+communicates directly with them via USB so it is normal for them to not exist or
+be disconnected when cgminer is running.
 
 The BFL devices should come up as one of the following:
 
@@ -102,11 +103,13 @@ ASIC SPECIFIC COMMANDS
 --avalon-options <arg> Set avalon options baud:miners:asic:timeout:freq
 --avalon-temp <arg> Set avalon target temperature (default: 50)
 --bflsc-overheat <arg> Set overheat temperature where BFLSC devices throttle, 0 to disable (default: 90)
---bitburner-voltage <arg> Set BitBurner core voltage, in millivolts
---klondike-options <arg> Set klondike options clock:temp1:temp2:fan
+--bitburner-fury-options <arg> Override avalon-options for BitBurner Fury boards baud:miners:asic:timeout:freq
+--bitburner-fury-voltage <arg> Set BitBurner Fury core voltage, in millivolts
+--bitburner-voltage <arg> Set BitBurner (Avalon) core voltage, in millivolts
+--klondike-options <arg> Set klondike options clock:temptarget
 
 
-AVALON DEVICES
+AVALON AND BITBURNER DEVICES
 
 Currently all known Avalon devices come with their own operating system and
 a preinstalled version of cgminer as part of the flash firmware, based on the
@@ -118,6 +121,9 @@ command, and adjust its fan control-temperature relationship with avalon-temp.
 By default the avalon will also cut off when its temperature reaches 60
 degrees.
 
+All current BitBurner devices (BitBurner X, BitBurner XX and BitBurner Fury)
+emulate Avalon devices, whether or not they use Avalon chips.
+
 Avalon commands:
 
 --avalon-auto       Adjust avalon overclock frequency dynamically for best hashrate
@@ -126,7 +132,9 @@ Avalon commands:
 --avalon-freq <arg> Set frequency range for avalon-auto, single value or range
 --avalon-options <arg> Set avalon options baud:miners:asic:timeout:freq
 --avalon-temp <arg> Set avalon target temperature (default: 50)
---bitburner-voltage <arg> Set BitBurner core voltage, in millivolts
+--bitburner-fury-options <arg> Override avalon-options for BitBurner Fury boards baud:miners:asic:timeout:freq
+--bitburner-fury-voltage <arg> Set BitBurner Fury core voltage, in millivolts
+--bitburner-voltage <arg> Set BitBurner (Avalon) core voltage, in millivolts
 
 
 Avalon auto will enable dynamic overclocking gradually increasing and
@@ -177,8 +185,15 @@ Miners:
 Most Avalons are 3 module devices, which come to 24 miners. 4 module devices
 would use 32 here.
 
+For BitBurner X and BitBurner XX devices you should use twice the number of
+boards in the stack.  e.g. for a two-board stack you would use 4.  For
+BitBurner Fury devices you should use the total number of BitFury chips in the
+stack (i.e. 16 times the number of boards).  e.g. for a two-board stack you
+would use 32.
+
 Asic count:
-Virtually all have 10, so don't change this.
+Virtually all have 10, so don't change this.  BitBurner devices use 10 here
+even if the boards have some other number of ASICs.
 
 Timeout:
 This is how long the device will work on a work item before accepting new work
@@ -198,16 +213,61 @@ Sample settings for valid different frequencies (last 2 values):
 50:256
 
 Frequency:
-This is the clock speed of the devices. Only specific values work, 256, 270,
-282 (default), 300, 325, 350 and 375.
+This is the clock speed of the devices. For Avalon devices, only specific
+values work, 256, 270, 282 (default), 300, 325, 350 and 375.  For BitBurner
+devices, other values can be used.
 
 Note that setting a value with an asterisk next to it will be using your
 avalon outside its spec and you do so at your own risk.
 
+The default frequency for BitBurner X and BitBurner XX boards is 282.  The
+default frequency for BitBurner Fury boards is 256.  Overclocking is
+possible - please consult the product documentation and/or manufacturer for
+information on safe values.  Values outside this range are used at your own
+risk.  Underclocking is also possible, at least with the X and XX boards.
+
+eg:
+--bitburner-fury-options <arg> Override avalon-options for BitBurner Fury boards baud:miners:asic:timeout:freq
+
+This option takes the same format as --avalon-options.  When specified, it
+will be used for BitBurner Fury boards in preference to the values specified
+in --avalon-options.  (If not specified, BitBurner Fury boards will be
+controlled by the values used in --avalon options.)  See --avalon-options for
+a detailed description of the fields.
+
+This option is particularly useful when using a mixture of different BitBurner
+devices as BitBurner Fury devices generally require significantly different
+clock frequencies from Avalon-based devices.  This option is only available
+for boards with recent firmware that are recognized by cgminer as BBF.
+
 eg:
---bitburner-voltage <arg> Set BitBurner core voltage, in millivolts
+--bitburner-fury-voltage <arg> Set BitBurner Fury core voltage, in millivolts
+
+Sets the core voltage for the BitBurner Fury boards.  The default value is
+900.  Overvolting is possible - please consult the product documentation
+and/or manufaturer about the safe range of values.  Values outside this range
+are used at your own risk.
+
+This option is only available for boards with recent firmware that are
+recognized by cgminer as BBF.  For boards recognized as BTB, see
+--bitburner-voltage
+
+eg:
+--bitburner-voltage <arg> Set BitBurner (Avalon) core voltage, in millivolts
+
+Sets the core voltage for the Avalon-based BitBurner X and BitBurner XX
+boards.  The default value is 1200.  Overvolting and undervolting is
+possible - please consult the product documentation and/or the manufacturer
+for information about the safe range.  Values outside this range are used at
+your own risk.
+
+Older BitBurner Fury firmware emulates a BitBurner XX board and is identified
+by cgminer as BTB.  On these devices, --bitburner-voltage is used to control
+the voltage of the BitBurner Fury board.  The actual core voltage will be
+300mV less than the requested voltage, so to run a BitBurner Fury board at
+950mV use --bitburner-voltage 1250.  The default value of 1200 therefore
+corresponds to the default core voltage of 900mV.
 
-Self evident.
 
 If you use the full curses based interface with Avalons you will get this
 information:
diff --git a/Makefile.am b/Makefile.am
index 1e51d90..895b60f 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -1,10 +1,10 @@
 
 ACLOCAL_AMFLAGS = -I m4
 
-JANSSON_INCLUDES= -I$(top_srcdir)/compat/jansson-2.5/src
+JANSSON_INCLUDES= -I$(top_builddir)/compat/jansson-2.5/src -I$(top_srcdir)/compat/jansson-2.5/src
 
 if WANT_USBUTILS
-USBUTILS_INCLUDES = -I$(top_srcdir)/compat/libusb-1.0/libusb
+USBUTILS_INCLUDES = -I$(top_builddir)/compat/libusb-1.0/libusb -I$(top_srcdir)/compat/libusb-1.0/libusb
 else
 USBUTILS_INCLUDES =
 endif
@@ -59,7 +59,6 @@ endif
 
 endif
 
-
 if NEED_FPGAUTILS
 cgminer_SOURCES += fpgautils.c fpgautils.h
 endif
@@ -68,6 +67,15 @@ if WANT_USBUTILS
 cgminer_SOURCES += usbutils.c usbutils.h
 endif
 
+# Device drivers
+if HAS_AVALON
+cgminer_SOURCES += driver-avalon.c driver-avalon.h
+endif
+
+if HAS_KNC
+cgminer_SOURCES += driver-knc-spi-fpga.c
+endif
+
 if HAS_BFLSC
 cgminer_SOURCES += driver-bflsc.c driver-bflsc.h
 endif
@@ -76,6 +84,10 @@ if HAS_BITFORCE
 cgminer_SOURCES += driver-bitforce.c
 endif
 
+if HAS_HASHFAST
+cgminer_SOURCES += driver-hashfast.c driver-hashfast.h hf_protocol.h
+endif
+
 if HAS_BITFURY
 cgminer_SOURCES += driver-bitfury.c driver-bitfury.h
 endif
@@ -88,10 +100,6 @@ if HAS_ICARUS
 cgminer_SOURCES += driver-icarus.c
 endif
 
-if HAS_AVALON
-cgminer_SOURCES += driver-avalon.c driver-avalon.h
-endif
-
 if HAS_KLONDIKE
 cgminer_SOURCES += driver-klondike.c
 endif
diff --git a/NEWS b/NEWS
index f4d8f5b..69b5d6d 100644
--- a/NEWS
+++ b/NEWS
@@ -1,3 +1,183 @@
+Version 3.7.0 - 4th November 2013
+
+- Use WRITEIOERR macro check for all usb writes.
+- Always use a usb read buffer instead of having to explicitly enable it.
+- Force unlocking of the console lock on restart to avoid corrupting the console
+state when we finally quit.
+- Never wait indefinitely for a pthread conditional in the hash_pop loop in case
+the work scheduler misses the last wakeup.
+- Make hash_pop signal the work scheduler each time it waits on the conditional
+that it should look for more work.
+- Discriminate between libusb transfer errors and regular libusb errors and make
+sure to capture them all.
+- Always read a full sized transfer for bulk reads.
+- Deprecate preferred packet size functions in usbutils since they're unhelpful.
+- Copy known transferred amount back to buffer for usb reads instead of
+requested length.
+- Treat timeout errors on usb writes as IO errors.
+- Ignore iManufacturer from bitfury devices to support bluefury as well as
+redfury.
+- Add more debugging info for when usb details don't match.
+- Look for timeout overruns in usb read/write.
+- Use an int for usb_read/write to identify overruns.
+- Use the callback timeout as a safety mechanism only on windows.
+- Instead of using complicated sleeps to emulate characters per second on usb
+writes, submit only as many characters as can be transferred per usb poll of
+1ms, and use timeouts in bulk transfers, cancelling transfers only as a
+failsafe.
+- Remove discarded work from quota used.
+- Display works completed in summary and API data.
+- Store how many work items are worked on per pool.
+- Make each pool store its on reference for what the most current block is and
+fine tune management of block change in shared pool failover strategies using
+the information.
+- Rationalise use of current_hash to a single hex string the length of the
+previous block and display only the first non zero hex chars of the block in the
+status window.
+- Update uthash to latest.
+- show_hash doesn't know the size of the string so hard code the max size.
+- Remove as many initial zeroes as exist on share display, abstracting out a
+hash show function to use across different submission mechanisms.
+- Add missing endian swap functions for 64bits.
+- Sanity check for absurd target setting and divide by zero.
+- Abstract out conversion of a 256 bit endian number to a double, correcting
+errors and use it for determining any magnitude share diff.
+- Avoid the extra generation of a byte flipped hash2 in struct work and directly
+use the LE work hash.
+- Add a sanity check to avoid divide by zero crashes in set_target
+- Calculate diff from target accurately for all 256 bits.
+- Set a true 256bit binary target based on any diff value in set_target()
+- Provide a copy_work_noffset function for copying a work struct but changing
+its ntime.
+- Make calls to flush queue and flush work asynchronous wrt to the main work
+loops.
+- Share is also above target for submit noffset nonce.
+- Use round for displaying current pool diff.
+- Use round for stratum share diff display instead of floor.
+- Use round instead of floor for displayed pool difficulty.
+- Allow arbitrary diffs to be tested against nonces via a test_nonce_diff
+function.
+- Abstract out the rebuilding of hash2 in work.
+- Share is above, not below target, when it doesn't meet it.
+- Add the ability to add uint8 and uint16 entities to api data.
+- Use a non blocking connect with a 1 second select timeout when initiating
+stratum to allow us to iterate over all IPs returned by getaddrinfo in round
+robin DNS pools.
+- Minor style changes to output.
+- Revert two different hash_sequence(_head)'s to one variable, use
+HF_SEQUENCE_DISTANCE in both places
+- Remove duplicate HF_SEQUENCE_DISTANCE() macro, and duplicate hash_sequence
+from info structure
+- Change SEQUENCE_DISTANCE() macro to HF_SEQUENCE_DISTANCE()
+- Structure changes for OP_NONCE, add big endian header
+- klondike - initialise stat_lock
+- klondike - better to unlock locks than to lock them twice :)
+- Add copyright notice to knc driver.
+- Trivial style changes to knc driver.
+- Improve performance of work generation by optimizing hex2bin and bin2hex
+- klondike - change options to clock and temptarget only
+- klondike - fix another uninit dev warning
+- klondike - downgrade 'late update' but add an idle detect - and correct error
+levels
+- klondike - fix isc uninit warning
+- Use a mutex to protect data in the knc structure, to prevent loading more work
+during a flush, and unlock and return to main between calls to get_queued_work.
+- Use the existing device_data for knc state data.
+- Only count successful nonces as hashrate in the knc driver.
+- Fix trivial warnings in knc driver.
+- Add KNC to api
+- klondike - drop the device for hotplug if it's unresponsive
+- usbutils - usb_nodev() allow a driver to drop a device
+- klondike - single 'shutdown' and ensure it happens
+- klondike remove SCNu8 - unsupported on windows
+- Correctly calculate sleep_estimate in usbutils that may have been preventing
+usecps from working.
+- Use a sanity check on timeout on windows.
+- Better HW error count; disable permanently those cores which fail often
+- KnC driver: knc-spi-fpga ASIC driver
+- Fixup jansson & libusb include paths when using separate build directory
+- 'llround' is more suitable here than 'roundl'
+- Silence warning if MAX/MIN is already defined
+- Remove prebuild ccan/opt dependencies
+- Reinstate block solve testing.
+- Dramatically simplify the calculation of blockdiff.
+- Simplify the set_target function, allowing it to work properly for fractional
+diffs.
+- Merge hashfast driver
+- Merge KnC driver
+
+
+Version 3.6.6 - 26th October 2013
+
+- Remove inappropriate extra locking in _usb_transfer_read
+
+
+Version 3.6.5 - 26th October 2013
+
+- klondike - fix uninitialised dev bug
+- Adjust the binary ntime data in submit_noffset_nonce even when there is no hex
+ntime string for eg. gbt.
+- Put an entry into the work struct telling drivers how much they can roll the
+ntime themselves.
+- Only set libusb cancellable status if the transfer succeeds.
+- Remove the applog on miner threads dying to prevent deadlocks on exit.
+- Do one extra guaranteed libusb event handling before testing if there are any
+pending async usb transfers.
+- Use a linked list for all usb transfers instead of just cancellable ones.
+- Provide a mechanism for informing drivers of updated work templates for
+stratum and gbt mining.
+- Add cancellable transfers correctly to the ct_list
+- Check for presence of thr in icarus get nonce for startup nonce testing to
+work.
+- Use cancellable usb transfers in the icarus driver to avoid having to loop and
+poll when waiting for a response and to speed up work restart response time.
+- Add a usb_read_ii_timeout_cancellable wrapper
+- Add usb transfer cancellation on shutdown and documentation regarding where
+cancellable transfers are suitable.
+- Use cancellable transfers on bitfury device.
+- Cancel cancellable usb transfers on work restart messages.
+- Don't bother having a separate cancellable transfer struct for usb transfers,
+simply include the list in the usb_transfer struct.
+- Add wrappers for usb_read_cancellable and usb_read_timeout_cancellable
+- Specifically set the cancellable state for it to not be uninitialised in the
+usb transfer struct.
+- Alter the usb cancellable list only under cgusb_fd_lock write lock.
+- Pass the cancellable option to _usb_read options to decide on whether to add
+usb transfers to the list of cancellable transfers.
+- Create a linked list of potentially cancellable usb transfers.
+- Don't attempt to disable curses or print a summary during an app restart to
+prevent deadlocks.
+- Keep the libusb event handle polling thread active until there are no async
+usb transfers in progress.
+- Keep a global counter of how many async usb transfers are in place.
+- Perform libusb_submit_transfer under the write variant of cgusb_fd_lock
+- klondike - error condition handling
+- Avoid entering static libusb directory if --with-system-libusb is enabled.
+- Minor opencl build corrections.
+- Enable dynamic linking against system libusb --with-system-libusb
+- Modify Makefile to only include opencl related code when configured in.
+- Convert opencl to need to be explicitly enabled during build with
+--enable-opencl
+- Implement a cglock_destroy function.
+- Implement a rwlock_destroy function.
+- Implement a mutex_destroy function.
+- Add usb command name to critical libusb error reporting.
+- Use windows' own higher resolution time and handlers allowing us to have
+higher precision absolute timeouts.
+- Fix lldiv error in windows cgminer_t calculation.
+- miner.php correct sort gen field names largest to smallest
+- api ... the code related to device elapsed
+- api add device elapsed since hotplug devices Elapsed is less than cgminer
+Elapsed
+- Drop usb buffering message to debug logging level.
+- Do the ntime binary modification to the work struct when submitting an ntime
+offset nonce within submit_noffset_nonce
+- Code cleanup and improved documentation
+- Improvements to support for BitBurner boards
+- Convert libusb transfer errors to regular libusb error messages to allow for
+accurate message reporting.
+
+
 Version 3.6.4 - 18th October 2013
 
 - Fixing the memory leak for remaining semaphores means we can go back to using
diff --git a/README b/README
index 5c73991..87c558e 100644
--- a/README
+++ b/README
@@ -106,17 +106,23 @@ If building from git:
 
 
 CGMiner specific configuration options:
-	--disable-opencl        Override detection and disable building with opencl
-	--disable-adl           Override detection and disable building with adl
-	--enable-bflsc          Compile support for BFL ASICs (default disabled)
-	--enable-bitforce       Compile support for BitForce FPGAs(default disabled)
-	--enable-icarus         Compile support for Icarus bitstream FPGAs(default disabled)
-	--enable-modminer       Compile support for ModMiner FPGAs(default disabled)
-	--enable-ztex           Compile support for Ztex Board(default disabled)
-	--enable-avalon         Compile support for Avalon (default disabled)
-	--enable-klondike       Compile support for Klondike (default disabled)
-	--enable-scrypt         Compile support for scrypt litecoin mining (default disabled)
-	--without-curses        Compile support for curses TUI (default enabled)
+  --enable-opencl         Enable support for GPU mining with opencl
+  --disable-adl           Override detection and disable building with adl
+  --enable-scrypt         Compile support for scrypt litecoin mining (default
+                          disabled)
+  --enable-avalon         Compile support for Avalon (default disabled)
+  --enable-bflsc          Compile support for BFL ASICs (default disabled)
+  --enable-bitforce       Compile support for BitForce FPGAs (default
+                          disabled)
+  --enable-bitfury        Compile support for BitFury ASICs (default disabled)
+  --enable-hashfast       Compile support for Hashfast (default disabled)
+  --enable-icarus         Compile support for Icarus (default disabled)
+  --enable-knc            Compile support for KnC miners (default disabled)
+  --enable-klondike       Compile support for Klondike (default disabled)
+  --enable-modminer       Compile support for ModMiner FPGAs(default disabled)
+  --without-curses        Compile support for curses TUI (default enabled)
+  --with-system-libusb    Compile against dynamic system libusb (default use
+                          included static libusb)
 
 Basic *nix build instructions:
 	To actually build:
@@ -220,7 +226,10 @@ ASIC only options:
 --avalon-options <arg> Set avalon options baud:miners:asic:timeout:freq
 --avalon-temp <arg> Set avalon target temperature (default: 50)
 --bflsc-overheat <arg> Set overheat temperature where BFLSC devices throttle, 0 to disable (default: 90)
---bitburner-voltage <arg> Set BitBurner core voltage, in millivolts
+--bitburner-fury-options <arg> Override avalon-options for BitBurner Fury boards baud:miners:asic:timeout:freq
+--bitburner-fury-voltage <arg> Set BitBurner Fury core voltage, in millivolts
+--bitburner-voltage <arg> Set BitBurner (Avalon) core voltage, in millivolts
+--klondike-options <arg> Set klondike options clock:temptarget
 
 See ASIC-README for more information regarding these.
 
@@ -271,7 +280,7 @@ See SCRYPT-README for more information regarding litecoin mining.
 
 Cgminer should automatically find all of your Avalon ASIC, BFL ASIC, BitForce
 FPGAs, Icarus bitstream FPGAs, Klondike ASIC, ASICMINER usb block erupters,
-ModMiner FPGAs or Ztex FPGAs
+KnC ASICs, Hashfast ASICs and ModMiner FPGAs.
 
 ---
 
@@ -755,7 +764,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 4 FPGAs: BitForce, Icarus, ModMiner, and Ztex.
+A: At the moment, cgminer supports 3 FPGAs: BitForce, Icarus and ModMiner.
 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/api.c b/api.c
index 3494f9e..3ceaa8e 100644
--- a/api.c
+++ b/api.c
@@ -29,7 +29,7 @@
 #include "miner.h"
 #include "util.h"
 
-#if defined(USE_BFLSC) || defined(USE_AVALON) || defined(USE_BITFURY) || defined(USE_KLONDIKE)
+#if defined(USE_BFLSC) || defined(USE_AVALON) || defined(USE_HASHFAST) || defined(USE_BITFURY) || defined(USE_KLONDIKE) || defined(USE_KNC)
 #define HAVE_AN_ASIC 1
 #endif
 
@@ -167,8 +167,8 @@ static const char *SCRYPTSTR = "scrypt";
 static const char *SHA256STR = "sha256";
 
 static const char *DEVICECODE = ""
-#ifdef HAVE_OPENCL
-			"GPU "
+#ifdef USE_AVALON
+			"AVA "
 #endif
 #ifdef USE_BFLSC
 			"BAS "
@@ -179,11 +179,20 @@ static const char *DEVICECODE = ""
 #ifdef USE_BITFURY
 			"BFU "
 #endif
+#ifdef HAVE_OPENCL
+			"GPU "
+#endif
+#ifdef USE_HASHFAST
+			"HFA "
+#endif
 #ifdef USE_ICARUS
 			"ICA "
 #endif
-#ifdef USE_AVALON
-			"AVA "
+#ifdef USE_MODMINER
+			"MMQ "
+#endif
+#ifdef USE_KNC
+			"KnC "
 #endif
 #ifdef USE_MODMINER
 			"MMQ "
@@ -927,6 +936,16 @@ static struct api_data *api_add_data_full(struct api_data *root, char *name, enu
 				api_data->data = (void *)malloc(strlen((char *)data) + 1);
 				strcpy((char*)(api_data->data), (char *)data);
 				break;
+			case API_UINT8:
+				/* Most OSs won't really alloc less than 4 */
+				api_data->data = malloc(4);
+				*(uint8_t *)api_data->data = *(uint8_t *)data;
+				break;
+			case API_UINT16:
+				/* Most OSs won't really alloc less than 4 */
+				api_data->data = malloc(4);
+				*(uint16_t *)api_data->data = *(uint16_t *)data;
+				break;
 			case API_INT:
 				api_data->data = (void *)malloc(sizeof(int));
 				*((int *)(api_data->data)) = *((int *)data);
@@ -998,6 +1017,16 @@ struct api_data *api_add_const(struct api_data *root, char *name, const char *da
 	return api_add_data_full(root, name, API_CONST, (void *)data, copy_data);
 }
 
+struct api_data *api_add_uint8(struct api_data *root, char *name, uint8_t *data, bool copy_data)
+{
+	return api_add_data_full(root, name, API_UINT8, (void *)data, copy_data);
+}
+
+struct api_data *api_add_uint16(struct api_data *root, char *name, uint16_t *data, bool copy_data)
+{
+	return api_add_data_full(root, name, API_UINT16, (void *)data, copy_data);
+}
+
 struct api_data *api_add_int(struct api_data *root, char *name, int *data, bool copy_data)
 {
 	return api_add_data_full(root, name, API_INT, (void *)data, copy_data);
@@ -1131,6 +1160,12 @@ static struct api_data *print_data(struct api_data *root, char *buf, bool isjson
 				if (escape != original)
 					free(escape);
 				break;
+			case API_UINT8:
+				sprintf(buf, "%u", *(uint8_t *)root->data);
+				break;
+			case API_UINT16:
+				sprintf(buf, "%u", *(uint16_t *)root->data);
+				break;
 			case API_INT:
 				sprintf(buf, "%d", *((int *)(root->data)));
 				break;
@@ -2511,6 +2546,7 @@ static void poolstatus(struct io_data *io_data, __maybe_unused SOCKETTYPE c, __m
 		root = api_add_uint(root, "Getworks", &(pool->getwork_requested), false);
 		root = api_add_int(root, "Accepted", &(pool->accepted), false);
 		root = api_add_int(root, "Rejected", &(pool->rejected), false);
+		root = api_add_int(root, "Works", &pool->works, false);
 		root = api_add_uint(root, "Discarded", &(pool->discarded_work), false);
 		root = api_add_uint(root, "Stale", &(pool->stale_shares), false);
 		root = api_add_uint(root, "Get Failures", &(pool->getfail_occasions), false);
@@ -3630,14 +3666,8 @@ static void minecoin(struct io_data *io_data, __maybe_unused SOCKETTYPE c, __may
 		root = api_add_const(root, "Hash Method", SHA256STR, false);
 
 	cg_rlock(&ch_lock);
-	if (current_fullhash && *current_fullhash) {
-		root = api_add_timeval(root, "Current Block Time", &block_timeval, true);
-		root = api_add_string(root, "Current Block Hash", current_fullhash, true);
-	} else {
-		struct timeval t = {0,0};
-		root = api_add_timeval(root, "Current Block Time", &t, true);
-		root = api_add_const(root, "Current Block Hash", BLANK, false);
-	}
+	root = api_add_timeval(root, "Current Block Time", &block_timeval, true);
+	root = api_add_string(root, "Current Block Hash", current_hash, true);
 	cg_runlock(&ch_lock);
 
 	root = api_add_bool(root, "LP", &have_longpoll, false);
diff --git a/ccan/opt/helpers.d b/ccan/opt/helpers.d
deleted file mode 100644
index 669baaf..0000000
--- a/ccan/opt/helpers.d
+++ /dev/null
@@ -1,24 +0,0 @@
-ccan/opt/helpers.o: ccan/opt/helpers.c ccan/opt/opt.h \
- ccan/compiler/compiler.h config.h ccan/typesafe_cb/typesafe_cb.h \
- /usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5.2/include/stdbool.h \
- /usr/include/stdlib.h /usr/include/features.h \
- /usr/include/bits/predefs.h /usr/include/sys/cdefs.h \
- /usr/include/bits/wordsize.h /usr/include/gnu/stubs.h \
- /usr/include/gnu/stubs-32.h \
- /usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5.2/include/stddef.h \
- /usr/include/bits/waitflags.h /usr/include/bits/waitstatus.h \
- /usr/include/endian.h /usr/include/bits/endian.h \
- /usr/include/bits/byteswap.h /usr/include/xlocale.h \
- /usr/include/sys/types.h /usr/include/bits/types.h \
- /usr/include/bits/typesizes.h /usr/include/time.h \
- /usr/include/sys/select.h /usr/include/bits/select.h \
- /usr/include/bits/sigset.h /usr/include/bits/time.h \
- /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h \
- /usr/include/alloca.h /usr/include/string.h /usr/include/errno.h \
- /usr/include/bits/errno.h /usr/include/linux/errno.h \
- /usr/include/i386-linux-gnu/asm/errno.h /usr/include/asm-generic/errno.h \
- /usr/include/asm-generic/errno-base.h /usr/include/stdio.h \
- /usr/include/libio.h /usr/include/_G_config.h /usr/include/wchar.h \
- /usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5.2/include/stdarg.h \
- /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
- ccan/opt/private.h
diff --git a/ccan/opt/opt.d b/ccan/opt/opt.d
deleted file mode 100644
index 7320564..0000000
--- a/ccan/opt/opt.d
+++ /dev/null
@@ -1,26 +0,0 @@
-ccan/opt/opt.o: ccan/opt/opt.c ccan/opt/opt.h ccan/compiler/compiler.h \
- config.h ccan/typesafe_cb/typesafe_cb.h \
- /usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5.2/include/stdbool.h \
- /usr/include/stdlib.h /usr/include/features.h \
- /usr/include/bits/predefs.h /usr/include/sys/cdefs.h \
- /usr/include/bits/wordsize.h /usr/include/gnu/stubs.h \
- /usr/include/gnu/stubs-32.h \
- /usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5.2/include/stddef.h \
- /usr/include/bits/waitflags.h /usr/include/bits/waitstatus.h \
- /usr/include/endian.h /usr/include/bits/endian.h \
- /usr/include/bits/byteswap.h /usr/include/xlocale.h \
- /usr/include/sys/types.h /usr/include/bits/types.h \
- /usr/include/bits/typesizes.h /usr/include/time.h \
- /usr/include/sys/select.h /usr/include/bits/select.h \
- /usr/include/bits/sigset.h /usr/include/bits/time.h \
- /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h \
- /usr/include/alloca.h /usr/include/string.h /usr/include/errno.h \
- /usr/include/bits/errno.h /usr/include/linux/errno.h \
- /usr/include/i386-linux-gnu/asm/errno.h /usr/include/asm-generic/errno.h \
- /usr/include/asm-generic/errno-base.h /usr/include/stdio.h \
- /usr/include/libio.h /usr/include/_G_config.h /usr/include/wchar.h \
- /usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5.2/include/stdarg.h \
- /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
- /usr/include/err.h /usr/include/assert.h \
- /usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5.2/include/stdint.h \
- /usr/include/stdint.h /usr/include/bits/wchar.h ccan/opt/private.h
diff --git a/ccan/opt/parse.d b/ccan/opt/parse.d
deleted file mode 100644
index 016ba9e..0000000
--- a/ccan/opt/parse.d
+++ /dev/null
@@ -1,18 +0,0 @@
-ccan/opt/parse.o: ccan/opt/parse.c ccan/opt/opt.h \
- ccan/compiler/compiler.h config.h ccan/typesafe_cb/typesafe_cb.h \
- /usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5.2/include/stdbool.h \
- /usr/include/stdlib.h /usr/include/features.h \
- /usr/include/bits/predefs.h /usr/include/sys/cdefs.h \
- /usr/include/bits/wordsize.h /usr/include/gnu/stubs.h \
- /usr/include/gnu/stubs-32.h \
- /usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5.2/include/stddef.h \
- /usr/include/bits/waitflags.h /usr/include/bits/waitstatus.h \
- /usr/include/endian.h /usr/include/bits/endian.h \
- /usr/include/bits/byteswap.h /usr/include/xlocale.h \
- /usr/include/sys/types.h /usr/include/bits/types.h \
- /usr/include/bits/typesizes.h /usr/include/time.h \
- /usr/include/sys/select.h /usr/include/bits/select.h \
- /usr/include/bits/sigset.h /usr/include/bits/time.h \
- /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h \
- /usr/include/alloca.h /usr/include/string.h /usr/include/assert.h \
- ccan/opt/private.h
diff --git a/ccan/opt/usage.d b/ccan/opt/usage.d
deleted file mode 100644
index 0cacbfd..0000000
--- a/ccan/opt/usage.d
+++ /dev/null
@@ -1,22 +0,0 @@
-ccan/opt/usage.o: ccan/opt/usage.c ccan/opt/opt.h \
- ccan/compiler/compiler.h config.h ccan/typesafe_cb/typesafe_cb.h \
- /usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5.2/include/stdbool.h \
- /usr/include/stdlib.h /usr/include/features.h \
- /usr/include/bits/predefs.h /usr/include/sys/cdefs.h \
- /usr/include/bits/wordsize.h /usr/include/gnu/stubs.h \
- /usr/include/gnu/stubs-32.h \
- /usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5.2/include/stddef.h \
- /usr/include/bits/waitflags.h /usr/include/bits/waitstatus.h \
- /usr/include/endian.h /usr/include/bits/endian.h \
- /usr/include/bits/byteswap.h /usr/include/xlocale.h \
- /usr/include/sys/types.h /usr/include/bits/types.h \
- /usr/include/bits/typesizes.h /usr/include/time.h \
- /usr/include/sys/select.h /usr/include/bits/select.h \
- /usr/include/bits/sigset.h /usr/include/bits/time.h \
- /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h \
- /usr/include/alloca.h /usr/include/string.h /usr/include/stdio.h \
- /usr/include/libio.h /usr/include/_G_config.h /usr/include/wchar.h \
- /usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5.2/include/stdarg.h \
- /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
- /usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5.2/include/stdint.h \
- /usr/include/stdint.h /usr/include/bits/wchar.h ccan/opt/private.h
diff --git a/cgminer.c b/cgminer.c
index 429bee7..044149d 100644
--- a/cgminer.c
+++ b/cgminer.c
@@ -62,6 +62,12 @@ char *curly = ":D";
 #include "usbutils.h"
 #endif
 
+#if defined(unix) || defined(__APPLE__)
+	#include <errno.h>
+	#include <fcntl.h>
+	#include <sys/wait.h>
+#endif
+
 #ifdef USE_AVALON
 #include "driver-avalon.h"
 #endif
@@ -70,10 +76,8 @@ char *curly = ":D";
 #include "driver-bflsc.h"
 #endif
 
-#if defined(unix) || defined(__APPLE__)
-	#include <errno.h>
-	#include <fcntl.h>
-	#include <sys/wait.h>
+#ifdef USE_HASHFAST
+#include "driver-hashfast.h"
 #endif
 
 #if defined(USE_BITFORCE) || defined(USE_ICARUS) || defined(USE_AVALON) || defined(USE_MODMINER)
@@ -167,6 +171,7 @@ char *opt_icarus_timing = NULL;
 bool opt_worktime;
 #ifdef USE_AVALON
 char *opt_avalon_options = NULL;
+char *opt_bitburner_fury_options = NULL;
 #endif
 #ifdef USE_KLONDIKE
 char *opt_klondike_options = NULL;
@@ -274,11 +279,10 @@ const
 #endif
 bool curses_active;
 
-static char current_block[40];
-
 /* Protected by ch_lock */
-static char *current_hash;
-char *current_fullhash;
+char current_hash[68];
+static char prev_block[12];
+static char current_block[32];
 
 static char datestamp[40];
 static char blocktime[32];
@@ -289,7 +293,7 @@ static char block_diff[8];
 uint64_t best_diff = 0;
 
 struct block {
-	char hash[40];
+	char hash[68];
 	UT_hash_handle hh;
 	int block_no;
 };
@@ -1039,6 +1043,13 @@ static char *set_avalon_options(const char *arg)
 
 	return NULL;
 }
+
+static char *set_bitburner_fury_options(const char *arg)
+{
+	opt_set_charp(arg, &opt_bitburner_fury_options);
+
+	return NULL;
+}
 #endif
 
 #ifdef USE_KLONDIKE
@@ -1267,11 +1278,14 @@ static struct opt_table opt_config_table[] = {
 	OPT_WITH_ARG("--bitburner-fury-voltage",
 		     opt_set_intval, NULL, &opt_bitburner_fury_core_voltage,
 		     "Set BitBurner Fury core voltage, in millivolts"),
+	OPT_WITH_ARG("--bitburner-fury-options",
+		     set_bitburner_fury_options, NULL, NULL,
+		     "Override avalon-options for BitBurner Fury boards baud:miners:asic:timeout:freq"),
 #endif
 #ifdef USE_KLONDIKE
 	OPT_WITH_ARG("--klondike-options",
 		     set_klondike_options, NULL, NULL,
-		     "Set klondike options clock:temp1:temp2:fan"),
+		     "Set klondike options clock:temptarget"),
 #endif
 #ifdef USE_DRILLBIT
         OPT_WITH_ARG("--drillbit-options",
@@ -1618,12 +1632,18 @@ static char *opt_verusage_and_exit(const char *extra)
 #ifdef HAVE_OPENCL
 		"GPU "
 #endif
+#ifdef USE_HASHFAST
+		"hashfast "
+#endif
 #ifdef USE_ICARUS
 		"icarus "
 #endif
 #ifdef USE_KLONDIKE
 		"klondike "
 #endif
+#ifdef USE_KNC
+		"KnC "
+#endif
 #ifdef USE_MODMINER
 		"modminer "
 #endif
@@ -1754,7 +1774,7 @@ void free_work(struct work *work)
 }
 
 static void gen_hash(unsigned char *data, unsigned char *hash, int len);
-static void calc_diff(struct work *work, int known);
+static void calc_diff(struct work *work, double known);
 char *workpadding = "000000800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000";
 
 #ifdef HAVE_LIBCURL
@@ -2260,6 +2280,11 @@ static void get_statline(char *buf, size_t bufsiz, struct cgpu_info *cgpu)
 	cgpu->drv->get_statline(buf, bufsiz, cgpu);
 }
 
+static bool shared_strategy(void)
+{
+	return (pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE);
+}
+
 #ifdef HAVE_CURSES
 #define CURBUFSIZ 256
 #define cg_mvwprintw(win, y, x, fmt, ...) do { \
@@ -2288,7 +2313,7 @@ static void curses_print_status(void)
 		total_staged(), total_stale, new_blocks,
 		local_work, total_go, total_ro);
 	wclrtoeol(statuswin);
-	if ((pool_strategy == POOL_LOADBALANCE  || pool_strategy == POOL_BALANCE) && total_pools > 1) {
+	if (shared_strategy() && total_pools > 1) {
 		cg_mvwprintw(statuswin, 4, 0, " Connected to multiple pools with%s block change notify",
 			have_longpoll ? "": "out");
 	} else if (pool->has_stratum) {
@@ -2301,7 +2326,7 @@ static void curses_print_status(void)
 	}
 	wclrtoeol(statuswin);
 	cg_mvwprintw(statuswin, 5, 0, " Block: %s...  Diff:%s  Started: %s  Best share: %s   ",
-		  current_hash, block_diff, blocktime, best_share);
+		     prev_block, block_diff, blocktime, best_share);
 	mvwhline(statuswin, 6, 0, '-', 80);
 	mvwhline(statuswin, statusy - 1, 0, '-', 80);
 	cg_mvwprintw(statuswin, devcursor - 1, 1, "[P]ool management %s[S]ettings [D]isplay options [Q]uit",
@@ -2709,6 +2734,27 @@ static void print_status(int thr_id)
 		text_print_status(thr_id);
 }
 
+static void show_hash(struct work *work, char *hashshow)
+{
+	unsigned char rhash[32];
+	char diffdisp[16];
+	unsigned long h32;
+	uint32_t *hash32;
+	int intdiff, ofs;
+
+	swab256(rhash, work->hash);
+	for (ofs = 0; ofs <= 28; ofs ++) {
+		if (rhash[ofs])
+			break;
+	}
+	hash32 = (uint32_t *)(rhash + ofs);
+	h32 = be32toh(*hash32);
+	intdiff = round(work->work_difficulty);
+	suffix_string(work->share_diff, diffdisp, sizeof (diffdisp), 0);
+	snprintf(hashshow, 64, "%08lx Diff %s/%d%s", h32, diffdisp, intdiff,
+		 work->block? " BLOCK!" : "");
+}
+
 static bool submit_upstream_work(struct work *work, CURL *curl, bool resubmit)
 {
 	char *hexstr = NULL;
@@ -2802,20 +2848,7 @@ static bool submit_upstream_work(struct work *work, CURL *curl, bool resubmit)
 	err = json_object_get(val, "error");
 
 	if (!QUIET) {
-		int intdiff = floor(work->work_difficulty);
-		char diffdisp[16], *outhash;
-		unsigned char rhash[32];
-
-		swab256(rhash, work->hash);
-		if (opt_scrypt)
-			outhash = bin2hex(rhash + 2, 4);
-		else
-			outhash = bin2hex(rhash + 4, 4);
-		suffix_string(work->share_diff, diffdisp, sizeof(diffdisp), 0);
-		snprintf(hashshow, sizeof(hashshow), "%s Diff %s/%d%s",
-				outhash, diffdisp, intdiff,
-				work->block? " BLOCK!" : "");
-		free(outhash);
+		show_hash(work, hashshow);
 
 		if (opt_worktime) {
 			char workclone[20];
@@ -3066,43 +3099,62 @@ out:
 	return pool;
 }
 
-static double DIFFEXACTONE = 26959946667150639794667015087019630673637144422540572481103610249215.0;
-static const uint64_t diffone = 0xFFFF000000000000ull;
+/* truediffone == 0x00000000FFFF0000000000000000000000000000000000000000000000000000
+ * Generate a 256 bit binary LE target by cutting up diff into 64 bit sized
+ * portions or vice versa. */
+static const double truediffone = 26959535291011309493156476344723991336010898738574164086137773096960.0;
+static const double bits192 = 6277101735386680763835789423207666416102355444464034512896.0;
+static const double bits128 = 340282366920938463463374607431768211456.0;
+static const double bits64 = 18446744073709551616.0;
+
+/* Converts a little endian 256 bit value to a double */
+static double le256todouble(const void *target)
+{
+	uint64_t *data64;
+	double dcut64;
+
+	data64 = (uint64_t *)(target + 24);
+	dcut64 = le64toh(*data64) * bits192;
+
+	data64 = (uint64_t *)(target + 16);
+	dcut64 += le64toh(*data64) * bits128;
+
+	data64 = (uint64_t *)(target + 8);
+	dcut64 += le64toh(*data64) * bits64;
+
+	data64 = (uint64_t *)(target);
+	dcut64 += le64toh(*data64);
+
+	return dcut64;
+}
 
 /*
- * Calculate the work share difficulty
+ * Calculate the work->work_difficulty based on the work->target
  */
-static void calc_diff(struct work *work, int known)
+static void calc_diff(struct work *work, double known)
 {
 	struct cgminer_pool_stats *pool_stats = &(work->pool->cgminer_pool_stats);
 	double difficulty;
+	int intdiff;
 
-	if (opt_scrypt) {
-		uint64_t *data64, d64;
-		char rtarget[32];
-
-		swab256(rtarget, work->target);
-		data64 = (uint64_t *)(rtarget + 2);
-		d64 = be64toh(*data64);
-		if (unlikely(!d64))
-			d64 = 1;
-		work->work_difficulty = diffone / d64;
-	} else if (!known) {
-		double targ = 0;
-		int i;
-
-		for (i = 31; i >= 0; i--) {
-			targ *= 256;
-			targ += work->target[i];
-		}
-
-		work->work_difficulty = DIFFEXACTONE / (targ ? : DIFFEXACTONE);
-	} else
+	if (known)
 		work->work_difficulty = known;
+	else {
+		double d64, dcut64;
+
+		d64 = truediffone;
+		if (opt_scrypt)
+			d64 *= (double)65536;
+		dcut64 = le256todouble(work->target);
+		if (unlikely(!dcut64))
+			dcut64 = 1;
+		work->work_difficulty = d64 / dcut64;
+	}
 	difficulty = work->work_difficulty;
 
 	pool_stats->last_diff = difficulty;
-	suffix_string((uint64_t)difficulty, work->pool->diff, sizeof(work->pool->diff), 0);
+	intdiff = round(difficulty);
+	suffix_string(intdiff, work->pool->diff, sizeof(work->pool->diff), 0);
 
 	if (difficulty == pool_stats->min_diff)
 		pool_stats->min_diff_count++;
@@ -3149,9 +3201,22 @@ static void disable_curses_windows(void)
 	delwin(statuswin);
 }
 
+/* Force locking of curses console_lock on shutdown since a dead thread might
+ * have grabbed the lock. */
+static bool curses_active_forcelocked(void)
+{
+	bool ret;
+
+	mutex_trylock(&console_lock);
+	ret = curses_active;
+	if (!ret)
+		unlock_curses();
+	return ret;
+}
+
 static void disable_curses(void)
 {
-	if (curses_active_locked()) {
+	if (curses_active_forcelocked()) {
 		use_curses = false;
 		curses_active = false;
 		disable_curses_windows();
@@ -3615,12 +3680,14 @@ static void _copy_work(struct work *work, const struct work *base_work, int noff
 }
 
 /* Generates a copy of an existing work struct, creating fresh heap allocations
- * for all dynamically allocated arrays within the struct */
-struct work *copy_work(struct work *base_work)
+ * for all dynamically allocated arrays within the struct. noffset is used for
+ * when a driver has internally rolled the ntime, noffset is a relative value.
+ * The macro copy_work() calls this function with an noffset of 0. */
+struct work *copy_work_noffset(struct work *base_work, int noffset)
 {
 	struct work *work = make_work();
 
-	_copy_work(work, base_work, 0);
+	_copy_work(work, base_work, noffset);
 
 	return work;
 }
@@ -3707,19 +3774,18 @@ static bool stale_work(struct work *work, bool share)
 
 static uint64_t share_diff(const struct work *work)
 {
-	uint64_t *data64, d64, ret;
 	bool new_best = false;
-	char rhash[32];
+	double d64, s64;
+	uint64_t ret;
 
-	swab256(rhash, work->hash);
+	d64 = truediffone;
 	if (opt_scrypt)
-		data64 = (uint64_t *)(rhash + 2);
-	else
-		data64 = (uint64_t *)(rhash + 4);
-	d64 = be64toh(*data64);
-	if (unlikely(!d64))
-		d64 = 1;
-	ret = diffone / d64;
+		d64 *= (double)65536;
+	s64 = le256todouble(work->hash);
+	if (unlikely(!s64))
+		s64 = 0;
+
+	ret = round(d64 / s64);
 
 	cg_wlock(&control_lock);
 	if (unlikely(ret > best_diff)) {
@@ -3876,8 +3942,11 @@ void switch_pools(struct pool *selected)
 void discard_work(struct work *work)
 {
 	if (!work->clone && !work->rolls && !work->mined) {
-		if (work->pool)
+		if (work->pool) {
 			work->pool->discarded_work++;
+			work->pool->quota_used--;
+			work->pool->works--;
+		}
 		total_discarded++;
 		applog(LOG_DEBUG, "Discarded work");
 	} else
@@ -3940,9 +4009,12 @@ int restart_wait(struct thr_info *thr, unsigned int mstime)
 	return rc;
 }
 	
+static void flush_queue(struct cgpu_info *cgpu);
+
 static void restart_threads(void)
 {
 	struct pool *cp = current_pool();
+	struct cgpu_info *cgpu;
 	int i;
 
 	/* Artificially set the lagging flag to avoid pool not providing work
@@ -3953,8 +4025,12 @@ static void restart_threads(void)
 	discard_stale();
 
 	rd_lock(&mining_thr_lock);
-	for (i = 0; i < mining_threads; i++)
+	for (i = 0; i < mining_threads; i++) {
+		cgpu = mining_thr[i]->cgpu;
 		mining_thr[i]->work_restart = true;
+		flush_queue(cgpu);
+		cgpu->drv->flush_work(cgpu);
+	}
 	rd_unlock(&mining_thr_lock);
 
 	mutex_lock(&restart_lock);
@@ -3981,24 +4057,24 @@ static void signal_work_update(void)
 	rd_unlock(&mining_thr_lock);
 }
 
-static void set_curblock(char *hexstr, unsigned char *hash)
+static void set_curblock(char *hexstr, unsigned char *bedata)
 {
-	unsigned char hash_swap[32];
-	unsigned char block_hash_swap[32];
-
-	strcpy(current_block, hexstr);
-	swap256(hash_swap, hash);
-	swap256(block_hash_swap, hash + 4);
+	int ofs;
 
 	cg_wlock(&ch_lock);
 	cgtime(&block_timeval);
-	free(current_hash);
-	current_hash = bin2hex(hash_swap + 2, 8);
-	free(current_fullhash);
-	current_fullhash = bin2hex(block_hash_swap, 32);
+	strcpy(current_hash, hexstr);
+	memcpy(current_block, bedata, 32);
 	get_timestamp(blocktime, sizeof(blocktime), &block_timeval);
 	cg_wunlock(&ch_lock);
 
+	for (ofs = 0; ofs <= 56; ofs++) {
+		if (memcmp(&current_hash[ofs], "0", 1))
+			break;
+	}
+	strncpy(prev_block, &current_hash[ofs], 8);
+	prev_block[8] = '\0';
+
 	applog(LOG_INFO, "New block: %s... diff %s", current_hash, block_diff);
 }
 
@@ -4032,72 +4108,40 @@ static int block_sort(struct block *blocka, struct block *blockb)
 	return blocka->block_no - blockb->block_no;
 }
 
+/* Decode the current block difficulty which is in packed form */
 static void set_blockdiff(const struct work *work)
 {
-	uint64_t *data64, d64, diff64;
-	double previous_diff;
-	uint32_t diffhash[8];
-	uint32_t difficulty;
-	uint32_t diffbytes;
-	uint32_t diffvalue;
-	char rhash[32];
-	int diffshift;
-
-	difficulty = swab32(*((uint32_t *)(work->data + 72)));
-
-	diffbytes = ((difficulty >> 24) & 0xff) - 3;
-	diffvalue = difficulty & 0x00ffffff;
+	uint8_t pow = work->data[72];
+	int powdiff = (8 * (0x1d - 3)) - (8 * (pow - 3));
+	uint32_t diff32 = swab32(*((uint32_t *)(work->data + 72))) & 0x00FFFFFF;
+	double numerator = 0xFFFFULL << powdiff;
+	double ddiff = numerator / (double)diff32;
 
-	diffshift = (diffbytes % 4) * 8;
-	if (diffshift == 0) {
-		diffshift = 32;
-		diffbytes--;
-	}
-
-	memset(diffhash, 0, 32);
-	diffbytes >>= 2;
-	if (unlikely(diffbytes > 6))
-		return;
-	diffhash[diffbytes + 1] = diffvalue >> (32 - diffshift);
-	diffhash[diffbytes] = diffvalue << diffshift;
-
-	swab256(rhash, diffhash);
-
-	if (opt_scrypt)
-		data64 = (uint64_t *)(rhash + 2);
-	else
-		data64 = (uint64_t *)(rhash + 4);
-	d64 = bswap_64(*data64);
-	if (unlikely(!d64))
-		d64 = 1;
-
-	previous_diff = current_diff;
-	diff64 = diffone / d64;
-	suffix_string(diff64, block_diff, sizeof(block_diff), 0);
-	current_diff = (double)diffone / (double)d64;
-	if (unlikely(current_diff != previous_diff))
+	if (unlikely(current_diff != ddiff)) {
+		suffix_string(ddiff, block_diff, sizeof(block_diff), 0);
+		current_diff = ddiff;
 		applog(LOG_NOTICE, "Network diff set to %s", block_diff);
+	}
 }
 
 static bool test_work_current(struct work *work)
 {
+	struct pool *pool = work->pool;
+	unsigned char bedata[32];
+	char hexstr[68];
 	bool ret = true;
-	char hexstr[40];
 
 	if (work->mandatory)
 		return ret;
 
-	/* Hack to work around dud work sneaking into test */
-	__bin2hex(hexstr, work->data + 8, 18);
-	if (!strncmp(hexstr, "000000000000000000000000000000000000", 36))
-		return ret;
+	swap256(bedata, work->data + 4);
+	__bin2hex(hexstr, bedata, 32);
 
 	/* Search to see if this block exists yet and if not, consider it a
 	 * new block and set the current block details to this one */
 	if (!block_exists(hexstr)) {
 		struct block *s = calloc(sizeof(struct block), 1);
 		int deleted_block = 0;
-		ret = false;
 
 		if (unlikely(!s))
 			quit (1, "test_work_current OOM");
@@ -4123,31 +4167,71 @@ static bool test_work_current(struct work *work)
 
 		if (deleted_block)
 			applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
-		set_curblock(hexstr, work->data);
-		if (unlikely(new_blocks == 1))
-			return ret;
+		set_curblock(hexstr, bedata);
+		/* Copy the information to this pool's prev_block since it
+		 * knows the new block exists. */
+		memcpy(pool->prev_block, bedata, 32);
+		if (unlikely(new_blocks == 1)) {
+			ret = false;
+			goto out;
+		}
 
 		work->work_block = ++work_block;
 
-		if (!work->stratum) {
-			if (work->longpoll) {
+		if (work->longpoll) {
+			if (work->stratum) {
+				applog(LOG_NOTICE, "Stratum from pool %d detected new block",
+				       pool->pool_no);
+			} else {
 				applog(LOG_NOTICE, "%sLONGPOLL from pool %d detected new block",
 				       work->gbt ? "GBT " : "", work->pool->pool_no);
-			} else if (have_longpoll)
-				applog(LOG_NOTICE, "New block detected on network before longpoll");
-			else
-				applog(LOG_NOTICE, "New block detected on network");
-		}
+			}
+		} else if (have_longpoll)
+			applog(LOG_NOTICE, "New block detected on network before longpoll");
+		else
+			applog(LOG_NOTICE, "New block detected on network");
 		restart_threads();
-	} else if (work->longpoll) {
-		work->work_block = ++work_block;
-		if (work->pool == current_pool()) {
-			applog(LOG_NOTICE, "%sLONGPOLL from pool %d requested work restart",
-			       work->gbt ? "GBT " : "", work->pool->pool_no);
-			restart_threads();
+	} else {
+		if (memcmp(pool->prev_block, bedata, 32)) {
+			/* Work doesn't match what this pool has stored as
+			 * prev_block. Let's see if the work is from an old
+			 * block or the pool is just learning about a new
+			 * block. */
+			if (memcmp(bedata, current_block, 32)) {
+				/* Doesn't match current block. It's stale */
+				applog(LOG_DEBUG, "Stale data from pool %d", pool->pool_no);
+				ret = false;
+			} else {
+				/* Work is from new block and pool is up now
+				 * current. */
+				applog(LOG_INFO, "Pool %d now up to date", pool->pool_no);
+				memcpy(pool->prev_block, bedata, 32);
+			}
+		}
+#if 0
+		/* This isn't ideal, this pool is still on an old block but
+		 * accepting shares from it. To maintain fair work distribution
+		 * we work on it anyway. */
+		if (memcmp(bedata, current_block, 32))
+			applog(LOG_DEBUG, "Pool %d still on old block", pool->pool_no);
+#endif
+		if (work->longpoll) {
+			work->work_block = ++work_block;
+			if (shared_strategy() || work->pool == current_pool()) {
+				if (work->stratum) {
+					applog(LOG_NOTICE, "Stratum from pool %d requested work restart",
+					       pool->pool_no);
+				} else {
+					applog(LOG_NOTICE, "%sLONGPOLL from pool %d requested work restart",
+					       work->gbt ? "GBT " : "", work->pool->pool_no);
+				}
+				restart_threads();
+			}
 		}
 	}
+out:
 	work->longpoll = false;
+
 	return ret;
 }
 
@@ -4220,6 +4304,7 @@ static void stage_work(struct work *work)
 	applog(LOG_DEBUG, "Pushing work from pool %d to hash queue", work->pool->pool_no);
 	work->work_block = work_block;
 	test_work_current(work);
+	work->pool->works++;
 	hash_push(work);
 }
 
@@ -4263,6 +4348,7 @@ static void display_pool_summary(struct pool *pool)
 		if (!pool_localgen(pool))
 			wlog(" Efficiency (accepted / queued): %.0f%%\n", efficiency);
 
+		wlog(" Items worked on: %d\n", pool->works);
 		wlog(" Discarded work due to new blocks: %d\n", pool->discarded_work);
 		wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
 		wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
@@ -5154,7 +5240,7 @@ static void hashmeter(int thr_id, struct timeval *diff,
 
 	local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
 	decay_time(&total_rolling, local_mhashes_done / local_secs, local_secs);
-	global_hashrate = roundl(total_rolling) * 1000000;
+	global_hashrate = llround(total_rolling) * 1000000;
 
 	timersub(&total_tv_end, &total_tv_start, &total_diff);
 	total_secs = (double)total_diff.tv_sec +
@@ -5190,16 +5276,8 @@ static void stratum_share_result(json_t *val, json_t *res_val, json_t *err_val,
 {
 	struct work *work = sshare->work;
 	char hashshow[64];
-	uint32_t *hash32;
-	char diffdisp[16];
-	int intdiff;
 
-	hash32 = (uint32_t *)(work->hash);
-	intdiff = floor(work->work_difficulty);
-	suffix_string(work->share_diff, diffdisp, sizeof (diffdisp), 0);
-	snprintf(hashshow, sizeof(hashshow),
-		"%08lx Diff %s/%d%s", (unsigned long)htole32(hash32[6]), diffdisp, intdiff,
-		work->block? " BLOCK!" : "");
+	show_hash(work, hashshow);
 	share_result(val, res_val, err_val, work, hashshow, false, "");
 }
 
@@ -5512,15 +5590,10 @@ static void *stratum_rthread(void *userdata)
 			 * block database */
 			pool->swork.clean = false;
 			gen_stratum_work(pool, work);
-			if (test_work_current(work)) {
-				/* Only accept a work restart if this stratum
-				 * connection is from the current pool */
-				if (pool == current_pool()) {
-					restart_threads();
-					applog(LOG_NOTICE, "Stratum from pool %d requested work restart", pool->pool_no);
-				}
-			} else
-				applog(LOG_NOTICE, "Stratum from pool %d detected new block", pool->pool_no);
+			work->longpoll = true;
+			/* Return value doesn't matter. We're just informing
+			 * that we may need to restart. */
+			test_work_current(work);
 			free_work(work);
 		}
 	}
@@ -5879,24 +5952,22 @@ static struct work *hash_pop(void)
 
 	mutex_lock(stgd_lock);
 	while (!HASH_COUNT(staged_work)) {
-		if (!no_work) {
-			struct timespec then;
-			struct timeval now;
-			int rc;
+		struct timespec then;
+		struct timeval now;
+		int rc;
 
-			cgtime(&now);
-			then.tv_sec = now.tv_sec + 10;
-			then.tv_nsec = now.tv_usec * 1000;
-			rc = pthread_cond_timedwait(&getq->cond, stgd_lock, &then);
-			/* Check again for !no_work as multiple threads may be
-			 * waiting on this condition and another may set the
-			 * bool separately. */
-			if (rc && !no_work) {
-				no_work = true;
-				applog(LOG_WARNING, "Waiting for work to be available from pools.");
-			}
-		} else
-			pthread_cond_wait(&getq->cond, stgd_lock);
+		cgtime(&now);
+		then.tv_sec = now.tv_sec + 10;
+		then.tv_nsec = now.tv_usec * 1000;
+		pthread_cond_signal(&gws_cond);
+		rc = pthread_cond_timedwait(&getq->cond, stgd_lock, &then);
+		/* Check again for !no_work as multiple threads may be
+			* waiting on this condition and another may set the
+			* bool separately. */
+		if (rc && !no_work) {
+			no_work = true;
+			applog(LOG_WARNING, "Waiting for work to be available from pools.");
+		}
 	}
 
 	if (no_work) {
@@ -5935,38 +6006,50 @@ static void gen_hash(unsigned char *data, unsigned char *hash, int len)
 	sha256(hash1, 32, hash);
 }
 
-/* Diff 1 is a 256 bit unsigned integer of
- * 0x00000000ffff0000000000000000000000000000000000000000000000000000
- * so we use a big endian 64 bit unsigned integer centred on the 5th byte to
- * cover a huge range of difficulty targets, though not all 256 bits' worth */
 void set_target(unsigned char *dest_target, double diff)
 {
 	unsigned char target[32];
 	uint64_t *data64, h64;
-	double d64;
+	double d64, dcut64;
+
+	if (unlikely(diff == 0.0)) {
+		/* This shouldn't happen but best we check to prevent a crash */
+		applog(LOG_ERR, "Diff zero passed to set_target");
+		diff = 1.0;
+	}
 
-	d64 = diffone;
+	d64 = truediffone;
+	if (opt_scrypt)
+		d64 *= (double)65536;
 	d64 /= diff;
-	h64 = d64;
 
-	memset(target, 0, 32);
-	if (h64) {
-		unsigned char rtarget[32];
+	dcut64 = d64 / bits192;
+	h64 = dcut64;
+	data64 = (uint64_t *)(target + 24);
+	*data64 = htole64(h64);
+	dcut64 = h64;
+	dcut64 *= bits192;
+	d64 -= dcut64;
+
+	dcut64 = d64 / bits128;
+	h64 = dcut64;
+	data64 = (uint64_t *)(target + 16);
+	*data64 = htole64(h64);
+	dcut64 = h64;
+	dcut64 *= bits128;
+	d64 -= dcut64;
+
+	dcut64 = d64 / bits64;
+	h64 = dcut64;
+	data64 = (uint64_t *)(target + 8);
+	*data64 = htole64(h64);
+	dcut64 = h64;
+	dcut64 *= bits64;
+	d64 -= dcut64;
 
-		memset(rtarget, 0, 32);
-		if (opt_scrypt)
-			data64 = (uint64_t *)(rtarget + 2);
-		else
-			data64 = (uint64_t *)(rtarget + 4);
-		*data64 = htobe64(h64);
-		swab256(target, rtarget);
-	} else {
-		/* Support for the classic all FFs just-below-1 diff */
-		if (opt_scrypt)
-			memset(target, 0xff, 30);
-		else
-			memset(target, 0xff, 28);
-	}
+	h64 = d64;
+	data64 = (uint64_t *)(target);
+	*data64 = htole64(h64);
 
 	if (opt_debug) {
 		char *htarget = bin2hex(target, 32);
@@ -6131,26 +6214,57 @@ void inc_hw_errors(struct thr_info *thr)
 	thr->cgpu->drv->hw_error(thr);
 }
 
-bool test_nonce(struct work *work, uint32_t nonce)
+/* Fills in the work nonce and builds the output data in work->hash */
+static void rebuild_nonce(struct work *work, uint32_t nonce)
 {
 	uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
-	uint32_t *hash2_32 = (uint32_t *)work->hash2;
-	uint32_t diff1targ;
 
 	*work_nonce = htole32(nonce);
 
-	/* Do one last check before attempting to submit the work */
 	rebuild_hash(work);
-	flip32(hash2_32, work->hash);
+}
 
+/* For testing a nonce against diff 1 */
+bool test_nonce(struct work *work, uint32_t nonce)
+{
+	uint32_t *hash_32 = (uint32_t *)(work->hash + 28);
+	uint32_t diff1targ;
+
+	rebuild_nonce(work, nonce);
 	diff1targ = opt_scrypt ? 0x0000ffffUL : 0;
-	return (be32toh(hash2_32[7]) <= diff1targ);
+
+	return (le32toh(*hash_32) <= diff1targ);
+}
+
+/* For testing a nonce against an arbitrary diff */
+bool test_nonce_diff(struct work *work, uint32_t nonce, double diff)
+{
+	uint64_t *hash64 = (uint64_t *)(work->hash + 24), diff64;
+
+	rebuild_nonce(work, nonce);
+	diff64 = opt_scrypt ? 0x0000ffff00000000ULL : 0x00000000ffff0000ULL;
+	diff64 /= diff;
+
+	return (le64toh(*hash64) <= diff64);
 }
 
 static void update_work_stats(struct thr_info *thr, struct work *work)
 {
+	double test_diff = current_diff;
+
 	work->share_diff = share_diff(work);
 
+	if (opt_scrypt)
+		test_diff *= 65536;
+
+	if (unlikely(work->share_diff >= test_diff)) {
+		work->block = true;
+		work->pool->solved++;
+		found_blocks++;
+		work->mandatory = true;
+		applog(LOG_NOTICE, "Found block for pool %d!", work->pool->pool_no);
+	}
+
 	mutex_lock(&stats_lock);
 	total_diff1 += work->device_diff;
 	thr->cgpu->diff1 += work->device_diff;
@@ -6166,8 +6280,8 @@ void submit_tested_work(struct thr_info *thr, struct work *work)
 	struct work *work_out;
 	update_work_stats(thr, work);
 
-	if (!fulltest(work->hash2, work->target)) {
-		applog(LOG_INFO, "Share below target");
+	if (!fulltest(work->hash, work->target)) {
+		applog(LOG_INFO, "Share above target");
 		return;
 	}
 	work_out = copy_work(work);
@@ -6204,8 +6318,8 @@ bool submit_noffset_nonce(struct thr_info *thr, struct work *work_in, uint32_t n
 	}
 	ret = true;
 	update_work_stats(thr, work);
-	if (!fulltest(work->hash2, work->target)) {
-		applog(LOG_INFO, "Share below target");
+	if (!fulltest(work->hash, work->target)) {
+		applog(LOG_INFO, "Share above target");
 		goto  out;
 	}
 	submit_work_async(work);
@@ -6524,7 +6638,13 @@ static void flush_queue(struct cgpu_info *cgpu)
 {
 	struct work *work = NULL;
 
-	wr_lock(&cgpu->qlock);
+	if (unlikely(!cgpu))
+		return;
+
+	/* Use only a trylock in case we get into a deadlock with a queueing
+	 * function holding the read lock when we're called. */
+	if (wr_trylock(&cgpu->qlock))
+		return;
 	work = cgpu->unqueued_work;
 	cgpu->unqueued_work = NULL;
 	wr_unlock(&cgpu->qlock);
@@ -6578,10 +6698,7 @@ void hash_queued_work(struct thr_info *mythr)
 		if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
 			mt_disable(mythr, thr_id, drv);
 
-		if (unlikely(mythr->work_restart)) {
-			flush_queue(cgpu);
-			drv->flush_work(cgpu);
-		} else if (mythr->work_update)
+		if (mythr->work_update)
 			drv->update_work(cgpu);
 	}
 	cgpu->deven = DEV_DISABLED;
@@ -6628,9 +6745,7 @@ void hash_driver_work(struct thr_info *mythr)
 		if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
 			mt_disable(mythr, thr_id, drv);
 
-		if (unlikely(mythr->work_restart))
-			drv->flush_work(cgpu);
-		else if (mythr->work_update)
+		if (mythr->work_update)
 			drv->update_work(cgpu);
 	}
 	cgpu->deven = DEV_DISABLED;
@@ -7250,6 +7365,7 @@ void print_summary(void)
 			if (pool->accepted || pool->rejected)
 				applog(LOG_WARNING, " Reject ratio: %.1f%%", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
 
+			applog(LOG_WARNING, " Items worked on: %d", pool->works);
 			applog(LOG_WARNING, " Stale submissions discarded due to new blocks: %d", pool->stale_shares);
 			applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
 			applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
@@ -7291,15 +7407,11 @@ static void clean_up(bool restarting)
 #ifdef WIN32
 	timeEndPeriod(1);
 #endif
-	if (!restarting) {
-		/* Attempting to disable curses or print a summary during a
-		 * restart can lead to a deadlock. */
 #ifdef HAVE_CURSES
-		disable_curses();
+	disable_curses();
 #endif
-		if (!opt_realquiet && successful_connect)
-			print_summary();
-	}
+	if (!restarting && !opt_realquiet && successful_connect)
+		print_summary();
 
 	curl_global_cleanup();
 }
@@ -7978,7 +8090,7 @@ int main(int argc, char *argv[])
 	for (i = 0; i < 36; i++)
 		strcat(block->hash, "0");
 	HASH_ADD_STR(blocks, hash, block);
-	strcpy(current_block, block->hash);
+	strcpy(current_hash, block->hash);
 
 	INIT_LIST_HEAD(&scan_devices);
 
diff --git a/configure.ac b/configure.ac
index af7472d..895e886 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1,8 +1,8 @@
 ##--##--##--##--##--##--##--##--##--##--##--##--##--##--##--##--##
 ##--##--##--##--##--##--##--##--##--##--##--##--##--##--##--##--##
 m4_define([v_maj], [3])
-m4_define([v_min], [6])
-m4_define([v_mic], [4])
+m4_define([v_min], [7])
+m4_define([v_mic], [0])
 ##--##--##--##--##--##--##--##--##--##--##--##--##--##--##--##--##
 m4_define([v_ver], [v_maj.v_min.v_mic])
 m4_define([lt_rev], m4_eval(v_maj + v_min))
@@ -221,6 +221,28 @@ fi
 
 AM_CONDITIONAL([HAS_SCRYPT], [test x$scrypt = xyes])
 
+avalon="no"
+
+AC_ARG_ENABLE([avalon],
+	[AC_HELP_STRING([--enable-avalon],[Compile support for Avalon (default disabled)])],
+	[avalon=$enableval]
+	)
+if test "x$avalon" = xyes; then
+	AC_DEFINE([USE_AVALON], [1], [Defined to 1 if Avalon support is wanted])
+fi
+AM_CONDITIONAL([HAS_AVALON], [test x$avalon = xyes])
+
+knc="no"
+
+AC_ARG_ENABLE([knc],
+	[AC_HELP_STRING([--enable-knc],[Compile support for KnC miners (default disabled)])],
+	[knc=$enableval]
+	)
+if test "x$knc" = xyes; then
+	AC_DEFINE([USE_KNC], [1], [Defined to 1 if KnC miner support is wanted])
+fi
+AM_CONDITIONAL([HAS_KNC], [test x$knc = xyes])
+
 bflsc="no"
 
 AC_ARG_ENABLE([bflsc],
@@ -265,8 +287,18 @@ if test "x$drillbit" = xyes; then
 fi
 AM_CONDITIONAL([HAS_DRILLBIT], [test x$drillbit = xyes])
 
+hashfast="no"
+
+AC_ARG_ENABLE([hashfast],
+	[AC_HELP_STRING([--enable-hashfast],[Compile support for Hashfast (default disabled)])],
+	[hashfast=$enableval]
+	)
+if test "x$hashfast" = xyes; then
+	AC_DEFINE([USE_HASHFAST], [1], [Defined to 1 if Hashfast support is wanted])
+fi
+AM_CONDITIONAL([HAS_HASHFAST], [test x$hashfast = xyes])
 
-Icarus="no"
+icarus="no"
 
 AC_ARG_ENABLE([icarus],
 	[AC_HELP_STRING([--enable-icarus],[Compile support for Icarus (default disabled)])],
@@ -277,17 +309,6 @@ if test "x$icarus" = xyes; then
 fi
 AM_CONDITIONAL([HAS_ICARUS], [test x$icarus = xyes])
 
-avalon="no"
-
-AC_ARG_ENABLE([avalon],
-	[AC_HELP_STRING([--enable-avalon],[Compile support for Avalon (default disabled)])],
-	[avalon=$enableval]
-	)
-if test "x$avalon" = xyes; then
-	AC_DEFINE([USE_AVALON], [1], [Defined to 1 if Avalon support is wanted])
-fi
-AM_CONDITIONAL([HAS_AVALON], [test x$avalon = xyes])
-
 klondike="no"
 
 AC_ARG_ENABLE([klondike],
@@ -334,7 +355,7 @@ else
 	])
 fi
 
-if test x$avalon$bitforce$bitfury$drillbit$modminer$bflsc$icarus$klondike != xnononononononono; then
+if test x$avalon$bitforce$bitfury$modminer$bflsc$icarus$hashfast$klondike$drillbit != xnonononononononono; then
 	want_usbutils=true
 else
 	want_usbutils=false
@@ -527,14 +548,14 @@ if test "x$opencl" != xno; then
 
 	else
 		echo "  OpenCL...............: NOT FOUND. GPU mining support DISABLED"
-		if test "x$avalon$bitforce$bitfury$drillbit$icarus$modminer$bflsc$klondike" = xnononononononono; then
+		if test "x$avalon$bitforce$bitfury$icarus$modminer$bflsc$hashfast$klondike$knc$drillbit" = xnononononononononono; then
 			AC_MSG_ERROR([No mining configured in])
 		fi
 		echo "  scrypt...............: Disabled (needs OpenCL)"
 	fi
 else
 	echo "  OpenCL...............: Detection overrided. GPU mining support DISABLED"
-	if test "x$avalon$bitforce$bitfury$drillbit$icarus$modminer$bflsc$klondike" = xnononononononono; then
+	if test "x$avalon$bitforce$bitfury$icarus$modminer$bflsc$hashfast$klondike$knc$drillbit" = xnononononononononono; then
 		AC_MSG_ERROR([No mining configured in])
 	fi
 	echo "  scrypt...............: Disabled (needs OpenCL)"
@@ -563,6 +584,12 @@ else
 	echo "  BFL.ASICs............: Disabled"
 fi
 
+if test "x$knc" = xyes; then
+	echo "  KnC.ASICs............: Enabled"
+else
+	echo "  KnC.ASICs............: Disabled"
+fi
+
 if test "x$bitforce" = xyes; then
 	echo "  BitForce.FPGAs.......: Enabled"
 else
@@ -581,11 +608,16 @@ else
 	echo "  Drillbit.BitFury........: Disabled"
 fi
 
+if test "x$hashfast" = xyes; then
+	echo "  Hashfast.ASICs.......: Enabled"
+else
+	echo "  Hashfast.ASICs.......: Disabled"
+fi
 
 if test "x$icarus" = xyes; then
-	echo "  Icarus.FPGAs.........: Enabled"
+	echo "  Icarus.ASICs/FPGAs...: Enabled"
 else
-	echo "  Icarus.FPGAs.........: Disabled"
+	echo "  Icarus.ASICs/FPGAs...: Disabled"
 fi
 
 if test "x$klondike" = xyes; then
diff --git a/driver-avalon.c b/driver-avalon.c
index 09e6dfa..796085a 100644
--- a/driver-avalon.c
+++ b/driver-avalon.c
@@ -53,6 +53,7 @@ int opt_bitburner_fury_core_voltage = BITBURNER_FURY_DEFAULT_CORE_VOLTAGE;
 bool opt_avalon_auto;
 
 static int option_offset = -1;
+static int bbf_option_offset = -1;
 
 static int avalon_init_task(struct avalon_task *at,
 			    uint8_t reset, uint8_t ff, uint8_t fan,
@@ -400,7 +401,7 @@ static int avalon_calc_timeout(int frequency)
 }
 
 static bool get_options(int this_option_offset, int *baud, int *miner_count,
-			int *asic_count, int *timeout, int *frequency)
+			int *asic_count, int *timeout, int *frequency, char *options)
 {
 	char buf[BUFSIZ+1];
 	char *ptr, *comma, *colon, *colon2, *colon3, *colon4;
@@ -408,10 +409,10 @@ static bool get_options(int this_option_offset, int *baud, int *miner_count,
 	size_t max;
 	int i, tmp;
 
-	if (opt_avalon_options == NULL)
+	if (options == NULL)
 		buf[0] = '\0';
 	else {
-		ptr = opt_avalon_options;
+		ptr = options;
 		for (i = 0; i < this_option_offset; i++) {
 			comma = strchr(ptr, ',');
 			if (comma == NULL)
@@ -754,7 +755,7 @@ static void bitburner_get_version(struct cgpu_info *avalon)
 static bool avalon_detect_one(libusb_device *dev, struct usb_find_devices *found)
 {
 	int baud, miner_count, asic_count, timeout, frequency;
-	int this_option_offset = ++option_offset;
+	int this_option_offset;
 	struct avalon_info *info;
 	struct cgpu_info *avalon;
 	bool configured;
@@ -768,17 +769,17 @@ static bool avalon_detect_one(libusb_device *dev, struct usb_find_devices *found
 	timeout = AVALON_DEFAULT_TIMEOUT;
 	frequency = AVALON_DEFAULT_FREQUENCY;
 
-	configured = get_options(this_option_offset, &baud, &miner_count,
-				 &asic_count, &timeout, &frequency);
-
 	if (!usb_init(avalon, dev, found))
 		goto shin;
 
+	this_option_offset = usb_ident(avalon) == IDENT_BBF ? ++bbf_option_offset : ++option_offset;
+	configured = get_options(this_option_offset, &baud, &miner_count,
+				 &asic_count, &timeout, &frequency,
+				 (usb_ident(avalon) == IDENT_BBF && opt_bitburner_fury_options != NULL) ? opt_bitburner_fury_options : opt_avalon_options);
+
 	/* Even though this is an FTDI type chip, we want to do the parsing
 	 * all ourselves so set it to std usb type */
 	avalon->usbdev->usb_type = USB_TYPE_STD;
-	usb_set_pps(avalon, AVALON_USB_PACKETSIZE);
-	usb_buffer_enable(avalon);
 
 	/* We have a real Avalon! */
 	avalon_initialise(avalon);
@@ -796,10 +797,18 @@ static bool avalon_detect_one(libusb_device *dev, struct usb_find_devices *found
 		info->frequency = frequency;
 	} else {
 		info->baud = AVALON_IO_SPEED;
-		info->miner_count = AVALON_DEFAULT_MINER_NUM;
 		info->asic_count = AVALON_DEFAULT_ASIC_NUM;
-		info->timeout = AVALON_DEFAULT_TIMEOUT;
-		info->frequency = AVALON_DEFAULT_FREQUENCY;
+		switch (usb_ident(avalon)) {
+		case IDENT_BBF:
+			info->miner_count = BITBURNER_FURY_DEFAULT_MINER_NUM;
+			info->timeout = BITBURNER_FURY_DEFAULT_TIMEOUT;
+			info->frequency = BITBURNER_FURY_DEFAULT_FREQUENCY;
+			break;
+		default:
+			info->miner_count = AVALON_DEFAULT_MINER_NUM;
+			info->timeout = AVALON_DEFAULT_TIMEOUT;
+			info->frequency = AVALON_DEFAULT_FREQUENCY;
+		}
 	}
 
 	info->fan_pwm = AVALON_DEFAULT_FAN_MIN_PWM;
diff --git a/driver-avalon.h b/driver-avalon.h
index e506388..e84ddbb 100644
--- a/driver-avalon.h
+++ b/driver-avalon.h
@@ -55,10 +55,15 @@
 #define AVALON_MAX_MINER_NUM 0x100
 #define AVALON_DEFAULT_ASIC_NUM 0xA
 
+/* Default number of miners for Bitburner Fury is for a stack of 8 boards,
+   but it will work acceptably for smaller stacks, too */
+#define BITBURNER_FURY_DEFAULT_MINER_NUM 128
+#define BITBURNER_FURY_DEFAULT_FREQUENCY 256
+#define BITBURNER_FURY_DEFAULT_TIMEOUT 50
+
 #define AVALON_AUTO_CYCLE 1024
 
 #define AVALON_FTDI_READSIZE 510
-#define AVALON_USB_PACKETSIZE 512
 #define AVALON_READBUF_SIZE 8192
 #define AVALON_RESET_TIMEOUT 100
 #define AVALON_READ_TIMEOUT 18 /* Enough to only half fill the buffer */
diff --git a/driver-bflsc.c b/driver-bflsc.c
index a64e552..f3e45c4 100644
--- a/driver-bflsc.c
+++ b/driver-bflsc.c
@@ -888,8 +888,6 @@ reinit:
 	mutex_init(&bflsc->device_mutex);
 	rwlock_init(&sc_info->stat_lock);
 
-	usb_buffer_enable(bflsc);
-
 	return true;
 
 unshin:
diff --git a/driver-bitfury.c b/driver-bitfury.c
index 260f4f6..69f3aca 100644
--- a/driver-bitfury.c
+++ b/driver-bitfury.c
@@ -38,12 +38,12 @@ static int bitfury_open(struct cgpu_info *bitfury)
 	 * harmless on linux. */
 	buf[0] = 0x80250000;
 	buf[1] = 0x00000800;
-	err = usb_transfer(bitfury, 0, 9, 1, 0, C_BF1_RESET);
+	err = usb_transfer(bitfury, 0, 9, 1, 0, C_ATMEL_RESET);
 	if (!err)
-		err = usb_transfer(bitfury, 0x21, 0x22, 0, 0, C_BF1_OPEN);
+		err = usb_transfer(bitfury, 0x21, 0x22, 0, 0, C_ATMEL_OPEN);
 	if (!err) {
 		err = usb_transfer_data(bitfury, 0x21, 0x20, 0x0000, 0, buf,
-					BF1MSGSIZE, C_BF1_INIT);
+					BF1MSGSIZE, C_ATMEL_INIT);
 	}
 
 	if (err < 0) {
@@ -146,8 +146,6 @@ static bool bitfury_detect_one(struct libusb_device *dev, struct usb_find_device
 	 * hashrate to adapt quickly on starting. */
 	info->total_nonces = 1;
 
-	usb_buffer_enable(bitfury);
-
 	if (!bitfury_open(bitfury))
 		goto out_close;
 
diff --git a/driver-drillbit.c b/driver-drillbit.c
index 6c4b8ed..8a18e6d 100644
--- a/driver-drillbit.c
+++ b/driver-drillbit.c
@@ -335,8 +335,6 @@ static bool drillbit_detect_one(struct libusb_device *dev, struct usb_find_devic
 		quit(1, "Failed to calloc info in drillbit_detect_one");
 	drillbit->device_data = info;
 
-	usb_buffer_enable(drillbit);
-
 	drillbit_open(drillbit);
 
 	/* Send getinfo request */
diff --git a/driver-hashfast.c b/driver-hashfast.c
new file mode 100644
index 0000000..7549a83
--- /dev/null
+++ b/driver-hashfast.c
@@ -0,0 +1,937 @@
+/*
+ * Copyright 2013 Con Kolivas <kernel@kolivas.org>
+ * Copyright 2013 Hashfast Inc.
+ *
+ * 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 <stdbool.h>
+
+#include "miner.h"
+#include "usbutils.h"
+
+#include "driver-hashfast.h"
+
+////////////////////////////////////////////////////////////////////////////////
+// Support for the CRC's used in header (CRC-8) and packet body (CRC-32)
+////////////////////////////////////////////////////////////////////////////////
+
+#define GP8  0x107   /* x^8 + x^2 + x + 1 */
+#define DI8  0x07
+
+static unsigned char crc8_table[256];	/* CRC-8 table */
+
+static void hfa_init_crc8(void)
+{
+	int i,j;
+	unsigned char crc;
+
+	for (i = 0; i < 256; i++) {
+		crc = i;
+		for (j = 0; j < 8; j++)
+			crc = (crc << 1) ^ ((crc & 0x80) ? DI8 : 0);
+		crc8_table[i] = crc & 0xFF;
+	}
+}
+
+static unsigned char hfa_crc8(unsigned char *h)
+{
+	int i;
+	unsigned char crc;
+
+	h++;	// Preamble not included
+	for (i = 1, crc = 0xff; i < 7; i++)
+		crc = crc8_table[crc ^ *h++];
+
+	return crc;
+}
+
+struct hfa_cmd {
+	uint8_t cmd;
+	char *cmd_name;
+	enum usb_cmds usb_cmd;
+};
+
+/* Entries in this array need to align with the actual op values specified
+ * in hf_protocol.h */
+#define C_NULL C_MAX
+static const struct hfa_cmd hfa_cmds[] = {
+	{OP_NULL, "OP_NULL", C_NULL},				// 0
+	{OP_ROOT, "OP_ROOT", C_NULL},
+	{OP_RESET, "OP_RESET", C_HF_RESET},
+	{OP_PLL_CONFIG, "OP_PLL_CONFIG", C_HF_PLL_CONFIG},
+	{OP_ADDRESS, "OP_ADDRESS", C_HF_ADDRESS},
+	{OP_READDRESS, "OP_READDRESS", C_NULL},
+	{OP_HIGHEST, "OP_HIGHEST", C_NULL},
+	{OP_BAUD, "OP_BAUD", C_HF_BAUD},
+	{OP_UNROOT, "OP_UNROOT", C_NULL},			// 8
+	{OP_HASH, "OP_HASH", C_HF_HASH},
+	{OP_NONCE, "OP_NONCE", C_HF_NONCE},
+	{OP_ABORT, "OP_ABORT", C_HF_ABORT},
+	{OP_STATUS, "OP_STATUS", C_HF_STATUS},
+	{OP_GPIO, "OP_GPIO", C_NULL},
+	{OP_CONFIG, "OP_CONFIG", C_HF_CONFIG},
+	{OP_STATISTICS, "OP_STATISTICS", C_HF_STATISTICS},
+	{OP_GROUP, "OP_GROUP", C_NULL},				// 16
+	{OP_CLOCKGATE, "OP_CLOCKGATE", C_HF_CLOCKGATE},
+
+	{OP_USB_INIT, "OP_USB_INIT", C_HF_USB_INIT},		// 18
+	{OP_GET_TRACE, "OP_GET_TRACE", C_NULL},
+	{OP_LOOPBACK_USB, "OP_LOOPBACK_USB", C_NULL},
+	{OP_LOOPBACK_UART, "OP_LOOPBACK_UART", C_NULL},
+	{OP_DFU, "OP_DFU", C_NULL},
+	{OP_USB_SHUTDOWN, "OP_USB_SHUTDOWN", C_NULL},
+	{OP_DIE_STATUS, "OP_DIE_STATUS", C_HF_DIE_STATUS},	// 24
+	{OP_GWQ_STATUS, "OP_GWQ_STATUS", C_HF_GWQ_STATUS},
+	{OP_WORK_RESTART, "OP_WORK_RESTART", C_HF_WORK_RESTART},
+	{OP_USB_STATS1, "OP_USB_STATS1", C_NULL},
+	{OP_USB_GWQSTATS, "OP_USB_GWQSTATS", C_HF_GWQSTATS}
+};
+
+#define HF_USB_CMD_OFFSET (128 - 18)
+#define HF_USB_CMD(X) (X - HF_USB_CMD_OFFSET)
+
+/* Send an arbitrary frame, consisting of an 8 byte header and an optional
+ * packet body. */
+
+static bool hfa_send_frame(struct cgpu_info *hashfast, uint8_t opcode, uint16_t hdata,
+			   uint8_t *data, int len)
+{
+	int tx_length, ret, amount, id = hashfast->device_id;
+	uint8_t packet[256];
+	struct hf_header *p = (struct hf_header *)packet;
+
+	p->preamble = HF_PREAMBLE;
+	p->operation_code = hfa_cmds[opcode].cmd;
+	p->chip_address = HF_GWQ_ADDRESS;
+	p->core_address = 0;
+	p->hdata = htole16(hdata);
+	p->data_length = len / 4;
+	p->crc8 = hfa_crc8(packet);
+
+	if (len)
+		memcpy(&packet[sizeof(struct hf_header)], data, len);
+	tx_length = sizeof(struct hf_header) + len;
+
+	ret = usb_write(hashfast, (char *)packet, tx_length, &amount,
+			hfa_cmds[opcode].usb_cmd);
+	if (unlikely(ret < 0 || amount != tx_length)) {
+		applog(LOG_ERR, "HFA %d: hfa_send_frame: USB Send error, ret %d amount %d vs. tx_length %d",
+		       id, ret, amount, tx_length);
+		return false;
+	}
+	return true;
+}
+
+static bool hfa_send_header(struct cgpu_info *hashfast, struct hf_header *h, int cmd)
+{
+	int amount, ret, len;
+
+	len = sizeof(*h);
+	ret = usb_write(hashfast, (char *)h, len, &amount, hfa_cmds[cmd].usb_cmd);
+	if (ret < 0 || amount != len) {
+		applog(LOG_WARNING, "HFA%d: send_header: %s USB Send error, ret %d amount %d vs. length %d",
+		       hashfast->device_id, hfa_cmds[cmd].cmd_name, ret, amount, len);
+		return false;
+	}
+	return true;
+}
+
+static bool hfa_get_header(struct cgpu_info *hashfast, struct hf_header *h, uint8_t *computed_crc)
+{
+	int amount, ret, orig_len, len, ofs = 0, reads = 0;
+	char buf[512];
+	char *header;
+
+	/* Read for up to 200ms till we find the first occurrence of HF_PREAMBLE
+	 * though it should be the first byte unless we get woefully out of
+	 * sync. */
+	orig_len = len = sizeof(*h);
+	do {
+
+		if (++reads > 20)
+			return false;
+
+		ret = usb_read_timeout(hashfast, buf + ofs, len, &amount, 10, C_HF_GETHEADER);
+		if (unlikely(ret && ret != LIBUSB_ERROR_TIMEOUT))
+			return false;
+		ofs += amount;
+		header = memchr(buf, HF_PREAMBLE, ofs);
+		if (header)
+			len -= ofs - (header - buf);
+	} while (len);
+
+	memcpy(h, header, orig_len);
+	*computed_crc = hfa_crc8((uint8_t *)h);
+
+	return true;
+}
+
+static bool hfa_get_data(struct cgpu_info *hashfast, char *buf, int len4)
+{
+	int amount, ret, len = len4 * 4;
+
+	ret = usb_read(hashfast, buf, len, &amount, C_HF_GETDATA);
+	if (ret)
+		return false;
+	if (amount != len) {
+		applog(LOG_WARNING, "HFA %d: get_data: Strange amount returned %d vs. expected %d",
+		       hashfast->device_id, amount, len);
+		return false;
+	}
+	return true;
+}
+
+static bool hfa_reset(struct cgpu_info *hashfast, struct hashfast_info *info)
+{
+	struct hf_usb_init_header usb_init, *hu = &usb_init;
+	struct hf_usb_init_base *db;
+	char buf[1024];
+	struct hf_header *h = (struct hf_header *)buf;
+	uint8_t hcrc;
+	bool ret;
+	int i;
+
+	info->hash_clock_rate = 550;                        // Hash clock rate in Mhz
+	// Assemble the USB_INIT request
+	memset(hu, 0, sizeof(*hu));
+	hu->preamble = HF_PREAMBLE;
+	hu->operation_code = OP_USB_INIT;
+	hu->protocol = PROTOCOL_GLOBAL_WORK_QUEUE;          // Protocol to use
+	hu->hash_clock = info->hash_clock_rate;             // Hash clock rate in Mhz
+	hu->crc8 = hfa_crc8((uint8_t *)hu);
+	applog(LOG_INFO, "HFA%d: Sending OP_USB_INIT with GWQ protocol specified",
+	       hashfast->device_id);
+
+	if (!hfa_send_header(hashfast, (struct hf_header *)hu, HF_USB_CMD(OP_USB_INIT)))
+		return false;
+
+	// Check for the correct response.
+	// We extend the normal timeout - a complete device initialization, including
+	// bringing power supplies up from standby, etc., can take over a second.
+	for (i = 0; i < 30; i++) {
+		ret = hfa_get_header(hashfast, h, &hcrc);
+		if (ret)
+			break;
+	}
+	if (!ret) {
+		applog(LOG_WARNING, "HFA %d: OP_USB_INIT failed!", hashfast->device_id);
+		return false;
+	}
+	if (h->crc8 != hcrc) {
+		applog(LOG_WARNING, "HFA %d: OP_USB_INIT failed! CRC mismatch", hashfast->device_id);
+		return false;
+	}
+	if (h->operation_code != OP_USB_INIT) {
+		applog(LOG_WARNING, "HFA %d: OP_USB_INIT: Tossing packet, valid but unexpected type", hashfast->device_id);
+		hfa_get_data(hashfast, buf, h->data_length);
+		return false;
+	}
+
+	applog(LOG_DEBUG, "HFA %d: Good reply to OP_USB_INIT", hashfast->device_id);
+	applog(LOG_DEBUG, "HFA %d: OP_USB_INIT: %d die in chain, %d cores, device_type %d, refclk %d Mhz",
+	       hashfast->device_id, h->chip_address, h->core_address, h->hdata & 0xff, (h->hdata >> 8) & 0xff);
+
+	// Save device configuration
+	info->asic_count = h->chip_address;
+	info->core_count = h->core_address;
+	info->device_type = (uint8_t)h->hdata;
+	info->ref_frequency = (uint8_t)(h->hdata>>8);
+	info->hash_sequence_head = 0;
+	info->hash_sequence_tail = 0;
+	info->device_sequence_tail = 0;
+
+	// Size in bytes of the core bitmap in bytes
+	info->core_bitmap_size = (((info->asic_count * info->core_count) + 31) / 32) * 4;
+
+	// Get the usb_init_base structure
+	if (!hfa_get_data(hashfast, (char *)&info->usb_init_base, U32SIZE(info->usb_init_base))) {
+		applog(LOG_WARNING, "HFA %d: OP_USB_INIT failed! Failure to get usb_init_base data",
+		       hashfast->device_id);
+		return false;
+	}
+	db = &info->usb_init_base;
+	applog(LOG_INFO, "HFA %d:      firmware_rev:    %d.%d", hashfast->device_id,
+	       (db->firmware_rev >> 8) & 0xff, db->firmware_rev & 0xff);
+	applog(LOG_INFO, "HFA %d:      hardware_rev:    %d.%d", hashfast->device_id,
+	       (db->hardware_rev >> 8) & 0xff, db->hardware_rev & 0xff);
+	applog(LOG_INFO, "HFA %d:      serial number:   %d", hashfast->device_id,
+	       db->serial_number);
+	applog(LOG_INFO, "HFA %d:      hash clockrate:  %d Mhz", hashfast->device_id,
+	       db->hash_clockrate);
+	applog(LOG_INFO, "HFA %d:      inflight_target: %d", hashfast->device_id,
+	       db->inflight_target);
+	applog(LOG_INFO, "HFA %d:      sequence_modulus: %d", hashfast->device_id,
+	       db->sequence_modulus);
+	info->num_sequence = db->sequence_modulus;
+
+	// Now a copy of the config data used
+	if (!hfa_get_data(hashfast, (char *)&info->config_data, U32SIZE(info->config_data))) {
+		applog(LOG_WARNING, "HFA %d: OP_USB_INIT failed! Failure to get config_data",
+		       hashfast->device_id);
+		return false;
+	}
+
+	// Now the core bitmap
+	info->core_bitmap = malloc(info->core_bitmap_size);
+	if (!info->core_bitmap)
+		quit(1, "Failed to malloc info core bitmap in hfa_reset");
+	if (!hfa_get_data(hashfast, (char *)info->core_bitmap, info->core_bitmap_size / 4)) {
+		applog(LOG_WARNING, "HFA %d: OP_USB_INIT failed! Failure to get core_bitmap", hashfast->device_id);
+		return false;
+	}
+
+	return true;
+}
+
+static void hfa_send_shutdown(struct cgpu_info *hashfast)
+{
+	hfa_send_frame(hashfast, HF_USB_CMD(OP_USB_SHUTDOWN), 0, NULL, 0);
+}
+
+static void hfa_clear_readbuf(struct cgpu_info *hashfast)
+{
+	int amount, ret;
+	char buf[512];
+
+	do {
+		ret = usb_read(hashfast, buf, 512, &amount, C_HF_CLEAR_READ);
+	} while (!ret || amount);
+}
+
+static bool hfa_detect_common(struct cgpu_info *hashfast)
+{
+	struct hashfast_info *info;
+	bool ret;
+
+	info = calloc(sizeof(struct hashfast_info), 1);
+	if (!info)
+		quit(1, "Failed to calloc hashfast_info in hfa_detect_common");
+	hashfast->device_data = info;
+	/* hashfast_reset should fill in details for info */
+	ret = hfa_reset(hashfast, info);
+	if (!ret) {
+		hfa_send_shutdown(hashfast);
+		hfa_clear_readbuf(hashfast);
+		free(info);
+		hashfast->device_data = NULL;
+		return false;
+	}
+
+	// The per-die status array
+	info->die_status = calloc(info->asic_count, sizeof(struct hf_g1_die_data));
+	if (unlikely(!(info->die_status)))
+		quit(1, "Failed to calloc die_status");
+
+	// The per-die statistics array
+	info->die_statistics = calloc(info->asic_count, sizeof(struct hf_long_statistics));
+	if (unlikely(!(info->die_statistics)))
+		quit(1, "Failed to calloc die_statistics");
+
+	info->works = calloc(sizeof(struct work *), info->num_sequence);
+	if (!info->works)
+		quit(1, "Failed to calloc info works in hfa_detect_common");
+
+	return true;
+}
+
+static bool hfa_initialise(struct cgpu_info *hashfast)
+{
+	int err;
+
+	if (hashfast->usbinfo.nodev)
+		return false;
+
+	hfa_clear_readbuf(hashfast);
+
+	err = usb_transfer(hashfast, 0, 9, 1, 0, C_ATMEL_RESET);
+	if (!err)
+		err = usb_transfer(hashfast, 0x21, 0x22, 0, 0, C_ATMEL_OPEN);
+	if (!err) {
+		uint32_t buf[2];
+
+		/* Magic sequence to reset device only really needed for windows
+		 * but harmless on linux. */
+		buf[0] = 0x80250000;
+		buf[1] = 0x00000800;
+		err = usb_transfer_data(hashfast, 0x21, 0x20, 0x0000, 0, buf,
+					7, C_ATMEL_INIT);
+	}
+	if (err < 0) {
+		applog(LOG_INFO, "HFA %d: Failed to open with error %s",
+		       hashfast->device_id, libusb_error_name(err));
+	}
+	/* Must have transmitted init sequence sized buffer */
+	return (err == 7);
+}
+
+static bool hfa_detect_one_usb(libusb_device *dev, struct usb_find_devices *found)
+{
+	struct cgpu_info *hashfast;
+
+	hashfast = usb_alloc_cgpu(&hashfast_drv, HASHFAST_MINER_THREADS);
+	if (!hashfast)
+		quit(1, "Failed to usb_alloc_cgpu hashfast");
+
+	if (!usb_init(hashfast, dev, found)) {
+		hashfast = usb_free_cgpu(hashfast);
+		return false;
+	}
+
+	hashfast->usbdev->usb_type = USB_TYPE_STD;
+
+	if (!hfa_initialise(hashfast)) {
+		hashfast = usb_free_cgpu(hashfast);
+		return false;
+	}
+
+	add_cgpu(hashfast);
+
+	return hfa_detect_common(hashfast);
+}
+
+static void hfa_detect(bool hotplug)
+{
+	/* Set up the CRC tables only once. */
+	if (!hotplug)
+		hfa_init_crc8();
+	usb_detect(&hashfast_drv, hfa_detect_one_usb);
+}
+
+static bool hfa_get_packet(struct cgpu_info *hashfast, struct hf_header *h)
+{
+	uint8_t hcrc;
+	bool ret;
+
+	ret = hfa_get_header(hashfast, h, &hcrc);
+	if (unlikely(!ret))
+		goto out;
+	if (unlikely(h->crc8 != hcrc)) {
+		applog(LOG_WARNING, "HFA %d: Bad CRC %d vs %d, attempting to process anyway",
+		       hashfast->device_id, h->crc8, hcrc);
+	}
+	if (h->data_length > 0)
+		ret = hfa_get_data(hashfast, (char *)(h + 1), h->data_length);
+	if (unlikely(!ret)) {
+		applog(LOG_WARNING, "HFA %d: Failed to get data associated with header",
+		       hashfast->device_id);
+	}
+
+out:
+	return ret;
+}
+
+static void hfa_parse_gwq_status(struct cgpu_info *hashfast, struct hashfast_info *info,
+				 struct hf_header *h)
+{
+	struct hf_gwq_data *g = (struct hf_gwq_data *)(h + 1);
+	struct work *work;
+
+	applog(LOG_DEBUG, "HFA %d: OP_GWQ_STATUS, device_head %4d tail %4d my tail %4d shed %3d inflight %4d",
+		hashfast->device_id, g->sequence_head, g->sequence_tail, info->hash_sequence_tail,
+		g->shed_count, HF_SEQUENCE_DISTANCE(info->hash_sequence_head,g->sequence_tail));
+
+	mutex_lock(&info->lock);
+	info->hash_count += g->hash_count;
+	info->device_sequence_head = g->sequence_head;
+	info->device_sequence_tail = g->sequence_tail;
+	info->shed_count = g->shed_count;
+	/* Free any work that is no longer required */
+	while (info->device_sequence_tail != info->hash_sequence_tail) {
+		if (++info->hash_sequence_tail >= info->num_sequence)
+			info->hash_sequence_tail = 0;
+		if (unlikely(!(work = info->works[info->hash_sequence_tail]))) {
+			applog(LOG_ERR, "HFA %d: Bad work sequence tail",
+			       hashfast->device_id);
+			hashfast->shutdown = true;
+			break;
+		}
+		applog(LOG_DEBUG, "HFA %d: Completing work on hash_sequence_tail %d",
+		       hashfast->device_id, info->hash_sequence_tail);
+		free_work(work);
+		info->works[info->hash_sequence_tail] = NULL;
+	}
+	mutex_unlock(&info->lock);
+}
+
+static void hfa_update_die_status(struct cgpu_info *hashfast, struct hashfast_info *info,
+				  struct hf_header *h)
+{
+	struct hf_g1_die_data *d = (struct hf_g1_die_data *)(h + 1), *ds;
+	int num_included = (h->data_length * 4) / sizeof(struct hf_g1_die_data);
+	int i, j;
+
+	float die_temperature;
+	float core_voltage[6];
+
+	if (info->device_type == HFD_G1) {
+		// Copy in the data. They're numbered sequentially from the starting point
+		ds = info->die_status + h->chip_address;
+		for (i = 0; i < num_included; i++)
+			memcpy(ds++, d++, sizeof(struct hf_g1_die_data));
+
+		for (i = 0, d = &info->die_status[h->chip_address]; i < num_included; i++, d++) {
+			die_temperature = GN_DIE_TEMPERATURE(d->die.die_temperature);
+			for (j = 0; j < 6; j++)
+				core_voltage[j] = GN_CORE_VOLTAGE(d->die.core_voltage[j]);
+
+			applog(LOG_DEBUG, "HFA %d: die %2d: OP_DIE_STATUS Die temp %.2fC vdd's %.2f %.2f %.2f %.2f %.2f %.2f",
+			       hashfast->device_id, h->chip_address + i, die_temperature,
+			       core_voltage[0], core_voltage[1], core_voltage[2],
+			       core_voltage[3], core_voltage[4], core_voltage[5]);
+			// XXX Convert board phase currents, voltage, temperature
+		}
+	}
+}
+
+static void search_for_extra_nonce(struct thr_info *thr, struct work *work,
+				   struct hf_candidate_nonce *n)
+{
+	uint32_t nonce = n->nonce;
+	int i;
+
+	/* No function to test with ntime offsets yet */
+	if (n->ntime & HF_NTIME_MASK)
+		return;
+	for (i = 0; i < 128; i++, nonce++) {
+		/* We could break out of this early if nonce wraps or if we
+		 * find one correct nonce since the chance of more is extremely
+		 * low but this function will be hit so infrequently we may as
+		 * well test the entire range with the least code. */
+		if (test_nonce(work, nonce))
+			submit_tested_work(thr, work);
+	}
+}
+
+static void hfa_parse_nonce(struct thr_info *thr, struct cgpu_info *hashfast,
+			    struct hashfast_info *info, struct hf_header *h)
+{
+	struct hf_candidate_nonce *n = (struct hf_candidate_nonce *)(h + 1);
+	int i, num_nonces = h->data_length / U32SIZE(sizeof(struct hf_candidate_nonce));
+
+	applog(LOG_DEBUG, "HFA %d: OP_NONCE: %2d:, num_nonces %d hdata 0x%04x",
+	       hashfast->device_id, h->chip_address, num_nonces, h->hdata);
+	for (i = 0; i < num_nonces; i++, n++) {
+		struct work *work;
+
+		applog(LOG_DEBUG, "HFA %d: OP_NONCE: %2d: %2d: ntime %2d sequence %4d nonce 0x%08x",
+		       hashfast->device_id, h->chip_address, i, n->ntime & HF_NTIME_MASK, n->sequence, n->nonce);
+
+		// Find the job from the sequence number
+		mutex_lock(&info->lock);
+		work = info->works[n->sequence];
+		mutex_unlock(&info->lock);
+
+		if (unlikely(!work)) {
+			info->no_matching_work++;
+			applog(LOG_INFO, "HFA %d: No matching work!", hashfast->device_id);
+		} else {
+			applog(LOG_DEBUG, "HFA %d: OP_NONCE: sequence %d: submitting nonce 0x%08x ntime %d",
+			       hashfast->device_id, n->sequence, n->nonce, n->ntime & HF_NTIME_MASK);
+			if ((n->nonce & 0xffff0000) == 0x42420000)		// XXX REMOVE THIS
+				break;						// XXX PHONEY EMULATOR NONCE
+			submit_noffset_nonce(thr, work, n->nonce, n->ntime & HF_NTIME_MASK);	// XXX Return value from submit_nonce is error if set
+			if (unlikely(n->ntime & HF_NONCE_SEARCH)) {
+				/* This tells us there is another share in the
+				 * next 128 nonces */
+				applog(LOG_DEBUG, "HFA %d: OP_NONCE: SEARCH PROXIMITY EVENT FOUND",
+				       hashfast->device_id);
+				search_for_extra_nonce(thr, work, n);
+			}
+		}
+	}
+}
+
+static void hfa_update_die_statistics(struct hashfast_info *info, struct hf_header *h)
+{
+	struct hf_statistics *s = (struct hf_statistics *)(h + 1);
+	struct hf_long_statistics *l;
+
+	// Accumulate the data
+	l = info->die_statistics + h->chip_address;
+
+	l->rx_header_crc += s->rx_header_crc;
+	l->rx_body_crc += s->rx_body_crc;
+	l->rx_header_timeouts += s->rx_header_timeouts;
+	l->rx_body_timeouts += s->rx_body_timeouts;
+	l->core_nonce_fifo_full += s->core_nonce_fifo_full;
+	l->array_nonce_fifo_full += s->array_nonce_fifo_full;
+	l->stats_overrun += s->stats_overrun;
+}
+
+static void hfa_update_stats1(struct cgpu_info *hashfast, struct hashfast_info *info,
+			      struct hf_header *h)
+{
+	struct hf_long_usb_stats1 *s1 = &info->stats1;
+	struct hf_usb_stats1 *sd = (struct hf_usb_stats1 *)(h + 1);
+
+	s1->usb_rx_preambles += sd->usb_rx_preambles;
+	s1->usb_rx_receive_byte_errors += sd->usb_rx_receive_byte_errors;
+	s1->usb_rx_bad_hcrc += sd->usb_rx_bad_hcrc;
+
+	s1->usb_tx_attempts += sd->usb_tx_attempts;
+	s1->usb_tx_packets += sd->usb_tx_packets;
+	s1->usb_tx_timeouts += sd->usb_tx_timeouts;
+	s1->usb_tx_incompletes += sd->usb_tx_incompletes;
+	s1->usb_tx_endpointstalled += sd->usb_tx_endpointstalled;
+	s1->usb_tx_disconnected += sd->usb_tx_disconnected;
+	s1->usb_tx_suspended += sd->usb_tx_suspended;
+#if 0
+	/* We don't care about UART stats so they're not in our struct */
+	s1->uart_tx_queue_dma += sd->uart_tx_queue_dma;
+	s1->uart_tx_interrupts += sd->uart_tx_interrupts;
+
+	s1->uart_rx_preamble_ints += sd->uart_rx_preamble_ints;
+	s1->uart_rx_missed_preamble_ints += sd->uart_rx_missed_preamble_ints;
+	s1->uart_rx_header_done += sd->uart_rx_header_done;
+	s1->uart_rx_data_done += sd->uart_rx_data_done;
+	s1->uart_rx_bad_hcrc += sd->uart_rx_bad_hcrc;
+	s1->uart_rx_bad_dma += sd->uart_rx_bad_dma;
+	s1->uart_rx_short_dma += sd->uart_rx_short_dma;
+	s1->uart_rx_buffers_full += sd->uart_rx_buffers_full;
+#endif
+	if (sd->max_tx_buffers >  s1->max_tx_buffers)
+		s1->max_tx_buffers = sd->max_tx_buffers;
+	if (sd->max_rx_buffers >  s1->max_rx_buffers)
+		s1->max_rx_buffers = sd->max_rx_buffers;
+
+	applog(LOG_DEBUG, "HFA %d: OP_USB_STATS1:", hashfast->device_id);
+	applog(LOG_DEBUG, "      usb_rx_preambles:             %6d", sd->usb_rx_preambles);
+	applog(LOG_DEBUG, "      usb_rx_receive_byte_errors:   %6d", sd->usb_rx_receive_byte_errors);
+	applog(LOG_DEBUG, "      usb_rx_bad_hcrc:              %6d", sd->usb_rx_bad_hcrc);
+
+	applog(LOG_DEBUG, "      usb_tx_attempts:              %6d", sd->usb_tx_attempts);
+	applog(LOG_DEBUG, "      usb_tx_packets:               %6d", sd->usb_tx_packets);
+	applog(LOG_DEBUG, "      usb_tx_timeouts:              %6d", sd->usb_tx_timeouts);
+	applog(LOG_DEBUG, "      usb_tx_incompletes:           %6d", sd->usb_tx_incompletes);
+	applog(LOG_DEBUG, "      usb_tx_endpointstalled:       %6d", sd->usb_tx_endpointstalled);
+	applog(LOG_DEBUG, "      usb_tx_disconnected:          %6d", sd->usb_tx_disconnected);
+	applog(LOG_DEBUG, "      usb_tx_suspended:             %6d", sd->usb_tx_suspended);
+#if 0
+	applog(LOG_DEBUG, "      uart_tx_queue_dma:            %6d", sd->uart_tx_queue_dma);
+	applog(LOG_DEBUG, "      uart_tx_interrupts:           %6d", sd->uart_tx_interrupts);
+
+	applog(LOG_DEBUG, "      uart_rx_preamble_ints:        %6d", sd->uart_rx_preamble_ints);
+	applog(LOG_DEBUG, "      uart_rx_missed_preamble_ints: %6d", sd->uart_rx_missed_preamble_ints);
+	applog(LOG_DEBUG, "      uart_rx_header_done:          %6d", sd->uart_rx_header_done);
+	applog(LOG_DEBUG, "      uart_rx_data_done:            %6d", sd->uart_rx_data_done);
+	applog(LOG_DEBUG, "      uart_rx_bad_hcrc:             %6d", sd->uart_rx_bad_hcrc);
+	applog(LOG_DEBUG, "      uart_rx_bad_dma:              %6d", sd->uart_rx_bad_dma);
+	applog(LOG_DEBUG, "      uart_rx_short_dma:            %6d", sd->uart_rx_short_dma);
+	applog(LOG_DEBUG, "      uart_rx_buffers_full:         %6d", sd->uart_rx_buffers_full);
+#endif
+	applog(LOG_DEBUG, "      max_tx_buffers:               %6d", sd->max_tx_buffers);
+	applog(LOG_DEBUG, "      max_rx_buffers:               %6d", sd->max_rx_buffers);
+
+    }
+
+static void *hfa_read(void *arg)
+{
+	struct thr_info *thr = (struct thr_info *)arg;
+	struct cgpu_info *hashfast = thr->cgpu;
+	struct hashfast_info *info = hashfast->device_data;
+	char threadname[24];
+
+	snprintf(threadname, 24, "hfa_read/%d", hashfast->device_id);
+	RenameThread(threadname);
+
+	while (likely(!hashfast->shutdown)) {
+		char buf[512];
+		struct hf_header *h = (struct hf_header *)buf;
+		bool ret = hfa_get_packet(hashfast, h);
+
+		if (unlikely(!ret))
+			continue;
+
+		switch (h->operation_code) {
+			case OP_GWQ_STATUS:
+				hfa_parse_gwq_status(hashfast, info, h);
+				break;
+			case OP_DIE_STATUS:
+				hfa_update_die_status(hashfast, info, h);
+				break;
+			case OP_NONCE:
+				hfa_parse_nonce(thr, hashfast, info, h);
+				break;
+			case OP_STATISTICS:
+				hfa_update_die_statistics(info, h);
+				break;
+			case OP_USB_STATS1:
+				hfa_update_stats1(hashfast, info, h);
+				break;
+			default:
+				applog(LOG_WARNING, "HFA %d: Unhandled operation code %d",
+				       hashfast->device_id, h->operation_code);
+				break;
+		}
+	}
+
+	return NULL;
+}
+
+static bool hfa_prepare(struct thr_info *thr)
+{
+	struct cgpu_info *hashfast = thr->cgpu;
+	struct hashfast_info *info = hashfast->device_data;
+	struct timeval now;
+
+	mutex_init(&info->lock);
+	if (pthread_create(&info->read_thr, NULL, hfa_read, (void *)thr))
+		quit(1, "Failed to pthread_create read thr in hfa_prepare");
+
+	cgtime(&now);
+	get_datestamp(hashfast->init, sizeof(hashfast->init), &now);
+
+	return true;
+}
+
+/* Figure out how many jobs to send. */
+static int hfa_jobs(struct hashfast_info *info)
+{
+	int ret;
+
+	mutex_lock(&info->lock);
+	ret = info->usb_init_base.inflight_target - HF_SEQUENCE_DISTANCE(info->hash_sequence_head, info->device_sequence_tail);
+	/* Place an upper limit on how many jobs to queue to prevent sending
+	 * more  work than the device can use after a period of outage. */
+	if (ret > info->usb_init_base.inflight_target)
+		ret = info->usb_init_base.inflight_target;
+	mutex_unlock(&info->lock);
+
+	return ret;
+}
+
+static int64_t hfa_scanwork(struct thr_info *thr)
+{
+	struct cgpu_info *hashfast = thr->cgpu;
+	struct hashfast_info *info = hashfast->device_data;
+	int64_t hashes;
+	int jobs, ret;
+
+	if (unlikely(hashfast->usbinfo.nodev)) {
+		applog(LOG_WARNING, "HFA %d: device disappeared, disabling",
+		       hashfast->device_id);
+		return -1;
+	}
+
+	if (unlikely(thr->work_restart)) {
+restart:
+		ret = hfa_send_frame(hashfast, HF_USB_CMD(OP_WORK_RESTART), 0, (uint8_t *)NULL, 0);
+		if (unlikely(!ret)) {
+			ret = hfa_reset(hashfast, info);
+			if (unlikely(!ret)) {
+				applog(LOG_ERR, "HFA %d: Failed to reset after write failure, disabling",
+				hashfast->device_id);
+				return -1;
+			}
+		}
+	}
+
+	jobs = hfa_jobs(info);
+
+	if (!jobs) {
+		ret = restart_wait(thr, 100);
+		if (unlikely(!ret))
+			goto restart;
+		jobs = hfa_jobs(info);
+	}
+
+	while (jobs-- > 0) {
+		struct hf_hash_usb op_hash_data;
+		struct work *work;
+		uint64_t intdiff;
+		int i, sequence;
+		uint32_t *p;
+
+		/* This is a blocking function if there's no work */
+		work = get_work(thr, thr->id);
+
+		/* Assemble the data frame and send the OP_HASH packet */
+		memcpy(op_hash_data.midstate, work->midstate, sizeof(op_hash_data.midstate));
+		memcpy(op_hash_data.merkle_residual, work->data + 64, 4);
+		p = (uint32_t *)(work->data + 64 + 4);
+		op_hash_data.timestamp = *p++;
+		op_hash_data.bits = *p++;
+		op_hash_data.nonce_loops = 0;
+
+		/* Set the number of leading zeroes to look for based on diff.
+		 * Diff 1 = 32, Diff 2 = 33, Diff 4 = 34 etc. */
+		intdiff = (uint64_t)work->device_diff;
+		for (i = 31; intdiff; i++, intdiff >>= 1);
+		op_hash_data.search_difficulty = i;
+		if ((sequence = info->hash_sequence_head + 1) >= info->num_sequence)
+			sequence = 0;
+		ret = hfa_send_frame(hashfast, OP_HASH, sequence, (uint8_t *)&op_hash_data, sizeof(op_hash_data));
+		if (unlikely(!ret)) {
+			ret = hfa_reset(hashfast, info);
+			if (unlikely(!ret)) {
+				applog(LOG_ERR, "HFA %d: Failed to reset after write failure, disabling",
+				       hashfast->device_id);
+				return -1;
+			}
+		}
+
+		mutex_lock(&info->lock);
+		info->hash_sequence_head = sequence;
+		info->works[info->hash_sequence_head] = work;
+		mutex_unlock(&info->lock);
+
+		applog(LOG_DEBUG, "HFA %d: OP_HASH sequence %d search_difficulty %d work_difficulty %g",
+		       hashfast->device_id, info->hash_sequence_head, op_hash_data.search_difficulty, work->work_difficulty);
+	}
+
+	mutex_lock(&info->lock);
+	hashes = info->hash_count;
+	info->hash_count = 0;
+	mutex_unlock(&info->lock);
+
+	return hashes;
+}
+
+static struct api_data *hfa_api_stats(struct cgpu_info *cgpu)
+{
+	struct hashfast_info *info = cgpu->device_data;
+	struct hf_long_usb_stats1 *s1;
+	struct api_data *root = NULL;
+	struct hf_usb_init_base *db;
+	int varint, i;
+	char buf[64];
+
+	root = api_add_int(root, "asic count", &info->asic_count, false);
+	root = api_add_int(root, "core count", &info->core_count, false);
+
+	db = &info->usb_init_base;
+	sprintf(buf, "%d.%d", (db->firmware_rev >> 8) & 0xff, db->firmware_rev & 0xff);
+	root = api_add_string(root, "firmware rev", buf, true);
+	sprintf(buf, "%d.%d", (db->hardware_rev >> 8) & 0xff, db->hardware_rev & 0xff);
+	root = api_add_string(root, "hardware rev", buf, true);
+	varint = db->serial_number;
+	root = api_add_int(root, "serial number", &varint, true);
+	varint = db->hash_clockrate;
+	root = api_add_int(root, "hash clockrate", &varint, true);
+	varint = db->inflight_target;
+	root = api_add_int(root, "inflight target", &varint, true);
+	varint = db->sequence_modulus;
+	root = api_add_int(root, "sequence modules", &varint, true);
+
+	s1 = &info->stats1;
+	root = api_add_uint64(root, "rx preambles", &s1->usb_rx_preambles, false);
+	root = api_add_uint64(root, "rx rcv byte err", &s1->usb_rx_receive_byte_errors, false);
+	root = api_add_uint64(root, "rx bad hcrc", &s1->usb_rx_bad_hcrc, false);
+	root = api_add_uint64(root, "tx attempts", &s1->usb_tx_attempts, false);
+	root = api_add_uint64(root, "tx packets", &s1->usb_tx_packets, false);
+	root = api_add_uint64(root, "tx incompletes", &s1->usb_tx_incompletes, false);
+	root = api_add_uint64(root, "tx ep stalled", &s1->usb_tx_endpointstalled, false);
+	root = api_add_uint64(root, "tx disconnect", &s1->usb_tx_disconnected, false);
+	root = api_add_uint64(root, "tx suspend", &s1->usb_tx_suspended, false);
+	varint = s1->max_tx_buffers;
+	root = api_add_int(root, "max tx buf", &varint, true);
+	varint = s1->max_rx_buffers;
+	root = api_add_int(root, "max rx buf", &varint, true);
+
+	for (i = 0; i < info->asic_count; i++) {
+		struct hf_long_statistics *l = &info->die_statistics[i];
+		struct hf_g1_die_data *d = &info->die_status[i];
+		double die_temp, core_voltage;
+		int j;
+
+		root = api_add_int(root, "Core", &i, true);
+		die_temp = GN_DIE_TEMPERATURE(d->die.die_temperature);
+		root = api_add_double(root, "die temperature", &die_temp, true);
+		for (j = 0; j < 6; j++) {
+			core_voltage = GN_CORE_VOLTAGE(d->die.core_voltage[j]);
+			sprintf(buf, "%d: %.2f", j, core_voltage);
+			root = api_add_string(root, "core voltage", buf, true);
+		}
+		root = api_add_uint64(root, "rx header crc", &l->rx_header_crc, false);
+		root = api_add_uint64(root, "rx body crc", &l->rx_body_crc, false);
+		root = api_add_uint64(root, "rx header to", &l->rx_header_timeouts, false);
+		root = api_add_uint64(root, "rx body to", &l->rx_body_timeouts, false);
+		root = api_add_uint64(root, "cn fifo full", &l->core_nonce_fifo_full, false);
+		root = api_add_uint64(root, "an fifo full", &l->array_nonce_fifo_full, false);
+		root = api_add_uint64(root, "stats overrun", &l->stats_overrun, false);
+	}
+
+	return root;
+}
+
+static void hfa_statline_before(char *buf, size_t bufsiz, struct cgpu_info *hashfast)
+{
+	struct hashfast_info *info = hashfast->device_data;
+	double max_temp, max_volt;
+	struct hf_g1_die_data *d;
+	int i;
+
+	max_temp = max_volt = 0.0;
+
+	for (i = 0; i < info->asic_count; i++) {
+		double temp;
+		int j;
+
+		d = &info->die_status[i];
+		temp = GN_DIE_TEMPERATURE(d->die.die_temperature);
+		if (temp > max_temp)
+			max_temp = temp;
+		for (j = 0; j < 6; j++) {
+			double volt = GN_CORE_VOLTAGE(d->die.core_voltage[j]);
+
+			if (volt > max_volt)
+				max_volt = volt;
+		}
+	}
+
+	tailsprintf(buf, bufsiz, " max%3.0fC %3.2fV | ", max_temp, max_volt);
+}
+
+static void hfa_init(struct cgpu_info __maybe_unused *hashfast)
+{
+}
+
+static void hfa_free_all_work(struct hashfast_info *info)
+{
+	while (info->device_sequence_tail != info->hash_sequence_head) {
+		struct work *work;
+
+		if (++info->hash_sequence_tail >= info->num_sequence)
+			info->hash_sequence_tail = 0;
+		if (unlikely(!(work = info->works[info->hash_sequence_tail])))
+			break;
+		free_work(work);
+		info->works[info->hash_sequence_tail] = NULL;
+	}
+}
+
+static void hfa_shutdown(struct thr_info *thr)
+{
+	struct cgpu_info *hashfast = thr->cgpu;
+	struct hashfast_info *info = hashfast->device_data;
+
+	hfa_send_shutdown(hashfast);
+	pthread_join(info->read_thr, NULL);
+	hfa_free_all_work(info);
+	hfa_clear_readbuf(hashfast);
+	free(info->works);
+	free(info->die_statistics);
+	free(info->die_status);
+	free(info);
+}
+
+struct device_drv hashfast_drv = {
+	.drv_id = DRIVER_hashfast,
+	.dname = "Hashfast",
+	.name = "HFA",
+	.max_diff = 256.0, // Limit max diff to get some nonces back regardless
+	.drv_detect = hfa_detect,
+	.thread_prepare = hfa_prepare,
+	.hash_work = &hash_driver_work,
+	.scanwork = hfa_scanwork,
+	.get_api_stats = hfa_api_stats,
+	.get_statline_before = hfa_statline_before,
+	.reinit_device = hfa_init,
+	.thread_shutdown = hfa_shutdown,
+};
diff --git a/driver-hashfast.h b/driver-hashfast.h
new file mode 100644
index 0000000..6c8efb2
--- /dev/null
+++ b/driver-hashfast.h
@@ -0,0 +1,97 @@
+/*
+ * Copyright 2013 Con Kolivas <kernel@kolivas.org>
+ * Copyright 2013 Hashfast
+ *
+ * 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 HASHFAST_H
+#define HASHFAST_H
+
+#ifdef USE_HASHFAST
+#include "miner.h"
+#include "elist.h"
+#include "hf_protocol.h"
+
+#define HASHFAST_MINER_THREADS 1
+
+// Matching fields for hf_statistics, but large #s for local accumulation, per-die
+struct hf_long_statistics {
+	uint64_t rx_header_crc;                     // Header CRCs
+	uint64_t rx_body_crc;                       // Data CRCs
+	uint64_t rx_header_timeouts;                // Header timeouts
+	uint64_t rx_body_timeouts;                  // Data timeouts
+	uint64_t core_nonce_fifo_full;              // Core nonce Q overrun events
+	uint64_t array_nonce_fifo_full;             // System nonce Q overrun events
+	uint64_t stats_overrun;                     // Overrun in statistics reporting
+};
+
+// Matching fields for hf_usb_stats1, but large #s for local accumulation, per device
+struct hf_long_usb_stats1 {
+	// USB incoming
+	uint64_t usb_rx_preambles;
+	uint64_t usb_rx_receive_byte_errors;
+	uint64_t usb_rx_bad_hcrc;
+
+	// USB outgoing
+	uint64_t usb_tx_attempts;
+	uint64_t usb_tx_packets;
+	uint64_t usb_tx_timeouts;
+	uint64_t usb_tx_incompletes;
+	uint64_t usb_tx_endpointstalled;
+	uint64_t usb_tx_disconnected;
+	uint64_t usb_tx_suspended;
+#if 0
+	/* We don't care about UART stats */
+	// UART transmit
+	uint64_t uart_tx_queue_dma;
+	uint64_t uart_tx_interrupts;
+
+	// UART receive
+	uint64_t uart_rx_preamble_ints;
+	uint64_t uart_rx_missed_preamble_ints;
+	uint64_t uart_rx_header_done;
+	uint64_t uart_rx_data_done;
+	uint64_t uart_rx_bad_hcrc;
+	uint64_t uart_rx_bad_dma;
+	uint64_t uart_rx_short_dma;
+	uint64_t uart_rx_buffers_full;
+#endif
+
+	uint8_t  max_tx_buffers;
+	uint8_t  max_rx_buffers;
+};
+
+struct hashfast_info {
+	int asic_count;                             // # of chips in the chain
+	int core_count;                             // # of cores per chip
+	int device_type;                            // What sort of device this is
+	int num_sequence;                           // A power of 2. What the sequence number range is.
+	int ref_frequency;                          // Reference clock rate
+	struct hf_g1_die_data *die_status;          // Array of per-die voltage, current, temperature sensor data
+	struct hf_long_statistics *die_statistics;  // Array of per-die error counters
+	struct hf_long_usb_stats1 stats1;
+	int hash_clock_rate;                        // Hash clock rate to use, in Mhz
+	struct hf_usb_init_base usb_init_base;      // USB Base information from USB_INIT
+	struct hf_config_data config_data;          // Configuration data used from USB_INIT
+	int core_bitmap_size;                       // in bytes
+	uint32_t *core_bitmap;                      // Core OK bitmap test results, run with PLL Bypassed
+
+	pthread_mutex_t lock;
+	struct work **works;
+	uint16_t hash_sequence_head;                // HOST:   The next hash sequence # to be sent
+	uint16_t hash_sequence_tail;                // HOST:   Follows device_sequence_tail around to free work
+	uint16_t device_sequence_head;              // DEVICE: The most recent sequence number the device dispatched
+	uint16_t device_sequence_tail;              // DEVICE: The most recently completed job in the device
+	int64_t hash_count;
+	uint16_t shed_count;                        // Dynamic copy of #cores device has shed for thermal control
+	int no_matching_work;
+
+	pthread_t read_thr;
+};
+
+#endif /* USE_HASHFAST */
+#endif	/* HASHFAST_H */
diff --git a/driver-icarus.c b/driver-icarus.c
index 43a460e..bf53073 100644
--- a/driver-icarus.c
+++ b/driver-icarus.c
@@ -55,10 +55,6 @@
 // The size of a successful nonce read
 #define ICARUS_READ_SIZE 4
 
-#define AMU_PREF_PACKET 256
-#define BLT_PREF_PACKET 512
-#define ICA_PREF_PACKET 256
-
 // Ensure the sizes are correct for the Serial read
 #if (ICARUS_READ_SIZE != 4)
 #error ICARUS_READ_SIZE must be 4
@@ -329,8 +325,6 @@ static void icarus_initialise(struct cgpu_info *icarus, int baud)
 		case IDENT_LLT:
 		case IDENT_CMR1:
 		case IDENT_CMR2:
-			usb_set_pps(icarus, BLT_PREF_PACKET);
-
 			// Reset
 			transfer(icarus, FTDI_TYPE_OUT, FTDI_REQUEST_RESET, FTDI_VALUE_RESET,
 				 interface, C_RESET);
@@ -404,8 +398,6 @@ static void icarus_initialise(struct cgpu_info *icarus, int baud)
 				 interface, C_PURGERX);
 			break;
 		case IDENT_ICA:
-			usb_set_pps(icarus, ICA_PREF_PACKET);
-
 			// Set Data Control
 			transfer(icarus, PL2303_CTRL_OUT, PL2303_REQUEST_CTRL, PL2303_VALUE_CTRL,
 				 interface, C_SETDATA);
@@ -426,8 +418,6 @@ static void icarus_initialise(struct cgpu_info *icarus, int baud)
 				 interface, C_VENDOR);
 			break;
 		case IDENT_AMU:
-			usb_set_pps(icarus, AMU_PREF_PACKET);
-
 			// Enable the UART
 			transfer(icarus, CP210X_TYPE_OUT, CP210X_REQUEST_IFC_ENABLE,
 				 CP210X_VALUE_UART_ENABLE,
@@ -832,8 +822,6 @@ static bool icarus_detect_one(struct libusb_device *dev, struct usb_find_devices
 	if (!usb_init(icarus, dev, found))
 		goto shin;
 
-	usb_buffer_enable(icarus);
-
 	get_options(this_option_offset, icarus, &baud, &work_division, &fpga_count);
 
 	hex2bin((void *)(&workdata), golden_ob, sizeof(workdata));
diff --git a/driver-klondike.c b/driver-klondike.c
index 19965a4..a445bf4 100644
--- a/driver-klondike.c
+++ b/driver-klondike.c
@@ -63,9 +63,6 @@ static const char *msg_reply = "Reply";
 #define KLN_KILLWORK_TEMP	53.5
 #define KLN_COOLED_DOWN		45.5
 
-// If 5 late updates in a row, try to reset the device
-#define KLN_LATE_UPDATE_LIMIT	5
-
 /*
  *  Work older than 5s will already be completed
  *  FYI it must not be possible to complete 256 work
@@ -75,11 +72,28 @@ static const char *msg_reply = "Reply";
 #define OLD_WORK_MS ((int)(5 * 1000))
 
 /*
+ * How many incorrect slave counts to ignore in a row
+ * 2 means it allows random grabage returned twice
+ * Until slaves are implemented, this should never occur
+ * so allowing 2 in a row should ignore random errros
+ */
+#define KLN_ISS_IGNORE 2
+
+/*
  * If the queue status hasn't been updated for this long then do it now
  * 5GH/s = 859ms per full nonce range
  */
 #define LATE_UPDATE_MS ((int)(2.5 * 1000))
 
+// If 5 late updates in a row, try to reset the device
+#define LATE_UPDATE_LIMIT	5
+
+// If the reset fails sleep for 1s
+#define LATE_UPDATE_SLEEP_MS 1000
+
+// However give up after 8s
+#define LATE_UPDATE_NODEV_MS ((int)(8.0 * 1000))
+
 struct device_drv klondike_drv;
 
 typedef struct klondike_header {
@@ -194,12 +208,12 @@ typedef struct jobque {
 	int workqc;
 	struct timeval last_update;
 	bool overheat;
+	bool flushed;
 	int late_update_count;
 	int late_update_sequential;
 } JOBQUE;
 
 struct klondike_info {
-	bool shutdown;
 	pthread_rwlock_t stat_lock;
 	struct thr_info replies_thr;
 	cglock_t klist_lock;
@@ -216,6 +230,7 @@ struct klondike_info {
 	uint64_t hashcount;
 	uint64_t errorcount;
 	uint64_t noisecount;
+	int incorrect_slave_sequential;
 
 	// us Delay from USB reply to being processed
 	double delay_count;
@@ -301,7 +316,7 @@ static KLIST *allocate_kitem(struct cgpu_info *klncgpu)
 	cg_wunlock(&klninfo->klist_lock);
 
 	if (ran_out > 0)
-		applog(LOG_ERR, "%s", errbuf);
+		applog(LOG_WARNING, "%s", errbuf);
 
 	return kitem;
 }
@@ -540,7 +555,7 @@ static KLIST *GetReply(struct cgpu_info *klncgpu, uint8_t cmd, uint8_t dev)
 	KLIST *kitem;
 	int retries = CMD_REPLY_RETRIES;
 
-	while (retries-- > 0 && klninfo->shutdown == false) {
+	while (retries-- > 0 && klncgpu->shutdown == false) {
 		cgsleep_ms(REPLY_WAIT_TIME);
 		cg_rlock(&klninfo->klist_lock);
 		kitem = klninfo->used;
@@ -696,16 +711,13 @@ static bool klondike_init(struct cgpu_info *klncgpu)
 	// boundaries are checked by device, with valid values returned
 	if (opt_klondike_options != NULL) {
 		int hashclock;
-		double temp1, temp2;
+		double temptarget;
 
-		sscanf(opt_klondike_options, "%d:%lf:%lf:%"SCNu8,
-						&hashclock,
-						&temp1, &temp2,
-						&kline.cfg.fantarget);
+		sscanf(opt_klondike_options, "%d:%lf", &hashclock, &temptarget);
 		SET_HASHCLOCK(kline.cfg.hashclock, hashclock);
-		kline.cfg.temptarget = cvtCToKln(temp1);
-		kline.cfg.tempcritical = cvtCToKln(temp2);
-		kline.cfg.fantarget = (int)255*kline.cfg.fantarget/100;
+		kline.cfg.temptarget = cvtCToKln(temptarget);
+		kline.cfg.tempcritical = 0; // hard code for old firmware
+		kline.cfg.fantarget = 0xff; // hard code for old firmware
 		size = sizeof(kline.cfg) - 2;
 	}
 
@@ -809,6 +821,7 @@ static bool klondike_detect_one(struct libusb_device *dev, struct usb_find_devic
 					break;
 				update_usb_stats(klncgpu);
 				applog(LOG_DEBUG, "Klondike cgpu added");
+				rwlock_init(&klninfo->stat_lock);
 				cglock_init(&klninfo->klist_lock);
 				return true;
 			}
@@ -932,13 +945,13 @@ static void *klondike_get_replies(void *userdata)
 	struct klondike_info *klninfo = (struct klondike_info *)(klncgpu->device_data);
 	KLIST *kitem = NULL;
 	char *hexdata;
-	int err, recd, slaves, dev;
-	bool overheat;
+	int err, recd, slaves, dev, isc;
+	bool overheat, sent;
 
 	applog(LOG_DEBUG, "%s%i: listening for replies",
 			  klncgpu->drv->name, klncgpu->device_id);
 
-	while (klninfo->shutdown == false) {
+	while (klncgpu->shutdown == false) {
 		if (klncgpu->usbinfo.nodev)
 			return NULL;
 
@@ -956,7 +969,9 @@ static void *klondike_get_replies(void *userdata)
 		}
 		if (!err && recd == REPLY_SIZE) {
 			cgtime(&(kitem->tv_when));
+			rd_lock(&(klninfo->stat_lock));
 			kitem->block_seq = klninfo->block_seq;
+			rd_unlock(&(klninfo->stat_lock));
 			if (opt_log_level <= READ_DEBUG) {
 				hexdata = bin2hex((unsigned char *)&(kitem->kline.hd.dev), recd-1);
 				applog(READ_DEBUG, "%s%i:%d reply [%c:%s]",
@@ -968,10 +983,9 @@ static void *klondike_get_replies(void *userdata)
 
 			// We can't check this until it's initialised
 			if (klninfo->initialised) {
-				wr_lock(&(klninfo->stat_lock));
+				rd_lock(&(klninfo->stat_lock));
 				slaves = klninfo->status[0].kline.ws.slavecount;
-				klninfo->jobque[dev].late_update_sequential = 0;
-				wr_unlock(&(klninfo->stat_lock));
+				rd_unlock(&(klninfo->stat_lock));
 
 				if (kitem->kline.hd.dev > slaves) {
 					applog(LOG_ERR, "%s%i: reply [%c] has invalid dev=%d (max=%d) using 0",
@@ -979,7 +993,13 @@ static void *klondike_get_replies(void *userdata)
 							(char)(kitem->kline.hd.cmd),
 							(int)(kitem->kline.hd.dev),
 							slaves);
+					/* TODO: this is rather problematic if there are slaves
+					 * however without slaves - it should always be zero */
 					kitem->kline.hd.dev = 0;
+				} else {
+					wr_lock(&(klninfo->stat_lock));
+					klninfo->jobque[kitem->kline.hd.dev].late_update_sequential = 0;
+					wr_unlock(&(klninfo->stat_lock));
 				}
 			}
 
@@ -988,27 +1008,59 @@ static void *klondike_get_replies(void *userdata)
 					klondike_check_nonce(klncgpu, kitem);
 					display_kline(klncgpu, &kitem->kline, msg_reply);
 					break;
-				case KLN_CMD_STATUS:
 				case KLN_CMD_WORK:
+					// We can't do/check this until it's initialised
+					if (klninfo->initialised) {
+						dev = kitem->kline.ws.dev;
+						if (kitem->kline.ws.workqc == 0) {
+							bool idle = false;
+							rd_lock(&(klninfo->stat_lock));
+							if (klninfo->jobque[dev].flushed == false)
+								idle = true;
+							slaves = klninfo->status[0].kline.ws.slavecount;
+							rd_unlock(&(klninfo->stat_lock));
+							if (idle)
+								applog(LOG_WARNING, "%s%i:%d went idle before work was sent",
+										    klncgpu->drv->name,
+										    klncgpu->device_id,
+										    dev);
+						}
+						wr_lock(&(klninfo->stat_lock));
+						klninfo->jobque[dev].flushed = false;
+						wr_unlock(&(klninfo->stat_lock));
+					}
+				case KLN_CMD_STATUS:
 				case KLN_CMD_ABORT:
 					// We can't do/check this until it's initialised
 					if (klninfo->initialised) {
+						isc = 0;
 						dev = kitem->kline.ws.dev;
 						wr_lock(&(klninfo->stat_lock));
 						klninfo->jobque[dev].workqc = (int)(kitem->kline.ws.workqc);
 						cgtime(&(klninfo->jobque[dev].last_update));
 						slaves = klninfo->status[0].kline.ws.slavecount;
 						overheat = klninfo->jobque[dev].overheat;
+						if (dev == 0) {
+							if (kitem->kline.ws.slavecount != slaves)
+								isc = ++klninfo->incorrect_slave_sequential;
+							else
+								isc = klninfo->incorrect_slave_sequential = 0;
+						}
 						wr_unlock(&(klninfo->stat_lock));
 
-						if (kitem->kline.ws.slavecount != slaves) {
-							applog(LOG_ERR, "%s%i:%d reply [%c] has a diff # of slaves=%d"
-									" (curr=%d) dropping device to hotplug",
-									klncgpu->drv->name, klncgpu->device_id,
-									dev, (char)(kitem->kline.ws.cmd),
+						if (isc) {
+							applog(LOG_ERR, "%s%i:%d reply [%c] has a diff"
+									" # of slaves=%d (curr=%d)%s",
+									klncgpu->drv->name,
+									klncgpu->device_id,
+									dev,
+									(char)(kitem->kline.ws.cmd),
 									(int)(kitem->kline.ws.slavecount),
-									slaves);
-							klninfo->shutdown = true;
+									slaves,
+									isc <= KLN_ISS_IGNORE ? "" :
+									 " disabling device");
+							if (isc > KLN_ISS_IGNORE)
+								usb_nodev(klncgpu);
 							break;
 						}
 
@@ -1021,22 +1073,24 @@ static void *klondike_get_replies(void *userdata)
 								klninfo->jobque[dev].overheat = true;
 								wr_unlock(&(klninfo->stat_lock));
 
-								applog(LOG_ERR, "%s%i:%d Critical overheat (%.0fC)",
-										klncgpu->drv->name, klncgpu->device_id,
-										dev, temp);
+								applog(LOG_WARNING, "%s%i:%d Critical overheat (%.0fC)",
+										    klncgpu->drv->name,
+										    klncgpu->device_id,
+										    dev, temp);
 
 								zero_kline(&kline);
 								kline.hd.cmd = KLN_CMD_ABORT;
 								kline.hd.dev = dev;
-								if (!SendCmd(klncgpu, &kline, KSENDHD(0))) {
-									applog(LOG_ERR, "%s%i:%d failed to abort work"
-											" - dropping device to hotplug",
+								sent = SendCmd(klncgpu, &kline, KSENDHD(0));
+								kln_disable(klncgpu, dev, false);
+								if (!sent) {
+									applog(LOG_ERR, "%s%i:%d overheat failed to"
+											" abort work - disabling device",
 											klncgpu->drv->name,
 											klncgpu->device_id,
 											dev);
-									klninfo->shutdown = true;
+									usb_nodev(klncgpu);
 								}
-								kln_disable(klncgpu, dev, false);
 							}
 						}
 					}
@@ -1075,13 +1129,13 @@ static void klondike_flush_work(struct cgpu_info *klncgpu)
 	KLINE kline;
 	int slaves, dev;
 
+	wr_lock(&(klninfo->stat_lock));
 	klninfo->block_seq++;
+	slaves = klninfo->status[0].kline.ws.slavecount;
+	wr_unlock(&(klninfo->stat_lock));
 
 	applog(LOG_DEBUG, "%s%i: flushing work",
 			  klncgpu->drv->name, klncgpu->device_id);
-	rd_lock(&(klninfo->stat_lock));
-	slaves = klninfo->status[0].kline.ws.slavecount;
-	rd_unlock(&(klninfo->stat_lock));
 	zero_kline(&kline);
 	kline.hd.cmd = KLN_CMD_ABORT;
 	for (dev = 0; dev <= slaves; dev++) {
@@ -1092,6 +1146,7 @@ static void klondike_flush_work(struct cgpu_info *klncgpu)
 			memcpy((void *)&(klninfo->status[dev]),
 				kitem,
 				sizeof(klninfo->status[dev]));
+			klninfo->jobque[dev].flushed = true;
 			wr_unlock(&(klninfo->stat_lock));
 			kitem = release_kitem(klncgpu, kitem);
 		}
@@ -1137,7 +1192,7 @@ static void klondike_shutdown(struct thr_info *thr)
 
 	kln_disable(klncgpu, klninfo->status[0].kline.ws.slavecount, true);
 
-	klncgpu->shutdown = klninfo->shutdown = true;
+	klncgpu->shutdown = true;
 }
 
 static void klondike_thread_enable(struct thr_info *thr)
@@ -1223,10 +1278,13 @@ static bool klondike_queue_full(struct cgpu_info *klncgpu)
 {
 	struct klondike_info *klninfo = (struct klondike_info *)(klncgpu->device_data);
 	struct work *work = NULL;
-	int dev, queued, slaves, seq;
+	int dev, queued, slaves, seq, howlong;
 	struct timeval now;
 	bool nowork;
 
+	if (klncgpu->shutdown == true)
+		return true;
+
 	cgtime(&now);
 	rd_lock(&(klninfo->stat_lock));
 	slaves = klninfo->status[0].kline.ws.slavecount;
@@ -1235,25 +1293,30 @@ static bool klondike_queue_full(struct cgpu_info *klncgpu)
 			klninfo->jobque[dev].late_update_count++;
 			seq = ++klninfo->jobque[dev].late_update_sequential;
 			rd_unlock(&(klninfo->stat_lock));
-			if (seq < KLN_LATE_UPDATE_LIMIT) {
-				applog(LOG_ERR, "%s%i:%d late update",
+			if (seq < LATE_UPDATE_LIMIT) {
+				applog(LOG_DEBUG, "%s%i:%d late update",
 						klncgpu->drv->name, klncgpu->device_id, dev);
 				klondike_get_stats(klncgpu);
 				goto que;
 			} else {
-				applog(LOG_ERR, "%s%i:%d late update (%d) reached - attempting reset",
-						klncgpu->drv->name, klncgpu->device_id,
-						dev, KLN_LATE_UPDATE_LIMIT);
+				applog(LOG_WARNING, "%s%i:%d late update (%d) reached - attempting reset",
+						    klncgpu->drv->name, klncgpu->device_id,
+						    dev, LATE_UPDATE_LIMIT);
 				control_init(klncgpu);
 				kln_enable(klncgpu);
 				klondike_get_stats(klncgpu);
 				rd_lock(&(klninfo->stat_lock));
-				if (ms_tdiff(&now, &(klninfo->jobque[dev].last_update)) > LATE_UPDATE_MS) {
+				howlong = ms_tdiff(&now, &(klninfo->jobque[dev].last_update));
+				if (howlong > LATE_UPDATE_MS) {
 					rd_unlock(&(klninfo->stat_lock));
-					applog(LOG_ERR, "%s%i:%d reset failed - dropping device",
-							klncgpu->drv->name, klncgpu->device_id, dev);
-					klninfo->shutdown = true;
-					return false;
+					if (howlong > LATE_UPDATE_NODEV_MS) {
+						applog(LOG_ERR, "%s%i:%d reset failed - dropping device",
+								klncgpu->drv->name, klncgpu->device_id, dev);
+						usb_nodev(klncgpu);
+					} else
+						cgsleep_ms(LATE_UPDATE_SLEEP_MS);
+
+					return true;
 				}
 				break;
 			}
@@ -1278,9 +1341,9 @@ tryagain:
 				if (temp <= KLN_COOLED_DOWN) {
 					klninfo->jobque[dev].overheat = false;
 					rd_unlock(&(klninfo->stat_lock));
-					applog(LOG_ERR, "%s%i:%d Overheat recovered (%.0fC)",
-							klncgpu->drv->name, klncgpu->device_id,
-							dev, temp);
+					applog(LOG_WARNING, "%s%i:%d Overheat recovered (%.0fC)",
+							    klncgpu->drv->name, klncgpu->device_id,
+							    dev, temp);
 					kln_enable(klncgpu);
 					goto tryagain;
 				} else {
@@ -1340,6 +1403,7 @@ static int64_t klondike_scanwork(struct thr_info *thr)
 		klninfo->noncecount = 0;
 		rd_unlock(&(klninfo->stat_lock));
 	}
+
 	return newhashcount;
 }
 
diff --git a/driver-knc-spi-fpga.c b/driver-knc-spi-fpga.c
new file mode 100644
index 0000000..f848856
--- /dev/null
+++ b/driver-knc-spi-fpga.c
@@ -0,0 +1,762 @@
+/*
+ * cgminer driver for KnCminer devices
+ *
+ * Copyright 2013 Con Kolivas <kernel@kolivas.org>
+ * Copyright 2013 KnCminer
+ *
+ * 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 <stdlib.h>
+#include <assert.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <unistd.h>
+#include <sys/ioctl.h>
+#include <linux/types.h>
+#include <linux/spi/spidev.h>
+
+#include "logging.h"
+#include "miner.h"
+
+#define MAX_SPIS		1
+#define	MAX_BYTES_IN_SPI_XSFER	4096
+/* /dev/spidevB.C, where B = bus, C = chipselect */
+#define SPI_DEVICE_TEMPLATE	"/dev/spidev%d.%d"
+#define SPI_MODE		(SPI_CPHA | SPI_CPOL | SPI_CS_HIGH)
+#define SPI_BITS_PER_WORD	32
+#define SPI_MAX_SPEED		3000000
+#define SPI_DELAY_USECS		0
+/* Max number of ASICs permitted on one SPI device */
+#define MAX_ASICS		6
+
+/* How many hardware errors in a row before disabling the core */
+#define HW_ERR_LIMIT		10
+#define DISA_ERR_LIMIT		3
+
+#define MAX_ACTIVE_WORKS	(192 * 2 * 6 * 2)
+
+#define WORK_MIDSTATE_WORDS	8
+#define WORK_DATA_WORDS		3
+
+#define WORK_STALE_US		60000000
+
+/* Keep core disabled for no longer than 15 minutes */
+#define CORE_DISA_PERIOD_US	(15 * 60 * 1000000)
+
+struct spidev_context {
+	int fd;
+	uint32_t speed;
+	uint16_t delay;
+	uint8_t mode;
+	uint8_t bits;
+};
+
+struct spi_request {
+#define	CMD_NOP		0
+#define	CMD_GET_VERSION	1
+#define	CMD_SUBMIT_WORK	2
+#define	CMD_FLUSH_QUEUE	3
+
+#define	WORK_ID_MASK	0x7FFF
+
+#if (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
+	uint32_t cmd		:4;
+	uint32_t rsvd		:1; /* set to zero */
+	uint32_t queue_id	:12;
+	uint32_t work_id	:15;
+#else
+	uint32_t work_id	:15;
+	uint32_t queue_id	:12;
+	uint32_t rsvd		:1; /* set to zero */
+	uint32_t cmd		:4;
+#endif
+	uint32_t midstate[WORK_MIDSTATE_WORDS];
+	uint32_t data[WORK_DATA_WORDS];
+};
+
+struct spi_response {
+#define	RESPONSE_TYPE_NOP		0
+#define	RESPONSE_TYPE_NONCE_FOUND	1
+#define	RESPONSE_TYPE_WORK_DONE		2
+#if (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
+	uint32_t type		:2;
+	uint32_t asic		:3;
+	uint32_t queue_id	:12;
+	uint32_t work_id	:15;
+#else
+	uint32_t work_id	:15;
+	uint32_t queue_id	:12;
+	uint32_t asic		:3;
+	uint32_t type		:2;
+#endif
+	uint32_t nonce;
+	uint32_t core;
+};
+
+#define MAX_REQUESTS_IN_BATCH	( MAX_BYTES_IN_SPI_XSFER /	\
+				  sizeof(struct spi_request)	\
+				)
+
+static struct spi_request spi_txbuf[MAX_REQUESTS_IN_BATCH];
+
+#define MAX_RESPONSES_IN_BATCH	( (sizeof(spi_txbuf) - 12) /	\
+				   sizeof(struct spi_response)	\
+				)
+
+struct spi_rx_t {
+#if (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
+	uint32_t rsvd_1			:31;
+	uint32_t response_queue_full	:1;
+#else
+	uint32_t response_queue_full	:1;
+	uint32_t rsvd_1			:31;
+#endif
+#if (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
+	uint32_t rsvd_2			:16;
+	uint32_t works_accepted		:16;
+#else
+	uint32_t works_accepted		:16;
+	uint32_t rsvd_2			:16;
+#endif
+	uint32_t rsvd_3;
+	struct spi_response responses[MAX_RESPONSES_IN_BATCH];
+};
+
+static struct spi_rx_t spi_rxbuf;
+
+struct active_work {
+	struct work *work;
+	uint32_t work_id;
+	struct timeval begin;
+};
+
+struct core_disa_data {
+	struct timeval disa_begin;
+	uint8_t asic;
+	uint8_t core;
+};
+
+struct knc_state {
+	struct spidev_context *ctx;
+	int devices;
+	uint32_t salt;
+	uint32_t next_work_id;
+
+	/* read - last read item, next is at (read + 1) mod BUFSIZE
+	 * write - next write item, last written at (write - 1) mod BUFSIZE
+	 *  When buffer is empty, read + 1 == write
+	 *  Buffer full condition: read == write
+	 */
+	int read_q, write_q;
+#define KNC_QUEUED_BUFFER_SIZE	(MAX_REQUESTS_IN_BATCH + 1)
+	struct active_work queued_fifo[KNC_QUEUED_BUFFER_SIZE];
+
+	int read_a, write_a;
+#define KNC_ACTIVE_BUFFER_SIZE	(MAX_ACTIVE_WORKS + 1)
+	struct active_work active_fifo[KNC_ACTIVE_BUFFER_SIZE];
+
+	uint8_t hwerrs[MAX_ASICS * 256];
+	uint8_t disa_cnt[MAX_ASICS * 256];
+	uint32_t hwerr_work_id[MAX_ASICS * 256];
+	int read_d, write_d;
+#define KNC_DISA_CORES_SIZE	(MAX_ASICS * 256)
+	struct core_disa_data disa_cores_fifo[KNC_DISA_CORES_SIZE];
+
+	pthread_mutex_t lock;
+};
+
+static inline bool knc_queued_fifo_full(struct knc_state *knc)
+{
+	return (knc->read_q == knc->write_q);
+}
+
+static inline bool knc_active_fifo_full(struct knc_state *knc)
+{
+	return (knc->read_a == knc->write_a);
+}
+
+static inline void knc_queued_fifo_inc_idx(int *idx)
+{
+	if (unlikely(*idx >= ((int)KNC_QUEUED_BUFFER_SIZE - 1)))
+		*idx = 0;
+	else
+		++(*idx);
+}
+
+static inline void knc_active_fifo_inc_idx(int *idx)
+{
+	if (unlikely(*idx >= (KNC_ACTIVE_BUFFER_SIZE - 1)))
+		*idx = 0;
+	else
+		++(*idx);
+}
+
+static inline void knc_disa_cores_fifo_inc_idx(int *idx)
+{
+	if (unlikely(*idx >= (KNC_DISA_CORES_SIZE - 1)))
+		*idx = 0;
+	else
+		++(*idx);
+}
+
+/* Find SPI device with index idx, init it */
+static struct spidev_context *spi_new(int idx)
+{
+	struct spidev_context *ctx;
+	char dev_fname[PATH_MAX];
+
+	if (NULL == (ctx = malloc(sizeof(struct spidev_context)))) {
+		applog(LOG_ERR, "KnC spi: Out of memory");
+		goto l_exit_error;
+	}
+	ctx->mode = SPI_MODE;
+	ctx->bits = SPI_BITS_PER_WORD;
+	ctx->speed = SPI_MAX_SPEED;
+	ctx->delay = SPI_DELAY_USECS;
+
+	ctx->fd = -1;
+
+	sprintf(dev_fname, SPI_DEVICE_TEMPLATE,
+		idx, /* bus */
+		0    /* chipselect */
+	       );
+	if (0 > (ctx->fd = open(dev_fname, O_RDWR))) {
+		applog(LOG_ERR, "KnC spi: Can not open SPI device %s: %m",
+		       dev_fname);
+		goto l_free_exit_error;
+	}
+
+	/*
+	 * spi mode
+	 */
+	if (0 > ioctl(ctx->fd, SPI_IOC_WR_MODE, &ctx->mode))
+		goto l_ioctl_error;
+	if (0 > ioctl(ctx->fd, SPI_IOC_RD_MODE, &ctx->mode))
+		goto l_ioctl_error;
+
+	/*
+	 * bits per word
+	 */
+	if (0 > ioctl(ctx->fd, SPI_IOC_WR_BITS_PER_WORD, &ctx->bits))
+		goto l_ioctl_error;
+	if (0 > ioctl(ctx->fd, SPI_IOC_RD_BITS_PER_WORD, &ctx->bits))
+		goto l_ioctl_error;
+
+	/*
+	 * max speed hz
+	 */
+	if (0 > ioctl(ctx->fd, SPI_IOC_WR_MAX_SPEED_HZ, &ctx->speed))
+		goto l_ioctl_error;
+	if (0 > ioctl(ctx->fd, SPI_IOC_RD_MAX_SPEED_HZ, &ctx->speed))
+		goto l_ioctl_error;
+
+	applog(LOG_INFO, "KnC spi: device %s uses mode %hhu, bits %hhu, speed %u",
+	       dev_fname, ctx->mode, ctx->bits, ctx->speed);
+
+	return ctx;
+
+l_ioctl_error:
+	applog(LOG_ERR, "KnC spi: ioctl error on SPI device %s: %m", dev_fname);
+	close(ctx->fd);
+l_free_exit_error:
+	free(ctx);
+l_exit_error:
+	return NULL;
+}
+
+static void spi_free(struct spidev_context *ctx)
+{
+	if (NULL == ctx)
+		return;
+
+	close(ctx->fd);
+	free(ctx);
+}
+
+static int spi_transfer(struct spidev_context *ctx, uint8_t *txbuf,
+			uint8_t *rxbuf, int len)
+{
+	struct spi_ioc_transfer xfr;
+	int ret;
+
+	memset(rxbuf, 0xff, len);
+
+	ret = len;
+
+	xfr.tx_buf = (unsigned long)txbuf;
+	xfr.rx_buf = (unsigned long)rxbuf;
+	xfr.len = len;
+	xfr.speed_hz = ctx->speed;
+	xfr.delay_usecs = ctx->delay;
+	xfr.bits_per_word = ctx->bits;
+	xfr.cs_change = 0;
+	xfr.pad = 0;
+
+	if (1 > (ret = ioctl(ctx->fd, SPI_IOC_MESSAGE(1), &xfr)))
+		applog(LOG_ERR, "KnC spi xfer: ioctl error on SPI device: %m");
+
+	return ret;
+}
+
+static void disable_core(uint8_t asic, uint8_t core)
+{
+	char str[256];
+
+	snprintf(str, sizeof(str), "i2cset -y 2 0x2%hhu %hhu 0", asic, core);
+	if (0 != WEXITSTATUS(system(str)))
+		applog(LOG_ERR, "KnC: system call failed");
+}
+
+static void enable_core(uint8_t asic, uint8_t core)
+{
+	char str[256];
+
+	snprintf(str, sizeof(str), "i2cset -y 2 0x2%hhu %hhu 1", asic, core);
+	if (0 != WEXITSTATUS(system(str)))
+		applog(LOG_ERR, "KnC: system call failed");
+}
+
+static int64_t timediff(const struct timeval *a, const struct timeval *b)
+{
+	struct timeval diff;
+
+	timersub(a, b, &diff);
+
+	return diff.tv_sec * 1000000 + diff.tv_usec;
+}
+
+static void knc_check_disabled_cores(struct knc_state *knc)
+{
+	struct core_disa_data *core;
+	int next_read_d, cidx;
+	struct timeval now;
+	int64_t us;
+
+	next_read_d = knc->read_d;
+	knc_disa_cores_fifo_inc_idx(&next_read_d);
+	if (next_read_d == knc->write_d)
+		return; /* queue empty */
+
+	core = &knc->disa_cores_fifo[next_read_d];
+	gettimeofday(&now, NULL);
+	us = timediff(&now, &core->disa_begin);
+	if ((us >= 0) && (us < CORE_DISA_PERIOD_US))
+		return; /* latest disabled core still not expired */
+
+	cidx = core->asic * 256 + core->core;
+	enable_core(core->asic, core->core);
+	knc->hwerrs[cidx] = 0;
+	applog(LOG_NOTICE,
+	       "KnC: core %u-%u was enabled back from disabled state",
+	       core->asic, core->core);
+	knc->read_d = next_read_d;
+}
+
+static void knc_work_from_queue_to_spi(struct knc_state *knc,
+				       struct active_work *q_work,
+				       struct spi_request *spi_req)
+{
+	uint32_t *buf_from, *buf_to;
+	int i;
+
+	spi_req->cmd = CMD_SUBMIT_WORK;
+	spi_req->queue_id = 0; /* at the moment we have one and only queue #0 */
+	spi_req->work_id = (knc->next_work_id ^ knc->salt) & WORK_ID_MASK;
+	q_work->work_id = spi_req->work_id;
+	++(knc->next_work_id);
+	buf_to = spi_req->midstate;
+	buf_from = (uint32_t *)q_work->work->midstate;
+
+	for (i = 0; i < WORK_MIDSTATE_WORDS; ++i)
+		buf_to[i] = le32toh(buf_from[8 - i - 1]);
+	buf_to = spi_req->data;
+	buf_from = (uint32_t *)&(q_work->work->data[16 * 4]);
+
+	for (i = 0; i < WORK_DATA_WORDS; ++i)
+		buf_to[i] = le32toh(buf_from[3 - i - 1]);
+}
+
+static int64_t knc_process_response(struct thr_info *thr, struct cgpu_info *cgpu,
+				    struct spi_rx_t *rxbuf)
+{
+	struct knc_state *knc = cgpu->device_data;
+	int submitted, successful, i, num_sent;
+	int next_read_q, next_read_a;
+	struct timeval now;
+	struct work *work;
+	int64_t us;
+
+	num_sent = knc->write_q - knc->read_q - 1;
+	if (knc->write_q <= knc->read_q)
+		num_sent += KNC_QUEUED_BUFFER_SIZE;
+
+	/* Actually process SPI response */
+	if (rxbuf->works_accepted) {
+		applog(LOG_DEBUG, "KnC spi: raw response %08X %08X",
+		       ((uint32_t *)rxbuf)[0], ((uint32_t *)rxbuf)[1]);
+		applog(LOG_DEBUG,
+		       "KnC spi: response, accepted %u (from %u), full %u",
+		       rxbuf->works_accepted, num_sent,
+		       rxbuf->response_queue_full);
+	}
+	/* move works_accepted number of items from queued_fifo to active_fifo */
+	gettimeofday(&now, NULL);
+	submitted = 0;
+
+	for (i = 0; i < rxbuf->works_accepted; ++i) {
+		next_read_q = knc->read_q;
+		knc_queued_fifo_inc_idx(&next_read_q);
+		if ((next_read_q == knc->write_q) || knc_active_fifo_full(knc))
+			break;
+
+		memcpy(&knc->active_fifo[knc->write_a],
+		       &knc->queued_fifo[next_read_q],
+		       sizeof(struct active_work));
+		knc->active_fifo[knc->write_a].begin = now;
+		knc->queued_fifo[next_read_q].work = NULL;
+		knc->read_q = next_read_q;
+		knc_active_fifo_inc_idx(&knc->write_a);
+		++submitted;
+	}
+	if (submitted != rxbuf->works_accepted) {
+		applog(LOG_ERR,
+		       "KnC: accepted by FPGA %u works, but only %d submitted",
+		       rxbuf->works_accepted, submitted);
+	}
+
+	/* check for completed works and calculated nonces */
+	gettimeofday(&now, NULL);
+	successful = 0;
+
+	for (i = 0; i < (int)MAX_RESPONSES_IN_BATCH; ++i) {
+		if ((rxbuf->responses[i].type != RESPONSE_TYPE_NONCE_FOUND) &&
+		    (rxbuf->responses[i].type != RESPONSE_TYPE_WORK_DONE))
+			continue;
+
+		applog(LOG_DEBUG, "KnC spi: raw response %08X %08X",
+		       ((uint32_t *)&rxbuf->responses[i])[0],
+		       ((uint32_t *)&rxbuf->responses[i])[1]);
+		applog(LOG_DEBUG, "KnC spi: response, T:%u C:%u-%u Q:%u W:%u",
+		       rxbuf->responses[i].type,
+		       rxbuf->responses[i].asic, rxbuf->responses[i].core,
+		       rxbuf->responses[i].queue_id,
+		       rxbuf->responses[i].work_id);
+		/* Find active work with matching ID */
+		next_read_a = knc->read_a;
+		knc_active_fifo_inc_idx(&next_read_a);
+
+		while (next_read_a != knc->write_a) {
+			if (knc->active_fifo[next_read_a].work_id ==
+			    rxbuf->responses[i].work_id)
+				break;
+
+			/* check for stale works */
+			us = timediff(&now,
+				      &knc->active_fifo[next_read_a].begin);
+			if ((us < 0) || (us >= WORK_STALE_US)) {
+				applog(LOG_DEBUG,
+				       "KnC spi: remove stale work %u",
+				       knc->active_fifo[next_read_a].work_id);
+				work = knc->active_fifo[next_read_a].work;
+				knc_active_fifo_inc_idx(&knc->read_a);
+				work_completed(cgpu, work);
+				if (next_read_a != knc->read_a) {
+					memcpy(&(knc->active_fifo[next_read_a]),
+					       &(knc->active_fifo[knc->read_a]),
+					       sizeof(struct active_work));
+				}
+				knc->active_fifo[knc->read_a].work = NULL;
+			}
+
+			knc_active_fifo_inc_idx(&next_read_a);
+		}
+		if (next_read_a == knc->write_a)
+			continue;
+
+		applog(LOG_DEBUG, "KnC spi: response work %u found",
+		       rxbuf->responses[i].work_id);
+		work = knc->active_fifo[next_read_a].work;
+
+		if (rxbuf->responses[i].type == RESPONSE_TYPE_NONCE_FOUND) {
+			if (NULL != thr) {
+				int cidx = rxbuf->responses[i].asic * 256 +
+					   rxbuf->responses[i].core;
+
+				if (submit_nonce(thr, work,
+						 rxbuf->responses[i].nonce)) {
+					if (cidx < (int)sizeof(knc->hwerrs)) {
+						knc->hwerrs[cidx] = 0;
+						knc->disa_cnt[cidx] = 0;
+						knc->hwerr_work_id[cidx] = 0xFFFFFFFF;
+					}
+					successful++;
+				} else  {
+					if ((cidx < (int)sizeof(knc->hwerrs)) &&
+					    (knc->hwerr_work_id[cidx] != rxbuf->responses[i].work_id)) {
+						knc->hwerr_work_id[cidx] = rxbuf->responses[i].work_id;
+						if (++(knc->hwerrs[cidx]) >= HW_ERR_LIMIT) {
+						    struct core_disa_data *core;
+
+						    core = &knc->disa_cores_fifo[knc->write_d];
+						    core->disa_begin = now;
+						    core->asic = rxbuf->responses[i].asic;
+						    core->core = rxbuf->responses[i].core;
+						    disable_core(core->asic, core->core);
+						    if (++(knc->disa_cnt[cidx]) >= DISA_ERR_LIMIT) {
+							    applog(LOG_WARNING,
+			"KnC: core %u-%u was disabled permanently", core->asic, core->core);
+						    } else {
+							    applog(LOG_WARNING,
+			"KnC: core %u-%u was disabled due to %u HW errors in a row",
+								   core->asic, core->core, HW_ERR_LIMIT);
+							    knc_disa_cores_fifo_inc_idx(&knc->write_d);
+						    }
+						}
+					}
+				};
+			}
+			continue;
+		}
+
+		/* Work completed */
+		knc_active_fifo_inc_idx(&knc->read_a);
+		work_completed(cgpu, work);
+		if (next_read_a != knc->read_a) {
+			memcpy(&(knc->active_fifo[next_read_a]),
+			       &(knc->active_fifo[knc->read_a]),
+			       sizeof(struct active_work));
+		}
+		knc->active_fifo[knc->read_a].work = NULL;
+	}
+
+	return ((uint64_t)successful) * 0x100000000UL;
+}
+
+/* Send flush command via SPI */
+static int _internal_knc_flush_fpga(struct knc_state *knc)
+{
+	int len;
+
+	spi_txbuf[0].cmd = CMD_FLUSH_QUEUE;
+	spi_txbuf[0].queue_id = 0; /* at the moment we have one and only queue #0 */
+	len = spi_transfer(knc->ctx, (uint8_t *)spi_txbuf,
+			   (uint8_t *)&spi_rxbuf, sizeof(struct spi_request));
+	if (len != sizeof(struct spi_request))
+		return -1;
+
+	len /= sizeof(struct spi_response);
+
+	return len;
+}
+
+static bool knc_detect_one(struct spidev_context *ctx)
+{
+	/* Scan device for ASICs */
+	int chip_id, devices = 0;
+	struct cgpu_info *cgpu;
+	struct knc_state *knc;
+
+	for (chip_id = 0; chip_id < MAX_ASICS; ++chip_id) {
+		/* TODO: perform the ASIC test/detection */
+		++devices;
+	}
+
+	if (!devices) {
+		applog(LOG_INFO, "SPI detected, but not KnCminer ASICs");
+		return false;
+	}
+
+	applog(LOG_INFO, "Found a KnC miner with %d ASICs", devices);
+
+	cgpu = calloc(1, sizeof(*cgpu));
+	knc = calloc(1, sizeof(*knc));
+	if (!cgpu || !knc) {
+		applog(LOG_ERR, "KnC miner detected, but failed to allocate memory");
+		return false;
+	}
+
+	knc->ctx = ctx;
+	knc->devices = devices;
+	knc->read_q = 0;
+	knc->write_q = 1;
+	knc->read_a = 0;
+	knc->write_a = 1;
+	knc->read_d = 0;
+	knc->write_d = 1;
+	knc->salt = rand();
+	mutex_init(&knc->lock);
+
+	memset(knc->hwerr_work_id, 0xFF, sizeof(knc->hwerr_work_id));
+
+	_internal_knc_flush_fpga(knc);
+
+	cgpu->drv = &knc_drv;
+	cgpu->name = "KnCminer";
+	cgpu->threads = 1;	// .. perhaps our number of devices?
+
+	cgpu->device_data = knc;
+	add_cgpu(cgpu);
+
+	return true;
+}
+
+// http://www.concentric.net/~Ttwang/tech/inthash.htm
+static unsigned long mix(unsigned long a, unsigned long b, unsigned long c)
+{
+	a = a - b;  a = a - c;  a = a ^ (c >> 13);
+	b = b - c;  b = b - a;  b = b ^ (a << 8);
+	c = c - a;  c = c - b;  c = c ^ (b >> 13);
+	a = a - b;  a = a - c;  a = a ^ (c >> 12);
+	b = b - c;  b = b - a;  b = b ^ (a << 16);
+	c = c - a;  c = c - b;  c = c ^ (b >> 5);
+	a = a - b;  a = a - c;  a = a ^ (c >> 3);
+	b = b - c;  b = b - a;  b = b ^ (a << 10);
+	c = c - a;  c = c - b;  c = c ^ (b >> 15);
+
+	return c;
+}
+
+/* Probe devices and register with add_cgpu */
+void knc_detect(bool __maybe_unused hotplug)
+{
+	int idx;
+
+	srand(mix(clock(), time(NULL), getpid()));
+
+	/* Loop through all possible SPI interfaces */
+	for (idx = 0; idx < MAX_SPIS; ++idx) {
+		struct spidev_context *ctx = spi_new(idx + 1);
+
+		if (ctx != NULL) {
+			if (!knc_detect_one(ctx))
+				spi_free(ctx);
+		}
+	}
+}
+
+/* return value is number of nonces that have been checked since
+ * previous call
+ */
+static int64_t knc_scanwork(struct thr_info *thr)
+{
+	struct cgpu_info *cgpu = thr->cgpu;
+	struct knc_state *knc = cgpu->device_data;
+	int len, num, next_read_q;
+	int64_t ret;
+
+	applog(LOG_DEBUG, "KnC running scanwork");
+
+	knc_check_disabled_cores(knc);
+
+	/* Prepare tx buffer */
+	memset(spi_txbuf, 0, sizeof(spi_txbuf));
+	num = 0;
+
+	mutex_lock(&knc->lock);
+	next_read_q = knc->read_q;
+	knc_queued_fifo_inc_idx(&next_read_q);
+
+	while (next_read_q != knc->write_q) {
+		knc_work_from_queue_to_spi(knc, &knc->queued_fifo[next_read_q],
+					   &spi_txbuf[num]);
+		knc_queued_fifo_inc_idx(&next_read_q);
+		++num;
+	}
+	/* knc->read_q is advanced in knc_process_response, not here */
+
+	len = spi_transfer(knc->ctx, (uint8_t *)spi_txbuf,
+			   (uint8_t *)&spi_rxbuf, sizeof(spi_txbuf));
+	if (len != sizeof(spi_rxbuf)) {
+		ret = -1;
+		goto out_unlock;
+	}
+
+	applog(LOG_DEBUG, "KnC spi: %d works in request", num);
+
+	ret = knc_process_response(thr, cgpu, &spi_rxbuf);
+out_unlock:
+	mutex_unlock(&knc->lock);
+
+	return ret;
+}
+
+static bool knc_queue_full(struct cgpu_info *cgpu)
+{
+	struct knc_state *knc = cgpu->device_data;
+	int queue_full = false;
+	struct work *work;
+
+	applog(LOG_DEBUG, "KnC running queue full");
+
+	mutex_lock(&knc->lock);
+	if (knc_queued_fifo_full(knc)) {
+		queue_full = true;
+		goto out_unlock;
+	}
+	work = get_queued(cgpu);
+	if (!work)
+		goto out_unlock;
+	knc->queued_fifo[knc->write_q].work = work;
+	knc_queued_fifo_inc_idx(&(knc->write_q));
+	if (knc_queued_fifo_full(knc))
+		queue_full = true;
+out_unlock:
+	mutex_unlock(&knc->lock);
+
+	return queue_full;
+}
+
+static void knc_flush_work(struct cgpu_info *cgpu)
+{
+	struct knc_state *knc = cgpu->device_data;
+	int len, next_read_q, next_read_a;
+	struct work *work;
+
+	applog(LOG_ERR, "KnC running flushwork");
+
+	mutex_lock(&knc->lock);
+	/* Drain queued works */
+	next_read_q = knc->read_q;
+	knc_queued_fifo_inc_idx(&next_read_q);
+
+	while (next_read_q != knc->write_q) {
+		work = knc->queued_fifo[next_read_q].work;
+		work_completed(cgpu, work);
+		knc->queued_fifo[next_read_q].work = NULL;
+		knc->read_q = next_read_q;
+		knc_queued_fifo_inc_idx(&next_read_q);
+	}
+
+	/* Drain active works */
+	next_read_a = knc->read_a;
+	knc_active_fifo_inc_idx(&next_read_a);
+
+	while (next_read_a != knc->write_a) {
+		work = knc->active_fifo[next_read_a].work;
+		work_completed(cgpu, work);
+		knc->active_fifo[next_read_a].work = NULL;
+		knc->read_a = next_read_a;
+		knc_active_fifo_inc_idx(&next_read_a);
+	}
+
+	len = _internal_knc_flush_fpga(knc);
+	if (len > 0)
+		knc_process_response(NULL, cgpu, &spi_rxbuf);
+	mutex_unlock(&knc->lock);
+}
+
+struct device_drv knc_drv = {
+	.drv_id = DRIVER_knc,
+	.dname = "KnCminer",
+	.name = "KnC",
+	.drv_detect = knc_detect,	// Probe for devices, add with add_cgpu
+
+	.hash_work = hash_queued_work,
+	.scanwork = knc_scanwork,
+	.queue_full = knc_queue_full,
+	.flush_work = knc_flush_work,
+};
diff --git a/hf_protocol.h b/hf_protocol.h
new file mode 100644
index 0000000..387c284
--- /dev/null
+++ b/hf_protocol.h
@@ -0,0 +1,349 @@
+//
+// Copyright 2013 HashFast LLC
+//
+// 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.
+//
+// Useful data structures and values for interfacing with HashFast products
+//
+// Version 1.0
+//
+
+#ifndef _HF_PROTOCOL_H_
+#define _HF_PROTOCOL_H_
+
+#define HF_PROTOCOL_VERSION     ((0<<8)|1)
+
+#define HF_PREAMBLE             (uint8_t) 0xaa
+#define HF_BROADCAST_ADDRESS    (uint8_t) 0xff
+#define HF_GWQ_ADDRESS          (uint8_t) 254
+
+// Serial protocol operation codes (Second header byte)
+#define OP_NULL         0
+#define OP_ROOT         1
+#define OP_RESET        2
+#define OP_PLL_CONFIG   3
+#define OP_ADDRESS      4
+#define OP_READDRESS    5
+#define OP_HIGHEST      6
+#define OP_BAUD         7
+#define OP_UNROOT       8
+
+#define OP_HASH         9
+#define OP_NONCE        10
+#define OP_ABORT        11
+#define OP_STATUS       12
+#define OP_GPIO         13
+#define OP_CONFIG       14
+#define OP_STATISTICS   15
+#define OP_GROUP        16
+#define OP_CLOCKGATE    17
+
+// Conversions for the ADC readings from GN on-chip sensors
+#define GN_CORE_VOLTAGE(a)              ((float)(a)/256*1.2)
+#define GN_DIE_TEMPERATURE(a)           ((((float)(a)*240)/4096.0)-61.5)
+
+// The sequence distance between a sent and received sequence number.
+#define HF_SEQUENCE_DISTANCE(tx,rx)        ((tx)>=(rx)?((tx)-(rx)):(info->num_sequence+(tx)-(rx)))
+
+// Values the protocol field in the above structure may take
+#define PROTOCOL_USB_MAPPED_SERIAL      0
+#define PROTOCOL_GLOBAL_WORK_QUEUE      1
+
+// Conversions for the board/module level sensors
+#define M_VOLTAGE(a)                    ((float)(a)*19.0734e-6)
+#define M_PHASE_CURRENT(a)              ((float)(a)*0.794728597e-3)
+
+// Values info->device_type can take
+#define HFD_G1                            1         // HashFast G-1 GN ASIC
+#define HFD_VC709                       128
+#define HFD_ExpressAGX                  129
+
+// USB interface specific operation codes
+#define OP_USB_INIT                     128         // Initialize USB interface details
+#define OP_GET_TRACE                    129         // Send back the trace buffer if present
+#define OP_LOOPBACK_USB                 130
+#define OP_LOOPBACK_UART                131
+#define OP_DFU                          132         // Jump into the boot loader
+#define OP_USB_SHUTDOWN                 133         // Initialize USB interface details
+#define OP_DIE_STATUS                   134         // Die status. There are 4 die per ASIC
+#define OP_GWQ_STATUS                   135         // Global Work Queue protocol status
+#define OP_WORK_RESTART                 136         // Stratum work restart regime
+#define OP_USB_STATS1                   137         // Statistics class 1
+#define OP_USB_GWQSTATS                 138         // GWQ protocol statistics
+#define OP_USB_NOTICE                   139         // Asynchronous notification event
+#define OP_USB_DEBUG                    255
+
+// HashFast vendor and product ID's
+#define HF_USB_VENDOR_ID                0x297c
+#define HF_USB_PRODUCT_ID_G1            0x0001
+
+// If this bit is set, search forward for other nonce(s)
+#define HF_NTIME_MASK                   0xfff       // Mask for for ntime
+#define HF_NONCE_SEARCH                 0x1000      // Search bit in candidate_nonce -> ntime
+
+//
+// Fault codes that can be returned in struct hf_usb_init_base.operation_status
+//
+#define E_RESET_TIMEOUT                 1
+#define E_ADDRESS_TIMEOUT               2
+#define E_CLOCKGATE_TIMEOUT             3
+#define E_CONFIG_TIMEOUT                4
+#define E_EXCESS_CORE_FAILURES          5
+
+#define U32SIZE(x)                      (sizeof(x)/sizeof(uint32_t))
+
+
+// Structure definitions, LE platforms
+
+#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
+#include "hf_protocol_be.h"
+#else
+// Generic header
+struct hf_header {
+	uint8_t  preamble;                      // Always 0xaa
+	uint8_t  operation_code;
+	uint8_t  chip_address;
+	uint8_t  core_address;
+	uint16_t hdata;                         // Header specific data
+	uint8_t  data_length;                   // .. of data frame to follow, in 4 byte blocks, 0=no data
+	uint8_t  crc8;                          // Computed across bytes 1-6 inclusive
+} __attribute__((packed,aligned(4)));           // 8 bytes total
+
+// Header specific to OP_PLL_CONFIG
+struct hf_pll_config {
+	uint8_t  preamble;
+	uint8_t  operation_code;
+	uint8_t  chip_address;
+
+	uint8_t  pll_divr:6;
+	uint8_t  pll_bypass:1;
+	uint8_t  pll_reset:1;
+
+	uint8_t  pll_divf;
+
+	uint8_t  spare1:1;                      // Must always be 0
+	uint8_t  pll_divq:3;
+	uint8_t  pll_range:3;
+	uint8_t  pll_fse:1;                     // Must always be 1
+
+	uint8_t  data_length;                   // Always 0
+	uint8_t  crc8;                          // Computed across bytes 1-6 inclusive
+} __attribute__((packed,aligned(4)));           // 8 bytes total
+
+// OP_HASH serial data
+struct hf_hash_serial {
+	uint8_t  midstate[32];                  // Computed from first half of block header
+	uint8_t  merkle_residual[4];            // From block header
+	uint32_t timestamp;                     // From block header
+	uint32_t bits;                          // Actual difficulty target for block header
+	uint32_t starting_nonce;                // Usually set to 0
+	uint32_t nonce_loops;                   // How many nonces to search, or 0 for 2^32
+	uint16_t ntime_loops;                   // How many times to roll timestamp, or 0
+	uint8_t  search_difficulty;             // Search difficulty to use, # of '0' digits required
+	uint8_t  option;
+	uint8_t  group;
+	uint8_t  spare3[3];
+} __attribute__((packed,aligned(4)));
+
+// OP_HASH usb data - header+data = 64 bytes
+struct hf_hash_usb {
+	uint8_t  midstate[32];                  // Computed from first half of block header
+	uint8_t  merkle_residual[4];            // From block header
+	uint32_t timestamp;                     // From block header
+	uint32_t bits;                          // Actual difficulty target for block header
+	uint32_t starting_nonce;                // Usually set to 0
+	uint32_t nonce_loops;                   // How many nonces to search, or 0 for 2^32
+	uint16_t ntime_loops;                   // How many times to roll timestamp, or 0
+	uint8_t  search_difficulty;             // Search difficulty to use, # of '0' digits required
+	uint8_t  group;                         // Non-zero for valid group
+} __attribute__((packed,aligned(4)));
+
+// OP_NONCE data
+struct hf_candidate_nonce {
+	uint32_t nonce;                         // Candidate nonce
+	uint16_t sequence;                      // Sequence number from corresponding OP_HASH
+	uint16_t ntime;                         // ntime offset, if ntime roll occurred, in LS 12 bits
+						// If b12 set, search forward next 128 nonces to find solution(s)
+} __attribute__((packed,aligned(4)));
+
+// OP_CONFIG data
+struct hf_config_data {
+	uint16_t status_period:11;                  // Periodic status time, msec
+	uint16_t enable_periodic_status:1;          // Send periodic status
+	uint16_t send_status_on_core_idle:1;        // Schedule status whenever core goes idle
+	uint16_t send_status_on_pending_empty:1;    // Schedule status whenever core pending goes idle
+	uint16_t pwm_active_level:1;                // Active level of PWM outputs, if used
+	uint16_t forward_all_privileged_packets:1;  // Forward priv pkts -- diagnostic
+	uint8_t  status_batch_delay;                // Batching delay, time to wait before sending status
+	uint8_t  watchdog:7;                        // Watchdog timeout, seconds
+	uint8_t  disable_sensors:1;                 // Diagnostic
+
+	uint8_t  rx_header_timeout:7;               // Header timeout in char times
+	uint8_t  rx_ignore_header_crc:1;            // Ignore rx header crc's (diagnostic)
+	uint8_t  rx_data_timeout:7;                 // Data timeout in char times / 16
+	uint8_t  rx_ignore_data_crc:1;              // Ignore rx data crc's (diagnostic)
+	uint8_t  stats_interval:7;                  // Minimum interval to report statistics (seconds)
+	uint8_t  stat_diagnostic:1;                 // Never set this
+	uint8_t  measure_interval;                  // Die temperature measurement interval (msec)
+
+	uint32_t one_usec:12;                       // How many LF clocks per usec.
+	uint32_t max_nonces_per_frame:4;            // Maximum # of nonces to combine in a single frame
+	uint32_t voltage_sample_points:8;           // Bit mask for sample points (up to 5 bits set)
+	uint32_t pwm_phases:2;                      // phases - 1
+	uint32_t trim:4;                            // Trim value for temperature measurements
+	uint32_t clock_diagnostic:1;                // Never set this
+	uint32_t forward_all_packets:1;             // Forward everything - diagnostic.
+
+	uint16_t pwm_period;                        // Period of PWM outputs, in reference clock cycles
+	uint16_t pwm_pulse_period;                  // Initial count, phase 0
+} __attribute__((packed,aligned(4)));
+
+// OP_GROUP data
+struct hf_group_data {
+	uint16_t nonce_msoffset;                    // This value << 16 added to starting nonce
+	uint16_t ntime_offset;                      // This value added to timestamp
+} __attribute__((packed,aligned(4)));
+
+// Structure of the monitor fields for G-1, returned in OP_STATUS, core bitmap follows this
+struct hf_g1_monitor { 
+	uint16_t die_temperature;                   // Die temperature ADC count
+	uint8_t  core_voltage[6];                   // Core voltage
+						// [0] = main sensor
+						// [1]-[5] = other positions
+} __attribute__((packed,aligned(4)));
+
+// What comes back in the body of an OP_STATISTICS frame (On die statistics)
+struct hf_statistics {
+	uint8_t rx_header_crc;                      // Header CRC error's
+	uint8_t rx_body_crc;                        // Data CRC error's
+	uint8_t rx_header_timeouts;                 // Header timeouts
+	uint8_t rx_body_timeouts;                   // Data timeouts
+	uint8_t core_nonce_fifo_full;               // Core nonce Q overrun events
+	uint8_t array_nonce_fifo_full;              // System nonce Q overrun events
+	uint8_t stats_overrun;                      // Overrun in statistics reporting
+	uint8_t spare;
+} __attribute__((packed,aligned(4)));
+
+
+////////////////////////////////////////////////////////////////////////////////
+// USB protocol data structures
+////////////////////////////////////////////////////////////////////////////////
+
+// Convenience header specific to OP_USB_INIT
+struct hf_usb_init_header {
+	uint8_t  preamble;                      // Always 0xaa
+	uint8_t  operation_code;
+	uint8_t  spare1;
+
+	uint8_t  protocol:3;                    // Which protocol to use
+	uint8_t  user_configuration:1;          // Use the following configuration data
+	uint8_t  pll_bypass:1;                  // Force PLL bypass, hash clock = ref clock
+	uint8_t  no_asic_initialization:1;      // Do not perform automatic ASIC initialization
+	uint8_t  do_atspeed_core_tests:1;       // Do core tests at speed, return second bitmap
+	uint8_t  leave_powered_down:1;          // Init USB only, leave device powered down
+
+	uint16_t hash_clock;                    // Requested hash clock frequency
+
+	uint8_t  data_length;                   // .. of data frame to follow, in 4 byte blocks
+	uint8_t  crc8;                          // Computed across bytes 1-6 inclusive
+} __attribute__((packed,aligned(4)));           // 8 bytes total
+
+// Options (only if present) that may be appended to the above header
+// Each option involving a numerical value will only be in effect if the value is non-zero
+// This allows the user to select only those options desired for modification. Do not
+// use this facility unless you are an expert - loading inconsistent settings will not work.
+struct hf_usb_init_options {
+	uint16_t group_ntime_roll;                  // Total ntime roll amount per group
+	uint16_t core_ntime_roll;                   // Total core ntime roll amount
+	uint8_t  low_operating_temp_limit;          // Lowest normal operating limit
+	uint8_t  high_operating_temp_limit;         // Highest normal operating limit
+	uint16_t spare;
+} __attribute__((packed,aligned(4)));
+
+// Base item returned from device for OP_USB_INIT
+struct hf_usb_init_base { 
+	uint16_t firmware_rev;                      // Firmware revision #
+	uint16_t hardware_rev;                      // Hardware revision #
+	uint32_t serial_number;                     // Board serial number
+	uint8_t  operation_status;                  // Reply status for OP_USB_INIT (0 = success)
+	uint8_t  extra_status_1;                    // Extra reply status information, code specific
+	uint16_t sequence_modulus;                  // Sequence numbers are to be modulo this
+	uint16_t hash_clockrate;                    // Actual hash clock rate used (nearest Mhz)
+	uint16_t inflight_target;                   // Target inflight amount for GWQ protocol
+} __attribute__((packed,aligned(4)));
+
+// The above base item (16 bytes) is followed by the struct hf_config_data (16 bytes) actually
+// used internally (so users may modify non-critical fields by doing subsequent
+// OP_CONFIG operations). This is followed by a device specific "core good" bitmap (unless the
+// user disabled initialization), and optionally by an at-speed "core good" bitmap.
+
+
+// Information in an OP_DIE_STATUS frame. This is for one die - there are four per ASIC.
+// Board level phase current and voltage sensors are likely to disappear in later production models.
+struct hf_g1_die_data {
+	struct hf_g1_monitor die;                   // Die sensors - 8 bytes
+	uint16_t phase_currents[4];                 // Phase currents (0 if unavailable)
+	uint16_t voltage;                           // Voltage at device boundary (0 if unavailable)
+	uint16_t temperature;                       // Regulator temp sensor
+	uint16_t tacho;                             // See documentation
+	uint16_t spare;
+} __attribute__((packed,aligned(4)));               // 24 bytes total
+
+
+// Information for an OP_GWQ_STATUS frame
+// If sequence_head == sequence_tail, then there is no active work and sequence_head is invalid
+struct hf_gwq_data {
+	uint64_t hash_count;                        // Add this to host's cumulative hash count
+	uint16_t sequence_head;                     // The latest, internal, active sequence #
+	uint16_t sequence_tail;                     // The latest, internal, inactive sequence #
+	uint16_t shed_count;                        // # of cores have been shedded for thermal control
+	uint16_t spare;
+} __attribute__((packed,aligned(4)));
+
+
+// Information for an OP_USB_STATS1 frame - Communication statistics
+struct hf_usb_stats1 {
+	// USB incoming
+	uint16_t usb_rx_preambles;
+	uint16_t usb_rx_receive_byte_errors;
+	uint16_t usb_rx_bad_hcrc;
+
+	// USB outgoing
+	uint16_t usb_tx_attempts;
+	uint16_t usb_tx_packets;
+	uint16_t usb_tx_timeouts;
+	uint16_t usb_tx_incompletes;
+	uint16_t usb_tx_endpointstalled;
+	uint16_t usb_tx_disconnected;
+	uint16_t usb_tx_suspended;
+
+	// Internal UART transmit
+	uint16_t uart_tx_queue_dma;
+	uint16_t uart_tx_interrupts;
+
+	// Internal UART receive
+	uint16_t uart_rx_preamble_ints;
+	uint16_t uart_rx_missed_preamble_ints;
+	uint16_t uart_rx_header_done;
+	uint16_t uart_rx_data_done;
+	uint16_t uart_rx_bad_hcrc;
+	//uint16_t uart_rx_bad_crc32;
+	uint16_t uart_rx_bad_dma;
+	uint16_t uart_rx_short_dma;
+	uint16_t uart_rx_buffers_full;
+
+	uint8_t  max_tx_buffers;                        // Maximum # of send buffers ever used
+	uint8_t  max_rx_buffers;                        // Maximum # of receive buffers ever used
+} __attribute__((packed,aligned(4)));
+
+// Information for an OP_USB_NOTICE frame
+struct hf_usb_notice_data {
+	uint32_t extra_data;                        // Depends on notification code
+	char     message[];                         // NULL terminated, little endian byte order
+};
+#endif
+
+#endif
diff --git a/hf_protocol_be.h b/hf_protocol_be.h
new file mode 100644
index 0000000..20a9e89
--- /dev/null
+++ b/hf_protocol_be.h
@@ -0,0 +1,267 @@
+//
+// Copyright 2013 HashFast LLC
+//
+// 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.
+//
+// Big endian versions of packed structures
+//
+// Version 1.0
+//
+
+#ifndef _HF_PROTOCOL_BE_H_
+#define _HF_PROTOCOL_BE_H_
+
+// Generic header
+struct hf_header {
+	uint8_t  preamble;                      // Always 0xaa
+	uint8_t  operation_code;
+	uint8_t  chip_address;
+	uint8_t  core_address;
+	uint16_t hdata;                         // Header specific data
+	uint8_t  data_length;                   // .. of data frame to follow, in 4 byte blocks, 0=no data
+	uint8_t  crc8;                          // Computed across bytes 1-6 inclusive
+} __attribute__((packed,aligned(4)));           // 8 bytes total
+
+// Header specific to OP_PLL_CONFIG
+struct hf_pll_config {
+	uint8_t  preamble;
+	uint8_t  operation_code;
+	uint8_t  chip_address;
+
+	uint8_t  pll_reset:1;
+	uint8_t  pll_bypass:1;
+	uint8_t  pll_divr:6;
+
+	uint8_t  pll_divf;
+
+	uint8_t  pll_fse:1;                     // Must always be 1
+	uint8_t  pll_range:3;
+	uint8_t  pll_divq:3;
+	uint8_t  spare1:1;                      // Must always be 0
+
+	uint8_t  data_length;                   // Always 0
+	uint8_t  crc8;                          // Computed across bytes 1-6 inclusive
+} __attribute__((packed,aligned(4)));           // 8 bytes total
+
+// OP_HASH serial data
+struct hf_hash_serial {
+	uint8_t  midstate[32];                  // Computed from first half of block header
+	uint8_t  merkle_residual[4];            // From block header
+	uint32_t timestamp;                     // From block header
+	uint32_t bits;                          // Actual difficulty target for block header
+	uint32_t starting_nonce;                // Usually set to 0
+	uint32_t nonce_loops;                   // How many nonces to search, or 0 for 2^32
+	uint16_t ntime_loops;                   // How many times to roll timestamp, or 0
+	uint8_t  search_difficulty;             // Search difficulty to use, # of '0' digits required
+	uint8_t  option;
+	uint8_t  group;
+	uint8_t  spare3[3];
+} __attribute__((packed,aligned(4)));
+
+// OP_HASH usb data - header+data = 64 bytes
+struct hf_hash_usb {
+	uint8_t  midstate[32];                  // Computed from first half of block header
+	uint8_t  merkle_residual[4];            // From block header
+	uint32_t timestamp;                     // From block header
+	uint32_t bits;                          // Actual difficulty target for block header
+	uint32_t starting_nonce;                // Usually set to 0
+	uint32_t nonce_loops;                   // How many nonces to search, or 0 for 2^32
+	uint16_t ntime_loops;                   // How many times to roll timestamp, or 0
+	uint8_t  search_difficulty;             // Search difficulty to use, # of '0' digits required
+	uint8_t  group;                         // Non-zero for valid group
+} __attribute__((packed,aligned(4)));
+
+// OP_NONCE data
+struct hf_candidate_nonce {
+	uint32_t nonce;                         // Candidate nonce
+	uint16_t sequence;                      // Sequence number from corresponding OP_HASH
+	uint16_t ntime;                         // ntime offset, if ntime roll occurred, in LS 12 bits
+						// If b12 set, search forward next 128 nonces to find solution(s)
+} __attribute__((packed,aligned(4)));
+
+// OP_CONFIG data
+// This is usually internal data only, for serial drivers only
+// Users shouldn't normally need to interpret this, but in the event a Big Endian
+// user requires access to this data, the following structure will get all
+// the fields in the right place, but byte swaps will be required for the
+// uint16_t's and the uint32_t.
+struct hf_config_data {
+	uint16_t forward_all_privileged_packets:1;  // Forward priv pkts -- diagnostic
+	uint16_t pwm_active_level:1;                // Active level of PWM outputs, if used
+	uint16_t send_status_on_pending_empty:1;    // Schedule status whenever core pending goes idle
+	uint16_t send_status_on_core_idle:1;        // Schedule status whenever core goes idle
+	uint16_t enable_periodic_status:1;          // Send periodic status
+	uint16_t status_period:11;                  // Periodic status time, msec
+
+	uint8_t  status_batch_delay;                // Batching delay, time to wait before sending status
+	uint8_t  disable_sensors:1;                 // Diagnostic
+	uint8_t  watchdog:7;                        // Watchdog timeout, seconds
+
+	uint8_t  rx_ignore_header_crc:1;            // Ignore rx header crc's (diagnostic)
+	uint8_t  rx_header_timeout:7;               // Header timeout in char times
+	uint8_t  rx_ignore_data_crc:1;              // Ignore rx data crc's (diagnostic)
+	uint8_t  rx_data_timeout:7;                 // Data timeout in char times / 16
+	uint8_t  stat_diagnostic:1;                 // Never set this
+	uint8_t  stats_interval:7;                  // Minimum interval to report statistics (seconds)
+	uint8_t  measure_interval;                  // Die temperature measurement interval (msec)
+
+	uint32_t forward_all_packets:1;             // Forward everything - diagnostic.
+	uint32_t clock_diagnostic:1;                // Never set this
+	uint32_t trim:4;                            // Trim value for temperature measurements
+	uint32_t pwm_phases:2;                      // phases - 1
+	uint32_t voltage_sample_points:8;           // Bit mask for sample points (up to 5 bits set)
+	uint32_t max_nonces_per_frame:4;            // Maximum # of nonces to combine in a single frame
+	uint32_t one_usec:12;                       // How many LF clocks per usec.
+
+	uint16_t pwm_period;                        // Period of PWM outputs, in reference clock cycles
+	uint16_t pwm_pulse_period;                  // Initial count, phase 0
+} __attribute__((packed,aligned(4)));
+
+// OP_GROUP data
+struct hf_group_data {
+	uint16_t nonce_msoffset;                    // This value << 16 added to starting nonce
+	uint16_t ntime_offset;                      // This value added to timestamp
+} __attribute__((packed,aligned(4)));
+
+// Structure of the monitor fields for G-1, returned in OP_STATUS, core bitmap follows this
+struct hf_g1_monitor { 
+	uint16_t die_temperature;                   // Die temperature ADC count
+	uint8_t  core_voltage[6];                   // Core voltage
+						// [0] = main sensor
+						// [1]-[5] = other positions
+} __attribute__((packed,aligned(4)));
+
+// What comes back in the body of an OP_STATISTICS frame (On die statistics)
+struct hf_statistics {
+	uint8_t rx_header_crc;                      // Header CRC error's
+	uint8_t rx_body_crc;                        // Data CRC error's
+	uint8_t rx_header_timeouts;                 // Header timeouts
+	uint8_t rx_body_timeouts;                   // Data timeouts
+	uint8_t core_nonce_fifo_full;               // Core nonce Q overrun events
+	uint8_t array_nonce_fifo_full;              // System nonce Q overrun events
+	uint8_t stats_overrun;                      // Overrun in statistics reporting
+	uint8_t spare;
+} __attribute__((packed,aligned(4)));
+
+
+////////////////////////////////////////////////////////////////////////////////
+// USB protocol data structures
+////////////////////////////////////////////////////////////////////////////////
+
+// Convenience header specific to OP_USB_INIT
+struct hf_usb_init_header {
+	uint8_t  preamble;                      // Always 0xaa
+	uint8_t  operation_code;
+	uint8_t  spare1;
+
+	uint8_t  leave_powered_down:1;          // Init USB only, leave device powered down
+	uint8_t  do_atspeed_core_tests:1;       // Do core tests at speed, return second bitmap
+	uint8_t  no_asic_initialization:1;      // Do not perform automatic ASIC initialization
+	uint8_t  pll_bypass:1;                  // Force PLL bypass, hash clock = ref clock
+	uint8_t  user_configuration:1;          // Use the following configuration data
+	uint8_t  protocol:3;                    // Which protocol to use
+
+	uint16_t hash_clock;                    // Requested hash clock frequency
+
+	uint8_t  data_length;                   // .. of data frame to follow, in 4 byte blocks
+	uint8_t  crc8;                          // Computed across bytes 1-6 inclusive
+} __attribute__((packed,aligned(4)));           // 8 bytes total
+
+// Options (only if present) that may be appended to the above header
+// Each option involving a numerical value will only be in effect if the value is non-zero
+// This allows the user to select only those options desired for modification. Do not
+// use this facility unless you are an expert - loading inconsistent settings will not work.
+struct hf_usb_init_options {
+	uint16_t group_ntime_roll;                  // Total ntime roll amount per group
+	uint16_t core_ntime_roll;                   // Total core ntime roll amount
+	uint8_t  low_operating_temp_limit;          // Lowest normal operating limit
+	uint8_t  high_operating_temp_limit;         // Highest normal operating limit
+	uint16_t spare;
+} __attribute__((packed,aligned(4)));
+
+// Base item returned from device for OP_USB_INIT
+struct hf_usb_init_base { 
+	uint16_t firmware_rev;                      // Firmware revision #
+	uint16_t hardware_rev;                      // Hardware revision #
+	uint32_t serial_number;                     // Board serial number
+	uint8_t  operation_status;                  // Reply status for OP_USB_INIT (0 = success)
+	uint8_t  extra_status_1;                    // Extra reply status information, code specific
+	uint16_t sequence_modulus;                  // Sequence numbers are to be modulo this
+	uint16_t hash_clockrate;                    // Actual hash clock rate used (nearest Mhz)
+	uint16_t inflight_target;                   // Target inflight amount for GWQ protocol
+} __attribute__((packed,aligned(4)));
+
+// The above base item (16 bytes) is followed by the struct hf_config_data (16 bytes) actually
+// used internally (so users may modify non-critical fields by doing subsequent
+// OP_CONFIG operations). This is followed by a device specific "core good" bitmap (unless the
+// user disabled initialization), and optionally by an at-speed "core good" bitmap.
+
+
+// Information in an OP_DIE_STATUS frame. This is for one die - there are four per ASIC.
+// Board level phase current and voltage sensors are likely to disappear in later production models.
+struct hf_g1_die_data {
+	struct hf_g1_monitor die;                   // Die sensors - 8 bytes
+	uint16_t phase_currents[4];                 // Phase currents (0 if unavailable)
+	uint16_t voltage;                           // Voltage at device boundary (0 if unavailable)
+	uint16_t temperature;                       // Regulator temp sensor
+	uint16_t tacho;                             // See documentation
+	uint16_t spare;
+} __attribute__((packed,aligned(4)));               // 24 bytes total
+
+// Information for an OP_GWQ_STATUS frame
+// If sequence_head == sequence_tail, then there is no active work and sequence_head is invalid
+struct hf_gwq_data {
+	uint64_t hash_count;                        // Add this to host's cumulative hash count
+	uint16_t sequence_head;                     // The latest, internal, active sequence #
+	uint16_t sequence_tail;                     // The latest, internal, inactive sequence #
+	uint16_t shed_count;                        // # of cores have been shedded for thermal control
+	uint16_t spare;
+} __attribute__((packed,aligned(4)));
+
+
+// Information for an OP_USB_STATS1 frame - Communication statistics
+struct hf_usb_stats1 {
+	// USB incoming
+	uint16_t usb_rx_preambles;
+	uint16_t usb_rx_receive_byte_errors;
+	uint16_t usb_rx_bad_hcrc;
+
+	// USB outgoing
+	uint16_t usb_tx_attempts;
+	uint16_t usb_tx_packets;
+	uint16_t usb_tx_timeouts;
+	uint16_t usb_tx_incompletes;
+	uint16_t usb_tx_endpointstalled;
+	uint16_t usb_tx_disconnected;
+	uint16_t usb_tx_suspended;
+
+	// Internal UART transmit
+	uint16_t uart_tx_queue_dma;
+	uint16_t uart_tx_interrupts;
+
+	// Internal UART receive
+	uint16_t uart_rx_preamble_ints;
+	uint16_t uart_rx_missed_preamble_ints;
+	uint16_t uart_rx_header_done;
+	uint16_t uart_rx_data_done;
+	uint16_t uart_rx_bad_hcrc;
+	//uint16_t uart_rx_bad_crc32;
+	uint16_t uart_rx_bad_dma;
+	uint16_t uart_rx_short_dma;
+	uint16_t uart_rx_buffers_full;
+
+	uint8_t  max_tx_buffers;                        // Maximum # of send buffers ever used
+	uint8_t  max_rx_buffers;                        // Maximum # of receive buffers ever used
+	} __attribute__((packed,aligned(4)));
+
+// Information for an OP_USB_NOTICE frame
+struct hf_usb_notice_data {
+	uint32_t extra_data;                        // Depends on notification code
+	char     message[];                         // NULL terminated, little endian byte order
+};
+
+
+#endif
diff --git a/miner.h b/miner.h
index 576a9c9..1f5eef1 100644
--- a/miner.h
+++ b/miner.h
@@ -173,7 +173,9 @@ static inline int fsync (int fd)
 # if __BYTE_ORDER == __LITTLE_ENDIAN
 #  define htole16(x) (x)
 #  define htole32(x) (x)
+#  define htole64(x) (x)
 #  define le32toh(x) (x)
+#  define le64toh(x) (x)
 #  define be32toh(x) bswap_32(x)
 #  define be64toh(x) bswap_64(x)
 #  define htobe32(x) bswap_32(x)
@@ -182,6 +184,8 @@ static inline int fsync (int fd)
 #  define htole16(x) bswap_16(x)
 #  define htole32(x) bswap_32(x)
 #  define le32toh(x) bswap_32(x)
+#  define le64toh(x) bswap_64(x)
+#  define htole64(x) bswap_64(x)
 #  define be32toh(x) (x)
 #  define be64toh(x) (x)
 #  define htobe32(x) (x)
@@ -223,8 +227,12 @@ static inline int fsync (int fd)
 #define semtimedop(SEM, SOPS, VAL, TIMEOUT) semop(SEM, SOPS, VAL)
 #endif
 
+#ifndef MIN
 #define MIN(x, y)	((x) > (y) ? (y) : (x))
+#endif
+#ifndef MAX
 #define MAX(x, y)	((x) > (y) ? (x) : (y))
+#endif
 
 /* Put avalon last to make it the last device it tries to detect to prevent it
  * trying to claim same chip but different devices. Adding a device here will
@@ -238,9 +246,11 @@ static inline int fsync (int fd)
 #define ASIC_PARSE_COMMANDS(DRIVER_ADD_COMMAND) \
 	DRIVER_ADD_COMMAND(bflsc) \
 	DRIVER_ADD_COMMAND(bitfury) \
-	DRIVER_ADD_COMMAND(avalon) \
+	DRIVER_ADD_COMMAND(hashfast) \
 	DRIVER_ADD_COMMAND(klondike) \
-        DRIVER_ADD_COMMAND(drillbit)
+	DRIVER_ADD_COMMAND(knc) \
+	DRIVER_ADD_COMMAND(drillbit) \
+	DRIVER_ADD_COMMAND(avalon)
 
 #define DRIVER_PARSE_COMMANDS(DRIVER_ADD_COMMAND) \
 	DRIVER_ADD_COMMAND(opencl) \
@@ -789,6 +799,7 @@ extern void api_initlock(void *lock, enum cglock_typ typ, const char *file, cons
 #define mutex_unlock(_lock) _mutex_unlock(_lock, __FILE__, __func__, __LINE__)
 #define mutex_trylock(_lock) _mutex_trylock(_lock, __FILE__, __func__, __LINE__)
 #define wr_lock(_lock) _wr_lock(_lock, __FILE__, __func__, __LINE__)
+#define wr_trylock(_lock) _wr_trylock(_lock, __FILE__, __func__, __LINE__)
 #define rd_lock(_lock) _rd_lock(_lock, __FILE__, __func__, __LINE__)
 #define rw_unlock(_lock) _rw_unlock(_lock, __FILE__, __func__, __LINE__)
 #define rd_unlock_noyield(_lock) _rd_unlock_noyield(_lock, __FILE__, __func__, __LINE__)
@@ -846,6 +857,14 @@ static inline void _wr_lock(pthread_rwlock_t *lock, const char *file, const char
 	GOTLOCK(lock, file, func, line);
 }
 
+static inline int _wr_trylock(pthread_rwlock_t *lock, __maybe_unused const char *file, __maybe_unused const char *func, __maybe_unused const int line)
+{
+	TRYLOCK(lock, file, func, line);
+	int ret = pthread_rwlock_trywrlock(lock);
+	DIDLOCK(ret, lock, file, func, line);
+	return ret;
+}
+
 static inline void _rd_lock(pthread_rwlock_t *lock, const char *file, const char *func, const int line)
 {
 	GETLOCK(lock, file, func, line);
@@ -1023,6 +1042,7 @@ extern char *opt_icarus_timing;
 extern bool opt_worktime;
 #ifdef USE_AVALON
 extern char *opt_avalon_options;
+extern char *opt_bitburner_fury_options;
 #endif
 #ifdef USE_KLONDIKE
 extern char *opt_klondike_options;
@@ -1180,7 +1200,7 @@ extern unsigned int total_go, total_ro;
 extern const int opt_cutofftemp;
 extern int opt_log_interval;
 extern unsigned long long global_hashrate;
-extern char *current_fullhash;
+extern char current_hash[68];
 extern double current_diff;
 extern uint64_t best_diff;
 extern struct timeval block_timeval;
@@ -1264,6 +1284,7 @@ struct pool {
 	int quota;
 	int quota_gcd;
 	int quota_used;
+	int works;
 
 	double diff_accepted;
 	double diff_rejected;
@@ -1319,6 +1340,9 @@ struct pool {
 	struct cgminer_stats cgminer_stats;
 	struct cgminer_pool_stats cgminer_pool_stats;
 
+	/* The last block this particular pool knows about */
+	char prev_block[32];
+
 	/* Stratum variables */
 	char *stratum_url;
 	char *stratum_port;
@@ -1390,7 +1414,6 @@ struct work {
 #endif
 	double		device_diff;
 	uint64_t	share_diff;
-	unsigned char	hash2[32];
 
 	int		rolls;
 	int		drv_rolllimit; /* How much the driver can roll ntime */
@@ -1487,6 +1510,7 @@ struct modminer_fpga_state {
 extern void get_datestamp(char *, size_t, struct timeval *);
 extern void inc_hw_errors(struct thr_info *thr);
 extern bool test_nonce(struct work *work, uint32_t nonce);
+extern bool test_nonce_diff(struct work *work, uint32_t nonce, double diff);
 extern void submit_tested_work(struct thr_info *thr, struct work *work);
 extern bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce);
 extern bool submit_noffset_nonce(struct thr_info *thr, struct work *work, uint32_t nonce,
@@ -1528,7 +1552,8 @@ extern void adl(void);
 extern void app_restart(void);
 extern void clean_work(struct work *work);
 extern void free_work(struct work *work);
-extern struct work *copy_work(struct work *base_work);
+extern struct work *copy_work_noffset(struct work *base_work, int noffset);
+#define copy_work(work_in) copy_work_noffset(work_in, 0)
 extern struct thr_info *get_thread(int thr_id);
 extern struct cgpu_info *get_devices(int id);
 
@@ -1536,6 +1561,8 @@ enum api_data_type {
 	API_ESCAPE,
 	API_STRING,
 	API_CONST,
+	API_UINT8,
+	API_UINT16,
 	API_INT,
 	API_UINT,
 	API_UINT32,
@@ -1568,6 +1595,8 @@ struct api_data {
 extern struct api_data *api_add_escape(struct api_data *root, char *name, char *data, bool copy_data);
 extern struct api_data *api_add_string(struct api_data *root, char *name, char *data, bool copy_data);
 extern struct api_data *api_add_const(struct api_data *root, char *name, const char *data, bool copy_data);
+extern struct api_data *api_add_uint8(struct api_data *root, char *name, uint8_t *data, bool copy_data);
+extern struct api_data *api_add_uint16(struct api_data *root, char *name, uint16_t *data, bool copy_data);
 extern struct api_data *api_add_int(struct api_data *root, char *name, int *data, bool copy_data);
 extern struct api_data *api_add_uint(struct api_data *root, char *name, unsigned int *data, bool copy_data);
 extern struct api_data *api_add_uint32(struct api_data *root, char *name, uint32_t *data, bool copy_data);
diff --git a/usbutils.c b/usbutils.c
index 96663a2..e3181b3 100644
--- a/usbutils.c
+++ b/usbutils.c
@@ -68,6 +68,7 @@
 #define AVALON_TIMEOUT_MS 999
 #define KLONDIKE_TIMEOUT_MS 999
 #define ICARUS_TIMEOUT_MS 999
+#define HASHFAST_TIMEOUT_MS 999
 #else
 #define BFLSC_TIMEOUT_MS 300
 #define BITFORCE_TIMEOUT_MS 200
@@ -77,6 +78,7 @@
 #define AVALON_TIMEOUT_MS 200
 #define KLONDIKE_TIMEOUT_MS 200
 #define ICARUS_TIMEOUT_MS 200
+#define HASHFAST_TIMEOUT_MS 200
 #endif
 
 #define USB_READ_MINPOLL 40
@@ -103,8 +105,8 @@ static struct list_head ut_list;
 #ifdef USE_BFLSC
 // N.B. transfer size is 512 with USB2.0, but only 64 with USB1.1
 static struct usb_epinfo bas_epinfos[] = {
-	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(1), 0, 0, 0 },
-	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(2), 0, 0, 0 }
+	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(1), 0, 0 },
+	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(2), 0, 0 }
 };
 
 static struct usb_intinfo bas_ints[] = {
@@ -115,8 +117,8 @@ static struct usb_intinfo bas_ints[] = {
 #ifdef USE_BITFORCE
 // N.B. transfer size is 512 with USB2.0, but only 64 with USB1.1
 static struct usb_epinfo bfl_epinfos[] = {
-	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(1), 0, 0, 0 },
-	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(2), 0, 0, 0 }
+	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(1), 0, 0 },
+	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(2), 0, 0 }
 };
 
 static struct usb_intinfo bfl_ints[] = {
@@ -125,14 +127,13 @@ static struct usb_intinfo bfl_ints[] = {
 #endif
 
 #ifdef USE_BITFURY
-// Bitfury BF1
-static struct usb_epinfo bf1_int_epinfos[] = {
-	{ LIBUSB_TRANSFER_TYPE_INTERRUPT,	8,	EPI(2), 0, 0, 0 }
+static struct usb_epinfo bfu0_epinfos[] = {
+	{ LIBUSB_TRANSFER_TYPE_INTERRUPT,	8,	EPI(2), 0, 0 }
 };
 
-static struct usb_epinfo bf1_bulk_epinfos[] = {
-	{ LIBUSB_TRANSFER_TYPE_BULK,	16,	EPI(3), 0, 0, 0 },
-	{ LIBUSB_TRANSFER_TYPE_BULK,	16,	EPO(4), 0, 0, 0 }
+static struct usb_epinfo bfu1_epinfos[] = {
+	{ LIBUSB_TRANSFER_TYPE_BULK,	16,	EPI(3), 0, 0 },
+	{ LIBUSB_TRANSFER_TYPE_BULK,	16,	EPO(4), 0, 0 }
 };
 
 /* Default to interface 1 */
@@ -145,12 +146,12 @@ static struct usb_intinfo bf1_ints[] = {
 #ifdef USE_DRILLBIT
 // Drillbit Bitfury devices
 static struct usb_epinfo drillbit_int_epinfos[] = {
-	{ LIBUSB_TRANSFER_TYPE_INTERRUPT,	8,	EPI(3), 0, 0, 0 }
+	{ LIBUSB_TRANSFER_TYPE_INTERRUPT,	8,	EPI(3), 0, 0 }
 };
 
 static struct usb_epinfo drillbit_bulk_epinfos[] = {
-	{ LIBUSB_TRANSFER_TYPE_BULK,	16,	EPI(1), 0, 0, 0 },
-	{ LIBUSB_TRANSFER_TYPE_BULK,	16,	EPO(2), 0, 0, 0 }
+	{ LIBUSB_TRANSFER_TYPE_BULK,	16,	EPI(1), 0, 0 },
+	{ LIBUSB_TRANSFER_TYPE_BULK,	16,	EPO(2), 0, 0 },
 };
 
 /* Default to interface 1 */
@@ -160,10 +161,29 @@ static struct usb_intinfo drillbit_ints[] = {
 };
 #endif
 
+#ifdef USE_HASHFAST
+#include "driver-hashfast.h"
+
+static struct usb_epinfo hfa0_epinfos[] = {
+	{ LIBUSB_TRANSFER_TYPE_INTERRUPT,	8,	EPI(3), 0, 0 }
+};
+
+static struct usb_epinfo hfa1_epinfos[] = {
+	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(1), 0, 0 },
+	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(2), 0, 0 }
+};
+
+/* Default to interface 1 */
+static struct usb_intinfo hfa_ints[] = {
+	USB_EPS(1,  hfa1_epinfos),
+	USB_EPS(0,  hfa0_epinfos)
+};
+#endif
+
 #ifdef USE_MODMINER
 static struct usb_epinfo mmq_epinfos[] = {
-	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(3), 0, 0, 0 },
-	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(3), 0, 0, 0 }
+	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(3), 0, 0 },
+	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(3), 0, 0 }
 };
 
 static struct usb_intinfo mmq_ints[] = {
@@ -173,8 +193,8 @@ static struct usb_intinfo mmq_ints[] = {
 
 #ifdef USE_AVALON
 static struct usb_epinfo ava_epinfos[] = {
-	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(1), 0, 0, 0 },
-	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(2), 0, 0, 0 }
+	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(1), 0, 0 },
+	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(2), 0, 0 }
 };
 
 static struct usb_intinfo ava_ints[] = {
@@ -184,8 +204,8 @@ static struct usb_intinfo ava_ints[] = {
 
 #ifdef USE_KLONDIKE
 static struct usb_epinfo kln_epinfos[] = {
-	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(1), 0, 0, 0 },
-	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(1), 0, 0, 0 }
+	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(1), 0, 0 },
+	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(1), 0, 0 }
 };
 
 static struct usb_intinfo kln_ints[] = {
@@ -195,8 +215,8 @@ static struct usb_intinfo kln_ints[] = {
 
 #ifdef USE_ICARUS
 static struct usb_epinfo ica_epinfos[] = {
-	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(3), 0, 0, 0 },
-	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(2), 0, 0, 0 }
+	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(3), 0, 0 },
+	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(2), 0, 0 }
 };
 
 static struct usb_intinfo ica_ints[] = {
@@ -204,8 +224,8 @@ static struct usb_intinfo ica_ints[] = {
 };
 
 static struct usb_epinfo amu_epinfos[] = {
-	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(1), 0, 0, 0 },
-	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(1), 0, 0, 0 }
+	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(1), 0, 0 },
+	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(1), 0, 0 }
 };
 
 static struct usb_intinfo amu_ints[] = {
@@ -213,8 +233,8 @@ static struct usb_intinfo amu_ints[] = {
 };
 
 static struct usb_epinfo llt_epinfos[] = {
-	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(1), 0, 0, 0 },
-	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(2), 0, 0, 0 }
+	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(1), 0, 0 },
+	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(2), 0, 0 }
 };
 
 static struct usb_intinfo llt_ints[] = {
@@ -222,8 +242,8 @@ static struct usb_intinfo llt_ints[] = {
 };
 
 static struct usb_epinfo cmr1_epinfos[] = {
-	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(1), 0, 0, 0 },
-	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(2), 0, 0, 0 }
+	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(1), 0, 0 },
+	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(2), 0, 0 }
 };
 
 static struct usb_intinfo cmr1_ints[] = {
@@ -231,20 +251,20 @@ static struct usb_intinfo cmr1_ints[] = {
 };
 
 static struct usb_epinfo cmr2_epinfos0[] = {
-	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(1), 0, 0, 0 },
-	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(2), 0, 0, 0 }
+	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(1), 0, 0 },
+	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(2), 0, 0 }
 };
 static struct usb_epinfo cmr2_epinfos1[] = {
-	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(3), 0, 0, 0 },
-	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(4), 0, 0, 0 },
+	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(3), 0, 0 },
+	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(4), 0, 0 },
 };
 static struct usb_epinfo cmr2_epinfos2[] = {
-	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(5), 0, 0, 0 },
-	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(6), 0, 0, 0 },
+	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(5), 0, 0 },
+	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(6), 0, 0 },
 };
 static struct usb_epinfo cmr2_epinfos3[] = {
-	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(7), 0, 0, 0 },
-	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(8), 0, 0, 0 }
+	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(7), 0, 0 },
+	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(8), 0, 0 }
 };
 
 static struct usb_intinfo cmr2_ints[] = {
@@ -373,6 +393,20 @@ static struct usb_find_devices find_dev[] = {
 		.latency = 10,
 		INTINFO(ava_ints) },
 #endif
+#ifdef USE_HASHFAST
+	{
+		.drv = DRIVER_hashfast,
+		.name = "HFA",
+		.ident = IDENT_HFA,
+		.idVendor = HF_USB_VENDOR_ID,
+		.idProduct = HF_USB_PRODUCT_ID_G1,
+		.iManufacturer = "HashFast LLC",
+		.iProduct = "M1 Module",
+		.config = 1,
+		.timeout = HASHFAST_TIMEOUT_MS,
+		.latency = LATENCY_UNUSED,
+		INTINFO(hfa_ints) },
+#endif
 #ifdef USE_KLONDIKE
 	{
 		.drv = DRIVER_klondike,
@@ -467,6 +501,15 @@ static const char *nodatareturned = "no data returned ";
 			cgpu->usbinfo.continuous_ioerr_count = 0; \
 		}
 
+/* Timeout errors on writes are unusual and should be treated as IO errors. */
+#define WRITEIOERR_CHECK(cgpu, err) \
+		if (err == LIBUSB_ERROR_IO || err == LIBUSB_ERROR_TIMEOUT) { \
+			cgpu->usbinfo.ioerr_count++; \
+			cgpu->usbinfo.continuous_ioerr_count++; \
+		} else { \
+			cgpu->usbinfo.continuous_ioerr_count = 0; \
+		}
+
 #if 0 // enable USBDEBUG - only during development testing
  static const char *debug_true_str = "true";
  static const char *debug_false_str = "false";
@@ -1301,9 +1344,6 @@ static struct cg_usb_device *free_cgusb(struct cg_usb_device *cgusb)
 
 	free(cgusb->found);
 
-	if (cgusb->buffer)
-		free(cgusb->buffer);
-
 	free(cgusb);
 
 	return NULL;
@@ -1392,6 +1432,20 @@ static void release_cgpu(struct cgpu_info *cgpu)
 }
 
 /*
+ * Force a NODEV on a device so it goes back to hotplug
+ */
+void usb_nodev(struct cgpu_info *cgpu)
+{
+	int pstate;
+
+	DEVWLOCK(cgpu, pstate);
+
+	release_cgpu(cgpu);
+
+	DEVWUNLOCK(cgpu, pstate);
+}
+
+/*
  * Use the same usbdev thus locking is across all related devices
  */
 struct cgpu_info *usb_copy_cgpu(struct cgpu_info *orig)
@@ -1574,6 +1628,7 @@ static int _usb_init(struct cgpu_info *cgpu, struct libusb_device *dev, struct u
 		if (strcmp((char *)man, found->iManufacturer)) {
 			applog(LOG_DEBUG, "USB init, iManufacturer mismatch %s",
 			       devstr);
+			applog(LOG_DEBUG, "Found %s vs %s", man, found->iManufacturer);
 			bad = USB_INIT_IGNORE;
 			goto cldame;
 		}
@@ -1594,6 +1649,7 @@ static int _usb_init(struct cgpu_info *cgpu, struct libusb_device *dev, struct u
 		if (strcmp((char *)prod, found->iProduct)) {
 			applog(LOG_DEBUG, "USB init, iProduct mismatch %s",
 			       devstr);
+			applog(LOG_DEBUG, "Found %s vs %s", prod, found->iProduct);
 			bad = USB_INIT_IGNORE;
 			goto cldame;
 		}
@@ -2317,6 +2373,9 @@ static void LIBUSB_CALL transfer_callback(struct libusb_transfer *transfer)
 
 static int usb_transfer_toerr(int ret)
 {
+	if (ret <= 0)
+		return ret;
+
 	switch (ret) {
 		default:
 		case LIBUSB_TRANSFER_COMPLETED:
@@ -2390,15 +2449,24 @@ usb_bulk_transfer(struct libusb_device_handle *dev_handle, int intinfo,
 		  struct cgpu_info *cgpu, __maybe_unused int mode,
 		  enum usb_cmds cmd, __maybe_unused int seq, bool cancellable)
 {
+	int bulk_timeout, callback_timeout = timeout;
 	struct usb_epinfo *usb_epinfo;
 	struct usb_transfer ut;
 	unsigned char endpoint;
-	uint16_t MaxPacketSize;
 	int err, errn;
 #if DO_USB_STATS
 	struct timeval tv_start, tv_finish;
 #endif
 	unsigned char buf[512];
+#ifdef WIN32
+	/* On windows the callback_timeout is a safety mechanism only. */
+	bulk_timeout = timeout;
+	callback_timeout += timeout + cgpu->usbdev->found->timeout;
+#else
+	/* We give the transfer no timeout since we manage timeouts ourself on
+	 * non windows. */
+	bulk_timeout = 0;
+#endif
 
 	usb_epinfo = &(cgpu->usbdev->found->intinfos[intinfo].epinfos[epinfo]);
 	endpoint = usb_epinfo->ep;
@@ -2408,37 +2476,33 @@ usb_bulk_transfer(struct libusb_device_handle *dev_handle, int intinfo,
 	if (unlikely(cgpu->shutdown))
 		return libusb_bulk_transfer(dev_handle, endpoint, data, length, transferred, timeout);
 
-	/* Limit length of transfer to the largest this descriptor supports
-	 * and leave the higher level functions to transfer more if needed. */
-	if (usb_epinfo->PrefPacketSize)
-		MaxPacketSize = usb_epinfo->PrefPacketSize;
-	else
-		MaxPacketSize = usb_epinfo->wMaxPacketSize;
-	if (length > MaxPacketSize)
-		length = MaxPacketSize;
+	if (length > usb_epinfo->wMaxPacketSize)
+		length = usb_epinfo->wMaxPacketSize;
 	if ((endpoint & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_OUT)
 		memcpy(buf, data, length);
 
 	USBDEBUG("USB debug: @usb_bulk_transfer(%s (nodev=%s),intinfo=%d,epinfo=%d,data=%p,length=%d,timeout=%u,mode=%d,cmd=%s,seq=%d) endpoint=%d", cgpu->drv->name, bool_str(cgpu->usbinfo.nodev), intinfo, epinfo, data, length, timeout, mode, usb_cmdname(cmd), seq, (int)endpoint);
 
 	init_usb_transfer(&ut);
-	/* We give the transfer no timeout since we manage timeouts ourself */
 	libusb_fill_bulk_transfer(ut.transfer, dev_handle, endpoint, buf, length,
-				  transfer_callback, &ut, 0);
+				  transfer_callback, &ut, bulk_timeout);
 	STATS_TIMEVAL(&tv_start);
 	err = usb_submit_transfer(&ut, ut.transfer, cancellable);
 	errn = errno;
 	if (!err)
-		err = callback_wait(&ut, transferred, timeout);
+		err = callback_wait(&ut, transferred, callback_timeout);
+	else
+		err = usb_transfer_toerr(err);
 	complete_usb_transfer(&ut);
 
 	STATS_TIMEVAL(&tv_finish);
 	USB_STATS(cgpu, &tv_start, &tv_finish, err, mode, cmd, seq, timeout);
 
-	if (err < 0)
+	if (err < 0) {
 		applog(LOG_DEBUG, "%s%i: %s (amt=%d err=%d ern=%d)",
 				cgpu->drv->name, cgpu->device_id,
 				usb_cmdname(cmd), *transferred, err, errn);
+	}
 
 	if (err == LIBUSB_ERROR_PIPE) {
 		int retries = 0;
@@ -2457,12 +2521,12 @@ usb_bulk_transfer(struct libusb_device_handle *dev_handle, int intinfo,
 		} while (err && ++retries < USB_RETRY_MAX);
 	}
 	if ((endpoint & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_IN)
-		memcpy(data, buf, length);
+		memcpy(data, buf, *transferred);
 
 	return err;
 }
 
-int _usb_read(struct cgpu_info *cgpu, int intinfo, int epinfo, char *buf, size_t bufsiz, int *processed, unsigned int timeout, const char *end, enum usb_cmds cmd, bool readonce, bool cancellable)
+int _usb_read(struct cgpu_info *cgpu, int intinfo, int epinfo, char *buf, size_t bufsiz, int *processed, int timeout, const char *end, enum usb_cmds cmd, bool readonce, bool cancellable)
 {
 	struct cg_usb_device *usbdev;
 	bool ftdi;
@@ -2471,10 +2535,11 @@ int _usb_read(struct cgpu_info *cgpu, int intinfo, int epinfo, char *buf, size_t
 	double max, done;
 	int bufleft, err, got, tot, pstate;
 	bool first = true;
+	bool dobuffer;
 	char *search;
 	int endlen;
 	unsigned char *ptr, *usbbuf = cgpu->usbinfo.bulkbuf;
-	size_t usbbufread;
+	const size_t usbbufread = 512; /* Always read full size */
 
 	DEVRLOCK(cgpu, pstate);
 
@@ -2499,50 +2564,20 @@ int _usb_read(struct cgpu_info *cgpu, int intinfo, int epinfo, char *buf, size_t
 		timeout = usbdev->found->timeout;
 
 	if (end == NULL) {
-		if (usbdev->buffer && usbdev->bufamt) {
-			tot = usbdev->bufamt;
-			bufleft = bufsiz - tot;
+		tot = usbdev->bufamt;
+		bufleft = bufsiz - tot;
+		if (tot)
 			memcpy(usbbuf, usbdev->buffer, tot);
-			ptr = usbbuf + tot;
-			usbdev->bufamt = 0;
-		} else {
-			tot = 0;
-			bufleft = bufsiz;
-			ptr = usbbuf;
-		}
+		ptr = usbbuf + tot;
+		usbdev->bufamt = 0;
 
 		err = LIBUSB_SUCCESS;
 		initial_timeout = timeout;
 		max = ((double)timeout) / 1000.0;
 		cgtime(&read_start);
 		while (bufleft > 0) {
-			// TODO: use (USB_MAX_READ - tot) always?
-			if (usbdev->buffer)
-				usbbufread = USB_MAX_READ - tot;
-			else {
-				if (ftdi)
-					usbbufread = bufleft + 2;
-				else
-					usbbufread = bufleft;
-			}
 			got = 0;
 
-			if (first && usbdev->usecps && usbdev->last_write_siz) {
-				cgtimer_t now, already_done;
-				double sleep_estimate;
-				double write_time = (double)(usbdev->last_write_siz) /
-						    (double)(usbdev->cps);
-
-				cgtimer_time(&now);
-				cgtimer_sub(&now, &usbdev->cgt_last_write, &already_done);
-				sleep_estimate = write_time - cgtimer_to_ms(&already_done);
-
-				if (sleep_estimate > 0.0) {
-					cgsleep_ms_r(&usbdev->cgt_last_write, write_time * 1000.0);
-					cgpu->usbinfo.read_delay_count++;
-					cgpu->usbinfo.total_read_delay += sleep_estimate;
-				}
-			}
 			err = usb_bulk_transfer(usbdev->handle, intinfo, epinfo,
 						ptr, usbbufread, &got, timeout,
 						cgpu, MODE_BULK_READ, cmd, first ? SEQ0 : SEQ1,
@@ -2580,12 +2615,12 @@ int _usb_read(struct cgpu_info *cgpu, int intinfo, int epinfo, char *buf, size_t
 			if (unlikely(done >= max))
 				break;
 			timeout = initial_timeout - (done * 1000);
-			if (!timeout)
+			if (timeout <= 0)
 				break;
 		}
 
 		// N.B. usbdev->buffer was emptied before the while() loop
-		if (usbdev->buffer && tot > (int)bufsiz) {
+		if (tot > (int)bufsiz) {
 			usbdev->bufamt = tot - bufsiz;
 			memcpy(usbdev->buffer, usbbuf + bufsiz, usbdev->bufamt);
 			tot -= usbdev->bufamt;
@@ -2600,50 +2635,21 @@ int _usb_read(struct cgpu_info *cgpu, int intinfo, int epinfo, char *buf, size_t
 		goto out_unlock;
 	}
 
-	if (usbdev->buffer && usbdev->bufamt) {
-		tot = usbdev->bufamt;
-		bufleft = bufsiz - tot;
+	tot = usbdev->bufamt;
+	bufleft = bufsiz - tot;
+	if (tot)
 		memcpy(usbbuf, usbdev->buffer, tot);
-		ptr = usbbuf + tot;
-		usbdev->bufamt = 0;
-	} else {
-		tot = 0;
-		bufleft = bufsiz;
-		ptr = usbbuf;
-	}
+	ptr = usbbuf + tot;
+	usbdev->bufamt = 0;
 
 	endlen = strlen(end);
 	err = LIBUSB_SUCCESS;
 	initial_timeout = timeout;
 	max = ((double)timeout) / 1000.0;
 	cgtime(&read_start);
+
 	while (bufleft > 0) {
-		// TODO: use (USB_MAX_READ - tot) always?
-		if (usbdev->buffer)
-			usbbufread = USB_MAX_READ - tot;
-		else {
-			if (ftdi)
-				usbbufread = bufleft + 2;
-			else
-				usbbufread = bufleft;
-		}
 		got = 0;
-		if (first && usbdev->usecps && usbdev->last_write_siz) {
-			cgtimer_t now, already_done;
-			double sleep_estimate;
-			double write_time = (double)(usbdev->last_write_siz) /
-					    (double)(usbdev->cps);
-
-			cgtimer_time(&now);
-			cgtimer_sub(&now, &usbdev->cgt_last_write, &already_done);
-			sleep_estimate = write_time - cgtimer_to_ms(&already_done);
-
-			if (sleep_estimate > 0.0) {
-				cgsleep_ms_r(&usbdev->cgt_last_write, write_time * 1000.0);
-				cgpu->usbinfo.read_delay_count++;
-				cgpu->usbinfo.total_read_delay += sleep_estimate;
-			}
-		}
 		err = usb_bulk_transfer(usbdev->handle, intinfo, epinfo,
 					ptr, usbbufread, &got, timeout,
 					cgpu, MODE_BULK_READ, cmd, first ? SEQ0 : SEQ1,
@@ -2684,42 +2690,40 @@ int _usb_read(struct cgpu_info *cgpu, int intinfo, int epinfo, char *buf, size_t
 		if (unlikely(done >= max))
 			break;
 		timeout = initial_timeout - (done * 1000);
-		if (!timeout)
+		if (timeout <= 0)
 			break;
 	}
 
-	if (usbdev->buffer) {
-		bool dobuffer = false;
+	dobuffer = false;
 
-		if ((search = find_end(usbbuf, usbbuf, tot, tot, (char *)end, endlen, true))) {
-			// end finishes after bufsiz
-			if ((search + endlen - (char *)usbbuf) > (int)bufsiz) {
-				usbdev->bufamt = tot - bufsiz;
-				dobuffer = true;
-			} else {
-				// extra data after end
-				if (*(search + endlen)) {
-					usbdev->bufamt = tot - (search + endlen - (char *)usbbuf);
-					dobuffer = true;
-				}
-			}
+	if ((search = find_end(usbbuf, usbbuf, tot, tot, (char *)end, endlen, true))) {
+		// end finishes after bufsiz
+		if ((search + endlen - (char *)usbbuf) > (int)bufsiz) {
+			usbdev->bufamt = tot - bufsiz;
+			dobuffer = true;
 		} else {
-			// no end, but still bigger than bufsiz
-			if (tot > (int)bufsiz) {
-				usbdev->bufamt = tot - bufsiz;
+			// extra data after end
+			if (*(search + endlen)) {
+				usbdev->bufamt = tot - (search + endlen - (char *)usbbuf);
 				dobuffer = true;
 			}
 		}
-
-		if (dobuffer) {
-			tot -= usbdev->bufamt;
-			memcpy(usbdev->buffer, usbbuf + tot, usbdev->bufamt);
-			usbbuf[tot] = '\0';
-			applog(LOG_DEBUG, "USB: %s%i read2 buffering %d extra bytes",
-			       cgpu->drv->name, cgpu->device_id, usbdev->bufamt);
+	} else {
+		// no end, but still bigger than bufsiz
+		if (tot > (int)bufsiz) {
+			usbdev->bufamt = tot - bufsiz;
+			dobuffer = true;
 		}
 	}
 
+	if (dobuffer) {
+		tot -= usbdev->bufamt;
+		memcpy(usbdev->buffer, usbbuf + tot, usbdev->bufamt);
+		usbbuf[tot] = '\0';
+		applog(LOG_DEBUG, "USB: %s%i read2 buffering %d extra bytes",
+			cgpu->drv->name, cgpu->device_id, usbdev->bufamt);
+	}
+
 	*processed = tot;
 	memcpy((char *)buf, (const char *)usbbuf, (tot < (int)bufsiz) ? tot + 1 : (int)bufsiz);
 
@@ -2741,7 +2745,7 @@ out_noerrmsg:
 	return err;
 }
 
-int _usb_write(struct cgpu_info *cgpu, int intinfo, int epinfo, char *buf, size_t bufsiz, int *processed, unsigned int timeout, enum usb_cmds cmd)
+int _usb_write(struct cgpu_info *cgpu, int intinfo, int epinfo, char *buf, size_t bufsiz, int *processed, int timeout, enum usb_cmds cmd)
 {
 	struct cg_usb_device *usbdev;
 	struct timeval read_start, tv_finish;
@@ -2773,36 +2777,22 @@ int _usb_write(struct cgpu_info *cgpu, int intinfo, int epinfo, char *buf, size_
 	max = ((double)timeout) / 1000.0;
 	cgtime(&read_start);
 	while (bufsiz > 0) {
-		sent = 0;
+		int tosend = bufsiz;
+
 		if (usbdev->usecps) {
-			if (usbdev->last_write_siz) {
-				cgtimer_t now, already_done;
-				double sleep_estimate;
-				double write_time = (double)(usbdev->last_write_siz) /
-						    (double)(usbdev->cps);
-
-				cgtimer_time(&now);
-				cgtimer_sub(&now, &usbdev->cgt_last_write, &already_done);
-				sleep_estimate = write_time - cgtimer_to_ms(&already_done);
-
-				if (sleep_estimate > 0.0) {
-					cgsleep_ms_r(&usbdev->cgt_last_write, write_time * 1000.0);
-					cgpu->usbinfo.write_delay_count++;
-					cgpu->usbinfo.total_write_delay += sleep_estimate;
-				}
-			}
-			cgsleep_prepare_r(&usbdev->cgt_last_write);
-			usbdev->last_write_siz = bufsiz;
+			int cpms = usbdev->cps / 1000 ? : 1;
+			if (tosend > cpms)
+				tosend = cpms;
 		}
 		err = usb_bulk_transfer(usbdev->handle, intinfo, epinfo,
-					(unsigned char *)buf, bufsiz, &sent, timeout,
+					(unsigned char *)buf, tosend, &sent, timeout,
 					cgpu, MODE_BULK_WRITE, cmd, first ? SEQ0 : SEQ1,
 					false);
 		cgtime(&tv_finish);
 
 		USBDEBUG("USB debug: @_usb_write(%s (nodev=%s)) err=%d%s sent=%d", cgpu->drv->name, bool_str(cgpu->usbinfo.nodev), err, isnodev(err), sent);
 
-		IOERR_CHECK(cgpu, err);
+		WRITEIOERR_CHECK(cgpu, err);
 
 		tot += sent;
 
@@ -2819,7 +2809,7 @@ int _usb_write(struct cgpu_info *cgpu, int intinfo, int epinfo, char *buf, size_
 		if (unlikely(done >= max))
 			break;
 		timeout = initial_timeout - (done * 1000);
-		if (!timeout)
+		if (timeout <= 0)
 			break;
 	}
 
@@ -2913,26 +2903,6 @@ int __usb_transfer(struct cgpu_info *cgpu, uint8_t request_type, uint8_t bReques
 
 	USBDEBUG("USB debug: @_usb_transfer() buf=%s", bin2hex(buf, (size_t)siz));
 
-	if (usbdev->usecps) {
-		if (usbdev->last_write_siz) {
-			cgtimer_t now, already_done;
-			double sleep_estimate;
-			double write_time = (double)(usbdev->last_write_siz) /
-					    (double)(usbdev->cps);
-
-			cgtimer_time(&now);
-			cgtimer_sub(&now, &usbdev->cgt_last_write, &already_done);
-			sleep_estimate = write_time - cgtimer_to_ms(&already_done);
-
-			if (sleep_estimate > 0.0) {
-				cgsleep_ms_r(&usbdev->cgt_last_write, write_time * 1000.0);
-				cgpu->usbinfo.write_delay_count++;
-				cgpu->usbinfo.total_write_delay += sleep_estimate;
-			}
-		}
-		cgsleep_prepare_r(&usbdev->cgt_last_write);
-		usbdev->last_write_siz = siz;
-	}
 	STATS_TIMEVAL(&tv_start);
 	err = usb_control_transfer(cgpu, usbdev->handle, request_type, bRequest,
 				   wValue, wIndex, buf, (uint16_t)siz, timeout);
@@ -2941,7 +2911,7 @@ int __usb_transfer(struct cgpu_info *cgpu, uint8_t request_type, uint8_t bReques
 
 	USBDEBUG("USB debug: @_usb_transfer(%s (nodev=%s)) err=%d%s", cgpu->drv->name, bool_str(cgpu->usbinfo.nodev), err, isnodev(err));
 
-	IOERR_CHECK(cgpu, err);
+	WRITEIOERR_CHECK(cgpu, err);
 
 	if (err < 0 && err != LIBUSB_ERROR_TIMEOUT) {
 		applog(LOG_WARNING, "%s %i usb transfer err:(%d) %s", cgpu->drv->name, cgpu->device_id,
@@ -2996,28 +2966,10 @@ int _usb_transfer_read(struct cgpu_info *cgpu, uint8_t request_type, uint8_t bRe
 
 	*amount = 0;
 
-	if (usbdev->usecps && usbdev->last_write_siz) {
-		cgtimer_t now, already_done;
-		double sleep_estimate;
-		double write_time = (double)(usbdev->last_write_siz) /
-				    (double)(usbdev->cps);
-
-		cgtimer_time(&now);
-		cgtimer_sub(&now, &usbdev->cgt_last_write, &already_done);
-		sleep_estimate = write_time - cgtimer_to_ms(&already_done);
-
-		if (sleep_estimate > 0.0) {
-			cgsleep_ms_r(&usbdev->cgt_last_write, write_time * 1000.0);
-			cgpu->usbinfo.read_delay_count++;
-			cgpu->usbinfo.total_read_delay += sleep_estimate;
-		}
-	}
 	memset(tbuf, 0, 64);
 	STATS_TIMEVAL(&tv_start);
-	cg_rlock(&cgusb_fd_lock);
 	err = usb_control_transfer(cgpu, usbdev->handle, request_type, bRequest,
 				   wValue, wIndex, tbuf, (uint16_t)bufsiz, timeout);
-	cg_runlock(&cgusb_fd_lock);
 	STATS_TIMEVAL(&tv_finish);
 	USB_STATS(cgpu, &tv_start, &tv_finish, err, MODE_CTRL_READ, cmd, SEQ0, timeout);
 	memcpy(buf, tbuf, bufsiz);
@@ -3101,44 +3053,6 @@ int _usb_ftdi_set_latency(struct cgpu_info *cgpu, int intinfo)
 	return err;
 }
 
-void usb_buffer_enable(struct cgpu_info *cgpu)
-{
-	struct cg_usb_device *cgusb;
-	int pstate;
-
-	DEVWLOCK(cgpu, pstate);
-
-	cgusb = cgpu->usbdev;
-	if (cgusb && !cgusb->buffer) {
-		cgusb->bufamt = 0;
-		cgusb->buffer = malloc(USB_MAX_READ+1);
-		if (!cgusb->buffer)
-			quit(1, "Failed to malloc buffer for USB %s%i",
-				cgpu->drv->name, cgpu->device_id);
-		cgusb->bufsiz = USB_MAX_READ;
-	}
-
-	DEVWUNLOCK(cgpu, pstate);
-}
-
-void usb_buffer_disable(struct cgpu_info *cgpu)
-{
-	struct cg_usb_device *cgusb;
-	int pstate;
-
-	DEVWLOCK(cgpu, pstate);
-
-	cgusb = cgpu->usbdev;
-	if (cgusb && cgusb->buffer) {
-		cgusb->bufamt = 0;
-		cgusb->bufsiz = 0;
-		free(cgusb->buffer);
-		cgusb->buffer = NULL;
-	}
-
-	DEVWUNLOCK(cgpu, pstate);
-}
-
 void usb_buffer_clear(struct cgpu_info *cgpu)
 {
 	int pstate;
@@ -3239,40 +3153,6 @@ enum sub_ident usb_ident(struct cgpu_info *cgpu)
 	return ident;
 }
 
-/*
- * If you pass both intinfo and epinfo as <0 then it will set all
- * endpoints to PrefPacketSize
- * If intinfo >=0 but epinfo <0 then it will set all endpoints
- * for the given one intinfo to PrefPacketSize
- * If both are >=0 then it will set only the specified single
- * endpoint (intinfo,epinfo) to PrefPacketSize
- */
-void _usb_set_pps(struct cgpu_info *cgpu, int intinfo, int epinfo, uint16_t PrefPacketSize)
-{
-	struct usb_find_devices *found;
-	int pstate;
-
-	DEVWLOCK(cgpu, pstate);
-
-	if (cgpu->usbdev) {
-		found = cgpu->usbdev->found;
-		if (intinfo >= 0 && epinfo >= 0)
-			found->intinfos[intinfo].epinfos[epinfo].PrefPacketSize = PrefPacketSize;
-		else {
-			if (intinfo >= 0) {
-				for (epinfo = 0; epinfo < found->intinfos[intinfo].epinfo_count; epinfo++)
-					found->intinfos[intinfo].epinfos[epinfo].PrefPacketSize = PrefPacketSize;
-			} else {
-				for (intinfo = 0; intinfo < found->intinfo_count ; intinfo++)
-					for (epinfo = 0; epinfo < found->intinfos[intinfo].epinfo_count; epinfo++)
-						found->intinfos[intinfo].epinfos[epinfo].PrefPacketSize = PrefPacketSize;
-			}
-		}
-	}
-
-	DEVWUNLOCK(cgpu, pstate);
-}
-
 // Need to set all devices with matching usbdev
 void usb_set_dev_start(struct cgpu_info *cgpu)
 {
@@ -3323,6 +3203,7 @@ void usb_cleanup(void)
 			case DRIVER_icarus:
 			case DRIVER_avalon:
 			case DRIVER_klondike:
+			case DRIVER_hashfast:
 				DEVWLOCK(cgpu, pstate);
 				release_cgpu(cgpu);
 				DEVWUNLOCK(cgpu, pstate);
diff --git a/usbutils.h b/usbutils.h
index 0e8692b..ecf0810 100644
--- a/usbutils.h
+++ b/usbutils.h
@@ -122,7 +122,6 @@ struct usb_epinfo {
 	uint16_t size;
 	unsigned char ep;
 	uint16_t wMaxPacketSize;
-	uint16_t PrefPacketSize;
 	bool found;
 };
 
@@ -144,6 +143,7 @@ enum sub_ident {
 	IDENT_MMQ,
 	IDENT_AVA,
 	IDENT_BTB,
+	IDENT_HFA,
 	IDENT_BBF,
 	IDENT_KLN,
 	IDENT_ICA,
@@ -182,6 +182,8 @@ enum usb_types {
 	USB_TYPE_FTDI
 };
 
+#define USB_MAX_READ 8192
+
 struct cg_usb_device {
 	struct usb_find_devices *found;
 	libusb_device_handle *handle;
@@ -197,7 +199,7 @@ struct cg_usb_device {
 	char *serial_string;
 	unsigned char fwVersion;	// ??
 	unsigned char interfaceVersion;	// ??
-	char *buffer;
+	char buffer[USB_MAX_READ];
 	uint32_t bufsiz;
 	uint32_t bufamt;
 	cgtimer_t cgt_last_write;
@@ -206,8 +208,6 @@ struct cg_usb_device {
 
 #define USB_NOSTAT 0
 
-#define USB_MAX_READ 8192
-
 #define USB_TMO_0 50
 #define USB_TMO_1 100
 #define USB_TMO_2 500
@@ -346,7 +346,40 @@ struct cg_usb_info {
 	USB_ADD_COMMAND(C_BF_IFLUSH, "BFInterruptFlush") \
 	USB_ADD_COMMAND(C_BF_IDENTIFY, "BFIdentify") \
 	USB_ADD_COMMAND(C_BF_DETECTCHIPS, "BFDetectChips") \
-	USB_ADD_COMMAND(C_BF_CONFIG, "BFConfig")
+	USB_ADD_COMMAND(C_BF_CONFIG, "BFConfig") \
+	USB_ADD_COMMAND(C_ATMEL_RESET, "AtmelReset") \
+	USB_ADD_COMMAND(C_ATMEL_OPEN, "AtmelOpen") \
+	USB_ADD_COMMAND(C_ATMEL_INIT, "AtmelInit") \
+	USB_ADD_COMMAND(C_ATMEL_CLOSE, "AtmelClose") \
+	USB_ADD_COMMAND(C_BF1_REQINFO, "BF1RequestInfo") \
+	USB_ADD_COMMAND(C_BF1_GETINFO, "BF1GetInfo") \
+	USB_ADD_COMMAND(C_BF1_REQRESET, "BF1RequestReset") \
+	USB_ADD_COMMAND(C_BF1_GETRESET, "BF1GetReset") \
+	USB_ADD_COMMAND(C_BF1_REQWORK, "BF1RequestWork") \
+	USB_ADD_COMMAND(C_BF1_GETWORK, "BF1GetWork") \
+	USB_ADD_COMMAND(C_BF1_GETRES, "BF1GetResults") \
+	USB_ADD_COMMAND(C_BF1_FLUSH, "BF1Flush") \
+	USB_ADD_COMMAND(C_BF1_IFLUSH, "BF1InterruptFlush") \
+	USB_ADD_COMMAND(C_BF1_IDENTIFY, "BF1Identify") \
+	USB_ADD_COMMAND(C_HF_RESET, "HFReset") \
+	USB_ADD_COMMAND(C_HF_PLL_CONFIG, "HFPLLConfig") \
+	USB_ADD_COMMAND(C_HF_ADDRESS, "HFAddress") \
+	USB_ADD_COMMAND(C_HF_BAUD, "HFBaud") \
+	USB_ADD_COMMAND(C_HF_HASH, "HFHash") \
+	USB_ADD_COMMAND(C_HF_NONCE, "HFNonce") \
+	USB_ADD_COMMAND(C_HF_ABORT, "HFAbort") \
+	USB_ADD_COMMAND(C_HF_STATUS, "HFStatus") \
+	USB_ADD_COMMAND(C_HF_CONFIG, "HFConfig") \
+	USB_ADD_COMMAND(C_HF_STATISTICS, "HFStatistics") \
+	USB_ADD_COMMAND(C_HF_CLOCKGATE, "HFClockGate") \
+	USB_ADD_COMMAND(C_HF_USB_INIT, "HFUSBInit") \
+	USB_ADD_COMMAND(C_HF_DIE_STATUS, "HFDieStatus") \
+	USB_ADD_COMMAND(C_HF_GWQ_STATUS, "HFGWQStatus") \
+	USB_ADD_COMMAND(C_HF_WORK_RESTART, "HFWorkRestart") \
+	USB_ADD_COMMAND(C_HF_GWQSTATS, "HFGWQStats") \
+	USB_ADD_COMMAND(C_HF_GETHEADER, "HFGetHeader") \
+	USB_ADD_COMMAND(C_HF_GETDATA, "HFGetData") \
+	USB_ADD_COMMAND(C_HF_CLEAR_READ, "HFClearRead")
 
 /* Create usb_cmds enum from USB_PARSE_COMMANDS macro */
 enum usb_cmds {
@@ -361,7 +394,8 @@ bool async_usb_transfers(void);
 void cancel_usb_transfers(void);
 void usb_all(int level);
 const char *usb_cmdname(enum usb_cmds cmd);
-void usb_applog(struct cgpu_info *bflsc, enum usb_cmds cmd, char *msg, int amount, int err);
+void usb_applog(struct cgpu_info *cgpu, enum usb_cmds cmd, char *msg, int amount, int err);
+void usb_nodev(struct cgpu_info *cgpu);
 struct cgpu_info *usb_copy_cgpu(struct cgpu_info *orig);
 struct cgpu_info *usb_alloc_cgpu(struct device_drv *drv, int threads);
 struct cgpu_info *usb_free_cgpu(struct cgpu_info *cgpu);
@@ -370,15 +404,13 @@ bool usb_init(struct cgpu_info *cgpu, struct libusb_device *dev, struct usb_find
 void usb_detect(struct device_drv *drv, bool (*device_detect)(struct libusb_device *, struct usb_find_devices *));
 struct api_data *api_usb_stats(int *count);
 void update_usb_stats(struct cgpu_info *cgpu);
-int _usb_read(struct cgpu_info *cgpu, int intinfo, int epinfo, char *buf, size_t bufsiz, int *processed, unsigned int timeout, const char *end, enum usb_cmds cmd, bool readonce, bool cancellable);
-int _usb_write(struct cgpu_info *cgpu, int intinfo, int epinfo, char *buf, size_t bufsiz, int *processed, unsigned int timeout, enum usb_cmds);
+int _usb_read(struct cgpu_info *cgpu, int intinfo, int epinfo, char *buf, size_t bufsiz, int *processed, int timeout, const char *end, enum usb_cmds cmd, bool readonce, bool cancellable);
+int _usb_write(struct cgpu_info *cgpu, int intinfo, int epinfo, char *buf, size_t bufsiz, int *processed, int timeout, enum usb_cmds);
 int _usb_transfer(struct cgpu_info *cgpu, uint8_t request_type, uint8_t bRequest, uint16_t wValue, uint16_t wIndex, uint32_t *data, int siz, unsigned int timeout, enum usb_cmds cmd);
 int _usb_transfer_read(struct cgpu_info *cgpu, uint8_t request_type, uint8_t bRequest, uint16_t wValue, uint16_t wIndex, char *buf, int bufsiz, int *amount, unsigned int timeout, enum usb_cmds cmd);
 int usb_ftdi_cts(struct cgpu_info *cgpu);
 int _usb_ftdi_set_latency(struct cgpu_info *cgpu, int intinfo);
 #define usb_ftdi_set_latency(_cgpu) _usb_ftdi_set_latency(_cgpu, DEFAULT_INTINFO)
-void usb_buffer_enable(struct cgpu_info *cgpu);
-void usb_buffer_disable(struct cgpu_info *cgpu);
 void usb_buffer_clear(struct cgpu_info *cgpu);
 uint32_t usb_buffer_size(struct cgpu_info *cgpu);
 void usb_set_cps(struct cgpu_info *cgpu, int cps);
@@ -387,8 +419,6 @@ void usb_disable_cps(struct cgpu_info *cgpu);
 int _usb_interface(struct cgpu_info *cgpu, int intinfo);
 #define usb_interface(_cgpu) _usb_interface(_cgpu, DEFAULT_INTINFO)
 enum sub_ident usb_ident(struct cgpu_info *cgpu);
-void _usb_set_pps(struct cgpu_info *cgpu, int intinfo, int epinfo, uint16_t PrefPacketSize);
-#define usb_set_pps(_cgpu, _pps) _usb_set_pps(_cgpu, -1, -1, _pps)
 void usb_set_dev_start(struct cgpu_info *cgpu);
 void usb_cleanup();
 void usb_initialise();
diff --git a/uthash.h b/uthash.h
index 4cedb9c..72acf11 100644
--- a/uthash.h
+++ b/uthash.h
@@ -1,5 +1,5 @@
 /*
-Copyright (c) 2003-2011, Troy D. Hanson     http://uthash.sourceforge.net
+Copyright (c) 2003-2013, Troy D. Hanson     http://troydhanson.github.com/uthash/
 All rights reserved.
 
 Redistribution and use in source and binary forms, with or without
@@ -22,7 +22,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
 
 #ifndef UTHASH_H
-#define UTHASH_H
+#define UTHASH_H 
 
 #include <string.h>   /* memcmp,strlen */
 #include <stddef.h>   /* ptrdiff_t */
@@ -49,7 +49,7 @@ do {                                                                            
   char **_da_dst = (char**)(&(dst));                                             \
   *_da_dst = (char*)(src);                                                       \
 } while(0)
-#else
+#else 
 #define DECLTYPE_ASSIGN(dst,src)                                                 \
 do {                                                                             \
   (dst) = DECLTYPE(dst)(src);                                                    \
@@ -64,14 +64,24 @@ typedef unsigned char uint8_t;
 #include <inttypes.h>   /* uint32_t */
 #endif
 
-#define UTHASH_VERSION 1.9.4
+#define UTHASH_VERSION 1.9.8
 
+#ifndef uthash_fatal
 #define uthash_fatal(msg) exit(-1)        /* fatal error (out of memory,etc) */
+#endif
+#ifndef uthash_malloc
 #define uthash_malloc(sz) malloc(sz)      /* malloc fcn                      */
+#endif
+#ifndef uthash_free
 #define uthash_free(ptr,sz) free(ptr)     /* free fcn                        */
+#endif
 
+#ifndef uthash_noexpand_fyi
 #define uthash_noexpand_fyi(tbl)          /* can be defined to log noexpand  */
+#endif
+#ifndef uthash_expand_fyi
 #define uthash_expand_fyi(tbl)            /* can be defined to log expands   */
+#endif
 
 /* initial number of buckets */
 #define HASH_INITIAL_NUM_BUCKETS 32      /* initial number of buckets        */
@@ -104,12 +114,12 @@ do {                                                                            
   if (!((tbl)->bloom_bv))  { uthash_fatal( "out of memory"); }                   \
   memset((tbl)->bloom_bv, 0, HASH_BLOOM_BYTELEN);                                \
   (tbl)->bloom_sig = HASH_BLOOM_SIGNATURE;                                       \
-} while (0);
+} while (0) 
 
 #define HASH_BLOOM_FREE(tbl)                                                     \
 do {                                                                             \
   uthash_free((tbl)->bloom_bv, HASH_BLOOM_BYTELEN);                              \
-} while (0);
+} while (0) 
 
 #define HASH_BLOOM_BITSET(bv,idx) (bv[(idx)/8] |= (1U << ((idx)%8)))
 #define HASH_BLOOM_BITTEST(bv,idx) (bv[(idx)/8] & (1U << ((idx)%8)))
@@ -121,10 +131,11 @@ do {                                                                            
   HASH_BLOOM_BITTEST((tbl)->bloom_bv, (hashv & (uint32_t)((1ULL << (tbl)->bloom_nbits) - 1)))
 
 #else
-#define HASH_BLOOM_MAKE(tbl)
-#define HASH_BLOOM_FREE(tbl)
-#define HASH_BLOOM_ADD(tbl,hashv)
+#define HASH_BLOOM_MAKE(tbl) 
+#define HASH_BLOOM_FREE(tbl) 
+#define HASH_BLOOM_ADD(tbl,hashv) 
 #define HASH_BLOOM_TEST(tbl,hashv) (1)
+#define HASH_BLOOM_BYTELEN 0
 #endif
 
 #define HASH_MAKE_TABLE(hh,head)                                                 \
@@ -147,14 +158,24 @@ do {                                                                            
 } while(0)
 
 #define HASH_ADD(hh,head,fieldname,keylen_in,add)                                \
-        HASH_ADD_KEYPTR(hh,head,&add->fieldname,keylen_in,add)
+        HASH_ADD_KEYPTR(hh,head,&((add)->fieldname),keylen_in,add)
 
+#define HASH_REPLACE(hh,head,fieldname,keylen_in,add,replaced)                   \
+do {                                                                             \
+  replaced=NULL;                                                                 \
+  HASH_FIND(hh,head,&((add)->fieldname),keylen_in,replaced);                     \
+  if (replaced!=NULL) {                                                          \
+     HASH_DELETE(hh,head,replaced);                                              \
+  };                                                                             \
+  HASH_ADD(hh,head,fieldname,keylen_in,add);                                     \
+} while(0)
+ 
 #define HASH_ADD_KEYPTR(hh,head,keyptr,keylen_in,add)                            \
 do {                                                                             \
  unsigned _ha_bkt;                                                               \
  (add)->hh.next = NULL;                                                          \
- (add)->hh.key = (char*)keyptr;                                                  \
- (add)->hh.keylen = keylen_in;                                                   \
+ (add)->hh.key = (char*)(keyptr);                                                \
+ (add)->hh.keylen = (unsigned)(keylen_in);                                       \
  if (!(head)) {                                                                  \
     head = (add);                                                                \
     (head)->hh.prev = NULL;                                                      \
@@ -205,17 +226,17 @@ do {                                                                            
         _hd_hh_del = &((delptr)->hh);                                            \
         if ((delptr) == ELMT_FROM_HH((head)->hh.tbl,(head)->hh.tbl->tail)) {     \
             (head)->hh.tbl->tail =                                               \
-                (UT_hash_handle*)((char*)((delptr)->hh.prev) +                   \
+                (UT_hash_handle*)((ptrdiff_t)((delptr)->hh.prev) +               \
                 (head)->hh.tbl->hho);                                            \
         }                                                                        \
         if ((delptr)->hh.prev) {                                                 \
-            ((UT_hash_handle*)((char*)((delptr)->hh.prev) +                      \
+            ((UT_hash_handle*)((ptrdiff_t)((delptr)->hh.prev) +                  \
                     (head)->hh.tbl->hho))->next = (delptr)->hh.next;             \
         } else {                                                                 \
             DECLTYPE_ASSIGN(head,(delptr)->hh.next);                             \
         }                                                                        \
         if (_hd_hh_del->next) {                                                  \
-            ((UT_hash_handle*)((char*)_hd_hh_del->next +                         \
+            ((UT_hash_handle*)((ptrdiff_t)_hd_hh_del->next +                     \
                     (head)->hh.tbl->hho))->prev =                                \
                     _hd_hh_del->prev;                                            \
         }                                                                        \
@@ -232,14 +253,20 @@ do {                                                                            
     HASH_FIND(hh,head,findstr,strlen(findstr),out)
 #define HASH_ADD_STR(head,strfield,add)                                          \
     HASH_ADD(hh,head,strfield,strlen(add->strfield),add)
+#define HASH_REPLACE_STR(head,strfield,add,replaced)                             \
+  HASH_REPLACE(hh,head,strfield,strlen(add->strfield),add,replaced)
 #define HASH_FIND_INT(head,findint,out)                                          \
     HASH_FIND(hh,head,findint,sizeof(int),out)
 #define HASH_ADD_INT(head,intfield,add)                                          \
     HASH_ADD(hh,head,intfield,sizeof(int),add)
+#define HASH_REPLACE_INT(head,intfield,add,replaced)                             \
+    HASH_REPLACE(hh,head,intfield,sizeof(int),add,replaced)
 #define HASH_FIND_PTR(head,findptr,out)                                          \
     HASH_FIND(hh,head,findptr,sizeof(void *),out)
 #define HASH_ADD_PTR(head,ptrfield,add)                                          \
     HASH_ADD(hh,head,ptrfield,sizeof(void *),add)
+#define HASH_REPLACE_PTR(head,ptrfield,add)                                      \
+    HASH_REPLACE(hh,head,ptrfield,sizeof(void *),add,replaced)
 #define HASH_DEL(head,delptr)                                                    \
     HASH_DELETE(hh,head,delptr)
 
@@ -300,10 +327,10 @@ do {                                                                            
     }                                                                            \
 } while (0)
 #else
-#define HASH_FSCK(hh,head)
+#define HASH_FSCK(hh,head) 
 #endif
 
-/* When compiled with -DHASH_EMIT_KEYS, length-prefixed keys are emitted to
+/* When compiled with -DHASH_EMIT_KEYS, length-prefixed keys are emitted to 
  * the descriptor to which this macro is defined for tuning the hash function.
  * The app can #include <unistd.h> to get the prototype for write(2). */
 #ifdef HASH_EMIT_KEYS
@@ -313,12 +340,12 @@ do {                                                                            
     write(HASH_EMIT_KEYS, &_klen, sizeof(_klen));                                \
     write(HASH_EMIT_KEYS, keyptr, fieldlen);                                     \
 } while (0)
-#else
-#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen)
+#else 
+#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen)                    
 #endif
 
 /* default to Jenkin's hash unless overridden e.g. DHASH_FUNCTION=HASH_SAX */
-#ifdef HASH_FUNCTION
+#ifdef HASH_FUNCTION 
 #define HASH_FCN HASH_FUNCTION
 #else
 #define HASH_FCN HASH_JEN
@@ -335,7 +362,7 @@ do {                                                                            
 } while (0)
 
 
-/* SAX/FNV/OAT/JEN hash functions are macro variants of those listed at
+/* SAX/FNV/OAT/JEN hash functions are macro variants of those listed at 
  * http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx */
 #define HASH_SAX(key,keylen,num_bkts,hashv,bkt)                                  \
 do {                                                                             \
@@ -355,8 +382,8 @@ do {                                                                            
   for(_fn_i=0; _fn_i < keylen; _fn_i++)                                          \
       hashv = (hashv * 16777619) ^ _hf_key[_fn_i];                               \
   bkt = hashv & (num_bkts-1);                                                    \
-} while(0);
-
+} while(0) 
+ 
 #define HASH_OAT(key,keylen,num_bkts,hashv,bkt)                                  \
 do {                                                                             \
   unsigned _ho_i;                                                                \
@@ -389,10 +416,10 @@ do {                                                                            
 #define HASH_JEN(key,keylen,num_bkts,hashv,bkt)                                  \
 do {                                                                             \
   unsigned _hj_i,_hj_j,_hj_k;                                                    \
-  char *_hj_key=(char*)(key);                                                    \
+  unsigned char *_hj_key=(unsigned char*)(key);                                  \
   hashv = 0xfeedbeef;                                                            \
   _hj_i = _hj_j = 0x9e3779b9;                                                    \
-  _hj_k = keylen;                                                                \
+  _hj_k = (unsigned)(keylen);                                                      \
   while (_hj_k >= 12) {                                                          \
     _hj_i +=    (_hj_key[0] + ( (unsigned)_hj_key[1] << 8 )                      \
         + ( (unsigned)_hj_key[2] << 16 )                                         \
@@ -440,7 +467,7 @@ do {                                                                            
 #endif
 #define HASH_SFH(key,keylen,num_bkts,hashv,bkt)                                  \
 do {                                                                             \
-  char *_sfh_key=(char*)(key);                                                   \
+  unsigned char *_sfh_key=(unsigned char*)(key);                                 \
   uint32_t _sfh_tmp, _sfh_len = keylen;                                          \
                                                                                  \
   int _sfh_rem = _sfh_len & 3;                                                   \
@@ -450,7 +477,7 @@ do {                                                                            
   /* Main loop */                                                                \
   for (;_sfh_len > 0; _sfh_len--) {                                              \
     hashv    += get16bits (_sfh_key);                                            \
-    _sfh_tmp       = (get16bits (_sfh_key+2) << 11) ^ hashv;                     \
+    _sfh_tmp       = (uint32_t)(get16bits (_sfh_key+2)) << 11  ^ hashv;          \
     hashv     = (hashv << 16) ^ _sfh_tmp;                                        \
     _sfh_key += 2*sizeof (uint16_t);                                             \
     hashv    += hashv >> 11;                                                     \
@@ -460,7 +487,7 @@ do {                                                                            
   switch (_sfh_rem) {                                                            \
     case 3: hashv += get16bits (_sfh_key);                                       \
             hashv ^= hashv << 16;                                                \
-            hashv ^= _sfh_key[sizeof (uint16_t)] << 18;                          \
+            hashv ^= (uint32_t)(_sfh_key[sizeof (uint16_t)] << 18);              \
             hashv += hashv >> 11;                                                \
             break;                                                               \
     case 2: hashv += get16bits (_sfh_key);                                       \
@@ -480,19 +507,19 @@ do {                                                                            
     hashv ^= hashv << 25;                                                        \
     hashv += hashv >> 6;                                                         \
     bkt = hashv & (num_bkts-1);                                                  \
-} while(0);
+} while(0) 
 
 #ifdef HASH_USING_NO_STRICT_ALIASING
 /* The MurmurHash exploits some CPU's (x86,x86_64) tolerance for unaligned reads.
  * For other types of CPU's (e.g. Sparc) an unaligned read causes a bus error.
- * MurmurHash uses the faster approach only on CPU's where we know it's safe.
+ * MurmurHash uses the faster approach only on CPU's where we know it's safe. 
  *
  * Note the preprocessor built-in defines can be emitted using:
  *
  *   gcc -m64 -dM -E - < /dev/null                  (on gcc)
  *   cc -## a.c (where a.c is a simple test file)   (Sun Studio)
  */
-#if (defined(__i386__) || defined(__x86_64__))
+#if (defined(__i386__) || defined(__x86_64__)  || defined(_M_IX86))
 #define MUR_GETBLOCK(p,i) p[i]
 #else /* non intel */
 #define MUR_PLUS0_ALIGNED(p) (((unsigned long)p & 0x3) == 0)
@@ -531,10 +558,12 @@ do {                                                                   \
   uint32_t _mur_h1 = 0xf88D5353;                                       \
   uint32_t _mur_c1 = 0xcc9e2d51;                                       \
   uint32_t _mur_c2 = 0x1b873593;                                       \
+  uint32_t _mur_k1 = 0;                                                \
+  const uint8_t *_mur_tail;                                            \
   const uint32_t *_mur_blocks = (const uint32_t*)(_mur_data+_mur_nblocks*4); \
   int _mur_i;                                                          \
   for(_mur_i = -_mur_nblocks; _mur_i; _mur_i++) {                      \
-    uint32_t _mur_k1 = MUR_GETBLOCK(_mur_blocks,_mur_i);               \
+    _mur_k1 = MUR_GETBLOCK(_mur_blocks,_mur_i);                        \
     _mur_k1 *= _mur_c1;                                                \
     _mur_k1 = MUR_ROTL32(_mur_k1,15);                                  \
     _mur_k1 *= _mur_c2;                                                \
@@ -543,8 +572,8 @@ do {                                                                   \
     _mur_h1 = MUR_ROTL32(_mur_h1,13);                                  \
     _mur_h1 = _mur_h1*5+0xe6546b64;                                    \
   }                                                                    \
-  const uint8_t *_mur_tail = (const uint8_t*)(_mur_data + _mur_nblocks*4); \
-  uint32_t _mur_k1=0;                                                  \
+  _mur_tail = (const uint8_t*)(_mur_data + _mur_nblocks*4);            \
+  _mur_k1=0;                                                           \
   switch((keylen) & 3) {                                               \
     case 3: _mur_k1 ^= _mur_tail[2] << 16;                             \
     case 2: _mur_k1 ^= _mur_tail[1] << 8;                              \
@@ -562,7 +591,7 @@ do {                                                                   \
 #endif  /* HASH_USING_NO_STRICT_ALIASING */
 
 /* key comparison function; return 0 if keys equal */
-#define HASH_KEYCMP(a,b,len) memcmp(a,b,len)
+#define HASH_KEYCMP(a,b,len) memcmp(a,b,len) 
 
 /* iterate over items in a known bucket to find desired item */
 #define HASH_FIND_IN_BKT(tbl,hh,head,keyptr,keylen_in,out)                       \
@@ -570,10 +599,10 @@ do {                                                                            
  if (head.hh_head) DECLTYPE_ASSIGN(out,ELMT_FROM_HH(tbl,head.hh_head));          \
  else out=NULL;                                                                  \
  while (out) {                                                                   \
-    if (out->hh.keylen == keylen_in) {                                           \
-        if ((HASH_KEYCMP(out->hh.key,keyptr,keylen_in)) == 0) break;             \
+    if ((out)->hh.keylen == keylen_in) {                                           \
+        if ((HASH_KEYCMP((out)->hh.key,keyptr,keylen_in)) == 0) break;             \
     }                                                                            \
-    if (out->hh.hh_next) DECLTYPE_ASSIGN(out,ELMT_FROM_HH(tbl,out->hh.hh_next)); \
+    if ((out)->hh.hh_next) DECLTYPE_ASSIGN(out,ELMT_FROM_HH(tbl,(out)->hh.hh_next)); \
     else out = NULL;                                                             \
  }                                                                               \
 } while(0)
@@ -603,36 +632,36 @@ do {                                                                            
     }                                                                            \
     if (hh_del->hh_next) {                                                       \
         hh_del->hh_next->hh_prev = hh_del->hh_prev;                              \
-    }
+    }                                                                
 
 /* Bucket expansion has the effect of doubling the number of buckets
  * and redistributing the items into the new buckets. Ideally the
  * items will distribute more or less evenly into the new buckets
  * (the extent to which this is true is a measure of the quality of
- * the hash function as it applies to the key domain).
- *
+ * the hash function as it applies to the key domain). 
+ * 
  * With the items distributed into more buckets, the chain length
  * (item count) in each bucket is reduced. Thus by expanding buckets
- * the hash keeps a bound on the chain length. This bounded chain
+ * the hash keeps a bound on the chain length. This bounded chain 
  * length is the essence of how a hash provides constant time lookup.
- *
+ * 
  * The calculation of tbl->ideal_chain_maxlen below deserves some
  * explanation. First, keep in mind that we're calculating the ideal
  * maximum chain length based on the *new* (doubled) bucket count.
  * In fractions this is just n/b (n=number of items,b=new num buckets).
- * Since the ideal chain length is an integer, we want to calculate
+ * Since the ideal chain length is an integer, we want to calculate 
  * ceil(n/b). We don't depend on floating point arithmetic in this
  * hash, so to calculate ceil(n/b) with integers we could write
- *
+ * 
  *      ceil(n/b) = (n/b) + ((n%b)?1:0)
- *
+ * 
  * and in fact a previous version of this hash did just that.
  * But now we have improved things a bit by recognizing that b is
  * always a power of two. We keep its base 2 log handy (call it lb),
  * so now we can write this with a bit shift and logical AND:
- *
+ * 
  *      ceil(n/b) = (n>>lb) + ( (n & (b-1)) ? 1:0)
- *
+ * 
  */
 #define HASH_EXPAND_BUCKETS(tbl)                                                 \
 do {                                                                             \
@@ -684,7 +713,7 @@ do {                                                                            
 
 
 /* This is an adaptation of Simon Tatham's O(n log(n)) mergesort */
-/* Note that HASH_SORT assumes the hash handle name to be hh.
+/* Note that HASH_SORT assumes the hash handle name to be hh. 
  * HASH_SRT was added to allow the hash handle name to be passed in. */
 #define HASH_SORT(head,cmpfcn) HASH_SRT(hh,head,cmpfcn)
 #define HASH_SRT(hh,head,cmpfcn)                                                 \
@@ -722,18 +751,22 @@ do {                                                                            
                       _hs_qsize--;                                               \
                   } else if ( (_hs_qsize == 0) || !(_hs_q) ) {                   \
                       _hs_e = _hs_p;                                             \
-                      _hs_p = (UT_hash_handle*)((_hs_p->next) ?                  \
-                              ((void*)((char*)(_hs_p->next) +                    \
-                              (head)->hh.tbl->hho)) : NULL);                     \
+                      if (_hs_p){                                                \
+                        _hs_p = (UT_hash_handle*)((_hs_p->next) ?                \
+                                ((void*)((char*)(_hs_p->next) +                  \
+                                (head)->hh.tbl->hho)) : NULL);                   \
+                       }                                                         \
                       _hs_psize--;                                               \
                   } else if ((                                                   \
                       cmpfcn(DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl,_hs_p)), \
                              DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl,_hs_q))) \
                              ) <= 0) {                                           \
                       _hs_e = _hs_p;                                             \
-                      _hs_p = (UT_hash_handle*)((_hs_p->next) ?                  \
-                              ((void*)((char*)(_hs_p->next) +                    \
-                              (head)->hh.tbl->hho)) : NULL);                     \
+                      if (_hs_p){                                                \
+                        _hs_p = (UT_hash_handle*)((_hs_p->next) ?                \
+                               ((void*)((char*)(_hs_p->next) +                   \
+                               (head)->hh.tbl->hho)) : NULL);                    \
+                       }                                                         \
                       _hs_psize--;                                               \
                   } else {                                                       \
                       _hs_e = _hs_q;                                             \
@@ -748,13 +781,17 @@ do {                                                                            
                   } else {                                                       \
                       _hs_list = _hs_e;                                          \
                   }                                                              \
+                  if (_hs_e) {                                                   \
                   _hs_e->prev = ((_hs_tail) ?                                    \
                      ELMT_FROM_HH((head)->hh.tbl,_hs_tail) : NULL);              \
+                  }                                                              \
                   _hs_tail = _hs_e;                                              \
               }                                                                  \
               _hs_p = _hs_q;                                                     \
           }                                                                      \
-          _hs_tail->next = NULL;                                                 \
+          if (_hs_tail){                                                         \
+            _hs_tail->next = NULL;                                               \
+          }                                                                      \
           if ( _hs_nmerges <= 1 ) {                                              \
               _hs_looping=0;                                                     \
               (head)->hh.tbl->tail = _hs_tail;                                   \
@@ -766,10 +803,10 @@ do {                                                                            
  }                                                                               \
 } while (0)
 
-/* This function selects items from one hash into another hash.
- * The end result is that the selected items have dual presence
- * in both hashes. There is no copy of the items made; rather
- * they are added into the new hash through a secondary hash
+/* This function selects items from one hash into another hash. 
+ * The end result is that the selected items have dual presence 
+ * in both hashes. There is no copy of the items made; rather 
+ * they are added into the new hash through a secondary hash 
  * hash handle that must be present in the structure. */
 #define HASH_SELECT(hh_dst, dst, hh_src, src, cond)                              \
 do {                                                                             \
@@ -814,15 +851,22 @@ do {                                                                            
   if (head) {                                                                    \
     uthash_free((head)->hh.tbl->buckets,                                         \
                 (head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucket));      \
+    HASH_BLOOM_FREE((head)->hh.tbl);                                             \
     uthash_free((head)->hh.tbl, sizeof(UT_hash_table));                          \
     (head)=NULL;                                                                 \
   }                                                                              \
 } while(0)
 
+#define HASH_OVERHEAD(hh,head)                                                   \
+ (size_t)((((head)->hh.tbl->num_items   * sizeof(UT_hash_handle))   +            \
+           ((head)->hh.tbl->num_buckets * sizeof(UT_hash_bucket))   +            \
+            (sizeof(UT_hash_table))                                 +            \
+            (HASH_BLOOM_BYTELEN)))
+
 #ifdef NO_DECLTYPE
 #define HASH_ITER(hh,head,el,tmp)                                                \
 for((el)=(head), (*(char**)(&(tmp)))=(char*)((head)?(head)->hh.next:NULL);       \
-  el; (el)=(tmp),(*(char**)(&(tmp)))=(char*)((tmp)?(tmp)->hh.next:NULL))
+  el; (el)=(tmp),(*(char**)(&(tmp)))=(char*)((tmp)?(tmp)->hh.next:NULL)) 
 #else
 #define HASH_ITER(hh,head,el,tmp)                                                \
 for((el)=(head),(tmp)=DECLTYPE(el)((head)?(head)->hh.next:NULL);                 \
@@ -830,7 +874,7 @@ for((el)=(head),(tmp)=DECLTYPE(el)((head)?(head)->hh.next:NULL);                
 #endif
 
 /* obtain a count of items in the hash */
-#define HASH_COUNT(head) HASH_CNT(hh,head)
+#define HASH_COUNT(head) HASH_CNT(hh,head) 
 #define HASH_CNT(hh,head) ((head)?((head)->hh.tbl->num_items):0)
 
 typedef struct UT_hash_bucket {
@@ -839,7 +883,7 @@ typedef struct UT_hash_bucket {
 
    /* expand_mult is normally set to 0. In this situation, the max chain length
     * threshold is enforced at its default value, HASH_BKT_CAPACITY_THRESH. (If
-    * the bucket's chain exceeds this length, bucket expansion is triggered).
+    * the bucket's chain exceeds this length, bucket expansion is triggered). 
     * However, setting expand_mult to a non-zero value delays bucket expansion
     * (that would be triggered by additions to this particular bucket)
     * until its chain length reaches a *multiple* of HASH_BKT_CAPACITY_THRESH.
@@ -847,7 +891,7 @@ typedef struct UT_hash_bucket {
     * multiplier is to reduce bucket expansions, since they are expensive, in
     * situations where we know that a particular bucket tends to be overused.
     * It is better to let its chain length grow to a longer yet-still-bounded
-    * value, than to do an O(n) bucket expansion too often.
+    * value, than to do an O(n) bucket expansion too often. 
     */
    unsigned expand_mult;
 
@@ -873,7 +917,7 @@ typedef struct UT_hash_table {
     * hash distribution; reaching them in a chain traversal takes >ideal steps */
    unsigned nonideal_items;
 
-   /* ineffective expands occur when a bucket doubling was performed, but
+   /* ineffective expands occur when a bucket doubling was performed, but 
     * afterward, more than half the items in the hash had nonideal chain
     * positions. If this happens on two consecutive expansions we inhibit any
     * further expansion, as it's not helping; this happens when the hash
diff --git a/util.c b/util.c
index 363c73c..f5472c3 100644
--- a/util.c
+++ b/util.c
@@ -588,10 +588,13 @@ char *get_proxy(char *url, struct pool *pool)
 void __bin2hex(char *s, const unsigned char *p, size_t len)
 {
 	int i;
+	static const char hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
 
-	for (i = 0; i < (int)len; i++)
-		sprintf(s + (i * 2), "%02x", (unsigned int)p[i]);
-
+	for (i = 0; i < (int)len; i++) {
+		*s++ = hex[p[i] >> 4];
+		*s++ = hex[p[i] & 0xF];
+	}
+	*s++ = '\0';
 }
 
 /* Returns a malloced array string of a binary value of arbitrary length. The
@@ -615,33 +618,48 @@ char *bin2hex(const unsigned char *p, size_t len)
 }
 
 /* Does the reverse of bin2hex but does not allocate any ram */
+static const int hex2bin_tbl[256] = {
+	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+	 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, -1, -1, -1, -1, -1, -1,
+	-1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+	-1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+};
 bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
 {
+	int nibble1, nibble2;
+	unsigned char idx;
 	bool ret = false;
 
 	while (*hexstr && len) {
-		char hex_byte[4];
-		unsigned int v;
-
 		if (unlikely(!hexstr[1])) {
 			applog(LOG_ERR, "hex2bin str truncated");
 			return ret;
 		}
 
-		memset(hex_byte, 0, 4);
-		hex_byte[0] = hexstr[0];
-		hex_byte[1] = hexstr[1];
+		idx = *hexstr++;
+		nibble1 = hex2bin_tbl[idx];
+		idx = *hexstr++;
+		nibble2 = hex2bin_tbl[idx];
 
-		if (unlikely(sscanf(hex_byte, "%x", &v) != 1)) {
-			applog(LOG_INFO, "hex2bin sscanf '%s' failed", hex_byte);
+		if (unlikely((nibble1 < 0) || (nibble2 < 0))) {
+			applog(LOG_ERR, "hex2bin scan failed");
 			return ret;
 		}
 
-		*p = (unsigned char) v;
-
-		p++;
-		hexstr += 2;
-		len--;
+		*p++ = (((unsigned char)nibble1) << 4) | ((unsigned char)nibble2);
+		--len;
 	}
 
 	if (likely(len == 0 && *hexstr == 0))
@@ -651,21 +669,14 @@ bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
 
 bool fulltest(const unsigned char *hash, const unsigned char *target)
 {
-	unsigned char hash_swap[32], target_swap[32];
-	uint32_t *hash32 = (uint32_t *) hash_swap;
-	uint32_t *target32 = (uint32_t *) target_swap;
-	char *hash_str, *target_str;
+	uint32_t *hash32 = (uint32_t *)hash;
+	uint32_t *target32 = (uint32_t *)target;
 	bool rc = true;
 	int i;
 
-	swap256(hash_swap, hash);
-	swap256(target_swap, target);
-
-	for (i = 0; i < 32/4; i++) {
-		uint32_t h32tmp = htobe32(hash32[i]);
-		uint32_t t32tmp = htole32(target32[i]);
-
-		target32[i] = swab32(target32[i]);	/* for printing */
+	for (i = 28 / 4; i >= 0; i--) {
+		uint32_t h32tmp = le32toh(hash32[i]);
+		uint32_t t32tmp = le32toh(target32[i]);
 
 		if (h32tmp > t32tmp) {
 			rc = false;
@@ -678,6 +689,11 @@ bool fulltest(const unsigned char *hash, const unsigned char *target)
 	}
 
 	if (opt_debug) {
+		unsigned char hash_swap[32], target_swap[32];
+		char *hash_str, *target_str;
+
+		swab256(hash_swap, hash);
+		swab256(target_swap, target);
 		hash_str = bin2hex(hash_swap, 32);
 		target_str = bin2hex(target_swap, 32);
 
@@ -1061,9 +1077,13 @@ void cgtimer_time(cgtimer_t *ts_start)
 
 static void liSleep(LARGE_INTEGER *li, int timeout)
 {
-	HANDLE hTimer = CreateWaitableTimer(NULL, TRUE, NULL);
+	HANDLE hTimer;
 	DWORD ret;
 
+	if (unlikely(timeout <= 0))
+		return;
+
+	hTimer = CreateWaitableTimer(NULL, TRUE, NULL);
 	if (unlikely(!hTimer))
 		quit(1, "Failed to create hTimer in liSleep");
 	ret = SetWaitableTimer(hTimer, li, 0, NULL, NULL, 0);
@@ -2023,6 +2043,40 @@ static bool socks4_negotiate(struct pool *pool, int sockd, bool socks4a)
 	return true;
 }
 
+static void noblock_socket(SOCKETTYPE fd)
+{
+#ifndef WIN32
+	int flags = fcntl(fd, F_GETFL, 0);
+
+	fcntl(fd, F_SETFL, O_NONBLOCK | flags);
+#else
+	u_long flags = 1;
+
+	ioctlsocket(fd, FIONBIO, &flags);
+#endif
+}
+
+static void block_socket(SOCKETTYPE fd)
+{
+#ifndef WIN32
+	int flags = fcntl(fd, F_GETFL, 0);
+
+	fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
+#else
+	u_long flags = 0;
+
+	ioctlsocket(fd, FIONBIO, &flags);
+#endif
+}
+
+static bool sock_connecting(void)
+{
+#ifndef WIN32
+	return errno == EINPROGRESS;
+#else
+	return WSAGetLastError() == WSAEWOULDBLOCK;
+#endif
+}
 static bool setup_stratum_socket(struct pool *pool)
 {
 	struct addrinfo servinfobase, *servinfo, *hints, *p;
@@ -2074,11 +2128,41 @@ static bool setup_stratum_socket(struct pool *pool)
 			continue;
 		}
 
+		/* Iterate non blocking over entries returned by getaddrinfo
+		 * to cope with round robin DNS entries, finding the first one
+		 * we can connect to quickly. */
+		noblock_socket(sockd);
 		if (connect(sockd, p->ai_addr, p->ai_addrlen) == -1) {
+			struct timeval tv_timeout = {1, 0};
+			int selret;
+			fd_set rw;
+
+			if (!sock_connecting()) {
+				CLOSESOCKET(sockd);
+				applog(LOG_DEBUG, "Failed sock connect");
+				continue;
+			}
+			FD_ZERO(&rw);
+			FD_SET(sockd, &rw);
+			selret = select(sockd + 1, NULL, &rw, NULL, &tv_timeout);
+			if  (selret > 0 && FD_ISSET(sockd, &rw)) {
+				socklen_t len;
+				int err, n;
+
+				len = sizeof(err);
+				n = getsockopt(sockd, SOL_SOCKET, SO_ERROR, (void *)&err, &len);
+				if (!n && !err) {
+					applog(LOG_DEBUG, "Succeeded delayed connect");
+					block_socket(sockd);
+					break;
+				}
+			}
 			CLOSESOCKET(sockd);
-			applog(LOG_DEBUG, "Failed connect");
+			applog(LOG_DEBUG, "Select timeout/failed connect");
 			continue;
 		}
+		applog(LOG_WARNING, "Succeeded immediate connect");
+		block_socket(sockd);
 
 		break;
 	}
diff --git a/util.h b/util.h
index a32988b..d359656 100644
--- a/util.h
+++ b/util.h
@@ -61,6 +61,7 @@
 #endif
 
 #ifdef HAVE_LIBCURL
+#include <curl/curl.h>
 typedef curl_proxytype proxytypes_t;
 #else
 typedef int proxytypes_t;