Linux debugging

Check our new training course

Linux debugging, tracing, profiling & perf. analysis

Check our new training course
with Creative Commons CC-BY-SA
lecture and lab materials

Bootlin logo

Elixir Cross Referencer

   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
/* vi: set sw=4 ts=4: */
/*
 * hdparm implementation for busybox
 *
 * Copyright (C) [2003] by [Matteo Croce] <3297627799@wind.it>
 * Hacked by Tito <farmatito@tiscali.it> for size optimization.
 *
 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
 *
 * This program is based on the source code of hdparm: see below...
 * hdparm.c - Command line interface to get/set hard disk parameters
 *          - by Mark Lord (C) 1994-2002 -- freely distributable
 */

#include "libbb.h"
#include <linux/hdreg.h>

/* device types */
/* ------------ */
#define NO_DEV                  0xffff
#define ATA_DEV                 0x0000
#define ATAPI_DEV               0x0001

/* word definitions */
/* ---------------- */
#define GEN_CONFIG		0   /* general configuration */
#define LCYLS			1   /* number of logical cylinders */
#define CONFIG			2   /* specific configuration */
#define LHEADS			3   /* number of logical heads */
#define TRACK_BYTES		4   /* number of bytes/track (ATA-1) */
#define SECT_BYTES		5   /* number of bytes/sector (ATA-1) */
#define LSECTS			6   /* number of logical sectors/track */
#define START_SERIAL            10  /* ASCII serial number */
#define LENGTH_SERIAL           10  /* 10 words (20 bytes or characters) */
#define BUF_TYPE		20  /* buffer type (ATA-1) */
#define BUFFER__SIZE		21  /* buffer size (ATA-1) */
#define RW_LONG			22  /* extra bytes in R/W LONG cmd ( < ATA-4)*/
#define START_FW_REV            23  /* ASCII firmware revision */
#define LENGTH_FW_REV		 4  /*  4 words (8 bytes or characters) */
#define START_MODEL		27  /* ASCII model number */
#define LENGTH_MODEL		20  /* 20 words (40 bytes or characters) */
#define SECTOR_XFER_MAX		47  /* r/w multiple: max sectors xfered */
#define DWORD_IO		48  /* can do double-word IO (ATA-1 only) */
#define CAPAB_0			49  /* capabilities */
#define CAPAB_1			50
#define PIO_MODE		51  /* max PIO mode supported (obsolete)*/
#define DMA_MODE		52  /* max Singleword DMA mode supported (obs)*/
#define WHATS_VALID		53  /* what fields are valid */
#define LCYLS_CUR		54  /* current logical cylinders */
#define LHEADS_CUR		55  /* current logical heads */
#define LSECTS_CUR		56  /* current logical sectors/track */
#define CAPACITY_LSB		57  /* current capacity in sectors */
#define CAPACITY_MSB		58
#define SECTOR_XFER_CUR		59  /* r/w multiple: current sectors xfered */
#define LBA_SECTS_LSB		60  /* LBA: total number of user */
#define LBA_SECTS_MSB		61  /*      addressable sectors */
#define SINGLE_DMA		62  /* singleword DMA modes */
#define MULTI_DMA		63  /* multiword DMA modes */
#define ADV_PIO_MODES		64  /* advanced PIO modes supported */
				    /* multiword DMA xfer cycle time: */
#define DMA_TIME_MIN		65  /*   - minimum */
#define DMA_TIME_NORM		66  /*   - manufacturer's recommended	*/
				    /* minimum PIO xfer cycle time: */
#define PIO_NO_FLOW		67  /*   - without flow control */
#define PIO_FLOW		68  /*   - with IORDY flow control */
#define PKT_REL			71  /* typical #ns from PKT cmd to bus rel */
#define SVC_NBSY		72  /* typical #ns from SERVICE cmd to !BSY */
#define CDR_MAJOR		73  /* CD ROM: major version number */
#define CDR_MINOR		74  /* CD ROM: minor version number */
#define QUEUE_DEPTH		75  /* queue depth */
#define MAJOR			80  /* major version number */
#define MINOR			81  /* minor version number */
#define CMDS_SUPP_0		82  /* command/feature set(s) supported */
#define CMDS_SUPP_1		83
#define CMDS_SUPP_2		84
#define CMDS_EN_0		85  /* command/feature set(s) enabled */
#define CMDS_EN_1		86
#define CMDS_EN_2		87
#define ULTRA_DMA		88  /* ultra DMA modes */
				    /* time to complete security erase */
#define ERASE_TIME		89  /*   - ordinary */
#define ENH_ERASE_TIME		90  /*   - enhanced */
#define ADV_PWR			91  /* current advanced power management level
				       in low byte, 0x40 in high byte. */
#define PSWD_CODE		92  /* master password revision code	*/
#define HWRST_RSLT		93  /* hardware reset result */
#define ACOUSTIC		94  /* acoustic mgmt values ( >= ATA-6) */
#define LBA_LSB			100 /* LBA: maximum.  Currently only 48 */
#define LBA_MID			101 /*      bits are used, but addr 103 */
#define LBA_48_MSB		102 /*      has been reserved for LBA in */
#define LBA_64_MSB		103 /*      the future. */
#define RM_STAT			127 /* removable media status notification feature set support */
#define SECU_STATUS		128 /* security status */
#define CFA_PWR_MODE		160 /* CFA power mode 1 */
#define START_MEDIA             176 /* media serial number */
#define LENGTH_MEDIA            20  /* 20 words (40 bytes or characters)*/
#define START_MANUF             196 /* media manufacturer I.D. */
#define LENGTH_MANUF            10  /* 10 words (20 bytes or characters) */
#define INTEGRITY		255 /* integrity word */

/* bit definitions within the words */
/* -------------------------------- */

/* many words are considered valid if bit 15 is 0 and bit 14 is 1 */
#define VALID			0xc000
#define VALID_VAL		0x4000
/* many words are considered invalid if they are either all-0 or all-1 */
#define NOVAL_0			0x0000
#define NOVAL_1			0xffff

/* word 0: gen_config */
#define NOT_ATA			0x8000
#define NOT_ATAPI		0x4000	/* (check only if bit 15 == 1) */
#define MEDIA_REMOVABLE		0x0080
#define DRIVE_NOT_REMOVABLE	0x0040  /* bit obsoleted in ATA 6 */
#define INCOMPLETE		0x0004
#define CFA_SUPPORT_VAL		0x848a	/* 848a=CFA feature set support */
#define DRQ_RESPONSE_TIME	0x0060
#define DRQ_3MS_VAL		0x0000
#define DRQ_INTR_VAL		0x0020
#define DRQ_50US_VAL		0x0040
#define PKT_SIZE_SUPPORTED	0x0003
#define PKT_SIZE_12_VAL		0x0000
#define PKT_SIZE_16_VAL		0x0001
#define EQPT_TYPE		0x1f00
#define SHIFT_EQPT		8

#define CDROM 0x0005

/* word 1: number of logical cylinders */
#define LCYLS_MAX		0x3fff /* maximum allowable value */

/* word 2: specific configuration
 * (a) require SET FEATURES to spin-up
 * (b) require spin-up to fully reply to IDENTIFY DEVICE
 */
#define STBY_NID_VAL		0x37c8  /*     (a) and     (b) */
#define STBY_ID_VAL		0x738c	/*     (a) and not (b) */
#define PWRD_NID_VAL		0x8c73	/* not (a) and     (b) */
#define PWRD_ID_VAL		0xc837	/* not (a) and not (b) */

/* words 47 & 59: sector_xfer_max & sector_xfer_cur */
#define SECTOR_XFER		0x00ff  /* sectors xfered on r/w multiple cmds*/
#define MULTIPLE_SETTING_VALID  0x0100  /* 1=multiple sector setting is valid */

/* word 49: capabilities 0 */
#define STD_STBY		0x2000  /* 1=standard values supported (ATA); 0=vendor specific values */
#define IORDY_SUP		0x0800  /* 1=support; 0=may be supported */
#define IORDY_OFF		0x0400  /* 1=may be disabled */
#define LBA_SUP			0x0200  /* 1=Logical Block Address support */
#define DMA_SUP			0x0100  /* 1=Direct Memory Access support */
#define DMA_IL_SUP		0x8000  /* 1=interleaved DMA support (ATAPI) */
#define CMD_Q_SUP		0x4000  /* 1=command queuing support (ATAPI) */
#define OVLP_SUP		0x2000  /* 1=overlap operation support (ATAPI) */
#define SWRST_REQ		0x1000  /* 1=ATA SW reset required (ATAPI, obsolete */

/* word 50: capabilities 1 */
#define MIN_STANDBY_TIMER	0x0001  /* 1=device specific standby timer value minimum */

/* words 51 & 52: PIO & DMA cycle times */
#define MODE			0xff00  /* the mode is in the MSBs */

/* word 53: whats_valid */
#define OK_W88			0x0004	/* the ultra_dma info is valid */
#define OK_W64_70		0x0002  /* see above for word descriptions */
#define OK_W54_58		0x0001  /* current cyl, head, sector, cap. info valid */

/*word 63,88: dma_mode, ultra_dma_mode*/
#define MODE_MAX		7	/* bit definitions force udma <=7 (when
					 * udma >=8 comes out it'll have to be
					 * defined in a new dma_mode word!) */

/* word 64: PIO transfer modes */
#define PIO_SUP			0x00ff  /* only bits 0 & 1 are used so far,  */
#define PIO_MODE_MAX		8       /* but all 8 bits are defined        */

/* word 75: queue_depth */
#define DEPTH_BITS		0x001f  /* bits used for queue depth */

/* words 80-81: version numbers */
/* NOVAL_0 or  NOVAL_1 means device does not report version */

/* word 81: minor version number */
#define MINOR_MAX		0x22
/* words 82-84: cmds/feats supported */
#define CMDS_W82		0x77ff  /* word 82: defined command locations*/
#define CMDS_W83		0x3fff  /* word 83: defined command locations*/
#define CMDS_W84		0x002f  /* word 83: defined command locations*/
#define SUPPORT_48_BIT		0x0400
#define NUM_CMD_FEAT_STR	48

/* words 85-87: cmds/feats enabled */
/* use cmd_feat_str[] to display what commands and features have
 * been enabled with words 85-87
 */

/* words 89, 90, SECU ERASE TIME */
#define ERASE_BITS      0x00ff

/* word 92: master password revision */
/* NOVAL_0 or  NOVAL_1 means no support for master password revision */

/* word 93: hw reset result */
#define CBLID           0x2000  /* CBLID status */
#define RST0            0x0001  /* 1=reset to device #0 */
#define DEV_DET         0x0006  /* how device num determined */
#define JUMPER_VAL      0x0002  /* device num determined by jumper */
#define CSEL_VAL        0x0004  /* device num determined by CSEL_VAL */

/* word 127: removable media status notification feature set support */
#define RM_STAT_BITS    0x0003
#define RM_STAT_SUP     0x0001

/* word 128: security */
#define SECU_ENABLED    0x0002
#define SECU_LEVEL      0x0010
#define NUM_SECU_STR    6

/* word 160: CFA power mode */
#define VALID_W160              0x8000  /* 1=word valid */
#define PWR_MODE_REQ            0x2000  /* 1=CFA power mode req'd by some cmds*/
#define PWR_MODE_OFF            0x1000  /* 1=CFA power moded disabled */
#define MAX_AMPS                0x0fff  /* value = max current in ma */

/* word 255: integrity */
#define SIG                     0x00ff  /* signature location */
#define SIG_VAL                 0x00a5  /* signature value */

#define TIMING_BUF_MB           1
#define TIMING_BUF_BYTES        (TIMING_BUF_MB * 1024 * 1024)

#undef DO_FLUSHCACHE            /* under construction: force cache flush on -W0 */


enum { fd = 3 };


