Linux Audio

Check our new training course

Embedded Linux Audio

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

Bootlin logo

Elixir Cross Referencer

Loading...
   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
/*
 *  scsi.c Copyright (C) 1992 Drew Eckhardt
 *         Copyright (C) 1993, 1994, 1995, 1999 Eric Youngdale
 *
 *  generic mid-level SCSI driver
 *      Initial versions: Drew Eckhardt
 *      Subsequent revisions: Eric Youngdale
 *
 *  <drew@colorado.edu>
 *
 *  Bug correction thanks go to :
 *      Rik Faith <faith@cs.unc.edu>
 *      Tommy Thorn <tthorn>
 *      Thomas Wuensche <tw@fgb1.fgb.mw.tu-muenchen.de>
 *
 *  Modified by Eric Youngdale eric@andante.org or ericy@gnu.ai.mit.edu to
 *  add scatter-gather, multiple outstanding request, and other
 *  enhancements.
 *
 *  Native multichannel, wide scsi, /proc/scsi and hot plugging
 *  support added by Michael Neuffer <mike@i-connect.net>
 *
 *  Added request_module("scsi_hostadapter") for kerneld:
 *  (Put an "alias scsi_hostadapter your_hostadapter" in /etc/modules.conf)
 *  Bjorn Ekwall  <bj0rn@blox.se>
 *  (changed to kmod)
 *
 *  Major improvements to the timeout, abort, and reset processing,
 *  as well as performance modifications for large queue depths by
 *  Leonard N. Zubkoff <lnz@dandelion.com>
 *
 *  Converted cli() code to spinlocks, Ingo Molnar
 *
 *  Jiffies wrap fixes (host->resetting), 3 Dec 1998 Andrea Arcangeli
 *
 *  out_of_space hacks, D. Gilbert (dpg) 990608
 */

#include <linux/config.h>
#include <linux/module.h>

#include <linux/sched.h>
#include <linux/timer.h>
#include <linux/string.h>
#include <linux/malloc.h>
#include <linux/ioport.h>
#include <linux/kernel.h>
#include <linux/stat.h>
#include <linux/blk.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/init.h>

#define __KERNEL_SYSCALLS__

#include <linux/unistd.h>
#include <linux/spinlock.h>

#include <asm/system.h>
#include <asm/irq.h>
#include <asm/dma.h>
#include <asm/uaccess.h>

#include "scsi.h"
#include "hosts.h"
#include "constants.h"

#ifdef CONFIG_KMOD
#include <linux/kmod.h>
#endif

#undef USE_STATIC_SCSI_MEMORY

struct proc_dir_entry *proc_scsi = NULL;

#ifdef CONFIG_PROC_FS
static int scsi_proc_info(char *buffer, char **start, off_t offset, int length);
static void scsi_dump_status(int level);
#endif

/*
   static const char RCSid[] = "$Header: /vger/u4/cvs/linux/drivers/scsi/scsi.c,v 1.38 1997/01/19 23:07:18 davem Exp $";
 */

/*
 * Definitions and constants.
 */

/*
 * PAGE_SIZE must be a multiple of the sector size (512).  True
 * for all reasonably recent architectures (even the VAX...).
 */
#define SECTOR_SIZE		512
#define SECTORS_PER_PAGE	(PAGE_SIZE/SECTOR_SIZE)

#if SECTORS_PER_PAGE <= 8
typedef unsigned char FreeSectorBitmap;
#elif SECTORS_PER_PAGE <= 32
typedef unsigned int FreeSectorBitmap;
#else
#error You lose.
#endif

#define MIN_RESET_DELAY (2*HZ)

/* Do not call reset on error if we just did a reset within 15 sec. */
#define MIN_RESET_PERIOD (15*HZ)

/* The following devices are known not to tolerate a lun != 0 scan for
 * one reason or another.  Some will respond to all luns, others will
 * lock up.
 */

#define BLIST_NOLUN     	0x001
#define BLIST_FORCELUN  	0x002
#define BLIST_BORKEN    	0x004
#define BLIST_KEY       	0x008
#define BLIST_SINGLELUN 	0x010
#define BLIST_NOTQ		0x020
#define BLIST_SPARSELUN 	0x040
#define BLIST_MAX5LUN		0x080
#define BLIST_ISDISK    	0x100
#define BLIST_ISROM     	0x200
#define BLIST_GHOST     	0x400   



/*
 * Data declarations.
 */
unsigned long scsi_pid = 0;
Scsi_Cmnd *last_cmnd = NULL;
/* Command groups 3 and 4 are reserved and should never be used.  */
const unsigned char scsi_command_size[8] =
{
	6, 10, 10, 12,
	12, 12, 10, 10
};
static unsigned long serial_number = 0;
static Scsi_Cmnd *scsi_bh_queue_head = NULL;
static Scsi_Cmnd *scsi_bh_queue_tail = NULL;
static FreeSectorBitmap *dma_malloc_freelist = NULL;
static int need_isa_bounce_buffers;
static unsigned int dma_sectors = 0;
unsigned int scsi_dma_free_sectors = 0;
unsigned int scsi_need_isa_buffer = 0;
static unsigned char **dma_malloc_pages = NULL;

/*
 * Note - the initial logging level can be set here to log events at boot time.
 * After the system is up, you may enable logging via the /proc interface.
 */
unsigned int scsi_logging_level = 0;

const char *const scsi_device_types[MAX_SCSI_DEVICE_CODE] =
{
	"Direct-Access    ",
	"Sequential-Access",
	"Printer          ",
	"Processor        ",
	"WORM             ",
	"CD-ROM           ",
	"Scanner          ",
	"Optical Device   ",
	"Medium Changer   ",
	"Communications   ",
	"Unknown          ",
	"Unknown          ",
	"Unknown          ",
	"Enclosure        ",
};

/* 
 * Function prototypes.
 */
static void resize_dma_pool(void);
static void print_inquiry(unsigned char *data);
extern void scsi_times_out(Scsi_Cmnd * SCpnt);
static int scan_scsis_single(int channel, int dev, int lun, int *max_scsi_dev,
		int *sparse_lun, Scsi_Device ** SDpnt, Scsi_Cmnd * SCpnt,
			     struct Scsi_Host *shpnt, char *scsi_result);
void scsi_build_commandblocks(Scsi_Device * SDpnt);
static int scsi_unregister_device(struct Scsi_Device_Template *tpnt);

/*
 * These are the interface to the old error handling code.  It should go away
 * someday soon.
 */
extern void scsi_old_done(Scsi_Cmnd * SCpnt);
extern void scsi_old_times_out(Scsi_Cmnd * SCpnt);

struct dev_info {
	const char *vendor;
	const char *model;
	const char *revision;	/* Latest revision known to be bad.  Not used yet */
	unsigned flags;
};

/*
 * This is what was previously known as the blacklist.  The concept
 * has been expanded so that we can specify other types of things we
 * need to be aware of.
 */
static struct dev_info device_list[] =
{
	{"Aashima", "IMAGERY 2400SP", "1.03", BLIST_NOLUN},	/* Locks up if polled for lun != 0 */
	{"CHINON", "CD-ROM CDS-431", "H42", BLIST_NOLUN},	/* Locks up if polled for lun != 0 */
	{"CHINON", "CD-ROM CDS-535", "Q14", BLIST_NOLUN},	/* Locks up if polled for lun != 0 */
	{"DENON", "DRD-25X", "V", BLIST_NOLUN},			/* Locks up if probed for lun != 0 */
	{"HITACHI", "DK312C", "CM81", BLIST_NOLUN},		/* Responds to all lun - dtg */
	{"HITACHI", "DK314C", "CR21", BLIST_NOLUN},		/* responds to all lun */
	{"IMS", "CDD521/10", "2.06", BLIST_NOLUN},		/* Locks-up when LUN>0 polled. */
	{"MAXTOR", "XT-3280", "PR02", BLIST_NOLUN},		/* Locks-up when LUN>0 polled. */
	{"MAXTOR", "XT-4380S", "B3C", BLIST_NOLUN},		/* Locks-up when LUN>0 polled. */
	{"MAXTOR", "MXT-1240S", "I1.2", BLIST_NOLUN},		/* Locks up when LUN>0 polled */
	{"MAXTOR", "XT-4170S", "B5A", BLIST_NOLUN},		/* Locks-up sometimes when LUN>0 polled. */
	{"MAXTOR", "XT-8760S", "B7B", BLIST_NOLUN},		/* guess what? */
	{"MEDIAVIS", "RENO CD-ROMX2A", "2.03", BLIST_NOLUN},	/*Responds to all lun */
	{"MICROP", "4110", "*", BLIST_NOTQ},			/* Buggy Tagged Queuing */
	{"NEC", "CD-ROM DRIVE:841", "1.0", BLIST_NOLUN},	/* Locks-up when LUN>0 polled. */
	{"PHILIPS", "PCA80SC", "V4-2", BLIST_NOLUN},		/* Responds to all lun */
	{"RODIME", "RO3000S", "2.33", BLIST_NOLUN},		/* Locks up if polled for lun != 0 */
	{"SANYO", "CRD-250S", "1.20", BLIST_NOLUN},		/* causes failed REQUEST SENSE on lun 1
								 * for aha152x controller, which causes
								 * SCSI code to reset bus.*/
	{"SEAGATE", "ST157N", "\004|j", BLIST_NOLUN},		/* causes failed REQUEST SENSE on lun 1
								 * for aha152x controller, which causes
								 * SCSI code to reset bus.*/
	{"SEAGATE", "ST296", "921", BLIST_NOLUN},		/* Responds to all lun */
	{"SEAGATE", "ST1581", "6538", BLIST_NOLUN},		/* Responds to all lun */
	{"SONY", "CD-ROM CDU-541", "4.3d", BLIST_NOLUN},	
	{"SONY", "CD-ROM CDU-55S", "1.0i", BLIST_NOLUN},
	{"SONY", "CD-ROM CDU-561", "1.7x", BLIST_NOLUN},
	{"SONY", "CD-ROM CDU-8012", "*", BLIST_NOLUN},
	{"TANDBERG", "TDC 3600", "U07", BLIST_NOLUN},		/* Locks up if polled for lun != 0 */
	{"TEAC", "CD-R55S", "1.0H", BLIST_NOLUN},		/* Locks up if polled for lun != 0 */
	{"TEAC", "CD-ROM", "1.06", BLIST_NOLUN},		/* causes failed REQUEST SENSE on lun 1
								 * for seagate controller, which causes
								 * SCSI code to reset bus.*/
	{"TEAC", "MT-2ST/45S2-27", "RV M", BLIST_NOLUN},	/* Responds to all lun */
	{"TEXEL", "CD-ROM", "1.06", BLIST_NOLUN},		/* causes failed REQUEST SENSE on lun 1
								 * for seagate controller, which causes
								 * SCSI code to reset bus.*/
	{"QUANTUM", "LPS525S", "3110", BLIST_NOLUN},		/* Locks sometimes if polled for lun != 0 */
	{"QUANTUM", "PD1225S", "3110", BLIST_NOLUN},		/* Locks sometimes if polled for lun != 0 */
	{"QUANTUM", "FIREBALL ST4.3S", "0F0C", BLIST_NOLUN},	/* Locks up when polled for lun != 0 */
	{"MEDIAVIS", "CDR-H93MV", "1.31", BLIST_NOLUN},		/* Locks up if polled for lun != 0 */
	{"SANKYO", "CP525", "6.64", BLIST_NOLUN},		/* causes failed REQ SENSE, extra reset */
	{"HP", "C1750A", "3226", BLIST_NOLUN},			/* scanjet iic */
	{"HP", "C1790A", "", BLIST_NOLUN},			/* scanjet iip */
	{"HP", "C2500A", "", BLIST_NOLUN},			/* scanjet iicx */
	{"YAMAHA", "CDR100", "1.00", BLIST_NOLUN},		/* Locks up if polled for lun != 0 */
	{"YAMAHA", "CDR102", "1.00", BLIST_NOLUN},		/* Locks up if polled for lun != 0  
								 * extra reset */
	{"RELISYS", "Scorpio", "*", BLIST_NOLUN},		/* responds to all LUN */
	{"MICROTEK", "ScanMaker II", "5.61", BLIST_NOLUN},	/* responds to all LUN */

/*
 * Other types of devices that have special flags.
 */
	{"SONY", "CD-ROM CDU-8001", "*", BLIST_BORKEN},
	{"TEXEL", "CD-ROM", "1.06", BLIST_BORKEN},
	{"IOMEGA", "Io20S         *F", "*", BLIST_KEY},
	{"INSITE", "Floptical   F*8I", "*", BLIST_KEY},
	{"INSITE", "I325VM", "*", BLIST_KEY},
	{"NRC", "MBR-7", "*", BLIST_FORCELUN | BLIST_SINGLELUN},
	{"NRC", "MBR-7.4", "*", BLIST_FORCELUN | BLIST_SINGLELUN},
	{"REGAL", "CDC-4X", "*", BLIST_MAX5LUN | BLIST_SINGLELUN},
	{"NAKAMICH", "MJ-4.8S", "*", BLIST_FORCELUN | BLIST_SINGLELUN},
	{"NAKAMICH", "MJ-5.16S", "*", BLIST_FORCELUN | BLIST_SINGLELUN},
    {"PIONEER", "CD-ROM DRM-600", "*", BLIST_FORCELUN | BLIST_SINGLELUN},
   {"PIONEER", "CD-ROM DRM-602X", "*", BLIST_FORCELUN | BLIST_SINGLELUN},
   {"PIONEER", "CD-ROM DRM-604X", "*", BLIST_FORCELUN | BLIST_SINGLELUN},
	{"EMULEX", "MD21/S2     ESDI", "*", BLIST_SINGLELUN},
	{"CANON", "IPUBJD", "*", BLIST_SPARSELUN},
	{"nCipher", "Fastness Crypto", "*", BLIST_FORCELUN},
	{"NEC", "PD-1 ODX654P", "*", BLIST_FORCELUN | BLIST_SINGLELUN},
	{"MATSHITA", "PD-1", "*", BLIST_FORCELUN | BLIST_SINGLELUN},
	{"iomega", "jaz 1GB", "J.86", BLIST_NOTQ | BLIST_NOLUN},
 	{"CREATIVE","DVD-RAM RAM","*", BLIST_GHOST},
 	{"MATSHITA","PD-2 LF-D100","*", BLIST_GHOST},
 	{"HITACHI", "GF-1050","*", BLIST_GHOST},  /* Hitachi SCSI DVD-RAM */
 	{"TOSHIBA","CDROM","*", BLIST_ISROM},
	{"TOSHIBA","DVD-RAM SD-W1101","*", BLIST_GHOST},
	{"TOSHIBA","DVD-RAM SD-W1111","*", BLIST_GHOST},

	/*
	 * Must be at end of list...
	 */
	{NULL, NULL, NULL}
};

static int get_device_flags(unsigned char *response_data)
{
	int i = 0;
	unsigned char *pnt;
	for (i = 0; 1; i++) {
		if (device_list[i].vendor == NULL)
			return 0;
		pnt = &response_data[8];
		while (*pnt && *pnt == ' ')
			pnt++;
		if (memcmp(device_list[i].vendor, pnt,
			   strlen(device_list[i].vendor)))
			continue;
		pnt = &response_data[16];
		while (*pnt && *pnt == ' ')
			pnt++;
		if (memcmp(device_list[i].model, pnt,
			   strlen(device_list[i].model)))
			continue;
		return device_list[i].flags;
	}
	return 0;
}


static void scan_scsis_done(Scsi_Cmnd * SCpnt)
{

	SCSI_LOG_MLCOMPLETE(1, printk("scan_scsis_done(%p, %06x)\n", SCpnt->host, SCpnt->result));
	SCpnt->request.rq_status = RQ_SCSI_DONE;

	if (SCpnt->request.sem != NULL)
		up(SCpnt->request.sem);
}

#ifdef MODULE
MODULE_PARM(scsi_logging_level, "i");
MODULE_PARM_DESC(scsi_logging_level, "SCSI logging level; should be zero or nonzero");

