DragonFlyBSD Kernel Audit
sys/bus/firewire/firewire.c
← back
   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
/*
 * Copyright (c) 2003 Hidetoshi Shimokawa
 * Copyright (c) 1998-2002 Katsushi Kobayashi and Hidetoshi Shimokawa
 * 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 acknowledgement as bellow:
 *
 *    This product includes software developed by K. Kobayashi and H. Shimokawa
 *
 * 4. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
 * 
 * $FreeBSD: src/sys/dev/firewire/firewire.c,v 1.68 2004/01/08 14:58:09 simokawa Exp $
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/types.h>

#include <sys/kernel.h>
#include <sys/malloc.h>
#include <sys/conf.h>
#include <sys/bus.h>		/* used by smbus and newbus */
#include <sys/sysctl.h>
#include <sys/thread2.h>

#include <bus/firewire/firewire.h>
#include <bus/firewire/firewirereg.h>
#include <bus/firewire/fwmem.h>
#include <bus/firewire/iec13213.h>
#include <bus/firewire/iec68113.h>

struct crom_src_buf {
	struct crom_src	src;
	struct crom_chunk root;
	struct crom_chunk vendor;
	struct crom_chunk hw;
};

int firewire_debug=0, try_bmr=1, hold_count=3;
SYSCTL_INT(_debug, OID_AUTO, firewire_debug, CTLFLAG_RW, &firewire_debug, 0,
	"FireWire driver debug flag");
SYSCTL_NODE(_hw, OID_AUTO, firewire, CTLFLAG_RD, 0, "FireWire Subsystem");
SYSCTL_INT(_hw_firewire, OID_AUTO, try_bmr, CTLFLAG_RW, &try_bmr, 0,
	"Try to be a bus manager");
SYSCTL_INT(_hw_firewire, OID_AUTO, hold_count, CTLFLAG_RW, &hold_count, 0,
	"Number of count of bus resets for removing lost device information");

MALLOC_DEFINE(M_FW, "firewire", "FireWire");
MALLOC_DEFINE(M_FWXFER, "fw_xfer", "XFER/FireWire");

#define FW_MAXASYRTY 4

devclass_t firewire_devclass;

static int firewire_probe	(device_t);
static int firewire_attach      (device_t);
static int firewire_detach      (device_t);
static int firewire_resume      (device_t);
#if 0
static int firewire_shutdown    (device_t);
#endif
static device_t firewire_add_child (device_t, device_t, int, const char *, int);
static void fw_try_bmr (void *);
static void fw_try_bmr_callback (struct fw_xfer *);
static void fw_asystart (struct fw_xfer *);
static int fw_get_tlabel (struct firewire_comm *, struct fw_xfer *);
static void fw_bus_probe (struct firewire_comm *);
static void fw_bus_explore (struct firewire_comm *);
static void fw_bus_explore_callback (struct fw_xfer *);
static void fw_attach_dev (struct firewire_comm *);
#ifdef FW_VMACCESS
static void fw_vmaccess (struct fw_xfer *);
#endif
struct fw_xfer *asyreqq (struct firewire_comm *, u_int8_t, u_int8_t, u_int8_t,
	u_int32_t, u_int32_t, void (*)(struct fw_xfer *));
static int fw_bmr (struct firewire_comm *);

/*
 * note: bus_generic_identify() will automatically install a "firewire"
 * device under any attached fwohci device.
 */
static device_method_t firewire_methods[] = {
	/* Device interface */
	DEVMETHOD(device_identify,	bus_generic_identify),
	DEVMETHOD(device_probe,		firewire_probe),
	DEVMETHOD(device_attach,	firewire_attach),
	DEVMETHOD(device_detach,	firewire_detach),
	DEVMETHOD(device_suspend,	bus_generic_suspend),
	DEVMETHOD(device_resume,	firewire_resume),
	DEVMETHOD(device_shutdown,	bus_generic_shutdown),

	/* Bus interface */
	DEVMETHOD(bus_add_child,	firewire_add_child),
	DEVMETHOD(bus_print_child,	bus_generic_print_child),

	DEVMETHOD_END
};
char *linkspeed[] = {
	"S100", "S200", "S400", "S800",
	"S1600", "S3200", "undef", "undef"
};

static char *tcode_str[] = {
	"WREQQ", "WREQB", "WRES",   "undef",
	"RREQQ", "RREQB", "RRESQ",  "RRESB",
	"CYCS",  "LREQ",  "STREAM", "LRES",
	"undef", "undef", "PHY",    "undef"
};

/* IEEE-1394a Table C-2 Gap count as a function of hops*/
#define MAX_GAPHOP 15
u_int gap_cnt[] = { 5,  5,  7,  8, 10, 13, 16, 18,
		   21, 24, 26, 29, 32, 35, 37, 40};

static driver_t firewire_driver = {
	"firewire",
	firewire_methods,
	sizeof(struct firewire_softc),
};

/*
 * Lookup fwdev by node id.
 */
struct fw_device *
fw_noderesolve_nodeid(struct firewire_comm *fc, int dst)
{
	struct fw_device *fwdev;

	crit_enter();
	STAILQ_FOREACH(fwdev, &fc->devices, link)
		if (fwdev->dst == dst && fwdev->status != FWDEVINVAL)
			break;
	crit_exit();

	return fwdev;
}

/*
 * Lookup fwdev by EUI64.
 */
struct fw_device *
fw_noderesolve_eui64(struct firewire_comm *fc, struct fw_eui64 *eui)
{
	struct fw_device *fwdev;

	crit_enter();
	STAILQ_FOREACH(fwdev, &fc->devices, link)
		if (FW_EUI64_EQUAL(fwdev->eui, *eui))
			break;
	crit_exit();

	if(fwdev == NULL) return NULL;
	if(fwdev->status == FWDEVINVAL) return NULL;
	return fwdev;
}

/*
 * Async. request procedure for userland application.
 */
int
fw_asyreq(struct firewire_comm *fc, int sub, struct fw_xfer *xfer)
{
	int err = 0;
	struct fw_xferq *xferq;
	int tl = 0, len;
	struct fw_pkt *fp;
	int tcode;
	struct tcode_info *info;

	if(xfer == NULL) return EINVAL;
	if(xfer->act.hand == NULL){
		kprintf("act.hand == NULL\n");
		return EINVAL;
	}
	fp = &xfer->send.hdr;

	tcode = fp->mode.common.tcode & 0xf;
	info = &fc->tcode[tcode];
	if (info->flag == 0) {
		kprintf("invalid tcode=%x\n", tcode);
		return EINVAL;
	}
	if (info->flag & FWTI_REQ)
		xferq = fc->atq;
	else
		xferq = fc->ats;
	len = info->hdr_len;
	if (xfer->send.pay_len > MAXREC(fc->maxrec)) {
		kprintf("send.pay_len > maxrec\n");
		return EINVAL;
	}
	if (info->flag & FWTI_BLOCK_STR)
		len = fp->mode.stream.len;
	else if (info->flag & FWTI_BLOCK_ASY)
		len = fp->mode.rresb.len;
	else
		len = 0;
	if (len != xfer->send.pay_len){
		kprintf("len(%d) != send.pay_len(%d) %s(%x)\n",
		    len, xfer->send.pay_len, tcode_str[tcode], tcode);
		return EINVAL; 
	}

	if(xferq->start == NULL){
		kprintf("xferq->start == NULL\n");
		return EINVAL;
	}
	if(!(xferq->queued < xferq->maxq)){
		device_printf(fc->bdev, "Discard a packet (queued=%d)\n",
			xferq->queued);
		return EINVAL;
	}

	microtime(&xfer->tv);
	if (info->flag & FWTI_TLABEL) {
		if((tl = fw_get_tlabel(fc, xfer)) == -1 )
			return EIO;
		fp->mode.hdr.tlrt = tl << 2;
	}

	xfer->tl = tl;
	xfer->resp = 0;
	xfer->fc = fc;
	xfer->q = xferq;
	xfer->retry_req = fw_asybusy;

	fw_asystart(xfer);
	return err;
}
/*
 * Wakeup blocked process.
 */
void
fw_asy_callback(struct fw_xfer *xfer){
	wakeup(xfer);
	return;
}
/*
 * Postpone to later retry.
 */
void
fw_asybusy(struct fw_xfer *xfer)
{
	kprintf("fw_asybusy\n");
/*
	xfer->ch =  timeout((timeout_t *)fw_asystart, (void *)xfer, 20000);
*/
#if 0
	DELAY(20000);
#endif
	fw_asystart(xfer);
	return;
}

/*
 * Async. request with given xfer structure.
 */
static void
fw_asystart(struct fw_xfer *xfer)
{
	struct firewire_comm *fc = xfer->fc;

	if(xfer->retry++ >= fc->max_asyretry){
		device_printf(fc->bdev, "max_asyretry exceeded\n");
		xfer->resp = EBUSY;
		xfer->state = FWXF_BUSY;
		xfer->act.hand(xfer);
		return;
	}
#if 0 /* XXX allow bus explore packets only after bus rest */
	if (fc->status < FWBUSEXPLORE) {
		xfer->resp = EAGAIN;
		xfer->state = FWXF_BUSY;
		if (xfer->act.hand != NULL)
			xfer->act.hand(xfer);
		return;
	}
#endif
	crit_enter();
	xfer->state = FWXF_INQ;
	STAILQ_INSERT_TAIL(&xfer->q->q, xfer, link);
	xfer->q->queued ++;
	crit_exit();
	/* XXX just queue for mbuf */
	if (xfer->mbuf == NULL)
		xfer->q->start(fc);
	return;
}

