File: musb.c

package info (click to toggle)
hplip 3.18.12%2Bdfsg0-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 150,024 kB
  • sloc: python: 82,881; ansic: 69,716; cpp: 62,345; sh: 11,412; perl: 4,397; makefile: 926
file content (2354 lines) | stat: -rw-r--r-- 71,885 bytes parent folder | download | duplicates (4)
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
/*****************************************************************************\

  musb.c - USB support for multi-point transport driver

  (c) 2010 - 2014 Copyright HP Development Company, LP

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  of the Software, and to permit persons to whom the Software is furnished to do
  so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  Client/Server generic message format (see messaging-protocol.doc):

Author: Naga Samrat Chowdary Narla, Sarbeswar Meher
\*****************************************************************************/

#include "hpmud.h"
#include "hpmudi.h"
#include <dlfcn.h>
#include <stdlib.h>
#include "utils.h"


mud_device_vf __attribute__ ((visibility ("hidden"))) musb_mud_device_vf =
{
    .read = musb_read,
    .write = musb_write,
    .open = musb_open,
    .close = musb_close,
    .get_device_id = musb_get_device_id,
    .get_device_status = musb_get_device_status,
    .channel_open = musb_channel_open,
    .channel_close = musb_channel_close,
    .channel_write = musb_channel_write,
    .channel_read = musb_channel_read
};

static mud_channel_vf musb_raw_channel_vf =
{
    .open = musb_raw_channel_open,
    .close = musb_raw_channel_close,
    .channel_write = musb_raw_channel_write,
    .channel_read = musb_raw_channel_read
};

static mud_channel_vf musb_comp_channel_vf =
{
    .open = musb_comp_channel_open,
    .close = musb_raw_channel_close,
    .channel_write = musb_raw_channel_write,
    .channel_read = musb_raw_channel_read
};

static mud_channel_vf musb_mlc_channel_vf =
{
    .open = musb_mlc_channel_open,
    .close = musb_mlc_channel_close,
    .channel_write = musb_mlc_channel_write,
    .channel_read = musb_mlc_channel_read
};

static mud_channel_vf musb_dot4_channel_vf =
{
    .open = musb_dot4_channel_open,
    .close = musb_dot4_channel_close,
    .channel_write = musb_dot4_channel_write,
    .channel_read = musb_dot4_channel_read
};

/*
 * The folloing fd arrays must match "enum FD_ID" definition.
 */

static char *fd_name[MAX_FD] =
{
    "na",
    "7/1/2",
    "7/1/3",
    "7/1/4",
    "ff/1/1",
    "ff/2/1",
    "ff/3/1",
    "ff/ff/ff",
    "ff/d4/0",
    "ff/4/1",
    "ff/1/0",
    "ff/cc/0",
    "ff/2/10",
    "ff/9/1",
};

static int fd_class[MAX_FD] =
{
    0,0x7,0x7,0x7,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
};

static int fd_subclass[MAX_FD] =
{
    0,0x1,0x1,0x1,0x1,0x2,0x3,0xff,0xd4,0x4,0x1,0xcc,0x2,0x9,
};

static int fd_protocol[MAX_FD] =
{
    0,0x2,0x3,0x4,0x1,0x1,0x1,0xff,0,0x1,0,0,0x10,0x1,
};

static const unsigned char venice_power_on[] = {0x1b, '%','P','u','i','f','p','.','p','o','w','e','r',' ','1',';',
    'u','d','w','.','q','u','i','t',';',0x1b,'%','-','1','2','3','4','5','X' };

static libusb_device *libusb_dev = NULL;       /* libusb device referenced by URI */
static libusb_context *libusb_ctx = NULL;
static libusb_device **libusb_dev_list = NULL;

static file_descriptor fd_table[MAX_FD];       /* usb file descriptors */

/* This function is similar to usb_get_string_simple, but it handles zero returns. */
static int get_string_descriptor(libusb_device_handle *dev_handle, int index, char *buf, size_t buflen)
{
    unsigned char tbuf[255] = {0,};       /* Some devices choke on size > 255 */
    int ret, si, di, cnt=5;

    while (cnt--)
    {
        ret = libusb_control_transfer(dev_handle,
                LIBUSB_ENDPOINT_IN,
                LIBUSB_REQUEST_GET_DESCRIPTOR,
                (LIBUSB_DT_STRING << 8) + index,
                0x409,
                tbuf, sizeof(tbuf), LIBUSB_CONTROL_REQ_TIMEOUT);

        if (ret==0)
        {
            /* This retry is necessary for lj1000 and lj1005. des 12/12/07 */
            BUG("get_string_descriptor zero result, retrying...");
            continue;
        }
        break;
    }

    if (ret < 0)
    {
        BUG("unable get_string_descriptor %d: %m\n", ret);
        return ret;
    }

    if (tbuf[1] != LIBUSB_DT_STRING)
    {
        BUG("invalid get_string_descriptor tag act=%d exp=%d\n", tbuf[1], LIBUSB_DT_STRING);
        return -EIO;
    }

    if (tbuf[0] > ret)
    {
        BUG("invalid get_string_descriptor size act=%d exp=%d\n", tbuf[0], ret);
        return -EFBIG;
    }

    for (di = 0, si = 2; si < tbuf[0]; si += 2)
    {
        if (di >= (buflen - 1))
            break;

        if (tbuf[si + 1])   /* high byte */
            buf[di++] = '0';
        else
            buf[di++] = tbuf[si];
    }

    buf[di] = 0;

    return di;
}

/* Write HP vendor-specific ECP channel message. */
static int write_ecp_channel(file_descriptor *pfd, int value)
{
    libusb_device_handle *hd;
    int interface = pfd->interface;
    int len, stat=1;
    unsigned char byte;

    if (pfd->hd == NULL)
    {
        BUG("invalid write_ecp_channel state\n");
        goto bugout;
    }

    hd = pfd->hd;

    len = libusb_control_transfer(hd,
            LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_INTERFACE, /* bmRequestType */
            LIBUSB_REQUEST_GET_STATUS,        /* bRequest */
            value,        /* wValue */
            interface, /* wIndex */
            &byte, 1, LIBUSB_CONTROL_REQ_TIMEOUT);

    if (len != 1)
    {
        BUG("invalid write_ecp_channel: %m\n");
        goto bugout;
    }

    stat = 0;

bugout:
    return stat;
}

/* Set Cypress USS-725 Bridge Chip to 1284.4 mode. */
static int bridge_chip_up(file_descriptor *pfd)
{
    libusb_device_handle *hd;
    int len, stat=1;
    unsigned char buf[9];
    char nullByte=0;

    if (pfd->hd == NULL)
    {
        BUG("invalid bridge_chip_up state\n");
        goto bugout;
    }

    hd = pfd->hd;

    memset(buf, 0, sizeof(buf));

    /* Read register values. */
    len = libusb_control_transfer(hd,
            LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE, /* bmRequestType */
            LIBUSB_REQUEST_SET_FEATURE,        /* bRequest */
            0,        /* wValue */
            0, /* wIndex */
            buf, sizeof(buf), LIBUSB_CONTROL_REQ_TIMEOUT);
    if (len < 0)
    {
        BUG("invalid write_bridge_up: %m\n");
        goto bugout;
    }

    /* Check for auto ECP mode. */
    if (buf[ECRR] != 0x43)
    {
        /* Place 725 chip in register mode. */
        len = libusb_control_transfer(hd,
                LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE, /* bmRequestType */
                0x04,        /* bRequest */
                0x0758,        /* wValue */
                0, /* wIndex */
                NULL, 0, LIBUSB_CONTROL_REQ_TIMEOUT);
        /* Turn off RLE in auto ECP mode. */
        len = libusb_control_transfer(hd,
                LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE, /* bmRequestType */
                0x04,        /* bRequest */
                0x0a1d,        /* wValue */
                0, /* wIndex */
                NULL, 0, LIBUSB_CONTROL_REQ_TIMEOUT);
        /* Place 725 chip in auto ECP mode. */
        len = libusb_control_transfer(hd,
                LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE, /* bmRequestType */
                0x04,        /* bRequest */
                0x0759,        /* wValue */
                0, /* wIndex */
                NULL, 0, LIBUSB_CONTROL_REQ_TIMEOUT);
        /* Force negotiation. */
        len = libusb_control_transfer(hd,
                LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE, /* bmRequestType */
                0x04,        /* bRequest */
                0x0817,        /* wValue */
                0, /* wIndex */
                NULL, 0, LIBUSB_CONTROL_REQ_TIMEOUT);
        /* Read register values. */
        len = libusb_control_transfer(hd,
                LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE, /* bmRequestType */
                LIBUSB_REQUEST_SET_FEATURE,        /* bRequest */
                0,        /* wValue */
                0, /* wIndex */
                buf, sizeof(buf), LIBUSB_CONTROL_REQ_TIMEOUT);
        if (buf[ECRR] != 0x43)
        {
            BUG("invalid auto ecp mode mode=%d\n", buf[ECRR]);
        }
    }

    /* Reset to ECP channel 0. */
    len = libusb_control_transfer(hd,
            LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE, /* bmRequestType */
            0x04,        /* bRequest */
            0x05ce,        /* wValue */
            0, /* wIndex */
            NULL, 0, LIBUSB_CONTROL_REQ_TIMEOUT);
    musb_write(pfd->fd, &nullByte, 1, HPMUD_EXCEPTION_TIMEOUT);

    /* Switch to ECP channel 77. */
    len = libusb_control_transfer(hd,
            LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE, /* bmRequestType */
            0x04,        /* bRequest */
            0x05cd,        /* wValue */
            0, /* wIndex */
            NULL, 0, LIBUSB_CONTROL_REQ_TIMEOUT);

    stat = 0;

bugout:
    return stat;
}