struct globals {
	smallint get_identity, get_geom;
	smallint do_flush;
	smallint do_ctimings, do_timings;
	smallint reread_partn;
	smallint set_piomode, noisy_piomode;
	smallint set_readahead, get_readahead;
	smallint set_readonly, get_readonly;
	smallint set_unmask, get_unmask;
	smallint set_mult, get_mult;
#ifdef HDIO_GET_QDMA
	smallint get_dma_q;
#ifdef HDIO_SET_QDMA
	smallint set_dma_q;
#endif
#endif
	smallint set_nowerr, get_nowerr;
	smallint set_keep, get_keep;
	smallint set_io32bit, get_io32bit;
	int piomode;
	unsigned long Xreadahead;
	unsigned long readonly;
	unsigned long unmask;
	unsigned long mult;
#ifdef HDIO_SET_QDMA
	unsigned long dma_q;
#endif
	unsigned long nowerr;
	unsigned long keep;
	unsigned long io32bit;
#if ENABLE_FEATURE_HDPARM_HDIO_GETSET_DMA
	unsigned long dma;
	smallint set_dma, get_dma;
#endif
#ifdef HDIO_DRIVE_CMD
	smallint set_xfermode, get_xfermode;
	smallint set_dkeep, get_dkeep;
	smallint set_standby, get_standby;
	smallint set_lookahead, get_lookahead;
	smallint set_prefetch, get_prefetch;
	smallint set_defects, get_defects;
	smallint set_wcache, get_wcache;
	smallint set_doorlock, get_doorlock;
	smallint set_seagate, get_seagate;
	smallint set_standbynow, get_standbynow;
	smallint set_sleepnow, get_sleepnow;
	smallint get_powermode;
	smallint set_apmmode, get_apmmode;
	int xfermode_requested;
	unsigned long dkeep;
	unsigned long standby_requested; /* 0..255 */
	unsigned long lookahead;
	unsigned long prefetch;
	unsigned long defects;
	unsigned long wcache;
	unsigned long doorlock;
	unsigned long apmmode;
#endif
	USE_FEATURE_HDPARM_GET_IDENTITY(        smallint get_IDentity;)
	USE_FEATURE_HDPARM_HDIO_TRISTATE_HWIF(  smallint set_busstate, get_busstate;)
	USE_FEATURE_HDPARM_HDIO_DRIVE_RESET(    smallint perform_reset;)
	USE_FEATURE_HDPARM_HDIO_TRISTATE_HWIF(  smallint perform_tristate;)
	USE_FEATURE_HDPARM_HDIO_UNREGISTER_HWIF(smallint unregister_hwif;)
	USE_FEATURE_HDPARM_HDIO_SCAN_HWIF(      smallint scan_hwif;)
	USE_FEATURE_HDPARM_HDIO_TRISTATE_HWIF(  unsigned long busstate;)
	USE_FEATURE_HDPARM_HDIO_TRISTATE_HWIF(  unsigned long tristate;)
	USE_FEATURE_HDPARM_HDIO_UNREGISTER_HWIF(unsigned long hwif;)
#if ENABLE_FEATURE_HDPARM_HDIO_SCAN_HWIF
	unsigned long hwif_data;
	unsigned long hwif_ctrl;
	unsigned long hwif_irq;
#endif
#ifdef DO_FLUSHCACHE
	unsigned char flushcache[4] = { WIN_FLUSHCACHE, 0, 0, 0 };
#endif
};
#define G (*(struct globals*)&bb_common_bufsiz1)
struct BUG_G_too_big {
	char BUG_G_too_big[sizeof(G) <= COMMON_BUFSIZE ? 1 : -1];
};
#define get_identity       (G.get_identity           )
#define get_geom           (G.get_geom               )
#define do_flush           (G.do_flush               )
#define do_ctimings        (G.do_ctimings            )
#define do_timings         (G.do_timings             )
#define reread_partn       (G.reread_partn           )
#define set_piomode        (G.set_piomode            )
#define noisy_piomode      (G.noisy_piomode          )
#define set_readahead      (G.set_readahead          )
#define get_readahead      (G.get_readahead          )
#define set_readonly       (G.set_readonly           )
#define get_readonly       (G.get_readonly           )
#define set_unmask         (G.set_unmask             )
#define get_unmask         (G.get_unmask             )
#define set_mult           (G.set_mult               )
#define get_mult           (G.get_mult               )
#define set_dma_q          (G.set_dma_q              )
#define get_dma_q          (G.get_dma_q              )
#define set_nowerr         (G.set_nowerr             )
#define get_nowerr         (G.get_nowerr             )
#define set_keep           (G.set_keep               )
#define get_keep           (G.get_keep               )
#define set_io32bit        (G.set_io32bit            )
#define get_io32bit        (G.get_io32bit            )
#define piomode            (G.piomode                )
#define Xreadahead         (G.Xreadahead             )
#define readonly           (G.readonly               )
#define unmask             (G.unmask                 )
#define mult               (G.mult                   )
#define dma_q              (G.dma_q                  )
#define nowerr             (G.nowerr                 )
#define keep               (G.keep                   )
#define io32bit            (G.io32bit                )
#define dma                (G.dma                    )
#define set_dma            (G.set_dma                )
#define get_dma            (G.get_dma                )
#define set_xfermode       (G.set_xfermode           )
#define get_xfermode       (G.get_xfermode           )
#define set_dkeep          (G.set_dkeep              )
#define get_dkeep          (G.get_dkeep              )
#define set_standby        (G.set_standby            )
#define get_standby        (G.get_standby            )
#define set_lookahead      (G.set_lookahead          )
#define get_lookahead      (G.get_lookahead          )
#define set_prefetch       (G.set_prefetch           )
#define get_prefetch       (G.get_prefetch           )
#define set_defects        (G.set_defects            )
#define get_defects        (G.get_defects            )
#define set_wcache         (G.set_wcache             )
#define get_wcache         (G.get_wcache             )
#define set_doorlock       (G.set_doorlock           )
#define get_doorlock       (G.get_doorlock           )
#define set_seagate        (G.set_seagate            )
#define get_seagate        (G.get_seagate            )
#define set_standbynow     (G.set_standbynow         )
#define get_standbynow     (G.get_standbynow         )
#define set_sleepnow       (G.set_sleepnow           )
#define get_sleepnow       (G.get_sleepnow           )
#define get_powermode      (G.get_powermode          )
#define set_apmmode        (G.set_apmmode            )
#define get_apmmode        (G.get_apmmode            )
#define xfermode_requested (G.xfermode_requested     )
#define dkeep              (G.dkeep                  )
#define standby_requested  (G.standby_requested      )
#define lookahead          (G.lookahead              )
#define prefetch           (G.prefetch               )
#define defects            (G.defects                )
#define wcache             (G.wcache                 )
#define doorlock           (G.doorlock               )
#define apmmode            (G.apmmode                )
#define get_IDentity       (G.get_IDentity           )
#define set_busstate       (G.set_busstate           )
#define get_busstate       (G.get_busstate           )
#define perform_reset      (G.perform_reset          )
#define perform_tristate   (G.perform_tristate       )
#define unregister_hwif    (G.unregister_hwif        )
#define scan_hwif          (G.scan_hwif              )
#define busstate           (G.busstate               )
#define tristate           (G.tristate               )
#define hwif               (G.hwif                   )
#define hwif_data          (G.hwif_data              )
#define hwif_ctrl          (G.hwif_ctrl              )
#define hwif_irq           (G.hwif_irq               )


/* Busybox messages and functions */
#if ENABLE_IOCTL_HEX2STR_ERROR
static int ioctl_alt_func(/*int fd,*/ int cmd, unsigned char *args, int alt, const char *string)
{
	if (!ioctl(fd, cmd, args))
		return 0;
	args[0] = alt;
	return bb_ioctl_or_warn(fd, cmd, args, string);
}
#define ioctl_alt_or_warn(cmd,args,alt) ioctl_alt_func(cmd,args,alt,#cmd)
#else
static int ioctl_alt_func(/*int fd,*/ int cmd, unsigned char *args, int alt)
{
	if (!ioctl(fd, cmd, args))
		return 0;
	args[0] = alt;
	return bb_ioctl_or_warn(fd, cmd, args);
}
#define ioctl_alt_or_warn(cmd,args,alt) ioctl_alt_func(cmd,args,alt)
#endif

static void on_off(int value)
{
	puts(value ? " (on)" : " (off)");
}

static void print_flag_on_off(int get_arg, const char *s, unsigned long arg)
{
	if (get_arg) {
		printf(" setting %s to %ld", s, arg);
		on_off(arg);
	}
}

static void print_value_on_off(const char *str, unsigned long argp)
{
	printf(" %s\t= %2ld", str, argp);
	on_off(argp != 0);
}

#if ENABLE_FEATURE_HDPARM_GET_IDENTITY
static void print_ascii(const char *p, int length)
{
#if BB_BIG_ENDIAN
#define LE_ONLY(x)
	enum { ofs = 0 };
#else
#define LE_ONLY(x) x
	/* every 16bit word is big-endian (i.e. inverted) */
	/* accessing bytes in 1,0, 3,2, 5,4... sequence */
	int ofs = 1;
#endif

	length *= 2;
	/* find first non-space & print it */
	while (length && p[ofs] != ' ') {
		p++;
		LE_ONLY(ofs = -ofs;)
		length--;
	}
	while (length && p[ofs]) {
		bb_putchar(p[ofs]);
		p++;
		LE_ONLY(ofs = -ofs;)
		length--;
	}
	bb_putchar('\n');
#undef LE_ONLY
}

static void xprint_ascii(uint16_t *val, int i, const char *string, int n)
{
	if (val[i]) {
		printf("\t%-20s", string);
		print_ascii((void*)&val[i], n);
	}
}

static uint8_t mode_loop(uint16_t mode_sup, uint16_t mode_sel, int cc, uint8_t *have_mode)
{
	uint16_t ii;
	uint8_t err_dma = 0;

	for (ii = 0; ii <= MODE_MAX; ii++) {
		if (mode_sel & 0x0001) {
			printf("*%cdma%u ", cc, ii);
			if (*have_mode)
				err_dma = 1;
			*have_mode = 1;
		} else if (mode_sup & 0x0001)
			printf("%cdma%u ", cc, ii);

		mode_sup >>= 1;
		mode_sel >>= 1;
	}
	return err_dma;
}

static const char pkt_str[] ALIGN1 =
	"Direct-access device" "\0"             /* word 0, bits 12-8 = 00 */
	"Sequential-access device" "\0"         /* word 0, bits 12-8 = 01 */
	"Printer" "\0"                          /* word 0, bits 12-8 = 02 */
	"Processor" "\0"                        /* word 0, bits 12-8 = 03 */
	"Write-once device" "\0"                /* word 0, bits 12-8 = 04 */
	"CD-ROM" "\0"                           /* word 0, bits 12-8 = 05 */
	"Scanner" "\0"                          /* word 0, bits 12-8 = 06 */
	"Optical memory" "\0"                   /* word 0, bits 12-8 = 07 */
	"Medium changer" "\0"                   /* word 0, bits 12-8 = 08 */
	"Communications device" "\0"            /* word 0, bits 12-8 = 09 */
	"ACS-IT8 device" "\0"                   /* word 0, bits 12-8 = 0a */
	"ACS-IT8 device" "\0"                   /* word 0, bits 12-8 = 0b */
	"Array controller" "\0"                 /* word 0, bits 12-8 = 0c */
	"Enclosure services" "\0"               /* word 0, bits 12-8 = 0d */
	"Reduced block command device" "\0"     /* word 0, bits 12-8 = 0e */
	"Optical card reader/writer" "\0"       /* word 0, bits 12-8 = 0f */
;

