File: sg_lib.c

package info (click to toggle)
ddpt 0.95-1
  • links: PTS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 1,772 kB
  • sloc: ansic: 21,845; sh: 5,153; makefile: 155
file content (2141 lines) | stat: -rw-r--r-- 74,463 bytes parent folder | download
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
/*
 * Copyright (c) 1999-2014 Douglas Gilbert.
 * All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the BSD_LICENSE file.
 */

/* NOTICE:
 *    On 5th October 2004 (v1.00) this file name was changed from sg_err.c
 *    to sg_lib.c and the previous GPL was changed to a FreeBSD license.
 *    The intention is to maintain this file and the related sg_lib.h file
 *    as open source and encourage their unencumbered use.
 *
 * CONTRIBUTIONS:
 *    This file started out as a copy of SCSI opcodes, sense keys and
 *    additional sense codes (ASC/ASCQ) kept in the Linux SCSI subsystem
 *    in the kernel source file: drivers/scsi/constant.c . That file
 *    bore this notice: "Copyright (C) 1993, 1994, 1995 Eric Youngdale"
 *    and a GPL notice.
 *
 *    Much of the data in this file is derived from SCSI draft standards
 *    found at http://www.t10.org with the "SCSI Primary Commands-4" (SPC-4)
 *    being the central point of reference.
 *
 *    Contributions:
 *      sense key specific field decoding [Trent Piepho 20031116]
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <ctype.h>
#define __STDC_FORMAT_MACROS 1
#include <inttypes.h>

#include "sg_lib.h"
#include "sg_lib_data.h"

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

/* sg_lib_version_str (and datestamp) defined in sg_lib_data.c file */

#define ASCQ_ATA_PT_INFO_AVAILABLE 0x1d  /* corresponding ASC is 0 */

/* The following two opcodes were renamed to 'Third party copy out/in' in
 * spc4r34 */
#define SG_THIRD_PARTY_COPY_OUT SG_EXTENDED_COPY
#define SG_THIRD_PARTY_COPY_IN SG_RECEIVE_COPY

FILE * sg_warnings_strm = NULL;        /* would like to default to stderr */


#ifdef __GNUC__
static int my_snprintf(char * cp, int cp_max_len, const char * fmt, ...)
                       __attribute__ ((format (printf, 3, 4)));
#else
static int my_snprintf(char * cp, int cp_max_len, const char * fmt, ...);
#endif

/* Want safe, 'n += snprintf(b + n, blen - n, ...)' style sequence of
 * functions. Returns number number of chars placed in cp excluding the
 * trailing null char. So for cp_max_len > 0 the return value is always
 * < cp_max_len; for cp_max_len <= 1 the return value is 0 and no chars
 * are written to cp. Note this means that when cp_max_len = 1, this
 * function assumes that cp[0] is the null character and does nothing
 * (and returns 0).  */
static int
my_snprintf(char * cp, int cp_max_len, const char * fmt, ...)
{
    va_list args;
    int n;

    if (cp_max_len < 2)
        return 0;
    va_start(args, fmt);
    n = vsnprintf(cp, cp_max_len, fmt, args);
    va_end(args);
    return (n < cp_max_len) ? n : (cp_max_len - 1);
}

/* Searches 'arr' for match on 'value' then 'peri_type'. If matches
   'value' but not 'peri_type' then yields first 'value' match entry.
   Last element of 'arr' has NULL 'name'. If no match returns NULL. */
static const struct sg_lib_value_name_t *
get_value_name(const struct sg_lib_value_name_t * arr, int value,
               int peri_type)
{
    const struct sg_lib_value_name_t * vp = arr;
    const struct sg_lib_value_name_t * holdp;

    for (; vp->name; ++vp) {
        if (value == vp->value) {
            if (peri_type == vp->peri_dev_type)
                return vp;
            holdp = vp;
            while ((vp + 1)->name && (value == (vp + 1)->value)) {
                ++vp;
                if (peri_type == vp->peri_dev_type)
                    return vp;
            }
            return holdp;
        }
    }
    return NULL;
}

void
sg_set_warnings_strm(FILE * warnings_strm)
{
    sg_warnings_strm = warnings_strm;
}

#define CMD_NAME_LEN 128

void
sg_print_command(const unsigned char * command)
{
    int k, sz;
    char buff[CMD_NAME_LEN];

    sg_get_command_name(command, 0, CMD_NAME_LEN, buff);
    buff[CMD_NAME_LEN - 1] = '\0';

    if (NULL == sg_warnings_strm)
        sg_warnings_strm = stderr;
    fprintf(sg_warnings_strm, "%s [", buff);
    if (SG_VARIABLE_LENGTH_CMD == command[0])
        sz = command[7] + 8;
    else
        sz = sg_get_command_size(command[0]);
    for (k = 0; k < sz; ++k)
        fprintf(sg_warnings_strm, "%02x ", command[k]);
    fprintf(sg_warnings_strm, "]\n");
}

void
sg_get_scsi_status_str(int scsi_status, int buff_len, char * buff)
{
    const char * ccp = NULL;
    int unknown = 0;

    if ((NULL == buff) || (buff_len < 1))
        return;
    else if (1 ==  buff_len) {
        buff[0] = '\0';
        return;
    }
    scsi_status &= 0x7e; /* sanitize as much as possible */
    switch (scsi_status) {
        case 0: ccp = "Good"; break;
        case 0x2: ccp = "Check Condition"; break;
        case 0x4: ccp = "Condition Met"; break;
        case 0x8: ccp = "Busy"; break;
        case 0x10: ccp = "Intermediate (obsolete)"; break;
        case 0x14: ccp = "Intermediate-Condition Met (obsolete)"; break;
        case 0x18: ccp = "Reservation Conflict"; break;
        case 0x22: ccp = "Command Terminated (obsolete)"; break;
        case 0x28: ccp = "Task set Full"; break;
        case 0x30: ccp = "ACA Active"; break;
        case 0x40: ccp = "Task Aborted"; break;
        default:
            unknown = 1;
            break;
    }
    if (unknown)
        my_snprintf(buff, buff_len, "Unknown status [0x%x]", scsi_status);
    else
        my_snprintf(buff, buff_len, "%s", ccp);
}

void
sg_print_scsi_status(int scsi_status)
{
    char buff[128];

    sg_get_scsi_status_str(scsi_status, sizeof(buff) - 1, buff);
    buff[sizeof(buff) - 1] = '\0';
    if (NULL == sg_warnings_strm)
        sg_warnings_strm = stderr;
    fprintf(sg_warnings_strm, "%s ", buff);
}

/* Get sense key from sense buffer. If successful returns a sense key value
 * between 0 and 15. If sense buffer cannot be decode, returns -1 . */
int
sg_get_sense_key(const unsigned char * sensep, int sense_len)
{
    if ((NULL == sensep) || (sense_len < 2))
        return -1;
    switch (sensep[0] & 0x7f) {
    case 0x70:
    case 0x71:
        return (sense_len < 3) ? -1 : (sensep[2] & 0xf);
    case 0x72:
    case 0x73:
        return sensep[1] & 0xf;
    default:
        return -1;
    }
}

/* Yield string associated with sense_key value. Returns 'buff'. */
char *
sg_get_sense_key_str(int sense_key, int buff_len, char * buff)
{
    if (1 == buff_len) {
        buff[0] = '\0';
        return buff;
    }
    if ((sense_key >= 0) && (sense_key < 16))
         my_snprintf(buff, buff_len, "%s", sg_lib_sense_key_desc[sense_key]);
    else
         my_snprintf(buff, buff_len, "invalid value: 0x%x", sense_key);
    return buff;
}

/* Yield string associated with ASC/ASCQ values. Returns 'buff'. */
char *
sg_get_asc_ascq_str(int asc, int ascq, int buff_len, char * buff)
{
    int k, num, rlen;
    int found = 0;
    struct sg_lib_asc_ascq_t * eip;
    struct sg_lib_asc_ascq_range_t * ei2p;

    if (1 == buff_len) {
        buff[0] = '\0';
        return buff;
    }
    for (k = 0; sg_lib_asc_ascq_range[k].text; ++k) {
        ei2p = &sg_lib_asc_ascq_range[k];
        if ((ei2p->asc == asc) &&
            (ascq >= ei2p->ascq_min)  &&
            (ascq <= ei2p->ascq_max)) {
            found = 1;
            num = my_snprintf(buff, buff_len, "Additional sense: ");
            rlen = buff_len - num;
            num += my_snprintf(buff + num, ((rlen > 0) ? rlen : 0),
                               ei2p->text, ascq);
        }
    }
    if (found)
        return buff;

    for (k = 0; sg_lib_asc_ascq[k].text; ++k) {
        eip = &sg_lib_asc_ascq[k];
        if (eip->asc == asc &&
            eip->ascq == ascq) {
            found = 1;
            my_snprintf(buff, buff_len, "Additional sense: %s", eip->text);
        }
    }
    if (! found) {
        if (asc >= 0x80)
            my_snprintf(buff, buff_len, "vendor specific ASC=%02x, "
                        "ASCQ=%02x (hex)", asc, ascq);
        else if (ascq >= 0x80)
            my_snprintf(buff, buff_len, "ASC=%02x, vendor specific "
                        "qualification ASCQ=%02x (hex)", asc, ascq);
        else
            my_snprintf(buff, buff_len, "ASC=%02x, ASCQ=%02x (hex)", asc,
                        ascq);
    }
    return buff;
}

/* Attempt to find the first SCSI sense data descriptor that matches the
 * given 'desc_type'. If found return pointer to start of sense data
 * descriptor; otherwise (including fixed format sense data) returns NULL. */