/* Set Cypress USS-725 Bridge Chip to compatibility mode. */
static int bridge_chip_down(file_descriptor *pfd)
{
    libusb_device_handle *hd;
    int len, stat=1;

    if (pfd->hd == NULL)
    {
        BUG("invalid bridge_chip_down state\n");
        goto bugout;
    }

    hd = pfd->hd;

    len = libusb_control_transfer(hd,
            LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE, /* bmRequestType */
            0x04,        /* bRequest */
            0x080f,        /* wValue */
            0, /* wIndex */
            NULL, 0, LIBUSB_CONTROL_REQ_TIMEOUT);
    if (len < 0)
    {
        BUG("invalid write_bridge_up: %m\n");
        goto bugout;
    }

    stat = 0;

bugout:
    return stat;
}

/* Write HP vendor-specific Setup command. */
static int write_phoenix_setup(file_descriptor *pfd)
{
    libusb_device_handle *hd;
    int len, stat=1;

    if (pfd->hd == NULL)
    {
        BUG("invalid write_phoenix_setup state\n");
        goto bugout;
    }

    hd = pfd->hd;

    len = libusb_control_transfer(hd,
            LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_OTHER, /* bmRequestType */
            0x02,        /* bRequest */
            0,        /* wValue */
            0, /* wIndex */
            NULL, 0, LIBUSB_CONTROL_REQ_TIMEOUT);

    if (len < 0)
    {
        BUG("invalid write_phoenix_setup: %m\n");
        goto bugout;
    }

    stat = 0;

bugout:
    return stat;
}

/* Detach any kernel module that may have claimed specified inteface. */
static int detach(libusb_device_handle *hd, int interface)
{
    int ret ;
    /* If any kernel module has claimed this interface, detach it. */
    ret = libusb_kernel_driver_active (hd, interface);
    DBG("Active kernel driver on interface=%d ret=%d\n", interface, ret);
    if (ret == 1)
    {
        ret = libusb_detach_kernel_driver(hd, interface);
        DBG("Detaching kernel driver on interface=%d ret=%d\n", interface, ret);
        if (ret < 0)
            BUG("could not remove kernel driver interface=%d: %m\n",  interface);
    }
    return 0;
}

/* Get interface descriptor for specified xx/xx/xx protocol. */
static int get_interface(libusb_device *dev, enum FD_ID index, file_descriptor *pfd)
{
    struct libusb_device_descriptor device_desc; /* Current device descriptor */
    struct libusb_config_descriptor *confptr = NULL; /* Pointer to current configuration */
    struct libusb_interface *ifaceptr = NULL; /* Pointer to current interface */
    struct libusb_interface_descriptor *altptr = NULL; /* Pointer to current alternate setting */
    int conf, iface, altset;

    libusb_get_device_descriptor (dev, &device_desc);
    for (conf = 0 ; conf < device_desc.bNumConfigurations; conf++)
    {
        if (libusb_get_config_descriptor(dev, conf, &confptr) != 0)
            continue;
        for (iface = 0, ifaceptr = confptr->interface; iface < confptr->bNumInterfaces; iface++, ifaceptr++)
        {
            for (altset = 0, altptr = ifaceptr->altsetting; altset < ifaceptr->num_altsetting; altset ++, altptr ++)
            {
                if (altptr &&
                        altptr->bInterfaceClass == fd_class[index] &&
                        altptr->bInterfaceSubClass == fd_subclass[index] &&
                        altptr->bInterfaceProtocol == fd_protocol[index])
                {
                    pfd->config=conf;            /* found interface */
                    pfd->interface=iface;
                    pfd->alt_setting=altset;
                    pfd->fd=index;
                    DBG("Found interface conf=%d, iface=%d, altset=%d, index=%d\n", conf, iface, altset, index);

                    libusb_free_config_descriptor(confptr);
                    return 0;
                }
            }
        }
        libusb_free_config_descriptor(confptr);
    }

    return 1;    /* no interface found */
}

/* Get endpoint for specified interface descriptor. */
static int get_ep(libusb_device *dev, int config, int interface, int altset, enum libusb_transfer_type type, enum libusb_endpoint_direction epdir)
{
    struct libusb_config_descriptor *confptr = NULL;
    const struct libusb_interface_descriptor *pi;
    int i, endpoint = -1;

    if (libusb_get_config_descriptor(dev, config, &confptr) != 0)
        goto bugout;

    if (confptr == NULL || confptr->interface == NULL || confptr->interface[interface].altsetting == NULL)
        goto bugout;

    pi = &(confptr->interface[interface].altsetting[altset]);
    for (i=0; i<pi->bNumEndpoints; i++)
    {
        if (pi->endpoint == NULL)
            goto bugout;
        if (pi->endpoint[i].bmAttributes == type)
        {
            if (epdir == LIBUSB_ENDPOINT_IN)
            {
                if (pi->endpoint[i].bEndpointAddress & LIBUSB_ENDPOINT_IN)
                {
                    endpoint = pi->endpoint[i].bEndpointAddress;
                    break;
                }
            }
            else if (epdir == LIBUSB_ENDPOINT_OUT)
            {
                if (!(pi->endpoint[i].bEndpointAddress & LIBUSB_ENDPOINT_IN))
                {
                    endpoint = pi->endpoint[i].bEndpointAddress;
                    break;
                }
            }
        }
    }
    //DBG("get_ep(bmAttributes=%x): bEndpointAddress=%x interface=%x\n", type, endpoint, interface);
bugout:
    libusb_free_config_descriptor(confptr);
    if (endpoint == -1) DBG("get_ep: ERROR! returning -1\n");
    return endpoint; /* no endpoint found */
}

static int get_in_ep(libusb_device *dev, int config, int interface, int altset, enum libusb_transfer_type type)
{
    return get_ep(dev, config, interface, altset, type, LIBUSB_ENDPOINT_IN);
}

static int get_out_ep(libusb_device *dev, int config, int interface, int altset, enum libusb_transfer_type type)
{
    return get_ep(dev, config, interface, altset, type, LIBUSB_ENDPOINT_OUT);
}


static int claim_interface(libusb_device *dev, file_descriptor *pfd)
{
    int stat=1;

    if (pfd->hd != NULL)
        return 0;  /* interface is already claimed */

    libusb_open(dev, &pfd->hd);
    if (pfd->hd ==NULL)
    {
        BUG("invalid usb_open: %m\n");
        goto bugout;
    }
    detach(pfd->hd, pfd->interface);

    if (libusb_claim_interface(pfd->hd, pfd->interface))
    {
        libusb_close(pfd->hd);
        pfd->hd = NULL;
        DBG("invalid claim_interface %s: %m\n", fd_name[pfd->fd]);
        goto bugout;
    }

    if(pfd->alt_setting)
    {
    if (libusb_set_interface_alt_setting(pfd->hd, pfd->interface, pfd->alt_setting))
    {
        libusb_release_interface(pfd->hd, pfd->interface);
        libusb_close(pfd->hd);
        pfd->hd = NULL;
        BUG("invalid set_altinterface %s altset=%d: %m\n", fd_name[pfd->fd], pfd->alt_setting);
        goto bugout;
	    }
    }

    pfd->write_active=0;
    pthread_mutex_init(&pfd->mutex, NULL);
    pthread_cond_init(&pfd->write_done_cond, NULL);

    DBG("claimed %s interface\n", fd_name[pfd->fd]);

    stat=0;

bugout:
    return stat;
}

static int release_interface(file_descriptor *pfd)
{
    if (pfd->hd == NULL)
        return 0;

    if (pfd->write_active)
    {
        BUG("aborting outstanding %s write\n", fd_name[pfd->fd]);
        pthread_cancel(pfd->tid);    /* kill outstanding write */
        pfd->write_active = 0;
    }

    libusb_release_interface(pfd->hd, pfd->interface);
    libusb_close(pfd->hd);
    pfd->hd = NULL;
    pthread_mutex_destroy(&pfd->mutex);
    pthread_cond_destroy(&pfd->write_done_cond);

    DBG("released %s interface\n", fd_name[pfd->fd]);

    return 0;
}

/* Claim any open interface which is valid for device_id and device status. */
static int claim_id_interface(libusb_device *dev)
{
    enum FD_ID i;

    for (i=FD_7_1_2; i!=MAX_FD; i++)
    {
        if (get_interface(dev, i, &fd_table[i]) == 0)
        {
            if (claim_interface(dev, &fd_table[i]))
                continue;  /* interface is busy, try next interface */
            break;  /* done */
        }
    }

    return i;
}

/* See if this usb device and URI match. */
static int is_uri(libusb_device *dev, const char *uri)
{
    libusb_device_handle *hd=NULL;
    struct libusb_device_descriptor devdesc;
    char sz[128], uriModel[128], uriSerial[128], gen[128];
    int r, stat=0;

    libusb_open(dev, &hd);
    if (hd == NULL)
    {
        BUG("invalid usb_open: %m\n");
        goto bugout;
    }

    libusb_get_device_descriptor(dev, &devdesc);
    if (devdesc.idVendor != 0x3f0)
        goto bugout;

    if ((r=get_string_descriptor(hd, devdesc.iProduct, sz, sizeof(sz))) < 0)
    {
        BUG("invalid product id string ret=%d\n", r);
        goto bugout;
    }

    generalize_model(sz, gen, sizeof(gen));

    hpmud_get_uri_model(uri, uriModel, sizeof(uriModel));
    if (strcasecmp(uriModel, gen) != 0)
        goto bugout;

    if ((r=get_string_descriptor(hd, devdesc.iSerialNumber, sz, sizeof(sz))) < 0)
    {
        BUG("invalid serial id string ret=%d\n", r);
        goto bugout;
    }

    if (sz[0])
        generalize_serial(sz, gen, sizeof(gen));
    else
        strcpy(gen, "0");

    get_uri_serial(uri, uriSerial, sizeof(uriSerial));
    if (strcmp(uriSerial, gen) != 0)
        goto bugout;

    stat = 1;    /* found usb device that matches uri */

bugout:
    if (hd != NULL)
        libusb_close(hd);

    return stat;
}