static int
firewire_probe(device_t dev)
{
	device_set_desc(dev, "IEEE1394(FireWire) bus");
	return (0);
}

static void
firewire_xfer_timeout(struct firewire_comm *fc)
{
	struct fw_xfer *xfer;
	struct tlabel *tl;
	struct timeval tv;
	struct timeval split_timeout;
	int i;

	split_timeout.tv_sec = 0;
	split_timeout.tv_usec = 200 * 1000;	 /* 200 msec */

	microtime(&tv);
	timevalsub(&tv, &split_timeout);

	crit_enter();
	for (i = 0; i < 0x40; i ++) {
		while ((tl = STAILQ_FIRST(&fc->tlabels[i])) != NULL) {
			xfer = tl->xfer;
			if (timevalcmp(&xfer->tv, &tv, >))
				/* the rests are newer than this */
				break;
			if (xfer->state == FWXF_START)
				/* not sent yet */
				break;
			device_printf(fc->bdev,
				"split transaction timeout dst=0x%x tl=0x%x state=%d\n",
				xfer->send.hdr.mode.hdr.dst, i, xfer->state);
			xfer->resp = ETIMEDOUT;
			STAILQ_REMOVE_HEAD(&fc->tlabels[i], link);
			fw_xfer_done(xfer);
		}
	}
	crit_exit();
}

#define WATCHDOC_HZ 10
static void
firewire_watchdog(void *arg)
{
	struct firewire_comm *fc;
	static int watchdoc_clock = 0;

	fc = (struct firewire_comm *)arg;

	/*
	 * At boot stage, the device interrupt is disabled and
	 * We encounter a timeout easily. To avoid this,
	 * ignore clock interrupt for a while.
	 */
	if (watchdoc_clock > WATCHDOC_HZ * 15) {
		firewire_xfer_timeout(fc);
		fc->timeout(fc);
	} else
		watchdoc_clock ++;

	callout_reset(&fc->timeout_callout, hz / WATCHDOC_HZ,
			(void *)firewire_watchdog, (void *)fc);
}

/*
 * The attach routine.
 */
static int
firewire_attach(device_t dev)
{
	struct firewire_softc *sc = device_get_softc(dev);
	device_t pa = device_get_parent(dev);
	struct firewire_comm *fc;

	fc = (struct firewire_comm *)device_get_softc(pa);
	sc->fc = fc;
	fc->status = FWBUSNOTREADY;

	if( fc->nisodma > FWMAXNDMA) fc->nisodma = FWMAXNDMA;

	fwdev_makedev(sc);

	CALLOUT_INIT(&sc->fc->timeout_callout);
	CALLOUT_INIT(&sc->fc->bmr_callout);
	CALLOUT_INIT(&sc->fc->retry_probe_callout);
	CALLOUT_INIT(&sc->fc->busprobe_callout);

	callout_reset(&sc->fc->timeout_callout, hz,
			(void *)firewire_watchdog, (void *)sc->fc);

	/* Locate our children */
	bus_generic_probe(dev);

	/* launch attachement of the added children */
	bus_generic_attach(dev);

	/* bus_reset */
	fw_busreset(fc);
	fc->ibr(fc);

	return 0;
}

/*
 * Attach it as child.
 */
static device_t
firewire_add_child(device_t bus, device_t parent, int order, const char *name, int unit)
{
        device_t child;
	struct firewire_softc *sc;

	sc = (struct firewire_softc *)device_get_softc(parent);
	child = device_add_child(parent, name, unit);
	if (child) {
		device_set_ivars(child, sc->fc);
		device_probe_and_attach(child);
	}

	return child;
}

static int
firewire_resume(device_t dev)
{
	struct firewire_softc *sc;

	sc = (struct firewire_softc *)device_get_softc(dev);
	sc->fc->status = FWBUSNOTREADY;
	
	bus_generic_resume(dev);

	return(0);
}

/*
 * Dettach it.
 */
static int
firewire_detach(device_t dev)
{
	struct firewire_softc *sc;
	struct csrdir *csrd, *next;
	struct fw_device *fwdev, *fwdev_next;
	int err;

	sc = (struct firewire_softc *)device_get_softc(dev);
	if ((err = fwdev_destroydev(sc)) != 0)
		return err;

	if ((err = bus_generic_detach(dev)) != 0)
		return err;

	callout_stop(&sc->fc->timeout_callout);
	callout_stop(&sc->fc->bmr_callout);
	callout_stop(&sc->fc->retry_probe_callout);
	callout_stop(&sc->fc->busprobe_callout);

	/* XXX xfree_free and callout_stop on all xfers */
	for (fwdev = STAILQ_FIRST(&sc->fc->devices); fwdev != NULL;
							fwdev = fwdev_next) {
		fwdev_next = STAILQ_NEXT(fwdev, link);
		kfree(fwdev, M_FW);
	}
	for (csrd = SLIST_FIRST(&sc->fc->csrfree); csrd != NULL; csrd = next) {
		next = SLIST_NEXT(csrd, link);
		kfree(csrd, M_FW);
	}
	kfree(sc->fc->topology_map, M_FW);
	kfree(sc->fc->speed_map, M_FW);
	kfree(sc->fc->crom_src_buf, M_FW);
	return(0);
}
#if 0
static int
firewire_shutdown( device_t dev )
{
	return 0;
}
#endif


static void
fw_xferq_drain(struct fw_xferq *xferq)
{
	struct fw_xfer *xfer;

	while ((xfer = STAILQ_FIRST(&xferq->q)) != NULL) {
		STAILQ_REMOVE_HEAD(&xferq->q, link);
		xferq->queued --;
		xfer->resp = EAGAIN;
		xfer->state = FWXF_SENTERR;
		fw_xfer_done(xfer);
	}
}

void
fw_drain_txq(struct firewire_comm *fc)
{
	int i;

	fw_xferq_drain(fc->atq);
	fw_xferq_drain(fc->ats);
	for(i = 0; i < fc->nisodma; i++)
		fw_xferq_drain(fc->it[i]);
}

static void
fw_reset_csr(struct firewire_comm *fc)
{
	int i;

	CSRARC(fc, STATE_CLEAR)
			= 1 << 23 | 0 << 17 | 1 << 16 | 1 << 15 | 1 << 14 ;
	CSRARC(fc, STATE_SET) = CSRARC(fc, STATE_CLEAR);
	CSRARC(fc, NODE_IDS) = 0x3f;

	CSRARC(fc, TOPO_MAP + 8) = 0;
	fc->irm = -1;

	fc->max_node = -1;

	for(i = 2; i < 0x100/4 - 2 ; i++){
		CSRARC(fc, SPED_MAP + i * 4) = 0;
	}
	CSRARC(fc, STATE_CLEAR) = 1 << 23 | 0 << 17 | 1 << 16 | 1 << 15 | 1 << 14 ;
	CSRARC(fc, STATE_SET) = CSRARC(fc, STATE_CLEAR);
	CSRARC(fc, RESET_START) = 0;
	CSRARC(fc, SPLIT_TIMEOUT_HI) = 0;
	CSRARC(fc, SPLIT_TIMEOUT_LO) = 800 << 19;
	CSRARC(fc, CYCLE_TIME) = 0x0;
	CSRARC(fc, BUS_TIME) = 0x0;
	CSRARC(fc, BUS_MGR_ID) = 0x3f;
	CSRARC(fc, BANDWIDTH_AV) = 4915;
	CSRARC(fc, CHANNELS_AV_HI) = 0xffffffff;
	CSRARC(fc, CHANNELS_AV_LO) = 0xffffffff;
	CSRARC(fc, IP_CHANNELS) = (1 << 31);

	CSRARC(fc, CONF_ROM) = 0x04 << 24;
	CSRARC(fc, CONF_ROM + 4) = 0x31333934; /* means strings 1394 */
	CSRARC(fc, CONF_ROM + 8) = 1 << 31 | 1 << 30 | 1 << 29 |
				1 << 28 | 0xff << 16 | 0x09 << 8;
	CSRARC(fc, CONF_ROM + 0xc) = 0;

/* DV depend CSRs see blue book */
	CSRARC(fc, oPCR) &= ~DV_BROADCAST_ON; 
	CSRARC(fc, iPCR) &= ~DV_BROADCAST_ON; 

	CSRARC(fc, STATE_CLEAR) &= ~(1 << 23 | 1 << 15 | 1 << 14 );
	CSRARC(fc, STATE_SET) = CSRARC(fc, STATE_CLEAR);
}

static void
fw_init_crom(struct firewire_comm *fc)
{
	struct crom_src *src;

	fc->crom_src_buf = (struct crom_src_buf *)
		kmalloc(sizeof(struct crom_src_buf), M_FW, M_WAITOK | M_ZERO);

	src = &fc->crom_src_buf->src;
	bzero(src, sizeof(struct crom_src));

	/* BUS info sample */
	src->hdr.info_len = 4;

	src->businfo.bus_name = CSR_BUS_NAME_IEEE1394;

	src->businfo.irmc = 1;
	src->businfo.cmc = 1;
	src->businfo.isc = 1;
	src->businfo.bmc = 1;
	src->businfo.pmc = 0;
	src->businfo.cyc_clk_acc = 100;
	src->businfo.max_rec = fc->maxrec;
	src->businfo.max_rom = MAXROM_4;
	src->businfo.generation = 1;
	src->businfo.link_spd = fc->speed;

	src->businfo.eui64.hi = fc->eui.hi;
	src->businfo.eui64.lo = fc->eui.lo;

	STAILQ_INIT(&src->chunk_list);

	fc->crom_src = src;
	fc->crom_root = &fc->crom_src_buf->root;
}