const unsigned char *
sg_scsi_sense_desc_find(const unsigned char * sensep, int sense_len,
                        int desc_type)
{
    int add_sb_len, add_d_len, desc_len, k;
    const unsigned char * descp;

    if ((sense_len < 8) || (0 == (add_sb_len = sensep[7])))
        return NULL;
    if ((sensep[0] < 0x72) || (sensep[0] > 0x73))
        return NULL;
    add_sb_len = (add_sb_len < (sense_len - 8)) ?
                         add_sb_len : (sense_len - 8);
    descp = &sensep[8];
    for (desc_len = 0, k = 0; k < add_sb_len; k += desc_len) {
        descp += desc_len;
        add_d_len = (k < (add_sb_len - 1)) ? descp[1]: -1;
        desc_len = add_d_len + 2;
        if (descp[0] == desc_type)
            return descp;
        if (add_d_len < 0) /* short descriptor ?? */
            break;
    }
    return NULL;
}

/* Returns 1 if valid bit set, 0 if valid bit clear. Irrespective the
 * information field is written out via 'info_outp' (except when it is
 * NULL). Handles both fixed and descriptor sense formats. */
int
sg_get_sense_info_fld(const unsigned char * sensep, int sb_len,
                      uint64_t * info_outp)
{
    int j;
    const unsigned char * ucp;
    uint64_t ull;

    if (info_outp)
        *info_outp = 0;
    if (sb_len < 7)
        return 0;
    switch (sensep[0] & 0x7f) {
    case 0x70:
    case 0x71:
        if (info_outp)
            *info_outp = ((unsigned int)sensep[3] << 24) + (sensep[4] << 16) +
                         (sensep[5] << 8) + sensep[6];
        return (sensep[0] & 0x80) ? 1 : 0;
    case 0x72:
    case 0x73:
        ucp = sg_scsi_sense_desc_find(sensep, sb_len, 0 /* info desc */);
        if (ucp && (0xa == ucp[1])) {
            ull = 0;
            for (j = 0; j < 8; ++j) {
                if (j > 0)
                    ull <<= 8;
                ull |= ucp[4 + j];
            }
            if (info_outp)
                *info_outp = ull;
            return !!(ucp[2] & 0x80);   /* since spc3r23 should be set */
        } else
            return 0;
    default:
        return 0;
    }
}

/* Returns 1 if any of the 3 bits (i.e. FILEMARK, EOM or ILI) are set.
 * In descriptor format if the stream commands descriptor not found
 * then returns 0. Writes 1 or 0 corresponding to these bits to the
 * last three arguments if they are non-NULL. */
int
sg_get_sense_filemark_eom_ili(const unsigned char * sensep, int sb_len,
                              int * filemark_p, int * eom_p, int * ili_p)
{
    const unsigned char * ucp;

    if (sb_len < 7)
        return 0;
    switch (sensep[0] & 0x7f) {
    case 0x70:
    case 0x71:
        if (sensep[2] & 0xe0) {
            if (filemark_p)
                *filemark_p = !!(sensep[2] & 0x80);
            if (eom_p)
                *eom_p = !!(sensep[2] & 0x40);
            if (ili_p)
                *ili_p = !!(sensep[2] & 0x20);
            return 1;
        } else
            return 0;
    case 0x72:
    case 0x73:
       /* Look for stream commands sense data descriptor */
        ucp = sg_scsi_sense_desc_find(sensep, sb_len, 4);
        if (ucp && (ucp[1] >= 2)) {
            if (ucp[3] & 0xe0) {
                if (filemark_p)
                    *filemark_p = !!(ucp[3] & 0x80);
                if (eom_p)
                    *eom_p = !!(ucp[3] & 0x40);
                if (ili_p)
                    *ili_p = !!(ucp[3] & 0x20);
                return 1;
            }
        }
        return 0;
    default:
        return 0;
    }
}

/* Returns 1 if SKSV is set and sense key is NO_SENSE or NOT_READY. Also
 * returns 1 if progress indication sense data descriptor found. Places
 * progress field from sense data where progress_outp points. If progress
 * field is not available returns 0 and *progress_outp is unaltered. Handles
 * both fixed and descriptor sense formats.
 * Hint: if 1 is returned *progress_outp may be multiplied by 100 then
 * divided by 65536 to get the percentage completion. */
int
sg_get_sense_progress_fld(const unsigned char * sensep, int sb_len,
                          int * progress_outp)
{
    const unsigned char * ucp;
    int sk, sk_pr;

    if (sb_len < 7)
        return 0;
    switch (sensep[0] & 0x7f) {
    case 0x70:
    case 0x71:
        sk = (sensep[2] & 0xf);
        if ((sb_len < 18) ||
            ((SPC_SK_NO_SENSE != sk) && (SPC_SK_NOT_READY != sk)))
            return 0;
        if (sensep[15] & 0x80) {        /* SKSV bit set */
            if (progress_outp)
                *progress_outp = (sensep[16] << 8) + sensep[17];
            return 1;
        } else
            return 0;
    case 0x72:
    case 0x73:
        /* sense key specific progress (0x2) or progress descriptor (0xa) */
        sk = (sensep[1] & 0xf);
        sk_pr = (SPC_SK_NO_SENSE == sk) || (SPC_SK_NOT_READY == sk);
        if (sk_pr && ((ucp = sg_scsi_sense_desc_find(sensep, sb_len, 2))) &&
            (0x6 == ucp[1]) && (0x80 & ucp[4])) {
            if (progress_outp)
                *progress_outp = (ucp[5] << 8) + ucp[6];
            return 1;
        } else if (((ucp = sg_scsi_sense_desc_find(sensep, sb_len, 0xa))) &&
                   ((0x6 == ucp[1]))) {
            if (progress_outp)
                *progress_outp = (ucp[6] << 8) + ucp[7];
            return 1;
        } else
            return 0;
    default:
        return 0;
    }
}

char *
sg_get_pdt_str(int pdt, int buff_len, char * buff)
{
    if ((pdt < 0) || (pdt > 31))
        my_snprintf(buff, buff_len, "bad pdt");
    else
        my_snprintf(buff, buff_len, "%s", sg_lib_pdt_strs[pdt]);
    return buff;
}

char *
sg_get_trans_proto_str(int tpi, int buff_len, char * buff)
{
    if ((tpi < 0) || (tpi > 15))
        my_snprintf(buff, buff_len, "bad tpi");
    else
        my_snprintf(buff, buff_len, "%s", sg_lib_transport_proto_strs[tpi]);
    return buff;
}

#define TPGS_STATE_OPTIMIZED 0x0
#define TPGS_STATE_NONOPTIMIZED 0x1
#define TPGS_STATE_STANDBY 0x2
#define TPGS_STATE_UNAVAILABLE 0x3
#define TPGS_STATE_OFFLINE 0xe
#define TPGS_STATE_TRANSITIONING 0xf

static int
decode_tpgs_state(int st, char * b, int blen)
{
    switch (st) {
    case TPGS_STATE_OPTIMIZED:
        return my_snprintf(b, blen, "active/optimized");
    case TPGS_STATE_NONOPTIMIZED:
        return my_snprintf(b, blen, "active/non optimized");
    case TPGS_STATE_STANDBY:
        return my_snprintf(b, blen, "standby");
    case TPGS_STATE_UNAVAILABLE:
        return my_snprintf(b, blen, "unavailable");
    case TPGS_STATE_OFFLINE:
        return my_snprintf(b, blen, "offline");
    case TPGS_STATE_TRANSITIONING:
        return my_snprintf(b, blen, "transitioning between states");
    default:
        return my_snprintf(b, blen, "unknown: 0x%x", st);
    }
}

static int
uds_referral_descriptor_str(char * b, int blen, const unsigned char * dp,
                            int alen)
{
    int n = 0;
    int dlen = alen - 2;
    int k, j, g, f, tpgd;
    const unsigned char * tp;
    uint64_t ull;
    char c[40];

    n += my_snprintf(b + n, blen - n, "   Not all referrals: %d\n",
                     !!(dp[2] & 0x1));
    dp += 4;
    for (k = 0, f = 1; (k + 4) < dlen; k += g, dp += g, ++f) {
        tpgd = dp[3];
        g = (tpgd * 4) + 20;
        n += my_snprintf(b + n, blen - n, "    Descriptor %d\n", f);
        if ((k + g) > dlen) {
            n += my_snprintf(b + n, blen - n, "      truncated descriptor, "
                             "stop\n");
            return n;
        }
        ull = 0;
        for (j = 0; j < 8; ++j) {
            if (j > 0)
                ull <<= 8;
            ull |= dp[4 + j];
        }
        n += my_snprintf(b + n, blen - n, "      first uds LBA: 0x%" PRIx64
                         "\n", ull);
        ull = 0;
        for (j = 0; j < 8; ++j) {
            if (j > 0)
                ull <<= 8;
            ull |= dp[12 + j];
        }
        n += my_snprintf(b + n, blen - n, "      last uds LBA:  0x%" PRIx64
                         "\n", ull);
        for (j = 0; j < tpgd; ++j) {
            tp = dp + 20 + (j * 4);
            decode_tpgs_state(tp[0] & 0xf, c, sizeof(c));
            n += my_snprintf(b + n, blen - n, "        tpg: %d  state: %s\n",
                             (tp[2] << 8) + tp[3], c);
        }
    }
    return n;
}

static const char * sdata_src[] = {
    "unknown",
    "Extended Copy command source device",
    "Extended Copy command destination device",
    };


/* Decode descriptor format sense descriptors (assumes sense buffer is
 * in descriptor format) */