/* See if this usb device and serial number match. Return model if match. */
static int is_serial(libusb_device *dev, const char *sn, char *model, int model_size)
{
    libusb_device_handle *hd=NULL;
    struct libusb_device_descriptor devdesc;
    char sz[128];
    char gen[128];
    int r, stat=0;

    libusb_open(dev, &hd);
    if (hd == NULL)
    {
        BUG("invalid usb_open: %m\n");
        goto bugout;
    }

    libusb_get_device_descriptor(dev, &devdesc);
    if (devdesc.idVendor != 0x3f0)
        goto bugout;      /* not a HP product */

    if ((r=get_string_descriptor(hd, devdesc.iSerialNumber, sz, sizeof(sz))) < 0)
    {
        BUG("invalid serial id string ret=%d\n", r);
        goto bugout;
    }
    if (sz[0])
        generalize_serial(sz, gen, sizeof(gen));
    else
        strcpy(gen, "0");

    if (strncmp(sn, gen, sizeof(gen)) != 0)
        goto bugout;  /* match failed */

    if ((r=get_string_descriptor(hd, devdesc.iProduct, sz, sizeof(sz))) < 0)
    {
        BUG("invalid product id string ret=%d\n", r);
        goto bugout;
    }
    generalize_model(sz, model, model_size);

    stat = 1;    /* found usb device that matches sn */

bugout:
    if (hd != NULL)
        libusb_close(hd);

    return stat;
}

static libusb_device *get_libusb_device(const char *uri)
{
    libusb_device *dev = NULL; /* Current device */
    struct libusb_device_descriptor devdesc; /* Current device descriptor */
    struct libusb_config_descriptor *confptr = NULL; /* Pointer to current configuration */
    const struct libusb_interface *ifaceptr = NULL; /* Pointer to current interface */
    const struct libusb_interface_descriptor *altptr = NULL; /* Pointer to current alternate setting */
    int numdevs = 0;        /* number of connected devices */
    int i, conf, iface, altset ;

    i = libusb_init(&libusb_ctx);
    if (i) goto bugout;
    numdevs = libusb_get_device_list(libusb_ctx, &libusb_dev_list);
    for (i=0; i< numdevs; i++)
    {
        dev = libusb_dev_list[i];
        memset(&devdesc, 0, sizeof(devdesc));
        libusb_get_device_descriptor (dev, &devdesc);

        if (!devdesc.bNumConfigurations || !devdesc.idVendor || !devdesc.idProduct)
            continue;

        if (devdesc.idVendor != 0x3f0) /*Not a HP device*/
            continue;

        for (conf = 0; conf < devdesc.bNumConfigurations; conf++)
        {
            if (libusb_get_config_descriptor (dev, conf, &confptr) < 0)
                continue;
            for (iface = 0, ifaceptr = confptr->interface; iface < confptr->bNumInterfaces; iface ++, ifaceptr ++)
            {
                for (altset = 0, altptr = ifaceptr->altsetting; altset < ifaceptr->num_altsetting; altset++, altptr++)
                {
                    if (  ((altptr->bInterfaceClass == LIBUSB_CLASS_PRINTER) && (altptr->bInterfaceSubClass == 1)) ||\
                          ((altptr->bInterfaceClass == LIBUSB_CLASS_VENDOR_SPEC) && (altptr->bInterfaceSubClass == 0xcc)) )
                    {
                        if (is_uri(dev, uri))
                        {
                            libusb_free_config_descriptor(confptr);
                            return dev;  /* found usb device that matches uri */
                        }
                    }
                }
            }
            libusb_free_config_descriptor(confptr); confptr = NULL;
        }//end for conf
    }
bugout:
    if (confptr)
        libusb_free_config_descriptor(confptr);

    return NULL;
}

static int device_id(int fd, unsigned char *buffer, int size)
{
    libusb_device_handle *hd;
    int config,interface,alt;
    int len=0, rlen, maxSize;

    hd = fd_table[fd].hd;
    config = fd_table[fd].config;
    interface = fd_table[fd].interface;
    alt = fd_table[fd].alt_setting;

    if (hd == NULL)
    {
        BUG("invalid device_id state\n");
        goto bugout;
    }

    maxSize = (size > 1024) ? 1024 : size;   /* RH8 has a size limit for device id (usb) */

    rlen = libusb_control_transfer(hd,
            LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE, /* bmRequestType */
            LIBUSB_REQUEST_GET_STATUS,        /* bRequest */
            config,        /* wValue */
            interface, /* wIndex */    /* note firmware does not follow the USB Printer Class specification for wIndex */
            buffer, maxSize, LIBUSB_CONTROL_REQ_TIMEOUT);

    if (rlen < 0)
    {
        BUG("invalid deviceid ret=%d: %m\n", rlen);
        goto bugout;
    }

    len = ntohs(*(short *)buffer);
    if (len > (size-1))
        len = size-1;   /* leave byte for zero termination */
    if (len > 2)
        len -= 2;
    memcpy(buffer, buffer+2, len);    /* remove length */
    buffer[len]=0;
    DBG("read actual device_id successfully fd=%d len=%d\n", fd, len);

bugout:
    return len; /* length does not include zero termination */
}

static int device_status(int fd, unsigned int *status)
{
    libusb_device_handle *hd;
    int interface;
    int len, stat=1;
    unsigned char byte;

    hd = fd_table[fd].hd;
    interface = fd_table[fd].interface;

    if (hd == NULL)
    {
        BUG("invalid device_status state\n");
        goto bugout;
    }

    len = libusb_control_transfer(hd,
            LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE, /* bmRequestType */
            LIBUSB_REQUEST_CLEAR_FEATURE,        /* bRequest */
            0,        /* wValue */
            interface, /* wIndex */
            &byte, 1, LIBUSB_CONTROL_REQ_TIMEOUT);

    if (len < 0)
    {
        BUG("invalid device_status: %m\n");
        goto bugout;
    }

    *status = (unsigned int)byte;
    stat = 0;
    DBG("read actual device_status successfully fd=%d\n", fd);

bugout:
    return stat;
}

/* Get VStatus from S-field. */
static int sfield_printer_state(const char *id)
{
    char *pSf;
    int vstatus=0, ver;

    if ((pSf = strstr(id, ";S:")) == NULL)
    {
        BUG("invalid S-field\n");
        return vstatus;
    }

    /* Valid S-field, get version number. */
    pSf+=3;
    ver = 0;
    HEX2INT(*pSf, ver);
    pSf++;
    ver = ver << 4;
    HEX2INT(*pSf, ver);
    pSf++;

    /* Position pointer to printer state subfield. */
    switch (ver)
    {
        case 0:
        case 1:
        case 2:
            pSf+=12;
            break;
        case 3:
            pSf+=14;
            break;
        case 4:
            pSf+=18;
            break;
        default:
            BUG("unknown S-field version=%d\n", ver);
            pSf+=12;
            break;
    }

    /* Extract VStatus.*/
    vstatus = 0;
    HEX2INT(*pSf, vstatus);
    pSf++;
    vstatus = vstatus << 4;
    HEX2INT(*pSf, vstatus);

    return vstatus;
}

/*
 * Power up printer if necessary. Most all-in-ones have no power down state (ie: OJ K80), so they are already powered up.
 * Newer single function printers power-up with the print job. May be called by other mud_device.
 */
int __attribute__ ((visibility ("hidden"))) power_up(mud_device *pd, int fd)
{
    const char *pSf;

    if ((pSf = strstr(pd->id, "CMD:LDL")) != NULL)
        return 0;   /* crossbow don't do power-up */

    if ((pSf = strstr(pd->id, ";S:")) != NULL)
    {
        if (sfield_printer_state(pd->id) != 3)
            return 0;     /* already powered up */
    }
    else if ((pSf = strstr(pd->id, "VSTATUS:")) != NULL)
    {
        /* DJ895C returns $XB0$XC0 (unknown pens) when powered off. */
        if (!(strstr(pSf+8, "OFFF") || strstr(pSf+8, "PWDN") || strstr(pSf+8, "$X")))
            return 0;   /* already powered up */
    }
    else
        return 0;  /* must be laserjet, don't do power-up */

    (pd->vf.write)(fd, venice_power_on, sizeof(venice_power_on), HPMUD_EXCEPTION_TIMEOUT);
    sleep(2);

    return 0;
}

static int libusb_bulk_read(libusb_device_handle *dev, int ep, char *bytes, int size, int timeout)
{
    int actual_len = 0;

    libusb_bulk_transfer(dev, ep, (unsigned char*)bytes, size, &actual_len, timeout);
    return actual_len ;
}

static int libusb_bulk_write(libusb_device_handle *dev, int ep, char *bytes, int size, int timeout)
{
    int actual_len = 0;

    libusb_bulk_transfer(dev, ep, (unsigned char*)bytes, size, &actual_len, timeout);
    return actual_len ;
}

