|
root / base / usr / src / stand / lib
lib Plain Text 32988 lines 850.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
30840
30841
30842
30843
30844
30845
30846
30847
30848
30849
30850
30851
30852
30853
30854
30855
30856
30857
30858
30859
30860
30861
30862
30863
30864
30865
30866
30867
30868
30869
30870
30871
30872
30873
30874
30875
30876
30877
30878
30879
30880
30881
30882
30883
30884
30885
30886
30887
30888
30889
30890
30891
30892
30893
30894
30895
30896
30897
30898
30899
30900
30901
30902
30903
30904
30905
30906
30907
30908
30909
30910
30911
30912
30913
30914
30915
30916
30917
30918
30919
30920
30921
30922
30923
30924
30925
30926
30927
30928
30929
30930
30931
30932
30933
30934
30935
30936
30937
30938
30939
30940
30941
30942
30943
30944
30945
30946
30947
30948
30949
30950
30951
30952
30953
30954
30955
30956
30957
30958
30959
30960
30961
30962
30963
30964
30965
30966
30967
30968
30969
30970
30971
30972
30973
30974
30975
30976
30977
30978
30979
30980
30981
30982
30983
30984
30985
30986
30987
30988
30989
30990
30991
30992
30993
30994
30995
30996
30997
30998
30999
31000
31001
31002
31003
31004
31005
31006
31007
31008
31009
31010
31011
31012
31013
31014
31015
31016
31017
31018
31019
31020
31021
31022
31023
31024
31025
31026
31027
31028
31029
31030
31031
31032
31033
31034
31035
31036
31037
31038
31039
31040
31041
31042
31043
31044
31045
31046
31047
31048
31049
31050
31051
31052
31053
31054
31055
31056
31057
31058
31059
31060
31061
31062
31063
31064
31065
31066
31067
31068
31069
31070
31071
31072
31073
31074
31075
31076
31077
31078
31079
31080
31081
31082
31083
31084
31085
31086
31087
31088
31089
31090
31091
31092
31093
31094
31095
31096
31097
31098
31099
31100
31101
31102
31103
31104
31105
31106
31107
31108
31109
31110
31111
31112
31113
31114
31115
31116
31117
31118
31119
31120
31121
31122
31123
31124
31125
31126
31127
31128
31129
31130
31131
31132
31133
31134
31135
31136
31137
31138
31139
31140
31141
31142
31143
31144
31145
31146
31147
31148
31149
31150
31151
31152
31153
31154
31155
31156
31157
31158
31159
31160
31161
31162
31163
31164
31165
31166
31167
31168
31169
31170
31171
31172
31173
31174
31175
31176
31177
31178
31179
31180
31181
31182
31183
31184
31185
31186
31187
31188
31189
31190
31191
31192
31193
31194
31195
31196
31197
31198
31199
31200
31201
31202
31203
31204
31205
31206
31207
31208
31209
31210
31211
31212
31213
31214
31215
31216
31217
31218
31219
31220
31221
31222
31223
31224
31225
31226
31227
31228
31229
31230
31231
31232
31233
31234
31235
31236
31237
31238
31239
31240
31241
31242
31243
31244
31245
31246
31247
31248
31249
31250
31251
31252
31253
31254
31255
31256
31257
31258
31259
31260
31261
31262
31263
31264
31265
31266
31267
31268
31269
31270
31271
31272
31273
31274
31275
31276
31277
31278
31279
31280
31281
31282
31283
31284
31285
31286
31287
31288
31289
31290
31291
31292
31293
31294
31295
31296
31297
31298
31299
31300
31301
31302
31303
31304
31305
31306
31307
31308
31309
31310
31311
31312
31313
31314
31315
31316
31317
31318
31319
31320
31321
31322
31323
31324
31325
31326
31327
31328
31329
31330
31331
31332
31333
31334
31335
31336
31337
31338
31339
31340
31341
31342
31343
31344
31345
31346
31347
31348
31349
31350
31351
31352
31353
31354
31355
31356
31357
31358
31359
31360
31361
31362
31363
31364
31365
31366
31367
31368
31369
31370
31371
31372
31373
31374
31375
31376
31377
31378
31379
31380
31381
31382
31383
31384
31385
31386
31387
31388
31389
31390
31391
31392
31393
31394
31395
31396
31397
31398
31399
31400
31401
31402
31403
31404
31405
31406
31407
31408
31409
31410
31411
31412
31413
31414
31415
31416
31417
31418
31419
31420
31421
31422
31423
31424
31425
31426
31427
31428
31429
31430
31431
31432
31433
31434
31435
31436
31437
31438
31439
31440
31441
31442
31443
31444
31445
31446
31447
31448
31449
31450
31451
31452
31453
31454
31455
31456
31457
31458
31459
31460
31461
31462
31463
31464
31465
31466
31467
31468
31469
31470
31471
31472
31473
31474
31475
31476
31477
31478
31479
31480
31481
31482
31483
31484
31485
31486
31487
31488
31489
31490
31491
31492
31493
31494
31495
31496
31497
31498
31499
31500
31501
31502
31503
31504
31505
31506
31507
31508
31509
31510
31511
31512
31513
31514
31515
31516
31517
31518
31519
31520
31521
31522
31523
31524
31525
31526
31527
31528
31529
31530
31531
31532
31533
31534
31535
31536
31537
31538
31539
31540
31541
31542
31543
31544
31545
31546
31547
31548
31549
31550
31551
31552
31553
31554
31555
31556
31557
31558
31559
31560
31561
31562
31563
31564
31565
31566
31567
31568
31569
31570
31571
31572
31573
31574
31575
31576
31577
31578
31579
31580
31581
31582
31583
31584
31585
31586
31587
31588
31589
31590
31591
31592
31593
31594
31595
31596
31597
31598
31599
31600
31601
31602
31603
31604
31605
31606
31607
31608
31609
31610
31611
31612
31613
31614
31615
31616
31617
31618
31619
31620
31621
31622
31623
31624
31625
31626
31627
31628
31629
31630
31631
31632
31633
31634
31635
31636
31637
31638
31639
31640
31641
31642
31643
31644
31645
31646
31647
31648
31649
31650
31651
31652
31653
31654
31655
31656
31657
31658
31659
31660
31661
31662
31663
31664
31665
31666
31667
31668
31669
31670
31671
31672
31673
31674
31675
31676
31677
31678
31679
31680
31681
31682
31683
31684
31685
31686
31687
31688
31689
31690
31691
31692
31693
31694
31695
31696
31697
31698
31699
31700
31701
31702
31703
31704
31705
31706
31707
31708
31709
31710
31711
31712
31713
31714
31715
31716
31717
31718
31719
31720
31721
31722
31723
31724
31725
31726
31727
31728
31729
31730
31731
31732
31733
31734
31735
31736
31737
31738
31739
31740
31741
31742
31743
31744
31745
31746
31747
31748
31749
31750
31751
31752
31753
31754
31755
31756
31757
31758
31759
31760
31761
31762
31763
31764
31765
31766
31767
31768
31769
31770
31771
31772
31773
31774
31775
31776
31777
31778
31779
31780
31781
31782
31783
31784
31785
31786
31787
31788
31789
31790
31791
31792
31793
31794
31795
31796
31797
31798
31799
31800
31801
31802
31803
31804
31805
31806
31807
31808
31809
31810
31811
31812
31813
31814
31815
31816
31817
31818
31819
31820
31821
31822
31823
31824
31825
31826
31827
31828
31829
31830
31831
31832
31833
31834
31835
31836
31837
31838
31839
31840
31841
31842
31843
31844
31845
31846
31847
31848
31849
31850
31851
31852
31853
31854
31855
31856
31857
31858
31859
31860
31861
31862
31863
31864
31865
31866
31867
31868
31869
31870
31871
31872
31873
31874
31875
31876
31877
31878
31879
31880
31881
31882
31883
31884
31885
31886
31887
31888
31889
31890
31891
31892
31893
31894
31895
31896
31897
31898
31899
31900
31901
31902
31903
31904
31905
31906
31907
31908
31909
31910
31911
31912
31913
31914
31915
31916
31917
31918
31919
31920
31921
31922
31923
31924
31925
31926
31927
31928
31929
31930
31931
31932
31933
31934
31935
31936
31937
31938
31939
31940
31941
31942
31943
31944
31945
31946
31947
31948
31949
31950
31951
31952
31953
31954
31955
31956
31957
31958
31959
31960
31961
31962
31963
31964
31965
31966
31967
31968
31969
31970
31971
31972
31973
31974
31975
31976
31977
31978
31979
31980
31981
31982
31983
31984
31985
31986
31987
31988
31989
31990
31991
31992
31993
31994
31995
31996
31997
31998
31999
32000
32001
32002
32003
32004
32005
32006
32007
32008
32009
32010
32011
32012
32013
32014
32015
32016
32017
32018
32019
32020
32021
32022
32023
32024
32025
32026
32027
32028
32029
32030
32031
32032
32033
32034
32035
32036
32037
32038
32039
32040
32041
32042
32043
32044
32045
32046
32047
32048
32049
32050
32051
32052
32053
32054
32055
32056
32057
32058
32059
32060
32061
32062
32063
32064
32065
32066
32067
32068
32069
32070
32071
32072
32073
32074
32075
32076
32077
32078
32079
32080
32081
32082
32083
32084
32085
32086
32087
32088
32089
32090
32091
32092
32093
32094
32095
32096
32097
32098
32099
32100
32101
32102
32103
32104
32105
32106
32107
32108
32109
32110
32111
32112
32113
32114
32115
32116
32117
32118
32119
32120
32121
32122
32123
32124
32125
32126
32127
32128
32129
32130
32131
32132
32133
32134
32135
32136
32137
32138
32139
32140
32141
32142
32143
32144
32145
32146
32147
32148
32149
32150
32151
32152
32153
32154
32155
32156
32157
32158
32159
32160
32161
32162
32163
32164
32165
32166
32167
32168
32169
32170
32171
32172
32173
32174
32175
32176
32177
32178
32179
32180
32181
32182
32183
32184
32185
32186
32187
32188
32189
32190
32191
32192
32193
32194
32195
32196
32197
32198
32199
32200
32201
32202
32203
32204
32205
32206
32207
32208
32209
32210
32211
32212
32213
32214
32215
32216
32217
32218
32219
32220
32221
32222
32223
32224
32225
32226
32227
32228
32229
32230
32231
32232
32233
32234
32235
32236
32237
32238
32239
32240
32241
32242
32243
32244
32245
32246
32247
32248
32249
32250
32251
32252
32253
32254
32255
32256
32257
32258
32259
32260
32261
32262
32263
32264
32265
32266
32267
32268
32269
32270
32271
32272
32273
32274
32275
32276
32277
32278
32279
32280
32281
32282
32283
32284
32285
32286
32287
32288
32289
32290
32291
32292
32293
32294
32295
32296
32297
32298
32299
32300
32301
32302
32303
32304
32305
32306
32307
32308
32309
32310
32311
32312
32313
32314
32315
32316
32317
32318
32319
32320
32321
32322
32323
32324
32325
32326
32327
32328
32329
32330
32331
32332
32333
32334
32335
32336
32337
32338
32339
32340
32341
32342
32343
32344
32345
32346
32347
32348
32349
32350
32351
32352
32353
32354
32355
32356
32357
32358
32359
32360
32361
32362
32363
32364
32365
32366
32367
32368
32369
32370
32371
32372
32373
32374
32375
32376
32377
32378
32379
32380
32381
32382
32383
32384
32385
32386
32387
32388
32389
32390
32391
32392
32393
32394
32395
32396
32397
32398
32399
32400
32401
32402
32403
32404
32405
32406
32407
32408
32409
32410
32411
32412
32413
32414
32415
32416
32417
32418
32419
32420
32421
32422
32423
32424
32425
32426
32427
32428
32429
32430
32431
32432
32433
32434
32435
32436
32437
32438
32439
32440
32441
32442
32443
32444
32445
32446
32447
32448
32449
32450
32451
32452
32453
32454
32455
32456
32457
32458
32459
32460
32461
32462
32463
32464
32465
32466
32467
32468
32469
32470
32471
32472
32473
32474
32475
32476
32477
32478
32479
32480
32481
32482
32483
32484
32485
32486
32487
32488
32489
32490
32491
32492
32493
32494
32495
32496
32497
32498
32499
32500
32501
32502
32503
32504
32505
32506
32507
32508
32509
32510
32511
32512
32513
32514
32515
32516
32517
32518
32519
32520
32521
32522
32523
32524
32525
32526
32527
32528
32529
32530
32531
32532
32533
32534
32535
32536
32537
32538
32539
32540
32541
32542
32543
32544
32545
32546
32547
32548
32549
32550
32551
32552
32553
32554
32555
32556
32557
32558
32559
32560
32561
32562
32563
32564
32565
32566
32567
32568
32569
32570
32571
32572
32573
32574
32575
32576
32577
32578
32579
32580
32581
32582
32583
32584
32585
32586
32587
32588
32589
32590
32591
32592
32593
32594
32595
32596
32597
32598
32599
32600
32601
32602
32603
32604
32605
32606
32607
32608
32609
32610
32611
32612
32613
32614
32615
32616
32617
32618
32619
32620
32621
32622
32623
32624
32625
32626
32627
32628
32629
32630
32631
32632
32633
32634
32635
32636
32637
32638
32639
32640
32641
32642
32643
32644
32645
32646
32647
32648
32649
32650
32651
32652
32653
32654
32655
32656
32657
32658
32659
32660
32661
32662
32663
32664
32665
32666
32667
32668
32669
32670
32671
32672
32673
32674
32675
32676
32677
32678
32679
32680
32681
32682
32683
32684
32685
32686
32687
32688
32689
32690
32691
32692
32693
32694
32695
32696
32697
32698
32699
32700
32701
32702
32703
32704
32705
32706
32707
32708
32709
32710
32711
32712
32713
32714
32715
32716
32717
32718
32719
32720
32721
32722
32723
32724
32725
32726
32727
32728
32729
32730
32731
32732
32733
32734
32735
32736
32737
32738
32739
32740
32741
32742
32743
32744
32745
32746
32747
32748
32749
32750
32751
32752
32753
32754
32755
32756
32757
32758
32759
32760
32761
32762
32763
32764
32765
32766
32767
32768
32769
32770
32771
32772
32773
32774
32775
32776
32777
32778
32779
32780
32781
32782
32783
32784
32785
32786
32787
32788
32789
32790
32791
32792
32793
32794
32795
32796
32797
32798
32799
32800
32801
32802
32803
32804
32805
32806
32807
32808
32809
32810
32811
32812
32813
32814
32815
32816
32817
32818
32819
32820
32821
32822
32823
32824
32825
32826
32827
32828
32829
32830
32831
32832
32833
32834
32835
32836
32837
32838
32839
32840
32841
32842
32843
32844
32845
32846
32847
32848
32849
32850
32851
32852
32853
32854
32855
32856
32857
32858
32859
32860
32861
32862
32863
32864
32865
32866
32867
32868
32869
32870
32871
32872
32873
32874
32875
32876
32877
32878
32879
32880
32881
32882
32883
32884
32885
32886
32887
32888
32889
32890
32891
32892
32893
32894
32895
32896
32897
32898
32899
32900
32901
32902
32903
32904
32905
32906
32907
32908
32909
32910
32911
32912
32913
32914
32915
32916
32917
32918
32919
32920
32921
32922
32923
32924
32925
32926
32927
32928
32929
32930
32931
32932
32933
32934
32935
32936
32937
32938
32939
32940
32941
32942
32943
32944
32945
32946
32947
32948
32949
32950
32951
32952
32953
32954
32955
32956
32957
32958
32959
32960
32961
32962
32963
32964
32965
32966
32967
32968
32969
32970
32971
32972
32973
32974
32975
32976
32977
32978
32979
32980
32981
32982
32983
32984
32985
32986
32987
#
# 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 2014 Gary Mills
#
# Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

include Makefile.com

i386_SUBDIRS =
# Hammerhead: sparc_SUBDIRS removed - amd64 only build
SUBDIRS = fs/hsfs fs/nfs fs/ufs inet sa sock tcpstubs xdr \
	tcp $($(MACH)_SUBDIRS)

.PARALLEL: $(SUBDIRS)

.KEEP_STATE:

all	:	TARGET = all
clean	:	TARGET = clean
clobber	:	TARGET = clobber
install	:	TARGET = install

all clean clobber install: $(SUBDIRS)

$(SUBDIRS): FRC
	cd $@; pwd; $(MAKE) $(TARGET)

FRC:

#
# Cross-reference customization: set the include path to be reasonable.
#
XRINCDIRS = $(CPPINCS:-YI,%=-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 2009 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

#
# Common macro definitions and pattern rules for stand libraries.
# Basically just a trivial wrapper around $(SRC)/lib/Makefile.lib.
#

include $(SRC)/lib/Makefile.lib
include $(SRC)/stand/lib/Makefile.$(MACH)

SRCDIR =	.
LIBS +=		$(LIBRARY)
CFLAGS +=	$(CCVERBOSE)
LDFLAGS =	-r
LDLIBS +=	-lsa

#
# Reset ROOTLIBDIR to an alternate directory so that we don't clash with
# $(ROOT)/usr/lib.  The Makefiles over in usr/src/psm expect to find our
# libraries here.
#
ROOTLIBDIR = $(ROOT)/stand/lib

#
# Paths to a variety of commonly-referenced directories.  Note that we use
# relative paths so that references to filenames in the source (e.g.,
# through use of assert()) are not exposed absolutely (for reasons of
# taste and to help make the binaries end up the same even when built from
# different workspaces).  Makefiles that are more than one directory level
# deeper than this Makefile need to set DIRREL appropriately so that the
# relative paths can still be accessed correctly.
#
TOPDIR =	$(DIRREL)../../..
STANDDIR =	$(DIRREL)../..
CMNNETDIR =	$(TOPDIR)/common/net
SYSDIR	=	$(TOPDIR)/uts

#
# As a courtesy to the numerous standalone libraries which are built from
# sources living elsewhere, we provide a generic CMNDIR macro which the
# library's Makefile can set (if need be) to the primary other directory
# it grabs its sources from.
#
CMNDIR =	.

#
# Configure the appropriate #defines and #include path for building
# standalone bits.  Note that we turn off access to /usr/include and
# the proto area since those headers match libc's implementation, and
# libc is of course not available to standalone binaries.
#
CPPDEFS	=	-D$(KARCH) -D_BOOT -D_KERNEL -D_MACHDEP
CPPINCS	=	-YI,$(STANDDIR)/lib/sa -I$(STANDDIR)/lib/sa \
		-I$(STANDDIR) -I$(SRCDIR) -I$(CMNDIR) \
		-I$(STANDDIR)/$(MACH) -I$(SYSDIR)/common $(ARCHDIRS) \
		-I$(SYSDIR)/sun4 -I$(SYSDIR)/$(KARCH)

CPPFLAGS =	$(CPPDEFS) $(CPPINCS)
AS_CPPFLAGS =	$(CPPDEFS) $(CPPINCS:-YI,%=-I%)
ASFLAGS =	-D__STDC__ -D_ASM

#
# CPPFLAGS values that *must* be included whenever linking with or
# building libssl or libcrypto.
# Exclusions here are for both legal and size reasons.
#
OPENSSL_SRC = ../../../common/openssl
OPENSSL_BUILD_CPPFLAGS_sparc = -DB_ENDIAN
OPENSSL_BUILD_CPPFLAGS = -DOPENSSL_NO_ECDH -DOPENSSL_NO_ECDSA \
			-DOPENSSL_NO_HW_4758_CCA -DOPENSSL_NO_HW_AEP \
			-DOPENSSL_NO_HW_ATALLA -DOPENSSL_NO_HW_CHIL \
			-DOPENSSL_NO_HW_CSWIFT -DOPENSSL_NO_HW_GMP \
			-DOPENSSL_NO_HW_NURON -DOPENSSL_NO_HW_PADLOCK \
			-DOPENSSL_NO_HW_SUREWARE -DOPENSSL_NO_HW_UBSEC \
			-DOPENSSL_NO_HW \
			-DOPENSSL_NO_MD2 -DOPENSSL_NO_MD4 -DOPENSSL_NO_MDC2 \
			-DOPENSSL_NO_RIPEMD -DOPENSSL_NO_RC3 -DOPENSSL_NO_RC4 \
			-DOPENSSL_NO_EC -DOPENSSL_NO_RC5 -DOPENSSL_NO_IDEA \
			-DOPENSSL_NO_CAST -DOPENSSL_NO_AES \
			-DDEVRANDOM=\"/dev/urandom\" \
			-I.. \
			$(OPENSSL_BUILD_CPPFLAGS_$(MACH)) \
			-I$(ROOT)/usr/include \
			-I$(OPENSSL_SRC) -I$(OPENSSL_SRC)/crypto

#
# CPPFLAGS values that *must* be included whenever linking the DHCP
# routines in $SRC/common/net/dhcp.
#
DHCPCPPFLAGS = -I$(CMNNETDIR)/dhcp

#
# CPPFLAGS values that *must* be included whenever linking with or
# building libsock.
#
# The header files for libsock provide alternate definitions for data
# types that are also defined in <sys/stream.h>.  To make sure we get the
# right ones, prevent <sys/stream.h>'s contents from being included.  This
# is shameful.
#
SOCKCPPFLAGS = -I$(STANDDIR)/lib/sock -D_SYS_STREAM_H

#
# Using Makefile.lib pulls in the stack protector. Explicitly disable it
# as it is not initialized or supported in this environment currently.
#
STACKPROTECT = none

.KEEP_STATE:
#
# 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.
#

#
# We only support 64-bit builds on SPARC, so this is simple.
#
KARCH =	sun4u
ARCHDIRS = -I$(SYSDIR)/sparc -I$(SYSDIR)/sparc/v9 -I$(SYSDIR)/sun

include $(SRC)/psm/Makefile.psm.64

CFLAGS64 += -xchip=ultra
#
# 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 2006 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# ident	"%Z%%M%	%I%	%E% SMI"
#

all alllibs: $(LIBS)

clean:
	$(RM) $(OBJS) $(CLEANFILES)

clobber: clean
	$(RM) $(LIBS) $(CLOBBERFILES)

install: all .WAIT $(ROOTLIBDIR) .WAIT $(ROOTLIBS)

lint lintcheck: $$(SRCS)
	$(LINT.c) $(SRCS) -L$(ROOTLIBDIR) $(LDLIBS)

objs:
	-@mkdir -p $@

$(LIBRARY): objs .WAIT $$(OBJS)
	$(BUILD.AR)
	$(POST_PROCESS_A)

$(LINTLIB): $$(SRCS)
	$(LINT.c) -o $(LIBNAME) $(SRCS) 2>&1 

objs/%.o: $(SRCDIR)/%.c
	$(COMPILE.c) -o $@ $<
	$(POST_PROCESS_O)

objs/%.o: $(CMNDIR)/%.c
	$(COMPILE.c) -o $@ $<
	$(POST_PROCESS_O)

objs/%.o: $(SHA1DIR)/%.c
	$(COMPILE.c) -o $@ $<
	$(POST_PROCESS_O)

$(ROOTLIBDIR):
	$(INS.dir)

$(ROOTLIBDIR)/%: %
	$(INS.file)
#
# 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 2003 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

DIRREL	= ../

include ../../Makefile.com

#
# Right now, the filesystem modules are only clean when -y is used -- some
# needs to go finish cleaning them up, at which point this can be removed.
#
lint lintcheck : LINTFLAGS += -y

CERRWARN += -Wno-type-limits
CERRWARN += -Wno-parentheses
CERRWARN += $(CNOWARN_UNINIT)
CERRWARN += -Wno-switch
CERRWARN += -Wno-char-subscripts
/*
 * 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 2004 Sun Microsystems, Inc.  All rights reserved.
 *  Use is subject to license terms.
 *
 *  This is mostly new code.  Major revisions were made to allow multiple
 *  file systems to share a common cache.  While this consisted primarily
 *  of including a "devid_t" pointer in the hash functions, I also re-
 *  organized everything to eliminate much of the duplicated code that
 *  had existed previously.
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#include <sys/param.h>
#include <sys/vnode.h>
#include <sys/sysmacros.h>
#include <sys/filep.h>
#include <sys/salib.h>
#include <sys/promif.h>

#ifndef	ICACHE_SIZE
/*
 *  These should probably be defined in an architecture-specific header
 *  file.  The values below are analogous to those used in earlier versions
 *  of this module.
 */

#define	ICACHE_SIZE 350	    /* Max number of I-node in file cache	*/
#define	DCACHE_SIZE 1500    /* Max number of cached directories		*/
#define	BCACHE_SIZE 250	    /* Max number of cached disk blocks		*/
#endif

#define	Next 0		    /* Next pointer in Fwd/Bak link		*/
#define	Prev 1		    /* Previous pointer in Fwd/Back links	*/

#define	Frst 0		    /* Ptr to first element of a chain		*/
#define	Last 1		    /* Ptr to last element of a chain		*/

#define	Hash 2		    /* Offset of hash chain ptrs.		*/

typedef struct cache {	    /* Generic cache element:			*/
    struct cache *link[4];  /* .. Fwd/Bak links for hash chain & LRU	*/
    struct cache **chn;	    /* .. Hash chain link			*/
    int		   dev;	    /* .. Device file handle			*/
    void	 *data;	    /* .. Ptr to associated data		*/
    int		  size;	    /* .. Size of cached data			*/
} cache_t;

typedef struct head {	    /* Generic cache header:			*/
	cache_t	   *aged[2];	/* .. LRU list				*/
	int (*cmp)(cache_t *);	/* .. Ptr to comparison function	*/
	int	  size;		/* .. Size of "cache" objects		*/
	int	  maxblks;	/* .. Max number of cached elements	*/
	int	  count;	/* .. Current number of cached elements	*/
	int	  hits;		/* .. Total cache hits			*/
	int	  searches;	/* .. Total searches			*/
	int	  purges;	/* .. Total purges			*/
} head_t;

/* Constructor for cache headers:					*/
#define	cache_head(h, f, t, n) \
	{{(cache_t *)&h, (cache_t *)&h}, f, sizeof (t), n}

int read_opt;		/* Number of times cache was bypassed	*/
static int x_dev;	/* Target device ID saved here!		*/
static int x_len;	/* length of object			*/

#define	LOG2(x) \
	(((x) <= 16)  ?	 4 : /* Yeah, it's ugly.  But it works! */ \
	(((x) <= 32)  ?  5 : /* .. Binary log should be part of */ \
	(((x) <= 64)  ?  6 : /* .. the language!		*/ \
	(((x) <= 128) ?	 7 : 8))))

static cache_t *
get_cache(cache_t *cap, head_t *chp)
{
	/*
	 *  Search cache:
	 *
	 *  The caller pass a pointer to the first "cache" object in the current
	 *  hash chain ["cap"] and a pointer to the corresponding cache header
	 *  ["chp"].  This routine follows the cache chain until it finds an
	 *  entry that matches both the current device [as noted in "x_dev"]
	 *  and the cache-specific comparison ["chp->cmp"].
	 *
	 *  Returns the address of the matching cache object or null if there
	 *  is none.
	 */

	while (cap) {
		/*
		 * Check all entries on the cache chain.  We expect
		 * chains to be relatively short, so we use a simple
		 * linear search.
		 */
		if ((x_dev == cap->dev) && (*chp->cmp)(cap)) {
			/*
			 * Found the entry we're looking for! Move it
			 * to the front of the cache header's LRU list
			 * before returing its addres to the caller.
			 */
			cap->link[Next]->link[Prev] = cap->link[Prev];
			cap->link[Prev]->link[Next] = cap->link[Next];

			cap->link[Prev] = (cache_t *)chp->aged;
			cap->link[Next] = chp->aged[Frst];
			chp->aged[Frst]->link[Prev] = cap;
			chp->aged[Frst] = cap;
			chp->hits += 1;
			break;
		}

		cap = cap->link[Hash+Next];
	}

	chp->searches += 1;
	return (cap);
}

static cache_t *
reclaim_cache(head_t *chp, int dev)
{
	/*
	 * Reclaim a cache element:
	 *
	 * This routine is used to: [a] free the oldest element from
	 * the cache headed at "chp" and return the address of the
	 * corresponding "cache_t" struct (iff dev == -1), or [b] free all
	 * elements on the cache headed at "chp" that belong to the
	 * indicated "dev"ice.
	 */
	cache_t *cap, *cxp;
	cache_t *cpp = (cache_t *)chp;

	while ((cap = cpp->link[Prev]) != (cache_t *)chp) {
		/*
		 * We follow the cache's LRU chain from oldest to
		 * newest member.  This ensures that we remove only
		 * the oldest element when we're called with a
		 * negative "dev" argument.
		 */
		if ((dev == -1) || (dev == cap->dev)) {
			/*
			 * This is one of the (perhaps the only)
			 * elements we're supposed to free.  Remove it
			 * from both the LRU list and its associated
			 * hash chain.  Then free the data bound the
			 * the cache_t element and, if "dev" is
			 * not -1, the element itself!
			 */
			cap->link[Prev]->link[Next] = cap->link[Next];
			cap->link[Next]->link[Prev] = cap->link[Prev];

			if ((cxp = cap->link[Hash+Prev]) != 0)
				cxp->link[Hash+Next] = cap->link[Hash+Next];
			else
				*(cap->chn) = cap->link[Hash+Next];

			if ((cxp = cap->link[Hash+Next]) != 0)
				cxp->link[Hash+Prev] = cap->link[Hash+Prev];

			bkmem_free((caddr_t)cap->data, cap->size);
			if (dev == -1)
				return (cap);

			bkmem_free((caddr_t)cap, chp->size);
			chp->count -= 1;

		} else {
			/*
			 * Skip this element, it's not one of the
			 * ones we want to free up.
			 */
			cpp = cap;
		}
	};

	return (0);
}

static cache_t *
set_cache(cache_t **ccp, head_t *chp, int noreclaim)
{
	/*
	 *  Install a cache element:
	 *
	 *  The caller passes the address of cache descriptor ["chp"] and the
	 *  hash chain into which the new element is to be linked ["ccp"].  This
	 *  routine allocates a new cache_t structure (or, if the maximum number
	 *  of elements has already been allocated, reclaims the oldest element
	 *  from the cache), links it into the indicated hash chain, and returns
	 *  its address to the caller.
	 */
	cache_t *cap;

	if ((chp->count < chp->maxblks) &&
	    (cap = (cache_t *)bkmem_alloc(chp->size))) {
		/*
		 * We haven't reached the maximum cache size yet.
		 * Allocate a new "cache_t" struct to be added to the
		 * cache.
		 */
		chp->count += 1;

	} else {
		if (noreclaim)
			return (NULL);

		/*
		 * Cache is full.  Use the "reclaim_cache" routine to
		 * remove the oldest element from the cache.  This
		 * will become the cache_t struct associated with the
		 * new element.
		 */
		cap = reclaim_cache(chp, -1);
		chp->purges += 1;
	}

	bzero((char *)cap, chp->size);

	cap->chn = ccp;
	cap->link[Prev] = (cache_t *)chp;
	cap->link[Next] = chp->aged[Frst];
	cap->link[Prev]->link[Next] = cap->link[Next]->link[Prev] = cap;

	if ((cap->link[Hash+Next] = *ccp) != 0)
		(*ccp)->link[Hash+Prev] = cap;
	return (*ccp = cap);
}

/*
 *  The File Cache:
 *
 *  This cache (also known as the inode cache) is used to keep track of all
 *  files open on a given device.  The only special data required to locate
 *  a cache entry is the file reference number which is file-system dependent
 *  (for UNIX file systems, it's an inode number).
 */

typedef struct icache {		/* Inode cache element:		*/
	cache_t ic_hdr;		/* .. Standard header		*/
	int	ic_num;		/* .. I-node number		*/
} ic_t;

#define	IC_MAX_HDRS (1 << LOG2(ICACHE_SIZE/6))
#define	IC_HASH(d, i) (((d) + (i)) & (IC_MAX_HDRS - 1))

static int x_inode;

static int		    /* Cache search predicate:			    */
cmp_icache(cache_t *p)
{
	/* Just check the file number ("x_inode") ...	*/
	return (((ic_t *)p)->ic_num == x_inode);
}

static head_t	ic_head = cache_head(ic_head, cmp_icache, ic_t, ICACHE_SIZE);
static cache_t *ic_hash[IC_MAX_HDRS];

void *
get_icache(int dev, int inum)
{
	/*
	 *  Search File Cache:
	 *
	 *  This routine searches the file cache looking for the entry bound to
	 *  the given "dev"ice and file number ["inum"].  If said entry exists,
	 *  it returns the address of the associated file structure.  Otherwise
	 *  it returns null.
	 */
	cache_t *icp;

	x_dev = dev;
	x_inode = inum;
	icp = get_cache(ic_hash[IC_HASH(dev, inum)], &ic_head);

	return (icp ? (caddr_t)icp->data : 0);
}

void
set_icache(int dev, int inum, void *ip, int size)
{
	/*
	 *  Build a File Cache Entry:
	 *
	 * This routne installs the "size"-byte file structure at
	 * "*ip" in the inode cache where it may be retrieved by
	 * subsequent call to get_icache.
	 */
	ic_t *icp = (ic_t *)set_cache(&ic_hash[IC_HASH(dev, inum)],
								&ic_head, 0);
	icp->ic_num = inum;
	icp->ic_hdr.data = ip;
	icp->ic_hdr.dev = dev;
	icp->ic_hdr.size = size;
}

int
set_ricache(int dev, int inum, void *ip, int size)
{
	/*
	 * Reliably set the icache
	 *
	 * This routine is the same as set_icache except that it
	 * will return 1 if the entry could not be entered into the cache
	 * without a purge.
	 */
	ic_t *icp = (ic_t *)set_cache(&ic_hash[IC_HASH(dev, inum)],
					&ic_head, 1);

	if (icp == NULL)
		return (1);

	icp->ic_num = inum;
	icp->ic_hdr.data = ip;
	icp->ic_hdr.dev = dev;
	icp->ic_hdr.size = size;

	return (0);
}

/*
 *  The Directory Cache:
 *
 *  This cache is designed to speed directory searches.	 Each entry cor-
 *  responds to a directory entry that was used in a pathname resolution.
 *  The idea is that most files used by the boot wil be contained in a hand-
 *  full of directories, so we can speed searches if we know ahead of time
 *  just where these directories are.
 */

typedef struct dcache {		/* Directory cache objects:	*/
	cache_t dc_hdr;		/* .. Standard header		*/
	int	dc_inum;	/* .. File number		*/
	int	dc_pnum;	/* .. Parent diretory's file number */
} dc_t;

#define	DC_MAX_HDRS (1 << LOG2(DCACHE_SIZE/6))
#define	DC_HASH(d, n, l) (((d) + (n)[0] + (n)[(l)-1] + (l)) & (DC_MAX_HDRS-1))

static char *x_name;
static int x_pnum;

static int
cmp_dcache(cache_t *p) /* Cache Search predicate:	*/
{
	/* Check name, length, and parent's file number	*/
	return ((x_len == p->size) && (x_pnum == ((dc_t *)p)->dc_pnum) &&
	    (strcmp((char *)p->data, x_name) == 0));
}

static head_t	dc_head = cache_head(dc_head, cmp_dcache, dc_t, DCACHE_SIZE);
static cache_t *dc_hash[DC_MAX_HDRS];

int
get_dcache(int dev, char *name, int pnum)
{
	/*
	 *  Search Directory Cache:
	 *
	 *  This routine searches the directory cache for an entry
	 *  associated with directory number "pnum" from the given
	 *  file system that de-scribes a file of the given "name".
	 *  If we find such an entry, we return the corresponding file
	 *  number, 0 otherwise.
	 */
	dc_t *dcp;

	x_dev = dev;
	x_len = strlen(name)+1;
	x_pnum = pnum;
	x_name = name;
	dcp = (dc_t *)get_cache(dc_hash[DC_HASH(dev, name, x_len)], &dc_head);

	return (dcp ? dcp->dc_inum : 0);
}

void
set_dcache(int dev, char *name, int pnum, int inum)
{
	/*
	 *  Build Directory Cache Entry:
	 *
	 *  This routine creates directory cache entries to be retrieved later
	 *  via "get_dcache".  The cache key is composed of three parts: The
	 *  device specifier, the file name ("name"), and the file number of
	 *  the directory containing that name ("pnum").  The data portion of
	 *  the entry consists of the file number ("inum").
	 */

	int len = strlen(name)+1;
	dc_t *dcp =
	    (dc_t *)set_cache(&dc_hash[DC_HASH(dev, name, len)], &dc_head, 0);

	if (dcp->dc_hdr.data = (void *)bkmem_alloc(len)) {
		/*
		 * Allocate a buffer for the pathname component, and
		 * make this the "data" portion of the generalize
		 * "cache_t" struct. Also fill in the cache-specific
		 * fields (pnum, inum).
		 */
		dcp->dc_pnum = pnum;
		dcp->dc_inum = inum;
		dcp->dc_hdr.dev = dev;
		dcp->dc_hdr.size = len;
		bcopy(name, (char *)dcp->dc_hdr.data, len);

	} else {
		/*
		 * Not enough memory to make a copy of the name!
		 * There's probably not enough to do much else either!
		 */
		prom_panic("no memory for directory cache");
	}
}

int
set_rdcache(int dev, char *name, int pnum, int inum)
{
	/*
	 * Reliably set the dcache
	 *
	 * This routine is the same as set_dcache except that it
	 * return 1 if the entry could not be entered into
	 * the cache without a purge.
	 */
	int len = strlen(name) + 1;
	dc_t *dcp =
		(dc_t *)set_cache(&dc_hash[DC_HASH(dev, name, len)],
								&dc_head, 1);

	if (dcp == NULL)
		return (1);

	if ((dcp->dc_hdr.data = (void *)bkmem_alloc(len)) == NULL) {
		/*
		 * Not enough memory to make a copy of the name!
		 * There's probably not enough to do much else either!
		 */
		prom_panic("no memory for directory cache");
		/* NOTREACHED */
	}

	/*
	 * Allocate a buffer for the pathname component, and
	 * make this the "data" portion of the generalize
	 * "cache_t" struct. Also fill in the cache-specific
	 * fields (pnum, inum).
	 */
	dcp->dc_pnum = pnum;
	dcp->dc_inum = inum;
	dcp->dc_hdr.dev = dev;
	dcp->dc_hdr.size = len;
	bcopy(name, (char *)dcp->dc_hdr.data, len);

	return (0);
}

/*
 *  Disk Block Cache:
 */

typedef struct bcache {	    /* Disk block cache objects:		*/
	cache_t		bc_hdr;	/* .. Standard header			*/
	unsigned long	bc_blk;	/* .. The block number			*/
} bc_t;

#define	BC_MAX_HDRS (1 << LOG2(BCACHE_SIZE/6))
#define	BC_HASH(d, b, l) (((d) + (b) + ((l) >> 8)) & (BC_MAX_HDRS-1))

static unsigned long x_blkno;

static int
cmp_bcache(cache_t *p) /* Cache Search predicate:		*/
{
	/* Check block number, buffer size	*/
	return ((x_len == p->size) && (x_blkno == ((bc_t *)p)->bc_blk));
}

static head_t	bc_head = cache_head(bc_head, cmp_bcache, bc_t, BCACHE_SIZE);
static cache_t *bc_hash[BC_MAX_HDRS];

caddr_t
get_bcache(fileid_t *fp)
{
	/*
	 *  Search Disk Block Cache:
	 *
	 *  This should be getting pretty monotonous by now.  Aren't generalized
	 *  subroutines ("objects", if you prefer) great?
	 */
	cache_t *bcp;

	x_len = fp->fi_count;
	x_blkno = fp->fi_blocknum;
	x_dev = fp->fi_devp->di_dcookie;
	bcp = get_cache(bc_hash[BC_HASH(x_dev, x_blkno, x_len)], &bc_head);

	return (bcp ? (caddr_t)bcp->data : 0);
}

int
set_bcache(fileid_t *fp)
{
	/*
	 *  Insert Disk Block Cache Entry:
	 *
	 *  In this case, we actually read the requested block into a
	 *  dynamically allocated buffer before inserting it into the
	 *  cache.  If the read fails, we return a non-zero value.
	 *
	 *  The search keys for disk blocks are the block number and
	 *  buffer size.  The data associated with each entry is the
	 *  corresponding data buffer.
	 */
	bc_t *bcp;

	if (fp->fi_memp = bkmem_alloc(x_len = fp->fi_count)) {
		/*
		 *  We were able to succesffully allocate an input
		 *  buffer, now read the data into it.
		 */
		if (diskread(fp) != 0) {
			/*
			 * I/O error on read. Free the input buffer,
			 * print an error message, and bail out.
			 */
			bkmem_free(fp->fi_memp, x_len);
			printf("disk read error\n");
			return (-1);
		}

		x_blkno = fp->fi_blocknum;
		x_dev = fp->fi_devp->di_dcookie;
		bcp = (bc_t *)
			set_cache(&bc_hash[BC_HASH(x_dev, x_blkno, x_len)],
								&bc_head, 0);
		bcp->bc_blk = x_blkno;
		bcp->bc_hdr.dev = x_dev;
		bcp->bc_hdr.size = x_len;
		bcp->bc_hdr.data = (void *)fp->fi_memp;

	} else {
		/*
		 * We could be a bit more convervative here by
		 * calling "set_cache" before we try to allocate a
		 * buffer (thereby giving us a chance to re-use a
		 * previously allocated buffer) but the error recovery
		 * is a bit trickier, and if we're that short on memory
		 * we'll have trouble elsewhere anyway!
		 */
		prom_panic("can't read - no memory");
	}

	return (0);
}

void
release_cache(int dev)
{
	/*
	 *  Reclaim all cache entries:
	 *
	 *  This routine is called by the file-system's "closeall" method.  It
	 *  removes all cache entries associated with that file system from the
	 *  global cache and release any resources bound to said entrires.
	 */

	(void) reclaim_cache(&ic_head, dev);
	(void) reclaim_cache(&dc_head, dev);
	(void) reclaim_cache(&bc_head, dev);
}

void
print_cache_data()
{
	/*
	 *  Print some cacheing statistics ...
	 */
	static char	*tag[] = { "inode", "directory", "disk block", 0};
	static head_t	*hdp[] = { &ic_head, &dc_head, &bc_head, 0};

	int j;

	for (j = 0; tag[j]; j++) {
		/*
		 * Print statistics maintained in the header
		 * ("head_t" struct) of each of the above caches.
		 */
		head_t *hp = hdp[j];

		if (j)
			printf("\n");
		printf("%s cache:\n", tag[j]);
		printf("   max size %d\n", hp->maxblks);
		printf("   actual size %d\n", hp->count);
		printf("   total searches %d\n", hp->searches);
		printf("   cache hits %d\n", hp->hits);
		printf("   cache purges %d\n", hp->purges);
	}

	printf("\nread opts %d\n", read_opt);
}
/*
 * 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 1994-1996, 2002-2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#include <sys/param.h>
#include <sys/vnode.h>
#include <sys/fs/ufs_fsdir.h>
#include <sys/fs/ufs_fs.h>
#include <sys/fs/ufs_inode.h>
#include <sys/sysmacros.h>
#include <sys/promif.h>
#include <sys/filep.h>
#include <sys/salib.h>

static	char	prom_dev_type = 0;

/*
 * unix root slice offset for PROMS that do
 * not know about fdisk partitions or Solaris
 * slices.
 * the default is 0 for machines with proms that
 * do know how to interpret solaris slices.
 */
unsigned long unix_startblk = 0;

/*
 *	The various flavors of PROM make this grotesque.
 */
int
diskread(fileid_t *filep)
{
	int err;
	devid_t	*devp;
	uint_t blocknum;

	/* add in offset of root slice */
	blocknum = filep->fi_blocknum + unix_startblk;

	devp = filep->fi_devp;

	err = prom_seek(devp->di_dcookie,
	    (unsigned long long)blocknum * (unsigned long long)DEV_BSIZE);
	if (err == -1) {
		printf("Seek error at block %x\n", blocknum);
		return (-1);
	}

	if ((err = prom_read(devp->di_dcookie, filep->fi_memp, filep->fi_count,
	    blocknum, prom_dev_type)) != filep->fi_count) {
		printf("Short read.  0x%x chars read\n", err);
		return (-1);
	}

	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 1994-1996, 2002-2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#include <sys/param.h>
#include <sys/sysmacros.h>
#include <sys/stat.h>
#include <sys/bootvfs.h>
#include <sys/bootsyms.h>
#include <sys/promif.h>
#include <sys/salib.h>

static struct boot_fs_ops *dfl_fsw = (struct boot_fs_ops *)NULL;
static char *fsmsg = "Fstype has not been selected yet!\n";
static char *msg_noops = "not fs_ops supplied\n";

/*
 * return fs_ops pointer for a given file system name
 */
struct boot_fs_ops *
get_fs_ops_pointer(char *fsw_name)
{
	int	fsw_idx;

	for (fsw_idx = 0; fsw_idx < boot_nfsw; fsw_idx++)
		if (strcmp(boot_fsw[fsw_idx]->fsw_name, fsw_name) == 0) {
			return (boot_fsw[fsw_idx]);
		}
	return ((struct boot_fs_ops *)NULL);
}

/*
 * set default file system type
 */
void
set_default_fs(char *fsw_name)
{
	int	fsw_idx;

	for (fsw_idx = 0; fsw_idx < boot_nfsw; fsw_idx++)
		if (strcmp(boot_fsw[fsw_idx]->fsw_name, fsw_name) == 0) {
			dfl_fsw = boot_fsw[fsw_idx];
			return;
		}
	printf("Fstype <%s> is not recognized\n", fsw_name);
	prom_panic("");
}

/*
 * clear default file system type
 */
void
clr_default_fs(void)
{
	dfl_fsw = NULL;
}

struct boot_fs_ops *
get_default_fs(void)
{
	return (dfl_fsw);
}

void
boot_no_ops_void()
{
	prom_panic(msg_noops);
	/*NOTREACHED*/
}

int
boot_no_ops()
{
	prom_panic(msg_noops);
	/*NOTREACHED*/
	return (0);
}

int
close(int fd)
{
	if (dfl_fsw != (struct boot_fs_ops *)NULL)
		return ((*dfl_fsw->fsw_close)(fd));
	prom_panic(fsmsg);
	/*NOTREACHED*/
}

int
mountroot(char *str)
{
	if (dfl_fsw != (struct boot_fs_ops *)NULL)
		return ((*dfl_fsw->fsw_mountroot)(str));
	prom_panic(fsmsg);
	/*NOTREACHED*/
}

int
unmountroot(void)
{
	if (dfl_fsw != (struct boot_fs_ops *)NULL)
		return ((*dfl_fsw->fsw_unmountroot)());
	prom_panic(fsmsg);
	/*NOTREACHED*/
}

/*ARGSUSED*/
int
open(const char *filename, int flags)
{
	if (dfl_fsw != (struct boot_fs_ops *)NULL)
		return ((*dfl_fsw->fsw_open)((char *)filename, flags));
	prom_panic(fsmsg);
	/*NOTREACHED*/
}

ssize_t
read(int fd, void *buf, size_t size)
{
	if (dfl_fsw != (struct boot_fs_ops *)NULL)
		return ((*dfl_fsw->fsw_read)(fd, buf, size));
	prom_panic(fsmsg);
	/*NOTREACHED*/
}

void
closeall(int flag)
{
	if (dfl_fsw != (struct boot_fs_ops *)NULL) {
		(*dfl_fsw->fsw_closeall)(flag);
		return;
	}
	prom_panic(fsmsg);
	/*NOTREACHED*/
}

int
fstat(int fd, struct stat *sb)
{
	struct bootstat buf;
	int ret;

	if (dfl_fsw == NULL)
		prom_panic(fsmsg);

	ret = (*dfl_fsw->fsw_fstat)(fd, &buf);
	if (ret == -1)
		return (-1);

	sb->st_dev		= buf.st_dev;
	sb->st_ino		= buf.st_ino;
	sb->st_mode		= buf.st_mode;
	sb->st_nlink		= buf.st_nlink;
	sb->st_uid 		= buf.st_uid;
	sb->st_gid		= buf.st_gid;
	sb->st_rdev		= buf.st_rdev;
	sb->st_size		= (off_t)buf.st_size;
	sb->st_blksize		= buf.st_blksize;
	sb->st_blocks		= buf.st_blocks;
	sb->st_atim.tv_sec	= buf.st_atim.tv_sec;
	sb->st_atim.tv_nsec	= buf.st_atim.tv_nsec;
	sb->st_mtim.tv_sec 	= buf.st_mtim.tv_sec;
	sb->st_mtim.tv_nsec	= buf.st_mtim.tv_nsec;
	sb->st_ctim.tv_sec	= buf.st_ctim.tv_sec;
	sb->st_ctim.tv_nsec	= buf.st_ctim.tv_nsec;

	(void) memcpy(sb->st_fstype, buf.st_fstype, sizeof (sb->st_fstype));
	return (0);
}

int
stat(const char *filename, struct stat *sb)
{
	int fd, ret = -1;

	if ((fd = open(filename, O_RDONLY)) != -1) {
		ret = fstat(fd, sb);
		(void) close(fd);
	}

	return (ret);
}

off_t
lseek(int filefd, off_t addr, int whence)
{
	if (dfl_fsw != (struct boot_fs_ops *)NULL)
		return ((*dfl_fsw->fsw_lseek)(filefd, addr, whence));
	prom_panic(fsmsg);
	/*NOTREACHED*/
}

/*
 * Kernel Interface
 */
int
kern_open(char *str, int flags)
{
	if (dfl_fsw != (struct boot_fs_ops *)NULL)
		return ((*dfl_fsw->fsw_open)(str, flags));
	prom_panic(fsmsg);
	/*NOTREACHED*/
}

/*
 *  hi and lo refer to the MS end of the off_t word
 *  and the LS end of the off_t word for when we want
 *  to support 64-bit offsets.  For now, lseek() just
 *  supports 32 bits.
 */

/*ARGSUSED*/
off_t
kern_lseek(int filefd, off_t hi, off_t lo)
{
	if (dfl_fsw != (struct boot_fs_ops *)NULL)
		return ((*dfl_fsw->fsw_lseek)(filefd, lo, 0));
	prom_panic(fsmsg);
	/*NOTREACHED*/
}

ssize_t
kern_read(int fd, caddr_t buf, size_t size)
{
	if (dfl_fsw != (struct boot_fs_ops *)NULL)
		return ((*dfl_fsw->fsw_read)(fd, buf, size));
	prom_panic(fsmsg);
	/*NOTREACHED*/
}

int
kern_close(int fd)
{
	if (dfl_fsw != (struct boot_fs_ops *)NULL)
		return ((*dfl_fsw->fsw_close)(fd));
	prom_panic(fsmsg);
	/*NOTREACHED*/
}

int
kern_fstat(int fd, struct bootstat *buf)
{
	if (dfl_fsw != (struct boot_fs_ops *)NULL)
		return ((*dfl_fsw->fsw_fstat)(fd, buf));
	prom_panic(fsmsg);
	/*NOTREACHED*/
}

int
kern_getdents(int fd, struct dirent *buf, size_t size)
{
	if (dfl_fsw != (struct boot_fs_ops *)NULL)
		return ((*dfl_fsw->fsw_getdents)(fd, buf, size));
	prom_panic(fsmsg);
	/*NOTREACHED*/
}

int
kern_mountroot(char *path)
{
	return (mountroot(path));
}

int
kern_unmountroot(void)
{
	return (unmountroot());
}
/*
 * 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.
 */
#pragma ident	"%Z%%M%	%I%	%E% SMI"

#include <sys/param.h>
#include <sys/sysmacros.h>
#include <sys/stat.h>
#include <sys/bootvfs.h>
#include <sys/bootsyms.h>
#include <sys/promif.h>
#include <sys/salib.h>

/*
 *  Function prototypes
 */
static int	promfs_mountroot(char *str);
static int	promfs_unmountroot(void);
static int	promfs_open(char *filename, int flags);
static int	promfs_close(int fd);
static ssize_t	promfs_read(int fd, caddr_t buf, size_t size);
static off_t	promfs_lseek(int fd, off_t offset, int whence);
static int	promfs_fstat(int fd, struct bootstat *stp);
static void	promfs_closeall(int flag);

struct boot_fs_ops promfs_ops = {
	"promfs",
	promfs_mountroot,
	promfs_unmountroot,
	promfs_open,
	promfs_close,
	promfs_read,
	promfs_lseek,
	promfs_fstat,
	promfs_closeall,
	NULL
};

static ihandle_t fsih;

static int
promfs_mountroot(char *str)
{

	(void) prom_getprop(prom_chosennode(), str, (caddr_t)&fsih);
	return (fsih == -1);
}

static int
promfs_unmountroot(void)
{
	(void) prom_close(fsih);
	return (0);
}

/*ARGSUSED*/
static int
promfs_open(char *filename, int flags)
{
	return (prom_fopen(fsih, filename));
}

static int
promfs_close(int fd)
{
	prom_fclose(fsih, fd);
	return (0);
}

static ssize_t
promfs_read(int fd, caddr_t buf, size_t size)
{
	return (prom_fread(fsih, fd, buf, size));
}

/*ARGSUSED*/
static off_t
promfs_lseek(int fd, off_t offset, int whence)
{
	return (prom_fseek(fsih, fd, offset));
}

static int
promfs_fstat(int fd, struct bootstat *stp)
{
	return (prom_fsize(fsih, fd, (size_t *)&stp->st_size));
}

/*ARGSUSED*/
static void
promfs_closeall(int 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 2003 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# ident	"%Z%%M%	%I%	%E% SMI"
#

LIBRARY = libhsfs.a
OBJECTS = hsfsops.o

include ../Makefile.com

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 2000 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"

static char *hsfs_sig_tab[] = {
	SUSP_SP,
	SUSP_CE,
	SUSP_PD,
	SUSP_ST,
	SUSP_ER,
	RRIP_PX,
	RRIP_PN,
	RRIP_SL,
	RRIP_CL,
	RRIP_PL,
	RRIP_RE,
	RRIP_TF,
	RRIP_RR,
	RRIP_NM
};

static int hsfs_num_sig = sizeof (hsfs_sig_tab) / sizeof (hsfs_sig_tab[0]);

#define	SUSP_SP_IX	0
#define	SUSP_CE_IX	1
#define	SUSP_PD_IX	2
#define	SUSP_ST_IX	3
#define	SUSP_ER_IX	4

#define	RRIP_PX_IX	5
#define	RRIP_PN_IX	6
#define	RRIP_SL_IX	7
#define	RRIP_CL_IX	8
#define	RRIP_PL_IX	9
#define	RRIP_RE_IX	10
#define	RRIP_RF_IX	11
#define	RRIP_RR_IX	12
#define	RRIP_NM_IX	13
/*
 * 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.
 */

#include <sys/param.h>
#include <sys/vnode.h>
#include <sys/fs/ufs_fsdir.h>
#include <sys/fs/ufs_fs.h>
#include <sys/fs/ufs_inode.h>
#include <sys/sysmacros.h>
#include <sys/promif.h>
#include <sys/filep.h>
#include <sys/salib.h>
#include <sys/sacache.h>

#include <sys/fs/hsfs_spec.h>
#include <sys/fs/hsfs_isospec.h>
#include <sys/fs/hsfs_node.h>
#include <sys/fs/hsfs_susp.h>
#include <sys/fs/hsfs_rrip.h>

#include "hsfs_sig.h"

#include <sys/stat.h>
#include <sys/bootvfs.h>
#include <sys/bootconf.h>
#include <sys/bootdebug.h>

#define	hdbtodb(n)	((ISO_SECTOR_SIZE / DEV_BSIZE) * (n))

#define	THE_EPOCH	1970
#define	END_OF_TIME	2099

/* May not need this... */
static uint_t	sua_offset = 0;

/* The root inode on an HSFS filesystem can be anywhere! */
static uint_t	root_ino = 0;		/* This is both a flag and a value */

static fileid_t *head;

/* Only got one of these...ergo, only 1 fs open at once */
static devid_t *devp;

struct dirinfo {
	int 	loc;
	fileid_t *fi;
};

struct hs_direct {
    struct	direct	hs_ufs_dir;
    struct	hs_direntry hs_dir;
};

/*
 *  Function prototypes
 */

static int	boot_hsfs_mountroot(char *str);
static int	boot_hsfs_unmountroot(void);
static int	boot_hsfs_open(char *filename, int flags);
static int	boot_hsfs_close(int fd);
static ssize_t	boot_hsfs_read(int fd, caddr_t buf, size_t size);
static off_t	boot_hsfs_lseek(int, off_t, int);
static int	boot_hsfs_fstat(int fd, struct bootstat *stp);
static void	boot_hsfs_closeall(int flag);
static int	boot_hsfs_getdents(int fd, struct dirent *dep, unsigned size);

struct boot_fs_ops boot_hsfs_ops = {
	"hsfs",
	boot_hsfs_mountroot,
	boot_hsfs_unmountroot,
	boot_hsfs_open,
	boot_hsfs_close,
	boot_hsfs_read,
	boot_hsfs_lseek,
	boot_hsfs_fstat,
	boot_hsfs_closeall,
	boot_hsfs_getdents
};

static 	ino_t	find(fileid_t *, char *);
static	ino_t	dlook(fileid_t *, char *);
static	int	opendir(fileid_t *, ino_t);
static	struct	hs_direct *readdir(struct dirinfo *);
static	uint_t	parse_dir(fileid_t *, int, struct hs_direct *);
static	uint_t	parse_susp(char *, uint_t *, struct hs_direct *);
static	void	hs_seti(fileid_t *,  struct hs_direct *, ino_t);
static void	hs_dodates(enum hs_vol_type, struct hs_direntry *, char *);
static time_t	hs_date_to_gmtime(int, int, int, int);

/*
 *	There is only 1 open (mounted) device at any given time.
 *	So we can keep a single, global devp file descriptor to
 *	use to index into the di[] array.  This is not true for the
 *	fi[] array.  We can have more than one file open at once,
 *	so there is no global fd for the fi[].
 *	The user program must save the fd passed back from open()
 *	and use it to do subsequent read()'s.
 */

static int
opendir(fileid_t *filep, ino_t inode)
{
	struct hs_direct hsdep;
	int retval;

	/* Set up the saio request */
	filep->fi_offset = 0;
	filep->fi_blocknum = hdbtodb(inode);
	filep->fi_count = ISO_SECTOR_SIZE;

	/* Maybe the block is in the disk block cache */
	if ((filep->fi_memp = get_bcache(filep)) == NULL) {
		/* Not in the block cache so read it from disk */
		if (retval = set_bcache(filep)) {
			return (retval);
		}
	}

	filep->fi_offset = 0;
	filep->fi_blocknum = hdbtodb(inode);

	if (inode != root_ino)
		return (0);

	if ((int)(parse_dir(filep, 0, &hsdep)) > 0) {
		hs_seti(filep, &hsdep, inode);
		return (0);
	}
	return (1);
}

static ino_t
find(fileid_t *filep, char *path)
{
	register char *q;
	char c;
	ino_t inode;

	if (path == NULL || *path == '\0') {
		printf("null path\n");
		return (0);
	}

	if ((boothowto & RB_DEBUG) && (boothowto & RB_VERBOSE))
		printf("find(): path=<%s>\n", path);

	/* Read the ROOT directory */
	if (opendir(filep, inode = root_ino)) {
		printf("find(): root_ino opendir() failed!\n");
		return ((ino_t)-1);
	}

	while (*path) {
		while (*path == '/')
			path++;
		if (*(q = path) == '\0')
			break;
		while (*q != '/' && *q != '\0')
			q++;
		c = *q;
		*q = '\0';

		if ((inode = dlook(filep, path)) != 0) {
			if (c == '\0')
				break;
			if (opendir(filep, inode)) {
				printf("find(): opendir(%d) failed!\n", inode);
				*q = c;
				return ((ino_t)-1);
			}
			*q = c;
			path = q;
			continue;
		} else {
			*q = c;
			return (0);
		}
	}
	return (inode);
}

static fileid_t *
find_fp(int fd)
{
	fileid_t *filep = head;

	if (fd >= 0) {
		while ((filep = filep->fi_forw) != head)
			if (fd == filep->fi_filedes)
				return (filep->fi_taken ? filep : 0);
	}

	return (0);
}

static ino_t
dlook(fileid_t *filep, char *path)
{
	int dv = filep->fi_devp->di_dcookie;
	register struct hs_direct *hsdep;
	register struct direct *udp;
	register struct inode *ip;
	struct dirinfo dirp;
	register int len;
	ino_t in;

	ip = filep->fi_inode;
	if (path == NULL || *path == '\0')
		return (0);
	if ((ip->i_smode & IFMT) != IFDIR) {
		return (0);
	}
	if (ip->i_size == 0) {
		return (0);
	}
	len = strlen(path);
	/* first look through the directory entry cache */
	if (in = get_dcache(dv, path, ip->i_number)) {
		if ((filep->fi_inode = get_icache(dv, in)) != NULL) {
			filep->fi_offset = 0;
			filep->fi_blocknum = hdbtodb(in);
			return (in);
		}
	}
	dirp.loc = 0;
	dirp.fi = filep;
	for (hsdep = readdir(&dirp); hsdep != NULL; hsdep = readdir(&dirp)) {
		udp = &hsdep->hs_ufs_dir;
		if (udp->d_namlen == 1 &&
		    udp->d_name[0] == '.' &&
		    udp->d_name[1] == '\0')
			continue;
		if (udp->d_namlen == 2 &&
		    udp->d_name[0] == '.' &&
		    udp->d_name[1] == '.' &&
		    udp->d_name[2] == '\0')
			continue;
		if (udp->d_namlen == len && (strcmp(path, udp->d_name) == 0)) {
			set_dcache(dv, path, ip->i_number, udp->d_ino);
			hs_seti(filep, hsdep, udp->d_ino);
			filep->fi_offset = 0;
			filep->fi_blocknum = hdbtodb(udp->d_ino);
			/* put this entry into the cache */
			return (udp->d_ino);
		}
		/* Allow "*" to print all names at that level, w/out match */
		if (strcmp(path, "*") == 0)
			printf("%s\n", udp->d_name);
	}
	return (0);
}

/*
 * get next entry in a directory.
 */
static struct hs_direct *
readdir(struct dirinfo *dirp)
{
	static struct hs_direct hsdep;
	register struct direct *udp = &hsdep.hs_ufs_dir;
	register struct inode *ip;
	register fileid_t *filep;
	register daddr_t lbn;
	register int off;

	filep = dirp->fi;
	ip = filep->fi_inode;
	for (;;) {
		if (dirp->loc >= ip->i_size) {
			return (NULL);
		}
		off = dirp->loc & ((1 << ISO_SECTOR_SHIFT) - 1);
		if (off == 0) {
			lbn = hdbtodb(dirp->loc >> ISO_SECTOR_SHIFT);
			filep->fi_blocknum = lbn + hdbtodb(ip->i_number);
			filep->fi_count = ISO_SECTOR_SIZE;
			/* check the block cache */
			if ((filep->fi_memp = get_bcache(filep)) == 0)
				if (set_bcache(filep))
					return ((struct hs_direct *)-1);
		}
		dirp->loc += parse_dir(filep, off, &hsdep);
		if (udp->d_reclen == 0 && dirp->loc <= ip->i_size) {
			dirp->loc = roundup(dirp->loc, ISO_SECTOR_SIZE);
			continue;
		}
		return (&hsdep);
	}
}

/*
 * Get the next block of data from the file.  If possible, dma right into
 * user's buffer
 */
static int
getblock(fileid_t *filep, caddr_t buf, int count, int *rcount)
{
	register struct inode *ip;
	register caddr_t p;
	register int off, size, diff;
	register daddr_t lbn;
	static int	pos;
	static char 	ind[] = "|/-\\";	/* that's entertainment? */
	static int	blks_read;

	ip = filep->fi_inode;
	p = filep->fi_memp;
	if ((signed)filep->fi_count <= 0) {

		/* find the amt left to be read in the file */
		diff = ip->i_size - filep->fi_offset;
		if (diff <= 0) {
			printf("Short read\n");
			return (-1);
		}

		/* which block (or frag) in the file do we read? */
		lbn = hdbtodb(filep->fi_offset >> ISO_SECTOR_SHIFT);

		/* which physical block on the device do we read? */
		filep->fi_blocknum = lbn + hdbtodb(ip->i_number);

		off = filep->fi_offset & ((1 << ISO_SECTOR_SHIFT) - 1);

		size = sizeof (filep->fi_buf);
		if (size > ISO_SECTOR_SIZE)
			size = ISO_SECTOR_SIZE;

		filep->fi_count = size;
		filep->fi_memp = filep->fi_buf;

		/*
		 * optimization if we are reading large blocks of data then
		 * we can go directly to user's buffer
		 */
		*rcount = 0;
		if (off == 0 && count >= size) {
			filep->fi_memp = buf;
			if (diskread(filep)) {
				return (-1);
			}
			*rcount = size;
			filep->fi_count = 0;
			read_opt++;
			if ((blks_read++ & 0x3) == 0)
				printf("%c\b", ind[pos++ & 3]);
			return (0);
		} else
			if (diskread(filep))
				return (-1);

		/*
		 * round and round she goes (though not on every block..
		 * - OBP's take a fair bit of time to actually print stuff)
		 */
		if ((blks_read++ & 0x3) == 0)
			printf("%c\b", ind[pos++ & 3]);

		if (filep->fi_offset - off + size >= ip->i_size)
			filep->fi_count = diff + off;
		filep->fi_count -= off;
		p = &filep->fi_memp[off];
	}
	filep->fi_memp = p;
	return (0);
}


/*
 *  This is the high-level read function.  It works like this.
 *  We assume that our IO device buffers up some amount of
 *  data ant that we can get a ptr to it.  Thus we need
 *  to actually call the device func about filesize/blocksize times
 *  and this greatly increases our IO speed.  When we already
 *  have data in the buffer, we just return that data (with bcopy() ).
 */

static ssize_t
boot_hsfs_read(int fd, caddr_t buf, size_t count)
{
	size_t i, j;
	struct inode *ip;
	caddr_t	n;
	fileid_t *filep;
	int rcount;

	if (!(filep = find_fp(fd))) {
		return (-1);
	}

	ip = filep->fi_inode;

	if (filep->fi_offset + count > ip->i_size)
		count = ip->i_size - filep->fi_offset;

	/* that was easy */
	if ((i = count) == 0)
		return (0);

	n = buf;
	while (i > 0) {
		/* If we need to reload the buffer, do so */
		if ((j = filep->fi_count) == 0) {
			(void) getblock(filep, buf, i, &rcount);
			i -= rcount;
			buf += rcount;
			filep->fi_offset += rcount;
		} else {
			/* else just bcopy from our buffer */
			j = MIN(i, j);
			bcopy(filep->fi_memp, buf, (unsigned)j);
			buf += j;
			filep->fi_memp += j;
			filep->fi_offset += j;
			filep->fi_count -= j;
			i -= j;
		}
	}
	return (buf - n);
}

/*
 *	This routine will open a device as it is known by the
 *	V2 OBP.
 *	Interface Defn:
 *	err = mountroot(string);
 *	err:	0 on success
 *		-1 on failure
 *	string:	char string describing the properties of the device.
 *	We must not dork with any fi[]'s here.  Save that for later.
 */

static int
boot_hsfs_mountroot(char *str)
{
	ihandle_t	h;
	struct hs_volume *fsp;
	char 		*bufp;

	if ((boothowto & RB_DEBUG) && (boothowto & RB_VERBOSE))
		printf("mountroot()\n");

	/*
	 * If already mounted, just return success.
	 */
	if (root_ino != 0) {
		return (0);
	}

	h = prom_open(str);

	if (h == 0) {
		printf("Cannot open %s\n", str);
		return (-1);
	}

	devp = (devid_t *)bkmem_alloc(sizeof (devid_t));
	devp->di_taken = 1;
	devp->di_dcookie = h;
	devp->di_desc = (char *)bkmem_alloc(strlen(str) + 1);
	(void) strcpy(devp->di_desc, str);
	bzero(devp->un_fs.dummy, sizeof (devp->un_fs.dummy));
	head = (fileid_t *)bkmem_alloc(sizeof (fileid_t));
	head->fi_back = head->fi_forw = head;
	head->fi_filedes = 0;
	head->fi_taken = 0;

	/* Setup read of the "superblock" */
	bzero(head->fi_buf, sizeof (head->fi_buf));
	head->fi_devp = devp;
	head->fi_blocknum = hdbtodb(ISO_VOLDESC_SEC);
	head->fi_count = ISO_SECTOR_SIZE;
	head->fi_memp = head->fi_buf;
	head->fi_offset = 0;

	if (diskread(head)) {
		printf("mountroot(): read super block failed!\n");
		boot_hsfs_closeall(1);
		return (-1);
	}

	bufp = head->fi_memp;
	fsp = (struct hs_volume *)devp->un_fs.dummy;
	/* Since RRIP is based on ISO9660, that's where we start */

	if (ISO_DESC_TYPE(bufp) != ISO_VD_PVD ||
	    strncmp((char *)(ISO_std_id(bufp)), (char *)(ISO_ID_STRING),
	    ISO_ID_STRLEN) != 0 || ISO_STD_VER(bufp) != ISO_ID_VER) {
		boot_hsfs_closeall(1);
		return (-1);
	}

	/* Now we fill in the volume descriptor */
	fsp->vol_size = ISO_VOL_SIZE(bufp);
	fsp->lbn_size = ISO_BLK_SIZE(bufp);
	fsp->lbn_shift = ISO_SECTOR_SHIFT;
	fsp->lbn_secshift = ISO_SECTOR_SHIFT;
	fsp->vol_set_size = (ushort_t)ISO_SET_SIZE(bufp);
	fsp->vol_set_seq = (ushort_t)ISO_SET_SEQ(bufp);

	/* Make sure we have a valid logical block size */
	if (fsp->lbn_size & ~(1 << fsp->lbn_shift)) {
		printf("%d byte logical block size invalid.\n", fsp->lbn_size);
		boot_hsfs_closeall(1);
		return (-1);
	}

	/* Since an HSFS root could be located anywhere on the media! */
	root_ino = IDE_EXT_LBN(ISO_root_dir(bufp));

	if ((boothowto & RB_DEBUG) && (boothowto & RB_VERBOSE)) {
		int	i;

		printf("root_ino=%d\n", root_ino);
		printf("ID=");
		for (i = 0; i < ISO_ID_STRLEN; i++)
			printf("%c", *(ISO_std_id(bufp)+i));
		printf(" VS=%d\n", fsp->vol_size);
	}

	return (0);
}

/*
 * Unmount the currently mounted root fs.  In practice, this means
 * closing all open files and releasing resources.  All of this
 * is done by boot_hsfs_closeall().
 */

int
boot_hsfs_unmountroot(void)
{
	if (root_ino == 0)
		return (-1);

	boot_hsfs_closeall(1);

	return (0);
}

/*
 *	We allocate an fd here for use when talking
 *	to the file itself.
 */

/*ARGSUSED*/
static int
boot_hsfs_open(char *filename, int flags)
{
	fileid_t	*filep;
	ino_t		inode;
	static int	filedes = 1;

	/* build and link a new file descriptor */
	filep = (fileid_t *)bkmem_alloc(sizeof (fileid_t));
	filep->fi_back = head->fi_back;
	filep->fi_forw = head;
	head->fi_back->fi_forw = filep;
	head->fi_back = filep;

	filep->fi_filedes = filedes++;
	filep->fi_taken = 1;
	filep->fi_path = (char *)bkmem_alloc(strlen(filename) + 1);
	(void) strcpy(filep->fi_path, filename);
	filep->fi_devp = devp; /* dev is already "mounted" */

	filep->fi_inode = 0;

	inode = find(filep, filename);
	if (inode == (ino_t)0) {
		if ((boothowto & RB_DEBUG) && (boothowto & RB_VERBOSE))
			printf("open(%s) ENOENT\n", filename);
		(void) boot_hsfs_close(filep->fi_filedes);
		return (-1);
	}

	filep->fi_blocknum = hdbtodb(inode);
	filep->fi_offset = filep->fi_count = 0;

	if ((boothowto & RB_DEBUG) && (boothowto & RB_VERBOSE))
		printf("open(%s) fd=%d\n", filename, filep->fi_filedes);
	return (filep->fi_filedes);
}

/*
 * hsfs_fstat() only supports size, mode and times at present time.
 */

static int
boot_hsfs_fstat(int fd, struct bootstat *stp)
{
	fileid_t	*filep;
	struct inode	*ip;

	if (!(filep = find_fp(fd)))
		return (-1);

	ip = filep->fi_inode;

	stp->st_mode = 0;
	stp->st_size = 0;

	if (ip == NULL)
		return (0);

	switch (ip->i_smode & IFMT) {
	case IFDIR:
		stp->st_mode = S_IFDIR;
		break;
	case IFREG:
		stp->st_mode = S_IFREG;
		break;
	default:
		break;
	}
	stp->st_size = ip->i_size;

	/* file times */
	stp->st_atim.tv_sec = ip->i_atime.tv_sec;
	stp->st_atim.tv_nsec = ip->i_atime.tv_usec * 1000;
	stp->st_mtim.tv_sec = ip->i_mtime.tv_sec;
	stp->st_mtim.tv_nsec = ip->i_mtime.tv_usec * 1000;
	stp->st_ctim.tv_sec = ip->i_ctime.tv_sec;
	stp->st_ctim.tv_nsec = ip->i_ctime.tv_usec * 1000;

	return (0);
}

/*
 *  We don't do any IO here.
 *  We just play games with the device pointers.
 */

/*ARGSUSED*/
static off_t
boot_hsfs_lseek(int fd, off_t addr, int whence)
{
	fileid_t *filep;

	if (!(filep = find_fp(fd)))
		return (-1);

	filep->fi_offset = addr;
	filep->fi_blocknum = addr / DEV_BSIZE;
	filep->fi_count = 0;

	return (0);
}

static int
boot_hsfs_close(int fd)
{
	fileid_t *filep;

	if ((boothowto & RB_DEBUG) && (boothowto & RB_VERBOSE))
		printf("close(%d)\n", fd);

	if (filep = find_fp(fd)) {
		/* Clear the ranks */
		bkmem_free(filep->fi_path, strlen(filep->fi_path)+1);
		filep->fi_blocknum = filep->fi_count = filep->fi_offset = 0;
		filep->fi_memp = (caddr_t)0;
		filep->fi_devp = 0;
		filep->fi_taken = 0;

		/* unlink and deallocate node */
		filep->fi_forw->fi_back = filep->fi_back;
		filep->fi_back->fi_forw = filep->fi_forw;
		bkmem_free((char *)filep, sizeof (fileid_t));

		return (0);
	} else {
		/* Big problem */
		printf("\nFile descrip %d not allocated!", fd);
		return (-1);
	}
}

/* closeall is now idempotent */
/*ARGSUSED*/
static void
boot_hsfs_closeall(int flag)
{
	fileid_t	*filep = head;
	extern int verbosemode;

	if (devp == NULL) {
		if (head)
			prom_panic("boot_hsfs_closeall: head != NULL.\n");
		return;
	}

	while ((filep = filep->fi_forw) != head)
		if (filep->fi_taken)
			if (boot_hsfs_close(filep->fi_filedes))
				prom_panic("Filesystem may be inconsistent.\n");


	release_cache(devp->di_dcookie);
	(void) prom_close(devp->di_dcookie);
	devp->di_taken = 0;
	if (verbosemode)
		print_cache_data();
	bkmem_free((char *)devp, sizeof (devid_t));
	bkmem_free((char *)head, sizeof (fileid_t));
	root_ino = 0;
	devp = NULL;
	head = NULL;
}

static uint_t
parse_dir(fileid_t *filep, int offset, struct hs_direct *hsdep)
{
	char *bufp = (char *)(filep->fi_memp + offset);
	struct direct *udp = &hsdep->hs_ufs_dir;
	struct hs_direntry *hdp = &hsdep->hs_dir;
	uint_t ce_lbn;
	uint_t ce_len;
	uint_t nmlen;
	uint_t i;
	uchar_t c;
	int ret_code = 0;

	if ((udp->d_reclen = IDE_DIR_LEN(bufp)) == 0)
		return (0);

	hdp->ext_lbn  = IDE_EXT_LBN(bufp);
	hdp->ext_size = IDE_EXT_SIZE(bufp);
	hs_dodates(HS_VOL_TYPE_ISO, hdp, bufp);
	hdp->xar_len  = IDE_XAR_LEN(bufp);
	hdp->intlf_sz = IDE_INTRLV_SIZE(bufp);
	hdp->intlf_sk = IDE_INTRLV_SKIP(bufp);
	hdp->sym_link = NULL;

	udp->d_ino = hdp->ext_lbn;

	c = IDE_FLAGS(bufp);
	if (IDE_REGULAR_FILE(c)) {
		hdp->type = VREG;
		hdp->mode = IFREG;
		hdp->nlink = 1;
	} else if (IDE_REGULAR_DIR(c)) {
		hdp->type = VDIR;
		hdp->mode = IFDIR;
		hdp->nlink = 2;
	} else {
		printf("parse_dir(): file type=0x%x unknown.\n", c);
		return ((uint_t)-1);
	}

	/* Some initial conditions */
	nmlen = IDE_NAME_LEN(bufp);
	c = *IDE_NAME(bufp);
	/* Special Case: Current Directory */
	if (nmlen == 1 && c == '\0') {
		udp->d_name[0] = '.';
		udp->d_name[1] = '\0';
		udp->d_namlen = 1;
	/* Special Case: Parent Directory */
	} else if (nmlen == 1 && c == '\001') {
		udp->d_name[0] = '.';
		udp->d_name[1] = '.';
		udp->d_name[2] = '\0';
		udp->d_namlen = 2;
	/* Other file name */
	} else {
		udp->d_namlen = 0;
		for (i = 0; i < nmlen; i++) {
			c = *(IDE_name(bufp)+i);
			if (c == ';')
				break;
			else if (c == ' ')
				continue;
			else
				udp->d_name[udp->d_namlen++] = c;
		}
		udp->d_name[udp->d_namlen] = '\0';
	}
	/* System Use Fields */
	ce_len = IDE_SUA_LEN(bufp);
	ce_lbn = 0;
	if ((int)(ce_len) > 0) {
		ce_lbn = parse_susp((char *)IDE_sys_use_area(bufp),
		    &ce_len, hsdep);
		while (ce_lbn) {
			daddr_t save_blocknum = filep->fi_blocknum;
			daddr_t save_offset = filep->fi_offset;
			caddr_t save_memp = filep->fi_memp;
			uint_t save_count = filep->fi_count;

#ifdef	noisy
			print_io_req(filep, "parse_dir(): [I]");
#endif	/* noisy */

			filep->fi_blocknum = hdbtodb(ce_lbn);
			filep->fi_offset = 0;
			filep->fi_count = ISO_SECTOR_SIZE;

#ifdef	noisy
			print_io_req(filep, "parse_dir(): [0]");
#endif	/* noisy */

			if ((filep->fi_memp = get_bcache(filep)) == 0)
				ret_code = set_bcache(filep);

#ifdef	noisy
			print_io_req(filep, "parse_dir(): [1]");
#endif	/* noisy */

			if (ret_code) {
				filep->fi_blocknum = save_blocknum;
				filep->fi_offset = save_offset;
				filep->fi_memp = save_memp;
				filep->fi_count = save_count;
				printf("parse_dir(): "
				    "set_bcache() failed (%d)\n", ret_code);
				break;
			}
			ce_lbn = parse_susp(filep->fi_memp, &ce_len, hsdep);

			filep->fi_blocknum = save_blocknum;
			filep->fi_offset = save_offset;
			filep->fi_memp = save_memp;
			filep->fi_count = save_count;

#ifdef	noisy
			print_io_req(filep, "parse_dir(): [2]");
#endif	/* noisy */
		}
	}

	return (udp->d_reclen);
}

static uint_t
parse_susp(char *bufp, uint_t *ce_len, struct hs_direct *hsdep)
{
	struct direct *udp = &hsdep->hs_ufs_dir;
	uchar_t *susp;
	uint_t cur_off = 0;
	uint_t blk_len = *ce_len;
	uint_t susp_len = 0;
	uint_t ce_lbn = 0;
	uint_t i;

	while (cur_off < blk_len) {
		susp = (uchar_t *)(bufp + cur_off);
		if (susp[0] == '\0' || susp[1] == '\0')
			break;
		susp_len = SUF_LEN(susp);
		if (susp_len == 0)
			break;
		for (i = 0; i < hsfs_num_sig; i++) {
			if (strncmp(hsfs_sig_tab[i],
			    (char *)susp, SUF_SIG_LEN) == 0) {
#ifdef	noisy
				if ((boothowto & RB_DEBUG) &&
				    (boothowto & RB_VERBOSE))
					printf("  SUSP_%c%c %d\n",
					    susp[0], susp[1], susp_len);
#endif	/* noisy */
				switch (i) {
				case SUSP_SP_IX:
					if (CHECK_BYTES_OK(susp)) {
						sua_offset =
						    SP_SUA_OFFSET(susp);
#ifdef	lint
						/* this may not be needed */
						i = (int)sua_offset;
#endif	/* lint */
					}
					break;

				case SUSP_CE_IX:
					ce_lbn = CE_BLK_LOC(susp);
					*ce_len = CE_CONT_LEN(susp);
#ifdef	noisy
					if ((boothowto & RB_DEBUG) &&
					    (boothowto & RB_VERBOSE))
						printf("parse_susp(): "
						    "CE: ce_lbn = %d "
						    "ce_len=%d\n",
						    ce_lbn, *ce_len);
#endif	/* noisy */
					break;

				case SUSP_ST_IX:
					printf("parse_susp(): ST: returning "
					    "%d\n", ce_lbn);
					return (ce_lbn);

				case RRIP_SL_IX:
#ifdef	noisy
					if ((boothowto & RB_DEBUG) &&
					    (boothowto & RB_VERBOSE))
						printf("parse_susp(): "
						    "******* SL *******\n");
#endif	/* noisy */
					break;

				case RRIP_RR_IX:
					break;

				case RRIP_NM_IX:
					if (!RRIP_NAME_FLAGS(susp)) {
						udp->d_namlen =
						    RRIP_NAME_LEN(susp);
						bcopy((char *)RRIP_name(susp),
						    (char *)udp->d_name,
						    udp->d_namlen);
						udp->d_name
						    [udp->d_namlen] = '\0';
					}
					break;
				}
				cur_off += susp_len;
				break;
			}
		}
		if (i > hsfs_num_sig) {
			printf("parse_susp(): Bad SUSP\n");
			cur_off = blk_len;
			break;
		}
	}
	return (ce_lbn);
}

static void
hs_seti(fileid_t *filep, struct hs_direct *hsdep, ino_t inode)
{
	register struct inode *ip;
	int dv = filep->fi_devp->di_dcookie;

	/* Try the inode cache first */
	if ((filep->fi_inode = get_icache(dv, inode)) != NULL)
		return;

	filep->fi_inode = (struct inode *)bkmem_alloc(sizeof (struct inode));
	ip = filep->fi_inode;
	bzero((char *)ip, sizeof (struct inode));
	ip->i_size = hsdep->hs_dir.ext_size;
	ip->i_smode = hsdep->hs_dir.mode;
	ip->i_number = inode;
	ip->i_atime.tv_sec = hsdep->hs_dir.adate.tv_sec;
	ip->i_atime.tv_usec = hsdep->hs_dir.adate.tv_usec;
	ip->i_ctime.tv_sec = hsdep->hs_dir.cdate.tv_sec;
	ip->i_ctime.tv_usec = hsdep->hs_dir.cdate.tv_usec;
	ip->i_mtime.tv_sec = hsdep->hs_dir.mdate.tv_sec;
	ip->i_mtime.tv_usec = hsdep->hs_dir.mdate.tv_usec;
	set_icache(dv, inode, ip, sizeof (struct inode));
}

#ifdef	noisy
static void
print_io_req(fileid_t *filep, char *str)
{
	printf("%s o=%d b=%d c=%d m=%x\n",
	    str,
	    filep->fi_offset,
	    filep->fi_blocknum,
	    filep->fi_count,
	    (uint_t)filep->fi_memp);
}
#endif	/* noisy */

static int
boot_hsfs_getdents(int fd, struct dirent *dep, unsigned size)
{
	/*
	 * Read directory entries from the file open on "fd" into the
	 * "size"-byte buffer at "dep" until the buffer is exhausted
	 * or we reach EOF on the directory.  Returns the number of
	 * entries read.
	 */
	int n;
	int cnt = 0;
	struct dirinfo dir;
	struct hs_direct *hdp;
	unsigned long oldoff, oldblok;

#define	SLOP (sizeof (struct dirent) - offsetof(struct dirent, d_name[1]))

	if (!(dir.fi = find_fp(fd)) ||
	    ((dir.fi->fi_inode->i_smode & IFMT) != IFDIR)) {
		/*
		 *  Bogus file descriptor, bail out now!
		 */
		return (-1);
	}

	oldoff = dir.loc = dir.fi->fi_offset;
	oldblok = dir.fi->fi_blocknum;

	for (hdp = readdir(&dir); hdp; hdp = readdir(&dir)) {
		/*
		 * Compute name length and break loop if there's not
		 * enough space in the output buffer for the next
		 * entry.
		 *
		 *  NOTE: "SLOP" is the number of bytes inserted into the dirent
		 *	  struct's "d_name" field by the compiler to preserve
		 *	  alignment.
		 */
		n = strlen(hdp->hs_ufs_dir.d_name);
		n = roundup((sizeof (struct dirent) + ((n > SLOP) ? n : 0)),
		    sizeof (off_t));

		if (n > size) {
			dir.fi->fi_blocknum = oldblok;
			dir.fi->fi_offset = oldoff;
			break;
		}

		oldblok = dir.fi->fi_blocknum;
		oldoff = dir.loc;
		size -= n;
		cnt += 1;

		(void) strlcpy(dep->d_name, hdp->hs_ufs_dir.d_name,
		    strlen(hdp->hs_ufs_dir.d_name) + 1);
		dep->d_ino = hdp->hs_ufs_dir.d_ino;
		dep->d_off = dir.loc;
		dep->d_reclen = (unsigned short)n;

		dep = (struct dirent *)((char *)dep + n);
	}

#undef SLOP

	return (cnt);
}

static void
hs_dodates(enum hs_vol_type type, struct hs_direntry *hdp, char *bufp)
{
	if (type == HS_VOL_TYPE_HS) {
		hs_parse_dirdate(HDE_cdate(bufp), &hdp->cdate);
		hs_parse_dirdate(HDE_cdate(bufp), &hdp->adate);
		hs_parse_dirdate(HDE_cdate(bufp), &hdp->mdate);
	} else if (type == HS_VOL_TYPE_ISO) {
		hs_parse_dirdate(IDE_cdate(bufp), &hdp->cdate);
		hs_parse_dirdate(IDE_cdate(bufp), &hdp->adate);
		hs_parse_dirdate(IDE_cdate(bufp), &hdp->mdate);
	} else
		prom_panic("hs_dodates:  bad volume type");
}

/*
 * hs_parse_dirdate
 *
 * Parse the short 'directory-format' date into a Unix timeval.
 * This is the date format used in Directory Entries.
 *
 * If the date is not representable, make something up.
 */
void
hs_parse_dirdate(uchar_t *dp, struct timeval *tvp)
{
	int year, month, day, hour, minute, sec, gmtoff;

	year = HDE_DATE_YEAR(dp);
	month = HDE_DATE_MONTH(dp);
	day = HDE_DATE_DAY(dp);
	hour = HDE_DATE_HOUR(dp);
	minute = HDE_DATE_MIN(dp);
	sec = HDE_DATE_SEC(dp);
	gmtoff = HDE_DATE_GMTOFF(dp);

	tvp->tv_usec = 0;
	if (year < THE_EPOCH) {
		tvp->tv_sec = 0;
	} else {
		tvp->tv_sec = hs_date_to_gmtime(year, month, day, gmtoff);
		if (tvp->tv_sec != -1) {
			tvp->tv_sec += ((hour * 60) + minute) * 60 + sec;
		}
	}

	return;

}

/*
 * hs_parse_longdate
 *
 * Parse the long 'user-oriented' date into a Unix timeval.
 * This is the date format used in the Volume Descriptor.
 *
 * If the date is not representable, make something up.
 */
void
hs_parse_longdate(uchar_t *dp, struct timeval *tvp)
{
	int year, month, day, hour, minute, sec, gmtoff;

	year = HSV_DATE_YEAR(dp);
	month = HSV_DATE_MONTH(dp);
	day = HSV_DATE_DAY(dp);
	hour = HSV_DATE_HOUR(dp);
	minute = HSV_DATE_MIN(dp);
	sec = HSV_DATE_SEC(dp);
	gmtoff = HSV_DATE_GMTOFF(dp);

	tvp->tv_usec = 0;
	if (year < THE_EPOCH) {
		tvp->tv_sec = 0;
	} else {
		tvp->tv_sec = hs_date_to_gmtime(year, month, day, gmtoff);
		if (tvp->tv_sec != -1) {
			tvp->tv_sec += ((hour * 60) + minute) * 60 + sec;
			tvp->tv_usec = HSV_DATE_HSEC(dp) * 10000;
		}
	}

}

/* cumulative number of seconds per month,  non-leap and leap-year versions */
static time_t cum_sec[] = {
	0x0, 0x28de80, 0x4dc880, 0x76a700, 0x9e3400, 0xc71280,
	0xee9f80, 0x1177e00, 0x1405c80, 0x167e980, 0x190c800, 0x1b85500
};
static time_t cum_sec_leap[] = {
	0x0, 0x28de80, 0x4f1a00, 0x77f880, 0x9f8580, 0xc86400,
	0xeff100, 0x118cf80, 0x141ae00, 0x1693b00, 0x1921980, 0x1b9a680
};
#define	SEC_PER_DAY	0x15180
#define	SEC_PER_YEAR	0x1e13380

/*
 * hs_date_to_gmtime
 *
 * Convert year(1970-2099)/month(1-12)/day(1-31) to seconds-since-1970/1/1.
 *
 * Returns -1 if the date is out of range.
 */
static time_t
hs_date_to_gmtime(int year, int mon, int day, int gmtoff)
{
	time_t sum;
	time_t *cp;
	int y;

	if ((year < THE_EPOCH) || (year > END_OF_TIME) ||
	    (mon < 1) || (mon > 12) ||
	    (day < 1) || (day > 31))
		return (-1);

	/*
	 * Figure seconds until this year and correct for leap years.
	 * Note: 2000 is a leap year but not 2100.
	 */
	y = year - THE_EPOCH;
	sum = y * SEC_PER_YEAR;
	sum += ((y + 1) / 4) * SEC_PER_DAY;
	/*
	 * Point to the correct table for this year and
	 * add in seconds until this month.
	 */
	cp = ((y + 2) % 4) ? cum_sec : cum_sec_leap;
	sum += cp[mon - 1];
	/*
	 * Add in seconds until 0:00 of this day.
	 * (days-per-month validation is not done here)
	 */
	sum += (day - 1) * SEC_PER_DAY;
	sum -= (gmtoff * 15 * 60);
	return (sum);
}
#
# 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 2004 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# ident	"%Z%%M%	%I%	%E% SMI"
#

LIBRARY = libnfs.a
LOCOBJS = auth_none.o auth_unix.o bootparams.o getdents.o \
	  getdents3.o getdents4.o lookup.o mount.o \
	  nfsops.o nfs2ops.o nfs3ops.o nfs4ops.o pathname.o pmap.o rpc.o \
	  clnt_budp.o clnt_btcp.o nfs_xdr.o nfs3_xdr.o nfs4_xdr.o xdr_rec.o

RPC_CMNOBJS = rpc_prot.o
CMNOBJS = bootparam_xdr.o
OBJECTS = $(LOCOBJS) $(RPC_CMNOBJS) $(CMNOBJS)

include ../Makefile.com

RPC_CMNDIR = $(TOPDIR)/uts/common/rpc
CMNDIR = $(TOPDIR)/uts/common/fs/nfs
SRCS	= $(LOCOBJS:%.o=$(SRCDIR)/%.c) $(RPC_CMNOBJS:%.o=$(RPC_CMNDIR)/%.c) \
		$(CMNOBJS:%.o=$(CMNDIR)/%.c)

LDLIBS += -linet -lsock -lxdr
CPPFLAGS += $(SOCKCPPFLAGS) $(DHCPCPPFLAGS) -I../../inet
CPPFLAGS += -I$(STANDDIR)/lib/sa -I$(TOPDIR)/head

#
# This is really wrong, but we have no choice since <rpc/*.h> needs to
# resolve types that are in <sys/stream.h>.  Thankfully, we don't use
# anything from libsock.a that relies on the definition of an mblk_t.
#
CPPFLAGS += -U_SYS_STREAM_H

objs/%.o: $(RPC_CMNDIR)/%.c
	$(COMPILE.c) -o $@ $<
	$(POST_PROCESS_O)

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 (c) 1997-1999 by Sun Microsystems, Inc.
 * All rights reserved.
 */

#ifndef	_AUTH_INET_H
#define	_AUTH_INET_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#ifdef	__cplusplus
extern "C" {
#endif

extern struct opaque_auth _null_auth;
extern AUTH *authnone_create(void);
extern AUTH *authunix_create(char *, uid_t, gid_t, int, gid_t *);

#ifdef	__cplusplus
}
#endif

#endif	/* _AUTH_INET_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 2004 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/* from SunOS 4.1 */
#pragma ident	"%Z%%M%	%I%	%E% SMI"

/*
 * modified for use by the boot program.
 *
 * auth_none.c
 * Creates a client authentication handle for passing "null"
 * credentials and verifiers to remote systems.
 */

#include <rpc/types.h>
#include <rpc/xdr.h>
#include <rpc/auth.h>
#include "clnt.h"

#define	MAX_MARSHEL_SIZE 20

static struct auth_ops *authnone_ops();

static struct authnone_private {
	AUTH	no_client;
	char	marshalled_client[MAX_MARSHEL_SIZE];
	uint_t	mcnt;
} *authnone_private;

static struct authnone_private authnone_local;

AUTH *
authnone_create(void)
{
	struct authnone_private *ap = authnone_private;
	XDR xdr_stream;
	XDR *xdrs;

	if (ap == 0) {
		ap = &authnone_local;
		authnone_private = ap;
	}
	if (!ap->mcnt) {
		ap->no_client.ah_cred = ap->no_client.ah_verf = _null_auth;
		ap->no_client.ah_ops = authnone_ops();
		xdrs = &xdr_stream;
		xdrmem_create(xdrs, ap->marshalled_client,
			(uint_t)MAX_MARSHEL_SIZE, XDR_ENCODE);
		(void) xdr_opaque_auth(xdrs, &ap->no_client.ah_cred);
		(void) xdr_opaque_auth(xdrs, &ap->no_client.ah_verf);
		ap->mcnt = XDR_GETPOS(xdrs);
		XDR_DESTROY(xdrs);
	}
	return (&ap->no_client);
}

/*ARGSUSED*/
static bool_t
authnone_marshal(AUTH *client, XDR *xdrs, struct cred *cr)
{
	struct authnone_private *ap = authnone_private;

	if (ap == 0)
		return (0);
	return ((*xdrs->x_ops->x_putbytes)(xdrs,
	    ap->marshalled_client, ap->mcnt));
}

/* ARGSUSED */
static void
authnone_verf(AUTH *foo)
{
}

/* ARGSUSED */
static bool_t
authnone_validate(AUTH *foo, struct opaque_auth *bar)
{
	return (TRUE);
}

/* ARGSUSED */
static bool_t
authnone_refresh(AUTH *foo, struct rpc_msg *bar, cred_t *cr)
{
	return (FALSE);
}

/* ARGSUSED */
static void
authnone_destroy(AUTH *foo)
{
}

static struct auth_ops *
authnone_ops(void)
{
	static struct auth_ops ops;

	if (ops.ah_nextverf == NULL) {
		ops.ah_nextverf = authnone_verf;
		ops.ah_marshal = authnone_marshal;
		ops.ah_validate = authnone_validate;
		ops.ah_refresh = authnone_refresh;
		ops.ah_destroy = authnone_destroy;
	}
	return (&ops);
}
/*
 * 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 2004 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/* Copyright (c) 1983, 1984, 1985, 1986, 1987, 1988, 1989 AT&T */
/* All Rights Reserved */

/*
 * Portions of this source code were derived from Berkeley 4.3 BSD
 * under license from the Regents of the University of California.
 */

/*
 * Adapted for use by the boot program.
 *
 * auth_unix.c, Implements UNIX style authentication parameters.
 *
 * The system is very weak.  The client uses no encryption for its
 * credentials and only sends null verifiers.  The server sends backs
 * null verifiers or optionally a verifier that suggests a new short hand
 * for the credentials.
 */

#include <stdlib.h>
#include <sys/sysmacros.h>
#include <rpc/types.h>
#include <rpc/xdr.h>
#include <rpc/auth.h>
#include "clnt.h"
#include <rpc/auth_unix.h>
#include <sys/promif.h>
#include <sys/salib.h>
#include <sys/bootdebug.h>
#include "nfs_inet.h"

static struct auth_ops *authunix_ops();
/*
 * This struct is pointed to by the ah_private field of an auth_handle.
 */
struct audata {
	struct opaque_auth	au_origcred;	/* original credentials */
	struct opaque_auth	au_shcred;	/* short hand cred */
	uint_t			au_shfaults;	/* short hand cache faults */
	char			au_marshed[MAX_AUTH_BYTES];
	uint_t			au_mpos;	/* xdr pos at end of marshed */
};
#define	AUTH_PRIVATE(auth)	((struct audata *)auth->ah_private)

static void marshal_new_auth(AUTH *);

#define	dprintf	if (boothowto & RB_DEBUG) printf

/*
 * Create a unix style authenticator.
 * Returns an auth handle with the given stuff in it.
 */
AUTH *
authunix_create(char *machname, uid_t uid, gid_t gid, int len, gid_t *aup_gids)
{
	struct authunix_parms aup;
	char mymem[MAX_AUTH_BYTES];
	XDR xdrs;
	AUTH *auth;
	struct audata *au;

	/*
	 * Allocate and set up auth handle
	 */
	auth = (AUTH *) bkmem_alloc(sizeof (*auth));
	if (auth == NULL) {
		prom_panic("authunix_create: Cannot allocate memory.");
	}

	au = (struct audata *)bkmem_alloc(sizeof (*au));
	if (au == NULL) {
		prom_panic("authunix_create: Cannot allocate memory.");
	}

	/* setup authenticator. */
	auth->ah_ops = authunix_ops();
	auth->ah_private = (caddr_t)au;

	/* structure copies */
	auth->ah_verf = au->au_shcred = _null_auth;

	au->au_shfaults = 0;

	/*
	 * fill in param struct from the given params
	 */
	aup.aup_time = prom_gettime() / 1000;
	aup.aup_machname = machname;
	aup.aup_uid = uid;
	aup.aup_gid = gid;
	aup.aup_len = (uint_t)len;
	aup.aup_gids = (gid_t *)aup_gids;

	/*
	 * Serialize the parameters into origcred
	 */
	xdrmem_create(&xdrs, mymem, MAX_AUTH_BYTES, XDR_ENCODE);
	if (!xdr_authunix_parms(&xdrs, &aup)) {
		prom_panic("authunix_create:  xdr_authunix_parms failed");
	}
	au->au_origcred.oa_length = len = XDR_GETPOS(&xdrs);
	au->au_origcred.oa_flavor = (uint_t)AUTH_UNIX;
	if ((au->au_origcred.oa_base = bkmem_alloc((uint_t)len)) == NULL) {
		prom_panic("authunix_create: memory alloc failed");
	}
	(void) bcopy(mymem, au->au_origcred.oa_base, (uint_t)len);

	/*
	 * set auth handle to reflect new cred.
	 */
	auth->ah_cred = au->au_origcred;
	marshal_new_auth(auth);
	return (auth);
}

/*
 * authunix operations
 */

/* ARGSUSED */
static void
authunix_nextverf(AUTH *auth)
{
}

/* ARGSUSED */
static bool_t
authunix_marshal(AUTH *auth, XDR *xdrs, cred_t *cr)
{
	struct audata *au = AUTH_PRIVATE(auth);

	return (XDR_PUTBYTES(xdrs, au->au_marshed, au->au_mpos));
}

static bool_t
authunix_validate(AUTH *auth, struct opaque_auth *verf)
{
	struct audata *au;
	XDR xdrs;

	if (verf->oa_flavor == AUTH_SHORT) {
		au = AUTH_PRIVATE(auth);


		xdrmem_create(&xdrs, verf->oa_base, verf->oa_length,
		    XDR_DECODE);

		if (xdr_opaque_auth(&xdrs, &au->au_shcred)) {
			auth->ah_cred = au->au_shcred;
		} else {
			xdrs.x_op = XDR_FREE;
			(void) xdr_opaque_auth(&xdrs, &au->au_shcred);
			au->au_shcred.oa_base = 0;
			auth->ah_cred = au->au_origcred;
		}
		marshal_new_auth(auth);
	}

	return (TRUE);
}

/*ARGSUSED*/
static bool_t
authunix_refresh(AUTH *auth, struct rpc_msg *msg, cred_t *cr)
{
	struct audata *au = AUTH_PRIVATE(auth);
	struct authunix_parms aup;
	XDR xdrs;
	int stat;

	if (auth->ah_cred.oa_base == au->au_origcred.oa_base) {
		/* there is no hope.  Punt */
		return (FALSE);
	}
	au->au_shfaults ++;

	/* first deserialize the creds back into a struct authunix_parms */
	aup.aup_machname = (char *)0;
	aup.aup_gids = (gid_t *)0;
	xdrmem_create(&xdrs, au->au_origcred.oa_base,
			au->au_origcred.oa_length, XDR_DECODE);
	stat = xdr_authunix_parms(&xdrs, &aup);
	if (!stat)
		goto done;

	/* update the time and serialize in place */
	aup.aup_time = (prom_gettime() / 1000);
	xdrs.x_op = XDR_ENCODE;
	(void) XDR_SETPOS(&xdrs, 0);
	stat = xdr_authunix_parms(&xdrs, &aup);
	if (!stat)
		goto done;
	auth->ah_cred = au->au_origcred;
	marshal_new_auth(auth);
done:
	/* free the struct authunix_parms created by deserializing */
	xdrs.x_op = XDR_FREE;
	(void) xdr_authunix_parms(&xdrs, &aup);
	XDR_DESTROY(&xdrs);
	return (stat);
}

static void
authunix_destroy(AUTH *auth)
{
	struct audata *au = AUTH_PRIVATE(auth);

	if (au->au_shcred.oa_base != NULL)
		bkmem_free(au->au_shcred.oa_base, au->au_shcred.oa_length);
	bkmem_free(auth->ah_private, sizeof (struct audata));
	if (auth->ah_verf.oa_base != NULL)
		bkmem_free(auth->ah_verf.oa_base, auth->ah_verf.oa_length);
	bkmem_free((caddr_t)auth, sizeof (*auth));
}

/*
 * Marshals (pre-serializes) an auth struct.
 * sets private data, au_marshed and au_mpos
 */
static void
marshal_new_auth(AUTH *auth)
{
	XDR xdr_stream;
	XDR *xdrs = &xdr_stream;
	struct audata *au = AUTH_PRIVATE(auth);

	xdrmem_create(xdrs, au->au_marshed, MAX_AUTH_BYTES, XDR_ENCODE);
	if ((!xdr_opaque_auth(xdrs, &(auth->ah_cred))) ||
	    (!xdr_opaque_auth(xdrs, &(auth->ah_verf)))) {
		dprintf("marshal_new_auth - Fatal marshalling problem");
	} else {
		au->au_mpos = XDR_GETPOS(xdrs);
	}
	XDR_DESTROY(xdrs);
}


static struct auth_ops *
authunix_ops(void)
{
	static struct auth_ops ops;

	if (ops.ah_nextverf == 0) {
		ops.ah_nextverf = authunix_nextverf;
		ops.ah_marshal = authunix_marshal;
		ops.ah_validate = authunix_validate;
		ops.ah_refresh = authunix_refresh;
		ops.ah_destroy = authunix_destroy;
	}
	return (&ops);
}

/*
 * XDR for unix authentication parameters.
 */
bool_t
xdr_authunix_parms(XDR *xdrs, struct authunix_parms *p)
{
	if (xdr_u_int(xdrs, &(p->aup_time)) &&
	    xdr_string(xdrs, &(p->aup_machname), MAX_MACHINE_NAME) &&
	    xdr_int(xdrs, (int *)&(p->aup_uid)) &&
	    xdr_int(xdrs, (int *)&(p->aup_gid)) &&
	    xdr_array(xdrs, (caddr_t *)&(p->aup_gids),
		    &(p->aup_len), NGRPS, sizeof (int), xdr_int)) {
		return (TRUE);
	}
	return (FALSE);
}
/*
 * 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 2004 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * This file contains routines responsible for getting the system's
 * name and boot params. Most of it comes from the SVR4 diskless boot
 * code (dlboot_inet), modified to work in a non socket environment.
 */

#include <sys/types.h>
#include <rpc/types.h>
#include <sys/errno.h>
#include <rpc/auth.h>
#include <rpc/xdr.h>
#include <rpc/rpc_msg.h>
#include <sys/t_lock.h>
#include "clnt.h"
#include <rpc/rpc.h>
#include <sys/utsname.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <net/if.h>
#include <netinet/if_ether.h>
#include <netinet/in.h>
#include <sys/promif.h>
#include <rpcsvc/bootparam.h>
#include "pmap.h"
#include "brpc.h"
#include "socket_inet.h"
#include "ipv4.h"
#include <sys/salib.h>
#include <sys/bootdebug.h>

extern int errno;
static struct bp_whoami_res	bp;
static char			bp_hostname[SYS_NMLN+1];
static char			bp_domainname[SYS_NMLN+1];
static struct in_addr		responder; /* network order */

static const char *noserver =
	"No bootparam (%s) server responding; still trying...\n";

#define	GETFILE_BTIMEO		1
#define	GETFILE_BRETRIES	2

#define	dprintf	if (boothowto & RB_DEBUG) printf

/*
 * Returns TRUE if it has set the global structure 'bp' to our boot
 * parameters, FALSE if some failure occurred.
 */
bool_t
whoami(void)
{
	struct bp_whoami_arg	arg;
	struct sockaddr_in	to, from;
	struct in_addr		ipaddr;
	enum clnt_stat		stat;
	bool_t			retval = TRUE;
	int			rexmit;		/* retransmission interval */
	int			resp_wait;	/* secs to wait for resp */
	int			namelen;
	int			printed_waiting_msg;

	/*
	 * Set our destination IP address to the limited broadcast address
	 * (INADDR_BROADCAST).
	 */
	to.sin_family = AF_INET;
	to.sin_addr.s_addr = htonl(INADDR_BROADCAST);
	to.sin_port = htons(0);

	/*
	 * Set up the arguments expected by bootparamd.
	 */
	arg.client_address.address_type = IP_ADDR_TYPE;
	ipv4_getipaddr(&ipaddr);
	ipaddr.s_addr = htonl(ipaddr.s_addr);
	bcopy((caddr_t)&ipaddr,
		(caddr_t)&arg.client_address.bp_address_u.ip_addr,
		sizeof (ipaddr));

	/*
	 * Retransmit/wait for up to resp_wait secs.
	 */
	rexmit = 0;	/* start at default retransmission interval. */
	resp_wait = 16;

	bp.client_name = &bp_hostname[0];
	bp.domain_name = &bp_domainname[0];

	/*
	 * Do a broadcast call to find a bootparam daemon that
	 * will tell us our hostname, domainname and any
	 * router that we have to use to talk to our NFS server.
	 */
	printed_waiting_msg = 0;
	do {
		/*
		 * First try the SunOS portmapper and if no reply is
		 * received will then try the SVR4 rpcbind.
		 * Either way, `bootpaddr' will be set to the
		 * correct address for the bootparamd that responds.
		 */
		stat = bpmap_rmtcall((rpcprog_t)BOOTPARAMPROG,
		    (rpcvers_t)BOOTPARAMVERS, (rpcproc_t)BOOTPARAMPROC_WHOAMI,
		    xdr_bp_whoami_arg, (caddr_t)&arg,
		    xdr_bp_whoami_res, (caddr_t)&bp, rexmit, resp_wait,
			&to, &from, AUTH_NONE);
		if (stat == RPC_TIMEDOUT && !printed_waiting_msg) {
			dprintf(noserver, "whoami");
			printed_waiting_msg = 1;
		}
		/*
		 * Retransmission interval for second and subsequent tries.
		 * We expect first bpmap_rmtcall to retransmit and backoff to
		 * at least this value.
		 */
		rexmit = resp_wait;
		resp_wait = 0;		/* go to default wait now. */
	} while (stat == RPC_TIMEDOUT);

	if (stat != RPC_SUCCESS) {
		dprintf("whoami RPC call failed with rpc status: %d\n", stat);
		retval = FALSE;
		goto done;
	} else {
		if (printed_waiting_msg && (boothowto & RB_VERBOSE))
			printf("Bootparam response received\n");

		/* Cache responder... We'll send our getfile here... */
		responder.s_addr = from.sin_addr.s_addr;
	}

	namelen = strlen(bp.client_name);
	if (namelen > SYS_NMLN) {
		dprintf("whoami: hostname too long");
		retval = FALSE;
		goto done;
	}
	if (namelen > 0) {
		if (boothowto & RB_VERBOSE)
			printf("hostname: %s\n", bp.client_name);
		(void) sethostname(bp.client_name, namelen);
	} else {
		dprintf("whoami: no host name\n");
		retval = FALSE;
		goto done;
	}

	namelen = strlen(bp.domain_name);
	if (namelen > SYS_NMLN) {
		dprintf("whoami: domainname too long");
		retval = FALSE;
		goto done;
	}
	if (namelen > 0)
		if (boothowto & RB_VERBOSE)
			printf("domainname: %s\n", bp.domain_name);
	else
		dprintf("whoami: no domain name\n");

	if (bp.router_address.address_type == IP_ADDR_TYPE) {
		bcopy((caddr_t)&bp.router_address.bp_address_u.ip_addr,
		    (caddr_t)&ipaddr, sizeof (ipaddr));
		if (ntohl(ipaddr.s_addr) != INADDR_ANY) {
			dprintf("whoami: Router ip is: %s\n",
			    inet_ntoa(ipaddr));
			/* ipv4_route expects IP addresses in network order */
			(void) ipv4_route(IPV4_ADD_ROUTE, RT_DEFAULT, NULL,
			    &ipaddr);
		}
	} else
		dprintf("whoami: unknown gateway addr family %d\n",
		    bp.router_address.address_type);
done:
	return (retval);
}

/*
 * Returns:
 *	1) The ascii form of our root servers name in `server_name'.
 *	2) Pathname of our root on the server in `server_path'.
 *
 * NOTE: it's ok for getfile() to do dynamic allocation - it's only
 * used locally, then freed. If the server address returned from the
 * getfile call is different from our current destination address,
 * reset destination IP address to the new value.
 */
bool_t
getfile(char *fileid, char *server_name, struct in_addr *server_ip,
    char *server_path)
{
	struct bp_getfile_arg	arg;
	struct bp_getfile_res	res;
	enum clnt_stat		stat;
	struct sockaddr_in	to, from;
	int			rexmit;
	int			wait;
	uint_t			max_retries = 0xFFFFFFFF;
	int			def_rexmit = 0;
	int			def_wait = 32;
	int			printed_waiting_msg;

	/*
	 * For non-root requests, set a smaller timeout
	 */
	if (strcmp(fileid, "root") != 0) {
		/*
		 * Only send one request per call
		 */
		def_wait = GETFILE_BTIMEO;
		def_rexmit = GETFILE_BTIMEO;
		max_retries = GETFILE_BRETRIES;
	}

	arg.client_name = bp.client_name;
	arg.file_id = fileid;

	res.server_name = (bp_machine_name_t)bkmem_zalloc(SYS_NMLN + 1);
	res.server_path = (bp_path_t)bkmem_zalloc(SYS_NMLN + 1);

	if (res.server_name == NULL || res.server_path == NULL) {
		dprintf("getfile: rpc_call failed: No memory\n");
		errno = ENOMEM;
		if (res.server_name != NULL)
			bkmem_free(res.server_name, SYS_NMLN + 1);
		if (res.server_path != NULL)
			bkmem_free(res.server_path, SYS_NMLN + 1);
		return (FALSE);
	}

	to.sin_family = AF_INET;
	to.sin_addr.s_addr = responder.s_addr;
	to.sin_port = htons(0);

	/*
	 * Our addressing information was filled in by the call to
	 * whoami(), so now send an rpc message to the
	 * bootparam daemon requesting our server information.
	 *
	 * Wait only 32 secs for rpc_call to succeed.
	 */
	rexmit = def_rexmit;
	wait = def_wait;

	stat = brpc_call((rpcprog_t)BOOTPARAMPROG, (rpcvers_t)BOOTPARAMVERS,
	    (rpcproc_t)BOOTPARAMPROC_GETFILE, xdr_bp_getfile_arg, (caddr_t)&arg,
	    xdr_bp_getfile_res, (caddr_t)&res, rexmit, wait,
				&to, &from, AUTH_NONE);

	if (stat == RPC_TIMEDOUT) {
		/*
		 * The server that answered the whoami doesn't
		 * answer our getfile. Broadcast the call to all. Keep
		 * trying forever. Set up for limited broadcast.
		 */
		to.sin_addr.s_addr = htonl(INADDR_BROADCAST);
		to.sin_port = htons(0);

		rexmit = def_rexmit;	/* use default rexmit interval */
		wait = def_wait;
		printed_waiting_msg = 0;
		do {
			/*
			 * Limit the number of retries
			 */
			if (max_retries-- == 0)
				break;

			stat = bpmap_rmtcall((rpcprog_t)BOOTPARAMPROG,
			    (rpcvers_t)BOOTPARAMVERS,
			    (rpcproc_t)BOOTPARAMPROC_GETFILE,
			    xdr_bp_getfile_arg, (caddr_t)&arg,
			    xdr_bp_getfile_res, (caddr_t)&res, rexmit,
			    wait, &to, &from, AUTH_NONE);

			if (stat == RPC_SUCCESS) {
				/*
				 * set our destination addresses to
				 * those of the server that responded.
				 * It's probably our server, and we
				 * can thus save arping for no reason later.
				 */
				responder.s_addr = from.sin_addr.s_addr;
				if (printed_waiting_msg &&
				    (boothowto & RB_VERBOSE)) {
					printf(
					    "Bootparam response received.\n");
				}
				break;
			}
			if (stat == RPC_TIMEDOUT && !printed_waiting_msg) {
				dprintf(noserver, "getfile");
				printed_waiting_msg = 1;
			}
			/*
			 * Retransmission interval for second and
			 * subsequent tries. We expect first bpmap_rmtcall
			 * to retransmit and backoff to at least this
			 * value.
			 */
			rexmit = wait;
			wait = def_wait;
		} while (stat == RPC_TIMEDOUT);
	}

	if (stat == RPC_SUCCESS) {
		/* got the goods */
		bcopy(res.server_name, server_name, strlen(res.server_name));
		bcopy(res.server_path, server_path, strlen(res.server_path));
		switch (res.server_address.address_type) {
		case IP_ADDR_TYPE:
			/*
			 * server_address is where we will get our root
			 * from. Replace destination entries in address if
			 * necessary.
			 */
			bcopy((caddr_t)&res.server_address.bp_address_u.ip_addr,
			    (caddr_t)server_ip, sizeof (struct in_addr));
			break;
		default:
			dprintf("getfile: unknown address type %d\n",
				res.server_address.address_type);
			server_ip->s_addr = htonl(INADDR_ANY);
			bkmem_free(res.server_name, SYS_NMLN + 1);
			bkmem_free(res.server_path, SYS_NMLN + 1);
			return (FALSE);
		}
	} else {
		dprintf("getfile: rpc_call failed.\n");
		bkmem_free(res.server_name, SYS_NMLN + 1);
		bkmem_free(res.server_path, SYS_NMLN + 1);
		return (FALSE);
	}

	bkmem_free(res.server_name, SYS_NMLN + 1);
	bkmem_free(res.server_path, SYS_NMLN + 1);

	return (TRUE);
}
/*
 * 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 2004 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef	_BRPC_H
#define	_BRPC_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#include <rpc/rpc.h>

#ifdef	__cplusplus
extern "C" {
#endif

#define	RPC_ALLOWABLE_ERRORS	(10)	/* Threshold on receiving bad results */
#define	RPC_REXMIT_MSEC		(500)	/* default 1/2 second retransmissions */
#define	RPC_RCVWAIT_MSEC	(20000)	/* default response waittime */

extern enum clnt_stat brpc_call(rpcprog_t, rpcvers_t, rpcproc_t, xdrproc_t,
	caddr_t, xdrproc_t, caddr_t, int, int, struct sockaddr_in *,
	struct sockaddr_in *, uint_t);

extern void rpc_disperr(struct rpc_err *stat);

#ifdef	__cplusplus
}
#endif

#endif	/* _BRPC_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 2004 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 *
 * clnt.h - Client side remote procedure call interface.
 * Stripped down sockets based client for boot.
 */

#ifndef _RPC_CLNT_H
#define	_RPC_CLNT_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#include <sys/types.h>
#include <rpc/clnt_stat.h>
#include <rpc/auth.h>
#include <netinet/in.h>

#ifdef	__cplusplus
extern "C" {
#endif

/*
 * Error info.
 */
struct rpc_err {
	enum clnt_stat re_status;
	union {
		int RE_errno;		/* realated system error */
		enum auth_stat RE_why;	/* why the auth error occurred */
	} ru;
#define	re_errno	ru.RE_errno
#define	re_why		ru.RE_why
};


/*
 * Client rpc handle.
 * Created by individual implementations, see e.g. rpc_udp.c.
 * Client is responsible for initializing auth, see e.g. auth_none.c.
 */
typedef struct __client {
	AUTH	*cl_auth;			/* authenticator */
	struct clnt_ops {
				/* call remote procedure */
		enum clnt_stat	(*cl_call)(struct __client *, rpcproc_t,
					xdrproc_t, caddr_t, xdrproc_t,
					caddr_t, struct timeval);
				/* abort a call */
		void		(*cl_abort)(/* various */);
				/* get specific error code */
		void		(*cl_geterr)(struct __client *,
					struct rpc_err *);
				/* frees results */
		bool_t		(*cl_freeres)(struct __client *, xdrproc_t,
					caddr_t);
				/* destroy this structure */
		void		(*cl_destroy)(struct __client *);
				/* the ioctl() of rpc */
		bool_t		(*cl_control)(struct __client *, int, char *);
	} *cl_ops;
	caddr_t			cl_private;	/* private stuff */
} CLIENT;


/*
 * client side rpc interface ops
 *
 * Parameter types are:
 *
 */

/*
 * enum clnt_stat
 * CLNT_CALL(rh, proc, xargs, argsp, xres, resp, timeout)
 * 	CLIENT *rh;
 *	ulong_t proc;
 *	xdrproc_t xargs;
 *	caddr_t argsp;
 *	xdrproc_t xres;
 *	caddr_t resp;
 *	struct timeval timeout;
 */
#define	CLNT_CALL(rh, proc, xargs, argsp, xres, resp, secs)	\
	((*(rh)->cl_ops->cl_call)(rh, proc, xargs, argsp, xres, resp, secs))

/*
 * void
 * CLNT_ABORT(rh);
 * 	CLIENT *rh;
 */
#define	CLNT_ABORT(rh)	((*(rh)->cl_ops->cl_abort)(rh))

/*
 * struct rpc_err
 * CLNT_GETERR(rh);
 * 	CLIENT *rh;
 */
#define	CLNT_GETERR(rh, errp)	((*(rh)->cl_ops->cl_geterr)(rh, errp))

/*
 * bool_t
 * CLNT_FREERES(rh, xres, resp);
 * 	CLIENT *rh;
 *	xdrproc_t xres;
 *	caddr_t resp;
 */
#define	CLNT_FREERES(rh, xres, resp) ((*(rh)->cl_ops->cl_freeres)\
	(rh, xres, resp))

/*
 * bool_t
 * CLNT_CONTROL(cl, request, info)
 *	CLIENT *cl;
 *	uint_t request;
 *	char *info;
 */
#define	CLNT_CONTROL(cl, rq, in) ((*(cl)->cl_ops->cl_control)(cl, rq, in))

/*
 * control operations that apply to both udp and tcp transports
 */
#define	CLSET_TIMEOUT		1   /* set timeout (timeval) */
#define	CLGET_TIMEOUT		2   /* get timeout (timeval) */
#define	CLGET_SERVER_ADDR	3   /* get server's address (sockaddr) */
#define	CLGET_FD		6   /* get connections file descriptor */
#define	CLSET_FD_CLOSE		8   /* close fd while clnt_destroy */
#define	CLSET_FD_NCLOSE		9   /* Do not close fd while clnt_destroy */
/*
 * udp only control operations
 */
#define	CLSET_RETRY_TIMEOUT 4   /* set retry timeout (timeval) */
#define	CLGET_RETRY_TIMEOUT 5   /* get retry timeout (timeval) */

/*
 * void
 * CLNT_DESTROY(rh);
 * 	CLIENT *rh;
 */
#define	CLNT_DESTROY(rh)	((*(rh)->cl_ops->cl_destroy)(rh))

/*
 * By convention, procedure 0 takes null arguments and returns them
 */

#define	NULLPROC ((ulong_t)0)

/*
 * Below are the client handle creation routines for the various
 * implementations of client side rpc.  They can return NULL if a
 * creation failure occurs.
 */

/*
 * UDP based rpc.
 * CLIENT *
 * clntbudp_create(raddr, program, version, wait, sockp)
 *	struct sockaddr_in *raddr;
 *	ulong_t program;
 *	ulong_t version;
 *	struct timeval wait;
 *	int *sockp;
 *
 * Same as above, but you specify max packet sizes.
 * CLIENT *
 * clntbudp_bufcreate(raddr, program, version, wait, sockp, sendsz, recvsz)
 *	struct sockaddr_in *raddr;
 *	ulong_t program;
 *	ulong_t version;
 *	struct timeval wait;
 *	int *sockp;
 *	uint_t sendsz;
 *	uint_t recvsz;
 */
extern CLIENT *clntbudp_create(struct sockaddr_in *raddr, rpcprog_t program,
				rpcvers_t version, struct timeval wait,
				int *sockp);
extern CLIENT *clntbudp_bufcreate(struct sockaddr_in *raddr, rpcprog_t program,
				rpcvers_t version, struct timeval wait,
				int *sockp, uint_t sendsz, uint_t recvsz);

/*
 * TCP based rpc.
 * CLIENT *
 * clntbtcp_create(raddr, program, version, wait, sockp, sendsz, recvsz)
 *	struct sockaddr_in *raddr;
 *	ulong_t program;
 *	ulong_t version;
 *	struct timeval wait;
 *	int *sockp;
 *	uint_t sendsz;
 *	uint_t recvsz;
 *
 */
extern CLIENT *clntbtcp_create(struct sockaddr_in *raddr, rpcprog_t program,
				rpcvers_t version, struct timeval wait,
				int *sockp, uint_t sendsz, uint_t recvsz);
/*
 * If a creation fails, the following allows the user to figure out why.
 */
struct rpc_createerr {
	enum clnt_stat cf_stat;
	struct rpc_err cf_error; /* useful when cf_stat == RPC_PMAPFAILURE */
};

extern struct rpc_createerr rpc_createerr;

#define	UDPMSGSIZE	8800	/* rpc imposed limit on udp msg size */
#define	RPCSMALLMSGSIZE	400	/* a more reasonable packet size */
#define	TCPMSGSIZE	(32 * 1024) /* reasonably sized RPC/TCP msg */
#ifdef	__cplusplus
}
#endif

#endif /* !_RPC_CLNT_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 2004 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/* Copyright (c) 1983, 1984, 1985, 1986, 1987, 1988, 1989 AT&T */
/* All Rights Reserved */

/*
 * Portions of this source code were derived from Berkeley 4.3 BSD
 * under license from the Regents of the University of California.
 */

/*
 * Boot subsystem client side rpc (TCP)
 */

#include <sys/salib.h>
#include <sys/errno.h>
#include <rpc/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include "socket_inet.h"
#include "ipv4.h"
#include "clnt.h"
#include <rpc/rpc.h>
#include "brpc.h"
#include "pmap.h"
#include <sys/promif.h>
#include <rpc/xdr.h>
#include <rpc/auth.h>
#include <rpc/auth_sys.h>
#include "auth_inet.h"
#include <rpc/rpc_msg.h>
#include <sys/bootdebug.h>

#define	dprintf if (boothowto & RB_DEBUG) printf

#define	MCALL_MSG_SIZE 24

extern int errno;

extern void xdrrec_create();
extern bool_t xdrrec_endofrecord();
extern bool_t xdrrec_skiprecord();

/*
 * If we create another clnt type this should be
 * moved to a common file
 */
struct rpc_createerr rpc_createerr;

static int readtcp();
static int writetcp();

static struct clnt_ops *clntbtcp_ops();

/*
 * Private data kept per client handle
 */
struct ct_data {
	int			ct_sock;
	bool_t			ct_closeit;
	struct sockaddr_in	ct_raddr;
	uint_t			ct_wait_msec;
	struct timeval		ct_total;
	struct rpc_err		ct_error;
	XDR			ct_xdrs;
	char			ct_mcall[MCALL_MSG_SIZE];
	uint_t			ct_mpos;
	uint_t			ct_xdrpos;
};

/*
 * Create a TCP based client handle.
 * If *sockp<0, *sockp is set to a newly created TCP socket.
 * If raddr->sin_port is 0 a binder on the remote machine
 * is consulted for the correct port number.
 * NB: It is the clients responsibility to close *sockp.
 * NB: The rpch->cl_auth is initialized to null authentication.
 *	Caller may wish to set this something more useful.
 *
 * wait is the amount of time used between retransmitting a call if
 * no response has been heard;  retransmition occurs until the actual
 * rpc call times out.
 *
 * sendsz and recvsz are the maximum allowable packet sizes that can be
 * sent and received.
 */
CLIENT *
clntbtcp_create(
	struct sockaddr_in *raddr,
	rpcprog_t program,
	rpcvers_t version,
	struct timeval wait,
	int *sockp,
	uint_t sendsz,
	uint_t recvsz)
{
	CLIENT *cl;
	struct ct_data *ct;
	struct rpc_msg call_msg;
#if 0	/* XXX not yet */
	int min_buf_sz;
	int pref_buf_sz = 64 * 1024; /* 64 KB */
	socklen_t optlen;
#endif /* not yet */
	cl = (CLIENT *)bkmem_alloc(sizeof (CLIENT));
	if (cl == NULL) {
		errno = ENOMEM;
		rpc_createerr.cf_stat = RPC_SYSTEMERROR;
		rpc_createerr.cf_error.re_errno = errno;
		return ((CLIENT *)NULL);
	}

	ct = (struct ct_data *)bkmem_alloc(sizeof (*ct));
	if (ct == NULL) {
		errno = ENOMEM;
		rpc_createerr.cf_stat = RPC_SYSTEMERROR;
		rpc_createerr.cf_error.re_errno = errno;
		goto fooy;
	}

	if (raddr->sin_port == 0) {
		ushort_t port;
		if ((port = bpmap_getport(program, version,
				&(rpc_createerr.cf_stat), raddr, NULL)) == 0) {
			goto fooy;
		}
		raddr->sin_port = htons(port);
	}

	if (*sockp < 0) {
		struct sockaddr_in from;

		*sockp = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
		if (*sockp < 0) {
			rpc_createerr.cf_stat = RPC_SYSTEMERROR;
			rpc_createerr.cf_error.re_errno = errno;
			goto fooy;
		}
		/*
		 * Bootparams assumes a local net, so be sure to let lower
		 * layer protocols know not to route.
		 */
		if (dontroute) {
			(void) setsockopt(*sockp, SOL_SOCKET, SO_DONTROUTE,
				(const void *)&dontroute, sizeof (dontroute));
		}

		/* attempt to bind to priv port */
		from.sin_family = AF_INET;
		ipv4_getipaddr(&from.sin_addr);
		from.sin_addr.s_addr = htonl(from.sin_addr.s_addr);
		from.sin_port = get_source_port(TRUE);

		if (bind(*sockp, (struct sockaddr *)&from, sizeof (from)) < 0) {
			rpc_createerr.cf_stat = RPC_SYSTEMERROR;
			rpc_createerr.cf_error.re_errno = errno;
			if (*sockp > 0)
				(void) close(*sockp);
			goto fooy;
		}

		if (connect(*sockp, (struct sockaddr *)raddr,
			    sizeof (struct sockaddr_in)) < 0) {
			rpc_createerr.cf_stat = RPC_SYSTEMERROR;
			rpc_createerr.cf_error.re_errno = errno;
			if (*sockp > 0)
				(void) close(*sockp);
			goto fooy;
		}

#if 0 /* XXX not yet */
		/*
		 * In the future we may want RPC to use larger transfer sizes
		 * over TCP.  In this case we will want to increase the
		 * window size.
		 */
		/*
		 * Resize the receive window if possible
		 */
		optlen = sizeof (int);
		if (getsockopt(*sockp, SOL_SOCKET, SO_RCVBUF,
				(void *)&min_buf_sz, &optlen) != 0)
			goto keep_going;

		if (min_buf_sz < pref_buf_sz)
			(void) setsockopt(*sockp, SOL_SOCKET, SO_RCVBUF,
				(const void *)&pref_buf_sz, sizeof (int));

keep_going:
#endif		/* not yet */
		ct->ct_closeit = TRUE;
	} else
		ct->ct_closeit = FALSE;

	/*
	 * Set up the private data
	 */
	ct->ct_sock = *sockp;
	ct->ct_wait_msec = 0;
	ct->ct_total.tv_sec = wait.tv_sec;
	ct->ct_total.tv_usec = -1;
	ct->ct_raddr = *raddr;

	/*
	 * Initialize the call message
	 */

	/*
	 * XXX - The xid might need to be randomized more.  Imagine if there
	 * are a rack of blade servers all booting at the same time.  They
	 * may cause havoc on the server with xid replays.
	 */
	call_msg.rm_xid = (uint_t)prom_gettime() + 1;
	call_msg.rm_direction = CALL;
	call_msg.rm_call.cb_rpcvers = RPC_MSG_VERSION;
	call_msg.rm_call.cb_prog = program;
	call_msg.rm_call.cb_vers = version;

	/*
	 * pre-serialize the static part of the call msg and stash it away
	 */
	xdrmem_create(&(ct->ct_xdrs), ct->ct_mcall, MCALL_MSG_SIZE,
			XDR_ENCODE);
	if (! xdr_callhdr(&(ct->ct_xdrs), &call_msg)) {
		if (ct->ct_closeit)
			(void) close(*sockp);
		goto fooy;
	}
	ct->ct_mpos = XDR_GETPOS(&(ct->ct_xdrs));
	XDR_DESTROY(&(ct->ct_xdrs));

	/*
	 * XXX - Memory allocations can fail in xdrrec_create, so we need to
	 * be able to catch those errors.
	 */
	xdrrec_create(&(ct->ct_xdrs), sendsz, recvsz, (caddr_t)ct, readtcp,
			writetcp);

	cl->cl_ops = clntbtcp_ops();
	cl->cl_private = (caddr_t)ct;
	cl->cl_auth = authnone_create();
	return (cl);

fooy:
	if (ct)
		bkmem_free((caddr_t)ct, sizeof (*ct));
	if (cl)
		bkmem_free((caddr_t)cl, sizeof (CLIENT));
	return ((CLIENT *)NULL);
}

static enum clnt_stat
clntbtcp_call(
	CLIENT *cl,
	rpcproc_t proc,
	xdrproc_t xargs,
	caddr_t argsp,
	xdrproc_t xdr_results,
	caddr_t resultsp,
	struct timeval utimeout)
{
	struct ct_data *ct;
	XDR *xdrs;
	struct rpc_msg reply_msg;
	uint32_t x_id;
	uint32_t *msg_x_id;
	bool_t shipnow;
	int nrefreshes = 2;	/* number of times to refresh cred */
	struct timeval timeout;

	ct = (struct ct_data *)cl->cl_private;
	msg_x_id = (uint32_t *)ct->ct_mcall;

	xdrs = &(ct->ct_xdrs);

	ct->ct_total = utimeout;

	/*
	 * We have to be able to wait for some non-zero period of time, so
	 * use a default timeout.
	 */
	if (ct->ct_total.tv_sec == 0)
		ct->ct_total.tv_sec = RPC_RCVWAIT_MSEC / 1000;

	ct->ct_wait_msec = ct->ct_total.tv_sec * 1000 +
		ct->ct_total.tv_usec / 1000;

	timeout = ct->ct_total;

	shipnow = (xdr_results == (xdrproc_t)0 && timeout.tv_sec == 0 &&
			timeout.tv_usec == 0) ? FALSE : TRUE;

call_again:
	xdrs->x_op = XDR_ENCODE;
	ct->ct_error.re_status = RPC_SUCCESS;
	x_id = ntohl(++(*msg_x_id));
	if ((! XDR_PUTBYTES(xdrs, ct->ct_mcall, ct->ct_mpos)) ||
	    (! XDR_PUTINT32(xdrs, (int32_t *)&proc)) ||
	    (! AUTH_MARSHALL(cl->cl_auth, xdrs, NULL)) ||
	    (! (*xargs)(xdrs, argsp))) {
		(void) xdrrec_endofrecord(xdrs, TRUE);
		ct->ct_error.re_status = RPC_CANTENCODEARGS;
		printf("clntbtcp_call: xdr encode args failed\n");
		return (ct->ct_error.re_status);
	}

	if (!xdrrec_endofrecord(xdrs, shipnow)) {
		printf("clntbtcp_call: rpc cansend error\n");
		ct->ct_error.re_status = RPC_CANTSEND;
		return (ct->ct_error.re_status);
	}

	if (!shipnow)
		return (RPC_SUCCESS);

	if (timeout.tv_sec == 0 && timeout.tv_usec == 0) {
		ct->ct_error.re_status = RPC_TIMEDOUT;
		return (ct->ct_error.re_status);
	}

	xdrs->x_op = XDR_DECODE;

	/* CONSTCOND */
	while (TRUE) {
		reply_msg.acpted_rply.ar_verf = _null_auth;
		reply_msg.acpted_rply.ar_results.where = NULL;
		reply_msg.acpted_rply.ar_results.proc = xdr_void;
		if (!xdrrec_skiprecord(xdrs)) {
			return (ct->ct_error.re_status);
		}

		if (!xdr_replymsg(xdrs, &reply_msg)) {
			if (ct->ct_error.re_status == RPC_SUCCESS)
				continue;
			return (ct->ct_error.re_status);
		}
		if (reply_msg.rm_xid == x_id) {
			break;
		}
	}

	/*
	 * process header
	 */
	_seterr_reply(&reply_msg, &(ct->ct_error));
	if (ct->ct_error.re_status == RPC_SUCCESS) {
		if (!AUTH_VALIDATE(cl->cl_auth,
				&reply_msg.acpted_rply.ar_verf)) {
			ct->ct_error.re_status = RPC_AUTHERROR;
			ct->ct_error.re_why = AUTH_INVALIDRESP;
		} else if (!(*xdr_results)(xdrs, resultsp)) {
			if (ct->ct_error.re_status == RPC_SUCCESS) {
				ct->ct_error.re_status = RPC_CANTDECODERES;
			}
		}
		if (reply_msg.acpted_rply.ar_verf.oa_base != NULL) {
			xdrs->x_op = XDR_FREE;
			(void) xdr_opaque_auth(xdrs,
				&(reply_msg.acpted_rply.ar_verf));
		}
	} else {
		if (nrefreshes-- && AUTH_REFRESH(cl->cl_auth, &reply_msg,
						NULL)) {
			goto call_again;
		}
	}
	return (ct->ct_error.re_status);
}

/*
 * Interface between xdr serializer and tcp connection.
 * Behaves like the system calls, read & write, but keeps some error state
 * around for the rpc level.
 */
static int
readtcp(struct ct_data *ct,
	caddr_t buf,
	int len)
{
	int inlen = 0;
	uint_t start, diff;
	struct sockaddr from;
	uint_t fromlen = sizeof (from);

	if (len <= 0)
		return (0);

	/*
	 * Do non-blocking reads here until we get some data or timeout
	 */
	start = prom_gettime();
	while ((inlen = recvfrom(ct->ct_sock, buf, len, 0, &from,
					&fromlen)) == 0) {
		diff = (uint_t)(prom_gettime() - start);
		if (diff > ct->ct_wait_msec) {
			errno = ETIMEDOUT;
			inlen = -1;
			break;
		}
	}
#ifdef DEBUG
	printf("readtcp: inlen = %d\n", inlen);
#endif
	switch (inlen) {
	case 0:
		/* premature eof */
		ct->ct_error.re_errno = ECONNRESET;
		ct->ct_error.re_status = RPC_CANTRECV;
		inlen = -1;  /* it's really an error */
		break;
	case -1:
		ct->ct_error.re_errno = errno;
		ct->ct_error.re_status = RPC_CANTRECV;
		break;
	}

	return (inlen);
}

static int
writetcp(ct, buf, len)
	struct ct_data *ct;
	caddr_t buf;
	int len;
{
	register int i, cnt;

	for (cnt = len; cnt > 0; cnt -= i, buf += i) {
		if ((i = sendto(ct->ct_sock, (void *)buf, cnt, 0,
				(struct sockaddr *)&(ct->ct_raddr),
				sizeof (ct->ct_raddr))) == -1) {
			ct->ct_error.re_errno = errno;
			ct->ct_error.re_status = RPC_CANTSEND;
			return (-1);
		}
	}
	return (len);
}

static void
clntbtcp_geterr(
	CLIENT *cl,
	struct rpc_err *errp)
{
	struct ct_data *ct = (struct ct_data *)cl->cl_private;

	*errp = ct->ct_error;
}


static bool_t
clntbtcp_freeres(
	CLIENT *cl,
	xdrproc_t xdr_res,
	caddr_t res_ptr)
{
	struct ct_data *ct = (struct ct_data *)cl->cl_private;
	XDR *xdrs = &(ct->ct_xdrs);

	xdrs->x_op = XDR_FREE;
	return ((*xdr_res)(xdrs, res_ptr));
}

static void
clntbtcp_abort()
	/* CLIENT *h; */
{
}

/* ARGSUSED */
static bool_t
clntbtcp_control(
	CLIENT *cl,
	int request,
	char *info)
{
	/* Not implemented in boot */
	return (FALSE);
}

static void
clntbtcp_destroy(CLIENT *cl)
{
	struct ct_data *ct = (struct ct_data *)cl->cl_private;

	if (ct->ct_closeit) {
		(void) socket_close(ct->ct_sock);
	}
	XDR_DESTROY(&(ct->ct_xdrs));
	bkmem_free((caddr_t)ct, (sizeof (struct ct_data)));
	bkmem_free((caddr_t)cl, sizeof (CLIENT));
}

static struct clnt_ops *
clntbtcp_ops()
{
	static struct clnt_ops ops;

	if (ops.cl_call == NULL) {
		ops.cl_call = clntbtcp_call;
		ops.cl_abort = clntbtcp_abort;
		ops.cl_geterr = clntbtcp_geterr;
		ops.cl_freeres = clntbtcp_freeres;
		ops.cl_destroy = clntbtcp_destroy;
		ops.cl_control = clntbtcp_control;
	}
	return (&ops);
}
/*
 * 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 2006 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/* Copyright (c) 1983, 1984, 1985, 1986, 1987, 1988, 1989 AT&T */
/* All Rights Reserved */

/*
 * Portions of this source code were derived from Berkeley 4.3 BSD
 * under license from the Regents of the University of California.
 */

/*
 * Boot subsystem client side rpc
 */

#include <sys/errno.h>
#include <rpc/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include "socket_inet.h"
#include "ipv4.h"
#include "clnt.h"
#include <rpc/rpc.h>
#include "brpc.h"
#include "pmap.h"
#include <sys/promif.h>
#include <rpc/xdr.h>
#include <rpc/auth.h>
#include <rpc/auth_sys.h>
#include "auth_inet.h"
#include <rpc/rpc_msg.h>
#include <sys/salib.h>
#include <sys/bootdebug.h>

#define	dprintf if (boothowto & RB_DEBUG) printf

/* retries to send RPC message when sendto fails */
#define	RPC_UDP_SEND_RETRIES	3

extern int errno;

/*
 * If we create another clnt type this should be
 * moved to a common file
 */
extern struct rpc_createerr rpc_createerr;

static struct clnt_ops *clntbudp_ops();

/*
 * Private data kept per client handle
 */
struct cu_data {
	int		   cu_sock;
	bool_t		   cu_closeit;
	struct sockaddr_in cu_raddr;
	int		   cu_rlen;
	struct timeval	   cu_wait;
	struct timeval	   cu_total;
	struct rpc_err	   cu_error;
	XDR		   cu_outxdrs;
	uint_t		   cu_xdrpos;
	uint_t		   cu_sendsz;
	char		   *cu_outbuf;
	uint_t		   cu_recvsz;
	char		   cu_inbuf[1];
};

/*
 * Create a UDP based client handle.
 * If *sockp<0, *sockp is set to a newly created UPD socket.
 * If raddr->sin_port is 0 a binder on the remote machine
 * is consulted for the correct port number.
 * NB: It is the clients responsibility to close *sockp.
 * NB: The rpch->cl_auth is initialized to null authentication.
 *	Caller may wish to set this something more useful.
 *
 * wait is the amount of time used between retransmitting a call if
 * no response has been heard;  retransmition occurs until the actual
 * rpc call times out.
 *
 * sendsz and recvsz are the maximum allowable packet sizes that can be
 * sent and received.
 */
CLIENT *
clntbudp_bufcreate(struct sockaddr_in *raddr, rpcprog_t program,
    rpcvers_t version, struct timeval wait, int *sockp, uint_t sendsz,
    uint_t recvsz)
{
	CLIENT *cl;
	struct cu_data *cu;
	struct rpc_msg call_msg;

	cl = (CLIENT *)bkmem_alloc(sizeof (CLIENT));
	if (cl == NULL) {
		errno = ENOMEM;
		rpc_createerr.cf_stat = RPC_SYSTEMERROR;
		rpc_createerr.cf_error.re_errno = errno;
		return ((CLIENT *)NULL);
	}
	sendsz = ((sendsz + 3) / 4) * 4;
	recvsz = ((recvsz + 3) / 4) * 4;
	cu = (struct cu_data *)bkmem_alloc(sizeof (*cu) + sendsz + recvsz);
	if (cu == NULL) {
		errno = ENOMEM;
		rpc_createerr.cf_stat = RPC_SYSTEMERROR;
		rpc_createerr.cf_error.re_errno = errno;
		goto fooy;
	}
	cu->cu_outbuf = &cu->cu_inbuf[recvsz];

	if (raddr->sin_port == 0) {
		ushort_t port;
		if ((port = bpmap_getport(program, version,
		    &(rpc_createerr.cf_stat), raddr, NULL)) == 0) {
			goto fooy;
		}
		raddr->sin_port = htons(port);
	}
	cl->cl_ops = clntbudp_ops();
	cl->cl_private = (caddr_t)cu;
	cu->cu_raddr = *raddr;
	cu->cu_rlen = sizeof (cu->cu_raddr);
	cu->cu_wait = wait;
	cu->cu_total.tv_sec = -1;
	cu->cu_total.tv_usec = -1;
	cu->cu_sendsz = sendsz;
	cu->cu_recvsz = recvsz;
	call_msg.rm_xid = (uint_t)prom_gettime() + 1;
	call_msg.rm_direction = CALL;
	call_msg.rm_call.cb_rpcvers = RPC_MSG_VERSION;
	call_msg.rm_call.cb_prog = program;
	call_msg.rm_call.cb_vers = version;
	xdrmem_create(&(cu->cu_outxdrs), cu->cu_outbuf,
	    sendsz, XDR_ENCODE);
	if (! xdr_callhdr(&(cu->cu_outxdrs), &call_msg)) {
		goto fooy;
	}
	cu->cu_xdrpos = XDR_GETPOS(&(cu->cu_outxdrs));
	cu->cu_closeit = FALSE;

	if (*sockp < 0) {
		struct sockaddr_in from;

		*sockp = socket(PF_INET, SOCK_DGRAM, 0);
		if (*sockp < 0) {
			rpc_createerr.cf_stat = RPC_SYSTEMERROR;
			rpc_createerr.cf_error.re_errno = errno;
			goto fooy;
		}

		if (dontroute) {
			(void) setsockopt(*sockp, SOL_SOCKET, SO_DONTROUTE,
			    (const void *)&dontroute, sizeof (dontroute));
		}

		/* attempt to bind to priv port */
		from.sin_family = AF_INET;
		ipv4_getipaddr(&from.sin_addr);
		from.sin_addr.s_addr = htonl(from.sin_addr.s_addr);
		from.sin_port = get_source_port(TRUE);

		if (bind(*sockp, (struct sockaddr *)&from, sizeof (from)) < 0) {
			rpc_createerr.cf_stat = RPC_SYSTEMERROR;
			rpc_createerr.cf_error.re_errno = errno;
			goto fooy;
		}

		cu->cu_closeit = TRUE;
	}

	cu->cu_sock = *sockp;
	cl->cl_auth = authnone_create();
	return (cl);
fooy:
	if (cu)
		bkmem_free((caddr_t)cu, sizeof (*cu) + sendsz + recvsz);
	if (cl)
		bkmem_free((caddr_t)cl, sizeof (CLIENT));
	return ((CLIENT *)NULL);
}

CLIENT *
clntbudp_create(struct sockaddr_in *raddr, rpcprog_t program,
    rpcvers_t version, struct timeval wait, int *sockp)
{

	return (clntbudp_bufcreate(raddr, program, version, wait, sockp,
	    UDPMSGSIZE, UDPMSGSIZE));
}

static enum clnt_stat
clntbudp_call(CLIENT *cl, rpcproc_t proc, xdrproc_t xargs, caddr_t argsp,
    xdrproc_t  xresults, caddr_t resultsp, struct timeval utimeout)
{
	struct cu_data *cu;
	XDR *xdrs;
	int outlen;
	int inlen;
	socklen_t fromlen;
	struct sockaddr_in from;
	struct rpc_msg reply_msg;
	XDR reply_xdrs;
	uint_t xdelay;
	int wait_time;
	bool_t ok;
	int nrefreshes = 2;	/* number of times to refresh cred */
	struct timeval timeout;
	int errors;
	short send_retries = RPC_UDP_SEND_RETRIES;

	cu = (struct cu_data *)cl->cl_private;
	if (cu->cu_total.tv_usec == -1)
		timeout = utimeout;	/* use supplied timeout */
	else
		timeout = cu->cu_total; /* use default timeout */

	/*
	 * set a media level timeout
	 */
	xdelay = cu->cu_wait.tv_sec + 1000 + cu->cu_wait.tv_usec / 1000;
	(void) setsockopt(cu->cu_sock, SOL_SOCKET, SO_RCVTIMEO,
	    (void *)&xdelay, sizeof (xdelay));

	wait_time = (timeout.tv_sec * 1000) + (timeout.tv_usec / 1000);
	if (wait_time == 0)
		wait_time = RPC_RCVWAIT_MSEC;
	wait_time += prom_gettime();

	errors = 0;

call_again:
	xdrs = &(cu->cu_outxdrs);
	xdrs->x_op = XDR_ENCODE;
	(void) XDR_SETPOS(xdrs, cu->cu_xdrpos);
	/*
	 * the transaction is the first thing in the out buffer
	 */
	(*(ushort_t *)(cu->cu_outbuf))++;
	if ((! XDR_PUTINT32(xdrs, (int32_t *)&proc)) ||
	    (! AUTH_MARSHALL(cl->cl_auth, xdrs, NULL)) ||
	    (! (*xargs)(xdrs, argsp)))
		return (cu->cu_error.re_status = RPC_CANTENCODEARGS);
	outlen = (int)XDR_GETPOS(xdrs);

send_again:
	if (sendto(cu->cu_sock, cu->cu_outbuf, outlen, 0,
	    (struct sockaddr *)&(cu->cu_raddr), cu->cu_rlen)
	    != outlen) {
		if (errno == ETIMEDOUT) {
			/*
			 * sendto() times out probably because
			 * ARP times out while waiting for reply.
			 * We retry sending RPC message again.
			 */
			if (send_retries-- > 0) {
				dprintf("clntbudp_call: timedout, try sending"
				    "RPC again\n");
				errno = 0;
				goto send_again;
			}
			cu->cu_error.re_status = RPC_TIMEDOUT;
		} else {
			cu->cu_error.re_status = RPC_CANTSEND;
		}
		cu->cu_error.re_errno = errno;
		return (cu->cu_error.re_status);
	}

	/*
	 * sub-optimal code appears here because we have
	 * some clock time to spare while the packets are in flight.
	 * (We assume that this is actually only executed once.)
	 */
recv_again:
	reply_msg.acpted_rply.ar_verf = _null_auth;
	reply_msg.acpted_rply.ar_results.where = resultsp;
	reply_msg.acpted_rply.ar_results.proc = xresults;

	for (;;) {
		if (errors >= RPC_ALLOWABLE_ERRORS)
			return (cu->cu_error.re_status);

		if (prom_gettime() >= wait_time) {
			cu->cu_error.re_errno = ETIMEDOUT;
			return (cu->cu_error.re_status = RPC_TIMEDOUT);
		}

		/*
		 * Use MSG_DONTWAIT because we have set
		 * a media level timeout above.
		 */
		fromlen = sizeof (struct sockaddr);

		inlen = recvfrom(cu->cu_sock, cu->cu_inbuf,
		    (int)cu->cu_recvsz, MSG_DONTWAIT,
		    (struct sockaddr *)&from, &fromlen);

		if (inlen < 0) {
			if (errno == EWOULDBLOCK) {
				/*
				 * Media level has timedout
				 * and no more data in buffers.
				 */
				goto send_again;
			}

			cu->cu_error.re_status = RPC_CANTRECV;
			if (errno == ETIMEDOUT) {
				errno = ETIMEDOUT;
				cu->cu_error.re_status = RPC_TIMEDOUT;
			}

			cu->cu_error.re_errno = errno;
			return (cu->cu_error.re_status);
		}

		if (inlen < sizeof (uint32_t))
			continue;

		/* see if reply transaction id matches sent id */
		if (*((uint32_t *)(cu->cu_inbuf)) !=
		    *((uint32_t *)(cu->cu_outbuf))) {
			dprintf("clntbudp_call: xid: 0x%x != 0x%x\n",
			    *(uint32_t *)(cu->cu_inbuf),
			    *(uint32_t *)(cu->cu_outbuf));
			continue;
		}
		/* we now assume we have the proper reply */
		break;
	}

	/*
	 * now decode and validate the response
	 */
	xdrmem_create(&reply_xdrs, cu->cu_inbuf, (uint_t)inlen, XDR_DECODE);
	ok = xdr_replymsg(&reply_xdrs, &reply_msg);
	/* XDR_DESTROY(&reply_xdrs);  save a few cycles on noop destroy */
	if (!ok) {
		cu->cu_error.re_status = RPC_CANTDECODERES;
		return (cu->cu_error.re_status);
	}

	_seterr_reply(&reply_msg, &(cu->cu_error));
	if (cu->cu_error.re_status == RPC_SUCCESS) {
		if (! AUTH_VALIDATE(cl->cl_auth,
		    &reply_msg.acpted_rply.ar_verf)) {
			cu->cu_error.re_status = RPC_AUTHERROR;
			cu->cu_error.re_why = AUTH_INVALIDRESP;
			errors++;
			goto call_again;
		}
		if (reply_msg.acpted_rply.ar_verf.oa_base != NULL) {
			xdrs->x_op = XDR_FREE;
			(void) xdr_opaque_auth(xdrs,
			    &(reply_msg.acpted_rply.ar_verf));
		}
		return (cu->cu_error.re_status);
	}  /* end successful completion */

	if (cu->cu_error.re_status == RPC_AUTHERROR) {
		/* maybe our credentials need to be refreshed ... */
		if (nrefreshes > 0 &&
		    AUTH_REFRESH(cl->cl_auth, NULL, NULL)) {
			nrefreshes--;
		}
		errors++;
		goto call_again;
	}

	/* Just keep trying till there's no data... */
	errors++;
	dprintf("clntbudp_call: from: %s, error: ",
	    inet_ntoa(from.sin_addr));
	rpc_disperr(&cu->cu_error);
	goto recv_again;
}

static void
clntbudp_geterr(CLIENT *cl, struct rpc_err *errp)
{
	struct cu_data *cu = (struct cu_data *)cl->cl_private;

	*errp = cu->cu_error;
}


static bool_t
clntbudp_freeres(CLIENT *cl, xdrproc_t xdr_res, caddr_t res_ptr)
{
	struct cu_data *cu = (struct cu_data *)cl->cl_private;
	XDR *xdrs = &(cu->cu_outxdrs);

	xdrs->x_op = XDR_FREE;
	return ((*xdr_res)(xdrs, res_ptr));
}

static void
clntbudp_abort(void)
{
}

/* ARGSUSED */
static bool_t
clntbudp_control(CLIENT *cl, int request, char *info)
{
	/* CLNT_CONTROL is not used in boot */
	return (FALSE);
}

static void
clntbudp_destroy(CLIENT *cl)
{
	struct cu_data *cu = (struct cu_data *)cl->cl_private;

	if (cu->cu_closeit) {
		(void) socket_close(cu->cu_sock);
	}
	XDR_DESTROY(&(cu->cu_outxdrs));
	bkmem_free((caddr_t)cu, (sizeof (*cu) + cu->cu_sendsz + cu->cu_recvsz));
	bkmem_free((caddr_t)cl, sizeof (CLIENT));
}

static struct clnt_ops *
clntbudp_ops(void)
{
	static struct clnt_ops ops;

	if (ops.cl_call == NULL) {
		ops.cl_call = clntbudp_call;
		ops.cl_abort = clntbudp_abort;
		ops.cl_geterr = clntbudp_geterr;
		ops.cl_freeres = clntbudp_freeres;
		ops.cl_destroy = clntbudp_destroy;
		ops.cl_control = clntbudp_control;
	}
	return (&ops);
}
/*
 * 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.
 *
 *  Stuff relating to directory reading ...
 */

#include <rpc/types.h>
#include <rpc/auth.h>
#include <rpc/xdr.h>
#include "clnt.h"
#include <rpc/rpc_msg.h>
#include <sys/t_lock.h>
#include "nfs_inet.h"
#include <rpc/rpc.h>
#include "brpc.h"
#include <rpcsvc/nfs_prot.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/bootvfs.h>
#include <sys/sysmacros.h>
#include "socket_inet.h"
#include <sys/salib.h>
#include <sys/bootdebug.h>

#define	MAXDENTS 16
#define	MINSIZ 20

/*
 * Boot needs to be cleaned up to use either dirent32 or dirent64,
 * in the meantime use dirent_t and always round to 8 bytes
 */
#define	BDIRENT_RECLEN(namelen) \
	((offsetof(dirent_t, d_name[0]) + 1 + (namelen) + 7) & ~ 7)

#define	dprintf	if (boothowto & RB_DEBUG) printf

/*
 *  Get directory entries:
 *
 *	Uses the nfs "READDIR" operation to read directory entries
 *	into a local buffer.  These are then translated into file
 *	system independent "dirent" structs and returned in the
 *	caller's buffer.  Returns the number of entries converted
 *	(-1 if there's an error).
 *
 *	Although the xdr functions can allocate memory, we have
 *	a limited heap so we allocate our own space,
 *	assuming the worst case of 256 byte names.
 *	This is a space hog in our local buffer, so we want
 *	the number of buffers to be small. To make sure we don't
 *	get more names than we can handle, we tell the rpc
 *	routine that we only have space for MAXDENT names if
 *	they are all the minimum size. This keeps the return
 *	packet unfragmented, but may result in lots of reads
 *	to process a large directory. Since this is standalone
 *	we don't worry about speed. With MAXDENTs at 16, the
 *	local buffer is 4k.
 */

int
nfsgetdents(struct nfs_file *nfp, struct dirent *dep, unsigned size)
{
	entry *ep;
	readdirargs rda;
	readdirres  res;
	enum clnt_stat status;
	struct {
		entry etlist[MAXDENTS];
		char names[MAXDENTS][NFS_MAXNAMLEN+1];
	} rdbuf;
	uint32_t offset;
	int j, cnt = 0;
	struct timeval zero_timeout = {0, 0};	/* default */

	bzero((caddr_t)&res, sizeof (res));
	bzero((caddr_t)&rda, sizeof (rda));
	bzero((caddr_t)rdbuf.etlist, sizeof (rdbuf.etlist));
	bcopy((caddr_t)&nfp->fh.fh2, (caddr_t)&rda.dir, NFS_FHSIZE);
	bcopy((caddr_t)nfp->cookie.cookie2, (caddr_t)rda.cookie,
						sizeof (nfscookie));

	while (!res.readdirres_u.reply.eof) {
		/*
		 *  Keep issuing nfs calls until EOF is reached on
		 *  the directory or the user buffer is filled.
		 */

		for (j = 0; j < MAXDENTS; j++) {
			/*
			 *  Link our buffers together for the benefit of
			 *  XDR.  We do this each time we issue the rpc call
			 *  JIC the xdr decode
			 *  routines screw up the linkage!
			 */

			rdbuf.etlist[j].name = rdbuf.names[(MAXDENTS-1) - j];
			rdbuf.etlist[j].nextentry =
				(j < (MAXDENTS-1)) ? &rdbuf.etlist[j+1] : 0;
		}

		res.readdirres_u.reply.entries = rdbuf.etlist;
		/*
		 * Cannot give the whole buffer unless every name is
		 * 256 bytes! Assume the worst case of all 1 byte names.
		 * This results in MINSIZ bytes/name in the xdr stream.
		 */
		rda.count = sizeof (res) + MAXDENTS*MINSIZ;
		bzero((caddr_t)rdbuf.names, sizeof (rdbuf.names));

		status = CLNT_CALL(root_CLIENT, NFSPROC_READDIR,
		    xdr_readdirargs, (caddr_t)&rda,
		    xdr_readdirres, (caddr_t)&res, zero_timeout);

		if (status != RPC_SUCCESS) {
			dprintf("nfs_getdents: RPC error\n");
			return (-1);
		}
		if (res.status != NFS_OK) {
			/*
			 *  The most common failure here would be trying to
			 *  issue a getdents call on a non-directory!
			 */

			nfs_error(res.status);
			return (-1);
		}

		for (ep = rdbuf.etlist; ep; ep = ep->nextentry) {
			/*
			 *  Step thru all entries returned by NFS, converting
			 *  to the cannonical form and copying out to the
			 *  user's buffer.
			 */

			int n;

			/*
			 * catch the case user called at EOF
			 */
			if ((n = strlen(ep->name)) == 0)
				return (cnt);

			n = BDIRENT_RECLEN(n);

			if (n > size)
				return (cnt);
			size -= n;

			(void) strlcpy(dep->d_name, ep->name,
			    strlen(ep->name) + 1);
			dep->d_ino = ep->fileid;
			bcopy(ep->cookie, &offset, sizeof (nfscookie));
			dep->d_off = offset;
			dep->d_reclen = (ushort_t)n;

			dep = (struct dirent *)((char *)dep + n);
			bcopy(ep->cookie, rda.cookie, sizeof (nfscookie));
			bcopy(ep->cookie, nfp->cookie.cookie2,
							sizeof (nfscookie));
			cnt++;
		}
	}

	return (cnt);
}
/*
 * 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.
 *
 *  Stuff relating to NFSv3 directory reading ...
 */

#include <rpc/types.h>
#include <rpc/auth.h>
#include <rpc/xdr.h>
#include "clnt.h"
#include <rpc/rpc_msg.h>
#include <sys/t_lock.h>
#include "nfs_inet.h"
#include <rpc/rpc.h>
#include "brpc.h"
#include <rpcsvc/nfs_prot.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/bootvfs.h>
#include <sys/sysmacros.h>
#include "socket_inet.h"
#include <sys/salib.h>
#include <sys/bootdebug.h>

#define	MAXDENTS 16
#define	MINSIZ 20

/*
 * Boot needs to be cleaned up to use either dirent32 or dirent64,
 * in the meantime use dirent_t and always round to 8 bytes
 */
#define	BDIRENT_RECLEN(namelen) \
	((offsetof(dirent_t, d_name[0]) + 1 + (namelen) + 7) & ~ 7)

#define	dprintf	if (boothowto & RB_DEBUG) printf

/*
 *  Get directory entries:
 *
 *	Uses the nfs "READDIR" operation to read directory entries
 *	into a local buffer.  These are then translated into file
 *	system independent "dirent" structs and returned in the
 *	caller's buffer.  Returns the number of entries converted
 *	(-1 if there's an error).
 *
 *	Although the xdr functions can allocate memory, we have
 *	a limited heap so we allocate our own space,
 *	assuming the worst case of 256 byte names.
 *	This is a space hog in our local buffer, so we want
 *	the number of buffers to be small. To make sure we don't
 *	get more names than we can handle, we tell the rpc
 *	routine that we only have space for MAXDENT names if
 *	they are all the minimum size. This keeps the return
 *	packet unfragmented, but may result in lots of reads
 *	to process a large directory. Since this is standalone
 *	we don't worry about speed. With MAXDENTs at 16, the
 *	local buffer is 4k.
 */

int
nfs3getdents(struct nfs_file *nfp, struct dirent *dep, unsigned size)
{
	int cnt = 0;
	entry3 *ep;
	READDIR3args rda;
	READDIR3res  res;
	enum clnt_stat status;
	struct {
		entry3 etlist[MAXDENTS];
		char names[MAXDENTS][NFS_MAXNAMLEN+1];
	} rdbuf;
	int j;
	struct timeval zero_timeout = {0, 0};   /* default */

	bzero((caddr_t)&res, sizeof (res));
	bzero((caddr_t)&rda, sizeof (rda));
	bzero((caddr_t)rdbuf.etlist, sizeof (rdbuf.etlist));

	rda.dir.data.data_len = nfp->fh.fh3.len;
	rda.dir.data.data_val = nfp->fh.fh3.data;
	rda.cookie = nfp->cookie.cookie3;

	while (!res.READDIR3res_u.resok.reply.eof) {
		/*
		 *  Keep issuing nfs calls until EOF is reached on
		 *  the directory or the user buffer is filled.
		 */

		for (j = 0; j < MAXDENTS; j++) {
			/*
			 *  Link our buffers together for the benefit of
			 *  XDR.  We do this each time we issue the rpc call
			 *  JIC the xdr decode
			 *  routines screw up the linkage!
			 */

			rdbuf.etlist[j].name = rdbuf.names[(MAXDENTS-1) - j];
			rdbuf.etlist[j].nextentry =
				(j < (MAXDENTS-1)) ? &rdbuf.etlist[j+1] : 0;
		}

		res.READDIR3res_u.resok.reply.entries = rdbuf.etlist;
		/*
		 * Cannot give the whole buffer unless every name is
		 * 256 bytes! Assume the worst case of all 1 byte names.
		 * This results in MINSIZ bytes/name in the xdr stream.
		 */
		rda.count = sizeof (res) + MAXDENTS*MINSIZ;
		bzero((caddr_t)rdbuf.names, sizeof (rdbuf.names));

		status = CLNT_CALL(root_CLIENT, NFSPROC3_READDIR,
		    xdr_READDIR3args, (caddr_t)&rda,
		    xdr_READDIR3res, (caddr_t)&res, zero_timeout);

		if (status != RPC_SUCCESS) {
			dprintf("nfs3_getdents: RPC error\n");
			return (-1);
		}
		if (res.status != NFS3_OK) {
			/*
			 *  The most common failure here would be trying to
			 *  issue a getdents call on a non-directory!
			 */

			nfs3_error(res.status);
			return (-1);
		}

		for (ep = rdbuf.etlist; ep; ep = ep->nextentry) {
			/*
			 *  Step thru all entries returned by NFS, converting
			 *  to the cannonical form and copying out to the
			 *  user's buffer.
			 */

			int n;

			/*
			 * catch the case user called at EOF
			 */
			if ((n = strlen(ep->name)) == 0)
				return (cnt);

			n = BDIRENT_RECLEN(n);

			if (n > size)
				return (cnt);
			size -= n;

			(void) strlcpy(dep->d_name, ep->name,
			    strlen(ep->name) + 1);
			dep->d_ino = ep->fileid;
			dep->d_off = (off_t)ep->cookie;
			dep->d_reclen = (ushort_t)n;

			dep = (struct dirent *)((char *)dep + n);
			rda.cookie = ep->cookie;
			nfp->cookie.cookie3 = ep->cookie;
			cnt++;
		}
	}

	return (cnt);
}
/*
 * 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.
 *
 * Stuff relating to NFSv4 directory reading ...
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#include <rpc/types.h>
#include <rpc/auth.h>
#include <rpc/xdr.h>
#include "clnt.h"
#include <rpc/rpc_msg.h>
#include <sys/t_lock.h>
#include "nfs_inet.h"
#include <rpc/rpc.h>
#include "brpc.h"
#include <rpcsvc/nfs_prot.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/bootvfs.h>
#include <sys/sysmacros.h>
#include "socket_inet.h"
#include <sys/salib.h>
#include <sys/bootdebug.h>

#define	MAXDENTS 16
#define	MINSIZ 20

/*
 * Boot needs to be cleaned up to use either dirent32 or dirent64,
 * in the meantime use dirent_t and always round to 8 bytes
 */
#define	BDIRENT_RECLEN(namelen) \
	((offsetof(dirent_t, d_name[0]) + 1 + (namelen) + 7) & ~ 7)

#define	dprintf	if (boothowto & RB_DEBUG) printf

/*
 *  Get directory entries:
 *
 *	Uses the nfs "READDIR" operation to read directory entries
 *	into a local buffer.  These are then translated into file
 *	system independent "dirent" structs and returned in the
 *	caller's buffer.  Returns the number of entries converted
 *	(-1 if there's an error).
 *
 *	Although the xdr functions can allocate memory, we have
 *	a limited heap so we allocate our own space,
 *	assuming the worst case of 256 byte names.
 *	This is a space hog in our local buffer, so we want
 *	the number of buffers to be small. To make sure we don't
 *	get more names than we can handle, we tell the rpc
 *	routine that we only have space for MAXDENT names if
 *	they are all the minimum size. This keeps the return
 *	packet unfragmented, but may result in lots of reads
 *	to process a large directory. Since this is standalone
 *	we don't worry about speed. With MAXDENTs at 16, the
 *	local buffer is 4k.
 */

int
nfs4getdents(struct nfs_file *nfp, struct dirent *dep, unsigned size)
{
	int		cnt = 0;
	b_entry4_t	*ep;
	readdir4arg_t	readdir_args;
	readdir4res_t	readdir_res;
	attr4_bitmap1_t	bitmap1;
	enum clnt_stat	status;
	struct {
		b_entry4_t etlist[MAXDENTS];
		char names[MAXDENTS][NFS_MAXNAMLEN+1];
	} rdbuf;
	int		j;
	struct timeval	zero_timeout = {0, 0};   /* default */
	utf8string	str;
	char		tagname[] = "inetboot readdir";

	bzero((caddr_t)&readdir_res, sizeof (readdir4res_t));
	bzero((caddr_t)&readdir_args, sizeof (readdir4arg_t));
	bzero((caddr_t)rdbuf.etlist, sizeof (rdbuf.etlist));

	str.utf8string_len = sizeof (tagname) - 1;
	str.utf8string_val = tagname;

	if (nfp->fh.fh4.len > 0)
		compound_init(&readdir_args.rd_arg, &str, 0, 2, &nfp->fh.fh4);
	else
		compound_init(&readdir_args.rd_arg, &str, 0, 2, NULL);

	readdir_args.rd_opreaddir = OP_READDIR;
	readdir_args.rd_cookie = nfp->cookie.cookie4;

	while (!readdir_res.rd_eof) {
		/*
		 *  Keep issuing nfs calls until EOF is reached on
		 *  the directory or the user buffer is filled.
		 */
		for (j = 0; j < MAXDENTS; j++) {
			/*
			 *  Link our buffers together for the benefit of
			 *  XDR.  We do this each time we issue the rpc call
			 *  JIC the xdr decode
			 *  routines screw up the linkage!
			 */
			rdbuf.etlist[j].b_name.utf8string_len = NFS_MAXNAMLEN;
			rdbuf.etlist[j].b_name.utf8string_val =
				rdbuf.names[(MAXDENTS-1) - j];
			rdbuf.etlist[j].b_nextentry =
				(j < (MAXDENTS-1)) ? &rdbuf.etlist[j+1] : 0;
		}

		readdir_res.rd_entries = rdbuf.etlist;
		/*
		 * Cannot give the whole buffer unless every name is
		 * 256 bytes! Assume the worst case of all 1 byte names.
		 * This results in MINSIZ bytes/name in the xdr stream.
		 */
		readdir_args.rd_dircount = MAXDENTS * MINSIZ;
		readdir_args.rd_maxcount = sizeof (readdir4res_t) +
							(MAXDENTS * MINSIZ);
		bzero((caddr_t)rdbuf.names, sizeof (rdbuf.names));

		/*
		 * Set the attr bitmap, so we get the fileid back.
		 */
		bitmap1.word = 0;
		bitmap1.bm_fattr4_fileid = 1;
		readdir_args.rd_attr_req.b_bitmap_len = 1;
		readdir_args.rd_attr_req.b_bitmap_val[0] = bitmap1.word;

		status = CLNT_CALL(root_CLIENT, NFSPROC4_COMPOUND,
			xdr_readdir4_args, (caddr_t)&readdir_args,
			xdr_readdir4_res, (caddr_t)&readdir_res, zero_timeout);

		if (status != RPC_SUCCESS) {
			dprintf("nfs4_getdents: RPC error\n");
			return (-1);
		}
		if (readdir_res.rd_status != NFS4_OK) {
			/*
			 *  The most common failure here would be trying to
			 *  issue a getdents call on a non-directory!
			 */

			nfs4_error(readdir_res.rd_status);
			return (-1);
		}

		/*
		 * If we are reading from the beginning of the
		 * directory we will need to create the "." and ".."
		 * since we won't be getting them from the server.  To obtain
		 * the fileid's just issue a couple otw lookups to get the
		 * info we need.
		 */
		if (readdir_args.rd_cookie == 0 &&
		    rdbuf.etlist[0].b_cookie > 2) {
			int n;
			int error;
			uint64_t fileid;
			struct vattr va;

			/*
			 * Do a getattr for the '.'
			 */
			error = nfs4getattr(nfp, &va);
			if (error)
				return (-1);

			dep->d_name[0] = '.';
			dep->d_name[1] = '\0';
			dep->d_ino = va.va_nodeid;
			dep->d_off = 1;
			n = BDIRENT_RECLEN(1);
			dep->d_reclen = n;
			dep = (struct dirent *)((char *)dep + n);

			/*
			 * Do a lookupp for the '..'
			 */
			(void) nfs4lookupp(nfp, &error, &fileid);
			if (error)
				return (-1);

			dep->d_name[0] = '.';
			dep->d_name[1] = '.';
			dep->d_name[2] = '\0';
			dep->d_ino = fileid;
			dep->d_off = 2;
			n = BDIRENT_RECLEN(2);
			dep->d_reclen = n;
			dep = (struct dirent *)((char *)dep + n);
		}

		for (ep = rdbuf.etlist; ep; ep = ep->b_nextentry) {
			/*
			 *  Step thru all entries returned by NFS, converting
			 *  to the cannonical form and copying out to the
			 *  user's buffer.
			 */
			int n;
			int namlen;

			/*
			 * catch the case user called at EOF
			 */
			if ((namlen = ep->b_name.utf8string_len) == 0)
				return (cnt);

			n = BDIRENT_RECLEN(namlen);

			if (n > size)
				return (cnt);
			size -= n;

			bcopy(ep->b_name.utf8string_val, dep->d_name, namlen);
			dep->d_name[namlen] = '\0';
			dep->d_ino = ep->b_fileid;
			dep->d_off = (off_t)ep->b_cookie;
			dep->d_reclen = (ushort_t)n;

			dep = (struct dirent *)((char *)dep + n);
			readdir_args.rd_cookie = ep->b_cookie;
			nfp->cookie.cookie4 = ep->b_cookie;
			cnt++;
		}
	}

	return (cnt);
}
#!/bin/sh
#
# 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
#
# ident	"%Z%%M%	%I%	%E% SMI"
#

find_files "s.*" usr/src/common/net/dhcp
/*
 * 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) 1983, 1984, 1985, 1986, 1987, 1988, 1989 AT&T */
/* All Rights Reserved */

/*
 * Portions of this source code were derived from Berkeley 4.3 BSD
 * under license from the Regents of the University of California.
 */

/*
 * This file contains the file lookup code for NFS.
 */

#include <rpc/rpc.h>
#include "brpc.h"
#include <rpc/types.h>
#include <rpc/auth.h>
#include <rpc/xdr.h>
#include <rpc/rpc_msg.h>
#include <sys/t_lock.h>
#include "clnt.h"
#include <rpcsvc/mount.h>
#include <st_pathname.h>
#include <sys/errno.h>
#include <sys/promif.h>
#include "nfs_inet.h"
#include "socket_inet.h"
#include <rpcsvc/nfs_prot.h>
#include <rpcsvc/nfs4_prot.h>
#include <sys/types.h>
#include <sys/salib.h>
#include <sys/sacache.h>
#include <sys/stat.h>
#include <sys/bootvfs.h>
#include <sys/bootdebug.h>
#include "mac.h"

static int root_inum = 1;	/* Dummy i-node number for root */
static int next_inum = 1;	/* Next dummy i-node number	*/

#define	dprintf	if (boothowto & RB_DEBUG) printf

/*
 * starting at current directory (root for us), lookup the pathname.
 * return the file handle of said file.
 */

static int stlookuppn(struct st_pathname *pnp, struct nfs_file *cfile,
			bool_t needroothandle);

/*
 * For NFSv4 we may be calling lookup in the context of evaluating the
 * root path.  In this case we set needroothandle to TRUE.
 */
int
lookup(char *pathname, struct nfs_file *cur_file, bool_t needroothandle)
{
	struct st_pathname pnp;
	int error;

	static char lkup_path[NFS_MAXPATHLEN];	/* pn_alloc doesn't */

	pnp.pn_buf = &lkup_path[0];
	bzero(pnp.pn_buf, NFS_MAXPATHLEN);
	error = stpn_get(pathname, &pnp);
	if (error)
		return (error);
	error = stlookuppn(&pnp, cur_file, needroothandle);
	return (error);
}

static int
stlookuppn(struct st_pathname *pnp, struct nfs_file *cfile,
bool_t needroothandle)
{
	char component[NFS_MAXNAMLEN+1];	/* buffer for component */
	int nlink = 0;
	int error = 0;
	int dino, cino;
	struct nfs_file *cdp = NULL;

	*cfile = roothandle;	/* structure copy - start at the root. */
	dino = root_inum;
begin:
	/*
	 * Each time we begin a new name interpretation (e.g.
	 * when first called and after each symbolic link is
	 * substituted), we allow the search to start at the
	 * root directory if the name starts with a '/', otherwise
	 * continuing from the current directory.
	 */
	component[0] = '\0';
	if (stpn_peekchar(pnp) == '/') {
		if (!needroothandle)
			*cfile = roothandle;
		dino = root_inum;
		stpn_skipslash(pnp);
	}

next:
	/*
	 * Make sure we have a directory.
	 */
	if (!cfile_is_dir(cfile)) {
		error = ENOTDIR;
		goto bad;
	}
	/*
	 * Process the next component of the pathname.
	 */
	error = stpn_stripcomponent(pnp, component);
	if (error)
		goto bad;

	/*
	 * Check for degenerate name (e.g. / or "")
	 * which is a way of talking about a directory,
	 * e.g. "/." or ".".
	 */
	if (component[0] == '\0')
		return (0);

	/*
	 * Handle "..": two special cases.
	 * 1. If at root directory (e.g. after chroot)
	 *    then ignore it so can't get out.
	 * 2. If this vnode is the root of a mounted
	 *    file system, then replace it with the
	 *    vnode which was mounted on so we take the
	 *    .. in the other file system.
	 */
	if (strcmp(component, "..") == 0) {
		if (cfile == &roothandle)
			goto skip;
	}

	/*
	 * Perform a lookup in the current directory.
	 * We create a simple negative lookup cache by storing
	 * inode -1 to indicate file not found.
	 */
	cino = get_dcache(mac_get_dev(), component, dino);
	if (cino == -1)
		return (ENOENT);
#ifdef DEBUG
	dprintf("lookup: component %s pathleft %s\n", component, pnp->pn_path);
#endif
	if ((cino == 0) ||
	    ((cdp = (struct nfs_file *)get_icache(mac_get_dev(), cino)) == 0)) {
		struct nfs_file *lkp;

		/*
		 * If an RPC error occurs, error is not changed,
		 * else it is the NFS error if NULL is returned.
		 */
		error = -1;
		switch (cfile->version) {
		case NFS_VERSION:
			lkp = nfslookup(cfile, component, &error);
			break;
		case NFS_V3:
			lkp = nfs3lookup(cfile, component, &error);
			break;
		case NFS_V4:
			lkp = nfs4lookup(cfile, component, &error);
			break;
		default:
			printf("lookup: NFS Version %d not supported\n",
			    cfile->version);
			lkp = NULL;
			break;
		}

		/*
		 * Check for RPC error
		 */
		if (error == -1) {
			printf("lookup: lookup RPC error\n");
			return (error);
		}

		/*
		 * Check for NFS error
		 */
		if (lkp == NULL) {
			if ((error != NFSERR_NOENT) &&
			    (error != NFS3ERR_NOENT) &&
			    (error != NFS4ERR_NOENT)) {
#ifdef DEBUG
			dprintf("lookup: lkp is NULL with error %d\n", error);
#endif
				return (error);
			}
#ifdef DEBUG
			dprintf("lookup: lkp is NULL with error %d\n", error);
#endif
			/*
			 * File not found so set cached inode to -1
			 */
			set_dcache(mac_get_dev(), component, dino, -1);
			return (error);
		}

		if (cdp = (struct nfs_file *)
		    bkmem_alloc(sizeof (struct nfs_file))) {
			/*
			 *  Save this entry in cache for next time ...
			 */
			if (!cino)
				cino = ++next_inum;
			*cdp = *lkp;

			set_dcache(mac_get_dev(), component, dino, cino);
			set_icache(mac_get_dev(), cino, cdp,
						sizeof (struct nfs_file));
		} else {
			/*
			 *  Out of memory, clear cache keys so we don't get
			 *  confused later.
			 */
			cino = 0;
			cdp = lkp;
		}
	}
	dino = cino;

	/*
	 * If we hit a symbolic link and there is more path to be
	 * translated or this operation does not wish to apply
	 * to a link, then place the contents of the link at the
	 * front of the remaining pathname.
	 */
	if (cfile_is_lnk(cdp)) {
		struct st_pathname linkpath;
		static char path_tmp[NFS_MAXPATHLEN];	/* used for symlinks */
		char *pathp;

		linkpath.pn_buf = &path_tmp[0];

		nlink++;
		if (nlink > MAXSYMLINKS) {
			error = ELOOP;
			goto bad;
		}
		switch (cdp->version) {
		case NFS_VERSION:
			error = nfsgetsymlink(cdp, &pathp);
			break;
		case NFS_V3:
			error = nfs3getsymlink(cdp, &pathp);
			break;
		case NFS_V4:
			error = nfs4getsymlink(cdp, &pathp);
			break;
		default:
			printf("getsymlink: NFS Version %d not supported\n",
			    cdp->version);
			error = ENOTSUP;
			break;
		}

		if (error)
			goto bad;

		(void) stpn_get(pathp, &linkpath);

		if (stpn_pathleft(&linkpath) == 0)
			(void) stpn_set(&linkpath, ".");
		error = stpn_combine(pnp, &linkpath); /* linkpath before pn */
		if (error)
			goto bad;
		goto begin;
	}

	if (needroothandle) {
		roothandle = *cdp;
		needroothandle = FALSE;
	}
	*cfile = *cdp;

skip:
	/*
	 * Skip to next component of the pathname.
	 * If no more components, return last directory (if wanted)  and
	 * last component (if wanted).
	 */
	if (stpn_pathleft(pnp) == 0) {
		(void) stpn_set(pnp, component);
		return (0);
	}
	/*
	 * skip over slashes from end of last component
	 */
	stpn_skipslash(pnp);
	goto next;
bad:
	/*
	 * Error.
	 */
	return (error);
}
/*
 * 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 2006 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*	Copyright (c) 1988 AT&T */
/*	All Rights Reserved */

#include <sys/utsname.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <rpc/types.h>
#include <rpc/auth.h>
#include <sys/t_lock.h>
#include <netdb.h>
#include "clnt.h"
#include <rpc/xdr.h>
#include <rpc/rpc_msg.h>
#include <rpc/rpc.h>
#include "brpc.h"
#include "auth_inet.h"
#include "pmap.h"
#include <rpcsvc/nfs_prot.h>
#include <rpcsvc/nfs4_prot.h>
#include "nfs_inet.h"
#include <rpcsvc/bootparam.h>
#include <dhcp_impl.h>
#include <rpcsvc/mount.h>
#include <sys/promif.h>
#include <sys/salib.h>
#include "socket_inet.h"
#include "ipv4.h"
#include "mac.h"
#include <sys/bootdebug.h>
#include <errno.h>
#include "dhcpv4.h"
#include <sys/mntent.h>

/* ARP timeout in milliseconds for BOOTP/RARP */
#define	ARP_INETBOOT_TIMEOUT 1000

struct nfs_file		roothandle;			/* root file handle */
static char		root_hostname[SYS_NMLN];	/* server hostname */
static char		my_hostname[MAXHOSTNAMELEN];
static char		root_pathbuf[NFS_MAXPATHLEN];	/* the root's path */
static char		root_boot_file[NFS_MAXPATHLEN];	/* optional boot file */
static struct sockaddr_in root_to;			/* server sock ip */
							/* in network order */
CLIENT			*root_CLIENT = NULL;		/* CLIENT handle */
int dontroute = FALSE;	/* In case rarp/bootparams was selected */
char			rootopts[MAX_PATH_LEN];
static gid_t		fake_gids = 1;	/* fake gids list for auth_unix */

extern void set_default_filename(char *);	/* boot.c */

/*
 * xdr routines used by mount.
 */

bool_t
xdr_fhstatus(XDR *xdrs, struct fhstatus *fhsp)
{
	if (!xdr_int(xdrs, (int *)&fhsp->fhs_status))
		return (FALSE);
	if (fhsp->fhs_status == 0) {
		return (xdr_fhandle(xdrs, fhsp->fhstatus_u.fhs_fhandle));
	}
	return (TRUE);
}

bool_t
xdr_fhandle(XDR *xdrs, fhandle fhp)
{
	return (xdr_opaque(xdrs, (char *)fhp, NFS_FHSIZE));
}

bool_t
xdr_path(XDR *xdrs, char **pathp)
{
	return (xdr_string(xdrs, pathp, MNTPATHLEN));
}

bool_t
xdr_fhandle3(XDR *xdrs, fhandle3 *objp)
{
	return (xdr_bytes(xdrs, (char **)&objp->fhandle3_val,
				(uint_t *)&objp->fhandle3_len, FHSIZE3));
}

bool_t
xdr_mountstat3(XDR *xdrs, mountstat3 *objp)
{
	return (xdr_enum(xdrs, (enum_t *)objp));
}

bool_t
xdr_mountres3_ok(XDR *xdrs, mountres3_ok *objp)
{
	if (!xdr_fhandle3(xdrs, &objp->fhandle))
		return (FALSE);
	return (xdr_array(xdrs, (char **)&objp->auth_flavors.auth_flavors_val,
			(uint_t *)&objp->auth_flavors.auth_flavors_len, ~0,
			sizeof (int), (xdrproc_t)xdr_int));
}

bool_t
xdr_mountres3(XDR *xdrs, mountres3 *objp)
{
	if (!xdr_mountstat3(xdrs, &objp->fhs_status))
		return (FALSE);
	if (objp->fhs_status == MNT_OK)
		return (xdr_mountres3_ok(xdrs, &objp->mountres3_u.mountinfo));
	return (TRUE);
}

static int
nfsmountroot(char *path, struct nfs_file *filep)
{
	int		rexmit;
	int		resp_wait;
	enum clnt_stat	status;
	struct fhstatus	root_tmp;			/* to pass to rpc/xdr */

	/*
	 * Wait up to 16 secs for first response, retransmitting expon.
	 */
	rexmit = 0;	/* default retransmission interval */
	resp_wait = 16;

	do {
		status = brpc_call((rpcprog_t)MOUNTPROG, (rpcvers_t)MOUNTVERS,
		    (rpcproc_t)MOUNTPROC_MNT, xdr_path, (caddr_t)&path,
		    xdr_fhstatus, (caddr_t)&(root_tmp), rexmit, resp_wait,
		    &root_to, NULL, AUTH_UNIX);
		if (status == RPC_TIMEDOUT) {
			dprintf("boot: %s:%s mount server not responding.\n",
			    root_hostname, path);
		}
		rexmit = resp_wait;
		resp_wait = 0;	/* use default wait time. */
	} while (status == RPC_TIMEDOUT);

	if ((status != RPC_SUCCESS) || (root_tmp.fhs_status != 0)) {
		nfs_error(root_tmp.fhs_status);
		root_to.sin_port = 0;
		return (-1);
	}

	/*
	 * Since the mount succeeded, we'll mark the filep's
	 * status as NFS_OK, and its type as NFDIR. If these
	 * points aren't the case, then we wouldn't be here.
	 */
	bcopy(&root_tmp.fhstatus_u.fhs_fhandle, &filep->fh.fh2, FHSIZE);
	filep->ftype.type2 = NFDIR;
	filep->version = NFS_VERSION;
	nfs_readsize = nfs_readsize <  NFS_MAXDATA ? nfs_readsize : NFS_MAXDATA;
	/*
	 * Set a reasonable lower limit on readsize
	 */
	nfs_readsize = (nfs_readsize != 0 && nfs_readsize < 512) ?
							512 : nfs_readsize;
	return (0);
}

int
setup_root_vars(void)
{
	size_t		buflen;
	uint16_t	readsize;

	/*
	 * Root server name. Required.
	 */
	buflen = sizeof (root_hostname);
	if (dhcp_getinfo(DSYM_VENDOR, VS_NFSMNT_ROOTSRVR_NAME, 0,
	    root_hostname, &buflen)) {
		root_hostname[buflen] = '\0';
	} else {
		dprintf("BOUND: Missing Root Server Name Option\n");
		errno = EINVAL;
		return (-1);
	}

	/*
	 * Root server IP. Required.
	 */
	buflen = sizeof (root_to.sin_addr);
	if (!dhcp_getinfo(DSYM_VENDOR, VS_NFSMNT_ROOTSRVR_IP, 0,
	    &root_to.sin_addr, &buflen)) {
		dprintf("BOUND: Missing Root Server IP Option\n");
		errno = EINVAL;
		return (-1);
	}

	/*
	 * Root path Required.
	 */
	buflen = sizeof (root_pathbuf);
	if (dhcp_getinfo(DSYM_VENDOR, VS_NFSMNT_ROOTPATH, 0,
	    root_pathbuf, &buflen)) {
		root_pathbuf[buflen] = '\0';
	} else {
		dprintf("BOUND: Missing Root Path Option\n");
		errno = EINVAL;
		return (-1);
	}

	/*
	 * Optional Bootfile path.
	 */
	buflen = sizeof (root_boot_file);
	if (dhcp_getinfo(DSYM_VENDOR, VS_NFSMNT_BOOTFILE, 0,
		    root_boot_file, &buflen)) {
		root_boot_file[buflen] = '\0';
		dprintf("BOUND: Optional Boot File is: %s\n", root_boot_file);
	}

	/* if we got a boot file name, use it as the default */
	if (root_boot_file[0] != '\0')
		set_default_filename(root_boot_file);

	/*
	 * Set the NFS read size. The mount code will adjust it to
	 * the maximum size.
	 */
	buflen = sizeof (readsize);
	if (dhcp_getinfo(DSYM_VENDOR, VS_BOOT_NFS_READSIZE, 0,
	    &readsize, &buflen)) {
		nfs_readsize = ntohs(readsize);
		if (boothowto & RB_VERBOSE) {
			printf("Boot NFS read size: %d\n", nfs_readsize);
		}
	}

	/*
	 * Optional rootopts.
	 */
	buflen = sizeof (rootopts);
	if (dhcp_getinfo(DSYM_VENDOR, VS_NFSMNT_ROOTOPTS, 0,
	    rootopts, &buflen)) {
		rootopts[buflen] = '\0';
		dprintf("BOUND: Optional Rootopts is: %s\n", rootopts);
	}

	return (0);
}

static void
mnt3_error(enum mountstat3 status)
{
	if (!(boothowto & RB_DEBUG))
		return;

	switch (status) {
	case MNT_OK:
		printf("Mount: No error.\n");
		break;
	case MNT3ERR_PERM:
		printf("Mount: Not owner.\n");
		break;
	case MNT3ERR_NOENT:
		printf("Mount: No such file or directory.\n");
		break;
	case MNT3ERR_IO:
		printf("Mount: I/O error.\n");
		break;
	case MNT3ERR_ACCES:
		printf("Mount: Permission denied.\n");
		break;
	case MNT3ERR_NOTDIR:
		printf("Mount: Not a directory.\n");
		break;
	case MNT3ERR_INVAL:
		printf("Mount: Invalid argument.\n");
		break;
	case MNT3ERR_NAMETOOLONG:
		printf("Mount: File name too long.\n");
		break;
	case MNT3ERR_NOTSUPP:
		printf("Mount: Operation not supported.\n");
		break;
	case MNT3ERR_SERVERFAULT:
		printf("Mount: Server fault.\n");
		break;
	default:
		printf("Mount: unknown error.\n");
		break;
	}
}

static int
nfs3mountroot(char *path, struct nfs_file *filep)
{
	int		rexmit;
	int		resp_wait;
	struct mountres3 res3;
	enum clnt_stat	status;

	/*
	 * Wait up to 16 secs for first response, retransmitting expon.
	 */
	rexmit = 0;	/* default retransmission interval */
	resp_wait = 16;

	/*
	 * Try to mount using V3
	 */
	do {
		bzero(&res3, sizeof (struct mountres3));

		status = brpc_call((rpcprog_t)MOUNTPROG, (rpcvers_t)MOUNTVERS3,
		    (rpcproc_t)MOUNTPROC_MNT, xdr_path, (caddr_t)&path,
		    xdr_mountres3, (caddr_t)&res3, rexmit, resp_wait,
		    &root_to, NULL, AUTH_UNIX);

		if (status != RPC_TIMEDOUT)
			break;

		dprintf("boot: %s:%s mount server not responding.\n",
			    root_hostname, path);

		rexmit = resp_wait;
		resp_wait = 0;	/* use default wait time. */

		xdr_free(xdr_mountres3, (caddr_t)&res3);
	} while (status == RPC_TIMEDOUT);

	if ((status != RPC_SUCCESS) || (res3.fhs_status != MNT_OK)) {
		mnt3_error(res3.fhs_status);
		root_to.sin_port = 0;
		return (-1);
	}

	/*
	 * Since the mount succeeded, we'll mark the filep's
	 * status as NFS_OK, and its type as NF3DIR. If these
	 * points aren't the case, then we wouldn't be here.
	 */
	filep->fh.fh3.len = res3.mountres3_u.mountinfo.fhandle.fhandle3_len;
	bcopy(res3.mountres3_u.mountinfo.fhandle.fhandle3_val,
			filep->fh.fh3.data,
			filep->fh.fh3.len);
	filep->ftype.type3 = NF3DIR;
	filep->version = NFS_V3;
	/*
	 * Hardwire in a known reasonable upper limit of 32K
	 */
	nfs_readsize = nfs_readsize <  32 * 1024 ? nfs_readsize : 32 * 1024;
	/*
	 * Set a reasonable lower limit on readsize
	 */
	nfs_readsize = (nfs_readsize != 0 && nfs_readsize < 512) ?
							512 : nfs_readsize;
	xdr_free(xdr_mountres3, (caddr_t)&res3);
	return (0);
}

/*
 * Setup v4 client for inetboot
 */
static int
nfs4init(char *path, uint16_t nfs_port)
{
	struct timeval	wait;
	int		fd = -1;
	int		error = 0;
	enum clnt_stat	rpc_stat;
	struct nfs_file	rootpath;

	wait.tv_sec = RPC_RCVWAIT_MSEC / 1000;
	wait.tv_usec = 0;

	/*
	 * If we haven't explicitly set the port number, set to the standard
	 * 2049 and don't cause a rpcbind request.
	 */
	if (nfs_port == 0)
		nfs_port = 2049;

	root_to.sin_port = htons(nfs_port);

	/*
	 * Support TCP only
	 */
	root_CLIENT = clntbtcp_create(&root_to, NFS_PROGRAM,
					NFS_V4, wait, &fd,
					NFS4BUF_SIZE, NFS4BUF_SIZE);

	if (root_CLIENT == NULL) {
		root_to.sin_port = 0;
		return (-1);
	}

	root_CLIENT->cl_auth =
			authunix_create(my_hostname, 0, 1, 1, &fake_gids);

	/*
	 * Send NULL proc the server first to see if V4 exists
	 */
	rpc_stat = CLNT_CALL(root_CLIENT, NFSPROC4_NULL, xdr_void, NULL,
				xdr_void, NULL, wait);

	if (rpc_stat != RPC_SUCCESS) {
		dprintf("boot: NULL proc failed NFSv4 service not available\n");
		AUTH_DESTROY(root_CLIENT->cl_auth);
		CLNT_DESTROY(root_CLIENT);
		root_to.sin_port = 0;
		return (-1);
	}

	/*
	 * Do a lookup to get to the root_path.  This is nice since it can
	 * handle multicomponent lookups.
	 */
	roothandle.version = NFS_V4;
	roothandle.ftype.type4 = NF4DIR;
	roothandle.fh.fh4.len = 0;		/* Force a PUTROOTFH */
	roothandle.offset = (uint_t)0;		/* it's a directory! */
	error = lookup(path, &rootpath, TRUE);

	if (error) {
		printf("boot: lookup %s failed\n", path);
		return (-1);
	}
	roothandle = rootpath;	/* structure copy */

	/*
	 * Hardwire in a known reasonable upper limit of 32K
	 */
	nfs_readsize = nfs_readsize <  32 * 1024 ? nfs_readsize : 32 * 1024;
	/*
	 * Set a reasonable lower limit on readsize
	 */
	nfs_readsize = (nfs_readsize != 0 && nfs_readsize < 512) ?
							512 : nfs_readsize;

	return (0);
}

static int
atoi(const char *p)
{
	int n;
	int c, neg = 0;

	if (!isdigit(c = *p)) {
		while (c == ' ' || c == '\t' || c == '\n')
			c = *++p;
		switch (c) {
		case '-':
			neg++;
			/* FALLTHROUGH */
		case '+':
			c = *++p;
		}
		if (!isdigit(c))
			return (0);
	}
	for (n = '0' - c; isdigit(c = *++p); ) {
		n *= 10; /* two steps to avoid unnecessary overflow */
		n += '0' - c; /* accum neg to avoid surprises at MAX */
	}
	return (neg ? n : -n);
}

/*
 * Parse suboptions from a string.
 * Same as getsubopt(3C).
 */
static int
getsubopt(char **optionsp, char * const *tokens, char **valuep)
{
	char *s = *optionsp, *p;
	int i;
	size_t optlen;

	*valuep = NULL;
	if (*s == '\0')
		return (-1);
	p = strchr(s, ',');		/* find next option */
	if (p == NULL) {
		p = s + strlen(s);
	} else {
		*p++ = '\0';		/* mark end and point to next */
	}
	*optionsp = p;			/* point to next option */
	p = strchr(s, '=');		/* find value */
	if (p == NULL) {
		optlen = strlen(s);
		*valuep = NULL;
	} else {
		optlen = p - s;
		*valuep = ++p;
	}
	for (i = 0; tokens[i] != NULL; i++) {
		if ((optlen == strlen(tokens[i])) &&
		    (strncmp(s, tokens[i], optlen) == 0))
			return (i);
	}
	/* no match, point value at option and return error */
	*valuep = s;
	return (-1);
}

/*
 * The only interesting NFS mount options for initiating the kernel
 * all others are ignored.
 */
static char *optlist[] = {
#define	OPT_RSIZE	0
	MNTOPT_RSIZE,
#define	OPT_TIMEO	1
	MNTOPT_TIMEO,
#define	OPT_VERS	2
	MNTOPT_VERS,
#define	OPT_PROTO	3
	MNTOPT_PROTO,
#define	OPT_PORT	4
	MNTOPT_PORT,
	NULL
};

/*
 * This routine will open a device as it is known by the V2 OBP. It
 * then goes thru the stuff necessary to initialize the network device,
 * get our network parameters, (using DHCP or rarp/bootparams), and
 * finally actually go and get the root filehandle. Sound like fun?
 * Suuurrrree. Take a look.
 *
 * Returns 0 if things worked. -1 if we crashed and burned.
 */
int
boot_nfs_mountroot(char *str)
{
	int		status;
	enum clnt_stat	rpc_stat;
	char		*root_path = &root_pathbuf[0];	/* to make XDR happy */
	struct timeval	wait;
	int		fd;
	int		bufsize;
	char		*opts, *val;
	int		nfs_version = 0;
	int		istcp = 1;
	int		nfs_port = 0;	/* Cause pmap to get port */
	struct sockaddr_in tmp_addr;	/* throw away */

	if (root_CLIENT != NULL) {
		AUTH_DESTROY(root_CLIENT->cl_auth);
		CLNT_DESTROY(root_CLIENT);
		root_CLIENT = NULL;
	}

	root_to.sin_family = AF_INET;
	root_to.sin_addr.s_addr = htonl(INADDR_ANY);
	root_to.sin_port = htons(0);

	mac_init(str);

	(void) ipv4_setpromiscuous(TRUE);

	if (get_netconfig_strategy() == NCT_BOOTP_DHCP) {
		if (boothowto & RB_VERBOSE)
			printf("Using BOOTP/DHCP...\n");
		if (dhcp() != 0 || setup_root_vars() != 0) {
			(void) ipv4_setpromiscuous(FALSE);
			if (boothowto & RB_VERBOSE)
				printf("BOOTP/DHCP configuration failed!\n");
			return (-1);
		}

		/* now that we have an IP address, turn off promiscuous mode */
		(void) ipv4_setpromiscuous(FALSE);
	} else {
		/* Use RARP/BOOTPARAMS. RARP will try forever... */
		if (boothowto & RB_VERBOSE)
			printf("Using RARP/BOOTPARAMS...\n");
		mac_call_rarp();

		/*
		 * Since there is no way to determine our netmask, and therefore
		 * figure out if the router we got is useful, we assume all
		 * services are local. Use DHCP if this bothers you.
		 */
		dontroute = TRUE;
		/*
		 * We are trying to keep the ARP response
		 * timeout on the lower side with BOOTP/RARP.
		 * We are doing this for BOOTP/RARP where policy
		 * doesn't allow to route the packets outside
		 * the subnet as it has no idea about the
		 * netmask. By doing so, we are reducing
		 * ARP response timeout for any packet destined
		 * for outside booting clients subnet. Client can
		 * not expect such ARP replies and will finally
		 * timeout after a long delay. This would cause
		 * booting client to get stalled for a longer
		 * time. We can not avoid accepting any outside
		 * subnet packets accidentally destined for the
		 * booting client.
		 */
		mac_set_arp_timeout(ARP_INETBOOT_TIMEOUT);

		/* now that we have an IP address, turn off promiscuous mode */
		(void) ipv4_setpromiscuous(FALSE);

		/* get our hostname */
		if (whoami() == FALSE)
			return (-1);

		/* get our bootparams. */
		if (getfile("root", root_hostname, &root_to.sin_addr,
		    root_pathbuf) == FALSE)
			return (-1);

		/* get our rootopts. */
		(void) getfile("rootopts", root_hostname, &tmp_addr.sin_addr,
		    rootopts);
	}

	/* mount root */
	if (boothowto & RB_VERBOSE) {
		printf("root server: %s (%s)\n", root_hostname,
		    inet_ntoa(root_to.sin_addr));
		printf("root directory: %s\n", root_pathbuf);
	}

	/*
	 * Assumes we've configured the stack and thus know our
	 * IP address/hostname, either by using DHCP or rarp/bootparams.
	 */
	(void) gethostname(my_hostname, sizeof (my_hostname));

	wait.tv_sec = RPC_RCVWAIT_MSEC / 1000;
	wait.tv_usec = 0;

	/*
	 * Parse out the interesting root options, if an invalid
	 * or unknown option is provided, silently ignore it and
	 * use the defaults.
	 */
	opts = rootopts;
	while (*opts) {
		int ival;
		switch (getsubopt(&opts, optlist, &val)) {
		case OPT_RSIZE:
			if (val == NULL || !isdigit(*val))
				break;
			nfs_readsize = atoi(val);
			break;
		case OPT_TIMEO:
			if (val == NULL || !isdigit(*val))
				break;
			ival = atoi(val);
			wait.tv_sec = ival / 10;
			wait.tv_usec = (ival % 10) * 100000;
			break;
		case OPT_VERS:
			if (val == NULL || !isdigit(*val))
				break;
			nfs_version = atoi(val);
			break;
		case OPT_PROTO:
			if (val == NULL || isdigit(*val))
				break;
			if ((strncmp(val, "udp", 3) == 0))
				istcp = 0;
			else
				istcp = 1;	/* must be tcp */
			break;
		case OPT_PORT:
			if (val == NULL || !isdigit(*val))
				break;
			nfs_port = atoi(val);

			/*
			 * Currently nfs_dlinet.c doesn't support setting
			 * the root NFS port. Delete this when it does.
			 */
			nfs_port = 0;
			break;
		default:
			/*
			 * Unknown options are silently ignored
			 */
			break;
		}
	}

	/*
	 * If version is set, then try that version first.
	 */
	switch (nfs_version) {
	case NFS_VERSION:
		if (nfsmountroot(root_path, &roothandle) == 0)
			goto domount;
		break;
	case NFS_V3:
		if (nfs3mountroot(root_path, &roothandle) == 0)
			goto domount;
		break;
	case NFS_V4:
		/*
		 * With v4 we skip the mount and go straight to
		 * setting the root filehandle.  Because of this we
		 * do things slightly differently and obtain our
		 * client handle first.
		 */
		if (istcp && nfs4init(root_path, nfs_port) == 0) {
			/*
			 * If v4 init succeeded then we are done.  Just return.
			 */
			return (0);
		}
	}

	/*
	 * If there was no chosen version or the chosen version failed
	 * try all versions in order, this may still fail to boot
	 * at the kernel level if the options are not right, but be
	 * generous at this early stage.
	 */
	if (istcp && nfs4init(root_path, nfs_port) == 0) {
		/*
		 * If v4 init succeeded then we are done.  Just return.
		 */
		return (0);
	}

	if (nfs3mountroot(root_path, &roothandle) == 0)
		goto domount;

	if ((status = nfsmountroot(root_path, &roothandle)) != 0)
		return (status);

domount:
	/*
	 * Only v2 and v3 go on from here.
	 */
	roothandle.offset = (uint_t)0;		/* it's a directory! */
	root_to.sin_port = htons(nfs_port);	/* NFS is next after mount */

	/*
	 * Create the CLIENT handle for NFS operations
	 */
	if (roothandle.version == NFS_VERSION)
		bufsize = NFSBUF_SIZE;
	else
		bufsize = NFS3BUF_SIZE;

	/*
	 * First try TCP then UDP (unless UDP asked for explicitly), if mountd
	 * alows this version but neither transport is available we are stuck.
	 */
	if (istcp) {
		fd = -1;
		root_CLIENT = clntbtcp_create(&root_to, NFS_PROGRAM,
			roothandle.version, wait, &fd, bufsize, bufsize);
		if (root_CLIENT != NULL) {
			root_CLIENT->cl_auth =
			    authunix_create(my_hostname, 0, 1, 1, &fake_gids);
			/*
			 * Send NULL proc, check if the server really exists
			 */
			rpc_stat = CLNT_CALL(root_CLIENT, 0,
					xdr_void, NULL, xdr_void, NULL, wait);

			if (rpc_stat == RPC_SUCCESS)
				return (0);

			AUTH_DESTROY(root_CLIENT->cl_auth);
			CLNT_DESTROY(root_CLIENT);
			root_CLIENT = NULL;
		}
		/* Fall through to UDP case */
	}

	fd = -1;
	root_CLIENT = clntbudp_bufcreate(&root_to, NFS_PROGRAM,
			roothandle.version, wait, &fd, bufsize, bufsize);
	if (root_CLIENT == NULL)
		return (-1);

	root_CLIENT->cl_auth =
			    authunix_create(my_hostname, 0, 1, 1, &fake_gids);
	/*
	 * Send NULL proc, check if the server really exists
	 */
	rpc_stat = CLNT_CALL(root_CLIENT, 0,
				xdr_void, NULL, xdr_void, NULL, wait);

	if (rpc_stat == RPC_SUCCESS)
		return (0);

	AUTH_DESTROY(root_CLIENT->cl_auth);
	CLNT_DESTROY(root_CLIENT);
	root_CLIENT = NULL;
	return (-1);
}
/*
 * 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.
 *
 * Simple nfs ops - open, close, read, and lseek.
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#include <rpc/types.h>
#include <rpc/auth.h>
#include <sys/t_lock.h>
#include "clnt.h"
#include <sys/fcntl.h>
#include <sys/vfs.h>
#include <errno.h>
#include <sys/promif.h>
#include <rpc/xdr.h>
#include "nfs_inet.h"
#include <sys/stat.h>
#include <sys/bootvfs.h>
#include <sys/bootdebug.h>
#include <sys/salib.h>
#include <sys/sacache.h>
#include <rpc/rpc.h>
#include "brpc.h"
#include <rpcsvc/nfs_prot.h>

#define	dprintf	if (boothowto & RB_DEBUG) printf

static struct timeval zero_timeout = {0, 0};	/* default */

/*
 * NFS Version 2 specific functions
 */

ssize_t
nfsread(struct nfs_file *filep, char *buf, size_t size)
{
	readargs		read_args;
	readres			read_res;
	enum clnt_stat		read_stat;
	uint_t			readcnt = 0;	/* # bytes read by nfs */
	uint_t			count = 0;	/* # bytes transferred to buf */
	int			done = FALSE;	/* last block has come in */
	int			framing_errs = 0;	/* stack errors */
	char			*buf_offset;	/* current buffer offset */
	struct timeval		timeout;
	static uint_t		pos;		/* progress indicator counter */
	static char		ind[] = "|/-\\";	/* progress indicator */
	static int		blks_read;

	read_args.file = filep->fh.fh2;		/* structure copy */
	read_args.offset = filep->offset;
	buf_offset = buf;

	/* Optimize for reads of less than one block size */

	if (nfs_readsize == 0)
		nfs_readsize = READ_SIZE;

	if (size < nfs_readsize)
		read_args.count = size;
	else
		read_args.count = nfs_readsize;

	do {
		/* use the user's buffer to stuff the data into. */
		read_res.readres_u.reply.data.data_val = buf_offset;

		/*
		 * Handle the case where the file does not end
		 * on a block boundary.
		 */
		if ((count + read_args.count) > size)
			read_args.count = size - count;

		timeout.tv_sec = NFS_REXMIT_MIN; /* Total wait for call */
		timeout.tv_usec = 0;
		do {
			read_stat = CLNT_CALL(root_CLIENT, NFSPROC_READ,
			    xdr_readargs, (caddr_t)&read_args,
			    xdr_readres, (caddr_t)&read_res, timeout);

			if (read_stat == RPC_TIMEDOUT) {
				dprintf("NFS read(%d) timed out. Retrying...\n",
				    read_args.count);
				/*
				 * If the remote is there and trying to respond,
				 * but our stack is having trouble reassembling
				 * the reply, reduce the read size in an
				 * attempt to compensate. Reset the
				 * transmission and reply wait timers.
				 */
				if (errno == ETIMEDOUT)
					framing_errs++;

				if (framing_errs > NFS_MAX_FERRS &&
				    read_args.count > NFS_READ_DECR) {
					read_args.count -= NFS_READ_DECR;
					nfs_readsize -= NFS_READ_DECR;
					dprintf("NFS Read size now %d.\n",
					    nfs_readsize);
					timeout.tv_sec = NFS_REXMIT_MIN;
					framing_errs = 0;
				} else {
					if (timeout.tv_sec < NFS_REXMIT_MAX)
						timeout.tv_sec++;
					else
						timeout.tv_sec = 0;
							/* default RPC */
				}
			}
		} while (read_stat == RPC_TIMEDOUT);

		if (read_stat != RPC_SUCCESS)
			return (-1);

		readcnt = read_res.readres_u.reply.data.data_len;
		/*
		 * Handle the case where the file is simply empty, and
		 * nothing could be read.
		 */
		if (readcnt == 0)
			break; /* eof */

		/*
		 * Handle the case where the file is smaller than
		 * the size of the read request, thus the request
		 * couldn't be completely filled.
		 */
		if (readcnt < read_args.count) {
#ifdef NFS_OPS_DEBUG
		if ((boothowto & DBFLAGS) == DBFLAGS)
			printf("nfsread(): partial read %d"
			    " instead of %d\n",
			    readcnt, read_args.count);
#endif
		done = TRUE; /* update the counts and exit */
		}

		/* update various offsets */
		count += readcnt;
		filep->offset += readcnt;
		buf_offset += readcnt;
		read_args.offset += readcnt;
		/*
		 * round and round she goes (though not on every block..
		 * - OBP's take a fair bit of time to actually print stuff)
		 */
		if ((blks_read++ & 0x3) == 0)
			printf("%c\b", ind[pos++ & 3]);
	} while (count < size && !done);

	return (count);
}

static vtype_t nf_to_vt[] = {
	VNON, VREG, VDIR, VBLK, VCHR, VLNK, VSOCK
};

int
nfsgetattr(struct nfs_file *nfp, struct vattr *vap)
{
	enum clnt_stat getattr_stat;
	attrstat getattr_res;
	fattr *na;
	struct timeval timeout = {0, 0};	/* default */

	getattr_stat = CLNT_CALL(root_CLIENT, NFSPROC_GETATTR,
	    xdr_nfs_fh, (caddr_t)&(nfp->fh.fh2),
	    xdr_attrstat, (caddr_t)&getattr_res, timeout);

	if (getattr_stat != RPC_SUCCESS) {
		dprintf("nfs_getattr: RPC error %d\n", getattr_stat);
		return (-1);
	}
	if (getattr_res.status != NFS_OK) {
		nfs_error(getattr_res.status);
		return (getattr_res.status);
	}

	/* adapted from nattr_to_vattr() in nfs_client.c */

	na = &getattr_res.attrstat_u.attributes;
	if (vap->va_mask & AT_TYPE) {
		if (na->type < NFNON || na->type > NFSOCK)
			vap->va_type = VBAD;
		else
			vap->va_type = nf_to_vt[na->type];
	}
	if (vap->va_mask & AT_MODE)
		vap->va_mode = na->mode;
	if (vap->va_mask & AT_SIZE)
		vap->va_size = na->size;
	if (vap->va_mask & AT_NODEID)
		vap->va_nodeid = na->fileid;
	if (vap->va_mask & AT_ATIME) {
		vap->va_atime.tv_sec  = na->atime.seconds;
		vap->va_atime.tv_nsec = na->atime.useconds * 1000;
	}
	if (vap->va_mask & AT_CTIME) {
		vap->va_ctime.tv_sec  = na->ctime.seconds;
		vap->va_ctime.tv_nsec = na->ctime.useconds * 1000;
	}
	if (vap->va_mask & AT_MTIME) {
		vap->va_mtime.tv_sec  = na->mtime.seconds;
		vap->va_mtime.tv_nsec = na->mtime.useconds * 1000;
	}

#ifdef NFS_OPS_DEBUG
	if ((boothowto & DBFLAGS) == DBFLAGS)
		printf("nfs_getattr(): done.\n");
#endif
	return (getattr_res.status);
}

/*
 * Display nfs error messages.
 */
/*ARGSUSED*/
void
nfs_error(enum nfsstat status)
{
	if (!(boothowto & RB_DEBUG))
		return;

	switch (status) {
	case NFSERR_PERM:
		printf("NFS: Not owner.\n");
		break;
	case NFSERR_NOENT:
#ifdef	NFS_OPS_DEBUG
		printf("NFS: No such file or directory.\n");
#endif	/* NFS_OPS_DEBUG */
		break;
	case NFSERR_IO:
		printf("NFS: IO ERROR occurred on NFS server.\n");
		break;
	case NFSERR_NXIO:
		printf("NFS: No such device or address.\n");
		break;
	case NFSERR_ACCES:
		printf("NFS: Permission denied.\n");
		break;
	case NFSERR_EXIST:
		printf("NFS: File exists.\n");
		break;
	case NFSERR_NODEV:
		printf("NFS: No such device.\n");
		break;
	case NFSERR_NOTDIR:
		printf("NFS: Not a directory.\n");
		break;
	case NFSERR_ISDIR:
		printf("NFS: Is a directory.\n");
		break;
	case NFSERR_FBIG:
		printf("NFS: File too large.\n");
		break;
	case NFSERR_NOSPC:
		printf("NFS: No space left on device.\n");
		break;
	case NFSERR_ROFS:
		printf("NFS: Read-only filesystem.\n");
		break;
	case NFSERR_NAMETOOLONG:
		printf("NFS: File name too long.\n");
		break;
	case NFSERR_NOTEMPTY:
		printf("NFS: Directory not empty.\n");
		break;
	case NFSERR_DQUOT:
		printf("NFS: Disk quota exceeded.\n");
		break;
	case NFSERR_STALE:
		printf("NFS: Stale file handle.\n");
		break;
	case NFSERR_WFLUSH:
		printf("NFS: server's write cache has been flushed.\n");
		break;
	default:
		printf("NFS: unknown error.\n");
		break;
	}
}

struct nfs_file *
nfslookup(struct nfs_file *dir, char *name, int *nstat)
{
	static struct nfs_file cd;
	diropargs dirop;
	diropres res_lookup;
	enum clnt_stat status;

	*nstat = (int)NFS_OK;

	bcopy(&dir->fh.fh2, &dirop.dir, NFS_FHSIZE);
	dirop.name = name;

	status = CLNT_CALL(root_CLIENT, NFSPROC_LOOKUP, xdr_diropargs,
	    (caddr_t)&dirop, xdr_diropres, (caddr_t)&res_lookup,
	    zero_timeout);
	if (status != RPC_SUCCESS) {
		dprintf("lookup: RPC error.\n");
		return (NULL);
	}
	if (res_lookup.status != NFS_OK) {
		nfs_error(res_lookup.status);
		*nstat = (int)res_lookup.status;
		return (NULL);
	}

	bzero((caddr_t)&cd, sizeof (struct nfs_file));
	cd.version = NFS_VERSION;
	cd.ftype.type2 = res_lookup.diropres_u.diropres.attributes.type;
	bcopy(&res_lookup.diropres_u.diropres.file, &cd.fh.fh2, NFS_FHSIZE);
	return (&cd);
}

/*
 * Gets symbolic link into pathname.
 */
int
nfsgetsymlink(struct nfs_file *cfile, char **path)
{
	enum clnt_stat status;
	struct readlinkres linkres;
	static char symlink_path[NFS_MAXPATHLEN];

	/*
	 * linkres needs a zeroed buffer to place path data into:
	 */
	bzero(symlink_path, NFS_MAXPATHLEN);
	linkres.readlinkres_u.data = &symlink_path[0];

	status = CLNT_CALL(root_CLIENT, NFSPROC_READLINK,
	    xdr_nfs_fh, (caddr_t)&cfile->fh.fh2,
	    xdr_readlinkres, (caddr_t)&linkres, zero_timeout);
	if (status != RPC_SUCCESS) {
		dprintf("nfsgetsymlink: RPC call failed.\n");
		return (-1);
	}
	if (linkres.status != NFS_OK) {
		nfs_error(linkres.status);
		return (linkres.status);
	}

	*path = linkres.readlinkres_u.data;

	return (NFS_OK);
}
/*
 * 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 2004 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#include <rpc/types.h>
#include <rpc/xdr.h>
#include <rpc/rpc.h>
#include <rpcsvc/nfs_prot.h>

/*
 * Xdr routines for NFS ops.
 */

static bool_t
xdr_b_nfs_fh3(XDR *xdrs, nfs_fh3 *objp)
{
	return (xdr_bytes(xdrs, (char **)&objp->data.data_val,
				(uint_t *)&objp->data.data_len, NFS3_FHSIZE));
}

static bool_t
xdr_b_fattr3(XDR *xdrs, fattr3 *objp)
{
	if (!xdr_enum(xdrs, (enum_t *)&objp->type))
		return (FALSE);
	if (!xdr_u_int(xdrs, &objp->mode))
		return (FALSE);
	if (!xdr_u_int(xdrs, &objp->nlink))
		return (FALSE);
	if (!xdr_u_int(xdrs, &objp->uid))
		return (FALSE);
	if (!xdr_u_int(xdrs, &objp->gid))
		return (FALSE);
	if (!xdr_u_longlong_t(xdrs, &objp->size))
		return (FALSE);
	if (!xdr_u_longlong_t(xdrs, &objp->used))
		return (FALSE);
	if (!xdr_u_int(xdrs, &objp->rdev.specdata1))
		return (FALSE);
	if (!xdr_u_int(xdrs, &objp->rdev.specdata2))
		return (FALSE);
	if (!xdr_u_longlong_t(xdrs, &objp->fsid))
		return (FALSE);
	if (!xdr_u_longlong_t(xdrs, &objp->fileid))
		return (FALSE);
	if (!xdr_u_int(xdrs, &objp->atime.seconds))
		return (FALSE);
	if (!xdr_u_int(xdrs, &objp->atime.nseconds))
		return (FALSE);
	if (!xdr_u_int(xdrs, &objp->mtime.seconds))
		return (FALSE);
	if (!xdr_u_int(xdrs, &objp->mtime.nseconds))
		return (FALSE);
	if (!xdr_u_int(xdrs, &objp->ctime.seconds))
		return (FALSE);
	return (xdr_u_int(xdrs, &objp->ctime.nseconds));
}

static bool_t
xdr_b_post_op_attr(XDR *xdrs, post_op_attr *objp)
{
	if (!xdr_bool(xdrs, &objp->attributes_follow))
		return (FALSE);
	switch (objp->attributes_follow) {
	case TRUE:
		return (xdr_b_fattr3(xdrs, &objp->post_op_attr_u.attributes));
	case FALSE:
		return (TRUE);
	default:
		return (FALSE);
	}
}

static bool_t
xdr_b_diropargs3(XDR *xdrs, diropargs3 *objp)
{
	if (!xdr_b_nfs_fh3(xdrs, &objp->dir))
		return (FALSE);
	return (xdr_string(xdrs, &objp->name, ~0));
}

bool_t
xdr_GETATTR3args(XDR *xdrs, GETATTR3args *objp)
{
	return (xdr_b_nfs_fh3(xdrs, &objp->object));
}

static bool_t
xdr_b_GETATTR3resok(XDR *xdrs, GETATTR3resok *objp)
{
	return (xdr_b_fattr3(xdrs, &objp->obj_attributes));
}

bool_t
xdr_GETATTR3res(XDR *xdrs, GETATTR3res *objp)
{
	if (!xdr_enum(xdrs, (enum_t *)&objp->status))
		return (FALSE);
	if (objp->status == NFS3_OK)
		return (xdr_b_GETATTR3resok(xdrs, &objp->GETATTR3res_u.resok));
	return (TRUE);
}

bool_t
xdr_LOOKUP3args(XDR *xdrs, LOOKUP3args *objp)
{
	return (xdr_b_diropargs3(xdrs, &objp->what));
}

static bool_t
xdr_b_LOOKUP3resok(XDR *xdrs, LOOKUP3resok *objp)
{
	if (!xdr_b_nfs_fh3(xdrs, &objp->object))
		return (FALSE);
	if (!xdr_b_post_op_attr(xdrs, &objp->obj_attributes))
		return (FALSE);
	return (xdr_b_post_op_attr(xdrs, &objp->dir_attributes));
}

static bool_t
xdr_b_LOOKUP3resfail(XDR *xdrs, LOOKUP3resfail *objp)
{
	return (xdr_b_post_op_attr(xdrs, &objp->dir_attributes));
}

bool_t
xdr_LOOKUP3res(XDR *xdrs, LOOKUP3res *objp)
{
	if (!xdr_enum(xdrs, (enum_t *)&objp->status))
		return (FALSE);

	if (objp->status == NFS3_OK)
		return (xdr_b_LOOKUP3resok(xdrs, &objp->LOOKUP3res_u.resok));

	return (xdr_b_LOOKUP3resfail(xdrs, &objp->LOOKUP3res_u.resfail));
}

bool_t
xdr_READLINK3args(XDR *xdrs, READLINK3args *objp)
{
	return (xdr_b_nfs_fh3(xdrs, &objp->symlink));
}

static bool_t
xdr_b_READLINK3resok(XDR *xdrs, READLINK3resok *objp)
{
	if (!xdr_b_post_op_attr(xdrs, &objp->symlink_attributes))
		return (FALSE);
	return (xdr_string(xdrs, &objp->data, ~0));
}

static bool_t
xdr_b_READLINK3resfail(XDR *xdrs, READLINK3resfail *objp)
{
	return (xdr_b_post_op_attr(xdrs, &objp->symlink_attributes));
}

bool_t
xdr_READLINK3res(XDR *xdrs, READLINK3res *objp)
{
	if (!xdr_enum(xdrs, (enum_t *)&objp->status))
		return (FALSE);
	if (objp->status == NFS3_OK)
		return (xdr_b_READLINK3resok(xdrs,
						&objp->READLINK3res_u.resok));
	return (xdr_b_READLINK3resfail(xdrs, &objp->READLINK3res_u.resfail));
}

bool_t
xdr_READ3args(XDR *xdrs, READ3args *objp)
{
	if (!xdr_b_nfs_fh3(xdrs, &objp->file))
		return (FALSE);
	if (!xdr_u_longlong_t(xdrs, &objp->offset))
		return (FALSE);
	return (xdr_u_int(xdrs, &objp->count));
}

static bool_t
xdr_b_READ3resok(XDR *xdrs, READ3resok *objp)
{
	if (!xdr_b_post_op_attr(xdrs, &objp->file_attributes))
		return (FALSE);
	if (!xdr_u_int(xdrs, &objp->count))
		return (FALSE);
	if (!xdr_bool(xdrs, &objp->eof))
		return (FALSE);
	return (xdr_bytes(xdrs, (char **)&objp->data.data_val,
					(uint_t *)&objp->data.data_len, ~0));
}

static bool_t
xdr_b_READ3resfail(XDR *xdrs, READ3resfail *objp)
{
	return (xdr_b_post_op_attr(xdrs, &objp->file_attributes));
}

bool_t
xdr_READ3res(XDR *xdrs, READ3res *objp)
{
	if (!xdr_enum(xdrs, (enum_t *)&objp->status))
		return (FALSE);
	if (objp->status == NFS3_OK)
		return (xdr_b_READ3resok(xdrs, &objp->READ3res_u.resok));
	return (xdr_b_READ3resfail(xdrs, &objp->READ3res_u.resfail));
}

bool_t
xdr_READDIR3args(XDR *xdrs, READDIR3args *objp)
{
	if (!xdr_b_nfs_fh3(xdrs, &objp->dir))
		return (FALSE);
	if (!xdr_u_longlong_t(xdrs, &objp->cookie))
		return (FALSE);
	if (!xdr_opaque(xdrs, objp->cookieverf, NFS3_COOKIEVERFSIZE))
		return (FALSE);
	return (xdr_u_int(xdrs, &objp->count));
}

static bool_t
xdr_b_entry3(XDR *xdrs, entry3 *objp)
{
	if (!xdr_u_longlong_t(xdrs, &objp->fileid))
		return (FALSE);
	if (!xdr_string(xdrs, &objp->name, ~0))
		return (FALSE);
	if (!xdr_u_longlong_t(xdrs, &objp->cookie))
		return (FALSE);
	return (xdr_pointer(xdrs, (char **)&objp->nextentry,
				sizeof (entry3), (xdrproc_t)xdr_b_entry3));
}

static bool_t
xdr_b_READDIR3resok(XDR *xdrs, READDIR3resok *objp)
{
	if (!xdr_b_post_op_attr(xdrs, &objp->dir_attributes))
		return (FALSE);
	if (!xdr_opaque(xdrs, objp->cookieverf, NFS3_COOKIEVERFSIZE))
		return (FALSE);
	if (!xdr_pointer(xdrs, (char **)&objp->reply.entries,
				sizeof (entry3), (xdrproc_t)xdr_b_entry3))
		return (FALSE);
	return (xdr_bool(xdrs, &objp->reply.eof));
}

static bool_t
xdr_b_READDIR3resfail(XDR *xdrs, READDIR3resfail *objp)
{
	return (xdr_b_post_op_attr(xdrs, &objp->dir_attributes));
}

bool_t
xdr_READDIR3res(XDR *xdrs, READDIR3res *objp)
{
	if (!xdr_enum(xdrs, (enum_t *)&objp->status))
		return (FALSE);
	if (objp->status == NFS3_OK)
		return (xdr_b_READDIR3resok(xdrs, &objp->READDIR3res_u.resok));
	return (xdr_b_READDIR3resfail(xdrs, &objp->READDIR3res_u.resfail));
}
/*
 * 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.
 *
 * Simple nfs V3 ops
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#include <rpc/types.h>
#include <rpc/auth.h>
#include <sys/t_lock.h>
#include "clnt.h"
#include <sys/fcntl.h>
#include <sys/vfs.h>
#include <errno.h>
#include <sys/promif.h>
#include <rpc/xdr.h>
#include "nfs_inet.h"
#include <sys/stat.h>
#include <sys/bootvfs.h>
#include <sys/bootdebug.h>
#include <sys/salib.h>
#include <sys/sacache.h>
#include <rpc/rpc.h>
#include "brpc.h"
#include <rpcsvc/nfs_prot.h>

#define	dprintf	if (boothowto & RB_DEBUG) printf

/*
 * NFS Version 3 specific functions
 */

ssize_t
nfs3read(struct nfs_file *filep, char *buf, size_t size)
{
	READ3args		read_args;
	READ3res		read_res;
	enum clnt_stat		read_stat;
	uint_t			readcnt = 0;	/* # bytes read by nfs */
	uint_t			count = 0;	/* # bytes transferred to buf */
	int			done = FALSE;	/* last block has come in */
	int			framing_errs = 0;	/* stack errors */
	char			*buf_offset;	/* current buffer offset */
	struct timeval		timeout;
	static uint_t		pos;		/* progress indicator counter */
	static char		ind[] = "|/-\\";	/* progress indicator */
	static int		blks_read;

	read_args.file.data.data_len = filep->fh.fh3.len;
	read_args.file.data.data_val = filep->fh.fh3.data;
	read_args.offset = filep->offset;

	bzero(&read_res, sizeof (read_res));

	buf_offset = buf;

	/* Optimize for reads of less than one block size */

	if (nfs_readsize == 0)
		nfs_readsize = READ3_SIZE;

	if (size < nfs_readsize)
		read_args.count = size;
	else
		read_args.count = nfs_readsize;

	do {
		/* use the user's buffer to stuff the data into. */
		read_res.READ3res_u.resok.data.data_val = buf_offset;

		/*
		 * Handle the case where the file does not end
		 * on a block boundary.
		 */
		if ((count + read_args.count) > size)
			read_args.count = size - count;

		timeout.tv_sec = NFS_REXMIT_MIN; /* Total wait for call */
		timeout.tv_usec = 0;
		do {
			read_stat = CLNT_CALL(root_CLIENT, NFSPROC3_READ,
			    xdr_READ3args, (caddr_t)&read_args,
			    xdr_READ3res, (caddr_t)&read_res, timeout);

			if (read_stat == RPC_TIMEDOUT) {
				dprintf("NFS read(%d) timed out. Retrying...\n",
				    read_args.count);
				/*
				 * If the remote is there and trying to respond,
				 * but our stack is having trouble reassembling
				 * the reply, reduce the read size in an
				 * attempt to compensate. Reset the
				 * transmission and reply wait timers.
				 */
				if (errno == ETIMEDOUT)
					framing_errs++;

				if (framing_errs > NFS_MAX_FERRS &&
				    read_args.count > NFS_READ_DECR) {
					read_args.count /= 2;
					nfs_readsize /= 2;
					dprintf("NFS Read size now %d.\n",
					    nfs_readsize);
					timeout.tv_sec = NFS_REXMIT_MIN;
					framing_errs = 0;
				} else {
					if (timeout.tv_sec < NFS_REXMIT_MAX)
						timeout.tv_sec++;
					else
						timeout.tv_sec = 0;
							/* default RPC */
				}
			}
		} while (read_stat == RPC_TIMEDOUT);

		if (read_stat != RPC_SUCCESS)
			return (-1);

		if (read_res.status != NFS3_OK)
			return (-1);

		readcnt = read_res.READ3res_u.resok.data.data_len;
		/*
		 * If we are at EOF, update counts and exit
		 */
		if (read_res.READ3res_u.resok.eof == TRUE)
			done = TRUE;

		/*
		 * Handle the case where the file is smaller than
		 * the size of the read request, thus the request
		 * couldn't be completely filled.
		 */
		if (readcnt < read_args.count) {
#ifdef NFS_OPS_DEBUG
			if ((boothowto & DBFLAGS) == DBFLAGS)
				printf("nfs3read(): partial read %d"
				    " instead of %d\n",
				    readcnt, read_args.count);
#endif
			done = TRUE; /* update the counts and exit */
		}

		/* update various offsets */
		count += readcnt;
		filep->offset += readcnt;
		buf_offset += readcnt;
		read_args.offset += readcnt;
		/*
		 * round and round she goes (though not on every block..
		 * - OBP's take a fair bit of time to actually print stuff)
		 */
		if ((blks_read++ & 0x3) == 0)
			printf("%c\b", ind[pos++ & 3]);
	} while (count < size && !done);

	return (count);
}

int
nfs3getattr(struct nfs_file *nfp, struct vattr *vap)
{
	enum clnt_stat getattr_stat;
	GETATTR3args getattr_args;
	GETATTR3res getattr_res;
	fattr3 *na;
	struct timeval timeout = {0, 0};	/* default */
	vtype_t nf3_to_vt[] =
			{ VBAD, VREG, VDIR, VBLK, VCHR, VLNK, VSOCK, VFIFO };


	bzero(&getattr_args, sizeof (getattr_args));
	getattr_args.object.data.data_len = nfp->fh.fh3.len;
	getattr_args.object.data.data_val = nfp->fh.fh3.data;

	bzero(&getattr_res, sizeof (getattr_res));

	getattr_stat = CLNT_CALL(root_CLIENT, NFSPROC3_GETATTR,
	    xdr_GETATTR3args, (caddr_t)&getattr_args,
	    xdr_GETATTR3res, (caddr_t)&getattr_res, timeout);

	if (getattr_stat != RPC_SUCCESS) {
		dprintf("nfs_getattr: RPC error %d\n", getattr_stat);
		return (-1);
	}
	if (getattr_res.status != NFS3_OK) {
		nfs3_error(getattr_res.status);
		return (getattr_res.status);
	}

	na = &getattr_res.GETATTR3res_u.resok.obj_attributes;
	if (vap->va_mask & AT_TYPE) {
		if (na->type < NF3REG || na->type > NF3FIFO)
			vap->va_type = VBAD;
		else
			vap->va_type = nf3_to_vt[na->type];
	}
	if (vap->va_mask & AT_MODE)
		vap->va_mode = (mode_t)na->mode;
	if (vap->va_mask & AT_SIZE)
		vap->va_size = (u_offset_t)na->size;
	if (vap->va_mask & AT_NODEID)
		vap->va_nodeid = (u_longlong_t)na->fileid;
	if (vap->va_mask & AT_ATIME) {
		vap->va_atime.tv_sec  = na->atime.seconds;
		vap->va_atime.tv_nsec = na->atime.nseconds;
	}
	if (vap->va_mask & AT_CTIME) {
		vap->va_ctime.tv_sec  = na->ctime.seconds;
		vap->va_ctime.tv_nsec = na->ctime.nseconds;
	}
	if (vap->va_mask & AT_MTIME) {
		vap->va_mtime.tv_sec  = na->mtime.seconds;
		vap->va_mtime.tv_nsec = na->mtime.nseconds;
	}

	return (NFS3_OK);
}

/*
 * Display nfs error messages.
 */
/*ARGSUSED*/
void
nfs3_error(enum nfsstat3 status)
{
	if (!(boothowto & RB_DEBUG))
		return;

	switch (status) {
	case NFS3_OK:
		printf("NFS: No error.\n");
		break;
	case NFS3ERR_PERM:
		printf("NFS: Not owner.\n");
		break;
	case NFS3ERR_NOENT:
#ifdef	NFS_OPS_DEBUG
		printf("NFS: No such file or directory.\n");
#endif	/* NFS_OPS_DEBUG */
		break;
	case NFS3ERR_IO:
		printf("NFS: IO ERROR occurred on NFS server.\n");
		break;
	case NFS3ERR_NXIO:
		printf("NFS: No such device or address.\n");
		break;
	case NFS3ERR_ACCES:
		printf("NFS: Permission denied.\n");
		break;
	case NFS3ERR_EXIST:
		printf("NFS: File exists.\n");
		break;
	case NFS3ERR_XDEV:
		printf("NFS: Cross device hard link.\n");
		break;
	case NFS3ERR_NODEV:
		printf("NFS: No such device.\n");
		break;
	case NFS3ERR_NOTDIR:
		printf("NFS: Not a directory.\n");
		break;
	case NFS3ERR_ISDIR:
		printf("NFS: Is a directory.\n");
		break;
	case NFS3ERR_INVAL:
		printf("NFS: Invalid argument.\n");
		break;
	case NFS3ERR_FBIG:
		printf("NFS: File too large.\n");
		break;
	case NFS3ERR_NOSPC:
		printf("NFS: No space left on device.\n");
		break;
	case NFS3ERR_ROFS:
		printf("NFS: Read-only filesystem.\n");
		break;
	case NFS3ERR_MLINK:
		printf("NFS: Too many hard links.\n");
		break;
	case NFS3ERR_NAMETOOLONG:
		printf("NFS: File name too long.\n");
		break;
	case NFS3ERR_NOTEMPTY:
		printf("NFS: Directory not empty.\n");
		break;
	case NFS3ERR_DQUOT:
		printf("NFS: Disk quota exceeded.\n");
		break;
	case NFS3ERR_STALE:
		printf("NFS: Stale file handle.\n");
		break;
	case NFS3ERR_REMOTE:
		printf("NFS: Remote file in path.\n");
		break;
	case NFS3ERR_BADHANDLE:
		printf("NFS: Illegal NFS file handle.\n");
		break;
	case NFS3ERR_NOT_SYNC:
		printf("NFS: Synchronization mismatch.\n");
		break;
	case NFS3ERR_BAD_COOKIE:
		printf("NFS: Stale Cookie.\n");
		break;
	case NFS3ERR_NOTSUPP:
		printf("NFS: Operation is not supported.\n");
		break;
	case NFS3ERR_TOOSMALL:
		printf("NFS: Buffer too small.\n");
		break;
	case NFS3ERR_SERVERFAULT:
		printf("NFS: Server fault.\n");
		break;
	case NFS3ERR_BADTYPE:
		printf("NFS: Unsupported object type.\n");
		break;
	case NFS3ERR_JUKEBOX:
		printf("NFS: Resource temporarily unavailable.\n");
		break;
	default:
		printf("NFS: unknown error.\n");
		break;
	}
}

struct nfs_file *
nfs3lookup(struct nfs_file *dir, char *name, int *nstat)
{
	struct timeval zero_timeout = {0, 0};	/* default */
	static struct nfs_file cd;
	LOOKUP3args dirop;
	LOOKUP3res res_lookup;
	enum clnt_stat status;

	*nstat = (int)NFS3_OK;

	bzero((caddr_t)&dirop, sizeof (LOOKUP3args));
	bzero((caddr_t)&res_lookup, sizeof (LOOKUP3res));

	dirop.what.dir.data.data_len = dir->fh.fh3.len;
	dirop.what.dir.data.data_val = dir->fh.fh3.data;
	dirop.what.name = name;

	status = CLNT_CALL(root_CLIENT, NFSPROC3_LOOKUP, xdr_LOOKUP3args,
	    (caddr_t)&dirop, xdr_LOOKUP3res, (caddr_t)&res_lookup,
	    zero_timeout);
	if (status != RPC_SUCCESS) {
		dprintf("lookup: RPC error.\n");
		return (NULL);
	}
	if (res_lookup.status != NFS3_OK) {
		nfs3_error(res_lookup.status);
		*nstat = (int)res_lookup.status;
		(void) CLNT_FREERES(root_CLIENT,
		    xdr_LOOKUP3res, (caddr_t)&res_lookup);
		return (NULL);
	}

	bzero((caddr_t)&cd, sizeof (struct nfs_file));
	cd.version = NFS_V3;
	/*
	 * Server must supply post_op_attr's
	 */
	if (res_lookup.LOOKUP3res_u.resok.obj_attributes.attributes_follow ==
	    FALSE) {
		printf("nfs3lookup: server fails to return post_op_attr\n");
		(void) CLNT_FREERES(root_CLIENT,
		    xdr_LOOKUP3res, (caddr_t)&res_lookup);
		return (NULL);
	}

	cd.ftype.type3 = res_lookup.LOOKUP3res_u.resok.obj_attributes
	    .post_op_attr_u.attributes.type;
	cd.fh.fh3.len = res_lookup.LOOKUP3res_u.resok.object.data.data_len;
	bcopy(res_lookup.LOOKUP3res_u.resok.object.data.data_val,
	    cd.fh.fh3.data, cd.fh.fh3.len);
	(void) CLNT_FREERES(root_CLIENT, xdr_LOOKUP3res, (caddr_t)&res_lookup);
	return (&cd);
}

/*
 * Gets symbolic link into pathname.
 */
int
nfs3getsymlink(struct nfs_file *cfile, char **path)
{
	struct timeval zero_timeout = {0, 0};	/* default */
	enum clnt_stat status;
	struct READLINK3res linkres;
	struct READLINK3args linkargs;
	static char symlink_path[NFS_MAXPATHLEN];

	bzero(&linkargs, sizeof (linkargs));
	linkargs.symlink.data.data_len = cfile->fh.fh3.len;
	linkargs.symlink.data.data_val = cfile->fh.fh3.data;

	/*
	 * linkres needs a zeroed buffer to place path data into:
	 */
	bzero(&linkres, sizeof (linkres));
	bzero(symlink_path, NFS_MAXPATHLEN);
	linkres.READLINK3res_u.resok.data = symlink_path;

	status = CLNT_CALL(root_CLIENT, NFSPROC3_READLINK,
	    xdr_READLINK3args, (caddr_t)&linkargs,
	    xdr_READLINK3res, (caddr_t)&linkres, zero_timeout);
	if (status != RPC_SUCCESS) {
		dprintf("nfs3getsymlink: RPC call failed.\n");
		return (-1);
	}
	if (linkres.status != NFS3_OK) {
		nfs3_error(linkres.status);
		return (linkres.status);
	}

	*path = symlink_path;

	return (NFS3_OK);
}
/*
 * 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 2015 Nexenta Systems, Inc.  All rights reserved.
 */

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

#include <sys/salib.h>
#include <rpc/types.h>
#include <rpc/xdr.h>
#include <rpc/rpc.h>
#include <rpcsvc/nfs4_prot.h>
#include "nfs_inet.h"

#define	dprintf if (boothowto & RB_DEBUG) printf

/*
 * XDR routines for NFSv4 ops.
 */
static bool_t
xdr_b_utf8string(XDR *xdrs, utf8string *objp)
{
	return (xdr_bytes(xdrs, (char **)&objp->utf8string_val,
	    (uint_t *)&objp->utf8string_len, NFS4_MAX_UTF8STRING));
}

static bool_t
xdr_nfs_bfh4(XDR *xdrs, struct nfs_bfh4 *objp)
{
	char *data = (char *)&objp->data;
	return (xdr_bytes(xdrs, (char **)&data, (uint_t *)&objp->len,
	    NFS4_FHSIZE));
}

static bool_t
xdr_b_putfh4_args(XDR *xdrs, putfh4arg_t *objp)
{
	if (!xdr_u_int(xdrs, (uint_t *)&objp->pf_opnum))
		return (FALSE);
	return (xdr_nfs_bfh4(xdrs, (struct nfs_bfh4 *)&objp->pf_filehandle));
}

/*
 * Common xdr routines for compound.  Let the specific op routines handle
 * op specific portions of the compound.
 */
static bool_t
xdr_b_compound_args(XDR *xdrs, b_compound_t *objp)
{
	if (!xdr_b_utf8string(xdrs, &objp->ca_tag)) {
		return (FALSE);
	}
	if (!xdr_u_int(xdrs, &objp->ca_minorversion))
		return (FALSE);
	if (!xdr_u_int(xdrs, &objp->ca_argarray_len))
		return (FALSE);
	if (objp->ca_isputrootfh)
		return (xdr_u_int(xdrs, &objp->ca_opputfh.pf_opnum));
	return (xdr_b_putfh4_args(xdrs, &objp->ca_opputfh));
}

static bool_t
xdr_b_compound_res(XDR *xdrs, b_compound_t *objp)
{
	if (!xdr_enum(xdrs, (enum_t *)&objp->cr_status))
		return (FALSE);
	if (!xdr_b_utf8string(xdrs, &objp->cr_tag))
		return (FALSE);
	if (!xdr_u_int(xdrs, &objp->cr_resarray_len))
		return (FALSE);
	if (!xdr_u_int(xdrs, &objp->cr_opputfh))
		return (FALSE);
	return (xdr_enum(xdrs, (enum_t *)&objp->cr_putfh_status));
}

static bool_t
xdr_b_bitmap4(XDR *xdrs, b_bitmap4_t *objp)
{
	char *arp = (char *)&objp->b_bitmap_val;
	return (xdr_array(xdrs, (char **)&arp,
	    (uint_t *)&objp->b_bitmap_len, ~0,
	    sizeof (uint_t), (xdrproc_t)xdr_u_int));
}

static bool_t
xdr_b_stateid4(XDR *xdrs, stateid4 *objp)
{
	if (!xdr_u_int(xdrs, (uint_t *)&objp->seqid))
		return (FALSE);
	return (xdr_opaque(xdrs, objp->other, NFS4_OTHER_SIZE));
}

bool_t
xdr_getattr4_args(XDR *xdrs, getattr4arg_t *objp)
{
	if (!xdr_b_compound_args(xdrs, (b_compound_t *)&objp->ga_arg))
		return (FALSE);
	if (!xdr_u_int(xdrs, (uint_t *)&objp->ga_opgetattr))
		return (FALSE);
	return (xdr_b_bitmap4(xdrs, (b_bitmap4_t *)&objp->ga_attr_req));
}

static bool_t
xdr_b_getattr_res_common(XDR *xdrs, getattrres_cmn_t *objp)
{
	if (!xdr_u_int(xdrs, (uint_t *)&objp->gc_opgetattr))
		return (FALSE);
	if (!xdr_enum(xdrs, (enum_t *)&objp->gc_attr_status))
		return (FALSE);

	/*
	 * If the getattr suceeded, proceed and begin to decode the attributes.
	 */
	if (objp->gc_attr_status == NFS4_OK) {
		char		attrvals[sizeof (b_fattr4_t)];
		char		*ap = attrvals;

		if (!xdr_b_bitmap4(xdrs, (b_bitmap4_t *)&objp->gc_retattr))
			return (FALSE);

		bzero(&attrvals, sizeof (attrvals));
		if (!xdr_bytes(xdrs, (char **)&ap,
		    (uint_t *)&objp->gc_attrlist_len, sizeof (b_fattr4_t)))
			return (FALSE);
#ifdef DEBUG
		printf("xdr_b_getattr_res_common: attrlist_len = %d\n",
		    objp->gc_attrlist_len);
#endif
		/*
		 * Go through the bitmap and see if the server
		 * sent us anything.
		 */
		if (objp->gc_attrlist_len > 0) {
			XDR		mxdrs;
			b_fattr4_t	*fattrp = &objp->gc_attrs;
			attr4_bitmap1_t bitmap1;
			attr4_bitmap2_t bitmap2;
#ifdef DEBUG
			int i;

			printf("dumping contents of attr buffer\n");
			for (i = 0; i < objp->gc_attrlist_len; i++) {
				printf("[%d] = 0x%x\n", i, ap[i]);
			}
#endif
			bitmap1.word = objp->gc_retattr.b_bitmap_val[0];
			bitmap2.word = objp->gc_retattr.b_bitmap_val[1];

#ifdef DEBUG
			printf("xdr_b_getattr_res_common: bitmap1 = %d "
			    "			bitmap2 = %d\n",
			    bitmap1.word, bitmap2.word);
#endif
			xdrmem_create(&mxdrs, ap, objp->gc_attrlist_len,
			    XDR_DECODE);

			/*
			 * Start with the first bitmap
			 */
			if (bitmap1.word > 0) {
				if (bitmap1.bm_supported_attrs) {
					if (!xdr_b_bitmap4(&mxdrs,
					    (b_bitmap4_t *)&fattrp->
					    b_supported_attrs))
						return (FALSE);
				}

				if (bitmap1.bm_fattr4_type) {
					if (!xdr_enum(&mxdrs,
				(enum_t *)&fattrp->b_fattr4_type)) {
						return (FALSE);
					}
				}
				if (bitmap1.bm_fattr4_size) {
					if (!xdr_u_longlong_t(&mxdrs,
					    (u_longlong_t *)&fattrp->
					    b_fattr4_size))
						return (FALSE);
				}

				if (bitmap1.bm_fattr4_fsid) {
					if (!xdr_u_longlong_t(&mxdrs,
					    (u_longlong_t *)&fattrp->
					    b_fattr4_fsid.major))
						return (FALSE);

					if (!xdr_u_longlong_t(&mxdrs,
					    (u_longlong_t *)&fattrp->
					    b_fattr4_fsid.minor))
						return (FALSE);
				}
				if (bitmap1.bm_fattr4_filehandle) {
					if (!xdr_nfs_bfh4(&mxdrs,
					    (struct nfs_bfh4 *)&fattrp->
					    b_fattr4_filehandle))
						return (FALSE);
				}
				if (bitmap1.bm_fattr4_fileid) {
					if (!xdr_u_longlong_t(&mxdrs,
					    (u_longlong_t *)&fattrp->
					    b_fattr4_fileid))
						return (FALSE);
				}
			}

			/*
			 * Now the second bitmap
			 */
			if (bitmap2.word > 0) {
				if (bitmap2.bm_fattr4_mode) {
					if (!xdr_u_int(&mxdrs, (uint_t *)&objp->
					    gc_attrs.b_fattr4_mode))
						return (FALSE);
				}

				if (bitmap2.bm_fattr4_time_access) {
					if (!xdr_longlong_t(&mxdrs,
					    (longlong_t *)&objp->gc_attrs.
					    b_fattr4_time_access.seconds))
						return (FALSE);
					if (!xdr_u_int(&mxdrs,
					    (uint_t *)&objp->gc_attrs.
					    b_fattr4_time_access.nseconds))
						return (FALSE);
				}

				if (bitmap2.bm_fattr4_time_metadata) {
					if (!xdr_longlong_t(&mxdrs,
					    (longlong_t *)&objp->gc_attrs.
					    b_fattr4_time_metadata.seconds))
						return (FALSE);
					if (!xdr_u_int(&mxdrs,
					    (uint_t *)&objp->gc_attrs.
					    b_fattr4_time_metadata.nseconds))
						return (FALSE);
				}

				if (bitmap2.bm_fattr4_time_modify) {
					if (!xdr_longlong_t(&mxdrs,
					    (longlong_t *)&objp->gc_attrs.
					    b_fattr4_time_modify.seconds))
						return (FALSE);
					if (!xdr_u_int(&mxdrs,
					    (uint_t *)&objp->gc_attrs.
					    b_fattr4_time_modify.nseconds))
						return (FALSE);
				}
			}
		}
	}
	return (TRUE);
}

bool_t
xdr_getattr4_res(XDR *xdrs, getattr4res_t *objp)
{
	if (!xdr_b_compound_res(xdrs, (b_compound_t *)&objp->gr_res))
		return (FALSE);
	return (xdr_b_getattr_res_common(xdrs,
	    (getattrres_cmn_t *)&objp->gr_cmn));
}

bool_t
xdr_lookup4_args(XDR *xdrs, lookup4arg_t *objp)
{
	if (!xdr_b_compound_args(xdrs, (b_compound_t *)&objp->la_arg))
		return (FALSE);
	if (!xdr_u_int(xdrs, (uint_t *)&objp->la_oplookup))
		return (FALSE);
	if (!xdr_b_utf8string(xdrs, (utf8string *)&objp->la_pathname))
		return (FALSE);
	if (!xdr_u_int(xdrs, (uint_t *)&objp->la_opgetattr))
		return (FALSE);
	return (xdr_b_bitmap4(xdrs, (b_bitmap4_t *)&objp->la_attr_req));
}

bool_t
xdr_lookup4_res(XDR *xdrs, lookup4res_t *objp)
{
	if (!xdr_b_compound_res(xdrs, (b_compound_t *)&objp->lr_res))
		return (FALSE);
	if (!xdr_u_int(xdrs, (uint_t *)&objp->lr_oplookup))
		return (FALSE);
	if (!xdr_enum(xdrs, (enum_t *)&objp->lr_lookup_status))
		return (FALSE);
	if (objp->lr_lookup_status == NFS4_OK) {
		return (xdr_b_getattr_res_common(xdrs,
		    (getattrres_cmn_t *)&objp->lr_gcmn));
	}
	return (TRUE);
}

bool_t
xdr_lookupp4_args(XDR *xdrs, lookupp4arg_t *objp)
{
	if (!xdr_b_compound_args(xdrs, (b_compound_t *)&objp->la_arg))
		return (FALSE);
	if (!xdr_u_int(xdrs, (uint_t *)&objp->la_oplookupp))
		return (FALSE);
	if (!xdr_u_int(xdrs, (uint_t *)&objp->la_opgetattr))
		return (FALSE);
	return (xdr_b_bitmap4(xdrs, (b_bitmap4_t *)&objp->la_attr_req));
}

bool_t
xdr_read4_args(XDR *xdrs, read4arg_t *objp)
{
	if (!xdr_b_compound_args(xdrs, (b_compound_t *)&objp->r_arg))
		return (FALSE);
	if (!xdr_u_int(xdrs, (uint_t *)&objp->r_opread))
		return (FALSE);
	if (!xdr_b_stateid4(xdrs, (stateid4 *)&objp->r_stateid))
		return (FALSE);
	if (!xdr_u_longlong_t(xdrs, (u_longlong_t *)&objp->r_offset))
		return (FALSE);
	return (xdr_u_int(xdrs, (uint_t *)&objp->r_count));
}

bool_t
xdr_read4_res(XDR *xdrs, read4res_t *objp)
{
	if (!xdr_b_compound_res(xdrs, (b_compound_t *)&objp->r_res))
		return (FALSE);
	if (!xdr_u_int(xdrs, (uint_t *)&objp->r_opread))
		return (FALSE);
	if (!xdr_enum(xdrs, (enum_t *)&objp->r_status))
		return (FALSE);
	if (objp->r_status == NFS4_OK) {
		if (!xdr_bool(xdrs, (bool_t *)&objp->r_eof))
			return (FALSE);
		return (xdr_bytes(xdrs, (char **)&objp->r_data_val,
		    (uint_t *)&objp->r_data_len, ~0));
	}
	return (TRUE);
}

bool_t
xdr_readdir4_args(XDR *xdrs, readdir4arg_t *objp)
{
	if (!xdr_b_compound_args(xdrs, (b_compound_t *)&objp->rd_arg))
		return (FALSE);
	if (!xdr_u_int(xdrs, (uint_t *)&objp->rd_opreaddir))
		return (FALSE);
	if (!xdr_u_longlong_t(xdrs, (u_longlong_t *)&objp->rd_cookie))
		return (FALSE);
	if (!xdr_opaque(xdrs, objp->rd_cookieverf, NFS4_VERIFIER_SIZE))
		return (FALSE);
	if (!xdr_u_int(xdrs, (uint_t *)&objp->rd_dircount))
		return (FALSE);
	if (!xdr_u_int(xdrs, (uint_t *)&objp->rd_maxcount))
		return (FALSE);
	return (xdr_b_bitmap4(xdrs, (b_bitmap4_t *)&objp->rd_attr_req));
}

static bool_t
xdr_b_entry4(XDR *xdrs, b_entry4_t *objp)
{
	uint_t		attrlen;
	char		attrvals[sizeof (b_fattr4_t)];
	char		*ap = attrvals;
	XDR		mxdrs;

	if (!xdr_u_longlong_t(xdrs, (u_longlong_t *)&objp->b_cookie))
		return (FALSE);
	if (!xdr_b_utf8string(xdrs, &objp->b_name))
		return (FALSE);

	bzero(&attrvals, sizeof (attrvals));
	if (!xdr_bytes(xdrs, (char **)&ap, (uint_t *)&attrlen,
	    sizeof (b_fattr4_t)))
		return (FALSE);

	/*
	 * We are *only* interested in the fileid, so just extract that.
	 */
	if (attrlen < sizeof (uint64_t))
		return (FALSE);

	xdrmem_create(&mxdrs, ap, attrlen, XDR_DECODE);

	if (!xdr_u_longlong_t(&mxdrs, (u_longlong_t *)&objp->b_fileid))
		return (FALSE);
	return (xdr_pointer(xdrs, (char **)&objp->b_nextentry,
	    sizeof (b_entry4_t), (xdrproc_t)xdr_b_entry4));
}

bool_t
xdr_readdir4_res(XDR *xdrs, readdir4res_t *objp)
{
	if (!xdr_b_compound_res(xdrs, (b_compound_t *)&objp->rd_res))
		return (FALSE);
	if (!xdr_u_int(xdrs, (uint_t *)&objp->rd_opreaddir))
		return (FALSE);
	if (!xdr_enum(xdrs, (enum_t *)&objp->rd_status))
		return (FALSE);
	if (objp->rd_status == NFS4_OK) {
		if (!xdr_opaque(xdrs, objp->rd_cookieverf, NFS4_VERIFIER_SIZE))
			return (FALSE);
		if (!xdr_pointer(xdrs, (char **)&objp->rd_entries,
		    sizeof (b_entry4_t), (xdrproc_t)xdr_b_entry4))
			return (FALSE);
		return (xdr_bool(xdrs, &objp->rd_eof));
	}
	return (TRUE);
}

bool_t
xdr_readlink4_args(XDR *xdrs, readlink4arg_t *objp)
{
	if (!xdr_b_compound_args(xdrs, (b_compound_t *)&objp->rl_arg))
		return (FALSE);
	return (xdr_u_int(xdrs, (uint_t *)&objp->rl_opreadlink));
}

bool_t
xdr_readlink4_res(XDR *xdrs, readlink4res_t *objp)
{
	if (!xdr_b_compound_res(xdrs, (b_compound_t *)&objp->rl_res))
		return (FALSE);
	if (!xdr_u_int(xdrs, (uint_t *)&objp->rl_opreadlink))
		return (FALSE);
	if (!xdr_enum(xdrs, (enum_t *)&objp->rl_status))
		return (FALSE);
	if (objp->rl_status == NFS4_OK)
		return (xdr_b_utf8string(xdrs, (utf8string *)&objp->rl_link));
	return (TRUE);
}
/*
 * 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.
 *
 * Simple nfs V4 ops
 */

#include <rpc/types.h>
#include <rpc/auth.h>
#include <sys/t_lock.h>
#include "clnt.h"
#include <sys/fcntl.h>
#include <sys/vfs.h>
#include <errno.h>
#include <sys/promif.h>
#include <rpc/xdr.h>
#include "nfs_inet.h"
#include <sys/stat.h>
#include <sys/bootvfs.h>
#include <sys/bootdebug.h>
#include <sys/salib.h>
#include <sys/sacache.h>
#include <rpc/rpc.h>
#include "brpc.h"
#include <rpcsvc/nfs4_prot.h>

#define	dprintf	if (boothowto & RB_DEBUG) printf

static struct timeval zero_timeout = {0, 0};	/* default */

/*
 * NFS Version 4 specific functions
 */

ssize_t
nfs4read(struct nfs_file *filep, char *buf, size_t size)
{
	enum clnt_stat	status;
	read4arg_t	readargs;
	read4res_t	readres;
	char		*buf_offset;
	uint_t		count = 0;
	uint_t		readcnt = 0;
	bool_t		done = FALSE;
	struct timeval	timeout;
	int		framing_errs = 0;
	static uint_t	pos;
	static char	ind[] = "|/-\\";
	static int	blks_read;
	utf8string	str;
	char		tagname[] = "inetboot read";

	bzero(&readres, sizeof (readres));

	str.utf8string_len = sizeof (tagname) - 1;
	str.utf8string_val = tagname;

	/*
	 * read
	 */
	buf_offset = buf;

	if (nfs_readsize == 0)
		nfs_readsize = READ4_SIZE;

	if (size < nfs_readsize)
		readargs.r_count = size;
	else
		readargs.r_count = nfs_readsize;

	if (filep->fh.fh4.len > 0)
		compound_init(&readargs.r_arg, &str, 0, 2, &filep->fh.fh4);
	else
		compound_init(&readargs.r_arg, &str, 0, 2, NULL);

	readargs.r_opread = OP_READ;
	/*
	 * zero out the stateid field
	 */
	bzero(&readargs.r_stateid, sizeof (readargs.r_stateid));
	readargs.r_offset = filep->offset;

	do {
		readres.r_data_val = buf_offset;

		if ((count + readargs.r_count) > size)
			readargs.r_count = size - count;

		timeout.tv_sec = NFS_REXMIT_MIN;
		timeout.tv_usec = 0;

		do {
			status = CLNT_CALL(root_CLIENT, NFSPROC4_COMPOUND,
			    xdr_read4_args, (caddr_t)&readargs,
			    xdr_read4_res, (caddr_t)&readres,
			    timeout);

			if (status == RPC_TIMEDOUT) {
				dprintf("NFS read(%d) timed out. Retrying...\n",
				    readargs.r_count);
				if (errno == ETIMEDOUT)
					framing_errs++;

				if (framing_errs > NFS_MAX_FERRS &&
				    readargs.r_count > NFS_READ_DECR) {
					readargs.r_count /= 2;
					nfs_readsize /= 2;
					dprintf("NFS read size now %d.\n",
					    nfs_readsize);
					timeout.tv_sec = NFS_REXMIT_MIN;
					framing_errs = 0;
				} else {
					if (timeout.tv_sec < NFS_REXMIT_MAX)
						timeout.tv_sec++;
					else
						timeout.tv_sec = 0;
				}
			}
		} while (status == RPC_TIMEDOUT);

		if (status != RPC_SUCCESS)
			return (-1);

		if (readres.r_status != NFS4_OK) {
			nfs4_error(readres.r_status);
			return (-1);
		}

		readcnt = readres.r_data_len;

		if (readres.r_eof == TRUE)
			done = TRUE;

		if (readcnt < readargs.r_count) {
#ifdef NFS_OPS_DEBUG
			if ((boothowto & DBFLAGS) == DBFLAGS)
				printf("nfs4read: partial read %d instead "
				"of %d\n", readcnt, readargs.count);
#endif
			done = TRUE;
		}

		count += readcnt;
		filep->offset += readcnt;
		buf_offset += readcnt;
		readargs.r_offset += readcnt;
		if ((blks_read++ & 0x3) == 0)
			printf("%c\b", ind[pos++ & 3]);
	} while (count < size && !done);

	return (count);
}


static vtype_t nf4_to_vt[] = {
	VBAD, VREG, VDIR, VBLK, VCHR, VLNK, VSOCK, VFIFO
};

int
nfs4getattr(struct nfs_file *nfp, struct vattr *vap)
{
	enum clnt_stat	status;
	attr4_bitmap1_t bitmap1;
	attr4_bitmap2_t bitmap2;
	getattr4arg_t	getattrargs;
	getattr4res_t	getattrres;
	b_fattr4_t	*bfattr4;
	utf8string	str;
	char		tagname[] = "inetboot getattr";

	bzero(&getattrres, sizeof (getattrres));
	/*
	 * Putfh
	 */
	str.utf8string_len = sizeof (tagname) - 1;
	str.utf8string_val = tagname;

	if (nfp->fh.fh4.len > 0)
		compound_init(&getattrargs.ga_arg, &str, 0, 2, &nfp->fh.fh4);
	else
		compound_init(&getattrargs.ga_arg, &str, 0, 2, NULL);

	/*
	 * getattr
	 */
	getattrargs.ga_opgetattr = OP_GETATTR;
	/*
	 * Set up the attribute bitmap.  We pretty much need everything
	 * except for the filehandle and supported attrs.
	 */
	bitmap1.word = 0;
	bitmap1.bm_fattr4_type = 1;
	bitmap1.bm_fattr4_size = 1;
	bitmap1.bm_fattr4_fileid = 1;
	bitmap2.word = 0;
	bitmap2.bm_fattr4_mode = 1;
	bitmap2.bm_fattr4_time_access = 1;
	bitmap2.bm_fattr4_time_metadata = 1;
	bitmap2.bm_fattr4_time_modify = 1;

	getattrargs.ga_attr_req.b_bitmap_len = NFS4_MAX_BITWORDS;
	getattrargs.ga_attr_req.b_bitmap_val[0] = bitmap1.word;
	getattrargs.ga_attr_req.b_bitmap_val[1] = bitmap2.word;

	status = CLNT_CALL(root_CLIENT, NFSPROC4_COMPOUND, xdr_getattr4_args,
	    (caddr_t)&getattrargs, xdr_getattr4_res,
	    (caddr_t)&getattrres, zero_timeout);

	if (status != RPC_SUCCESS) {
		dprintf("nfs4getattr: RPC error %d\n", status);
		return (-1);
	}

	if (getattrres.gr_attr_status != NFS4_OK) {
		nfs4_error(getattrres.gr_attr_status);
		return (getattrres.gr_attr_status);
	}

	bfattr4 = &getattrres.gr_attrs;
	if (vap->va_mask & AT_TYPE) {
		if (bfattr4->b_fattr4_type < NF4REG ||
		    bfattr4->b_fattr4_type > NF4FIFO)
			vap->va_type = VBAD;
		else
			vap->va_type = nf4_to_vt[bfattr4->b_fattr4_type];
	}
	if (vap->va_mask & AT_MODE)
		vap->va_mode = (mode_t)bfattr4->b_fattr4_mode;
	if (vap->va_mask & AT_SIZE)
		vap->va_size = (u_offset_t)bfattr4->b_fattr4_size;
	if (vap->va_mask & AT_NODEID)
		vap->va_nodeid = (uint64_t)bfattr4->b_fattr4_fileid;
	/*
	 * XXX - may need to do something more here.
	 */
	if (vap->va_mask & AT_ATIME) {
		vap->va_atime.tv_sec = bfattr4->b_fattr4_time_access.seconds;
		vap->va_atime.tv_nsec = bfattr4->b_fattr4_time_access.nseconds;
	}
	if (vap->va_mask & AT_CTIME) {
		vap->va_ctime.tv_sec = bfattr4->b_fattr4_time_metadata.seconds;
		vap->va_ctime.tv_nsec =
		    bfattr4->b_fattr4_time_metadata.nseconds;
	}
	if (vap->va_mask & AT_MTIME) {
		vap->va_mtime.tv_sec = bfattr4->b_fattr4_time_modify.seconds;
		vap->va_mtime.tv_nsec = bfattr4->b_fattr4_time_modify.nseconds;
	}

	return (NFS4_OK);
}

/*
 * Display nfs error messages.
 */
/*ARGSUSED*/
void
nfs4_error(enum nfsstat4 status)
{
	if (!(boothowto & RB_DEBUG))
		return;

	switch (status) {
	case NFS4_OK:
		printf("NFS: No error.\n");
		break;
	case NFS4ERR_PERM:
		printf("NFS: Not owner.\n");
		break;
	case NFS4ERR_NOENT:
#ifdef	NFS_OPS_DEBUG
		printf("NFS: No such file or directory.\n");
#endif	/* NFS_OPS_DEBUG */
		break;
	case NFS4ERR_IO:
		printf("NFS: IO ERROR occurred on NFS server.\n");
		break;
	case NFS4ERR_NXIO:
		printf("NFS: No such device or address.\n");
		break;
	case NFS4ERR_ACCESS:
		printf("NFS: Permission denied.\n");
		break;
	case NFS4ERR_EXIST:
		printf("NFS: File exists.\n");
		break;
	case NFS4ERR_XDEV:
		printf("NFS: Cross device hard link.\n");
		break;
	case NFS4ERR_NOTDIR:
		printf("NFS: Not a directory.\n");
		break;
	case NFS4ERR_ISDIR:
		printf("NFS: Is a directory.\n");
		break;
	case NFS4ERR_INVAL:
		printf("NFS: Invalid argument.\n");
		break;
	case NFS4ERR_FBIG:
		printf("NFS: File too large.\n");
		break;
	case NFS4ERR_NOSPC:
		printf("NFS: No space left on device.\n");
		break;
	case NFS4ERR_ROFS:
		printf("NFS: Read-only filesystem.\n");
		break;
	case NFS4ERR_MLINK:
		printf("NFS: Too many hard links.\n");
		break;
	case NFS4ERR_NAMETOOLONG:
		printf("NFS: File name too long.\n");
		break;
	case NFS4ERR_NOTEMPTY:
		printf("NFS: Directory not empty.\n");
		break;
	case NFS4ERR_DQUOT:
		printf("NFS: Disk quota exceeded.\n");
		break;
	case NFS4ERR_STALE:
		printf("NFS: Stale file handle.\n");
		break;
	case NFS4ERR_BADHANDLE:
		printf("NFS: Illegal NFS file handle.\n");
		break;
	case NFS4ERR_BAD_COOKIE:
		printf("NFS: Stale Cookie.\n");
		break;
	case NFS4ERR_NOTSUPP:
		printf("NFS: Operation is not supported.\n");
		break;
	case NFS4ERR_TOOSMALL:
		printf("NFS: Buffer too small.\n");
		break;
	case NFS4ERR_SERVERFAULT:
		printf("NFS: Server fault.\n");
		break;
	case NFS4ERR_BADTYPE:
		printf("NFS: Unsupported object type.\n");
		break;
	case NFS4ERR_BAD_STATEID:
		printf("NFS: Bad stateid\n");
		break;
	case NFS4ERR_BAD_SEQID:
		printf("NFS: Bad seqid\n");
		break;
	default:
		printf("NFS: unknown error.\n");
		break;
	}
}

/*
 * lookup one component.  for multicomponent lookup use a driver like lookup().
 */
struct nfs_file *
nfs4lookup(struct nfs_file *dir, char *name, int *nstat)
{
	static struct nfs_file	cd;
	attr4_bitmap1_t		bitmap1;
	lookup4arg_t		lookupargs;
	lookup4res_t		lookupres;
	enum clnt_stat		status;
	utf8string		str;
	char			tagname[] = "inetboot lookup";

	/*
	 * NFSv4 uses a special LOOKUPP op
	 * for looking up the parent directory.
	 */
	if (strcmp(name, "..") == 0)
		return (nfs4lookupp(dir, nstat, NULL));

	*nstat = (int)NFS4_OK;

	bzero(&lookupres, sizeof (lookupres));

	/*
	 * Check if we have a filehandle and initialize the compound
	 * with putfh or putrootfh appropriately.
	 */
	str.utf8string_len = sizeof (tagname) - 1;
	str.utf8string_val = tagname;

	if (dir->fh.fh4.len > 0)
		compound_init(&lookupargs.la_arg, &str, 0, 3, &dir->fh.fh4);
	else
		compound_init(&lookupargs.la_arg, &str, 0, 3, NULL);

	/*
	 * lookup
	 */
	lookupargs.la_oplookup = OP_LOOKUP;
	/*
	 * convert the pathname from char * to utf8string
	 */
	lookupargs.la_pathname.utf8string_len = strlen(name);
	lookupargs.la_pathname.utf8string_val =
	    bkmem_alloc(lookupargs.la_pathname.utf8string_len);
	if (lookupargs.la_pathname.utf8string_val == NULL) {
		dprintf("nfs4lookup: bkmem_alloc failed\n");
		return (NULL);
	}
	bcopy(name, lookupargs.la_pathname.utf8string_val,
	    lookupargs.la_pathname.utf8string_len);

	/*
	 * Setup the attr bitmap.  All we need is the type and filehandle info
	 */
	lookupargs.la_opgetattr = OP_GETATTR;
	bitmap1.word = 0;
	bitmap1.bm_fattr4_type = 1;
	bitmap1.bm_fattr4_filehandle = 1;
	lookupargs.la_attr_req.b_bitmap_len = 1;
	lookupargs.la_attr_req.b_bitmap_val[0] = bitmap1.word;
	lookupargs.la_attr_req.b_bitmap_val[1] = 0;

	status = CLNT_CALL(root_CLIENT, NFSPROC4_COMPOUND, xdr_lookup4_args,
	    (caddr_t)&lookupargs, xdr_lookup4_res,
	    (caddr_t)&lookupres, zero_timeout);

	if (status != RPC_SUCCESS) {
		dprintf("nfs4lookup: RPC error. status %d\n", status);
		return (NULL);
	}

	if (lookupres.lr_lookup_status != NFS4_OK) {
#ifdef DEBUG
		dprintf("nfs4lookup: lookup status = %d\n",
		    lookupres.lr_lookup_status);
#endif
		nfs4_error(lookupres.lr_lookup_status);
		*nstat = (int)lookupres.lr_lookup_status;
		if (lookupargs.la_pathname.utf8string_val != NULL)
			bkmem_free(lookupargs.la_pathname.utf8string_val,
			    lookupargs.la_pathname.utf8string_len);
		return (NULL);
	}

	if (lookupres.lr_attr_status != NFS4_OK) {
#ifdef DEBUG
		dprintf("nfs4lookup: getattr status = %d\n",
		    lookupres.lr_attr_status);
#endif
		nfs4_error(lookupres.lr_attr_status);
		*nstat = (int)lookupres.lr_attr_status;
		if (lookupargs.la_pathname.utf8string_val != NULL)
			bkmem_free(lookupargs.la_pathname.utf8string_val,
			    lookupargs.la_pathname.utf8string_len);
		return (NULL);
	}

	/*
	 * We have all the information we need to update the file pointer
	 */
	bzero((caddr_t)&cd, sizeof (struct nfs_file));
	cd.version = NFS_V4;
	cd.ftype.type4 = lookupres.lr_attrs.b_fattr4_type;
	cd.fh.fh4.len = lookupres.lr_attrs.b_fattr4_filehandle.len;
	bcopy(lookupres.lr_attrs.b_fattr4_filehandle.data, cd.fh.fh4.data,
	    cd.fh.fh4.len);

	/*
	 * Free the arg string
	 */
	if (lookupargs.la_pathname.utf8string_val != NULL)
		bkmem_free(lookupargs.la_pathname.utf8string_val,
		    lookupargs.la_pathname.utf8string_len);

	return (&cd);
}

/*
 * lookup parent directory.
 */
struct nfs_file *
nfs4lookupp(struct nfs_file *dir, int *nstat, uint64_t *fileid)
{
	static struct nfs_file	cd;
	attr4_bitmap1_t		bitmap1;
	lookupp4arg_t		lookuppargs;
	lookup4res_t		lookupres;
	enum clnt_stat		status;
	utf8string		str;
	char			tagname[] = "inetboot lookupp";

	*nstat = (int)NFS4_OK;

	bzero(&lookupres, sizeof (lookupres));

	/*
	 * Check if we have a filehandle and initialize the compound
	 * with putfh or putrootfh appropriately.
	 */
	str.utf8string_len = sizeof (tagname) - 1;
	str.utf8string_val = tagname;

	if (dir->fh.fh4.len > 0)
		compound_init(&lookuppargs.la_arg, &str, 0, 3, &dir->fh.fh4);
	else
		compound_init(&lookuppargs.la_arg, &str, 0, 3, NULL);

	/*
	 * lookupp
	 */
	lookuppargs.la_oplookupp = OP_LOOKUPP;
	/*
	 * Setup the attr bitmap.  Normally, all we need is the type and
	 * filehandle info, but getdents might require the fileid of the
	 * parent.
	 */
	lookuppargs.la_opgetattr = OP_GETATTR;
	bitmap1.word = 0;
	bitmap1.bm_fattr4_type = 1;
	bitmap1.bm_fattr4_filehandle = 1;
	if (fileid != NULL)
		bitmap1.bm_fattr4_fileid = 1;
	lookuppargs.la_attr_req.b_bitmap_len = 1;
	lookuppargs.la_attr_req.b_bitmap_val[0] = bitmap1.word;
	lookuppargs.la_attr_req.b_bitmap_val[1] = 0;

	status = CLNT_CALL(root_CLIENT, NFSPROC4_COMPOUND, xdr_lookupp4_args,
	    (caddr_t)&lookuppargs, xdr_lookup4_res,
	    (caddr_t)&lookupres, zero_timeout);

	if (status != RPC_SUCCESS) {
		dprintf("nfs4lookupp: RPC error. status %d\n", status);
		return (NULL);
	}

	if (lookupres.lr_lookup_status != NFS4_OK) {
#ifdef DEBUG
		dprintf("nfs4lookupp: lookupp status = %d\n",
		    lookupres.lr_lookup_status);
#endif
		nfs4_error(lookupres.lr_lookup_status);
		*nstat = (int)lookupres.lr_lookup_status;
		return (NULL);
	}

	if (lookupres.lr_attr_status != NFS4_OK) {
#ifdef DEBUG
		dprintf("nfs4lookupp: getattr status = %d\n",
		    lookupres.lr_attr_status);
#endif
		nfs4_error(lookupres.lr_attr_status);
		*nstat = (int)lookupres.lr_attr_status;
		return (NULL);
	}

	/*
	 * We have all the information we need to update the file pointer
	 */
	bzero((caddr_t)&cd, sizeof (struct nfs_file));
	cd.version = NFS_V4;
	cd.ftype.type4 = lookupres.lr_attrs.b_fattr4_type;
	cd.fh.fh4.len = lookupres.lr_attrs.b_fattr4_filehandle.len;
	bcopy(lookupres.lr_attrs.b_fattr4_filehandle.data, cd.fh.fh4.data,
	    cd.fh.fh4.len);

	/*
	 * Fill in the fileid if the user passed in one
	 */
	if (fileid != NULL)
		*fileid = lookupres.lr_attrs.b_fattr4_fileid;

	return (&cd);
}

/*
 * Gets symbolic link into pathname.
 */
int
nfs4getsymlink(struct nfs_file *cfile, char **path)
{
	enum clnt_stat	status;
	readlink4arg_t	readlinkargs;
	readlink4res_t	readlinkres;
	static char	symlink_path[NFS_MAXPATHLEN];
	int		spathlen;
	utf8string	str;
	char		tagname[] = "inetboot getsymlink";
	int		error = NFS4_OK;

	bzero(&readlinkres, sizeof (readlinkres));

	/*
	 * readlink
	 */
	str.utf8string_len = sizeof (tagname) - 1;
	str.utf8string_val = tagname;

	if (cfile->fh.fh4.len > 0)
		compound_init(&readlinkargs.rl_arg, &str, 0, 2,
		    &cfile->fh.fh4);
	else
		compound_init(&readlinkargs.rl_arg, &str, 0, 2,	NULL);

	readlinkargs.rl_opreadlink = OP_READLINK;
	status = CLNT_CALL(root_CLIENT, NFSPROC4_COMPOUND, xdr_readlink4_args,
	    (caddr_t)&readlinkargs, xdr_readlink4_res,
	    (caddr_t)&readlinkres, zero_timeout);

	if (status != RPC_SUCCESS) {
		dprintf("nfs4getsymlink: RPC readlink error %d\n", status);
		error = -1;
		goto out;
	}

	if (readlinkres.rl_status != NFS4_OK) {
		nfs4_error(readlinkres.rl_status);
		error = readlinkres.rl_status;
		goto out;
	}

	/*
	 * Convert the utf8string to a normal character string
	 */
	spathlen = readlinkres.rl_link.utf8string_len;
	if (spathlen <= 0 || readlinkres.rl_link.utf8string_val == NULL) {
		*path = NULL;
		error = readlinkres.rl_status;
		goto out;
	}

	bcopy(readlinkres.rl_link.utf8string_val, symlink_path, spathlen);
	symlink_path[spathlen] = '\0';
	*path = symlink_path;

out:
	/*
	 * Free the results
	 */
	if (readlinkres.rl_link.utf8string_val != NULL)
		bkmem_free(readlinkres.rl_link.utf8string_val, spathlen);

	return (error);
}

/*
 * Should just forget about the tag, but will leave in support for the time
 * being.
 */
void
compound_init(b_compound_t *cp, utf8string *str, uint_t mvers, uint_t arglen,
		struct nfs_bfh4 *pfh)
{
	if (str == NULL || str->utf8string_len == 0) {
		cp->ca_tag.utf8string_len = 0;
		cp->ca_tag.utf8string_val = NULL;
	} else {
		cp->ca_tag.utf8string_len = str->utf8string_len;
		cp->ca_tag.utf8string_val = str->utf8string_val;
	}
	cp->ca_minorversion = mvers;
	cp->ca_argarray_len = arglen;
	if (pfh == NULL) {
		cp->ca_isputrootfh = TRUE;
		cp->ca_opputfh.pf_opnum = OP_PUTROOTFH;
	} else {
		cp->ca_isputrootfh = FALSE;
		cp->ca_opputfh.pf_opnum = OP_PUTFH;
		cp->ca_opputfh.pf_filehandle.len = pfh->len;
		bcopy(pfh->data, cp->ca_opputfh.pf_filehandle.data, pfh->len);
	}
}
/*
 * 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 2004 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 *
 * nfs_inet.h contains definitions specific to inetboot's nfs implementation.
 */

#ifndef _NFS_INET_H
#define	_NFS_INET_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#ifdef	__cplusplus
extern "C" {
#endif

#include <netinet/in.h>
#include <sys/socket.h>
#include <net/if.h>
#include <netinet/if_ether.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/udp.h>
#include <sys/saio.h>
#include <rpcsvc/nfs_prot.h>
#include <rpcsvc/nfs4_prot.h>
#include "clnt.h"
#include <sys/vfs.h>
#include <sys/dirent.h>

#define	NFSBUF_SIZE	(READ_SIZE+1024)
#define	READ_SIZE	(8192)	/* NFS readsize */
#define	NFS_READ_DECR	(1024)	/* NFS readsize decrement */
#define	NFS3BUF_SIZE	(READ3_SIZE+1024)
#define	READ3_SIZE	(32 * 1024)	/* NFS3 readsize */
#define	NFS4BUF_SIZE	(READ4_SIZE+1024)
#define	READ4_SIZE	(32 * 1024)	/* NFS4 readsize */
#define	NFS4_MAX_UTF8STRING	(8 * 1024)
#define	NFS4_MAX_BITWORDS	(2)
#define	NFS_MAX_FERRS	(3)	/* MAX frame errors before decr read size */
#define	NFS_REXMIT_MIN	(3)	/* NFS retry min in secs */
#define	NFS_REXMIT_MAX	(15)	/* NFS retry max in secs */

extern int nfs_readsize;
extern struct nfs_file roothandle;
extern CLIENT *root_CLIENT;

/*
 * Boot specific V4 fh with maximum allowed data statically allocated
 */
struct nfs_bfh4 {
	uint_t len;
	char data[NFS4_FHSIZE];
};

/*
 * Boot specific V3 fh with maximum allowed data statically allocated
 */
struct nfs_bfh3 {
	uint_t len;
	char data[NFS3_FHSIZE];
};

union _nfs_fh {
	nfs_fh fh2;
	struct nfs_bfh3 fh3;
	struct nfs_bfh4 fh4;
};

union _nfs_cookie {
	nfscookie cookie2;
	cookie3 cookie3;
	nfs_cookie4 cookie4;
};

union _nfs_ftype {
	ftype type2;
	ftype3 type3;
	nfs_ftype4 type4;
};

/*
 * NFS: This structure represents the current open file.
 */
struct nfs_file {
	int version;
	ulong_t offset;
	union _nfs_ftype ftype;
	union _nfs_fh fh;
	union _nfs_cookie cookie;
};

struct nfs_fid {
	ushort_t nf_len;
	ushort_t nf_pad;
	struct nfs_fh fh;
};

#define	cfile_is_dir(cf)    (((cf)->version == NFS_VERSION) ?	\
				((cf)->ftype.type2 == NFDIR) :	\
				(((cf)->version == NFS_V3) ?	\
				((cf)->ftype.type3 == NF3DIR) : \
				(((cf)->version == NFS_V4) ?	\
				((cf)->ftype.type4 == NF4DIR) : 0)))

#define	cfile_is_lnk(cf)    (((cf)->version == NFS_VERSION) ?	\
				((cf)->ftype.type2 == NFLNK) :	\
				(((cf)->version == NFS_V3) ?	\
				((cf)->ftype.type3 == NF3LNK) : \
				(((cf)->version == NFS_V4) ?	\
				((cf)->ftype.type4 == NF4LNK) : 0)))

/*
 * Predefine an attribute bitmap that inetboot will most likely be
 * interested in.
 */
typedef union attr4_bitmap1_u {
	struct {
		unsigned int
#ifdef _BIT_FIELDS_HTOL
		b_pad4:			11,
		b_fattr4_fileid:	1,
		b_fattr4_filehandle:	1,
		b_pad3:			10,
		b_fattr4_fsid:		1,
		b_pad2:			3,
		b_fattr4_size:		1,
		b_pad1:			2,
		b_fattr4_type:		1,
		b_supported_attrs:	1;
#endif
#ifdef _BIT_FIELDS_LTOH
		b_supported_attrs:	1,
		b_fattr4_type:		1,
		b_pad1:			2,
		b_fattr4_size:		1,
		b_pad2:			3,
		b_fattr4_fsid:		1,
		b_pad3:			10,
		b_fattr4_filehandle:	1,
		b_fattr4_fileid:	1,
		b_pad4:			11;
#endif
	} bitmap_s;
	uint_t word;
} attr4_bitmap1_t;

#define	bm_supported_attrs	bitmap_s.b_supported_attrs
#define	bm_fattr4_type		bitmap_s.b_fattr4_type
#define	bm_fattr4_size		bitmap_s.b_fattr4_size
#define	bm_fattr4_fsid		bitmap_s.b_fattr4_fsid
#define	bm_fattr4_fileid	bitmap_s.b_fattr4_fileid
#define	bm_fattr4_filehandle	bitmap_s.b_fattr4_filehandle

typedef	union attr4_bitmap2_u {
	struct {
		unsigned int
#ifdef _BIT_FIELDS_HTOL
		b_pad4:			10,
		b_fattr4_time_modify:	1,
		b_fattr4_time_metadata:	1,
		b_pad3:			4,
		b_fattr4_time_access:	1,
		b_pad2:			13,
		b_fattr4_mode:		1,
		b_pad1:			1;
#endif
#ifdef _BIT_FIELDS_LTOH
		b_pad1:			1,
		b_fattr4_mode:		1,
		b_pad2:			13,
		b_fattr4_time_access:	1,
		b_pad3:			4,
		b_fattr4_time_metadata:	1,
		b_fattr4_time_modify:	1,
		b_pad4:			10;
#endif
	} bitmap_s;
	uint_t word;
} attr4_bitmap2_t;

#define	bm_fattr4_mode		bitmap_s.b_fattr4_mode
#define	bm_fattr4_time_access	bitmap_s.b_fattr4_time_access
#define	bm_fattr4_time_metadata	bitmap_s.b_fattr4_time_metadata
#define	bm_fattr4_time_modify	bitmap_s.b_fattr4_time_modify

typedef struct b_bitmap4 {
	uint_t b_bitmap_len;
	uint_t b_bitmap_val[NFS4_MAX_BITWORDS];
} b_bitmap4_t;

/*
 * Define a usable set of v4 atttributes for inetboot.
 */
typedef struct b_fattr4_s {
	b_bitmap4_t	b_supported_attrs;
	nfs_ftype4	b_fattr4_type;
	uint64_t	b_fattr4_size;
	fsid4		b_fattr4_fsid;
	struct nfs_bfh4	b_fattr4_filehandle;
	uint64_t	b_fattr4_fileid;
	mode4		b_fattr4_mode;
	nfstime4	b_fattr4_time_access;
	nfstime4	b_fattr4_time_metadata;
	nfstime4	b_fattr4_time_modify;
} b_fattr4_t;

/*
 * common to putfh and putfhroot.
 */
typedef struct putfh4arg_s {
	uint_t		pf_opnum;	/* can either be putfh or putrootfh */
	struct nfs_bfh4	pf_filehandle;	/* only used by putfh */
} putfh4arg_t;

/*
 * Use this struct to construct our OTW compound procedures.  Layout makes for
 * easy XDR'ing. Include putfh.
 */
typedef union compound_u {
	struct {
		utf8string	tag;
		uint_t		minorversion;	/* 0 */
		uint_t		argarray_len;	/* 1 + n for putfh */
		bool_t		isputrootfh;	/* flag */
		putfh4arg_t	opputfh;	/* putfh args */
	} compound_ua_s;
	struct {
		nfsstat4	status;		/* status of last op */
		utf8string	tag;
		uint_t		resarray_len;	/* 1 + n for putfh */
		uint_t		opputfh;	/* putfh opnum */
		nfsstat4	putfh_status;	/* putfh status */
	} compound_ur_s;
} b_compound_t;

/*
 * Define some macros for easy access into the compound structrue
 */
#define	ca_tag compound_ua_s.tag
#define	ca_minorversion compound_ua_s.minorversion
#define	ca_argarray_len compound_ua_s.argarray_len
#define	ca_isputrootfh compound_ua_s.isputrootfh
#define	ca_opputfh compound_ua_s.opputfh

#define	cr_status compound_ur_s.status
#define	cr_tag compound_ur_s.tag
#define	cr_resarray_len compound_ur_s.resarray_len
#define	cr_opputfh compound_ur_s.opputfh
#define	cr_putfh_status compound_ur_s.putfh_status
/*
 * Define simple compound structs that include op specific data
 */
typedef struct getattrres_cmn {
	uint_t		gc_opgetattr;		/* getattr opnum */
	nfsstat4	gc_attr_status;		/* getattr result */
	b_bitmap4_t	gc_retattr;		/* getattr result */
	uint_t		gc_attrlist_len;	/* getattr result */
	b_fattr4_t	gc_attrs;		/* getattr result */
} getattrres_cmn_t;

/*
 * getattr: putfh/getattr
 */
typedef struct getattr4arg_s {
	b_compound_t	ga_arg;		/* compound + putfh */
	uint_t		ga_opgetattr;	/* getattr opnum */
	b_bitmap4_t	ga_attr_req;	/* getattr arg */
} getattr4arg_t;

typedef struct getattr4res_s {
	b_compound_t		gr_res;	/* compound + putfh */
	getattrres_cmn_t	gr_cmn;
} getattr4res_t;

#define	gr_opgetattr gr_cmn.gc_opgetattr
#define	gr_attr_status gr_cmn.gc_attr_status
#define	gr_retattr gr_cmn.gc_retattr
#define	gr_attrs gr_cmn.gc_attrs

/*
 * lookup: putfh/lookup/getattr
 */
typedef struct lookup4arg_s {
	b_compound_t	la_arg;		/* compound + putfh */
	uint_t		la_oplookup;	/* lookup opnum */
	component4	la_pathname;	/* lookup arg */
	uint_t		la_opgetattr;	/* getattr opnum */
	b_bitmap4_t	la_attr_req;	/* getattr arg */
} lookup4arg_t;

typedef struct lookup4res_s {
	b_compound_t		lr_res;		/* compound + putfh */
	uint_t			lr_oplookup;	/* lookup opnum */
	nfsstat4		lr_lookup_status;	/* lookup result */
	getattrres_cmn_t	lr_gcmn;	/* getattr result */
} lookup4res_t;

#define	lr_opgetattr lr_gcmn.gc_opgetattr
#define	lr_attr_status lr_gcmn.gc_attr_status
#define	lr_retattr lr_gcmn.gc_retattr
#define	lr_attrs lr_gcmn.gc_attrs

/*
 * lookupp: putfh/lookupp/getattr
 *
 * For results: use the lookup4res_t
 */
typedef struct lookupp4arg_s {
	b_compound_t	la_arg;		/* compound + putfh */
	uint_t		la_oplookupp;	/* lookupp opnum */
	uint_t		la_opgetattr;	/* lookupp arg */
	b_bitmap4_t	la_attr_req;	/* lookupp arg */
} lookupp4arg_t;

/*
 * read: putfh/read
 */
typedef struct read4arg_s {
	b_compound_t	r_arg;		/* compound + putfh */
	uint_t		r_opread;	/* read opnum */
	stateid4	r_stateid;	/* read arg */
	offset4		r_offset;	/* read arg */
	count4		r_count;	/* read arg */
} read4arg_t;

typedef struct read4res_s {
	b_compound_t	r_res;		/* compound + putfh */
	uint_t		r_opread;	/* read opnum */
	nfsstat4	r_status;	/* read result */
	bool_t		r_eof;		/* read result */
	uint_t		r_data_len;	/* read result */
	char		*r_data_val;	/* read result */
} read4res_t;

typedef struct b_entry4_s {
	nfs_cookie4		b_cookie;
	utf8string		b_name;
	uint64_t		b_fileid;
	struct b_entry4_s	*b_nextentry;
} b_entry4_t;

/*
 * readdir: putfh/readdir/getattr
 */
typedef struct readdir4arg_s {
	b_compound_t	rd_arg;		/* compoud + putfh */
	uint_t		rd_opreaddir;	/* readdir opnum */
	nfs_cookie4	rd_cookie;	/* readdir arg */
	verifier4	rd_cookieverf;	/* readdir arg */
	count4		rd_dircount;	/* readdir arg */
	count4		rd_maxcount;	/* readdir arg */
	b_bitmap4_t	rd_attr_req;	/* readdir arg */
} readdir4arg_t;

typedef struct readdir4res_s {
	b_compound_t	rd_res;		/* compound + putfh */
	uint_t		rd_opreaddir;	/* readdir opnum */
	nfsstat4	rd_status;	/* readdir result */
	verifier4	rd_cookieverf;	/* readdir result */
	b_entry4_t	*rd_entries;	/* readdir result */
	bool_t		rd_eof;		/* readdir result */
} readdir4res_t;

/*
 * readlink: putfh/readlink
 */
typedef struct readlink4arg_s {
	b_compound_t	rl_arg;		/* compound + putfh */
	uint_t		rl_opreadlink;	/* readlink opnum */
} readlink4arg_t;

typedef struct readlink4res_s {
	b_compound_t	rl_res;		/* compound + putfh */
	uint_t		rl_opreadlink;	/* readlink opnum */
	nfsstat4	rl_status;	/* readlink result */
	utf8string	rl_link;	/* readlink result */
} readlink4res_t;

/*
 * Generic NFS functions
 */
extern int	boot_nfs_mountroot(char *);
extern int	boot_nfs_unmountroot(void);
extern int	lookup(char *pathname, struct nfs_file *, bool_t);
extern bool_t	whoami(void);
extern bool_t	getfile(char *, char *, struct in_addr *, char *);

/*
 * NFS Version 2 specific functions
 */
extern void	nfs_error(enum nfsstat);
extern ssize_t	nfsread(struct nfs_file *, char *, size_t);
extern int	nfsgetattr(struct nfs_file *, struct vattr *);
extern int	nfsgetdents(struct nfs_file *, struct dirent *, unsigned);
extern struct nfs_file *nfslookup(struct nfs_file *, char *, int *);
extern int nfsgetsymlink(struct nfs_file *cfile, char **path);

/*
 * NFS Version 3 specific functions
 */
extern void	nfs3_error(enum nfsstat3);
extern ssize_t	nfs3read(struct nfs_file *, char *, size_t);
extern int	nfs3getattr(struct nfs_file *, struct vattr *);
extern int	nfs3getdents(struct nfs_file *, struct dirent *, unsigned);
extern struct nfs_file *nfs3lookup(struct nfs_file *, char *, int *);
extern int	nfs3getsymlink(struct nfs_file *, char **);

/*
 * NFS Version 4 specific functions
 */
extern void	nfs4_error(enum nfsstat4);
extern ssize_t	nfs4read(struct nfs_file *, char *, size_t);
extern int	nfs4getattr(struct nfs_file *, struct vattr *);
extern int	nfs4_getdents(struct nfs_file *, struct dirent *, unsigned);
extern struct nfs_file *nfs4lookup(struct nfs_file *, char *, int *);
extern struct nfs_file *nfs4lookupp(struct nfs_file *, int *, uint64_t *);
extern int	nfs4getsymlink(struct nfs_file *, char **);
extern void	compound_init(b_compound_t *, utf8string *, uint_t, uint_t,
				struct nfs_bfh4 *);

/*
 * NFSv4 xdr ops
 */
extern bool_t	xdr_getattr4_args(XDR *, getattr4arg_t *);
extern bool_t	xdr_getattr4_res(XDR *, getattr4res_t *);
extern bool_t	xdr_lookup4_args(XDR *, lookup4arg_t *);
extern bool_t	xdr_lookup4_res(XDR *, lookup4res_t *);
extern bool_t	xdr_lookupp4_args(XDR *, lookupp4arg_t *);
extern bool_t	xdr_read4_args(XDR *, read4arg_t *);
extern bool_t	xdr_read4_res(XDR *, read4res_t *);
extern bool_t	xdr_readdir4_args(XDR *, readdir4arg_t *);
extern bool_t	xdr_readdir4_res(XDR *, readdir4res_t *);
extern bool_t	xdr_readlink4_args(XDR *, readlink4arg_t *);
extern bool_t	xdr_readlink4_res(XDR *, readlink4res_t *);

#ifdef	__cplusplus
}
#endif

#endif /* _NFS_INET_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 2004 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#include <rpc/types.h>
#include <rpc/xdr.h>
#include <rpc/rpc.h>
#include <rpcsvc/nfs_prot.h>

/*
 * XDR routines for NFS ops.
 */
static bool_t
xdr_b_nfsstat(XDR *xdrs, nfsstat *objp)
{
	return (xdr_enum(xdrs, (enum_t *)objp));
}

static bool_t
xdr_b_ftype(XDR *xdrs, ftype *objp)
{
	return (xdr_enum(xdrs, (enum_t *)objp));
}

bool_t
xdr_nfs_fh(XDR *xdrs, nfs_fh *objp)
{
	return (xdr_opaque(xdrs, objp->data, NFS_FHSIZE));
}

static bool_t
xdr_b_nfstime(XDR *xdrs, nfstime *objp)
{
	if (!xdr_u_int(xdrs, &objp->seconds)) {
		return (FALSE);
	}
	return (xdr_u_int(xdrs, &objp->useconds));
}

static bool_t
xdr_b_fattr(XDR *xdrs, fattr *objp)
{
	if (!xdr_b_ftype(xdrs, &objp->type)) {
		return (FALSE);
	}
	if (!xdr_u_int(xdrs, &objp->mode)) {
		return (FALSE);
	}
	if (!xdr_u_int(xdrs, &objp->nlink)) {
		return (FALSE);
	}
	if (!xdr_u_int(xdrs, &objp->uid)) {
		return (FALSE);
	}
	if (!xdr_u_int(xdrs, &objp->gid)) {
		return (FALSE);
	}
	if (!xdr_u_int(xdrs, &objp->size)) {
		return (FALSE);
	}
	if (!xdr_u_int(xdrs, &objp->blocksize)) {
		return (FALSE);
	}
	if (!xdr_u_int(xdrs, &objp->rdev)) {
		return (FALSE);
	}
	if (!xdr_u_int(xdrs, &objp->blocks)) {
		return (FALSE);
	}
	if (!xdr_u_int(xdrs, &objp->fsid)) {
		return (FALSE);
	}
	if (!xdr_u_int(xdrs, &objp->fileid)) {
		return (FALSE);
	}
	if (!xdr_b_nfstime(xdrs, &objp->atime)) {
		return (FALSE);
	}
	if (!xdr_b_nfstime(xdrs, &objp->mtime)) {
		return (FALSE);
	}
	return (xdr_b_nfstime(xdrs, &objp->ctime));
}

static bool_t
xdr_b_filename(XDR *xdrs, filename *objp)
{
	return (xdr_string(xdrs, objp, NFS_MAXNAMLEN));
}

static bool_t
xdr_b_nfspath(XDR *xdrs, nfspath *objp)
{
	return (xdr_string(xdrs, objp, NFS_MAXPATHLEN));
}

bool_t
xdr_attrstat(XDR *xdrs, attrstat *objp)
{
	if (!xdr_b_nfsstat(xdrs, &objp->status)) {
		return (FALSE);
	}
	if (objp->status == NFS_OK) {
		return (xdr_b_fattr(xdrs, &objp->attrstat_u.attributes));
	}
	return (TRUE);
}

bool_t
xdr_diropargs(XDR *xdrs, diropargs *objp)
{
	if (!xdr_nfs_fh(xdrs, &objp->dir)) {
		return (FALSE);
	}
	return (xdr_b_filename(xdrs, &objp->name));
}

static bool_t
xdr_b_diropokres(XDR *xdrs, diropokres *objp)
{
	if (!xdr_nfs_fh(xdrs, &objp->file)) {
		return (FALSE);
	}
	return (xdr_b_fattr(xdrs, &objp->attributes));
}

bool_t
xdr_diropres(XDR *xdrs, diropres *objp)
{
	if (!xdr_b_nfsstat(xdrs, &objp->status)) {
		return (FALSE);
	}
	if (objp->status == NFS_OK) {
		return (xdr_b_diropokres(xdrs, &objp->diropres_u.diropres));
	}
	return (TRUE);
}

bool_t
xdr_readlinkres(XDR *xdrs, readlinkres *objp)
{
	if (!xdr_b_nfsstat(xdrs, &objp->status)) {
		return (FALSE);
	}
	if (objp->status == NFS_OK) {
		return (xdr_b_nfspath(xdrs, &objp->readlinkres_u.data));
	}
	return (TRUE);
}

bool_t
xdr_readargs(XDR *xdrs, readargs *objp)
{
	if (!xdr_nfs_fh(xdrs, &objp->file)) {
		return (FALSE);
	}
	if (!xdr_u_int(xdrs, &objp->offset)) {
		return (FALSE);
	}
	if (!xdr_u_int(xdrs, &objp->count)) {
		return (FALSE);
	}
	return (xdr_u_int(xdrs, &objp->totalcount));
}

static bool_t
xdr_b_readokres(XDR *xdrs, readokres *objp)
{
	if (!xdr_b_fattr(xdrs, &objp->attributes)) {
		return (FALSE);
	}
	return (xdr_bytes(xdrs, (char **)&objp->data.data_val,
	    (uint_t *)&objp->data.data_len, NFS_MAXDATA));
}

bool_t
xdr_readres(XDR *xdrs, readres *objp)
{
	if (!xdr_b_nfsstat(xdrs, &objp->status)) {
		return (FALSE);
	}
	if (objp->status == NFS_OK) {
		return (xdr_b_readokres(xdrs, &objp->readres_u.reply));
	}
	return (TRUE);
}

static bool_t
xdr_b_nfscookie(XDR *xdrs, nfscookie objp)
{
	return (xdr_opaque(xdrs, objp, NFS_COOKIESIZE));
}

bool_t
xdr_readdirargs(XDR *xdrs, readdirargs *objp)
{
	if (!xdr_nfs_fh(xdrs, &objp->dir)) {
		return (FALSE);
	}
	if (!xdr_b_nfscookie(xdrs, objp->cookie)) {
		return (FALSE);
	}
	return (xdr_u_int(xdrs, &objp->count));
}

static bool_t
xdr_b_entry(XDR *xdrs, entry *objp)
{
	if (!xdr_u_int(xdrs, &objp->fileid)) {
		return (FALSE);
	}
	if (!xdr_b_filename(xdrs, &objp->name)) {
		return (FALSE);
	}
	if (!xdr_b_nfscookie(xdrs, objp->cookie)) {
		return (FALSE);
	}
	return (xdr_pointer(xdrs, (char **)&objp->nextentry, sizeof (entry),
						(xdrproc_t)xdr_b_entry));
}

static bool_t
xdr_b_dirlist(XDR *xdrs, dirlist *objp)
{
	if (!xdr_pointer(xdrs, (char **)&objp->entries, sizeof (entry),
	    (xdrproc_t)xdr_b_entry)) {
		return (FALSE);
	}
	return (xdr_bool(xdrs, &objp->eof));
}

bool_t
xdr_readdirres(XDR *xdrs, readdirres *objp)
{
	if (!xdr_b_nfsstat(xdrs, &objp->status)) {
		return (FALSE);
	}
	if (objp->status == NFS_OK) {
		return (xdr_b_dirlist(xdrs, &objp->readdirres_u.reply));
	}
	return (TRUE);
}
/*
 * 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.
 *
 * Simple nfs ops - open, close, read, and lseek.
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#include <rpc/types.h>
#include <rpc/auth.h>
#include <sys/t_lock.h>
#include "clnt.h"
#include <sys/fcntl.h>
#include <sys/vfs.h>
#include <errno.h>
#include <sys/promif.h>
#include <rpc/xdr.h>
#include "nfs_inet.h"
#include <sys/stat.h>
#include <sys/bootvfs.h>
#include <sys/bootdebug.h>
#include <sys/salib.h>
#include <sys/sacache.h>
#include <rpc/rpc.h>
#include "brpc.h"
#include <rpcsvc/nfs_prot.h>
#include "socket_inet.h"
#include "mac.h"
#include <sys/mode.h>

ushort_t vttoif_tab[] = {
	0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK, S_IFIFO,
	S_IFDOOR, 0, S_IFSOCK, 0
};

static int file_desc = 1;
static struct nfs_files {
	struct nfs_file file;
	int	desc;
	struct nfs_files *next;
} nfs_files[1] = {
	{0, 0, 0},
};

#define	dprintf	if (boothowto & RB_DEBUG) printf

static int	boot_nfs_open(char *filename, int flags);
static int	boot_nfs_close(int fd);
static ssize_t	boot_nfs_read(int fd, caddr_t buf, size_t size);
static off_t	boot_nfs_lseek(int, off_t, int);
static int	boot_nfs_fstat(int fd, struct bootstat *stp);
static void	boot_nfs_closeall(int flag);
static int	boot_nfs_getdents(int fd, struct dirent *dep, unsigned size);

struct boot_fs_ops boot_nfs_ops = {
	"nfs",
	boot_nfs_mountroot,
	boot_nfs_unmountroot,
	boot_nfs_open,
	boot_nfs_close,
	boot_nfs_read,
	boot_nfs_lseek,
	boot_nfs_fstat,
	boot_nfs_closeall,
	boot_nfs_getdents
};

/*
 * bootops.c calls a closeall() function to close all open files. Since
 * we only permit one open file at a time (not counting the device), this
 * is simple to implement.
 */

/*ARGSUSED*/
static void
boot_nfs_closeall(int flag)
{
	struct nfs_files	*filep;

#ifdef NFS_OPS_DEBUG
	if ((boothowto & DBFLAGS) == DBFLAGS)
		printf("boot_nfs_closeall(%x)\n", flag);
#endif

	if (nfs_files->file.version == 0 &&
	    nfs_files->desc == 0 &&
	    nfs_files->next == NULL)
		return;

	/* delete any dynamically allocated entries */
	while ((filep = nfs_files->next) != NULL) {
		nfs_files->next = filep->next;
		bkmem_free((caddr_t)filep, sizeof (struct  nfs_files));
	}

	/* clear the first, static file */
	bzero((caddr_t)nfs_files, sizeof (struct nfs_files));

	/* Close device */
	release_cache(mac_get_dev());

	mac_fini();
}

/*
 * Get a file pointer given a file descriptor.  Return 0 on error
 */
static struct nfs_files *
get_filep(int fd)
{
	struct nfs_files *filep;

	for (filep = nfs_files; filep; filep = filep->next) {
		if (fd == filep->desc)
			return (filep);
	}
	return (NULL);
}

/*
 * Unmount the root fs -- not supported for this fstype.
 */

int
boot_nfs_unmountroot(void)
{
	return (-1);
}

/*
 * open a file for reading. Note: writing is NOT supported.
 */

static int
boot_nfs_open(char *path, int flags)
{
	struct nfs_files *filep, *newfilep;
	int got_filep;

#ifdef NFS_OPS_DEBUG
	if ((boothowto & DBFLAGS) == DBFLAGS)
		printf("boot_nfs_open(%s, %x)\n", path, flags);
#endif

	/* file can only be opened readonly. */
	if (flags & ~O_RDONLY) {
		dprintf("boot_nfs_open: files can only be opened O_RDONLY.\n");
		return (-1);
	}

	if (path == NULL || *path == '\0') {
		dprintf("boot_nfs_open: NULL or EMPTY pathname argument.\n");
		return (-1);
	}

	/* Try and find a vacant file pointer */
	filep = nfs_files;
	got_filep = FALSE;
	do {
		if (filep->desc == 0) {
			filep->desc = file_desc++;
			got_filep = TRUE;
			break;		/* We've got a file pointer */
		}
		/* Get next entry if not at end of list */
		if (filep->next)
			filep = filep->next;
	} while (filep->next);

	/* If a a vacant file pointer cannot be found, make one */
	if (!got_filep) {
		if ((newfilep = (struct nfs_files *)
		    bkmem_zalloc(sizeof (struct nfs_files))) == 0) {
			dprintf("open: Cannot allocate file pointer\n");
			return (-1);
		}
		filep->next = newfilep;
		filep = newfilep;
		filep->desc = file_desc++;
	}

	if (lookup(path, &filep->file, FALSE) != 0) {
#ifdef NFS_OPS_DEBUG
		if ((boothowto & DBFLAGS) == DBFLAGS)
			printf("boot_nfs_open(): Cannot open '%s'.\n", path);
#endif
		/* zero file pointer */
		bzero((caddr_t)filep, sizeof (struct nfs_file));
		filep->desc = 0;
		return (-1);
	}
	bzero(&filep->file.cookie, sizeof (filep->file.cookie));

#ifdef NFS_OPS_DEBUG
	if ((boothowto & DBFLAGS) == DBFLAGS)
		printf("boot_nfs_open(): '%s' successful, fd = 0x%x\n",
		    path, filep->desc);
#endif
	return (filep->desc);
}

/*
 * close a previously opened file.
 */
static int
boot_nfs_close(int fd)
{
	struct nfs_files *filep;

#ifdef NFS_OPS_DEBUG
	if ((boothowto & DBFLAGS) == DBFLAGS)
		printf("boot_nfs_close(%d)\n", fd);
#endif
	if ((filep = get_filep(fd)) == 0)
		return (0);

	/*
	 * zero file pointer
	 */
	bzero((caddr_t)&filep->file, sizeof (struct nfs_file));

	/*
	 * "close" the fd.
	 */
	filep->desc = 0;

	return (0);
}

/*
 * read from a file.
 */
static ssize_t
boot_nfs_read(int fd, char *buf, size_t size)
{
	struct nfs_files	*filep;
	int			count = 0;

	if (fd == 0) {
		dprintf("boot_nfs_read: Bad file number.\n");
		return (-1);
	}
	if (buf == NULL) {
		dprintf("boot_nfs_read: Bad address.\n");
		return (-1);
	}

#ifdef NFS_OPS_DEBUG
	if ((boothowto & DBFLAGS) == DBFLAGS)
		printf("boot_nfs_read(%d, %x, 0x%x)\n", fd, buf, size);
#endif

	/* initialize for read */
	if ((filep = get_filep(fd)) == 0)
		return (-1);

	switch (filep->file.version) {
	case NFS_VERSION:
		count = nfsread(&filep->file, buf, size);
		break;
	case NFS_V3:
		count = nfs3read(&filep->file, buf, size);
		break;
	case NFS_V4:
		count = nfs4read(&filep->file, buf, size);
		break;
	default:
		printf("boot_nfs_read: NFS Version %d not supported\n",
		    filep->file.version);
		count = -1;
		break;
	}

#ifdef NFS_OPS_DEBUG
	if ((boothowto & DBFLAGS) == DBFLAGS)
		printf("boot_nfs_read(): 0x%x bytes.\n", count);
#endif
	return (count);
}

/*
 * lseek - move read file pointer.
 */

static off_t
boot_nfs_lseek(int fd, off_t offset, int whence)
{
	struct nfs_files *filep;

#ifdef NFS_OPS_DEBUG
	if ((boothowto & DBFLAGS) == DBFLAGS)
		printf("boot_nfs_lseek(%d, 0x%x, %d)\n", fd, offset, whence);
#endif

	if (fd == 0) {
		dprintf("boot_nfs_lseek: Bad file number.\n");
		return (-1);
	}

	if ((filep = get_filep(fd)) == 0)
		return (-1);

	switch (whence) {

	case SEEK_SET:
		/*
		 * file ptr is set to offset from beginning of file
		 */
		filep->file.offset = offset;
		break;
	case SEEK_CUR:
		/*
		 * file ptr is set to offset from current position
		 */
		filep->file.offset += offset;
		break;
	case SEEK_END:
		/*
		 * file ptr is set to current size of file plus offset.
		 * But since we only support reading, this is illegal.
		 */
	default:
		/*
		 * invalid offset origin
		 */
		dprintf("boot_nfs_lseek: invalid whence value.\n");
		return (-1);
	}

#ifdef notyet
	return (filep->file.offset);
#else
	/*
	 * BROKE - lseek should return the offset seeked to on a
	 * successful seek, not zero - This must be fixed in the
	 * kernel before It can be fixed here.
	 */
	return (0);
#endif /* notyet */
}

/*
 * This version of fstat supports mode, size, inode #, and times only.
 * It can be enhanced if more is required,
 */

static int
boot_nfs_fstat(int fd, struct bootstat *stp)
{
	struct vattr va;
	struct nfs_files *filep;
	int status;

#ifdef NFS_OPS_DEBUG
	if ((boothowto & DBFLAGS) == DBFLAGS) {
		printf("boot_nfs_fstat(%d, 0x%x)\n", fd, stp);
	}
#endif
	if (fd == 0) {
		dprintf("boot_nfs_fstat(): Bad file number 0.\n");
		return (-1);
	}

	if ((filep = get_filep(fd)) == 0)
		return (-1);

	bzero((char *)&va, sizeof (va));
	va.va_mask = AT_TYPE | AT_SIZE | AT_MODE | AT_NODEID |
	    AT_ATIME | AT_CTIME | AT_MTIME;

	switch (filep->file.version) {
	case NFS_VERSION:
		status = nfsgetattr(&filep->file, &va);
		break;
	case NFS_V3:
		status = nfs3getattr(&filep->file, &va);
		break;
	case NFS_V4:
		status = nfs4getattr(&filep->file, &va);
		break;
	default:
		printf("boot_nfs_fstat: NFS Version %d not supported\n",
		    filep->file.version);
		status = -1;
		break;
	}

	if (status != 0)
		return (-1);

	if (va.va_size > (u_offset_t)MAXOFF_T) {
		dprintf("boot_nfs_fstat(): File too large.\n");
		return (-1);
	}
	stp->st_size = (off_t)va.va_size;
	stp->st_mode = VTTOIF(va.va_type) | va.va_mode;
	stp->st_atim.tv_sec = va.va_atime.tv_sec;
	stp->st_atim.tv_nsec = va.va_atime.tv_nsec;
	stp->st_ctim.tv_sec = va.va_ctime.tv_sec;
	stp->st_ctim.tv_nsec = va.va_ctime.tv_nsec;
	stp->st_mtim.tv_sec = va.va_mtime.tv_sec;
	stp->st_mtim.tv_nsec = va.va_mtime.tv_nsec;
	stp->st_ino = (ino_t)va.va_nodeid;

#ifdef NFS_OPS_DEBUG
	if ((boothowto & DBFLAGS) == DBFLAGS)
		printf("boot_nfs_fstat(): done.\n");
#endif
	return (0);
}

static int
boot_nfs_getdents(int fd, struct dirent *dep, unsigned size)
{
	struct nfs_files *filep;
	int status;

#ifdef NFS_OPS_DEBUG
	if ((boothowto & DBFLAGS) == DBFLAGS) {
		printf("boot_nfs_getdents(%d, 0x%x, 0x%x)\n", fd, dep, size);
	}
#endif

	if (fd == 0) {
		dprintf("boot_nfs_getdents(): Bad file number 0.\n");
		return (-1);
	}

	if ((filep = get_filep(fd)) == 0)
		return (-1);

	switch (filep->file.version) {
	case NFS_VERSION:
		status = nfsgetdents(&filep->file, dep, size);
		break;
	case NFS_V3:
		status = nfs3getdents(&filep->file, dep, size);
		break;
	default:
		printf("boot_nfs_getdents: NFS Version %d not supported\n",
		    filep->file.version);
		status = -1;
	}

#ifdef NFS_OPS_DEBUG
	if ((boothowto & DBFLAGS) == DBFLAGS)
		printf("boot_nfs_getdents(): done.\n");
#endif
	return (status);
}
/*
 * 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) 1983, 1984, 1985, 1986, 1987, 1988, 1989 AT&T */
/* All Rights Reserved */

/*
 * Portions of this source code were derived from Berkeley 4.3 BSD
 * under license from the Regents of the University of California.
 */

#include <sys/types.h>
#include <sys/param.h>
#include <sys/errno.h>
#include <st_pathname.h>
#include <sys/promif.h>
#include <sys/salib.h>
#include <sys/bootdebug.h>

/*
 * Pathname utilities.
 *
 * In translating file names we copy each argument file
 * name into a pathname structure where we operate on it.
 * Each pathname structure can hold MAXPATHLEN characters
 * including a terminating null, and operations here support
 * fetching strings from user space, getting the next character from
 * a pathname, combining two pathnames (used in symbolic
 * link processing), and peeling off the first component
 * of a pathname.
 */

#define	dprintf	if (boothowto & RB_DEBUG) printf

/*
 * Setup contents of pathname structure. Warn about missing allocations.
 * Structure itself is typically automatic
 * variable in calling routine for convenience.
 *
 * NOTE: if buf is NULL, failure occurs.
 */
int
stpn_alloc(struct st_pathname *pnp)
{
	if (pnp->pn_buf == NULL)
		return (-1);
	pnp->pn_path = (char *)pnp->pn_buf;
	pnp->pn_pathlen = 0;
	return (0);
}

/*
 * Pull a pathname from user user or kernel space
 */
int
stpn_get(char *str, struct st_pathname *pnp)
{
	if (stpn_alloc(pnp) != 0)
		return (-1);
	bcopy(str, pnp->pn_path, strlen(str));
	pnp->pn_pathlen = strlen(str);		/* don't count null byte */
	return (0);
}

/*
 * Set pathname to argument string.
 */
int
stpn_set(struct st_pathname *pnp, char *path)
{
	pnp->pn_path = pnp->pn_buf;
	pnp->pn_pathlen = strlen(pnp->pn_path); /* don't count null byte */
	bcopy(pnp->pn_path, path, pnp->pn_pathlen);
	return (0);
}

/*
 * Combine two argument pathnames by putting
 * second argument before first in first's buffer,
 * and freeing second argument.
 * This isn't very general: it is designed specifically
 * for symbolic link processing.
 */
int
stpn_combine(struct st_pathname *pnp, struct st_pathname *sympnp)
{

	if (pnp->pn_pathlen + sympnp->pn_pathlen >= MAXPATHLEN)
		return (ENAMETOOLONG);
	bcopy(pnp->pn_path, pnp->pn_buf + sympnp->pn_pathlen,
	    (uint_t)pnp->pn_pathlen);
	bcopy(sympnp->pn_path, pnp->pn_buf, (uint_t)sympnp->pn_pathlen);
	pnp->pn_pathlen += sympnp->pn_pathlen;
	pnp->pn_buf[pnp->pn_pathlen] = '\0';
	pnp->pn_path = pnp->pn_buf;
	return (0);
}

/*
 * Get next component off a pathname and leave in
 * buffer comoponent which should have room for
 * NFS_MAXNAMLEN (1024) bytes and a null terminator character.
 * If PEEK is set in flags, just peek at the component,
 * i.e., don't strip it out of pnp.
 */
int
stpn_getcomponent(struct st_pathname *pnp, char *component, int flags)
{
	char *cp;
	int l;
	int n;

	cp = pnp->pn_path;
	l = pnp->pn_pathlen;
	n = 1024;
	while ((l > 0) && (*cp != '/')) {
		if (--n < 0)
			return (ENAMETOOLONG);
		*component++ = *cp++;
		--l;
	}
	if (!(flags & PN_PEEK)) {
		pnp->pn_path = cp;
		pnp->pn_pathlen = l;
	}
	*component = 0;
	return (0);
}

/*
 * skip over consecutive slashes in the pathname
 */
void
stpn_skipslash(struct st_pathname *pnp)
{
	while ((pnp->pn_pathlen != 0) && (*pnp->pn_path == '/')) {
		pnp->pn_path++;
		pnp->pn_pathlen--;
	}
}

/*
 * free pathname resources. This is a nop - the user of these
 * routines is responsible for allocating and freeing their memory.
 */
/*ARGSUSED*/
void
stpn_free(struct st_pathname *pnp)
{
	/* nop */
	dprintf("pn_free(): you shouldn't be calling pn_free()!\n");
}
/*
 * 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 2004 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * This file contains the routines that maintain a linked list of known
 * program to udp port mappings. There are three static members initialized
 * by default, one for the portmapper itself (of course), one for rpcbind,
 * and one for nfs. If a program number is not in the list, then routines
 * in this file contact the portmapper on the server, and dynamically add
 * new members to this list.
 *
 * This file also contains bpmap_rmtcall() - which lets one get the port
 * number AND run the rpc call in one step. Only the server that successfully
 * completes the rpc call will return a result.
 *
 * NOTE: Because we will end up caching the port entries we need
 * before the kernel begins running, we can use dynamic allocation here.
 * boot_memfree() calls bpmap_memfree() to free up any dynamically
 * allocated entries when the boot program has finished its job.
 */

#include <sys/types.h>
#include <rpc/types.h>
#include <sys/errno.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <net/if.h>
#include <netinet/in.h>
#include <netinet/if_ether.h>
#include <rpc/xdr.h>
#include <rpc/auth.h>
#include <sys/t_lock.h>
#include "clnt.h"
#include <rpc/pmap_prot.h>
#include <rpc/pmap_rmt.h>
#include <rpc/rpc.h>
#include "brpc.h"
#include "pmap.h"
#include "nfs_inet.h"
#include <rpcsvc/nfs_prot.h>
#include <rpc/rpcb_prot.h>
#include <sys/salib.h>
#include "socket_inet.h"
#include <sys/promif.h>
#include <sys/bootdebug.h>

/* portmap structure */
#define	PMAP_STATIC	(3)	/* last statically allocated list entry */
struct pmaplist pre_init[PMAP_STATIC + 1] = {
	{ {PMAPPROG,	PMAPVERS,	IPPROTO_UDP, PMAPPORT}, &pre_init[1] },
	/* SVR4 rpcbind listens to old portmapper port */
	{ {RPCBPROG,	RPCBVERS,	IPPROTO_UDP, PMAPPORT}, &pre_init[2] },
	{ {NFS_PROGRAM, NFS_VERSION,	IPPROTO_UDP, NFS_PORT}, &pre_init[3] },
	{ {NFS_PROGRAM, NFS_V3,		IPPROTO_UDP, NFS_PORT}, NULL }
};

struct pmaplist *map_head = &pre_init[0];
struct pmaplist *map_tail = &pre_init[PMAP_STATIC];

#define	dprintf	if (boothowto & RB_DEBUG) printf

/*
 * bpmap_addport: adds a new entry on to the end of the pmap cache.
 * Items are kept in host order.
 */
static void
bpmap_addport(rpcprog_t prog, rpcvers_t vers, rpcport_t port)
{
	struct pmaplist *newp;

	/* allocate new pmaplist */
	newp = (struct pmaplist *)bkmem_alloc(sizeof (struct pmaplist));

	if (newp == NULL)
		return; /* not fatal here, we'll just throw out the entry */

	newp->pml_map.pm_prog = prog;
	newp->pml_map.pm_vers = vers;
	newp->pml_map.pm_prot = (rpcprot_t)IPPROTO_UDP;
	newp->pml_map.pm_port = port;

	map_tail->pml_next = newp;
	newp->pml_next = NULL;
	map_tail = newp;
}

/*
 * bpmap_delport: deletes an existing entry from the list. Caution - don't
 * call this function to delete statically allocated entries. Why would
 * you want to, anyway? Only IPPROTO_UDP is supported, of course.
 */
static void
bpmap_delport(rpcprog_t prog, rpcvers_t vers)
{
	struct pmaplist *tmp, *prev;

	prev = map_head;
	for (tmp = map_head; tmp != NULL; tmp = tmp->pml_next) {
		if ((tmp->pml_map.pm_prog == prog) &&
		    (tmp->pml_map.pm_vers == vers)) {
			if (tmp == map_head)
				map_head = tmp->pml_next; /* new head */
			else if (tmp == map_tail) {
				map_tail = prev;	/* new tail */
				map_tail->pml_next = NULL;
			} else {
				/* internal delete */
				prev->pml_next = tmp->pml_next;
			}
#ifdef	DEBUG
			printf("bpmap_delport: prog: %x, vers: %x\n", prog,
			    vers);
#endif	/* DEBUG */
			bkmem_free((caddr_t)tmp, sizeof (struct pmaplist));
			break;
		} else
			prev = tmp;
	}
}

/*
 * Modified strtol(3).
 */
static int
strtoi(char *str, char **ptr)
{
	int c, val;

	for (val = 0, c = *str++; c >= '0' && c <= '9'; c = *str++) {
		val *= 10;
		val += c - '0';
	}
	*ptr = str;
	return (val);
}

/*
 * (from dlboot_inet.c) (kernel)
 * Convert a port number from a sockaddr_in expressed
 * in universal address format.
 */
static int
uaddr2port(char	*addr)
{
	int	p1, p2;
	char	*next;

	/*
	 * A struct sockaddr_in expressed in universal address
	 * format looks like:
	 *
	 *	"IP.IP.IP.IP.PORT[top byte].PORT[bot. byte]"
	 *
	 * Where each component expresses as a charactor,
	 * the corresponding part of the IP address
	 * and port number.
	 * Thus 127.0.0.1, port 2345 looks like:
	 *
	 *	49 50 55 46 48 46 48 46 49 46 57 46 52 49
	 *	1  2  7  .  0  .  0  .  1  .  9  .  4  1
	 *
	 * 2345 = 929base16 = 9.32+9 = 9.41
	 */
	(void) strtoi(addr, &next);
	(void) strtoi(next, &next);
	(void) strtoi(next, &next);
	(void) strtoi(next, &next);
	p1 = strtoi(next, &next);
	p2 = strtoi(next, &next);

	return ((p1 << 8) + p2);
}

/*
 * Xdr routines used for calling portmapper/rpcbind.
 */

bool_t
xdr_pmap(XDR *xdrs, struct pmap *regs)
{
	if (xdr_rpcprog(xdrs, &regs->pm_prog) &&
		xdr_rpcvers(xdrs, &regs->pm_vers) &&
		xdr_rpcprot(xdrs, &regs->pm_prot))
		return (xdr_rpcprot(xdrs, &regs->pm_port));
	return (FALSE);
}

bool_t
xdr_rpcb(XDR *xdrs, RPCB *objp)
{
	if (!xdr_rpcprog(xdrs, &objp->r_prog))
		return (FALSE);
	if (!xdr_rpcvers(xdrs, &objp->r_vers))
		return (FALSE);
	if (!xdr_string(xdrs, &objp->r_netid, ~0))
		return (FALSE);
	if (!xdr_string(xdrs, &objp->r_addr, ~0))
		return (FALSE);
	if (!xdr_string(xdrs, &objp->r_owner, ~0))
		return (FALSE);
	return (TRUE);
}

/*
 * XDR remote call arguments
 * written for XDR_ENCODE direction only
 */
bool_t
xdr_rmtcall_args(XDR *xdrs, struct rmtcallargs *cap)
{
	uint_t	lenposition, argposition, position;

	if (xdr_rpcprog(xdrs, &(cap->prog)) &&
	    xdr_rpcvers(xdrs, &(cap->vers)) &&
	    xdr_rpcproc(xdrs, &(cap->proc))) {
		lenposition = XDR_GETPOS(xdrs);
		if (!xdr_u_int(xdrs, &(cap->arglen)))
			return (FALSE);
		argposition = XDR_GETPOS(xdrs);
		if (!(*(cap->xdr_args))(xdrs, cap->args_ptr))
			return (FALSE);
		position = XDR_GETPOS(xdrs);
		cap->arglen = position - argposition;
		(void) XDR_SETPOS(xdrs, lenposition);
		if (!xdr_u_int(xdrs, &(cap->arglen)))
			return (FALSE);
		(void) XDR_SETPOS(xdrs, position);
		return (TRUE);
	}
	return (FALSE);
}

/*
 * XDR remote call results
 * written for XDR_DECODE direction only
 */
bool_t
xdr_rmtcallres(XDR *xdrs, struct rmtcallres *crp)
{
	caddr_t	port_ptr;

	port_ptr = (caddr_t)crp->port_ptr;
	if (xdr_reference(xdrs, &port_ptr, sizeof (uint_t), xdr_u_int) &&
	    xdr_u_int(xdrs, &crp->resultslen)) {
		crp->port_ptr = (rpcport_t *)port_ptr;
		return ((*(crp->xdr_results))(xdrs, crp->results_ptr));
	}
	return (FALSE);
}

/*
 * XDR remote call arguments
 * written for XDR_ENCODE direction only
 */
bool_t
xdr_rpcb_rmtcallargs(XDR *xdrs, struct rpcb_rmtcallargs *objp)
{
	uint_t lenposition, argposition, position;

	if (!xdr_rpcprog(xdrs, &objp->prog))
		return (FALSE);
	if (!xdr_rpcvers(xdrs, &objp->vers))
		return (FALSE);
	if (!xdr_rpcproc(xdrs, &objp->proc))
		return (FALSE);
	/*
	 * All the jugglery for just getting the size of the arguments
	 */
	lenposition = XDR_GETPOS(xdrs);
	if (!xdr_u_int(xdrs, &(objp->arglen)))
		return (FALSE);
	argposition = XDR_GETPOS(xdrs);
	if (!(*(objp->xdr_args))(xdrs, objp->args_ptr))
		return (FALSE);
	position = XDR_GETPOS(xdrs);
	objp->arglen = position - argposition;
	(void) XDR_SETPOS(xdrs, lenposition);
	if (!xdr_u_int(xdrs, &(objp->arglen)))
		return (FALSE);
	(void) XDR_SETPOS(xdrs, position);
	return (TRUE);
}

/*
 * XDR remote call results
 * written for XDR_DECODE direction only
 */
bool_t
xdr_rpcb_rmtcallres(XDR *xdrs, struct rpcb_rmtcallres *objp)
{
	if (!xdr_string(xdrs, &objp->addr_ptr, ~0))
		return (FALSE);
	if (!xdr_u_int(xdrs, &objp->resultslen))
		return (FALSE);
	return ((*(objp->xdr_results))(xdrs, objp->results_ptr));
}

/*
 * bpmap_rmtcall: does PMAPPROC_CALLIT broadcasts w/ rpc_call requests.
 * Lets one do a PMAPGETPORT/RPC PROC call in one easy step. sockaddr_in args
 * are taken as network order.
 *
 * Code adapted from bpmap_rmtcall() in dlboot_inet.c (kernel)
 */
/*ARGSUSED*/
enum clnt_stat
bpmap_rmtcall(
	rpcprog_t		prog,	/* rpc program number to call. */
	rpcvers_t		vers,	/* rpc program version */
	rpcproc_t		proc,	/* rpc procedure to call */
	xdrproc_t		in_xdr,	/* routine to serialize arguments */
	caddr_t			args,	/* arg vector for remote call */
	xdrproc_t		out_xdr, /* routine to deserialize results */
	caddr_t			ret,	/* addr of buf to place results in */
	int			rexmit,	/* retransmission interval (secs) */
	int			wait,	/* how long (secs) to wait for a resp */
	struct sockaddr_in 	*to,	/* destination */
	struct sockaddr_in	*from,	/* filled in w/ responder's port/addr */
	uint_t			auth)	/* type of authentication wanted. */
{
	enum clnt_stat		status;		/* rpc_call status */
	rpcport_t		port = 0;	/* returned port # */
	struct rmtcallargs	pmap_a;		/* args for pmap call */
	struct rmtcallres	pmap_r;		/* results from pmap call */
	struct rpcb_rmtcallargs	rpcb_a;		/* args for rpcb call */
	struct rpcb_rmtcallres	rpcb_r;		/* results from rpcb call */
	char			ua[UA_SIZE];	/* universal addr buffer */

	/* initialize pmap */
	pmap_a.prog = prog;
	pmap_a.vers = vers;
	pmap_a.proc = proc;
	pmap_a.args_ptr = args;
	pmap_a.xdr_args = in_xdr;
	pmap_r.port_ptr = &port;
	pmap_r.results_ptr = ret;
	pmap_r.xdr_results = out_xdr;

	status = brpc_call((rpcprog_t)PMAPPROG, (rpcvers_t)PMAPVERS,
	    (rpcproc_t)PMAPPROC_CALLIT, xdr_rmtcall_args, (caddr_t)&pmap_a,
	    xdr_rmtcallres, (caddr_t)&pmap_r, rexmit, wait, to, from,
	    AUTH_NONE);
	if (status != RPC_PROGUNAVAIL) {
		if (status == RPC_SUCCESS) {
			/* delete old port mapping, if it exists */
			bpmap_delport(prog, vers);

			/* save the new port mapping */
			bpmap_addport(prog, vers, port);
		}
		return (status);
	}

	/*
	 * PMAP is unavailable. Maybe there's a SVR4 machine, with rpcbind.
	 */
	bzero(ua, sizeof (ua));

	/* initialize rpcb */
	rpcb_a.prog = prog;
	rpcb_a.vers = vers;
	rpcb_a.proc = proc;
	rpcb_a.args_ptr = args;
	rpcb_a.xdr_args = in_xdr;
	rpcb_r.addr_ptr = ua;
	rpcb_r.results_ptr = ret;
	rpcb_r.xdr_results = out_xdr;

	status = brpc_call((rpcprog_t)RPCBPROG, (rpcvers_t)RPCBVERS,
	    (rpcproc_t)RPCBPROC_CALLIT, xdr_rpcb_rmtcallargs, (caddr_t)&rpcb_a,
	    xdr_rpcb_rmtcallres, (caddr_t)&rpcb_r, rexmit, wait, to, from,
	    AUTH_NONE);
	if (status == RPC_SUCCESS) {
		/* delete old port mapping, if it exists */
		bpmap_delport(prog, vers);

		/* save the new port mapping */
		port = ntohs(uaddr2port(ua));
		bpmap_addport(prog, vers, port);
	}
	return (status);
}

/*
 * bpmap_getport: Queries current list of cached pmap_list entries,
 * returns the port number of the entry found. If the port number
 * is not cached, then getport makes a rpc call first to the portmapper,
 * and then to rpcbind (SVR4) if the portmapper does not respond. The
 * returned port is then added to the cache, and the port number is
 * returned. If both portmapper and rpc bind fail to give us the necessary
 * port, we return 0 to signal we hit an error, and set rpc_stat to
 * the appropriate RPC error code. Only IPPROTO_UDP protocol is supported.
 *
 * Port and sockaddr_in arguments taken in network order. rpcport_t is returned
 * in host order.
 */
rpcport_t
bpmap_getport(rpcprog_t prog, rpcvers_t vers, enum clnt_stat *rpc_stat,
    struct sockaddr_in *to, struct sockaddr_in *from)
{
	struct pmaplist	*walk;
	struct pmap	pmap_send;	/* portmap */
	in_port_t	pmap_port;
	rpcport_t	dport;

#ifdef DEBUG
	printf("bpmap_getport: called with: prog: %d, vers: %d\n", prog, vers);
#endif /* DEBUG */
	for (walk = map_head; walk != 0; walk = walk->pml_next) {
		if ((walk->pml_map.pm_prog == prog) &&
		    (walk->pml_map.pm_vers == vers) &&
		    (walk->pml_map.pm_prot == (rpcprot_t)IPPROTO_UDP)) {
#ifdef DEBUG
			printf("bpmap_getport: Found in cache. returning: %d\n",
			    walk->pml_map.pm_port);
#endif /* DEBUG */
			return (walk->pml_map.pm_port);
		}
	}

	/*
	 * Not in the cache. First try the portmapper (SunOS server?) and
	 * if that fails, try rpcbind (SVR4 server).
	 */
	pmap_send.pm_prog = prog;
	pmap_send.pm_vers = vers;
	pmap_send.pm_prot = (rpcprot_t)IPPROTO_UDP;
	pmap_send.pm_port = 0;	/* what we're after */

	*rpc_stat = brpc_call(PMAPPROG, PMAPVERS, PMAPPROC_GETPORT,
	    xdr_pmap, (caddr_t)&pmap_send, xdr_u_short,
	    (caddr_t)&pmap_port, 0, 0, to, from, AUTH_NONE);

	if (*rpc_stat == RPC_PROGUNAVAIL) {
		/*
		 * The portmapper isn't available. Try rpcbind.
		 * Maybe the server is a SVR4 server.
		 */
		char	*ua;			/* universal address */
		char	ua_buf[UA_SIZE];	/* and its buffer */
		RPCB	rpcb_send;

		rpcb_send.r_prog = prog;
		rpcb_send.r_vers = vers;
		rpcb_send.r_netid = NULL;
		rpcb_send.r_addr = NULL;
		rpcb_send.r_owner = NULL;

		bzero(ua_buf, UA_SIZE);
		ua = ua_buf;

		/*
		 * Again, default # of retries. xdr_wrapstring()
		 * wants a char **.
		 */
		*rpc_stat = brpc_call(RPCBPROG, RPCBVERS, RPCBPROC_GETADDR,
		    xdr_rpcb, (caddr_t)&rpcb_send, xdr_wrapstring,
		    (char *)&ua, 0, 0, to, from, AUTH_NONE);

		if (*rpc_stat == RPC_SUCCESS) {
			if (ua[0] != '\0')
				dport = ntohs(uaddr2port(ua));
			else
				return (0); /* Address unknown */
		}
	} else {
		/*
		 * Why are rpcport_t's uint32_t? port numbers are uint16_t
		 * for ipv4 AND ipv6.... XXXX
		 */
		dport = (rpcport_t)pmap_port;
	}

	if (*rpc_stat != RPC_SUCCESS)  {
		dprintf("pmap_getport: Failed getting port.\n");
		return (0);	/* we failed. */
	}

#ifdef DEBUG
	printf("bpmap_getport: prog: %d, vers: %d; returning port: %d.\n",
	    prog, vers, dport);
#endif /* DEBUG */

	bpmap_addport(prog, vers, dport);

	return (dport);
}

/*
 * bpmap_memfree: frees up any dynamically allocated entries.
 */
void
bpmap_memfree(void)
{
	struct pmaplist *current, *tmp;

	if (map_tail == &pre_init[PMAP_STATIC])
		return; /* no dynamic entries */

	/* free from head of the list to the tail. */
	current = pre_init[PMAP_STATIC].pml_next;
	while (current != NULL) {
		tmp = current->pml_next;
		bkmem_free((caddr_t)current, sizeof (struct pmaplist));
		current = tmp;
	}
}
/*
 * 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 2004 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef	_PMAP_H
#define	_PMAP_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#ifdef	__cplusplus
extern "C" {
#endif

#define	UA_SIZE		(128)	/* max space needed for an universal addr */

extern enum clnt_stat bpmap_rmtcall(rpcprog_t, rpcvers_t, rpcproc_t, xdrproc_t,
    caddr_t, xdrproc_t, caddr_t, int, int, struct sockaddr_in *,
    struct sockaddr_in *, uint_t);
extern rpcport_t bpmap_getport(rpcprog_t, rpcvers_t, enum clnt_stat *,
	struct sockaddr_in *, struct sockaddr_in *);
extern void bpmap_memfree(void);

#ifdef	__cplusplus
}
#endif

#endif	/* _PMAP_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 2006 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 *
 * This file contains a simple implementation of RPC. Standard XDR is
 * used.
 */

#include <sys/sysmacros.h>
#include <rpc/types.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include "socket_inet.h"
#include "ipv4.h"
#include <rpc/xdr.h>
#include <rpc/auth.h>
#include <rpc/auth_sys.h>
#include <rpc/rpc_msg.h>
#include <sys/t_lock.h>
#include <netdb.h>
#include "clnt.h"
#include <rpc/rpc.h>
#include "brpc.h"
#include "auth_inet.h"
#include "pmap.h"
#include <sys/promif.h>
#include "nfs_inet.h"
#include <rpcsvc/nfs_prot.h>
#include <rpc/auth_unix.h>
#include <sys/salib.h>
#include "mac.h"
#include <sys/bootdebug.h>

#define	dprintf	if (boothowto & RB_DEBUG) printf

static struct in_addr cached_destination;

void
rpc_disperr(struct rpc_err *stat)
{
	if (boothowto & RB_DEBUG) {
		switch (stat->re_status) {
		case RPC_CANTENCODEARGS:
			printf("RPC: Can't encode arguments.\n");
			break;
		case RPC_CANTDECODERES:
			printf("RPC: Can't decode result.\n");
			break;
		case RPC_CANTSEND:
			printf("RPC: Unable to send (%s).\n",
			    strerror(errno));
			break;
		case RPC_CANTRECV:
			printf("RPC: Unable to receive (%s).\n",
			    strerror(errno));
			break;
		case RPC_TIMEDOUT:
			printf("RPC: Timed out.\n");
			break;
		case RPC_VERSMISMATCH:
			printf("RPC: Incompatible versions of RPC.\n");
			break;
		case RPC_AUTHERROR:
			printf("RPC: Authentication error:\n");
			switch (stat->re_why) {
			case AUTH_BADCRED:
				printf("remote: bogus credentials "
				    "(seal broken).\n");
				break;
			case AUTH_REJECTEDCRED:
				printf("remote: client should begin new "
				    "session.\n");
				break;
			case AUTH_BADVERF:
				printf("remote: bogus verifier "
				    "(seal broken).\n");
				break;
			case AUTH_REJECTEDVERF:
				printf("remote: verifier expired or was "
				    "replayed.\n");
				break;
			case AUTH_TOOWEAK:
				printf("remote: rejected due to security "
				    "reasons.\n");
				break;
			case AUTH_INVALIDRESP:
				printf("local: bogus response verifier.\n");
				break;
			case AUTH_FAILED:
				/* FALLTHRU */
			default:
				printf("local: unknown error.\n");
				break;
			}
			break;
		case RPC_PROGUNAVAIL:
			printf("RPC: Program unavailable.\n");
			break;
		case RPC_PROGVERSMISMATCH:
			printf("RPC: Program/version mismatch.\n");
			break;
		case RPC_PROCUNAVAIL:
			printf("RPC: Procedure unavailable.\n");
			break;
		case RPC_CANTDECODEARGS:
			printf("RPC: Server can't decode arguments.\n");
			break;
		case RPC_SYSTEMERROR:
			printf("RPC: Remote system error.\n");
			break;
		case RPC_UNKNOWNHOST:
			printf("RPC: Unknown host.\n");
			break;
		case RPC_UNKNOWNPROTO:
			printf("RPC: Unknown protocol.\n");
			break;
		case RPC_PMAPFAILURE:
			printf("RPC: Port mapper failure.\n");
			break;
		case RPC_PROGNOTREGISTERED:
			printf("RPC: Program not registered.\n");
			break;
		case RPC_FAILED:
			printf("RPC: Failed (unspecified error).\n");
			break;
		default:
			printf("RPC: (unknown error code).\n");
			break;
		}
	}
}

/*
 * rpc_hdr: sets the fields in the rpc msg header.
 *
 * Returns: TRUE on success, FALSE if failure.
 */
/*ARGSUSED*/
static bool_t
rpc_hdr(XDR *xdrs, uint_t xid, rpcprog_t prog, rpcvers_t vers, rpcproc_t proc)
{
	struct rpc_msg call_msg;

	/* setup header */
	call_msg.rm_xid = xid;
	call_msg.rm_direction = CALL;
	call_msg.rm_call.cb_rpcvers = (rpcvers_t)RPC_MSG_VERSION;
	call_msg.rm_call.cb_prog = prog;
	call_msg.rm_call.cb_vers = vers;

	/* xdr the header. */
	if (xdr_callhdr(xdrs, &call_msg) == FALSE)
		return (FALSE);
	else
		return (TRUE);
}

/*
 * our version of brpc_call(). We cache in portnumber in to->sin_port for
 * your convenience. to and from addresses are taken and received in network
 * order.
 */
enum clnt_stat
brpc_call(
	rpcprog_t	prog,		/* rpc program number to call. */
	rpcvers_t	vers,		/* rpc program version */
	rpcproc_t	proc,		/* rpc procedure to call */
	xdrproc_t	in_xdr,		/* routine to serialize arguments */
	caddr_t		args,		/* arg vector for remote call */
	xdrproc_t	out_xdr,	/* routine to deserialize results */
	caddr_t		ret,		/* addr of buf to place results in */
	int		rexmit,		/* retransmission interval (secs) */
	int		wait_time,	/* how long (secs) to wait (resp) */
	struct sockaddr_in 	*to,		/* destination */
	struct sockaddr_in	*from_who,	/* responder's port/address */
	uint_t			auth)		/* type of auth wanted. */
{
	int s;
	char hostname[MAXHOSTNAMELEN];
	struct sockaddr_in from;	/* us. */
	socklen_t from_len;
	XDR xmit_xdrs, rcv_xdrs;	/* xdr memory */
	AUTH *xmit_auth;		/* our chosen auth cookie */
	gid_t fake_gids = 1;		/* fake gids list for auth_unix */
	caddr_t trm_msg, rcv_msg;	/* outgoing/incoming rpc mesgs */
	struct rpc_msg reply;		/* our reply msg header */
	int trm_len, rcv_len;
	struct rpc_err rpc_error;	/* to store RPC errors in on rcv. */
	static uint_t xid;		/* current xid */
	uint_t xmit_len;		/* How much of the buffer we used */
	int nrefreshes = 2;		/* # of times to refresh cred */
	int flags = 0;			/* send flags */
	uint_t xdelay;
	int errors, preserve_errno;
	uint32_t timeout;
	socklen_t optlen;

	xmit_auth = NULL;

	trm_len = mac_get_mtu();
	trm_msg = bkmem_alloc(trm_len);
	rcv_msg = bkmem_alloc(NFSBUF_SIZE);

	if (trm_msg == NULL || rcv_msg == NULL) {
		errno = ENOMEM;
		rpc_error.re_status = RPC_CANTSEND;
		goto gt_error;
	}

	if ((s = socket(PF_INET, SOCK_DGRAM, 0)) < 0) {
		rpc_error.re_status = RPC_CANTSEND;
		goto gt_error;
	}

	if (dontroute) {
		(void) setsockopt(s, SOL_SOCKET, SO_DONTROUTE,
		    (const void *)&dontroute, sizeof (dontroute));
	}

	if (to->sin_addr.s_addr == cached_destination.s_addr) {
		optlen = sizeof (timeout);
		(void) getsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (void *)&timeout,
		    &optlen);
	} else {
		cached_destination.s_addr = htonl(INADDR_ANY);
	}

	/* Bind our endpoint. */
	from.sin_family = AF_INET;
	ipv4_getipaddr(&from.sin_addr);
	from.sin_addr.s_addr = htonl(from.sin_addr.s_addr);
	from.sin_port = get_source_port(B_TRUE);

	if (bind(s, (struct sockaddr *)&from, sizeof (from)) < 0) {
		rpc_error.re_status = RPC_CANTSEND;
		goto gt_error;
	}

	bzero((caddr_t)&rpc_error, sizeof (struct rpc_err));

	/* initialize reply's rpc_msg struct, so we can decode later. */
	reply.acpted_rply.ar_verf = _null_auth;	/* struct copy */
	reply.acpted_rply.ar_results.where = ret;
	reply.acpted_rply.ar_results.proc = out_xdr;

	if (ntohs(to->sin_port) == 0) {
		/* snag the udp port we need. */
		if ((to->sin_port = (in_port_t)bpmap_getport(prog, vers,
		    &(rpc_error.re_status), to, NULL)) == 0)
			goto gt_error;
		to->sin_port = htons(to->sin_port);
	}

	/* generate xid - increment */
	if (xid == 0)
		xid = (uint_t)(prom_gettime() / 1000) + 1;
	else
		xid++;

	/* set up outgoing pkt as xdr modified. */
	xdrmem_create(&xmit_xdrs, trm_msg, trm_len, XDR_ENCODE);

	/* setup rpc header */
	if (rpc_hdr(&xmit_xdrs, xid, prog, vers, proc) != TRUE) {
		dprintf("brpc_call: cannot setup rpc header.\n");
		rpc_error.re_status = RPC_FAILED;
		goto gt_error;
	}

	/* setup authentication */
	switch (auth) {
	case AUTH_NONE:
		xmit_auth = authnone_create();
		break;
	case AUTH_UNIX:
		/*
		 * Assumes we've configured the stack and thus know our
		 * IP address/hostname, either by using DHCP or rarp/bootparams.
		 */
		(void) gethostname(hostname, sizeof (hostname));
		xmit_auth = authunix_create(hostname, 0, 1, 1, &fake_gids);
		break;
	default:
		dprintf("brpc_call: Unsupported authentication type: %d\n",
		    auth);
		rpc_error.re_status = RPC_AUTHERROR;
		goto gt_error;
	/*NOTREACHED*/
	}

	/*
	 * rpc_hdr puts everything in the xmit buffer for the header
	 * EXCEPT the proc. Put it, and our authentication info into
	 * it now, serializing as we go. We will be at the place where
	 * we left off.
	 */
	xmit_xdrs.x_op = XDR_ENCODE;
	if ((XDR_PUTINT32(&xmit_xdrs, (int32_t *)&proc) == FALSE) ||
	    (AUTH_MARSHALL(xmit_auth, &xmit_xdrs, NULL) == FALSE) ||
	    ((*in_xdr)(&xmit_xdrs, args) == FALSE)) {
		rpc_error.re_status = RPC_CANTENCODEARGS;
		goto gt_error;
	} else
		xmit_len = (int)XDR_GETPOS(&xmit_xdrs); /* for sendto */

	/*
	 * Right now the outgoing packet should be all serialized and
	 * ready to go... Set up timers.
	 */

	xdelay = (rexmit == 0) ? RPC_REXMIT_MSEC : (rexmit * 1000);
	(void) setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (void *)&xdelay,
	    sizeof (xdelay));
	wait_time = (wait_time == 0) ? RPC_RCVWAIT_MSEC : (wait_time * 1000);

	wait_time += prom_gettime();

	/*
	 * send out the request. The first item in the receive buffer will
	 * be the xid. Check if it is correct.
	 */
	errors = 0;
	rpc_error.re_status = RPC_TIMEDOUT;
	do {
		if (sendto(s, trm_msg, xmit_len, flags, (struct sockaddr *)to,
		    sizeof (struct sockaddr_in)) < 0) {
			/*
			 * If errno is set to ETIMEDOUT, return
			 * with RPC status as RPC_TIMEDOUT. Calling
			 * funciton will take care of this error by
			 * retrying the RPC call.
			 */
			if (errno == ETIMEDOUT) {
				rpc_error.re_status = RPC_TIMEDOUT;
			} else {
				rpc_error.re_status = RPC_CANTSEND;
			}
			goto gt_error;
		}

		from_len = sizeof (struct sockaddr_in);
		while ((rcv_len = recvfrom(s, rcv_msg, NFSBUF_SIZE,
		    MSG_DONTWAIT, (struct sockaddr *)from_who,
		    &from_len)) > 0 || errors < RPC_ALLOWABLE_ERRORS) {
			if (rcv_len < 0) {
				if (errno == EWOULDBLOCK ||
				    errno == ETIMEDOUT) {
					break; /* timeout */
				}
				rpc_error.re_status = RPC_CANTRECV;
				goto gt_error;
			}
			if (ntohl(*((uint32_t *)(rcv_msg))) != xid) {
				dprintf("brpc_call: xid: 0x%x != 0x%x\n",
				    *(uint32_t *)(rcv_msg), xid);
				continue;
			}
			/*
			 * Let's deserialize the data into our 'ret' buffer.
			 */
			xdrmem_create(&rcv_xdrs, rcv_msg, rcv_len, XDR_DECODE);
			if (xdr_replymsg(&rcv_xdrs, &reply) == FALSE) {
				rpc_error.re_status = RPC_CANTDECODERES;
				goto gt_error;
			}
			_seterr_reply(&reply, &rpc_error);
			switch (rpc_error.re_status) {
			case RPC_SUCCESS:
				/*
				 * XXX - validate for unix and none
				 * always return true.
				 */
				if (AUTH_VALIDATE(xmit_auth,
				    &reply.acpted_rply.ar_verf) == FALSE) {
					rpc_error.re_status = RPC_AUTHERROR;
					rpc_error.re_why = AUTH_INVALIDRESP;
					errors++;
				}
				if (reply.acpted_rply.ar_verf.oa_base !=
				    0) {
					xmit_xdrs.x_op = XDR_FREE;
					(void) xdr_opaque_auth(
					    &xmit_xdrs,
					    &reply.acpted_rply.ar_verf);
				}
				break;

			case RPC_AUTHERROR:
				/*
				 * Let's see if our credentials need
				 * refreshing
				 */
				if (nrefreshes > 0 && AUTH_REFRESH(xmit_auth,
				    NULL, NULL)) {
					nrefreshes--;
				}
				errors++;
				break;

			case RPC_PROCUNAVAIL:
				/*
				 * Might be a silly portmapper implementation
				 * erroneously responding to our rpc broadcast
				 * indirect portmapper call. For this
				 * particular case, we don't increment the
				 * error counter because we want to keep
				 * sifting for successful replies...
				 */
				if (to->sin_addr.s_addr !=
				    ntohl(INADDR_BROADCAST))
					errors++;
				break;

			case RPC_PROGVERSMISMATCH:
				/*
				 * Successfully talked to server, but they
				 * don't speak our lingo.
				 */
				goto gt_error;

			default:
				/* Just keep trying till there's no data... */
				errors++;
				break;
			}

			if (rpc_error.re_status != RPC_SUCCESS) {
				dprintf("brpc_call: from: %s, error: ",
				    inet_ntoa(from_who->sin_addr));
				rpc_disperr(&rpc_error);
			} else
				break;
		}

		/*
		 * If we're having trouble reassembling datagrams, let the
		 * application know ASAP so that it can take the appropriate
		 * actions.
		 */

	} while (rpc_error.re_status != RPC_SUCCESS && errno != ETIMEDOUT &&
	    prom_gettime() < wait_time);

gt_error:
	if (xmit_auth != NULL)
		AUTH_DESTROY(xmit_auth);

	if (trm_msg != NULL)
		bkmem_free(trm_msg, trm_len);
	if (rcv_msg != NULL)
		bkmem_free(rcv_msg, NFSBUF_SIZE);

	if (rpc_error.re_status != RPC_SUCCESS)
		rpc_disperr(&rpc_error);

	/*
	 * socket calls reset errno. Since we want to hold onto the errno
	 * value if it is ETIMEDOUT to communicate to our caller that this
	 * RPC_TIMEDOUT situation is due to a stack problem (we're getting
	 * a reply, but the stack simply can't assemble it.), we need to
	 * preserve errno's value over the socket_close().
	 */
	preserve_errno = (errno == ETIMEDOUT) ? errno : 0;
	(void) socket_close(s);
	errno = preserve_errno;

	return (rpc_error.re_status);
}
/*
 * 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 _ST_PATHNAME_H
#define	_ST_PATHNAME_H

#ifdef	__cplusplus
extern "C" {
#endif

/*
 * Pathname structure.
 * System calls which operate on path names gather the
 * pathname from system call into this structure and reduce
 * it by peeling off translated components.  If a symbolic
 * link is encountered the new pathname to be translated
 * is also assembled in this structure.
 */

struct st_pathname {
	char	*pn_buf;		/* underlying storage */
	char	*pn_path;		/* remaining pathname */
	uint_t	pn_pathlen;		/* remaining length */
};

#define	PN_STRIP 0x00		/* Strip next component off pn */
#define	PN_PEEK	0x01  		/* Only peek at next pn component */
#define	stpn_peekcomponent(PNP, COMP) stpn_getcomponent(PNP, COMP, PN_PEEK)
#define	stpn_stripcomponent(PNP, COMP) stpn_getcomponent(PNP, COMP, PN_STRIP)

#define	stpn_peekchar(PNP) 	(((PNP)->pn_pathlen != 0) ? \
				    *((PNP)->pn_path) : (char)0)
#define	stpn_pathleft(PNP)	((PNP)->pn_pathlen)
#define	stpn_getpath(PNP)		((PNP)->pn_path)
#define	stpn_copy(PNP1, PNP2)	(stpn_set(PNP2, stpn_getpath(PNP1)))

extern int	stpn_alloc();		/* allocate buffer for pathname */
extern int	stpn_get();		/* allocate buf and copy path into it */
extern int	stpn_set();		/* set pathname to string */
extern int	stpn_combine();		/* combine to pathnames (for symlink) */
extern int	stpn_getcomponent();	/* get next component of pathname */
extern void	stpn_skipslash();		/* skip over slashes */
extern void	stpn_free();		/* free pathname buffer */

#ifdef	__cplusplus
}
#endif

#endif /* _ST_PATHNAME_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.
 */

/* Copyright (c) 1983, 1984, 1985, 1986, 1987, 1988, 1989 AT&T */
/* All Rights Reserved */

/*
 * Portions of this source code were derived from Berkeley 4.3 BSD
 * under license from the Regents of the University of California.
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"

/*
 * xdr_rec.c, Implements TCP/IP based XDR streams with a "record marking"
 * layer above tcp (for rpc's use).
 *
 * These routines interface XDRSTREAMS to a tcp/ip connection.
 * There is a record marking layer between the xdr stream
 * and the tcp transport level.  A record is composed on one or more
 * record fragments.  A record fragment is a thirty-two bit header followed
 * by n bytes of data, where n is contained in the header.  The header
 * is represented as a htonl(u_long).  The high order bit encodes
 * whether or not the fragment is the last fragment of the record
 * (1 => fragment is last, 0 => more fragments to follow.
 * The other 31 bits encode the byte length of the fragment.
 */

#include <rpc/types.h>
#include <rpc/xdr.h>
#include <netinet/in.h>
#include <sys/promif.h>
#include <sys/salib.h>
#include <sys/bootdebug.h>

#define	dprintf if (boothowto & RB_DEBUG) printf

extern long	lseek();

static bool_t	xdrrec_getint32();
static bool_t	xdrrec_putint32();
static bool_t	xdrrec_getbytes();
static bool_t	xdrrec_putbytes();
static uint_t	xdrrec_getpos();
static bool_t	xdrrec_setpos();
static int32_t *xdrrec_inline();
static void	xdrrec_destroy();

static struct xdr_ops *xdrrec_ops();
static bool_t flush_out();
static bool_t fill_input_buf();
static bool_t get_input_bytes();
static bool_t set_input_fragment();
static bool_t skip_input_bytes();
static uint_t fix_buf_size();

/*
 * A record is composed of one or more record fragments.
 * A record fragment is a four-byte header followed by zero to
 * 2**32-1 bytes.  The header is treated as a long unsigned and is
 * encode/decoded to the network via htonl/ntohl.  The low order 31 bits
 * are a byte count of the fragment.  The highest order bit is a boolean:
 * 1 => this fragment is the last fragment of the record,
 * 0 => this fragment is followed by more fragment(s).
 *
 * The fragment/record machinery is not general;  it is constructed to
 * meet the needs of xdr and rpc based on tcp.
 */
#define	LAST_FRAG 0x80000000

typedef struct rec_strm {
	caddr_t tcp_handle;
	caddr_t the_buffer;
	/*
	 * out-goung bits
	 */
	int (*writeit)();
	caddr_t out_base;	/* output buffer (points to frag header) */
	caddr_t out_finger;	/* next output position */
	caddr_t out_boundry;	/* data cannot up to this address */
	uint32_t *frag_header;	/* beginning of current fragment */
	bool_t frag_sent;	/* true if buffer sent in middle of record */
	/*
	 * in-coming bits
	 */
	int (*readit)();
	uint32_t in_size;	/* fixed size of the input buffer */
	caddr_t in_base;
	caddr_t in_finger;	/* location of next byte to be had */
	caddr_t in_boundry;	/* can read up to this location */
	int fbtbc;		/* fragment bytes to be consumed */
	bool_t last_frag;
	uint_t sendsize;
	uint_t recvsize;
} RECSTREAM;


/*
 * Create an xdr handle for xdrrec
 * xdrrec_create fills in xdrs.  Sendsize and recvsize are
 * send and recv buffer sizes (0 => use default).
 * tcp_handle is an opaque handle that is passed as the first parameter to
 * the procedures readit and writeit.  Readit and writeit are read and
 * write respectively.   They are like the system
 * calls expect that they take an opaque handle rather than an fd.
 */
void
xdrrec_create(XDR *xdrs, uint_t sendsize, uint_t recvsize, caddr_t tcp_handle,
		int (*readit)(), int (*writeit)())
{
	RECSTREAM *rstrm = (RECSTREAM *)mem_alloc(sizeof (RECSTREAM));
	if (rstrm == NULL) {
		dprintf("xdrrec_create: out of memory\n");
		/*
		 *  This is bad.  Should rework xdrrec_create to
		 *  return a handle, and in this case return NULL
		 */
		return;
	}
	/*
	 * adjust sizes and allocate buffer quad byte aligned
	 */
	rstrm->sendsize = sendsize = fix_buf_size(sendsize);
	rstrm->recvsize = recvsize = fix_buf_size(recvsize);
	rstrm->the_buffer = mem_alloc(sendsize + recvsize + BYTES_PER_XDR_UNIT);
	if (rstrm->the_buffer == NULL) {
		dprintf("xdrrec_create: out of memory\n");
		return;
	}
	for (rstrm->out_base = rstrm->the_buffer;
		(uintptr_t)rstrm->out_base % BYTES_PER_XDR_UNIT != 0;
		rstrm->out_base++);
	rstrm->in_base = rstrm->out_base + sendsize;
	/*
	 * now the rest ...
	 */
	xdrs->x_ops = xdrrec_ops();
	xdrs->x_private = (caddr_t)rstrm;
	rstrm->tcp_handle = tcp_handle;
	rstrm->readit = readit;
	rstrm->writeit = writeit;
	rstrm->out_finger = rstrm->out_boundry = rstrm->out_base;
	rstrm->frag_header = (uint32_t *)rstrm->out_base;
	rstrm->out_finger += sizeof (uint_t);
	rstrm->out_boundry += sendsize;
	rstrm->frag_sent = FALSE;
	rstrm->in_size = recvsize;
	rstrm->in_boundry = rstrm->in_base;
	rstrm->in_finger = (rstrm->in_boundry += recvsize);
	rstrm->fbtbc = 0;
	rstrm->last_frag = TRUE;

}


/*
 * The routines defined below are the xdr ops which will go into the
 * xdr handle filled in by xdrrec_create.
 */

static bool_t
xdrrec_getint32(XDR *xdrs, int32_t *ip)
{
	RECSTREAM *rstrm = (RECSTREAM *)(xdrs->x_private);
	int32_t *bufip = (int32_t *)(rstrm->in_finger);
	int32_t myint;

	/* first try the inline, fast case */
	if ((rstrm->fbtbc >= sizeof (int32_t)) &&
		(((ptrdiff_t)rstrm->in_boundry
		    - (ptrdiff_t)bufip) >= sizeof (int32_t))) {
		*ip = (int32_t)ntohl((uint32_t)(*bufip));
		rstrm->fbtbc -= sizeof (int32_t);
		rstrm->in_finger += sizeof (int32_t);
	} else {
		if (!xdrrec_getbytes(xdrs, (caddr_t)&myint, sizeof (int32_t)))
			return (FALSE);
		*ip = (int32_t)ntohl((uint32_t)myint);
	}
	return (TRUE);
}

static bool_t
xdrrec_putint32(XDR *xdrs, int32_t *ip)
{
	RECSTREAM *rstrm = (RECSTREAM *)(xdrs->x_private);
	int32_t *dest_ip = ((int32_t *)(rstrm->out_finger));

	if ((rstrm->out_finger += sizeof (int32_t)) > rstrm->out_boundry) {
		/*
		 * this case should almost never happen so the code is
		 * inefficient
		 */
		rstrm->out_finger -= sizeof (int32_t);
		rstrm->frag_sent = TRUE;
		if (! flush_out(rstrm, FALSE))
			return (FALSE);
		dest_ip = ((int32_t *)(rstrm->out_finger));
		rstrm->out_finger += sizeof (int32_t);
	}
	*dest_ip = (int32_t)htonl((uint32_t)(*ip));
	return (TRUE);
}

/*
 * We need to be a little smarter here because we don't want to induce any
 * pathological behavior in inetboot's networking stack.  The algorithm we
 * pursue is to try to consume the entire fragment exactly instead of
 * blindly requesting the max to fill the input buffer.
 */
static bool_t  /* must manage buffers, fragments, and records */
xdrrec_getbytes(XDR *xdrs, caddr_t addr, int32_t len)
{
	RECSTREAM *rstrm = (RECSTREAM *)(xdrs->x_private);
	int current;
	int frag_len;

	while (len > 0) {
		current =  frag_len = rstrm->fbtbc;
		if (current == 0) {
			if (rstrm->last_frag)
				return (FALSE);
			if (!set_input_fragment(rstrm))
				return (FALSE);
			continue;
		}

		current = (len < current) ? len : current;
		if (!get_input_bytes(rstrm, addr, frag_len, current))
			return (FALSE);
		addr += current;
		rstrm->fbtbc -= current;
		len -= current;
	}
	return (TRUE);
}

static bool_t
xdrrec_putbytes(XDR *xdrs, caddr_t addr, int32_t len)
{
	RECSTREAM *rstrm = (RECSTREAM *)(xdrs->x_private);
	ptrdiff_t current;

	while (len > 0) {
		current = rstrm->out_boundry - rstrm->out_finger;
		current = (len < current) ? len : current;
		bcopy(addr, rstrm->out_finger, current);
		rstrm->out_finger += current;
		addr += current;
		len -= current;
		if (rstrm->out_finger == rstrm->out_boundry) {
			rstrm->frag_sent = TRUE;
			if (! flush_out(rstrm, FALSE))
				return (FALSE);
		}
	}
	return (TRUE);
}

static uint_t
xdrrec_getpos(XDR *xdrs)
{
	RECSTREAM *rstrm = (RECSTREAM *)xdrs->x_private;
	int32_t pos;

	pos = lseek((int)(intptr_t)rstrm->tcp_handle, 0, 1);
	if (pos != -1)
		switch (xdrs->x_op) {

		case XDR_ENCODE:
			pos += rstrm->out_finger - rstrm->out_base;
			break;

		case XDR_DECODE:
			pos -= rstrm->in_boundry - rstrm->in_finger;
			break;

		default:
			pos = (uint_t)-1;
			break;
		}
	return ((uint_t)pos);
}

static bool_t
xdrrec_setpos(XDR *xdrs, uint_t pos)
{
	RECSTREAM *rstrm = (RECSTREAM *)xdrs->x_private;
	uint_t currpos = xdrrec_getpos(xdrs);
	int delta = currpos - pos;
	caddr_t newpos;

	if ((int)currpos != -1)
		switch (xdrs->x_op) {

		case XDR_ENCODE:
			newpos = rstrm->out_finger - delta;
			if ((newpos > (caddr_t)(rstrm->frag_header)) &&
				(newpos < rstrm->out_boundry)) {
				rstrm->out_finger = newpos;
				return (TRUE);
			}
			break;

		case XDR_DECODE:
			newpos = rstrm->in_finger - delta;
			if ((delta < (int)(rstrm->fbtbc)) &&
				(newpos <= rstrm->in_boundry) &&
				(newpos >= rstrm->in_base)) {
				rstrm->in_finger = newpos;
				rstrm->fbtbc -= delta;
				return (TRUE);
			}
			break;
		}
	return (FALSE);
}

static int32_t *
xdrrec_inline(XDR *xdrs, int len)
{
	RECSTREAM *rstrm = (RECSTREAM *)xdrs->x_private;
	int32_t *buf = NULL;

	switch (xdrs->x_op) {

	case XDR_ENCODE:
		if ((rstrm->out_finger + len) <= rstrm->out_boundry) {
			buf = (int32_t *)rstrm->out_finger;
			rstrm->out_finger += len;
		}
		break;

	case XDR_DECODE:
		if ((len <= rstrm->fbtbc) &&
			((rstrm->in_finger + len) <= rstrm->in_boundry)) {
			buf = (int32_t *)rstrm->in_finger;
			rstrm->fbtbc -= len;
			rstrm->in_finger += len;
		}
		break;
	}
	return (buf);
}

static void
xdrrec_destroy(XDR *xdrs)
{
	RECSTREAM *rstrm = (RECSTREAM *)xdrs->x_private;

	mem_free(rstrm->the_buffer,
		rstrm->sendsize + rstrm->recvsize + BYTES_PER_XDR_UNIT);
	mem_free((caddr_t)rstrm, sizeof (RECSTREAM));
}


/*
 * Exported routines to manage xdr records
 */

/*
 * Before reading (deserializing from the stream, one should always call
 * this procedure to guarantee proper record alignment.
 */
bool_t
xdrrec_skiprecord(XDR *xdrs)
{
	RECSTREAM *rstrm = (RECSTREAM *)(xdrs->x_private);

	while (rstrm->fbtbc > 0 || (! rstrm->last_frag)) {
		if (! skip_input_bytes(rstrm, rstrm->fbtbc))
			return (FALSE);
		rstrm->fbtbc = 0;
		if ((! rstrm->last_frag) && (! set_input_fragment(rstrm)))
			return (FALSE);
	}
	rstrm->last_frag = FALSE;
	return (TRUE);
}

#ifdef notneeded
/*
 * Look ahead fuction.
 * Returns TRUE iff there is no more input in the buffer
 * after consuming the rest of the current record.
 */
bool_t
xdrrec_eof(XDR *xdrs)
{
	RECSTREAM *rstrm = (RECSTREAM *)(xdrs->x_private);

	while (rstrm->fbtbc > 0 || (! rstrm->last_frag)) {
		if (! skip_input_bytes(rstrm, rstrm->fbtbc))
			return (TRUE);
		rstrm->fbtbc = 0;
		if ((! rstrm->last_frag) && (! set_input_fragment(rstrm)))
			return (TRUE);
	}
	if (rstrm->in_finger == rstrm->in_boundry)
		return (TRUE);
	return (FALSE);
}
#endif /* notneeded */

/*
 * The client must tell the package when an end-of-record has occurred.
 * The second paraemters tells whether the record should be flushed to the
 * (output) tcp stream.  (This let's the package support batched or
 * pipelined procedure calls.)  TRUE => immmediate flush to tcp connection.
 */
bool_t
xdrrec_endofrecord(XDR *xdrs, bool_t sendnow)
{
	RECSTREAM *rstrm = (RECSTREAM *)(xdrs->x_private);
	ptrdiff_t len;  /* fragment length */

	if (sendnow || rstrm->frag_sent ||
		((ptrdiff_t)rstrm->out_finger + sizeof (uint32_t)
		    >= (ptrdiff_t)rstrm->out_boundry)) {
		rstrm->frag_sent = FALSE;
		return (flush_out(rstrm, TRUE));
	}
	len = (ptrdiff_t)rstrm->out_finger - (ptrdiff_t)rstrm->frag_header;
	len -= sizeof (uint32_t);
	*(rstrm->frag_header) = htonl((uint32_t)len | LAST_FRAG);
	rstrm->frag_header = (uint32_t *)rstrm->out_finger;
	rstrm->out_finger += sizeof (uint32_t);
	return (TRUE);
}


/*
 * Internal useful routines
 */
static bool_t
flush_out(RECSTREAM *rstrm, bool_t eor)
{
	uint32_t eormask = (eor == TRUE) ? LAST_FRAG : 0;
	ptrdiff_t len;

	len = (ptrdiff_t)rstrm->out_finger - (ptrdiff_t)rstrm->frag_header;
	len -= sizeof (uint32_t);

	*(rstrm->frag_header) = htonl(len | eormask);
	len = rstrm->out_finger - rstrm->out_base;
	if ((*(rstrm->writeit))(rstrm->tcp_handle, rstrm->out_base, (int)len)
	    != (int)len)
		return (FALSE);

	rstrm->frag_header = (uint32_t *)rstrm->out_base;
	rstrm->out_finger = (caddr_t)rstrm->out_base + sizeof (uint32_t);
	return (TRUE);
}

static bool_t  /* knows nothing about records!  Only about input buffers */
fill_input_buf(RECSTREAM *rstrm, int frag_len)
{
	caddr_t where;
	uintptr_t i;
	int len;

	where = rstrm->in_base;
	i = (uintptr_t)rstrm->in_boundry % BYTES_PER_XDR_UNIT;
	where += i;
	len = (frag_len < (rstrm->in_size - i)) ? frag_len :
		rstrm->in_size - i;
#ifdef DEBUG
	printf("fill_input_buf: len = %d\n", len);
#endif
	if ((len = (*(rstrm->readit))(rstrm->tcp_handle, where, len)) == -1)
		return (FALSE);
	rstrm->in_finger = where;
	where += len;
	rstrm->in_boundry = where;
	return (TRUE);
}

static bool_t
get_input_bytes(RECSTREAM *rstrm, caddr_t addr, int frag_len, int len)
{
	ptrdiff_t current;

	while (len > 0) {
		current = rstrm->in_boundry - rstrm->in_finger;
#ifdef DEBUG
	printf("get_input_bytes: len = %d, frag_len = %d, current %d\n",
		len, frag_len, current);
#endif
		/*
		 * set_input_bytes doesn't know how large the fragment is, we
		 * need to get the header so just grab a header's size worth
		 */
		if (frag_len == 0)
			frag_len = len;

		if (current == 0) {
			if (! fill_input_buf(rstrm, frag_len))
				return (FALSE);
			continue;
		}

		current = (len < current) ? len : current;
		bcopy(rstrm->in_finger, addr, current);
		rstrm->in_finger += current;
		addr += current;
		len -= current;
	}
	return (TRUE);
}

static bool_t  /* next four bytes of the input stream are treated as a header */
set_input_fragment(RECSTREAM *rstrm)
{
	uint32_t header;

	if (! get_input_bytes(rstrm, (caddr_t)&header, 0, sizeof (header)))
		return (FALSE);
	header = (uint32_t)ntohl(header);
	rstrm->last_frag = ((header & LAST_FRAG) == 0) ? FALSE : TRUE;
	rstrm->fbtbc = header & (~LAST_FRAG);
#ifdef DEBUG
	printf("set_input_fragment: frag_len = %d, last frag = %s\n",
		rstrm->fbtbc, rstrm->last_frag ? "TRUE" : "FALSE");
#endif
	return (TRUE);
}

static bool_t  /* consumes input bytes; knows nothing about records! */
skip_input_bytes(RECSTREAM *rstrm, int32_t cnt)
{
	ptrdiff_t current;
#ifdef DEBUG
	printf("skip_input_fragment: cnt = %d\n", cnt);
#endif
	while (cnt > 0) {
		current = rstrm->in_boundry - rstrm->in_finger;
		if (current == 0) {
			if (! fill_input_buf(rstrm, cnt))
				return (FALSE);
			continue;
		}
		current = (cnt < current) ? cnt : current;
		rstrm->in_finger += current;
		cnt -= current;
	}
	return (TRUE);
}

static uint_t
fix_buf_size(uint_t s)
{

	if (s < 100)
		s = 4000;
	return (RNDUP(s));
}

static struct xdr_ops *
xdrrec_ops()
{
	static struct xdr_ops ops;

	if (ops.x_getint32 == NULL) {
		ops.x_getint32 = xdrrec_getint32;
		ops.x_putint32 = xdrrec_putint32;
		ops.x_getbytes = xdrrec_getbytes;
		ops.x_putbytes = xdrrec_putbytes;
		ops.x_getpostn = xdrrec_getpos;
		ops.x_setpostn = xdrrec_setpos;
		ops.x_inline = xdrrec_inline;
		ops.x_destroy = xdrrec_destroy;
	}

	return (&ops);
}
#!/bin/sh
#
# 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 2003 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# ident	"%Z%%M%	%I%	%E% SMI"

echo_file usr/src/stand/lib/fs/Makefile.com
#
# 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 2004 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# ident	"%Z%%M%	%I%	%E% SMI"
#

LIBRARY = libufs.a
OBJECTS = ufsops.o lufsboot.o

include	../Makefile.com

include ../../Makefile.targ
/*
 * 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.
 */

#include <sys/param.h>
#include <sys/vnode.h>
#include <sys/fs/ufs_fsdir.h>
#include <sys/fs/ufs_fs.h>
#include <sys/fs/ufs_inode.h>
#include <sys/fs/ufs_log.h>
#include <sys/sysmacros.h>
#include <sys/promif.h>
#include <sys/machparam.h>

#include <sys/stat.h>
#include <sys/bootdebug.h>
#include <sys/salib.h>
#include <sys/saio.h>
#include <sys/filep.h>


/*
 * Big theory statement on how ufsboot makes use of the log
 * in case the filesystem wasn't shut down cleanly.
 *
 * The structure of the ufs on-disk log looks like this:
 *
 * +-----------------+
 * | SUPERBLOCK      |
 * | ...             |
 * | fs_logbno       +--> +-----------------------+
 * | ...             |    | EXTENT BLOCK          |
 * +-----------------+    |   ...                 |
 *                        |   nextents            |
 * +----------------------+   extents[0].pbno     |
 * |                      | { extents[1].pbno }   +------------+
 * |                      |   ...                 +--> ...     |
 * |                      +-----------------------+            |
 * v                                                           |
 * +-----------------------------+      \                      |
 * | ON-DISK LOG HEADER          |      |                      |
 * | ...                         |      |                      |
 * | od_head_lof                 +--+   |                      |
 * | ...                         |  |   |                      |
 * +-----------------------------+ <|---|- od_bol_lof          |
 * | sector (may contain deltas) |  |   |  (logical offset)    |
 * |   +-------------------------+  |   |                      |
 * |   | trailer (some ident#)   |  |    > extents[0].nbno     |
 * +---+-------------------------+  |   |  blocks ("sectors")  |
 * .                             .  |   |                      |
 * .                             .  |   |                      |
 * +-----------------------------+<-+   |                      |
 * | delta1 delta2       delta3  |      |                      |
 * | d +-------------------------+      |                      |
 * | e | ident#: od_head_ident   |      |                      |
 * +---+-------------------------+      /                      |
 *                                                             |
 * +-----------------------------+ <---------------------------+
 * | lta4    delta5 delta6    de |
 * | l +-------------------------+
 * | t | ident#: od_head_ident+1 |
 * +---+-------------------------+
 * .                             .
 * +-----------------------------+
 * | sector (may contain deltas) |
 * |          +------------------+
 * |          | trailer (ident#) |
 * +----------+------------------+ <-- od_eol_lof (logical offset)
 *
 * The ufs on-disk log has the following properties:
 *
 * 1. The log is made up from at least one extent. "fs_logbno" in
 *    the superblock points to where this is found.
 * 2. Extents describe the logical layout.
 *      - Logical offset 0 is the on-disk log header. It's also
 *        at the beginning of the first physical block.
 *      - If there's more than one extent, the equation holds:
 *             extent[i+1].lbno == extent[i].lbno + extent[i].nbno
 *        i.e. logical offsets form a contiguous sequence. Yet on disk,
 *        two logically-adjacent offsets may be located in two
 *        physically disjoint extents, so logical offsets need to be
 *        translated into physical disk block addresses for access.
 *      - Various fields in the on-disk log header structure refer
 *        to such logical log offsets.
 * 3. The actual logical logspace begins after the log header, at
 *    the logical offset indicated by "od_bol_lof". Every 512 Bytes
 *    (a "sector" in terms of ufs logging) is a sector trailer which
 *    contains a sequence number, the sector ident.
 * 4. Deltas are packed tight in the remaining space, i.e. a delta
 *    may be part of more than one sector. Reads from the logspace
 *    must be split at sector boundaries, since the trailer is never
 *    part of a delta. Delta sizes vary.
 * 5. The field "od_head_lof" points to the start of the dirty part
 *    of the log, i.e. to the first delta header. Likewise, "od_head_ident"
 *    is the sequence number where the valid part of the log starts; if
 *    the sector pointed to by "od_head_lof" has a sector ident different
 *    from "od_head_ident", the log is empty.
 * 6. The valid part of the log extends for as many sectors as their ident
 *    numbers form a contiguous sequence. When reaching the logical end of
 *    the log, "od_bol_lof", logical offsets wrap around to "od_bol_lof",
 *    i.e. the log forms a circular buffer.
 *
 * For the strategy how to handle accessing the log, item 4. is the
 * most important one - its consequence is that the log can only be
 * read in one direction - forward, starting at the head.
 *
 * The task of identifying whether a given metadata block is
 * actually in the log therefore requires reading the entire
 * log. Doing so is memory-efficient but kills speed if re-done
 * at every metadata read (64MB log size vs. 512 byte metadata
 * block size: 128 times as much I/O, possibly only to find out
 * that this block was not in the log ...).
 *
 * First thought to speed this up is to let ufsboot roll the log.
 * But this is not possible because:
 * - ufsboot currently does not implement any write functionality,
 *   the boot-time ufs implementation is read-only.
 * - firmware write interfaces may or may not be available, in any
 *   case, they're rarely used and untested for such a purpose.
 * - that would duplicate a lot of code, since at the moment only
 *   kernel ufs logging implements log rolling.
 * - the boot environment cannot be considered high-performance;
 *   rolling the log there would be slow.
 * - boot device and root device could well be different, creating
 *   inconsistencies e.g. with a mirrored root if the log is rolled.
 *
 * Therefore, caching the log structural information (boot-relevant
 * deltas and their logical log offset) is required for fast access
 * to the data in the log. This code builds a logmap for that purpose.
 *
 * As a simple optimization, if we find the log is empty, we will not
 * use it - log reader support for ufsboot has no noticeable overhead
 * for clean logs, or for root filesystems that aren't logging.
 */

#define	LB_HASHSHIFT		13
#define	LB_HASHSIZE		(1 << LB_HASHSHIFT)
#define	LB_HASHFUNC(mof)	(((mof) >> LB_HASHSHIFT) & (LB_HASHSIZE - 1))

#define	LOGBUF_MAXSIZE	(8*1024*1024)
#define	LOGBUF_MINSIZE	(256*1024)

#define	LOG_IS_EMPTY	0
#define	LOG_IS_OK	1
#define	LOG_IS_ERRORED	2

/*
 * We build a hashed logmap of those while scanning the log.
 * sizeof(lb_map_t) is 40 on 64bit, 32 on 32bit; the max sized
 * resalloc'ed buffer can accomodate around ~500k of those;
 * this is approximately the maximum amount of deltas we'll
 * see if a 64MB ufs log is completely filled. We'll make no
 * attempt to free and reallocate the resalloc'ed buffer if
 * we overflow, as conservative sizing should make that an
 * impossibility. A future enhancement may allocate memory
 * here as needed - once the boot time memory allocator
 * supports that.
 */
typedef struct lb_mapentry {
	struct lb_mapentry	*l_next;	/* hash chaining */
	struct lb_mapentry	*l_prev;	/* hash chaining */
	int64_t		l_mof;		/* disk addr this delta is against */
	int16_t		l_nb;		/* size of delta */
	int16_t		l_flags;
	int32_t		l_lof;		/* log offset for delta header */
	int32_t		l_tid;		/* transaction this delta is part of */
	delta_t		l_typ;		/* see <sys/fs/ufs_trans.h> */
} lb_me_t;

#define	LB_ISCANCELLED	1

#define	inslist(lh, l)	if ((*(lh))) {				\
				(*(lh))->l_prev->l_next = (l);	\
				(l)->l_next = (*(lh));		\
				(l)->l_prev = (*(lh))->l_prev;	\
				(*(lh))->l_prev = (l);		\
			} else {				\
				(l)->l_next = (l);		\
				(l)->l_prev = (l);		\
				(*(lh)) = l;			\
			}

#define	remlist(lh, l)	\
	if ((l)->l_next == (l)) {			\
		if (*(lh) != (l) || (l)->l_prev != (l))	\
			dprintf("Logmap hash inconsistency.\n");	\
		*(lh) = (lb_me_t *)NULL;		\
	} else {					\
		if (*(lh) == (l))			\
			*(lh) = (l)->l_next;		\
		(l)->l_prev->l_next = (l)->l_next;	\
		(l)->l_next->l_prev = (l)->l_prev;	\
	}

#define	lufs_alloc_me()	\
	(lb_me_t *)lufs_alloc_from_logbuf(sizeof (lb_me_t))

extern int		boothowto;
static int		ufs_is_lufs = 0;
static fileid_t		*logfp = (fileid_t *)NULL;
static extent_block_t	*eb = (extent_block_t *)NULL;
static ml_odunit_t	odi;

static char		logbuffer_min[LOGBUF_MINSIZE];
static caddr_t		logbuffer = (caddr_t)NULL;
static caddr_t		elogbuffer = (caddr_t)NULL;
static caddr_t		logbuf_curptr;
static lb_me_t		**loghash = (lb_me_t **)NULL;
static lb_me_t		*lfreelist;

static uint32_t		curtid;


int	lufs_support = 1;

void	lufs_boot_init(fileid_t *);
void	lufs_closeall(void);
void	lufs_merge_deltas(fileid_t *);

static	int	lufs_logscan(void);

extern	int	diskread(fileid_t *filep);
extern	caddr_t	resalloc(enum RESOURCES, size_t, caddr_t, int);

#if defined(__sparcv9)
#define	LOGBUF_BASEADDR	((caddr_t)(SYSBASE - LOGBUF_MAXSIZE))
#endif

static int
lufs_alloc_logbuf(void)
{
	/*
	 * Allocate memory for caching the log. Since the logbuffer can
	 * potentially exceed the boot scratch memory limit, we use resalloc
	 * directly, passing the allocation to the low-level boot-time
	 * backend allocator. The chosen VA range is the top end of
	 * the kernel's segmap segment, so we're not interfering
	 * with the kernel because segmap is created at a time when
	 * the 2nd-stage boot has already been unloaded and this VA
	 * range was given back.
	 *
	 * On sparc platforms, the kernel cannot recover the memory
	 * obtained from resalloc because the page structs are allocated
	 * before the call to BOP_QUIESCE. To avoid leaking this
	 * memory, the logbuffer is allocated from a small bss array
	 * that should hold the logmap except in the most extreme cases.
	 * If the bss array is too small, the logbuffer is extended
	 * from resalloc 1 page at a time.
	 */

	logbuffer = logbuffer_min;
	elogbuffer = logbuffer+LOGBUF_MINSIZE;
	logbuf_curptr = logbuffer;
	lfreelist = (lb_me_t *)NULL;

	if (logbuffer == (caddr_t)NULL)
		return (0);

	dprintf("Buffer for boot loader logging support: 0x%p, size 0x%x\n",
	    logbuffer, elogbuffer-logbuffer);

	return (1);
}

static void
lufs_free_logbuf()
{
	/*
	 * Solaris/x86 has no prom_free() routine at this time.
	 * Reclaiming the VA range below KERNEL_TEXT on Solaris/x86
	 * is done by the kernel startup itself, in hat_unload_prom()
	 * after the bootloader has been quiesced.
	 *
	 * Solaris on sparc has a prom_free() routine that will update
	 *   the memlist properties to reflect the freeing of the
	 *   logbuffer. However, the sparc kernel cannot recover
	 *   the memory freed after the call to BOP_QUIESCE as the
	 *   page struct have already been allocated. We call
	 *   prom_free anyway so that the kernel can reclaim this
	 *   memory in the future.
	 */
	if (logbuffer == LOGBUF_BASEADDR)
		prom_free(logbuffer, elogbuffer-logbuffer);
	logbuffer = (caddr_t)NULL;
}

static caddr_t
lufs_alloc_from_logbuf(size_t sz)
{
	caddr_t tmpaddr;
	lb_me_t	*l;

	/*
	 * Satisfy lb_me_t allocations from the freelist
	 * first if possible.
	 */
	if ((sz == sizeof (lb_me_t)) && lfreelist) {
		l = lfreelist;
		lfreelist = lfreelist->l_next;
		return ((caddr_t)l);
	}
	if (elogbuffer < logbuf_curptr + sz) {
		caddr_t np;
		size_t nsz;

		/*
		 * Out of space in current chunk - try to add another.
		 */
		if (logbuffer == logbuffer_min) {
			np = LOGBUF_BASEADDR;
		} else {
			np = elogbuffer;
		}
		nsz = roundup(sz, PAGESIZE);
		if (np + nsz > LOGBUF_BASEADDR + LOGBUF_MAXSIZE) {
			return ((caddr_t)NULL);
		}

		np = resalloc(RES_CHILDVIRT, nsz, np, 0UL);
		if (np == (caddr_t)NULL) {
			return ((caddr_t)NULL);
		}
		if (logbuffer == logbuffer_min)
			logbuffer = LOGBUF_BASEADDR;
		logbuf_curptr = np;
		elogbuffer = logbuf_curptr + nsz;
	}

	tmpaddr = logbuf_curptr;
	logbuf_curptr += sz;
	bzero(tmpaddr, sz);
	return (tmpaddr);
}

static int32_t
lufs_read_log(int32_t addr, caddr_t va, int nb)
{
	int		i, fastpath = 0;
	daddr_t		pblk, lblk;
	sect_trailer_t	*st;
	uint32_t	ident;

	/*
	 * Fast path for skipping the read if no target buffer
	 * is specified. Don't do this for the initial scan.
	 */
	if (ufs_is_lufs && (va == (caddr_t)NULL))
		fastpath = 1;

	while (nb) {
		/* log wraparound check */
		if (addr == odi.od_eol_lof)
			addr = odi.od_bol_lof;
		if (fastpath)
			goto read_done;

		/*
		 * Translate logically-contiguous log offsets into physical
		 * block numbers. For a log consisting of a single extent:
		 *	pbno = btodb(addr) - extents[0].lbno;
		 * Otherwise, search for the extent which contains addr.
		 */
		pblk = 0;
		lblk = btodb(addr);
		for (i = 0; i < eb->nextents; i++) {
			if (lblk >= eb->extents[i].lbno &&
			    lblk < eb->extents[i].lbno +
			    eb->extents[i].nbno) {
				pblk = lblk - eb->extents[i].lbno +
				    eb->extents[i].pbno;
				break;
			}
		}

		if (pblk == 0) {
			/*
			 * block #0 can never be in a log extent since this
			 * block always contains the primary superblock copy.
			 */
			dprintf("No log extent found for log offset 0x%llx.\n",
			    addr);
			return (0);
		}

		/*
		 * Check whether the block we want is cached from the last
		 * read. If not, read it in now.
		 */
		if (logfp->fi_blocknum != pblk) {
			logfp->fi_blocknum = pblk;
			logfp->fi_memp = logfp->fi_buf;
			logfp->fi_count = DEV_BSIZE;
			logfp->fi_offset = 0;
			if (diskread(logfp)) {
				dprintf("I/O error reading the ufs log" \
				    " at block 0x%x.\n",
				    logfp->fi_blocknum);
				return (0);
			}
			/*
			 * Log structure verification. The block which we just
			 * read has an ident number that must match its offset
			 * in blocks from the head of the log. Since the log
			 * can wrap around, we have to check for that to get the
			 * ident right. Out-of-sequence idents can happen after
			 * power failures, panics during a partial transaction,
			 * media errors, ... - in any case, they mark the end of
			 * the valid part of the log.
			 */
			st = (sect_trailer_t *)(logfp->fi_memp +
			    LDL_USABLE_BSIZE);
			/* od_head_ident is where the sequence starts */
			ident = odi.od_head_ident;
			if (lblk >= lbtodb(odi.od_head_lof)) {
				/* no wraparound */
				ident += (lblk - lbtodb(odi.od_head_lof));
			} else {
				/* log wrapped around the end */
				ident += (lbtodb(odi.od_eol_lof) -
				    lbtodb(odi.od_head_lof));
				ident += (lblk - lbtodb(odi.od_bol_lof));
			}

			if (ident != st->st_ident)
				return (0);
		}
read_done:
		/*
		 * Copy the delta contents to the destination buffer if
		 * one was specified. Otherwise, just skip the contents.
		 */
		i = MIN(NB_LEFT_IN_SECTOR(addr), nb);
		if (va != NULL) {
			bcopy(logfp->fi_buf + (addr - ldbtob(lbtodb(addr))),
			    va, i);
			va += i;
		}
		nb -= i;
		addr += i;
		/*
		 * Skip sector trailer if necessary.
		 */
		if (NB_LEFT_IN_SECTOR(addr) == 0)
			addr += sizeof (sect_trailer_t);
	}
	return (addr);
}

void
lufs_boot_init(fileid_t *filep)
{
	struct fs *sb = (struct fs *)filep->fi_memp;
	int err = 0;

	/*
	 * boot_ufs_mountroot() should have called us with a
	 * filep pointing to the superblock. Verify that this
	 * is so first.
	 * Then check whether this filesystem has a dirty log.
	 * Also return if lufs support was disabled on request.
	 */
	if (!lufs_support ||
	    sb != (struct fs *)&filep->fi_devp->un_fs.di_fs ||
	    sb->fs_clean != FSLOG || sb->fs_logbno == 0) {
		return;
	}

	if (boothowto & RB_VERBOSE)
		printf("The boot filesystem is logging.\n");

	/*
	 * The filesystem is logging, there is a log area
	 * allocated for it. Check the log state and determine
	 * whether it'll be possible to use this log.
	 */

	/*
	 * Allocate a private fileid_t for use when reading
	 * from the log.
	 */
	eb = (extent_block_t *)bkmem_zalloc(sb->fs_bsize);
	logfp = (fileid_t *)bkmem_zalloc(sizeof (fileid_t));
	logfp->fi_memp = logfp->fi_buf;
	logfp->fi_devp = filep->fi_devp;

	/*
	 * Read the extent block and verify that what we
	 * find there are actually lufs extents.
	 * Make it simple: the extent block including all
	 * extents cannot be larger than a filesystem block.
	 * So read a whole filesystem block, to make sure
	 * we have read all extents in the same operation.
	 */
	logfp->fi_blocknum = sb->fs_logbno;
	logfp->fi_count = sb->fs_bsize;
	logfp->fi_memp = (caddr_t)eb;
	logfp->fi_offset = 0;
	if (diskread(logfp) || eb->type != LUFS_EXTENTS) {
		dprintf("Failed to read log extent block.\n");
		err = LOG_IS_ERRORED;
		goto out;
	}

	/*
	 * Read the on disk log header. If that fails,
	 * try the backup copy on the adjacent block.
	 */
	logfp->fi_blocknum = eb->extents[0].pbno;
	logfp->fi_count = sizeof (ml_odunit_t);
	logfp->fi_memp = (caddr_t)&odi;
	logfp->fi_offset = 0;
	if (diskread(logfp)) {
		logfp->fi_blocknum = eb->extents[0].pbno + 1;
		logfp->fi_count = sizeof (ml_odunit_t);
		logfp->fi_memp = (caddr_t)&odi;
		logfp->fi_offset = 0;
		if (diskread(logfp)) {
			dprintf("Failed to read on-disk log header.\n");
			err = LOG_IS_ERRORED;
			goto out;
		}
	}

	/*
	 * Verify that we understand this log, and
	 * that the log isn't bad or empty.
	 */
	if (odi.od_version != LUFS_VERSION_LATEST) {
		dprintf("On-disk log format v%d != supported format v%d.\n",
		    odi.od_version, LUFS_VERSION_LATEST);
		err = LOG_IS_ERRORED;
	} else if (odi.od_badlog) {
		dprintf("On-disk log is marked bad.\n");
		err = LOG_IS_ERRORED;
	} else if (odi.od_chksum != odi.od_head_ident + odi.od_tail_ident) {
		dprintf("On-disk log checksum %d != ident sum %d.\n",
		    odi.od_chksum, odi.od_head_ident + odi.od_tail_ident);
		err = LOG_IS_ERRORED;
	} else {
		/*
		 * All consistency checks ok. Scan the log, build the
		 * log hash. If this succeeds we'll be using the log
		 * when reading from this filesystem.
		 */
		err = lufs_logscan();
	}
out:
	ufs_is_lufs = 1;
	switch (err) {
	case LOG_IS_EMPTY:
		if (boothowto & RB_VERBOSE)
			printf("The ufs log is empty and will not be used.\n");
		lufs_closeall();
		break;
	case LOG_IS_OK:
		if (boothowto & RB_VERBOSE)
			printf("Using the ufs log.\n");
		break;
	case LOG_IS_ERRORED:
		if (boothowto & RB_VERBOSE)
			printf("Couldn't build log hash. Can't use ufs log.\n");
		lufs_closeall();
		break;
	default:
		dprintf("Invalid error %d while scanning the ufs log.\n", err);
		break;
	}
}

static int
lufs_logscan_read(int32_t *addr, struct delta *d)
{
	*addr = lufs_read_log(*addr, (caddr_t)d, sizeof (struct delta));

	if (*addr == 0 ||
	    (int)d->d_typ < DT_NONE || d->d_typ > DT_MAX ||
	    d->d_nb >= odi.od_logsize)
		return (0);

	return (1);
}

static int
lufs_logscan_skip(int32_t *addr, struct delta *d)
{
	switch (d->d_typ) {
	case DT_COMMIT:
		/*
		 * A DT_COMMIT delta has no size as such, but will
		 * always "fill up" the sector that contains it.
		 * The next delta header is found at the beginning
		 * of the next 512-Bytes sector, adjust "addr" to
		 * reflect that.
		 */
		*addr += ((*addr & (DEV_BSIZE - 1))) ?
		    NB_LEFT_IN_SECTOR(*addr) +
		    sizeof (sect_trailer_t) : 0;
		return (1);
	case DT_CANCEL:
	case DT_ABZERO:
		/*
		 * These types of deltas occupy no space in the log
		 */
		return (1);
	default:
		/*
		 * Skip over the delta contents.
		 */
		*addr = lufs_read_log(*addr, NULL, d->d_nb);
	}

	return (*addr != 0);
}

static void
lufs_logscan_freecancel(void)
{
	lb_me_t		**lh, *l, *lnext;
	int		i;

	/*
	 * Walk the entire log hash and put cancelled entries
	 * onto the freelist. Corner cases:
	 * a) empty hash chain (*lh == NULL)
	 * b) only one entry in chain, and that is cancelled.
	 *    If for every cancelled delta another one would've
	 *    been added, this situation couldn't occur, but a
	 *    DT_CANCEL delta can lead to this as it is never
	 *    added.
	 */
	for (i = 0; i < LB_HASHSIZE; i++) {
		lh = &loghash[i];
		l = *lh;
		do {
			if (*lh == (lb_me_t *)NULL)
				break;
			lnext = l->l_next;
			if (l->l_flags & LB_ISCANCELLED) {
				remlist(lh, l);
				bzero((caddr_t)l, sizeof (lb_me_t));
				l->l_next = lfreelist;
				lfreelist = l;
				/*
				 * Just removed the hash head. In order not
				 * to terminate the while loop, respin chain
				 * walk for this hash chain.
				 */
				if (lnext == *lh) {
					i--;
					break;
				}
			}
			l = lnext;
		} while (l != *lh);
	}
}

static int
lufs_logscan_addmap(int32_t *addr, struct delta *d)
{
	lb_me_t		**lh, *l;

	switch (d->d_typ) {
	case DT_COMMIT:
		/*
		 * Handling DT_COMMIT deltas is special. We need to:
		 * 1. increase the transaction ID
		 * 2. remove cancelled entries.
		 */
		lufs_logscan_freecancel();
		curtid++;
		break;
	case DT_INODE:
		/*
		 * Deltas against parts of on-disk inodes are
		 * assumed to be timestamps. Ignore those.
		 */
		if (d->d_nb != sizeof (struct dinode))
			break;
		/* FALLTHROUGH */
	case DT_CANCEL:
	case DT_ABZERO:
	case DT_AB:
	case DT_DIR:
	case DT_FBI:
		/*
		 * These types of deltas contain and/or modify structural
		 * information that is needed for booting the system:
		 * - where to find a file (DT_DIR, DT_FBI)
		 * - the file itself (DT_INODE)
		 * - data blocks associated with a file (DT_AB, DT_ABZERO)
		 *
		 * Building the hash chains becomes complicated because there
		 * may exist an older (== previously added) entry that overlaps
		 * with the one we want to add.
		 * Four cases must be distinguished:
		 * 1. The new delta is an exact match for an existing one,
		 *    or is a superset of an existing one, and both
		 *    belong to the same transaction.
		 *    The new delta completely supersedes the old one, so
		 *    remove that and reuse the structure for the new.
		 *    Then add the new delta to the head of the hashchain.
		 * 2. The new delta is an exact match for an existing one,
		 *    or is a superset of an existing one, but the two
		 *    belong to different transactions (i.e. the old one is
		 *    committed).
		 *    The existing one is marked to be cancelled when the
		 *    next DT_COMMIT record is found, and the hash chain
		 *    walk is continued as there may be more existing entries
		 *    found which overlap the new delta (happens if that is
		 *    a superset of those in the log).
		 *    Once no more overlaps are found, goto 4.
		 * 3. An existing entry completely covers the new one.
		 *    The new delta is then added directly before this
		 *    existing one.
		 * 4. No (more) overlaps with existing entries are found.
		 *    Unless this is a DT_CANCEL delta, whose only purpose
		 *    is already handled by marking overlapping entries for
		 *    cancellation, add the new delta at the hash chain head.
		 *
		 * This strategy makes sure that the hash chains are properly
		 * ordered. lufs_merge_deltas() walks the hash chain backward,
		 * which then ensures that delta merging is done in the same
		 * order as those deltas occur in the log - remember, the
		 * log can only be read in one direction.
		 *
		 */
		lh = &loghash[LB_HASHFUNC(d->d_mof)];
		l = *lh;
		do {
			if (l == (lb_me_t *)NULL)
				break;
			/*
			 * This covers the first two cases above.
			 * If this is a perfect match from the same transaction,
			 * and it isn't already cancelled, we simply replace it
			 * with its newer incarnation.
			 * Otherwise, mark it for cancellation. Handling of
			 * DT_COMMIT is going to remove it, then.
			 */
			if (WITHIN(l->l_mof, l->l_nb, d->d_mof, d->d_nb)) {
				if (!(l->l_flags & LB_ISCANCELLED)) {
					if (l->l_tid == curtid &&
					    d->d_typ != DT_CANCEL) {
						remlist(lh, l);
						l->l_mof = d->d_mof;
						l->l_lof = *addr;
						l->l_nb = d->d_nb;
						l->l_typ = d->d_typ;
						l->l_flags = 0;
						l->l_tid = curtid;
						inslist(lh, l);
						return (1);
					} else {
						/*
						 * 2nd case - cancel only.
						 */
						l->l_flags |= LB_ISCANCELLED;
					}
				}
			} else if (WITHIN(d->d_mof, d->d_nb,
			    l->l_mof, l->l_nb)) {
				/*
				 * This is the third case above.
				 * With deltas DT_ABZERO/DT_AB and DT_FBI/DT_DIR
				 * this may happen - an existing previous delta
				 * is larger than the current one we're planning
				 * to add - DT_ABZERO deltas are supersets of
				 * DT_AB deltas, and likewise DT_FBI/DT_DIR.
				 * In order to do merging correctly, such deltas
				 * put up a barrier for new ones that overlap,
				 * and we have to add the new delta immediately
				 * before (!) the existing one.
				 */
				lb_me_t *newl;
				newl = lufs_alloc_me();
				if (newl == (lb_me_t *)NULL) {
					/*
					 * No memory. Throw away everything
					 * and try booting without logging
					 * support.
					 */
					curtid = 0;
					return (0);
				}
				newl->l_mof = d->d_mof;
				newl->l_lof = *addr;	/* "payload" address */
				newl->l_nb = d->d_nb;
				newl->l_typ = d->d_typ;
				newl->l_tid = curtid;
				newl->l_prev = l->l_prev;
				newl->l_next = l;
				l->l_prev->l_next = newl;
				l->l_prev = newl;
				if (*lh == l)
					*lh = newl;
				return (1);
			}
			l = l->l_next;
		} while (l != *lh);

		/*
		 * This is case 4., add a new delta at the head of the chain.
		 *
		 * If the new delta is a DT_CANCEL entry, we handled it by
		 * marking everything it covered for cancellation. We can
		 * get by without actually adding the delta itself to the
		 * hash, as it'd need to be removed by the commit code anyway.
		 */
		if (d->d_typ == DT_CANCEL)
			break;

		l = lufs_alloc_me();
		if (l == (lb_me_t *)NULL) {
			/*
			 * No memory. Throw away everything
			 * and try booting without logging
			 * support.
			 */
			curtid = 0;
			return (0);
		}
		l->l_mof = d->d_mof;
		l->l_lof = *addr;	/* this is the "payload" address */
		l->l_nb = d->d_nb;
		l->l_typ = d->d_typ;
		l->l_tid = curtid;
		inslist(lh, l);
		break;
	default:
		break;
	}
	return (1);
}

static int
lufs_logscan_prescan(void)
{
	/*
	 * Simulate a full log by setting the tail to be one sector
	 * behind the head. This will make the logscan read all
	 * of the log until an out-of-sequence sector ident is
	 * found.
	 */
	odi.od_tail_lof = dbtob(btodb(odi.od_head_lof)) - DEV_BSIZE;
	if (odi.od_tail_lof < odi.od_bol_lof)
		odi.od_tail_lof = odi.od_eol_lof - DEV_BSIZE;
	if (odi.od_tail_lof >= odi.od_eol_lof)
		odi.od_tail_lof = odi.od_bol_lof;

	/*
	 * While sector trailers maintain TID values, od_head_tid
	 * is not being updated by the kernel ufs logging support
	 * at this time. We therefore count transactions ourselves
	 * starting at zero - as does the kernel ufs logscan code.
	 */
	curtid = 0;

	if (!lufs_alloc_logbuf()) {
		dprintf("Failed to allocate log buffer.\n");
		return (0);
	}

	loghash = (lb_me_t **)lufs_alloc_from_logbuf(
	    LB_HASHSIZE * sizeof (lb_me_t *));
	if (loghash == (lb_me_t **)NULL) {
		dprintf("Can't allocate loghash[] array.");
		return (0);
	}
	return (1);
}

/*
 * This function must remove all uncommitted entries (l->l_tid == curtid)
 * from the log hash. Doing this, we implicitly delete pending cancellations
 * as well.
 * It uses the same hash walk algorithm as lufs_logscan_freecancel(). Only
 * the check for entries that need to be removed is different.
 */
static void
lufs_logscan_postscan(void)
{
	lb_me_t	**lh, *l, *lnext;
	int	i;

	for (i = 0; i < LB_HASHSIZE; i++) {
		lh = &loghash[i];
		l = *lh;
		do {
			if (l == (lb_me_t *)NULL)
				break;
			lnext = l->l_next;
			if (l->l_tid == curtid) {
				remlist(lh, l);
				bzero((caddr_t)l, sizeof (lb_me_t));
				l->l_next = lfreelist;
				lfreelist = l;
				if (*lh == (lb_me_t *)NULL)
					break;
				/*
				 * Just removed the hash head. In order not
				 * to terminate the while loop, respin chain
				 * walk for this hash chain.
				 */
				if (lnext == *lh) {
					i--;
					break;
				}
			} else {
				l->l_flags &= ~(LB_ISCANCELLED);
			}
			l = lnext;
		} while (l != *lh);
	}
}

/*
 * This function builds the log hash. It performs the same sequence
 * of actions at logscan as the kernel ufs logging support:
 * - Prepare the log for scanning by simulating a full log.
 * - As long as sectors read from the log have contiguous idents, do:
 *	read the delta header
 *	add the delta to the logmap
 *	skip over the contents to the start of the next delta header
 * - After terminating the scan, remove uncommitted entries.
 *
 * This function cannot fail except if mapping the logbuffer area
 * during lufs_logscan_prescan() fails. If there is a structural
 * integrity problem and the on-disk log cannot be read, we'll
 * treat this as the same situation as an uncommitted transaction
 * at the end of the log (or, corner case of that, an empty log
 * with no committed transactions in it at all).
 *
 */
static int
lufs_logscan(void)
{
	int32_t		addr;
	struct delta	d;

	if (!lufs_logscan_prescan())
		return (LOG_IS_ERRORED);

	addr = odi.od_head_lof;

	/*
	 * Note that addr == od_tail_lof means a completely filled
	 * log. This almost never happens, so the common exit path
	 * from this loop is via one of the 'break's.
	 */
	while (addr != odi.od_tail_lof) {
		if (!lufs_logscan_read(&addr, &d))
			break;
		if (!lufs_logscan_addmap(&addr, &d))
			return (LOG_IS_ERRORED);
		if (!lufs_logscan_skip(&addr, &d))
			break;
	}

	lufs_logscan_postscan();
	/*
	 * Check whether the log contains data, and if so whether
	 * it contains committed data.
	 */
	if (addr == odi.od_head_lof || curtid == 0) {
		return (LOG_IS_EMPTY);
	}
	return (LOG_IS_OK);
}

/*
 * A metadata block was read from disk. Check whether the logmap
 * has a delta against this byte range, and if so read it in, since
 * the data in the log is more recent than what was read from other
 * places on the disk.
 */
void
lufs_merge_deltas(fileid_t *fp)
{
	int		nb;
	int64_t		bof;
	lb_me_t		**lh, *l;
	int32_t		skip;

	/*
	 * No logmap: Empty log. Nothing to do here.
	 */
	if (!ufs_is_lufs || logbuffer == (caddr_t)NULL)
		return;

	bof = ldbtob(fp->fi_blocknum);
	nb = fp->fi_count;

	/*
	 * Search the log hash.
	 * Merge deltas if an overlap is found.
	 */

	lh = &loghash[LB_HASHFUNC(bof)];

	if (*lh == (lb_me_t *)NULL)
		return;

	l = *lh;

	do {
		l = l->l_prev;
		if (OVERLAP(l->l_mof, l->l_nb, bof, nb)) {
			/*
			 * Found a delta in the log hash which overlaps
			 * with the current metadata block. Read the
			 * actual delta payload from the on-disk log
			 * directly into the file buffer.
			 */
			if (l->l_typ != DT_ABZERO) {
				/*
				 * We have to actually read this part of the
				 * log as it could contain a sector trailer, or
				 * wrap around the end of the log.
				 * If it did, the second offset generation would
				 * be incorrect if we'd started at l->l_lof.
				 */
				if (!(skip = lufs_read_log(l->l_lof, NULL,
				    MAX(bof - l->l_mof, 0))))
					dprintf("scan/merge error, pre-skip\n");
				if (!(skip = lufs_read_log(skip,
				    fp->fi_memp + MAX(l->l_mof - bof, 0),
				    MIN(l->l_mof + l->l_nb, bof + nb) -
				    MAX(l->l_mof, bof))))
					dprintf("scan/merge error, merge\n");
			} else {
				/*
				 * DT_ABZERO requires no disk access, just
				 * clear the byte range which overlaps with
				 * the delta.
				 */
				bzero(fp->fi_memp + MAX(l->l_mof - bof, 0),
				    MIN(l->l_mof + l->l_nb, bof + nb) -
				    MAX(l->l_mof, bof));
			}
		}
	} while (l->l_prev != (*lh)->l_prev);

	printf("*\b");
}

void
lufs_closeall(void)
{
	if (ufs_is_lufs) {
		bkmem_free((char *)eb, logfp->fi_devp->un_fs.di_fs.fs_bsize);
		bkmem_free((char *)logfp, sizeof (fileid_t));
		eb = (extent_block_t *)NULL;
		bzero((caddr_t)&odi, sizeof (ml_odunit_t));
		logfp = (fileid_t *)NULL;
		lufs_free_logbuf();
		ufs_is_lufs = 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.
 * Copyright (c) 2016 by Delphix. All rights reserved.
 */

#include <sys/param.h>
#include <sys/vnode.h>
#include <sys/fs/ufs_fsdir.h>
#include <sys/fs/ufs_fs.h>
#include <sys/fs/ufs_inode.h>
#include <sys/sysmacros.h>
#include <sys/promif.h>

#include <sys/stat.h>
#include <sys/bootvfs.h>
#include <sys/bootdebug.h>
#include <sys/salib.h>
#include <sys/sacache.h>


int print_cache_stats = 0;

/*
 * This fd is used when talking to the device file itself.
 */
static fileid_t *head;
/*
 * hooks into ufs logging support
 */
extern void	lufs_boot_init(fileid_t *);
extern void	lufs_closeall(void);
extern void	lufs_merge_deltas(fileid_t *);

/* Only got one of these...ergo, only 1 fs open at once */
/* static */
devid_t		*ufs_devp;

struct dirinfo {
	int 	loc;
	fileid_t *fi;
};

/*
 *  Function prototypes
 */
static int	boot_ufs_mountroot(char *str);
static int	boot_ufs_unmountroot(void);
static int	boot_ufs_open(char *filename, int flags);
static int	boot_ufs_close(int fd);
static ssize_t	boot_ufs_read(int fd, caddr_t buf, size_t size);
static off_t	boot_ufs_lseek(int, off_t, int);
static int	boot_ufs_fstat(int fd, struct bootstat *stp);
static void	boot_ufs_closeall(int flag);
static int	boot_ufs_getdents(int fd, struct dirent *dep, unsigned size);

struct boot_fs_ops boot_ufs_ops = {
	"ufs",
	boot_ufs_mountroot,
	boot_ufs_unmountroot,
	boot_ufs_open,
	boot_ufs_close,
	boot_ufs_read,
	boot_ufs_lseek,
	boot_ufs_fstat,
	boot_ufs_closeall,
	boot_ufs_getdents
};

static 	ino_t	find(fileid_t *filep, char *path);
static	ino_t	dlook(fileid_t *filep, char *path);
static 	daddr32_t	sbmap(fileid_t *filep, daddr32_t bn);
static  struct direct *readdir(struct dirinfo *dstuff);

/* These are the pools of buffers, etc. */
#define	NBUFS	(NIADDR+1)
/* Compilers like to play with alignment, so force the issue here */
static union {
	char		*blk[NBUFS];
	daddr32_t		*dummy;
} b;
daddr32_t		blknos[NBUFS];

/*
 *	There is only 1 open (mounted) device at any given time.
 *	So we can keep a single, global devp file descriptor to
 *	use to index into the di[] array.  This is not true for the
 *	fi[] array.  We can have more than one file open at once,
 *	so there is no global fd for the fi[].
 *	The user program must save the fd passed back from open()
 *	and use it to do subsequent read()'s.
 */

static int
openi(fileid_t *filep, ino_t inode)
{
	int retval;
	struct dinode *dp;
	devid_t *devp = filep->fi_devp;

	/* Try the inode cache first */
	if ((filep->fi_inode = get_icache(devp->di_dcookie, inode)) != NULL)
		return (0);
	/* Nope, not there so lets read it off the disk. */
	filep->fi_offset = 0;
	filep->fi_blocknum = fsbtodb(&devp->un_fs.di_fs,
	    itod(&devp->un_fs.di_fs, inode));

	/* never more than 1 disk block */
	filep->fi_count = devp->un_fs.di_fs.fs_bsize;
	filep->fi_memp = filep->fi_buf;

	/* Maybe the block is in the disk block cache */
	if ((filep->fi_memp = get_bcache(filep)) == NULL) {
		/* Not in the block cache so read it from disk */
		if (retval = set_bcache(filep))
			return (retval);
		lufs_merge_deltas(filep);
	}

	dp = (struct dinode *)filep->fi_memp;
	filep->fi_inode = (struct inode *)
	    bkmem_alloc(sizeof (struct inode));
	bzero((char *)filep->fi_inode, sizeof (struct inode));
	filep->fi_inode->i_ic =
	    dp[itoo(&devp->un_fs.di_fs, inode)].di_un.di_icom;
	filep->fi_inode->i_number = inode;
	if (set_ricache(devp->di_dcookie, inode, (void *)filep->fi_inode,
	    sizeof (struct inode)))
		filep->fi_inode->i_flag = FI_NOCACHE;
	return (0);
}

static fileid_t *
find_fp(int fd)
{
	fileid_t *filep = head;

	if (fd >= 0) {
		while ((filep = filep->fi_forw) != head)
			if (fd == filep->fi_filedes)
				return (filep->fi_taken ? filep : 0);
	}

	return (0);
}

static ino_t
find(fileid_t *filep, char *path)
{
	char *q;
	char c;
	ino_t inode;
	char lpath[MAXPATHLEN];
	char *lpathp = lpath;
	int len, r;
	devid_t	*devp;

	if (path == NULL || *path == '\0') {
		printf("null path\n");
		return ((ino_t)0);
	}

	bzero(lpath, sizeof (lpath));
	bcopy(path, lpath, strlen(path));
	devp = filep->fi_devp;
	while (*lpathp) {
		/* if at the beginning of pathname get root inode */
		r = (lpathp == lpath);
		if (r && openi(filep, (ino_t)UFSROOTINO))
			return ((ino_t)0);
		while (*lpathp == '/')
			lpathp++;	/* skip leading slashes */
		q = lpathp;
		while (*q != '/' && *q != '\0')
			q++;		/* find end of component */
		c = *q;
		*q = '\0';		/* terminate component */

		/* Bail out early if opening root */
		if (r && (*lpathp == '\0'))
			return ((ino_t)UFSROOTINO);
		if ((inode = dlook(filep, lpathp)) != 0) {
			if (openi(filep, inode))
				return ((ino_t)0);
			if ((filep->fi_inode->i_smode & IFMT) == IFLNK) {
				filep->fi_blocknum =
				    fsbtodb(&devp->un_fs.di_fs,
				    filep->fi_inode->i_db[0]);
				filep->fi_count = DEV_BSIZE;
				/* check the block cache */
				if ((filep->fi_memp =
				    get_bcache(filep)) == NULL) {
					if (set_bcache(filep))
						return ((ino_t)0);
					lufs_merge_deltas(filep);
				}
				len = strlen(filep->fi_memp);
				if (filep->fi_memp[0] == '/')
					/* absolute link */
					lpathp = lpath;
				/* copy rest of unprocessed path up */
				bcopy(q, lpathp + len, strlen(q + 1) + 2);
				/* point to unprocessed path */
				*(lpathp + len) = c;
				/* prepend link in before unprocessed path */
				bcopy(filep->fi_memp, lpathp, len);
				lpathp = lpath;
				continue;
			} else
				*q = c;
			if (c == '\0')
				break;
			lpathp = q;
			continue;
		} else {
			return ((ino_t)0);
		}
	}
	return (inode);
}

/*
 * Map <file, file logical block> into a file system block number.
 * Reads indirect blocks as needed to find the block.  Returns zero when
 * block isn't there; returns negative fsbn when block is uninitialized.
 */
static daddr32_t
sbmap(fileid_t *filep, daddr32_t bn)
{
	struct inode *inodep;
	int i, j, sh;
	daddr32_t nb, *bap;
	daddr32_t *db;
	devid_t	*devp;

	devp = filep->fi_devp;
	inodep = filep->fi_inode;
	db = inodep->i_db;

	/*
	 * blocks 0..NDADDR are direct blocks
	 */
	if (bn < NDADDR) {
		nb = db[bn];
		return (nb);
	}

	/*
	 * addresses NIADDR have single and double indirect blocks.
	 * the first step is to determine how many levels of indirection.
	 */
	sh = 1;
	bn -= NDADDR;
	for (j = NIADDR; j > 0; j--) {
		sh *= NINDIR(&devp->un_fs.di_fs);
		if (bn < sh)
			break;
		bn -= sh;
	}
	if (j == 0) {
		return ((daddr32_t)0);
	}

	/*
	 * fetch the first indirect block address from the inode
	 */
	nb = inodep->i_ib[NIADDR - j];
	if (nb == 0) {
		return ((daddr32_t)0);
	}

	/*
	 * fetch through the indirect blocks
	 */
	for (; j <= NIADDR; j++) {
		if (blknos[j] != nb) {
			filep->fi_blocknum = fsbtodb(&devp->un_fs.di_fs, nb);
			filep->fi_count = devp->un_fs.di_fs.fs_bsize;
			/* First look through the disk block cache */
			if ((filep->fi_memp = get_bcache(filep)) == NULL) {
				if (set_bcache(filep)) /* Gotta do I/O */
					return (0);
				lufs_merge_deltas(filep);
			}
			b.blk[j] = filep->fi_memp;
			blknos[j] = nb;
		}
		bap = (daddr32_t *)b.blk[j];
		sh /= NINDIR(&devp->un_fs.di_fs);
		i = (bn / sh) % NINDIR(&devp->un_fs.di_fs);
		nb = bap[i];
		if (nb == 0) {
			return ((daddr32_t)0);
		}
	}
	return (nb);
}

static ino_t
dlook(fileid_t *filep, char *path)
{
	devid_t *devp = filep->fi_devp;
	struct direct *dp;
	struct inode *ip;
	struct dirinfo dirp;
	int len;
	ino_t in;
#ifdef DEBUG
	static int warned = 0;
#endif

	ip = filep->fi_inode;
	if (path == NULL || *path == '\0')
		return (0);
	if ((ip->i_smode & IFMT) != IFDIR)
		return (0);
	if (ip->i_size == 0)
		return (0);
	len = strlen(path);

	/*
	 * First look through the directory entry cache
	 */
	if ((in = get_dcache(devp->di_dcookie, path, ip->i_number)) != 0)
		return (in);

	/*
	 * If the entire directory is cached, return failure
	 */
	if (ip->i_flag & FI_CACHED)
		return (0);

	/*
	 * Otherwise, read the entire directory into the cache
	 */
	in = 0;
	dirp.loc = 0;
	dirp.fi = filep;
	if (!(ip->i_flag & FI_NOCACHE))
		ip->i_flag |= FI_CACHED;
	for (dp = readdir(&dirp); dp != NULL; dp = readdir(&dirp)) {
		if (dp->d_ino == 0)
			continue;
		if (dp->d_namlen == len && strcmp(path, dp->d_name) == 0)
			in = dp->d_ino;

		/*
		 * Allow "*" to print all names at that level, w/out match
		 */
		if (strcmp(path, "*") == 0)
			printf("%s\n", dp->d_name);

		if (ip->i_flag & FI_NOCACHE)
			continue;

		/*
		 * Put this entry into the cache.  If the entry has been
		 * partially cached, check before inserting.  This should be
		 * rare if sized correctly
		 */
		if ((ip->i_flag & FI_PARTIAL_CACHE) &&
		    (get_dcache(devp->di_dcookie, dp->d_name, dp->d_ino) != 0))
			continue;

		if (set_rdcache(devp->di_dcookie, dp->d_name, ip->i_number,
		    dp->d_ino)) {
			ip->i_flag &= ~FI_CACHED;
			ip->i_flag |= FI_PARTIAL_CACHE;
#ifdef DEBUG
			if (!warned) {
				printf("ufsboot: directory cache too small\n");
				warned++;
			}
#endif
		}
	}
	return (in);
}

/*
 * get next entry in a directory.
 */
struct direct *
readdir(struct dirinfo *dstuff)
{
	struct direct *dp;
	fileid_t *filep;
	daddr32_t lbn, d;
	int off;
	devid_t	*devp;

	filep = dstuff->fi;
	devp = filep->fi_devp;
	for (;;) {
		if (dstuff->loc >= filep->fi_inode->i_size) {
			return (NULL);
		}
		off = blkoff(&devp->un_fs.di_fs, dstuff->loc);
		if (off == 0) {
			lbn = lblkno(&devp->un_fs.di_fs, dstuff->loc);
			d = sbmap(filep, lbn);

			if (d <= 0)
				return (NULL);

			filep->fi_blocknum = fsbtodb(&devp->un_fs.di_fs, d);
			filep->fi_count =
			    blksize(&devp->un_fs.di_fs, filep->fi_inode, lbn);
			/* check the block cache */
			if ((filep->fi_memp = get_bcache(filep)) == NULL) {
				if (set_bcache(filep))
					return (NULL);
				lufs_merge_deltas(filep);
			}
		}
		dp = (struct direct *)(filep->fi_memp + off);
		dstuff->loc += dp->d_reclen;
		if (dp->d_ino == 0)
			continue;
		return (dp);
	}
}

/*
 * Get the next block of data from the file.  If possible, dma right into
 * user's buffer
 */
static int
getblock(fileid_t *filep, caddr_t buf, int count, int *rcount)
{
	struct fs *fs;
	caddr_t p;
	int off, size, diff, zeroize;
	daddr32_t lbn, fsbn;
	devid_t	*devp;
	static int	pos;
	static char 	ind[] = "|/-\\";	/* that's entertainment? */
	static int	blks_read;
	devp = filep->fi_devp;
	p = filep->fi_memp;
	if ((signed)filep->fi_count <= 0) {

		/* find the amt left to be read in the file */
		diff = filep->fi_inode->i_size - filep->fi_offset;
		if (diff <= 0) {
			printf("Short read\n");
			return (-1);
		}

		fs = &devp->un_fs.di_fs;
		/* which block (or frag) in the file do we read? */
		lbn = lblkno(fs, filep->fi_offset);

		/* which physical block on the device do we read? */
		fsbn = sbmap(filep, lbn);

		/*
		 * zero fsbn -> unallocated hole.
		 * negative fsbn -> allocated but uninitialized.
		 * since we only read from the fs, treat both the same.
		 */
		zeroize = (fsbn <= 0);

		filep->fi_blocknum = fsbtodb(fs, fsbn);

		off = blkoff(fs, filep->fi_offset);

		/* either blksize or fragsize */
		size = blksize(fs, filep->fi_inode, lbn);
		filep->fi_count = size;
		filep->fi_memp = filep->fi_buf;

		/*
		 * optimization if we are reading large blocks of data then
		 * we can go directly to user's buffer
		 */
		*rcount = 0;
		if (off == 0 && count >= size) {
			filep->fi_memp = buf;
			if (zeroize) {
				bzero(buf, size);
			} else if (diskread(filep)) {
				return (-1);
			}
			*rcount = size;
			filep->fi_count = 0;
			read_opt++;
			if ((blks_read++ & 0x3) == 0)
				printf("%c\b", ind[pos++ & 3]);
			return (0);
		} else {
			if (zeroize) {
				bzero(filep->fi_memp, size);
			} else if (diskread(filep))
				return (-1);
		}

		/*
		 * round and round she goes (though not on every block..
		 * - OBP's take a fair bit of time to actually print stuff)
		 * On x86, the screen oriented bootconf program doesn't
		 * want this noise...
		 */
		if ((blks_read++ & 0x3) == 0)
			printf("%c\b", ind[pos++ & 3]);

		if (filep->fi_offset - off + size >= filep->fi_inode->i_size)
			filep->fi_count = diff + off;
		filep->fi_count -= off;
		p = &filep->fi_memp[off];
	}
	filep->fi_memp = p;
	return (0);
}


/*
 *  This is the high-level read function.  It works like this.
 *  We assume that our IO device buffers up some amount of
 *  data and that we can get a ptr to it.  Thus we need
 *  to actually call the device func about filesize/blocksize times
 *  and this greatly increases our IO speed.  When we already
 *  have data in the buffer, we just return that data (with bcopy() ).
 */

static ssize_t
boot_ufs_read(int fd, caddr_t buf, size_t count)
{
	size_t i, j;
	caddr_t	n;
	int rcount;
	fileid_t *filep;

	if (!(filep = find_fp(fd))) {
		return (-1);
	}

	if (filep->fi_offset + count > filep->fi_inode->i_size)
		count = filep->fi_inode->i_size - filep->fi_offset;

	/* that was easy */
	if ((i = count) == 0)
		return (0);

	n = buf;
	while (i > 0) {
		/* If we need to reload the buffer, do so */
		if ((j = filep->fi_count) == 0) {
			(void) getblock(filep, buf, i, &rcount);
			i -= rcount;
			buf += rcount;
			filep->fi_offset += rcount;
		} else {
			/* else just bcopy from our buffer */
			j = MIN(i, j);
			bcopy(filep->fi_memp, buf, (unsigned)j);
			buf += j;
			filep->fi_memp += j;
			filep->fi_offset += j;
			filep->fi_count -= j;
			i -= j;
		}
	}
	return (buf - n);
}

/*
 *	This routine will open a device as it is known by the V2 OBP.
 *	Interface Defn:
 *	err = boot_ufs_mountroot(string);
 *		err = 0 on success
 *		err = -1 on failure
 *	string:	char string describing the properties of the device.
 *	We must not dork with any fi[]'s here.  Save that for later.
 */

static int
boot_ufs_mountroot(char *str)
{
	int	h;

	/*
	 * Open the device and setup the read of the ufs superblock
	 * only the first time mountroot is called.  Subsequent calls
	 * to mountroot succeed immediatly
	 */
	if (ufs_devp == NULL) {

		/*
		 * Encode the knowledge that we normally boot from the 'a'
		 * slice of the leaf device on the OBP path; we also permit
		 * a 'nolabel' device, i.e. the entire device.  Since v2path
		 * points to 'str' as well, changing str should have the
		 * desired result.
		 */
		if (strchr(str, ':') == NULL) {
			(void) strcat(str, ":a");
		}
		h = prom_open(str);
		if (h == 0) {
			printf("Cannot open %s\n", str);
			return (-1);
		}

		ufs_devp = (devid_t *)bkmem_alloc(sizeof (devid_t));
		ufs_devp->di_taken = 1;
		ufs_devp->di_dcookie = h;
		ufs_devp->di_desc = (char *)bkmem_alloc(strlen(str) + 1);
		(void) strcpy(ufs_devp->di_desc, str);
		bzero(ufs_devp->un_fs.dummy, SBSIZE);
		head = (fileid_t *)bkmem_alloc(sizeof (fileid_t));
		head->fi_back = head->fi_forw = head;
		head->fi_filedes = 0;
		head->fi_taken = 0;

		/* Setup read of the superblock */
		head->fi_devp = ufs_devp;
		head->fi_blocknum = SBLOCK;
		head->fi_count = (uint_t)SBSIZE;
		head->fi_memp = (caddr_t)&(ufs_devp->un_fs.di_fs);
		head->fi_offset = 0;

		if (diskread(head) ||
		    ufs_devp->un_fs.di_fs.fs_magic != FS_MAGIC) {
			boot_ufs_closeall(1);
			return (-1);
		}
		lufs_boot_init(head);
	}
	return (0);
}

/*
 * Unmount the currently mounted root fs.  In practice, this means
 * closing all open files and releasing resources.  All of this
 * is done by boot_ufs_closeall().
 */

int
boot_ufs_unmountroot(void)
{
	if (ufs_devp == NULL)
		return (-1);

	boot_ufs_closeall(1);

	return (0);
}

/*
 *	We allocate an fd here for use when talking
 *	to the file itself.
 */

/*ARGSUSED*/
static int
boot_ufs_open(char *filename, int flags)
{
	fileid_t	*filep;
	ino_t	inode;
	static int	filedes = 1;

	/* build and link a new file descriptor */
	filep = (fileid_t *)bkmem_alloc(sizeof (fileid_t));
	filep->fi_back = head->fi_back;
	filep->fi_forw = head;
	head->fi_back->fi_forw = filep;
	head->fi_back = filep;
	filep->fi_filedes = filedes++;
	filep->fi_taken = 1;
	filep->fi_path = (char *)bkmem_alloc(strlen(filename) + 1);
	(void) strcpy(filep->fi_path, filename);
	filep->fi_devp = ufs_devp; /* dev is already "mounted" */
	filep->fi_inode = NULL;
	bzero(filep->fi_buf, MAXBSIZE);

	inode = find(filep, filename);
	if (inode == (ino_t)0) {
		(void) boot_ufs_close(filep->fi_filedes);
		return (-1);
	}
	if (openi(filep, inode)) {
		(void) boot_ufs_close(filep->fi_filedes);
		return (-1);
	}

	filep->fi_offset = filep->fi_count = 0;

	return (filep->fi_filedes);
}

/*
 *  We don't do any IO here.
 *  We just play games with the device pointers.
 */

static off_t
boot_ufs_lseek(int fd, off_t addr, int whence)
{
	fileid_t *filep;

	/* Make sure user knows what file they're talking to */
	if (!(filep = find_fp(fd)))
		return (-1);

	switch (whence) {
	case SEEK_CUR:
		filep->fi_offset += addr;
		break;
	case SEEK_SET:
		filep->fi_offset = addr;
		break;
	default:
	case SEEK_END:
		printf("ufs_lseek(): invalid whence value %d\n", whence);
		break;
	}

	filep->fi_blocknum = addr / DEV_BSIZE;
	filep->fi_count = 0;

	return (0);
}

/*
 * ufs_fstat() only supports size, mode, and times at present time.
 */

static int
boot_ufs_fstat(int fd, struct bootstat *stp)
{
	fileid_t	*filep;
	struct inode	*ip;

	if (!(filep = find_fp(fd)))
		return (-1);

	ip = filep->fi_inode;

	stp->st_mode = 0;
	stp->st_size = 0;

	if (ip == NULL)
		return (0);

	switch (ip->i_smode & IFMT) {
	case IFDIR:
		stp->st_mode = S_IFDIR;
		break;
	case IFLNK:
		stp->st_mode = S_IFLNK;
		break;
	case IFREG:
		stp->st_mode = S_IFREG;
		break;
	default:
		break;
	}
	stp->st_size = ip->i_size;
	stp->st_atim.tv_sec = ip->i_atime.tv_sec;
	stp->st_atim.tv_nsec = ip->i_atime.tv_usec * 1000;
	stp->st_mtim.tv_sec = ip->i_mtime.tv_sec;
	stp->st_mtim.tv_nsec = ip->i_mtime.tv_usec * 1000;
	stp->st_ctim.tv_sec = ip->i_ctime.tv_sec;
	stp->st_ctim.tv_nsec = ip->i_ctime.tv_usec * 1000;

	return (0);
}

static int
boot_ufs_close(int fd)
{
	fileid_t *filep;

	/* Make sure user knows what file they're talking to */
	if (!(filep = find_fp(fd)))
		return (-1);

	if (filep->fi_taken && (filep != head)) {
		/* Clear the ranks */
		bkmem_free(filep->fi_path, strlen(filep->fi_path)+1);
		filep->fi_blocknum = filep->fi_count = filep->fi_offset = 0;
		filep->fi_memp = (caddr_t)0;
		filep->fi_devp = 0;
		filep->fi_taken = 0;

		/* unlink and deallocate node */
		filep->fi_forw->fi_back = filep->fi_back;
		filep->fi_back->fi_forw = filep->fi_forw;
		bkmem_free((char *)filep, sizeof (fileid_t));

		return (0);
	} else {
		/* Big problem */
		printf("\nFile descrip %d not allocated!", fd);
		return (-1);
	}
}

/* closeall is now idempotent */
/*ARGSUSED*/
static void
boot_ufs_closeall(int flag)
{
	fileid_t *filep = head;

	if (ufs_devp == NULL) {
		if (head)
			prom_panic("boot_ufs_closeall: head != NULL.\n");
		return;
	}

	while ((filep = filep->fi_forw) != head)
		if (filep->fi_taken)
			if (boot_ufs_close(filep->fi_filedes))
				prom_panic("Filesystem may be inconsistent.\n");


	release_cache(ufs_devp->di_dcookie);
	(void) prom_close(ufs_devp->di_dcookie);
	ufs_devp->di_taken = 0;
	if (verbosemode & print_cache_stats)
		print_cache_data();
	lufs_closeall();
	bkmem_free((char *)ufs_devp, sizeof (devid_t));
	bkmem_free((char *)head, sizeof (fileid_t));
	ufs_devp = (devid_t *)NULL;
	head = (fileid_t *)NULL;
}

static int
boot_ufs_getdents(int fd, struct dirent *dep, unsigned size)
{
	/*
	 * Read directory entries from the file open on "fd" into the
	 * "size"-byte buffer at "dep" until the buffer is exhausted
	 * or we reach EOF on the directory.  Returns the number of
	 * entries read.
	 */
	int n;
	fileid_t *fp;
	unsigned long oldoff, oldblok;

#define	SLOP (sizeof (struct dirent) - offsetof(struct dirent, d_name[1]))

	if (fp = find_fp(fd)) {
		/*
		 *  File is open, check type to make sure it's a directory.
		 */

		while ((fp->fi_inode->i_smode & IFMT) == IFLNK) {
			/*
			 * If file is a symbolic link, we'll follow
			 * it JIC it points to a directory!
			 */
			fileid_t fx;
			char pn[MAXPATHLEN];
			fp->fi_count = DEV_BSIZE;
			fp->fi_blocknum = fsbtodb(&fp->fi_devp->un_fs.di_fs,
			    fp->fi_inode->i_db[0]);

			/*
			 * Return failure if:
			 * (a) we get an I/O error reading the path name.
			 * (b) the path name points to a non-existant file,
			 * (c) we get an I/O error reading the target inode.
			 */
			if ((fp->fi_memp = get_bcache(fp)) == NULL) {
				if (set_bcache(fp))
					return (-1);
				lufs_merge_deltas(fp);
			}
			if (!(n = find(&fx, strcpy(pn, fp->fi_memp))) ||
			    openi(fp = &fx, n)) {
				return (-1);
			}
		}

		if ((fp->fi_inode->i_smode & IFMT) == IFDIR) {
			/*
			 * If target file is a directory, go ahead
			 * and read it.  This consists of making
			 * repeated calls to readdir() until we reach
			 * end-of-file or run out of buffer space.
			 */
			int cnt = 0;
			struct direct *dp;
			struct dirinfo dir;

			dir.fi = fp;
			oldblok = fp->fi_blocknum;
			dir.loc = oldoff = fp->fi_offset;

			for (dp = readdir(&dir); dp; dp = readdir(&dir)) {
				/*
				 *  Read all directory entries in the file ...
				 */

				if (dp->d_ino) {
					/*
					 *  Next entry is valid.
					 * Compute name length and
					 * break loop if there's not
					 * enough space in the output
					 * buffer for the next entry.
					 *
					 *  NOTE: "SLOP" is the number
					 * of bytes inserted into the
					 * dirent struct's "d_name"
					 * field by the compiler to
					 * preserve alignment.
					 */
					dep->d_ino = dp->d_ino;
					n = strlen(dp->d_name);
					n = roundup((sizeof (struct dirent) +
					    ((n > SLOP) ? n : 0)),
					    sizeof (off_t));

					if (n > size)
						break; /* user buffer is full */

					oldblok = fp->fi_blocknum;
					oldoff = dir.loc;
					size -= n;
					cnt += 1;

					(void) strlcpy(dep->d_name, dp->d_name,
					    strlen(dp->d_name) + 1);
					dep->d_off = dir.loc;
					dep->d_reclen = (ushort_t)n;

					dep = (struct dirent *)
					    ((char *)dep + n);
				}
			}
			/*
			 * Remember where we left off for next time
			 */
			fp->fi_blocknum = oldblok;
			fp->fi_offset = oldoff;

			return (cnt);
		}
	}

#undef SLOP

	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 2003 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

LIBRARY = libinet.a
LOCOBJS = ipv4.o icmp4.o udp.o mac.o ethernet.o dhcpv4.o ibd.o
CMNOBJS = ipv4_sum.o udp_sum.o octet.o scan.o dhcpinfo.o
OBJECTS = $(LOCOBJS) $(CMNOBJS)

include ../Makefile.com

CMNDIR  = $(CMNNETDIR)/dhcp
SRCS	= $(LOCOBJS:%.o=$(SRCDIR)/%.c) $(CMNOBJS:%.o=$(CMNDIR)/%.c)
LDLIBS += -lsock
CPPFLAGS += $(SOCKCPPFLAGS) -I$(TOPDIR)/psm/stand

CERRWARN += -Wno-char-subscripts
CERRWARN += $(CNOWARN_UNINIT)

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 (c) 1999, Sun Microsystems, Inc.
 *
 * ATM implementation-specific definitions
 */

#ifndef _ATM_INET_H
#define	_ATM_INET_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#ifdef	__cplusplus
extern "C" {
#endif

#define	ATMSIZE			(4500)	/* Default ATM MTU size */
#define	ATM_ARP_TIMEOUT		(300000)	/* in milliseconds */
#define	ATM_IN_TIMEOUT		(4)	/* milliseconds wait for IP input */

#ifdef	__cplusplus
}
#endif

#endif /* _ATM_INET_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.
 *
 * Standalone dhcp client.
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#include <sys/types.h>
#include <sys/salib.h>
#include <sys/bootconf.h>
#include <sys/bootcmn.h>
#include <sys/socket.h>
#include <sys/isa_defs.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/inetutil.h>
#include <netinet/dhcp.h>
#include <netinet/ip.h>
#include <netinet/udp.h>
#include <dhcp_impl.h>
#include <net/if_types.h>
#include <sys/promif.h>
#include <sys/platnames.h>
#include <socket_inet.h>

#include "ipv4.h"
#include "mac.h"
#include <sys/bootdebug.h>
#include "dhcpv4.h"

static char		*s_n = "INIT";
static enum DHCPSTATE 	dhcp_state = INIT;

static PKT		*dhcp_snd_bufp, *dhcp_rcv_bufp;
static int		dhcp_buf_size;

static const uint8_t	magic[] = BOOTMAGIC;	/* RFC1048 */
static uint8_t		opt_discover[]  = { CD_DHCP_TYPE, 1, DISCOVER };
static uint8_t		opt_request[]   = { CD_DHCP_TYPE, 1, REQUEST };
static uint8_t		opt_decline[]   = { CD_DHCP_TYPE, 1, DECLINE };

static uint8_t		dhcp_classid[DHCP_MAX_OPT_SIZE + 3];
static uint8_t		dhcp_clientid[DHCP_MAX_CID_LEN];
static uint8_t		dhcp_clientid_len = 0;

static uint32_t		dhcp_start_time;	/* start time (msecs */
static time_t		dhcp_secs;
static uint32_t		timeout;	/* timeout in milliseconds */

static int		pkt_counter;
PKT_LIST		*list_tl, *list_hd;
PKT_LIST		*state_pl = NULL;

#define	PROM_BOOT_CACHED	"bootp-response"
extern char	*bootp_response;	/* bootprop.c */
extern int	pagesize;

/*
 * Do whatever reset actions/initialization actions are generic for every
 * DHCP/bootp message. Set the message type.
 *
 * Returns: the updated options ptr.
 */
static uint8_t *
init_msg(PKT *pkt, uint8_t *pkttype)
{
	static uint32_t xid;

	bzero(pkt, dhcp_buf_size);
	bcopy(magic, pkt->cookie, sizeof (pkt->cookie));
	pkt->op = BOOTREQUEST;
	if (xid == 0)
		bcopy(mac_get_addr_buf()+2, &xid, 4);
	else
		xid++;
	pkt->xid = xid;
	bcopy(pkttype, pkt->options, 3);
	return ((uint8_t *)(pkt->options + 3));
}

/*
 *  Parameter request list.
 */
static void
parameter_request_list(uint8_t **opt)
{
	/*
	 * This parameter request list is used in the normal 4-packet
	 * DHCPDISCOVER/OFFER/REQUEST/ACK exchange; it must not contain
	 * CD_REQUESTED_IP_ADDR or CD_LEASE_TIME.
	 */
	static uint8_t	prlist[] = {
	    CD_REQUEST_LIST,	/* parameter request list option number */
	    4,			/* number of options requested */
	    CD_SUBNETMASK,
	    CD_ROUTER,
	    CD_HOSTNAME,
	    CD_VENDOR_SPEC
	    };
	if (opt && *opt) {
		bcopy(prlist, *opt, sizeof (prlist));
		*opt += sizeof (prlist);
	}
}

/*
 * Set hardware specific fields
 */
static void
set_hw_spec_data(PKT *p, uint8_t **opt, uint8_t *pkttype)
{
	char mfg[DHCP_MAX_OPT_SIZE + 1], cbuf[DHCP_MAX_OPT_SIZE + 1];
	uint8_t *tp, *dp;
	int adjust_len, len, i;

	p->htype = mac_arp_type(mac_get_type());
	len = (uchar_t)mac_get_addr_len();
	if (len <= sizeof (p->chaddr)) {
		p->hlen = len;
		bcopy(mac_get_addr_buf(), p->chaddr, len);
	} else {
		uint8_t type = *(pkttype + 2);
		/*
		 * The mac address does not fit in the chaddr
		 * field, thus it can not be sent to the server,
		 * thus server can not unicast the reply. Per
		 * RFC 2131 4.4.1, client can set this bit in
		 * DISCOVER/REQUEST.
		 */
		if ((type == DISCOVER) || (type == REQUEST))
			p->flags = htons(BCAST_MASK);
	}

	if (opt && *opt) {
		if (dhcp_classid[0] == '\0') {
			/*
			 * Classids based on mfg name: Commas (,) are
			 * converted to periods (.), and spaces ( ) are removed.
			 */
			dhcp_classid[0] = CD_CLASS_ID;

			(void) strncpy(mfg, get_mfg_name(), sizeof (mfg));
			if (strncmp(mfg, "SUNW", strlen("SUNW")) != 0) {
				len = strlen("SUNW.");
				(void) strcpy(cbuf, "SUNW.");
			} else {
				len = 0;
				cbuf[0] = '\0';
			}
			len += strlen(mfg);

			if ((len + 2) < DHCP_MAX_OPT_SIZE) {
				tp = (uint8_t *)strcat(cbuf, mfg);
				dp = &dhcp_classid[2];
				adjust_len = 0;
				for (i = 0; i < len; i++, tp++) {
					if (*tp == ',') {
						*dp++ = '.';
					} else if (*tp == ' ') {
						adjust_len++;
					} else {
						*dp++ = *tp;
					}
				}
				len -= adjust_len;
				dhcp_classid[1] = (uint8_t)len;
			} else
				prom_panic("Not enough space for class id");
#ifdef	DHCP_DEBUG
			printf("%s: Classid: %s\n", s_n, &dhcp_classid[2]);
#endif	/* DHCP_DEBUG */
		}
		bcopy(dhcp_classid, *opt, dhcp_classid[1] + 2);
		*opt += dhcp_classid[1] + 2;
	}
}

static void
flush_list(void)
{
	PKT_LIST *wk, *tmp;

	wk = list_hd;
	while (wk != NULL) {
		tmp = wk;
		wk = wk->next;
		bkmem_free((char *)tmp->pkt, tmp->len);
		bkmem_free((char *)tmp, sizeof (PKT_LIST));
	}
	list_hd = list_tl = NULL;
	pkt_counter = 0;
}

static void
remove_list(PKT_LIST *pl, int flag)
{
	if (list_hd == NULL)
		return;

	if (list_hd == list_tl) {
		list_hd = list_tl = NULL;
	} else if (list_hd == pl) {
		list_hd = pl->next;
		list_hd->prev = NULL;
	} else if (list_tl == pl) {
		list_tl = list_tl->prev;
		list_tl->next = NULL;
	} else {
		pl->prev->next = pl->next;
		pl->next->prev = pl->prev;
	}
	pkt_counter--;
	if (flag) {
		bkmem_free((char *)pl->pkt, pl->len);
		bkmem_free((char *)pl, sizeof (PKT_LIST));
	}
}

/*
 * Collects BOOTP responses. Length has to be right, it has to be
 * a BOOTP reply pkt, with the same XID and HW address as ours. Adds
 * them to the pkt list.
 *
 * Returns 0 if no error processing packet, 1 if an error occurred and/or
 * collection of replies should stop. Used in inet() calls.
 */
static int
bootp_collect(int len)
{
	PKT		*s = (PKT *)dhcp_snd_bufp;
	PKT		*r = (PKT *)dhcp_rcv_bufp;
	PKT_LIST	*pl;

	if (len < sizeof (PKT)) {
		dprintf("%s: BOOTP reply too small: %d\n", s_n, len);
		return (1);
	}
	if (r->op == BOOTREPLY && r->xid == s->xid &&
	    bcmp((caddr_t)s->chaddr, (caddr_t)r->chaddr, s->hlen) == 0) {
		/* Add a packet to the pkt list */
		if (pkt_counter > (MAX_PKT_LIST - 1))
			return (1);	/* got enough packets already */
		if (((pl = (PKT_LIST *)bkmem_zalloc(sizeof (PKT_LIST))) ==
		    NULL) || ((pl->pkt = (PKT *)bkmem_zalloc(len)) == NULL)) {
			errno = ENOMEM;
			if (pl != NULL)
				bkmem_free((char *)pl, sizeof (PKT_LIST));
			return (1);
		}
		bcopy(dhcp_rcv_bufp, pl->pkt, len);
		pl->len = len;
		if (list_hd == NULL) {
			list_hd = list_tl = pl;
			pl->prev = NULL;
		} else {
			list_tl->next = pl;
			pl->prev = list_tl;
			list_tl = pl;
		}
		pkt_counter++;
		pl->next = NULL;
	}
	return (0);
}

/*
 * Checks if BOOTP exchange(s) were successful. Returns 1 if they
 * were, 0 otherwise. Used in inet() calls.
 */
static int
bootp_success(void)
{
	PKT	*s = (PKT *)dhcp_snd_bufp;

	if (list_hd != NULL) {
		/* remember the secs - we may need them later */
		dhcp_secs = ntohs(s->secs);
		return (1);
	}
	s->secs = htons((uint16_t)((prom_gettime() - dhcp_start_time)/1000));
	return (0);
}

/*
 * This function accesses the network. Opens a connection, and binds to
 * it if a client binding doesn't already exist. If 'tries' is 0, then
 * no reply is expected/returned. If 'tries' is non-zero, then 'tries'
 * attempts are made to get a valid response. If 'tol' is not zero,
 * then this function will wait for 'tol' milliseconds for more than one
 * response to a transmit.
 *
 * Returns 0 for success, errno otherwise.
 */
static int
inet(uint32_t size, struct in_addr *src, struct in_addr *dest, uint32_t tries,
    uint32_t tol)
{
	int			done = B_FALSE, flags, len;
	uint32_t		attempts = 0;
	int			sd;
	uint32_t		wait_time;	/* Max time collect replies */
	uint32_t		init_timeout;	/* Max time wait ANY reply */
	uint32_t		now;
	struct sockaddr_in	saddr, daddr;

	if ((sd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
		dprintf("%s: Can't open a socket.\n", s_n);
		return (errno);
	}

	flags = 0;

	bzero(&saddr, sizeof (struct sockaddr_in));
	saddr.sin_family = AF_INET;
	saddr.sin_port = htons(IPPORT_BOOTPC);
	saddr.sin_addr.s_addr = htonl(src->s_addr);

	if (bind(sd, (struct sockaddr *)&saddr, sizeof (saddr)) < 0) {
		dprintf("%s: Cannot bind to port %d, errno: %d\n",
		    s_n, IPPORT_BOOTPC, errno);
		(void) socket_close(sd);
		return (errno);
	}

	if (ntohl(dest->s_addr) == INADDR_BROADCAST) {
		int dontroute = B_TRUE;
		(void) setsockopt(sd, SOL_SOCKET, SO_DONTROUTE,
		    (const void *)&dontroute, sizeof (dontroute));
	}

	bzero(&daddr, sizeof (struct sockaddr_in));
	daddr.sin_family = AF_INET;
	daddr.sin_port = htons(IPPORT_BOOTPS);
	daddr.sin_addr.s_addr = htonl(dest->s_addr);
	wait_time = prom_gettime() + tol;

	do {
		if (sendto(sd, (char *)dhcp_snd_bufp, size, flags,
		    (struct sockaddr *)&daddr, sizeof (daddr)) < 0) {
			dprintf("%s: sendto failed with errno: %d\n",
			    s_n, errno);
			(void) socket_close(sd);
			return (errno);
		}
		if (!tries)
			break;   /* don't bother to check for reply */

		now = prom_gettime();
		if (timeout == 0)
			timeout = 4000;
		else {
			timeout <<= 1;
			if (timeout > 64000)
				timeout = 64000;
		}
		init_timeout = now + timeout;
		wait_time = now + tol;
		do {
			if ((len = recvfrom(sd, (char *)dhcp_rcv_bufp,
			    (int)dhcp_buf_size, MSG_DONTWAIT, NULL,
			    NULL)) < 0) {
				if (errno == EWOULDBLOCK)
					continue;	/* DONT WAIT */
				(void) socket_close(sd);
				flush_list();
				return (errno);
			}

			if (bootp_collect(len))
				break;	/* Stop collecting */

			if (tol != 0) {
				if (wait_time < prom_gettime())
					break; /* collection timeout */
			}
		} while (prom_gettime() < init_timeout);

		if (bootp_success()) {
			done = B_TRUE;
			break;  /* got the goods */
		}
	} while (++attempts < tries);

	(void) socket_close(sd);

	return (done ? 0 : DHCP_NO_DATA);
}

/*
 * Print the message from the server.
 */
static void
prt_server_msg(DHCP_OPT *p)
{
	int len = p->len;
	char scratch[DHCP_MAX_OPT_SIZE + 1];

	if (len > DHCP_MAX_OPT_SIZE)
		len = DHCP_MAX_OPT_SIZE;
	bcopy(p->value, scratch, len);
	scratch[len] = '\0';
	printf("%s: Message from server: '%s'\n", s_n, scratch);
}

/*
 * This function scans the list of OFFERS, and returns the "best" offer.
 * The criteria used for determining this is:
 *
 * The best:
 * DHCP OFFER (not BOOTP), same client_id as ours, same class_id,
 * Longest lease, all the options we need.
 *
 * Not quite as good:
 * DHCP OFFER, no class_id, short lease, only some of the options we need.
 *
 * We're really reach'in
 * BOOTP reply.
 *
 * DON'T select an offer from a server that gave us a configuration we
 * couldn't use. Take this server off the "bad" list when this is done.
 * Next time, we could potentially retry this server's configuration.
 *
 * NOTE: perhaps this bad server should have a counter associated with it.
 */
static PKT_LIST *
select_best(void)
{
	PKT_LIST	*wk, *tk, *best;
	int		err = 0;

	/* Pass one. Scan for options, set appropriate opt field. */
	wk = list_hd;
	while (wk != NULL) {
		if ((err = dhcp_options_scan(wk, B_TRUE)) != 0) {
			/* Garbled Options. Nuke this pkt. */
			if (boothowto & RB_DEBUG) {
				switch (err) {
				case DHCP_WRONG_MSG_TYPE:
					printf("%s: Unexpected DHCP message.\n",
					    s_n);
					break;
				case DHCP_GARBLED_MSG_TYPE:
					printf(
					    "%s: Garbled DHCP message type.\n",
					    s_n);
					break;
				case DHCP_BAD_OPT_OVLD:
					printf("%s: Bad option overload.\n",
					    s_n);
					break;
				}
			}
			tk = wk;
			wk = wk->next;
			remove_list(tk, B_TRUE);
			continue;
		}
		wk = wk->next;
	}

	/*
	 * Pass two. Pick out the best offer. Point system.
	 * What's important?
	 *	0) DHCP
	 *	1) No option overload
	 *	2) Encapsulated vendor option
	 *	3) Non-null sname and siaddr fields
	 *	4) Non-null file field
	 *	5) Hostname
	 *	6) Subnetmask
	 *	7) Router
	 */
	best = NULL;
	for (wk = list_hd; wk != NULL; wk = wk->next) {
		wk->offset = 0;
		if (wk->opts[CD_DHCP_TYPE] &&
		    wk->opts[CD_DHCP_TYPE]->len == 1) {
			if (*wk->opts[CD_DHCP_TYPE]->value != OFFER) {
				dprintf("%s: Unexpected DHCP message."
				    " Expected OFFER message.\n", s_n);
				continue;
			}
			if (!wk->opts[CD_LEASE_TIME]) {
				dprintf("%s: DHCP OFFER message without lease "
				    "time parameter.\n", s_n);
				continue;
			} else {
				if (wk->opts[CD_LEASE_TIME]->len != 4) {
					dprintf("%s: Lease expiration time is "
					    "garbled.\n", s_n);
					continue;
				}
			}
			if (!wk->opts[CD_SERVER_ID]) {
				dprintf("%s: DHCP OFFER message without server "
				    "id parameter.\n", s_n);
				continue;
			} else {
				if (wk->opts[CD_SERVER_ID]->len != 4) {
					dprintf("%s: Server identifier "
					    "parameter is garbled.\n", s_n);
					continue;
				}
			}
			/* Valid DHCP OFFER. See if we got our parameters. */
			dprintf("%s: Found valid DHCP OFFER message.\n", s_n);

			wk->offset += 30;

			/*
			 * Also could be faked, though more difficult
			 * because the encapsulation is hard to encode
			 * on a BOOTP server; plus there's not as much
			 * real estate in the packet for options, so
			 * it's likely this option would get dropped.
			 */
			if (wk->opts[CD_VENDOR_SPEC])
				wk->offset += 80;
		} else
			dprintf("%s: Found valid BOOTP reply.\n", s_n);

		/*
		 * RFC1048 BOOTP?
		 */
		if (bcmp((caddr_t)wk->pkt->cookie, (caddr_t)magic,
		    sizeof (magic)) == 0) {
			wk->offset += 5;
			if (wk->opts[CD_SUBNETMASK])
				wk->offset++;
			if (wk->opts[CD_ROUTER])
				wk->offset++;
			if (wk->opts[CD_HOSTNAME])
				wk->offset += 5;

			/*
			 * Prefer options that have diskless boot significance
			 */
			if (ntohl(wk->pkt->siaddr.s_addr) != INADDR_ANY)
				wk->offset += 10; /* server ip */
			if (wk->opts[CD_OPTION_OVERLOAD] == NULL) {
				if (wk->pkt->sname[0] != '\0')
					wk->offset += 10; /* server name */
				if (wk->pkt->file[0] != '\0')
					wk->offset += 5; /* File to load */
			}
		}
#ifdef	DHCP_DEBUG
		printf("%s: This server configuration has '%d' points.\n", s_n,
		    wk->offset);
#endif	/* DHCP_DEBUG */
		if (!best)
			best = wk;
		else {
			if (best->offset < wk->offset)
				best = wk;
		}
	}
	if (best) {
#ifdef	DHCP_DEBUG
		printf("%s: Found best: points: %d\n", s_n, best->offset);
#endif	/* DHCP_DEBUG */
		remove_list(best, B_FALSE);
	} else {
		dprintf("%s: No valid BOOTP reply or DHCP OFFER was found.\n",
		    s_n);
	}
	flush_list();	/* toss the remaining list */
	return (best);
}

/*
 * Send a decline message to the generator of the DHCPACK.
 */
static void
dhcp_decline(char *msg, PKT_LIST *pl)
{
	PKT		*pkt;
	uint8_t		*opt, ulen;
	int		pkt_size;
	struct in_addr	nets, ours, t_server, t_yiaddr;

	if (pl != NULL) {
		if (pl->opts[CD_SERVER_ID] != NULL &&
		    pl->opts[CD_SERVER_ID]->len == sizeof (struct in_addr)) {
			bcopy(pl->opts[CD_SERVER_ID]->value,
			    &t_server, pl->opts[CD_SERVER_ID]->len);
		} else
			t_server.s_addr = htonl(INADDR_BROADCAST);
		t_yiaddr.s_addr = pl->pkt->yiaddr.s_addr;
	}
	pkt = (PKT *)dhcp_snd_bufp;
	opt = init_msg(pkt, opt_decline);
	set_hw_spec_data(pkt, &opt, opt_decline);

	*opt++ = CD_SERVER_ID;
	*opt++ = sizeof (struct in_addr);
	bcopy(&t_server, opt, sizeof (struct in_addr));
	opt += sizeof (struct in_addr);
	nets.s_addr = htonl(INADDR_BROADCAST);

	/*
	 * Use the given yiaddr in our ciaddr field so server can identify us.
	 */
	pkt->ciaddr.s_addr = t_yiaddr.s_addr;

	ipv4_getipaddr(&ours);	/* Could be 0, could be yiaddr */
	ours.s_addr = htonl(ours.s_addr);

	ulen = (uint8_t)strlen(msg);
	*opt++ = CD_MESSAGE;
	*opt++ = ulen;
	bcopy(msg, opt, ulen);
	opt += ulen;
	*opt++ = CD_END;

	pkt_size = (uint8_t *)opt - (uint8_t *)pkt;
	if (pkt_size < sizeof (PKT))
		pkt_size = sizeof (PKT);

	timeout = 0;	/* reset timeout */
	(void) inet(pkt_size, &ours, &nets, 0, 0L);
}

/*
 * Implementings SELECTING state of DHCP client state machine.
 */
static int
dhcp_selecting(void)
{
	int		pkt_size;
	PKT		*pkt;
	uint8_t		*opt;
	uint16_t	size;
	uint32_t	lease;
	struct in_addr	nets, ours;

	pkt = (PKT *)dhcp_snd_bufp;
	opt = init_msg(pkt, opt_discover);
	pkt->secs = htons((uint16_t)((prom_gettime() - dhcp_start_time)/1000));

	*opt++ = CD_MAX_DHCP_SIZE;
	*opt++ = sizeof (size);
	size = (uint16_t)(dhcp_buf_size - sizeof (struct ip) -
	    sizeof (struct udphdr));
	size = htons(size);
	bcopy(&size, opt, sizeof (size));
	opt += sizeof (size);

	set_hw_spec_data(pkt, &opt, opt_discover);

	*opt++ = CD_LEASE_TIME;
	*opt++ = sizeof (lease);
	lease = htonl(DHCP_PERM);	/* ask for a permanent lease */
	bcopy(&lease, opt, sizeof (lease));
	opt += sizeof (lease);

	/*
	 * If a clientid was set using dhcp_set_client_id(), add this
	 * to the options.
	 */
	if (dhcp_clientid_len > 0) {
		*opt++ = CD_CLIENT_ID;
		*opt++ = dhcp_clientid_len;
		bcopy(dhcp_clientid, opt, dhcp_clientid_len);
		opt += dhcp_clientid_len;
	}

	parameter_request_list(&opt);

	*opt++ = CD_END;

	pkt_size = (uint8_t *)opt - (uint8_t *)pkt;
	if (pkt_size < sizeof (PKT))
		pkt_size = sizeof (PKT);

	nets.s_addr = INADDR_BROADCAST;
	ours.s_addr = INADDR_ANY;
	timeout = 0;	/* reset timeout */

	return (inet(pkt_size, &ours, &nets, DHCP_RETRIES, DHCP_WAIT));
}

/*
 * implements the REQUESTING state of the DHCP client state machine.
 */
static int
dhcp_requesting(void)
{
	PKT_LIST	*pl, *wk;
	PKT		*pkt, *pl_pkt;
	uint8_t		*opt;
	int		pkt_size, err;
	uint32_t	t_time;
	struct in_addr	nets, ours;
	DHCP_OPT	*doptp;
	uint16_t	size;

	/* here we scan the list of OFFERS, select the best one. */
	state_pl = NULL;

	if ((pl = select_best()) == NULL) {
		dprintf("%s: No valid BOOTP reply or DHCP OFFER was found.\n",
		    s_n);
		return (1);
	}

	pl_pkt = pl->pkt;

	/*
	 * Check to see if we got an OFFER pkt(s). If not, then We only got
	 * a response from a BOOTP server. We'll go to the bound state and
	 * try to use that configuration.
	 */
	if (pl->opts[CD_DHCP_TYPE] == NULL) {
		if (mac_call_arp(&pl_pkt->yiaddr, NULL, DHCP_ARP_TIMEOUT)) {
			/* Someone responded! go back to SELECTING state. */
			printf("%s: Some host already using BOOTP %s.\n", s_n,
			    inet_ntoa(pl_pkt->yiaddr));
			bkmem_free((char *)pl->pkt, pl->len);
			bkmem_free((char *)pl, sizeof (PKT_LIST));
			return (1);
		}
		state_pl = pl;
		return (0);
	}

	/*
	 * if we got a message from the server, display it.
	 */
	if (pl->opts[CD_MESSAGE])
		prt_server_msg(pl->opts[CD_MESSAGE]);
	/*
	 * Assemble a DHCPREQUEST, with the ciaddr field set to 0, since we
	 * got here from DISCOVER state. Keep secs field the same for relay
	 * agents. We start with the DHCPOFFER packet we got, and the
	 * options contained in it to make a requested option list.
	 */
	pkt = (PKT *)dhcp_snd_bufp;
	opt = init_msg(pkt, opt_request);

	/* Time from Successful DISCOVER message. */
	pkt->secs = htons((uint16_t)dhcp_secs);

	size = (uint16_t)(dhcp_buf_size - sizeof (struct ip) -
	    sizeof (struct udphdr));
	size = htons(size);
	*opt++ = CD_MAX_DHCP_SIZE;
	*opt++ = sizeof (size);
	bcopy(&size, opt, sizeof (size));
	opt += sizeof (size);

	set_hw_spec_data(pkt, &opt, opt_request);
	*opt++ = CD_SERVER_ID;
	*opt++ = pl->opts[CD_SERVER_ID]->len;
	bcopy(pl->opts[CD_SERVER_ID]->value, opt,
	    pl->opts[CD_SERVER_ID]->len);
	opt += pl->opts[CD_SERVER_ID]->len;

	/* our offered lease minus boot time */
	*opt++ = CD_LEASE_TIME;
	*opt++ = 4;
	bcopy(pl->opts[CD_LEASE_TIME]->value, &t_time,
	    sizeof (t_time));
	t_time = ntohl(t_time);
	if ((uint32_t)t_time != DHCP_PERM)
		t_time -= (uint32_t)dhcp_secs;
	t_time = htonl(t_time);
	bcopy(&t_time, opt, sizeof (t_time));
	opt += sizeof (t_time);

	/* our offered IP address, as required. */
	*opt++ = CD_REQUESTED_IP_ADDR;
	*opt++ = sizeof (struct in_addr);
	bcopy(&pl_pkt->yiaddr, opt, sizeof (struct in_addr));
	opt += sizeof (struct in_addr);

	/*
	 * If a clientid was set using dhcp_set_client_id(), add this
	 * to the options.
	 */
	if (dhcp_clientid_len > 0) {
		*opt++ = CD_CLIENT_ID;
		*opt++ = dhcp_clientid_len;
		bcopy(dhcp_clientid, opt, dhcp_clientid_len);
		opt += dhcp_clientid_len;
	}

	parameter_request_list(&opt);

	*opt++ = CD_END;

	/* Done with the OFFER pkt. */
	bkmem_free((char *)pl->pkt, pl->len);
	bkmem_free((char *)pl, sizeof (PKT_LIST));

	/*
	 * We make 4 attempts here. We wait for 2 seconds to accumulate
	 * requests, just in case a BOOTP server is too fast!
	 */
	pkt_size = (uint8_t *)opt - (uint8_t *)pkt;
	if (pkt_size < sizeof (PKT))
		pkt_size = sizeof (PKT);

	nets.s_addr = INADDR_BROADCAST;
	ours.s_addr = INADDR_ANY;
	timeout = 0;	/* reset timeout */

	if ((err = inet(pkt_size, &ours, &nets, 4, (time_t)2L)) != 0)
		return (err);
	for (wk = list_hd; wk != NULL && state_pl == NULL; wk = wk->next) {
		if (dhcp_options_scan(wk, B_TRUE) != 0 ||
		    !wk->opts[CD_DHCP_TYPE])
			continue;	/* garbled options */
		switch (*wk->opts[CD_DHCP_TYPE]->value) {
		case ACK:
			remove_list(wk, B_FALSE);
			state_pl = wk;
			break;
		case NAK:
			printf("%s: rejected by DHCP server: %s\n",
			    s_n, inet_ntoa(*((struct in_addr *)wk->
			    opts[CD_SERVER_ID]->value)));
			if (wk->opts[CD_MESSAGE])
				prt_server_msg(wk->opts[CD_MESSAGE]);
			break;
		default:
			dprintf("%s: Unexpected DHCP message type.\n", s_n);
			break;
		}
	}
	flush_list();
	if (state_pl != NULL) {
		if (state_pl->opts[CD_MESSAGE])
			prt_server_msg(state_pl->opts[CD_MESSAGE]);
		pl_pkt = state_pl->pkt;
		/* arp our new address, just to make sure */
		if (!mac_call_arp(&pl_pkt->yiaddr, NULL, DHCP_ARP_TIMEOUT)) {
			/*
			 * No response. Check if lease is ok.
			 */
			doptp = state_pl->opts[CD_LEASE_TIME];
			if (state_pl->opts[CD_DHCP_TYPE] && (!doptp ||
			    (doptp->len % 4) != 0)) {
				dhcp_decline("Missing or corrupted lease time",
				    state_pl);
				err++;
			}
		} else {
			dhcp_decline("IP Address already being used!",
			    state_pl);
			err++;
		}
		if (err) {
			bkmem_free((char *)state_pl->pkt, state_pl->len);
			bkmem_free((char *)state_pl, sizeof (PKT_LIST));
			state_pl = NULL;
		} else
			return (0);	/* passes the tests! */
	}
	dprintf("%s: No valid DHCP acknowledge messages received.\n", s_n);
	return (1);
}

/*
 * Implements BOUND state of DHCP client state machine.
 */
static int
dhcp_bound(void)
{
	PKT		*pl_pkt = state_pl->pkt;
	DHCP_OPT	*doptp;
	uint8_t		*tp, *hp;
	int		items, i, fnd, k;
	char		hostname[MAXHOSTNAMELEN+1];
	struct in_addr	subnet, defr, savr, *ipp, xip;

#ifdef	DHCP_DEBUG
	if (dhcp_classid[0] != 0) {
		char 	scratch[DHCP_MAX_OPT_SIZE + 1];

		bcopy(&dhcp_classid[2], scratch, dhcp_classid[1]);
		scratch[dhcp_classid[1]] = '\0';
		printf("Your machine is of the class: '%s'.\n", scratch);
	}
#endif	/* DHCP_DEBUG */

	/* First, set the bare essentials. (IP layer parameters) */

	ipv4_getipaddr(&xip);
	if (xip.s_addr != INADDR_ANY)
		ipp = &xip;
	else {
		ipp = &pl_pkt->yiaddr;
		ipp->s_addr = ntohl(ipp->s_addr);
		ipv4_setipaddr(ipp);
	}

	ipp->s_addr = htonl(ipp->s_addr);

	if (boothowto & RB_VERBOSE)
		printf("%s: IP address is: %s\n", s_n, inet_ntoa(*ipp));

	/*
	 * Ensure that the Boot NFS READ size, if given, is an int16_t.
	 */
	if (state_pl->vs[VS_BOOT_NFS_READSIZE] != NULL) {
		doptp = state_pl->vs[VS_BOOT_NFS_READSIZE];
		if (doptp->len != sizeof (int16_t))
			state_pl->vs[VS_BOOT_NFS_READSIZE] = NULL;
	}

	/*
	 * Set subnetmask. Nice, but not required.
	 */
	if (state_pl->opts[CD_SUBNETMASK] != NULL) {
		doptp = state_pl->opts[CD_SUBNETMASK];
		if (doptp->len != 4)
			state_pl->opts[CD_SUBNETMASK] = NULL;
		else {
			bcopy(doptp->value, &subnet,
			    sizeof (struct in_addr));
			dprintf("%s: Setting netmask to: %s\n", s_n,
			    inet_ntoa(subnet));
			subnet.s_addr = ntohl(subnet.s_addr);
			ipv4_setnetmask(&subnet);
		}
	}

	/*
	 * Set default IP TTL. Nice, but not required.
	 */
	if (state_pl->opts[CD_IPTTL] != NULL) {
		doptp = state_pl->opts[CD_IPTTL];
		if (doptp->len > 1)
			state_pl->opts[CD_IPTTL] = NULL;
		else {
			doptp = state_pl->opts[CD_IPTTL];
			ipv4_setmaxttl(*(uint8_t *)doptp->value);
			dprintf("%s: Setting IP TTL to: %d\n", s_n,
			    *(uint8_t *)doptp->value);
		}
	}

	/*
	 * Set default router. Not required, although we'll know soon
	 * enough...
	 */
	if (state_pl->opts[CD_ROUTER] != NULL) {
		doptp = state_pl->opts[CD_ROUTER];
		if ((doptp->len % 4) != 0) {
			state_pl->opts[CD_ROUTER] = NULL;
		} else {
			if ((hp = (uint8_t *)bkmem_alloc(
			    mac_get_hdr_len())) == NULL) {
				errno = ENOMEM;
				return (-1);
			}
			items = doptp->len / sizeof (struct in_addr);
			tp = doptp->value;
			bcopy(tp, &savr, sizeof (struct in_addr));
			for (i = 0, fnd = 0; i < items; i++) {
				bcopy(tp, &defr, sizeof (struct in_addr));
				for (k = 0, fnd = 0; k < 2 && fnd == 0; k++) {
					fnd = mac_get_arp(&defr, hp,
					    mac_get_hdr_len(),
					    mac_get_arp_timeout());
				}
				if (fnd)
					break;
				dprintf(
				    "%s: Warning: Router %s is unreachable.\n",
				    s_n, inet_ntoa(defr));
				tp += sizeof (struct in_addr);
			}
			bkmem_free((char *)hp, mac_get_hdr_len());

			/*
			 * If fnd is 0, we didn't find a working router. We'll
			 * still try to use first default router. If we got
			 * a bad router address (like not on the same net),
			 * we're hosed anyway.
			 */
			if (!fnd) {
				dprintf(
				    "%s: Warning: Using default router: %s\n",
				    s_n, inet_ntoa(savr));
				defr.s_addr = savr.s_addr;
			}
			/* ipv4_route expects network order IP addresses */
			(void) ipv4_route(IPV4_ADD_ROUTE, RT_DEFAULT, NULL,
			    &defr);
		}
	}

	/*
	 * Set hostname. Not required.
	 */
	if (state_pl->opts[CD_HOSTNAME] != NULL) {
		doptp = state_pl->opts[CD_HOSTNAME];
		i = doptp->len;
		if (i > MAXHOSTNAMELEN)
			i = MAXHOSTNAMELEN;
		bcopy(doptp->value, hostname, i);
		hostname[i] = '\0';
		(void) sethostname(hostname, i);
		if (boothowto & RB_VERBOSE)
			printf("%s: Hostname is %s\n", s_n, hostname);
	}

	/*
	 * We don't care about the lease time.... We can't enforce it anyway.
	 */
	return (0);
}

/*
 * Convert the DHCPACK into a pure ASCII boot property for use by the kernel
 * later in the boot process.
 */
static void
create_bootpresponse_bprop(PKT_LIST *pl)
{
	uint_t	buflen;

	if (pl == NULL || bootp_response != NULL)
		return;

	buflen = (pl->len * 2) + 1;	/* extra space for null (1) */
	if ((bootp_response = bkmem_alloc(buflen)) == NULL)
		return;

	if (octet_to_hexascii((uint8_t *)pl->pkt, pl->len, bootp_response,
	    &buflen) != 0) {
		bkmem_free(bootp_response, (pl->len * 2) + 1);
		bootp_response = NULL;
	}

#if defined(__sparc)
	prom_create_encoded_prop("bootp-response", pl->pkt, pl->len,
	    ENCODE_BYTES);
#endif	/* __sparc */
}

/*
 * Examines /chosen node for "bootp-response" property. If it exists, this
 * property is the DHCPACK cached there by the PROM's DHCP implementation.
 *
 * If cache_present is B_TRUE, we simply return B_TRUE if the property exists
 * w/o decoding it. If cache_present is B_FALSE, we decode the packet and
 * use it as our state packet for the jump to BOUND mode. Note that it's good
 * enough that the cache exists w/o validation for determining if that's what
 * the user intended.
 *
 * We'll short-circuit the DHCP exchange by accepting this packet. We build a
 * PKT_LIST structure, and copy the bootp-response property value into a
 * PKT buffer we allocated. We then scan the PKT for options, and then
 * set state_pl to point to it.
 *
 * Returns B_TRUE if a packet was cached (and was processed correctly), false
 * otherwise. The caller needs to make the state change from SELECTING to
 * BOUND upon a B_TRUE return from this function.
 */
int
prom_cached_reply(int cache_present)
{
	PKT_LIST	*pl;
	int	len;
	pnode_t	chosen;
	char	*prop = PROM_BOOT_CACHED;

	chosen = prom_finddevice("/chosen");
	if (chosen == OBP_NONODE || chosen == OBP_BADNODE)
		chosen = prom_nextnode((pnode_t)0);	/* root node */

	if ((len = prom_getproplen(chosen, prop)) <= 0)
		return (B_FALSE);

	if (cache_present)
		return (B_TRUE);

	if (((pl = (PKT_LIST *)bkmem_zalloc(sizeof (PKT_LIST))) == NULL) ||
	    ((pl->pkt = (PKT *)bkmem_zalloc(len)) == NULL)) {
		errno = ENOMEM;
		if (pl != NULL)
			bkmem_free((char *)pl, sizeof (PKT_LIST));
		return (B_FALSE);
	}

	(void) prom_getprop(chosen, prop, (caddr_t)pl->pkt);

	pl->len = len;

	if (dhcp_options_scan(pl, B_TRUE) != 0) {
		/* garbled packet */
		bkmem_free((char *)pl->pkt, pl->len);
		bkmem_free((char *)pl, sizeof (PKT_LIST));
		return (B_FALSE);
	}

	state_pl = pl;
	return (B_TRUE);
}

/*
 * Perform DHCP to acquire what we used to get using rarp/bootparams.
 * Returns 0 for success, nonzero otherwise.
 *
 * DHCP client state machine.
 */
int
dhcp(void)
{
	int	err = 0;
	int	done = B_FALSE;

	dhcp_buf_size = mac_get_mtu();
	dhcp_snd_bufp = (PKT *)bkmem_alloc(dhcp_buf_size);
	dhcp_rcv_bufp = (PKT *)bkmem_alloc(dhcp_buf_size);

	if (dhcp_snd_bufp == NULL || dhcp_rcv_bufp == NULL) {
		if (dhcp_snd_bufp != NULL)
			bkmem_free((char *)dhcp_snd_bufp, dhcp_buf_size);
		if (dhcp_rcv_bufp != NULL)
			bkmem_free((char *)dhcp_rcv_bufp, dhcp_buf_size);
		errno = ENOMEM;
		return (-1);
	}

	while (err == 0 && !done) {
		switch (dhcp_state) {
		case INIT:

			s_n = "INIT";
			if (prom_cached_reply(B_FALSE)) {
				dprintf("%s: Using PROM cached BOOT reply...\n",
				    s_n);
				dhcp_state = BOUND;
			} else {
				dhcp_state = SELECTING;
				dhcp_start_time = prom_gettime();
			}
			break;

		case SELECTING:

			s_n = "SELECTING";
			err = dhcp_selecting();
			switch (err) {
			case 0:
				dhcp_state = REQUESTING;
				break;
			case DHCP_NO_DATA:
				dprintf(
				    "%s: No DHCP response after %d tries.\n",
				    s_n, DHCP_RETRIES);
				break;
			default:
				/* major network problems */
				dprintf("%s: Network transaction failed: %d\n",
				    s_n, err);
				break;
			}
			break;

		case REQUESTING:

			s_n = "REQUESTING";
			err = dhcp_requesting();
			switch (err) {
			case 0:
				dhcp_state = BOUND;
				break;
			case DHCP_NO_DATA:
				dprintf("%s: Request timed out.\n", s_n);
				dhcp_state = SELECTING;
				err = 0;
				(void) sleep(10);
				break;
			default:
				/* major network problems */
				dprintf("%s: Network transaction failed: %d\n",
				    s_n, err);
				break;
			}
			break;

		case BOUND:

			/*
			 * We just "give up" if bound state fails.
			 */
			s_n = "BOUND";
			if ((err = dhcp_bound()) == 0) {
				dhcp_state = CONFIGURED;
			}
			break;

		case CONFIGURED:
			s_n = "CONFIGURED";
			create_bootpresponse_bprop(state_pl);
			done = B_TRUE;
			break;
		}
	}
	bkmem_free((char *)dhcp_snd_bufp, dhcp_buf_size);
	bkmem_free((char *)dhcp_rcv_bufp, dhcp_buf_size);

	return (err);
}

/*
 * Returns a copy of the DHCP-supplied value of the parameter requested
 * by code.
 */
boolean_t
dhcp_getinfo(uchar_t optcat, uint16_t code, uint16_t optsize, void *value,
    size_t *vallenp)
{
	size_t		len = *vallenp;

	if (dhcp_getinfo_pl(state_pl, optcat, code,
	    optsize, value, &len)) {

		if (len <= *vallenp) {
			*vallenp = len;
			return (B_TRUE);
		}
	}

	return (B_FALSE);
}

/*
 * Sets the clientid option.
 */
void
dhcp_set_client_id(uint8_t *clientid, uint8_t clientid_len)
{
	bcopy(clientid, dhcp_clientid, clientid_len);
	dhcp_clientid_len = clientid_len;
}
/*
 * 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 2002-2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef	_DHCPV4_H
#define	_DHCPV4_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#ifdef	__cplusplus
extern "C" {
#endif

#define	DHCP_NO_DATA	1			/* no data */
#define	DHCP_ARP_TIMEOUT	1000		/* Wait one sec for response */
#define	DHCP_RETRIES	0xffffffff	/* Forever */
#define	DHCP_WAIT	4		/* first wait - 4 seconds */

enum DHCPSTATE { INIT, SELECTING, REQUESTING, BOUND, CONFIGURED };

extern PKT_LIST *state_pl;

extern int dhcp(void);
extern boolean_t dhcp_getinfo(uchar_t, uint16_t, uint16_t, void *, size_t *);
extern void dhcp_set_client_id(uint8_t *, uint8_t);

#ifdef	__cplusplus
}
#endif

#endif	/* _DHCPV4_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.
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"

/*
 * Ethernet routines. Includes ARP and Reverse ARP. Used for ethernet-like
 * media also - so be sure NOT to use ETHERMTU as a mtu limit. macinit()
 * will set this appropriately.
 */

#include <sys/types.h>
#include <socket_impl.h>
#include <socket_inet.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <netinet/in_systm.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/if_ether.h>
#include <sys/promif.h>
#include <sys/prom_plat.h>
#include <sys/salib.h>
#include <sys/bootdebug.h>

#include "ipv4.h"
#include "ipv4_impl.h"
#include "mac.h"
#include "mac_impl.h"
#include "ethernet_inet.h"

ether_addr_t etherbroadcastaddr = {
	0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};

struct arp_packet {
	struct ether_header	arp_eh;
	struct ether_arp	arp_ea;
#define	USED_SIZE (sizeof (struct ether_header) + sizeof (struct ether_arp))
	char	filler[ETHERMIN - sizeof (struct ether_arp)];
};

static char *
ether_print(ether_addr_t ea)
{
	static char eprintbuf[20];

	(void) sprintf(eprintbuf, "%x:%x:%x:%x:%x:%x", ea[0], ea[1], ea[2],
	    ea[3], ea[4], ea[5]);
	return (eprintbuf);
}

/*
 * Common ARP code. Broadcast the packet and wait for the right response.
 *
 * If rarp is called for, caller expects an IPv4 address in the target
 * protocol address (tpa) field of the "out" argument.
 *
 * If arp is called for, caller expects a hardware address in the
 * source hardware address (sha) field of the "out" argument.
 *
 * Returns TRUE if transaction succeeded, FALSE otherwise.
 *
 * The timeout argument is the number of milliseconds to wait for a
 * response. An infinite timeout can be specified as 0xffffffff.
 */
static int
ether_comarp(struct arp_packet *out, uint32_t timeout)
{
	struct arp_packet *in = (struct arp_packet *)mac_state.mac_buf;
	int count, time, feedback, len, delay = 2;
	char    *ind = "-\\|/";
	struct in_addr tmp_ia;
	uint32_t wait_time;

	bcopy((caddr_t)etherbroadcastaddr, (caddr_t)&out->arp_eh.ether_dhost,
	    sizeof (ether_addr_t));
	bcopy((caddr_t)mac_state.mac_addr_buf,
	    (caddr_t)&out->arp_eh.ether_shost, sizeof (ether_addr_t));

	out->arp_ea.arp_hrd =  htons(ARPHRD_ETHER);
	out->arp_ea.arp_pro = htons(ETHERTYPE_IP);
	out->arp_ea.arp_hln = sizeof (ether_addr_t);
	out->arp_ea.arp_pln = sizeof (struct in_addr);
	bcopy(mac_state.mac_addr_buf, (caddr_t)&out->arp_ea.arp_sha,
	    sizeof (ether_addr_t));
	ipv4_getipaddr(&tmp_ia);
	tmp_ia.s_addr = htonl(tmp_ia.s_addr);
	bcopy((caddr_t)&tmp_ia, (caddr_t)out->arp_ea.arp_spa,
	    sizeof (struct in_addr));
	feedback = 0;

	wait_time = prom_gettime() + timeout;
	for (count = 0; timeout == ~0U || prom_gettime() < wait_time; count++) {
		if (count == ETHER_WAITCNT) {
			if (out->arp_ea.arp_op == ARPOP_REQUEST) {
				bcopy((caddr_t)out->arp_ea.arp_tpa,
				    (caddr_t)&tmp_ia, sizeof (struct in_addr));
				printf(
				    "\nRequesting Ethernet address for: %s\n",
				    inet_ntoa(tmp_ia));
			} else {
				printf("\nRequesting Internet address for %s\n",
				    ether_print(out->arp_ea.arp_tha));
			}
		}

		(void) prom_write(mac_state.mac_dev, (caddr_t)out,
		    sizeof (*out), 0, NETWORK);

		if (count >= ETHER_WAITCNT)
			printf("%c\b", ind[feedback++ % 4]); /* activity */

		time = prom_gettime() + (delay * 1000);	/* broadcast delay */
		while (prom_gettime() <= time) {
			len = prom_read(mac_state.mac_dev, mac_state.mac_buf,
			    mac_state.mac_mtu, 0, NETWORK);
			if (len < USED_SIZE)
				continue;
			if (in->arp_ea.arp_pro != ntohs(ETHERTYPE_IP))
				continue;
			if (out->arp_ea.arp_op == ntohs(ARPOP_REQUEST)) {
				if (in->arp_eh.ether_type !=
				    ntohs(ETHERTYPE_ARP))
					continue;
				if (in->arp_ea.arp_op != ntohs(ARPOP_REPLY))
					continue;
				if (bcmp((caddr_t)in->arp_ea.arp_spa,
				    (caddr_t)out->arp_ea.arp_tpa,
				    sizeof (struct in_addr)) != 0)
					continue;
				if (boothowto & RB_VERBOSE) {
					bcopy((caddr_t)in->arp_ea.arp_spa,
					    (caddr_t)&tmp_ia,
					    sizeof (struct in_addr));
					printf("Found %s @ %s\n",
					    inet_ntoa(tmp_ia),
					    ether_print(in->arp_ea.arp_sha));
				}
				/* copy hardware addr into "out" for caller */
				bcopy((caddr_t)&in->arp_ea.arp_sha,
				    (caddr_t)&out->arp_ea.arp_sha,
				    sizeof (ether_addr_t));
				return (TRUE);
			} else {		/* Reverse ARP */
				if (in->arp_eh.ether_type !=
				    ntohs(ETHERTYPE_REVARP))
					continue;
				if (in->arp_ea.arp_op != ntohs(REVARP_REPLY))
					continue;
				if (bcmp((caddr_t)in->arp_ea.arp_tha,
				    (caddr_t)out->arp_ea.arp_tha,
				    sizeof (ether_addr_t)) != 0)
					continue;
				if (boothowto & RB_VERBOSE) {
					bcopy((caddr_t)in->arp_ea.arp_tpa,
					    (caddr_t)&tmp_ia,
					    sizeof (struct in_addr));
					printf("Internet address is: %s\n",
					    inet_ntoa(tmp_ia));
				}
				/* copy IP address into "out" for caller */
				bcopy((caddr_t)in->arp_ea.arp_tpa,
				    (caddr_t)out->arp_ea.arp_tpa,
				    sizeof (struct in_addr));
				return (TRUE);
			}
		}

		delay = delay * 2;	/* Double the request delay */
		if (delay > 64)		/* maximum delay is 64 seconds */
			delay = 64;
	}
	return (FALSE);
}

/*
 * ARP client side
 * Broadcasts to determine MAC address given network order IP address.
 * See RFC 826
 *
 * Returns TRUE if successful, FALSE otherwise.
 */
int
ether_arp(struct in_addr *ip, void *hap, uint32_t timeout)
{
	ether_addr_t *ep = (ether_addr_t *)hap;
	struct arp_packet out;
	int result;

	if (!initialized)
		prom_panic("Ethernet device is not initialized.");

	bzero((char *)&out, sizeof (struct arp_packet));

	out.arp_eh.ether_type = htons(ETHERTYPE_ARP);
	out.arp_ea.arp_op = htons(ARPOP_REQUEST);
	bcopy((caddr_t)etherbroadcastaddr, (caddr_t)&out.arp_ea.arp_tha,
	    sizeof (ether_addr_t));
	bcopy((caddr_t)ip, (caddr_t)out.arp_ea.arp_tpa,
	    sizeof (struct in_addr));

	result = ether_comarp(&out, timeout);

	if (result && (ep != NULL)) {
		bcopy((caddr_t)&out.arp_ea.arp_sha, (caddr_t)ep,
		    sizeof (ether_addr_t));
	}
	return (result);
}

/*
 * Reverse ARP client side
 * Determine our Internet address given our MAC address
 * See RFC 903
 */
void
ether_revarp(void)
{
	struct in_addr	ip;
	struct arp_packet out;

	if (!initialized)
		prom_panic("Ethernet device is not initialized.");

	bzero((char *)&out, sizeof (struct arp_packet));

	out.arp_eh.ether_type = htons(ETHERTYPE_REVARP);
	out.arp_ea.arp_op = htons(REVARP_REQUEST);
	bcopy(mac_state.mac_addr_buf, (caddr_t)&out.arp_ea.arp_tha,
	    sizeof (ether_addr_t));

	/* Wait forever */
	(void) ether_comarp(&out, 0xffffffff);

	bcopy((caddr_t)&out.arp_ea.arp_tpa, (caddr_t)&ip,
	    sizeof (struct in_addr));

	ip.s_addr = ntohl(ip.s_addr);
	ipv4_setipaddr(&ip);
}

/* ARGSUSED */
int
ether_header_len(struct inetgram *igm)
{
	return (sizeof (struct ether_header));
}

/*
 * Handle a IP datagram addressed to our ethernet address or to the
 * ethernet broadcast address. Also respond to ARP requests. Generates
 * inetgrams as long as there's data and the mac level IP timeout timer
 * hasn't expired. As soon as there is no data, we try for
 * ETHER_INPUT_ATTEMPTS for more, then exit the loop, even if there is time
 * left, since we expect to have data waiting for us when we're called, we just
 * don't know how much.
 *
 * We workaround slow proms (some proms have hard sleeps for as much as 3msec)
 * even though there are is data waiting.
 *
 * Returns the total number of MEDIA_LVL frames placed on the socket.
 * Caller is expected to free up the inetgram resources.
 */
int
ether_input(int index)
{
	struct inetgram		*inp;
	struct ether_header	*eh;
	int		frames = 0;	/* successful frames */
	int		attempts = 0;	/* failed attempts after success */
	int16_t		len = 0, data_len;
	uint32_t	timeout, reltime;
	uint32_t	pre_pr, post_pr; /* prom_read interval */

#ifdef	DEBUG
	int		failures = 0;		/* total failures */
	int		total_attempts = 0;	/* total prom_read */
	int		no_data = 0;		/* no data in prom */
	int		arps = 0;		/* arp requests processed */
	uint32_t	tot_pr = 0;		/* prom_read time */
	uint32_t	tot_pc = 0;		/* inetgram creation time */
	uint32_t	pre_pc;
	uint32_t	now;
#endif	/* DEBUG */

	if (!initialized)
		prom_panic("Ethernet device is not initialized.");

	if ((reltime = sockets[index].in_timeout) == 0)
		reltime = mac_state.mac_in_timeout;
	timeout = prom_gettime() + reltime;

	do {
		if (frames > ETHER_MAX_FRAMES) {
			/* someone is trying a denial of service attack */
			break;
		}

		/*
		 * The following is a workaround for a calvin prom (V2) bug
		 * where prom_read() returns a nonzero length, even when it's
		 * not read a packet. So we zero out the header to compensate.
		 */
		bzero(mac_state.mac_buf, sizeof (struct ether_header));

		/*
		 * Prom_read() will return 0 or -2 if no data is present. A
		 * return value of -1 means an error has occurred. We adjust
		 * the timeout by calling the time spent in prom_read() "free".
		 * prom_read() returns the number of bytes actually read, but
		 * will only copy "len" bytes into our buffer. Adjust in
		 * case the MTU is wrong.
		 */
		pre_pr = prom_gettime();
		len = prom_read(mac_state.mac_dev, mac_state.mac_buf,
		    mac_state.mac_mtu, 0, NETWORK);
		post_pr = prom_gettime();
		timeout += (post_pr - pre_pr);
#ifdef	DEBUG
		tot_pr += (post_pr - pre_pr);
		total_attempts++;
#endif	/* DEBUG */

		if (len > mac_state.mac_mtu) {
			dprintf("ether_input: adjusting MTU %d -> %d\n",
			    mac_state.mac_mtu, len);
			bkmem_free(mac_state.mac_buf, mac_state.mac_mtu);
			mac_state.mac_mtu = len;
			mac_state.mac_buf = bkmem_alloc(mac_state.mac_mtu);
			if (mac_state.mac_buf == NULL) {
				prom_panic("ether_input: Cannot reallocate "
				    "netbuf memory.");
			}
			len = 0; /* pretend there was no data */
		}

		if (len == -1) {
#ifdef	DEBUG
			failures++;
#endif	/* DEBUG */
			break;
		}
		if (len == 0 || len == -2) {
			if (frames != 0)
				attempts++;
#ifdef	DEBUG
			no_data++;
#endif	/* DEBUG */
			continue;
		}

		eh = (struct ether_header *)mac_state.mac_buf;
		if (eh->ether_type == ntohs(ETHERTYPE_IP) &&
		    len >= (sizeof (struct ether_header) +
		    sizeof (struct ip))) {

			int offset;
#ifdef	DEBUG
			pre_pc = prom_gettime();
#endif	/* DEBUG */

			inp = (struct inetgram *)bkmem_zalloc(
			    sizeof (struct inetgram));
			if (inp == NULL) {
				errno = ENOMEM;
				return (frames == 0 ? -1 : frames);
			}
			offset = sizeof (struct ether_header);
			data_len = len - offset;
			inp->igm_mp = allocb(data_len, 0);
			if (inp->igm_mp == NULL) {
				errno = ENOMEM;
				bkmem_free((caddr_t)inp,
				    sizeof (struct inetgram));
				return (frames == 0 ? -1 : frames);
			}
			bcopy((caddr_t)(mac_state.mac_buf + offset),
			    inp->igm_mp->b_rptr, data_len);
			inp->igm_mp->b_wptr += data_len;
			inp->igm_level = NETWORK_LVL;
			add_grams(&sockets[index].inq, inp);
			frames++;
			attempts = 0;
#ifdef	DEBUG
			tot_pc += prom_gettime() - pre_pc;
#endif	/* DEBUG */
			continue;
		}

		if (eh->ether_type == ntohs(ETHERTYPE_ARP) &&
		    len >= (sizeof (struct ether_header) +
		    sizeof (struct ether_arp))) {

			struct in_addr		ip;
			struct ether_arp	*ea;

#ifdef	DEBUG
			printf("ether_input: ARP message received\n");
			arps++;
#endif	/* DEBUG */

			ea = (struct ether_arp *)(mac_state.mac_buf +
			    sizeof (struct ether_header));
			if (ea->arp_pro != ntohs(ETHERTYPE_IP))
				continue;

			ipv4_getipaddr(&ip);
			ip.s_addr = ntohl(ip.s_addr);

			if (ea->arp_op == ntohs(ARPOP_REQUEST) &&
			    ip.s_addr != INADDR_ANY &&
			    (bcmp((caddr_t)ea->arp_tpa, (caddr_t)&ip,
			    sizeof (struct in_addr)) == 0)) {
				ea->arp_op = htons(ARPOP_REPLY);
				bcopy((caddr_t)ea->arp_sha,
				    (caddr_t)&eh->ether_dhost,
				    sizeof (ether_addr_t));
				bcopy(mac_state.mac_addr_buf,
				    (caddr_t)&eh->ether_shost,
				    mac_state.mac_addr_len);
				bcopy((caddr_t)ea->arp_sha,
				    (caddr_t)ea->arp_tha,
				    sizeof (ether_addr_t));
				bcopy((caddr_t)ea->arp_spa,
				    (caddr_t)ea->arp_tpa,
				    sizeof (struct in_addr));
				bcopy(mac_state.mac_addr_buf,
				    (caddr_t)ea->arp_sha,
				    mac_state.mac_addr_len);
				bcopy((caddr_t)&ip, (caddr_t)ea->arp_spa,
				    sizeof (struct in_addr));
				(void) prom_write(mac_state.mac_dev,
				    mac_state.mac_buf,
				    sizeof (struct arp_packet),
				    0, NETWORK);
				/* don't charge for ARP replies */
				timeout += reltime;
			}
		}
	} while (attempts < ETHER_INPUT_ATTEMPTS &&
#ifdef	DEBUG
		(now = prom_gettime()) < timeout);
#else
		prom_gettime() < timeout);
#endif	/* DEBUG */

#ifdef	DEBUG
	printf("ether_input(%d): T/S/N/A/F/P/M: %d/%d/%d/%d/%d/%d/%d "
	    "T/O: %d < %d = %s\n", index, total_attempts, frames, no_data,
	    arps, failures, tot_pr, tot_pc, now, timeout,
	    (now < timeout) ? "TRUE" : "FALSE");
#endif	/* DEBUG */
	return (frames);
}

/*
 * Send out an ethernet datagram. We expect a IP frame appropriately fragmented
 * at this level.
 *
 * Errno is set and -1 is returned if an error occurs. Number of bytes sent
 * is returned on success.
 */
/* ARGSUSED */
int
ether_output(int index, struct inetgram *ogp)
{
	int			header_len, result;
	struct ether_header	eh;
	struct ip		*ip;
	struct in_addr		tmpip, ipdst, netid;
	int			broadcast = FALSE;
	int			size;
	mblk_t			*mp;


#ifdef DEBUG
	printf("ether_output (%d): size %d\n", index,
	    ogp->igm_mp->b_wptr - ogp->igm_mp->b_rptr);
#endif
	if (!initialized)
		prom_panic("Ethernet device is not initialized.");

	if (ogp->igm_level != MEDIA_LVL) {
		dprintf("ether_output: frame type wrong: socket: %d\n",
		    index * SOCKETTYPE);
		errno = EINVAL;
		return (-1);
	}

	header_len = sizeof (struct ether_header);
	mp = ogp->igm_mp;
	size = mp->b_wptr - mp->b_rptr;
	if (size > mac_state.mac_mtu) {
		dprintf("ether_output: frame size too big: %d\n", size);
		errno = E2BIG;
		return (-1);
	}

	size += header_len;
	ip = (struct ip *)(mp->b_rptr);

	eh.ether_type = htons(ETHERTYPE_IP);
	bcopy(mac_state.mac_addr_buf, (caddr_t)&eh.ether_shost,
	    mac_state.mac_addr_len);
	bcopy((caddr_t)&ip->ip_dst, (caddr_t)&ipdst, sizeof (ipdst));

	if (ipdst.s_addr == htonl(INADDR_BROADCAST))
		broadcast = TRUE; /* limited broadcast */

	if (!broadcast) {
		struct in_addr mask;

		ipv4_getnetid(&netid);
		ipv4_getnetmask(&mask);
		mask.s_addr = htonl(mask.s_addr);
		netid.s_addr = htonl(netid.s_addr);

		/*
		 * check for all-hosts directed broadcast for
		 * to its own subnet.
		 */
		if (mask.s_addr != htonl(INADDR_BROADCAST) &&
		    (ipdst.s_addr & ~mask.s_addr) == 0 &&
		    (ipdst.s_addr & mask.s_addr) ==  netid.s_addr) {
			broadcast = TRUE; /* directed broadcast */
		} else {
			if (ogp->igm_router.s_addr != htonl(INADDR_ANY))
				tmpip.s_addr = ogp->igm_router.s_addr;
			else
				tmpip.s_addr = ipdst.s_addr;

			result = mac_get_arp(&tmpip, (void *)&eh.ether_dhost,
			    sizeof (ether_addr_t), mac_state.mac_arp_timeout);
			if (!result) {
				errno = ETIMEDOUT;
				dprintf("ether_output: ARP request for %s "
				    "timed out.\n", inet_ntoa(tmpip));
				return (-1);
			}
		}
	}

	if (broadcast) {
		bcopy((caddr_t)etherbroadcastaddr,
		    (caddr_t)&eh.ether_dhost, sizeof (ether_addr_t));
	}

	/* add the ethernet header */
	mp->b_rptr -= sizeof (eh);
	bcopy((caddr_t)&eh, mp->b_rptr, sizeof (eh));
#ifdef	DEBUG
	printf("ether_output(%d): level(%d) frame(0x%x) len(%d)\n",
	    index, ogp->igm_level, mp->b_rptr, size);
#if DEBUG > 1
	printf("Dump ethernet (%d): \n", size);
	hexdump((char *)mp->b_rptr, size);
	printf("\n");
#endif /* DEBUG > 1 */
#endif	/* DEBUG */
	return (prom_write(mac_state.mac_dev, (char *)mp->b_rptr, size,
	    0, NETWORK));
}
/*
 * 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 1990-1999, 2001-2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 *
 * Ethernet implementation-specific definitions
 */

#ifndef _ETHERNET_INET_H
#define	_ETHERNET_INET_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#ifdef	__cplusplus
extern "C" {
#endif

#define	ETHERSIZE	(ETHERMTU + 50)	/* Usually a little bigger than 1500 */
#define	ETHER_ARP_TIMEOUT	(300000)	/* in milliseconds */
#define	ETHER_IN_TIMEOUT	(5)	/* msecond wait for IP frames */
#define	ETHER_MAX_FRAMES	(200)	/* Maximum of consecutive frames */
#define	ETHER_INPUT_ATTEMPTS	(8)	/* Number of consecutive attempts */
#define	ETHER_WAITCNT		(2)	/* Activity interval */

extern int ether_header_len(struct inetgram *);
extern int ether_arp(struct in_addr *, void *, uint32_t);
extern void ether_revarp(void);
extern int ether_input(int);
extern int ether_output(int, struct inetgram *);

#ifdef	__cplusplus
}
#endif

#endif /* _ETHERNET_INET_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) 1990-1999, Sun Microsystems, Inc.
 *
 * FDDI implementation-specific definitions
 */

#ifndef _FDDI_INET_H
#define	_FDDI_INET_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#ifdef	__cplusplus
extern "C" {
#endif

#define	FDDISIZE		(4500)	/* Default FDDI MTU size */
#define	FDDI_ARP_TIMEOUT	(300000)	/* in milliseconds */
#define	FDDI_IN_TIMEOUT		(4)	/* milliseconds wait for IP input */

#ifdef	__cplusplus
}
#endif

#endif /* _FDDI_INET_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.
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#include <dhcp_impl.h>
#include <sys/types.h>
#include <socket_impl.h>
#include <socket_inet.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <netinet/in_systm.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/if_ether.h>
#include <sys/promif.h>
#include <sys/prom_plat.h>
#include <sys/salib.h>
#include <sys/bootdebug.h>
#include <sys/ib/clients/ibd/ibd.h>

#include "ipv4.h"
#include "dhcpv4.h"
#include "ipv4_impl.h"
#include "mac.h"
#include "mac_impl.h"
#include "ibd_inet.h"

struct ibd_arp {
	struct arphdr	ea_hdr;		/* fixed-size header */
	ipoib_mac_t	arp_sha;	/* sender hardware address */
	uchar_t		arp_spa[4];	/* sender protocol address */
	ipoib_mac_t	arp_tha;	/* target hardware address */
	uchar_t		arp_tpa[4];	/* target protocol address */
};

extern int errno;
ipoib_mac_t ibdbroadcastaddr;

/*
 * Assumptions about OBP behavior (refer FWARC 2002/702, 2003/251):
 * 1. prom_write() accepts the 20 byte destination address as the
 * first component in the send buffer. The buffer pointer points
 * to the start of this 20 byte address. The length parameter is
 * the IPoIB datagram size with the 20 byte of destination
 * address.
 * 2. OBP will not provide max-frame-size, since obp can only
 * determine that by querying the IBA mcg, and thus the property
 * has to be /chosen:ipib-frame-size. This will refer to the IPoIB
 * link MTU as per section 4.0 of ietf i/d, ie, the 4 byte IPoIB
 * header plus the IP payload mtu. Plus the 20 bytes of addressing
 * information.
 * 3. OBP will not provide mac-address property for IPoIB since there
 * are built in assumptions about 6 byte address with that. Instead,
 * /chosen:ipib-address will provide the local address.
 * 4. prom_read() returns 20 byte 0'ed filler followed by 4 byte
 * IPoIB header followed by IP payload. The return value is -2,
 * -1, 0, or the length of the received IPoIB datagram alongwith
 * the 20 bytes MBZ. The buffer pointer points to the start of
 * the 20 MBZ bytes. The length parameter reflects the max data
 * size that should be copied into the buffer including the 20
 * MBZ bytes.
 * 5. OBP will not provide chosen-network-type, only
 * network-interface-type = ipib. On an Infiniband device, this
 * however does not guarantee that it is a network device.
 * 6. OBP will provide the DHCP client id in /chosen:client-id.
 * 7. /chosen:ipib-broadcast will provide the broadcast address.
 * 8. OBP will validate that RARP is not being used before
 * allowing boot to proceed to inetboot.
 */

struct arp_packet {
	ipoib_ptxhdr_t		arp_eh;
	struct ibd_arp		arp_ea;
};

#define	dprintf	if (boothowto & RB_DEBUG) printf

static char *
ibd_print(ipoib_mac_t *ea)
{
	unsigned char *macaddr = (unsigned char *)ea;
	static char pbuf[(3 * IPOIB_ADDRL) + 1];
	int i;
	char *ptr = pbuf;

	ptr = pbuf + sprintf(pbuf, "%x", *macaddr++);
	for (i = 0; i < (IPOIB_ADDRL - 1); i++)
		ptr += sprintf(ptr, ":%x", *macaddr++);
	return (pbuf);
}


/*
 * Common ARP code. Broadcast the packet and wait for the right response.
 *
 * If arp is called for, caller expects a hardware address in the
 * source hardware address (sha) field of the "out" argument.
 *
 * IPoIB does not support RARP (see ibd_revarp()).
 *
 * Returns TRUE if transaction succeeded, FALSE otherwise.
 *
 * The timeout argument is the number of milliseconds to wait for a
 * response. An infinite timeout can be specified as 0xffffffff.
 */
static int
ibd_comarp(struct arp_packet *out, uint32_t timeout)
{
	struct arp_packet *in = (struct arp_packet *)mac_state.mac_buf;
	int count, time, feedback, len, delay = 2;
	char    *ind = "-\\|/";
	struct in_addr tmp_ia;
	uint32_t wait_time;

	bcopy((caddr_t)&ibdbroadcastaddr, (caddr_t)&out->arp_eh.ipoib_dest,
	    IPOIB_ADDRL);

	out->arp_ea.arp_hrd =  htons(ARPHRD_IB);
	out->arp_ea.arp_pro = htons(ETHERTYPE_IP);
	out->arp_ea.arp_hln = IPOIB_ADDRL;
	out->arp_ea.arp_pln = sizeof (struct in_addr);
	bcopy(mac_state.mac_addr_buf, (caddr_t)&out->arp_ea.arp_sha,
	    IPOIB_ADDRL);
	ipv4_getipaddr(&tmp_ia);
	tmp_ia.s_addr = htonl(tmp_ia.s_addr);
	bcopy((caddr_t)&tmp_ia, (caddr_t)out->arp_ea.arp_spa,
	    sizeof (struct in_addr));
	feedback = 0;

	wait_time = prom_gettime() + timeout;
	for (count = 0; timeout == ~0U || prom_gettime() < wait_time; count++) {
		if (count == IBD_WAITCNT) {
			/*
			 * Since IPoIB does not support RARP (see ibd_revarp),
			 * we know that out->arp_ea.arp_op == ARPOP_REQUEST.
			 */
			bcopy((caddr_t)out->arp_ea.arp_tpa,
			    (caddr_t)&tmp_ia, sizeof (struct in_addr));
			printf("\nRequesting MAC address for: %s\n",
			    inet_ntoa(tmp_ia));
		}

		(void) prom_write(mac_state.mac_dev, (caddr_t)out,
		    sizeof (*out), 0, NETWORK);

		if (count >= IBD_WAITCNT)
			printf("%c\b", ind[feedback++ % 4]); /* activity */

		time = prom_gettime() + (delay * 1000);	/* broadcast delay */
		while (prom_gettime() <= time) {
			len = prom_read(mac_state.mac_dev, mac_state.mac_buf,
			    mac_state.mac_mtu, 0, NETWORK);
			if (len < sizeof (struct arp_packet))
				continue;
			if (in->arp_ea.arp_pro != ntohs(ETHERTYPE_IP))
				continue;
			/*
			 * Since IPoIB does not support RARP (see ibd_revarp),
			 * we know that out->arp_ea.arp_op == ARPOP_REQUEST.
			 */
			if (in->arp_eh.ipoib_rhdr.ipoib_type !=
			    ntohs(ETHERTYPE_ARP))
				continue;
			if (in->arp_ea.arp_op != ntohs(ARPOP_REPLY))
				continue;
			if (bcmp((caddr_t)in->arp_ea.arp_spa,
			    (caddr_t)out->arp_ea.arp_tpa,
			    sizeof (struct in_addr)) != 0)
				continue;
			if (boothowto & RB_VERBOSE) {
				bcopy((caddr_t)in->arp_ea.arp_spa,
				    (caddr_t)&tmp_ia,
				    sizeof (struct in_addr));
				printf("Found %s @ %s\n",
				    inet_ntoa(tmp_ia),
				    ibd_print(&in->arp_ea.arp_sha));
			}
			/* copy hardware addr into "out" for caller */
			bcopy((caddr_t)&in->arp_ea.arp_sha,
			    (caddr_t)&out->arp_ea.arp_sha, IPOIB_ADDRL);
			return (TRUE);
		}

		delay = delay * 2;	/* Double the request delay */
		if (delay > 64)		/* maximum delay is 64 seconds */
			delay = 64;
	}
	return (FALSE);
}

/*
 * ARP client side
 * Broadcasts to determine MAC address given network order IP address.
 * See RFC 826
 *
 * Returns TRUE if successful, FALSE otherwise.
 */
static int
ibd_arp(struct in_addr *ip, void *hap, uint32_t timeout)
{
	ipoib_mac_t *ep = (ipoib_mac_t *)hap;
	struct arp_packet out;
	int result;

	if (!initialized)
		prom_panic("IPoIB device is not initialized.");

	bzero((char *)&out, sizeof (struct arp_packet));

	out.arp_eh.ipoib_rhdr.ipoib_type = htons(ETHERTYPE_ARP);
	out.arp_ea.arp_op = htons(ARPOP_REQUEST);
	bcopy((caddr_t)&ibdbroadcastaddr, (caddr_t)&out.arp_ea.arp_tha,
	    IPOIB_ADDRL);
	bcopy((caddr_t)ip, (caddr_t)out.arp_ea.arp_tpa,
	    sizeof (struct in_addr));

	result = ibd_comarp(&out, timeout);

	if (result && (ep != NULL)) {
		bcopy((caddr_t)&out.arp_ea.arp_sha, (caddr_t)ep, IPOIB_ADDRL);
	}
	return (result);
}

/*
 * Reverse ARP client side
 * Determine our Internet address given our MAC address
 * See RFC 903
 */
static void
ibd_revarp(void)
{
	prom_panic("IPoIB can not boot with RARP.");
}

/* ARGSUSED */
static int
ibd_header_len(struct inetgram *igm)
{
	/*
	 * We indicate to upper layers to leave enough space
	 * in output buffers for filling in the IPoIB header
	 * and the 20 byte destination address in ibd_output().
	 */
	return (IPOIB_HDRSIZE + IPOIB_ADDRL);
}

/*
 * Handle a IP datagram addressed to our MAC address or to the link
 * layer broadcast address. Also respond to ARP requests. Generates
 * inetgrams as long as there's data and the mac level IP timeout timer
 * hasn't expired. As soon as there is no data, we try for
 * IBD_INPUT_ATTEMPTS for more, then exit the loop, even if there is time
 * left, since we expect to have data waiting for us when we're called, we just
 * don't know how much.
 *
 * We workaround slow proms (some proms have hard sleeps for as much as 3msec)
 * even though there are is data waiting.
 *
 * Returns the total number of MEDIA_LVL frames placed on the socket.
 * Caller is expected to free up the inetgram resources.
 */
static int
ibd_input(int index)
{
	struct inetgram		*inp;
	ipoib_ptxhdr_t		*eh;
	int		frames = 0;	/* successful frames */
	int		attempts = 0;	/* failed attempts after success */
	int16_t		len = 0, data_len;
	uint32_t	timeout, reltime;
	uint32_t	pre_pr, post_pr; /* prom_read interval */

#ifdef	DEBUG
	int		failures = 0;		/* total failures */
	int		total_attempts = 0;	/* total prom_read */
	int		no_data = 0;		/* no data in prom */
	int		arps = 0;		/* arp requests processed */
	uint32_t	tot_pr = 0;		/* prom_read time */
	uint32_t	tot_pc = 0;		/* inetgram creation time */
	uint32_t	pre_pc;
	uint32_t	now;
#endif	/* DEBUG */

	if (!initialized)
		prom_panic("IPoIB device is not initialized.");

	if ((reltime = sockets[index].in_timeout) == 0)
		reltime = mac_state.mac_in_timeout;
	timeout = prom_gettime() + reltime;

	do {
		if (frames > IBD_MAX_FRAMES) {
			/* someone is trying a denial of service attack */
			break;
		}

		/*
		 * The following is being paranoid about possible bugs
		 * where prom_read() returns a nonzero length, even when
		 * it's not read a packet; it zeroes out the header to
		 * compensate. Paranoia from calvin prom (V2) days.
		 */
		bzero(mac_state.mac_buf, sizeof (ipoib_ptxhdr_t));

		/*
		 * Prom_read() will return 0 or -2 if no data is present. A
		 * return value of -1 means an error has occurred. We adjust
		 * the timeout by calling the time spent in prom_read() "free".
		 * prom_read() returns the number of bytes actually read, but
		 * will only copy "len" bytes into our buffer. Adjust in
		 * case the MTU is wrong.
		 */
		pre_pr = prom_gettime();
		len = prom_read(mac_state.mac_dev, mac_state.mac_buf,
		    mac_state.mac_mtu, 0, NETWORK);
		post_pr = prom_gettime();
		timeout += (post_pr - pre_pr);
#ifdef	DEBUG
		tot_pr += (post_pr - pre_pr);
		total_attempts++;
#endif	/* DEBUG */

		if (len > mac_state.mac_mtu) {
			dprintf("ibd_input: adjusting MTU %d -> %d\n",
			    mac_state.mac_mtu, len);
			bkmem_free(mac_state.mac_buf, mac_state.mac_mtu);
			mac_state.mac_mtu = len;
			mac_state.mac_buf = bkmem_alloc(mac_state.mac_mtu);
			if (mac_state.mac_buf == NULL) {
				prom_panic("ibd_input: Cannot reallocate "
				    "netbuf memory.");
			}
			len = 0; /* pretend there was no data */
		}

		if (len == -1) {
#ifdef	DEBUG
			failures++;
#endif	/* DEBUG */
			break;
		}
		if (len == 0 || len == -2) {
			if (frames != 0)
				attempts++;
#ifdef	DEBUG
			no_data++;
#endif	/* DEBUG */
			continue;
		}

		eh = (ipoib_ptxhdr_t *)mac_state.mac_buf;
		if (eh->ipoib_rhdr.ipoib_type == ntohs(ETHERTYPE_IP) &&
		    len >= (sizeof (ipoib_ptxhdr_t) + sizeof (struct ip))) {

			int offset;
#ifdef	DEBUG
			pre_pc = prom_gettime();
#endif	/* DEBUG */

			inp = (struct inetgram *)bkmem_zalloc(
			    sizeof (struct inetgram));
			if (inp == NULL) {
				errno = ENOMEM;
				return (frames == 0 ? -1 : frames);
			}
			offset = sizeof (ipoib_ptxhdr_t);
			data_len = len - offset;
			inp->igm_mp = allocb(data_len, 0);
			if (inp->igm_mp == NULL) {
				errno = ENOMEM;
				bkmem_free((caddr_t)inp,
				    sizeof (struct inetgram));
				return (frames == 0 ? -1 : frames);
			}
			bcopy((caddr_t)(mac_state.mac_buf + offset),
			    inp->igm_mp->b_rptr, data_len);
			inp->igm_mp->b_wptr += data_len;
			inp->igm_level = NETWORK_LVL;
			add_grams(&sockets[index].inq, inp);
			frames++;
			attempts = 0;
#ifdef	DEBUG
			tot_pc += prom_gettime() - pre_pc;
#endif	/* DEBUG */
			continue;
		}

		if (eh->ipoib_rhdr.ipoib_type == ntohs(ETHERTYPE_ARP) &&
		    len >= sizeof (struct arp_packet)) {

			struct in_addr		ip;
			struct ibd_arp		*ea;

#ifdef	DEBUG
			printf("ibd_input: ARP message received\n");
			arps++;
#endif	/* DEBUG */

			ea = (struct ibd_arp *)(mac_state.mac_buf +
			    sizeof (ipoib_ptxhdr_t));
			if (ea->arp_pro != ntohs(ETHERTYPE_IP))
				continue;

			ipv4_getipaddr(&ip);
			ip.s_addr = ntohl(ip.s_addr);

			if (ea->arp_op == ntohs(ARPOP_REQUEST) &&
			    ip.s_addr != INADDR_ANY &&
			    (bcmp((caddr_t)ea->arp_tpa, (caddr_t)&ip,
			    sizeof (struct in_addr)) == 0)) {
				ea->arp_op = htons(ARPOP_REPLY);
				bcopy((caddr_t)&ea->arp_sha,
				    (caddr_t)&eh->ipoib_dest, IPOIB_ADDRL);
				bcopy((caddr_t)&ea->arp_sha,
				    (caddr_t)&ea->arp_tha, IPOIB_ADDRL);
				bcopy((caddr_t)ea->arp_spa,
				    (caddr_t)ea->arp_tpa,
				    sizeof (struct in_addr));
				bcopy(mac_state.mac_addr_buf,
				    (caddr_t)&ea->arp_sha,
				    mac_state.mac_addr_len);
				bcopy((caddr_t)&ip, (caddr_t)ea->arp_spa,
				    sizeof (struct in_addr));
				(void) prom_write(mac_state.mac_dev,
				    mac_state.mac_buf,
				    sizeof (struct arp_packet), 0, NETWORK);
				/* don't charge for ARP replies */
				timeout += reltime;
			}
		}
	} while (attempts < IBD_INPUT_ATTEMPTS &&
#ifdef	DEBUG
	    (now = prom_gettime()) < timeout);
#else
	    prom_gettime() < timeout);
#endif	/* DEBUG */

#ifdef	DEBUG
	printf("ibd_input(%d): T/S/N/A/F/P/M: %d/%d/%d/%d/%d/%d/%d "
	    "T/O: %d < %d = %s\n", index, total_attempts, frames, no_data,
	    arps, failures, tot_pr, tot_pc, now, timeout,
	    (now < timeout) ? "TRUE" : "FALSE");
#endif	/* DEBUG */
	return (frames);
}

/*
 * Send out an IPoIB datagram. We expect a IP frame appropriately fragmented
 * at this level.
 *
 * Errno is set and -1 is returned if an error occurs. Number of bytes sent
 * is returned on success.
 */
/* ARGSUSED */
static int
ibd_output(int index, struct inetgram *ogp)
{
	int			header_len, result;
	ipoib_ptxhdr_t		eh;
	struct ip		*ip;
	struct in_addr		tmpip, ipdst;
	int			broadcast = FALSE;
	int			size;
	mblk_t			*mp;

	if (!initialized)
		prom_panic("IPoIB device is not initialized.");

	if (ogp->igm_level != MEDIA_LVL) {
		dprintf("ibd_output: frame type wrong: socket: %d\n",
		    index * SOCKETTYPE);
		errno = EINVAL;
		return (-1);
	}

	header_len = IPOIB_HDRSIZE + IPOIB_ADDRL;
	mp = ogp->igm_mp;
	size = mp->b_wptr - mp->b_rptr;
	if (size > (mac_state.mac_mtu - IPOIB_ADDRL)) {
		dprintf("ibd_output: frame size too big: %d\n", size);
		errno = E2BIG;
		return (-1);
	}

	size += header_len;
	ip = (struct ip *)(mp->b_rptr);

	eh.ipoib_rhdr.ipoib_type = htons(ETHERTYPE_IP);
	eh.ipoib_rhdr.ipoib_mbz = 0;
	bcopy((caddr_t)&ip->ip_dst, (caddr_t)&ipdst, sizeof (ipdst));

	if (ipdst.s_addr == htonl(INADDR_BROADCAST))
		broadcast = TRUE; /* limited broadcast */

	if (!broadcast) {
		struct in_addr mask;

		ipv4_getnetmask(&mask);
		mask.s_addr = htonl(mask.s_addr);
		if (mask.s_addr != htonl(INADDR_BROADCAST) &&
		    (ipdst.s_addr & ~mask.s_addr) == 0) {
			broadcast = TRUE; /* directed broadcast */
		} else {
			if (ogp->igm_router.s_addr != htonl(INADDR_ANY))
				tmpip.s_addr = ogp->igm_router.s_addr;
			else
				tmpip.s_addr = ipdst.s_addr;

			result = mac_get_arp(&tmpip, (void *)&eh.ipoib_dest,
			    IPOIB_ADDRL, mac_state.mac_arp_timeout);
			if (!result) {
				errno = ETIMEDOUT;
				dprintf("ibd_output: ARP request for %s "
				    "timed out.\n", inet_ntoa(tmpip));
				return (-1);
			}
		}
	}

	if (broadcast)
		bcopy((caddr_t)&ibdbroadcastaddr, (caddr_t)&eh.ipoib_dest,
		    IPOIB_ADDRL);

	/* add the ibd header */
	mp->b_rptr -= sizeof (eh);
	bcopy((caddr_t)&eh, mp->b_rptr, sizeof (eh));

#ifdef	DEBUG
	printf("ibd_output(%d): level(%d) frame(0x%x) len(%d)\n",
	    index, ogp->igm_level, mp->b_rptr, size);
#endif	/* DEBUG */

	return (prom_write(mac_state.mac_dev, (char *)mp->b_rptr, size,
	    0, NETWORK));
}

void
ibd_init(void)
{
	pnode_t	chosen;
	char	*mtuprop = "ipib-frame-size";
	char	*bcastprop = "ipib-broadcast";
	char	*addrprop = "ipib-address";
	char	*cidprop = "client-id";
	int	cidlen;
	uint8_t	dhcpcid[DHCP_MAX_CID_LEN];

	mac_state.mac_addr_len = IPOIB_ADDRL;
	mac_state.mac_addr_buf = bkmem_alloc(mac_state.mac_addr_len);
	if (mac_state.mac_addr_buf == NULL)
		prom_panic("ibd_init: Cannot allocate memory.");

	chosen = prom_finddevice("/chosen");
	if (chosen == OBP_NONODE || chosen == OBP_BADNODE)
		prom_panic("ibd_init: Cannot find /chosen.");

	if (prom_getprop(chosen, addrprop, (caddr_t)mac_state.mac_addr_buf) !=
	    IPOIB_ADDRL)
		prom_panic("ibd_init: Cannot find /chosen:ipib-address\n.");

	if (prom_getprop(chosen, bcastprop, (caddr_t)&ibdbroadcastaddr) !=
	    IPOIB_ADDRL)
		prom_panic("ibd_init: Cannot find /chosen:ipib-broadcast\n.");

	if (((cidlen = prom_getproplen(chosen, cidprop)) <= 0) ||
	    (cidlen > DHCP_MAX_CID_LEN) || (prom_getprop(chosen, cidprop,
	    (caddr_t)&dhcpcid) != cidlen))
		prom_panic("ibd_init: Invalid /chosen:client-id\n.");
	dhcp_set_client_id(dhcpcid, cidlen);

	/*
	 * Note that prom reports mtu including 20 bytes of
	 * addressing information.
	 */
	if (prom_getprop(chosen, mtuprop,
	    (caddr_t)&mac_state.mac_mtu) <= 0)
		mac_state.mac_mtu = IBDSIZE + IPOIB_ADDRL;

	/*
	 * Tell upper layers that we can support a little
	 * more. We will be taking off these 20 bytes at
	 * the start before we invoke prom_write() to send
	 * over the wire.
	 */
	mac_state.mac_arp_timeout = IBD_ARP_TIMEOUT;
	mac_state.mac_in_timeout = IBD_IN_TIMEOUT;

	mac_state.mac_arp = ibd_arp;
	mac_state.mac_rarp = ibd_revarp;
	mac_state.mac_header_len = ibd_header_len;
	mac_state.mac_input = ibd_input;
	mac_state.mac_output = ibd_output;
}
/*
 * 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 2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef _IBD_INET_H
#define	_IBD_INET_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#ifdef	__cplusplus
extern "C" {
#endif

#define	IBDSIZE			(2048)
#define	IBD_ARP_TIMEOUT		(300000) /* in milliseconds */
#define	IBD_IN_TIMEOUT		(5)	/* msecond wait for IP frames */
#define	IBD_MAX_FRAMES		(200)	/* Maximum of consecutive frames */
#define	IBD_INPUT_ATTEMPTS	(8)	/* Number of consecutive attempts */
#define	IBD_WAITCNT		(2)	/* Activity interval */

extern void ibd_init(void);

#ifdef	__cplusplus
}
#endif

#endif /* _IBD_INET_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 1991-2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 *
 * icmp4.c, Code implementing the Internet Control Message Protocol (v4) ICMP.
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#include <sys/types.h>
#include <socket_impl.h>
#include <socket_inet.h>
#include <sys/salib.h>
#include <sys/socket.h>
#include <netinet/in_systm.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/udp.h>
#include <netinet/ip_icmp.h>
#include <sys/bootconf.h>
#include <sys/fcntl.h>

#include "icmp4.h"
#include "ipv4.h"
#include "ipv4_impl.h"
#include "mac.h"
#include "v4_sum_impl.h"
#include <sys/bootdebug.h>

/*
 * Handle ICMP redirects, ICMP echo messages. We only deal with redirects to a
 * different default router by changing the default route to the specified
 * value.
 */
void
icmp4(struct inetgram *igp, struct ip *iphp, uint16_t iphlen,
struct in_addr ipsrc)
{
	int		icmp_len;
	struct in_addr	our_ip;
	struct icmp	*icmphp;

	icmp_len = ntohs(iphp->ip_len) - iphlen;
	if (icmp_len < ICMP_MINLEN) {
#ifdef	DEBUG
		printf("icmp4: ICMP message from %s is too short\n",
		    inet_ntoa(ipsrc));
#endif	/* DEBUG */
		return;
	}

	icmphp = (struct icmp *)(igp->igm_mp->b_rptr + iphlen);

	/* check alignment */
	if ((uintptr_t)icmphp % sizeof (uint16_t)) {
		dprintf("icmp4: ICMP header not aligned (from %s)\n",
		    inet_ntoa(ipsrc));
		return;
	}
	if (ipv4cksum((uint16_t *)icmphp, icmp_len) != 0) {
		dprintf("icmp4: Bad ICMP checksum (from %s)\n",
		    inet_ntoa(ipsrc));
		return;
	}
	switch (icmphp->icmp_type) {
	case ICMP_REDIRECT:
		if (icmphp->icmp_code != ICMP_REDIRECT_HOST)
			break;
		dprintf("ICMP Redirect to gateway %s.\n",
		    inet_ntoa(icmphp->icmp_gwaddr));
		if (ipv4_route(IPV4_ADD_ROUTE, RT_HOST, &icmphp->icmp_ip.ip_dst,
		    &icmphp->icmp_gwaddr) != 0) {
			dprintf("icmp4: Cannot add route %s, %d\n",
			    inet_ntoa(icmphp->icmp_ip.ip_dst), errno);
		}
		break;
	case ICMP_UNREACH:
		/*
		 * Need to highlight an error on the socket, and save the
		 * destination address so that we can ensure it is destined
		 * to this socket. We need the port number to be sure...
		 */
		dprintf("ICMP destination unreachable (%s)\n",
		    inet_ntoa(icmphp->icmp_ip.ip_dst));
		break;
	case ICMP_ECHO:
		/*
		 * swap the source and destination IP addresses
		 * and send a reply right out.
		 */
		ipv4_getipaddr(&our_ip);
		if (our_ip.s_addr != INADDR_ANY) {
			int			s;
			struct sockaddr_in	dest;

			if ((s = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0) {
				dprintf("icmp4: socket: %d\n", errno);
				break;
			}
			icmphp->icmp_type = ICMP_ECHOREPLY;
			icmphp->icmp_cksum = 0;
			icmphp->icmp_cksum = ipv4cksum((uint16_t *)icmphp,
			    icmp_len);
			dest.sin_family = AF_INET;
			dest.sin_addr.s_addr = ipsrc.s_addr;
			dest.sin_port = htons(0);
			(void) sendto(s, (caddr_t)icmphp, icmp_len, 0,
			    (const struct sockaddr *)&dest, sizeof (dest));
			(void) socket_close(s);
		}
		break;
	default:
		dprintf("icmp4: Unsupported ICMP message type: 0x%x "
		    "received from %s\n", icmphp->icmp_type, inet_ntoa(ipsrc));
		break;
	}
}
/*
 * 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, Sun Microsystems, Inc.
 * All rights reserved.
 *
 * ICMPv4 implementation-specific definitions
 */

#ifndef _ICMP4_H
#define	_ICMP4_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#ifdef	__cplusplus
extern "C" {
#endif

extern void icmp4(struct inetgram *, struct ip *, uint16_t, struct in_addr);

#ifdef	__cplusplus
}
#endif

#endif /* _ICMP4_H */
#!/bin/sh
#
# 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 2003 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# ident	"%Z%%M%	%I%	%E% SMI"

find_files "s.*" usr/src/common/net/dhcp
/*
 * 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.
 *
 * ipv4.c, Code implementing the IPv4 internet protocol.
 */

#include <sys/types.h>
#include <socket_impl.h>
#include <socket_inet.h>
#include <sys/sysmacros.h>
#include <sys/socket.h>
#include <netinet/in_systm.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/udp.h>
#include <net/if_arp.h>
#include <sys/promif.h>
#include <sys/bootconf.h>
#include <sys/fcntl.h>
#include <sys/salib.h>

#include "icmp4.h"
#include "ipv4.h"
#include "ipv4_impl.h"
#include "mac.h"
#include "mac_impl.h"
#include "v4_sum_impl.h"
#include <sys/bootdebug.h>

static struct ip_frag	fragment[FRAG_MAX];	/* ip fragment buffers */
static int		fragments;		/* Number of fragments */
static uint8_t		ttl = MAXTTL;		/* IP ttl */
static struct in_addr	myip;			/* our network-order IP addr */
static struct in_addr	mynet;			/* net-order netaddr */
static struct in_addr	netmask =
	{ 0xff, 0xff, 0xff, 0xff };		/* our network-order netmask */
static boolean_t	netmask_set = B_FALSE;	/* has anyone set netmask? */
static struct in_addr	defaultrouter;		/* net-order defaultrouter */
static int		promiscuous;		/* promiscuous mode */
static struct routing table[IPV4_ROUTE_TABLE_SIZE];

static uint16_t	g_ip_id;

#ifdef	DEBUG
#define	FRAG_DEBUG
#endif	/* DEBUG */

#ifdef FRAG_DEBUG
/*
 * display the fragment list. For debugging purposes.
 */
static void
frag_disp(uint16_t size)
{
	int	i;
	uint_t	total = 0;

	printf("Dumping fragment info: (%d)\n\n", fragments);
	printf("More:\tOffset:\tDatap:\t\tIPid:\t\tIPlen:\tIPhlen:\n");
	for (i = 0; i < FRAG_MAX; i++) {
		if (fragment[i].mp == NULL)
			continue;
		printf("%d\t%d\t0x%x\t%d\t\t%d\t%d\n", fragment[i].more,
		    fragment[i].offset, fragment[i].mp->b_rptr,
		    fragment[i].ipid, fragment[i].iplen, fragment[i].iphlen);
		total += (fragment[i].iplen - fragment[i].iphlen);
	}
	printf("Total length is: %d. It should be: %d\n\n", total, size);
}
#endif /* FRAG_DEBUG */

/*
 * This function returns index of fragment 0 of the current fragmented DGRAM
 * (which would contain the transport header). Return the fragment number
 * for success, -1 if we don't yet have the first fragment.
 */
static int
frag_first(void)
{
	int		i;

	if (fragments == 0)
		return (-1);

	for (i = 0; i < FRAG_MAX; i++) {
		if (fragment[i].mp != NULL && fragment[i].offset == 0)
			return (i);
	}
	return (-1);
}

/*
 * This function returns index of the last fragment of the current DGRAM.
 * Returns the fragment number for success, -1 if we don't yet have the
 * last fragment.
 */
static int
frag_last(void)
{
	int		i;

	if (fragments == 0)
		return (-1);

	for (i = 0; i < FRAG_MAX; i++) {
		if (fragment[i].mp != NULL && !fragment[i].more)
			return (i);
	}
	return (-1);
}

/*
 * This function adds a fragment to the current pkt fragment list. Returns
 * FRAG_NOSLOTS if there are no more slots, FRAG_DUP if the fragment is
 * a duplicate, or FRAG_SUCCESS if it is successful.
 */
static int
frag_add(int16_t offset, mblk_t *mp, uint16_t ipid,
    int16_t iplen, int16_t iphlen, uint8_t ipp)
{
	int	i;
	int16_t	true_offset = IPV4_OFFSET(offset);

	/* first pass - look for duplicates */
	for (i = 0; i < FRAG_MAX; i++) {
		if (fragment[i].mp != NULL &&
		    fragment[i].offset == true_offset)
			return (FRAG_DUP);
	}

	/* second pass - fill in empty slot */
	for (i = 0; i < FRAG_MAX; i++) {
		if (fragment[i].mp == NULL) {
			fragment[i].more = (offset & IP_MF);
			fragment[i].offset = true_offset;
			fragment[i].mp = mp;
			fragment[i].ipid = ipid;
			fragment[i].iplen = iplen;
			fragment[i].iphlen = iphlen;
			fragment[i].ipp = ipp;
			fragments++;
			return (FRAG_SUCCESS);
		}
	}
	return (FRAG_NOSLOTS);
}

/*
 * Nuke a fragment.
 */
static void
frag_free(int index)
{
	if (fragment[index].mp != NULL) {
		freeb(fragment[index].mp);
		fragments--;
	}
	bzero((caddr_t)&fragment[index], sizeof (struct ip_frag));
}

/*
 * zero the frag list.
 */
static void
frag_flush(void)
{
	int i;

	for (i = 0; i < FRAG_MAX; i++)
		frag_free(i);

	fragments = 0;
}

/*
 * Analyze the fragment list - see if we captured all our fragments.
 *
 * Returns TRUE if we've got all the fragments, and FALSE if we don't.
 */
static int
frag_chk(void)
{
	int		i, first_frag, last_frag;
	int16_t		actual, total;
	uint16_t	ip_id;
	uint8_t		ipp;

	if (fragments == 0 || (first_frag = frag_first()) < 0 ||
	    (last_frag = frag_last()) < 0)
		return (FALSE);

	/*
	 * Validate the ipid's of our fragments - nuke those that don't
	 * match the id of the first fragment or don't match the IP
	 * protocol of the first fragment.
	 */
	ip_id = fragment[first_frag].ipid;
	ipp = fragment[first_frag].ipp;
	for (i = 0; i < FRAG_MAX; i++) {
		if (fragment[i].mp != NULL && ip_id != fragment[i].ipid &&
		    fragment[i].ipp != ipp) {
#ifdef FRAG_DEBUG
			printf("ipv4: Frag id mismatch: %x != %x\n",
			    fragment[i].ipid, ip_id);
#endif /* FRAG_DEBUG */
			frag_free(i);
		}
	}

	if (frag_last() < 0)
		return (FALSE);

	total = fragment[last_frag].offset + fragment[last_frag].iplen -
	    fragment[last_frag].iphlen;

	for (i = 0, actual = 0; i < FRAG_MAX; i++)
		actual += (fragment[i].iplen - fragment[i].iphlen);

#ifdef FRAG_DEBUG
	frag_disp(total);
#endif /* FRAG_DEBUG */

	return (total == actual);
}

/*
 * Load the assembled fragments into igp. Returns 0 for success, nonzero
 * otherwise.
 */
static int
frag_load(struct inetgram *igp)
{
	int	i;
	int16_t	len;
	uint_t	total_len;
	boolean_t first_frag = B_FALSE;
	mblk_t *mp;
	struct ip *iph;
	int first_iph_len;

	if (fragments == 0)
		return (ENOENT);

	mp = igp->igm_mp;
	/* Get the IP header length of the first fragment. */
	i = frag_first();
	assert(i >= 0);
	first_iph_len = fragment[i].iphlen;
	for (i = 0, len = 0, total_len = 0; i < FRAG_MAX; i++) {
		if (fragment[i].mp != NULL) {
			/*
			 * Copy just the data (omit the ip header of all
			 * fragments except the first one which contains
			 * all the info...)
			 */
			if (fragment[i].offset == 0) {
				len = fragment[i].iplen;
				first_frag = B_TRUE;
			} else {
				len = fragment[i].iplen - fragment[i].iphlen;
			}
			total_len += len;
			if (total_len > mp->b_size)
				return (E2BIG);
			if (first_frag) {
				bcopy((caddr_t)(fragment[i].mp->b_rptr),
				    (caddr_t)mp->b_rptr, len);
				first_frag = B_FALSE;
			} else {
				bcopy((caddr_t)(fragment[i].mp->b_rptr +
				    fragment[i].iphlen),
				    (caddr_t)(mp->b_rptr + first_iph_len +
				    fragment[i].offset), len);
			}
			mp->b_wptr += len;
		}
	}
	/* Fix the total length in the IP header. */
	iph = (struct ip *)mp->b_rptr;
	iph->ip_len = htons(total_len);
	return (0);
}

/*
 * Locate a routing table entry based upon arguments. IP addresses expected
 * in network order. Returns index for success, -1 if entry not found.
 */
static int
find_route(uint8_t *flagp, struct in_addr *destp, struct in_addr *gatewayp)
{
	int i, table_entry = -1;

	for (i = 0; table_entry == -1 && i < IPV4_ROUTE_TABLE_SIZE; i++) {
		if (flagp != NULL) {
			if (*flagp & table[i].flag)
				table_entry = i;
		}
		if (destp != NULL) {
			if (destp->s_addr == table[i].dest.s_addr)
				table_entry = i;
			else
				table_entry = -1;
		}
		if (gatewayp != NULL) {
			if (gatewayp->s_addr == table[i].gateway.s_addr)
				table_entry = i;
			else
				table_entry = -1;
		}
	}
	return (table_entry);
}

/*
 * ADD or DEL a routing table entry. Returns 0 for success, -1 and errno
 * otherwise. IP addresses are expected in network order.
 */
int
ipv4_route(int cmd, uint8_t flag, struct in_addr *destp,
    struct in_addr *gatewayp)
{
	static	int	routing_table_initialized;
	int		index;
	uint8_t		tmp_flag;

	if (gatewayp == NULL) {
		errno = EINVAL;
		return (-1);
	}

	/* initialize routing table */
	if (routing_table_initialized == 0) {
		for (index = 0; index < IPV4_ROUTE_TABLE_SIZE; index++)
			table[index].flag = RT_UNUSED;
		routing_table_initialized = 1;
	}

	switch (cmd) {
	case IPV4_ADD_ROUTE:
		tmp_flag = (uint8_t)RT_UNUSED;
		if ((index = find_route(&tmp_flag, NULL, NULL)) == -1) {
			dprintf("ipv4_route: routing table full.\n");
			errno = ENOSPC;
			return (-1);
		}
		table[index].flag = flag;
		if (destp != NULL)
			table[index].dest.s_addr = destp->s_addr;
		else
			table[index].dest.s_addr = htonl(INADDR_ANY);
		table[index].gateway.s_addr = gatewayp->s_addr;
		break;
	case IPV4_BAD_ROUTE:
		/* FALLTHRU */
	case IPV4_DEL_ROUTE:
		if ((index = find_route(&flag, destp, gatewayp)) == -1) {
			dprintf("ipv4_route: No such routing entry.\n");
			errno = ENOENT;
			return (-1);
		}
		if (cmd == IPV4_DEL_ROUTE) {
			table[index].flag = RT_UNUSED;
			table[index].dest.s_addr = htonl(INADDR_ANY);
			table[index].gateway.s_addr = htonl(INADDR_ANY);
		} else {
			table[index].flag = RT_NG;
		}
		break;
	default:
		errno = EINVAL;
		return (-1);
	}
	return (0);
}

/*
 * Return gateway to destination. Returns gateway IP address in network order
 * for success, NULL if no route to destination exists.
 */
struct in_addr *
ipv4_get_route(uint8_t flag, struct in_addr *destp, struct in_addr *gatewayp)
{
	int index;
	if ((index = find_route(&flag, destp, gatewayp)) == -1)
		return (NULL);
	return (&table[index].gateway);
}

/*
 * Initialize the IPv4 generic parts of the socket, as well as the routing
 * table.
 */
void
ipv4_socket_init(struct inetboot_socket *isp)
{
	isp->input[NETWORK_LVL] = ipv4_input;
	isp->output[NETWORK_LVL] = ipv4_output;
	isp->close[NETWORK_LVL] = NULL;
	isp->headerlen[NETWORK_LVL] = ipv4_header_len;
}

/*
 * Initialize a raw ipv4 socket.
 */
void
ipv4_raw_socket(struct inetboot_socket *isp, uint8_t proto)
{
	isp->type = INETBOOT_RAW;
	if (proto == 0)
		isp->proto = IPPROTO_IP;
	else
		isp->proto = proto;
	isp->input[TRANSPORT_LVL] = NULL;
	isp->output[TRANSPORT_LVL] = NULL;
	isp->headerlen[TRANSPORT_LVL] = NULL;
	isp->ports = NULL;
}

/*
 * Return the size of an IPv4 header (no options)
 */
/* ARGSUSED */
int
ipv4_header_len(struct inetgram *igm)
{
	return (sizeof (struct ip));
}

/*
 * Set our source address.
 * Argument is assumed to be host order.
 */
void
ipv4_setipaddr(struct in_addr *ip)
{
	myip.s_addr = htonl(ip->s_addr);
}

/*
 * Returns our current source address in host order.
 */
void
ipv4_getipaddr(struct in_addr *ip)
{
	ip->s_addr = ntohl(myip.s_addr);
}

/*
 * Set our netmask.
 * Argument is assumed to be host order.
 */
void
ipv4_setnetmask(struct in_addr *ip)
{
	netmask_set = B_TRUE;
	netmask.s_addr = htonl(ip->s_addr);
	mynet.s_addr = netmask.s_addr & myip.s_addr; /* implicit */
}

void
ipv4_getnetid(struct in_addr *my_netid)
{
	struct in_addr my_netmask;
	if (mynet.s_addr != 0)
		my_netid->s_addr = ntohl(mynet.s_addr);
	else {
		ipv4_getnetmask(&my_netmask);
		my_netid->s_addr = my_netmask.s_addr & ntohl(myip.s_addr);
	}
}

/*
 * Returns our current netmask in host order.
 * Neither OBP nor the standalone DHCP client mandate
 * that the netmask be specified, so in the absence of
 * a netmask, we attempt to derive it using class-based
 * heuristics.
 */
void
ipv4_getnetmask(struct in_addr *ip)
{
	if (netmask_set || (myip.s_addr == 0))
		ip->s_addr = ntohl(netmask.s_addr);
	else {
		/* base the netmask on our IP address */
		if (IN_CLASSA(ntohl(myip.s_addr)))
			ip->s_addr = ntohl(IN_CLASSA_NET);
		else if (IN_CLASSB(ntohl(myip.s_addr)))
			ip->s_addr = ntohl(IN_CLASSB_NET);
		else if (IN_CLASSC(ntohl(myip.s_addr)))
			ip->s_addr = ntohl(IN_CLASSC_NET);
		else
			ip->s_addr = ntohl(IN_CLASSE_NET);
	}
}

/*
 * Set our default router.
 * Argument is assumed to be host order, and *MUST* be on the same network
 * as our source IP address.
 */
void
ipv4_setdefaultrouter(struct in_addr *ip)
{
	defaultrouter.s_addr = htonl(ip->s_addr);
}

/*
 * Returns our current default router in host order.
 */
void
ipv4_getdefaultrouter(struct in_addr *ip)
{
	ip->s_addr = ntohl(defaultrouter.s_addr);
}

/*
 * Toggle promiscuous flag. If set, client disregards destination IP
 * address. Otherwise, only limited broadcast, network broadcast, and
 * unicast traffic get through. Returns previous setting.
 */
int
ipv4_setpromiscuous(int toggle)
{
	int old = promiscuous;

	promiscuous = toggle;

	return (old);
}

/*
 * Set IP TTL.
 */
void
ipv4_setmaxttl(uint8_t cttl)
{
	ttl = cttl;
}

/*
 * Convert an ipv4 address to dotted notation.
 * Returns ptr to statically allocated buffer containing dotted string.
 */
char *
inet_ntoa(struct in_addr ip)
{
	uint8_t *p;
	static char ipaddr[16];

	p = (uint8_t *)&ip.s_addr;
	(void) sprintf(ipaddr, "%u.%u.%u.%u", p[0], p[1], p[2], p[3]);
	return (ipaddr);
}

/*
 * Construct a transport datagram from a series of IP fragments (igp == NULL)
 * or from a single IP datagram (igp != NULL). Return the address of the
 * contructed transport datagram.
 */
struct inetgram *
make_trans_datagram(int index, struct inetgram *igp, struct in_addr ipsrc,
    struct in_addr ipdst, uint16_t iphlen)
{
	uint16_t	trans_len, *transp, new_len;
	int		first_frag, last_frag;
	boolean_t	fragmented;
	struct inetgram	*ngp;
	struct ip	*iph;

	fragmented = (igp == NULL);

	ngp = (struct inetgram *)bkmem_zalloc(sizeof (struct inetgram));
	if (ngp == NULL) {
		errno = ENOMEM;
		if (fragmented)
			frag_flush();
		return (NULL);
	}

	if (fragmented) {
		last_frag = frag_last();
		trans_len = fragment[last_frag].offset +
		    fragment[last_frag].iplen - fragment[last_frag].iphlen;
		first_frag = frag_first();
		/*
		 * The returned buffer contains the IP header of the
		 * first fragment.
		 */
		trans_len += fragment[first_frag].iphlen;
		transp = (uint16_t *)(fragment[first_frag].mp->b_rptr +
		    fragment[first_frag].iphlen);
	} else {
		/*
		 * Note that igm_len may not be the real length of an
		 * IP packet because some network interface, such as
		 * Ethernet, as a minimum frame size.  So we should not
		 * use the interface frame size to determine the
		 * length of an IP packet.  We should use the IP
		 * length field in the IP header.
		 */
		iph = (struct ip *)igp->igm_mp->b_rptr;
		trans_len = ntohs(iph->ip_len);
		transp = (uint16_t *)(igp->igm_mp->b_rptr + iphlen);
	}

	ngp->igm_saddr.sin_addr.s_addr = ipsrc.s_addr;
	ngp->igm_saddr.sin_port = sockets[index].ports(transp, SOURCE);
	ngp->igm_target.s_addr = ipdst.s_addr;
	ngp->igm_level = TRANSPORT_LVL;

	/*
	 * Align to 16bit value.  Checksum code may require an extra byte
	 * for padding.
	 */
	new_len = ((trans_len + sizeof (int16_t) - 1) &
	    ~(sizeof (int16_t) - 1));
	if ((ngp->igm_mp = allocb(new_len, 0)) == NULL) {
		errno = ENOMEM;
		bkmem_free((caddr_t)ngp, sizeof (struct inetgram));
		if (fragmented)
			frag_flush();
		return (NULL);
	}

	if (fragmented) {
		if (frag_load(ngp) != 0) {
			freeb(ngp->igm_mp);
			bkmem_free((caddr_t)ngp, sizeof (struct inetgram));
			frag_flush();
			return (NULL);
		}
		frag_flush();
	} else {
		bcopy((caddr_t)(igp->igm_mp->b_rptr),
		    (caddr_t)ngp->igm_mp->b_rptr, trans_len);
		ngp->igm_mp->b_wptr += trans_len;
	}
	return (ngp);
}

/*
 * ipv4_input: Pull in IPv4 datagrams addressed to us. Handle IP fragmentation
 * (fragments received in any order) and ICMP at this level.
 *
 * Note that because our network is serviced by polling when we expect
 * something (upon a referenced socket), we don't go through the work of
 * locating the appropriate socket a datagram is destined for. We'll only
 * accept data for the referenced socket. This means we don't have
 * asynchronous networking, but since we can't service the net using an
 * interrupt handler, it doesn't do us any good to try to service datagrams
 * destined for sockets other than the referenced one. Data is handled in
 * a fifo manner.
 *
 * The mac layer will grab all frames for us. If we find we don't have all
 * the necessary fragments to reassemble the datagram, we'll call the mac
 * layer again for FRAG_ATTEMPTS to see if it has any more frames.
 *
 * Supported protocols: IPPROTO_IP, IPPROTO_ICMP, IPPROTO_UDP.
 *
 * Returns: number of NETWORK_LVL datagrams placed on socket , -1 if error
 * occurred.
 *
 * Note: errno is set to ETIMEDOUT if fragment reassembly fails.
 */
int
ipv4_input(int index)
{
	int			datagrams = 0;
	int			frag_stat, input_attempts = 0;
	uint16_t		iphlen, iplen, ip_id;
	int16_t			curr_off;
	struct ip		*iphp;
	struct inetgram		*igp, *newgp = NULL, *ipv4_listp = NULL;
	struct in_addr		ipdst, ipsrc;
	mblk_t			*mp;
	enum SockType		type;

#ifdef	DEBUG
	printf("ipv4_input(%d): start ######################################\n",
	    index);
#endif	/* DEBUG */

	frag_flush();

ipv4_try_again:

	while ((igp = sockets[index].inq) != NULL) {
		if (igp->igm_level != NETWORK_LVL) {
#ifdef	DEBUG
			printf("ipv4_input(%d): unexpected frame type: %d\n",
			    index, igp->igm_level);
#endif	/* DEBUG */
			del_gram(&sockets[index].inq, igp, TRUE);
			continue;
		}
		iphp = (struct ip *)igp->igm_mp->b_rptr;
		if (iphp->ip_v != IPVERSION) {
			dprintf("ipv4_input(%d): IPv%d datagram discarded\n",
			    index, iphp->ip_v);
			del_gram(&sockets[index].inq, igp, TRUE);
			continue;
		}
		iphlen = iphp->ip_hl << 2;
		if (iphlen < sizeof (struct ip)) {
			dprintf("ipv4_input(%d): IP msg too short (%d < %u)\n",
			    index, iphlen, (uint_t)sizeof (struct ip));
			del_gram(&sockets[index].inq, igp, TRUE);
			continue;
		}
		iplen = ntohs(iphp->ip_len);
		if (iplen > msgdsize(igp->igm_mp)) {
			dprintf("ipv4_input(%d): IP len/buffer mismatch "
			    "(%d > %lu)\n", index, iplen, igp->igm_mp->b_size);
			del_gram(&sockets[index].inq, igp, TRUE);
			continue;
		}

		bcopy((caddr_t)&(iphp->ip_dst), (caddr_t)&ipdst,
		    sizeof (ipdst));
		bcopy((caddr_t)&(iphp->ip_src), (caddr_t)&ipsrc,
		    sizeof (ipsrc));

		/* igp->igm_mp->b_datap is guaranteed to be 64 bit aligned] */
		if (ipv4cksum((uint16_t *)iphp, iphlen) != 0) {
			dprintf("ipv4_input(%d): Bad IP header checksum "
			    "(to %s)\n", index, inet_ntoa(ipdst));
			del_gram(&sockets[index].inq, igp, TRUE);
			continue;
		}

		if (!promiscuous) {
			/* validate destination address */
			if (ipdst.s_addr != htonl(INADDR_BROADCAST) &&
			    ipdst.s_addr != (mynet.s_addr | ~netmask.s_addr) &&
			    ipdst.s_addr != myip.s_addr) {
#ifdef	DEBUG
				printf("ipv4_input(%d): msg to %s discarded.\n",
				    index, inet_ntoa(ipdst));
#endif	/* DEBUG */
				/* not ours */
				del_gram(&sockets[index].inq, igp, TRUE);
				continue;
			}
		}

		/* Intercept ICMP first */
		if (!promiscuous && (iphp->ip_p == IPPROTO_ICMP)) {
			icmp4(igp, iphp, iphlen, ipsrc);
			del_gram(&sockets[index].inq, igp, TRUE);
			continue;
		}

#ifdef	DEBUG
		printf("ipv4_input(%d): processing ID: 0x%x protocol %d "
		    "(0x%x) (0x%x,%d)\n",
		    index, ntohs(iphp->ip_id), iphp->ip_p, igp, igp->igm_mp,
		    igp->igm_mp->b_size);
#endif	/* DEBUG */
		type = sockets[index].type;
		if (type == INETBOOT_RAW) {
			/* No fragmentation - Just the raw packet. */
#ifdef	DEBUG
			printf("ipv4_input(%d): Raw packet.\n", index);
#endif	/* DEBUG */
			del_gram(&sockets[index].inq, igp, FALSE);
			add_grams(&ipv4_listp, igp);
			igp->igm_mp->b_rptr += iphlen;
			igp->igm_mp->b_wptr = igp->igm_mp->b_rptr + iplen;
			datagrams++;
			continue;
		}

		if ((type == INETBOOT_DGRAM && iphp->ip_p != IPPROTO_UDP) ||
		    (type == INETBOOT_STREAM && iphp->ip_p != IPPROTO_TCP)) {
			/* Wrong protocol. */
			dprintf("ipv4_input(%d): unexpected protocol: "
			    "%d for socket type %d\n", index, iphp->ip_p, type);
			del_gram(&sockets[index].inq, igp, TRUE);
			continue;
		}

		/*
		 * The following code is common to both STREAM and DATAGRAM
		 * sockets.
		 */

		/*
		 * Once we process the first fragment, we won't have
		 * the transport header, so we'll have to  match on
		 * IP id.
		 */
		curr_off = ntohs(iphp->ip_off);
		if ((curr_off & ~(IP_DF | IP_MF)) == 0) {
			uint16_t	*transp;

			/* Validate transport header. */
			mp = igp->igm_mp;
			if ((mp->b_wptr - mp->b_rptr - iphlen) <
			    sockets[index].headerlen[TRANSPORT_LVL](igp)) {
				dprintf("ipv4_input(%d): datagram 0 "
				    "too small to hold transport header "
				    "(from %s)\n", index, inet_ntoa(ipsrc));
				del_gram(&sockets[index].inq, igp, TRUE);
				continue;
			}

			/*
			 * check alignment - transport elements are 16
			 * bit aligned..
			 */
			transp = (uint16_t *)(mp->b_rptr + iphlen);
			if ((uintptr_t)transp % sizeof (uint16_t)) {
				dprintf("ipv4_input(%d): Transport "
				    "header is not 16-bit aligned "
				    "(0x%lx, from %s)\n", index, (long)transp,
				    inet_ntoa(ipsrc));
				del_gram(&sockets[index].inq, igp, TRUE);
				continue;
			}

			if (curr_off & IP_MF) {
				/* fragment 0 of fragmented datagram */
				ip_id = ntohs(iphp->ip_id);
				frag_stat = frag_add(curr_off, igp->igm_mp,
				    ip_id, iplen, iphlen, iphp->ip_p);
				if (frag_stat != FRAG_SUCCESS) {
#ifdef	FRAG_DEBUG
					if (frag_stat == FRAG_DUP) {
						printf("ipv4_input"
						    "(%d): Frag dup.\n", index);
					} else {
						printf("ipv4_input"
						    "(%d): too many "
						    "frags\n", index);
					}
#endif	/* FRAG_DEBUG */
					del_gram(&sockets[index].inq,
					    igp, TRUE);
					continue;
				}

				del_gram(&sockets[index].inq, igp, FALSE);
				/* keep the data, lose the inetgram */
				bkmem_free((caddr_t)igp,
				    sizeof (struct inetgram));
#ifdef	FRAG_DEBUG
				printf("ipv4_input(%d): Frag/Off/Id "
				    "(%d/%d/%x)\n", index, fragments,
				    IPV4_OFFSET(curr_off), ip_id);
#endif	/* FRAG_DEBUG */
			} else {
				/* Single, unfragmented datagram */
				newgp = make_trans_datagram(index, igp,
				    ipsrc, ipdst, iphlen);
				if (newgp != NULL) {
					add_grams(&ipv4_listp, newgp);
					datagrams++;
				}
				del_gram(&sockets[index].inq, igp,
				    TRUE);
				continue;
			}
		} else {
			/* fragments other than 0 */
			frag_stat = frag_add(curr_off, igp->igm_mp,
			    ntohs(iphp->ip_id), iplen, iphlen, iphp->ip_p);

			if (frag_stat == FRAG_SUCCESS) {
#ifdef	FRAG_DEBUG
				printf("ipv4_input(%d): Frag(%d) "
				    "off(%d) id(%x)\n", index,
				    fragments, IPV4_OFFSET(curr_off),
				    ntohs(iphp->ip_id));
#endif	/* FRAG_DEBUG */
				del_gram(&sockets[index].inq, igp, FALSE);
				/* keep the data, lose the inetgram */
				bkmem_free((caddr_t)igp,
				    sizeof (struct inetgram));
			} else {
#ifdef	FRAG_DEBUG
				if (frag_stat == FRAG_DUP)
					printf("ipv4_input(%d): Frag "
					    "dup.\n", index);
				else {
					printf("ipv4_input(%d): too "
					    "many frags\n", index);
				}
#endif	/* FRAG_DEBUG */
				del_gram(&sockets[index].inq, igp, TRUE);
				continue;
			}
		}

		/*
		 * Determine if we have all of the fragments.
		 *
		 * NOTE: at this point, we've placed the data in the
		 * fragment table, and the inetgram (igp) has been
		 * deleted.
		 */
		if (!frag_chk())
			continue;

		newgp = make_trans_datagram(index, NULL, ipsrc, ipdst, iphlen);
		if (newgp == NULL)
			continue;
		add_grams(&ipv4_listp, newgp);
		datagrams++;
	}
	if (ipv4_listp == NULL && fragments != 0) {
		if (++input_attempts > FRAG_ATTEMPTS) {
			dprintf("ipv4_input(%d): reassembly(%d) timed out in "
			    "%d msecs.\n", index, fragments,
			    sockets[index].in_timeout * input_attempts);
			frag_flush();
			errno = ETIMEDOUT;
			return (-1);
		} else {
			/*
			 * Call the media layer again... there may be more
			 * packets waiting.
			 */
			if (sockets[index].input[MEDIA_LVL](index) < 0) {
				/* errno will be set appropriately */
				frag_flush();
				return (-1);
			}
			goto ipv4_try_again;
		}
	}

	add_grams(&sockets[index].inq, ipv4_listp);

	return (datagrams);
}

/*
 * ipv4_output: Generate IPv4 datagram(s) for the payload and deliver them.
 * Routing is handled here as well, by reusing the saddr field to hold the
 * router's IP address.
 *
 * We don't deal with fragmentation on the outgoing side.
 *
 * Arguments: index to socket, inetgram to send.
 *
 * Returns: 0 for success, -1 if error occurred.
 */
int
ipv4_output(int index, struct inetgram *ogp)
{
	struct ip	*iphp;
	uint64_t	iphbuffer[sizeof (struct ip)];

#ifdef	DEBUG
	printf("ipv4_output(%d): size %d\n", index,
	    ogp->igm_mp->b_wptr - ogp->igm_mp->b_rptr);
#endif	/* DEBUG */

	/* we don't deal (yet) with fragmentation. Maybe never will */
	if ((ogp->igm_mp->b_wptr - ogp->igm_mp->b_rptr) > mac_get_mtu()) {
		dprintf("ipv4: datagram too big for MAC layer.\n");
		errno = E2BIG;
		return (-1);
	}

	if (ogp->igm_level != NETWORK_LVL) {
#ifdef	DEBUG
		printf("ipv4_output(%d): unexpected frame type: %d\n", index,
		    ogp->igm_level);
#endif	/* DEBUG */
		errno = EINVAL;
		return (-1);
	}

	if (sockets[index].out_flags & SO_DONTROUTE)
		ogp->igm_oflags |= MSG_DONTROUTE;

	iphp = (struct ip *)&iphbuffer;
	iphp->ip_v = IPVERSION;
	iphp->ip_hl = sizeof (struct ip) / 4;
	iphp->ip_tos = 0;
	iphp->ip_len = htons(ogp->igm_mp->b_wptr - ogp->igm_mp->b_rptr +
	    sizeof (struct ip));
	iphp->ip_id = htons(++g_ip_id);
	iphp->ip_off = htons(IP_DF);
	iphp->ip_p = sockets[index].proto;
	iphp->ip_sum = htons(0);
	iphp->ip_ttl = ttl;

	/* struct copies */
	iphp->ip_src = myip;
	iphp->ip_dst = ogp->igm_saddr.sin_addr;

	/*
	 * On local / limited broadcasts, don't route. From a purist's
	 * perspective, we should be setting the TTL to 1. But
	 * operational experience has shown that some BOOTP relay agents
	 * (ciscos) discard our packets. Furthermore, these devices also
	 * *don't* reset the TTL to MAXTTL on the unicast side of the
	 * BOOTP relay agent! Sigh. Thus to work correctly in these
	 * environments, we leave the TTL as it has been been set by
	 * the application layer, and simply don't check for a route.
	 */
	if (iphp->ip_dst.s_addr == htonl(INADDR_BROADCAST) ||
	    (netmask.s_addr != htonl(INADDR_BROADCAST) &&
	    iphp->ip_dst.s_addr == (mynet.s_addr | ~netmask.s_addr))) {
		ogp->igm_oflags |= MSG_DONTROUTE;
	}

	/* Routing necessary? */
	if ((ogp->igm_oflags & MSG_DONTROUTE) == 0 &&
	    ((iphp->ip_dst.s_addr & netmask.s_addr) != mynet.s_addr)) {
		struct in_addr *rip;
		if ((rip = ipv4_get_route(RT_HOST, &iphp->ip_dst,
		    NULL)) == NULL) {
			rip = ipv4_get_route(RT_DEFAULT, NULL, NULL);
		}
		if (rip == NULL) {
			dprintf("ipv4(%d): No route to %s.\n",
			    index, inet_ntoa(iphp->ip_dst));
			errno = EHOSTUNREACH;
			return (-1);
		}
		ogp->igm_router.s_addr = rip->s_addr;
	} else
		ogp->igm_router.s_addr = htonl(INADDR_ANY);

	iphp->ip_sum = ipv4cksum((uint16_t *)iphp, sizeof (struct ip));
	ogp->igm_mp->b_rptr -= sizeof (struct ip);
	bcopy((caddr_t)iphp, (caddr_t)(ogp->igm_mp->b_rptr),
	    sizeof (struct ip));

	ogp->igm_level = MEDIA_LVL;

	return (0);
}

/*
 * Function to be called by TCP to send out a packet.  This is used
 * when TCP wants to send out packets which it has already filled in
 * most of the header fields.
 */
int
ipv4_tcp_output(int sock_id, mblk_t *pkt)
{
	struct ip *iph;
	struct in_addr *rip = NULL;
	struct inetgram datagram;

	iph = (struct ip *)pkt->b_rptr;

	bzero(&datagram, sizeof (struct inetgram));

	/*
	 * Bootparams doesn't know about subnet masks, so we need to
	 * explicitly check for this flag.
	 */
	if (sockets[sock_id].out_flags & SO_DONTROUTE)
		datagram.igm_oflags |= MSG_DONTROUTE;

	/* Routing necessary? */
	if (((datagram.igm_oflags & MSG_DONTROUTE) == 0) &&
	    ((iph->ip_dst.s_addr & netmask.s_addr) != mynet.s_addr)) {
		if ((rip = ipv4_get_route(RT_HOST, &iph->ip_dst,
		    NULL)) == NULL) {
			rip = ipv4_get_route(RT_DEFAULT, NULL, NULL);
		}
		if (rip == NULL) {
			dprintf("ipv4(%d): No route to %s.\n",
			    sock_id, inet_ntoa(iph->ip_dst));
			errno = EHOSTUNREACH;
			return (-1);
		}
	}

	iph->ip_id = htons(++g_ip_id);
	iph->ip_sum = ipv4cksum((uint16_t *)iph, sizeof (struct ip));
#if DEBUG > 1
	printf("ipv4_tcp_output: dump IP packet(%d)\n", iph->ip_len);
	hexdump((char *)pkt->b_rptr, iph->ip_len);
#endif
	/* Call the MAC layer output routine to send it out. */
	datagram.igm_mp = pkt;
	datagram.igm_level = MEDIA_LVL;
	if (rip != NULL)
		datagram.igm_router.s_addr = rip->s_addr;
	else
		datagram.igm_router.s_addr = 0;
	return (mac_state.mac_output(sock_id, &datagram));
}

/*
 * Internet address interpretation routine.
 * All the network library routines call this
 * routine to interpret entries in the data bases
 * which are expected to be an address.
 * The value returned is in network order.
 */
in_addr_t
inet_addr(const char *cp)
{
	uint32_t val, base, n;
	char c;
	uint32_t parts[4], *pp = parts;

	if (*cp == '\0')
		return ((uint32_t)-1); /* disallow null string in cp */
again:
	/*
	 * Collect number up to ``.''.
	 * Values are specified as for C:
	 * 0x=hex, 0=octal, other=decimal.
	 */
	val = 0; base = 10;
	if (*cp == '0') {
		if (*++cp == 'x' || *cp == 'X')
			base = 16, cp++;
		else
			base = 8;
	}
	while ((c = *cp) != '\0') {
		if (isdigit(c)) {
			if ((c - '0') >= base)
				break;
			val = (val * base) + (c - '0');
			cp++;
			continue;
		}
		if (base == 16 && isxdigit(c)) {
			val = (val << 4) + (c + 10 - (islower(c) ? 'a' : 'A'));
			cp++;
			continue;
		}
		break;
	}
	if (*cp == '.') {
		/*
		 * Internet format:
		 *	a.b.c.d
		 *	a.b.c	(with c treated as 16-bits)
		 *	a.b	(with b treated as 24 bits)
		 */
		if ((pp >= parts + 3) || (val > 0xff)) {
			return ((uint32_t)-1);
		}
		*pp++ = val, cp++;
		goto again;
	}
	/*
	 * Check for trailing characters.
	 */
	if (*cp && !isspace(*cp)) {
		return ((uint32_t)-1);
	}
	*pp++ = val;
	/*
	 * Concoct the address according to
	 * the number of parts specified.
	 */
	n = pp - parts;
	switch (n) {

	case 1:				/* a -- 32 bits */
		val = parts[0];
		break;

	case 2:				/* a.b -- 8.24 bits */
		if (parts[1] > 0xffffff)
			return ((uint32_t)-1);
		val = (parts[0] << 24) | (parts[1] & 0xffffff);
		break;

	case 3:				/* a.b.c -- 8.8.16 bits */
		if (parts[2] > 0xffff)
			return ((uint32_t)-1);
		val = (parts[0] << 24) | ((parts[1] & 0xff) << 16) |
		    (parts[2] & 0xffff);
		break;

	case 4:				/* a.b.c.d -- 8.8.8.8 bits */
		if (parts[3] > 0xff)
			return ((uint32_t)-1);
		val = (parts[0] << 24) | ((parts[1] & 0xff) << 16) |
		    ((parts[2] & 0xff) << 8) | (parts[3] & 0xff);
		break;

	default:
		return ((uint32_t)-1);
	}
	val = htonl(val);
	return (val);
}

void
hexdump(char *data, int datalen)
{
	char *p;
	ushort_t *p16 = (ushort_t *)data;
	char *p8 = data;
	int i, left, len;
	int chunk = 16;  /* 16 bytes per line */

	printf("\n");

	for (p = data; p < data + datalen; p += chunk) {
		printf("\t%4d: ", (int)(p - data));
		left = (data + datalen) - p;
		len = MIN(chunk, left);
		for (i = 0; i < (len / 2); i++)
			printf("%04x ", ntohs(*p16++) & 0xffff);
		if (len % 2) {
			printf("%02x   ", *((unsigned char *)p16));
		}
		for (i = 0; i < (chunk - left) / 2; i++)
			printf("     ");

		printf("   ");
		for (i = 0; i < len; i++, p8++)
			printf("%c", isprint(*p8) ? *p8 : '.');
		printf("\n");
	}

	printf("\n");
}
/*
 * 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.
 *
 * IPv4 implementation-specific definitions
 */

#ifndef _IPV4_H
#define	_IPV4_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#ifdef	__cplusplus
extern "C" {
#endif

#define	RT_UNUSED	1	/* Table entry is unused */
#define	RT_DEFAULT	2	/* Gateway is a default router */
#define	RT_HOST		4	/* Destination is a host */
#define	RT_NET		8	/* Destination is a network */
#define	RT_NG		10	/* Route is No Good */
#define	IPV4_ROUTE_TABLE_SIZE	(5)	/* Number of entries in the table */

#define	IPV4_ADD_ROUTE		0
#define	IPV4_DEL_ROUTE		1
#define	IPV4_BAD_ROUTE		2

extern char		*inet_ntoa(struct in_addr);
extern void		ipv4_setdefaultrouter(struct in_addr *);
extern int		ipv4_setpromiscuous(int);
extern void		ipv4_setipaddr(struct in_addr *);
extern void		ipv4_getipaddr(struct in_addr *);
extern void		ipv4_setnetmask(struct in_addr *);
extern void		ipv4_getnetmask(struct in_addr *);
extern int		ipv4_route(int, uint8_t, struct in_addr *,
			    struct in_addr *);
extern void		ipv4_setmaxttl(uint8_t);
extern in_addr_t	inet_addr(const char *);
extern void		hexdump(char *, int);
extern int		prom_cached_reply(int);
extern void		ipv4_getnetid(struct in_addr *);
#ifdef	__cplusplus
}
#endif

#endif /* _IPV4_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 2004 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 *
 * Internal IPv4 implementation-specific definitions
 */

#ifndef _IPV4_IMPL_H
#define	_IPV4_IMPL_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#ifdef	__cplusplus
extern "C" {
#endif

#define	FRAG_MAX	(40)	/* max number of IP fragments per datagram */
#define	FRAG_SUCCESS	(0)	/* datagram reassembled ok */
#define	FRAG_DUP	(1)	/* duplicate ip fragment */
#define	FRAG_NOSLOTS	(2)	/* no more ip fragment slots */
#define	FRAG_ATTEMPTS	1	/* Try twice to get all the fragments */

/*
 * IP fragmentation data structure
 */
struct ip_frag {
	int16_t		more;	/* Fragment bit (TRUE == MF, FALSE == No more */
	int16_t		offset;	/* Offset within the encapsulated datagram */
	mblk_t		*mp;	/* Fragment including IP header */
	uint16_t	ipid;	/* fragment ident */
	int16_t		iplen;	/* IP datagram's length */
	int16_t		iphlen;	/* Len of IP header */
	uint8_t		ipp;	/* IP protocol */
};

/*
 * true offset is in 8 octet units. The high order 3 bits of the IP header
 * offset field are therefore used for fragmentation flags. Shift these
 * bits off to produce the true offset. The high order flag bit is unused
 * (what would be considered the sign bit). Still, we cast the callers
 * value as an unsigned quantity to ensure it is treated as positive.
 */
#define	IPV4_OFFSET(a)	((uint16_t)(a) << 3)

#define	IPV4_VERSION	4
#define	IPH_HDR_LENGTH(iph)	(((struct ip *)(iph))->ip_hl << 2)

/* ECN code points for IPv4 TOS byte and IPv6 traffic class octet. */
#define	IPH_ECN_NECT	0x0	/* Not ECN-Capabable Transport */
#define	IPH_ECN_ECT1	0x1	/* ECN-Capable Transport, ECT(1) */
#define	IPH_ECN_ECT0	0x2	/* ECN-Capable Transport, ECT(0) */
#define	IPH_ECN_CE	0x3	/* ECN-Congestion Experienced (CE) */

#define	IPV4_VERSION			4
#define	IP_VERSION			IPV4_VERSION
#define	IP_SIMPLE_HDR_LENGTH_IN_WORDS	5
#define	IP_SIMPLE_HDR_LENGTH		20
#define	IP_MAX_HDR_LENGTH		60

#define	IP_MIN_MTU			(IP_MAX_HDR_LENGTH + 8)	/* 68 bytes */

/*
 * IP routing table. IP addresses are in network-order.
 */
struct routing {
	struct in_addr	dest;
	struct in_addr	gateway;
	uint8_t		flag;
};

extern void		ipv4_raw_socket(struct inetboot_socket *, uint8_t);
extern void		ipv4_socket_init(struct inetboot_socket *);
extern int		ipv4_header_len(struct inetgram *);
extern int		ipv4_input(int);
extern int		ipv4_output(int, struct inetgram *);
extern int		ipv4_tcp_output(int, mblk_t *);
extern struct in_addr	*ipv4_get_route(uint8_t, struct in_addr *,
			    struct in_addr *);

#ifdef	__cplusplus
}
#endif

#endif /* _IPV4_IMPL_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.
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#include <sys/types.h>
#include <socket_impl.h>
#include <socket_inet.h>
#include <sys/param.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <net/if_types.h>
#include <netinet/in_systm.h>
#include <netinet/in.h>
#include <netinet/if_ether.h>
#include <sys/promif.h>
#include <sys/prom_plat.h>
#include <sys/salib.h>

#include "mac.h"
#include "mac_impl.h"
#include "atm_inet.h"
#include "ethernet_inet.h"
#include "fddi_inet.h"
#include "token_inet.h"
#include "ibd_inet.h"

/*
 * MAC layer interface
 */
boolean_t		initialized;	/* Boolean state */
struct mac_type		mac_state;
int			arp_index;	/* current arp table index */
static struct arptable	atable[ARP_TABLE_SIZE];

struct ofw_net_types {
	char	*n_name;	/* OFW network media name */
	int	n_type;		/* IFT */
} ofw_types[] = {
	{ "atm",	IFT_ATM	},
	{ "ethernet",	IFT_ETHER },
	{ "fddi",	IFT_FDDI },
	{ "token-ring",	IFT_ISO88025 },
	{ "ipib",	IFT_IB }
};

/*
 * given the mac type, initialize the mac interface state.
 */
void
mac_init(char *bootdevicename)
{
	int		type = 0;
	static char	*mtu_name = "max-frame-size";
	static char	*chosen_net = "chosen-network-type";
	static char	*supported_net = "supported-network-types";
	static char	*netiftype = "network-interface-type";
	pnode_t		node;
	char		*wp, *media_type;
	int		len = 0, i;
	char		tmpbuf[MAXNAMELEN];
	char		devname[MAXNAMELEN];

	if (initialized)
		return;

	mac_state.mac_in_timeout = MAC_IN_TIMEOUT;

#ifdef	DEBUG
	printf("mac_init: device path: %s\n", bootdevicename);
#endif	/* DEBUG */

	if ((mac_state.mac_dev = prom_open(bootdevicename)) == 0) {
		(void) snprintf(tmpbuf, sizeof (tmpbuf),
		    "Cannot prom_open network device %s.", bootdevicename);
		prom_panic(tmpbuf);
	}

	(void) prom_devname_from_pathname(bootdevicename, devname);

#ifdef	DEBUG
	printf("mac_init: Network device name: %s\n", devname);
#endif	/* DEBUG */

	/*
	 * Ask the prom for our MTU and media type. "chosen-network-type"
	 * is of the form of "<network type>,<speed (Mbps)>,<connector type>,
	 * <duplex mode>: e.g.: "ethernet,100,rj45,full"
	 */
	node = prom_finddevice(devname);
	if (node != OBP_NONODE && node != OBP_BADNODE) {
		if (prom_getproplen(node, mtu_name) == sizeof (ihandle_t)) {
			(void) prom_getprop(node, mtu_name,
			    (caddr_t)&mac_state.mac_mtu);
		}
		bzero(tmpbuf, sizeof (tmpbuf));
		/*
		 * The following order of looking for properties is
		 * from FWARC 2002/345.
		 */
		if ((len = prom_getproplen(node, netiftype)) > 0 &&
		    len < sizeof (tmpbuf)) {
			(void) prom_getprop(node, netiftype, tmpbuf);
		} else if ((len = prom_getproplen(node, chosen_net)) > 0 &&
		    len < sizeof (tmpbuf)) {
			(void) prom_getprop(node, chosen_net, tmpbuf);
		} else if ((len = prom_getproplen(node, supported_net)) > 0 &&
		    len < sizeof (tmpbuf)) {
			(void) prom_getprop(node, supported_net, tmpbuf);
		}
		media_type = NULL;
		if (len > 0) {
			if ((wp = strstr(tmpbuf, ",")) != NULL)
				*wp = '\0';
			media_type = tmpbuf;
		}
		if (media_type != NULL) {
#ifdef	DEBUG
			printf("mac_init: Media type: %s\n", media_type);
#endif	/* DEBUG */
			for (i = 0; i < sizeof (ofw_types) /
			    sizeof (struct ofw_net_types); i++) {
				if (strcmp(ofw_types[i].n_name,
				    media_type) == 0) {
					type = ofw_types[i].n_type;
					break;
				}
			}
		}
	}

	switch (type) {
	case IFT_ATM:
		/*
		 * ATM is currently treated mostly like ethernet,
		 * with the exception that the MTU is most likely
		 * different.
		 */
		mac_state.mac_type = IFT_ATM;
		mac_state.mac_arp_timeout = ATM_ARP_TIMEOUT;
		mac_state.mac_in_timeout = ATM_IN_TIMEOUT;
		if (mac_state.mac_mtu == 0)
			mac_state.mac_mtu = ATMSIZE;
		mac_state.mac_addr_len = sizeof (ether_addr_t);
		mac_state.mac_addr_buf = bkmem_alloc(mac_state.mac_addr_len);
		if (mac_state.mac_addr_buf == NULL)
			prom_panic("mac_init: Cannot allocate memory.");
		if (prom_getmacaddr(mac_state.mac_dev,
		    (caddr_t)mac_state.mac_addr_buf) != 0)
			prom_panic("mac_init: Cannot obtain MAC address.");
		mac_state.mac_arp = ether_arp;
		mac_state.mac_rarp = ether_revarp;
		mac_state.mac_header_len = ether_header_len;
		mac_state.mac_input = ether_input;
		mac_state.mac_output = ether_output;
		break;

	case IFT_FDDI:
		/*
		 * FDDI is currently treated mostly like ethernet,
		 * with the exception that the MTU is most likely
		 * different.
		 */
		mac_state.mac_type = IFT_FDDI;
		mac_state.mac_arp_timeout = FDDI_ARP_TIMEOUT;
		mac_state.mac_in_timeout = FDDI_IN_TIMEOUT;
		if (mac_state.mac_mtu == 0)
			mac_state.mac_mtu = FDDISIZE;
		mac_state.mac_addr_len = sizeof (ether_addr_t);
		mac_state.mac_addr_buf = bkmem_alloc(mac_state.mac_addr_len);
		if (mac_state.mac_addr_buf == NULL)
			prom_panic("mac_init: Cannot allocate memory.");
		if (prom_getmacaddr(mac_state.mac_dev,
		    (caddr_t)mac_state.mac_addr_buf) != 0)
			prom_panic("mac_init: Cannot obtain MAC address.");
		mac_state.mac_arp = ether_arp;
		mac_state.mac_rarp = ether_revarp;
		mac_state.mac_header_len = ether_header_len;
		mac_state.mac_input = ether_input;
		mac_state.mac_output = ether_output;
		break;

	case IFT_ISO88025:
		/*
		 * Token ring is currently treated mostly like ethernet,
		 * with the exception that the MTU is most likely different.
		 */
		mac_state.mac_type = IFT_ISO88025;
		mac_state.mac_arp_timeout = TOKEN_ARP_TIMEOUT;
		mac_state.mac_in_timeout = TOKEN_IN_TIMEOUT;
		if (mac_state.mac_mtu == 0)
			mac_state.mac_mtu = TOKENSIZE;
		mac_state.mac_addr_len = sizeof (ether_addr_t);
		mac_state.mac_addr_buf = bkmem_alloc(mac_state.mac_addr_len);
		if (mac_state.mac_addr_buf == NULL)
			prom_panic("mac_init: Cannot allocate memory.");
		if (prom_getmacaddr(mac_state.mac_dev,
		    (caddr_t)mac_state.mac_addr_buf) != 0)
			prom_panic("mac_init: Cannot obtain MAC address.");
		mac_state.mac_arp = ether_arp;
		mac_state.mac_rarp = ether_revarp;
		mac_state.mac_header_len = ether_header_len;
		mac_state.mac_input = ether_input;
		mac_state.mac_output = ether_output;
		break;

	case IFT_IB:
		mac_state.mac_type = IFT_IB;
		ibd_init();
		break;

	case IFT_ETHER:
		/* FALLTHRU - default to ethernet */
	default:
		mac_state.mac_type = IFT_ETHER;
		mac_state.mac_mtu = ETHERSIZE;
		mac_state.mac_arp_timeout = ETHER_ARP_TIMEOUT;
		mac_state.mac_in_timeout = ETHER_IN_TIMEOUT;
		if (mac_state.mac_mtu == 0)
			mac_state.mac_mtu = ETHERSIZE;
		mac_state.mac_addr_len = sizeof (ether_addr_t);
		mac_state.mac_addr_buf = bkmem_alloc(mac_state.mac_addr_len);
		if (mac_state.mac_addr_buf == NULL)
			prom_panic("mac_init: Cannot allocate memory.");
		if (prom_getmacaddr(mac_state.mac_dev,
		    (caddr_t)mac_state.mac_addr_buf) != 0)
			prom_panic("mac_init: Cannot obtain MAC address.");
		mac_state.mac_arp = ether_arp;
		mac_state.mac_rarp = ether_revarp;
		mac_state.mac_header_len = ether_header_len;
		mac_state.mac_input = ether_input;
		mac_state.mac_output = ether_output;
		break;
	}

	mac_state.mac_buf = bkmem_alloc(mac_state.mac_mtu);
	if (mac_state.mac_buf == NULL)
		prom_panic("mac_init: Cannot allocate netbuf memory.");
	else
		initialized = B_TRUE;
}

void
mac_fini()
{
	if (mac_state.mac_addr_buf != NULL) {
		bkmem_free((caddr_t)mac_state.mac_addr_buf,
		    mac_state.mac_addr_len);
		mac_state.mac_addr_buf = NULL;
	}
	if (mac_state.mac_buf != NULL) {
		bkmem_free(mac_state.mac_buf, mac_state.mac_mtu);
		mac_state.mac_buf = NULL;
	}
	(void) prom_close(mac_state.mac_dev);
	initialized = B_FALSE;
}

/* MAC layer specific socket initialization */
void
mac_socket_init(struct inetboot_socket *isp)
{
	isp->input[MEDIA_LVL] = mac_state.mac_input;
	isp->output[MEDIA_LVL] = mac_state.mac_output;
	isp->close[MEDIA_LVL] = NULL;
	isp->headerlen[MEDIA_LVL] = mac_state.mac_header_len;
	isp->in_timeout = mac_state.mac_in_timeout;
}

/*
 * Add an entry to the ARP table. All values in table are network order.
 * No checking is done to determine whether there's duplicates.
 */
void
mac_set_arp(struct in_addr *ip, void *hp, int hl)
{
	atable[arp_index].ia.s_addr = ip->s_addr;
	bcopy(hp, (char *)atable[arp_index].ha, hl);
	atable[arp_index].hl = hl;
	arp_index++;
	if (arp_index >= ARP_TABLE_SIZE)
		arp_index = 0;
}

/*
 * Retrieve an entry from the ARP table using network-order IP address as
 * search criteria. HW address buffer is filled in up to hl in len. (make
 * sure the buffer is big enough given the mac type)
 *
 * Returns TRUE if successful, FALSE otherwise. Will wait timeout milliseconds
 * for a response.
 */
int
mac_get_arp(struct in_addr *ip, void *hp, int hl, uint32_t timeout)
{
	int i, result;

	for (i = 0; i < ARP_TABLE_SIZE; i++) {
		if (ip->s_addr == atable[i].ia.s_addr) {
			bcopy((char *)atable[i].ha, hp, hl);
			return (TRUE);
		}
	}

	/* Not found. ARP for it. */
	bzero(hp, hl);
	result = mac_state.mac_arp(ip, hp, timeout);

	if (result) {
		/* Cool - add it to the arp table */
		mac_set_arp(ip, hp, hl);
	}
	return (result);
}

int
mac_get_mtu(void)
{
	if (!initialized)
		return (-1);
	else
		return (mac_state.mac_mtu);
}

int
mac_get_dev(void)
{
	if (!initialized)
		return (-1);
	else
		return (mac_state.mac_dev);
}

uint8_t *
mac_get_addr_buf(void)
{
	if (!initialized)
		return (NULL);
	else
		return (mac_state.mac_addr_buf);
}

int
mac_get_addr_len(void)
{
	if (!initialized)
		return (-1);
	else
		return (mac_state.mac_addr_len);
}

int
mac_get_type(void)
{
	if (!initialized)
		return (-1);
	else
		return (mac_state.mac_type);
}

void
mac_set_arp_timeout(unsigned int timeout)
{
	mac_state.mac_arp_timeout =
	    timeout;
}

int
mac_get_arp_timeout(void)
{
	if (!initialized)
		return (-1);
	else
		return (mac_state.mac_arp_timeout);
}

int
mac_get_hdr_len(void)
{
	if (!initialized)
		return (-1);
	else
		return (mac_state.mac_header_len(NULL));
}

int
mac_call_arp(struct in_addr *addr, void *buf, uint32_t timeout)
{
	return (mac_state.mac_arp(addr, buf, timeout));
}

void
mac_call_rarp(void)
{
	mac_state.mac_rarp();
}

/*
 * Map a IFT_ type to an RFC 1700 arp hwtype.
 */
uint8_t
mac_arp_type(uint8_t ift_type)
{
	uint8_t arptype;

	switch (ift_type) {
	case IFT_ISO88025:
		arptype = 4;	/* token ring */
		break;
	case IFT_ATM:
		arptype = 16;	/* ATM */
		break;
	case IFT_FDDI:
		arptype = 18;	/* Fiber Channel */
		break;
	case IFT_IB:
		arptype = 32;	/* Infiniband */
		break;
	case IFT_ETHER:
		/* FALLTHRU */
	default:
		arptype = 1;	/* default to ethernet */
		break;
	}
	return (arptype);
}
/*
 * 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 2006 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 *
 * mac.h contains MAC layer independent definttions
 */

#ifndef _MAC_H
#define	_MAC_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#ifdef	__cplusplus
extern "C" {
#endif

extern int 	mac_call_arp(struct in_addr *, void *, uint32_t);
extern void	mac_call_rarp(void);
extern void	mac_init(char *);	/* initialize MAC layer */
extern void	mac_fini(void);		/* tear down MAC layer */
extern uint8_t	*mac_get_addr_buf(void);
extern int	mac_get_addr_len(void);
extern int	mac_get_arp_timeout(void);
extern int	mac_get_hdr_len(void);
extern int	mac_get_mtu(void);
extern int	mac_get_type(void);
extern int	mac_get_arp(struct in_addr *, void *, int, uint32_t);
extern int	mac_get_dev(void);
extern uint8_t	mac_arp_type(uint8_t);
extern void	mac_set_arp_timeout(unsigned int);
extern struct mac_type mac_state;	/* in mac.c */

#ifdef	__cplusplus
}
#endif

#endif /* _MAC_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 2002-2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 *
 * mac_impl.h contains internal MAC layer independent definttions
 */

#ifndef _MAC_IMPL_H
#define	_MAC_IMPL_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#ifdef	__cplusplus
extern "C" {
#endif

extern boolean_t	initialized;	/* TRUE if network device initialized */
extern int	arp_index;	/* current arp table index */

struct mac_type {
	int		mac_type;	/* if_types.h */
	int		mac_dev;
	int		mac_mtu;
	caddr_t		mac_buf;	/* MTU sized buffer */
	uint8_t		*mac_addr_buf;
	uint32_t	mac_arp_timeout;
	uint32_t	mac_in_timeout;
	uint32_t	mac_in_timeo_incr;
	int		mac_addr_len;
	int		(*mac_arp)(struct in_addr *, void *, uint32_t);
	void		(*mac_rarp)(void);
	int		(*mac_header_len)(struct inetgram *);
	int		(*mac_input)(int);
	int		(*mac_output)(int, struct inetgram *);
};

#define	ARP_TABLE_SIZE		(3)	/* size of ARP table */
#define	HW_ADDR_SIZE		(128)	/* max size of hardware address */
#define	MAC_IN_TIMEOUT		(10)	/* collect IP grams for X mseconds. */
#define	MAC_IN_TIMEO_MULT	(8)	/* Multiplier to arrive at maximum */

/* format of an arp table entry */
struct	arptable {
	struct in_addr	ia;
	uchar_t		ha[HW_ADDR_SIZE];
	int		hl;
};

extern void	mac_set_arp(struct in_addr *, void *, int);
extern void	mac_socket_init(struct inetboot_socket *);

#ifdef	__cplusplus
}
#endif

#endif /* _MAC_IMPL_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) 1990-1999, Sun Microsystems, Inc.
 * All rights reserved.
 *
 * Token ring implementation-specific definitions
 */

#ifndef _TOKEN_INET_H
#define	_TOKEN_INET_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#ifdef	__cplusplus
extern "C" {
#endif

#define	TOKENSIZE		(17800)	/* Default Token Ring MTU size */
#define	TOKEN_ARP_TIMEOUT	(300000)	/* in milliseconds */
#define	TOKEN_IN_TIMEOUT	(8)	/* millisecond wait for IP frames */

#ifdef	__cplusplus
}
#endif

#endif /* _TOKEN_INET_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 1991-2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 *
 * udp.c, Code implementing the UDP internet protocol.
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#include <sys/types.h>
#include <socket_impl.h>
#include <socket_inet.h>
#include <sys/salib.h>
#include <sys/socket.h>
#include <netinet/in_systm.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/udp.h>

#include "udp_inet.h"
#include "ipv4.h"
#include "ipv4_impl.h"
#include "mac.h"
#include "mac_impl.h"
#include "v4_sum_impl.h"
#include <sys/bootdebug.h>

/* Checksum all architectures */
static int udp_cksum_flag = TRUE;	/* checksum on if set */

/*
 * Initialize the udp-specific parts of a socket.
 */
void
udp_socket_init(struct inetboot_socket *isp)
{
	isp->type = INETBOOT_DGRAM;
	isp->proto = IPPROTO_UDP;
	isp->input[TRANSPORT_LVL] = udp_input;
	isp->output[TRANSPORT_LVL] = udp_output;
	isp->close[TRANSPORT_LVL] = NULL;
	isp->headerlen[TRANSPORT_LVL] = udp_header_len;
	isp->ports = udp_ports;
}

/*
 * Return the size of an UDP header
 */
/* ARGSUSED */
int
udp_header_len(struct inetgram *igm)
{
	return (sizeof (struct udphdr));
}

/*
 * Return the requested port number in network order.
 */
in_port_t
udp_ports(uint16_t *udphp, enum Ports request)
{
	if (request == SOURCE)
		return (((struct udphdr *)udphp)->uh_sport);
	return (((struct udphdr *)udphp)->uh_dport);
}

/*
 * Process the IPv4 datagram that IPv4 has given us. We:
 *
 *	1) Checksum the datagram if checksum is turned on.
 *	2) Strip the udp header from the inetgram.
 *	3) Return the number of TRANSPORT frames for success, -1 if a
 *		failure occurred.
 *
 * Arguments: index: index into the open socket table, ip is the inetgram
 * we got from IPv4, which will contain the udp header and all the data.
 */
int
udp_input(int index)
{
	int frames = 0, header_len;
	struct inetgram	*igp, *ugp = NULL;
	struct udphdr	*udphp;
	mblk_t *mp;

#ifdef DEBUG
	printf("udp_input(%d) ###############################\n", index);
#endif
	while ((igp = sockets[index].inq) != NULL) {
		if (igp->igm_level != TRANSPORT_LVL) {
#ifdef	DEBUG
			printf("udp_input(%d): level %d datagram discarded.\n",
			    index, igp->igm_level);
#endif	/* DEBUG */
			del_gram(&sockets[index].inq, igp, TRUE);
			continue;
		}
		mp = igp->igm_mp;
		udphp = (struct udphdr *)(mp->b_rptr +
		    IPH_HDR_LENGTH(mp->b_rptr));
		header_len = (sockets[index].headerlen[TRANSPORT_LVL])(NULL);
		mp->b_rptr = ((unsigned char *)udphp) + header_len;
		mp->b_wptr = ((unsigned char *)udphp) + ntohs(udphp->uh_ulen);

		/* generate checksum */
		if (udp_cksum_flag && udphp->uh_sum != 0) {
			if (udp_chksum(udphp, &igp->igm_saddr.sin_addr,
			    &igp->igm_target, sockets[index].proto) != 0) {
				dprintf("udp_input(%d): bad udp chksum "
				    "from %s.\n", index,
				    inet_ntoa(igp->igm_saddr.sin_addr));
				del_gram(&sockets[index].inq, igp, TRUE);
				continue;
			}
		}

		/* validate port number */
		if (sockets[index].bind.sin_port != udphp->uh_dport) {
			dprintf("udp_input(%d): Unexpected port number: "
			    "%d != %d from %s.\n", index,
			    ntohs(udphp->uh_dport), ntohs(
			    sockets[index].bind.sin_port),
			    inet_ntoa(igp->igm_saddr.sin_addr));
			del_gram(&sockets[index].inq, igp, TRUE);
			continue;
		}

		igp->igm_level = APP_LVL;
		del_gram(&sockets[index].inq, igp, FALSE);
		add_grams(&ugp, igp);
		frames++;
	}
	add_grams(&sockets[index].inq, ugp);

	return (frames);
}

/*
 * Create a UDP datagram given the data and sockaddr_in we got from sendto().
 * We will calculate the checksum if checksumming is turned on, and fill in
 * appropriate length and port fields. We convert the inetgram from a
 * block of data into a udp datagram... Returns the number of bytes contained
 * in the udp datagram (including header).
 *
 * Arguments: index: index into the open socket table, ogp is the inetgram
 * we got from sendto(), which will contain just the data and sockaddr_in.
 */
int
udp_output(int index, struct inetgram *ogp)
{
	struct udphdr	*udphp;
	mblk_t		*mp;

#ifdef	DEBUG
	printf("udp_output(%d): 0x%x, %d\n", index, ogp->igm_mp,
	    ogp->igm_mp->b_wptr - ogp->igm_mp->b_rptr);
#endif	/* DEBUG */

	mp = ogp->igm_mp;
	mp->b_rptr -= sizeof (struct udphdr);
	udphp = (struct udphdr *)(mp->b_rptr);

	udphp->uh_dport = ogp->igm_saddr.sin_port;
	if (sockets[index].bound)
		udphp->uh_sport = sockets[index].bind.sin_port;
	else
		udphp->uh_sport = ogp->igm_saddr.sin_port;
	udphp->uh_ulen = htons(mp->b_wptr - mp->b_rptr);
	udphp->uh_sum = 0;

	if (udp_cksum_flag) {
		udphp->uh_sum = udp_chksum(udphp, &sockets[index].bind.sin_addr,
		    &ogp->igm_saddr.sin_addr, sockets[index].proto);
	}

	ogp->igm_level = NETWORK_LVL;

	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 1990-1999, 2001-2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 *
 * UDP implementation-specific definitions
 */

#ifndef _UDP_INET_H
#define	_UDP_INET_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#ifdef	__cplusplus
extern "C" {
#endif

extern int		udp_header_len(struct inetgram *);
extern in_port_t	udp_ports(uint16_t *, enum Ports);
extern int		udp_input(int);
extern int		udp_output(int, struct inetgram *);
extern void		udp_socket_init(struct inetboot_socket *);

#ifdef	__cplusplus
}
#endif

#endif /* _UDP_INET_H */
#!/bin/sh
#
# 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.
#
# ident	"%Z%%M%	%I%	%E% SMI"

echo_file usr/src/lib/Makefile.lib
echo_file usr/src/stand/lib/Makefile.com
echo_file usr/src/stand/lib/Makefile.sparc
echo_file usr/src/stand/lib/Makefile.targ
echo_file usr/src/psm/Makefile.psm.64
find_files "s.*.h" usr/src/psm/stand/sys
find_files "s.*.h" usr/src/stand
find_files "s.*.h" usr/src/uts
#
# 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.
#

LIBRARY		= libsa.a
LOCOBJS		= assert.o ctype.o errno.o libintl.o malloc.o memlist.o \
		  standalloc.o stdio.o stdlib.o strdup.o strings.o \
		  time.o unistd.o
CMNOBJS		= cache.o diskread.o fsswitch.o promfs.o

sparc_CMNUTILOBJS = memchr.o memmove.o
CMNUTILOBJS	= $($(MACH)_CMNUTILOBJS) \
		  bsearch.o memcmp.o memcpy.o memset.o qsort.o \
		  string.o strtol.o strtoul.o multi3.o

i386_MACHOBJS	= get.o map_prog.o
sparc_MACHOBJS	= prom_misc.o
MACHOBJS	= $($(MACH)_MACHOBJS)

i386_ASMOBJS	= _setjmp.o samuldiv64.o
sparc_ASMOBJS	= _setjmp.o
ASMOBJS		= $($(MACH)_ASMOBJS)

OBJECTS		= $(LOCOBJS) $(CMNOBJS) $(CMNUTILOBJS) $(MACHOBJS) $(ASMOBJS)

include ../Makefile.com

CMNDIR		= ../fs/common
CMNUTILDIR	= $(TOPDIR)/common/util
SRCS		= $(LOCOBJS:%.o=$(SRCDIR)/%.c) $(CMNOBJS:%.o=$(CMNDIR)/%.c) \
		  $(CMNUTILOBJS:%.o=$(CMNUTILDIR)/%.c) \
		  $($(MACH)_ASMOBJS:%.o=$(MACH)/%.s) \
		  $($(MACH)_OBJS:%.o=$(MACH)/%.c)

LDLIBS += -lsock
CPPFLAGS += $(SOCKCPPFLAGS)

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

objs/%.o: $(MACH)/%.s
	  $(COMPILE.s) -o $@ $<
	  $(POST_PROCESS_O)

objs/%.o: $(MACH)/%.c
	  $(COMPILE.c) -o $@ $<
	  $(POST_PROCESS_O)

objs/%.o: $(CMNUTILDIR)/%.c
	  $(COMPILE.c) -o $@ $<
	  $(POST_PROCESS_O)

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 2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef _SA_ARPA_INET_H
#define	_SA_ARPA_INET_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

/*
 * Exported interfaces for standalone's subset of libsocket's <arpa/inet.h>.
 * All standalone code *must* use this header rather than libsockets's.
 *
 * Since all the sources that #include this file do it spuriously, we provide
 * no definitions.  Note that we do this rather than removing the errant
 * #includes because the code they live in (openssl) is third-party and we're
 * still receiving code drops for it.
 */

#endif /* _SA_ARPA_INET_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 2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#include <assert.h>
#include <stdio.h>
#include <sys/promif.h>

void
__assert(const char *assertion, const char *file, int line)
{
	char panicmsg[1024];

	(void) snprintf(panicmsg, sizeof (panicmsg), "assertion failed: "
	    "%s, file: %s, line: %d", assertion, file, line);
	prom_panic(panicmsg);
}
/*
 * 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 2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef _SA_ASSERT_H
#define	_SA_ASSERT_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

/*
 * Exported interfaces for standalone's subset of libc's <assert.h>.
 * All standalone code *must* use this header rather than libc's.
 */

#ifdef __cplusplus
extern "C" {
#endif

extern void __assert(const char *, const char *, int);

#ifdef __cplusplus
}
#endif

#endif /* _SA_ASSERT_H */

/*
 * Note that the ANSI C Standard requires all headers to be idempotent except
 * <assert.h> which is explicitly required not to be idempotent (section 4.1.2).
 * Therefore, it is by intent that the header guards (#ifndef _SA_ASSERT_H) do
 * not span this entire file.
 */

#undef  assert

#ifdef  NDEBUG
#define	assert(EX) ((void)0)
#else
#define	assert(EX) (void)((EX) || (__assert(#EX, __FILE__, __LINE__), 0))
#endif  /* NDEBUG */
/*
 * 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 1992-2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#include <ctype.h>

int
tolower(int c)
{
	/* standalone only supports the C locale */
	if ((c >= 'A') && (c <= 'Z'))
		c += 'a' - 'A';
	return (c);
}

int
toupper(int c)
{
	/* standalone only supports the C locale */
	if ((c >= 'a') && (c <= 'z'))
		c -= 'a' - 'A';
	return (c);
}

unsigned char __ctype[129] =
{
	0, /* EOF */
	_C,	_C,	_C,	_C,	_C,	_C,	_C,	_C,
	_C,	_S|_C,	_S|_C,	_S|_C,	_S|_C,	_S|_C,	_C,	_C,
	_C,	_C,	_C,	_C,	_C,	_C,	_C,	_C,
	_C,	_C,	_C,	_C,	_C,	_C,	_C,	_C,
	_S|_B,	_P,	_P,	_P,	_P,	_P,	_P,	_P,
	_P,	_P,	_P,	_P,	_P,	_P,	_P,	_P,
	_N|_X,	_N|_X,	_N|_X,	_N|_X,	_N|_X,	_N|_X,	_N|_X,	_N|_X,
	_N|_X,	_N|_X,	_P,	_P,	_P,	_P,	_P,	_P,
	_P,	_U|_X,	_U|_X,	_U|_X,	_U|_X,	_U|_X,	_U|_X,	_U,
	_U,	_U,	_U,	_U,	_U,	_U,	_U,	_U,
	_U,	_U,	_U,	_U,	_U,	_U,	_U,	_U,
	_U,	_U,	_U,	_P,	_P,	_P,	_P,	_P,
	_P,	_L|_X,	_L|_X,	_L|_X,	_L|_X,	_L|_X,	_L|_X,	_L,
	_L,	_L,	_L,	_L,	_L,	_L,	_L,	_L,
	_L,	_L,	_L,	_L,	_L,	_L,	_L,	_L,
	_L,	_L,	_L,	_P,	_P,	_P,	_P,	_C,
};
/*
 * 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 2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*	Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T	*/
/*	  All Rights Reserved	*/

#ifndef _SA_CTYPE_H
#define	_SA_CTYPE_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

/*
 * Exported interfaces for standalone's subset of libc's <ctype.h>.
 * All standalone code *must* use this header rather than libc's.
 */

#ifdef __cplusplus
extern "C" {
#endif

#define	_U	0x00000001	/* Upper case */
#define	_L	0x00000002	/* Lower case */
#define	_N	0x00000004	/* Numeral (digit) */
#define	_S	0x00000008	/* Spacing character */
#define	_P	0x00000010	/* Punctuation */
#define	_C	0x00000020	/* Control character */
#define	_B	0x00000040	/* Blank */
#define	_X	0x00000080	/* heXadecimal digit */

#define	isalpha(c)	((__ctype + 1)[c] & (_U | _L))
#define	isupper(c)	((__ctype + 1)[c] & _U)
#define	islower(c)	((__ctype + 1)[c] & _L)
#define	isdigit(c)	((__ctype + 1)[c] & _N)
#define	isxdigit(c)	((__ctype + 1)[c] & _X)
#define	isalnum(c)	((__ctype + 1)[c] & (_U | _L | _N))
#define	isspace(c)	((__ctype + 1)[c] & _S)
#define	ispunct(c)	((__ctype + 1)[c] & _P)
#define	isprint(c)	((__ctype + 1)[c] & (_P | _U | _L | _N | _B))
#define	isgraph(c)	((__ctype + 1)[c] & (_P | _U | _L | _N))
#define	iscntrl(c)	((__ctype + 1)[c] & _C)
#define	isascii(c)	(!((c) & ~0177))

extern unsigned char __ctype[];

/*
 * Some header files define their own macros for tolower/toupper which mangle
 * our prototypes -- thus only provide ours if no macros have been defined.
 */
#ifndef tolower
extern int tolower(int);
#endif
#ifndef toupper
extern int toupper(int);
#endif

#ifdef __cplusplus
}
#endif

#endif /* _SA_CTYPE_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 2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef _SA_DIRENT_H
#define	_SA_DIRENT_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

/*
 * Exported interfaces for standalone's subset of libc's <dirent.h>.
 * All standalone code *must* use this header rather than libc's.
 */

#include <sys/types.h>
#include <sys/dirent.h>

#ifdef __cplusplus
extern "C" {
#endif

typedef struct DIR DIR;

extern DIR *opendir(const char *);
extern struct dirent *readdir(DIR *);
extern int closedir(DIR *);

#ifdef __cplusplus
}
#endif

#endif /* _SA_DIRENT_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 2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"

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

int		errno;
static char	errmsgbuf[1024];

/*
 * Trivial standalone error-to-string routine; someday it might be worth
 * making this print actual strings like libc (or, better yet, share libc's
 * implementation).
 */
char *
strerror(int errnum)
{
	(void) snprintf(errmsgbuf, sizeof (errmsgbuf), "ERRNO: %d", errnum);
	return (errmsgbuf);
}
/*
 * 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 2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef _SA_ERRNO_H
#define	_SA_ERRNO_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

/*
 * Exported interfaces for standalone's subset of libc's <errno.h>.
 * All standalone code *must* use this header rather than libc's.
 */

#include <sys/errno.h>

#ifdef __cplusplus
extern "C" {
#endif

extern int errno;

#ifdef __cplusplus
}
#endif

#endif /* _SA_ERRNO_H */
#!/bin/sh
#
# 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 2003 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# ident	"%Z%%M%	%I%	%E% SMI"

find_files "s.*" usr/src/common/util
find_files "s.*" usr/src/stand/lib/fs/common
/*
 * 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 2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#include <libintl.h>

/*
 * Get a localized string. Since localization is not
 * supported in the sa environment just return the
 * pointer to the msgid.
 */
/*ARGSUSED*/
char *
dgettext(const char *domainname, const char *msgid)
{
	return ((char *)msgid);
}
/*
 * 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 2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef _SA_LIBINTL_H
#define	_SA_LIBINTL_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

/*
 * Exported interfaces for standalone's subset of libintl's <libintl.h>.
 * All standalone code *must* use this header rather than libintl's.
 */

#ifdef __cplusplus
extern "C" {
#endif

#define	TEXT_DOMAIN	"None"

extern char	*dgettext(const char *, const char *);

#ifdef __cplusplus
}
#endif

#endif /* _SA_LIBINTL_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 2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef _SA_LIMITS_H
#define	_SA_LIMITS_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

/*
 * Exported interfaces for standalone's subset of libc's <limits.h>.
 * All standalone code *must* use this header rather than libc's.
 *
 * Since all the sources that #include this file do it spuriously, we provide
 * no definitions.  Note that we do this rather than removing the errant
 * #includes because the code they live in (openssl) is third-party and we're
 * still receiving code drops for it.
 */

#endif /* _SA_LIMITS_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 2002-2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#include <sys/salib.h>

/*
 * For documentation on these functions, see malloc(3C).
 */

void *
malloc(size_t size)
{
	size_t *iaddr;

	iaddr = (size_t *)bkmem_alloc(size + sizeof (size_t));
	if (iaddr == NULL) {
		errno = ENOMEM;
		return (NULL);
	}

	iaddr[0] = size;
	return (&iaddr[1]);
}

void *
calloc(size_t number, size_t size)
{
	void *addr;

	addr = malloc(number * size);
	if (addr == NULL)
		return (NULL);

	return (memset(addr, 0, number * size));
}

void *
realloc(void *oldaddr, size_t size)
{
	void *addr;
	size_t oldsize;

	addr = malloc(size);
	if (oldaddr != NULL) {
		oldsize = ((size_t *)oldaddr)[-1];
		if (addr != NULL) {
			bcopy(oldaddr, addr, (oldsize > size ? oldsize : size));
			free(oldaddr);
		}
	}

	return (addr);
}

void
free(void *addr)
{
	size_t *lenloc;

	if (addr == NULL)
		return;
	lenloc = (size_t *)addr - 1;
	bkmem_free((caddr_t)lenloc, *lenloc + sizeof (size_t));
}
/*
 * 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 2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef _SA_MATH_H
#define	_SA_MATH_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

/*
 * Exported interfaces for standalone's subset of libm's <math.h>.
 * All standalone code *must* use this header rather than libm's.
 *
 * Since all the sources that #include this file do it spuriously, we provide
 * no definitions.  Note that we do this rather than removing the errant
 * #includes because the code they live in (openssl) is third-party and we're
 * still receiving code drops for it.
 */

#endif /* _SA_MATH_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 2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef _SA_MD5_H
#define	_SA_MD5_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

/*
 * Exported interfaces for standalone's subset of libmd5's <md5.h>.
 * All standalone code *must* use this header rather than libmd5's.
 */

#include <sys/md5.h>

#endif /* _SA_MD5_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 2010 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#include <sys/types.h>
#include <sys/param.h>
#include <sys/sysmacros.h>
#include <sys/machparam.h>
#include <sys/promif.h>
#include <sys/bootconf.h>
#include <sys/salib.h>

caddr_t memlistpage;

/* Always pts to the next free link in the headtable */
/* i.e. it is always memlistpage+tableoffset */
caddr_t tablep = NULL;
static int table_freespace;

/*
 *	Function prototypes
 */
extern void reset_alloc(void);

void
print_memlist(struct memlist *av)
{
	struct memlist *p = av;

	while (p != NULL) {
		printf("addr = 0x%x:0x%x, size = 0x%x:0x%x\n",
		    (uint_t)(p->ml_address >> 32), (uint_t)p->ml_address,
		    (uint_t)(p->ml_size >> 32), (uint_t)p->ml_size);
		p = p->ml_next;
	}

}

/* allocate room for n bytes, return 8-byte aligned address */
void *
getlink(uint_t n)
{
	void *p;
	extern int pagesize;

	if (memlistpage == NULL)
		reset_alloc();

	if (tablep == NULL) {
		/*
		 * Took the following 2 lines out of above test for
		 * memlistpage == null so we can initialize table_freespace
		 */
		table_freespace = pagesize - sizeof (struct bsys_mem);
		tablep = memlistpage + sizeof (struct bsys_mem);
		tablep = (caddr_t)roundup((uintptr_t)tablep, 8);
	}

	if (n == 0)
		return (NULL);

	n = roundup(n, 8);
	p = tablep;

	table_freespace -= n;
	tablep += n;
	if (table_freespace <= 0) {
		char buf[80];

		(void) sprintf(buf,
		    "Boot getlink(): no memlist space (need %d)\n", n);
		prom_panic(buf);
	}

	return (p);
}


/*
 * This is the number of memlist structures allocated in one shot. kept
 * to small number to reduce wastage of memory, it should not be too small
 * to slow down boot.
 */
#define		ALLOC_SZ	5
static struct memlist *free_memlist_ptr = NULL;

/*
 * Free memory lists are maintained as simple single linked lists.
 * get_memlist_struct returns a memlist structure without initializing
 * any of the fields.  It is caller's responsibility to do that.
 */

struct memlist *
get_memlist_struct(void)
{
	struct memlist *ptr;
	int i;

	if (free_memlist_ptr == NULL) {
		ptr = free_memlist_ptr = getlink(ALLOC_SZ *
		    sizeof (struct memlist));
		bzero(free_memlist_ptr, (ALLOC_SZ * sizeof (struct memlist)));
		for (i = 0; i < ALLOC_SZ; i++)
			ptr[i].ml_next = &ptr[i+1];
		ptr[i-1].ml_next = NULL;
	}
	ptr = free_memlist_ptr;
	free_memlist_ptr = ptr->ml_next;
	return (ptr);
}

/*
 * Return memlist structure to free list.
 */
void
add_to_freelist(struct memlist *ptr)
{
	struct memlist *tmp;

	if (free_memlist_ptr == NULL) {
		free_memlist_ptr = ptr;
	} else {
		for (tmp = free_memlist_ptr; tmp->ml_next; tmp = tmp->ml_next)
			;
		tmp->ml_next = ptr;
	}
}
/*
 * 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 2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/* Copyright (c) 1983, 1984, 1985, 1986, 1987, 1988, 1989 AT&T */
/* All Rights Reserved */

/*
 * Portions of this source code were derived from Berkeley 4.3 BSD
 * under license from the Regents of the University of California.
 */

#ifndef _SA_NETDB_H
#define	_SA_NETDB_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"


/*
 * Exported interfaces for standalone's subset of libnsl's <netdb.h>.
 * All standalone code *must* use this header rather than libnsl's.
 */

#ifdef __cplusplus
extern "C" {
#endif

#define	MAXHOSTNAMELEN	256

#define	HOST_NOT_FOUND	1 /* Authoritive Answer Host not found */
#define	TRY_AGAIN	2 /* Non-Authoritive Host not found, or SERVERFAIL */
#define	NO_RECOVERY	3 /* Non recoverable errors, FORMERR, REFUSED, NOTIMP */
#define	NO_DATA		4 /* Valid name, no data record of requested type */

struct	hostent {
	char	*h_name;	/* official name of host */
	char	**h_aliases;	/* alias list */
	int	h_addrtype;	/* host address type */
	int	h_length;	/* length of address */
	char	**h_addr_list;	/* list of addresses from name server */
#define	h_addr	h_addr_list[0]	/* address, for backward compatiblity */
};

extern int h_errno;

extern struct hostent *gethostbyname(const char *);

#ifdef __cplusplus
}
#endif

#endif /* _SA_NETDB_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.
 */

#include <sys/types.h>
#include <sys/saio.h>
#include <sys/sysmacros.h>
#include <sys/promif.h>
#include <sys/bootconf.h>
#include <sys/salib.h>

#ifdef DEBUG
static int	resalloc_debug = 1;
#else /* DEBUG */
static int	resalloc_debug = 0;
#endif /* DEBUG */
#define	dprintf	if (resalloc_debug) printf

extern	caddr_t		resalloc(enum RESOURCES type,
				size_t bytes, caddr_t virthint, int align);
extern	void		resfree(enum RESOURCES type,
				caddr_t virtaddr, size_t bytes);

extern int	pagesize;

/*
 *  This routine should be called get_a_page().
 *  It allocates from the appropriate entity one or
 *  more pages and maps them in.
 */

caddr_t
kern_resalloc(caddr_t virthint, size_t size, int align)
{
	if (virthint != 0)
		return (resalloc(RES_CHILDVIRT, size, virthint, align));
	else {
		return (resalloc(RES_BOOTSCRATCH, size, NULL, NULL));
	}
}

/*
 * This is called only on sparcv9 for freeing scratch memory.
 * The standalone allocator cannot free other types of memory.
 */
void
kern_resfree(caddr_t virtaddr, size_t size)
{
	resfree(RES_BOOTSCRATCH, virtaddr, size);
}

int
get_progmemory(caddr_t vaddr, size_t size, int align)
{
	uintptr_t n;

	/*
	 * if the vaddr given is not a mult of PAGESIZE,
	 * then we rounddown to a page, but keep the same
	 * ending addr.
	 */
	n = (uintptr_t)vaddr & (pagesize - 1);
	if (n) {
		vaddr -= n;
		size += n;
	}

	dprintf("get_progmemory: requesting %lx bytes at %p\n", size,
	    (void *)vaddr);
	if (resalloc(RES_CHILDVIRT, size, vaddr, align) != vaddr)
		return (-1);
	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 2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef _SA_STDARG_H
#define	_SA_STDARG_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

/*
 * Exported interfaces for standalone's subset of libc's <stdarg.h>.
 * All standalone code *must* use this header rather than libc's.
 */

#include <sys/varargs.h>

#endif /* _SA_STDARG_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.
 */

#ifndef _SA_STDDEF_H
#define	_SA_STDDEF_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

/*
 * Exported interfaces for standalone's subset of libc's <stddef.h>.
 * All standalone code *must* use this header rather than libc's.
 */

#ifdef	__cplusplus
extern "C" {
#endif

#ifndef	NULL
#define	NULL    0
#endif

#ifndef offsetof
#define	offsetof(s, m)  (size_t)(&(((s *)0)->m))
#endif

#ifdef	__cplusplus
}
#endif

#endif /* _SA_STDDEF_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 2002-2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 *
 * "buffered" i/o functions for the standalone environment. (ugh).
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#include <sys/types.h>
#include <sys/promif.h>
#include <sys/varargs.h>
#include <sys/bootvfs.h>
#include <sys/salib.h>

enum {
	F_OPEN		= 0x01,
	F_ERROR		= 0x02,
	F_SEEKABLE	= 0x04
};

FILE	__iob[_NFILE] = {
	{ F_OPEN, 0, 0, 0, "stdin"	},
	{ F_OPEN, 1, 0, 0, "stdout"	},
	{ F_OPEN, 2, 0, 0, "stderr"	}
};

static boolean_t
fcheck(FILE *stream, int flags)
{
	errno = 0;
	if ((stream->_flag & flags) != flags) {
		errno = EBADF;
		return (B_FALSE);
	}
	return (B_TRUE);
}

int
fclose(FILE *stream)
{
	if (!fcheck(stream, F_OPEN))
		return (EOF);

	(void) close(stream->_file);
	stream->_flag = 0;
	stream->_file = -1;
	stream->_name[0] = '\0';
	return (0);
}

int
feof(FILE *stream)
{
	if (!fcheck(stream, F_OPEN))
		return (0);

	return (stream->_len == stream->_offset);
}

int
ferror(FILE *stream)
{
	if (!fcheck(stream, F_OPEN))
		return (0);

	return ((stream->_flag & F_ERROR) != 0);
}

void
clearerr(FILE *stream)
{
	stream->_flag &= ~F_ERROR;
}

int
fflush(FILE *stream)
{
	if (!fcheck(stream, F_OPEN))
		return (EOF);

	/* Currently, a nop */
	return (0);
}

char *
fgets(char *s, int n, FILE *stream)
{
	int	bytes;
	ssize_t	cnt;

	if (!fcheck(stream, F_OPEN))
		return (NULL);

	for (bytes = 0; bytes < (n - 1); ++bytes) {
		cnt = read(stream->_file, &s[bytes], 1);
		if (cnt < 0) {
			if (bytes != 0) {
				s[bytes] = '\0';
				return (s);
			} else {
				stream->_flag |= F_ERROR;
				return (NULL);
			}
		} else if (cnt == 0) {
			/* EOF */
			if (bytes != 0) {
				s[bytes] = '\0';
				return (s);
			} else
				return (NULL);
		} else {
			stream->_offset++;
			if (s[bytes] == '\n') {
				s[bytes + 1] = '\0';
				return (s);
			}
		}
	}
	s[bytes] = '\0';
	return (s);
}

/*
 * We currently only support read-only ("r" mode) opens and unbuffered I/O.
 */
FILE *
fopen(const char *filename, const char *mode)
{
	FILE		*stream;
	const char	*t;
	int		fd, i;

	errno = 0;

	/*
	 * Make sure we have a filesystem underneath us before even trying.
	 */
	if (get_default_fs() == NULL)
		return (NULL);

	for (t = mode; t != NULL && *t != '\0'; t++) {
		switch (*t) {
		case 'b':
			/* We ignore this a'la ISO C standard conformance */
			break;
		case 'r':
			/* We ignore this because we always open for reading */
			break;

		case 'a':
		case 'w':
		case '+':
			errno = EROFS;
			return (NULL);

		default:
			errno = EINVAL;
			return (NULL);
		}
	}

	for (i = 0; i < _NFILE; i++) {
		stream = &__iob[i];
		if ((stream->_flag & F_OPEN) == 0) {
			fd = open(filename, O_RDONLY);
			if (fd < 0)
				return (NULL);

			stream->_file = fd;
			stream->_flag |= F_OPEN;
			(void) strlcpy(stream->_name, filename,
			    sizeof (stream->_name));
			return (stream);
		}
	}

	errno = EMFILE;
	return (NULL);
}

/* PRINTFLIKE1 */
void
printf(const char *fmt, ...)
{
	va_list adx;

	va_start(adx, fmt);
	prom_vprintf(fmt, adx);
	va_end(adx);
}

/*
 * Only writing to stderr or stdout is permitted.
 */
/* PRINTFLIKE2 */
int
fprintf(FILE *stream, const char *format, ...)
{
	int	nwritten;
	va_list	va;

	if (!fcheck(stream, F_OPEN))
		return (-1);

	/*
	 * Since fopen() doesn't return writable streams, the only valid
	 * writable streams are stdout and stderr.
	 */
	if (stream != stdout && stream != stderr) {
		errno = EBADF;
		return (-1);
	}

	va_start(va, format);
	printf(format, va);
	va_end(va);

	va_start(va, format);
	nwritten = vsnprintf(NULL, 0, format, va);
	va_end(va);

	return (nwritten);
}

size_t
fread(void *ptr, size_t size, size_t nitems, FILE *stream)
{
	size_t	items;
	ssize_t	bytes, totbytes = 0;
	char	*strp = ptr;

	if (!fcheck(stream, F_OPEN))
		return (0);

	for (items = 0, bytes = 0; items < nitems; items++) {
		bytes = read(stream->_file, &strp[totbytes], size);
		if (bytes < 0) {
			stream->_flag |= F_ERROR;
			return (0);
		} else if (bytes == 0) {
			/* EOF */
			return ((totbytes == 0) ? 0 : totbytes / size);
		} else if (bytes == size) {
			stream->_offset += bytes;
			totbytes += bytes;
		} else {
			(void) lseek(stream->_file, stream->_offset, SEEK_SET);
			return (totbytes / size);
		}
	}

	return (totbytes / size);
}

/*
 * We don't grow files.
 */
int
fseek(FILE *stream, long offset, int whence)
{
	off_t	new_offset, result;

	if (!fcheck(stream, F_OPEN | F_SEEKABLE))
		return (-1);

	switch (whence) {
	case SEEK_SET:
		new_offset = (off_t)offset;
		break;
	case SEEK_CUR:
		new_offset = stream->_offset + (off_t)offset;
		break;
	case SEEK_END:
		new_offset = (off_t)stream->_len + (off_t)offset;
		break;
	default:
		errno = EINVAL;
		return (-1);
	}

	if (new_offset > (off_t)stream->_len) {
		errno = EFBIG;
	} else if (new_offset < 0L) {
		errno = EOVERFLOW;
	} else {
		errno = 0;
	}

	result = lseek(stream->_file, new_offset, SEEK_SET);
	if (result >= 0)
		stream->_offset = result;
	else
		stream->_flag |= F_ERROR;

	return (result);
}

long
ftell(FILE *stream)
{
	if (!fcheck(stream, F_OPEN | F_SEEKABLE))
		return (0);

	return ((long)stream->_offset);
}

size_t
fwrite(const void *ptr, size_t size, size_t nitems, FILE *stream)
{
	if (!fcheck(stream, F_OPEN))
		return (0);

	/*
	 * Since fopen() doesn't return writable streams, the only valid
	 * writable streams are stdout and stderr.
	 */
	if (stream != stdout && stream != stderr) {
		errno = EBADF;
		return (0);
	}

	prom_writestr(ptr, size * nitems);
	return (nitems);
}

/*ARGSUSED*/
int
setvbuf(FILE *stream, char *buf, int type, size_t size)
{
	if (!fcheck(stream, F_OPEN))
		return (-1);

	/* Currently a nop, probably always will be. */
	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 2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef _SA_STDIO_H
#define	_SA_STDIO_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#include <sys/types.h>
#include <stdarg.h>

/*
 * Exported interfaces for standalone's subset of libc's <stdio.h>.
 * All standalone code *must* use this header rather than libc's.
 */

#ifdef __cplusplus
extern "C" {
#endif

#ifndef NULL
#define	NULL	0
#endif

#ifndef	EOF
#define	EOF	(-1)
#endif

/*
 * Flags to setvbuf() which we pretend to support.  We're always really _IONBF.
 */
#define	_IOFBF	0000	/* full buffered */
#define	_IOLBF	0100	/* line buffered */
#define	_IONBF	0004	/* not buffered */

typedef struct {
	unsigned char	_flag; 		/* state of the stream */
	int		_file;		/* file descriptor */
	ssize_t		_len;		/* total len of file */
	ssize_t		_offset;	/* offset within the file */
	char		_name[256];	/* name of the file (for debugging) */
} FILE;

#define	stdin	(&__iob[0])
#define	stdout	(&__iob[1])
#define	stderr	(&__iob[2])

#define	_NFILE	10
extern	FILE	__iob[_NFILE];

extern int	fclose(FILE *);
extern int	feof(FILE *);
extern int	fflush(FILE *);
extern int	ferror(FILE *);
extern void	clearerr(FILE *);

extern char	*fgets(char *, int, FILE *);
extern FILE	*fopen(const char *, const char *);
extern size_t	fread(void *, size_t, size_t, FILE *);
extern int	fseek(FILE *, long, int);
extern long	ftell(FILE *);
extern size_t	fwrite(const void *, size_t, size_t, FILE *);
extern int	setvbuf(FILE *, char *, int, size_t);

/* PRINTFLIKE1 */
extern void	printf(const char *, ...);
/* PRINTFLIKE2 */
extern int	fprintf(FILE *, const char *, ...);
/* PRINTFLIKE2 */
extern int	sprintf(char *, const char *, ...);
/* PRINTFLIKE3 */
extern size_t	snprintf(char *, size_t, const char *, ...);
extern int	vsprintf(char *, const char *, va_list);
extern size_t	vsnprintf(char *, size_t, const char *, va_list);

#ifdef __cplusplus
}
#endif

#endif /* _SA_STDIO_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 2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#include <sys/promif.h>
#include <stddef.h>

/*
 * Trivial version of getenv() -- since standalone has no environment
 * variables, just return NULL.
 */
/* ARGSUSED */
char *
getenv(const char *name)
{
	return (NULL);
}

/*
 * Standalone's approximation of abort().
 */
void
abort(void)
{
	prom_panic("fatal error; aborting");
}
/*
 * 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 2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef _SA_STDLIB_H
#define	_SA_STDLIB_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"


/*
 * Exported interfaces for standalone's subset of libc's <stdlib.h>.
 * All standalone code *must* use this header rather than libc's.
 */

#include <sys/types.h>

#ifdef __cplusplus
extern "C" {
#endif

extern void *malloc(size_t);
extern void *calloc(size_t, size_t);
extern void *realloc(void *, size_t);
extern void free(void *);
extern void abort(void);
extern char *getenv(const char *);
extern void qsort(void *, size_t, size_t, int (*)(const void *, const void *));
extern void *bsearch(const void *, const void *, size_t, size_t,
    int (*)(const void *, const void *));

#ifdef __cplusplus
}
#endif

#endif /* _SA_STDLIB_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 2002-2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#include <string.h>
#include <stdlib.h>
#include <stddef.h>

char *
strdup(const char *s)
{
	int	n;
	char 	*ret;

	n = strlen(s) + 1;
	if ((ret = malloc(n)) == NULL)
		return (NULL);

	return (strcpy(ret, s));
}
/*
 * 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 2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef _SA_STRING_H
#define	_SA_STRING_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

/*
 * Exported interfaces for standalone's subset of libc's <string.h>.
 * All standalone code *must* use this header rather than libc's.
 */

#include <sys/types.h>

#ifdef __cplusplus
extern "C" {
#endif

#ifndef	NULL
#define	NULL    0		/* defined here as per ISO C */
#endif

extern int	memcmp(const void *,  const void *, size_t);
extern void	*memmove(void *, const void *, size_t);
extern void	*memset(void *, int, size_t);
extern void	*memcpy(void *, const void *, size_t);
extern void	*memchr(const void *, int, size_t);

extern int	strcmp(const char *, const char *);
extern int	strncmp(const char *, const char *, size_t);
extern size_t	strlen(const char *);
extern char	*strcat(char *, const char *);
extern char	*strncat(char *, const char *, size_t);
extern size_t	strlcat(char *, const char *, size_t);
extern char	*strcpy(char *, const char *);
extern char	*strncpy(char *, const char *, size_t);
extern size_t	strlcpy(char *, const char *, size_t);
extern char	*strchr(const char *, int);
extern char	*strrchr(const char *, int);
extern char	*strstr(const char *, const char *);
extern char	*strtok(char *, const char *);
extern char	*strerror(int);
extern char	*strdup(const char *);
extern long	strtol(const char *, char **, int);
extern unsigned long strtoul(const char *, char **, int);

#ifdef __cplusplus
}
#endif

#endif /* _SA_STRING_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 1998, 2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"	/* from SVR4.0 1.1 */

#include <stdio.h>
#include <strings.h>

/*
 * NOTE: strcasecmp()/strncasecmp() are in $SRC/common/util/string.c.
 */

int
bcmp(const void *s1, const void *s2, size_t len)
{
	return (memcmp(s1, s2, len) != 0);
}

/*
 * NOTE: our memmove() implementation depends on the fact that this bcopy()
 * supports overlapping regions.
 */
void
bcopy(const void *src, void *dest, size_t count)
{
	const char	*csrc	= src;
	char		*cdest	= dest;

	if (count == 0)
		return;

	if (csrc < cdest && (csrc + count) > cdest) {
		/* overlap copy */
		while (count != 0)
			--count, *(cdest + count) = *(csrc + count);
	} else {
		while (count != 0)
			--count, *cdest++ = *csrc++;
	}
}

void
bzero(void *p, size_t n)
{
	char	*cp;

	for (cp = p; n != 0; n--)
		*cp++ = 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 2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef _SA_STRINGS_H
#define	_SA_STRINGS_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

/*
 * Exported interfaces for standalone's subset of libc's <strings.h>.
 * All standalone code *must* use this header rather than libc's.
 */

#include <sys/types.h>
#include <string.h>

#ifdef __cplusplus
extern "C" {
#endif

extern int	bcmp(const void *, const void *, size_t);
extern void	bcopy(const void *, void *, size_t);
extern void	bzero(void *, size_t);

extern int	strcasecmp(const char *, const char *);
extern int	strncasecmp(const char *, const char *, size_t);

#ifdef __cplusplus
}
#endif

#endif /* _SA_STRINGS_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 2002-2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 *
 * Time routines, snagged from libc.
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#include <errno.h>
#include <sys/types.h>
#include <sys/bootvfs.h>
#include <sys/salib.h>
#include <sys/promif.h>
#include <stdio.h>
#include <time.h>

#define	CBUFSIZ 26

static time_t	start_time, secs_since_boot;

const int	__year_lengths[2] = {
	DAYS_PER_NYEAR, DAYS_PER_LYEAR
};
const int	__mon_lengths[2][MONS_PER_YEAR] = {
	31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,
	31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};

/*
 * Initializes our "clock" to the creation date of /timestamp, which is
 * made on the fly for us by the web server. Thereafter, time() will keep
 * time sort of up to date.
 */
void
init_boot_time(void)
{
	struct stat sb;

	if (start_time == 0) {
		if (stat("/timestamp", &sb) < 0)
			prom_panic("init_boot_time: cannot stat /timestamp");

		start_time = sb.st_ctim.tv_sec;
		secs_since_boot = prom_gettime() / 1000;
	}
}

/*
 * Time is crudely incremented.
 */
time_t
time(time_t *tloc)
{
	time_t	time_now;

	time_now = start_time + ((prom_gettime() / 1000) - secs_since_boot);

	if (tloc != NULL)
		*tloc = time_now;

	if (start_time == 0)
		return (0);
	else
		return (time_now);
}

struct tm *
gmtime(const time_t *clock)
{
	static struct tm	result;
	struct tm	*tmp;
	long		days;
	int		rem;
	long		y;
	long		newy;
	const int	*ip;

	tmp = &result;
	days = *clock / SECS_PER_DAY;
	rem = *clock % SECS_PER_DAY;
	while (rem < 0) {
		rem += SECS_PER_DAY;
		--days;
	}
	while (rem >= SECS_PER_DAY) {
		rem -= SECS_PER_DAY;
		++days;
	}
	tmp->tm_hour = (int)(rem / SECS_PER_HOUR);
	rem = rem % SECS_PER_HOUR;
	tmp->tm_min = (int)(rem / SECS_PER_MIN);
	tmp->tm_sec = (int)(rem % SECS_PER_MIN);
	tmp->tm_wday = (int)((EPOCH_WDAY + days) % DAYS_PER_WEEK);
	if (tmp->tm_wday < 0)
		tmp->tm_wday += DAYS_PER_WEEK;
	y = EPOCH_YEAR;

#define	LEAPS_THRU_END_OF(y)    ((y) / 4 - (y) / 100 + (y) / 400)

	while (days < 0 || days >= (long)__year_lengths[isleap(y)]) {
		newy = y + days / DAYS_PER_NYEAR;
		if (days < 0)
			--newy;
		days -= ((long)newy - (long)y) * DAYS_PER_NYEAR +
			LEAPS_THRU_END_OF(newy > 0 ? newy - 1L : newy) -
			LEAPS_THRU_END_OF(y > 0 ? y - 1L : y);
		y = newy;
	}

	tmp->tm_year = y - TM_YEAR_BASE;
	tmp->tm_yday = days;
	ip = __mon_lengths[isleap(y)];
	for (tmp->tm_mon = 0; days >= ip[tmp->tm_mon]; ++(tmp->tm_mon))
		days = days - ip[tmp->tm_mon];
	tmp->tm_mday = (days + 1);
	tmp->tm_isdst = 0;
	return (tmp);
}

/*
 * The standalone booter runs in GMT.
 */
struct tm *
localtime(const time_t *clock)
{
	return (gmtime(clock));
}

static char *
ct_numb(char *cp, int n)
{
	cp++;
	if (n >= 10)
		*cp++ = (n / 10) % 10 + '0';
	else
		*cp++ = ' ';		/* Pad with blanks */
	*cp++ = n % 10 + '0';
	return (cp);
}

char *
asctime(const struct tm *t)
{
	char *cp;
	const char *ncp;
	const int *tp;
	const char *Date = "Day Mon 00 00:00:00 1900\n";
	const char *Day  = "SunMonTueWedThuFriSat";
	const char *Month = "JanFebMarAprMayJunJulAugSepOctNovDec";
	static char cbuf[CBUFSIZ];

	cp = cbuf;
	for (ncp = Date; *cp++ = *ncp++; /* */);
	ncp = Day + (3 * t->tm_wday);
	cp = cbuf;
	*cp++ = *ncp++;
	*cp++ = *ncp++;
	*cp++ = *ncp++;
	cp++;
	tp = &t->tm_mon;
	ncp = Month + ((*tp) * 3);
	*cp++ = *ncp++;
	*cp++ = *ncp++;
	*cp++ = *ncp++;
	cp = ct_numb(cp, *--tp);
	cp = ct_numb(cp, *--tp + 100);
	cp = ct_numb(cp, *--tp + 100);
	--tp;
	cp = ct_numb(cp, *tp + 100);
	if (t->tm_year < 100) {
		/* Common case: "19" already in buffer */
		cp += 2;
	} else if (t->tm_year < 8100) {
		cp = ct_numb(cp, (1900 + t->tm_year) / 100);
		cp--;
	} else {
		/* Only 4-digit years are supported */
		errno = EOVERFLOW;
		return (NULL);
	}
	(void) ct_numb(cp, t->tm_year + 100);
	return (cbuf);
}

char *
ctime(const time_t *t)
{
	return (asctime(localtime(t)));
}
/*
 * 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 2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef _SA_TIME_H
#define	_SA_TIME_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

/*
 * Exported interfaces for standalone's subset of libc's <time.h>.
 * All standalone code *must* use this header rather than libc's.
 */

#include <sys/types.h>

#ifdef __cplusplus
extern "C" {
#endif

struct	tm {
	int	tm_sec;		/* seconds after the minute */
	int	tm_min;		/* minutes after the hour */
	int	tm_hour;	/* hour since midnight */
	int	tm_mday;	/* day of the month */
	int	tm_mon;		/* months since January */
	int	tm_year;	/* years since 1900 */
	int	tm_wday;	/* days since Sunday */
	int	tm_yday;	/* Days since January 1 */
	int	tm_isdst;	/* flag for alternate daylight savings time */
};

extern time_t time(time_t *);
extern char *ctime(const time_t *t);
extern struct tm *gmtime(const time_t *);
extern struct tm *localtime(const time_t *);

/*
 * The following silly #defines are actually ripped off from <tzfile.h>.
 * Since <tzfile.h> is not a documented header, it seemed better to just
 * inline them here rather than having a full-blown <tzfile.h> of our own.
 */
#define	EPOCH_YEAR		1970
#define	EPOCH_WDAY		4
#define	SECS_PER_MIN		60
#define	DAYS_PER_WEEK		7
#define	DAYS_PER_NYEAR		365
#define	DAYS_PER_LYEAR		366
#define	MONS_PER_YEAR		12
#define	SECS_PER_HOUR		(SECS_PER_MIN * 60)
#define	SECS_PER_DAY		(SECS_PER_HOUR * 24)
#define	TM_YEAR_BASE		1900

#define	isleap(y) (((y) % 4) == 0 && (((y) % 100) != 0 || ((y) % 400) == 0))

#ifdef __cplusplus
}
#endif

#endif /* _SA_TIME_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 2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/sysmacros.h>
#include <sys/promif.h>

static char hostname[MAXHOSTNAMELEN] = "UNKNOWN";

/*
 * Get system hostname
 */
int
gethostname(char *name, int namelen)
{
	(void) strlcpy(name, hostname, MIN(namelen, MAXHOSTNAMELEN));
	return (0);
}

/*
 * Set system hostname
 */
int
sethostname(char *name, int namelen)
{
	(void) strlcpy(hostname, name, MIN(namelen + 1, MAXHOSTNAMELEN));
	return (0);
}

/*
 * Get the current PID; in standalone we always use 2 since it's the first
 * "mortal" PID.
 */
pid_t
getpid(void)
{
	return (2);
}

/*
 * Sleep for a given number of seconds
 */
unsigned int
sleep(unsigned int secs)
{
	uint_t end = (secs * 1000) + prom_gettime();

	while (prom_gettime() < end)
		/* Null body */;

	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 2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef _SA_UNISTD_H
#define	_SA_UNISTD_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

/*
 * Exported interfaces for standalone's subset of libc's <unistd.h>.
 * All standalone code *must* use this header rather than libc's.
 */

#include <sys/types.h>

#ifdef __cplusplus
extern "C" {
#endif

/*
 * NOTE: Some of these are duplicated from <sys/bootvfs.h>; we do this
 *	 rather than just #including it to avoid polluting the namespace.
 */
extern int	open(const char *, int);
extern int	close(int);
extern off_t	lseek(int, off_t, int);
extern ssize_t	read(int, void *, size_t);
extern pid_t	getpid(void);
extern int	gethostname(char *, int);
extern int	sethostname(char *, int);
extern unsigned int sleep(unsigned int);

#ifdef __cplusplus
}
#endif

#endif /* _SA_UNISTD_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 2004 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

LIBRARY = libsock.a
OBJECTS = socket.o sock_test.o

include ../Makefile.com

LDLIBS += -linet -ltcp
CPPFLAGS += -I../inet -I../tcp $(SOCKCPPFLAGS)
CERRWARN += -Wno-type-limits
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 2001-2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 *
 * sock_test.c.  Implementing a CLI for inetboot testing.
 */
#pragma ident	"%Z%%M%	%I%	%E% SMI"

#include <sys/types.h>
#include "socket_impl.h"
#include "socket_inet.h"
#include <sys/socket.h>
#include <sys/sysmacros.h>
#include <netinet/in_systm.h>
#include <sys/promif.h>
#include <sys/salib.h>
#include <ctype.h>
#include <errno.h>
#include <netinet/in.h>
#include "tcp_inet.h"
#include "ipv4.h"
#include <netinet/tcp.h>

static int atoi(const char *);
static int st_accept(void);
static int st_bind(void);
static int st_connect(void);
static int st_echo(void);
static int st_getsockname(void);
static int st_getsockopt(void);
static int st_get_addr_and_port(in_addr_t *, unsigned short *);
static int st_get_buf_and_cnt(char **, int *);
static int st_listen(void);
static int st_match_option(char *, int *, int *);
static int st_send(void);
static int st_sendto(void);
static int st_recv(void);
static int st_recvfrom(void);
static int st_set_addr(void);
static int st_set_netmask(void);
static int st_set_router(void);
static int st_setsockopt(void);
static int st_socket(void);
static int st_sock_close(void);
static int st_tcp_tw_report(void);
static int st_toggle_promiscuous(void);
static int st_use_obp(void);

/* Wrapper for socket calls. */
static int st_local_accept(int, struct sockaddr *, socklen_t *);
static int st_local_bind(int, const struct sockaddr *, socklen_t);
static int st_local_connect(int,  const  struct  sockaddr  *, socklen_t);
static int st_local_getsockname(int, struct sockaddr *, socklen_t *);
static int st_local_getsockopt(int, int, int, void *, socklen_t *);
static int st_local_listen(int, int);
static int st_local_recv(int, void *, size_t, int);
static int st_local_recvfrom(int, void *, size_t, int, struct sockaddr *,
	socklen_t *);
static int st_local_send(int, const void *, size_t, int);
static int st_local_sendto(int, const void *, size_t, int,
	const struct sockaddr *, socklen_t);
static int st_local_setsockopt(int, int, int, const void *, socklen_t);
static int st_local_socket(int, int, int);
static int st_local_socket_close(int);

struct sock_test_cmd_s {
	char *st_cmd;
	int (*st_fn)(void);
};

static struct sock_test_cmd_s st_cmds[] = {
	{ "set_addr", st_set_addr},
	{ "set_netmask", st_set_netmask},
	{ "set_router", st_set_router},
	{ "socket", st_socket },
	{ "bind", st_bind },
	{ "accept", st_accept },
	{ "connect", st_connect },
	{ "listen", st_listen },
	{ "send", st_send },
	{ "sendto", st_sendto },
	{ "recv", st_recv },
	{ "recvfrom", st_recvfrom },
	{ "setsockopt", st_setsockopt },
	{ "getsockopt", st_getsockopt },
	{ "getsockname", st_getsockname },
	{ "close", st_sock_close },
	{ "echo", st_echo },
	{ "toggle_promiscous", st_toggle_promiscuous},
	{ "use_obp", st_use_obp},
	{ "tcp_tw_report", st_tcp_tw_report},
	{ NULL, NULL }
};

struct so_option_string_s {
	char *so_name;
	int so_opt;
	int so_opt_level;
} so_option_array[] = {
	{ "rcvtimeo", SO_RCVTIMEO, SOL_SOCKET },
	{ "dontroute", SO_DONTROUTE, SOL_SOCKET },
	{ "reuseaddr", SO_REUSEADDR, SOL_SOCKET },
	{ "rcvbuf", SO_RCVBUF, SOL_SOCKET },
	{ "sndbuf", SO_SNDBUF, SOL_SOCKET },
	{ NULL, 0 }
};

#define	NO_OPENED_SOCKET	-1

/* Right now, we only allow one socket at one time. */
static int g_sock_fd = NO_OPENED_SOCKET;
static int save_g_sock_fd = NO_OPENED_SOCKET;

/* Boolean to decide if OBP network routines should be used. */
static boolean_t use_obp = B_FALSE;


/*
 * The following routines are wrappers for the real socket routines.  The
 * boolean use_obp is used to decide whether the real socket routines is
 * called or the "equivalent" OBP provided routines should be called.
 */
static int
st_local_socket(int domain, int type, int protocol)
{
	if (!use_obp) {
		return (socket(domain, type, protocol));
	} else {
		return (0);
	}
}

static int
st_local_socket_close(int sd)
{
	if (!use_obp) {
		return (socket_close(sd));
	} else {
		return (0);
	}
}

static int
st_local_accept(int sd, struct sockaddr *addr, socklen_t *addr_len)
{
	if (!use_obp) {
		return (accept(sd, addr, addr_len));
	} else {
		return (0);
	}
}

static int
st_local_bind(int sd, const struct sockaddr *name, socklen_t namelen)
{
	if (!use_obp) {
		return (bind(sd, name, namelen));
	} else {
		return (0);
	}
}

static int
st_local_connect(int sd,  const struct sockaddr *addr, socklen_t addr_len)
{
	if (!use_obp) {
		return (connect(sd, addr, addr_len));
	} else {
		return (0);
	}
}

static int
st_local_listen(int sd,  int backlog)
{
	if (!use_obp) {
		return (listen(sd, backlog));
	} else {
		return (0);
	}
}

static int
st_local_send(int sd, const void *msg, size_t len, int flags)
{
	if (!use_obp) {
		return (send(sd, msg, len, flags));
	} else {
		return (0);
	}
}

static int
st_local_sendto(int sd, const void *msg, size_t len, int flags,
    const struct sockaddr *to, socklen_t tolen)
{
	if (!use_obp) {
		return (sendto(sd, msg, len, flags, to, tolen));
	} else {
		return (0);
	}
}

static int
st_local_recv(int sd, void *buf, size_t len, int flags)
{
	if (!use_obp) {
		return (recv(sd, buf, len, flags));
	} else {
		return (0);
	}
}

static int
st_local_recvfrom(int sd, void *buf, size_t len, int flags,
    struct sockaddr *from, socklen_t *fromlen)
{
	if (!use_obp) {
		return (recvfrom(sd, buf, len, flags, from, fromlen));
	} else {
		return (0);
	}
}

static int
st_local_getsockname(int sd, struct sockaddr *name, socklen_t *namelen)
{
	if (!use_obp) {
		return (getsockname(sd, name, namelen));
	} else {
		return (0);
	}
}


static int
st_local_getsockopt(int sd, int level, int option, void *optval,
    socklen_t *optlen)
{
	if (!use_obp) {
		return (getsockopt(sd, level, option, optval, optlen));
	} else {
		return (0);
	}
}

static int
st_local_setsockopt(int sd, int level, int option, const void *optval,
    socklen_t optlen)
{
	if (!use_obp) {
		return (setsockopt(sd, level, option, optval, optlen));
	} else {
		return (0);
	}
}

static int
atoi(const char *p)
{
	int n;
	int c = *p++, neg = 0;

	while (isspace(c)) {
		c = *p++;
	}
	if (!isdigit(c)) {
		switch (c) {
		case '-':
			neg++;
			/* FALLTHROUGH */
		case '+':
			c = *p++;
		}
	}
	for (n = 0; isdigit(c); c = *p++) {
		n *= 10; /* two steps to avoid unnecessary overflow */
		n += '0' - c; /* accum neg to avoid surprises at MAX */
	}
	return (neg ? n : -n);
}

int
st_interpret(char *buf)
{
	char *cmd;
	int i;

	if ((cmd = strtok(buf, " ")) == NULL)
		return (-1);

	for (i = 0; st_cmds[i].st_cmd != NULL; i++) {
		if (strcmp(cmd, st_cmds[i].st_cmd) == 0) {
			return (st_cmds[i].st_fn());
		}
	}
	printf("! Unknown command: %s\n", cmd);
	return (-1);
}


static int
st_socket(void)
{
	char *type;

	if ((type = strtok(NULL, " ")) == NULL) {
		printf("! usage: socket type\n");
		return (-1);
	}
	if (g_sock_fd != NO_OPENED_SOCKET) {
		printf("! Cannot open more than 1 socket\n");
		return (-1);
	}

	if (strcmp(type, "stream") == 0) {
		if ((g_sock_fd = st_local_socket(AF_INET, SOCK_STREAM,
		    0)) < 0) {
			printf("! Error in opening TCP socket: %d\n", errno);
			return (-1);
		} else {
			printf("@ TCP socket opened\n");
		}
	} else if (strcmp(type, "dgram") == 0) {
		if ((g_sock_fd = st_local_socket(AF_INET, SOCK_DGRAM,
		    0)) < 0) {
			printf("! Error in opening UDP socket: %d\n", errno);
			return (-1);
		} else {
			printf("@ UDP socket opened\n");
		}
	} else if (strcmp(type, "raw") == 0) {
		if ((g_sock_fd = st_local_socket(AF_INET, SOCK_RAW, 0)) < 0) {
			printf("! Error in opening RAW socket: %d\n", errno);
			return (-1);
		} else {
			printf("@ RAW socket opened\n");
		}
	} else {
		printf("! Unknown socket type: %s\n", type);
		return (-1);
	}

	return (0);
}

static int
st_set_addr(void)
{
	char *tmp;
	struct in_addr addr;

	tmp = strtok(NULL, " ");
	if (tmp == NULL) {
		printf("! No address given\n");
		return (-1);
	}
	if ((addr.s_addr = inet_addr(tmp)) == (uint32_t)-1) {
		printf("! Malformed address\n");
		return (-1);
	}

	ipv4_setipaddr(&addr);
	printf("@ IP address %s set\n", inet_ntoa(addr));

	return (0);
}

static int
st_set_netmask(void)
{
	char *tmp;
	struct in_addr addr;

	tmp = strtok(NULL, " ");
	if (tmp == NULL) {
		printf("! No netmask given\n");
		return (-1);
	}
	if ((addr.s_addr = inet_addr(tmp)) == (uint32_t)-1) {
		printf("! Malformed netmask\n");
		return (-1);
	}

	ipv4_setnetmask(&addr);
	printf("@ Netmask %s set\n", inet_ntoa(addr));

	return (0);
}

static int
st_set_router(void)
{
	char *tmp;
	struct in_addr addr;

	tmp = strtok(NULL, " ");
	if (tmp == NULL) {
		printf("! No router address given\n");
		return (-1);
	}
	if ((addr.s_addr = inet_addr(tmp)) == (uint32_t)-1) {
		printf("! Malformed router address\n");
		return (-1);
	}

	ipv4_setdefaultrouter(&addr);
	if (ipv4_route(IPV4_ADD_ROUTE, RT_DEFAULT, NULL, &addr) < 0) {
		printf("! Cannot add default route\n");
	} else {
		printf("@ Default router %s set\n", inet_ntoa(addr));
	}

	return (0);
}

static int
st_get_addr_and_port(in_addr_t *addr, unsigned short *port)
{
	char *tmp;

	if (g_sock_fd == NO_OPENED_SOCKET) {
		printf("! No socket opened\n");
		return (-1);
	}

	tmp = strtok(NULL, "/");
	if (tmp == NULL) {
		printf("! No address given\n");
		return (-1);
	}
	if ((*addr = inet_addr(tmp)) == (uint32_t)-1) {
		printf("! Malformed address\n");
		return (-1);
	}

	tmp = strtok(NULL, " ");
	if (tmp == NULL) {
		printf("! No port given\n");
		return (-1);
	}
	*port = htons(atoi(tmp));

	return (0);
}

static int
st_bind(void)
{
	struct sockaddr_in local_addr;

	if (st_get_addr_and_port(&(local_addr.sin_addr.s_addr),
	    &(local_addr.sin_port)) < 0) {
		return (-1);
	}

	local_addr.sin_family = AF_INET;
	if (st_local_bind(g_sock_fd, (struct sockaddr *)&local_addr,
	    sizeof (local_addr)) < 0) {
		printf("! Bind failed: %d\n", errno);
		return (-1);
	}
	printf("@ Socket bound to %s/%d\n", inet_ntoa(local_addr.sin_addr),
	    ntohs(local_addr.sin_port));
	return (0);
}

static int
st_listen(void)
{
	char *tmp;

	if (g_sock_fd == NO_OPENED_SOCKET) {
		printf("! No socket opened\n");
		return (-1);
	}
	if ((tmp = strtok(NULL, " ")) == NULL) {
		printf("! No backlog given\n");
		return (-1);
	}
	if (st_local_listen(g_sock_fd, atoi(tmp)) < 0) {
		printf("! Listen failed: %d\n", errno);
		return (-1);
	}
	printf("@ Listen succeeded\n");
	return (0);
}

static int
st_accept(void)
{
	struct sockaddr_in addr;
	socklen_t addr_len;
	int sd;

	if (g_sock_fd == NO_OPENED_SOCKET) {
		printf("! No socket opened\n");
		return (-1);
	}
	addr_len = sizeof (struct sockaddr_in);
	if ((sd = st_local_accept(g_sock_fd, (struct sockaddr *)&addr,
	    &addr_len)) < 0) {
		printf("! Accept failed: %d\n", errno);
		return (-1);
	}
	printf("@ Accept succeeded from %s:%d.  Socket descriptor saved\n",
	    inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
	save_g_sock_fd = g_sock_fd;
	g_sock_fd = sd;
	return (0);
}

static int
st_connect(void)
{
	struct sockaddr_in peer_addr;

	if (st_get_addr_and_port(&(peer_addr.sin_addr.s_addr),
	    &(peer_addr.sin_port)) < 0) {
		return (-1);
	}

	peer_addr.sin_family = AF_INET;
	if (st_local_connect(g_sock_fd, (struct sockaddr *)&peer_addr,
	    sizeof (peer_addr)) < 0) {
		printf("! Connect failed: %d\n", errno);
		return (-1);
	}
	printf("@ Socket connected to %s/%d\n", inet_ntoa(peer_addr.sin_addr),
	    ntohs(peer_addr.sin_port));

	return (0);
}

static int
st_get_buf_and_cnt(char **buf, int *send_cnt)
{
	char *cnt;

	if ((*buf = strtok(NULL, " ")) == NULL) {
		printf("! No send buffer\n");
		return (-1);
	}
	if ((cnt = strtok(NULL, " ")) == NULL) {
		printf("! Missing send length\n");
		return (-1);
	}

	if ((*send_cnt = atoi(cnt)) < 0) {
		printf("! Invalid send count\n");
		return (-1);
	}
	return (0);
}

static int
st_send(void)
{
	char *buf;
	int send_cnt;

	if (g_sock_fd == NO_OPENED_SOCKET) {
		printf("! No socket opened\n");
		return (-1);
	}

	if (st_get_buf_and_cnt(&buf, &send_cnt) < 0)
		return (-1);

	if ((send_cnt = st_local_send(g_sock_fd, buf, send_cnt, 0)) < 0) {
		printf("! Send failed: %d\n", errno);
		return (-1);
	}
	printf("@ Send %d bytes\n", send_cnt);

	return (0);
}

static int
st_sendto(void)
{
	struct sockaddr_in peer_addr;
	char *buf;
	int send_cnt;

	if (st_get_addr_and_port(&(peer_addr.sin_addr.s_addr),
	    &(peer_addr.sin_port)) < 0) {
		return (-1);
	}
	peer_addr.sin_family = AF_INET;

	if (st_get_buf_and_cnt(&buf, &send_cnt) < 0)
		return (-1);

	if ((send_cnt = st_local_sendto(g_sock_fd, buf, send_cnt, 0,
	    (struct sockaddr *)&peer_addr, sizeof (peer_addr))) < 0) {
		printf("! Sendto failed: %d\n", errno);
		return (-1);
	}
	printf("@ Send %d bytes\n", send_cnt);

	return (0);
}

static int
st_recv(void)
{
	char *tmp;
	char *buf;
	int buf_len, ret;

	if (g_sock_fd == NO_OPENED_SOCKET) {
		printf("! No socket opened\n");
		return (-1);
	}

	if ((tmp = strtok(NULL, " ")) == NULL) {
		printf("! No buffer len given\n");
		return (-1);
	}
	buf_len = atoi(tmp);

	if ((buf = bkmem_zalloc(buf_len)) == NULL) {
		printf("! Cannot allocate buffer: %d\n", errno);
		return (-1);
	}
	if ((ret = st_local_recv(g_sock_fd, buf, buf_len, 0)) <= 0) {
		if (ret == 0) {
			printf("@ EOF received: %d\n", errno);
			return (0);
		}
		printf("! Cannot recv: %d\n", errno);
		return (-1);
	}
	printf("@ Bytes received: %d\n", ret);
	hexdump(buf, ret);
	bkmem_free(buf, buf_len);
	return (0);
}

static int
st_recvfrom(void)
{
	char *tmp;
	char *buf;
	int buf_len, ret;
	struct sockaddr_in from;
	socklen_t fromlen;

	if (g_sock_fd == NO_OPENED_SOCKET) {
		printf("! No socket opened\n");
		return (-1);
	}

	if ((tmp = strtok(NULL, " ")) == NULL) {
		printf("! No buffer len given\n");
		return (-1);
	}
	buf_len = atoi(tmp);

	if ((buf = bkmem_zalloc(buf_len)) == NULL) {
		printf("! Cannot allocate buffer: %d\n", errno);
		return (-1);
	}
	fromlen = sizeof (from);
	if ((ret = st_local_recvfrom(g_sock_fd, buf, buf_len, 0,
	    (struct sockaddr *)&from, &fromlen)) <= 0) {
		if (ret == 0) {
			printf("@ EOF received: %d\n", errno);
			return (0);
		}
		printf("! Cannot recv: %d\n", errno);
		return (-1);
	}
	printf("@ Bytes received from %s/%d: %d\n",
	    inet_ntoa(from.sin_addr), ntohs(from.sin_port), ret);
	hexdump(buf, ret);
	bkmem_free(buf, buf_len);
	return (0);
}

/*
 * To act as an echo server.  Note that it assumes the address and
 * netmask have been set.
 */
static int
st_echo(void)
{
	char *tmp;
	int listen_fd, newfd;
	int echo_port;
	struct sockaddr_in addr;
	socklen_t addr_size;
	int backlog = 20;
	char *buf;
	int buf_len, ret, snd_cnt;

	tmp = strtok(NULL, " ");
	if (tmp == NULL) {
		printf("! No echo port given\n");
		return (-1);
	}
	echo_port = atoi(tmp);
	tmp = strtok(NULL, " ");
	if (tmp == NULL) {
		printf("! No buffer size given\n");
		return (-1);
	}
	buf_len = atoi(tmp);

	/* Create local socket for echo server */
	if ((listen_fd = st_local_socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		printf("! Error in opening TCP socket: %d\n", errno);
		return (-1);
	} else {
		printf("@ Local TCP socket opened\n");
	}

	/* Bind local socket */
	addr.sin_family = AF_INET;
	addr.sin_port = htons(echo_port);
	addr.sin_addr.s_addr = INADDR_ANY;

	if (st_local_bind(listen_fd, (struct sockaddr *)&addr,
	    sizeof (addr)) < 0) {
		printf("! Bind failed: %d\n", errno);
		return (-1);
	}
	if (st_local_listen(listen_fd, backlog) < 0) {
		printf("! Listen failed: %d\n", errno);
		return (-1);
	}

	addr_size = sizeof (addr);
	if ((newfd = st_local_accept(listen_fd, (struct sockaddr *)&addr,
	    &addr_size)) < 0) {
		printf("! Accept failed: %d\n", errno);
		(void) st_local_socket_close(listen_fd);
		return (-1);
	}
	printf("@ Accepted connection: %s/%d\n", inet_ntoa(addr.sin_addr),
		ntohs(addr.sin_port));
	(void) st_local_socket_close(listen_fd);

	if ((buf = bkmem_zalloc(buf_len)) == NULL) {
		printf("! Cannot allocate buffer: %d\n", errno);
		(void) st_local_socket_close(newfd);
		return (-1);
	}
	while ((ret = st_local_recv(newfd, buf, buf_len, 0)) > 0) {
		printf("@ Bytes received: %d\n", ret);
		hexdump(buf, ret);
		if ((snd_cnt = st_local_send(newfd, buf, ret, 0)) < ret) {
			printf("! Send failed: %d\n", errno);
			bkmem_free(buf, buf_len);
			return (-1);
		}
		printf("@ Sent %d bytes\n", snd_cnt);
	}
	(void) st_local_socket_close(newfd);
	if (ret < 0) {
		printf("! Cannot recv: %d\n", errno);
		bkmem_free(buf, buf_len);
		return (-1);
	} else {
		return (0);
	}
}

static int
st_match_option(char *opt_s, int *opt, int *opt_level)
{
	int i;

	for (i = 0; so_option_array[i].so_name != NULL; i++) {
		if (strcmp(so_option_array[i].so_name, opt_s) == 0) {
			*opt = so_option_array[i].so_opt;
			*opt_level = so_option_array[i].so_opt_level;
			return (0);
		}
	}
	printf("! Unknown option\n");
	return (-1);
}

static int
st_setsockopt(void)
{
	char *tmp;
	int opt, opt_level, opt_val;

	if (g_sock_fd == NO_OPENED_SOCKET) {
		printf("! No socket opened\n");
		return (-1);
	}

	if ((tmp = strtok(NULL, " ")) == NULL) {
		printf("! No option given\n");
		return (-1);
	}
	if (st_match_option(tmp, &opt, &opt_level) < 0) {
		return (-1);
	}

	/* We only support integer option for the moment. */
	if ((tmp = strtok(NULL, " ")) == NULL) {
		printf("! No option value given\n");
		return (-1);
	}
	opt_val = atoi(tmp);

	if (st_local_setsockopt(g_sock_fd, opt_level, opt, &opt_val,
	    sizeof (int)) < 0) {
		printf("! Cannot set option: %d\n", errno);
		return (-1);
	}
	printf("@ Option set successfully\n");
	return (0);
}

static int
st_getsockname(void)
{
	struct sockaddr_in addr;
	socklen_t len;

	if (g_sock_fd == NO_OPENED_SOCKET) {
		printf("! No socket opened\n");
		return (-1);
	}

	len = sizeof (addr);
	if (st_local_getsockname(g_sock_fd, (struct sockaddr *)&addr,
	    &len) < 0) {
		printf("! getsockname failed: %d\n", errno);
		return (-1);
	}
	printf("@ Local socket name: %s/%d\n", inet_ntoa(addr.sin_addr),
	    ntohs(addr.sin_port));
	return (0);
}

static int
st_getsockopt(void)
{
	char *tmp;
	int opt, opt_level, opt_val;
	socklen_t opt_len;

	if (g_sock_fd == NO_OPENED_SOCKET) {
		printf("! No socket opened\n");
		return (-1);
	}

	if ((tmp = strtok(NULL, " ")) == NULL) {
		printf("! No option given\n");
		return (-1);
	}
	if (st_match_option(tmp, &opt, &opt_level) < 0) {
		return (-1);
	}

	opt_len = sizeof (opt_val);
	if (st_local_getsockopt(g_sock_fd, opt_level, opt, &opt_val,
	    &opt_len) < 0) {
		printf("! Cannot get option: %d\n", errno);
		return (-1);
	}
	printf("@ Option value is %d\n", opt_val);
	return (-1);
}

static int
st_sock_close(void)
{
	if (g_sock_fd == NO_OPENED_SOCKET) {
		printf("! No socket opened\n");
		return (-1);
	}
	if (st_local_socket_close(g_sock_fd) < 0) {
		printf("! Error in closing socket: %d\n", errno);
		return (-1);
	}
	printf("@ Socket closed");
	if (save_g_sock_fd != NO_OPENED_SOCKET) {
		g_sock_fd = save_g_sock_fd;
		save_g_sock_fd = NO_OPENED_SOCKET;
		printf(", switching to saved socket descriptor\n");
	} else {
		g_sock_fd = NO_OPENED_SOCKET;
		printf("\n");
	}
	return (0);
}

static int
st_toggle_promiscuous(void)
{
	/* We always start with non-promiscuous mode. */
	static boolean_t promiscuous = B_FALSE;

	promiscuous = !promiscuous;
	(void) ipv4_setpromiscuous(promiscuous);
	printf("@ Setting promiscuous to %d\n", promiscuous);
	return (0);
}

static int
st_use_obp(void)
{
	if ((use_obp = !use_obp) == B_TRUE) {
		printf("@ Now using OBP routines\n");
	} else {
		printf("@ Now using socket routines\n");
	}
	return (0);
}

static int
st_tcp_tw_report(void)
{
	printf("@ TCP Time Wait report\n");
	tcp_time_wait_report();
	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 2001-2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 *
 * Socket CLI testing header file.
 */

#ifndef _SOCK_TEST_H
#define	_SOCK_TEST_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#ifdef	__cplusplus
extern "C" {
#endif

extern int st_interpret(char *);

#ifdef	__cplusplus
}
#endif

#endif /* _SOCK_TEST_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.
 *
 * socket.c, Code implementing a simple socket interface.
 */

#include <sys/types.h>
#include "socket_impl.h"
#include <sys/isa_defs.h>
#include <sys/sysmacros.h>
#include <sys/bootconf.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <sys/uio.h>
#include <sys/salib.h>
#include "socket_inet.h"
#include "ipv4.h"
#include "ipv4_impl.h"
#include "udp_inet.h"
#include "tcp_inet.h"
#include "mac.h"
#include "mac_impl.h"
#include <sys/promif.h>

struct inetboot_socket	sockets[MAXSOCKET] = { 0 };

/* Default send and receive socket buffer size */
#define	SO_DEF_SNDBUF	48*1024
#define	SO_DEF_RCVBUF	48*1024

/* Default max socket buffer size */
#define	SO_MAX_BUF	4*1024*1024

static ssize_t dgram_sendto(int, const void *, size_t, int,
    const struct sockaddr *, int);
static ssize_t stream_sendto(int, const void *, size_t, int);
static int bind_check(int, const struct sockaddr *);
static int quickbind(int);

/* Check the validity of a fd and return the socket index of that fd. */
int
so_check_fd(int fd, int *errno)
{
	int i;

	i = FD_TO_SOCKET(fd);
	if (i < 0 || i >= MAXSOCKET) {
		*errno = ENOTSOCK;
		return (-1);
	}
	if (sockets[i].type == INETBOOT_UNUSED) {
		*errno = ENOTSOCK;
		return (-1);
	}
	return (i);
}

/*
 * Create an endpoint for network communication. Returns a descriptor.
 *
 * Notes:
 *	Only PF_INET communication domains are supported. Within
 *	this domain, only SOCK_RAW, SOCK_DGRAM and SOCK_STREAM types are
 *	supported.
 */
int
socket(int domain, int type, int protocol)
{
	static int sock_initialized;
	int i;

	errno = 0;

	if (!sock_initialized) {
		for (i = 0; i < MAXSOCKET; i++)
			sockets[i].type = INETBOOT_UNUSED;
		sock_initialized = B_TRUE;
	}
	if (domain != AF_INET) {
		errno = EPROTONOSUPPORT;
		return (-1);
	}

	/* Find available socket */
	for (i = 0; i < MAXSOCKET; i++) {
		if (sockets[i].type == INETBOOT_UNUSED)
			break;
	}
	if (i >= MAXSOCKET) {
		errno = EMFILE;	/* No slots left. */
		return (-1);
	}

	/* Some socket initialization... */
	sockets[i].so_rcvbuf = SO_DEF_RCVBUF;
	sockets[i].so_sndbuf = SO_DEF_SNDBUF;

	/*
	 * Note that we ignore the protocol field for SOCK_DGRAM and
	 * SOCK_STREAM.  When we support different protocols in future,
	 * this needs to be changed.
	 */
	switch (type) {
	case SOCK_RAW:
		ipv4_raw_socket(&sockets[i], (uint8_t)protocol);
		break;
	case SOCK_DGRAM:
		udp_socket_init(&sockets[i]);
		break;
	case SOCK_STREAM:
		tcp_socket_init(&sockets[i]);
		break;
	default:
		errno = EPROTOTYPE;
		break;
	}

	if (errno != 0)
		return (-1);

	/* IPv4 generic initialization. */
	ipv4_socket_init(&sockets[i]);

	/* MAC generic initialization. */
	mac_socket_init(&sockets[i]);

	return (i + SOCKETTYPE);
}

int
getsockname(int s, struct sockaddr *name,  socklen_t *namelen)
{
	int i;

	errno = 0;
	if ((i = so_check_fd(s, &errno)) == -1)
		return (-1);

	if (*namelen < sizeof (struct sockaddr_in)) {
		errno = ENOMEM;
		return (-1);
	}

	/* Structure assignment... */
	*((struct sockaddr_in *)name) = sockets[i].bind;
	*namelen = sizeof (struct sockaddr_in);
	return (0);
}

/*
 * The socket options we support are:
 * SO_RCVTIMEO	-	Value is in msecs, and is of uint32_t.
 * SO_DONTROUTE	-	Value is an int, and is a boolean (nonzero if set).
 * SO_REUSEADDR -	Value is an int boolean.
 * SO_RCVBUF -		Value is an int.
 * SO_SNDBUF -		Value is an int.
 */
int
getsockopt(int s, int level, int option, void *optval, socklen_t *optlen)
{
	int i;

	errno = 0;
	if ((i = so_check_fd(s, &errno)) == -1)
		return (-1);

	switch (level) {
	case SOL_SOCKET: {
		switch (option) {
		case SO_RCVTIMEO:
			if (*optlen == sizeof (uint32_t)) {
				*(uint32_t *)optval = sockets[i].in_timeout;
			} else {
				*optlen = 0;
				errno = EINVAL;
			}
			break;
		case SO_DONTROUTE:
			if (*optlen == sizeof (int)) {
				*(int *)optval =
				    (sockets[i].out_flags & SO_DONTROUTE);
			} else {
				*optlen = 0;
				errno = EINVAL;
			}
			break;
		case SO_REUSEADDR:
			if (*optlen == sizeof (int)) {
				*(int *)optval =
				    (sockets[i].so_opt & SO_REUSEADDR);
			} else {
				*optlen = 0;
				errno = EINVAL;
			}
			break;
		case SO_RCVBUF:
			if (*optlen == sizeof (int)) {
				*(int *)optval = sockets[i].so_rcvbuf;
			} else {
				*optlen = 0;
				errno = EINVAL;
			}
			break;
		case SO_SNDBUF:
			if (*optlen == sizeof (int)) {
				*(int *)optval = sockets[i].so_sndbuf;
			} else {
				*optlen = 0;
				errno = EINVAL;
			}
			break;
		case SO_LINGER:
			if (*optlen == sizeof (struct linger)) {
				/* struct copy */
				*(struct linger *)optval = sockets[i].so_linger;
			} else {
				*optlen = 0;
				errno = EINVAL;
			}
			break;
		default:
			errno = ENOPROTOOPT;
			break;
		}
		break;
	} /* case SOL_SOCKET */
	case IPPROTO_TCP:
	case IPPROTO_IP: {
		switch (option) {
		default:
			*optlen = 0;
			errno = ENOPROTOOPT;
			break;
		}
		break;
	} /* case IPPROTO_IP or IPPROTO_TCP */
	default:
		errno = ENOPROTOOPT;
		break;
	} /* switch (level) */

	if (errno != 0)
		return (-1);
	else
		return (0);
}

/*
 * Generate a network-order source port from the privileged range if
 * "reserved" is true, dynamic/private range otherwise. We consider the
 * range of 512-1023 privileged ports as ports we can use. This mirrors
 * historical rpc client practice for privileged port selection.
 */
in_port_t
get_source_port(boolean_t reserved)
{
	static in_port_t	dynamic = IPPORT_DYNAMIC_START - 1,
	    rsvdport = (IPPORT_RESERVED / 2) - 1;
	in_port_t		p;

	if (reserved) {
		if (++rsvdport >= IPPORT_RESERVED)
			p = rsvdport = IPPORT_RESERVED / 2;
		else
			p = rsvdport;
	} else
		p = ++dynamic;

	return (htons(p));
}

/*
 * The socket options we support are:
 * SO_RECVTIMEO	-	Value is uint32_t msecs.
 * SO_DONTROUTE	-	Value is int boolean (nonzero == TRUE, zero == FALSE).
 * SO_REUSEADDR -	value is int boolean.
 * SO_RCVBUF -		Value is int.
 * SO_SNDBUF -		Value is int.
 */
int
setsockopt(int s, int level, int option, const void *optval, socklen_t optlen)
{
	int i;

	errno = 0;
	if ((i = so_check_fd(s, &errno)) == -1)
		return (-1);

	switch (level) {
	case SOL_SOCKET: {
		switch (option) {
		case SO_RCVTIMEO:
			if (optlen == sizeof (uint32_t))
				sockets[i].in_timeout = *(uint32_t *)optval;
			else {
				errno = EINVAL;
			}
			break;
		case SO_DONTROUTE:
			if (optlen == sizeof (int)) {
				if (*(int *)optval)
					sockets[i].out_flags |= SO_DONTROUTE;
				else
					sockets[i].out_flags &= ~SO_DONTROUTE;
			} else {
				errno = EINVAL;
			}
			break;
		case SO_REUSEADDR:
			if (optlen == sizeof (int)) {
				if (*(int *)optval)
					sockets[i].so_opt |= SO_REUSEADDR;
				else
					sockets[i].so_opt &= ~SO_REUSEADDR;
			} else {
				errno = EINVAL;
			}
			break;
		case SO_RCVBUF:
			if (optlen == sizeof (int)) {
				sockets[i].so_rcvbuf = *(int *)optval;
				if (sockets[i].so_rcvbuf > SO_MAX_BUF)
					sockets[i].so_rcvbuf = SO_MAX_BUF;
				(void) tcp_opt_set(sockets[i].pcb,
				    level, option, optval, optlen);
			} else {
				errno = EINVAL;
			}
			break;
		case SO_SNDBUF:
			if (optlen == sizeof (int)) {
				sockets[i].so_sndbuf = *(int *)optval;
				if (sockets[i].so_sndbuf > SO_MAX_BUF)
					sockets[i].so_sndbuf = SO_MAX_BUF;
				(void) tcp_opt_set(sockets[i].pcb,
				    level, option, optval, optlen);
			} else {
				errno = EINVAL;
			}
			break;
		case SO_LINGER:
			if (optlen == sizeof (struct linger)) {
				/* struct copy */
				sockets[i].so_linger = *(struct linger *)optval;
				(void) tcp_opt_set(sockets[i].pcb,
				    level, option, optval, optlen);
			} else {
				errno = EINVAL;
			}
			break;
		default:
			errno = ENOPROTOOPT;
			break;
		}
		break;
	} /* case SOL_SOCKET */
	case IPPROTO_TCP:
	case IPPROTO_IP: {
		switch (option) {
		default:
			errno = ENOPROTOOPT;
			break;
		}
		break;
	} /* case IPPROTO_IP  or IPPROTO_TCP */
	default:
		errno = ENOPROTOOPT;
		break;
	} /* switch (level) */

	if (errno != 0)
		return (-1);
	else
		return (0);
}

/*
 * Shut down part of a full-duplex connection.
 *
 * Only supported for TCP sockets
 */
int
shutdown(int s, int how)
{
	int sock_id;
	int i;

	errno = 0;
	if ((sock_id = so_check_fd(s, &errno)) == -1)
		return (-1);

	/* shutdown only supported for TCP sockets */
	if (sockets[sock_id].type != INETBOOT_STREAM) {
		errno = EOPNOTSUPP;
		return (-1);
	}

	if (!(sockets[sock_id].so_state & SS_ISCONNECTED)) {
		errno = ENOTCONN;
		return (-1);
	}

	switch (how) {
	case 0:
		sockets[sock_id].so_state |= SS_CANTRCVMORE;
		break;
	case 1:
		sockets[sock_id].so_state |= SS_CANTSENDMORE;
		break;
	case 2:
		sockets[sock_id].so_state |= (SS_CANTRCVMORE | SS_CANTSENDMORE);
		break;
	default:
		errno = EINVAL;
		return (-1);
	}

	switch (sockets[sock_id].so_state &
	    (SS_CANTRCVMORE | SS_CANTSENDMORE)) {
	case (SS_CANTRCVMORE | SS_CANTSENDMORE):
		/* Call lower level protocol close routine. */
		for (i = TRANSPORT_LVL; i >= MEDIA_LVL; i--) {
			if (sockets[sock_id].close[i] != NULL) {
				(void) sockets[sock_id].close[i](sock_id);
			}
		}
		nuke_grams(&sockets[sock_id].inq);
		break;
	case SS_CANTRCVMORE:
		nuke_grams(&sockets[sock_id].inq);
		break;
	case SS_CANTSENDMORE:
		/* Call lower level protocol close routine. */
		if (tcp_shutdown(sock_id) < 0)
			return (-1);
		break;
	default:
		errno = EINVAL;
		return (-1);
	}

	return (0);
}

/*
 * "close" a socket.
 */
int
socket_close(int s)
{
	int sock_id, i;

	errno = 0;
	if ((sock_id = so_check_fd(s, &errno)) == -1)
		return (-1);

	/* Call lower level protocol close routine. */
	for (i = TRANSPORT_LVL; i >= MEDIA_LVL; i--) {
		if (sockets[sock_id].close[i] != NULL) {
			/*
			 * Note that the close() routine of other
			 * layers can return an error.  But right
			 * now, the only mechanism to report that
			 * back is for the close() routine to set
			 * the errno and socket_close() will return
			 * an error.  But the close operation will
			 * not be stopped.
			 */
			(void) sockets[sock_id].close[i](sock_id);
		}
	}

	/*
	 * Clear the input queue.  This has to be done
	 * after the lower level protocol close routines have been
	 * called as they may want to do something about the queue.
	 */
	nuke_grams(&sockets[sock_id].inq);

	bzero((caddr_t)&sockets[sock_id], sizeof (struct inetboot_socket));
	sockets[sock_id].type = INETBOOT_UNUSED;

	return (0);
}

/*
 * Read up to `nbyte' of data from socket `s' into `buf'; if non-zero,
 * then give up after `read_timeout' seconds.  Returns the number of
 * bytes read, or -1 on failure.
 */
int
socket_read(int s, void *buf, size_t nbyte, int read_timeout)
{
	ssize_t	n;
	uint_t	start, diff;

	/*
	 * keep calling non-blocking recvfrom until something received
	 * or an error occurs
	 */
	start = prom_gettime();
	for (;;) {
		n = recvfrom(s, buf, nbyte, MSG_DONTWAIT, NULL, NULL);
		if (n == -1 && errno == EWOULDBLOCK) {
			diff = (uint_t)((prom_gettime() - start) + 500) / 1000;
			if (read_timeout != 0 && diff > read_timeout) {
				errno = EINTR;
				return (-1);
			}
		} else {
			return (n);
		}
	}
}

/*
 * Write up to `nbyte' bytes of data from `buf' to the address pointed to
 * `addr' using socket `s'.  Returns the number of bytes writte on success,
 * or -1 on failure.
 */
int
socket_write(int s, const void *buf, size_t nbyte, struct sockaddr_in *addr)
{
	return (sendto(s, buf, nbyte, 0, (struct sockaddr *)addr,
	    sizeof (*addr)));
}

static int
bind_check(int sock_id, const struct sockaddr *addr)
{
	int k;
	struct sockaddr_in *in_addr = (struct sockaddr_in *)addr;

	/* Do not check for duplicate bind() if SO_REUSEADDR option is set. */
	if (! (sockets[sock_id].so_opt & SO_REUSEADDR)) {
		for (k = 0; k < MAXSOCKET; k++) {
			if (sockets[k].type != INETBOOT_UNUSED &&
			    sockets[k].proto == sockets[sock_id].proto &&
			    sockets[k].bound) {
				if ((sockets[k].bind.sin_addr.s_addr ==
				    in_addr->sin_addr.s_addr) &&
				    (sockets[k].bind.sin_port ==
				    in_addr->sin_port)) {
					errno = EADDRINUSE;
					return (-1);
				}
			}
		}
	}
	return (0);
}

/* Assign a name to an unnamed socket. */
int
bind(int s, const struct sockaddr *name, socklen_t namelen)
{
	int i;

	errno = 0;

	if ((i = so_check_fd(s, &errno)) == -1)
		return (-1);

	if (name == NULL) {
		/* unbind */
		if (sockets[i].bound) {
			bzero((caddr_t)&sockets[i].bind,
			    sizeof (struct sockaddr_in));
			sockets[i].bound = B_FALSE;
		}
		return (0);
	}
	if (namelen != sizeof (struct sockaddr_in) || name == NULL) {
		errno = EINVAL;
		return (-1);
	}
	if (name->sa_family != AF_INET) {
		errno = EAFNOSUPPORT;
		return (-1);
	}
	if (sockets[i].bound) {
		if (bcmp((caddr_t)&sockets[i].bind, (caddr_t)name,
		    namelen) == 0) {
			/* attempt to bind to same address ok... */
			return (0);
		}
		errno = EINVAL;	/* already bound */
		return (-1);
	}

	if (errno != 0) {
		return (-1);
	}

	/* Check for duplicate bind(). */
	if (bind_check(i, name) < 0)
		return (-1);

	bcopy((caddr_t)name, (caddr_t)&sockets[i].bind, namelen);
	if (sockets[i].type == INETBOOT_STREAM) {
		if (tcp_bind(i) < 0) {
			return (-1);
		}
	}
	sockets[i].bound = B_TRUE;

	return (0);
}

static int
quickbind(int sock_id)
{
	int i;
	struct sockaddr_in addr;

	/*
	 * XXX This needs more work.  Right now, if ipv4_setipaddr()
	 * have not been called, this will be wrong.  But we need
	 * something better.  Need to be revisited.
	 */
	ipv4_getipaddr(&addr.sin_addr);
	addr.sin_family = AF_INET;

	for (i = SMALLEST_ANON_PORT; i <= LARGEST_ANON_PORT; i++) {
		addr.sin_port = htons(i);
		if (bind_check(sock_id, (struct sockaddr *)&addr) == 0)
			break;
	}
	/* Need to clear errno as it is probably set by bind_check(). */
	errno = 0;

	if (i <= LARGEST_ANON_PORT) {
		bcopy((caddr_t)&addr, (caddr_t)&sockets[sock_id].bind,
		    sizeof (struct sockaddr_in));
		sockets[sock_id].bound = B_TRUE;
#ifdef DEBUG
		printf("quick bind done addr %s port %d\n",
		    inet_ntoa(sockets[sock_id].bind.sin_addr),
		    ntohs(sockets[sock_id].bind.sin_port));
#endif
		return (0);
	} else {
		return (-1);
	}
}

int
listen(int fd, int backlog)
{
	int sock_id;

	errno = 0;
	if ((sock_id = so_check_fd(fd, &errno)) == -1)
		return (-1);

	if (sockets[sock_id].type != INETBOOT_STREAM) {
		errno = EOPNOTSUPP;
		return (-1);
	}
	if (sockets[sock_id].so_error != 0) {
		errno = sockets[sock_id].so_error;
		return (-1);
	}
	return (tcp_listen(sock_id, backlog));
}

int
accept(int fd, struct sockaddr *addr,  socklen_t *addr_len)
{
	int sock_id;
	int new_sd;

	errno = 0;
	if ((sock_id = so_check_fd(fd, &errno)) == -1)
		return (-1);

	if (sockets[sock_id].type != INETBOOT_STREAM) {
		errno = EOPNOTSUPP;
		return (-1);
	}
	if (sockets[sock_id].so_error != 0) {
		errno = sockets[sock_id].so_error;
		return (-1);
	}
	if ((new_sd = tcp_accept(sock_id, addr, addr_len)) == -1)
		return (-1);
	sock_id = so_check_fd(new_sd, &errno);
	sockets[sock_id].so_state |= SS_ISCONNECTED;
	return (new_sd);
}

int
connect(int fd, const  struct sockaddr *addr, socklen_t addr_len)
{
	int sock_id;
	int so_type;

	errno = 0;
	if ((sock_id = so_check_fd(fd, &errno)) == -1)
		return (-1);

	so_type = sockets[sock_id].type;

	if (addr == NULL || addr_len == 0) {
		errno = EINVAL;
		return (-1);
	}
	/* Don't allow connect for raw socket. */
	if (so_type == INETBOOT_RAW) {
		errno = EPROTONOSUPPORT;
		return (-1);
	}

	if (sockets[sock_id].so_state & SS_ISCONNECTED) {
		errno = EINVAL;
		return (-1);
	}

	if (sockets[sock_id].so_error != 0) {
		errno = sockets[sock_id].so_error;
		return (-1);
	}

	/* If the socket is not bound, we need to do a quick bind. */
	if (!sockets[sock_id].bound) {
		/* For TCP socket, just call tcp_bind(). */
		if (so_type == INETBOOT_STREAM) {
			if (tcp_bind(sock_id) < 0)
				return (-1);
		} else {
			if (quickbind(sock_id) < 0) {
				errno = EADDRNOTAVAIL;
				return (-1);
			}
		}
	}
	/* Should do some sanity check for addr .... */
	bcopy((caddr_t)addr, &sockets[sock_id].remote,
	    sizeof (struct sockaddr_in));

	if (sockets[sock_id].type == INETBOOT_STREAM) {
		/* Call TCP connect routine. */
		if (tcp_connect(sock_id) == 0)
			sockets[sock_id].so_state |= SS_ISCONNECTED;
		else {
			if (sockets[sock_id].so_error != 0)
				errno = sockets[sock_id].so_error;
			return (-1);
		}
	} else {
		sockets[sock_id].so_state |= SS_ISCONNECTED;
	}
	return (0);
}

/* Just a wrapper around recvfrom(). */
ssize_t
recv(int s, void *buf, size_t len, int flags)
{
	return (recvfrom(s, buf, len, flags, NULL, NULL));
}

/*
 * Receive messages from a connectionless socket. Legal flags are 0 and
 * MSG_DONTWAIT. MSG_WAITALL is not currently supported.
 *
 * Returns length of message for success, -1 if error occurred.
 */
ssize_t
recvfrom(int s, void *buf, size_t len, int flags, struct sockaddr *from,
    socklen_t *fromlen)
{
	int			sock_id, i;
	ssize_t			datalen, bytes = 0;
	struct inetgram		*icp;
	enum SockType		so_type;
	char			*tmp_buf;
	mblk_t			*mp;

	errno = 0;

	if ((sock_id = so_check_fd(s, &errno)) == -1) {
		errno = EINVAL;
		return (-1);
	}

	if (sockets[sock_id].type == INETBOOT_STREAM &&
	    !(sockets[sock_id].so_state & SS_ISCONNECTED)) {
		errno = ENOTCONN;
		return (-1);
	}

	if (buf == NULL || len == 0) {
		errno = EINVAL;
		return (-1);
	}
	/* Yup - MSG_WAITALL not implemented */
	if ((flags & ~MSG_DONTWAIT) != 0) {
		errno = EINVAL;
		return (-1);
	}

retry:
	if (sockets[sock_id].inq == NULL) {
		/* Go out and check the wire */
		for (i = MEDIA_LVL; i < APP_LVL; i++) {
			if (sockets[sock_id].input[i] != NULL) {
				if (sockets[sock_id].input[i](sock_id) < 0) {
					if (sockets[sock_id].so_error != 0) {
						errno =
						    sockets[sock_id].so_error;
					}
					return (-1);
				}
			}
		}
	}

	so_type = sockets[sock_id].type;

	/* Remove unknown inetgrams from the head of inq.  Can this happen? */
	while ((icp = sockets[sock_id].inq) != NULL) {
		if ((so_type == INETBOOT_DGRAM ||
		    so_type == INETBOOT_STREAM) &&
		    icp->igm_level != APP_LVL) {
#ifdef	DEBUG
			printf("recvfrom: unexpected level %d frame found\n",
			    icp->igm_level);
#endif	/* DEBUG */
			del_gram(&sockets[sock_id].inq, icp, B_TRUE);
			continue;
		} else {
			break;
		}
	}


	if (icp == NULL) {
		/*
		 * Checking for error should be done everytime a lower layer
		 * input routing is called.  For example, if TCP gets a RST,
		 * this should be reported asap.
		 */
		if (sockets[sock_id].so_state & SS_CANTRCVMORE) {
			if (sockets[sock_id].so_error != 0) {
				errno = sockets[sock_id].so_error;
				return (-1);
			} else {
				return (0);
			}
		}

		if ((flags & MSG_DONTWAIT) == 0)
			goto retry;	/* wait forever */

		/* no data */
		errno = EWOULDBLOCK;
		return (-1);
	}

	if (from != NULL && fromlen != NULL) {
		switch (so_type) {
		case INETBOOT_STREAM:
			/* Need to copy from the socket's remote address. */
			bcopy(&(sockets[sock_id].remote), from, MIN(*fromlen,
			    sizeof (struct sockaddr_in)));
			break;
		case INETBOOT_RAW:
		case INETBOOT_DGRAM:
		default:
			if (*fromlen > sizeof (icp->igm_saddr))
				*fromlen = sizeof (icp->igm_saddr);
			bcopy((caddr_t)&(icp->igm_saddr), (caddr_t)from,
			    MIN(*fromlen, sizeof (struct sockaddr_in)));
			break;
		}
	}

	mp = icp->igm_mp;
	switch (so_type) {
	case INETBOOT_STREAM:
		/*
		 * If the message has igm_id == TCP_CALLB_MAGIC_ID, we need
		 * to drain the data held by tcp and try again.
		 */
		if (icp->igm_id == TCP_CALLB_MAGIC_ID) {
			del_gram(&sockets[sock_id].inq, icp, B_TRUE);
			tcp_rcv_drain_sock(sock_id);
			goto retry;
		}

		/* TCP should put only user data in the inetgram. */
		tmp_buf = (char *)buf;
		while (len > 0 && icp != NULL) {
			datalen = mp->b_wptr - mp->b_rptr;
			if (len < datalen) {
				bcopy(mp->b_rptr, tmp_buf, len);
				bytes += len;
				mp->b_rptr += len;
				break;
			} else {
				bcopy(mp->b_rptr, tmp_buf, datalen);
				len -= datalen;
				bytes += datalen;
				tmp_buf += datalen;
				del_gram(&sockets[sock_id].inq, icp, B_TRUE);

				/*
				 * If we have any embedded magic messages just
				 * drop them.
				 */
				while ((icp = sockets[sock_id].inq) != NULL) {
					if (icp->igm_id != TCP_CALLB_MAGIC_ID)
						break;
					del_gram(&sockets[sock_id].inq, icp,
					    B_TRUE);
				}

				if (icp == NULL)
					break;
				mp = icp->igm_mp;
			}
		}
		sockets[sock_id].so_rcvbuf += (int32_t)bytes;
		break;
	case INETBOOT_DGRAM:
		datalen = mp->b_wptr - mp->b_rptr;
		if (len < datalen)
			bytes = len;
		else
			bytes = datalen;
		bcopy(mp->b_rptr, buf, bytes);
		del_gram(&sockets[sock_id].inq, icp, B_TRUE);
		break;
	case INETBOOT_RAW:
	default:
		datalen = mp->b_wptr - mp->b_rptr;
		if (len < datalen)
			bytes = len;
		else
			bytes = datalen;
		bcopy(mp->b_rptr, buf, bytes);
		del_gram(&sockets[sock_id].inq, icp, B_TRUE);
		break;
	}

#ifdef	DEBUG
	printf("recvfrom(%d): data: (0x%x,%d)\n", sock_id,
	    (icp != NULL) ? icp->igm_mp : 0, bytes);
#endif	/* DEBUG */
	return (bytes);
}


/* Just a wrapper around sendto(). */
ssize_t
send(int s, const void *msg, size_t len, int flags)
{
	return (sendto(s, msg, len, flags, NULL, 0));
}

/*
 * Transmit a message through a socket.
 *
 * Supported flags: MSG_DONTROUTE or 0.
 */
ssize_t
sendto(int s, const void *msg, size_t len, int flags, const struct sockaddr *to,
    socklen_t tolen)
{
	enum SockType so_type;
	int sock_id;
	ssize_t bytes;

	errno = 0;

	if ((sock_id = so_check_fd(s, &errno)) == -1) {
		return (-1);
	}
	if (msg == NULL) {
		errno = EINVAL;
		return (-1);
	}
	so_type = sockets[sock_id].type;
	if ((flags & ~MSG_DONTROUTE) != 0) {
		errno = EINVAL;
		return (-1);
	}
	if (sockets[sock_id].so_error != 0) {
		errno = sockets[sock_id].so_error;
		return (-1);
	}
	if (to != NULL && to->sa_family != AF_INET) {
		errno = EAFNOSUPPORT;
		return (-1);
	}

	switch (so_type) {
	case INETBOOT_RAW:
	case INETBOOT_DGRAM:
		if (!(sockets[sock_id].so_state & SS_ISCONNECTED) &&
		    (to == NULL || tolen != sizeof (struct sockaddr_in))) {
			errno = EINVAL;
			return (-1);
		}
		bytes = dgram_sendto(sock_id, msg, len, flags, to, tolen);
		break;
	case INETBOOT_STREAM:
		if (!((sockets[sock_id].so_state & SS_ISCONNECTED) ||
		    (sockets[sock_id].so_state & SS_ISCONNECTING))) {
			errno = EINVAL;
			return (-1);
		}
		if (sockets[sock_id].so_state & SS_CANTSENDMORE) {
			errno = EPIPE;
			return (-1);
		}
		bytes = stream_sendto(sock_id, msg, len, flags);
		break;
	default:
		/* Should not happen... */
		errno = EPROTOTYPE;
		return (-1);
	}
	return (bytes);
}

static ssize_t
dgram_sendto(int i, const void *msg, size_t len, int flags,
    const struct sockaddr *to, int tolen)
{
	struct inetgram		oc;
	int			l, offset;
	size_t			tlen;
	mblk_t			*mp;

#ifdef	DEBUG
	{
	struct sockaddr_in *sin = (struct sockaddr_in *)to;
	printf("sendto(%d): msg of length: %d sent to port %d and host: %s\n",
	    i, len, ntohs(sin->sin_port), inet_ntoa(sin->sin_addr));
	}
#endif	/* DEBUG */

	nuke_grams(&sockets[i].inq); /* flush the input queue */

	/* calculate offset for data */
	offset = sockets[i].headerlen[MEDIA_LVL](NULL) +
	    (sockets[i].headerlen[NETWORK_LVL])(NULL);

	bzero((caddr_t)&oc, sizeof (oc));
	if (sockets[i].type != INETBOOT_RAW) {
		offset += (sockets[i].headerlen[TRANSPORT_LVL])(NULL);
		oc.igm_level = TRANSPORT_LVL;
	} else
		oc.igm_level = NETWORK_LVL;
	oc.igm_oflags = flags;

	if (to != NULL) {
		bcopy((caddr_t)to, (caddr_t)&oc.igm_saddr, tolen);
	} else {
		bcopy((caddr_t)&sockets[i].remote, (caddr_t)&oc.igm_saddr,
		    sizeof (struct sockaddr_in));
	}

	/* Get a legal source port if the socket isn't bound. */
	if (sockets[i].bound == B_FALSE &&
	    ntohs(oc.igm_saddr.sin_port == 0)) {
		((struct sockaddr_in *)&oc.igm_saddr)->sin_port =
		    get_source_port(B_FALSE);
	}

	/* Round up to 16bit value for checksum purposes */
	if (sockets[i].type == INETBOOT_DGRAM) {
		tlen = ((len + sizeof (uint16_t) - 1) &
		    ~(sizeof (uint16_t) - 1));
	} else
		tlen = len;

	if ((oc.igm_mp = allocb(tlen + offset, 0)) == NULL) {
		errno = ENOMEM;
		return (-1);
	}
	mp = oc.igm_mp;
	mp->b_rptr = mp->b_wptr += offset;
	bcopy((caddr_t)msg, mp->b_wptr, len);
	mp->b_wptr += len;
	for (l = TRANSPORT_LVL; l >= MEDIA_LVL; l--) {
		if (sockets[i].output[l] != NULL) {
			if (sockets[i].output[l](i, &oc) < 0) {
				freeb(mp);
				if (errno == 0)
					errno = EIO;
				return (-1);
			}
		}
	}
	freeb(mp);
	return (len);
}

/* ARGSUSED */
static ssize_t
stream_sendto(int i, const void *msg, size_t len, int flags)
{
	int cnt;

	assert(sockets[i].pcb != NULL);

	/*
	 * Call directly TCP's send routine.  We do this because TCP
	 * needs to decide whether to send out the data.
	 *
	 * Note also that currently, TCP ignores all flags passed in for
	 * TCP socket.
	 */
	if ((cnt = tcp_send(i, sockets[i].pcb, msg, len)) < 0) {
		if (sockets[i].so_error != 0)
			errno = sockets[i].so_error;
		return (-1);
	} else {
		return (cnt);
	}
}

/*
 * Returns ptr to the last inetgram in the list, or null if list is null
 */
struct inetgram *
last_gram(struct inetgram *igp)
{
	struct inetgram	*wp;
	for (wp = igp; wp != NULL; wp = wp->igm_next) {
		if (wp->igm_next == NULL)
			return (wp);
	}
	return (NULL);
}

/*
 * Adds an inetgram or list of inetgrams to the end of the list.
 */
void
add_grams(struct inetgram **igpp, struct inetgram *newgp)
{
	struct inetgram	 *wp;

	if (newgp == NULL)
		return;

	if (*igpp == NULL)
		*igpp = newgp;
	else {
		wp = last_gram(*igpp);
		wp->igm_next = newgp;
	}
}

/*
 * Nuke a whole list of grams.
 */
void
nuke_grams(struct inetgram **lgpp)
{
	while (*lgpp != NULL)
		del_gram(lgpp, *lgpp, B_TRUE);
}

/*
 * Remove the referenced inetgram. List is altered accordingly. Destroy the
 * referenced inetgram if freeit is B_TRUE.
 */
void
del_gram(struct inetgram **lgpp, struct inetgram *igp, int freeit)
{
	struct inetgram	*wp, *pp = NULL;

	if (lgpp == NULL || igp == NULL)
		return;

	wp = *lgpp;
	while (wp != NULL) {
		if (wp == igp) {
			/* detach wp from the list */
			if (*lgpp == wp)
				*lgpp = (*lgpp)->igm_next;
			else
				pp->igm_next = wp->igm_next;
			igp->igm_next = NULL;

			if (freeit) {
				if (igp->igm_mp != NULL)
					freeb(igp->igm_mp);
				bkmem_free((caddr_t)igp,
				    sizeof (struct inetgram));
			}
			break;
		}
		pp = wp;
		wp = wp->igm_next;
	}
}

struct nct_t nct[] = {
	"bootp",	NCT_BOOTP_DHCP,
	"dhcp",		NCT_BOOTP_DHCP,
	"rarp",		NCT_RARP_BOOTPARAMS,
	"manual",	NCT_MANUAL
};
int	nct_entries = sizeof (nct) / sizeof (nct[0]);

/*
 * Figure out from the bootpath what kind of network configuration strategy
 * we should use. Returns the network config strategy.
 */
int
get_netconfig_strategy(void)
{
	int	i;
#define	ISSPACE(c) (c == ' ' || c == '\t' || c == '\n' || c == '\0')
	char	lbootpath[OBP_MAXPATHLEN];
	char	net_options[NCT_BUFSIZE];
	char	*op, *nop, *sp;
	pnode_t	cn;
	int	proplen;

	/* If the PROM DHCP cache exists, we're done */
	if (prom_cached_reply(B_TRUE))
		return (NCT_BOOTP_DHCP);

	/*
	 *	Newer (version 4) PROMs will put the name in the
	 *	"net-config-strategy" property.
	 */
	cn = prom_finddevice("/chosen");
	if ((proplen = prom_getproplen(cn, "net-config-strategy")) <
	    sizeof (net_options)) {
		(void) prom_getprop(cn, "net-config-strategy", net_options);
		net_options[proplen] = '\0';
	} else {

		/*
		 * We're reduced to sacanning bootpath for the prototol to use.
		 * Since there was no "net-config-strategy" property, this is
		 * an old PROM, so we need to excise any extraneous key/value
		 * initializations from bootpath[].
		 */
		for (op = prom_bootpath(), sp = lbootpath; op != NULL &&
		    !ISSPACE(*op); sp++, op++)
			*sp = *op;
		*sp = '\0';
		/* find the last '/' (in the device path) */
		if ((op = strrchr(lbootpath, '/')) == NULL)	/* last '/' */
			op = lbootpath;
		else
			op++;
		/* then look for the ':' separating it from the protocol */
		while (*op != ':' && *op != '\0')
			op++;

		if (*op == ':') {
			for (nop = net_options, op++;
			    *op != '\0' && *op != '/' && !ISSPACE(*op) &&
			    nop < &net_options[NCT_BUFSIZE]; nop++, op++)
				*nop = *op;
			*nop = '\0';
		} else
			net_options[0] = '\0';
	}

#undef	ISSPACE

	for (i = 0; i < nct_entries; i++)
		if (strcmp(net_options, nct[i].p_name) == 0)
			return (nct[i].p_id);

	return (NCT_DEFAULT);
}

/* Modified STREAM routines for ease of porting core TCP code. */

/*ARGSUSED*/
mblk_t *
allocb(size_t size, uint_t pri)
{
	unsigned char *base;
	mblk_t *mp;

	if ((mp = (mblk_t *)bkmem_zalloc(sizeof (mblk_t))) == NULL)
		return (NULL);
	if ((base = (unsigned char *)bkmem_zalloc(size)) == NULL)
		return (NULL);

	mp->b_next = mp->b_prev = mp->b_cont = NULL;
	mp->b_rptr = mp->b_wptr = mp->b_datap = (unsigned char *)base;
	mp->b_size = size;

	return (mp);
}

void
freeb(mblk_t *mp)
{
#ifdef DEBUG
	printf("freeb datap %x\n", mp->b_datap);
#endif
	bkmem_free((caddr_t)(mp->b_datap), mp->b_size);
#ifdef DEBUG
	printf("freeb mp %x\n", mp);
#endif
	bkmem_free((caddr_t)mp, sizeof (mblk_t));
}

void
freemsg(mblk_t *mp)
{
	while (mp) {
		mblk_t *mp_cont = mp->b_cont;

		freeb(mp);
		mp = mp_cont;
	}
}

mblk_t *
copyb(mblk_t *bp)
{
	mblk_t *nbp;
	unsigned char *ndp;

	assert((uintptr_t)(bp->b_wptr - bp->b_rptr) >= 0);

	if (!(nbp = allocb(bp->b_size, 0)))
		return (NULL);
	nbp->b_cont = NULL;
	ndp = nbp->b_datap;

	nbp->b_rptr = ndp + (bp->b_rptr - bp->b_datap);
	nbp->b_wptr = nbp->b_rptr + (bp->b_wptr - bp->b_rptr);
	bcopy(bp->b_datap, nbp->b_datap, bp->b_size);
	return (nbp);
}

/* To simplify things, dupb() is implemented as copyb(). */
mblk_t *
dupb(mblk_t *mp)
{
	return (copyb(mp));
}

/*
 * get number of data bytes in message
 */
size_t
msgdsize(mblk_t *bp)
{
	size_t count = 0;

	for (; bp != NULL; bp = bp->b_cont) {
		assert(bp->b_wptr >= bp->b_rptr);
		count += bp->b_wptr - bp->b_rptr;
	}
	return (count);
}
/*
 * 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 2002-2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 *
 * Internal socket-specific definitions
 */

#ifndef _SOCKET_IMPL_H
#define	_SOCKET_IMPL_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#ifdef	__cplusplus
extern "C" {
#endif

#include <sys/types.h>
#include <sys/socket.h>

/*
 * Socket support definitions
 */

#define	MAXSOCKET	(10)
#define	SOCKETTYPE	(65536)
#define	MEDIA_LVL	0
#define	NETWORK_LVL	1
#define	TRANSPORT_LVL	2
#define	APP_LVL		3

/* Anonymous ports assigned by socket. */
#define	SMALLEST_ANON_PORT	32768
#define	LARGEST_ANON_PORT	((64 * 1024) - 1)

/* Socket state bits. */
#define	SS_ISCONNECTED		0x000001 /* socket connected to a peer */
#define	SS_ISCONNECTING		0x000002 /* in process of connecting to peer */

#define	SS_CANTRCVMORE		0x000010 /* can't receive more data from peer */
#define	SS_CANTSENDMORE		0x000008 /* can't send more data to peer */

enum { FALSE, TRUE };
enum SockType { INETBOOT_UNUSED, INETBOOT_DGRAM, INETBOOT_RAW,
    INETBOOT_STREAM };
enum Ports { SOURCE, DESTINATION };
#define	FD_TO_SOCKET(v)	((v) - SOCKETTYPE)

/*
 * Message block descriptor copied from usr/src/uts/common/sys/stream.h.
 * We need to do that to simplify the porting of TCP code from core
 * kernel to inetboot.  Note that fields which are not used by TCP
 * code are removed.
 */
typedef struct  msgb {
	struct  msgb	*b_next;
	struct  msgb	*b_prev;
	struct  msgb	*b_cont;
	unsigned char	*b_rptr;
	unsigned char	*b_wptr;
	unsigned char	*b_datap;
	size_t		b_size;
} mblk_t;

/* Modified stream routines to ease TCP porting. */
extern mblk_t *allocb(size_t, uint_t);
extern mblk_t *dupb(mblk_t *);
extern void freeb(mblk_t *);
extern void freemsg(mblk_t *);
extern size_t msgdsize(mblk_t *);

/*
 * "target" is needed for input prior to IP address assignment. It may
 * seem redundant given the binding information contained in the socket,
 * but that's only true if we have an IP address. If we don't, and we
 * try DHCP, we'll try to udp checksum using INADDR_ANY as the destination
 * IP address, when in fact the destination IP address was the IP address
 * we were OFFERED/Assigned.
 */
struct inetgram {
	/* Common */
	struct sockaddr_in	igm_saddr;	/* source address info */
	int			igm_level;	/* Stack level (LVL) of data */
	mblk_t			*igm_mp;
	struct inetgram		*igm_next;	/* next inetgram in list */
	union {
		struct {
			/* Input specific */
			struct in_addr	in_t;
			uint16_t	in_i;
		} _IN_un;
		struct {
			/* Output specific */
			struct in_addr	out_r;
			int		out_f;
		} _OUT_un;
	} _i_o_inet;
#define	igm_target	_i_o_inet._IN_un.in_t	/* See above comment block */
#define	igm_id		_i_o_inet._IN_un.in_i	/* IP id */
#define	igm_router	_i_o_inet._OUT_un.out_r	/* first router IP  ... */
#define	igm_oflags	_i_o_inet._OUT_un.out_f	/* flag: 0 or MSG_DONTROUTE */
};

struct inetboot_socket {
	enum SockType		type;		/* socket type */
	uint8_t			proto;		/* ip protocol */
	int			out_flags;	/* 0 or MSG_DONTROUTE */
	boolean_t		bound;		/* boolean */
	uint32_t		so_state;	/* Socket state */
	int			so_error;	/* Socket error */
	struct sockaddr_in	bind;		/* Binding info */
	struct sockaddr_in	remote;		/* Remote address */
	struct inetgram		*inq;		/* input queue */
	int			so_sndbuf;	/* max send buf size */
	int			so_rcvbuf;	/* max receive buf size */
	struct linger		so_linger;	/* close linger time */
	uint32_t		in_timeout;	/* Input timeout (msec) */
	uint32_t		so_opt;		/* socket level option */
	int			(*headerlen[APP_LVL])(struct inetgram *);
	int			(*input[APP_LVL])(int);
	int			(*output[APP_LVL])(int, struct inetgram *);
	int			(*close[APP_LVL])(int);
	in_port_t		(*ports)(uint16_t *, enum Ports);
	void			*pcb;		/* Protocol control block */
};

extern struct inetboot_socket	sockets[MAXSOCKET];

extern void add_grams(struct inetgram **, struct inetgram *);
extern void del_gram(struct inetgram **, struct inetgram *, int);
extern void nuke_grams(struct inetgram **);
extern struct inetgram *last_gram(struct inetgram *);

extern int so_check_fd(int, int *);

#ifdef	__cplusplus
}
#endif

#endif /* _SOCKET_IMPL_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 2004 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 *
 * Socket-specific definitions
 */

#ifndef _SOCKET_INET_H
#define	_SOCKET_INET_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#include <sys/types.h>
#include <sys/socket.h>

#ifdef	__cplusplus
extern "C" {
#endif

/* Network configuration protocol definitions */
enum nc_type { NCT_BOOTP_DHCP, NCT_RARP_BOOTPARAMS, NCT_MANUAL };
struct nct_t {
	char		*p_name;
	enum nc_type	p_id;
};
#define	NCT_DEFAULT		NCT_RARP_BOOTPARAMS
#define	NCT_BUFSIZE		(64)
extern struct nct_t	nct[];
extern int		nct_entries;

/*
 * Dynamic/private ports can be allocated in the range of 49152-65535.
 * Source: IANA (www.iana.org) port numbers.
 */
#define	IPPORT_DYNAMIC_START	49152

extern int dontroute;

extern int socket_read(int, void *, size_t, int);
extern int socket_write(int, const void *, size_t, struct sockaddr_in *);
extern int socket_close(int);

extern int get_netconfig_strategy(void);
extern in_port_t get_source_port(boolean_t);

#ifdef	__cplusplus
}
#endif

#endif /* _SOCKET_INET_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 2003 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

LIBRARY = libtcp.a
OBJECTS = tcp.o tcp_sack.o

include ../Makefile.com

CMNDIR  = $(CMNNETDIR)/dhcp
LDLIBS += -linet
CPPFLAGS += -I../inet $(SOCKCPPFLAGS)

CERRWARN += -Wno-unused-label
CERRWARN += $(CNOWARN_UNINIT)

# tcp.c is too hairy.
SMATCH=off

include ../Makefile.targ
Copyright (c) 1982, 1986 Regents of the University of California.  
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

    1. Redistributions of source code must retain the above copyright
       notice, this list of conditions and the following disclaimer.
    2. Redistributions in binary form must reproduce the above
       copyright notice, this list of conditions and the following
       disclaimer in the documentation and/or other materials provided
       with the distribution.
    3. All advertising materials mentioning features or use of this
       software must display the following acknowledgement:
           This product includes software developed by the University
           of California, Berkeley and its contributors.
    4. Neither the name of the University nor the names of its
       contributors may be used to endorse or promote products derived
       from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
PORTIONS OF STANDALONE TCP FUNCTIONALITY
/*
 * 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 2006 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 * Copyright (c) 2016 by Delphix. All rights reserved.
 *
 * tcp.c, Code implementing the TCP protocol.
 */

#include <sys/types.h>
#include <socket_impl.h>
#include <socket_inet.h>
#include <sys/sysmacros.h>
#include <sys/promif.h>
#include <sys/socket.h>
#include <netinet/in_systm.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <net/if_types.h>
#include <sys/salib.h>

#include "ipv4.h"
#include "ipv4_impl.h"
#include "mac.h"
#include "mac_impl.h"
#include "v4_sum_impl.h"
#include <sys/bootdebug.h>
#include "tcp_inet.h"
#include "tcp_sack.h"
#include <inet/common.h>
#include <inet/mib2.h>

/*
 * We need to redefine BUMP_MIB/UPDATE_MIB to not have DTrace probes.
 */
#undef BUMP_MIB
#define	BUMP_MIB(x) (x)++

#undef UPDATE_MIB
#define	UPDATE_MIB(x, y) x += y

/*
 * MIB-2 stuff for SNMP
 */
mib2_tcp_t	tcp_mib;	/* SNMP fixed size info */

/* The TCP mib does not include the following errors. */
static uint_t tcp_cksum_errors;
static uint_t tcp_drops;

/* Macros for timestamp comparisons */
#define	TSTMP_GEQ(a, b)	((int32_t)((a)-(b)) >= 0)
#define	TSTMP_LT(a, b)	((int32_t)((a)-(b)) < 0)

/*
 * Parameters for TCP Initial Send Sequence number (ISS) generation.
 * The ISS is calculated by adding three components: a time component
 * which grows by 1 every 4096 nanoseconds (versus every 4 microseconds
 * suggested by RFC 793, page 27);
 * a per-connection component which grows by 125000 for every new connection;
 * and an "extra" component that grows by a random amount centered
 * approximately on 64000.  This causes the the ISS generator to cycle every
 * 4.89 hours if no TCP connections are made, and faster if connections are
 * made.
 */
#define	ISS_INCR	250000
#define	ISS_NSEC_SHT	0

static uint32_t tcp_iss_incr_extra;	/* Incremented for each connection */

#define	TCP_XMIT_LOWATER	4096
#define	TCP_XMIT_HIWATER	49152
#define	TCP_RECV_LOWATER	2048
#define	TCP_RECV_HIWATER	49152

/*
 *  PAWS needs a timer for 24 days.  This is the number of ms in 24 days
 */
#define	PAWS_TIMEOUT	((uint32_t)(24*24*60*60*1000))

/*
 * TCP options struct returned from tcp_parse_options.
 */
typedef struct tcp_opt_s {
	uint32_t	tcp_opt_mss;
	uint32_t	tcp_opt_wscale;
	uint32_t	tcp_opt_ts_val;
	uint32_t	tcp_opt_ts_ecr;
	tcp_t		*tcp;
} tcp_opt_t;

/*
 * RFC1323-recommended phrasing of TSTAMP option, for easier parsing
 */

#ifdef _BIG_ENDIAN
#define	TCPOPT_NOP_NOP_TSTAMP ((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | \
	(TCPOPT_TSTAMP << 8) | 10)
#else
#define	TCPOPT_NOP_NOP_TSTAMP ((10 << 24) | (TCPOPT_TSTAMP << 16) | \
	(TCPOPT_NOP << 8) | TCPOPT_NOP)
#endif

/*
 * Flags returned from tcp_parse_options.
 */
#define	TCP_OPT_MSS_PRESENT	1
#define	TCP_OPT_WSCALE_PRESENT	2
#define	TCP_OPT_TSTAMP_PRESENT	4
#define	TCP_OPT_SACK_OK_PRESENT	8
#define	TCP_OPT_SACK_PRESENT	16

/* TCP option length */
#define	TCPOPT_NOP_LEN		1
#define	TCPOPT_MAXSEG_LEN	4
#define	TCPOPT_WS_LEN		3
#define	TCPOPT_REAL_WS_LEN	(TCPOPT_WS_LEN+1)
#define	TCPOPT_TSTAMP_LEN	10
#define	TCPOPT_REAL_TS_LEN	(TCPOPT_TSTAMP_LEN+2)
#define	TCPOPT_SACK_OK_LEN	2
#define	TCPOPT_REAL_SACK_OK_LEN	(TCPOPT_SACK_OK_LEN+2)
#define	TCPOPT_REAL_SACK_LEN	4
#define	TCPOPT_MAX_SACK_LEN	36
#define	TCPOPT_HEADER_LEN	2

/* TCP cwnd burst factor. */
#define	TCP_CWND_INFINITE	65535
#define	TCP_CWND_SS		3
#define	TCP_CWND_NORMAL		5

/* Named Dispatch Parameter Management Structure */
typedef struct tcpparam_s {
	uint32_t	tcp_param_min;
	uint32_t	tcp_param_max;
	uint32_t	tcp_param_val;
	char		*tcp_param_name;
} tcpparam_t;

/* Max size IP datagram is 64k - 1 */
#define	TCP_MSS_MAX_IPV4 (IP_MAXPACKET - (sizeof (struct ip) + \
	sizeof (tcph_t)))

/* Max of the above */
#define	TCP_MSS_MAX	TCP_MSS_MAX_IPV4

/* Largest TCP port number */
#define	TCP_MAX_PORT	(64 * 1024 - 1)

/* Round up the value to the nearest mss. */
#define	MSS_ROUNDUP(value, mss)		((((value) - 1) / (mss) + 1) * (mss))

#define	MS	1L
#define	SECONDS	(1000 * MS)
#define	MINUTES	(60 * SECONDS)
#define	HOURS	(60 * MINUTES)
#define	DAYS	(24 * HOURS)

/* All NDD params in the core TCP became static variables. */
static int	tcp_time_wait_interval = 1 * MINUTES;
static int	tcp_conn_req_max_q = 128;
static int	tcp_conn_req_max_q0 = 1024;
static int	tcp_conn_req_min = 1;
static int	tcp_conn_grace_period = 0 * SECONDS;
static int	tcp_cwnd_max_ = 1024 * 1024;
static int	tcp_smallest_nonpriv_port = 1024;
static int	tcp_ip_abort_cinterval = 3 * MINUTES;
static int	tcp_ip_abort_linterval = 3 * MINUTES;
static int	tcp_ip_abort_interval = 8 * MINUTES;
static int	tcp_ip_notify_cinterval = 10 * SECONDS;
static int	tcp_ip_notify_interval = 10 * SECONDS;
static int	tcp_ipv4_ttl = 64;
static int	tcp_mss_def_ipv4 = 536;
static int	tcp_mss_max_ipv4 = TCP_MSS_MAX_IPV4;
static int	tcp_mss_min = 108;
static int	tcp_naglim_def = (4*1024)-1;
static int	tcp_rexmit_interval_initial = 3 * SECONDS;
static int	tcp_rexmit_interval_max = 60 * SECONDS;
static int	tcp_rexmit_interval_min = 400 * MS;
static int	tcp_dupack_fast_retransmit = 3;
static int	tcp_smallest_anon_port = 32 * 1024;
static int	tcp_largest_anon_port = TCP_MAX_PORT;
static int	tcp_xmit_lowat = TCP_XMIT_LOWATER;
static int	tcp_recv_hiwat_minmss = 4;
static int	tcp_fin_wait_2_flush_interval = 1 * MINUTES;
static int	tcp_max_buf = 1024 * 1024;
static int	tcp_wscale_always = 1;
static int	tcp_tstamp_always = 1;
static int	tcp_tstamp_if_wscale = 1;
static int	tcp_rexmit_interval_extra = 0;
static int	tcp_slow_start_after_idle = 2;
static int	tcp_slow_start_initial = 2;
static int	tcp_sack_permitted = 2;
static int	tcp_ecn_permitted = 2;

/* Extra room to fit in headers. */
static uint_t	tcp_wroff_xtra;

/* Hint for next port to try. */
static in_port_t	tcp_next_port_to_try = 32*1024;

/*
 * Figure out the value of window scale opton.  Note that the rwnd is
 * ASSUMED to be rounded up to the nearest MSS before the calculation.
 * We cannot find the scale value and then do a round up of tcp_rwnd
 * because the scale value may not be correct after that.
 */
#define	SET_WS_VALUE(tcp) \
{ \
	int i; \
	uint32_t rwnd = (tcp)->tcp_rwnd; \
	for (i = 0; rwnd > TCP_MAXWIN && i < TCP_MAX_WINSHIFT; \
	    i++, rwnd >>= 1) \
		; \
	(tcp)->tcp_rcv_ws = i; \
}

/*
 * Set ECN capable transport (ECT) code point in IP header.
 *
 * Note that there are 2 ECT code points '01' and '10', which are called
 * ECT(1) and ECT(0) respectively.  Here we follow the original ECT code
 * point ECT(0) for TCP as described in RFC 2481.
 */
#define	SET_ECT(tcp, iph) \
	if ((tcp)->tcp_ipversion == IPV4_VERSION) { \
		/* We need to clear the code point first. */ \
		((struct ip *)(iph))->ip_tos &= 0xFC; \
		((struct ip *)(iph))->ip_tos |= IPH_ECN_ECT0; \
	}

/*
 * The format argument to pass to tcp_display().
 * DISP_PORT_ONLY means that the returned string has only port info.
 * DISP_ADDR_AND_PORT means that the returned string also contains the
 * remote and local IP address.
 */
#define	DISP_PORT_ONLY		1
#define	DISP_ADDR_AND_PORT	2

/*
 * TCP reassembly macros.  We hide starting and ending sequence numbers in
 * b_next and b_prev of messages on the reassembly queue.  The messages are
 * chained using b_cont.  These macros are used in tcp_reass() so we don't
 * have to see the ugly casts and assignments.
 * Note. use uintptr_t to suppress the gcc warning.
 */
#define	TCP_REASS_SEQ(mp)		((uint32_t)(uintptr_t)((mp)->b_next))
#define	TCP_REASS_SET_SEQ(mp, u)	((mp)->b_next = \
					    (mblk_t *)((uintptr_t)(u)))
#define	TCP_REASS_END(mp)		((uint32_t)(uintptr_t)((mp)->b_prev))
#define	TCP_REASS_SET_END(mp, u)	((mp)->b_prev = \
					    (mblk_t *)((uintptr_t)(u)))

#define	TCP_TIMER_RESTART(tcp, intvl) \
	(tcp)->tcp_rto_timeout = prom_gettime() + intvl; \
	(tcp)->tcp_timer_running = B_TRUE;

static int tcp_accept_comm(tcp_t *, tcp_t *, mblk_t *, uint_t);
static mblk_t *tcp_ack_mp(tcp_t *);
static in_port_t tcp_bindi(in_port_t, in_addr_t *, boolean_t, boolean_t);
static uint16_t tcp_cksum(uint16_t *, uint32_t);
static void tcp_clean_death(int, tcp_t *, int err);
static tcp_t *tcp_conn_request(tcp_t *, mblk_t *mp, uint_t, uint_t);
static char *tcp_display(tcp_t *, char *, char);
static int tcp_drain_input(tcp_t *, int, int);
static void tcp_drain_needed(int, tcp_t *);
static boolean_t tcp_drop_q0(tcp_t *);
static mblk_t *tcp_get_seg_mp(tcp_t *, uint32_t, int32_t *);
static int tcp_header_len(struct inetgram *);
static in_port_t tcp_report_ports(uint16_t *, enum Ports);
static int tcp_input(int);
static void tcp_iss_init(tcp_t *);
static tcp_t *tcp_lookup_ipv4(struct ip *, tcpha_t *, int, int *);
static tcp_t *tcp_lookup_listener_ipv4(in_addr_t, in_port_t, int *);
static int tcp_conn_check(tcp_t *);
static int tcp_close(int);
static void tcp_close_detached(tcp_t *);
static void tcp_eager_cleanup(tcp_t *, boolean_t, int);
static void tcp_eager_unlink(tcp_t *);
static void tcp_free(tcp_t *);
static int tcp_header_init_ipv4(tcp_t *);
static void tcp_mss_set(tcp_t *, uint32_t);
static int tcp_parse_options(tcph_t *, tcp_opt_t *);
static boolean_t tcp_paws_check(tcp_t *, tcph_t *, tcp_opt_t *);
static void tcp_process_options(tcp_t *, tcph_t *);
static int tcp_random(void);
static void tcp_random_init(void);
static mblk_t *tcp_reass(tcp_t *, mblk_t *, uint32_t);
static void tcp_reass_elim_overlap(tcp_t *, mblk_t *);
static void tcp_rcv_drain(int sock_id, tcp_t *);
static void tcp_rcv_enqueue(tcp_t *, mblk_t *, uint_t);
static void tcp_rput_data(tcp_t *, mblk_t *, int);
static int tcp_rwnd_set(tcp_t *, uint32_t);
static int32_t tcp_sack_rxmit(tcp_t *, int);
static void tcp_set_cksum(mblk_t *);
static void tcp_set_rto(tcp_t *, int32_t);
static void tcp_ss_rexmit(tcp_t *, int);
static int tcp_state_wait(int, tcp_t *, int);
static void tcp_timer(tcp_t *, int);
static void tcp_time_wait_append(tcp_t *);
static void tcp_time_wait_collector(void);
static void tcp_time_wait_processing(tcp_t *, mblk_t *, uint32_t,
    uint32_t, int, tcph_t *, int sock_id);
static void tcp_time_wait_remove(tcp_t *);
static in_port_t tcp_update_next_port(in_port_t);
static int tcp_verify_cksum(mblk_t *);
static void tcp_wput_data(tcp_t *, mblk_t *, int);
static void tcp_xmit_ctl(char *, tcp_t *, mblk_t *, uint32_t, uint32_t,
    int, uint_t, int);
static void tcp_xmit_early_reset(char *, int, mblk_t *, uint32_t, uint32_t,
    int, uint_t);
static int tcp_xmit_end(tcp_t *, int);
static void tcp_xmit_listeners_reset(int, mblk_t *, uint_t);
static mblk_t *tcp_xmit_mp(tcp_t *, mblk_t *, int32_t, int32_t *,
    mblk_t **, uint32_t, boolean_t, uint32_t *, boolean_t);
static int tcp_init_values(tcp_t *, struct inetboot_socket *);

#if DEBUG > 1
#define	TCP_DUMP_PACKET(str, mp) \
{ \
	int len = (mp)->b_wptr - (mp)->b_rptr; \
\
	printf("%s: dump TCP(%d): \n", (str), len); \
	hexdump((char *)(mp)->b_rptr, len); \
}
#else
#define	TCP_DUMP_PACKET(str, mp)
#endif

#ifdef DEBUG
#define	DEBUG_1(str, arg)		printf(str, (arg))
#define	DEBUG_2(str, arg1, arg2)	printf(str, (arg1), (arg2))
#define	DEBUG_3(str, arg1, arg2, arg3)	printf(str, (arg1), (arg2), (arg3))
#else
#define	DEBUG_1(str, arg)
#define	DEBUG_2(str, arg1, arg2)
#define	DEBUG_3(str, arg1, arg2, arg3)
#endif

/* Whether it is the first time TCP is used. */
static boolean_t tcp_initialized = B_FALSE;

/* TCP time wait list. */
static tcp_t *tcp_time_wait_head;
static tcp_t *tcp_time_wait_tail;
static uint32_t tcp_cum_timewait;
/* When the tcp_time_wait_collector is run. */
static uint32_t tcp_time_wait_runtime;

#define	TCP_RUN_TIME_WAIT_COLLECTOR() \
	if (prom_gettime() > tcp_time_wait_runtime) \
		tcp_time_wait_collector();

/*
 * Accept will return with an error if there is no connection coming in
 * after this (in ms).
 */
static int tcp_accept_timeout = 60000;

/*
 * Initialize the TCP-specific parts of a socket.
 */
void
tcp_socket_init(struct inetboot_socket *isp)
{
	/* Do some initializations. */
	if (!tcp_initialized) {
		tcp_random_init();
		/* Extra head room for the MAC layer address. */
		if ((tcp_wroff_xtra = mac_get_hdr_len()) & 0x3) {
			tcp_wroff_xtra = (tcp_wroff_xtra & ~0x3) + 0x4;
		}
		/* Schedule the first time wait cleanup time */
		tcp_time_wait_runtime = prom_gettime() + tcp_time_wait_interval;
		tcp_initialized = B_TRUE;
	}
	TCP_RUN_TIME_WAIT_COLLECTOR();

	isp->proto = IPPROTO_TCP;
	isp->input[TRANSPORT_LVL] = tcp_input;
	/* Socket layer should call tcp_send() directly. */
	isp->output[TRANSPORT_LVL] = NULL;
	isp->close[TRANSPORT_LVL] = tcp_close;
	isp->headerlen[TRANSPORT_LVL] = tcp_header_len;
	isp->ports = tcp_report_ports;
	if ((isp->pcb = bkmem_alloc(sizeof (tcp_t))) == NULL) {
		errno = ENOBUFS;
		return;
	}
	if ((errno = tcp_init_values((tcp_t *)isp->pcb, isp)) != 0) {
		bkmem_free(isp->pcb, sizeof (tcp_t));
		return;
	}
	/*
	 * This is set last because this field is used to determine if
	 * a socket is in use or not.
	 */
	isp->type = INETBOOT_STREAM;
}

/*
 * Return the size of a TCP header including TCP option.
 */
static int
tcp_header_len(struct inetgram *igm)
{
	mblk_t *pkt;
	int ipvers;

	/* Just returns the standard TCP header without option */
	if (igm == NULL)
		return (sizeof (tcph_t));

	if ((pkt = igm->igm_mp) == NULL)
		return (0);

	ipvers = ((struct ip *)pkt->b_rptr)->ip_v;
	if (ipvers == IPV4_VERSION) {
		return (TCP_HDR_LENGTH((tcph_t *)(pkt + IPH_HDR_LENGTH(pkt))));
	} else {
		dprintf("tcp_header_len: non-IPv4 packet.\n");
		return (0);
	}
}

/*
 * Return the requested port number in network order.
 */
static in_port_t
tcp_report_ports(uint16_t *tcphp, enum Ports request)
{
	if (request == SOURCE)
		return (*(uint16_t *)(((tcph_t *)tcphp)->th_lport));
	return (*(uint16_t *)(((tcph_t *)tcphp)->th_fport));
}

/*
 * Because inetboot is not interrupt driven, TCP can only poll.  This
 * means that there can be packets stuck in the NIC buffer waiting to
 * be processed.  Thus we need to drain them before, for example, sending
 * anything because an ACK may actually be stuck there.
 *
 * The timeout arguments determine how long we should wait for draining.
 */
static int
tcp_drain_input(tcp_t *tcp, int sock_id, int timeout)
{
	struct inetgram *in_gram;
	struct inetgram *old_in_gram;
	int old_timeout;
	mblk_t *mp;
	int i;

	dprintf("tcp_drain_input(%d): %s\n", sock_id,
	    tcp_display(tcp, NULL, DISP_ADDR_AND_PORT));

	/*
	 * Since the driver uses the in_timeout value in the socket
	 * structure to determine the timeout value, we need to save
	 * the original one so that we can restore that after draining.
	 */
	old_timeout = sockets[sock_id].in_timeout;
	sockets[sock_id].in_timeout = timeout;

	/*
	 * We do this because the input queue may have some user
	 * data already.
	 */
	old_in_gram = sockets[sock_id].inq;
	sockets[sock_id].inq = NULL;

	/* Go out and check the wire */
	for (i = MEDIA_LVL; i < TRANSPORT_LVL; i++) {
		if (sockets[sock_id].input[i] != NULL) {
			if (sockets[sock_id].input[i](sock_id) < 0) {
				sockets[sock_id].in_timeout = old_timeout;
				if (sockets[sock_id].inq != NULL)
					nuke_grams(&sockets[sock_id].inq);
				sockets[sock_id].inq = old_in_gram;
				return (-1);
			}
		}
	}
#if DEBUG
	printf("tcp_drain_input: done with checking packets\n");
#endif
	while ((in_gram = sockets[sock_id].inq) != NULL) {
		/* Remove unknown inetgrams from the head of inq. */
		if (in_gram->igm_level != TRANSPORT_LVL) {
#if DEBUG
			printf("tcp_drain_input: unexpected packet "
			    "level %d frame found\n", in_gram->igm_level);
#endif
			del_gram(&sockets[sock_id].inq, in_gram, B_TRUE);
			continue;
		}
		mp = in_gram->igm_mp;
		del_gram(&sockets[sock_id].inq, in_gram, B_FALSE);
		bkmem_free((caddr_t)in_gram, sizeof (struct inetgram));
		tcp_rput_data(tcp, mp, sock_id);
		sockets[sock_id].in_timeout = old_timeout;

		/*
		 * The other side may have closed this connection or
		 * RST us.  But we need to continue to process other
		 * packets in the socket's queue because they may be
		 * belong to another TCP connections.
		 */
		if (sockets[sock_id].pcb == NULL)
			tcp = NULL;
	}

	if (tcp == NULL || sockets[sock_id].pcb == NULL) {
		if (sockets[sock_id].so_error != 0)
			return (-1);
		else
			return (0);
	}
#if DEBUG
	printf("tcp_drain_input: done with processing packets\n");
#endif
	sockets[sock_id].in_timeout = old_timeout;
	sockets[sock_id].inq = old_in_gram;

	/*
	 * Data may have been received so indicate it is available
	 */
	tcp_drain_needed(sock_id, tcp);
	return (0);
}

/*
 * The receive entry point for upper layer to call to get data.  Note
 * that this follows the current architecture that lower layer receive
 * routines have been called already.  Thus if the inq of socket is
 * not NULL, the packets must be for us.
 */
static int
tcp_input(int sock_id)
{
	struct inetgram *in_gram;
	mblk_t *mp;
	tcp_t *tcp;

	TCP_RUN_TIME_WAIT_COLLECTOR();

	if ((tcp = sockets[sock_id].pcb) == NULL)
		return (-1);

	while ((in_gram = sockets[sock_id].inq) != NULL) {
		/* Remove unknown inetgrams from the head of inq. */
		if (in_gram->igm_level != TRANSPORT_LVL) {
#ifdef DEBUG
			printf("tcp_input: unexpected packet "
			    "level %d frame found\n", in_gram->igm_level);
#endif
			del_gram(&sockets[sock_id].inq, in_gram, B_TRUE);
			continue;
		}
		mp = in_gram->igm_mp;
		del_gram(&sockets[sock_id].inq, in_gram, B_FALSE);
		bkmem_free((caddr_t)in_gram, sizeof (struct inetgram));
		tcp_rput_data(tcp, mp, sock_id);
		/* The TCP may be gone because it gets a RST. */
		if (sockets[sock_id].pcb == NULL)
			return (-1);
	}

	/* Flush the receive list. */
	if (tcp->tcp_rcv_list != NULL) {
		tcp_rcv_drain(sock_id, tcp);
	} else {
		/* The other side has closed the connection, report this up. */
		if (tcp->tcp_state == TCPS_CLOSE_WAIT) {
			sockets[sock_id].so_state |= SS_CANTRCVMORE;
			return (0);
		}
	}
	return (0);
}

/*
 * The send entry point for upper layer to call to send data.  In order
 * to minimize changes to the core TCP code, we need to put the
 * data into mblks.
 */
int
tcp_send(int sock_id, tcp_t *tcp, const void *msg, int len)
{
	mblk_t *mp;
	mblk_t *head = NULL;
	mblk_t *tail;
	int mss = tcp->tcp_mss;
	int cnt = 0;
	int win_size;
	char *buf = (char *)msg;

	TCP_RUN_TIME_WAIT_COLLECTOR();

	/* We don't want to append 0 size mblk. */
	if (len == 0)
		return (0);
	while (len > 0) {
		if (len < mss) {
			mss = len;
		}
		/*
		 * If we cannot allocate more buffer, stop here and
		 * the number of bytes buffered will be returned.
		 *
		 * Note that we follow the core TCP optimization that
		 * each mblk contains only MSS bytes data.
		 */
		if ((mp = allocb(mss + tcp->tcp_ip_hdr_len +
		    TCP_MAX_HDR_LENGTH + tcp_wroff_xtra, 0)) == NULL) {
			break;
		}
		mp->b_rptr += tcp->tcp_hdr_len + tcp_wroff_xtra;
		bcopy(buf, mp->b_rptr, mss);
		mp->b_wptr = mp->b_rptr + mss;
		buf += mss;
		cnt += mss;
		len -= mss;

		if (head == NULL) {
			head = mp;
			tail = mp;
		} else {
			tail->b_cont = mp;
			tail = mp;
		}
	}

	/*
	 * Since inetboot is not interrupt driven, there may be
	 * some ACKs in the MAC's buffer.  Drain them first,
	 * otherwise, we may not be able to send.
	 *
	 * We expect an ACK in two cases:
	 *
	 * 1) We have un-ACK'ed data.
	 *
	 * 2) All ACK's have been received and the sender's window has been
	 * closed.  We need an ACK back to open the window so that we can
	 * send.  In this case, call tcp_drain_input() if the window size is
	 * less than 2 * MSS.
	 */

	/* window size = MIN(swnd, cwnd) - unacked bytes */
	win_size = (tcp->tcp_swnd > tcp->tcp_cwnd) ? tcp->tcp_cwnd :
		tcp->tcp_swnd;
	win_size -= tcp->tcp_snxt;
	win_size += tcp->tcp_suna;
	if (win_size < (2 * tcp->tcp_mss))
		if (tcp_drain_input(tcp, sock_id, 5) < 0)
			return (-1);

	tcp_wput_data(tcp, head, sock_id);
	/*
	 * errno should be reset here as it may be
	 * set to ETIMEDOUT. This may be set by
	 * the MAC driver in case it has timed out
	 * waiting for ARP reply. Any segment which
	 * was not transmitted because of ARP timeout
	 * will be retransmitted by TCP.
	 */
	if (errno == ETIMEDOUT)
		errno = 0;
	return (cnt);
}

/* Free up all TCP related stuff */
static void
tcp_free(tcp_t *tcp)
{
	if (tcp->tcp_iphc != NULL) {
		bkmem_free((caddr_t)tcp->tcp_iphc, tcp->tcp_iphc_len);
		tcp->tcp_iphc = NULL;
	}
	if (tcp->tcp_xmit_head != NULL) {
		freemsg(tcp->tcp_xmit_head);
		tcp->tcp_xmit_head = NULL;
	}
	if (tcp->tcp_rcv_list != NULL) {
		freemsg(tcp->tcp_rcv_list);
		tcp->tcp_rcv_list = NULL;
	}
	if (tcp->tcp_reass_head != NULL) {
		freemsg(tcp->tcp_reass_head);
		tcp->tcp_reass_head = NULL;
	}
	if (tcp->tcp_sack_info != NULL) {
		bkmem_free((caddr_t)tcp->tcp_sack_info,
		    sizeof (tcp_sack_info_t));
		tcp->tcp_sack_info = NULL;
	}
}

static void
tcp_close_detached(tcp_t *tcp)
{
	if (tcp->tcp_listener != NULL)
		tcp_eager_unlink(tcp);
	tcp_free(tcp);
	bkmem_free((caddr_t)tcp, sizeof (tcp_t));
}

/*
 * If we are an eager connection hanging off a listener that hasn't
 * formally accepted the connection yet, get off its list and blow off
 * any data that we have accumulated.
 */
static void
tcp_eager_unlink(tcp_t *tcp)
{
	tcp_t	*listener = tcp->tcp_listener;

	assert(listener != NULL);
	if (tcp->tcp_eager_next_q0 != NULL) {
		assert(tcp->tcp_eager_prev_q0 != NULL);

		/* Remove the eager tcp from q0 */
		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
		    tcp->tcp_eager_prev_q0;
		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
		    tcp->tcp_eager_next_q0;
		listener->tcp_conn_req_cnt_q0--;
	} else {
		tcp_t   **tcpp = &listener->tcp_eager_next_q;
		tcp_t	*prev = NULL;

		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
			if (tcpp[0] == tcp) {
				if (listener->tcp_eager_last_q == tcp) {
					/*
					 * If we are unlinking the last
					 * element on the list, adjust
					 * tail pointer. Set tail pointer
					 * to nil when list is empty.
					 */
					assert(tcp->tcp_eager_next_q == NULL);
					if (listener->tcp_eager_last_q ==
					    listener->tcp_eager_next_q) {
						listener->tcp_eager_last_q =
						NULL;
					} else {
						/*
						 * We won't get here if there
						 * is only one eager in the
						 * list.
						 */
						assert(prev != NULL);
						listener->tcp_eager_last_q =
						    prev;
					}
				}
				tcpp[0] = tcp->tcp_eager_next_q;
				tcp->tcp_eager_next_q = NULL;
				tcp->tcp_eager_last_q = NULL;
				listener->tcp_conn_req_cnt_q--;
				break;
			}
			prev = tcpp[0];
		}
	}
	tcp->tcp_listener = NULL;
}

/*
 * Reset any eager connection hanging off this listener
 * and then reclaim it's resources.
 */
static void
tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only, int sock_id)
{
	tcp_t	*eager;

	if (!q0_only) {
		/* First cleanup q */
		while ((eager = listener->tcp_eager_next_q) != NULL) {
			assert(listener->tcp_eager_last_q != NULL);
			tcp_xmit_ctl("tcp_eager_cleanup, can't wait",
			    eager, NULL, eager->tcp_snxt, 0, TH_RST, 0,
			    sock_id);
			tcp_close_detached(eager);
		}
		assert(listener->tcp_eager_last_q == NULL);
	}
	/* Then cleanup q0 */
	while ((eager = listener->tcp_eager_next_q0) != listener) {
		tcp_xmit_ctl("tcp_eager_cleanup, can't wait",
		    eager, NULL, eager->tcp_snxt, 0, TH_RST, 0, sock_id);
		tcp_close_detached(eager);
	}
}

/*
 * To handle the shutdown request. Called from shutdown()
 */
int
tcp_shutdown(int sock_id)
{
	tcp_t	*tcp;

	DEBUG_1("tcp_shutdown: sock_id %x\n", sock_id);

	if ((tcp = sockets[sock_id].pcb) == NULL) {
		return (-1);
	}

	/*
	 * Since inetboot is not interrupt driven, there may be
	 * some ACKs in the MAC's buffer.  Drain them first,
	 * otherwise, we may not be able to send.
	 */
	if (tcp_drain_input(tcp, sock_id, 5) < 0) {
		/*
		 * If we return now without freeing TCP, there will be
		 * a memory leak.
		 */
		if (sockets[sock_id].pcb != NULL)
			tcp_clean_death(sock_id, tcp, 0);
		return (-1);
	}

	DEBUG_1("tcp_shutdown: tcp_state %x\n", tcp->tcp_state);
	switch (tcp->tcp_state) {

	case TCPS_SYN_RCVD:
		/*
		 * Shutdown during the connect 3-way handshake
		 */
	case TCPS_ESTABLISHED:
		/*
		 * Transmit the FIN
		 * wait for the FIN to be ACKed,
		 * then remain in FIN_WAIT_2
		 */
		dprintf("tcp_shutdown: sending fin\n");
		if (tcp_xmit_end(tcp, sock_id) == 0 &&
			tcp_state_wait(sock_id, tcp, TCPS_FIN_WAIT_2) < 0) {
			/* During the wait, TCP may be gone... */
			if (sockets[sock_id].pcb == NULL)
				return (-1);
		}
		dprintf("tcp_shutdown: done\n");
		break;

	default:
		break;

	}
	return (0);
}

/* To handle closing of the socket */
static int
tcp_close(int sock_id)
{
	char	*msg;
	tcp_t	*tcp;
	int	error = 0;

	if ((tcp = sockets[sock_id].pcb) == NULL) {
		return (-1);
	}

	TCP_RUN_TIME_WAIT_COLLECTOR();

	/*
	 * Since inetboot is not interrupt driven, there may be
	 * some ACKs in the MAC's buffer.  Drain them first,
	 * otherwise, we may not be able to send.
	 */
	if (tcp_drain_input(tcp, sock_id, 5) < 0) {
		/*
		 * If we return now without freeing TCP, there will be
		 * a memory leak.
		 */
		if (sockets[sock_id].pcb != NULL)
			tcp_clean_death(sock_id, tcp, 0);
		return (-1);
	}

	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
		/* Cleanup for listener */
		tcp_eager_cleanup(tcp, 0, sock_id);
	}

	msg = NULL;
	switch (tcp->tcp_state) {
	case TCPS_CLOSED:
	case TCPS_IDLE:
	case TCPS_BOUND:
	case TCPS_LISTEN:
		break;
	case TCPS_SYN_SENT:
		msg = "tcp_close, during connect";
		break;
	case TCPS_SYN_RCVD:
		/*
		 * Close during the connect 3-way handshake
		 * but here there may or may not be pending data
		 * already on queue. Process almost same as in
		 * the ESTABLISHED state.
		 */
		/* FALLTHRU */
	default:
		/*
		 * If SO_LINGER has set a zero linger time, abort the
		 * connection with a reset.
		 */
		if (tcp->tcp_linger && tcp->tcp_lingertime == 0) {
			msg = "tcp_close, zero lingertime";
			break;
		}

		/*
		 * Abort connection if there is unread data queued.
		 */
		if (tcp->tcp_rcv_list != NULL ||
				tcp->tcp_reass_head != NULL) {
			msg = "tcp_close, unread data";
			break;
		}
		if (tcp->tcp_state <= TCPS_LISTEN)
			break;

		/*
		 * Transmit the FIN before detaching the tcp_t.
		 * After tcp_detach returns this queue/perimeter
		 * no longer owns the tcp_t thus others can modify it.
		 * The TCP could be closed in tcp_state_wait called by
		 * tcp_wput_data called by tcp_xmit_end.
		 */
		(void) tcp_xmit_end(tcp, sock_id);
		if (sockets[sock_id].pcb == NULL)
			return (0);

		/*
		 * If lingering on close then wait until the fin is acked,
		 * the SO_LINGER time passes, or a reset is sent/received.
		 */
		if (tcp->tcp_linger && tcp->tcp_lingertime > 0 &&
		    !(tcp->tcp_fin_acked) &&
		    tcp->tcp_state >= TCPS_ESTABLISHED) {
			uint32_t stoptime; /* in ms */

			tcp->tcp_client_errno = 0;
			stoptime = prom_gettime() +
			    (tcp->tcp_lingertime * 1000);
			while (!(tcp->tcp_fin_acked) &&
			    tcp->tcp_state >= TCPS_ESTABLISHED &&
			    tcp->tcp_client_errno == 0 &&
			    ((int32_t)(stoptime - prom_gettime()) > 0)) {
				if (tcp_drain_input(tcp, sock_id, 5) < 0) {
					if (sockets[sock_id].pcb != NULL) {
						tcp_clean_death(sock_id,
						    tcp, 0);
					}
					return (-1);
				}
			}
			tcp->tcp_client_errno = 0;
		}
		if (tcp_state_wait(sock_id, tcp, TCPS_TIME_WAIT) < 0) {
			/* During the wait, TCP may be gone... */
			if (sockets[sock_id].pcb == NULL)
				return (0);
			msg = "tcp_close, couldn't detach";
		} else {
			return (0);
		}
		break;
	}

	/* Something went wrong...  Send a RST and report the error */
	if (msg != NULL) {
		if (tcp->tcp_state == TCPS_ESTABLISHED ||
		    tcp->tcp_state == TCPS_CLOSE_WAIT)
			BUMP_MIB(tcp_mib.tcpEstabResets);
		if (tcp->tcp_state == TCPS_SYN_SENT ||
		    tcp->tcp_state == TCPS_SYN_RCVD)
			BUMP_MIB(tcp_mib.tcpAttemptFails);
		tcp_xmit_ctl(msg, tcp, NULL, tcp->tcp_snxt, 0, TH_RST, 0,
		    sock_id);
	}

	tcp_free(tcp);
	bkmem_free((caddr_t)tcp, sizeof (tcp_t));
	sockets[sock_id].pcb = NULL;
	return (error);
}

/* To make an endpoint a listener. */
int
tcp_listen(int sock_id, int backlog)
{
	tcp_t *tcp;

	if ((tcp = (tcp_t *)(sockets[sock_id].pcb)) == NULL) {
		errno = EINVAL;
		return (-1);
	}
	/* We allow calling listen() multiple times to change the backlog. */
	if (tcp->tcp_state > TCPS_LISTEN || tcp->tcp_state < TCPS_BOUND) {
		errno = EOPNOTSUPP;
		return (-1);
	}
	/* The following initialization should only be done once. */
	if (tcp->tcp_state != TCPS_LISTEN) {
		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
		tcp->tcp_eager_next_q = NULL;
		tcp->tcp_state = TCPS_LISTEN;
		tcp->tcp_second_ctimer_threshold = tcp_ip_abort_linterval;
	}
	if ((tcp->tcp_conn_req_max = backlog) > tcp_conn_req_max_q) {
		tcp->tcp_conn_req_max = tcp_conn_req_max_q;
	}
	if (tcp->tcp_conn_req_max < tcp_conn_req_min) {
		tcp->tcp_conn_req_max = tcp_conn_req_min;
	}
	return (0);
}

/* To accept connections. */
int
tcp_accept(int sock_id, struct sockaddr *addr, socklen_t *addr_len)
{
	tcp_t *listener;
	tcp_t *eager;
	int sd, new_sock_id;
	struct sockaddr_in *new_addr = (struct sockaddr_in *)addr;
	int timeout;

	/* Sanity check. */
	if ((listener = (tcp_t *)(sockets[sock_id].pcb)) == NULL ||
	    new_addr == NULL || addr_len == NULL ||
	    *addr_len < sizeof (struct sockaddr_in) ||
	    listener->tcp_state != TCPS_LISTEN) {
		errno = EINVAL;
		return (-1);
	}

	if (sockets[sock_id].in_timeout > tcp_accept_timeout)
		timeout = prom_gettime() + sockets[sock_id].in_timeout;
	else
		timeout = prom_gettime() + tcp_accept_timeout;
	while (listener->tcp_eager_next_q == NULL &&
	    timeout > prom_gettime()) {
#if DEBUG
		printf("tcp_accept: Waiting in tcp_accept()\n");
#endif
		if (tcp_drain_input(listener, sock_id, 5) < 0) {
			return (-1);
		}
	}
	/* If there is an eager, don't timeout... */
	if (timeout <= prom_gettime() && listener->tcp_eager_next_q == NULL) {
#if DEBUG
		printf("tcp_accept: timeout\n");
#endif
		errno = ETIMEDOUT;
		return (-1);
	}
#if DEBUG
	printf("tcp_accept: got a connection\n");
#endif

	/* Now create the socket for this new TCP. */
	if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		return (-1);
	}
	if ((new_sock_id = so_check_fd(sd, &errno)) == -1)
		/* This should not happen! */
		prom_panic("so_check_fd() fails in tcp_accept()");
	/* Free the TCP PCB in the original socket. */
	bkmem_free((caddr_t)(sockets[new_sock_id].pcb), sizeof (tcp_t));
	/* Dequeue the eager and attach it to the socket. */
	eager = listener->tcp_eager_next_q;
	listener->tcp_eager_next_q = eager->tcp_eager_next_q;
	if (listener->tcp_eager_last_q == eager)
		listener->tcp_eager_last_q = NULL;
	eager->tcp_eager_next_q = NULL;
	sockets[new_sock_id].pcb = eager;
	listener->tcp_conn_req_cnt_q--;

	/* Copy in the address info. */
	bcopy(&eager->tcp_remote, &new_addr->sin_addr.s_addr,
	    sizeof (in_addr_t));
	bcopy(&eager->tcp_fport, &new_addr->sin_port, sizeof (in_port_t));
	new_addr->sin_family = AF_INET;

#ifdef DEBUG
	printf("tcp_accept(), new sock_id: %d\n", sd);
#endif
	return (sd);
}

/* Update the next anonymous port to use.  */
static in_port_t
tcp_update_next_port(in_port_t port)
{
	/* Don't allow the port to fall out of the anonymous port range. */
	if (port < tcp_smallest_anon_port || port > tcp_largest_anon_port)
		port = (in_port_t)tcp_smallest_anon_port;

	if (port < tcp_smallest_nonpriv_port)
		port = (in_port_t)tcp_smallest_nonpriv_port;
	return (port);
}

/* To check whether a bind to a port is allowed. */
static in_port_t
tcp_bindi(in_port_t port, in_addr_t *addr, boolean_t reuseaddr,
    boolean_t bind_to_req_port_only)
{
	int i, count;
	tcp_t *tcp;

	count = tcp_largest_anon_port - tcp_smallest_anon_port;
try_again:
	for (i = 0; i < MAXSOCKET; i++) {
		if (sockets[i].type != INETBOOT_STREAM ||
		    ((tcp = (tcp_t *)sockets[i].pcb) == NULL) ||
		    ntohs(tcp->tcp_lport) != port) {
			continue;
		}
		/*
		 * Both TCPs have the same port.  If SO_REUSEDADDR is
		 * set and the bound TCP has a state greater than
		 * TCPS_LISTEN, it is fine.
		 */
		if (reuseaddr && tcp->tcp_state > TCPS_LISTEN) {
			continue;
		}
		if (tcp->tcp_bound_source != INADDR_ANY &&
		    *addr != INADDR_ANY &&
		    tcp->tcp_bound_source != *addr) {
			continue;
		}
		if (bind_to_req_port_only) {
			return (0);
		}
		if (--count > 0) {
			port = tcp_update_next_port(++port);
			goto try_again;
		} else {
			return (0);
		}
	}
	return (port);
}

/* To handle the bind request. */
int
tcp_bind(int sock_id)
{
	tcp_t *tcp;
	in_port_t requested_port, allocated_port;
	boolean_t bind_to_req_port_only;
	boolean_t reuseaddr;

	if ((tcp = (tcp_t *)sockets[sock_id].pcb) == NULL) {
		errno = EINVAL;
		return (-1);
	}

	if (tcp->tcp_state >= TCPS_BOUND) {
		/* We don't allow multiple bind(). */
		errno = EPROTO;
		return (-1);
	}

	requested_port = ntohs(sockets[sock_id].bind.sin_port);

	/* The bound source can be INADDR_ANY. */
	tcp->tcp_bound_source = sockets[sock_id].bind.sin_addr.s_addr;

	tcp->tcp_ipha->ip_src.s_addr = tcp->tcp_bound_source;

	/* Verify the port is available. */
	if (requested_port == 0)
		bind_to_req_port_only = B_FALSE;
	else			/* T_BIND_REQ and requested_port != 0 */
		bind_to_req_port_only = B_TRUE;

	if (requested_port == 0) {
		requested_port = tcp_update_next_port(++tcp_next_port_to_try);
	}
	reuseaddr = sockets[sock_id].so_opt & SO_REUSEADDR;
	allocated_port = tcp_bindi(requested_port, &(tcp->tcp_bound_source),
	    reuseaddr, bind_to_req_port_only);

	if (allocated_port == 0) {
		errno = EADDRINUSE;
		return (-1);
	}
	tcp->tcp_lport = htons(allocated_port);
	*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
	sockets[sock_id].bind.sin_port = tcp->tcp_lport;
	tcp->tcp_state = TCPS_BOUND;
	return (0);
}

/*
 * Check for duplicate TCP connections.
 */
static int
tcp_conn_check(tcp_t *tcp)
{
	int i;
	tcp_t *tmp_tcp;

	for (i = 0; i < MAXSOCKET; i++) {
		if (sockets[i].type != INETBOOT_STREAM)
			continue;
		/* Socket may not be closed but the TCP can be gone. */
		if ((tmp_tcp = (tcp_t *)sockets[i].pcb) == NULL)
			continue;
		/* We only care about TCP in states later than SYN_SENT. */
		if (tmp_tcp->tcp_state < TCPS_SYN_SENT)
			continue;
		if (tmp_tcp->tcp_lport != tcp->tcp_lport ||
		    tmp_tcp->tcp_fport != tcp->tcp_fport ||
		    tmp_tcp->tcp_bound_source != tcp->tcp_bound_source ||
		    tmp_tcp->tcp_remote != tcp->tcp_remote) {
			continue;
		} else {
			return (-1);
		}
	}
	return (0);
}

/* To handle a connect request. */
int
tcp_connect(int sock_id)
{
	tcp_t *tcp;
	in_addr_t dstaddr;
	in_port_t dstport;
	tcph_t	*tcph;
	int mss;
	mblk_t *syn_mp;

	if ((tcp = (tcp_t *)(sockets[sock_id].pcb)) == NULL) {
		errno = EINVAL;
		return (-1);
	}

	TCP_RUN_TIME_WAIT_COLLECTOR();

	dstaddr = sockets[sock_id].remote.sin_addr.s_addr;
	dstport = sockets[sock_id].remote.sin_port;

	/*
	 * Check for attempt to connect to INADDR_ANY or non-unicast addrress.
	 * We don't have enough info to check for broadcast addr, except
	 * for the all 1 broadcast.
	 */
	if (dstaddr == INADDR_ANY || IN_CLASSD(ntohl(dstaddr)) ||
	    dstaddr == INADDR_BROADCAST)  {
		/*
		 * SunOS 4.x and 4.3 BSD allow an application
		 * to connect a TCP socket to INADDR_ANY.
		 * When they do this, the kernel picks the
		 * address of one interface and uses it
		 * instead.  The kernel usually ends up
		 * picking the address of the loopback
		 * interface.  This is an undocumented feature.
		 * However, we provide the same thing here
		 * in order to have source and binary
		 * compatibility with SunOS 4.x.
		 * Update the T_CONN_REQ (sin/sin6) since it is used to
		 * generate the T_CONN_CON.
		 *
		 * Fail this for inetboot TCP.
		 */
		errno = EINVAL;
		return (-1);
	}

	/* It is not bound to any address yet... */
	if (tcp->tcp_bound_source == INADDR_ANY) {
		ipv4_getipaddr(&(sockets[sock_id].bind.sin_addr));
		/* We don't have an address! */
		if (ntohl(sockets[sock_id].bind.sin_addr.s_addr) ==
		    INADDR_ANY) {
			errno = EPROTO;
			return (-1);
		}
		tcp->tcp_bound_source = sockets[sock_id].bind.sin_addr.s_addr;
		tcp->tcp_ipha->ip_src.s_addr = tcp->tcp_bound_source;
	}

	/*
	 * Don't let an endpoint connect to itself.
	 */
	if (dstaddr == tcp->tcp_ipha->ip_src.s_addr &&
	    dstport == tcp->tcp_lport) {
		errno = EINVAL;
		return (-1);
	}

	tcp->tcp_ipha->ip_dst.s_addr = dstaddr;
	tcp->tcp_remote = dstaddr;
	tcph = tcp->tcp_tcph;
	*(uint16_t *)tcph->th_fport = dstport;
	tcp->tcp_fport = dstport;

	/*
	 * Don't allow this connection to completely duplicate
	 * an existing connection.
	 */
	if (tcp_conn_check(tcp) < 0) {
		errno = EADDRINUSE;
		return (-1);
	}

	/*
	 * Just make sure our rwnd is at
	 * least tcp_recv_hiwat_mss * MSS
	 * large, and round up to the nearest
	 * MSS.
	 *
	 * We do the round up here because
	 * we need to get the interface
	 * MTU first before we can do the
	 * round up.
	 */
	mss = tcp->tcp_mss - tcp->tcp_hdr_len;
	tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
	    tcp_recv_hiwat_minmss * mss);
	tcp->tcp_rwnd_max = tcp->tcp_rwnd;
	SET_WS_VALUE(tcp);
	U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
	    tcp->tcp_tcph->th_win);
	if (tcp->tcp_rcv_ws > 0 || tcp_wscale_always)
		tcp->tcp_snd_ws_ok = B_TRUE;

	/*
	 * Set tcp_snd_ts_ok to true
	 * so that tcp_xmit_mp will
	 * include the timestamp
	 * option in the SYN segment.
	 */
	if (tcp_tstamp_always ||
	    (tcp->tcp_rcv_ws && tcp_tstamp_if_wscale)) {
		tcp->tcp_snd_ts_ok = B_TRUE;
	}

	if (tcp_sack_permitted == 2 ||
	    tcp->tcp_snd_sack_ok) {
		assert(tcp->tcp_sack_info == NULL);
		if ((tcp->tcp_sack_info = (tcp_sack_info_t *)bkmem_zalloc(
		    sizeof (tcp_sack_info_t))) == NULL) {
			tcp->tcp_snd_sack_ok = B_FALSE;
		} else {
			tcp->tcp_snd_sack_ok = B_TRUE;
		}
	}
	/*
	 * Should we use ECN?  Note that the current
	 * default value (SunOS 5.9) of tcp_ecn_permitted
	 * is 2.  The reason for doing this is that there
	 * are equipments out there that will drop ECN
	 * enabled IP packets.  Setting it to 1 avoids
	 * compatibility problems.
	 */
	if (tcp_ecn_permitted == 2)
		tcp->tcp_ecn_ok = B_TRUE;

	tcp_iss_init(tcp);
	TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
	tcp->tcp_active_open = B_TRUE;

	tcp->tcp_state = TCPS_SYN_SENT;
	syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, tcp->tcp_iss, B_FALSE,
	    NULL, B_FALSE);
	if (syn_mp != NULL) {
		int ret;

		/* Dump the packet when debugging. */
		TCP_DUMP_PACKET("tcp_connect", syn_mp);
		/* Send out the SYN packet. */
		ret = ipv4_tcp_output(sock_id, syn_mp);
		freeb(syn_mp);
		/*
		 * errno ETIMEDOUT is set by the mac driver
		 * in case it is not able to receive ARP reply.
		 * TCP will retransmit this segment so we can
		 * ignore the ARP timeout.
		 */
		if ((ret < 0) && (errno != ETIMEDOUT)) {
			return (-1);
		}
		/* tcp_state_wait() will finish the 3 way handshake. */
		return (tcp_state_wait(sock_id, tcp, TCPS_ESTABLISHED));
	} else {
		errno = ENOBUFS;
		return (-1);
	}
}

/*
 * Common accept code.  Called by tcp_conn_request.
 * cr_pkt is the SYN packet.
 */
static int
tcp_accept_comm(tcp_t *listener, tcp_t *acceptor, mblk_t *cr_pkt,
    uint_t ip_hdr_len)
{
	tcph_t		*tcph;

#ifdef DEBUG
	printf("tcp_accept_comm #######################\n");
#endif

	/*
	 * When we get here, we know that the acceptor header template
	 * has already been initialized.
	 * However, it may not match the listener if the listener
	 * includes options...
	 * It may also not match the listener if the listener is v6 and
	 * and the acceptor is v4
	 */
	acceptor->tcp_lport = listener->tcp_lport;

	if (listener->tcp_ipversion == acceptor->tcp_ipversion) {
		if (acceptor->tcp_iphc_len != listener->tcp_iphc_len) {
			/*
			 * Listener had options of some sort; acceptor inherits.
			 * Free up the acceptor template and allocate one
			 * of the right size.
			 */
			bkmem_free(acceptor->tcp_iphc, acceptor->tcp_iphc_len);
			acceptor->tcp_iphc = bkmem_zalloc(
			    listener->tcp_iphc_len);
			if (acceptor->tcp_iphc == NULL) {
				acceptor->tcp_iphc_len = 0;
				return (ENOMEM);
			}
			acceptor->tcp_iphc_len = listener->tcp_iphc_len;
		}
		acceptor->tcp_hdr_len = listener->tcp_hdr_len;
		acceptor->tcp_ip_hdr_len = listener->tcp_ip_hdr_len;
		acceptor->tcp_tcp_hdr_len = listener->tcp_tcp_hdr_len;

		/*
		 * Copy the IP+TCP header template from listener to acceptor
		 */
		bcopy(listener->tcp_iphc, acceptor->tcp_iphc,
		    listener->tcp_hdr_len);
		acceptor->tcp_ipha = (struct ip *)acceptor->tcp_iphc;
		acceptor->tcp_tcph = (tcph_t *)(acceptor->tcp_iphc +
		    acceptor->tcp_ip_hdr_len);
	} else {
		prom_panic("tcp_accept_comm: version not equal");
	}

	/* Copy our new dest and fport from the connection request packet */
	if (acceptor->tcp_ipversion == IPV4_VERSION) {
		struct ip *ipha;

		ipha = (struct ip *)cr_pkt->b_rptr;
		acceptor->tcp_ipha->ip_dst = ipha->ip_src;
		acceptor->tcp_remote = ipha->ip_src.s_addr;
		acceptor->tcp_ipha->ip_src = ipha->ip_dst;
		acceptor->tcp_bound_source = ipha->ip_dst.s_addr;
		tcph = (tcph_t *)&cr_pkt->b_rptr[ip_hdr_len];
	} else {
		prom_panic("tcp_accept_comm: not IPv4");
	}
	bcopy(tcph->th_lport, acceptor->tcp_tcph->th_fport, sizeof (in_port_t));
	bcopy(acceptor->tcp_tcph->th_fport, &acceptor->tcp_fport,
	    sizeof (in_port_t));
	/*
	 * For an all-port proxy listener, the local port is determined by
	 * the port number field in the SYN packet.
	 */
	if (listener->tcp_lport == 0) {
		acceptor->tcp_lport = *(in_port_t *)tcph->th_fport;
		bcopy(tcph->th_fport, acceptor->tcp_tcph->th_lport,
		    sizeof (in_port_t));
	}
	/* Inherit various TCP parameters from the listener */
	acceptor->tcp_naglim = listener->tcp_naglim;
	acceptor->tcp_first_timer_threshold =
	    listener->tcp_first_timer_threshold;
	acceptor->tcp_second_timer_threshold =
	    listener->tcp_second_timer_threshold;

	acceptor->tcp_first_ctimer_threshold =
	    listener->tcp_first_ctimer_threshold;
	acceptor->tcp_second_ctimer_threshold =
	    listener->tcp_second_ctimer_threshold;

	acceptor->tcp_xmit_hiwater = listener->tcp_xmit_hiwater;

	acceptor->tcp_state = TCPS_LISTEN;
	tcp_iss_init(acceptor);

	/* Process all TCP options. */
	tcp_process_options(acceptor, tcph);

	/* Is the other end ECN capable? */
	if (tcp_ecn_permitted >= 1 &&
	    (tcph->th_flags[0] & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
		acceptor->tcp_ecn_ok = B_TRUE;
	}

	/*
	 * listener->tcp_rq->q_hiwat should be the default window size or a
	 * window size changed via SO_RCVBUF option.  First round up the
	 * acceptor's tcp_rwnd to the nearest MSS.  Then find out the window
	 * scale option value if needed.  Call tcp_rwnd_set() to finish the
	 * setting.
	 *
	 * Note if there is a rpipe metric associated with the remote host,
	 * we should not inherit receive window size from listener.
	 */
	acceptor->tcp_rwnd = MSS_ROUNDUP(
	    (acceptor->tcp_rwnd == 0 ? listener->tcp_rwnd_max :
	    acceptor->tcp_rwnd), acceptor->tcp_mss);
	if (acceptor->tcp_snd_ws_ok)
		SET_WS_VALUE(acceptor);
	/*
	 * Note that this is the only place tcp_rwnd_set() is called for
	 * accepting a connection.  We need to call it here instead of
	 * after the 3-way handshake because we need to tell the other
	 * side our rwnd in the SYN-ACK segment.
	 */
	(void) tcp_rwnd_set(acceptor, acceptor->tcp_rwnd);

	return (0);
}

/*
 * Defense for the SYN attack -
 * 1. When q0 is full, drop from the tail (tcp_eager_prev_q0) the oldest
 *    one that doesn't have the dontdrop bit set.
 * 2. Don't drop a SYN request before its first timeout. This gives every
 *    request at least til the first timeout to complete its 3-way handshake.
 * 3. The current threshold is - # of timeout > q0len/4 => SYN alert on
 *    # of timeout drops back to <= q0len/32 => SYN alert off
 */
static boolean_t
tcp_drop_q0(tcp_t *tcp)
{
	tcp_t	*eager;

	assert(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
	/*
	 * New one is added after next_q0 so prev_q0 points to the oldest
	 * Also do not drop any established connections that are deferred on
	 * q0 due to q being full
	 */

	eager = tcp->tcp_eager_prev_q0;
	while (eager->tcp_dontdrop || eager->tcp_conn_def_q0) {
		/* XXX should move the eager to the head */
		eager = eager->tcp_eager_prev_q0;
		if (eager == tcp) {
			eager = tcp->tcp_eager_prev_q0;
			break;
		}
	}
	dprintf("tcp_drop_q0: listen half-open queue (max=%d) overflow"
	    " (%d pending) on %s, drop one", tcp_conn_req_max_q0,
	    tcp->tcp_conn_req_cnt_q0,
	    tcp_display(tcp, NULL, DISP_PORT_ONLY));

	BUMP_MIB(tcp_mib.tcpHalfOpenDrop);
	bkmem_free((caddr_t)eager, sizeof (tcp_t));
	return (B_TRUE);
}

/* ARGSUSED */
static tcp_t *
tcp_conn_request(tcp_t *tcp, mblk_t *mp, uint_t sock_id, uint_t ip_hdr_len)
{
	tcp_t	*eager;
	struct ip *ipha;
	int	err;

#ifdef DEBUG
	printf("tcp_conn_request ###################\n");
#endif

	if (tcp->tcp_conn_req_cnt_q >= tcp->tcp_conn_req_max) {
		BUMP_MIB(tcp_mib.tcpListenDrop);
		dprintf("tcp_conn_request: listen backlog (max=%d) "
		    "overflow (%d pending) on %s",
		    tcp->tcp_conn_req_max, tcp->tcp_conn_req_cnt_q,
		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
		return (NULL);
	}

	assert(OK_32PTR(mp->b_rptr));

	if (tcp->tcp_conn_req_cnt_q0 >=
	    tcp->tcp_conn_req_max + tcp_conn_req_max_q0) {
		/*
		 * Q0 is full. Drop a pending half-open req from the queue
		 * to make room for the new SYN req. Also mark the time we
		 * drop a SYN.
		 */
		tcp->tcp_last_rcv_lbolt = prom_gettime();
		if (!tcp_drop_q0(tcp)) {
			freemsg(mp);
			BUMP_MIB(tcp_mib.tcpListenDropQ0);
			dprintf("tcp_conn_request: listen half-open queue "
			    "(max=%d) full (%d pending) on %s",
			    tcp_conn_req_max_q0,
			    tcp->tcp_conn_req_cnt_q0,
			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
			return (NULL);
		}
	}

	ipha = (struct ip *)mp->b_rptr;
	if (IN_CLASSD(ntohl(ipha->ip_src.s_addr)) ||
	    ipha->ip_src.s_addr == INADDR_BROADCAST ||
	    ipha->ip_src.s_addr == INADDR_ANY ||
	    ipha->ip_dst.s_addr == INADDR_BROADCAST) {
		freemsg(mp);
		return (NULL);
	}
	/*
	 * We allow the connection to proceed
	 * by generating a detached tcp state vector and put it in
	 * the eager queue.  When an accept happens, it will be
	 * dequeued sequentially.
	 */
	if ((eager = (tcp_t *)bkmem_alloc(sizeof (tcp_t))) == NULL) {
		freemsg(mp);
		errno = ENOBUFS;
		return (NULL);
	}
	if ((errno = tcp_init_values(eager, NULL)) != 0) {
		freemsg(mp);
		bkmem_free((caddr_t)eager, sizeof (tcp_t));
		return (NULL);
	}

	/*
	 * Eager connection inherits address form from its listener,
	 * but its packet form comes from the version of the received
	 * SYN segment.
	 */
	eager->tcp_family = tcp->tcp_family;

	err = tcp_accept_comm(tcp, eager, mp, ip_hdr_len);
	if (err) {
		bkmem_free((caddr_t)eager, sizeof (tcp_t));
		return (NULL);
	}

	tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
	eager->tcp_eager_next_q0 = tcp->tcp_eager_next_q0;
	tcp->tcp_eager_next_q0 = eager;
	eager->tcp_eager_prev_q0 = tcp;

	/* Set tcp_listener before adding it to tcp_conn_fanout */
	eager->tcp_listener = tcp;
	tcp->tcp_conn_req_cnt_q0++;

	return (eager);
}

/*
 * To get around the non-interrupt problem of inetboot.
 * Keep on processing packets until a certain state is reached or the
 * TCP is destroyed because of getting a RST packet.
 */
static int
tcp_state_wait(int sock_id, tcp_t *tcp, int state)
{
	int i;
	struct inetgram *in_gram;
	mblk_t *mp;
	int timeout;
	boolean_t changed = B_FALSE;

	/*
	 * We need to make sure that the MAC does not wait longer
	 * than RTO for any packet so that TCP can do retransmission.
	 * But if the MAC timeout is less than tcp_rto, we are fine
	 * and do not need to change it.
	 */
	timeout = sockets[sock_id].in_timeout;
	if (timeout > tcp->tcp_rto) {
		sockets[sock_id].in_timeout = tcp->tcp_rto;
		changed = B_TRUE;
	}
retry:
	if (sockets[sock_id].inq == NULL) {
		/* Go out and check the wire */
		for (i = MEDIA_LVL; i < TRANSPORT_LVL; i++) {
			if (sockets[sock_id].input[i] != NULL) {
				if (sockets[sock_id].input[i](sock_id) < 0) {
					if (changed) {
						sockets[sock_id].in_timeout =
						    timeout;
					}
					return (-1);
				}
			}
		}
	}

	while ((in_gram = sockets[sock_id].inq) != NULL) {
		if (tcp->tcp_state == state)
			break;

		/* Remove unknown inetgrams from the head of inq. */
		if (in_gram->igm_level != TRANSPORT_LVL) {
#ifdef DEBUG
			printf("tcp_state_wait for state %d: unexpected "
			    "packet level %d frame found\n", state,
			    in_gram->igm_level);
#endif
			del_gram(&sockets[sock_id].inq, in_gram, B_TRUE);
			continue;
		}
		mp = in_gram->igm_mp;
		del_gram(&sockets[sock_id].inq, in_gram, B_FALSE);
		bkmem_free((caddr_t)in_gram, sizeof (struct inetgram));
		tcp_rput_data(tcp, mp, sock_id);

		/*
		 * The other side may have closed this connection or
		 * RST us.  But we need to continue to process other
		 * packets in the socket's queue because they may be
		 * belong to another TCP connections.
		 */
		if (sockets[sock_id].pcb == NULL) {
			tcp = NULL;
		}
	}

	/* If the other side has closed the connection, just return. */
	if (tcp == NULL || sockets[sock_id].pcb == NULL) {
#ifdef DEBUG
		printf("tcp_state_wait other side dead: state %d "
		    "error %d\n", state, sockets[sock_id].so_error);
#endif
		if (sockets[sock_id].so_error != 0)
			return (-1);
		else
			return (0);
	}
	/*
	 * TCPS_ALL_ACKED is not a valid TCP state, it is just used as an
	 * indicator to tcp_state_wait to mean that it is being called
	 * to wait till we have received acks for all the new segments sent.
	 */
	if ((state == TCPS_ALL_ACKED) && (tcp->tcp_suna == tcp->tcp_snxt)) {
		goto done;
	}
	if (tcp->tcp_state != state) {
		if (prom_gettime() > tcp->tcp_rto_timeout)
			tcp_timer(tcp, sock_id);
		goto retry;
	}
done:
	if (changed)
		sockets[sock_id].in_timeout = timeout;

	tcp_drain_needed(sock_id, tcp);
	return (0);
}

/* Verify the checksum of a segment. */
static int
tcp_verify_cksum(mblk_t *mp)
{
	struct ip *iph;
	tcpha_t *tcph;
	int len;
	uint16_t old_sum;

	iph = (struct ip *)mp->b_rptr;
	tcph = (tcpha_t *)(iph + 1);
	len = ntohs(iph->ip_len);

	/*
	 * Calculate the TCP checksum.  Need to include the psuedo header,
	 * which is similar to the real IP header starting at the TTL field.
	 */
	iph->ip_sum = htons(len - IP_SIMPLE_HDR_LENGTH);
	old_sum = tcph->tha_sum;
	tcph->tha_sum = 0;
	iph->ip_ttl = 0;
	if (old_sum == tcp_cksum((uint16_t *)&(iph->ip_ttl),
	    len - IP_SIMPLE_HDR_LENGTH + 12)) {
		return (0);
	} else {
		tcp_cksum_errors++;
		return (-1);
	}
}

/* To find a TCP connection matching the incoming segment. */
static tcp_t *
tcp_lookup_ipv4(struct ip *iph, tcpha_t *tcph, int min_state, int *sock_id)
{
	int i;
	tcp_t *tcp;

	for (i = 0; i < MAXSOCKET; i++) {
		if (sockets[i].type == INETBOOT_STREAM &&
		    (tcp = (tcp_t *)sockets[i].pcb) != NULL) {
			if (tcph->tha_lport == tcp->tcp_fport &&
			    tcph->tha_fport == tcp->tcp_lport &&
			    iph->ip_src.s_addr == tcp->tcp_remote &&
			    iph->ip_dst.s_addr == tcp->tcp_bound_source &&
			    tcp->tcp_state >= min_state) {
				*sock_id = i;
				return (tcp);
			}
		}
	}
	/* Find it in the time wait list. */
	for (tcp = tcp_time_wait_head; tcp != NULL;
	    tcp = tcp->tcp_time_wait_next) {
		if (tcph->tha_lport == tcp->tcp_fport &&
		    tcph->tha_fport == tcp->tcp_lport &&
		    iph->ip_src.s_addr == tcp->tcp_remote &&
		    iph->ip_dst.s_addr == tcp->tcp_bound_source &&
		    tcp->tcp_state >= min_state) {
			*sock_id = -1;
			return (tcp);
		}
	}
	return (NULL);
}

/* To find a TCP listening connection matching the incoming segment. */
static tcp_t *
tcp_lookup_listener_ipv4(in_addr_t addr, in_port_t port, int *sock_id)
{
	int i;
	tcp_t *tcp;

	for (i = 0; i < MAXSOCKET; i++) {
		if (sockets[i].type == INETBOOT_STREAM &&
		    (tcp = (tcp_t *)sockets[i].pcb) != NULL) {
			if (tcp->tcp_lport == port &&
			    (tcp->tcp_bound_source == addr ||
			    tcp->tcp_bound_source == INADDR_ANY)) {
				*sock_id = i;
				return (tcp);
			}
		}
	}

	return (NULL);
}

/* To find a TCP eager matching the incoming segment. */
static tcp_t *
tcp_lookup_eager_ipv4(tcp_t *listener, struct ip *iph, tcpha_t *tcph)
{
	tcp_t *tcp;

#ifdef DEBUG
	printf("tcp_lookup_eager_ipv4 ###############\n");
#endif
	for (tcp = listener->tcp_eager_next_q; tcp != NULL;
	    tcp = tcp->tcp_eager_next_q) {
		if (tcph->tha_lport == tcp->tcp_fport &&
		    tcph->tha_fport == tcp->tcp_lport &&
		    iph->ip_src.s_addr == tcp->tcp_remote &&
		    iph->ip_dst.s_addr == tcp->tcp_bound_source) {
			return (tcp);
		}
	}

	for (tcp = listener->tcp_eager_next_q0; tcp != listener;
	    tcp = tcp->tcp_eager_next_q0) {
		if (tcph->tha_lport == tcp->tcp_fport &&
		    tcph->tha_fport == tcp->tcp_lport &&
		    iph->ip_src.s_addr == tcp->tcp_remote &&
		    iph->ip_dst.s_addr == tcp->tcp_bound_source) {
			return (tcp);
		}
	}
#ifdef DEBUG
	printf("No eager found\n");
#endif
	return (NULL);
}

/* To destroy a TCP control block. */
static void
tcp_clean_death(int sock_id, tcp_t *tcp, int err)
{
	tcp_free(tcp);
	if (tcp->tcp_state == TCPS_TIME_WAIT)
		tcp_time_wait_remove(tcp);

	if (sock_id >= 0) {
		sockets[sock_id].pcb = NULL;
		if (err != 0)
			sockets[sock_id].so_error = err;
	}
	bkmem_free((caddr_t)tcp, sizeof (tcp_t));
}

/*
 * tcp_rwnd_set() is called to adjust the receive window to a desired value.
 * We do not allow the receive window to shrink.  After setting rwnd,
 * set the flow control hiwat of the stream.
 *
 * This function is called in 2 cases:
 *
 * 1) Before data transfer begins, in tcp_accept_comm() for accepting a
 *    connection (passive open) and in tcp_rput_data() for active connect.
 *    This is called after tcp_mss_set() when the desired MSS value is known.
 *    This makes sure that our window size is a mutiple of the other side's
 *    MSS.
 * 2) Handling SO_RCVBUF option.
 *
 * It is ASSUMED that the requested size is a multiple of the current MSS.
 *
 * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
 * user requests so.
 */
static int
tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
{
	uint32_t	mss = tcp->tcp_mss;
	uint32_t	old_max_rwnd;
	uint32_t	max_transmittable_rwnd;

	if (tcp->tcp_rwnd_max != 0)
		old_max_rwnd = tcp->tcp_rwnd_max;
	else
		old_max_rwnd = tcp->tcp_rwnd;

	/*
	 * Insist on a receive window that is at least
	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
	 * funny TCP interactions of Nagle algorithm, SWS avoidance
	 * and delayed acknowledgement.
	 */
	rwnd = MAX(rwnd, tcp_recv_hiwat_minmss * mss);

	/*
	 * If window size info has already been exchanged, TCP should not
	 * shrink the window.  Shrinking window is doable if done carefully.
	 * We may add that support later.  But so far there is not a real
	 * need to do that.
	 */
	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
		/* MSS may have changed, do a round up again. */
		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
	}

	/*
	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
	 * can be applied even before the window scale option is decided.
	 */
	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
	if (rwnd > max_transmittable_rwnd) {
		rwnd = max_transmittable_rwnd -
		    (max_transmittable_rwnd % mss);
		if (rwnd < mss)
			rwnd = max_transmittable_rwnd;
		/*
		 * If we're over the limit we may have to back down tcp_rwnd.
		 * The increment below won't work for us. So we set all three
		 * here and the increment below will have no effect.
		 */
		tcp->tcp_rwnd = old_max_rwnd = rwnd;
	}

	/*
	 * Increment the current rwnd by the amount the maximum grew (we
	 * can not overwrite it since we might be in the middle of a
	 * connection.)
	 */
	tcp->tcp_rwnd += rwnd - old_max_rwnd;
	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win);
	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
		tcp->tcp_cwnd_max = rwnd;
	tcp->tcp_rwnd_max = rwnd;

	return (rwnd);
}

/*
 * Extract option values from a tcp header.  We put any found values into the
 * tcpopt struct and return a bitmask saying which options were found.
 */
static int
tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt)
{
	uchar_t		*endp;
	int		len;
	uint32_t	mss;
	uchar_t		*up = (uchar_t *)tcph;
	int		found = 0;
	int32_t		sack_len;
	tcp_seq		sack_begin, sack_end;
	tcp_t		*tcp;

	endp = up + TCP_HDR_LENGTH(tcph);
	up += TCP_MIN_HEADER_LENGTH;
	while (up < endp) {
		len = endp - up;
		switch (*up) {
		case TCPOPT_EOL:
			break;

		case TCPOPT_NOP:
			up++;
			continue;

		case TCPOPT_MAXSEG:
			if (len < TCPOPT_MAXSEG_LEN ||
			    up[1] != TCPOPT_MAXSEG_LEN)
				break;

			mss = BE16_TO_U16(up+2);
			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
			tcpopt->tcp_opt_mss = mss;
			found |= TCP_OPT_MSS_PRESENT;

			up += TCPOPT_MAXSEG_LEN;
			continue;

		case TCPOPT_WSCALE:
			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
				break;

			if (up[2] > TCP_MAX_WINSHIFT)
				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
			else
				tcpopt->tcp_opt_wscale = up[2];
			found |= TCP_OPT_WSCALE_PRESENT;

			up += TCPOPT_WS_LEN;
			continue;

		case TCPOPT_SACK_PERMITTED:
			if (len < TCPOPT_SACK_OK_LEN ||
			    up[1] != TCPOPT_SACK_OK_LEN)
				break;
			found |= TCP_OPT_SACK_OK_PRESENT;
			up += TCPOPT_SACK_OK_LEN;
			continue;

		case TCPOPT_SACK:
			if (len <= 2 || up[1] <= 2 || len < up[1])
				break;

			/* If TCP is not interested in SACK blks... */
			if ((tcp = tcpopt->tcp) == NULL) {
				up += up[1];
				continue;
			}
			sack_len = up[1] - TCPOPT_HEADER_LEN;
			up += TCPOPT_HEADER_LEN;

			/*
			 * If the list is empty, allocate one and assume
			 * nothing is sack'ed.
			 */
			assert(tcp->tcp_sack_info != NULL);
			if (tcp->tcp_notsack_list == NULL) {
				tcp_notsack_update(&(tcp->tcp_notsack_list),
				    tcp->tcp_suna, tcp->tcp_snxt,
				    &(tcp->tcp_num_notsack_blk),
				    &(tcp->tcp_cnt_notsack_list));

				/*
				 * Make sure tcp_notsack_list is not NULL.
				 * This happens when kmem_alloc(KM_NOSLEEP)
				 * returns NULL.
				 */
				if (tcp->tcp_notsack_list == NULL) {
					up += sack_len;
					continue;
				}
				tcp->tcp_fack = tcp->tcp_suna;
			}

			while (sack_len > 0) {
				if (up + 8 > endp) {
					up = endp;
					break;
				}
				sack_begin = BE32_TO_U32(up);
				up += 4;
				sack_end = BE32_TO_U32(up);
				up += 4;
				sack_len -= 8;
				/*
				 * Bounds checking.  Make sure the SACK
				 * info is within tcp_suna and tcp_snxt.
				 * If this SACK blk is out of bound, ignore
				 * it but continue to parse the following
				 * blks.
				 */
				if (SEQ_LEQ(sack_end, sack_begin) ||
				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
					continue;
				}
				tcp_notsack_insert(&(tcp->tcp_notsack_list),
				    sack_begin, sack_end,
				    &(tcp->tcp_num_notsack_blk),
				    &(tcp->tcp_cnt_notsack_list));
				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
					tcp->tcp_fack = sack_end;
				}
			}
			found |= TCP_OPT_SACK_PRESENT;
			continue;

		case TCPOPT_TSTAMP:
			if (len < TCPOPT_TSTAMP_LEN ||
			    up[1] != TCPOPT_TSTAMP_LEN)
				break;

			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);

			found |= TCP_OPT_TSTAMP_PRESENT;

			up += TCPOPT_TSTAMP_LEN;
			continue;

		default:
			if (len <= 1 || len < (int)up[1] || up[1] == 0)
				break;
			up += up[1];
			continue;
		}
		break;
	}
	return (found);
}

/*
 * Set the mss associated with a particular tcp based on its current value,
 * and a new one passed in. Observe minimums and maximums, and reset
 * other state variables that we want to view as multiples of mss.
 *
 * This function is called in various places mainly because
 * 1) Various stuffs, tcp_mss, tcp_cwnd, ... need to be adjusted when the
 *    other side's SYN/SYN-ACK packet arrives.
 * 2) PMTUd may get us a new MSS.
 * 3) If the other side stops sending us timestamp option, we need to
 *    increase the MSS size to use the extra bytes available.
 */
static void
tcp_mss_set(tcp_t *tcp, uint32_t mss)
{
	uint32_t	mss_max;

	mss_max = tcp_mss_max_ipv4;

	if (mss < tcp_mss_min)
		mss = tcp_mss_min;
	if (mss > mss_max)
		mss = mss_max;
	/*
	 * Unless naglim has been set by our client to
	 * a non-mss value, force naglim to track mss.
	 * This can help to aggregate small writes.
	 */
	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
		tcp->tcp_naglim = mss;
	/*
	 * TCP should be able to buffer at least 4 MSS data for obvious
	 * performance reason.
	 */
	if ((mss << 2) > tcp->tcp_xmit_hiwater)
		tcp->tcp_xmit_hiwater = mss << 2;
	tcp->tcp_mss = mss;
	/*
	 * Initialize cwnd according to draft-floyd-incr-init-win-01.txt.
	 * Previously, we use tcp_slow_start_initial to control the size
	 * of the initial cwnd.  Now, when tcp_slow_start_initial * mss
	 * is smaller than the cwnd calculated from the formula suggested in
	 * the draft, we use tcp_slow_start_initial * mss as the cwnd.
	 * Otherwise, use the cwnd from the draft's formula.  The default
	 * of tcp_slow_start_initial is 2.
	 */
	tcp->tcp_cwnd = MIN(tcp_slow_start_initial * mss,
	    MIN(4 * mss, MAX(2 * mss, 4380 / mss * mss)));
	tcp->tcp_cwnd_cnt = 0;
}

/*
 * Process all TCP option in SYN segment.
 *
 * This function sets up the correct tcp_mss value according to the
 * MSS option value and our header size.  It also sets up the window scale
 * and timestamp values, and initialize SACK info blocks.  But it does not
 * change receive window size after setting the tcp_mss value.  The caller
 * should do the appropriate change.
 */
void
tcp_process_options(tcp_t *tcp, tcph_t *tcph)
{
	int options;
	tcp_opt_t tcpopt;
	uint32_t mss_max;
	char *tmp_tcph;

	tcpopt.tcp = NULL;
	options = tcp_parse_options(tcph, &tcpopt);

	/*
	 * Process MSS option.  Note that MSS option value does not account
	 * for IP or TCP options.  This means that it is equal to MTU - minimum
	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
	 * IPv6.
	 */
	if (!(options & TCP_OPT_MSS_PRESENT)) {
		tcpopt.tcp_opt_mss = tcp_mss_def_ipv4;
	} else {
		if (tcp->tcp_ipversion == IPV4_VERSION)
			mss_max = tcp_mss_max_ipv4;
		if (tcpopt.tcp_opt_mss < tcp_mss_min)
			tcpopt.tcp_opt_mss = tcp_mss_min;
		else if (tcpopt.tcp_opt_mss > mss_max)
			tcpopt.tcp_opt_mss = mss_max;
	}

	/* Process Window Scale option. */
	if (options & TCP_OPT_WSCALE_PRESENT) {
		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
		tcp->tcp_snd_ws_ok = B_TRUE;
	} else {
		tcp->tcp_snd_ws = B_FALSE;
		tcp->tcp_snd_ws_ok = B_FALSE;
		tcp->tcp_rcv_ws = B_FALSE;
	}

	/* Process Timestamp option. */
	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
	    (tcp->tcp_snd_ts_ok || !tcp->tcp_active_open)) {
		tmp_tcph = (char *)tcp->tcp_tcph;

		tcp->tcp_snd_ts_ok = B_TRUE;
		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
		tcp->tcp_last_rcv_lbolt = prom_gettime();
		assert(OK_32PTR(tmp_tcph));
		assert(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);

		/* Fill in our template header with basic timestamp option. */
		tmp_tcph += tcp->tcp_tcp_hdr_len;
		tmp_tcph[0] = TCPOPT_NOP;
		tmp_tcph[1] = TCPOPT_NOP;
		tmp_tcph[2] = TCPOPT_TSTAMP;
		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
		tcp->tcp_hdr_len += TCPOPT_REAL_TS_LEN;
		tcp->tcp_tcp_hdr_len += TCPOPT_REAL_TS_LEN;
		tcp->tcp_tcph->th_offset_and_rsrvd[0] += (3 << 4);
	} else {
		tcp->tcp_snd_ts_ok = B_FALSE;
	}

	/*
	 * Process SACK options.  If SACK is enabled for this connection,
	 * then allocate the SACK info structure.
	 */
	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
	    (tcp->tcp_snd_sack_ok ||
	    (tcp_sack_permitted != 0 && !tcp->tcp_active_open))) {
		/* This should be true only in the passive case. */
		if (tcp->tcp_sack_info == NULL) {
			tcp->tcp_sack_info = (tcp_sack_info_t *)bkmem_zalloc(
			    sizeof (tcp_sack_info_t));
		}
		if (tcp->tcp_sack_info == NULL) {
			tcp->tcp_snd_sack_ok = B_FALSE;
		} else {
			tcp->tcp_snd_sack_ok = B_TRUE;
			if (tcp->tcp_snd_ts_ok) {
				tcp->tcp_max_sack_blk = 3;
			} else {
				tcp->tcp_max_sack_blk = 4;
			}
		}
	} else {
		/*
		 * Resetting tcp_snd_sack_ok to B_FALSE so that
		 * no SACK info will be used for this
		 * connection.  This assumes that SACK usage
		 * permission is negotiated.  This may need
		 * to be changed once this is clarified.
		 */
		if (tcp->tcp_sack_info != NULL) {
			bkmem_free((caddr_t)tcp->tcp_sack_info,
			    sizeof (tcp_sack_info_t));
			tcp->tcp_sack_info = NULL;
		}
		tcp->tcp_snd_sack_ok = B_FALSE;
	}

	/*
	 * Now we know the exact TCP/IP header length, subtract
	 * that from tcp_mss to get our side's MSS.
	 */
	tcp->tcp_mss -= tcp->tcp_hdr_len;
	/*
	 * Here we assume that the other side's header size will be equal to
	 * our header size.  We calculate the real MSS accordingly.  Need to
	 * take into additional stuffs IPsec puts in.
	 *
	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
	 */
	tcpopt.tcp_opt_mss -= tcp->tcp_hdr_len -
	    (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH);

	/*
	 * Set MSS to the smaller one of both ends of the connection.
	 * We should not have called tcp_mss_set() before, but our
	 * side of the MSS should have been set to a proper value
	 * by tcp_adapt_ire().  tcp_mss_set() will also set up the
	 * STREAM head parameters properly.
	 *
	 * If we have a larger-than-16-bit window but the other side
	 * didn't want to do window scale, tcp_rwnd_set() will take
	 * care of that.
	 */
	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss));
}

/*
 * This function does PAWS protection check.  Returns B_TRUE if the
 * segment passes the PAWS test, else returns B_FALSE.
 */
boolean_t
tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp)
{
	uint8_t	flags;
	int	options;
	uint8_t *up;

	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
	/*
	 * If timestamp option is aligned nicely, get values inline,
	 * otherwise call general routine to parse.  Only do that
	 * if timestamp is the only option.
	 */
	if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH +
	    TCPOPT_REAL_TS_LEN &&
	    OK_32PTR((up = ((uint8_t *)tcph) +
	    TCP_MIN_HEADER_LENGTH)) &&
	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));

		options = TCP_OPT_TSTAMP_PRESENT;
	} else {
		if (tcp->tcp_snd_sack_ok) {
			tcpoptp->tcp = tcp;
		} else {
			tcpoptp->tcp = NULL;
		}
		options = tcp_parse_options(tcph, tcpoptp);
	}

	if (options & TCP_OPT_TSTAMP_PRESENT) {
		/*
		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
		 * regardless of the timestamp, page 18 RFC 1323.bis.
		 */
		if ((flags & TH_RST) == 0 &&
		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
		    tcp->tcp_ts_recent)) {
			if (TSTMP_LT(prom_gettime(),
			    tcp->tcp_last_rcv_lbolt + PAWS_TIMEOUT)) {
				/* This segment is not acceptable. */
				return (B_FALSE);
			} else {
				/*
				 * Connection has been idle for
				 * too long.  Reset the timestamp
				 * and assume the segment is valid.
				 */
				tcp->tcp_ts_recent =
				    tcpoptp->tcp_opt_ts_val;
			}
		}
	} else {
		/*
		 * If we don't get a timestamp on every packet, we
		 * figure we can't really trust 'em, so we stop sending
		 * and parsing them.
		 */
		tcp->tcp_snd_ts_ok = B_FALSE;

		tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
		tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
		tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4);
		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN);
		if (tcp->tcp_snd_sack_ok) {
			assert(tcp->tcp_sack_info != NULL);
			tcp->tcp_max_sack_blk = 4;
		}
	}
	return (B_TRUE);
}

/*
 * tcp_get_seg_mp() is called to get the pointer to a segment in the
 * send queue which starts at the given seq. no.
 *
 * Parameters:
 *	tcp_t *tcp: the tcp instance pointer.
 *	uint32_t seq: the starting seq. no of the requested segment.
 *	int32_t *off: after the execution, *off will be the offset to
 *		the returned mblk which points to the requested seq no.
 *
 * Return:
 *	A mblk_t pointer pointing to the requested segment in send queue.
 */
static mblk_t *
tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
{
	int32_t	cnt;
	mblk_t	*mp;

	/* Defensive coding.  Make sure we don't send incorrect data. */
	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt) ||
	    off == NULL) {
		return (NULL);
	}
	cnt = seq - tcp->tcp_suna;
	mp = tcp->tcp_xmit_head;
	while (cnt > 0 && mp) {
		cnt -= mp->b_wptr - mp->b_rptr;
		if (cnt < 0) {
			cnt += mp->b_wptr - mp->b_rptr;
			break;
		}
		mp = mp->b_cont;
	}
	assert(mp != NULL);
	*off = cnt;
	return (mp);
}

/*
 * This function handles all retransmissions if SACK is enabled for this
 * connection.  First it calculates how many segments can be retransmitted
 * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
 * segments.  A segment is eligible if sack_cnt for that segment is greater
 * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
 * all eligible segments, it checks to see if TCP can send some new segments
 * (fast recovery).  If it can, it returns 1.  Otherwise it returns 0.
 *
 * Parameters:
 *	tcp_t *tcp: the tcp structure of the connection.
 *
 * Return:
 *	1 if the pipe is not full (new data can be sent), 0 otherwise
 */
static int32_t
tcp_sack_rxmit(tcp_t *tcp, int sock_id)
{
	notsack_blk_t	*notsack_blk;
	int32_t		usable_swnd;
	int32_t		mss;
	uint32_t	seg_len;
	mblk_t		*xmit_mp;

	assert(tcp->tcp_sack_info != NULL);
	assert(tcp->tcp_notsack_list != NULL);
	assert(tcp->tcp_rexmit == B_FALSE);

	/* Defensive coding in case there is a bug... */
	if (tcp->tcp_notsack_list == NULL) {
		return (0);
	}
	notsack_blk = tcp->tcp_notsack_list;
	mss = tcp->tcp_mss;

	/*
	 * Limit the num of outstanding data in the network to be
	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
	 */
	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;

	/* At least retransmit 1 MSS of data. */
	if (usable_swnd <= 0) {
		usable_swnd = mss;
	}

	/* Make sure no new RTT samples will be taken. */
	tcp->tcp_csuna = tcp->tcp_snxt;

	notsack_blk = tcp->tcp_notsack_list;
	while (usable_swnd > 0) {
		mblk_t		*snxt_mp, *tmp_mp;
		tcp_seq		begin = tcp->tcp_sack_snxt;
		tcp_seq		end;
		int32_t		off;

		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
			if (SEQ_GT(notsack_blk->end, begin) &&
			    (notsack_blk->sack_cnt >=
			    tcp_dupack_fast_retransmit)) {
				end = notsack_blk->end;
				if (SEQ_LT(begin, notsack_blk->begin)) {
					begin = notsack_blk->begin;
				}
				break;
			}
		}
		/*
		 * All holes are filled.  Manipulate tcp_cwnd to send more
		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
		 * set to tcp_cwnd_ssthresh.
		 */
		if (notsack_blk == NULL) {
			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
			if (usable_swnd <= 0) {
				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
				assert(tcp->tcp_cwnd > 0);
				return (0);
			} else {
				usable_swnd = usable_swnd / mss;
				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
				    MAX(usable_swnd * mss, mss);
				return (1);
			}
		}

		/*
		 * Note that we may send more than usable_swnd allows here
		 * because of round off, but no more than 1 MSS of data.
		 */
		seg_len = end - begin;
		if (seg_len > mss)
			seg_len = mss;
		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
		assert(snxt_mp != NULL);
		/* This should not happen.  Defensive coding again... */
		if (snxt_mp == NULL) {
			return (0);
		}

		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);

		if (xmit_mp == NULL)
			return (0);

		usable_swnd -= seg_len;
		tcp->tcp_pipe += seg_len;
		tcp->tcp_sack_snxt = begin + seg_len;
		TCP_DUMP_PACKET("tcp_sack_rxmit", xmit_mp);
		(void) ipv4_tcp_output(sock_id, xmit_mp);
		freeb(xmit_mp);

		/*
		 * Update the send timestamp to avoid false retransmission.
		 * Note. use uintptr_t to suppress the gcc warning.
		 */
		snxt_mp->b_prev = (mblk_t *)(uintptr_t)prom_gettime();

		BUMP_MIB(tcp_mib.tcpRetransSegs);
		UPDATE_MIB(tcp_mib.tcpRetransBytes, seg_len);
		BUMP_MIB(tcp_mib.tcpOutSackRetransSegs);
		/*
		 * Update tcp_rexmit_max to extend this SACK recovery phase.
		 * This happens when new data sent during fast recovery is
		 * also lost.  If TCP retransmits those new data, it needs
		 * to extend SACK recover phase to avoid starting another
		 * fast retransmit/recovery unnecessarily.
		 */
		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
		}
	}
	return (0);
}

static void
tcp_rput_data(tcp_t *tcp, mblk_t *mp, int sock_id)
{
	uchar_t		*rptr;
	struct ip	*iph;
	tcp_t		*tcp1;
	tcpha_t		*tcph;
	uint32_t	seg_ack;
	int		seg_len;
	uint_t		ip_hdr_len;
	uint32_t	seg_seq;
	mblk_t		*mp1;
	uint_t		flags;
	uint32_t	new_swnd = 0;
	int		mss;
	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
	int32_t		gap;
	int32_t		rgap;
	tcp_opt_t	tcpopt;
	int32_t		bytes_acked;
	int		npkt;
	uint32_t	cwnd;
	uint32_t	add;

#ifdef DEBUG
	printf("tcp_rput_data sock %d mp %x mp_datap %x #################\n",
	    sock_id, mp, mp->b_datap);
#endif

	/* Dump the packet when debugging. */
	TCP_DUMP_PACKET("tcp_rput_data", mp);

	assert(OK_32PTR(mp->b_rptr));

	rptr = mp->b_rptr;
	iph = (struct ip *)rptr;
	ip_hdr_len = IPH_HDR_LENGTH(rptr);
	if (ip_hdr_len != IP_SIMPLE_HDR_LENGTH) {
#ifdef DEBUG
		printf("Not simple IP header\n");
#endif
		/* We cannot handle IP option yet... */
		tcp_drops++;
		freeb(mp);
		return;
	}
	/* The TCP header must be aligned. */
	tcph = (tcpha_t *)&rptr[ip_hdr_len];
	seg_seq = ntohl(tcph->tha_seq);
	seg_ack = ntohl(tcph->tha_ack);
	assert((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
	seg_len = (int)(mp->b_wptr - rptr) -
	    (ip_hdr_len + TCP_HDR_LENGTH(((tcph_t *)tcph)));
	/* In inetboot, b_cont should always be NULL. */
	assert(mp->b_cont == NULL);

	/* Verify the checksum. */
	if (tcp_verify_cksum(mp) < 0) {
#ifdef DEBUG
		printf("tcp_rput_data: wrong cksum\n");
#endif
		freemsg(mp);
		return;
	}

	/*
	 * This segment is not for us, try to find its
	 * intended receiver.
	 */
	if (tcp == NULL ||
	    tcph->tha_lport != tcp->tcp_fport ||
	    tcph->tha_fport != tcp->tcp_lport ||
	    iph->ip_src.s_addr != tcp->tcp_remote ||
	    iph->ip_dst.s_addr != tcp->tcp_bound_source) {
#ifdef DEBUG
		printf("tcp_rput_data: not for us, state %d\n",
		    tcp->tcp_state);
#endif
		/*
		 * First try to find a established connection.  If none
		 * is found, look for a listener.
		 *
		 * If a listener is found, we need to check to see if the
		 * incoming segment is for one of its eagers.  If it is,
		 * give it to the eager.  If not, listener should take care
		 * of it.
		 */
		if ((tcp1 = tcp_lookup_ipv4(iph, tcph, TCPS_SYN_SENT,
		    &sock_id)) != NULL ||
		    (tcp1 = tcp_lookup_listener_ipv4(iph->ip_dst.s_addr,
		    tcph->tha_fport, &sock_id)) != NULL) {
			if (tcp1->tcp_state == TCPS_LISTEN) {
				if ((tcp = tcp_lookup_eager_ipv4(tcp1,
				    iph, tcph)) == NULL) {
					/* No eager... sent to listener */
#ifdef DEBUG
					printf("found the listener: %s\n",
					    tcp_display(tcp1, NULL,
					    DISP_ADDR_AND_PORT));
#endif
					tcp = tcp1;
				}
#ifdef DEBUG
				else {
					printf("found the eager: %s\n",
					    tcp_display(tcp, NULL,
					    DISP_ADDR_AND_PORT));
				}
#endif
			} else {
				/* Non listener found... */
#ifdef DEBUG
				printf("found the connection: %s\n",
				    tcp_display(tcp1, NULL,
				    DISP_ADDR_AND_PORT));
#endif
				tcp = tcp1;
			}
		} else {
			/*
			 * No connection for this segment...
			 * Send a RST to the other side.
			 */
			tcp_xmit_listeners_reset(sock_id, mp, ip_hdr_len);
			return;
		}
	}

	flags = tcph->tha_flags & 0xFF;
	BUMP_MIB(tcp_mib.tcpInSegs);
	if (tcp->tcp_state == TCPS_TIME_WAIT) {
		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
		    seg_len, (tcph_t *)tcph, sock_id);
		return;
	}
	/*
	 * From this point we can assume that the tcp is not compressed,
	 * since we would have branched off to tcp_time_wait_processing()
	 * in such a case.
	 */
	assert(tcp != NULL && tcp->tcp_state != TCPS_TIME_WAIT);

	/*
	 * After this point, we know we have the correct TCP, so update
	 * the receive time.
	 */
	tcp->tcp_last_recv_time = prom_gettime();

	/* In inetboot, we do not handle urgent pointer... */
	if (flags & TH_URG) {
		freemsg(mp);
		DEBUG_1("tcp_rput_data(%d): received segment with urgent "
		    "pointer\n", sock_id);
		tcp_drops++;
		return;
	}

	switch (tcp->tcp_state) {
	case TCPS_LISTEN:
		if ((flags & (TH_RST | TH_ACK | TH_SYN)) != TH_SYN) {
			if (flags & TH_RST) {
				freemsg(mp);
				return;
			}
			if (flags & TH_ACK) {
				tcp_xmit_early_reset("TCPS_LISTEN-TH_ACK",
				    sock_id, mp, seg_ack, 0, TH_RST,
				    ip_hdr_len);
				return;
			}
			if (!(flags & TH_SYN)) {
				freemsg(mp);
				return;
			}
			printf("tcp_rput_data: %d\n", __LINE__);
			prom_panic("inetboot");
		}
		if (tcp->tcp_conn_req_max > 0) {
			tcp = tcp_conn_request(tcp, mp, sock_id, ip_hdr_len);
			if (tcp == NULL) {
				freemsg(mp);
				return;
			}
#ifdef DEBUG
			printf("tcp_rput_data: new tcp created\n");
#endif
		}
		tcp->tcp_irs = seg_seq;
		tcp->tcp_rack = seg_seq;
		tcp->tcp_rnxt = seg_seq + 1;
		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
		BUMP_MIB(tcp_mib.tcpPassiveOpens);
		goto syn_rcvd;
	case TCPS_SYN_SENT:
		if (flags & TH_ACK) {
			/*
			 * Note that our stack cannot send data before a
			 * connection is established, therefore the
			 * following check is valid.  Otherwise, it has
			 * to be changed.
			 */
			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
				if (flags & TH_RST) {
					freemsg(mp);
					return;
				}
				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
				    tcp, mp, seg_ack, 0, TH_RST,
				    ip_hdr_len, sock_id);
				return;
			}
			assert(tcp->tcp_suna + 1 == seg_ack);
		}
		if (flags & TH_RST) {
			freemsg(mp);
			if (flags & TH_ACK) {
				tcp_clean_death(sock_id, tcp, ECONNREFUSED);
			}
			return;
		}
		if (!(flags & TH_SYN)) {
			freemsg(mp);
			return;
		}

		/* Process all TCP options. */
		tcp_process_options(tcp, (tcph_t *)tcph);
		/*
		 * The following changes our rwnd to be a multiple of the
		 * MIN(peer MSS, our MSS) for performance reason.
		 */
		(void) tcp_rwnd_set(tcp, MSS_ROUNDUP(tcp->tcp_rwnd,
		    tcp->tcp_mss));

		/* Is the other end ECN capable? */
		if (tcp->tcp_ecn_ok) {
			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
				tcp->tcp_ecn_ok = B_FALSE;
			}
		}
		/*
		 * Clear ECN flags because it may interfere with later
		 * processing.
		 */
		flags &= ~(TH_ECE|TH_CWR);

		tcp->tcp_irs = seg_seq;
		tcp->tcp_rack = seg_seq;
		tcp->tcp_rnxt = seg_seq + 1;
		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);

		if (flags & TH_ACK) {
			/* One for the SYN */
			tcp->tcp_suna = tcp->tcp_iss + 1;
			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
			tcp->tcp_state = TCPS_ESTABLISHED;

			/*
			 * If SYN was retransmitted, need to reset all
			 * retransmission info.  This is because this
			 * segment will be treated as a dup ACK.
			 */
			if (tcp->tcp_rexmit) {
				tcp->tcp_rexmit = B_FALSE;
				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
				tcp->tcp_rexmit_max = tcp->tcp_snxt;
				tcp->tcp_snd_burst = TCP_CWND_NORMAL;

				/*
				 * Set tcp_cwnd back to 1 MSS, per
				 * recommendation from
				 * draft-floyd-incr-init-win-01.txt,
				 * Increasing TCP's Initial Window.
				 */
				tcp->tcp_cwnd = tcp->tcp_mss;
			}

			tcp->tcp_swl1 = seg_seq;
			tcp->tcp_swl2 = seg_ack;

			new_swnd = BE16_TO_U16(((tcph_t *)tcph)->th_win);
			tcp->tcp_swnd = new_swnd;
			if (new_swnd > tcp->tcp_max_swnd)
				tcp->tcp_max_swnd = new_swnd;

			/*
			 * Always send the three-way handshake ack immediately
			 * in order to make the connection complete as soon as
			 * possible on the accepting host.
			 */
			flags |= TH_ACK_NEEDED;
			/*
			 * Check to see if there is data to be sent.  If
			 * yes, set the transmit flag.  Then check to see
			 * if received data processing needs to be done.
			 * If not, go straight to xmit_check.  This short
			 * cut is OK as we don't support T/TCP.
			 */
			if (tcp->tcp_unsent)
				flags |= TH_XMIT_NEEDED;

			if (seg_len == 0) {
				freemsg(mp);
				goto xmit_check;
			}

			flags &= ~TH_SYN;
			seg_seq++;
			break;
		}
		syn_rcvd:
		tcp->tcp_state = TCPS_SYN_RCVD;
		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
		if (mp1 != NULL) {
			TCP_DUMP_PACKET("tcp_rput_data replying SYN", mp1);
			(void) ipv4_tcp_output(sock_id, mp1);
			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
			freeb(mp1);
			/*
			 * Let's wait till our SYN has been ACKED since we
			 * don't have a timer.
			 */
			if (tcp_state_wait(sock_id, tcp, TCPS_ALL_ACKED) < 0) {
				freemsg(mp);
				return;
			}
		}
		freemsg(mp);
		return;
	default:
		break;
	}
	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH((tcph_t *)tcph);
	new_swnd = ntohs(tcph->tha_win) <<
	    ((flags & TH_SYN) ? 0 : tcp->tcp_snd_ws);
	mss = tcp->tcp_mss;

	if (tcp->tcp_snd_ts_ok) {
		if (!tcp_paws_check(tcp, (tcph_t *)tcph, &tcpopt)) {
			/*
			 * This segment is not acceptable.
			 * Drop it and send back an ACK.
			 */
			freemsg(mp);
			flags |= TH_ACK_NEEDED;
			goto ack_check;
		}
	} else if (tcp->tcp_snd_sack_ok) {
		assert(tcp->tcp_sack_info != NULL);
		tcpopt.tcp = tcp;
		/*
		 * SACK info in already updated in tcp_parse_options.  Ignore
		 * all other TCP options...
		 */
		(void) tcp_parse_options((tcph_t *)tcph, &tcpopt);
	}
try_again:;
	gap = seg_seq - tcp->tcp_rnxt;
	rgap = tcp->tcp_rwnd - (gap + seg_len);
	/*
	 * gap is the amount of sequence space between what we expect to see
	 * and what we got for seg_seq.  A positive value for gap means
	 * something got lost.  A negative value means we got some old stuff.
	 */
	if (gap < 0) {
		/* Old stuff present.  Is the SYN in there? */
		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
		    (seg_len != 0)) {
			flags &= ~TH_SYN;
			seg_seq++;
			/* Recompute the gaps after noting the SYN. */
			goto try_again;
		}
		BUMP_MIB(tcp_mib.tcpInDataDupSegs);
		UPDATE_MIB(tcp_mib.tcpInDataDupBytes,
		    (seg_len > -gap ? -gap : seg_len));
		/* Remove the old stuff from seg_len. */
		seg_len += gap;
		/*
		 * Anything left?
		 * Make sure to check for unack'd FIN when rest of data
		 * has been previously ack'd.
		 */
		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
			/*
			 * Resets are only valid if they lie within our offered
			 * window.  If the RST bit is set, we just ignore this
			 * segment.
			 */
			if (flags & TH_RST) {
				freemsg(mp);
				return;
			}

			/*
			 * This segment is "unacceptable".  None of its
			 * sequence space lies within our advertized window.
			 *
			 * Adjust seg_len to the original value for tracing.
			 */
			seg_len -= gap;
#ifdef DEBUG
			printf("tcp_rput: unacceptable, gap %d, rgap "
			    "%d, flags 0x%x, seg_seq %u, seg_ack %u, "
			    "seg_len %d, rnxt %u, snxt %u, %s",
			    gap, rgap, flags, seg_seq, seg_ack,
			    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
			    tcp_display(tcp, NULL, DISP_ADDR_AND_PORT));
#endif

			/*
			 * Arrange to send an ACK in response to the
			 * unacceptable segment per RFC 793 page 69. There
			 * is only one small difference between ours and the
			 * acceptability test in the RFC - we accept ACK-only
			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
			 * will be generated.
			 *
			 * Note that we have to ACK an ACK-only packet at least
			 * for stacks that send 0-length keep-alives with
			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
			 * section 4.2.3.6. As long as we don't ever generate
			 * an unacceptable packet in response to an incoming
			 * packet that is unacceptable, it should not cause
			 * "ACK wars".
			 */
			flags |=  TH_ACK_NEEDED;

			/*
			 * Continue processing this segment in order to use the
			 * ACK information it contains, but skip all other
			 * sequence-number processing.	Processing the ACK
			 * information is necessary in order to
			 * re-synchronize connections that may have lost
			 * synchronization.
			 *
			 * We clear seg_len and flag fields related to
			 * sequence number processing as they are not
			 * to be trusted for an unacceptable segment.
			 */
			seg_len = 0;
			flags &= ~(TH_SYN | TH_FIN | TH_URG);
			goto process_ack;
		}

		/* Fix seg_seq, and chew the gap off the front. */
		seg_seq = tcp->tcp_rnxt;
		do {
			mblk_t	*mp2;
			assert((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
			    (uintptr_t)UINT_MAX);
			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
			if (gap > 0) {
				mp->b_rptr = mp->b_wptr - gap;
				break;
			}
			mp2 = mp;
			mp = mp->b_cont;
			freeb(mp2);
		} while (gap < 0);
	}
	/*
	 * rgap is the amount of stuff received out of window.  A negative
	 * value is the amount out of window.
	 */
	if (rgap < 0) {
		mblk_t	*mp2;

		if (tcp->tcp_rwnd == 0)
			BUMP_MIB(tcp_mib.tcpInWinProbe);
		else {
			BUMP_MIB(tcp_mib.tcpInDataPastWinSegs);
			UPDATE_MIB(tcp_mib.tcpInDataPastWinBytes, -rgap);
		}

		/*
		 * seg_len does not include the FIN, so if more than
		 * just the FIN is out of window, we act like we don't
		 * see it.  (If just the FIN is out of window, rgap
		 * will be zero and we will go ahead and acknowledge
		 * the FIN.)
		 */
		flags &= ~TH_FIN;

		/* Fix seg_len and make sure there is something left. */
		seg_len += rgap;
		if (seg_len <= 0) {
			/*
			 * Resets are only valid if they lie within our offered
			 * window.  If the RST bit is set, we just ignore this
			 * segment.
			 */
			if (flags & TH_RST) {
				freemsg(mp);
				return;
			}

			/* Per RFC 793, we need to send back an ACK. */
			flags |= TH_ACK_NEEDED;

			/*
			 * If this is a zero window probe, continue to
			 * process the ACK part.  But we need to set seg_len
			 * to 0 to avoid data processing.  Otherwise just
			 * drop the segment and send back an ACK.
			 */
			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
				flags &= ~(TH_SYN | TH_URG);
				seg_len = 0;
				/* Let's see if we can update our rwnd */
				tcp_rcv_drain(sock_id, tcp);
				goto process_ack;
			} else {
				freemsg(mp);
				goto ack_check;
			}
		}
		/* Pitch out of window stuff off the end. */
		rgap = seg_len;
		mp2 = mp;
		do {
			assert((uintptr_t)(mp2->b_wptr -
			    mp2->b_rptr) <= (uintptr_t)INT_MAX);
			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
			if (rgap < 0) {
				mp2->b_wptr += rgap;
				if ((mp1 = mp2->b_cont) != NULL) {
					mp2->b_cont = NULL;
					freemsg(mp1);
				}
				break;
			}
		} while ((mp2 = mp2->b_cont) != NULL);
	}
ok:;
	/*
	 * TCP should check ECN info for segments inside the window only.
	 * Therefore the check should be done here.
	 */
	if (tcp->tcp_ecn_ok) {
		uchar_t tos = ((struct ip *)rptr)->ip_tos;

		if (flags & TH_CWR) {
			tcp->tcp_ecn_echo_on = B_FALSE;
		}
		/*
		 * Note that both ECN_CE and CWR can be set in the
		 * same segment.  In this case, we once again turn
		 * on ECN_ECHO.
		 */
		if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
			tcp->tcp_ecn_echo_on = B_TRUE;
		}
	}

	/*
	 * Check whether we can update tcp_ts_recent.  This test is
	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
	 * Extensions for High Performance: An Update", Internet Draft.
	 */
	if (tcp->tcp_snd_ts_ok &&
	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
		tcp->tcp_last_rcv_lbolt = prom_gettime();
	}

	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
		/*
		 * FIN in an out of order segment.  We record this in
		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
		 * Clear the FIN so that any check on FIN flag will fail.
		 * Remember that FIN also counts in the sequence number
		 * space.  So we need to ack out of order FIN only segments.
		 */
		if (flags & TH_FIN) {
			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
			flags &= ~TH_FIN;
			flags |= TH_ACK_NEEDED;
		}
		if (seg_len > 0) {
			/* Fill in the SACK blk list. */
			if (tcp->tcp_snd_sack_ok) {
				assert(tcp->tcp_sack_info != NULL);
				tcp_sack_insert(tcp->tcp_sack_list,
				    seg_seq, seg_seq + seg_len,
				    &(tcp->tcp_num_sack_blk));
			}

			/*
			 * Attempt reassembly and see if we have something
			 * ready to go.
			 */
			mp = tcp_reass(tcp, mp, seg_seq);
			/* Always ack out of order packets */
			flags |= TH_ACK_NEEDED | TH_PUSH;
			if (mp != NULL) {
				assert((uintptr_t)(mp->b_wptr -
				    mp->b_rptr) <= (uintptr_t)INT_MAX);
				seg_len = mp->b_cont ? msgdsize(mp) :
					(int)(mp->b_wptr - mp->b_rptr);
				seg_seq = tcp->tcp_rnxt;
				/*
				 * A gap is filled and the seq num and len
				 * of the gap match that of a previously
				 * received FIN, put the FIN flag back in.
				 */
				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
					flags |= TH_FIN;
					tcp->tcp_valid_bits &=
					    ~TCP_OFO_FIN_VALID;
				}
			} else {
				/*
				 * Keep going even with NULL mp.
				 * There may be a useful ACK or something else
				 * we don't want to miss.
				 *
				 * But TCP should not perform fast retransmit
				 * because of the ack number.  TCP uses
				 * seg_len == 0 to determine if it is a pure
				 * ACK.  And this is not a pure ACK.
				 */
				seg_len = 0;
				ofo_seg = B_TRUE;
			}
		}
	} else if (seg_len > 0) {
		BUMP_MIB(tcp_mib.tcpInDataInorderSegs);
		UPDATE_MIB(tcp_mib.tcpInDataInorderBytes, seg_len);
		/*
		 * If an out of order FIN was received before, and the seq
		 * num and len of the new segment match that of the FIN,
		 * put the FIN flag back in.
		 */
		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
			flags |= TH_FIN;
			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
		}
	}
	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
	if (flags & TH_RST) {
		freemsg(mp);
		switch (tcp->tcp_state) {
		case TCPS_SYN_RCVD:
			(void) tcp_clean_death(sock_id, tcp, ECONNREFUSED);
			break;
		case TCPS_ESTABLISHED:
		case TCPS_FIN_WAIT_1:
		case TCPS_FIN_WAIT_2:
		case TCPS_CLOSE_WAIT:
			(void) tcp_clean_death(sock_id, tcp, ECONNRESET);
			break;
		case TCPS_CLOSING:
		case TCPS_LAST_ACK:
			(void) tcp_clean_death(sock_id, tcp, 0);
			break;
		default:
			assert(tcp->tcp_state != TCPS_TIME_WAIT);
			(void) tcp_clean_death(sock_id, tcp, ENXIO);
			break;
		}
		return;
	}
	if (flags & TH_SYN) {
		/*
		 * See RFC 793, Page 71
		 *
		 * The seq number must be in the window as it should
		 * be "fixed" above.  If it is outside window, it should
		 * be already rejected.  Note that we allow seg_seq to be
		 * rnxt + rwnd because we want to accept 0 window probe.
		 */
		assert(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
		freemsg(mp);
		/*
		 * If the ACK flag is not set, just use our snxt as the
		 * seq number of the RST segment.
		 */
		if (!(flags & TH_ACK)) {
			seg_ack = tcp->tcp_snxt;
		}
		tcp_xmit_ctl("TH_SYN", tcp, NULL, seg_ack,
		    seg_seq + 1, TH_RST|TH_ACK, 0, sock_id);
		assert(tcp->tcp_state != TCPS_TIME_WAIT);
		(void) tcp_clean_death(sock_id, tcp, ECONNRESET);
		return;
	}

process_ack:
	if (!(flags & TH_ACK)) {
#ifdef DEBUG
		printf("No ack in segment, dropped it, seq:%x\n", seg_seq);
#endif
		freemsg(mp);
		goto xmit_check;
	}
	}
	bytes_acked = (int)(seg_ack - tcp->tcp_suna);

	if (tcp->tcp_state == TCPS_SYN_RCVD) {
		tcp_t	*listener = tcp->tcp_listener;
#ifdef DEBUG
		printf("Done with eager 3-way handshake\n");
#endif
		/*
		 * NOTE: RFC 793 pg. 72 says this should be 'bytes_acked < 0'
		 * but that would mean we have an ack that ignored our SYN.
		 */
		if (bytes_acked < 1 || SEQ_GT(seg_ack, tcp->tcp_snxt)) {
			freemsg(mp);
			tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
			    tcp, NULL, seg_ack, 0, TH_RST, 0, sock_id);
			return;
		}

		/*
		 * if the conn_req_q is full defer processing
		 * until space is availabe after accept()
		 * processing
		 */
		if (listener->tcp_conn_req_cnt_q <
		    listener->tcp_conn_req_max) {
			tcp_t *tail;

			listener->tcp_conn_req_cnt_q0--;
			listener->tcp_conn_req_cnt_q++;

			/* Move from SYN_RCVD to ESTABLISHED list  */
			tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
				tcp->tcp_eager_prev_q0;
			tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
				tcp->tcp_eager_next_q0;
			tcp->tcp_eager_prev_q0 = NULL;
			tcp->tcp_eager_next_q0 = NULL;

			/*
			 * Insert at end of the queue because sockfs
			 * sends down T_CONN_RES in chronological
			 * order. Leaving the older conn indications
			 * at front of the queue helps reducing search
			 * time.
			 */
			tail = listener->tcp_eager_last_q;
			if (tail != NULL) {
				tail->tcp_eager_next_q = tcp;
			} else {
				listener->tcp_eager_next_q = tcp;
			}
			listener->tcp_eager_last_q = tcp;
			tcp->tcp_eager_next_q = NULL;
		} else {
			/*
			 * Defer connection on q0 and set deferred
			 * connection bit true
			 */
			tcp->tcp_conn_def_q0 = B_TRUE;

			/* take tcp out of q0 ... */
			tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
			    tcp->tcp_eager_next_q0;
			tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
			    tcp->tcp_eager_prev_q0;

			/* ... and place it at the end of q0 */
			tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
			tcp->tcp_eager_next_q0 = listener;
			listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
			listener->tcp_eager_prev_q0 = tcp;
		}

		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
		bytes_acked--;

		/*
		 * If SYN was retransmitted, need to reset all
		 * retransmission info as this segment will be
		 * treated as a dup ACK.
		 */
		if (tcp->tcp_rexmit) {
			tcp->tcp_rexmit = B_FALSE;
			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
			tcp->tcp_rexmit_max = tcp->tcp_snxt;
			tcp->tcp_snd_burst = TCP_CWND_NORMAL;
			tcp->tcp_ms_we_have_waited = 0;
			tcp->tcp_cwnd = mss;
		}

		/*
		 * We set the send window to zero here.
		 * This is needed if there is data to be
		 * processed already on the queue.
		 * Later (at swnd_update label), the
		 * "new_swnd > tcp_swnd" condition is satisfied
		 * the XMIT_NEEDED flag is set in the current
		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
		 * called if there is already data on queue in
		 * this state.
		 */
		tcp->tcp_swnd = 0;

		if (new_swnd > tcp->tcp_max_swnd)
			tcp->tcp_max_swnd = new_swnd;
		tcp->tcp_swl1 = seg_seq;
		tcp->tcp_swl2 = seg_ack;
		tcp->tcp_state = TCPS_ESTABLISHED;
		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
	}
	/* This code follows 4.4BSD-Lite2 mostly. */
	if (bytes_acked < 0)
		goto est;

	/*
	 * If TCP is ECN capable and the congestion experience bit is
	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
	 * done once per window (or more loosely, per RTT).
	 */
	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
		tcp->tcp_cwr = B_FALSE;
	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
		if (!tcp->tcp_cwr) {
			npkt = (MIN(tcp->tcp_cwnd, tcp->tcp_swnd) >> 1) / mss;
			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
			tcp->tcp_cwnd = npkt * mss;
			/*
			 * If the cwnd is 0, use the timer to clock out
			 * new segments.  This is required by the ECN spec.
			 */
			if (npkt == 0) {
				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
				/*
				 * This makes sure that when the ACK comes
				 * back, we will increase tcp_cwnd by 1 MSS.
				 */
				tcp->tcp_cwnd_cnt = 0;
			}
			tcp->tcp_cwr = B_TRUE;
			/*
			 * This marks the end of the current window of in
			 * flight data.  That is why we don't use
			 * tcp_suna + tcp_swnd.  Only data in flight can
			 * provide ECN info.
			 */
			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
			tcp->tcp_ecn_cwr_sent = B_FALSE;
		}
	}

	mp1 = tcp->tcp_xmit_head;
	if (bytes_acked == 0) {
		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
			int dupack_cnt;

			BUMP_MIB(tcp_mib.tcpInDupAck);
			/*
			 * Fast retransmit.  When we have seen exactly three
			 * identical ACKs while we have unacked data
			 * outstanding we take it as a hint that our peer
			 * dropped something.
			 *
			 * If TCP is retransmitting, don't do fast retransmit.
			 */
			if (mp1 != NULL && tcp->tcp_suna != tcp->tcp_snxt &&
			    ! tcp->tcp_rexmit) {
				/* Do Limited Transmit */
				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
				    tcp_dupack_fast_retransmit) {
					/*
					 * RFC 3042
					 *
					 * What we need to do is temporarily
					 * increase tcp_cwnd so that new
					 * data can be sent if it is allowed
					 * by the receive window (tcp_rwnd).
					 * tcp_wput_data() will take care of
					 * the rest.
					 *
					 * If the connection is SACK capable,
					 * only do limited xmit when there
					 * is SACK info.
					 *
					 * Note how tcp_cwnd is incremented.
					 * The first dup ACK will increase
					 * it by 1 MSS.  The second dup ACK
					 * will increase it by 2 MSS.  This
					 * means that only 1 new segment will
					 * be sent for each dup ACK.
					 */
					if (tcp->tcp_unsent > 0 &&
					    (!tcp->tcp_snd_sack_ok ||
					    (tcp->tcp_snd_sack_ok &&
					    tcp->tcp_notsack_list != NULL))) {
						tcp->tcp_cwnd += mss <<
						    (tcp->tcp_dupack_cnt - 1);
						flags |= TH_LIMIT_XMIT;
					}
				} else if (dupack_cnt ==
				    tcp_dupack_fast_retransmit) {

				BUMP_MIB(tcp_mib.tcpOutFastRetrans);
				/*
				 * If we have reduced tcp_ssthresh
				 * because of ECN, do not reduce it again
				 * unless it is already one window of data
				 * away.  After one window of data, tcp_cwr
				 * should then be cleared.  Note that
				 * for non ECN capable connection, tcp_cwr
				 * should always be false.
				 *
				 * Adjust cwnd since the duplicate
				 * ack indicates that a packet was
				 * dropped (due to congestion.)
				 */
				if (!tcp->tcp_cwr) {
					npkt = (MIN(tcp->tcp_cwnd,
					    tcp->tcp_swnd) >> 1) / mss;
					if (npkt < 2)
						npkt = 2;
					tcp->tcp_cwnd_ssthresh = npkt * mss;
					tcp->tcp_cwnd = (npkt +
					    tcp->tcp_dupack_cnt) * mss;
				}
				if (tcp->tcp_ecn_ok) {
					tcp->tcp_cwr = B_TRUE;
					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
					tcp->tcp_ecn_cwr_sent = B_FALSE;
				}

				/*
				 * We do Hoe's algorithm.  Refer to her
				 * paper "Improving the Start-up Behavior
				 * of a Congestion Control Scheme for TCP,"
				 * appeared in SIGCOMM'96.
				 *
				 * Save highest seq no we have sent so far.
				 * Be careful about the invisible FIN byte.
				 */
				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
				    (tcp->tcp_unsent == 0)) {
					tcp->tcp_rexmit_max = tcp->tcp_fss;
				} else {
					tcp->tcp_rexmit_max = tcp->tcp_snxt;
				}

				/*
				 * Do not allow bursty traffic during.
				 * fast recovery.  Refer to Fall and Floyd's
				 * paper "Simulation-based Comparisons of
				 * Tahoe, Reno and SACK TCP" (in CCR ??)
				 * This is a best current practise.
				 */
				tcp->tcp_snd_burst = TCP_CWND_SS;

				/*
				 * For SACK:
				 * Calculate tcp_pipe, which is the
				 * estimated number of bytes in
				 * network.
				 *
				 * tcp_fack is the highest sack'ed seq num
				 * TCP has received.
				 *
				 * tcp_pipe is explained in the above quoted
				 * Fall and Floyd's paper.  tcp_fack is
				 * explained in Mathis and Mahdavi's
				 * "Forward Acknowledgment: Refining TCP
				 * Congestion Control" in SIGCOMM '96.
				 */
				if (tcp->tcp_snd_sack_ok) {
					assert(tcp->tcp_sack_info != NULL);
					if (tcp->tcp_notsack_list != NULL) {
						tcp->tcp_pipe = tcp->tcp_snxt -
						    tcp->tcp_fack;
						tcp->tcp_sack_snxt = seg_ack;
						flags |= TH_NEED_SACK_REXMIT;
					} else {
						/*
						 * Always initialize tcp_pipe
						 * even though we don't have
						 * any SACK info.  If later
						 * we get SACK info and
						 * tcp_pipe is not initialized,
						 * funny things will happen.
						 */
						tcp->tcp_pipe =
						    tcp->tcp_cwnd_ssthresh;
					}
				} else {
					flags |= TH_REXMIT_NEEDED;
				} /* tcp_snd_sack_ok */

				} else {
					/*
					 * Here we perform congestion
					 * avoidance, but NOT slow start.
					 * This is known as the Fast
					 * Recovery Algorithm.
					 */
					if (tcp->tcp_snd_sack_ok &&
					    tcp->tcp_notsack_list != NULL) {
						flags |= TH_NEED_SACK_REXMIT;
						tcp->tcp_pipe -= mss;
						if (tcp->tcp_pipe < 0)
							tcp->tcp_pipe = 0;
					} else {
					/*
					 * We know that one more packet has
					 * left the pipe thus we can update
					 * cwnd.
					 */
					cwnd = tcp->tcp_cwnd + mss;
					if (cwnd > tcp->tcp_cwnd_max)
						cwnd = tcp->tcp_cwnd_max;
					tcp->tcp_cwnd = cwnd;
					flags |= TH_XMIT_NEEDED;
					}
				}
			}
		} else if (tcp->tcp_zero_win_probe) {
			/*
			 * If the window has opened, need to arrange
			 * to send additional data.
			 */
			if (new_swnd != 0) {
				/* tcp_suna != tcp_snxt */
				/* Packet contains a window update */
				BUMP_MIB(tcp_mib.tcpInWinUpdate);
				tcp->tcp_zero_win_probe = 0;
				tcp->tcp_timer_backoff = 0;
				tcp->tcp_ms_we_have_waited = 0;

				/*
				 * Transmit starting with tcp_suna since
				 * the one byte probe is not ack'ed.
				 * If TCP has sent more than one identical
				 * probe, tcp_rexmit will be set.  That means
				 * tcp_ss_rexmit() will send out the one
				 * byte along with new data.  Otherwise,
				 * fake the retransmission.
				 */
				flags |= TH_XMIT_NEEDED;
				if (!tcp->tcp_rexmit) {
					tcp->tcp_rexmit = B_TRUE;
					tcp->tcp_dupack_cnt = 0;
					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
				}
			}
		}
		goto swnd_update;
	}

	/*
	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
	 * If the ACK value acks something that we have not yet sent, it might
	 * be an old duplicate segment.  Send an ACK to re-synchronize the
	 * other side.
	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
	 * state is handled above, so we can always just drop the segment and
	 * send an ACK here.
	 *
	 * Should we send ACKs in response to ACK only segments?
	 */
	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
		BUMP_MIB(tcp_mib.tcpInAckUnsent);
		/* drop the received segment */
		freemsg(mp);

		/* Send back an ACK. */
		mp = tcp_ack_mp(tcp);

		if (mp == NULL) {
			return;
		}
		BUMP_MIB(tcp_mib.tcpOutAck);
		(void) ipv4_tcp_output(sock_id, mp);
		freeb(mp);
		return;
	}

	/*
	 * TCP gets a new ACK, update the notsack'ed list to delete those
	 * blocks that are covered by this ACK.
	 */
	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
	}

	/*
	 * If we got an ACK after fast retransmit, check to see
	 * if it is a partial ACK.  If it is not and the congestion
	 * window was inflated to account for the other side's
	 * cached packets, retract it.  If it is, do Hoe's algorithm.
	 */
	if (tcp->tcp_dupack_cnt >= tcp_dupack_fast_retransmit) {
		assert(tcp->tcp_rexmit == B_FALSE);
		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
			tcp->tcp_dupack_cnt = 0;
			/*
			 * Restore the orig tcp_cwnd_ssthresh after
			 * fast retransmit phase.
			 */
			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
			}
			tcp->tcp_rexmit_max = seg_ack;
			tcp->tcp_cwnd_cnt = 0;
			tcp->tcp_snd_burst = TCP_CWND_NORMAL;

			/*
			 * Remove all notsack info to avoid confusion with
			 * the next fast retrasnmit/recovery phase.
			 */
			if (tcp->tcp_snd_sack_ok &&
			    tcp->tcp_notsack_list != NULL) {
				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
			}
		} else {
			if (tcp->tcp_snd_sack_ok &&
			    tcp->tcp_notsack_list != NULL) {
				flags |= TH_NEED_SACK_REXMIT;
				tcp->tcp_pipe -= mss;
				if (tcp->tcp_pipe < 0)
					tcp->tcp_pipe = 0;
			} else {
				/*
				 * Hoe's algorithm:
				 *
				 * Retransmit the unack'ed segment and
				 * restart fast recovery.  Note that we
				 * need to scale back tcp_cwnd to the
				 * original value when we started fast
				 * recovery.  This is to prevent overly
				 * aggressive behaviour in sending new
				 * segments.
				 */
				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
					tcp_dupack_fast_retransmit * mss;
				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
				BUMP_MIB(tcp_mib.tcpOutFastRetrans);
				flags |= TH_REXMIT_NEEDED;
			}
		}
	} else {
		tcp->tcp_dupack_cnt = 0;
		if (tcp->tcp_rexmit) {
			/*
			 * TCP is retranmitting.  If the ACK ack's all
			 * outstanding data, update tcp_rexmit_max and
			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
			 * to the correct value.
			 *
			 * Note that SEQ_LEQ() is used.  This is to avoid
			 * unnecessary fast retransmit caused by dup ACKs
			 * received when TCP does slow start retransmission
			 * after a time out.  During this phase, TCP may
			 * send out segments which are already received.
			 * This causes dup ACKs to be sent back.
			 */
			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
					tcp->tcp_rexmit_nxt = seg_ack;
				}
				if (seg_ack != tcp->tcp_rexmit_max) {
					flags |= TH_XMIT_NEEDED;
				}
			} else {
				tcp->tcp_rexmit = B_FALSE;
				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
				tcp->tcp_snd_burst = TCP_CWND_NORMAL;
			}
			tcp->tcp_ms_we_have_waited = 0;
		}
	}

	BUMP_MIB(tcp_mib.tcpInAckSegs);
	UPDATE_MIB(tcp_mib.tcpInAckBytes, bytes_acked);
	tcp->tcp_suna = seg_ack;
	if (tcp->tcp_zero_win_probe != 0) {
		tcp->tcp_zero_win_probe = 0;
		tcp->tcp_timer_backoff = 0;
	}

	/*
	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
	 * Note that it cannot be the SYN being ack'ed.  The code flow
	 * will not reach here.
	 */
	if (mp1 == NULL) {
		goto fin_acked;
	}

	/*
	 * Update the congestion window.
	 *
	 * If TCP is not ECN capable or TCP is ECN capable but the
	 * congestion experience bit is not set, increase the tcp_cwnd as
	 * usual.
	 */
	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
		cwnd = tcp->tcp_cwnd;
		add = mss;

		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
			/*
			 * This is to prevent an increase of less than 1 MSS of
			 * tcp_cwnd.  With partial increase, tcp_wput_data()
			 * may send out tinygrams in order to preserve mblk
			 * boundaries.
			 *
			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
			 * increased by 1 MSS for every RTTs.
			 */
			if (tcp->tcp_cwnd_cnt <= 0) {
				tcp->tcp_cwnd_cnt = cwnd + add;
			} else {
				tcp->tcp_cwnd_cnt -= add;
				add = 0;
			}
		}
		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
	}

	/* Can we update the RTT estimates? */
	if (tcp->tcp_snd_ts_ok) {
		/* Ignore zero timestamp echo-reply. */
		if (tcpopt.tcp_opt_ts_ecr != 0) {
			tcp_set_rto(tcp, (int32_t)(prom_gettime() -
			    tcpopt.tcp_opt_ts_ecr));
		}

		/* If needed, restart the timer. */
		if (tcp->tcp_set_timer == 1) {
			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
			tcp->tcp_set_timer = 0;
		}
		/*
		 * Update tcp_csuna in case the other side stops sending
		 * us timestamps.
		 */
		tcp->tcp_csuna = tcp->tcp_snxt;
	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
		/*
		 * An ACK sequence we haven't seen before, so get the RTT
		 * and update the RTO.
		 * Note. use uintptr_t to suppress the gcc warning.
		 */
		tcp_set_rto(tcp, (int32_t)(prom_gettime() -
		    (uint32_t)(uintptr_t)mp1->b_prev));

		/* Remeber the last sequence to be ACKed */
		tcp->tcp_csuna = seg_ack;
		if (tcp->tcp_set_timer == 1) {
			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
			tcp->tcp_set_timer = 0;
		}
	} else {
		BUMP_MIB(tcp_mib.tcpRttNoUpdate);
	}

	/* Eat acknowledged bytes off the xmit queue. */
	for (;;) {
		mblk_t	*mp2;
		uchar_t	*wptr;

		wptr = mp1->b_wptr;
		assert((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
		bytes_acked -= (int)(wptr - mp1->b_rptr);
		if (bytes_acked < 0) {
			mp1->b_rptr = wptr + bytes_acked;
			break;
		}
		mp1->b_prev = NULL;
		mp2 = mp1;
		mp1 = mp1->b_cont;
		freeb(mp2);
		if (bytes_acked == 0) {
			if (mp1 == NULL) {
				/* Everything is ack'ed, clear the tail. */
				tcp->tcp_xmit_tail = NULL;
				goto pre_swnd_update;
			}
			if (mp2 != tcp->tcp_xmit_tail)
				break;
			tcp->tcp_xmit_tail = mp1;
			assert((uintptr_t)(mp1->b_wptr -
			    mp1->b_rptr) <= (uintptr_t)INT_MAX);
			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
			    mp1->b_rptr);
			break;
		}
		if (mp1 == NULL) {
			/*
			 * More was acked but there is nothing more
			 * outstanding.  This means that the FIN was
			 * just acked or that we're talking to a clown.
			 */
fin_acked:
			assert(tcp->tcp_fin_sent);
			tcp->tcp_xmit_tail = NULL;
			if (tcp->tcp_fin_sent) {
				tcp->tcp_fin_acked = B_TRUE;
			} else {
				/*
				 * We should never got here because
				 * we have already checked that the
				 * number of bytes ack'ed should be
				 * smaller than or equal to what we
				 * have sent so far (it is the
				 * acceptability check of the ACK).
				 * We can only get here if the send
				 * queue is corrupted.
				 *
				 * Terminate the connection and
				 * panic the system.  It is better
				 * for us to panic instead of
				 * continuing to avoid other disaster.
				 */
				tcp_xmit_ctl(NULL, tcp, NULL, tcp->tcp_snxt,
				    tcp->tcp_rnxt, TH_RST|TH_ACK, 0, sock_id);
				printf("Memory corruption "
				    "detected for connection %s.\n",
				    tcp_display(tcp, NULL,
					DISP_ADDR_AND_PORT));
				/* We should never get here... */
				prom_panic("tcp_rput_data");
			}
			goto pre_swnd_update;
		}
		assert(mp2 != tcp->tcp_xmit_tail);
	}
	if (tcp->tcp_unsent) {
		flags |= TH_XMIT_NEEDED;
	}
pre_swnd_update:
	tcp->tcp_xmit_head = mp1;
swnd_update:
	/*
	 * The following check is different from most other implementations.
	 * For bi-directional transfer, when segments are dropped, the
	 * "normal" check will not accept a window update in those
	 * retransmitted segemnts.  Failing to do that, TCP may send out
	 * segments which are outside receiver's window.  As TCP accepts
	 * the ack in those retransmitted segments, if the window update in
	 * the same segment is not accepted, TCP will incorrectly calculates
	 * that it can send more segments.  This can create a deadlock
	 * with the receiver if its window becomes zero.
	 */
	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
		/*
		 * The criteria for update is:
		 *
		 * 1. the segment acknowledges some data.  Or
		 * 2. the segment is new, i.e. it has a higher seq num. Or
		 * 3. the segment is not old and the advertised window is
		 * larger than the previous advertised window.
		 */
		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
			flags |= TH_XMIT_NEEDED;
		tcp->tcp_swnd = new_swnd;
		if (new_swnd > tcp->tcp_max_swnd)
			tcp->tcp_max_swnd = new_swnd;
		tcp->tcp_swl1 = seg_seq;
		tcp->tcp_swl2 = seg_ack;
	}
est:
	if (tcp->tcp_state > TCPS_ESTABLISHED) {
		switch (tcp->tcp_state) {
		case TCPS_FIN_WAIT_1:
			if (tcp->tcp_fin_acked) {
				tcp->tcp_state = TCPS_FIN_WAIT_2;
				/*
				 * We implement the non-standard BSD/SunOS
				 * FIN_WAIT_2 flushing algorithm.
				 * If there is no user attached to this
				 * TCP endpoint, then this TCP struct
				 * could hang around forever in FIN_WAIT_2
				 * state if the peer forgets to send us
				 * a FIN.  To prevent this, we wait only
				 * 2*MSL (a convenient time value) for
				 * the FIN to arrive.  If it doesn't show up,
				 * we flush the TCP endpoint.  This algorithm,
				 * though a violation of RFC-793, has worked
				 * for over 10 years in BSD systems.
				 * Note: SunOS 4.x waits 675 seconds before
				 * flushing the FIN_WAIT_2 connection.
				 */
				TCP_TIMER_RESTART(tcp,
				    tcp_fin_wait_2_flush_interval);
			}
			break;
		case TCPS_FIN_WAIT_2:
			break;	/* Shutdown hook? */
		case TCPS_LAST_ACK:
			freemsg(mp);
			if (tcp->tcp_fin_acked) {
				(void) tcp_clean_death(sock_id, tcp, 0);
				return;
			}
			goto xmit_check;
		case TCPS_CLOSING:
			if (tcp->tcp_fin_acked) {
				tcp->tcp_state = TCPS_TIME_WAIT;
				tcp_time_wait_append(tcp);
				TCP_TIMER_RESTART(tcp, tcp_time_wait_interval);
			}
			/*FALLTHRU*/
		case TCPS_CLOSE_WAIT:
			freemsg(mp);
			goto xmit_check;
		default:
			assert(tcp->tcp_state != TCPS_TIME_WAIT);
			break;
		}
	}
	if (flags & TH_FIN) {
		/* Make sure we ack the fin */
		flags |= TH_ACK_NEEDED;
		if (!tcp->tcp_fin_rcvd) {
			tcp->tcp_fin_rcvd = B_TRUE;
			tcp->tcp_rnxt++;
			U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);

			switch (tcp->tcp_state) {
			case TCPS_SYN_RCVD:
			case TCPS_ESTABLISHED:
				tcp->tcp_state = TCPS_CLOSE_WAIT;
				/* Keepalive? */
				break;
			case TCPS_FIN_WAIT_1:
				if (!tcp->tcp_fin_acked) {
					tcp->tcp_state = TCPS_CLOSING;
					break;
				}
				/* FALLTHRU */
			case TCPS_FIN_WAIT_2:
				tcp->tcp_state = TCPS_TIME_WAIT;
				tcp_time_wait_append(tcp);
				TCP_TIMER_RESTART(tcp, tcp_time_wait_interval);
				if (seg_len) {
					/*
					 * implies data piggybacked on FIN.
					 * break to handle data.
					 */
					break;
				}
				freemsg(mp);
				goto ack_check;
			}
		}
	}
	if (mp == NULL)
		goto xmit_check;
	if (seg_len == 0) {
		freemsg(mp);
		goto xmit_check;
	}
	if (mp->b_rptr == mp->b_wptr) {
		/*
		 * The header has been consumed, so we remove the
		 * zero-length mblk here.
		 */
		mp1 = mp;
		mp = mp->b_cont;
		freeb(mp1);
	}
	/*
	 * ACK every other segments, unless the input queue is empty
	 * as we don't have a timer available.
	 */
	if (++tcp->tcp_rack_cnt == 2 || sockets[sock_id].inq == NULL) {
		flags |= TH_ACK_NEEDED;
		tcp->tcp_rack_cnt = 0;
	}
	tcp->tcp_rnxt += seg_len;
	U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);

	/* Update SACK list */
	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
		    &(tcp->tcp_num_sack_blk));
	}

	if (tcp->tcp_listener) {
		/*
		 * Side queue inbound data until the accept happens.
		 * tcp_accept/tcp_rput drains this when the accept happens.
		 */
		tcp_rcv_enqueue(tcp, mp, seg_len);
	} else {
		/* Just queue the data until the app calls read. */
		tcp_rcv_enqueue(tcp, mp, seg_len);
		/*
		 * Make sure the timer is running if we have data waiting
		 * for a push bit. This provides resiliency against
		 * implementations that do not correctly generate push bits.
		 */
		if (tcp->tcp_rcv_list != NULL)
			flags |= TH_TIMER_NEEDED;
	}

xmit_check:
	/* Is there anything left to do? */
	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_TIMER_NEEDED)) == 0)
		return;

	/* Any transmit work to do and a non-zero window? */
	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
		if (flags & TH_REXMIT_NEEDED) {
			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;

			if (snd_size > mss)
				snd_size = mss;
			if (snd_size > tcp->tcp_swnd)
				snd_size = tcp->tcp_swnd;
			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
			    B_TRUE);

			if (mp1 != NULL) {
				/* use uintptr_t to suppress the gcc warning */
				tcp->tcp_xmit_head->b_prev =
				    (mblk_t *)(uintptr_t)prom_gettime();
				tcp->tcp_csuna = tcp->tcp_snxt;
				BUMP_MIB(tcp_mib.tcpRetransSegs);
				UPDATE_MIB(tcp_mib.tcpRetransBytes, snd_size);
				(void) ipv4_tcp_output(sock_id, mp1);
				freeb(mp1);
			}
		}
		if (flags & TH_NEED_SACK_REXMIT) {
			if (tcp_sack_rxmit(tcp, sock_id) != 0) {
				flags |= TH_XMIT_NEEDED;
			}
		}
		/*
		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
		 * out new segment.  Note that tcp_rexmit should not be
		 * set, otherwise TH_LIMIT_XMIT should not be set.
		 */
		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
			if (!tcp->tcp_rexmit) {
				tcp_wput_data(tcp, NULL, sock_id);
			} else {
				tcp_ss_rexmit(tcp, sock_id);
			}
			/*
			 * The TCP could be closed in tcp_state_wait via
			 * tcp_wput_data (tcp_ss_rexmit could call
			 * tcp_wput_data as well).
			 */
			if (sockets[sock_id].pcb == NULL)
				return;
		}
		/*
		 * Adjust tcp_cwnd back to normal value after sending
		 * new data segments.
		 */
		if (flags & TH_LIMIT_XMIT) {
			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
		}

		/* Anything more to do? */
		if ((flags & (TH_ACK_NEEDED|TH_TIMER_NEEDED)) == 0)
			return;
	}
ack_check:
	if (flags & TH_ACK_NEEDED) {
		/*
		 * Time to send an ack for some reason.
		 */
		if ((mp1 = tcp_ack_mp(tcp)) != NULL) {
			TCP_DUMP_PACKET("tcp_rput_data: ack mp", mp1);
			(void) ipv4_tcp_output(sock_id, mp1);
			BUMP_MIB(tcp_mib.tcpOutAck);
			freeb(mp1);
		}
	}
}

/*
 * tcp_ss_rexmit() is called in tcp_rput_data() to do slow start
 * retransmission after a timeout.
 *
 * To limit the number of duplicate segments, we limit the number of segment
 * to be sent in one time to tcp_snd_burst, the burst variable.
 */
static void
tcp_ss_rexmit(tcp_t *tcp, int sock_id)
{
	uint32_t	snxt;
	uint32_t	smax;
	int32_t		win;
	int32_t		mss;
	int32_t		off;
	int32_t		burst = tcp->tcp_snd_burst;
	mblk_t		*snxt_mp;

	/*
	 * Note that tcp_rexmit can be set even though TCP has retransmitted
	 * all unack'ed segments.
	 */
	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
		smax = tcp->tcp_rexmit_max;
		snxt = tcp->tcp_rexmit_nxt;
		if (SEQ_LT(snxt, tcp->tcp_suna)) {
			snxt = tcp->tcp_suna;
		}
		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
		win -= snxt - tcp->tcp_suna;
		mss = tcp->tcp_mss;
		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);

		while (SEQ_LT(snxt, smax) && (win > 0) &&
		    (burst > 0) && (snxt_mp != NULL)) {
			mblk_t	*xmit_mp;
			mblk_t	*old_snxt_mp = snxt_mp;
			uint32_t cnt = mss;

			if (win < cnt) {
				cnt = win;
			}
			if (SEQ_GT(snxt + cnt, smax)) {
				cnt = smax - snxt;
			}
			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);

			if (xmit_mp == NULL)
				return;

			(void) ipv4_tcp_output(sock_id, xmit_mp);
			freeb(xmit_mp);

			snxt += cnt;
			win -= cnt;
			/*
			 * Update the send timestamp to avoid false
			 * retransmission.
			 * Note. use uintptr_t to suppress the gcc warning.
			 */
			old_snxt_mp->b_prev =
			    (mblk_t *)(uintptr_t)prom_gettime();
			BUMP_MIB(tcp_mib.tcpRetransSegs);
			UPDATE_MIB(tcp_mib.tcpRetransBytes, cnt);

			tcp->tcp_rexmit_nxt = snxt;
			burst--;
		}
		/*
		 * If we have transmitted all we have at the time
		 * we started the retranmission, we can leave
		 * the rest of the job to tcp_wput_data().  But we
		 * need to check the send window first.  If the
		 * win is not 0, go on with tcp_wput_data().
		 */
		if (SEQ_LT(snxt, smax) || win == 0) {
			return;
		}
	}
	/* Only call tcp_wput_data() if there is data to be sent. */
	if (tcp->tcp_unsent) {
		tcp_wput_data(tcp, NULL, sock_id);
	}
}

/*
 * tcp_timer is the timer service routine.  It handles all timer events for
 * a tcp instance except keepalives.  It figures out from the state of the
 * tcp instance what kind of action needs to be done at the time it is called.
 */
static void
tcp_timer(tcp_t	*tcp, int sock_id)
{
	mblk_t		*mp;
	uint32_t	first_threshold;
	uint32_t	second_threshold;
	uint32_t	ms;
	uint32_t	mss;

	first_threshold =  tcp->tcp_first_timer_threshold;
	second_threshold = tcp->tcp_second_timer_threshold;
	switch (tcp->tcp_state) {
	case TCPS_IDLE:
	case TCPS_BOUND:
	case TCPS_LISTEN:
		return;
	case TCPS_SYN_RCVD:
	case TCPS_SYN_SENT:
		first_threshold =  tcp->tcp_first_ctimer_threshold;
		second_threshold = tcp->tcp_second_ctimer_threshold;
		break;
	case TCPS_ESTABLISHED:
	case TCPS_FIN_WAIT_1:
	case TCPS_CLOSING:
	case TCPS_CLOSE_WAIT:
	case TCPS_LAST_ACK:
		/* If we have data to rexmit */
		if (tcp->tcp_suna != tcp->tcp_snxt) {
			int32_t time_to_wait;

			BUMP_MIB(tcp_mib.tcpTimRetrans);
			if (tcp->tcp_xmit_head == NULL)
				break;
			/* use uintptr_t to suppress the gcc warning */
			time_to_wait = (int32_t)(prom_gettime() -
			    (uint32_t)(uintptr_t)tcp->tcp_xmit_head->b_prev);
			time_to_wait = tcp->tcp_rto - time_to_wait;
			if (time_to_wait > 0) {
				/*
				 * Timer fired too early, so restart it.
				 */
				TCP_TIMER_RESTART(tcp, time_to_wait);
				return;
			}
			/*
			 * When we probe zero windows, we force the swnd open.
			 * If our peer acks with a closed window swnd will be
			 * set to zero by tcp_rput(). As long as we are
			 * receiving acks tcp_rput will
			 * reset 'tcp_ms_we_have_waited' so as not to trip the
			 * first and second interval actions.  NOTE: the timer
			 * interval is allowed to continue its exponential
			 * backoff.
			 */
			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
				DEBUG_1("tcp_timer (%d): zero win", sock_id);
				break;
			} else {
				/*
				 * After retransmission, we need to do
				 * slow start.  Set the ssthresh to one
				 * half of current effective window and
				 * cwnd to one MSS.  Also reset
				 * tcp_cwnd_cnt.
				 *
				 * Note that if tcp_ssthresh is reduced because
				 * of ECN, do not reduce it again unless it is
				 * already one window of data away (tcp_cwr
				 * should then be cleared) or this is a
				 * timeout for a retransmitted segment.
				 */
				uint32_t npkt;

				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
					npkt = (MIN((tcp->tcp_timer_backoff ?
					    tcp->tcp_cwnd_ssthresh :
					    tcp->tcp_cwnd),
					    tcp->tcp_swnd) >> 1) /
					    tcp->tcp_mss;
					if (npkt < 2)
						npkt = 2;
					tcp->tcp_cwnd_ssthresh = npkt *
					    tcp->tcp_mss;
				}
				tcp->tcp_cwnd = tcp->tcp_mss;
				tcp->tcp_cwnd_cnt = 0;
				if (tcp->tcp_ecn_ok) {
					tcp->tcp_cwr = B_TRUE;
					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
					tcp->tcp_ecn_cwr_sent = B_FALSE;
				}
			}
			break;
		}
		/*
		 * We have something to send yet we cannot send.  The
		 * reason can be:
		 *
		 * 1. Zero send window: we need to do zero window probe.
		 * 2. Zero cwnd: because of ECN, we need to "clock out
		 * segments.
		 * 3. SWS avoidance: receiver may have shrunk window,
		 * reset our knowledge.
		 *
		 * Note that condition 2 can happen with either 1 or
		 * 3.  But 1 and 3 are exclusive.
		 */
		if (tcp->tcp_unsent != 0) {
			if (tcp->tcp_cwnd == 0) {
				/*
				 * Set tcp_cwnd to 1 MSS so that a
				 * new segment can be sent out.  We
				 * are "clocking out" new data when
				 * the network is really congested.
				 */
				assert(tcp->tcp_ecn_ok);
				tcp->tcp_cwnd = tcp->tcp_mss;
			}
			if (tcp->tcp_swnd == 0) {
				/* Extend window for zero window probe */
				tcp->tcp_swnd++;
				tcp->tcp_zero_win_probe = B_TRUE;
				BUMP_MIB(tcp_mib.tcpOutWinProbe);
			} else {
				/*
				 * Handle timeout from sender SWS avoidance.
				 * Reset our knowledge of the max send window
				 * since the receiver might have reduced its
				 * receive buffer.  Avoid setting tcp_max_swnd
				 * to one since that will essentially disable
				 * the SWS checks.
				 *
				 * Note that since we don't have a SWS
				 * state variable, if the timeout is set
				 * for ECN but not for SWS, this
				 * code will also be executed.  This is
				 * fine as tcp_max_swnd is updated
				 * constantly and it will not affect
				 * anything.
				 */
				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
			}
			tcp_wput_data(tcp, NULL, sock_id);
			return;
		}
		/* Is there a FIN that needs to be to re retransmitted? */
		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
		    !tcp->tcp_fin_acked)
			break;
		/* Nothing to do, return without restarting timer. */
		return;
	case TCPS_FIN_WAIT_2:
		/*
		 * User closed the TCP endpoint and peer ACK'ed our FIN.
		 * We waited some time for for peer's FIN, but it hasn't
		 * arrived.  We flush the connection now to avoid
		 * case where the peer has rebooted.
		 */
		/* FALLTHRU */
	case TCPS_TIME_WAIT:
		(void) tcp_clean_death(sock_id, tcp, 0);
		return;
	default:
		DEBUG_3("tcp_timer (%d): strange state (%d) %s", sock_id,
		    tcp->tcp_state, tcp_display(tcp, NULL,
		    DISP_PORT_ONLY));
		return;
	}
	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
		/*
		 * For zero window probe, we need to send indefinitely,
		 * unless we have not heard from the other side for some
		 * time...
		 */
		if ((tcp->tcp_zero_win_probe == 0) ||
		    ((prom_gettime() - tcp->tcp_last_recv_time) >
		    second_threshold)) {
			BUMP_MIB(tcp_mib.tcpTimRetransDrop);
			/*
			 * If TCP is in SYN_RCVD state, send back a
			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
			 * should be zero in TCPS_SYN_RCVD state.
			 */
			if (tcp->tcp_state == TCPS_SYN_RCVD) {
				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
				    "in SYN_RCVD",
				    tcp, NULL, tcp->tcp_snxt,
				    tcp->tcp_rnxt, TH_RST | TH_ACK, 0, sock_id);
			}
			(void) tcp_clean_death(sock_id, tcp,
			    tcp->tcp_client_errno ?
			    tcp->tcp_client_errno : ETIMEDOUT);
			return;
		} else {
			/*
			 * Set tcp_ms_we_have_waited to second_threshold
			 * so that in next timeout, we will do the above
			 * check (lbolt - tcp_last_recv_time).  This is
			 * also to avoid overflow.
			 *
			 * We don't need to decrement tcp_timer_backoff
			 * to avoid overflow because it will be decremented
			 * later if new timeout value is greater than
			 * tcp_rexmit_interval_max.  In the case when
			 * tcp_rexmit_interval_max is greater than
			 * second_threshold, it means that we will wait
			 * longer than second_threshold to send the next
			 * window probe.
			 */
			tcp->tcp_ms_we_have_waited = second_threshold;
		}
	} else if (ms > first_threshold && tcp->tcp_rtt_sa != 0) {
		/*
		 * We have been retransmitting for too long...  The RTT
		 * we calculated is probably incorrect.  Reinitialize it.
		 * Need to compensate for 0 tcp_rtt_sa.  Reset
		 * tcp_rtt_update so that we won't accidentally cache a
		 * bad value.  But only do this if this is not a zero
		 * window probe.
		 */
		if (tcp->tcp_zero_win_probe == 0) {
			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
			    (tcp->tcp_rtt_sa >> 5);
			tcp->tcp_rtt_sa = 0;
			tcp->tcp_rtt_update = 0;
		}
	}
	tcp->tcp_timer_backoff++;
	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
	    tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
	    tcp_rexmit_interval_min) {
		/*
		 * This means the original RTO is tcp_rexmit_interval_min.
		 * So we will use tcp_rexmit_interval_min as the RTO value
		 * and do the backoff.
		 */
		ms = tcp_rexmit_interval_min << tcp->tcp_timer_backoff;
	} else {
		ms <<= tcp->tcp_timer_backoff;
	}
	if (ms > tcp_rexmit_interval_max) {
		ms = tcp_rexmit_interval_max;
		/*
		 * ms is at max, decrement tcp_timer_backoff to avoid
		 * overflow.
		 */
		tcp->tcp_timer_backoff--;
	}
	tcp->tcp_ms_we_have_waited += ms;
	if (tcp->tcp_zero_win_probe == 0) {
		tcp->tcp_rto = ms;
	}
	TCP_TIMER_RESTART(tcp, ms);
	/*
	 * This is after a timeout and tcp_rto is backed off.  Set
	 * tcp_set_timer to 1 so that next time RTO is updated, we will
	 * restart the timer with a correct value.
	 */
	tcp->tcp_set_timer = 1;
	mss = tcp->tcp_snxt - tcp->tcp_suna;
	if (mss > tcp->tcp_mss)
		mss = tcp->tcp_mss;
	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
		mss = tcp->tcp_swnd;

	if ((mp = tcp->tcp_xmit_head) != NULL) {
		/* use uintptr_t to suppress the gcc warning */
		mp->b_prev = (mblk_t *)(uintptr_t)prom_gettime();
	}
	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
	    B_TRUE);
	if (mp == NULL)
		return;
	tcp->tcp_csuna = tcp->tcp_snxt;
	BUMP_MIB(tcp_mib.tcpRetransSegs);
	UPDATE_MIB(tcp_mib.tcpRetransBytes, mss);
	/* Dump the packet when debugging. */
	TCP_DUMP_PACKET("tcp_timer", mp);

	(void) ipv4_tcp_output(sock_id, mp);
	freeb(mp);

	/*
	 * When slow start after retransmission begins, start with
	 * this seq no.  tcp_rexmit_max marks the end of special slow
	 * start phase.  tcp_snd_burst controls how many segments
	 * can be sent because of an ack.
	 */
	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
	tcp->tcp_snd_burst = TCP_CWND_SS;
	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
	    (tcp->tcp_unsent == 0)) {
		tcp->tcp_rexmit_max = tcp->tcp_fss;
	} else {
		tcp->tcp_rexmit_max = tcp->tcp_snxt;
	}
	tcp->tcp_rexmit = B_TRUE;
	tcp->tcp_dupack_cnt = 0;

	/*
	 * Remove all rexmit SACK blk to start from fresh.
	 */
	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
		tcp->tcp_num_notsack_blk = 0;
		tcp->tcp_cnt_notsack_list = 0;
	}
}

/*
 * The TCP normal data output path.
 * NOTE: the logic of the fast path is duplicated from this function.
 */
static void
tcp_wput_data(tcp_t *tcp, mblk_t *mp, int sock_id)
{
	int		len;
	mblk_t		*local_time;
	mblk_t		*mp1;
	uchar_t		*rptr;
	uint32_t	snxt;
	int		tail_unsent;
	int		tcpstate;
	int		usable = 0;
	mblk_t		*xmit_tail;
	int32_t		num_burst_seg;
	int32_t		mss;
	int32_t		num_sack_blk = 0;
	int32_t		tcp_hdr_len;
	ipaddr_t	*dst;
	ipaddr_t	*src;

#ifdef DEBUG
	printf("tcp_wput_data(%d) ##############################\n", sock_id);
#endif
	tcpstate = tcp->tcp_state;
	if (mp == NULL) {
		/* Really tacky... but we need this for detached closes. */
		len = tcp->tcp_unsent;
		goto data_null;
	}

	/*
	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
	 * or before a connection attempt has begun.
	 *
	 * The following should not happen in inetboot....
	 */
	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
			printf("tcp_wput_data: data after ordrel, %s\n",
			    tcp_display(tcp, NULL, DISP_ADDR_AND_PORT));
		}
		freemsg(mp);
		return;
	}

	/* Strip empties */
	for (;;) {
		assert((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
		    (uintptr_t)INT_MAX);
		len = (int)(mp->b_wptr - mp->b_rptr);
		if (len > 0)
			break;
		mp1 = mp;
		mp = mp->b_cont;
		freeb(mp1);
		if (mp == NULL) {
			return;
		}
	}

	/* If we are the first on the list ... */
	if (tcp->tcp_xmit_head == NULL) {
		tcp->tcp_xmit_head = mp;
		tcp->tcp_xmit_tail = mp;
		tcp->tcp_xmit_tail_unsent = len;
	} else {
		tcp->tcp_xmit_last->b_cont = mp;
		len += tcp->tcp_unsent;
	}

	/* Tack on however many more positive length mblks we have */
	if ((mp1 = mp->b_cont) != NULL) {
		do {
			int tlen;
			assert((uintptr_t)(mp1->b_wptr -
			    mp1->b_rptr) <= (uintptr_t)INT_MAX);
			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
			if (tlen <= 0) {
				mp->b_cont = mp1->b_cont;
				freeb(mp1);
			} else {
				len += tlen;
				mp = mp1;
			}
		} while ((mp1 = mp->b_cont) != NULL);
	}
	tcp->tcp_xmit_last = mp;
	tcp->tcp_unsent = len;

data_null:
	snxt = tcp->tcp_snxt;
	xmit_tail = tcp->tcp_xmit_tail;
	tail_unsent = tcp->tcp_xmit_tail_unsent;

	/*
	 * Note that tcp_mss has been adjusted to take into account the
	 * timestamp option if applicable.  Because SACK options do not
	 * appear in every TCP segments and they are of variable lengths,
	 * they cannot be included in tcp_mss.  Thus we need to calculate
	 * the actual segment length when we need to send a segment which
	 * includes SACK options.
	 */
	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
		int32_t	opt_len;

		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
		    tcp->tcp_num_sack_blk);
		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
		    2 + TCPOPT_HEADER_LEN;
		mss = tcp->tcp_mss - opt_len;
		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
	} else {
		mss = tcp->tcp_mss;
		tcp_hdr_len = tcp->tcp_hdr_len;
	}

	if ((tcp->tcp_suna == snxt) &&
	    (prom_gettime() - tcp->tcp_last_recv_time) >= tcp->tcp_rto) {
		tcp->tcp_cwnd = MIN(tcp_slow_start_after_idle * mss,
		    MIN(4 * mss, MAX(2 * mss, 4380 / mss * mss)));
	}
	if (tcpstate == TCPS_SYN_RCVD) {
		/*
		 * The three-way connection establishment handshake is not
		 * complete yet. We want to queue the data for transmission
		 * after entering ESTABLISHED state (RFC793). Setting usable to
		 * zero cause a jump to "done" label effectively leaving data
		 * on the queue.
		 */

		usable = 0;
	} else {
		int usable_r = tcp->tcp_swnd;

		/*
		 * In the special case when cwnd is zero, which can only
		 * happen if the connection is ECN capable, return now.
		 * New segments is sent using tcp_timer().  The timer
		 * is set in tcp_rput_data().
		 */
		if (tcp->tcp_cwnd == 0) {
			/*
			 * Note that tcp_cwnd is 0 before 3-way handshake is
			 * finished.
			 */
			assert(tcp->tcp_ecn_ok ||
			    tcp->tcp_state < TCPS_ESTABLISHED);
			return;
		}

		/* usable = MIN(swnd, cwnd) - unacked_bytes */
		if (usable_r > tcp->tcp_cwnd)
			usable_r = tcp->tcp_cwnd;

		/* NOTE: trouble if xmitting while SYN not acked? */
		usable_r -= snxt;
		usable_r += tcp->tcp_suna;

		/* usable = MIN(usable, unsent) */
		if (usable_r > len)
			usable_r = len;

		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
		if (usable_r != 0)
			usable = usable_r;
	}

	/* use uintptr_t to suppress the gcc warning */
	local_time = (mblk_t *)(uintptr_t)prom_gettime();

	/*
	 * "Our" Nagle Algorithm.  This is not the same as in the old
	 * BSD.  This is more in line with the true intent of Nagle.
	 *
	 * The conditions are:
	 * 1. The amount of unsent data (or amount of data which can be
	 *    sent, whichever is smaller) is less than Nagle limit.
	 * 2. The last sent size is also less than Nagle limit.
	 * 3. There is unack'ed data.
	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
	 *    Nagle algorithm.  This reduces the probability that urgent
	 *    bytes get "merged" together.
	 * 5. The app has not closed the connection.  This eliminates the
	 *    wait time of the receiving side waiting for the last piece of
	 *    (small) data.
	 *
	 * If all are satisified, exit without sending anything.  Note
	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
	 * 4095).
	 */
	if (usable < (int)tcp->tcp_naglim &&
	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
	    snxt != tcp->tcp_suna &&
	    !(tcp->tcp_valid_bits & TCP_URG_VALID))
		goto done;

	num_burst_seg = tcp->tcp_snd_burst;
	for (;;) {
		tcph_t		*tcph;
		mblk_t		*new_mp;

		if (num_burst_seg-- == 0)
			goto done;

		len = mss;
		if (len > usable) {
			len = usable;
			if (len <= 0) {
				/* Terminate the loop */
				goto done;
			}
			/*
			 * Sender silly-window avoidance.
			 * Ignore this if we are going to send a
			 * zero window probe out.
			 *
			 * TODO: force data into microscopic window ??
			 *	==> (!pushed || (unsent > usable))
			 */
			if (len < (tcp->tcp_max_swnd >> 1) &&
			    (tcp->tcp_unsent - (snxt - tcp->tcp_snxt)) > len &&
			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
			    len == 1) && (! tcp->tcp_zero_win_probe)) {
				/*
				 * If the retransmit timer is not running
				 * we start it so that we will retransmit
				 * in the case when the the receiver has
				 * decremented the window.
				 */
				if (snxt == tcp->tcp_snxt &&
				    snxt == tcp->tcp_suna) {
					/*
					 * We are not supposed to send
					 * anything.  So let's wait a little
					 * bit longer before breaking SWS
					 * avoidance.
					 *
					 * What should the value be?
					 * Suggestion: MAX(init rexmit time,
					 * tcp->tcp_rto)
					 */
					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
				}
				goto done;
			}
		}

		tcph = tcp->tcp_tcph;

		usable -= len;	/* Approximate - can be adjusted later */
		if (usable > 0)
			tcph->th_flags[0] = TH_ACK;
		else
			tcph->th_flags[0] = (TH_ACK | TH_PUSH);

		U32_TO_ABE32(snxt, tcph->th_seq);

		if (tcp->tcp_valid_bits) {
			uchar_t		*prev_rptr = xmit_tail->b_rptr;
			uint32_t	prev_snxt = tcp->tcp_snxt;

			if (tail_unsent == 0) {
				assert(xmit_tail->b_cont != NULL);
				xmit_tail = xmit_tail->b_cont;
				prev_rptr = xmit_tail->b_rptr;
				tail_unsent = (int)(xmit_tail->b_wptr -
				    xmit_tail->b_rptr);
			} else {
				xmit_tail->b_rptr = xmit_tail->b_wptr -
				    tail_unsent;
			}
			mp = tcp_xmit_mp(tcp, xmit_tail, len, NULL, NULL,
			    snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
			/* Restore tcp_snxt so we get amount sent right. */
			tcp->tcp_snxt = prev_snxt;
			if (prev_rptr == xmit_tail->b_rptr)
				xmit_tail->b_prev = local_time;
			else
				xmit_tail->b_rptr = prev_rptr;

			if (mp == NULL)
				break;

			mp1 = mp->b_cont;

			snxt += len;
			tcp->tcp_last_sent_len = (ushort_t)len;
			while (mp1->b_cont) {
				xmit_tail = xmit_tail->b_cont;
				xmit_tail->b_prev = local_time;
				mp1 = mp1->b_cont;
			}
			tail_unsent = xmit_tail->b_wptr - mp1->b_wptr;
			BUMP_MIB(tcp_mib.tcpOutDataSegs);
			UPDATE_MIB(tcp_mib.tcpOutDataBytes, len);
			/* Dump the packet when debugging. */
			TCP_DUMP_PACKET("tcp_wput_data (valid bits)", mp);
			(void) ipv4_tcp_output(sock_id, mp);
			freeb(mp);
			continue;
		}

		snxt += len;	/* Adjust later if we don't send all of len */
		BUMP_MIB(tcp_mib.tcpOutDataSegs);
		UPDATE_MIB(tcp_mib.tcpOutDataBytes, len);

		if (tail_unsent) {
			/* Are the bytes above us in flight? */
			rptr = xmit_tail->b_wptr - tail_unsent;
			if (rptr != xmit_tail->b_rptr) {
				tail_unsent -= len;
				len += tcp_hdr_len;
				tcp->tcp_ipha->ip_len = htons(len);
				mp = dupb(xmit_tail);
				if (!mp)
					break;
				mp->b_rptr = rptr;
				goto must_alloc;
			}
		} else {
			xmit_tail = xmit_tail->b_cont;
			assert((uintptr_t)(xmit_tail->b_wptr -
			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
			tail_unsent = (int)(xmit_tail->b_wptr -
			    xmit_tail->b_rptr);
		}

		tail_unsent -= len;
		tcp->tcp_last_sent_len = (ushort_t)len;

		len += tcp_hdr_len;
		if (tcp->tcp_ipversion == IPV4_VERSION)
			tcp->tcp_ipha->ip_len = htons(len);

		xmit_tail->b_prev = local_time;

		mp = dupb(xmit_tail);
		if (mp == NULL)
			goto out_of_mem;

		len = tcp_hdr_len;
		/*
		 * There are four reasons to allocate a new hdr mblk:
		 *  1) The bytes above us are in use by another packet
		 *  2) We don't have good alignment
		 *  3) The mblk is being shared
		 *  4) We don't have enough room for a header
		 */
		rptr = mp->b_rptr - len;
		if (!OK_32PTR(rptr) ||
		    rptr < mp->b_datap) {
			/* NOTE: we assume allocb returns an OK_32PTR */

		must_alloc:;
			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
			    tcp_wroff_xtra, 0);
			if (mp1 == NULL) {
				freemsg(mp);
				goto out_of_mem;
			}
			mp1->b_cont = mp;
			mp = mp1;
			/* Leave room for Link Level header */
			len = tcp_hdr_len;
			rptr = &mp->b_rptr[tcp_wroff_xtra];
			mp->b_wptr = &rptr[len];
		}

		if (tcp->tcp_snd_ts_ok) {
			/* use uintptr_t to suppress the gcc warning */
			U32_TO_BE32((uint32_t)(uintptr_t)local_time,
				(char *)tcph+TCP_MIN_HEADER_LENGTH+4);
			U32_TO_BE32(tcp->tcp_ts_recent,
			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
		} else {
			assert(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
		}

		mp->b_rptr = rptr;

		/* Copy the template header. */
		dst = (ipaddr_t *)rptr;
		src = (ipaddr_t *)tcp->tcp_iphc;
		dst[0] = src[0];
		dst[1] = src[1];
		dst[2] = src[2];
		dst[3] = src[3];
		dst[4] = src[4];
		dst[5] = src[5];
		dst[6] = src[6];
		dst[7] = src[7];
		dst[8] = src[8];
		dst[9] = src[9];
		len = tcp->tcp_hdr_len;
		if (len -= 40) {
			len >>= 2;
			dst += 10;
			src += 10;
			do {
				*dst++ = *src++;
			} while (--len);
		}

		/*
		 * Set tcph to point to the header of the outgoing packet,
		 * not to the template header.
		 */
		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);

		/*
		 * Set the ECN info in the TCP header if it is not a zero
		 * window probe.  Zero window probe is only sent in
		 * tcp_wput_data() and tcp_timer().
		 */
		if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
			SET_ECT(tcp, rptr);

			if (tcp->tcp_ecn_echo_on)
				tcph->th_flags[0] |= TH_ECE;
			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
				tcph->th_flags[0] |= TH_CWR;
				tcp->tcp_ecn_cwr_sent = B_TRUE;
			}
		}

		/* Fill in SACK options */
		if (num_sack_blk > 0) {
			uchar_t *wptr = rptr + tcp->tcp_hdr_len;
			sack_blk_t *tmp;
			int32_t	i;

			wptr[0] = TCPOPT_NOP;
			wptr[1] = TCPOPT_NOP;
			wptr[2] = TCPOPT_SACK;
			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
			    sizeof (sack_blk_t);
			wptr += TCPOPT_REAL_SACK_LEN;

			tmp = tcp->tcp_sack_list;
			for (i = 0; i < num_sack_blk; i++) {
				U32_TO_BE32(tmp[i].begin, wptr);
				wptr += sizeof (tcp_seq);
				U32_TO_BE32(tmp[i].end, wptr);
				wptr += sizeof (tcp_seq);
			}
			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
			    << 4);
		}

		if (tail_unsent) {
			mp1 = mp->b_cont;
			if (mp1 == NULL)
				mp1 = mp;
			/*
			 * If we're a little short, tack on more mblks
			 * as long as we don't need to split an mblk.
			 */
			while (tail_unsent < 0 &&
			    tail_unsent + (int)(xmit_tail->b_cont->b_wptr -
			    xmit_tail->b_cont->b_rptr) <= 0) {
				xmit_tail = xmit_tail->b_cont;
				/* Stash for rtt use later */
				xmit_tail->b_prev = local_time;
				mp1->b_cont = dupb(xmit_tail);
				mp1 = mp1->b_cont;
				assert((uintptr_t)(xmit_tail->b_wptr -
				    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
				tail_unsent += (int)(xmit_tail->b_wptr -
				    xmit_tail->b_rptr);
				if (mp1 == NULL) {
					freemsg(mp);
					goto out_of_mem;
				}
			}
			/* Trim back any surplus on the last mblk */
			if (tail_unsent > 0)
				mp1->b_wptr -= tail_unsent;
			if (tail_unsent < 0) {
				uint32_t ip_len;

				/*
				 * We did not send everything we could in
				 * order to preserve mblk boundaries.
				 */
				usable -= tail_unsent;
				snxt += tail_unsent;
				tcp->tcp_last_sent_len += tail_unsent;
				UPDATE_MIB(tcp_mib.tcpOutDataBytes,
				    tail_unsent);
				/* Adjust the IP length field. */
				ip_len = ntohs(((struct ip *)rptr)->ip_len) +
				    tail_unsent;
				((struct ip *)rptr)->ip_len = htons(ip_len);
				tail_unsent = 0;
			}
		}

		if (mp == NULL)
			goto out_of_mem;

		/*
		 * Performance hit!  We need to pullup the whole message
		 * in order to do checksum and for the MAC output routine.
		 */
		if (mp->b_cont != NULL) {
			int mp_size;
#ifdef	DEBUG
			printf("Multiple mblk %d\n", msgdsize(mp));
#endif
			new_mp = allocb(msgdsize(mp) + tcp_wroff_xtra, 0);
			new_mp->b_rptr += tcp_wroff_xtra;
			new_mp->b_wptr = new_mp->b_rptr;
			while (mp != NULL) {
				mp_size = mp->b_wptr - mp->b_rptr;
				bcopy(mp->b_rptr, new_mp->b_wptr, mp_size);
				new_mp->b_wptr += mp_size;
				mp = mp->b_cont;
			}
			freemsg(mp);
			mp = new_mp;
		}
		tcp_set_cksum(mp);
		((struct ip *)mp->b_rptr)->ip_ttl = (uint8_t)tcp_ipv4_ttl;
		TCP_DUMP_PACKET("tcp_wput_data", mp);
		(void) ipv4_tcp_output(sock_id, mp);
		freemsg(mp);
	}
out_of_mem:;
	/* Pretend that all we were trying to send really got sent */
	if (tail_unsent < 0) {
		do {
			xmit_tail = xmit_tail->b_cont;
			xmit_tail->b_prev = local_time;
			assert((uintptr_t)(xmit_tail->b_wptr -
			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
			tail_unsent += (int)(xmit_tail->b_wptr -
			    xmit_tail->b_rptr);
		} while (tail_unsent < 0);
	}
done:;
	tcp->tcp_xmit_tail = xmit_tail;
	tcp->tcp_xmit_tail_unsent = tail_unsent;
	len = tcp->tcp_snxt - snxt;
	if (len) {
		/*
		 * If new data was sent, need to update the notsack
		 * list, which is, afterall, data blocks that have
		 * not been sack'ed by the receiver.  New data is
		 * not sack'ed.
		 */
		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
			/* len is a negative value. */
			tcp->tcp_pipe -= len;
			tcp_notsack_update(&(tcp->tcp_notsack_list),
			    tcp->tcp_snxt, snxt,
			    &(tcp->tcp_num_notsack_blk),
			    &(tcp->tcp_cnt_notsack_list));
		}
		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
		tcp->tcp_rack = tcp->tcp_rnxt;
		tcp->tcp_rack_cnt = 0;
		if ((snxt + len) == tcp->tcp_suna) {
			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
		}
		/*
		 * Note that len is the amount we just sent but with a negative
		 * sign. We update tcp_unsent here since we may come back to
		 * tcp_wput_data from tcp_state_wait.
		 */
		len += tcp->tcp_unsent;
		tcp->tcp_unsent = len;

		/*
		 * Let's wait till all the segments have been acked, since we
		 * don't have a timer.
		 */
		(void) tcp_state_wait(sock_id, tcp, TCPS_ALL_ACKED);
		return;
	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
		/*
		 * Didn't send anything. Make sure the timer is running
		 * so that we will probe a zero window.
		 */
		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
	}

	/* Note that len is the amount we just sent but with a negative sign */
	len += tcp->tcp_unsent;
	tcp->tcp_unsent = len;

}

static void
tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp,
    uint32_t seg_seq, uint32_t seg_ack, int seg_len, tcph_t *tcph,
    int sock_id)
{
	int32_t		bytes_acked;
	int32_t		gap;
	int32_t		rgap;
	tcp_opt_t	tcpopt;
	uint_t		flags;
	uint32_t	new_swnd = 0;

#ifdef DEBUG
	printf("Time wait processing called ###############3\n");
#endif

	/* Just make sure we send the right sock_id to tcp_clean_death */
	if ((sockets[sock_id].pcb == NULL) || (sockets[sock_id].pcb != tcp))
		sock_id = -1;

	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
	new_swnd = BE16_TO_U16(tcph->th_win) <<
	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
	if (tcp->tcp_snd_ts_ok) {
		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
			freemsg(mp);
			tcp_xmit_ctl(NULL, tcp, NULL, tcp->tcp_snxt,
			    tcp->tcp_rnxt, TH_ACK, 0, -1);
			return;
		}
	}
	gap = seg_seq - tcp->tcp_rnxt;
	rgap = tcp->tcp_rwnd - (gap + seg_len);
	if (gap < 0) {
		BUMP_MIB(tcp_mib.tcpInDataDupSegs);
		UPDATE_MIB(tcp_mib.tcpInDataDupBytes,
		    (seg_len > -gap ? -gap : seg_len));
		seg_len += gap;
		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
			if (flags & TH_RST) {
				freemsg(mp);
				return;
			}
			if ((flags & TH_FIN) && seg_len == -1) {
				/*
				 * When TCP receives a duplicate FIN in
				 * TIME_WAIT state, restart the 2 MSL timer.
				 * See page 73 in RFC 793. Make sure this TCP
				 * is already on the TIME_WAIT list. If not,
				 * just restart the timer.
				 */
				tcp_time_wait_remove(tcp);
				tcp_time_wait_append(tcp);
				TCP_TIMER_RESTART(tcp, tcp_time_wait_interval);
				tcp_xmit_ctl(NULL, tcp, NULL, tcp->tcp_snxt,
				    tcp->tcp_rnxt, TH_ACK, 0, -1);
				freemsg(mp);
				return;
			}
			flags |=  TH_ACK_NEEDED;
			seg_len = 0;
			goto process_ack;
		}

		/* Fix seg_seq, and chew the gap off the front. */
		seg_seq = tcp->tcp_rnxt;
	}

	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
		/*
		 * Make sure that when we accept the connection, pick
		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
		 * old connection.
		 *
		 * The next ISS generated is equal to tcp_iss_incr_extra
		 * + ISS_INCR/2 + other components depending on the
		 * value of tcp_strong_iss.  We pre-calculate the new
		 * ISS here and compare with tcp_snxt to determine if
		 * we need to make adjustment to tcp_iss_incr_extra.
		 *
		 * Note that since we are now in the global queue
		 * perimeter and need to do a lateral_put() to the
		 * listener queue, there can be other connection requests/
		 * attempts while the lateral_put() is going on.  That
		 * means what we calculate here may not be correct.  This
		 * is extremely difficult to solve unless TCP and IP
		 * modules are merged and there is no perimeter, but just
		 * locks.  The above calculation is ugly and is a
		 * waste of CPU cycles...
		 */
		uint32_t new_iss = tcp_iss_incr_extra;
		int32_t adj;

		/* Add time component and min random (i.e. 1). */
		new_iss += (prom_gettime() >> ISS_NSEC_SHT) + 1;
		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
			/*
			 * New ISS not guaranteed to be ISS_INCR/2
			 * ahead of the current tcp_snxt, so add the
			 * difference to tcp_iss_incr_extra.
			 */
			tcp_iss_incr_extra += adj;
		}
		tcp_clean_death(sock_id, tcp, 0);

		/*
		 * This is a passive open.  Right now we do not
		 * do anything...
		 */
		freemsg(mp);
		return;
	}

	/*
	 * rgap is the amount of stuff received out of window.  A negative
	 * value is the amount out of window.
	 */
	if (rgap < 0) {
		BUMP_MIB(tcp_mib.tcpInDataPastWinSegs);
		UPDATE_MIB(tcp_mib.tcpInDataPastWinBytes, -rgap);
		/* Fix seg_len and make sure there is something left. */
		seg_len += rgap;
		if (seg_len <= 0) {
			if (flags & TH_RST) {
				freemsg(mp);
				return;
			}
			flags |=  TH_ACK_NEEDED;
			seg_len = 0;
			goto process_ack;
		}
	}
	/*
	 * Check whether we can update tcp_ts_recent.  This test is
	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
	 * Extensions for High Performance: An Update", Internet Draft.
	 */
	if (tcp->tcp_snd_ts_ok &&
	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
		tcp->tcp_last_rcv_lbolt = prom_gettime();
	}

	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
		/* Always ack out of order packets */
		flags |= TH_ACK_NEEDED;
		seg_len = 0;
	} else if (seg_len > 0) {
		BUMP_MIB(tcp_mib.tcpInDataInorderSegs);
		UPDATE_MIB(tcp_mib.tcpInDataInorderBytes, seg_len);
	}
	if (flags & TH_RST) {
		freemsg(mp);
		(void) tcp_clean_death(sock_id, tcp, 0);
		return;
	}
	if (flags & TH_SYN) {
		freemsg(mp);
		tcp_xmit_ctl("TH_SYN", tcp, NULL, seg_ack, seg_seq + 1,
		    TH_RST|TH_ACK, 0, -1);
		/*
		 * Do not delete the TCP structure if it is in
		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
		 */
		return;
	}
process_ack:
	if (flags & TH_ACK) {
		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
		if (bytes_acked <= 0) {
			if (bytes_acked == 0 && seg_len == 0 &&
			    new_swnd == tcp->tcp_swnd)
				BUMP_MIB(tcp_mib.tcpInDupAck);
		} else {
			/* Acks something not sent */
			flags |= TH_ACK_NEEDED;
		}
	}
	freemsg(mp);
	if (flags & TH_ACK_NEEDED) {
		/*
		 * Time to send an ack for some reason.
		 */
		tcp_xmit_ctl(NULL, tcp, NULL, tcp->tcp_snxt,
		    tcp->tcp_rnxt, TH_ACK, 0, -1);
	}
}

static int
tcp_init_values(tcp_t *tcp, struct inetboot_socket *isp)
{
	int	err;

	tcp->tcp_family = AF_INET;
	tcp->tcp_ipversion = IPV4_VERSION;

	/*
	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
	 * allow the algorithm to adjust slowly to large fluctuations of RTT
	 * during first few transmissions of a connection as seen in slow
	 * links.
	 */
	tcp->tcp_rtt_sa = tcp_rexmit_interval_initial << 2;
	tcp->tcp_rtt_sd = tcp_rexmit_interval_initial >> 1;
	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
	    tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
	    tcp_conn_grace_period;
	if (tcp->tcp_rto < tcp_rexmit_interval_min)
		tcp->tcp_rto = tcp_rexmit_interval_min;
	tcp->tcp_timer_backoff = 0;
	tcp->tcp_ms_we_have_waited = 0;
	tcp->tcp_last_recv_time = prom_gettime();
	tcp->tcp_cwnd_max = tcp_cwnd_max_;
	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
	tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
	/* For Ethernet, the mtu returned is actually 1550... */
	if (mac_get_type() == IFT_ETHER) {
		tcp->tcp_if_mtu = mac_get_mtu() - 50;
	} else {
		tcp->tcp_if_mtu = mac_get_mtu();
	}
	tcp->tcp_mss = tcp->tcp_if_mtu;

	tcp->tcp_first_timer_threshold = tcp_ip_notify_interval;
	tcp->tcp_first_ctimer_threshold = tcp_ip_notify_cinterval;
	tcp->tcp_second_timer_threshold = tcp_ip_abort_interval;
	/*
	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
	 * passive open.
	 */
	tcp->tcp_second_ctimer_threshold = tcp_ip_abort_cinterval;

	tcp->tcp_naglim = tcp_naglim_def;

	/* NOTE:  ISS is now set in tcp_adapt_ire(). */

	/* Initialize the header template */
	if (tcp->tcp_ipversion == IPV4_VERSION) {
		err = tcp_header_init_ipv4(tcp);
	}
	if (err)
		return (err);

	/*
	 * Init the window scale to the max so tcp_rwnd_set() won't pare
	 * down tcp_rwnd. tcp_adapt_ire() will set the right value later.
	 */
	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
	tcp->tcp_xmit_lowater = tcp_xmit_lowat;
	if (isp != NULL) {
		tcp->tcp_xmit_hiwater = isp->so_sndbuf;
		tcp->tcp_rwnd = isp->so_rcvbuf;
		tcp->tcp_rwnd_max = isp->so_rcvbuf;
	}
	tcp->tcp_state = TCPS_IDLE;
	return (0);
}

/*
 * Initialize the IPv4 header. Loses any record of any IP options.
 */
static int
tcp_header_init_ipv4(tcp_t *tcp)
{
	tcph_t		*tcph;

	/*
	 * This is a simple initialization. If there's
	 * already a template, it should never be too small,
	 * so reuse it.  Otherwise, allocate space for the new one.
	 */
	if (tcp->tcp_iphc != NULL) {
		assert(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
	} else {
		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
		tcp->tcp_iphc = bkmem_zalloc(tcp->tcp_iphc_len);
		if (tcp->tcp_iphc == NULL) {
			tcp->tcp_iphc_len = 0;
			return (ENOMEM);
		}
	}
	tcp->tcp_ipha = (struct ip *)tcp->tcp_iphc;
	tcp->tcp_ipversion = IPV4_VERSION;

	/*
	 * Note that it does not include TCP options yet.  It will
	 * after the connection is established.
	 */
	tcp->tcp_hdr_len = sizeof (struct ip) + sizeof (tcph_t);
	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
	tcp->tcp_ip_hdr_len = sizeof (struct ip);
	tcp->tcp_ipha->ip_v = IP_VERSION;
	/* We don't support IP options... */
	tcp->tcp_ipha->ip_hl = IP_SIMPLE_HDR_LENGTH_IN_WORDS;
	tcp->tcp_ipha->ip_p = IPPROTO_TCP;
	/* We are not supposed to do PMTU discovery... */
	tcp->tcp_ipha->ip_sum = 0;

	tcph = (tcph_t *)(tcp->tcp_iphc + sizeof (struct ip));
	tcp->tcp_tcph = tcph;
	tcph->th_offset_and_rsrvd[0] = (5 << 4);
	return (0);
}

/*
 * Send out a control packet on the tcp connection specified.  This routine
 * is typically called where we need a simple ACK or RST generated.
 *
 * This function is called with or without a mp.
 */
static void
tcp_xmit_ctl(char *str, tcp_t *tcp, mblk_t *mp, uint32_t seq,
    uint32_t ack, int ctl, uint_t ip_hdr_len, int sock_id)
{
	uchar_t		*rptr;
	tcph_t		*tcph;
	struct ip	*iph = NULL;
	int		tcp_hdr_len;
	int		tcp_ip_hdr_len;

	tcp_hdr_len = tcp->tcp_hdr_len;
	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;

	if (mp) {
		assert(ip_hdr_len != 0);
		rptr = mp->b_rptr;
		tcph = (tcph_t *)(rptr + ip_hdr_len);
		/* Don't reply to a RST segment. */
		if (tcph->th_flags[0] & TH_RST) {
			freeb(mp);
			return;
		}
		freemsg(mp);
		rptr = NULL;
	} else {
		assert(ip_hdr_len == 0);
	}
	/* If a text string is passed in with the request, print it out. */
	if (str != NULL) {
		dprintf("tcp_xmit_ctl(%d): '%s', seq 0x%x, ack 0x%x, "
		    "ctl 0x%x\n", sock_id, str, seq, ack, ctl);
	}
	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcp_wroff_xtra, 0);
	if (mp == NULL) {
		dprintf("tcp_xmit_ctl(%d): Cannot allocate memory\n", sock_id);
		return;
	}
	rptr = &mp->b_rptr[tcp_wroff_xtra];
	mp->b_rptr = rptr;
	mp->b_wptr = &rptr[tcp_hdr_len];
	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);

	iph = (struct ip *)rptr;
	iph->ip_len = htons(tcp_hdr_len);

	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
	tcph->th_flags[0] = (uint8_t)ctl;
	if (ctl & TH_RST) {
		BUMP_MIB(tcp_mib.tcpOutRsts);
		BUMP_MIB(tcp_mib.tcpOutControl);
		/*
		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
		 */
		if (tcp->tcp_snd_ts_ok && tcp->tcp_state > TCPS_SYN_SENT) {
			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
			*(mp->b_wptr) = TCPOPT_EOL;
			iph->ip_len = htons(tcp_hdr_len -
			    TCPOPT_REAL_TS_LEN);
			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
		}
	}
	if (ctl & TH_ACK) {
		uint32_t now = prom_gettime();

		if (tcp->tcp_snd_ts_ok) {
			U32_TO_BE32(now,
			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
			U32_TO_BE32(tcp->tcp_ts_recent,
			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
		}
		tcp->tcp_rack = ack;
		tcp->tcp_rack_cnt = 0;
		BUMP_MIB(tcp_mib.tcpOutAck);
	}
	BUMP_MIB(tcp_mib.tcpOutSegs);
	U32_TO_BE32(seq, tcph->th_seq);
	U32_TO_BE32(ack, tcph->th_ack);

	tcp_set_cksum(mp);
	iph->ip_ttl = (uint8_t)tcp_ipv4_ttl;
	TCP_DUMP_PACKET("tcp_xmit_ctl", mp);
	(void) ipv4_tcp_output(sock_id, mp);
	freeb(mp);
}

/* Generate an ACK-only (no data) segment for a TCP endpoint */
static mblk_t *
tcp_ack_mp(tcp_t *tcp)
{
	if (tcp->tcp_valid_bits) {
		/*
		 * For the complex case where we have to send some
		 * controls (FIN or SYN), let tcp_xmit_mp do it.
		 * When sending an ACK-only segment (no data)
		 * into a zero window, always set the seq number to
		 * suna, since snxt will be extended past the window.
		 * If we used snxt, the receiver might consider the ACK
		 * unacceptable.
		 */
		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
		    (tcp->tcp_zero_win_probe) ?
		    tcp->tcp_suna :
		    tcp->tcp_snxt, B_FALSE, NULL, B_FALSE));
	} else {
		/* Generate a simple ACK */
		uchar_t	*rptr;
		tcph_t	*tcph;
		mblk_t	*mp1;
		int32_t	tcp_hdr_len;
		int32_t	num_sack_blk = 0;
		int32_t sack_opt_len;

		/*
		 * Allocate space for TCP + IP headers
		 * and link-level header
		 */
		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
			    tcp->tcp_num_sack_blk);
			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
		} else {
			tcp_hdr_len = tcp->tcp_hdr_len;
		}
		mp1 = allocb(tcp_hdr_len + tcp_wroff_xtra, 0);
		if (mp1 == NULL)
			return (NULL);

		/* copy in prototype TCP + IP header */
		rptr = mp1->b_rptr + tcp_wroff_xtra;
		mp1->b_rptr = rptr;
		mp1->b_wptr = rptr + tcp_hdr_len;
		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);

		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];

		/*
		 * Set the TCP sequence number.
		 * When sending an ACK-only segment (no data)
		 * into a zero window, always set the seq number to
		 * suna, since snxt will be extended past the window.
		 * If we used snxt, the receiver might consider the ACK
		 * unacceptable.
		 */
		U32_TO_ABE32((tcp->tcp_zero_win_probe) ?
		    tcp->tcp_suna : tcp->tcp_snxt, tcph->th_seq);

		/* Set up the TCP flag field. */
		tcph->th_flags[0] = (uchar_t)TH_ACK;
		if (tcp->tcp_ecn_echo_on)
			tcph->th_flags[0] |= TH_ECE;

		tcp->tcp_rack = tcp->tcp_rnxt;
		tcp->tcp_rack_cnt = 0;

		/* fill in timestamp option if in use */
		if (tcp->tcp_snd_ts_ok) {
			uint32_t llbolt = (uint32_t)prom_gettime();

			U32_TO_BE32(llbolt,
			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
			U32_TO_BE32(tcp->tcp_ts_recent,
			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
		}

		/* Fill in SACK options */
		if (num_sack_blk > 0) {
			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
			sack_blk_t *tmp;
			int32_t	i;

			wptr[0] = TCPOPT_NOP;
			wptr[1] = TCPOPT_NOP;
			wptr[2] = TCPOPT_SACK;
			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
			    sizeof (sack_blk_t);
			wptr += TCPOPT_REAL_SACK_LEN;

			tmp = tcp->tcp_sack_list;
			for (i = 0; i < num_sack_blk; i++) {
				U32_TO_BE32(tmp[i].begin, wptr);
				wptr += sizeof (tcp_seq);
				U32_TO_BE32(tmp[i].end, wptr);
				wptr += sizeof (tcp_seq);
			}
			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
			    << 4);
		}

		((struct ip *)rptr)->ip_len = htons(tcp_hdr_len);
		tcp_set_cksum(mp1);
		((struct ip *)rptr)->ip_ttl = (uint8_t)tcp_ipv4_ttl;
		return (mp1);
	}
}

/*
 * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
 * ip and tcp header ready to pass down to IP.  If the mp passed in is
 * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
 * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
 * otherwise it will dup partial mblks.)
 * Otherwise, an appropriate ACK packet will be generated.  This
 * routine is not usually called to send new data for the first time.  It
 * is mostly called out of the timer for retransmits, and to generate ACKs.
 *
 * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
 * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
 * of the original mblk chain will be returned in *offset and *end_mp.
 */
static mblk_t *
tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
    mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
    boolean_t rexmit)
{
	int	data_length;
	int32_t	off = 0;
	uint_t	flags;
	mblk_t	*mp1;
	mblk_t	*mp2;
	mblk_t	*new_mp;
	uchar_t	*rptr;
	tcph_t	*tcph;
	int32_t	num_sack_blk = 0;
	int32_t	sack_opt_len = 0;

	/* Allocate for our maximum TCP header + link-level */
	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
	    tcp_wroff_xtra, 0);
	if (mp1 == NULL)
		return (NULL);
	data_length = 0;

	/*
	 * Note that tcp_mss has been adjusted to take into account the
	 * timestamp option if applicable.  Because SACK options do not
	 * appear in every TCP segments and they are of variable lengths,
	 * they cannot be included in tcp_mss.  Thus we need to calculate
	 * the actual segment length when we need to send a segment which
	 * includes SACK options.
	 */
	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
		    tcp->tcp_num_sack_blk);
		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
		if (max_to_send + sack_opt_len > tcp->tcp_mss)
			max_to_send -= sack_opt_len;
	}

	if (offset != NULL) {
		off = *offset;
		/* We use offset as an indicator that end_mp is not NULL. */
		*end_mp = NULL;
	}
	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
		/* This could be faster with cooperation from downstream */
		if (mp2 != mp1 && !sendall &&
		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
		    max_to_send)
			/*
			 * Don't send the next mblk since the whole mblk
			 * does not fit.
			 */
			break;
		mp2->b_cont = dupb(mp);
		mp2 = mp2->b_cont;
		if (mp2 == NULL) {
			freemsg(mp1);
			return (NULL);
		}
		mp2->b_rptr += off;
		assert((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
		    (uintptr_t)INT_MAX);

		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
		if (data_length > max_to_send) {
			mp2->b_wptr -= data_length - max_to_send;
			data_length = max_to_send;
			off = mp2->b_wptr - mp->b_rptr;
			break;
		} else {
			off = 0;
		}
	}
	if (offset != NULL) {
		*offset = off;
		*end_mp = mp;
	}
	if (seg_len != NULL) {
		*seg_len = data_length;
	}

	rptr = mp1->b_rptr + tcp_wroff_xtra;
	mp1->b_rptr = rptr;
	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
	U32_TO_ABE32(seq, tcph->th_seq);

	/*
	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
	 * that this function was called from tcp_wput_data. Thus, when called
	 * to retransmit data the setting of the PUSH bit may appear some
	 * what random in that it might get set when it should not. This
	 * should not pose any performance issues.
	 */
	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
	    tcp->tcp_unsent == data_length)) {
		flags = TH_ACK | TH_PUSH;
	} else {
		flags = TH_ACK;
	}

	if (tcp->tcp_ecn_ok) {
		if (tcp->tcp_ecn_echo_on)
			flags |= TH_ECE;

		/*
		 * Only set ECT bit and ECN_CWR if a segment contains new data.
		 * There is no TCP flow control for non-data segments, and
		 * only data segment is transmitted reliably.
		 */
		if (data_length > 0 && !rexmit) {
			SET_ECT(tcp, rptr);
			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
				flags |= TH_CWR;
				tcp->tcp_ecn_cwr_sent = B_TRUE;
			}
		}
	}

	if (tcp->tcp_valid_bits) {
		uint32_t u1;

		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
		    seq == tcp->tcp_iss) {
			uchar_t	*wptr;

			/*
			 * Tack on the MSS option.  It is always needed
			 * for both active and passive open.
			 */
			wptr = mp1->b_wptr;
			wptr[0] = TCPOPT_MAXSEG;
			wptr[1] = TCPOPT_MAXSEG_LEN;
			wptr += 2;
			/*
			 * MSS option value should be interface MTU - MIN
			 * TCP/IP header.
			 */
			u1 = tcp->tcp_if_mtu - IP_SIMPLE_HDR_LENGTH -
			    TCP_MIN_HEADER_LENGTH;
			U16_TO_BE16(u1, wptr);
			mp1->b_wptr = wptr + 2;
			/* Update the offset to cover the additional word */
			tcph->th_offset_and_rsrvd[0] += (1 << 4);

			/*
			 * Note that the following way of filling in
			 * TCP options are not optimal.  Some NOPs can
			 * be saved.  But there is no need at this time
			 * to optimize it.  When it is needed, we will
			 * do it.
			 */
			switch (tcp->tcp_state) {
			case TCPS_SYN_SENT:
				flags = TH_SYN;

				if (tcp->tcp_snd_ws_ok) {
					wptr = mp1->b_wptr;
					wptr[0] =  TCPOPT_NOP;
					wptr[1] =  TCPOPT_WSCALE;
					wptr[2] =  TCPOPT_WS_LEN;
					wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
					mp1->b_wptr += TCPOPT_REAL_WS_LEN;
					tcph->th_offset_and_rsrvd[0] +=
					    (1 << 4);
				}

				if (tcp->tcp_snd_ts_ok) {
					uint32_t llbolt;

					llbolt = prom_gettime();
					wptr = mp1->b_wptr;
					wptr[0] = TCPOPT_NOP;
					wptr[1] = TCPOPT_NOP;
					wptr[2] = TCPOPT_TSTAMP;
					wptr[3] = TCPOPT_TSTAMP_LEN;
					wptr += 4;
					U32_TO_BE32(llbolt, wptr);
					wptr += 4;
					assert(tcp->tcp_ts_recent == 0);
					U32_TO_BE32(0L, wptr);
					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
					tcph->th_offset_and_rsrvd[0] +=
					    (3 << 4);
				}

				if (tcp->tcp_snd_sack_ok) {
					wptr = mp1->b_wptr;
					wptr[0] = TCPOPT_NOP;
					wptr[1] = TCPOPT_NOP;
					wptr[2] = TCPOPT_SACK_PERMITTED;
					wptr[3] = TCPOPT_SACK_OK_LEN;
					mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
					tcph->th_offset_and_rsrvd[0] +=
					    (1 << 4);
				}

				/*
				 * Set up all the bits to tell other side
				 * we are ECN capable.
				 */
				if (tcp->tcp_ecn_ok) {
					flags |= (TH_ECE | TH_CWR);
				}
				break;
			case TCPS_SYN_RCVD:
				flags |= TH_SYN;

				if (tcp->tcp_snd_ws_ok) {
				    wptr = mp1->b_wptr;
				    wptr[0] =  TCPOPT_NOP;
				    wptr[1] =  TCPOPT_WSCALE;
				    wptr[2] =  TCPOPT_WS_LEN;
				    wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
				    mp1->b_wptr += TCPOPT_REAL_WS_LEN;
				    tcph->th_offset_and_rsrvd[0] += (1 << 4);
				}

				if (tcp->tcp_snd_sack_ok) {
					wptr = mp1->b_wptr;
					wptr[0] = TCPOPT_NOP;
					wptr[1] = TCPOPT_NOP;
					wptr[2] = TCPOPT_SACK_PERMITTED;
					wptr[3] = TCPOPT_SACK_OK_LEN;
					mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
					tcph->th_offset_and_rsrvd[0] +=
					    (1 << 4);
				}

				/*
				 * If the other side is ECN capable, reply
				 * that we are also ECN capable.
				 */
				if (tcp->tcp_ecn_ok) {
					flags |= TH_ECE;
				}
				break;
			default:
				break;
			}
			/* allocb() of adequate mblk assures space */
			assert((uintptr_t)(mp1->b_wptr -
			    mp1->b_rptr) <= (uintptr_t)INT_MAX);
			if (flags & TH_SYN)
				BUMP_MIB(tcp_mib.tcpOutControl);
		}
		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
		    (seq + data_length) == tcp->tcp_fss) {
			if (!tcp->tcp_fin_acked) {
				flags |= TH_FIN;
				BUMP_MIB(tcp_mib.tcpOutControl);
			}
			if (!tcp->tcp_fin_sent) {
				tcp->tcp_fin_sent = B_TRUE;
				switch (tcp->tcp_state) {
				case TCPS_SYN_RCVD:
				case TCPS_ESTABLISHED:
					tcp->tcp_state = TCPS_FIN_WAIT_1;
					break;
				case TCPS_CLOSE_WAIT:
					tcp->tcp_state = TCPS_LAST_ACK;
					break;
				}
				if (tcp->tcp_suna == tcp->tcp_snxt) {
					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
				}
				tcp->tcp_snxt = tcp->tcp_fss + 1;
			}
		}
	}
	tcph->th_flags[0] = (uchar_t)flags;
	tcp->tcp_rack = tcp->tcp_rnxt;
	tcp->tcp_rack_cnt = 0;

	if (tcp->tcp_snd_ts_ok) {
		if (tcp->tcp_state != TCPS_SYN_SENT) {
			uint32_t llbolt = prom_gettime();

			U32_TO_BE32(llbolt,
			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
			U32_TO_BE32(tcp->tcp_ts_recent,
			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
		}
	}

	if (num_sack_blk > 0) {
		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
		sack_blk_t *tmp;
		int32_t	i;

		wptr[0] = TCPOPT_NOP;
		wptr[1] = TCPOPT_NOP;
		wptr[2] = TCPOPT_SACK;
		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
		    sizeof (sack_blk_t);
		wptr += TCPOPT_REAL_SACK_LEN;

		tmp = tcp->tcp_sack_list;
		for (i = 0; i < num_sack_blk; i++) {
			U32_TO_BE32(tmp[i].begin, wptr);
			wptr += sizeof (tcp_seq);
			U32_TO_BE32(tmp[i].end, wptr);
			wptr += sizeof (tcp_seq);
		}
		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
	}
	assert((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
	data_length += (int)(mp1->b_wptr - rptr);
	if (tcp->tcp_ipversion == IPV4_VERSION)
		((struct ip *)rptr)->ip_len = htons(data_length);

	/*
	 * Performance hit!  We need to pullup the whole message
	 * in order to do checksum and for the MAC output routine.
	 */
	if (mp1->b_cont != NULL) {
		int mp_size;
#ifdef DEBUG
		printf("Multiple mblk %d\n", msgdsize(mp1));
#endif
		mp2 = mp1;
		new_mp = allocb(msgdsize(mp1) + tcp_wroff_xtra, 0);
		new_mp->b_rptr += tcp_wroff_xtra;
		new_mp->b_wptr = new_mp->b_rptr;
		while (mp1 != NULL) {
			mp_size = mp1->b_wptr - mp1->b_rptr;
			bcopy(mp1->b_rptr, new_mp->b_wptr, mp_size);
			new_mp->b_wptr += mp_size;
			mp1 = mp1->b_cont;
		}
		freemsg(mp2);
		mp1 = new_mp;
	}
	tcp_set_cksum(mp1);
	/* Fill in the TTL field as it is 0 in the header template. */
	((struct ip *)mp1->b_rptr)->ip_ttl = (uint8_t)tcp_ipv4_ttl;

	return (mp1);
}

/*
 * Generate a "no listener here" reset in response to the
 * connection request contained within 'mp'
 */
static void
tcp_xmit_listeners_reset(int sock_id, mblk_t *mp, uint_t ip_hdr_len)
{
	uchar_t		*rptr;
	uint32_t	seg_len;
	tcph_t		*tcph;
	uint32_t	seg_seq;
	uint32_t	seg_ack;
	uint_t		flags;

	rptr = mp->b_rptr;

	tcph = (tcph_t *)&rptr[ip_hdr_len];
	seg_seq = BE32_TO_U32(tcph->th_seq);
	seg_ack = BE32_TO_U32(tcph->th_ack);
	flags = tcph->th_flags[0];

	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
	if (flags & TH_RST) {
		freeb(mp);
	} else if (flags & TH_ACK) {
		tcp_xmit_early_reset("no tcp, reset",
		    sock_id, mp, seg_ack, 0, TH_RST, ip_hdr_len);
	} else {
		if (flags & TH_SYN)
			seg_len++;
		tcp_xmit_early_reset("no tcp, reset/ack", sock_id,
		    mp, 0, seg_seq + seg_len,
		    TH_RST | TH_ACK, ip_hdr_len);
	}
}

/* Non overlapping byte exchanger */
static void
tcp_xchg(uchar_t *a, uchar_t *b, int len)
{
	uchar_t	uch;

	while (len-- > 0) {
		uch = a[len];
		a[len] = b[len];
		b[len] = uch;
	}
}

/*
 * Generate a reset based on an inbound packet for which there is no active
 * tcp state that we can find.
 */
static void
tcp_xmit_early_reset(char *str, int sock_id, mblk_t *mp, uint32_t seq,
    uint32_t ack, int ctl, uint_t ip_hdr_len)
{
	struct ip	*iph = NULL;
	ushort_t	len;
	tcph_t		*tcph;
	int		i;
	ipaddr_t	addr;
	mblk_t		*new_mp;

	if (str != NULL) {
		dprintf("tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
		    "flags 0x%x\n", str, seq, ack, ctl);
	}

	/*
	 * We skip reversing source route here.
	 * (for now we replace all IP options with EOL)
	 */
	iph = (struct ip *)mp->b_rptr;
	for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
		mp->b_rptr[i] = IPOPT_EOL;
	/*
	 * Make sure that src address is not a limited broadcast
	 * address. Not all broadcast address checking for the
	 * src address is possible, since we don't know the
	 * netmask of the src addr.
	 * No check for destination address is done, since
	 * IP will not pass up a packet with a broadcast dest address
	 * to TCP.
	 */
	if (iph->ip_src.s_addr == INADDR_ANY ||
	    iph->ip_src.s_addr == INADDR_BROADCAST) {
		freemsg(mp);
		return;
	}

	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
	if (tcph->th_flags[0] & TH_RST) {
		freemsg(mp);
		return;
	}
	/*
	 * Now copy the original header to a new buffer.  The reason
	 * for doing this is that we need to put extra room before
	 * the header for the MAC layer address.  The original mblk
	 * does not have this extra head room.
	 */
	len = ip_hdr_len + sizeof (tcph_t);
	if ((new_mp = allocb(len + tcp_wroff_xtra, 0)) == NULL) {
		freemsg(mp);
		return;
	}
	new_mp->b_rptr += tcp_wroff_xtra;
	bcopy(mp->b_rptr, new_mp->b_rptr, len);
	new_mp->b_wptr = new_mp->b_rptr + len;
	freemsg(mp);
	mp = new_mp;
	iph = (struct ip *)mp->b_rptr;
	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];

	tcph->th_offset_and_rsrvd[0] = (5 << 4);
	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
	U32_TO_BE32(ack, tcph->th_ack);
	U32_TO_BE32(seq, tcph->th_seq);
	U16_TO_BE16(0, tcph->th_win);
	bzero(tcph->th_sum, sizeof (int16_t));
	tcph->th_flags[0] = (uint8_t)ctl;
	if (ctl & TH_RST) {
		BUMP_MIB(tcp_mib.tcpOutRsts);
		BUMP_MIB(tcp_mib.tcpOutControl);
	}

	iph->ip_len = htons(len);
	/* Swap addresses */
	addr = iph->ip_src.s_addr;
	iph->ip_src = iph->ip_dst;
	iph->ip_dst.s_addr = addr;
	iph->ip_id = 0;
	iph->ip_ttl = 0;
	tcp_set_cksum(mp);
	iph->ip_ttl = (uint8_t)tcp_ipv4_ttl;

	/* Dump the packet when debugging. */
	TCP_DUMP_PACKET("tcp_xmit_early_reset", mp);
	(void) ipv4_tcp_output(sock_id, mp);
	freemsg(mp);
}

static void
tcp_set_cksum(mblk_t *mp)
{
	struct ip *iph;
	tcpha_t *tcph;
	int len;

	iph = (struct ip *)mp->b_rptr;
	tcph = (tcpha_t *)(iph + 1);
	len = ntohs(iph->ip_len);
	/*
	 * Calculate the TCP checksum.  Need to include the psuedo header,
	 * which is similar to the real IP header starting at the TTL field.
	 */
	iph->ip_sum = htons(len - IP_SIMPLE_HDR_LENGTH);
	tcph->tha_sum = 0;
	tcph->tha_sum = tcp_cksum((uint16_t *)&(iph->ip_ttl),
	    len - IP_SIMPLE_HDR_LENGTH + 12);
	iph->ip_sum = 0;
}

static uint16_t
tcp_cksum(uint16_t *buf, uint32_t len)
{
	/*
	 * Compute Internet Checksum for "count" bytes
	 * beginning at location "addr".
	 */
	int32_t sum = 0;

	while (len > 1) {
		/*  This is the inner loop */
		sum += *buf++;
		len -= 2;
	}

	/*  Add left-over byte, if any */
	if (len > 0)
		sum += *(unsigned char *)buf * 256;

	/*  Fold 32-bit sum to 16 bits */
	while (sum >> 16)
		sum = (sum & 0xffff) + (sum >> 16);

	return ((uint16_t)~sum);
}

/*
 * Type three generator adapted from the random() function in 4.4 BSD:
 */

/*
 * Copyright (c) 1983, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

/* Type 3 -- x**31 + x**3 + 1 */
#define	DEG_3		31
#define	SEP_3		3


/* Protected by tcp_random_lock */
static int tcp_randtbl[DEG_3 + 1];

static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
static int *tcp_random_rptr = &tcp_randtbl[1];

static int *tcp_random_state = &tcp_randtbl[1];
static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];

static void
tcp_random_init(void)
{
	int i;
	uint32_t hrt;
	uint32_t wallclock;
	uint32_t result;

	/*
	 *
	 * XXX We don't have high resolution time in standalone...  The
	 * following is just some approximation on the comment below.
	 *
	 * Use high-res timer and current time for seed.  Gethrtime() returns
	 * a longlong, which may contain resolution down to nanoseconds.
	 * The current time will either be a 32-bit or a 64-bit quantity.
	 * XOR the two together in a 64-bit result variable.
	 * Convert the result to a 32-bit value by multiplying the high-order
	 * 32-bits by the low-order 32-bits.
	 *
	 * XXX We don't have gethrtime() in prom and the wallclock....
	 */

	hrt = prom_gettime();
	wallclock = (uint32_t)time(NULL);
	result = wallclock ^ hrt;
	tcp_random_state[0] = result;

	for (i = 1; i < DEG_3; i++)
		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
			+ 12345;
	tcp_random_fptr = &tcp_random_state[SEP_3];
	tcp_random_rptr = &tcp_random_state[0];
	for (i = 0; i < 10 * DEG_3; i++)
		(void) tcp_random();
}

/*
 * tcp_random: Return a random number in the range [1 - (128K + 1)].
 * This range is selected to be approximately centered on TCP_ISS / 2,
 * and easy to compute. We get this value by generating a 32-bit random
 * number, selecting out the high-order 17 bits, and then adding one so
 * that we never return zero.
 */
static int
tcp_random(void)
{
	int i;

	*tcp_random_fptr += *tcp_random_rptr;

	/*
	 * The high-order bits are more random than the low-order bits,
	 * so we select out the high-order 17 bits and add one so that
	 * we never return zero.
	 */
	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
	if (++tcp_random_fptr >= tcp_random_end_ptr) {
		tcp_random_fptr = tcp_random_state;
		++tcp_random_rptr;
	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
		tcp_random_rptr = tcp_random_state;

	return (i);
}

/*
 * Generate ISS, taking into account NDD changes may happen halfway through.
 * (If the iss is not zero, set it.)
 */
static void
tcp_iss_init(tcp_t *tcp)
{
	tcp_iss_incr_extra += (ISS_INCR >> 1);
	tcp->tcp_iss = tcp_iss_incr_extra;
	tcp->tcp_iss += (prom_gettime() >> ISS_NSEC_SHT) + tcp_random();
	tcp->tcp_valid_bits = TCP_ISS_VALID;
	tcp->tcp_fss = tcp->tcp_iss - 1;
	tcp->tcp_suna = tcp->tcp_iss;
	tcp->tcp_snxt = tcp->tcp_iss + 1;
	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
	tcp->tcp_csuna = tcp->tcp_snxt;
}

/*
 * Diagnostic routine used to return a string associated with the tcp state.
 * Note that if the caller does not supply a buffer, it will use an internal
 * static string.  This means that if multiple threads call this function at
 * the same time, output can be corrupted...  Note also that this function
 * does not check the size of the supplied buffer.  The caller has to make
 * sure that it is big enough.
 */
static char *
tcp_display(tcp_t *tcp, char *sup_buf, char format)
{
	char		buf1[30];
	static char	priv_buf[INET_ADDRSTRLEN * 2 + 80];
	char		*buf;
	char		*cp;
	char		local_addrbuf[INET_ADDRSTRLEN];
	char		remote_addrbuf[INET_ADDRSTRLEN];
	struct in_addr	addr;

	if (sup_buf != NULL)
		buf = sup_buf;
	else
		buf = priv_buf;

	if (tcp == NULL)
		return ("NULL_TCP");
	switch (tcp->tcp_state) {
	case TCPS_CLOSED:
		cp = "TCP_CLOSED";
		break;
	case TCPS_IDLE:
		cp = "TCP_IDLE";
		break;
	case TCPS_BOUND:
		cp = "TCP_BOUND";
		break;
	case TCPS_LISTEN:
		cp = "TCP_LISTEN";
		break;
	case TCPS_SYN_SENT:
		cp = "TCP_SYN_SENT";
		break;
	case TCPS_SYN_RCVD:
		cp = "TCP_SYN_RCVD";
		break;
	case TCPS_ESTABLISHED:
		cp = "TCP_ESTABLISHED";
		break;
	case TCPS_CLOSE_WAIT:
		cp = "TCP_CLOSE_WAIT";
		break;
	case TCPS_FIN_WAIT_1:
		cp = "TCP_FIN_WAIT_1";
		break;
	case TCPS_CLOSING:
		cp = "TCP_CLOSING";
		break;
	case TCPS_LAST_ACK:
		cp = "TCP_LAST_ACK";
		break;
	case TCPS_FIN_WAIT_2:
		cp = "TCP_FIN_WAIT_2";
		break;
	case TCPS_TIME_WAIT:
		cp = "TCP_TIME_WAIT";
		break;
	default:
		(void) sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
		cp = buf1;
		break;
	}
	switch (format) {
	case DISP_ADDR_AND_PORT:
		/*
		 * Note that we use the remote address in the tcp_b
		 * structure.  This means that it will print out
		 * the real destination address, not the next hop's
		 * address if source routing is used.
		 */
		addr.s_addr = tcp->tcp_bound_source;
		bcopy(inet_ntoa(addr), local_addrbuf, sizeof (local_addrbuf));
		addr.s_addr = tcp->tcp_remote;
		bcopy(inet_ntoa(addr), remote_addrbuf, sizeof (remote_addrbuf));
		(void) snprintf(buf, sizeof (priv_buf), "[%s.%u, %s.%u] %s",
		    local_addrbuf, ntohs(tcp->tcp_lport), remote_addrbuf,
		    ntohs(tcp->tcp_fport), cp);
		break;
	case DISP_PORT_ONLY:
	default:
		(void) snprintf(buf, sizeof (priv_buf), "[%u, %u] %s",
		    ntohs(tcp->tcp_lport), ntohs(tcp->tcp_fport), cp);
		break;
	}

	return (buf);
}

/*
 * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
 * is filled, return as much as we can.  The message passed in may be
 * multi-part, chained using b_cont.  "start" is the starting sequence
 * number for this piece.
 */
static mblk_t *
tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
{
	uint32_t	end;
	mblk_t		*mp1;
	mblk_t		*mp2;
	mblk_t		*next_mp;
	uint32_t	u1;

	/* Walk through all the new pieces. */
	do {
		assert((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
		    (uintptr_t)INT_MAX);
		end = start + (int)(mp->b_wptr - mp->b_rptr);
		next_mp = mp->b_cont;
		if (start == end) {
			/* Empty.  Blast it. */
			freeb(mp);
			continue;
		}
		mp->b_cont = NULL;
		TCP_REASS_SET_SEQ(mp, start);
		TCP_REASS_SET_END(mp, end);
		mp1 = tcp->tcp_reass_tail;
		if (!mp1) {
			tcp->tcp_reass_tail = mp;
			tcp->tcp_reass_head = mp;
			BUMP_MIB(tcp_mib.tcpInDataUnorderSegs);
			UPDATE_MIB(tcp_mib.tcpInDataUnorderBytes, end - start);
			continue;
		}
		/* New stuff completely beyond tail? */
		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
			/* Link it on end. */
			mp1->b_cont = mp;
			tcp->tcp_reass_tail = mp;
			BUMP_MIB(tcp_mib.tcpInDataUnorderSegs);
			UPDATE_MIB(tcp_mib.tcpInDataUnorderBytes, end - start);
			continue;
		}
		mp1 = tcp->tcp_reass_head;
		u1 = TCP_REASS_SEQ(mp1);
		/* New stuff at the front? */
		if (SEQ_LT(start, u1)) {
			/* Yes... Check for overlap. */
			mp->b_cont = mp1;
			tcp->tcp_reass_head = mp;
			tcp_reass_elim_overlap(tcp, mp);
			continue;
		}
		/*
		 * The new piece fits somewhere between the head and tail.
		 * We find our slot, where mp1 precedes us and mp2 trails.
		 */
		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
			u1 = TCP_REASS_SEQ(mp2);
			if (SEQ_LEQ(start, u1))
				break;
		}
		/* Link ourselves in */
		mp->b_cont = mp2;
		mp1->b_cont = mp;

		/* Trim overlap with following mblk(s) first */
		tcp_reass_elim_overlap(tcp, mp);

		/* Trim overlap with preceding mblk */
		tcp_reass_elim_overlap(tcp, mp1);

	} while (start = end, mp = next_mp);
	mp1 = tcp->tcp_reass_head;
	/* Anything ready to go? */
	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
		return (NULL);
	/* Eat what we can off the queue */
	for (;;) {
		mp = mp1->b_cont;
		end = TCP_REASS_END(mp1);
		TCP_REASS_SET_SEQ(mp1, 0);
		TCP_REASS_SET_END(mp1, 0);
		if (!mp) {
			tcp->tcp_reass_tail = NULL;
			break;
		}
		if (end != TCP_REASS_SEQ(mp)) {
			mp1->b_cont = NULL;
			break;
		}
		mp1 = mp;
	}
	mp1 = tcp->tcp_reass_head;
	tcp->tcp_reass_head = mp;
	return (mp1);
}

/* Eliminate any overlap that mp may have over later mblks */
static void
tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
{
	uint32_t	end;
	mblk_t		*mp1;
	uint32_t	u1;

	end = TCP_REASS_END(mp);
	while ((mp1 = mp->b_cont) != NULL) {
		u1 = TCP_REASS_SEQ(mp1);
		if (!SEQ_GT(end, u1))
			break;
		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
			mp->b_wptr -= end - u1;
			TCP_REASS_SET_END(mp, u1);
			BUMP_MIB(tcp_mib.tcpInDataPartDupSegs);
			UPDATE_MIB(tcp_mib.tcpInDataPartDupBytes, end - u1);
			break;
		}
		mp->b_cont = mp1->b_cont;
		freeb(mp1);
		BUMP_MIB(tcp_mib.tcpInDataDupSegs);
		UPDATE_MIB(tcp_mib.tcpInDataDupBytes, end - u1);
	}
	if (!mp1)
		tcp->tcp_reass_tail = mp;
}

/*
 * Remove a connection from the list of detached TIME_WAIT connections.
 */
static void
tcp_time_wait_remove(tcp_t *tcp)
{
	if (tcp->tcp_time_wait_expire == 0) {
		assert(tcp->tcp_time_wait_next == NULL);
		assert(tcp->tcp_time_wait_prev == NULL);
		return;
	}
	assert(tcp->tcp_state == TCPS_TIME_WAIT);
	if (tcp == tcp_time_wait_head) {
		assert(tcp->tcp_time_wait_prev == NULL);
		tcp_time_wait_head = tcp->tcp_time_wait_next;
		if (tcp_time_wait_head != NULL) {
			tcp_time_wait_head->tcp_time_wait_prev = NULL;
		} else {
			tcp_time_wait_tail = NULL;
		}
	} else if (tcp == tcp_time_wait_tail) {
		assert(tcp != tcp_time_wait_head);
		assert(tcp->tcp_time_wait_next == NULL);
		tcp_time_wait_tail = tcp->tcp_time_wait_prev;
		assert(tcp_time_wait_tail != NULL);
		tcp_time_wait_tail->tcp_time_wait_next = NULL;
	} else {
		assert(tcp->tcp_time_wait_prev->tcp_time_wait_next == tcp);
		assert(tcp->tcp_time_wait_next->tcp_time_wait_prev == tcp);
		tcp->tcp_time_wait_prev->tcp_time_wait_next =
		    tcp->tcp_time_wait_next;
		tcp->tcp_time_wait_next->tcp_time_wait_prev =
		    tcp->tcp_time_wait_prev;
	}
	tcp->tcp_time_wait_next = NULL;
	tcp->tcp_time_wait_prev = NULL;
	tcp->tcp_time_wait_expire = 0;
}

/*
 * Add a connection to the list of detached TIME_WAIT connections
 * and set its time to expire ...
 */
static void
tcp_time_wait_append(tcp_t *tcp)
{
	tcp->tcp_time_wait_expire = prom_gettime() + tcp_time_wait_interval;
	if (tcp->tcp_time_wait_expire == 0)
		tcp->tcp_time_wait_expire = 1;

	if (tcp_time_wait_head == NULL) {
		assert(tcp_time_wait_tail == NULL);
		tcp_time_wait_head = tcp;
	} else {
		assert(tcp_time_wait_tail != NULL);
		assert(tcp_time_wait_tail->tcp_state == TCPS_TIME_WAIT);
		tcp_time_wait_tail->tcp_time_wait_next = tcp;
		tcp->tcp_time_wait_prev = tcp_time_wait_tail;
	}
	tcp_time_wait_tail = tcp;

	/* for ndd stats about compression */
	tcp_cum_timewait++;
}

/*
 * Periodic qtimeout routine run on the default queue.
 * Performs 2 functions.
 * 	1.  Does TIME_WAIT compression on all recently added tcps. List
 *	    traversal is done backwards from the tail.
 *	2.  Blows away all tcps whose TIME_WAIT has expired. List traversal
 *	    is done forwards from the head.
 */
void
tcp_time_wait_collector(void)
{
	tcp_t *tcp;
	uint32_t now;

	/*
	 * In order to reap time waits reliably, we should use a
	 * source of time that is not adjustable by the user
	 */
	now = prom_gettime();
	while ((tcp = tcp_time_wait_head) != NULL) {
		/*
		 * Compare times using modular arithmetic, since
		 * lbolt can wrapover.
		 */
		if ((int32_t)(now - tcp->tcp_time_wait_expire) < 0) {
			break;
		}
		/*
		 * Note that the err must be 0 as there is no socket
		 * associated with this TCP...
		 */
		(void) tcp_clean_death(-1, tcp, 0);
	}
	/* Schedule next run time. */
	tcp_time_wait_runtime = prom_gettime() + 10000;
}

void
tcp_time_wait_report(void)
{
	tcp_t *tcp;

	printf("Current time %u\n", prom_gettime());
	for (tcp = tcp_time_wait_head; tcp != NULL;
	    tcp = tcp->tcp_time_wait_next) {
		printf("%s expires at %u\n", tcp_display(tcp, NULL,
		    DISP_ADDR_AND_PORT), tcp->tcp_time_wait_expire);
	}
}

/*
 * Send up all messages queued on tcp_rcv_list.
 * Have to set tcp_co_norm since we use putnext.
 */
static void
tcp_rcv_drain(int sock_id, tcp_t *tcp)
{
	mblk_t *mp;
	struct inetgram *in_gram;
	mblk_t *in_mp;
	int len;

	/* Don't drain if the app has not finished reading all the data. */
	if (sockets[sock_id].so_rcvbuf <= 0)
		return;

	/* We might have come here just to updated the rwnd */
	if (tcp->tcp_rcv_list == NULL)
		goto win_update;

	if ((in_gram = (struct inetgram *)bkmem_zalloc(
	    sizeof (struct inetgram))) == NULL) {
		return;
	}
	if ((in_mp = allocb(tcp->tcp_rcv_cnt, 0)) == NULL) {
		bkmem_free((caddr_t)in_gram, sizeof (struct inetgram));
		return;
	}
	in_gram->igm_level = APP_LVL;
	in_gram->igm_mp = in_mp;
	in_gram->igm_id = 0;

	while ((mp = tcp->tcp_rcv_list) != NULL) {
		tcp->tcp_rcv_list = mp->b_cont;
		len = mp->b_wptr - mp->b_rptr;
		bcopy(mp->b_rptr, in_mp->b_wptr, len);
		in_mp->b_wptr += len;
		freeb(mp);
	}

	tcp->tcp_rcv_last_tail = NULL;
	tcp->tcp_rcv_cnt = 0;
	add_grams(&sockets[sock_id].inq, in_gram);

	/* This means that so_rcvbuf can be less than 0. */
	sockets[sock_id].so_rcvbuf -= in_mp->b_wptr - in_mp->b_rptr;
win_update:
	/*
	 * Increase the receive window to max.  But we need to do receiver
	 * SWS avoidance.  This means that we need to check the increase of
	 * of receive window is at least 1 MSS.
	 */
	if (sockets[sock_id].so_rcvbuf > 0 &&
	    (tcp->tcp_rwnd_max - tcp->tcp_rwnd >= tcp->tcp_mss)) {
		tcp->tcp_rwnd = tcp->tcp_rwnd_max;
		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
		    tcp->tcp_tcph->th_win);
	}
}

/*
 * Wrapper for recvfrom to call
 */
void
tcp_rcv_drain_sock(int sock_id)
{
	tcp_t *tcp;
	if ((tcp = sockets[sock_id].pcb) == NULL)
		return;
	tcp_rcv_drain(sock_id, tcp);
}

/*
 * If the inq == NULL and the tcp_rcv_list != NULL, we have data that
 * recvfrom could read. Place a magic message in the inq to let recvfrom
 * know that it needs to call tcp_rcv_drain_sock to pullup the data.
 */
static void
tcp_drain_needed(int sock_id, tcp_t *tcp)
{
	struct inetgram *in_gram;
#ifdef DEBUG
	printf("tcp_drain_needed: inq %x, tcp_rcv_list %x\n",
		sockets[sock_id].inq, tcp->tcp_rcv_list);
#endif
	if ((sockets[sock_id].inq != NULL) ||
		(tcp->tcp_rcv_list == NULL))
		return;

	if ((in_gram = (struct inetgram *)bkmem_zalloc(
		sizeof (struct inetgram))) == NULL)
		return;

	in_gram->igm_level = APP_LVL;
	in_gram->igm_mp = NULL;
	in_gram->igm_id = TCP_CALLB_MAGIC_ID;

	add_grams(&sockets[sock_id].inq, in_gram);
}

/*
 * Queue data on tcp_rcv_list which is a b_next chain.
 * Each element of the chain is a b_cont chain.
 *
 * M_DATA messages are added to the current element.
 * Other messages are added as new (b_next) elements.
 */
static void
tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len)
{
	assert(seg_len == msgdsize(mp));
	if (tcp->tcp_rcv_list == NULL) {
		tcp->tcp_rcv_list = mp;
	} else {
		tcp->tcp_rcv_last_tail->b_cont = mp;
	}
	while (mp->b_cont)
		mp = mp->b_cont;
	tcp->tcp_rcv_last_tail = mp;
	tcp->tcp_rcv_cnt += seg_len;
	tcp->tcp_rwnd -= seg_len;
#ifdef DEBUG
	printf("tcp_rcv_enqueue rwnd %d\n", tcp->tcp_rwnd);
#endif
	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win);
}

/* The minimum of smoothed mean deviation in RTO calculation. */
#define	TCP_SD_MIN	400

/*
 * Set RTO for this connection.  The formula is from Jacobson and Karels'
 * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
 * are the same as those in Appendix A.2 of that paper.
 *
 * m = new measurement
 * sa = smoothed RTT average (8 * average estimates).
 * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
 */
static void
tcp_set_rto(tcp_t *tcp, int32_t rtt)
{
	int32_t m = rtt;
	uint32_t sa = tcp->tcp_rtt_sa;
	uint32_t sv = tcp->tcp_rtt_sd;
	uint32_t rto;

	BUMP_MIB(tcp_mib.tcpRttUpdate);
	tcp->tcp_rtt_update++;

	/* tcp_rtt_sa is not 0 means this is a new sample. */
	if (sa != 0) {
		/*
		 * Update average estimator:
		 *	new rtt = 7/8 old rtt + 1/8 Error
		 */

		/* m is now Error in estimate. */
		m -= sa >> 3;
		if ((int32_t)(sa += m) <= 0) {
			/*
			 * Don't allow the smoothed average to be negative.
			 * We use 0 to denote reinitialization of the
			 * variables.
			 */
			sa = 1;
		}

		/*
		 * Update deviation estimator:
		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
		 */
		if (m < 0)
			m = -m;
		m -= sv >> 2;
		sv += m;
	} else {
		/*
		 * This follows BSD's implementation.  So the reinitialized
		 * RTO is 3 * m.  We cannot go less than 2 because if the
		 * link is bandwidth dominated, doubling the window size
		 * during slow start means doubling the RTT.  We want to be
		 * more conservative when we reinitialize our estimates.  3
		 * is just a convenient number.
		 */
		sa = m << 3;
		sv = m << 1;
	}
	if (sv < TCP_SD_MIN) {
		/*
		 * We do not know that if sa captures the delay ACK
		 * effect as in a long train of segments, a receiver
		 * does not delay its ACKs.  So set the minimum of sv
		 * to be TCP_SD_MIN, which is default to 400 ms, twice
		 * of BSD DATO.  That means the minimum of mean
		 * deviation is 100 ms.
		 *
		 */
		sv = TCP_SD_MIN;
	}
	tcp->tcp_rtt_sa = sa;
	tcp->tcp_rtt_sd = sv;
	/*
	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
	 *
	 * Add tcp_rexmit_interval extra in case of extreme environment
	 * where the algorithm fails to work.  The default value of
	 * tcp_rexmit_interval_extra should be 0.
	 *
	 * As we use a finer grained clock than BSD and update
	 * RTO for every ACKs, add in another .25 of RTT to the
	 * deviation of RTO to accomodate burstiness of 1/4 of
	 * window size.
	 */
	rto = (sa >> 3) + sv + tcp_rexmit_interval_extra + (sa >> 5);

	if (rto > tcp_rexmit_interval_max) {
		tcp->tcp_rto = tcp_rexmit_interval_max;
	} else if (rto < tcp_rexmit_interval_min) {
		tcp->tcp_rto = tcp_rexmit_interval_min;
	} else {
		tcp->tcp_rto = rto;
	}

	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
	tcp->tcp_timer_backoff = 0;
}

/*
 * Initiate closedown sequence on an active connection.
 * Return value zero for OK return, non-zero for error return.
 */
static int
tcp_xmit_end(tcp_t *tcp, int sock_id)
{
	mblk_t	*mp;

	if (tcp->tcp_state < TCPS_SYN_RCVD ||
	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
		/*
		 * Invalid state, only states TCPS_SYN_RCVD,
		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
		 */
		return (-1);
	}

	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
	tcp->tcp_valid_bits |= TCP_FSS_VALID;
	/*
	 * If there is nothing more unsent, send the FIN now.
	 * Otherwise, it will go out with the last segment.
	 */
	if (tcp->tcp_unsent == 0) {
		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);

		if (mp != NULL) {
			/* Dump the packet when debugging. */
			TCP_DUMP_PACKET("tcp_xmit_end", mp);
			(void) ipv4_tcp_output(sock_id, mp);
			freeb(mp);
		} else {
			/*
			 * Couldn't allocate msg.  Pretend we got it out.
			 * Wait for rexmit timeout.
			 */
			tcp->tcp_snxt = tcp->tcp_fss + 1;
			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
		}

		/*
		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
		 * changed.
		 */
		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
		}
	} else {
		tcp_wput_data(tcp, NULL, B_FALSE);
	}

	return (0);
}

int
tcp_opt_set(tcp_t *tcp, int level, int option, const void *optval,
    socklen_t optlen)
{
	switch (level) {
	case SOL_SOCKET: {
		switch (option) {
		case SO_RCVBUF:
			if (optlen == sizeof (int)) {
				int val = *(int *)optval;

				if (val > tcp_max_buf) {
					errno = ENOBUFS;
					break;
				}
				/* Silently ignore zero */
				if (val != 0) {
					val = MSS_ROUNDUP(val, tcp->tcp_mss);
					(void) tcp_rwnd_set(tcp, val);
				}
			} else {
				errno = EINVAL;
			}
			break;
		case SO_SNDBUF:
			if (optlen == sizeof (int)) {
				tcp->tcp_xmit_hiwater = *(int *)optval;
				if (tcp->tcp_xmit_hiwater > tcp_max_buf)
					tcp->tcp_xmit_hiwater = tcp_max_buf;
			} else {
				errno = EINVAL;
			}
			break;
		case SO_LINGER:
			if (optlen == sizeof (struct linger)) {
				struct linger *lgr = (struct linger *)optval;

				if (lgr->l_onoff) {
					tcp->tcp_linger = 1;
					tcp->tcp_lingertime = lgr->l_linger;
				} else {
					tcp->tcp_linger = 0;
					tcp->tcp_lingertime = 0;
				}
			} else {
				errno = EINVAL;
			}
			break;
		default:
			errno = ENOPROTOOPT;
			break;
		}
		break;
	} /* case SOL_SOCKET */
	case IPPROTO_TCP: {
		switch (option) {
		default:
			errno = ENOPROTOOPT;
			break;
		}
		break;
	} /* case IPPROTO_TCP */
	case IPPROTO_IP: {
		switch (option) {
		default:
			errno = ENOPROTOOPT;
			break;
		}
		break;
	} /* case IPPROTO_IP */
	default:
		errno = ENOPROTOOPT;
		break;
	} /* switch (level) */

	if (errno != 0)
		return (-1);
	else
		return (0);
}
/*
 * Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * Copyright (c) 1982, 1986 Regents of the University of California.
 * All rights reserved. The Berkeley software License Agreement
 * specifies the terms and conditions for redistribution.
 */

#ifndef _TCP_INET_H
#define	_TCP_INET_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#ifdef	__cplusplus
extern "C" {
#endif

#include "tcp_sack.h"

/* TCP states */
#define	TCPS_ALL_ACKED		-7	/* Internal state for retransmissions */
#define	TCPS_CLOSED		-6
#define	TCPS_IDLE		-5	/* idle (opened, but not bound) */
#define	TCPS_BOUND		-4	/* bound, ready to connect or accept */
#define	TCPS_LISTEN		-3	/* listening for connection */
#define	TCPS_SYN_SENT		-2	/* active, have sent syn */
#define	TCPS_SYN_RCVD		-1	/* have received syn (and sent ours) */
/* states < TCPS_ESTABLISHED are those where connections not established */
#define	TCPS_ESTABLISHED	0	/* established */
#define	TCPS_CLOSE_WAIT		1	/* rcvd fin, waiting for close */
/* states > TCPS_CLOSE_WAIT are those where user has closed */
#define	TCPS_FIN_WAIT_1		2	/* have closed and sent fin */
#define	TCPS_CLOSING		3	/* closed, xchd FIN, await FIN ACK */
#define	TCPS_LAST_ACK		4	/* had fin and close; await FIN ACK */
/* states > TCPS_CLOSE_WAIT && < TCPS_FIN_WAIT_2 await ACK of FIN */
#define	TCPS_FIN_WAIT_2		5	/* have closed, fin is acked */
#define	TCPS_TIME_WAIT		6	/* in 2*msl quiet wait after close */

/*
 * Internal flags used in conjunction with the packet header flags.
 * Used in tcp_rput_data to keep track of what needs to be done.
 */
#define	TH_LIMIT_XMIT		0x0400	/* Limited xmit is needed */
#define	TH_XMIT_NEEDED		0x0800	/* Window opened - send queued data */
#define	TH_REXMIT_NEEDED	0x1000	/* Time expired for unacked data */
#define	TH_ACK_NEEDED		0x2000	/* Send an ack now. */
#define	TH_NEED_SACK_REXMIT	0x4000	/* Use SACK info to retransmission */
#define	TH_TIMER_NEEDED 0x8000	/* Start the delayed ack/push bit timer */

/*
 * Special Magic number used by TCP to issue a callback to recvfrom() in the
 * form of a dummy inetgram.
 */
#define	TCP_CALLB_MAGIC_ID	0xFFFF

/*
 * TCP sequence numbers are 32 bit integers operated
 * on with modular arithmetic.  These macros can be
 * used to compare such integers.
 */
#define	SEQ_LT(a, b)	((int32_t)((a)-(b)) < 0)
#define	SEQ_LEQ(a, b)	((int32_t)((a)-(b)) <= 0)
#define	SEQ_GT(a, b)	((int32_t)((a)-(b)) > 0)
#define	SEQ_GEQ(a, b)	((int32_t)((a)-(b)) >= 0)

/* TCP Protocol header */
typedef	struct tcphdr_s {
	uint8_t		th_lport[2];	/* Source port */
	uint8_t		th_fport[2];	/* Destination port */
	uint8_t		th_seq[4];	/* Sequence number */
	uint8_t		th_ack[4];	/* Acknowledgement number */
	uint8_t		th_offset_and_rsrvd[1]; /* Offset to the packet data */
	uint8_t		th_flags[1];
	uint8_t		th_win[2];	/* Allocation number */
	uint8_t		th_sum[2];	/* TCP checksum */
	uint8_t		th_urp[2];	/* Urgent pointer */
} tcph_t;

#define	TCP_HDR_LENGTH(tcph) (((tcph)->th_offset_and_rsrvd[0] >>2) &(0xF << 2))
#define	TCP_MAX_COMBINED_HEADER_LENGTH	(60 + 60) /* Maxed out ip + tcp */
#define	TCP_MAX_IP_OPTIONS_LENGTH	(60 - IP_SIMPLE_HDR_LENGTH)
#define	TCP_MAX_HDR_LENGTH		60
#define	TCP_MAX_TCP_OPTIONS_LENGTH	(60 - sizeof (tcph_t))
#define	TCP_MIN_HEADER_LENGTH		20
#define	TCP_MAXWIN			65535
#define	TCP_PORT_LEN			sizeof (in_port_t)
#define	TCP_MAX_WINSHIFT		14
#define	TCP_MAX_LARGEWIN		(TCP_MAXWIN << TCP_MAX_WINSHIFT)

#define	TCPIP_HDR_LENGTH(mp, n)					\
	(n) = IPH_HDR_LENGTH((mp)->b_rptr),			\
	(n) += TCP_HDR_LENGTH((tcph_t *)&(mp)->b_rptr[(n)])

/* TCP Protocol header (used if the header is known to be 32-bit aligned) */
typedef	struct tcphdra_s {
	in_port_t	tha_lport;	/* Source port */
	in_port_t	tha_fport;	/* Destination port */
	uint32_t	tha_seq;	/* Sequence number */
	uint32_t	tha_ack;	/* Acknowledgement number */
	uint8_t tha_offset_and_reserved; /* Offset to the packet data */
	uint8_t		tha_flags;
	uint16_t	tha_win;	/* Allocation number */
	uint16_t	tha_sum;	/* TCP checksum */
	uint16_t	tha_urp;	/* Urgent pointer */
} tcpha_t;

typedef struct tcp_s {
	struct tcp_s *tcp_time_wait_next; /* Next TCP in TIME_WAIT list */
	struct tcp_s *tcp_time_wait_prev; /* Prev TCP in TIME_WAIT list */
	uint32_t tcp_max_swnd;		/* Maximum swnd we have seen */
	uint32_t tcp_suna;		/* Sender unacknowledged */
	uint32_t tcp_csuna;		/* Clear (no rexmits in window) suna */
	uint32_t tcp_snxt;		/* Senders next seq num */
	uint32_t tcp_swnd;		/* Senders window (relative to suna) */
	uint32_t tcp_mss;		/* Max segment size */
	uint32_t tcp_iss;		/* Initial send seq num */
	uint32_t tcp_rnxt;		/* Seq we expect to recv next */
	uint32_t tcp_rwnd;		/* Current receive window */
	uint32_t tcp_rwnd_max;		/* Max receive window */

	uint32_t tcp_irs;		/* Initial recv seq num */
	uint32_t tcp_fss;		/* Final/fin send seq num */

	uint32_t tcp_swl1;		/* These help us avoid using stale */
	uint32_t tcp_swl2;		/*  packets to update state */

	uint32_t tcp_cwnd;		/* Congestion window */
	int32_t tcp_cwnd_cnt;		/* cwnd cnt in congestion avoidance */
	uint32_t tcp_cwnd_ssthresh;	/* Congestion window */
	uint32_t tcp_cwnd_max;

	int32_t	tcp_snd_burst;		/* Send burst factor */

	int32_t	tcp_state;
	int32_t	tcp_rcv_ws;		/* My window scale power */
	int32_t	tcp_snd_ws;		/* Sender's window scale power */
	uint32_t tcp_ts_recent;	/* Timestamp of earliest unacked */
					/*  data segment */

	uint32_t	tcp_if_mtu;	/* Outgoing interface MTU. */

	uint32_t	tcp_rtt_sa;	/* Round trip smoothed average */
	uint32_t	tcp_rtt_sd;	/* Round trip smoothed deviation */
	uint32_t	tcp_rtt_update;		/* Round trip update(s) */
	uint32_t 	tcp_ms_we_have_waited;	/* Total retrans time */
	uint32_t	tcp_rto;	/* Round trip timeout */
	uint32_t	tcp_rto_timeout;	/* RTT timeout time */
	uint32_t	tcp_time_wait_expire;
				/* time in hz when t/w expires */
	uint32_t	tcp_last_rcv_lbolt;
				/* lbolt on last packet, used for PAWS */
	int	tcp_lingertime;		/* Close linger time (in seconds) */

	uint32_t	tcp_first_timer_threshold;  /* When to prod IP */
	uint32_t tcp_second_timer_threshold; /* When to give up completely */
	uint32_t tcp_first_ctimer_threshold; /* 1st threshold when connecting */
	uint32_t tcp_second_ctimer_threshold; /* 2nd ... while connecting */

	uint32_t tcp_rexmit_nxt;	/* Next rexmit seq num */
	uint32_t tcp_rexmit_max;	/* Max retran seq num */

	uint32_t tcp_naglim;		/* Tunable nagle limit */
	uint32_t	tcp_valid_bits;
#define	TCP_ISS_VALID	0x1	/* Is the tcp_iss seq num active? */
#define	TCP_FSS_VALID	0x2	/* Is the tcp_fss seq num active? */
#define	TCP_URG_VALID	0x4	/* Is the tcp_urg seq num active? */
#define	TCP_OFO_FIN_VALID 0x8	/* Has TCP received an out of order FIN? */

	int32_t	tcp_xmit_hiwater;	/* Send buffer high water mark. */
	int32_t	tcp_xmit_lowater;	/* Send buffer low water mark. */

	uchar_t	tcp_timer_backoff;	/* Backoff shift count. */
	uint32_t tcp_last_recv_time;	/* Last time we receive a segment. */

	/* Fields arranged in approximate access order along main paths */
	mblk_t	*tcp_xmit_head;		/* Head of rexmit list */
	mblk_t	*tcp_xmit_last;		/* last valid data seen by tcp_wput */
	uint32_t tcp_unsent;		/* # of bytes in hand that are unsent */
	mblk_t	*tcp_xmit_tail;		/* Last rexmit data sent */
	uint32_t tcp_xmit_tail_unsent;	/* # of unsent bytes in xmit_tail */
	mblk_t	*tcp_rcv_list;		/* Queued until push or exceed */
	mblk_t	*tcp_rcv_last_tail;	/* tcp_rcv_push_wait. */
	uint32_t tcp_rcv_cnt;		/* tcp_rcv_list is b_next chain. */

	uint32_t tcp_rack;		/* Seq # we have acked */
	uint32_t tcp_rack_cnt;		/* # of bytes we have deferred ack */

	mblk_t	*tcp_reass_head;	 /* Out of order reassembly list head */
	mblk_t	*tcp_reass_tail;	 /* Out of order reassembly list tail */

	tcp_sack_info_t	*tcp_sack_info;

#define	tcp_pipe	tcp_sack_info->tcp_pipe
#define	tcp_fack	tcp_sack_info->tcp_fack
#define	tcp_sack_snxt	tcp_sack_info->tcp_sack_snxt
#define	tcp_max_sack_blk	tcp_sack_info->tcp_max_sack_blk
#define	tcp_num_sack_blk	tcp_sack_info->tcp_num_sack_blk
#define	tcp_sack_list		tcp_sack_info->tcp_sack_list
#define	tcp_num_notsack_blk	tcp_sack_info->tcp_num_notsack_blk
#define	tcp_cnt_notsack_list	tcp_sack_info->tcp_cnt_notsack_list
#define	tcp_notsack_list		tcp_sack_info->tcp_notsack_list

	int tcp_conn_req_cnt_q0;	/* # of conn reqs in SYN_RCVD */
	int tcp_conn_req_cnt_q;	/* # of conn reqs in ESTABLISHED */
	int tcp_conn_req_max;	/* # of ESTABLISHED conn reqs allowed */

	int	tcp_iphc_len;		/* actual allocated buffer size */
	int32_t	tcp_hdr_len;		/* Byte len of combined TCP/IP hdr */
	struct ip	*tcp_ipha;	/* IPv4 header in the buffer */
	int	tcp_ip_hdr_len;		/* Byte len of our current IPvx hdr */
	tcph_t	*tcp_tcph;		/* tcp header within combined hdr */
	int32_t	tcp_tcp_hdr_len;	/* tcp header len within combined */

	uint16_t tcp_last_sent_len;	/* Record length for nagle */
	uint16_t tcp_dupack_cnt;	/* # of consequtive duplicate acks */

	/*
	 * Address family that app wishes returned addrsses to be in.
	 * Currently taken from address family used in T_BIND_REQ, but
	 * should really come from family used in original socket() call.
	 * Value can be AF_INET or AF_INET6.
	 */
	uint_t	tcp_family;

	uint32_t	tcp_ofo_fin_seq; /* Recv out of order FIN seq num */
	uint32_t	tcp_cwr_snd_max;

	uint32_t
		tcp_fin_acked : 1,	/* Has our FIN been acked? */
		tcp_fin_rcvd : 1,	/* Have we seen a FIN? */
		tcp_fin_sent : 1,	/* Have we sent our FIN yet? */
		tcp_useloopback : 1,	/* SO_USELOOPBACK "socket" option. */

		tcp_conn_def_q0: 1,	/* move from q0 to q deferred */
		tcp_zero_win_probe: 1,	/* Zero win probing is in progress */
		tcp_set_timer : 1,
		tcp_active_open: 1,	/* This is a active open */

		tcp_timer_running: 1,	/* Retransmission timer running */
		tcp_rexmit : 1,		/* TCP is retransmitting */
		tcp_snd_sack_ok : 1,	/* Can use SACK for this connection */
		tcp_ecn_ok : 1,		/* Can use ECN for this connection */

		tcp_ecn_echo_on : 1,	/* Need to do ECN echo */
		tcp_ecn_cwr_sent : 1,	/* ECN_CWR has been sent */
		tcp_cwr : 1,		/* Cwnd has reduced recently */
		tcp_snd_ts_ok  : 1,

		tcp_snd_ws_ok  : 1,
		tcp_linger : 1,
		tcp_dontdrop : 1,
		tcp_junk_fill_thru_bit_31 : 13;

	char	*tcp_iphc;		/* Buffer holding tcp/ip hdr template */

	in_addr_t	tcp_remote;	/* true remote address - needed for */
					/* source routing. */
	in_addr_t	tcp_bound_source;	/* IP address in bind_req */
	/*
	 * These fields contain the same information as tcp_tcph->th_*port.
	 * However, the lookup functions can not use the header fields
	 * since during IP option manipulation the tcp_tcph pointer
	 * changes.
	 */
	union {
		struct {
			in_port_t	tcpu_fport;	/* Remote port */
			in_port_t	tcpu_lport;	/* Local port */
		} tcpu_ports1;
		uint32_t		tcpu_ports2;	/* Rem port, */
							/* local port */
					/* Used for TCP_MATCH performance */
	} tcp_tcpu;
#define	tcp_fport	tcp_tcpu.tcpu_ports1.tcpu_fport
#define	tcp_lport	tcp_tcpu.tcpu_ports1.tcpu_lport
#define	tcp_ports	tcp_tcpu.tcpu_ports2
	/*
	 * IP format that packets transmitted from this struct should use.
	 * Value can be IPV4_VERSION or IPV6_VERSION.  Determines whether
	 * IP+TCP header template above stores an IPv4 or IPv6 header.
	 */
	ushort_t	tcp_ipversion;
	int		tcp_client_errno;
	struct tcp_s *tcp_eager_next_q; /* next eager in ESTABLISHED state */
	struct tcp_s *tcp_eager_last_q;	/* last eager in ESTABLISHED state */
	struct tcp_s *tcp_eager_next_q0; /* next eager in SYN_RCVD state */
	struct tcp_s *tcp_eager_prev_q0; /* prev eager in SYN_RCVD state */
	struct tcp_s *tcp_listener;	/* Our listener */
} tcp_t;

/* External TCP functions. */
extern void tcp_socket_init(struct inetboot_socket *);
extern int tcp_connect(int);
extern int tcp_listen(int, int);
extern int tcp_bind(int);
extern int tcp_send(int, tcp_t *, const void *, int);
extern int tcp_opt_set(tcp_t *, int, int, const void *, socklen_t);
extern int tcp_accept(int, struct sockaddr *, socklen_t *);
extern int tcp_shutdown(int);

/* Exported for recvfrom */
extern void tcp_rcv_drain_sock(int);

/* Exported for stand/lib/sock/sock_test.c */
extern void tcp_time_wait_report(void);

#ifdef	__cplusplus
}
#endif

#endif /* _TCP_INET_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 1997-2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"

/* Modified to be used by inetboot. */

#include <sys/types.h>
#include <socket_impl.h>
#include <sys/debug.h>
#include <netinet/tcp.h>
#include <sys/systm.h>
#include <sys/stropts.h>
#include <netinet/in.h>
#include <netinet/ip6.h>
#include <inet/common.h>
#include <sys/salib.h>
#include <sys/socket.h>

#include "tcp_inet.h"
#include "tcp_sack.h"

/*
 * To insert a new blk to the array of SACK blk in receiver.
 *
 * Parameters:
 *	sack_blk_t *head: pointer to the array of SACK blks.
 *	tcp_seq begin: starting seq num of the new blk.
 *	tcp_seq end: ending seq num of the new blk.
 *	int32_t *num: (referenced) total num of SACK blks on the list.
 */
void
tcp_sack_insert(sack_blk_t *head, tcp_seq begin, tcp_seq end, int32_t *num)
{
	int32_t	i, j, old_num, new_num;
	sack_blk_t tmp[MAX_SACK_BLK - 1];

	/* The array is empty, just add the new one. */
	if (*num == 0) {
		head[0].begin = begin;
		head[0].end = end;
		*num = 1;
		return;
	}

	/*
	 * Check for overlap.  There are five cases.
	 *
	 * 1. there is no overlap with any other SACK blks.
	 * 2. new SACK blk is completely contained in another blk.
	 * 3. tail part of new SACK blk overlaps with another blk.
	 * 4. head part of new SACK blk overlaps with another blk.
	 * 5. new SACK blk completely contains another blk.
	 *
	 * Use tmp to hold old SACK blks.  After the loop, copy them back
	 * to head.
	 */
	old_num = *num;
	if (old_num > MAX_SACK_BLK - 1) {
		old_num = MAX_SACK_BLK - 1;
	}
	new_num = old_num;
	j = 0;
	for (i = 0; i < old_num; i++) {
		if (SEQ_LT(end, head[i].begin) || SEQ_GT(begin, head[i].end)) {
			/* Case 1: continue to check. */
			tmp[j].begin = head[i].begin;
			tmp[j].end = head[i].end;
			j++;
			continue;
		} else if (SEQ_GEQ(begin, head[i].begin) &&
		    SEQ_LEQ(end, head[i].end)) {
			/* Case 2: re-insert the old blk to the head. */
			begin = head[i].begin;
			end = head[i].end;
		} else if (SEQ_LEQ(end, head[i].end) &&
		    SEQ_GEQ(end, head[i].begin)) {
			/*
			 * Case 3: Extend the new blk, remove the old one
			 * and continue to check.
			 */
			end = head[i].end;
		} else if (SEQ_GEQ(begin, head[i].begin) &&
		    SEQ_LEQ(begin, head[i].end)) {
			/* Case 4 */
			begin = head[i].begin;
		}
		/*
		 * Common code for all cases except the first one, which
		 * copies the original SACK blk into the tmp storage.  Other
		 * cases remove the original SACK blk by not copying into
		 * tmp storage.
		 */
		new_num--;
	}

	head[0].begin = begin;
	head[0].end = end;
	for (i = 0; i < new_num; i++) {
		head[i+1].begin = tmp[i].begin;
		head[i+1].end = tmp[i].end;
	}
	*num = new_num + 1;
}


/*
 * To remove a SACK block.
 *
 * Parameters:
 *	sack_blk_t *head: pointer to the array of SACK blks.
 *	tcp_seq end: to remove all sack blk with seq num less than end.
 *	int32_t *num: (referenced) total num of SACK blks in the array.
 */
void
tcp_sack_remove(sack_blk_t *head, tcp_seq end, int32_t *num)
{
	sack_blk_t tmp[MAX_SACK_BLK];
	int32_t i, j, old_num, new_num;

	if (*num == 0)
		return;

	old_num = *num;
	new_num = old_num;
	j = 0;
	/* Walk thru the whole list and copy the new list to tmp[]. */
	for (i = 0; i < old_num; i++) {
		if (SEQ_GT(end, head[i].begin)) {
			/*
			 * Check to see if the old SACK blk needs to be
			 * removed or updated.  If the old blk is just
			 * partially covered, update begin and continue.
			 * If the old blk is completely covered, remove it
			 * and continue to check.
			 */
			if (SEQ_GEQ(end, head[i].end)) {
				new_num--;
				continue;
			} else {
				tmp[j].begin = end;
				tmp[j].end = head[i].end;
			}
		} else {
			tmp[j].begin = head[i].begin;
			tmp[j].end = head[i].end;
		}
		j++;
	}
	/* Copy tmp[] back to the original list. */
	for (i = 0; i < new_num; i++) {
		head[i].begin = tmp[i].begin;
		head[i].end = tmp[i].end;
	}
	*num = new_num;
}


/*
 * Use the SACK info to insert a "notsack'ed" blk.  The notsack'ed blk list
 * contains the list of blks which have not been selectively acknowledged
 * by the receiver.  The SACK info is a blk which is being selectively
 * acknowledged by the receiver.
 *
 * Parameters:
 *	notsack_blk_t **head: address of the pointer to the list of notsack'ed
 *		blks.
 *	tcp_seq begin: starting seq num of the SACK info.
 *	tcp_seq end: ending seq num of the SACK info.
 *	int32_t *num: (referenced) total num of notsack'ed blk on the list.
 *	uint32_t *sum: (referenced) total num of bytes of all the notsack'ed
 *		blks.
 */
void
tcp_notsack_insert(notsack_blk_t **head, tcp_seq begin, tcp_seq end,
    int32_t *num, uint32_t *sum)
{
	notsack_blk_t *prev, *tmp, *new;
	uint32_t tmp_sum, tmp_num;

	if (*head == NULL) {
		return;
	}

	tmp = *head;
	prev = NULL;
	/* Find the right place of updating the list. */
	while ((tmp != NULL) && SEQ_LEQ(tmp->end, begin)) {
		prev = tmp;
		(tmp->sack_cnt)++;
		tmp = tmp->next;
	}

	/*
	 * This can happen only when TCP sends new data but the notsack list
	 * is not updated.
	 */
	if (tmp == NULL) {
		return;
	}

	/*
	 * This means the new SACK info covers something that is not on
	 * the list anymore.
	 */
	if (SEQ_LEQ(end, tmp->begin)) {
		return;
	}

	/* The SACK info covers up to this blk.  So just check for this blk. */
	if (SEQ_LEQ(end, tmp->end)) {
		/*
		 * Only this notsack'ed blk is completely covered.  Delete
		 * it and return.
		 */
		if (end == tmp->end && SEQ_LEQ(begin, tmp->begin)) {
			if (prev != NULL) {
				prev->next = tmp->next;
			} else {
				*head = tmp->next;
			}
			(*num)--;
			*sum -= tmp->end - tmp->begin;
			bkmem_free(tmp, sizeof (notsack_blk_t));
			return;
		}
		/* This blk is partially covered. */
		if (SEQ_GEQ(begin, tmp->begin)) {
			/* Check what needs to be updated. */
			if (begin == tmp->begin) {
				*sum -= end - tmp->begin;
				tmp->begin = end;
			} else if (end == tmp->end) {
				*sum -= tmp->end - begin;
				tmp->end = begin;
				(tmp->sack_cnt)++;
			} else {
				/* Split the notsack blk. */
				if ((new = (notsack_blk_t *)bkmem_alloc(
				    sizeof (notsack_blk_t))) == NULL) {
					return;
				}
				new->end = tmp->end;
				new->begin = end;
				new->next = tmp->next;
				new->sack_cnt = 0;
				tmp->end = begin;
				tmp->next = new;
				(tmp->sack_cnt)++;
				(*num)++;
				*sum -= end - begin;
			}
		} else {
			*sum -= end - tmp->begin;
			tmp->begin = end;
		}
		return;
	}

	/* Need to check for coverage of this blk and later blks. */
	tmp_sum = *sum;
	tmp_num = *num;
	if (SEQ_LT(tmp->begin, begin)) {
		tmp_sum -= tmp->end - begin;
		tmp->end = begin;
		(tmp->sack_cnt)++;
		prev = tmp;
		tmp = tmp->next;
	}

	while (tmp != NULL) {
		/* The coverage stops here. */
		if (SEQ_GT(tmp->begin, end)) {
			break;
		} else {
			/* Is the blk completely or partially covered? */
			if (SEQ_LEQ(tmp->end, end)) {
				tmp_num--;
				tmp_sum -= tmp->end - tmp->begin;
				if (prev != NULL) {
					prev->next = tmp->next;
					bkmem_free((caddr_t)tmp,
					    sizeof (notsack_blk_t));
					tmp = prev->next;
				} else {
					*head = tmp->next;
					bkmem_free((caddr_t)tmp,
					    sizeof (notsack_blk_t));
					tmp = *head;
				}
			} else {
				/*
				 * This blk is partially covered.  It also
				 * means it should be the end of coverage.
				 */
				tmp_sum -= end - tmp->begin;
				tmp->begin = end;
				break;
			}
		}
	}
	*num = tmp_num;
	*sum = tmp_sum;
}


/*
 * To remove notsack'ed blks.
 *
 * Parameters:
 *	notsack_blk_t **head: address of the pointer to the list of notsack'ed
 *		blks.
 *	tcp_seq end: to remove all notsack'ed blk with seq num less than end.
 *	int32_t *num: (referenced) total num of notsack'ed blks.
 *	uint32_t *sum: (referenced) total num of bytes of all the notsack'ed
 *		blks.
 */
void
tcp_notsack_remove(notsack_blk_t **head, tcp_seq end, int32_t *num,
    uint32_t *sum)
{
	notsack_blk_t *prev, *tmp;
	uint32_t tmp_sum = *sum;

	if (*head == NULL)
		return;

	prev = NULL;
	tmp = *head;
	while (tmp != NULL) {
		/* There is nothing to discard. */
		if (SEQ_GT(tmp->begin, end)) {
			break;
		}

		/* Is the blk completely or partially covered? */
		if (SEQ_GEQ(end, tmp->end)) {
			(*num)--;
			tmp_sum -= tmp->end - tmp->begin;
			if (prev == NULL) {
				*head = tmp->next;
				bkmem_free((caddr_t)tmp,
				    sizeof (notsack_blk_t));
				tmp = *head;
			} else {
				prev->next = tmp->next;
				bkmem_free((caddr_t)tmp,
				    sizeof (notsack_blk_t));
				tmp = tmp->next;
			}
		} else {
			tmp_sum -= end - tmp->begin;
			tmp->begin = end;
			break;
		}
	}
	*sum = tmp_sum;
}


/*
 * To update the notsack'ed list when new data is sent.
 *
 * Assumption: this should only be called when new notsack blk is to be added.
 *
 * Parameters:
 *	notsack_blk_t **head: address of the pointer to the list of notsack'ed
 *		blks.
 *	tcp_seq begin: beginning seq num of new data.
 *	tcp_seq end: ending seq num of new data.
 *	int32_t *num: (referenced) total num of notsack'ed blks.
 *	uint32_t *sum: (referenced) total num of bytes of all the notsack'ed
 *		blks.
 */
void tcp_notsack_update(notsack_blk_t **head, tcp_seq begin, tcp_seq end,
    int32_t *num, uint32_t *sum)
{
	notsack_blk_t *tmp;

	tmp = *head;
	/* If the list is empty, create a new one. */
	if (tmp == NULL) {
		if ((tmp = (notsack_blk_t *)bkmem_alloc(
		    sizeof (notsack_blk_t))) == NULL) {
			return;
		}
		tmp->begin = begin;
		tmp->end = end;
		tmp->next = NULL;
		tmp->sack_cnt = 0;
		*head = tmp;
		*num = 1;
		*sum = end - begin;
		return;
	}

	/*
	 * Find the place to add the new blk.  This assumes that new data
	 * is being sent, so the place to insert the new notsack blk is at
	 * the end of the list.
	 */
	while (tmp->next != NULL) {
		tmp = tmp->next;
	}

	/* Does the new blk overlap with old one? */
	if (SEQ_GEQ(tmp->end, begin)) {
		*sum += end - tmp->end;
		tmp->end = end;
	} else {
		/* No.  Need to create a new notsack blk. */
		tmp->next = (notsack_blk_t *)bkmem_alloc(
		    sizeof (notsack_blk_t));
		if (tmp->next != NULL) {
			tmp = tmp->next;
			tmp->begin = begin;
			tmp->end = end;
			tmp->next = NULL;
			tmp->sack_cnt = 0;
			(*num)++;
			*sum += end - begin;
		}
	}
}
/*
 * 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 1997, 2002-2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef	_INET_SACK_H
#define	_INET_SACK_H

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#include <netinet/tcp.h>	/* for tcp_seq */

#ifdef	__cplusplus
extern "C" {
#endif

/* Maximum num of receiver's SACK blocks */
#define	MAX_SACK_BLK	5

/* Receiver's SACK blk structure */
typedef struct sack_blk
{
	tcp_seq	begin;
	tcp_seq	end;
} sack_blk_t;

/* Sender's notsack'ed blk structure */
typedef struct notsack_blk
{
	struct notsack_blk	*next;
	tcp_seq			begin;
	tcp_seq			end;
	uint32_t		sack_cnt; /* Dup SACK count */
} notsack_blk_t;


/* SACK information in the tcp_t structure. */
typedef struct
{
	int32_t	tcp_pipe;	/* # of bytes in network */
	tcp_seq	tcp_fack;	/* highest sack'ed seq num */
	tcp_seq	tcp_sack_snxt;	/* next seq num to be rexmited using SACK. */

	int32_t	tcp_max_sack_blk; /* max # of SACK info blk in a segment */
	int32_t	tcp_num_sack_blk; /* num of blks in sack list */
	sack_blk_t	tcp_sack_list[MAX_SACK_BLK]; /* the sack list */

	/* num of blks in notsack list */
	int32_t		tcp_num_notsack_blk;
	/* # of bytes represented in blks in notsack list */
	uint32_t	tcp_cnt_notsack_list;
	/* the notsack list */
	notsack_blk_t	*tcp_notsack_list;
} tcp_sack_info_t;

extern void tcp_sack_insert(sack_blk_t *, tcp_seq, tcp_seq, int32_t *);
extern void tcp_sack_remove(sack_blk_t *, tcp_seq, int32_t *);
extern void tcp_notsack_insert(notsack_blk_t **, tcp_seq, tcp_seq,
    int32_t *, uint32_t *);
extern void tcp_notsack_remove(notsack_blk_t **, tcp_seq, int32_t *,
    uint32_t *);
extern void tcp_notsack_update(notsack_blk_t **, tcp_seq, tcp_seq,
    int32_t *, uint32_t *);


/*
 * Macro to remove all the notsack'ed blks in sender.
 *
 * Param:
 * notsack_blk_t *head: pointer to the head of the list of notsack'ed blks.
 */
#define	TCP_NOTSACK_REMOVE_ALL(head) \
{ \
	notsack_blk_t *prev, *tmp; \
	tmp = (head); \
	do { \
		prev = tmp; \
		tmp = tmp->next; \
		bkmem_free((caddr_t)prev, sizeof (notsack_blk_t)); \
	} while (tmp != NULL); \
	(head) = NULL; \
}

#ifdef	__cplusplus
}
#endif

#endif	/* _INET_SACK_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 2003 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# ident	"%Z%%M%	%I%	%E% SMI"
#

LIBRARY = libtcpstubs.a
OBJECTS = tcpstubs.o

include ../Makefile.com

CPPFLAGS += -I../tcp $(SOCKCPPFLAGS)

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 2004 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#include <sys/promif.h>
#include <socket_impl.h>
#include <netinet/in.h>
#include <tcp_inet.h>
#include <errno.h>

/* ARGSUSED */
void
tcp_socket_init(struct inetboot_socket *arg)
{
	errno = EPROTOTYPE;
}

/* ARGSUSED */
int
tcp_connect(int arg)
{
	errno = EPROTOTYPE;
	return (-1);
}

/* ARGSUSED */
int
tcp_listen(int arg0, int arg1)
{
	errno = EOPNOTSUPP;
	return (-1);
}

/* ARGSUSED */
int
tcp_bind(int arg0)
{
	errno = EBADF;
	return (-1);
}

/* ARGSUSED */
int
tcp_send(int arg0, tcp_t *arg1, const void *arg2, int arg3)
{
	errno = EBADF;
	return (-1);
}

/* ARGSUSED */
int
tcp_opt_set(tcp_t *arg0, int arg1, int arg2, const void *arg3, socklen_t arg4)
{
	errno = ENOPROTOOPT;
	return (-1);
}

/* ARGSUSED */
int
tcp_accept(int arg0, struct sockaddr *arg1, socklen_t *arg2)
{
	errno = EBADF;
	return (-1);
}

/* ARGSUSED */
int
tcp_shutdown(int arg)
{
	errno = EBADF;
	return (-1);
}

/* ARGSUSED */
void
tcp_rcv_drain_sock(int sock_id)
{
	errno = EBADF;
}
#
# 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 2004 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

LIBRARY = libxdr.a
CMNOBJS = xdr.o xdr_array.o xdr_mem.o xdr_refer.o
LOCOBJS = byteorder.o
OBJECTS = $(LOCOBJS) $(CMNOBJS)

include ../Makefile.com

CMNDIR	= $(TOPDIR)/uts/common/rpc
SRCS	= $(LOCOBJS:%.o=$(SRCDIR)/%.c) $(CMNOBJS:%.o=$(CMNDIR)/%.c)

include Makefile.$(MACH).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 2003 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# ident	"%Z%%M%	%I%	%E% SMI"
#

include ../Makefile.targ
/*
 * 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.
 */

#include <sys/types.h>
#include <netinet/in.h>

/*
 * htonll(), ntohll(), htonl(), ntohl(), htons(), ntohs()
 *
 * On little endian machines these functions reverse the byte order of the
 * input parameter and returns the result.  This is to convert the byte order
 * from host byte order (little endian) to network byte order (big endian),
 * or vice versa.
 *
 * On big endian machines these functions just return the input parameter,
 * as the host byte order is the same as the network byte order (big endian).
 */


#ifdef	_LITTLE_ENDIAN
uint64_t
htonll(uint64_t in)
{
	return ((uint64_t)htonl((in >> 32) & 0xffffffff) |
	    ((uint64_t)htonl(in & 0xffffffff) << 32));
}

uint64_t
ntohll(uint64_t in)
{
	return ((uint64_t)ntohl((in >> 32) & 0xffffffff) |
	    ((uint64_t)ntohl(in & 0xffffffff) << 32));
}

uint32_t
htonl(uint32_t in)
{
	uint32_t	i;

	i = (uint32_t)((in & (uint32_t)0xff000000) >> 24) +
	    (uint32_t)((in & (uint32_t)0x00ff0000) >> 8) +
	    (uint32_t)((in & (uint32_t)0x0000ff00) << 8) +
	    (uint32_t)((in & (uint32_t)0x000000ff) << 24);
	return (i);
}

uint32_t
ntohl(uint32_t in)
{
	return (htonl(in));
}

uint16_t
htons(uint16_t in)
{
	register int arg = (int)in;
	uint16_t i;

	i = (uint16_t)(((arg & 0xff00) >> 8) & 0xff);
	i |= (uint16_t)((arg & 0xff) << 8);
	return ((uint16_t)i);
}

uint16_t
ntohs(uint16_t in)
{
	return (htons(in));
}

#else	/* _LITTLE_ENDIAN */

#if defined(lint)
uint64_t
htonll(uint64_t in)
{
	return (in);
}

uint64_t
ntohll(uint64_t in)
{
	return (in);
}

uint32_t
htonl(uint32_t in)
{
	return (in);
}

uint32_t
ntohl(uint32_t in)
{
	return (in);
}

uint16_t
htons(uint16_t in)
{
	return (in);
}

uint16_t
ntohs(uint16_t in)
{
	return (in);
}

#endif	/* lint */
#endif	/* _LITTLE_ENDIAN */