static void
fw_reset_crom(struct firewire_comm *fc)
{
	struct crom_src_buf *buf;
	struct crom_src *src;
	struct crom_chunk *root;

	if (fc->crom_src_buf == NULL)
		fw_init_crom(fc);

	buf =  fc->crom_src_buf;
	src = fc->crom_src;
	root = fc->crom_root;

	STAILQ_INIT(&src->chunk_list);

	bzero(root, sizeof(struct crom_chunk));
	crom_add_chunk(src, NULL, root, 0);
	crom_add_entry(root, CSRKEY_NCAP, 0x0083c0); /* XXX */
	/* private company_id */
	crom_add_entry(root, CSRKEY_VENDOR, CSRVAL_VENDOR_PRIVATE);
	crom_add_simple_text(src, root, &buf->vendor, "DragonFly Project");
	crom_add_entry(root, CSRKEY_HW, __DragonFly_version);
	crom_add_simple_text(src, root, &buf->hw, hostname);
}

/*
 * Called after bus reset.
 */
void
fw_busreset(struct firewire_comm *fc)
{
	struct firewire_dev_comm *fdc;
	struct crom_src *src;
	device_t *devlistp;
	void *newrom;
	int i, devcnt;

	switch(fc->status){
	case FWBUSMGRELECT:
		callout_stop(&fc->bmr_callout);
		break;
	default:
		break;
	}
	fc->status = FWBUSRESET;
	fw_reset_csr(fc);
	fw_reset_crom(fc);

	if (device_get_children(fc->bdev, &devlistp, &devcnt) == 0) {
		for( i = 0 ; i < devcnt ; i++)
			if (device_get_state(devlistp[i]) >= DS_ATTACHED)  {
				fdc = device_get_softc(devlistp[i]);
				if (fdc->post_busreset != NULL)
					fdc->post_busreset(fdc);
			}
		kfree(devlistp, M_TEMP);
	}

	newrom = kmalloc(CROMSIZE, M_FW, M_WAITOK | M_ZERO);
	src = &fc->crom_src_buf->src;
	crom_load(src, (u_int32_t *)newrom, CROMSIZE);
	if (bcmp(newrom, fc->config_rom, CROMSIZE) != 0) {
		/* bump generation and reload */
		src->businfo.generation ++;
		/* generation must be between 0x2 and 0xF */
		if (src->businfo.generation < 2)
			src->businfo.generation ++;
		crom_load(src, (u_int32_t *)newrom, CROMSIZE);
		bcopy(newrom, (void *)fc->config_rom, CROMSIZE);
	}
	kfree(newrom, M_FW);
}

/* Call once after reboot */
void
fw_init(struct firewire_comm *fc)
{
	int i;
	struct csrdir *csrd;
#ifdef FW_VMACCESS
	struct fw_xfer *xfer;
	struct fw_bind *fwb;
#endif

	fc->max_asyretry = FW_MAXASYRTY;

	fc->arq->queued = 0;
	fc->ars->queued = 0;
	fc->atq->queued = 0;
	fc->ats->queued = 0;

	fc->arq->buf = NULL;
	fc->ars->buf = NULL;
	fc->atq->buf = NULL;
	fc->ats->buf = NULL;

	fc->arq->flag = 0;
	fc->ars->flag = 0;
	fc->atq->flag = 0;
	fc->ats->flag = 0;

	STAILQ_INIT(&fc->atq->q);
	STAILQ_INIT(&fc->ats->q);

	for( i = 0 ; i < fc->nisodma ; i ++ ){
		fc->it[i]->queued = 0;
		fc->ir[i]->queued = 0;

		fc->it[i]->start = NULL;
		fc->ir[i]->start = NULL;

		fc->it[i]->buf = NULL;
		fc->ir[i]->buf = NULL;

		fc->it[i]->flag = FWXFERQ_STREAM;
		fc->ir[i]->flag = FWXFERQ_STREAM;

		STAILQ_INIT(&fc->it[i]->q);
		STAILQ_INIT(&fc->ir[i]->q);

		STAILQ_INIT(&fc->it[i]->binds);
		STAILQ_INIT(&fc->ir[i]->binds);
	}

	fc->arq->maxq = FWMAXQUEUE;
	fc->ars->maxq = FWMAXQUEUE;
	fc->atq->maxq = FWMAXQUEUE;
	fc->ats->maxq = FWMAXQUEUE;

	for( i = 0 ; i < fc->nisodma ; i++){
		fc->ir[i]->maxq = FWMAXQUEUE;
		fc->it[i]->maxq = FWMAXQUEUE;
	}
/* Initialize csr registers */
	fc->topology_map = kmalloc(sizeof(struct fw_topology_map),
				    M_FW, M_WAITOK | M_ZERO);
	fc->speed_map = kmalloc(sizeof(struct fw_speed_map),
				    M_FW, M_WAITOK | M_ZERO);
	CSRARC(fc, TOPO_MAP) = 0x3f1 << 16;
	CSRARC(fc, TOPO_MAP + 4) = 1;
	CSRARC(fc, SPED_MAP) = 0x3f1 << 16;
	CSRARC(fc, SPED_MAP + 4) = 1;

	STAILQ_INIT(&fc->devices);

/* Initialize csr ROM work space */
	SLIST_INIT(&fc->ongocsr);
	SLIST_INIT(&fc->csrfree);
	for( i = 0 ; i < FWMAXCSRDIR ; i++){
		csrd = kmalloc(sizeof(struct csrdir), M_FW, M_WAITOK);
		SLIST_INSERT_HEAD(&fc->csrfree, csrd, link);
	}

/* Initialize Async handlers */
	STAILQ_INIT(&fc->binds);
	for( i = 0 ; i < 0x40 ; i++){
		STAILQ_INIT(&fc->tlabels[i]);
	}

/* DV depend CSRs see blue book */
#if 0
	CSRARC(fc, oMPR) = 0x3fff0001; /* # output channel = 1 */
	CSRARC(fc, oPCR) = 0x8000007a;
	for(i = 4 ; i < 0x7c/4 ; i+=4){
		CSRARC(fc, i + oPCR) = 0x8000007a; 
	}
 
	CSRARC(fc, iMPR) = 0x00ff0001; /* # input channel = 1 */
	CSRARC(fc, iPCR) = 0x803f0000;
	for(i = 4 ; i < 0x7c/4 ; i+=4){
		CSRARC(fc, i + iPCR) = 0x0; 
	}
#endif

	fc->crom_src_buf = NULL;

#ifdef FW_VMACCESS
	xfer = fw_xfer_alloc();
	if(xfer == NULL) return;

	fwb = kmalloc(sizeof (struct fw_bind), M_FW, M_WAITOK);
	xfer->act.hand = fw_vmaccess;
	xfer->fc = fc;
	xfer->sc = NULL;

	fwb->start_hi = 0x2;
	fwb->start_lo = 0;
	fwb->addrlen = 0xffffffff;
	fwb->xfer = xfer;
	fw_bindadd(fc, fwb);
#endif
}

#define BIND_CMP(addr, fwb) (((addr) < (fwb)->start)?-1:\
    ((fwb)->end < (addr))?1:0)

/*
 * To lookup binded process from IEEE1394 address.
 */
struct fw_bind *
fw_bindlookup(struct firewire_comm *fc, u_int16_t dest_hi, u_int32_t dest_lo)
{
	u_int64_t addr;
	struct fw_bind *tfw;

	addr = ((u_int64_t)dest_hi << 32) | dest_lo;
	STAILQ_FOREACH(tfw, &fc->binds, fclist)
		if (tfw->act_type != FWACT_NULL && BIND_CMP(addr, tfw) == 0)
			return(tfw);
	return(NULL);
}

/*
 * To bind IEEE1394 address block to process.
 */
int
fw_bindadd(struct firewire_comm *fc, struct fw_bind *fwb)
{
	struct fw_bind *tfw, *prev = NULL;

	if (fwb->start > fwb->end) {
		kprintf("%s: invalid range\n", __func__);
		return EINVAL;
	}

	STAILQ_FOREACH(tfw, &fc->binds, fclist) {
		if (fwb->end < tfw->start)
			break;
		prev = tfw;
	}
	if (prev == NULL) {
		STAILQ_INSERT_HEAD(&fc->binds, fwb, fclist);
		goto out;
	}
	if (prev->end < fwb->start) {
		STAILQ_INSERT_AFTER(&fc->binds, prev, fwb, fclist);
		goto out;
	}

	kprintf("%s: bind failed\n", __func__);
	return (EBUSY);

out:
	if (fwb->act_type == FWACT_CH)
		STAILQ_INSERT_HEAD(&fc->ir[fwb->sub]->binds, fwb, chlist);
	return (0);
}

/*
 * To free IEEE1394 address block.
 */
int
fw_bindremove(struct firewire_comm *fc, struct fw_bind *fwb)
{
#if 0
	struct fw_xfer *xfer, *next;
#endif
	struct fw_bind *tfw;

	crit_enter();
	STAILQ_FOREACH(tfw, &fc->binds, fclist)
		if (tfw == fwb) {
			STAILQ_REMOVE(&fc->binds, fwb, fw_bind, fclist);
			goto found;
		}

	kprintf("%s: no such bind\n", __func__);
	crit_exit();
	return (1);
found:
#if 0
	/* shall we do this? */
	for (xfer = STAILQ_FIRST(&fwb->xferlist); xfer != NULL; xfer = next) {
		next = STAILQ_NEXT(xfer, link);
		fw_xfer_free(xfer);
	}
	STAILQ_INIT(&fwb->xferlist);
#endif

	crit_exit();
	return 0;
}