/* Create channel object given the requested socket id and service name. */
static int new_channel(mud_device *pd, int index, const char *sn)
{
    int stat=1;

    /* Check for existing name service already open. */
    if (pd->channel[index].client_cnt)
    {
        BUG("%s channel=%d is busy, used by [%d], clientCnt=%d channelCnt=%d\n", sn, index, pd->channel[index].pid, pd->channel[index].client_cnt, pd->channel_cnt);
        goto bugout;
    }

    if (index == HPMUD_EWS_CHANNEL || index == HPMUD_EWS_LEDM_CHANNEL ||
            index == HPMUD_SOAPSCAN_CHANNEL || index == HPMUD_SOAPFAX_CHANNEL ||
            index == HPMUD_MARVELL_SCAN_CHANNEL || index == HPMUD_MARVELL_FAX_CHANNEL ||
            index == HPMUD_LEDM_SCAN_CHANNEL || index == HPMUD_MARVELL_EWS_CHANNEL ||
            index == HPMUD_IPP_CHANNEL || index == HPMUD_IPP_CHANNEL2 || index == HPMUD_ESCL_SCAN_CHANNEL) {
        pd->channel[index].vf = musb_comp_channel_vf;
    }
    else if (pd->io_mode == HPMUD_RAW_MODE || pd->io_mode == HPMUD_UNI_MODE) {
        pd->channel[index].vf = musb_raw_channel_vf;
    }
    else if (pd->io_mode == HPMUD_MLC_GUSHER_MODE || pd->io_mode == HPMUD_MLC_MISER_MODE) {
        pd->channel[index].vf = musb_mlc_channel_vf;
    }
    else {
        pd->channel[index].vf = musb_dot4_channel_vf;
    }

    pd->channel[index].index = index;
    pd->channel[index].client_cnt = 1;
    pd->channel[index].sockid = index;   /* static socket id is valid for MLC but not 1284.4 */
    pd->channel[index].pid = getpid();
    pd->channel[index].dindex = pd->index;
    pd->channel[index].fd = 0;
    strcpy(pd->channel[index].sn, sn);
    pd->channel_cnt++;

    stat = 0;
    DBG("new %s channel=%d clientCnt=%d channelCnt=%d\n", sn, index, pd->channel[index].client_cnt, pd->channel_cnt);

bugout:
    return stat;
}

/* Remove channel object given the channel decriptor. */
static int del_channel(mud_device *pd, mud_channel *pc)
{
    pc->client_cnt--;

    if (pc->client_cnt <= 0)
    {
        pd->channel_cnt--;
    }
    DBG("removed %s channel=%d clientCnt=%d channelCnt=%d\n", pc->sn, pc->index, pc->client_cnt, pd->channel_cnt);
    return 0;
}

static void write_thread(file_descriptor *pfd)
{
    int ep = -1;

    pthread_detach(pthread_self());

    ep = get_out_ep(libusb_dev, pfd->config, pfd->interface, pfd->alt_setting, LIBUSB_TRANSFER_TYPE_BULK);
    if (ep < 0)
    {
        BUG("invalid bulk out endpoint\n");
        pfd->write_return = -ENOTCONN;
        goto bugout;
    }

    /* Wait forever for write to complete (actually 72 hours in ms). */
    pfd->write_return = libusb_bulk_write (pfd->hd, ep, (char *)pfd->write_buf, pfd->write_size, 72*3600*1000);

bugout:
    pthread_mutex_lock(&pfd->mutex);
    pfd->write_buf = NULL;
    pthread_cond_signal(&pfd->write_done_cond);   /* signal write is complete */
    pthread_mutex_unlock(&pfd->mutex);

    return;
}

/*********************************************************************************************************************************
 * USB mud_device functions.
 */

int __attribute__ ((visibility ("hidden"))) musb_write(int fd, const void *buf, int size, int usec)
{
    int len=-EIO;

    if (fd_table[fd].hd == NULL)
    {
        BUG("invalid musb_write state\n");
        goto bugout;
    }

#if 1
    struct timeval now;
    struct timespec timeout;
    int ret;
    /* If write is still active, probably OOP condition, don't kick off a new write. */
    if (!fd_table[fd].write_active)
    {
        fd_table[fd].write_active = 1;
        fd_table[fd].write_buf = buf;
        fd_table[fd].write_size = size;

        /* Create usb_bulk_write thread so we can use our own timeout. Otherwise we cannot handle OOP condition. */
        if (pthread_create(&fd_table[fd].tid, NULL, (void *(*)(void*))write_thread, (void *)&fd_table[fd]) != 0)
        {
            BUG("unable to creat write_thread: %m\n");
            goto bugout; /* bail */
        }
    }
    /* Wait for write to complete. */
    pthread_mutex_lock(&fd_table[fd].mutex);
    gettimeofday(&now, NULL);
    now.tv_usec += usec;
    now.tv_sec += now.tv_usec / 1000000;
    now.tv_usec %= 1000000;
    timeout.tv_sec = now.tv_sec;
    timeout.tv_nsec = now.tv_usec * 1000;
    ret = 0;
    while (fd_table[fd].write_buf && ret != ETIMEDOUT)
    {
        ret = pthread_cond_timedwait(&fd_table[fd].write_done_cond, &fd_table[fd].mutex, &timeout);
    }
    pthread_mutex_unlock(&fd_table[fd].mutex);
    if (ret == ETIMEDOUT)
    {
        len = -ETIMEDOUT;     /* write timeout, let client know */
        goto bugout;
    }

    fd_table[fd].write_active = 0;

    len = fd_table[fd].write_return;
#else
    int ep;
    if ((ep = get_out_ep(libusb_dev, fd_table[fd].config, fd_table[fd].interface, fd_table[fd].alt_setting, LIBUSB_TRANSFER_TYPE_BULK)) < 0)
    {
        BUG("invalid bulk out endpoint\n");
        goto bugout;
    }

    len = libusb_bulk_write(fd_table[fd].hd, ep, (char *)buf, size, usec);
#endif

    if (len < 0)
    {
        BUG("bulk_write failed buf=%p size=%d len=%d: %m\n", buf, size, len);
        goto bugout;
    }

    DBG_DUMP(buf, len < 512 ? len : 512);

bugout:
    return len;
}

int __attribute__ ((visibility ("hidden"))) musb_read(int fd, void *buf, int size, int usec)
{
    struct timeval t1, t2;
    int total_usec, tmo_usec=usec;
    int len=-EIO, ep;

    if (fd_table[fd].hd == NULL)
    {
        BUG("invalid musb_read state\n");
        goto bugout;
    }

    gettimeofday (&t1, NULL);     /* get start time */

    ep = get_in_ep(libusb_dev, fd_table[fd].config, fd_table[fd].interface, fd_table[fd].alt_setting, LIBUSB_TRANSFER_TYPE_BULK);
    if (ep < 0)
    {
        BUG("invalid bulk in endpoint\n");
        goto bugout;
    }

    while (1)
    {
        len = libusb_bulk_read(fd_table[fd].hd, ep, (char *)buf, size, tmo_usec/1000);

        if (len == -ETIMEDOUT)
            goto bugout;

        if (len < 0)
        {
            BUG("bulk_read failed: %m\n");
            goto bugout;
        }

        if (len == 0)
        {
            /* Bulk_read has a timeout, but bulk_read can return zero byte packet(s), so we must use our own timeout here. */
            gettimeofday(&t2, NULL);   /* get current time */

            total_usec = (t2.tv_sec - t1.tv_sec)*1000000;
            total_usec += (t2.tv_usec > t1.tv_usec) ? t2.tv_usec - t1.tv_usec : t1.tv_usec - t2.tv_usec;
            if (total_usec > usec)
            {
                len = -ETIMEDOUT;   /* timeout */
                goto bugout;
            }
            tmo_usec = usec - total_usec;    /* decrease timeout */
            continue;
        }

        break;
    }

    //DBG("read fd=%d len=%d size=%d usec=%d ep=%d\n", fd, len, size, usec, ep);
    DBG_DUMP(buf, len < 32 ? len : 32);

bugout:
    return len;
}

enum HPMUD_RESULT __attribute__ ((visibility ("hidden"))) musb_open(mud_device *pd)
{
    int len=0, fd=0;
    enum HPMUD_RESULT stat = HPMUD_R_IO_ERROR;

    /* Find usb device for specified uri. */
    if ((libusb_dev = get_libusb_device(pd->uri)) == NULL)
    {
        BUG("unable to open %s\n", pd->uri);
        goto bugout;
    }

    pthread_mutex_lock(&pd->mutex);

    if (pd->id[0] == 0)
    {
        /* First client. */
        if ((fd = claim_id_interface(libusb_dev)) == MAX_FD)
        {
            stat = HPMUD_R_DEVICE_BUSY;
            goto blackout;
        }

        len = device_id(fd, (unsigned char *)pd->id, sizeof(pd->id));  /* get new copy and cache it  */

        if (len > 0 && is_hp(pd->id))
            power_up(pd, fd);

        release_interface(&fd_table[fd]);

        if (len == 0)
            goto blackout;

        pd->open_fd = fd;
    }

    stat = HPMUD_R_OK;

blackout:
    pthread_mutex_unlock(&pd->mutex);

bugout:
    return stat;
}

enum HPMUD_RESULT __attribute__ ((visibility ("hidden"))) musb_close(mud_device *pd)
{
    int i;
    enum HPMUD_RESULT stat = HPMUD_R_OK;

    pthread_mutex_lock(&pd->mutex);

    for (i=1; i<MAX_FD; i++)
    {
        if (fd_table[i].hd != NULL)
            release_interface(&fd_table[i]);
    }

    pd->id[0] = 0;

    if (libusb_dev)
    {
        libusb_free_device_list(libusb_dev_list, 1);
        libusb_exit(libusb_ctx);
        libusb_ctx = NULL;
        libusb_dev_list = NULL;
        libusb_dev = NULL ;
    }

    pthread_mutex_unlock(&pd->mutex);

    return stat;
}

enum HPMUD_RESULT __attribute__ ((visibility ("hidden"))) musb_get_device_id(mud_device *pd, char *buf, int size, int *len)
{
    int i, fd=FD_NA;
    enum HPMUD_RESULT stat = HPMUD_R_DEVICE_BUSY;

    *len=0;

    pthread_mutex_lock(&pd->mutex);