static void
sg_get_sense_descriptors_str(const unsigned char * sense_buffer, int sb_len,
                             int blen, char * b)
{
    int add_sb_len, add_d_len, desc_len, k, j, sense_key, processed;
    int n, progress, pr, rem;
    const unsigned char * descp;
    const char * dtsp = "   >> descriptor too short";

    if ((NULL == b) || (blen <= 0))
        return;
    b[0] = '\0';
    if ((sb_len < 8) || (0 == (add_sb_len = sense_buffer[7])))
        return;
    add_sb_len = (add_sb_len < (sb_len - 8)) ? add_sb_len : (sb_len - 8);
    sense_key = (sense_buffer[1] & 0xf);

    for (descp = (sense_buffer + 8), k = 0, n = 0;
         (k < add_sb_len) && (n < blen);
         k += desc_len, descp += desc_len) {
        add_d_len = (k < (add_sb_len - 1)) ? descp[1] : -1;
        if ((k + add_d_len + 2) > add_sb_len)
            add_d_len = add_sb_len - k - 2;
        desc_len = add_d_len + 2;
        n += my_snprintf(b + n, blen - n, "  Descriptor type: ");
        processed = 1;
        switch (descp[0]) {
        case 0:
            n += my_snprintf(b + n, blen - n, "Information\n");
            if ((add_d_len >= 10) && (0x80 & descp[2])) {
                n += my_snprintf(b + n, blen - n, "    0x");
                for (j = 0; j < 8; ++j)
                    n += my_snprintf(b + n, blen - n, "%02x", descp[4 + j]);
                n += my_snprintf(b + n, blen - n, "\n");
            } else {
                n += my_snprintf(b + n, blen - n, "%s\n", dtsp);
                processed = 0;
            }
            break;
        case 1:
            n += my_snprintf(b + n, blen - n, "Command specific\n");
            if (add_d_len >= 10) {
                n += my_snprintf(b + n, blen - n, "    0x");
                for (j = 0; j < 8; ++j)
                    n += my_snprintf(b + n, blen - n, "%02x", descp[4 + j]);
                n += my_snprintf(b + n, blen - n, "\n");
            } else {
                n += my_snprintf(b + n, blen - n, "%s\n", dtsp);
                processed = 0;
            }
            break;
        case 2:
            n += my_snprintf(b + n, blen - n, "Sense key specific:");
            switch (sense_key) {
            case SPC_SK_ILLEGAL_REQUEST:
                n += my_snprintf(b + n, blen - n, " Field pointer\n");
                if (add_d_len < 6) {
                    n += my_snprintf(b + n, blen - n, "%s\n", dtsp);
                    processed = 0;
                    break;
                }
                n += my_snprintf(b + n, blen - n, "    Error in %s: byte %d",
                                 (descp[4] & 0x40) ? "Command" :
                                                     "Data parameters",
                                 (descp[5] << 8) | descp[6]);
                if (descp[4] & 0x08) {
                    n += my_snprintf(b + n, blen - n, " bit %d\n",
                                     descp[4] & 0x07);
                } else
                    n += my_snprintf(b + n, blen - n, "\n");
                break;
            case SPC_SK_HARDWARE_ERROR:
            case SPC_SK_MEDIUM_ERROR:
            case SPC_SK_RECOVERED_ERROR:
                n += my_snprintf(b + n, blen - n, " Actual retry count\n");
                if (add_d_len < 6) {
                    n += my_snprintf(b + n, blen - n, "%s\n", dtsp);
                    processed = 0;
                    break;
                }
                n += my_snprintf(b + n, blen - n,"    0x%02x%02x\n", descp[5],
                                 descp[6]);
                break;
            case SPC_SK_NO_SENSE:
            case SPC_SK_NOT_READY:
                n += my_snprintf(b + n, blen - n, " Progress indication: ");
                if (add_d_len < 6) {
                    n += my_snprintf(b + n, blen - n, "%s\n", dtsp);
                    processed = 0;
                    break;
                }
                progress = (descp[5] << 8) + descp[6];
                pr = (progress * 100) / 65536;
                rem = ((progress * 100) % 65536) / 656;
                n += my_snprintf(b + n, blen - n, "%d.%02d%%\n", pr, rem);
                break;
            case SPC_SK_COPY_ABORTED:
                n += my_snprintf(b + n, blen - n, " Segment pointer\n");
                if (add_d_len < 6) {
                    n += my_snprintf(b + n, blen - n, "%s\n", dtsp);
                    processed = 0;
                    break;
                }
                n += my_snprintf(b + n, blen - n, " Relative to start of %s, "
                                 "byte %d",
                                 (descp[4] & 0x20) ? "segment descriptor" :
                                                     "parameter list",
                                 (descp[5] << 8) | descp[6]);
                if (descp[4] & 0x08)
                    n += my_snprintf(b + n, blen - n, " bit %d\n",
                                     descp[4] & 0x07);
                else
                    n += my_snprintf(b + n, blen - n, "\n");
                break;
            case SPC_SK_UNIT_ATTENTION:
                n += my_snprintf(b + n, blen - n, " Unit attention condition "
                                 "queue: ");
                n += my_snprintf(b + n, blen - n, "overflow flag is %d\n",
                             !!(descp[4] & 0x1));
                break;
            default:
                n += my_snprintf(b + n, blen - n, " Sense_key: 0x%x "
                                 "unexpected\n", sense_key);
                processed = 0;
                break;
            }
            break;
        case 3:
            n += my_snprintf(b + n, blen - n, "Field replaceable unit\n");
            if (add_d_len >= 2)
                n += my_snprintf(b + n, blen - n, "    code=0x%x\n",
                                 descp[3]);
            else {
                n += my_snprintf(b + n, blen - n, "%s\n", dtsp);
                processed = 0;
            }
            break;
        case 4:
            n += my_snprintf(b + n, blen - n, "Stream commands\n");
            if (add_d_len >= 2) {
                if (descp[3] & 0x80)
                    n += my_snprintf(b + n, blen - n, "    FILEMARK");
                if (descp[3] & 0x40)
                    n += my_snprintf(b + n, blen - n, "    End Of Medium "
                                     "(EOM)");
                if (descp[3] & 0x20)
                    n += my_snprintf(b + n, blen - n, "    Incorrect Length "
                                     "Indicator (ILI)");
                n += my_snprintf(b + n, blen - n, "\n");
            } else {
                n += my_snprintf(b + n, blen - n, "%s\n", dtsp);
                processed = 0;
            }
            break;
        case 5:
            n += my_snprintf(b + n, blen - n, "Block commands\n");
            if (add_d_len >= 2)
                n += my_snprintf(b + n, blen - n, "    Incorrect Length "
                                 "Indicator (ILI) %s\n",
                                 (descp[3] & 0x20) ? "set" : "clear");
            else {
                n += my_snprintf(b + n, blen - n, "%s\n", dtsp);
                processed = 0;
            }
            break;
        case 6:
            n += my_snprintf(b + n, blen - n, "OSD object identification\n");
            processed = 0;
            break;
        case 7:
            n += my_snprintf(b + n, blen - n, "OSD response integrity check "
                             "value\n");
            processed = 0;
            break;
        case 8:
            n += my_snprintf(b + n, blen - n, "OSD attribute "
                             "identification\n");
            processed = 0;
            break;
        case 9:         /* this is defined in SAT (and SAT-2) */
            n += my_snprintf(b + n, blen - n, "ATA Status Return\n");
            if (add_d_len >= 12) {
                int extend, sector_count;

                extend = descp[2] & 1;
                sector_count = descp[5] + (extend ? (descp[4] << 8) : 0);
                n += my_snprintf(b + n, blen - n, "    extend=%d  error=0x%x "
                                 " sector_count=0x%x\n", extend, descp[3],
                                 sector_count);
                if (extend)
                    n += my_snprintf(b + n, blen - n, "    "
                                     "lba=0x%02x%02x%02x%02x%02x%02x\n",
                                     descp[10], descp[8], descp[6],
                                     descp[11], descp[9], descp[7]);
                else
                    n += my_snprintf(b + n, blen - n, "    "
                                     "lba=0x%02x%02x%02x\n",
                                     descp[11], descp[9], descp[7]);
                n += my_snprintf(b + n, blen - n, "    device=0x%x  "
                                 "status=0x%x\n", descp[12], descp[13]);
            } else {
                n += my_snprintf(b + n, blen - n, "%s\n", dtsp);
                processed = 0;
            }
            break;
        case 0xa:
           /* Added in SPC-4 rev 17, became 'Another ...' in rev 34 */
            n += my_snprintf(b + n, blen - n, "Another progress "
                             "indication\n");
            if (add_d_len < 6) {
                n += my_snprintf(b + n, blen - n, "%s\n", dtsp);
                processed = 0;
                break;
            }
            progress = (descp[6] << 8) + descp[7];
            pr = (progress * 100) / 65536;
            rem = ((progress * 100) % 65536) / 656;
            n += my_snprintf(b + n, blen - n, "    %d.02%d%%", pr, rem);
            n += my_snprintf(b + n, blen - n, " [sense_key=0x%x "
                             "asc,ascq=0x%x,0x%x]\n",
                             descp[2], descp[3], descp[4]);
            break;
        case 0xb:       /* Added in SPC-4 rev 23, defined in SBC-3 rev 22 */
            n += my_snprintf(b + n, blen - n, "User data segment referral\n");
            if (add_d_len < 2) {
                n += my_snprintf(b + n, blen - n, "%s\n", dtsp);
                processed = 0;
                break;
            }
            n += uds_referral_descriptor_str(b + n, blen - n, descp,
                                             add_d_len);
            break;
        case 0xc:       /* Added in SPC-4 rev 28 */
            n += my_snprintf(b + n, blen - n, "Forwarded sense data\n");
            if (add_d_len < 2) {
                n += my_snprintf(b + n, blen - n, "%s\n", dtsp);
                processed = 0;
                break;
            }
            n += my_snprintf(b + n, blen - n, "    FSDT: %s\n",
                             (descp[2] & 0x80) ? "set" : "clear");
            j = descp[2] & 0xf;
            if (j < 3)
                n += my_snprintf(b + n, blen - n, "    Sense data source: "
                                 "%s\n", sdata_src[j]);
            else
                n += my_snprintf(b + n, blen - n, "    Sense data source: "
                                 "reserved [%d]\n", j);
            {
                char c[200];

                sg_get_scsi_status_str(descp[3], sizeof(c) - 1, c);
                c[sizeof(c) - 1] = '\0';
                n += my_snprintf(b + n, blen - n, "    Forwarded status: "
                                 "%s\n", c);
                if (add_d_len > 2) {
                    /* recursing; hope not to get carried away */
                    n += my_snprintf(b + n, blen - n, " vvvvvvvvvvvvvvvv\n");
                    sg_get_sense_str(NULL, descp + 4, add_d_len - 2, 0,
                                     sizeof(c), c);
                    n += my_snprintf(b + n, blen - n, "%s", c);
                    n += my_snprintf(b + n, blen - n, " ^^^^^^^^^^^^^^^^\n");
                }
            }
            break;
        default:
            if (descp[0] >= 0x80)
                n += my_snprintf(b + n, blen - n, "Vendor specific [0x%x]\n",
                                 descp[0]);
            else
                n += my_snprintf(b + n, blen - n, "Unknown [0x%x]\n",
                                 descp[0]);
            processed = 0;
            break;
        }
        if (! processed) {
            if (add_d_len > 0) {
                n += my_snprintf(b + n, blen - n, "    ");
                for (j = 0; j < add_d_len; ++j) {
                    if ((j > 0) && (0 == (j % 24)))
                        n += my_snprintf(b + n, blen - n, "\n    ");
                    n += my_snprintf(b + n, blen - n, "%02x ", descp[j + 2]);
                }
                n += my_snprintf(b + n, blen - n, "\n");
            }
        }
        if (add_d_len < 0)
            n += my_snprintf(b + n, blen - n, "    short descriptor\n");
    }
}