/*
 * To free transaction label.
 */
static void
fw_tl_free(struct firewire_comm *fc, struct fw_xfer *xfer)
{
	struct tlabel *tl;

	crit_enter();
	for( tl = STAILQ_FIRST(&fc->tlabels[xfer->tl]); tl != NULL;
		tl = STAILQ_NEXT(tl, link)){
		if(tl->xfer == xfer){
			STAILQ_REMOVE(&fc->tlabels[xfer->tl], tl, tlabel, link);
			kfree(tl, M_FW);
			break;
		}
	}
	crit_exit();
}

/*
 * To obtain XFER structure by transaction label.
 */
static struct fw_xfer *
fw_tl2xfer(struct firewire_comm *fc, int node, int tlabel)
{
	struct fw_xfer *xfer;
	struct tlabel *tl;

	crit_enter();

	for( tl = STAILQ_FIRST(&fc->tlabels[tlabel]); tl != NULL;
		tl = STAILQ_NEXT(tl, link)){
		if(tl->xfer->send.hdr.mode.hdr.dst == node){
			xfer = tl->xfer;
			crit_exit();
			if (firewire_debug > 2)
				kprintf("fw_tl2xfer: found tl=%d\n", tlabel);
			return(xfer);
		}
	}
	if (firewire_debug > 1)
		kprintf("fw_tl2xfer: not found tl=%d\n", tlabel);
	crit_exit();
	return(NULL);
}

/*
 * To allocate IEEE1394 XFER structure.
 */
struct fw_xfer *
fw_xfer_alloc(struct malloc_type *type)
{
	struct fw_xfer *xfer;

	xfer = kmalloc(sizeof(struct fw_xfer), type, M_INTWAIT | M_ZERO);
	xfer->malloc = type;

	return xfer;
}

struct fw_xfer *
fw_xfer_alloc_buf(struct malloc_type *type, int send_len, int recv_len)
{
	struct fw_xfer *xfer;

	xfer = fw_xfer_alloc(type);
	if (xfer == NULL)
		return(NULL);
	xfer->send.pay_len = send_len;
	xfer->recv.pay_len = recv_len;
	if (send_len > 0) {
		xfer->send.payload = kmalloc(send_len, type, M_INTWAIT | M_ZERO);
		if (xfer->send.payload == NULL) {
			fw_xfer_free(xfer);
			return(NULL);
		}
	}
	if (recv_len > 0) {
		xfer->recv.payload = kmalloc(recv_len, type, M_INTWAIT);
		if (xfer->recv.payload == NULL) {
			if (xfer->send.payload != NULL)
				kfree(xfer->send.payload, type);
			fw_xfer_free(xfer);
			return(NULL);
		}
	}
	return(xfer);
}

/*
 * IEEE1394 XFER post process.
 */
void
fw_xfer_done(struct fw_xfer *xfer)
{
	if (xfer->act.hand == NULL) {
		kprintf("act.hand == NULL\n");
		return;
	}

	if (xfer->fc == NULL)
		panic("fw_xfer_done: why xfer->fc is NULL?");

	xfer->act.hand(xfer);
}

void
fw_xfer_unload(struct fw_xfer* xfer)
{
	if(xfer == NULL ) return;
	if(xfer->state == FWXF_INQ){
		kprintf("fw_xfer_free FWXF_INQ\n");
		crit_enter();
		STAILQ_REMOVE(&xfer->q->q, xfer, fw_xfer, link);
		xfer->q->queued --;
		crit_exit();
	}
	if (xfer->fc != NULL) {
#if 1
		if(xfer->state == FWXF_START)
			/*
			 * This could happen if:
			 *  1. We call fwohci_arcv() before fwohci_txd().
			 *  2. firewire_watch() is called.
			 */
			kprintf("fw_xfer_free FWXF_START\n");
#endif
		fw_tl_free(xfer->fc, xfer);
	}
	xfer->state = FWXF_INIT;
	xfer->resp = 0;
	xfer->retry = 0;
}
/*
 * To free IEEE1394 XFER structure. 
 */
void
fw_xfer_free_buf( struct fw_xfer* xfer)
{
	if (xfer == NULL) {
		kprintf("%s: xfer == NULL\n", __func__);
		return;
	}
	fw_xfer_unload(xfer);
	if(xfer->send.payload != NULL){
		kfree(xfer->send.payload, xfer->malloc);
	}
	if(xfer->recv.payload != NULL){
		kfree(xfer->recv.payload, xfer->malloc);
	}
	kfree(xfer, xfer->malloc);
}

void
fw_xfer_free( struct fw_xfer* xfer)
{
	if (xfer == NULL) {
		kprintf("%s: xfer == NULL\n", __func__);
		return;
	}
	fw_xfer_unload(xfer);
	kfree(xfer, xfer->malloc);
}

void
fw_asy_callback_free(struct fw_xfer *xfer)
{
#if 0
	kprintf("asyreq done state=%d resp=%d\n",
				xfer->state, xfer->resp);
#endif
	fw_xfer_free(xfer);
}

/*
 * To configure PHY. 
 */
static void
fw_phy_config(struct firewire_comm *fc, int root_node, int gap_count)
{
	struct fw_xfer *xfer;
	struct fw_pkt *fp;

	fc->status = FWBUSPHYCONF;

	xfer = fw_xfer_alloc(M_FWXFER);
	if (xfer == NULL)
		return;
	xfer->fc = fc;
	xfer->retry_req = fw_asybusy;
	xfer->act.hand = fw_asy_callback_free;

	fp = &xfer->send.hdr;
	fp->mode.ld[1] = 0;
	if (root_node >= 0)
		fp->mode.ld[1] |= (root_node & 0x3f) << 24 | 1 << 23;
	if (gap_count >= 0)
		fp->mode.ld[1] |= 1 << 22 | (gap_count & 0x3f) << 16;
	fp->mode.ld[2] = ~fp->mode.ld[1];
/* XXX Dangerous, how to pass PHY packet to device driver */
	fp->mode.common.tcode |= FWTCODE_PHY;

	if (firewire_debug)
		kprintf("send phy_config root_node=%d gap_count=%d\n",
						root_node, gap_count);
	fw_asyreq(fc, -1, xfer);
}

#if 0
/*
 * Dump self ID. 
 */
static void
fw_print_sid(u_int32_t sid)
{
	union fw_self_id *s;
	s = (union fw_self_id *) &sid;
	kprintf("node:%d link:%d gap:%d spd:%d del:%d con:%d pwr:%d"
		" p0:%d p1:%d p2:%d i:%d m:%d\n",
		s->p0.phy_id, s->p0.link_active, s->p0.gap_count,
		s->p0.phy_speed, s->p0.phy_delay, s->p0.contender,
		s->p0.power_class, s->p0.port0, s->p0.port1,
		s->p0.port2, s->p0.initiated_reset, s->p0.more_packets);
}
#endif

/*
 * To receive self ID. 
 */
void
fw_sidrcv(struct firewire_comm* fc, u_int32_t *sid, u_int len)
{
	u_int32_t *p;
	union fw_self_id *self_id;
	u_int i, j, node, c_port = 0, i_branch = 0;

	fc->sid_cnt = len /(sizeof(u_int32_t) * 2);
	fc->status = FWBUSINIT;
	fc->max_node = fc->nodeid & 0x3f;
	CSRARC(fc, NODE_IDS) = ((u_int32_t)fc->nodeid) << 16;
	fc->status = FWBUSCYMELECT;
	fc->topology_map->crc_len = 2;
	fc->topology_map->generation ++;
	fc->topology_map->self_id_count = 0;
	fc->topology_map->node_count = 0;
	fc->speed_map->generation ++;
	fc->speed_map->crc_len = 1 + (64*64 + 3) / 4;
	self_id = &fc->topology_map->self_id[0];
	for(i = 0; i < fc->sid_cnt; i ++){
		if (sid[1] != ~sid[0]) {
			kprintf("fw_sidrcv: invalid self-id packet\n");
			sid += 2;
			continue;
		}
		*self_id = *((union fw_self_id *)sid);
		fc->topology_map->crc_len++;
		if(self_id->p0.sequel == 0){
			fc->topology_map->node_count ++;
			c_port = 0;
#if 0
			fw_print_sid(sid[0]);
#endif
			node = self_id->p0.phy_id;
			if(fc->max_node < node){
				fc->max_node = self_id->p0.phy_id;
			}
			/* XXX I'm not sure this is the right speed_map */
			fc->speed_map->speed[node][node]
					= self_id->p0.phy_speed;
			for (j = 0; j < node; j ++) {
				fc->speed_map->speed[j][node]
					= fc->speed_map->speed[node][j]
					= min(fc->speed_map->speed[j][j],
							self_id->p0.phy_speed);
			}
			if ((fc->irm == -1 || self_id->p0.phy_id > fc->irm) &&
			  (self_id->p0.link_active && self_id->p0.contender)) {
				fc->irm = self_id->p0.phy_id;
			}
			if(self_id->p0.port0 >= 0x2){
				c_port++;
			}
			if(self_id->p0.port1 >= 0x2){
				c_port++;
			}
			if(self_id->p0.port2 >= 0x2){
				c_port++;
			}
		}
		if(c_port > 2){
			i_branch += (c_port - 2);
		}
		sid += 2;
		self_id++;
		fc->topology_map->self_id_count ++;
	}
	device_printf(fc->bdev, "%d nodes", fc->max_node + 1);
	/* CRC */
	fc->topology_map->crc = fw_crc16(
			(u_int32_t *)&fc->topology_map->generation,
			fc->topology_map->crc_len * 4);
	fc->speed_map->crc = fw_crc16(
			(u_int32_t *)&fc->speed_map->generation,
			fc->speed_map->crc_len * 4);
	/* byteswap and copy to CSR */
	p = (u_int32_t *)fc->topology_map;
	for (i = 0; i <= fc->topology_map->crc_len; i++)
		CSRARC(fc, TOPO_MAP + i * 4) = htonl(*p++);
	p = (u_int32_t *)fc->speed_map;
	CSRARC(fc, SPED_MAP) = htonl(*p++);
	CSRARC(fc, SPED_MAP + 4) = htonl(*p++);
	/* don't byte-swap u_int8_t array */
	bcopy(p, &CSRARC(fc, SPED_MAP + 8), (fc->speed_map->crc_len - 1)*4);

	fc->max_hop = fc->max_node - i_branch;
	kprintf(", maxhop <= %d", fc->max_hop);
		
	if(fc->irm == -1 ){
		kprintf(", Not found IRM capable node");
	}else{
		kprintf(", cable IRM = %d", fc->irm);
		if (fc->irm == fc->nodeid)
			kprintf(" (me)");
	}
	kprintf("\n");

	if (try_bmr && (fc->irm != -1) && (CSRARC(fc, BUS_MGR_ID) == 0x3f)) {
		if (fc->irm == fc->nodeid) {
			fc->status = FWBUSMGRDONE;
			CSRARC(fc, BUS_MGR_ID) = fc->set_bmr(fc, fc->irm);
			fw_bmr(fc);
		} else {
			fc->status = FWBUSMGRELECT;
			callout_reset(&fc->bmr_callout, hz/8,
				(void *)fw_try_bmr, (void *)fc);
		}
	} else
		fc->status = FWBUSMGRDONE;

	callout_reset(&fc->busprobe_callout, hz/4,
			(void *)fw_bus_probe, (void *)fc);
}