    if (pd->io_mode == HPMUD_DOT4_BRIDGE_MODE || pd->io_mode == HPMUD_UNI_MODE)
    {
        *len = strlen(pd->id);  /* usb/parallel bridge chip, use cached copy */
    }
    else
    {
        /* See if any interface is already claimed. */
        for (i=1; i<MAX_FD; i++)
        {
            if (fd_table[i].hd != NULL)
            {
                fd = i;
                break;
            }
        }

        if (fd == FD_NA)
        {
            /* Device not in use. Claim interface, but release for other processes. */
            if ((fd = claim_id_interface(libusb_dev)) != MAX_FD)
            {
                *len = device_id(fd, (unsigned char *)pd->id, sizeof(pd->id));  /* get new copy and cache it  */
                release_interface(&fd_table[fd]);
            }
            else
            {
                /* Device is in use by another process, return cache copy. */
                *len = strlen(pd->id);
            }
        }
        else
        {
            /* Device in use by current process, leave interface up. Other processes are blocked. */
            *len = device_id(fd, (unsigned char *)pd->id, sizeof(pd->id));  /* get new copy and cache it  */
        }
    }

    if (*len)
    {
        memcpy(buf, pd->id, *len > size ? size : *len);
        stat = HPMUD_R_OK;
    }

    pthread_mutex_unlock(&pd->mutex);
    return stat;
}

enum HPMUD_RESULT __attribute__ ((visibility ("hidden"))) musb_get_device_status(mud_device *pd, unsigned int *status)
{
    int i, fd=FD_NA;
    enum HPMUD_RESULT stat = HPMUD_R_DEVICE_BUSY;
    int r=1;

    pthread_mutex_lock(&pd->mutex);

    if (pd->io_mode == HPMUD_DOT4_BRIDGE_MODE || pd->io_mode == HPMUD_UNI_MODE)
        *status = NFAULT_BIT;   /* usb/parallel bridge chip, fake status */
    else
    {
        /* See if any interface is already claimed. */
        for (i=1; i<MAX_FD; i++)
        {
            if (fd_table[i].hd != NULL)
            {
                fd = i;
                break;
            }
        }

        if (fd == FD_NA)
        {
            /* Device not in use. Claim interface, but release for other processes. */
            if ((fd = claim_id_interface(libusb_dev)) != MAX_FD)
            {
                r = device_status(fd, status);
                release_interface(&fd_table[fd]);
            }
        }
        else
        {
            /* Device in use by current process, leave interface up. Other processes are blocked. */
            r = device_status(fd, status);
        }
    }

    pthread_mutex_unlock(&pd->mutex);

    if (r != 0)
        goto bugout;

    stat = HPMUD_R_OK;

bugout:
    return stat;
}

enum HPMUD_RESULT __attribute__ ((visibility ("hidden"))) musb_channel_write(mud_device *pd, mud_channel *pc, const void *buf, int length, int sec_timeout, int *bytes_wrote)
{
    enum HPMUD_RESULT stat;

    pthread_mutex_lock(&pd->mutex);
    stat  = (pc->vf.channel_write)(pc, buf, length, sec_timeout, bytes_wrote);
    pthread_mutex_unlock(&pd->mutex);
    return stat;
}

enum HPMUD_RESULT __attribute__ ((visibility ("hidden"))) musb_channel_read(mud_device *pd, mud_channel *pc, void *buf, int length, int sec_timeout, int *bytes_read)
{
    enum HPMUD_RESULT stat;

    if (pd->io_mode == HPMUD_UNI_MODE)
    {
        stat = HPMUD_R_INVALID_STATE;
        BUG("invalid channel_read io_mode=%d\n", pd->io_mode);
        goto bugout;
    }

    pthread_mutex_lock(&pd->mutex);
    stat  = (pc->vf.channel_read)(pc, buf, length, sec_timeout, bytes_read);
    pthread_mutex_unlock(&pd->mutex);

bugout:
    return stat;
}

enum HPMUD_RESULT __attribute__ ((visibility ("hidden"))) musb_channel_open(mud_device *pd, const char *sn, HPMUD_CHANNEL *cd)
{
    int index;
    enum HPMUD_RESULT stat;

    /* Check for valid service requests. */
    if ((stat = service_to_channel(pd, sn, &index)) != HPMUD_R_OK)
        goto bugout;

    pthread_mutex_lock(&pd->mutex);

    if (new_channel(pd, index, sn))
    {
        stat = HPMUD_R_DEVICE_BUSY;
    }
    else
    {
        if ((stat = (pd->channel[index].vf.open)(&pd->channel[index])) != HPMUD_R_OK)  /* call transport specific open */
            del_channel(pd, &pd->channel[index]);   /* open failed, cleanup */
        else
            *cd = index;
    }

    pthread_mutex_unlock(&pd->mutex);

bugout:
    return stat;
}

enum HPMUD_RESULT __attribute__ ((visibility ("hidden"))) musb_channel_close(mud_device *pd, mud_channel *pc)
{
    enum HPMUD_RESULT stat = HPMUD_R_OK;

    pthread_mutex_lock(&pd->mutex);
    stat = (pc->vf.close)(pc);      /* call trasport specific close */
    del_channel(pd, pc);
    pthread_mutex_unlock(&pd->mutex);

    return stat;
}

/*******************************************************************************************************************************
 * USB raw_channel functions.
 */

enum HPMUD_RESULT __attribute__ ((visibility ("hidden"))) musb_raw_channel_open(mud_channel *pc)
{
    int fd = FD_7_1_2;
    enum HPMUD_RESULT stat = HPMUD_R_DEVICE_BUSY;

    get_interface(libusb_dev, fd, &fd_table[fd]);

    if (claim_interface(libusb_dev, &fd_table[fd]))
        goto bugout;

    pc->fd = fd;

    stat = HPMUD_R_OK;

bugout:
    return stat;
}

enum HPMUD_RESULT __attribute__ ((visibility ("hidden"))) musb_raw_channel_close(mud_channel *pc)
{
    int fd = pc->fd;

    // For New laserjet devices like Tsunami, end point was getting stall or halted, hence clearing it
    int ep = -1;

    if (( ep = get_in_ep(libusb_dev, fd_table[fd].config, fd_table[fd].interface, fd_table[fd].alt_setting, LIBUSB_TRANSFER_TYPE_BULK)) >= 0)
    {
		//libusb_clear_halt(fd_table[fd].hd,  ep);
    }

    if (( ep = get_out_ep(libusb_dev, fd_table[fd].config, fd_table[fd].interface, fd_table[fd].alt_setting, LIBUSB_TRANSFER_TYPE_BULK)) >= 0)
    {
		//libusb_clear_halt(fd_table[fd].hd,  ep);
    }
    release_interface(&fd_table[fd]);

    pc->fd = 0;

    return HPMUD_R_OK;
}

enum HPMUD_RESULT __attribute__ ((visibility ("hidden"))) musb_raw_channel_write(mud_channel *pc, const void *buf, int length, int sec_timeout, int *bytes_wrote)
{
    int len, size, total=0;
    enum HPMUD_RESULT stat = HPMUD_R_IO_ERROR;

    *bytes_wrote=0;
    size = length;

    while (size > 0)
    {
        len = (msp->device[pc->dindex].vf.write)(pc->fd, buf+total, size, sec_timeout*1000000);
        if (len < 0)
        {
            if (len == -ETIMEDOUT)
            {
                stat = HPMUD_R_IO_TIMEOUT;
                if (sec_timeout >= HPMUD_EXCEPTION_SEC_TIMEOUT)
                    BUG("unable to write data %s: %d second io timeout\n", msp->device[pc->dindex].uri, sec_timeout);
            }
            else
                BUG("unable to write data (len = %d) %s: %m\n", msp->device[pc->dindex].uri, len);
            goto bugout;
        }
		if(len == 0 && size > 0)
		{
			stat = HPMUD_R_IO_ERROR;
			goto bugout;	
		}
        size-=len;
        total+=len;
        *bytes_wrote+=len;
    }

    stat = HPMUD_R_OK;

bugout:
    return stat;
}

/*
 * Channel_read() tries to read "length" bytes from the peripheral. The returned read count may be zero
 * (timeout, no data available), less than "length" or equal "length".
 */
enum HPMUD_RESULT __attribute__ ((visibility ("hidden"))) musb_raw_channel_read(mud_channel *pc, void *buf, int length, int sec_timeout, int *bytes_read)
{
    int len=0, usec;
    enum HPMUD_RESULT stat = HPMUD_R_IO_ERROR;

    *bytes_read = 0;

    if (sec_timeout==0)
        usec = 1000;       /* minmum timeout is 1ms for libusb 0.1.12, hangs forever with zero */
    else
        usec = sec_timeout*1000000;

    len = (msp->device[pc->dindex].vf.read)(pc->fd, buf, length, usec);
    if (len < 0)
    {
        if (len == -ETIMEDOUT)
        {
            stat = HPMUD_R_IO_TIMEOUT;
            if (sec_timeout >= HPMUD_EXCEPTION_SEC_TIMEOUT)
                BUG("unable to read data %s: %d second io timeout\n", msp->device[pc->dindex].uri, sec_timeout);
        }
        else
            BUG("unable to read data %s: %m\n", msp->device[pc->dindex].uri);
        goto bugout;
    }

    *bytes_read = len;
    stat = HPMUD_R_OK;

bugout:
    return stat;
}

/*******************************************************************************************************************************
 * USB comp_channel functions.
 */

enum HPMUD_RESULT __attribute__ ((visibility ("hidden"))) musb_comp_channel_open(mud_channel *pc)
{
    int fd;
    enum HPMUD_RESULT stat = HPMUD_R_DEVICE_BUSY;