#else

static int __init scsi_logging_setup(char *str)
{
	int tmp;

	if (get_option(&str, &tmp) == 1) {
		scsi_logging_level = (tmp ? ~0 : 0);
		return 1;
	} else {
		printk("scsi_logging_setup : usage scsi_logging_level=n "
		       "(n should be 0 or non-zero)\n");
		return 0;
	}
}

__setup("scsi_logging=", scsi_logging_setup);

#endif

#ifdef CONFIG_SCSI_MULTI_LUN
static int max_scsi_luns = 8;
#else
static int max_scsi_luns = 1;
#endif

#ifdef MODULE

MODULE_PARM(max_scsi_luns, "i");
MODULE_PARM_DESC(max_scsi_luns, "last scsi LUN (should be between 1 and 8)");

#else

static int __init scsi_luns_setup(char *str)
{
	int tmp;

	if (get_option(&str, &tmp) == 1) {
		max_scsi_luns = tmp;
		return 1;
	} else {
		printk("scsi_luns_setup : usage max_scsi_luns=n "
		       "(n should be between 1 and 8)\n");
		return 0;
	}
}

__setup("max_scsi_luns=", scsi_luns_setup);

#endif

/*
 *	Issue a command and wait for it to complete
 */
 
void scsi_wait_cmd (Scsi_Cmnd * SCpnt, const void *cmnd ,
		  void *buffer, unsigned bufflen, void (*done)(Scsi_Cmnd *),
		  int timeout, int retries)
{
	DECLARE_MUTEX_LOCKED(sem);
	
	SCpnt->request.sem = &sem;
	SCpnt->request.rq_status = RQ_SCSI_BUSY;
	scsi_do_cmd (SCpnt, (void *) cmnd,
		buffer, bufflen, done, timeout, retries);
	down (&sem);
	SCpnt->request.sem = NULL;
}


/*
 *  Detecting SCSI devices :
 *  We scan all present host adapter's busses,  from ID 0 to ID (max_id).
 *  We use the INQUIRY command, determine device type, and pass the ID /
 *  lun address of all sequential devices to the tape driver, all random
 *  devices to the disk driver.
 */
static void scan_scsis(struct Scsi_Host *shpnt,
		       unchar hardcoded,
		       unchar hchannel,
		       unchar hid,
		       unchar hlun)
{
	int channel;
	int dev;
	int lun;
	int max_dev_lun;
	Scsi_Cmnd *SCpnt;
	unsigned char *scsi_result;
	unsigned char scsi_result0[256];
	Scsi_Device *SDpnt;
	Scsi_Device *SDtail;
	int sparse_lun;

	scsi_result = NULL;
	SCpnt = (Scsi_Cmnd *) scsi_init_malloc(sizeof(Scsi_Cmnd),
					       GFP_ATOMIC | GFP_DMA);
	if (SCpnt) {
		SDpnt = (Scsi_Device *) scsi_init_malloc(sizeof(Scsi_Device),
							 GFP_ATOMIC);
		if (SDpnt) {
			/*
			 * Register the queue for the device.  All I/O requests will come
			 * in through here.  We also need to register a pointer to
			 * ourselves, since the queue handler won't know what device
			 * the queue actually represents.   We could look it up, but it
			 * is pointless work.
			 */
			blk_init_queue(&SDpnt->request_queue, scsi_request_fn);
			blk_queue_headactive(&SDpnt->request_queue, 0);
			SDpnt->request_queue.queuedata = (void *) SDpnt;
			/* Make sure we have something that is valid for DMA purposes */
			scsi_result = ((!shpnt->unchecked_isa_dma)
				       ? &scsi_result0[0] : scsi_init_malloc(512, GFP_DMA));
		}
	}
	if (scsi_result == NULL) {
		printk("Unable to obtain scsi_result buffer\n");
		goto leave;
	}
	/*
	 * We must chain ourself in the host_queue, so commands can time out 
	 */
	SCpnt->next = NULL;
	SDpnt->device_queue = SCpnt;
	SDpnt->host = shpnt;
	SDpnt->online = TRUE;

	initialize_merge_fn(SDpnt);

        /*
         * Initialize the object that we will use to wait for command blocks.
         */
	init_waitqueue_head(&SDpnt->scpnt_wait);

	/*
	 * Next, hook the device to the host in question.
	 */
	SDpnt->prev = NULL;
	SDpnt->next = NULL;
	if (shpnt->host_queue != NULL) {
		SDtail = shpnt->host_queue;
		while (SDtail->next != NULL)
			SDtail = SDtail->next;

		SDtail->next = SDpnt;
		SDpnt->prev = SDtail;
	} else {
		shpnt->host_queue = SDpnt;
	}

	/*
	 * We need to increment the counter for this one device so we can track when
	 * things are quiet.
	 */
	atomic_inc(&shpnt->host_active);
	atomic_inc(&SDpnt->device_active);

	if (hardcoded == 1) {
		Scsi_Device *oldSDpnt = SDpnt;
		struct Scsi_Device_Template *sdtpnt;
		channel = hchannel;
		if (channel > shpnt->max_channel)
			goto leave;
		dev = hid;
		if (dev >= shpnt->max_id)
			goto leave;
		lun = hlun;
		if (lun >= shpnt->max_lun)
			goto leave;
		scan_scsis_single(channel, dev, lun, &max_dev_lun, &sparse_lun,
				  &SDpnt, SCpnt, shpnt, scsi_result);
		if (SDpnt != oldSDpnt) {

			/* it could happen the blockdevice hasn't yet been inited */
			for (sdtpnt = scsi_devicelist; sdtpnt; sdtpnt = sdtpnt->next)
				if (sdtpnt->init && sdtpnt->dev_noticed)
					(*sdtpnt->init) ();

			for (sdtpnt = scsi_devicelist; sdtpnt; sdtpnt = sdtpnt->next) {
				if (sdtpnt->attach) {
					(*sdtpnt->attach) (oldSDpnt);
					if (oldSDpnt->attached) {
						scsi_build_commandblocks(oldSDpnt);
						if (0 == oldSDpnt->has_cmdblocks) {
							printk("scan_scsis: DANGER, no command blocks\n");
							/* What to do now ?? */
						}
					}
				}
			}
			resize_dma_pool();

			for (sdtpnt = scsi_devicelist; sdtpnt; sdtpnt = sdtpnt->next) {
				if (sdtpnt->finish && sdtpnt->nr_dev) {
					(*sdtpnt->finish) ();
				}
			}
		}
	} else {
		/* Actual LUN. PC ordering is 0->n IBM/spec ordering is n->0 */
		int order_dev;

		for (channel = 0; channel <= shpnt->max_channel; channel++) {
			for (dev = 0; dev < shpnt->max_id; ++dev) {
				if (shpnt->reverse_ordering)
					/* Shift to scanning 15,14,13... or 7,6,5,4, */
					order_dev = shpnt->max_id - dev - 1;
				else
					order_dev = dev;

				if (shpnt->this_id != order_dev) {

					/*
					 * We need the for so our continue, etc. work fine. We put this in
					 * a variable so that we can override it during the scan if we
					 * detect a device *KNOWN* to have multiple logical units.
					 */
					max_dev_lun = (max_scsi_luns < shpnt->max_lun ?
					 max_scsi_luns : shpnt->max_lun);
					sparse_lun = 0;
					for (lun = 0; lun < max_dev_lun; ++lun) {
						if (!scan_scsis_single(channel, order_dev, lun, &max_dev_lun,
								       &sparse_lun, &SDpnt, SCpnt, shpnt,
							     scsi_result)
						    && !sparse_lun)
							break;	/* break means don't probe further for luns!=0 */
					}	/* for lun ends */
				}	/* if this_id != id ends */
			}	/* for dev ends */
		}		/* for channel ends */
	}			/* if/else hardcoded */

	/*
	 * We need to decrement the counter for this one device
	 * so we know when everything is quiet.
	 */
	atomic_dec(&shpnt->host_active);
	atomic_dec(&SDpnt->device_active);

      leave:

	{			/* Unchain SCpnt from host_queue */
		Scsi_Device *prev, *next;
		Scsi_Device *dqptr;

		for (dqptr = shpnt->host_queue; dqptr != SDpnt; dqptr = dqptr->next)
			continue;
		if (dqptr) {
			prev = dqptr->prev;
			next = dqptr->next;
			if (prev)
				prev->next = next;
			else
				shpnt->host_queue = next;
			if (next)
				next->prev = prev;
		}
	}

	/* Last device block does not exist.  Free memory. */
	if (SDpnt != NULL)
		scsi_init_free((char *) SDpnt, sizeof(Scsi_Device));

	if (SCpnt != NULL)
		scsi_init_free((char *) SCpnt, sizeof(Scsi_Cmnd));

	/* If we allocated a buffer so we could do DMA, free it now */
	if (scsi_result != &scsi_result0[0] && scsi_result != NULL) {
		scsi_init_free(scsi_result, 512);
	} {
		Scsi_Device *sdev;
		Scsi_Cmnd *scmd;

		SCSI_LOG_SCAN_BUS(4, printk("Host status for host %p:\n", shpnt));
		for (sdev = shpnt->host_queue; sdev; sdev = sdev->next) {
			SCSI_LOG_SCAN_BUS(4, printk("Device %d %p: ", sdev->id, sdev));
			for (scmd = sdev->device_queue; scmd; scmd = scmd->next) {
				SCSI_LOG_SCAN_BUS(4, printk("%p ", scmd));
			}
			SCSI_LOG_SCAN_BUS(4, printk("\n"));
		}
	}
}

/*
 * The worker for scan_scsis.
 * Returning 0 means Please don't ask further for lun!=0, 1 means OK go on.
 * Global variables used : scsi_devices(linked list)
 */
int scan_scsis_single(int channel, int dev, int lun, int *max_dev_lun,
	       int *sparse_lun, Scsi_Device ** SDpnt2, Scsi_Cmnd * SCpnt,
		      struct Scsi_Host *shpnt, char *scsi_result)
{
	unsigned char scsi_cmd[12];
	struct Scsi_Device_Template *sdtpnt;
	Scsi_Device *SDtail, *SDpnt = *SDpnt2;
	int bflags, type = -1;
	static int ghost_channel=-1, ghost_dev=-1;
	int org_lun = lun;

	SDpnt->host = shpnt;
	SDpnt->id = dev;
	SDpnt->lun = lun;
	SDpnt->channel = channel;
	SDpnt->online = TRUE;

 
	if ((channel == ghost_channel) && (dev == ghost_dev) && (lun == 1)) {
		SDpnt->lun = 0;
	} else {
		ghost_channel = ghost_dev = -1;
	}
	     

	/* Some low level driver could use device->type (DB) */
	SDpnt->type = -1;

	/*
	 * Assume that the device will have handshaking problems, and then fix this
	 * field later if it turns out it doesn't
	 */
	SDpnt->borken = 1;
	SDpnt->was_reset = 0;
	SDpnt->expecting_cc_ua = 0;
	SDpnt->starved = 0;

	scsi_cmd[0] = TEST_UNIT_READY;
	scsi_cmd[1] = lun << 5;
	scsi_cmd[2] = scsi_cmd[3] = scsi_cmd[4] = scsi_cmd[5] = 0;

	SCpnt->host = SDpnt->host;
	SCpnt->device = SDpnt;
	SCpnt->target = SDpnt->id;
	SCpnt->lun = SDpnt->lun;
	SCpnt->channel = SDpnt->channel;

	scsi_wait_cmd (SCpnt, (void *) scsi_cmd,
	          (void *) NULL,
	          0, scan_scsis_done, SCSI_TIMEOUT + 4 * HZ, 5);

	SCSI_LOG_SCAN_BUS(3, printk("scsi: scan_scsis_single id %d lun %d. Return code 0x%08x\n",
				    dev, lun, SCpnt->result));
	SCSI_LOG_SCAN_BUS(3, print_driverbyte(SCpnt->result));
	SCSI_LOG_SCAN_BUS(3, print_hostbyte(SCpnt->result));
	SCSI_LOG_SCAN_BUS(3, printk("\n"));

	if (SCpnt->result) {
		if (((driver_byte(SCpnt->result) & DRIVER_SENSE) ||
		     (status_byte(SCpnt->result) & CHECK_CONDITION)) &&
		    ((SCpnt->sense_buffer[0] & 0x70) >> 4) == 7) {
			if (((SCpnt->sense_buffer[2] & 0xf) != NOT_READY) &&
			    ((SCpnt->sense_buffer[2] & 0xf) != UNIT_ATTENTION) &&
			    ((SCpnt->sense_buffer[2] & 0xf) != ILLEGAL_REQUEST || lun > 0))
				return 1;
		} else
			return 0;
	}
	SCSI_LOG_SCAN_BUS(3, printk("scsi: performing INQUIRY\n"));
	/*
	 * Build an INQUIRY command block.
	 */
	scsi_cmd[0] = INQUIRY;
	scsi_cmd[1] = (lun << 5) & 0xe0;
	scsi_cmd[2] = 0;
	scsi_cmd[3] = 0;
	scsi_cmd[4] = 255;
	scsi_cmd[5] = 0;
	SCpnt->cmd_len = 0;

	scsi_wait_cmd (SCpnt, (void *) scsi_cmd,
	          (void *) scsi_result,
	          256, scan_scsis_done, SCSI_TIMEOUT, 3);

	SCSI_LOG_SCAN_BUS(3, printk("scsi: INQUIRY %s with code 0x%x\n",
		SCpnt->result ? "failed" : "successful", SCpnt->result));

	if (SCpnt->result)
		return 0;	/* assume no peripheral if any sort of error */

	/*
	 * Check the peripheral qualifier field - this tells us whether LUNS
	 * are supported here or not.
	 */
	if ((scsi_result[0] >> 5) == 3) {
		return 0;	/* assume no peripheral if any sort of error */
	}

	/*
	 * Get any flags for this device.  
	 */
	bflags = get_device_flags (scsi_result);


	 /*   The Toshiba ROM was "gender-changed" here as an inline hack.
	      This is now much more generic.
	      This is a mess: What we really want is to leave the scsi_result
	      alone, and just change the SDpnt structure. And the SDpnt is what
	      we want print_inquiry to print.  -- REW
	 */
	if (bflags & BLIST_ISDISK) {
		scsi_result[0] = TYPE_DISK;                                                
		scsi_result[1] |= 0x80;     /* removable */
	}

	if (bflags & BLIST_ISROM) {
		scsi_result[0] = TYPE_ROM;
		scsi_result[1] |= 0x80;     /* removable */
	}
    
  	if (bflags & BLIST_GHOST) {
		if ((ghost_channel == channel) && (ghost_dev == dev) && (org_lun == 1)) {
			lun=1;
		} else {
			ghost_channel = channel;
			ghost_dev = dev;
			scsi_result[0] = TYPE_MOD;
			scsi_result[1] |= 0x80;     /* removable */
		}
	}
       

	memcpy(SDpnt->vendor, scsi_result + 8, 8);
	memcpy(SDpnt->model, scsi_result + 16, 16);
	memcpy(SDpnt->rev, scsi_result + 32, 4);

	SDpnt->removable = (0x80 & scsi_result[1]) >> 7;
	SDpnt->online = TRUE;
	SDpnt->lockable = SDpnt->removable;
	SDpnt->changed = 0;
	SDpnt->access_count = 0;
	SDpnt->busy = 0;
	SDpnt->has_cmdblocks = 0;
	/*
	 * Currently, all sequential devices are assumed to be tapes, all random
	 * devices disk, with the appropriate read only flags set for ROM / WORM
	 * treated as RO.
	 */
	switch (type = (scsi_result[0] & 0x1f)) {
	case TYPE_TAPE:
	case TYPE_DISK:
	case TYPE_MOD:
	case TYPE_PROCESSOR:
	case TYPE_SCANNER:
	case TYPE_MEDIUM_CHANGER:
	case TYPE_ENCLOSURE:
		SDpnt->writeable = 1;
		break;
	case TYPE_WORM:
	case TYPE_ROM:
		SDpnt->writeable = 0;
		break;
	default:
		printk("scsi: unknown type %d\n", type);
	}