/* Decode SAT ATA PASS-THROUGH fixed format sense */
static void
sg_get_sense_sat_pt_fixed_str(const unsigned char * sp, int slen, int blen,
                              char * b)
{
    int n = 0;

    if ((blen < 1) || (slen < 12))
        return;
    if (SPC_SK_RECOVERED_ERROR != (0xf & sp[2]))
        n += my_snprintf(b + n, blen - n, "  >> expected Sense key: "
                         "Recovered Error ??\n");
    n += my_snprintf(b + n, blen - n, "  error=0x%x, status=0x%x, "
                     "device=0x%x, sector_count(7:0)=0x%x%c\n", sp[3], sp[4],
                     sp[5], sp[6], ((0x40 & sp[8]) ? '+' : ' '));
    n += my_snprintf(b + n, blen - n, "  extend=%d, log_index=0x%x, "
                     "lba_high,mid,low(7:0)=0x%x,0x%x,0x%x%c\n",
                     (!!(0x80 & sp[8])), (0xf & sp[8]), sp[9], sp[10], sp[11],
                     ((0x20 & sp[8]) ? '+' : ' '));
}

/* Fetch sense information */
void
sg_get_sense_str(const char * leadin, const unsigned char * sense_buffer,
                 int sb_len, int raw_sinfo, int buff_len, char * buff)
{
    int len, valid, progress, n, r, pr, rem, blen;
    unsigned int info;
    int descriptor_format = 0;
    int sdat_ovfl = 0;
    const char * ebp = NULL;
    char error_buff[64];
    char b[256];
    struct sg_scsi_sense_hdr ssh;

    if ((NULL == buff) || (buff_len <= 0))
        return;
    else if (1 == buff_len) {
        buff[0] = '\0';
        return;
    }
    blen = sizeof(b);
    n = 0;
    if (sb_len < 1) {
            my_snprintf(buff, buff_len, "sense buffer empty\n");
            return;
    }
    if (leadin)
        n += my_snprintf(buff + n, buff_len - n, "%s: ", leadin);
    len = sb_len;
    if (sg_scsi_normalize_sense(sense_buffer, sb_len, &ssh)) {
        switch (ssh.response_code) {
        case 0x70:      /* fixed, current */
            ebp = "Fixed format, current";
            len = (sb_len > 7) ? (sense_buffer[7] + 8) : sb_len;
            len = (len > sb_len) ? sb_len : len;
            sdat_ovfl = (len > 2) ? !!(sense_buffer[2] & 0x10) : 0;
            break;
        case 0x71:      /* fixed, deferred */
            /* error related to a previous command */
            ebp = "Fixed format, <<<deferred>>>";
            len = (sb_len > 7) ? (sense_buffer[7] + 8) : sb_len;
            len = (len > sb_len) ? sb_len : len;
            sdat_ovfl = (len > 2) ? !!(sense_buffer[2] & 0x10) : 0;
            break;
        case 0x72:      /* descriptor, current */
            descriptor_format = 1;
            ebp = "Descriptor format, current";
            sdat_ovfl = (sb_len > 4) ? !!(sense_buffer[4] & 0x80) : 0;
            break;
        case 0x73:      /* descriptor, deferred */
            descriptor_format = 1;
            ebp = "Descriptor format, <<<deferred>>>";
            sdat_ovfl = (sb_len > 4) ? !!(sense_buffer[4] & 0x80) : 0;
            break;
        case 0x0:
            ebp = "Response code: 0x0 (?)";
            break;
        default:
            my_snprintf(error_buff, sizeof(error_buff),
                        "Unknown response code: 0x%x", ssh.response_code);
            ebp = error_buff;
            break;
        }
        n += my_snprintf(buff + n, buff_len - n, " %s;  Sense key: %s\n ",
                         ebp, sg_lib_sense_key_desc[ssh.sense_key]);
        if (sdat_ovfl)
            n += my_snprintf(buff + n, buff_len - n, "<<<Sense data "
                             "overflow>>>\n");
        if (descriptor_format) {
            n += my_snprintf(buff + n, buff_len - n, "%s\n",
                             sg_get_asc_ascq_str(ssh.asc, ssh.ascq,
                                                 sizeof(b), b));
            sg_get_sense_descriptors_str(sense_buffer, len, buff_len - n,
                                         buff + n);
            n = strlen(buff);
        } else if ((len > 12) && (0 == ssh.asc) &&
                   (ASCQ_ATA_PT_INFO_AVAILABLE == ssh.ascq)) {
            /* SAT ATA PASS-THROUGH fixed format */
            n += my_snprintf(buff + n, buff_len - n, "%s\n",
                             sg_get_asc_ascq_str(ssh.asc, ssh.ascq,
                             sizeof(b), b));
            sg_get_sense_sat_pt_fixed_str(sense_buffer, len, buff_len - n,
                                          buff + n);
            n = strlen(buff);
        } else if (len > 2) {   /* fixed format */
            if (len > 12)
                n += my_snprintf(buff + n, buff_len - n, "%s\n",
                                 sg_get_asc_ascq_str(ssh.asc, ssh.ascq,
                                                     sizeof(b), b));
            r = 0;
            valid = sense_buffer[0] & 0x80;
            if (len > 6) {
                info = (unsigned int)((sense_buffer[3] << 24) |
                        (sense_buffer[4] << 16) | (sense_buffer[5] << 8) |
                        sense_buffer[6]);
                if (valid)
                    r += my_snprintf(b + r, blen - r, "  Info fld=0x%x [%u] ",
                                     info, info);
                else if (info > 0)
                    r += my_snprintf(b + r, blen - r, "  Valid=0, Info "
                                     "fld=0x%x [%u] ", info, info);
            } else
                info = 0;
            if (sense_buffer[2] & 0xe0) {
                if (sense_buffer[2] & 0x80)
                   r += my_snprintf(b + r, blen - r, " FMK");
                            /* current command has read a filemark */
                if (sense_buffer[2] & 0x40)
                   r += my_snprintf(b + r, blen - r, " EOM");
                            /* end-of-medium condition exists */
                if (sense_buffer[2] & 0x20)
                   r += my_snprintf(b + r, blen - r, " ILI");
                            /* incorrect block length requested */
                r += my_snprintf(b + r, blen - r, "\n");
            } else if (valid || (info > 0))
                r += my_snprintf(b + r, blen - r, "\n");
            if ((len >= 14) && sense_buffer[14])
                r += my_snprintf(b + r, blen - r, "  Field replaceable unit "
                                 "code: %d\n", sense_buffer[14]);
            if ((len >= 18) && (sense_buffer[15] & 0x80)) {
                /* sense key specific decoding */
                switch (ssh.sense_key) {
                case SPC_SK_ILLEGAL_REQUEST:
                    r += my_snprintf(b + r, blen - r, "  Sense Key Specific: "
                             "Error in %s: byte %d",
                             ((sense_buffer[15] & 0x40) ? "Command" :
                                                          "Data parameters"),
                             (sense_buffer[16] << 8) | sense_buffer[17]);
                    if (sense_buffer[15] & 0x08)
                        r += my_snprintf(b + r, blen - r, " bit %d\n",
                                         sense_buffer[15] & 0x07);
                    else
                        r += my_snprintf(b + r, blen - r, "\n");
                    break;
                case SPC_SK_NO_SENSE:
                case SPC_SK_NOT_READY:
                    progress = (sense_buffer[16] << 8) + sense_buffer[17];
                    pr = (progress * 100) / 65536;
                    rem = ((progress * 100) % 65536) / 656;
                    r += my_snprintf(b + r, blen - r, "  Progress "
                                     "indication: %d.%02d%%\n", pr, rem);
                    break;
                case SPC_SK_HARDWARE_ERROR:
                case SPC_SK_MEDIUM_ERROR:
                case SPC_SK_RECOVERED_ERROR:
                    r += my_snprintf(b + r, blen - r, "  Actual retry count: "
                                     "0x%02x%02x\n", sense_buffer[16],
                                     sense_buffer[17]);
                    break;
                case SPC_SK_COPY_ABORTED:
                    r += my_snprintf(b + r, blen - r, "  Segment pointer: ");
                    r += my_snprintf(b + r, blen - r, "Relative to start of "
                                     "%s, byte %d",
                                     ((sense_buffer[15] & 0x20) ?
                                      "segment descriptor" : "parameter list"),
                                     ((sense_buffer[16] << 8) +
                                      sense_buffer[17]));
                    if (sense_buffer[15] & 0x08)
                        r += my_snprintf(b + r, blen - r, " bit %d\n",
                                         sense_buffer[15] & 0x07);
                    else
                        r += my_snprintf(b + r, blen - r, "\n");
                    break;
                case SPC_SK_UNIT_ATTENTION:
                    r += my_snprintf(b + r, blen - r, "  Unit attention "
                                     "condition queue: ");
                    r += my_snprintf(b + r, blen - r, "overflow flag is %d\n",
                                     !!(sense_buffer[15] & 0x1));
                    break;
                default:
                    r += my_snprintf(b + r, blen - r, "  Sense_key: 0x%x "
                                     "unexpected\n", ssh.sense_key);
                    break;
                }
            }
            if (r > 0)
                n += my_snprintf(buff + n, buff_len - n, "%s", b);
        } else
            n += my_snprintf(buff + n, buff_len - n, " fixed descriptor "
                             "length too short, len=%d\n", len);
    } else {    /* non-extended SCSI-1 sense data ?? */
        if (sb_len < 4) {
            n += my_snprintf(buff + n, buff_len - n, "sense buffer too short "
                             "(4 byte minimum)\n");
            return;
        }
        r = 0;
        r += my_snprintf(b + r, blen - r, "Probably uninitialized data.\n  "
                         "Try to view as SCSI-1 non-extended sense:\n");
        r += my_snprintf(b + r, blen - r, "  AdValid=%d  Error class=%d  "
                         "Error code=%d\n", !!(sense_buffer[0] & 0x80),
                         ((sense_buffer[0] >> 4) & 0x7),
                         (sense_buffer[0] & 0xf));
        if (sense_buffer[0] & 0x80)
            r += my_snprintf(b + r, blen - r, "  lba=0x%x\n",
                             ((sense_buffer[1] & 0x1f) << 16) +
                             (sense_buffer[2] << 8) + sense_buffer[3]);
        n += my_snprintf(buff + n, buff_len - n, "%s\n", b);
        len = sb_len;
        if (len > 32)
            len = 32;   /* trim in case there is a lot of rubbish */
    }
    if (raw_sinfo) {
        n += my_snprintf(buff + n, buff_len - n, " Raw sense data (in hex):"
                         "\n");
        if (n >= (buff_len - 1))
            return;
        dStrHexStr((const char *)sense_buffer, len, "        ", 0,
                   buff_len - n, buff + n);
    }
}