/*
 * To probe devices on the IEEE1394 bus. 
 */
static void
fw_bus_probe(struct firewire_comm *fc)
{
	struct fw_device *fwdev;

	crit_enter();
	fc->status = FWBUSEXPLORE;
	fc->retry_count = 0;

	/* Invalidate all devices, just after bus reset. */
	STAILQ_FOREACH(fwdev, &fc->devices, link)
		if (fwdev->status != FWDEVINVAL) {
			fwdev->status = FWDEVINVAL;
			fwdev->rcnt = 0;
		}

	fc->ongonode = 0;
	fc->ongoaddr = CSRROMOFF;
	fc->ongodev = NULL;
	fc->ongoeui.hi = 0xffffffff; fc->ongoeui.lo = 0xffffffff;
	fw_bus_explore(fc);
	crit_exit();
}

/*
 * To collect device informations on the IEEE1394 bus. 
 */
static void
fw_bus_explore(struct firewire_comm *fc )
{
	int err = 0;
	struct fw_device *fwdev, *pfwdev, *tfwdev;
	u_int32_t addr;
	struct fw_xfer *xfer;
	struct fw_pkt *fp;

	if(fc->status != FWBUSEXPLORE)
		return;

loop:
	if(fc->ongonode == fc->nodeid) fc->ongonode++;

	if(fc->ongonode > fc->max_node) goto done;
	if(fc->ongonode >= 0x3f) goto done;

	/* check link */
	/* XXX we need to check phy_id first */
	if (!fc->topology_map->self_id[fc->ongonode].p0.link_active) {
		if (firewire_debug)
			kprintf("node%d: link down\n", fc->ongonode);
		fc->ongonode++;
		goto loop;
	}

	if(fc->ongoaddr <= CSRROMOFF &&
		fc->ongoeui.hi == 0xffffffff &&
		fc->ongoeui.lo == 0xffffffff ){
		fc->ongoaddr = CSRROMOFF;
		addr = 0xf0000000 | fc->ongoaddr;
	}else if(fc->ongoeui.hi == 0xffffffff ){
		fc->ongoaddr = CSRROMOFF + 0xc;
		addr = 0xf0000000 | fc->ongoaddr;
	}else if(fc->ongoeui.lo == 0xffffffff ){
		fc->ongoaddr = CSRROMOFF + 0x10;
		addr = 0xf0000000 | fc->ongoaddr;
	}else if(fc->ongodev == NULL){
		STAILQ_FOREACH(fwdev, &fc->devices, link)
			if (FW_EUI64_EQUAL(fwdev->eui, fc->ongoeui))
				break;
		if(fwdev != NULL){
			fwdev->dst = fc->ongonode;
			fwdev->status = FWDEVINIT;
			fc->ongodev = fwdev;
			fc->ongoaddr = CSRROMOFF;
			addr = 0xf0000000 | fc->ongoaddr;
			goto dorequest;
		}
		fwdev = kmalloc(sizeof(struct fw_device), M_FW,
				M_WAITOK | M_ZERO);
		fwdev->fc = fc;
		fwdev->rommax = 0;
		fwdev->dst = fc->ongonode;
		fwdev->eui.hi = fc->ongoeui.hi; fwdev->eui.lo = fc->ongoeui.lo;
		fwdev->status = FWDEVINIT;
		fwdev->speed = fc->speed_map->speed[fc->nodeid][fc->ongonode];

		pfwdev = NULL;
		STAILQ_FOREACH(tfwdev, &fc->devices, link) {
			if (tfwdev->eui.hi > fwdev->eui.hi ||
					(tfwdev->eui.hi == fwdev->eui.hi &&
					tfwdev->eui.lo > fwdev->eui.lo))
				break;
			pfwdev = tfwdev;
		}
		if (pfwdev == NULL)
			STAILQ_INSERT_HEAD(&fc->devices, fwdev, link);
		else
			STAILQ_INSERT_AFTER(&fc->devices, pfwdev, fwdev, link);

		device_printf(fc->bdev, "New %s device ID:%08x%08x\n",
			linkspeed[fwdev->speed],
			fc->ongoeui.hi, fc->ongoeui.lo);

		fc->ongodev = fwdev;
		fc->ongoaddr = CSRROMOFF;
		addr = 0xf0000000 | fc->ongoaddr;
	}else{
		addr = 0xf0000000 | fc->ongoaddr;
	}
dorequest:
#if 0
	xfer = asyreqq(fc, FWSPD_S100, 0, 0,
		((FWLOCALBUS | fc->ongonode) << 16) | 0xffff , addr,
		fw_bus_explore_callback);
	if(xfer == NULL) goto done;
#else
	xfer = fw_xfer_alloc(M_FWXFER);
	if(xfer == NULL){
		goto done;
	}
	xfer->send.spd = 0;
	fp = &xfer->send.hdr;
	fp->mode.rreqq.dest_hi = 0xffff;
	fp->mode.rreqq.tlrt = 0;
	fp->mode.rreqq.tcode = FWTCODE_RREQQ;
	fp->mode.rreqq.pri = 0;
	fp->mode.rreqq.src = 0;
	fp->mode.rreqq.dst = FWLOCALBUS | fc->ongonode;
	fp->mode.rreqq.dest_lo = addr;
	xfer->act.hand = fw_bus_explore_callback;

	if (firewire_debug)
		kprintf("node%d: explore addr=0x%x\n",
				fc->ongonode, fc->ongoaddr);
	err = fw_asyreq(fc, -1, xfer);
	if(err){
		fw_xfer_free( xfer);
		return;
	}
#endif
	return;
done:
	/* fw_attach_devs */
	fc->status = FWBUSEXPDONE;
	if (firewire_debug)
		kprintf("bus_explore done\n");
	fw_attach_dev(fc);
	return;

}

/* Portable Async. request read quad */
struct fw_xfer *
asyreqq(struct firewire_comm *fc, u_int8_t spd, u_int8_t tl, u_int8_t rt,
	u_int32_t addr_hi, u_int32_t addr_lo,
	void (*hand) (struct fw_xfer*))
{
	struct fw_xfer *xfer;
	struct fw_pkt *fp;
	int err;

	xfer = fw_xfer_alloc(M_FWXFER);
	if (xfer == NULL)
		return NULL;

	xfer->send.spd = spd; /* XXX:min(spd, fc->spd) */
	fp = &xfer->send.hdr;
	fp->mode.rreqq.dest_hi = addr_hi & 0xffff;
	if(tl & FWP_TL_VALID){
		fp->mode.rreqq.tlrt = (tl & 0x3f) << 2;
	}else{
		fp->mode.rreqq.tlrt = 0;
	}
	fp->mode.rreqq.tlrt |= rt & 0x3;
	fp->mode.rreqq.tcode = FWTCODE_RREQQ;
	fp->mode.rreqq.pri = 0;
	fp->mode.rreqq.src = 0;
	fp->mode.rreqq.dst = addr_hi >> 16;
	fp->mode.rreqq.dest_lo = addr_lo;
	xfer->act.hand = hand;

	err = fw_asyreq(fc, -1, xfer);
	if(err){
		fw_xfer_free( xfer);
		return NULL;
	}
	return xfer;
}

/*
 * Callback for the IEEE1394 bus information collection. 
 */