	SDpnt->device_blocked = FALSE;
	SDpnt->device_busy = 0;
	SDpnt->single_lun = 0;
	SDpnt->soft_reset =
	    (scsi_result[7] & 1) && ((scsi_result[3] & 7) == 2);
	SDpnt->random = (type == TYPE_TAPE) ? 0 : 1;
	SDpnt->type = (type & 0x1f);

	print_inquiry(scsi_result);

	for (sdtpnt = scsi_devicelist; sdtpnt;
	     sdtpnt = sdtpnt->next)
		if (sdtpnt->detect)
			SDpnt->attached +=
			    (*sdtpnt->detect) (SDpnt);

	SDpnt->scsi_level = scsi_result[2] & 0x07;
	if (SDpnt->scsi_level >= 2 ||
	    (SDpnt->scsi_level == 1 &&
	     (scsi_result[3] & 0x0f) == 1))
		SDpnt->scsi_level++;

	/*
	 * Accommodate drivers that want to sleep when they should be in a polling
	 * loop.
	 */
	SDpnt->disconnect = 0;


	/*
	 * Set the tagged_queue flag for SCSI-II devices that purport to support
	 * tagged queuing in the INQUIRY data.
	 */
	SDpnt->tagged_queue = 0;
	if ((SDpnt->scsi_level >= SCSI_2) &&
	    (scsi_result[7] & 2) &&
	    !(bflags & BLIST_NOTQ)) {
		SDpnt->tagged_supported = 1;
		SDpnt->current_tag = 0;
	}
	/*
	 * Some revisions of the Texel CD ROM drives have handshaking problems when
	 * used with the Seagate controllers.  Before we know what type of device
	 * we're talking to, we assume it's borken and then change it here if it
	 * turns out that it isn't a TEXEL drive.
	 */
	if ((bflags & BLIST_BORKEN) == 0)
		SDpnt->borken = 0;

	/*
	 * If we want to only allow I/O to one of the luns attached to this device
	 * at a time, then we set this flag.
	 */
	if (bflags & BLIST_SINGLELUN)
		SDpnt->single_lun = 1;

	/*
	 * These devices need this "key" to unlock the devices so we can use it
	 */
	if ((bflags & BLIST_KEY) != 0) {
		printk("Unlocked floptical drive.\n");
		SDpnt->lockable = 0;
		scsi_cmd[0] = MODE_SENSE;
		scsi_cmd[1] = (lun << 5) & 0xe0;
		scsi_cmd[2] = 0x2e;
		scsi_cmd[3] = 0;
		scsi_cmd[4] = 0x2a;
		scsi_cmd[5] = 0;
		SCpnt->cmd_len = 0;
		scsi_wait_cmd (SCpnt, (void *) scsi_cmd,
	        	(void *) scsi_result, 0x2a,
	        	scan_scsis_done, SCSI_TIMEOUT, 3);
	}
	/*
	 * Detach the command from the device. It was just a temporary to be used while
	 * scanning the bus - the real ones will be allocated later.
	 */
	SDpnt->device_queue = NULL;

	/*
	 * This device was already hooked up to the host in question,
	 * so at this point we just let go of it and it should be fine.  We do need to
	 * allocate a new one and attach it to the host so that we can further scan the bus.
	 */
	SDpnt = (Scsi_Device *) scsi_init_malloc(sizeof(Scsi_Device), GFP_ATOMIC);
	*SDpnt2 = SDpnt;
	if (!SDpnt) {
		printk("scsi: scan_scsis_single: Cannot malloc\n");
		return 0;
	}
	/*
	 * Register the queue for the device.  All I/O requests will come
	 * in through here.  We also need to register a pointer to
	 * ourselves, since the queue handler won't know what device
	 * the queue actually represents.   We could look it up, but it
	 * is pointless work.
	 */
	blk_init_queue(&SDpnt->request_queue, scsi_request_fn);
	blk_queue_headactive(&SDpnt->request_queue, 0);
	SDpnt->request_queue.queuedata = (void *) SDpnt;
	SDpnt->host = shpnt;
	initialize_merge_fn(SDpnt);

	/*
	 * And hook up our command block to the new device we will be testing
	 * for.
	 */
	SDpnt->device_queue = SCpnt;
	SDpnt->online = TRUE;

        /*
         * Initialize the object that we will use to wait for command blocks.
         */
	init_waitqueue_head(&SDpnt->scpnt_wait);

	/*
	 * Since we just found one device, there had damn well better be one in the list
	 * already.
	 */
	if (shpnt->host_queue == NULL)
		panic("scan_scsis_single: Host queue == NULL\n");

	SDtail = shpnt->host_queue;
	while (SDtail->next) {
		SDtail = SDtail->next;
	}

	/* Add this device to the linked list at the end */
	SDtail->next = SDpnt;
	SDpnt->prev = SDtail;
	SDpnt->next = NULL;

	/*
	 * Some scsi devices cannot be polled for lun != 0 due to firmware bugs
	 */
	if (bflags & BLIST_NOLUN)
		return 0;	/* break; */

	/*
	 * If this device is known to support sparse multiple units, override the
	 * other settings, and scan all of them.
	 */
	if (bflags & BLIST_SPARSELUN) {
		*max_dev_lun = 8;
		*sparse_lun = 1;
		return 1;
	}
	/*
	 * If this device is known to support multiple units, override the other
	 * settings, and scan all of them.
	 */
	if (bflags & BLIST_FORCELUN) {
		*max_dev_lun = 8;
		return 1;
	}
	/*
	 * REGAL CDC-4X: avoid hang after LUN 4
	 */
	if (bflags & BLIST_MAX5LUN) {
		*max_dev_lun = 5;
		return 1;
	}

	/*
	 * If this device is Ghosted, scan upto two luns. (It physically only
	 * has one). -- REW
	 */
	if (bflags & BLIST_GHOST) {
	        *max_dev_lun = 2;
	        return 1;
	}  


	/*
	 * We assume the device can't handle lun!=0 if: - it reports scsi-0 (ANSI
	 * SCSI Revision 0) (old drives like MAXTOR XT-3280) or - it reports scsi-1
	 * (ANSI SCSI Revision 1) and Response Data Format 0
	 */
	if (((scsi_result[2] & 0x07) == 0)
	    ||
	    ((scsi_result[2] & 0x07) == 1 &&
	     (scsi_result[3] & 0x0f) == 0))
		return 0;
	return 1;
}

/*
 *  Flag bits for the internal_timeout array
 */
#define NORMAL_TIMEOUT 0
#define IN_ABORT  1
#define IN_RESET  2
#define IN_RESET2 4
#define IN_RESET3 8


/*
 * This lock protects the freelist for all devices on the system.
 * We could make this finer grained by having a single lock per
 * device if it is ever found that there is excessive contention
 * on this lock.
 */
static spinlock_t device_request_lock = SPIN_LOCK_UNLOCKED;

/*
 * Used for access to internal allocator used for DMA safe buffers.
 */
static spinlock_t allocator_request_lock = SPIN_LOCK_UNLOCKED;

/*
 * Used to protect insertion into and removal from the queue of
 * commands to be processed by the bottom half handler.
 */
static spinlock_t scsi_bhqueue_lock = SPIN_LOCK_UNLOCKED;

/*
 * Function:    scsi_allocate_device
 *
 * Purpose:     Allocate a command descriptor.
 *
 * Arguments:   device    - device for which we want a command descriptor
 *              wait      - 1 if we should wait in the event that none
 *                          are available.
 *              interruptible - 1 if we should unblock and return NULL
 *                          in the event that we must wait, and a signal
 *                          arrives.
 *
 * Lock status: No locks assumed to be held.  This function is SMP-safe.
 *
 * Returns:     Pointer to command descriptor.
 *
 * Notes:       Prior to the new queue code, this function was not SMP-safe.
 *
 *              If the wait flag is true, and we are waiting for a free
 *              command block, this function will interrupt and return
 *              NULL in the event that a signal arrives that needs to
 *              be handled.
 */

Scsi_Cmnd *scsi_allocate_device(Scsi_Device * device, int wait, 
                                int interruptable)
{
 	struct Scsi_Host *host;
  	Scsi_Cmnd *SCpnt = NULL;
	Scsi_Device *SDpnt;
	unsigned long flags;
  
  	if (!device)
  		panic("No device passed to scsi_allocate_device().\n");
  
  	host = device->host;
  
	spin_lock_irqsave(&device_request_lock, flags);
 
	while (1 == 1) {
		SCpnt = NULL;
		if (!device->device_blocked) {
			if (device->single_lun) {
				/*
				 * FIXME(eric) - this is not at all optimal.  Given that
				 * single lun devices are rare and usually slow
				 * (i.e. CD changers), this is good enough for now, but
				 * we may want to come back and optimize this later.
				 *
				 * Scan through all of the devices attached to this
				 * host, and see if any are active or not.  If so,
				 * we need to defer this command.
				 *
				 * We really need a busy counter per device.  This would
				 * allow us to more easily figure out whether we should
				 * do anything here or not.
				 */
				for (SDpnt = host->host_queue;
				     SDpnt;
				     SDpnt = SDpnt->next) {
					/*
					 * Only look for other devices on the same bus
					 * with the same target ID.
					 */
					if (SDpnt->channel != device->channel
					    || SDpnt->id != device->id
					    || SDpnt == device) {
 						continue;
					}
                                        if( atomic_read(&SDpnt->device_active) != 0)
                                        {
                                                break;
                                        }
				}
				if (SDpnt) {
					/*
					 * Some other device in this cluster is busy.
					 * If asked to wait, we need to wait, otherwise
					 * return NULL.
					 */
					SCpnt = NULL;
					break;
				}
			}
			/*
			 * Now we can check for a free command block for this device.
			 */
			for (SCpnt = device->device_queue; SCpnt; SCpnt = SCpnt->next) {
				if (SCpnt->request.rq_status == RQ_INACTIVE)
					break;
			}
		}
		/*
		 * If we couldn't find a free command block, and we have been
		 * asked to wait, then do so.
		 */
		if (SCpnt) {
			break;
		}
		/*
		 * If we have been asked to wait for a free block, then
		 * wait here.
		 */
		if (wait) {
                        DECLARE_WAITQUEUE(wait, current);

                        /*
                         * We need to wait for a free commandblock.  We need to
                         * insert ourselves into the list before we release the
                         * lock.  This way if a block were released the same
                         * microsecond that we released the lock, the call
                         * to schedule() wouldn't block (well, it might switch,
                         * but the current task will still be schedulable.
                         */
                        add_wait_queue(&device->scpnt_wait, &wait);
                        if( interruptable ) {
                                set_current_state(TASK_INTERRUPTIBLE);
                        } else {
                                set_current_state(TASK_UNINTERRUPTIBLE);
                        }

                        spin_unlock_irqrestore(&device_request_lock, flags);

			/*
			 * This should block until a device command block
			 * becomes available.
			 */
                        schedule();

			spin_lock_irqsave(&device_request_lock, flags);

                        remove_wait_queue(&device->scpnt_wait, &wait);
                        /*
                         * FIXME - Isn't this redundant??  Someone
                         * else will have forced the state back to running.
                         */
                        set_current_state(TASK_RUNNING);
                        /*
                         * In the event that a signal has arrived that we need
                         * to consider, then simply return NULL.  Everyone
                         * that calls us should be prepared for this
                         * possibility, and pass the appropriate code back
                         * to the user.
                         */
                        if( interruptable ) {
                                if (signal_pending(current))
                                        return NULL;
                        }
		} else {
                        spin_unlock_irqrestore(&device_request_lock, flags);
			return NULL;
		}
	}

	SCpnt->request.rq_status = RQ_SCSI_BUSY;
	SCpnt->request.sem = NULL;	/* And no one is waiting for this
					 * to complete */
	atomic_inc(&SCpnt->host->host_active);
	atomic_inc(&SCpnt->device->device_active);

	SCpnt->buffer  = NULL;
	SCpnt->bufflen = 0;
	SCpnt->request_buffer = NULL;
	SCpnt->request_bufflen = 0;

	SCpnt->use_sg = 0;	/* Reset the scatter-gather flag */
	SCpnt->old_use_sg = 0;
	SCpnt->transfersize = 0;	/* No default transfer size */
	SCpnt->cmd_len = 0;

        SCpnt->result = 0;
	SCpnt->underflow = 0;	/* Do not flag underflow conditions */
	SCpnt->resid = 0;
	SCpnt->state = SCSI_STATE_INITIALIZING;
	SCpnt->owner = SCSI_OWNER_HIGHLEVEL;

	spin_unlock_irqrestore(&device_request_lock, flags);

	SCSI_LOG_MLQUEUE(5, printk("Activating command for device %d (%d)\n",
				   SCpnt->target,
				atomic_read(&SCpnt->host->host_active)));

	return SCpnt;
}

/*
 * Function:    scsi_release_command
 *
 * Purpose:     Release a command block.
 *
 * Arguments:   SCpnt - command block we are releasing.
 *
 * Notes:       The command block can no longer be used by the caller once
 *              this funciton is called.  This is in effect the inverse
 *              of scsi_allocate_device.  Note that we also must perform
 *              a couple of additional tasks.  We must first wake up any
 *              processes that might have blocked waiting for a command
 *              block, and secondly we must hit the queue handler function
 *              to make sure that the device is busy.
 *
 *              The idea is that a lot of the mid-level internals gunk
 *              gets hidden in this function.  Upper level drivers don't
 *              have any chickens to wave in the air to get things to
 *              work reliably.
 */
void scsi_release_command(Scsi_Cmnd * SCpnt)
{
	unsigned long flags;
        Scsi_Device * SDpnt;

	spin_lock_irqsave(&device_request_lock, flags);

        SDpnt = SCpnt->device;

	SCpnt->request.rq_status = RQ_INACTIVE;
	SCpnt->state = SCSI_STATE_UNUSED;
	SCpnt->owner = SCSI_OWNER_NOBODY;
	atomic_dec(&SCpnt->host->host_active);
	atomic_dec(&SDpnt->device_active);

	SCSI_LOG_MLQUEUE(5, printk("Deactivating command for device %d (active=%d, failed=%d)\n",
				   SCpnt->target,
				   atomic_read(&SCpnt->host->host_active),
				   SCpnt->host->host_failed));
	if (SCpnt->host->host_failed != 0) {
		SCSI_LOG_ERROR_RECOVERY(5, printk("Error handler thread %d %d\n",
						SCpnt->host->in_recovery,
						SCpnt->host->eh_active));
	}
	/*
	 * If the host is having troubles, then look to see if this was the last
	 * command that might have failed.  If so, wake up the error handler.
	 */
	if (SCpnt->host->in_recovery
	    && !SCpnt->host->eh_active
	    && SCpnt->host->host_busy == SCpnt->host->host_failed) {
		SCSI_LOG_ERROR_RECOVERY(5, printk("Waking error handler thread (%d)\n",
			     atomic_read(&SCpnt->host->eh_wait->count)));
		up(SCpnt->host->eh_wait);
	}

	spin_unlock_irqrestore(&device_request_lock, flags);

        /*
         * Wake up anyone waiting for this device.  Do this after we
         * have released the lock, as they will need it as soon as
         * they wake up.  
         */
	wake_up(&SDpnt->scpnt_wait);

        /*
         * Finally, hit the queue request function to make sure that
         * the device is actually busy if there are requests present.
         * This won't block - if the device cannot take any more, life
         * will go on.  
         */
        {
                request_queue_t *q;

                q = &SDpnt->request_queue;
                scsi_queue_next_request(q, NULL);                
        }
}

/*
 * Function:    scsi_dispatch_command
 *
 * Purpose:     Dispatch a command to the low-level driver.
 *
 * Arguments:   SCpnt - command block we are dispatching.
 *
 * Notes:
 */