/* Print sense information */
void
sg_print_sense(const char * leadin, const unsigned char * sense_buffer,
               int sb_len, int raw_sinfo)
{
    char b[2048];

    sg_get_sense_str(leadin, sense_buffer, sb_len, raw_sinfo, sizeof(b), b);
    if (NULL == sg_warnings_strm)
        sg_warnings_strm = stderr;
    fprintf(sg_warnings_strm, "%s", b);
}

/* See description in sg_lib.h header file */
int
sg_scsi_normalize_sense(const unsigned char * sensep, int sb_len,
                        struct sg_scsi_sense_hdr * sshp)
{
    if (sshp)
        memset(sshp, 0, sizeof(struct sg_scsi_sense_hdr));
    if ((NULL == sensep) || (0 == sb_len) || (0x70 != (0x70 & sensep[0])))
        return 0;
    if (sshp) {
        sshp->response_code = (0x7f & sensep[0]);
        if (sshp->response_code >= 0x72) {  /* descriptor format */
            if (sb_len > 1)
                sshp->sense_key = (0xf & sensep[1]);
            if (sb_len > 2)
                sshp->asc = sensep[2];
            if (sb_len > 3)
                sshp->ascq = sensep[3];
            if (sb_len > 7)
                sshp->additional_length = sensep[7];
        } else {                              /* fixed format */
            if (sb_len > 2)
                sshp->sense_key = (0xf & sensep[2]);
            if (sb_len > 7) {
                sb_len = (sb_len < (sensep[7] + 8)) ? sb_len :
                                                      (sensep[7] + 8);
                if (sb_len > 12)
                    sshp->asc = sensep[12];
                if (sb_len > 13)
                    sshp->ascq = sensep[13];
            }
        }
    }
    return 1;
}

/* Returns a SG_LIB_CAT_* value. If cannot decode sense_buffer or a less
 * common sense key then return SG_LIB_CAT_SENSE .*/
int
sg_err_category_sense(const unsigned char * sense_buffer, int sb_len)
{
    struct sg_scsi_sense_hdr ssh;

    if ((sense_buffer && (sb_len > 2)) &&
        (sg_scsi_normalize_sense(sense_buffer, sb_len, &ssh))) {
        switch (ssh.sense_key) {        /* 0 to 0x1f */
        case SPC_SK_NO_SENSE:
            return SG_LIB_CAT_NO_SENSE;
        case SPC_SK_RECOVERED_ERROR:
            return SG_LIB_CAT_RECOVERED;
        case SPC_SK_NOT_READY:
            return SG_LIB_CAT_NOT_READY;
        case SPC_SK_MEDIUM_ERROR:
        case SPC_SK_HARDWARE_ERROR:
        case SPC_SK_BLANK_CHECK:
            return SG_LIB_CAT_MEDIUM_HARD;
        case SPC_SK_UNIT_ATTENTION:
            return SG_LIB_CAT_UNIT_ATTENTION;
            /* used to return SG_LIB_CAT_MEDIA_CHANGED when ssh.asc==0x28 */
        case SPC_SK_ILLEGAL_REQUEST:
            if ((0x20 == ssh.asc) && (0x0 == ssh.ascq))
                return SG_LIB_CAT_INVALID_OP;
            else
                return SG_LIB_CAT_ILLEGAL_REQ;
            break;
        case SPC_SK_ABORTED_COMMAND:
            if (0x10 == ssh.asc)
                return SG_LIB_CAT_PROTECTION;
            else
                return SG_LIB_CAT_ABORTED_COMMAND;
        case SPC_SK_MISCOMPARE:
            return SG_LIB_CAT_MISCOMPARE;
        case SPC_SK_DATA_PROTECT:
            return SG_LIB_CAT_DATA_PROTECT;
        case SPC_SK_COPY_ABORTED:
            return SG_LIB_CAT_COPY_ABORTED;
        case SPC_SK_COMPLETED:
        case SPC_SK_VOLUME_OVERFLOW:
            return SG_LIB_CAT_SENSE;
        default:
            ;   /* reserved and vendor specific sense keys fall through */
        }
    }
    return SG_LIB_CAT_SENSE;
}

/* Beware: gives wrong answer for variable length command (opcode=0x7f) */
int
sg_get_command_size(unsigned char opcode)
{
    switch ((opcode >> 5) & 0x7) {
    case 0:
        return 6;
    case 1: case 2: case 6: case 7:
        return 10;
    case 3: case 5:
        return 12;
        break;
    case 4:
        return 16;
    default:
        return 10;
    }
}

void
sg_get_command_name(const unsigned char * cmdp, int peri_type, int buff_len,
                    char * buff)
{
    int service_action;

    if ((NULL == buff) || (buff_len < 1))
        return;
    else if (1 == buff_len) {
        buff[0] = '\0';
        return;
    }
    if (NULL == cmdp) {
        my_snprintf(buff, buff_len, "%s", "<null> command pointer");
        return;
    }
    service_action = (SG_VARIABLE_LENGTH_CMD == cmdp[0]) ?
                     ((cmdp[8] << 8) | cmdp[9]) : (cmdp[1] & 0x1f);
    sg_get_opcode_sa_name(cmdp[0], service_action, peri_type, buff_len, buff);
}

struct op_code2sa_t {
    int op_code;
    struct sg_lib_value_name_t * arr;
    const char * prefix;
};

static struct op_code2sa_t op_code2sa_arr[] = {
    {SG_VARIABLE_LENGTH_CMD, sg_lib_variable_length_arr, NULL},
    {SG_MAINTENANCE_IN, sg_lib_maint_in_arr, NULL},
    {SG_MAINTENANCE_OUT, sg_lib_maint_out_arr, NULL},
    {SG_SERVICE_ACTION_IN_12, sg_lib_serv_in12_arr, NULL},
    {SG_SERVICE_ACTION_OUT_12, sg_lib_serv_out12_arr, NULL},
    {SG_SERVICE_ACTION_IN_16, sg_lib_serv_in16_arr, NULL},
    {SG_SERVICE_ACTION_OUT_16, sg_lib_serv_out16_arr, NULL},
    {SG_SERVICE_ACTION_BIDI, sg_lib_serv_bidi_arr, NULL},
    {SG_PERSISTENT_RESERVE_IN, sg_lib_pr_in_arr, "Persistent reserve in"},
    {SG_PERSISTENT_RESERVE_OUT, sg_lib_pr_out_arr, "Persistent reserve out"},
    {SG_THIRD_PARTY_COPY_OUT, sg_lib_xcopy_sa_arr, NULL},
    {SG_THIRD_PARTY_COPY_IN, sg_lib_rec_copy_sa_arr, NULL},
    {SG_READ_BUFFER, sg_lib_read_buff_arr, "Read buffer"},
    {SG_WRITE_BUFFER, sg_lib_write_buff_arr, "Write buffer"},
    {SG_SANITIZE, sg_lib_sanitize_sa_arr, "Sanitize"},
    {0xffff, NULL, NULL},
};


void
sg_get_opcode_sa_name(unsigned char cmd_byte0, int service_action,
                      int peri_type, int buff_len, char * buff)
{
    const struct sg_lib_value_name_t * vnp;
    const struct op_code2sa_t * osp;
    char b[80];

    if ((NULL == buff) || (buff_len < 1))
        return;
    else if (1 == buff_len) {
        buff[0] = '\0';
        return;
    }

    for (osp = op_code2sa_arr; osp->arr; ++osp) {
        if ((int)cmd_byte0 == osp->op_code) {
            vnp = get_value_name(osp->arr, service_action, peri_type);
            if (vnp) {
                if (osp->prefix)
                    my_snprintf(buff, buff_len, "%s, %s", osp->prefix,
                                vnp->name);
                else
                    my_snprintf(buff, buff_len, "%s", vnp->name);
            } else {
                sg_get_opcode_name(cmd_byte0, peri_type, sizeof(b), b);
                my_snprintf(buff, buff_len, "%s service action=0x%x",
                            b, service_action);
            }
            return;
        }
    }

    sg_get_opcode_name(cmd_byte0, peri_type, buff_len, buff);
}