static void
fw_bus_explore_callback(struct fw_xfer *xfer)
{
	struct firewire_comm *fc;
	struct fw_pkt *sfp,*rfp;
	struct csrhdr *chdr;
	struct csrdir *csrd;
	struct csrreg *csrreg;
	u_int32_t offset;

	
	if(xfer == NULL) {
		kprintf("xfer == NULL\n");
		return;
	}
	fc = xfer->fc;

	if (firewire_debug)
		kprintf("node%d: callback addr=0x%x\n",
			fc->ongonode, fc->ongoaddr);

	if(xfer->resp != 0){
		kprintf("node%d: resp=%d addr=0x%x\n",
			fc->ongonode, xfer->resp, fc->ongoaddr);
		goto errnode;
	}

	sfp = &xfer->send.hdr;
	rfp = &xfer->recv.hdr;
#if 0
	{
		u_int32_t *qld;
		int i;
		qld = (u_int32_t *)xfer->recv.buf;
		kprintf("len:%d\n", xfer->recv.len);
		for( i = 0 ; i <= xfer->recv.len && i < 32; i+= 4){
			kprintf("0x%08x ", rfp->mode.ld[i/4]);
			if((i % 16) == 15) kprintf("\n");
		}
		if((i % 16) != 15) kprintf("\n");
	}
#endif
	if(fc->ongodev == NULL){
		if(sfp->mode.rreqq.dest_lo == (0xf0000000 | CSRROMOFF)){
			rfp->mode.rresq.data = ntohl(rfp->mode.rresq.data);
			chdr = (struct csrhdr *)(void *)(&rfp->mode.rresq.data);
/* If CSR is minimal confinguration, more investgation is not needed. */
			if(chdr->info_len == 1){
				if (firewire_debug)
					kprintf("node%d: minimal config\n",
								fc->ongonode);
				goto nextnode;
			}else{
				fc->ongoaddr = CSRROMOFF + 0xc;
			}
		}else if(sfp->mode.rreqq.dest_lo == (0xf0000000 |(CSRROMOFF + 0xc))){
			fc->ongoeui.hi = ntohl(rfp->mode.rresq.data);
			fc->ongoaddr = CSRROMOFF + 0x10;
		}else if(sfp->mode.rreqq.dest_lo == (0xf0000000 |(CSRROMOFF + 0x10))){
			fc->ongoeui.lo = ntohl(rfp->mode.rresq.data);
			if (fc->ongoeui.hi == 0 && fc->ongoeui.lo == 0) {
				if (firewire_debug)
					kprintf("node%d: eui64 is zero.\n",
							fc->ongonode);
				goto nextnode;
			}
			fc->ongoaddr = CSRROMOFF;
		}
	}else{
		if (fc->ongoaddr == CSRROMOFF &&
		    fc->ongodev->csrrom[0] == ntohl(rfp->mode.rresq.data)) {
			fc->ongodev->status = FWDEVATTACHED;
			goto nextnode;
		}
		fc->ongodev->csrrom[(fc->ongoaddr - CSRROMOFF)/4] = ntohl(rfp->mode.rresq.data);
		if(fc->ongoaddr > fc->ongodev->rommax){
			fc->ongodev->rommax = fc->ongoaddr;
		}
		csrd = SLIST_FIRST(&fc->ongocsr);
		if((csrd = SLIST_FIRST(&fc->ongocsr)) == NULL){
			chdr = (struct csrhdr *)(fc->ongodev->csrrom);
			offset = CSRROMOFF;
		}else{
			chdr = (struct csrhdr *)&fc->ongodev->csrrom[(csrd->off - CSRROMOFF)/4];
			offset = csrd->off;
		}
		if(fc->ongoaddr > (CSRROMOFF + 0x14) && fc->ongoaddr != offset){
			csrreg = (struct csrreg *)&fc->ongodev->csrrom[(fc->ongoaddr - CSRROMOFF)/4];
			if( csrreg->key == 0x81 || csrreg->key == 0xd1){
				csrd = SLIST_FIRST(&fc->csrfree);
				if(csrd == NULL){
					goto nextnode;
				}else{
					csrd->ongoaddr = fc->ongoaddr;
					fc->ongoaddr += csrreg->val * 4;
					csrd->off = fc->ongoaddr;
					SLIST_REMOVE_HEAD(&fc->csrfree, link);
					SLIST_INSERT_HEAD(&fc->ongocsr, csrd, link);
					goto nextaddr;
				}
			}
		}
		fc->ongoaddr += 4;
		if(((fc->ongoaddr - offset)/4 > chdr->crc_len) &&
				(fc->ongodev->rommax < 0x414)){
			if(fc->ongodev->rommax <= 0x414){
				csrd = SLIST_FIRST(&fc->csrfree);
				if(csrd == NULL) goto nextnode;
				csrd->off = fc->ongoaddr;
				csrd->ongoaddr = fc->ongoaddr;
				SLIST_REMOVE_HEAD(&fc->csrfree, link);
				SLIST_INSERT_HEAD(&fc->ongocsr, csrd, link);
			}
			goto nextaddr;
		}

		while(((fc->ongoaddr - offset)/4 > chdr->crc_len)){
			if(csrd == NULL){
				goto nextnode;
			}
			fc->ongoaddr = csrd->ongoaddr + 4;
			SLIST_REMOVE_HEAD(&fc->ongocsr, link);
			SLIST_INSERT_HEAD(&fc->csrfree, csrd, link);
			csrd = SLIST_FIRST(&fc->ongocsr);
			if((csrd = SLIST_FIRST(&fc->ongocsr)) == NULL){
				chdr = (struct csrhdr *)(fc->ongodev->csrrom);
				offset = CSRROMOFF;
			}else{
				chdr = (struct csrhdr *)&(fc->ongodev->csrrom[(csrd->off - CSRROMOFF)/4]);
				offset = csrd->off;
			}
		}
		if((fc->ongoaddr - CSRROMOFF) > CSRROMSIZE){
			goto nextnode;
		}
	}
nextaddr:
	fw_xfer_free( xfer);
	fw_bus_explore(fc);
	return;
errnode:
	fc->retry_count++;
	if (fc->ongodev != NULL)
		fc->ongodev->status = FWDEVINVAL;
nextnode:
	fw_xfer_free( xfer);
	fc->ongonode++;
/* housekeeping work space */
	fc->ongoaddr = CSRROMOFF;
	fc->ongodev = NULL;
	fc->ongoeui.hi = 0xffffffff; fc->ongoeui.lo = 0xffffffff;
	while((csrd = SLIST_FIRST(&fc->ongocsr)) != NULL){
		SLIST_REMOVE_HEAD(&fc->ongocsr, link);
		SLIST_INSERT_HEAD(&fc->csrfree, csrd, link);
	}
	fw_bus_explore(fc);
	return;
}

/*
 * To attach sub-devices layer onto IEEE1394 bus.
 */
static void
fw_attach_dev(struct firewire_comm *fc)
{
	struct fw_device *fwdev, *next;
	int i, err;
	device_t *devlistp;
	int devcnt;
	struct firewire_dev_comm *fdc;

	for (fwdev = STAILQ_FIRST(&fc->devices); fwdev != NULL; fwdev = next) {
		next = STAILQ_NEXT(fwdev, link);
		if (fwdev->status == FWDEVINIT) {
			fwdev->status = FWDEVATTACHED;
		} else if (fwdev->status == FWDEVINVAL) {
			fwdev->rcnt ++;
			if (fwdev->rcnt > hold_count) {
				/*
				 * Remove devices which have not been seen
				 * for a while.
				 */
				STAILQ_REMOVE(&fc->devices, fwdev, fw_device,
				    link);
				kfree(fwdev, M_FW);
			}
		}
	}

	err = device_get_children(fc->bdev, &devlistp, &devcnt);
	if( err != 0 )
		return;
	for( i = 0 ; i < devcnt ; i++){
		if (device_get_state(devlistp[i]) >= DS_ATTACHED)  {
			fdc = device_get_softc(devlistp[i]);
			if (fdc->post_explore != NULL)
				fdc->post_explore(fdc);
		}
	}
	kfree(devlistp, M_TEMP);

	if (fc->retry_count > 0) {
		kprintf("probe failed for %d node\n", fc->retry_count);
#if 0
		callout_reset(&fc->retry_probe_callout, hz*2,
					(void *)fc->ibr, (void *)fc);
#endif
	}
	return;
}

/*
 * To allocate uniq transaction label.
 */
static int
fw_get_tlabel(struct firewire_comm *fc, struct fw_xfer *xfer)
{
	u_int i;
	struct tlabel *tl, *tmptl;
	static u_int32_t label = 0;

	crit_enter();
	for( i = 0 ; i < 0x40 ; i ++){
		label = (label + 1) & 0x3f;
		for(tmptl = STAILQ_FIRST(&fc->tlabels[label]);
			tmptl != NULL; tmptl = STAILQ_NEXT(tmptl, link)){
			if (tmptl->xfer->send.hdr.mode.hdr.dst ==
			    xfer->send.hdr.mode.hdr.dst)
				break;
		}
		if(tmptl == NULL) {
			tl = kmalloc(sizeof(struct tlabel), M_FW, M_WAITOK);
			tl->xfer = xfer;
			STAILQ_INSERT_TAIL(&fc->tlabels[label], tl, link);
			crit_exit();
			if (firewire_debug > 1)
				kprintf("fw_get_tlabel: dst=%d tl=%d\n",
				    xfer->send.hdr.mode.hdr.dst, label);
			return(label);
		}
	}
	crit_exit();

	kprintf("fw_get_tlabel: no free tlabel\n");
	return(-1);
}