int scsi_dispatch_cmd(Scsi_Cmnd * SCpnt)
{
#ifdef DEBUG_DELAY
	unsigned long clock;
#endif
	struct Scsi_Host *host;
	int rtn = 0;
	unsigned long flags;
	unsigned long timeout;

	ASSERT_LOCK(&io_request_lock, 0);

#if DEBUG
	unsigned long *ret = 0;
#ifdef __mips__
	__asm__ __volatile__("move\t%0,$31":"=r"(ret));
#else
	ret = __builtin_return_address(0);
#endif
#endif

	host = SCpnt->host;

	/* Assign a unique nonzero serial_number. */
	if (++serial_number == 0)
		serial_number = 1;
	SCpnt->serial_number = serial_number;

	/*
	 * We will wait MIN_RESET_DELAY clock ticks after the last reset so
	 * we can avoid the drive not being ready.
	 */
	timeout = host->last_reset + MIN_RESET_DELAY;

	if (host->resetting && time_before(jiffies, timeout)) {
		int ticks_remaining = timeout - jiffies;
		/*
		 * NOTE: This may be executed from within an interrupt
		 * handler!  This is bad, but for now, it'll do.  The irq
		 * level of the interrupt handler has been masked out by the
		 * platform dependent interrupt handling code already, so the
		 * sti() here will not cause another call to the SCSI host's
		 * interrupt handler (assuming there is one irq-level per
		 * host).
		 */
		while (--ticks_remaining >= 0)
			mdelay(1 + 999 / HZ);
		host->resetting = 0;
	}
	if (host->hostt->use_new_eh_code) {
		scsi_add_timer(SCpnt, SCpnt->timeout_per_command, scsi_times_out);
	} else {
		scsi_add_timer(SCpnt, SCpnt->timeout_per_command,
			       scsi_old_times_out);
	}

	/*
	 * We will use a queued command if possible, otherwise we will emulate the
	 * queuing and calling of completion function ourselves.
	 */
	SCSI_LOG_MLQUEUE(3, printk("scsi_dispatch_cmnd (host = %d, channel = %d, target = %d, "
	       "command = %p, buffer = %p, \nbufflen = %d, done = %p)\n",
	SCpnt->host->host_no, SCpnt->channel, SCpnt->target, SCpnt->cmnd,
			    SCpnt->buffer, SCpnt->bufflen, SCpnt->done));

	SCpnt->state = SCSI_STATE_QUEUED;
	SCpnt->owner = SCSI_OWNER_LOWLEVEL;
	if (host->can_queue) {
		SCSI_LOG_MLQUEUE(3, printk("queuecommand : routine at %p\n",
					   host->hostt->queuecommand));
		/*
		 * Use the old error handling code if we haven't converted the driver
		 * to use the new one yet.  Note - only the new queuecommand variant
		 * passes a meaningful return value.
		 */
		if (host->hostt->use_new_eh_code) {
                        spin_lock_irqsave(&io_request_lock, flags);
			rtn = host->hostt->queuecommand(SCpnt, scsi_done);
                        spin_unlock_irqrestore(&io_request_lock, flags);
			if (rtn != 0) {
				scsi_delete_timer(SCpnt);
				scsi_mlqueue_insert(SCpnt, SCSI_MLQUEUE_HOST_BUSY);
                                SCSI_LOG_MLQUEUE(3, printk("queuecommand : request rejected\n"));                                
			}
		} else {
                        spin_lock_irqsave(&io_request_lock, flags);
			host->hostt->queuecommand(SCpnt, scsi_old_done);
                        spin_unlock_irqrestore(&io_request_lock, flags);
		}
	} else {
		int temp;

		SCSI_LOG_MLQUEUE(3, printk("command() :  routine at %p\n", host->hostt->command));
                spin_lock_irqsave(&io_request_lock, flags);
		temp = host->hostt->command(SCpnt);
		SCpnt->result = temp;
#ifdef DEBUG_DELAY
                spin_unlock_irqrestore(&io_request_lock, flags);
		clock = jiffies + 4 * HZ;
		while (time_before(jiffies, clock))
			barrier();
		printk("done(host = %d, result = %04x) : routine at %p\n",
		       host->host_no, temp, host->hostt->command);
                spin_lock_irqsave(&io_request_lock, flags);
#endif
		if (host->hostt->use_new_eh_code) {
			scsi_done(SCpnt);
		} else {
			scsi_old_done(SCpnt);
		}
                spin_unlock_irqrestore(&io_request_lock, flags);
	}
	SCSI_LOG_MLQUEUE(3, printk("leaving scsi_dispatch_cmnd()\n"));
	return rtn;
}

/*
 * scsi_do_cmd sends all the commands out to the low-level driver.  It
 * handles the specifics required for each low level driver - ie queued
 * or non queued.  It also prevents conflicts when different high level
 * drivers go for the same host at the same time.
 */

/*
 * Function:    scsi_do_cmd
 *
 * Purpose:     Queue a SCSI command
 *
 * Arguments:   SCpnt     - command descriptor.
 *              cmnd      - actual SCSI command to be performed.
 *              buffer    - data buffer.
 *              bufflen   - size of data buffer.
 *              done      - completion function to be run.
 *              timeout   - how long to let it run before timeout.
 *              retries   - number of retries we allow.
 *
 * Lock status: With the new queueing code, this is SMP-safe, and no locks
 *              need be held upon entry.   The old queueing code the lock was
 *              assumed to be held upon entry.
 *
 * Returns:     Nothing.
 *
 * Notes:       Prior to the new queue code, this function was not SMP-safe.
 *              Also, this function is now only used for queueing requests
 *              for things like ioctls and character device requests - this
 *              is because we essentially just inject a request into the
 *              queue for the device. Normal block device handling manipulates
 *              the queue directly.
 */
void scsi_do_cmd(Scsi_Cmnd * SCpnt, const void *cmnd,
	      void *buffer, unsigned bufflen, void (*done) (Scsi_Cmnd *),
		 int timeout, int retries)
{
	struct Scsi_Host *host = SCpnt->host;

	ASSERT_LOCK(&io_request_lock, 0);

	SCpnt->owner = SCSI_OWNER_MIDLEVEL;

	SCSI_LOG_MLQUEUE(4,
			 {
			 int i;
			 int target = SCpnt->target;
			 printk("scsi_do_cmd (host = %d, channel = %d target = %d, "
		    "buffer =%p, bufflen = %d, done = %p, timeout = %d, "
				"retries = %d)\n"
				"command : ", host->host_no, SCpnt->channel, target, buffer,
				bufflen, done, timeout, retries);
			 for (i = 0; i < 10; ++i)
			 printk("%02x  ", ((unsigned char *) cmnd)[i]);
			 printk("\n");
			 });

	if (!host) {
		panic("Invalid or not present host.\n");
	}
	/*
	 * We must prevent reentrancy to the lowlevel host driver.  This prevents
	 * it - we enter a loop until the host we want to talk to is not busy.
	 * Race conditions are prevented, as interrupts are disabled in between the
	 * time we check for the host being not busy, and the time we mark it busy
	 * ourselves.
	 */


	/*
	 * Our own function scsi_done (which marks the host as not busy, disables
	 * the timeout counter, etc) will be called by us or by the
	 * scsi_hosts[host].queuecommand() function needs to also call
	 * the completion function for the high level driver.
	 */

	memcpy((void *) SCpnt->data_cmnd, (const void *) cmnd, 12);
	SCpnt->reset_chain = NULL;
	SCpnt->serial_number = 0;
	SCpnt->serial_number_at_timeout = 0;
	SCpnt->bufflen = bufflen;
	SCpnt->buffer = buffer;
	SCpnt->flags = 0;
	SCpnt->retries = 0;
	SCpnt->allowed = retries;
	SCpnt->done = done;
	SCpnt->timeout_per_command = timeout;

	memcpy((void *) SCpnt->cmnd, (const void *) cmnd, 12);
	/* Zero the sense buffer.  Some host adapters automatically request
	 * sense on error.  0 is not a valid sense code.
	 */
	memset((void *) SCpnt->sense_buffer, 0, sizeof SCpnt->sense_buffer);
	SCpnt->request_buffer = buffer;
	SCpnt->request_bufflen = bufflen;
	SCpnt->old_use_sg = SCpnt->use_sg;
	if (SCpnt->cmd_len == 0)
		SCpnt->cmd_len = COMMAND_SIZE(SCpnt->cmnd[0]);
	SCpnt->old_cmd_len = SCpnt->cmd_len;

	/* Start the timer ticking.  */

	SCpnt->internal_timeout = NORMAL_TIMEOUT;
	SCpnt->abort_reason = 0;
	SCpnt->result = 0;

	/*
	 * At this point, we merely set up the command, stick it in the normal
	 * request queue, and return.  Eventually that request will come to the
	 * top of the list, and will be dispatched.
	 */
	scsi_insert_special_cmd(SCpnt, 0);

	SCSI_LOG_MLQUEUE(3, printk("Leaving scsi_do_cmd()\n"));
}

/*
 * This function is the mid-level interrupt routine, which decides how
 *  to handle error conditions.  Each invocation of this function must
 *  do one and *only* one of the following:
 *
 *      1) Insert command in BH queue.
 *      2) Activate error handler for host.
 *
 * FIXME(eric) - I am concerned about stack overflow (still).  An
 * interrupt could come while we are processing the bottom queue,
 * which would cause another command to be stuffed onto the bottom
 * queue, and it would in turn be processed as that interrupt handler
 * is returning.  Given a sufficiently steady rate of returning
 * commands, this could cause the stack to overflow.  I am not sure
 * what is the most appropriate solution here - we should probably
 * keep a depth count, and not process any commands while we still
 * have a bottom handler active higher in the stack.
 *
 * There is currently code in the bottom half handler to monitor
 * recursion in the bottom handler and report if it ever happens.  If
 * this becomes a problem, it won't be hard to engineer something to
 * deal with it so that only the outer layer ever does any real
 * processing.  
 */
void scsi_done(Scsi_Cmnd * SCpnt)
{
	unsigned long flags;
	int tstatus;

	/*
	 * We don't have to worry about this one timing out any more.
	 */
	tstatus = scsi_delete_timer(SCpnt);

	/*
	 * If we are unable to remove the timer, it means that the command
	 * has already timed out.  In this case, we have no choice but to
	 * let the timeout function run, as we have no idea where in fact
	 * that function could really be.  It might be on another processor,
	 * etc, etc.
	 */
	if (!tstatus) {
		SCpnt->done_late = 1;
		return;
	}
	/* Set the serial numbers back to zero */
	SCpnt->serial_number = 0;

	/*
	 * First, see whether this command already timed out.  If so, we ignore
	 * the response.  We treat it as if the command never finished.
	 *
	 * Since serial_number is now 0, the error handler cound detect this
	 * situation and avoid to call the the low level driver abort routine.
	 * (DB)
         *
         * FIXME(eric) - I believe that this test is now redundant, due to
         * the test of the return status of del_timer().
	 */
	if (SCpnt->state == SCSI_STATE_TIMEOUT) {
		SCSI_LOG_MLCOMPLETE(1, printk("Ignoring completion of %p due to timeout status", SCpnt));
		return;
	}
	spin_lock_irqsave(&scsi_bhqueue_lock, flags);

	SCpnt->serial_number_at_timeout = 0;
	SCpnt->state = SCSI_STATE_BHQUEUE;
	SCpnt->owner = SCSI_OWNER_BH_HANDLER;
	SCpnt->bh_next = NULL;

	/*
	 * Next, put this command in the BH queue.
	 * 
	 * We need a spinlock here, or compare and exchange if we can reorder incoming
	 * Scsi_Cmnds, as it happens pretty often scsi_done is called multiple times
	 * before bh is serviced. -jj
	 *
	 * We already have the io_request_lock here, since we are called from the
	 * interrupt handler or the error handler. (DB)
	 *
	 * This may be true at the moment, but I would like to wean all of the low
	 * level drivers away from using io_request_lock.   Technically they should
	 * all use their own locking.  I am adding a small spinlock to protect
	 * this datastructure to make it safe for that day.  (ERY)
	 */
	if (!scsi_bh_queue_head) {
		scsi_bh_queue_head = SCpnt;
		scsi_bh_queue_tail = SCpnt;
	} else {
		scsi_bh_queue_tail->bh_next = SCpnt;
		scsi_bh_queue_tail = SCpnt;
	}

	spin_unlock_irqrestore(&scsi_bhqueue_lock, flags);
	/*
	 * Mark the bottom half handler to be run.
	 */
	mark_bh(SCSI_BH);
}

/*
 * Procedure:   scsi_bottom_half_handler
 *
 * Purpose:     Called after we have finished processing interrupts, it
 *              performs post-interrupt handling for commands that may
 *              have completed.
 *
 * Notes:       This is called with all interrupts enabled.  This should reduce
 *              interrupt latency, stack depth, and reentrancy of the low-level
 *              drivers.
 *
 * The io_request_lock is required in all the routine. There was a subtle
 * race condition when scsi_done is called after a command has already
 * timed out but before the time out is processed by the error handler.
 * (DB)
 *
 * I believe I have corrected this.  We simply monitor the return status of
 * del_timer() - if this comes back as 0, it means that the timer has fired
 * and that a timeout is in progress.   I have modified scsi_done() such
 * that in this instance the command is never inserted in the bottom
 * half queue.  Thus the only time we hold the lock here is when
 * we wish to atomically remove the contents of the queue.
 */
void scsi_bottom_half_handler(void)
{
	Scsi_Cmnd *SCpnt;
	Scsi_Cmnd *SCnext;
	unsigned long flags;


	while (1 == 1) {
		spin_lock_irqsave(&scsi_bhqueue_lock, flags);
		SCpnt = scsi_bh_queue_head;
		scsi_bh_queue_head = NULL;
		spin_unlock_irqrestore(&scsi_bhqueue_lock, flags);

		if (SCpnt == NULL) {
			return;
		}
		SCnext = SCpnt->bh_next;

		for (; SCpnt; SCpnt = SCnext) {
			SCnext = SCpnt->bh_next;

			switch (scsi_decide_disposition(SCpnt)) {
			case SUCCESS:
				/*
				 * Add to BH queue.
				 */
				SCSI_LOG_MLCOMPLETE(3, printk("Command finished %d %d 0x%x\n", SCpnt->host->host_busy,
						SCpnt->host->host_failed,
							 SCpnt->result));

				scsi_finish_command(SCpnt);
				break;
			case NEEDS_RETRY:
				/*
				 * We only come in here if we want to retry a command.  The
				 * test to see whether the command should be retried should be
				 * keeping track of the number of tries, so we don't end up looping,
				 * of course.
				 */
				SCSI_LOG_MLCOMPLETE(3, printk("Command needs retry %d %d 0x%x\n", SCpnt->host->host_busy,
				SCpnt->host->host_failed, SCpnt->result));

				scsi_retry_command(SCpnt);
				break;
			case ADD_TO_MLQUEUE:
				/* 
				 * This typically happens for a QUEUE_FULL message -
				 * typically only when the queue depth is only
				 * approximate for a given device.  Adding a command
				 * to the queue for the device will prevent further commands
				 * from being sent to the device, so we shouldn't end up
				 * with tons of things being sent down that shouldn't be.
				 */
				SCSI_LOG_MLCOMPLETE(3, printk("Command rejected as device queue full, put on ml queue %p\n",
                                                              SCpnt));
				scsi_mlqueue_insert(SCpnt, SCSI_MLQUEUE_DEVICE_BUSY);
				break;
			default:
				/*
				 * Here we have a fatal error of some sort.  Turn it over to
				 * the error handler.
				 */
				SCSI_LOG_MLCOMPLETE(3, printk("Command failed %p %x active=%d busy=%d failed=%d\n",
						    SCpnt, SCpnt->result,
				  atomic_read(&SCpnt->host->host_active),
						  SCpnt->host->host_busy,
					      SCpnt->host->host_failed));

				/*
				 * Dump the sense information too.
				 */
				if ((status_byte(SCpnt->result) & CHECK_CONDITION) != 0) {
					SCSI_LOG_MLCOMPLETE(3, print_sense("bh", SCpnt));
				}
				if (SCpnt->host->eh_wait != NULL) {
					SCpnt->host->host_failed++;
					SCpnt->owner = SCSI_OWNER_ERROR_HANDLER;
					SCpnt->state = SCSI_STATE_FAILED;
					SCpnt->host->in_recovery = 1;
					/*
					 * If the host is having troubles, then look to see if this was the last
					 * command that might have failed.  If so, wake up the error handler.
					 */
					if (SCpnt->host->host_busy == SCpnt->host->host_failed) {
						SCSI_LOG_ERROR_RECOVERY(5, printk("Waking error handler thread (%d)\n",
										  atomic_read(&SCpnt->host->eh_wait->count)));
						up(SCpnt->host->eh_wait);
					}
				} else {
					/*
					 * We only get here if the error recovery thread has died.
					 */
					scsi_finish_command(SCpnt);
				}
			}
		}		/* for(; SCpnt...) */

	}			/* while(1==1) */

}