void
sg_get_opcode_name(unsigned char cmd_byte0, int peri_type, int buff_len,
                   char * buff)
{
    const struct sg_lib_value_name_t * vnp;
    int grp;

    if ((NULL == buff) || (buff_len < 1))
        return;
    else if (1 == buff_len) {
        buff[0] = '\0';
        return;
    }
    if (SG_VARIABLE_LENGTH_CMD == cmd_byte0) {
        my_snprintf(buff, buff_len, "%s", "Variable length");
        return;
    }
    grp = (cmd_byte0 >> 5) & 0x7;
    switch (grp) {
    case 0:
    case 1:
    case 2:
    case 4:
    case 5:
        vnp = get_value_name(sg_lib_normal_opcodes, cmd_byte0, peri_type);
        if (vnp)
            my_snprintf(buff, buff_len, "%s", vnp->name);
        else
            my_snprintf(buff, buff_len, "Opcode=0x%x", (int)cmd_byte0);
        break;
    case 3:
        my_snprintf(buff, buff_len, "Reserved [0x%x]", (int)cmd_byte0);
        break;
    case 6:
    case 7:
        my_snprintf(buff, buff_len, "Vendor specific [0x%x]", (int)cmd_byte0);
        break;
    default:
        my_snprintf(buff, buff_len, "Opcode=0x%x", (int)cmd_byte0);
        break;
    }
}

/* Iterates to next designation descriptor in the device identification
 * VPD page. The 'initial_desig_desc' should point to start of first
 * descriptor with 'page_len' being the number of valid bytes in that
 * and following descriptors. To start, 'off' should point to a negative
 * value, thereafter it should point to the value yielded by the previous
 * call. If 0 returned then 'initial_desig_desc + *off' should be a valid
 * descriptor; returns -1 if normal end condition and -2 for an abnormal
 * termination. Matches association, designator_type and/or code_set when
 * any of those values are greater than or equal to zero. */
int
sg_vpd_dev_id_iter(const unsigned char * initial_desig_desc, int page_len,
                   int * off, int m_assoc, int m_desig_type, int m_code_set)
{
    const unsigned char * ucp;
    int k, c_set, assoc, desig_type;

    for (k = *off, ucp = initial_desig_desc ; (k + 3) < page_len; ) {
        k = (k < 0) ? 0 : (k + ucp[k + 3] + 4);
        if ((k + 4) > page_len)
            break;
        c_set = (ucp[k] & 0xf);
        if ((m_code_set >= 0) && (m_code_set != c_set))
            continue;
        assoc = ((ucp[k + 1] >> 4) & 0x3);
        if ((m_assoc >= 0) && (m_assoc != assoc))
            continue;
        desig_type = (ucp[k + 1] & 0xf);
        if ((m_desig_type >= 0) && (m_desig_type != desig_type))
            continue;
        *off = k;
        return 0;
    }
    return (k == page_len) ? -1 : -2;
}

static const char * bad_sense_cat = "Bad sense category";

/* Yield string associated with sense++ category. Returns 'buff' (or pointer
 * to "Bad sense category" if 'buff' is NULL). If sense_cat unknown then
 * yield "Sense category: <sense_cat>" string. */
const char *
sg_get_category_sense_str(int sense_cat, int buff_len, char * buff,
                          int verbose)
{
    int n;

    if (NULL == buff)
        return bad_sense_cat;
    if (buff_len <= 0)
        return buff;
    switch (sense_cat) {
    case SG_LIB_CAT_CLEAN:              /* 0 */
        snprintf(buff, buff_len, "No errors");
        break;
    case SG_LIB_SYNTAX_ERROR:           /* 1 */
        snprintf(buff, buff_len, "Syntax error");
        break;
    case SG_LIB_CAT_NOT_READY:          /* 2 */
        n = snprintf(buff, buff_len, "Not ready");
        if (verbose && (n < (buff_len - 1)))
            snprintf(buff + n, buff_len - n, " sense key");
        break;
    case SG_LIB_CAT_MEDIUM_HARD:        /* 3 */
        n = snprintf(buff, buff_len, "Medium or hardware error");
        if (verbose && (n < (buff_len - 1)))
            snprintf(buff + n, buff_len - n, " sense key (plus blank check)");
        break;
    case SG_LIB_CAT_ILLEGAL_REQ:        /* 5 */
        n = snprintf(buff, buff_len, "Illegal request");
        if (verbose && (n < (buff_len - 1)))
            snprintf(buff + n, buff_len - n, " sense key, apart from Invalid "
                     "opcode");
        break;
    case SG_LIB_CAT_UNIT_ATTENTION:     /* 6 */
        n = snprintf(buff, buff_len, "Unit attention");
        if (verbose && (n < (buff_len - 1)))
            snprintf(buff + n, buff_len - n, " sense key");
        break;
    case SG_LIB_CAT_DATA_PROTECT:       /* 7 */
        n = snprintf(buff, buff_len, "Data protect");
        if (verbose && (n < (buff_len - 1)))
            snprintf(buff + n, buff_len - n, " sense key, write protected "
                     "media?");
        break;
    case SG_LIB_CAT_INVALID_OP:         /* 9 */
        n = snprintf(buff, buff_len, "Illegal request, invalid opcode");
        if (verbose && (n < (buff_len - 1)))
            snprintf(buff + n, buff_len - n, " sense key");
        break;
    case SG_LIB_CAT_COPY_ABORTED:       /* 10 */
        n = snprintf(buff, buff_len, "Copy aborted");
        if (verbose && (n < (buff_len - 1)))
            snprintf(buff + n, buff_len - n, " sense key");
        break;
    case SG_LIB_CAT_ABORTED_COMMAND:    /* 11 */
        n = snprintf(buff, buff_len, "Aborted command");
        if (verbose && (n < (buff_len - 1)))
            snprintf(buff + n, buff_len - n, " sense key, other than "
                     "protection related (asc=0x10)");
        break;
    case SG_LIB_CAT_MISCOMPARE:         /* 14 */
        n = snprintf(buff, buff_len, "Miscompare");
        if (verbose && (n < (buff_len - 1)))
            snprintf(buff + n, buff_len - n, " sense key");
        break;
    case SG_LIB_FILE_ERROR:             /* 15 */
        snprintf(buff, buff_len, "File error");
        break;
    case SG_LIB_CAT_ILLEGAL_REQ_WITH_INFO:  /* 17 */
        snprintf(buff, buff_len, "Illegal request with info");
        break;
    case SG_LIB_CAT_MEDIUM_HARD_WITH_INFO:  /* 18 */
        snprintf(buff, buff_len, "Medium or hardware error with info");
        break;
    case SG_LIB_CAT_NO_SENSE:           /* 20 */
        n = snprintf(buff, buff_len, "No sense key");
        if (verbose && (n < (buff_len - 1)))
            snprintf(buff + n, buff_len - n, " probably additional sense "
                     "information");
        break;
    case SG_LIB_CAT_RECOVERED:          /* 21 */
        n = snprintf(buff, buff_len, "Recovered error");
        if (verbose && (n < (buff_len - 1)))
            snprintf(buff + n, buff_len - n, " sense key");
        break;
    case SG_LIB_CAT_RES_CONFLICT:       /* 24 */
        n = snprintf(buff, buff_len, "Reservation conflict");
        if (verbose && (n < (buff_len - 1)))
            snprintf(buff + n, buff_len - n, " SCSI status");
        break;
    case SG_LIB_CAT_TIMEOUT:            /* 33 */
        snprintf(buff, buff_len, "SCSI command timeout");
        break;
    case SG_LIB_CAT_PROTECTION:         /* 40 */
        n = snprintf(buff, buff_len, "Aborted command, protection");
        if (verbose && (n < (buff_len - 1)))
            snprintf(buff + n, buff_len - n, " information (PI) problem");
        break;
    case SG_LIB_CAT_PROTECTION_WITH_INFO: /* 41 */
        n = snprintf(buff, buff_len, "Aborted command with info, protection");
        if (verbose && (n < (buff_len - 1)))
            snprintf(buff + n, buff_len - n, " information (PI) problem");
        break;
    case SG_LIB_CAT_MALFORMED:          /* 97 */
        n = snprintf(buff, buff_len, "Malformed response");
        if (verbose && (n < (buff_len - 1)))
            snprintf(buff + n, buff_len - n, " to SCSI command");
        break;
    case SG_LIB_CAT_SENSE:              /* 98 */
        n = snprintf(buff, buff_len, "Some other sense data problem");
        if (verbose && (n < (buff_len - 1)))
            snprintf(buff + n, buff_len - n, ", try '-v' option for more "
                     "information");
        break;
    case SG_LIB_CAT_OTHER:              /* 99 */
        n = snprintf(buff, buff_len, "Some other error/warning has occurred");
        if (verbose && (n < (buff_len - 1)))
            snprintf(buff + n, buff_len - n, ", possible transport of driver "
                     "issue");
    default:
        n = snprintf(buff, buff_len, "Sense category: %d", sense_cat);
        if (verbose && (n < (buff_len - 1)))
            snprintf(buff + n, buff_len - n, ", try '-v' option for more "
                     "information");
        break;
    }
    return buff;
}

/* safe_strerror() contributed by Clayton Weaver <cgweav at email dot com>
 * Allows for situation in which strerror() is given a wild value (or the
 * C library is incomplete) and returns NULL. Still not thread safe.
 */

static char safe_errbuf[64] = {'u', 'n', 'k', 'n', 'o', 'w', 'n', ' ',
                               'e', 'r', 'r', 'n', 'o', ':', ' ', 0};

