|
root / base / usr / src / cmd / format
format Plain Text 30840 lines 750.5 KB
    1
    2
    3
    4
    5
    6
    7
    8
    9
   10
   11
   12
   13
   14
   15
   16
   17
   18
   19
   20
   21
   22
   23
   24
   25
   26
   27
   28
   29
   30
   31
   32
   33
   34
   35
   36
   37
   38
   39
   40
   41
   42
   43
   44
   45
   46
   47
   48
   49
   50
   51
   52
   53
   54
   55
   56
   57
   58
   59
   60
   61
   62
   63
   64
   65
   66
   67
   68
   69
   70
   71
   72
   73
   74
   75
   76
   77
   78
   79
   80
   81
   82
   83
   84
   85
   86
   87
   88
   89
   90
   91
   92
   93
   94
   95
   96
   97
   98
   99
  100
  101
  102
  103
  104
  105
  106
  107
  108
  109
  110
  111
  112
  113
  114
  115
  116
  117
  118
  119
  120
  121
  122
  123
  124
  125
  126
  127
  128
  129
  130
  131
  132
  133
  134
  135
  136
  137
  138
  139
  140
  141
  142
  143
  144
  145
  146
  147
  148
  149
  150
  151
  152
  153
  154
  155
  156
  157
  158
  159
  160
  161
  162
  163
  164
  165
  166
  167
  168
  169
  170
  171
  172
  173
  174
  175
  176
  177
  178
  179
  180
  181
  182
  183
  184
  185
  186
  187
  188
  189
  190
  191
  192
  193
  194
  195
  196
  197
  198
  199
  200
  201
  202
  203
  204
  205
  206
  207
  208
  209
  210
  211
  212
  213
  214
  215
  216
  217
  218
  219
  220
  221
  222
  223
  224
  225
  226
  227
  228
  229
  230
  231
  232
  233
  234
  235
  236
  237
  238
  239
  240
  241
  242
  243
  244
  245
  246
  247
  248
  249
  250
  251
  252
  253
  254
  255
  256
  257
  258
  259
  260
  261
  262
  263
  264
  265
  266
  267
  268
  269
  270
  271
  272
  273
  274
  275
  276
  277
  278
  279
  280
  281
  282
  283
  284
  285
  286
  287
  288
  289
  290
  291
  292
  293
  294
  295
  296
  297
  298
  299
  300
  301
  302
  303
  304
  305
  306
  307
  308
  309
  310
  311
  312
  313
  314
  315
  316
  317
  318
  319
  320
  321
  322
  323
  324
  325
  326
  327
  328
  329
  330
  331
  332
  333
  334
  335
  336
  337
  338
  339
  340
  341
  342
  343
  344
  345
  346
  347
  348
  349
  350
  351
  352
  353
  354
  355
  356
  357
  358
  359
  360
  361
  362
  363
  364
  365
  366
  367
  368
  369
  370
  371
  372
  373
  374
  375
  376
  377
  378
  379
  380
  381
  382
  383
  384
  385
  386
  387
  388
  389
  390
  391
  392
  393
  394
  395
  396
  397
  398
  399
  400
  401
  402
  403
  404
  405
  406
  407
  408
  409
  410
  411
  412
  413
  414
  415
  416
  417
  418
  419
  420
  421
  422
  423
  424
  425
  426
  427
  428
  429
  430
  431
  432
  433
  434
  435
  436
  437
  438
  439
  440
  441
  442
  443
  444
  445
  446
  447
  448
  449
  450
  451
  452
  453
  454
  455
  456
  457
  458
  459
  460
  461
  462
  463
  464
  465
  466
  467
  468
  469
  470
  471
  472
  473
  474
  475
  476
  477
  478
  479
  480
  481
  482
  483
  484
  485
  486
  487
  488
  489
  490
  491
  492
  493
  494
  495
  496
  497
  498
  499
  500
  501
  502
  503
  504
  505
  506
  507
  508
  509
  510
  511
  512
  513
  514
  515
  516
  517
  518
  519
  520
  521
  522
  523
  524
  525
  526
  527
  528
  529
  530
  531
  532
  533
  534
  535
  536
  537
  538
  539
  540
  541
  542
  543
  544
  545
  546
  547
  548
  549
  550
  551
  552
  553
  554
  555
  556
  557
  558
  559
  560
  561
  562
  563
  564
  565
  566
  567
  568
  569
  570
  571
  572
  573
  574
  575
  576
  577
  578
  579
  580
  581
  582
  583
  584
  585
  586
  587
  588
  589
  590
  591
  592
  593
  594
  595
  596
  597
  598
  599
  600
  601
  602
  603
  604
  605
  606
  607
  608
  609
  610
  611
  612
  613
  614
  615
  616
  617
  618
  619
  620
  621
  622
  623
  624
  625
  626
  627
  628
  629
  630
  631
  632
  633
  634
  635
  636
  637
  638
  639
  640
  641
  642
  643
  644
  645
  646
  647
  648
  649
  650
  651
  652
  653
  654
  655
  656
  657
  658
  659
  660
  661
  662
  663
  664
  665
  666
  667
  668
  669
  670
  671
  672
  673
  674
  675
  676
  677
  678
  679
  680
  681
  682
  683
  684
  685
  686
  687
  688
  689
  690
  691
  692
  693
  694
  695
  696
  697
  698
  699
  700
  701
  702
  703
  704
  705
  706
  707
  708
  709
  710
  711
  712
  713
  714
  715
  716
  717
  718
  719
  720
  721
  722
  723
  724
  725
  726
  727
  728
  729
  730
  731
  732
  733
  734
  735
  736
  737
  738
  739
  740
  741
  742
  743
  744
  745
  746
  747
  748
  749
  750
  751
  752
  753
  754
  755
  756
  757
  758
  759
  760
  761
  762
  763
  764
  765
  766
  767
  768
  769
  770
  771
  772
  773
  774
  775
  776
  777
  778
  779
  780
  781
  782
  783
  784
  785
  786
  787
  788
  789
  790
  791
  792
  793
  794
  795
  796
  797
  798
  799
  800
  801
  802
  803
  804
  805
  806
  807
  808
  809
  810
  811
  812
  813
  814
  815
  816
  817
  818
  819
  820
  821
  822
  823
  824
  825
  826
  827
  828
  829
  830
  831
  832
  833
  834
  835
  836
  837
  838
  839
  840
  841
  842
  843
  844
  845
  846
  847
  848
  849
  850
  851
  852
  853
  854
  855
  856
  857
  858
  859
  860
  861
  862
  863
  864
  865
  866
  867
  868
  869
  870
  871
  872
  873
  874
  875
  876
  877
  878
  879
  880
  881
  882
  883
  884
  885
  886
  887
  888
  889
  890
  891
  892
  893
  894
  895
  896
  897
  898
  899
  900
  901
  902
  903
  904
  905
  906
  907
  908
  909
  910
  911
  912
  913
  914
  915
  916
  917
  918
  919
  920
  921
  922
  923
  924
  925
  926
  927
  928
  929
  930
  931
  932
  933
  934
  935
  936
  937
  938
  939
  940
  941
  942
  943
  944
  945
  946
  947
  948
  949
  950
  951
  952
  953
  954
  955
  956
  957
  958
  959
  960
  961
  962
  963
  964
  965
  966
  967
  968
  969
  970
  971
  972
  973
  974
  975
  976
  977
  978
  979
  980
  981
  982
  983
  984
  985
  986
  987
  988
  989
  990
  991
  992
  993
  994
  995
  996
  997
  998
  999
 1000
 1001
 1002
 1003
 1004
 1005
 1006
 1007
 1008
 1009
 1010
 1011
 1012
 1013
 1014
 1015
 1016
 1017
 1018
 1019
 1020
 1021
 1022
 1023
 1024
 1025
 1026
 1027
 1028
 1029
 1030
 1031
 1032
 1033
 1034
 1035
 1036
 1037
 1038
 1039
 1040
 1041
 1042
 1043
 1044
 1045
 1046
 1047
 1048
 1049
 1050
 1051
 1052
 1053
 1054
 1055
 1056
 1057
 1058
 1059
 1060
 1061
 1062
 1063
 1064
 1065
 1066
 1067
 1068
 1069
 1070
 1071
 1072
 1073
 1074
 1075
 1076
 1077
 1078
 1079
 1080
 1081
 1082
 1083
 1084
 1085
 1086
 1087
 1088
 1089
 1090
 1091
 1092
 1093
 1094
 1095
 1096
 1097
 1098
 1099
 1100
 1101
 1102
 1103
 1104
 1105
 1106
 1107
 1108
 1109
 1110
 1111
 1112
 1113
 1114
 1115
 1116
 1117
 1118
 1119
 1120
 1121
 1122
 1123
 1124
 1125
 1126
 1127
 1128
 1129
 1130
 1131
 1132
 1133
 1134
 1135
 1136
 1137
 1138
 1139
 1140
 1141
 1142
 1143
 1144
 1145
 1146
 1147
 1148
 1149
 1150
 1151
 1152
 1153
 1154
 1155
 1156
 1157
 1158
 1159
 1160
 1161
 1162
 1163
 1164
 1165
 1166
 1167
 1168
 1169
 1170
 1171
 1172
 1173
 1174
 1175
 1176
 1177
 1178
 1179
 1180
 1181
 1182
 1183
 1184
 1185
 1186
 1187
 1188
 1189
 1190
 1191
 1192
 1193
 1194
 1195
 1196
 1197
 1198
 1199
 1200
 1201
 1202
 1203
 1204
 1205
 1206
 1207
 1208
 1209
 1210
 1211
 1212
 1213
 1214
 1215
 1216
 1217
 1218
 1219
 1220
 1221
 1222
 1223
 1224
 1225
 1226
 1227
 1228
 1229
 1230
 1231
 1232
 1233
 1234
 1235
 1236
 1237
 1238
 1239
 1240
 1241
 1242
 1243
 1244
 1245
 1246
 1247
 1248
 1249
 1250
 1251
 1252
 1253
 1254
 1255
 1256
 1257
 1258
 1259
 1260
 1261
 1262
 1263
 1264
 1265
 1266
 1267
 1268
 1269
 1270
 1271
 1272
 1273
 1274
 1275
 1276
 1277
 1278
 1279
 1280
 1281
 1282
 1283
 1284
 1285
 1286
 1287
 1288
 1289
 1290
 1291
 1292
 1293
 1294
 1295
 1296
 1297
 1298
 1299
 1300
 1301
 1302
 1303
 1304
 1305
 1306
 1307
 1308
 1309
 1310
 1311
 1312
 1313
 1314
 1315
 1316
 1317
 1318
 1319
 1320
 1321
 1322
 1323
 1324
 1325
 1326
 1327
 1328
 1329
 1330
 1331
 1332
 1333
 1334
 1335
 1336
 1337
 1338
 1339
 1340
 1341
 1342
 1343
 1344
 1345
 1346
 1347
 1348
 1349
 1350
 1351
 1352
 1353
 1354
 1355
 1356
 1357
 1358
 1359
 1360
 1361
 1362
 1363
 1364
 1365
 1366
 1367
 1368
 1369
 1370
 1371
 1372
 1373
 1374
 1375
 1376
 1377
 1378
 1379
 1380
 1381
 1382
 1383
 1384
 1385
 1386
 1387
 1388
 1389
 1390
 1391
 1392
 1393
 1394
 1395
 1396
 1397
 1398
 1399
 1400
 1401
 1402
 1403
 1404
 1405
 1406
 1407
 1408
 1409
 1410
 1411
 1412
 1413
 1414
 1415
 1416
 1417
 1418
 1419
 1420
 1421
 1422
 1423
 1424
 1425
 1426
 1427
 1428
 1429
 1430
 1431
 1432
 1433
 1434
 1435
 1436
 1437
 1438
 1439
 1440
 1441
 1442
 1443
 1444
 1445
 1446
 1447
 1448
 1449
 1450
 1451
 1452
 1453
 1454
 1455
 1456
 1457
 1458
 1459
 1460
 1461
 1462
 1463
 1464
 1465
 1466
 1467
 1468
 1469
 1470
 1471
 1472
 1473
 1474
 1475
 1476
 1477
 1478
 1479
 1480
 1481
 1482
 1483
 1484
 1485
 1486
 1487
 1488
 1489
 1490
 1491
 1492
 1493
 1494
 1495
 1496
 1497
 1498
 1499
 1500
 1501
 1502
 1503
 1504
 1505
 1506
 1507
 1508
 1509
 1510
 1511
 1512
 1513
 1514
 1515
 1516
 1517
 1518
 1519
 1520
 1521
 1522
 1523
 1524
 1525
 1526
 1527
 1528
 1529
 1530
 1531
 1532
 1533
 1534
 1535
 1536
 1537
 1538
 1539
 1540
 1541
 1542
 1543
 1544
 1545
 1546
 1547
 1548
 1549
 1550
 1551
 1552
 1553
 1554
 1555
 1556
 1557
 1558
 1559
 1560
 1561
 1562
 1563
 1564
 1565
 1566
 1567
 1568
 1569
 1570
 1571
 1572
 1573
 1574
 1575
 1576
 1577
 1578
 1579
 1580
 1581
 1582
 1583
 1584
 1585
 1586
 1587
 1588
 1589
 1590
 1591
 1592
 1593
 1594
 1595
 1596
 1597
 1598
 1599
 1600
 1601
 1602
 1603
 1604
 1605
 1606
 1607
 1608
 1609
 1610
 1611
 1612
 1613
 1614
 1615
 1616
 1617
 1618
 1619
 1620
 1621
 1622
 1623
 1624
 1625
 1626
 1627
 1628
 1629
 1630
 1631
 1632
 1633
 1634
 1635
 1636
 1637
 1638
 1639
 1640
 1641
 1642
 1643
 1644
 1645
 1646
 1647
 1648
 1649
 1650
 1651
 1652
 1653
 1654
 1655
 1656
 1657
 1658
 1659
 1660
 1661
 1662
 1663
 1664
 1665
 1666
 1667
 1668
 1669
 1670
 1671
 1672
 1673
 1674
 1675
 1676
 1677
 1678
 1679
 1680
 1681
 1682
 1683
 1684
 1685
 1686
 1687
 1688
 1689
 1690
 1691
 1692
 1693
 1694
 1695
 1696
 1697
 1698
 1699
 1700
 1701
 1702
 1703
 1704
 1705
 1706
 1707
 1708
 1709
 1710
 1711
 1712
 1713
 1714
 1715
 1716
 1717
 1718
 1719
 1720
 1721
 1722
 1723
 1724
 1725
 1726
 1727
 1728
 1729
 1730
 1731
 1732
 1733
 1734
 1735
 1736
 1737
 1738
 1739
 1740
 1741
 1742
 1743
 1744
 1745
 1746
 1747
 1748
 1749
 1750
 1751
 1752
 1753
 1754
 1755
 1756
 1757
 1758
 1759
 1760
 1761
 1762
 1763
 1764
 1765
 1766
 1767
 1768
 1769
 1770
 1771
 1772
 1773
 1774
 1775
 1776
 1777
 1778
 1779
 1780
 1781
 1782
 1783
 1784
 1785
 1786
 1787
 1788
 1789
 1790
 1791
 1792
 1793
 1794
 1795
 1796
 1797
 1798
 1799
 1800
 1801
 1802
 1803
 1804
 1805
 1806
 1807
 1808
 1809
 1810
 1811
 1812
 1813
 1814
 1815
 1816
 1817
 1818
 1819
 1820
 1821
 1822
 1823
 1824
 1825
 1826
 1827
 1828
 1829
 1830
 1831
 1832
 1833
 1834
 1835
 1836
 1837
 1838
 1839
 1840
 1841
 1842
 1843
 1844
 1845
 1846
 1847
 1848
 1849
 1850
 1851
 1852
 1853
 1854
 1855
 1856
 1857
 1858
 1859
 1860
 1861
 1862
 1863
 1864
 1865
 1866
 1867
 1868
 1869
 1870
 1871
 1872
 1873
 1874
 1875
 1876
 1877
 1878
 1879
 1880
 1881
 1882
 1883
 1884
 1885
 1886
 1887
 1888
 1889
 1890
 1891
 1892
 1893
 1894
 1895
 1896
 1897
 1898
 1899
 1900
 1901
 1902
 1903
 1904
 1905
 1906
 1907
 1908
 1909
 1910
 1911
 1912
 1913
 1914
 1915
 1916
 1917
 1918
 1919
 1920
 1921
 1922
 1923
 1924
 1925
 1926
 1927
 1928
 1929
 1930
 1931
 1932
 1933
 1934
 1935
 1936
 1937
 1938
 1939
 1940
 1941
 1942
 1943
 1944
 1945
 1946
 1947
 1948
 1949
 1950
 1951
 1952
 1953
 1954
 1955
 1956
 1957
 1958
 1959
 1960
 1961
 1962
 1963
 1964
 1965
 1966
 1967
 1968
 1969
 1970
 1971
 1972
 1973
 1974
 1975
 1976
 1977
 1978
 1979
 1980
 1981
 1982
 1983
 1984
 1985
 1986
 1987
 1988
 1989
 1990
 1991
 1992
 1993
 1994
 1995
 1996
 1997
 1998
 1999
 2000
 2001
 2002
 2003
 2004
 2005
 2006
 2007
 2008
 2009
 2010
 2011
 2012
 2013
 2014
 2015
 2016
 2017
 2018
 2019
 2020
 2021
 2022
 2023
 2024
 2025
 2026
 2027
 2028
 2029
 2030
 2031
 2032
 2033
 2034
 2035
 2036
 2037
 2038
 2039
 2040
 2041
 2042
 2043
 2044
 2045
 2046
 2047
 2048
 2049
 2050
 2051
 2052
 2053
 2054
 2055
 2056
 2057
 2058
 2059
 2060
 2061
 2062
 2063
 2064
 2065
 2066
 2067
 2068
 2069
 2070
 2071
 2072
 2073
 2074
 2075
 2076
 2077
 2078
 2079
 2080
 2081
 2082
 2083
 2084
 2085
 2086
 2087
 2088
 2089
 2090
 2091
 2092
 2093
 2094
 2095
 2096
 2097
 2098
 2099
 2100
 2101
 2102
 2103
 2104
 2105
 2106
 2107
 2108
 2109
 2110
 2111
 2112
 2113
 2114
 2115
 2116
 2117
 2118
 2119
 2120
 2121
 2122
 2123
 2124
 2125
 2126
 2127
 2128
 2129
 2130
 2131
 2132
 2133
 2134
 2135
 2136
 2137
 2138
 2139
 2140
 2141
 2142
 2143
 2144
 2145
 2146
 2147
 2148
 2149
 2150
 2151
 2152
 2153
 2154
 2155
 2156
 2157
 2158
 2159
 2160
 2161
 2162
 2163
 2164
 2165
 2166
 2167
 2168
 2169
 2170
 2171
 2172
 2173
 2174
 2175
 2176
 2177
 2178
 2179
 2180
 2181
 2182
 2183
 2184
 2185
 2186
 2187
 2188
 2189
 2190
 2191
 2192
 2193
 2194
 2195
 2196
 2197
 2198
 2199
 2200
 2201
 2202
 2203
 2204
 2205
 2206
 2207
 2208
 2209
 2210
 2211
 2212
 2213
 2214
 2215
 2216
 2217
 2218
 2219
 2220
 2221
 2222
 2223
 2224
 2225
 2226
 2227
 2228
 2229
 2230
 2231
 2232
 2233
 2234
 2235
 2236
 2237
 2238
 2239
 2240
 2241
 2242
 2243
 2244
 2245
 2246
 2247
 2248
 2249
 2250
 2251
 2252
 2253
 2254
 2255
 2256
 2257
 2258
 2259
 2260
 2261
 2262
 2263
 2264
 2265
 2266
 2267
 2268
 2269
 2270
 2271
 2272
 2273
 2274
 2275
 2276
 2277
 2278
 2279
 2280
 2281
 2282
 2283
 2284
 2285
 2286
 2287
 2288
 2289
 2290
 2291
 2292
 2293
 2294
 2295
 2296
 2297
 2298
 2299
 2300
 2301
 2302
 2303
 2304
 2305
 2306
 2307
 2308
 2309
 2310
 2311
 2312
 2313
 2314
 2315
 2316
 2317
 2318
 2319
 2320
 2321
 2322
 2323
 2324
 2325
 2326
 2327
 2328
 2329
 2330
 2331
 2332
 2333
 2334
 2335
 2336
 2337
 2338
 2339
 2340
 2341
 2342
 2343
 2344
 2345
 2346
 2347
 2348
 2349
 2350
 2351
 2352
 2353
 2354
 2355
 2356
 2357
 2358
 2359
 2360
 2361
 2362
 2363
 2364
 2365
 2366
 2367
 2368
 2369
 2370
 2371
 2372
 2373
 2374
 2375
 2376
 2377
 2378
 2379
 2380
 2381
 2382
 2383
 2384
 2385
 2386
 2387
 2388
 2389
 2390
 2391
 2392
 2393
 2394
 2395
 2396
 2397
 2398
 2399
 2400
 2401
 2402
 2403
 2404
 2405
 2406
 2407
 2408
 2409
 2410
 2411
 2412
 2413
 2414
 2415
 2416
 2417
 2418
 2419
 2420
 2421
 2422
 2423
 2424
 2425
 2426
 2427
 2428
 2429
 2430
 2431
 2432
 2433
 2434
 2435
 2436
 2437
 2438
 2439
 2440
 2441
 2442
 2443
 2444
 2445
 2446
 2447
 2448
 2449
 2450
 2451
 2452
 2453
 2454
 2455
 2456
 2457
 2458
 2459
 2460
 2461
 2462
 2463
 2464
 2465
 2466
 2467
 2468
 2469
 2470
 2471
 2472
 2473
 2474
 2475
 2476
 2477
 2478
 2479
 2480
 2481
 2482
 2483
 2484
 2485
 2486
 2487
 2488
 2489
 2490
 2491
 2492
 2493
 2494
 2495
 2496
 2497
 2498
 2499
 2500
 2501
 2502
 2503
 2504
 2505
 2506
 2507
 2508
 2509
 2510
 2511
 2512
 2513
 2514
 2515
 2516
 2517
 2518
 2519
 2520
 2521
 2522
 2523
 2524
 2525
 2526
 2527
 2528
 2529
 2530
 2531
 2532
 2533
 2534
 2535
 2536
 2537
 2538
 2539
 2540
 2541
 2542
 2543
 2544
 2545
 2546
 2547
 2548
 2549
 2550
 2551
 2552
 2553
 2554
 2555
 2556
 2557
 2558
 2559
 2560
 2561
 2562
 2563
 2564
 2565
 2566
 2567
 2568
 2569
 2570
 2571
 2572
 2573
 2574
 2575
 2576
 2577
 2578
 2579
 2580
 2581
 2582
 2583
 2584
 2585
 2586
 2587
 2588
 2589
 2590
 2591
 2592
 2593
 2594
 2595
 2596
 2597
 2598
 2599
 2600
 2601
 2602
 2603
 2604
 2605
 2606
 2607
 2608
 2609
 2610
 2611
 2612
 2613
 2614
 2615
 2616
 2617
 2618
 2619
 2620
 2621
 2622
 2623
 2624
 2625
 2626
 2627
 2628
 2629
 2630
 2631
 2632
 2633
 2634
 2635
 2636
 2637
 2638
 2639
 2640
 2641
 2642
 2643
 2644
 2645
 2646
 2647
 2648
 2649
 2650
 2651
 2652
 2653
 2654
 2655
 2656
 2657
 2658
 2659
 2660
 2661
 2662
 2663
 2664
 2665
 2666
 2667
 2668
 2669
 2670
 2671
 2672
 2673
 2674
 2675
 2676
 2677
 2678
 2679
 2680
 2681
 2682
 2683
 2684
 2685
 2686
 2687
 2688
 2689
 2690
 2691
 2692
 2693
 2694
 2695
 2696
 2697
 2698
 2699
 2700
 2701
 2702
 2703
 2704
 2705
 2706
 2707
 2708
 2709
 2710
 2711
 2712
 2713
 2714
 2715
 2716
 2717
 2718
 2719
 2720
 2721
 2722
 2723
 2724
 2725
 2726
 2727
 2728
 2729
 2730
 2731
 2732
 2733
 2734
 2735
 2736
 2737
 2738
 2739
 2740
 2741
 2742
 2743
 2744
 2745
 2746
 2747
 2748
 2749
 2750
 2751
 2752
 2753
 2754
 2755
 2756
 2757
 2758
 2759
 2760
 2761
 2762
 2763
 2764
 2765
 2766
 2767
 2768
 2769
 2770
 2771
 2772
 2773
 2774
 2775
 2776
 2777
 2778
 2779
 2780
 2781
 2782
 2783
 2784
 2785
 2786
 2787
 2788
 2789
 2790
 2791
 2792
 2793
 2794
 2795
 2796
 2797
 2798
 2799
 2800
 2801
 2802
 2803
 2804
 2805
 2806
 2807
 2808
 2809
 2810
 2811
 2812
 2813
 2814
 2815
 2816
 2817
 2818
 2819
 2820
 2821
 2822
 2823
 2824
 2825
 2826
 2827
 2828
 2829
 2830
 2831
 2832
 2833
 2834
 2835
 2836
 2837
 2838
 2839
 2840
 2841
 2842
 2843
 2844
 2845
 2846
 2847
 2848
 2849
 2850
 2851
 2852
 2853
 2854
 2855
 2856
 2857
 2858
 2859
 2860
 2861
 2862
 2863
 2864
 2865
 2866
 2867
 2868
 2869
 2870
 2871
 2872
 2873
 2874
 2875
 2876
 2877
 2878
 2879
 2880
 2881
 2882
 2883
 2884
 2885
 2886
 2887
 2888
 2889
 2890
 2891
 2892
 2893
 2894
 2895
 2896
 2897
 2898
 2899
 2900
 2901
 2902
 2903
 2904
 2905
 2906
 2907
 2908
 2909
 2910
 2911
 2912
 2913
 2914
 2915
 2916
 2917
 2918
 2919
 2920
 2921
 2922
 2923
 2924
 2925
 2926
 2927
 2928
 2929
 2930
 2931
 2932
 2933
 2934
 2935
 2936
 2937
 2938
 2939
 2940
 2941
 2942
 2943
 2944
 2945
 2946
 2947
 2948
 2949
 2950
 2951
 2952
 2953
 2954
 2955
 2956
 2957
 2958
 2959
 2960
 2961
 2962
 2963
 2964
 2965
 2966
 2967
 2968
 2969
 2970
 2971
 2972
 2973
 2974
 2975
 2976
 2977
 2978
 2979
 2980
 2981
 2982
 2983
 2984
 2985
 2986
 2987
 2988
 2989
 2990
 2991
 2992
 2993
 2994
 2995
 2996
 2997
 2998
 2999
 3000
 3001
 3002
 3003
 3004
 3005
 3006
 3007
 3008
 3009
 3010
 3011
 3012
 3013
 3014
 3015
 3016
 3017
 3018
 3019
 3020
 3021
 3022
 3023
 3024
 3025
 3026
 3027
 3028
 3029
 3030
 3031
 3032
 3033
 3034
 3035
 3036
 3037
 3038
 3039
 3040
 3041
 3042
 3043
 3044
 3045
 3046
 3047
 3048
 3049
 3050
 3051
 3052
 3053
 3054
 3055
 3056
 3057
 3058
 3059
 3060
 3061
 3062
 3063
 3064
 3065
 3066
 3067
 3068
 3069
 3070
 3071
 3072
 3073
 3074
 3075
 3076
 3077
 3078
 3079
 3080
 3081
 3082
 3083
 3084
 3085
 3086
 3087
 3088
 3089
 3090
 3091
 3092
 3093
 3094
 3095
 3096
 3097
 3098
 3099
 3100
 3101
 3102
 3103
 3104
 3105
 3106
 3107
 3108
 3109
 3110
 3111
 3112
 3113
 3114
 3115
 3116
 3117
 3118
 3119
 3120
 3121
 3122
 3123
 3124
 3125
 3126
 3127
 3128
 3129
 3130
 3131
 3132
 3133
 3134
 3135
 3136
 3137
 3138
 3139
 3140
 3141
 3142
 3143
 3144
 3145
 3146
 3147
 3148
 3149
 3150
 3151
 3152
 3153
 3154
 3155
 3156
 3157
 3158
 3159
 3160
 3161
 3162
 3163
 3164
 3165
 3166
 3167
 3168
 3169
 3170
 3171
 3172
 3173
 3174
 3175
 3176
 3177
 3178
 3179
 3180
 3181
 3182
 3183
 3184
 3185
 3186
 3187
 3188
 3189
 3190
 3191
 3192
 3193
 3194
 3195
 3196
 3197
 3198
 3199
 3200
 3201
 3202
 3203
 3204
 3205
 3206
 3207
 3208
 3209
 3210
 3211
 3212
 3213
 3214
 3215
 3216
 3217
 3218
 3219
 3220
 3221
 3222
 3223
 3224
 3225
 3226
 3227
 3228
 3229
 3230
 3231
 3232
 3233
 3234
 3235
 3236
 3237
 3238
 3239
 3240
 3241
 3242
 3243
 3244
 3245
 3246
 3247
 3248
 3249
 3250
 3251
 3252
 3253
 3254
 3255
 3256
 3257
 3258
 3259
 3260
 3261
 3262
 3263
 3264
 3265
 3266
 3267
 3268
 3269
 3270
 3271
 3272
 3273
 3274
 3275
 3276
 3277
 3278
 3279
 3280
 3281
 3282
 3283
 3284
 3285
 3286
 3287
 3288
 3289
 3290
 3291
 3292
 3293
 3294
 3295
 3296
 3297
 3298
 3299
 3300
 3301
 3302
 3303
 3304
 3305
 3306
 3307
 3308
 3309
 3310
 3311
 3312
 3313
 3314
 3315
 3316
 3317
 3318
 3319
 3320
 3321
 3322
 3323
 3324
 3325
 3326
 3327
 3328
 3329
 3330
 3331
 3332
 3333
 3334
 3335
 3336
 3337
 3338
 3339
 3340
 3341
 3342
 3343
 3344
 3345
 3346
 3347
 3348
 3349
 3350
 3351
 3352
 3353
 3354
 3355
 3356
 3357
 3358
 3359
 3360
 3361
 3362
 3363
 3364
 3365
 3366
 3367
 3368
 3369
 3370
 3371
 3372
 3373
 3374
 3375
 3376
 3377
 3378
 3379
 3380
 3381
 3382
 3383
 3384
 3385
 3386
 3387
 3388
 3389
 3390
 3391
 3392
 3393
 3394
 3395
 3396
 3397
 3398
 3399
 3400
 3401
 3402
 3403
 3404
 3405
 3406
 3407
 3408
 3409
 3410
 3411
 3412
 3413
 3414
 3415
 3416
 3417
 3418
 3419
 3420
 3421
 3422
 3423
 3424
 3425
 3426
 3427
 3428
 3429
 3430
 3431
 3432
 3433
 3434
 3435
 3436
 3437
 3438
 3439
 3440
 3441
 3442
 3443
 3444
 3445
 3446
 3447
 3448
 3449
 3450
 3451
 3452
 3453
 3454
 3455
 3456
 3457
 3458
 3459
 3460
 3461
 3462
 3463
 3464
 3465
 3466
 3467
 3468
 3469
 3470
 3471
 3472
 3473
 3474
 3475
 3476
 3477
 3478
 3479
 3480
 3481
 3482
 3483
 3484
 3485
 3486
 3487
 3488
 3489
 3490
 3491
 3492
 3493
 3494
 3495
 3496
 3497
 3498
 3499
 3500
 3501
 3502
 3503
 3504
 3505
 3506
 3507
 3508
 3509
 3510
 3511
 3512
 3513
 3514
 3515
 3516
 3517
 3518
 3519
 3520
 3521
 3522
 3523
 3524
 3525
 3526
 3527
 3528
 3529
 3530
 3531
 3532
 3533
 3534
 3535
 3536
 3537
 3538
 3539
 3540
 3541
 3542
 3543
 3544
 3545
 3546
 3547
 3548
 3549
 3550
 3551
 3552
 3553
 3554
 3555
 3556
 3557
 3558
 3559
 3560
 3561
 3562
 3563
 3564
 3565
 3566
 3567
 3568
 3569
 3570
 3571
 3572
 3573
 3574
 3575
 3576
 3577
 3578
 3579
 3580
 3581
 3582
 3583
 3584
 3585
 3586
 3587
 3588
 3589
 3590
 3591
 3592
 3593
 3594
 3595
 3596
 3597
 3598
 3599
 3600
 3601
 3602
 3603
 3604
 3605
 3606
 3607
 3608
 3609
 3610
 3611
 3612
 3613
 3614
 3615
 3616
 3617
 3618
 3619
 3620
 3621
 3622
 3623
 3624
 3625
 3626
 3627
 3628
 3629
 3630
 3631
 3632
 3633
 3634
 3635
 3636
 3637
 3638
 3639
 3640
 3641
 3642
 3643
 3644
 3645
 3646
 3647
 3648
 3649
 3650
 3651
 3652
 3653
 3654
 3655
 3656
 3657
 3658
 3659
 3660
 3661
 3662
 3663
 3664
 3665
 3666
 3667
 3668
 3669
 3670
 3671
 3672
 3673
 3674
 3675
 3676
 3677
 3678
 3679
 3680
 3681
 3682
 3683
 3684
 3685
 3686
 3687
 3688
 3689
 3690
 3691
 3692
 3693
 3694
 3695
 3696
 3697
 3698
 3699
 3700
 3701
 3702
 3703
 3704
 3705
 3706
 3707
 3708
 3709
 3710
 3711
 3712
 3713
 3714
 3715
 3716
 3717
 3718
 3719
 3720
 3721
 3722
 3723
 3724
 3725
 3726
 3727
 3728
 3729
 3730
 3731
 3732
 3733
 3734
 3735
 3736
 3737
 3738
 3739
 3740
 3741
 3742
 3743
 3744
 3745
 3746
 3747
 3748
 3749
 3750
 3751
 3752
 3753
 3754
 3755
 3756
 3757
 3758
 3759
 3760
 3761
 3762
 3763
 3764
 3765
 3766
 3767
 3768
 3769
 3770
 3771
 3772
 3773
 3774
 3775
 3776
 3777
 3778
 3779
 3780
 3781
 3782
 3783
 3784
 3785
 3786
 3787
 3788
 3789
 3790
 3791
 3792
 3793
 3794
 3795
 3796
 3797
 3798
 3799
 3800
 3801
 3802
 3803
 3804
 3805
 3806
 3807
 3808
 3809
 3810
 3811
 3812
 3813
 3814
 3815
 3816
 3817
 3818
 3819
 3820
 3821
 3822
 3823
 3824
 3825
 3826
 3827
 3828
 3829
 3830
 3831
 3832
 3833
 3834
 3835
 3836
 3837
 3838
 3839
 3840
 3841
 3842
 3843
 3844
 3845
 3846
 3847
 3848
 3849
 3850
 3851
 3852
 3853
 3854
 3855
 3856
 3857
 3858
 3859
 3860
 3861
 3862
 3863
 3864
 3865
 3866
 3867
 3868
 3869
 3870
 3871
 3872
 3873
 3874
 3875
 3876
 3877
 3878
 3879
 3880
 3881
 3882
 3883
 3884
 3885
 3886
 3887
 3888
 3889
 3890
 3891
 3892
 3893
 3894
 3895
 3896
 3897
 3898
 3899
 3900
 3901
 3902
 3903
 3904
 3905
 3906
 3907
 3908
 3909
 3910
 3911
 3912
 3913
 3914
 3915
 3916
 3917
 3918
 3919
 3920
 3921
 3922
 3923
 3924
 3925
 3926
 3927
 3928
 3929
 3930
 3931
 3932
 3933
 3934
 3935
 3936
 3937
 3938
 3939
 3940
 3941
 3942
 3943
 3944
 3945
 3946
 3947
 3948
 3949
 3950
 3951
 3952
 3953
 3954
 3955
 3956
 3957
 3958
 3959
 3960
 3961
 3962
 3963
 3964
 3965
 3966
 3967
 3968
 3969
 3970
 3971
 3972
 3973
 3974
 3975
 3976
 3977
 3978
 3979
 3980
 3981
 3982
 3983
 3984
 3985
 3986
 3987
 3988
 3989
 3990
 3991
 3992
 3993
 3994
 3995
 3996
 3997
 3998
 3999
 4000
 4001
 4002
 4003
 4004
 4005
 4006
 4007
 4008
 4009
 4010
 4011
 4012
 4013
 4014
 4015
 4016
 4017
 4018
 4019
 4020
 4021
 4022
 4023
 4024
 4025
 4026
 4027
 4028
 4029
 4030
 4031
 4032
 4033
 4034
 4035
 4036
 4037
 4038
 4039
 4040
 4041
 4042
 4043
 4044
 4045
 4046
 4047
 4048
 4049
 4050
 4051
 4052
 4053
 4054
 4055
 4056
 4057
 4058
 4059
 4060
 4061
 4062
 4063
 4064
 4065
 4066
 4067
 4068
 4069
 4070
 4071
 4072
 4073
 4074
 4075
 4076
 4077
 4078
 4079
 4080
 4081
 4082
 4083
 4084
 4085
 4086
 4087
 4088
 4089
 4090
 4091
 4092
 4093
 4094
 4095
 4096
 4097
 4098
 4099
 4100
 4101
 4102
 4103
 4104
 4105
 4106
 4107
 4108
 4109
 4110
 4111
 4112
 4113
 4114
 4115
 4116
 4117
 4118
 4119
 4120
 4121
 4122
 4123
 4124
 4125
 4126
 4127
 4128
 4129
 4130
 4131
 4132
 4133
 4134
 4135
 4136
 4137
 4138
 4139
 4140
 4141
 4142
 4143
 4144
 4145
 4146
 4147
 4148
 4149
 4150
 4151
 4152
 4153
 4154
 4155
 4156
 4157
 4158
 4159
 4160
 4161
 4162
 4163
 4164
 4165
 4166
 4167
 4168
 4169
 4170
 4171
 4172
 4173
 4174
 4175
 4176
 4177
 4178
 4179
 4180
 4181
 4182
 4183
 4184
 4185
 4186
 4187
 4188
 4189
 4190
 4191
 4192
 4193
 4194
 4195
 4196
 4197
 4198
 4199
 4200
 4201
 4202
 4203
 4204
 4205
 4206
 4207
 4208
 4209
 4210
 4211
 4212
 4213
 4214
 4215
 4216
 4217
 4218
 4219
 4220
 4221
 4222
 4223
 4224
 4225
 4226
 4227
 4228
 4229
 4230
 4231
 4232
 4233
 4234
 4235
 4236
 4237
 4238
 4239
 4240
 4241
 4242
 4243
 4244
 4245
 4246
 4247
 4248
 4249
 4250
 4251
 4252
 4253
 4254
 4255
 4256
 4257
 4258
 4259
 4260
 4261
 4262
 4263
 4264
 4265
 4266
 4267
 4268
 4269
 4270
 4271
 4272
 4273
 4274
 4275
 4276
 4277
 4278
 4279
 4280
 4281
 4282
 4283
 4284
 4285
 4286
 4287
 4288
 4289
 4290
 4291
 4292
 4293
 4294
 4295
 4296
 4297
 4298
 4299
 4300
 4301
 4302
 4303
 4304
 4305
 4306
 4307
 4308
 4309
 4310
 4311
 4312
 4313
 4314
 4315
 4316
 4317
 4318
 4319
 4320
 4321
 4322
 4323
 4324
 4325
 4326
 4327
 4328
 4329
 4330
 4331
 4332
 4333
 4334
 4335
 4336
 4337
 4338
 4339
 4340
 4341
 4342
 4343
 4344
 4345
 4346
 4347
 4348
 4349
 4350
 4351
 4352
 4353
 4354
 4355
 4356
 4357
 4358
 4359
 4360
 4361
 4362
 4363
 4364
 4365
 4366
 4367
 4368
 4369
 4370
 4371
 4372
 4373
 4374
 4375
 4376
 4377
 4378
 4379
 4380
 4381
 4382
 4383
 4384
 4385
 4386
 4387
 4388
 4389
 4390
 4391
 4392
 4393
 4394
 4395
 4396
 4397
 4398
 4399
 4400
 4401
 4402
 4403
 4404
 4405
 4406
 4407
 4408
 4409
 4410
 4411
 4412
 4413
 4414
 4415
 4416
 4417
 4418
 4419
 4420
 4421
 4422
 4423
 4424
 4425
 4426
 4427
 4428
 4429
 4430
 4431
 4432
 4433
 4434
 4435
 4436
 4437
 4438
 4439
 4440
 4441
 4442
 4443
 4444
 4445
 4446
 4447
 4448
 4449
 4450
 4451
 4452
 4453
 4454
 4455
 4456
 4457
 4458
 4459
 4460
 4461
 4462
 4463
 4464
 4465
 4466
 4467
 4468
 4469
 4470
 4471
 4472
 4473
 4474
 4475
 4476
 4477
 4478
 4479
 4480
 4481
 4482
 4483
 4484
 4485
 4486
 4487
 4488
 4489
 4490
 4491
 4492
 4493
 4494
 4495
 4496
 4497
 4498
 4499
 4500
 4501
 4502
 4503
 4504
 4505
 4506
 4507
 4508
 4509
 4510
 4511
 4512
 4513
 4514
 4515
 4516
 4517
 4518
 4519
 4520
 4521
 4522
 4523
 4524
 4525
 4526
 4527
 4528
 4529
 4530
 4531
 4532
 4533
 4534
 4535
 4536
 4537
 4538
 4539
 4540
 4541
 4542
 4543
 4544
 4545
 4546
 4547
 4548
 4549
 4550
 4551
 4552
 4553
 4554
 4555
 4556
 4557
 4558
 4559
 4560
 4561
 4562
 4563
 4564
 4565
 4566
 4567
 4568
 4569
 4570
 4571
 4572
 4573
 4574
 4575
 4576
 4577
 4578
 4579
 4580
 4581
 4582
 4583
 4584
 4585
 4586
 4587
 4588
 4589
 4590
 4591
 4592
 4593
 4594
 4595
 4596
 4597
 4598
 4599
 4600
 4601
 4602
 4603
 4604
 4605
 4606
 4607
 4608
 4609
 4610
 4611
 4612
 4613
 4614
 4615
 4616
 4617
 4618
 4619
 4620
 4621
 4622
 4623
 4624
 4625
 4626
 4627
 4628
 4629
 4630
 4631
 4632
 4633
 4634
 4635
 4636
 4637
 4638
 4639
 4640
 4641
 4642
 4643
 4644
 4645
 4646
 4647
 4648
 4649
 4650
 4651
 4652
 4653
 4654
 4655
 4656
 4657
 4658
 4659
 4660
 4661
 4662
 4663
 4664
 4665
 4666
 4667
 4668
 4669
 4670
 4671
 4672
 4673
 4674
 4675
 4676
 4677
 4678
 4679
 4680
 4681
 4682
 4683
 4684
 4685
 4686
 4687
 4688
 4689
 4690
 4691
 4692
 4693
 4694
 4695
 4696
 4697
 4698
 4699
 4700
 4701
 4702
 4703
 4704
 4705
 4706
 4707
 4708
 4709
 4710
 4711
 4712
 4713
 4714
 4715
 4716
 4717
 4718
 4719
 4720
 4721
 4722
 4723
 4724
 4725
 4726
 4727
 4728
 4729
 4730
 4731
 4732
 4733
 4734
 4735
 4736
 4737
 4738
 4739
 4740
 4741
 4742
 4743
 4744
 4745
 4746
 4747
 4748
 4749
 4750
 4751
 4752
 4753
 4754
 4755
 4756
 4757
 4758
 4759
 4760
 4761
 4762
 4763
 4764
 4765
 4766
 4767
 4768
 4769
 4770
 4771
 4772
 4773
 4774
 4775
 4776
 4777
 4778
 4779
 4780
 4781
 4782
 4783
 4784
 4785
 4786
 4787
 4788
 4789
 4790
 4791
 4792
 4793
 4794
 4795
 4796
 4797
 4798
 4799
 4800
 4801
 4802
 4803
 4804
 4805
 4806
 4807
 4808
 4809
 4810
 4811
 4812
 4813
 4814
 4815
 4816
 4817
 4818
 4819
 4820
 4821
 4822
 4823
 4824
 4825
 4826
 4827
 4828
 4829
 4830
 4831
 4832
 4833
 4834
 4835
 4836
 4837
 4838
 4839
 4840
 4841
 4842
 4843
 4844
 4845
 4846
 4847
 4848
 4849
 4850
 4851
 4852
 4853
 4854
 4855
 4856
 4857
 4858
 4859
 4860
 4861
 4862
 4863
 4864
 4865
 4866
 4867
 4868
 4869
 4870
 4871
 4872
 4873
 4874
 4875
 4876
 4877
 4878
 4879
 4880
 4881
 4882
 4883
 4884
 4885
 4886
 4887
 4888
 4889
 4890
 4891
 4892
 4893
 4894
 4895
 4896
 4897
 4898
 4899
 4900
 4901
 4902
 4903
 4904
 4905
 4906
 4907
 4908
 4909
 4910
 4911
 4912
 4913
 4914
 4915
 4916
 4917
 4918
 4919
 4920
 4921
 4922
 4923
 4924
 4925
 4926
 4927
 4928
 4929
 4930
 4931
 4932
 4933
 4934
 4935
 4936
 4937
 4938
 4939
 4940
 4941
 4942
 4943
 4944
 4945
 4946
 4947
 4948
 4949
 4950
 4951
 4952
 4953
 4954
 4955
 4956
 4957
 4958
 4959
 4960
 4961
 4962
 4963
 4964
 4965
 4966
 4967
 4968
 4969
 4970
 4971
 4972
 4973
 4974
 4975
 4976
 4977
 4978
 4979
 4980
 4981
 4982
 4983
 4984
 4985
 4986
 4987
 4988
 4989
 4990
 4991
 4992
 4993
 4994
 4995
 4996
 4997
 4998
 4999
 5000
 5001
 5002
 5003
 5004
 5005
 5006
 5007
 5008
 5009
 5010
 5011
 5012
 5013
 5014
 5015
 5016
 5017
 5018
 5019
 5020
 5021
 5022
 5023
 5024
 5025
 5026
 5027
 5028
 5029
 5030
 5031
 5032
 5033
 5034
 5035
 5036
 5037
 5038
 5039
 5040
 5041
 5042
 5043
 5044
 5045
 5046
 5047
 5048
 5049
 5050
 5051
 5052
 5053
 5054
 5055
 5056
 5057
 5058
 5059
 5060
 5061
 5062
 5063
 5064
 5065
 5066
 5067
 5068
 5069
 5070
 5071
 5072
 5073
 5074
 5075
 5076
 5077
 5078
 5079
 5080
 5081
 5082
 5083
 5084
 5085
 5086
 5087
 5088
 5089
 5090
 5091
 5092
 5093
 5094
 5095
 5096
 5097
 5098
 5099
 5100
 5101
 5102
 5103
 5104
 5105
 5106
 5107
 5108
 5109
 5110
 5111
 5112
 5113
 5114
 5115
 5116
 5117
 5118
 5119
 5120
 5121
 5122
 5123
 5124
 5125
 5126
 5127
 5128
 5129
 5130
 5131
 5132
 5133
 5134
 5135
 5136
 5137
 5138
 5139
 5140
 5141
 5142
 5143
 5144
 5145
 5146
 5147
 5148
 5149
 5150
 5151
 5152
 5153
 5154
 5155
 5156
 5157
 5158
 5159
 5160
 5161
 5162
 5163
 5164
 5165
 5166
 5167
 5168
 5169
 5170
 5171
 5172
 5173
 5174
 5175
 5176
 5177
 5178
 5179
 5180
 5181
 5182
 5183
 5184
 5185
 5186
 5187
 5188
 5189
 5190
 5191
 5192
 5193
 5194
 5195
 5196
 5197
 5198
 5199
 5200
 5201
 5202
 5203
 5204
 5205
 5206
 5207
 5208
 5209
 5210
 5211
 5212
 5213
 5214
 5215
 5216
 5217
 5218
 5219
 5220
 5221
 5222
 5223
 5224
 5225
 5226
 5227
 5228
 5229
 5230
 5231
 5232
 5233
 5234
 5235
 5236
 5237
 5238
 5239
 5240
 5241
 5242
 5243
 5244
 5245
 5246
 5247
 5248
 5249
 5250
 5251
 5252
 5253
 5254
 5255
 5256
 5257
 5258
 5259
 5260
 5261
 5262
 5263
 5264
 5265
 5266
 5267
 5268
 5269
 5270
 5271
 5272
 5273
 5274
 5275
 5276
 5277
 5278
 5279
 5280
 5281
 5282
 5283
 5284
 5285
 5286
 5287
 5288
 5289
 5290
 5291
 5292
 5293
 5294
 5295
 5296
 5297
 5298
 5299
 5300
 5301
 5302
 5303
 5304
 5305
 5306
 5307
 5308
 5309
 5310
 5311
 5312
 5313
 5314
 5315
 5316
 5317
 5318
 5319
 5320
 5321
 5322
 5323
 5324
 5325
 5326
 5327
 5328
 5329
 5330
 5331
 5332
 5333
 5334
 5335
 5336
 5337
 5338
 5339
 5340
 5341
 5342
 5343
 5344
 5345
 5346
 5347
 5348
 5349
 5350
 5351
 5352
 5353
 5354
 5355
 5356
 5357
 5358
 5359
 5360
 5361
 5362
 5363
 5364
 5365
 5366
 5367
 5368
 5369
 5370
 5371
 5372
 5373
 5374
 5375
 5376
 5377
 5378
 5379
 5380
 5381
 5382
 5383
 5384
 5385
 5386
 5387
 5388
 5389
 5390
 5391
 5392
 5393
 5394
 5395
 5396
 5397
 5398
 5399
 5400
 5401
 5402
 5403
 5404
 5405
 5406
 5407
 5408
 5409
 5410
 5411
 5412
 5413
 5414
 5415
 5416
 5417
 5418
 5419
 5420
 5421
 5422
 5423
 5424
 5425
 5426
 5427
 5428
 5429
 5430
 5431
 5432
 5433
 5434
 5435
 5436
 5437
 5438
 5439
 5440
 5441
 5442
 5443
 5444
 5445
 5446
 5447
 5448
 5449
 5450
 5451
 5452
 5453
 5454
 5455
 5456
 5457
 5458
 5459
 5460
 5461
 5462
 5463
 5464
 5465
 5466
 5467
 5468
 5469
 5470
 5471
 5472
 5473
 5474
 5475
 5476
 5477
 5478
 5479
 5480
 5481
 5482
 5483
 5484
 5485
 5486
 5487
 5488
 5489
 5490
 5491
 5492
 5493
 5494
 5495
 5496
 5497
 5498
 5499
 5500
 5501
 5502
 5503
 5504
 5505
 5506
 5507
 5508
 5509
 5510
 5511
 5512
 5513
 5514
 5515
 5516
 5517
 5518
 5519
 5520
 5521
 5522
 5523
 5524
 5525
 5526
 5527
 5528
 5529
 5530
 5531
 5532
 5533
 5534
 5535
 5536
 5537
 5538
 5539
 5540
 5541
 5542
 5543
 5544
 5545
 5546
 5547
 5548
 5549
 5550
 5551
 5552
 5553
 5554
 5555
 5556
 5557
 5558
 5559
 5560
 5561
 5562
 5563
 5564
 5565
 5566
 5567
 5568
 5569
 5570
 5571
 5572
 5573
 5574
 5575
 5576
 5577
 5578
 5579
 5580
 5581
 5582
 5583
 5584
 5585
 5586
 5587
 5588
 5589
 5590
 5591
 5592
 5593
 5594
 5595
 5596
 5597
 5598
 5599
 5600
 5601
 5602
 5603
 5604
 5605
 5606
 5607
 5608
 5609
 5610
 5611
 5612
 5613
 5614
 5615
 5616
 5617
 5618
 5619
 5620
 5621
 5622
 5623
 5624
 5625
 5626
 5627
 5628
 5629
 5630
 5631
 5632
 5633
 5634
 5635
 5636
 5637
 5638
 5639
 5640
 5641
 5642
 5643
 5644
 5645
 5646
 5647
 5648
 5649
 5650
 5651
 5652
 5653
 5654
 5655
 5656
 5657
 5658
 5659
 5660
 5661
 5662
 5663
 5664
 5665
 5666
 5667
 5668
 5669
 5670
 5671
 5672
 5673
 5674
 5675
 5676
 5677
 5678
 5679
 5680
 5681
 5682
 5683
 5684
 5685
 5686
 5687
 5688
 5689
 5690
 5691
 5692
 5693
 5694
 5695
 5696
 5697
 5698
 5699
 5700
 5701
 5702
 5703
 5704
 5705
 5706
 5707
 5708
 5709
 5710
 5711
 5712
 5713
 5714
 5715
 5716
 5717
 5718
 5719
 5720
 5721
 5722
 5723
 5724
 5725
 5726
 5727
 5728
 5729
 5730
 5731
 5732
 5733
 5734
 5735
 5736
 5737
 5738
 5739
 5740
 5741
 5742
 5743
 5744
 5745
 5746
 5747
 5748
 5749
 5750
 5751
 5752
 5753
 5754
 5755
 5756
 5757
 5758
 5759
 5760
 5761
 5762
 5763
 5764
 5765
 5766
 5767
 5768
 5769
 5770
 5771
 5772
 5773
 5774
 5775
 5776
 5777
 5778
 5779
 5780
 5781
 5782
 5783
 5784
 5785
 5786
 5787
 5788
 5789
 5790
 5791
 5792
 5793
 5794
 5795
 5796
 5797
 5798
 5799
 5800
 5801
 5802
 5803
 5804
 5805
 5806
 5807
 5808
 5809
 5810
 5811
 5812
 5813
 5814
 5815
 5816
 5817
 5818
 5819
 5820
 5821
 5822
 5823
 5824
 5825
 5826
 5827
 5828
 5829
 5830
 5831
 5832
 5833
 5834
 5835
 5836
 5837
 5838
 5839
 5840
 5841
 5842
 5843
 5844
 5845
 5846
 5847
 5848
 5849
 5850
 5851
 5852
 5853
 5854
 5855
 5856
 5857
 5858
 5859
 5860
 5861
 5862
 5863
 5864
 5865
 5866
 5867
 5868
 5869
 5870
 5871
 5872
 5873
 5874
 5875
 5876
 5877
 5878
 5879
 5880
 5881
 5882
 5883
 5884
 5885
 5886
 5887
 5888
 5889
 5890
 5891
 5892
 5893
 5894
 5895
 5896
 5897
 5898
 5899
 5900
 5901
 5902
 5903
 5904
 5905
 5906
 5907
 5908
 5909
 5910
 5911
 5912
 5913
 5914
 5915
 5916
 5917
 5918
 5919
 5920
 5921
 5922
 5923
 5924
 5925
 5926
 5927
 5928
 5929
 5930
 5931
 5932
 5933
 5934
 5935
 5936
 5937
 5938
 5939
 5940
 5941
 5942
 5943
 5944
 5945
 5946
 5947
 5948
 5949
 5950
 5951
 5952
 5953
 5954
 5955
 5956
 5957
 5958
 5959
 5960
 5961
 5962
 5963
 5964
 5965
 5966
 5967
 5968
 5969
 5970
 5971
 5972
 5973
 5974
 5975
 5976
 5977
 5978
 5979
 5980
 5981
 5982
 5983
 5984
 5985
 5986
 5987
 5988
 5989
 5990
 5991
 5992
 5993
 5994
 5995
 5996
 5997
 5998
 5999
 6000
 6001
 6002
 6003
 6004
 6005
 6006
 6007
 6008
 6009
 6010
 6011
 6012
 6013
 6014
 6015
 6016
 6017
 6018
 6019
 6020
 6021
 6022
 6023
 6024
 6025
 6026
 6027
 6028
 6029
 6030
 6031
 6032
 6033
 6034
 6035
 6036
 6037
 6038
 6039
 6040
 6041
 6042
 6043
 6044
 6045
 6046
 6047
 6048
 6049
 6050
 6051
 6052
 6053
 6054
 6055
 6056
 6057
 6058
 6059
 6060
 6061
 6062
 6063
 6064
 6065
 6066
 6067
 6068
 6069
 6070
 6071
 6072
 6073
 6074
 6075
 6076
 6077
 6078
 6079
 6080
 6081
 6082
 6083
 6084
 6085
 6086
 6087
 6088
 6089
 6090
 6091
 6092
 6093
 6094
 6095
 6096
 6097
 6098
 6099
 6100
 6101
 6102
 6103
 6104
 6105
 6106
 6107
 6108
 6109
 6110
 6111
 6112
 6113
 6114
 6115
 6116
 6117
 6118
 6119
 6120
 6121
 6122
 6123
 6124
 6125
 6126
 6127
 6128
 6129
 6130
 6131
 6132
 6133
 6134
 6135
 6136
 6137
 6138
 6139
 6140
 6141
 6142
 6143
 6144
 6145
 6146
 6147
 6148
 6149
 6150
 6151
 6152
 6153
 6154
 6155
 6156
 6157
 6158
 6159
 6160
 6161
 6162
 6163
 6164
 6165
 6166
 6167
 6168
 6169
 6170
 6171
 6172
 6173
 6174
 6175
 6176
 6177
 6178
 6179
 6180
 6181
 6182
 6183
 6184
 6185
 6186
 6187
 6188
 6189
 6190
 6191
 6192
 6193
 6194
 6195
 6196
 6197
 6198
 6199
 6200
 6201
 6202
 6203
 6204
 6205
 6206
 6207
 6208
 6209
 6210
 6211
 6212
 6213
 6214
 6215
 6216
 6217
 6218
 6219
 6220
 6221
 6222
 6223
 6224
 6225
 6226
 6227
 6228
 6229
 6230
 6231
 6232
 6233
 6234
 6235
 6236
 6237
 6238
 6239
 6240
 6241
 6242
 6243
 6244
 6245
 6246
 6247
 6248
 6249
 6250
 6251
 6252
 6253
 6254
 6255
 6256
 6257
 6258
 6259
 6260
 6261
 6262
 6263
 6264
 6265
 6266
 6267
 6268
 6269
 6270
 6271
 6272
 6273
 6274
 6275
 6276
 6277
 6278
 6279
 6280
 6281
 6282
 6283
 6284
 6285
 6286
 6287
 6288
 6289
 6290
 6291
 6292
 6293
 6294
 6295
 6296
 6297
 6298
 6299
 6300
 6301
 6302
 6303
 6304
 6305
 6306
 6307
 6308
 6309
 6310
 6311
 6312
 6313
 6314
 6315
 6316
 6317
 6318
 6319
 6320
 6321
 6322
 6323
 6324
 6325
 6326
 6327
 6328
 6329
 6330
 6331
 6332
 6333
 6334
 6335
 6336
 6337
 6338
 6339
 6340
 6341
 6342
 6343
 6344
 6345
 6346
 6347
 6348
 6349
 6350
 6351
 6352
 6353
 6354
 6355
 6356
 6357
 6358
 6359
 6360
 6361
 6362
 6363
 6364
 6365
 6366
 6367
 6368
 6369
 6370
 6371
 6372
 6373
 6374
 6375
 6376
 6377
 6378
 6379
 6380
 6381
 6382
 6383
 6384
 6385
 6386
 6387
 6388
 6389
 6390
 6391
 6392
 6393
 6394
 6395
 6396
 6397
 6398
 6399
 6400
 6401
 6402
 6403
 6404
 6405
 6406
 6407
 6408
 6409
 6410
 6411
 6412
 6413
 6414
 6415
 6416
 6417
 6418
 6419
 6420
 6421
 6422
 6423
 6424
 6425
 6426
 6427
 6428
 6429
 6430
 6431
 6432
 6433
 6434
 6435
 6436
 6437
 6438
 6439
 6440
 6441
 6442
 6443
 6444
 6445
 6446
 6447
 6448
 6449
 6450
 6451
 6452
 6453
 6454
 6455
 6456
 6457
 6458
 6459
 6460
 6461
 6462
 6463
 6464
 6465
 6466
 6467
 6468
 6469
 6470
 6471
 6472
 6473
 6474
 6475
 6476
 6477
 6478
 6479
 6480
 6481
 6482
 6483
 6484
 6485
 6486
 6487
 6488
 6489
 6490
 6491
 6492
 6493
 6494
 6495
 6496
 6497
 6498
 6499
 6500
 6501
 6502
 6503
 6504
 6505
 6506
 6507
 6508
 6509
 6510
 6511
 6512
 6513
 6514
 6515
 6516
 6517
 6518
 6519
 6520
 6521
 6522
 6523
 6524
 6525
 6526
 6527
 6528
 6529
 6530
 6531
 6532
 6533
 6534
 6535
 6536
 6537
 6538
 6539
 6540
 6541
 6542
 6543
 6544
 6545
 6546
 6547
 6548
 6549
 6550
 6551
 6552
 6553
 6554
 6555
 6556
 6557
 6558
 6559
 6560
 6561
 6562
 6563
 6564
 6565
 6566
 6567
 6568
 6569
 6570
 6571
 6572
 6573
 6574
 6575
 6576
 6577
 6578
 6579
 6580
 6581
 6582
 6583
 6584
 6585
 6586
 6587
 6588
 6589
 6590
 6591
 6592
 6593
 6594
 6595
 6596
 6597
 6598
 6599
 6600
 6601
 6602
 6603
 6604
 6605
 6606
 6607
 6608
 6609
 6610
 6611
 6612
 6613
 6614
 6615
 6616
 6617
 6618
 6619
 6620
 6621
 6622
 6623
 6624
 6625
 6626
 6627
 6628
 6629
 6630
 6631
 6632
 6633
 6634
 6635
 6636
 6637
 6638
 6639
 6640
 6641
 6642
 6643
 6644
 6645
 6646
 6647
 6648
 6649
 6650
 6651
 6652
 6653
 6654
 6655
 6656
 6657
 6658
 6659
 6660
 6661
 6662
 6663
 6664
 6665
 6666
 6667
 6668
 6669
 6670
 6671
 6672
 6673
 6674
 6675
 6676
 6677
 6678
 6679
 6680
 6681
 6682
 6683
 6684
 6685
 6686
 6687
 6688
 6689
 6690
 6691
 6692
 6693
 6694
 6695
 6696
 6697
 6698
 6699
 6700
 6701
 6702
 6703
 6704
 6705
 6706
 6707
 6708
 6709
 6710
 6711
 6712
 6713
 6714
 6715
 6716
 6717
 6718
 6719
 6720
 6721
 6722
 6723
 6724
 6725
 6726
 6727
 6728
 6729
 6730
 6731
 6732
 6733
 6734
 6735
 6736
 6737
 6738
 6739
 6740
 6741
 6742
 6743
 6744
 6745
 6746
 6747
 6748
 6749
 6750
 6751
 6752
 6753
 6754
 6755
 6756
 6757
 6758
 6759
 6760
 6761
 6762
 6763
 6764
 6765
 6766
 6767
 6768
 6769
 6770
 6771
 6772
 6773
 6774
 6775
 6776
 6777
 6778
 6779
 6780
 6781
 6782
 6783
 6784
 6785
 6786
 6787
 6788
 6789
 6790
 6791
 6792
 6793
 6794
 6795
 6796
 6797
 6798
 6799
 6800
 6801
 6802
 6803
 6804
 6805
 6806
 6807
 6808
 6809
 6810
 6811
 6812
 6813
 6814
 6815
 6816
 6817
 6818
 6819
 6820
 6821
 6822
 6823
 6824
 6825
 6826
 6827
 6828
 6829
 6830
 6831
 6832
 6833
 6834
 6835
 6836
 6837
 6838
 6839
 6840
 6841
 6842
 6843
 6844
 6845
 6846
 6847
 6848
 6849
 6850
 6851
 6852
 6853
 6854
 6855
 6856
 6857
 6858
 6859
 6860
 6861
 6862
 6863
 6864
 6865
 6866
 6867
 6868
 6869
 6870
 6871
 6872
 6873
 6874
 6875
 6876
 6877
 6878
 6879
 6880
 6881
 6882
 6883
 6884
 6885
 6886
 6887
 6888
 6889
 6890
 6891
 6892
 6893
 6894
 6895
 6896
 6897
 6898
 6899
 6900
 6901
 6902
 6903
 6904
 6905
 6906
 6907
 6908
 6909
 6910
 6911
 6912
 6913
 6914
 6915
 6916
 6917
 6918
 6919
 6920
 6921
 6922
 6923
 6924
 6925
 6926
 6927
 6928
 6929
 6930
 6931
 6932
 6933
 6934
 6935
 6936
 6937
 6938
 6939
 6940
 6941
 6942
 6943
 6944
 6945
 6946
 6947
 6948
 6949
 6950
 6951
 6952
 6953
 6954
 6955
 6956
 6957
 6958
 6959
 6960
 6961
 6962
 6963
 6964
 6965
 6966
 6967
 6968
 6969
 6970
 6971
 6972
 6973
 6974
 6975
 6976
 6977
 6978
 6979
 6980
 6981
 6982
 6983
 6984
 6985
 6986
 6987
 6988
 6989
 6990
 6991
 6992
 6993
 6994
 6995
 6996
 6997
 6998
 6999
 7000
 7001
 7002
 7003
 7004
 7005
 7006
 7007
 7008
 7009
 7010
 7011
 7012
 7013
 7014
 7015
 7016
 7017
 7018
 7019
 7020
 7021
 7022
 7023
 7024
 7025
 7026
 7027
 7028
 7029
 7030
 7031
 7032
 7033
 7034
 7035
 7036
 7037
 7038
 7039
 7040
 7041
 7042
 7043
 7044
 7045
 7046
 7047
 7048
 7049
 7050
 7051
 7052
 7053
 7054
 7055
 7056
 7057
 7058
 7059
 7060
 7061
 7062
 7063
 7064
 7065
 7066
 7067
 7068
 7069
 7070
 7071
 7072
 7073
 7074
 7075
 7076
 7077
 7078
 7079
 7080
 7081
 7082
 7083
 7084
 7085
 7086
 7087
 7088
 7089
 7090
 7091
 7092
 7093
 7094
 7095
 7096
 7097
 7098
 7099
 7100
 7101
 7102
 7103
 7104
 7105
 7106
 7107
 7108
 7109
 7110
 7111
 7112
 7113
 7114
 7115
 7116
 7117
 7118
 7119
 7120
 7121
 7122
 7123
 7124
 7125
 7126
 7127
 7128
 7129
 7130
 7131
 7132
 7133
 7134
 7135
 7136
 7137
 7138
 7139
 7140
 7141
 7142
 7143
 7144
 7145
 7146
 7147
 7148
 7149
 7150
 7151
 7152
 7153
 7154
 7155
 7156
 7157
 7158
 7159
 7160
 7161
 7162
 7163
 7164
 7165
 7166
 7167
 7168
 7169
 7170
 7171
 7172
 7173
 7174
 7175
 7176
 7177
 7178
 7179
 7180
 7181
 7182
 7183
 7184
 7185
 7186
 7187
 7188
 7189
 7190
 7191
 7192
 7193
 7194
 7195
 7196
 7197
 7198
 7199
 7200
 7201
 7202
 7203
 7204
 7205
 7206
 7207
 7208
 7209
 7210
 7211
 7212
 7213
 7214
 7215
 7216
 7217
 7218
 7219
 7220
 7221
 7222
 7223
 7224
 7225
 7226
 7227
 7228
 7229
 7230
 7231
 7232
 7233
 7234
 7235
 7236
 7237
 7238
 7239
 7240
 7241
 7242
 7243
 7244
 7245
 7246
 7247
 7248
 7249
 7250
 7251
 7252
 7253
 7254
 7255
 7256
 7257
 7258
 7259
 7260
 7261
 7262
 7263
 7264
 7265
 7266
 7267
 7268
 7269
 7270
 7271
 7272
 7273
 7274
 7275
 7276
 7277
 7278
 7279
 7280
 7281
 7282
 7283
 7284
 7285
 7286
 7287
 7288
 7289
 7290
 7291
 7292
 7293
 7294
 7295
 7296
 7297
 7298
 7299
 7300
 7301
 7302
 7303
 7304
 7305
 7306
 7307
 7308
 7309
 7310
 7311
 7312
 7313
 7314
 7315
 7316
 7317
 7318
 7319
 7320
 7321
 7322
 7323
 7324
 7325
 7326
 7327
 7328
 7329
 7330
 7331
 7332
 7333
 7334
 7335
 7336
 7337
 7338
 7339
 7340
 7341
 7342
 7343
 7344
 7345
 7346
 7347
 7348
 7349
 7350
 7351
 7352
 7353
 7354
 7355
 7356
 7357
 7358
 7359
 7360
 7361
 7362
 7363
 7364
 7365
 7366
 7367
 7368
 7369
 7370
 7371
 7372
 7373
 7374
 7375
 7376
 7377
 7378
 7379
 7380
 7381
 7382
 7383
 7384
 7385
 7386
 7387
 7388
 7389
 7390
 7391
 7392
 7393
 7394
 7395
 7396
 7397
 7398
 7399
 7400
 7401
 7402
 7403
 7404
 7405
 7406
 7407
 7408
 7409
 7410
 7411
 7412
 7413
 7414
 7415
 7416
 7417
 7418
 7419
 7420
 7421
 7422
 7423
 7424
 7425
 7426
 7427
 7428
 7429
 7430
 7431
 7432
 7433
 7434
 7435
 7436
 7437
 7438
 7439
 7440
 7441
 7442
 7443
 7444
 7445
 7446
 7447
 7448
 7449
 7450
 7451
 7452
 7453
 7454
 7455
 7456
 7457
 7458
 7459
 7460
 7461
 7462
 7463
 7464
 7465
 7466
 7467
 7468
 7469
 7470
 7471
 7472
 7473
 7474
 7475
 7476
 7477
 7478
 7479
 7480
 7481
 7482
 7483
 7484
 7485
 7486
 7487
 7488
 7489
 7490
 7491
 7492
 7493
 7494
 7495
 7496
 7497
 7498
 7499
 7500
 7501
 7502
 7503
 7504
 7505
 7506
 7507
 7508
 7509
 7510
 7511
 7512
 7513
 7514
 7515
 7516
 7517
 7518
 7519
 7520
 7521
 7522
 7523
 7524
 7525
 7526
 7527
 7528
 7529
 7530
 7531
 7532
 7533
 7534
 7535
 7536
 7537
 7538
 7539
 7540
 7541
 7542
 7543
 7544
 7545
 7546
 7547
 7548
 7549
 7550
 7551
 7552
 7553
 7554
 7555
 7556
 7557
 7558
 7559
 7560
 7561
 7562
 7563
 7564
 7565
 7566
 7567
 7568
 7569
 7570
 7571
 7572
 7573
 7574
 7575
 7576
 7577
 7578
 7579
 7580
 7581
 7582
 7583
 7584
 7585
 7586
 7587
 7588
 7589
 7590
 7591
 7592
 7593
 7594
 7595
 7596
 7597
 7598
 7599
 7600
 7601
 7602
 7603
 7604
 7605
 7606
 7607
 7608
 7609
 7610
 7611
 7612
 7613
 7614
 7615
 7616
 7617
 7618
 7619
 7620
 7621
 7622
 7623
 7624
 7625
 7626
 7627
 7628
 7629
 7630
 7631
 7632
 7633
 7634
 7635
 7636
 7637
 7638
 7639
 7640
 7641
 7642
 7643
 7644
 7645
 7646
 7647
 7648
 7649
 7650
 7651
 7652
 7653
 7654
 7655
 7656
 7657
 7658
 7659
 7660
 7661
 7662
 7663
 7664
 7665
 7666
 7667
 7668
 7669
 7670
 7671
 7672
 7673
 7674
 7675
 7676
 7677
 7678
 7679
 7680
 7681
 7682
 7683
 7684
 7685
 7686
 7687
 7688
 7689
 7690
 7691
 7692
 7693
 7694
 7695
 7696
 7697
 7698
 7699
 7700
 7701
 7702
 7703
 7704
 7705
 7706
 7707
 7708
 7709
 7710
 7711
 7712
 7713
 7714
 7715
 7716
 7717
 7718
 7719
 7720
 7721
 7722
 7723
 7724
 7725
 7726
 7727
 7728
 7729
 7730
 7731
 7732
 7733
 7734
 7735
 7736
 7737
 7738
 7739
 7740
 7741
 7742
 7743
 7744
 7745
 7746
 7747
 7748
 7749
 7750
 7751
 7752
 7753
 7754
 7755
 7756
 7757
 7758
 7759
 7760
 7761
 7762
 7763
 7764
 7765
 7766
 7767
 7768
 7769
 7770
 7771
 7772
 7773
 7774
 7775
 7776
 7777
 7778
 7779
 7780
 7781
 7782
 7783
 7784
 7785
 7786
 7787
 7788
 7789
 7790
 7791
 7792
 7793
 7794
 7795
 7796
 7797
 7798
 7799
 7800
 7801
 7802
 7803
 7804
 7805
 7806
 7807
 7808
 7809
 7810
 7811
 7812
 7813
 7814
 7815
 7816
 7817
 7818
 7819
 7820
 7821
 7822
 7823
 7824
 7825
 7826
 7827
 7828
 7829
 7830
 7831
 7832
 7833
 7834
 7835
 7836
 7837
 7838
 7839
 7840
 7841
 7842
 7843
 7844
 7845
 7846
 7847
 7848
 7849
 7850
 7851
 7852
 7853
 7854
 7855
 7856
 7857
 7858
 7859
 7860
 7861
 7862
 7863
 7864
 7865
 7866
 7867
 7868
 7869
 7870
 7871
 7872
 7873
 7874
 7875
 7876
 7877
 7878
 7879
 7880
 7881
 7882
 7883
 7884
 7885
 7886
 7887
 7888
 7889
 7890
 7891
 7892
 7893
 7894
 7895
 7896
 7897
 7898
 7899
 7900
 7901
 7902
 7903
 7904
 7905
 7906
 7907
 7908
 7909
 7910
 7911
 7912
 7913
 7914
 7915
 7916
 7917
 7918
 7919
 7920
 7921
 7922
 7923
 7924
 7925
 7926
 7927
 7928
 7929
 7930
 7931
 7932
 7933
 7934
 7935
 7936
 7937
 7938
 7939
 7940
 7941
 7942
 7943
 7944
 7945
 7946
 7947
 7948
 7949
 7950
 7951
 7952
 7953
 7954
 7955
 7956
 7957
 7958
 7959
 7960
 7961
 7962
 7963
 7964
 7965
 7966
 7967
 7968
 7969
 7970
 7971
 7972
 7973
 7974
 7975
 7976
 7977
 7978
 7979
 7980
 7981
 7982
 7983
 7984
 7985
 7986
 7987
 7988
 7989
 7990
 7991
 7992
 7993
 7994
 7995
 7996
 7997
 7998
 7999
 8000
 8001
 8002
 8003
 8004
 8005
 8006
 8007
 8008
 8009
 8010
 8011
 8012
 8013
 8014
 8015
 8016
 8017
 8018
 8019
 8020
 8021
 8022
 8023
 8024
 8025
 8026
 8027
 8028
 8029
 8030
 8031
 8032
 8033
 8034
 8035
 8036
 8037
 8038
 8039
 8040
 8041
 8042
 8043
 8044
 8045
 8046
 8047
 8048
 8049
 8050
 8051
 8052
 8053
 8054
 8055
 8056
 8057
 8058
 8059
 8060
 8061
 8062
 8063
 8064
 8065
 8066
 8067
 8068
 8069
 8070
 8071
 8072
 8073
 8074
 8075
 8076
 8077
 8078
 8079
 8080
 8081
 8082
 8083
 8084
 8085
 8086
 8087
 8088
 8089
 8090
 8091
 8092
 8093
 8094
 8095
 8096
 8097
 8098
 8099
 8100
 8101
 8102
 8103
 8104
 8105
 8106
 8107
 8108
 8109
 8110
 8111
 8112
 8113
 8114
 8115
 8116
 8117
 8118
 8119
 8120
 8121
 8122
 8123
 8124
 8125
 8126
 8127
 8128
 8129
 8130
 8131
 8132
 8133
 8134
 8135
 8136
 8137
 8138
 8139
 8140
 8141
 8142
 8143
 8144
 8145
 8146
 8147
 8148
 8149
 8150
 8151
 8152
 8153
 8154
 8155
 8156
 8157
 8158
 8159
 8160
 8161
 8162
 8163
 8164
 8165
 8166
 8167
 8168
 8169
 8170
 8171
 8172
 8173
 8174
 8175
 8176
 8177
 8178
 8179
 8180
 8181
 8182
 8183
 8184
 8185
 8186
 8187
 8188
 8189
 8190
 8191
 8192
 8193
 8194
 8195
 8196
 8197
 8198
 8199
 8200
 8201
 8202
 8203
 8204
 8205
 8206
 8207
 8208
 8209
 8210
 8211
 8212
 8213
 8214
 8215
 8216
 8217
 8218
 8219
 8220
 8221
 8222
 8223
 8224
 8225
 8226
 8227
 8228
 8229
 8230
 8231
 8232
 8233
 8234
 8235
 8236
 8237
 8238
 8239
 8240
 8241
 8242
 8243
 8244
 8245
 8246
 8247
 8248
 8249
 8250
 8251
 8252
 8253
 8254
 8255
 8256
 8257
 8258
 8259
 8260
 8261
 8262
 8263
 8264
 8265
 8266
 8267
 8268
 8269
 8270
 8271
 8272
 8273
 8274
 8275
 8276
 8277
 8278
 8279
 8280
 8281
 8282
 8283
 8284
 8285
 8286
 8287
 8288
 8289
 8290
 8291
 8292
 8293
 8294
 8295
 8296
 8297
 8298
 8299
 8300
 8301
 8302
 8303
 8304
 8305
 8306
 8307
 8308
 8309
 8310
 8311
 8312
 8313
 8314
 8315
 8316
 8317
 8318
 8319
 8320
 8321
 8322
 8323
 8324
 8325
 8326
 8327
 8328
 8329
 8330
 8331
 8332
 8333
 8334
 8335
 8336
 8337
 8338
 8339
 8340
 8341
 8342
 8343
 8344
 8345
 8346
 8347
 8348
 8349
 8350
 8351
 8352
 8353
 8354
 8355
 8356
 8357
 8358
 8359
 8360
 8361
 8362
 8363
 8364
 8365
 8366
 8367
 8368
 8369
 8370
 8371
 8372
 8373
 8374
 8375
 8376
 8377
 8378
 8379
 8380
 8381
 8382
 8383
 8384
 8385
 8386
 8387
 8388
 8389
 8390
 8391
 8392
 8393
 8394
 8395
 8396
 8397
 8398
 8399
 8400
 8401
 8402
 8403
 8404
 8405
 8406
 8407
 8408
 8409
 8410
 8411
 8412
 8413
 8414
 8415
 8416
 8417
 8418
 8419
 8420
 8421
 8422
 8423
 8424
 8425
 8426
 8427
 8428
 8429
 8430
 8431
 8432
 8433
 8434
 8435
 8436
 8437
 8438
 8439
 8440
 8441
 8442
 8443
 8444
 8445
 8446
 8447
 8448
 8449
 8450
 8451
 8452
 8453
 8454
 8455
 8456
 8457
 8458
 8459
 8460
 8461
 8462
 8463
 8464
 8465
 8466
 8467
 8468
 8469
 8470
 8471
 8472
 8473
 8474
 8475
 8476
 8477
 8478
 8479
 8480
 8481
 8482
 8483
 8484
 8485
 8486
 8487
 8488
 8489
 8490
 8491
 8492
 8493
 8494
 8495
 8496
 8497
 8498
 8499
 8500
 8501
 8502
 8503
 8504
 8505
 8506
 8507
 8508
 8509
 8510
 8511
 8512
 8513
 8514
 8515
 8516
 8517
 8518
 8519
 8520
 8521
 8522
 8523
 8524
 8525
 8526
 8527
 8528
 8529
 8530
 8531
 8532
 8533
 8534
 8535
 8536
 8537
 8538
 8539
 8540
 8541
 8542
 8543
 8544
 8545
 8546
 8547
 8548
 8549
 8550
 8551
 8552
 8553
 8554
 8555
 8556
 8557
 8558
 8559
 8560
 8561
 8562
 8563
 8564
 8565
 8566
 8567
 8568
 8569
 8570
 8571
 8572
 8573
 8574
 8575
 8576
 8577
 8578
 8579
 8580
 8581
 8582
 8583
 8584
 8585
 8586
 8587
 8588
 8589
 8590
 8591
 8592
 8593
 8594
 8595
 8596
 8597
 8598
 8599
 8600
 8601
 8602
 8603
 8604
 8605
 8606
 8607
 8608
 8609
 8610
 8611
 8612
 8613
 8614
 8615
 8616
 8617
 8618
 8619
 8620
 8621
 8622
 8623
 8624
 8625
 8626
 8627
 8628
 8629
 8630
 8631
 8632
 8633
 8634
 8635
 8636
 8637
 8638
 8639
 8640
 8641
 8642
 8643
 8644
 8645
 8646
 8647
 8648
 8649
 8650
 8651
 8652
 8653
 8654
 8655
 8656
 8657
 8658
 8659
 8660
 8661
 8662
 8663
 8664
 8665
 8666
 8667
 8668
 8669
 8670
 8671
 8672
 8673
 8674
 8675
 8676
 8677
 8678
 8679
 8680
 8681
 8682
 8683
 8684
 8685
 8686
 8687
 8688
 8689
 8690
 8691
 8692
 8693
 8694
 8695
 8696
 8697
 8698
 8699
 8700
 8701
 8702
 8703
 8704
 8705
 8706
 8707
 8708
 8709
 8710
 8711
 8712
 8713
 8714
 8715
 8716
 8717
 8718
 8719
 8720
 8721
 8722
 8723
 8724
 8725
 8726
 8727
 8728
 8729
 8730
 8731
 8732
 8733
 8734
 8735
 8736
 8737
 8738
 8739
 8740
 8741
 8742
 8743
 8744
 8745
 8746
 8747
 8748
 8749
 8750
 8751
 8752
 8753
 8754
 8755
 8756
 8757
 8758
 8759
 8760
 8761
 8762
 8763
 8764
 8765
 8766
 8767
 8768
 8769
 8770
 8771
 8772
 8773
 8774
 8775
 8776
 8777
 8778
 8779
 8780
 8781
 8782
 8783
 8784
 8785
 8786
 8787
 8788
 8789
 8790
 8791
 8792
 8793
 8794
 8795
 8796
 8797
 8798
 8799
 8800
 8801
 8802
 8803
 8804
 8805
 8806
 8807
 8808
 8809
 8810
 8811
 8812
 8813
 8814
 8815
 8816
 8817
 8818
 8819
 8820
 8821
 8822
 8823
 8824
 8825
 8826
 8827
 8828
 8829
 8830
 8831
 8832
 8833
 8834
 8835
 8836
 8837
 8838
 8839
 8840
 8841
 8842
 8843
 8844
 8845
 8846
 8847
 8848
 8849
 8850
 8851
 8852
 8853
 8854
 8855
 8856
 8857
 8858
 8859
 8860
 8861
 8862
 8863
 8864
 8865
 8866
 8867
 8868
 8869
 8870
 8871
 8872
 8873
 8874
 8875
 8876
 8877
 8878
 8879
 8880
 8881
 8882
 8883
 8884
 8885
 8886
 8887
 8888
 8889
 8890
 8891
 8892
 8893
 8894
 8895
 8896
 8897
 8898
 8899
 8900
 8901
 8902
 8903
 8904
 8905
 8906
 8907
 8908
 8909
 8910
 8911
 8912
 8913
 8914
 8915
 8916
 8917
 8918
 8919
 8920
 8921
 8922
 8923
 8924
 8925
 8926
 8927
 8928
 8929
 8930
 8931
 8932
 8933
 8934
 8935
 8936
 8937
 8938
 8939
 8940
 8941
 8942
 8943
 8944
 8945
 8946
 8947
 8948
 8949
 8950
 8951
 8952
 8953
 8954
 8955
 8956
 8957
 8958
 8959
 8960
 8961
 8962
 8963
 8964
 8965
 8966
 8967
 8968
 8969
 8970
 8971
 8972
 8973
 8974
 8975
 8976
 8977
 8978
 8979
 8980
 8981
 8982
 8983
 8984
 8985
 8986
 8987
 8988
 8989
 8990
 8991
 8992
 8993
 8994
 8995
 8996
 8997
 8998
 8999
 9000
 9001
 9002
 9003
 9004
 9005
 9006
 9007
 9008
 9009
 9010
 9011
 9012
 9013
 9014
 9015
 9016
 9017
 9018
 9019
 9020
 9021
 9022
 9023
 9024
 9025
 9026
 9027
 9028
 9029
 9030
 9031
 9032
 9033
 9034
 9035
 9036
 9037
 9038
 9039
 9040
 9041
 9042
 9043
 9044
 9045
 9046
 9047
 9048
 9049
 9050
 9051
 9052
 9053
 9054
 9055
 9056
 9057
 9058
 9059
 9060
 9061
 9062
 9063
 9064
 9065
 9066
 9067
 9068
 9069
 9070
 9071
 9072
 9073
 9074
 9075
 9076
 9077
 9078
 9079
 9080
 9081
 9082
 9083
 9084
 9085
 9086
 9087
 9088
 9089
 9090
 9091
 9092
 9093
 9094
 9095
 9096
 9097
 9098
 9099
 9100
 9101
 9102
 9103
 9104
 9105
 9106
 9107
 9108
 9109
 9110
 9111
 9112
 9113
 9114
 9115
 9116
 9117
 9118
 9119
 9120
 9121
 9122
 9123
 9124
 9125
 9126
 9127
 9128
 9129
 9130
 9131
 9132
 9133
 9134
 9135
 9136
 9137
 9138
 9139
 9140
 9141
 9142
 9143
 9144
 9145
 9146
 9147
 9148
 9149
 9150
 9151
 9152
 9153
 9154
 9155
 9156
 9157
 9158
 9159
 9160
 9161
 9162
 9163
 9164
 9165
 9166
 9167
 9168
 9169
 9170
 9171
 9172
 9173
 9174
 9175
 9176
 9177
 9178
 9179
 9180
 9181
 9182
 9183
 9184
 9185
 9186
 9187
 9188
 9189
 9190
 9191
 9192
 9193
 9194
 9195
 9196
 9197
 9198
 9199
 9200
 9201
 9202
 9203
 9204
 9205
 9206
 9207
 9208
 9209
 9210
 9211
 9212
 9213
 9214
 9215
 9216
 9217
 9218
 9219
 9220
 9221
 9222
 9223
 9224
 9225
 9226
 9227
 9228
 9229
 9230
 9231
 9232
 9233
 9234
 9235
 9236
 9237
 9238
 9239
 9240
 9241
 9242
 9243
 9244
 9245
 9246
 9247
 9248
 9249
 9250
 9251
 9252
 9253
 9254
 9255
 9256
 9257
 9258
 9259
 9260
 9261
 9262
 9263
 9264
 9265
 9266
 9267
 9268
 9269
 9270
 9271
 9272
 9273
 9274
 9275
 9276
 9277
 9278
 9279
 9280
 9281
 9282
 9283
 9284
 9285
 9286
 9287
 9288
 9289
 9290
 9291
 9292
 9293
 9294
 9295
 9296
 9297
 9298
 9299
 9300
 9301
 9302
 9303
 9304
 9305
 9306
 9307
 9308
 9309
 9310
 9311
 9312
 9313
 9314
 9315
 9316
 9317
 9318
 9319
 9320
 9321
 9322
 9323
 9324
 9325
 9326
 9327
 9328
 9329
 9330
 9331
 9332
 9333
 9334
 9335
 9336
 9337
 9338
 9339
 9340
 9341
 9342
 9343
 9344
 9345
 9346
 9347
 9348
 9349
 9350
 9351
 9352
 9353
 9354
 9355
 9356
 9357
 9358
 9359
 9360
 9361
 9362
 9363
 9364
 9365
 9366
 9367
 9368
 9369
 9370
 9371
 9372
 9373
 9374
 9375
 9376
 9377
 9378
 9379
 9380
 9381
 9382
 9383
 9384
 9385
 9386
 9387
 9388
 9389
 9390
 9391
 9392
 9393
 9394
 9395
 9396
 9397
 9398
 9399
 9400
 9401
 9402
 9403
 9404
 9405
 9406
 9407
 9408
 9409
 9410
 9411
 9412
 9413
 9414
 9415
 9416
 9417
 9418
 9419
 9420
 9421
 9422
 9423
 9424
 9425
 9426
 9427
 9428
 9429
 9430
 9431
 9432
 9433
 9434
 9435
 9436
 9437
 9438
 9439
 9440
 9441
 9442
 9443
 9444
 9445
 9446
 9447
 9448
 9449
 9450
 9451
 9452
 9453
 9454
 9455
 9456
 9457
 9458
 9459
 9460
 9461
 9462
 9463
 9464
 9465
 9466
 9467
 9468
 9469
 9470
 9471
 9472
 9473
 9474
 9475
 9476
 9477
 9478
 9479
 9480
 9481
 9482
 9483
 9484
 9485
 9486
 9487
 9488
 9489
 9490
 9491
 9492
 9493
 9494
 9495
 9496
 9497
 9498
 9499
 9500
 9501
 9502
 9503
 9504
 9505
 9506
 9507
 9508
 9509
 9510
 9511
 9512
 9513
 9514
 9515
 9516
 9517
 9518
 9519
 9520
 9521
 9522
 9523
 9524
 9525
 9526
 9527
 9528
 9529
 9530
 9531
 9532
 9533
 9534
 9535
 9536
 9537
 9538
 9539
 9540
 9541
 9542
 9543
 9544
 9545
 9546
 9547
 9548
 9549
 9550
 9551
 9552
 9553
 9554
 9555
 9556
 9557
 9558
 9559
 9560
 9561
 9562
 9563
 9564
 9565
 9566
 9567
 9568
 9569
 9570
 9571
 9572
 9573
 9574
 9575
 9576
 9577
 9578
 9579
 9580
 9581
 9582
 9583
 9584
 9585
 9586
 9587
 9588
 9589
 9590
 9591
 9592
 9593
 9594
 9595
 9596
 9597
 9598
 9599
 9600
 9601
 9602
 9603
 9604
 9605
 9606
 9607
 9608
 9609
 9610
 9611
 9612
 9613
 9614
 9615
 9616
 9617
 9618
 9619
 9620
 9621
 9622
 9623
 9624
 9625
 9626
 9627
 9628
 9629
 9630
 9631
 9632
 9633
 9634
 9635
 9636
 9637
 9638
 9639
 9640
 9641
 9642
 9643
 9644
 9645
 9646
 9647
 9648
 9649
 9650
 9651
 9652
 9653
 9654
 9655
 9656
 9657
 9658
 9659
 9660
 9661
 9662
 9663
 9664
 9665
 9666
 9667
 9668
 9669
 9670
 9671
 9672
 9673
 9674
 9675
 9676
 9677
 9678
 9679
 9680
 9681
 9682
 9683
 9684
 9685
 9686
 9687
 9688
 9689
 9690
 9691
 9692
 9693
 9694
 9695
 9696
 9697
 9698
 9699
 9700
 9701
 9702
 9703
 9704
 9705
 9706
 9707
 9708
 9709
 9710
 9711
 9712
 9713
 9714
 9715
 9716
 9717
 9718
 9719
 9720
 9721
 9722
 9723
 9724
 9725
 9726
 9727
 9728
 9729
 9730
 9731
 9732
 9733
 9734
 9735
 9736
 9737
 9738
 9739
 9740
 9741
 9742
 9743
 9744
 9745
 9746
 9747
 9748
 9749
 9750
 9751
 9752
 9753
 9754
 9755
 9756
 9757
 9758
 9759
 9760
 9761
 9762
 9763
 9764
 9765
 9766
 9767
 9768
 9769
 9770
 9771
 9772
 9773
 9774
 9775
 9776
 9777
 9778
 9779
 9780
 9781
 9782
 9783
 9784
 9785
 9786
 9787
 9788
 9789
 9790
 9791
 9792
 9793
 9794
 9795
 9796
 9797
 9798
 9799
 9800
 9801
 9802
 9803
 9804
 9805
 9806
 9807
 9808
 9809
 9810
 9811
 9812
 9813
 9814
 9815
 9816
 9817
 9818
 9819
 9820
 9821
 9822
 9823
 9824
 9825
 9826
 9827
 9828
 9829
 9830
 9831
 9832
 9833
 9834
 9835
 9836
 9837
 9838
 9839
 9840
 9841
 9842
 9843
 9844
 9845
 9846
 9847
 9848
 9849
 9850
 9851
 9852
 9853
 9854
 9855
 9856
 9857
 9858
 9859
 9860
 9861
 9862
 9863
 9864
 9865
 9866
 9867
 9868
 9869
 9870
 9871
 9872
 9873
 9874
 9875
 9876
 9877
 9878
 9879
 9880
 9881
 9882
 9883
 9884
 9885
 9886
 9887
 9888
 9889
 9890
 9891
 9892
 9893
 9894
 9895
 9896
 9897
 9898
 9899
 9900
 9901
 9902
 9903
 9904
 9905
 9906
 9907
 9908
 9909
 9910
 9911
 9912
 9913
 9914
 9915
 9916
 9917
 9918
 9919
 9920
 9921
 9922
 9923
 9924
 9925
 9926
 9927
 9928
 9929
 9930
 9931
 9932
 9933
 9934
 9935
 9936
 9937
 9938
 9939
 9940
 9941
 9942
 9943
 9944
 9945
 9946
 9947
 9948
 9949
 9950
 9951
 9952
 9953
 9954
 9955
 9956
 9957
 9958
 9959
 9960
 9961
 9962
 9963
 9964
 9965
 9966
 9967
 9968
 9969
 9970
 9971
 9972
 9973
 9974
 9975
 9976
 9977
 9978
 9979
 9980
 9981
 9982
 9983
 9984
 9985
 9986
 9987
 9988
 9989
 9990
 9991
 9992
 9993
 9994
 9995
 9996
 9997
 9998
 9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
18498
18499
18500
18501
18502
18503
18504
18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522
18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535
18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546
18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559
18560
18561
18562
18563
18564
18565
18566
18567
18568
18569
18570
18571
18572
18573
18574
18575
18576
18577
18578
18579
18580
18581
18582
18583
18584
18585
18586
18587
18588
18589
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
18602
18603
18604
18605
18606
18607
18608
18609
18610
18611
18612
18613
18614
18615
18616
18617
18618
18619
18620
18621
18622
18623
18624
18625
18626
18627
18628
18629
18630
18631
18632
18633
18634
18635
18636
18637
18638
18639
18640
18641
18642
18643
18644
18645
18646
18647
18648
18649
18650
18651
18652
18653
18654
18655
18656
18657
18658
18659
18660
18661
18662
18663
18664
18665
18666
18667
18668
18669
18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681
18682
18683
18684
18685
18686
18687
18688
18689
18690
18691
18692
18693
18694
18695
18696
18697
18698
18699
18700
18701
18702
18703
18704
18705
18706
18707
18708
18709
18710
18711
18712
18713
18714
18715
18716
18717
18718
18719
18720
18721
18722
18723
18724
18725
18726
18727
18728
18729
18730
18731
18732
18733
18734
18735
18736
18737
18738
18739
18740
18741
18742
18743
18744
18745
18746
18747
18748
18749
18750
18751
18752
18753
18754
18755
18756
18757
18758
18759
18760
18761
18762
18763
18764
18765
18766
18767
18768
18769
18770
18771
18772
18773
18774
18775
18776
18777
18778
18779
18780
18781
18782
18783
18784
18785
18786
18787
18788
18789
18790
18791
18792
18793
18794
18795
18796
18797
18798
18799
18800
18801
18802
18803
18804
18805
18806
18807
18808
18809
18810
18811
18812
18813
18814
18815
18816
18817
18818
18819
18820
18821
18822
18823
18824
18825
18826
18827
18828
18829
18830
18831
18832
18833
18834
18835
18836
18837
18838
18839
18840
18841
18842
18843
18844
18845
18846
18847
18848
18849
18850
18851
18852
18853
18854
18855
18856
18857
18858
18859
18860
18861
18862
18863
18864
18865
18866
18867
18868
18869
18870
18871
18872
18873
18874
18875
18876
18877
18878
18879
18880
18881
18882
18883
18884
18885
18886
18887
18888
18889
18890
18891
18892
18893
18894
18895
18896
18897
18898
18899
18900
18901
18902
18903
18904
18905
18906
18907
18908
18909
18910
18911
18912
18913
18914
18915
18916
18917
18918
18919
18920
18921
18922
18923
18924
18925
18926
18927
18928
18929
18930
18931
18932
18933
18934
18935
18936
18937
18938
18939
18940
18941
18942
18943
18944
18945
18946
18947
18948
18949
18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964
18965
18966
18967
18968
18969
18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988
18989
18990
18991
18992
18993
18994
18995
18996
18997
18998
18999
19000
19001
19002
19003
19004
19005
19006
19007
19008
19009
19010
19011
19012
19013
19014
19015
19016
19017
19018
19019
19020
19021
19022
19023
19024
19025
19026
19027
19028
19029
19030
19031
19032
19033
19034
19035
19036
19037
19038
19039
19040
19041
19042
19043
19044
19045
19046
19047
19048
19049
19050
19051
19052
19053
19054
19055
19056
19057
19058
19059
19060
19061
19062
19063
19064
19065
19066
19067
19068
19069
19070
19071
19072
19073
19074
19075
19076
19077
19078
19079
19080
19081
19082
19083
19084
19085
19086
19087
19088
19089
19090
19091
19092
19093
19094
19095
19096
19097
19098
19099
19100
19101
19102
19103
19104
19105
19106
19107
19108
19109
19110
19111
19112
19113
19114
19115
19116
19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
19129
19130
19131
19132
19133
19134
19135
19136
19137
19138
19139
19140
19141
19142
19143
19144
19145
19146
19147
19148
19149
19150
19151
19152
19153
19154
19155
19156
19157
19158
19159
19160
19161
19162
19163
19164
19165
19166
19167
19168
19169
19170
19171
19172
19173
19174
19175
19176
19177
19178
19179
19180
19181
19182
19183
19184
19185
19186
19187
19188
19189
19190
19191
19192
19193
19194
19195
19196
19197
19198
19199
19200
19201
19202
19203
19204
19205
19206
19207
19208
19209
19210
19211
19212
19213
19214
19215
19216
19217
19218
19219
19220
19221
19222
19223
19224
19225
19226
19227
19228
19229
19230
19231
19232
19233
19234
19235
19236
19237
19238
19239
19240
19241
19242
19243
19244
19245
19246
19247
19248
19249
19250
19251
19252
19253
19254
19255
19256
19257
19258
19259
19260
19261
19262
19263
19264
19265
19266
19267
19268
19269
19270
19271
19272
19273
19274
19275
19276
19277
19278
19279
19280
19281
19282
19283
19284
19285
19286
19287
19288
19289
19290
19291
19292
19293
19294
19295
19296
19297
19298
19299
19300
19301
19302
19303
19304
19305
19306
19307
19308
19309
19310
19311
19312
19313
19314
19315
19316
19317
19318
19319
19320
19321
19322
19323
19324
19325
19326
19327
19328
19329
19330
19331
19332
19333
19334
19335
19336
19337
19338
19339
19340
19341
19342
19343
19344
19345
19346
19347
19348
19349
19350
19351
19352
19353
19354
19355
19356
19357
19358
19359
19360
19361
19362
19363
19364
19365
19366
19367
19368
19369
19370
19371
19372
19373
19374
19375
19376
19377
19378
19379
19380
19381
19382
19383
19384
19385
19386
19387
19388
19389
19390
19391
19392
19393
19394
19395
19396
19397
19398
19399
19400
19401
19402
19403
19404
19405
19406
19407
19408
19409
19410
19411
19412
19413
19414
19415
19416
19417
19418
19419
19420
19421
19422
19423
19424
19425
19426
19427
19428
19429
19430
19431
19432
19433
19434
19435
19436
19437
19438
19439
19440
19441
19442
19443
19444
19445
19446
19447
19448
19449
19450
19451
19452
19453
19454
19455
19456
19457
19458
19459
19460
19461
19462
19463
19464
19465
19466
19467
19468
19469
19470
19471
19472
19473
19474
19475
19476
19477
19478
19479
19480
19481
19482
19483
19484
19485
19486
19487
19488
19489
19490
19491
19492
19493
19494
19495
19496
19497
19498
19499
19500
19501
19502
19503
19504
19505
19506
19507
19508
19509
19510
19511
19512
19513
19514
19515
19516
19517
19518
19519
19520
19521
19522
19523
19524
19525
19526
19527
19528
19529
19530
19531
19532
19533
19534
19535
19536
19537
19538
19539
19540
19541
19542
19543
19544
19545
19546
19547
19548
19549
19550
19551
19552
19553
19554
19555
19556
19557
19558
19559
19560
19561
19562
19563
19564
19565
19566
19567
19568
19569
19570
19571
19572
19573
19574
19575
19576
19577
19578
19579
19580
19581
19582
19583
19584
19585
19586
19587
19588
19589
19590
19591
19592
19593
19594
19595
19596
19597
19598
19599
19600
19601
19602
19603
19604
19605
19606
19607
19608
19609
19610
19611
19612
19613
19614
19615
19616
19617
19618
19619
19620
19621
19622
19623
19624
19625
19626
19627
19628
19629
19630
19631
19632
19633
19634
19635
19636
19637
19638
19639
19640
19641
19642
19643
19644
19645
19646
19647
19648
19649
19650
19651
19652
19653
19654
19655
19656
19657
19658
19659
19660
19661
19662
19663
19664
19665
19666
19667
19668
19669
19670
19671
19672
19673
19674
19675
19676
19677
19678
19679
19680
19681
19682
19683
19684
19685
19686
19687
19688
19689
19690
19691
19692
19693
19694
19695
19696
19697
19698
19699
19700
19701
19702
19703
19704
19705
19706
19707
19708
19709
19710
19711
19712
19713
19714
19715
19716
19717
19718
19719
19720
19721
19722
19723
19724
19725
19726
19727
19728
19729
19730
19731
19732
19733
19734
19735
19736
19737
19738
19739
19740
19741
19742
19743
19744
19745
19746
19747
19748
19749
19750
19751
19752
19753
19754
19755
19756
19757
19758
19759
19760
19761
19762
19763
19764
19765
19766
19767
19768
19769
19770
19771
19772
19773
19774
19775
19776
19777
19778
19779
19780
19781
19782
19783
19784
19785
19786
19787
19788
19789
19790
19791
19792
19793
19794
19795
19796
19797
19798
19799
19800
19801
19802
19803
19804
19805
19806
19807
19808
19809
19810
19811
19812
19813
19814
19815
19816
19817
19818
19819
19820
19821
19822
19823
19824
19825
19826
19827
19828
19829
19830
19831
19832
19833
19834
19835
19836
19837
19838
19839
19840
19841
19842
19843
19844
19845
19846
19847
19848
19849
19850
19851
19852
19853
19854
19855
19856
19857
19858
19859
19860
19861
19862
19863
19864
19865
19866
19867
19868
19869
19870
19871
19872
19873
19874
19875
19876
19877
19878
19879
19880
19881
19882
19883
19884
19885
19886
19887
19888
19889
19890
19891
19892
19893
19894
19895
19896
19897
19898
19899
19900
19901
19902
19903
19904
19905
19906
19907
19908
19909
19910
19911
19912
19913
19914
19915
19916
19917
19918
19919
19920
19921
19922
19923
19924
19925
19926
19927
19928
19929
19930
19931
19932
19933
19934
19935
19936
19937
19938
19939
19940
19941
19942
19943
19944
19945
19946
19947
19948
19949
19950
19951
19952
19953
19954
19955
19956
19957
19958
19959
19960
19961
19962
19963
19964
19965
19966
19967
19968
19969
19970
19971
19972
19973
19974
19975
19976
19977
19978
19979
19980
19981
19982
19983
19984
19985
19986
19987
19988
19989
19990
19991
19992
19993
19994
19995
19996
19997
19998
19999
20000
20001
20002
20003
20004
20005
20006
20007
20008
20009
20010
20011
20012
20013
20014
20015
20016
20017
20018
20019
20020
20021
20022
20023
20024
20025
20026
20027
20028
20029
20030
20031
20032
20033
20034
20035
20036
20037
20038
20039
20040
20041
20042
20043
20044
20045
20046
20047
20048
20049
20050
20051
20052
20053
20054
20055
20056
20057
20058
20059
20060
20061
20062
20063
20064
20065
20066
20067
20068
20069
20070
20071
20072
20073
20074
20075
20076
20077
20078
20079
20080
20081
20082
20083
20084
20085
20086
20087
20088
20089
20090
20091
20092
20093
20094
20095
20096
20097
20098
20099
20100
20101
20102
20103
20104
20105
20106
20107
20108
20109
20110
20111
20112
20113
20114
20115
20116
20117
20118
20119
20120
20121
20122
20123
20124
20125
20126
20127
20128
20129
20130
20131
20132
20133
20134
20135
20136
20137
20138
20139
20140
20141
20142
20143
20144
20145
20146
20147
20148
20149
20150
20151
20152
20153
20154
20155
20156
20157
20158
20159
20160
20161
20162
20163
20164
20165
20166
20167
20168
20169
20170
20171
20172
20173
20174
20175
20176
20177
20178
20179
20180
20181
20182
20183
20184
20185
20186
20187
20188
20189
20190
20191
20192
20193
20194
20195
20196
20197
20198
20199
20200
20201
20202
20203
20204
20205
20206
20207
20208
20209
20210
20211
20212
20213
20214
20215
20216
20217
20218
20219
20220
20221
20222
20223
20224
20225
20226
20227
20228
20229
20230
20231
20232
20233
20234
20235
20236
20237
20238
20239
20240
20241
20242
20243
20244
20245
20246
20247
20248
20249
20250
20251
20252
20253
20254
20255
20256
20257
20258
20259
20260
20261
20262
20263
20264
20265
20266
20267
20268
20269
20270
20271
20272
20273
20274
20275
20276
20277
20278
20279
20280
20281
20282
20283
20284
20285
20286
20287
20288
20289
20290
20291
20292
20293
20294
20295
20296
20297
20298
20299
20300
20301
20302
20303
20304
20305
20306
20307
20308
20309
20310
20311
20312
20313
20314
20315
20316
20317
20318
20319
20320
20321
20322
20323
20324
20325
20326
20327
20328
20329
20330
20331
20332
20333
20334
20335
20336
20337
20338
20339
20340
20341
20342
20343
20344
20345
20346
20347
20348
20349
20350
20351
20352
20353
20354
20355
20356
20357
20358
20359
20360
20361
20362
20363
20364
20365
20366
20367
20368
20369
20370
20371
20372
20373
20374
20375
20376
20377
20378
20379
20380
20381
20382
20383
20384
20385
20386
20387
20388
20389
20390
20391
20392
20393
20394
20395
20396
20397
20398
20399
20400
20401
20402
20403
20404
20405
20406
20407
20408
20409
20410
20411
20412
20413
20414
20415
20416
20417
20418
20419
20420
20421
20422
20423
20424
20425
20426
20427
20428
20429
20430
20431
20432
20433
20434
20435
20436
20437
20438
20439
20440
20441
20442
20443
20444
20445
20446
20447
20448
20449
20450
20451
20452
20453
20454
20455
20456
20457
20458
20459
20460
20461
20462
20463
20464
20465
20466
20467
20468
20469
20470
20471
20472
20473
20474
20475
20476
20477
20478
20479
20480
20481
20482
20483
20484
20485
20486
20487
20488
20489
20490
20491
20492
20493
20494
20495
20496
20497
20498
20499
20500
20501
20502
20503
20504
20505
20506
20507
20508
20509
20510
20511
20512
20513
20514
20515
20516
20517
20518
20519
20520
20521
20522
20523
20524
20525
20526
20527
20528
20529
20530
20531
20532
20533
20534
20535
20536
20537
20538
20539
20540
20541
20542
20543
20544
20545
20546
20547
20548
20549
20550
20551
20552
20553
20554
20555
20556
20557
20558
20559
20560
20561
20562
20563
20564
20565
20566
20567
20568
20569
20570
20571
20572
20573
20574
20575
20576
20577
20578
20579
20580
20581
20582
20583
20584
20585
20586
20587
20588
20589
20590
20591
20592
20593
20594
20595
20596
20597
20598
20599
20600
20601
20602
20603
20604
20605
20606
20607
20608
20609
20610
20611
20612
20613
20614
20615
20616
20617
20618
20619
20620
20621
20622
20623
20624
20625
20626
20627
20628
20629
20630
20631
20632
20633
20634
20635
20636
20637
20638
20639
20640
20641
20642
20643
20644
20645
20646
20647
20648
20649
20650
20651
20652
20653
20654
20655
20656
20657
20658
20659
20660
20661
20662
20663
20664
20665
20666
20667
20668
20669
20670
20671
20672
20673
20674
20675
20676
20677
20678
20679
20680
20681
20682
20683
20684
20685
20686
20687
20688
20689
20690
20691
20692
20693
20694
20695
20696
20697
20698
20699
20700
20701
20702
20703
20704
20705
20706
20707
20708
20709
20710
20711
20712
20713
20714
20715
20716
20717
20718
20719
20720
20721
20722
20723
20724
20725
20726
20727
20728
20729
20730
20731
20732
20733
20734
20735
20736
20737
20738
20739
20740
20741
20742
20743
20744
20745
20746
20747
20748
20749
20750
20751
20752
20753
20754
20755
20756
20757
20758
20759
20760
20761
20762
20763
20764
20765
20766
20767
20768
20769
20770
20771
20772
20773
20774
20775
20776
20777
20778
20779
20780
20781
20782
20783
20784
20785
20786
20787
20788
20789
20790
20791
20792
20793
20794
20795
20796
20797
20798
20799
20800
20801
20802
20803
20804
20805
20806
20807
20808
20809
20810
20811
20812
20813
20814
20815
20816
20817
20818
20819
20820
20821
20822
20823
20824
20825
20826
20827
20828
20829
20830
20831
20832
20833
20834
20835
20836
20837
20838
20839
20840
20841
20842
20843
20844
20845
20846
20847
20848
20849
20850
20851
20852
20853
20854
20855
20856
20857
20858
20859
20860
20861
20862
20863
20864
20865
20866
20867
20868
20869
20870
20871
20872
20873
20874
20875
20876
20877
20878
20879
20880
20881
20882
20883
20884
20885
20886
20887
20888
20889
20890
20891
20892
20893
20894
20895
20896
20897
20898
20899
20900
20901
20902
20903
20904
20905
20906
20907
20908
20909
20910
20911
20912
20913
20914
20915
20916
20917
20918
20919
20920
20921
20922
20923
20924
20925
20926
20927
20928
20929
20930
20931
20932
20933
20934
20935
20936
20937
20938
20939
20940
20941
20942
20943
20944
20945
20946
20947
20948
20949
20950
20951
20952
20953
20954
20955
20956
20957
20958
20959
20960
20961
20962
20963
20964
20965
20966
20967
20968
20969
20970
20971
20972
20973
20974
20975
20976
20977
20978
20979
20980
20981
20982
20983
20984
20985
20986
20987
20988
20989
20990
20991
20992
20993
20994
20995
20996
20997
20998
20999
21000
21001
21002
21003
21004
21005
21006
21007
21008
21009
21010
21011
21012
21013
21014
21015
21016
21017
21018
21019
21020
21021
21022
21023
21024
21025
21026
21027
21028
21029
21030
21031
21032
21033
21034
21035
21036
21037
21038
21039
21040
21041
21042
21043
21044
21045
21046
21047
21048
21049
21050
21051
21052
21053
21054
21055
21056
21057
21058
21059
21060
21061
21062
21063
21064
21065
21066
21067
21068
21069
21070
21071
21072
21073
21074
21075
21076
21077
21078
21079
21080
21081
21082
21083
21084
21085
21086
21087
21088
21089
21090
21091
21092
21093
21094
21095
21096
21097
21098
21099
21100
21101
21102
21103
21104
21105
21106
21107
21108
21109
21110
21111
21112
21113
21114
21115
21116
21117
21118
21119
21120
21121
21122
21123
21124
21125
21126
21127
21128
21129
21130
21131
21132
21133
21134
21135
21136
21137
21138
21139
21140
21141
21142
21143
21144
21145
21146
21147
21148
21149
21150
21151
21152
21153
21154
21155
21156
21157
21158
21159
21160
21161
21162
21163
21164
21165
21166
21167
21168
21169
21170
21171
21172
21173
21174
21175
21176
21177
21178
21179
21180
21181
21182
21183
21184
21185
21186
21187
21188
21189
21190
21191
21192
21193
21194
21195
21196
21197
21198
21199
21200
21201
21202
21203
21204
21205
21206
21207
21208
21209
21210
21211
21212
21213
21214
21215
21216
21217
21218
21219
21220
21221
21222
21223
21224
21225
21226
21227
21228
21229
21230
21231
21232
21233
21234
21235
21236
21237
21238
21239
21240
21241
21242
21243
21244
21245
21246
21247
21248
21249
21250
21251
21252
21253
21254
21255
21256
21257
21258
21259
21260
21261
21262
21263
21264
21265
21266
21267
21268
21269
21270
21271
21272
21273
21274
21275
21276
21277
21278
21279
21280
21281
21282
21283
21284
21285
21286
21287
21288
21289
21290
21291
21292
21293
21294
21295
21296
21297
21298
21299
21300
21301
21302
21303
21304
21305
21306
21307
21308
21309
21310
21311
21312
21313
21314
21315
21316
21317
21318
21319
21320
21321
21322
21323
21324
21325
21326
21327
21328
21329
21330
21331
21332
21333
21334
21335
21336
21337
21338
21339
21340
21341
21342
21343
21344
21345
21346
21347
21348
21349
21350
21351
21352
21353
21354
21355
21356
21357
21358
21359
21360
21361
21362
21363
21364
21365
21366
21367
21368
21369
21370
21371
21372
21373
21374
21375
21376
21377
21378
21379
21380
21381
21382
21383
21384
21385
21386
21387
21388
21389
21390
21391
21392
21393
21394
21395
21396
21397
21398
21399
21400
21401
21402
21403
21404
21405
21406
21407
21408
21409
21410
21411
21412
21413
21414
21415
21416
21417
21418
21419
21420
21421
21422
21423
21424
21425
21426
21427
21428
21429
21430
21431
21432
21433
21434
21435
21436
21437
21438
21439
21440
21441
21442
21443
21444
21445
21446
21447
21448
21449
21450
21451
21452
21453
21454
21455
21456
21457
21458
21459
21460
21461
21462
21463
21464
21465
21466
21467
21468
21469
21470
21471
21472
21473
21474
21475
21476
21477
21478
21479
21480
21481
21482
21483
21484
21485
21486
21487
21488
21489
21490
21491
21492
21493
21494
21495
21496
21497
21498
21499
21500
21501
21502
21503
21504
21505
21506
21507
21508
21509
21510
21511
21512
21513
21514
21515
21516
21517
21518
21519
21520
21521
21522
21523
21524
21525
21526
21527
21528
21529
21530
21531
21532
21533
21534
21535
21536
21537
21538
21539
21540
21541
21542
21543
21544
21545
21546
21547
21548
21549
21550
21551
21552
21553
21554
21555
21556
21557
21558
21559
21560
21561
21562
21563
21564
21565
21566
21567
21568
21569
21570
21571
21572
21573
21574
21575
21576
21577
21578
21579
21580
21581
21582
21583
21584
21585
21586
21587
21588
21589
21590
21591
21592
21593
21594
21595
21596
21597
21598
21599
21600
21601
21602
21603
21604
21605
21606
21607
21608
21609
21610
21611
21612
21613
21614
21615
21616
21617
21618
21619
21620
21621
21622
21623
21624
21625
21626
21627
21628
21629
21630
21631
21632
21633
21634
21635
21636
21637
21638
21639
21640
21641
21642
21643
21644
21645
21646
21647
21648
21649
21650
21651
21652
21653
21654
21655
21656
21657
21658
21659
21660
21661
21662
21663
21664
21665
21666
21667
21668
21669
21670
21671
21672
21673
21674
21675
21676
21677
21678
21679
21680
21681
21682
21683
21684
21685
21686
21687
21688
21689
21690
21691
21692
21693
21694
21695
21696
21697
21698
21699
21700
21701
21702
21703
21704
21705
21706
21707
21708
21709
21710
21711
21712
21713
21714
21715
21716
21717
21718
21719
21720
21721
21722
21723
21724
21725
21726
21727
21728
21729
21730
21731
21732
21733
21734
21735
21736
21737
21738
21739
21740
21741
21742
21743
21744
21745
21746
21747
21748
21749
21750
21751
21752
21753
21754
21755
21756
21757
21758
21759
21760
21761
21762
21763
21764
21765
21766
21767
21768
21769
21770
21771
21772
21773
21774
21775
21776
21777
21778
21779
21780
21781
21782
21783
21784
21785
21786
21787
21788
21789
21790
21791
21792
21793
21794
21795
21796
21797
21798
21799
21800
21801
21802
21803
21804
21805
21806
21807
21808
21809
21810
21811
21812
21813
21814
21815
21816
21817
21818
21819
21820
21821
21822
21823
21824
21825
21826
21827
21828
21829
21830
21831
21832
21833
21834
21835
21836
21837
21838
21839
21840
21841
21842
21843
21844
21845
21846
21847
21848
21849
21850
21851
21852
21853
21854
21855
21856
21857
21858
21859
21860
21861
21862
21863
21864
21865
21866
21867
21868
21869
21870
21871
21872
21873
21874
21875
21876
21877
21878
21879
21880
21881
21882
21883
21884
21885
21886
21887
21888
21889
21890
21891
21892
21893
21894
21895
21896
21897
21898
21899
21900
21901
21902
21903
21904
21905
21906
21907
21908
21909
21910
21911
21912
21913
21914
21915
21916
21917
21918
21919
21920
21921
21922
21923
21924
21925
21926
21927
21928
21929
21930
21931
21932
21933
21934
21935
21936
21937
21938
21939
21940
21941
21942
21943
21944
21945
21946
21947
21948
21949
21950
21951
21952
21953
21954
21955
21956
21957
21958
21959
21960
21961
21962
21963
21964
21965
21966
21967
21968
21969
21970
21971
21972
21973
21974
21975
21976
21977
21978
21979
21980
21981
21982
21983
21984
21985
21986
21987
21988
21989
21990
21991
21992
21993
21994
21995
21996
21997
21998
21999
22000
22001
22002
22003
22004
22005
22006
22007
22008
22009
22010
22011
22012
22013
22014
22015
22016
22017
22018
22019
22020
22021
22022
22023
22024
22025
22026
22027
22028
22029
22030
22031
22032
22033
22034
22035
22036
22037
22038
22039
22040
22041
22042
22043
22044
22045
22046
22047
22048
22049
22050
22051
22052
22053
22054
22055
22056
22057
22058
22059
22060
22061
22062
22063
22064
22065
22066
22067
22068
22069
22070
22071
22072
22073
22074
22075
22076
22077
22078
22079
22080
22081
22082
22083
22084
22085
22086
22087
22088
22089
22090
22091
22092
22093
22094
22095
22096
22097
22098
22099
22100
22101
22102
22103
22104
22105
22106
22107
22108
22109
22110
22111
22112
22113
22114
22115
22116
22117
22118
22119
22120
22121
22122
22123
22124
22125
22126
22127
22128
22129
22130
22131
22132
22133
22134
22135
22136
22137
22138
22139
22140
22141
22142
22143
22144
22145
22146
22147
22148
22149
22150
22151
22152
22153
22154
22155
22156
22157
22158
22159
22160
22161
22162
22163
22164
22165
22166
22167
22168
22169
22170
22171
22172
22173
22174
22175
22176
22177
22178
22179
22180
22181
22182
22183
22184
22185
22186
22187
22188
22189
22190
22191
22192
22193
22194
22195
22196
22197
22198
22199
22200
22201
22202
22203
22204
22205
22206
22207
22208
22209
22210
22211
22212
22213
22214
22215
22216
22217
22218
22219
22220
22221
22222
22223
22224
22225
22226
22227
22228
22229
22230
22231
22232
22233
22234
22235
22236
22237
22238
22239
22240
22241
22242
22243
22244
22245
22246
22247
22248
22249
22250
22251
22252
22253
22254
22255
22256
22257
22258
22259
22260
22261
22262
22263
22264
22265
22266
22267
22268
22269
22270
22271
22272
22273
22274
22275
22276
22277
22278
22279
22280
22281
22282
22283
22284
22285
22286
22287
22288
22289
22290
22291
22292
22293
22294
22295
22296
22297
22298
22299
22300
22301
22302
22303
22304
22305
22306
22307
22308
22309
22310
22311
22312
22313
22314
22315
22316
22317
22318
22319
22320
22321
22322
22323
22324
22325
22326
22327
22328
22329
22330
22331
22332
22333
22334
22335
22336
22337
22338
22339
22340
22341
22342
22343
22344
22345
22346
22347
22348
22349
22350
22351
22352
22353
22354
22355
22356
22357
22358
22359
22360
22361
22362
22363
22364
22365
22366
22367
22368
22369
22370
22371
22372
22373
22374
22375
22376
22377
22378
22379
22380
22381
22382
22383
22384
22385
22386
22387
22388
22389
22390
22391
22392
22393
22394
22395
22396
22397
22398
22399
22400
22401
22402
22403
22404
22405
22406
22407
22408
22409
22410
22411
22412
22413
22414
22415
22416
22417
22418
22419
22420
22421
22422
22423
22424
22425
22426
22427
22428
22429
22430
22431
22432
22433
22434
22435
22436
22437
22438
22439
22440
22441
22442
22443
22444
22445
22446
22447
22448
22449
22450
22451
22452
22453
22454
22455
22456
22457
22458
22459
22460
22461
22462
22463
22464
22465
22466
22467
22468
22469
22470
22471
22472
22473
22474
22475
22476
22477
22478
22479
22480
22481
22482
22483
22484
22485
22486
22487
22488
22489
22490
22491
22492
22493
22494
22495
22496
22497
22498
22499
22500
22501
22502
22503
22504
22505
22506
22507
22508
22509
22510
22511
22512
22513
22514
22515
22516
22517
22518
22519
22520
22521
22522
22523
22524
22525
22526
22527
22528
22529
22530
22531
22532
22533
22534
22535
22536
22537
22538
22539
22540
22541
22542
22543
22544
22545
22546
22547
22548
22549
22550
22551
22552
22553
22554
22555
22556
22557
22558
22559
22560
22561
22562
22563
22564
22565
22566
22567
22568
22569
22570
22571
22572
22573
22574
22575
22576
22577
22578
22579
22580
22581
22582
22583
22584
22585
22586
22587
22588
22589
22590
22591
22592
22593
22594
22595
22596
22597
22598
22599
22600
22601
22602
22603
22604
22605
22606
22607
22608
22609
22610
22611
22612
22613
22614
22615
22616
22617
22618
22619
22620
22621
22622
22623
22624
22625
22626
22627
22628
22629
22630
22631
22632
22633
22634
22635
22636
22637
22638
22639
22640
22641
22642
22643
22644
22645
22646
22647
22648
22649
22650
22651
22652
22653
22654
22655
22656
22657
22658
22659
22660
22661
22662
22663
22664
22665
22666
22667
22668
22669
22670
22671
22672
22673
22674
22675
22676
22677
22678
22679
22680
22681
22682
22683
22684
22685
22686
22687
22688
22689
22690
22691
22692
22693
22694
22695
22696
22697
22698
22699
22700
22701
22702
22703
22704
22705
22706
22707
22708
22709
22710
22711
22712
22713
22714
22715
22716
22717
22718
22719
22720
22721
22722
22723
22724
22725
22726
22727
22728
22729
22730
22731
22732
22733
22734
22735
22736
22737
22738
22739
22740
22741
22742
22743
22744
22745
22746
22747
22748
22749
22750
22751
22752
22753
22754
22755
22756
22757
22758
22759
22760
22761
22762
22763
22764
22765
22766
22767
22768
22769
22770
22771
22772
22773
22774
22775
22776
22777
22778
22779
22780
22781
22782
22783
22784
22785
22786
22787
22788
22789
22790
22791
22792
22793
22794
22795
22796
22797
22798
22799
22800
22801
22802
22803
22804
22805
22806
22807
22808
22809
22810
22811
22812
22813
22814
22815
22816
22817
22818
22819
22820
22821
22822
22823
22824
22825
22826
22827
22828
22829
22830
22831
22832
22833
22834
22835
22836
22837
22838
22839
22840
22841
22842
22843
22844
22845
22846
22847
22848
22849
22850
22851
22852
22853
22854
22855
22856
22857
22858
22859
22860
22861
22862
22863
22864
22865
22866
22867
22868
22869
22870
22871
22872
22873
22874
22875
22876
22877
22878
22879
22880
22881
22882
22883
22884
22885
22886
22887
22888
22889
22890
22891
22892
22893
22894
22895
22896
22897
22898
22899
22900
22901
22902
22903
22904
22905
22906
22907
22908
22909
22910
22911
22912
22913
22914
22915
22916
22917
22918
22919
22920
22921
22922
22923
22924
22925
22926
22927
22928
22929
22930
22931
22932
22933
22934
22935
22936
22937
22938
22939
22940
22941
22942
22943
22944
22945
22946
22947
22948
22949
22950
22951
22952
22953
22954
22955
22956
22957
22958
22959
22960
22961
22962
22963
22964
22965
22966
22967
22968
22969
22970
22971
22972
22973
22974
22975
22976
22977
22978
22979
22980
22981
22982
22983
22984
22985
22986
22987
22988
22989
22990
22991
22992
22993
22994
22995
22996
22997
22998
22999
23000
23001
23002
23003
23004
23005
23006
23007
23008
23009
23010
23011
23012
23013
23014
23015
23016
23017
23018
23019
23020
23021
23022
23023
23024
23025
23026
23027
23028
23029
23030
23031
23032
23033
23034
23035
23036
23037
23038
23039
23040
23041
23042
23043
23044
23045
23046
23047
23048
23049
23050
23051
23052
23053
23054
23055
23056
23057
23058
23059
23060
23061
23062
23063
23064
23065
23066
23067
23068
23069
23070
23071
23072
23073
23074
23075
23076
23077
23078
23079
23080
23081
23082
23083
23084
23085
23086
23087
23088
23089
23090
23091
23092
23093
23094
23095
23096
23097
23098
23099
23100
23101
23102
23103
23104
23105
23106
23107
23108
23109
23110
23111
23112
23113
23114
23115
23116
23117
23118
23119
23120
23121
23122
23123
23124
23125
23126
23127
23128
23129
23130
23131
23132
23133
23134
23135
23136
23137
23138
23139
23140
23141
23142
23143
23144
23145
23146
23147
23148
23149
23150
23151
23152
23153
23154
23155
23156
23157
23158
23159
23160
23161
23162
23163
23164
23165
23166
23167
23168
23169
23170
23171
23172
23173
23174
23175
23176
23177
23178
23179
23180
23181
23182
23183
23184
23185
23186
23187
23188
23189
23190
23191
23192
23193
23194
23195
23196
23197
23198
23199
23200
23201
23202
23203
23204
23205
23206
23207
23208
23209
23210
23211
23212
23213
23214
23215
23216
23217
23218
23219
23220
23221
23222
23223
23224
23225
23226
23227
23228
23229
23230
23231
23232
23233
23234
23235
23236
23237
23238
23239
23240
23241
23242
23243
23244
23245
23246
23247
23248
23249
23250
23251
23252
23253
23254
23255
23256
23257
23258
23259
23260
23261
23262
23263
23264
23265
23266
23267
23268
23269
23270
23271
23272
23273
23274
23275
23276
23277
23278
23279
23280
23281
23282
23283
23284
23285
23286
23287
23288
23289
23290
23291
23292
23293
23294
23295
23296
23297
23298
23299
23300
23301
23302
23303
23304
23305
23306
23307
23308
23309
23310
23311
23312
23313
23314
23315
23316
23317
23318
23319
23320
23321
23322
23323
23324
23325
23326
23327
23328
23329
23330
23331
23332
23333
23334
23335
23336
23337
23338
23339
23340
23341
23342
23343
23344
23345
23346
23347
23348
23349
23350
23351
23352
23353
23354
23355
23356
23357
23358
23359
23360
23361
23362
23363
23364
23365
23366
23367
23368
23369
23370
23371
23372
23373
23374
23375
23376
23377
23378
23379
23380
23381
23382
23383
23384
23385
23386
23387
23388
23389
23390
23391
23392
23393
23394
23395
23396
23397
23398
23399
23400
23401
23402
23403
23404
23405
23406
23407
23408
23409
23410
23411
23412
23413
23414
23415
23416
23417
23418
23419
23420
23421
23422
23423
23424
23425
23426
23427
23428
23429
23430
23431
23432
23433
23434
23435
23436
23437
23438
23439
23440
23441
23442
23443
23444
23445
23446
23447
23448
23449
23450
23451
23452
23453
23454
23455
23456
23457
23458
23459
23460
23461
23462
23463
23464
23465
23466
23467
23468
23469
23470
23471
23472
23473
23474
23475
23476
23477
23478
23479
23480
23481
23482
23483
23484
23485
23486
23487
23488
23489
23490
23491
23492
23493
23494
23495
23496
23497
23498
23499
23500
23501
23502
23503
23504
23505
23506
23507
23508
23509
23510
23511
23512
23513
23514
23515
23516
23517
23518
23519
23520
23521
23522
23523
23524
23525
23526
23527
23528
23529
23530
23531
23532
23533
23534
23535
23536
23537
23538
23539
23540
23541
23542
23543
23544
23545
23546
23547
23548
23549
23550
23551
23552
23553
23554
23555
23556
23557
23558
23559
23560
23561
23562
23563
23564
23565
23566
23567
23568
23569
23570
23571
23572
23573
23574
23575
23576
23577
23578
23579
23580
23581
23582
23583
23584
23585
23586
23587
23588
23589
23590
23591
23592
23593
23594
23595
23596
23597
23598
23599
23600
23601
23602
23603
23604
23605
23606
23607
23608
23609
23610
23611
23612
23613
23614
23615
23616
23617
23618
23619
23620
23621
23622
23623
23624
23625
23626
23627
23628
23629
23630
23631
23632
23633
23634
23635
23636
23637
23638
23639
23640
23641
23642
23643
23644
23645
23646
23647
23648
23649
23650
23651
23652
23653
23654
23655
23656
23657
23658
23659
23660
23661
23662
23663
23664
23665
23666
23667
23668
23669
23670
23671
23672
23673
23674
23675
23676
23677
23678
23679
23680
23681
23682
23683
23684
23685
23686
23687
23688
23689
23690
23691
23692
23693
23694
23695
23696
23697
23698
23699
23700
23701
23702
23703
23704
23705
23706
23707
23708
23709
23710
23711
23712
23713
23714
23715
23716
23717
23718
23719
23720
23721
23722
23723
23724
23725
23726
23727
23728
23729
23730
23731
23732
23733
23734
23735
23736
23737
23738
23739
23740
23741
23742
23743
23744
23745
23746
23747
23748
23749
23750
23751
23752
23753
23754
23755
23756
23757
23758
23759
23760
23761
23762
23763
23764
23765
23766
23767
23768
23769
23770
23771
23772
23773
23774
23775
23776
23777
23778
23779
23780
23781
23782
23783
23784
23785
23786
23787
23788
23789
23790
23791
23792
23793
23794
23795
23796
23797
23798
23799
23800
23801
23802
23803
23804
23805
23806
23807
23808
23809
23810
23811
23812
23813
23814
23815
23816
23817
23818
23819
23820
23821
23822
23823
23824
23825
23826
23827
23828
23829
23830
23831
23832
23833
23834
23835
23836
23837
23838
23839
23840
23841
23842
23843
23844
23845
23846
23847
23848
23849
23850
23851
23852
23853
23854
23855
23856
23857
23858
23859
23860
23861
23862
23863
23864
23865
23866
23867
23868
23869
23870
23871
23872
23873
23874
23875
23876
23877
23878
23879
23880
23881
23882
23883
23884
23885
23886
23887
23888
23889
23890
23891
23892
23893
23894
23895
23896
23897
23898
23899
23900
23901
23902
23903
23904
23905
23906
23907
23908
23909
23910
23911
23912
23913
23914
23915
23916
23917
23918
23919
23920
23921
23922
23923
23924
23925
23926
23927
23928
23929
23930
23931
23932
23933
23934
23935
23936
23937
23938
23939
23940
23941
23942
23943
23944
23945
23946
23947
23948
23949
23950
23951
23952
23953
23954
23955
23956
23957
23958
23959
23960
23961
23962
23963
23964
23965
23966
23967
23968
23969
23970
23971
23972
23973
23974
23975
23976
23977
23978
23979
23980
23981
23982
23983
23984
23985
23986
23987
23988
23989
23990
23991
23992
23993
23994
23995
23996
23997
23998
23999
24000
24001
24002
24003
24004
24005
24006
24007
24008
24009
24010
24011
24012
24013
24014
24015
24016
24017
24018
24019
24020
24021
24022
24023
24024
24025
24026
24027
24028
24029
24030
24031
24032
24033
24034
24035
24036
24037
24038
24039
24040
24041
24042
24043
24044
24045
24046
24047
24048
24049
24050
24051
24052
24053
24054
24055
24056
24057
24058
24059
24060
24061
24062
24063
24064
24065
24066
24067
24068
24069
24070
24071
24072
24073
24074
24075
24076
24077
24078
24079
24080
24081
24082
24083
24084
24085
24086
24087
24088
24089
24090
24091
24092
24093
24094
24095
24096
24097
24098
24099
24100
24101
24102
24103
24104
24105
24106
24107
24108
24109
24110
24111
24112
24113
24114
24115
24116
24117
24118
24119
24120
24121
24122
24123
24124
24125
24126
24127
24128
24129
24130
24131
24132
24133
24134
24135
24136
24137
24138
24139
24140
24141
24142
24143
24144
24145
24146
24147
24148
24149
24150
24151
24152
24153
24154
24155
24156
24157
24158
24159
24160
24161
24162
24163
24164
24165
24166
24167
24168
24169
24170
24171
24172
24173
24174
24175
24176
24177
24178
24179
24180
24181
24182
24183
24184
24185
24186
24187
24188
24189
24190
24191
24192
24193
24194
24195
24196
24197
24198
24199
24200
24201
24202
24203
24204
24205
24206
24207
24208
24209
24210
24211
24212
24213
24214
24215
24216
24217
24218
24219
24220
24221
24222
24223
24224
24225
24226
24227
24228
24229
24230
24231
24232
24233
24234
24235
24236
24237
24238
24239
24240
24241
24242
24243
24244
24245
24246
24247
24248
24249
24250
24251
24252
24253
24254
24255
24256
24257
24258
24259
24260
24261
24262
24263
24264
24265
24266
24267
24268
24269
24270
24271
24272
24273
24274
24275
24276
24277
24278
24279
24280
24281
24282
24283
24284
24285
24286
24287
24288
24289
24290
24291
24292
24293
24294
24295
24296
24297
24298
24299
24300
24301
24302
24303
24304
24305
24306
24307
24308
24309
24310
24311
24312
24313
24314
24315
24316
24317
24318
24319
24320
24321
24322
24323
24324
24325
24326
24327
24328
24329
24330
24331
24332
24333
24334
24335
24336
24337
24338
24339
24340
24341
24342
24343
24344
24345
24346
24347
24348
24349
24350
24351
24352
24353
24354
24355
24356
24357
24358
24359
24360
24361
24362
24363
24364
24365
24366
24367
24368
24369
24370
24371
24372
24373
24374
24375
24376
24377
24378
24379
24380
24381
24382
24383
24384
24385
24386
24387
24388
24389
24390
24391
24392
24393
24394
24395
24396
24397
24398
24399
24400
24401
24402
24403
24404
24405
24406
24407
24408
24409
24410
24411
24412
24413
24414
24415
24416
24417
24418
24419
24420
24421
24422
24423
24424
24425
24426
24427
24428
24429
24430
24431
24432
24433
24434
24435
24436
24437
24438
24439
24440
24441
24442
24443
24444
24445
24446
24447
24448
24449
24450
24451
24452
24453
24454
24455
24456
24457
24458
24459
24460
24461
24462
24463
24464
24465
24466
24467
24468
24469
24470
24471
24472
24473
24474
24475
24476
24477
24478
24479
24480
24481
24482
24483
24484
24485
24486
24487
24488
24489
24490
24491
24492
24493
24494
24495
24496
24497
24498
24499
24500
24501
24502
24503
24504
24505
24506
24507
24508
24509
24510
24511
24512
24513
24514
24515
24516
24517
24518
24519
24520
24521
24522
24523
24524
24525
24526
24527
24528
24529
24530
24531
24532
24533
24534
24535
24536
24537
24538
24539
24540
24541
24542
24543
24544
24545
24546
24547
24548
24549
24550
24551
24552
24553
24554
24555
24556
24557
24558
24559
24560
24561
24562
24563
24564
24565
24566
24567
24568
24569
24570
24571
24572
24573
24574
24575
24576
24577
24578
24579
24580
24581
24582
24583
24584
24585
24586
24587
24588
24589
24590
24591
24592
24593
24594
24595
24596
24597
24598
24599
24600
24601
24602
24603
24604
24605
24606
24607
24608
24609
24610
24611
24612
24613
24614
24615
24616
24617
24618
24619
24620
24621
24622
24623
24624
24625
24626
24627
24628
24629
24630
24631
24632
24633
24634
24635
24636
24637
24638
24639
24640
24641
24642
24643
24644
24645
24646
24647
24648
24649
24650
24651
24652
24653
24654
24655
24656
24657
24658
24659
24660
24661
24662
24663
24664
24665
24666
24667
24668
24669
24670
24671
24672
24673
24674
24675
24676
24677
24678
24679
24680
24681
24682
24683
24684
24685
24686
24687
24688
24689
24690
24691
24692
24693
24694
24695
24696
24697
24698
24699
24700
24701
24702
24703
24704
24705
24706
24707
24708
24709
24710
24711
24712
24713
24714
24715
24716
24717
24718
24719
24720
24721
24722
24723
24724
24725
24726
24727
24728
24729
24730
24731
24732
24733
24734
24735
24736
24737
24738
24739
24740
24741
24742
24743
24744
24745
24746
24747
24748
24749
24750
24751
24752
24753
24754
24755
24756
24757
24758
24759
24760
24761
24762
24763
24764
24765
24766
24767
24768
24769
24770
24771
24772
24773
24774
24775
24776
24777
24778
24779
24780
24781
24782
24783
24784
24785
24786
24787
24788
24789
24790
24791
24792
24793
24794
24795
24796
24797
24798
24799
24800
24801
24802
24803
24804
24805
24806
24807
24808
24809
24810
24811
24812
24813
24814
24815
24816
24817
24818
24819
24820
24821
24822
24823
24824
24825
24826
24827
24828
24829
24830
24831
24832
24833
24834
24835
24836
24837
24838
24839
24840
24841
24842
24843
24844
24845
24846
24847
24848
24849
24850
24851
24852
24853
24854
24855
24856
24857
24858
24859
24860
24861
24862
24863
24864
24865
24866
24867
24868
24869
24870
24871
24872
24873
24874
24875
24876
24877
24878
24879
24880
24881
24882
24883
24884
24885
24886
24887
24888
24889
24890
24891
24892
24893
24894
24895
24896
24897
24898
24899
24900
24901
24902
24903
24904
24905
24906
24907
24908
24909
24910
24911
24912
24913
24914
24915
24916
24917
24918
24919
24920
24921
24922
24923
24924
24925
24926
24927
24928
24929
24930
24931
24932
24933
24934
24935
24936
24937
24938
24939
24940
24941
24942
24943
24944
24945
24946
24947
24948
24949
24950
24951
24952
24953
24954
24955
24956
24957
24958
24959
24960
24961
24962
24963
24964
24965
24966
24967
24968
24969
24970
24971
24972
24973
24974
24975
24976
24977
24978
24979
24980
24981
24982
24983
24984
24985
24986
24987
24988
24989
24990
24991
24992
24993
24994
24995
24996
24997
24998
24999
25000
25001
25002
25003
25004
25005
25006
25007
25008
25009
25010
25011
25012
25013
25014
25015
25016
25017
25018
25019
25020
25021
25022
25023
25024
25025
25026
25027
25028
25029
25030
25031
25032
25033
25034
25035
25036
25037
25038
25039
25040
25041
25042
25043
25044
25045
25046
25047
25048
25049
25050
25051
25052
25053
25054
25055
25056
25057
25058
25059
25060
25061
25062
25063
25064
25065
25066
25067
25068
25069
25070
25071
25072
25073
25074
25075
25076
25077
25078
25079
25080
25081
25082
25083
25084
25085
25086
25087
25088
25089
25090
25091
25092
25093
25094
25095
25096
25097
25098
25099
25100
25101
25102
25103
25104
25105
25106
25107
25108
25109
25110
25111
25112
25113
25114
25115
25116
25117
25118
25119
25120
25121
25122
25123
25124
25125
25126
25127
25128
25129
25130
25131
25132
25133
25134
25135
25136
25137
25138
25139
25140
25141
25142
25143
25144
25145
25146
25147
25148
25149
25150
25151
25152
25153
25154
25155
25156
25157
25158
25159
25160
25161
25162
25163
25164
25165
25166
25167
25168
25169
25170
25171
25172
25173
25174
25175
25176
25177
25178
25179
25180
25181
25182
25183
25184
25185
25186
25187
25188
25189
25190
25191
25192
25193
25194
25195
25196
25197
25198
25199
25200
25201
25202
25203
25204
25205
25206
25207
25208
25209
25210
25211
25212
25213
25214
25215
25216
25217
25218
25219
25220
25221
25222
25223
25224
25225
25226
25227
25228
25229
25230
25231
25232
25233
25234
25235
25236
25237
25238
25239
25240
25241
25242
25243
25244
25245
25246
25247
25248
25249
25250
25251
25252
25253
25254
25255
25256
25257
25258
25259
25260
25261
25262
25263
25264
25265
25266
25267
25268
25269
25270
25271
25272
25273
25274
25275
25276
25277
25278
25279
25280
25281
25282
25283
25284
25285
25286
25287
25288
25289
25290
25291
25292
25293
25294
25295
25296
25297
25298
25299
25300
25301
25302
25303
25304
25305
25306
25307
25308
25309
25310
25311
25312
25313
25314
25315
25316
25317
25318
25319
25320
25321
25322
25323
25324
25325
25326
25327
25328
25329
25330
25331
25332
25333
25334
25335
25336
25337
25338
25339
25340
25341
25342
25343
25344
25345
25346
25347
25348
25349
25350
25351
25352
25353
25354
25355
25356
25357
25358
25359
25360
25361
25362
25363
25364
25365
25366
25367
25368
25369
25370
25371
25372
25373
25374
25375
25376
25377
25378
25379
25380
25381
25382
25383
25384
25385
25386
25387
25388
25389
25390
25391
25392
25393
25394
25395
25396
25397
25398
25399
25400
25401
25402
25403
25404
25405
25406
25407
25408
25409
25410
25411
25412
25413
25414
25415
25416
25417
25418
25419
25420
25421
25422
25423
25424
25425
25426
25427
25428
25429
25430
25431
25432
25433
25434
25435
25436
25437
25438
25439
25440
25441
25442
25443
25444
25445
25446
25447
25448
25449
25450
25451
25452
25453
25454
25455
25456
25457
25458
25459
25460
25461
25462
25463
25464
25465
25466
25467
25468
25469
25470
25471
25472
25473
25474
25475
25476
25477
25478
25479
25480
25481
25482
25483
25484
25485
25486
25487
25488
25489
25490
25491
25492
25493
25494
25495
25496
25497
25498
25499
25500
25501
25502
25503
25504
25505
25506
25507
25508
25509
25510
25511
25512
25513
25514
25515
25516
25517
25518
25519
25520
25521
25522
25523
25524
25525
25526
25527
25528
25529
25530
25531
25532
25533
25534
25535
25536
25537
25538
25539
25540
25541
25542
25543
25544
25545
25546
25547
25548
25549
25550
25551
25552
25553
25554
25555
25556
25557
25558
25559
25560
25561
25562
25563
25564
25565
25566
25567
25568
25569
25570
25571
25572
25573
25574
25575
25576
25577
25578
25579
25580
25581
25582
25583
25584
25585
25586
25587
25588
25589
25590
25591
25592
25593
25594
25595
25596
25597
25598
25599
25600
25601
25602
25603
25604
25605
25606
25607
25608
25609
25610
25611
25612
25613
25614
25615
25616
25617
25618
25619
25620
25621
25622
25623
25624
25625
25626
25627
25628
25629
25630
25631
25632
25633
25634
25635
25636
25637
25638
25639
25640
25641
25642
25643
25644
25645
25646
25647
25648
25649
25650
25651
25652
25653
25654
25655
25656
25657
25658
25659
25660
25661
25662
25663
25664
25665
25666
25667
25668
25669
25670
25671
25672
25673
25674
25675
25676
25677
25678
25679
25680
25681
25682
25683
25684
25685
25686
25687
25688
25689
25690
25691
25692
25693
25694
25695
25696
25697
25698
25699
25700
25701
25702
25703
25704
25705
25706
25707
25708
25709
25710
25711
25712
25713
25714
25715
25716
25717
25718
25719
25720
25721
25722
25723
25724
25725
25726
25727
25728
25729
25730
25731
25732
25733
25734
25735
25736
25737
25738
25739
25740
25741
25742
25743
25744
25745
25746
25747
25748
25749
25750
25751
25752
25753
25754
25755
25756
25757
25758
25759
25760
25761
25762
25763
25764
25765
25766
25767
25768
25769
25770
25771
25772
25773
25774
25775
25776
25777
25778
25779
25780
25781
25782
25783
25784
25785
25786
25787
25788
25789
25790
25791
25792
25793
25794
25795
25796
25797
25798
25799
25800
25801
25802
25803
25804
25805
25806
25807
25808
25809
25810
25811
25812
25813
25814
25815
25816
25817
25818
25819
25820
25821
25822
25823
25824
25825
25826
25827
25828
25829
25830
25831
25832
25833
25834
25835
25836
25837
25838
25839
25840
25841
25842
25843
25844
25845
25846
25847
25848
25849
25850
25851
25852
25853
25854
25855
25856
25857
25858
25859
25860
25861
25862
25863
25864
25865
25866
25867
25868
25869
25870
25871
25872
25873
25874
25875
25876
25877
25878
25879
25880
25881
25882
25883
25884
25885
25886
25887
25888
25889
25890
25891
25892
25893
25894
25895
25896
25897
25898
25899
25900
25901
25902
25903
25904
25905
25906
25907
25908
25909
25910
25911
25912
25913
25914
25915
25916
25917
25918
25919
25920
25921
25922
25923
25924
25925
25926
25927
25928
25929
25930
25931
25932
25933
25934
25935
25936
25937
25938
25939
25940
25941
25942
25943
25944
25945
25946
25947
25948
25949
25950
25951
25952
25953
25954
25955
25956
25957
25958
25959
25960
25961
25962
25963
25964
25965
25966
25967
25968
25969
25970
25971
25972
25973
25974
25975
25976
25977
25978
25979
25980
25981
25982
25983
25984
25985
25986
25987
25988
25989
25990
25991
25992
25993
25994
25995
25996
25997
25998
25999
26000
26001
26002
26003
26004
26005
26006
26007
26008
26009
26010
26011
26012
26013
26014
26015
26016
26017
26018
26019
26020
26021
26022
26023
26024
26025
26026
26027
26028
26029
26030
26031
26032
26033
26034
26035
26036
26037
26038
26039
26040
26041
26042
26043
26044
26045
26046
26047
26048
26049
26050
26051
26052
26053
26054
26055
26056
26057
26058
26059
26060
26061
26062
26063
26064
26065
26066
26067
26068
26069
26070
26071
26072
26073
26074
26075
26076
26077
26078
26079
26080
26081
26082
26083
26084
26085
26086
26087
26088
26089
26090
26091
26092
26093
26094
26095
26096
26097
26098
26099
26100
26101
26102
26103
26104
26105
26106
26107
26108
26109
26110
26111
26112
26113
26114
26115
26116
26117
26118
26119
26120
26121
26122
26123
26124
26125
26126
26127
26128
26129
26130
26131
26132
26133
26134
26135
26136
26137
26138
26139
26140
26141
26142
26143
26144
26145
26146
26147
26148
26149
26150
26151
26152
26153
26154
26155
26156
26157
26158
26159
26160
26161
26162
26163
26164
26165
26166
26167
26168
26169
26170
26171
26172
26173
26174
26175
26176
26177
26178
26179
26180
26181
26182
26183
26184
26185
26186
26187
26188
26189
26190
26191
26192
26193
26194
26195
26196
26197
26198
26199
26200
26201
26202
26203
26204
26205
26206
26207
26208
26209
26210
26211
26212
26213
26214
26215
26216
26217
26218
26219
26220
26221
26222
26223
26224
26225
26226
26227
26228
26229
26230
26231
26232
26233
26234
26235
26236
26237
26238
26239
26240
26241
26242
26243
26244
26245
26246
26247
26248
26249
26250
26251
26252
26253
26254
26255
26256
26257
26258
26259
26260
26261
26262
26263
26264
26265
26266
26267
26268
26269
26270
26271
26272
26273
26274
26275
26276
26277
26278
26279
26280
26281
26282
26283
26284
26285
26286
26287
26288
26289
26290
26291
26292
26293
26294
26295
26296
26297
26298
26299
26300
26301
26302
26303
26304
26305
26306
26307
26308
26309
26310
26311
26312
26313
26314
26315
26316
26317
26318
26319
26320
26321
26322
26323
26324
26325
26326
26327
26328
26329
26330
26331
26332
26333
26334
26335
26336
26337
26338
26339
26340
26341
26342
26343
26344
26345
26346
26347
26348
26349
26350
26351
26352
26353
26354
26355
26356
26357
26358
26359
26360
26361
26362
26363
26364
26365
26366
26367
26368
26369
26370
26371
26372
26373
26374
26375
26376
26377
26378
26379
26380
26381
26382
26383
26384
26385
26386
26387
26388
26389
26390
26391
26392
26393
26394
26395
26396
26397
26398
26399
26400
26401
26402
26403
26404
26405
26406
26407
26408
26409
26410
26411
26412
26413
26414
26415
26416
26417
26418
26419
26420
26421
26422
26423
26424
26425
26426
26427
26428
26429
26430
26431
26432
26433
26434
26435
26436
26437
26438
26439
26440
26441
26442
26443
26444
26445
26446
26447
26448
26449
26450
26451
26452
26453
26454
26455
26456
26457
26458
26459
26460
26461
26462
26463
26464
26465
26466
26467
26468
26469
26470
26471
26472
26473
26474
26475
26476
26477
26478
26479
26480
26481
26482
26483
26484
26485
26486
26487
26488
26489
26490
26491
26492
26493
26494
26495
26496
26497
26498
26499
26500
26501
26502
26503
26504
26505
26506
26507
26508
26509
26510
26511
26512
26513
26514
26515
26516
26517
26518
26519
26520
26521
26522
26523
26524
26525
26526
26527
26528
26529
26530
26531
26532
26533
26534
26535
26536
26537
26538
26539
26540
26541
26542
26543
26544
26545
26546
26547
26548
26549
26550
26551
26552
26553
26554
26555
26556
26557
26558
26559
26560
26561
26562
26563
26564
26565
26566
26567
26568
26569
26570
26571
26572
26573
26574
26575
26576
26577
26578
26579
26580
26581
26582
26583
26584
26585
26586
26587
26588
26589
26590
26591
26592
26593
26594
26595
26596
26597
26598
26599
26600
26601
26602
26603
26604
26605
26606
26607
26608
26609
26610
26611
26612
26613
26614
26615
26616
26617
26618
26619
26620
26621
26622
26623
26624
26625
26626
26627
26628
26629
26630
26631
26632
26633
26634
26635
26636
26637
26638
26639
26640
26641
26642
26643
26644
26645
26646
26647
26648
26649
26650
26651
26652
26653
26654
26655
26656
26657
26658
26659
26660
26661
26662
26663
26664
26665
26666
26667
26668
26669
26670
26671
26672
26673
26674
26675
26676
26677
26678
26679
26680
26681
26682
26683
26684
26685
26686
26687
26688
26689
26690
26691
26692
26693
26694
26695
26696
26697
26698
26699
26700
26701
26702
26703
26704
26705
26706
26707
26708
26709
26710
26711
26712
26713
26714
26715
26716
26717
26718
26719
26720
26721
26722
26723
26724
26725
26726
26727
26728
26729
26730
26731
26732
26733
26734
26735
26736
26737
26738
26739
26740
26741
26742
26743
26744
26745
26746
26747
26748
26749
26750
26751
26752
26753
26754
26755
26756
26757
26758
26759
26760
26761
26762
26763
26764
26765
26766
26767
26768
26769
26770
26771
26772
26773
26774
26775
26776
26777
26778
26779
26780
26781
26782
26783
26784
26785
26786
26787
26788
26789
26790
26791
26792
26793
26794
26795
26796
26797
26798
26799
26800
26801
26802
26803
26804
26805
26806
26807
26808
26809
26810
26811
26812
26813
26814
26815
26816
26817
26818
26819
26820
26821
26822
26823
26824
26825
26826
26827
26828
26829
26830
26831
26832
26833
26834
26835
26836
26837
26838
26839
26840
26841
26842
26843
26844
26845
26846
26847
26848
26849
26850
26851
26852
26853
26854
26855
26856
26857
26858
26859
26860
26861
26862
26863
26864
26865
26866
26867
26868
26869
26870
26871
26872
26873
26874
26875
26876
26877
26878
26879
26880
26881
26882
26883
26884
26885
26886
26887
26888
26889
26890
26891
26892
26893
26894
26895
26896
26897
26898
26899
26900
26901
26902
26903
26904
26905
26906
26907
26908
26909
26910
26911
26912
26913
26914
26915
26916
26917
26918
26919
26920
26921
26922
26923
26924
26925
26926
26927
26928
26929
26930
26931
26932
26933
26934
26935
26936
26937
26938
26939
26940
26941
26942
26943
26944
26945
26946
26947
26948
26949
26950
26951
26952
26953
26954
26955
26956
26957
26958
26959
26960
26961
26962
26963
26964
26965
26966
26967
26968
26969
26970
26971
26972
26973
26974
26975
26976
26977
26978
26979
26980
26981
26982
26983
26984
26985
26986
26987
26988
26989
26990
26991
26992
26993
26994
26995
26996
26997
26998
26999
27000
27001
27002
27003
27004
27005
27006
27007
27008
27009
27010
27011
27012
27013
27014
27015
27016
27017
27018
27019
27020
27021
27022
27023
27024
27025
27026
27027
27028
27029
27030
27031
27032
27033
27034
27035
27036
27037
27038
27039
27040
27041
27042
27043
27044
27045
27046
27047
27048
27049
27050
27051
27052
27053
27054
27055
27056
27057
27058
27059
27060
27061
27062
27063
27064
27065
27066
27067
27068
27069
27070
27071
27072
27073
27074
27075
27076
27077
27078
27079
27080
27081
27082
27083
27084
27085
27086
27087
27088
27089
27090
27091
27092
27093
27094
27095
27096
27097
27098
27099
27100
27101
27102
27103
27104
27105
27106
27107
27108
27109
27110
27111
27112
27113
27114
27115
27116
27117
27118
27119
27120
27121
27122
27123
27124
27125
27126
27127
27128
27129
27130
27131
27132
27133
27134
27135
27136
27137
27138
27139
27140
27141
27142
27143
27144
27145
27146
27147
27148
27149
27150
27151
27152
27153
27154
27155
27156
27157
27158
27159
27160
27161
27162
27163
27164
27165
27166
27167
27168
27169
27170
27171
27172
27173
27174
27175
27176
27177
27178
27179
27180
27181
27182
27183
27184
27185
27186
27187
27188
27189
27190
27191
27192
27193
27194
27195
27196
27197
27198
27199
27200
27201
27202
27203
27204
27205
27206
27207
27208
27209
27210
27211
27212
27213
27214
27215
27216
27217
27218
27219
27220
27221
27222
27223
27224
27225
27226
27227
27228
27229
27230
27231
27232
27233
27234
27235
27236
27237
27238
27239
27240
27241
27242
27243
27244
27245
27246
27247
27248
27249
27250
27251
27252
27253
27254
27255
27256
27257
27258
27259
27260
27261
27262
27263
27264
27265
27266
27267
27268
27269
27270
27271
27272
27273
27274
27275
27276
27277
27278
27279
27280
27281
27282
27283
27284
27285
27286
27287
27288
27289
27290
27291
27292
27293
27294
27295
27296
27297
27298
27299
27300
27301
27302
27303
27304
27305
27306
27307
27308
27309
27310
27311
27312
27313
27314
27315
27316
27317
27318
27319
27320
27321
27322
27323
27324
27325
27326
27327
27328
27329
27330
27331
27332
27333
27334
27335
27336
27337
27338
27339
27340
27341
27342
27343
27344
27345
27346
27347
27348
27349
27350
27351
27352
27353
27354
27355
27356
27357
27358
27359
27360
27361
27362
27363
27364
27365
27366
27367
27368
27369
27370
27371
27372
27373
27374
27375
27376
27377
27378
27379
27380
27381
27382
27383
27384
27385
27386
27387
27388
27389
27390
27391
27392
27393
27394
27395
27396
27397
27398
27399
27400
27401
27402
27403
27404
27405
27406
27407
27408
27409
27410
27411
27412
27413
27414
27415
27416
27417
27418
27419
27420
27421
27422
27423
27424
27425
27426
27427
27428
27429
27430
27431
27432
27433
27434
27435
27436
27437
27438
27439
27440
27441
27442
27443
27444
27445
27446
27447
27448
27449
27450
27451
27452
27453
27454
27455
27456
27457
27458
27459
27460
27461
27462
27463
27464
27465
27466
27467
27468
27469
27470
27471
27472
27473
27474
27475
27476
27477
27478
27479
27480
27481
27482
27483
27484
27485
27486
27487
27488
27489
27490
27491
27492
27493
27494
27495
27496
27497
27498
27499
27500
27501
27502
27503
27504
27505
27506
27507
27508
27509
27510
27511
27512
27513
27514
27515
27516
27517
27518
27519
27520
27521
27522
27523
27524
27525
27526
27527
27528
27529
27530
27531
27532
27533
27534
27535
27536
27537
27538
27539
27540
27541
27542
27543
27544
27545
27546
27547
27548
27549
27550
27551
27552
27553
27554
27555
27556
27557
27558
27559
27560
27561
27562
27563
27564
27565
27566
27567
27568
27569
27570
27571
27572
27573
27574
27575
27576
27577
27578
27579
27580
27581
27582
27583
27584
27585
27586
27587
27588
27589
27590
27591
27592
27593
27594
27595
27596
27597
27598
27599
27600
27601
27602
27603
27604
27605
27606
27607
27608
27609
27610
27611
27612
27613
27614
27615
27616
27617
27618
27619
27620
27621
27622
27623
27624
27625
27626
27627
27628
27629
27630
27631
27632
27633
27634
27635
27636
27637
27638
27639
27640
27641
27642
27643
27644
27645
27646
27647
27648
27649
27650
27651
27652
27653
27654
27655
27656
27657
27658
27659
27660
27661
27662
27663
27664
27665
27666
27667
27668
27669
27670
27671
27672
27673
27674
27675
27676
27677
27678
27679
27680
27681
27682
27683
27684
27685
27686
27687
27688
27689
27690
27691
27692
27693
27694
27695
27696
27697
27698
27699
27700
27701
27702
27703
27704
27705
27706
27707
27708
27709
27710
27711
27712
27713
27714
27715
27716
27717
27718
27719
27720
27721
27722
27723
27724
27725
27726
27727
27728
27729
27730
27731
27732
27733
27734
27735
27736
27737
27738
27739
27740
27741
27742
27743
27744
27745
27746
27747
27748
27749
27750
27751
27752
27753
27754
27755
27756
27757
27758
27759
27760
27761
27762
27763
27764
27765
27766
27767
27768
27769
27770
27771
27772
27773
27774
27775
27776
27777
27778
27779
27780
27781
27782
27783
27784
27785
27786
27787
27788
27789
27790
27791
27792
27793
27794
27795
27796
27797
27798
27799
27800
27801
27802
27803
27804
27805
27806
27807
27808
27809
27810
27811
27812
27813
27814
27815
27816
27817
27818
27819
27820
27821
27822
27823
27824
27825
27826
27827
27828
27829
27830
27831
27832
27833
27834
27835
27836
27837
27838
27839
27840
27841
27842
27843
27844
27845
27846
27847
27848
27849
27850
27851
27852
27853
27854
27855
27856
27857
27858
27859
27860
27861
27862
27863
27864
27865
27866
27867
27868
27869
27870
27871
27872
27873
27874
27875
27876
27877
27878
27879
27880
27881
27882
27883
27884
27885
27886
27887
27888
27889
27890
27891
27892
27893
27894
27895
27896
27897
27898
27899
27900
27901
27902
27903
27904
27905
27906
27907
27908
27909
27910
27911
27912
27913
27914
27915
27916
27917
27918
27919
27920
27921
27922
27923
27924
27925
27926
27927
27928
27929
27930
27931
27932
27933
27934
27935
27936
27937
27938
27939
27940
27941
27942
27943
27944
27945
27946
27947
27948
27949
27950
27951
27952
27953
27954
27955
27956
27957
27958
27959
27960
27961
27962
27963
27964
27965
27966
27967
27968
27969
27970
27971
27972
27973
27974
27975
27976
27977
27978
27979
27980
27981
27982
27983
27984
27985
27986
27987
27988
27989
27990
27991
27992
27993
27994
27995
27996
27997
27998
27999
28000
28001
28002
28003
28004
28005
28006
28007
28008
28009
28010
28011
28012
28013
28014
28015
28016
28017
28018
28019
28020
28021
28022
28023
28024
28025
28026
28027
28028
28029
28030
28031
28032
28033
28034
28035
28036
28037
28038
28039
28040
28041
28042
28043
28044
28045
28046
28047
28048
28049
28050
28051
28052
28053
28054
28055
28056
28057
28058
28059
28060
28061
28062
28063
28064
28065
28066
28067
28068
28069
28070
28071
28072
28073
28074
28075
28076
28077
28078
28079
28080
28081
28082
28083
28084
28085
28086
28087
28088
28089
28090
28091
28092
28093
28094
28095
28096
28097
28098
28099
28100
28101
28102
28103
28104
28105
28106
28107
28108
28109
28110
28111
28112
28113
28114
28115
28116
28117
28118
28119
28120
28121
28122
28123
28124
28125
28126
28127
28128
28129
28130
28131
28132
28133
28134
28135
28136
28137
28138
28139
28140
28141
28142
28143
28144
28145
28146
28147
28148
28149
28150
28151
28152
28153
28154
28155
28156
28157
28158
28159
28160
28161
28162
28163
28164
28165
28166
28167
28168
28169
28170
28171
28172
28173
28174
28175
28176
28177
28178
28179
28180
28181
28182
28183
28184
28185
28186
28187
28188
28189
28190
28191
28192
28193
28194
28195
28196
28197
28198
28199
28200
28201
28202
28203
28204
28205
28206
28207
28208
28209
28210
28211
28212
28213
28214
28215
28216
28217
28218
28219
28220
28221
28222
28223
28224
28225
28226
28227
28228
28229
28230
28231
28232
28233
28234
28235
28236
28237
28238
28239
28240
28241
28242
28243
28244
28245
28246
28247
28248
28249
28250
28251
28252
28253
28254
28255
28256
28257
28258
28259
28260
28261
28262
28263
28264
28265
28266
28267
28268
28269
28270
28271
28272
28273
28274
28275
28276
28277
28278
28279
28280
28281
28282
28283
28284
28285
28286
28287
28288
28289
28290
28291
28292
28293
28294
28295
28296
28297
28298
28299
28300
28301
28302
28303
28304
28305
28306
28307
28308
28309
28310
28311
28312
28313
28314
28315
28316
28317
28318
28319
28320
28321
28322
28323
28324
28325
28326
28327
28328
28329
28330
28331
28332
28333
28334
28335
28336
28337
28338
28339
28340
28341
28342
28343
28344
28345
28346
28347
28348
28349
28350
28351
28352
28353
28354
28355
28356
28357
28358
28359
28360
28361
28362
28363
28364
28365
28366
28367
28368
28369
28370
28371
28372
28373
28374
28375
28376
28377
28378
28379
28380
28381
28382
28383
28384
28385
28386
28387
28388
28389
28390
28391
28392
28393
28394
28395
28396
28397
28398
28399
28400
28401
28402
28403
28404
28405
28406
28407
28408
28409
28410
28411
28412
28413
28414
28415
28416
28417
28418
28419
28420
28421
28422
28423
28424
28425
28426
28427
28428
28429
28430
28431
28432
28433
28434
28435
28436
28437
28438
28439
28440
28441
28442
28443
28444
28445
28446
28447
28448
28449
28450
28451
28452
28453
28454
28455
28456
28457
28458
28459
28460
28461
28462
28463
28464
28465
28466
28467
28468
28469
28470
28471
28472
28473
28474
28475
28476
28477
28478
28479
28480
28481
28482
28483
28484
28485
28486
28487
28488
28489
28490
28491
28492
28493
28494
28495
28496
28497
28498
28499
28500
28501
28502
28503
28504
28505
28506
28507
28508
28509
28510
28511
28512
28513
28514
28515
28516
28517
28518
28519
28520
28521
28522
28523
28524
28525
28526
28527
28528
28529
28530
28531
28532
28533
28534
28535
28536
28537
28538
28539
28540
28541
28542
28543
28544
28545
28546
28547
28548
28549
28550
28551
28552
28553
28554
28555
28556
28557
28558
28559
28560
28561
28562
28563
28564
28565
28566
28567
28568
28569
28570
28571
28572
28573
28574
28575
28576
28577
28578
28579
28580
28581
28582
28583
28584
28585
28586
28587
28588
28589
28590
28591
28592
28593
28594
28595
28596
28597
28598
28599
28600
28601
28602
28603
28604
28605
28606
28607
28608
28609
28610
28611
28612
28613
28614
28615
28616
28617
28618
28619
28620
28621
28622
28623
28624
28625
28626
28627
28628
28629
28630
28631
28632
28633
28634
28635
28636
28637
28638
28639
28640
28641
28642
28643
28644
28645
28646
28647
28648
28649
28650
28651
28652
28653
28654
28655
28656
28657
28658
28659
28660
28661
28662
28663
28664
28665
28666
28667
28668
28669
28670
28671
28672
28673
28674
28675
28676
28677
28678
28679
28680
28681
28682
28683
28684
28685
28686
28687
28688
28689
28690
28691
28692
28693
28694
28695
28696
28697
28698
28699
28700
28701
28702
28703
28704
28705
28706
28707
28708
28709
28710
28711
28712
28713
28714
28715
28716
28717
28718
28719
28720
28721
28722
28723
28724
28725
28726
28727
28728
28729
28730
28731
28732
28733
28734
28735
28736
28737
28738
28739
28740
28741
28742
28743
28744
28745
28746
28747
28748
28749
28750
28751
28752
28753
28754
28755
28756
28757
28758
28759
28760
28761
28762
28763
28764
28765
28766
28767
28768
28769
28770
28771
28772
28773
28774
28775
28776
28777
28778
28779
28780
28781
28782
28783
28784
28785
28786
28787
28788
28789
28790
28791
28792
28793
28794
28795
28796
28797
28798
28799
28800
28801
28802
28803
28804
28805
28806
28807
28808
28809
28810
28811
28812
28813
28814
28815
28816
28817
28818
28819
28820
28821
28822
28823
28824
28825
28826
28827
28828
28829
28830
28831
28832
28833
28834
28835
28836
28837
28838
28839
28840
28841
28842
28843
28844
28845
28846
28847
28848
28849
28850
28851
28852
28853
28854
28855
28856
28857
28858
28859
28860
28861
28862
28863
28864
28865
28866
28867
28868
28869
28870
28871
28872
28873
28874
28875
28876
28877
28878
28879
28880
28881
28882
28883
28884
28885
28886
28887
28888
28889
28890
28891
28892
28893
28894
28895
28896
28897
28898
28899
28900
28901
28902
28903
28904
28905
28906
28907
28908
28909
28910
28911
28912
28913
28914
28915
28916
28917
28918
28919
28920
28921
28922
28923
28924
28925
28926
28927
28928
28929
28930
28931
28932
28933
28934
28935
28936
28937
28938
28939
28940
28941
28942
28943
28944
28945
28946
28947
28948
28949
28950
28951
28952
28953
28954
28955
28956
28957
28958
28959
28960
28961
28962
28963
28964
28965
28966
28967
28968
28969
28970
28971
28972
28973
28974
28975
28976
28977
28978
28979
28980
28981
28982
28983
28984
28985
28986
28987
28988
28989
28990
28991
28992
28993
28994
28995
28996
28997
28998
28999
29000
29001
29002
29003
29004
29005
29006
29007
29008
29009
29010
29011
29012
29013
29014
29015
29016
29017
29018
29019
29020
29021
29022
29023
29024
29025
29026
29027
29028
29029
29030
29031
29032
29033
29034
29035
29036
29037
29038
29039
29040
29041
29042
29043
29044
29045
29046
29047
29048
29049
29050
29051
29052
29053
29054
29055
29056
29057
29058
29059
29060
29061
29062
29063
29064
29065
29066
29067
29068
29069
29070
29071
29072
29073
29074
29075
29076
29077
29078
29079
29080
29081
29082
29083
29084
29085
29086
29087
29088
29089
29090
29091
29092
29093
29094
29095
29096
29097
29098
29099
29100
29101
29102
29103
29104
29105
29106
29107
29108
29109
29110
29111
29112
29113
29114
29115
29116
29117
29118
29119
29120
29121
29122
29123
29124
29125
29126
29127
29128
29129
29130
29131
29132
29133
29134
29135
29136
29137
29138
29139
29140
29141
29142
29143
29144
29145
29146
29147
29148
29149
29150
29151
29152
29153
29154
29155
29156
29157
29158
29159
29160
29161
29162
29163
29164
29165
29166
29167
29168
29169
29170
29171
29172
29173
29174
29175
29176
29177
29178
29179
29180
29181
29182
29183
29184
29185
29186
29187
29188
29189
29190
29191
29192
29193
29194
29195
29196
29197
29198
29199
29200
29201
29202
29203
29204
29205
29206
29207
29208
29209
29210
29211
29212
29213
29214
29215
29216
29217
29218
29219
29220
29221
29222
29223
29224
29225
29226
29227
29228
29229
29230
29231
29232
29233
29234
29235
29236
29237
29238
29239
29240
29241
29242
29243
29244
29245
29246
29247
29248
29249
29250
29251
29252
29253
29254
29255
29256
29257
29258
29259
29260
29261
29262
29263
29264
29265
29266
29267
29268
29269
29270
29271
29272
29273
29274
29275
29276
29277
29278
29279
29280
29281
29282
29283
29284
29285
29286
29287
29288
29289
29290
29291
29292
29293
29294
29295
29296
29297
29298
29299
29300
29301
29302
29303
29304
29305
29306
29307
29308
29309
29310
29311
29312
29313
29314
29315
29316
29317
29318
29319
29320
29321
29322
29323
29324
29325
29326
29327
29328
29329
29330
29331
29332
29333
29334
29335
29336
29337
29338
29339
29340
29341
29342
29343
29344
29345
29346
29347
29348
29349
29350
29351
29352
29353
29354
29355
29356
29357
29358
29359
29360
29361
29362
29363
29364
29365
29366
29367
29368
29369
29370
29371
29372
29373
29374
29375
29376
29377
29378
29379
29380
29381
29382
29383
29384
29385
29386
29387
29388
29389
29390
29391
29392
29393
29394
29395
29396
29397
29398
29399
29400
29401
29402
29403
29404
29405
29406
29407
29408
29409
29410
29411
29412
29413
29414
29415
29416
29417
29418
29419
29420
29421
29422
29423
29424
29425
29426
29427
29428
29429
29430
29431
29432
29433
29434
29435
29436
29437
29438
29439
29440
29441
29442
29443
29444
29445
29446
29447
29448
29449
29450
29451
29452
29453
29454
29455
29456
29457
29458
29459
29460
29461
29462
29463
29464
29465
29466
29467
29468
29469
29470
29471
29472
29473
29474
29475
29476
29477
29478
29479
29480
29481
29482
29483
29484
29485
29486
29487
29488
29489
29490
29491
29492
29493
29494
29495
29496
29497
29498
29499
29500
29501
29502
29503
29504
29505
29506
29507
29508
29509
29510
29511
29512
29513
29514
29515
29516
29517
29518
29519
29520
29521
29522
29523
29524
29525
29526
29527
29528
29529
29530
29531
29532
29533
29534
29535
29536
29537
29538
29539
29540
29541
29542
29543
29544
29545
29546
29547
29548
29549
29550
29551
29552
29553
29554
29555
29556
29557
29558
29559
29560
29561
29562
29563
29564
29565
29566
29567
29568
29569
29570
29571
29572
29573
29574
29575
29576
29577
29578
29579
29580
29581
29582
29583
29584
29585
29586
29587
29588
29589
29590
29591
29592
29593
29594
29595
29596
29597
29598
29599
29600
29601
29602
29603
29604
29605
29606
29607
29608
29609
29610
29611
29612
29613
29614
29615
29616
29617
29618
29619
29620
29621
29622
29623
29624
29625
29626
29627
29628
29629
29630
29631
29632
29633
29634
29635
29636
29637
29638
29639
29640
29641
29642
29643
29644
29645
29646
29647
29648
29649
29650
29651
29652
29653
29654
29655
29656
29657
29658
29659
29660
29661
29662
29663
29664
29665
29666
29667
29668
29669
29670
29671
29672
29673
29674
29675
29676
29677
29678
29679
29680
29681
29682
29683
29684
29685
29686
29687
29688
29689
29690
29691
29692
29693
29694
29695
29696
29697
29698
29699
29700
29701
29702
29703
29704
29705
29706
29707
29708
29709
29710
29711
29712
29713
29714
29715
29716
29717
29718
29719
29720
29721
29722
29723
29724
29725
29726
29727
29728
29729
29730
29731
29732
29733
29734
29735
29736
29737
29738
29739
29740
29741
29742
29743
29744
29745
29746
29747
29748
29749
29750
29751
29752
29753
29754
29755
29756
29757
29758
29759
29760
29761
29762
29763
29764
29765
29766
29767
29768
29769
29770
29771
29772
29773
29774
29775
29776
29777
29778
29779
29780
29781
29782
29783
29784
29785
29786
29787
29788
29789
29790
29791
29792
29793
29794
29795
29796
29797
29798
29799
29800
29801
29802
29803
29804
29805
29806
29807
29808
29809
29810
29811
29812
29813
29814
29815
29816
29817
29818
29819
29820
29821
29822
29823
29824
29825
29826
29827
29828
29829
29830
29831
29832
29833
29834
29835
29836
29837
29838
29839
29840
29841
29842
29843
29844
29845
29846
29847
29848
29849
29850
29851
29852
29853
29854
29855
29856
29857
29858
29859
29860
29861
29862
29863
29864
29865
29866
29867
29868
29869
29870
29871
29872
29873
29874
29875
29876
29877
29878
29879
29880
29881
29882
29883
29884
29885
29886
29887
29888
29889
29890
29891
29892
29893
29894
29895
29896
29897
29898
29899
29900
29901
29902
29903
29904
29905
29906
29907
29908
29909
29910
29911
29912
29913
29914
29915
29916
29917
29918
29919
29920
29921
29922
29923
29924
29925
29926
29927
29928
29929
29930
29931
29932
29933
29934
29935
29936
29937
29938
29939
29940
29941
29942
29943
29944
29945
29946
29947
29948
29949
29950
29951
29952
29953
29954
29955
29956
29957
29958
29959
29960
29961
29962
29963
29964
29965
29966
29967
29968
29969
29970
29971
29972
29973
29974
29975
29976
29977
29978
29979
29980
29981
29982
29983
29984
29985
29986
29987
29988
29989
29990
29991
29992
29993
29994
29995
29996
29997
29998
29999
30000
30001
30002
30003
30004
30005
30006
30007
30008
30009
30010
30011
30012
30013
30014
30015
30016
30017
30018
30019
30020
30021
30022
30023
30024
30025
30026
30027
30028
30029
30030
30031
30032
30033
30034
30035
30036
30037
30038
30039
30040
30041
30042
30043
30044
30045
30046
30047
30048
30049
30050
30051
30052
30053
30054
30055
30056
30057
30058
30059
30060
30061
30062
30063
30064
30065
30066
30067
30068
30069
30070
30071
30072
30073
30074
30075
30076
30077
30078
30079
30080
30081
30082
30083
30084
30085
30086
30087
30088
30089
30090
30091
30092
30093
30094
30095
30096
30097
30098
30099
30100
30101
30102
30103
30104
30105
30106
30107
30108
30109
30110
30111
30112
30113
30114
30115
30116
30117
30118
30119
30120
30121
30122
30123
30124
30125
30126
30127
30128
30129
30130
30131
30132
30133
30134
30135
30136
30137
30138
30139
30140
30141
30142
30143
30144
30145
30146
30147
30148
30149
30150
30151
30152
30153
30154
30155
30156
30157
30158
30159
30160
30161
30162
30163
30164
30165
30166
30167
30168
30169
30170
30171
30172
30173
30174
30175
30176
30177
30178
30179
30180
30181
30182
30183
30184
30185
30186
30187
30188
30189
30190
30191
30192
30193
30194
30195
30196
30197
30198
30199
30200
30201
30202
30203
30204
30205
30206
30207
30208
30209
30210
30211
30212
30213
30214
30215
30216
30217
30218
30219
30220
30221
30222
30223
30224
30225
30226
30227
30228
30229
30230
30231
30232
30233
30234
30235
30236
30237
30238
30239
30240
30241
30242
30243
30244
30245
30246
30247
30248
30249
30250
30251
30252
30253
30254
30255
30256
30257
30258
30259
30260
30261
30262
30263
30264
30265
30266
30267
30268
30269
30270
30271
30272
30273
30274
30275
30276
30277
30278
30279
30280
30281
30282
30283
30284
30285
30286
30287
30288
30289
30290
30291
30292
30293
30294
30295
30296
30297
30298
30299
30300
30301
30302
30303
30304
30305
30306
30307
30308
30309
30310
30311
30312
30313
30314
30315
30316
30317
30318
30319
30320
30321
30322
30323
30324
30325
30326
30327
30328
30329
30330
30331
30332
30333
30334
30335
30336
30337
30338
30339
30340
30341
30342
30343
30344
30345
30346
30347
30348
30349
30350
30351
30352
30353
30354
30355
30356
30357
30358
30359
30360
30361
30362
30363
30364
30365
30366
30367
30368
30369
30370
30371
30372
30373
30374
30375
30376
30377
30378
30379
30380
30381
30382
30383
30384
30385
30386
30387
30388
30389
30390
30391
30392
30393
30394
30395
30396
30397
30398
30399
30400
30401
30402
30403
30404
30405
30406
30407
30408
30409
30410
30411
30412
30413
30414
30415
30416
30417
30418
30419
30420
30421
30422
30423
30424
30425
30426
30427
30428
30429
30430
30431
30432
30433
30434
30435
30436
30437
30438
30439
30440
30441
30442
30443
30444
30445
30446
30447
30448
30449
30450
30451
30452
30453
30454
30455
30456
30457
30458
30459
30460
30461
30462
30463
30464
30465
30466
30467
30468
30469
30470
30471
30472
30473
30474
30475
30476
30477
30478
30479
30480
30481
30482
30483
30484
30485
30486
30487
30488
30489
30490
30491
30492
30493
30494
30495
30496
30497
30498
30499
30500
30501
30502
30503
30504
30505
30506
30507
30508
30509
30510
30511
30512
30513
30514
30515
30516
30517
30518
30519
30520
30521
30522
30523
30524
30525
30526
30527
30528
30529
30530
30531
30532
30533
30534
30535
30536
30537
30538
30539
30540
30541
30542
30543
30544
30545
30546
30547
30548
30549
30550
30551
30552
30553
30554
30555
30556
30557
30558
30559
30560
30561
30562
30563
30564
30565
30566
30567
30568
30569
30570
30571
30572
30573
30574
30575
30576
30577
30578
30579
30580
30581
30582
30583
30584
30585
30586
30587
30588
30589
30590
30591
30592
30593
30594
30595
30596
30597
30598
30599
30600
30601
30602
30603
30604
30605
30606
30607
30608
30609
30610
30611
30612
30613
30614
30615
30616
30617
30618
30619
30620
30621
30622
30623
30624
30625
30626
30627
30628
30629
30630
30631
30632
30633
30634
30635
30636
30637
30638
30639
30640
30641
30642
30643
30644
30645
30646
30647
30648
30649
30650
30651
30652
30653
30654
30655
30656
30657
30658
30659
30660
30661
30662
30663
30664
30665
30666
30667
30668
30669
30670
30671
30672
30673
30674
30675
30676
30677
30678
30679
30680
30681
30682
30683
30684
30685
30686
30687
30688
30689
30690
30691
30692
30693
30694
30695
30696
30697
30698
30699
30700
30701
30702
30703
30704
30705
30706
30707
30708
30709
30710
30711
30712
30713
30714
30715
30716
30717
30718
30719
30720
30721
30722
30723
30724
30725
30726
30727
30728
30729
30730
30731
30732
30733
30734
30735
30736
30737
30738
30739
30740
30741
30742
30743
30744
30745
30746
30747
30748
30749
30750
30751
30752
30753
30754
30755
30756
30757
30758
30759
30760
30761
30762
30763
30764
30765
30766
30767
30768
30769
30770
30771
30772
30773
30774
30775
30776
30777
30778
30779
30780
30781
30782
30783
30784
30785
30786
30787
30788
30789
30790
30791
30792
30793
30794
30795
30796
30797
30798
30799
30800
30801
30802
30803
30804
30805
30806
30807
30808
30809
30810
30811
30812
30813
30814
30815
30816
30817
30818
30819
30820
30821
30822
30823
30824
30825
30826
30827
30828
30829
30830
30831
30832
30833
30834
30835
30836
30837
30838
30839
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
#
# Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# Copyright 2015 Nexenta Systems, Inc. All rights reserved.
# Copyright (c) 2018, Joyent, Inc.

PROG= format

COBJS=	add_definition.o analyze.o checkdev.o ctlr_scsi.o \
	defect.o init_menus.o io.o label.o main.o \
	menu.o menu_analyze.o menu_cache.o menu_command.o menu_defect.o \
	menu_partition.o misc.o modify_partition.o partition.o \
	prompts.o startup.o menu_scsi.o auto_sense.o disk_generic.o \
	menu_developer.o menu_fdisk.o

OBJS_sparc=   init_csparc.o ctlr_ata.o

OBJS_i386=    init_ci386.o ctlr_ata.o ix_altsctr.o

OBJS_=                non-existent

OBJS=  $(OBJS_$(MACH))  $(COBJS)

DATA= format.dat

include ../Makefile.cmd

CERRWARN += $(CNOWARN_UNINIT)
CERRWARN += -Wno-parentheses
CERRWARN += -Wno-clobbered

# Hammerhead: Suppress pointer/int cast and format warnings in legacy format code
CERRWARN += -Wno-pointer-to-int-cast
CERRWARN += -Wno-incompatible-pointer-types
CERRWARN += -Wno-format
CERRWARN += -Wno-return-type

# not linted
SMATCH=off

ROOTSYMLINK= $(ROOTETCPROG)
ROOTETCDATA= $(ROOTETC)/$(DATA)

$(ROOTETCDATA) : FILEMODE = 0644

LDLIBS_i386= -lfdisk
LDLIBS_sparc=
LDLIBS +=	-ladm -lefi -ldiskmgt -lnvpair -ldevid -ldevinfo $(LDLIBS_$(MACH))

# Hammerhead: Define i386 for amd64 builds to satisfy platform checks in legacy code
# The code checks "defined(i386)" for x86-specific code paths that also apply to amd64
CPPFLAGS    += -D_EXTVTOC -Di386

.KEEP_STATE:

all: $(PROG) $(DATA)

.PARALLEL: $(OBJS)

$(PROG): $(OBJS)
	$(LINK.c) -o $(PROG) $(OBJS) $(LDLIBS)
	$(POST_PROCESS)

#
# Install format as /usr/sbin/format, with link from /etc/format
#
install: $(ROOTUSRSBINPROG) $(ROOTSYMLINK) $(ROOTETCDATA)

$(ROOTSYMLINK):
	$(RM) $@; $(SYMLINK) ../usr/sbin/$(PROG) $@

clean:
	$(RM) $(OBJS)

include ../Makefile.targ
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * This file contains the code to add new disk_type and partition
 * definitions to a format data file.
 */
#include "global.h"

#include <ctype.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <memory.h>
#include <sys/fcntl.h>
#include <sys/param.h>
#include <time.h>
#include <sys/time.h>
#include <stdarg.h>

#include "add_definition.h"
#include "misc.h"
#include "partition.h"
#include "menu_command.h"
#include "startup.h"

extern	struct	ctlr_type ctlr_types[];
extern	int	nctypes;

extern	int	errno;

/* Function prototypes */
#ifdef	__STDC__

static void	add_disktype(FILE *fd, struct disk_info *disk_info);
static void	add_partition(FILE *fd, struct disk_info *,
		struct partition_info *);
static int	add_entry(int col, FILE *fd, char *format, ...);

#else	/* __STDC__ */

static void	add_disktype();
static void	add_partition();
static int	add_entry();

#endif	/* __STDC__ */

/*
 * Add new definitions for the current disk/partition to a format data file.
 */
int
add_definition(void)
{
	FILE	*fd;
	char	*filename;
	time_t	clock;
	char	*prompt;
	union {
		int	xfoo;
		char	deflt_str[MAXPATHLEN];
	} x;

	/*
	 * There must be a current disk and partition table
	 */
	if (cur_disk == NULL) {
		err_print("No Current Disk.\n");
		return (0);
	}
	if (cur_dtype == NULL) {
		err_print("Current disk type is not set.\n");
		return (-1);
	}
	if (cur_parts == NULL) {
		err_print("Current partition is not set.\n");
		return (-1);
	}
	/*
	 * If neither the disk definition nor the partition
	 * information has been changed, there's nothing to save.
	 */
	if (cur_dtype->dtype_filename != NULL &&
	    cur_parts->pinfo_filename != NULL) {
		err_print("\
Neither the disk type nor the partitioning has been changed.\n");
		return (-1);
	}
	/*
	 * If saving the partition, and it's unnamed, the user should name
	 * it first.
	 */
	if (cur_parts->pinfo_name == NULL) {
		assert(cur_parts->pinfo_filename == NULL);
		err_print("Please name this partition type before saving it\n");
		return (-1);
	}
	/*
	 * Let the user know what we're doing
	 */
	if (cur_dtype->dtype_filename == NULL &&
	    cur_parts->pinfo_filename == NULL) {
		fmt_print("Saving new disk and partition definitions\n");
	} else if (cur_dtype->dtype_filename == NULL) {
		fmt_print("Saving new disk definition\n");
	} else {
		assert(cur_parts->pinfo_filename == NULL);
		fmt_print("Saving new partition definition\n");
	}
	/*
	 * Ask for the file to which to append the new definitions
	 */
	prompt = "Enter file name";
	(void) strcpy(x.deflt_str, "./format.dat");
	filename = (char *)(uintptr_t)input(FIO_OSTR, prompt,
	    ':', NULL, &x.xfoo, DATA_INPUT);
	assert(filename != NULL);
	/*
	 * Open the file in append mode, or create it, if necessary
	 */
	if ((fd = fopen(filename, "a")) == NULL) {
		err_print("Cannot open `%s' - %s\n", filename,
		    strerror(errno));
		destroy_data(filename);
		return (-1);
	}
	/*
	 * Write a header for the new definitions
	 */
	if ((cur_dtype->dtype_filename == NULL) &&
	    (cur_parts->pinfo_filename == NULL)) {
		(void) fprintf(fd, "#\n# New disk/partition type ");
	} else if (cur_dtype->dtype_filename == NULL) {
		(void) fprintf(fd, "#\n# New disk type ");
	} else {
		(void) fprintf(fd, "#\n# New partition type ");
	}
	(void) time(&clock);
	(void) fprintf(fd, " saved on %s#\n", ctime(&clock));
	/*
	 * Save the new definitions
	 */
	if (cur_dtype->dtype_filename == NULL) {
		add_disktype(fd, cur_disk);
	}
	if (cur_parts->pinfo_filename == NULL) {
		add_partition(fd, cur_disk, cur_parts);
	}
	/*
	 * We're finished.  Clean up
	 */
	(void) fclose(fd);
	destroy_data(filename);
	return (0);
}

/*
 * Add a disk_type definition to the file fd
 */
static void
add_disktype(FILE *fd, struct disk_info *disk_info)
{
	int			col;
	struct disk_type	*disk_type;

	disk_type = disk_info->disk_type;

	(void) fprintf(fd, "disk_type = \"%s\" \\\n",
	    disk_type->dtype_asciilabel);
	col = add_entry(0, fd, " : ctlr = %s",
	    ((disk_info->disk_ctlr)->ctlr_ctype)->ctype_name);

	col = add_entry(col, fd, " : ncyl = %d", disk_type->dtype_ncyl);

	col = add_entry(col, fd, " : acyl = %d", disk_type->dtype_acyl);

	col = add_entry(col, fd, " : pcyl = %d", disk_type->dtype_pcyl);

	col = add_entry(col, fd, " : nhead = %d", disk_type->dtype_nhead);

	if (disk_type->dtype_options & SUP_PHEAD) {
		col = add_entry(col, fd, " : phead = %d",
		    disk_type->dtype_phead);
	}

	col = add_entry(col, fd, " : nsect = %d", disk_type->dtype_nsect);

	if (disk_type->dtype_options & SUP_PSECT) {
		col = add_entry(col, fd, " : psect = %d",
		    disk_type->dtype_psect);
	}

	if (disk_type->dtype_options & SUP_BPT) {
		col = add_entry(col, fd, " : bpt = %d", disk_type->dtype_bpt);
	}

	col = add_entry(col, fd, " : rpm = %d", disk_type->dtype_rpm);

	if (disk_type->dtype_options & SUP_FMTTIME) {
		col = add_entry(col, fd, " : fmt_time = %d",
		    disk_type->dtype_fmt_time);
	}

	if (disk_type->dtype_options & SUP_CYLSKEW) {
		col = add_entry(col, fd, " : cyl_skew = %d",
		    disk_type->dtype_cyl_skew);
	}

	if (disk_type->dtype_options & SUP_TRKSKEW) {
		col = add_entry(col, fd, " : trk_skew = %d",
		    disk_type->dtype_trk_skew);
	}

	if (disk_type->dtype_options & SUP_TRKS_ZONE) {
		col = add_entry(col, fd, " : trks_zone = %d",
		    disk_type->dtype_trks_zone);
	}

	if (disk_type->dtype_options & SUP_ATRKS) {
		col = add_entry(col, fd, " : atrks = %d",
		    disk_type->dtype_atrks);
	}

	if (disk_type->dtype_options & SUP_ASECT) {
		col = add_entry(col, fd, " : asect = %d",
		    disk_type->dtype_asect);
	}

	if (disk_type->dtype_options & SUP_CACHE) {
		col = add_entry(col, fd, " : cache = %d",
		    disk_type->dtype_cache);
	}

	if (disk_type->dtype_options & SUP_PREFETCH) {
		col = add_entry(col, fd, " : prefetch = %d",
		    disk_type->dtype_threshold);
	}

	if (disk_type->dtype_options & SUP_CACHE_MIN) {
		col = add_entry(col, fd, " : min_prefetch = %d",
		    disk_type->dtype_prefetch_min);
	}

	if (disk_type->dtype_options & SUP_CACHE_MAX) {
		col = add_entry(col, fd, " : max_prefetch = %d",
		    disk_type->dtype_prefetch_max);
	}

	if (disk_type->dtype_options & SUP_BPS) {
		col = add_entry(col, fd, " : bps = %d",
		    disk_type->dtype_bps);
	}

	if (disk_type->dtype_options & SUP_DRTYPE) {
		col = add_entry(col, fd, " : drive_type = %d",
		    disk_type->dtype_dr_type);
	}

	/*
	 * Terminate the last line, and print one blank line
	 */
	(void) fprintf(fd, col == 0 ? "\n" : "\n\n");
}



/*
 * Once we exceed this length, wrap to a new line
 */
#define	MAX_COLUMNS	50

/*
 * Add a partition definition to the file fd
 */
static void
add_partition(FILE *fd, struct disk_info *disk_info,
    struct partition_info *part)
{
	int			col;
	int			i;
	struct disk_type	*disk_type;
	struct dk_map32		*pp;
	char			*s;

#if defined(_SUNOS_VTOC_8)
	struct dk_map2		*pv;

#elif defined(_SUNOS_VTOC_16)
	struct dkl_partition	*pv;

#else
#error No VTOC format defined.
#endif			/* defined (_SUNOS_VTOC_8) */
	struct dk_map2		*dv;

	disk_type = disk_info->disk_type;

	(void) fprintf(fd, "partition = \"%s\" \\\n", part->pinfo_name);
	(void) fprintf(fd, "\t : disk = \"%s\" : ctlr = %s \\\n",
	    disk_type->dtype_asciilabel,
	    ((disk_info->disk_ctlr)->ctlr_ctype)->ctype_name);

	/*
	 * Print the specifications for each useful partition
	 */
	col = 0;
	pp = part->pinfo_map;
	pv = part->vtoc.v_part;
	dv = default_vtoc_map;
	for (i = 0; i < NDKMAP; i++, pp++, pv++, dv++) {
		if (pp->dkl_nblk != 0) {
			col = add_entry(col, fd, " : %c = ",
			    i + PARTITION_BASE);
			if (pv->p_tag != dv->p_tag ||
			    pv->p_flag != dv->p_flag) {
				s = find_string(ptag_choices, (int)pv->p_tag);
				if (s != NULL) {
					col = add_entry(col, fd, " %s,", s);
				}
				s = find_string(pflag_choices, (int)pv->p_flag);
				if (s != NULL) {
					col = add_entry(col, fd, " %s,", s);
				}
			}
			col = add_entry(col, fd, " %d, %d", pp->dkl_cylno,
			    pp->dkl_nblk);
		}
	}

	/*
	 * Terminate the last line, and print one blank line
	 */
	(void) fprintf(fd, col == 0 ? "\n" : "\n\n");
}

/*
 * Add an entry to the file fd.  col is the current starting column.
 * Return the resulting new column position.
 */
/*PRINTFLIKE3*/
static int
add_entry(int col, FILE *fd, char *format, ...)
{
	va_list	ap;
	va_start(ap, format);

	if (col > MAX_COLUMNS) {
		(void) fprintf(fd, " \\\n");
		col = 0;
	}
	if (col == 0) {
		col += fprintf(fd, "\t");
	}
	col += vfprintf(fd, format, ap);
	va_end(ap);

	return (col);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright (c) 1991-2001 by Sun Microsystems, Inc.
 */

#ifndef	_ADD_DEFINITION_H
#define	_ADD_DEFINITION_H

#ifdef	__cplusplus
extern "C" {
#endif

/*
 *	Prototypes for ANSI C compilers
 */
int	add_definition(void);

#ifdef	__cplusplus
}
#endif

#endif	/* _ADD_DEFINITION_H */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * This file contains routines to analyze the surface of a disk.
 */
#include "global.h"
#include "analyze.h"
#include <stdlib.h>
#include <errno.h>
#include "misc.h"
#include "defect.h"
#include "label.h"
#include "param.h"
#include "checkdev.h"


/*
 * These global variables control the surface analysis process.  They
 * are set from a command in the defect menu.
 */
int	scan_entire = 1;		/* scan whole disk flag */
diskaddr_t	scan_lower = 0;			/* lower bound */
diskaddr_t	scan_upper = 0;			/* upper bound */
int	scan_correct = 1;		/* correct errors flag */
int	scan_stop = 0;			/* stop after error flag */
int	scan_loop = 0;			/* loop forever flag */
int	scan_passes = 2;		/* number of passes */
int	scan_random = 0;		/* random patterns flag */
uint_t	scan_size = 0;			/* sectors/scan operation */
int	scan_auto = 1;			/* scan after format flag */
int	scan_restore_defects = 1;	/* restore defect list after writing */
int	scan_restore_label = 1;		/* restore label after writing */

/*
 * These are summary variables to print out info after analysis.
 * Values less than 0 imply they are invalid.
 */
offset_t	scan_cur_block = -1;		/* current block */
int64_t		scan_blocks_fixed = -1;		/* # blocks repaired */

/*
 * This variable is used to tell whether the most recent surface
 * analysis error was caused by a media defect or some other problem.
 */
int	media_error;			/* error was caused by defect */

int	disk_error;			/* disk errors during analysis */

/*
 * These are the data patterns used if random patterns are not chosen.
 * They are designed to show pattern dependent errors.
 */
static unsigned int	scan_patterns[] = {
	0xc6dec6de,
	0x6db6db6d,
	0x00000000,
	0xffffffff,
	0xaaaaaaaa,
};
#define	NPATTERNS	5		/* number of predefined patterns */

/*
 * These are the data patterns from the SunFed requirements document.
 */
static unsigned int purge_patterns[] = {	/* patterns to be written */
	0xaaaaaaaa,		/* 10101010... */
	0x55555555,		/* 01010101...  == UUUU... */
	0xaaaaaaaa,		/* 10101010... */
	0xaaaaaaaa,		/* 10101010... */
};

static unsigned int alpha_pattern =  0x40404040;   /* 10000000...  == @@@@... */

static int	scan_repair(diskaddr_t bn, int mode);
static int	analyze_blocks(int flags, diskaddr_t blkno, uint_t blkcnt,
		unsigned data, int init, int driver_flags, int *xfercntp);
static int	handle_error_conditions(void);
static int	verify_blocks(int flags, diskaddr_t blkno, uint_t blkcnt,
		unsigned data, int driver_flags, int *xfercntp);

/*
 * This routine performs a surface analysis based upon the global
 * parameters.  It is called from several commands in the defect menu,
 * and from the format command in the command menu (if post-format
 * analysis is enable).
 */
int
do_scan(int flags, int mode)
{
	diskaddr_t	start, end, curnt;
	int	pass, needinit, data;
	uint_t	size;
	int	status, founderr, i, j;
	int	error = 0;
	int	pattern = 0;
	int	xfercnt;

	/*
	 * Check to be sure we aren't correcting without a defect list
	 * if the controller can correct the defect.
	 */
	if (scan_correct && !EMBEDDED_SCSI && (cur_ops->op_repair != NULL) &&
	    (cur_list.list == NULL)) {
		err_print("Current Defect List must be initialized ");
		err_print("to do automatic repair.\n");
		return (-1);
	}
	/*
	 * Define the bounds of the scan.
	 */
	if (scan_entire) {
		start = 0;
		if (cur_label == L_TYPE_SOLARIS) {
			if (cur_ctype->ctype_flags & CF_SCSI)
				end = datasects() - 1;
			else
				end = physsects() - 1;
		} else if (cur_label == L_TYPE_EFI) {
			end = cur_parts->etoc->efi_last_lba;
		}
	} else {
		start = scan_lower;
		end = scan_upper;
	}
	/*
	 * Make sure the user knows if we are scanning over a mounted
	 * partition.
	 */
	if ((flags & (SCAN_PATTERN | SCAN_WRITE)) &&
	    (checkmount(start, end))) {
		err_print("Cannot do analysis on a mounted partition.\n");
		return (-1);
	}

	/*
	 * Make sure the user knows if we are scanning over a
	 * partition being used for swapping.
	 */
	if ((flags & (SCAN_PATTERN | SCAN_WRITE)) &&
	    (checkswap(start, end))) {
		err_print("Cannot do analysis on a partition \
		    which is currently being used for swapping.\n");
		return (-1);
	}

	/*
	 * Check to see if any partitions used for svm, vxvm, ZFS zpool
	 * or live upgrade are on the disk.
	 */
	if ((flags & (SCAN_PATTERN | SCAN_WRITE)) &&
	    (checkdevinuse(cur_disk->disk_name, (diskaddr_t)-1,
	    (diskaddr_t)-1, 0, 0))) {
		err_print("Cannot do analysis on a partition "
		    "while it in use as described above.\n");
		return (-1);
	}

	/*
	 * If we are scanning destructively over certain sectors,
	 * we mark the defect list and/or label dirty so it will get rewritten.
	 */
	if (flags & (SCAN_PATTERN | SCAN_WRITE)) {
		if (cur_label == L_TYPE_SOLARIS) {
			if (start < (diskaddr_t)totalsects() &&
			    end >= (diskaddr_t)datasects()) {
				if (!EMBEDDED_SCSI) {
					cur_list.flags |= LIST_DIRTY;
				}
				if (cur_disk->disk_flags & DSK_LABEL)
					cur_flags |= LABEL_DIRTY;
			}
		}
		if (start == 0) {
			if (cur_disk->disk_flags & DSK_LABEL)
				cur_flags |= LABEL_DIRTY;
		}
	}
	/*
	 * Initialize the summary info on sectors repaired.
	 */
	scan_blocks_fixed = 0;
	/*
	 * Loop through the passes of the scan. If required, loop forever.
	 */
	for (pass = 0; pass < scan_passes || scan_loop; pass++) {
		/*
		 * Determine the data pattern to use if pattern testing
		 * is to be done.
		 */
		if (flags & SCAN_PATTERN) {
			if (scan_random)
				data = (int)mrand48();
			else
				data = scan_patterns[pass % NPPATTERNS];

			if (flags & SCAN_PURGE) {
				flags &= ~(SCAN_PURGE_READ_PASS
				    | SCAN_PURGE_ALPHA_PASS);
				switch (pattern % (NPPATTERNS + 1)) {
				case NPPATTERNS:
					pattern = 0;
					if (!error) {
						fmt_print(
"\nThe last %d passes were successful, running alpha pattern pass", NPPATTERNS);
						flags |= SCAN_PURGE_ALPHA_PASS;
						data = alpha_pattern;
					} else {
						data = purge_patterns[pattern];
						pattern++;
					};
					break;
				case READPATTERN:
					flags |=  SCAN_PURGE_READ_PASS;
					/* FALLTHROUGH */
				default:
					data = purge_patterns[pattern];
					pattern++;
					break;
				}
			}
			fmt_print("\n        pass %d", pass);
			fmt_print(" - pattern = 0x%x", data);
		} else
			fmt_print("\n        pass %d", pass);

		fmt_print("\n");
		/*
		 * Mark the pattern buffer as corrupt, since it
		 * hasn't been initialized.
		 */
		needinit = 1;
		/*
		 * Print the first block number to the log file if
		 * logging is on so there is some record of what
		 * analysis was performed.
		 */
		if (log_file) {
			pr_dblock(log_print, start);
			log_print("\n");
		}
		/*
		 * Loop through this pass, each time analyzing an amount
		 * specified by the global parameters.
		 */
		xfercnt = 0;
		for (curnt = start; curnt <= end; curnt += size) {
			if ((end - curnt) < scan_size)
				size = end - curnt + 1;
			else
				size = scan_size;
			/*
			 * Print out where we are, so we don't look dead.
			 * Also store it in summary info for logging.
			 */
			scan_cur_block = curnt;
			nolog_print("   ");
			pr_dblock(nolog_print, curnt);
			nolog_print("  \015");
			(void) fflush(stdout);
			disk_error = 0;
			/*
			 * Do the actual analysis.
			 */
			status = analyze_blocks(flags, curnt, size,
			    (unsigned)data, needinit, (F_ALLERRS | F_SILENT),
			    &xfercnt);
			/*
			 * If there were no errors, the pattern buffer is
			 * still initialized, and we just loop to next chunk.
			 */
			needinit = 0;
			if (!status)
				continue;
			/*
			 * There was an error. Check if surface analysis
			 * can be continued.
			 */
			if (handle_error_conditions()) {
				scan_blocks_fixed = scan_cur_block = -1;
				return (-1);
			}
			/*
			 * There was an error. Mark the pattern buffer
			 * corrupt so it will get reinitialized.
			 */
			needinit = 1;
			/*
			 * If it was not a media error, ignore it.
			 */
			if (!media_error)
				continue;
			/*
			 * Loop 5 times through each sector of the chunk,
			 * analyzing them individually.
			 */
			nolog_print("   ");
			pr_dblock(nolog_print, curnt);
			nolog_print("  \015");
			(void) fflush(stdout);
			founderr = 0;
			for (j = 0; j < size * 5; j++) {
				i = j % size;
				disk_error = 0;
				status = analyze_blocks(flags, (curnt + i), 1,
				    (unsigned)data, needinit, F_ALLERRS, NULL);
				needinit = 0;
				if (!status)
					continue;
				/*
				 * There was an error. Check if surface analysis
				 * can be continued.
				 */
				if (handle_error_conditions()) {
					scan_blocks_fixed = scan_cur_block = -1;
					return (-1);
				}
				/*
				 * An error occurred.  Mark the buffer
				 * corrupt and see if it was media
				 * related.
				 */
				needinit = 1;
				if (!media_error)
					continue;
				/*
				 * We found a bad sector. Print out a message
				 * and fix it if required.
				 */
				founderr = 1;
				if (scan_correct && (flags != SCAN_VALID)) {
					if (scan_repair(curnt+i, mode)) {
						error = -1;
					}
				} else
					err_print("\n");
				/*
				 * Stop after the error if required.
				 */
				if (scan_stop)
					goto out;
			}
			/*
			 * Mark the pattern buffer corrupt to be safe.
			 */
			needinit = 1;
			/*
			 * We didn't find an individual sector that was bad.
			 * Print out a warning.
			 */
			if (!founderr) {
				err_print("Warning: unable to pinpoint ");
				err_print("defective block.\n");
			}
		}
		/*
		 * Print the end of each pass to the log file.
		 */
		enter_critical();
		if (log_file) {
			pr_dblock(log_print, scan_cur_block);
			log_print("\n");
		}
		scan_cur_block = -1;
		exit_critical();
		fmt_print("\n");

		/*
		 * alternate the read and write for SCAN_VERIFY test
		 */
		if (flags & SCAN_VERIFY) {
			flags ^= SCAN_VERIFY_READ_PASS;
		}
	}
out:
	/*
	 * We got here either by giving up after an error or falling
	 * through after all passes were completed.
	 */
	fmt_print("\n");
	enter_critical();
	/*
	 * If the defect list is dirty, write it to disk,
	 * if scan_restore_defects (the default) is true.
	 */
	if (!EMBEDDED_SCSI && (cur_list.flags & LIST_DIRTY) &&
	    (scan_restore_defects)) {
		cur_list.flags = 0;
		write_deflist(&cur_list);
		}
	/*
	 * If the label is dirty, write it to disk.
	 * if scan_restore_label (the default) is true.
	 */
	if ((cur_flags & LABEL_DIRTY) && (scan_restore_label)) {
		cur_flags &= ~LABEL_DIRTY;
		(void) write_label();
	}
	/*
	 * If we dropped down to here after an error, we need to write
	 * the final block number to the log file for record keeping.
	 */
	if (log_file && scan_cur_block >= 0) {
		pr_dblock(log_print, scan_cur_block);
		log_print("\n");
	}
	fmt_print("Total of %lld defective blocks repaired.\n",
	    scan_blocks_fixed);
	/*
	 * Reinitialize the logging variables so they don't get used
	 * when they are not really valid.
	 */
	scan_blocks_fixed = scan_cur_block = -1;
	exit_critical();
	return (error);
}


/*
 * This routine is called to repair a bad block discovered
 * during a scan operation.  Return 0 for success, 1 for failure.
 * (This has been extracted out of do_scan(), to simplify it.)
 */
static int
scan_repair(diskaddr_t bn, int mode)
{
	int	status;
	int	result = 1;
	char	*buf;
	int	buf_is_good;
	int	i;

	if (cur_ops->op_repair == NULL) {
		err_print("Warning: Controller does ");
		err_print("not support repairing.\n\n");
		return (result);
	}

	buf = malloc(cur_blksz);
	if (buf == NULL) {
		err_print("Warning: no memory.\n\n");
		return (result);
	}
	enter_critical();

	/*
	 * Determine if the error appears to be hard or soft.  We
	 * already assume there's an error.  If we can get any
	 * good data out of the sector, write that data back
	 * after the repair.
	 */
	buf_is_good = 0;
	for (i = 0; i < 5; i++) {
		status = (*cur_ops->op_rdwr)(DIR_READ, cur_file, bn, 1,
		    buf, F_SILENT, NULL);
		if (status == 0) {
			buf_is_good = 1;
			break;
		}
	}

	fmt_print("Repairing %s error on %llu (",
	    buf_is_good ? "soft" : "hard", bn);
	pr_dblock(fmt_print, bn);
	fmt_print(")...");

	status = (*cur_ops->op_repair)(bn, mode);
	if (status) {
		/*
		 * If the repair failed, we note it and will return the
		 * failure. However, the analysis goes on.
		 */
		fmt_print("failed.\n\n");
	} else {
		/*
		 * The repair worked.  Write the good data we could
		 * recover from the failed block, if possible.
		 * If not, zero the block.  In doing so, try to
		 * determine if the new block appears ok.
		 */
		if (!buf_is_good) {
			bzero(buf, cur_blksz);
			fmt_print("Warning: Block %llu zero-filled.\n", bn);
		} else {
			fmt_print("ok.\n");
		}
		status = (*cur_ops->op_rdwr)(DIR_WRITE, cur_file, bn,
		    1, buf, (F_SILENT | F_ALLERRS), NULL);
		if (status == 0) {
			status = (*cur_ops->op_rdwr)(DIR_READ, cur_file, bn,
			    1, buf, (F_SILENT | F_ALLERRS), NULL);
		}
		if (status) {
			fmt_print("The new block also appears defective.\n");
		}
		fmt_print("\n");
		/*
		 * add the defect to the list and write the list out.
		 * Also, kill the working list so it will get resynced
		 * with the current list.
		 *
		 * For embedded scsi, we don't require a defect list.
		 * However, if we have one, add the defect if the
		 * list includes the grown list.  If not, kill it
		 * to force a resync if we need the list later.
		 */
		if (EMBEDDED_SCSI) {
			if (cur_list.list != NULL) {
				if (cur_list.flags & LIST_PGLIST) {
					add_ldef(bn, &cur_list);
				} else {
					kill_deflist(&cur_list);
				}
			}
		/*
		 * The next "if" statement reflects the fix for
		 * bug id 1026096 where format keeps adding the
		 * same defect to the defect list.
		 */
		} else if (cur_ctype->ctype_flags & CF_WLIST) {
			kill_deflist(&cur_list);
			(*cur_ops->op_ex_cur)(&cur_list);
			fmt_print("Current list updated\n");
		} else {
			add_ldef(bn, &cur_list);
			write_deflist(&cur_list);
		}
		kill_deflist(&work_list);

		/* Log the repair.  */
		scan_blocks_fixed++;

		/* return ok */
		result = 0;
	}

	exit_critical();
	free(buf);
	return (result);
}


/*
 * This routine analyzes a set of sectors on the disk.  It simply returns
 * an error if a defect is found.  It is called by do_scan().
 */
static int
analyze_blocks(int flags, diskaddr_t blkno, uint_t blkcnt, unsigned data,
    int init, int driver_flags, int *xfercntp)
{
	int		corrupt = 0;
	int		status;
	diskaddr_t	i, nints;
	unsigned *ptr = (uint_t *)pattern_buf;

	media_error = 0;
	if (flags & SCAN_VERIFY) {
		return (verify_blocks(flags, blkno, blkcnt, data,
		    driver_flags, xfercntp));
	}

	/*
	 * Initialize the pattern buffer if necessary.
	 */
	nints = (diskaddr_t)blkcnt * cur_blksz / sizeof (int);
	if ((flags & SCAN_PATTERN) && init) {
		for (i = 0; i < nints; i++)
			*((int *)((int *)pattern_buf + i)) = data;
	}
	/*
	 * Lock out interrupts so we can insure valid data will get
	 * restored. This is necessary because there are modes
	 * of scanning that corrupt the disk data then restore it at
	 * the end of the analysis.
	 */
	enter_critical();
	/*
	 * If the disk data is valid, read it into the data buffer.
	 */
	if (flags & SCAN_VALID) {
		status = (*cur_ops->op_rdwr)(DIR_READ, cur_file, blkno,
		    blkcnt, (caddr_t)cur_buf, driver_flags, xfercntp);
		if (status)
			goto bad;
	}
	/*
	 * If we are doing pattern testing, write and read the pattern
	 * from the pattern buffer.
	 */
	if (flags & SCAN_PATTERN) {
		/*
		 * If the disk data was valid, mark it corrupt so we know
		 * to restore it later.
		 */
		if (flags & SCAN_VALID)
			corrupt++;
		/*
		 * Only write if we're not on the read pass of SCAN_PURGE.
		 */
		if (!(flags & SCAN_PURGE_READ_PASS)) {
			status = (*cur_ops->op_rdwr)(DIR_WRITE, cur_file, blkno,
			    blkcnt, (caddr_t)pattern_buf, driver_flags,
			    xfercntp);
			if (status)
				goto bad;
		}
		/*
		 * Only read if we are on the read pass of SCAN_PURGE, if we
		 * are purging.
		 */
		if ((!(flags & SCAN_PURGE)) || (flags & SCAN_PURGE_READ_PASS)) {
			status = (*cur_ops->op_rdwr)(DIR_READ, cur_file, blkno,
			    blkcnt, (caddr_t)pattern_buf, driver_flags,
			    xfercntp);
			if (status)
				goto bad;
		}
	}
	/*
	 * If we are doing a data compare, make sure the pattern
	 * came back intact.
	 * Only compare if we are on the read pass of SCAN_PURGE, or
	 * we wrote random data instead of the expected data pattern.
	 */
	if ((flags & SCAN_COMPARE) || (flags & SCAN_PURGE_READ_PASS)) {
		for (i = nints, ptr = (uint_t *)pattern_buf; i; i--)
			if (*ptr++ != data) {
				err_print("Data miscompare error (expecting ");
				err_print("0x%x, got 0x%x) at ", data,
				    *((int *)((int *)pattern_buf +
				    (nints - i))));
				pr_dblock(err_print, blkno);
				err_print(", offset = 0x%llx.\n",
				    (nints - i) * sizeof (int));
				goto bad;
			}
	}
	/*
	 * If we are supposed to write data out, do so.
	 */
	if (flags & SCAN_WRITE) {
		status = (*cur_ops->op_rdwr)(DIR_WRITE, cur_file, blkno,
		    blkcnt, (caddr_t)cur_buf, driver_flags, xfercntp);
		if (status)
			goto bad;
	}
	exit_critical();
	/*
	 * No errors occurred, return ok.
	 */
	return (0);
bad:
	/*
	 * There was an error.  If the data was corrupted, we write it
	 * out from the data buffer to restore it.
	 */
	if (corrupt) {
		if ((*cur_ops->op_rdwr)(DIR_WRITE, cur_file, blkno,
		    blkcnt, (caddr_t)cur_buf, F_NORMAL, xfercntp))
		err_print("Warning: unable to restore original data.\n");
	}
	exit_critical();
	/*
	 * Return the error.
	 */
	return (-1);
}


/*
 * This routine analyzes a set of sectors on the disk. It simply returns
 * an error if a defect is found.  It is called by analyze_blocks().
 * For simplicity, this is done as a separate function instead of
 * making the analyze_block routine complex.
 *
 * This routine implements the 'verify' command.  It writes the disk
 * by writing unique data for each block; after the write pass, it
 * reads the data and verifies for correctness. Note that the entire
 * disk (or the range of disk) is fully written first and then read.
 * This should eliminate any caching effect on the drives.
 */
static int
verify_blocks(int flags, diskaddr_t blkno, uint_t blkcnt, unsigned data,
    int driver_flags, int *xfercntp)
{
	int		status, i, nints;
	unsigned	*ptr = (uint_t *)pattern_buf;

	nints = cur_blksz / sizeof (int);

	/*
	 * Initialize the pattern buffer if we are in write pass.
	 * Use the block number itself as data, each block has unique
	 * buffer data that way.
	 */
	if (!(flags & SCAN_VERIFY_READ_PASS)) {
		for (data = blkno; data < blkno + blkcnt; data++) {
			for (i = 0; i < nints; i++) {
				*ptr++ = data;
			}
		}
		ptr = (uint_t *)pattern_buf;
	}

	/*
	 * Only write if we're not on the read pass of SCAN_VERIFY.
	 */
	if (!(flags & SCAN_VERIFY_READ_PASS)) {
		status = (*cur_ops->op_rdwr)(DIR_WRITE, cur_file, blkno,
		    blkcnt, (caddr_t)pattern_buf, driver_flags, xfercntp);
		if (status)
			goto bad;
	} else {
		/*
		 * Only read if we are on the read pass of SCAN_VERIFY
		 */
		status = (*cur_ops->op_rdwr)(DIR_READ, cur_file, blkno,
		    blkcnt, (caddr_t)pattern_buf, driver_flags, xfercntp);
		if (status)
			goto bad;
		/*
		 * compare and make sure the pattern came back intact.
		 */
		for (data = blkno; data < blkno + blkcnt; data++) {
			for (i = 0; i < nints; i++) {
				if (*ptr++ != data) {
					ptr--;
					err_print("Data miscompare error "
					    "(expecting 0x%x, got 0x%x) at ",
					    data, *ptr);
					pr_dblock(err_print, blkno);
					err_print(", offset = 0x%x.\n",
					    (ptr - (uint_t *)pattern_buf) *
					    sizeof (int));
					goto bad;
				}
			}
		}
	}
	/*
	 * No errors occurred, return ok.
	 */
	return (0);
bad:
	return (-1);
}


static int
handle_error_conditions(void)
{

	/*
	 * Check if the errno is ENXIO.
	 */
	if (errno == ENXIO) {
		fmt_print("\n\nWarning:Cannot access drive, ");
		fmt_print("aborting surface analysis.\n");
		return (-1);
	}
	/*
	 * check for disk errors
	 */
	switch (disk_error) {
	case DISK_STAT_RESERVED:
	case DISK_STAT_UNAVAILABLE:
		fmt_print("\n\nWarning:Drive may be reserved ");
		fmt_print("or has been removed, ");
		fmt_print("aborting surface analysis.\n");
		return (-1);
	case DISK_STAT_NOTREADY:
		fmt_print("\n\nWarning: Drive not ready, ");
		fmt_print("aborting surface analysis.\n");
		return (-1);
	case DISK_STAT_DATA_PROTECT:
		fmt_print("\n\nWarning: Drive is write protected, ");
		fmt_print("aborting surface analysis.\n");
		return (-1);
	default:
		break;
	}
	return (0);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef	_ANALYZE_H
#define	_ANALYZE_H

#ifdef	__cplusplus
extern "C" {
#endif

/*
 * This file contains definitions related to surface analysis.
 */

/*
 * These are variables referenced by the analysis routines.  They
 * are declared in analyze.c.
 */
extern	int scan_entire;
extern	diskaddr_t scan_lower, scan_upper;
extern	int scan_correct, scan_stop, scan_loop, scan_passes;
extern	int scan_random, scan_auto;
extern	uint_t scan_size;
extern	int scan_restore_defects, scan_restore_label;

/*
 * These variables hold summary info for the end of analysis.
 * They are declared in analyze.c.
 */
extern	offset_t scan_cur_block;
extern	int64_t scan_blocks_fixed;

/*
 * This variable is used to tell whether the most recent surface
 * analysis error was caused by a media defect or some other problem.
 * It is declared in analyze.c.
 */
extern	int media_error;
extern	int disk_error;

/*
 * These defines are flags for the surface analysis types.
 */
#define	SCAN_VALID		0x01		/* read data off disk */
#define	SCAN_PATTERN		0x02		/* write and read pattern */
#define	SCAN_COMPARE		0x04		/* manually check pattern */
#define	SCAN_WRITE		0x08		/* write data to disk */
#define	SCAN_PURGE		0x10		/* purge data on disk */
#define	SCAN_PURGE_READ_PASS	0x20		/* read/compare pass */
#define	SCAN_PURGE_ALPHA_PASS	0x40		/* alpha pattern pass */
#define	SCAN_VERIFY		0x80		/* verify data on disk */
#define	SCAN_VERIFY_READ_PASS	0x100		/* read/compare pass */


/*
 * Miscellaneous defines.
 */
#define	BUF_SECTS		126		/* size of the buffers */
/*
 * Number of passes for purge command.  It is kept here to allow
 * it to be used in menu_analyze.c also
 * This feature is added at the request of Sun Fed.
 */
#define	NPPATTERNS	4	/* number of purge patterns */
#define	READPATTERN	(NPPATTERNS - 1)


/*
 * defines for disk errors during surface analysis.
 */
#define	DISK_STAT_RESERVED		0x01	/* disk is reserved */
#define	DISK_STAT_NOTREADY		0x02	/* disk not ready */
#define	DISK_STAT_UNAVAILABLE		0x03	/* disk is being formatted */
#define	DISK_STAT_DATA_PROTECT		0x04	/* disk is write protected */

/*
 *	Prototypes for ANSI C compilers
 */
int	do_scan(int flags, int mode);

#ifdef	__cplusplus
}
#endif

#endif	/* _ANALYZE_H */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright (c) 2011 Gary Mills
 *
 * Copyright 2010 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 * Copyright 2015 Nexenta Systems, Inc. All rights reserved.
 * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>
 */

/*
 * This file contains functions to implement automatic configuration
 * of scsi disks.
 */
#include "global.h"

#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include <ctype.h>

#include "misc.h"
#include "param.h"
#include "ctlr_scsi.h"
#include "auto_sense.h"
#include "partition.h"
#include "label.h"
#include "startup.h"
#include "analyze.h"
#include "io.h"
#include "hardware_structs.h"
#include "menu_fdisk.h"


#define	DISK_NAME_MAX		256

extern	int			nctypes;
extern	struct	ctlr_type	ctlr_types[];


/*
 * Marker for free hog partition
 */
#define	HOG		(-1)



/*
 * Default partition tables
 *
 *	Disk capacity		root	swap	usr
 *	-------------		----	----	---
 *	0mb to 64mb		0	0	remainder
 *	64mb to 180mb		16mb	16mb	remainder
 *	180mb to 280mb		16mb	32mb	remainder
 *	280mb to 380mb		24mb	32mb	remainder
 *	380mb to 600mb		32mb	32mb	remainder
 *	600mb to 1gb		32mb	64mb	remainder
 *	1gb to 2gb		64mb	128mb	remainder
 *	2gb on up		128mb	128mb	remainder
 */
struct part_table {
	int	partitions[NDKMAP];
};

static struct part_table part_table_64mb = {
	{ 0,	0,	0,	0,	0,	0,	HOG,	0}
};

static struct part_table part_table_180mb = {
	{ 16,	16,	0,	0,	0,	0,	HOG,	0}
};

static struct part_table part_table_280mb = {
	{ 16,	32,	0,	0,	0,	0,	HOG,	0}
};

static struct part_table part_table_380mb = {
	{ 24,	32,	0,	0,	0,	0,	HOG,	0}
};

static struct part_table part_table_600mb = {
	{ 32,	32,	0,	0,	0,	0,	HOG,	0}
};

static struct part_table part_table_1gb = {
	{ 32,	64,	0,	0,	0,	0,	HOG,	0}
};

static struct part_table part_table_2gb = {
	{ 64,	128,	0,	0,	0,	0,	HOG,	0}
};

static struct part_table part_table_infinity = {
	{ 128,	128,	0,	0,	0,	0,	HOG,	0}
};


static struct default_partitions {
	diskaddr_t		min_capacity;
	diskaddr_t		max_capacity;
	struct part_table	*part_table;
} default_partitions[] = {
	{ 0,	64,		&part_table_64mb },	/* 0 to 64 mb */
	{ 64,	180,		&part_table_180mb },	/* 64 to 180 mb */
	{ 180,	280,		&part_table_280mb },	/* 180 to 280 mb */
	{ 280,	380,		&part_table_380mb },	/* 280 to 380 mb */
	{ 380,	600,		&part_table_600mb },	/* 380 to 600 mb */
	{ 600,	1024,		&part_table_1gb },	/* 600 to 1 gb */
	{ 1024,	2048,		&part_table_2gb },	/* 1 to 2 gb */
	{ 2048,	INFINITY,	&part_table_infinity },	/* 2 gb on up */
};

#define	DEFAULT_PARTITION_TABLE_SIZE	\
	(sizeof (default_partitions) / sizeof (struct default_partitions))

/*
 * msgs for check()
 */
#define	FORMAT_MSG	"Auto configuration via format.dat"
#define	GENERIC_MSG	"Auto configuration via generic SCSI-2"

/*
 * Disks on symbios(Hardwire raid controller) return a fixed number
 * of heads(64)/cylinders(64) and adjust the cylinders depending
 * capacity of the configured lun.
 * In such a case we get number of physical cylinders < 3 which
 * is the minimum required by solaris(2 reserved + 1 data cylinders).
 * Hence try to adjust the cylinders by reducing the "nsect/nhead".
 *
 */
/*
 * assuming a minimum of 32 block cylinders.
 */
#define	MINIMUM_NO_HEADS	2
#define	MINIMUM_NO_SECTORS	16

#define	MINIMUM_NO_CYLINDERS	128

#if defined(_SUNOS_VTOC_8)

/* These are 16-bit fields */
#define	MAXIMUM_NO_HEADS	65535
#define	MAXIMUM_NO_SECTORS	65535
#define	MAXIMUM_NO_CYLINDERS	65535

#endif	/* defined(_SUNOS_VTOC_8) */

/*
 * minimum number of cylinders required by Solaris.
 */
#define	SUN_MIN_CYL		3

static struct disk_type	*generic_disk_sense(
				int		fd,
				int		can_prompt,
				struct dk_label	*label,
				struct scsi_inquiry *inquiry,
				struct scsi_capacity_16 *capacity,
				char		*disk_name);
static int		use_existing_disk_type(
				int		fd,
				int		can_prompt,
				struct dk_label	*label,
				struct scsi_inquiry *inquiry,
				struct disk_type *disk_type,
				struct scsi_capacity_16 *capacity);
int			build_default_partition(struct dk_label *label,
				int ctrl_type);
static struct disk_type	*find_scsi_disk_type(
				char		*disk_name,
				struct dk_label	*label);
static struct disk_type	*find_scsi_disk_by_name(
				char		*disk_name);
static struct ctlr_type	*find_scsi_ctlr_type(void);
static struct ctlr_info	*find_scsi_ctlr_info(
				struct dk_cinfo	*dkinfo);
static struct disk_type	*new_scsi_disk_type(
				int		fd,
				char		*disk_name,
				struct dk_label	*label);
static struct disk_info	*find_scsi_disk_info(
				struct dk_cinfo	*dkinfo);

static struct disk_type *new_direct_disk_type(int fd, char *disk_name,
    struct dk_label *label);

static int efi_ioctl(int fd, int cmd, dk_efi_t *dk_ioc);
static int auto_label_init(struct dk_label *label);
static struct ctlr_type *find_ctlr_type(ushort_t);
static struct ctlr_info *find_ctlr_info(struct dk_cinfo	*, ushort_t);
static struct disk_info *find_disk_info(struct dk_cinfo *, ushort_t);

static char		*get_sun_disk_name(
				char		*disk_name,
				struct scsi_inquiry *inquiry);
static char		*strcopy(
				char	*dst,
				char	*src,
				int	n);
static	int		adjust_disk_geometry(diskaddr_t capacity, uint_t *cyl,
				uint_t *nsect, uint_t *nhead);
static void		compute_chs_values(diskaddr_t total_capacity,
				diskaddr_t usable_capacity, uint_t *pcylp,
				uint_t *nheadp, uint_t *nsectp);
#if defined(_SUNOS_VTOC_8)
static diskaddr_t square_box(
			diskaddr_t capacity,
			uint_t *dim1, uint_t lim1,
			uint_t *dim2, uint_t lim2,
			uint_t *dim3, uint_t lim3);
#endif	/* defined(_SUNOS_VTOC_8) */


/*
 * We need to get information necessary to construct a *new* efi
 * label type
 */
struct disk_type *
auto_efi_sense(int fd, struct efi_info *label)
{

	struct dk_gpt	*vtoc;
	int		i;

	struct disk_type *disk, *dp;
	struct disk_info *disk_info;
	struct ctlr_info *ctlr;
	struct dk_cinfo dkinfo;
	struct partition_info *part;
	uint64_t reserved;
	uint16_t type;

	if (ioctl(fd, DKIOCINFO, &dkinfo) == -1) {
		if (option_msg && diag_msg) {
			err_print("DKIOCINFO failed\n");
		}
		return (NULL);
	}
	if (cur_ctype != NULL)
		type = cur_ctype->ctype_ctype;
	else
		type = dkinfo.dki_ctype;

	if (type == DKC_DIRECT || type == DKC_VBD || type == DKC_BLKDEV) {
		ctlr = find_ctlr_info(&dkinfo, type);
		disk_info = find_disk_info(&dkinfo, type);
	} else {
		ctlr = find_scsi_ctlr_info(&dkinfo);
		disk_info = find_scsi_disk_info(&dkinfo);
	}

	/*
	 * get vendor, product, revision and capacity info.
	 */
	if (get_disk_info(fd, label, disk_info) == -1) {
		return (NULL);
	}
	/*
	 * Now build the default partition table
	 */
	if (efi_alloc_and_init(fd, EFI_NUMPAR, &vtoc) != 0) {
		err_print("efi_alloc_and_init failed. \n");
		return (NULL);
	}

	label->e_parts = vtoc;
	reserved = efi_reserved_sectors(vtoc);

	/*
	 * Create a whole hog EFI partition table:
	 * S0 takes the whole disk except the primary EFI label,
	 * backup EFI label, and the reserved partition.
	 */
	vtoc->efi_parts[0].p_tag = V_USR;
	vtoc->efi_parts[0].p_start = vtoc->efi_first_u_lba;
	vtoc->efi_parts[0].p_size = vtoc->efi_last_u_lba - vtoc->efi_first_u_lba
	    - reserved + 1;

	/*
	 * S1-S6 are unassigned slices.
	 */
	for (i = 1; i < vtoc->efi_nparts - 2; i ++) {
		vtoc->efi_parts[i].p_tag = V_UNASSIGNED;
		vtoc->efi_parts[i].p_start = 0;
		vtoc->efi_parts[i].p_size = 0;
	}

	/*
	 * The reserved slice
	 */
	vtoc->efi_parts[vtoc->efi_nparts - 1].p_tag = V_RESERVED;
	vtoc->efi_parts[vtoc->efi_nparts - 1].p_start =
	    vtoc->efi_last_u_lba - reserved + 1;
	vtoc->efi_parts[vtoc->efi_nparts - 1].p_size = reserved;

	/*
	 * Now stick all of it into the disk_type struct
	 */

	disk = (struct disk_type *)zalloc(sizeof (struct disk_type));
	assert(disk_info->disk_ctlr == ctlr);
	dp = ctlr->ctlr_ctype->ctype_dlist;
	if (dp == NULL) {
		ctlr->ctlr_ctype->ctype_dlist = dp;
	} else {
		while (dp->dtype_next != NULL) {
			dp = dp->dtype_next;
		}
		dp->dtype_next = disk;
	}
	disk->dtype_next = NULL;

	disk->vendor = strdup(label->vendor);
	disk->product = strdup(label->product);
	disk->revision = strdup(label->revision);

	if (disk->vendor == NULL ||
	    disk->product == NULL ||
	    disk->revision == NULL) {
		free(disk->vendor);
		free(disk->product);
		free(disk->revision);
		free(disk);
		return (NULL);
	}

	disk->capacity = label->capacity;

	part = (struct partition_info *)
	    zalloc(sizeof (struct partition_info));
	disk->dtype_plist = part;

	part->pinfo_name = alloc_string("default");
	part->pinfo_next = NULL;
	part->etoc = vtoc;

	bzero(disk_info->v_volume, LEN_DKL_VVOL);
	disk_info->disk_parts = part;
	return (disk);
}

static int
efi_ioctl(int fd, int cmd, dk_efi_t *dk_ioc)
{
	void *data = dk_ioc->dki_data;
	int error;

	dk_ioc->dki_data_64 = (uint64_t)(uintptr_t)data;
	error = ioctl(fd, cmd, (void *)dk_ioc);
	dk_ioc->dki_data = data;

	return (error);
}

static struct ctlr_type *
find_ctlr_type(ushort_t type)
{
	struct	mctlr_list	*mlp;

	assert(type == DKC_DIRECT ||
	    type == DKC_VBD ||
	    type == DKC_BLKDEV);

	mlp = controlp;

	while (mlp != NULL) {
		if (mlp->ctlr_type->ctype_ctype == type) {
			return (mlp->ctlr_type);
		}
		mlp = mlp->next;
	}

	impossible("no DIRECT/VBD/BLKDEV controller type");

	return (NULL);
}

static struct ctlr_info *
find_ctlr_info(struct dk_cinfo *dkinfo, ushort_t type)
{
	struct ctlr_info	*ctlr;

	assert(type == DKC_DIRECT ||
	    type == DKC_VBD ||
	    type == DKC_BLKDEV);

	for (ctlr = ctlr_list; ctlr != NULL; ctlr = ctlr->ctlr_next) {
		if (ctlr->ctlr_addr == dkinfo->dki_addr &&
		    ctlr->ctlr_space == dkinfo->dki_space &&
		    ctlr->ctlr_ctype->ctype_ctype == dkinfo->dki_ctype) {
			return (ctlr);
		}
	}

	impossible("no DIRECT/VBD/BLKDEV controller info");
	/*NOTREACHED*/
	return (NULL);
}

static  struct disk_info *
find_disk_info(struct dk_cinfo *dkinfo, ushort_t type)
{
	struct disk_info	*disk;
	struct dk_cinfo		*dp;

	assert(type == DKC_DIRECT ||
	    type == DKC_VBD ||
	    type == DKC_BLKDEV);

	for (disk = disk_list; disk != NULL; disk = disk->disk_next) {
		dp = &disk->disk_dkinfo;
		if (dp->dki_ctype == dkinfo->dki_ctype &&
		    dp->dki_cnum == dkinfo->dki_cnum &&
		    dp->dki_unit == dkinfo->dki_unit &&
		    strcmp(dp->dki_dname, dkinfo->dki_dname) == 0) {
			return (disk);
		}
	}

	impossible("No DIRECT/VBD/BLKDEV disk info instance\n");
	/*NOTREACHED*/
	return (NULL);
}

/*
 * To convert EFI to SMI labels, we need to get label geometry.
 * Unfortunately at this time there is no good way to do so.
 * DKIOCGGEOM will fail if disk is EFI labeled. So we hack around
 * it and clear EFI label, do a DKIOCGGEOM and put the EFI label
 * back on disk.
 * This routine gets the label geometry and initializes the label
 * It uses cur_file as opened device.
 * returns 0 if succeeds or -1 if failed.
 */
static int
auto_label_init(struct dk_label *label)
{
	dk_efi_t	dk_ioc;
	dk_efi_t	dk_ioc_back;
	efi_gpt_t	*data = NULL;
	efi_gpt_t	*databack = NULL;
	struct dk_geom	disk_geom;
	struct dk_minfo	disk_info;
	efi_gpt_t	*backsigp;
	int		fd = cur_file;
	int		rval = -1;
	int		efisize = EFI_LABEL_SIZE * 2;
	int		success = 0;
	uint64_t	sig;
	uint64_t	backsig;

	if ((data = calloc(efisize, 1)) == NULL) {
		err_print("auto_label_init: calloc failed\n");
		goto auto_label_init_out;
	}

	dk_ioc.dki_data = data;
	dk_ioc.dki_lba = 1;
	dk_ioc.dki_length = efisize;

	if (efi_ioctl(fd, DKIOCGETEFI, &dk_ioc) != 0) {
		err_print("auto_label_init: GETEFI failed\n");
		goto auto_label_init_out;
	}

	if ((databack = calloc(efisize, 1)) == NULL) {
		err_print("auto_label_init calloc2 failed");
		goto auto_label_init_out;
	}

	/* get the LBA size and capacity */
	if (ioctl(fd, DKIOCGMEDIAINFO, (caddr_t)&disk_info) == -1) {
		err_print("auto_label_init: dkiocgmediainfo failed\n");
		goto auto_label_init_out;
	}

	if (disk_info.dki_lbsize == 0) {
		if (option_msg && diag_msg) {
			err_print("auto_lbal_init: assuming 512 byte"
			    "block size");
		}
		disk_info.dki_lbsize = DEV_BSIZE;
	}

	dk_ioc_back.dki_data = databack;

	/*
	 * back up efi label goes to capacity - 1, we are reading an extra block
	 * before the back up label.
	 */
	dk_ioc_back.dki_lba = disk_info.dki_capacity - 1 - 1;
	dk_ioc_back.dki_length = efisize;

	if (efi_ioctl(fd, DKIOCGETEFI, &dk_ioc_back) != 0) {
		err_print("auto_label_init: GETEFI backup failed\n");
		goto auto_label_init_out;
	}

	sig = dk_ioc.dki_data->efi_gpt_Signature;
	dk_ioc.dki_data->efi_gpt_Signature = 0x0;

	enter_critical();

	if (efi_ioctl(fd, DKIOCSETEFI, &dk_ioc) == -1) {
		err_print("auto_label_init: SETEFI failed\n");
		exit_critical();
		goto auto_label_init_out;
	}

	backsigp = (efi_gpt_t *)((uintptr_t)dk_ioc_back.dki_data + cur_blksz);

	backsig = backsigp->efi_gpt_Signature;

	backsigp->efi_gpt_Signature = 0;

	if (efi_ioctl(fd, DKIOCSETEFI, &dk_ioc_back) == -1) {
		err_print("auto_label_init: SETEFI backup failed\n");
	}

	if (ioctl(cur_file, DKIOCGGEOM, &disk_geom) != 0)
		err_print("auto_label_init: GGEOM failed\n");
	else
		success = 1;

	dk_ioc.dki_data->efi_gpt_Signature = sig;
	backsigp->efi_gpt_Signature = backsig;

	if (efi_ioctl(cur_file, DKIOCSETEFI, &dk_ioc_back) == -1) {
		err_print("auto_label_init: SETEFI revert backup failed\n");
		success = 0;
	}

	if (efi_ioctl(cur_file, DKIOCSETEFI, &dk_ioc) == -1) {
		err_print("auto_label_init: SETEFI revert failed\n");
		success = 0;
	}

	exit_critical();

	if (success == 0)
		goto auto_label_init_out;

	ncyl = disk_geom.dkg_ncyl;
	acyl = disk_geom.dkg_acyl;
	nhead =  disk_geom.dkg_nhead;
	nsect = disk_geom.dkg_nsect;
	pcyl = ncyl + acyl;

	label->dkl_pcyl = pcyl;
	label->dkl_ncyl = ncyl;
	label->dkl_acyl = acyl;
	label->dkl_nhead = nhead;
	label->dkl_nsect = nsect;
	label->dkl_apc = 0;
	label->dkl_intrlv = 1;
	label->dkl_rpm = disk_geom.dkg_rpm;

	label->dkl_magic = DKL_MAGIC;

	(void) snprintf(label->dkl_asciilabel, sizeof (label->dkl_asciilabel),
	    "%s cyl %u alt %u hd %u sec %u",
	    "DEFAULT", ncyl, acyl, nhead, nsect);

	rval = 0;
#if defined(_FIRMWARE_NEEDS_FDISK)
	(void) auto_solaris_part(label);
	ncyl = label->dkl_ncyl;

#endif	/* defined(_FIRMWARE_NEEDS_FDISK) */

	if (!build_default_partition(label, DKC_DIRECT)) {
		rval = -1;
	}

	(void) checksum(label, CK_MAKESUM);


auto_label_init_out:
	if (data)
		free(data);
	if (databack)
		free(databack);

	return (rval);
}

static struct disk_type *
new_direct_disk_type(
	int		fd,
	char		*disk_name,
	struct dk_label	*label)
{
	struct disk_type	*dp;
	struct disk_type	*disk;
	struct ctlr_info	*ctlr;
	struct dk_cinfo		dkinfo;
	struct partition_info	*part = NULL;
	struct partition_info	*pt;
	struct disk_info	*disk_info;
	int			i;

	/*
	 * Get the disk controller info for this disk
	 */
	if (ioctl(fd, DKIOCINFO, &dkinfo) == -1) {
		if (option_msg && diag_msg) {
			err_print("DKIOCINFO failed\n");
		}
		return (NULL);
	}

	/*
	 * Find the ctlr_info for this disk.
	 */
	ctlr = find_ctlr_info(&dkinfo, dkinfo.dki_ctype);

	/*
	 * Allocate a new disk type for the direct controller.
	 */
	disk = (struct disk_type *)zalloc(sizeof (struct disk_type));

	/*
	 * Find the disk_info instance for this disk.
	 */
	disk_info = find_disk_info(&dkinfo, dkinfo.dki_ctype);

	/*
	 * The controller and the disk should match.
	 */
	assert(disk_info->disk_ctlr == ctlr);

	/*
	 * Link the disk into the list of disks
	 */
	dp = ctlr->ctlr_ctype->ctype_dlist;
	if (dp == NULL) {
		ctlr->ctlr_ctype->ctype_dlist = dp;
	} else {
		while (dp->dtype_next != NULL) {
			dp = dp->dtype_next;
		}
		dp->dtype_next = disk;
	}
	disk->dtype_next = NULL;

	/*
	 * Allocate and initialize the disk name.
	 */
	disk->dtype_asciilabel = alloc_string(disk_name);

	/*
	 * Initialize disk geometry info
	 */
	disk->dtype_pcyl = label->dkl_pcyl;
	disk->dtype_ncyl = label->dkl_ncyl;
	disk->dtype_acyl = label->dkl_acyl;
	disk->dtype_nhead = label->dkl_nhead;
	disk->dtype_nsect = label->dkl_nsect;
	disk->dtype_rpm = label->dkl_rpm;

	part = (struct partition_info *)
	    zalloc(sizeof (struct partition_info));
	pt = disk->dtype_plist;
	if (pt == NULL) {
		disk->dtype_plist = part;
	} else {
		while (pt->pinfo_next != NULL) {
			pt = pt->pinfo_next;
		}
		pt->pinfo_next = part;
	}

	part->pinfo_next = NULL;

	/*
	 * Set up the partition name
	 */
	part->pinfo_name = alloc_string("default");

	/*
	 * Fill in the partition info from the label
	 */
	for (i = 0; i < NDKMAP; i++) {

#if defined(_SUNOS_VTOC_8)
		part->pinfo_map[i] = label->dkl_map[i];

#elif defined(_SUNOS_VTOC_16)
		part->pinfo_map[i].dkl_cylno =
		    label->dkl_vtoc.v_part[i].p_start /
		    ((blkaddr_t)(disk->dtype_nhead *
		    disk->dtype_nsect - apc));
		part->pinfo_map[i].dkl_nblk =
		    label->dkl_vtoc.v_part[i].p_size;
#else
#error No VTOC format defined.
#endif				/* defined(_SUNOS_VTOC_8) */
	}

	/*
	 * Use the VTOC if valid, or install a default
	 */
	if (label->dkl_vtoc.v_version == V_VERSION) {
		(void) memcpy(disk_info->v_volume, label->dkl_vtoc.v_volume,
		    LEN_DKL_VVOL);
		part->vtoc = label->dkl_vtoc;
	} else {
		(void) memset(disk_info->v_volume, 0, LEN_DKL_VVOL);
		set_vtoc_defaults(part);
	}

	/*
	 * Link the disk to the partition map
	 */
	disk_info->disk_parts = part;

	return (disk);
}

/*
 * Get a disk type that has label info. This is used to convert
 * EFI label to SMI label
 */
struct disk_type *
auto_direct_get_geom_label(int fd, struct dk_label *label)
{
	struct disk_type		*disk_type;

	if (auto_label_init(label) != 0) {
		err_print("auto_direct_get_geom_label: failed to get label"
		    "geometry");
		return (NULL);
	} else {
		disk_type = new_direct_disk_type(fd, "DEFAULT", label);
		return (disk_type);
	}
}

/*
 * Auto-sense a scsi disk configuration, ie get the information
 * necessary to construct a label.  We have two different
 * ways to auto-sense a scsi disk:
 *	- format.dat override, via inquiry name
 *	- generic scsi, via standard mode sense and inquiry
 * Depending on how and when we are called, and/or
 * change geometry and reformat.
 */
struct disk_type *
auto_sense(
	int		fd,
	int		can_prompt,
	struct dk_label	*label)
{
	struct scsi_inquiry		inquiry;
	struct scsi_capacity_16		capacity;
	struct disk_type		*disk_type;
	char				disk_name[DISK_NAME_MAX];
	int				force_format_dat = 0;
	int				force_generic = 0;
	u_ioparam_t			ioparam;
	int				deflt;
	char				*buf;

	/*
	 * First, if expert mode, find out if the user
	 * wants to override any of the standard methods.
	 */
	if (can_prompt && expert_mode) {
		deflt = 1;
		ioparam.io_charlist = confirm_list;
		if (input(FIO_MSTR, FORMAT_MSG, '?', &ioparam,
		    &deflt, DATA_INPUT) == 0) {
			force_format_dat = 1;
		} else if (input(FIO_MSTR, GENERIC_MSG, '?', &ioparam,
		    &deflt, DATA_INPUT) == 0) {
			force_generic = 1;
		}
	}

	/*
	 * Get the Inquiry data.  If this fails, there's
	 * no hope for this disk, so give up.
	 */
	if (uscsi_inquiry(fd, (char *)&inquiry, sizeof (inquiry))) {
		return (NULL);
	}
	if (option_msg && diag_msg) {
		err_print("Product id: ");
		print_buf(inquiry.inq_pid, sizeof (inquiry.inq_pid));
		err_print("\n");
	}

	/*
	 * Get the Read Capacity
	 */
	if (uscsi_read_capacity(fd, &capacity)) {
		return (NULL);
	}

	/*
	 * If the reported capacity is set to zero, then the disk
	 * is not usable. If the reported capacity is set to all
	 * 0xf's, then this disk is too large.  These could only
	 * happen with a device that supports LBAs larger than 64
	 * bits which are not defined by any current T10 standards
	 * or by error responding from target.
	 */
	if ((capacity.sc_capacity == 0) ||
	    (capacity.sc_capacity == UINT_MAX64)) {
		if (option_msg && diag_msg) {
			err_print("Invalid capacity\n");
		}
		return (NULL);
	}
	if (option_msg && diag_msg) {
		err_print("blocks:  %llu (0x%llx)\n",
		    capacity.sc_capacity, capacity.sc_capacity);
		err_print("blksize: %u\n", capacity.sc_lbasize);
	}

	/*
	 * Extract the disk name for the format.dat override
	 */
	(void) get_sun_disk_name(disk_name, &inquiry);
	if (option_msg && diag_msg) {
		err_print("disk name:  `%s`\n", disk_name);
	}

	buf = zalloc(cur_blksz);
	if (scsi_rdwr(DIR_READ, fd, (diskaddr_t)0, 1, (caddr_t)buf,
	    F_SILENT, NULL)) {
		free(buf);
		return (NULL);
	}
	free(buf);

	/*
	 * Figure out which method we use for auto sense.
	 * If a particular method fails, we fall back to
	 * the next possibility.
	 */

	if (force_generic) {
		return (generic_disk_sense(fd, can_prompt, label,
		    &inquiry, &capacity, disk_name));
	}

	/*
	 * Try for an existing format.dat first
	 */
	if ((disk_type = find_scsi_disk_by_name(disk_name)) != NULL) {
		if (use_existing_disk_type(fd, can_prompt, label,
		    &inquiry, disk_type, &capacity)) {
			return (disk_type);
		}
		if (force_format_dat) {
			return (NULL);
		}
	}

	/*
	 * Otherwise, try using generic SCSI-2 sense and inquiry.
	 */

	return (generic_disk_sense(fd, can_prompt, label,
	    &inquiry, &capacity, disk_name));
}



/*ARGSUSED*/
static struct disk_type *
generic_disk_sense(
	int			fd,
	int			can_prompt,
	struct dk_label		*label,
	struct scsi_inquiry	*inquiry,
	struct scsi_capacity_16	*capacity,
	char			*disk_name)
{
	struct disk_type		*disk;
	int				setdefault = 0;
	uint_t				pcyl = 0;
	uint_t				ncyl = 0;
	uint_t				acyl = 0;
	uint_t				nhead = 0;
	uint_t				nsect = 0;
	int				rpm = 0;
	diskaddr_t			nblocks = 0;
	diskaddr_t			tblocks = 0;
	union {
		struct mode_format	page3;
		uchar_t			buf3[MAX_MODE_SENSE_SIZE];
	} u_page3;
	union {
		struct mode_geometry	page4;
		uchar_t			buf4[MAX_MODE_SENSE_SIZE];
	} u_page4;
	struct mode_format		*page3 = &u_page3.page3;
	struct mode_geometry		*page4 = &u_page4.page4;
	struct scsi_ms_header		header;

	/*
	 * If the name of this disk appears to be "SUN", use it,
	 * otherwise construct a name out of the generic
	 * Inquiry info.  If it turns out that we already
	 * have a SUN disk type of this name that differs
	 * in geometry, we will revert to the generic name
	 * anyway.
	 */
	if (memcmp(disk_name, "SUN", strlen("SUN")) != 0) {
		(void) get_generic_disk_name(disk_name, inquiry);
	}

	/*
	 * Get the number of blocks from Read Capacity data. Note that
	 * the logical block address range from 0 to capacity->sc_capacity.
	 * Limit the size to 2 TB (UINT32_MAX) to use with SMI labels.
	 */
	tblocks = (capacity->sc_capacity + 1);
	if (tblocks > UINT32_MAX)
		nblocks = UINT32_MAX;
	else
		nblocks = tblocks;

	/*
	 * Get current Page 3 - Format Parameters page
	 */
	if (uscsi_mode_sense(fd, DAD_MODE_FORMAT, MODE_SENSE_PC_CURRENT,
	    (caddr_t)&u_page3, MAX_MODE_SENSE_SIZE, &header)) {
		setdefault = 1;
	}

	/*
	 * Get current Page 4 - Drive Geometry page
	 */
	if (uscsi_mode_sense(fd, DAD_MODE_GEOMETRY, MODE_SENSE_PC_CURRENT,
	    (caddr_t)&u_page4, MAX_MODE_SENSE_SIZE, &header)) {
		setdefault = 1;
	}

	if (setdefault != 1) {
		/* The inquiry of mode page 3 & page 4 are successful */
		/*
		 * Correct for byte order if necessary
		 */
		page4->rpm = BE_16(page4->rpm);
		page4->step_rate = BE_16(page4->step_rate);
		page3->tracks_per_zone = BE_16(page3->tracks_per_zone);
		page3->alt_sect_zone = BE_16(page3->alt_sect_zone);
		page3->alt_tracks_zone = BE_16(page3->alt_tracks_zone);
		page3->alt_tracks_vol = BE_16(page3->alt_tracks_vol);
		page3->sect_track = BE_16(page3->sect_track);
		page3->data_bytes_sect = BE_16(page3->data_bytes_sect);
		page3->interleave = BE_16(page3->interleave);
		page3->track_skew = BE_16(page3->track_skew);
		page3->cylinder_skew = BE_16(page3->cylinder_skew);


		/*
		 * Construct a new label out of the sense data,
		 * Inquiry and Capacity.
		 *
		 * If the disk capacity is > 1TB then simply compute
		 * the CHS values based on the total disk capacity and
		 * not use the values from mode-sense data.
		 */
		if (tblocks > INT32_MAX) {
			compute_chs_values(tblocks, nblocks, &pcyl, &nhead,
			    &nsect);
		} else {
			pcyl = (page4->cyl_ub << 16) + (page4->cyl_mb << 8) +
			    page4->cyl_lb;
			nhead = page4->heads;
			nsect = page3->sect_track;
		}

		rpm = page4->rpm;

		/*
		 * If the number of physical cylinders reported is less
		 * the SUN_MIN_CYL(3) then try to adjust the geometry so that
		 * we have atleast SUN_MIN_CYL cylinders.
		 */
		if (pcyl < SUN_MIN_CYL) {
			if (nhead == 0 || nsect == 0) {
				setdefault = 1;
			} else if (adjust_disk_geometry(
			    (diskaddr_t)(capacity->sc_capacity + 1),
			    &pcyl, &nhead, &nsect)) {
				setdefault = 1;
			}
		}
	}

	/*
	 * Mode sense page 3 and page 4 are obsolete in SCSI-3. For
	 * newly developed large sector size disk, we will not rely on
	 * those two pages but compute geometry directly.
	 */
	if ((setdefault == 1) || (capacity->sc_lbasize != DEV_BSIZE)) {
		/*
		 * If the number of cylinders or the number of heads reported
		 * is zero, we think the inquiry of page 3 and page 4 failed.
		 * We will set the geometry infomation by ourselves.
		 */
		compute_chs_values(tblocks, nblocks, &pcyl, &nhead, &nsect);
	}

	/*
	 * The sd driver reserves 2 cylinders the backup disk label and
	 * the deviceid.  Set the number of data cylinders to pcyl-acyl.
	 */
	acyl = DK_ACYL;
	ncyl = pcyl - acyl;

	if (option_msg && diag_msg) {
		err_print("Geometry:\n");
		err_print("    pcyl:    %u\n", pcyl);
		err_print("    ncyl:    %u\n", ncyl);
		err_print("    heads:   %u\n", nhead);
		err_print("    nsects:  %u\n", nsect);
		err_print("    acyl:    %u\n", acyl);

#if defined(_SUNOS_VTOC_16)
		err_print("    bcyl:    %u\n", bcyl);
#endif			/* defined(_SUNOS_VTOC_16) */

		err_print("    rpm:     %d\n", rpm);
		err_print("    nblocks:     %llu\n", nblocks);
	}

	/*
	 * Some drives do not support page4 or report 0 for page4->rpm,
	 * adjust it to AVG_RPM, 3600.
	 */
	if (rpm < MIN_RPM || rpm > MAX_RPM) {
		if (option_msg && diag_msg)
			err_print("The current rpm value %d is invalid,"
			    " adjusting it to %d\n", rpm, AVG_RPM);
		rpm = AVG_RPM;
	}

	/*
	 * Some drives report 0 for nsect (page 3, byte 10 and 11) if they
	 * have variable number of sectors per track. So adjust nsect.
	 * Also the value is defined as vendor specific, hence check if
	 * it is in a tolerable range. The values (32 and 4 below) are
	 * chosen so that this change below does not generate a different
	 * geometry for currently supported sun disks.
	 */
	if ((nsect == 0) ||
	    ((diskaddr_t)pcyl * nhead * nsect) < (nblocks - nblocks/32) ||
	    ((diskaddr_t)pcyl * nhead * nsect) > (nblocks + nblocks/4)) {
		if (nblocks > (pcyl * nhead)) {
			err_print("Mode sense page(3) reports nsect value"
			    " as %d, adjusting it to %llu\n",
			    nsect, nblocks / (pcyl * nhead));
			nsect = nblocks / (pcyl * nhead);
		} else {
			/* convert capacity to nsect * nhead * pcyl */
			err_print("\nWARNING: Disk geometry is based on "
			    "capacity data.\n\n");
			compute_chs_values(tblocks, nblocks, &pcyl, &nhead,
			    &nsect);
			ncyl = pcyl - acyl;
			if (option_msg && diag_msg) {
				err_print("Geometry:(after adjustment)\n");
				err_print("    pcyl:    %u\n", pcyl);
				err_print("    ncyl:    %u\n", ncyl);
				err_print("    heads:   %u\n", nhead);
				err_print("    nsects:  %u\n", nsect);
				err_print("    acyl:    %u\n", acyl);

#if defined(_SUNOS_VTOC_16)
				err_print("    bcyl:    %u\n", bcyl);
#endif

				err_print("    rpm:     %d\n", rpm);
				err_print("    nblocks:     %llu\n", nblocks);
			}
		}
	}

	/*
	 * Some drives report their physical geometry such that
	 * it is greater than the actual capacity.  Adjust the
	 * geometry to allow for this, so we don't run off
	 * the end of the disk.
	 */
	if (((diskaddr_t)pcyl * nhead * nsect) > nblocks) {
		uint_t	p = pcyl;
		if (option_msg && diag_msg) {
			err_print("Computed capacity (%llu) exceeds actual "
			    "disk capacity (%llu)\n",
			    (diskaddr_t)pcyl * nhead * nsect, nblocks);
		}
		do {
			pcyl--;
		} while (((diskaddr_t)pcyl * nhead * nsect) > nblocks);

		if (can_prompt && expert_mode && !option_f) {
			/*
			 * Try to adjust nsect instead of pcyl to see if we
			 * can optimize. For compatability reasons do this
			 * only in expert mode (refer to bug 1144812).
			 */
			uint_t	n = nsect;
			do {
				n--;
			} while (((diskaddr_t)p * nhead * n) > nblocks);
			if (((diskaddr_t)p * nhead * n) >
			    ((diskaddr_t)pcyl * nhead * nsect)) {
				u_ioparam_t	ioparam;
				int		deflt = 1;
				/*
				 * Ask the user for a choice here.
				 */
				ioparam.io_bounds.lower = 1;
				ioparam.io_bounds.upper = 2;
				err_print("1. Capacity = %llu, with pcyl = %u "
				    "nhead = %u nsect = %u\n",
				    ((diskaddr_t)pcyl * nhead * nsect),
				    pcyl, nhead, nsect);
				err_print("2. Capacity = %llu, with pcyl = %u "
				    "nhead = %u nsect = %u\n",
				    ((diskaddr_t)p * nhead * n),
				    p, nhead, n);
				if (input(FIO_INT, "Select one of the above "
				    "choices ", ':', &ioparam,
				    &deflt, DATA_INPUT) == 2) {
					pcyl = p;
					nsect = n;
				}
			}
		}
	}

#if defined(_SUNOS_VTOC_8)
	/*
	 * Finally, we need to make sure we don't overflow any of the
	 * fields in our disk label.  To do this we need to `square
	 * the box' so to speak.  We will lose bits here.
	 */

	if ((pcyl > MAXIMUM_NO_CYLINDERS &&
	    ((nsect > MAXIMUM_NO_SECTORS) ||
	    (nhead > MAXIMUM_NO_HEADS))) ||
	    ((nsect > MAXIMUM_NO_SECTORS) &&
	    (nhead > MAXIMUM_NO_HEADS))) {
		err_print("This disk is too big to label. "
		    " You will lose some blocks.\n");
	}
	if ((pcyl > MAXIMUM_NO_CYLINDERS) ||
	    (nsect > MAXIMUM_NO_SECTORS) ||
	    (nhead > MAXIMUM_NO_HEADS)) {
		u_ioparam_t	ioparam;
		int		order;
		char		msg[256];

		order = ((pcyl > nhead)<<2) |
		    ((pcyl > nsect)<<1) |
		    (nhead > nsect);
		switch (order) {
		case 0x7: /* pcyl > nhead > nsect */
			nblocks =
			    square_box(nblocks,
			    &pcyl, MAXIMUM_NO_CYLINDERS,
			    &nhead, MAXIMUM_NO_HEADS,
			    &nsect, MAXIMUM_NO_SECTORS);
			break;
		case 0x6: /* pcyl > nsect > nhead */
			nblocks =
			    square_box(nblocks,
			    &pcyl, MAXIMUM_NO_CYLINDERS,
			    &nsect, MAXIMUM_NO_SECTORS,
			    &nhead, MAXIMUM_NO_HEADS);
			break;
		case 0x4: /* nsect > pcyl > nhead */
			nblocks =
			    square_box(nblocks,
			    &nsect, MAXIMUM_NO_SECTORS,
			    &pcyl, MAXIMUM_NO_CYLINDERS,
			    &nhead, MAXIMUM_NO_HEADS);
			break;
		case 0x0: /* nsect > nhead > pcyl */
			nblocks =
			    square_box(nblocks,
			    &nsect, MAXIMUM_NO_SECTORS,
			    &nhead, MAXIMUM_NO_HEADS,
			    &pcyl, MAXIMUM_NO_CYLINDERS);
			break;
		case 0x3: /* nhead > pcyl > nsect */
			nblocks =
			    square_box(nblocks,
			    &nhead, MAXIMUM_NO_HEADS,
			    &pcyl, MAXIMUM_NO_CYLINDERS,
			    &nsect, MAXIMUM_NO_SECTORS);
			break;
		case 0x1: /* nhead > nsect > pcyl */
			nblocks =
			    square_box(nblocks,
			    &nhead, MAXIMUM_NO_HEADS,
			    &nsect, MAXIMUM_NO_SECTORS,
			    &pcyl, MAXIMUM_NO_CYLINDERS);
			break;
		default:
			/* How did we get here? */
			impossible("label overflow adjustment");

			/* Do something useful */
			nblocks =
			    square_box(nblocks,
			    &nhead, MAXIMUM_NO_HEADS,
			    &nsect, MAXIMUM_NO_SECTORS,
			    &pcyl, MAXIMUM_NO_CYLINDERS);
			break;
		}
		if (option_msg && diag_msg &&
		    (capacity->sc_capacity + 1 != nblocks)) {
			err_print("After adjusting geometry you lost"
			    " %llu of %llu blocks.\n",
			    (capacity->sc_capacity + 1 - nblocks),
			    capacity->sc_capacity + 1);
		}
		while (can_prompt && expert_mode && !option_f) {
			int				deflt = 1;

			/*
			 * Allow user to modify this by hand if desired.
			 */
			(void) sprintf(msg,
			    "\nGeometry: %u heads, %u sectors %u cylinders"
			    " result in %llu out of %llu blocks.\n"
			    "Do you want to modify the device geometry",
			    nhead, nsect, pcyl,
			    nblocks, capacity->sc_capacity + 1);

			ioparam.io_charlist = confirm_list;
			if (input(FIO_MSTR, msg, '?', &ioparam,
			    &deflt, DATA_INPUT) != 0)
				break;

			ioparam.io_bounds.lower = MINIMUM_NO_HEADS;
			ioparam.io_bounds.upper = MAXIMUM_NO_HEADS;
			nhead = input(FIO_INT, "Number of heads", ':',
			    &ioparam, (int *)&nhead, DATA_INPUT);
			ioparam.io_bounds.lower = MINIMUM_NO_SECTORS;
			ioparam.io_bounds.upper = MAXIMUM_NO_SECTORS;
			nsect = input(FIO_INT,
			    "Number of sectors per track",
			    ':', &ioparam, (int *)&nsect, DATA_INPUT);
			ioparam.io_bounds.lower = SUN_MIN_CYL;
			ioparam.io_bounds.upper = MAXIMUM_NO_CYLINDERS;
			pcyl = input(FIO_INT, "Number of cylinders",
			    ':', &ioparam, (int *)&pcyl, DATA_INPUT);
			nblocks = (diskaddr_t)nhead * nsect * pcyl;
			if (nblocks > capacity->sc_capacity + 1) {
				err_print("Warning: %llu blocks exceeds "
				    "disk capacity of %llu blocks\n",
				    nblocks,
				    capacity->sc_capacity + 1);
			}
		}
	}
#endif		/* defined(_SUNOS_VTOC_8) */

	ncyl = pcyl - acyl;

	if (option_msg && diag_msg) {
		err_print("\nGeometry after adjusting for capacity:\n");
		err_print("    pcyl:    %u\n", pcyl);
		err_print("    ncyl:    %u\n", ncyl);
		err_print("    heads:   %u\n", nhead);
		err_print("    nsects:  %u\n", nsect);
		err_print("    acyl:    %u\n", acyl);
		err_print("    rpm:     %d\n", rpm);
	}

	(void) memset((char *)label, 0, sizeof (struct dk_label));

	label->dkl_magic = DKL_MAGIC;

	(void) snprintf(label->dkl_asciilabel, sizeof (label->dkl_asciilabel),
	    "%s cyl %u alt %u hd %u sec %u",
	    disk_name, ncyl, acyl, nhead, nsect);

	label->dkl_pcyl = pcyl;
	label->dkl_ncyl = ncyl;
	label->dkl_acyl = acyl;
	label->dkl_nhead = nhead;
	label->dkl_nsect = nsect;
	label->dkl_apc = 0;
	label->dkl_intrlv = 1;
	label->dkl_rpm = rpm;

#if defined(_FIRMWARE_NEEDS_FDISK)
	if (auto_solaris_part(label) == -1)
		goto err;
	ncyl = label->dkl_ncyl;
#endif		/* defined(_FIRMWARE_NEEDS_FDISK) */


	if (!build_default_partition(label, DKC_SCSI_CCS)) {
		goto err;
	}

	(void) checksum(label, CK_MAKESUM);

	/*
	 * Find an existing disk type defined for this disk.
	 * For this to work, both the name and geometry must
	 * match.  If there is no such type, but there already
	 * is a disk defined with that name, but with a different
	 * geometry, construct a new generic disk name out of
	 * the inquiry information.  Whatever name we're
	 * finally using, if there's no such disk type defined,
	 * build a new disk definition.
	 */
	if ((disk = find_scsi_disk_type(disk_name, label)) == NULL) {
		if (find_scsi_disk_by_name(disk_name) != NULL) {
			char	old_name[DISK_NAME_MAX];
			(void) strcpy(old_name, disk_name);
			(void) get_generic_disk_name(disk_name,
			    inquiry);
			if (option_msg && diag_msg) {
				err_print(
"Changing disk type name from '%s' to '%s'\n", old_name, disk_name);
			}
			(void) snprintf(label->dkl_asciilabel,
			    sizeof (label->dkl_asciilabel),
			    "%s cyl %u alt %u hd %u sec %u",
			    disk_name, ncyl, acyl, nhead, nsect);
			(void) checksum(label, CK_MAKESUM);
			disk = find_scsi_disk_type(disk_name, label);
		}
		if (disk == NULL) {
			disk = new_scsi_disk_type(fd, disk_name, label);
			if (disk == NULL)
				goto err;
		}
	}

	return (disk);

err:
	if (option_msg && diag_msg) {
		err_print(
		"Configuration via generic SCSI-2 information failed\n");
	}
	return (NULL);
}


/*ARGSUSED*/
static int
use_existing_disk_type(
	int			fd,
	int			can_prompt,
	struct dk_label		*label,
	struct scsi_inquiry	*inquiry,
	struct disk_type	*disk_type,
	struct scsi_capacity_16	*capacity)
{
	int			pcyl;
	int			acyl;
	int			nhead;
	int			nsect;
	int			rpm;

	/*
	 * Construct a new label out of the format.dat
	 */
	pcyl = disk_type->dtype_pcyl;
	acyl = disk_type->dtype_acyl;
	ncyl = disk_type->dtype_ncyl;
	nhead = disk_type->dtype_nhead;
	nsect = disk_type->dtype_nsect;
	rpm = disk_type->dtype_rpm;

	if (option_msg && diag_msg) {
		err_print("Format.dat geometry:\n");
		err_print("    pcyl:    %u\n", pcyl);
		err_print("    heads:   %u\n", nhead);
		err_print("    nsects:  %u\n", nsect);
		err_print("    acyl:    %u\n", acyl);
		err_print("    rpm:     %d\n", rpm);
	}

	(void) memset((char *)label, 0, sizeof (struct dk_label));

	label->dkl_magic = DKL_MAGIC;

	(void) snprintf(label->dkl_asciilabel, sizeof (label->dkl_asciilabel),
	    "%s cyl %u alt %u hd %u sec %u",
	    disk_type->dtype_asciilabel,
	    ncyl, acyl, nhead, nsect);

	label->dkl_pcyl = pcyl;
	label->dkl_ncyl = ncyl;
	label->dkl_acyl = acyl;
	label->dkl_nhead = nhead;
	label->dkl_nsect = nsect;
	label->dkl_apc = 0;
	label->dkl_intrlv = 1;
	label->dkl_rpm = rpm;

	if (!build_default_partition(label, DKC_SCSI_CCS)) {
		goto err;
	}

	(void) checksum(label, CK_MAKESUM);
	return (1);

err:
	if (option_msg && diag_msg) {
		err_print(
		    "Configuration via format.dat geometry failed\n");
	}
	return (0);
}

int
build_default_partition(
	struct dk_label			*label,
	int				ctrl_type)
{
	int				i;
	int				ncyls[NDKMAP];
	diskaddr_t			nblks;
	int				cyl;
	struct dk_vtoc			*vtoc;
	struct part_table		*pt;
	struct default_partitions	*dpt;
	diskaddr_t			capacity;
	int				freecyls;
	int				blks_per_cyl;
	int				ncyl;

#ifdef lint
	ctrl_type = ctrl_type;
#endif

	/*
	 * Install a default vtoc
	 */
	vtoc = &label->dkl_vtoc;
	vtoc->v_version = V_VERSION;
	vtoc->v_nparts = NDKMAP;
	vtoc->v_sanity = VTOC_SANE;

	for (i = 0; i < NDKMAP; i++) {
		vtoc->v_part[i].p_tag = default_vtoc_map[i].p_tag;
		vtoc->v_part[i].p_flag = default_vtoc_map[i].p_flag;
	}

	/*
	 * Find a partition that matches this disk.  Capacity
	 * is in integral number of megabytes.
	 */
	capacity = ((diskaddr_t)(label->dkl_ncyl) * label->dkl_nhead *
	    label->dkl_nsect) / (diskaddr_t)((1024 * 1024) / cur_blksz);
	dpt = default_partitions;
	for (i = 0; i < DEFAULT_PARTITION_TABLE_SIZE; i++, dpt++) {
		if (capacity >= dpt->min_capacity &&
		    capacity < dpt->max_capacity) {
			break;
		}
	}
	if (i == DEFAULT_PARTITION_TABLE_SIZE) {
		if (option_msg && diag_msg) {
			err_print("No matching default partition (%llu)\n",
			    capacity);
		}
		return (0);
	}
	pt = dpt->part_table;

	/*
	 * Go through default partition table, finding fixed
	 * sized entries.
	 */
	freecyls = label->dkl_ncyl;
	blks_per_cyl = label->dkl_nhead * label->dkl_nsect;
	for (i = 0; i < NDKMAP; i++) {
		if (pt->partitions[i] == HOG || pt->partitions[i] == 0) {
			ncyls[i] = 0;
		} else {
			/*
			 * Calculate number of cylinders necessary
			 * for specified size, rounding up to
			 * the next greatest integral number of
			 * cylinders.  Always give what they
			 * asked or more, never less.
			 */
			nblks = pt->partitions[i] * ((1024*1024)/cur_blksz);
			nblks += (blks_per_cyl - 1);
			ncyls[i] = nblks / blks_per_cyl;
			freecyls -= ncyls[i];
		}
	}

	if (freecyls < 0) {
		if (option_msg && diag_msg) {
			for (i = 0; i < NDKMAP; i++) {
				if (ncyls[i] == 0)
					continue;
				err_print("Partition %d: %u cyls\n",
				    i, ncyls[i]);
			}
			err_print("Free cylinders exhausted (%d)\n",
			    freecyls);
		}
		return (0);
	}
#if defined(i386)
	/*
	 * Set the default boot partition to 1 cylinder
	 */
	ncyls[8] = 1;
	freecyls -= 1;

	/*
	 * If current disk type is not a SCSI disk,
	 * set the default alternates partition to 2 cylinders
	 */
	if (ctrl_type != DKC_SCSI_CCS) {
		ncyls[9] = 2;
		freecyls -= 2;
	}
#endif			/* defined(i386) */

	/*
	 * Set the free hog partition to whatever space remains.
	 * It's an error to have more than one HOG partition,
	 * but we don't verify that here.
	 */
	for (i = 0; i < NDKMAP; i++) {
		if (pt->partitions[i] == HOG) {
			assert(ncyls[i] == 0);
			ncyls[i] = freecyls;
			break;
		}
	}

	/*
	 * Error checking
	 */
	ncyl = 0;
	for (i = 0; i < NDKMAP; i++) {
		ncyl += ncyls[i];
	}
	assert(ncyl == (label->dkl_ncyl));

	/*
	 * Finally, install the partition in the label.
	 */
	cyl = 0;

#if defined(_SUNOS_VTOC_16)
	for (i = NDKMAP/2; i < NDKMAP; i++) {
		if (i == 2 || ncyls[i] == 0)
			continue;
		label->dkl_vtoc.v_part[i].p_start = cyl * blks_per_cyl;
		label->dkl_vtoc.v_part[i].p_size = ncyls[i] * blks_per_cyl;
		cyl += ncyls[i];
	}
	for (i = 0; i < NDKMAP/2; i++) {

#elif defined(_SUNOS_VTOC_8)
	for (i = 0; i < NDKMAP; i++) {

#else
#error No VTOC format defined.
#endif				/* defined(_SUNOS_VTOC_16) */

		if (i == 2 || ncyls[i] == 0) {
#if defined(_SUNOS_VTOC_8)
			if (i != 2) {
				label->dkl_map[i].dkl_cylno = 0;
				label->dkl_map[i].dkl_nblk = 0;
			}
#endif
			continue;
		}
#if defined(_SUNOS_VTOC_8)
		label->dkl_map[i].dkl_cylno = cyl;
		label->dkl_map[i].dkl_nblk = ncyls[i] * blks_per_cyl;
#elif defined(_SUNOS_VTOC_16)
		label->dkl_vtoc.v_part[i].p_start = cyl * blks_per_cyl;
		label->dkl_vtoc.v_part[i].p_size = ncyls[i] * blks_per_cyl;

#else
#error No VTOC format defined.
#endif				/* defined(_SUNOS_VTOC_8) */

		cyl += ncyls[i];
	}

	/*
	 * Set the whole disk partition
	 */
#if defined(_SUNOS_VTOC_8)
	label->dkl_map[2].dkl_cylno = 0;
	label->dkl_map[2].dkl_nblk =
	    label->dkl_ncyl * label->dkl_nhead * label->dkl_nsect;

#elif defined(_SUNOS_VTOC_16)
	label->dkl_vtoc.v_part[2].p_start = 0;
	label->dkl_vtoc.v_part[2].p_size =
	    (label->dkl_ncyl + label->dkl_acyl) * label->dkl_nhead *
	    label->dkl_nsect;
#else
#error No VTOC format defined.
#endif				/* defined(_SUNOS_VTOC_8) */


	if (option_msg && diag_msg) {
		float	scaled;
		err_print("\n");
		for (i = 0; i < NDKMAP; i++) {
#if defined(_SUNOS_VTOC_8)
			if (label->dkl_map[i].dkl_nblk == 0)

#elif defined(_SUNOS_VTOC_16)
			if (label->dkl_vtoc.v_part[i].p_size == 0)

#else
#error No VTOC format defined.
#endif				/* defined(_SUNOS_VTOC_8) */

				continue;
			err_print("Partition %d:   ", i);
#if defined(_SUNOS_VTOC_8)
			scaled = bn2mb(label->dkl_map[i].dkl_nblk);

#elif defined(_SUNOS_VTOC_16)

			scaled = bn2mb(label->dkl_vtoc.v_part[i].p_size);
#else
#error No VTOC format defined.
#endif				/* defined(_SUNOS_VTOC_8) */

			if (scaled > 1024.0) {
				err_print("%6.2fGB  ", scaled/1024.0);
			} else {
				err_print("%6.2fMB  ", scaled);
			}
#if defined(_SUNOS_VTOC_8)
			err_print(" %6d cylinders\n",
			    label->dkl_map[i].dkl_nblk/blks_per_cyl);
#elif defined(_SUNOS_VTOC_16)
			err_print(" %6d cylinders\n",
			    label->dkl_vtoc.v_part[i].p_size/blks_per_cyl);
#else
#error No VTOC format defined.
#endif				/* defined(_SUNOS_VTOC_8) */

		}
		err_print("\n");
	}

	return (1);
}



/*
 * Find an existing scsi disk definition by this name,
 * if possible.
 */
static struct disk_type *
find_scsi_disk_type(
	char			*disk_name,
	struct dk_label		*label)
{
	struct ctlr_type	*ctlr;
	struct disk_type	*dp;

	ctlr = find_scsi_ctlr_type();
	for (dp = ctlr->ctype_dlist; dp != NULL; dp = dp->dtype_next) {
		if (dp->dtype_asciilabel) {
			if ((strcmp(dp->dtype_asciilabel, disk_name) == 0) &&
			    dp->dtype_pcyl == label->dkl_pcyl &&
			    dp->dtype_ncyl == label->dkl_ncyl &&
			    dp->dtype_acyl == label->dkl_acyl &&
			    dp->dtype_nhead == label->dkl_nhead &&
			    dp->dtype_nsect == label->dkl_nsect) {
				return (dp);
			}
		}
	}

	return (NULL);
}


/*
 * Find an existing scsi disk definition by this name,
 * if possible.
 */
static struct disk_type *
find_scsi_disk_by_name(
	char			*disk_name)
{
	struct ctlr_type	*ctlr;
	struct disk_type	*dp;

	ctlr = find_scsi_ctlr_type();
	for (dp = ctlr->ctype_dlist; dp != NULL; dp = dp->dtype_next) {
		if (dp->dtype_asciilabel) {
			if ((strcmp(dp->dtype_asciilabel, disk_name) == 0)) {
				return (dp);
			}
		}
	}

	return (NULL);
}


/*
 * Return a pointer to the ctlr_type structure for SCSI
 * disks.  This list is built into the program, so there's
 * no chance of not being able to find it, unless someone
 * totally mangles the code.
 */
static struct ctlr_type *
find_scsi_ctlr_type(void)
{
	struct	mctlr_list	*mlp;

	mlp = controlp;

	while (mlp != NULL) {
		if (mlp->ctlr_type->ctype_ctype == DKC_SCSI_CCS) {
			return (mlp->ctlr_type);
		}
		mlp = mlp->next;
	}

	impossible("no SCSI controller type");

	return (NULL);
}



/*
 * Return a pointer to the scsi ctlr_info structure.  This
 * structure is allocated the first time format sees a
 * disk on this controller, so it must be present.
 */
static struct ctlr_info *
find_scsi_ctlr_info(
	struct dk_cinfo		*dkinfo)
{
	struct ctlr_info	*ctlr;

	if (dkinfo->dki_ctype != DKC_SCSI_CCS) {
		return (NULL);
	}

	for (ctlr = ctlr_list; ctlr != NULL; ctlr = ctlr->ctlr_next) {
		if (ctlr->ctlr_addr == dkinfo->dki_addr &&
		    ctlr->ctlr_space == dkinfo->dki_space &&
		    ctlr->ctlr_ctype->ctype_ctype == DKC_SCSI_CCS) {
			return (ctlr);
		}
	}

	impossible("no SCSI controller info");

	return (NULL);
}



static struct disk_type *
new_scsi_disk_type(
	int		fd,
	char		*disk_name,
	struct dk_label	*label)
{
	struct disk_type	*dp;
	struct disk_type	*disk;
	struct ctlr_info	*ctlr;
	struct dk_cinfo		dkinfo;
	struct partition_info	*part;
	struct partition_info	*pt;
	struct disk_info	*disk_info;
	int			i;

	/*
	 * Get the disk controller info for this disk
	 */
	if (ioctl(fd, DKIOCINFO, &dkinfo) == -1) {
		if (option_msg && diag_msg) {
			err_print("DKIOCINFO failed\n");
		}
		return (NULL);
	}

	/*
	 * Find the ctlr_info for this disk.
	 */
	ctlr = find_scsi_ctlr_info(&dkinfo);

	/*
	 * Allocate a new disk type for the SCSI controller.
	 */
	disk = (struct disk_type *)zalloc(sizeof (struct disk_type));

	/*
	 * Find the disk_info instance for this disk.
	 */
	disk_info = find_scsi_disk_info(&dkinfo);

	/*
	 * The controller and the disk should match.
	 */
	assert(disk_info->disk_ctlr == ctlr);

	/*
	 * Link the disk into the list of disks
	 */
	dp = ctlr->ctlr_ctype->ctype_dlist;
	if (dp == NULL) {
		ctlr->ctlr_ctype->ctype_dlist = disk;
	} else {
		while (dp->dtype_next != NULL) {
			dp = dp->dtype_next;
		}
		dp->dtype_next = disk;
	}
	disk->dtype_next = NULL;

	/*
	 * Allocate and initialize the disk name.
	 */
	disk->dtype_asciilabel = alloc_string(disk_name);

	/*
	 * Initialize disk geometry info
	 */
	disk->dtype_pcyl = label->dkl_pcyl;
	disk->dtype_ncyl = label->dkl_ncyl;
	disk->dtype_acyl = label->dkl_acyl;
	disk->dtype_nhead = label->dkl_nhead;
	disk->dtype_nsect = label->dkl_nsect;
	disk->dtype_rpm = label->dkl_rpm;

	/*
	 * Attempt to match the partition map in the label
	 * with a know partition for this disk type.
	 */
	for (part = disk->dtype_plist; part; part = part->pinfo_next) {
		if (parts_match(label, part)) {
			break;
		}
	}

	/*
	 * If no match was made, we need to create a partition
	 * map for this disk.
	 */
	if (part == NULL) {
		part = (struct partition_info *)
		    zalloc(sizeof (struct partition_info));
		pt = disk->dtype_plist;
		if (pt == NULL) {
			disk->dtype_plist = part;
		} else {
			while (pt->pinfo_next != NULL) {
				pt = pt->pinfo_next;
			}
			pt->pinfo_next = part;
		}
		part->pinfo_next = NULL;

		/*
		 * Set up the partition name
		 */
		part->pinfo_name = alloc_string("default");

		/*
		 * Fill in the partition info from the label
		 */
		for (i = 0; i < NDKMAP; i++) {

#if defined(_SUNOS_VTOC_8)
			part->pinfo_map[i] = label->dkl_map[i];

#elif defined(_SUNOS_VTOC_16)
			part->pinfo_map[i].dkl_cylno =
			    label->dkl_vtoc.v_part[i].p_start /
			    ((blkaddr32_t)(disk->dtype_nhead *
			    disk->dtype_nsect - apc));
			part->pinfo_map[i].dkl_nblk =
			    label->dkl_vtoc.v_part[i].p_size;
#else
#error No VTOC format defined.
#endif				/* defined(_SUNOS_VTOC_8) */

		}
	}


	/*
	 * Use the VTOC if valid, or install a default
	 */
	if (label->dkl_vtoc.v_version == V_VERSION) {
		(void) memcpy(disk_info->v_volume, label->dkl_vtoc.v_volume,
		    LEN_DKL_VVOL);
		part->vtoc = label->dkl_vtoc;
	} else {
		(void) memset(disk_info->v_volume, 0, LEN_DKL_VVOL);
		set_vtoc_defaults(part);
	}

	/*
	 * Link the disk to the partition map
	 */
	disk_info->disk_parts = part;

	return (disk);
}


/*
 * Delete a disk type from disk type list.
 */
int
delete_disk_type(struct disk_type *disk_type)
{
	struct ctlr_type	*ctlr;
	struct disk_type	*dp, *disk;

	if (cur_ctype->ctype_ctype == DKC_DIRECT ||
	    cur_ctype->ctype_ctype == DKC_VBD ||
	    cur_ctype->ctype_ctype == DKC_BLKDEV)
		ctlr = find_ctlr_type(cur_ctype->ctype_ctype);
	else
		ctlr = find_scsi_ctlr_type();
	if (ctlr == NULL || ctlr->ctype_dlist == NULL) {
		return (-1);
	}

	disk = ctlr->ctype_dlist;
	if (disk == disk_type) {
		ctlr->ctype_dlist = disk->dtype_next;
		if (cur_label == L_TYPE_EFI)
			free(disk->dtype_plist->etoc);
		free(disk->dtype_plist);
		free(disk->vendor);
		free(disk->product);
		free(disk->revision);
		free(disk);
		return (0);
	} else {
		for (dp = disk->dtype_next; dp != NULL;
		    disk = disk->dtype_next, dp = dp->dtype_next) {
			if (dp == disk_type) {
				disk->dtype_next = dp->dtype_next;
				if (cur_label == L_TYPE_EFI)
					free(dp->dtype_plist->etoc);
				free(dp->dtype_plist);
				free(dp->vendor);
				free(dp->product);
				free(dp->revision);
				free(dp);
				return (0);
			}
		}
		return (-1);
	}
}


static struct disk_info *
find_scsi_disk_info(
	struct dk_cinfo		*dkinfo)
{
	struct disk_info	*disk;
	struct dk_cinfo		*dp;

	for (disk = disk_list; disk != NULL; disk = disk->disk_next) {
		assert(dkinfo->dki_ctype == DKC_SCSI_CCS);
		dp = &disk->disk_dkinfo;
		if (dp->dki_ctype == dkinfo->dki_ctype &&
		    dp->dki_cnum == dkinfo->dki_cnum &&
		    dp->dki_unit == dkinfo->dki_unit &&
		    strcmp(dp->dki_dname, dkinfo->dki_dname) == 0) {
			return (disk);
		}
	}

	impossible("No SCSI disk info instance\n");

	return (NULL);
}


static char *
get_sun_disk_name(
	char			*disk_name,
	struct scsi_inquiry	*inquiry)
{
	/*
	 * Extract the sun name of the disk
	 */
	(void) memset(disk_name, 0, DISK_NAME_MAX);
	(void) memcpy(disk_name, (char *)&inquiry->inq_pid[9], 7);

	return (disk_name);
}


char *
get_generic_disk_name(
	char			*disk_name,
	struct scsi_inquiry	*inquiry)
{
	char	*p;

	(void) memset(disk_name, 0, DISK_NAME_MAX);
	p = strcopy(disk_name, inquiry->inq_vid,
	    sizeof (inquiry->inq_vid));
	*p++ = '-';
	p = strcopy(p, inquiry->inq_pid, sizeof (inquiry->inq_pid));
	*p++ = '-';
	p = strcopy(p, inquiry->inq_revision,
	    sizeof (inquiry->inq_revision));

	return (disk_name);
}

/*
 * Copy a string of characters from src to dst, for at
 * most n bytes.  Strip all leading and trailing spaces,
 * and stop if there are any non-printable characters.
 * Return ptr to the next character to be filled.
 */
static char *
strcopy(
	char	*dst,
	char	*src,
	int	n)
{
	int	i;

	while (*src == ' ' && n > 0) {
		src++;
		n--;
	}

	for (i = 0; n-- > 0 && isascii(*src) && isprint(*src); src++) {
		if (*src == ' ') {
			i++;
		} else {
			while (i-- > 0)
				*dst++ = ' ';
			*dst++ = *src;
		}
	}

	*dst = 0;
	return (dst);
}

/*
 * adjust disk geometry.
 * This is used when disk reports a disk geometry page having
 * no of physical cylinders is < 3 which is the minimum required
 * by Solaris (2 for storing labels and at least one as a data
 * cylinder )
 */
int
adjust_disk_geometry(diskaddr_t capacity, uint_t *cyl, uint_t *nhead,
    uint_t *nsect)
{
	uint_t	lcyl = *cyl;
	uint_t	lnhead = *nhead;
	uint_t	lnsect = *nsect;

	assert(lcyl < SUN_MIN_CYL);

	/*
	 * reduce nsect by 2 for each iteration  and re-calculate
	 * the number of cylinders.
	 */
	while (lnsect > MINIMUM_NO_SECTORS &&
	    lcyl < MINIMUM_NO_CYLINDERS) {
		/*
		 * make sure that we do not go below MINIMUM_NO_SECTORS.
		 */
		lnsect = max(MINIMUM_NO_SECTORS, lnsect / 2);
		lcyl   = (capacity) / (lnhead * lnsect);
	}
	/*
	 * If the geometry still does not satisfy
	 * MINIMUM_NO_CYLINDERS then try to reduce the
	 * no of heads.
	 */
	while (lnhead > MINIMUM_NO_HEADS &&
	    lcyl < MINIMUM_NO_CYLINDERS) {
		lnhead = max(MINIMUM_NO_HEADS, lnhead / 2);
		lcyl =  (capacity) / (lnhead * lnsect);
	}
	/*
	 * now we should have atleast SUN_MIN_CYL cylinders.
	 * If we still do not get SUN_MIN_CYL with MINIMUM_NO_HEADS
	 * and MINIMUM_NO_HEADS then return error.
	 */
	if (lcyl < SUN_MIN_CYL)
		return (1);
	else {
		*cyl = lcyl;
		*nhead = lnhead;
		*nsect = lnsect;
		return (0);
	}
}

#if defined(_SUNOS_VTOC_8)
/*
 * Reduce the size of one dimention below a specified
 * limit with a minimum loss of volume.  Dimenstions are
 * assumed to be passed in form the largest value (the one
 * that needs to be reduced) to the smallest value.  The
 * values will be twiddled until they are all less than or
 * equal to their limit.  Returns the number in the new geometry.
 */
static diskaddr_t
square_box(
		diskaddr_t capacity,
		uint_t *dim1, uint_t lim1,
		uint_t *dim2, uint_t lim2,
		uint_t *dim3, uint_t lim3)
{
	uint_t	i;

	/*
	 * Although the routine should work with any ordering of
	 * parameters, it's most efficient if they are passed in
	 * in decreasing magnitude.
	 */
	assert(*dim1 >= *dim2);
	assert(*dim2 >= *dim3);

	/*
	 * This is done in a very arbitrary manner.  We could try to
	 * find better values but I can't come up with a method that
	 * would run in a reasonable amount of time.  That could take
	 * approximately 65535 * 65535 iterations of a dozen flops each
	 * or well over 4G flops.
	 *
	 * First:
	 *
	 * Let's see how far we can go with bitshifts w/o losing
	 * any blocks.
	 */

	for (i = 0; (((*dim1)>>i)&1) == 0 && ((*dim1)>>i) > lim1; i++)
		;
	if (i) {
		*dim1 = ((*dim1)>>i);
		*dim3 = ((*dim3)<<i);
	}

	if (((*dim1) > lim1) || ((*dim2) > lim2) || ((*dim3) > lim3)) {
		double	d[4];

		/*
		 * Second:
		 *
		 * Set the highest value at its limit then calculate errors,
		 * adjusting the 2nd highest value (we get better resolution
		 * that way).
		 */
		d[1] = lim1;
		d[3] = *dim3;
		d[2] = (double)capacity/(d[1]*d[3]);

		/*
		 * If we overflowed the middle term, set it to its limit and
		 * chose a new low term.
		 */
		if (d[2] > lim2) {
			d[2] = lim2;
			d[3] = (double)capacity/(d[1]*d[2]);
		}
		/*
		 * Convert to integers.
		 */
		*dim1 = (int)d[1];
		*dim2 = (int)d[2];
		*dim3 = (int)d[3];
	}
	/*
	 * Fixup any other possible problems.
	 * If this happens, we need a new disklabel format.
	 */
	if (*dim1 > lim1) *dim1 = lim1;
	if (*dim2 > lim2) *dim2 = lim2;
	if (*dim3 > lim3) *dim3 = lim3;
	return (*dim1 * *dim2 * *dim3);
}
#endif /* defined(_SUNOS_VTOC_8) */

/*
 * Calculate CHS values based on the capacity data.
 *
 * NOTE: This function is same as cmlb_convert_geomerty() function in
 * cmlb kernel module.
 */
static void
compute_chs_values(diskaddr_t total_capacity, diskaddr_t usable_capacity,
    uint_t *pcylp, uint_t *nheadp, uint_t *nsectp)
{

	/* Unlabeled SCSI floppy device */
	if (total_capacity < 160) {
		/* Less than 80K */
		*nheadp = 1;
		*pcylp = total_capacity;
		*nsectp = 1;
		return;
	} else if (total_capacity <= 0x1000) {
		*nheadp = 2;
		*pcylp = 80;
		*nsectp = total_capacity / (80 * 2);
		return;
	}

	/*
	 * For all devices we calculate cylinders using the heads and sectors
	 * we assign based on capacity of the device.  The algorithm is
	 * designed to be compatible with the way other operating systems
	 * lay out fdisk tables for X86 and to insure that the cylinders never
	 * exceed 65535 to prevent problems with X86 ioctls that report
	 * geometry.
	 * For some smaller disk sizes we report geometry that matches those
	 * used by X86 BIOS usage. For larger disks, we use SPT that are
	 * multiples of 63, since other OSes that are not limited to 16-bits
	 * for cylinders stop at 63 SPT we make do by using multiples of 63 SPT.
	 *
	 * The following table (in order) illustrates some end result
	 * calculations:
	 *
	 * Maximum number of blocks		nhead	nsect
	 *
	 * 2097152 (1GB)			64	32
	 * 16777216 (8GB)			128	32
	 * 1052819775 (502.02GB)		255	63
	 * 2105639550 (0.98TB)			255	126
	 * 3158459325 (1.47TB)			255	189
	 * 4211279100 (1.96TB)			255	252
	 * 5264098875 (2.45TB)			255	315
	 * ...
	 */

	if (total_capacity <= 0x200000) {
		*nheadp = 64;
		*nsectp = 32;
	} else if (total_capacity <= 0x01000000) {
		*nheadp = 128;
		*nsectp = 32;
	} else {
		*nheadp = 255;

		/* make nsect be smallest multiple of 63 */
		*nsectp = ((total_capacity +
		    (UINT16_MAX * 255 * 63) - 1) /
		    (UINT16_MAX * 255 * 63)) * 63;

		if (*nsectp == 0)
			*nsectp = (UINT16_MAX / 63) * 63;
	}

	if (usable_capacity < total_capacity)
		*pcylp = usable_capacity / ((*nheadp) * (*nsectp));
	else
		*pcylp = total_capacity / ((*nheadp) * (*nsectp));
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright (c) 2011 Gary Mills
 *
 * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef	_AUTO_SENSE_H
#define	_AUTO_SENSE_H

#ifdef	__cplusplus
extern "C" {
#endif

struct scsi_inquiry;	/* anonymous struct */

#ifdef	__STDC__
/*
 *	Prototypes for ANSI C compilers
 */
struct disk_type	*auto_sense(
				int		fd,
				int		can_prompt,
				struct dk_label	*label);

struct disk_type	*auto_efi_sense(
				int			fd,
				struct efi_info		*label);

int			build_default_partition(
				struct dk_label *label,
				int		ctrl_type);
int			delete_disk_type(
				struct disk_type *disk_type);

struct disk_type *auto_direct_get_geom_label(int fd, struct dk_label *label);
char			*get_generic_disk_name(
				char *disk_name,
				struct scsi_inquiry *inquiry);
#else

struct disk_type	*auto_sense();
struct disk_type	*auto_efi_sense();
int			build_default_partition();
struct disk_type *auto_direct_get_geom_label();
char			*get_generic_disk_name();


#endif	/* __STDC__ */

#ifdef	__cplusplus
}
#endif

#endif	/* _AUTO_SENSE_H */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 *
 * copyright (c) 1990, 1991 UNIX System Laboratories, Inc.
 * copyright (c) 1984, 1986, 1987, 1988, 1989, 1990 AT&T
 * All Rights Reserved
 */

#ifndef	_BADSEC_H
#define	_BADSEC_H

#ifdef	__cplusplus
extern "C" {
#endif

#define	BADSECFILE	"/etc/scsi/badsec"
#define	FAILURE	1
#define	SUCCESS	0

#define	MAXBLENT	4
struct	badsec_lst {
	uint_t	bl_cnt;
	struct	badsec_lst *bl_nxt;
	uint_t	bl_sec[MAXBLENT];
};

#define	BADSLSZ		sizeof (struct badsec_lst)
#define	BFI_FORMAT	0
#define	ATA_FORMAT	1

#define	ALTS_ADDPART	0x1	/* add alternate partition		*/
struct	alts_mempart {			/* incore alts partition info	*/
	int	ap_flag;		/* flag for alternate partition	*/
	struct	alts_parttbl *ap_tblp;	/* alts partition table		*/
	uint_t	ap_tbl_secsiz;		/* alts parttbl sector size	*/
	uchar_t	*ap_memmapp;		/* incore alternate sector map	*/
	uchar_t	*ap_mapp;		/* alternate sector map		*/
	uint_t	ap_map_secsiz;		/* alts partmap sector size	*/
	uint_t	ap_map_sectot;		/* alts partmap # sector 	*/
	struct  alts_ent *ap_entp;	/* alternate sector entry table */
	uint_t	ap_ent_secsiz;		/* alts entry sector size	*/
	struct	alts_ent *ap_gbadp;	/* growing badsec entry table	*/
	uint_t	ap_gbadcnt;		/* growing bad sector count	*/
	struct	dkl_partition part;	/* alts partition configuration */
};

/*	size of incore alternate partition memory structure		*/
#define	ALTS_MEMPART_SIZE	sizeof (struct alts_mempart)

struct	altsectbl {			/* working alts info		*/
	struct  alts_ent *ast_entp;	/* alternate sector entry table */
	uint_t	ast_entused;		/* entry used			*/
	struct	alt_info *ast_alttblp;	/* alts info			*/
	uint_t	ast_altsiz;		/* size of alts info		*/
	struct  alts_ent *ast_gbadp;	/* growing bad sector entry ptr */
	uint_t	ast_gbadcnt;		/* growing bad sector entry cnt */
};
/*	size of incore alternate partition memory structure		*/
#define	ALTSECTBL_SIZE	sizeof (struct altsectbl)

/*	macro definitions						*/
#define	byte_to_secsiz(APSIZE, BPS)	(uint_t) \
					((((APSIZE) + (BPS) - 1) \
					    / (uint_t)(BPS)) * (BPS))

#ifdef	__cplusplus
}
#endif

#endif	/* _BADSEC_H */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */



/*
 * This file contains miscellaneous device validation routines.
 */

#include "global.h"
#include <sys/mnttab.h>
#include <sys/mntent.h>
#include <sys/autoconf.h>

#include <signal.h>
#include <malloc.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <libgen.h>
#include <sys/ioctl.h>
#include <sys/fcntl.h>
#include <sys/stat.h>
#include <sys/swap.h>
#include <sys/sysmacros.h>
#include <sys/mkdev.h>
#include <sys/modctl.h>
#include <ctype.h>
#include <libdiskmgt.h>
#include <libnvpair.h>
#include "misc.h"
#include "checkdev.h"
#include <sys/efi_partition.h>

/* Function prototypes */
static struct	swaptable *getswapentries(void);
static void	freeswapentries(struct swaptable *);
static int	getpartition(char *pathname);
static int	checkpartitions(int bm_mounted);

static struct swaptable *
getswapentries(void)
{
	struct swaptable *st;
	struct swapent *swapent;
	int	i, num;
	char	fullpathname[MAXPATHLEN];

	/*
	 * get the number of swap entries
	 */
	if ((num = swapctl(SC_GETNSWP, NULL)) == -1) {
		err_print("swapctl error ");
		fullabort();
	}
	if (num == 0)
		return (NULL);
	if ((st = (swaptbl_t *)malloc(num * sizeof (swapent_t) + sizeof (int)))
	    == NULL) {
		err_print("getswapentries: malloc  failed.\n");
		fullabort();
	}
	swapent = st->swt_ent;
	for (i = 0; i < num; i++, swapent++) {
		if ((swapent->ste_path = malloc(MAXPATHLEN)) == NULL) {
			err_print("getswapentries: malloc  failed.\n");
			fullabort();
		}
	}
	st->swt_n = num;
	if ((num = swapctl(SC_LIST, (void *)st)) == -1) {
		err_print("swapctl error ");
		fullabort();
	}
	swapent = st->swt_ent;
	for (i = 0; i < num; i++, swapent++) {
		if (*swapent->ste_path != '/') {
			(void) snprintf(fullpathname, sizeof (fullpathname),
			    "/dev/%s", swapent->ste_path);
			(void) strcpy(swapent->ste_path, fullpathname);
		}
	}
	return (st);
}

static void
freeswapentries(struct swaptable *st)
{
	struct swapent *swapent;
	int i;

	swapent = st->swt_ent;
	for (i = 0; i < st->swt_n; i++, swapent++)
		free(swapent->ste_path);
	free(st);

}

/*
 *  function getpartition:
 */
static int
getpartition(char *pathname)
{
	int		mfd;
	struct dk_cinfo dkinfo;
	struct stat	stbuf;
	char		raw_device[MAXPATHLEN];
	int		found = -1;

	/*
	 * Map the block device name to the raw device name.
	 * If it doesn't appear to be a device name, skip it.
	 */
	if (match_substr(pathname, "/dev/") == 0)
		return (found);
	(void) strcpy(raw_device, "/dev/r");
	(void) strcat(raw_device, pathname + strlen("/dev/"));
	/*
	 * Determine if this appears to be a disk device.
	 * First attempt to open the device.  If if fails, skip it.
	 */
	if ((mfd = open(raw_device, O_RDWR | O_NDELAY)) < 0) {
		return (found);
	}
	/*
	 * Must be a character device
	 */
	if (fstat(mfd, &stbuf) == -1 || !S_ISCHR(stbuf.st_mode)) {
		(void) close(mfd);
		return (found);
	}
	/*
	 * Attempt to read the configuration info on the disk.
	 */
	if (ioctl(mfd, DKIOCINFO, &dkinfo) < 0) {
		(void) close(mfd);
		return (found);
	}
	/*
	 * Finished with the opened device
	 */
	(void) close(mfd);

	/*
	 * If it's not the disk we're interested in, it doesn't apply.
	 */
	if (cur_disk->disk_dkinfo.dki_ctype != dkinfo.dki_ctype ||
	    cur_disk->disk_dkinfo.dki_cnum != dkinfo.dki_cnum ||
	    cur_disk->disk_dkinfo.dki_unit != dkinfo.dki_unit ||
	    strcmp(cur_disk->disk_dkinfo.dki_dname, dkinfo.dki_dname) != 0) {
		return (found);
	}

	/*
	 *  Extract the partition that is mounted.
	 */
	return (PARTITION(stbuf.st_rdev));
}

/*
 * This Routine checks to see if there are partitions used for swapping overlaps
 * a given portion of a disk. If the start parameter is < 0, it means
 * that the entire disk should be checked
 */
int
checkswap(diskaddr_t start, diskaddr_t end)
{
	struct swaptable *st;
	struct swapent *swapent;
	int		i;
	int		found = 0;
	struct dk_map32	*map;
	int		part;

	/*
	 * If we are only checking part of the disk, the disk must
	 * have a partition map to check against.  If it doesn't,
	 * we hope for the best.
	 */
	if (cur_parts == NULL)
		return (0);

	/*
	 * check for swap entries
	 */
	st = getswapentries();
	/*
	 * if there are no swap entries return.
	 */
	if (st == NULL)
		return (0);
	swapent = st->swt_ent;
	for (i = 0; i < st->swt_n; i++, swapent++) {
		if ((part = getpartition(swapent->ste_path)) != -1) {
			if (start == UINT_MAX64) {
				found = -1;
				break;
			}
			map = &cur_parts->pinfo_map[part];
			if ((start >= (int)(map->dkl_cylno * spc() +
			    map->dkl_nblk)) ||
			    (end < (int)(map->dkl_cylno * spc()))) {
					continue;
			}
			found = -1;
			break;
		};
	}
	freeswapentries(st);
	/*
	 * If we found trouble and we're running from a command file,
	 * quit before doing something we really regret.
	 */

	if (found && option_f) {
		err_print(
"Operation on disks being used for swapping must be interactive.\n");
		cmdabort(SIGINT);
	}

	return (found);


}
/*
 * Determines if there are partitions that are a part of an SVM, VxVM, zpool
 * volume or a live upgrade device,  overlapping a given portion of a disk.
 * Mounts and swap devices are checked in legacy format code.
 */
int
checkdevinuse(char *cur_disk_path, diskaddr_t start, diskaddr_t end, int print,
    int check_label)
{

	int		error;
	int		found = 0;
	int		check = 0;
	int		i;
	int		bm_inuse = 0;
	int		part = 0;
	uint64_t	slice_start, slice_size;
	dm_descriptor_t	*slices = NULL;
	nvlist_t	*attrs = NULL;
	char		*usage;
	char		*name;

	/*
	 * If the user does not want to do in use checking, return immediately.
	 * Normally, this is handled in libdiskmgt. For format, there is more
	 * processing required, so we want to bypass the in use checking
	 * here.
	 */

	if (NOINUSE_SET)
		return (0);

	/*
	 * Skip if it is not a real disk
	 *
	 * There could be two kinds of strings in cur_disk_path
	 * One starts with c?t?d?, while the other is a absolute path of a
	 * block device file.
	 */

	if (*cur_disk_path != 'c') {
		struct	stat	stbuf;
		char		majorname[16];
		major_t		majornum;

		(void) stat(cur_disk_path, &stbuf);
		majornum = major(stbuf.st_rdev);
		(void) modctl(MODGETNAME, majorname, sizeof (majorname),
		    &majornum);

		if (strcmp(majorname, "sd"))
			if (strcmp(majorname, "ssd"))
				if (strcmp(majorname, "cmdk"))
					return (0);
	}

	/*
	 * Truncate the characters following "d*", such as "s*" or "p*"
	 */
	cur_disk_path = basename(cur_disk_path);
	name = strrchr(cur_disk_path, 'd');
	if (name) {
		name++;
		for (; (*name <= '9') && (*name >= '0'); name++) {
		}
		*name = (char)0;
	}


	/*
	 * For format, we get basic 'in use' details from libdiskmgt. After
	 * that we must do the appropriate checking to see if the 'in use'
	 * details require a bit of additional work.
	 */

	dm_get_slices(cur_disk_path, &slices, &error);
	if (error) {
		/*
		 * If ENODEV, it actually means the device is not in use.
		 * We will return 0 without displaying error.
		 */
		if (error != ENODEV) {
			err_print("Error occurred with device in use"
			    "checking: %s\n", strerror(error));
			return (found);
		}
	}
	if (slices == NULL)
		return (found);

	for (i = 0; slices[i] != 0; i++) {
		/*
		 * If we are checking the whole disk
		 * then any and all in use data is
		 * relevant.
		 */
		if (start == UINT_MAX64) {
			name = dm_get_name(slices[i], &error);
			if (error != 0 || !name) {
				err_print("Error occurred with device "
				    "in use checking: %s\n", strerror(error));
				continue;
			}
			if (dm_inuse(name, &usage, DM_WHO_FORMAT, &error) ||
			    error) {
				if (error != 0) {
					dm_free_name(name);
					name = NULL;
					err_print("Error occurred with "
					    "device in use checking: "
					    "%s\n", strerror(error));
					continue;
				}
				dm_free_name(name);
				name = NULL;
				/*
				 * If this is a dump device, then it is
				 * a failure. You cannot format a slice
				 * that is a dedicated dump device.
				 */

				if (strstr(usage, DM_USE_DUMP)) {
					if (print) {
						err_print(usage);
						free(usage);
					}
					dm_free_descriptors(slices);
					return (1);
				}
				/*
				 * We really found a device that is in use.
				 * Set 'found' for the return value, and set
				 * 'check' to indicate below that we must
				 * get the partition number to set bm_inuse
				 * in the event we are trying to label this
				 * device. check_label is set when we are
				 * checking modifications for in use slices
				 * on the device.
				 */
				found ++;
				check = 1;
				if (print) {
					err_print(usage);
					free(usage);
				}
			}
		} else {
			/*
			 * Before getting the in use data, verify that the
			 * current slice is within the range we are checking.
			 */
			attrs = dm_get_attributes(slices[i], &error);
			if (error) {
				err_print("Error occurred with device in use "
				    "checking: %s\n", strerror(error));
				continue;
			}
			if (attrs == NULL) {
				continue;
			}

			(void) nvlist_lookup_uint64(attrs, DM_START,
			    &slice_start);
			(void) nvlist_lookup_uint64(attrs, DM_SIZE,
			    &slice_size);
			if (start >= (slice_start + slice_size) ||
			    (end < slice_start)) {
				nvlist_free(attrs);
				attrs = NULL;
				continue;
			}
			name = dm_get_name(slices[i], &error);
			if (error != 0 || !name) {
				err_print("Error occurred with device "
				    "in use checking: %s\n", strerror(error));
				nvlist_free(attrs);
				attrs = NULL;
				continue;
			}
			if (dm_inuse(name, &usage,
			    DM_WHO_FORMAT, &error) || error) {
				if (error != 0) {
					dm_free_name(name);
					name = NULL;
					err_print("Error occurred with "
					    "device in use checking: "
					    "%s\n", strerror(error));
					nvlist_free(attrs);
					attrs = NULL;
					continue;
				}
				dm_free_name(name);
				name = NULL;
				/*
				 * If this is a dump device, then it is
				 * a failure. You cannot format a slice
				 * that is a dedicated dump device.
				 */
				if (strstr(usage, DM_USE_DUMP)) {
					if (print) {
						err_print(usage);
						free(usage);
					}
					dm_free_descriptors(slices);
					nvlist_free(attrs);
					return (1);
				}
				/*
				 * We really found a device that is in use.
				 * Set 'found' for the return value, and set
				 * 'check' to indicate below that we must
				 * get the partition number to set bm_inuse
				 * in the event we are trying to label this
				 * device. check_label is set when we are
				 * checking modifications for in use slices
				 * on the device.
				 */
				found ++;
				check = 1;
				if (print) {
					err_print(usage);
					free(usage);
				}
			}
		}
		/*
		 * If check is set it means we found a slice(the current slice)
		 * on this device in use in some way.  We potentially want
		 * to check this slice when labeling is
		 * requested. We set bm_inuse with this partition value
		 * for use later if check_label was set when called.
		 */
		if (check) {
			name = dm_get_name(slices[i], &error);
			if (error != 0 || !name) {
				err_print("Error occurred with device "
				    "in use checking: %s\n", strerror(error));
				nvlist_free(attrs);
				attrs = NULL;
				continue;
			}
			part = getpartition(name);
			dm_free_name(name);
			name = NULL;
			if (part != -1) {
				bm_inuse |= 1 << part;
			}
			check = 0;
		}
		/*
		 * If we have attributes then we have successfully
		 * found the slice we were looking for and we also
		 * know this means we are not searching the whole
		 * disk so break out of the loop
		 * now.
		 */
		if (attrs) {
			nvlist_free(attrs);
			break;
		}
	}

	if (slices) {
		dm_free_descriptors(slices);
	}

	/*
	 * The user is trying to label the disk. We have to do special
	 * checking here to ensure they are not trying to modify a slice
	 * that is in use in an incompatible way.
	 */
	if (check_label && bm_inuse) {
		/*
		 * !0 indicates that we found a
		 * problem. In this case, we have overloaded
		 * the use of checkpartitions to work for
		 * in use devices. bm_inuse is representative
		 * of the slice that is in use, not that
		 * is mounted as is in the case of the normal
		 * use of checkpartitions.
		 *
		 * The call to checkpartitions will return !0 if
		 * we are trying to shrink a device that we have found
		 * to be in use above.
		 */
		return (checkpartitions(bm_inuse));
	}

	return (found);
}
/*
 * This routine checks to see if there are mounted partitions overlapping
 * a given portion of a disk.  If the start parameter is < 0, it means
 * that the entire disk should be checked.
 */
int
checkmount(diskaddr_t start, diskaddr_t end)
{
	FILE		*fp;
	int		found = 0;
	struct dk_map32	*map;
	int		part;
	struct mnttab	mnt_record;
	struct mnttab	*mp = &mnt_record;

	/*
	 * If we are only checking part of the disk, the disk must
	 * have a partition map to check against.  If it doesn't,
	 * we hope for the best.
	 */
	if (cur_parts == NULL)
		return (0);

	/*
	 * Lock out interrupts because of the mntent protocol.
	 */
	enter_critical();
	/*
	 * Open the mount table.
	 */
	fp = fopen(MNTTAB, "r");
	if (fp == NULL) {
		err_print("Unable to open mount table.\n");
		fullabort();
	}
	/*
	 * Loop through the mount table until we run out of entries.
	 */
	while ((getmntent(fp, mp)) != -1) {

		if ((part = getpartition(mp->mnt_special)) == -1)
			continue;

		/*
		 * It's a mount on the disk we're checking.  If we are
		 * checking whole disk, then we found trouble.  We can
		 * quit searching.
		 */
		if (start == UINT_MAX64) {
			found = -1;
			break;
		}

		/*
		 * If the partition overlaps the zone we're checking,
		 * then we found trouble.  We can quit searching.
		 */
		map = &cur_parts->pinfo_map[part];
		if ((start >= (int)(map->dkl_cylno * spc() + map->dkl_nblk)) ||
		    (end < (int)(map->dkl_cylno * spc()))) {
			continue;
		}
		found = -1;
		break;
	}
	/*
	 * Close down the mount table.
	 */
	(void) fclose(fp);
	exit_critical();

	/*
	 * If we found trouble and we're running from a command file,
	 * quit before doing something we really regret.
	 */

	if (found && option_f) {
		err_print("Operation on mounted disks must be interactive.\n");
		cmdabort(SIGINT);
	}
	/*
	 * Return the result.
	 */
	return (found);
}

int
check_label_with_swap(void)
{
	int			i;
	struct swaptable *st;
	struct swapent *swapent;
	int	part;
	int	bm_swap = 0;

	/*
	 * If we are only checking part of the disk, the disk must
	 * have a partition map to check against.  If it doesn't,
	 * we hope for the best.
	 */
	if (cur_parts == NULL)
		return (0);	/* Will be checked later */

	/*
	 * Check for swap entries
	 */
	st = getswapentries();
	/*
	 * if there are no swap entries return.
	 */
	if (st == NULL)
		return (0);
	swapent = st->swt_ent;
	for (i = 0; i < st->swt_n; i++, swapent++)
		if ((part = getpartition(swapent->ste_path)) != -1)
				bm_swap |= (1 << part);
	freeswapentries(st);

	return (checkpartitions(bm_swap));
}

/*
 * Check the new label with the existing label on the disk,
 * to make sure that any mounted partitions are not being
 * affected by writing the new label.
 */
int
check_label_with_mount(void)
{
	FILE			*fp;
	int			part;
	struct mnttab		mnt_record;
	struct mnttab		*mp = &mnt_record;
	int			bm_mounted = 0;


	/*
	 * If we are only checking part of the disk, the disk must
	 * have a partition map to check against.  If it doesn't,
	 * we hope for the best.
	 */
	if (cur_parts == NULL)
		return (0);	/* Will be checked later */

	/*
	 * Lock out interrupts because of the mntent protocol.
	 */
	enter_critical();
	/*
	 * Open the mount table.
	 */
	fp = fopen(MNTTAB, "r");
	if (fp == NULL) {
		err_print("Unable to open mount table.\n");
		fullabort();
	}
	/*
	 * Loop through the mount table until we run out of entries.
	 */
	while ((getmntent(fp, mp)) != -1) {
		if ((part = getpartition(mp->mnt_special)) != -1)
			bm_mounted |= (1 << part);
	}
	/*
	 * Close down the mount table.
	 */
	(void) fclose(fp);
	exit_critical();

	return (checkpartitions(bm_mounted));

}

/*
 * This Routine checks if any partitions specified
 * are affected by writing the new label
 */
static int
checkpartitions(int bm_mounted)
{
	struct dk_map32		*n;
	struct dk_map		*o;
	struct dk_allmap	old_map;
	int			i, found = 0;
	struct partition64	o_efi;

	/*
	 * Now we need to check that the current partition list and the
	 * previous partition list (which there must be if we actually
	 * have partitions mounted) overlap  in any way on the mounted
	 * partitions
	 */

	/*
	 * Check if the user wants to online-label an
	 * existing EFI label.
	 */
	if (cur_label == L_TYPE_EFI) {
		for (i = 0; i < EFI_NUMPAR; i++) {
			if (bm_mounted & (1 << i)) {
				o_efi.p_partno = i;
				if (ioctl(cur_file, DKIOCPARTITION, &o_efi)
				    == -1) {
					err_print("Unable to get information "
					    "for EFI partition %d.\n", i);
					return (-1);
				}

				/*
				 * Partition can grow or remain same.
				 */
				if (o_efi.p_start == cur_parts->etoc->
				    efi_parts[i].p_start && o_efi.p_size
				    <= cur_parts->etoc->efi_parts[i].p_size) {
					continue;
				}

				found = -1;
			}
			if (found)
				break;
		}

	} else {

		/*
		 * Get the "real" (on-disk) version of the partition table
		 */
		if (ioctl(cur_file, DKIOCGAPART, &old_map) == -1) {
			err_print("Unable to get current partition map.\n");
			return (-1);
		}
		for (i = 0; i < NDKMAP; i++) {
			if (bm_mounted & (1 << i)) {
				/*
				 * This partition is mounted
				 */
				o = &old_map.dka_map[i];
				n = &cur_parts->pinfo_map[i];
#ifdef DEBUG
				fmt_print(
"checkpartitions :checking partition '%c' \n", i + PARTITION_BASE);
#endif
				/*
				 * If partition is identical, we're fine.
				 * If the partition grows, we're also fine,
				 * because the routines in partition.c check
				 * for overflow. It will (ultimately) be up
				 * to the routines in partition.c to warn
				 * about creation of overlapping partitions.
				 */
				if (o->dkl_cylno == n->dkl_cylno &&
				    o->dkl_nblk <= n->dkl_nblk) {
#ifdef	DEBUG
					if (o->dkl_nblk < n->dkl_nblk) {
						fmt_print(
"- new partition larger by %d blocks", n->dkl_nblk-o->dkl_nblk);
					}
					fmt_print("\n");
#endif
					continue;
				}
#ifdef DEBUG
				fmt_print("- changes; old (%d,%d)->new "
"(%d,%d)\n", o->dkl_cylno, o->dkl_nblk, n->dkl_cylno, n->dkl_nblk);
#endif
				found = -1;
			}
			if (found)
				break;
		}
	}

	/*
	 * If we found trouble and we're running from a command file,
	 * quit before doing something we really regret.
	 */

	if (found && option_f) {
		err_print("Operation on mounted disks or \
disks currently being used for swapping must be interactive.\n");
		cmdabort(SIGINT);
	}
	/*
	 * Return the result.
	 */
	return (found);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef	_CHECKDEV_H
#define	_CHECKDEV_H

#ifdef	__cplusplus
extern "C" {
#endif

/*
 *	Prototypes for ANSI C
 */
int	checkmount(diskaddr_t start, diskaddr_t end);
int	checkswap(diskaddr_t start, diskaddr_t end);
int	check_label_with_mount(void);
int	check_label_with_swap(void);
int	checkdevinuse(char *cur_disk_path, diskaddr_t start, diskaddr_t end,
	    int print, int check_label);


#ifdef	__cplusplus
}
#endif

#endif	/* _CHECKDEV_H */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * This file contains the routines for the IDE drive interface
 */
#include "global.h"

#include <sys/types.h>
#include <sys/param.h>
#include <sys/ioctl.h>
#include <sys/uio.h>
#include <sys/fcntl.h>
#include <memory.h>
#include <malloc.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/byteorder.h>
#include <errno.h>
#if defined(i386)
#include <sys/dktp/altsctr.h>
#endif
#include <sys/dktp/dadkio.h>


#include "startup.h"
#include "misc.h"
#include "ctlr_ata.h"
#include "analyze.h"
#include "param.h"
#include "io.h"
#include "badsec.h"

#include "menu_fdisk.h"

diskaddr_t altsec_offset;

int	wr_altsctr();
int	read_altsctr();
int	updatebadsec();

static int	ata_ck_format(void);
#ifdef i386
static int	ata_ex_cur(struct defect_list *);
static int	ata_wr_cur(struct defect_list *);
static int	ata_repair(diskaddr_t, int);
#endif /* i386 */

struct  ctlr_ops ataops = {
#if defined(sparc)
	ata_rdwr,
	ata_ck_format,
	0,
	0,
	0,
	0,
	0,
	0,
#else
	ata_rdwr,
	ata_ck_format,
	0,
	0,
	ata_ex_cur,
	ata_repair,
	0,
	ata_wr_cur,
#endif	/* defined(sparc) */
};

struct  ctlr_ops pcmcia_ataops = {
	ata_rdwr,
	ata_ck_format,
	0,
	0,
	0,
	0,
	0,
	0,
};


#if defined(i386)
static struct	dkl_partition	*dpart = NULL;
#endif	/* defined(i386) */
extern	struct	badsec_lst	*badsl_chain;
extern	int	badsl_chain_cnt;
extern	struct	badsec_lst	*gbadsl_chain;
extern	int	gbadsl_chain_cnt;
extern	struct	alts_mempart	*ap;

static char *dadkrawioerrs[] = {
	"cmd was successful",		/* DADKIO_STAT_NO_ERROR */
	"device not ready",		/* DADKIO_STAT_NOT_READY */
	"error on medium blkno: %d",	/* DADKIO_STAT_MEDIUM_ERROR */
	"other hardware error",		/* DADKIO_STAT_HARDWARE_ERROR */
	"illegal request",		/* DADKIO_STAT_ILLEGAL_REQUEST */
	"illegal block address: %d",	/* DADKIO_STAT_ILLEGAL_ADDRESS */
	"device write-protected",	/* DADKIO_STAT_WRITE_PROTECTED	*/
	"no response from device",	/* DADKIO_STAT_TIMED_OUT */
	"parity error in data",		/* DADKIO_STAT_PARITY */
	"error on bus",			/* DADKIO_STAT_BUS_ERROR */
	"data recovered via ECC",	/* DADKIO_STAT_SOFT_ERROR */
	"no resources for cmd",		/* DADKIO_STAT_NO_RESOURCES */
	"device is not formatted",	/* DADKIO_STAT_NOT_FORMATTED */
	"device is reserved",		/* DADKIO_STAT_RESERVED */
	"feature not supported",	/* DADKIO_STAT_NOT_SUPPORTED */
	};

/*ARGSUSED6*/
_STATIC int
ata_rdwr(int dir, int fd, diskaddr_t blk64, int secnt, caddr_t bufaddr,
    int flags, int *xfercntp)
{
	int	tmpsec;
	struct dadkio_rwcmd	dadkio_rwcmd;
	blkaddr_t	blkno;

	blkno = (blkaddr_t)blk64;
	bzero((caddr_t)&dadkio_rwcmd, sizeof (struct dadkio_rwcmd));

	tmpsec = secnt * cur_blksz;

	/* Doing raw read */
	dadkio_rwcmd.cmd = (dir == DIR_READ) ? DADKIO_RWCMD_READ :
	    DADKIO_RWCMD_WRITE;
	dadkio_rwcmd.blkaddr = blkno;
	dadkio_rwcmd.buflen  = tmpsec;
	dadkio_rwcmd.flags   = flags;
	dadkio_rwcmd.bufaddr = bufaddr;

	media_error = 0;
	if (cur_ctype->ctype_ctype == DKC_PCMCIA_ATA) {
		/*
		 * PCATA requires to use "p0" when calling
		 *	DIOCTL_RWCMD ioctl() to read/write the label
		 */
		(void) close(fd);
		(void) open_cur_file(FD_USE_P0_PATH);
		fd = cur_file;
	}

	if (ioctl(fd, DIOCTL_RWCMD, &dadkio_rwcmd) == -1) {
		err_print("DIOCTL_RWCMD: %s\n", strerror(errno));
		return (1);
	}

	if (cur_ctype->ctype_ctype == DKC_PCMCIA_ATA) {
		/* Restore cur_file with cur_disk->disk_path */
		(void) open_cur_file(FD_USE_CUR_DISK_PATH);
	}

	switch (dadkio_rwcmd.status.status) {
	case  DADKIO_STAT_NOT_READY:
			disk_error = DISK_STAT_NOTREADY;
			break;
	case  DADKIO_STAT_RESERVED:
			disk_error = DISK_STAT_RESERVED;
			break;
	case  DADKIO_STAT_WRITE_PROTECTED:
			disk_error = DISK_STAT_DATA_PROTECT;
			break;
	case DADKIO_STAT_MEDIUM_ERROR:
			media_error = 1;
			break;
	}

	if (dadkio_rwcmd.status.status) {
		if ((flags & F_SILENT) == 0)
			err_print(dadkrawioerrs[dadkio_rwcmd.status.status],
			    dadkio_rwcmd.status.failed_blk);
		return (1);
	}
	return (0);
}

int
ata_ck_format(void)
{
	char *bufaddr;
	int status;

	bufaddr = (char *)zalloc(4 * cur_blksz);
	status = ata_rdwr(DIR_READ, cur_file, (diskaddr_t)1, 4,
	    (caddr_t)bufaddr, 0, NULL);

	free(bufaddr);

	return (!status);
}


#if defined(i386)

static int
get_alts_slice(void)
{

	int	i;
	int	alts_slice = -1;

	if (cur_parts == NULL) {
		(void) fprintf(stderr, "No current partition list\n");
		return (-1);
	}

	for (i = 0; i < V_NUMPAR && alts_slice == -1; i++) {
		if (cur_parts->vtoc.v_part[i].p_tag == V_ALTSCTR) {
			alts_slice = i;
			dpart = &cur_parts->vtoc.v_part[i];
		}
	}

	if (alts_slice == -1) {
		(void) fprintf(stderr, "NO Alt slice\n");
		return (-1);
	}
	if (!solaris_offset)
		if (copy_solaris_part(&cur_disk->fdisk_part))
			return (-1);

	altsec_offset = dpart->p_start + solaris_offset;

	return (SUCCESS);
}


static int
put_alts_slice(void)
{
	int	status;

	status = wr_altsctr();
	if (status) {
		return (status);
	}

	if (ioctl(cur_file, DKIOCADDBAD, NULL) == -1) {
		(void) fprintf(stderr, "Warning: DKIOCADDBAD ioctl failed\n");
		sync();
		return (-1);
	}
	sync();
	return (0);
}

static int
ata_convert_list(struct defect_list *list, int list_format)
{

	int	i;
	struct  defect_entry    *new_defect;

	switch (list_format) {

	case BFI_FORMAT:
		if (ap->ap_tblp->alts_ent_used) {
			new_defect = calloc(ap->ap_tblp->alts_ent_used,
			    sizeof (struct defect_entry));
			if (new_defect == NULL) {
				err_print(
				    "ata_convert_list: calloc failed\n");
				fullabort();
			}
			list->header.count = ap->ap_tblp->alts_ent_used;
			list->header.magicno = (uint_t)DEFECT_MAGIC;
			list->list = new_defect;
			for (i = 0; i < ap->ap_tblp->alts_ent_used;
			    i++, new_defect++) {
				new_defect->cyl =
				    bn2c((ap->ap_entp)[i].bad_start);
				new_defect->head =
				    bn2h((ap->ap_entp)[i].bad_start);
				new_defect->bfi = UNKNOWN;
				new_defect->sect =
				    bn2s((ap->ap_entp)[i].bad_start);
				new_defect->nbits = UNKNOWN;
			}


		} else {

			list->header.count = 0;
			list->header.magicno = (uint_t)DEFECT_MAGIC;
			new_defect = calloc(1,
			    sizeof (struct defect_entry));
			if (new_defect == NULL) {
				err_print(
				    "ata_convert_list: calloc failed\n");
				fullabort();
			}
			list->list = new_defect;
		}
		break;

	default:
		err_print("ata_convert_list: can't deal with it\n");
		exit(0);
	}
	(void) checkdefsum(list, CK_MAKESUM);
	return (0);
}


/*
 * NB - there used to be a ata_ex_man() which was identical to
 * ata_ex_cur; since it's really not a "manufacturer's list",
 * it's gone; if we ever want that exact functionality back,
 * we can add ata_ex_cur() to the ctlr_ops above.  Otherwise,
 * if this is ever modified to support formatting of IDE drives,
 * we should probably add something that issues the
 * drive Read Defect list rather than getting the s9 info
 * as ata_ex_cur() does.
 */

static int
ata_ex_cur(struct defect_list *list)
{
	int	status;

	status = get_alts_slice();
	if (status)
		return (status);
	status = read_altsctr(dpart);
	if (status) {
		return (status);
	}
	(void) ata_convert_list(list, BFI_FORMAT);
	return (status);
}

int
ata_repair(diskaddr_t bn, int flag)
{

	int	status;
	struct	badsec_lst	*blc_p;
	struct	badsec_lst	*blc_p_nxt;

#ifdef lint
	flag++;
#endif

	(void) get_alts_slice();
	if (!gbadsl_chain) {
		blc_p = (struct badsec_lst *)calloc(1, BADSLSZ);
		if (!blc_p) {
			(void) fprintf(stderr,
		"Unable to allocate memory for additional bad sectors\n");
			return (-1);
		}
		gbadsl_chain = blc_p;
	}
	for (blc_p = gbadsl_chain; blc_p->bl_nxt; )
		blc_p = blc_p->bl_nxt;

	if (blc_p->bl_cnt == MAXBLENT) {
		blc_p->bl_nxt = (struct badsec_lst *)calloc(1, BADSLSZ);
		if (!blc_p->bl_nxt) {
			(void) fprintf(stderr,
		"Unable to allocate memory for additional bad sectors\n");
			return (-1);
		}
		blc_p = blc_p->bl_nxt;
	}
	blc_p->bl_sec[blc_p->bl_cnt++] = (uint_t)bn;
	gbadsl_chain_cnt++;

	(void) updatebadsec(dpart, 0);
	status = put_alts_slice();

	/* clear out the bad sector list chains that were generated */

	if (badsl_chain) {
		if (badsl_chain->bl_nxt == NULL) {
			free(badsl_chain);
		} else {
			for (blc_p = badsl_chain; blc_p; ) {
				blc_p_nxt = blc_p->bl_nxt;
				free(blc_p);
				blc_p = blc_p_nxt;
			}
		}
		badsl_chain = NULL;
		badsl_chain_cnt = 0;
	}

	if (gbadsl_chain) {
		if (gbadsl_chain->bl_nxt == NULL) {
			free(gbadsl_chain);
		} else {
			for (blc_p = gbadsl_chain; blc_p; ) {
				blc_p_nxt = blc_p->bl_nxt;
				free(blc_p);
				blc_p = blc_p_nxt;
			}
		}
		gbadsl_chain = NULL;
		gbadsl_chain_cnt = 0;
	}

	return (status);

}

int
ata_wr_cur(struct defect_list *list)
{
	int	status;
	int	sec_count;
	int	x;
	struct	badsec_lst	*blc_p;
	struct	badsec_lst	*blc_p_nxt;
	struct	defect_entry	*dlist;

	if (list->header.magicno != (uint_t)DEFECT_MAGIC)
		return (-1);

	sec_count = list->header.count;
	dlist = list->list;

	(void) get_alts_slice();
	for (x = 0; x < sec_count; x++) {

		/* test for unsupported list format */
		if ((dlist->bfi != UNKNOWN) || (dlist->nbits != UNKNOWN)) {
			(void) fprintf(stderr,
			    "BFI unsuported format for bad sectors\n");
			return (-1);
		}

		if (!gbadsl_chain) {
			blc_p = (struct badsec_lst *)calloc(1, BADSLSZ);
			if (!blc_p) {
				(void) fprintf(stderr,
		"Unable to allocate memory for additional bad sectors\n");
				return (-1);
			}
			gbadsl_chain = blc_p;
		}

		for (blc_p = gbadsl_chain; blc_p->bl_nxt; )
			blc_p = blc_p->bl_nxt;

		if (blc_p->bl_cnt == MAXBLENT) {
			blc_p->bl_nxt = (struct badsec_lst *)calloc(1, BADSLSZ);
			if (!blc_p->bl_nxt) {
				(void) fprintf(stderr,
		"Unable to allocate memory for additional bad sectors\n");
				return (-1);
			}
			blc_p = blc_p->bl_nxt;
		}
		blc_p->bl_sec[blc_p->bl_cnt++] =
		    (uint_t)chs2bn(dlist->cyl, dlist->head, dlist->sect);
		gbadsl_chain_cnt++;
		dlist++;
	}


	(void) updatebadsec(dpart, 0);
	status = put_alts_slice();

	/* clear out the bad sector list chains that were generated */

	if (badsl_chain) {
		if (badsl_chain->bl_nxt == NULL) {
			free(badsl_chain);
		} else {
			for (blc_p = badsl_chain; blc_p; ) {
				blc_p_nxt = blc_p->bl_nxt;
				free(blc_p);
				blc_p = blc_p_nxt;
			}
		}
		badsl_chain = NULL;
		badsl_chain_cnt = 0;
	}

	if (gbadsl_chain) {
		if (gbadsl_chain->bl_nxt == NULL) {
			free(gbadsl_chain);
		} else {
			for (blc_p = gbadsl_chain; blc_p; ) {
				blc_p_nxt = blc_p->bl_nxt;
				free(blc_p);
				blc_p = blc_p_nxt;
			}
		}
		gbadsl_chain = NULL;
		gbadsl_chain_cnt = 0;
	}

	return (status);
}

#endif	/*  defined(i386)  */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef	_CTLR_ATA_H
#define	_CTLR_ATA_H

#ifdef	__cplusplus
extern "C" {
#endif

#include <sys/buf.h>


/*
 * Rounded parameter, as returned in Extended Sense information
 */
#define	ROUNDED_PARAMETER	0x37


/*
 * Convert a three-byte triplet into an int
 */
#define	TRIPLET(u, m, l)	((int)((((u))&0xff<<16) + \
				(((m)&0xff)<<8) + (l&0xff)))
#if	defined(i386)
extern diskaddr_t	altsec_offset;	/* Alternate sector offset */
#endif	/* defined(i386) */

/*
 *	Local prototypes for ANSI C compilers
 */

#if	defined(i386)
#define	_STATIC
#else
#define	_STATIC	static
#endif	/* defined(i386) */

_STATIC int	ata_rdwr(int, int, diskaddr_t, int, caddr_t, int, int *);

int	ata_ex_man(struct defect_list *);
int	ata_ex_grown(struct defect_list *);
int	ata_read_defect_data(struct defect_list *, int);
int	apply_chg_list(int, int, uchar_t *, uchar_t *, struct chg_list *);

#ifdef	__cplusplus
}
#endif

#endif	/* _CTLR_ATA_H */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright (c) 1991, 2010, Oracle and/or its affiliates. All rights reserved.
 * Copyright (c) 2016 by Delphix. All rights reserved.
 */

/*
 * This file contains the routines for embedded scsi disks
 */
#include "global.h"

#include <sys/types.h>
#include <sys/param.h>
#include <sys/ioctl.h>
#include <sys/uio.h>
#include <sys/fcntl.h>
#include <errno.h>
#include <memory.h>
#include <malloc.h>
#include <unistd.h>
#include <stdlib.h>
#include <values.h>
#include <sys/byteorder.h>



#include "startup.h"
#include "scsi_com.h"
#include "misc.h"
#include "ctlr_scsi.h"
#include "analyze.h"
#include "param.h"
#include "io.h"


#ifndef	DAD_MODE_CACHE_CCS
#define	DAD_MODE_CACHE_CCS		0x38
#endif /* DAD_MODE_CACHE_CCS */

/* format defect header bits */
#define	FDH_FOV				0x80
#define	FDH_IMMED			0x02

#define	SENSE_LEN			20

#define	RETRY_DELAY			5

#define	PROGRESS_INDICATION_BASE	65536

static int	scsi_format(uint64_t, uint64_t, struct defect_list *);
static int	scsi_raw_format(void);
static int	scsi_ms_page8(int);
static int	scsi_ms_page38(int);
static void	scsi_convert_list_to_new(struct defect_list *,
			struct scsi_defect_list *, int);
static char	*scsi_find_command_name(uint_t);
static int	chg_list_affects_page(struct chg_list *, int);
static void	scsi_printerr(struct uscsi_cmd *,
			struct scsi_extended_sense *, int);
static diskaddr_t
scsi_extract_sense_info_descr(struct scsi_descr_sense_hdr *sdsp, int rqlen);

static void	scsi_print_extended_sense(struct scsi_extended_sense *, int);
static void	scsi_print_descr_sense(struct scsi_descr_sense_hdr *, int);

static int	test_until_ready(int fd);
static int	uscsi_reserve_release(int, int);
static int	check_support_for_defects(void);
static int	scsi_format_without_defects(void);
static int	scsi_ms_page1(int);
static int	scsi_ms_page2(int);
static int	scsi_ms_page3(int);
static int	scsi_ms_page4(int);
static int	scsi_repair(uint64_t, int);
static int	scsi_read_defect_data(struct defect_list *, int);
static int	scsi_ck_format(void);

struct	ctlr_ops scsiops = {
	scsi_rdwr,
	scsi_ck_format,
	scsi_format,
	scsi_ex_man,
	scsi_ex_cur,
	scsi_repair,
	0,
};

#define	SCMD_UNKNOWN		0xff

/*
 * Names of commands.  Must have SCMD_UNKNOWN at end of list.
 */
static struct scsi_command_name {
	uchar_t command;
	char *name;
} scsi_command_names[] = {
	SCMD_FORMAT,		"format",
	SCMD_READ,		"read",
	SCMD_WRITE,		"write",
	SCMD_READ|SCMD_GROUP1,	"read",
	SCMD_WRITE|SCMD_GROUP1,	"write",
	SCMD_INQUIRY,		"inquiry",
	SCMD_MODE_SELECT,	"mode select",
	SCMD_MODE_SENSE,	"mode sense",
	SCMD_REASSIGN_BLOCK,	"reassign block",
	SCMD_READ_DEFECT_LIST,	"read defect list",
	SCMD_UNKNOWN,		"unknown"
};


/*
 * Strings for printing mode sense page control values
 */
static slist_t page_control_strings[] = {
	{ "current",	"",	MODE_SENSE_PC_CURRENT },
	{ "changeable",	"",	MODE_SENSE_PC_CHANGEABLE },
	{ "default",	"",	MODE_SENSE_PC_DEFAULT },
	{ "saved",	"",	MODE_SENSE_PC_SAVED }
};

/*
 * Strings for printing the mode select options
 */
static slist_t mode_select_strings[] = {
	{ "",		"",	0 },
	{ " (pf)",	"",	MODE_SELECT_PF },
	{ " (sp)",	"",	MODE_SELECT_SP },
	{ " (pf,sp)",	"",	MODE_SELECT_PF|MODE_SELECT_SP }
};

static int scsi_format_revolutions = 5;
static int scsi_format_timeout = 2 * 60 * 60;		/* two hours */

/*
 * READ DEFECT DATA commands is optional as per SCSI-2 spec.
 * Hence check if the read_defect_data command fails with
 * Invalid Opcode so that we can give a more meaningful message
 * to the user.
 */
#define	INVALID_OPCODE	0x20

/*
 * Read or write the disk.
 */
int
scsi_rdwr(int dir, int fd, diskaddr_t blkno, int secnt, caddr_t bufaddr,
    int flags, int *xfercntp)
{
	struct uscsi_cmd	ucmd;
	union scsi_cdb		cdb;
	int	max_sectors;
	int	rc = 0;

	/*
	 * If the max xfercnt hasn't been determined start with BUF_SECTS
	 * (currently 126 == 63K), otherwise use the xfercnt value
	 * my caller saved from the previous invocation.
	 */
	if (xfercntp == NULL) {
		max_sectors = BUF_SECTS;
	} else if (*xfercntp == 0) {
		max_sectors = BUF_SECTS;
		*xfercntp = max_sectors;
	} else {
		max_sectors = *xfercntp;
	}

	/*
	 * Build and execute the uscsi ioctl.  We build a group0
	 * or group1 command as necessary, since some targets
	 * do not support group1 commands.
	 */
	while (secnt)  {
		int	nsectors;

		nsectors = (max_sectors < secnt) ? max_sectors : secnt;
		(void) memset((char *)&ucmd, 0, sizeof (ucmd));
		(void) memset((char *)&cdb, 0, sizeof (union scsi_cdb));
		cdb.scc_cmd = (dir == DIR_READ) ? SCMD_READ : SCMD_WRITE;
		if (blkno < (2<<20) && nsectors <= 0xff) {
			FORMG0ADDR(&cdb, blkno);
			FORMG0COUNT(&cdb, nsectors);
			ucmd.uscsi_cdblen = CDB_GROUP0;
		} else {
			if (blkno > 0xffffffff) {
				FORMG4LONGADDR(&cdb, blkno);
				FORMG4COUNT(&cdb, nsectors);
				ucmd.uscsi_cdblen = CDB_GROUP4;
				cdb.scc_cmd |= SCMD_GROUP4;
			} else {
				FORMG1ADDR(&cdb, blkno);
				FORMG1COUNT(&cdb, nsectors);
				ucmd.uscsi_cdblen = CDB_GROUP1;
				cdb.scc_cmd |= SCMD_GROUP1;
			}
		}
		ucmd.uscsi_cdb = (caddr_t)&cdb;
		ucmd.uscsi_bufaddr = bufaddr;
		ucmd.uscsi_buflen = nsectors * cur_blksz;
		rc = uscsi_cmd(fd, &ucmd, flags);

		if (rc != 0)
			break;

		/*
		 * check if partial DMA breakup required
		 * if so, reduce the request size by half and retry
		 * the last request
		 */
		if (ucmd.uscsi_resid == ucmd.uscsi_buflen) {
			max_sectors >>= 1;
			if (max_sectors <= 0) {
				rc = -1;
				break;
			}
			continue;
		}
		if (ucmd.uscsi_resid != 0) {
			rc = -1;
			break;
		}

		blkno += nsectors;
		secnt -= nsectors;
		bufaddr += nsectors * cur_blksz;
	}

	/*
	 * If the xfercnt wasn't previously saved or if the
	 * new value is smaller than the old value, save the
	 * current value in my caller's save area.
	 */
	if (xfercntp != NULL && max_sectors < *xfercntp) {
		if (diag_msg)
			err_print("reducing xfercnt %d %d\n",
			    *xfercntp, max_sectors);
		*xfercntp = max_sectors;
	}
	return (rc);
}


/*
 * Check to see if the disk has been formatted.
 * If we are able to read the first track, we conclude that
 * the disk has been formatted.
 */
static int
scsi_ck_format(void)
{
	int	status;

	/*
	 * Try to read the first four blocks.
	 */
	status = scsi_rdwr(DIR_READ, cur_file, (diskaddr_t)0, 4,
	    (caddr_t)cur_buf, F_SILENT, NULL);
	return (!status);
}


/*
 * Format the disk, the whole disk, and nothing but the disk.
 */
static int
scsi_format(uint64_t start __unused, uint64_t end, struct defect_list *list)
{
	struct uscsi_cmd	ucmd;
	union scsi_cdb		cdb;
	int			status;
	int			flag;
	char			rawbuf[MAX_MODE_SENSE_SIZE];
	struct scsi_inquiry	*inq;
	uint8_t	fmt_prot_info;
	uint8_t	prot_field_usage;
	uint8_t	param_long_list = 1;
	uint8_t	fmt_long_param_header[8];

	/*
	 * Determine if the target appears to be SCSI-2
	 * compliant.  We handle mode sense/mode selects
	 * a little differently, depending upon CCS/SCSI-2
	 */
	if (uscsi_inquiry(cur_file, rawbuf, sizeof (rawbuf))) {
		err_print("Inquiry failed\n");
		return (-1);
	}
	inq = (struct scsi_inquiry *)rawbuf;
	flag = (inq->inq_rdf == RDF_SCSI2);

	/*
	 * Reserve the scsi disk before performing mode select and
	 * format operations. This will keep other hosts, if any, from
	 * touching the disk while we are here.
	 */
	if (uscsi_reserve_release(cur_file, SCMD_RESERVE)) {
		err_print("Reserve failed\n");
		return (-1);
	}

	/*
	 * Set up the various SCSI parameters specified before
	 * formatting the disk.  Each routine handles the
	 * parameters relevant to a particular page.
	 * If no parameters are specified for a page, there's
	 * no need to do anything.  Otherwise, issue a mode
	 * sense for that page.  If a specified parameter
	 * differs from the drive's default value, and that
	 * parameter is not fixed, then issue a mode select to
	 * set the default value for the disk as specified
	 * in format.dat.
	 */
	if (scsi_ms_page1(flag) || scsi_ms_page2(flag) ||
	    scsi_ms_page4(flag) || scsi_ms_page38(flag) ||
	    scsi_ms_page8(flag) || scsi_ms_page3(flag)) {
		(void) uscsi_reserve_release(cur_file, SCMD_RELEASE);
		return (-1);
	}

	/*
	 * If we're debugging the drive, dump every page
	 * the device supports, for thorough analysis.
	 */
	if (option_msg && diag_msg) {
		(void) scsi_dump_mode_sense_pages(MODE_SENSE_PC_DEFAULT);
		(void) scsi_dump_mode_sense_pages(MODE_SENSE_PC_CURRENT);
		(void) scsi_dump_mode_sense_pages(MODE_SENSE_PC_SAVED);
		(void) scsi_dump_mode_sense_pages(MODE_SENSE_PC_CHANGEABLE);
		err_print("\n");
	}

	/*
	 * Determine the FMTPINFO field in format cdb, and the
	 * PROTECTION FIELD USAGE in the long parameter list, via
	 * the protection type input by users.
	 */
	switch (prot_type) {
	case PROT_TYPE_0:
		fmt_prot_info = 0x00;
		prot_field_usage = 0x00;
		break;
	case PROT_TYPE_1:
		fmt_prot_info = 0x02;
		prot_field_usage = 0x00;
		break;
	case PROT_TYPE_2:
		fmt_prot_info = 0x03;
		prot_field_usage = 0x00;
		break;
	case PROT_TYPE_3:
		fmt_prot_info = 0x03;
		prot_field_usage = 0x01;
		break;
	default:
		fmt_print("invalid protection type\n");
		return (-1);
	}

	/*
	 * Construct the uscsi format ioctl.  The form depends
	 * upon the defect list the user extracted.  If they
	 * extracted the "original" list, we format with only
	 * the P (manufacturer's defect) list.  Otherwise, we
	 * format with both the P and the G (grown) list.
	 * To format with the P and G list, we set the fmtData
	 * bit, and send an empty list.  To format with the
	 * P list only, we also set the cmpLst bit, meaning
	 * that the (empty) list we send down is the complete
	 * G list, thereby discarding the old G list..
	 */
	(void) memset((char *)&ucmd, 0, sizeof (ucmd));
	(void) memset((char *)&cdb, 0, sizeof (union scsi_cdb));

	cdb.scc_cmd		= SCMD_FORMAT;
	ucmd.uscsi_cdb		= (caddr_t)&cdb;
	ucmd.uscsi_cdblen	= CDB_GROUP0;
	cdb.cdb_opaque[1]	= FPB_DATA;

	/*
	 * Use the long parameter header in format command,
	 * and set the FMTPINFO field., when type 1, 2, 3.
	 */
	cdb.cdb_opaque[1] |= (param_long_list << 5) | (fmt_prot_info << 6);
	(void) memset((char *)fmt_long_param_header, 0,
	    sizeof (fmt_long_param_header));

	/*
	 * Set the PROTECTION FIELD USAGE field in the long
	 * parameter list header, which combines with FMTINFO to
	 * determine the protection type.
	 * The PROTECTION INTERVAL EXPONET field is set default 0.
	 * So only one protection information interval is used
	 * in type 1, 2, 3.
	 */
	fmt_long_param_header[0] = prot_field_usage;
	fmt_long_param_header[1] = FDH_FOV | FDH_IMMED;
	ucmd.uscsi_bufaddr = (caddr_t)fmt_long_param_header;
	ucmd.uscsi_buflen = sizeof (fmt_long_param_header);

	if ((list->list != NULL) && ((list->flags & LIST_PGLIST) == 0)) {
		/*
		 * No G list.  The empty list we send down
		 * is the complete list.
		 */
		cdb.cdb_opaque[1] |= FPB_CMPLT;
	}

	/*
	 * Issue the format ioctl
	 */
	fmt_print("Formatting...\n");
	(void) fflush(stdout);
	status = uscsi_cmd(cur_file, &ucmd,
	    (option_msg && diag_msg) ? F_NORMAL : F_SILENT);

	/* check if format with immed was successfully accepted */
	if (status == 0) {
		/* immed accepted poll to completion */
		status = test_until_ready(cur_file);
	} else {
		/* clear FOV and try again */
		(void) memset((char *)fmt_long_param_header, 0,
		    sizeof (fmt_long_param_header));
		fmt_long_param_header[0] = prot_field_usage;
		fmt_long_param_header[1] = FDH_IMMED;
		status = uscsi_cmd(cur_file, &ucmd,
		    (option_msg && diag_msg) ? F_NORMAL : F_SILENT);
		if (status == 0) {
			/* immed accepted, poll for progress */
			status = test_until_ready(cur_file);
		} else {
			/*
			 * clear defect header and try basecase format
			 * command will hang until format complete
			 */
			(void) memset((char *)fmt_long_param_header, 0,
			    sizeof (fmt_long_param_header));
			fmt_long_param_header[0] = prot_field_usage;
			status = uscsi_cmd(cur_file, &ucmd,
			    (option_msg && diag_msg) ? F_NORMAL : F_SILENT);
		}
	}

	/* format failure check					*/
	if (status != 0) {
		/*
		 * formatting failed with fmtdata = 1.
		 * Check if defects list command is supported, if it
		 * is not supported then use fmtdata = 0.
		 *	From SCSI Spec
		 *	    A FmtData bit of zero indicates, the
		 *	    source of defect information is not specified.
		 * else
		 *	proceed to format using with mode selects.
		 */
		if (!(check_support_for_defects())) {
			status = scsi_format_without_defects();
		}

		if (status != 0) {
			fmt_print("Format failed\n");
			status = scsi_raw_format();
		}
	}
	(void) uscsi_reserve_release(cur_file, SCMD_RELEASE);
	return (status);
}

/*
 * Format without any of the standard mode selects ignoring Grown defects list.
 */
static int
scsi_raw_format(void)
{
	struct uscsi_cmd	ucmd;
	union scsi_cdb		cdb;
	struct scsi_defect_hdr	defect_hdr;
	int			status;

	fmt_print("\n"
	    "Retry of formatting operation without any of the standard\n"
	    "mode selects and ignoring disk's Grown Defects list.  The\n"
	    "disk may be able to be reformatted this way if an earlier\n"
	    "formatting operation was interrupted by a power failure or\n"
	    "SCSI bus reset.  The Grown Defects list will be recreated\n"
	    "by format verification and surface analysis.\n\n");

	if (check("Retry format without mode selects and Grown Defects list")
	    != 0) {
		return (-1);
	}

	/*
	 * Construct the uscsi format ioctl.
	 * To format with the P and G list, we set the fmtData
	 * and cmpLst bits to zero.  To format with just the
	 * P list, we set the fmtData bit (meaning that we will
	 * send down a defect list in the data phase) and the
	 * cmpLst bit (meaning that the list we send is the
	 * complete G list), and a defect list header with
	 * a defect list length of zero.
	 */
	(void) memset((char *)&ucmd, 0, sizeof (ucmd));
	(void) memset((char *)&cdb, 0, sizeof (union scsi_cdb));
	(void) memset((char *)&defect_hdr, 0, sizeof (defect_hdr));

	cdb.scc_cmd		= SCMD_FORMAT;
	ucmd.uscsi_cdb		= (caddr_t)&cdb;
	ucmd.uscsi_cdblen	= CDB_GROUP0;
	/* No G list.   Send empty defect list to replace it */
	cdb.cdb_opaque[1]	= FPB_DATA | FPB_CMPLT | FPB_BFI;
	ucmd.uscsi_bufaddr	= (caddr_t)&defect_hdr;
	ucmd.uscsi_buflen	= sizeof (defect_hdr);
	defect_hdr.descriptor	= FDH_FOV | FDH_IMMED;

	/*
	 * Issue the format ioctl
	 */
	fmt_print("Formatting...\n");
	(void) fflush(stdout);
	status = uscsi_cmd(cur_file, &ucmd, F_NORMAL);

	/* check if format with immed was successfully accepted */
	if (status == 0) {
		/* immed accepted pool to completion */
		status = test_until_ready(cur_file);
	} else {
		/* clear defect header and try basecase format */
		(void) memset((char *)&defect_hdr, 0, sizeof (defect_hdr));
		status = uscsi_cmd(cur_file, &ucmd, F_NORMAL);
	}

	/* fmt_print(status ? "Format failed\n\n" : "Format ok\n\n"); */
	return (status);
}

/*
 * Estimate the time required for format operation (See 1163770).
 * format time = (5_revs * p4_heads * p4_cylinders) / p4_rpm
 * 5 revolutions (correspond to format_time keyword in format.dat file) are:
 *	1 rev.  for positioning
 *	2 rev.  for writing the track
 *	1 rev.  for positioning
 *	1 rev.  for cerifying the data integrity of the track
 * The return value is a good estimate on the formatting time in minutes.
 * Caller should add 50% margin to cover defect management overhead.
 */
int
scsi_format_time(void)
{
	struct mode_geometry		*page4;
	struct scsi_ms_header		header;
	int				status;
	int				p4_cylinders, p4_heads, p4_rpm;
	int				length;
	int				format_time;
	union {
		struct mode_geometry	page4;
		char			rawbuf[MAX_MODE_SENSE_SIZE];
	} u_page4;


	page4 = &u_page4.page4;
	(void) memset(&u_page4, 0, sizeof (u_page4));

	/*
	 * Issue a mode sense to determine the default parameters
	 * If it fail, try to use the saved or current instead.
	 */
	status = uscsi_mode_sense(cur_file, DAD_MODE_GEOMETRY,
	    MODE_SENSE_PC_DEFAULT, (caddr_t)page4,
	    MAX_MODE_SENSE_SIZE, &header);

	if (status) {
		status = uscsi_mode_sense(cur_file, DAD_MODE_GEOMETRY,
		    MODE_SENSE_PC_SAVED, (caddr_t)page4,
		    MAX_MODE_SENSE_SIZE, &header);
	}
	if (status) {
		status = uscsi_mode_sense(cur_file, DAD_MODE_GEOMETRY,
		    MODE_SENSE_PC_CURRENT, (caddr_t)page4,
		    MAX_MODE_SENSE_SIZE, &header);
	}
	if (status) {
		return (0);
	}

	/*
	 * We only need the common subset between the CCS
	 * and SCSI-2 structures, so we can treat both
	 * cases identically.
	 */
	length = MODESENSE_PAGE_LEN(page4);
	if (length < MIN_PAGE4_LEN) {
		return (0);
	}

	page4->rpm = BE_16(page4->rpm);
	p4_cylinders = (page4->cyl_ub << 16) + (page4->cyl_mb << 8) +
	    page4->cyl_lb;
	p4_heads = page4->heads;
	p4_rpm = page4->rpm;

	/*
	 * Some drives report 0 for page4->rpm, adjust it to AVG_RPM, 3600.
	 */
	if (p4_rpm < MIN_RPM || p4_rpm > MAX_RPM) {
		err_print("Mode sense page(4) reports rpm value as %d,"
		    " adjusting it to %d\n", p4_rpm, AVG_RPM);
		p4_rpm = AVG_RPM;
	}

	if (p4_cylinders <= 0 || p4_heads <= 0)
		return (0);

	format_time = ((scsi_format_revolutions * p4_heads *
	    p4_cylinders) + p4_rpm) / p4_rpm;

	if (option_msg && diag_msg) {
		err_print("       pcyl:    %d\n", p4_cylinders);
		err_print("      heads:    %d\n", p4_heads);
		err_print("        rpm:    %d\n", p4_rpm);
		err_print("format_time:    %d minutes\n", format_time);
	}
	return (format_time);
}

/*
 * Check disk error recovery parameters via mode sense.
 * Issue a mode select if we need to change something.
 */
static int
scsi_ms_page1(int scsi2_flag __unused)
{
	struct mode_err_recov		*page1;
	struct mode_err_recov		*fixed;
	struct scsi_ms_header		header;
	struct scsi_ms_header		fixed_hdr;
	int				status;
	int				tmp1, tmp2;
	int				flag;
	int				length;
	int				sp_flags;
	union {
		struct mode_err_recov	page1;
		char			rawbuf[MAX_MODE_SENSE_SIZE];
	} u_page1, u_fixed;


	page1 = &u_page1.page1;
	fixed = &u_fixed.page1;

	/*
	 * If debugging, issue mode senses on the default and
	 * current values.
	 */
	if (option_msg && diag_msg) {
		(void) uscsi_mode_sense(cur_file, DAD_MODE_ERR_RECOV,
		    MODE_SENSE_PC_DEFAULT, (caddr_t)page1,
		    MAX_MODE_SENSE_SIZE, &header);
		(void) uscsi_mode_sense(cur_file, DAD_MODE_ERR_RECOV,
		    MODE_SENSE_PC_CURRENT, (caddr_t)page1,
		    MAX_MODE_SENSE_SIZE, &header);
	}

	/*
	 * Issue a mode sense to determine the saved parameters
	 * If the saved values fail, use the current instead.
	 */
	status = uscsi_mode_sense(cur_file, DAD_MODE_ERR_RECOV,
	    MODE_SENSE_PC_SAVED, (caddr_t)page1,
	    MAX_MODE_SENSE_SIZE, &header);
	if (status) {
		status = uscsi_mode_sense(cur_file, DAD_MODE_ERR_RECOV,
		    MODE_SENSE_PC_CURRENT, (caddr_t)page1,
		    MAX_MODE_SENSE_SIZE, &header);
		if (status) {
			return (0);
		}
	}

	/*
	 * We only need the common subset between the CCS
	 * and SCSI-2 structures, so we can treat both
	 * cases identically.  Whatever the drive gives
	 * us, we return to the drive in the mode select,
	 * delta'ed by whatever we want to change.
	 */
	length = MODESENSE_PAGE_LEN(page1);
	if (length < MIN_PAGE1_LEN) {
		return (0);
	}

	/*
	 * Ask for changeable parameters.
	 */
	status = uscsi_mode_sense(cur_file, DAD_MODE_ERR_RECOV,
	    MODE_SENSE_PC_CHANGEABLE, (caddr_t)fixed,
	    MAX_MODE_SENSE_SIZE, &fixed_hdr);
	if (status || MODESENSE_PAGE_LEN(fixed) < MIN_PAGE1_LEN) {
		return (0);
	}

	/*
	 * We need to issue a mode select only if one or more
	 * parameters need to be changed, and those parameters
	 * are flagged by the drive as changeable.
	 */
	flag = 0;
	tmp1 = page1->read_retry_count;
	tmp2 = page1->write_retry_count;
	if (cur_dtype->dtype_options & SUP_READ_RETRIES &&
	    fixed->read_retry_count != 0) {
		flag |= (page1->read_retry_count !=
		    cur_dtype->dtype_read_retries);
		page1->read_retry_count = cur_dtype->dtype_read_retries;
	}
	if (length > 8) {
		if (cur_dtype->dtype_options & SUP_WRITE_RETRIES &&
		    fixed->write_retry_count != 0) {
			flag |= (page1->write_retry_count !=
			    cur_dtype->dtype_write_retries);
			page1->write_retry_count =
			    cur_dtype->dtype_write_retries;
		}
	}
	/*
	 * Report any changes so far...
	 */
	if (flag && option_msg) {
		fmt_print("PAGE 1: read retries= %d (%d) "
		    " write retries= %d (%d)\n",
		    page1->read_retry_count, tmp1,
		    page1->write_retry_count, tmp2);
	}
	/*
	 * Apply any changes requested via the change list method
	 */
	flag |= apply_chg_list(DAD_MODE_ERR_RECOV, length,
	    (uchar_t *)page1, (uchar_t *)fixed, cur_dtype->dtype_chglist);
	/*
	 * If no changes required, do not issue a mode select
	 */
	if (flag == 0) {
		return (0);
	}
	/*
	 * We always want to set the Page Format bit for mode
	 * selects.  Set the Save Page bit if the drive indicates
	 * that it can save this page via the mode sense.
	 */
	sp_flags = MODE_SELECT_PF;
	if (page1->mode_page.ps) {
		sp_flags |= MODE_SELECT_SP;
	}
	page1->mode_page.ps = 0;
	header.mode_header.length = 0;
	header.mode_header.device_specific = 0;
	status = uscsi_mode_select(cur_file, DAD_MODE_ERR_RECOV,
	    sp_flags, (caddr_t)page1, length, &header);
	if (status && (sp_flags & MODE_SELECT_SP)) {
		/* If failed, try not saving mode select params. */
		sp_flags &= ~MODE_SELECT_SP;
		status = uscsi_mode_select(cur_file, DAD_MODE_ERR_RECOV,
		    sp_flags, (caddr_t)page1, length, &header);
		}
	if (status && option_msg) {
		err_print("Warning: Using default error recovery "
		    "parameters.\n\n");
	}

	/*
	 * If debugging, issue mode senses on the current and
	 * saved values, so we can see the result of the mode
	 * selects.
	 */
	if (option_msg && diag_msg) {
		(void) uscsi_mode_sense(cur_file, DAD_MODE_ERR_RECOV,
		    MODE_SENSE_PC_CURRENT, (caddr_t)page1,
		    MAX_MODE_SENSE_SIZE, &header);
		(void) uscsi_mode_sense(cur_file, DAD_MODE_ERR_RECOV,
		    MODE_SENSE_PC_SAVED, (caddr_t)page1,
		    MAX_MODE_SENSE_SIZE, &header);
	}

	return (0);
}

/*
 * Check disk disconnect/reconnect parameters via mode sense.
 * Issue a mode select if we need to change something.
 */
static int
scsi_ms_page2(int scsi2_flag __unused)
{
	struct mode_disco_reco		*page2;
	struct mode_disco_reco		*fixed;
	struct scsi_ms_header		header;
	struct scsi_ms_header		fixed_hdr;
	int				status;
	int				flag;
	int				length;
	int				sp_flags;
	union {
		struct mode_disco_reco	page2;
		char			rawbuf[MAX_MODE_SENSE_SIZE];
	} u_page2, u_fixed;

	page2 = &u_page2.page2;
	fixed = &u_fixed.page2;

	/*
	 * If debugging, issue mode senses on the default and
	 * current values.
	 */
	if (option_msg && diag_msg) {
		(void) uscsi_mode_sense(cur_file, MODEPAGE_DISCO_RECO,
		    MODE_SENSE_PC_DEFAULT, (caddr_t)page2,
		    MAX_MODE_SENSE_SIZE, &header);
		(void) uscsi_mode_sense(cur_file, MODEPAGE_DISCO_RECO,
		    MODE_SENSE_PC_CURRENT, (caddr_t)page2,
		    MAX_MODE_SENSE_SIZE, &header);
	}

	/*
	 * Issue a mode sense to determine the saved parameters
	 * If the saved values fail, use the current instead.
	 */
	status = uscsi_mode_sense(cur_file, MODEPAGE_DISCO_RECO,
	    MODE_SENSE_PC_SAVED, (caddr_t)page2,
	    MAX_MODE_SENSE_SIZE, &header);
	if (status) {
		status = uscsi_mode_sense(cur_file, MODEPAGE_DISCO_RECO,
		    MODE_SENSE_PC_CURRENT, (caddr_t)page2,
		    MAX_MODE_SENSE_SIZE, &header);
		if (status) {
			return (0);
		}
	}

	/*
	 * We only need the common subset between the CCS
	 * and SCSI-2 structures, so we can treat both
	 * cases identically.  Whatever the drive gives
	 * us, we return to the drive in the mode select,
	 * delta'ed by whatever we want to change.
	 */
	length = MODESENSE_PAGE_LEN(page2);
	if (length < MIN_PAGE2_LEN) {
		return (0);
	}

	/*
	 * Ask for changeable parameters.
	 */
	status = uscsi_mode_sense(cur_file, MODEPAGE_DISCO_RECO,
	    MODE_SENSE_PC_CHANGEABLE, (caddr_t)fixed,
	    MAX_MODE_SENSE_SIZE, &fixed_hdr);
	if (status || MODESENSE_PAGE_LEN(fixed) < MIN_PAGE2_LEN) {
		return (0);
	}

	/*
	 * We need to issue a mode select only if one or more
	 * parameters need to be changed, and those parameters
	 * are flagged by the drive as changeable.
	 */
	flag = 0;
	/*
	 * Apply any changes requested via the change list method
	 */
	flag |= apply_chg_list(MODEPAGE_DISCO_RECO, length,
	    (uchar_t *)page2, (uchar_t *)fixed, cur_dtype->dtype_chglist);
	/*
	 * If no changes required, do not issue a mode select
	 */
	if (flag == 0) {
		return (0);
	}
	/*
	 * We always want to set the Page Format bit for mode
	 * selects.  Set the Save Page bit if the drive indicates
	 * that it can save this page via the mode sense.
	 */
	sp_flags = MODE_SELECT_PF;
	if (page2->mode_page.ps) {
		sp_flags |= MODE_SELECT_SP;
	}
	page2->mode_page.ps = 0;
	header.mode_header.length = 0;
	header.mode_header.device_specific = 0;
	status = uscsi_mode_select(cur_file, MODEPAGE_DISCO_RECO,
	    MODE_SELECT_SP, (caddr_t)page2, length, &header);
	if (status && (sp_flags & MODE_SELECT_SP)) {
		/* If failed, try not saving mode select params. */
		sp_flags &= ~MODE_SELECT_SP;
		status = uscsi_mode_select(cur_file, MODEPAGE_DISCO_RECO,
		    sp_flags, (caddr_t)page2, length, &header);
		}
	if (status && option_msg) {
		err_print("Warning: Using default .\n\n");
	}

	/*
	 * If debugging, issue mode senses on the current and
	 * saved values, so we can see the result of the mode
	 * selects.
	 */
	if (option_msg && diag_msg) {
		(void) uscsi_mode_sense(cur_file, MODEPAGE_DISCO_RECO,
		    MODE_SENSE_PC_CURRENT, (caddr_t)page2,
		    MAX_MODE_SENSE_SIZE, &header);
		(void) uscsi_mode_sense(cur_file, MODEPAGE_DISCO_RECO,
		    MODE_SENSE_PC_SAVED, (caddr_t)page2,
		    MAX_MODE_SENSE_SIZE, &header);
	}

	return (0);
}

/*
 * Check disk format parameters via mode sense.
 * Issue a mode select if we need to change something.
 */
static int
scsi_ms_page3(int scsi2_flag __unused)
{
	struct mode_format		*page3;
	struct mode_format		*fixed;
	struct scsi_ms_header		header;
	struct scsi_ms_header		fixed_hdr;
	int				status;
	int				tmp1, tmp2, tmp3;
	int				tmp4, tmp5, tmp6;
	int				flag;
	int				length;
	int				sp_flags;
	union {
		struct mode_format	page3;
		char			rawbuf[MAX_MODE_SENSE_SIZE];
	} u_page3, u_fixed;


	page3 = &u_page3.page3;
	fixed = &u_fixed.page3;

	/*
	 * If debugging, issue mode senses on the default and
	 * current values.
	 */
	if (option_msg && diag_msg) {
		(void) uscsi_mode_sense(cur_file, DAD_MODE_FORMAT,
		    MODE_SENSE_PC_DEFAULT, (caddr_t)page3,
		    MAX_MODE_SENSE_SIZE, &header);
		(void) uscsi_mode_sense(cur_file, DAD_MODE_FORMAT,
		    MODE_SENSE_PC_CURRENT, (caddr_t)page3,
		    MAX_MODE_SENSE_SIZE, &header);
	}

	/*
	 * Issue a mode sense to determine the saved parameters
	 * If the saved values fail, use the current instead.
	 */
	status = uscsi_mode_sense(cur_file, DAD_MODE_FORMAT,
	    MODE_SENSE_PC_SAVED, (caddr_t)page3,
	    MAX_MODE_SENSE_SIZE, &header);
	if (status) {
		status = uscsi_mode_sense(cur_file, DAD_MODE_FORMAT,
		    MODE_SENSE_PC_CURRENT, (caddr_t)page3,
		    MAX_MODE_SENSE_SIZE, &header);
		if (status) {
			return (0);
		}
	}

	/*
	 * We only need the common subset between the CCS
	 * and SCSI-2 structures, so we can treat both
	 * cases identically.  Whatever the drive gives
	 * us, we return to the drive in the mode select,
	 * delta'ed by whatever we want to change.
	 */
	length = MODESENSE_PAGE_LEN(page3);
	if (length < MIN_PAGE3_LEN) {
		return (0);
	}

	/*
	 * Ask for changeable parameters.
	 */
	status = uscsi_mode_sense(cur_file, DAD_MODE_FORMAT,
	    MODE_SENSE_PC_CHANGEABLE, (caddr_t)fixed,
	    MAX_MODE_SENSE_SIZE, &fixed_hdr);
	if (status || MODESENSE_PAGE_LEN(fixed) < MIN_PAGE3_LEN) {
		return (0);
	}

	/*
	 * We need to issue a mode select only if one or more
	 * parameters need to be changed, and those parameters
	 * are flagged by the drive as changeable.
	 */
	tmp1 = page3->track_skew;
	tmp2 = page3->cylinder_skew;
	tmp3 = page3->sect_track;
	tmp4 = page3->tracks_per_zone;
	tmp5 = page3->alt_tracks_vol;
	tmp6 = page3->alt_sect_zone;

	flag = (page3->data_bytes_sect != cur_blksz);
	page3->data_bytes_sect = cur_blksz;

	flag |= (page3->interleave != 1);
	page3->interleave = 1;

	if (cur_dtype->dtype_options & SUP_CYLSKEW &&
	    fixed->cylinder_skew != 0) {
		flag |= (page3->cylinder_skew != cur_dtype->dtype_cyl_skew);
		page3->cylinder_skew = cur_dtype->dtype_cyl_skew;
	}
	if (cur_dtype->dtype_options & SUP_TRKSKEW && fixed->track_skew != 0) {
		flag |= (page3->track_skew != cur_dtype->dtype_trk_skew);
		page3->track_skew = cur_dtype->dtype_trk_skew;
	}
	if (cur_dtype->dtype_options & SUP_PSECT && fixed->sect_track != 0) {
		flag |= (page3->sect_track != psect);
		page3->sect_track = (ushort_t)psect;
	}
	if (cur_dtype->dtype_options & SUP_TRKS_ZONE &&
	    fixed->tracks_per_zone != 0) {
		flag |= (page3->tracks_per_zone != cur_dtype->dtype_trks_zone);
		page3->tracks_per_zone = cur_dtype->dtype_trks_zone;
	}
	if (cur_dtype->dtype_options & SUP_ASECT && fixed->alt_sect_zone != 0) {
		flag |= (page3->alt_sect_zone != cur_dtype->dtype_asect);
		page3->alt_sect_zone = cur_dtype->dtype_asect;
	}
	if (cur_dtype->dtype_options & SUP_ATRKS &&
	    fixed->alt_tracks_vol != 0) {
		flag |= (page3->alt_tracks_vol != cur_dtype->dtype_atrks);
		page3->alt_tracks_vol = cur_dtype->dtype_atrks;
	}
	/*
	 * Notify user of any changes so far
	 */
	if (flag && option_msg) {
		fmt_print("PAGE 3: trk skew= %d (%d)   cyl skew= %d (%d)   ",
		    page3->track_skew, tmp1, page3->cylinder_skew, tmp2);
		fmt_print("sects/trk= %d (%d)\n", page3->sect_track, tmp3);
		fmt_print("        trks/zone= %d (%d)   alt trks= %d (%d)   ",
		    page3->tracks_per_zone, tmp4,
		    page3->alt_tracks_vol, tmp5);
		fmt_print("alt sects/zone= %d (%d)\n",
		    page3->alt_sect_zone, tmp6);
	}
	/*
	 * Apply any changes requested via the change list method
	 */
	flag |= apply_chg_list(DAD_MODE_FORMAT, length,
	    (uchar_t *)page3, (uchar_t *)fixed, cur_dtype->dtype_chglist);
	/*
	 * If no changes required, do not issue a mode select
	 */
	if (flag == 0) {
		return (0);
	}
	/*
	 * Issue a mode select
	 */
	/*
	 * We always want to set the Page Format bit for mode
	 * selects.  Set the Save Page bit if the drive indicates
	 * that it can save this page via the mode sense.
	 */
	sp_flags = MODE_SELECT_PF;
	if (page3->mode_page.ps) {
		sp_flags |= MODE_SELECT_SP;
	}
	page3->mode_page.ps = 0;
	header.mode_header.length = 0;
	header.mode_header.device_specific = 0;
	status = uscsi_mode_select(cur_file, DAD_MODE_FORMAT,
	    MODE_SELECT_SP, (caddr_t)page3, length, &header);
	if (status && (sp_flags & MODE_SELECT_SP)) {
		/* If failed, try not saving mode select params. */
		sp_flags &= ~MODE_SELECT_SP;
		status = uscsi_mode_select(cur_file, DAD_MODE_FORMAT,
		    sp_flags, (caddr_t)page3, length, &header);
		}
	if (status && option_msg) {
		err_print("Warning: Using default drive format parameters.\n");
		err_print("Warning: Drive format may not be correct.\n\n");
	}

	/*
	 * If debugging, issue mode senses on the current and
	 * saved values, so we can see the result of the mode
	 * selects.
	 */
	if (option_msg && diag_msg) {
		(void) uscsi_mode_sense(cur_file, DAD_MODE_FORMAT,
		    MODE_SENSE_PC_CURRENT, (caddr_t)page3,
		    MAX_MODE_SENSE_SIZE, &header);
		(void) uscsi_mode_sense(cur_file, DAD_MODE_FORMAT,
		    MODE_SENSE_PC_SAVED, (caddr_t)page3,
		    MAX_MODE_SENSE_SIZE, &header);
	}

	return (0);
}

/*
 * Check disk geometry parameters via mode sense.
 * Issue a mode select if we need to change something.
 */
static int
scsi_ms_page4(int scsi2_flag __unused)
{
	struct mode_geometry		*page4;
	struct mode_geometry		*fixed;
	struct scsi_ms_header		header;
	struct scsi_ms_header		fixed_hdr;
	int				status;
	int				tmp1, tmp2;
	int				flag;
	int				length;
	int				sp_flags;
	union {
		struct mode_geometry	page4;
		char			rawbuf[MAX_MODE_SENSE_SIZE];
	} u_page4, u_fixed;

	page4 = &u_page4.page4;
	fixed = &u_fixed.page4;

	/*
	 * If debugging, issue mode senses on the default and
	 * current values.
	 */
	if (option_msg && diag_msg) {
		(void) uscsi_mode_sense(cur_file, DAD_MODE_GEOMETRY,
		    MODE_SENSE_PC_DEFAULT, (caddr_t)page4,
		    MAX_MODE_SENSE_SIZE, &header);
		(void) uscsi_mode_sense(cur_file, DAD_MODE_GEOMETRY,
		    MODE_SENSE_PC_CURRENT, (caddr_t)page4,
		    MAX_MODE_SENSE_SIZE, &header);
	}

	/*
	 * Issue a mode sense to determine the saved parameters
	 * If the saved values fail, use the current instead.
	 */
	status = uscsi_mode_sense(cur_file, DAD_MODE_GEOMETRY,
	    MODE_SENSE_PC_SAVED, (caddr_t)page4,
	    MAX_MODE_SENSE_SIZE, &header);
	if (status) {
		status = uscsi_mode_sense(cur_file, DAD_MODE_GEOMETRY,
		    MODE_SENSE_PC_CURRENT, (caddr_t)page4,
		    MAX_MODE_SENSE_SIZE, &header);
		if (status) {
			return (0);
		}
	}

	/*
	 * We only need the common subset between the CCS
	 * and SCSI-2 structures, so we can treat both
	 * cases identically.  Whatever the drive gives
	 * us, we return to the drive in the mode select,
	 * delta'ed by whatever we want to change.
	 */
	length = MODESENSE_PAGE_LEN(page4);
	if (length < MIN_PAGE4_LEN) {
		return (0);
	}

	/*
	 * Ask for changeable parameters.
	 */
	status = uscsi_mode_sense(cur_file, DAD_MODE_GEOMETRY,
	    MODE_SENSE_PC_CHANGEABLE, (caddr_t)fixed,
	    MAX_MODE_SENSE_SIZE, &fixed_hdr);
	if (status || MODESENSE_PAGE_LEN(fixed) < MIN_PAGE4_LEN) {
		return (0);
	}

	/*
	 * We need to issue a mode select only if one or more
	 * parameters need to be changed, and those parameters
	 * are flagged by the drive as changeable.
	 */
	tmp1 = (page4->cyl_ub << 16) + (page4->cyl_mb << 8) + page4->cyl_lb;
	tmp2 = page4->heads;

	flag = 0;
	if ((cur_dtype->dtype_options & SUP_PHEAD) && fixed->heads != 0) {
		flag |= (page4->heads != phead);
		page4->heads = phead;
	}
	/*
	 * Notify user of changes so far
	 */
	if (flag && option_msg) {
		fmt_print("PAGE 4:   cylinders= %d    heads= %d (%d)\n",
		    tmp1, page4->heads, tmp2);
	}
	/*
	 * Apply any changes requested via the change list method
	 */
	flag |= apply_chg_list(DAD_MODE_GEOMETRY, length,
	    (uchar_t *)page4, (uchar_t *)fixed, cur_dtype->dtype_chglist);
	/*
	 * If no changes required, do not issue a mode select
	 */
	if (flag == 0) {
		return (0);
	}
	/*
	 * Issue a mode select
	 */
	/*
	 * We always want to set the Page Format bit for mode
	 * selects.  Set the Save Page bit if the drive indicates
	 * that it can save this page via the mode sense.
	 */
	sp_flags = MODE_SELECT_PF;
	if (page4->mode_page.ps) {
		sp_flags |= MODE_SELECT_SP;
	}
	page4->mode_page.ps = 0;
	header.mode_header.length = 0;
	header.mode_header.device_specific = 0;
	status = uscsi_mode_select(cur_file, DAD_MODE_GEOMETRY,
	    MODE_SELECT_SP, (caddr_t)page4, length, &header);
	if (status && (sp_flags & MODE_SELECT_SP)) {
		/* If failed, try not saving mode select params. */
		sp_flags &= ~MODE_SELECT_SP;
		status = uscsi_mode_select(cur_file, DAD_MODE_GEOMETRY,
		    sp_flags, (caddr_t)page4, length, &header);
		}
	if (status && option_msg) {
		err_print("Warning: Using default drive geometry.\n\n");
	}

	/*
	 * If debugging, issue mode senses on the current and
	 * saved values, so we can see the result of the mode
	 * selects.
	 */
	if (option_msg && diag_msg) {
		(void) uscsi_mode_sense(cur_file, DAD_MODE_GEOMETRY,
		    MODE_SENSE_PC_CURRENT, (caddr_t)page4,
		    MAX_MODE_SENSE_SIZE, &header);
		(void) uscsi_mode_sense(cur_file, DAD_MODE_GEOMETRY,
		    MODE_SENSE_PC_SAVED, (caddr_t)page4,
		    MAX_MODE_SENSE_SIZE, &header);
	}

	return (0);
}

/*
 * Check SCSI-2 disk cache parameters via mode sense.
 * Issue a mode select if we need to change something.
 */
static int
scsi_ms_page8(int scsi2_flag __unused)
{
	struct mode_cache		*page8;
	struct mode_cache		*fixed;
	struct scsi_ms_header		header;
	struct scsi_ms_header		fixed_hdr;
	int				status;
	int				flag;
	int				length;
	int				sp_flags;
	union {
		struct mode_cache	page8;
		char			rawbuf[MAX_MODE_SENSE_SIZE];
	} u_page8, u_fixed;

	page8 = &u_page8.page8;
	fixed = &u_fixed.page8;

	/*
	 * Only SCSI-2 devices support this page
	 */
	if (!scsi2_flag) {
		return (0);
	}

	/*
	 * If debugging, issue mode senses on the default and
	 * current values.
	 */
	if (option_msg && diag_msg) {
		(void) uscsi_mode_sense(cur_file, DAD_MODE_CACHE,
		    MODE_SENSE_PC_DEFAULT, (caddr_t)page8,
		    MAX_MODE_SENSE_SIZE, &header);
		(void) uscsi_mode_sense(cur_file, DAD_MODE_CACHE,
		    MODE_SENSE_PC_CURRENT, (caddr_t)page8,
		    MAX_MODE_SENSE_SIZE, &header);
	}

	/*
	 * Issue a mode sense to determine the saved parameters
	 * If the saved values fail, use the current instead.
	 */
	status = uscsi_mode_sense(cur_file, DAD_MODE_CACHE,
	    MODE_SENSE_PC_SAVED, (caddr_t)page8,
	    MAX_MODE_SENSE_SIZE, &header);
	if (status) {
		status = uscsi_mode_sense(cur_file, DAD_MODE_CACHE,
		    MODE_SENSE_PC_CURRENT, (caddr_t)page8,
		    MAX_MODE_SENSE_SIZE, &header);
		if (status) {
			return (0);
		}
	}

	/*
	 * We only need the common subset between the CCS
	 * and SCSI-2 structures, so we can treat both
	 * cases identically.  Whatever the drive gives
	 * us, we return to the drive in the mode select,
	 * delta'ed by whatever we want to change.
	 */
	length = MODESENSE_PAGE_LEN(page8);
	if (length < MIN_PAGE8_LEN) {
		return (0);
	}

	/*
	 * Ask for changeable parameters.
	 */
	status = uscsi_mode_sense(cur_file, DAD_MODE_CACHE,
	    MODE_SENSE_PC_CHANGEABLE, (caddr_t)fixed,
	    MAX_MODE_SENSE_SIZE, &fixed_hdr);
	if (status || MODESENSE_PAGE_LEN(fixed) < MIN_PAGE8_LEN) {
		return (0);
	}

	/*
	 * We need to issue a mode select only if one or more
	 * parameters need to be changed, and those parameters
	 * are flagged by the drive as changeable.
	 */
	flag = 0;
	/*
	 * Apply any changes requested via the change list method
	 */
	flag |= apply_chg_list(DAD_MODE_CACHE, length,
	    (uchar_t *)page8, (uchar_t *)fixed, cur_dtype->dtype_chglist);
	/*
	 * If no changes required, do not issue a mode select
	 */
	if (flag == 0) {
		return (0);
	}
	/*
	 * Issue a mode select
	 */
	/*
	 * We always want to set the Page Format bit for mode
	 * selects.  Set the Save Page bit if the drive indicates
	 * that it can save this page via the mode sense.
	 */
	sp_flags = MODE_SELECT_PF;
	if (page8->mode_page.ps) {
		sp_flags |= MODE_SELECT_SP;
	}
	page8->mode_page.ps = 0;
	header.mode_header.length = 0;
	header.mode_header.device_specific = 0;
	status = uscsi_mode_select(cur_file, DAD_MODE_CACHE,
	    sp_flags, (caddr_t)page8, length, &header);
	if (status && (sp_flags & MODE_SELECT_SP)) {
		/* If failed, try not saving mode select params. */
		sp_flags &= ~MODE_SELECT_SP;
		status = uscsi_mode_select(cur_file, DAD_MODE_CACHE,
		    sp_flags, (caddr_t)page8, length, &header);
	}
	if (status && option_msg) {
		err_print(
		    "Warning: Using default SCSI-2 cache parameters.\n\n");
	}

	/*
	 * If debugging, issue mode senses on the current and
	 * saved values, so we can see the result of the mode
	 * selects.
	 */
	if (option_msg && diag_msg) {
		(void) uscsi_mode_sense(cur_file, DAD_MODE_CACHE,
		    MODE_SENSE_PC_CURRENT, (caddr_t)page8,
		    MAX_MODE_SENSE_SIZE, &header);
		(void) uscsi_mode_sense(cur_file, DAD_MODE_CACHE,
		    MODE_SENSE_PC_SAVED, (caddr_t)page8,
		    MAX_MODE_SENSE_SIZE, &header);
	}

	return (0);
}

/*
 * Check CCS disk cache parameters via mode sense.
 * Issue a mode select if we need to change something.
 */
static int
scsi_ms_page38(int scsi2_flag __unused)
{
	struct mode_cache_ccs		*page38;
	struct mode_cache_ccs		*fixed;
	struct scsi_ms_header		header;
	struct scsi_ms_header		fixed_hdr;
	int				status;
	int				tmp1, tmp2, tmp3, tmp4;
	int				flag;
	int				length;
	int				sp_flags;
	union {
		struct mode_cache_ccs	page38;
		char			rawbuf[MAX_MODE_SENSE_SIZE];
	} u_page38, u_fixed;

	/*
	 * First, determine if we need to look at page 38 at all.
	 * Not all devices support it.
	 */
	if (((cur_dtype->dtype_options & (SUP_CACHE | SUP_PREFETCH |
	    SUP_CACHE_MIN | SUP_CACHE_MAX)) == 0) &&
	    (!chg_list_affects_page(cur_dtype->dtype_chglist, 0x38))) {
		return (0);
	}

	page38 = &u_page38.page38;
	fixed = &u_fixed.page38;

	/*
	 * If debugging, issue mode senses on the default and
	 * current values.
	 */
	if (option_msg && diag_msg) {
		(void) uscsi_mode_sense(cur_file, DAD_MODE_CACHE_CCS,
		    MODE_SENSE_PC_DEFAULT, (caddr_t)page38,
		    MAX_MODE_SENSE_SIZE, &header);
		(void) uscsi_mode_sense(cur_file, DAD_MODE_CACHE_CCS,
		    MODE_SENSE_PC_CURRENT, (caddr_t)page38,
		    MAX_MODE_SENSE_SIZE, &header);
	}

	/*
	 * Issue a mode sense to determine the saved parameters
	 * If the saved values fail, use the current instead.
	 */
	status = uscsi_mode_sense(cur_file, DAD_MODE_CACHE_CCS,
	    MODE_SENSE_PC_SAVED, (caddr_t)page38,
	    MAX_MODE_SENSE_SIZE, &header);
	if (status) {
		status = uscsi_mode_sense(cur_file, DAD_MODE_CACHE_CCS,
		    MODE_SENSE_PC_CURRENT, (caddr_t)page38,
		    MAX_MODE_SENSE_SIZE, &header);
		if (status) {
			return (0);
		}
	}

	/*
	 * We only need the common subset between the CCS
	 * and SCSI-2 structures, so we can treat both
	 * cases identically.  Whatever the drive gives
	 * us, we return to the drive in the mode select,
	 * delta'ed by whatever we want to change.
	 */
	length = MODESENSE_PAGE_LEN(page38);
	if (length < MIN_PAGE38_LEN) {
		return (0);
	}

	/*
	 * Ask for changeable parameters.
	 */
	status = uscsi_mode_sense(cur_file, DAD_MODE_CACHE_CCS,
	    MODE_SENSE_PC_CHANGEABLE, (caddr_t)fixed,
	    MAX_MODE_SENSE_SIZE, &fixed_hdr);
	if (status || MODESENSE_PAGE_LEN(fixed) < MIN_PAGE38_LEN) {
		return (0);
	}

	/*
	 * We need to issue a mode select only if one or more
	 * parameters need to be changed, and those parameters
	 * are flagged by the drive as changeable.
	 */
	tmp1 = page38->mode;
	tmp2 = page38->threshold;
	tmp3 = page38->min_prefetch;
	tmp4 = page38->max_prefetch;

	flag = 0;
	if ((cur_dtype->dtype_options & SUP_CACHE) &&
	    (fixed->mode & cur_dtype->dtype_cache) ==
	    cur_dtype->dtype_cache) {
		flag |= (page38->mode != cur_dtype->dtype_cache);
		page38->mode = cur_dtype->dtype_cache;
	}
	if ((cur_dtype->dtype_options & SUP_PREFETCH) &&
	    (fixed->threshold & cur_dtype->dtype_threshold) ==
	    cur_dtype->dtype_threshold) {
		flag |= (page38->threshold != cur_dtype->dtype_threshold);
		page38->threshold = cur_dtype->dtype_threshold;
	}
	if ((cur_dtype->dtype_options & SUP_CACHE_MIN) &&
	    (fixed->min_prefetch & cur_dtype->dtype_prefetch_min) ==
	    cur_dtype->dtype_prefetch_min) {
		flag |= (page38->min_prefetch != cur_dtype->dtype_prefetch_min);
		page38->min_prefetch = cur_dtype->dtype_prefetch_min;
	}
	if ((cur_dtype->dtype_options & SUP_CACHE_MAX) &&
	    (fixed->max_prefetch & cur_dtype->dtype_prefetch_max) ==
	    cur_dtype->dtype_prefetch_max) {
		flag |= (page38->max_prefetch != cur_dtype->dtype_prefetch_max);
		page38->max_prefetch = cur_dtype->dtype_prefetch_max;
	}
	/*
	 * Notify the user of changes up to this point
	 */
	if (flag && option_msg) {
		fmt_print("PAGE 38: cache mode= 0x%x (0x%x)\n",
		    page38->mode, tmp1);
		fmt_print("         min. prefetch multiplier= %d   ",
		    page38->min_multiplier);
		fmt_print("max. prefetch multiplier= %d\n",
		    page38->max_multiplier);
		fmt_print("         threshold= %d (%d)   ",
		    page38->threshold, tmp2);
		fmt_print("min. prefetch= %d (%d)   ",
		    page38->min_prefetch, tmp3);
		fmt_print("max. prefetch= %d (%d)\n",
		    page38->max_prefetch, tmp4);
	}
	/*
	 * Apply any changes requested via the change list method
	 */
	flag |= apply_chg_list(DAD_MODE_CACHE_CCS, length,
	    (uchar_t *)page38, (uchar_t *)fixed,
	    cur_dtype->dtype_chglist);
	/*
	 * If no changes required, do not issue a mode select
	 */
	if (flag == 0) {
		return (0);
	}
	/*
	 * Issue a mode select
	 *
	 * We always want to set the Page Format bit for mode
	 * selects.  Set the Save Page bit if the drive indicates
	 * that it can save this page via the mode sense.
	 */
	sp_flags = MODE_SELECT_PF;
	if (page38->mode_page.ps) {
		sp_flags |= MODE_SELECT_SP;
	}
	page38->mode_page.ps = 0;
	header.mode_header.length = 0;
	header.mode_header.device_specific = 0;
	status = uscsi_mode_select(cur_file, DAD_MODE_CACHE_CCS,
	    sp_flags, (caddr_t)page38, length, &header);
	if (status && (sp_flags & MODE_SELECT_SP)) {
		/* If failed, try not saving mode select params. */
		sp_flags &= ~MODE_SELECT_SP;
		status = uscsi_mode_select(cur_file, DAD_MODE_CACHE_CCS,
		    sp_flags, (caddr_t)page38, length, &header);
	}
	if (status && option_msg) {
		err_print("Warning: Using default CCS cache parameters.\n\n");
	}

	/*
	 * If debugging, issue mode senses on the current and
	 * saved values, so we can see the result of the mode
	 * selects.
	 */
	if (option_msg && diag_msg) {
		(void) uscsi_mode_sense(cur_file, DAD_MODE_CACHE_CCS,
		    MODE_SENSE_PC_CURRENT, (caddr_t)page38,
		    MAX_MODE_SENSE_SIZE, &header);
		(void) uscsi_mode_sense(cur_file, DAD_MODE_CACHE_CCS,
		    MODE_SENSE_PC_SAVED, (caddr_t)page38,
		    MAX_MODE_SENSE_SIZE, &header);
	}

	return (0);
}


/*
 * Extract the manufacturer's defect list.
 */
int
scsi_ex_man(struct defect_list *list)
{
	int	i;

	i = scsi_read_defect_data(list, DLD_MAN_DEF_LIST);
	if (i != 0)
		return (i);
	list->flags &= ~LIST_PGLIST;
	return (0);
}

/*
 * Extract the current defect list.
 * For embedded scsi drives, this means both the manufacturer's (P)
 * and the grown (G) lists.
 */
int
scsi_ex_cur(struct defect_list *list)
{
	int	i;

	i = scsi_read_defect_data(list, DLD_GROWN_DEF_LIST|DLD_MAN_DEF_LIST);
	if (i != 0)
		return (i);
	list->flags |= LIST_PGLIST;
	return (0);
}


/*
 * Extract the grown list only
 */
int
scsi_ex_grown(struct defect_list *list)
{
	int	i;

	i = scsi_read_defect_data(list, DLD_GROWN_DEF_LIST);
	if (i != 0)
		return (i);
	list->flags |= LIST_PGLIST;
	return (0);
}


static int
scsi_read_defect_data(struct defect_list *list, int pglist_flags)
{
	struct uscsi_cmd	ucmd;
	char			rqbuf[255];
	union scsi_cdb		cdb;
	struct scsi_defect_list	*defects;
	struct scsi_defect_list	def_list;
	struct scsi_defect_hdr	*hdr;
	int			status;
	int			nbytes;
	int			len;	/* returned defect list length */
	struct scsi_extended_sense	*rq;

	hdr = (struct scsi_defect_hdr *)&def_list;

	/*
	 * First get length of list by asking for the header only.
	 */
	(void) memset((char *)&def_list, 0, sizeof (def_list));

	/*
	 * Build and execute the uscsi ioctl
	 */
	(void) memset((char *)&ucmd, 0, sizeof (ucmd));
	(void) memset((char *)&cdb, 0, sizeof (union scsi_cdb));
	(void) memset((char *)rqbuf, 0, 255);
	cdb.scc_cmd = SCMD_READ_DEFECT_LIST;
	FORMG1COUNT(&cdb, sizeof (struct scsi_defect_hdr));
	cdb.cdb_opaque[2] = pglist_flags | DLD_BFI_FORMAT;
	ucmd.uscsi_cdb = (caddr_t)&cdb;
	ucmd.uscsi_cdblen = CDB_GROUP1;
	ucmd.uscsi_bufaddr = (caddr_t)hdr;
	ucmd.uscsi_buflen = sizeof (struct scsi_defect_hdr);
	ucmd.uscsi_rqbuf = rqbuf;
	ucmd.uscsi_rqlen = sizeof (rqbuf);
	ucmd.uscsi_rqresid = sizeof (rqbuf);
	rq = (struct scsi_extended_sense *)ucmd.uscsi_rqbuf;

	status = uscsi_cmd(cur_file, &ucmd,
	    (option_msg && diag_msg) ? F_NORMAL : F_SILENT);

	if (status != 0) {
		/*
		 * check if read_defect_list_is_supported.
		 */
		if (ucmd.uscsi_rqstatus == STATUS_GOOD &&
		    rq->es_key == KEY_ILLEGAL_REQUEST &&
		    rq->es_add_code == INVALID_OPCODE) {
			err_print("\nWARNING: Current Disk does not support"
			    " defect lists.\n");
		} else if (option_msg) {
			err_print("No %s defect list.\n",
			    pglist_flags & DLD_GROWN_DEF_LIST ?
			    "grown" : "manufacturer's");
		}
		return (-1);
	}

	/*
	 * Read the full list the second time
	 */
	hdr->length = BE_16(hdr->length);
	len = hdr->length;
	nbytes = len + sizeof (struct scsi_defect_hdr);

	defects = zalloc(nbytes);
	*(struct scsi_defect_hdr *)defects = *(struct scsi_defect_hdr *)hdr;

	(void) memset((char *)&ucmd, 0, sizeof (ucmd));
	(void) memset((char *)&cdb, 0, sizeof (union scsi_cdb));
	cdb.scc_cmd = SCMD_READ_DEFECT_LIST;
	FORMG1COUNT(&cdb, nbytes);
	cdb.cdb_opaque[2] = pglist_flags | DLD_BFI_FORMAT;
	ucmd.uscsi_cdb = (caddr_t)&cdb;
	ucmd.uscsi_cdblen = CDB_GROUP1;
	ucmd.uscsi_bufaddr = (caddr_t)defects;
	ucmd.uscsi_buflen = nbytes;
	status = uscsi_cmd(cur_file, &ucmd,
	    (option_msg && diag_msg) ? F_NORMAL : F_SILENT);

	if (status) {
		err_print("can't read defect list 2nd time");
		destroy_data((char *)defects);
		return (-1);
	}

	defects->length = BE_16(defects->length);

	if (len != hdr->length) {
		err_print("not enough defects");
		destroy_data((char *)defects);
		return (-1);
	}
	scsi_convert_list_to_new(list, (struct scsi_defect_list *)defects,
	    DLD_BFI_FORMAT);
	destroy_data((char *)defects);
	return (0);
}


/*
 * Map a block.
 */
static int
scsi_repair(uint64_t bn, int flag __unused)
{
	struct uscsi_cmd		ucmd;
	union scsi_cdb			cdb;
	struct scsi_reassign_blk	defect_list;

	/*
	 * Build and execute the uscsi ioctl
	 */
	(void) memset((char *)&ucmd, 0, sizeof (ucmd));
	(void) memset((char *)&cdb, 0, sizeof (union scsi_cdb));
	(void) memset((char *)&defect_list, 0,
	    sizeof (struct scsi_reassign_blk));
	cdb.scc_cmd = SCMD_REASSIGN_BLOCK;
	ucmd.uscsi_cdb = (caddr_t)&cdb;
	ucmd.uscsi_cdblen = CDB_GROUP0;
	ucmd.uscsi_bufaddr = (caddr_t)&defect_list;
	ucmd.uscsi_buflen = sizeof (struct scsi_reassign_blk);
	defect_list.length = sizeof (defect_list.defect);
	defect_list.length = BE_16(defect_list.length);
	defect_list.defect = bn;
	defect_list.defect = BE_32(defect_list.defect);
	return (uscsi_cmd(cur_file, &ucmd,
	    (option_msg && diag_msg) ? F_NORMAL : F_SILENT));
}

/*
 * Convert a SCSI-style defect list to our generic format.
 * We can handle different format lists.
 */
static void
scsi_convert_list_to_new(struct defect_list *list,
    struct scsi_defect_list *def_list, int list_format)
{
	struct scsi_bfi_defect	*old_defect, *old_defect1;
	struct defect_entry	*new_defect;
	int			len, new_len, obfi, nbfi;
	int			i;
	int				old_cyl, new_cyl;
	unsigned char			*cp;


	switch (list_format) {

	case DLD_BFI_FORMAT:
		/*
		 * Allocate space for the rest of the list.
		 */
		len = def_list->length / sizeof (struct scsi_bfi_defect);
		old_defect = def_list->list;
		new_defect = (struct defect_entry *)
		    zalloc(deflist_size(cur_blksz, len) *
		    cur_blksz);

		list->header.magicno = (uint_t)DEFECT_MAGIC;
		list->list = new_defect;

		for (i = 0, new_len = 0; i < len; new_defect++, new_len++) {
			cp = (unsigned char *)old_defect;
			new_defect->cyl = (cp[0] << 16 | cp[1] << 8) | cp[2];
			new_defect->head = old_defect->head;
			new_defect->bfi = (int)old_defect->bytes_from_index;
			new_defect->bfi = BE_32(new_defect->bfi);
			new_defect->nbits = 0;	/* size of defect */
			old_defect1 = old_defect++;
			i++;
			/*
			 * Since we reached the end of the list, old_defect
			 * now points to an invalid reference, since it got
			 * incremented in the above operation. So we don't
			 * need to proceed further. new_len needs to be
			 * incremented to account for the last element.
			 */
			if (i == len) {
				new_len++;
				break;
			}
			obfi = new_defect->bfi;
			nbfi = (int)old_defect->bytes_from_index;
			nbfi = BE_32(nbfi);

			old_cyl =  new_defect->cyl;
			cp = (unsigned char *)old_defect;
			new_cyl = (cp[0] << 16 | cp[1] << 8) | cp[2];


			/*
			 * Merge adjacent contiguous defect entries into one
			 * and update the length of the defect
			 */
			while ((i < len) &&
			    (old_cyl  == new_cyl) &&
			    (old_defect->head == old_defect1->head) &&
			    (nbfi == (obfi + BITSPERBYTE))) {
				old_defect1 = old_defect++;
				cp = (unsigned char *)old_defect;
				new_cyl = (cp[0] << 16 | cp[1] << 8) | cp[2];
				obfi = (int)old_defect1->bytes_from_index;
				obfi = BE_32(obfi);
				nbfi = (int)old_defect->bytes_from_index;
				nbfi = BE_32(nbfi);
				new_defect->nbits += (8*BITSPERBYTE);
				i++;
			}
		}

		list->header.count = new_len;
		break;

	default:
		err_print("scsi_convert_list_to_new: can't deal with it\n");
		exit(0);
		/*NOTREACHED*/
	}

	(void) checkdefsum(list, CK_MAKESUM);
}



/*
 * Execute a command and determine the result.
 * Uses the "uscsi" ioctl interface, which is
 * fully supported.
 *
 * If the user wants request sense data to be returned
 * in case of error then , the "uscsi_cmd" structure
 * should have the request sense buffer allocated in
 * uscsi_rqbuf.
 *
 */
int
uscsi_cmd(int fd, struct uscsi_cmd *ucmd, int flags)
{
	struct scsi_extended_sense	*rq;
	char				rqbuf[255];
	int				status;
	int				rqlen;
	int				timeout = 0;

	/*
	 * Set function flags for driver.
	 */
	ucmd->uscsi_flags = USCSI_ISOLATE;
	if (flags & F_SILENT) {
		ucmd->uscsi_flags |= USCSI_SILENT;
	}
	if (flags & F_RQENABLE) {
		ucmd->uscsi_flags |= USCSI_RQENABLE;
	}

	/*
	 * If this command will perform a read, set the USCSI_READ flag
	 */
	if (ucmd->uscsi_buflen > 0) {
		/*
		 * uscsi_cdb is declared as a caddr_t, so any CDB
		 * command byte with the MSB set will result in a
		 * compiler error unless we cast to an unsigned value.
		 */
		switch ((uint8_t)ucmd->uscsi_cdb[0]) {
		case SCMD_READ:
		case SCMD_READ|SCMD_GROUP1:
		case SCMD_READ|SCMD_GROUP4:
		case SCMD_MODE_SENSE:
		case SCMD_INQUIRY:
		case SCMD_READ_DEFECT_LIST:
		case SCMD_READ_CAPACITY:
		case SCMD_SVC_ACTION_IN_G4:
			ucmd->uscsi_flags |= USCSI_READ;
			break;
		}
	}

	/*
	 * Set timeout: 30 seconds for all commands except format
	 */
	switch (ucmd->uscsi_cdb[0]) {
	case SCMD_FORMAT:
		if (ucmd->uscsi_timeout == 0) {
			ucmd->uscsi_timeout = scsi_format_timeout;
			/*
			 * Get the timeout value computed using page4 geometry.
			 * add 50% margin to cover defect management overhead.
			 * add another 50% margin to have a safe timeout.
			 * If it exceeds 2 hours then use this value.
			 */
			if ((timeout = scsi_format_time()) > 0) {
				timeout *= 60;	/* convert to seconds */
				timeout += timeout;
				/*
				 * formatting drives with huge capacity
				 * will cause these heuristics to come
				 * up with times that overflow ~9 hours
				 */
				if (timeout > SHRT_MAX)
					timeout = SHRT_MAX;
				if (timeout > scsi_format_timeout)
					ucmd->uscsi_timeout = timeout;
			}
		}
		if (option_msg && diag_msg) {
			err_print("format_timeout set to %d seconds, %d"
			    " required\n", ucmd->uscsi_timeout, timeout);
		}
		break;

	default:
		ucmd->uscsi_timeout = 30;		/* 30 seconds */
		break;
	}

	/*
	 * Set up Request Sense buffer
	 */
	ucmd->uscsi_flags |= USCSI_RQENABLE;

	if (ucmd->uscsi_rqbuf == NULL)  {
		ucmd->uscsi_rqbuf = rqbuf;
		ucmd->uscsi_rqlen = sizeof (rqbuf);
		ucmd->uscsi_rqresid = sizeof (rqbuf);
	}
	ucmd->uscsi_rqstatus = IMPOSSIBLE_SCSI_STATUS;

	/*
	 * Clear global error state
	 */
	media_error = 0;

	/*
	 * Execute the ioctl
	 */
	status = ioctl(fd, USCSICMD, ucmd);
	if (status == 0 && ucmd->uscsi_status == 0) {
		return (status);
	}

	/*
	 * Check the status and return appropriate errors if the disk is
	 * unavailable (could be formatting) or reserved (by other host).
	 * In either case we can not talk to the disk now.
	 */
	if (status == -1 && errno == EAGAIN) {
		disk_error = DISK_STAT_UNAVAILABLE;
		return (DSK_UNAVAILABLE);
	}
	if ((ucmd->uscsi_status & STATUS_MASK) == STATUS_RESERVATION_CONFLICT) {
		disk_error = DISK_STAT_RESERVED;
		return (DSK_RESERVED);
	}
	/*
	 * Check for physically removed or completely unresponsive drive
	 */
	if (status == -1 && !ucmd->uscsi_status && errno == EIO) {
		disk_error = DISK_STAT_UNAVAILABLE;
		return (DSK_UNAVAILABLE);
	}

	/*
	 * If an automatic Request Sense gave us valid
	 * info about the error, we may be able to use
	 * that to print a reasonable error msg.
	 */
	if (ucmd->uscsi_rqstatus == IMPOSSIBLE_SCSI_STATUS) {
		if (option_msg && diag_msg) {
			err_print("No request sense for command %s\n",
			    scsi_find_command_name(ucmd->uscsi_cdb[0]));
		}
		return (-1);
	}
	if (ucmd->uscsi_rqstatus != STATUS_GOOD) {
		if (option_msg && diag_msg) {
			err_print("Request sense status for command %s: 0x%x\n",
			    scsi_find_command_name(ucmd->uscsi_cdb[0]),
			    ucmd->uscsi_rqstatus);
		}
		return (-1);
	}
	rq = (struct scsi_extended_sense *)ucmd->uscsi_rqbuf;
	rqlen = ucmd->uscsi_rqlen - ucmd->uscsi_rqresid;
	if ((((int)rq->es_add_len) + 8) < MIN_REQUEST_SENSE_LEN ||
	    rq->es_class != CLASS_EXTENDED_SENSE ||
	    rqlen < MIN_REQUEST_SENSE_LEN) {
		if (option_msg) {
			err_print("Request sense for command %s failed\n",
			    scsi_find_command_name(ucmd->uscsi_cdb[0]));
		}
		if (option_msg && diag_msg) {
			err_print("Sense data:\n");
			dump("", (caddr_t)rqbuf, rqlen, HEX_ONLY);
		}
		if (errno == EIO) {
			disk_error = DISK_STAT_UNAVAILABLE;
			return (DSK_UNAVAILABLE);
		} else {
			return (-1);
		}
	}

	/*
	 * If the failed command is a Mode Select, and the
	 * target is indicating that it has rounded one of
	 * the mode select parameters, as defined in the SCSI-2
	 * specification, then we should accept the command
	 * as successful.
	 */
	if (ucmd->uscsi_cdb[0] == SCMD_MODE_SELECT) {
		if (rq->es_key == KEY_RECOVERABLE_ERROR &&
		    rq->es_add_code == ROUNDED_PARAMETER &&
		    rq->es_qual_code == 0) {
			return (0);
		}
	}

	switch (rq->es_key) {
	case KEY_NOT_READY:
		disk_error = DISK_STAT_NOTREADY;
		break;
	case KEY_DATA_PROTECT:
		disk_error = DISK_STAT_DATA_PROTECT;
		break;
	}

	if (flags & F_ALLERRS) {
		media_error = (rq->es_key == KEY_MEDIUM_ERROR);
	}
	if (!(flags & F_SILENT) || option_msg) {
		scsi_printerr(ucmd, rq, rqlen);
	}
	if ((rq->es_key != KEY_RECOVERABLE_ERROR) || (flags & F_ALLERRS)) {
		return (-1);
	}

	if (status == -1 && errno == EIO) {
		disk_error = DISK_STAT_UNAVAILABLE;
		return (DSK_UNAVAILABLE);
	}

	return (0);
}


/*
 * Execute a uscsi mode sense command.
 * This can only be used to return one page at a time.
 * Return the mode header/block descriptor and the actual
 * page data separately - this allows us to support
 * devices which return either 0 or 1 block descriptors.
 * Whatever a device gives us in the mode header/block descriptor
 * will be returned to it upon subsequent mode selects.
 */
int
uscsi_mode_sense(int fd, int page_code, int page_control, caddr_t page_data,
    int page_size, struct scsi_ms_header *header)
{
	caddr_t			mode_sense_buf;
	struct mode_header	*hdr;
	struct mode_page	*pg;
	int			nbytes;
	struct uscsi_cmd	ucmd;
	union scsi_cdb		cdb;
	int			status;
	int			maximum;

	assert(page_size >= 0 && page_size < 256);
	assert(page_control == MODE_SENSE_PC_CURRENT ||
	    page_control == MODE_SENSE_PC_CHANGEABLE ||
	    page_control == MODE_SENSE_PC_DEFAULT ||
	    page_control == MODE_SENSE_PC_SAVED);
	/*
	 * Allocate a buffer for the mode sense headers
	 * and mode sense data itself.
	 */
	nbytes = sizeof (struct block_descriptor) +
	    sizeof (struct mode_header) + page_size;
	nbytes = page_size;
	if ((mode_sense_buf = malloc((uint_t)nbytes)) == NULL) {
		err_print("cannot malloc %d bytes\n", nbytes);
		return (-1);
	}

	/*
	 * Build and execute the uscsi ioctl
	 */
	(void) memset(mode_sense_buf, 0, nbytes);
	(void) memset((char *)&ucmd, 0, sizeof (ucmd));
	(void) memset((char *)&cdb, 0, sizeof (union scsi_cdb));
	cdb.scc_cmd = SCMD_MODE_SENSE;
	FORMG0COUNT(&cdb, (uchar_t)nbytes);
	cdb.cdb_opaque[2] = page_control | page_code;
	ucmd.uscsi_cdb = (caddr_t)&cdb;
	ucmd.uscsi_cdblen = CDB_GROUP0;
	ucmd.uscsi_bufaddr = mode_sense_buf;
	ucmd.uscsi_buflen = nbytes;
	status = uscsi_cmd(fd, &ucmd,
	    (option_msg && diag_msg) ? F_NORMAL : F_SILENT);
	if (status) {
		if (option_msg) {
			err_print("Mode sense page 0x%x failed\n",
			    page_code);
		}
		free(mode_sense_buf);
		return (-1);
	}

	/*
	 * Verify that the returned data looks reasonabled,
	 * find the actual page data, and copy it into the
	 * user's buffer.  Copy the mode_header and block_descriptor
	 * into the header structure, which can then be used to
	 * return the same data to the drive when issuing a mode select.
	 */
	hdr = (struct mode_header *)mode_sense_buf;
	(void) memset((caddr_t)header, 0, sizeof (struct scsi_ms_header));
	if (hdr->bdesc_length != sizeof (struct block_descriptor) &&
	    hdr->bdesc_length != 0) {
		if (option_msg) {
			err_print("\nMode sense page 0x%x: block "
			    "descriptor length %d incorrect\n",
			    page_code, hdr->bdesc_length);
			if (diag_msg)
				dump("Mode sense: ", mode_sense_buf,
				    nbytes, HEX_ONLY);
		}
		free(mode_sense_buf);
		return (-1);
	}
	(void) memcpy((caddr_t)header, mode_sense_buf,
	    sizeof (struct mode_header) + hdr->bdesc_length);
	pg = (struct mode_page *)((ulong_t)mode_sense_buf +
	    sizeof (struct mode_header) + hdr->bdesc_length);
	if (pg->code != page_code) {
		if (option_msg) {
			err_print("\nMode sense page 0x%x: incorrect page "
			    "code 0x%x\n", page_code, pg->code);
			if (diag_msg)
				dump("Mode sense: ", mode_sense_buf,
				    nbytes, HEX_ONLY);
		}
		free(mode_sense_buf);
		return (-1);
	}
	/*
	 * Accept up to "page_size" bytes of mode sense data.
	 * This allows us to accept both CCS and SCSI-2
	 * structures, as long as we request the greater
	 * of the two.
	 */
	maximum = page_size - sizeof (struct mode_page) - hdr->bdesc_length;
	if (((int)pg->length) > maximum) {
		if (option_msg) {
			err_print("Mode sense page 0x%x: incorrect page "
			    "length %d - expected max %d\n",
			    page_code, pg->length, maximum);
			if (diag_msg)
				dump("Mode sense: ", mode_sense_buf,
				    nbytes, HEX_ONLY);
		}
		free(mode_sense_buf);
		return (-1);
	}

	(void) memcpy(page_data, (caddr_t)pg, MODESENSE_PAGE_LEN(pg));

	if (option_msg && diag_msg) {
		char *pc = find_string(page_control_strings, page_control);

		err_print("\nMode sense page 0x%x (%s):\n", page_code,
		    pc != NULL ? pc : "");
		dump("header: ", (caddr_t)header,
		    sizeof (struct scsi_ms_header), HEX_ONLY);
		dump("data:   ", page_data,
		    MODESENSE_PAGE_LEN(pg), HEX_ONLY);
	}

	free(mode_sense_buf);
	return (0);
}


/*
 * Execute a uscsi mode select command.
 */
int
uscsi_mode_select(int fd, int page_code, int options, caddr_t page_data,
    int page_size, struct scsi_ms_header *header)
{
	caddr_t				mode_select_buf;
	int				nbytes;
	struct uscsi_cmd		ucmd;
	union scsi_cdb			cdb;
	int				status;

	assert(((struct mode_page *)page_data)->ps == 0);
	assert(header->mode_header.length == 0);
	assert(header->mode_header.device_specific == 0);
	assert((options & ~(MODE_SELECT_SP|MODE_SELECT_PF)) == 0);

	/*
	 * Allocate a buffer for the mode select header and data
	 */
	nbytes = sizeof (struct block_descriptor) +
	    sizeof (struct mode_header) + page_size;
	if ((mode_select_buf = malloc((uint_t)nbytes)) == NULL) {
		err_print("cannot malloc %d bytes\n", nbytes);
		return (-1);
	}

	/*
	 * Build the mode select data out of the header and page data
	 * This allows us to support devices which return either
	 * 0 or 1 block descriptors.
	 */
	(void) memset(mode_select_buf, 0, nbytes);
	nbytes = sizeof (struct mode_header);
	if (header->mode_header.bdesc_length ==
	    sizeof (struct block_descriptor)) {
		nbytes += sizeof (struct block_descriptor);
	}

	/*
	 * Dump the structures if anyone's interested
	 */
	if (option_msg && diag_msg) {
		char *s;

		s = find_string(mode_select_strings,
		    options & (MODE_SELECT_SP|MODE_SELECT_PF));
		err_print("\nMode select page 0x%x%s:\n", page_code,
		    s != NULL ? s : "");
		dump("header: ", (caddr_t)header,
		    nbytes, HEX_ONLY);
		dump("data:   ", (caddr_t)page_data,
		    page_size, HEX_ONLY);
	}

	/*
	 * Fix the code for byte ordering
	 */

	switch (page_code) {
	case  DAD_MODE_ERR_RECOV:
		{
		struct mode_err_recov *pd;
		pd = (struct mode_err_recov *)(void *)page_data;
		pd->recovery_time_limit = BE_16(pd->recovery_time_limit);
		break;
		}
	case MODEPAGE_DISCO_RECO:
		{
		struct mode_disco_reco *pd;
		pd = (struct mode_disco_reco *)(void *)page_data;
		pd->bus_inactivity_limit = BE_16(pd->bus_inactivity_limit);
		pd->disconect_time_limit = BE_16(pd->disconect_time_limit);
		pd->connect_time_limit = BE_16(pd->connect_time_limit);
		pd->max_burst_size = BE_16(pd->max_burst_size);
		break;
		}
	case DAD_MODE_FORMAT:
		{
		struct mode_format *pd;
		pd = (struct mode_format *)(void *)page_data;
		pd->tracks_per_zone = BE_16(pd->tracks_per_zone);
		pd->alt_sect_zone = BE_16(pd->alt_sect_zone);
		pd->alt_tracks_zone = BE_16(pd->alt_tracks_zone);
		pd->alt_tracks_vol = BE_16(pd->alt_tracks_vol);
		pd->sect_track = BE_16(pd->sect_track);
		pd->data_bytes_sect = BE_16(pd->data_bytes_sect);
		pd->interleave = BE_16(pd->interleave);
		pd->track_skew = BE_16(pd->track_skew);
		pd->cylinder_skew = BE_16(pd->cylinder_skew);
		break;
		}
	case DAD_MODE_GEOMETRY:
		{
		struct mode_geometry *pd;
		pd = (struct mode_geometry *)(void *)page_data;
		pd->step_rate = BE_16(pd->step_rate);
		pd->rpm = BE_16(pd->rpm);
		break;
		}
	case DAD_MODE_CACHE:
		{
		struct mode_cache *pd;
		pd = (struct mode_cache *)(void *)page_data;
		pd->dis_prefetch_len = BE_16(pd->dis_prefetch_len);
		pd->min_prefetch = BE_16(pd->min_prefetch);
		pd->max_prefetch = BE_16(pd->max_prefetch);
		pd->prefetch_ceiling = BE_16(pd->prefetch_ceiling);
		break;
		}
	case MODEPAGE_PDEVICE:
		{
		struct mode_pdevice *pd;
		pd = (struct mode_pdevice *)(void *)page_data;
		pd->if_ident = BE_16(pd->if_ident);
		break;
		}
	case MODEPAGE_CTRL_MODE:
		{
		struct mode_control *pd;
		pd = (struct mode_control *)(void *)page_data;
		pd->ready_aen_holdoff = BE_16(pd->ready_aen_holdoff);
		break;
		}
	}

	/*
	 * Put the header and data together
	 */
	(void) memcpy(mode_select_buf, (caddr_t)header, nbytes);
	(void) memcpy(mode_select_buf + nbytes, page_data, page_size);
	nbytes += page_size;

	/*
	 * Build and execute the uscsi ioctl
	 */
	(void) memset((char *)&ucmd, 0, sizeof (ucmd));
	(void) memset((char *)&cdb, 0, sizeof (union scsi_cdb));
	cdb.scc_cmd = SCMD_MODE_SELECT;
	FORMG0COUNT(&cdb, (uchar_t)nbytes);
	cdb.cdb_opaque[1] = (uchar_t)options;
	ucmd.uscsi_cdb = (caddr_t)&cdb;
	ucmd.uscsi_cdblen = CDB_GROUP0;
	ucmd.uscsi_bufaddr = mode_select_buf;
	ucmd.uscsi_buflen = nbytes;
	status = uscsi_cmd(fd, &ucmd,
	    (option_msg && diag_msg) ? F_NORMAL : F_SILENT);

	if (status && option_msg) {
		err_print("Mode select page 0x%x failed\n", page_code);
	}

	free(mode_select_buf);
	return (status);
}


/*
 * Execute a uscsi inquiry command and return the
 * resulting data.
 */
int
uscsi_inquiry(int fd, caddr_t inqbuf, int inqbufsiz)
{
	struct uscsi_cmd	ucmd;
	union scsi_cdb		cdb;
	struct scsi_inquiry	*inq;
	int			n;
	int			status;

	assert(inqbufsiz >= sizeof (struct scsi_inquiry) && inqbufsiz < 256);

	/*
	 * Build and execute the uscsi ioctl
	 */
	(void) memset((char *)inqbuf, 0, inqbufsiz);
	(void) memset((char *)&ucmd, 0, sizeof (ucmd));
	(void) memset((char *)&cdb, 0, sizeof (union scsi_cdb));
	cdb.scc_cmd = SCMD_INQUIRY;
	FORMG0COUNT(&cdb, (uchar_t)inqbufsiz);
	ucmd.uscsi_cdb = (caddr_t)&cdb;
	ucmd.uscsi_cdblen = CDB_GROUP0;
	ucmd.uscsi_bufaddr = (caddr_t)inqbuf;
	ucmd.uscsi_buflen = inqbufsiz;
	status = uscsi_cmd(fd, &ucmd,
	    (option_msg && diag_msg) ? F_NORMAL : F_SILENT);
	if (status) {
		if (option_msg) {
			err_print("Inquiry failed\n");
		}
	} else if (option_msg && diag_msg) {
		/*
		 * Dump the inquiry data if anyone's interested
		 */
		inq = (struct scsi_inquiry *)inqbuf;
		n = (int)inq->inq_len + 4;
		n = min(n, inqbufsiz);
		err_print("Inquiry:\n");
		dump("", (caddr_t)inqbuf, n, HEX_ASCII);
	}
	return (status);
}

/*
 * Execute a uscsi inquiry command with page code 86h
 */
int
uscsi_inquiry_page_86h(int fd, caddr_t inqbuf, int inqbufsiz)
{
	struct uscsi_cmd	ucmd;
	union scsi_cdb	cdb;
	int	status;

	assert(inqbuf);
	assert(inqbufsiz >= sizeof (struct scsi_inquiry) &&
	    inqbufsiz < 256);
	/*
	 * Build and execute uscsi ioctl
	 */
	(void) memset((char *)inqbuf, 0, inqbufsiz);
	(void) memset((char *)&ucmd, 0, sizeof (ucmd));
	(void) memset((char *)&cdb, 0, sizeof (cdb));
	cdb.scc_cmd = SCMD_INQUIRY;
	FORMG0COUNT(&cdb, (uchar_t)inqbufsiz);
	cdb.cdb_opaque[1] |= 0x01;
	cdb.cdb_opaque[2] = 0x86;
	ucmd.uscsi_cdb = (caddr_t)&cdb;
	ucmd.uscsi_cdblen = CDB_GROUP0;
	ucmd.uscsi_bufaddr = (caddr_t)inqbuf;
	ucmd.uscsi_buflen = inqbufsiz;

	status = uscsi_cmd(fd, &ucmd,
	    (option_msg && diag_msg) ? F_NORMAL : F_SILENT);

	if (status) {
		if (option_msg) {
			err_print("Inquriy with page_86h failed\n");
		}
	}
	return (status);
}

/*
 * Return the Read Capacity information
 */
int
uscsi_read_capacity_16(int fd, struct scsi_capacity_16 *capacity)
{
	struct uscsi_cmd	ucmd;
	union scsi_cdb	cdb;
	int	status;

	(void) memset((char *)capacity, 0, sizeof (struct scsi_capacity_16));
	(void) memset((char *)&ucmd, 0, sizeof (ucmd));
	(void) memset((char *)&cdb, 0, sizeof (union scsi_cdb));

	ucmd.uscsi_cdb = (caddr_t)&cdb;
	ucmd.uscsi_cdblen = CDB_GROUP4;
	ucmd.uscsi_bufaddr = (caddr_t)capacity;
	ucmd.uscsi_buflen = sizeof (struct scsi_capacity_16);

	/*
	 * Read Capacity (16) is a Service Action In command.  One
	 * command byte (0x9E) is overloaded for multiple operations,
	 * with the second CDB byte specifying the desired operation
	 */
	cdb.scc_cmd = SCMD_SVC_ACTION_IN_G4;
	cdb.cdb_opaque[1] = SSVC_ACTION_READ_CAPACITY_G4;

	/*
	 * Fill in allocation length field
	 */
	cdb.cdb_opaque[10] =
	    (uchar_t)((ucmd.uscsi_buflen & 0xff000000) >> 24);
	cdb.cdb_opaque[11] =
	    (uchar_t)((ucmd.uscsi_buflen & 0x00ff0000) >> 16);
	cdb.cdb_opaque[12] =
	    (uchar_t)((ucmd.uscsi_buflen & 0x0000ff00) >> 8);
	cdb.cdb_opaque[13] =
	    (uchar_t)(ucmd.uscsi_buflen & 0x000000ff);

	status = uscsi_cmd(fd, &ucmd,
	    (option_msg && diag_msg) ? F_NORMAL : F_SILENT);

	if (status) {
		if (option_msg) {
			err_print("Read capacity 16 failed\n");
		}
	} else if (option_msg && diag_msg) {
		/*
		 * Dump the capacity data if anyone's interested
		 */
		dump("Capacity: ", (caddr_t)capacity,
		    sizeof (struct scsi_capacity_16), HEX_ONLY);
	}

	capacity->sc_capacity = BE_64(capacity->sc_capacity);
	capacity->sc_lbasize = BE_32(capacity->sc_lbasize);

	return (status);
}

int
uscsi_read_capacity(int fd, struct scsi_capacity_16 *capacity)
{
	struct uscsi_cmd	ucmd;
	union scsi_cdb		cdb;
	int			status;
	struct scsi_capacity	cap_old;

	/*
	 * Build and execute the uscsi ioctl
	 */
	(void) memset((char *)capacity, 0, sizeof (struct scsi_capacity_16));
	(void) memset((char *)&cap_old, 0, sizeof (struct scsi_capacity));
	(void) memset((char *)&ucmd, 0, sizeof (ucmd));
	(void) memset((char *)&cdb, 0, sizeof (union scsi_cdb));
	cdb.scc_cmd = SCMD_READ_CAPACITY;
	ucmd.uscsi_cdb = (caddr_t)&cdb;
	ucmd.uscsi_cdblen = CDB_GROUP1;
	ucmd.uscsi_bufaddr = (caddr_t)&cap_old;
	ucmd.uscsi_buflen = sizeof (struct scsi_capacity);
	status = uscsi_cmd(fd, &ucmd,
	    (option_msg && diag_msg) ? F_NORMAL : F_SILENT);

	if (cap_old.capacity == UINT_MAX32) {
		/*
		 * A capacity of 0xffffffff in response to a
		 * READ CAPACITY 10 indicates that the lun
		 * is too large to report the size in a 32 bit
		 * value, and a READ CAPACITY 16 is required
		 * to get the correct size.
		 */
		(void) memset((char *)&ucmd, 0, sizeof (ucmd));
		(void) memset((char *)&cdb, 0, sizeof (union scsi_cdb));

		ucmd.uscsi_cdb = (caddr_t)&cdb;
		ucmd.uscsi_cdblen = CDB_GROUP4;
		ucmd.uscsi_bufaddr = (caddr_t)capacity;
		ucmd.uscsi_buflen = sizeof (struct scsi_capacity_16);

		/*
		 * Read Capacity (16) is a Service Action In command.  One
		 * command byte (0x9E) is overloaded for multiple operations,
		 * with the second CDB byte specifying the desired operation
		 */
		cdb.scc_cmd = SCMD_SVC_ACTION_IN_G4;
		cdb.cdb_opaque[1] = SSVC_ACTION_READ_CAPACITY_G4;

		/*
		 * Fill in allocation length field
		 */
		cdb.cdb_opaque[10] =
		    (uchar_t)((ucmd.uscsi_buflen & 0xff000000) >> 24);
		cdb.cdb_opaque[11] =
		    (uchar_t)((ucmd.uscsi_buflen & 0x00ff0000) >> 16);
		cdb.cdb_opaque[12] =
		    (uchar_t)((ucmd.uscsi_buflen & 0x0000ff00) >> 8);
		cdb.cdb_opaque[13] =
		    (uchar_t)(ucmd.uscsi_buflen & 0x000000ff);

		status = uscsi_cmd(fd, &ucmd,
		    (option_msg && diag_msg) ? F_NORMAL : F_SILENT);
	}

	if (status) {
		if (option_msg) {
			/*
			 * Indicate which of the commands failed
			 */
			if (cdb.scc_cmd == SCMD_READ_CAPACITY) {
				err_print("Read capacity failed\n");
			} else {
				err_print("Read capacity 16 failed\n");
			}
		}
	} else if (option_msg && diag_msg) {
		/*
		 * Dump the capacity data if anyone's interested
		 */
		if (cap_old.capacity == UINT_MAX32) {
			dump("Capacity: ", (caddr_t)capacity,
			    sizeof (struct scsi_capacity_16), HEX_ONLY);
		} else {
			dump("Capacity: ", (caddr_t)&cap_old,
			    sizeof (struct scsi_capacity), HEX_ONLY);
		}
	}

	if (cap_old.capacity == UINT_MAX32) {
		capacity->sc_capacity = BE_64(capacity->sc_capacity);
		capacity->sc_lbasize = BE_32(capacity->sc_lbasize);
	} else {
		capacity->sc_capacity = (uint64_t)BE_32(cap_old.capacity);
		capacity->sc_lbasize = BE_32(cap_old.lbasize);
	}

	return (status);
}


/*
 * Reserve the current disk
 */
static int
uscsi_reserve_release(int fd __maybe_unused, int cmd __maybe_unused)
{
	int			status = 0;
#ifdef sparc
	struct uscsi_cmd	ucmd;
	union scsi_cdb		cdb;

	/*
	 * Build and execute the uscsi ioctl
	 */
	(void) memset((char *)&ucmd, 0, sizeof (ucmd));
	(void) memset((char *)&cdb, 0, sizeof (union scsi_cdb));
	cdb.scc_cmd = (cmd == SCMD_RESERVE) ? SCMD_RESERVE : SCMD_RELEASE;
	ucmd.uscsi_cdb = (caddr_t)&cdb;
	ucmd.uscsi_cdblen = CDB_GROUP0;
	status = uscsi_cmd(fd, &ucmd,
	    (option_msg && diag_msg) ? F_NORMAL : F_SILENT);

	if (status) {
		/*
		 * Reserve/Release(6) failed.
		 * Try Reserve/Release(10) , if it succeeds then
		 * return success.
		 */
		(void) memset((char *)&ucmd, 0, sizeof (ucmd));
		(void) memset((char *)&cdb, 0, sizeof (union scsi_cdb));
		ucmd.uscsi_cdb = (caddr_t)&cdb;
		cdb.scc_cmd = (cmd == SCMD_RESERVE) ?
		    SCMD_RESERVE_G1 : SCMD_RELEASE_G1;
		ucmd.uscsi_cdblen = CDB_GROUP1;
		status = uscsi_cmd(fd, &ucmd,
		    (option_msg && diag_msg) ? F_NORMAL : F_SILENT);
		if (status) {
			if (option_msg) {
				err_print("%s failed\n", (cmd == SCMD_RESERVE) ?
				    "Reserve" : "Release");
			}
		}
	}
#endif /* sparc */

	return (status);
}

int
scsi_dump_mode_sense_pages(int page_control)
{
	struct uscsi_cmd	ucmd;
	union scsi_cdb		cdb;
	char			*msbuf;
	int			nbytes;
	char			*pc_str;
	int			status;
	struct mode_header	*mh;
	char			*p;
	struct mode_page	*mp;
	int			n;
	char			s[16];
	int			result = 0;

	pc_str = find_string(page_control_strings, page_control);

	/*
	 * Allocate memory for the mode sense buffer.
	 */
	nbytes = 255;
	msbuf = (char *)zalloc(nbytes);

	/*
	 * Build and execute the uscsi ioctl
	 */
	(void) memset(msbuf, 0, nbytes);
	(void) memset((char *)&ucmd, 0, sizeof (ucmd));
	(void) memset((char *)&cdb, 0, sizeof (union scsi_cdb));
	cdb.scc_cmd = SCMD_MODE_SENSE;
	FORMG0COUNT(&cdb, (uchar_t)nbytes);
	cdb.cdb_opaque[2] = page_control | 0x3f;
	ucmd.uscsi_cdb = (caddr_t)&cdb;
	ucmd.uscsi_cdblen = CDB_GROUP0;
	ucmd.uscsi_bufaddr = msbuf;
	ucmd.uscsi_buflen = nbytes;
	status = uscsi_cmd(cur_file, &ucmd,
	    (option_msg && diag_msg) ? F_NORMAL : F_SILENT);
	if (status) {
		err_print("\nMode sense page 0x3f (%s) failed\n",
		    pc_str);
		result = 1;
	} else {
		err_print("\nMode sense pages (%s):\n", pc_str);
		mh = (struct mode_header *)msbuf;
		nbytes = mh->length - sizeof (struct mode_header) -
		    mh->bdesc_length + 1;
		p = msbuf + sizeof (struct mode_header) +
		    mh->bdesc_length;
		dump("         ", msbuf, sizeof (struct mode_header) +
		    (int)mh->bdesc_length, HEX_ONLY);
		while (nbytes > 0) {
			mp = (struct mode_page *)p;
			n = mp->length + sizeof (struct mode_page);
			nbytes -= n;
			if (nbytes < 0)
				break;
			(void) sprintf(s, "   %3x:  ", mp->code);
			dump(s, p, n, HEX_ONLY);
			p += n;
		}
		if (nbytes < 0) {
			err_print("  Sense data formatted incorrectly:\n");
			dump("    ", msbuf, (int)mh->length + 1, HEX_ONLY);
			result = 1;
		}
		err_print("\n");
	}

	free(msbuf);
	return (result);
}


static void
scsi_printerr(struct uscsi_cmd *ucmd, struct scsi_extended_sense *rq, int rqlen)
{
	diskaddr_t	blkno;
	struct scsi_descr_sense_hdr *sdsp =
	    (struct scsi_descr_sense_hdr *)rq;

	switch (rq->es_key) {
	case KEY_NO_SENSE:
		err_print("No sense error");
		break;
	case KEY_RECOVERABLE_ERROR:
		err_print("Recoverable error");
		break;
	case KEY_NOT_READY:
		err_print("Not ready error");
		break;
	case KEY_MEDIUM_ERROR:
		err_print("Medium error");
		break;
	case KEY_HARDWARE_ERROR:
		err_print("Hardware error");
		break;
	case KEY_ILLEGAL_REQUEST:
		err_print("Illegal request");
		break;
	case KEY_UNIT_ATTENTION:
		err_print("Unit attention error");
		break;
	case KEY_WRITE_PROTECT:
		err_print("Write protect error");
		break;
	case KEY_BLANK_CHECK:
		err_print("Blank check error");
		break;
	case KEY_VENDOR_UNIQUE:
		err_print("Vendor unique error");
		break;
	case KEY_COPY_ABORTED:
		err_print("Copy aborted error");
		break;
	case KEY_ABORTED_COMMAND:
		err_print("Aborted command");
		break;
	case KEY_EQUAL:
		err_print("Equal error");
		break;
	case KEY_VOLUME_OVERFLOW:
		err_print("Volume overflow");
		break;
	case KEY_MISCOMPARE:
		err_print("Miscompare error");
		break;
	case KEY_RESERVED:
		err_print("Reserved error");
		break;
	default:
		err_print("Unknown error");
		break;
	}

	err_print(" during %s", scsi_find_command_name(ucmd->uscsi_cdb[0]));

	/*
	 * Get asc, ascq and info field from sense data.  There are two
	 * possible formats (fixed sense data and descriptor sense data)
	 * depending on the value of es_code.
	 */
	switch (rq->es_code) {
	case CODE_FMT_DESCR_CURRENT:
	case CODE_FMT_DESCR_DEFERRED:
		blkno =
		    (diskaddr_t)scsi_extract_sense_info_descr(sdsp, rqlen);
		if (blkno != (diskaddr_t)-1) {
			err_print(": block %lld (0x%llx) (", blkno, blkno);
			pr_dblock(err_print, blkno);
			err_print(")");
		}

		err_print("\n");

		err_print("ASC: 0x%x   ASCQ: 0x%x\n",
		    sdsp->ds_add_code, sdsp->ds_qual_code);
		break;
	case CODE_FMT_FIXED_CURRENT:
	case CODE_FMT_FIXED_DEFERRED:
	default:
		if (rq->es_valid) {
			blkno = (rq->es_info_1 << 24) |
			    (rq->es_info_2 << 16) |
			    (rq->es_info_3 << 8) | rq->es_info_4;
			err_print(": block %lld (0x%llx) (", blkno, blkno);
			pr_dblock(err_print, blkno);
			err_print(")");
		}

		err_print("\n");

		if (rq->es_add_len >= 6) {
			err_print("ASC: 0x%x   ASCQ: 0x%x\n",
			    rq->es_add_code, rq->es_qual_code);
		}
		break;
	}

	if (option_msg && diag_msg) {
		if (rq->es_key == KEY_ILLEGAL_REQUEST) {
			dump("cmd:    ", (caddr_t)ucmd,
			    sizeof (struct uscsi_cmd), HEX_ONLY);
			dump("cdb:    ", (caddr_t)ucmd->uscsi_cdb,
			    ucmd->uscsi_cdblen, HEX_ONLY);
		}
		dump("sense:  ", (caddr_t)rq, rqlen, HEX_ONLY);
	}

	if (option_msg) {
		switch (rq->es_code) {
		case CODE_FMT_DESCR_CURRENT:
		case CODE_FMT_DESCR_DEFERRED:
			scsi_print_descr_sense(sdsp, rqlen);
			break;
		case CODE_FMT_FIXED_CURRENT:
		case CODE_FMT_FIXED_DEFERRED:
		default:
			scsi_print_extended_sense(rq, rqlen);
			break;
		}
	}
}

/*
 * Retrieve "information" field from descriptor format
 * sense data.  Iterates through each sense descriptor
 * looking for the information descriptor and returns
 * the information field from that descriptor.
 */
static diskaddr_t
scsi_extract_sense_info_descr(struct scsi_descr_sense_hdr *sdsp, int rqlen)
{
	diskaddr_t result;
	uint8_t *descr_offset;
	int valid_sense_length;
	struct scsi_information_sense_descr *isd;

	/*
	 * Initialize result to -1 indicating there is no information
	 * descriptor
	 */
	result = (diskaddr_t)-1;

	/*
	 * The first descriptor will immediately follow the header
	 */
	descr_offset = (uint8_t *)(sdsp+1); /* Pointer arithmetic */

	/*
	 * Calculate the amount of valid sense data
	 */
	valid_sense_length =
	    min((sizeof (struct scsi_descr_sense_hdr) +
	    sdsp->ds_addl_sense_length),
	    rqlen);

	/*
	 * Iterate through the list of descriptors, stopping when we
	 * run out of sense data
	 */
	while ((descr_offset + sizeof (struct scsi_information_sense_descr)) <=
	    (uint8_t *)sdsp + valid_sense_length) {
		/*
		 * Check if this is an information descriptor.  We can
		 * use the scsi_information_sense_descr structure as a
		 * template sense the first two fields are always the
		 * same
		 */
		isd = (struct scsi_information_sense_descr *)descr_offset;
		if (isd->isd_descr_type == DESCR_INFORMATION) {
			/*
			 * Found an information descriptor.  Copy the
			 * information field.  There will only be one
			 * information descriptor so we can stop looking.
			 */
			result =
			    (((diskaddr_t)isd->isd_information[0] << 56) |
			    ((diskaddr_t)isd->isd_information[1] << 48) |
			    ((diskaddr_t)isd->isd_information[2] << 40) |
			    ((diskaddr_t)isd->isd_information[3] << 32) |
			    ((diskaddr_t)isd->isd_information[4] << 24) |
			    ((diskaddr_t)isd->isd_information[5] << 16) |
			    ((diskaddr_t)isd->isd_information[6] << 8)  |
			    ((diskaddr_t)isd->isd_information[7]));
			break;
		}

		/*
		 * Get pointer to the next descriptor.  The "additional
		 * length" field holds the length of the descriptor except
		 * for the "type" and "additional length" fields, so
		 * we need to add 2 to get the total length.
		 */
		descr_offset += (isd->isd_addl_length + 2);
	}

	return (result);
}

/*
 * Return a pointer to a string telling us the name of the command.
 */
static char *
scsi_find_command_name(uint_t cmd)
{
	struct scsi_command_name *c;

	for (c = scsi_command_names; c->command != SCMD_UNKNOWN; c++)
		if (c->command == cmd)
			break;
	return (c->name);
}


/*
 * Return true if we support a particular mode page
 */
int
scsi_supported_page(int page)
{
	return (page == 1 || page == 2 || page == 3 || page == 4 ||
	    page == 8 || page == 0x38);
}


int
apply_chg_list(int pageno, int pagsiz, uchar_t *curbits,
    uchar_t *chgbits, struct chg_list *chglist)
{
	uchar_t		c;
	int		i;
	int		m;
	int		delta;
	int		changed = 0;

	while (chglist != NULL) {
		if (chglist->pageno == pageno &&
		    chglist->byteno < pagsiz) {
			i = chglist->byteno;
			c = curbits[i];
			switch (chglist->mode) {
			case CHG_MODE_SET:
				c |= (uchar_t)chglist->value;
				break;
			case CHG_MODE_CLR:
				c &= (uchar_t)chglist->value;
				break;
			case CHG_MODE_ABS:
				c = (uchar_t)chglist->value;
				break;
			}
			/*
			 * Figure out which bits changed, and
			 * are marked as changeable.  If this
			 * result actually differs from the
			 * current value, update the current
			 * value, and note that a mode select
			 * should be done.
			 */
			delta = c ^ curbits[i];
			for (m = 0x01; m < 0x100; m <<= 1) {
				if ((delta & m) && (chgbits[i] & m)) {
					curbits[i] ^= m;
					changed = 1;
				}
			}
		}
		chglist = chglist->next;
	}

	return (changed);
}


/*
 * Return whether a given page is affected by an item on
 * the change list.
 */
static int
chg_list_affects_page(struct chg_list *chglist, int pageno)
{
	while (chglist != NULL) {
		if (chglist->pageno == pageno) {
			return (1);
		}
		chglist = chglist->next;
	}

	return (0);
}


/*
 * Labels for the various fields of the scsi_extended_sense structure
 */
static char *scsi_extended_sense_labels[] = {
	"Request sense valid:             ",
	"Error class and code:            ",
	"Segment number:                  ",
	"Filemark:                        ",
	"End-of-medium:                   ",
	"Incorrect length indicator:      ",
	"Sense key:                       ",
	"Information field:               ",
	"Additional sense length:         ",
	"Command-specific information:    ",
	"Additional sense code:           ",
	"Additional sense code qualifier: ",
	"Field replaceable unit code:     ",
	"Sense-key specific:              ",
	"Additional sense bytes:          "
};


/*
 * Display the full scsi_extended_sense as returned by the device
 */
static void
scsi_print_extended_sense(struct scsi_extended_sense *rq, int rqlen)
{
	char			**p;

	p = scsi_extended_sense_labels;
	if (rqlen < (sizeof (*rq) - 2) || !rq->es_valid) {
		/*
		 * target should be capable of returning at least 18
		 * bytes of data, i.e upto rq->es_skey_specific field.
		 * The additional sense bytes (2 or more ...) are optional.
		 */
		return;
	}

	fmt_print("\n%s%s\n", *p++, rq->es_valid ? "yes" : "no");
	fmt_print("%s0x%02x\n", *p++, (rq->es_class << 4) + rq->es_code);
	fmt_print("%s%d\n", *p++, rq->es_segnum);
	fmt_print("%s%s\n", *p++, rq->es_filmk ? "yes" : "no");
	fmt_print("%s%s\n", *p++, rq->es_eom ? "yes" : "no");
	fmt_print("%s%s\n", *p++, rq->es_ili ? "yes" : "no");
	fmt_print("%s%d\n", *p++, rq->es_key);

	fmt_print("%s0x%02x 0x%02x 0x%02x 0x%02x\n", *p++, rq->es_info_1,
	    rq->es_info_2, rq->es_info_3, rq->es_info_4);
	fmt_print("%s%d\n", *p++, rq->es_add_len);
	fmt_print("%s0x%02x 0x%02x 0x%02x 0x%02x\n", *p++, rq->es_cmd_info[0],
	    rq->es_cmd_info[1], rq->es_cmd_info[2], rq->es_cmd_info[3]);
	fmt_print("%s0x%02x = %d\n", *p++, rq->es_add_code, rq->es_add_code);
	fmt_print("%s0x%02x = %d\n", *p++, rq->es_qual_code, rq->es_qual_code);
	fmt_print("%s%d\n", *p++, rq->es_fru_code);
	fmt_print("%s0x%02x 0x%02x 0x%02x\n", *p++, rq->es_skey_specific[0],
	    rq->es_skey_specific[1], rq->es_skey_specific[2]);
	if (rqlen >= sizeof (*rq)) {
		fmt_print("%s0x%02x 0x%02x%s\n", *p, rq->es_add_info[0],
		    rq->es_add_info[1], (rqlen > sizeof (*rq)) ? " ..." : "");
	}

	fmt_print("\n");
}

/*
 * Labels for the various fields of the scsi_descr_sense_hdr structure
 */
static char *scsi_descr_sense_labels[] = {
	"Error class and code:            ",
	"Sense key:                       ",
	"Additional sense length:         ",
	"Additional sense code:           ",
	"Additional sense code qualifier: ",
	"Additional sense bytes:          "
};


/*
 * Display the full descriptor sense data as returned by the device
 */

static void
scsi_print_descr_sense(struct scsi_descr_sense_hdr *rq, int rqlen)
{
	char			**p;
	uint8_t			*descr_offset;
	int			valid_sense_length;
	struct scsi_information_sense_descr *isd;

	p = scsi_descr_sense_labels;
	if (rqlen < sizeof (struct scsi_descr_sense_hdr)) {
		/*
		 * target must return at least 8 bytes of data
		 */
		return;
	}

	/* Print descriptor sense header */
	fmt_print("%s0x%02x\n", *p++, (rq->ds_class << 4) + rq->ds_code);
	fmt_print("%s%d\n", *p++, rq->ds_key);

	fmt_print("%s%d\n", *p++, rq->ds_addl_sense_length);
	fmt_print("%s0x%02x = %d\n", *p++, rq->ds_add_code, rq->ds_add_code);
	fmt_print("%s0x%02x = %d\n", *p++, rq->ds_qual_code, rq->ds_qual_code);
	fmt_print("\n");

	/*
	 * Now print any sense descriptors.   The first descriptor will
	 * immediately follow the header
	 */
	descr_offset = (uint8_t *)(rq+1); /* Pointer arithmetic */

	/*
	 * Calculate the amount of valid sense data
	 */
	valid_sense_length =
	    min((sizeof (struct scsi_descr_sense_hdr) +
	    rq->ds_addl_sense_length), rqlen);

	/*
	 * Iterate through the list of descriptors, stopping when we
	 * run out of sense data.  Descriptor format is:
	 *
	 * <Descriptor type> <Descriptor length> <Descriptor data> ...
	 */
	while ((descr_offset + *(descr_offset + 1)) <=
	    (uint8_t *)rq + valid_sense_length) {
		/*
		 * Determine descriptor type.  We can use the
		 * scsi_information_sense_descr structure as a
		 * template since the first two fields are always the
		 * same.
		 */
		isd = (struct scsi_information_sense_descr *)descr_offset;
		switch (isd->isd_descr_type) {
		case DESCR_INFORMATION: {
			uint64_t information;

			information =
			    (((uint64_t)isd->isd_information[0] << 56) |
			    ((uint64_t)isd->isd_information[1] << 48) |
			    ((uint64_t)isd->isd_information[2] << 40) |
			    ((uint64_t)isd->isd_information[3] << 32) |
			    ((uint64_t)isd->isd_information[4] << 24) |
			    ((uint64_t)isd->isd_information[5] << 16) |
			    ((uint64_t)isd->isd_information[6] << 8)  |
			    ((uint64_t)isd->isd_information[7]));
			fmt_print("Information field:               "
			    "%0llx\n", information);
			break;
		}
		case DESCR_COMMAND_SPECIFIC: {
			struct scsi_cmd_specific_sense_descr *c =
			    (struct scsi_cmd_specific_sense_descr *)isd;
			uint64_t cmd_specific;

			cmd_specific =
			    (((uint64_t)c->css_cmd_specific_info[0] << 56) |
			    ((uint64_t)c->css_cmd_specific_info[1] << 48) |
			    ((uint64_t)c->css_cmd_specific_info[2] << 40) |
			    ((uint64_t)c->css_cmd_specific_info[3] << 32) |
			    ((uint64_t)c->css_cmd_specific_info[4] << 24) |
			    ((uint64_t)c->css_cmd_specific_info[5] << 16) |
			    ((uint64_t)c->css_cmd_specific_info[6] << 8)  |
			    ((uint64_t)c->css_cmd_specific_info[7]));
			fmt_print("Command-specific information:    "
			    "%0llx\n", cmd_specific);
			break;
		}
		case DESCR_SENSE_KEY_SPECIFIC: {
			struct scsi_sk_specific_sense_descr *ssd =
			    (struct scsi_sk_specific_sense_descr *)isd;
			uint8_t *sk_spec_ptr = (uint8_t *)&ssd->sss_data;
			fmt_print("Sense-key specific:              "
			    "0x%02x 0x%02x 0x%02x\n", sk_spec_ptr[0],
			    sk_spec_ptr[1], sk_spec_ptr[2]);
			break;
		}
		case DESCR_FRU: {
			struct scsi_fru_sense_descr *fsd =
			    (struct scsi_fru_sense_descr *)isd;
			fmt_print("Field replaceable unit code:     "
			    "%d\n", fsd->fs_fru_code);
			break;
		}
		case DESCR_BLOCK_COMMANDS: {
			struct scsi_block_cmd_sense_descr *bsd =
			    (struct scsi_block_cmd_sense_descr *)isd;
			fmt_print("Incorrect length indicator:      "
			    "%s\n", bsd->bcs_ili ? "yes" : "no");
			break;
		}
		default:
			/* Ignore */
			break;
		}

		/*
		 * Get pointer to the next descriptor.  The "additional
		 * length" field holds the length of the descriptor except
		 * for the "type" and "additional length" fields, so
		 * we need to add 2 to get the total length.
		 */
		descr_offset += (isd->isd_addl_length + 2);
	}

	fmt_print("\n");
}

/*
 * Function checks if READ DEFECT DATA command is supported
 * on the current disk.
 */
static int
check_support_for_defects(void)
{
	struct uscsi_cmd	ucmd;
	union scsi_cdb		cdb;
	struct scsi_defect_list	def_list;
	struct scsi_defect_hdr	*hdr;
	int			status;
	char			rqbuf[255];
	struct scsi_extended_sense	*rq;

	hdr = (struct scsi_defect_hdr *)&def_list;

	/*
	 * First get length of list by asking for the header only.
	 */
	(void) memset((char *)&def_list, 0, sizeof (def_list));

	/*
	 * Build and execute the uscsi ioctl
	 */
	(void) memset((char *)&ucmd, 0, sizeof (ucmd));
	(void) memset((char *)&cdb, 0, sizeof (union scsi_cdb));
	(void) memset((char *)rqbuf, 0, 255);
	cdb.scc_cmd = SCMD_READ_DEFECT_LIST;
	FORMG1COUNT(&cdb, sizeof (struct scsi_defect_hdr));
	cdb.cdb_opaque[2] = DLD_MAN_DEF_LIST | DLD_BFI_FORMAT;
	ucmd.uscsi_cdb = (caddr_t)&cdb;
	ucmd.uscsi_cdblen = CDB_GROUP1;
	ucmd.uscsi_bufaddr = (caddr_t)hdr;
	ucmd.uscsi_buflen = sizeof (struct scsi_defect_hdr);
	ucmd.uscsi_rqbuf = rqbuf;
	ucmd.uscsi_rqlen = sizeof (rqbuf);
	ucmd.uscsi_rqresid = sizeof (rqbuf);
	rq = (struct scsi_extended_sense *)ucmd.uscsi_rqbuf;

	status = uscsi_cmd(cur_file, &ucmd,
	    (option_msg && diag_msg) ? F_NORMAL : F_SILENT);

	if (status != 0) {
		/*
		 * check if read_defect_list_is_supported.
		 */
		if (ucmd.uscsi_rqstatus == STATUS_GOOD &&
		    rq->es_key == KEY_ILLEGAL_REQUEST &&
		    rq->es_add_code == INVALID_OPCODE)
			return (0);
	}
	return (1);
}

/*
 * Format the disk, the whole disk, and nothing but the disk.
 * Function will be called only for disks
 * which do not support read defect list command.
 */
static int
scsi_format_without_defects(void)
{
	struct uscsi_cmd	ucmd;
	union scsi_cdb		cdb;
	struct scsi_defect_hdr	defect_hdr;
	int			status;

	/*
	 * Construct the uscsi format ioctl.
	 * Use fmtdata = 0 , indicating the no source of
	 * defects information is provided .
	 * Function will be called only for disks
	 * which do not support read defect list command.
	 */
	(void) memset((char *)&ucmd, 0, sizeof (ucmd));
	(void) memset((char *)&cdb, 0, sizeof (union scsi_cdb));
	(void) memset((char *)&defect_hdr, 0, sizeof (defect_hdr));
	cdb.scc_cmd = SCMD_FORMAT;
	ucmd.uscsi_cdb = (caddr_t)&cdb;
	ucmd.uscsi_cdblen = CDB_GROUP0;
	ucmd.uscsi_bufaddr = (caddr_t)&defect_hdr;
	ucmd.uscsi_buflen = sizeof (defect_hdr);
	cdb.cdb_opaque[1] = 0;
	/*
	 * Issue the format ioctl
	 */
	status = uscsi_cmd(cur_file, &ucmd,
	    (option_msg && diag_msg) ? F_NORMAL : F_SILENT);
	return (status);
}

/*
 * Name: test_until_ready
 *
 * Description: This function is used by scsi_format and
 *   scsi_format_raw to poll the device while the FORMAT
 *   UNIT cdb in in progress.
 *
 * Parameters:
 *   file descriptor to poll
 *
 * Returns:
 *   0 - good status
 *   !0 - bad status
 */
static int test_until_ready(int fd) {
	int				status = 1;
	struct uscsi_cmd		ucmd;
	union scsi_cdb			cdb;
	struct scsi_extended_sense	sense;
	time_t				start, check, time_left;
	uint16_t			progress;
	int				hour, min, sec;

	(void) memset((char *)&ucmd, 0, sizeof (ucmd));
	(void) memset((char *)&cdb, 0, sizeof (union scsi_cdb));

	ucmd.uscsi_cdb		= (caddr_t)&cdb;
	ucmd.uscsi_cdblen	= CDB_GROUP0;
	ucmd.uscsi_rqbuf	= (caddr_t)&sense;
	ucmd.uscsi_rqlen	= SENSE_LEN;

	start = check = time((time_t *)0);

	/* Loop sending TEST UNIT READY until format is complete */
	while (status) {
		/* clear last request sense data */
		ucmd.uscsi_rqstatus	= 0;
		ucmd.uscsi_rqresid	= 0;
		(void) memset((char *)&sense, 0, SENSE_LEN);

		/* issue test unit ready */
		status = uscsi_cmd(fd, &ucmd, F_SILENT
				| F_RQENABLE);

		check = time((time_t *)0);

		/* If device returns not ready we get EIO */
		if (status != 0 && errno == EIO) {
			/* Check SKSV if progress indication is avail */
			if (sense.es_skey_specific[0] == 0x80) {
				/* Store progress indication */
				progress = ((uint16_t)sense.
					es_skey_specific[1]) << 8;
				progress |= (uint16_t)sense.
					es_skey_specific[2];
				progress = (uint16_t)(((float)progress /
					(float)PROGRESS_INDICATION_BASE)*100);

				fmt_print("\015");

				/*
				 * check to see if we can estimate
				 * time remaining  - wait until the format
				 * is at least 5 percent complete to avoid
				 * wildly-fluctuating time estimates
				 */
				if ((check - start) <= 0 || progress <= 5) {
					/* unable to estimate */
					fmt_print("  %02d%% complete ",
						progress);
				} else {
					/* display with estimated time */
					time_left = (time_t)(((float)(check
						- start) / (float)progress) *
						(float)(100 - progress));
					sec = time_left % 60;
					min = (time_left / 60) % 60;
					hour = time_left / 3600;

					fmt_print("  %02d%% complete "
						"(%02d:%02d:%02d remaining) ",
						progress, hour, min, sec);
				}
				/* flush or the screen will not update */
				(void) fflush(stdout);
			}
		} else {
			/* format not in progress */
			if (option_msg) {
			fmt_print("\nRequest Sense ASC=0x%x ASCQ=0x%x",
				sense.es_add_code, sense.es_qual_code);
			}
			break;
		}

		/* delay so we don't waste cpu time */
		(void) sleep(RETRY_DELAY);
	}
	return (status);
}

/*
 * Get the current protection type from the PROT_EN and P_TYPE
 */
uint8_t
get_cur_protection_type(struct scsi_capacity_16 *capacity)
{
	uint8_t	cp13;
	uint8_t	prot_en;
	uint8_t	p_type;

	cp13 = ((capacity->sc_rsvd0 & 0x3f) << 2)
	    | ((capacity->sc_prot_en & 0x01) << 1)
	    | (capacity->sc_rto_en & 0x01);
	prot_en = cp13 & 0x01;
	if (prot_en == 0) {
		p_type = 0;
	} else {
		p_type = (cp13 << 4) >> 5;
		p_type += 1;
	}
	return (p_type);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright (c) 1993, 2010, Oracle and/or its affiliates. All rights reserved.
 */

#ifndef	_CTLR_SCSI_H
#define	_CTLR_SCSI_H

#ifdef	__cplusplus
extern "C" {
#endif

#include <sys/buf.h>
#include <sys/scsi/scsi.h>


/*
 * Rounded parameter, as returned in Extended Sense information
 */
#define	ROUNDED_PARAMETER	0x37

/*
 * Timeout Value during formatting
 */
#ifndef	SHRT_MAX
#define	SHRT_MAX	32767
#endif

/*
 * Mode sense/select page header information
 */
struct scsi_ms_header {
	struct mode_header	mode_header;
	struct block_descriptor	block_descriptor;
};

/*
 * Mode Sense Page Control
 */
#define	MODE_SENSE_PC_CURRENT		(0 << 6)
#define	MODE_SENSE_PC_CHANGEABLE	(1 << 6)
#define	MODE_SENSE_PC_DEFAULT		(2 << 6)
#define	MODE_SENSE_PC_SAVED		(3 << 6)

/*
 * Mode Select options
 */
#define	MODE_SELECT_SP			0x01
#define	MODE_SELECT_PF			0x10



/*
 * Minimum length of Request Sense data that we can accept
 */
#define	MIN_REQUEST_SENSE_LEN		18

/*
 * "impossible" status value
 */
#define	IMPOSSIBLE_SCSI_STATUS		0xff

/*
 * Convert a three-byte triplet into an int
 */
#define	TRIPLET(u, m, l)	((int)((((u))&0xff<<16) + \
				(((m)&0xff)<<8) + (l&0xff)))

/*
 * Define the amount of slop we can tolerate on a SCSI-2 mode sense.
 * Usually we try to deal with just the common subset between the
 * the SCSI-2 structure and the CCS structure.  The length of the
 * data returned can vary between targets, so being tolerant gives
 * gives us a higher chance of success.
 */
#define	PAGE1_SLOP		5
#define	PAGE2_SLOP		6
#define	PAGE3_SLOP		3
#define	PAGE4_SLOP		8
#define	PAGE8_SLOP		8
#define	PAGE38_SLOP		8

/*
 * Minimum lengths of a particular SCSI-2 mode sense page that
 * we can deal with.  We must reject anything less than this.
 */
#define	MIN_PAGE1_LEN		(sizeof (struct mode_err_recov)-PAGE1_SLOP)
#define	MIN_PAGE2_LEN		(sizeof (struct mode_disco_reco)-PAGE2_SLOP)
#define	MIN_PAGE3_LEN		(sizeof (struct mode_format)-PAGE3_SLOP)
#define	MIN_PAGE4_LEN		(sizeof (struct mode_geometry)-PAGE4_SLOP)
#define	MIN_PAGE8_LEN		(sizeof (struct mode_cache)-PAGE8_SLOP)
#define	MIN_PAGE38_LEN		(sizeof (struct mode_cache_ccs)-PAGE38_SLOP)

/*
 * Macro to extract the length of a mode sense page
 * as returned by a target.
 */
#define	MODESENSE_PAGE_LEN(p)	(((int)((struct mode_page *)p)->length) + \
					sizeof (struct mode_page))

/*
 * Request this number of bytes for all mode senses.  Since the
 * data returned is self-defining, we can accept anywhere from
 * the minimum for a particular page, up to this maximum.
 * Whatever the drive gives us, we return to the drive, delta'ed
 * by whatever we want to change.
 */
#define	MAX_MODE_SENSE_SIZE		255


#ifdef	__STDC__
/*
 *	Local prototypes for ANSI C compilers
 */
int	scsi_rdwr(int, int, diskaddr_t, int, caddr_t, int, int *);
int	scsi_ex_man(struct defect_list *);
int	scsi_ex_cur(struct defect_list *);
int	scsi_ex_grown(struct defect_list *);
int	uscsi_cmd(int, struct uscsi_cmd *, int);
int	uscsi_mode_sense(int, int, int, caddr_t, int,
		struct scsi_ms_header *);
int	uscsi_mode_select(int, int, int, caddr_t, int,
		struct scsi_ms_header *);
int	uscsi_inquiry(int, caddr_t, int);
int	uscsi_inquiry_page_86h(int, caddr_t, int);
int	uscsi_read_capacity(int, struct scsi_capacity_16 *);
int	uscsi_read_capacity_16(int, struct scsi_capacity_16 *);
int	scsi_translate(int, struct scsi_bfi_defect *);
int	scsi_dump_mode_sense_pages(int);
int	scsi_supported_page(int);
int	apply_chg_list(int, int, uchar_t *, uchar_t *, struct chg_list *);
int	scsi_format_time(void);
uint8_t	get_cur_protection_type(struct scsi_capacity_16 *);

#else

#ifdef sparc
int	scsi_ms_page1();
int	scsi_ms_page2();
int	scsi_ms_page3();
int	scsi_ms_page4();
int	scsi_read_defect_data();
int	scsi_repair();
#endif /* sparc */

int	scsi_rdwr();
int	scsi_ck_format();
int	scsi_ex_man();
int	scsi_ex_cur();
int	scsi_ex_grown();
int	uscsi_cmd();
int	uscsi_mode_sense();
int	uscsi_mode_select();
int	uscsi_inquiry();
int	uscsi_read_capacity();
int	scsi_translate();
int	scsi_dump_mode_sense_pages();
int	scsi_supported_page();
int	apply_chg_list();
int	scsi_format_time();

#endif	/* __STDC__ */

#ifdef	__cplusplus
}
#endif

#endif	/* _CTLR_SCSI_H */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * This file contains routines that manipulate the defect list.
 */
#include "global.h"
#include <sys/types.h>
#include <sys/param.h>

#if defined(sparc)
#include <sys/hdio.h>
#endif		/* defined(sparc) */

#include <sys/buf.h>
#include <sys/ioctl.h>
#include <sys/uio.h>
#include <sys/fcntl.h>
#include <string.h>
#include <unistd.h>
#include <memory.h>

#if defined(sparc)
#include <sys/dkbad.h>
#endif		/* defined(sparc) */

#include "misc.h"
#include "param.h"


#if defined(sparc)
/*
 * This structure is the bad block table for the current disk if
 * the disk uses bad-144 defect mapping.
 */
struct	dkbad badmap;
#endif		/* defined(sparc) */

/*
 * This routine reads the defect list off the disk.  It also reads in the
 * bad block table if the disk is a BAD144 type.  The defect list is
 * located on the first 2 tracks of the 2nd alternate cylinder of all
 * disks.  The bad block map is located on the first 5 even sectors of
 * the last track of the last cylinder.
 */
void
read_list(struct defect_list *list)
{
	int	size, head;

#if defined(sparc)
	int sec, status;
	struct	bt_bad *bt;
#endif	/* defined(sparc) */

	assert(!EMBEDDED_SCSI);

	/*
	 * This flags has been introduced only for Sparc ATA IDE.
	 * This indicates that no list manipulation is done in this controller
	 * and hence return without any other checking.
	 */
	if (cur_ctype->ctype_flags & CF_NOWLIST) {
		return;
	}

	/*
	 * Panther's working list is maintained by the controller
	 */
	if (cur_ctype->ctype_flags & CF_WLIST) {
		if (*cur_ops->op_ex_cur != NULL &&
		    ((*cur_ops->op_ex_cur)(list)) == 0) {
			if (list->header.magicno != DEFECT_MAGIC) {
				fmt_print("Defect list BAD\n");
			} else {
				fmt_print("Controller working list found\n");
			}
			return;
		}

		if (*cur_ops->op_ex_man != NULL &&
		    ((*cur_ops->op_ex_man)(list)) == 0) {
			if (list->header.magicno != DEFECT_MAGIC) {
				fmt_print("Defect list BAD\n");
			} else {
				fmt_print("MANUFACTURER's list found\n");
			}
			return;
		}
		fmt_print("No defect list found\n");
		return;
	}

	/*
	 * Loop for each copy of the defect list until we get a good one.
	 */
	for (head = 0; head < LISTCOUNT; head++) {
		/*
		 * Try to read the list header.
		 */
		if ((*cur_ops->op_rdwr)(DIR_READ, cur_file,
		    (diskaddr_t)chs2bn(ncyl + 1, head, 0), 1,
		    (char *)&list->header, NULL), F_NORMAL)
			continue;
		/*
		 * If the magic number is wrong, this copy is corrupt.
		 */
		if (list->header.magicno != DEFECT_MAGIC)
			continue;
		/*
		 * Allocate space for the rest of the list.
		 */
		size = deflist_size(cur_blksz, list->header.count);
		list->list = (struct defect_entry *)zalloc(size * cur_blksz);
		/*
		 * Try to read in the rest of the list. If there is an
		 * error, or the checksum is wrong, this copy is corrupt.
		 */
		if ((*cur_ops->op_rdwr)(DIR_READ, cur_file,
		    (diskaddr_t)chs2bn(ncyl + 1, head, 1), size,
		    (char *)list->list, F_NORMAL, NULL) ||
		    checkdefsum(list, CK_CHECKSUM)) {
			/*
			 * Destroy the list and go on.
			 */
			kill_deflist(list);
			continue;
		}
		/*
		 * Got a good copy, stop searching.
		 */
		break;
	}
#if defined(sparc)
	if (!(cur_ctlr->ctlr_flags & DKI_BAD144))
		return;
	/*
	 * The disk uses BAD144, read in the bad-block table.
	 */
	for (sec = 0; ((sec < BAD_LISTCNT * 2) && (sec < nsect)); sec += 2) {
		status = (*cur_ops->op_rdwr)(DIR_READ, cur_file,
		    (diskaddr_t)chs2bn(ncyl + acyl - 1, nhead - 1, sec), 1,
		    &badmap, F_NORMAL, NULL);
		if (status)
			continue;
		/*
		 * Do a sanity check on the list read in.  If it passes,
		 * stop searching.
		 */
		if (badmap.bt_mbz != 0)
			continue;
		for (bt = badmap.bt_bad; bt - badmap.bt_bad < NDKBAD; bt++) {
			if (bt->bt_cyl < 0)
				break;
			if (bt->bt_trksec < 0)
				continue;
			head = bt->bt_trksec >> 8;
			if ((bt->bt_cyl >= pcyl) || (head >= nhead) ||
			    ((bt->bt_trksec & 0xff) >= sectors(head))) {
				status = -1;
				break;
			}
		}
		if (status)
			continue;
		return;
	}
	/*
	 * If we couldn't find the bad block table, initialize it to
	 * zero entries.
	 */
	for (bt = badmap.bt_bad; bt - badmap.bt_bad < NDKBAD; bt++)
		bt->bt_cyl = bt->bt_trksec = -1;
	badmap.bt_mbz = badmap.bt_csn = badmap.bt_flag = 0;
#endif		/* defined(sparc) */
}

/*
 * This routine either checks or calculates the checksum for a defect
 * list, depending on the mode parameter. In check mode, it returns
 * whether or not the checksum is correct.
 */
int
checkdefsum(struct defect_list *list, int mode)
{
	register int *lp, i, sum = 0;

	/*
	 * Perform the rolling xor to get what the checksum should be.
	 */
	lp = (int *)list->list;
	for (i = 0; i < (list->header.count *
	    sizeof (struct defect_entry) / sizeof (int)); i++)
		sum ^= *(lp + i);
	/*
	 * If in check mode, return whether header checksum was correct.
	 */
	if (mode == CK_CHECKSUM)
		return (sum != list->header.cksum);
	/*
	 * If in create mode, set the header checksum.
	 */
	else {
		list->header.cksum = sum;
		return (0);
	}
}

/*
 * This routine prints a single defect to stdout in a readable format.
 */
void
pr_defect(struct defect_entry *def, int num)
{

	/*
	 * Make defect numbering look 1 relative.
	 */
	++num;
	/*
	 * Print out common values.
	 */
	fmt_print("%4d%8d%7d", num, def->cyl, def->head);
	/*
	 * The rest of the values may be unknown. If they are, just
	 * print blanks instead.  Also, only print length only if bfi is
	 * known, and assume that a known bfi implies an unknown sect.
	 */
	if (def->bfi != UNKNOWN) {
		fmt_print("%8d", def->bfi);
		if (def->nbits != UNKNOWN)
			fmt_print("%8d", def->nbits);
	} else {
		fmt_print("                ");
		fmt_print("%8d", def->sect);
		fmt_print("%8llu", chs2bn(def->cyl, def->head, def->sect));
	}
	fmt_print("\n");
}

/*
 * This routine calculates where in a defect list a given defect should
 * be sorted. It returns the index that the defect should become.  The
 * algorithm used sorts all bfi based defects by cylinder/head/bfi, and
 * adds all logical sector defects to the end of the list.  This is
 * necessary because the ordering of logical sector defects is significant
 * when sector slipping is employed.
 */
int
sort_defect(struct defect_entry *def, struct defect_list *list)
{
	struct	defect_entry *ptr;

	/*
	 * If it's a logical sector defect, return the entry at the end
	 * of the list.
	 */
	if (def->bfi == UNKNOWN)
		return (list->header.count);
	/*
	 * It's a bfi defect.  Loop through the defect list.
	 */
	for (ptr = list->list; ptr - list->list < list->header.count; ptr++) {
		/*
		 * If we get to a logical sector defect, put this defect
		 * right before it.
		 */
		if (ptr->bfi == UNKNOWN)
			goto found;
		/*
		 * If we get to a defect that is past this one in
		 * cylinder/head/bfi, put this defect right before it.
		 */
		if (def->cyl < ptr->cyl)
			goto found;
		if (def->cyl != ptr->cyl)
			continue;
		if (def->head < ptr->head)
			goto found;
		if (def->head != ptr->head)
			continue;
		if (def->bfi < ptr->bfi)
			goto found;
	}
found:
	/*
	 * Return the index to put the defect at.
	 */
	return (ptr - list->list);
}

/*
 * This routine writes the defect list on the back on the disk.  It also
 * writes the bad block table to disk if bad-144 mapping applies to the
 * current disk.
 */
void
write_deflist(struct defect_list *list)
{
	int	size, head, status;

#if defined(sparc)
	int sec;
	caddr_t	bad_ptr = (caddr_t)&badmap;
#endif			/* defined(sparc) */

	assert(!EMBEDDED_SCSI);

	/*
	 * Sparc ATA IDE.
	 * This indicates that no list manipulation is done in this controller
	 * and hence return without any other checking.
	 */
	if (cur_ctype->ctype_flags & CF_NOWLIST) {
		return;
	}

	/*
	 * Panther's working list is maintained by the controller
	 */
	if (cur_ctype->ctype_flags & CF_WLIST) {
		(*cur_ops->op_wr_cur)(list);
		return;
	}

	/*
	 * If the list is null, there is nothing to write.
	 */
	if (list->list != NULL) {
		/*
		 * calculate how many sectors the defect list will occupy.
		 */
		size = deflist_size(cur_blksz, list->header.count);
		/*
		 * Loop for each copy of the list to be written.  Write
		 * out the header of the list followed by the data.
		 */
		for (head = 0; head < LISTCOUNT; head++) {
			status = (*cur_ops->op_rdwr)(DIR_WRITE, cur_file,
			    (diskaddr_t)chs2bn(ncyl + 1, head, 0), 1,
			    (char *)&list->header, F_NORMAL, NULL);
			if (status) {
				err_print(
"Warning: error saving defect list.\n");
				continue;
			}
			status = (*cur_ops->op_rdwr)(DIR_WRITE, cur_file,
			    (diskaddr_t)chs2bn(ncyl + 1, head, 1), size,
			    (char *)list->list, F_NORMAL, NULL);
			if (status)
				err_print(
"Warning: error saving defect list.\n");
		}
	}
	if (!(cur_ctlr->ctlr_flags & DKI_BAD144))
		return;
#if defined(sparc)
	/*
	 * Current disk uses bad-144 mapping.  Loop for each copy of the
	 * bad block table to be written and write it out.
	 */
	for (sec = 0; ((sec < BAD_LISTCNT * 2) && (sec < nsect)); sec += 2) {
		status = (*cur_ops->op_rdwr)(DIR_WRITE, cur_file,
		    (diskaddr_t)chs2bn(ncyl + acyl - 1, nhead - 1, sec), 1,
		    &badmap, F_NORMAL, NULL);
		if (status) {
			err_print(
"Warning: error saving bad block map table.\n");
			continue;
		}
	}
	/*
	 * Execute an ioctl to tell unix about the new bad block table.
	 */
	if (ioctl(cur_file, HDKIOCSBAD, &bad_ptr))
		err_print(
"Warning: error telling SunOS bad block map table.\n");
#endif		/* defined(sparc) */
}

/*
 * This routine adds a logical sector to the given defect list.
 */
void
add_ldef(diskaddr_t blkno, struct defect_list *list)
{
	struct	defect_entry def;
	int	index;


	/*
	 * Calculate the fields for the defect struct.
	 */
	def.cyl = bn2c(blkno);
	def.head = bn2h(blkno);
	def.sect = bn2s(blkno);
	/*
	 * Initialize the unknown fields.
	 */
	def.bfi = def.nbits = UNKNOWN;
	/*
	 * Calculate the index into the list that the defect belongs at.
	 */
	index = sort_defect(&def, list);
	/*
	 * Add the defect to the list.
	 */
	add_def(&def, list, index);
}

/*
 * This routine adds the given defect struct to the defect list at
 * a precalculated index.
 */
void
add_def(struct defect_entry *def, struct defect_list *list, int index)
{
	int	count, i;

	/*
	 * If adding this defect makes the list overflow into another
	 * sector, allocate the necessary space.
	 */
	count = list->header.count;
	if (deflist_size(cur_blksz, count + 1) > deflist_size(cur_blksz, count))
		list->list = (struct defect_entry *)rezalloc((void *)list->list,
		    deflist_size(cur_blksz, count + 1) * cur_blksz);
	/*
	 * Slip all the defects after this one down one slot in the list.
	 */
	for (i = count; i > index; i--)
		*(list->list + i) = *(list->list + i - 1);
	/*
	 * Fill in the created hole with this defect.
	 */
	*(list->list + i) = *def;
	/*
	 * Increment the count and calculate a new checksum.
	 */
	list->header.count++;
	(void) checkdefsum(list, CK_MAKESUM);
}

/*
 * This routine sets the given defect list back to null.
 */
void
kill_deflist(struct defect_list *list)
{

	/*
	 * If it's already null, we're done.
	 */
	if (list->list == NULL)
		return;
	/*
	 * Free the malloc'd space it's using.
	 */
	destroy_data((char *)list->list);
	/*
	 * Mark it as null, and clear any flags.
	 */
	list->list = NULL;
	list->flags = 0;
}

/*
 * This routine returns the defect list size
 * according to the sector size.
 */
int
deflist_size(int secsz, int sz)
{
	int rval;

	if (secsz == 0) {
		secsz = SECSIZE;
	}

	rval = sz ? ((sz * sizeof (struct defect_entry) +
	    secsz - 1) / secsz) : 1;

	return (rval);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef	_DEFECT_H
#define	_DEFECT_H

#ifdef	__cplusplus
extern "C" {
#endif

/*
 * This file contains definitions related to the defect list.
 */

extern	struct defect_list work_list;
extern	struct dkbad badmap;

/*
 * This is the structure of the header of a defect list.  It is always
 * the first sector on a track containing a defect list.
 */
struct defectHeader {
	uint_t	magicno;
	int	count;
	int	cksum;
	int	save[125];
};

/*
 * This is the structure of a defect.  Defects are stored on the disk
 * as an array of these structures following the defect header.
 */
struct defect_entry {
	short	cyl;
	short	head;
	short	sect;
	short	nbits;
	int	bfi;
};

/*
 * This is the internal representation of a defect list.  We store
 * the header statically, but dynamically allocate space for the
 * actual defects, since their number may vary.  The flags field is
 * used to keep track of whether the list has been modified.
 */
struct defect_list {
	struct	defectHeader header;
	struct	defect_entry *list;
	int	flags;
};

/*
 * This defines the number of copies of the defect list kept on the disk.
 * They are stored 1/track, starting at track 0 of the second alternate cyl.
 */
#define	LISTCOUNT	2

/*
 * These defines are the flags for the defect list.
 */
#define	LIST_DIRTY	0x01	/* List needs to be synced */
#define	LIST_RELOAD	0x02	/* Reload list after formatting (SCSI) */
#define	LIST_PGLIST	0x04	/* embedded SCSI - both manufacturer's (P) */
				/* and grown (G) list */

/*
 * Miscellaneous defines.
 */
#define	DEFECT_MAGIC	0x89898989	/* magic no for defect lists */
#define	NO_CHECKSUM	0x1		/* magic no for no checksum in */
					/* defect list */
#define	UNKNOWN		(-1)		/* value used in defect fields */
#define	DEF_PRINTHEADER	" num     cyl     hd     bfi     len     sec     blk\n"

/*
 * This defines the number of copies of the bad block table kept on the
 * disk.  They are stored in the first 5 even sectors on the last track
 * of the disk.  Note: this also defines the number of backup labels,
 * which are kept in the first 5 odd sectors of the appropriate
 * track.
 */
#define	BAD_LISTCNT	5


/*
 * Prototypes for ANSI C compilers
 */
void	read_list(struct defect_list *list);
int	makebfi(struct defect_list *list, struct defect_entry *def);
void	calc_bfi(struct defect_list *list, struct defect_entry *def,
		struct defect_entry *end, int skew);
int	makelsect(struct defect_list *list);
int	checkdefsum(struct defect_list *list, int mode);
void	pr_defect(struct defect_entry *def, int num);
int	sort_defect(struct defect_entry *def, struct defect_list *list);
void	write_deflist(struct defect_list *list);
void	add_ldef(diskaddr_t blkno, struct defect_list *list);
void	add_def(struct defect_entry *def, struct defect_list *list,
		int index);
void	kill_deflist(struct defect_list *list);

/*
 * This defines the size (in sectors) of the defect array given the number
 * of defects in the array.  It must be rounded to a sector boundary since
 * that is the atomic disk size.  We make a zero length list use up a
 * sector because it is convenient to have malloc'd space in every
 * non-null list.
 */
int	deflist_size(int secsz, int sz);

#ifdef	__cplusplus
}
#endif

#endif	/* _DEFECT_H */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * This file contains functions that implement the fdisk menu commands.
 */
#include "global.h"
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/wait.h>
#include <signal.h>
#include <string.h>
#include <sys/fcntl.h>
#include <sys/stat.h>

#include <sys/dklabel.h>
#include <errno.h>


#include "main.h"
#include "analyze.h"
#include "menu.h"
#include "menu_command.h"
#include "menu_defect.h"
#include "menu_partition.h"
#if defined(_FIRMWARE_NEEDS_FDISK)
#include "menu_fdisk.h"
#endif	/* defined(_FIRMWARE_NEEDS_FDISK) */
#include "param.h"
#include "misc.h"
#include "label.h"
#include "startup.h"
#include "partition.h"
#include "prompts.h"
#include "checkdev.h"
#include "io.h"
#include "ctlr_scsi.h"
#include "auto_sense.h"

static int	generic_ck_format(void);
static int	generic_rdwr(int dir, int fd, diskaddr_t blkno, int secnt,
			caddr_t bufaddr, int flags, int *xfercntp);

struct  ctlr_ops genericops = {
	generic_rdwr,
	generic_ck_format,
	0,
	0,
	0,
	0,
	0,
};


/*
 * Check to see if the disk has been formatted.
 * If we are able to read the first track, we conclude that
 * the disk has been formatted.
 */
static int
generic_ck_format(void)
{
	int	status;

	/*
	 * Try to read the first four blocks.
	 */
	status = generic_rdwr(DIR_READ, cur_file, 0, 4, (caddr_t)cur_buf,
	    F_SILENT, NULL);
	return (!status);
}

/*
 * Read or write the disk.
 * Temporary interface until IOCTL interface finished.
 */
/*ARGSUSED*/
static int
generic_rdwr(int dir, int fd, diskaddr_t blkno, int secnt, caddr_t bufaddr,
    int flags, int *xfercntp)
{

	offset_t	tmpsec, status, tmpblk;
	int		ret;

	tmpsec = (offset_t)secnt * cur_blksz;
	tmpblk = (offset_t)blkno * cur_blksz;

#if defined(_FIRMWARE_NEEDS_FDISK)
	/* Use "p0" file to seek/read the data  */
	(void) open_cur_file(FD_USE_P0_PATH);
#endif
	if (dir == DIR_READ) {
		status = llseek(fd, tmpblk, SEEK_SET);
		if (status != tmpblk) {
			ret = (int)status;
			goto out;
		}

		status = read(fd, bufaddr, (size_t)tmpsec);
		if (status != tmpsec)
			ret = (int)tmpsec;
		else
			ret = 0;
	} else {
		status = llseek(fd, tmpblk, SEEK_SET);
		if (status != tmpblk) {
			ret = (int)status;
			goto out;
		}

		status = write(fd, bufaddr, (size_t)tmpsec);
		if (status != tmpsec)
			ret = (int)tmpsec;
		else
			ret = 0;
	}
out:
#if defined(_FIRMWARE_NEEDS_FDISK)
	/* Restore cur_file with cur_disk->disk_path */
	(void) open_cur_file(FD_USE_CUR_DISK_PATH);
#endif
	return (ret);
}
#
# Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License, Version 1.0 only
# (the "License").  You may not use this file except in compliance
# with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
# Data file for the 'format' program.  This file defines the known
# disks, disk types, and partition maps.
#

#
# Following is a list of sample embedded SCSI disk configurations.
#
disk_type = "Quantum ProDrive 80S" \
	: ctlr = SCSI : fmt_time = 1 \
	: cache = 0x07 : trks_zone = 6 : atrks = 0 : asect = 1 \
	: ncyl = 832 : acyl = 2 : pcyl = 834 : nhead = 6 : nsect = 34 \
	: rpm = 3662 : bpt = 16896

#disk_type = "CDC Wren VII 94601-12G" \
#	: ctlr = SCSI : fmt_time = 4 \
#	: cache = 0x11 : trks_zone = 15 : asect = 5 : atrks = 30 \
#	: ncyl =  1703 : acyl = 2 : pcyl = 1931 : nhead = 15 : nsect = 80 \
#	: rpm = 3597 : bpt = 41301

#
# An early CDC Wren IV, shipped with the 386i
#
#disk_type = "CDC Wren IV 94171-327" \
#	: ctlr = SCSI : fmt_time = 4 \
#	: cache = 0x11 : trks_zone = 9 : asect = 3 \
#	: ncyl = 1520 : acyl = 2 : pcyl = 1549 : nhead = 9 : nsect = 46 \
#	: rpm = 3600 : bpt = 20833

#
# This is the list of Sun supported disks for embedded SCSI.
#
disk_type = "Quantum ProDrive 105S" \
	: ctlr = SCSI : fmt_time = 1 \
	: cache = 0x07 : trks_zone = 6 : atrks = 0 : asect = 1 \
	: ncyl = 974 : acyl = 2 : pcyl = 1019 : nhead = 6 : nsect = 35 \
	: rpm = 3662 : bpt = 16896

disk_type = "CDC Wren IV 94171-344" \
	: ctlr = SCSI : fmt_time = 4 \
	: cache = 0x11 : trks_zone = 9 : asect = 3 \
	: ncyl = 1545 : acyl = 2 : pcyl = 1549 : nhead = 9 : nsect = 46 \
	: rpm = 3600 : bpt = 20833

disk_type = "SUN0104" \
	: ctlr = SCSI : fmt_time = 1 \
	: trks_zone = 6 : atrks = 0 : asect = 1 \
	: ncyl = 974 : acyl = 2 : pcyl = 1019 : nhead = 6 : nsect = 35 \
	: rpm = 3662 : bpt = 16896

disk_type = "SUN0207" \
	: ctlr = SCSI \
	: trks_zone = 9 : atrks = 2: asect = 4 \
	: ncyl = 1254 : acyl = 2 : pcyl = 1272 : nhead = 9 : nsect = 36 \
	: rpm = 3600 : bpt = 18432

disk_type = "SUN0327" \
	: ctlr = SCSI : fmt_time = 4 \
	: cache = 0x11 : trks_zone = 9 : asect = 3 \
	: ncyl = 1545 : acyl = 2 : pcyl = 1549 : nhead = 9 : nsect = 46 \
	: rpm = 3600 : bpt = 20833

disk_type = "SUN0340" \
	: ctlr = SCSI : fmt_time = 2 \
	: trks_zone = 6  \
	: ncyl = 1538 : acyl = 2 : pcyl = 1544 : nhead = 6 : nsect = 72 \
	: rpm = 4200

disk_type = "SUN0424" \
	: ctlr = SCSI : fmt_time = 4 \
	: trks_zone = 9 : asect = 2 \
	: ncyl = 1151 : acyl = 2 : pcyl = 2500 : nhead = 9 : nsect = 80 \
	: rpm = 4400 : bpt = 26000

disk_type = "SUN0535" \
	: ctlr = SCSI : fmt_time = 4 \
	: ncyl = 1866 : acyl = 2 : pcyl = 2500 : nhead = 7 : nsect = 80 \
	: rpm = 5400

disk_type = "SUN0669" \
	: ctlr = SCSI : fmt_time = 4 \
	: trks_zone = 15 : asect = 5 : atrks = 30 \
	: ncyl =  1614 : acyl = 2 : pcyl = 1632 : nhead = 15 : nsect = 54 \
	: rpm = 3600 : bpt = 31410

disk_type = "SUN1.0G" \
	: ctlr = SCSI : fmt_time = 4 \
	: trks_zone = 15 : asect = 5 : atrks = 30 \
	: ncyl =  1703 : acyl = 2 : pcyl = 1931 : nhead = 15 : nsect = 80 \
	: rpm = 3597 : bpt = 41301

disk_type = "SUN1.05" \
	: ctlr = SCSI : fmt_time = 4 \
	: ncyl = 2036 : acyl = 2 : pcyl = 2038 : nhead = 14 : nsect = 72 \
	: rpm = 5400

disk_type = "SUN1.3G" \
	: ctlr = SCSI : fmt_time = 4 \
	: trks_zone = 17 : asect = 6 : atrks = 17 \
	: ncyl = 1965 : acyl = 2 : pcyl = 3500 : nhead = 17 : nsect = 80 \
	: rpm = 5400 : bpt = 44823

disk_type = "SUN2.1G" \
	: ctlr = SCSI : fmt_time = 4 \
	: ncyl = 2733 : acyl = 2 : pcyl = 3500 : nhead = 19 : nsect = 80 \
	: rpm = 5400 : bpt = 44823

disk_type = "SUN2.9G" \
	: ctlr = SCSI : fmt_time = 4 \
	: ncyl = 2734 : acyl = 2 : pcyl = 3500 : nhead = 21 : nsect = 99 \
	: rpm = 5400

disk_type = "Zip 100" \
	: ctlr = SCSI \
	: ncyl = 95 : acyl = 0 : pcyl = 95 : nhead = 64 : nsect = 32 \
	: rpm = 2941 : bpt = 16384

disk_type = "Zip 250" \
	: ctlr = SCSI : ncyl = 6117 : acyl = 2 : pcyl = 6119 \
	: nhead = 2 : nsect = 40 : rpm = 3600

disk_type = "Peerless 10GB" \
	: ctlr = SCSI : ncyl = 9583 : acyl = 2 : pcyl = 9585 \
	: nhead = 64 : nsect = 32 : rpm = 3600


#
# Following is a list of sample partition tables for embedded SCSI disks.
#
partition = "Quantum ProDrive 80S" \
	: disk = "Quantum ProDrive 80S" : ctlr = SCSI \
	: 0 = 0, 16384 : 1 = 64, 32512 : 2 = 0, 198144 : 6 = 191, 149248

#partition = "CDC Wren VII 94601-12G" \
#	: disk = "CDC Wren VII 94601-12G" : ctlr = SCSI \
#	: 0 = 0, 32400 : 1 = 27, 64800 : 2 = 0, 2043600 : 6 = 81, 1946400

#partition = "CDC Wren IV 94171-327" \
#	: disk = "CDC Wren IV 94171-327" : ctlr = SCSI \
#	: 0 = 0, 31878 : 1 = 77, 59616 : 2 = 0, 629280 : 6 = 221, 527786

#
# This is the list of partition tables for embedded SCSI controllers.
#
partition = "Quantum ProDrive 105S" \
	: disk = "Quantum ProDrive 105S" : ctlr = SCSI \
	: 0 = 0, 16170 : 1 = 77, 28140 : 2 = 0, 204540 : 6 = 211, 160230

partition = "CDC Wren IV 94171-344, small root" \
	: disk = "CDC Wren IV 94171-344" : ctlr = SCSI \
	: 0 = 0, 16974 : 1 = 41, 33948 : 2 = 0, 639630 : 6 = 123, 588708

partition = "CDC Wren IV 94171-344" \
	: disk = "CDC Wren IV 94171-344" : ctlr = SCSI \
	: 0 = 0, 31878 : 1 = 77, 59616 : 2 = 0, 639630 : 6 = 221, 548136

partition = "SUN0104" \
	: disk = "SUN0104" : ctlr = SCSI \
	: 0 = 0, 16170 : 1 = 77, 28140 : 2 = 0, 204540 : 6 = 211, 160230

partition = "SUN0207" \
	: disk = "SUN0207" : ctlr = SCSI \
	: 0 = 0, 33048 : 1 = 102, 65448 : 2 = 0, 406296 : 6 = 304, 307800

partition = "SUN0327" \
	: disk = "SUN0327" : ctlr = SCSI \
	: 0 = 0, 31878 : 1 = 77, 59616 : 2 = 0, 639630 : 6 = 221, 548136

partition = "SUN0340" \
	: disk = "SUN0340" : ctlr = SCSI \
	: 0 = 0, 86400 : 1 = 200, 66960 : 2 = 0, 664416 : 6 = 355, 446256 \
	: 7 = 1388, 64800

partition = "SUN0424" \
	: disk = "SUN0424" : ctlr = SCSI \
	: 0 = 0, 33120 : 1 = 46, 65520 : 2 = 0, 828720 : 6 = 137, 730080

partition = "SUN0535" \
	: disk = "SUN0535" : ctlr = SCSI \
	: 0 = 0, 64400 : 1 = 115, 103600 : 2 = 0, 1044960 : 6 = 300, 876960

partition = "SUN0669" \
	: disk = "SUN0669" : ctlr = SCSI \
	: 0 = 0, 32400 : 1 = 40, 64800 : 2 = 0, 1307340 : 6 = 120, 1210140

partition = "SUN1.0G" \
	: disk = "SUN1.0G" : ctlr = SCSI \
	: 0 = 0, 32400 : 1 = 27, 64800 : 2 = 0, 2043600 : 6 = 81, 1946400

partition = "SUN1.05" \
	: disk = "SUN1.05" : ctlr = SCSI \
	: 0 = 0, 66528 : 1 = 66, 133056 : 2 = 0, 2052288 : 6 = 198, 1852704

partition = "SUN1.3G" \
	: disk = "SUN1.3G" : ctlr = SCSI \
	: 0 = 0, 34000 : 1 = 25, 133280 : 2 = 0, 2672400 : 6 = 123, 2505120

partition = "SUN2.1G" \
	: disk = "SUN2.1G" : ctlr = SCSI \
	: 0 = 0, 62320 : 1 = 41, 197600 : 2 = 0, 4154160 : 6 = 171, 3894240

partition = "SUN2.9G" \
	: disk = "SUN2.9G" : ctlr = SCSI \
	: 0 = 0, 195426 : 1 = 94, 390852 : 2 = 0, 5683986 : 6 = 282, 5097708

partition = "Zip 100" \
	: disk = "Zip 100" : ctlr = SCSI \
	: 0 = 0, 194560 : 2 = 0, 194560

partition = "Zip 250" \
	: disk = "Zip 250" : ctlr = SCSI \
	: 0 =  0, 489360 : 2 =  0, 489360

partition = "Peerless 10GB" \
	: disk = "Peerless 10GB" : ctlr = SCSI \
	: 0 = 0, 19625984 : 2 = 0, 19625984
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright (c) 1993, 2010, Oracle and/or its affiliates. All rights reserved.
 */

#ifndef	_GLOBAL_H
#define	_GLOBAL_H

#ifdef	__cplusplus
extern "C" {
#endif

/*
 * Definitions for Label types: L_TYPE_SOLORIS is the default Sun label
 * a.k.a VTOC. L_TYPE_EFI is the EFI label type.
 */
#define	L_TYPE_SOLARIS	0
#define	L_TYPE_EFI	1

#ifndef	UINT_MAX64
#define	UINT_MAX64	0xffffffffffffffffULL
#endif

#ifndef UINT_MAX32
#define	UINT_MAX32	0xffffffffU
#endif

#if !defined(_EXTVTOC)
#define	_EXTVTOC	/* extented vtoc (struct extvtoc) format is used */
#endif

/*
 * This file contains global definitions and declarations.  It is intended
 * to be included by everyone.
 */
#include <stdio.h>
#include <assert.h>
#include <memory.h>
#include <unistd.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/isa_defs.h>

#include <sys/dklabel.h>
#include <sys/vtoc.h>
#include <sys/dkio.h>

#include "hardware_structs.h"
#include "defect.h"
#include "io.h"

#include <sys/dktp/fdisk.h>
#include <sys/fcntl.h>


/*
 * These declarations are global state variables.
 */
extern struct	disk_info *disk_list;		/* list of found disks */
extern struct	ctlr_info *ctlr_list;		/* list of found ctlrs */
extern char	cur_menu;			/* current menu level */
extern char	last_menu;			/* last menu level */
extern char	option_msg;			/* extended message options */
extern char	diag_msg;			/* extended diagnostic msgs */
extern char	option_s;			/* silent mode option */
extern char	*option_f;			/* input redirect option */
extern char	*option_l;			/* log file option */
extern FILE	*log_file;			/* log file pointer */
extern char	*option_d;			/* forced disk option */
extern char	*option_t;			/* forced disk type option */
extern char	*option_p;		/* forced partition table option */
extern char	*option_x;		/* data file redirection option */
extern FILE	*data_file;		/* data file pointer */
extern char	*file_name;		/* current data file name */
					/* for useful error messages */
extern int	expert_mode;		/* enable for expert mode */
					/* commands */
extern int	need_newline;		/* for correctly formatted output */
extern int	dev_expert;		/* enable for developer mode */
					/* commands */

/*
 * These declarations are used for quick access to information about
 * the disk being worked on.
 */
extern int	cur_file;		/* file descriptor for current disk */
extern int	cur_flags;			/* flags for current disk */
extern int	cur_label;			/* current label type */
extern uint_t	cur_blksz;			/* currect disk block size */
extern struct	disk_info *cur_disk;		/* current disk */
extern struct	disk_type *cur_dtype;		/* current dtype */
extern struct	ctlr_info *cur_ctlr;		/* current ctlr */
extern struct	ctlr_type *cur_ctype;		/* current ctype */
extern struct	ctlr_ops *cur_ops;		/* current ctlr's ops vector */
extern struct	partition_info *cur_parts; /* current disk's partitioning */
extern struct	defect_list cur_list;		/* current disk's defect list */
extern void	*cur_buf;			/* current disk's I/O buffer */
extern void	*pattern_buf;		/* current disk's pattern buffer */
extern uint_t	pcyl;				/* # physical cyls */
extern uint_t	ncyl;				/* # data cyls */
extern uint_t	acyl;				/* # alt cyls */
extern uint_t	nhead;				/* # heads */
extern uint_t	phead;				/* # physical heads */
extern uint_t	nsect;				/* # data sects/track */
extern uint_t	psect;				/* # physical sects/track */
extern uint_t	apc;				/* # alternates/cyl */
extern uint_t	solaris_offset;		/* Solaris offset, this value is zero */
					/* for non-fdisk machines. */
extern int	prot_type;		/* protection type to format disk */

#if defined(_SUNOS_VTOC_16)
extern uint_t	bcyl;				/* # other cyls */
#endif		/* defined(_SUNOS_VTOC_16) */

extern struct	mboot boot_sec;			/* fdisk partition info */
extern uint_t	xstart;				/* solaris partition start */
extern char	x86_devname[MAXNAMELEN]; /* saved device name for fdisk */
					/* information accesses */
extern struct	mctlr_list	*controlp;	/* master controller list ptr */


/*
 * These defines are used to manipulate the physical characteristics of
 * the current disk.
 */
#define	sectors(h)	((h) == nhead - 1 ? nsect - apc : nsect)
#define	spc()		(nhead * nsect - apc)
#define	chs2bn(c, h, s)	(((diskaddr_t)(c) * spc() + (h) * nsect + (s)))
#define	bn2c(bn)	(uint_t)((diskaddr_t)(bn) / spc())
#define	bn2h(bn)	(uint_t)(((diskaddr_t)(bn) % spc()) / nsect)
#define	bn2s(bn)	(uint_t)(((diskaddr_t)(bn) % spc()) % nsect)
#define	datasects()	(ncyl * spc())
#define	totalsects()	((ncyl + acyl) * spc())
#define	physsects()	(pcyl * spc())

/*
 * Macro to convert a device number into a partition number
 */
#define	PARTITION(dev)	(minor(dev) & 0x07)

/*
 * These values define flags for the current disk (cur_flags).
 */
#define	DISK_FORMATTED		0x01	/* disk is formatted */
#define	LABEL_DIRTY		0x02	/* label has been scribbled */

/*
 * These flags are for the controller type flags field.
 */
#define	CF_NONE		0x0000		/* NO FLAGS */
#define	CF_BLABEL	0x0001		/* backup labels in funny place */
#define	CF_DEFECTS	0x0002		/* disk has manuf. defect list */
#define	CF_APC		0x0004		/* ctlr uses alternates per cyl */
#define	CF_SMD_DEFS	0x0008		/* ctlr does smd defect handling */

#define	CF_SCSI		0x0040		/* ctlr is for SCSI disks */
#define	CF_EMBEDDED	0x0080		/* ctlr is for embedded SCSI disks */

#define	CF_IPI		0x0100		/* ctlr is for IPI disks */
#define	CF_WLIST	0x0200		/* ctlt handles working list */
#define	CF_NOFORMAT	0x0400		/* Manufacture formatting only */
/*
 * This flag has been introduced only for SPARC ATA. Which has been approved
 * at that time with the agreement in the next fix it will be removed and the
 * format will be revamped with controller Ops structure not to  have
 * any operation to be NULL. As it makes things more modular.
 *
 * This flag is also used for PCMCIA pcata driver.
 * The flag prevents reading or writing a defect list on the disk
 * testing and console error reporting still work normally.
 * This is appropriate for the PCMCIA disks which often have MS/DOS filesystems
 * and have not allocated any space for alternate cylinders to keep
 * the bab block lists.
 */
#define	CF_NOWLIST	0x0800		/* Ctlr doesnot handle working list */


/*
 * Do not require confirmation to extract defect lists on SCSI
 * and IPI drives, since this operation is instantaneous
 */
#define	CF_CONFIRM	(CF_SCSI|CF_IPI)

/*
 * Macros to make life easier
 */
#define	SMD		(cur_ctype->ctype_flags & CF_SMD_DEFS)
#define	SCSI		(cur_ctype->ctype_flags & CF_SCSI)
#define	EMBEDDED_SCSI	((cur_ctype->ctype_flags & (CF_SCSI|CF_EMBEDDED)) == \
				(CF_SCSI|CF_EMBEDDED))

/*
 * These flags are for the disk type flags field.
 */
#define	DT_NEED_SPEFS	0x01		/* specifics fields are uninitialized */

/*
 * These defines are used to access the ctlr specific
 * disk type fields (based on ctlr flags).
 */
#define	dtype_bps	dtype_specifics[0]	/* bytes/sector */
#define	dtype_dr_type	dtype_specifics[1]	/* drive type */
#define	dtype_dr_type_data dtype_specifics[2]	/* drive type in data file */

/*
 * These flags are for the disk info flags field.
 */
#define	DSK_LABEL	0x01		/* disk is currently labelled */
#define	DSK_LABEL_DIRTY	0x02		/* disk auto-sensed, but not */
					/* labeled yet. */
#define	DSK_AUTO_CONFIG	0x04		/* disk was auto-configured */
#define	DSK_RESERVED	0x08		/* disk is reserved by other host */
#define	DSK_UNAVAILABLE	0x10		/* disk not available, could be */
					/* currently formatting */

/*
 * These flags are used to control disk command execution.
 */
#define	F_NORMAL	0x00		/* normal operation */
#define	F_SILENT	0x01		/* no error msgs at all */
#define	F_ALLERRS	0x02		/* return any error, not just fatal */
#define	F_RQENABLE	0x04		/* no error msgs at all */

/*
 * Directional parameter for the op_rdwr controller op.
 */
#define	DIR_READ	0
#define	DIR_WRITE	1

/*
 * These defines are the mode parameter for the checksum routines.
 */
#define	CK_CHECKSUM		0		/* check checksum */
#define	CK_MAKESUM		1		/* generate checksum */

/*
 * This is the base character for partition identifiers
 */
#define	PARTITION_BASE		'0'

/*
 * Base pathname for devfs names to be stripped from physical name.
 */
#define	DEVFS_PREFIX	"/devices"

/*
 *  Protection type by SCSI-3
 */
#define	PROT_TYPE_0	0
#define	PROT_TYPE_1	1
#define	PROT_TYPE_2	2
#define	PROT_TYPE_3	3
#define	NUM_PROT_TYPE	4

/*
 * Function prototypes ... Both for ANSI and non-ANSI C compilers
 */
#ifdef	__STDC__

int copy_solaris_part(struct ipart *);
int good_fdisk(void);
int fdisk_physical_name(char *);

#else	/* __STDC__ */

int copy_solaris_part();
int good_fdisk();
int fdisk_physical_name();

#endif	/* __STDC__ */

#ifdef	__cplusplus
}
#endif

#endif	/* _GLOBAL_H */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 * Copyright 2015 Nexenta Systems, Inc. All rights reserved.
 * Copyright (c) 2016 by Delphix. All rights reserved.
 */

#ifndef	_HARDWARE_STRUCTS_H
#define	_HARDWARE_STRUCTS_H

#ifdef	__cplusplus
extern "C" {
#endif

#include <sys/isa_defs.h>

#include <sys/dktp/fdisk.h>
#include <sys/dklabel.h>
#include <sys/efi_partition.h>

/*
 * This file contains definitions of data structures pertaining to disks
 * and controllers.
 */

/*
 * This structure describes a specific disk.  These structures are in a
 * linked list because they are malloc'd as disks are found during the
 * initial search.
 */
struct disk_info {
	int			label_type;	/* EFI or non-EFI disk */
	struct dk_cinfo		disk_dkinfo;	/* controller config info */
	struct disk_type	*disk_type;	/* ptr to physical info */
	struct partition_info	*disk_parts;	/* ptr to partition info */
	struct dk_gpt		*efi_parts;	/* ptr to partition info */
	struct ctlr_info	*disk_ctlr;	/* ptr to disk's ctlr */
	struct disk_info	*disk_next;	/* ptr to next disk */
	struct ipart		fdisk_part;	/* fdisk partition info */
	int			disk_flags;	/* misc gotchas */
	char			*disk_name;	/* name of the disk */
	char			*disk_path;	/* pathname to device */
	char			*devfs_name;	/* devfs name for device */
	char			v_volume[LEN_DKL_VVOL];
						/* volume name from label */
						/* (no terminating null) */
	uint_t			disk_lbasize;	/* disk block size */

};

#define	NSPECIFICS	8

/*
 * This structure describes a type (model) of drive.  It is malloc'd
 * and filled in as the data file is read and when a type 'other' disk
 * is selected.  The link is used to make a list of all drive types
 * supported by a ctlr type.
 */
struct disk_type {
	char	*dtype_asciilabel;		/* drive identifier */
	int	dtype_flags;			/* flags for disk type */
	ulong_t	dtype_options;			/* flags for options */
	uint_t	dtype_fmt_time;			/* format time */
	uint_t	dtype_bpt;			/* # bytes per track */
	uint_t	dtype_ncyl;			/* # of data cylinders */
	uint_t	dtype_acyl;			/* # of alternate cylinders */
	uint_t	dtype_pcyl;			/* # of physical cylinders */
	uint_t	dtype_nhead;			/* # of heads */
	uint_t	dtype_phead;			/* # of physical heads */
	uint_t	dtype_nsect;			/* # of data sectors/track */
	uint_t	dtype_psect;			/* # physical sectors/track */
	uint_t	dtype_rpm;			/* rotations per minute */
	int	dtype_cyl_skew;			/* cylinder skew */
	int	dtype_trk_skew;			/* track skew */
	uint_t	dtype_trks_zone;		/* # tracks per zone */
	uint_t	dtype_atrks;			/* # alt. tracks  */
	uint_t	dtype_asect;			/* # alt. sectors */
	int	dtype_cache;			/* cache control */
	int	dtype_threshold;		/* cache prefetch threshold */
	int	dtype_read_retries;		/* read retries */
	int	dtype_write_retries;		/* write retries */
	int	dtype_prefetch_min;		/* cache min. prefetch */
	int	dtype_prefetch_max;		/* cache max. prefetch */
	uint_t	dtype_specifics[NSPECIFICS];	/* ctlr specific drive info */
	struct	chg_list	*dtype_chglist;	/* mode sense/select */
						/* change list - scsi */
	struct	partition_info	*dtype_plist;	/* possible partitions */
	struct	disk_type	*dtype_next;	/* ptr to next drive type */
	/*
	 * Added so that we can print a useful diagnostic if
	 * inconsistent definitions found in multiple files.
	 */
	char	*dtype_filename;		/* filename where defined */
	int	dtype_lineno;			/* line number in file */

	char		*vendor;
	char		*product;
	char		*revision;
	uint64_t	capacity;
};

struct efi_info {
	char		*vendor;
	char		*product;
	char		*revision;
	uint64_t	capacity;
	struct dk_gpt	*e_parts;
};

/*
 * This structure describes a specific ctlr.  These structures are in
 * a linked list because they are malloc'd as ctlrs are found during
 * the initial search.
 */
struct ctlr_info {
	char	ctlr_cname[DK_DEVLEN+1];	/* name of ctlr */
	char	ctlr_dname[DK_DEVLEN+1];	/* name of disks */
	ushort_t ctlr_flags;			/* flags for ctlr */
	short	ctlr_num;			/* number of ctlr */
	int	ctlr_addr;			/* address of ctlr */
	uint_t	ctlr_space;			/* bus space it occupies */
	int	ctlr_prio;			/* interrupt priority */
	int	ctlr_vec;			/* interrupt vector */
	struct	ctlr_type *ctlr_ctype;		/* ptr to ctlr type info */
	struct	ctlr_info *ctlr_next;		/* ptr to next ctlr */
};

/*
 * This structure describes a type (model) of ctlr.  All supported ctlr
 * types are built into the program statically, they cannot be added by
 * the user.
 */
struct ctlr_type {
	ushort_t ctype_ctype;			/* type of ctlr */
	char	*ctype_name;			/* name of ctlr type */
	struct	ctlr_ops *ctype_ops;		/* ptr to ops vector */
	int	ctype_flags;			/* flags for gotchas */
	struct	disk_type *ctype_dlist;		/* list of disk types */
};

/*
 * This structure is the operation vector for a controller type.  It
 * contains pointers to all the functions a controller type can support.
 */
struct ctlr_ops {
	int	(*op_rdwr)();		/* read/write - mandatory */
	int	(*op_ck_format)();	/* check format - mandatory */
	int	(*op_format)();		/* format - mandatory */
	int	(*op_ex_man)();		/* get manufacturer's list - optional */
	int	(*op_ex_cur)();		/* get current list - optional */
	int	(*op_repair)();		/* repair bad sector - optional */
	int	(*op_create)();		/* create original manufacturers */
					/* defect list. - optional */
	int	(*op_wr_cur)();		/* write current list - optional */
};

/*
 * This structure describes a specific partition layout.  It is malloc'd
 * when the data file is read and whenever the user creates their own
 * partition layout.  The link is used to make a list of possible
 * partition layouts for each drive type.
 */
struct partition_info {
	char	*pinfo_name;			/* name of layout */
	struct	dk_map32 pinfo_map[NDKMAP];	/* layout info */
	struct	dk_vtoc vtoc;			/* SVr4 vtoc additions */
	struct	partition_info *pinfo_next;	/* ptr to next layout */
	char	*pinfo_filename;		/* filename where defined */
	int	pinfo_lineno;			/* line number in file */
	struct	dk_gpt	*etoc;			/* EFI partition info */
};


/*
 * This structure describes a change to be made to a particular
 * SCSI mode sense page, before issuing a mode select on that
 * page.  This changes are specified in format.dat, and one
 * such structure is created for each specification, linked
 * into a list, in the order specified.
 */
struct chg_list {
	int		pageno;		/* mode sense page no. */
	int		byteno;		/* byte within page */
	int		mode;		/* see below */
	int		value;		/* desired value */
	struct chg_list	*next;		/* ptr to next */
};

/*
 * Change list modes
 */
#define	CHG_MODE_UNDEFINED	(-1)		/* undefined value */
#define	CHG_MODE_SET		0		/* set bits by or'ing */
#define	CHG_MODE_CLR		1		/* clr bits by and'ing */
#define	CHG_MODE_ABS		2		/* set absolute value */

/*
 * This is the structure that creates a dynamic list of controllers
 * that we know about.  This structure will point to the items that
 * use to be statically created in the format program but will now allow
 * dynamic creation of the list so that we can do 3'rd party generic
 * disk/controller support.
 */

struct mctlr_list {
	struct mctlr_list *next;
	struct ctlr_type  *ctlr_type;
};

#ifdef	__cplusplus
}
#endif

#endif	/* _HARDWARE_STRUCTS_H */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * This file defines the known controller types.  To add a new controller
 * type, simply add a new line to the array and define the necessary
 * ops vector in a 'driver' file.
 */
#include "global.h"
#include <sys/dkio.h>

extern	struct ctlr_ops scsiops;
extern	struct ctlr_ops ataops;
extern	struct ctlr_ops pcmcia_ataops;
extern  struct ctlr_ops genericops;

/*
 * This array defines the supported controller types
 */
struct	ctlr_type ctlr_types[] = {

	{ DKC_DIRECT,
		"ata",
		&ataops,
		CF_NOFORMAT | CF_WLIST },

	{ DKC_SCSI_CCS,
		"SCSI",
		&scsiops,
		CF_SCSI | CF_EMBEDDED },

	{ DKC_PCMCIA_ATA,
		"pcmcia",
		&pcmcia_ataops,
		CF_NOFORMAT | CF_NOWLIST },

	{ DKC_VBD,
		"virtual-dsk",
		&genericops,
		CF_NOWLIST },

	{ DKC_BLKDEV,
		"generic-block-device",
		&genericops,
		CF_NOWLIST }
};

/*
 * This variable is used to count the entries in the array so its
 * size is not hard-wired anywhere.
 */
int	nctypes = sizeof (ctlr_types) / sizeof (struct ctlr_type);
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 1996,1998,2000,2002 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * This file defines the known controller types.  To add a new controller
 * type, simply add a new line to the array and define the necessary
 * ops vector in a 'driver' file.
 */
#include "global.h"

extern	struct ctlr_ops scsiops;
extern	struct ctlr_ops ataops;
extern	struct ctlr_ops pcmcia_ataops;

/*
 * This array defines the supported controller types
 */
struct	ctlr_type ctlr_types[] = {
	{ DKC_SCSI_CCS,
		"SCSI",
		&scsiops,
		CF_SCSI | CF_EMBEDDED },
	{ DKC_DIRECT,
		"ata",
		&ataops,
		CF_NOFORMAT | CF_NOWLIST },

	{ DKC_PCMCIA_ATA,
		"pcmcia",
		&pcmcia_ataops,
		CF_NOFORMAT | CF_NOWLIST },
};

/*
 * This variable is used to count the entries in the array so its
 * size is not hard-wired anywhere.
 */
int	nctypes = sizeof (ctlr_types) / sizeof (struct ctlr_type);
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * This file contains the declarations of menus for the program.  To add
 * a new command/menu, simply add it to the appropriate table and define
 * the function that executes it.
 */
#include <sys/isa_defs.h>
#include "global.h"
#include "menu.h"
#include "menu_partition.h"
#include "menu_command.h"
#include "menu_analyze.h"
#include "menu_defect.h"
#include "add_definition.h"
#include "menu_scsi.h"
#include "menu_developer.h"
#include "menu_cache.h"

#include "menu_fdisk.h"


/*
 * This declaration is for the command menu.  It is the menu first
 * encountered upon entering the program.
 */
struct	menu_item menu_command[] = {
	{ "disk       - select a disk",
		c_disk, true },

	{ "type       - select (define) a disk type",
		c_type, true },

	{ "partition  - select (define) a partition table",
		c_partition, true },

	{ "current    - describe the current disk",
		c_current, true },

	{ "format     - format and analyze the disk",
		c_format, true },

	{ "fdisk      - run the fdisk program",
		c_fdisk, support_fdisk_on_sparc },

	{ "repair     - repair a defective sector",
		c_repair, true },

	{ "show       - translate a disk address",
		c_show,	 not_scsi },

	{ "label      - write label to the disk",
		c_label, true },

	{ "analyze    - surface analysis",
		c_analyze, true },

	{ "defect     - defect list management",
		c_defect, true },

	{ "backup     - search for backup labels",
		c_backup, true },

	{ "verify     - read and display labels",
		c_verify, true },

	{ "save       - save new disk/partition definitions",
		add_definition, not_efi },

	{ "inquiry    - show vendor, product and revision",
		c_inquiry, scsi },

	{ "scsi       - independent SCSI mode selects",
		c_scsi, scsi_expert },

	{ "cache      - enable, disable or query SCSI disk cache",
		c_cache, scsi_expert },

	{ "volname    - set 8-character volume name",
		c_volname, true },

	{ "developer  - dump developer things",
		c_developer, developer },

	{ "!<cmd>     - execute <cmd>, then return",
		execute_shell, true},

	{ NULL }
};


/*
 * This declaration is for the partition menu.  It is used to create
 * and maintain partition tables.
 */
struct	menu_item menu_partition[] = {
	{ "0      - change `0' partition",
		p_apart, true },
	{ "1      - change `1' partition",
		p_bpart, true },
	{ "2      - change `2' partition",
		p_cpart, true },
	{ "3      - change `3' partition",
		p_dpart, true },
	{ "4      - change `4' partition",
		p_epart, true },
	{ "5      - change `5' partition",
		p_fpart, true },
	{ "6      - change `6' partition",
		p_gpart, true },
	{ "7      - change `7' partition",
		p_hpart, disp_expert_change_expert_efi },
	{ "8      - change '8' partition",
		p_ipart, disp_all_change_expert_efi },
#if defined(i386)
	{ "9      - change `9' partition",
		p_jpart, expert },
#endif
	{ "expand - expand label to use whole disk",
		p_expand, disp_expand_efi },
	{ "select - select a predefined table",
		p_select, true },
	{ "modify - modify a predefined partition table",
		p_modify, true },
	{ "name   - name the current table",
		p_name, true },
	{ "print  - display the current table",
		p_print, true },
	{ "label  - write partition map and label to the disk",
		c_label, true },
	{ "!<cmd> - execute <cmd>, then return",
		execute_shell, true},

	{ NULL }
};



/*
 * This declaration is for the analysis menu.  It is used to set up
 * and execute surface analysis of a disk.
 */
struct menu_item menu_analyze[] = {
	{ "read     - read only test   (doesn't harm SunOS)",
		a_read,	 true },
	{ "refresh  - read then write  (doesn't harm data)",
		a_refresh, true },
	{ "test     - pattern testing  (doesn't harm data)",
		a_test,	 true },
	{ "write    - write then read      (corrupts data)",
		a_write, true },
	{ "compare  - write, read, compare (corrupts data)",
		a_compare, true },
	{ "purge    - write, read, write   (corrupts data)",
		a_purge, true },
	{ "verify   - write entire disk, then verify (corrupts data)",
		a_verify, true },
	{ "print    - display data buffer",
		a_print, true },
	{ "setup    - set analysis parameters",
		a_setup, true },
	{ "config   - show analysis parameters",
		a_config, true },
	{ "!<cmd>   - execute <cmd> , then return",
		execute_shell, true},
	{ NULL }
};



/*
 * This declaration is for the defect menu.  It is used to manipulate
 * the defect list for a disk.
 */
struct menu_item menu_defect[] = {
	{ "restore  - set working list = current list",
		d_restore, not_embedded_scsi },
	{ "original - extract manufacturer's list from disk",
		d_original, not_embedded_scsi },
	{ "extract  - extract working list from disk",
		d_extract, not_embedded_scsi },
	{ "primary  - extract manufacturer's defect list",
		d_primary, embedded_scsi },
	{ "grown    - extract the grown defects list",
		d_grown, embedded_scsi },
	{ "both     - extract both primary and grown defects lists",
		d_both, embedded_scsi },
	{ "add      - add defects to working list",
		d_add,	 not_embedded_scsi },
	{ "delete   - delete a defect from working list",
		d_delete, not_embedded_scsi },
	{ "print    - display defect list",
		d_print, embedded_scsi },
	{ "dump     - dump defect list to file",
		d_dump,	 embedded_scsi },
	{ "print    - display working list",
		d_print, not_embedded_scsi },
	{ "dump     - dump working list to file",
		d_dump,	 not_embedded_scsi },
	{ "load     - load working list from file",
		d_load,	 not_embedded_scsi },
	{ "commit   - set current list = working list",
		d_commit, not_embedded_scsi },
	{ "create   - recreates maufacturer's defect list on disk",
		d_create, not_embedded_scsi },
	{ "!<cmd>   - execute <cmd>, then return",
		execute_shell, true},

	{ NULL }
};

/*
 * This declaration is for the developer menu.
 */
struct menu_item menu_developer[] = {
	{ "dump_disk  - dump disk entries",
		dv_disk, true },
	{ "dump_cont  - dump controller entries",
		dv_cont, true },
	{ "dump_c_chain - dump controller chain entries",
		dv_cont_chain, true },
	{ "dev_params - dump device parameters",
		dv_params, true },
	{ "!<cmd>     - execute <cmd>, then return",
		execute_shell, true},
	{ NULL }
};

/*
 * This declaration is for the cache menu.
 */
struct menu_item menu_cache[] = {
	{ "write_cache - display or modify write cache settings",
		ca_write_cache, scsi_expert },
	{ "read_cache  - display or modify read cache settings",
		ca_read_cache,  scsi_expert },
	{ "!<cmd>      - execute <cmd>, then return",
		execute_shell, true},
	{ NULL }
};

/*
 * This declaration is for the write_cache menu.
 */
struct menu_item menu_write_cache[] = {
	{ "display     - display current setting of write cache",
		ca_write_display, scsi_expert },
	{ "enable      - enable write cache",
		ca_write_enable,  scsi_expert },
	{ "disable     - disable write cache",
		ca_write_disable, scsi_expert },
	{ "!<cmd>      - execute <cmd>, then return",
		execute_shell, true},
	{ NULL }
};

/*
 * This declaration is for the read_cache menu.
 */
struct menu_item menu_read_cache[] = {
	{ "display     - display current setting of read cache",
		ca_read_display, scsi_expert },
	{ "enable      - enable read cache",
		ca_read_enable,  scsi_expert },
	{ "disable     - disable read cache",
		ca_read_disable, scsi_expert },
	{ "!<cmd>      - execute <cmd>, then return",
		execute_shell, true},
	{ NULL }
};
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 * Copyright 2015 Nexenta Systems, Inc. All rights reserved.
 */

/*
 * This file contains I/O related functions.
 */
#include "global.h"

#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <ctype.h>
#include <stdarg.h>
#include <sys/tty.h>
#include <sys/termio.h>
#include <sys/termios.h>
#include <sys/efi_partition.h>

#include "startup.h"
#include "misc.h"
#include "menu_partition.h"
#include "param.h"
#include "menu.h"


extern int	data_lineno;
extern char	*space2str(uint_t);

/*
 * This variable is used to determine whether a token is present in the pipe
 * already.
 */
static	char	token_present = 0;

/*
 * This variable always gives us access to the most recent token type
 */
int	last_token_type = 0;

static int	sup_get_token(char *);
static void	pushchar(int c);
static int	checkeof(void);
static void	flushline(void);
static int	strcnt(char *s1, char *s2);
static int	getbn(char *str, diskaddr_t *iptr);
static void	print_input_choices(int type, u_ioparam_t *param);
static int	slist_widest_str(slist_t *slist);
static void	ljust_print(char *str, int width);
static int	sup_inputchar(void);
static void	sup_pushchar(int c);
static int	geti64(char *str, uint64_t *iptr, uint64_t *wild);

/*
 * This routine pushes the given character back onto the input stream.
 */
static void
pushchar(int c)
{
	(void) ungetc(c, stdin);
}

/*
 * This routine checks the input stream for an eof condition.
 */
static int
checkeof(void)
{
	return (feof(stdin));
}

/*
 * This routine gets the next token off the input stream.  A token is
 * basically any consecutive non-white characters.
 */
char *
gettoken(char *inbuf)
{
	char	*ptr = inbuf;
	int	c, quoted = 0;

retoke:
	/*
	 * Remove any leading white-space.
	 */
	while ((isspace(c = getchar())) && (c != '\n'))
		;
	/*
	 * If we are at the beginning of a line and hit the comment character,
	 * flush the line and start again.
	 */
	if (!token_present && c == COMMENT_CHAR) {
		token_present = 1;
		flushline();
		goto retoke;
	}
	/*
	 * Loop on each character until we hit unquoted white-space.
	 */
	while (!isspace(c) || quoted && (c != '\n')) {
		/*
		 * If we hit eof, get out.
		 */
		if (checkeof())
			return (NULL);
		/*
		 * If we hit a double quote, change the state of quotedness.
		 */
		if (c == '"')
			quoted = !quoted;
		/*
		 * If there's room in the buffer, add the character to the end.
		 */
		else if (ptr - inbuf < TOKEN_SIZE)
			*ptr++ = (char)c;
		/*
		 * Get the next character.
		 */
		c = getchar();
	}
	/*
	 * Null terminate the token.
	 */
	*ptr = '\0';
	/*
	 * Peel off white-space still in the pipe.
	 */
	while (isspace(c) && (c != '\n'))
		c = getchar();
	/*
	 * If we hit another token, push it back and set state.
	 */
	if (c != '\n') {
		pushchar(c);
		token_present = 1;
	} else
		token_present = 0;
	/*
	 * Return the token.
	 */
	return (inbuf);
}

/*
 * This routine removes the leading and trailing spaces from a token.
 */
void
clean_token(char *cleantoken, char *token)
{
	char	*ptr;

	/*
	 * Strip off leading white-space.
	 */
	for (ptr = token; isspace(*ptr); ptr++)
		;
	/*
	 * Copy it into the clean buffer.
	 */
	(void) strcpy(cleantoken, ptr);
	/*
	 * Strip off trailing white-space.
	 */
	for (ptr = cleantoken + strlen(cleantoken) - 1;
	    isspace(*ptr) && (ptr >= cleantoken); ptr--) {
		*ptr = '\0';
	}
}

/*
 * This routine checks if a token is already present on the input line
 */
int
istokenpresent(void)
{
	return (token_present);
}

/*
 * This routine flushes the rest of an input line if there is known
 * to be data in it.  The flush has to be qualified because the newline
 * may have already been swallowed by the last gettoken.
 */
static void
flushline(void)
{
	if (token_present) {
		/*
		 * Flush the pipe to eol or eof.
		 */
		while ((getchar() != '\n') && !checkeof())
			;
		/*
		 * Mark the pipe empty.
		 */
		token_present = 0;
	}
}

/*
 * This routine returns the number of characters that are identical
 * between s1 and s2, stopping as soon as a mismatch is found.
 */
static int
strcnt(char *s1, char *s2)
{
	int	i = 0;

	while ((*s1 != '\0') && (*s1++ == *s2++))
		i++;
	return (i);
}

/*
 * This routine converts the given token into an integer.  The token
 * must convert cleanly into an integer with no unknown characters.
 * If the token is the wildcard string, and the wildcard parameter
 * is present, the wildcard value will be returned.
 */
int
geti(char *str, int *iptr, int *wild)
{
	char	*str2;

	/*
	 * If there's a wildcard value and the string is wild, return the
	 * wildcard value.
	 */
	if (wild != NULL && strcmp(str, WILD_STRING) == 0)
		*iptr = *wild;
	else {
		/*
		 * Conver the string to an integer.
		 */
		*iptr = (int)strtol(str, &str2, 0);
		/*
		 * If any characters didn't convert, it's an error.
		 */
		if (*str2 != '\0') {
			err_print("`%s' is not an integer.\n", str);
			return (-1);
		}
	}
	return (0);
}

/*
 * This routine converts the given token into a long long.  The token
 * must convert cleanly into a 64-bit integer with no unknown characters.
 * If the token is the wildcard string, and the wildcard parameter
 * is present, the wildcard value will be returned.
 */
static int
geti64(char *str, uint64_t *iptr, uint64_t *wild)
{
	char	*str2;

	/*
	 * If there's a wildcard value and the string is wild, return the
	 * wildcard value.
	 */
	if ((wild != NULL) && (strcmp(str, WILD_STRING)) == 0) {
		*iptr = *wild;
	} else {
		/*
		 * Conver the string to an integer.
		 */
		*iptr = (uint64_t)strtoll(str, &str2, 0);
		/*
		 * If any characters didn't convert, it's an error.
		 */
		if (*str2 != '\0') {
			err_print("`%s' is not an integer.\n", str);
			return (-1);
		}
	}
	return (0);
}

/*
 * This routine converts the given string into a block number on the
 * current disk.  The format of a block number is either a self-based
 * number, or a series of self-based numbers separated by slashes.
 * Any number preceeding the first slash is considered a cylinder value.
 * Any number succeeding the first slash but preceeding the second is
 * considered a head value.  Any number succeeding the second slash is
 * considered a sector value.  Any of these numbers can be wildcarded
 * to the highest possible legal value.
 */
static int
getbn(char *str, diskaddr_t *iptr)
{
	char	*cptr, *hptr, *sptr;
	int	cyl, head, sect;
	int	wild;
	diskaddr_t	wild64;
	TOKEN	buf;

	/*
	 * Set cylinder pointer to beginning of string.
	 */
	cptr = str;
	/*
	 * Look for the first slash.
	 */
	while ((*str != '\0') && (*str != '/'))
		str++;
	/*
	 * If there wasn't one, convert string to an integer and return it.
	 */
	if (*str == '\0') {
		wild64 = physsects() - 1;
		if (geti64(cptr, iptr, &wild64))
			return (-1);
		return (0);
	}
	/*
	 * Null out the slash and set head pointer just beyond it.
	 */
	*str++ = '\0';
	hptr = str;
	/*
	 * Look for the second slash.
	 */
	while ((*str != '\0') && (*str != '/'))
		str++;
	/*
	 * If there wasn't one, sector pointer points to a .
	 */
	if (*str == '\0')
		sptr = str;
	/*
	 * If there was, null it out and set sector point just beyond it.
	 */
	else {
		*str++ = '\0';
		sptr = str;
	}
	/*
	 * Convert the cylinder part to an integer and store it.
	 */
	clean_token(buf, cptr);
	wild = ncyl + acyl - 1;
	if (geti(buf, &cyl, &wild))
		return (-1);
	if ((cyl < 0) || (cyl >= (ncyl + acyl))) {
		err_print("`%d' is out of range [0-%u].\n", cyl,
		    ncyl + acyl - 1);
		return (-1);
	}
	/*
	 * Convert the head part to an integer and store it.
	 */
	clean_token(buf, hptr);
	wild = nhead - 1;
	if (geti(buf, &head, &wild))
		return (-1);
	if ((head < 0) || (head >= nhead)) {
		err_print("`%d' is out of range [0-%u].\n", head, nhead - 1);
		return (-1);
	}
	/*
	 * Convert the sector part to an integer and store it.
	 */
	clean_token(buf, sptr);
	wild = sectors(head) - 1;
	if (geti(buf, &sect, &wild))
		return (-1);
	if ((sect < 0) || (sect >= sectors(head))) {
		err_print("`%d' is out of range [0-%u].\n", sect,
		    sectors(head) - 1);
		return (-1);
	}
	/*
	 * Combine the pieces into a block number and return it.
	 */
	*iptr = chs2bn(cyl, head, sect);
	return (0);
}

/*
 * This routine is the basis for all input into the program.  It
 * understands the semantics of a set of input types, and provides
 * consistent error messages for all input.  It allows for default
 * values and prompt strings.
 */
uint64_t
input(int type, char *promptstr, int delim, u_ioparam_t *param, int *deflt,
    int cmdflag)
{
	int		interactive, help, i, length, index, tied;
	blkaddr_t	bn;
	diskaddr_t	bn64;
	char		**str, **strings;
	TOKEN		token, cleantoken;
	TOKEN		token2, cleantoken2;
	char		*arg;
	struct		bounds *bounds;
	char		*s;
	int		value;
	int		cyls, cylno;
	uint64_t	blokno;
	float		nmegs;
	float		ngigs;
	char		shell_argv[MAXPATHLEN];
	part_deflt_t	*part_deflt;
	efi_deflt_t	*efi_deflt;

	/*
	 * Optional integer input has been added as a hack.
	 * Function result is 1 if user typed anything.
	 * Whatever they typed is returned in *deflt.
	 * This permits us to distinguish between "no value",
	 * and actually entering in some value, for instance.
	 */
	if (type == FIO_OPINT) {
		assert(deflt != NULL);
	}
reprompt:
	help = interactive = 0;
	/*
	 * If we are inputting a command, flush any current input in the pipe.
	 */
	if (cmdflag == CMD_INPUT)
		flushline();
	/*
	 * Note whether the token is already present.
	 */
	if (!token_present)
		interactive = 1;
	/*
	 * Print the prompt.
	 */
	fmt_print(promptstr);
	/*
	 * If there is a default value, print it in a format appropriate
	 * for the input type.
	 */
	if (deflt != NULL) {
		switch (type) {
		case FIO_BN:
#if !defined(lint)	/* caller has aligned the pointer specifying FIO_BN */
			fmt_print("[%llu, ", *(diskaddr_t *)deflt);
			pr_dblock(fmt_print, *(diskaddr_t *)deflt);
			fmt_print("]");
#endif
			break;
		case FIO_INT:
			fmt_print("[%d]", *deflt);
			break;
		case FIO_INT64:
#if defined(lint)
			/* caller is longlong aligned specifying FIO_INT64 */
			efi_deflt = NULL;
#else
			efi_deflt = (efi_deflt_t *)deflt;
#endif
			fmt_print("[%llu]", efi_deflt->start_sector);
			break;
		case FIO_CSTR:
		case FIO_MSTR:
			strings = (char **)param->io_charlist;
			for (i = 0, str = strings; i < *deflt; i++, str++)
				;
			fmt_print("[%s]", *str);
			break;
		case FIO_OSTR:
			fmt_print("[\"%s\"]", (char *)deflt);
			break;
		case FIO_SLIST:
			/*
			 * Search for a string matching the default
			 * value.  If found, use it.  Otherwise
			 * assume the default value is actually
			 * an illegal choice, and default to
			 * the first item in the list.
			 */
			s = find_string(param->io_slist, *deflt);
			if (s == NULL) {
				s = (param->io_slist)->str;
			}
			fmt_print("[%s]", s);
			break;
		case FIO_CYL:
			/*
			 * Old-style partition size input, used to
			 * modify complete partition tables
			 */
			blokno = *(blkaddr32_t *)deflt;
			fmt_print("[%llub, %uc, %1.2fmb, %1.2fgb]", blokno,
			    bn2c(blokno), bn2mb(blokno), bn2gb(blokno));
			break;
		case FIO_ECYL:
			/*
			 * set up pointer to partition defaults
			 * structure
			 */
			part_deflt = (part_deflt_t *)deflt;

			/*
			 * Build print format specifier.  We use the
			 * starting cylinder number which was entered
			 * before this call to input(), in case the
			 * user has changed it from the value in the
			 * cur_parts->pinfo_map[].dkl_cylno
			 * field for the current parition
			 */

			/*
			 * Determine the proper default end cylinder:
			 * Start Cyl	Default Size	End Cylinder
			 *	0		0	0
			 *	>0		0	Start Cyl
			 *	0		>0	Default Size
			 *				(Cyls) - 1
			 *	>0		>0	(Start +
			 *				Default Size
			 *				(Cyls)) -1
			 */

			if (part_deflt->deflt_size == 0) {
				cylno = part_deflt->start_cyl;
			} else if (part_deflt->start_cyl == 0) {
				cylno = bn2c(part_deflt->deflt_size) - 1;
			} else {
				cylno = (bn2c(part_deflt->deflt_size) +
				    part_deflt->start_cyl) - 1;
			}

			fmt_print("[%ub, %uc, %de, %1.2fmb, %1.2fgb]",
			    part_deflt->deflt_size,
			    bn2c(part_deflt->deflt_size),
			    cylno,
			    bn2mb(part_deflt->deflt_size),
			    bn2gb(part_deflt->deflt_size));

			break;
		case FIO_EFI:
#if defined(lint)
			/* caller is longlong aligned when specifying FIO_EFI */
			efi_deflt = NULL;
#else
			efi_deflt = (efi_deflt_t *)deflt;
#endif

			fmt_print("[%llub, %llue, %llumb, %llugb, %llutb]",
			    efi_deflt->end_sector,
			    efi_deflt->start_sector + efi_deflt->end_sector - 1,
			    (efi_deflt->end_sector * cur_blksz) /
			    (1024 * 1024),
			    (efi_deflt->end_sector * cur_blksz) /
			    (1024 * 1024 * 1024),
			    (efi_deflt->end_sector * cur_blksz) /
			    ((uint64_t)1024 * 1024 * 1024 * 1024));
			break;
		case FIO_OPINT:
			/* no default value for optional input type */
			fmt_print("[default]");
			break;
		default:
			err_print("Error: unknown input type.\n");
			fullabort();
		}
	}
	/*
	 * Print the delimiter character.
	 */
	fmt_print("%c ", delim);
	/*
	 * Get the token.  If we hit eof, exit the program gracefully.
	 */
	if (gettoken(token) == NULL)
		fullabort();

	/*
	 * check if the user has issued (!) , escape to shell
	 */
	if ((cmdflag == CMD_INPUT) && (token[0] == '!')) {

	    /* get the list of arguments to shell command */
		(void) memset(shell_argv, 0, sizeof (shell_argv));

		/* initialize to the first token... */
		arg = &token[1];

		/*
		 * ... and then collect all tokens until the end of
		 * the line as arguments
		 */
		do {
			/* skip empty tokens. */
			if (*arg == '\0')
				continue;
			/*
			 * If either of the following two strlcat()
			 * operations overflows, report an error and
			 * exit gracefully.
			 */
			if ((strlcat(shell_argv, arg, sizeof (shell_argv)) >=
			    sizeof (shell_argv)) ||
			    (strlcat(shell_argv, " ", sizeof (shell_argv)) >=
			    sizeof (shell_argv))) {
				err_print("Error: Command line too long.\n");
				fullabort();
			}
		} while (token_present && (arg = gettoken(token)) != NULL);

		/* execute the shell command */
		(void) execute_shell(shell_argv, sizeof (shell_argv));
		redisplay_menu_list((char **)param->io_charlist);
		if (interactive) {
			goto reprompt;
		}
	}

	/*
	 * Certain commands accept up to two tokens
	 * Unfortunately, this is kind of a hack.
	 */
	token2[0] = 0;
	cleantoken2[0] = 0;
	if (type == FIO_CYL || type == FIO_ECYL) {
		if (token_present) {
			if (gettoken(token2) == NULL)
				fullabort();
			clean_token(cleantoken2, token2);
		}
	}
	/*
	 * Echo the token back to the user if it was in the pipe or we
	 * are running out of a command file.
	 */
	if (!interactive || option_f) {
		if (token2[0] == 0) {
			fmt_print("%s\n", token);
		} else {
			fmt_print("%s %s\n", token, token2);
		}
	}
	/*
	 * If we are logging, echo the token to the log file.  The else
	 * is necessary here because the above printf will also put the
	 * token in the log file.
	 */
	else if (log_file) {
		log_print("%s %s\n", token, token2);
	}
	/*
	 * If the token was not in the pipe and it wasn't a command, flush
	 * the rest of the line to keep things in sync.
	 */
	if (interactive && cmdflag != CMD_INPUT)
		flushline();
	/*
	 * Scrub off the white-space.
	 */
	clean_token(cleantoken, token);
	/*
	 * If the input was a blank line and we weren't prompting
	 * specifically for a blank line...
	 */
	if ((strcmp(cleantoken, "") == 0) && (type != FIO_BLNK)) {
		/*
		 * If there's a default, return it.
		 */
		if (deflt != NULL) {
			if (type == FIO_OSTR) {
				/*
				 * Duplicate and return the default string
				 */
				return ((int)alloc_string((char *)deflt));
			} else if (type == FIO_SLIST) {
				/*
				 * If we can find a match for the default
				 * value in the list, return the default
				 * value.  If there's no match for the
				 * default value, it's an illegal
				 * choice.  Return the first value in
				 * the list.
				 */
				s = find_string(param->io_slist, *deflt);
				if ((cur_label == L_TYPE_EFI) &&
				    (s == NULL)) {
					return (*deflt);
				}
				if (s == NULL) {
					return ((param->io_slist)->value);
				} else {
					return (*deflt);
				}
			} else if (type == FIO_OPINT) {
				/*
				 * The user didn't enter anything
				 */
				return (0);
			} else if (type == FIO_ECYL) {
				return (part_deflt->deflt_size);
			} else if (type == FIO_INT64) {
				return (efi_deflt->start_sector);
			} else if (type == FIO_EFI) {
				return (efi_deflt->end_sector);
			} else {
				return (*deflt);
			}
		}
		/*
		 * If the blank was not in the pipe, just reprompt.
		 */
		if (interactive) {
			goto reprompt;
		}
		/*
		 * If the blank was in the pipe, it's an error.
		 */
		err_print("No default for this entry.\n");
		cmdabort(SIGINT);
	}
	/*
	 * If token is a '?' or a 'h', it is a request for help.
	 */
	if ((strcmp(cleantoken, "?") == 0) ||
	    (strcmp(cleantoken, "h") == 0) ||
	    (strcmp(cleantoken, "help") == 0)) {
		help = 1;
	}
	/*
	 * Switch on the type of input expected.
	 */
	switch (type) {
	/*
	 * Expecting a disk block number.
	 */
	case FIO_BN:
		/*
		 * Parameter is the bounds of legal block numbers.
		 */
		bounds = (struct bounds *)&param->io_bounds;
		/*
		 * Print help message if required.
		 */
		if (help) {
			fmt_print("Expecting a block number from %llu (",
			    bounds->lower);
			pr_dblock(fmt_print, bounds->lower);
			fmt_print(") to %llu (", bounds->upper);
			pr_dblock(fmt_print, bounds->upper);
			fmt_print(")\n");
			break;
		}
		/*
		 * Convert token to a disk block number.
		 */
		if (cur_label == L_TYPE_EFI) {
			if (geti64(cleantoken, (uint64_t *)&bn64, NULL))
				break;
		} else {
			if (getbn(cleantoken, &bn64))
				break;
		}
		/*
		 * Check to be sure it is within the legal bounds.
		 */
		if ((bn64 < bounds->lower) || (bn64 > bounds->upper)) {
			err_print("`");
			pr_dblock(err_print, bn64);
			err_print("' is out of range [%llu-%llu].\n",
			    bounds->lower, bounds->upper);
			break;
		}
		/*
		 * It's ok, return it.
		 */
		return (bn64);
	/*
	 * Expecting an integer.
	 */
	case FIO_INT:
		/*
		 * Parameter is the bounds of legal integers.
		 */
		bounds = (struct bounds *)&param->io_bounds;
		/*
		 * Print help message if required.
		 */
		if (help) {
			fmt_print("Expecting an integer from %llu",
			    bounds->lower);
			fmt_print(" to %llu\n", bounds->upper);
			break;
		}
		/*
		 * Convert the token into an integer.
		 */
		if (geti(cleantoken, (int *)&bn, NULL))
			break;
		/*
		 * Check to be sure it is within the legal bounds.
		 */
		if ((bn < bounds->lower) || (bn > bounds->upper)) {
			err_print("`%lu' is out of range [%llu-%llu].\n", bn,
			    bounds->lower, bounds->upper);
			break;
		}
		/*
		 * If it's ok, return it.
		 */
		return (bn);
	case FIO_INT64:
		/*
		 * Parameter is the bounds of legal integers.
		 */
		bounds = (struct bounds *)&param->io_bounds;
		/*
		 * Print help message if required.
		 */
		if (help) {
			fmt_print("Expecting an integer from %llu",
			    bounds->lower);
			fmt_print(" to %llu\n", bounds->upper);
			break;
		}
		/*
		 * Convert the token into an integer.
		 */
		if (geti64(cleantoken, (uint64_t *)&bn64, NULL)) {
			break;
		}
		/*
		 * Check to be sure it is within the legal bounds.
		 */
		if ((bn64 < bounds->lower) || (bn64 > bounds->upper)) {
			err_print("`%llu' is out of range [%llu-%llu].\n",
			    bn64, bounds->lower, bounds->upper);
			break;
		}
		/*
		 * If it's ok, return it.
		 */
		return (bn64);
	/*
	 * Expecting an integer, or no input.
	 */
	case FIO_OPINT:
		/*
		 * Parameter is the bounds of legal integers.
		 */
		bounds = (struct bounds *)&param->io_bounds;
		/*
		 * Print help message if required.
		 */
		if (help) {
			fmt_print("Expecting an integer from %llu",
			    bounds->lower);
			fmt_print(" to %llu, or no input\n", bounds->upper);
			break;
		}
		/*
		 * Convert the token into an integer.
		 */
		if (geti(cleantoken, (int *)&bn, NULL))
			break;
		/*
		 * Check to be sure it is within the legal bounds.
		 */
		if ((bn < bounds->lower) || (bn > bounds->upper)) {
			err_print("`%lu' is out of range [%llu-%llu].\n", bn,
			    bounds->lower, bounds->upper);
			break;
		}
		/*
		 * For optional case, return 1 indicating that
		 * the user actually did enter something.
		 */
		if (!deflt)
			*deflt = bn;
		return (1);
	/*
	 * Expecting a closed string.  This means that the input
	 * string must exactly match one of the strings passed in
	 * as the parameter.
	 */
	case FIO_CSTR:
		/*
		 * The parameter is a null terminated array of character
		 * pointers, each one pointing to a legal input string.
		 */
		strings = (char **)param->io_charlist;
		/*
		 * Walk through the legal strings, seeing if any of them
		 * match the token.  If a match is made, return the index
		 * of the string that was matched.
		 */
		for (str = strings; *str != NULL; str++)
			if (strcmp(cleantoken, *str) == 0)
				return (str - strings);
		/*
		 * Print help message if required.
		 */
		if (help) {
			print_input_choices(type, param);
		} else {
			err_print("`%s' is not expected.\n", cleantoken);
		}
		break;
	/*
	 * Expecting a matched string.  This means that the input
	 * string must either match one of the strings passed in,
	 * or be a unique abbreviation of one of them.
	 */
	case FIO_MSTR:
		/*
		 * The parameter is a null terminated array of character
		 * pointers, each one pointing to a legal input string.
		 */
		strings = (char **)param->io_charlist;
		length = index = tied = 0;
		/*
		 * Loop through the legal input strings.
		 */
		for (str = strings; *str != NULL; str++) {
			/*
			 * See how many characters of the token match
			 * this legal string.
			 */
			i = strcnt(cleantoken, *str);
			/*
			 * If it's not the whole token, then it's not a match.
			 */
			if ((uint_t)i < strlen(cleantoken))
				continue;
			/*
			 * If it ties with another input, remember that.
			 */
			if (i == length)
				tied = 1;
			/*
			 * If it matches the most so far, record that.
			 */
			if (i > length) {
				index = str - strings;
				tied = 0;
				length = i;
			}
		}
		/*
		 * Print help message if required.
		 */
		if (length == 0) {
			if (help) {
				print_input_choices(type, param);
			} else {
				err_print("`%s' is not expected.\n",
				    cleantoken);
			}
			break;
		}
		/*
		 * If the abbreviation was non-unique, it's an error.
		 */
		if (tied) {
			err_print("`%s' is ambiguous.\n", cleantoken);
			break;
		}
		/*
		 * We matched one.  Return the index of the string we matched.
		 */
		return (index);
	/*
	 * Expecting an open string.  This means that any string is legal.
	 */
	case FIO_OSTR:
		/*
		 * Print a help message if required.
		 */
		if (help) {
			fmt_print("Expecting a string\n");
			break;
		}
		/*
		 * alloc a copy of the string and return it
		 */
		return ((int)alloc_string(token));

	/*
	 * Expecting a blank line.
	 */
	case FIO_BLNK:
		/*
		 * We are always in non-echo mode when we are inputting
		 * this type.  We echo the newline as a carriage return
		 * only so the prompt string will be covered over.
		 */
		nolog_print("\015");
		/*
		 * If we are logging, send a newline to the log file.
		 */
		if (log_file)
			log_print("\n");
		/*
		 * There is no value returned for this type.
		 */
		return (0);

	/*
	 * Expecting one of the entries in a string list.
	 * Accept unique abbreviations.
	 * Return the value associated with the matched string.
	 */
	case FIO_SLIST:
		i = find_value((slist_t *)param->io_slist, cleantoken, &value);
		if (i == 1) {
			return (value);
		} else {
			/*
			 * Print help message if required.
			 */

			if (help) {
				print_input_choices(type, param);
			} else {
				if (i == 0)
					err_print("`%s' not expected.\n",
					    cleantoken);
				else
					err_print("`%s' is ambiguous.\n",
					    cleantoken);
			}
		}
		break;

	/*
	 * Cylinder size input when modifying a complete partition map
	 */
	case FIO_CYL:
		/*
		 * Parameter is the bounds of legal block numbers.
		 */
		bounds = (struct bounds *)&param->io_bounds;
		assert(bounds->lower == 0);
		/*
		 * Print help message if required.
		 */
		if (help) {
			fmt_print("Expecting up to %llu blocks,",
			    bounds->upper);
			fmt_print(" %u cylinders, ", bn2c(bounds->upper));
			fmt_print(" %1.2f megabytes, ", bn2mb(bounds->upper));
			fmt_print("or %1.2f gigabytes\n", bn2gb(bounds->upper));
			break;
		}
		/*
		 * Parse the first token: try to find 'b', 'c' or 'm'
		 */
		s = cleantoken;
		while (*s && (isdigit(*s) || (*s == '.') || (*s == '$'))) {
			s++;
		}
		/*
		 * If we found a conversion specifier, second token is unused
		 * Otherwise, the second token should supply it.
		 */
		if (*s != 0) {
			value = *s;
			*s = 0;
		} else {
			value = cleantoken2[0];
		}
		/*
		 * If the token is the wild card, simply supply the max
		 * This order allows the user to specify the maximum in
		 * either blocks/cyls/megabytes - a convenient fiction.
		 */
		if (strcmp(cleantoken, WILD_STRING) == 0) {
			return (bounds->upper);
		}
		/*
		 * Allow the user to specify zero with no units,
		 * by just defaulting to cylinders.
		 */
		if (strcmp(cleantoken, "0") == 0) {
			value = 'c';
		}
		/*
		 * If there's a decimal point, but no unit specification,
		 * let's assume megabytes.
		 */
		if ((value == 0) && (strchr(cleantoken, '.') != NULL)) {
			value = 'm';
		}
		/*
		 * Handle each unit type we support
		 */
		switch (value) {
		case 'b':
			/*
			 * Convert token to a disk block number.
			 */
			if (geti64(cleantoken, &bn64, &bounds->upper))
				break;
			/*
			 * Check to be sure it is within the legal bounds.
			 */
			if ((bn64 < bounds->lower) || (bn64 > bounds->upper)) {
				err_print(
				    "`%llub' is out of the range %llu "
				    "to %llu\n",
				    bn64, bounds->lower, bounds->upper);
				break;
			}
			/*
			 * Verify the block lies on a cylinder boundary
			 */
			if ((bn64 % spc()) != 0) {
				err_print(
				    "partition size must be a multiple of "
				    "%u blocks to lie on a cylinder boundary\n",
				    spc());
				err_print(
				    "%llu blocks is approximately %u cylinders,"
				    " %1.2f megabytes or %1.2f gigabytes\n",
				    bn64, bn2c(bn64), bn2mb(bn64), bn2gb(bn64));
				break;
			}
			return (bn64);
		case 'c':
			/*
			 * Convert token from a number of cylinders to
			 * a number of blocks.
			 */
			i = bn2c(bounds->upper);
			if (geti(cleantoken, &cyls, &i))
				break;
			/*
			 * Check the bounds - cyls is number of cylinders
			 */
			if (cyls > (bounds->upper / spc())) {
				err_print("`%dc' is out of range [0-%llu]\n",
				    cyls, bounds->upper / spc());
				break;
			}
			/*
			 * Convert cylinders to blocks and return
			 */
			return (cyls * spc());
		case 'm':
			/*
			 * Convert token from megabytes to a block number.
			 */
			if (sscanf(cleantoken, "%f2", &nmegs) != 1) {
				err_print("`%s' is not recognized\n",
				    cleantoken);
				break;
			}
			/*
			 * Check the bounds
			 */
			if (nmegs > bn2mb(bounds->upper)) {
				err_print("`%1.2fmb' is out of range "
				    "[0-%1.2f]\n", nmegs, bn2mb(bounds->upper));
				break;
			}
			/*
			 * Convert to blocks
			 */
			bn64 = mb2bn(nmegs);
			/*
			 * Round value up to nearest cylinder
			 */
			i = spc();
			bn64 = ((bn64 + (i-1)) / i) * i;
			return (bn64);
		case 'g':
			/*
			 * Convert token from gigabytes to a block number.
			 */
			if (sscanf(cleantoken, "%f2", &ngigs) != 1) {
				err_print("`%s' is not recognized\n",
				    cleantoken);
				break;
			}
			/*
			 * Check the bounds
			 */
			if (ngigs > bn2gb(bounds->upper)) {
				err_print("`%1.2fgb' is out of range "
				    "[0-%1.2f]\n", ngigs, bn2gb(bounds->upper));
				break;
			}
			/*
			 * Convert to blocks
			 */
			bn64 = gb2bn(ngigs);
			/*
			 * Round value up to nearest cylinder
			 */
			i = spc();
			bn64 = ((bn64 + (i-1)) / i) * i;
			return (bn64);
		default:
			err_print(
"Please specify units in either b(blocks), c(cylinders), m(megabytes) \
or g(gigabytes)\n");
			break;
		}
		break;

	case FIO_ECYL:
		/*
		 * Parameter is the bounds of legal block numbers.
		 */
		bounds = (struct bounds *)&param->io_bounds;
		assert(bounds->lower == 0);

		/*
		 * Print help message if required.
		 */
		if (help) {
			fmt_print("Expecting up to %llu blocks,",
			    bounds->upper);
			fmt_print(" %u cylinders, ",
			    bn2c(bounds->upper));
			fmt_print(" %u end cylinder, ",
			    (uint_t)(bounds->upper / spc()));
			fmt_print(" %1.2f megabytes, ",
			    bn2mb(bounds->upper));
			fmt_print("or %1.2f gigabytes\n",
			    bn2gb(bounds->upper));
			break;
		}

		/*
		 * Parse the first token: try to find 'b', 'c', 'e'
		 * or 'm'
		 */
		s = cleantoken;
		while (*s && (isdigit(*s) || (*s == '.') || (*s == '$'))) {
			s++;
		}

		/*
		 * If we found a conversion specifier, second token is
		 * unused Otherwise, the second token should supply it.
		 */
		if (*s != 0) {
			value = *s;
			*s = 0;
		} else {
			value = cleantoken2[0];
		}

		/*
		 * If the token is the wild card, simply supply the max
		 * This order allows the user to specify the maximum in
		 * either blocks/cyls/megabytes - a convenient fiction.
		 */
		if (strcmp(cleantoken, WILD_STRING) == 0) {
			return (bounds->upper);
		}

		/*
		 * Allow the user to specify zero with no units,
		 * by just defaulting to cylinders.
		 */

		if (value != 'e' && strcmp(cleantoken, "0") == 0) {
			value = 'c';
		}


		/*
		 * If there's a decimal point, but no unit
		 * specification, let's assume megabytes.
		 */
		if ((value == 0) && (strchr(cleantoken, '.') != NULL)) {
			value = 'm';
		}

		/*
		 * Handle each unit type we support
		 */
		switch (value) {
		case 'b':
			/*
			 * Convert token to a disk block number.
			 */
			if (geti64(cleantoken, &bn64, &bounds->upper))
				break;
			/*
			 * Check to be sure it is within the
			 * legal bounds.
			 */
			if ((bn64 < bounds->lower) || (bn64 > bounds->upper)) {
				err_print(
"`%llub' is out of the range %llu to %llu\n",
				    bn64, bounds->lower, bounds->upper);
				break;
			}

			/*
			 * Verify the block lies on a cylinder
			 * boundary
			 */
			if ((bn64 % spc()) != 0) {
				err_print(
				    "partition size must be a multiple of %u "
				    "blocks to lie on a cylinder boundary\n",
				    spc());
				err_print(
				    "%llu blocks is approximately %u cylinders,"
				    " %1.2f megabytes or %1.2f gigabytes\n",
				    bn64, bn2c(bn64), bn2mb(bn64), bn2gb(bn64));
				break;
			}

			return (bn64);

		case 'e':
			/*
			 * Token is ending cylinder
			 */

			/* convert token to integer */
			if (geti(cleantoken, &cylno, NULL)) {
				break;
			}

			/*
			 * check that input cylno isn't before the current
			 * starting cylinder number.  Note that we are NOT
			 * using the starting cylinder from
			 * cur_parts->pinfo_map[].dkl_cylno!
			 */
			if (cylno < part_deflt->start_cyl) {
				err_print(
"End cylinder must fall on or after start cylinder %u\n",
				    part_deflt->start_cyl);
				break;
			}

			/*
			 * calculate cylinder number of upper boundary, and
			 * verify that our input is within range
			 */
			i = (bn2c(bounds->upper) + part_deflt->start_cyl - 1);

			if (cylno > i) {
				err_print(
"End cylinder %d is beyond max cylinder %d\n",
				    cylno, i);
				break;
			}

			/*
			 * calculate number of cylinders based on input
			 */
			cyls = ((cylno - part_deflt->start_cyl) + 1);

			return (cyls * spc());

		case 'c':
			/*
			 * Convert token from a number of
			 * cylinders to a number of blocks.
			 */
			i = bn2c(bounds->upper);
			if (geti(cleantoken, &cyls, &i))
				break;

			/*
			 * Check the bounds - cyls is number of
			 * cylinders
			 */
			if (cyls > (bounds->upper / spc())) {
				err_print("`%dc' is out of range [0-%llu]\n",
				    cyls, bounds->upper / spc());
				break;
			}

			/*
			 * Convert cylinders to blocks and
			 * return
			 */
			return (cyls * spc());

		case 'm':
			/*
			 * Convert token from megabytes to a
			 * block number.
			 */
			if (sscanf(cleantoken, "%f2", &nmegs) != 1) {
				err_print("`%s' is not recognized\n",
				    cleantoken);
				break;
			}

			/*
			 * Check the bounds
			 */
			if (nmegs > bn2mb(bounds->upper)) {
				err_print("`%1.2fmb' is out of range "
				    "[0-%1.2f]\n", nmegs, bn2mb(bounds->upper));
				break;
			}

			/*
			 * Convert to blocks
			 */
			bn64 = mb2bn(nmegs);

			/*
			 * Round value up to nearest cylinder
			 */
			i = spc();
			bn64 = ((bn64 + (i-1)) / i) * i;
			return (bn64);

		case 'g':
			/*
			 * Convert token from gigabytes to a
			 * block number.
			 */
			if (sscanf(cleantoken, "%f2", &ngigs) != 1) {
				err_print("`%s' is not recognized\n",
				    cleantoken);
				break;
			}

			/*
			 * Check the bounds
			 */
			if (ngigs > bn2gb(bounds->upper)) {
				err_print("`%1.2fgb' is out of range "
				    "[0-%1.2f]\n", ngigs, bn2gb(bounds->upper));
				break;
			}

			/*
			 * Convert to blocks
			 */
			bn64 = gb2bn(ngigs);

			/*
			 * Round value up to nearest cylinder
			 */
			i = spc();
			bn64 = ((bn64 + (i-1)) / i) * i;
			return (bn64);

		default:
			err_print(
"Please specify units in either b(blocks), c(cylinders), e(end cylinder),\n");
			err_print("m(megabytes) or g(gigabytes)\n");
			break;
		}
		break;
	case FIO_EFI:
		/*
		 * Parameter is the bounds of legal block numbers.
		 */
		bounds = (struct bounds *)&param->io_bounds;

		/*
		 * Print help message if required.
		 */
		if (help) {
			fmt_print("Expecting up to %llu sectors,",
			    cur_parts->etoc->efi_last_u_lba);
			fmt_print("or %llu megabytes,",
			    (cur_parts->etoc->efi_last_u_lba * cur_blksz) /
			    (1024 * 1024));
			fmt_print("or %llu gigabytes\n",
			    (cur_parts->etoc->efi_last_u_lba * cur_blksz) /
			    (1024 * 1024 * 1024));
			fmt_print("or %llu terabytes\n",
			    (cur_parts->etoc->efi_last_u_lba * cur_blksz) /
			    ((uint64_t)1024 * 1024 * 1024 * 1024));
			break;
		}

		/*
		 * Parse the first token: try to find 'b', 'c', 'e'
		 * or 'm'
		 */
		s = cleantoken;
		while (*s && (isdigit(*s) || (*s == '.') || (*s == '$'))) {
			s++;
		}

		/*
		 * If we found a conversion specifier, second token is
		 * unused Otherwise, the second token should supply it.
		 */
		if (*s != 0) {
			value = *s;
			*s = 0;
		} else {
			value = cleantoken2[0];
		}

		/*
		 * If the token is the wild card, simply supply the max
		 * This order allows the user to specify the maximum in
		 * either blocks/cyls/megabytes - a convenient fiction.
		 */
		if (strcmp(cleantoken, WILD_STRING) == 0) {
			uint64_t reserved;

			reserved = efi_reserved_sectors(cur_parts->etoc);
			return (bounds->upper - reserved -
			    efi_deflt->start_sector + 1);
		}

		/*
		 * Allow the user to specify zero with no units,
		 * by just defaulting to sectors.
		 */

		if (value != 'e' && strcmp(cleantoken, "0") == 0) {
			value = 'm';
		}


		/*
		 * If there's a decimal point, but no unit
		 * specification, let's assume megabytes.
		 */
		if ((value == 0) && (strchr(cleantoken, '.') != NULL)) {
			value = 'm';
		}

		/*
		 * Handle each unit type we support
		 */
		switch (value) {
		case 'b':
			/*
			 * Token is number of blocks
			 */
			if (geti64(cleantoken, &blokno, NULL)) {
				break;
			}
			if (blokno > bounds->upper) {
				err_print("Number of blocks must be less that "
				    "the total available blocks.\n");
				break;
			}
			return (blokno);

		case 'e':
			/*
			 * Token is ending block number
			 */

			/* convert token to integer */
			if (geti64(cleantoken, &blokno, NULL)) {
				break;
			}

			/*
			 * Some sanity check
			 */
			if (blokno < efi_deflt->start_sector) {
				err_print("End Sector must fall on or after "
				    "start sector %llu\n",
				    efi_deflt->start_sector);
				break;
			}

			/*
			 * verify that our input is within range
			 */
			if (blokno > cur_parts->etoc->efi_last_u_lba) {
				err_print("End Sector %llu is beyond max "
				    "Sector %llu\n",
				    blokno, cur_parts->etoc->efi_last_u_lba);
				break;
			}

			/*
			 * calculate number of blocks based on input
			 */

			return (blokno - efi_deflt->start_sector + 1);

		case 'm':
			/*
			 * Convert token from megabytes to a
			 * block number.
			 */
			if (sscanf(cleantoken, "%f2", &nmegs) != 1) {
				err_print("`%s' is not recognized\n",
				    cleantoken);
				break;
			}

			/*
			 * Check the bounds
			 */
			if (nmegs > bn2mb(bounds->upper - bounds->lower)) {
				err_print("`%1.2fmb' is out of range "
				    "[0-%1.2f]\n", nmegs,
				    bn2mb(bounds->upper - bounds->lower));
				break;
			}

			return (mb2bn(nmegs));

		case 'g':
			if (sscanf(cleantoken, "%f2", &nmegs) != 1) {
				err_print("`%s' is not recognized\n",
				    cleantoken);
				break;
			}
			if (nmegs > bn2gb(bounds->upper - bounds->lower)) {
				err_print("`%1.2fgb' is out of range "
				    "[0-%1.2f]\n", nmegs,
				    bn2gb(bounds->upper - bounds->lower));
				break;
			}

			return (gb2bn(nmegs));

		case 't':
			if (sscanf(cleantoken, "%f2", &nmegs) != 1) {
				err_print("`%s' is not recognized\n",
				    cleantoken);
				break;
			}
			if (nmegs > bn2tb(bounds->upper - bounds->lower)) {
				err_print("`%1.2ftb' is out of range "
				    "[0-%1.2f]\n", nmegs,
				    bn2tb(bounds->upper - bounds->lower));
				break;
			}
			return (uint64_t)((float)nmegs * 1024.0 *
			    1024.0 * 1024.0 * 1024.0 / cur_blksz);

		default:
			err_print("Please specify units in either "
			    "b(number of blocks), e(end sector),\n");
			err_print(" g(gigabytes), m(megabytes)");
			err_print(" or t(terabytes)\n");
			break;
		}
		break;

	/*
	 * If we don't recognize the input type, it's bad news.
	 */
	default:
		err_print("Error: unknown input type.\n");
		fullabort();
	}
	/*
	 * If we get here, it's because some error kept us from accepting
	 * the token.  If we are running out of a command file, gracefully
	 * leave the program.  If we are interacting with the user, simply
	 * reprompt.  If the token was in the pipe, abort the current command.
	 */
	if (option_f)
		fullabort();
	else if (interactive)
		goto reprompt;
	else
		cmdabort(SIGINT);
	/*
	 * Never actually reached.
	 */
	return (-1);
}

/*
 * Print input choices
 */
static void
print_input_choices(int type, u_ioparam_t *param)
{
	char		**sp;
	slist_t		*lp;
	int		width;
	int		col;
	int		ncols;

	switch (type) {
	case FIO_CSTR:
		fmt_print("Expecting one of the following:\n");
		goto common;

	case FIO_MSTR:
		fmt_print("Expecting one of the following: ");
		fmt_print("(abbreviations ok):\n");
common:
		for (sp = (char **)param->io_charlist; *sp != NULL; sp++) {
			fmt_print("\t%s\n", *sp);
		}
		break;

	case FIO_SLIST:
		fmt_print("Expecting one of the following: ");
		fmt_print("(abbreviations ok):\n");
		/*
		 * Figure out the width of the widest string
		 */
		width = slist_widest_str((slist_t *)param->io_slist);
		width += 4;
		/*
		 * If the help messages are empty, print the
		 * possible choices in left-justified columns
		 */
		lp = (slist_t *)param->io_slist;
		if (*lp->help == 0) {
			col = 0;
			ncols = 60 / width;
			for (; lp->str != NULL; lp++) {
				if (col == 0)
					fmt_print("\t");
				ljust_print(lp->str,
				    (++col == ncols) ? 0 : width);
				if (col == ncols) {
					col = 0;
					fmt_print("\n");
				}
			}
			if (col != 0)
				fmt_print("\n");
		} else {
			/*
			 * With help messages, print each choice,
			 * and help message, on its own line.
			 */
			for (; lp->str != NULL; lp++) {
				fmt_print("\t");
				ljust_print(lp->str, width);
				fmt_print("- %s\n", lp->help);
			}
		}
		break;

	default:
		err_print("Error: unknown input type.\n");
		fullabort();
	}

	fmt_print("\n");
}


/*
 * Search a string list for a particular string.
 * Use minimum recognition, to accept unique abbreviations
 * Return the number of possible matches found.
 * If only one match was found, return the arbitrary value
 * associated with the matched string in match_value.
 */
int
find_value(slist_t *slist, char *match_str, int *match_value)
{
	int		i;
	int		nmatches;
	int		length;
	int		match_length;

	nmatches = 0;
	length = 0;

	match_length = strlen(match_str);

	for (; slist->str != NULL; slist++) {
		/*
		 * See how many characters of the token match
		 */
		i = strcnt(match_str, slist->str);
		/*
		 * If it's not the whole token, then it's not a match.
		 */
		if (i  < match_length)
			continue;
		/*
		 * If it ties with another input, remember that.
		 */
		if (i == length)
			nmatches++;
		/*
		 * If it matches the most so far, record that.
		 */
		if (i > length) {
			*match_value = slist->value;
			nmatches = 1;
			length = i;
		}
	}

	return (nmatches);
}

/*
 * Search a string list for a particular value.
 * Return the string associated with that value.
 */
char *
find_string(slist_t *slist, int match_value)
{
	for (; slist->str != NULL; slist++) {
		if (slist->value == match_value) {
			return (slist->str);
		}
	}

	return (NULL);
}

/*
 * Return the width of the widest string in an slist
 */
static int
slist_widest_str(slist_t *slist)
{
	int	i;
	int	width;

	width = 0;
	for (; slist->str != NULL; slist++) {
		if ((i = strlen(slist->str)) > width)
			width = i;
	}

	return (width);
}

/*
 * Print a string left-justified to a fixed width.
 */
static void
ljust_print(char *str, int width)
{
	int	i;

	fmt_print("%s", str);
	for (i = width - strlen(str); i > 0; i--) {
		fmt_print(" ");
	}
}

/*
 * This routine is a modified version of printf.  It handles the cases
 * of silent mode and logging; other than that it is identical to the
 * library version.
 */
/*PRINTFLIKE1*/
void
fmt_print(char *format, ...)
{
	va_list ap;

	va_start(ap, format);

	/*
	 * If we are running silent, skip it.
	 */
	if (option_s == 0) {
		/*
		 * Do the print to standard out.
		 */
		if (need_newline) {
			(void) printf("\n");
		}
		(void) vprintf(format, ap);
		/*
		 * If we are logging, also print to the log file.
		 */
		if (log_file) {
			if (need_newline) {
				(void) fprintf(log_file, "\n");
			}
			(void) vfprintf(log_file, format, ap);
			(void) fflush(log_file);
		}
	}

	need_newline = 0;

	va_end(ap);
}

/*
 * This routine is a modified version of printf.  It handles the cases
 * of silent mode; other than that it is identical to the
 * library version.  It differs from the above printf in that it does
 * not print the message to a log file.
 */
/*PRINTFLIKE1*/
void
nolog_print(char *format, ...)
{
	va_list ap;

	va_start(ap, format);

	/*
	 * If we are running silent, skip it.
	 */
	if (option_s == 0) {
		/*
		 * Do the print to standard out.
		 */
		if (need_newline) {
			(void) printf("\n");
		}
		(void) vprintf(format, ap);
	}

	va_end(ap);

	need_newline = 0;
}

/*
 * This routine is a modified version of printf.  It handles the cases
 * of silent mode, and only prints the message to the log file, not
 * stdout.  Other than that is identical to the library version.
 */
/*PRINTFLIKE1*/
void
log_print(char *format, ...)
{
	va_list ap;

	va_start(ap, format);

	/*
	 * If we are running silent, skip it.
	 */
	if (option_s == 0) {
		/*
		 * Do the print to the log file.
		 */
		if (need_newline) {
			(void) fprintf(log_file, "\n");
		}
		(void) vfprintf(log_file, format, ap);
		(void) fflush(log_file);
	}

	va_end(ap);

	need_newline = 0;
}

/*
 * This routine is a modified version of printf.  It prints the message
 * to stderr, and to the log file is appropriate.
 * Other than that is identical to the library version.
 */
/*PRINTFLIKE1*/
void
err_print(char *format, ...)
{
	va_list ap;

	va_start(ap, format);

	/*
	 * Flush anything pending to stdout
	 */
	if (need_newline) {
		(void) printf("\n");
	}
	(void) fflush(stdout);
	/*
	 * Do the print to stderr.
	 */
	(void) vfprintf(stderr, format, ap);
	/*
	 * If we are logging, also print to the log file.
	 */
	if (log_file) {
		if (need_newline) {
			(void) fprintf(log_file, "\n");
		}
		(void) vfprintf(log_file, format, ap);
		(void) fflush(log_file);
	}
	va_end(ap);

	need_newline = 0;
}

/*
 * Print a number of characters from a buffer.  The buffer
 * does not need to be null-terminated.  Since the data
 * may be coming from a device, we cannot be sure the
 * data is not crud, so be rather defensive.
 */
void
print_buf(char *buf, int nbytes)
{
	int	c;

	while (nbytes-- > 0) {
		c = *buf++;
		if (isascii(c) && isprint(c)) {
			fmt_print("%c", c);
		} else
			break;
	}
}

#ifdef	not
/*
 * This routine prints out a message describing the given ctlr.
 * The message is identical to the one printed by the kernel during
 * booting.
 */
void
pr_ctlrline(struct ctlr_info *ctlr)
{

	fmt_print("           %s%d at %s 0x%x ",
	    ctlr->ctlr_cname, ctlr->ctlr_num,
	    space2str(ctlr->ctlr_space), ctlr->ctlr_addr);
	if (ctlr->ctlr_vec != 0)
		fmt_print("vec 0x%x ", ctlr->ctlr_vec);
	else
		fmt_print("pri %d ", ctlr->ctlr_prio);
	fmt_print("\n");
}
#endif /* not */

/*
 * This routine prints out a message describing the given disk.
 * The message is identical to the one printed by the kernel during
 * booting.
 */
void
pr_diskline(struct disk_info *disk, int	num)
{
	struct	ctlr_info *ctlr = disk->disk_ctlr;
	struct	disk_type *type = disk->disk_type;

	fmt_print("    %4d. %s ", num, disk->disk_name);
	if ((type != NULL) && (disk->label_type == L_TYPE_SOLARIS)) {
		fmt_print("<%s cyl %u alt %u hd %u sec %u>",
		    type->dtype_asciilabel, type->dtype_ncyl,
		    type->dtype_acyl, type->dtype_nhead,
		    type->dtype_nsect);
	} else if ((type != NULL) && (disk->label_type == L_TYPE_EFI)) {
		cur_blksz = disk->disk_lbasize;
		print_efi_string(type->vendor, type->product,
		    type->revision, type->capacity);
	} else if (disk->disk_flags & DSK_RESERVED) {
		fmt_print("<drive not available: reserved>");
	} else if (disk->disk_flags & DSK_UNAVAILABLE) {
		fmt_print("<drive not available>");
	} else {
		fmt_print("<drive type unknown>");
	}
	if (chk_volname(disk)) {
		fmt_print("  ");
		print_volname(disk);
	}
	fmt_print("\n");

	if (disk->devfs_name != NULL) {
		fmt_print("          %s\n", disk->devfs_name);
	} else {
		fmt_print("          %s%d at %s%d slave %d\n",
		    ctlr->ctlr_dname, disk->disk_dkinfo.dki_unit,
		    ctlr->ctlr_cname, ctlr->ctlr_num,
		    disk->disk_dkinfo.dki_slave);
	}

#ifdef	OLD
	fmt_print("    %4d. %s at %s%d slave %d", num, disk->disk_name,
	    ctlr->ctlr_cname, ctlr->ctlr_num, disk->disk_dkinfo.dki_slave);
	if (chk_volname(disk)) {
		fmt_print(": ");
		print_volname(disk);
	}
	fmt_print("\n");
	if (type != NULL) {
		fmt_print("           %s%d: <%s cyl %u alt %u hd %u sec %u>\n",
		    ctlr->ctlr_dname, disk->disk_dkinfo.dki_unit,
		    type->dtype_asciilabel, type->dtype_ncyl,
		    type->dtype_acyl, type->dtype_nhead,
		    type->dtype_nsect);
	} else {
		fmt_print("           %s%d: <drive type unknown>\n",
		    ctlr->ctlr_dname, disk->disk_dkinfo.dki_unit);
	}
#endif /* OLD */
}

/*
 * This routine prints out a given disk block number in cylinder/head/sector
 * format.  It uses the printing routine passed in to do the actual output.
 */
void
pr_dblock(void (*func)(char *, ...), diskaddr_t bn)
{
	if (cur_label == L_TYPE_SOLARIS) {
		(*func)("%u/%u/%u", bn2c(bn),
		    bn2h(bn), bn2s(bn));
	} else {
		(*func)("%llu", bn);
	}
}

/*
 * This routine inputs a character from the data file.  It understands
 * the use of '\' to prevent interpretation of a newline.  It also keeps
 * track of the current line in the data file via a global variable.
 */
static int
sup_inputchar(void)
{
	int	c;

	/*
	 * Input the character.
	 */
	c = getc(data_file);
	/*
	 * If it's not a backslash, return it.
	 */
	if (c != '\\')
		return (c);
	/*
	 * It was a backslash.  Get the next character.
	 */
	c = getc(data_file);
	/*
	 * If it was a newline, update the line counter and get the next
	 * character.
	 */
	if (c == '\n') {
		data_lineno++;
		c = getc(data_file);
	}
	/*
	 * Return the character.
	 */
	return (c);
}

/*
 * This routine pushes a character back onto the input pipe for the data file.
 */
static void
sup_pushchar(int c)
{
	(void) ungetc(c, data_file);
}

/*
 * Variables to support pushing back tokens
 */
static  int	have_pushed_token = 0;
static  TOKEN	pushed_buf;
static  int	pushed_token;

/*
 * This routine inputs a token from the data file.  A token is a series
 * of contiguous non-white characters or a recognized special delimiter
 * character.  Use of the wrapper lets us always have the value of the
 * last token around, which is useful for error recovery.
 */
int
sup_gettoken(char *buf)
{
	last_token_type = sup_get_token(buf);
	return (last_token_type);
}

static int
sup_get_token(char *buf)
{
	char	*ptr = buf;
	int	c, quoted = 0;

	/*
	 * First check for presence of push-backed token.
	 * If so, return it.
	 */
	if (have_pushed_token) {
		have_pushed_token = 0;
		bcopy(pushed_buf, buf, TOKEN_SIZE+1);
		return (pushed_token);
	}
	/*
	 * Zero out the returned token buffer
	 */
	bzero(buf, TOKEN_SIZE + 1);
	/*
	 * Strip off leading white-space.
	 */
	while ((isspace(c = sup_inputchar())) && (c != '\n'))
		;
	/*
	 * Read in characters until we hit unquoted white-space.
	 */
	for (; !isspace(c) || quoted; c = sup_inputchar()) {
		/*
		 * If we hit eof, that's a token.
		 */
		if (feof(data_file))
			return (SUP_EOF);
		/*
		 * If we hit a double quote, change the state of quoting.
		 */
		if (c == '"') {
			quoted = !quoted;
			continue;
		}
		/*
		 * If we hit a newline, that delimits a token.
		 */
		if (c == '\n')
			break;
		/*
		 * If we hit any nonquoted special delimiters, that delimits
		 * a token.
		 */
		if (!quoted && (c == '=' || c == ',' || c == ':' ||
		    c == '#' || c == '|' || c == '&' || c == '~'))
			break;
		/*
		 * Store the character if there's room left.
		 */
		if (ptr - buf < TOKEN_SIZE)
			*ptr++ = (char)c;
	}
	/*
	 * If we stored characters in the buffer, then we inputted a string.
	 * Push the delimiter back into the pipe and return the string.
	 */
	if (ptr - buf > 0) {
		sup_pushchar(c);
		return (SUP_STRING);
	}
	/*
	 * We didn't input a string, so we must have inputted a known delimiter.
	 * store the delimiter in the buffer, so it will get returned.
	 */
	buf[0] = c;
	/*
	 * Switch on the delimiter.  Return the appropriate value for each one.
	 */
	switch (c) {
	case '=':
		return (SUP_EQL);
	case ':':
		return (SUP_COLON);
	case ',':
		return (SUP_COMMA);
	case '\n':
		return (SUP_EOL);
	case '|':
		return (SUP_OR);
	case '&':
		return (SUP_AND);
	case '~':
		return (SUP_TILDE);
	case '#':
		/*
		 * For comments, we flush out the rest of the line and return
		 * an EOL.
		 */
		while ((c = sup_inputchar()) != '\n' && !feof(data_file))
			;
		if (feof(data_file))
			return (SUP_EOF);
		else
			return (SUP_EOL);
	/*
	 * Shouldn't ever get here.
	 */
	default:
		return (SUP_STRING);
	}
}

/*
 * Push back a token
 */
void
sup_pushtoken(char *token_buf, int token_type)
{
	/*
	 * We can only push one token back at a time
	 */
	assert(have_pushed_token == 0);

	have_pushed_token = 1;
	bcopy(token_buf, pushed_buf, TOKEN_SIZE+1);
	pushed_token = token_type;
}

/*
 * Get an entire line of input.  Handles logging, comments,
 * and EOF.
 */
void
get_inputline(char *line, int nbytes)
{
	char	*p = line;
	int	c;

	/*
	 * Remove any leading white-space and comments
	 */
	do {
		while ((isspace(c = getchar())) && (c != '\n'))
			;
	} while (c == COMMENT_CHAR);
	/*
	 * Loop on each character until end of line
	 */
	while (c != '\n') {
		/*
		 * If we hit eof, get out.
		 */
		if (checkeof()) {
			fullabort();
		}
		/*
		 * Add the character to the buffer.
		 */
		if (nbytes > 1) {
			*p++ = (char)c;
			nbytes --;
		}
		/*
		 * Get the next character.
		 */
		c = getchar();
	}
	/*
	 * Null terminate the token.
	 */
	*p = 0;
	/*
	 * Indicate that we've emptied the pipe
	 */
	token_present = 0;
	/*
	 * If we're running out of a file, echo the line to
	 * the user, otherwise if we're logging, copy the
	 * input to the log file.
	 */
	if (option_f) {
		fmt_print("%s\n", line);
	} else if (log_file) {
		log_print("%s\n", line);
	}
}

/*
 * execute the shell escape command
 */
int
execute_shell(char *s, size_t buff_size)
{
	struct	termio	termio;
	struct	termios	tty;
	int	tty_flag, i, j;
	char	*shell_name;
	static char	*default_shell = "/bin/sh";

	tty_flag = -1;

	if (*s == '\0') {
		shell_name = getenv("SHELL");

		if (shell_name == NULL) {
			shell_name = default_shell;
		}
		if (strlcpy(s, shell_name, buff_size) >=
		    buff_size) {
			err_print("Error: Shell command ($SHELL) too long.\n");
			fullabort();
		}
	}

	/* save tty information */

	if (isatty(0)) {
		if (ioctl(0, TCGETS, &tty) == 0)
			tty_flag = 1;
		else {
			if (ioctl(0, TCGETA, &termio) == 0) {
				tty_flag = 0;
				tty.c_iflag = termio.c_iflag;
				tty.c_oflag = termio.c_oflag;
				tty.c_cflag = termio.c_cflag;
				tty.c_lflag = termio.c_lflag;
				for (i = 0; i < NCC; i++)
					tty.c_cc[i] = termio.c_cc[i];
			}
		}
	}

	/* close the current file descriptor */
	if (cur_disk != NULL) {
		(void) close(cur_file);
	}

	/* execute the shell escape */
	(void) system(s);

	/* reopen file descriptor if one was open before */
	if (cur_disk != NULL) {
		if ((cur_file = open_disk(cur_disk->disk_path,
		    O_RDWR | O_NDELAY)) < 0) {
			err_print("Error: can't reopen selected disk '%s'. \n",
			    cur_disk->disk_name);
			fullabort();
		}
	}

	/* Restore tty information */

	if (isatty(0)) {
		if (tty_flag > 0)
			(void) ioctl(0, TCSETSW, &tty);
		else if (tty_flag == 0) {
			termio.c_iflag = tty.c_iflag;
			termio.c_oflag = tty.c_oflag;
			termio.c_cflag = tty.c_cflag;
			termio.c_lflag = tty.c_lflag;
			for (j = 0; j < NCC; j++)
				termio.c_cc[j] = tty.c_cc[j];
			(void) ioctl(0, TCSETAW, &termio);
		}

		if (isatty(1)) {
			fmt_print("\n[Hit Return to continue] \n");
			(void) fflush(stdin);
			if (getchar() == EOF)
				fullabort();
		}
	}
	return (0);
}

void
print_efi_string(char *vendor, char *product, char *revision,
    uint64_t capacity)
{
	char *new_vendor;
	char *new_product;
	char *new_revision;
	char capacity_string[10];
	float scaled;
	int i;

	/* Strip whitespace from the end of inquiry strings */
	new_vendor = strdup(vendor);
	if (new_vendor == NULL)
		return;

	for (i = (strlen(new_vendor) - 1); i >= 0; i--) {
		if (new_vendor[i] != 0x20) {
			new_vendor[i+1] = '\0';
			break;
		}
	}

	new_product = strdup(product);
	if (new_product == NULL) {
		free(new_vendor);
		return;
	}

	for (i = (strlen(new_product) - 1); i >= 0; i--) {
		if (new_product[i] != 0x20) {
			new_product[i+1] = '\0';
			break;
		}
	}

	new_revision = strdup(revision);
	if (new_product == NULL) {
		free(new_vendor);
		free(new_product);
		return;
	}

	for (i = (strlen(new_revision) - 1); i >= 0; i--) {
		if (new_revision[i] != 0x20) {
			new_revision[i+1] = '\0';
			break;
		}
	}

	/* Now build size string */
	scaled = bn2mb(capacity);
	if (scaled >= (float)1024.0 * 1024) {
		(void) snprintf(capacity_string, sizeof (capacity_string),
		    "%.2fTB", scaled/((float)1024.0 * 1024));
	} else if (scaled >= (float)1024.0) {
		(void) snprintf(capacity_string, sizeof (capacity_string),
		    "%.2fGB", scaled/(float)1024.0);
	} else {
		(void) snprintf(capacity_string, sizeof (capacity_string),
		    "%.2fMB", scaled);
	}

	fmt_print("<%s-%s-%s-%s>",
	    new_vendor, new_product, new_revision, capacity_string);

	free(new_revision);
	free(new_product);
	free(new_vendor);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef	_IO_H
#define	_IO_H

#ifdef	__cplusplus
extern "C" {
#endif


/*
 * Bounds structure for integer and disk input.
 */
struct bounds {
	diskaddr_t	lower;
	diskaddr_t	upper;
};

/*
 * List of strings with arbitrary matching values
 */
typedef struct slist {
	char	*str;
	char	*help;
	int	value;
} slist_t;

/*
 * Input structure for current partition information
 */
typedef struct partition_defaults {
	uint_t start_cyl;
	uint_t deflt_size;
} part_deflt_t;

typedef struct efi_defaults {
	uint64_t	start_sector;
	uint64_t	end_sector;
} efi_deflt_t;

/*
 * Input parameter can be any one of these types.
 */
typedef union input_param {
	struct slist	*io_slist;
	char		**io_charlist;
	struct bounds	io_bounds;
} u_ioparam_t;

/*
 * These declarations define the legal input types.
 */
#define	FIO_BN		0		/* block number */
#define	FIO_INT		1		/* integer input */
#define	FIO_CSTR	2		/* closed string - exact match */
#define	FIO_MSTR	3		/* matched string, with abbreviations */
#define	FIO_OSTR	4		/* open string - anything's legal */
#define	FIO_BLNK	5		/* blank line */
#define	FIO_SLIST	6		/* one string out of a list, abbr. */
#define	FIO_CYL		7		/* nblocks, on cylinder boundary */
#define	FIO_OPINT	8		/* optional integer input */
#define	FIO_ECYL	9		/* allows end cylinder input */
#define	FIO_INT64	10		/* Input for EFI partitions */
#define	FIO_EFI		11		/* Input EFI part size	*/

/*
 * Miscellaneous definitions.
 */
#define	TOKEN_SIZE	36			/* max length of a token */
typedef	char TOKEN[TOKEN_SIZE+1];		/* token type */
#define	DATA_INPUT	0			/* 2 modes of input */
#define	CMD_INPUT	1
#define	WILD_STRING	"$"			/* wildcard character */
#define	COMMENT_CHAR	'#'			/* comment character */


/*
 *	Prototypes for ANSI C
 */
char	*gettoken(char *inbuf);
void	clean_token(char *cleantoken, char *token);
int	geti(char *str, int *iptr, int *wild);
uint64_t	input(int, char *, int, u_ioparam_t *, int *, int);
int	find_value(slist_t *slist, char *match_str, int *match_value);
char	*find_string(slist_t *slist, int match_value);
void	fmt_print(char *format, ...) __PRINTFLIKE(1);
void	nolog_print(char *format, ...) __PRINTFLIKE(1);
void	log_print(char *format, ...) __PRINTFLIKE(1);
void	err_print(char *format, ...) __PRINTFLIKE(1);
void	print_buf(char *buf, int nbytes);
void	pr_diskline(struct disk_info *disk, int num);
void	pr_dblock(void (*func)(char *, ...), diskaddr_t bn);
int	sup_gettoken(char *buf);
void	sup_pushtoken(char *token_buf, int token_type);
void	get_inputline(char *, int);
int	istokenpresent(void);
int	execute_shell(char *, size_t);
void	print_efi_string(char *vendor, char *product, char *revision,
    uint64_t capacity);

/*
 * Most recent token type
 */
extern	int	last_token_type;

#ifdef	__cplusplus
}
#endif

#endif	/* _IO_H */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 *
 * copyright (c) 1990, 1991 UNIX System Laboratories, Inc.
 * copyright (c) 1984, 1986, 1987, 1988, 1989, 1990 AT&T
 * All rights reserved.
 */

/*
 * Copyrighted as an unpublished work.
 * (c) Copyright INTERACTIVE Systems Corporation 1986, 1988, 1990
 * All rights reserved.
 */

#include <sys/types.h>
#include <ctype.h>
#include <fcntl.h>
#include <malloc.h>
#include <sys/stat.h>
#include <sys/swap.h>
#include <stdio.h>
#include <string.h>
#include <sys/vtoc.h>
#include <sys/param.h>
#include <sys/dkio.h>
#include <sys/dktp/altsctr.h>
#include <sys/dktp/fdisk.h>
#include "badsec.h"
#include "global.h"
#include "ctlr_ata.h"
#include "misc.h"

#define	FAILURE	1
#define	SUCCESS	0

#define	CMD_READ	0
#define	CMD_WRITE	1

struct	badsec_lst *badsl_chain = NULL;
int	badsl_chain_cnt = 0;
struct	badsec_lst *gbadsl_chain = NULL;
int	gbadsl_chain_cnt = 0;

static struct	alts_mempart alts_part = { 0, NULL, 0 };
struct	alts_mempart	*ap = &alts_part;	/* pointer to incore */
						/*  alts tables	*/

/* prototypes */
int updatebadsec(struct  dkl_partition *, int);
int read_altsctr(struct  dkl_partition *);
static int chk_badsec(void);
static int init_altsctr(void);
static int get_altsctr(void);
int wr_altsctr(void);
static void get_badsec(void);
static int count_badsec(void);
static int gen_alts_ent(void);
static int assign_altsctr(void);
static void expand_map(void);
static void compress_map(void);
static int altsmap_getbit(blkaddr_t);
static blkaddr_t altsmap_alloc(blkaddr_t, blkaddr_t, int, int);
static void ent_sort(struct  alts_ent *, int);
static void ent_compress(struct  alts_ent *, int);
static int ent_merge(struct alts_ent *, struct alts_ent *, int,
		struct alts_ent *, int);
static int ent_bsearch(struct  alts_ent *, int, struct  alts_ent *);
static int chk_bad_altsctr(blkaddr_t);

/*
 * updatebadsec () -- update bad sector/track mapping tables
 */
int
updatebadsec(struct dkl_partition *part, int init_flag)
{
	if (init_flag)
		ap->ap_flag |= ALTS_ADDPART;
	get_badsec();
	(void) read_altsctr(part);
	ent_sort(ap->ap_gbadp, ap->ap_gbadcnt);
	ent_compress(ap->ap_gbadp, ap->ap_gbadcnt);
	(void) gen_alts_ent();
	compress_map();
	return (SUCCESS);
}

/*
 * read_altsctr( ptr to alternate sector partition )
 *		-- read the alternate sector partition tables
 */
int
read_altsctr(struct dkl_partition *part)
{
	if (ap->ap_tblp == NULL) {
		/* allocate buffer for the alts partition table (sector size) */
		ap->ap_tbl_secsiz = byte_to_secsiz(ALTS_PARTTBL_SIZE, NBPSCTR);
		ap->ap_tblp = malloc(ap->ap_tbl_secsiz);
		if (ap->ap_tblp == NULL) {
			(void) fprintf(stderr,
			    "Unable to malloc alternate partition table.\n");
			return (50);
		}

		/*
		 * allocate buffer for the alts partition map (sector size)
		 * buffers include the disk image bit map
		 * and the incore transformed char map.
		 */

		if ((ap->ap_memmapp = malloc(part->p_size)) == NULL) {
			(void) fprintf(stderr, "Unable to malloc incore "
			    "alternate partition map.\n");
			return (51);
		}
		ap->ap_tblp->alts_map_len = (part->p_size + 8 - 1) / 8;
		ap->ap_map_secsiz = byte_to_secsiz(ap->ap_tblp->alts_map_len,
		    NBPSCTR);
		ap->ap_map_sectot = ap->ap_map_secsiz / NBPSCTR;
		if ((ap->ap_mapp = malloc(ap->ap_map_secsiz)) == NULL) {
			(void) fprintf(stderr, "Unable to malloc alternate "
			    "partition map.\n");
			return (52);
		}
		/* clear the buffers to zero */
		(void) memset(ap->ap_memmapp, 0, part->p_size);
		(void) memset(ap->ap_mapp, 0, ap->ap_map_secsiz);
		ap->part = *part;		/* struct copy */

		/*
		 * if add alternate partition flag is set, then install
		 * the partition. Otherwise read the alts partition info
		 * from disk. If failed, then assume the first installation
		 */
		if (ap->ap_flag & ALTS_ADDPART) {
			(void) fprintf(stderr, "WARNING: Manually "
			    "initializing alternate table.\n");
			(void) init_altsctr();
		} else {
			if (get_altsctr() == SUCCESS)
				(void) chk_badsec();
			else
				(void) init_altsctr();
		}
	}
	return (SUCCESS);
}


/*
 *	checking duplicate bad sectors or bad sectors in ALTSCTR partition
 */
static int
chk_badsec(void)
{
	blkaddr_t	badsec;
	blkaddr_t	altsp_srtsec = ap->part.p_start;
	blkaddr_t	altsp_endsec = ap->part.p_start + ap->part.p_size - 1;
	int	cnt;
	int	status;

	for (cnt = 0; cnt < ap->ap_gbadcnt; cnt++) {
		badsec = (ap->ap_gbadp)[cnt].bad_start;

		/* if bad sector is within the ATLSCTR partition */
		if ((badsec >= altsp_srtsec) && (badsec <= altsp_endsec)) {
			if ((ap->ap_memmapp)[badsec - altsp_srtsec] !=
			    ALTS_BAD) {
				if ((badsec >= altsp_srtsec) &&
				    (badsec <= (altsp_srtsec +
				    ap->ap_tbl_secsiz / NBPSCTR - 1))) {
					(void) fprintf(stderr,
					    "Alternate partition information "
					    "table is bad.\n");
					return (53);
				}
				if ((badsec >=
				    altsp_srtsec+ap->ap_tblp->alts_map_base) &&
				    (badsec <=
				    (altsp_srtsec + ap->ap_tblp->alts_map_base +
				    ap->ap_map_sectot - 1))) {
					(void) fprintf(stderr, "Alternate "
					    "partition map is bad.\n");
					return (54);
				}
				if ((badsec >=
				    altsp_srtsec+ap->ap_tblp->alts_ent_base) &&
				    (badsec <=
				    (altsp_srtsec + ap->ap_tblp->alts_ent_base +
				    ap->ap_ent_secsiz / NBPSCTR - 1))) {
					(void) fprintf(stderr, "Alternate "
					    "partition entry table is bad.\n");
					return (55);
				}
				(ap->ap_memmapp)[badsec - altsp_srtsec] =
				    ALTS_BAD;
				(ap->ap_gbadp)[cnt].bad_start =
				    (uint32_t)ALTS_ENT_EMPTY;
			} else {
				status = chk_bad_altsctr(badsec);
				(ap->ap_gbadp)[cnt].bad_start =
				    (uint32_t)ALTS_ENT_EMPTY;
			}
		} else {
			/*
			 * binary search for bad sector in the alts entry table
			 */
			status = ent_bsearch(ap->ap_entp,
			    ap->ap_tblp->alts_ent_used,
			    &((ap->ap_gbadp)[cnt]));
			/*
			 * if the bad sector had already been remapped
			 * (found in alts_entry), then ignore the bad sector.
			 */
			if (status != -1) {
				(ap->ap_gbadp)[cnt].bad_start =
				    (uint32_t)ALTS_ENT_EMPTY;
			}
		}
	}
	return (SUCCESS);
}

/*
 *	initialize the alternate partition tables
 */
static int
init_altsctr(void)
{
	blkaddr_t	badsec;
	blkaddr_t	altsp_srtsec = ap->part.p_start;
	blkaddr_t	altsp_endsec = ap->part.p_start + ap->part.p_size - 1;
	int	cnt;

	ap->ap_entp = NULL;
	ap->ap_ent_secsiz = 0;
	ap->ap_tblp->alts_sanity = ALTS_SANITY;
	ap->ap_tblp->alts_version = ALTS_VERSION1;
	ap->ap_tblp->alts_map_len = (ap->part.p_size + 8 - 1) / 8;
	ap->ap_tblp->alts_ent_used = 0;
	ap->ap_tblp->alts_ent_base = 0;
	ap->ap_tblp->alts_ent_end  = 0;
	ap->ap_tblp->alts_resv_base = ap->part.p_size - 1;
	for (cnt = 0; cnt < 5; cnt++)
		ap->ap_tblp->alts_pad[cnt] = 0;

	for (cnt = 0; cnt < ap->ap_gbadcnt; cnt++) {
		badsec = (ap->ap_gbadp)[cnt].bad_start;
		if ((badsec >= altsp_srtsec) && (badsec <= altsp_endsec)) {
			if (badsec == altsp_srtsec) {
				(void) fprintf(stderr, "First sector of "
				    "alternate partition is bad.\n");
				return (56);
			}
			(ap->ap_memmapp)[badsec - altsp_srtsec] = ALTS_BAD;
			(ap->ap_gbadp)[cnt].bad_start =
			    (uint32_t)ALTS_ENT_EMPTY;
		}
	}

	/* allocate the alts_map on disk skipping possible bad sectors */
	ap->ap_tblp->alts_map_base =
	    altsmap_alloc(ap->ap_tbl_secsiz / NBPSCTR,
	    ap->part.p_size, ap->ap_map_sectot, ALTS_MAP_UP);
	if (ap->ap_tblp->alts_map_base == 0) {
		perror("Unable to allocate alternate map on disk: ");
		return (57);
	}
	(void) wr_altsctr();

	return (SUCCESS);
}


/*
 *	read the alternate partition tables from disk
 */
static int
get_altsctr(void)
{
	int	mystatus = FAILURE;
	int	status = 0;

	/* get alts partition table info */

	status = ata_rdwr(DIR_READ, cur_file, altsec_offset,
	    ap->ap_tbl_secsiz / UBSIZE, (char *)ap->ap_tblp, 0, NULL);
	if (status == FAILURE) {
		perror("Unable to read alternate sector partition: ");
		return (58);
	}
	if (ap->ap_tblp->alts_sanity != ALTS_SANITY)
		return (mystatus);

	/* get the alts map */
	status = ata_rdwr(DIR_READ, cur_file,
	    (ap->ap_tblp->alts_map_base) + altsec_offset,
	    ap->ap_map_secsiz / UBSIZE, (char *)ap->ap_mapp, 0, NULL);
	if (status == FAILURE) {
		perror("Unable to read alternate sector partition map: ");
		return (59);
	}

	/* transform the disk image bit-map to incore char map */
	expand_map();

	if (ap->ap_tblp->alts_ent_used == 0) {
		ap->ap_entp = NULL;
		ap->ap_ent_secsiz = 0;
	} else {
		ap->ap_ent_secsiz = byte_to_secsiz(
		    (ap->ap_tblp->alts_ent_used*ALTS_ENT_SIZE), NBPSCTR);
		ap->ap_entp = malloc(ap->ap_ent_secsiz);
		if (ap->ap_entp == NULL) {
			(void) fprintf(stderr,
			    "Unable to malloc alternate sector entry table.\n");
			return (60);
		}

		status = ata_rdwr(DIR_READ, cur_file,
		    (ap->ap_tblp->alts_ent_base) + altsec_offset,
		    ap->ap_ent_secsiz / UBSIZE, (char *)ap->ap_entp,
		    0, NULL);
		if (status == FAILURE) {
			perror("Unable to read alternate sector entry table: ");
			return (61);
		}
	}

	return (SUCCESS);
}


/*
 *	update the new alternate partition tables on disk
 */
int
wr_altsctr(void)
{
	int	status;

	if (ap->ap_tblp == NULL)
		return (0);
	status = ata_rdwr(DIR_WRITE, cur_file, altsec_offset,
	    ap->ap_tbl_secsiz / UBSIZE, (char *)ap->ap_tblp, 0, NULL);
	if (status) {
		(void) printf("ata_rdwr status = %d need = %d\n",
		    status, ap->ap_tbl_secsiz / 512);
		perror("Unable to write with ata_rdwr the alt sector part: ");
		return (62);
	}

	if (ata_rdwr(DIR_WRITE, cur_file, (ap->ap_tblp->alts_map_base) +
	    altsec_offset, ap->ap_map_secsiz / UBSIZE,
	    (char *)ap->ap_mapp, 0, NULL) == FAILURE) {
		perror("Unable to write alternate sector partition map: ");
		return (63);
	}

	if (ap->ap_tblp->alts_ent_used != 0) {
		if (ata_rdwr(DIR_WRITE, cur_file,
		    (ap->ap_tblp->alts_ent_base)+ altsec_offset,
		    ap->ap_ent_secsiz / UBSIZE,
		    (char *)ap->ap_entp, 0, NULL) == FAILURE) {
			perror("Unable to write alternate sector "
			    "entry table: ");
			return (64);
		}
	}
	return (0);
}


/*
 *	get a list of bad sector
 */
static void
get_badsec(void)
{
	int	cnt;
	struct	badsec_lst *blc_p;
	blkaddr_t	curbad;
	blkaddr_t	maxsec = cur_dtype->dtype_nhead *
	    cur_dtype->dtype_ncyl * cur_dtype->dtype_nsect;
	struct	alts_ent *growbadp;
	int	i;

	cnt = count_badsec();
	if (cnt == 0) {
		ap->ap_gbadp = NULL;
		ap->ap_gbadcnt = 0;
	} else {
		ap->ap_gbadp = malloc(cnt * ALTS_ENT_SIZE);
		if (ap->ap_gbadp == NULL) {
			err_print("get_badsec: unable to malloc %d bytes\n",
			    cnt * ALTS_ENT_SIZE);
			fullabort();
		}
		(void) memset(ap->ap_gbadp, 0, cnt * ALTS_ENT_SIZE);

		for (growbadp = ap->ap_gbadp, cnt = 0, blc_p = badsl_chain;
		    blc_p; blc_p = blc_p->bl_nxt) {
			for (i = 0; i < blc_p->bl_cnt; i++) {
				curbad = blc_p->bl_sec[i];
				if (curbad <
				    (blkaddr_t)cur_dtype->dtype_nsect) {
					(void) fprintf(stderr, "Ignoring bad "
					    "sector %ld which is in first "
					    "track of the drive.\n", curbad);
					continue;
				}
				if (curbad >= maxsec) {
					(void) fprintf(stderr, "Ignoring bad "
					    "sector %ld which is past the end "
					    "of the drive.\n", curbad);
					continue;
				}
				growbadp[cnt].bad_start = curbad;
				growbadp[cnt].bad_end = curbad;
				cnt++;
			}
		}
	}
	ap->ap_gbadcnt = cnt;
}

/*
 *	count number of bad sector on list
 *	merging the bad sector list from surface analysis and the
 *	one given through the command line
 */
static int
count_badsec(void)
{
	struct badsec_lst *blc_p;

	if (!badsl_chain) {
		badsl_chain = gbadsl_chain;
	} else {
		for (blc_p = badsl_chain; blc_p->bl_nxt; blc_p = blc_p->bl_nxt)
			;
		blc_p->bl_nxt = gbadsl_chain;
	}

	badsl_chain_cnt += gbadsl_chain_cnt;
	return (badsl_chain_cnt);
}


/*
 *	generate alternate entry table by merging the existing and
 *	the new entry list.
 */
static int
gen_alts_ent(void)
{
	uint_t	ent_used;
	struct	alts_ent *entp;

	if (ap->ap_gbadcnt == 0)
		return (0);

	ent_used = ap->ap_tblp->alts_ent_used + ap->ap_gbadcnt;
	ap->ap_ent_secsiz = byte_to_secsiz(ent_used*ALTS_ENT_SIZE, NBPSCTR);
	entp = malloc(ap->ap_ent_secsiz);
	if (entp == NULL) {
		err_print("get_alts_ent: unable to malloc %d bytes\n",
		    ap->ap_ent_secsiz);
		fullabort();
	}

	ent_used = ent_merge(entp, ap->ap_entp, ap->ap_tblp->alts_ent_used,
	    ap->ap_gbadp, ap->ap_gbadcnt);
	free(ap->ap_entp);
	free(ap->ap_gbadp);
	ap->ap_entp = entp;
	ap->ap_ent_secsiz = byte_to_secsiz(ent_used*ALTS_ENT_SIZE, NBPSCTR);
	ap->ap_tblp->alts_ent_used = ent_used;
	ap->ap_gbadp = NULL;
	ap->ap_gbadcnt = 0;

	/* assign alternate sectors to the bad sectors */
	(void) assign_altsctr();

	/* allocate the alts_entry on disk skipping possible bad sectors */
	ap->ap_tblp->alts_ent_base =
	    altsmap_alloc((blkaddr_t)ap->ap_tblp->alts_map_base +
	    ap->ap_map_sectot, (blkaddr_t)ap->part.p_size,
	    ap->ap_ent_secsiz / NBPSCTR, ALTS_MAP_UP);
	if (ap->ap_tblp->alts_ent_base == 0) {
		perror("Unable to allocate alternate entry table on disk: ");
		return (65);
	}

	ap->ap_tblp->alts_ent_end = ap->ap_tblp->alts_ent_base +
	    (ap->ap_ent_secsiz / NBPSCTR) - 1;
	return (0);
}


/*
 *	assign alternate sectors for bad sector mapping
 */
static int
assign_altsctr(void)
{
	uint_t	i;
	uint_t	j;
	blkaddr_t	alts_ind;
	uint_t	cluster;

	for (i = 0; i < ap->ap_tblp->alts_ent_used; i++) {
		if ((ap->ap_entp)[i].bad_start == (uint32_t)ALTS_ENT_EMPTY)
			continue;
		if ((ap->ap_entp)[i].good_start != 0)
			continue;
		cluster =
		    (ap->ap_entp)[i].bad_end - (ap->ap_entp)[i].bad_start + 1;
		alts_ind = altsmap_alloc(ap->part.p_size - 1,
		    ap->ap_tblp->alts_map_base +
		    ap->ap_map_sectot - 1, cluster, ALTS_MAP_DOWN);
		if (alts_ind == 0) {
			(void) fprintf(stderr, "Unable to allocate alternates "
			    "for bad starting sector %u.\n",
			    (ap->ap_entp)[i].bad_start);
			return (65);
		}
		alts_ind = alts_ind - cluster + 1;
		(ap->ap_entp)[i].good_start = alts_ind +ap->part.p_start;
		for (j = 0; j < cluster; j++) {
			(ap->ap_memmapp)[alts_ind+j] = ALTS_BAD;
		}
	}
	return (SUCCESS);
}

/*
 *	transform the disk image alts bit map to incore char map
 */
static void
expand_map(void)
{
	int	i;

	for (i = 0; i < ap->part.p_size; i++) {
		(ap->ap_memmapp)[i] = altsmap_getbit(i);
	}
}

/*
 *	transform the incore alts char map to the disk image bit map
 */
static void
compress_map(void)
{
	int	i;
	int	bytesz;
	char	mask = 0;
	int	maplen = 0;

	for (i = 0, bytesz = 7; i < ap->part.p_size; i++) {
		mask |= ((ap->ap_memmapp)[i] << bytesz--);
		if (bytesz < 0) {
			(ap->ap_mapp)[maplen++] = mask;
			bytesz = 7;
			mask = 0;
		}
	}
	/*
	 * if partition size != multiple number of bytes
	 * then record the last partial byte
	 */
	if (bytesz != 7)
		(ap->ap_mapp)[maplen] = mask;
}

/*
 *	given a bad sector number, search in the alts bit map
 *	and identify the sector as good or bad
 */
static int
altsmap_getbit(blkaddr_t badsec)
{
	uint_t	slot = badsec / 8;
	uint_t	field = badsec % 8;
	uchar_t	mask;

	mask = ALTS_BAD<<7;
	mask >>= field;
	if ((ap->ap_mapp)[slot] & mask)
		return (ALTS_BAD);
	return (ALTS_GOOD);
}


/*
 *	allocate a range of sectors from the alternate partition
 */
static blkaddr_t
altsmap_alloc(blkaddr_t srt_ind, blkaddr_t end_ind, int cnt, int dir)
{
	blkaddr_t	i;
	blkaddr_t	total;
	blkaddr_t	first_ind;

	for (i = srt_ind, first_ind = srt_ind, total = 0;
	    i != end_ind; i += dir) {
		if ((ap->ap_memmapp)[i] == ALTS_BAD) {
			total = 0;
			first_ind = i + dir;
			continue;
		}
		total++;
		if (total == cnt)
			return (first_ind);
	}
	return (0);
}



/*
 *	bubble sort the entry table into ascending order
 */
static void
ent_sort(struct alts_ent buf[], int cnt)
{
	struct	alts_ent temp;
	int	flag;
	int	i, j;

	for (i = 0; i < cnt-1; i++) {
		temp = buf[cnt-1];
		flag = 1;

		for (j = cnt-1; j > i; j--) {
			if (buf[j-1].bad_start < temp.bad_start) {
				buf[j] = temp;
				temp = buf[j - 1];
			} else {
				buf[j] = buf[j - 1];
				flag = 0;
			}
		}
		buf[i] = temp;
		if (flag)
			break;
	}
}


/*
 *	compress all the contiguous bad sectors into a single entry
 *	in the entry table. The entry table must be sorted into ascending
 *	before the compression.
 */
static void
ent_compress(struct alts_ent buf[], int cnt)
{
	int	keyp;
	int	movp;
	int	i;

	for (i = 0; i < cnt; i++) {
		if (buf[i].bad_start == (uint32_t)ALTS_ENT_EMPTY)
			continue;
		for (keyp = i, movp = i+1; movp < cnt; movp++) {
			if (buf[movp].bad_start == (uint32_t)ALTS_ENT_EMPTY)
				continue;
			if (buf[keyp].bad_end+1 != buf[movp].bad_start)
				break;
			buf[keyp].bad_end++;
			buf[movp].bad_start = (uint32_t)ALTS_ENT_EMPTY;
		}
		if (movp == cnt)
			break;
	}
}


/*
 *	merging two entry tables into a single table. In addition,
 *	all empty slots in the entry table will be removed.
 */
static int
ent_merge(struct alts_ent buf[], struct alts_ent list1[], int lcnt1,
    struct alts_ent list2[], int lcnt2)
{
	int	i;
	int	j1, j2;

	for (i = 0, j1 = 0, j2 = 0; j1 < lcnt1 && j2 < lcnt2; ) {
		if (list1[j1].bad_start == (uint32_t)ALTS_ENT_EMPTY) {
			j1++;
			continue;
		}
		if (list2[j2].bad_start == (uint32_t)ALTS_ENT_EMPTY) {
			j2++;
			continue;
		}
		if (list1[j1].bad_start < list2[j2].bad_start)
			buf[i++] = list1[j1++];
		else
			buf[i++] = list2[j2++];
	}
	for (; j1 < lcnt1; j1++) {
		if (list1[j1].bad_start == (uint32_t)ALTS_ENT_EMPTY)
			continue;
		buf[i++] = list1[j1];
	}
	for (; j2 < lcnt2; j2++) {
		if (list2[j2].bad_start == (uint32_t)ALTS_ENT_EMPTY)
			continue;
		buf[i++] = list2[j2];
	}
	return (i);
}


/*
 *	binary search for bad sector in the alternate entry table
 */
static int
ent_bsearch(struct alts_ent buf[], int cnt, struct alts_ent *key)
{
	int	i;
	int	ind;
	int	interval;
	int	mystatus = -1;

	if (!cnt)
		return (mystatus);

	for (i = 1; i <= cnt; i <<= 1)
		ind = i;

	for (interval = ind; interval; ) {
		if ((key->bad_start >= buf[ind-1].bad_start) &&
		    (key->bad_start <= buf[ind-1].bad_end)) {
			return (mystatus = ind-1);
		} else {
			interval >>= 1;
			if (!interval) break;
			if (key->bad_start < buf[ind-1].bad_start) {
				ind = ind - interval;
			} else {
				/*
				 * if key is larger than the last element,
				 * then break.
				 */
				if (ind == cnt)
					break;
				if ((ind + interval) <= cnt)
					ind += interval;
			}
		}
	}
	return (mystatus);
}

/*
 *	check for bad sector in assigned alternate sectors
 */
static int
chk_bad_altsctr(blkaddr_t badsec)
{
	int	i;
	blkaddr_t	numsec;
	int	cnt = ap->ap_tblp->alts_ent_used;
/*
 *	daddr_t intv[3];
 */

	for (i = 0; i < cnt; i++) {
		numsec = (ap->ap_entp)[i].bad_end - (ap->ap_entp)[i].bad_start;
		if ((badsec >= (ap->ap_entp)[i].good_start) &&
		    (badsec <= ((ap->ap_entp)[i].good_start + numsec))) {
			(void) fprintf(stderr,
			    "Bad sector %ld is an assigned alternate sector.\n",
			    badsec);
			return (66);
/*
 *		if (!numsec) {
 *		    (ap->ap_entp)[i].good_start = 0;
 *		    return (FAILURE);
 *		}
 *		intv[0] = badsec - (ap->ap_entp)[i].good_start;
 *		intv[1] = 1;
 *		intv[2] = (ap->ap_entp)[i].good_start + numsec - badsec;
 */
		}
	}
	/* the bad sector has already been identified as bad */
	return (SUCCESS);

}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright (c) 1991, 2010, Oracle and/or its affiliates. All rights reserved.
 * Copyright 2015 Nexenta Systems, Inc. All rights reserved.
 */

/*
 * This file contains the code relating to label manipulation.
 */

#include <string.h>
#include <stdlib.h>
#include <memory.h>
#include <sys/isa_defs.h>
#include <sys/efi_partition.h>
#include <sys/vtoc.h>
#include <sys/uuid.h>
#include <errno.h>
#include <devid.h>
#include <libdevinfo.h>
#include "global.h"
#include "label.h"
#include "misc.h"
#include "main.h"
#include "partition.h"
#include "ctlr_scsi.h"
#include "checkdev.h"

#if defined(_FIRMWARE_NEEDS_FDISK)
#include <sys/dktp/fdisk.h>
#include "menu_fdisk.h"
#endif		/* defined(_FIRMWARE_NEEDS_FDISK) */

#ifndef	WD_NODE
#define	WD_NODE		7
#endif

static int	do_geometry_sanity_check(void);
static int	vtoc_to_label(struct dk_label *, struct extvtoc *,
		struct dk_geom *, struct dk_cinfo *);
extern int	read_extvtoc(int, struct extvtoc *);
extern int	write_extvtoc(int, struct extvtoc *);
static int	vtoc64_to_label(struct efi_info *, struct dk_gpt *);

#ifdef	DEBUG
static void dump_label(struct dk_label *);
#endif

/*
 * This routine checks the given label to see if it is valid.
 */
int
checklabel(struct dk_label *label)
{

	/*
	 * Check the magic number.
	 */
	if (label->dkl_magic != DKL_MAGIC)
		return (0);
	/*
	 * Check the checksum.
	 */
	if (checksum(label, CK_CHECKSUM) != 0)
		return (0);
	return (1);
}

/*
 * This routine checks or calculates the label checksum, depending on
 * the mode it is called in.
 */
int
checksum(struct	dk_label *label, int mode)
{
	short *sp, sum = 0;
	short count = (sizeof (struct dk_label)) / (sizeof (short));

	/*
	 * If we are generating a checksum, don't include the checksum
	 * in the rolling xor.
	 */
	if (mode == CK_MAKESUM)
		count -= 1;
	sp = (short *)label;
	/*
	 * Take the xor of all the half-words in the label.
	 */
	while (count--) {
		sum ^= *sp++;
	}
	/*
	 * If we are checking the checksum, the total will be zero for
	 * a correct checksum, so we can just return the sum.
	 */
	if (mode == CK_CHECKSUM)
		return (sum);
	/*
	 * If we are generating the checksum, fill it in.
	 */
	else {
		label->dkl_cksum = sum;
		return (0);
	}
}

/*
 * This routine is used to extract the id string from the string stored
 * in a disk label.  The problem is that the string in the label has
 * the physical characteristics of the drive appended to it.  The approach
 * is to find the beginning of the physical attributes portion of the string
 * and truncate it there.
 */
int
trim_id(char *id)
{
	char *c;

	/*
	 * Start at the end of the string.  When we match the word ' cyl',
	 * we are at the beginning of the attributes.
	 */
	for (c = id + strlen(id); c >= id; c--) {
		if (strncmp(c, " cyl", strlen(" cyl")) == 0) {
			/*
			 * Remove any white space.
			 */
			for (; (((*(c - 1) == ' ') || (*(c - 1) == '\t')) &&
			    (c >= id)); c--)
				;
			break;
		}
	}
	/*
	 * If we ran off the beginning of the string, something is wrong.
	 */
	if (c < id)
		return (-1);
	/*
	 * Truncate the string.
	 */
	*c = '\0';
	return (0);
}

/*
 * This routine is used by write_label() to do a quick sanity check on the
 * supplied geometry. This is not a thorough check.
 *
 * The SCSI READ_CAPACITY command is used here to get the capacity of the
 * disk. But, the available area to store data on a disk is usually less
 * than this. So, if the specified geometry evaluates to a value which falls
 * in this margin, then such illegal geometries can slip through the cracks.
 */
static int
do_geometry_sanity_check(void)
{
	struct scsi_capacity_16	 capacity;

	if (uscsi_read_capacity(cur_file, &capacity)) {
		err_print("Warning: Unable to get capacity."
		    " Cannot check geometry\n");
		return (0);	/* Just ignore this problem */
	}

	if (capacity.sc_capacity < ncyl * nhead * nsect) {
		err_print("\nWarning: Current geometry overshoots "
		    "actual geometry of disk\n\n");
		if (check("Continue labelling disk") != 0)
			return (-1);
		return (0);	/* Just ignore this problem */
	}

	return (0);
}

/*
 * create a clear EFI partition table when format is used
 * to convert an SMI label to an EFI label
 */
int
SMI_vtoc_to_EFI(int fd, struct dk_gpt **new_vtoc)
{
	int i;
	struct dk_gpt *efi;
	uint64_t reserved;

	if (efi_alloc_and_init(fd, EFI_NUMPAR, new_vtoc) != 0) {
		err_print("SMI vtoc to EFI failed\n");
		return (-1);
	}
	efi = *new_vtoc;
	reserved = efi_reserved_sectors(efi);

	/*
	 * create a clear EFI partition table:
	 * s0 takes the whole disk except the primary EFI lable,
	 * backup EFI labels, and the reserved partition.
	 * s1-s6 are unassigned slices.
	 */
	efi->efi_parts[0].p_tag = V_USR;
	efi->efi_parts[0].p_start = efi->efi_first_u_lba;
	efi->efi_parts[0].p_size = efi->efi_last_u_lba - efi->efi_first_u_lba
	    - reserved + 1;

	/*
	 * s1-s6 are unassigned slices
	 */
	for (i = 1; i < efi->efi_nparts - 2; i++) {
		efi->efi_parts[i].p_tag = V_UNASSIGNED;
		efi->efi_parts[i].p_start = 0;
		efi->efi_parts[i].p_size = 0;
	}

	/*
	 * the reserved slice
	 */
	efi->efi_parts[efi->efi_nparts - 1].p_tag = V_RESERVED;
	efi->efi_parts[efi->efi_nparts - 1].p_start =
	    efi->efi_last_u_lba - reserved + 1;
	efi->efi_parts[efi->efi_nparts - 1].p_size = reserved;

	return (0);
}

/*
 * This routine constructs and writes a label on the disk.  It writes both
 * the primary and backup labels.  It assumes that there is a current
 * partition map already defined.  It also notifies the SunOS kernel of
 * the label and partition information it has written on the disk.
 */
int
write_label(void)
{
	int	error = 0, head, sec;
	struct dk_label label;
	struct extvtoc	vtoc;
	struct dk_geom	geom;
	struct dk_gpt	*vtoc64;
	int		nbackups;
	char		*new_label;

#if defined(_SUNOS_VTOC_8)
	int i;
#endif		/* defined(_SUNOS_VTOC_8) */

	/*
	 * Check to see if any partitions used for svm, vxvm or live upgrade
	 * are on the disk. If so, refuse to label the disk, but only
	 * if we are trying to shrink a partition in use.
	 */
	if (checkdevinuse(cur_disk->disk_name, (diskaddr_t)-1,
	    (diskaddr_t)-1, 0, 1)) {
		err_print("Cannot label disk when "
		    "partitions are in use as described.\n");
		return (-1);
	}

	/*
	 * If EFI label, then write it out to disk
	 */
	if (cur_label == L_TYPE_EFI) {
		enter_critical();
		vtoc64 = cur_parts->etoc;
		efi_err_check(vtoc64);
		if (efi_write(cur_file, vtoc64) != 0) {
			err_print("Warning: error writing EFI.\n");
			error = -1;
			}

		cur_disk->disk_flags |= DSK_LABEL;
		exit_critical();
		return (error);
	}

	/*
	 * Fill in a label structure with the geometry information.
	 */
	(void) memset((char *)&label, 0, sizeof (struct dk_label));
	new_label = zalloc(cur_blksz);

	label.dkl_pcyl = pcyl;
	label.dkl_ncyl = ncyl;
	label.dkl_acyl = acyl;

#if defined(_SUNOS_VTOC_16)
	label.dkl_bcyl = bcyl;
#endif			/* defined(_SUNOC_VTOC_16) */

	label.dkl_nhead = nhead;
	label.dkl_nsect = nsect;
	label.dkl_apc = apc;
	label.dkl_intrlv = 1;
	label.dkl_rpm = cur_dtype->dtype_rpm;

#if defined(_SUNOS_VTOC_8)
	/*
	 * Also fill in the current partition information.
	 */
	for (i = 0; i < NDKMAP; i++) {
		label.dkl_map[i] = cur_parts->pinfo_map[i];
	}
#endif			/* defined(_SUNOS_VTOC_8) */

	label.dkl_magic = DKL_MAGIC;

	/*
	 * Fill in the vtoc information
	 */
	label.dkl_vtoc = cur_parts->vtoc;

	/*
	 * Use the current label
	 */
	bcopy(cur_disk->v_volume, label.dkl_vtoc.v_volume, LEN_DKL_VVOL);

	/*
	 * Put asciilabel in; on x86 it's in the vtoc, not the label.
	 */
	(void) snprintf(label.dkl_asciilabel, sizeof (label.dkl_asciilabel),
	    "%s cyl %d alt %d hd %d sec %d",
	    cur_dtype->dtype_asciilabel, ncyl, acyl, nhead, nsect);

#if defined(_SUNOS_VTOC_16)
	/*
	 * Also add in v_sectorsz, as the driver will.
	 */
	label.dkl_vtoc.v_sectorsz = cur_blksz;
#endif			/* defined(_SUNOS_VTOC_16) */

	/*
	 * Generate the correct checksum.
	 */
	(void) checksum(&label, CK_MAKESUM);
	/*
	 * Convert the label into a vtoc
	 */
	if (label_to_vtoc(&vtoc, &label) == -1) {
		free(new_label);
		return (-1);
	}
	/*
	 * Fill in the geometry info.  This is critical that
	 * we do this before writing the vtoc.
	 */
	bzero((caddr_t)&geom, sizeof (struct dk_geom));
	geom.dkg_ncyl = ncyl;
	geom.dkg_acyl = acyl;

#if defined(_SUNOS_VTOC_16)
	geom.dkg_bcyl = bcyl;
#endif			/* defined(_SUNOS_VTOC_16) */

	geom.dkg_nhead = nhead;
	geom.dkg_nsect = nsect;
	geom.dkg_intrlv = 1;
	geom.dkg_apc = apc;
	geom.dkg_rpm = cur_dtype->dtype_rpm;
	geom.dkg_pcyl = pcyl;

	/*
	 * Make a quick check to see that the geometry is being
	 * written now is not way off from the actual capacity
	 * of the disk. This is only an appoximate check and
	 * is only for SCSI disks.
	 */
	if (SCSI && do_geometry_sanity_check() != 0) {
		free(new_label);
		return (-1);
	}

	/*
	 * Lock out interrupts so we do things in sync.
	 */
	enter_critical();
	/*
	 * Do the ioctl to tell the kernel the geometry.
	 */
	if (ioctl(cur_file, DKIOCSGEOM, &geom) == -1) {
		err_print("Warning: error setting drive geometry.\n");
		error = -1;
	}
	/*
	 * Write the vtoc.  At the time of this writing, our
	 * drivers convert the vtoc back to a label, and
	 * then write both the primary and backup labels.
	 * This is not a requirement, however, as we
	 * always use an ioctl to read the vtoc from the
	 * driver, so it can do as it likes.
	 */
	if (write_extvtoc(cur_file, &vtoc) != 0) {
		err_print("Warning: error writing VTOC.\n");
		error = -1;
	}

	/*
	 * Calculate where the backup labels went.  They are always on
	 * the last alternate cylinder, but some older drives put them
	 * on head 2 instead of the last head.  They are always on the
	 * first 5 odd sectors of the appropriate track.
	 */
	if (cur_ctype->ctype_flags & CF_BLABEL)
		head  = 2;
	else
		head = nhead - 1;
	/*
	 * Read and verify the backup labels.
	 */
	nbackups = 0;
	for (sec = 1; ((sec < BAD_LISTCNT * 2 + 1) && (sec < nsect));
	    sec += 2) {
		if ((*cur_ops->op_rdwr)(DIR_READ, cur_file, (diskaddr_t)
		    ((chs2bn(ncyl + acyl - 1, head, sec))
		    + solaris_offset), 1, new_label, F_NORMAL, NULL)) {
			err_print("Warning: error reading"
			    "backup label.\n");
			error = -1;
		} else {
			if (bcmp((char *)&label, new_label,
			    sizeof (struct dk_label)) == 0) {
				nbackups++;
			}
		}
	}
	if (nbackups != BAD_LISTCNT) {
		err_print("Warning: %s\n", nbackups == 0 ?
		    "no backup labels" : "some backup labels incorrect");
	}
	/*
	 * Mark the current disk as labelled and notify the kernel of what
	 * has happened.
	 */
	cur_disk->disk_flags |= DSK_LABEL;

	exit_critical();
	free(new_label);
	return (error);
}


/*
 * Read the label from the disk.
 * Do this via the read_extvtoc() library routine, then convert it to a label.
 * We also need a DKIOCGGEOM ioctl to get the disk's geometry.
 */
int
read_label(int fd, struct dk_label *label)
{
	struct extvtoc	vtoc;
	struct dk_geom	geom;
	struct dk_cinfo	dkinfo;

	if (read_extvtoc(fd, &vtoc) < 0		||
	    ioctl(fd, DKIOCGGEOM, &geom) == -1	||
	    ioctl(fd, DKIOCINFO, &dkinfo) == -1) {
		return (-1);
	}

	return (vtoc_to_label(label, &vtoc, &geom, &dkinfo));
}

int
get_disk_inquiry_prop(char *devpath, char **vid, char **pid, char **rid)
{
	char *v, *p, *r;
	di_node_t node;
	int ret = -1;

	node = di_init(devpath, DINFOCPYALL);

	if (node == DI_NODE_NIL)
		goto out;

	if (di_prop_lookup_strings(DDI_DEV_T_ANY, node,
	    "inquiry-vendor-id", &v) != 1)
		goto out;

	if (di_prop_lookup_strings(DDI_DEV_T_ANY, node,
	    "inquiry-product-id", &p) != 1)
		goto out;

	if (di_prop_lookup_strings(DDI_DEV_T_ANY, node,
	    "inquiry-revision-id", &r) != 1)
		goto out;

	*vid = strdup(v);
	*pid = strdup(p);
	*rid = strdup(r);

	if (*vid == NULL || *pid == NULL || *rid == NULL) {
		free(*vid);
		free(*pid);
		free(*rid);
		goto out;
	}

	ret = 0;

out:
	di_fini(node);
	return (ret);
}

int
get_disk_inquiry_uscsi(int fd, char **vid, char **pid, char **rid)
{
	struct scsi_inquiry inquiry;

	if (uscsi_inquiry(fd, (char *)&inquiry, sizeof (inquiry)))
		return (-1);

	*vid = strndup(inquiry.inq_vid, 8);
	*pid = strndup(inquiry.inq_pid, 16);
	*rid = strndup(inquiry.inq_revision, 4);

	if (*vid == NULL || *pid == NULL || *rid == NULL) {
		free(*vid);
		free(*pid);
		free(*rid);
		return (-1);
	}

	return (0);
}

int
get_disk_capacity(int fd, uint64_t *capacity)
{
	struct dk_minfo	minf;
	struct scsi_capacity_16	cap16;

	if (ioctl(fd, DKIOCGMEDIAINFO, &minf) == 0) {
		*capacity = minf.dki_capacity * minf.dki_lbsize / cur_blksz;
		return (0);
	}

	if (uscsi_read_capacity(fd, &cap16) == 0) {
		*capacity = cap16.sc_capacity;

		/* Since we are counting from zero, add 1 to capacity */
		(*capacity)++;

		return (0);
	}

	err_print("Fetch Capacity failed\n");
	return (-1);
}

int
get_disk_inquiry_devid(int fd, char **vid, char **pid, char **rid)
{
	ddi_devid_t	devid;
	char		*s;
	char		*v, *p;
	struct dk_cinfo	dkinfo;

	if (devid_get(fd, &devid)) {
		if (option_msg && diag_msg)
			err_print("devid_get failed\n");
		return (-1);
	}

	s = (char *)devid;

	if (ioctl(fd, DKIOCINFO, &dkinfo) == -1) {
		if (option_msg && diag_msg)
			err_print("DKIOCINFO failed\n");
		return (-1);
	}

	if (dkinfo.dki_ctype != DKC_DIRECT)
		return (-1);

	v = s+12;
	if (!(p = strchr(v, '=')))
		return (-1);
	p += 1;

	*vid = strdup(v);
	*pid = strdup(p);
	*rid = strdup("0001");
	devid_free(devid);

	if (*vid == NULL || *pid == NULL || *rid == NULL) {
		free(*vid);
		free(*pid);
		free(*rid);
		return (-1);
	}

	return (0);
}

/*
 * Issue uscsi_inquiry and read_capacity commands to
 * retrieve the disk's Vendor, Product, Revision and
 * Capacity information.
 */
int
get_disk_info(int fd, struct efi_info *label, struct disk_info *disk_info)
{
	(void) get_disk_capacity(fd, &label->capacity);

	if (get_disk_inquiry_prop(disk_info->devfs_name,
	    &label->vendor, &label->product, &label->revision) != 0) {
		if (get_disk_inquiry_devid(fd, &label->vendor, &label->product,
		    &label->revision) != 0) {
			if (get_disk_inquiry_uscsi(fd, &label->vendor,
			    &label->product, &label->revision) != 0) {
				label->vendor = strdup("Unknown");
				label->product = strdup("Unknown");
				label->revision = strdup("0001");
				if (label->vendor == NULL ||
				    label->product == NULL ||
				    label->revision == NULL) {
					free(label->vendor);
					free(label->product);
					free(label->revision);
					return (-1);
				}
			}
		}
	}

	return (0);
}

int
read_efi_label(int fd, struct efi_info *label, struct disk_info *disk_info)
{
	struct dk_gpt	*vtoc64;

	/* This could fail if there is no label already */
	if (efi_alloc_and_read(fd, &vtoc64) < 0) {
		return (-1);
	}
	if (vtoc64_to_label(label, vtoc64) != 0) {
		err_print("vtoc64_to_label failed\n");
		return (-1);
	}
	efi_free(vtoc64);
	if (get_disk_info(fd, label, disk_info) != 0) {
		return (-1);
	}
	return (0);
}


/*
 * We've read a 64-bit label which has no geometry information.  Use
 * some heuristics to fake up a geometry that would match the disk in
 * order to make the rest of format(8) happy.
 */
static int
vtoc64_to_label(struct efi_info *label, struct dk_gpt *vtoc)
{
	int		i, nparts = 0;
	struct dk_gpt	*lmap;

	(void) memset((char *)label, 0, sizeof (struct efi_info));

	/* XXX do a sanity check here for nparts */
	nparts = vtoc->efi_nparts;
	lmap = (struct dk_gpt *) calloc(1, (sizeof (struct dk_part) *
	    nparts) + sizeof (struct dk_gpt));
	if (lmap == NULL) {
		err_print("vtoc64_to_label: unable to allocate lmap\n");
		fullabort();
	}
	label->e_parts = lmap;

	/*
	 * Copy necessary portions
	 * XXX Maybe we can use memcpy() ??
	 */
	lmap->efi_version = vtoc->efi_version;
	lmap->efi_nparts = vtoc->efi_nparts;
	lmap->efi_part_size = vtoc->efi_part_size;
	lmap->efi_lbasize = vtoc->efi_lbasize;
	lmap->efi_last_lba = vtoc->efi_last_lba;
	lmap->efi_first_u_lba = vtoc->efi_first_u_lba;
	lmap->efi_last_u_lba = vtoc->efi_last_u_lba;
	lmap->efi_altern_lba = vtoc->efi_altern_lba;
	lmap->efi_flags = vtoc->efi_flags;
	(void) memcpy((uchar_t *)&lmap->efi_disk_uguid,
	    (uchar_t *)&vtoc->efi_disk_uguid, sizeof (struct uuid));

	for (i = 0; i < nparts; i++) {
		lmap->efi_parts[i].p_tag = vtoc->efi_parts[i].p_tag;
		lmap->efi_parts[i].p_flag = vtoc->efi_parts[i].p_flag;
		lmap->efi_parts[i].p_start = vtoc->efi_parts[i].p_start;
		lmap->efi_parts[i].p_size = vtoc->efi_parts[i].p_size;
		(void) memcpy((uchar_t *)&lmap->efi_parts[i].p_uguid,
		    (uchar_t *)&vtoc->efi_parts[i].p_uguid,
		    sizeof (struct uuid));
		if (vtoc->efi_parts[i].p_tag == V_RESERVED) {
			bcopy(vtoc->efi_parts[i].p_name,
			    lmap->efi_parts[i].p_name, LEN_DKL_VVOL);
		}
	}
	return (0);
}

/*
 * Convert vtoc/geom to label.
 */
static int
vtoc_to_label(struct dk_label *label, struct extvtoc *vtoc,
    struct dk_geom *geom, struct dk_cinfo *cinfo)
{
#if defined(_SUNOS_VTOC_8)
	struct dk_map32		*lmap;
#elif defined(_SUNOS_VTOC_16)
	struct dkl_partition	*lmap;
#else
#error No VTOC format defined.
#endif			/* defined(_SUNOS_VTOC_8) */

	struct extpartition	*vpart;
	ulong_t			nblks;
	int			i;

	(void) memset((char *)label, 0, sizeof (struct dk_label));

	/*
	 * Sanity-check the vtoc
	 */
	if (vtoc->v_sanity != VTOC_SANE ||
	    vtoc->v_nparts != V_NUMPAR) {
		return (-1);
	}

	/*
	 * Sanity check of geometry
	 */
	if (geom->dkg_ncyl == 0 || geom->dkg_nhead == 0 ||
	    geom->dkg_nsect == 0) {
		return (-1);
	}

	label->dkl_magic = DKL_MAGIC;

	/*
	 * Copy necessary portions of the geometry information
	 */
	label->dkl_rpm = geom->dkg_rpm;
	label->dkl_pcyl = geom->dkg_pcyl;
	label->dkl_apc = geom->dkg_apc;
	label->dkl_intrlv = geom->dkg_intrlv;
	label->dkl_ncyl = geom->dkg_ncyl;
	label->dkl_acyl = geom->dkg_acyl;

#if defined(_SUNOS_VTOC_16)
	label->dkl_bcyl = geom->dkg_bcyl;
#endif			/* defined(_SUNOS_VTOC_16) */

	label->dkl_nhead = geom->dkg_nhead;
	label->dkl_nsect = geom->dkg_nsect;

#if defined(_SUNOS_VTOC_8)
	label->dkl_obs1 = geom->dkg_obs1;
	label->dkl_obs2 = geom->dkg_obs2;
	label->dkl_obs3 = geom->dkg_obs3;
#endif			/* defined(_SUNOS_VTOC_8) */

	label->dkl_write_reinstruct = geom->dkg_write_reinstruct;
	label->dkl_read_reinstruct = geom->dkg_read_reinstruct;

	/*
	 * Copy vtoc structure fields into the disk label dk_vtoc
	 */
	label->dkl_vtoc.v_sanity = vtoc->v_sanity;
	label->dkl_vtoc.v_nparts = vtoc->v_nparts;
	label->dkl_vtoc.v_version = vtoc->v_version;

	(void) memcpy(label->dkl_vtoc.v_volume, vtoc->v_volume,
	    LEN_DKL_VVOL);
	for (i = 0; i < V_NUMPAR; i++) {
		label->dkl_vtoc.v_part[i].p_tag = vtoc->v_part[i].p_tag;
		label->dkl_vtoc.v_part[i].p_flag = vtoc->v_part[i].p_flag;
		label->dkl_vtoc.v_timestamp[i] = vtoc->timestamp[i];
	}

	for (i = 0; i < 10; i++)
		label->dkl_vtoc.v_reserved[i] = vtoc->v_reserved[i];

	label->dkl_vtoc.v_bootinfo[0] = vtoc->v_bootinfo[0];
	label->dkl_vtoc.v_bootinfo[1] = vtoc->v_bootinfo[1];
	label->dkl_vtoc.v_bootinfo[2] = vtoc->v_bootinfo[2];

	(void) memcpy(label->dkl_asciilabel, vtoc->v_asciilabel,
	    LEN_DKL_ASCII);

	/*
	 * Note the conversion from starting sector number
	 * to starting cylinder number.
	 * Return error if division results in a remainder.
	 *
	 * Note: don't check, if probing virtual disk in Xen
	 * for that virtual disk will use fabricated # of headers
	 * and sectors per track which may cause the capacity
	 * not multiple of # of blocks per cylinder
	 */
#if defined(_SUNOS_VTOC_8)
	lmap = label->dkl_map;

#elif defined(_SUNOS_VTOC_16)
	lmap = label->dkl_vtoc.v_part;
#else
#error No VTOC format defined.
#endif			/* defined(_SUNOS_VTOC_8) */

	vpart = vtoc->v_part;

	nblks = label->dkl_nsect * label->dkl_nhead;

	for (i = 0; i < NDKMAP; i++, lmap++, vpart++) {
		if (cinfo->dki_ctype != DKC_VBD) {
			if ((vpart->p_start % nblks) != 0 ||
			    (vpart->p_size % nblks) != 0) {
				return (-1);
			}
		}
#if defined(_SUNOS_VTOC_8)
		lmap->dkl_cylno = (blkaddr32_t)(vpart->p_start / nblks);
		lmap->dkl_nblk = (blkaddr32_t)vpart->p_size;

#elif defined(_SUNOS_VTOC_16)
		lmap->p_start = (blkaddr32_t)vpart->p_start;
		lmap->p_size = (blkaddr32_t)vpart->p_size;
#else
#error No VTOC format defined.
#endif			/* defined(_SUNOS_VTOC_8) */
	}

	/*
	 * Finally, make a checksum
	 */
	(void) checksum(label, CK_MAKESUM);

#ifdef DEBUG
	if (option_msg && diag_msg)
		dump_label(label);
#endif
	return (0);
}



/*
 * Extract a vtoc structure out of a valid label
 */
int
label_to_vtoc(struct extvtoc *vtoc, struct dk_label *label)
{
#if defined(_SUNOS_VTOC_8)
	struct dk_map2		*lpart;
	struct dk_map32		*lmap;
	ulong_t			nblks;

#elif defined(_SUNOS_VTOC_16)
	struct dkl_partition	*lpart;
#else
#error No VTOC format defined.
#endif				/* defined(_SUNOS_VTOC_8) */

	struct extpartition	*vpart;
	int			i;

	(void) memset((char *)vtoc, 0, sizeof (struct extvtoc));

	switch (label->dkl_vtoc.v_version) {
	case 0:
		/*
		 * No valid vtoc information in the label.
		 * Construct default p_flags and p_tags.
		 */
		vpart = vtoc->v_part;
		for (i = 0; i < V_NUMPAR; i++, vpart++) {
			vpart->p_tag = default_vtoc_map[i].p_tag;
			vpart->p_flag = default_vtoc_map[i].p_flag;
		}
		break;

	case V_VERSION:
		vpart = vtoc->v_part;
		lpart = label->dkl_vtoc.v_part;
		for (i = 0; i < V_NUMPAR; i++, vpart++, lpart++) {
			vpart->p_tag = lpart->p_tag;
			vpart->p_flag = lpart->p_flag;

#if defined(_SUNOS_VTOC_16)
			vpart->p_start = (diskaddr_t)lpart->p_start;
			vpart->p_size = (diskaddr_t)lpart->p_size;
#endif	/* defined(_SUNOS_VTOC_16) */
			vtoc->timestamp[i] = label->dkl_vtoc.v_timestamp[i];
		}
		(void) memcpy(vtoc->v_volume, label->dkl_vtoc.v_volume,
		    LEN_DKL_VVOL);

		for (i = 0; i < 10; i++)
			vtoc->v_reserved[i] = label->dkl_vtoc.v_reserved[i];

		vtoc->v_bootinfo[0] = label->dkl_vtoc.v_bootinfo[0];
		vtoc->v_bootinfo[1] = label->dkl_vtoc.v_bootinfo[1];
		vtoc->v_bootinfo[2] = label->dkl_vtoc.v_bootinfo[2];
		break;

	default:
		return (-1);
	}

	/*
	 * XXX - this looks wrong to me....
	 * why are these values hardwired, rather than returned from
	 * the real disk label?
	 */
	vtoc->v_sanity = VTOC_SANE;
	vtoc->v_version = V_VERSION;
	vtoc->v_sectorsz = cur_blksz;
	vtoc->v_nparts = V_NUMPAR;

	(void) memcpy(vtoc->v_asciilabel, label->dkl_asciilabel,
	    LEN_DKL_ASCII);

#if defined(_SUNOS_VTOC_8)
	/*
	 * Convert partitioning information.
	 * Note the conversion from starting cylinder number
	 * to starting sector number.
	 */
	lmap = label->dkl_map;
	vpart = vtoc->v_part;
	nblks = label->dkl_nsect * label->dkl_nhead;
	for (i = 0; i < V_NUMPAR; i++, vpart++, lmap++) {
		vpart->p_start = (diskaddr_t)(lmap->dkl_cylno * nblks);
		vpart->p_size = (diskaddr_t)lmap->dkl_nblk;
	}
#endif			/* defined(_SUNOS_VTOC_8) */

	return (0);
}

/*
 * Input: File descriptor
 * Output: 1 if disk has an EFI label, 0 otherwise.
 */

int
is_efi_type(int fd)
{
	struct extvtoc vtoc;

	if (read_extvtoc(fd, &vtoc) == VT_ENOTSUP) {
		/* assume the disk has EFI label */
		return (1);
	}
	return (0);
}

#ifdef	DEBUG
static void
dump_label(struct dk_label *label)
{
	int		i;

	fmt_print("%s\n", label->dkl_asciilabel);

	fmt_print("version:  %d\n", label->dkl_vtoc.v_version);
	fmt_print("volume:   ");
	for (i = 0; i < LEN_DKL_VVOL; i++) {
		if (label->dkl_vtoc.v_volume[i] == 0)
			break;
		fmt_print("%c", label->dkl_vtoc.v_volume[i]);
	}
	fmt_print("\n");
	fmt_print("v_nparts: %d\n", label->dkl_vtoc.v_nparts);
	fmt_print("v_sanity: %lx\n", label->dkl_vtoc.v_sanity);

#if defined(_SUNOS_VTOC_8)
	fmt_print("rpm:      %d\n", label->dkl_rpm);
	fmt_print("pcyl:     %d\n", label->dkl_pcyl);
	fmt_print("apc:      %d\n", label->dkl_apc);
	fmt_print("obs1:     %d\n", label->dkl_obs1);
	fmt_print("obs2:     %d\n", label->dkl_obs2);
	fmt_print("intrlv:   %d\n", label->dkl_intrlv);
	fmt_print("ncyl:     %d\n", label->dkl_ncyl);
	fmt_print("acyl:     %d\n", label->dkl_acyl);
	fmt_print("nhead:    %d\n", label->dkl_nhead);
	fmt_print("nsect:    %d\n", label->dkl_nsect);
	fmt_print("obs3:     %d\n", label->dkl_obs3);
	fmt_print("obs4:     %d\n", label->dkl_obs4);

#elif defined(_SUNOS_VTOC_16)
	fmt_print("rpm:      %d\n", label->dkl_rpm);
	fmt_print("pcyl:     %d\n", label->dkl_pcyl);
	fmt_print("apc:      %d\n", label->dkl_apc);
	fmt_print("intrlv:   %d\n", label->dkl_intrlv);
	fmt_print("ncyl:     %d\n", label->dkl_ncyl);
	fmt_print("acyl:     %d\n", label->dkl_acyl);
	fmt_print("nhead:    %d\n", label->dkl_nhead);
	fmt_print("nsect:    %d\n", label->dkl_nsect);
	fmt_print("bcyl:     %d\n", label->dkl_bcyl);
	fmt_print("skew:     %d\n", label->dkl_skew);
#else
#error No VTOC format defined.
#endif				/* defined(_SUNOS_VTOC_8) */
	fmt_print("magic:    %0x\n", label->dkl_magic);
	fmt_print("cksum:    %0x\n", label->dkl_cksum);

	for (i = 0; i < NDKMAP; i++) {

#if defined(_SUNOS_VTOC_8)
		fmt_print("%c:        cyl=%d, blocks=%d", i+'a',
		    label->dkl_map[i].dkl_cylno,
		    label->dkl_map[i].dkl_nblk);

#elif defined(_SUNOS_VTOC_16)
		fmt_print("%c:        start=%u, blocks=%u", i+'a',
		    label->dkl_vtoc.v_part[i].p_start,
		    label->dkl_vtoc.v_part[i].p_size);
#else
#error No VTOC format defined.
#endif				/* defined(_SUNOS_VTOC_8) */

		fmt_print(",  tag=%d,  flag=%d",
		    label->dkl_vtoc.v_part[i].p_tag,
		    label->dkl_vtoc.v_part[i].p_flag);
		fmt_print("\n");
	}

	fmt_print("read_reinstruct:  %d\n", label->dkl_read_reinstruct);
	fmt_print("write_reinstruct: %d\n", label->dkl_write_reinstruct);

	fmt_print("bootinfo: ");
	for (i = 0; i < 3; i++) {
		fmt_print("0x%x ", label->dkl_vtoc.v_bootinfo[i]);
	}
	fmt_print("\n");

	fmt_print("reserved: ");
	for (i = 0; i < 10; i++) {
		if ((i % 4) == 3)
			fmt_print("\n");
		fmt_print("0x%x ", label->dkl_vtoc.v_reserved[i]);
	}
	fmt_print("\n");

	fmt_print("timestamp:\n");
	for (i = 0; i < NDKMAP; i++) {
		if ((i % 4) == 3)
			fmt_print("\n");
		fmt_print("0x%x ", label->dkl_vtoc.v_timestamp[i]);
	}
	fmt_print("\n");

	fmt_print("pad:\n");
	dump("", label->dkl_pad, LEN_DKL_PAD, HEX_ONLY);

	fmt_print("\n\n");
}
#endif	/* DEBUG */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 * Copyright 2015 Nexenta Systems, Inc. All rights reserved.
 */

#ifndef	_LABEL_H
#define	_LABEL_H

#ifdef	__cplusplus
extern "C" {
#endif

/*
 *	Prototypes for ANSI C compilers
 */
int	checklabel(struct dk_label *);
int	checksum(struct dk_label *, int);
int	trim_id(char *);
int	write_label(void);
int	read_label(int, struct dk_label *);
int	read_efi_label(int, struct efi_info *, struct disk_info *);
int	get_disk_inquiry_prop(char *, char **, char **, char **);
int	get_disk_info(int, struct efi_info *, struct disk_info *);
int	label_to_vtoc(struct extvtoc *, struct dk_label *);
int	SMI_vtoc_to_EFI(int, struct dk_gpt **);
void	efi_err_check(struct dk_gpt *);
extern int	is_efi_type(int);

#ifdef	__cplusplus
}
#endif

#endif	/* _LABEL_H */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 * Copyright (c) 2016 by Delphix. All rights reserved.
 */

/*
 * This file contains the main entry point of the program and other
 * routines relating to the general flow.
 */
#include "global.h"
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <memory.h>
#include <string.h>
#include <errno.h>

#ifdef sparc
#include <sys/hdio.h>
#include <sys/dkbad.h>
#endif

#include <sys/time.h>
#include "main.h"
#include "analyze.h"
#include "menu.h"
#include "param.h"
#include "misc.h"
#include "startup.h"
#include "menu_command.h"
#include "menu_partition.h"
#include "prompts.h"
#include "checkdev.h"
#include "label.h"

extern	struct menu_item menu_command[];
uint_t	apc;
uint_t	solaris_offset;
char	cur_menu;
char	last_menu;
void	*pattern_buf;
FILE	*log_file;
void	*cur_buf;
struct disk_info *cur_disk;
struct ctlr_ops *cur_ops;
struct ctlr_info *cur_ctlr;
struct ctlr_type *cur_ctype;
struct disk_type *cur_dtype;
struct partition_info *cur_parts;
struct defect_list cur_list;
int	cur_file;
int	cur_flags;
int	cur_label;
uint_t	pcyl;
uint_t	ncyl;
uint_t	acyl;
uint_t	bcyl;
uint_t	nhead;
uint_t	phead;
uint_t	nsect;
uint_t	psect;

#ifdef	__STDC__

/*
 *	Local prototypes for ANSI C compilers
 */
static void	get_disk_characteristics(void);


#else	/* __STDC__ */

/*
 *	Local prototypes for non-ANSI C compilers
 */
static void	get_disk_characteristics();

#endif	/* __STDC__ */

/*
 * This is the main entry point.
 */
int
main(int argc, char *argv[])
{
	int	i;
	int	ret_code = 1;
	char	**arglist;
	struct	disk_info *disk = NULL;
	struct	disk_type *type, *oldtype;
	struct	partition_info *parts;
	struct	sigaction act;

	solaris_offset = 0;
	/*
	 * Initialize cur_ctype to avoid null pointer dereference
	 * in auto_efi_sense().
	 */
	cur_ctype = NULL;
	/*
	 * Decode the command line options.
	 */
	i = do_options(argc, argv);
	/*
	 * If we are to run from a command file, open it up.
	 */
	if (option_f) {
		if (freopen(option_f, "r", stdin) == NULL) {
			err_print("Unable to open command file '%s'.\n",
			    option_f);
			fullabort();
		}
	}
	/*
	 * If we are logging, open the log file.
	 */
	if (option_l) {
		if ((log_file = fopen(option_l, "w")) == NULL) {
			err_print("Unable to open log file '%s'.\n",
			    option_l);
			fullabort();
		}
	}
	/*
	 * Read in the data file and initialize the hardware structs.
	 */
	sup_init();
	/*
	 * If there are no disks on the command line, search the
	 * appropriate device directory for character devices that
	 * look like disks.
	 */
	if (i < 0) {
		arglist = NULL;
	/*
	 * There were disks on the command line.  They comprise the
	 * search list.
	 */
	} else {
		arglist = &argv[i];
	}
	/*
	 * Perform the search for disks.
	 */
	do_search(arglist);
	/*
	 * Catch ctrl-C and ctrl-Z so critical sections can be
	 * implemented.  We use sigaction, as this sets up the
	 * signal handler permanently, and also automatically
	 * restarts any interrupted system call.
	 */
	act.sa_handler = cmdabort;
	(void) memset(&act.sa_mask, 0, sizeof (sigset_t));
	act.sa_flags = SA_RESTART | SA_NODEFER;
	if (sigaction(SIGINT, &act, NULL) == -1) {
		err_print("sigaction(SIGINT) failed - %s\n",
		    strerror(errno));
		fullabort();
	}

	act.sa_handler = onsusp;
	(void) memset(&act.sa_mask, 0, sizeof (sigset_t));
	act.sa_flags = SA_RESTART | SA_NODEFER;
	if (sigaction(SIGTSTP, &act, NULL) == -1) {
		err_print("sigaction(SIGTSTP) failed - %s\n",
		    strerror(errno));
		fullabort();
	}

	act.sa_handler = onalarm;
	(void) memset(&act.sa_mask, 0, sizeof (sigset_t));
	act.sa_flags = SA_RESTART;
	if (sigaction(SIGALRM, &act, NULL) == -1) {
		err_print("sigaction(SIGALRM) failed - %s\n",
		    strerror(errno));
		fullabort();
	}

	/*
	 * If there was only 1 disk on the command line, mark it
	 * to be the current disk.  If it wasn't found, it's an error.
	 */
	if (i == argc - 1) {
		disk = disk_list;
		if (disk == NULL) {
			err_print("Unable to find specified disk '%s'.\n",
			    argv[i]);
			fullabort();
		}
	}
	/*
	 * A disk was forced on the command line.
	 */
	if (option_d) {
		/*
		 * Find it in the list of found disks and mark it to
		 * be the current disk.
		 */
		for (disk = disk_list; disk != NULL; disk = disk->disk_next)
			if (diskname_match(option_d, disk))
				break;
		/*
		 * If it wasn't found, it's an error.
		 */
		if (disk == NULL) {
			err_print("Unable to find specified disk '%s'.\n",
			    option_d);
			fullabort();
		}
	}
	/*
	 * A disk type was forced on the command line.
	 */
	if (option_t != NULL) {
		/*
		 * Only legal if a disk was also forced.
		 */
		if (disk == NULL) {
			err_print("Must specify disk as well as type.\n");
			fullabort();
		}
		oldtype = disk->disk_type;
		/*
		 * Find the specified type in the list of legal types
		 * for the disk.
		 */
		for (type = disk->disk_ctlr->ctlr_ctype->ctype_dlist;
		    type != NULL; type = type->dtype_next)
			if (strcmp(option_t, type->dtype_asciilabel) == 0)
				break;
		/*
		 * If it wasn't found, it's an error.
		 */
		if (type == NULL) {
			err_print(
"Specified type '%s' is not a known type.\n", option_t);
			fullabort();
		}
		/*
		 * If the specified type is not the same as the type
		 * in the disk label, update the type and nullify the
		 * partition map.
		 */
		if (type != oldtype) {
			disk->disk_type = type;
			disk->disk_parts = NULL;
		}
	}
	/*
	 * A partition map was forced on the command line.
	 */
	if (option_p) {
		/*
		 * Only legal if both disk and type were also forced.
		 */
		if (disk == NULL || disk->disk_type == NULL) {
			err_print("Must specify disk and type as well ");
			err_print("as partitiion.\n");
			fullabort();
		}
		/*
		 * Find the specified map in the list of legal maps
		 * for the type.
		 */
		for (parts = disk->disk_type->dtype_plist; parts != NULL;
		    parts = parts->pinfo_next)
			if (strcmp(option_p, parts->pinfo_name) == 0)
				break;
		/*
		 * If it wasn't found, it's an error.
		 */
		if (parts == NULL) {
			err_print(
"Specified table '%s' is not a known table.\n", option_p);
			fullabort();
		}
		/*
		 * Update the map.
		 */
		disk->disk_parts = parts;
	}
	/*
	 * If a disk was marked to become current, initialize the state
	 * to make it current.  If not, ask user to pick one.
	 */
	if (disk != NULL) {
		init_globals(disk);
	} else if (option_f == 0 && option_d == 0) {
		while (ret_code) {
			ret_code = c_disk();
		}
	}

#ifdef	BUG1134748
	/*
	 * if -f command-file is specified, check for disk and disktype
	 * input also. For SCSI disks, the type input may not be needed
	 * since format would have figured that using inquiry information.
	 */
	if (option_f) {
		if (cur_disk == NULL) {
			err_print("Must specify a disk using -d option.\n");
			fullabort();
		}
		if (cur_dtype == NULL) {
			err_print("Must specify disk as well as type.\n");
			fullabort();
		}
	}
#endif	/* BUG1134748 */

	/*
	 * Run the command menu.
	 */
	cur_menu = last_menu = 0;
	run_menu(menu_command, "FORMAT", "format", 1);

	/*
	 * normal ending. Explicitly return(0);
	 */
	return (0);
}

/*
 * This routine initializes the internal state to ready it for a new
 * current disk.  There are a zillion state variables that store
 * information on the current disk, and they must all be updated.
 * We also tell SunOS about the disk, since it may not know if the
 * disk wasn't labeled at boot time.
 */
void
init_globals(struct disk_info *disk)
{
	int		status;
	int		found_mount;
	int		found_inuse;
#ifdef sparc
	int		i;
	caddr_t		bad_ptr = (caddr_t)&badmap;
#endif

	/*
	 * If there was an old current disk, close the file for it.
	 */
	if (cur_disk != NULL)
		(void) close(cur_file);
	/*
	 * Kill off any defect lists still lying around.
	 */
	kill_deflist(&cur_list);
	kill_deflist(&work_list);
	/*
	 * If there were any buffers, free them up.
	 */
	if ((char *)cur_buf != NULL) {
		destroy_data((char *)cur_buf);
		cur_buf = NULL;
	}
	if ((char *)pattern_buf != NULL) {
		destroy_data((char *)pattern_buf);
		pattern_buf = NULL;
	}
	/*
	 * Fill in the hardware struct pointers for the new disk.
	 */
	cur_disk = disk;
	cur_dtype = cur_disk->disk_type;
	cur_label = cur_disk->label_type;
	cur_ctlr = cur_disk->disk_ctlr;
	cur_parts = cur_disk->disk_parts;
	cur_blksz = cur_disk->disk_lbasize;
	cur_ctype = cur_ctlr->ctlr_ctype;
	cur_ops = cur_ctype->ctype_ops;
	cur_flags = 0;
	/*
	 * Open a file for the new disk.
	 */
	if ((cur_file = open_disk(cur_disk->disk_path,
	    O_RDWR | O_NDELAY)) < 0) {
		err_print(
"Error: can't open selected disk '%s'.\n", cur_disk->disk_name);
		fullabort();
	}
#ifdef sparc
	/*
	 * If the new disk uses bad-144, initialize the bad block table.
	 */
	if (cur_ctlr->ctlr_flags & DKI_BAD144) {
		badmap.bt_mbz = badmap.bt_csn = badmap.bt_flag = 0;
		for (i = 0; i < NDKBAD; i++) {
			badmap.bt_bad[i].bt_cyl = -1;
			badmap.bt_bad[i].bt_trksec = -1;
		}
	}
#endif
	/*
	 * If the type of the new disk is known...
	 */
	if (cur_dtype != NULL) {
		/*
		 * Initialize the physical characteristics.
		 * If need disk specs, prompt for undefined disk
		 * characteristics.  If running from a file,
		 * use defaults.
		 */
		if (cur_dtype->dtype_flags & DT_NEED_SPEFS) {
			get_disk_characteristics();
			cur_dtype->dtype_flags &= ~DT_NEED_SPEFS;
		}

		ncyl = cur_dtype->dtype_ncyl;
		acyl = cur_dtype->dtype_acyl;
		pcyl = cur_dtype->dtype_pcyl;
		nhead = cur_dtype->dtype_nhead;
		nsect = cur_dtype->dtype_nsect;
		phead = cur_dtype->dtype_phead;
		psect = cur_dtype->dtype_psect;
		/*
		 * Alternates per cylinder are forced to 0 or 1,
		 * independent of what the label says.  This works
		 * because we know which ctlr we are dealing with.
		 */
		if (cur_ctype->ctype_flags & CF_APC)
			apc = 1;
		else
			apc = 0;
		/*
		 * Initialize the surface analysis info.  We always start
		 * out with scan set for the whole disk.  Note,
		 * for SCSI disks, we can only scan the data area.
		 */
		scan_lower = 0;
		scan_size = BUF_SECTS;
		if ((cur_ctype->ctype_flags & CF_SCSI) &&
		    (cur_disk->label_type == L_TYPE_SOLARIS)) {
			scan_upper = datasects() - 1;
		} else if (cur_disk->label_type == L_TYPE_SOLARIS) {
			scan_upper = physsects() - 1;
		} else if (cur_disk->label_type == L_TYPE_EFI) {
			scan_upper = cur_parts->etoc->efi_last_lba;
		}

		/*
		 * Allocate the buffers.
		 */
		cur_buf = (void *) zalloc(BUF_SECTS * cur_blksz);
		pattern_buf = (void *) zalloc(BUF_SECTS * cur_blksz);

		/*
		 * Tell the user which disk they selected.
		 */
		if (chk_volname(cur_disk)) {
			fmt_print("selecting %s: ", cur_disk->disk_name);
			print_volname(cur_disk);
			fmt_print("\n");
		} else {
			fmt_print("selecting %s\n", cur_disk->disk_name);
		}

		/*
		 * If the drive is formatted...
		 */
		if ((*cur_ops->op_ck_format)()) {
			/*
			 * Mark it formatted.
			 */
			cur_flags |= DISK_FORMATTED;
			/*
			 * Read the defect list, if we have one.
			 */
			if (!EMBEDDED_SCSI) {
				read_list(&cur_list);
			}
#ifdef sparc
			/*
			 * If the disk does BAD-144, we do an ioctl to
			 * tell SunOS about the bad block table.
			 */
			if (cur_ctlr->ctlr_flags & DKI_BAD144) {
				if (ioctl(cur_file, HDKIOCSBAD, &bad_ptr)) {
					err_print(
"Warning: error telling SunOS bad block map table.\n");
				}
			}
#endif
			fmt_print("[disk formatted");
			if (!EMBEDDED_SCSI) {
				if (cur_list.list != NULL) {
					fmt_print(", defect list found");
				} else {
					fmt_print(", no defect list found");
				}
			}
			fmt_print("]");
		/*
		 * Drive wasn't formatted.  Tell the user in case they
		 * disagree.
		 */
		} else if (EMBEDDED_SCSI) {
			fmt_print("[disk unformatted]");
		} else {
			/*
			 * Make sure the user is serious.  Note, for
			 * SCSI disks since this is instantaneous, we
			 * will just do it and not ask for confirmation.
			 */
			status = 0;
			if (!(cur_ctype->ctype_flags & CF_CONFIRM)) {
				if (check("\n\
Ready to get manufacturer's defect list from unformatted drive.\n\
This cannot be interrupted and takes a long while.\n\
Continue"))
					status = 1;
				else
					fmt_print(
				"Extracting manufacturer's defect list...");
			}
			/*
			 * Extract manufacturer's defect list.
			 */
			if ((status == 0) && (cur_ops->op_ex_man != NULL)) {
				status = (*cur_ops->op_ex_man)(&cur_list);
			} else {
				status = 1;
			}
			fmt_print("[disk unformatted");
			if (status != 0) {
				fmt_print(", no defect list found]");
			} else {
				fmt_print(", defect list found]");
			}
		}
	} else {
		/*
		 * Disk type is not known.
		 * Initialize physical characteristics to 0 and tell the
		 * user we don't know what type the disk is.
		 */
		ncyl = acyl = nhead = nsect = psect = 0;
	}

	fmt_print("\n");

	/*
	 * Check to see if there are any mounted file systems on the
	 * disk.  If there are, print a warning.
	 */
	if ((found_mount = checkmount((diskaddr_t)-1, (diskaddr_t)-1)) != 0)
		err_print("Warning: Current Disk has mounted partitions.\n");

	/*
	 * If any part of this device is also part of an SVM, VxVM or
	 * Live Upgrade device, print a warning.
	 */
	found_inuse =  checkdevinuse(cur_disk->disk_name, (diskaddr_t)-1,
	    (diskaddr_t)-1, 1, 0);

	/*
	 * Get the Solaris Fdisk Partition information
	 */
	(void) copy_solaris_part(&cur_disk->fdisk_part);

	if (!found_mount && !found_inuse &&
	    cur_disk->label_type == L_TYPE_EFI) {

		/*
		 * If alter_lba is 1, we are using the backup label.
		 * Since we can locate the backup label by disk capacity,
		 * there must be no space expanded after backup label.
		 */
		if ((cur_parts->etoc->efi_altern_lba != 1) &&
		    (cur_parts->etoc->efi_altern_lba <
		    cur_parts->etoc->efi_last_lba)) {

			/*
			 * Lun expansion detected. Prompt user now and actually
			 * adjust the label in <partition> command.
			 */
			fmt_print(
"Note: capacity in disk label is smaller than the real disk capacity.\n\
Select <partition> <expand> to adjust the label capacity. \n");
		}
	}
}


/*
 * Prompt for some undefined disk characteristics.
 * Used when there is no disk definition, but the
 * disk has a valid label, so basically we're
 * prompting for everything that isn't in the label.
 */
static void
get_disk_characteristics(void)
{
	/*
	 * The need_spefs flag is used to tell us that this disk
	 * is not a known type and the ctlr specific info must
	 * be prompted for.  We only prompt for the info that applies
	 * to this ctlr.
	 */
	assert(cur_dtype->dtype_flags & DT_NEED_SPEFS);

	/*
	 * If we're running with input from a file, use
	 * reasonable defaults, since prompting for the
	 * information will probably mess things up.
	 */
	if (option_f) {
		cur_dtype->dtype_pcyl = ncyl + acyl;
		cur_dtype->dtype_rpm = AVG_RPM;
		cur_dtype->dtype_bpt = INFINITY;
		cur_dtype->dtype_phead = 0;
		cur_dtype->dtype_psect = 0;
		cur_dtype->dtype_cyl_skew = 0;
		cur_dtype->dtype_trk_skew = 0;
		cur_dtype->dtype_trks_zone = 0;
		cur_dtype->dtype_atrks = 0;
		cur_dtype->dtype_asect = 0;
		cur_dtype->dtype_cache = 0;
		cur_dtype->dtype_threshold = 0;
		cur_dtype->dtype_prefetch_min = 0;
		cur_dtype->dtype_prefetch_max = 0;

		if (cur_ctype->ctype_flags & CF_SMD_DEFS) {
			cur_dtype->dtype_bps = AVG_BPS;
		}
	} else {

		cur_dtype->dtype_pcyl = get_pcyl(ncyl, cur_dtype->dtype_acyl);
		cur_dtype->dtype_bpt = get_bpt(cur_dtype->dtype_nsect,
		    &cur_dtype->dtype_options);
		cur_dtype->dtype_rpm = get_rpm();
		cur_dtype->dtype_fmt_time =
		    get_fmt_time(&cur_dtype->dtype_options);
		cur_dtype->dtype_cyl_skew =
		    get_cyl_skew(&cur_dtype->dtype_options);
		cur_dtype->dtype_trk_skew =
		    get_trk_skew(&cur_dtype->dtype_options);
		cur_dtype->dtype_trks_zone =
		    get_trks_zone(&cur_dtype->dtype_options);
		cur_dtype->dtype_atrks = get_atrks(&cur_dtype->dtype_options);
		cur_dtype->dtype_asect = get_asect(&cur_dtype->dtype_options);
		cur_dtype->dtype_cache = get_cache(&cur_dtype->dtype_options);
		cur_dtype->dtype_threshold =
		    get_threshold(&cur_dtype->dtype_options);
		cur_dtype->dtype_prefetch_min =
		    get_min_prefetch(&cur_dtype->dtype_options);
		cur_dtype->dtype_prefetch_max =
		    get_max_prefetch(cur_dtype->dtype_prefetch_min,
		    &cur_dtype->dtype_options);
		cur_dtype->dtype_phead =
		    get_phead(nhead, &cur_dtype->dtype_options);
		cur_dtype->dtype_psect = get_psect(&cur_dtype->dtype_options);
		cur_dtype->dtype_bps = get_bps();
#ifdef sparc
		cur_dtype->dtype_dr_type = 0;
#endif
	}
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef	_MAIN_H
#define	_MAIN_H

#ifdef	__cplusplus
extern "C" {
#endif

/*
 *	Prototypes for ANSI C compilers
 */
int	main(int argc, char *argv[]);
int	notify_unix(void);
void	init_globals(struct disk_info *disk);

#ifdef	__cplusplus
}
#endif

#endif	/* _MAIN_H */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * This file contains routines relating to running the menus.
 */
#include <string.h>
#include "global.h"
#include "menu.h"
#include "misc.h"

static int	(*find_enabled_menu_item(struct menu_item *, int))(void);

static char	cur_title[MAXPATHLEN];

/*
 * This routine takes a menu struct and concatenates the
 * command names into an array of strings describing the menu.
 * All menus have a 'quit' command at the bottom to exit the menu.
 */
char **
create_menu_list(struct menu_item *menu)
{
	struct menu_item *mptr;
	char	**cpptr;
	char	**list;
	int		nitems;

	/*
	 * A minimum list consists of the quit command, followed
	 * by a terminating null.
	 */
	nitems = 2;
	/*
	 * Count the number of active commands in the menu and allocate
	 * space for the array of pointers.
	 */
	for (mptr = menu; mptr->menu_cmd != NULL; mptr++) {
		if ((*mptr->menu_state)())
			nitems++;
	}
	list = (char **)zalloc(nitems * sizeof (char *));
	cpptr = list;
	/*
	 * Fill in the array with the names of the menu commands.
	 */
	for (mptr = menu; mptr->menu_cmd != NULL; mptr++) {
		if ((*mptr->menu_state)()) {
			*cpptr++ = mptr->menu_cmd;
		}
	}
	/*
	 * Add the 'quit' command to the end.
	 */
	*cpptr = "quit";
	return (list);
}

/*
 * This routine takes a menu list created by the above routine and
 * prints it nicely on the screen.
 */
void
display_menu_list(char **list)
{
	char **str;

	for (str = list; *str != NULL; str++)
		fmt_print("        %s\n", *str);
}

/*
 * Find the "i"th enabled menu in a menu list.  This depends
 * on menu_state() returning the same status as when the
 * original list of enabled commands was constructed.
 */
static int (*
find_enabled_menu_item(struct menu_item *menu, int item))(void)
{
	struct menu_item	*mp;

	for (mp = menu; mp->menu_cmd != NULL; mp++) {
		if ((*mp->menu_state)()) {
			if (item-- == 0) {
				return (mp->menu_func);
			}
		}
	}

	return (NULL);
}

/*
 * This routine 'runs' a menu.  It repeatedly requests a command and
 * executes the command chosen.  It exits when the 'quit' command is
 * executed.
 */
/*ARGSUSED*/
void
run_menu(struct menu_item *menu, char *title, char *prompt, int display_flag)
{
	char		**list;
	int		i;
	struct		env env;
	u_ioparam_t	ioparam;
	int		(*f)();


	/*
	 * Create the menu list and display it.
	 */
	list = create_menu_list(menu);
	(void) strcpy(cur_title, title);
	fmt_print("\n\n%s MENU:\n", title);
	display_menu_list(list);
	/*
	 * Save the environment so a ctrl-C out of a command lands here.
	 */
	saveenv(env);
	for (;;) {
		/*
		 * Ask the user which command they want to run.
		 */
		ioparam.io_charlist = list;
		i = input(FIO_MSTR, prompt, '>', &ioparam, NULL, CMD_INPUT);
		/*
		 * If they choose 'quit', the party's over.
		 */
		if ((f = find_enabled_menu_item(menu, i)) == NULL)
			break;

		/*
		 * Mark the saved environment active so the user can now
		 * do a ctrl-C to get out of the command.
		 */
		useenv();
		/*
		 * Run the command.  If it returns an error and we are
		 * running out of a command file, the party's really over.
		 */
		if ((*f)() && option_f)
			fullabort();
		/*
		 * Mark the saved environment inactive so ctrl-C doesn't
		 * work at the menu itself.
		 */
		unuseenv();
		/*
		 * Since menu items are dynamic, some commands
		 * cause changes to occur.  Destroy the old menu,
		 * and rebuild it, so we're always up-to-date.
		 */
		destroy_data((char *)list);
		list = create_menu_list(menu);
		/*
		 * Redisplay menu, if we're returning to this one.
		 */
		if (cur_menu != last_menu) {
			last_menu = cur_menu;
			(void) strcpy(cur_title, title);
			fmt_print("\n\n%s MENU:\n", title);
			display_menu_list(list);
		}
	}
	/*
	 * Clean up the environment stack and throw away the menu list.
	 */
	clearenv();
	destroy_data((char *)list);
}

/*
 * re-display the screen after exiting from shell escape
 *
 */
void
redisplay_menu_list(char **list)
{
	fmt_print("\n\n%s MENU:\n", cur_title);
	display_menu_list(list);
}


/*
 * Glue to always return true.  Used for menu items which
 * are always enabled.
 */
int
true(void)
{
	return (1);
}

/*
 * Note: The following functions are used to enable the inclusion
 * of device specific options (see init_menus.c). But when we are
 * running non interactively with commands taken from a script file,
 * current disk (cur_disk, cur_type, cur_ctype) may not be defined.
 * They get defined when the script selects a disk using "disk" option
 * in the main menu. However, in the normal interactive mode, the disk
 * selection happens before entering the main menu.
 */
/*
 * Return true for menu items enabled only for embedded SCSI controllers
 */
int
embedded_scsi(void)
{
	if (cur_ctype == NULL && option_f)
		return (0);
	return (EMBEDDED_SCSI);
}

/*
 * Return false for menu items disabled only for embedded SCSI controllers
 */
int
not_embedded_scsi(void)
{
	if (cur_ctype == NULL && option_f)
		return (0);
	return (!EMBEDDED_SCSI);
}

/*
 * Return false for menu items disabled for scsi controllers
 */
int
not_scsi(void)
{
	if (cur_ctype == NULL && option_f)
		return (0);
	return (!SCSI);
}

/*
 * Return false for menu items disabled for efi labels
 */
int
not_efi(void)
{
	if ((cur_disk == NULL) && option_f)
		return (0);
	if (cur_disk->label_type == L_TYPE_EFI)
		return (0);
	return (1);
}

int
disp_expert_change_expert_efi(void)
{
	if ((cur_disk == NULL) && option_f)
		return (0);
	if ((cur_disk->label_type == L_TYPE_EFI) && expert_mode)
		return (1);
	if (cur_disk->label_type != L_TYPE_EFI)
		return (1);
	return (0);
}

int
disp_expand_efi(void)
{
	if ((cur_disk == NULL) && option_f)
		return (0);
	if (cur_disk->label_type != L_TYPE_EFI)
		return (0);
	if (cur_parts == NULL)
		return (0);
	return (1);
}

int
disp_all_change_expert_efi(void)
{
	if ((cur_disk == NULL) && option_f)
		return (0);
	if ((cur_disk->label_type != L_TYPE_EFI) || (!expert_mode))
		return (0);
	return (1);
}

/*
 * Return true for menu items enabled scsi controllers
 */
int
scsi(void)
{
	if (cur_ctype == NULL && option_f)
		return (0);
	return (SCSI);
}


/*
 * Return true for menu items enabled if expert mode is enabled
 */
int
scsi_expert(void)
{
	if (cur_ctype == NULL && option_f)
		return (0);
	return (SCSI && expert_mode);
}

#if	defined(i386)
/*
 * Return true for menu items enabled if expert mode is enabled
 */
int
expert(void)
{
	return (expert_mode);
}
#endif	/* defined(i386) */

/*
 * Return true for menu items enabled if developer mode is enabled
 */
int
developer(void)
{
	return (dev_expert);
}

/*
 * For x86, always return true for menu items enabled
 *	since fdisk is already supported on these two platforms.
 * For Sparc, only return true for menu items enabled
 *	if a PCATA disk is selected.
 */
int
support_fdisk_on_sparc(void)
{
#if defined(sparc)
	/*
	 * If it's a SCSI disk then we don't support fdisk and we
	 * don't need to know the type cause we can ask the disk,
	 * therefore we return true only if we *KNOW* it's an ATA
	 * disk.
	 */
	if (cur_ctype && cur_ctype->ctype_ctype == DKC_PCMCIA_ATA) {
		return (1);
	} else {
		return (0);
	}
#elif defined(i386) || defined(__amd64)
	return (1);
#else
#error  No Platform defined
#endif /* defined(sparc) */

}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef	_MENU_H
#define	_MENU_H

#ifdef	__cplusplus
extern "C" {
#endif

/*
 * This file contains declarations pertaining to the menus.
 */
/*
 * This structure defines a menu entry.  It consists of a command
 * name, the function to run the command, and a function to determine
 * if the menu entry is enabled at this particular state in the program.
 * The descriptive text that appears after the command name in the menus
 * is actually part of the command name to the program.  Since
 * abbreviation is allowed for commands, the user never notices the
 * extra characters.
 */
struct menu_item {
	char	*menu_cmd;
	int	(*menu_func)();
	int	(*menu_state)();
};


/*
 *	Prototypes for ANSI C compilers
 */

char	**create_menu_list(struct menu_item *menu);
void	display_menu_list(char **list);
void	redisplay_menu_list(char **list);
void	run_menu(struct menu_item *, char *, char *, int);
int	true(void);
int	embedded_scsi(void);
int	not_embedded_scsi(void);
int	not_scsi(void);
int	not_efi(void);
int	disp_expert_change_expert_efi(void);
int	disp_expand_efi(void);
int	disp_all_change_expert_efi(void);
int	scsi(void);
int	scsi_expert(void);
int	expert(void);
int	developer(void);
int	support_fdisk_on_sparc(void);

#ifdef	__cplusplus
}
#endif

#endif	/* _MENU_H */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * This file contains functions implementing the analyze menu commands.
 */
#include <string.h>
#include "global.h"
#include "analyze.h"
#include "misc.h"
#include "menu_analyze.h"
#include "param.h"

/*
 * This routine implements the 'read' command.  It performs surface
 * analysis by reading the disk.  It is ok to run this command on
 * mounted file systems.
 */
int
a_read(void)
{
	/*
	 * The current disk must be formatted before disk analysis.
	 */
	if (!(cur_flags & DISK_FORMATTED)) {
		err_print("Current Disk is unformatted.\n");
		return (-1);
	}

	if (check(
"Ready to analyze (won't harm SunOS). This takes a long time, \n"
"but is interruptible with CTRL-C. Continue"))
		return (-1);
	return (do_scan(SCAN_VALID, F_NORMAL));
}

/*
 * This routine implements the 'refresh' command.  It performs surface
 * analysis by reading the disk then writing the same data back to the
 * disk.  It is ok to run this command on file systems, but not while
 * they are mounted.
 */
int
a_refresh(void)
{
	/*
	 * The current disk must be formatted before disk analysis.
	 */
	if (!(cur_flags & DISK_FORMATTED)) {
		err_print("Current Disk is unformatted.\n");
		return (-1);
	}

	if (check(
"Ready to analyze (won't harm data). This takes a long time, \n"
"but is interruptible with CTRL-C. Continue"))
		return (-1);
	return (do_scan(SCAN_VALID | SCAN_WRITE, F_NORMAL));
}

/*
 * This routine implements the 'test' command.  It performs surface
 * analysis by reading the disk, writing then reading a pattern on the disk,
 * then writing the original data back to the disk.
 * It is ok to run this command on file systems, but not while they are
 * mounted.
 */
int
a_test(void)
{
	/*
	 * The current disk must be formatted before disk analysis.
	 */
	if (!(cur_flags & DISK_FORMATTED)) {
		err_print("Current Disk is unformatted.\n");
		return (-1);
	}

	if (check(
"Ready to analyze (won't harm data). This takes a long time, \n"
"but is interruptible with CTRL-C. Continue"))
		return (-1);
	return (do_scan(SCAN_VALID | SCAN_PATTERN | SCAN_WRITE, F_NORMAL));
}

/*
 * This routine implements the 'write' command.  It performs surface
 * analysis by writing a pattern to the disk then reading it back.
 * It is not ok to run this command on any data you want to keep.
 */
int
a_write(void)
{
	/*
	 * The current disk must be formatted before disk analysis.
	 */
	if (!(cur_flags & DISK_FORMATTED)) {
		err_print("Current Disk is unformatted.\n");
		return (-1);
	}

	if (check(
"Ready to analyze (will corrupt data). This takes a long time, \n"
"but is interruptible with CTRL-C. Continue"))
		return (-1);
	return (do_scan(SCAN_PATTERN, F_NORMAL));
}

/*
 * This routine implements the 'compare' command.  It performs surface
 * analysis by writing a pattern to the disk, reading it back, then
 * checking the data to be sure it's the same.
 * It is not ok to run this command on any data you want to keep.
 */
int
a_compare(void)
{
	/*
	 * The current disk must be formatted before disk analysis.
	 */
	if (!(cur_flags & DISK_FORMATTED)) {
		err_print("Current Disk is unformatted.\n");
		return (-1);
	}

	if (check(
"Ready to analyze (will corrupt data). This takes a long time, \n"
"but is interruptible with CTRL-C. Continue"))
		return (-1);
	return (do_scan(SCAN_PATTERN | SCAN_COMPARE, F_NORMAL));
}

/*
 * This routine implements the 'print' command.  It displays the data
 * buffer in hexadecimal.  It is only useful for checking the disk for
 * a specific set of data (by reading it then printing it).
 */
int
a_print(void)
{
	int	i, j, lines, nomore = 0;
	int	c, one_line = 0;
	int	tty_lines = get_tty_lines();

	/*
	 * If we are running out of command file, don't page the output.
	 * Otherwise we are running with a user.  Turn off echoing of
	 * input characters so we can page the output.
	 */
	if (option_f || (!isatty(0)) || (!isatty(1)))
		nomore++;
	else {
		enter_critical();
		echo_off();
		charmode_on();
		exit_critical();
	}
	/*
	 * Loop through the data buffer.
	 */
	lines = 0;
	for (i = 0; i < scan_size * cur_blksz / sizeof (int); i += 6) {
		/*
		 * Print the data.
		 */
		for (j = 0; j < 6; j++)
			if (i + j < scan_size * cur_blksz / sizeof (int))
				fmt_print("0x%08x  ",
				    *((int *)((int *)cur_buf + i + j)));
		fmt_print("\n");
		lines++;

		/*
		 * If we are paging and hit the end of a page, wait for
		 * the user to hit either space-bar, "q", return,
		 * or ctrl-C before going on.
		 */
		if (one_line ||
		    (!nomore && (lines % (tty_lines - 1) == 0))) {
			/*
			 * Print until first screenfull
			 */
			if (lines < (tty_lines -1))
				continue;
			/*
			 * Get the next character.
			 */
			(void) printf("- hit space for more - ");
			c = getchar();
			(void) printf("\015");
			one_line = 0;
			/*
			 * Handle display one line command (return key)
			 */
			if (c == '\012') {
				one_line++;
			}
			/* Handle Quit command */
			if (c == 'q') {
				(void) printf(
				"                       \015");
				goto PRINT_EXIT;
			}
			/* handle ^D */
			if (c == '\004')
				fullabort();
		}
	}
	/*
	 * If we were doing paging, turn echoing back on.
	 */
PRINT_EXIT:
	if (!nomore) {
		enter_critical();
		charmode_off();
		echo_on();
		exit_critical();
	}
	return (0);
}

/*
 * This routine implements the 'setup' command.  It allows the user
 * to program the variables that drive surface analysis.  The approach
 * is to prompt the user for the value of each variable, with the current
 * value as the default.
 */
int
a_setup(void)
{
	int			deflt;
	uint64_t		size;
	u_ioparam_t		ioparam;

	/*
	 * Because of the polarity of the yes/no structure (yes is 0),
	 * we have to invert the values for all yes/no questions.
	 */
	deflt = !scan_entire;
	ioparam.io_charlist = confirm_list;
	scan_entire = !input(FIO_MSTR, "Analyze entire disk", '?',
	    &ioparam, &deflt, DATA_INPUT);
	/*
	 * If we are not scanning the whole disk, input the bounds of the scan.
	 */
	if (!scan_entire) {
		ioparam.io_bounds.lower = 0;
		if ((cur_ctype->ctype_flags & CF_SCSI) &&
		    (cur_disk->label_type == L_TYPE_SOLARIS)) {
			ioparam.io_bounds.upper = datasects() - 1;
		} else if (cur_disk->label_type == L_TYPE_SOLARIS) {
			ioparam.io_bounds.upper = physsects() - 1;
		} else if (cur_disk->label_type == L_TYPE_EFI) {
			ioparam.io_bounds.upper = cur_parts->etoc->efi_last_lba;
		}

		scan_lower = (diskaddr_t)input(FIO_BN,
		    "Enter starting block number", ':',
		    &ioparam, (int *)&scan_lower, DATA_INPUT);
		ioparam.io_bounds.lower = scan_lower;
		if (scan_upper < scan_lower)
			scan_upper = scan_lower;
		scan_upper = (diskaddr_t)input(FIO_BN,
		    "Enter ending block number", ':',
		    &ioparam, (int *)&scan_upper, DATA_INPUT);
	}
	deflt = !scan_loop;
	ioparam.io_charlist = confirm_list;
	scan_loop = !input(FIO_MSTR, "Loop continuously", '?',
	    &ioparam, &deflt, DATA_INPUT);
	/*
	 * If we are not looping continuously, input the number of passes.
	 */
	if (!scan_loop) {
		ioparam.io_bounds.lower = 1;
		ioparam.io_bounds.upper = 100;
		scan_passes = input(FIO_INT, "Enter number of passes", ':',
		    &ioparam, &scan_passes, DATA_INPUT);
	}
	deflt = !scan_correct;
	ioparam.io_charlist = confirm_list;
	scan_correct = !input(FIO_MSTR, "Repair defective blocks", '?',
	    &ioparam, &deflt, DATA_INPUT);
	deflt = !scan_stop;
	ioparam.io_charlist = confirm_list;
	scan_stop = !input(FIO_MSTR, "Stop after first error", '?',
	    &ioparam, &deflt, DATA_INPUT);
	deflt = !scan_random;
	ioparam.io_charlist = confirm_list;
	scan_random = !input(FIO_MSTR, "Use random bit patterns", '?',
	    &ioparam, &deflt, DATA_INPUT);
	ioparam.io_bounds.lower = 1;
	/*
	 * The number of blocks per transfer is limited by the buffer
	 * size, or the scan boundaries, whichever is smaller.
	 */
	if ((scan_entire) && (cur_disk->label_type == L_TYPE_SOLARIS)) {
		size = physsects() - 1;
	} else if ((scan_entire) && (cur_disk->label_type == L_TYPE_EFI)) {
		size = cur_parts->etoc->efi_last_lba;
	} else {
		size = scan_upper - scan_lower + 1;
	}
	ioparam.io_bounds.upper = min(size, BUF_SECTS);
	if (scan_size > ioparam.io_bounds.upper)
		scan_size = ioparam.io_bounds.upper;
	scan_size = input(FIO_INT, "Enter number of blocks per transfer", ':',
	    &ioparam, (int *)&scan_size, DATA_INPUT);
	deflt = !scan_auto;
	ioparam.io_charlist = confirm_list;
	scan_auto = !input(FIO_MSTR, "Verify media after formatting", '?',
	    &ioparam, &deflt, DATA_INPUT);

	deflt = !option_msg;
	ioparam.io_charlist = confirm_list;
	option_msg = !input(FIO_MSTR, "Enable extended messages", '?',
	    &ioparam, &deflt, DATA_INPUT);
	deflt = !scan_restore_defects;
	ioparam.io_charlist = confirm_list;
	scan_restore_defects = !input(FIO_MSTR, "Restore defect list", '?',
	    &ioparam, &deflt, DATA_INPUT);
	deflt = !scan_restore_label;
	ioparam.io_charlist = confirm_list;
	scan_restore_label = !input(FIO_MSTR, "Restore disk label", '?',
	    &ioparam, &deflt, DATA_INPUT);
	fmt_print("\n");
	return (0);
}

/*
 * This routine implements the 'config' command.  It simply prints out
 * the values of all the variables controlling surface analysis.  It
 * is meant to complement the 'setup' command by allowing the user to
 * check the current setup.
 */
int
a_config(void)
{

	fmt_print("        Analyze entire disk? ");
	fmt_print(scan_entire ? "yes\n" : "no\n");

	if (!scan_entire) {
		fmt_print("        Starting block number: %llu (", scan_lower);
		pr_dblock(fmt_print, scan_lower);
		fmt_print(")\n        Ending block number: %llu (", scan_upper);
		pr_dblock(fmt_print, scan_upper);
		fmt_print(")\n");
	}
	fmt_print("        Loop continuously? ");
	fmt_print(scan_loop ? "yes\n" : "no\n");

	if (!scan_loop) {
		fmt_print("        Number of passes: %d\n", scan_passes);
	}

	fmt_print("        Repair defective blocks? ");
	fmt_print(scan_correct ? "yes\n" : "no\n");

	fmt_print("        Stop after first error? ");
	fmt_print(scan_stop ? "yes\n" : "no\n");

	fmt_print("        Use random bit patterns? ");
	fmt_print(scan_random ? "yes\n" : "no\n");

	fmt_print("        Number of blocks per transfer: %d (", scan_size);
	pr_dblock(fmt_print, (diskaddr_t)scan_size);
	fmt_print(")\n");

	fmt_print("        Verify media after formatting? ");
	fmt_print(scan_auto ? "yes\n" : "no\n");

	fmt_print("        Enable extended messages? ");
	fmt_print(option_msg ? "yes\n" : "no\n");

	fmt_print("        Restore defect list? ");
	fmt_print(scan_restore_defects ? "yes\n" : "no\n");

	fmt_print("        Restore disk label? ");
	fmt_print(scan_restore_label ? "yes\n" : "no\n");

	fmt_print("\n");
	return (0);
}

/*
 * This routine implements the 'purge' command.  It purges the disk
 * by writing three patterns to the disk then reading the last one back.
 * It is not ok to run this command on any data you want to keep.
 */
int
a_purge(void)
{
	int status = 0;

	/*
	 * The current disk must be formatted before disk analysis.
	 */
	if (!(cur_flags & DISK_FORMATTED)) {
		err_print("Current Disk is unformatted.\n");
		return (-1);
	}
	if (scan_random) {
		fmt_print("The purge command does not write random data\n");
		scan_random = 0;
	}

	if (!scan_loop && (scan_passes <= NPPATTERNS)) {
		if (scan_passes < NPPATTERNS) {
			fmt_print("The purge command runs for a minimum of ");
			fmt_print("%d passes plus a last pass if the\n",
			    NPPATTERNS);
			fmt_print("first %d passes were successful.\n",
			    NPPATTERNS);
		}
		scan_passes = NPPATTERNS + 1;
	}

	if (check(
"Ready to purge (will corrupt data). This takes a long time, \n"
"but is interruptible with CTRL-C. Continue"))
		return (-1);

	status = do_scan(SCAN_PATTERN | SCAN_PURGE, F_NORMAL);

	return (status);
}

/*
 * This routine implements the 'verify' command.  It writes the disk
 * by writing unique data for each block; after the write pass, it
 * reads the data and verifies for correctness. Note that the entire
 * disk (or the range of disk) is fully written first and then read.
 * This should eliminate any caching effect on the drives.
 * It is not ok to run this command on any data you want to keep.
 */
int
a_verify(void)
{
	/*
	 * The current disk must be formatted before disk analysis.
	 */
	if (!(cur_flags & DISK_FORMATTED)) {
		err_print("Current Disk is unformatted.\n");
		return (-1);
	}
	if (scan_random) {
		fmt_print("The verify command does not write random data\n");
		scan_random = 0;
	}
	if (scan_passes < 2 && !scan_loop) {
		scan_passes = 2;
		fmt_print("The verify command runs minimum of 2 passes, one"
		    " for writing and \nanother for reading and verfying."
		    " Resetting the number of passes to 2.\n");
	}

	if (check("Ready to verify (will corrupt data). This takes a long time,"
	    "\nbut is interruptible with CTRL-C. Continue")) {
		return (-1);
	}

	return (do_scan(SCAN_WRITE | SCAN_VERIFY, F_NORMAL));
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright (c) 1991-2001 by Sun Microsystems, Inc.
 */

#ifndef	_MENU_ANALYZE_H
#define	_MENU_ANALYZE_H

#ifdef	__cplusplus
extern "C" {
#endif

/*
 *	Prototypes for ANSI
 */

int	a_read(void);
int	a_refresh(void);
int	a_test(void);
int	a_write(void);
int	a_compare(void);
int	a_verify(void);
int	a_print(void);
int	a_setup(void);
int	a_config(void);
int	a_purge(void);

#ifdef	__cplusplus
}
#endif

#endif	/* _MENU_ANALYZE_H */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * This file contains functions that implement the cache menu commands.
 */
#include "global.h"
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/wait.h>
#include <signal.h>
#include <string.h>
#include <sys/fcntl.h>
#include <sys/stat.h>

#include <sys/dklabel.h>

#include "main.h"
#include "analyze.h"
#include "menu.h"
#include "menu_cache.h"
#include "param.h"
#include "misc.h"
#include "label.h"
#include "startup.h"
#include "partition.h"
#include "prompts.h"
#include "checkdev.h"
#include "io.h"
#include "ctlr_scsi.h"
#include "auto_sense.h"
#include "hardware_structs.h"

extern	struct menu_item menu_cache[];
extern	struct menu_item menu_write_cache[];
extern	struct menu_item menu_read_cache[];


int
c_cache(void)
{
	cur_menu++;
	last_menu = cur_menu;
	run_menu(menu_cache, "CACHE", "cache", 0);
	cur_menu--;
	return (0);
}

int
ca_write_cache(void)
{
	cur_menu++;
	last_menu = cur_menu;
	run_menu(menu_write_cache, "WRITE_CACHE", "write_cache", 0);
	cur_menu--;
	return (0);
}

int
ca_read_cache(void)
{
	cur_menu++;
	last_menu = cur_menu;
	run_menu(menu_read_cache, "READ_CACHE", "read_cache", 0);
	cur_menu--;
	return (0);
}

int
ca_write_display(void)
{
	struct mode_cache		*page8;
	struct scsi_ms_header		header;
	int				status;
	union {
		struct mode_cache	page8;
		char			rawbuf[MAX_MODE_SENSE_SIZE];
	} u_page8;

	page8 = &u_page8.page8;

	status = uscsi_mode_sense(cur_file, DAD_MODE_CACHE,
	    MODE_SENSE_PC_CURRENT, (caddr_t)page8,
	    MAX_MODE_SENSE_SIZE, &header);

	if (status == 0) {
		if (page8->wce) {
			fmt_print("Write Cache is enabled\n");
		} else {
			fmt_print("Write Cache is disabled\n");
		}
	} else {
		err_print("Mode sense failed.\n");
	}
	return (0);
}

int
ca_write_enable(void)
{
	struct mode_cache		*page8;
	struct scsi_ms_header		header;
	int				status;
	int				length;
	int				sp_flags;
	union {
		struct mode_cache	page8;
		char			rawbuf[MAX_MODE_SENSE_SIZE];
	} u_page8;

	page8 = &u_page8.page8;

	status = uscsi_mode_sense(cur_file, DAD_MODE_CACHE,
	    MODE_SENSE_PC_CHANGEABLE, (caddr_t)page8,
	    MAX_MODE_SENSE_SIZE, &header);

	if (status == 0) {
		if (page8->wce) {
			status = uscsi_mode_sense(cur_file, DAD_MODE_CACHE,
			    MODE_SENSE_PC_SAVED, (caddr_t)page8,
			    MAX_MODE_SENSE_SIZE, &header);
			if (status != 0) {
				status = uscsi_mode_sense(cur_file,
				    DAD_MODE_CACHE, MODE_SENSE_PC_CURRENT,
				    (caddr_t)page8, MAX_MODE_SENSE_SIZE,
				    &header);
			}

			if (status == 0) {
				length = MODESENSE_PAGE_LEN(page8);
				sp_flags = MODE_SELECT_PF;
				if (page8->mode_page.ps) {
					sp_flags |= MODE_SELECT_SP;
				} else {
					err_print("\
This setting is valid until next reset only. It is not saved permanently.\n");
				}
				page8->mode_page.ps = 0;
				page8->wce = 1;
				header.mode_header.length = 0;
				header.mode_header.device_specific = 0;
				status = uscsi_mode_select(cur_file,
				    DAD_MODE_CACHE, sp_flags,
				    (caddr_t)page8, length, &header);
				if (status != 0) {
					err_print("Mode select failed\n");
					return (0);
				}
			}
		} else {
			err_print("Write cache setting is not changeable\n");
		}
	}
	if (status != 0) {
		err_print("Mode sense failed.\n");
	}
	return (0);
}

int
ca_write_disable(void)
{
	struct mode_cache		*page8;
	struct scsi_ms_header		header;
	int				status;
	int				length;
	int				sp_flags;
	union {
		struct mode_cache	page8;
		char			rawbuf[MAX_MODE_SENSE_SIZE];
	} u_page8;

	page8 = &u_page8.page8;

	status = uscsi_mode_sense(cur_file, DAD_MODE_CACHE,
	    MODE_SENSE_PC_CHANGEABLE, (caddr_t)page8,
	    MAX_MODE_SENSE_SIZE, &header);

	if (status == 0) {
		if (page8->wce) {
			status = uscsi_mode_sense(cur_file, DAD_MODE_CACHE,
			    MODE_SENSE_PC_SAVED, (caddr_t)page8,
			    MAX_MODE_SENSE_SIZE, &header);
			if (status != 0) {
				status = uscsi_mode_sense(cur_file,
				    DAD_MODE_CACHE, MODE_SENSE_PC_CURRENT,
				    (caddr_t)page8, MAX_MODE_SENSE_SIZE,
				    &header);
			}

			if (status == 0) {
				length = MODESENSE_PAGE_LEN(page8);
				sp_flags = MODE_SELECT_PF;
				if (page8->mode_page.ps) {
					sp_flags |= MODE_SELECT_SP;
				} else {
					err_print("\
This setting is valid until next reset only. It is not saved permanently.\n");
				}
				page8->mode_page.ps = 0;
				page8->wce = 0;
				header.mode_header.length = 0;
				header.mode_header.device_specific = 0;
				status = uscsi_mode_select(cur_file,
				    DAD_MODE_CACHE, sp_flags,
				    (caddr_t)page8, length, &header);
				if (status != 0) {
					err_print("Mode select failed\n");
					return (0);
				}
			}
		} else {
			err_print("Write cache setting is not changeable\n");
		}
	}
	if (status != 0) {
		err_print("Mode sense failed.\n");
	}
	return (0);
}

int
ca_read_display(void)
{
	struct mode_cache		*page8;
	struct scsi_ms_header		header;
	int				status;
	union {
		struct mode_cache	page8;
		char			rawbuf[MAX_MODE_SENSE_SIZE];
	} u_page8;

	page8 = &u_page8.page8;

	status = uscsi_mode_sense(cur_file, DAD_MODE_CACHE,
	    MODE_SENSE_PC_CURRENT, (caddr_t)page8,
	    MAX_MODE_SENSE_SIZE, &header);

	if (status == 0) {
		if (page8->rcd) {
			fmt_print("Read Cache is disabled\n");
		} else {
			fmt_print("Read Cache is enabled\n");
		}
	} else {
		err_print("Mode sense failed.\n");
	}
	return (0);
}

int
ca_read_enable(void)
{
	struct mode_cache		*page8;
	struct scsi_ms_header		header;
	int				status;
	int				length;
	int				sp_flags;
	union {
		struct mode_cache	page8;
		char			rawbuf[MAX_MODE_SENSE_SIZE];
	} u_page8;

	page8 = &u_page8.page8;

	status = uscsi_mode_sense(cur_file, DAD_MODE_CACHE,
	    MODE_SENSE_PC_CHANGEABLE, (caddr_t)page8,
	    MAX_MODE_SENSE_SIZE, &header);

	if (status == 0) {
		if (page8->rcd) {
			status = uscsi_mode_sense(cur_file, DAD_MODE_CACHE,
			    MODE_SENSE_PC_SAVED, (caddr_t)page8,
			    MAX_MODE_SENSE_SIZE, &header);
			if (status != 0) {
				status = uscsi_mode_sense(cur_file,
				    DAD_MODE_CACHE, MODE_SENSE_PC_CURRENT,
				    (caddr_t)page8, MAX_MODE_SENSE_SIZE,
				    &header);
			}

			if (status == 0) {
				length = MODESENSE_PAGE_LEN(page8);
				sp_flags = MODE_SELECT_PF;
				if (page8->mode_page.ps) {
					sp_flags |= MODE_SELECT_SP;
				} else {
					err_print("\
This setting is valid until next reset only. It is not saved permanently.\n");
				}
				page8->mode_page.ps = 0;
				page8->rcd = 0;
				header.mode_header.length = 0;
				header.mode_header.device_specific = 0;
				status = uscsi_mode_select(cur_file,
				    DAD_MODE_CACHE, sp_flags,
				    (caddr_t)page8, length, &header);
				if (status != 0) {
					err_print("Mode select failed\n");
					return (0);
				}
			}
		} else {
			err_print("Read cache setting is not changeable\n");
		}
	}
	if (status != 0) {
		err_print("Mode sense failed.\n");
	}
	return (0);
}

int
ca_read_disable(void)
{
	struct mode_cache		*page8;
	struct scsi_ms_header		header;
	int				status;
	int				length;
	int				sp_flags;
	union {
		struct mode_cache	page8;
		char			rawbuf[MAX_MODE_SENSE_SIZE];
	} u_page8;

	page8 = &u_page8.page8;

	status = uscsi_mode_sense(cur_file, DAD_MODE_CACHE,
	    MODE_SENSE_PC_CHANGEABLE, (caddr_t)page8,
	    MAX_MODE_SENSE_SIZE, &header);

	if (status == 0) {
		if (page8->rcd) {
			status = uscsi_mode_sense(cur_file, DAD_MODE_CACHE,
			    MODE_SENSE_PC_SAVED, (caddr_t)page8,
			    MAX_MODE_SENSE_SIZE, &header);
			if (status != 0) {
				status = uscsi_mode_sense(cur_file,
				    DAD_MODE_CACHE, MODE_SENSE_PC_CURRENT,
				    (caddr_t)page8, MAX_MODE_SENSE_SIZE,
				    &header);
			}

			if (status == 0) {
				length = MODESENSE_PAGE_LEN(page8);
				sp_flags = MODE_SELECT_PF;
				if (page8->mode_page.ps) {
					sp_flags |= MODE_SELECT_SP;
				} else {
					err_print("\
This setting is valid until next reset only. It is not saved permanently.\n");
				}
				page8->mode_page.ps = 0;
				page8->rcd = 1;
				header.mode_header.length = 0;
				header.mode_header.device_specific = 0;
				status = uscsi_mode_select(cur_file,
				    DAD_MODE_CACHE, sp_flags,
				    (caddr_t)page8, length, &header);
				if (status != 0) {
					err_print("Mode select failed\n");
					return (0);
				}
			}
		} else {
			err_print("Read cache setting is not changeable\n");
		}
	}
	if (status != 0) {
		err_print("Mode sense failed.\n");
	}
	return (0);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright (c) 1999 by Sun Microsystems, Inc.
 */

#ifndef	_MENU_CACHE_H
#define	_MENU_CACHE_H

#ifdef	__cplusplus
extern "C" {
#endif

/*
 *	Prototypes for ANSI
 */
int	c_cache(void);
int	ca_write_cache(void);
int	ca_read_cache(void);
int	ca_write_display(void);
int	ca_write_enable(void);
int	ca_write_disable(void);
int	ca_read_display(void);
int	ca_read_enable(void);
int	ca_read_disable(void);

#ifdef	__cplusplus
}
#endif

#endif	/* _MENU_CACHE_H */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright (c) 1993, 2010, Oracle and/or its affiliates. All rights reserved.
 * Copyright 2012 Milan Jurik. All rights reserved.
 * Copyright 2014 Toomas Soome <tsoome@me.com>
 * Copyright 2015 Nexenta Systems, Inc. All rights reserved.
 * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>
 * Copyright (c) 2016 by Delphix. All rights reserved.
 */

/*
 * This file contains functions that implement the command menu commands.
 */

#include "global.h"
#include <time.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/wait.h>
#include <strings.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>

#if defined(sparc)
#include <sys/hdio.h>
#endif /* defined(sparc) */

#include "main.h"
#include "analyze.h"
#include "menu.h"
#include "menu_command.h"
#include "menu_defect.h"
#include "menu_partition.h"
#include "param.h"
#include "misc.h"
#include "label.h"
#include "startup.h"
#include "partition.h"
#include "prompts.h"
#include "checkdev.h"
#include "io.h"
#include "ctlr_scsi.h"
#include "auto_sense.h"
#include "modify_partition.h"


extern	struct menu_item menu_partition[];
extern	struct menu_item menu_analyze[];
extern	struct menu_item menu_defect[];
int	prot_type;

/*
 * Choices for the p_tag vtoc field
 */
slist_t	ptag_choices[] = {
	{ "unassigned",	"",	V_UNASSIGNED	},
	{ "boot",	"",	V_BOOT		},
	{ "root",	"",	V_ROOT		},
	{ "swap",	"",	V_SWAP		},
	{ "usr",	"",	V_USR		},
	{ "backup",	"",	V_BACKUP	},
	{ "stand",	"",	V_STAND		},
	{ "var",	"",	V_VAR		},
	{ "home",	"",	V_HOME		},
	{ "alternates",	"",	V_ALTSCTR	},
	{ "reserved",	"",	V_RESERVED	},
	{ "system",	"",	V_SYSTEM	},
	{ "BIOS_boot",	"",	V_BIOS_BOOT	},
	{ "FreeBSD boot", "",	V_FREEBSD_BOOT	},
	{ "FreeBSD swap", "",	V_FREEBSD_SWAP	},
	{ "FreeBSD UFS", "",	V_FREEBSD_UFS	},
	{ "FreeBSD ZFS", "",	V_FREEBSD_ZFS	},

	{ NULL }
};


/*
 * Choices for the p_flag vtoc field
 */
slist_t	pflag_choices[] = {
	{ "wm",	"read-write, mountable",	0		},
	{ "wu",	"read-write, unmountable",	V_UNMNT		},
	{ "rm",	"read-only, mountable",		V_RONLY		},
	{ "ru",	"read-only, unmountable",	V_RONLY|V_UNMNT	},
	{ NULL }
};


/*
 * This routine implements the 'disk' command.  It allows the user to
 * select a disk to be current.  The list of choices is the list of
 * disks that were found at startup time.
 */
int
c_disk(void)
{
	struct disk_info	*disk;
	u_ioparam_t		ioparam;
	int			i;
	int			ndisks = 0;
	int			blind_select = 0;
	int			deflt;
	int			index;
	int			*defltptr = NULL;
	int			more = 0;
	int			more_quit = 0;
	int			one_line = 0;
	int			tty_lines;

/*
 * This buffer holds the check() prompt that verifies we've got the right
 * disk when performing a blind selection.  The size should be sufficient
 * to hold the prompt string, plus 256 characters for the disk name -
 * way more than should ever be necessary.  See the #define in misc.h.
 */
	char			chk_buf[BLIND_SELECT_VER_PROMPT];

	if (istokenpresent()) {
		/*
		 * disk number to be selected is already in the
		 * input stream .
		 */
		TOKEN token, cleantoken;

		/*
		 * Get the disk number the user has given.
		 */
		i = 0;
		for (disk = disk_list; disk != NULL; disk = disk->disk_next) {
			i++;
		}

		ioparam.io_bounds.lower = 0;
		ioparam.io_bounds.upper = i - 1;
		(void) gettoken(token);
		clean_token(cleantoken, token);

		/*
		 * Convert the token into an integer.
		 */
		if (geti(cleantoken, &index, NULL))
			return (0);

		/*
		 * Check to be sure it is within the legal bounds.
		 */
		if ((index < 0) || (index >= i)) {
			err_print("`%d' is out of range.\n", index);
			return (0);
		}
		goto checkdisk;
	}

	fmt_print("\n\nAVAILABLE DISK SELECTIONS:\n");

	i = 0;
	if ((option_f == NULL) && isatty(0) == 1 && isatty(1) == 1) {
		/*
		 * We have a real terminal for std input and output, enable
		 * more style of output for disk selection list.
		 */
		more = 1;
		tty_lines = get_tty_lines();
		enter_critical();
		echo_off();
		charmode_on();
		exit_critical();
	}

	/*
	 * Loop through the list of found disks.
	 */
	for (disk = disk_list; disk != NULL; disk = disk->disk_next) {
		/*
		 * If using more output, account 2 lines for each disk.
		 */
		if (more && !more_quit && i && (one_line ||
		    ((2 * i + 1) % (tty_lines - 2) <= 1))) {
			int	c;

			/*
			 * Get the next character.
			 */
			fmt_print("- hit space for more or s to select - ");
			c = getchar();
			fmt_print("\015");
			one_line = 0;
			/*
			 * Handle display one line command
			 * (return key)
			 */
			if (c == '\012') {
				one_line++;
			}
			/* Handle Quit command */
			if (c == 'q') {
				fmt_print(
				"                       \015");
				more_quit++;
			}
			/* Handle ^D command */
			if (c == '\004')
				fullabort();
			/* or get on with the show */
			if (c == 's' || c == 'S') {
				fmt_print("%80s\n", " ");
				break;
			}
		}
		/*
		 * If this is the current disk, mark it as
		 * the default.
		 */
		if (cur_disk == disk) {
			deflt = i;
			defltptr = &deflt;
		}
		if (!more || !more_quit)
			pr_diskline(disk, i);
		i++;
	}
	if (more) {
		enter_critical();
		charmode_off();
		echo_on();
		exit_critical();
	}

	/*
	 * Determine total number of disks, and ask the user which disk they
	 * would like to make current.
	 */

	for (disk = disk_list; disk != NULL; disk = disk->disk_next) {
		ndisks++;
	}

	ioparam.io_bounds.lower = 0;
	ioparam.io_bounds.upper = ndisks - 1;
	index = input(FIO_INT, "Specify disk (enter its number)", ':',
	    &ioparam, defltptr, DATA_INPUT);

	if (index >= i) {
		blind_select = 1;
	}

	/*
	 * Find the disk chosen.  Search through controllers/disks
	 * in the same original order, so we match what the user
	 * chose.
	 */
checkdisk:
	i = 0;
	for (disk = disk_list; disk != NULL; disk = disk->disk_next) {
		if (i == index)
			goto found;
		i++;
	}
	/*
	 * Should never happen.
	 */
	impossible("no disk found");

found:
	if (blind_select) {
		(void) snprintf(chk_buf, sizeof (chk_buf),
"Disk %s selected - is this the desired disk? ", disk->disk_name);
		if (check(chk_buf)) {
			return (-1);
		}
	}

	/*
	 * Update the state.  We lock out interrupts so the state can't
	 * get half-updated.
	 */

	enter_critical();
	init_globals(disk);
	exit_critical();

	/*
	 * If type unknown and interactive, ask user to specify type.
	 * Also, set partition table (best guess) too.
	 */
	if (!option_f && ncyl == 0 && nhead == 0 && nsect == 0 &&
	    (disk->label_type != L_TYPE_EFI)) {
		(void) c_type();
	}

	/*
	 * Get the Solaris Fdisk Partition information
	 */
	if (nhead != 0 && nsect != 0)
		(void) copy_solaris_part(&cur_disk->fdisk_part);

	if ((cur_disk->label_type == L_TYPE_EFI) &&
	    (cur_disk->disk_parts->etoc->efi_flags &
	    EFI_GPT_PRIMARY_CORRUPT)) {
		err_print("Reading the primary EFI GPT label ");
		err_print("failed.  Using backup label.\n");
		err_print("Use the 'backup' command to restore ");
		err_print("the primary label.\n");
	}

#if defined(_SUNOS_VTOC_16)
	/*
	 * If there is no fdisk solaris partition.
	 */
	if (cur_disk->fdisk_part.numsect == 0) {
		err_print("No Solaris fdisk partition found.\n");
		goto exit;
	}
#endif /* defined(_SUNOS_VTOC_16) */

	/*
	 * If the label of the disk is marked dirty,
	 * see if they'd like to label the disk now.
	 */
	if (cur_disk->disk_flags & DSK_LABEL_DIRTY) {
		if (check("Disk not labeled.  Label it now") == 0) {
			if (write_label()) {
				err_print("Write label failed\n");
			} else {
				cur_disk->disk_flags &= ~DSK_LABEL_DIRTY;
			}
		}
	}
exit:
	return (0);
}

/*
 * This routine implements the 'type' command.  It allows the user to
 * specify the type of the current disk.  It should be necessary only
 * if the disk was not labelled or was somehow labelled incorrectly.
 * The list of legal types for the disk comes from information that was
 * in the data file.
 */
int
c_type(void)
{
	struct disk_type	*type, *tptr, *oldtype;
	u_ioparam_t		ioparam;
	int			i, index, deflt, *defltptr = NULL;
	struct disk_type	disk_type;
	struct disk_type	*d = &disk_type;
	int			first_disk;
	int			auto_conf_choice;
	int			other_choice;
	struct dk_label		label;
	struct efi_info		efi_info;
	uint64_t		maxLBA;
	char			volname[LEN_DKL_VVOL];
	int			volinit = 0;

	/*
	 * There must be a current disk.
	 */
	if (cur_disk == NULL) {
		err_print("Current Disk is not set.\n");
		return (-1);
	}
	oldtype = cur_disk->disk_type;
	type = cur_ctype->ctype_dlist;
	/*
	 * Print out the list of choices.
	 */
	fmt_print("\n\nAVAILABLE DRIVE TYPES:\n");
	first_disk = 0;
	if (cur_ctype->ctype_ctype == DKC_SCSI_CCS) {
		auto_conf_choice = 0;
		fmt_print("        %d. Auto configure\n", first_disk++);
	} else {
		auto_conf_choice = -1;
	}

	i = first_disk;
	for (tptr = type; tptr != NULL; tptr = tptr->dtype_next) {
		/*
		 * If we pass the current type, mark it to be the default.
		 */
		if (cur_dtype == tptr) {
			deflt = i;
			defltptr = &deflt;
		}
		if (cur_disk->label_type == L_TYPE_EFI) {
			continue;
		}
		if (tptr->dtype_asciilabel)
			fmt_print("        %d. %s\n", i++,
			    tptr->dtype_asciilabel);
	}
	other_choice = i;
	fmt_print("        %d. other\n", i);
	ioparam.io_bounds.lower = 0;
	ioparam.io_bounds.upper = i;
	/*
	 * Ask the user which type the disk is.
	 */
	index = input(FIO_INT, "Specify disk type (enter its number)", ':',
	    &ioparam, defltptr, DATA_INPUT);
	/*
	 * Find the type they chose.
	 */
	if (index == auto_conf_choice) {
		float			scaled;
		diskaddr_t		nblks;
		int			nparts;

		/*
		 * User chose "auto configure".
		 */
		(void) strcpy(x86_devname, cur_disk->disk_name);
		switch (cur_disk->label_type) {
		case L_TYPE_SOLARIS:
			if ((tptr = auto_sense(cur_file, 1, &label)) == NULL) {
				err_print("Auto configure failed\n");
				return (-1);
			}
			fmt_print("%s: configured with capacity of ",
			    cur_disk->disk_name);
			nblks = (diskaddr_t)tptr->dtype_ncyl *
			    tptr->dtype_nhead * tptr->dtype_nsect;
			scaled = bn2mb(nblks);
			if (scaled > 1024.0) {
				fmt_print("%1.2fGB\n", scaled/1024.0);
			} else {
				fmt_print("%1.2fMB\n", scaled);
			}
			fmt_print("<%s cyl %d alt %d hd %d sec %d>\n",
			    tptr->dtype_asciilabel, tptr->dtype_ncyl,
			    tptr->dtype_acyl, tptr->dtype_nhead,
			    tptr->dtype_nsect);
			break;
		case L_TYPE_EFI:
			if ((tptr = auto_efi_sense(cur_file, &efi_info))
			    == NULL) {
				err_print("Auto configure failed\n");
				return (-1);
			}
			fmt_print("%s: configured with capacity of ",
			    cur_disk->disk_name);
			scaled = bn2mb(efi_info.capacity);
			if (scaled > 1024.0) {
				fmt_print("%1.2fGB\n", scaled/1024.0);
			} else {
				fmt_print("%1.2fMB\n", scaled);
			}
			cur_blksz = efi_info.e_parts->efi_lbasize;
			print_efi_string(efi_info.vendor, efi_info.product,
			    efi_info.revision, efi_info.capacity);
			fmt_print("\n");
			for (nparts = 0; nparts < cur_parts->etoc->efi_nparts;
			    nparts++) {
				if (cur_parts->etoc->efi_parts[nparts].p_tag ==
				    V_RESERVED) {
					(void) strcpy(volname,
					    cur_parts->etoc->efi_parts
					    [nparts].p_name);
					volinit = 1;
					break;
				}
			}
			enter_critical();
			if (delete_disk_type(cur_disk->disk_type) != 0) {
				fmt_print("Autoconfiguration failed.\n");
				return (-1);
			}
			cur_disk->disk_type = tptr;
			cur_disk->disk_parts = tptr->dtype_plist;
			init_globals(cur_disk);
			exit_critical();
			if (volinit) {
				for (nparts = 0; nparts <
				    cur_parts->etoc->efi_nparts; nparts++) {
				if (cur_parts->etoc->efi_parts[nparts].p_tag ==
				    V_RESERVED) {
				(void) strcpy(
				    cur_parts->etoc->efi_parts[nparts].p_name,
				    volname);
				(void) strlcpy(cur_disk->v_volume, volname,
				    LEN_DKL_VVOL);
				break;
				}
				}
			}
			return (0);
		default:
			/* Should never happen */
			return (-1);
		}
	} else if ((index == other_choice) && (cur_label == L_TYPE_SOLARIS)) {
		/*
		 * User chose "other".
		 * Get the standard information on the new type.
		 * Put all information in a tmp structure, in
		 * case user aborts.
		 */
		bzero((char *)d, sizeof (struct disk_type));

		d->dtype_ncyl = get_ncyl();
		d->dtype_acyl = get_acyl(d->dtype_ncyl);
		d->dtype_pcyl = get_pcyl(d->dtype_ncyl, d->dtype_acyl);
		d->dtype_nhead = get_nhead();
		d->dtype_phead = get_phead(d->dtype_nhead, &d->dtype_options);
		d->dtype_nsect = get_nsect();
		d->dtype_psect = get_psect(&d->dtype_options);
		d->dtype_bpt = get_bpt(d->dtype_nsect, &d->dtype_options);
		d->dtype_rpm = get_rpm();
		d->dtype_fmt_time = get_fmt_time(&d->dtype_options);
		d->dtype_cyl_skew = get_cyl_skew(&d->dtype_options);
		d->dtype_trk_skew = get_trk_skew(&d->dtype_options);
		d->dtype_trks_zone = get_trks_zone(&d->dtype_options);
		d->dtype_atrks = get_atrks(&d->dtype_options);
		d->dtype_asect = get_asect(&d->dtype_options);
		d->dtype_cache = get_cache(&d->dtype_options);
		d->dtype_threshold = get_threshold(&d->dtype_options);
		d->dtype_prefetch_min = get_min_prefetch(&d->dtype_options);
		d->dtype_prefetch_max = get_max_prefetch(d->dtype_prefetch_min,
		    &d->dtype_options);
		d->dtype_bps = get_bps();
#if defined(sparc)
		d->dtype_dr_type = 0;
#endif /* defined(sparc) */

		d->dtype_asciilabel = get_asciilabel();
		/*
		 * Add the new type to the list of possible types for
		 * this controller.  We lock out interrupts so the lists
		 * can't get munged.  We put off actually allocating the
		 * structure till here in case the user wanted to
		 * interrupt while still inputting information.
		 */
		enter_critical();
		tptr = (struct disk_type *)zalloc(sizeof (struct disk_type));
		if (type == NULL)
			cur_ctype->ctype_dlist = tptr;
		else {
			while (type->dtype_next != NULL)
				type = type->dtype_next;
			type->dtype_next = tptr;
		}
		bcopy((char *)d, (char *)tptr, sizeof (disk_type));
		tptr->dtype_next = NULL;
		/*
		 * the new disk type does not have any defined
		 * partition table . Hence copy the current partition
		 * table if possible else create a default
		 * paritition table.
		 */
		new_partitiontable(tptr, oldtype);
	} else if ((index == other_choice) && (cur_label == L_TYPE_EFI)) {
		uint64_t start_lba = cur_parts->etoc->efi_first_u_lba;
		uint64_t reserved;

		reserved = efi_reserved_sectors(cur_parts->etoc);
		maxLBA = get_mlba();
		cur_parts->etoc->efi_last_lba = maxLBA;
		cur_parts->etoc->efi_last_u_lba = maxLBA - start_lba;
		for (i = 0; i < cur_parts->etoc->efi_nparts; i++) {
			cur_parts->etoc->efi_parts[i].p_start = 0;
			cur_parts->etoc->efi_parts[i].p_size = 0;
			cur_parts->etoc->efi_parts[i].p_tag = V_UNASSIGNED;
		}
		cur_parts->etoc->efi_parts[8].p_start =
		    maxLBA - start_lba - reserved;
		cur_parts->etoc->efi_parts[8].p_size = reserved;
		cur_parts->etoc->efi_parts[8].p_tag = V_RESERVED;
		if (write_label()) {
			err_print("Write label failed\n");
		} else {
			cur_disk->disk_flags &= ~DSK_LABEL_DIRTY;
		}
		return (0);
	} else {
		/*
		 * User picked an existing disk type.
		 */
		i = first_disk;
		tptr = type;
		while (i < index) {
			if (tptr->dtype_asciilabel) {
				i++;
			}
			tptr = tptr->dtype_next;
		}
		if ((tptr->dtype_asciilabel == NULL) &&
		    (tptr->dtype_next != NULL)) {
			while (tptr->dtype_asciilabel == NULL) {
				tptr = tptr->dtype_next;
			}
		}
	}
	/*
	 * Check for mounted file systems in the format zone.
	 * One potential problem with this would be that check()
	 * always returns 'yes' when running out of a file.  However,
	 * it is actually ok because we don't let the program get
	 * started if there are mounted file systems and we are
	 * running from a file.
	 */
	if ((tptr != oldtype) &&
	    checkmount((diskaddr_t)-1, (diskaddr_t)-1)) {
		err_print(
		    "Cannot set disk type while it has mounted "
		    "partitions.\n\n");
		return (-1);
	}
	/*
	 * check for partitions being used for swapping in format zone
	 */
	if ((tptr != oldtype) &&
	    checkswap((diskaddr_t)-1, (diskaddr_t)-1)) {
		err_print("Cannot set disk type while its partition are "
		"currently being used for swapping.\n");
		return (-1);
	}

	/*
	 * Check for partitions being used in SVM, VxVM or LU devices
	 */

	if ((tptr != oldtype) &&
	    checkdevinuse(cur_disk->disk_name, (diskaddr_t)-1,
	    (diskaddr_t)-1, 0, 0)) {
		err_print("Cannot set disk type while its "
		    "partitions are currently in use.\n");
		return (-1);
	}
	/*
	 * If the type selected is different from the previous type,
	 * mark the disk as not labelled and reload the current
	 * partition info.  This is not essential but probably the
	 * right thing to do, since the size of the disk has probably
	 * changed.
	 */
	enter_critical();
	if (tptr != oldtype) {
		cur_disk->disk_type = tptr;
		cur_disk->disk_parts = NULL;
		cur_disk->disk_flags &= ~DSK_LABEL;
	}
	/*
	 * Initialize the state of the current disk.
	 */
	init_globals(cur_disk);
	(void) get_partition();
	exit_critical();

	/*
	 * If the label of the disk is marked dirty,
	 * see if they'd like to label the disk now.
	 */
	if (cur_disk->disk_flags & DSK_LABEL_DIRTY) {
		if (check("Disk not labeled.  Label it now") == 0) {
			if (write_label()) {
				err_print("Write label failed\n");
			} else {
				cur_disk->disk_flags &= ~DSK_LABEL_DIRTY;
			}
		}
	}

	return (0);
}

/*
 * This routine implements the 'partition' command.  It simply runs
 * the partition menu.
 */
int
c_partition(void)
{

	/*
	 * There must be a current disk type and a current disk
	 */
	if (cur_dtype == NULL) {
		err_print("Current Disk Type is not set.\n");
		return (-1);
	}
	/*
	 * Check for a valid fdisk table entry for Solaris
	 */
	if (!good_fdisk()) {
		return (-1);
	}

	cur_menu++;
	last_menu = cur_menu;

#ifdef	not
	/*
	 * If there is no current partition table, make one.  This is
	 * so the commands within the menu never have to check for
	 * a non-existent table.
	 */
	if (cur_parts == NULL)
		err_print("making partition.\n");
		make_partition();
#endif	/* not */

	/*
	 * Run the menu.
	 */
	run_menu(menu_partition, "PARTITION", "partition", 0);
	cur_menu--;
	return (0);
}

/*
 * This routine implements the 'current' command.  It describes the
 * current disk.
 */
int
c_current(void)
{

	/*
	 * If there is no current disk, say so.  Note that this is
	 * not an error since it is a legitimate response to the inquiry.
	 */
	if (cur_disk == NULL) {
		fmt_print("No Current Disk.\n");
		return (0);
	}
	/*
	 * Print out the info we have on the current disk.
	 */
	fmt_print("Current Disk = %s", cur_disk->disk_name);
	if (chk_volname(cur_disk)) {
		fmt_print(": ");
		print_volname(cur_disk);
	}
	fmt_print("\n");
	if (cur_disk->devfs_name != NULL) {
		if (cur_dtype == NULL) {
			fmt_print("<type unknown>\n");
		} else if (cur_label == L_TYPE_SOLARIS) {
			fmt_print("<%s cyl %d alt %d hd %d sec %d>\n",
			    cur_dtype->dtype_asciilabel, ncyl,
			    acyl, nhead, nsect);
		} else if (cur_label == L_TYPE_EFI) {
			print_efi_string(cur_dtype->vendor,
			    cur_dtype->product, cur_dtype->revision,
			    cur_dtype->capacity);
			fmt_print("\n");
		}
		fmt_print("%s\n", cur_disk->devfs_name);
	} else {
		fmt_print("%s%d: <", cur_ctlr->ctlr_dname,
		    cur_disk->disk_dkinfo.dki_unit);
		if (cur_dtype == NULL) {
			fmt_print("type unknown");
		} else if (cur_label == L_TYPE_SOLARIS) {
			fmt_print("%s cyl %d alt %d hd %d sec %d",
			    cur_dtype->dtype_asciilabel, ncyl,
			    acyl, nhead, nsect);
		} else if (cur_label == L_TYPE_EFI) {
			print_efi_string(cur_dtype->vendor,
			    cur_dtype->product, cur_dtype->revision,
			    cur_dtype->capacity);
			fmt_print("\n");
		}
		fmt_print(">\n");
	}
	fmt_print("\n");
	return (0);
}
/*
 * This routine implements the 'format' command.  It allows the user
 * to format and verify any portion of the disk.
 */
int
c_format(void)
{
	diskaddr_t		start, end;
	time_t			clock;
	int			format_time, format_tracks, format_cyls;
	int			format_interval;
	diskaddr_t		deflt;
	int			status;
	u_ioparam_t		ioparam;
	struct scsi_inquiry	*inq;
	char	rawbuf[MAX_MODE_SENSE_SIZE];
	struct scsi_capacity_16	capacity;
	struct vpd_hdr	*vpdhdr;
	uint8_t	protect;
	uint8_t	pagecode;
	uint8_t	spt;
	uint8_t	p_type;
	uint8_t	prot_flag[NUM_PROT_TYPE] = {1, 0, 0, 0};
	int	i;
	char	*prot_descriptor[NUM_PROT_TYPE] = {
	    "Protection Information is disabled.",
	    "Protection Information is enabled.",
	    "Protection Information is enabled.",
	    "Protection Information is enabled.", };

	/*
	 * There must be a current disk type and a current disk
	 */
	if (cur_dtype == NULL) {
		err_print("Current Disk Type is not set.\n");
		return (-1);
	}

	/*
	 * There must be a format routine in cur_ops structure to have
	 *  this routine work.
	 */
	if (cur_ops->op_format == NULL) {
		err_print(
"Cannot format this drive. Please use your Manufacturer supplied formatting "
"utility.\n");
		return (-1);
	}

	/*
	 * There must be a current defect list.  Except for
	 * unformatted SCSI disks.  For them the defect list
	 * can only be retrieved after formatting the disk.
	 */
	if ((cur_ctype->ctype_flags & CF_SCSI) && !EMBEDDED_SCSI &&
	    (cur_ctype->ctype_flags & CF_DEFECTS) &&
	    ! (cur_flags & DISK_FORMATTED)) {
		cur_list.flags |= LIST_RELOAD;

	} else if (cur_list.list == NULL && !EMBEDDED_SCSI) {
		err_print("Current Defect List must be initialized.\n");
		return (-1);
	}
	/*
	 * Ask for the bounds of the format.  We always use the whole
	 * disk as the default, since that is the most likely case.
	 * Note, for disks which must be formatted accross the whole disk,
	 * don't bother the user.
	 */
	ioparam.io_bounds.lower = start = 0;
	if (cur_label == L_TYPE_SOLARIS) {
		if (cur_ctype->ctype_flags & CF_SCSI) {
			ioparam.io_bounds.upper = end = datasects() - 1;
		} else {
			ioparam.io_bounds.upper = end = physsects() - 1;
		}
	} else {
		ioparam.io_bounds.upper = end = cur_parts->etoc->efi_last_lba;
	}

	if (! (cur_ctlr->ctlr_flags & DKI_FMTVOL)) {
		deflt = ioparam.io_bounds.lower;
		start = input(FIO_BN,
		    "Enter starting block number", ':',
		    &ioparam, (int *)&deflt, DATA_INPUT);
		ioparam.io_bounds.lower = start;
		deflt = ioparam.io_bounds.upper;
		end = input(FIO_BN,
		    "Enter ending block number", ':',
		    &ioparam, (int *)&deflt, DATA_INPUT);
	}
	/*
	 * Some disks can format tracks.  Make sure the whole track is
	 * specified for them.
	 */
	if (cur_ctlr->ctlr_flags & DKI_FMTTRK) {
		if (bn2s(start) != 0 ||
		    bn2s(end) != sectors(bn2h(end)) - 1) {
			err_print("Controller requires formatting of ");
			err_print("entire tracks.\n");
			return (-1);
		}
	}
	/*
	 * Check for mounted file systems in the format zone, and if we
	 * find any, make sure they are really serious.  One potential
	 * problem with this would be that check() always returns 'yes'
	 * when running out of a file.  However, it is actually ok
	 * because we don't let the program get started if there are
	 * mounted file systems and we are running from a file.
	 */
	if (checkmount(start, end)) {
		err_print(
		"Cannot format disk while it has mounted partitions.\n\n");
		return (-1);
	}
	/*
	 * check for partitions being used for swapping in format zone
	 */
	if (checkswap(start, end)) {
		err_print("Cannot format disk while its partition are \
currently being used for swapping.\n");
		return (-1);
	}
	/*
	 * Check for partitions being used in SVM, VxVM or LU devices
	 * in this format zone
	 */
	if (checkdevinuse(cur_disk->disk_name, start, end, 0, 0)) {
		err_print("Cannot format disk while its partitions "
		    "are currently in use.\n");
		return (-1);
	}

	if (cur_disk->disk_lbasize != DEV_BSIZE) {
		fmt_print("Current disk sector size is %d Byte, format\n"
		    "will change the sector size to 512 Byte. ",
		    cur_disk->disk_lbasize);
		if (check("Continue")) {
			return (-1);
		}
	}

	/*
	 * set the default protection type
	 */
	prot_type = PROT_TYPE_0;

	/*
	 * Check if the protect information of this disk is enabled
	 */
	if (uscsi_inquiry(cur_file, rawbuf, sizeof (rawbuf))) {
		err_print("Inquiry failed\n");
		return (-1);
	}
	inq = (struct scsi_inquiry *)rawbuf;
	protect = inq->inq_protect;
	if (protect == 0) {
		fmt_print("The protection information is not enabled\n");
		fmt_print(
		    "The disk will be formatted with protection type 0\n");
	} else {
		(void) memset(rawbuf, 0, MAX_MODE_SENSE_SIZE);
		if (uscsi_inquiry_page_86h(cur_file, rawbuf, sizeof (rawbuf))) {
			err_print("Inquiry with page 86h failed\n");
			return (-1);
		}
		vpdhdr = (struct vpd_hdr *)rawbuf;
		pagecode = vpdhdr->page_code;
		if (pagecode != 0x86) {
			err_print("Inquiry with page 86h failed\n");
			return (-1);
		}
		spt = (rawbuf[4] << 2) >> 5;
		fmt_print("This disk can support protection types:\n");

		switch (spt) {
		case 0:
			prot_flag[1] = 1;
			break;
		case 1:
			prot_flag[1] = 1;
			prot_flag[2] = 1;
			break;
		case 2:
			prot_flag[2] = 1;
			break;
		case 3:
			prot_flag[1] = 1;
			prot_flag[3] = 1;
			break;
		case 4:
			prot_flag[3] = 1;
			break;
		case 5:
			prot_flag[2] = 1;
			prot_flag[3] = 1;
			break;
		case 7:
			prot_flag[1] = 1;
			prot_flag[2] = 1;
			prot_flag[3] = 1;
			break;
		default:
			err_print(
			    "Invalid supported protection types\n");
			return (-1);
		}
		for (i = 0; i < NUM_PROT_TYPE; i++) {
			if (prot_flag[i] == 1) {
				fmt_print("[%d] TYPE_%d : ", i, i);
				fmt_print("%s\n", prot_descriptor[i]);
			}
		}

		/*
		 * Get the current protection type
		 */
		if (uscsi_read_capacity_16(cur_file, &capacity)) {
			err_print("Read capacity_16 failed\n");
			return (-1);
		}
		p_type = get_cur_protection_type(&capacity);
		fmt_print("\nThe disk is currently formatted with TYPE_%d.\n",
		    p_type);

		/*
		 * Ask user what protection type to use
		 */
		ioparam.io_bounds.lower = PROT_TYPE_0;
		ioparam.io_bounds.upper = PROT_TYPE_3;
		prot_type = input(FIO_INT, "Specify the New Protection Type",
		    ':', &ioparam, NULL, DATA_INPUT);
		/*
		 * if get a unsupported protection type, then use the
		 * current type: p_type.
		 */
		if (prot_flag[prot_type] == 0) {
			fmt_print("Unsupported protection type.\n");
			prot_type = p_type;
		}
		fmt_print("The disk will be formatted to type %d\n", prot_type);
	}

	if (SCSI && (format_time = scsi_format_time()) > 0) {
		fmt_print(
		    "\nReady to format.  Formatting cannot be interrupted\n"
		    "and takes %d minutes (estimated). ", format_time);

	} else if (cur_dtype->dtype_options & SUP_FMTTIME) {
		/*
		 * Formatting time is (2 * time of 1 spin * number of
		 * tracks) + (step rate * number of cylinders) rounded
		 * up to the nearest minute.  Note, a 10% fudge factor
		 * is thrown in for insurance.
		 */
		if (cur_dtype->dtype_fmt_time == 0)
			cur_dtype->dtype_fmt_time = 2;

		format_tracks = ((end-start) / cur_dtype->dtype_nsect) + 1;
		format_cyls = format_tracks / cur_dtype->dtype_nhead;
		format_tracks = format_tracks * cur_dtype->dtype_fmt_time;

		/*
		 * ms.
		 */
		format_time = ((60000 / cur_dtype->dtype_rpm) +1) *
		    format_tracks + format_cyls * 7;
		/*
		 * 20% done tick (sec)
		 */
		format_interval = format_time / 5000;
		/*
		 * min.
		 */
		format_time = (format_time + 59999) / 60000;

		/*
		 * Check format time values and make adjustments
		 * to prevent sleeping too long (forever?) or
		 * too short.
		 */
		if (format_time <= 1) {
			/*
			 * Format time is less than 1 min..
			 */
			format_time = 1;
		}

		if (format_interval < 11) {
			/* Format time is less than 1 minute. */
			if (format_interval < 2)
				format_interval = 2;	/* failsafe */
			format_interval = 10;
		} else {
			/* Format time is greater than 1 minute. */
			format_interval -= 10;
		}

		fmt_print(
		    "Ready to format.  Formatting cannot be interrupted\n"
		    "and takes %d minutes (estimated). ", format_time);
	} else {
		fmt_print(
		    "Ready to format.  Formatting cannot be interrupted.\n");
	}
	if (check("Continue")) {
		return (-1);
	}

	/*
	 * Print the time so that the user will know when format started.
	 * Lock out interrupts.  This could be a problem, since it could
	 * cause the user to sit for quite awhile with no control, but we
	 * don't have any other good way of keeping their gun from going off.
	 */
	clock = time(NULL);
	fmt_print("Beginning format. The current time is %s\n",
	    ctime(&clock));
	enter_critical();
	/*
	 * Mark the defect list dirty so it will be rewritten when we are
	 * done.  It is possible to qualify this so it doesn't always
	 * get rewritten, but it's not worth the trouble.
	 * Note: no defect lists for embedded scsi drives.
	 */
	if (!EMBEDDED_SCSI) {
		cur_list.flags |= LIST_DIRTY;
	}
	/*
	 * If we are formatting over any of the labels, mark the label
	 * dirty so it will be rewritten.
	 */
	if (cur_disk->label_type == L_TYPE_SOLARIS) {
		if (start < totalsects() && end >= datasects()) {
			if (cur_disk->disk_flags & DSK_LABEL)
				cur_flags |= LABEL_DIRTY;
		}
	} else if (cur_disk->label_type == L_TYPE_EFI) {
		if (start < cur_parts->etoc->efi_first_u_lba) {
			if (cur_disk->disk_flags & DSK_LABEL)
				cur_flags |= LABEL_DIRTY;
		}
	}
	if (start == 0) {
		cur_flags |= LABEL_DIRTY;
	}
	/*
	 * Do the format. bugid 1009138 removed the use of fork to
	 * background the format and print a tick.
	 */

	status = (*cur_ops->op_format)(start, end, &cur_list);
	if (status) {
		exit_critical();
		err_print("failed\n");
		return (-1);
	}
	fmt_print("done\n");
	if (option_msg && diag_msg) {
		clock = time((time_t *)0);
		fmt_print("The current time is %s\n", ctime(&clock));
	}
	cur_flags |= DISK_FORMATTED;
	/*
	 * If the defect list or label is dirty, write them out again.
	 * Note, for SCSI we have to wait til now to load defect list
	 * since we can't access it until after formatting a virgin disk.
	 */
	/* enter_critical(); */
	if (cur_list.flags & LIST_RELOAD) {
		assert(!EMBEDDED_SCSI);
		if (*cur_ops->op_ex_man == NULL ||
		    (*cur_ops->op_ex_man)(&cur_list)) {
			err_print("Warning: unable to reload defect list\n");
			cur_list.flags &= ~LIST_DIRTY;
			return (-1);
		}
		cur_list.flags |= LIST_DIRTY;
	}

	if (cur_list.flags & LIST_DIRTY) {
		assert(!EMBEDDED_SCSI);
		write_deflist(&cur_list);
		cur_list.flags = 0;
	}
	if (cur_flags & LABEL_DIRTY) {
		(void) write_label();
		cur_flags &= ~LABEL_DIRTY;
	}
	/*
	 * Come up for air, since the verify step does not need to
	 * be atomic (it does it's own lockouts when necessary).
	 */
	exit_critical();
	/*
	 * If we are supposed to verify, we do the 'write' test over
	 * the format zone.  The rest of the analysis parameters are
	 * left the way they were.
	 */
	if (scan_auto) {
		scan_entire = 0;
		scan_lower = start;
		scan_upper = end;
		fmt_print("\nVerifying media...");
		status = do_scan(SCAN_PATTERN, F_SILENT);
	}
	/*
	 * If the defect list or label is dirty, write them out again.
	 */
	if (cur_list.flags & LIST_DIRTY) {
		assert(!EMBEDDED_SCSI);
		cur_list.flags = 0;
		write_deflist(&cur_list);
	}
	if (cur_flags & LABEL_DIRTY) {
		cur_flags &= ~LABEL_DIRTY;
		(void) write_label();
	}
	return (status);
}

/*
 * This routine implements the 'repair' command.  It allows the user
 * to reallocate sectors on the disk that have gone bad.
 */
int
c_repair(void)
{
	diskaddr_t	bn;
	int		status;
	u_ioparam_t	ioparam;
	char		*buf;
	int		buf_is_good;
	int		block_has_error;
	int		i;

	/*
	 * There must be a current disk type (and therefore a current disk).
	 */
	if (cur_dtype == NULL) {
		err_print("Current Disk Type is not set.\n");
		return (-1);
	}
	/*
	 * The current disk must be formatted for repair to work.
	 */
	if (!(cur_flags & DISK_FORMATTED)) {
		err_print("Current Disk is unformatted.\n");
		return (-1);
	}
	/*
	 * Check for a valid fdisk table entry for Solaris
	 */
	if (!good_fdisk()) {
		return (-1);
	}
	/*
	 * Repair is an optional command for controllers, so it may
	 * not be supported.
	 */
	if (cur_ops->op_repair == NULL) {
		err_print("Controller does not support repairing.\n");
		err_print("or disk supports automatic defect management.\n");
		return (-1);
	}
	/*
	 * There must be a defect list for non-embedded scsi devices,
	 * since we will add to it.
	 */
	if (!EMBEDDED_SCSI && cur_list.list == NULL) {
		err_print("Current Defect List must be initialized.\n");
		return (-1);
	}
	/*
	 * Ask the user which sector has gone bad.
	 */
	ioparam.io_bounds.lower = 0;
	if (cur_disk->label_type == L_TYPE_SOLARIS) {
		ioparam.io_bounds.upper = physsects() - 1;
	} else {
		ioparam.io_bounds.upper = cur_parts->etoc->efi_last_lba;
	}
	bn = input(FIO_BN,
	    "Enter absolute block number of defect", ':',
	    &ioparam, NULL, DATA_INPUT);
	/*
	 * Check to see if there is a mounted file system over the
	 * specified sector.  If there is, make sure the user is
	 * really serious.
	 */
	if (checkmount(bn, bn)) {
		if (check("Repair is in a mounted partition, continue"))
			return (-1);
	}
	/*
	 * check for partitions being used for swapping in format zone
	 */
	if (checkswap(bn, bn)) {
		if (check("Repair is in a partition which is currently \
being used for swapping.\ncontinue"))
		return (-1);
	}

	if (checkdevinuse(cur_disk->disk_name, bn, bn, 0, 0)) {
		if (check("Repair is in a partition which is currently "
		    "in use.\ncontinue"))
			return (-1);
	}

	buf = zalloc((cur_disk->disk_lbasize == 0) ?
	    SECSIZE : cur_disk->disk_lbasize);

	/*
	 * Try to read the sector before repairing it.  If we can
	 * get good data out of it, we can write that data back
	 * after the repair.  If the sector looks ok, ask the
	 * user to confirm the repair, since it doesn't appear
	 * necessary.  Try reading the block several times to
	 * see if we can read it consistently.
	 *
	 * First, let's see if the block appears to have problems...
	 */
	block_has_error = 1;
	for (i = 0; i < 5; i++) {
		status = (*cur_ops->op_rdwr)(DIR_READ, cur_file, bn,
		    1, buf, (F_SILENT | F_ALLERRS), NULL);
		if (status)
			break;		/* one of the tries failed */
	}
	if (status == 0) {
		block_has_error = 0;
		if (check("\
This block doesn't appear to be bad.  Repair it anyway")) {
			free(buf);
			return (0);
		}
	}
	/*
	 * Last chance...
	 */
	if (check("Ready to repair defect, continue")) {
		free(buf);
		return (-1);
	}
	/*
	 * We're committed to repairing it.  Try to get any good
	 * data out of the block if possible.  Note that we do
	 * not set the F_ALLERRS flag.
	 */
	buf_is_good = 0;
	for (i = 0; i < 5; i++) {
		status = (*cur_ops->op_rdwr)(DIR_READ, cur_file, bn,
		    1, buf, F_SILENT, NULL);
		if (status == 0) {
			buf_is_good = 1;
			break;
		}
	}
	/*
	 * Lock out interrupts so the disk can't get out of sync with
	 * the defect list.
	 */
	enter_critical();

	fmt_print("Repairing ");
	if (block_has_error) {
		fmt_print("%s error on ", buf_is_good ? "soft" : "hard");
	}
	fmt_print("block %llu (", bn);
	pr_dblock(fmt_print, bn);
	fmt_print(")...");
	/*
	 * Do the repair.
	 */
	status = (*cur_ops->op_repair)(bn, F_NORMAL);
	if (status) {
		fmt_print("failed.\n\n");
	} else {
		/*
		 * The repair worked.  Write the old data to the new
		 * block if we were able to read it, otherwise
		 * zero out the new block.  If it looks like the
		 * new block is bad, let the user know that, too.
		 * Should we attempt auto-repair in this case?
		 */
		fmt_print("ok.\n");
		if (!buf_is_good) {
			bzero(buf, cur_disk->disk_lbasize);
		}
		status = (*cur_ops->op_rdwr)(DIR_WRITE, cur_file, bn,
		    1, buf, (F_SILENT | F_ALLERRS), NULL);
		if (status == 0) {
			status = (*cur_ops->op_rdwr)(DIR_READ, cur_file,
			    bn, 1, buf, (F_SILENT | F_ALLERRS), NULL);
		}
		if (status) {
			fmt_print("The new block %llu (", bn);
			pr_dblock(fmt_print, bn);
			fmt_print(") also appears defective.\n");
		}
		fmt_print("\n");
		/*
		 * Add the bad sector to the defect list, write out
		 * the defect list, and kill off the working list so
		 * it will get synced up with the current defect list
		 * next time we need it.
		 *
		 * For embedded scsi, we don't require a defect list.
		 * However, if we have one, add the defect if the
		 * list includes the grown list.  If not, kill it
		 * to force a resync if we need the list later.
		 */
		if (EMBEDDED_SCSI) {
			if (cur_list.list != NULL) {
				if (cur_list.flags & LIST_PGLIST) {
					add_ldef(bn, &cur_list);
				} else {
					kill_deflist(&cur_list);
				}
			}
		} else if (cur_ctype->ctype_flags & CF_WLIST) {
			kill_deflist(&cur_list);
			if (*cur_ops->op_ex_cur != NULL) {
				(*cur_ops->op_ex_cur)(&cur_list);
				fmt_print("Current list updated\n");
			}
		} else {
			add_ldef(bn, &cur_list);
			write_deflist(&cur_list);
		}
		kill_deflist(&work_list);
	}
	exit_critical();
	free(buf);

	/*
	 * Return status.
	 */
	return (status);
}

/*
 * This routine implements the 'show' command.  It translates a disk
 * block given in any format into decimal, hexadecimal, and
 * cylinder/head/sector format.
 */
int
c_show(void)
{
	u_ioparam_t	ioparam;
	diskaddr_t	bn;

	/*
	 * There must be a current disk type, so we will know the geometry.
	 */
	if (cur_dtype == NULL) {
		err_print("Current Disk Type is not set.\n");
		return (-1);
	}
	/*
	 * Ask the user for a disk block.
	 */
	ioparam.io_bounds.lower = 0;
	if (cur_disk->label_type == L_TYPE_SOLARIS) {
		ioparam.io_bounds.upper = physsects() - 1;
	} else {
		ioparam.io_bounds.upper = cur_parts->etoc->efi_last_lba;
	}
	bn = input(FIO_BN, "Enter a disk block", ':',
	    &ioparam, NULL, DATA_INPUT);
	/*
	 * Echo it back.
	 */
	fmt_print("Disk block = %lld = 0x%llx = (", bn, bn);
	pr_dblock(fmt_print, bn);
	fmt_print(")\n\n");
	return (0);
}

/*
 * This routine implements the 'label' command.  It writes the
 * primary and backup labels onto the current disk.
 */
int
c_label(void)
{
	int			status;
	int			deflt, *defltptr = NULL;

	/*
	 * There must be a current disk type (and therefore a current disk).
	 */
	if (cur_dtype == NULL) {
		err_print("Current Disk Type is not set.\n");
		return (-1);
	}
	/*
	 * The current disk must be formatted to label it.
	 */
	if (!(cur_flags & DISK_FORMATTED)) {
		err_print("Current Disk is unformatted.\n");
		return (-1);
	}
	/*
	 * Check for a valid fdisk table entry for Solaris
	 */
	if (!good_fdisk()) {
		return (-1);
	}
	/*
	 * Check to see if there are any mounted file systems anywhere
	 * on the current disk.  If so, refuse to label the disk, but
	 * only if the partitions would change for the mounted partitions.
	 *
	 */
	if (checkmount((diskaddr_t)-1, (diskaddr_t)-1)) {
		/* Bleagh, too descriptive */
		if (check_label_with_mount()) {
			err_print("Cannot label disk while it has "
			    "mounted partitions.\n\n");
			return (-1);
		}
	}

	/*
	 * check to see if there any partitions being used for swapping
	 * on the current disk.  If so, refuse to label the disk, but
	 * only if the partitions would change for the mounted partitions.
	 */
	if (checkswap((diskaddr_t)-1, (diskaddr_t)-1)) {
		if (check_label_with_swap()) {
			err_print("Cannot label disk while its "
			    "partitions are currently being used for "
			    "swapping.\n");
			return (-1);
		}
	}

	/*
	 * Check to see if any partitions used for svm, vxvm or live upgrade
	 * are on the disk. If so, refuse to label the disk, but only
	 * if we are trying to shrink a partition in use.
	 */
	if (checkdevinuse(cur_disk->disk_name, (diskaddr_t)-1,
	    (diskaddr_t)-1, 0, 1)) {
		err_print("Cannot label disk when "
		    "partitions are in use as described.\n");
		return (-1);
	}

	/*
	 * If there is not a current partition map, warn the user we
	 * are going to use the default.  The default is the first
	 * partition map we encountered in the data file.  If there is
	 * no default we give up.
	 */
	if (cur_parts == NULL) {
		fmt_print("Current Partition Table is not set, "
		    "using default.\n");
		cur_disk->disk_parts = cur_parts = cur_dtype->dtype_plist;
		if (cur_parts == NULL) {
			err_print("No default available, cannot label.\n");
			return (-1);
		}
	}
	/*
	 * If expert (-e) mode, then ask user if they wish
	 * to change the current solaris label into an EFI one
	 */
	if (expert_mode) {
#if defined(_SUNOS_VTOC_8)
		int		i;
#endif
		int		choice;
		u_ioparam_t		ioparam;
		struct extvtoc	vtoc;
		struct dk_label	label;
		struct dk_gpt	*vtoc64;
		struct efi_info	efinfo;
		struct disk_type	*dptr;

		/* Ask user what label to use */
		fmt_print("[0] SMI Label\n");
		fmt_print("[1] EFI Label\n");
		ioparam.io_bounds.lower = 0;
		ioparam.io_bounds.upper = 1;
		if ((cur_label == L_TYPE_SOLARIS) &&
		    (cur_disk->fdisk_part.systid != EFI_PMBR))
			deflt = L_TYPE_SOLARIS;
		else
			deflt = L_TYPE_EFI;
		defltptr = &deflt;
		choice = input(FIO_INT, "Specify Label type", ':',
		    &ioparam, defltptr, DATA_INPUT);
		if ((choice == L_TYPE_SOLARIS) &&
		    (cur_label == L_TYPE_SOLARIS) &&
		    (cur_disk->fdisk_part.systid != EFI_PMBR)) {
			goto expert_end;
		} else if ((choice == L_TYPE_EFI) &&
		    (cur_label == L_TYPE_EFI)) {
			goto expert_end;
		}
		switch (choice) {
		case L_TYPE_SOLARIS:
		/*
		 * EFI label to SMI label
		 */
		if (cur_dtype->capacity > INFINITY) {
			fmt_print("Warning: SMI labels only support up to "
			    "2 TB.\n");
		}

		if (cur_disk->fdisk_part.systid == EFI_PMBR) {
			fmt_print("Warning: This disk has an EFI label. "
			    "Changing to SMI label will erase all\n"
			    "current partitions.\n");
			if (check("Continue"))
			return (-1);
#if defined(_FIRMWARE_NEEDS_FDISK)
			fmt_print("You must use fdisk to delete the current "
			    "EFI partition and create a new\n"
			    "Solaris partition before you can convert the "
			    "label.\n");
			return (-1);
#endif
		}

#if defined(_FIRMWARE_NEEDS_FDISK)
		if (!(((cur_disk->fdisk_part.systid != SUNIXOS) ||
		    (cur_disk->fdisk_part.systid != SUNIXOS2)) &&
		    (cur_disk->fdisk_part.numsect > 0))) {
			fmt_print("You must use fdisk to create a Solaris "
			    "partition before you can convert the label.\n");
			return (-1);
		}
#endif

		(void) memset((char *)&label, 0, sizeof (struct dk_label));

		(void) strcpy(x86_devname, cur_disk->disk_name);
		if (cur_ctype->ctype_ctype == DKC_DIRECT ||
		    cur_ctype->ctype_ctype == DKC_BLKDEV)
			dptr = auto_direct_get_geom_label(cur_file,  &label);
		else
			dptr = auto_sense(cur_file, 1, &label);
		if (dptr == NULL) {
			fmt_print("Autoconfiguration failed.\n");
			return (-1);
		}

		pcyl = label.dkl_pcyl;
		ncyl = label.dkl_ncyl;
		acyl = label.dkl_acyl;
		nhead = label.dkl_nhead;
		nsect = label.dkl_nsect;

		if (delete_disk_type(cur_disk->disk_type) == 0) {
			cur_label = L_TYPE_SOLARIS;
			cur_disk->label_type = L_TYPE_SOLARIS;
			cur_disk->disk_type = dptr;
			cur_disk->disk_parts = dptr->dtype_plist;
			cur_dtype = dptr;
			cur_parts = dptr->dtype_plist;

			if (status = write_label())
				err_print("Label failed.\n");
			else
				cur_disk->disk_flags &= ~DSK_LABEL_DIRTY;

			return (status);
		} else {
			err_print("Label failed.\n");
			return (-1);
		}


		case L_TYPE_EFI:
		/*
		 * SMI label to EFI label
		 */

		if ((cur_disk->fdisk_part.systid == SUNIXOS) ||
		    (cur_disk->fdisk_part.systid == SUNIXOS2)) {
			fmt_print("Warning: This disk has an SMI label. "
			    "Changing to EFI label will erase all\ncurrent "
			    "partitions.\n");
			if (check("Continue")) {
				return (-1);
			}
		}

		if (get_disk_info(cur_file, &efinfo, cur_disk) != 0) {
			return (-1);
		}
		(void) memset((char *)&label, 0, sizeof (struct dk_label));
		label.dkl_pcyl = pcyl;
		label.dkl_ncyl = ncyl;
		label.dkl_acyl = acyl;
#if defined(_SUNOS_VTOC_16)
		label.dkl_bcyl = bcyl;
#endif			/* defined(_SUNOC_VTOC_16) */
		label.dkl_nhead = nhead;
		label.dkl_nsect = nsect;
#if defined(_SUNOS_VTOC_8)
		for (i = 0; i < NDKMAP; i++) {
			label.dkl_map[i] = cur_parts->pinfo_map[i];
		}
#endif			/* defined(_SUNOS_VTOC_8) */
		label.dkl_magic = DKL_MAGIC;
		label.dkl_vtoc = cur_parts->vtoc;
		if (label_to_vtoc(&vtoc, &label) == -1) {
			return (-1);
		}
		if (SMI_vtoc_to_EFI(cur_file, &vtoc64) == -1) {
			return (-1);
		}
		if (efi_write(cur_file, vtoc64) != 0) {
			efi_err_check(vtoc64);
			err_print("Warning: error writing EFI.\n");
			return (-1);
		} else {
			cur_disk->disk_flags &= ~DSK_LABEL_DIRTY;
		}
		/*
		 * copy over the EFI vtoc onto the SMI vtoc and return
		 * okay.
		 */
		dptr = auto_efi_sense(cur_file, &efinfo);
		if (dptr == NULL) {
			fmt_print("Autoconfiguration failed.\n");
			return (-1);
		}

		cur_label = L_TYPE_EFI;
		cur_disk->label_type = L_TYPE_EFI;
		cur_disk->disk_type = dptr;
		cur_disk->disk_parts = dptr->dtype_plist;
		cur_dtype = dptr;
		cur_parts = dptr->dtype_plist;
		cur_parts->etoc = vtoc64;

		ncyl = pcyl = nsect = psect = acyl = phead = 0;

		/*
		 * Get the Solais Fdisk Partition information.
		 */
		(void) copy_solaris_part(&cur_disk->fdisk_part);

		return (0);
		}
	}

expert_end:
	/*
	 * Make sure the user is serious.
	 */
	if (check("Ready to label disk, continue")) {
		return (-1);
	}
	/*
	 * Write the labels out (this will also notify unix) and
	 * return status.
	 */
	fmt_print("\n");
	if (status = write_label())
		err_print("Label failed.\n");
	return (status);
}

/*
 * This routine implements the 'analyze' command.  It simply runs
 * the analyze menu.
 */
int
c_analyze(void)
{

	/*
	 * There must be a current disk type (and therefor a current disk).
	 */
	if (cur_dtype == NULL) {
		err_print("Current Disk Type is not set.\n");
		return (-1);
	}
	cur_menu++;
	last_menu = cur_menu;

	/*
	 * Run the menu.
	 */
	run_menu(menu_analyze, "ANALYZE", "analyze", 0);
	cur_menu--;
	return (0);
}

/*
 * This routine implements the 'defect' command.  It simply runs
 * the defect menu.
 */
int
c_defect(void)
{
	int	i;

	/*
	 * There must be a current disk type (and therefor a current disk).
	 */
	if (cur_dtype == NULL) {
		err_print("Current Disk Type is not set.\n");
		return (-1);
	}

	/*
	 * Check for the defect management and list management ops and
	 * display appropriate message.
	 */
	if ((cur_ops->op_ex_man == NULL) && (cur_ops->op_ex_cur == NULL) &&
	    (cur_ops->op_create == NULL) && (cur_ops->op_wr_cur == NULL)) {
		err_print("Controller does not support defect management\n");
		err_print("or disk supports automatic defect management.\n");
		return (-1);
	}
	cur_menu++;
	last_menu = cur_menu;

	/*
	 * Lock out interrupt while we manipulate the defect lists.
	 */
	enter_critical();
	/*
	 * If the working list is null but there is a current list,
	 * update the working list to be a copy of the current list.
	 */
	if ((work_list.list == NULL) && (cur_list.list != NULL)) {
		work_list.header = cur_list.header;
		work_list.list = (struct defect_entry *)zalloc(
		    deflist_size(cur_blksz, work_list.header.count) *
		    cur_blksz);
		for (i = 0; i < work_list.header.count; i++)
			*(work_list.list + i) = *(cur_list.list + i);
		work_list.flags = cur_list.flags & LIST_PGLIST;
	}
	exit_critical();
	/*
	 * Run the menu.
	 */
	run_menu(menu_defect, "DEFECT", "defect", 0);
	cur_menu--;

	/*
	 * If the user has modified the working list but not committed
	 * it, warn them that they are probably making a mistake.
	 */
	if (work_list.flags & LIST_DIRTY) {
		if (!EMBEDDED_SCSI) {
			err_print(
		"Warning: working defect list modified; but not committed.\n");
			if (!check(
		"Do you wish to commit changes to current defect list"))
			(void) do_commit();
		}
	}
	return (0);
}

/*
 * This routine implements the 'backup' command.  It allows the user
 * to search for backup labels on the current disk.  This is useful
 * if the primary label was lost and the user wishes to recover the
 * partition information for the disk. The disk is relabeled and
 * the current defect list is written out if a backup label is found.
 */
int
c_backup(void)
{
	struct	dk_label label;
	struct	disk_type *dtype;
	struct	partition_info *parts, *plist;
	diskaddr_t	bn;
	int	sec, head, i;
	char	*buf;

	/*
	 * There must be a current disk type (and therefore a current disk).
	 */
	if (cur_dtype == NULL) {
		err_print("Current Disk Type is not set.\n");
		return (-1);
	}
	/*
	 * The disk must be formatted to read backup labels.
	 */
	if (!(cur_flags & DISK_FORMATTED)) {
		err_print("Current Disk is unformatted.\n");
		return (-1);
	}
	/*
	 * Check for a valid fdisk table entry for Solaris
	 */
	if (!good_fdisk()) {
		return (-1);
	}
	/*
	 * If we found a primary label on this disk, make sure
	 * the user is serious.
	 */
	if (cur_disk->label_type == L_TYPE_EFI) {
		if (((cur_disk->disk_parts->etoc->efi_flags &
		    EFI_GPT_PRIMARY_CORRUPT) == 0) &&
		    check("Disk has a primary label, still continue"))
			return (-1);
		fmt_print("Restoring primary label.\n");
		if (write_label()) {
			err_print("Failed\n");
			return (-1);
		}
		return (0);
	} else if (((cur_disk->disk_flags & (DSK_LABEL | DSK_LABEL_DIRTY)) ==
	    DSK_LABEL) &&
	    (check("Disk has a primary label, still continue"))) {
		return (-1);
	}

	buf = zalloc(cur_blksz);
	fmt_print("Searching for backup labels...");
	(void) fflush(stdout);

	/*
	 * Some disks have the backup labels in a strange place.
	 */
	if (cur_ctype->ctype_flags & CF_BLABEL)
		head = 2;
	else
		head = nhead - 1;
	/*
	 * Loop through each copy of the backup label.
	 */
	for (sec = 1; ((sec < BAD_LISTCNT * 2 + 1) && (sec < nsect));
	    sec += 2) {
		bn = chs2bn(ncyl + acyl - 1, head, sec) + solaris_offset;
		/*
		 * Attempt to read it.
		 */
		if ((*cur_ops->op_rdwr)(DIR_READ, cur_file, bn,
		    1, buf, F_NORMAL, NULL)) {
			continue;
		}

		(void) memcpy((char *)&label, buf, sizeof (struct dk_label));

		/*
		 * Verify that it is a reasonable label.
		 */
		if (!checklabel(&label))
			continue;
		if (trim_id(label.dkl_asciilabel))
			continue;
		/*
		 * Lock out interrupts while we manipulate lists.
		 */
		enter_critical();
		fmt_print("found.\n");
		/*
		 * Find out which disk type the backup label claims.
		 */
		for (dtype = cur_ctype->ctype_dlist; dtype != NULL;
		    dtype = dtype->dtype_next)
			if (dtype_match(&label, dtype))
				break;
		/*
		 * If it disagrees with our current type, something
		 * real bad is happening.
		 */
		if (dtype != cur_dtype) {
			if (dtype == NULL) {
				fmt_print("\
Unknown disk type in backup label\n");
				exit_critical();
				free(buf);
				return (-1);
			}
			fmt_print("Backup label claims different type:\n");
			fmt_print("    <%s cyl %d alt %d hd %d sec %d>\n",
			    label.dkl_asciilabel, label.dkl_ncyl,
			    label.dkl_acyl, label.dkl_nhead,
			    label.dkl_nsect);
			if (check("Continue")) {
				exit_critical();
				free(buf);
				return (-1);
			}
			cur_dtype = dtype;
		}
		/*
		 * Try to match the partition map with a known map.
		 */
		for (parts = dtype->dtype_plist; parts != NULL;
		    parts = parts->pinfo_next)
			if (parts_match(&label, parts))
				break;
		/*
		 * If we couldn't match it, allocate space for a new one,
		 * fill in the info, and add it to the list.  The name
		 * for the new map is derived from the disk name.
		 */
		if (parts == NULL) {
			parts = (struct partition_info *)
			    zalloc(sizeof (struct partition_info));
			plist = dtype->dtype_plist;
			if (plist == NULL)
				dtype->dtype_plist = parts;
			else {
				while (plist->pinfo_next != NULL)
					plist = plist->pinfo_next;
				plist->pinfo_next = parts;
			}
			parts->pinfo_name = alloc_string("original");
			for (i = 0; i < NDKMAP; i++) {

#if defined(_SUNOS_VTOC_8)
				parts->pinfo_map[i] = label.dkl_map[i];

#elif defined(_SUNOS_VTOC_16)
				parts->pinfo_map[i].dkl_cylno  =
				    label.dkl_vtoc.v_part[i].p_start / spc();
				parts->pinfo_map[i].dkl_nblk =
				    label.dkl_vtoc.v_part[i].p_size;
#else
#error No VTOC layout defined.
#endif /* defined(_SUNOS_VTOC_8) */
			}
			parts->vtoc = label.dkl_vtoc;
		}
		/*
		 * We now have a partition map.  Make it the current map.
		 */
		cur_disk->disk_parts = cur_parts = parts;
		exit_critical();
		/*
		 * Rewrite the labels and defect lists, as appropriate.
		 */
		if (EMBEDDED_SCSI) {
			fmt_print("Restoring primary label.\n");
			if (write_label()) {
				free(buf);
				return (-1);
			}
		} else {
			fmt_print("Restoring primary label and defect list.\n");
			if (write_label()) {
				free(buf);
				return (-1);
			}
			if (cur_list.list != NULL)
				write_deflist(&cur_list);
		}
		fmt_print("\n");
		free(buf);
		return (0);
	}
	/*
	 * If we didn't find any backup labels, say so.
	 */
	fmt_print("not found.\n\n");
	free(buf);
	return (0);
}

/*
 * This routine is called by c_verify() for an EFI labeled disk
 */
static int
c_verify_efi(void)
{
	struct efi_info efi_info;
	struct	partition_info	tmp_pinfo;
	int status;

	status = read_efi_label(cur_file, &efi_info, cur_disk);
	if (status != 0) {
		err_print("Warning: Could not read label.\n");
		return (-1);
	}
	if (cur_parts->etoc->efi_flags & EFI_GPT_PRIMARY_CORRUPT) {
		err_print("Reading the primary EFI GPT label ");
		err_print("failed.  Using backup label.\n");
		err_print("Use the 'backup' command to restore ");
		err_print("the primary label.\n");
	}
	tmp_pinfo.etoc = efi_info.e_parts;
	fmt_print("\n");
	fmt_print("Volume name = <%8s>\n",
	    cur_parts->etoc->efi_parts[8].p_name);
	fmt_print("ascii name  = ");
	print_efi_string(efi_info.vendor, efi_info.product,
	    efi_info.revision, efi_info.capacity);
	fmt_print("\n");

	fmt_print("bytes/sector	=  %d\n", cur_blksz);
	fmt_print("sectors = %llu\n", cur_parts->etoc->efi_last_lba + 1);
	fmt_print("accessible sectors = %llu\n",
	    cur_parts->etoc->efi_last_u_lba -
	    cur_parts->etoc->efi_first_u_lba -
	    efi_reserved_sectors(cur_parts->etoc) + 1);
	fmt_print("first usable sector = %llu\n",
	    cur_parts->etoc->efi_first_u_lba);
	fmt_print("last usable sector = %llu\n",
	    cur_parts->etoc->efi_last_u_lba);

	print_map(&tmp_pinfo);

	free(efi_info.vendor);
	free(efi_info.product);
	free(efi_info.revision);
	return (0);
}

/*
 * This routine implements the 'verify' command.  It allows the user
 * to read the labels on the current disk.
 */
int
c_verify(void)
{
	struct	dk_label p_label, b_label, *label;
	struct	partition_info tmp_pinfo;
	diskaddr_t	bn;
	int	sec, head, i, status;
	int	p_label_bad = 0;
	int	b_label_bad = 0;
	int	p_label_found = 0;
	int	b_label_found = 0;
	char	id_str[128];
	char	*buf;

	/*
	 * There must be a current disk type (and therefore a current disk).
	 */
	if (cur_dtype == NULL) {
		err_print("Current Disk Type is not set.\n");
		return (-1);
	}
	/*
	 * The disk must be formatted to read labels.
	 */
	if (!(cur_flags & DISK_FORMATTED)) {
		err_print("Current Disk is unformatted.\n");
		return (-1);
	}
	/*
	 * Check for a valid fdisk table entry for Solaris
	 */
	if (!good_fdisk()) {
		return (-1);
	}
	/*
	 * Branch off here if the disk is EFI labelled.
	 */
	if (cur_label == L_TYPE_EFI) {
		return (c_verify_efi());
	}
	/*
	 * Attempt to read the primary label.
	 */
	status = read_label(cur_file, &p_label);
	if (status == -1) {
		err_print("Warning: Could not read primary label.\n");
		p_label_bad = 1;
	} else {
		/*
		 * Verify that it is a reasonable label.
		 */
		/*
		 * Save complete ascii string for printing later.
		 */
		(void) strncpy(id_str, p_label.dkl_asciilabel, 128);

		if ((!checklabel((struct dk_label *)&p_label)) ||
		    (trim_id(p_label.dkl_asciilabel))) {
			err_print("\
Warning: Primary label appears to be corrupt.\n");
			p_label_bad = 1;
		} else {
			p_label_found = 1;
			/*
			 * Make sure it matches current label
			 */
			if ((!dtype_match(&p_label, cur_dtype)) ||
			    (!parts_match(&p_label, cur_parts))) {
				err_print("\
Warning: Primary label on disk appears to be different from\ncurrent label.\n");
				p_label_bad = 1;
			}
		}
	}

	/*
	 * Read backup labels.
	 * Some disks have the backup labels in a strange place.
	 */
	if (cur_ctype->ctype_flags & CF_BLABEL)
		head = 2;
	else
		head = nhead - 1;

	buf = zalloc(cur_blksz);
	/*
	 * Loop through each copy of the backup label.
	 */
	for (sec = 1; ((sec < BAD_LISTCNT * 2 + 1) && (sec < nsect));
	    sec += 2) {
		bn = chs2bn(ncyl + acyl - 1, head, sec) + solaris_offset;
		/*
		 * Attempt to read it.
		 */
		if ((*cur_ops->op_rdwr)(DIR_READ, cur_file, bn,
		    1, buf, F_NORMAL, NULL))
			continue;

		(void) memcpy((char *)&b_label, buf,
		    sizeof (struct dk_label));

		/*
		 * Verify that it is a reasonable label.
		 */
		if (!checklabel(&b_label))
			continue;

		/*
		 * Save complete label only if no primary label exists
		 */
		if (!p_label_found)
			(void) strncpy(id_str, b_label.dkl_asciilabel, 128);

		if (trim_id(b_label.dkl_asciilabel))
			continue;
		b_label_found = 1;
		/*
		 * Compare against primary label
		 */
		if (p_label_found) {
			if ((strcmp(b_label.dkl_asciilabel,
			    p_label.dkl_asciilabel) != 0) ||
			    (b_label.dkl_ncyl != p_label.dkl_ncyl) ||
			    (b_label.dkl_acyl != p_label.dkl_acyl) ||
			    (b_label.dkl_nhead != p_label.dkl_nhead) ||
			    (b_label.dkl_nsect != p_label.dkl_nsect)) {
				b_label_bad = 1;
			} else {
				for (i = 0; i < NDKMAP; i++) {
#if defined(_SUNOS_VTOC_8)
					if ((b_label.dkl_map[i].dkl_cylno !=
					    p_label.dkl_map[i].dkl_cylno) ||
					    (b_label.dkl_map[i].dkl_nblk !=
					    p_label.dkl_map[i].dkl_nblk)) {
						b_label_bad = 1;
						break;
					}

#elif defined(_SUNOS_VTOC_16)
					if ((b_label.dkl_vtoc.v_part[i].p_tag !=
					    p_label.dkl_vtoc.v_part[i].p_tag) ||
					    (b_label.dkl_vtoc.v_part[i].p_flag
					    != p_label.dkl_vtoc.v_part[i].
					    p_flag) ||
					    (b_label.dkl_vtoc.v_part[i].p_start
					    != p_label.dkl_vtoc.v_part[i].
					    p_start) ||
					    (b_label.dkl_vtoc.v_part[i].p_size
					    != p_label.dkl_vtoc.v_part[i].
					    p_size)) {
						b_label_bad = 1;
						break;
					}
#else
#error No VTOC layout defined.
#endif /* defined(_SUNOS_VTOC_8) */
				}
			}
		}
		if (b_label_bad)
			err_print(
"Warning: Primary and backup labels do not match.\n");
		break;
	}
	/*
	 * If we didn't find any backup labels, say so.
	 */
	if (!b_label_found)
		err_print("Warning: Could not read backup labels.\n");

	if ((!b_label_found) || (p_label_bad) || (b_label_bad))
		err_print("\n\
Warning: Check the current partitioning and 'label' the disk or use the\n\
\t 'backup' command.\n");

	/*
	 * Print label information.
	 */
	if (p_label_found) {
		fmt_print("\nPrimary label contents:\n");
		label = &p_label;
	} else if (b_label_found) {
		fmt_print("\nBackup label contents:\n");
		label = &b_label;
	} else {
		free(buf);
		return (0);
	}

	/*
	 * Must put info into partition_info struct for
	 * for print routine.
	 */
	bzero(&tmp_pinfo, sizeof (struct partition_info));
	for (i = 0; i < NDKMAP; i++) {

#if defined(_SUNOS_VTOC_8)
		tmp_pinfo.pinfo_map[i] = label->dkl_map[i];

#elif defined(_SUNOS_VTOC_16)
		tmp_pinfo.pinfo_map[i].dkl_cylno =
		    label->dkl_vtoc.v_part[i].p_start / spc();
		tmp_pinfo.pinfo_map[i].dkl_nblk =
		    label->dkl_vtoc.v_part[i].p_size;
#else
#error No VTOC layout defined.
#endif /* defined(_SUNOS_VTOC_8) */
	}
	tmp_pinfo.vtoc = label->dkl_vtoc;

	fmt_print("\n");
	fmt_print("Volume name = <%8s>\n", label->dkl_vtoc.v_volume);
	fmt_print("ascii name  = <%s>\n", id_str);
	fmt_print("pcyl        = %4d\n", label->dkl_pcyl);
	fmt_print("ncyl        = %4d\n", label->dkl_ncyl);
	fmt_print("acyl        = %4d\n", label->dkl_acyl);

#if defined(_SUNOS_VTOC_16)
	fmt_print("bcyl        = %4d\n", label->dkl_bcyl);
#endif /* defined(_SUNOS_VTOC_16) */

	fmt_print("nhead       = %4d\n", label->dkl_nhead);
	fmt_print("nsect       = %4d\n", label->dkl_nsect);

	print_map(&tmp_pinfo);
	free(buf);
	return (0);
}


/*
 * This command implements the inquiry command, for embedded SCSI
 * disks only, which issues a SCSI inquiry command, and
 * displays the resulting vendor, product id and revision level.
 */
int
c_inquiry(void)
{
	char			inqbuf[255];
	struct scsi_inquiry	*inq;

	assert(SCSI);

	inq = (struct scsi_inquiry *)inqbuf;

	if (uscsi_inquiry(cur_file, inqbuf, sizeof (inqbuf))) {
		err_print("Failed\n");
		return (-1);
	} else {
		fmt_print("Vendor:   ");
		print_buf(inq->inq_vid, sizeof (inq->inq_vid));
		fmt_print("\nProduct:  ");
		print_buf(inq->inq_pid, sizeof (inq->inq_pid));
		fmt_print("\nRevision: ");
		print_buf(inq->inq_revision, sizeof (inq->inq_revision));
		fmt_print("\n");
	}

	return (0);
}


/*
 * This routine allows the user to set the 8-character
 * volume name in the vtoc.  It then writes both the
 * primary and backup labels onto the current disk.
 */
int
c_volname(void)
{
	int	 status;
	char	*prompt;
	union {
		int	xfoo;
		char	defvolname[LEN_DKL_VVOL+1];
	} x;
	char    s1[MAXPATHLEN], nclean[MAXPATHLEN];
	char	*volname;


	/*
	 * There must be a current disk type (and therefore a current disk).
	 */
	if (cur_dtype == NULL) {
		err_print("Current Disk Type is not set.\n");
		return (-1);
	}
	/*
	 * The current disk must be formatted to label it.
	 */
	if (!(cur_flags & DISK_FORMATTED)) {
		err_print("Current Disk is unformatted.\n");
		return (-1);
	}
	/*
	 * Check for a valid fdisk table entry for Solaris
	 */
	if (!good_fdisk()) {
		return (-1);
	}
	/*
	 * The current disk must be formatted to label it.
	 */
	if (cur_parts == NULL) {
	err_print(
"Please select a partition map for the disk first.\n");
	return (-1);
	}

	/*
	 * Check to see if there are any mounted file systems anywhere
	 * on the current disk.  If so, refuse to label the disk, but
	 * only if the partitions would change for the mounted partitions.
	 *
	 */
	if (checkmount((diskaddr_t)-1, (diskaddr_t)-1)) {
		/* Bleagh, too descriptive */
		if (check_label_with_mount()) {
			err_print(
"Cannot label disk while it has mounted partitions.\n\n");
			return (-1);
		}
	}

	/*
	 * Check to see if there are partitions being used for swapping
	 * on the current disk.  If so, refuse to label the disk, but
	 * only if the partitions would change for the swap partitions.
	 *
	 */
	if (checkswap((diskaddr_t)-1, (diskaddr_t)-1)) {
		/* Bleagh, too descriptive */
		if (check_label_with_swap()) {
			err_print(
"Cannot label disk while its partitions are currently \
being used for swapping.\n\n");
			return (-1);
		}
	}

	/*
	 * Check to see if any partitions used for svm, vxvm, ZFS zpool
	 * or live upgrade are on the disk. If so, refuse to label the
	 * disk, but only if we are trying to shrink a partition in
	 * use.
	 */
	if (checkdevinuse(cur_disk->disk_name, (diskaddr_t)-1,
	    (diskaddr_t)-1, 0, 1)) {
		err_print("Cannot label disk while its partitions "
		    "are in use as described.\n");
		return (-1);
	}

	/*
	 * Prompt for the disk volume name.
	 */
	prompt = "Enter 8-character volume name (remember quotes)";
	bzero(x.defvolname, LEN_DKL_VVOL+1);
	bcopy(cur_disk->v_volume, x.defvolname, LEN_DKL_VVOL);
	/*
	 *  Get the input using "get_inputline" since
	 *  input would never return null string.
	 */
	fmt_print("%s[\"%s\"]:", prompt, x.defvolname);

	/*
	 * Get input from the user.
	 */
	get_inputline(nclean, MAXPATHLEN);
	clean_token(s1, nclean);
	/*
	 * check for return.
	 */
	if (s1[0] == 0) {
		volname = x.defvolname;
	} else {
		/*
		 * remove the " mark from volname.
		 */
		if (s1[0] == '"') {
			int i = 1;
			volname = &s1[1];
			while (s1[i] != '"' && s1[i] != '\0')
				i++;
			s1[i] = '\0';
			clean_token(nclean, volname);
			volname = nclean;
		} else {
			(void) sscanf(&s1[0], "%1024s", nclean);
			volname = nclean;
		};
	}
	/*
	 * Make sure the user is serious.
	 */
	if (check("Ready to label disk, continue")) {
		fmt_print("\n");
		return (-1);
	}
	/*
	 * Use the volume name chosen above
	 */
	bzero(cur_disk->v_volume, LEN_DKL_VVOL);
	bcopy(volname, cur_disk->v_volume, min((int)strlen(volname),
	    LEN_DKL_VVOL));
	if (cur_label == L_TYPE_EFI) {
		bzero(cur_parts->etoc->efi_parts[8].p_name, LEN_DKL_VVOL);
		bcopy(volname, cur_parts->etoc->efi_parts[8].p_name,
		    LEN_DKL_VVOL);
	}
	/*
	 * Write the labels out (this will also notify unix) and
	 * return status.
	 */
	fmt_print("\n");
	if (status = write_label())
		err_print("Label failed.\n");
	return (status);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright (c) 1991-2001 by Sun Microsystems, Inc.
 */

#ifndef	_MENU_COMMAND_H
#define	_MENU_COMMAND_H

#ifdef	__cplusplus
extern "C" {
#endif


/*
 *	Prototypes for ANSI
 */
int	c_disk(void);
int	c_type(void);
int	c_partition(void);
int	c_current(void);
int	c_format(void);
int	c_fdisk(void);
int	c_repair(void);
int	c_show(void);
int	c_label(void);
int	c_analyze(void);
int	c_defect(void);
int	c_backup(void);
int	c_volname(void);
int	c_verify(void);
int	c_inquiry(void);


extern slist_t	ptag_choices[];
extern slist_t	pflag_choices[];

#ifdef	__cplusplus
}
#endif

#endif	/* _MENU_COMMAND_H */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 * Copyright (c) 2016 by Delphix. All rights reserved.
 */

/*
 * This file contains functions to implement the defect menu commands.
 */
#include "global.h"
#include <unistd.h>
#include <string.h>
#include "misc.h"
#include "menu_defect.h"
#include "param.h"
#include "ctlr_scsi.h"

/*
 * This is the working defect list.  All the commands here operate on
 * the working list, except for 'commit'.  This way the user can
 * change their mind at any time without having mangled the current defect
 * list.
 */
struct	defect_list work_list;

static int	commit_list(void);

/*
 * This routine implements the 'restore' command.  It sets the working
 * list equal to the current list.
 */
int
d_restore(void)
{
	int	i;

	assert(!EMBEDDED_SCSI);

	/*
	 * If the working list has not been modified, there's nothing to do.
	 */
	if (!(work_list.flags & LIST_DIRTY)) {
		err_print("working list was not modified.\n");
		return (0);
	}
	/*
	 * Make sure the user is serious.
	 */
	if (check("Ready to update working list, continue"))
		return (-1);
	/*
	 * Lock out interrupts so the lists can't get mangled.
	 */
	enter_critical();
	/*
	 * Kill off the old working list.
	 */
	kill_deflist(&work_list);
	/*
	 * If the current isn't null, set the working list to be a
	 * copy of it.
	 */
	if (cur_list.list != NULL) {
		work_list.header = cur_list.header;
		work_list.list = (struct defect_entry *)zalloc(
		    deflist_size(cur_blksz, work_list.header.count) *
		    cur_blksz);
		for (i = 0; i < work_list.header.count; i++)
			*(work_list.list + i) = *(cur_list.list + i);
	}
	/*
	 * Initialize the flags since they are now in sync.
	 */
	work_list.flags = 0;
	if (work_list.list == NULL)
		fmt_print("working list set to null.\n\n");
	else
		fmt_print("working list updated, total of %d defects.\n\n",
		    work_list.header.count);
	exit_critical();
	return (0);
}

/*
 * This routine implements the 'original' command.  It extracts the
 * manufacturer's defect list from the current disk.
 */
int
d_original(void)
{
	int	status;


	/*
	 * If the controller does not support the extraction, we're out
	 * of luck.
	 */
	if (cur_ops->op_ex_man == NULL) {
		err_print("Controller does not support extracting ");
		err_print("manufacturer's defect list.\n");
		return (-1);
	}
	/*
	 * Make sure the user is serious.  Note, for SCSI disks
	 * since this is instantaneous, we will just do it and
	 * not ask for confirmation.
	 */
	if (!(cur_ctype->ctype_flags & CF_CONFIRM) &&
	    check(
"Ready to update working list. This cannot be interrupted\n\
and may take a long while. Continue"))
		return (-1);
	/*
	 * Lock out interrupts so we don't get half the list.
	 */
	enter_critical();
	/*
	 * Kill off the working list.
	 */
	kill_deflist(&work_list);
	fmt_print("Extracting manufacturer's defect list...");
	/*
	 * Do the extraction.
	 */
	status = (*cur_ops->op_ex_man)(&work_list);
	if (status)
		fmt_print("Extraction failed.\n\n");
	else {
		fmt_print("Extraction complete.\n");
		fmt_print("Working list updated, total of %d defects.\n\n",
		    work_list.header.count);
	}
	/*
	 * Mark the working list dirty since we modified it.
	 */
	work_list.flags |= LIST_DIRTY;
	exit_critical();
	/*
	 * Return status.
	 */
	return (status);
}

/*
 * This routine implements the 'extract' command.  It extracts the
 * entire defect list from the current disk.
 */
int
d_extract(void)
{
	int	status;

	/*
	 * If the controller does not support the extraction, we are out
	 * of luck.
	 */
	if (cur_ops->op_ex_cur == NULL) {
		err_print("Controller does not support extracting ");
		err_print("current defect list.\n");
		return (-1);
	}

	/*
	 * If disk is unformatted, you really shouldn't do this.
	 * However, ask user to be sure.
	 */
	if (! (cur_flags & DISK_FORMATTED) &&
	    (check(
"Cannot extract defect list from an unformatted disk. Continue")))
		return (-1);

	/*
	 * If this takes a long time, let's ask the user if they
	 * doesn't mind waiting.  Note, for SCSI disks
	 * this operation is instantaneous so we won't ask for
	 * for confirmation.
	 */
	if (! (cur_ctype->ctype_flags & CF_CONFIRM) &&
	    check(
"Ready to extract working list. This cannot be interrupted\n\
and may take a long while. Continue"))
		return (-1);
	/*
	 * Lock out interrupts so we don't get half the list and
	 * Kill off the working list.
	 */
	enter_critical();
	kill_deflist(&work_list);
	fmt_print("Extracting defect list...");

	/*
	 * Do the extraction.
	 */
	status = (*cur_ops->op_ex_cur)(&work_list);
	if (status) {
		if (!EMBEDDED_SCSI) {
			if (cur_flags & DISK_FORMATTED)
				read_list(&work_list);

			if (work_list.list != NULL) {
				status = 0;
				fmt_print("Extraction complete.\n");
				fmt_print(
"Working list updated, total of %d defects.\n\n",
				    work_list.header.count);
			} else {
				fmt_print("Extraction failed.\n\n");
			}
		} else {
			fmt_print("Extraction failed.\n\n");
		}
	} else {
		fmt_print("Extraction complete.\n");
		fmt_print("Working list updated, total of %d defects.\n\n",
		    work_list.header.count);
	}
	/*
	 * Mark the working list dirty since we modified it.
	 */
	work_list.flags |= LIST_DIRTY;
	exit_critical();
	/*
	 * Return status.
	 */
	return (status);
}

/*
 * This routine implements the 'add' command.  It allows the user to
 * enter the working defect list manually.  It loops infinitely until
 * the user breaks out with a ctrl-C.
 */
int
d_add(void)
{
	int			type, deflt, index;
	diskaddr_t		bn;
	u_ioparam_t		ioparam;
	struct defect_entry	def;

	assert(!EMBEDDED_SCSI);

	/*
	 * Ask the user which mode of input they'd like to use.
	 */
	fmt_print("        0. bytes-from-index\n");
	fmt_print("        1. logical block\n");
	deflt = 0;
	ioparam.io_bounds.lower = 0;
	ioparam.io_bounds.upper = 1;
	type = input(FIO_INT, "Select input format (enter its number)", ':',
	    &ioparam, &deflt, DATA_INPUT);
	fmt_print("\nEnter Control-C to terminate.\n");
loop:
	if (type) {
		/*
		 * Mode selected is logical block.  Input the defective block
		 * and fill in the defect entry with the info.
		 */
		def.bfi = def.nbits = UNKNOWN;
		ioparam.io_bounds.lower = 0;
		if (cur_disk->label_type == L_TYPE_SOLARIS) {
			ioparam.io_bounds.upper = physsects() - 1;
		} else {
			ioparam.io_bounds.upper = cur_parts->etoc->efi_last_lba;
		}
		bn = input(FIO_BN, "Enter defective block number", ':',
		    &ioparam, NULL, DATA_INPUT);
		def.cyl = bn2c(bn);
		def.head = bn2h(bn);
		def.sect = bn2s(bn);
	} else {
		/*
		 * Mode selected is bytes-from-index.  Input the information
		 * about the defect and fill in the defect entry.
		 */
		def.sect = UNKNOWN;
		ioparam.io_bounds.lower = 0;
		ioparam.io_bounds.upper = pcyl - 1;
		def.cyl = input(FIO_INT,
		    "Enter defect's cylinder number", ':',
		    &ioparam, NULL, DATA_INPUT);
		ioparam.io_bounds.upper = nhead - 1;
		def.head = input(FIO_INT, "Enter defect's head number",
		    ':', &ioparam, NULL, DATA_INPUT);
		ioparam.io_bounds.upper = cur_dtype->dtype_bpt - 1;
		def.bfi = input(FIO_INT, "Enter defect's bytes-from-index",
		    ':', &ioparam, NULL, DATA_INPUT);
		ioparam.io_bounds.lower = -1;
		ioparam.io_bounds.upper = (cur_dtype->dtype_bpt - def.bfi) * 8;
		if (ioparam.io_bounds.upper >= 32 * 1024)
			ioparam.io_bounds.upper = 32 * 1024 - 1;
		/*
		 * Note: a length of -1 means the length is not known.  We
		 * make this the default value.
		 */
		deflt = -1;
		def.nbits = input(FIO_INT, "Enter defect's length (in bits)",
		    ':', &ioparam, &deflt, DATA_INPUT);
	}
	/*
	 * Calculate where in the defect list this defect belongs
	 * and print it out.
	 */
	index = sort_defect(&def, &work_list);
	fmt_print(DEF_PRINTHEADER);
	pr_defect(&def, index);

	/*
	 * Lock out interrupts so lists don't get mangled.
	 * Also, mark the working list dirty since we are modifying it.
	 */
	enter_critical();
	work_list.flags |= LIST_DIRTY;
	/*
	 * If the list is null, create it with zero length.  This is
	 * necessary because the routines to add a defect to the list
	 * assume the list is initialized.
	 */
	if (work_list.list == NULL) {
		work_list.header.magicno = (uint_t)DEFECT_MAGIC;
		work_list.header.count = 0;
		work_list.list = (struct defect_entry *)zalloc(
		    deflist_size(cur_blksz, 0) * cur_blksz);
	}
	/*
	 * Add the defect to the working list.
	 */
	add_def(&def, &work_list, index);
	fmt_print("defect number %d added.\n\n", index + 1);
	exit_critical();
	/*
	 * Loop back for the next defect.
	 */
	goto loop;
	/*NOTREACHED*/
#ifdef	lint
	return (0);
#endif
}

/*
 * This routine implements the 'delete' command.  It allows the user
 * to manually delete a defect from the working list.
 */
int
d_delete(void)
{
	int		i, count, num;
	u_ioparam_t	ioparam;

	assert(!EMBEDDED_SCSI);

	/*
	 * If the working list is null or zero length, there's nothing
	 * to delete.
	 */
	count = work_list.header.count;
	if (work_list.list == NULL || count == 0) {
		err_print("No defects to delete.\n");
		return (-1);
	}
	/*
	 * Ask the user which defect should be deleted. Bounds are off by
	 * one because user sees a one-relative list.
	 */
	ioparam.io_bounds.lower = 1;
	ioparam.io_bounds.upper = count;
	num = input(FIO_INT, "Specify defect to be deleted (enter its number)",
	    ':', &ioparam, NULL, DATA_INPUT);
	/*
	 *
	 * The user thinks it's one relative but it's not really.
	 */
	--num;
	/*
	 * Print the defect selected and ask the user for confirmation.
	 */
	fmt_print(DEF_PRINTHEADER);
	pr_defect(work_list.list + num, num);
	/*
	 * Lock out interrupts so the lists don't get mangled.
	 */
	enter_critical();
	/*
	 * Move down all the defects beyond the one deleted so the defect
	 * list is still fully populated.
	 */
	for (i = num; i < count - 1; i++)
		*(work_list.list + i) = *(work_list.list + i + 1);
	/*
	 * If the size of the list in sectors has changed, reallocate
	 * the list to shrink it appropriately.
	 */
	if (deflist_size(cur_blksz, count - 1) <
	    deflist_size(cur_blksz, count))
		work_list.list = (struct defect_entry *)rezalloc(
		    (void *)work_list.list,
		    deflist_size(cur_blksz, count - 1) * cur_blksz);
	/*
	 * Decrement the defect count.
	 */
	work_list.header.count--;
	/*
	 * Recalculate the list's checksum.
	 */
	(void) checkdefsum(&work_list, CK_MAKESUM);
	/*
	 * Mark the working list dirty since we modified it.
	 */
	work_list.flags |= LIST_DIRTY;
	fmt_print("defect number %d deleted.\n\n", ++num);
	exit_critical();
	return (0);
}

/*
 * This routine implements the 'print' command.  It prints the working
 * defect list out in human-readable format.
 */
int
d_print(void)
{
	int	i, nomore = 0;
	int	c, one_line = 0;
	int	tty_lines = get_tty_lines();

	/*
	 * If the working list is null, there's nothing to print.
	 */
	if (work_list.list == NULL) {
		if (EMBEDDED_SCSI)
			err_print(
"No list defined,extract primary or grown or both defects list first.\n");
		else
			err_print("No working list defined.\n");
		return (-1);
	}
	/*
	 * If we're running from a file, don't use the paging scheme.
	 * If we are running interactive, turn off echoing.
	 */
	if (option_f || (!isatty(0)) || (!isatty(1)))
		nomore++;
	else {
		enter_critical();
		echo_off();
		charmode_on();
		exit_critical();
	}
	/* Print out the banner. */
	if (work_list.header.count != 0)
		fmt_print(DEF_PRINTHEADER);

	/*
	 * Loop through the each defect in the working list.
	 */
	for (i = 0; i < work_list.header.count; i++) {
		/*
		 * If we are paging and hit the end of a page, wait for
		 * the user to hit either space-bar, "q", or return
		 * before going on.
		 */
		if (one_line ||
		    (!nomore && ((i + 1) % (tty_lines - 1) == 0))) {
			/*
			 * Get the next character.
			 */
			fmt_print("- hit space for more - ");
			c = getchar();
			fmt_print("\015");
			one_line = 0;
			/* Handle display one line command (return key) */
			if (c == '\012') {
				one_line++;
			}
			/* Handle Quit command */
			if (c == 'q') {
				fmt_print("                       \015");
				goto PRINT_EXIT;
			}
			/* Handle ^D */
			if (c == '\004')
				fullabort();
		}
		/*
		 * Print the defect.
		 */
		pr_defect(work_list.list + i, i);
	}
	fmt_print("total of %d defects.\n\n", i);
	/*
	 * If we were doing paging, turn echoing back on.
	 */
PRINT_EXIT:
	if (!nomore) {
		enter_critical();
		charmode_off();
		echo_on();
		exit_critical();
	}
	return (0);
}

/*
 * This routine implements the 'dump' command.  It writes the working
 * defect list to a file.
 */
int
d_dump(void)
{
	int	i, status = 0;
	char	*str;
	FILE	*fptr;
	struct	defect_entry *dptr;

	/*
	 * If the working list is null, there's nothing to do.
	 */
	if (work_list.list == NULL) {
		if (EMBEDDED_SCSI)
			err_print(
"No list defined,extract primary or grown or both defects list first.\n");
		else
			err_print("No working list defined.\n");
		return (-1);
	}
	/*
	 * Ask the user for the name of the defect file.  Note that the
	 * input will be in malloc'd space since we are inputting
	 * type OSTR.
	 */
	str = (char *)(uintptr_t)input(FIO_OSTR, "Enter name of defect file",
	    ':', NULL, NULL, DATA_INPUT);
	/*
	 * Lock out interrupts so the file doesn't get half written.
	 */
	enter_critical();
	/*
	 * Open the file for writing.
	 */
	if ((fptr = fopen(str, "w+")) == NULL) {
		err_print("unable to open defect file.\n");
		status = -1;
		goto out;
	}
	/*
	 * Print a header containing the magic number, count, and checksum.
	 */
	(void) fprintf(fptr, "0x%08x%8d  0x%08x\n",
	    work_list.header.magicno,
	    work_list.header.count, work_list.header.cksum);
	/*
	 * Loop through each defect in the working list.  Write the
	 * defect info to the defect file.
	 */
	for (i = 0; i < work_list.header.count; i++) {
		dptr = work_list.list + i;
		(void) fprintf(fptr, "%4d%8d%7d%8d%8d%8d\n",
		    i+1, dptr->cyl, dptr->head,
		    dptr->bfi, dptr->nbits, dptr->sect);
	}
	fmt_print("defect file updated, total of %d defects.\n", i);
	/*
	 * Close the defect file.
	 */
	(void) fclose(fptr);
out:
	/*
	 * Destroy the string used for the file name.
	 */
	destroy_data(str);
	exit_critical();
	fmt_print("\n");
	return (status);
}

/*
 * This routine implements the 'load' command.  It reads the working
 * list in from a file.
 */
int
d_load(void)
{
	int	i, items, status = 0, count, cksum;
	uint_t	magicno;
	char	*str;
	TOKEN	filename;
	FILE	*fptr;
	struct	defect_entry *dptr;

	assert(!EMBEDDED_SCSI);

	/*
	 * Ask the user for the name of the defect file.  Note that the
	 * input will be malloc'd space since we inputted type OSTR.
	 */
	str = (char *)(uintptr_t)input(FIO_OSTR, "Enter name of defect file",
	    ':', NULL, NULL, DATA_INPUT);
	/*
	 * Copy the file name into local space then destroy the string
	 * it came in.  This is simply a precaution against later having
	 * to remember to destroy this space.
	 */
	enter_critical();
	(void) strcpy(filename, str);
	destroy_data(str);
	exit_critical();
	/*
	 * See if the defect file is accessable.  If not, we can't load
	 * from it.  We do this here just so we can get out before asking
	 * the user for confirmation.
	 */
	status = access(filename, 4);
	if (status) {
		err_print("defect file not accessable.\n");
		return (-1);
	}
	/*
	 * Make sure the user is serious.
	 */
	if (check("ready to update working list, continue"))
		return (-1);
	/*
	 * Lock out interrupts so the list doesn't get half loaded.
	 */
	enter_critical();
	/*
	 * Open the defect file.
	 */
	if ((fptr = fopen(filename, "r")) == NULL) {
		err_print("unable to open defect file.\n");
		exit_critical();
		return (-1);
	}
	/*
	 * Scan in the header.
	 */
	items = fscanf(fptr, "0x%x%d  0x%x\n", &magicno,
	    &count, (uint_t *)&cksum);
	/*
	 * If the header is wrong, this isn't a good defect file.
	 */
	if (items != 3 || count < 0 ||
	    (magicno != (uint_t)DEFECT_MAGIC &&
	    magicno != (uint_t)NO_CHECKSUM)) {
		err_print("Defect file is corrupted.\n");
		status = -1;
		goto out;
	}
	/*
	 * Kill off any old defects in the working list.
	 */
	kill_deflist(&work_list);
	/*
	 * Load the working list header with the header info.
	 */
	if (magicno == NO_CHECKSUM)
		work_list.header.magicno = (uint_t)DEFECT_MAGIC;
	else
		work_list.header.magicno = magicno;
	work_list.header.count = count;
	work_list.header.cksum = cksum;
	/*
	 * Allocate space for the new list.
	 */
	work_list.list = (struct defect_entry *)zalloc(
	    deflist_size(cur_blksz, count) * cur_blksz);
	/*
	 * Mark the working list dirty since we are modifying it.
	 */
	work_list.flags |= LIST_DIRTY;
	/*
	 * Loop through each defect in the defect file.
	 */
	for (i = 0; i < count; i++) {
		dptr = work_list.list + i;
		/*
		 * Scan the info into the defect entry.
		 */
		items = fscanf(fptr, "%*d%hd%hd%d%hd%hd\n", &dptr->cyl,
		    &dptr->head, &dptr->bfi, &dptr->nbits, &dptr->sect);
		/*
		 * If it didn't scan right, give up.
		 */
		if (items != 5)
			goto bad;
	}
	/*
	 * Check to be sure the checksum from the defect file was correct
	 * unless there wasn't supposed to be a checksum.
	 * If there was supposed to be a valid checksum and there isn't
	 * then give up.
	 */
	if (magicno != NO_CHECKSUM && checkdefsum(&work_list, CK_CHECKSUM))
		goto bad;
	fmt_print("working list updated, total of %d defects.\n", i);
	goto out;

bad:
	/*
	 * Some kind of error occurred.  Kill off the working list and
	 * mark the status bad.
	 */
	err_print("Defect file is corrupted, working list set to NULL.\n");
	kill_deflist(&work_list);
	status = -1;
out:
	/*
	 * Close the defect file.
	 */
	(void) fclose(fptr);
	exit_critical();
	fmt_print("\n");
	return (status);
}

/*
 * This routine implements the 'commit' command.  It causes the current
 * defect list to be set equal to the working defect list.  It is the only
 * way that changes made to the working list can actually take effect in
 * the next format.
 */
int
d_commit(void)
{
	/*
	 * If the working list wasn't modified, no commit is necessary.
	 */
	if (work_list.list != NULL && !(work_list.flags & LIST_DIRTY)) {
		err_print("working list was not modified.\n");
		return (0);
	}

	/*
	 * Make sure the user is serious.
	 */
	if (check("Ready to update Current Defect List, continue"))
		return (-1);
	return (do_commit());
}

int
do_commit(void)
{
	int	status;

	if ((status = commit_list()) == 0) {
		/*
		 * Remind the user to format the drive, since changing
		 * the list does nothing unless a format is performed.
		 */
		fmt_print(\
"Disk must be reformatted for changes to take effect.\n\n");
	}
	return (status);
}


static int
commit_list(void)
{
	int	i;

	/*
	 * Lock out interrupts so the list doesn't get half copied.
	 */
	enter_critical();
	/*
	 * Kill off any current defect list.
	 */
	kill_deflist(&cur_list);
	/*
	 * If the working list is null, initialize it to zero length.
	 * This is so the user can do a commit on a null list and get
	 * a zero length list.  Otherwise there would be no way to get
	 * a zero length list conveniently.
	 */
	if (work_list.list == NULL) {
		work_list.header.magicno = (uint_t)DEFECT_MAGIC;
		work_list.header.count = 0;
		work_list.list = (struct defect_entry *)zalloc(
		    deflist_size(cur_blksz, 0) * cur_blksz);
	}
	/*
	 * Copy the working list into the current list.
	 */
	cur_list.header = work_list.header;
	cur_list.list = (struct defect_entry *)zalloc(
	    deflist_size(cur_blksz, cur_list.header.count) * cur_blksz);
	for (i = 0; i < cur_list.header.count; i++)
		*(cur_list.list + i) = *(work_list.list + i);
	/*
	 * Mark the working list clean, since it is now the same as the
	 * current list.  Note we do not mark the current list dirty,
	 * even though it has been changed.  This is because it does
	 * not reflect the state of disk, so we don't want it written
	 * out until a format has been done.  The format will mark it
	 * dirty and write it out.
	 */
	work_list.flags &= ~(LIST_DIRTY|LIST_RELOAD);
	cur_list.flags = work_list.flags;
	if (EMBEDDED_SCSI)
		fmt_print("Defect List has a total of %d defects.\n",
		    cur_list.header.count);
	else
		fmt_print("Current Defect List updated, total of %d defects.\n",
		    cur_list.header.count);
	exit_critical();
	return (0);
}


/*
 * This routine implements the 'create' command.  It creates the
 * manufacturer's defect on the current disk from the defect list
 */
int
d_create(void)
{
	int	status;

	assert(!EMBEDDED_SCSI);

	/*
	 * If the controller does not support the extraction, we're out
	 * of luck.
	 */
	if (cur_ops->op_create == NULL) {
		err_print("Controller does not support creating ");
		err_print("manufacturer's defect list.\n");
		return (-1);
	}
	/*
	 * Make sure the user is serious.  Note, for SCSI disks
	 * since this is instantaneous, we will just do it and
	 * not ask for confirmation.
	 */
	if (! (cur_ctype->ctype_flags & CF_SCSI) &&
	    check(
"Ready to create the manufacturers defect information on the disk.\n\
This cannot be interrupted and may take a long while.\n\
IT WILL DESTROY ALL OF THE DATA ON THE DISK! Continue"))
		return (-1);
	/*
	 * Lock out interrupts so we don't get half the list.
	 */
	enter_critical();
	fmt_print("Creating manufacturer's defect list...");
	/*
	 * Do the Creation
	 */
	status = (*cur_ops->op_create)(&work_list);
	if (status) {
		fmt_print("Creation failed.\n\n");
	} else {
		fmt_print("Creation complete.\n");
	}
	exit_critical();
	/*
	 * Return status.
	 */
	return (status);
}


/*
 * Extract primary defect list - SCSI only
 */
int
d_primary(void)
{
	int	status;

	assert(EMBEDDED_SCSI);

	/*
	 * Lock out interrupts so we don't get half the list and
	 * Kill off the working list.
	 */
	enter_critical();
	kill_deflist(&work_list);
	fmt_print("Extracting primary defect list...");

	/*
	 * Do the extraction.
	 */
	status = scsi_ex_man(&work_list);
	if (status) {
		fmt_print("Extraction failed.\n\n");
	} else {
		fmt_print("Extraction complete.\n");
		/*
		 * Mark the working list dirty since we modified it.
		 * Automatically commit it, for SCSI only.
		 */
		work_list.flags |= LIST_DIRTY;
		status = commit_list();
		fmt_print("\n");
	}
	exit_critical();

	/*
	 * Return status.
	 */
	return (status);
}


/*
 * Extract grown defects list - SCSI only
 */
int
d_grown(void)
{
	int	status;

	assert(EMBEDDED_SCSI);

	/*
	 * Lock out interrupts so we don't get half the list and
	 * Kill off the working list.
	 */
	enter_critical();
	kill_deflist(&work_list);
	fmt_print("Extracting grown defects list...");

	/*
	 * Do the extraction.
	 */
	status = scsi_ex_grown(&work_list);
	if (status) {
		fmt_print("Extraction failed.\n\n");
	} else {
		fmt_print("Extraction complete.\n");
		/*
		 * Mark the working list dirty since we modified it.
		 * Automatically commit it, for SCSI only.
		 */
		work_list.flags |= LIST_DIRTY;
		status = commit_list();
		fmt_print("\n");
	}
	exit_critical();

	/*
	 * Return status.
	 */
	return (status);
}


/*
 * Extract both primary and grown defects list - SCSI only
 */
int
d_both(void)
{
	int	status;

	assert(EMBEDDED_SCSI);

	/*
	 * Lock out interrupts so we don't get half the list and
	 * Kill off the working list.
	 */
	enter_critical();
	kill_deflist(&work_list);
	fmt_print("Extracting both primary and grown defects lists...");

	/*
	 * Do the extraction.
	 */
	status = scsi_ex_cur(&work_list);
	if (status) {
		fmt_print("Extraction failed.\n\n");
	} else {
		fmt_print("Extraction complete.\n");
		/*
		 * Mark the working list dirty since we modified it.
		 * Automatically commit it, for SCSI only.
		 */
		work_list.flags |= LIST_DIRTY;
		status = commit_list();
		fmt_print("\n");
	}
	exit_critical();

	/*
	 * Return status.
	 */
	return (status);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright (c) 1991-2001 by Sun Microsystems, Inc.
 */

#ifndef	_MENU_DEFECT_H
#define	_MENU_DEFECT_H

#ifdef	__cplusplus
extern "C" {
#endif

/*
 *	Prototypes for ANSI C compilers
 */
int	d_restore(void);
int	d_original(void);
int	d_extract(void);
int	d_add(void);
int	d_delete(void);
int	d_print(void);
int	d_dump(void);
int	d_load(void);
int	d_commit(void);
int	do_commit(void);
int	d_create(void);
int	d_primary(void);
int	d_grown(void);
int	d_both(void);

#ifdef	__cplusplus
}
#endif

#endif	/* _MENU_DEFECT_H */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright 2005 Sun Microsystems, Inc.   All rights reserved.
 * Use is subject to license terms.
 */

/*
 * This file contains functions that implement the fdisk menu commands.
 */
#include "global.h"
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/wait.h>
#include <signal.h>
#include <string.h>
#include <sys/fcntl.h>
#include <sys/stat.h>

#include <sys/dklabel.h>

#include "main.h"
#include "analyze.h"
#include "menu.h"
#include "menu_developer.h"
#include "param.h"
#include "misc.h"
#include "label.h"
#include "startup.h"
#include "partition.h"
#include "prompts.h"
#include "checkdev.h"
#include "io.h"
#include "ctlr_scsi.h"
#include "auto_sense.h"
#include "hardware_structs.h"

extern	struct menu_item menu_developer[];


int
c_developer(void)
{

	cur_menu++;
	last_menu = cur_menu;

	/*
	 * Run the menu.
	 */
	run_menu(menu_developer, "DEVELOPER", "developer", 0);
	cur_menu--;
	return (0);
}

int
dv_disk(void)
{
	struct disk_info *diskp;

	diskp = disk_list;
	while (diskp != NULL) {

		(void) printf("\ndisk_name %s  ", diskp->disk_name);
		(void) printf("disk_path %s\n", diskp->disk_path);
		(void) printf("ctlr_cname = %s  ",
		    diskp->disk_ctlr->ctlr_cname);
		(void) printf("cltr_dname = %s  ",
		    diskp->disk_ctlr->ctlr_dname);
		(void) printf("ctype_name = %s\n",
		    diskp->disk_ctlr->ctlr_ctype->ctype_name);
		(void) printf("ctype_ctype = %d\n",
		    diskp->disk_ctlr->ctlr_ctype->ctype_ctype);
		(void) printf("devfsname = %s\n", diskp->devfs_name);
		diskp = diskp->disk_next;
	}
	return (0);
}

int
dv_cont(void)
{
	struct ctlr_info *contp;

	contp = ctlr_list;
	while (contp != NULL) {

		(void) printf("\nctype_name = %s ",
		    contp->ctlr_ctype->ctype_name);
		(void) printf("cname = %s dname =  %s ",
		    contp->ctlr_cname, contp->ctlr_dname);
		(void) printf("ctype_ctype = %d\n",
		    contp->ctlr_ctype->ctype_ctype);
		contp = contp->ctlr_next;
	}
	return (0);
}

int
dv_cont_chain(void)
{
	struct mctlr_list *ctlrp;

	ctlrp = controlp;

	if (ctlrp == NULL)
		(void) printf("ctlrp is NULL!!\n");

	while (ctlrp != NULL) {
		(void) printf("ctlrp->ctlr_type->ctype_name = %s\n",
		    ctlrp->ctlr_type->ctype_name);
		ctlrp = ctlrp->next;
	}
	return (0);
}

int
dv_params(void)
{
	(void) printf("ncyl = %d\n", ncyl);
	(void) printf("acyl = %d\n", acyl);
	(void) printf("pcyl = %d\n", pcyl);
	(void) printf("nhead = %d\n", nhead);
	(void) printf("nsect = %d\n", nsect);

	return (0);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright (c) 1993-2001 by Sun Microsystems, Inc.
 */

#ifndef	_MENU_DEVELOPER_H
#define	_MENU_DEVELOPER_H

#ifdef	__cplusplus
extern "C" {
#endif

/*
 *	Prototypes for ANSI
 */
int	c_developer(void);
int	dv_disk(void);
int	dv_cont(void);
int	dv_cont_chain(void);
int	dv_params(void);

#ifdef	__cplusplus
}
#endif

#endif	/* _MENU_DEVELOPER_H */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright (c) 1993, 2010, Oracle and/or its affiliates. All rights reserved.
 * Copyright 2016 Toomas Soome <tsoome@me.com>
 */

/*
 * This file contains functions that implement the fdisk menu commands.
 */
#include "global.h"
#include <errno.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/wait.h>
#include <signal.h>
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/dktp/fdisk.h>
#include <sys/stat.h>
#include <sys/dklabel.h>
#ifdef i386
#include <libfdisk.h>
#endif

#include "main.h"
#include "analyze.h"
#include "menu.h"
#include "menu_command.h"
#include "menu_defect.h"
#include "menu_partition.h"
#include "menu_fdisk.h"
#include "param.h"
#include "misc.h"
#include "label.h"
#include "startup.h"
#include "partition.h"
#include "prompts.h"
#include "checkdev.h"
#include "io.h"
#include "ctlr_scsi.h"
#include "auto_sense.h"

extern	struct menu_item menu_fdisk[];
struct mboot boot_sec;
uint_t	xstart;

/*
 * Byte swapping macros for accessing struct ipart
 *	to resolve little endian on Sparc.
 */
#if defined(sparc)
#define	les(val)	((((val)&0xFF)<<8)|(((val)>>8)&0xFF))
#define	lel(val)	(((unsigned)(les((val)&0x0000FFFF))<<16) | \
			(les((unsigned)((val)&0xffff0000)>>16)))

#elif	defined(i386) || defined(__amd64)

#define	les(val)	(val)
#define	lel(val)	(val)

#else	/* defined(sparc) */

#error	No Platform defined

#endif	/* defined(sparc) */


/* Function prototypes */
#ifdef	__STDC__

#if	defined(sparc)

static int getbyte(uchar_t **);
static int getlong(uchar_t **);

#endif	/* defined(sparc) */

static int get_solaris_part(int fd, struct ipart *ipart);

#else	/* __STDC__ */

#if	defined(sparc)

static int getbyte();
static int getlong();

#endif	/* defined(sparc) */

static int get_solaris_part();

#endif	/* __STDC__ */

#if defined(i386) || defined(__amd64)
int extpart_init(ext_part_t **epp);
#endif
/*
 * Handling the alignment problem of struct ipart.
 */
static void
fill_ipart(char *bootptr, struct ipart *partp)
{
#if defined(sparc)
	/*
	 * Sparc platform:
	 *
	 * Packing short/word for struct ipart to resolve
	 *	little endian on Sparc since it is not
	 *	properly aligned on Sparc.
	 */
	partp->bootid = getbyte((uchar_t **)&bootptr);
	partp->beghead = getbyte((uchar_t **)&bootptr);
	partp->begsect = getbyte((uchar_t **)&bootptr);
	partp->begcyl = getbyte((uchar_t **)&bootptr);
	partp->systid = getbyte((uchar_t **)&bootptr);
	partp->endhead = getbyte((uchar_t **)&bootptr);
	partp->endsect = getbyte((uchar_t **)&bootptr);
	partp->endcyl = getbyte((uchar_t **)&bootptr);
	partp->relsect = getlong((uchar_t **)&bootptr);
	partp->numsect = getlong((uchar_t **)&bootptr);
#elif defined(i386) || defined(__amd64)
	/*
	 * i386/amd64 platform:
	 *
	 * The fdisk table does not begin on a 4-byte boundary within
	 * the master boot record; so, we need to recopy its contents
	 * to another data structure to avoid an alignment exception.
	 */
	(void) bcopy(bootptr, partp, sizeof (struct ipart));
#else
#error  No Platform defined
#endif /* defined(sparc) */
}

/*
 * Get a correct byte/short/word routines for Sparc platform.
 */
#if defined(sparc)
static int
getbyte(uchar_t **bp)
{
	int	b;

	b = **bp;
	*bp = *bp + 1;
	return (b);
}

#ifdef DEADCODE
static int
getshort(uchar_t **bp)
{
	int	b;

	b = ((**bp) << 8) | *(*bp + 1);
	*bp += 2;
	return (b);
}
#endif /* DEADCODE */

static int
getlong(uchar_t **bp)
{
	int	b, bh, bl;

	bh = ((**bp) << 8) | *(*bp + 1);
	*bp += 2;
	bl = ((**bp) << 8) | *(*bp + 1);
	*bp += 2;

	b = (bh << 16) | bl;
	return (b);
}
#endif /* defined(sparc) */

#ifdef i386
/*
 * Convert emcpowerN[a-p,p0,p1,p2,p3,p4] to emcpowerNp0 path,
 * this is specific for emc powerpath driver.
 */
static void
get_emcpower_pname(char *name, char *devname)
{
	char	*emcp = "emcpower";
	char	*npt = NULL;
	char	np[MAXNAMELEN];
	int	i = strlen(emcp);

	(void) strcpy(np, devname);
	npt = strstr(np, emcp);
	while ((i < strlen(npt)) && (isdigit(npt[i])))
		i++;
	npt[i] = '\0';
	(void) snprintf(name, MAXNAMELEN, "/dev/rdsk/%sp0", npt);
}
#endif

/*
 * Convert cn[tn]dn to cn[tn]dns2 path
 */
static void
get_sname(char *name)
{
	char		buf[MAXPATHLEN];
	char		*devp = "/dev/dsk";
	char		*rdevp = "/dev/rdsk";
	char		np[MAXNAMELEN];
	char		*npt;

#ifdef i386
	if (emcpower_name(cur_disk->disk_name)) {
		get_emcpower_pname(name, cur_disk->disk_name);
		return;
	}
#endif

	/*
	 * If it is a full path /dev/[r]dsk/cn[tn]dn, use this path
	 */
	(void) strcpy(np, cur_disk->disk_name);
	if (strncmp(rdevp, cur_disk->disk_name, strlen(rdevp)) == 0 ||
	    strncmp(devp, cur_disk->disk_name, strlen(devp)) == 0) {
		/*
		 * Skip if the path is already included with sN
		 */
		if (strchr(np, 's') == strrchr(np, 's')) {
			npt = strrchr(np, 'p');
			/* If pN is found, do not include it */
			if (npt != NULL) {
				*npt = '\0';
			}
			(void) snprintf(buf, sizeof (buf), "%ss2", np);
		} else {
			(void) snprintf(buf, sizeof (buf), "%s", np);
		}
	} else {
		(void) snprintf(buf, sizeof (buf), "/dev/rdsk/%ss2", np);
	}
	(void) strcpy(name, buf);
}

/*
 * Convert cn[tn]dnsn to cn[tn]dnp0 path
 */
static void
get_pname(char *name)
{
	char		buf[MAXPATHLEN];
	char		*devp = "/dev/dsk";
	char		*rdevp = "/dev/rdsk";
	char		np[MAXNAMELEN];
	char		*npt;

	/*
	 * If it is a full path /dev/[r]dsk/cn[tn]dnsn, use this path
	 */
	if (cur_disk == NULL) {
		(void) strcpy(np, x86_devname);
	} else {
		(void) strcpy(np, cur_disk->disk_name);
	}

#ifdef i386
	if (emcpower_name(np)) {
		get_emcpower_pname(name, np);
		return;
	}
#endif

	if (strncmp(rdevp, np, strlen(rdevp)) == 0 ||
	    strncmp(devp, np, strlen(devp)) == 0) {
		/*
		 * Skip if the path is already included with pN
		 */
		if (strchr(np, 'p') == NULL) {
			npt = strrchr(np, 's');
			/* If sN is found, do not include it */
			if (isdigit(*++npt)) {
				*--npt = '\0';
			}
			(void) snprintf(buf, sizeof (buf), "%sp0", np);
		} else {
			(void) snprintf(buf, sizeof (buf), "%s", np);
		}
	} else {
		(void) snprintf(buf, sizeof (buf), "/dev/rdsk/%sp0", np);
	}
	(void) strcpy(name, buf);
}

/*
 * Open file descriptor for current disk (cur_file)
 *	with "p0" path or cur_disk->disk_path
 */
void
open_cur_file(int mode)
{
	char	*dkpath;
	char	pbuf[MAXPATHLEN];

	switch (mode) {
		case FD_USE_P0_PATH:
			(void) get_pname(&pbuf[0]);
			dkpath = pbuf;
			break;
		case FD_USE_CUR_DISK_PATH:
			if (cur_disk->fdisk_part.systid == SUNIXOS ||
			    cur_disk->fdisk_part.systid == SUNIXOS2) {
				(void) get_sname(&pbuf[0]);
				dkpath = pbuf;
			} else {
				dkpath = cur_disk->disk_path;
			}
			break;
		default:
			err_print("Error: Invalid mode option for opening "
			    "cur_file\n");
			fullabort();
	}

	/* Close previous cur_file */
	(void) close(cur_file);
	/* Open cur_file with the required path dkpath */
	if ((cur_file = open_disk(dkpath, O_RDWR | O_NDELAY)) < 0) {
		err_print(
		    "Error: can't open selected disk '%s'.\n", dkpath);
		fullabort();
	}
}


/*
 * This routine implements the 'fdisk' command.  It simply runs
 * the fdisk command on the current disk.
 * Use of this is restricted to interactive mode only.
 */
int
c_fdisk(void)
{

	char		buf[MAXPATHLEN];
	char		pbuf[MAXPATHLEN];
	struct stat	statbuf;

	/*
	 * We must be in interactive mode to use the fdisk command
	 */
	if (option_f != NULL || isatty(0) != 1 || isatty(1) != 1) {
		err_print("Fdisk command is for interactive use only!\n");
		return (-1);
	}

	/*
	 * There must be a current disk type and a current disk
	 */
	if (cur_dtype == NULL) {
		err_print("Current Disk Type is not set.\n");
		return (-1);
	}

	/*
	 * Before running the fdisk command, get file status of
	 *	/dev/rdsk/cn[tn]dnp0 path to see if this disk
	 *	supports fixed disk partition table.
	 */
	(void) get_pname(&pbuf[0]);
	if (stat(pbuf, (struct stat *)&statbuf) == -1 ||
	    !S_ISCHR(statbuf.st_mode)) {
		err_print(
		"Disk does not support fixed disk partition table\n");
		return (0);
	}

	/*
	 * Run the fdisk program.
	 */
	(void) snprintf(buf, sizeof (buf), "fdisk %s\n", pbuf);
	(void) system(buf);

	/*
	 * Open cur_file with "p0" path for accessing the fdisk table
	 */
	(void) open_cur_file(FD_USE_P0_PATH);

	/*
	 * Get solaris partition information in the fdisk partition table
	 */
	if (get_solaris_part(cur_file, &cur_disk->fdisk_part) == -1) {
		err_print("No fdisk solaris partition found\n");
		cur_disk->fdisk_part.numsect = 0;  /* No Solaris */
	}

	/*
	 * Restore cur_file with cur_disk->disk_path
	 */
	(void) open_cur_file(FD_USE_CUR_DISK_PATH);

	return (0);
}

/*
 * Read MBR on the disk
 * if the Solaris partition has changed,
 *	reread the vtoc
 */
#ifdef DEADCODE
static void
update_cur_parts(void)
{

	int i;
	register struct partition_info *parts;

	for (i = 0; i < NDKMAP; i++) {
#if defined(_SUNOS_VTOC_16)
		if (cur_parts->vtoc.v_part[i].p_tag &&
		    cur_parts->vtoc.v_part[i].p_tag != V_ALTSCTR) {
			cur_parts->vtoc.v_part[i].p_start = 0;
			cur_parts->vtoc.v_part[i].p_size = 0;

#endif
			cur_parts->pinfo_map[i].dkl_nblk = 0;
			cur_parts->pinfo_map[i].dkl_cylno = 0;
			cur_parts->vtoc.v_part[i].p_tag =
			    default_vtoc_map[i].p_tag;
			cur_parts->vtoc.v_part[i].p_flag =
			    default_vtoc_map[i].p_flag;
#if defined(_SUNOS_VTOC_16)
		}
#endif
	}
	cur_parts->pinfo_map[C_PARTITION].dkl_nblk = ncyl * spc();

#if defined(_SUNOS_VTOC_16)
	/*
	 * Adjust for the boot partitions
	 */
	cur_parts->pinfo_map[I_PARTITION].dkl_nblk = spc();
	cur_parts->pinfo_map[I_PARTITION].dkl_cylno = 0;
	cur_parts->vtoc.v_part[C_PARTITION].p_start =
	    cur_parts->pinfo_map[C_PARTITION].dkl_cylno * nhead * nsect;
	cur_parts->vtoc.v_part[C_PARTITION].p_size =
	    cur_parts->pinfo_map[C_PARTITION].dkl_nblk;

	cur_parts->vtoc.v_part[I_PARTITION].p_start =
	    cur_parts->pinfo_map[I_PARTITION].dkl_cylno;
	cur_parts->vtoc.v_part[I_PARTITION].p_size =
	    cur_parts->pinfo_map[I_PARTITION].dkl_nblk;

#endif	/* defined(_SUNOS_VTOC_16) */
	parts = cur_dtype->dtype_plist;
	cur_dtype->dtype_ncyl = ncyl;
	cur_dtype->dtype_plist = cur_parts;
	parts->pinfo_name = cur_parts->pinfo_name;
	cur_disk->disk_parts = cur_parts;
	cur_ctype->ctype_dlist = cur_dtype;

}
#endif /* DEADCODE */

static int
get_solaris_part(int fd, struct ipart *ipart)
{
	int		i;
	struct ipart	ip;
	int		status;
	char		*mbr;
	char		*bootptr;
	struct dk_label	update_label;
	ushort_t	found = 0;
#ifdef i386
	uint32_t	relsec, numsec;
	int		pno, rval, ext_part_found = 0;
	ext_part_t	*epp;
#endif

	(void) lseek(fd, 0, 0);

	/*
	 * We may get mbr of different size, but the first 512 bytes
	 * are valid information.
	 */
	mbr = malloc(cur_blksz);
	if (mbr == NULL) {
		err_print("No memory available.\n");
		return (-1);
	}
	status = read(fd, mbr, cur_blksz);

	if (status != cur_blksz) {
		err_print("Bad read of fdisk partition. Status = %x\n", status);
		err_print("Cannot read fdisk partition information.\n");
		free(mbr);
		return (-1);
	}

	(void) memcpy(&boot_sec, mbr, sizeof (struct mboot));
	free(mbr);

#ifdef i386
	(void) extpart_init(&epp);
#endif
	for (i = 0; i < FD_NUMPART; i++) {
		int	ipc;

		ipc = i * sizeof (struct ipart);

		/* Handling the alignment problem of struct ipart */
		bootptr = &boot_sec.parts[ipc];
		(void) fill_ipart(bootptr, &ip);

#ifdef i386
		if (fdisk_is_dos_extended(ip.systid) && (ext_part_found == 0)) {
			/* We support only one extended partition per disk */
			ext_part_found = 1;
			rval = fdisk_get_solaris_part(epp, &pno, &relsec,
			    &numsec);
			if (rval == FDISK_SUCCESS) {
				/*
				 * Found a solaris partition inside the
				 * extended partition. Update the statistics.
				 */
				if (nhead != 0 && nsect != 0) {
					pcyl = numsec / (nhead * nsect);
					xstart = relsec / (nhead * nsect);
					ncyl = pcyl - acyl;
				}
				solaris_offset = relsec;
				found = 2;
				ip.bootid = 0;
				ip.beghead = ip.begsect = ip.begcyl = 0xff;
				ip.endhead = ip.endsect = ip.endcyl = 0xff;
				ip.systid = SUNIXOS2;
				ip.relsect = relsec;
				ip.numsect = numsec;
				ipart->bootid = ip.bootid;
				status = bcmp(&ip, ipart,
				    sizeof (struct ipart));
				bcopy(&ip, ipart, sizeof (struct ipart));
			}
			continue;
		}
#endif

		/*
		 * we are interested in Solaris and EFI partition types
		 */
#ifdef i386
		if ((ip.systid == SUNIXOS &&
		    (fdisk_is_linux_swap(epp, lel(ip.relsect), NULL) != 0)) ||
		    ip.systid == SUNIXOS2 ||
		    ip.systid == EFI_PMBR) {
#else
		if (ip.systid == SUNIXOS ||
		    ip.systid == SUNIXOS2 ||
		    ip.systid == EFI_PMBR) {
#endif
			/*
			 * if the disk has an EFI label, nhead and nsect may
			 * be zero.  This test protects us from FPE's, and
			 * format still seems to work fine
			 */
			if (nhead != 0 && nsect != 0) {
				pcyl = lel(ip.numsect) / (nhead * nsect);
				xstart = lel(ip.relsect) / (nhead * nsect);
				ncyl = pcyl - acyl;
			}
#ifdef DEBUG
			else {
				err_print("Critical geometry values are zero:\n"
				    "\tnhead = %d; nsect = %d\n", nhead, nsect);
			}
#endif /* DEBUG */

			solaris_offset = (uint_t)lel(ip.relsect);
			found = 1;
			break;
		}
	}

#ifdef i386
	libfdisk_fini(&epp);
#endif

	if (!found) {
		err_print("Solaris fdisk partition not found\n");
		return (-1);
	} else if (found == 1) {
		/*
		 * Found a primary solaris partition.
		 * compare the previous and current Solaris partition
		 * but don't use bootid in determination of Solaris partition
		 * changes
		 */
		ipart->bootid = ip.bootid;
		status = bcmp(&ip, ipart, sizeof (struct ipart));

		bcopy(&ip, ipart, sizeof (struct ipart));
	}

	/* if the disk partitioning has changed - get the VTOC */
	if (status) {
		struct extvtoc exvtoc;
		struct vtoc vtoc;

		status = ioctl(fd, DKIOCGEXTVTOC, &exvtoc);
		if (status == -1) {
			i = errno;
			/* Try the old ioctl DKIOCGVTOC */
			status = ioctl(fd, DKIOCGVTOC, &vtoc);
			if (status == -1) {
				err_print("Bad ioctl DKIOCGEXTVTOC.\n");
				err_print("errno=%d %s\n", i, strerror(i));
				err_print("Cannot read vtoc information.\n");
				return (-1);
			}
		}

		status = read_label(fd, &update_label);
		if (status == -1) {
			err_print("Cannot read label information.\n");
			return (-1);
		}

		/* copy vtoc information */
		cur_parts->vtoc = update_label.dkl_vtoc;

#if defined(_SUNOS_VTOC_16)
		/*
		 * this is to update the slice table on x86
		 * we don't care about VTOC8 here
		 */
		for (i = 0; i < NDKMAP; i ++) {
			cur_parts->pinfo_map[i].dkl_cylno =
			    update_label.dkl_vtoc.v_part[i].p_start /
			    ((int)(update_label.dkl_nhead *
			    update_label.dkl_nsect));
			cur_parts->pinfo_map[i].dkl_nblk =
			    update_label.dkl_vtoc.v_part[i].p_size;
		}
#endif /* defined(_SUNOS_VTOC_16) */

		cur_dtype->dtype_ncyl = update_label.dkl_ncyl;
		cur_dtype->dtype_pcyl = update_label.dkl_pcyl;
		cur_dtype->dtype_acyl = update_label.dkl_acyl;
		cur_dtype->dtype_nhead = update_label.dkl_nhead;
		cur_dtype->dtype_nsect = update_label.dkl_nsect;
		ncyl = cur_dtype->dtype_ncyl;
		acyl = cur_dtype->dtype_acyl;
		pcyl = cur_dtype->dtype_pcyl;
		nsect = cur_dtype->dtype_nsect;
		nhead = cur_dtype->dtype_nhead;
	}
	return (0);
}


int
copy_solaris_part(struct ipart *ipart)
{

	int		status, i, fd;
	struct mboot	mboot;
	char		*mbr;
	struct ipart	ip;
	char		buf[MAXPATHLEN];
	char		*bootptr;
	struct stat	statbuf;
#ifdef i386
	uint32_t	relsec, numsec;
	int		pno, rval, ext_part_found = 0;
	ext_part_t	*epp;
#endif

	(void) get_pname(&buf[0]);
	if (stat(buf, &statbuf) == -1 ||
	    !S_ISCHR(statbuf.st_mode) ||
	    ((cur_label == L_TYPE_EFI) &&
	    (cur_disk->disk_flags & DSK_LABEL_DIRTY))) {
		/*
		 * Make sure to reset solaris_offset to zero if it is
		 *	previously set by a selected disk that
		 *	supports the fdisk table.
		 */
		solaris_offset = 0;
		/*
		 * Return if this disk does not support fdisk table or
		 * if it uses an EFI label but has not yet been labelled.
		 * If the EFI label has not been written then the open
		 * on the partition will fail.
		 */
		return (0);
	}

	if ((fd = open(buf, O_RDONLY)) < 0) {
		/*
		 * Labeled device support in lofi provides p0 partition on
		 * both x86 and sparc. However, sparc does not implement fdisk
		 * partitioning. This workaround will allow format
		 * to ignore fdisk errors in case of lofi devices.
		 */
		if (strcmp(cur_disk->disk_dkinfo.dki_cname, "lofi") == 0) {
			solaris_offset = 0;
			return (0);
		}
		err_print("Error: can't open disk '%s'.\n", buf);
		return (-1);
	}

	/*
	 * We may get mbr of different size, but the first 512 bytes
	 * are valid information.
	 */
	mbr = malloc(cur_blksz);
	if (mbr == NULL) {
		err_print("No memory available.\n");
		return (-1);
	}
	status = read(fd, mbr, cur_blksz);

	if (status != cur_blksz) {
		err_print("Bad read of fdisk partition.\n");
		(void) close(fd);
		free(mbr);
		return (-1);
	}

	(void) memcpy(&mboot, mbr, sizeof (struct mboot));

#ifdef i386
	(void) extpart_init(&epp);
#endif
	for (i = 0; i < FD_NUMPART; i++) {
		int	ipc;

		ipc = i * sizeof (struct ipart);

		/* Handling the alignment problem of struct ipart */
		bootptr = &mboot.parts[ipc];
		(void) fill_ipart(bootptr, &ip);

#ifdef i386
		if (fdisk_is_dos_extended(ip.systid) && (ext_part_found == 0)) {
			/* We support only one extended partition per disk */
			ext_part_found = 1;
			rval = fdisk_get_solaris_part(epp, &pno, &relsec,
			    &numsec);
			if (rval == FDISK_SUCCESS) {
				/*
				 * Found a solaris partition inside the
				 * extended partition. Update the statistics.
				 */
				if (nhead != 0 && nsect != 0) {
					pcyl = numsec / (nhead * nsect);
					ncyl = pcyl - acyl;
				}
				solaris_offset = relsec;
				ip.bootid = 0;
				ip.beghead = ip.begsect = ip.begcyl = 0xff;
				ip.endhead = ip.endsect = ip.endcyl = 0xff;
				ip.systid = SUNIXOS2;
				ip.relsect = relsec;
				ip.numsect = numsec;
				bcopy(&ip, ipart, sizeof (struct ipart));
			}
			continue;
		}
#endif


#ifdef i386
		if ((ip.systid == SUNIXOS &&
		    (fdisk_is_linux_swap(epp, lel(ip.relsect), NULL) != 0)) ||
		    ip.systid == SUNIXOS2 ||
		    ip.systid == EFI_PMBR) {
#else
		if (ip.systid == SUNIXOS ||
		    ip.systid == SUNIXOS2 ||
		    ip.systid == EFI_PMBR) {
#endif
			solaris_offset = lel(ip.relsect);
			bcopy(&ip, ipart, sizeof (struct ipart));

			/*
			 * if the disk has an EFI label, we typically won't
			 * have values for nhead and nsect.  format seems to
			 * work without them, and we need to protect ourselves
			 * from FPE's
			 */
			if (nhead != 0 && nsect != 0) {
				pcyl = lel(ip.numsect) / (nhead * nsect);
				ncyl = pcyl - acyl;
			}
#ifdef DEBUG
			else {
				err_print("Critical geometry values are zero:\n"
				    "\tnhead = %d; nsect = %d\n", nhead, nsect);
			}
#endif /* DEBUG */

			break;
		}
	}
#ifdef i386
	libfdisk_fini(&epp);
#endif

	(void) close(fd);
	free(mbr);
	return (0);
}

#if defined(_FIRMWARE_NEEDS_FDISK)
int
auto_solaris_part(struct dk_label *label)
{

	int		status, i, fd;
	struct mboot	mboot;
	char		*mbr;
	struct ipart	ip;
	char		*bootptr;
	char		pbuf[MAXPATHLEN];
#ifdef i386
	uint32_t	relsec, numsec;
	int		pno, rval, ext_part_found = 0;
	ext_part_t	*epp;
#endif

	(void) get_pname(&pbuf[0]);
	if ((fd = open_disk(pbuf, O_RDONLY)) < 0) {
		err_print("Error: can't open selected disk '%s'.\n", pbuf);
		return (-1);
	}

	/*
	 * We may get mbr of different size, but the first 512 bytes
	 * are valid information.
	 */
	mbr = malloc(cur_blksz);
	if (mbr == NULL) {
		err_print("No memory available.\n");
		return (-1);
	}
	status = read(fd, mbr, cur_blksz);

	if (status != cur_blksz) {
		err_print("Bad read of fdisk partition.\n");
		free(mbr);
		return (-1);
	}

	(void) memcpy(&mboot, mbr, sizeof (struct mboot));

#ifdef i386
	(void) extpart_init(&epp);
#endif
	for (i = 0; i < FD_NUMPART; i++) {
		int	ipc;

		ipc = i * sizeof (struct ipart);

		/* Handling the alignment problem of struct ipart */
		bootptr = &mboot.parts[ipc];
		(void) fill_ipart(bootptr, &ip);

#ifdef i386
		if (fdisk_is_dos_extended(ip.systid) && (ext_part_found == 0)) {
			/* We support only one extended partition per disk */
			ext_part_found = 1;
			rval = fdisk_get_solaris_part(epp, &pno, &relsec,
			    &numsec);
			if (rval == FDISK_SUCCESS) {
				/*
				 * Found a solaris partition inside the
				 * extended partition. Update the statistics.
				 */
				if ((label->dkl_nhead != 0) &&
				    (label->dkl_nsect != 0)) {
					label->dkl_pcyl =
					    numsec / (label->dkl_nhead *
					    label->dkl_nsect);
					label->dkl_ncyl = label->dkl_pcyl -
					    label->dkl_acyl;
				}
				solaris_offset = relsec;
			}
			continue;
		}
#endif

		/*
		 * if the disk has an EFI label, the nhead and nsect fields
		 * the label may be zero.  This protects us from FPE's, and
		 * format still seems to work happily
		 */


#ifdef i386
		if ((ip.systid == SUNIXOS &&
		    (fdisk_is_linux_swap(epp, lel(ip.relsect), NULL) != 0)) ||
		    ip.systid == SUNIXOS2 ||
		    ip.systid == EFI_PMBR) {
#else
		if (ip.systid == SUNIXOS ||
		    ip.systid == SUNIXOS2 ||
		    ip.systid == EFI_PMBR) {
#endif
			if ((label->dkl_nhead != 0) &&
			    (label->dkl_nsect != 0)) {
				label->dkl_pcyl = lel(ip.numsect) /
				    (label->dkl_nhead * label->dkl_nsect);
				label->dkl_ncyl = label->dkl_pcyl -
				    label->dkl_acyl;
			}
#ifdef DEBUG
			else {
				err_print("Critical label fields aren't "
				    "non-zero:\n"
				    "\tlabel->dkl_nhead = %d; "
				    "label->dkl_nsect = "
				    "%d\n", label->dkl_nhead,
				    label->dkl_nsect);
			}
#endif /* DEBUG */

		solaris_offset = lel(ip.relsect);
		break;
		}
	}

#ifdef i386
	libfdisk_fini(&epp);
#endif
	(void) close(fd);
	free(mbr);
	return (0);
}
#endif	/* defined(_FIRMWARE_NEEDS_FDISK) */


int
good_fdisk(void)
{
	char		buf[MAXPATHLEN];
	struct stat	statbuf;

	(void) get_pname(&buf[0]);
	if (stat(buf, &statbuf) == -1 ||
	    !S_ISCHR(statbuf.st_mode) ||
	    cur_label == L_TYPE_EFI) {
		/*
		 * Return if this disk does not support fdisk table or
		 * if the disk is labeled with EFI.
		 */
		return (1);
	}

	if (lel(cur_disk->fdisk_part.numsect) > 0) {
		return (1);
	} else {
		/*
		 * Labeled device support in lofi provides p0 partition on
		 * both x86 and sparc. However, sparc does not implement fdisk
		 * partitioning. This workaround will allow format
		 * to ignore fdisk errors in case of lofi devices.
		 */
		if (strcmp(cur_disk->disk_dkinfo.dki_cname, "lofi") == 0) {
			return (1);
		}
		err_print("WARNING - ");
		err_print("This disk may be in use by an application "
		    "that has\n\t  modified the fdisk table. Ensure "
		    "that this disk is\n\t  not currently in use "
		    "before proceeding to use fdisk.\n");
		return (0);
	}
}

#ifdef i386
int
extpart_init(ext_part_t **epp)
{
	int		rval, lf_op_flag = 0;
	char		p0_path[MAXPATHLEN];

	get_pname(&p0_path[0]);
	lf_op_flag |= FDISK_READ_DISK;
	if ((rval = libfdisk_init(epp, p0_path, NULL, lf_op_flag)) !=
	    FDISK_SUCCESS) {
		switch (rval) {
			/*
			 * FDISK_EBADLOGDRIVE, FDISK_ENOLOGDRIVE
			 * and FDISK_EBADMAGIC can be considered
			 * as soft errors and hence we do not exit.
			 */
			case FDISK_EBADLOGDRIVE:
				break;
			case FDISK_ENOLOGDRIVE:
				break;
			case FDISK_EBADMAGIC:
				break;
			case FDISK_ENOVGEOM:
				err_print("Could not get virtual geometry for"
				    " this device\n");
				fullabort();
				break;
			case FDISK_ENOPGEOM:
				err_print("Could not get physical geometry for"
				    " this device\n");
				fullabort();
				break;
			case FDISK_ENOLGEOM:
				err_print("Could not get label geometry for "
				    " this device\n");
				fullabort();
				break;
			default:
				err_print("Failed to initialise libfdisk.\n");
				fullabort();
				break;
		}
	}
	return (0);
}
#endif
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright (c) 1993-2001 by Sun Microsystems, Inc.
 * All rights reserved.
 */

#ifndef	_MENU_FDISK_H
#define	_MENU_FDISK_H

#ifdef	__cplusplus
extern "C" {
#endif

/*
 *	Prototypes for ANSI
 */
int	copy_solaris_part(struct ipart *ipart);
void	open_cur_file(int);
int	auto_solaris_part(struct dk_label *);


/*
 * These flags are used to open file descriptor for current
 *	disk (cur_file) with "p0" path or cur_disk->disk_path
 */
#define	FD_USE_P0_PATH		0
#define	FD_USE_CUR_DISK_PATH	1

#ifdef	__cplusplus
}
#endif

#endif	/* _MENU_FDISK_H */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright (c) 1991, 2010, Oracle and/or its affiliates. All rights reserved.
 */

/*
 * This file contains functions to implement the partition menu commands.
 */
#include "global.h"
#include <stdlib.h>
#include <string.h>

#include "partition.h"
#include "menu_partition.h"
#include "menu_command.h"
#include "misc.h"
#include "param.h"

static void	nspaces(int);
static int	ndigits(uint64_t);

/*
 * This routine implements the 'a' command.  It changes the 'a' partition.
 */
int
p_apart(void)
{

	change_partition(0);
	return (0);
}

/*
 * This routine implements the 'b' command.  It changes the 'b' partition.
 */
int
p_bpart(void)
{

	change_partition(1);
	return (0);
}

/*
 * This routine implements the 'c' command.  It changes the 'c' partition.
 */
int
p_cpart(void)
{

	change_partition(2);
	return (0);
}

/*
 * This routine implements the 'd' command.  It changes the 'd' partition.
 */
int
p_dpart(void)
{

	change_partition(3);
	return (0);
}

/*
 * This routine implements the 'e' command.  It changes the 'e' partition.
 */
int
p_epart(void)
{

	change_partition(4);
	return (0);
}

/*
 * This routine implements the 'f' command.  It changes the 'f' partition.
 */
int
p_fpart(void)
{

	change_partition(5);
	return (0);
}

/*
 * This routine implements the 'g' command.  It changes the 'g' partition.
 */
int
p_gpart(void)
{

	change_partition(6);
	return (0);
}

/*
 * This routine implements the 'h' command.  It changes the 'h' partition.
 */
int
p_hpart(void)
{

	change_partition(7);
	return (0);
}

/*
 * This routine implements the 'i' command. It is valid only for EFI
 * labeled disks. This can be used only in expert mode.
 */
int
p_ipart(void)
{
	change_partition(8);
	return (0);
}

#if defined(i386)
/*
 * This routine implements the 'j' command.  It changes the 'j' partition.
 */
int
p_jpart(void)
{

	change_partition(9);
	return (0);
}
#endif	/* defined(i386) */

int
p_expand(void)
{
	uint64_t delta;
	uint_t nparts;
	struct dk_gpt *efi_label = cur_parts->etoc;

	if (cur_parts->etoc->efi_altern_lba == 1 ||
	    (cur_parts->etoc->efi_altern_lba >=
	    cur_parts->etoc->efi_last_lba)) {
		err_print("Warning: No expanded capacity is found.\n");
		return (0);
	}

	delta = efi_label->efi_last_lba - efi_label->efi_altern_lba;
	nparts = efi_label->efi_nparts;

	enter_critical();
	efi_label->efi_parts[nparts - 1].p_start += delta;
	efi_label->efi_last_u_lba += delta;
	efi_label->efi_altern_lba = cur_parts->etoc->efi_last_lba;
	exit_critical();

	fmt_print("The expanded capacity is added to the unallocated space.\n");
	return (0);
}

/*
 * This routine implements the 'select' command.  It allows the user
 * to make a pre-defined partition map the current map.
 */
int
p_select(void)
{
	struct partition_info	*pptr, *parts;
	u_ioparam_t		ioparam;
	int			i, index, deflt, *defltptr = NULL;
	blkaddr_t		b_cylno;
#if defined(i386)
	blkaddr_t		cyl_offset;
#endif

	parts = cur_dtype->dtype_plist;
	/*
	 * If there are no pre-defined maps for this disk type, it's
	 * an error.
	 */
	if (parts == NULL) {
		err_print("No defined partition tables.\n");
		return (-1);
	}

	/*
	 * Loop through the pre-defined maps and list them by name.  If
	 * the current map is one of them, make it the default.  If any
	 * the maps are unnamed, label them as such.
	 */
	for (i = 0, pptr = parts; pptr != NULL; pptr = pptr->pinfo_next) {
		if (cur_parts == pptr) {
			deflt = i;
			defltptr = &deflt;
		}
		if (pptr->pinfo_name == NULL)
			fmt_print("        %d. unnamed\n", i++);
		else
			fmt_print("        %d. %s\n", i++, pptr->pinfo_name);
	}
	ioparam.io_bounds.lower = 0;
	ioparam.io_bounds.upper = i - 1;
	/*
	 * Ask which map should be made current.
	 */
	index = input(FIO_INT, "Specify table (enter its number)", ':',
	    &ioparam, defltptr, DATA_INPUT);
	for (i = 0, pptr = parts; i < index; i++, pptr = pptr->pinfo_next)
		;
	if (cur_label == L_TYPE_EFI) {
		enter_critical();
		cur_disk->disk_parts = cur_parts = pptr;
		exit_critical();
		fmt_print("\n");
		return (0);
	}
#if defined(i386)
	/*
	 * Adjust for the boot and alternate sectors partition - assuming that
	 * the alternate sectors partition physical location follows
	 * immediately the boot partition and partition sizes are
	 * expressed in multiple of cylinder size.
	 */
	cyl_offset = pptr->pinfo_map[I_PARTITION].dkl_cylno + 1;
	if (pptr->pinfo_map[J_PARTITION].dkl_nblk != 0) {
		cyl_offset = pptr->pinfo_map[J_PARTITION].dkl_cylno +
		    ((pptr->pinfo_map[J_PARTITION].dkl_nblk +
		    (spc() - 1)) / spc());
	}
#else	/* !defined(i386) */

	b_cylno = 0;

#endif	/* defined(i386) */

	/*
	 * Before we blow the current map away, do some limits checking.
	 */
	for (i = 0; i < NDKMAP; i++)  {

#if defined(i386)
		if (i == I_PARTITION || i == J_PARTITION || i == C_PARTITION) {
			b_cylno = 0;
		} else if (pptr->pinfo_map[i].dkl_nblk == 0) {
			/*
			 * Always accept starting cyl 0 if the size is 0 also
			 */
			b_cylno = 0;
		} else {
			b_cylno = cyl_offset;
		}
#endif		/* defined(i386) */
		if (pptr->pinfo_map[i].dkl_cylno < b_cylno ||
		    pptr->pinfo_map[i].dkl_cylno > (ncyl-1)) {
			err_print("partition %c: starting cylinder %d is out "
			    "of range\n", (PARTITION_BASE + i),
			    pptr->pinfo_map[i].dkl_cylno);
			return (0);
		}
		if (pptr->pinfo_map[i].dkl_nblk > ((ncyl -
		    pptr->pinfo_map[i].dkl_cylno) * spc())) {
			err_print(
			    "partition %c: specified # of blocks, %u, "
			    "is out of range\n",
			    (PARTITION_BASE+i),
			    pptr->pinfo_map[i].dkl_nblk);
			return (0);
		}
	}
	/*
	 * Lock out interrupts so the lists don't get mangled.
	 */
	enter_critical();
	/*
	 * If the old current map is unnamed, delete it.
	 */
	if (cur_parts != NULL && cur_parts != pptr &&
	    cur_parts->pinfo_name == NULL)
		delete_partition(cur_parts);
	/*
	 * Make the selected map current.
	 */
	cur_disk->disk_parts = cur_parts = pptr;

#if defined(_SUNOS_VTOC_16)
	for (i = 0; i < NDKMAP; i++)  {
		cur_parts->vtoc.v_part[i].p_start =
		    (blkaddr_t)(cur_parts->pinfo_map[i].dkl_cylno *
		    (nhead * nsect));
		cur_parts->vtoc.v_part[i].p_size =
		    (blkaddr_t)cur_parts->pinfo_map[i].dkl_nblk;
	}
#endif	/* defined(_SUNOS_VTOC_16) */

	exit_critical();
	fmt_print("\n");
	return (0);
}

/*
 * This routine implements the 'name' command.  It allows the user
 * to name the current partition map.  If the map was already named,
 * the name is changed.  Once a map is named, the values of the partitions
 * cannot be changed.  Attempts to change them will cause another map
 * to be created.
 */
int
p_name(void)
{
	char	*name;

	/*
	 * check if there exists a partition table for the disk.
	 */
	if (cur_parts == NULL) {
		err_print("Current Disk has no partition table.\n");
		return (-1);
	}


	/*
	 * Ask for the name.  Note that the input routine will malloc
	 * space for the name since we are using the OSTR input type.
	 */
	name = (char *)(uintptr_t)input(FIO_OSTR,
	    "Enter table name (remember quotes)",
	    ':', NULL, NULL, DATA_INPUT);
	/*
	 * Lock out interrupts.
	 */
	enter_critical();
	/*
	 * If it was already named, destroy the old name.
	 */
	if (cur_parts->pinfo_name != NULL)
		destroy_data(cur_parts->pinfo_name);
	/*
	 * Set the name.
	 */
	cur_parts->pinfo_name = name;
	exit_critical();
	fmt_print("\n");
	return (0);
}


/*
 * This routine implements the 'print' command.  It lists the values
 * for all the partitions in the current partition map.
 */
int
p_print(void)
{
	/*
	 * check if there exists a partition table for the disk.
	 */
	if (cur_parts == NULL) {
		err_print("Current Disk has no partition table.\n");
		return (-1);
	}

	/*
	 * Print the volume name, if it appears to be set
	 */
	if (chk_volname(cur_disk)) {
		fmt_print("Volume:  ");
		print_volname(cur_disk);
		fmt_print("\n");
	}
	/*
	 * Print the name of the current map.
	 */
	if ((cur_parts->pinfo_name != NULL) && (cur_label == L_TYPE_SOLARIS)) {
		fmt_print("Current partition table (%s):\n",
		    cur_parts->pinfo_name);
		fmt_print("Total disk cylinders available: %d + %d "
		    "(reserved cylinders)\n\n", ncyl, acyl);
	} else if (cur_label == L_TYPE_SOLARIS) {
		fmt_print("Current partition table (unnamed):\n");
		fmt_print("Total disk cylinders available: %d + %d "
		    "(reserved cylinders)\n\n", ncyl, acyl);
	} else if (cur_label == L_TYPE_EFI) {
		unsigned reserved;

		reserved = efi_reserved_sectors(cur_parts->etoc);
		fmt_print("Current partition table (%s):\n",
		    cur_parts->pinfo_name != NULL ?
		    cur_parts->pinfo_name : "unnamed");
		fmt_print("Total disk sectors available: %llu + %u "
		    "(reserved sectors)\n\n",
		    cur_parts->etoc->efi_last_u_lba - reserved -
		    cur_parts->etoc->efi_first_u_lba + 1, reserved);
	}


	/*
	 * Print the partition map itself
	 */
	print_map(cur_parts);
	return (0);
}


/*
 * Print a partition map
 */
void
print_map(struct partition_info *map)
{
	int	i;
	int	want_header;
	struct	dk_gpt *vtoc64;

	if (cur_label == L_TYPE_EFI) {
		vtoc64 = map->etoc;
		want_header = 1;
		for (i = 0; i < vtoc64->efi_nparts; i++) {
		/*
		 * we want to print partitions above 7 in expert mode only
		 * or if the partition is reserved
		 */
			if (i >= 7 && !expert_mode &&
			    ((int)vtoc64->efi_parts[i].p_tag !=
			    V_RESERVED)) {
				continue;
			}

			print_efi_partition(vtoc64, i, want_header);
			want_header = 0;
		}
		fmt_print("\n");
		return;
	}
	/*
	 * Loop through each partition, printing the header
	 * the first time.
	 */
	want_header = 1;
	for (i = 0; i < NDKMAP; i++) {
		if (i > 9) {
			break;
		}
		print_partition(map, i, want_header);
		want_header = 0;
	}

	fmt_print("\n");
}

/*
 * Print out one line of partition information,
 * with optional header for EFI type disks.
 */
/*ARGSUSED*/
void
print_efi_partition(struct dk_gpt *map, int partnum, int want_header)
{
	int		ncyl2_digits = 0;
	float		scaled;
	char		*s;
	uint64_t	secsize;

	ncyl2_digits = ndigits(map->efi_last_u_lba);
	if (want_header) {
		fmt_print("Part      ");
		fmt_print("Tag    Flag     ");
		fmt_print("First Sector");
		nspaces(ncyl2_digits);
		fmt_print("Size");
		nspaces(ncyl2_digits);
		fmt_print("Last Sector\n");
	}

	fmt_print("  %d ", partnum);
	s = find_string(ptag_choices, (int)map->efi_parts[partnum].p_tag);
	if (s == NULL)
		s = "-";
	nspaces(10 - (int)strlen(s));
	fmt_print("%s", s);

	s = find_string(pflag_choices, (int)map->efi_parts[partnum].p_flag);
	if (s == NULL)
		s = "-";
	nspaces(6 - (int)strlen(s));
	fmt_print("%s", s);

	nspaces(2);

	secsize = map->efi_parts[partnum].p_size;
	if (secsize == 0) {
		fmt_print("%16llu", map->efi_parts[partnum].p_start);
		nspaces(ncyl2_digits);
		fmt_print("  0     ");
	} else {
		fmt_print("%16llu", map->efi_parts[partnum].p_start);
		scaled = bn2mb(secsize);
		nspaces(ncyl2_digits - 5);
		if (scaled >= (float)1024.0 * 1024) {
			fmt_print("%8.2fTB", scaled/((float)1024.0 * 1024));
		} else if (scaled >= (float)1024.0) {
			fmt_print("%8.2fGB", scaled/(float)1024.0);
		} else {
			fmt_print("%8.2fMB", scaled);
		}
	}
	nspaces(ncyl2_digits);
	if ((map->efi_parts[partnum].p_start + secsize - 1) == UINT_MAX64) {
		fmt_print(" 0    \n");
	} else {
		fmt_print(" %llu    \n",
		    map->efi_parts[partnum].p_start + secsize - 1);
	}
}

/*
 * Print out one line of partition information,
 * with optional header.
 */
/*ARGSUSED*/
void
print_partition(struct partition_info *pinfo, int partnum, int want_header)
{
	int		i;
	blkaddr_t	nblks;
	int		cyl1;
	int		cyl2;
	float		scaled;
	int		maxcyl2;
	int		ncyl2_digits;
	char		*s;
	blkaddr_t	maxnblks = 0;
	blkaddr_t	len;

	/*
	 * To align things nicely, we need to know the maximum
	 * width of the number of cylinders field.
	 */
	maxcyl2 = 0;
	for (i = 0; i < NDKMAP; i++) {
		nblks	= (uint_t)pinfo->pinfo_map[i].dkl_nblk;
		cyl1	= pinfo->pinfo_map[i].dkl_cylno;
		cyl2	= cyl1 + (nblks / spc()) - 1;
		if (nblks > 0) {
			maxcyl2 = max(cyl2, maxcyl2);
			maxnblks = max(nblks, maxnblks);
		}
	}
	/*
	 * Get the number of digits required
	 */
	ncyl2_digits = ndigits(maxcyl2);

	/*
	 * Print the header, if necessary
	 */
	if (want_header) {
		fmt_print("Part      ");
		fmt_print("Tag    Flag     ");
		fmt_print("Cylinders");
		nspaces(ncyl2_digits);
		fmt_print("    Size            Blocks\n");
	}

	/*
	 * Print the partition information
	 */
	nblks	= pinfo->pinfo_map[partnum].dkl_nblk;
	cyl1	= pinfo->pinfo_map[partnum].dkl_cylno;
	cyl2	= cyl1 + (nblks / spc()) - 1;

	fmt_print("  %x ", partnum);

	/*
	 * Print the partition tag.  If invalid, print -
	 */
	s = find_string(ptag_choices, (int)pinfo->vtoc.v_part[partnum].p_tag);
	if (s == NULL)
		s = "-";
	nspaces(10 - (int)strlen(s));
	fmt_print("%s", s);

	/*
	 * Print the partition flag.  If invalid print -
	 */
	s = find_string(pflag_choices, (int)pinfo->vtoc.v_part[partnum].p_flag);
	if (s == NULL)
		s = "-";
	nspaces(6 - (int)strlen(s));
	fmt_print("%s", s);

	nspaces(2);

	if (nblks == 0) {
		fmt_print("%6d      ", cyl1);
		nspaces(ncyl2_digits);
		fmt_print("     0         ");
	} else {
		fmt_print("%6d - ", cyl1);
		nspaces(ncyl2_digits - ndigits(cyl2));
		fmt_print("%d    ", cyl2);
		scaled = bn2mb(nblks);
		if (scaled > (float)1024.0 * 1024.0) {
			fmt_print("%8.2fTB    ",
			    scaled/((float)1024.0 * 1024.0));
		} else if (scaled > (float)1024.0) {
			fmt_print("%8.2fGB    ", scaled/(float)1024.0);
		} else {
			fmt_print("%8.2fMB    ", scaled);
		}
	}
	fmt_print("(");
	pr_dblock(fmt_print, nblks);
	fmt_print(")");

	nspaces(ndigits(maxnblks/spc()) - ndigits(nblks/spc()));
	/*
	 * Allocates size of the printf format string.
	 * ndigits(ndigits(maxblks)) gives the byte size of
	 * the printf width field for maxnblks.
	 */
	len = strlen(" %") + ndigits(ndigits(maxnblks)) + strlen("d\n") + 1;
	s = zalloc(len);
	(void) snprintf(s, len, "%s%u%s", " %", ndigits(maxnblks), "u\n");
	fmt_print(s, nblks);
	(void) free(s);
}


/*
 * Return true if a disk has a volume name
 */
int
chk_volname(struct disk_info *disk)
{
	return (disk->v_volume[0] != 0);
}


/*
 * Print the volume name, if it appears to be set
 */
void
print_volname(struct disk_info *disk)
{
	int	i;
	char	*p;

	p = disk->v_volume;
	for (i = 0; i < LEN_DKL_VVOL; i++, p++) {
		if (*p == 0)
			break;
		fmt_print("%c", *p);
	}
}


/*
 * Print a number of spaces
 */
static void
nspaces(int n)
{
	while (n-- > 0)
		fmt_print(" ");
}

/*
 * Return the number of digits required to print a number
 */
static int
ndigits(uint64_t n)
{
	int	i;

	i = 0;
	while (n > 0) {
		n /= 10;
		i++;
	}

	return (i == 0 ? 1 : i);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef	_MENU_PARTITION_H
#define	_MENU_PARTITION_H

#ifdef	__cplusplus
extern "C" {
#endif


/*
 *	Prototypes for ANSI C compilers
 */
int	p_apart(void);
int	p_bpart(void);
int	p_cpart(void);
int	p_dpart(void);
int	p_epart(void);
int	p_fpart(void);
int	p_gpart(void);
int	p_hpart(void);
int	p_ipart(void);

#if defined(i386)
int	p_jpart(void);
#endif			/* defined(i386) */

int	p_select(void);
int	p_expand(void);
int	p_modify(void);
int	p_name(void);
int	p_print(void);

void	print_map(struct partition_info *map);
void	print_partition(struct partition_info *pinfo, int partnum,
		int want_header);
void	print_efi_partition(struct dk_gpt *map, int partnum,
		int want_header);

int	chk_volname(struct disk_info *);
void	print_volname(struct disk_info *);

#ifdef	__cplusplus
}
#endif

#endif	/* _MENU_PARTITION_H */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * This file contains functions implementing the scsi menu commands.
 *
 * These functions are intended for expert use only, and provide
 * a raw access to a scsi device's mode pages.  The ability to
 * issue a raw format command is also provided, should a page be
 * changed that requires a format.
 */
#include "global.h"
#include <stdlib.h>
#include <ctype.h>

#include "io.h"
#include "menu.h"
#include "misc.h"
#include "menu_scsi.h"
#include "ctlr_scsi.h"
#include "startup.h"
#include "checkdev.h"

static int	do_mode_sense(int);
static int	do_mode_sense_all(void);
static int	do_mode_select(struct chg_list *);
static int	do_format(void);
static void	do_list(void);
static int	do_inquiry(void);
static void	do_apply(void);
static void	do_cancel(void);
static void	do_display(void);
static int	parse_change_spec(char *, char *, int, struct chg_list *);
static void	add_new_change_list_item(struct chg_list *);
static void	free_change_list(void);
static void	do_default(char *);
static void	default_all_pages(void);
static int	default_page(int);

/*
 * Menu data for the SCSI menu display
 */
static char	*scsi_menu_strings[] = {
	"p<n>                   - display a mode sense page",
	"p<n> b<n> <op> [~]<n>  - change a byte and issue mode select",
	"b<n> <op> [~]<n>       - add an operation to the mode select list",
	"                             for the current page",
	"",
	"        where:  p<n> specifies the page with page code <n>",
	"                b<n> specifies byte <n> of the page",
	"                <op> can be one of the following operators:",
	"                     =    (set specified value)",
	"                     |=   (bitwise OR with current value)",
	"                     &=   (bitwise AND with current value)",
	"                <n> can be a decimal value in the range 0-255,",
	"                or two hexadecimal digits, in the form 0x<xx>.",
	"                [~] complements the specified value",
	"",
	"apply                  - apply mode select list",
	"cancel                 - cancel mode select list",
	"display                - display mode select list",
	"all                    - display all supported mode sense pages",
	"default p<n>           - mode select page <n> to default values",
	"default all            - mode select all pages to default values",
	"format                 - format without standard mode selects",
	"inquiry                - display device's inquiry response",
	"list                   - list common SCSI-2 mode pages",
	"!<cmd>                 - execute <cmd> , then return"
};

#define	N_SCSI_STRINGS	(sizeof (scsi_menu_strings) / sizeof (char *))

/*
 * Command types
 */
#define	CMD_ALL			0
#define	CMD_FORMAT		1
#define	CMD_QUIT		2
#define	CMD_HELP		3
#define	CMD_LIST		4
#define	CMD_INQUIRY		5
#define	CMD_APPLY		6
#define	CMD_CANCEL		7
#define	CMD_DISPLAY		8

/*
 * SCSI menu commands for minimum recognition
 */
static struct slist	cmds_list[] = {
	{ "all",	NULL,	CMD_ALL },
	{ "format",	NULL,	CMD_FORMAT },
	{ "quit",	NULL,	CMD_QUIT },
	{ "help",	NULL,	CMD_HELP },
	{ "?",		NULL,	CMD_HELP },
	{ "list",	NULL,	CMD_LIST },
	{ "inquiry",	NULL,	CMD_INQUIRY },
	{ "apply",	NULL,	CMD_APPLY },
	{ "cancel",	NULL,	CMD_CANCEL },
	{ "display",	NULL,	CMD_DISPLAY },
	{ NULL	}
};

/*
 * Implied page for mode select change lists
 */
static	int		current_page;
static	struct chg_list	*change_list;

/*
 * Manage the SCSI menu.
 * Parse input and dispatch to the appropriate functions.
 * The commands we accept are not simple one-word commands,
 * so we cannot use the standard format menu-handling functions.
 */
int
c_scsi(void)
{
	int			i;
	struct env		env;
	char			**menu;
	struct menu_item	scsi_menu[N_SCSI_STRINGS+1];
	struct chg_list		change_item;
	struct chg_list		*chg_item;
	char			s[MAXPATHLEN], nclean[MAXPATHLEN];
	char			*p;
	char			*p2;
	int			cmd;
	int			pageno;
	int			help = 1;

	/*
	 * Warn casual users that maybe they should not be
	 * using this menu.
	 */
	fmt_print("\n"
"Warning:  these functions are intended for expert use only, for\n"
"debugging disk devices and for unusual configuration settings.\n"
"It is recommended that you do not use this menu for normal disk\n"
"configuration and formatting, unless you have explicit instructions,\n"
"or know exactly what you are doing.\n");

	/*
	 * Initialize change list and current page to empty
	 */
	current_page = -1;
	change_list = NULL;

	/*
	 * Build and display the menu.
	 * we only use this for display purposes.
	 */
	for (i = 0; i < N_SCSI_STRINGS; i++) {
		scsi_menu[i].menu_cmd = scsi_menu_strings[i];
		scsi_menu[i].menu_func = NULL;
		scsi_menu[i].menu_state = true;
	}
	scsi_menu[i].menu_cmd = NULL;
	menu = create_menu_list(scsi_menu);
	/*
	 * Save the environment so a ctrl-C out of a command lands here.
	 */
	saveenv(env);
	for (;;) {
		if (help) {
			help = 0;
			fmt_print("\n\nSCSI MENU:\n");
			display_menu_list(menu);
		}
		/*
		 * Prompt and get next input line.  We don't use the
		 * standard input routine, since we need a little
		 * more flexibility in parsing the input.
		 */
		fmt_print("scsi> ");
		get_inputline(nclean, sizeof (nclean));

		clean_token(s, nclean);

		/*
		 * Mark the saved environment active so the user can now
		 * do a ctrl-C to get out of the command.
		 */
		useenv();

		/*
		 * Figure out what the user chose
		 */
		i = find_value(cmds_list, s, &cmd);
		if (i == 1) {
			switch (cmd) {
			case CMD_ALL:
				(void) do_mode_sense_all();
				break;
			case CMD_FORMAT:
				(void) do_format();
				break;
			case CMD_QUIT:
				goto exit;
				/*NOTREACHED*/
			case CMD_HELP:
				fmt_print("\n\nSCSI MENU:\n");
				display_menu_list(menu);
				break;
			case CMD_LIST:
				do_list();
				break;
			case CMD_INQUIRY:
				(void) do_inquiry();
				break;
			case CMD_APPLY:
				do_apply();
				break;
			case CMD_CANCEL:
				do_cancel();
				break;
			case CMD_DISPLAY:
				do_display();
				break;
			}
		} else if (s[0] == 'd') {
			do_default(s);
		} else if (s[0] == 'p') {
			p = s + 1;
			pageno = (int)strtol(p, &p2, 0);
			if (p2 == p) {
				err_print("Syntax error: %s\n", s);
				goto error;
			}
			current_page = pageno;
			for (p = p2; *p == ' '; p++)
				;
			if (*p == 0) {
				(void) do_mode_sense(pageno);
			} else if (*p == 'b') {
				if (parse_change_spec(s, p, pageno,
				    &change_item)) {
					(void) do_mode_select(&change_item);
				}
			}
		} else if (s[0] == 'b') {
				if (current_page == -1) {
					err_print("\
Please display the page on which you'd like to do a mode select\n");
					goto error;
				}
				chg_item = (struct chg_list *)
				    zalloc(sizeof (struct chg_list));
				if (parse_change_spec(s, s, current_page,
				    chg_item)) {
					add_new_change_list_item(chg_item);
				} else {
					destroy_data((char *)chg_item);
				}
		} else if (s[0] == '!') {
			(void) execute_shell(&s[1], sizeof (s) - 1);
			help = 1;
		} else if (s[0] != 0) {
			err_print("Syntax error: %s\n", s);
		}
error:
		/*
		 * Mark the saved environment inactive so ctrl-C doesn't
		 * work at the menu itself.
		 */
		unuseenv();
	}
exit:
	/*
	 * Clean up the environment stack and free the menu
	 */
	clearenv();
	destroy_data((char *)menu);

	/*
	 * Clean up the change list, if anything left over
	 */
	free_change_list();

	/*
	 * Make sure user is prompted with previous menu
	 */
	last_menu++;

	return (0);
}


/*
 * Do a mode sense on a particular page, and dump the data.
 * Get all the various flavors:  default, current, saved, changeable.
 */
static int
do_mode_sense(int pageno)
{
	struct scsi_ms_header	header;
	struct mode_page	*pg;
	char			msbuf[MAX_MODE_SENSE_SIZE];
	int			result = 0;

	char	*default_msg	= "default:     ";
	char	*saved_msg	= "saved:       ";
	char	*current_msg	= "current:     ";
	char	*changeable_msg	= "changeable:  ";


	pg = (struct mode_page *)msbuf;

	fmt_print("\nPage 0x%x:\n", pageno);
	if (uscsi_mode_sense(cur_file, pageno, MODE_SENSE_PC_DEFAULT,
	    msbuf, MAX_MODE_SENSE_SIZE, &header)) {
		err_print("%sfailed\n", default_msg);
		result = 1;
	} else {
		dump(default_msg, msbuf, MODESENSE_PAGE_LEN(pg), HEX_ONLY);
	}

	if (uscsi_mode_sense(cur_file, pageno, MODE_SENSE_PC_CURRENT,
	    msbuf, MAX_MODE_SENSE_SIZE, &header)) {
		err_print("%sfailed\n", current_msg);
		result = 1;
	} else {
		dump(current_msg, msbuf, MODESENSE_PAGE_LEN(pg), HEX_ONLY);
	}

	if (uscsi_mode_sense(cur_file, pageno, MODE_SENSE_PC_SAVED,
	    msbuf, MAX_MODE_SENSE_SIZE, &header)) {
		err_print("%sfailed\n", saved_msg);
		result = 1;
	} else {
		dump(saved_msg, msbuf, MODESENSE_PAGE_LEN(pg), HEX_ONLY);
	}

	if (uscsi_mode_sense(cur_file, pageno, MODE_SENSE_PC_CHANGEABLE,
	    msbuf, MAX_MODE_SENSE_SIZE, &header)) {
		err_print("%sfailed\n", changeable_msg);
		result = 1;
	} else {
		dump(changeable_msg, msbuf, MODESENSE_PAGE_LEN(pg), HEX_ONLY);
	}

	fmt_print("\n");
	return (result);
}


/*
 * Dump all the pages a device supports
 */
static int
do_mode_sense_all(void)
{
	int	result = 0;

	if (scsi_dump_mode_sense_pages(MODE_SENSE_PC_DEFAULT)) {
		result = 1;
	}
	if (scsi_dump_mode_sense_pages(MODE_SENSE_PC_CURRENT)) {
		result = 1;
	}
	if (scsi_dump_mode_sense_pages(MODE_SENSE_PC_SAVED)) {
		result = 1;
	}
	if (scsi_dump_mode_sense_pages(MODE_SENSE_PC_CHANGEABLE)) {
		result = 1;
	}
	fmt_print("\n");
	return (result);
}


/*
 * Get the current mode sense for a particular page, change
 * a byte, and issue a mode select.  Note that we can only
 * change a value if the device indicates that those bits
 * are changeable.
 */
static int
do_mode_select(struct chg_list *change_item)
{
	struct scsi_ms_header	header;
	char			saved[MAX_MODE_SENSE_SIZE];
	char			changeable[MAX_MODE_SENSE_SIZE];
	struct mode_page	*pg;
	struct mode_page	*pg2;
	int			length;
	int			pageno;
	int			flags;
	int			result = 0;

	pageno = change_item->pageno;

	/*
	 * Get changeable mode sense
	 */
	if (uscsi_mode_sense(cur_file, pageno, MODE_SENSE_PC_CHANGEABLE,
	    changeable, MAX_MODE_SENSE_SIZE, &header)) {
		err_print("Mode sense on page %x (changeable) failed\n",
		    pageno);
		return (1);
	}

	/*
	 * Get saved mode sense.  If saved fails, use current values.
	 */
	if (uscsi_mode_sense(cur_file, pageno, MODE_SENSE_PC_SAVED,
	    saved, MAX_MODE_SENSE_SIZE, &header)) {
		err_print("Mode sense on page %x (saved) failed\n", pageno);
		if (uscsi_mode_sense(cur_file, pageno, MODE_SENSE_PC_CURRENT,
		    saved, MAX_MODE_SENSE_SIZE, &header)) {
			err_print("Mode sense on page %x (current) failed\n",
			    pageno);
			return (1);
		} else {
			err_print("Using current values instead\n");
		}
	}

	/*
	 * Use the intersection of the saved and changeable
	 */
	pg = (struct mode_page *)saved;
	pg2 = (struct mode_page *)changeable;
	length = min(MODESENSE_PAGE_LEN(pg), MODESENSE_PAGE_LEN(pg2));

	/*
	 * Try making this change to this page
	 */
	if (apply_chg_list(pageno, length, (uchar_t *)saved,
	    (uchar_t *)changeable, change_item)) {
		/*
		 * A change was made.  Do a mode select
		 * We always want to set the Page Format bit.
		 * Set the Save Page bit if the drive indicates
		 * that it can save this page.
		 */
		flags = MODE_SELECT_PF;
		if (pg->ps) {
			flags |= MODE_SELECT_SP;
		}
		pg->ps = 0;
		header.mode_header.length = 0;
		header.mode_header.device_specific = 0;
		if (uscsi_mode_select(cur_file, pageno, flags,
		    saved, length, &header)) {
			/*
			 * Failed - try not saving parameters,
			 * if possible.
			 */
			if (flags & MODE_SELECT_SP) {
				flags &= ~MODE_SELECT_SP;
				if (uscsi_mode_select(cur_file, pageno,
				    flags, saved, length, &header)) {
					result = 1;
				}
			} else {
				result = 1;
			}
		}

		if (result) {
			fmt_print("\n\
Mode select on page %x failed.\n", pageno);
		} else if ((flags & MODE_SELECT_SP) == 0) {
			fmt_print("\n\
Mode select on page %x ok, but unable to save change permanently.\n", pageno);
		} else {
			fmt_print("\n\
Mode select on page %x ok.\n", pageno);
		}
	} else {
		err_print("\nDevice cannot support this change\n");
	}

	fmt_print("\n");
	return (result);
}


/*
 * Format a device, without any of the standard mode selects.
 * Ask if we should format with the P or the P&G lists.
 */
static int
do_format(void)
{
	struct uscsi_cmd	ucmd;
	union scsi_cdb		cdb;
	struct scsi_defect_hdr	defect_hdr;
	int			status;
	u_ioparam_t		ioparam;
	int			deflt;
	int			grown_list;

	fmt_print("\n");
	/*
	 * Are there mounted partitions?
	 */
	if (checkmount((diskaddr_t)-1, (diskaddr_t)-1)) {
		err_print("Cannot format disk with mounted partitions\n\n");
		return (-1);
	}

	/*
	 * Is any of the partitions being used for swapping.
	 */
	if (checkswap((diskaddr_t)-1, (diskaddr_t)-1)) {
		err_print("Cannot format disk while its partitions are \
currently being used for swapping.\n\n");
		return (-1);
	}
	/*
	 * Are any being used for SVM, VxVM or live upgrade.
	 */
	if (checkdevinuse(cur_disk->disk_name, (diskaddr_t)-1,
	    (diskaddr_t)-1, 0, 0)) {
		err_print("Cannot format disk while its partitions are "
		    "currently being used as described.\n");
		return (-1);
	}

	/*
	 * Let the user choose between formatting with either
	 * the P, or the P&G lists.  Note that yes is 0, no is 1.
	 */
	deflt = 0;
	ioparam.io_charlist = confirm_list;
	grown_list = !input(FIO_MSTR, "Format with the Grown Defects list",
	    '?', &ioparam, &deflt, DATA_INPUT);

	/*
	 * Construct the uscsi format ioctl.
	 * To format with the P and G list, we set the fmtData
	 * and cmpLst bits to zero.  To format with just the
	 * P list, we set the fmtData bit (meaning that we will
	 * send down a defect list in the data phase) and the
	 * cmpLst bit (meaning that the list we send is the
	 * complete G list), and a defect list header with
	 * a defect list length of zero.
	 */
	(void) memset((char *)&ucmd, 0, sizeof (ucmd));
	(void) memset((char *)&cdb, 0, sizeof (union scsi_cdb));
	cdb.scc_cmd = SCMD_FORMAT;
	ucmd.uscsi_cdb = (caddr_t)&cdb;
	ucmd.uscsi_cdblen = CDB_GROUP0;
	if (!grown_list) {
		/*
		 * No G list.   Send empty defect list to replace it.
		 */
		cdb.cdb_opaque[1] = FPB_DATA | FPB_CMPLT | FPB_BFI;
		(void) memset((char *)&defect_hdr, 0, sizeof (defect_hdr));
		ucmd.uscsi_bufaddr = (caddr_t)&defect_hdr;
		ucmd.uscsi_buflen = sizeof (defect_hdr);
	}

	/*
	 * Issue the format ioctl
	 */
	fmt_print("Formatting...\n");
	(void) fflush(stdout);
	status = uscsi_cmd(cur_file, &ucmd, F_NORMAL);
	fmt_print(status ? "Format failed\n\n" : "Format ok\n\n");
	return (status);
}


/*
 * List common SCSI-2 mode pages
 */
static void
do_list(void)
{
	fmt_print("\n\
Common SCSI-2 pages applicable to direct-access devices:\n\n");
	fmt_print("Page 0x1   - Read-Write Error Recovery Page\n");
	fmt_print("Page 0x2   - Disconnect-Reconnect Page\n");
	fmt_print("Page 0x3   - Format Device Page\n");
	fmt_print("Page 0x4   - Rigid Disk Geometry Page\n");
	fmt_print("Page 0x7   - Verify Error Recovery Page\n");
	fmt_print("Page 0x8   - Caching Page\n");
	fmt_print("Page 0xA   - Control Mode Page\n");
	fmt_print("\n");
}


/*
 * Labels for the various fields of the scsi_inquiry structure
 */
static char *scsi_inquiry_labels[] = {
	"Vendor:                     ",
	"Product:                    ",
	"Revision:                   ",
	"Removable media:            ",
	"Device type:                ",
	"ISO version:                ",
	"ECMA version:               ",
	"ANSI version:               ",
	"Async event notification:   ",
	"Terminate i/o process msg:  ",
	"Response data format:       ",
	"Additional length:          ",
	"Relative addressing:        ",
	"32 bit transfers:           ",
	"16 bit transfers:           ",
	"Synchronous transfers:      ",
	"Linked commands:            ",
	"Command queueing:           ",
	"Soft reset option:          "
};


/*
 * Dump the full inquiry as returned by the device
 */
static int
do_inquiry(void)
{
	char			inqbuf[255];
	struct scsi_inquiry	*inq;
	char			**p;

	inq = (struct scsi_inquiry *)inqbuf;

	if (uscsi_inquiry(cur_file, inqbuf, sizeof (inqbuf))) {
		err_print("\nInquiry failed\n");
		return (1);
	}

	fmt_print("\nInquiry:\n");
	/*
	 * The SCSI-2 spec defines "Additional length" as (n-4) bytes,
	 * where n is the last byte of the INQUIRY data.  Thus
	 * there are n+1 bytes of INQUIRY data.  We need to add 5 to
	 * inq_len in order to get all the INQUIRY data.
	 */
	dump("    ", inqbuf, inq->inq_len + 5, HEX_ASCII);
	fmt_print("\n");

	p = scsi_inquiry_labels;

	fmt_print("%s", *p++);
	print_buf(inq->inq_vid, sizeof (inq->inq_vid));
	fmt_print("\n%s", *p++);
	print_buf(inq->inq_pid, sizeof (inq->inq_pid));
	fmt_print("\n%s", *p++);
	print_buf(inq->inq_revision, sizeof (inq->inq_revision));

	fmt_print("\n%s%s\n", *p++, inq->inq_rmb ? "yes" : "no");
	fmt_print("%s%d\n", *p++, inq->inq_qual);
	fmt_print("%s%d\n", *p++, inq->inq_iso);
	fmt_print("%s%d\n", *p++, inq->inq_ecma);
	fmt_print("%s%d\n", *p++, inq->inq_ansi);
	fmt_print("%s%s\n", *p++, inq->inq_aenc ? "yes" : "no");
	fmt_print("%s%s\n", *p++, inq->inq_trmiop ? "yes" : "no");
	fmt_print("%s%d\n", *p++, inq->inq_rdf);
	fmt_print("%s%d\n", *p++, inq->inq_len);
	fmt_print("%s%s\n", *p++, inq->inq_reladdr ? "yes" : "no");
	fmt_print("%s%s\n", *p++, inq->inq_wbus32 ? "yes" : "no");
	fmt_print("%s%s\n", *p++, inq->inq_wbus16 ? "yes" : "no");
	fmt_print("%s%s\n", *p++, inq->inq_sync ? "yes" : "no");
	fmt_print("%s%s\n", *p++, inq->inq_linked ? "yes" : "no");
	fmt_print("%s%s\n", *p++, inq->inq_cmdque ? "yes" : "no");
	fmt_print("%s%s\n", *p++, inq->inq_sftre ? "yes" : "no");

	fmt_print("\n");
	return (0);
}


static void
do_apply(void)
{
	if (change_list == NULL) {
		fmt_print("\nlist empty.\n");
	} else {
		(void) do_mode_select(change_list);
		free_change_list();
	}
}


static void
do_cancel(void)
{
	if (change_list == NULL) {
		fmt_print("\nlist empty.\n");
	} else {
		free_change_list();
	}
}


static void
do_display(void)
{
	struct chg_list	*cp;

	if (change_list == NULL) {
		fmt_print("\nlist empty.\n");
	} else {
		fmt_print("\nPage 0x%x\n", current_page);
		for (cp = change_list; cp != NULL; cp = cp->next) {
			fmt_print("   b0x%x ", cp->byteno);
			switch (cp->mode) {
			case CHG_MODE_ABS:
				fmt_print("= 0x%x\n", cp->value);
				break;
			case CHG_MODE_SET:
				fmt_print("|= 0x%x\n", cp->value);
				break;
			case CHG_MODE_CLR:
				fmt_print("&= ~0x%x\n",
				    (~(cp->value)) & 0xff);
				break;
			default:
				impossible("do_display");
				/*NOTREACHED*/
			}
		}
		fmt_print("\n");
	}
}


static int
parse_change_spec(char *full_input, char *input, int pageno,
    struct chg_list *chg_item)
{
	char		*p;
	int		tilde;

	assert(*input == 'b');

	chg_item->pageno = pageno;
	chg_item->next = NULL;

	input++;
	chg_item->byteno = (int)strtol(input, &p, 0);
	if (p == input) {
		err_print("Syntax error: %s\n", full_input);
		return (0);
	}
	if (chg_item->byteno < 2) {
		err_print(" Unsupported byte offset: %d\n", chg_item->byteno);
		return (0);
	}
	for (input = p; *input == ' '; input++)
		;
	chg_item->mode = CHG_MODE_UNDEFINED;
	switch (*input++) {
	case '=':
		chg_item->mode = CHG_MODE_ABS;
		break;
	case '|':
		if (*input++ == '=') {
			chg_item->mode = CHG_MODE_SET;
		}
		break;
	case '&':
		if (*input++ == '=') {
			chg_item->mode = CHG_MODE_CLR;
		}
		break;
	}
	if (chg_item->mode == CHG_MODE_UNDEFINED) {
		err_print("Syntax error: %s\n", full_input);
		return (0);
	}
	for (; *input == ' '; input++)
		;
	if (*input == '~') {
		tilde = 1;
		for (input++; *input == ' '; input++)
			;
	} else {
		tilde = 0;
	}
	chg_item->value = (int)strtol(input, &p, 0);
	if (p == input || *p != 0) {
		err_print("Syntax error: %s\n", full_input);
		return (0);
	}
	/*
	 * Apply complement if selected.
	 * Constrain to a byte value.
	 */
	if (tilde) {
		chg_item->value = ~chg_item->value;
	}
	chg_item->value &= 0xff;

	return (1);
}


static void
add_new_change_list_item(struct chg_list *chg_item)
{
	struct chg_list	*cp;

	if (change_list == NULL) {
		change_list = chg_item;
	} else {
		for (cp = change_list; cp->next != NULL; cp = cp->next)
			;
		cp->next = chg_item;
	}
	chg_item->next = NULL;
}


static void
free_change_list(void)
{
	struct chg_list	*cp;
	struct chg_list	*cp2;

	cp = change_list;
	while (cp != NULL) {
		cp2 = cp->next;
		destroy_data((char *)cp);
		cp = cp2;
	}
	change_list = NULL;
}


static void
do_default(char *input)
{
	char		*s = input;
	char		*p;
	int		n;

	/*
	 * Reset current page indicator
	 */
	current_page = -1;

	/*
	 * Skip the leading "default" command, which we
	 * must have, or we wouldn't have come here,
	 * and any white space.
	 */
	while (isspace(*s)) {
		s++;
	}

	while (*s && isascii(*s) && isalpha(*s)) {
		s++;
	}

	while (isspace(*s)) {
		s++;
	}

	/*
	 * Subsequent modifier must be either "p<n>", or "all".
	 */
	if (*s == 'p') {
		s++;
		n = (int)strtol(s, &p, 0);
		if (p == s || *p != 0) {
			err_print("Syntax error: %s\n", input);
		} else {
			fmt_print("\n");
			(void) default_page(n);
			fmt_print("\n");
		}
	} else if (*s == 'a') {
		default_all_pages();
	} else {
		err_print("Syntax error: %s\n", input);
	}
}


static void
default_all_pages(void)
{
	char			*p;
	struct mode_header	*mh;
	struct mode_page	*mp;
	int			n;
	struct uscsi_cmd	ucmd;
	union scsi_cdb		cdb;
	char			msbuf[MAX_MODE_SENSE_SIZE];
	int			nbytes = sizeof (msbuf);
	int			status;

	/*
	 * Build and execute the uscsi ioctl.  Note that
	 * we cannot simply call uscsi_mode_sense() here,
	 * since that function attempts to valididate the
	 * returned data, and the page 0x3f has a unique
	 * format.
	 */
	nbytes = MAX_MODE_SENSE_SIZE;
	(void) memset(msbuf, 0, nbytes);
	(void) memset((char *)&ucmd, 0, sizeof (ucmd));
	(void) memset((char *)&cdb, 0, sizeof (union scsi_cdb));
	cdb.scc_cmd = SCMD_MODE_SENSE;
	FORMG0COUNT(&cdb, (uchar_t)nbytes);
	cdb.cdb_opaque[2] = MODE_SENSE_PC_DEFAULT | 0x3f;
	ucmd.uscsi_cdb = (caddr_t)&cdb;
	ucmd.uscsi_cdblen = CDB_GROUP0;
	ucmd.uscsi_bufaddr = msbuf;
	ucmd.uscsi_buflen = nbytes;
	status = uscsi_cmd(cur_file, &ucmd, (option_msg) ? F_NORMAL : F_SILENT);
	if (status) {
		if (!option_msg) {
			err_print("\nMode sense page 0x3f failed\n");
		}
		return;
	}

	fmt_print("\n");

	/*
	 * Now parse the page 0x3f
	 */
	mh = (struct mode_header *)msbuf;
	nbytes = mh->length - sizeof (struct mode_header) -
	    mh->bdesc_length + 1;
	p = msbuf + sizeof (struct mode_header) + mh->bdesc_length;

	while (nbytes > 0) {
		mp = (struct mode_page *)p;
		n = mp->length + sizeof (struct mode_page);
		nbytes -= n;
		if (nbytes < 0)
			break;
		if (default_page(mp->code) == 0) {
			goto error;
		}
		p += n;
	}

	if (nbytes < 0) {
		err_print("Mode sense page 0x3f formatted incorrectly:\n");
	}
error:
	fmt_print("\n");
}


static int
default_page(int pageno)
{
	struct scsi_ms_header	header;
	char			saved[MAX_MODE_SENSE_SIZE];
	char			current[MAX_MODE_SENSE_SIZE];
	char			dfault[MAX_MODE_SENSE_SIZE];
	struct mode_page	*sp;
	struct mode_page	*cp;
	struct mode_page	*dp;
	int			length;
	int			flags;
	int			i;
	int			need_mode_select;

	/*
	 * Get default mode sense
	 */
	if (uscsi_mode_sense(cur_file, pageno, MODE_SENSE_PC_DEFAULT,
	    dfault, MAX_MODE_SENSE_SIZE, &header)) {
		err_print("Mode sense on page %x (dfault) failed\n", pageno);
		return (0);
	}

	/*
	 * Get the current mode sense.
	 */
	if (uscsi_mode_sense(cur_file, pageno, MODE_SENSE_PC_CURRENT,
	    current, MAX_MODE_SENSE_SIZE, &header)) {
		err_print("Mode sense on page %x (current) failed\n", pageno);
		return (0);
	}

	/*
	 * Get saved mode sense.  If this fails, assume it is
	 * the same as the current.
	 */
	if (uscsi_mode_sense(cur_file, pageno, MODE_SENSE_PC_SAVED,
	    saved, MAX_MODE_SENSE_SIZE, &header)) {
		(void) memcpy(saved, current, MAX_MODE_SENSE_SIZE);
	}

	/*
	 * Determine if we need a mode select on this page.
	 * Just deal with the intersection of the three pages.
	 */
	sp = (struct mode_page *)saved;
	cp = (struct mode_page *)current;
	dp = (struct mode_page *)dfault;
	length = min(MODESENSE_PAGE_LEN(sp), MODESENSE_PAGE_LEN(cp));
	length = min(length, MODESENSE_PAGE_LEN(dp));

	need_mode_select = 0;
	for (i = 2; i < length; i++) {
		if (current[i] != dfault[i] || saved[i] != dfault[i]) {
			current[i] = dfault[i];
			need_mode_select = 1;
		}
	}

	if (need_mode_select == 0) {
		fmt_print("Defaulting page 0x%x: ok\n", pageno);
		return (1);
	}

	/*
	 * A change was made.  Do a mode select
	 * We always want to set the Page Format bit.
	 * Set the Save Page bit if the drive indicates
	 * that it can save this page.
	 */
	length = MODESENSE_PAGE_LEN(cp);
	flags = MODE_SELECT_PF;
	if (cp->ps) {
		flags |= MODE_SELECT_SP;
	}
	cp->ps = 0;
	header.mode_header.length = 0;
	header.mode_header.device_specific = 0;
	if (uscsi_mode_select(cur_file, pageno, flags,
	    current, length, &header)) {
		/*
		 * Failed - try not saving parameters,
		 * if possible.
		 */
		if (flags & MODE_SELECT_SP) {
			flags &= ~MODE_SELECT_SP;
			if (uscsi_mode_select(cur_file, pageno, flags,
			    saved, length, &header)) {
				fmt_print("Defaulting page 0x%x: failed\n",
				    pageno);
			} else {
				fmt_print("Defaulting page 0x%x: ", pageno);
				fmt_print("cannot save page permanently\n");
			}
		} else {
			fmt_print("Defaulting page 0x%x: ", pageno);
			fmt_print("cannot save page permanently\n");
		}
	} else {
		fmt_print("Defaulting page 0x%x: mode select ok\n", pageno);
	}

	return (1);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright (c) 1991-2001 by Sun Microsystems, Inc.
 */

#ifndef	_MENU_SCSI_H
#define	_MENU_SCSI_H

#ifdef	__cplusplus
extern "C" {
#endif

/*
 *	Prototypes for ANSI
 */
int	c_scsi(void);

#ifdef	__cplusplus
}
#endif

#endif	/* _MENU_SCSI_H */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright (c) 1991, 2010, Oracle and/or its affiliates. All rights reserved.
 */

/*
 * This file contains miscellaneous routines.
 */
#include "global.h"

#include <stdlib.h>
#include <signal.h>
#include <malloc.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/fcntl.h>
#include <sys/time.h>
#include <ctype.h>
#include <termio.h>
#include "misc.h"
#include "analyze.h"
#include "label.h"
#include "startup.h"

/* Function prototypes for ANSI C Compilers */
static void	cleanup(int sig);

struct	env *current_env = NULL;	/* ptr to current environment */
static int	stop_pending = 0;	/* ctrl-Z is pending */
struct	ttystate ttystate;		/* tty info */
static int	aborting = 0;		/* in process of aborting */

/*
 * For 4.x, limit the choices of valid disk names to this set.
 */
static char		*disk_4x_identifiers[] = { "sd", "id"};
#define	N_DISK_4X_IDS	(sizeof (disk_4x_identifiers)/sizeof (char *))


/*
 * This is the list of legal inputs for all yes/no questions.
 */
char	*confirm_list[] = {
	"yes",
	"no",
	NULL,
};

/*
 * This routine is a wrapper for malloc.  It allocates pre-zeroed space,
 * and checks the return value so the caller doesn't have to.
 */
void *
zalloc(int count)
{
	void	*ptr;

	if ((ptr = calloc(1, (unsigned)count)) == NULL) {
		err_print("Error: unable to calloc more space.\n");
		fullabort();
	}
	return (ptr);
}

/*
 * This routine is a wrapper for realloc.  It reallocates the given
 * space, and checks the return value so the caller doesn't have to.
 * Note that the any space added by this call is NOT necessarily
 * zeroed.
 */
void *
rezalloc(void *ptr, int count)
{
	void	*new_ptr;


	if ((new_ptr = realloc((char *)ptr, (unsigned)count)) == NULL) {
		err_print("Error: unable to realloc more space.\n");
		fullabort();
	}
	return (new_ptr);
}

/*
 * This routine is a wrapper for free.
 */
void
destroy_data(char *data)
{
	free(data);
}

#ifdef	not
/*
 * This routine takes the space number returned by an ioctl call and
 * returns a mnemonic name for that space.
 */
char *
space2str(uint_t space)
{
	char	*name;

	switch (space&SP_BUSMASK) {
	case SP_VIRTUAL:
		name = "virtual";
		break;
	case SP_OBMEM:
		name = "obmem";
		break;
	case SP_OBIO:
		name = "obio";
		break;
	case SP_MBMEM:
		name = "mbmem";
		break;
	case SP_MBIO:
		name = "mbio";
		break;
	default:
		err_print("Error: unknown address space type encountered.\n");
		fullabort();
	}
	return (name);
}
#endif	/* not */

/*
 * This routine asks the user the given yes/no question and returns
 * the response.
 */
int
check(char *question)
{
	int		answer;
	u_ioparam_t	ioparam;

	/*
	 * If we are running out of a command file, assume a yes answer.
	 */
	if (option_f)
		return (0);
	/*
	 * Ask the user.
	 */
	ioparam.io_charlist = confirm_list;
	answer = input(FIO_MSTR, question, '?', &ioparam, NULL, DATA_INPUT);
	return (answer);
}

/*
 * This routine aborts the current command.  It is called by a ctrl-C
 * interrupt and also under certain error conditions.
 */
void
cmdabort(int sig __unused)
{
	/*
	 * If there is no usable saved environment, gracefully exit.  This
	 * allows the user to interrupt the program even when input is from
	 * a file, or if there is no current menu, like at the "Select disk:"
	 * prompt.
	 */
	if (current_env == NULL || !(current_env->flags & ENV_USE))
		fullabort();

	/*
	 * If we are in a critical zone, note the attempt and return.
	 */
	if (current_env->flags & ENV_CRITICAL) {
		current_env->flags |= ENV_ABORT;
		return;
	}
	/*
	 * All interruptions when we are running out of a command file
	 * cause the program to gracefully exit.
	 */
	if (option_f)
		fullabort();
	fmt_print("\n");
	/*
	 * Clean up any state left by the interrupted command.
	 */
	cleanup(sig);
	/*
	 * Jump to the saved environment.
	 */
	longjmp(current_env->env, 0);
}

/*
 * This routine implements the ctrl-Z suspend mechanism.  It is called
 * when a suspend signal is received.
 */
void
onsusp(int sig __unused)
{
	int		fix_term;
#ifdef	NOT_DEF
	sigset_t	sigmask;
#endif	/* NOT_DEF */

	/*
	 * If we are in a critical zone, note the attempt and return.
	 */
	if (current_env != NULL && current_env->flags & ENV_CRITICAL) {
		stop_pending = 1;
		return;
	}
	/*
	 * If the terminal is mucked up, note that we will need to
	 * re-muck it when we start up again.
	 */
	fix_term = ttystate.ttyflags;
	fmt_print("\n");
	/*
	 * Clean up any state left by the interrupted command.
	 */
	cleanup(sig);
#ifdef	NOT_DEF
	/* Investigate whether all this is necessary */
	/*
	 * Stop intercepting the suspend signal, then send ourselves one
	 * to cause us to stop.
	 */
	sigmask.sigbits[0] = (ulong_t)0xffffffff;
	if (sigprocmask(SIG_SETMASK, &sigmask, NULL) == -1)
		err_print("sigprocmask failed %d\n", errno);
#endif	/* NOT_DEF */
	(void) signal(SIGTSTP, SIG_DFL);
	(void) kill(0, SIGTSTP);
	/*
	 * PC stops here
	 */
	/*
	 * We are started again.  Set us up to intercept the suspend
	 * signal once again.
	 */
	(void) signal(SIGTSTP, onsusp);
	/*
	 * Re-muck the terminal if necessary.
	 */
	if (fix_term & TTY_ECHO_OFF)
		echo_off();
	if (fix_term & TTY_CBREAK_ON)
		charmode_on();
}

/*
 * This routine implements the timing function used during long-term
 * disk operations (e.g. formatting).  It is called when an alarm signal
 * is received.
 */
void
onalarm(int sig __unused)
{
}


/*
 * This routine gracefully exits the program.
 */
void
fullabort(void)
{

	fmt_print("\n");
	/*
	 * Clean up any state left by an interrupted command.
	 * Avoid infinite loops caused by a clean-up
	 * routine failing again...
	 */
	if (!aborting) {
		aborting = 1;
		cleanup(SIGKILL);
	}
	exit(1);
	/*NOTREACHED*/
}

/*
 * This routine cleans up the state of the world.  It is a hodge-podge
 * of kludges to allow us to interrupt commands whenever possible.
 *
 * Some cleanup actions may depend on the type of signal.
 */
static void
cleanup(int sig)
{

	/*
	 * Lock out interrupts to avoid recursion.
	 */
	enter_critical();
	/*
	 * Fix up the tty if necessary.
	 */
	if (ttystate.ttyflags & TTY_CBREAK_ON) {
		charmode_off();
	}
	if (ttystate.ttyflags & TTY_ECHO_OFF) {
		echo_on();
	}

	/*
	 * If the defect list is dirty, write it out.
	 */
	if (cur_list.flags & LIST_DIRTY) {
		cur_list.flags = 0;
		if (!EMBEDDED_SCSI)
			write_deflist(&cur_list);
	}
	/*
	 * If the label is dirty, write it out.
	 */
	if (cur_flags & LABEL_DIRTY) {
		cur_flags &= ~LABEL_DIRTY;
		(void) write_label();
	}
	/*
	 * If we are logging and just interrupted a scan, print out
	 * some summary info to the log file.
	 */
	if (log_file && scan_cur_block >= 0) {
		pr_dblock(log_print, scan_cur_block);
		log_print("\n");
	}
	if (scan_blocks_fixed >= 0)
		fmt_print("Total of %lld defective blocks repaired.\n",
		    scan_blocks_fixed);
	if (sig != SIGSTOP) { /* Don't reset on suspend (converted to stop) */
		scan_cur_block = scan_blocks_fixed = -1;
	}
	exit_critical();
}

/*
 * This routine causes the program to enter a critical zone.  Within the
 * critical zone, no interrupts are allowed.  Note that calls to this
 * routine for the same environment do NOT nest, so there is not
 * necessarily pairing between calls to enter_critical() and exit_critical().
 */
void
enter_critical(void)
{

	/*
	 * If there is no saved environment, interrupts will be ignored.
	 */
	if (current_env == NULL)
		return;
	/*
	 * Mark the environment to be in a critical zone.
	 */
	current_env->flags |= ENV_CRITICAL;
}

/*
 * This routine causes the program to exit a critical zone.  Note that
 * calls to enter_critical() for the same environment do NOT nest, so
 * one call to exit_critical() will erase any number of such calls.
 */
void
exit_critical(void)
{

	/*
	 * If there is a saved environment, mark it to be non-critical.
	 */
	if (current_env != NULL)
		current_env->flags &= ~ENV_CRITICAL;
	/*
	 * If there is a stop pending, execute the stop.
	 */
	if (stop_pending) {
		stop_pending = 0;
		onsusp(SIGSTOP);
	}
	/*
	 * If there is an abort pending, execute the abort.
	 */
	if (current_env == NULL)
		return;
	if (current_env->flags & ENV_ABORT) {
		current_env->flags &= ~ENV_ABORT;
		cmdabort(SIGINT);
	}
}

/*
 * This routine turns off echoing on the controlling tty for the program.
 */
void
echo_off(void)
{
	/*
	 * Open the tty and store the file pointer for later.
	 */
	if (ttystate.ttyflags == 0) {
		if ((ttystate.ttyfile = open("/dev/tty",
		    O_RDWR | O_NDELAY)) < 0) {
			err_print("Unable to open /dev/tty.\n");
			fullabort();
		}
	}
	/*
	 * Get the parameters for the tty, turn off echoing and set them.
	 */
	if (tcgetattr(ttystate.ttyfile, &ttystate.ttystate) < 0) {
		err_print("Unable to get tty parameters.\n");
		fullabort();
	}
	ttystate.ttystate.c_lflag &= ~ECHO;
	if (tcsetattr(ttystate.ttyfile, TCSANOW, &ttystate.ttystate) < 0) {
		err_print("Unable to set tty to echo off state.\n");
		fullabort();
	}

	/*
	 * Remember that we've successfully turned
	 * ECHO mode off, so we know to fix it later.
	 */
	ttystate.ttyflags |= TTY_ECHO_OFF;
}

/*
 * This routine turns on echoing on the controlling tty for the program.
 */
void
echo_on(void)
{

	/*
	 * Using the saved parameters, turn echoing on and set them.
	 */
	ttystate.ttystate.c_lflag |= ECHO;
	if (tcsetattr(ttystate.ttyfile, TCSANOW, &ttystate.ttystate) < 0) {
		err_print("Unable to set tty to echo on state.\n");
		fullabort();
	}
	/*
	 * Close the tty and mark it ok again.
	 */
	ttystate.ttyflags &= ~TTY_ECHO_OFF;
	if (ttystate.ttyflags == 0) {
		(void) close(ttystate.ttyfile);
	}
}

/*
 * This routine turns off single character entry mode for tty.
 */
void
charmode_on(void)
{

	/*
	 * If tty unopened, open the tty and store the file pointer for later.
	 */
	if (ttystate.ttyflags == 0) {
		if ((ttystate.ttyfile = open("/dev/tty",
		    O_RDWR | O_NDELAY)) < 0) {
			err_print("Unable to open /dev/tty.\n");
			fullabort();
		}
	}
	/*
	 * Get the parameters for the tty, turn on char mode.
	 */
	if (tcgetattr(ttystate.ttyfile, &ttystate.ttystate) < 0) {
		err_print("Unable to get tty parameters.\n");
		fullabort();
	}
	ttystate.vmin = ttystate.ttystate.c_cc[VMIN];
	ttystate.vtime = ttystate.ttystate.c_cc[VTIME];

	ttystate.ttystate.c_lflag &= ~ICANON;
	ttystate.ttystate.c_cc[VMIN] = 1;
	ttystate.ttystate.c_cc[VTIME] = 0;

	if (tcsetattr(ttystate.ttyfile, TCSANOW, &ttystate.ttystate) < 0) {
		err_print("Unable to set tty to cbreak on state.\n");
		fullabort();
	}

	/*
	 * Remember that we've successfully turned
	 * CBREAK mode on, so we know to fix it later.
	 */
	ttystate.ttyflags |= TTY_CBREAK_ON;
}

/*
 * This routine turns on single character entry mode for tty.
 * Note, this routine must be called before echo_on.
 */
void
charmode_off(void)
{

	/*
	 * Using the saved parameters, turn char mode on.
	 */
	ttystate.ttystate.c_lflag |= ICANON;
	ttystate.ttystate.c_cc[VMIN] = ttystate.vmin;
	ttystate.ttystate.c_cc[VTIME] = ttystate.vtime;
	if (tcsetattr(ttystate.ttyfile, TCSANOW, &ttystate.ttystate) < 0) {
		err_print("Unable to set tty to cbreak off state.\n");
		fullabort();
	}
	/*
	 * Close the tty and mark it ok again.
	 */
	ttystate.ttyflags &= ~TTY_CBREAK_ON;
	if (ttystate.ttyflags == 0) {
		(void) close(ttystate.ttyfile);
	}
}


/*
 * Allocate space for and return a pointer to a string
 * on the stack.  If the string is null, create
 * an empty string.
 * Use destroy_data() to free when no longer used.
 */
char *
alloc_string(char *s)
{
	char	*ns;

	if (s == NULL) {
		ns = zalloc(1);
	} else {
		ns = zalloc(strlen(s) + 1);
		(void) strcpy(ns, s);
	}
	return (ns);
}



/*
 * This function can be used to build up an array of strings
 * dynamically, with a trailing NULL to terminate the list.
 *
 * Parameters:
 *	argvlist:  a pointer to the base of the current list.
 *		   does not have to be initialized.
 *	size:	   pointer to an integer, indicating the number
 *		   of string installed in the list.  Must be
 *		   initialized to zero.
 *	alloc:	   pointer to an integer, indicating the amount
 *		   of space allocated.  Must be initialized to
 *		   zero.  For efficiency, we allocate the list
 *		   in chunks and use it piece-by-piece.
 *	str:	   the string to be inserted in the list.
 *		   A copy of the string is malloc'ed, and
 *		   appended at the end of the list.
 * Returns:
 *	a pointer to the possibly-moved argvlist.
 *
 * No attempt to made to free unused memory when the list is
 * completed, although this would not be hard to do.  For
 * reasonably small lists, this should suffice.
 */
#define	INITIAL_LISTSIZE	32
#define	INCR_LISTSIZE		32

char **
build_argvlist(char **argvlist, int *size, int *alloc, char *str)
{
	if (*size + 2 > *alloc) {
		if (*alloc == 0) {
			*alloc = INITIAL_LISTSIZE;
			argvlist = zalloc(sizeof (char *) * (*alloc));
		} else {
			*alloc += INCR_LISTSIZE;
			argvlist = rezalloc((void *) argvlist,
			    sizeof (char *) * (*alloc));
		}
	}

	argvlist[*size] = alloc_string(str);
	*size += 1;
	argvlist[*size] = NULL;

	return (argvlist);
}


/*
 * Useful parsing macros
 */
#define	must_be(s, c)		if (*s++ != c) return (0)
#define	skip_digits(s)		while (isdigit(*s)) s++
/* Parsing macro below is created to handle fabric devices which contains */
/* upper hex digits like c2t210000203708B8CEd0s0.			  */
/* To get the target id(tid) the digit and hex upper digit need to	  */
/* be processed.							  */
#define	skip_digit_or_hexupper(s)	while (isdigit(*s) || \
					(isxdigit(*s) && isupper(*s))) s++

/*
 * Return true if a device name matches the conventions
 * for the particular system.
 */
int
conventional_name(char *name)
{
	must_be(name, 'c');
	skip_digits(name);
	if (*name == 't') {
		name++;
		skip_digit_or_hexupper(name);
	}
	must_be(name, 'd');
	skip_digits(name);
	must_be(name, 's');
	skip_digits(name);
	return (*name == 0);
}

#ifdef i386
/*
 * Return true if a device name match the emc powerpath name scheme:
 * emcpowerN[a-p,p0,p1,p2,p3,p4]
 */
int
emcpower_name(char *name)
{
	char	*emcp = "emcpower";
	char	*devp = "/dev/dsk";
	char	*rdevp = "/dev/rdsk";

	if (strncmp(devp, name, strlen(devp)) == 0) {
		name += strlen(devp) + 1;
	} else if (strncmp(rdevp, name, strlen(rdevp)) == 0) {
		name += strlen(rdevp) + 1;
	}
	if (strncmp(emcp, name, strlen(emcp)) == 0) {
		name += strlen(emcp);
		if (isdigit(*name)) {
			skip_digits(name);
			if ((*name >= 'a') && (*name <= 'p')) {
				name ++;
				if ((*name >= '0') && (*name <= '4')) {
					name++;
				}
			}
			return (*name == '\0');
		}
	}
	return (0);
}
#endif

/*
 * Return true if a device name matches the intel physical name conventions
 * for the particular system.
 */
int
fdisk_physical_name(char *name)
{
	must_be(name, 'c');
	skip_digits(name);
	if (*name == 't') {
		name++;
		skip_digit_or_hexupper(name);
	}
	must_be(name, 'd');
	skip_digits(name);
	must_be(name, 'p');
	skip_digits(name);
	return (*name == 0);
}

/*
 * Return true if a device name matches the conventions
 * for a "whole disk" name for the particular system.
 * The name in this case must match exactly that which
 * would appear in the device directory itself.
 */
int
whole_disk_name(char *name)
{
	must_be(name, 'c');
	skip_digits(name);
	if (*name == 't') {
		name++;
		skip_digit_or_hexupper(name);
	}
	must_be(name, 'd');
	skip_digits(name);
	must_be(name, 's');
	must_be(name, '2');
	return (*name == 0);
}


/*
 * Return true if a name is in the internal canonical form
 */
int
canonical_name(char *name)
{
	must_be(name, 'c');
	skip_digits(name);
	if (*name == 't') {
		name++;
		skip_digit_or_hexupper(name);
	}
	must_be(name, 'd');
	skip_digits(name);
	return (*name == 0);
}


/*
 * Return true if a name is in the internal canonical form for 4.x
 * Used to support 4.x naming conventions under 5.0.
 */
int
canonical4x_name(char *name)
{
	char    **p;
	int	i;

	p = disk_4x_identifiers;
	for (i = N_DISK_4X_IDS; i > 0; i--, p++) {
		if (match_substr(name, *p)) {
			name += strlen(*p);
			break;
		}
	}
	if (i == 0)
		return (0);
	skip_digits(name);
	return (*name == 0);
}


/*
 * Map a conventional name into the internal canonical form:
 *
 *	/dev/rdsk/c0t0d0s0 -> c0t0d0
 */
void
canonicalize_name(char *dst, char *src)
{
	char	*s;

	/*
	 * Copy from the 'c' to the end to the destination string...
	 */
	s = strchr(src, 'c');
	if (s != NULL) {
		(void) strcpy(dst, s);
		/*
		 * Remove the trailing slice (partition) reference
		 */
		s = dst + strlen(dst) - 2;
		if (*s == 's') {
			*s = 0;
		}
	} else {
		*dst = 0;	/* be tolerant of garbage input */
	}
}


/*
 * Return true if we find an occurance of s2 at the
 * beginning of s1.  We don't have to match all of
 * s1, but we do have to match all of s2
 */
int
match_substr(char *s1, char *s2)
{
	while (*s2 != 0) {
		if (*s1++ != *s2++)
		return (0);
	}

	return (1);
}


/*
 * Dump a structure in hexadecimal, for diagnostic purposes
 */
#define	BYTES_PER_LINE		16

void
dump(char *hdr, caddr_t src, int nbytes, int format)
{
	int	i;
	int	n;
	char	*p;
	char	s[256];

	assert(format == HEX_ONLY || format == HEX_ASCII);

	(void) strcpy(s, hdr);
	for (p = s; *p; p++) {
		*p = ' ';
	}

	p = hdr;
	while (nbytes > 0) {
		err_print("%s", p);
		p = s;
		n = min(nbytes, BYTES_PER_LINE);
		for (i = 0; i < n; i++) {
			err_print("%02x ", src[i] & 0xff);
		}
		if (format == HEX_ASCII) {
			for (i = BYTES_PER_LINE-n; i > 0; i--) {
				err_print("   ");
			}
			err_print("    ");
			for (i = 0; i < n; i++) {
				err_print("%c", isprint(src[i]) ? src[i] : '.');
			}
		}
		err_print("\n");
		nbytes -= n;
		src += n;
	}
}


float
bn2mb(uint64_t nblks)
{
	float	n;

	n = (float)nblks / 1024.0;
	return ((n / 1024.0) * cur_blksz);
}


diskaddr_t
mb2bn(float mb)
{
	diskaddr_t	n;

	n = (diskaddr_t)(mb * 1024.0 * (1024.0 / cur_blksz));
	return (n);
}

float
bn2gb(uint64_t nblks)
{
	float	n;

	n = (float)nblks / (1024.0 * 1024.0);
	return ((n/1024.0) * cur_blksz);

}

float
bn2tb(uint64_t nblks)
{
	float	n;

	n = (float)nblks / (1024.0 * 1024.0 * 1024.0);
	return ((n/1024.0) * cur_blksz);
}

diskaddr_t
gb2bn(float gb)
{
	diskaddr_t	n;

	n = (diskaddr_t)(gb * 1024.0 * 1024.0 * (1024.0 / cur_blksz));
	return (n);
}

/*
 * This routine finds out the number of lines (rows) in a terminal
 * window. The default value of TTY_LINES is returned on error.
 */
int
get_tty_lines(void)
{
	int	tty_lines = TTY_LINES;
	struct	winsize	winsize;

	if ((option_f == NULL) && isatty(0) == 1 && isatty(1) == 1) {
		/*
		 * We have a real terminal for std input and output
		 */
		winsize.ws_row = 0;
		if (ioctl(1, TIOCGWINSZ, &winsize) == 0) {
			if (winsize.ws_row > 2) {
				/*
				 * Should be atleast 2 lines, for division
				 * by (tty_lines - 1, tty_lines - 2) to work.
				 */
				tty_lines = winsize.ws_row;
			}
		}
	}
	return (tty_lines);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright (c) 1991, 2010, Oracle and/or its affiliates. All rights reserved.
 */

#ifndef	_MISC_H
#define	_MISC_H

#ifdef	__cplusplus
extern "C" {
#endif

/*
 * This file contains declarations pertaining to the miscellaneous routines.
 */
#include <setjmp.h>
#include <termios.h>

/*
 * Define macros bzero and bcopy for convenience
 */
#ifndef	bzero
#define	bzero(p, n)		(void) memset((p), 0, (n))
#endif
#ifndef	bcopy
#define	bcopy(src, dst, n)	(void) memcpy((dst), (src), (n))
#endif
#ifndef	bcmp
#define	bcmp(p1, p2, n)		memcmp((p1), (p2), (n))
#endif

/*
 * Minimum and maximum macros
 */
#ifndef min
#define	min(x, y)	((x) < (y) ? (x) : (y))
#endif	/* min */
#ifndef max
#define	max(x, y)	((x) > (y) ? (x) : (y))
#endif	/* max */

/*
 * This defines the structure of a saved environment.  It consists of the
 * environment itself, a pointer to the next environment on the stack, and
 * flags to tell whether the environment is active, etc.
 */
struct env {
	jmp_buf env;				/* environment buf */
	struct	env *ptr;			/* ptr to next on list */
	char	flags;				/* flags */
};
extern	struct env *current_env;
/*
 * This macro saves the current environment in the given structure and
 * pushes the structure onto our enivornment stack.  It initializes the
 * flags to zero (inactive).
 */
#define	saveenv(x)	{ \
			x.ptr = current_env; \
			current_env = &x; \
			(void) setjmp(x.env); \
			x.flags = 0; \
			}
/*
 * This macro marks the environment on the top of the stack active.  It
 * assumes that there is an environment on the stack.
 */
#define	useenv()	(current_env->flags |= ENV_USE)
/*
 * This macro marks the environment on the top of the stack inactive.  It
 * assumes that there is an environment on the stack.
 */
#define	unuseenv()	(current_env->flags &= ~ENV_USE)
/*
 * This macro pops an environment off the top of the stack.  It
 * assumes that there is an environment on the stack.
 */
#define	clearenv()	(current_env = current_env->ptr)
/*
 * These are the flags for the environment struct.
 */
#define	ENV_USE		0x01			/* active */
#define	ENV_CRITICAL	0x02			/* in critical zone */
#define	ENV_ABORT	0x04			/* abort pending */

/*
 * This structure is used to keep track of the state of the tty.  This
 * is necessary because some of the commands turn off echoing.
 */
struct ttystate {
	struct termios	ttystate;		/* buffer for ioctls */
	int		ttyflags;		/* changes to tty state */
	int		ttyfile;		/* file for ioctls */
	int		vmin;			/* min read satisfier */
	int		vtime;			/* read timing */
};

/*
 * ttyflags - changes we can make to the tty state.
 */
#define	TTY_ECHO_OFF	0x01			/* turned echo off */
#define	TTY_CBREAK_ON	0x02			/* turned cbreak on */

/*
 * This is the number lines assumed for the tty.  It is designed to work
 * on terminals as well as sun monitors.
 */
#define	TTY_LINES	24

/*
 * format parameter to dump()
 */
#define	HEX_ONLY	0			/* print hex only */
#define	HEX_ASCII	1			/* hex and ascii */


/*
 *	Prototypes for ANSI C
 */
void	*zalloc(int count);
void	*rezalloc(void *ptr, int count);
void	destroy_data(char *data);
int	check(char *question);
void	cmdabort(int sig);
void	onsusp(int sig);
void	onalarm(int sig);
void	fullabort(void) __NORETURN;
void	enter_critical(void);
void	exit_critical(void);
void	echo_off(void);
void	echo_on(void);
void	charmode_on(void);
void	charmode_off(void);
char	*alloc_string(char *s);
char	**build_argvlist(char **, int *, int *, char *);
int	conventional_name(char *name);
#ifdef i386
int	emcpower_name(char *name);
#endif


#if defined(_FIRMWARE_NEEDS_FDISK)
int	fdisk_physical_name(char *name);
#endif	/* defined(_FIRMWARE_NEEDS_FDISK) */

int	whole_disk_name(char *name);
int	canonical_name(char *name);
int	canonical4x_name(char *name);
void	canonicalize_name(char *dst, char *src);
int	match_substr(char *s1, char *s2);
void	dump(char *, caddr_t, int, int);
float	bn2mb(uint64_t);
diskaddr_t	mb2bn(float);
float	bn2gb(uint64_t);
float	bn2tb(uint64_t);
diskaddr_t	gb2bn(float);
int	get_tty_lines();


/*
 * Macro to handle internal programming errors that
 * should "never happen".
 */
#define	impossible(msg)	{err_print("Internal error: file %s, line %d: %s\n", \
				__FILE__, __LINE__, msg); \
			fullabort(); }


extern	char	*confirm_list[];

/*
 * This defines the size of the blind selection verfication prompt
 */

#define	BLIND_SELECT_VER_PROMPT	(43 + MAXNAMELEN)

#ifdef	__cplusplus
}
#endif

#endif	/* _MISC_H */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright (c) 1991, 2010, Oracle and/or its affiliates. All rights reserved.
 */

/*
 * This file contains functions to implement the partition menu commands.
 */
#include <stdlib.h>
#include <string.h>
#include "global.h"
#include "partition.h"
#include "menu_partition.h"
#include "menu_command.h"
#include "modify_partition.h"
#include "checkdev.h"
#include "misc.h"
#include "label.h"
#include "auto_sense.h"

static void	adj_cyl_offset(struct dk_map32 *map);
static int	check_map(struct dk_map32 *map);
static void	get_user_map(struct dk_map32 *map, int float_part);
static void	get_user_map_efi(struct dk_gpt *map, int float_part);

static char *partn_list[] = { "0", "1", "2", "3", "4", "5", "6", "7", NULL };

static char *sel_list[] = { "0", "1", "2", "3", NULL };

#define	MBYTE	(1024*1024)


/*
 * Modify/Create a predefined partition table.
 */
int
p_modify(void)
{
	struct	partition_info	tmp_pinfo[1];
	struct	dk_map32	*map = tmp_pinfo->pinfo_map;
	u_ioparam_t		ioparam;
	int			inpt_dflt = 0;
	int			free_hog = -1;
	int			i;
	char			tmpstr[80];
	char			tmpstr2[300];
	int			sel_type = 0;

	/*
	 * There must be a current disk type (and therefore a current disk).
	 */
	if (cur_dtype == NULL) {
		err_print("Current Disk Type is not set.\n");
		return (-1);
	}

	/*
	 * check if there exists a partition table for the disk.
	 */
	if (cur_parts == NULL) {
		err_print("Current Disk has no partition table.\n");
		return (-1);
	}


	/*
	 * If the disk has mounted partitions, cannot modify
	 */
	if (checkmount((diskaddr_t)-1, (diskaddr_t)-1)) {
		err_print(
"Cannot modify disk partitions while it has mounted partitions.\n\n");
		return (-1);
	}

	/*
	 * If the disk has partitions currently being used for
	 * swapping, cannot modify
	 */
	if (checkswap((diskaddr_t)-1, (diskaddr_t)-1)) {
		err_print(
"Cannot modify disk partitions while it is \
currently being used for swapping.\n");
		return (-1);
	}

	/*
	 * Check to see if any partitions used for svm, vxvm, ZFS zpool
	 * or live upgrade are on the disk.
	 */
	if (checkdevinuse(cur_disk->disk_name, (diskaddr_t)-1,
	    (diskaddr_t)-1, 0, 0)) {
		err_print("Cannot modify disk partition when "
		    "partitions are in use as described.\n");
		return (-1);
	}

	/*
	 * prompt user for a partition table base
	 */
	if (cur_parts->pinfo_name != NULL) {
		(void) snprintf(tmpstr, sizeof (tmpstr),
		    "\t0. Current partition table (%s)",
		    cur_parts->pinfo_name);
	} else {
		(void) sprintf(tmpstr,
		    "\t0. Current partition table (unnamed)");
	}

	(void) snprintf(tmpstr2, sizeof (tmpstr2),
	    "Select partitioning base:\n%s\n"
	    "\t1. All Free Hog\n"
	    "Choose base (enter number) ",
	    tmpstr);

	ioparam.io_charlist = sel_list;
	sel_type = input(FIO_MSTR, tmpstr2, '?', &ioparam,
	    &sel_type, DATA_INPUT);

	switch (cur_label) {
	case L_TYPE_SOLARIS:
		if (sel_type == 0) {
			/*
			 * Check for invalid parameters but do
			 * not modify the table.
			 */
			if (check_map(cur_parts->pinfo_map)) {
				err_print("Warning: Fix, or select a "
				    "different partition table.\n");
				return (0);
			}
			/*
			 * Create partition map from existing map
			 */
			tmp_pinfo->vtoc = cur_parts->vtoc;
			for (i = 0; i < NDKMAP; i++) {
				map[i].dkl_nblk =
				    cur_parts->pinfo_map[i].dkl_nblk;
				map[i].dkl_cylno =
				    cur_parts->pinfo_map[i].dkl_cylno;
			}
		} else {
			/*
			 * Make an empty partition map, with all the space
			 * in the c partition.
			 */
			set_vtoc_defaults(tmp_pinfo);
			for (i = 0; i < NDKMAP; i++) {
				map[i].dkl_nblk = 0;
				map[i].dkl_cylno = 0;
			}
			map[C_PARTITION].dkl_nblk = ncyl * spc();

#if defined(i386)
			/*
			 * Adjust for the boot and possibly alternates
			 * partitions.
			 */
			map[I_PARTITION].dkl_nblk = spc();
			map[I_PARTITION].dkl_cylno = 0;
			if (cur_ctype->ctype_ctype != DKC_SCSI_CCS) {
				map[J_PARTITION].dkl_nblk = 2 * spc();
				map[J_PARTITION].dkl_cylno = spc() / spc();
			}
#endif			/* defined(i386) */
		}
		break;
	case L_TYPE_EFI:
		if (sel_type == 1) {
			for (i = 0; i < cur_parts->etoc->efi_nparts; i++) {
				cur_parts->etoc->efi_parts[i].p_start = 0;
				cur_parts->etoc->efi_parts[i].p_size = 0;
			}
		}
		break;
	}

	fmt_print("\n");
	if (cur_label == L_TYPE_SOLARIS) {
		print_map(tmp_pinfo);
	} else {
		print_map(cur_parts);
	}

	ioparam.io_charlist = confirm_list;
	if (input(FIO_MSTR, "Do you wish to continue creating a new "
	    "partition\ntable based on above table",
	    '?', &ioparam, &inpt_dflt, DATA_INPUT)) {
		return (0);
	}

	/*
	 * get Free Hog partition
	 */
	inpt_dflt = 1;
	while ((free_hog < 0) && (cur_label == L_TYPE_SOLARIS)) {
		free_hog = G_PARTITION;	/* default to g partition */
		ioparam.io_charlist = partn_list;
		free_hog = input(FIO_MSTR, "Free Hog partition", '?',
		    &ioparam, &free_hog, DATA_INPUT);
		/* disallow c partition */
		if (free_hog == C_PARTITION) {
			fmt_print("'%c' cannot be the 'Free Hog' partition.\n",
			    C_PARTITION + PARTITION_BASE);
			free_hog = -1;
			continue;
		}
		/*
		 * If user selected all float set the
		 * float to be the whole disk.
		 */
		if (sel_type == 1) {
			map[free_hog].dkl_nblk = map[C_PARTITION].dkl_nblk;
#if defined(i386)
			map[free_hog].dkl_nblk -= map[I_PARTITION].dkl_nblk;
			if (cur_ctype->ctype_ctype != DKC_SCSI_CCS) {
				map[free_hog].dkl_nblk -=
				    map[J_PARTITION].dkl_nblk;
			}
#endif			/* defined(i386) */
			break;
		}
		/*
		 * Warn the user if there is no free space in
		 * the float partition.
		 */
		if (map[free_hog].dkl_nblk == 0) {
			err_print("Warning: No space available from Free Hog "
			    "partition.\n");
			ioparam.io_charlist = confirm_list;
			if (input(FIO_MSTR, "Continue", '?',
			    &ioparam, &inpt_dflt, DATA_INPUT)) {
				free_hog = -1;
			}
		}
	}
	inpt_dflt = 0;

	if (cur_label == L_TYPE_EFI) {
		free_hog = G_PARTITION; /* default to g partition */
		ioparam.io_charlist = partn_list;
		free_hog = input(FIO_MSTR, "Free Hog partition", '?',
		    &ioparam, &free_hog, DATA_INPUT);
		/* disallow c partition */
		if (free_hog == C_PARTITION) {
			fmt_print("'%c' cannot be the 'Free Hog' partition.\n",
			    C_PARTITION + PARTITION_BASE);
			return (-1);
		}
		get_user_map_efi(cur_parts->etoc, free_hog);
		print_map(cur_parts);
		if (check("Ready to label disk, continue")) {
			return (-1);
		}
		fmt_print("\n");
		if (write_label()) {
			err_print("Writing label failed\n");
			return (-1);
		}
		return (0);
	}
	/*
	 * get user modified partition table
	 */
	get_user_map(map, free_hog);

	/*
	 * Update cylno offsets
	 */
	adj_cyl_offset(map);

	fmt_print("\n");
	print_map(tmp_pinfo);

	ioparam.io_charlist = confirm_list;
	if (input(FIO_MSTR, "Okay to make this the current partition table",
	    '?', &ioparam, &inpt_dflt, DATA_INPUT)) {
		return (0);
	} else {
		make_partition();
		/*
		 * Update new partition map
		 */
		for (i = 0; i < NDKMAP; i++) {
			cur_parts->pinfo_map[i].dkl_nblk = map[i].dkl_nblk;
			cur_parts->pinfo_map[i].dkl_cylno = map[i].dkl_cylno;
#ifdef i386
			cur_parts->vtoc.v_part[i].p_start =
			    map[i].dkl_cylno * nhead * nsect;
			cur_parts->vtoc.v_part[i].p_size =
			    map[i].dkl_nblk;
#endif
		}
		(void) p_name();

		/*
		 * Label the disk now
		 */
		if (check("Ready to label disk, continue")) {
			return (-1);
		}
		fmt_print("\n");
		if (write_label()) {
			err_print("Writing label failed\n");
			return (-1);
		}
		return (0);
	}
}

/*
 * Adjust cylinder offsets
 */
static void
adj_cyl_offset(struct dk_map32 *map)
{
	int	i;
	int	cyloffset = 0;


	/*
	 * Update cylno offsets
	 */

#if defined(_SUNOS_VTOC_16)
	/*
	 * Correct cylinder allocation for having the boot and alternates
	 * slice in the beginning of the disk
	 */
	for (i = NDKMAP/2; i < NDKMAP; i++) {
		if (i != C_PARTITION && map[i].dkl_nblk) {
			map[i].dkl_cylno = cyloffset;
			cyloffset += (map[i].dkl_nblk + (spc()-1))/spc();
		} else if (map[i].dkl_nblk == 0) {
			map[i].dkl_cylno = 0;
		}
	}
	for (i = 0; i < NDKMAP/2; i++) {

#else					/* !defined(_SUNOS_VTOC_16) */
	for (i = 0; i < NDKMAP; i++) {
#endif					/* defined(_SUNOS_VTOC_16) */

		if (i != C_PARTITION && map[i].dkl_nblk) {
			map[i].dkl_cylno = cyloffset;
			cyloffset += (map[i].dkl_nblk + (spc()-1))/spc();
		} else if (map[i].dkl_nblk == 0) {
			map[i].dkl_cylno = 0;
		}
	}
}


/*
 * Check partition table
 */
static int
check_map(struct dk_map32 *map)
{
	int		i;
	int		cyloffset = 0;
	blkaddr32_t	tot_blks = 0;

#ifdef i386
	/*
	 * On x86, we must account for the boot and alternates
	 */
	cyloffset = map[0].dkl_cylno;
	tot_blks = map[0].dkl_nblk;
#endif

	/*
	 * Do some checks for invalid parameters but do
	 * not modify the table.
	 */
	for (i = 0; i < NDKMAP; i++) {
		if (map[i].dkl_cylno > (blkaddr32_t)ncyl-1) {
			err_print("Warning: Partition %c starting cylinder "
			    "%d is out of range.\n",
			    (PARTITION_BASE+i), map[i].dkl_cylno);
			return (-1);
		}
		if (map[i].dkl_nblk >
		    (blkaddr32_t)(ncyl - map[i].dkl_cylno) * spc()) {
			err_print("Warning: Partition %c, specified # of "
			    "blocks, %u, is out of range.\n",
			    (PARTITION_BASE+i), map[i].dkl_nblk);
			return (-1);
		}
		if (i != C_PARTITION && map[i].dkl_nblk) {
#ifdef	i386
			if (i == I_PARTITION || i == J_PARTITION)
				continue;
#endif
			if (map[i].dkl_cylno < cyloffset) {
				err_print("Warning: Overlapping partition "
				    "(%c) in table.\n", PARTITION_BASE+i);
				return (-1);
			} else if (map[i].dkl_cylno > cyloffset) {
				err_print("Warning: Non-contiguous partition "
				    "(%c) in table.\n", PARTITION_BASE+i);
			}
			cyloffset += (map[i].dkl_nblk + (spc()-1))/spc();
			tot_blks = map[i].dkl_nblk;
		}
	}
	if (tot_blks > map[C_PARTITION].dkl_nblk) {
		err_print("Warning: Total blocks used is greater than number "
		    "of blocks in '%c'\n\tpartition.\n",
		    C_PARTITION + PARTITION_BASE);
	return (-1);
	}
	return (0);
}



/*
 * get user defined partitions
 */
static void
get_user_map(struct dk_map32 *map, int float_part)
{
	int		i;
	blkaddr32_t	newsize;
	blkaddr32_t	deflt;
	char		tmpstr[80];
	u_ioparam_t	ioparam;

	/*
	 * Get partition sizes
	 */
	for (i = 0; i < NDKMAP; i++) {
		if (partn_list[i] == NULL)
			break;
		if ((i == C_PARTITION) || (i == float_part)) {
			continue;
		} else {
			ioparam.io_bounds.lower = 0;
			ioparam.io_bounds.upper = map[i].dkl_nblk +
			    map[float_part].dkl_nblk;
			deflt = map[i].dkl_nblk;
			if (ioparam.io_bounds.upper == 0) {
				err_print("Warning: no space available for "
				    "'%s' from Free Hog partition\n",
				    partn_list[i]);
				continue;
			}
			(void) snprintf(tmpstr, sizeof (tmpstr),
			    "Enter size of partition '%s' ",
			    partn_list[i]);
			newsize = (blkaddr32_t)input(FIO_CYL, tmpstr, ':',
			    &ioparam, (int *)&deflt, DATA_INPUT);
			map[float_part].dkl_nblk -= (newsize - map[i].dkl_nblk);
			map[i].dkl_nblk = newsize;
		}
	}
}

static struct partition_info *
build_partition(struct disk_type *tptr)
{
	struct partition_info	*part;
	struct dk_label		*label;
	int			i;

#ifdef DEBUG
	fmt_print("Creating Default Partition for the disk \n");
#endif
	/*
	 * construct a label and pass it on to
	 * build_default_partition() which builds the
	 * default partition list.
	 */
	label = zalloc(sizeof (struct dk_label));
	label->dkl_pcyl = tptr->dtype_pcyl;
	label->dkl_ncyl = tptr->dtype_ncyl;
	label->dkl_acyl = tptr->dtype_acyl;
	label->dkl_nhead = tptr->dtype_nhead;
	label->dkl_nsect = tptr->dtype_nsect;
	label->dkl_apc = apc;
	label->dkl_intrlv = 1;
	label->dkl_rpm	= tptr->dtype_rpm;

	if (!build_default_partition(label, cur_ctype->ctype_ctype))
		return (NULL);

	part = zalloc(sizeof (struct partition_info));
	part->pinfo_name = alloc_string(tptr->dtype_asciilabel);
	/*
	 * Fill in the partition info from the label
	 */
	for (i = 0; i < NDKMAP; i++) {
#if defined(_SUNOS_VTOC_8)
		part->pinfo_map[i] = label->dkl_map[i];
#else
		part->pinfo_map[i].dkl_cylno =
		    label->dkl_vtoc.v_part[i].p_start /
		    (blkaddr32_t)(tptr->dtype_nhead * tptr->dtype_nsect - apc);
		part->pinfo_map[i].dkl_nblk =
		    label->dkl_vtoc.v_part[i].p_size;
#endif /* ifdefined(_SUNOS_VTOC_8) */
	}
	part->vtoc = label->dkl_vtoc;
	return (part);
}

/*
 * build new partition table for given disk type
 */
static void
get_user_map_efi(struct dk_gpt *map, int float_part)
{
	int		i;
	efi_deflt_t	efi_deflt;
	u_ioparam_t	ioparam;
	char		tmpstr[80];
	uint64_t	i64;
	uint64_t	start_lba = map->efi_first_u_lba;
	uint64_t	reserved;

	reserved = efi_reserved_sectors(map);
	for (i = 0; i < map->efi_nparts - 1; i++) {
		/* GPT partition 7 is whole disk device, minor node "wd" */
		if (i == float_part || i == 7)
			continue;

		ioparam.io_bounds.lower = start_lba;
		ioparam.io_bounds.upper = map->efi_last_u_lba;
		efi_deflt.start_sector = ioparam.io_bounds.lower;
		efi_deflt.end_sector = map->efi_parts[i].p_size;
		(void) sprintf(tmpstr, "Enter size of partition %d ", i);
		i64 = input(FIO_EFI, tmpstr, ':',
		    &ioparam, (int *)&efi_deflt, DATA_INPUT);
		if (i64 == 0) {
			map->efi_parts[i].p_tag = V_UNASSIGNED;
		} else if ((i64 != 0) && (map->efi_parts[i].p_tag ==
		    V_UNASSIGNED)) {
			map->efi_parts[i].p_tag = V_USR;
		}
		if (i64 == 0) {
			map->efi_parts[i].p_start = 0;
		} else {
			map->efi_parts[i].p_start = start_lba;
		}
		map->efi_parts[i].p_size = i64;
		start_lba += i64;
	}
	map->efi_parts[float_part].p_start = start_lba;
	map->efi_parts[float_part].p_size = map->efi_last_u_lba + 1 -
	    start_lba - reserved;
	map->efi_parts[float_part].p_tag = V_USR;
	if (map->efi_parts[float_part].p_size == 0) {
		map->efi_parts[float_part].p_size = 0;
		map->efi_parts[float_part].p_start = 0;
		map->efi_parts[float_part].p_tag = V_UNASSIGNED;
		fmt_print("Warning: No space left for HOG\n");
	}

	for (i = 0; i < map->efi_nparts; i++) {
		if (map->efi_parts[i].p_tag == V_RESERVED) {
			map->efi_parts[i].p_start = map->efi_last_u_lba -
			    reserved + 1;
			map->efi_parts[i].p_size = reserved;
			break;
		}
	}
}


void
new_partitiontable(struct disk_type *tptr, struct disk_type *oldtptr)
{
	struct partition_info *part;

	/*
	 * check if disk geometry has changed , if so add new
	 * partition table else copy the old partition table.(best guess).
	 */
	if ((oldtptr != NULL) &&
	    (tptr->dtype_ncyl == oldtptr->dtype_ncyl) &&
	    (tptr->dtype_nhead == oldtptr->dtype_nhead) &&
	    (tptr->dtype_nsect == oldtptr->dtype_nsect)) {
		part = (struct partition_info *)
		    zalloc(sizeof (struct partition_info));
		bcopy((char *)cur_parts, (char *)part,
		    sizeof (struct partition_info));
		part->pinfo_next = tptr->dtype_plist;
		tptr->dtype_plist = part;
	} else {

#ifdef DEBUG
		if (cur_parts != NULL) {
			fmt_print("Warning: Partition Table is set");
			fmt_print("to default partition table. \n");
		}
#endif
		if (tptr->dtype_plist == NULL) {
			part = (struct partition_info *)build_partition(tptr);
			if (part != NULL) {
				part->pinfo_next = tptr->dtype_plist;
				tptr->dtype_plist = part;
			}
		}
	}
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright (c) 1991-2001 by Sun Microsystems, Inc.
 * All rights reserved.
 */

#ifndef	_MODIFY_PARTITION_H
#define	_MODIFY_PARTITION_H

#ifdef	__cplusplus
extern "C" {
#endif


/*
 *	Prototypes for ANSI C compilers
 */
int	p_modify(void);

void	new_partitiontable(struct disk_type *tptr, struct  disk_type *oldtype);

#ifdef	__cplusplus
}
#endif

#endif	/* _MODIFY_PARTITION_H */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef	_PARAM_H
#define	_PARAM_H

#ifdef	__cplusplus
extern "C" {
#endif

#ifndef UINT16_MAX
#define	UINT16_MAX	0xffffU
#endif

#ifndef UINT32_MAX
#define	UINT32_MAX	0xffffffffU
#endif

#ifndef INT32_MAX
#define	INT32_MAX	0x7fffffff
#endif

/*
 * This file contains declarations of miscellaneous parameters.
 */
#ifndef	SECSIZE
#define	SECSIZE		DEV_BSIZE
#endif

#define	MAX_CYLS	(0x10000 - 1)		/* max legal cylinder count */
#define	MAX_HEADS	(0x10000 - 1)		/* max legal head count */
#define	MAX_SECTS	(0x10000 - 1)		/* max legal sector count */

#define	MIN_RPM		2000			/* min legal rpm */
#define	AVG_RPM		3600			/* default rpm */
#define	MAX_RPM		76000			/* max legal rpm */

#define	MIN_BPS		512			/* min legal bytes/sector */
#define	AVG_BPS		600			/* default bytes/sector */
#define	MAX_BPS		1000			/* max legal bytes/sector */

#define	INFINITY	0xffffffffU		/* a big number */

#define	MAXBLKS(heads, spt)	UINT16_MAX * heads * spt, heads, spt
#ifdef	__cplusplus
}
#endif

#endif	/* _PARAM_H */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright (c) 1991, 2010, Oracle and/or its affiliates. All rights reserved.
 * Copyright (c) 2016 by Delphix. All rights reserved.
 */

/*
 * This file contains functions that operate on partition tables.
 */
#include <string.h>
#include <stdlib.h>
#include "global.h"
#include "partition.h"
#include "misc.h"
#include "menu_command.h"
#include "menu_partition.h"


/*
 * Default vtoc information for non-SVr4 partitions
 */
struct dk_map2	default_vtoc_map[NDKMAP] = {
	{	V_ROOT,		0	},		/* a - 0 */
	{	V_SWAP,		V_UNMNT	},		/* b - 1 */
	{	V_BACKUP,	V_UNMNT	},		/* c - 2 */
	{	V_UNASSIGNED,	0	},		/* d - 3 */
	{	V_UNASSIGNED,	0	},		/* e - 4 */
	{	V_UNASSIGNED,	0	},		/* f - 5 */
	{	V_USR,		0	},		/* g - 6 */
	{	V_UNASSIGNED,	0	},		/* h - 7 */

#if defined(_SUNOS_VTOC_16)

#if defined(i386)
	{	V_BOOT,		V_UNMNT	},		/* i - 8 */
	{	V_ALTSCTR,	0	},		/* j - 9 */

#else
#error No VTOC format defined.
#endif			/* defined(i386) */

	{	V_UNASSIGNED,	0	},		/* k - 10 */
	{	V_UNASSIGNED,	0	},		/* l - 11 */
	{	V_UNASSIGNED,	0	},		/* m - 12 */
	{	V_UNASSIGNED,	0	},		/* n - 13 */
	{	V_UNASSIGNED,	0	},		/* o - 14 */
	{	V_UNASSIGNED,	0	},		/* p - 15 */
#endif			/* defined(_SUNOS_VTOC_16) */
};

/*
 * This routine finds the last usable sector in the partition table.
 * It skips the BACKUP partition.
 */
static uint64_t
maxofN(struct dk_gpt *map)
{
	uint64_t	max;
	uint64_t	sec_no[2], start[2], size[2];
	int		i;

	for (i = 0; i < map->efi_nparts - 1; i++) {
		start[0] = map->efi_parts[i].p_start;
		size[0] = map->efi_parts[i].p_size;
		sec_no[0] = start[0] + size[0];

		start[1] = map->efi_parts[i + 1].p_start;
		size[1] = map->efi_parts[i + 1].p_size;
		sec_no[1] = start[1] + size[1];

		if (map->efi_parts[i].p_tag == V_BACKUP) {
			sec_no[0] = 0;
		}
		if (map->efi_parts[i+1].p_tag == V_BACKUP) {
			sec_no[1] = 0;
		}
		if (i == 0) {
			max = sec_no[1];
		}
		if (sec_no[0] > max) {
			max = sec_no[0];
		} else {
			max = max;
		}
	}
	if (max == 0)
		max = map->efi_first_u_lba;
	return (max);
}

/*
 * This routine allows the user to change the boundaries of the given
 * partition in the current partition map.
 */
void
change_partition(int num)
{
	uint_t		i;
	uint64_t	i64, j64;
	uint_t		j;
	int		deflt;
	part_deflt_t	p_deflt;
	u_ioparam_t	ioparam;
	int		tag;
	int		flag;
	char		msg[256];
	blkaddr32_t	cyl_offset = 0;
	efi_deflt_t	efi_deflt;

	/*
	 * check if there exists a partition table for the disk.
	 */
	if (cur_parts == NULL) {
		err_print("Current Disk has no partition table.\n");
		return;
	}

	if (cur_label == L_TYPE_EFI) {
		if (num > cur_parts->etoc->efi_nparts - 1) {
			err_print("Invalid partition for EFI label\n");
			return;
		}
		print_efi_partition(cur_parts->etoc, num, 1);
		fmt_print("\n");
		/*
		 * Prompt for p_tag and p_flag values for this partition
		 */
		deflt = cur_parts->etoc->efi_parts[num].p_tag;
		if (deflt == V_UNASSIGNED) {
			deflt = V_USR;
		}
		(void) sprintf(msg, "Enter partition id tag");
		ioparam.io_slist = ptag_choices;
		tag = input(FIO_SLIST, msg, ':', &ioparam, &deflt, DATA_INPUT);

		deflt = cur_parts->etoc->efi_parts[num].p_flag;
		(void) sprintf(msg, "Enter partition permission flags");
		ioparam.io_slist = pflag_choices;
		flag = input(FIO_SLIST, msg, ':', &ioparam, &deflt, DATA_INPUT);

		ioparam.io_bounds.lower = cur_parts->etoc->efi_first_u_lba;
		ioparam.io_bounds.upper = cur_parts->etoc->efi_last_u_lba;

		efi_deflt.start_sector = maxofN(cur_parts->etoc);
		if ((cur_parts->etoc->efi_parts[num].p_start != 0) &&
		    (cur_parts->etoc->efi_parts[num].p_size != 0)) {
			efi_deflt.start_sector =
			    cur_parts->etoc->efi_parts[num].p_start;
		}
		efi_deflt.end_sector = ioparam.io_bounds.upper -
		    efi_deflt.start_sector;
		i64 = input(FIO_INT64, "Enter new starting Sector", ':',
		    &ioparam, (int *)&efi_deflt, DATA_INPUT);

		ioparam.io_bounds.lower = 0;
		ioparam.io_bounds.upper = cur_parts->etoc->efi_last_u_lba;
		efi_deflt.end_sector = cur_parts->etoc->efi_parts[num].p_size;
		efi_deflt.start_sector = i64;
		j64 = input(FIO_EFI, "Enter partition size", ':', &ioparam,
		    (int *)&efi_deflt, DATA_INPUT);
		if (j64 == 0) {
			tag = V_UNASSIGNED;
			i64 = 0;
		} else if ((j64 != 0) && (tag == V_UNASSIGNED)) {
			tag = V_USR;
		}

		if (cur_parts->pinfo_name != NULL)
			make_partition();

		cur_parts->etoc->efi_parts[num].p_tag = tag;
		cur_parts->etoc->efi_parts[num].p_flag = flag;
		cur_parts->etoc->efi_parts[num].p_start = i64;
		cur_parts->etoc->efi_parts[num].p_size = j64;
		/*
		 * We are now done with EFI part, so return now
		 */
		return;
	}
	/*
	 * Print out the given partition so the user knows what they're
	 * getting into.
	 */
	print_partition(cur_parts, num, 1);
	fmt_print("\n");

	/*
	 * Prompt for p_tag and p_flag values for this partition.
	 */
	assert(cur_parts->vtoc.v_version == V_VERSION);
	deflt = cur_parts->vtoc.v_part[num].p_tag;
	(void) sprintf(msg, "Enter partition id tag");
	ioparam.io_slist = ptag_choices;
	tag = input(FIO_SLIST, msg, ':', &ioparam, &deflt, DATA_INPUT);

	deflt = cur_parts->vtoc.v_part[num].p_flag;
	(void) sprintf(msg, "Enter partition permission flags");
	ioparam.io_slist = pflag_choices;
	flag = input(FIO_SLIST, msg, ':', &ioparam, &deflt, DATA_INPUT);

	/*
	 * Ask for the new values.  The old values are the defaults, and
	 * strict bounds checking is done on the values given.
	 */

#if defined(i386)

	if (tag != V_UNASSIGNED && tag != V_BACKUP && tag != V_BOOT) {
		/*
		 * Determine cyl offset for boot and alternate partitions.
		 * Assuming that the alternate sectors partition (slice)
		 * physical location immediately follows the boot
		 * partition and partition sizes are expressed in multiples
		 * of cylinder size.
		 */
		cyl_offset = cur_parts->pinfo_map[I_PARTITION].dkl_cylno + 1;
		if (tag != V_ALTSCTR) {
			if (cur_parts->pinfo_map[J_PARTITION].dkl_nblk != 0) {
				cyl_offset =
				    cur_parts->
				    pinfo_map[J_PARTITION].dkl_cylno +
				    ((cur_parts->
				    pinfo_map[J_PARTITION].dkl_nblk +
				    (spc() - 1)) / spc());
			}
		}
	}
#endif	/* defined(i386) */

	ioparam.io_bounds.lower = 0;
	ioparam.io_bounds.upper = ncyl - 1;
	deflt = max(cur_parts->pinfo_map[num].dkl_cylno, cyl_offset);
	i = (uint_t)input(FIO_INT, "Enter new starting cyl", ':', &ioparam,
	    &deflt, DATA_INPUT);

	ioparam.io_bounds.lower = 0;
	ioparam.io_bounds.upper = (ncyl - i) * spc();

	/* fill in defaults for the current partition */
	p_deflt.start_cyl = i;
	p_deflt.deflt_size = min(cur_parts->pinfo_map[num].dkl_nblk,
	    ioparam.io_bounds.upper);

	/* call input, passing p_deflt's address, typecast to (int *) */
	j = (uint_t)input(FIO_ECYL, "Enter partition size", ':', &ioparam,
	    (int *)&p_deflt, DATA_INPUT);

	/*
	 * If the current partition has a size of zero change the
	 * tag to Unassigned and the starting cylinder to zero
	 */

	if (j == 0) {
		tag = V_UNASSIGNED;
		i = 0;
	}


#if defined(i386)

	if (i < cyl_offset && tag != V_UNASSIGNED && tag != V_BACKUP &&
	    tag != V_BOOT) {
		/*
		 * This slice overlaps boot and/or alternates slice
		 * Check if it's the boot or alternates slice and warn
		 * accordingly
		 */
		if (i < cur_parts->pinfo_map[I_PARTITION].dkl_cylno + 1) {
			fmt_print("\nWarning: Partition overlaps boot ");
			fmt_print("partition. Specify different start cyl.\n");
			return;
		}
		/*
		 * Cyl offset for alternates partition was calculated before
		 */
		if (i < cyl_offset) {
			fmt_print("\nWarning: Partition overlaps alternates ");
			fmt_print("partition. Specify different start cyl.\n");
			return;
		}
	}

#endif	/* defined(i386) */

	/*
	 * If user has entered a V_BACKUP tag then the partition
	 * size should specify full disk capacity else
	 * return an Error.
	 */
	if (tag == V_BACKUP) {
		uint_t fullsz;

		fullsz = ncyl * nhead * nsect;
		if (fullsz != j) {
		/*
		 * V_BACKUP Tag Partition != full disk capacity.
		 * print useful messages.
		 */
		fmt_print("\nWarning: Partition with V_BACKUP tag should ");
		fmt_print("specify full disk capacity. \n");
		return;
		}
	}


	/*
	 * If the current partition is named, we can't change it.
	 * We create a new current partition map instead.
	 */
	if (cur_parts->pinfo_name != NULL)
		make_partition();
	/*
	 * Change the values.
	 */
	cur_parts->pinfo_map[num].dkl_cylno = i;
	cur_parts->pinfo_map[num].dkl_nblk = j;

#if defined(_SUNOS_VTOC_16)
	cur_parts->vtoc.v_part[num].p_start = (daddr_t)(i * (nhead * nsect));
	cur_parts->vtoc.v_part[num].p_size = (long)j;
#endif	/* defined(_SUNOS_VTOC_16) */

	/*
	 * Install the p_tag and p_flag values for this partition
	 */
	assert(cur_parts->vtoc.v_version == V_VERSION);
	cur_parts->vtoc.v_part[num].p_tag = (ushort_t)tag;
	cur_parts->vtoc.v_part[num].p_flag = (ushort_t)flag;
}


/*
 * This routine picks to closest partition table which matches the
 * selected disk type.  It is called each time the disk type is
 * changed.  If no match is found, it uses the first element
 * of the partition table.  If no table exists, a dummy is
 * created.
 */
int
get_partition(void)
{
	register struct partition_info *pptr;
	register struct partition_info *parts;

	/*
	 * If there are no pre-defined maps for this disk type, it's
	 * an error.
	 */
	parts = cur_dtype->dtype_plist;
	if (parts == NULL) {
		err_print("No defined partition tables.\n");
		make_partition();
		return (-1);
	}
	/*
	 * Loop through the pre-defined maps searching for one which match
	 * disk type.  If found copy it into unmamed partition.
	 */
	enter_critical();
	for (pptr = parts; pptr != NULL; pptr = pptr->pinfo_next) {
		if (cur_dtype->dtype_asciilabel) {
			if (pptr->pinfo_name != NULL && strcmp(pptr->pinfo_name,
			    cur_dtype->dtype_asciilabel) == 0) {
				/*
				 * Set current partition and name it.
				 */
				cur_disk->disk_parts = cur_parts = pptr;
				cur_parts->pinfo_name = pptr->pinfo_name;
				exit_critical();
				return (0);
			}
		}
	}
	/*
	 * If we couldn't find a match, take the first one.
	 * Set current partition and name it.
	 */
	cur_disk->disk_parts = cur_parts = cur_dtype->dtype_plist;
	cur_parts->pinfo_name = parts->pinfo_name;
	exit_critical();
	return (0);
}


/*
 * This routine creates a new partition map and sets it current.  If there
 * was a current map, the new map starts out identical to it.  Otherwise
 * the new map starts out all zeroes.
 */
void
make_partition(void)
{
	register struct partition_info *pptr, *parts;
	int	i;

	/*
	 * Lock out interrupts so the lists don't get mangled.
	 */
	enter_critical();
	/*
	 * Get space for for the new map and link it into the list
	 * of maps for the current disk type.
	 */
	pptr = (struct partition_info *)zalloc(sizeof (struct partition_info));
	parts = cur_dtype->dtype_plist;
	if (parts == NULL) {
		cur_dtype->dtype_plist = pptr;
	} else {
		while (parts->pinfo_next != NULL) {
			parts = parts->pinfo_next;
		}
		parts->pinfo_next = pptr;
		pptr->pinfo_next = NULL;
	}
	/*
	 * If there was a current map, copy its values.
	 */
	if (cur_label == L_TYPE_EFI) {
		struct dk_gpt	*map;
		int		nparts;
		int		size;

		nparts = cur_parts->etoc->efi_nparts;
		size = sizeof (struct dk_part) * nparts +
		    sizeof (struct dk_gpt);
		map = zalloc(size);
		(void) memcpy(map, cur_parts->etoc, size);
		pptr->etoc = map;
		cur_disk->disk_parts = cur_parts = pptr;
		exit_critical();
		return;
	}
	if (cur_parts != NULL) {
		for (i = 0; i < NDKMAP; i++) {
			pptr->pinfo_map[i] = cur_parts->pinfo_map[i];
		}
		pptr->vtoc = cur_parts->vtoc;
	} else {
		/*
		 * Otherwise set initial default vtoc values
		 */
		set_vtoc_defaults(pptr);
	}

	/*
	 * Make the new one current.
	 */
	cur_disk->disk_parts = cur_parts = pptr;
	exit_critical();
}


/*
 * This routine deletes a partition map from the list of maps for
 * the given disk type.
 */
void
delete_partition(struct partition_info *parts)
{
	struct	partition_info *pptr;

	/*
	 * If there isn't a current map, it's an error.
	 */
	if (cur_dtype->dtype_plist == NULL) {
		err_print("Error: unexpected null partition list.\n");
		fullabort();
	}
	/*
	 * Remove the map from the list.
	 */
	if (cur_dtype->dtype_plist == parts)
		cur_dtype->dtype_plist = parts->pinfo_next;
	else {
		for (pptr = cur_dtype->dtype_plist; pptr->pinfo_next != parts;
		    pptr = pptr->pinfo_next)
			;
		pptr->pinfo_next = parts->pinfo_next;
	}
	/*
	 * Free the space it was using.
	 */
	destroy_data((char *)parts);
}


/*
 * Set all partition vtoc fields to defaults
 */
void
set_vtoc_defaults(struct partition_info *part)
{
	int	i;

	bzero((caddr_t)&part->vtoc, sizeof (struct dk_vtoc));

	part->vtoc.v_version = V_VERSION;
	part->vtoc.v_nparts = NDKMAP;
	part->vtoc.v_sanity = VTOC_SANE;

	for (i = 0; i < NDKMAP; i++) {
		part->vtoc.v_part[i].p_tag = default_vtoc_map[i].p_tag;
		part->vtoc.v_part[i].p_flag = default_vtoc_map[i].p_flag;
	}
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright (c) 1991-2001 by Sun Microsystems, Inc.
 */

#ifndef	_PARTITION_H
#define	_PARTITION_H

#ifdef	__cplusplus
extern "C" {
#endif

/*
 * Mnemonics for the partitions we recognize
 */
#define	A_PARTITION		0
#define	B_PARTITION		1
#define	C_PARTITION		2
#define	D_PARTITION		3
#define	E_PARTITION		4
#define	F_PARTITION		5
#define	G_PARTITION		6
#define	H_PARTITION		7

#if defined(i386)
/*
 * the boot and alts slices only exist in the x86 disk layout.
 */
#define	I_PARTITION		8
#define	J_PARTITION		9
#endif		/* defined(i386) */

/*
 *	Prototypes for ANSI C compilers
 */
void	change_partition(int num);
int	get_partition(void);
void	make_partition(void);
void	delete_partition(struct partition_info *parts);
void	set_vtoc_defaults(struct partition_info	*part);


extern	struct dk_map2	default_vtoc_map[NDKMAP];

#ifdef	__cplusplus
}
#endif

#endif	/* _PARTITION_H */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * This file contains functions to prompt the user for various
 * disk characteristics.  By isolating these into functions,
 * we can guarantee that prompts, defaults, etc are identical.
 */
#include "global.h"
#include "prompts.h"
#include "io.h"
#include "param.h"
#include "startup.h"

#ifdef sparc
#include <sys/hdio.h>
#endif


/*
 * Prompt for max number of LBA
 */
uint64_t
get_mlba(void)
{
	u_ioparam_t	ioparam;

	ioparam.io_bounds.lower = (1024 * 16) + 68;
	ioparam.io_bounds.upper = UINT_MAX64;

	return (input(FIO_INT64, "Enter maximum number of LBAs",
	    ':', &ioparam, NULL, DATA_INPUT));
}

/*
 * Prompt for number of cylinders
 */
int
get_ncyl(void)
{
	u_ioparam_t	ioparam;

	ioparam.io_bounds.lower = 1;
	ioparam.io_bounds.upper = MAX_CYLS;
	return (input(FIO_INT, "Enter number of data cylinders",
	    ':', &ioparam, NULL, DATA_INPUT));
}

/*
 * Prompt for number of alternate cylinders
 */
int
get_acyl(int n_cyls)
{
	u_ioparam_t	ioparam;
	int		deflt;

	ioparam.io_bounds.lower = 2;
	ioparam.io_bounds.upper = MAX_CYLS - n_cyls;
	deflt = 2;
	return (input(FIO_INT, "Enter number of alternate cylinders", ':',
	    &ioparam, &deflt, DATA_INPUT));
}

/*
 * Prompt for number of physical cylinders
 */
int
get_pcyl(int n_cyls, int a_cyls)
{
	u_ioparam_t	ioparam;
	int		deflt;

	ioparam.io_bounds.lower = n_cyls + a_cyls;
	ioparam.io_bounds.upper = MAX_CYLS;
	deflt = n_cyls + a_cyls;
	return (input(FIO_INT, "Enter number of physical cylinders", ':',
	    &ioparam, &deflt, DATA_INPUT));
}

/*
 * Prompt for number of heads
 */
int
get_nhead(void)
{
	u_ioparam_t	ioparam;

	ioparam.io_bounds.lower = 1;
	ioparam.io_bounds.upper = MAX_HEADS;
	return (input(FIO_INT, "Enter number of heads", ':',
	    &ioparam, NULL, DATA_INPUT));
}

/*
 * Prompt for number of physical heads
 */
int
get_phead(int n_heads, ulong_t *options)
{
	u_ioparam_t	ioparam;
	int		deflt;

	if (SCSI) {
		ioparam.io_bounds.lower = n_heads;
		ioparam.io_bounds.upper = INFINITY;
		if (input(FIO_OPINT, "Enter physical number of heads",
		    ':', &ioparam, &deflt, DATA_INPUT)) {
			*options |= SUP_PHEAD;
			return (deflt);
		}
	}
	return (0);
}


/*
 * Prompt for number of sectors per track
 */
int
get_nsect(void)
{
	u_ioparam_t	ioparam;

	ioparam.io_bounds.lower = 1;
	ioparam.io_bounds.upper = MAX_SECTS;
	return (input(FIO_INT,
	    "Enter number of data sectors/track", ':',
	    &ioparam, NULL, DATA_INPUT));
}

/*
 * Prompt for number of physical sectors per track
 */
int
get_psect(ulong_t *options)
{
	u_ioparam_t	ioparam;
	int		deflt;

	if (SCSI) {
		ioparam.io_bounds.lower = 0;
		ioparam.io_bounds.upper = INFINITY;
		if (input(FIO_OPINT, "Enter number of physical sectors/track",
		    ':', &ioparam, &deflt, DATA_INPUT)) {
			*options |= SUP_PSECT;
			return (deflt);
		}
	}
	return (0);
}

/*
 * Prompt for bytes per track
 */
int
get_bpt(int n_sects, ulong_t *options)
{
	u_ioparam_t	ioparam;
	int		deflt;

	if (SMD) {
		*options |= SUP_BPT;
		ioparam.io_bounds.lower = 1;
		ioparam.io_bounds.upper = INFINITY;
		deflt = n_sects * cur_blksz;
		return (input(FIO_INT, "Enter number of bytes/track",
		    ':', &ioparam, &deflt, DATA_INPUT));
	}

	return (0);
}

/*
 * Prompt for rpm
 */
int
get_rpm(void)
{
	u_ioparam_t	ioparam;
	int		deflt;

	ioparam.io_bounds.lower = MIN_RPM;
	ioparam.io_bounds.upper = MAX_RPM;
	deflt = AVG_RPM;
	return (input(FIO_INT, "Enter rpm of drive", ':',
	    &ioparam, &deflt, DATA_INPUT));
}

/*
 * Prompt for formatting time
 */
int
get_fmt_time(ulong_t *options)
{
	u_ioparam_t	ioparam;
	int		deflt;

	ioparam.io_bounds.lower = 0;
	ioparam.io_bounds.upper = INFINITY;
	if (input(FIO_OPINT, "Enter format time", ':',
	    &ioparam, &deflt, DATA_INPUT)) {
		*options |= SUP_FMTTIME;
		return (deflt);
	}
	return (0);
}

/*
 * Prompt for cylinder skew
 */
int
get_cyl_skew(ulong_t *options)
{
	u_ioparam_t	ioparam;
	int		deflt;

	ioparam.io_bounds.lower = 0;
	ioparam.io_bounds.upper = INFINITY;
	if (input(FIO_OPINT, "Enter cylinder skew", ':',
	    &ioparam, &deflt, DATA_INPUT)) {
		*options |= SUP_CYLSKEW;
		return (deflt);
	}
	return (0);
}

/*
 * Prompt for track skew
 */
int
get_trk_skew(ulong_t *options)
{
	u_ioparam_t	ioparam;
	int		deflt;

	ioparam.io_bounds.lower = 0;
	ioparam.io_bounds.upper = INFINITY;
	if (input(FIO_OPINT, "Enter track skew", ':',
	    &ioparam, &deflt, DATA_INPUT)) {
		*options |= SUP_TRKSKEW;
		return (deflt);
	}
	return (0);
}

/*
 * Prompt for tracks per zone
 */
int
get_trks_zone(ulong_t *options)
{
	u_ioparam_t	ioparam;
	int		deflt;

	ioparam.io_bounds.lower = 0;
	ioparam.io_bounds.upper = INFINITY;
	if (input(FIO_OPINT, "Enter tracks per zone", ':',
	    &ioparam, &deflt, DATA_INPUT)) {
		*options |= SUP_TRKS_ZONE;
		return (deflt);
	}
	return (0);
}

/*
 * Prompt for alternate tracks
 */
int
get_atrks(ulong_t *options)
{
	u_ioparam_t	ioparam;
	int		deflt;

	ioparam.io_bounds.lower = 0;
	ioparam.io_bounds.upper = INFINITY;
	if (input(FIO_OPINT, "Enter alternate tracks", ':',
	    &ioparam, &deflt, DATA_INPUT)) {
		*options |= SUP_ATRKS;
		return (deflt);
	}
	return (0);
}

/*
 * Prompt for alternate sectors
 */
int
get_asect(ulong_t *options)
{
	u_ioparam_t	ioparam;
	int		deflt;

	ioparam.io_bounds.lower = 0;
	ioparam.io_bounds.upper = INFINITY;
	if (input(FIO_OPINT, "Enter alternate sectors", ':',
	    &ioparam, &deflt, DATA_INPUT)) {
		*options |= SUP_ASECT;
		return (deflt);
	}
	return (0);
}

/*
 * Prompt for cache setting
 */
int
get_cache(ulong_t *options)
{
	u_ioparam_t	ioparam;
	int		deflt;

	ioparam.io_bounds.lower = 0;
	ioparam.io_bounds.upper = 0xff;
	if (input(FIO_OPINT, "Enter cache control", ':',
	    &ioparam, &deflt, DATA_INPUT)) {
		*options |= SUP_CACHE;
		return (deflt);
	}
	return (0);
}

/*
 * Prompt for prefetch threshold
 */
int
get_threshold(ulong_t *options)
{
	u_ioparam_t	ioparam;
	int		deflt;

	ioparam.io_bounds.lower = 0;
	ioparam.io_bounds.upper = INFINITY;
	if (input(FIO_OPINT, "Enter prefetch threshold",
	    ':', &ioparam, &deflt, DATA_INPUT)) {
		*options |= SUP_PREFETCH;
		return (deflt);
	}
	return (0);
}

/*
 * Prompt for minimum prefetch
 */
int
get_min_prefetch(ulong_t *options)
{
	u_ioparam_t	ioparam;
	int		deflt;

	ioparam.io_bounds.lower = 0;
	ioparam.io_bounds.upper = INFINITY;
	if (input(FIO_OPINT, "Enter minimum prefetch",
	    ':', &ioparam, &deflt, DATA_INPUT)) {
		*options |= SUP_CACHE_MIN;
		return (deflt);
	}
	return (0);
}

/*
 * Prompt for maximum prefetch
 */
int
get_max_prefetch(int min_prefetch, ulong_t *options)
{
	u_ioparam_t	ioparam;
	int		deflt;

	ioparam.io_bounds.lower = min_prefetch;
	ioparam.io_bounds.upper = INFINITY;
	if (input(FIO_OPINT, "Enter maximum prefetch",
	    ':', &ioparam, &deflt, DATA_INPUT)) {
		*options |= SUP_CACHE_MAX;
		return (deflt);
	}
	return (0);
}

/*
 * Prompt for bytes per sector
 */
int
get_bps(void)
{
	u_ioparam_t	ioparam;
	int		deflt;

	if (cur_ctype->ctype_flags & CF_SMD_DEFS) {
		ioparam.io_bounds.lower = MIN_BPS;
		ioparam.io_bounds.upper = MAX_BPS;
		deflt = AVG_BPS;
		return (input(FIO_INT, "Enter bytes per sector",
		    ':', &ioparam, &deflt, DATA_INPUT));
	}

	return (0);
}

/*
 * Prompt for ascii label
 */
char *
get_asciilabel(void)
{
	return ((char *)(uintptr_t)input(FIO_OSTR,
	    "Enter disk type name (remember quotes)", ':',
	    NULL, NULL, DATA_INPUT));
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 1991-2002 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef	_PROMPTS_H
#define	_PROMPTS_H

#ifdef	__cplusplus
extern "C" {
#endif


int	get_ncyl(void);
uint64_t	get_mlba(void);
int	get_acyl(int n_cyls);
int	get_pcyl(int n_cyls, int p_cyls);
int	get_nhead(void);
int	get_phead(int n_heads, ulong_t *option);
int	get_nsect(void);
int	get_psect(ulong_t *option);
int	get_bpt(int n_sects, ulong_t *option);
int	get_rpm(void);
int	get_fmt_time(ulong_t *option);
int	get_cyl_skew(ulong_t *option);
int	get_trk_skew(ulong_t *option);
int	get_trks_zone(ulong_t *option);
int	get_atrks(ulong_t *option);
int	get_asect(ulong_t *option);
int	get_cache(ulong_t *option);
int	get_threshold(ulong_t *option);
int	get_min_prefetch(ulong_t *option);
int	get_max_prefetch(int min_prefetch, ulong_t *option);
int	get_bps(void);
char	*get_asciilabel(void);

#ifdef	__cplusplus
}
#endif

#endif	/* _PROMPTS_H */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright (c) 1991-2001 by Sun Microsystems, Inc.
 */

#ifndef	_SCSI_COM_H
#define	_SCSI_COM_H

#ifdef	__cplusplus
extern "C" {
#endif

/*
 * Common definitions for SCSI routines.
 */

/*
 * Possible error levels.
 */
#define	ERRLVL_COR	1	/* corrected error */
#define	ERRLVL_RETRY	2	/* retryable error */
#define	ERRLVL_FAULT	3	/* drive faulted */
#define	ERRLVL_FATAL	4	/* fatal error */

#ifdef	__cplusplus
}
#endif

#endif	/* _SCSI_COM_H */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2015 Nexenta Systems, Inc.  All rights reserved.
 *
 * Copyright (c) 2011 Gary Mills
 *
 * Copyright (c) 1993, 2010, Oracle and/or its affiliates. All rights reserved.
 */

/*
 * This file contains the code to perform program startup.  This
 * includes reading the data file and the search for disks.
 */
#include "global.h"

#include <ctype.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <strings.h>
#include <fcntl.h>
#include <errno.h>
#include <memory.h>
#include <dirent.h>
#include <sys/fcntl.h>
#include <sys/param.h>
#include <sys/stat.h>

#include "startup.h"
#include "param.h"
#include "label.h"
#include "misc.h"
#include "menu_command.h"
#include "partition.h"
#include "ctlr_scsi.h"

#include "auto_sense.h"

extern	struct	ctlr_type ctlr_types[];
extern	int	nctypes;
extern	struct	ctlr_ops	genericops;
extern	long	strtol();

extern	int	errno;

char	*file_name;
char	*option_d;
char	*option_f;
char	*option_l;
char	*option_p;
char	option_s;
char	*option_t;
char	*option_x;
char	diag_msg;
char	option_msg;
int	need_newline;
int	dev_expert;
int	expert_mode;
uint_t	cur_blksz;
struct ctlr_info	*ctlr_list;
struct disk_info	*disk_list;
struct mctlr_list	*controlp;
char	x86_devname[MAXNAMELEN];
FILE	*data_file;

#ifdef __STDC__

/* Function prototypes for ANSI C Compilers */
static void	usage(void);
static int	sup_prxfile(void);
static void	sup_setpath(void);
static void	sup_setdtype(void);
static int	sup_change_spec(struct disk_type *, char *);
static void	sup_setpart(void);
static void	search_for_logical_dev(char *devname);
static void	add_device_to_disklist(char *devname, char *devpath);
static int	disk_is_known(struct dk_cinfo *dkinfo);
static void	datafile_error(char *errmsg, char *token);
static void	search_duplicate_dtypes(void);
static void	search_duplicate_pinfo(void);
static void	check_dtypes_for_inconsistency(struct disk_type *dp1,
		struct disk_type *dp2);
static void	check_pinfo_for_inconsistency(struct partition_info *pp1,
		struct partition_info *pp2);
static uint_t	str2blks(char *str);
static int	str2cyls(char *str);
static struct	chg_list *new_chg_list(struct disk_type *);
static char	*get_physical_name(char *);
static void	sort_disk_list(void);
static int	disk_name_compare(const void *, const void *);
static void	make_controller_list(void);
static void	check_for_duplicate_disknames(char *arglist[]);

#else	/* __STDC__ */

/* Function prototypes for non-ANSI C Compilers */
static void	usage();
static int	sup_prxfile();
static void	sup_setpath();
static void	sup_setdtype();
static int	sup_change_spec();
static void	sup_setpart();
static void	search_for_logical_dev();
static void	add_device_to_disklist();
static int	disk_is_known();
static void	datafile_error();
static void	search_duplicate_dtypes();
static void	search_duplicate_pinfo();
static void	check_dtypes_for_inconsistency();
static void	check_pinfo_for_inconsistency();
static uint_t	str2blks();
static int	str2cyls();
static struct	chg_list *new_chg_list();
static char	*get_physical_name();
static void	sort_disk_list();
static int	disk_name_compare();
static void	make_controller_list();
static void	check_for_duplicate_disknames();

#endif	/* __STDC__ */

#if defined(sparc)
static char *other_ctlrs[] = {
	"ata"
	};
#define	OTHER_CTLRS 1

#elif defined(i386) || defined(__amd64)
static char *other_ctlrs[] = {
	"ISP-80"
	};
#define	OTHER_CTLRS 2

#else
#error No Platform defined.
#endif


/*
 * This global is used to store the current line # in the data file.
 * It must be global because the I/O routines are allowed to side
 * effect it to keep track of backslashed newlines.
 */
int	data_lineno;			/* current line # in data file */

/*
 * Search path as defined in the format.dat files
 */
static char	**search_path = NULL;


static int name_represents_wholedisk(char *name);

static void get_disk_name(int fd, char *disk_name, struct disk_info *disk_info);

/*
 * This routine digests the options on the command line.  It returns
 * the index into argv of the first string that is not an option.  If
 * there are none, it returns -1.
 */
int
do_options(int argc, char *argv[])
{
	char	*ptr;
	int	i;
	int	next;

	/*
	 * Default is no extended messages.  Can be enabled manually.
	 */
	option_msg = 0;
	diag_msg = 0;
	expert_mode = 0;
	need_newline = 0;
	dev_expert = 0;

	/*
	 * Loop through the argument list, incrementing each time by
	 * an amount determined by the options found.
	 */
	for (i = 1; i < argc; i = next) {
		/*
		 * Start out assuming an increment of 1.
		 */
		next = i + 1;
		/*
		 * As soon as we hit a non-option, we're done.
		 */
		if (*argv[i] != '-')
			return (i);
		/*
		 * Loop through all the characters in this option string.
		 */
		for (ptr = argv[i] + 1; *ptr != '\0'; ptr++) {
			/*
			 * Determine each option represented.  For options
			 * that use a second string, increase the increment
			 * of the main loop so they aren't re-interpreted.
			 */
			switch (*ptr) {
			case 's':
			case 'S':
				option_s = 1;
				break;
			case 'f':
			case 'F':
				option_f = argv[next++];
				if (next > argc)
					goto badopt;
				break;
			case 'l':
			case 'L':
				option_l = argv[next++];
				if (next > argc)
					goto badopt;
				break;
			case 'x':
			case 'X':
				option_x = argv[next++];
				if (next > argc)
					goto badopt;
				break;
			case 'd':
			case 'D':
				option_d = argv[next++];
				if (next > argc)
					goto badopt;
				break;
			case 't':
			case 'T':
				option_t = argv[next++];
				if (next > argc)
					goto badopt;
				break;
			case 'p':
			case 'P':
				option_p = argv[next++];
				if (next > argc)
					goto badopt;
				break;
			case 'm':
				option_msg = 1;
				break;
			case 'M':
				option_msg = 1;
				diag_msg = 1;
				break;
			case 'e':
				expert_mode = 1;
				break;
#ifdef DEBUG
			case 'z':
				dev_expert = 1;
				break;
#endif
			default:
badopt:
				usage();
				break;
			}
		}
	}
	/*
	 * All the command line strings were options.  Return that fact.
	 */
	return (-1);
}


static void
usage(void)
{
	err_print("Usage:  format [-s][-d disk_name]");
	err_print("[-t disk_type][-p partition_name]\n");
	err_print("\t[-f cmd_file][-l log_file]");
	err_print("[-x data_file] [-m] [-M] [-e] disk_list\n");
	fullabort();
}


/*
 * This routine reads in and digests the data file.  The data file contains
 * definitions for the search path, known disk types, and known partition
 * maps.
 *
 * Note: for each file being processed, file_name is a pointer to that
 * file's name.  We are careful to make sure that file_name points to
 * globally-accessible data, not data on the stack, because each
 * disk/partition/controller definition now keeps a pointer to the
 * filename in which it was defined.  In the case of duplicate,
 * conflicting definitions, we can thus tell the user exactly where
 * the problem is occurring.
 */
void
sup_init(void)
{
	int		nopened_files = 0;
	char		fname[MAXPATHLEN];
	char		*path;
	char		*p;
	struct stat	stbuf;


	/*
	 * Create a singly-linked list of controller types so that we may
	 * dynamically add unknown controllers to this for 3'rd
	 * party disk support.
	 */

	make_controller_list();

	/*
	 * If a data file was specified on the command line, use it first
	 * If the file cannot be opened, fail.  We want to guarantee
	 * that, if the user explicitly names a file, they can
	 * access it.
	 *
	 * option_x is already global, no need to dup it on the heap.
	 */
	if (option_x) {
		file_name = option_x;
		if (sup_prxfile()) {
			nopened_files++;
		} else {
			err_print("Unable to open data file '%s' - %s.\n",
			    file_name, strerror(errno));
			fullabort();
		}
	}

	/*
	 * Now look for an environment variable FORMAT_PATH.
	 * If found, we use it as a colon-separated list
	 * of directories.  If no such environment variable
	 * is defined, use a default path of "/etc".
	 */
	path = getenv("FORMAT_PATH");
	if (path == NULL) {
		path = "/etc";
	}
	/*
	 * Traverse the path one file at a time.  Pick off
	 * the file name, and append the name "format.dat"
	 * at the end of the pathname.
	 * Whatever string we construct, duplicate it on the
	 * heap, so that file_name is globally accessible.
	 */
	while (*path != 0) {
		p = fname;
		while (*path != 0 && *path != ':')
			*p++ = *path++;
		if (p == fname)
			continue;
		*p = 0;
		if (*path == ':')
			path++;
		/*
		 * If the path we have so far is a directory,
		 * look for a format.dat file in that directory,
		 * otherwise try using the path name specified.
		 * This permits arbitrary file names in the
		 * path specification, if this proves useful.
		 */
		if (stat(fname, &stbuf) == -1) {
			err_print("Unable to access '%s' - %s.\n",
			    fname, strerror(errno));
		} else {
			if (S_ISDIR(stbuf.st_mode)) {
				if (*(p-1) != '/')
					*p++ = '/';
				(void) strcpy(p, "format.dat");
			}
			file_name = alloc_string(fname);
			if (sup_prxfile()) {
				nopened_files++;
			}
		}
	}

	/*
	 * Check for duplicate disk or partitions definitions
	 * that are inconsistent - this would be very confusing.
	 */
	search_duplicate_dtypes();
	search_duplicate_pinfo();
}


/*
 * Open and process a format data file.  Unfortunately, we use
 * globals: file_name for the file name, and data_file
 * for the descriptor.  Return true if able to open the file.
 */
static int
sup_prxfile(void)
{
	int	status;
	TOKEN	token;
	TOKEN	cleaned;

	/*
	 * Open the data file.  Return 0 if unable to do so.
	 */
	data_file = fopen(file_name, "r");
	if (data_file == NULL) {
		return (0);
	}
	/*
	 * Step through the data file a meta-line at a time.  There are
	 * typically several backslashed newlines in each meta-line,
	 * so data_lineno will be getting side effected along the way.
	 */
	data_lineno = 0;
	for (;;) {
		data_lineno++;
		/*
		 * Get the keyword.
		 */
		status = sup_gettoken(token);
		/*
		 * If we hit the end of the data file, we're done.
		 */
		if (status == SUP_EOF)
			break;
		/*
		 * If the line is blank, skip it.
		 */
		if (status == SUP_EOL)
			continue;
		/*
		 * If the line starts with some key character, it's an error.
		 */
		if (status != SUP_STRING) {
			datafile_error("Expecting keyword, found '%s'", token);
			continue;
		}
		/*
		 * Clean up the token and see which keyword it is.  Call
		 * the appropriate routine to process the rest of the line.
		 */
		clean_token(cleaned, token);
		if (strcmp(cleaned, "search_path") == 0)
			sup_setpath();
		else if (strcmp(cleaned, "disk_type") == 0)
			sup_setdtype();
		else if (strcmp(cleaned, "partition") == 0)
			sup_setpart();
		else {
			datafile_error("Unknown keyword '%s'", cleaned);
		}
	}
	/*
	 * Close the data file.
	 */
	(void) fclose(data_file);

	return (1);
}

/*
 * This routine processes a 'search_path' line in the data file.  The
 * search path is a list of disk names that will be searched for by the
 * program.
 *
 * The static path_size and path_alloc are used to build up the
 * list of files comprising the search path.  The static definitions
 * enable supporting multiple search path definitions.
 */
static void
sup_setpath(void)
{
	TOKEN		token;
	TOKEN		cleaned;
	int		status;
	static int	path_size;
	static int	path_alloc;

	/*
	 * Pull in some grammar.
	 */
	status = sup_gettoken(token);
	if (status != SUP_EQL) {
		datafile_error("Expecting '=', found '%s'", token);
		return;
	}
	/*
	 * Loop through the entries.
	 */
	for (;;) {
		/*
		 * Pull in the disk name.
		 */
		status = sup_gettoken(token);
		/*
		 * If we hit end of line, we're done.
		 */
		if (status == SUP_EOL)
			break;
		/*
		 * If we hit some key character, it's an error.
		 */
		if (status != SUP_STRING) {
			datafile_error("Expecting value, found '%s'", token);
			break;
		}
		clean_token(cleaned, token);
		/*
		 * Build the string into an argvlist.  This array
		 * is dynamically sized, as necessary, and terminated
		 * with a null.  Each name is alloc'ed on the heap,
		 * so no dangling references.
		 */
		search_path = build_argvlist(search_path, &path_size,
		    &path_alloc, cleaned);
		/*
		 * Pull in some grammar.
		 */
		status = sup_gettoken(token);
		if (status == SUP_EOL)
			break;
		if (status != SUP_COMMA) {
			datafile_error("Expecting ', ', found '%s'", token);
			break;
		}
	}
}

/*
 * This routine processes a 'disk_type' line in the data file.  It defines
 * the physical attributes of a brand of disk when connected to a specific
 * controller type.
 */
static void
sup_setdtype(void)
{
	TOKEN	token, cleaned, ident;
	int	val, status, i;
	ulong_t	flags = 0;
	struct	disk_type *dtype, *type;
	struct	ctlr_type *ctype;
	char	*dtype_name, *ptr;
	struct	mctlr_list	*mlp;

	/*
	 * Pull in some grammar.
	 */
	status = sup_gettoken(token);
	if (status != SUP_EQL) {
		datafile_error("Expecting '=', found '%s'", token);
		return;
	}
	/*
	 * Pull in the name of the disk type.
	 */
	status = sup_gettoken(token);
	if (status != SUP_STRING) {
		datafile_error("Expecting value, found '%s'", token);
		return;
	}
	clean_token(cleaned, token);
	/*
	 * Allocate space for the disk type and copy in the name.
	 */
	dtype_name = (char *)zalloc(strlen(cleaned) + 1);
	(void) strcpy(dtype_name, cleaned);
	dtype = (struct disk_type *)zalloc(sizeof (struct disk_type));
	dtype->dtype_asciilabel = dtype_name;
	/*
	 * Save the filename/linenumber where this disk was defined
	 */
	dtype->dtype_filename = file_name;
	dtype->dtype_lineno = data_lineno;
	/*
	 * Loop for each attribute.
	 */
	for (;;) {
		/*
		 * Pull in some grammar.
		 */
		status = sup_gettoken(token);
		/*
		 * If we hit end of line, we're done.
		 */
		if (status == SUP_EOL)
			break;
		if (status != SUP_COLON) {
			datafile_error("Expecting ':', found '%s'", token);
			return;
		}
		/*
		 * Pull in the attribute.
		 */
		status = sup_gettoken(token);
		/*
		 * If we hit end of line, we're done.
		 */
		if (status == SUP_EOL)
			break;
		/*
		 * If we hit a key character, it's an error.
		 */
		if (status != SUP_STRING) {
			datafile_error("Expecting keyword, found '%s'", token);
			return;
		}
		clean_token(ident, token);
		/*
		 * Check to see if we've got a change specification
		 * If so, this routine will parse the entire
		 * specification, so just restart at top of loop
		 */
		if (sup_change_spec(dtype, ident)) {
			continue;
		}
		/*
		 * Pull in more grammar.
		 */
		status = sup_gettoken(token);
		if (status != SUP_EQL) {
			datafile_error("Expecting '=', found '%s'", token);
			return;
		}
		/*
		 * Pull in the value of the attribute.
		 */
		status = sup_gettoken(token);
		if (status != SUP_STRING) {
			datafile_error("Expecting value, found '%s'", token);
			return;
		}
		clean_token(cleaned, token);
		/*
		 * If the attribute defined the ctlr...
		 */
		if (strcmp(ident, "ctlr") == 0) {
			/*
			 * Match the value with a ctlr type.
			 */
			mlp = controlp;

			while (mlp != NULL) {
				if (strcmp(mlp->ctlr_type->ctype_name,
				    cleaned) == 0)
					break;
				mlp = mlp->next;
			}
			/*
			 * If we couldn't match it, it's an error.
			 */
			if (mlp == NULL) {
				for (i = 0; i < OTHER_CTLRS; i++) {
					if (strcmp(other_ctlrs[i], cleaned)
					    == 0) {
						datafile_error(NULL, NULL);
						return;
					}
				}
				if (i == OTHER_CTLRS) {
					datafile_error(
					    "Unknown controller '%s'",
					    cleaned);
					return;
				}
			}
			/*
			 * Found a match.  Add this disk type to the list
			 * for the ctlr type if we can complete the
			 * disk specification correctly.
			 */
			ctype = mlp->ctlr_type;
			flags |= SUP_CTLR;
			continue;
		}
		/*
		 * All other attributes require a numeric value.  Convert
		 * the value to a number.
		 */
		val = (int)strtol(cleaned, &ptr, 0);
		if (*ptr != '\0') {
			datafile_error("Expecting an integer, found '%s'",
			    cleaned);
			return;
		}
		/*
		 * Figure out which attribute it was and fill in the
		 * appropriate value.  Also note that the attribute
		 * has been defined.
		 */
		if (strcmp(ident, "ncyl") == 0) {
			dtype->dtype_ncyl = val;
			flags |= SUP_NCYL;
		} else if (strcmp(ident, "acyl") == 0) {
			dtype->dtype_acyl = val;
			flags |= SUP_ACYL;
		} else if (strcmp(ident, "pcyl") == 0) {
			dtype->dtype_pcyl = val;
			flags |= SUP_PCYL;
		} else if (strcmp(ident, "nhead") == 0) {
			dtype->dtype_nhead = val;
			flags |= SUP_NHEAD;
		} else if (strcmp(ident, "nsect") == 0) {
			dtype->dtype_nsect = val;
			flags |= SUP_NSECT;
		} else if (strcmp(ident, "rpm") == 0) {
			dtype->dtype_rpm = val;
			flags |= SUP_RPM;
		} else if (strcmp(ident, "bpt") == 0) {
			dtype->dtype_bpt = val;
			flags |= SUP_BPT;
		} else if (strcmp(ident, "bps") == 0) {
			dtype->dtype_bps = val;
			flags |= SUP_BPS;
		} else if (strcmp(ident, "drive_type") == 0) {
			dtype->dtype_dr_type = val;
			flags |= SUP_DRTYPE;
		} else if (strcmp(ident, "cache") == 0) {
			dtype->dtype_cache = val;
			flags |= SUP_CACHE;
		} else if (strcmp(ident, "prefetch") == 0) {
			dtype->dtype_threshold = val;
			flags |= SUP_PREFETCH;
		} else if (strcmp(ident, "read_retries") == 0) {
			dtype->dtype_read_retries = val;
			flags |= SUP_READ_RETRIES;
		} else if (strcmp(ident, "write_retries") == 0) {
			dtype->dtype_write_retries = val;
			flags |= SUP_WRITE_RETRIES;
		} else if (strcmp(ident, "min_prefetch") == 0) {
			dtype->dtype_prefetch_min = val;
			flags |= SUP_CACHE_MIN;
		} else if (strcmp(ident, "max_prefetch") == 0) {
			dtype->dtype_prefetch_max = val;
			flags |= SUP_CACHE_MAX;
		} else if (strcmp(ident, "trks_zone") == 0) {
			dtype->dtype_trks_zone = val;
			flags |= SUP_TRKS_ZONE;
		} else if (strcmp(ident, "atrks") == 0) {
			dtype->dtype_atrks = val;
			flags |= SUP_ATRKS;
		} else if (strcmp(ident, "asect") == 0) {
			dtype->dtype_asect = val;
			flags |= SUP_ASECT;
		} else if (strcmp(ident, "psect") == 0) {
			dtype->dtype_psect = val;
			flags |= SUP_PSECT;
		} else if (strcmp(ident, "phead") == 0) {
			dtype->dtype_phead = val;
			flags |= SUP_PHEAD;
		} else if (strcmp(ident, "fmt_time") == 0) {
			dtype->dtype_fmt_time = val;
			flags |= SUP_FMTTIME;
		} else if (strcmp(ident, "cyl_skew") == 0) {
			dtype->dtype_cyl_skew = val;
			flags |= SUP_CYLSKEW;
		} else if (strcmp(ident, "trk_skew") == 0) {
			dtype->dtype_trk_skew = val;
			flags |= SUP_TRKSKEW;
		} else {
			datafile_error("Unknown keyword '%s'", ident);
		}
	}
	/*
	 * Check to be sure all the necessary attributes have been defined.
	 * If any are missing, it's an error.  Also, log options for later
	 * use by specific driver.
	 */
	dtype->dtype_options = flags;
	if ((flags & SUP_MIN_DRIVE) != SUP_MIN_DRIVE) {
		datafile_error("Incomplete specification", "");
		return;
	}
	if ((!(ctype->ctype_flags & CF_SCSI)) && (!(flags & SUP_BPT)) &&
	    (!(ctype->ctype_flags & CF_NOFORMAT))) {
		datafile_error("Incomplete specification", "");
		return;
	}
	if ((ctype->ctype_flags & CF_SMD_DEFS) && (!(flags & SUP_BPS))) {
		datafile_error("Incomplete specification", "");
		return;
	}
	/*
	 * Add this disk type to the list for the ctlr type
	 */
	assert(flags & SUP_CTLR);
	type = ctype->ctype_dlist;
	if (type == NULL) {
		ctype->ctype_dlist = dtype;
	} else {
		while (type->dtype_next != NULL)
			type = type->dtype_next;
		type->dtype_next = dtype;
	}
}


/*
 * Parse a SCSI mode page change specification.
 *
 * Return:
 *		0:  not change specification, continue parsing
 *		1:  was change specification, it was ok,
 *		    or we already handled the error.
 */
static int
sup_change_spec(struct disk_type *disk, char *id)
{
	char		*p;
	char		*p2;
	int		pageno;
	int		byteno;
	int		mode;
	int		value;
	TOKEN		token;
	TOKEN		ident;
	struct chg_list	*cp;
	int		tilde;
	int		i;

	/*
	 * Syntax: p[<nn>|0x<xx>]
	 */
	if (*id != 'p') {
		return (0);
	}
	pageno = (int)strtol(id+1, &p2, 0);
	if (*p2 != 0) {
		return (0);
	}
	/*
	 * Once we get this far, we know we have the
	 * beginnings of a change specification.
	 * If there's a problem now, report the problem,
	 * and return 1, so that the caller can restart
	 * parsing at the next expression.
	 */
	if (!scsi_supported_page(pageno)) {
		datafile_error("Unsupported mode page '%s'", id);
		return (1);
	}
	/*
	 * Next token should be the byte offset
	 */
	if (sup_gettoken(token) != SUP_STRING) {
		datafile_error("Unexpected value '%s'", token);
		return (1);
	}
	clean_token(ident, token);

	/*
	 * Syntax: b[<nn>|0x<xx>]
	 */
	p = ident;
	if (*p++ != 'b') {
		datafile_error("Unknown keyword '%s'", ident);
		return (1);
	}
	byteno = (int)strtol(p, &p2, 10);
	if (*p2 != 0) {
		datafile_error("Unknown keyword '%s'", ident);
		return (1);
	}
	if (byteno == 0 || byteno == 1) {
		datafile_error("Unsupported byte offset '%s'", ident);
		return (1);
	}

	/*
	 * Get the operator for this expression
	 */
	mode = CHG_MODE_UNDEFINED;
	switch (sup_gettoken(token)) {
	case SUP_EQL:
		mode = CHG_MODE_ABS;
		break;
	case SUP_OR:
		if (sup_gettoken(token) == SUP_EQL)
			mode = CHG_MODE_SET;
		break;
	case SUP_AND:
		if (sup_gettoken(token) == SUP_EQL)
			mode = CHG_MODE_CLR;
		break;
	}
	if (mode == CHG_MODE_UNDEFINED) {
		datafile_error("Unexpected operator: '%s'", token);
		return (1);
	}

	/*
	 * Get right-hand of expression - accept optional tilde
	 */
	tilde = 0;
	if ((i = sup_gettoken(token)) == SUP_TILDE) {
		tilde = 1;
		i = sup_gettoken(token);
	}
	if (i != SUP_STRING) {
		datafile_error("Expecting value, found '%s'", token);
		return (1);
	}
	clean_token(ident, token);
	value = (int)strtol(ident, &p, 0);
	if (*p != 0) {
		datafile_error("Expecting value, found '%s'", token);
		return (1);
	}

	/*
	 * Apply the tilde operator, if found.
	 * Constrain to a byte value.
	 */
	if (tilde) {
		value = ~value;
	}
	value &= 0xff;

	/*
	 * We parsed a successful change specification expression.
	 * Add it to the list for this disk type.
	 */
	cp = new_chg_list(disk);
	cp->pageno = pageno;
	cp->byteno = byteno;
	cp->mode = mode;
	cp->value = value;
	return (1);
}


/*
 * This routine processes a 'partition' line in the data file.  It defines
 * a known partition map for a particular disk type on a particular
 * controller type.
 */
static void
sup_setpart(void)
{
	TOKEN	token, cleaned, disk, ctlr, ident;
	struct	disk_type *dtype = NULL;
	struct	ctlr_type *ctype = NULL;
	struct	partition_info *pinfo, *parts;
	char	*pinfo_name;
	int	i, index, status, flags = 0;
	uint_t	val1, val2;
	ushort_t	vtoc_tag;
	ushort_t	vtoc_flag;
	struct	mctlr_list	*mlp;

	/*
	 * Pull in some grammar.
	 */
	status = sup_gettoken(token);
	if (status != SUP_EQL) {
		datafile_error("Expecting '=', found '%s'", token);
		return;
	}
	/*
	 * Pull in the name of the map.
	 */
	status = sup_gettoken(token);
	if (status != SUP_STRING) {
		datafile_error("Expecting value, found '%s'", token);
		return;
	}
	clean_token(cleaned, token);
	/*
	 * Allocate space for the partition map and fill in the name.
	 */
	pinfo_name = (char *)zalloc(strlen(cleaned) + 1);
	(void) strcpy(pinfo_name, cleaned);
	pinfo = (struct partition_info *)zalloc(sizeof (struct partition_info));
	pinfo->pinfo_name = pinfo_name;
	/*
	 * Save the filename/linenumber where this partition was defined
	 */
	pinfo->pinfo_filename = file_name;
	pinfo->pinfo_lineno = data_lineno;

	/*
	 * Install default vtoc information into the new partition table
	 */
	set_vtoc_defaults(pinfo);

	/*
	 * Loop for each attribute in the line.
	 */
	for (;;) {
		/*
		 * Pull in some grammar.
		 */
		status = sup_gettoken(token);
		/*
		 * If we hit end of line, we're done.
		 */
		if (status == SUP_EOL)
			break;
		if (status != SUP_COLON) {
			datafile_error("Expecting ':', found '%s'", token);
			return;
		}
		/*
		 * Pull in the attribute.
		 */
		status = sup_gettoken(token);
		/*
		 * If we hit end of line, we're done.
		 */
		if (status == SUP_EOL)
			break;
		if (status != SUP_STRING) {
			datafile_error("Expecting keyword, found '%s'", token);
			return;
		}
		clean_token(ident, token);
		/*
		 * Pull in more grammar.
		 */
		status = sup_gettoken(token);
		if (status != SUP_EQL) {
			datafile_error("Expecting '=', found '%s'", token);
			return;
		}
		/*
		 * Pull in the value of the attribute.
		 */
		status = sup_gettoken(token);
		/*
		 * If we hit a key character, it's an error.
		 */
		if (status != SUP_STRING) {
			datafile_error("Expecting value, found '%s'", token);
			return;
		}
		clean_token(cleaned, token);
		/*
		 * If the attribute is the ctlr, save the ctlr name and
		 * mark it defined.
		 */
		if (strcmp(ident, "ctlr") == 0) {
			(void) strcpy(ctlr, cleaned);
			flags |= SUP_CTLR;
			continue;
		/*
		 * If the attribute is the disk, save the disk name and
		 * mark it defined.
		 */
		} else if (strcmp(ident, "disk") == 0) {
			(void) strcpy(disk, cleaned);
			flags |= SUP_DISK;
			continue;
		}
		/*
		 * If we now know both the controller name and the
		 * disk name, let's see if we can find the controller
		 * and disk type.  This will give us the geometry,
		 * which can permit us to accept partitions specs
		 * in cylinders or blocks.
		 */
		if (((flags & (SUP_DISK|SUP_CTLR)) == (SUP_DISK|SUP_CTLR)) &&
		    dtype == NULL && ctype == NULL) {
			/*
			 * Attempt to match the specified ctlr to a known type.
			 */
			mlp = controlp;

			while (mlp != NULL) {
				if (strcmp(mlp->ctlr_type->ctype_name,
				    ctlr) == 0)
					break;
				mlp = mlp->next;
			}
			/*
			 * If no match is found, it's an error.
			 */
			if (mlp == NULL) {
				for (i = 0; i < OTHER_CTLRS; i++) {
					if (strcmp(other_ctlrs[i], ctlr) == 0) {
						datafile_error(NULL, NULL);
						return;
					}
				}
				if (i == OTHER_CTLRS) {
					datafile_error(
					    "Unknown controller '%s'", ctlr);
					return;
				}
			}
			ctype = mlp->ctlr_type;
			/*
			 * Attempt to match the specified disk to a known type.
			 */
			for (dtype = ctype->ctype_dlist; dtype != NULL;
			    dtype = dtype->dtype_next) {
				if (strcmp(dtype->dtype_asciilabel, disk) == 0)
					break;
			}
			/*
			 * If no match is found, it's an error.
			 */
			if (dtype == NULL) {
				datafile_error("Unknown disk '%s'", disk);
				return;
			}
			/*
			 * Now that we know the disk type, set up the
			 * globals that let that magic macro "spc()"
			 * do it's thing.  Sorry that this is glued
			 * together so poorly...
			 */
			nhead = dtype->dtype_nhead;
			nsect = dtype->dtype_nsect;
			acyl = dtype->dtype_acyl;
			ncyl = dtype->dtype_ncyl;
		}
		/*
		 * By now, the disk and controller type must be defined
		 */
		if (dtype == NULL || ctype == NULL) {
			datafile_error("Incomplete specification", "");
			return;
		}
		/*
		 * The rest of the attributes are all single letters.
		 * Make sure the specified attribute is a single letter.
		 */
		if (strlen(ident) != 1) {
			datafile_error("Unknown keyword '%s'", ident);
			return;
		}
		/*
		 * Also make sure it is within the legal range of letters.
		 */
		if (ident[0] < PARTITION_BASE || ident[0] > PARTITION_BASE+9) {
			datafile_error("Unknown keyword '%s'", ident);
			return;
		}
		/*
		 * Here's the index of the partition we're dealing with
		 */
		index = ident[0] - PARTITION_BASE;
		/*
		 * For SunOS 5.0, we support the additional syntax:
		 *	[<tag>, ] [<flag>, ] <start>, <end>
		 * instead of:
		 *	<start>, <end>
		 *
		 * <tag> may be one of: boot, root, swap, etc.
		 * <flag> consists of two characters:
		 *	W (writable) or R (read-only)
		 *	M (mountable) or U (unmountable)
		 *
		 * Start with the defaults assigned above:
		 */
		vtoc_tag = pinfo->vtoc.v_part[index].p_tag;
		vtoc_flag = pinfo->vtoc.v_part[index].p_flag;

		/*
		 * First try to match token against possible tag values
		 */
		if (find_value(ptag_choices, cleaned, &i) == 1) {
			/*
			 * Found valid tag. Use it and advance parser
			 */
			vtoc_tag = (ushort_t)i;
			status = sup_gettoken(token);
			if (status != SUP_COMMA) {
				datafile_error(
				    "Expecting ', ', found '%s'", token);
				return;
			}
			status = sup_gettoken(token);
			if (status != SUP_STRING) {
				datafile_error("Expecting value, found '%s'",
				    token);
				return;
			}
			clean_token(cleaned, token);
		}

		/*
		 * Try to match token against possible flag values
		 */
		if (find_value(pflag_choices, cleaned, &i) == 1) {
			/*
			 * Found valid flag. Use it and advance parser
			 */
			vtoc_flag = (ushort_t)i;
			status = sup_gettoken(token);
			if (status != SUP_COMMA) {
				datafile_error("Expecting ', ', found '%s'",
				    token);
				return;
			}
			status = sup_gettoken(token);
			if (status != SUP_STRING) {
				datafile_error("Expecting value, found '%s'",
				    token);
				return;
			}
			clean_token(cleaned, token);
		}
		/*
		 * All other attributes have a pair of numeric values.
		 * Convert the first value to a number.  This value
		 * is the starting cylinder number of the partition.
		 */
		val1 = str2cyls(cleaned);
		if (val1 == (uint_t)(-1)) {
			datafile_error("Expecting an integer, found '%s'",
			    cleaned);
			return;
		}
		/*
		 * Pull in some grammar.
		 */
		status = sup_gettoken(token);
		if (status != SUP_COMMA) {
			datafile_error("Expecting ', ', found '%s'", token);
			return;
		}
		/*
		 * Pull in the second value.
		 */
		status = sup_gettoken(token);
		if (status != SUP_STRING) {
			datafile_error("Expecting value, found '%s'", token);
			return;
		}
		clean_token(cleaned, token);
		/*
		 * Convert the second value to a number.  This value
		 * is the number of blocks composing the partition.
		 * If the token is terminated with a 'c', the units
		 * are cylinders, not blocks.  Also accept a 'b', if
		 * they choose to be so specific.
		 */
		val2 = str2blks(cleaned);
		if (val2 == (uint_t)(-1)) {
			datafile_error("Expecting an integer, found '%s'",
			    cleaned);
			return;
		}
		/*
		 * Fill in the appropriate map entry with the values.
		 */
		pinfo->pinfo_map[index].dkl_cylno = val1;
		pinfo->pinfo_map[index].dkl_nblk = val2;
		pinfo->vtoc.v_part[index].p_tag = vtoc_tag;
		pinfo->vtoc.v_part[index].p_flag = vtoc_flag;

#if defined(_SUNOS_VTOC_16)
		pinfo->vtoc.v_part[index].p_start = val1 * (nhead * nsect);
		pinfo->vtoc.v_part[index].p_size = val2;

		if (val2 == 0) {
			pinfo->vtoc.v_part[index].p_tag = 0;
			pinfo->vtoc.v_part[index].p_flag = 0;
			pinfo->vtoc.v_part[index].p_start = 0;
			pinfo->pinfo_map[index].dkl_cylno = 0;
		}
#endif /* defined(_SUNOS_VTOC_16) */

	}
	/*
	 * Check to be sure that all necessary attributes were defined.
	 */
	if ((flags & SUP_MIN_PART) != SUP_MIN_PART) {
		datafile_error("Incomplete specification", "");
		return;
	}
	/*
	 * Add this partition map to the list of known maps for the
	 * specified disk/ctlr.
	 */
	parts = dtype->dtype_plist;
	if (parts == NULL)
		dtype->dtype_plist = pinfo;
	else {
		while (parts->pinfo_next != NULL)
			parts = parts->pinfo_next;
		parts->pinfo_next = pinfo;
	}
}

/*
 * Open the disk device - just a wrapper for open.
 */
int
open_disk(char *diskname, int flags)
{
	return (open(diskname, flags));
}

/*
 * This routine performs the disk search during startup.  It looks for
 * all the disks in the search path, and creates a list of those that
 * are found.
 */
void
do_search(char *arglist[])
{
	char			**sp;
	DIR			*dir;
	struct dirent		*dp;
	char			s[MAXPATHLEN];
	char			path[MAXPATHLEN];
	char			curdir[MAXPATHLEN];
	char			*directory = "/dev/rdsk";
	struct disk_info	*disk;
	int			i;

	/*
	 * Change directory to the device directory.  This
	 * gives us the most efficient access to that directory.
	 * Remember where we were, and return there when finished.
	 */
	if (getcwd(curdir, sizeof (curdir)) == NULL) {
		err_print("Cannot get current directory - %s\n",
		    strerror(errno));
		fullabort();
	}
	if (chdir(directory) == -1) {
		err_print("Cannot set directory to %s - %s\n",
		    directory, strerror(errno));
		fullabort();
	}

	/*
	 * If there were disks specified on the command line,
	 * use those disks, and nothing but those disks.
	 */
	if (arglist != NULL) {
		check_for_duplicate_disknames(arglist);
		for (; *arglist != NULL; arglist++) {
			search_for_logical_dev(*arglist);
		}
	} else {
		/*
		 * If there were no disks specified on the command line,
		 * search for all disks attached to the system.
		 */
		fmt_print("Searching for disks...");
		(void) fflush(stdout);
		need_newline = 1;

		/*
		 * Find all disks specified in search_path definitions
		 * in whatever format.dat files were processed.
		 */
		sp = search_path;
		if (sp != NULL) {
			while (*sp != NULL) {
				search_for_logical_dev(*sp++);
			}
		}

		/*
		 * Open the device directory
		 */
		if ((dir = opendir(".")) == NULL) {
			err_print("Cannot open %s - %s\n",
			    directory, strerror(errno));
			fullabort();
		}

		/*
		 * Now find all usable nodes in /dev/rdsk (or /dev, if 4.x)
		 * First find all nodes which do not conform to
		 * standard disk naming conventions.  This permits
		 * all user-defined names to override the default names.
		 */
		while ((dp = readdir(dir)) != NULL) {
			if (strcmp(dp->d_name, ".") == 0 ||
			    strcmp(dp->d_name, "..") == 0)
				continue;
			if (!conventional_name(dp->d_name)) {
				if (!fdisk_physical_name(dp->d_name)) {
					/*
					 * If non-conventional name represents
					 * a link to non-s2 slice , ignore it.
					 */
					if (!name_represents_wholedisk
					    (dp->d_name)) {
						(void) strcpy(path, directory);
						(void) strcat(path, "/");
						(void) strcat(path, dp->d_name);
						add_device_to_disklist(
						    dp->d_name, path);
					}
				}
			}
		}
		rewinddir(dir);


		/*
		 * Now find all nodes corresponding to the standard
		 * device naming conventions.
		 */
		while ((dp = readdir(dir)) != NULL) {
			if (strcmp(dp->d_name, ".") == 0 ||
			    strcmp(dp->d_name, "..") == 0)
				continue;
			if (whole_disk_name(dp->d_name)) {
				(void) strcpy(path, directory);
				(void) strcat(path, "/");
				(void) strcat(path, dp->d_name);
				canonicalize_name(s, dp->d_name);
				add_device_to_disklist(s, path);
			}
		}
		/*
		 * Close the directory
		 */
		if (closedir(dir) == -1) {
			err_print("Cannot close directory %s - %s\n",
			    directory, strerror(errno));
			fullabort();
		}

		need_newline = 0;
		fmt_print("done\n");
	}

	/*
	 * Return to whence we came
	 */
	if (chdir(curdir) == -1) {
		err_print("Cannot set directory to %s - %s\n",
		    curdir, strerror(errno));
		fullabort();
	}

	/*
	 * If we didn't find any disks, give up.
	 */
	if (disk_list == NULL) {
		if (geteuid() == 0) {
			err_print("No disks found!\n");
		} else {
			err_print("No permission (or no disks found)!\n");
		}
		(void) fflush(stdout);
		fullabort();
	}

	sort_disk_list();

	/*
	 * Tell user the results of the auto-configure process
	 */
	i = 0;
	for (disk = disk_list; disk != NULL; disk = disk->disk_next) {
		float			scaled;
		diskaddr_t		nblks;
		struct disk_type	*type;
		if (disk->disk_flags & DSK_AUTO_CONFIG) {
			if (i++ == 0) {
				fmt_print("\n");
			}
			fmt_print("%s: ", disk->disk_name);
			if (disk->disk_flags & DSK_LABEL_DIRTY) {
				fmt_print("configured ");
			} else {
				fmt_print("configured and labeled ");
			}
			type = disk->disk_type;
			nblks = type->dtype_ncyl * type->dtype_nhead *
			    type->dtype_nsect;
			if (disk->label_type == L_TYPE_SOLARIS)
				scaled = bn2mb(nblks);
			else
				scaled = bn2mb(type->capacity);
			fmt_print("with capacity of ");
			if (scaled > 1024.0) {
				fmt_print("%1.2fGB\n", scaled/1024.0);
			} else {
				fmt_print("%1.2fMB\n", scaled);
			}
		}
	}
}


/*
 * For a given "logical" disk name as specified in a format.dat
 * search path, try to find the device it actually refers to.
 * Since we are trying to maintain 4.x naming convention
 * compatibility in 5.0, this involves a little bit of work.
 * We also want to be able to function under 4.x, if needed.
 *
 * canonical:	standard name reference.  append a partition
 *	reference, and open that file in the device directory.
 *	examples:	SVR4:	c0t0d0
 *			4.x:	sd0
 *
 * absolute:	begins with a '/', and is assumed to be an
 *	absolute pathname to some node.
 *
 * relative:	non-canonical, doesn't begin with a '/'.
 *	assumed to be the name of a file in the appropriate
 *	device directory.
 */
static void
search_for_logical_dev(char *devname)
{
	char		path[MAXPATHLEN];
	char		*directory = "/dev/rdsk/";
	char		*partition = "s2";

	/*
	 * If the name is an absolute path name, accept it as is
	 */
	if (*devname == '/') {
		(void) strcpy(path, devname);
	} else if (canonical_name(devname)) {
		/*
		 * If canonical name, construct a standard path name.
		 */
		(void) strcpy(path, directory);
		(void) strcat(path, devname);
		(void) strcat(path, partition);
	} else if (canonical4x_name(devname)) {
		/*
		 * Check to see if it's a 4.x file name in the /dev
		 * directory on 5.0.  Here, we only accept the
		 * canonicalized form: sd0.
		 */
		(void) strcpy(path, "/dev/r");
		(void) strcat(path, devname);
		(void) strcat(path, "c");
	} else {
		/*
		 * If it's not a canonical name, then it may be a
		 * reference to an actual file name in the device
		 * directory itself.
		 */
		(void) strcpy(path, directory);
		(void) strcat(path, devname);
	}

	/* now add the device */
	add_device_to_disklist(devname, path);
}

/*
 * Get the disk name from the inquiry data
 */
static void
get_disk_name(int fd, char *disk_name, struct disk_info *disk_info)
{
	struct scsi_inquiry	inquiry;
	char			*vid, *pid, *rid;

	if (get_disk_inquiry_prop(disk_info->devfs_name, &vid, &pid, &rid)
	    == 0) {
		(void) snprintf(disk_name, MAXNAMELEN - 1, "%s-%s-%s",
		    vid, pid, rid);
		free(vid);
		free(pid);
		free(rid);

		return;
	}

	if (uscsi_inquiry(fd, (char *)&inquiry, sizeof (inquiry))) {
		if (option_msg)
			err_print("\nInquiry failed - %s\n", strerror(errno));
		(void) strcpy(disk_name, "Unknown-Unknown-0001");
		return;
	}

	(void) get_generic_disk_name(disk_name, &inquiry);
}

/*
 * Add a device to the disk list, if it appears to be a disk,
 * and we haven't already found it under some other name.
 */
static void
add_device_to_disklist(char *devname, char *devpath)
{
	struct disk_info	*search_disk;
	struct ctlr_info	*search_ctlr;
	struct disk_type	*search_dtype, *efi_disk;
	struct partition_info	*search_parts;
	struct disk_info	*dptr;
	struct ctlr_info	*cptr;
	struct disk_type	*type;
	struct partition_info	*parts;
	struct dk_label		search_label;
	struct dk_cinfo		dkinfo;
	struct stat		stbuf;
	struct ctlr_type	*ctlr, *tctlr;
	struct	mctlr_list	*mlp;
	struct	efi_info	efi_info;
	struct dk_minfo		mediainfo;
	int			search_file;
	int			status;
	int			i;
	int			access_flags = 0;
	char			disk_name[MAXNAMELEN];

	/*
	 * Attempt to open the disk.  If it fails, skip it.
	 */
	if ((search_file = open_disk(devpath, O_RDWR | O_NDELAY)) < 0) {
		return;
	}
	/*
	 * Must be a character device
	 */
	if (fstat(search_file, &stbuf) == -1 || !S_ISCHR(stbuf.st_mode)) {
		(void) close(search_file);
		return;
	}
	/*
	 * Attempt to read the configuration info on the disk.
	 * Again, if it fails, we assume the disk's not there.
	 * Note we must close the file for the disk before we
	 * continue.
	 */
	if (ioctl(search_file, DKIOCINFO, &dkinfo) < 0) {
		(void) close(search_file);
		return;
	}

	/* If it is a removable media, skip it. */

	if (!expert_mode) {
		int isremovable, ret;
		ret = ioctl(search_file, DKIOCREMOVABLE, &isremovable);
		if ((ret >= 0) && (isremovable != 0)) {
			(void) close(search_file);
			return;
		}
	}

	if (ioctl(search_file, DKIOCGMEDIAINFO, &mediainfo) == -1) {
		cur_blksz = DEV_BSIZE;
	} else {
		cur_blksz = mediainfo.dki_lbsize;
	}

	/*
	 * If the type of disk is one we don't know about,
	 * add it to the list.
	 */
	mlp = controlp;

	while (mlp != NULL) {
		if (mlp->ctlr_type->ctype_ctype == dkinfo.dki_ctype) {
			break;
		}
		mlp = mlp->next;
	}

	if (mlp == NULL) {
		if (dkinfo.dki_ctype == DKC_CDROM) {
			if (ioctl(search_file, DKIOCGMEDIAINFO,
			    &mediainfo) < 0) {
				mediainfo.dki_media_type = DK_UNKNOWN;
			}
		}
		/*
		 * Skip CDROM devices, they are read only.
		 * But not devices like Iomega Rev Drive which
		 * identifies itself as a CDROM, but has a removable
		 * disk.
		 */
		if ((dkinfo.dki_ctype == DKC_CDROM) &&
		    (mediainfo.dki_media_type != DK_REMOVABLE_DISK)) {
			(void) close(search_file);
			return;
		}
		/*
		 * create the new ctlr_type structure and fill it in.
		 */
		tctlr = zalloc(sizeof (struct ctlr_type));
		tctlr->ctype_ctype = dkinfo.dki_ctype;
		tctlr->ctype_name = zalloc(DK_DEVLEN);
		if (strlcpy(tctlr->ctype_name, dkinfo.dki_cname,
		    DK_DEVLEN) > DK_DEVLEN) {
			/*
			 * DKIOCINFO returned a controller name longer
			 * than DK_DEVLEN bytes, which means more of the
			 * dk_cinfo structure may be corrupt.  We don't
			 * allow the user to perform any operations on
			 * the device in this case
			 */
			err_print("\nError: Device %s: controller "
			    "name (%s)\nis invalid.  Device will not "
			    "be displayed.\n", devname, dkinfo.dki_cname);
			(void) close(search_file);
			destroy_data(tctlr->ctype_name);
			destroy_data((char *)tctlr);
			return;
		} else {
			tctlr->ctype_ops = zalloc(sizeof (struct ctlr_ops));

			/*
			 * copy the generic disk ops structure into local copy.
			 */
			*(tctlr->ctype_ops) = genericops;

			tctlr->ctype_flags = CF_WLIST;

			mlp = controlp;

			while (mlp->next != NULL) {
				mlp = mlp->next;
			}

			mlp->next = zalloc(sizeof (struct mctlr_list));
			mlp->next->ctlr_type = tctlr;
		}
	}

	/*
	 * Search through all disks known at this time, to
	 * determine if we're already identified this disk.
	 * If so, then there's no need to include it a
	 * second time.  This permits the user-defined names
	 * to supercede the standard conventional names.
	 */
	if (disk_is_known(&dkinfo)) {
		(void) close(search_file);
		return;
	}
#if defined(sparc)
	/*
	 * Because opening id with FNDELAY always succeeds,
	 * read the label early on to see whether the device
	 * really exists.  A result of DSK_RESERVED
	 * means the disk may be reserved.
	 * In the future, it will be good
	 * to move these into controller specific files and have a common
	 * generic check for reserved disks here, including intel disks.
	 */
	if (dkinfo.dki_ctype == DKC_SCSI_CCS) {
		char	*first_sector;

		first_sector = zalloc(cur_blksz);
		i = scsi_rdwr(DIR_READ, search_file, (diskaddr_t)0,
		    1, first_sector, F_SILENT, NULL);
		switch (i) {
		case DSK_RESERVED:
			access_flags |= DSK_RESERVED;
			break;
		case DSK_UNAVAILABLE:
			access_flags |= DSK_UNAVAILABLE;
			break;
		default:
			break;
		}
		free(first_sector);
	}
#endif /* defined(sparc) */

	/*
	 * The disk appears to be present.  Allocate space for the
	 * disk structure and add it to the list of found disks.
	 */
	search_disk = (struct disk_info *)zalloc(sizeof (struct disk_info));
	if (disk_list == NULL)
		disk_list = search_disk;
	else {
		for (dptr = disk_list; dptr->disk_next != NULL;
		    dptr = dptr->disk_next)
			;
		dptr->disk_next = search_disk;
	}
	/*
	 * Fill in some info from the ioctls.
	 */
	search_disk->disk_dkinfo = dkinfo;
	if (is_efi_type(search_file)) {
		search_disk->label_type = L_TYPE_EFI;
	} else {
		search_disk->label_type = L_TYPE_SOLARIS;
	}
	/*
	 * Remember the names of the disk
	 */
	search_disk->disk_name = alloc_string(devname);
	search_disk->disk_path = alloc_string(devpath);

	/*
	 * Remember the lba size of the disk
	 */
	search_disk->disk_lbasize = cur_blksz;

	(void) strcpy(x86_devname, devname);

	/*
	 * Determine if this device is linked to a physical name.
	 */
	search_disk->devfs_name = get_physical_name(devpath);

	/*
	 * Try to match the ctlr for this disk with a ctlr we
	 * have already found.  A match is assumed if the ctlrs
	 * are at the same address && ctypes agree
	 */
	for (search_ctlr = ctlr_list; search_ctlr != NULL;
	    search_ctlr = search_ctlr->ctlr_next)
		if (search_ctlr->ctlr_addr == dkinfo.dki_addr &&
		    search_ctlr->ctlr_space == dkinfo.dki_space &&
		    search_ctlr->ctlr_ctype->ctype_ctype ==
		    dkinfo.dki_ctype)
			break;
	/*
	 * If no match was found, we need to identify this ctlr.
	 */
	if (search_ctlr == NULL) {
		/*
		 * Match the type of the ctlr to a known type.
		 */
		mlp = controlp;

		while (mlp != NULL) {
			if (mlp->ctlr_type->ctype_ctype == dkinfo.dki_ctype)
				break;
			mlp = mlp->next;
		}
		/*
		 * If no match was found, it's an error.
		 * Close the disk and report the error.
		 */
		if (mlp == NULL) {
			err_print("\nError: found disk attached to ");
			err_print("unsupported controller type '%d'.\n",
			    dkinfo.dki_ctype);
			(void) close(search_file);
			return;
		}
		/*
		 * Allocate space for the ctlr structure and add it
		 * to the list of found ctlrs.
		 */
		search_ctlr = (struct ctlr_info *)
		    zalloc(sizeof (struct ctlr_info));
		search_ctlr->ctlr_ctype = mlp->ctlr_type;
		if (ctlr_list == NULL)
			ctlr_list = search_ctlr;
		else {
			for (cptr = ctlr_list; cptr->ctlr_next != NULL;
			    cptr = cptr->ctlr_next)
				;
			cptr->ctlr_next = search_ctlr;
		}
		/*
		 * Fill in info from the ioctl.
		 */
		for (i = 0; i < DK_DEVLEN; i++) {
			search_ctlr->ctlr_cname[i] = dkinfo.dki_cname[i];
			search_ctlr->ctlr_dname[i] = dkinfo.dki_dname[i];
		}
		/*
		 * Make sure these can be used as simple strings
		 */
		search_ctlr->ctlr_cname[i] = 0;
		search_ctlr->ctlr_dname[i] = 0;

		search_ctlr->ctlr_flags = dkinfo.dki_flags;
		search_ctlr->ctlr_num = dkinfo.dki_cnum;
		search_ctlr->ctlr_addr = dkinfo.dki_addr;
		search_ctlr->ctlr_space = dkinfo.dki_space;
		search_ctlr->ctlr_prio = dkinfo.dki_prio;
		search_ctlr->ctlr_vec = dkinfo.dki_vec;
	}
	/*
	 * By this point, we have a known ctlr.  Link the disk
	 * to the ctlr.
	 */
	search_disk->disk_ctlr = search_ctlr;
	if (access_flags & (DSK_RESERVED | DSK_UNAVAILABLE)) {
		if (access_flags & DSK_RESERVED)
			search_disk->disk_flags |= DSK_RESERVED;
		else
			search_disk->disk_flags |= DSK_UNAVAILABLE;
		(void) close(search_file);
		return;
	} else {
		search_disk->disk_flags &= ~(DSK_RESERVED | DSK_UNAVAILABLE);
	}

	/*
	 * Attempt to read the primary label.
	 * (Note that this is really through the DKIOCGVTOC
	 * ioctl, then converted from vtoc to label.)
	 */
	if (search_disk->label_type == L_TYPE_SOLARIS) {
		status = read_label(search_file, &search_label);
	} else {
		status = read_efi_label(search_file, &efi_info, search_disk);
	}
	/*
	 * If reading the label failed, and this is a SCSI
	 * disk, we can attempt to auto-sense the disk
	 * Configuration.
	 */
	ctlr = search_ctlr->ctlr_ctype;
	if ((status == -1) &&
	    (ctlr->ctype_ctype == DKC_SCSI_CCS ||
	    ctlr->ctype_ctype == DKC_BLKDEV)) {
		if (option_msg && diag_msg) {
			err_print("%s: attempting auto configuration\n",
			    search_disk->disk_name);
		}

		switch (search_disk->label_type) {
		case (L_TYPE_SOLARIS):
			if (auto_sense(search_file, 0, &search_label) != NULL) {
			/*
			 * Auto config worked, so we now have
			 * a valid label for the disk.  Mark
			 * the disk as needing the label flushed.
			 */
				status = 0;
				search_disk->disk_flags |=
				    (DSK_LABEL_DIRTY | DSK_AUTO_CONFIG);
				break;
			}
			/* With SOLARIS label type failed, try EFI. */
			/* FALLTHROUGH */
		case (L_TYPE_EFI):
			efi_disk = auto_efi_sense(search_file, &efi_info);
			if (efi_disk != NULL) {
				/*
				 * Auto config worked, so we now have
				 * a valid label for the disk.
				 */
				search_disk->label_type = L_TYPE_EFI;
				status = 0;
				search_disk->disk_flags |=
				    (DSK_LABEL_DIRTY | DSK_AUTO_CONFIG);
			}
			break;
		default:
			/* Should never happen */
			break;
		}
	}

	/*
	 * If we didn't successfully read the label, or the label
	 * appears corrupt, just leave the disk as an unknown type.
	 */
	if (status == -1) {
		(void) close(search_file);
		return;
	}

	if (search_disk->label_type == L_TYPE_SOLARIS) {
		if (!checklabel(&search_label)) {
			(void) close(search_file);
			return;
		}
		if (trim_id(search_label.dkl_asciilabel)) {
			(void) close(search_file);
			return;
		}
	}
	/*
	 * The label looks ok.  Mark the disk as labeled.
	 */
	search_disk->disk_flags |= DSK_LABEL;

	if (search_disk->label_type == L_TYPE_EFI) {
		search_dtype = (struct disk_type *)
		    zalloc(sizeof (struct disk_type));
		type = search_ctlr->ctlr_ctype->ctype_dlist;
		if (type == NULL) {
			search_ctlr->ctlr_ctype->ctype_dlist =
			    search_dtype;
		} else {
			while (type->dtype_next != NULL) {
				type = type->dtype_next;
			}
			type->dtype_next = search_dtype;
		}
		search_dtype->dtype_next = NULL;

		search_dtype->vendor = strdup(efi_info.vendor);
		search_dtype->product = strdup(efi_info.product);
		search_dtype->revision = strdup(efi_info.revision);

		if (search_dtype->vendor == NULL ||
		    search_dtype->product == NULL ||
		    search_dtype->revision == NULL) {
			free(search_dtype->vendor);
			free(search_dtype->product);
			free(search_dtype->revision);
			free(search_dtype);
			goto out;
		}

		search_dtype->capacity = efi_info.capacity;
		search_disk->disk_type = search_dtype;

		search_parts = (struct partition_info *)
		    zalloc(sizeof (struct partition_info));
		search_dtype->dtype_plist = search_parts;

		search_parts->pinfo_name = alloc_string("original");
		search_parts->pinfo_next = NULL;
		search_parts->etoc = efi_info.e_parts;
		search_disk->disk_parts = search_parts;

		/*
		 * Copy the volume name, if present
		 */
		for (i = 0; i < search_parts->etoc->efi_nparts; i++) {
			if (search_parts->etoc->efi_parts[i].p_tag ==
			    V_RESERVED) {
				bcopy(search_parts->etoc->efi_parts[i].p_name,
				    search_disk->v_volume, LEN_DKL_VVOL);
				break;
			}
		}
	out:
		(void) close(search_file);

		free(efi_info.vendor);
		free(efi_info.product);
		free(efi_info.revision);
		return;
	}

	/*
	 * Attempt to match the disk type in the label with a
	 * known disk type.
	 */
	for (search_dtype = search_ctlr->ctlr_ctype->ctype_dlist;
	    search_dtype != NULL;
	    search_dtype = search_dtype->dtype_next)
		if (dtype_match(&search_label, search_dtype))
			break;
	/*
	 * If no match was found, we need to create a disk type
	 * for this disk.
	 */
	if (search_dtype == NULL) {
		/*
		 * Allocate space for the disk type and add it
		 * to the list of disk types for this ctlr type.
		 */
		search_dtype = (struct disk_type *)
		    zalloc(sizeof (struct disk_type));
		type = search_ctlr->ctlr_ctype->ctype_dlist;
		if (type == NULL)
			search_ctlr->ctlr_ctype->ctype_dlist =
			    search_dtype;
		else {
			while (type->dtype_next != NULL)
				type = type->dtype_next;
			type->dtype_next = search_dtype;
		}
		/*
		 * Fill in the drive info from the disk label.
		 */
		search_dtype->dtype_next = NULL;
		if (strncmp(search_label.dkl_asciilabel, "DEFAULT",
		    strlen("DEFAULT")) == 0) {
			(void) get_disk_name(search_file, disk_name,
			    search_disk);
			search_dtype->dtype_asciilabel = (char *)
			    zalloc(strlen(disk_name) + 1);
			(void) strcpy(search_dtype->dtype_asciilabel,
			    disk_name);
		} else {
			search_dtype->dtype_asciilabel = (char *)
			    zalloc(strlen(search_label.dkl_asciilabel) + 1);
			(void) strcpy(search_dtype->dtype_asciilabel,
			    search_label.dkl_asciilabel);
		}
		search_dtype->dtype_pcyl = search_label.dkl_pcyl;
		search_dtype->dtype_ncyl = search_label.dkl_ncyl;
		search_dtype->dtype_acyl = search_label.dkl_acyl;
		search_dtype->dtype_nhead = search_label.dkl_nhead;
		search_dtype->dtype_nsect = search_label.dkl_nsect;
		search_dtype->dtype_rpm = search_label.dkl_rpm;
		/*
		 * Mark the disk as needing specification of
		 * ctlr specific attributes.  This is necessary
		 * because the label doesn't contain these attributes,
		 * and they aren't known at this point.  They will
		 * be asked for if this disk is ever selected by
		 * the user.
		 * Note: for SCSI, we believe the label.
		 */
		if ((search_ctlr->ctlr_ctype->ctype_ctype != DKC_SCSI_CCS) &&
		    (search_ctlr->ctlr_ctype->ctype_ctype != DKC_DIRECT) &&
		    (search_ctlr->ctlr_ctype->ctype_ctype != DKC_VBD) &&
		    (search_ctlr->ctlr_ctype->ctype_ctype != DKC_PCMCIA_ATA) &&
		    (search_ctlr->ctlr_ctype->ctype_ctype != DKC_BLKDEV)) {
			search_dtype->dtype_flags |= DT_NEED_SPEFS;
		}
	}
	/*
	 * By this time we have a known disk type.  Link the disk
	 * to the disk type.
	 */
	search_disk->disk_type = search_dtype;

	/*
	 * Close the file for this disk
	 */
	(void) close(search_file);

	/*
	 * Attempt to match the partition map in the label with
	 * a known partition map for this disk type.
	 */
	for (search_parts = search_dtype->dtype_plist;
	    search_parts != NULL;
	    search_parts = search_parts->pinfo_next)
		if (parts_match(&search_label, search_parts)) {
			break;
		}
	/*
	 * If no match was made, we need to create a partition
	 * map for this disk.
	 */
	if (search_parts == NULL) {
		/*
		 * Allocate space for the partition map and add
		 * it to the list of maps for this disk type.
		 */
		search_parts = (struct partition_info *)
		    zalloc(sizeof (struct partition_info));
		parts = search_dtype->dtype_plist;
		if (parts == NULL)
			search_dtype->dtype_plist = search_parts;
		else {
			while (parts->pinfo_next != NULL)
				parts = parts->pinfo_next;
			parts->pinfo_next = search_parts;
		}
		search_parts->pinfo_next = NULL;
		/*
		 * Fill in the name of the map with a name derived
		 * from the name of this disk.  This is necessary
		 * because the label contains no name for the
		 * partition map.
		 */
		search_parts->pinfo_name = alloc_string("original");
		/*
		 * Fill in the partition info from the disk label.
		 */
		for (i = 0; i < NDKMAP; i++) {

#if defined(_SUNOS_VTOC_8)
			search_parts->pinfo_map[i] =
			    search_label.dkl_map[i];

#elif defined(_SUNOS_VTOC_16)
			search_parts->pinfo_map[i].dkl_cylno =
			    search_label.dkl_vtoc.v_part[i].p_start /
			    ((blkaddr32_t)(search_label.dkl_nhead *
			    search_label.dkl_nsect));
			search_parts->pinfo_map[i].dkl_nblk =
			    search_label.dkl_vtoc.v_part[i].p_size;

#else
#error No VTOC format defined.
#endif
		}
	}
	/*
	 * If the vtoc looks valid, copy the volume name and vtoc
	 * info from the label.  Otherwise, install a default vtoc.
	 * This permits vtoc info to automatically appear in the sun
	 * label, without requiring an upgrade procedure.
	 */
	if (search_label.dkl_vtoc.v_version == V_VERSION) {
		bcopy(search_label.dkl_vtoc.v_volume,
		    search_disk->v_volume, LEN_DKL_VVOL);
		search_parts->vtoc = search_label.dkl_vtoc;
	} else {
		bzero(search_disk->v_volume, LEN_DKL_VVOL);
		set_vtoc_defaults(search_parts);
	}
	/*
	 * By this time we have a known partitition map.  Link the
	 * disk to the partition map.
	 */
	search_disk->disk_parts = search_parts;
}


/*
 * Search the disk list for a disk with the identical configuration.
 * Return true if one is found.
 */
static int
disk_is_known(struct dk_cinfo *dkinfo)
{
	struct disk_info	*dp;

	dp = disk_list;
	while (dp != NULL) {
		if (dp->disk_dkinfo.dki_ctype == dkinfo->dki_ctype &&
		    dp->disk_dkinfo.dki_cnum == dkinfo->dki_cnum &&
		    dp->disk_dkinfo.dki_unit == dkinfo->dki_unit &&
		    strcmp(dp->disk_dkinfo.dki_dname, dkinfo->dki_dname) == 0) {
			return (1);
		}
		dp = dp->disk_next;
	}
	return (0);
}


/*
 * This routine checks to see if a given disk type matches the type
 * in the disk label.
 */
int
dtype_match(struct dk_label *label, struct disk_type *dtype)
{

	if (dtype->dtype_asciilabel == NULL) {
		return (0);
	}

	/*
	 * If the any of the physical characteristics are different, or
	 * the name is different, it doesn't match.
	 */
	if ((strcmp(label->dkl_asciilabel, dtype->dtype_asciilabel) != 0) ||
	    (label->dkl_ncyl != dtype->dtype_ncyl) ||
	    (label->dkl_acyl != dtype->dtype_acyl) ||
	    (label->dkl_nhead != dtype->dtype_nhead) ||
	    (label->dkl_nsect != dtype->dtype_nsect)) {
		return (0);
	}
	/*
	 * If those are all identical, assume it's a match.
	 */
	return (1);
}

/*
 * This routine checks to see if a given partition map matches the map
 * in the disk label.
 */
int
parts_match(struct dk_label *label, struct partition_info *pinfo)
{
	int i;

	/*
	 * If any of the partition entries is different, it doesn't match.
	 */
	for (i = 0; i < NDKMAP; i++)

#if defined(_SUNOS_VTOC_8)
		if ((label->dkl_map[i].dkl_cylno !=
		    pinfo->pinfo_map[i].dkl_cylno) ||
		    (label->dkl_map[i].dkl_nblk !=
		    pinfo->pinfo_map[i].dkl_nblk))

#elif defined(_SUNOS_VTOC_16)
		if ((pinfo->pinfo_map[i].dkl_cylno !=
		    label->dkl_vtoc.v_part[i].p_start /
		    (label->dkl_nhead * label->dkl_nsect)) ||
		    (pinfo->pinfo_map[i].dkl_nblk !=
		    label->dkl_vtoc.v_part[i].p_size))
#else
#error No VTOC format defined.
#endif
			return (0);
	/*
	 * Compare the vtoc information for a match
	 * Do not require the volume name to be equal, for a match!
	 */
	if (label->dkl_vtoc.v_version != pinfo->vtoc.v_version)
		return (0);
	if (label->dkl_vtoc.v_nparts != pinfo->vtoc.v_nparts)
		return (0);
	for (i = 0; i < NDKMAP; i++) {
		if (label->dkl_vtoc.v_part[i].p_tag !=
		    pinfo->vtoc.v_part[i].p_tag)
			return (0);
		if (label->dkl_vtoc.v_part[i].p_flag !=
		    pinfo->vtoc.v_part[i].p_flag)
			return (0);
	}
	/*
	 * If they are all identical, it's a match.
	 */
	return (1);
}

/*
 * This routine checks to see if the given disk name refers to the disk
 * in the given disk structure.
 */
int
diskname_match(char *name, struct disk_info *disk)
{
	struct dk_cinfo		dkinfo;
	char			s[MAXPATHLEN];
	int			fd;

	/*
	 * Match the name of the disk in the disk_info structure
	 */
	if (strcmp(name, disk->disk_name) == 0) {
		return (1);
	}

	/*
	 * Check to see if it's a 4.x file name in the /dev
	 * directory on 5.0.  Here, we only accept the
	 * canonicalized form: sd0.
	 */
	if (canonical4x_name(name) == 0) {
		return (0);
	}

	(void) strcpy(s, "/dev/r");
	(void) strcat(s, name);
	(void) strcat(s, "c");

	if ((fd = open_disk(s, O_RDWR | O_NDELAY)) < 0) {
		return (0);
	}

	if (ioctl(fd, DKIOCINFO, &dkinfo) < 0) {
		(void) close(fd);
		return (0);
	}
	(void) close(fd);

	if (disk->disk_dkinfo.dki_ctype == dkinfo.dki_ctype &&
	    disk->disk_dkinfo.dki_cnum == dkinfo.dki_cnum &&
	    disk->disk_dkinfo.dki_unit == dkinfo.dki_unit &&
	    strcmp(disk->disk_dkinfo.dki_dname, dkinfo.dki_dname) == 0) {
		return (1);
	}
	return (0);
}


static void
datafile_error(char *errmsg, char *token)
{
	int	token_type;
	TOKEN	token_buf;

	/*
	 * Allow us to get by controllers that the other platforms don't
	 * know about.
	 */
	if (errmsg != NULL) {
		err_print(errmsg, token);
		err_print(" - %s (%d)\n", file_name, data_lineno);
	}

	/*
	 * Re-sync the parsing at the beginning of the next line
	 * unless of course we're already there.
	 */
	if (last_token_type != SUP_EOF && last_token_type != SUP_EOL) {
		do {
			token_type = sup_gettoken(token_buf);
		} while (token_type != SUP_EOF && token_type != SUP_EOL);

		if (token_type == SUP_EOF) {
			sup_pushtoken(token_buf, token_type);
		}
	}
}


/*
 * Search through all defined disk types for duplicate entries
 * that are inconsistent with each other.  Disks with different
 * characteristics should be named differently.
 * Note that this function only checks for duplicate disks
 * for the same controller.  It's possible to have two disks with
 * the same name, but defined for different controllers.
 * That may or may not be a problem...
 */
static void
search_duplicate_dtypes(void)
{
	struct disk_type	*dp1;
	struct disk_type	*dp2;
	struct mctlr_list	*mlp;

	mlp = controlp;

	while (mlp != NULL) {
		dp1 = mlp->ctlr_type->ctype_dlist;
		while (dp1 != NULL) {
			dp2 = dp1->dtype_next;
			while (dp2 != NULL) {
				check_dtypes_for_inconsistency(dp1, dp2);
				dp2 = dp2->dtype_next;
			}
			dp1 = dp1->dtype_next;
		}
	mlp = mlp->next;
	}
}


/*
 * Search through all defined partition types for duplicate entries
 * that are inconsistent with each other.  Partitions with different
 * characteristics should be named differently.
 * Note that this function only checks for duplicate partitions
 * for the same disk.  It's possible to have two partitions with
 * the same name, but defined for different disks.
 * That may or may not be a problem...
 */
static void
search_duplicate_pinfo(void)
{
	struct disk_type	*dp;
	struct partition_info	*pp1;
	struct partition_info	*pp2;
	struct mctlr_list	*mlp;

	mlp = controlp;

	while (mlp != NULL) {
		dp = mlp->ctlr_type->ctype_dlist;
		while (dp != NULL) {
			pp1 = dp->dtype_plist;
			while (pp1 != NULL) {
				pp2 = pp1->pinfo_next;
				while (pp2 != NULL) {
					check_pinfo_for_inconsistency(pp1, pp2);
					pp2 = pp2->pinfo_next;
				}
				pp1 = pp1->pinfo_next;
			}
			dp = dp->dtype_next;
		}
	mlp = mlp->next;
	}
}


/*
 * Determine if two particular disk definitions are inconsistent.
 * Ie:  same name, but different characteristics.
 * If so, print an error message and abort.
 */
static void
check_dtypes_for_inconsistency(struct disk_type	*dp1, struct disk_type *dp2)
{
	int		i;
	int		result;
	struct chg_list	*cp1;
	struct chg_list	*cp2;


	/*
	 * If the name's different, we're ok
	 */
	if (strcmp(dp1->dtype_asciilabel, dp2->dtype_asciilabel) != 0) {
		return;
	}

	/*
	 * Compare all the disks' characteristics
	 */
	result = 0;
	result |= (dp1->dtype_flags != dp2->dtype_flags);
	result |= (dp1->dtype_options != dp2->dtype_options);
	result |= (dp1->dtype_fmt_time != dp2->dtype_fmt_time);
	result |= (dp1->dtype_bpt != dp2->dtype_bpt);
	result |= (dp1->dtype_ncyl != dp2->dtype_ncyl);
	result |= (dp1->dtype_acyl != dp2->dtype_acyl);
	result |= (dp1->dtype_pcyl != dp2->dtype_pcyl);
	result |= (dp1->dtype_nhead != dp2->dtype_nhead);
	result |= (dp1->dtype_nsect != dp2->dtype_nsect);
	result |= (dp1->dtype_rpm != dp2->dtype_rpm);
	result |= (dp1->dtype_cyl_skew != dp2->dtype_cyl_skew);
	result |= (dp1->dtype_trk_skew != dp2->dtype_trk_skew);
	result |= (dp1->dtype_trks_zone != dp2->dtype_trks_zone);
	result |= (dp1->dtype_atrks != dp2->dtype_atrks);
	result |= (dp1->dtype_asect != dp2->dtype_asect);
	result |= (dp1->dtype_cache != dp2->dtype_cache);
	result |= (dp1->dtype_threshold != dp2->dtype_threshold);
	result |= (dp1->dtype_read_retries != dp2->dtype_read_retries);
	result |= (dp1->dtype_write_retries != dp2->dtype_write_retries);
	result |= (dp1->dtype_prefetch_min != dp2->dtype_prefetch_min);
	result |= (dp1->dtype_prefetch_max != dp2->dtype_prefetch_max);
	for (i = 0; i < NSPECIFICS; i++) {
		result |= (dp1->dtype_specifics[i] != dp2->dtype_specifics[i]);
	}

	cp1 = dp1->dtype_chglist;
	cp2 = dp2->dtype_chglist;
	while (cp1 != NULL && cp2 != NULL) {
		if (cp1 == NULL || cp2 == NULL) {
			result = 1;
			break;
		}
		result |= (cp1->pageno != cp2->pageno);
		result |= (cp1->byteno != cp2->byteno);
		result |= (cp1->mode != cp2->mode);
		result |= (cp1->value != cp2->value);
		cp1 = cp1->next;
		cp2 = cp2->next;
	}

	if (result) {
		err_print("Inconsistent definitions for disk type '%s'\n",
		    dp1->dtype_asciilabel);
		if (dp1->dtype_filename != NULL &&
		    dp2->dtype_filename != NULL) {
			err_print("%s (%d) - %s (%d)\n",
			    dp1->dtype_filename, dp1->dtype_lineno,
			    dp2->dtype_filename, dp2->dtype_lineno);
		}
		fullabort();
	}
}


/*
 * Determine if two particular partition definitions are inconsistent.
 * Ie:  same name, but different characteristics.
 * If so, print an error message and abort.
 */
static void
check_pinfo_for_inconsistency(struct partition_info *pp1,
    struct partition_info *pp2)
{
	int		i;
	int		result;
	struct dk_map32	*map1;
	struct dk_map32	*map2;

#if defined(_SUNOS_VTOC_8)
	struct dk_map2	*vp1;
	struct dk_map2	*vp2;

#elif defined(_SUNOS_VTOC_16)
	struct dkl_partition    *vp1;
	struct dkl_partition    *vp2;
#else
#error No VTOC layout defined.
#endif /* defined(_SUNOS_VTOC_8) */

	/*
	 * If the name's different, we're ok
	 */
	if (strcmp(pp1->pinfo_name, pp2->pinfo_name) != 0) {
		return;
	}

	/*
	 * Compare all the partitions' characteristics
	 */
	result = 0;
	map1 = pp1->pinfo_map;
	map2 = pp2->pinfo_map;
	for (i = 0; i < NDKMAP; i++, map1++, map2++) {
		result |= (map1->dkl_cylno != map2->dkl_cylno);
		result |= (map1->dkl_nblk != map2->dkl_nblk);
	}

	/*
	 * Compare the significant portions of the vtoc information
	 */
	vp1 = pp1->vtoc.v_part;
	vp2 = pp2->vtoc.v_part;
	for (i = 0; i < NDKMAP; i++, vp1++, vp2++) {
		result |= (vp1->p_tag != vp2->p_tag);
		result |= (vp1->p_flag != vp2->p_flag);
	}

	if (result) {
		err_print("Inconsistent definitions for partition type '%s'\n",
		    pp1->pinfo_name);
		if (pp1->pinfo_filename != NULL &&
		    pp2->pinfo_filename != NULL) {
			err_print("%s (%d) - %s (%d)\n",
			    pp1->pinfo_filename, pp1->pinfo_lineno,
			    pp2->pinfo_filename, pp2->pinfo_lineno);
		}
		fullabort();
	}
}

/*
 * Convert a string of digits into a block number.
 * The digits are assumed to be a block number unless the
 * the string is terminated by 'c', in which case it is
 * assumed to be in units of cylinders.  Accept a 'b'
 * to explictly specify blocks, for consistency.
 *
 * NB: uses the macro spc(), which requires that the
 * globals nhead/nsect/acyl be set up correctly.
 *
 * Returns -1 in the case of an error.
 */
static uint_t
str2blks(char *str)
{
	int	blks;
	char	*p;

	blks = (int)strtol(str, &p, 0);
	/*
	 * Check what terminated the conversion.
	 */
	if (*p != 0) {
		/*
		 * Units specifier of 'c': convert cylinders to blocks
		 */
		if (*p == 'c') {
			p++;
			blks = blks * spc();
		/*
		 * Ignore a 'b' specifier.
		 */
		} else if (*p == 'b') {
			p++;
		}
		/*
		 * Anthing left over is an error
		 */
		if (*p != 0) {
			blks = -1;
		}
	}

	return (blks);
}
/*
 * Convert a string of digits into a cylinder number.
 * Accept a an optional 'c' specifier, for consistency.
 *
 * Returns -1 in the case of an error.
 */
int
str2cyls(char *str)
{
	int	cyls;
	char	*p;

	cyls = (int)strtol(str, &p, 0);
	/*
	 * Check what terminated the conversion.
	 */
	if (*p != 0) {
		/*
		 * Units specifier of 'c': accept it.
		 */
		if (*p == 'c') {
			p++;
		}
		/*
		 * Anthing left over is an error
		 */
		if (*p != 0) {
			cyls = -1;
		}
	}

	return (cyls);
}


/*
 * Create a new chg_list structure, and append it onto the
 * end of the current chg_list under construction.  By
 * applying changes in the order in which listed in the
 * data file, the changes we make are deterministic.
 * Return a pointer to the new structure, so that the
 * caller can fill in the appropriate information.
 */
static struct chg_list *
new_chg_list(struct disk_type *disk)
{
	struct chg_list		*cp;
	struct chg_list		*nc;

	nc = zalloc(sizeof (struct chg_list));

	if (disk->dtype_chglist == NULL) {
		disk->dtype_chglist = nc;
	} else {
		for (cp = disk->dtype_chglist; cp->next; cp = cp->next)
			;
		cp->next = nc;
	}
	nc->next = NULL;
	return (nc);
}


/*
 * Follow symbolic links from the logical device name to
 * the /devfs physical device name.  To be complete, we
 * handle the case of multiple links.  This function
 * either returns NULL (no links, or some other error),
 * or the physical device name, alloc'ed on the heap.
 *
 * Note that the standard /devices prefix is stripped from
 * the final pathname, if present.  The trailing options
 * are also removed (":c, raw").
 */
static char *
get_physical_name(char *path)
{
	struct stat	stbuf;
	int		i;
	int		level;
	char		*p;
	char		s[MAXPATHLEN];
	char		buf[MAXPATHLEN];
	char		dir[MAXPATHLEN];
	char		savedir[MAXPATHLEN];
	char		*result = NULL;

	if (getcwd(savedir, sizeof (savedir)) == NULL) {
		err_print("getcwd() failed - %s\n", strerror(errno));
		return (NULL);
	}

	(void) strcpy(s, path);
	if ((p = strrchr(s, '/')) != NULL) {
		*p = 0;
	}
	if (s[0] == 0) {
		(void) strcpy(s, "/");
	}
	if (chdir(s) == -1) {
		err_print("cannot chdir() to %s - %s\n",
		    s, strerror(errno));
		goto exit;
	}

	level = 0;
	(void) strcpy(s, path);
	for (;;) {
		/*
		 * See if there's a real file out there.  If not,
		 * we have a dangling link and we ignore it.
		 */
		if (stat(s, &stbuf) == -1) {
			goto exit;
		}
		if (lstat(s, &stbuf) == -1) {
			err_print("%s: lstat() failed - %s\n",
			    s, strerror(errno));
			goto exit;
		}
		/*
		 * If the file is not a link, we're done one
		 * way or the other.  If there were links,
		 * return the full pathname of the resulting
		 * file.
		 */
		if (!S_ISLNK(stbuf.st_mode)) {
			if (level > 0) {
				/*
				 * Strip trailing options from the
				 * physical device name
				 */
				if ((p = strrchr(s, ':')) != NULL) {
					*p = 0;
				}
				/*
				 * Get the current directory, and
				 * glue the pieces together.
				 */
				if (getcwd(dir, sizeof (dir)) == NULL) {
					err_print("getcwd() failed - %s\n",
					    strerror(errno));
					goto exit;
				}
				(void) strcat(dir, "/");
				(void) strcat(dir, s);
				/*
				 * If we have the standard fixed
				 * /devices prefix, remove it.
				 */
				p = (strstr(dir, DEVFS_PREFIX) == dir) ?
				    dir+strlen(DEVFS_PREFIX) : dir;
				result = alloc_string(p);
			}
			goto exit;
		}
		i = readlink(s, buf, sizeof (buf));
		if (i == -1) {
			err_print("%s: readlink() failed - %s\n",
			    s, strerror(errno));
			goto exit;
		}
		level++;
		buf[i] = 0;

		/*
		 * Break up the pathname into the directory
		 * reference, if applicable and simple filename.
		 * chdir()'ing to the directory allows us to
		 * handle links with relative pathnames correctly.
		 */
		(void) strcpy(dir, buf);
		if ((p = strrchr(dir, '/')) != NULL) {
			*p = 0;
			if (chdir(dir) == -1) {
				err_print("cannot chdir() to %s - %s\n",
				    dir, strerror(errno));
				goto exit;
			}
			(void) strcpy(s, p+1);
		} else {
			(void) strcpy(s, buf);
		}
	}

exit:
	if (chdir(savedir) == -1) {
		err_print("cannot chdir() to %s - %s\n",
		    savedir, strerror(errno));
	}

	return (result);
}


static void
sort_disk_list(void)
{
	int			n;
	struct disk_info	**disks;
	struct disk_info	*d;
	struct disk_info	**dp;
	struct disk_info	**dp2;

	/*
	 * Count the number of disks in the list
	 */
	n = 0;
	for (d = disk_list; d != NULL; d = d->disk_next) {
		n++;
	}
	if (n == 0) {
		return;
	}

	/*
	 * Allocate a simple disk list array and fill it in
	 */
	disks = (struct disk_info **)
	    zalloc((n+1) * sizeof (struct disk_info *));

	dp = disks;
	for (d = disk_list; d != NULL; d = d->disk_next) {
		*dp++ = d;
	}
	*dp = NULL;

	/*
	 * Sort the disk list array
	 */
	qsort((void *) disks, n, sizeof (struct disk_info *),
	    disk_name_compare);

	/*
	 * Rebuild the linked list disk list structure
	 */
	dp = disks;
	disk_list = *dp;
	dp2 = dp + 1;
	do {
		(*dp++)->disk_next = *dp2++;
	} while (*dp != NULL);

	/*
	 * Clean up
	 */
	(void) destroy_data((void *)disks);
}


/*
 * Compare two disk names
 */
static int
disk_name_compare(
	const void	*arg1,
	const void	*arg2)
{
	char		*s1;
	char		*s2;
	int		n1;
	int		n2;
	char		*p1;
	char		*p2;

	s1 = (*((struct disk_info **)arg1))->disk_name;
	s2 = (*((struct disk_info **)arg2))->disk_name;

	for (;;) {
		if (*s1 == 0 || *s2 == 0)
			break;
		if (isdigit(*s1) && isdigit(*s2)) {
			n1 = strtol(s1, &p1, 10);
			n2 = strtol(s2, &p2, 10);
			if (n1 != n2) {
				return (n1 - n2);
			}
			s1 = p1;
			s2 = p2;
		} else if (*s1 != *s2) {
			break;
		} else {
			s1++;
			s2++;
		}
	}

	return (*s1 - *s2);
}

static void
make_controller_list(void)
{
	int	x;
	struct	mctlr_list	*ctlrp;

	ctlrp = controlp;

	for (x = nctypes; x != 0; x--) {
		ctlrp = zalloc(sizeof (struct mctlr_list));
		ctlrp->next = controlp;
		ctlrp->ctlr_type = &ctlr_types[x - 1];
		controlp = ctlrp;

	}
}

static void
check_for_duplicate_disknames(char *arglist[])
{
	char			*directory = "/dev/rdsk/";
	char			**disklist;
	int			len;
	char			s[MAXPATHLEN], t[MAXPATHLEN];
	int			diskno = 0;
	int			i;


	len = strlen(directory);
	disklist = arglist;
	for (; *disklist != NULL; disklist++) {
		if (strncmp(directory, *disklist, len) == 0) {
			/* Disk is in conventional format */
			canonicalize_name(s, *disklist);
			/*
			 *  check if the disk is already present in
			 *  disk list.
			 */
			for (i = 0; i < diskno; i++) {
				canonicalize_name(t, arglist[i]);
				if (strncmp(s, t, strlen(t)) == 0)
					break;
			}
			if (i != diskno)
				continue;
		}
		(void) strcpy(arglist[diskno], *disklist);
		diskno++;
	}
	arglist[diskno] = NULL;
}

#define	DISK_PREFIX	"/dev/rdsk/"

/*
 * This Function checks if the non-conventional name is a a link to
 * one of the conventional whole disk name.
 */
static int
name_represents_wholedisk(char	*name)
{
	char	symname[MAXPATHLEN];
	char	localname[MAXPATHLEN];
	char	*nameptr;
	ssize_t symname_size;

	if (strlcpy(localname, name, MAXPATHLEN) >= MAXPATHLEN)
		return (1); /* buffer overflow, reject this name */

	while ((symname_size = readlink(
	    localname, symname, MAXPATHLEN - 1)) != -1) {
		symname[symname_size] = '\0';
		nameptr = symname;
		if (strncmp(symname, DISK_PREFIX,
		    (sizeof (DISK_PREFIX) - 1)) == 0)
			nameptr += (sizeof (DISK_PREFIX) - 1);

		if (conventional_name(nameptr)) {
			if (whole_disk_name(nameptr))
				return (0);
			else
				return (1);
		}

		(void) strcpy(localname, symname);
	}
	return (0);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright (c) 1991-2001 by Sun Microsystems, Inc.
 */

#ifndef	_STARTUP_H
#define	_STARTUP_H

#ifdef	__cplusplus
extern "C" {
#endif

/*
 * This file contains declarations pertaining to reading the data file.
 */
/*
 * The definitions are the token types that the data file parser recognizes.
 */
#define	SUP_EOF			-1		/* eof token */
#define	SUP_STRING		0		/* string token */
#define	SUP_EQL			1		/* equals token */
#define	SUP_COMMA		2		/* comma token */
#define	SUP_COLON		3		/* colon token */
#define	SUP_EOL			4		/* newline token */
#define	SUP_OR			5		/* vertical bar */
#define	SUP_AND			6		/* ampersand */
#define	SUP_TILDE		7		/* tilde */

/*
 * These definitions are flags for the legal keywords in the data file.
 * They are used to keep track of what parameters appear on the current
 * line in the file.
 */
#define	SUP_CTLR		0x00000001	/* set ctlr */
#define	SUP_DISK		0x00000002	/* set disk */
#define	SUP_NCYL		0x00000004	/* set ncyl */
#define	SUP_ACYL		0x00000008	/* set acyl */
#define	SUP_PCYL		0x00000010	/* set pcyl */
#define	SUP_NHEAD		0x00000020	/* set nhead */
#define	SUP_NSECT		0x00000040	/* set nsect */
#define	SUP_RPM			0x00000080	/* set rpm */
#define	SUP_BPT			0x00000100	/* set bytes/track */
#define	SUP_BPS			0x00000200	/* set bytes/sector */
#define	SUP_DRTYPE		0x00000400	/* set drive type */

#define	SUP_READ_RETRIES	0x00000800	/* set read retries */
#define	SUP_WRITE_RETRIES	0x00001000	/* set write retries */

#define	SUP_TRKS_ZONE		0x00002000	/* set tracks/zone */
#define	SUP_ATRKS		0x00004000	/* set alt. tracks */
#define	SUP_ASECT		0x00008000	/* set sectors/zone */
#define	SUP_CACHE		0x00010000	/* set cache size */
#define	SUP_PREFETCH		0x00020000	/* set prefetch threshold */
#define	SUP_CACHE_MIN		0x00040000	/* set min. prefetch */
#define	SUP_CACHE_MAX		0x00080000	/* set max. prefetch */
#define	SUP_PSECT		0x00100000	/* set physical sectors */
#define	SUP_PHEAD		0x00200000	/* set physical heads */
#define	SUP_FMTTIME		0x00400000	/* set format time */
#define	SUP_CYLSKEW		0x00800000	/* set cylinder skew */
#define	SUP_TRKSKEW		0x01000000	/* set track skew */


/*
 * The define the minimum set of parameters necessary to declare a disk
 * and a partition map in the data file.  Depending on the ctlr type,
 * more info than this may be necessary for declaring disks.
 */
#define	SUP_MIN_DRIVE   (SUP_CTLR | SUP_RPM | SUP_PCYL | \
			SUP_NCYL | SUP_ACYL | SUP_NHEAD | SUP_NSECT)

#define	SUP_MIN_PART	0x0003			/* for maps */


/*
 *	Prototypes for ANSI C compilers
 */
int	do_options(int argc, char *argv[]);
void	sup_init(void);
int	open_disk(char *diskname, int flags);
void	do_search(char *arglist[]);
int	dtype_match(struct dk_label *label, struct disk_type *dtype);
int	parts_match(struct dk_label *label, struct partition_info *pinfo);
int	diskname_match(char *name, struct disk_info *disk);



#ifdef	__cplusplus
}
#endif

#endif	/* _STARTUP_H */