/*
 * Function:    scsi_retry_command
 *
 * Purpose:     Send a command back to the low level to be retried.
 *
 * Notes:       This command is always executed in the context of the
 *              bottom half handler, or the error handler thread. Low
 *              level drivers should not become re-entrant as a result of
 *              this.
 */
int scsi_retry_command(Scsi_Cmnd * SCpnt)
{
	memcpy((void *) SCpnt->cmnd, (void *) SCpnt->data_cmnd,
	       sizeof(SCpnt->data_cmnd));
	SCpnt->request_buffer = SCpnt->buffer;
	SCpnt->request_bufflen = SCpnt->bufflen;
	SCpnt->use_sg = SCpnt->old_use_sg;
	SCpnt->cmd_len = SCpnt->old_cmd_len;

        /*
         * Zero the sense information from the last time we tried
         * this command.
         */
	memset((void *) SCpnt->sense_buffer, 0, sizeof SCpnt->sense_buffer);

	return scsi_dispatch_cmd(SCpnt);
}

/*
 * Function:    scsi_finish_command
 *
 * Purpose:     Pass command off to upper layer for finishing of I/O
 *              request, waking processes that are waiting on results,
 *              etc.
 */
void scsi_finish_command(Scsi_Cmnd * SCpnt)
{
	struct Scsi_Host *host;
	Scsi_Device *device;

	ASSERT_LOCK(&io_request_lock, 0);

	host = SCpnt->host;
	device = SCpnt->device;

	host->host_busy--;	/* Indicate that we are free */
	device->device_busy--;	/* Decrement device usage counter. */

        /*
         * Clear the flags which say that the device/host is no longer
         * capable of accepting new commands.  These are set in scsi_queue.c
         * for both the queue full condition on a device, and for a
         * host full condition on the host.
         */
        host->host_blocked = FALSE;
        device->device_blocked = FALSE;

	/*
	 * If we have valid sense information, then some kind of recovery
	 * must have taken place.  Make a note of this.
	 */
	if (scsi_sense_valid(SCpnt)) {
		SCpnt->result |= (DRIVER_SENSE << 24);
	}
	SCSI_LOG_MLCOMPLETE(3, printk("Notifying upper driver of completion for device %d %x\n",
				      SCpnt->device->id, SCpnt->result));

	SCpnt->owner = SCSI_OWNER_HIGHLEVEL;
	SCpnt->state = SCSI_STATE_FINISHED;

	/* We can get here with use_sg=0, causing a panic in the upper level (DB) */
	SCpnt->use_sg = SCpnt->old_use_sg;

	SCpnt->done(SCpnt);
}

#ifdef CONFIG_MODULES
static int scsi_register_host(Scsi_Host_Template *);
static void scsi_unregister_host(Scsi_Host_Template *);
#endif

/*
 * Function:    scsi_malloc
 *
 * Purpose:     Allocate memory from the DMA-safe pool.
 *
 * Arguments:   len       - amount of memory we need.
 *
 * Lock status: No locks assumed to be held.  This function is SMP-safe.
 *
 * Returns:     Pointer to memory block.
 *
 * Notes:       Prior to the new queue code, this function was not SMP-safe.
 *              This function can only allocate in units of sectors
 *              (i.e. 512 bytes).
 *
 *              We cannot use the normal system allocator becuase we need
 *              to be able to guarantee that we can process a complete disk
 *              I/O request without touching the system allocator.  Think
 *              about it - if the system were heavily swapping, and tried to
 *              write out a block of memory to disk, and the SCSI code needed
 *              to allocate more memory in order to be able to write the
 *              data to disk, you would wedge the system.
 */
void *scsi_malloc(unsigned int len)
{
	unsigned int nbits, mask;
	unsigned long flags;

	int i, j;
	if (len % SECTOR_SIZE != 0 || len > PAGE_SIZE)
		return NULL;

	nbits = len >> 9;
	mask = (1 << nbits) - 1;

	spin_lock_irqsave(&allocator_request_lock, flags);

	for (i = 0; i < dma_sectors / SECTORS_PER_PAGE; i++)
		for (j = 0; j <= SECTORS_PER_PAGE - nbits; j++) {
			if ((dma_malloc_freelist[i] & (mask << j)) == 0) {
				dma_malloc_freelist[i] |= (mask << j);
				scsi_dma_free_sectors -= nbits;
#ifdef DEBUG
				SCSI_LOG_MLQUEUE(3, printk("SMalloc: %d %p [From:%p]\n", len, dma_malloc_pages[i] + (j << 9)));
				printk("SMalloc: %d %p [From:%p]\n", len, dma_malloc_pages[i] + (j << 9));
#endif
				spin_unlock_irqrestore(&allocator_request_lock, flags);
				return (void *) ((unsigned long) dma_malloc_pages[i] + (j << 9));
			}
		}
	spin_unlock_irqrestore(&allocator_request_lock, flags);
	return NULL;		/* Nope.  No more */
}

/*
 * Function:    scsi_free
 *
 * Purpose:     Free memory into the DMA-safe pool.
 *
 * Arguments:   ptr       - data block we are freeing.
 *              len       - size of block we are freeing.
 *
 * Lock status: No locks assumed to be held.  This function is SMP-safe.
 *
 * Returns:     Nothing
 *
 * Notes:       This function *must* only be used to free memory
 *              allocated from scsi_malloc().
 *
 *              Prior to the new queue code, this function was not SMP-safe.
 *              This function can only allocate in units of sectors
 *              (i.e. 512 bytes).
 */
int scsi_free(void *obj, unsigned int len)
{
	unsigned int page, sector, nbits, mask;
	unsigned long flags;

#ifdef DEBUG
	unsigned long ret = 0;

#ifdef __mips__
	__asm__ __volatile__("move\t%0,$31":"=r"(ret));
#else
	ret = __builtin_return_address(0);
#endif
	printk("scsi_free %p %d\n", obj, len);
	SCSI_LOG_MLQUEUE(3, printk("SFree: %p %d\n", obj, len));
#endif

	spin_lock_irqsave(&allocator_request_lock, flags);

	for (page = 0; page < dma_sectors / SECTORS_PER_PAGE; page++) {
		unsigned long page_addr = (unsigned long) dma_malloc_pages[page];
		if ((unsigned long) obj >= page_addr &&
		    (unsigned long) obj < page_addr + PAGE_SIZE) {
			sector = (((unsigned long) obj) - page_addr) >> 9;

			nbits = len >> 9;
			mask = (1 << nbits) - 1;

			if ((mask << sector) >= (1 << SECTORS_PER_PAGE))
				panic("scsi_free:Bad memory alignment");

			if ((dma_malloc_freelist[page] &
			     (mask << sector)) != (mask << sector)) {
#ifdef DEBUG
				printk("scsi_free(obj=%p, len=%d) called from %08lx\n",
				       obj, len, ret);
#endif
				panic("scsi_free:Trying to free unused memory");
			}
			scsi_dma_free_sectors += nbits;
			dma_malloc_freelist[page] &= ~(mask << sector);
			spin_unlock_irqrestore(&allocator_request_lock, flags);
			return 0;
		}
	}
	panic("scsi_free:Bad offset");
}


int scsi_loadable_module_flag;	/* Set after we scan builtin drivers */

void *scsi_init_malloc(unsigned int size, int gfp_mask)
{
	void *retval;

	/*
	 * For buffers used by the DMA pool, we assume page aligned 
	 * structures.
	 */
	if ((size % PAGE_SIZE) == 0) {
		int order, a_size;
		for (order = 0, a_size = PAGE_SIZE;
		     a_size < size; order++, a_size <<= 1);
		retval = (void *) __get_free_pages(gfp_mask | GFP_DMA, order);
	} else
		retval = kmalloc(size, gfp_mask);

	if (retval)
		memset(retval, 0, size);
	return retval;
}


void scsi_init_free(char *ptr, unsigned int size)
{
	/*
	 * We need this special code here because the DMA pool assumes
	 * page aligned data.  Besides, it is wasteful to allocate
	 * page sized chunks with kmalloc.
	 */
	if ((size % PAGE_SIZE) == 0) {
		int order, a_size;

		for (order = 0, a_size = PAGE_SIZE;
		     a_size < size; order++, a_size <<= 1);
		free_pages((unsigned long) ptr, order);
	} else
		kfree(ptr);
}

void scsi_build_commandblocks(Scsi_Device * SDpnt)
{
	unsigned long flags;
	struct Scsi_Host *host = SDpnt->host;
	int j;
	Scsi_Cmnd *SCpnt;

	spin_lock_irqsave(&device_request_lock, flags);

	if (SDpnt->queue_depth == 0)
		SDpnt->queue_depth = host->cmd_per_lun;
	SDpnt->device_queue = NULL;

	for (j = 0; j < SDpnt->queue_depth; j++) {
		SCpnt = (Scsi_Cmnd *)
		    scsi_init_malloc(sizeof(Scsi_Cmnd),
				     GFP_ATOMIC |
				(host->unchecked_isa_dma ? GFP_DMA : 0));
		if (NULL == SCpnt)
			break;	/* If not, the next line will oops ... */
		memset(&SCpnt->eh_timeout, 0, sizeof(SCpnt->eh_timeout));
		SCpnt->host = host;
		SCpnt->device = SDpnt;
		SCpnt->target = SDpnt->id;
		SCpnt->lun = SDpnt->lun;
		SCpnt->channel = SDpnt->channel;
		SCpnt->request.rq_status = RQ_INACTIVE;
		SCpnt->use_sg = 0;
		SCpnt->old_use_sg = 0;
		SCpnt->old_cmd_len = 0;
		SCpnt->underflow = 0;
		SCpnt->transfersize = 0;
		SCpnt->resid = 0;
		SCpnt->serial_number = 0;
		SCpnt->serial_number_at_timeout = 0;
		SCpnt->host_scribble = NULL;
		SCpnt->next = SDpnt->device_queue;
		SDpnt->device_queue = SCpnt;
		SCpnt->state = SCSI_STATE_UNUSED;
		SCpnt->owner = SCSI_OWNER_NOBODY;
	}
	if (j < SDpnt->queue_depth) {	/* low on space (D.Gilbert 990424) */
		printk("scsi_build_commandblocks: want=%d, space for=%d blocks\n",
		       SDpnt->queue_depth, j);
		SDpnt->queue_depth = j;
		SDpnt->has_cmdblocks = (0 != j);
	} else {
		SDpnt->has_cmdblocks = 1;
	}
	spin_unlock_irqrestore(&device_request_lock, flags);
}

static int proc_scsi_gen_write(struct file * file, const char * buf,
                              unsigned long length, void *data);

#ifndef MODULE			/* { */
/*
 * scsi_dev_init() is our initialization routine, which in turn calls host
 * initialization, bus scanning, and sd/st initialization routines.
 * This is only used at boot time.
 */
int __init scsi_dev_init(void)
{
	Scsi_Device *SDpnt;
	struct Scsi_Host *shpnt;
	struct Scsi_Device_Template *sdtpnt;
	struct proc_dir_entry *generic;
#ifdef FOO_ON_YOU
	return;
#endif

	/* Yes we're here... */

	/*
	 * This makes /proc/scsi and /proc/scsi/scsi visible.
	 */
#ifdef CONFIG_PROC_FS
	proc_scsi = proc_mkdir("scsi", 0);
	if (!proc_scsi) {
		printk (KERN_ERR "cannot init /proc/scsi\n");
		return -ENOMEM;
	}
	
	generic = create_proc_info_entry ("scsi/scsi", 0, 0, scsi_proc_info);
	if (!generic) {
		printk (KERN_ERR "cannot init /proc/scsi/scsi\n");
		remove_proc_entry("scsi", 0);
		return -ENOMEM;
	}
	generic->write_proc = proc_scsi_gen_write;
#endif

	/* Init a few things so we can "malloc" memory. */
	scsi_loadable_module_flag = 0;

	/* initialize all hosts */
	scsi_init();

	/*
	 * This is where the processing takes place for most everything
	 * when commands are completed.  Until we do this, we will not be able
	 * to queue any commands.
	 */
	init_bh(SCSI_BH, scsi_bottom_half_handler);

	for (shpnt = scsi_hostlist; shpnt; shpnt = shpnt->next) {
		scan_scsis(shpnt, 0, 0, 0, 0);	/* scan for scsi devices */
		if (shpnt->select_queue_depths != NULL)
			(shpnt->select_queue_depths) (shpnt, shpnt->host_queue);
	}

	printk("scsi : detected ");
	for (sdtpnt = scsi_devicelist; sdtpnt; sdtpnt = sdtpnt->next)
		if (sdtpnt->dev_noticed && sdtpnt->name)
			printk("%d SCSI %s%s ", sdtpnt->dev_noticed, sdtpnt->name,
			       (sdtpnt->dev_noticed != 1) ? "s" : "");
	printk("total.\n");

	for (sdtpnt = scsi_devicelist; sdtpnt; sdtpnt = sdtpnt->next)
		if (sdtpnt->init && sdtpnt->dev_noticed)
			(*sdtpnt->init) ();

	for (shpnt = scsi_hostlist; shpnt; shpnt = shpnt->next) {
		for (SDpnt = shpnt->host_queue; SDpnt; SDpnt = SDpnt->next) {
			/* SDpnt->scsi_request_fn = NULL; */
			for (sdtpnt = scsi_devicelist; sdtpnt; sdtpnt = sdtpnt->next)
				if (sdtpnt->attach)
					(*sdtpnt->attach) (SDpnt);
			if (SDpnt->attached) {
				scsi_build_commandblocks(SDpnt);
				if (0 == SDpnt->has_cmdblocks) {
					printk("scsi_dev_init: DANGER, no command blocks\n");
					/* What to do now ?? */
				}
			}
		}
	}

	/*
	 * This should build the DMA pool.
	 */
	resize_dma_pool();

	/*
	 * OK, now we finish the initialization by doing spin-up, read
	 * capacity, etc, etc
	 */
	for (sdtpnt = scsi_devicelist; sdtpnt; sdtpnt = sdtpnt->next)
		if (sdtpnt->finish && sdtpnt->nr_dev)
			(*sdtpnt->finish) ();

	scsi_loadable_module_flag = 1;

	return 0;
}
#endif	/* MODULE */		/* } */

static void print_inquiry(unsigned char *data)
{
	int i;

	printk("  Vendor: ");
	for (i = 8; i < 16; i++) {
		if (data[i] >= 0x20 && i < data[4] + 5)
			printk("%c", data[i]);
		else
			printk(" ");
	}

	printk("  Model: ");
	for (i = 16; i < 32; i++) {
		if (data[i] >= 0x20 && i < data[4] + 5)
			printk("%c", data[i]);
		else
			printk(" ");
	}

	printk("  Rev: ");
	for (i = 32; i < 36; i++) {
		if (data[i] >= 0x20 && i < data[4] + 5)
			printk("%c", data[i]);
		else
			printk(" ");
	}

	printk("\n");

	i = data[0] & 0x1f;

	printk("  Type:   %s ",
	       i < MAX_SCSI_DEVICE_CODE ? scsi_device_types[i] : "Unknown          ");
	printk("                 ANSI SCSI revision: %02x", data[2] & 0x07);
	if ((data[2] & 0x07) == 1 && (data[3] & 0x0f) == 1)
		printk(" CCS\n");
	else
		printk("\n");
}