char *
safe_strerror(int errnum)
{
    size_t len;
    char * errstr;

    if (errnum < 0)
        errnum = -errnum;
    errstr = strerror(errnum);
    if (NULL == errstr) {
        len = strlen(safe_errbuf);
        my_snprintf(safe_errbuf + len, sizeof(safe_errbuf) - len, "%i",
                    errnum);
        return safe_errbuf;
    }
    return errstr;
}

static void
trimTrailingSpaces(char * b)
{
    int k;

    for (k = ((int)strlen(b) - 1); k >= 0; --k) {
        if (' ' != b[k])
            break;
    }
    if ('\0' != b[k + 1])
        b[k + 1] = '\0';
}

/* Note the ASCII-hex output goes to stdout. [Most other output from functions
 * in this file go to sg_warnings_strm (default stderr).]
 * 'no_ascii' allows for 3 output types:
 *     > 0     each line has address then up to 16 ASCII-hex bytes
 *     = 0     in addition, the bytes are listed in ASCII to the right
 *     < 0     only the ASCII-hex bytes are listed (i.e. without address) */
static void
dStrHexFp(const char* str, int len, int no_ascii, FILE * fp)
{
    const char * p = str;
    const char * formatstr;
    unsigned char c;
    char buff[82];
    int a = 0;
    int bpstart = 5;
    const int cpstart = 60;
    int cpos = cpstart;
    int bpos = bpstart;
    int i, k, blen;

    if (len <= 0)
        return;
    blen = (int)sizeof(buff);
    if (0 == no_ascii)  /* address at left and ASCII at right */
        formatstr = "%.76s\n";
    else if (no_ascii > 0)
        formatstr = "%s\n";     /* was: "%.58s\n" */
    else /* negative: no address at left and no ASCII at right */
        formatstr = "%s\n";     /* was: "%.48s\n"; */
    memset(buff, ' ', 80);
    buff[80] = '\0';
    if (no_ascii < 0) {
        bpstart = 0;
        bpos = bpstart;
        for (k = 0; k < len; k++) {
            c = *p++;
            if (bpos == (bpstart + (8 * 3)))
                bpos++;
            my_snprintf(&buff[bpos], blen - bpos, "%.2x",
                        (int)(unsigned char)c);
            buff[bpos + 2] = ' ';
            if ((k > 0) && (0 == ((k + 1) % 16))) {
                trimTrailingSpaces(buff);
                fprintf(fp, formatstr, buff);
                bpos = bpstart;
                memset(buff, ' ', 80);
            } else
                bpos += 3;
        }
        if (bpos > bpstart) {
            buff[bpos + 2] = '\0';
            trimTrailingSpaces(buff);
            fprintf(fp, "%s\n", buff);
        }
        return;
    }
    /* no_ascii>=0, start each line with address (offset) */
    k = my_snprintf(buff + 1, blen - 1, "%.2x", a);
    buff[k + 1] = ' ';

    for (i = 0; i < len; i++) {
        c = *p++;
        bpos += 3;
        if (bpos == (bpstart + (9 * 3)))
            bpos++;
        my_snprintf(&buff[bpos], blen - bpos, "%.2x", (int)(unsigned char)c);
        buff[bpos + 2] = ' ';
        if (no_ascii)
            buff[cpos++] = ' ';
        else {
            if ((c < ' ') || (c >= 0x7f))
                c = '.';
            buff[cpos++] = c;
        }
        if (cpos > (cpstart + 15)) {
            if (no_ascii)
                trimTrailingSpaces(buff);
            fprintf(fp, formatstr, buff);
            bpos = bpstart;
            cpos = cpstart;
            a += 16;
            memset(buff, ' ', 80);
            k = my_snprintf(buff + 1, blen - 1, "%.2x", a);
            buff[k + 1] = ' ';
        }
    }
    if (cpos > cpstart) {
        buff[cpos] = '\0';
        if (no_ascii)
            trimTrailingSpaces(buff);
        fprintf(fp, "%s\n", buff);
    }
}

void
dStrHex(const char* str, int len, int no_ascii)
{
    dStrHexFp(str, len, no_ascii, stdout);
}

void
dStrHexErr(const char* str, int len, int no_ascii)
{
    dStrHexFp(str, len, no_ascii,
              (sg_warnings_strm ? sg_warnings_strm : stderr));
}

/* Read 'len' bytes from 'str' and output as ASCII-Hex bytes (space
 * separated) to 'b' not to exceed 'b_len' characters. Each line
 * starts with 'leadin' (NULL for no leadin) and there are 16 bytes
 * per line with an extra space between the 8th and 9th bytes. 'format'
 * is unused (currently), set to 0 . */
void
dStrHexStr(const char* str, int len, const char * leadin, int format,
           int b_len, char * b)
{
    const char * p = str;
    unsigned char c;
    char buff[122];
    int bpstart, bpos, k, n;

    if (len <= 0) {
        if (b_len > 0)
            b[0] = '\0';
        return;
    }
    if (0 != format) {
        ;       /* do nothing different for now */
    }
    if (leadin) {
        bpstart = strlen(leadin);
        /* Cap leadin at 60 characters */
        if (bpstart > 60)
            bpstart = 60;
    } else
        bpstart = 0;
    bpos = bpstart;
    n = 0;
    memset(buff, ' ', 120);
    buff[120] = '\0';
    if (bpstart > 0)
        memcpy(buff, leadin, bpstart);
    for (k = 0; k < len; k++) {
        c = *p++;
        if (bpos == (bpstart + (8 * 3)))
            bpos++;
        my_snprintf(&buff[bpos], (int)sizeof(buff) - bpos, "%.2x",
                    (int)(unsigned char)c);
        buff[bpos + 2] = ' ';
        if ((k > 0) && (0 == ((k + 1) % 16))) {
            trimTrailingSpaces(buff);
            n += my_snprintf(b + n, b_len - n, "%s\n", buff);
            if (n >= (b_len - 1))
                return;
            bpos = bpstart;
            memset(buff, ' ', 120);
            if (bpstart > 0)
                memcpy(buff, leadin, bpstart);
        } else
            bpos += 3;
    }
    if (bpos > bpstart) {
        trimTrailingSpaces(buff);
        n += my_snprintf(b + n, b_len - n, "%s\n", buff);
    }
    return;
}

/* Returns 1 when executed on big endian machine; else returns 0.
 * Useful for displaying ATA identify words (which need swapping on a
 * big endian machine). */
int
sg_is_big_endian()
{
    union u_t {
        unsigned short s;
        unsigned char c[sizeof(unsigned short)];
    } u;

    u.s = 0x0102;
    return (u.c[0] == 0x01);     /* The lowest address contains
                                    the most significant byte */
}

static unsigned short
swapb_ushort(unsigned short u)
{
    unsigned short r;

    r = (u >> 8) & 0xff;
    r |= ((u & 0xff) << 8);
    return r;
}

/* Note the ASCII-hex output goes to stdout. [Most other output from functions
 * in this file go to sg_warnings_strm (default stderr).]
 * 'no_ascii' allows for 3 output types:
 *     > 0     each line has address then up to 8 ASCII-hex 16 bit words
 *     = 0     in addition, the ASCI bytes pairs are listed to the right
 *     = -1    only the ASCII-hex words are listed (i.e. without address)
 *     = -2    only the ASCII-hex words, formatted for "hdparm --Istdin"
 *     < -2    same as -1
 * If 'swapb' non-zero then bytes in each word swapped. Needs to be set
 * for ATA IDENTIFY DEVICE response on big-endian machines. */
void
dWordHex(const unsigned short* words, int num, int no_ascii, int swapb)
{
    const unsigned short * p = words;
    unsigned short c;
    char buff[82];
    unsigned char upp, low;
    int a = 0;
    const int bpstart = 3;
    const int cpstart = 52;
    int cpos = cpstart;
    int bpos = bpstart;
    int i, k, blen;

    if (num <= 0)
        return;
    blen = (int)sizeof(buff);
    memset(buff, ' ', 80);
    buff[80] = '\0';
    if (no_ascii < 0) {
        for (k = 0; k < num; k++) {
            c = *p++;
            if (swapb)
                c = swapb_ushort(c);
            bpos += 5;
            my_snprintf(&buff[bpos], blen - bpos, "%.4x", (unsigned int)c);
            buff[bpos + 4] = ' ';
            if ((k > 0) && (0 == ((k + 1) % 8))) {
                if (-2 == no_ascii)
                    printf("%.39s\n", buff +8);
                else
                    printf("%.47s\n", buff);
                bpos = bpstart;
                memset(buff, ' ', 80);
            }
        }
        if (bpos > bpstart) {
            if (-2 == no_ascii)
                printf("%.39s\n", buff +8);
            else
                printf("%.47s\n", buff);
        }
        return;
    }
    /* no_ascii>=0, start each line with address (offset) */
    k = my_snprintf(buff + 1, blen - 1, "%.2x", a);
    buff[k + 1] = ' ';

    for (i = 0; i < num; i++) {
        c = *p++;
        if (swapb)
            c = swapb_ushort(c);
        bpos += 5;
        my_snprintf(&buff[bpos], blen - bpos, "%.4x", (unsigned int)c);
        buff[bpos + 4] = ' ';
        if (no_ascii) {
            buff[cpos++] = ' ';
            buff[cpos++] = ' ';
            buff[cpos++] = ' ';
        } else {
            upp = (c >> 8) & 0xff;
            low = c & 0xff;
            if ((upp < 0x20) || (upp >= 0x7f))
                upp = '.';
            buff[cpos++] = upp;
            if ((low < 0x20) || (low >= 0x7f))
                low = '.';
            buff[cpos++] = low;
            buff[cpos++] = ' ';
        }
        if (cpos > (cpstart + 23)) {
            printf("%.76s\n", buff);
            bpos = bpstart;
            cpos = cpstart;
            a += 8;
            memset(buff, ' ', 80);
            k = my_snprintf(buff + 1, blen - 1, "%.2x", a);
            buff[k + 1] = ' ';
        }
    }
    if (cpos > cpstart)
        printf("%.76s\n", buff);
}