    /* Get requested composite interface. */
    switch (pc->index)
    {
        case HPMUD_EWS_CHANNEL:
            fd = FD_ff_1_1;
            break;
        case HPMUD_EWS_LEDM_CHANNEL:
            fd = FD_ff_4_1;
            break;
        case HPMUD_SOAPSCAN_CHANNEL:
            fd = FD_ff_2_1;
            break;
        case HPMUD_SOAPFAX_CHANNEL:
            fd = FD_ff_3_1;
            break;
        case HPMUD_MARVELL_SCAN_CHANNEL:
            fd = FD_ff_ff_ff;
            break;
        case HPMUD_MARVELL_FAX_CHANNEL:  //using vendor specific C/S/P codes for fax too
            fd = FD_ff_1_0;
            break;
        case HPMUD_LEDM_SCAN_CHANNEL:  //using vendor specific C/S/P codes for fax too
        case HPMUD_ESCL_SCAN_CHANNEL:
            fd = FD_ff_cc_0;
            break;
        case HPMUD_MARVELL_EWS_CHANNEL:
            fd = FD_ff_2_10;
            break;
        case HPMUD_IPP_CHANNEL:
            fd = FD_7_1_4;
            break;
        case HPMUD_IPP_CHANNEL2:
            fd = FD_ff_9_1;
            break;
        default:
            stat = HPMUD_R_INVALID_SN;
            BUG("invalid %s channel=%d\n", pc->sn, pc->index);
            goto bugout;
            break;
    }

    if (get_interface(libusb_dev, fd, &fd_table[fd]))
    {
        stat = HPMUD_R_INVALID_SN;
        BUG("invalid %s channel=%d\n", pc->sn, pc->index);
        goto bugout;
    }

    if (claim_interface(libusb_dev, &fd_table[fd]))
        goto bugout;

    pc->fd = fd;

    stat = HPMUD_R_OK;

bugout:
    return stat;
}

/*******************************************************************************************************************************
 * USB mlc_channel functions.
 */

enum HPMUD_RESULT __attribute__ ((visibility ("hidden"))) musb_mlc_channel_open(mud_channel *pc)
{
    mud_device *pd = &msp->device[pc->dindex];
    enum FD_ID fd;
    enum HPMUD_RESULT stat = HPMUD_R_IO_ERROR;

    /* Initialize MLC transport if this is the first MLC channel. */
    if (pd->channel_cnt==1)
    {
        if (get_interface(libusb_dev, FD_7_1_3, &fd_table[FD_7_1_3]) == 0 && claim_interface(libusb_dev, &fd_table[FD_7_1_3]) == 0)
            fd = FD_7_1_3;    /* mlc, dot4 */
        else if (get_interface(libusb_dev, FD_ff_ff_ff, &fd_table[FD_ff_ff_ff]) == 0 && claim_interface(libusb_dev, &fd_table[FD_ff_ff_ff]) == 0)
            fd = FD_ff_ff_ff;   /* mlc, dot4 */
        else if (get_interface(libusb_dev, FD_ff_d4_0, &fd_table[FD_ff_d4_0]) == 0 && claim_interface(libusb_dev, &fd_table[FD_ff_d4_0]) == 0)
            fd = FD_ff_d4_0;   /* mlc, dot4 */
        else if (get_interface(libusb_dev, FD_7_1_2, &fd_table[FD_7_1_2]) == 0 && claim_interface(libusb_dev, &fd_table[FD_7_1_2]) == 0)
            fd = FD_7_1_2;    /* raw, mlc, dot4 */
        else
        {
            stat = HPMUD_R_DEVICE_BUSY;
            goto bugout;
        }

        if (fd == FD_7_1_2)
        {
            /* Emulate 7/1/3 on 7/1/2 using vendor-specific ECP channel-77. */
            if (write_ecp_channel(&fd_table[fd], 77))
                goto bugout;
        }

        unsigned int i;

        /* MLC initialize */
        if (MlcInit(pc, fd) != 0)
            goto bugout;

        /* Reset transport attributes for all channels. */
        for (i=0; i<HPMUD_CHANNEL_MAX; i++)
            memset(&pd->channel[i].ta, 0 , sizeof(transport_attributes));

        pd->mlc_fd = fd;
        pd->mlc_up=1;

    } /* if (pDev->ChannelCnt==1) */

    if (MlcConfigSocket(pc, pd->mlc_fd))
        goto bugout;

    if (MlcOpenChannel(pc, pd->mlc_fd))
        goto bugout;

    pc->rcnt = pc->rindex = 0;

    stat = HPMUD_R_OK;

bugout:
    return stat;
}

enum HPMUD_RESULT __attribute__ ((visibility ("hidden"))) musb_mlc_channel_close(mud_channel *pc)
{
    mud_device *pd = &msp->device[pc->dindex];
    unsigned char nullByte=0;
    enum HPMUD_RESULT stat = HPMUD_R_OK;

    if (pd->mlc_up)
    {
        if (MlcCloseChannel(pc, pd->mlc_fd))
            stat = HPMUD_R_IO_ERROR;
    }

    /* Remove MLC transport if this is the last MLC channel. */
    if (pd->channel_cnt==1)
    {
        if (pd->mlc_up)
        {
            if (MlcExit(pc, pd->mlc_fd))
                stat = HPMUD_R_IO_ERROR;
        }
        pd->mlc_up=0;

        if (pd->mlc_fd == FD_7_1_2)
        {
            write_ecp_channel(&fd_table[pd->mlc_fd], 78);
            (pd->vf.write)(pd->mlc_fd, &nullByte, 1, HPMUD_EXCEPTION_TIMEOUT);
            write_ecp_channel(&fd_table[pd->mlc_fd], 0);
        }

        release_interface(&fd_table[pd->mlc_fd]);

        /* Delay for back-to-back scanning using scanimage (OJ 7110, OJ d135). */
        sleep(1);
    }

    return stat;
}

enum HPMUD_RESULT __attribute__ ((visibility ("hidden"))) musb_mlc_channel_write(mud_channel *pc, const void *buf, int length, int sec_timeout, int *bytes_wrote)
{
    mud_device *pd = &msp->device[pc->dindex];
    int ret, len, size, dlen, total=0;
    enum HPMUD_RESULT stat = HPMUD_R_IO_ERROR;

    *bytes_wrote=0;
    size = length;
    dlen = pc->ta.h2psize - sizeof(MLCHeader);
    while (size > 0)
    {
        len = (size > dlen) ? dlen : size;

        if (pc->ta.h2pcredit == 0 && pd->io_mode == HPMUD_MLC_MISER_MODE)
        {
            if (MlcCreditRequest(pc, pd->mlc_fd, 1))  /* Miser flow control */
            {
                BUG("invalid MlcCreditRequest from peripheral\n");
                goto bugout;
            }
        }

        if (pc->ta.h2pcredit == 0)
        {
            ret = MlcReverseCmd(pc, pd->mlc_fd);
            if (pc->ta.h2pcredit == 0)
            {
                if (ret == 0)
                    continue;  /* Got a reverse command, but no MlcCredit, try again. */

                if (pd->io_mode != HPMUD_MLC_MISER_MODE)
                {
                    /* If miser flow control works for this device, set "miser" in models.dat. */
                    BUG("invalid MlcCredit from peripheral, trying miser\n");
                    pd->io_mode = HPMUD_MLC_MISER_MODE;
                    continue;
                }

                BUG("invalid MlcCredit from peripheral\n");
                goto bugout;
            }
        }

        if (MlcForwardData(pc, pd->mlc_fd, buf+total, len, sec_timeout*1000000))
        {
            goto bugout;
        }

        pc->ta.h2pcredit--;
        size-=len;
        total+=len;
        *bytes_wrote+=len;
    }

    stat = HPMUD_R_OK;

bugout:
    return stat;
}

/*
 * Mlc_channel_read() tries to read "length" bytes from the peripheral. ReadData() reads data in packet size chunks.
 * The returned read count may be zero (timeout, no data available), less than "length" or equal "length".
 *
 * Mlc_channel_read() may read more the "length" if the data packet is greater than "length". For this case the
 * return value will equal "length" and the left over data will be buffered for the next ReadData() call.
 *
 * The "timeout" specifies how many seconds to wait for a data packet. Once the read of the data packet has
 * started the "timeout" is no longer used.
 *
 * Note, if a "timeout" occurs one peripheral to host credit is left outstanding. Which means the peripheral
 * can send unsolicited data later.
 */
enum HPMUD_RESULT __attribute__ ((visibility ("hidden"))) musb_mlc_channel_read(mud_channel *pc, void *buf, int length, int sec_timeout, int *bytes_read)
{
    mud_device *pd = &msp->device[pc->dindex];
    enum HPMUD_RESULT stat = HPMUD_R_IO_ERROR;

    *bytes_read=0;
    if (pc->ta.p2hsize==0)
    {
        BUG("invalid channel_read state\n");
        goto bugout;
    }

    if (pc->rcnt)
    {
        stat=HPMUD_R_OK;
        *bytes_read = cut_buf(pc, buf, length);
        goto bugout;
    }

    if (pc->ta.p2hcredit == 0)
    {
        /* Issue enough credit to the peripheral to read one data packet. */
        if (MlcCredit(pc, pd->mlc_fd, 1))
            goto bugout;
    }

    stat=HPMUD_R_OK;
    pc->rcnt = MlcReverseData(pc, pd->mlc_fd, pc->rbuf, sizeof(pc->rbuf), sec_timeout*1000000);
    if (pc->rcnt)
        pc->ta.p2hcredit--; /* one data packet was read, decrement credit count */

    *bytes_read = cut_buf(pc, buf, length);

bugout:
    return stat;
}

/*******************************************************************************************************************************
 * USB dot4_channel functions.
 */

enum HPMUD_RESULT __attribute__ ((visibility ("hidden"))) musb_dot4_channel_open(mud_channel *pc)
{
    mud_device *pd = &msp->device[pc->dindex];
    enum FD_ID fd;
    enum HPMUD_RESULT stat = HPMUD_R_IO_ERROR;