#ifdef CONFIG_PROC_FS
static int scsi_proc_info(char *buffer, char **start, off_t offset, int length)
{
	Scsi_Device *scd;
	struct Scsi_Host *HBA_ptr;
	int size, len = 0;
	off_t begin = 0;
	off_t pos = 0;

	/*
	 * First, see if there are any attached devices or not.
	 */
	for (HBA_ptr = scsi_hostlist; HBA_ptr; HBA_ptr = HBA_ptr->next) {
		if (HBA_ptr->host_queue != NULL) {
			break;
		}
	}
	size = sprintf(buffer + len, "Attached devices: %s\n", (HBA_ptr) ? "" : "none");
	len += size;
	pos = begin + len;
	for (HBA_ptr = scsi_hostlist; HBA_ptr; HBA_ptr = HBA_ptr->next) {
#if 0
		size += sprintf(buffer + len, "scsi%2d: %s\n", (int) HBA_ptr->host_no,
				HBA_ptr->hostt->procname);
		len += size;
		pos = begin + len;
#endif
		for (scd = HBA_ptr->host_queue; scd; scd = scd->next) {
			proc_print_scsidevice(scd, buffer, &size, len);
			len += size;
			pos = begin + len;

			if (pos < offset) {
				len = 0;
				begin = pos;
			}
			if (pos > offset + length)
				goto stop_output;
		}
	}

stop_output:
	*start = buffer + (offset - begin);	/* Start of wanted data */
	len -= (offset - begin);	/* Start slop */
	if (len > length)
		len = length;	/* Ending slop */
	return (len);
}

static int proc_scsi_gen_write(struct file * file, const char * buf,
                              unsigned long length, void *data)
{
	Scsi_Cmnd *SCpnt;
	struct Scsi_Device_Template *SDTpnt;
	Scsi_Device *scd;
	struct Scsi_Host *HBA_ptr;
	char *p;
	int host, channel, id, lun;
	char * buffer;
	int err;

	if (!buf || length>PAGE_SIZE)
		return -EINVAL;

	if (!(buffer = (char *) __get_free_page(GFP_KERNEL)))
		return -ENOMEM;
	copy_from_user(buffer, buf, length);

	err = -EINVAL;
	if (length < 11 || strncmp("scsi", buffer, 4))
		goto out;

	/*
	 * Usage: echo "scsi dump #N" > /proc/scsi/scsi
	 * to dump status of all scsi commands.  The number is used to specify the level
	 * of detail in the dump.
	 */
	if (!strncmp("dump", buffer + 5, 4)) {
		unsigned int level;

		p = buffer + 10;

		if (*p == '\0')
			goto out;

		level = simple_strtoul(p, NULL, 0);
		scsi_dump_status(level);
	}
	/*
	 * Usage: echo "scsi log token #N" > /proc/scsi/scsi
	 * where token is one of [error,scan,mlqueue,mlcomplete,llqueue,
	 * llcomplete,hlqueue,hlcomplete]
	 */
#ifdef CONFIG_SCSI_LOGGING		/* { */

	if (!strncmp("log", buffer + 5, 3)) {
		char *token;
		unsigned int level;

		p = buffer + 9;
		token = p;
		while (*p != ' ' && *p != '\t' && *p != '\0') {
			p++;
		}

		if (*p == '\0') {
			if (strncmp(token, "all", 3) == 0) {
				/*
				 * Turn on absolutely everything.
				 */
				scsi_logging_level = ~0;
			} else if (strncmp(token, "none", 4) == 0) {
				/*
				 * Turn off absolutely everything.
				 */
				scsi_logging_level = 0;
			} else {
				goto out;
			}
		} else {
			*p++ = '\0';

			level = simple_strtoul(p, NULL, 0);

			/*
			 * Now figure out what to do with it.
			 */
			if (strcmp(token, "error") == 0) {
				SCSI_SET_ERROR_RECOVERY_LOGGING(level);
			} else if (strcmp(token, "timeout") == 0) {
				SCSI_SET_TIMEOUT_LOGGING(level);
			} else if (strcmp(token, "scan") == 0) {
				SCSI_SET_SCAN_BUS_LOGGING(level);
			} else if (strcmp(token, "mlqueue") == 0) {
				SCSI_SET_MLQUEUE_LOGGING(level);
			} else if (strcmp(token, "mlcomplete") == 0) {
				SCSI_SET_MLCOMPLETE_LOGGING(level);
			} else if (strcmp(token, "llqueue") == 0) {
				SCSI_SET_LLQUEUE_LOGGING(level);
			} else if (strcmp(token, "llcomplete") == 0) {
				SCSI_SET_LLCOMPLETE_LOGGING(level);
			} else if (strcmp(token, "hlqueue") == 0) {
				SCSI_SET_HLQUEUE_LOGGING(level);
			} else if (strcmp(token, "hlcomplete") == 0) {
				SCSI_SET_HLCOMPLETE_LOGGING(level);
			} else if (strcmp(token, "ioctl") == 0) {
				SCSI_SET_IOCTL_LOGGING(level);
			} else {
				goto out;
			}
		}

		printk("scsi logging level set to 0x%8.8x\n", scsi_logging_level);
	}
#endif	/* CONFIG_SCSI_LOGGING */ /* } */

	/*
	 * Usage: echo "scsi add-single-device 0 1 2 3" >/proc/scsi/scsi
	 * with  "0 1 2 3" replaced by your "Host Channel Id Lun".
	 * Consider this feature BETA.
	 *     CAUTION: This is not for hotplugging your peripherals. As
	 *     SCSI was not designed for this you could damage your
	 *     hardware !
	 * However perhaps it is legal to switch on an
	 * already connected device. It is perhaps not
	 * guaranteed this device doesn't corrupt an ongoing data transfer.
	 */
	if (!strncmp("add-single-device", buffer + 5, 17)) {
		p = buffer + 23;

		host = simple_strtoul(p, &p, 0);
		channel = simple_strtoul(p + 1, &p, 0);
		id = simple_strtoul(p + 1, &p, 0);
		lun = simple_strtoul(p + 1, &p, 0);

		printk("scsi singledevice %d %d %d %d\n", host, channel,
		       id, lun);

		for (HBA_ptr = scsi_hostlist; HBA_ptr; HBA_ptr = HBA_ptr->next) {
			if (HBA_ptr->host_no == host) {
				break;
			}
		}
		err = -ENXIO;
		if (!HBA_ptr)
			goto out;

		for (scd = HBA_ptr->host_queue; scd; scd = scd->next) {
			if ((scd->channel == channel
			     && scd->id == id
			     && scd->lun == lun)) {
				break;
			}
		}

		err = -ENOSYS;
		if (scd)
			goto out;	/* We do not yet support unplugging */

		scan_scsis(HBA_ptr, 1, channel, id, lun);

		/* FIXME (DB) This assumes that the queue_depth routines can be used
		   in this context as well, while they were all designed to be
		   called only once after the detect routine. (DB) */
		if (HBA_ptr->select_queue_depths != NULL)
			(HBA_ptr->select_queue_depths) (HBA_ptr, HBA_ptr->host_queue);

		err = length;
		goto out;
	}
	/*
	 * Usage: echo "scsi remove-single-device 0 1 2 3" >/proc/scsi/scsi
	 * with  "0 1 2 3" replaced by your "Host Channel Id Lun".
	 *
	 * Consider this feature pre-BETA.
	 *
	 *     CAUTION: This is not for hotplugging your peripherals. As
	 *     SCSI was not designed for this you could damage your
	 *     hardware and thoroughly confuse the SCSI subsystem.
	 *
	 */
	else if (!strncmp("remove-single-device", buffer + 5, 20)) {
		p = buffer + 26;

		host = simple_strtoul(p, &p, 0);
		channel = simple_strtoul(p + 1, &p, 0);
		id = simple_strtoul(p + 1, &p, 0);
		lun = simple_strtoul(p + 1, &p, 0);


		for (HBA_ptr = scsi_hostlist; HBA_ptr; HBA_ptr = HBA_ptr->next) {
			if (HBA_ptr->host_no == host) {
				break;
			}
		}
		err = -ENODEV;
		if (!HBA_ptr)
			goto out;

		for (scd = HBA_ptr->host_queue; scd; scd = scd->next) {
			if ((scd->channel == channel
			     && scd->id == id
			     && scd->lun == lun)) {
				break;
			}
		}

		if (scd == NULL)
			goto out;	/* there is no such device attached */

		err = -EBUSY;
		if (scd->access_count)
			goto out;

		SDTpnt = scsi_devicelist;
		while (SDTpnt != NULL) {
			if (SDTpnt->detach)
				(*SDTpnt->detach) (scd);
			SDTpnt = SDTpnt->next;
		}

		if (scd->attached == 0) {
			/*
			 * Nobody is using this device any more.
			 * Free all of the command structures.
			 */
			for (SCpnt = scd->device_queue; SCpnt; SCpnt = SCpnt->next) {
				scd->device_queue = SCpnt->next;
				scsi_init_free((char *) SCpnt, sizeof(*SCpnt));
			}
			/* Now we can remove the device structure */
			if (scd->next != NULL)
				scd->next->prev = scd->prev;

			if (scd->prev != NULL)
				scd->prev->next = scd->next;

			if (HBA_ptr->host_queue == scd) {
				HBA_ptr->host_queue = scd->next;
			}
			blk_cleanup_queue(&scd->request_queue);
			scsi_init_free((char *) scd, sizeof(Scsi_Device));
		} else {
			goto out;
		}
		err = 0;
	}
out:
	
	free_page((unsigned long) buffer);
	return err;
}
#endif

/*
 * Function:    resize_dma_pool
 *
 * Purpose:     Ensure that the DMA pool is sufficiently large to be
 *              able to guarantee that we can always process I/O requests
 *              without calling the system allocator.
 *
 * Arguments:   None.
 *
 * Lock status: No locks assumed to be held.  This function is SMP-safe.
 *
 * Returns:     Nothing
 *
 * Notes:       Prior to the new queue code, this function was not SMP-safe.
 *              Go through the device list and recompute the most appropriate
 *              size for the dma pool.  Then grab more memory (as required).
 */
static void resize_dma_pool(void)
{
	int i, k;
	unsigned long size;
	unsigned long flags;
	struct Scsi_Host *shpnt;
	struct Scsi_Host *host = NULL;
	Scsi_Device *SDpnt;
	FreeSectorBitmap *new_dma_malloc_freelist = NULL;
	unsigned int new_dma_sectors = 0;
	unsigned int new_need_isa_buffer = 0;
	unsigned char **new_dma_malloc_pages = NULL;
	int out_of_space = 0;

	spin_lock_irqsave(&allocator_request_lock, flags);

	if (!scsi_hostlist) {
		/*
		 * Free up the DMA pool.
		 */
		if (scsi_dma_free_sectors != dma_sectors)
			panic("SCSI DMA pool memory leak %d %d\n", scsi_dma_free_sectors, dma_sectors);

		for (i = 0; i < dma_sectors / SECTORS_PER_PAGE; i++)
			scsi_init_free(dma_malloc_pages[i], PAGE_SIZE);
		if (dma_malloc_pages)
			scsi_init_free((char *) dma_malloc_pages,
				       (dma_sectors / SECTORS_PER_PAGE) * sizeof(*dma_malloc_pages));
		dma_malloc_pages = NULL;
		if (dma_malloc_freelist)
			scsi_init_free((char *) dma_malloc_freelist,
				       (dma_sectors / SECTORS_PER_PAGE) * sizeof(*dma_malloc_freelist));
		dma_malloc_freelist = NULL;
		dma_sectors = 0;
		scsi_dma_free_sectors = 0;
		spin_unlock_irqrestore(&allocator_request_lock, flags);
		return;
	}
	/* Next, check to see if we need to extend the DMA buffer pool */

	new_dma_sectors = 2 * SECTORS_PER_PAGE;		/* Base value we use */

	if (__pa(high_memory) - 1 > ISA_DMA_THRESHOLD)
		need_isa_bounce_buffers = 1;
	else
		need_isa_bounce_buffers = 0;

	if (scsi_devicelist)
		for (shpnt = scsi_hostlist; shpnt; shpnt = shpnt->next)
			new_dma_sectors += SECTORS_PER_PAGE;	/* Increment for each host */

	for (host = scsi_hostlist; host; host = host->next) {
		for (SDpnt = host->host_queue; SDpnt; SDpnt = SDpnt->next) {
			/*
			 * sd and sr drivers allocate scatterlists.
			 * sr drivers may allocate for each command 1x2048 or 2x1024 extra
			 * buffers for 2k sector size and 1k fs.
			 * sg driver allocates buffers < 4k.
			 * st driver does not need buffers from the dma pool.
			 * estimate 4k buffer/command for devices of unknown type (should panic).
			 */
			if (SDpnt->type == TYPE_WORM || SDpnt->type == TYPE_ROM ||
			    SDpnt->type == TYPE_DISK || SDpnt->type == TYPE_MOD) {
				new_dma_sectors += ((host->sg_tablesize *
				sizeof(struct scatterlist) + 511) >> 9) *
				 SDpnt->queue_depth;
				if (SDpnt->type == TYPE_WORM || SDpnt->type == TYPE_ROM)
					new_dma_sectors += (2048 >> 9) * SDpnt->queue_depth;
			} else if (SDpnt->type == TYPE_SCANNER ||
				   SDpnt->type == TYPE_PROCESSOR ||
				   SDpnt->type == TYPE_MEDIUM_CHANGER ||
				   SDpnt->type == TYPE_ENCLOSURE) {
				new_dma_sectors += (4096 >> 9) * SDpnt->queue_depth;
			} else {
				if (SDpnt->type != TYPE_TAPE) {
					printk("resize_dma_pool: unknown device type %d\n", SDpnt->type);
					new_dma_sectors += (4096 >> 9) * SDpnt->queue_depth;
				}
			}

			if (host->unchecked_isa_dma &&
			    need_isa_bounce_buffers &&
			    SDpnt->type != TYPE_TAPE) {
				new_dma_sectors += (PAGE_SIZE >> 9) * host->sg_tablesize *
				    SDpnt->queue_depth;
				new_need_isa_buffer++;
			}
		}
	}

#ifdef DEBUG_INIT
	printk("resize_dma_pool: needed dma sectors = %d\n", new_dma_sectors);
#endif

	/* limit DMA memory to 32MB: */
	new_dma_sectors = (new_dma_sectors + 15) & 0xfff0;

	/*
	 * We never shrink the buffers - this leads to
	 * race conditions that I would rather not even think
	 * about right now.
	 */
#if 0				/* Why do this? No gain and risks out_of_space */
	if (new_dma_sectors < dma_sectors)
		new_dma_sectors = dma_sectors;
#endif
	if (new_dma_sectors <= dma_sectors) {
		spin_unlock_irqrestore(&allocator_request_lock, flags);
		return;		/* best to quit while we are in front */
        }

	for (k = 0; k < 20; ++k) {	/* just in case */
		out_of_space = 0;
		size = (new_dma_sectors / SECTORS_PER_PAGE) *
		    sizeof(FreeSectorBitmap);
		new_dma_malloc_freelist = (FreeSectorBitmap *)
		    scsi_init_malloc(size, GFP_ATOMIC);
		if (new_dma_malloc_freelist) {
			size = (new_dma_sectors / SECTORS_PER_PAGE) *
			    sizeof(*new_dma_malloc_pages);
			new_dma_malloc_pages = (unsigned char **)
			    scsi_init_malloc(size, GFP_ATOMIC);
			if (!new_dma_malloc_pages) {
				size = (new_dma_sectors / SECTORS_PER_PAGE) *
				    sizeof(FreeSectorBitmap);
				scsi_init_free((char *) new_dma_malloc_freelist, size);
				out_of_space = 1;
			}
		} else
			out_of_space = 1;

		if ((!out_of_space) && (new_dma_sectors > dma_sectors)) {
			for (i = dma_sectors / SECTORS_PER_PAGE;
			   i < new_dma_sectors / SECTORS_PER_PAGE; i++) {
				new_dma_malloc_pages[i] = (unsigned char *)
				    scsi_init_malloc(PAGE_SIZE, GFP_ATOMIC | GFP_DMA);
				if (!new_dma_malloc_pages[i])
					break;
			}
			if (i != new_dma_sectors / SECTORS_PER_PAGE) {	/* clean up */
				int k = i;

				out_of_space = 1;
				for (i = 0; i < k; ++i)
					scsi_init_free(new_dma_malloc_pages[i], PAGE_SIZE);
			}
		}
		if (out_of_space) {	/* try scaling down new_dma_sectors request */
			printk("scsi::resize_dma_pool: WARNING, dma_sectors=%u, "
			       "wanted=%u, scaling\n", dma_sectors, new_dma_sectors);
			if (new_dma_sectors < (8 * SECTORS_PER_PAGE))
				break;	/* pretty well hopeless ... */
			new_dma_sectors = (new_dma_sectors * 3) / 4;
			new_dma_sectors = (new_dma_sectors + 15) & 0xfff0;
			if (new_dma_sectors <= dma_sectors)
				break;	/* stick with what we have got */
		} else
			break;	/* found space ... */
	}			/* end of for loop */
	if (out_of_space) {
		spin_unlock_irqrestore(&allocator_request_lock, flags);
		scsi_need_isa_buffer = new_need_isa_buffer;	/* some useful info */
		printk("      WARNING, not enough memory, pool not expanded\n");
		return;
	}
	/* When we dick with the actual DMA list, we need to
	 * protect things
	 */
	if (dma_malloc_freelist) {
		size = (dma_sectors / SECTORS_PER_PAGE) * sizeof(FreeSectorBitmap);
		memcpy(new_dma_malloc_freelist, dma_malloc_freelist, size);
		scsi_init_free((char *) dma_malloc_freelist, size);
	}
	dma_malloc_freelist = new_dma_malloc_freelist;

	if (dma_malloc_pages) {
		size = (dma_sectors / SECTORS_PER_PAGE) * sizeof(*dma_malloc_pages);
		memcpy(new_dma_malloc_pages, dma_malloc_pages, size);
		scsi_init_free((char *) dma_malloc_pages, size);
	}
	scsi_dma_free_sectors += new_dma_sectors - dma_sectors;
	dma_malloc_pages = new_dma_malloc_pages;
	dma_sectors = new_dma_sectors;
	scsi_need_isa_buffer = new_need_isa_buffer;

	spin_unlock_irqrestore(&allocator_request_lock, flags);

#ifdef DEBUG_INIT
	printk("resize_dma_pool: dma free sectors   = %d\n", scsi_dma_free_sectors);
	printk("resize_dma_pool: dma sectors        = %d\n", dma_sectors);
	printk("resize_dma_pool: need isa buffers   = %d\n", scsi_need_isa_buffer);
#endif
}