static const char ata1_cfg_str[] ALIGN1 =       /* word 0 in ATA-1 mode */
	"reserved" "\0"                         /* bit 0 */
	"hard sectored" "\0"                    /* bit 1 */
	"soft sectored" "\0"                    /* bit 2 */
	"not MFM encoded " "\0"                 /* bit 3 */
	"head switch time > 15us" "\0"          /* bit 4 */
	"spindle motor control option" "\0"     /* bit 5 */
	"fixed drive" "\0"                      /* bit 6 */
	"removable drive" "\0"                  /* bit 7 */
	"disk xfer rate <= 5Mbs" "\0"           /* bit 8 */
	"disk xfer rate > 5Mbs, <= 10Mbs" "\0"  /* bit 9 */
	"disk xfer rate > 5Mbs" "\0"            /* bit 10 */
	"rotational speed tol." "\0"            /* bit 11 */
	"data strobe offset option" "\0"        /* bit 12 */
	"track offset option" "\0"              /* bit 13 */
	"format speed tolerance gap reqd" "\0"  /* bit 14 */
	"ATAPI"                                 /* bit 14 */
;

static const char minor_str[] ALIGN1 =
	/* word 81 value: */
	"Unspecified" "\0"                                  /* 0x0000 */
	"ATA-1 X3T9.2 781D prior to rev.4" "\0"             /* 0x0001 */
	"ATA-1 published, ANSI X3.221-1994" "\0"            /* 0x0002 */
	"ATA-1 X3T9.2 781D rev.4" "\0"                      /* 0x0003 */
	"ATA-2 published, ANSI X3.279-1996" "\0"            /* 0x0004 */
	"ATA-2 X3T10 948D prior to rev.2k" "\0"             /* 0x0005 */
	"ATA-3 X3T10 2008D rev.1" "\0"                      /* 0x0006 */
	"ATA-2 X3T10 948D rev.2k" "\0"                      /* 0x0007 */
	"ATA-3 X3T10 2008D rev.0" "\0"                      /* 0x0008 */
	"ATA-2 X3T10 948D rev.3" "\0"                       /* 0x0009 */
	"ATA-3 published, ANSI X3.298-199x" "\0"            /* 0x000a */
	"ATA-3 X3T10 2008D rev.6" "\0"                      /* 0x000b */
	"ATA-3 X3T13 2008D rev.7 and 7a" "\0"               /* 0x000c */
	"ATA/ATAPI-4 X3T13 1153D rev.6" "\0"                /* 0x000d */
	"ATA/ATAPI-4 T13 1153D rev.13" "\0"                 /* 0x000e */
	"ATA/ATAPI-4 X3T13 1153D rev.7" "\0"                /* 0x000f */
	"ATA/ATAPI-4 T13 1153D rev.18" "\0"                 /* 0x0010 */
	"ATA/ATAPI-4 T13 1153D rev.15" "\0"                 /* 0x0011 */
	"ATA/ATAPI-4 published, ANSI INCITS 317-1998" "\0"  /* 0x0012 */
	"ATA/ATAPI-5 T13 1321D rev.3" "\0"                  /* 0x0013 */
	"ATA/ATAPI-4 T13 1153D rev.14" "\0"                 /* 0x0014 */
	"ATA/ATAPI-5 T13 1321D rev.1" "\0"                  /* 0x0015 */
	"ATA/ATAPI-5 published, ANSI INCITS 340-2000" "\0"  /* 0x0016 */
	"ATA/ATAPI-4 T13 1153D rev.17" "\0"                 /* 0x0017 */
	"ATA/ATAPI-6 T13 1410D rev.0" "\0"                  /* 0x0018 */
	"ATA/ATAPI-6 T13 1410D rev.3a" "\0"                 /* 0x0019 */
	"ATA/ATAPI-7 T13 1532D rev.1" "\0"                  /* 0x001a */
	"ATA/ATAPI-6 T13 1410D rev.2" "\0"                  /* 0x001b */
	"ATA/ATAPI-6 T13 1410D rev.1" "\0"                  /* 0x001c */
	"ATA/ATAPI-7 published, ANSI INCITS 397-2005" "\0"  /* 0x001d */
	"ATA/ATAPI-7 T13 1532D rev.0" "\0"                  /* 0x001e */
	"reserved" "\0"                                     /* 0x001f */
	"reserved" "\0"                                     /* 0x0020 */
	"ATA/ATAPI-7 T13 1532D rev.4a" "\0"                 /* 0x0021 */
	"ATA/ATAPI-6 published, ANSI INCITS 361-2002" "\0"  /* 0x0022 */
	"reserved"                                          /* 0x0023-0xfffe */
;
static const char actual_ver[MINOR_MAX + 2] ALIGN1 = {
	   /* word 81 value: */
	0, /* 0x0000 WARNING: actual_ver[] array */
	1, /* 0x0001 WARNING: corresponds        */
	1, /* 0x0002 WARNING: *exactly*          */
	1, /* 0x0003 WARNING: to the ATA/        */
	2, /* 0x0004 WARNING: ATAPI version      */
	2, /* 0x0005 WARNING: listed in          */
	3, /* 0x0006 WARNING: the                */
	2, /* 0x0007 WARNING: minor_str          */
	3, /* 0x0008 WARNING: array              */
	2, /* 0x0009 WARNING: above.             */
	3, /* 0x000a WARNING:                    */
	3, /* 0x000b WARNING: If you change      */
	3, /* 0x000c WARNING: that one,          */
	4, /* 0x000d WARNING: change this one    */
	4, /* 0x000e WARNING: too!!!             */
	4, /* 0x000f */
	4, /* 0x0010 */
	4, /* 0x0011 */
	4, /* 0x0012 */
	5, /* 0x0013 */
	4, /* 0x0014 */
	5, /* 0x0015 */
	5, /* 0x0016 */
	4, /* 0x0017 */
	6, /* 0x0018 */
	6, /* 0x0019 */
	7, /* 0x001a */
	6, /* 0x001b */
	6, /* 0x001c */
	7, /* 0x001d */
	7, /* 0x001e */
	0, /* 0x001f */
	0, /* 0x0020 */
	7, /* 0x0021 */
	6, /* 0x0022 */
	0  /* 0x0023-0xfffe */
};

static const char cmd_feat_str[] ALIGN1 =
	"" "\0"                                     /* word 82 bit 15: obsolete  */
	"NOP cmd" "\0"                              /* word 82 bit 14 */
	"READ BUFFER cmd" "\0"                      /* word 82 bit 13 */
	"WRITE BUFFER cmd" "\0"                     /* word 82 bit 12 */
	"" "\0"                                     /* word 82 bit 11: obsolete  */
	"Host Protected Area feature set" "\0"      /* word 82 bit 10 */
	"DEVICE RESET cmd" "\0"                     /* word 82 bit  9 */
	"SERVICE interrupt" "\0"                    /* word 82 bit  8 */
	"Release interrupt" "\0"                    /* word 82 bit  7 */
	"Look-ahead" "\0"                           /* word 82 bit  6 */
	"Write cache" "\0"                          /* word 82 bit  5 */
	"PACKET command feature set" "\0"           /* word 82 bit  4 */
	"Power Management feature set" "\0"         /* word 82 bit  3 */
	"Removable Media feature set" "\0"          /* word 82 bit  2 */
	"Security Mode feature set" "\0"            /* word 82 bit  1 */
	"SMART feature set" "\0"                    /* word 82 bit  0 */
	                                            /* -------------- */
	"" "\0"                                     /* word 83 bit 15: !valid bit */
	"" "\0"                                     /* word 83 bit 14:  valid bit */
	"FLUSH CACHE EXT cmd" "\0"                  /* word 83 bit 13 */
	"Mandatory FLUSH CACHE cmd " "\0"           /* word 83 bit 12 */
	"Device Configuration Overlay feature set " "\0"
	"48-bit Address feature set " "\0"          /* word 83 bit 10 */
	"" "\0"
	"SET MAX security extension" "\0"           /* word 83 bit  8 */
	"Address Offset Reserved Area Boot" "\0"    /* word 83 bit  7 */
	"SET FEATURES subcommand required to spinup after power up" "\0"
	"Power-Up In Standby feature set" "\0"      /* word 83 bit  5 */
	"Removable Media Status Notification feature set" "\0"
	"Adv. Power Management feature set" "\0"    /* word 83 bit  3 */
	"CFA feature set" "\0"                      /* word 83 bit  2 */
	"READ/WRITE DMA QUEUED" "\0"                /* word 83 bit  1 */
	"DOWNLOAD MICROCODE cmd" "\0"               /* word 83 bit  0 */
	                                            /* -------------- */
	"" "\0"                                     /* word 84 bit 15: !valid bit */
	"" "\0"                                     /* word 84 bit 14:  valid bit */
	"" "\0"                                     /* word 84 bit 13:  reserved */
	"" "\0"                                     /* word 84 bit 12:  reserved */
	"" "\0"                                     /* word 84 bit 11:  reserved */
	"" "\0"                                     /* word 84 bit 10:  reserved */
	"" "\0"                                     /* word 84 bit  9:  reserved */
	"" "\0"                                     /* word 84 bit  8:  reserved */
	"" "\0"                                     /* word 84 bit  7:  reserved */
	"" "\0"                                     /* word 84 bit  6:  reserved */
	"General Purpose Logging feature set" "\0"  /* word 84 bit  5 */
	"" "\0"                                     /* word 84 bit  4:  reserved */
	"Media Card Pass Through Command feature set " "\0"
	"Media serial number " "\0"                 /* word 84 bit  2 */
	"SMART self-test " "\0"                     /* word 84 bit  1 */
	"SMART error logging "                      /* word 84 bit  0 */
;

static const char secu_str[] ALIGN1 =
	"supported" "\0"                /* word 128, bit 0 */
	"enabled" "\0"                  /* word 128, bit 1 */
	"locked" "\0"                   /* word 128, bit 2 */
	"frozen" "\0"                   /* word 128, bit 3 */
	"expired: security count" "\0"  /* word 128, bit 4 */
	"supported: enhanced erase"     /* word 128, bit 5 */
;