    /* Initialize MLC transport if this is the first MLC channel. */
    if (pd->channel_cnt==1)
    {
        if (get_interface(libusb_dev, FD_7_1_3, &fd_table[FD_7_1_3]) == 0 && claim_interface(libusb_dev, &fd_table[FD_7_1_3]) == 0)
            fd = FD_7_1_3;    /* mlc, dot4 */
        else if (get_interface(libusb_dev, FD_ff_ff_ff, &fd_table[FD_ff_ff_ff]) == 0 && claim_interface(libusb_dev, &fd_table[FD_ff_ff_ff]) == 0)
            fd = FD_ff_ff_ff;   /* mlc, dot4 */
        else if (get_interface(libusb_dev, FD_ff_d4_0, &fd_table[FD_ff_d4_0]) == 0 && claim_interface(libusb_dev, &fd_table[FD_ff_d4_0]) == 0)
            fd = FD_ff_d4_0;   /* mlc, dot4 */
        else if (get_interface(libusb_dev, FD_7_1_2, &fd_table[FD_7_1_2]) == 0 && claim_interface(libusb_dev, &fd_table[FD_7_1_2]) == 0)
            fd = FD_7_1_2;    /* raw, mlc, dot4 */
        else
        {
            stat = HPMUD_R_DEVICE_BUSY;
            goto bugout;
        }

        if (fd == FD_7_1_2)
        {
            if (pd->io_mode == HPMUD_DOT4_BRIDGE_MODE)
            {
                /* Emulate 7/1/3 on 7/1/2 using the bridge chip set (ie: CLJ2500). */
                if (bridge_chip_up(&fd_table[fd]))
                    goto bugout;
            }
            else
            {
                /* Emulate 7/1/3 on 7/1/2 using vendor-specific ECP channel-77. */
                if (write_ecp_channel(&fd_table[fd], 77))
                    goto bugout;
            }
        }

        if (pd->io_mode == HPMUD_DOT4_PHOENIX_MODE)
            write_phoenix_setup(&fd_table[fd]);

        unsigned int i;

        /* DOT4 initialize */
        if (Dot4Init(pc, fd) != 0)
            goto bugout;

        /* Reset transport attributes for all channels. */
        for (i=0; i<HPMUD_CHANNEL_MAX; i++)
            memset(&pd->channel[i].ta, 0 , sizeof(transport_attributes));

        pd->mlc_fd = fd;
        pd->mlc_up=1;

    } /* if (pDev->ChannelCnt==1) */

    if (Dot4GetSocket(pc, pd->mlc_fd))
        goto bugout;

    if (Dot4OpenChannel(pc, pd->mlc_fd))
        goto bugout;

    if (pd->io_mode == HPMUD_DOT4_PHOENIX_MODE)
    {
        /* Issue credit to peripheral. */
        if (Dot4Credit(pc, pd->mlc_fd, 2))
        {
            BUG("invalid Dot4Credit to peripheral\n");
            goto bugout;
        }
    }
    pc->rcnt = pc->rindex = 0;

    stat = HPMUD_R_OK;

bugout:
    return stat;
}

enum HPMUD_RESULT __attribute__ ((visibility ("hidden"))) musb_dot4_channel_close(mud_channel *pc)
{
    mud_device *pd = &msp->device[pc->dindex];
    enum HPMUD_RESULT stat = HPMUD_R_OK;

    if (pd->mlc_up)
    {
        if (Dot4CloseChannel(pc, pd->mlc_fd))
            stat = HPMUD_R_IO_ERROR;
    }

    /* Remove 1284.4 transport if this is the last 1284.4 channel. */
    if (pd->channel_cnt==1)
    {
        if (pd->mlc_up)
        {
            if (Dot4Exit(pc, pd->mlc_fd))
                stat = HPMUD_R_IO_ERROR;
        }
        pd->mlc_up=0;

        if (pd->mlc_fd == FD_7_1_2)
        {
            if (pd->io_mode == HPMUD_DOT4_BRIDGE_MODE)
            {
                bridge_chip_down(&fd_table[pd->mlc_fd]);
            }
            else
            {
                write_ecp_channel(&fd_table[pd->mlc_fd], 78);
                write_ecp_channel(&fd_table[pd->mlc_fd], 0);
            }
        }

        release_interface(&fd_table[pd->mlc_fd]);

        /* Delay for back-to-back scanning using scanimage (OJ 7110, OJ d135). */
        sleep(1);
    }

    return stat;
}

enum HPMUD_RESULT __attribute__ ((visibility ("hidden"))) musb_dot4_channel_write(mud_channel *pc, const void *buf, int length, int sec_timeout, int *bytes_wrote)
{
    mud_device *pd = &msp->device[pc->dindex];
    int ret, len, size, dlen, total=0, cnt=0;
    enum HPMUD_RESULT stat = HPMUD_R_IO_ERROR;

    *bytes_wrote=0;
    size = length;
    dlen = pc->ta.h2psize - sizeof(DOT4Header);
    while (size > 0)
    {
        len = (size > dlen) ? dlen : size;

        if (pc->ta.h2pcredit == 0 && pd->io_mode == HPMUD_DOT4_PHOENIX_MODE)
        {
            /* Issue credit request to peripheral. */
            if (Dot4CreditRequest(pc, pd->mlc_fd, 1))
            {
                BUG("invalid Dot4CreditRequest from peripheral\n");
                goto bugout;
            }
            if (pc->ta.h2pcredit == 0)
            {
                if (cnt++ > HPMUD_EXCEPTION_SEC_TIMEOUT)
                {
                    BUG("invalid Dot4CreditRequest from peripheral\n");
                    goto bugout;
                }
                sleep(1);
                continue;    /* Got a valid Dot4CreditRequest but no credit from peripheral, try again. */
            }
        }

        if (pc->ta.h2pcredit == 0)
        {
            ret = Dot4ReverseCmd(pc, pd->mlc_fd);
            if (pc->ta.h2pcredit == 0)
            {
                if (ret == 0)
                    continue;  /* Got a reverse command, but no Dot4Credit, try again. */

                BUG("invalid Dot4Credit from peripheral\n");
                goto bugout;
            }
        }

        if (Dot4ForwardData(pc, pd->mlc_fd, buf+total, len, sec_timeout*1000000))
        {
            goto bugout;
        }

        pc->ta.h2pcredit--;
        size-=len;
        total+=len;
        *bytes_wrote+=len;
        cnt=0;
    }

    stat = HPMUD_R_OK;

bugout:
    return stat;
}

/*
 * dot4_read_data() tries to read "length" bytes from the peripheral. Read_data() reads data in packet size chunks.
 * The returned read count may be zero (timeout, no data available), less than "length" or equal "length".
 *
 * dot4_read_data() may read more the "length" if the data packet is greater than "length". For this case the
 * return value will equal "length" and the left over data will be buffered for the next read_data() call.
 *
 * The "timeout" specifies how many seconds to wait for a data packet. Once the read of the data packet has
 * started the "timeout" is no longer used.
 *
 * Note, if a "timeout" occurs one peripheral to host credit is left outstanding. Which means the peripheral
 * can send unsolicited data later.
 */
enum HPMUD_RESULT __attribute__ ((visibility ("hidden"))) musb_dot4_channel_read(mud_channel *pc, void *buf, int length, int sec_timeout, int *bytes_read)
{
    mud_device *pd = &msp->device[pc->dindex];
    enum HPMUD_RESULT stat = HPMUD_R_IO_ERROR;

    *bytes_read=0;
    if (pc->ta.p2hsize==0)
    {
        BUG("invalid channel_read state\n");
        goto bugout;
    }

    if (pc->rcnt)
    {
        stat=HPMUD_R_OK;
        *bytes_read = cut_buf(pc, buf, length);
        goto bugout;
    }

    if (pc->ta.p2hcredit == 0)
    {
        /* Issue enough credit to the peripheral to read one data packet. */
        if (Dot4Credit(pc, pd->mlc_fd, 1))
            goto bugout;
    }

    stat=HPMUD_R_OK;
    pc->rcnt = Dot4ReverseData(pc, pd->mlc_fd, pc->rbuf, sizeof(pc->rbuf), sec_timeout*1000000);
    if (pc->rcnt)
        pc->ta.p2hcredit--; /* one data packet was read, decrement credit count */

    *bytes_read = cut_buf(pc, buf, length);

bugout:
    return stat;
}

/*******************************************************************************************************************************
 * USB probe devices, walk the USB bus(s) looking for HP products.
 */