#ifdef CONFIG_MODULES		/* a big #ifdef block... */

/*
 * This entry point should be called by a loadable module if it is trying
 * add a low level scsi driver to the system.
 */
static int scsi_register_host(Scsi_Host_Template * tpnt)
{
	int pcount;
	struct Scsi_Host *shpnt;
	Scsi_Device *SDpnt;
	struct Scsi_Device_Template *sdtpnt;
	const char *name;
	unsigned long flags;
	int out_of_space = 0;

	if (tpnt->next || !tpnt->detect)
		return 1;	/* Must be already loaded, or
				 * no detect routine available
				 */
	pcount = next_scsi_host;

	/* The detect routine must carefully spinunlock/spinlock if 
	   it enables interrupts, since all interrupt handlers do 
	   spinlock as well.
	   All lame drivers are going to fail due to the following 
	   spinlock. For the time beeing let's use it only for drivers 
	   using the new scsi code. NOTE: the detect routine could
	   redefine the value tpnt->use_new_eh_code. (DB, 13 May 1998) */

	if (tpnt->use_new_eh_code) {
		spin_lock_irqsave(&io_request_lock, flags);
		tpnt->present = tpnt->detect(tpnt);
		spin_unlock_irqrestore(&io_request_lock, flags);
	} else
		tpnt->present = tpnt->detect(tpnt);

	if (tpnt->present) {
		if (pcount == next_scsi_host) {
			if (tpnt->present > 1) {
				printk("Failure to register low-level scsi driver");
				scsi_unregister_host(tpnt);
				return 1;
			}
			/* 
			 * The low-level driver failed to register a driver.  We
			 *  can do this now.
			 */
			scsi_register(tpnt, 0);
		}
		tpnt->next = scsi_hosts;	/* Add to the linked list */
		scsi_hosts = tpnt;

		/* Add the new driver to /proc/scsi */
#ifdef CONFIG_PROC_FS
		build_proc_dir_entries(tpnt);
#endif


		/*
		 * Add the kernel threads for each host adapter that will
		 * handle error correction.
		 */
		for (shpnt = scsi_hostlist; shpnt; shpnt = shpnt->next) {
			if (shpnt->hostt == tpnt && shpnt->hostt->use_new_eh_code) {
				DECLARE_MUTEX_LOCKED(sem);

				shpnt->eh_notify = &sem;
				kernel_thread((int (*)(void *)) scsi_error_handler,
					      (void *) shpnt, 0);

				/*
				 * Now wait for the kernel error thread to initialize itself
				 * as it might be needed when we scan the bus.
				 */
				down(&sem);
				shpnt->eh_notify = NULL;
			}
		}

		for (shpnt = scsi_hostlist; shpnt; shpnt = shpnt->next) {
			if (shpnt->hostt == tpnt) {
				if (tpnt->info) {
					name = tpnt->info(shpnt);
				} else {
					name = tpnt->name;
				}
				printk("scsi%d : %s\n",		/* And print a little message */
				       shpnt->host_no, name);
			}
		}

		printk("scsi : %d host%s.\n", next_scsi_host,
		       (next_scsi_host == 1) ? "" : "s");

		/* The next step is to call scan_scsis here.  This generates the
		 * Scsi_Devices entries
		 */
		for (shpnt = scsi_hostlist; shpnt; shpnt = shpnt->next) {
			if (shpnt->hostt == tpnt) {
				scan_scsis(shpnt, 0, 0, 0, 0);
				if (shpnt->select_queue_depths != NULL) {
					(shpnt->select_queue_depths) (shpnt, shpnt->host_queue);
				}
			}
		}

		for (sdtpnt = scsi_devicelist; sdtpnt; sdtpnt = sdtpnt->next) {
			if (sdtpnt->init && sdtpnt->dev_noticed)
				(*sdtpnt->init) ();
		}

		/*
		 * Next we create the Scsi_Cmnd structures for this host 
		 */
		for (shpnt = scsi_hostlist; shpnt; shpnt = shpnt->next) {
			for (SDpnt = shpnt->host_queue; SDpnt; SDpnt = SDpnt->next)
				if (SDpnt->host->hostt == tpnt) {
					for (sdtpnt = scsi_devicelist; sdtpnt; sdtpnt = sdtpnt->next)
						if (sdtpnt->attach)
							(*sdtpnt->attach) (SDpnt);
					if (SDpnt->attached) {
						scsi_build_commandblocks(SDpnt);
						if (0 == SDpnt->has_cmdblocks)
							out_of_space = 1;
					}
				}
		}

		/*
		 * Now that we have all of the devices, resize the DMA pool,
		 * as required.  */
		if (!out_of_space)
			resize_dma_pool();


		/* This does any final handling that is required. */
		for (sdtpnt = scsi_devicelist; sdtpnt; sdtpnt = sdtpnt->next) {
			if (sdtpnt->finish && sdtpnt->nr_dev) {
				(*sdtpnt->finish) ();
			}
		}
	}
#if defined(USE_STATIC_SCSI_MEMORY)
	printk("SCSI memory: total %ldKb, used %ldKb, free %ldKb.\n",
	       (scsi_memory_upper_value - scsi_memory_lower_value) / 1024,
	       (scsi_init_memory_start - scsi_memory_lower_value) / 1024,
	       (scsi_memory_upper_value - scsi_init_memory_start) / 1024);
#endif

	MOD_INC_USE_COUNT;

	if (out_of_space) {
		scsi_unregister_host(tpnt);	/* easiest way to clean up?? */
		return 1;
	} else
		return 0;
}

/*
 * Similarly, this entry point should be called by a loadable module if it
 * is trying to remove a low level scsi driver from the system.
 *
 * Note - there is a fatal flaw in the deregister module function.
 * There is no way to return a code that says 'I cannot be unloaded now'.
 * The system relies entirely upon usage counts that are maintained,
 * and the assumption is that if the usage count is 0, then the module
 * can be unloaded.
 */
static void scsi_unregister_host(Scsi_Host_Template * tpnt)
{
	int online_status;
	int pcount;
	Scsi_Cmnd *SCpnt;
	Scsi_Device *SDpnt;
	Scsi_Device *SDpnt1;
	struct Scsi_Device_Template *sdtpnt;
	struct Scsi_Host *sh1;
	struct Scsi_Host *shpnt;
	Scsi_Host_Template *SHT;
	Scsi_Host_Template *SHTp;
	char name[10];	/* host_no>=10^9? I don't think so. */

	/*
	 * First verify that this host adapter is completely free with no pending
	 * commands 
	 */
	for (shpnt = scsi_hostlist; shpnt; shpnt = shpnt->next) {
		for (SDpnt = shpnt->host_queue; SDpnt;
		     SDpnt = SDpnt->next) {
			if (SDpnt->host->hostt == tpnt
			    && SDpnt->host->hostt->module
			    && GET_USE_COUNT(SDpnt->host->hostt->module))
				return;
			/* 
			 * FIXME(eric) - We need to find a way to notify the
			 * low level driver that we are shutting down - via the
			 * special device entry that still needs to get added. 
			 *
			 * Is detach interface below good enough for this?
			 */
		}
	}

	/*
	 * FIXME(eric) put a spinlock on this.  We force all of the devices offline
	 * to help prevent race conditions where other hosts/processors could try and
	 * get in and queue a command.
	 */
	for (shpnt = scsi_hostlist; shpnt; shpnt = shpnt->next) {
		for (SDpnt = shpnt->host_queue; SDpnt;
		     SDpnt = SDpnt->next) {
			if (SDpnt->host->hostt == tpnt)
				SDpnt->online = FALSE;

		}
	}

	for (shpnt = scsi_hostlist; shpnt; shpnt = shpnt->next) {
		if (shpnt->hostt != tpnt) {
			continue;
		}
		for (SDpnt = shpnt->host_queue; SDpnt;
		     SDpnt = SDpnt->next) {
			/*
			 * Loop over all of the commands associated with the device.  If any of
			 * them are busy, then set the state back to inactive and bail.
			 */
			for (SCpnt = SDpnt->device_queue; SCpnt;
			     SCpnt = SCpnt->next) {
				online_status = SDpnt->online;
				SDpnt->online = FALSE;
				if (SCpnt->request.rq_status != RQ_INACTIVE) {
					printk("SCSI device not inactive - rq_status=%d, target=%d, pid=%ld, state=%d, owner=%d.\n",
					       SCpnt->request.rq_status, SCpnt->target, SCpnt->pid,
					     SCpnt->state, SCpnt->owner);
					for (SDpnt1 = shpnt->host_queue; SDpnt1;
					     SDpnt1 = SDpnt1->next) {
						for (SCpnt = SDpnt1->device_queue; SCpnt;
						     SCpnt = SCpnt->next)
							if (SCpnt->request.rq_status == RQ_SCSI_DISCONNECTING)
								SCpnt->request.rq_status = RQ_INACTIVE;
					}
					SDpnt->online = online_status;
					printk("Device busy???\n");
					return;
				}
				/*
				 * No, this device is really free.  Mark it as such, and
				 * continue on.
				 */
				SCpnt->state = SCSI_STATE_DISCONNECTING;
				SCpnt->request.rq_status = RQ_SCSI_DISCONNECTING;	/* Mark as busy */
			}
		}
	}
	/* Next we detach the high level drivers from the Scsi_Device structures */

	for (shpnt = scsi_hostlist; shpnt; shpnt = shpnt->next) {
		if (shpnt->hostt != tpnt) {
			continue;
		}
		for (SDpnt = shpnt->host_queue; SDpnt;
		     SDpnt = SDpnt->next) {
			for (sdtpnt = scsi_devicelist; sdtpnt; sdtpnt = sdtpnt->next)
				if (sdtpnt->detach)
					(*sdtpnt->detach) (SDpnt);

			/* If something still attached, punt */
			if (SDpnt->attached) {
				printk("Attached usage count = %d\n", SDpnt->attached);
				return;
			}
		}
	}

	/*
	 * Next, kill the kernel error recovery thread for this host.
	 */
	for (shpnt = scsi_hostlist; shpnt; shpnt = shpnt->next) {
		if (shpnt->hostt == tpnt
		    && shpnt->hostt->use_new_eh_code
		    && shpnt->ehandler != NULL) {
			DECLARE_MUTEX_LOCKED(sem);

			shpnt->eh_notify = &sem;
			send_sig(SIGHUP, shpnt->ehandler, 1);
			down(&sem);
			shpnt->eh_notify = NULL;
		}
	}

	/* Next we free up the Scsi_Cmnd structures for this host */

	for (shpnt = scsi_hostlist; shpnt; shpnt = shpnt->next) {
		if (shpnt->hostt != tpnt) {
			continue;
		}
		for (SDpnt = shpnt->host_queue; SDpnt;
		     SDpnt = shpnt->host_queue) {
			while (SDpnt->device_queue) {
				SCpnt = SDpnt->device_queue->next;
				scsi_init_free((char *) SDpnt->device_queue, sizeof(Scsi_Cmnd));
				SDpnt->device_queue = SCpnt;
			}
			SDpnt->has_cmdblocks = 0;

			blk_cleanup_queue(&SDpnt->request_queue);
			/* Next free up the Scsi_Device structures for this host */
			shpnt->host_queue = SDpnt->next;
			scsi_init_free((char *) SDpnt, sizeof(Scsi_Device));

		}
	}

	/* Next we go through and remove the instances of the individual hosts
	 * that were detected */

	for (shpnt = scsi_hostlist; shpnt; shpnt = sh1) {
		sh1 = shpnt->next;
		if (shpnt->hostt != tpnt || !shpnt->loaded_as_module)
			continue;
		pcount = next_scsi_host;
		/* Remove the /proc/scsi directory entry */
		sprintf(name,"%d",shpnt->host_no);
		remove_proc_entry(name, tpnt->proc_dir);
		if (tpnt->release)
			(*tpnt->release) (shpnt);
		else {
			/* This is the default case for the release function.
			 * It should do the right thing for most correctly
			 * written host adapters.
			 */
			if (shpnt->irq)
			free_irq(shpnt->irq, NULL);
			if (shpnt->dma_channel != 0xff)
				free_dma(shpnt->dma_channel);
			if (shpnt->io_port && shpnt->n_io_port)
				release_region(shpnt->io_port, shpnt->n_io_port);
		}
		if (pcount == next_scsi_host)
			scsi_unregister(shpnt);
		tpnt->present--;
	}

	/*
	 * If there are absolutely no more hosts left, it is safe
	 * to completely nuke the DMA pool.  The resize operation will
	 * do the right thing and free everything.
	 */
	if (!scsi_hosts)
		resize_dma_pool();

	printk("scsi : %d host%s.\n", next_scsi_host,
	       (next_scsi_host == 1) ? "" : "s");

#if defined(USE_STATIC_SCSI_MEMORY)
	printk("SCSI memory: total %ldKb, used %ldKb, free %ldKb.\n",
	       (scsi_memory_upper_value - scsi_memory_lower_value) / 1024,
	       (scsi_init_memory_start - scsi_memory_lower_value) / 1024,
	       (scsi_memory_upper_value - scsi_init_memory_start) / 1024);
#endif


	/* There were some hosts that were loaded at boot time, so we cannot
	   do any more than this */
	if (tpnt->present)
		return;

	/* OK, this is the very last step.  Remove this host adapter from the
	   linked list. */
	for (SHTp = NULL, SHT = scsi_hosts; SHT; SHTp = SHT, SHT = SHT->next)
		if (SHT == tpnt) {
			if (SHTp)
				SHTp->next = SHT->next;
			else
				scsi_hosts = SHT->next;
			SHT->next = NULL;
			break;
		}
	/* Rebuild the /proc/scsi directory entries */
	remove_proc_entry(tpnt->proc_name, proc_scsi);
	MOD_DEC_USE_COUNT;
}