/* If the number in 'buf' can be decoded or the multiplier is unknown
 * then -1 is returned. Accepts a hex prefix (0x or 0X) or a decimal
 * multiplier suffix (as per GNU's dd (since 2002: SI and IEC 60027-2)).
 * Main (SI) multipliers supported: K, M, G. Ignore leading spaces and
 * tabs; accept comma, space, tab and hash as terminator. */
int
sg_get_num(const char * buf)
{
    int res, num, n, len;
    unsigned int unum;
    char * cp;
    const char * b;
    char c = 'c';
    char c2, c3;
    char lb[16];

    if ((NULL == buf) || ('\0' == buf[0]))
        return -1;
    len = strlen(buf);
    n = strspn(buf, " \t");
    if (n > 0) {
        if (n == len)
            return -1;
        buf += n;
        len -=n;
    }
    /* following hack to keep C++ happy */
    cp = strpbrk((char *)buf, " \t,#");
    if (cp) {
        len = cp - buf;
        n = (int)sizeof(lb) - 1;
        len = (len < n) ? len : n;
        memcpy(lb, buf, len);
        lb[len] = '\0';
        b = lb;
    } else
        b = buf;
    if (('0' == b[0]) && (('x' == b[1]) || ('X' == b[1]))) {
        res = sscanf(b + 2, "%x", &unum);
        num = unum;
    } else if ('H' == toupper((int)b[len - 1])) {
        res = sscanf(b, "%x", &unum);
        num = unum;
    } else
        res = sscanf(b, "%d%c%c%c", &num, &c, &c2, &c3);
    if (res < 1)
        return -1LL;
    else if (1 == res)
        return num;
    else {
        if (res > 2)
            c2 = toupper((int)c2);
        if (res > 3)
            c3 = toupper((int)c3);
        switch (toupper((int)c)) {
        case 'C':
            return num;
        case 'W':
            return num * 2;
        case 'B':
            return num * 512;
        case 'K':
            if (2 == res)
                return num * 1024;
            if (('B' == c2) || ('D' == c2))
                return num * 1000;
            if (('I' == c2) && (4 == res) && ('B' == c3))
                return num * 1024;
            return -1;
        case 'M':
            if (2 == res)
                return num * 1048576;
            if (('B' == c2) || ('D' == c2))
                return num * 1000000;
            if (('I' == c2) && (4 == res) && ('B' == c3))
                return num * 1048576;
            return -1;
        case 'G':
            if (2 == res)
                return num * 1073741824;
            if (('B' == c2) || ('D' == c2))
                return num * 1000000000;
            if (('I' == c2) && (4 == res) && ('B' == c3))
                return num * 1073741824;
            return -1;
        case 'X':
            cp = (char *)strchr(b, 'x');
            if (NULL == cp)
                cp = (char *)strchr(b, 'X');
            if (cp) {
                n = sg_get_num(cp + 1);
                if (-1 != n)
                    return num * n;
            }
            return -1;
        default:
            if (NULL == sg_warnings_strm)
                sg_warnings_strm = stderr;
            fprintf(sg_warnings_strm, "unrecognized multiplier\n");
            return -1;
        }
    }
}

/* If the number in 'buf' can not be decoded then -1 is returned. Accepts a
 * hex prefix (0x or 0X) or a 'h' (or 'H') suffix; otherwise decimal is
 * assumed. Does not accept multipliers. Accept a comma (","), a whitespace
 * or newline as terminator. */
int
sg_get_num_nomult(const char * buf)
{
    int res, len, num;
    unsigned int unum;
    char * commap;

    if ((NULL == buf) || ('\0' == buf[0]))
        return -1;
    len = strlen(buf);
    commap = (char *)strchr(buf + 1, ',');
    if (('0' == buf[0]) && (('x' == buf[1]) || ('X' == buf[1]))) {
        res = sscanf(buf + 2, "%x", &unum);
        num = unum;
    } else if (commap && ('H' == toupper((int)*(commap - 1)))) {
        res = sscanf(buf, "%x", &unum);
        num = unum;
    } else if ((NULL == commap) && ('H' == toupper((int)buf[len - 1]))) {
        res = sscanf(buf, "%x", &unum);
        num = unum;
    } else
        res = sscanf(buf, "%d", &num);
    if (1 == res)
        return num;
    else
        return -1;
}

/* If the number in 'buf' can be decoded or the multiplier is unknown
 * then -1LL is returned. Accepts a hex prefix (0x or 0X) or a decimal
 * multiplier suffix (as per GNU's dd (since 2002: SI and IEC 60027-2)).
 * Main (SI) multipliers supported: K, M, G, T, P. Ignore leading spaces
 * and tabs; accept comma, space, tab and hash as terminator. */
int64_t
sg_get_llnum(const char * buf)
{
    int res, len, n;
    int64_t num, ll;
    uint64_t unum;
    char * cp;
    const char * b;
    char c = 'c';
    char c2, c3;
    char lb[32];

    if ((NULL == buf) || ('\0' == buf[0]))
        return -1LL;
    len = strlen(buf);
    n = strspn(buf, " \t");
    if (n > 0) {
        if (n == len)
            return -1LL;
        buf += n;
        len -=n;
    }
    /* following hack to keep C++ happy */
    cp = strpbrk((char *)buf, " \t,#");
    if (cp) {
        len = cp - buf;
        n = (int)sizeof(lb) - 1;
        len = (len < n) ? len : n;
        memcpy(lb, buf, len);
        lb[len] = '\0';
        b = lb;
    } else
        b = buf;
    if (('0' == b[0]) && (('x' == b[1]) || ('X' == b[1]))) {
        res = sscanf(b + 2, "%" SCNx64 "", &unum);
        num = unum;
    } else if ('H' == toupper((int)b[len - 1])) {
        res = sscanf(b, "%" SCNx64 "", &unum);
        num = unum;
    } else
        res = sscanf(b, "%" SCNd64 "%c%c%c", &num, &c, &c2, &c3);
    if (res < 1)
        return -1LL;
    else if (1 == res)
        return num;
    else {
        if (res > 2)
            c2 = toupper((int)c2);
        if (res > 3)
            c3 = toupper((int)c3);
        switch (toupper((int)c)) {
        case 'C':
            return num;
        case 'W':
            return num * 2;
        case 'B':
            return num * 512;
        case 'K':
            if (2 == res)
                return num * 1024;
            if (('B' == c2) || ('D' == c2))
                return num * 1000;
            if (('I' == c2) && (4 == res) && ('B' == c3))
                return num * 1024;
            return -1LL;
        case 'M':
            if (2 == res)
                return num * 1048576;
            if (('B' == c2) || ('D' == c2))
                return num * 1000000;
            if (('I' == c2) && (4 == res) && ('B' == c3))
                return num * 1048576;
            return -1LL;
        case 'G':
            if (2 == res)
                return num * 1073741824;
            if (('B' == c2) || ('D' == c2))
                return num * 1000000000;
            if (('I' == c2) && (4 == res) && ('B' == c3))
                return num * 1073741824;
            return -1LL;
        case 'T':
            if (2 == res)
                return num * 1099511627776LL;
            if (('B' == c2) || ('D' == c2))
                return num * 1000000000000LL;
            if (('I' == c2) && (4 == res) && ('B' == c3))
                return num * 1099511627776LL;
            return -1LL;
        case 'P':
            if (2 == res)
                return num * 1099511627776LL * 1024;
            if (('B' == c2) || ('D' == c2))
                return num * 1000000000000LL * 1000;
            if (('I' == c2) && (4 == res) && ('B' == c3))
                return num * 1099511627776LL * 1024;
            return -1LL;
        case 'X':
            cp = (char *)strchr(b, 'x');
            if (NULL == cp)
                cp = (char *)strchr(b, 'X');
            if (cp) {
                ll = sg_get_llnum(cp + 1);
                if (-1LL != ll)
                    return num * ll;
            }
            return -1LL;
        default:
            if (NULL == sg_warnings_strm)
                sg_warnings_strm = stderr;
            fprintf(sg_warnings_strm, "unrecognized multiplier\n");
            return -1LL;
        }
    }
}

/* Extract character sequence from ATA words as in the model string
 * in a IDENTIFY DEVICE response. Returns number of characters
 * written to 'ochars' before 0 character is found or 'num' words
 * are processed. */
int
sg_ata_get_chars(const unsigned short * word_arr, int start_word,
                 int num_words, int is_big_endian, char * ochars)
{
    int k;
    unsigned short s;
    char a, b;
    char * op = ochars;

    for (k = start_word; k < (start_word + num_words); ++k) {
        s = word_arr[k];
        if (is_big_endian) {
            a = s & 0xff;
            b = (s >> 8) & 0xff;
        } else {
            a = (s >> 8) & 0xff;
            b = s & 0xff;
        }
        if (a == 0)
            break;
        *op++ = a;
        if (b == 0)
            break;
        *op++ = b;
    }
    return op - ochars;
}

const char *
sg_lib_version()
{
    return sg_lib_version_str;
}


#ifdef SG_LIB_MINGW
/* Non Unix OSes distinguish between text and binary files.
   Set text mode on fd. Does nothing in Unix. Returns negative number on
   failure. */

#include <unistd.h>
#include <fcntl.h>

int
sg_set_text_mode(int fd)
{
    return setmode(fd, O_TEXT);
}

/* Set binary mode on fd. Does nothing in Unix. Returns negative number on
   failure. */
int
sg_set_binary_mode(int fd)
{
    return setmode(fd, O_BINARY);
}

#else
/* For Unix the following functions are dummies. */
int
sg_set_text_mode(int fd)
{
    return fd;  /* fd should be >= 0 */
}

int
sg_set_binary_mode(int fd)
{
    return fd;
}

#endif