int __attribute__ ((visibility ("hidden"))) musb_probe_devices(char *lst, int lst_size, int *cnt, enum HPMUD_DEVICE_TYPE devtype)
{
    libusb_context *ctx = NULL;
    libusb_device **list; /*List of connected USB devices */
    libusb_device *dev = NULL; /* Current device */
    struct libusb_device_descriptor devdesc; /* Current device descriptor */
    struct libusb_config_descriptor *confptr = NULL; /* Pointer to current configuration */
    const struct libusb_interface *ifaceptr = NULL; /* Pointer to current interface */
    const struct libusb_interface_descriptor *altptr = NULL; /* Pointer to current alternate setting */
    libusb_device_handle *hd = NULL;

    int numdevs = 0;        /* number of connected devices */
    int i, conf, iface, altset ;
    int dev_already_counted = 0;

    struct hpmud_model_attributes ma;
    char rmodel[128], rserial[128], model[128];
    char serial[128], mfg[128], sz[HPMUD_LINE_SIZE];
    int r, size=0;

    i = libusb_init(&ctx);
    if (i) goto bugout;
    numdevs = libusb_get_device_list(ctx, &list);

    if (numdevs <= 0)
        goto bugout;

    model[0] = serial[0] = rmodel[0] = rserial[0] = sz[0] = mfg[0] = 0;

    for (i = 0; i < numdevs; i++)
    {
        dev = list[i];
        dev_already_counted = 0 ;

        /* Ignore devices with no configuration data and anything that is not  a printer.  */

        libusb_get_device_descriptor (dev, &devdesc);

        if (!devdesc.bNumConfigurations || !devdesc.idVendor || !devdesc.idProduct)
            continue;

        if(devdesc.idVendor != 0x3f0) /*Not a HP device */
            continue;

        for (conf = 0; (dev_already_counted == 0 && conf < devdesc.bNumConfigurations); conf++)
        {
            if (libusb_get_config_descriptor (dev, conf, &confptr) < 0)
                continue;
            for (iface = 0, ifaceptr = confptr->interface;
                (dev_already_counted == 0 && iface < confptr->bNumInterfaces); iface ++, ifaceptr ++)
            {
                for (altset = 0, altptr = ifaceptr->altsetting; altset < ifaceptr->num_altsetting; altset++, altptr++)
                {
                    if ((altptr->bInterfaceClass == LIBUSB_CLASS_PRINTER) || (altptr->bInterfaceClass == LIBUSB_CLASS_VENDOR_SPEC)) 
                    {
                        if( (devtype == HPMUD_PRINTER) && (altptr->bInterfaceProtocol != 0x02) )
                        {
                            continue; /*Check for only print interface (7/1/2) */
                        }
                        
                        libusb_open(dev, &hd);
                        if (hd == NULL)
                        {
                            BUG("Invalid usb_open: %m\n");
                            continue;
                        }
                        /* Found hp device. */
                        if ((r=get_string_descriptor(hd, devdesc.iProduct, rmodel, sizeof(rmodel))) < 0)
                            BUG("invalid product id string ret=%d\n", r);
                        else
                            generalize_model(rmodel, model, sizeof(model));

                        if ((r=get_string_descriptor(hd, devdesc.iSerialNumber, rserial, sizeof(rserial))) < 0)
                            BUG("invalid serial id string ret=%d\n", r);
                        else
                            generalize_serial(rserial, serial, sizeof(serial));

                        if ((r=get_string_descriptor(hd, devdesc.iManufacturer, sz, sizeof(sz))) < 0)
                            BUG("invalid manufacturer string ret=%d\n", r);
                        else
                            generalize_serial(sz, mfg, sizeof(serial));

                        if (!serial[0])
                            strcpy(serial, "0"); /* no serial number, make it zero */

                        if (model[0])
                        {
                            snprintf(sz, sizeof(sz), "hp:/usb/%s?serial=%s", model, serial);

                            /* See if device is supported by hplip. */
                            hpmud_query_model(sz, &ma);
                            if (ma.support != HPMUD_SUPPORT_TYPE_HPLIP)
                            {
                                BUG("ignoring %s support=%d\n", sz, ma.support);
                                continue;           /* ignor, not supported */
                            }

                            /*
                             * For Cups 1.2 we append a dummy deviceid. A valid deviceid would require us to claim the USB interface, thus removing usblp.
                             * This will allow us to do discovery and not disable other CUPS backend(s) who use /dev/usb/lpx instead of libusb.
                             */
                            if (strncasecmp(rmodel, "hp ", 3) == 0)
                                size += snprintf(lst+size, lst_size-size, "direct %s \"HP %s\" \"HP %s USB %s HPLIP\" \"MFG:%s;MDL:%s;CLS:PRINTER;DES:%s;SN:%s;\"\n",
                                        sz, &rmodel[3], &rmodel[3], serial, mfg, rmodel, rmodel, rserial);
                            else
                                size += snprintf(lst+size, lst_size-size, "direct %s \"HP %s\" \"HP %s USB %s HPLIP\" \"MFG:%s;MDL:%s;CLS:PRINTER;DES:%s;SN:%s;\"\n",
                                        sz, rmodel, rmodel, serial, mfg, rmodel, rmodel, rserial);

                            *cnt+=1;
                        }
                        libusb_close(hd); hd = NULL;
                        dev_already_counted = 1;
                        break;
                    }
                }
            }
            libusb_free_config_descriptor(confptr); confptr = NULL;
        }

    }//end for loop

bugout:
    if (hd)
        libusb_close(hd);
    if (confptr)
        libusb_free_config_descriptor(confptr);
    if (list)
      libusb_free_device_list(list, 1);
    if (ctx)
      libusb_exit(ctx);

    return size;
}

enum HPMUD_RESULT hpmud_make_usb_uri(const char *busnum, const char *devnum, char *uri, int uri_size, int *bytes_read)
{
    libusb_context *ctx = NULL;
    libusb_device **list; /*List of connected USB devices */
    libusb_device *dev = NULL, *found_dev=NULL;
    libusb_device_handle *hd=NULL;
    struct libusb_device_descriptor devdesc; /* Current device descriptor */
    struct libusb_config_descriptor *confptr = NULL; /* Pointer to current configuration */
    const struct libusb_interface *ifaceptr = NULL; /* Pointer to current interface */
    const struct libusb_interface_descriptor *altptr = NULL; /* Pointer to current alternate setting */
    char model[128], serial[128], sz[256];
    int r, numdevs, i;
    int conf, iface, altset ;
    int bus_num, dev_num;
    enum HPMUD_RESULT stat = HPMUD_R_INVALID_DEVICE_NODE;
    int isSmartInstall_enabled = 0, isPrinter = 0;

    DBG("[%d] hpmud_make_usb_uri() bus=%s dev=%s\n", getpid(), busnum, devnum);

    *bytes_read=0;

    i = libusb_init(&ctx);
    if (i) goto bugout;
    numdevs = libusb_get_device_list(ctx, &list);

    if (numdevs <= 0)
        goto bugout;

    for (i = 0; i < numdevs; i++)
    {
        dev = list[i];
        bus_num = libusb_get_bus_number(dev);
        if (bus_num != atoi(busnum))
            continue;

        dev_num = libusb_get_device_address(dev);
        if (dev_num != atoi(devnum))
            continue;

        found_dev = dev;  /* found usb device that matches bus:device */
    }

    if (found_dev == NULL)
    {
        BUG("invalid busnum:devnum %s:%s\n", busnum, devnum);
        goto bugout;
    }

    dev = found_dev;
    libusb_open(dev, &hd);

    if (hd == NULL)
    {
        BUG("invalid libusb_open: %m\n");
        goto bugout;
    }

    model[0] = serial[0] = sz[0] = 0;

    libusb_get_device_descriptor (dev, &devdesc);

    if (devdesc.idVendor == 0x3f0)
    {
        /* Found hp device. */
        if ((r=get_string_descriptor(hd, devdesc.iProduct, sz, sizeof(sz))) < 0)
            BUG("invalid product id string ret=%d\n", r);
        else
            generalize_model(sz, model, sizeof(model));

        if ((r=get_string_descriptor(hd, devdesc.iSerialNumber, sz, sizeof(sz))) < 0)
            BUG("invalid serial id string ret=%d\n", r);
        else
            generalize_serial(sz, serial, sizeof(serial));

        if (!serial[0])
            strcpy(serial, "0"); /* no serial number, make it zero */

        for (conf = 0; conf < devdesc.bNumConfigurations; conf++)
        {
            if (libusb_get_config_descriptor (dev, conf, &confptr) < 0)
                continue;

            for (iface = 0, ifaceptr = confptr->interface; iface < confptr->bNumInterfaces; iface ++, ifaceptr ++)
            {
                for (altset = 0, altptr = ifaceptr->altsetting; altset < ifaceptr->num_altsetting; altset++, altptr++)
                {
                    if (confptr->bNumInterfaces == 1 && altptr->bInterfaceClass == LIBUSB_CLASS_MASS_STORAGE )
                    {
                        strcpy(serial, "SMART_INSTALL_ENABLED"); /* no serial number, make it zero */
                        isSmartInstall_enabled = 1;
                        break;
                    }
                    else if  (altptr->bInterfaceClass == LIBUSB_CLASS_PRINTER )
                    {
                        isPrinter = 1;
                        break;
                    }
                }
            }
            libusb_free_config_descriptor(confptr); confptr = NULL;
        }//end for conf

    }
    else
    {
        BUG("invalid vendor id: %d\n", devdesc.idVendor);
        goto bugout;
    }

    if (!model[0] || !serial[0])
        goto bugout;

    if ( isPrinter  == 1 || isSmartInstall_enabled == 1)
    {
        *bytes_read = snprintf(uri, uri_size, "hp:/usb/%s?serial=%s", model, serial);
        DBG("hpmud_make_usb_uri() uri=%s bytes_read=%d\n", uri, *bytes_read);
        stat = HPMUD_R_OK;
    }
    else
        DBG("hpmud_make_usb_uri() Invalid Device =%s\n", model);

bugout:
    if (hd != NULL)
        libusb_close(hd);

    if (list)
      libusb_free_device_list(list, 1);
    if (ctx)
      libusb_exit(ctx);

    return stat;
}

enum HPMUD_RESULT hpmud_make_usb_serial_uri(const char *sn, char *uri, int uri_size, int *bytes_read)
{
    libusb_context *ctx = NULL;
    libusb_device **list; /*List of connected USB devices */
    libusb_device *dev = NULL, *found_dev=NULL;

    char model[128];
    enum HPMUD_RESULT stat = HPMUD_R_INVALID_DEVICE_NODE;
    int i, numdevs;

    DBG("[%d] hpmud_make_usb_serial_uri() sn=%s\n", getpid(), sn);

    *bytes_read=0;

    i = libusb_init(&ctx);
    if (i) goto bugout;
    numdevs = libusb_get_device_list(ctx, &list);

    if (numdevs <= 0)
        goto bugout;

    for (i = 0; i < numdevs; i++)
    {
        dev = list[i];
        if (is_serial(dev, sn, model, sizeof(model)))
        {
            found_dev = dev;  /* found usb device that matches serial number */
            break;
        }
    }

    if (found_dev == NULL)
    {
        BUG("invalid sn %s\n", sn);
        goto bugout;
    }

    *bytes_read = snprintf(uri, uri_size, "hp:/usb/%s?serial=%s", model, sn);
    stat = HPMUD_R_OK;

bugout:
    if (list)
      libusb_free_device_list(list, 1);
    if (ctx)
      libusb_exit(ctx);

    return stat;
}