// Parse 512 byte disk identification block and print much crap.
static void identify(uint16_t *val) ATTRIBUTE_NORETURN;
static void identify(uint16_t *val)
{
	uint16_t ii, jj, kk;
	uint16_t like_std = 1, std = 0, min_std = 0xffff;
	uint16_t dev = NO_DEV, eqpt = NO_DEV;
	uint8_t  have_mode = 0, err_dma = 0;
	uint8_t  chksum = 0;
	uint32_t ll, mm, nn, oo;
	uint64_t bbbig; /* (:) */
	const char *strng;
#if BB_BIG_ENDIAN
	uint16_t buf[256];

	// Adjust for endianness
	swab(val, buf, sizeof(buf));
	val = buf;
#endif
	/* check if we recognise the device type */
	bb_putchar('\n');
	if (!(val[GEN_CONFIG] & NOT_ATA)) {
		dev = ATA_DEV;
		printf("ATA device, with ");
	} else if (val[GEN_CONFIG]==CFA_SUPPORT_VAL) {
		dev = ATA_DEV;
		like_std = 4;
		printf("CompactFlash ATA device, with ");
	} else if (!(val[GEN_CONFIG] & NOT_ATAPI)) {
		dev = ATAPI_DEV;
		eqpt = (val[GEN_CONFIG] & EQPT_TYPE) >> SHIFT_EQPT;
		printf("ATAPI %s, with ", eqpt <= 0xf ? nth_string(pkt_str, eqpt) : "unknown");
		like_std = 3;
	} else
		/* "Unknown device type:\n\tbits 15&14 of general configuration word 0 both set to 1.\n" */
		bb_error_msg_and_die("unknown device type");

	printf("%sremovable media\n", !(val[GEN_CONFIG] & MEDIA_REMOVABLE) ? "non-" : "");
	/* Info from the specific configuration word says whether or not the
	 * ID command completed correctly.  It is only defined, however in
	 * ATA/ATAPI-5 & 6; it is reserved (value theoretically 0) in prior
	 * standards.  Since the values allowed for this word are extremely
	 * specific, it should be safe to check it now, even though we don't
	 * know yet what standard this device is using.
	 */
	if ((val[CONFIG]==STBY_NID_VAL) || (val[CONFIG]==STBY_ID_VAL)
	 || (val[CONFIG]==PWRD_NID_VAL) || (val[CONFIG]==PWRD_ID_VAL)
	) {
		like_std = 5;
		if ((val[CONFIG]==STBY_NID_VAL) || (val[CONFIG]==STBY_ID_VAL))
			printf("powers-up in standby; SET FEATURES subcmd spins-up.\n");
		if (((val[CONFIG]==STBY_NID_VAL) || (val[CONFIG]==PWRD_NID_VAL)) && (val[GEN_CONFIG] & INCOMPLETE))
			printf("\n\tWARNING: ID response incomplete.\n\tFollowing data may be incorrect.\n\n");
	}

	/* output the model and serial numbers and the fw revision */
	xprint_ascii(val, START_MODEL,  "Model Number:",        LENGTH_MODEL);
	xprint_ascii(val, START_SERIAL, "Serial Number:",       LENGTH_SERIAL);
	xprint_ascii(val, START_FW_REV, "Firmware Revision:",   LENGTH_FW_REV);
	xprint_ascii(val, START_MEDIA,  "Media Serial Num:",    LENGTH_MEDIA);
	xprint_ascii(val, START_MANUF,  "Media Manufacturer:",  LENGTH_MANUF);

	/* major & minor standards version number (Note: these words were not
	 * defined until ATA-3 & the CDROM std uses different words.) */
	printf("Standards:");
	if (eqpt != CDROM) {
		if (val[MINOR] && (val[MINOR] <= MINOR_MAX)) {
			if (like_std < 3) like_std = 3;
			std = actual_ver[val[MINOR]];
			if (std) printf("\n\tUsed: %s ", nth_string(minor_str, val[MINOR]));

		}
		/* looks like when they up-issue the std, they obsolete one;
		 * thus, only the newest 4 issues need be supported. (That's
		 * what "kk" and "min_std" are all about.) */
		if (val[MAJOR] && (val[MAJOR] != NOVAL_1)) {
			printf("\n\tSupported: ");
			jj = val[MAJOR] << 1;
			kk = like_std >4 ? like_std-4: 0;
			for (ii = 14; (ii >0)&&(ii>kk); ii--) {
				if (jj & 0x8000) {
					printf("%u ", ii);
					if (like_std < ii) {
						like_std = ii;
						kk = like_std >4 ? like_std-4: 0;
					}
					if (min_std > ii) min_std = ii;
				}
				jj <<= 1;
			}
			if (like_std < 3) like_std = 3;
		}
		/* Figure out what standard the device is using if it hasn't told
		 * us.  If we know the std, check if the device is using any of
		 * the words from the next level up.  It happens.
		 */
		if (like_std < std) like_std = std;

		if (((std == 5) || (!std && (like_std < 6))) &&
			((((val[CMDS_SUPP_1] & VALID) == VALID_VAL) &&
			((	val[CMDS_SUPP_1] & CMDS_W83) > 0x00ff)) ||
			(((	val[CMDS_SUPP_2] & VALID) == VALID_VAL) &&
			(	val[CMDS_SUPP_2] & CMDS_W84) ) )
		) {
			like_std = 6;
		} else if (((std == 4) || (!std && (like_std < 5))) &&
			((((val[INTEGRITY]	& SIG) == SIG_VAL) && !chksum) ||
			((	val[HWRST_RSLT] & VALID) == VALID_VAL) ||
			(((	val[CMDS_SUPP_1] & VALID) == VALID_VAL) &&
			((	val[CMDS_SUPP_1] & CMDS_W83) > 0x001f)) ) )
		{
			like_std = 5;
		} else if (((std == 3) || (!std && (like_std < 4))) &&
				((((val[CMDS_SUPP_1] & VALID) == VALID_VAL) &&
				(((	val[CMDS_SUPP_1] & CMDS_W83) > 0x0000) ||
				((	val[CMDS_SUPP_0] & CMDS_W82) > 0x000f))) ||
				((	val[CAPAB_1] & VALID) == VALID_VAL) ||
				((	val[WHATS_VALID] & OK_W88) && val[ULTRA_DMA]) ||
				((	val[RM_STAT] & RM_STAT_BITS) == RM_STAT_SUP) )
		) {
			like_std = 4;
		} else if (((std == 2) || (!std && (like_std < 3)))
		 && ((val[CMDS_SUPP_1] & VALID) == VALID_VAL)
		) {
			like_std = 3;
		} else if (((std == 1) || (!std && (like_std < 2))) &&
				((val[CAPAB_0] & (IORDY_SUP | IORDY_OFF)) ||
				(val[WHATS_VALID] & OK_W64_70)) )
		{
			like_std = 2;
		}

		if (!std)
			printf("\n\tLikely used: %u\n", like_std);
		else if (like_std > std)
			printf("& some of %u\n", like_std);
		else
			bb_putchar('\n');
	} else {
		/* TBD: do CDROM stuff more thoroughly.  For now... */
		kk = 0;
		if (val[CDR_MINOR] == 9) {
			kk = 1;
			printf("\n\tUsed: ATAPI for CD-ROMs, SFF-8020i, r2.5");
		}
		if (val[CDR_MAJOR] && (val[CDR_MAJOR] !=NOVAL_1)) {
			kk = 1;
			printf("\n\tSupported: CD-ROM ATAPI");
			jj = val[CDR_MAJOR] >> 1;
			for (ii = 1; ii < 15; ii++) {
				if (jj & 0x0001) printf("-%u ", ii);
				jj >>= 1;
			}
		}
		puts(kk ? "" : "\n\tLikely used CD-ROM ATAPI-1");
		/* the cdrom stuff is more like ATA-2 than anything else, so: */
		like_std = 2;
	}

	if (min_std == 0xffff)
		min_std = like_std > 4 ? like_std - 3 : 1;

	printf("Configuration:\n");
	/* more info from the general configuration word */
	if ((eqpt != CDROM) && (like_std == 1)) {
		jj = val[GEN_CONFIG] >> 1;
		for (ii = 1; ii < 15; ii++) {
			if (jj & 0x0001)
				printf("\t%s\n", nth_string(ata1_cfg_str, ii));
			jj >>=1;
		}
	}
	if (dev == ATAPI_DEV) {
		if ((val[GEN_CONFIG] & DRQ_RESPONSE_TIME) ==  DRQ_3MS_VAL)
			strng = "3ms";
		else if ((val[GEN_CONFIG] & DRQ_RESPONSE_TIME) ==  DRQ_INTR_VAL)
			strng = "<=10ms with INTRQ";
		else if ((val[GEN_CONFIG] & DRQ_RESPONSE_TIME) ==  DRQ_50US_VAL)
			strng ="50us";
		else
			strng = "unknown";
		printf("\tDRQ response: %s\n\tPacket size: ", strng); /* Data Request (DRQ) */

		if ((val[GEN_CONFIG] & PKT_SIZE_SUPPORTED) == PKT_SIZE_12_VAL)
			strng = "12 bytes";
		else if ((val[GEN_CONFIG] & PKT_SIZE_SUPPORTED) == PKT_SIZE_16_VAL)
			strng = "16 bytes";
		else
			strng = "unknown";
		puts(strng);
	} else {
		/* addressing...CHS? See section 6.2 of ATA specs 4 or 5 */
		ll = (uint32_t)val[LBA_SECTS_MSB] << 16 | val[LBA_SECTS_LSB];
		mm = 0; bbbig = 0;
		if ((ll > 0x00FBFC10) && (!val[LCYLS]))
			printf("\tCHS addressing not supported\n");
		else {
			jj = val[WHATS_VALID] & OK_W54_58;
			printf("\tLogical\t\tmax\tcurrent\n\tcylinders\t%u\t%u\n\theads\t\t%u\t%u\n\tsectors/track\t%u\t%u\n\t--\n",
					val[LCYLS],jj?val[LCYLS_CUR]:0, val[LHEADS],jj?val[LHEADS_CUR]:0, val[LSECTS],jj?val[LSECTS_CUR]:0);

			if ((min_std == 1) && (val[TRACK_BYTES] || val[SECT_BYTES]))
				printf("\tbytes/track: %u\tbytes/sector: %u\n", val[TRACK_BYTES], val[SECT_BYTES]);

			if (jj) {
				mm = (uint32_t)val[CAPACITY_MSB] << 16 | val[CAPACITY_LSB];
				if (like_std < 3) {
					/* check Endian of capacity bytes */
					nn = val[LCYLS_CUR] * val[LHEADS_CUR] * val[LSECTS_CUR];
					oo = (uint32_t)val[CAPACITY_LSB] << 16 | val[CAPACITY_MSB];
					if (abs(mm - nn) > abs(oo - nn))
						mm = oo;
				}
				printf("\tCHS current addressable sectors:%11u\n", mm);
			}
		}
		/* LBA addressing */
		printf("\tLBA    user addressable sectors:%11u\n", ll);
		if (((val[CMDS_SUPP_1] & VALID) == VALID_VAL)
		 && (val[CMDS_SUPP_1] & SUPPORT_48_BIT)
		) {
			bbbig = (uint64_t)val[LBA_64_MSB] << 48 |
			        (uint64_t)val[LBA_48_MSB] << 32 |
			        (uint64_t)val[LBA_MID] << 16 |
					val[LBA_LSB];
			printf("\tLBA48  user addressable sectors:%11"PRIu64"\n", bbbig);
		}

		if (!bbbig)
			bbbig = (uint64_t)(ll>mm ? ll : mm); /* # 512 byte blocks */
		printf("\tdevice size with M = 1024*1024: %11"PRIu64" MBytes\n", bbbig>>11);
		bbbig = (bbbig << 9) / 1000000;
		printf("\tdevice size with M = 1000*1000: %11"PRIu64" MBytes ", bbbig);

		if (bbbig > 1000)
			printf("(%"PRIu64" GB)\n", bbbig/1000);
		else
			bb_putchar('\n');
	}

	/* hw support of commands (capabilities) */
	printf("Capabilities:\n\t");

	if (dev == ATAPI_DEV) {
		if (eqpt != CDROM && (val[CAPAB_0] & CMD_Q_SUP)) printf("Cmd queuing, ");
		if (val[CAPAB_0] & OVLP_SUP) printf("Cmd overlap, ");
	}
	if (val[CAPAB_0] & LBA_SUP) printf("LBA, ");

	if (like_std != 1) {
		printf("IORDY%s(can%s be disabled)\n",
				!(val[CAPAB_0] & IORDY_SUP) ? "(may be)" : "",
				(val[CAPAB_0] & IORDY_OFF) ? "" :"not");
	} else
		printf("no IORDY\n");

	if ((like_std == 1) && val[BUF_TYPE]) {
		printf("\tBuffer type: %04x: %s%s\n", val[BUF_TYPE],
				(val[BUF_TYPE] < 2) ? "single port, single-sector" : "dual port, multi-sector",
				(val[BUF_TYPE] > 2) ? " with read caching ability" : "");
	}

	if ((min_std == 1) && (val[BUFFER__SIZE] && (val[BUFFER__SIZE] != NOVAL_1))) {
		printf("\tBuffer size: %.1fkB\n", (float)val[BUFFER__SIZE]/2);
	}
	if ((min_std < 4) && (val[RW_LONG])) {
		printf("\tbytes avail on r/w long: %u\n", val[RW_LONG]);
	}
	if ((eqpt != CDROM) && (like_std > 3)) {
		printf("\tQueue depth: %u\n", (val[QUEUE_DEPTH] & DEPTH_BITS) + 1);
	}

	if (dev == ATA_DEV) {
		if (like_std == 1)
			printf("\tCan%s perform double-word IO\n", (!val[DWORD_IO]) ? "not" : "");
		else {
			printf("\tStandby timer values: spec'd by %s", (val[CAPAB_0] & STD_STBY) ? "Standard" : "Vendor");
			if ((like_std > 3) && ((val[CAPAB_1] & VALID) == VALID_VAL))
				printf(", %s device specific minimum\n", (val[CAPAB_1] & MIN_STANDBY_TIMER) ? "with" : "no");
			else
				bb_putchar('\n');
		}
		printf("\tR/W multiple sector transfer: ");
		if ((like_std < 3) && !(val[SECTOR_XFER_MAX] & SECTOR_XFER))
			printf("not supported\n");
		else {
			printf("Max = %u\tCurrent = ", val[SECTOR_XFER_MAX] & SECTOR_XFER);
			if (val[SECTOR_XFER_CUR] & MULTIPLE_SETTING_VALID)
				printf("%u\n", val[SECTOR_XFER_CUR] & SECTOR_XFER);
			else
				printf("?\n");
		}
		if ((like_std > 3) && (val[CMDS_SUPP_1] & 0x0008)) {
			/* We print out elsewhere whether the APM feature is enabled or
			   not.  If it's not enabled, let's not repeat the info; just print
			   nothing here. */
			printf("\tAdvancedPM level: ");
			if ((val[ADV_PWR] & 0xFF00) == 0x4000) {
				uint8_t apm_level = val[ADV_PWR] & 0x00FF;
				printf("%u (0x%x)\n", apm_level, apm_level);
			}
			else
				printf("unknown setting (0x%04x)\n", val[ADV_PWR]);
		}
		if (like_std > 5 && val[ACOUSTIC]) {
			printf("\tRecommended acoustic management value: %u, current value: %u\n",
					(val[ACOUSTIC] >> 8) & 0x00ff, val[ACOUSTIC] & 0x00ff);
		}
	} else {
		 /* ATAPI */
		if (eqpt != CDROM && (val[CAPAB_0] & SWRST_REQ))
			printf("\tATA sw reset required\n");

		if (val[PKT_REL] || val[SVC_NBSY]) {
			printf("\tOverlap support:");
			if (val[PKT_REL]) printf(" %uus to release bus.", val[PKT_REL]);
			if (val[SVC_NBSY]) printf(" %uus to clear BSY after SERVICE cmd.", val[SVC_NBSY]);
			bb_putchar('\n');
		}
	}

	/* DMA stuff. Check that only one DMA mode is selected. */
	printf("\tDMA: ");
	if (!(val[CAPAB_0] & DMA_SUP))
		printf("not supported\n");
	else {
		if (val[DMA_MODE] && !val[SINGLE_DMA] && !val[MULTI_DMA])
			printf(" sdma%u\n", (val[DMA_MODE] & MODE) >> 8);
		if (val[SINGLE_DMA]) {
			jj = val[SINGLE_DMA];
			kk = val[SINGLE_DMA] >> 8;
			err_dma += mode_loop(jj, kk, 's', &have_mode);
		}
		if (val[MULTI_DMA]) {
			jj = val[MULTI_DMA];
			kk = val[MULTI_DMA] >> 8;
			err_dma += mode_loop(jj, kk, 'm', &have_mode);
		}
		if ((val[WHATS_VALID] & OK_W88) && val[ULTRA_DMA]) {
			jj = val[ULTRA_DMA];
			kk = val[ULTRA_DMA] >> 8;
			err_dma += mode_loop(jj, kk, 'u', &have_mode);
		}
		if (err_dma || !have_mode) printf("(?)");
		bb_putchar('\n');

		if ((dev == ATAPI_DEV) && (eqpt != CDROM) && (val[CAPAB_0] & DMA_IL_SUP))
			printf("\t\tInterleaved DMA support\n");

		if ((val[WHATS_VALID] & OK_W64_70)
		 && (val[DMA_TIME_MIN] || val[DMA_TIME_NORM])
		) {
			printf("\t\tCycle time:");
			if (val[DMA_TIME_MIN]) printf(" min=%uns", val[DMA_TIME_MIN]);
			if (val[DMA_TIME_NORM]) printf(" recommended=%uns", val[DMA_TIME_NORM]);
			bb_putchar('\n');
		}
	}

	/* Programmed IO stuff */
	printf("\tPIO: ");
	/* If a drive supports mode n (e.g. 3), it also supports all modes less
	 * than n (e.g. 3, 2, 1 and 0).  Print all the modes. */
	if ((val[WHATS_VALID] & OK_W64_70) && (val[ADV_PIO_MODES] & PIO_SUP)) {
		jj = ((val[ADV_PIO_MODES] & PIO_SUP) << 3) | 0x0007;
		for (ii = 0; ii <= PIO_MODE_MAX; ii++) {
			if (jj & 0x0001) printf("pio%d ", ii);
			jj >>=1;
		}
		bb_putchar('\n');
	} else if (((min_std < 5) || (eqpt == CDROM)) && (val[PIO_MODE] & MODE)) {
		for (ii = 0; ii <= val[PIO_MODE]>>8; ii++)
			printf("pio%d ", ii);
		bb_putchar('\n');
	} else
		puts("unknown");

	if (val[WHATS_VALID] & OK_W64_70) {
		if (val[PIO_NO_FLOW] || val[PIO_FLOW]) {
			printf("\t\tCycle time:");
			if (val[PIO_NO_FLOW]) printf(" no flow control=%uns", val[PIO_NO_FLOW]);
			if (val[PIO_FLOW]) printf("  IORDY flow control=%uns", val[PIO_FLOW]);
			bb_putchar('\n');
		}
	}

	if ((val[CMDS_SUPP_1] & VALID) == VALID_VAL) {
		printf("Commands/features:\n\tEnabled\tSupported:\n");
		jj = val[CMDS_SUPP_0];
		kk = val[CMDS_EN_0];
		for (ii = 0; ii < NUM_CMD_FEAT_STR; ii++) {
			const char *feat_str = nth_string(cmd_feat_str, ii);
			if ((jj & 0x8000) && (*feat_str != '\0')) {
				printf("\t%s\t%s\n", (kk & 0x8000) ? "   *" : "", feat_str);
			}
			jj <<= 1;
			kk <<= 1;
			if (ii % 16 == 15) {
				jj = val[CMDS_SUPP_0+1+(ii/16)];
				kk = val[CMDS_EN_0+1+(ii/16)];
			}
			if (ii == 31) {
				if ((val[CMDS_SUPP_2] & VALID) != VALID_VAL)
					ii +=16;
			}
		}
	}
	/* Removable Media Status Notification feature set */
	if ((val[RM_STAT] & RM_STAT_BITS) == RM_STAT_SUP)
		printf("\t%s supported\n", nth_string(cmd_feat_str, 27));

	/* security */
	if ((eqpt != CDROM) && (like_std > 3)
	 && (val[SECU_STATUS] || val[ERASE_TIME] || val[ENH_ERASE_TIME])
	) {
		printf("Security:\n");
		if (val[PSWD_CODE] && (val[PSWD_CODE] != NOVAL_1))
			printf("\tMaster password revision code = %u\n", val[PSWD_CODE]);
		jj = val[SECU_STATUS];
		if (jj) {
			for (ii = 0; ii < NUM_SECU_STR; ii++) {
				printf("\t%s\t%s\n", (!(jj & 0x0001)) ? "not" : "", nth_string(secu_str, ii));
				jj >>=1;
			}
			if (val[SECU_STATUS] & SECU_ENABLED) {
				printf("\tSecurity level %s\n", (val[SECU_STATUS] & SECU_LEVEL) ? "maximum" : "high");
			}
		}
		jj =  val[ERASE_TIME]     & ERASE_BITS;
		kk =  val[ENH_ERASE_TIME] & ERASE_BITS;
		if (jj || kk) {
			bb_putchar('\t');
			if (jj) printf("%umin for %sSECURITY ERASE UNIT. ", jj==ERASE_BITS ? 508 : jj<<1, "");
			if (kk) printf("%umin for %sSECURITY ERASE UNIT. ", kk==ERASE_BITS ? 508 : kk<<1, "ENHANCED ");
			bb_putchar('\n');
		}
	}

	/* reset result */
	jj = val[HWRST_RSLT];
	if ((jj & VALID) == VALID_VAL) {
		oo = (jj & RST0);
		if (!oo)
			jj >>= 8;
		if ((jj & DEV_DET) == JUMPER_VAL)
			strng = " determined by the jumper";
		else if ((jj & DEV_DET) == CSEL_VAL)
			strng = " determined by CSEL";
		else
			strng = "";
		printf("HW reset results:\n\tCBLID- %s Vih\n\tDevice num = %i%s\n",
				(val[HWRST_RSLT] & CBLID) ? "above" : "below", !(oo), strng);
	}

	/* more stuff from std 5 */
	if ((like_std > 4) && (eqpt != CDROM)) {
		if (val[CFA_PWR_MODE] & VALID_W160) {
			printf("CFA power mode 1:\n\t%s%s\n", (val[CFA_PWR_MODE] & PWR_MODE_OFF) ? "disabled" : "enabled",
					(val[CFA_PWR_MODE] & PWR_MODE_REQ) ? " and required by some commands" : "");

			if (val[CFA_PWR_MODE] & MAX_AMPS)
				printf("\tMaximum current = %uma\n", val[CFA_PWR_MODE] & MAX_AMPS);
		}
		if ((val[INTEGRITY] & SIG) == SIG_VAL) {
			printf("Checksum: %scorrect\n", chksum ? "in" : "");
		}
	}

	exit(EXIT_SUCCESS);
}
#endif