static void
fw_rcv_copy(struct fw_rcv_buf *rb)
{
	struct fw_pkt *pkt;
	u_char *p;
	struct tcode_info *tinfo;
	u_int res, i, len, plen;

	rb->xfer->recv.spd -= rb->spd;

	pkt = (struct fw_pkt *)rb->vec->iov_base;
	tinfo = &rb->fc->tcode[pkt->mode.hdr.tcode];

	/* Copy header */ 
	p = (u_char *)&rb->xfer->recv.hdr;
	bcopy(rb->vec->iov_base, p, tinfo->hdr_len);
	rb->vec->iov_base = (uint8_t *)rb->vec->iov_base + tinfo->hdr_len;
	rb->vec->iov_len -= tinfo->hdr_len;

	/* Copy payload */
	p = (u_char *)rb->xfer->recv.payload;
	res = rb->xfer->recv.pay_len;

	/* special handling for RRESQ */
	if (pkt->mode.hdr.tcode == FWTCODE_RRESQ &&
	    p != NULL && res >= sizeof(u_int32_t)) {
		*(u_int32_t *)p = pkt->mode.rresq.data;
		rb->xfer->recv.pay_len = sizeof(u_int32_t);
		return;
	}

	if ((tinfo->flag & FWTI_BLOCK_ASY) == 0)
		return;

	plen = pkt->mode.rresb.len;

	for (i = 0; i < rb->nvec; i++, rb->vec++) {
		len = MIN(rb->vec->iov_len, plen);
		if (res < len) {
			kprintf("rcv buffer(%d) is %d bytes short.\n",
			    rb->xfer->recv.pay_len, len - res);
			len = res;
		}
		bcopy(rb->vec->iov_base, p, len);
		p += len;
		res -= len;
		plen -= len;
		if (res == 0 || plen == 0)
			break;
	}
	rb->xfer->recv.pay_len -= res;

}

/*
 * Generic packet receving process.
 */
void
fw_rcv(struct fw_rcv_buf *rb)
{
	struct fw_pkt *fp, *resfp;
	struct fw_bind *bind;
	int tcode;
	int i, len, oldstate;
#if 0
	{
		u_int32_t *qld;
		int i;
		qld = (u_int32_t *)buf;
		kprintf("spd %d len:%d\n", spd, len);
		for( i = 0 ; i <= len && i < 32; i+= 4){
			kprintf("0x%08x ", ntohl(qld[i/4]));
			if((i % 16) == 15) kprintf("\n");
		}
		if((i % 16) != 15) kprintf("\n");
	}
#endif
	fp = (struct fw_pkt *)rb->vec[0].iov_base;
	tcode = fp->mode.common.tcode;
	switch (tcode) {
	case FWTCODE_WRES:
	case FWTCODE_RRESQ:
	case FWTCODE_RRESB:
	case FWTCODE_LRES:
		rb->xfer = fw_tl2xfer(rb->fc, fp->mode.hdr.src,
					fp->mode.hdr.tlrt >> 2);
		if(rb->xfer == NULL) {
			kprintf("fw_rcv: unknown response "
			    "%s(%x) src=0x%x tl=0x%x rt=%d data=0x%x\n",
			    tcode_str[tcode], tcode,
			    fp->mode.hdr.src,
			    fp->mode.hdr.tlrt >> 2,
			    fp->mode.hdr.tlrt & 3,
			    fp->mode.rresq.data);
#if 1
			kprintf("try ad-hoc work around!!\n");
			rb->xfer = fw_tl2xfer(rb->fc, fp->mode.hdr.src,
					(fp->mode.hdr.tlrt >> 2)^3);
			if (rb->xfer == NULL) {
				kprintf("no use...\n");
				goto err;
			}
#else
			goto err;
#endif
		}
		fw_rcv_copy(rb);
		if (rb->xfer->recv.hdr.mode.wres.rtcode != RESP_CMP)
			rb->xfer->resp = EIO;
		else
			rb->xfer->resp = 0;
		/* make sure the packet is drained in AT queue */
		oldstate = rb->xfer->state;
		rb->xfer->state = FWXF_RCVD;
		switch (oldstate) {
		case FWXF_SENT:
			fw_xfer_done(rb->xfer);
			break;
		case FWXF_START:
#if 0
			if (firewire_debug)
				kprintf("not sent yet tl=%x\n", rb->xfer->tl);
#endif
			break;
		default:
			kprintf("unexpected state %d\n", rb->xfer->state);
		}
		return;
	case FWTCODE_WREQQ:
	case FWTCODE_WREQB:
	case FWTCODE_RREQQ:
	case FWTCODE_RREQB:
	case FWTCODE_LREQ:
		bind = fw_bindlookup(rb->fc, fp->mode.rreqq.dest_hi,
			fp->mode.rreqq.dest_lo);
		if(bind == NULL){
			kprintf("Unknown service addr 0x%04x:0x%08x %s(%x)"
			    " src=0x%x data=%x\n",
			    fp->mode.wreqq.dest_hi, fp->mode.wreqq.dest_lo,
			    tcode_str[tcode], tcode,
			    fp->mode.hdr.src, ntohl(fp->mode.wreqq.data));
			if (rb->fc->status == FWBUSRESET) {
				kprintf("fw_rcv: cannot respond(bus reset)!\n");
				goto err;
			}
			rb->xfer = fw_xfer_alloc(M_FWXFER);
			if(rb->xfer == NULL){
				return;
			}
			rb->xfer->send.spd = rb->spd;
			rb->xfer->send.pay_len = 0;
			resfp = &rb->xfer->send.hdr;
			switch (tcode) {
			case FWTCODE_WREQQ:
			case FWTCODE_WREQB:
				resfp->mode.hdr.tcode = FWTCODE_WRES;
				break;
			case FWTCODE_RREQQ:
				resfp->mode.hdr.tcode = FWTCODE_RRESQ;
				break;
			case FWTCODE_RREQB:
				resfp->mode.hdr.tcode = FWTCODE_RRESB;
				break;
			case FWTCODE_LREQ:
				resfp->mode.hdr.tcode = FWTCODE_LRES;
				break;
			}
			resfp->mode.hdr.dst = fp->mode.hdr.src;
			resfp->mode.hdr.tlrt = fp->mode.hdr.tlrt;
			resfp->mode.hdr.pri = fp->mode.hdr.pri;
			resfp->mode.rresb.rtcode = RESP_ADDRESS_ERROR;
			resfp->mode.rresb.extcode = 0;
			resfp->mode.rresb.len = 0;
/*
			rb->xfer->act.hand = fw_asy_callback;
*/
			rb->xfer->act.hand = fw_xfer_free;
			if(fw_asyreq(rb->fc, -1, rb->xfer)){
				fw_xfer_free(rb->xfer);
				return;
			}
			goto err;
		}
		len = 0;
		for (i = 0; i < rb->nvec; i ++)
			len += rb->vec[i].iov_len;
		switch(bind->act_type){
		case FWACT_XFER:
			crit_enter();
			rb->xfer = STAILQ_FIRST(&bind->xferlist);
			if (rb->xfer == NULL) {
				kprintf("Discard a packet for this bind.\n");
				crit_exit();
				goto err;
			}
			STAILQ_REMOVE_HEAD(&bind->xferlist, link);
			crit_exit();
			fw_rcv_copy(rb);
			rb->xfer->act.hand(rb->xfer);
			return;
			break;
		case FWACT_CH:
			if(rb->fc->ir[bind->sub]->queued >=
				rb->fc->ir[bind->sub]->maxq){
				device_printf(rb->fc->bdev,
					"Discard a packet %x %d\n",
					bind->sub,
					rb->fc->ir[bind->sub]->queued);
				goto err;
			}
			crit_enter();
			rb->xfer = STAILQ_FIRST(&bind->xferlist);
			if (rb->xfer == NULL) {
				kprintf("Discard packet for this bind\n");
				crit_exit();
				goto err;
			}
			STAILQ_REMOVE_HEAD(&bind->xferlist, link);
			crit_exit();
			fw_rcv_copy(rb);
			crit_enter();
			rb->fc->ir[bind->sub]->queued++;
			STAILQ_INSERT_TAIL(&rb->fc->ir[bind->sub]->q,
			    rb->xfer, link);
			crit_exit();

			wakeup((caddr_t)rb->fc->ir[bind->sub]);

			return;
			break;
		default:
			goto err;
			break;
		}
		break;
#if 0 /* shouldn't happen ?? or for GASP */
	case FWTCODE_STREAM:
	{
		struct fw_xferq *xferq;

		xferq = rb->fc->ir[sub];
#if 0
		kprintf("stream rcv dma %d len %d off %d spd %d\n",
			sub, len, off, spd);
#endif
		if(xferq->queued >= xferq->maxq) {
			kprintf("receive queue is full\n");
			goto err;
		}
		/* XXX get xfer from xfer queue, we don't need copy for 
			per packet mode */
		rb->xfer = fw_xfer_alloc_buf(M_FWXFER, 0, /* XXX */
						vec[0].iov_len);
		if (rb->xfer == NULL) goto err;
		fw_rcv_copy(rb)
		crit_enter();
		xferq->queued++;
		STAILQ_INSERT_TAIL(&xferq->q, rb->xfer, link);
		crit_exit();
		sc = device_get_softc(rb->fc->bdev);
		KNOTE(&xferq->rkq.ki_note, 0);
		if (xferq->flag & FWXFERQ_WAKEUP) {
			xferq->flag &= ~FWXFERQ_WAKEUP;
			wakeup((caddr_t)xferq);
		}
		if (xferq->flag & FWXFERQ_HANDLER) {
			xferq->hand(xferq);
		}
		return;
		break;
	}
#endif
	default:
		kprintf("fw_rcv: unknown tcode %d\n", tcode);
		break;
	}
err:
	return;
}

/*
 * Post process for Bus Manager election process.
 */