/*
 * This entry point should be called by a loadable module if it is trying
 * add a high level scsi driver to the system.
 */
static int scsi_register_device_module(struct Scsi_Device_Template *tpnt)
{
	Scsi_Device *SDpnt;
	struct Scsi_Host *shpnt;
	int out_of_space = 0;

	if (tpnt->next)
		return 1;

	scsi_register_device(tpnt);
	/*
	 * First scan the devices that we know about, and see if we notice them.
	 */

	for (shpnt = scsi_hostlist; shpnt; shpnt = shpnt->next) {
		for (SDpnt = shpnt->host_queue; SDpnt;
		     SDpnt = SDpnt->next) {
			if (tpnt->detect)
				SDpnt->attached += (*tpnt->detect) (SDpnt);
		}
	}

	/*
	 * If any of the devices would match this driver, then perform the
	 * init function.
	 */
	if (tpnt->init && tpnt->dev_noticed)
		if ((*tpnt->init) ())
			return 1;

	/*
	 * Now actually connect the devices to the new driver.
	 */
	for (shpnt = scsi_hostlist; shpnt; shpnt = shpnt->next) {
		for (SDpnt = shpnt->host_queue; SDpnt;
		     SDpnt = SDpnt->next) {
			if (tpnt->attach)
				(*tpnt->attach) (SDpnt);
			/*
			 * If this driver attached to the device, and don't have any
			 * command blocks for this device, allocate some.
			 */
			if (SDpnt->attached && SDpnt->has_cmdblocks == 0) {
				SDpnt->online = TRUE;
				scsi_build_commandblocks(SDpnt);
				if (0 == SDpnt->has_cmdblocks)
					out_of_space = 1;
			}
		}
	}

	/*
	 * This does any final handling that is required.
	 */
	if (tpnt->finish && tpnt->nr_dev)
		(*tpnt->finish) ();
	if (!out_of_space)
		resize_dma_pool();
	MOD_INC_USE_COUNT;

	if (out_of_space) {
		scsi_unregister_device(tpnt);	/* easiest way to clean up?? */
		return 1;
	} else
		return 0;
}

static int scsi_unregister_device(struct Scsi_Device_Template *tpnt)
{
	Scsi_Device *SDpnt;
	Scsi_Cmnd *SCpnt;
	struct Scsi_Host *shpnt;
	struct Scsi_Device_Template *spnt;
	struct Scsi_Device_Template *prev_spnt;

	/*
	 * If we are busy, this is not going to fly.
	 */
	if (GET_USE_COUNT(tpnt->module) != 0)
		return 0;

	/*
	 * Next, detach the devices from the driver.
	 */

	for (shpnt = scsi_hostlist; shpnt; shpnt = shpnt->next) {
		for (SDpnt = shpnt->host_queue; SDpnt;
		     SDpnt = SDpnt->next) {
			if (tpnt->detach)
				(*tpnt->detach) (SDpnt);
			if (SDpnt->attached == 0) {
				SDpnt->online = FALSE;

				/*
				 * Nobody is using this device any more.  Free all of the
				 * command structures.
				 */
				for (SCpnt = SDpnt->device_queue; SCpnt;
				     SCpnt = SCpnt->next) {
					if (SCpnt == SDpnt->device_queue)
						SDpnt->device_queue = SCpnt->next;
					scsi_init_free((char *) SCpnt, sizeof(*SCpnt));
				}
				SDpnt->has_cmdblocks = 0;
			}
		}
	}
	/*
	 * Extract the template from the linked list.
	 */
	spnt = scsi_devicelist;
	prev_spnt = NULL;
	while (spnt != tpnt) {
		prev_spnt = spnt;
		spnt = spnt->next;
	}
	if (prev_spnt == NULL)
		scsi_devicelist = tpnt->next;
	else
		prev_spnt->next = spnt->next;

	MOD_DEC_USE_COUNT;
	/*
	 * Final cleanup for the driver is done in the driver sources in the
	 * cleanup function.
	 */
	return 0;
}


int scsi_register_module(int module_type, void *ptr)
{
	switch (module_type) {
	case MODULE_SCSI_HA:
		return scsi_register_host((Scsi_Host_Template *) ptr);

		/* Load upper level device handler of some kind */
	case MODULE_SCSI_DEV:
#ifdef CONFIG_KMOD
		if (scsi_hosts == NULL)
			request_module("scsi_hostadapter");
#endif
		return scsi_register_device_module((struct Scsi_Device_Template *) ptr);
		/* The rest of these are not yet implemented */

		/* Load constants.o */
	case MODULE_SCSI_CONST:

		/* Load specialized ioctl handler for some device.  Intended for
		 * cdroms that have non-SCSI2 audio command sets. */
	case MODULE_SCSI_IOCTL:

	default:
		return 1;
	}
}

void scsi_unregister_module(int module_type, void *ptr)
{
	switch (module_type) {
	case MODULE_SCSI_HA:
		scsi_unregister_host((Scsi_Host_Template *) ptr);
		break;
	case MODULE_SCSI_DEV:
		scsi_unregister_device((struct Scsi_Device_Template *) ptr);
		break;
		/* The rest of these are not yet implemented. */
	case MODULE_SCSI_CONST:
	case MODULE_SCSI_IOCTL:
		break;
	default:
	}
	return;
}

#endif				/* CONFIG_MODULES */

#ifdef CONFIG_PROC_FS
/*
 * Function:    scsi_dump_status
 *
 * Purpose:     Brain dump of scsi system, used for problem solving.
 *
 * Arguments:   level - used to indicate level of detail.
 *
 * Notes:       The level isn't used at all yet, but we need to find some way
 *              of sensibly logging varying degrees of information.  A quick one-line
 *              display of each command, plus the status would be most useful.
 *
 *              This does depend upon CONFIG_SCSI_LOGGING - I do want some way of turning
 *              it all off if the user wants a lean and mean kernel.  It would probably
 *              also be useful to allow the user to specify one single host to be dumped.
 *              A second argument to the function would be useful for that purpose.
 *
 *              FIXME - some formatting of the output into tables would be very handy.
 */
static void scsi_dump_status(int level)
{
#ifdef CONFIG_SCSI_LOGGING		/* { */
	int i;
	struct Scsi_Host *shpnt;
	Scsi_Cmnd *SCpnt;
	Scsi_Device *SDpnt;
	printk("Dump of scsi host parameters:\n");
	i = 0;
	for (shpnt = scsi_hostlist; shpnt; shpnt = shpnt->next) {
		printk(" %d %d %d : %d\n",
		       shpnt->host_failed,
		       shpnt->host_busy,
		       atomic_read(&shpnt->host_active),
		       shpnt->host_blocked);

	}

	printk("\n\n");
	printk("Dump of scsi command parameters:\n");
	for (shpnt = scsi_hostlist; shpnt; shpnt = shpnt->next) {
		printk("h:c:t:l (dev sect nsect cnumsec sg) (ret all flg) (to/cmd to ito) cmd snse result\n");
		for (SDpnt = shpnt->host_queue; SDpnt; SDpnt = SDpnt->next) {
			for (SCpnt = SDpnt->device_queue; SCpnt; SCpnt = SCpnt->next) {
				/*  (0) h:c:t:l (dev sect nsect cnumsec sg) (ret all flg) (to/cmd to ito) cmd snse result %d %x      */
				printk("(%3d) %2d:%1d:%2d:%2d (%6s %4ld %4ld %4ld %4x %1d) (%1d %1d 0x%2x) (%4d %4d %4d) 0x%2.2x 0x%2.2x 0x%8.8x\n",
				       i++,

				       SCpnt->host->host_no,
				       SCpnt->channel,
				       SCpnt->target,
				       SCpnt->lun,

				       kdevname(SCpnt->request.rq_dev),
				       SCpnt->request.sector,
				       SCpnt->request.nr_sectors,
				       SCpnt->request.current_nr_sectors,
				       SCpnt->request.rq_status,
				       SCpnt->use_sg,

				       SCpnt->retries,
				       SCpnt->allowed,
				       SCpnt->flags,

				       SCpnt->timeout_per_command,
				       SCpnt->timeout,
				       SCpnt->internal_timeout,

				       SCpnt->cmnd[0],
				       SCpnt->sense_buffer[2],
				       SCpnt->result);
			}
		}
	}

	for (shpnt = scsi_hostlist; shpnt; shpnt = shpnt->next) {
		for (SDpnt = shpnt->host_queue; SDpnt; SDpnt = SDpnt->next) {
			/* Now dump the request lists for each block device */
			printk("Dump of pending block device requests\n");
			for (i = 0; i < MAX_BLKDEV; i++) {
				if (blk_dev[i].request_queue.current_request) {
					struct request *req;
					printk("%d: ", i);
					req = blk_dev[i].request_queue.current_request;
					while (req) {
						printk("(%s %d %ld %ld %ld) ",
						   kdevname(req->rq_dev),
						       req->cmd,
						       req->sector,
						       req->nr_sectors,
						req->current_nr_sectors);
						req = req->next;
					}
					printk("\n");
				}
			}
		}
	}
	printk("wait_for_request = %p\n", &wait_for_request);
#endif	/* CONFIG_SCSI_LOGGING */ /* } */
}
#endif				/* CONFIG_PROC_FS */

#ifdef MODULE

int init_module(void)
{
	unsigned long size;
	int has_space = 0;
	struct proc_dir_entry *generic;

	/*
	 * This makes /proc/scsi and /proc/scsi/scsi visible.
	 */
#ifdef CONFIG_PROC_FS
	proc_scsi = proc_mkdir("scsi", 0);
	if (!proc_scsi) {
		printk (KERN_ERR "cannot init /proc/scsi\n");
		return -ENOMEM;
	}
	generic = create_proc_info_entry ("scsi/scsi", 0, 0, scsi_proc_info);
	if (!generic) {
		printk (KERN_ERR "cannot init /proc/scsi/scsi\n");
		remove_proc_entry("scsi", 0);
		return -ENOMEM;
	}
	generic->write_proc = proc_scsi_gen_write;
#endif

	scsi_loadable_module_flag = 1;

	dma_sectors = PAGE_SIZE / SECTOR_SIZE;
	scsi_dma_free_sectors = dma_sectors;
	/*
	 * Set up a minimal DMA buffer list - this will be used during scan_scsis
	 * in some cases.
	 */

	/* One bit per sector to indicate free/busy */
	size = (dma_sectors / SECTORS_PER_PAGE) * sizeof(FreeSectorBitmap);
	dma_malloc_freelist = (FreeSectorBitmap *)
	    scsi_init_malloc(size, GFP_ATOMIC);
	if (dma_malloc_freelist) {
		/* One pointer per page for the page list */
		dma_malloc_pages = (unsigned char **) scsi_init_malloc(
									      (dma_sectors / SECTORS_PER_PAGE) * sizeof(*dma_malloc_pages),
							     GFP_ATOMIC);
		if (dma_malloc_pages) {
			dma_malloc_pages[0] = (unsigned char *)
			    scsi_init_malloc(PAGE_SIZE, GFP_ATOMIC | GFP_DMA);
			if (dma_malloc_pages[0])
				has_space = 1;
		}
	}
	if (!has_space) {
		if (dma_malloc_freelist) {
			scsi_init_free((char *) dma_malloc_freelist, size);
			if (dma_malloc_pages)
				scsi_init_free((char *) dma_malloc_pages,
					       (dma_sectors / SECTORS_PER_PAGE) * sizeof(*dma_malloc_pages));
		}
		printk("scsi::init_module: failed, out of memory\n");
		return 1;
	}
	/*
	 * This is where the processing takes place for most everything
	 * when commands are completed.
	 */
	init_bh(SCSI_BH, scsi_bottom_half_handler);

	return 0;
}

void cleanup_module(void)
{
	remove_bh(SCSI_BH);

#ifdef CONFIG_PROC_FS
	/* No, we're not here anymore. Don't show the /proc/scsi files. */
	remove_proc_entry ("scsi/scsi", 0);
	remove_proc_entry ("scsi", 0);
#endif
	
	/*
	 * Free up the DMA pool.
	 */
	resize_dma_pool();

}

#endif				/* MODULE */

/*
 * Function:    scsi_get_host_dev()
 *
 * Purpose:     Create a Scsi_Device that points to the host adapter itself.
 *
 * Arguments:   SHpnt   - Host that needs a Scsi_Device
 *
 * Lock status: None assumed.
 *
 * Returns:     Nothing
 *
 * Notes:
 */
Scsi_Device * scsi_get_host_dev(struct Scsi_Host * SHpnt)
{
        Scsi_Device * SDpnt;
        Scsi_Cmnd   * SCpnt;
        /*
         * Attach a single Scsi_Device to the Scsi_Host - this should
         * be made to look like a "pseudo-device" that points to the
         * HA itself.  For the moment, we include it at the head of
         * the host_queue itself - I don't think we want to show this
         * to the HA in select_queue_depths(), as this would probably confuse
         * matters.
         * Note - this device is not accessible from any high-level
         * drivers (including generics), which is probably not
         * optimal.  We can add hooks later to attach 
         */
        SDpnt = (Scsi_Device *) kmalloc(sizeof(Scsi_Device),
                                        GFP_ATOMIC);
        memset(SDpnt, 0, sizeof(Scsi_Device));

        SDpnt->host = SHpnt;
        SDpnt->id = SHpnt->this_id;
        SDpnt->type = -1;
        SDpnt->queue_depth = 1;
        
        SCpnt = kmalloc(sizeof(Scsi_Cmnd), GFP_ATOMIC);
        memset(SCpnt, 0, sizeof(Scsi_Cmnd));
        SCpnt->host = SHpnt;
        SCpnt->device = SDpnt;
        SCpnt->target = SDpnt->id;
        SCpnt->state = SCSI_STATE_UNUSED;
        SCpnt->owner = SCSI_OWNER_NOBODY;
        SCpnt->request.rq_status = RQ_INACTIVE;

        SDpnt->device_queue = SCpnt;

        blk_init_queue(&SDpnt->request_queue, scsi_request_fn);
        blk_queue_headactive(&SDpnt->request_queue, 0);
        SDpnt->request_queue.queuedata = (void *) SDpnt;

	SDpnt->online = TRUE;

        /*
         * Initialize the object that we will use to wait for command blocks.
         */
	init_waitqueue_head(&SDpnt->scpnt_wait);
        return SDpnt;
}

/*
 * Function:    scsi_free_host_dev()
 *
 * Purpose:     Create a Scsi_Device that points to the host adapter itself.
 *
 * Arguments:   SHpnt   - Host that needs a Scsi_Device
 *
 * Lock status: None assumed.
 *
 * Returns:     Nothing
 *
 * Notes:
 */
void scsi_free_host_dev(Scsi_Device * SDpnt)
{
        if( SDpnt->id != SDpnt->host->this_id )
        {
                panic("Attempt to delete wrong device\n");
        }

        blk_cleanup_queue(&SDpnt->request_queue);

        /*
         * We only have a single SCpnt attached to this device.  Free
         * it now.
         */
        kfree(SDpnt->device_queue);
        kfree(SDpnt);
}

/*
 * Overrides for Emacs so that we follow Linus's tabbing style.
 * Emacs will notice this stuff at the end of the file and automatically
 * adjust the settings for this buffer only.  This must remain at the end
 * of the file.
 * ---------------------------------------------------------------------------
 * Local variables:
 * c-indent-level: 4
 * c-brace-imaginary-offset: 0
 * c-brace-offset: -4
 * c-argdecl-indent: 4
 * c-label-offset: -4
 * c-continued-statement-offset: 4
 * c-continued-brace-offset: 0
 * indent-tabs-mode: nil
 * tab-width: 8
 * End:
 */