// Historically, if there was no HDIO_OBSOLETE_IDENTITY, then
// then the HDIO_GET_IDENTITY only returned 142 bytes.
// Otherwise, HDIO_OBSOLETE_IDENTITY returns 142 bytes,
// and HDIO_GET_IDENTITY returns 512 bytes.  But the latest
// 2.5.xx kernels no longer define HDIO_OBSOLETE_IDENTITY
// (which they should, but they should just return -EINVAL).
//
// So.. we must now assume that HDIO_GET_IDENTITY returns 512 bytes.
// On a really old system, it will not, and we will be confused.
// Too bad, really.

#if ENABLE_FEATURE_HDPARM_GET_IDENTITY
static const char cfg_str[] ALIGN1 =
	"""\0"            "HardSect""\0"   "SoftSect""\0"  "NotMFM""\0"
	"HdSw>15uSec""\0" "SpinMotCtl""\0" "Fixed""\0"     "Removeable""\0"
	"DTR<=5Mbs""\0"   "DTR>5Mbs""\0"   "DTR>10Mbs""\0" "RotSpdTol>.5%""\0"
	"dStbOff""\0"     "TrkOff""\0"     "FmtGapReq""\0" "nonMagnetic"
;

static const char BuffType[] ALIGN1 =
	"unknown""\0"     "1Sect""\0"      "DualPort""\0"  "DualPortCache"
;

static void dump_identity(const struct hd_driveid *id)
{
	int i;
	const unsigned short *id_regs = (const void*) id;

	printf("\n Model=%.40s, FwRev=%.8s, SerialNo=%.20s\n Config={",
				id->model, id->fw_rev, id->serial_no);
	for (i = 0; i <= 15; i++) {
		if (id->config & (1<<i))
			printf(" %s", nth_string(cfg_str, i));
	}
	printf(" }\n RawCHS=%u/%u/%u, TrkSize=%u, SectSize=%u, ECCbytes=%u\n"
			" BuffType=(%u) %s, BuffSize=%ukB, MaxMultSect=%u",
				id->cyls, id->heads, id->sectors, id->track_bytes,
				id->sector_bytes, id->ecc_bytes,
				id->buf_type, nth_string(BuffType, (id->buf_type > 3) ? 0 : id->buf_type),
				id->buf_size/2, id->max_multsect);
	if (id->max_multsect) {
		printf(", MultSect=");
		if (!(id->multsect_valid & 1))
			printf("?%u?", id->multsect);
		else if (id->multsect)
			printf("%u", id->multsect);
		else
			printf("off");
	}
	bb_putchar('\n');

	if (!(id->field_valid & 1))
		printf(" (maybe):");

	printf(" CurCHS=%u/%u/%u, CurSects=%lu, LBA=%s", id->cur_cyls, id->cur_heads,
		id->cur_sectors,
		(BB_BIG_ENDIAN) ?
			(unsigned long)(id->cur_capacity0 << 16) | id->cur_capacity1 :
			(unsigned long)(id->cur_capacity1 << 16) | id->cur_capacity0,
			((id->capability&2) == 0) ? "no" : "yes");

	if (id->capability & 2)
		printf(", LBAsects=%u", id->lba_capacity);

	printf("\n IORDY=%s", (id->capability & 8) ? (id->capability & 4) ?  "on/off" : "yes" : "no");

	if (((id->capability & 8) || (id->field_valid & 2)) && (id->field_valid & 2))
		printf(", tPIO={min:%u,w/IORDY:%u}", id->eide_pio, id->eide_pio_iordy);

	if ((id->capability & 1) && (id->field_valid & 2))
		printf(", tDMA={min:%u,rec:%u}", id->eide_dma_min, id->eide_dma_time);

	printf("\n PIO modes:  ");
	if (id->tPIO <= 5) {
		printf("pio0 ");
		if (id->tPIO >= 1) printf("pio1 ");
		if (id->tPIO >= 2) printf("pio2 ");
	}
	if (id->field_valid & 2) {
		static const masks_labels_t pio_modes = {
			.masks = { 1, 2, ~3 },
			.labels = "pio3 \0""pio4 \0""pio? \0",
		};
		print_flags(&pio_modes, id->eide_pio_modes);
	}
	if (id->capability & 1) {
		if (id->dma_1word | id->dma_mword) {
			static const int dma_wmode_masks[] = { 0x100, 1, 0x200, 2, 0x400, 4, 0xf800, 0xf8 };
			printf("\n DMA modes:  ");
			print_flags_separated(dma_wmode_masks,
				"*\0""sdma0 \0""*\0""sdma1 \0""*\0""sdma2 \0""*\0""sdma? \0",
				id->dma_1word, NULL);
			print_flags_separated(dma_wmode_masks,
				"*\0""mdma0\0""*\0""mdma1\0""*\0""mdma2\0""*\0""mdma?\0",
				id->dma_mword, NULL);
		}
	}
	if (((id->capability & 8) || (id->field_valid & 2)) && id->field_valid & 4) {
		static const masks_labels_t ultra_modes1 = {
			.masks = { 0x100, 0x001, 0x200, 0x002, 0x400, 0x004 },
			.labels = "*\0""udma0 \0""*\0""udma1 \0""*\0""udma2 \0",
		};

		printf("\n UDMA modes: ");
		print_flags(&ultra_modes1, id->dma_ultra);
#ifdef __NEW_HD_DRIVE_ID
		if (id->hw_config & 0x2000) {
#else /* !__NEW_HD_DRIVE_ID */
		if (id->word93 & 0x2000) {
#endif /* __NEW_HD_DRIVE_ID */
			static const masks_labels_t ultra_modes2 = {
				.masks = { 0x0800, 0x0008, 0x1000, 0x0010,
					0x2000, 0x0020, 0x4000, 0x0040,
					0x8000, 0x0080 },
				.labels = "*\0""udma3 \0""*\0""udma4 \0"
					"*\0""udma5 \0""*\0""udma6 \0"
					"*\0""udma7 \0"
			};
			print_flags(&ultra_modes2, id->dma_ultra);
		}
	}
	printf("\n AdvancedPM=%s", (!(id_regs[83] & 8)) ? "no" : "yes");
	if (id_regs[83] & 8) {
		if (!(id_regs[86] & 8))
			printf(": disabled (255)");
		else if ((id_regs[91] & 0xFF00) != 0x4000)
			printf(": unknown setting");
		else
			printf(": mode=0x%02X (%u)", id_regs[91] & 0xFF, id_regs[91] & 0xFF);
	}
	if (id_regs[82] & 0x20)
		printf(" WriteCache=%s", (id_regs[85] & 0x20) ? "enabled" : "disabled");
#ifdef __NEW_HD_DRIVE_ID
	if ((id->minor_rev_num && id->minor_rev_num <= 31)
	 || (id->major_rev_num && id->minor_rev_num <= 31)
	) {
		printf("\n Drive conforms to: %s: ", (id->minor_rev_num <= 31) ? nth_string(minor_str, id->minor_rev_num) : "unknown");
		if (id->major_rev_num != 0x0000 &&  /* NOVAL_0 */
		    id->major_rev_num != 0xFFFF) {  /* NOVAL_1 */
			for (i = 0; i <= 15; i++) {
				if (id->major_rev_num & (1<<i))
						printf(" ATA/ATAPI-%u", i);
			}
		}
	}
#endif /* __NEW_HD_DRIVE_ID */
	printf("\n\n * current active mode\n\n");
}
#endif

static void flush_buffer_cache(/*int fd*/ void)
{
	fsync(fd);				/* flush buffers */
	ioctl_or_warn(fd, BLKFLSBUF, NULL); /* do it again, big time */
#ifdef HDIO_DRIVE_CMD
	sleep(1);
	if (ioctl(fd, HDIO_DRIVE_CMD, NULL) && errno != EINVAL) {	/* await completion */
		if (ENABLE_IOCTL_HEX2STR_ERROR) /* To be coherent with ioctl_or_warn */
			bb_perror_msg("HDIO_DRIVE_CMD");
		else
			bb_perror_msg("ioctl %#x failed", HDIO_DRIVE_CMD);
	}
#endif
}

static void seek_to_zero(/*int fd*/ void)
{
	xlseek(fd, (off_t) 0, SEEK_SET);
}

static void read_big_block(/*int fd,*/ char *buf)
{
	int i;

	xread(fd, buf, TIMING_BUF_BYTES);
	/* access all sectors of buf to ensure the read fully completed */
	for (i = 0; i < TIMING_BUF_BYTES; i += 512)
		buf[i] &= 1;
}

static unsigned dev_size_mb(/*int fd*/ void)
{
	union {
		unsigned long long blksize64;
		unsigned blksize32;
	} u;

	if (0 == ioctl(fd, BLKGETSIZE64, &u.blksize64)) { // bytes
		u.blksize64 /= (1024 * 1024);
	} else {
		xioctl(fd, BLKGETSIZE, &u.blksize32); // sectors
		u.blksize64 = u.blksize32 / (2 * 1024);
	}
	if (u.blksize64 > UINT_MAX)
		return UINT_MAX;
	return u.blksize64;
}

static void print_timing(unsigned m, unsigned elapsed_us)
{
	unsigned sec = elapsed_us / 1000000;
	unsigned hs = (elapsed_us % 1000000) / 10000;

	printf("%5u MB in %u.%02u seconds = %u kB/s\n",
		m, sec, hs,
		/* "| 1" prevents div-by-0 */
		(unsigned) ((unsigned long long)m * (1024 * 1000000) / (elapsed_us | 1))
		// ~= (m * 1024) / (elapsed_us / 1000000)
		// = kb / elapsed_sec
	);
}

static void do_time(int cache /*,int fd*/)
/* cache=1: time cache: repeatedly read N MB at offset 0
 * cache=0: time device: linear read, starting at offset 0
 */
{
	unsigned max_iterations, iterations;
	unsigned start; /* doesn't need to be long long */
	unsigned elapsed, elapsed2;
	unsigned total_MB;
	char *buf = xmalloc(TIMING_BUF_BYTES);

	if (mlock(buf, TIMING_BUF_BYTES))
		bb_perror_msg_and_die("mlock");

	/* Clear out the device request queues & give them time to complete.
	 * NB: *small* delay. User is expected to have a clue and to not run
	 * heavy io in parallel with measurements. */
	sync();
	sleep(1);
	if (cache) { /* Time cache */
		seek_to_zero();
		read_big_block(buf);
		printf("Timing buffer-cache reads: ");
	} else { /* Time device */
		printf("Timing buffered disk reads:");
	}
	fflush(stdout);

	/* Now do the timing */
	iterations = 0;
	/* Max time to run (small for cache, avoids getting
	 * huge total_MB which can overlow unsigned type) */
	elapsed2 = 510000; /* cache */
	max_iterations = UINT_MAX;
	if (!cache) {
		elapsed2 = 3000000; /* not cache */
		/* Don't want to read past the end! */
		max_iterations = dev_size_mb() / TIMING_BUF_MB;
	}
	start = monotonic_us();
	do {
		if (cache)
			seek_to_zero();
		read_big_block(buf);
		elapsed = (unsigned)monotonic_us() - start;
		++iterations;
	} while (elapsed < elapsed2 && iterations < max_iterations);
	total_MB = iterations * TIMING_BUF_MB;
	//printf(" elapsed:%u iterations:%u ", elapsed, iterations);
	if (cache) {
		/* Cache: remove lseek() and monotonic_us() overheads
		 * from elapsed */
		start = monotonic_us();
		do {
			seek_to_zero();
			elapsed2 = (unsigned)monotonic_us() - start;
		} while (--iterations);
		//printf(" elapsed2:%u ", elapsed2);
		elapsed -= elapsed2;
		total_MB *= 2; // BUFCACHE_FACTOR (why?)
		flush_buffer_cache();
	}
	print_timing(total_MB, elapsed);
	munlock(buf, TIMING_BUF_BYTES);
	free(buf);
}

#if ENABLE_FEATURE_HDPARM_HDIO_TRISTATE_HWIF
static void bus_state_value(unsigned value)
{
	if (value == BUSSTATE_ON)
		on_off(1);
	else if (value == BUSSTATE_OFF)
		on_off(0);
	else if (value == BUSSTATE_TRISTATE)
		printf(" (tristate)\n");
	else
		printf(" (unknown: %d)\n", value);
}
#endif

#ifdef HDIO_DRIVE_CMD
static void interpret_standby(uint8_t standby)
{
	printf(" (");
	if (standby == 0) {
		printf("off");
	} else if (standby <= 240 || standby == 252 || standby == 255) {
		/* standby is in 5 sec units */
		printf("%u minutes %u seconds", standby / 12, (standby*5) % 60);
	} else if (standby <= 251) {
		unsigned t = (standby - 240); /* t is in 30 min units */;
		printf("%u.%c hours", t / 2, (t & 1) ? '0' : '5');
	}
	if (standby == 253)
		printf("vendor-specific");
	if (standby == 254)
		printf("reserved");
	printf(")\n");
}

static const uint8_t xfermode_val[] ALIGN1 = {
	 8,      9,     10,     11,     12,     13,     14,     15,
	16,     17,     18,     19,     20,     21,     22,     23,
	32,     33,     34,     35,     36,     37,     38,     39,
	64,     65,     66,     67,     68,     69,     70,     71
};
/* NB: we save size by _not_ storing terninating NUL! */
static const char xfermode_name[][5] ALIGN1 = {
	"pio0", "pio1", "pio2", "pio3", "pio4", "pio5", "pio6", "pio7",
	"sdma0","sdma1","sdma2","sdma3","sdma4","sdma5","sdma6","sdma7",
	"mdma0","mdma1","mdma2","mdma3","mdma4","mdma5","mdma6","mdma7",
	"udma0","udma1","udma2","udma3","udma4","udma5","udma6","udma7"
};

static int translate_xfermode(const char *name)
{
	int val;
	unsigned i;

	for (i = 0; i < ARRAY_SIZE(xfermode_val); i++) {
		if (!strncmp(name, xfermode_name[i], 5))
			if (strlen(name) <= 5)
				return xfermode_val[i];
	}
	/* Negative numbers are invalid and are caught later */
	val = bb_strtoi(name, NULL, 10);
	if (!errno)
		return val;
	return -1;
}

static void interpret_xfermode(unsigned xfermode)
{
	printf(" (");
	if (xfermode == 0)
		printf("default PIO mode");
	else if (xfermode == 1)
		printf("default PIO mode, disable IORDY");
	else if (xfermode >= 8 && xfermode <= 15)
		printf("PIO flow control mode%u", xfermode - 8);
	else if (xfermode >= 16 && xfermode <= 23)
		printf("singleword DMA mode%u", xfermode - 16);
	else if (xfermode >= 32 && xfermode <= 39)
		printf("multiword DMA mode%u", xfermode - 32);
	else if (xfermode >= 64 && xfermode <= 71)
		printf("UltraDMA mode%u", xfermode - 64);
	else
		printf("unknown");
	printf(")\n");
}
#endif /* HDIO_DRIVE_CMD */

static void print_flag(int flag, const char *s, unsigned long value)
{
	if (flag)
		printf(" setting %s to %ld\n", s, value);
}

static void process_dev(char *devname)
{
	/*int fd;*/
	long parm, multcount;
#ifndef HDIO_DRIVE_CMD
	int force_operation = 0;
#endif
	/* Please restore args[n] to these values after each ioctl
	   except for args[2] */
	unsigned char args[4] = { WIN_SETFEATURES, 0, 0, 0 };
	const char *fmt = " %s\t= %2ld";

	/*fd = xopen(devname, O_RDONLY | O_NONBLOCK);*/
	xmove_fd(xopen(devname, O_RDONLY | O_NONBLOCK), fd);
	printf("\n%s:\n", devname);

	if (set_readahead) {
		print_flag(get_readahead, "fs readahead", Xreadahead);
		ioctl_or_warn(fd, BLKRASET, (int *)Xreadahead);
	}
#if ENABLE_FEATURE_HDPARM_HDIO_UNREGISTER_HWIF
	if (unregister_hwif) {
		printf(" attempting to unregister hwif#%lu\n", hwif);
		ioctl_or_warn(fd, HDIO_UNREGISTER_HWIF, (int *)(unsigned long)hwif);
	}
#endif
#if ENABLE_FEATURE_HDPARM_HDIO_SCAN_HWIF
	if (scan_hwif) {
		printf(" attempting to scan hwif (0x%lx, 0x%lx, %lu)\n", hwif_data, hwif_ctrl, hwif_irq);
		args[0] = hwif_data;
		args[1] = hwif_ctrl;
		args[2] = hwif_irq;
		ioctl_or_warn(fd, HDIO_SCAN_HWIF, args);
		args[0] = WIN_SETFEATURES;
		args[1] = 0;
	}
#endif
	if (set_piomode) {
		if (noisy_piomode) {
			printf(" attempting to ");
			if (piomode == 255)
				printf("auto-tune PIO mode\n");
			else if (piomode < 100)
				printf("set PIO mode to %d\n", piomode);
			else if (piomode < 200)
				printf("set MDMA mode to %d\n", (piomode-100));
			else
				printf("set UDMA mode to %d\n", (piomode-200));
		}
		ioctl_or_warn(fd, HDIO_SET_PIO_MODE, (int *)(unsigned long)piomode);
	}
	if (set_io32bit) {
		print_flag(get_io32bit, "32-bit IO_support flag", io32bit);
		ioctl_or_warn(fd, HDIO_SET_32BIT, (int *)io32bit);
	}
	if (set_mult) {
		print_flag(get_mult, "multcount", mult);
#ifdef HDIO_DRIVE_CMD
		ioctl_or_warn(fd, HDIO_SET_MULTCOUNT, (void *)mult);
#else
		force_operation |= (!ioctl_or_warn(fd, HDIO_SET_MULTCOUNT, (void *)mult));
#endif
	}
	if (set_readonly) {
		print_flag_on_off(get_readonly, "readonly", readonly);
		ioctl_or_warn(fd, BLKROSET, &readonly);
	}
	if (set_unmask) {
		print_flag_on_off(get_unmask, "unmaskirq", unmask);
		ioctl_or_warn(fd, HDIO_SET_UNMASKINTR, (int *)unmask);
	}
#if ENABLE_FEATURE_HDPARM_HDIO_GETSET_DMA
	if (set_dma) {
		print_flag_on_off(get_dma, "using_dma", dma);
		ioctl_or_warn(fd, HDIO_SET_DMA, (int *)dma);
	}
#endif /* FEATURE_HDPARM_HDIO_GETSET_DMA */
#ifdef HDIO_SET_QDMA
	if (set_dma_q) {
		print_flag_on_off(get_dma_q, "DMA queue_depth", dma_q);
		ioctl_or_warn(fd, HDIO_SET_QDMA, (int *)dma_q);
	}
#endif
	if (set_nowerr) {
		print_flag_on_off(get_nowerr, "nowerr", nowerr);
		ioctl_or_warn(fd, HDIO_SET_NOWERR, (int *)nowerr);
	}
	if (set_keep) {
		print_flag_on_off(get_keep, "keep_settings", keep);
		ioctl_or_warn(fd, HDIO_SET_KEEPSETTINGS, (int *)keep);
	}
#ifdef HDIO_DRIVE_CMD
	if (set_doorlock) {
		args[0] = doorlock ? WIN_DOORLOCK : WIN_DOORUNLOCK;
		args[2] = 0;
		print_flag_on_off(get_doorlock, "drive doorlock", doorlock);
		ioctl_or_warn(fd, HDIO_DRIVE_CMD, &args);
		args[0] = WIN_SETFEATURES;
	}
	if (set_dkeep) {
		/* lock/unlock the drive's "feature" settings */
		print_flag_on_off(get_dkeep, "drive keep features", dkeep);
		args[2] = dkeep ? 0x66 : 0xcc;
		ioctl_or_warn(fd, HDIO_DRIVE_CMD, &args);
	}
	if (set_defects) {
		args[2] = defects ? 0x04 : 0x84;
		print_flag(get_defects, "drive defect-mgmt", defects);
		ioctl_or_warn(fd, HDIO_DRIVE_CMD, &args);
	}
	if (set_prefetch) {
		args[1] = prefetch;
		args[2] = 0xab;
		print_flag(get_prefetch, "drive prefetch", prefetch);
		ioctl_or_warn(fd, HDIO_DRIVE_CMD, &args);
		args[1] = 0;
	}
	if (set_xfermode) {
		args[1] = xfermode_requested;
		args[2] = 3;
		if (get_xfermode) {
			print_flag(1, "xfermode", xfermode_requested);
			interpret_xfermode(xfermode_requested);
		}
		ioctl_or_warn(fd, HDIO_DRIVE_CMD, &args);
		args[1] = 0;
	}
	if (set_lookahead) {
		args[2] = lookahead ? 0xaa : 0x55;
		print_flag_on_off(get_lookahead, "drive read-lookahead", lookahead);
		ioctl_or_warn(fd, HDIO_DRIVE_CMD, &args);
	}
	if (set_apmmode) {
		args[2] = (apmmode == 255) ? 0x85 /* disable */ : 0x05 /* set */; /* feature register */
		args[1] = apmmode; /* sector count register 1-255 */
		if (get_apmmode)
			printf(" setting APM level to %s 0x%02lX (%ld)\n", (apmmode == 255) ? "disabled" : "", apmmode, apmmode);
		ioctl_or_warn(fd, HDIO_DRIVE_CMD, &args);
		args[1] = 0;
	}
	if (set_wcache)	{
#ifdef DO_FLUSHCACHE
#ifndef WIN_FLUSHCACHE
#define WIN_FLUSHCACHE 0xe7
#endif
#endif /* DO_FLUSHCACHE */
		args[2] = wcache ? 0x02 : 0x82;
		print_flag_on_off(get_wcache, "drive write-caching", wcache);
#ifdef DO_FLUSHCACHE
		if (!wcache)
			ioctl_or_warn(fd, HDIO_DRIVE_CMD, &flushcache);
#endif /* DO_FLUSHCACHE */
		ioctl_or_warn(fd, HDIO_DRIVE_CMD, &args);
#ifdef DO_FLUSHCACHE
		if (!wcache)
			ioctl_or_warn(fd, HDIO_DRIVE_CMD, &flushcache);
#endif /* DO_FLUSHCACHE */
	}

	/* In code below, we do not preserve args[0], but the rest
	   is preserved, including args[2] */
	args[2] = 0;

	if (set_standbynow) {
#ifndef WIN_STANDBYNOW1
#define WIN_STANDBYNOW1 0xE0
#endif
#ifndef WIN_STANDBYNOW2
#define WIN_STANDBYNOW2 0x94
#endif
		if (get_standbynow) printf(" issuing standby command\n");
		args[0] = WIN_STANDBYNOW1;
		ioctl_alt_or_warn(HDIO_DRIVE_CMD, args, WIN_STANDBYNOW2);
	}
	if (set_sleepnow) {
#ifndef WIN_SLEEPNOW1
#define WIN_SLEEPNOW1 0xE6
#endif
#ifndef WIN_SLEEPNOW2
#define WIN_SLEEPNOW2 0x99
#endif
		if (get_sleepnow) printf(" issuing sleep command\n");
		args[0] = WIN_SLEEPNOW1;
		ioctl_alt_or_warn(HDIO_DRIVE_CMD, args, WIN_SLEEPNOW2);
	}
	if (set_seagate) {
		args[0] = 0xfb;
		if (get_seagate) printf(" disabling Seagate auto powersaving mode\n");
		ioctl_or_warn(fd, HDIO_DRIVE_CMD, &args);
	}
	if (set_standby) {
		args[0] = WIN_SETIDLE1;
		args[1] = standby_requested;
		if (get_standby) {
			print_flag(1, "standby", standby_requested);
			interpret_standby(standby_requested);
		}
		ioctl_or_warn(fd, HDIO_DRIVE_CMD, &args);
		args[1] = 0;
	}
#else	/* HDIO_DRIVE_CMD */
	if (force_operation) {
		char buf[512];
		flush_buffer_cache();
		if (-1 == read(fd, buf, sizeof(buf)))
			bb_perror_msg("read(%d bytes) failed (rc=-1)", sizeof(buf));
	}
#endif	/* HDIO_DRIVE_CMD */

	if (get_mult || get_identity) {
		multcount = -1;
		if (ioctl(fd, HDIO_GET_MULTCOUNT, &multcount)) {
			if (get_mult && ENABLE_IOCTL_HEX2STR_ERROR) /* To be coherent with ioctl_or_warn. */
				bb_perror_msg("HDIO_GET_MULTCOUNT");
			else
				bb_perror_msg("ioctl %#x failed", HDIO_GET_MULTCOUNT);
		} else if (get_mult) {
			printf(fmt, "multcount", multcount);
			on_off(multcount != 0);
		}
	}
	if (get_io32bit) {
		if (!ioctl_or_warn(fd, HDIO_GET_32BIT, &parm)) {
			printf(" IO_support\t=%3ld (", parm);
			if (parm == 0)
				printf("default 16-bit)\n");
			else if (parm == 2)
				printf("16-bit)\n");
			else if (parm == 1)
				printf("32-bit)\n");
			else if (parm == 3)
				printf("32-bit w/sync)\n");
			else if (parm == 8)
				printf("Request-Queue-Bypass)\n");
			else
				printf("\?\?\?)\n");
		}
	}
	if (get_unmask) {
		if(!ioctl_or_warn(fd, HDIO_GET_UNMASKINTR, &parm))
			print_value_on_off("unmaskirq", parm);
	}


#if ENABLE_FEATURE_HDPARM_HDIO_GETSET_DMA
	if (get_dma) {
		if (!ioctl_or_warn(fd, HDIO_GET_DMA, &parm)) {
			printf(fmt, "using_dma", parm);
			if (parm == 8)
				printf(" (DMA-Assisted-PIO)\n");
			else
				on_off(parm != 0);
		}
	}
#endif
#ifdef HDIO_GET_QDMA
	if (get_dma_q) {
		if(!ioctl_or_warn(fd, HDIO_GET_QDMA, &parm))
			print_value_on_off("queue_depth", parm);
	}
#endif
	if (get_keep) {
		if(!ioctl_or_warn(fd, HDIO_GET_KEEPSETTINGS, &parm))
			print_value_on_off("keepsettings", parm);
	}

	if (get_nowerr) {
		if(!ioctl_or_warn(fd, HDIO_GET_NOWERR, &parm))
			print_value_on_off("nowerr", parm);
	}
	if (get_readonly) {
		if(!ioctl_or_warn(fd, BLKROGET, &parm))
			print_value_on_off("readonly", parm);
	}
	if (get_readahead) {
		if(!ioctl_or_warn(fd, BLKRAGET, &parm))
			print_value_on_off("readahead", parm);
	}
	if (get_geom) {
		if (!ioctl_or_warn(fd, BLKGETSIZE, &parm)) {
			struct hd_geometry g;

			if (!ioctl_or_warn(fd, HDIO_GETGEO, &g))
				printf(" geometry\t= %u/%u/%u, sectors = %ld, start = %ld\n",
						g.cylinders, g.heads, g.sectors, parm, g.start);
		}
	}
#ifdef HDIO_DRIVE_CMD
	if (get_powermode) {
#ifndef WIN_CHECKPOWERMODE1
#define WIN_CHECKPOWERMODE1 0xE5
#endif
#ifndef WIN_CHECKPOWERMODE2
#define WIN_CHECKPOWERMODE2 0x98
#endif
		const char *state;

		args[0] = WIN_CHECKPOWERMODE1;
		if (ioctl_alt_or_warn(HDIO_DRIVE_CMD, args, WIN_CHECKPOWERMODE2)) {
			if (errno != EIO || args[0] != 0 || args[1] != 0)
				state = "unknown";
			else
				state = "sleeping";
		} else
			state = (args[2] == 255) ? "active/idle" : "standby";
		args[1] = args[2] = 0;

		printf(" drive state is:  %s\n", state);
	}
#endif
#if ENABLE_FEATURE_HDPARM_HDIO_DRIVE_RESET
	if (perform_reset) {
		ioctl_or_warn(fd, HDIO_DRIVE_RESET, NULL);
	}
#endif /* FEATURE_HDPARM_HDIO_DRIVE_RESET */
#if ENABLE_FEATURE_HDPARM_HDIO_TRISTATE_HWIF
	if (perform_tristate) {
		args[0] = 0;
		args[1] = tristate;
		ioctl_or_warn(fd, HDIO_TRISTATE_HWIF, &args);
	}
#endif /* FEATURE_HDPARM_HDIO_TRISTATE_HWIF */
#if ENABLE_FEATURE_HDPARM_GET_IDENTITY
	if (get_identity) {
		struct hd_driveid id;

		if (!ioctl(fd, HDIO_GET_IDENTITY, &id))	{
			if (multcount != -1) {
				id.multsect = multcount;
				id.multsect_valid |= 1;
			} else
				id.multsect_valid &= ~1;
			dump_identity(&id);
		} else if (errno == -ENOMSG)
			printf(" no identification info available\n");
		else if (ENABLE_IOCTL_HEX2STR_ERROR)  /* To be coherent with ioctl_or_warn */
			bb_perror_msg("HDIO_GET_IDENTITY");
		else
			bb_perror_msg("ioctl %#x failed", HDIO_GET_IDENTITY);
	}

	if (get_IDentity) {
		unsigned char args1[4+512]; /* = { ... } will eat 0.5k of rodata! */

		memset(args1, 0, sizeof(args1));
		args1[0] = WIN_IDENTIFY;
		args1[3] = 1;
		if (!ioctl_alt_or_warn(HDIO_DRIVE_CMD, args1, WIN_PIDENTIFY))
			identify((void *)(args1 + 4));
	}
#endif
#if ENABLE_FEATURE_HDPARM_HDIO_TRISTATE_HWIF
	if (set_busstate) {
		if (get_busstate) {
			print_flag(1, "bus state", busstate);
			bus_state_value(busstate);
		}
		ioctl_or_warn(fd, HDIO_SET_BUSSTATE, (int *)(unsigned long)busstate);
	}
	if (get_busstate) {
		if (!ioctl_or_warn(fd, HDIO_GET_BUSSTATE, &parm)) {
			printf(fmt, "bus state", parm);
			bus_state_value(parm);
		}
	}
#endif
	if (reread_partn)
		ioctl_or_warn(fd, BLKRRPART, NULL);

	if (do_ctimings)
		do_time(1 /*,fd*/); /* time cache */
	if (do_timings)
		do_time(0 /*,fd*/); /* time device */
	if (do_flush)
		flush_buffer_cache();
	close(fd);
}

#if ENABLE_FEATURE_HDPARM_GET_IDENTITY
static int fromhex(unsigned char c)
{
	if (isdigit(c))
		return (c - '0');
	if (c >= 'a' && c <= 'f')
		return (c - ('a' - 10));
	bb_error_msg_and_die("bad char: '%c' 0x%02x", c, c);
}

static void identify_from_stdin(void) ATTRIBUTE_NORETURN;
static void identify_from_stdin(void)
{
	uint16_t sbuf[256];
	unsigned char buf[1280];
	unsigned char *b = (unsigned char *)buf;
	int i;

	xread(STDIN_FILENO, buf, 1280);

	// Convert the newline-separated hex data into an identify block.

	for (i = 0; i < 256; i++) {
		int j;
		for (j = 0; j < 4; j++)
			sbuf[i] = (sbuf[i] << 4) + fromhex(*(b++));
	}

	// Parse the data.

	identify(sbuf);
}
#else
void identify_from_stdin(void);
#endif

/* busybox specific stuff */
static void parse_opts(smallint *get, smallint *set, unsigned long *value, int min, int max)
{
	if (get) {
		*get = 1;
	}
	if (optarg) {
		*set = 1;
		*value = xatol_range(optarg, min, max);
	}
}

static void parse_xfermode(int flag, smallint *get, smallint *set, int *value)
{
	if (flag) {
		*get = 1;
		if (optarg) {
			*value = translate_xfermode(optarg);
			*set = (*value > -1);
		}
	}
}

/*------- getopt short options --------*/
static const char hdparm_options[] ALIGN1 =
	"gfu::n::p:r::m::c::k::a::B:tT"
	USE_FEATURE_HDPARM_GET_IDENTITY("iI")
	USE_FEATURE_HDPARM_HDIO_GETSET_DMA("d::")
#ifdef HDIO_DRIVE_CMD
	"S:D:P:X:K:A:L:W:CyYzZ"
#endif
	USE_FEATURE_HDPARM_HDIO_UNREGISTER_HWIF("U:")
#ifdef HDIO_GET_QDMA
#ifdef HDIO_SET_QDMA
	"Q:"
#else
	"Q"
#endif
#endif
	USE_FEATURE_HDPARM_HDIO_DRIVE_RESET("w")
	USE_FEATURE_HDPARM_HDIO_TRISTATE_HWIF("x::b:")
	USE_FEATURE_HDPARM_HDIO_SCAN_HWIF("R:");
/*-------------------------------------*/

/* our main() routine: */
int hdparm_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int hdparm_main(int argc, char **argv)
{
	int c;
	int flagcount = 0;

	while ((c = getopt(argc, argv, hdparm_options)) >= 0) {
		flagcount++;
		USE_FEATURE_HDPARM_GET_IDENTITY(get_IDentity |= (c == 'I'));
		USE_FEATURE_HDPARM_GET_IDENTITY(get_identity |= (c == 'i'));
		get_geom |= (c == 'g');
		do_flush |= (c == 'f');
		if (c == 'u') parse_opts(&get_unmask, &set_unmask, &unmask, 0, 1);
		USE_FEATURE_HDPARM_HDIO_GETSET_DMA(if (c == 'd') parse_opts(&get_dma, &set_dma, &dma, 0, 9));
		if (c == 'n') parse_opts(&get_nowerr, &set_nowerr, &nowerr, 0, 1);
		parse_xfermode((c == 'p'), &noisy_piomode, &set_piomode, &piomode);
		if (c == 'r') parse_opts(&get_readonly, &set_readonly, &readonly, 0, 1);
		if (c == 'm') parse_opts(&get_mult, &set_mult, &mult, 0, INT_MAX /*32*/);
		if (c == 'c') parse_opts(&get_io32bit, &set_io32bit, &io32bit, 0, INT_MAX /*8*/);
		if (c == 'k') parse_opts(&get_keep, &set_keep, &keep, 0, 1);
		if (c == 'a') parse_opts(&get_readahead, &set_readahead, &Xreadahead, 0, INT_MAX);
		if (c == 'B') parse_opts(&get_apmmode, &set_apmmode, &apmmode, 1, 255);
		do_flush |= do_timings |= (c == 't');
		do_flush |= do_ctimings |= (c == 'T');
#ifdef HDIO_DRIVE_CMD
		if (c == 'S') parse_opts(&get_standby, &set_standby, &standby_requested, 0, 255);
		if (c == 'D') parse_opts(&get_defects, &set_defects, &defects, 0, INT_MAX);
		if (c == 'P') parse_opts(&get_prefetch, &set_prefetch, &prefetch, 0, INT_MAX);
		parse_xfermode((c == 'X'), &get_xfermode, &set_xfermode, &xfermode_requested);
		if (c == 'K') parse_opts(&get_dkeep, &set_dkeep, &prefetch, 0, 1);
		if (c == 'A') parse_opts(&get_lookahead, &set_lookahead, &lookahead, 0, 1);
		if (c == 'L') parse_opts(&get_doorlock, &set_doorlock, &doorlock, 0, 1);
		if (c == 'W') parse_opts(&get_wcache, &set_wcache, &wcache, 0, 1);
		get_powermode |= (c == 'C');
		get_standbynow = set_standbynow |= (c == 'y');
		get_sleepnow = set_sleepnow |= (c == 'Y');
		reread_partn |= (c == 'z');
		get_seagate = set_seagate |= (c == 'Z');
#endif
		USE_FEATURE_HDPARM_HDIO_UNREGISTER_HWIF(if (c == 'U') parse_opts(NULL, &unregister_hwif, &hwif, 0, INT_MAX));
#ifdef HDIO_GET_QDMA
		if (c == 'Q') {
#ifdef HDIO_SET_QDMA
			parse_opts(&get_dma_q, &set_dma_q, &dma_q, 0, INT_MAX);
#else
			parse_opts(&get_dma_q, NULL, NULL, 0, 0);
#endif
		}
#endif
		USE_FEATURE_HDPARM_HDIO_DRIVE_RESET(perform_reset = (c == 'r'));
		USE_FEATURE_HDPARM_HDIO_TRISTATE_HWIF(if (c == 'x') parse_opts(NULL, &perform_tristate, &tristate, 0, 1));
		USE_FEATURE_HDPARM_HDIO_TRISTATE_HWIF(if (c == 'b') parse_opts(&get_busstate, &set_busstate, &busstate, 0, 2));
#if ENABLE_FEATURE_HDPARM_HDIO_SCAN_HWIF
		if (c == 'R') {
			parse_opts(NULL, &scan_hwif, &hwif_data, 0, INT_MAX);
			hwif_ctrl = xatoi_u((argv[optind]) ? argv[optind] : "");
			hwif_irq  = xatoi_u((argv[optind+1]) ? argv[optind+1] : "");
			/* Move past the 2 additional arguments */
			argv += 2;
			argc -= 2;
		}
#endif
	}
	/* When no flags are given (flagcount = 0), -acdgkmnru is assumed. */
	if (!flagcount) {
		get_mult = get_io32bit = get_unmask = get_keep = get_readonly = get_readahead = get_geom = 1;
		USE_FEATURE_HDPARM_HDIO_GETSET_DMA(get_dma = 1);
	}
	argv += optind;

	if (!*argv) {
		if (ENABLE_FEATURE_HDPARM_GET_IDENTITY && !isatty(STDIN_FILENO))
			identify_from_stdin(); /* EXIT */
		bb_show_usage();
	}

	do {
		process_dev(*argv++);
	} while (*argv);

	return EXIT_SUCCESS;
}