static void
fw_try_bmr_callback(struct fw_xfer *xfer)
{
	struct firewire_comm *fc;
	int bmr;

	if (xfer == NULL)
		return;
	fc = xfer->fc;
	if (xfer->resp != 0)
		goto error;
	if (xfer->recv.payload == NULL)
		goto error;
	if (xfer->recv.hdr.mode.lres.rtcode != FWRCODE_COMPLETE)
		goto error;

	bmr = ntohl(xfer->recv.payload[0]);
	if (bmr == 0x3f)
		bmr = fc->nodeid;

	CSRARC(fc, BUS_MGR_ID) = fc->set_bmr(fc, bmr & 0x3f);
	fw_xfer_free_buf(xfer);
	fw_bmr(fc);
	return;

error:
	device_printf(fc->bdev, "bus manager election failed\n");
	fw_xfer_free_buf(xfer);
}


/*
 * To candidate Bus Manager election process.
 */
static void
fw_try_bmr(void *arg)
{
	struct fw_xfer *xfer;
	struct firewire_comm *fc = (struct firewire_comm *)arg;
	struct fw_pkt *fp;
	int err = 0;

	xfer = fw_xfer_alloc_buf(M_FWXFER, 8, 4);
	if(xfer == NULL){
		return;
	}
	xfer->send.spd = 0;
	fc->status = FWBUSMGRELECT;

	fp = &xfer->send.hdr;
	fp->mode.lreq.dest_hi = 0xffff;
	fp->mode.lreq.tlrt = 0;
	fp->mode.lreq.tcode = FWTCODE_LREQ;
	fp->mode.lreq.pri = 0;
	fp->mode.lreq.src = 0;
	fp->mode.lreq.len = 8;
	fp->mode.lreq.extcode = EXTCODE_CMP_SWAP;
	fp->mode.lreq.dst = FWLOCALBUS | fc->irm;
	fp->mode.lreq.dest_lo = 0xf0000000 | BUS_MGR_ID;
	xfer->send.payload[0] = htonl(0x3f);
	xfer->send.payload[1] = htonl(fc->nodeid);
	xfer->act.hand = fw_try_bmr_callback;

	err = fw_asyreq(fc, -1, xfer);
	if(err){
		fw_xfer_free_buf(xfer);
		return;
	}
	return;
}

#ifdef FW_VMACCESS
/*
 * Software implementation for physical memory block access.
 * XXX:Too slow, usef for debug purpose only.
 */
static void
fw_vmaccess(struct fw_xfer *xfer){
	struct fw_pkt *rfp, *sfp = NULL;
	u_int32_t *ld = (u_int32_t *)xfer->recv.buf;

	kprintf("vmaccess spd:%2x len:%03x data:%08x %08x %08x %08x\n",
			xfer->spd, xfer->recv.len, ntohl(ld[0]), ntohl(ld[1]), ntohl(ld[2]), ntohl(ld[3]));
	kprintf("vmaccess          data:%08x %08x %08x %08x\n", ntohl(ld[4]), ntohl(ld[5]), ntohl(ld[6]), ntohl(ld[7]));
	if(xfer->resp != 0){
		fw_xfer_free( xfer);
		return;
	}
	if(xfer->recv.buf == NULL){
		fw_xfer_free( xfer);
		return;
	}
	rfp = (struct fw_pkt *)xfer->recv.buf;
	switch(rfp->mode.hdr.tcode){
		/* XXX need fix for 64bit arch */
		case FWTCODE_WREQB:
			xfer->send.buf = kmalloc(12, M_FW, M_WAITOK);
			xfer->send.len = 12;
			sfp = (struct fw_pkt *)xfer->send.buf;
			bcopy(rfp->mode.wreqb.payload,
				(caddr_t)ntohl(rfp->mode.wreqb.dest_lo), ntohs(rfp->mode.wreqb.len));
			sfp->mode.wres.tcode = FWTCODE_WRES;
			sfp->mode.wres.rtcode = 0;
			break;
		case FWTCODE_WREQQ:
			xfer->send.buf = kmalloc(12, M_FW, M_WAITOK);
			xfer->send.len = 12;
			sfp->mode.wres.tcode = FWTCODE_WRES;
			*((u_int32_t *)(ntohl(rfp->mode.wreqb.dest_lo))) = rfp->mode.wreqq.data;
			sfp->mode.wres.rtcode = 0;
			break;
		case FWTCODE_RREQB:
			xfer->send.buf = kmalloc(16 + rfp->mode.rreqb.len, M_FW, M_WAITOK);
			xfer->send.len = 16 + ntohs(rfp->mode.rreqb.len);
			sfp = (struct fw_pkt *)xfer->send.buf;
			bcopy((caddr_t)ntohl(rfp->mode.rreqb.dest_lo),
				sfp->mode.rresb.payload, (u_int16_t)ntohs(rfp->mode.rreqb.len));
			sfp->mode.rresb.tcode = FWTCODE_RRESB;
			sfp->mode.rresb.len = rfp->mode.rreqb.len;
			sfp->mode.rresb.rtcode = 0;
			sfp->mode.rresb.extcode = 0;
			break;
		case FWTCODE_RREQQ:
			xfer->send.buf = kmalloc(16, M_FW, M_WAITOK);
			xfer->send.len = 16;
			sfp = (struct fw_pkt *)xfer->send.buf;
			sfp->mode.rresq.data = *(u_int32_t *)(ntohl(rfp->mode.rreqq.dest_lo));
			sfp->mode.wres.tcode = FWTCODE_RRESQ;
			sfp->mode.rresb.rtcode = 0;
			break;
		default:
			fw_xfer_free( xfer);
			return;
	}
	sfp->mode.hdr.dst = rfp->mode.hdr.src;
	xfer->dst = ntohs(rfp->mode.hdr.src);
	xfer->act.hand = fw_xfer_free;
	xfer->retry_req = fw_asybusy;

	sfp->mode.hdr.tlrt = rfp->mode.hdr.tlrt;
	sfp->mode.hdr.pri = 0;

	fw_asyreq(xfer->fc, -1, xfer);
/**/
	return;
}
#endif 

/*
 * CRC16 check-sum for IEEE1394 register blocks.
 */
u_int16_t
fw_crc16(u_int32_t *ptr, u_int32_t len){
	u_int32_t i, sum, crc = 0;
	int shift;
	len = (len + 3) & ~3;
	for(i = 0 ; i < len ; i+= 4){
		for( shift = 28 ; shift >= 0 ; shift -= 4){
			sum = ((crc >> 12) ^ (ptr[i/4] >> shift)) & 0xf;
			crc = (crc << 4) ^ ( sum << 12 ) ^ ( sum << 5) ^ sum;
		}
		crc &= 0xffff;
	}
	return((u_int16_t) crc);
}

static int
fw_bmr(struct firewire_comm *fc)
{
	struct fw_device fwdev;
	union fw_self_id *self_id;
	int cmstr;
	u_int32_t quad;

	/* Check to see if the current root node is cycle master capable */
	self_id = &fc->topology_map->self_id[fc->max_node];
	if (fc->max_node > 0) {
		/* XXX check cmc bit of businfo block rather than contender */
		if (self_id->p0.link_active && self_id->p0.contender)
			cmstr = fc->max_node;
		else {
			device_printf(fc->bdev,
				"root node is not cycle master capable\n");
			/* XXX shall we be the cycle master? */
			cmstr = fc->nodeid;
			/* XXX need bus reset */
		}
	} else
		cmstr = -1;

	device_printf(fc->bdev, "bus manager %d ", CSRARC(fc, BUS_MGR_ID));
	if(CSRARC(fc, BUS_MGR_ID) != fc->nodeid) {
		/* We are not the bus manager */
		kprintf("\n");
		return(0);
	}
	kprintf("(me)\n");

	/* Optimize gapcount */
	if(fc->max_hop <= MAX_GAPHOP )
		fw_phy_config(fc, cmstr, gap_cnt[fc->max_hop]);
	/* If we are the cycle master, nothing to do */
	if (cmstr == fc->nodeid || cmstr == -1)
		return 0;
	/* Bus probe has not finished, make dummy fwdev for cmstr */
	bzero(&fwdev, sizeof(fwdev));
	fwdev.fc = fc;
	fwdev.dst = cmstr;
	fwdev.speed = 0;
	fwdev.maxrec = 8; /* 512 */
	fwdev.status = FWDEVINIT;
	/* Set cmstr bit on the cycle master */
	quad = htonl(1 << 8);
	fwmem_write_quad(&fwdev, NULL, 0/*spd*/,
		0xffff, 0xf0000000 | STATE_SET, &quad, fw_asy_callback_free);

	return 0;
}

static int
fw_modevent(module_t mode, int type, void *data)
{
	int err = 0;
#if defined(__FreeBSD__) && __FreeBSD_version >= 500000
	static eventhandler_tag fwdev_ehtag = NULL;
#endif

	switch (type) {
	case MOD_LOAD:
#if defined(__FreeBSD__) && __FreeBSD_version >= 500000
		fwdev_ehtag = EVENTHANDLER_REGISTER(dev_clone,
						fwdev_clone, 0, 1000);
#endif
		break;
	case MOD_UNLOAD:
#if defined(__FreeBSD__) && __FreeBSD_version >= 500000
		if (fwdev_ehtag != NULL)
			EVENTHANDLER_DEREGISTER(dev_clone, fwdev_ehtag);
#endif
		break;
	case MOD_SHUTDOWN:
		break;
	}
	return (err);
}

/*
 * This causes the firewire identify to be called for any attached fwohci
 * device in the system.
 */
DECLARE_DUMMY_MODULE(firewire);
DRIVER_MODULE(firewire,fwohci,firewire_driver,firewire_devclass,fw_modevent,NULL);
MODULE_VERSION(firewire, 1);