summaryrefslogtreecommitdiffstats
path: root/drivers/scsi/osst.c
blob: c585c7bef247c4cf7f5e051c6cf1898c3c996672 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
/*
  SCSI Tape Driver for Linux version 1.1 and newer. See the accompanying
  file Documentation/scsi/st.txt for more information.

  History:

  OnStream SCSI Tape support (osst) cloned from st.c by
  Willem Riede (osst@riede.org) Feb 2000
  Fixes ... Kurt Garloff <garloff@suse.de> Mar 2000

  Rewritten from Dwayne Forsyth's SCSI tape driver by Kai Makisara.
  Contribution and ideas from several people including (in alphabetical
  order) Klaus Ehrenfried, Wolfgang Denk, Steve Hirsch, Andreas Koppenh"ofer,
  Michael Leodolter, Eyal Lebedinsky, J"org Weule, and Eric Youngdale.

  Copyright 1992 - 2002 Kai Makisara / 2000 - 2004 Willem Riede
	 email osst@riede.org

  $Header: /cvsroot/osst/Driver/osst.c,v 1.73 2005/01/01 21:13:34 wriede Exp $

  Microscopic alterations - Rik Ling, 2000/12/21
  Last st.c sync: Tue Oct 15 22:01:04 2002 by makisara
  Some small formal changes - aeb, 950809
*/

static const char * cvsid = "$Id: osst.c,v 1.73 2005/01/01 21:13:34 wriede Exp $";
static const char * osst_version = "0.99.3";

/* The "failure to reconnect" firmware bug */
#define OSST_FW_NEED_POLL_MIN 10601 /*(107A)*/
#define OSST_FW_NEED_POLL_MAX 10704 /*(108D)*/
#define OSST_FW_NEED_POLL(x,d) ((x) >= OSST_FW_NEED_POLL_MIN && (x) <= OSST_FW_NEED_POLL_MAX && d->host->this_id != 7)

#include <linux/module.h>

#include <linux/fs.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/proc_fs.h>
#include <linux/mm.h>
#include <linux/init.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/mtio.h>
#include <linux/ioctl.h>
#include <linux/fcntl.h>
#include <linux/spinlock.h>
#include <linux/vmalloc.h>
#include <linux/blkdev.h>
#include <linux/moduleparam.h>
#include <linux/devfs_fs_kernel.h>
#include <linux/delay.h>
#include <asm/uaccess.h>
#include <asm/dma.h>
#include <asm/system.h>

/* The driver prints some debugging information on the console if DEBUG
   is defined and non-zero. */
#define DEBUG 0

/* The message level for the debug messages is currently set to KERN_NOTICE
   so that people can easily see the messages. Later when the debugging messages
   in the drivers are more widely classified, this may be changed to KERN_DEBUG. */
#define OSST_DEB_MSG  KERN_NOTICE

#include <scsi/scsi.h>
#include <scsi/scsi_dbg.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_driver.h>
#include <scsi/scsi_eh.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_ioctl.h>
#include <scsi/scsi_request.h>

#define ST_KILOBYTE 1024

#include "st.h"
#include "osst.h"
#include "osst_options.h"
#include "osst_detect.h"

static int max_dev = 0;
static int write_threshold_kbs = 0;
static int max_sg_segs = 0;

#ifdef MODULE
MODULE_AUTHOR("Willem Riede");
MODULE_DESCRIPTION("OnStream {DI-|FW-|SC-|USB}{30|50} Tape Driver");
MODULE_LICENSE("GPL");

module_param(max_dev, int, 0444);
MODULE_PARM_DESC(max_dev, "Maximum number of OnStream Tape Drives to attach (4)");

module_param(write_threshold_kbs, int, 0644);
MODULE_PARM_DESC(write_threshold_kbs, "Asynchronous write threshold (KB; 32)");

module_param(max_sg_segs, int, 0644);
MODULE_PARM_DESC(max_sg_segs, "Maximum number of scatter/gather segments to use (9)");
#else
static struct osst_dev_parm {
       char   *name;
       int    *val;
} parms[] __initdata = {
       { "max_dev",             &max_dev             },
       { "write_threshold_kbs", &write_threshold_kbs },
       { "max_sg_segs",         &max_sg_segs         }
};
#endif

static char *osst_formats[ST_NBR_MODES] ={"", "l", "m", "a"};

/* Some default definitions have been moved to osst_options.h */
#define OSST_BUFFER_SIZE (OSST_BUFFER_BLOCKS * ST_KILOBYTE)
#define OSST_WRITE_THRESHOLD (OSST_WRITE_THRESHOLD_BLOCKS * ST_KILOBYTE)

/* The buffer size should fit into the 24 bits for length in the
   6-byte SCSI read and write commands. */
#if OSST_BUFFER_SIZE >= (2 << 24 - 1)
#error "Buffer size should not exceed (2 << 24 - 1) bytes!"
#endif

#if DEBUG
static int debugging = 1;
/* uncomment define below to test error recovery */
// #define OSST_INJECT_ERRORS 1 
#endif

/* Do not retry! The drive firmware already retries when appropriate,
   and when it tries to tell us something, we had better listen... */
#define MAX_RETRIES 0

#define NO_TAPE  NOT_READY

#define OSST_WAIT_POSITION_COMPLETE   (HZ > 200 ? HZ / 200 : 1)
#define OSST_WAIT_WRITE_COMPLETE      (HZ / 12)
#define OSST_WAIT_LONG_WRITE_COMPLETE (HZ / 2)
	
#define OSST_TIMEOUT (200 * HZ)
#define OSST_LONG_TIMEOUT (1800 * HZ)

#define TAPE_NR(x) (iminor(x) & ~(-1 << ST_MODE_SHIFT))
#define TAPE_MODE(x) ((iminor(x) & ST_MODE_MASK) >> ST_MODE_SHIFT)
#define TAPE_REWIND(x) ((iminor(x) & 0x80) == 0)
#define TAPE_IS_RAW(x) (TAPE_MODE(x) & (ST_NBR_MODES >> 1))

/* Internal ioctl to set both density (uppermost 8 bits) and blocksize (lower
   24 bits) */
#define SET_DENS_AND_BLK 0x10001

static int osst_buffer_size       = OSST_BUFFER_SIZE;
static int osst_write_threshold   = OSST_WRITE_THRESHOLD;
static int osst_max_sg_segs       = OSST_MAX_SG;
static int osst_max_dev           = OSST_MAX_TAPES;
static int osst_nr_dev;

static struct osst_tape **os_scsi_tapes = NULL;
static DEFINE_RWLOCK(os_scsi_tapes_lock);

static int modes_defined = 0;

static struct osst_buffer *new_tape_buffer(int, int, int);
static int enlarge_buffer(struct osst_buffer *, int);
static void normalize_buffer(struct osst_buffer *);
static int append_to_buffer(const char __user *, struct osst_buffer *, int);
static int from_buffer(struct osst_buffer *, char __user *, int);
static int osst_zero_buffer_tail(struct osst_buffer *);
static int osst_copy_to_buffer(struct osst_buffer *, unsigned char *);
static int osst_copy_from_buffer(struct osst_buffer *, unsigned char *);

static int osst_probe(struct device *);
static int osst_remove(struct device *);

static struct scsi_driver osst_template = {
	.owner			= THIS_MODULE,
	.gendrv = {
		.name		=  "osst",
		.probe		= osst_probe,
		.remove		= osst_remove,
	}
};

static int osst_int_ioctl(struct osst_tape *STp, struct scsi_request ** aSRpnt,
			    unsigned int cmd_in, unsigned long arg);

static int osst_set_frame_position(struct osst_tape *STp, struct scsi_request ** aSRpnt, int frame, int skip);

static int osst_get_frame_position(struct osst_tape *STp, struct scsi_request ** aSRpnt);

static int osst_flush_write_buffer(struct osst_tape *STp, struct scsi_request ** aSRpnt);

static int osst_write_error_recovery(struct osst_tape * STp, struct scsi_request ** aSRpnt, int pending);

static inline char *tape_name(struct osst_tape *tape)
{
	return tape->drive->disk_name;
}

/* Routines that handle the interaction with mid-layer SCSI routines */

/* Convert the result to success code */
static int osst_chk_result(struct osst_tape * STp, struct scsi_request * SRpnt)
{
	char *name = tape_name(STp);
	int result = SRpnt->sr_result;
	unsigned char * sense = SRpnt->sr_sense_buffer, scode;
#if DEBUG
	const char *stp;
#endif

	if (!result) {
		sense[0] = 0;    /* We don't have sense data if this byte is zero */
		return 0;
	}
	if ((driver_byte(result) & DRIVER_MASK) == DRIVER_SENSE)
		scode = sense[2] & 0x0f;
	else {
		sense[0] = 0;    /* We don't have sense data if this byte is zero */
		scode = 0;
	}
#if DEBUG
	if (debugging) {
		printk(OSST_DEB_MSG "%s:D: Error: %x, cmd: %x %x %x %x %x %x Len: %d\n",
		   name, result,
		   SRpnt->sr_cmnd[0], SRpnt->sr_cmnd[1], SRpnt->sr_cmnd[2],
		   SRpnt->sr_cmnd[3], SRpnt->sr_cmnd[4], SRpnt->sr_cmnd[5],
		   SRpnt->sr_bufflen);
		if (scode) printk(OSST_DEB_MSG "%s:D: Sense: %02x, ASC: %02x, ASCQ: %02x\n",
			       	name, scode, sense[12], sense[13]);
		if (driver_byte(result) & DRIVER_SENSE)
			scsi_print_req_sense("osst ", SRpnt);
	}
	else
#endif
	if (!(driver_byte(result) & DRIVER_SENSE) ||
		((sense[0] & 0x70) == 0x70 &&
		 scode != NO_SENSE &&
		 scode != RECOVERED_ERROR &&
/*      	 scode != UNIT_ATTENTION && */
		 scode != BLANK_CHECK &&
		 scode != VOLUME_OVERFLOW &&
		 SRpnt->sr_cmnd[0] != MODE_SENSE &&
		 SRpnt->sr_cmnd[0] != TEST_UNIT_READY)) { /* Abnormal conditions for tape */
		if (driver_byte(result) & DRIVER_SENSE) {
			printk(KERN_WARNING "%s:W: Command with sense data:\n", name);
			scsi_print_req_sense("osst:", SRpnt);
		}
		else {
			static	int	notyetprinted = 1;

			printk(KERN_WARNING
			     "%s:W: Warning %x (sugg. bt 0x%x, driver bt 0x%x, host bt 0x%x).\n",
			     name, result, suggestion(result), driver_byte(result) & DRIVER_MASK,
			     host_byte(result));
			if (notyetprinted) {
				notyetprinted = 0;
				printk(KERN_INFO
					"%s:I: This warning may be caused by your scsi controller,\n", name);
				printk(KERN_INFO
					"%s:I: it has been reported with some Buslogic cards.\n", name);
			}
		}
	}
	STp->pos_unknown |= STp->device->was_reset;

	if ((sense[0] & 0x70) == 0x70 &&
	     scode == RECOVERED_ERROR) {
		STp->recover_count++;
		STp->recover_erreg++;
#if DEBUG
		if (debugging) {
			if (SRpnt->sr_cmnd[0] == READ_6)
				stp = "read";
			else if (SRpnt->sr_cmnd[0] == WRITE_6)
				stp = "write";
			else
				stp = "ioctl";
			printk(OSST_DEB_MSG "%s:D: Recovered %s error (%d).\n", name, stp,
					     STp->recover_count);
		}
#endif
		if ((sense[2] & 0xe0) == 0)
			return 0;
	}
	return (-EIO);
}


/* Wakeup from interrupt */
static void osst_sleep_done (struct scsi_cmnd * SCpnt)
{
	struct osst_tape * STp = container_of(SCpnt->request->rq_disk->private_data, struct osst_tape, driver);

	if ((STp->buffer)->writing &&
	    (SCpnt->sense_buffer[0] & 0x70) == 0x70 &&
	    (SCpnt->sense_buffer[2] & 0x40)) {
		/* EOM at write-behind, has all been written? */
		if ((SCpnt->sense_buffer[2] & 0x0f) == VOLUME_OVERFLOW)
			STp->buffer->midlevel_result = SCpnt->result; /* Error */
		else
			STp->buffer->midlevel_result = INT_MAX;       /* OK */
	}
	else
		STp->buffer->midlevel_result = SCpnt->result;
	SCpnt->request->rq_status = RQ_SCSI_DONE;
	STp->buffer->last_SRpnt = SCpnt->sc_request;

#if DEBUG
	STp->write_pending = 0;
#endif
	complete(SCpnt->request->waiting);
}


/* Do the scsi command. Waits until command performed if do_wait is true.
   Otherwise osst_write_behind_check() is used to check that the command
   has finished. */
static	struct scsi_request * osst_do_scsi(struct scsi_request *SRpnt, struct osst_tape *STp, 
	unsigned char *cmd, int bytes, int direction, int timeout, int retries, int do_wait)
{
	unsigned char *bp;
#ifdef OSST_INJECT_ERRORS
	static   int   inject = 0;
	static   int   repeat = 0;
#endif
	if (SRpnt == NULL) {
		if ((SRpnt = scsi_allocate_request(STp->device, GFP_ATOMIC)) == NULL) {
			printk(KERN_ERR "%s:E: Can't get SCSI request.\n", tape_name(STp));
			if (signal_pending(current))
				(STp->buffer)->syscall_result = (-EINTR);
			else
				(STp->buffer)->syscall_result = (-EBUSY);
			return NULL;
		}
	}

        init_completion(&STp->wait);
	SRpnt->sr_use_sg = (bytes > (STp->buffer)->sg[0].length) ?
				    (STp->buffer)->use_sg : 0;
	if (SRpnt->sr_use_sg) {
		bp = (char *)&(STp->buffer->sg[0]);
		if (STp->buffer->sg_segs < SRpnt->sr_use_sg)
			SRpnt->sr_use_sg = STp->buffer->sg_segs;
	}
	else
		bp = (STp->buffer)->b_data;
	SRpnt->sr_data_direction = direction;
	SRpnt->sr_cmd_len = 0;
	SRpnt->sr_request->waiting = &(STp->wait);
	SRpnt->sr_request->rq_status = RQ_SCSI_BUSY;
	SRpnt->sr_request->rq_disk = STp->drive;

	scsi_do_req(SRpnt, (void *)cmd, bp, bytes, osst_sleep_done, timeout, retries);

	if (do_wait) {
		wait_for_completion(SRpnt->sr_request->waiting);
		SRpnt->sr_request->waiting = NULL;
		STp->buffer->syscall_result = osst_chk_result(STp, SRpnt);
#ifdef OSST_INJECT_ERRORS
		if (STp->buffer->syscall_result == 0 &&
		    cmd[0] == READ_6 &&
		    cmd[4] && 
		    ( (++ inject % 83) == 29  ||
		      (STp->first_frame_position == 240 
			         /* or STp->read_error_frame to fail again on the block calculated above */ &&
				 ++repeat < 3))) {
			printk(OSST_DEB_MSG "%s:D: Injecting read error\n", tape_name(STp));
			STp->buffer->last_result_fatal = 1;
		}
#endif
	}
	return SRpnt;
}


/* Handle the write-behind checking (downs the semaphore) */
static void osst_write_behind_check(struct osst_tape *STp)
{
	struct osst_buffer * STbuffer;

	STbuffer = STp->buffer;

#if DEBUG
	if (STp->write_pending)
		STp->nbr_waits++;
	else
		STp->nbr_finished++;
#endif
	wait_for_completion(&(STp->wait));
	(STp->buffer)->last_SRpnt->sr_request->waiting = NULL;

	STp->buffer->syscall_result = osst_chk_result(STp, STp->buffer->last_SRpnt);

	if ((STp->buffer)->syscall_result)
		(STp->buffer)->syscall_result =
			osst_write_error_recovery(STp, &((STp->buffer)->last_SRpnt), 1);
	else
		STp->first_frame_position++;

	scsi_release_request((STp->buffer)->last_SRpnt);

	if (STbuffer->writing < STbuffer->buffer_bytes)
		printk(KERN_WARNING "osst :A: write_behind_check: something left in buffer!\n");

	STbuffer->buffer_bytes -= STbuffer->writing;
	STbuffer->writing = 0;

	return;
}



/* Onstream specific Routines */
/*
 * Initialize the OnStream AUX
 */
static void osst_init_aux(struct osst_tape * STp, int frame_type, int frame_seq_number,
					 int logical_blk_num, int blk_sz, int blk_cnt)
{
	os_aux_t       *aux = STp->buffer->aux;
	os_partition_t *par = &aux->partition;
	os_dat_t       *dat = &aux->dat;

	if (STp->raw) return;

	memset(aux, 0, sizeof(*aux));
	aux->format_id = htonl(0);
	memcpy(aux->application_sig, "LIN4", 4);
	aux->hdwr = htonl(0);
	aux->frame_type = frame_type;

	switch (frame_type) {
	  case	OS_FRAME_TYPE_HEADER:
		aux->update_frame_cntr    = htonl(STp->update_frame_cntr);
		par->partition_num        = OS_CONFIG_PARTITION;
		par->par_desc_ver         = OS_PARTITION_VERSION;
		par->wrt_pass_cntr        = htons(0xffff);
		/* 0-4 = reserved, 5-9 = header, 2990-2994 = header, 2995-2999 = reserved */
		par->first_frame_ppos     = htonl(0);
		par->last_frame_ppos      = htonl(0xbb7);
		aux->frame_seq_num        = htonl(0);
		aux->logical_blk_num_high = htonl(0);
		aux->logical_blk_num      = htonl(0);
		aux->next_mark_ppos       = htonl(STp->first_mark_ppos);
		break;
	  case	OS_FRAME_TYPE_DATA:
	  case	OS_FRAME_TYPE_MARKER:
		dat->dat_sz = 8;
		dat->reserved1 = 0;
		dat->entry_cnt = 1;
		dat->reserved3 = 0;
		dat->dat_list[0].blk_sz   = htonl(blk_sz);
		dat->dat_list[0].blk_cnt  = htons(blk_cnt);
		dat->dat_list[0].flags    = frame_type==OS_FRAME_TYPE_MARKER?
							OS_DAT_FLAGS_MARK:OS_DAT_FLAGS_DATA;
		dat->dat_list[0].reserved = 0;
	  case	OS_FRAME_TYPE_EOD:
		aux->update_frame_cntr    = htonl(0);
		par->partition_num        = OS_DATA_PARTITION;
		par->par_desc_ver         = OS_PARTITION_VERSION;
		par->wrt_pass_cntr        = htons(STp->wrt_pass_cntr);
		par->first_frame_ppos     = htonl(STp->first_data_ppos);
		par->last_frame_ppos      = htonl(STp->capacity);
		aux->frame_seq_num        = htonl(frame_seq_number);
		aux->logical_blk_num_high = htonl(0);
		aux->logical_blk_num      = htonl(logical_blk_num);
		break;
	  default: ; /* probably FILL */
	}
	aux->filemark_cnt = ntohl(STp->filemark_cnt);
	aux->phys_fm = ntohl(0xffffffff);
	aux->last_mark_ppos = ntohl(STp->last_mark_ppos);
	aux->last_mark_lbn  = ntohl(STp->last_mark_lbn);
}

/*
 * Verify that we have the correct tape frame
 */
static int osst_verify_frame(struct osst_tape * STp, int frame_seq_number, int quiet)
{
	char               * name = tape_name(STp);
	os_aux_t           * aux  = STp->buffer->aux;
	os_partition_t     * par  = &(aux->partition);
	struct st_partstat * STps = &(STp->ps[STp->partition]);
	int		     blk_cnt, blk_sz, i;

	if (STp->raw) {
		if (STp->buffer->syscall_result) {
			for (i=0; i < STp->buffer->sg_segs; i++)
				memset(page_address(STp->buffer->sg[i].page),
				       0, STp->buffer->sg[i].length);
			strcpy(STp->buffer->b_data, "READ ERROR ON FRAME");
                } else
			STp->buffer->buffer_bytes = OS_FRAME_SIZE;
		return 1;
	}
	if (STp->buffer->syscall_result) {
#if DEBUG
		printk(OSST_DEB_MSG "%s:D: Skipping frame, read error\n", name);
#endif
		return 0;
	}
	if (ntohl(aux->format_id) != 0) {
#if DEBUG
		printk(OSST_DEB_MSG "%s:D: Skipping frame, format_id %u\n", name, ntohl(aux->format_id));
#endif
		goto err_out;
	}
	if (memcmp(aux->application_sig, STp->application_sig, 4) != 0 &&
	    (memcmp(aux->application_sig, "LIN3", 4) != 0 || STp->linux_media_version != 4)) {
#if DEBUG
		printk(OSST_DEB_MSG "%s:D: Skipping frame, incorrect application signature\n", name);
#endif
		goto err_out;
	}
	if (par->partition_num != OS_DATA_PARTITION) {
		if (!STp->linux_media || STp->linux_media_version != 2) {
#if DEBUG
			printk(OSST_DEB_MSG "%s:D: Skipping frame, partition num %d\n",
					    name, par->partition_num);
#endif
			goto err_out;
		}
	}
	if (par->par_desc_ver != OS_PARTITION_VERSION) {
#if DEBUG
		printk(OSST_DEB_MSG "%s:D: Skipping frame, partition version %d\n", name, par->par_desc_ver);
#endif
		goto err_out;
	}
	if (ntohs(par->wrt_pass_cntr) != STp->wrt_pass_cntr) {
#if DEBUG
		printk(OSST_DEB_MSG "%s:D: Skipping frame, wrt_pass_cntr %d (expected %d)\n", 
				    name, ntohs(par->wrt_pass_cntr), STp->wrt_pass_cntr);
#endif
		goto err_out;
	}
	if (aux->frame_type != OS_FRAME_TYPE_DATA &&
	    aux->frame_type != OS_FRAME_TYPE_EOD &&
	    aux->frame_type != OS_FRAME_TYPE_MARKER) {
		if (!quiet)
#if DEBUG
			printk(OSST_DEB_MSG "%s:D: Skipping frame, frame type %x\n", name, aux->frame_type);
#endif
		goto err_out;
	}
	if (aux->frame_type == OS_FRAME_TYPE_EOD &&
	    STp->first_frame_position < STp->eod_frame_ppos) {
		printk(KERN_INFO "%s:I: Skipping premature EOD frame %d\n", name,
				 STp->first_frame_position);
		goto err_out;
	}
        if (frame_seq_number != -1 && ntohl(aux->frame_seq_num) != frame_seq_number) {
		if (!quiet)
#if DEBUG
			printk(OSST_DEB_MSG "%s:D: Skipping frame, sequence number %u (expected %d)\n", 
					    name, ntohl(aux->frame_seq_num), frame_seq_number);
#endif
		goto err_out;
	}
	if (aux->frame_type == OS_FRAME_TYPE_MARKER) {
		STps->eof = ST_FM_HIT;

		i = ntohl(aux->filemark_cnt);
		if (STp->header_cache != NULL && i < OS_FM_TAB_MAX && (i > STp->filemark_cnt ||
		    STp->first_frame_position - 1 != ntohl(STp->header_cache->dat_fm_tab.fm_tab_ent[i]))) {
#if DEBUG
			printk(OSST_DEB_MSG "%s:D: %s filemark %d at frame pos %d\n", name,
				  STp->header_cache->dat_fm_tab.fm_tab_ent[i] == 0?"Learned":"Corrected",
				  i, STp->first_frame_position - 1);
#endif
			STp->header_cache->dat_fm_tab.fm_tab_ent[i] = htonl(STp->first_frame_position - 1);
			if (i >= STp->filemark_cnt)
				 STp->filemark_cnt = i+1;
		}
	}
	if (aux->frame_type == OS_FRAME_TYPE_EOD) {
		STps->eof = ST_EOD_1;
		STp->frame_in_buffer = 1;
	}
	if (aux->frame_type == OS_FRAME_TYPE_DATA) {
                blk_cnt = ntohs(aux->dat.dat_list[0].blk_cnt);
		blk_sz  = ntohl(aux->dat.dat_list[0].blk_sz);
		STp->buffer->buffer_bytes = blk_cnt * blk_sz;
		STp->buffer->read_pointer = 0;
		STp->frame_in_buffer = 1;

		/* See what block size was used to write file */
		if (STp->block_size != blk_sz && blk_sz > 0) {
			printk(KERN_INFO
	    	"%s:I: File was written with block size %d%c, currently %d%c, adjusted to match.\n",
       				name, blk_sz<1024?blk_sz:blk_sz/1024,blk_sz<1024?'b':'k',
				STp->block_size<1024?STp->block_size:STp->block_size/1024,
				STp->block_size<1024?'b':'k');
			STp->block_size            = blk_sz;
			STp->buffer->buffer_blocks = OS_DATA_SIZE / blk_sz;
		}
		STps->eof = ST_NOEOF;
	}
        STp->frame_seq_number = ntohl(aux->frame_seq_num);
	STp->logical_blk_num  = ntohl(aux->logical_blk_num);
	return 1;

err_out:
	if (STp->read_error_frame == 0)
		STp->read_error_frame = STp->first_frame_position - 1;
	return 0;
}

/*
 * Wait for the unit to become Ready
 */
static int osst_wait_ready(struct osst_tape * STp, struct scsi_request ** aSRpnt,
				 unsigned timeout, int initial_delay)
{
	unsigned char		cmd[MAX_COMMAND_SIZE];
	struct scsi_request   * SRpnt;
	unsigned long		startwait = jiffies;
#if DEBUG
	int			dbg  = debugging;
	char    	      * name = tape_name(STp);

	printk(OSST_DEB_MSG "%s:D: Reached onstream wait ready\n", name);
#endif

	if (initial_delay > 0)
		msleep(jiffies_to_msecs(initial_delay));

	memset(cmd, 0, MAX_COMMAND_SIZE);
	cmd[0] = TEST_UNIT_READY;

	SRpnt = osst_do_scsi(*aSRpnt, STp, cmd, 0, DMA_NONE, STp->timeout, MAX_RETRIES, 1);
	*aSRpnt = SRpnt;
	if (!SRpnt) return (-EBUSY);

	while ( STp->buffer->syscall_result && time_before(jiffies, startwait + timeout*HZ) &&
	       (( SRpnt->sr_sense_buffer[2]  == 2 && SRpnt->sr_sense_buffer[12] == 4    &&
		 (SRpnt->sr_sense_buffer[13] == 1 || SRpnt->sr_sense_buffer[13] == 8)    ) ||
		( SRpnt->sr_sense_buffer[2]  == 6 && SRpnt->sr_sense_buffer[12] == 0x28 &&
		  SRpnt->sr_sense_buffer[13] == 0                                        )  )) {
#if DEBUG
	    if (debugging) {
		printk(OSST_DEB_MSG "%s:D: Sleeping in onstream wait ready\n", name);
		printk(OSST_DEB_MSG "%s:D: Turning off debugging for a while\n", name);
		debugging = 0;
	    }
#endif
	    msleep(100);

	    memset(cmd, 0, MAX_COMMAND_SIZE);
	    cmd[0] = TEST_UNIT_READY;

	    SRpnt = osst_do_scsi(SRpnt, STp, cmd, 0, DMA_NONE, STp->timeout, MAX_RETRIES, 1);
	}
	*aSRpnt = SRpnt;
#if DEBUG
	debugging = dbg;
#endif
	if ( STp->buffer->syscall_result &&
	     osst_write_error_recovery(STp, aSRpnt, 0) ) {
#if DEBUG
	    printk(OSST_DEB_MSG "%s:D: Abnormal exit from onstream wait ready\n", name);
	    printk(OSST_DEB_MSG "%s:D: Result = %d, Sense: 0=%02x, 2=%02x, 12=%02x, 13=%02x\n", name,
			STp->buffer->syscall_result, SRpnt->sr_sense_buffer[0], SRpnt->sr_sense_buffer[2],
			SRpnt->sr_sense_buffer[12], SRpnt->sr_sense_buffer[13]);
#endif
	    return (-EIO);
	}
#if DEBUG
	printk(OSST_DEB_MSG "%s:D: Normal exit from onstream wait ready\n", name);
#endif
	return 0;
}

/*
 * Wait for a tape to be inserted in the unit
 */
static int osst_wait_for_medium(struct osst_tape * STp, struct scsi_request ** aSRpnt, unsigned timeout)
{
	unsigned char		cmd[MAX_COMMAND_SIZE];
	struct scsi_request   * SRpnt;
	unsigned long		startwait = jiffies;
#if DEBUG
	int			dbg = debugging;
	char    	      * name = tape_name(STp);

	printk(OSST_DEB_MSG "%s:D: Reached onstream wait for medium\n", name);
#endif

	memset(cmd, 0, MAX_COMMAND_SIZE);
	cmd[0] = TEST_UNIT_READY;

	SRpnt = osst_do_scsi(*aSRpnt, STp, cmd, 0, DMA_NONE, STp->timeout, MAX_RETRIES, 1);
	*aSRpnt = SRpnt;
	if (!SRpnt) return (-EBUSY);

	while ( STp->buffer->syscall_result && time_before(jiffies, startwait + timeout*HZ) &&
		SRpnt->sr_sense_buffer[2]  == 2 && SRpnt->sr_sense_buffer[12] == 0x3a       &&
	        SRpnt->sr_sense_buffer[13] == 0                                             ) {
#if DEBUG
	    if (debugging) {
		printk(OSST_DEB_MSG "%s:D: Sleeping in onstream wait medium\n", name);
		printk(OSST_DEB_MSG "%s:D: Turning off debugging for a while\n", name);
		debugging = 0;
	    }
#endif
	    msleep(100);

	    memset(cmd, 0, MAX_COMMAND_SIZE);
	    cmd[0] = TEST_UNIT_READY;

	    SRpnt = osst_do_scsi(SRpnt, STp, cmd, 0, DMA_NONE, STp->timeout, MAX_RETRIES, 1);
	}
	*aSRpnt = SRpnt;
#if DEBUG
	debugging = dbg;
#endif
	if ( STp->buffer->syscall_result     && SRpnt->sr_sense_buffer[2]  != 2 &&
	     SRpnt->sr_sense_buffer[12] != 4 && SRpnt->sr_sense_buffer[13] == 1) {
#if DEBUG
	    printk(OSST_DEB_MSG "%s:D: Abnormal exit from onstream wait medium\n", name);
	    printk(OSST_DEB_MSG "%s:D: Result = %d, Sense: 0=%02x, 2=%02x, 12=%02x, 13=%02x\n", name,
			STp->buffer->syscall_result, SRpnt->sr_sense_buffer[0], SRpnt->sr_sense_buffer[2],
			SRpnt->sr_sense_buffer[12], SRpnt->sr_sense_buffer[13]);
#endif
	    return 0;
	}
#if DEBUG
	printk(OSST_DEB_MSG "%s:D: Normal exit from onstream wait medium\n", name);
#endif
	return 1;
}

static int osst_position_tape_and_confirm(struct osst_tape * STp, struct scsi_request ** aSRpnt, int frame)
{
	int	retval;

	osst_wait_ready(STp, aSRpnt, 15 * 60, 0);			/* TODO - can this catch a write error? */
	retval = osst_set_frame_position(STp, aSRpnt, frame, 0);
	if (retval) return (retval);
	osst_wait_ready(STp, aSRpnt, 15 * 60, OSST_WAIT_POSITION_COMPLETE);
	return (osst_get_frame_position(STp, aSRpnt));
}

/*
 * Wait for write(s) to complete
 */
static int osst_flush_drive_buffer(struct osst_tape * STp, struct scsi_request ** aSRpnt)
{
	unsigned char		cmd[MAX_COMMAND_SIZE];
	struct scsi_request   * SRpnt;
	int			result = 0;
	int			delay  = OSST_WAIT_WRITE_COMPLETE;
#if DEBUG
	char		      * name = tape_name(STp);

	printk(OSST_DEB_MSG "%s:D: Reached onstream flush drive buffer (write filemark)\n", name);
#endif

	memset(cmd, 0, MAX_COMMAND_SIZE);
	cmd[0] = WRITE_FILEMARKS;
	cmd[1] = 1;

	SRpnt = osst_do_scsi(*aSRpnt, STp, cmd, 0, DMA_NONE, STp->timeout, MAX_RETRIES, 1);
	*aSRpnt = SRpnt;
	if (!SRpnt) return (-EBUSY);
	if (STp->buffer->syscall_result) {
		if ((SRpnt->sr_sense_buffer[2] & 0x0f) == 2 && SRpnt->sr_sense_buffer[12] == 4) {
			if (SRpnt->sr_sense_buffer[13] == 8) {
				delay = OSST_WAIT_LONG_WRITE_COMPLETE;
			}
		} else
			result = osst_write_error_recovery(STp, aSRpnt, 0);
	}
	result |= osst_wait_ready(STp, aSRpnt, 5 * 60, delay);
	STp->ps[STp->partition].rw = OS_WRITING_COMPLETE;

	return (result);
}

#define OSST_POLL_PER_SEC 10
static int osst_wait_frame(struct osst_tape * STp, struct scsi_request ** aSRpnt, int curr, int minlast, int to)
{
	unsigned long	startwait = jiffies;
	char	      * name      = tape_name(STp);
#if DEBUG
	char	   notyetprinted  = 1;
#endif
	if (minlast >= 0 && STp->ps[STp->partition].rw != ST_READING)
		printk(KERN_ERR "%s:A: Waiting for frame without having initialized read!\n", name);

	while (time_before (jiffies, startwait + to*HZ))
	{ 
		int result;
		result = osst_get_frame_position(STp, aSRpnt);
		if (result == -EIO)
			if ((result = osst_write_error_recovery(STp, aSRpnt, 0)) == 0)
				return 0;	/* successful recovery leaves drive ready for frame */
		if (result < 0) break;
		if (STp->first_frame_position == curr &&
		    ((minlast < 0 &&
		      (signed)STp->last_frame_position > (signed)curr + minlast) ||
		     (minlast >= 0 && STp->cur_frames > minlast)
		    ) && result >= 0)
		{
#if DEBUG			
			if (debugging || jiffies - startwait >= 2*HZ/OSST_POLL_PER_SEC)
				printk (OSST_DEB_MSG
					"%s:D: Succ wait f fr %i (>%i): %i-%i %i (%i): %3li.%li s\n",
					name, curr, curr+minlast, STp->first_frame_position,
					STp->last_frame_position, STp->cur_frames,
					result, (jiffies-startwait)/HZ, 
					(((jiffies-startwait)%HZ)*10)/HZ);
#endif
			return 0;
		}
#if DEBUG
		if (jiffies - startwait >= 2*HZ/OSST_POLL_PER_SEC && notyetprinted)
		{
			printk (OSST_DEB_MSG "%s:D: Wait for frame %i (>%i): %i-%i %i (%i)\n",
				name, curr, curr+minlast, STp->first_frame_position,
				STp->last_frame_position, STp->cur_frames, result);
			notyetprinted--;
		}
#endif
		msleep(1000 / OSST_POLL_PER_SEC);
	}
#if DEBUG
	printk (OSST_DEB_MSG "%s:D: Fail wait f fr %i (>%i): %i-%i %i: %3li.%li s\n",
		name, curr, curr+minlast, STp->first_frame_position,
		STp->last_frame_position, STp->cur_frames,
		(jiffies-startwait)/HZ, (((jiffies-startwait)%HZ)*10)/HZ);
#endif	
	return -EBUSY;
}

static int osst_recover_wait_frame(struct osst_tape * STp, struct scsi_request ** aSRpnt, int writing)
{
	struct scsi_request   * SRpnt;
	unsigned char		cmd[MAX_COMMAND_SIZE];
	unsigned long   	startwait = jiffies;
	int			retval    = 1;
        char		      * name      = tape_name(STp);
                                                                                                                                
	if (writing) {
		char	mybuf[24];
		char  * olddata = STp->buffer->b_data;
		int	oldsize = STp->buffer->buffer_size;

		/* write zero fm then read pos - if shows write error, try to recover - if no progress, wait */

		memset(cmd, 0, MAX_COMMAND_SIZE);
		cmd[0] = WRITE_FILEMARKS;
		cmd[1] = 1;
		SRpnt = osst_do_scsi(*aSRpnt, STp, cmd, 0, DMA_NONE, STp->timeout,
								MAX_RETRIES, 1);

		while (retval && time_before (jiffies, startwait + 5*60*HZ)) {

			if (STp->buffer->syscall_result && (SRpnt->sr_sense_buffer[2] & 0x0f) != 2) {

				/* some failure - not just not-ready */
				retval = osst_write_error_recovery(STp, aSRpnt, 0);
				break;
			}
			set_current_state(TASK_INTERRUPTIBLE);
			schedule_timeout (HZ / OSST_POLL_PER_SEC);

			STp->buffer->b_data = mybuf; STp->buffer->buffer_size = 24;
			memset(cmd, 0, MAX_COMMAND_SIZE);
			cmd[0] = READ_POSITION;

			SRpnt = osst_do_scsi(SRpnt, STp, cmd, 20, DMA_FROM_DEVICE, STp->timeout,
										MAX_RETRIES, 1);

			retval = ( STp->buffer->syscall_result || (STp->buffer)->b_data[15] > 25 );
			STp->buffer->b_data = olddata; STp->buffer->buffer_size = oldsize;
		}
		if (retval)
			printk(KERN_ERR "%s:E: Device did not succeed to write buffered data\n", name);
	} else
		/* TODO - figure out which error conditions can be handled */
		if (STp->buffer->syscall_result)
			printk(KERN_WARNING
				"%s:W: Recover_wait_frame(read) cannot handle %02x:%02x:%02x\n", name,
					(*aSRpnt)->sr_sense_buffer[ 2] & 0x0f,
					(*aSRpnt)->sr_sense_buffer[12],
					(*aSRpnt)->sr_sense_buffer[13]);

	return retval;
}

/*
 * Read the next OnStream tape frame at the current location
 */
static int osst_read_frame(struct osst_tape * STp, struct scsi_request ** aSRpnt, int timeout)
{
	unsigned char		cmd[MAX_COMMAND_SIZE];
	struct scsi_request   * SRpnt;
	int			retval = 0;
#if DEBUG
	os_aux_t	      * aux    = STp->buffer->aux;
	char		      * name   = tape_name(STp);
#endif

	if (STp->poll)
		if (osst_wait_frame (STp, aSRpnt, STp->first_frame_position, 0, timeout))
			retval = osst_recover_wait_frame(STp, aSRpnt, 0);

	memset(cmd, 0, MAX_COMMAND_SIZE);
	cmd[0] = READ_6;
	cmd[1] = 1;
	cmd[4] = 1;

#if DEBUG
	if (debugging)
		printk(OSST_DEB_MSG "%s:D: Reading frame from OnStream tape\n", name);
#endif
	SRpnt = osst_do_scsi(*aSRpnt, STp, cmd, OS_FRAME_SIZE, DMA_FROM_DEVICE,
				      STp->timeout, MAX_RETRIES, 1);
	*aSRpnt = SRpnt;
	if (!SRpnt)
		return (-EBUSY);

	if ((STp->buffer)->syscall_result) {
	    retval = 1;
	    if (STp->read_error_frame == 0) {
		STp->read_error_frame = STp->first_frame_position;
#if DEBUG
		printk(OSST_DEB_MSG "%s:D: Recording read error at %d\n", name, STp->read_error_frame);
#endif
	    }
#if DEBUG
	    if (debugging)
		printk(OSST_DEB_MSG "%s:D: Sense: %2x %2x %2x %2x %2x %2x %2x %2x\n",
		   name,
		   SRpnt->sr_sense_buffer[0], SRpnt->sr_sense_buffer[1],
		   SRpnt->sr_sense_buffer[2], SRpnt->sr_sense_buffer[3],
		   SRpnt->sr_sense_buffer[4], SRpnt->sr_sense_buffer[5],
		   SRpnt->sr_sense_buffer[6], SRpnt->sr_sense_buffer[7]);
#endif
	}
	else
	    STp->first_frame_position++;
#if DEBUG
	if (debugging) {
	   char sig[8]; int i;
	   for (i=0;i<4;i++)
		   sig[i] = aux->application_sig[i]<32?'^':aux->application_sig[i];
	   sig[4] = '\0';
	   printk(OSST_DEB_MSG 
		"%s:D: AUX: %s UpdFrCt#%d Wpass#%d %s FrSeq#%d LogBlk#%d Qty=%d Sz=%d\n", name, sig,
			ntohl(aux->update_frame_cntr), ntohs(aux->partition.wrt_pass_cntr),
			aux->frame_type==1?"EOD":aux->frame_type==2?"MARK":
			aux->frame_type==8?"HEADR":aux->frame_type==0x80?"DATA":"FILL", 
			ntohl(aux->frame_seq_num), ntohl(aux->logical_blk_num),
			ntohs(aux->dat.dat_list[0].blk_cnt), ntohl(aux->dat.dat_list[0].blk_sz) );
	   if (aux->frame_type==2)
		printk(OSST_DEB_MSG "%s:D: mark_cnt=%d, last_mark_ppos=%d, last_mark_lbn=%d\n", name,
			ntohl(aux->filemark_cnt), ntohl(aux->last_mark_ppos), ntohl(aux->last_mark_lbn));
	   printk(OSST_DEB_MSG "%s:D: Exit read frame from OnStream tape with code %d\n", name, retval);
	}
#endif
	return (retval);
}

static int osst_initiate_read(struct osst_tape * STp, struct scsi_request ** aSRpnt)
{
	struct st_partstat    * STps   = &(STp->ps[STp->partition]);
	struct scsi_request   * SRpnt  ;
	unsigned char		cmd[MAX_COMMAND_SIZE];
	int			retval = 0;
	char		      * name   = tape_name(STp);

	if (STps->rw != ST_READING) {         /* Initialize read operation */
		if (STps->rw == ST_WRITING || STp->dirty) {
			STp->write_type = OS_WRITE_DATA;
                        osst_flush_write_buffer(STp, aSRpnt);
			osst_flush_drive_buffer(STp, aSRpnt);
		}
		STps->rw = ST_READING;
		STp->frame_in_buffer = 0;

		/*
		 *      Issue a read 0 command to get the OnStream drive
                 *      read frames into its buffer.
		 */
		memset(cmd, 0, MAX_COMMAND_SIZE);
		cmd[0] = READ_6;
		cmd[1] = 1;

#if DEBUG
		printk(OSST_DEB_MSG "%s:D: Start Read Ahead on OnStream tape\n", name);
#endif
		SRpnt   = osst_do_scsi(*aSRpnt, STp, cmd, 0, DMA_NONE, STp->timeout, MAX_RETRIES, 1);
		*aSRpnt = SRpnt;
		if ((retval = STp->buffer->syscall_result))
			printk(KERN_WARNING "%s:W: Error starting read ahead\n", name);
	}

	return retval;
}

static int osst_get_logical_frame(struct osst_tape * STp, struct scsi_request ** aSRpnt,
						int frame_seq_number, int quiet)
{
	struct st_partstat * STps  = &(STp->ps[STp->partition]);
	char		   * name  = tape_name(STp);
	int		     cnt   = 0,
			     bad   = 0,
			     past  = 0,
			     x,
			     position;

	/*
	 * If we want just any frame (-1) and there is a frame in the buffer, return it
	 */
	if (frame_seq_number == -1 && STp->frame_in_buffer) {
#if DEBUG
		printk(OSST_DEB_MSG "%s:D: Frame %d still in buffer\n", name, STp->frame_seq_number);
#endif
		return (STps->eof);
	}
	/*
         * Search and wait for the next logical tape frame
	 */
	while (1) {
		if (cnt++ > 400) {
                        printk(KERN_ERR "%s:E: Couldn't find logical frame %d, aborting\n",
					    name, frame_seq_number);
			if (STp->read_error_frame) {
				osst_set_frame_position(STp, aSRpnt, STp->read_error_frame, 0);
#if DEBUG
                        	printk(OSST_DEB_MSG "%s:D: Repositioning tape to bad frame %d\n",
						    name, STp->read_error_frame);
#endif
				STp->read_error_frame = 0;
				STp->abort_count++;
			}
			return (-EIO);
		}
#if DEBUG
		if (debugging)
			printk(OSST_DEB_MSG "%s:D: Looking for frame %d, attempt %d\n",
					  name, frame_seq_number, cnt);
#endif
		if ( osst_initiate_read(STp, aSRpnt)
                || ( (!STp->frame_in_buffer) && osst_read_frame(STp, aSRpnt, 30) ) ) {
			if (STp->raw)
				return (-EIO);
			position = osst_get_frame_position(STp, aSRpnt);
			if (position >= 0xbae && position < 0xbb8)
				position = 0xbb8;
			else if (position > STp->eod_frame_ppos || ++bad == 10) {
				position = STp->read_error_frame - 1;
				bad = 0;
			}
			else {
				position += 29;
				cnt      += 19;
			}
#if DEBUG
			printk(OSST_DEB_MSG "%s:D: Bad frame detected, positioning tape to block %d\n",
					 name, position);
#endif
			osst_set_frame_position(STp, aSRpnt, position, 0);
			continue;
		}
		if (osst_verify_frame(STp, frame_seq_number, quiet))
			break;
		if (osst_verify_frame(STp, -1, quiet)) {
			x = ntohl(STp->buffer->aux->frame_seq_num);
			if (STp->fast_open) {
				printk(KERN_WARNING
				       "%s:W: Found logical frame %d instead of %d after fast open\n",
				       name, x, frame_seq_number);
				STp->header_ok = 0;
				STp->read_error_frame = 0;
				return (-EIO);
			}
			if (x > frame_seq_number) {
				if (++past > 3) {
					/* positioning backwards did not bring us to the desired frame */
					position = STp->read_error_frame - 1;
				}
				else {
			        	position = osst_get_frame_position(STp, aSRpnt)
					         + frame_seq_number - x - 1;

					if (STp->first_frame_position >= 3000 && position < 3000)
						position -= 10;
				}
#if DEBUG
                                printk(OSST_DEB_MSG
				       "%s:D: Found logical frame %d while looking for %d: back up %d\n",
						name, x, frame_seq_number,
					       	STp->first_frame_position - position);
#endif
                        	osst_set_frame_position(STp, aSRpnt, position, 0);
				cnt += 10;
			}
			else
				past = 0;
		}
		if (osst_get_frame_position(STp, aSRpnt) == 0xbaf) {
#if DEBUG
			printk(OSST_DEB_MSG "%s:D: Skipping config partition\n", name);
#endif
			osst_set_frame_position(STp, aSRpnt, 0xbb8, 0);
			cnt--;
		}
		STp->frame_in_buffer = 0;
	}
	if (cnt > 1) {
		STp->recover_count++;
		STp->recover_erreg++;
		printk(KERN_WARNING "%s:I: Don't worry, Read error at position %d recovered\n", 
					name, STp->read_error_frame);
 	}
	STp->read_count++;

#if DEBUG
	if (debugging || STps->eof)
		printk(OSST_DEB_MSG
			"%s:D: Exit get logical frame (%d=>%d) from OnStream tape with code %d\n",
			name, frame_seq_number, STp->frame_seq_number, STps->eof);
#endif
	STp->fast_open = 0;
	STp->read_error_frame = 0;
	return (STps->eof);
}

static int osst_seek_logical_blk(struct osst_tape * STp, struct scsi_request ** aSRpnt, int logical_blk_num)
{
        struct st_partstat * STps = &(STp->ps[STp->partition]);
	char		   * name = tape_name(STp);
	int	retries    = 0;
	int	frame_seq_estimate, ppos_estimate, move;
	
	if (logical_blk_num < 0) logical_blk_num = 0;
#if DEBUG
	printk(OSST_DEB_MSG "%s:D: Seeking logical block %d (now at %d, size %d%c)\n",
				name, logical_blk_num, STp->logical_blk_num, 
				STp->block_size<1024?STp->block_size:STp->block_size/1024,
				STp->block_size<1024?'b':'k');
#endif
	/* Do we know where we are? */
	if (STps->drv_block >= 0) {
		move                = logical_blk_num - STp->logical_blk_num;
		if (move < 0) move -= (OS_DATA_SIZE / STp->block_size) - 1;
		move               /= (OS_DATA_SIZE / STp->block_size);
		frame_seq_estimate  = STp->frame_seq_number + move;
	} else
		frame_seq_estimate  = logical_blk_num * STp->block_size / OS_DATA_SIZE;

	if (frame_seq_estimate < 2980) ppos_estimate = frame_seq_estimate + 10;
	else			       ppos_estimate = frame_seq_estimate + 20;
	while (++retries < 10) {
	   if (ppos_estimate > STp->eod_frame_ppos-2) {
	       frame_seq_estimate += STp->eod_frame_ppos - 2 - ppos_estimate;
	       ppos_estimate       = STp->eod_frame_ppos - 2;
	   }
	   if (frame_seq_estimate < 0) {
	       frame_seq_estimate = 0;
	       ppos_estimate      = 10;
	   }
	   osst_set_frame_position(STp, aSRpnt, ppos_estimate, 0);
	   if (osst_get_logical_frame(STp, aSRpnt, frame_seq_estimate, 1) >= 0) {
	      /* we've located the estimated frame, now does it have our block? */
	      if (logical_blk_num <  STp->logical_blk_num ||
	          logical_blk_num >= STp->logical_blk_num + ntohs(STp->buffer->aux->dat.dat_list[0].blk_cnt)) {
		 if (STps->eof == ST_FM_HIT)
		    move = logical_blk_num < STp->logical_blk_num? -2 : 1;
		 else {
		    move                = logical_blk_num - STp->logical_blk_num;
		    if (move < 0) move -= (OS_DATA_SIZE / STp->block_size) - 1;
		    move               /= (OS_DATA_SIZE / STp->block_size);
		 }
		 if (!move) move = logical_blk_num > STp->logical_blk_num ? 1 : -1;
#if DEBUG
		 printk(OSST_DEB_MSG
			"%s:D: Seek retry %d at ppos %d fsq %d (est %d) lbn %d (need %d) move %d\n",
				name, retries, ppos_estimate, STp->frame_seq_number, frame_seq_estimate, 
				STp->logical_blk_num, logical_blk_num, move);
#endif
		 frame_seq_estimate += move;
		 ppos_estimate      += move;
		 continue;
	      } else {
		 STp->buffer->read_pointer  = (logical_blk_num - STp->logical_blk_num) * STp->block_size;
		 STp->buffer->buffer_bytes -= STp->buffer->read_pointer;
		 STp->logical_blk_num       =  logical_blk_num;
#if DEBUG
		 printk(OSST_DEB_MSG 
			"%s:D: Seek success at ppos %d fsq %d in_buf %d, bytes %d, ptr %d*%d\n",
				name, ppos_estimate, STp->frame_seq_number, STp->frame_in_buffer, 
				STp->buffer->buffer_bytes, STp->buffer->read_pointer / STp->block_size, 
				STp->block_size);
#endif
		 STps->drv_file = ntohl(STp->buffer->aux->filemark_cnt);
		 if (STps->eof == ST_FM_HIT) {
		     STps->drv_file++;
		     STps->drv_block = 0;
		 } else {
		     STps->drv_block = ntohl(STp->buffer->aux->last_mark_lbn)?
					  STp->logical_blk_num -
					     (STps->drv_file ? ntohl(STp->buffer->aux->last_mark_lbn) + 1 : 0):
					-1;
		 }
		 STps->eof = (STp->first_frame_position >= STp->eod_frame_ppos)?ST_EOD:ST_NOEOF;
		 return 0;
	      }
	   }
	   if (osst_get_logical_frame(STp, aSRpnt, -1, 1) < 0)
	      goto error;
	   /* we are not yet at the estimated frame, adjust our estimate of its physical position */
#if DEBUG
	   printk(OSST_DEB_MSG "%s:D: Seek retry %d at ppos %d fsq %d (est %d) lbn %d (need %d)\n", 
			   name, retries, ppos_estimate, STp->frame_seq_number, frame_seq_estimate, 
			   STp->logical_blk_num, logical_blk_num);
#endif
	   if (frame_seq_estimate != STp->frame_seq_number)
	      ppos_estimate += frame_seq_estimate - STp->frame_seq_number;
	   else
	      break;
	}
error:
	printk(KERN_ERR "%s:E: Couldn't seek to logical block %d (at %d), %d retries\n", 
			    name, logical_blk_num, STp->logical_blk_num, retries);
	return (-EIO);
}

/* The values below are based on the OnStream frame payload size of 32K == 2**15,
 * that is, OSST_FRAME_SHIFT + OSST_SECTOR_SHIFT must be 15. With a minimum block
 * size of 512 bytes, we need to be able to resolve 32K/512 == 64 == 2**6 positions
 * inside each frame. Finaly, OSST_SECTOR_MASK == 2**OSST_FRAME_SHIFT - 1.
 */
#define OSST_FRAME_SHIFT  6
#define OSST_SECTOR_SHIFT 9
#define OSST_SECTOR_MASK  0x03F

static int osst_get_sector(struct osst_tape * STp, struct scsi_request ** aSRpnt)
{
	int	sector;
#if DEBUG
	char  * name = tape_name(STp);
	
	printk(OSST_DEB_MSG 
		"%s:D: Positioned at ppos %d, frame %d, lbn %d, file %d, blk %d, %cptr %d, eof %d\n",
		name, STp->first_frame_position, STp->frame_seq_number, STp->logical_blk_num,
		STp->ps[STp->partition].drv_file, STp->ps[STp->partition].drv_block, 
		STp->ps[STp->partition].rw == ST_WRITING?'w':'r',
		STp->ps[STp->partition].rw == ST_WRITING?STp->buffer->buffer_bytes:
		STp->buffer->read_pointer, STp->ps[STp->partition].eof);
#endif
	/* do we know where we are inside a file? */
	if (STp->ps[STp->partition].drv_block >= 0) {
		sector = (STp->frame_in_buffer ? STp->first_frame_position-1 :
				STp->first_frame_position) << OSST_FRAME_SHIFT;
		if (STp->ps[STp->partition].rw == ST_WRITING)
		       	sector |= (STp->buffer->buffer_bytes >> OSST_SECTOR_SHIFT) & OSST_SECTOR_MASK;
		else
	       		sector |= (STp->buffer->read_pointer >> OSST_SECTOR_SHIFT) & OSST_SECTOR_MASK;
	} else {
		sector = osst_get_frame_position(STp, aSRpnt);
		if (sector > 0)
			sector <<= OSST_FRAME_SHIFT;
	}
	return sector;
}

static int osst_seek_sector(struct osst_tape * STp, struct scsi_request ** aSRpnt, int sector)
{
        struct st_partstat * STps   = &(STp->ps[STp->partition]);
	int		     frame  = sector >> OSST_FRAME_SHIFT,
			     offset = (sector & OSST_SECTOR_MASK) << OSST_SECTOR_SHIFT, 
			     r;
#if DEBUG
	char          * name = tape_name(STp);

	printk(OSST_DEB_MSG "%s:D: Seeking sector %d in frame %d at offset %d\n",
				name, sector, frame, offset);
#endif
	if (frame < 0 || frame >= STp->capacity) return (-ENXIO);

	if (frame <= STp->first_data_ppos) {
		STp->frame_seq_number = STp->logical_blk_num = STps->drv_file = STps->drv_block = 0;
		return (osst_set_frame_position(STp, aSRpnt, frame, 0));
	}
	r = osst_set_frame_position(STp, aSRpnt, offset?frame:frame-1, 0);
	if (r < 0) return r;

	r = osst_get_logical_frame(STp, aSRpnt, -1, 1);
	if (r < 0) return r;

	if (osst_get_frame_position(STp, aSRpnt) != (offset?frame+1:frame)) return (-EIO);

	if (offset) {
		STp->logical_blk_num      += offset / STp->block_size;
		STp->buffer->read_pointer  = offset;
		STp->buffer->buffer_bytes -= offset;
	} else {
		STp->frame_seq_number++;
		STp->frame_in_buffer       = 0;
		STp->logical_blk_num      += ntohs(STp->buffer->aux->dat.dat_list[0].blk_cnt);
		STp->buffer->buffer_bytes  = STp->buffer->read_pointer = 0;
	}
	STps->drv_file = ntohl(STp->buffer->aux->filemark_cnt);
	if (STps->eof == ST_FM_HIT) {
		STps->drv_file++;
		STps->drv_block = 0;
	} else {
		STps->drv_block = ntohl(STp->buffer->aux->last_mark_lbn)?
				    STp->logical_blk_num -
					(STps->drv_file ? ntohl(STp->buffer->aux->last_mark_lbn) + 1 : 0):
				  -1;
	}
	STps->eof       = (STp->first_frame_position >= STp->eod_frame_ppos)?ST_EOD:ST_NOEOF;
#if DEBUG
	printk(OSST_DEB_MSG 
		"%s:D: Now positioned at ppos %d, frame %d, lbn %d, file %d, blk %d, rptr %d, eof %d\n",
		name, STp->first_frame_position, STp->frame_seq_number, STp->logical_blk_num,
		STps->drv_file, STps->drv_block, STp->buffer->read_pointer, STps->eof);
#endif
	return 0;
}

/*
 * Read back the drive's internal buffer contents, as a part
 * of the write error recovery mechanism for old OnStream
 * firmware revisions.
 * Precondition for this function to work: all frames in the
 * drive's buffer must be of one type (DATA, MARK or EOD)!
 */
static int osst_read_back_buffer_and_rewrite(struct osst_tape * STp, struct scsi_request ** aSRpnt,
						unsigned int frame, unsigned int skip, int pending)
{
	struct scsi_request   * SRpnt = * aSRpnt;
	unsigned char	      * buffer, * p;
	unsigned char		cmd[MAX_COMMAND_SIZE];
	int			flag, new_frame, i;
	int			nframes          = STp->cur_frames;
	int			blks_per_frame   = ntohs(STp->buffer->aux->dat.dat_list[0].blk_cnt);
	int			frame_seq_number = ntohl(STp->buffer->aux->frame_seq_num)
						- (nframes + pending - 1);
	int			logical_blk_num  = ntohl(STp->buffer->aux->logical_blk_num) 
						- (nframes + pending - 1) * blks_per_frame;
	char		      * name             = tape_name(STp);
	unsigned long		startwait        = jiffies;
#if DEBUG
	int			dbg              = debugging;
#endif

	if ((buffer = (unsigned char *)vmalloc((nframes + 1) * OS_DATA_SIZE)) == NULL)
		return (-EIO);

	printk(KERN_INFO "%s:I: Reading back %d frames from drive buffer%s\n",
			 name, nframes, pending?" and one that was pending":"");

	osst_copy_from_buffer(STp->buffer, (p = &buffer[nframes * OS_DATA_SIZE]));
#if DEBUG
	if (pending && debugging)
		printk(OSST_DEB_MSG "%s:D: Pending frame %d (lblk %d), data %02x %02x %02x %02x\n",
				name, frame_seq_number + nframes,
			       	logical_blk_num + nframes * blks_per_frame,
			       	p[0], p[1], p[2], p[3]);
#endif
	for (i = 0, p = buffer; i < nframes; i++, p += OS_DATA_SIZE) {

		memset(cmd, 0, MAX_COMMAND_SIZE);
		cmd[0] = 0x3C;		/* Buffer Read           */
		cmd[1] = 6;		/* Retrieve Faulty Block */
		cmd[7] = 32768 >> 8;
		cmd[8] = 32768 & 0xff;

		SRpnt = osst_do_scsi(SRpnt, STp, cmd, OS_FRAME_SIZE, DMA_FROM_DEVICE,
					    STp->timeout, MAX_RETRIES, 1);
	
		if ((STp->buffer)->syscall_result || !SRpnt) {
			printk(KERN_ERR "%s:E: Failed to read frame back from OnStream buffer\n", name);
			vfree((void *)buffer);
			*aSRpnt = SRpnt;
			return (-EIO);
		}
		osst_copy_from_buffer(STp->buffer, p);
#if DEBUG
		if (debugging)
			printk(OSST_DEB_MSG "%s:D: Read back logical frame %d, data %02x %02x %02x %02x\n",
					  name, frame_seq_number + i, p[0], p[1], p[2], p[3]);
#endif
	}
	*aSRpnt = SRpnt;
	osst_get_frame_position(STp, aSRpnt);

#if DEBUG
	printk(OSST_DEB_MSG "%s:D: Frames left in buffer: %d\n", name, STp->cur_frames);
#endif
	/* Write synchronously so we can be sure we're OK again and don't have to recover recursively */
	/* In the header we don't actually re-write the frames that fail, just the ones after them */

	for (flag=1, new_frame=frame, p=buffer, i=0; i < nframes + pending; ) {

		if (flag) {
			if (STp->write_type == OS_WRITE_HEADER) {
				i += skip;
				p += skip * OS_DATA_SIZE;
			}
			else if (new_frame < 2990 && new_frame+skip+nframes+pending >= 2990)
				new_frame = 3000-i;
			else
				new_frame += skip;
#if DEBUG
			printk(OSST_DEB_MSG "%s:D: Position to frame %d, write fseq %d\n",
						name, new_frame+i, frame_seq_number+i);
#endif
			osst_set_frame_position(STp, aSRpnt, new_frame + i, 0);
			osst_wait_ready(STp, aSRpnt, 60, OSST_WAIT_POSITION_COMPLETE);
			osst_get_frame_position(STp, aSRpnt);
			SRpnt = * aSRpnt;

			if (new_frame > frame + 1000) {
				printk(KERN_ERR "%s:E: Failed to find writable tape media\n", name);
				vfree((void *)buffer);
				return (-EIO);
			}
			if ( i >= nframes + pending ) break;
			flag = 0;
		}
		osst_copy_to_buffer(STp->buffer, p);
		/*
		 * IMPORTANT: for error recovery to work, _never_ queue frames with mixed frame type!
		 */
		osst_init_aux(STp, STp->buffer->aux->frame_type, frame_seq_number+i,
			       	logical_blk_num + i*blks_per_frame,
			       	ntohl(STp->buffer->aux->dat.dat_list[0].blk_sz), blks_per_frame);
		memset(cmd, 0, MAX_COMMAND_SIZE);
		cmd[0] = WRITE_6;
		cmd[1] = 1;
		cmd[4] = 1;

#if DEBUG
		if (debugging)
			printk(OSST_DEB_MSG
				"%s:D: About to write frame %d, seq %d, lbn %d, data %02x %02x %02x %02x\n",
				name, new_frame+i, frame_seq_number+i, logical_blk_num + i*blks_per_frame,
				p[0], p[1], p[2], p[3]);
#endif
		SRpnt = osst_do_scsi(SRpnt, STp, cmd, OS_FRAME_SIZE, DMA_TO_DEVICE,
					    STp->timeout, MAX_RETRIES, 1);

		if (STp->buffer->syscall_result)
			flag = 1;
		else {
			p += OS_DATA_SIZE; i++;

			/* if we just sent the last frame, wait till all successfully written */
			if ( i == nframes + pending ) {
#if DEBUG
				printk(OSST_DEB_MSG "%s:D: Check re-write successful\n", name);
#endif
				memset(cmd, 0, MAX_COMMAND_SIZE);
				cmd[0] = WRITE_FILEMARKS;
				cmd[1] = 1;
				SRpnt = osst_do_scsi(SRpnt, STp, cmd, 0, DMA_NONE,
							    STp->timeout, MAX_RETRIES, 1);
#if DEBUG
				if (debugging) {
					printk(OSST_DEB_MSG "%s:D: Sleeping in re-write wait ready\n", name);
					printk(OSST_DEB_MSG "%s:D: Turning off debugging for a while\n", name);
					debugging = 0;
				}
#endif
				flag = STp->buffer->syscall_result;
				while ( !flag && time_before(jiffies, startwait + 60*HZ) ) {

					memset(cmd, 0, MAX_COMMAND_SIZE);
					cmd[0] = TEST_UNIT_READY;

					SRpnt = osst_do_scsi(SRpnt, STp, cmd, 0, DMA_NONE, STp->timeout,
												MAX_RETRIES, 1);

					if (SRpnt->sr_sense_buffer[2] == 2 && SRpnt->sr_sense_buffer[12] == 4 &&
					    (SRpnt->sr_sense_buffer[13] == 1 || SRpnt->sr_sense_buffer[13] == 8)) {
						/* in the process of becoming ready */
						msleep(100);
						continue;
					}
					if (STp->buffer->syscall_result)
						flag = 1;
					break;
				}
#if DEBUG
				debugging = dbg;
				printk(OSST_DEB_MSG "%s:D: Wait re-write finished\n", name);
#endif
			}
		}
		*aSRpnt = SRpnt;
		if (flag) {
			if ((SRpnt->sr_sense_buffer[ 2] & 0x0f) == 13 &&
			     SRpnt->sr_sense_buffer[12]         ==  0 &&
			     SRpnt->sr_sense_buffer[13]         ==  2) {
				printk(KERN_ERR "%s:E: Volume overflow in write error recovery\n", name);
				vfree((void *)buffer);
				return (-EIO);			/* hit end of tape = fail */
			}
			i = ((SRpnt->sr_sense_buffer[3] << 24) |
			     (SRpnt->sr_sense_buffer[4] << 16) |
			     (SRpnt->sr_sense_buffer[5] <<  8) |
			      SRpnt->sr_sense_buffer[6]        ) - new_frame;
			p = &buffer[i * OS_DATA_SIZE];
#if DEBUG
			printk(OSST_DEB_MSG "%s:D: Additional write error at %d\n", name, new_frame+i);
#endif
			osst_get_frame_position(STp, aSRpnt);
#if DEBUG
			printk(OSST_DEB_MSG "%s:D: reported frame positions: host = %d, tape = %d, buffer = %d\n",
					  name, STp->first_frame_position, STp->last_frame_position, STp->cur_frames);
#endif
		}
	}
	if (flag) {
		/* error recovery did not successfully complete */
		printk(KERN_ERR "%s:D: Write error recovery failed in %s\n", name,
				STp->write_type == OS_WRITE_HEADER?"header":"body");
	}
	if (!pending)
		osst_copy_to_buffer(STp->buffer, p);	/* so buffer content == at entry in all cases */
	vfree((void *)buffer);
	return 0;
}

static int osst_reposition_and_retry(struct osst_tape * STp, struct scsi_request ** aSRpnt,
					unsigned int frame, unsigned int skip, int pending)
{
	unsigned char		cmd[MAX_COMMAND_SIZE];
	struct scsi_request   * SRpnt;
	char		      * name      = tape_name(STp);
	int			expected  = 0;
	int			attempts  = 1000 / skip;
	int			flag      = 1;
	unsigned long		startwait = jiffies;
#if DEBUG
	int			dbg       = debugging;
#endif

	while (attempts && time_before(jiffies, startwait + 60*HZ)) {
		if (flag) {
#if DEBUG
			debugging = dbg;
#endif
			if (frame < 2990 && frame+skip+STp->cur_frames+pending >= 2990)
				frame = 3000-skip;
			expected = frame+skip+STp->cur_frames+pending;
#if DEBUG
			printk(OSST_DEB_MSG "%s:D: Position to fppos %d, re-write from fseq %d\n",
					  name, frame+skip, STp->frame_seq_number-STp->cur_frames-pending);
#endif
			osst_set_frame_position(STp, aSRpnt, frame + skip, 1);
			flag = 0;
			attempts--;
			set_current_state(TASK_INTERRUPTIBLE);
			schedule_timeout(HZ / 10);
		}
		if (osst_get_frame_position(STp, aSRpnt) < 0) {		/* additional write error */
#if DEBUG
			printk(OSST_DEB_MSG "%s:D: Addl error, host %d, tape %d, buffer %d\n",
					  name, STp->first_frame_position,
					  STp->last_frame_position, STp->cur_frames);
#endif
			frame = STp->last_frame_position;
			flag = 1;
			continue;
		}
		if (pending && STp->cur_frames < 50) {

			memset(cmd, 0, MAX_COMMAND_SIZE);
			cmd[0] = WRITE_6;
			cmd[1] = 1;
			cmd[4] = 1;
#if DEBUG
			printk(OSST_DEB_MSG "%s:D: About to write pending fseq %d at fppos %d\n",
					  name, STp->frame_seq_number-1, STp->first_frame_position);
#endif
			SRpnt = osst_do_scsi(*aSRpnt, STp, cmd, OS_FRAME_SIZE, DMA_TO_DEVICE,
						      STp->timeout, MAX_RETRIES, 1);
			*aSRpnt = SRpnt;

			if (STp->buffer->syscall_result) {		/* additional write error */
				if ((SRpnt->sr_sense_buffer[ 2] & 0x0f) == 13 &&
				     SRpnt->sr_sense_buffer[12]         ==  0 &&
				     SRpnt->sr_sense_buffer[13]         ==  2) {
					printk(KERN_ERR
					       "%s:E: Volume overflow in write error recovery\n",
					       name);
					break;				/* hit end of tape = fail */
				}
				flag = 1;
			}
			else
				pending = 0;

			continue;
		}
		if (STp->cur_frames == 0) {
#if DEBUG
			debugging = dbg;
			printk(OSST_DEB_MSG "%s:D: Wait re-write finished\n", name);
#endif
			if (STp->first_frame_position != expected) {
				printk(KERN_ERR "%s:A: Actual position %d - expected %d\n", 
						name, STp->first_frame_position, expected);
				return (-EIO);
			}
			return 0;
		}
#if DEBUG
		if (debugging) {
			printk(OSST_DEB_MSG "%s:D: Sleeping in re-write wait ready\n", name);
			printk(OSST_DEB_MSG "%s:D: Turning off debugging for a while\n", name);
			debugging = 0;
		}
#endif
		set_current_state(TASK_INTERRUPTIBLE);
		schedule_timeout(HZ / 10);
	}
	printk(KERN_ERR "%s:E: Failed to find valid tape media\n", name);
#if DEBUG
	debugging = dbg;
#endif
	return (-EIO);
}

/*
 * Error recovery algorithm for the OnStream tape.
 */

static int osst_write_error_recovery(struct osst_tape * STp, struct scsi_request ** aSRpnt, int pending)
{
	struct scsi_request * SRpnt  = * aSRpnt;
	struct st_partstat  * STps   = & STp->ps[STp->partition];
	char		    * name   = tape_name(STp);
	int		      retval = 0;
	int		      rw_state;
	unsigned int	      frame, skip;

	rw_state = STps->rw;

	if ((SRpnt->sr_sense_buffer[ 2] & 0x0f) != 3
	  || SRpnt->sr_sense_buffer[12]         != 12
	  || SRpnt->sr_sense_buffer[13]         != 0) {
#if DEBUG
		printk(OSST_DEB_MSG "%s:D: Write error recovery cannot handle %02x:%02x:%02x\n", name,
			SRpnt->sr_sense_buffer[2], SRpnt->sr_sense_buffer[12], SRpnt->sr_sense_buffer[13]);
#endif
		return (-EIO);
	}
	frame =	(SRpnt->sr_sense_buffer[3] << 24) |
		(SRpnt->sr_sense_buffer[4] << 16) |
		(SRpnt->sr_sense_buffer[5] <<  8) |
		 SRpnt->sr_sense_buffer[6];
	skip  =  SRpnt->sr_sense_buffer[9];
 
#if DEBUG
	printk(OSST_DEB_MSG "%s:D: Detected physical bad frame at %u, advised to skip %d\n", name, frame, skip);
#endif
	osst_get_frame_position(STp, aSRpnt);
#if DEBUG
	printk(OSST_DEB_MSG "%s:D: reported frame positions: host = %d, tape = %d\n",
			name, STp->first_frame_position, STp->last_frame_position);
#endif
	switch (STp->write_type) {
	   case OS_WRITE_DATA:
	   case OS_WRITE_EOD:
	   case OS_WRITE_NEW_MARK:
		printk(KERN_WARNING 
			"%s:I: Relocating %d buffered logical frames from position %u to %u\n",
			name, STp->cur_frames, frame, (frame + skip > 3000 && frame < 3000)?3000:frame + skip);
		if (STp->os_fw_rev >= 10600)
			retval = osst_reposition_and_retry(STp, aSRpnt, frame, skip, pending);
		else
			retval = osst_read_back_buffer_and_rewrite(STp, aSRpnt, frame, skip, pending);
		printk(KERN_WARNING "%s:%s: %sWrite error%srecovered\n", name,
			       	retval?"E"    :"I",
			       	retval?""     :"Don't worry, ",
			       	retval?" not ":" ");
		break;
	   case OS_WRITE_LAST_MARK:
		printk(KERN_ERR "%s:E: Bad frame in update last marker, fatal\n", name);
		osst_set_frame_position(STp, aSRpnt, frame + STp->cur_frames + pending, 0);
		retval = -EIO;
		break;
	   case OS_WRITE_HEADER:
		printk(KERN_WARNING "%s:I: Bad frame in header partition, skipped\n", name);
		retval = osst_read_back_buffer_and_rewrite(STp, aSRpnt, frame, 1, pending);
		break;
	   default:
		printk(KERN_INFO "%s:I: Bad frame in filler, ignored\n", name);
		osst_set_frame_position(STp, aSRpnt, frame + STp->cur_frames + pending, 0);
	}
	osst_get_frame_position(STp, aSRpnt);
#if DEBUG
	printk(OSST_DEB_MSG "%s:D: Positioning complete, cur_frames %d, pos %d, tape pos %d\n", 
			name, STp->cur_frames, STp->first_frame_position, STp->last_frame_position);
	printk(OSST_DEB_MSG "%s:D: next logical frame to write: %d\n", name, STp->logical_blk_num);
#endif
	if (retval == 0) {
		STp->recover_count++;
		STp->recover_erreg++;
	} else
		STp->abort_count++;

	STps->rw = rw_state;
	return retval;
}

static int osst_space_over_filemarks_backward(struct osst_tape * STp, struct scsi_request ** aSRpnt,
								 int mt_op, int mt_count)
{
	char  * name = tape_name(STp);
	int     cnt;
	int     last_mark_ppos = -1;

#if DEBUG
	printk(OSST_DEB_MSG "%s:D: Reached space_over_filemarks_backwards %d %d\n", name, mt_op, mt_count);
#endif
	if (osst_get_logical_frame(STp, aSRpnt, -1, 0) < 0) {
#if DEBUG
		printk(OSST_DEB_MSG "%s:D: Couldn't get logical blk num in space_filemarks_bwd\n", name);
#endif
		return -EIO;
	}
	if (STp->linux_media_version >= 4) {
		/*
		 * direct lookup in header filemark list
		 */
		cnt = ntohl(STp->buffer->aux->filemark_cnt);
		if (STp->header_ok                         && 
		    STp->header_cache != NULL              &&
		    (cnt - mt_count)  >= 0                 &&
		    (cnt - mt_count)   < OS_FM_TAB_MAX     &&
		    (cnt - mt_count)   < STp->filemark_cnt &&
		    STp->header_cache->dat_fm_tab.fm_tab_ent[cnt-1] == STp->buffer->aux->last_mark_ppos)

			last_mark_ppos = ntohl(STp->header_cache->dat_fm_tab.fm_tab_ent[cnt - mt_count]);
#if DEBUG
		if (STp->header_cache == NULL || (cnt - mt_count) < 0 || (cnt - mt_count) >= OS_FM_TAB_MAX)
			printk(OSST_DEB_MSG "%s:D: Filemark lookup fail due to %s\n", name,
			       STp->header_cache == NULL?"lack of header cache":"count out of range");
		else
			printk(OSST_DEB_MSG "%s:D: Filemark lookup: prev mark %d (%s), skip %d to %d\n",
				name, cnt,
				((cnt == -1 && ntohl(STp->buffer->aux->last_mark_ppos) == -1) ||
				 (STp->header_cache->dat_fm_tab.fm_tab_ent[cnt-1] ==
					 STp->buffer->aux->last_mark_ppos))?"match":"error",
			       mt_count, last_mark_ppos);
#endif
		if (last_mark_ppos > 10 && last_mark_ppos < STp->eod_frame_ppos) {
			osst_position_tape_and_confirm(STp, aSRpnt, last_mark_ppos);
			if (osst_get_logical_frame(STp, aSRpnt, -1, 0) < 0) {
#if DEBUG
				printk(OSST_DEB_MSG 
					"%s:D: Couldn't get logical blk num in space_filemarks\n", name);
#endif
				return (-EIO);
			}
			if (STp->buffer->aux->frame_type != OS_FRAME_TYPE_MARKER) {
				printk(KERN_WARNING "%s:W: Expected to find marker at ppos %d, not found\n",
						 name, last_mark_ppos);
				return (-EIO);
			}
			goto found;
		}
#if DEBUG
		printk(OSST_DEB_MSG "%s:D: Reverting to scan filemark backwards\n", name);
#endif
	}
	cnt = 0;
	while (cnt != mt_count) {
		last_mark_ppos = ntohl(STp->buffer->aux->last_mark_ppos);
		if (last_mark_ppos == -1)
			return (-EIO);
#if DEBUG
		printk(OSST_DEB_MSG "%s:D: Positioning to last mark at %d\n", name, last_mark_ppos);
#endif
		osst_position_tape_and_confirm(STp, aSRpnt, last_mark_ppos);
		cnt++;
		if (osst_get_logical_frame(STp, aSRpnt, -1, 0) < 0) {
#if DEBUG
			printk(OSST_DEB_MSG "%s:D: Couldn't get logical blk num in space_filemarks\n", name);
#endif
			return (-EIO);
		}
		if (STp->buffer->aux->frame_type != OS_FRAME_TYPE_MARKER) {
			printk(KERN_WARNING "%s:W: Expected to find marker at ppos %d, not found\n",
					 name, last_mark_ppos);
			return (-EIO);
		}
	}
found:
	if (mt_op == MTBSFM) {
		STp->frame_seq_number++;
		STp->frame_in_buffer      = 0;
		STp->buffer->buffer_bytes = 0;
		STp->buffer->read_pointer = 0;
		STp->logical_blk_num     += ntohs(STp->buffer->aux->dat.dat_list[0].blk_cnt);
	}
	return 0;
}

/*
 * ADRL 1.1 compatible "slow" space filemarks fwd version
 *
 * Just scans for the filemark sequentially.
 */
static int osst_space_over_filemarks_forward_slow(struct osst_tape * STp, struct scsi_request ** aSRpnt,
								     int mt_op, int mt_count)
{
	int	cnt = 0;
#if DEBUG
	char  * name = tape_name(STp);

	printk(OSST_DEB_MSG "%s:D: Reached space_over_filemarks_forward_slow %d %d\n", name, mt_op, mt_count);
#endif
	if (osst_get_logical_frame(STp, aSRpnt, -1, 0) < 0) {
#if DEBUG
		printk(OSST_DEB_MSG "%s:D: Couldn't get logical blk num in space_filemarks_fwd\n", name);
#endif
		return (-EIO);
	}
	while (1) {
		if (osst_get_logical_frame(STp, aSRpnt, -1, 0) < 0) {
#if DEBUG
			printk(OSST_DEB_MSG "%s:D: Couldn't get logical blk num in space_filemarks\n", name);
#endif
			return (-EIO);
		}
		if (STp->buffer->aux->frame_type == OS_FRAME_TYPE_MARKER)
			cnt++;
		if (STp->buffer->aux->frame_type == OS_FRAME_TYPE_EOD) {
#if DEBUG
			printk(OSST_DEB_MSG "%s:D: space_fwd: EOD reached\n", name);
#endif
			if (STp->first_frame_position > STp->eod_frame_ppos+1) {
#if DEBUG
				printk(OSST_DEB_MSG "%s:D: EOD position corrected (%d=>%d)\n",
					       	name, STp->eod_frame_ppos, STp->first_frame_position-1);
#endif
				STp->eod_frame_ppos = STp->first_frame_position-1;
			}
			return (-EIO);
		}
		if (cnt == mt_count)
			break;
		STp->frame_in_buffer = 0;
	}
	if (mt_op == MTFSF) {
		STp->frame_seq_number++;
		STp->frame_in_buffer      = 0;
		STp->buffer->buffer_bytes = 0;
		STp->buffer->read_pointer = 0;
		STp->logical_blk_num     += ntohs(STp->buffer->aux->dat.dat_list[0].blk_cnt);
	}
	return 0;
}

/*
 * Fast linux specific version of OnStream FSF
 */
static int osst_space_over_filemarks_forward_fast(struct osst_tape * STp, struct scsi_request ** aSRpnt,
								     int mt_op, int mt_count)
{
	char  * name = tape_name(STp);
	int	cnt  = 0,
		next_mark_ppos = -1;

#if DEBUG
	printk(OSST_DEB_MSG "%s:D: Reached space_over_filemarks_forward_fast %d %d\n", name, mt_op, mt_count);
#endif
	if (osst_get_logical_frame(STp, aSRpnt, -1, 0) < 0) {
#if DEBUG
		printk(OSST_DEB_MSG "%s:D: Couldn't get logical blk num in space_filemarks_fwd\n", name);
#endif
		return (-EIO);
	}

	if (STp->linux_media_version >= 4) {
		/*
		 * direct lookup in header filemark list
		 */
		cnt = ntohl(STp->buffer->aux->filemark_cnt) - 1;
		if (STp->header_ok                         && 
		    STp->header_cache != NULL              &&
		    (cnt + mt_count)   < OS_FM_TAB_MAX     &&
		    (cnt + mt_count)   < STp->filemark_cnt &&
		    ((cnt == -1 && ntohl(STp->buffer->aux->last_mark_ppos) == -1) ||
		     (STp->header_cache->dat_fm_tab.fm_tab_ent[cnt] == STp->buffer->aux->last_mark_ppos)))

			next_mark_ppos = ntohl(STp->header_cache->dat_fm_tab.fm_tab_ent[cnt + mt_count]);
#if DEBUG
		if (STp->header_cache == NULL || (cnt + mt_count) >= OS_FM_TAB_MAX)
			printk(OSST_DEB_MSG "%s:D: Filemark lookup fail due to %s\n", name,
			       STp->header_cache == NULL?"lack of header cache":"count out of range");
		else
			printk(OSST_DEB_MSG "%s:D: Filemark lookup: prev mark %d (%s), skip %d to %d\n",
			       name, cnt,
			       ((cnt == -1 && ntohl(STp->buffer->aux->last_mark_ppos) == -1) ||
				(STp->header_cache->dat_fm_tab.fm_tab_ent[cnt] ==
					 STp->buffer->aux->last_mark_ppos))?"match":"error",
			       mt_count, next_mark_ppos);
#endif
		if (next_mark_ppos <= 10 || next_mark_ppos > STp->eod_frame_ppos) {
#if DEBUG
			printk(OSST_DEB_MSG "%s:D: Reverting to slow filemark space\n", name);
#endif
			return osst_space_over_filemarks_forward_slow(STp, aSRpnt, mt_op, mt_count);
		} else {
			osst_position_tape_and_confirm(STp, aSRpnt, next_mark_ppos);
			if (osst_get_logical_frame(STp, aSRpnt, -1, 0) < 0) {
#if DEBUG
				printk(OSST_DEB_MSG "%s:D: Couldn't get logical blk num in space_filemarks\n",
						 name);
#endif
				return (-EIO);
			}
			if (STp->buffer->aux->frame_type != OS_FRAME_TYPE_MARKER) {
				printk(KERN_WARNING "%s:W: Expected to find marker at ppos %d, not found\n",
						 name, next_mark_ppos);
				return (-EIO);
			}
			if (ntohl(STp->buffer->aux->filemark_cnt) != cnt + mt_count) {
				printk(KERN_WARNING "%s:W: Expected to find marker %d at ppos %d, not %d\n",
						 name, cnt+mt_count, next_mark_ppos,
						 ntohl(STp->buffer->aux->filemark_cnt));
       				return (-EIO);
			}
		}
	} else {
		/*
		 * Find nearest (usually previous) marker, then jump from marker to marker
		 */
		while (1) {
			if (STp->buffer->aux->frame_type == OS_FRAME_TYPE_MARKER)
				break;
			if (STp->buffer->aux->frame_type == OS_FRAME_TYPE_EOD) {
#if DEBUG
				printk(OSST_DEB_MSG "%s:D: space_fwd: EOD reached\n", name);
#endif
				return (-EIO);
			}
			if (ntohl(STp->buffer->aux->filemark_cnt) == 0) {
				if (STp->first_mark_ppos == -1) {
#if DEBUG
					printk(OSST_DEB_MSG "%s:D: Reverting to slow filemark space\n", name);
#endif
					return osst_space_over_filemarks_forward_slow(STp, aSRpnt, mt_op, mt_count);
				}
				osst_position_tape_and_confirm(STp, aSRpnt, STp->first_mark_ppos);
				if (osst_get_logical_frame(STp, aSRpnt, -1, 0) < 0) {
#if DEBUG
					printk(OSST_DEB_MSG
					       "%s:D: Couldn't get logical blk num in space_filemarks_fwd_fast\n",
					       name);
#endif
					return (-EIO);
				}
				if (STp->buffer->aux->frame_type != OS_FRAME_TYPE_MARKER) {
					printk(KERN_WARNING "%s:W: Expected to find filemark at %d\n",
							 name, STp->first_mark_ppos);
					return (-EIO);
				}
			} else {
				if (osst_space_over_filemarks_backward(STp, aSRpnt, MTBSF, 1) < 0)
					return (-EIO);
				mt_count++;
			}
		}
		cnt++;
		while (cnt != mt_count) {
			next_mark_ppos = ntohl(STp->buffer->aux->next_mark_ppos);
			if (!next_mark_ppos || next_mark_ppos > STp->eod_frame_ppos) {
#if DEBUG
				printk(OSST_DEB_MSG "%s:D: Reverting to slow filemark space\n", name);
#endif
				return osst_space_over_filemarks_forward_slow(STp, aSRpnt, mt_op, mt_count - cnt);
			}
#if DEBUG
			else printk(OSST_DEB_MSG "%s:D: Positioning to next mark at %d\n", name, next_mark_ppos);
#endif
			osst_position_tape_and_confirm(STp, aSRpnt, next_mark_ppos);
			cnt++;
			if (osst_get_logical_frame(STp, aSRpnt, -1, 0) < 0) {
#if DEBUG
				printk(OSST_DEB_MSG "%s:D: Couldn't get logical blk num in space_filemarks\n",
						 name);
#endif
				return (-EIO);
			}
			if (STp->buffer->aux->frame_type != OS_FRAME_TYPE_MARKER) {
				printk(KERN_WARNING "%s:W: Expected to find marker at ppos %d, not found\n",
						 name, next_mark_ppos);
				return (-EIO);
			}
		}
	}
	if (mt_op == MTFSF) {
		STp->frame_seq_number++;
		STp->frame_in_buffer      = 0;
		STp->buffer->buffer_bytes = 0;
		STp->buffer->read_pointer = 0;
		STp->logical_blk_num     += ntohs(STp->buffer->aux->dat.dat_list[0].blk_cnt);
	}
	return 0;
}

/*
 * In debug mode, we want to see as many errors as possible
 * to test the error recovery mechanism.
 */
#if DEBUG
static void osst_set_retries(struct osst_tape * STp, struct scsi_request ** aSRpnt, int retries)
{
	unsigned char		cmd[MAX_COMMAND_SIZE];
	struct scsi_request   * SRpnt  = * aSRpnt;
	char		      * name   = tape_name(STp);

	memset(cmd, 0, MAX_COMMAND_SIZE);
	cmd[0] = MODE_SELECT;
	cmd[1] = 0x10;
	cmd[4] = NUMBER_RETRIES_PAGE_LENGTH + MODE_HEADER_LENGTH;

	(STp->buffer)->b_data[0] = cmd[4] - 1;
	(STp->buffer)->b_data[1] = 0;			/* Medium Type - ignoring */
	(STp->buffer)->b_data[2] = 0;			/* Reserved */
	(STp->buffer)->b_data[3] = 0;			/* Block Descriptor Length */
	(STp->buffer)->b_data[MODE_HEADER_LENGTH + 0] = NUMBER_RETRIES_PAGE | (1 << 7);
	(STp->buffer)->b_data[MODE_HEADER_LENGTH + 1] = 2;
	(STp->buffer)->b_data[MODE_HEADER_LENGTH + 2] = 4;
	(STp->buffer)->b_data[MODE_HEADER_LENGTH + 3] = retries;

	if (debugging)
	    printk(OSST_DEB_MSG "%s:D: Setting number of retries on OnStream tape to %d\n", name, retries);

	SRpnt = osst_do_scsi(SRpnt, STp, cmd, cmd[4], DMA_TO_DEVICE, STp->timeout, 0, 1);
	*aSRpnt = SRpnt;

	if ((STp->buffer)->syscall_result)
	    printk (KERN_ERR "%s:D: Couldn't set retries to %d\n", name, retries);
}
#endif


static int osst_write_filemark(struct osst_tape * STp, struct scsi_request ** aSRpnt)
{
	int	result;
	int	this_mark_ppos = STp->first_frame_position;
	int	this_mark_lbn  = STp->logical_blk_num;
#if DEBUG
	char  * name = tape_name(STp);
#endif

	if (STp->raw) return 0;

	STp->write_type = OS_WRITE_NEW_MARK;
#if DEBUG
	printk(OSST_DEB_MSG "%s:D: Writing Filemark %i at fppos %d (fseq %d, lblk %d)\n", 
	       name, STp->filemark_cnt, this_mark_ppos, STp->frame_seq_number, this_mark_lbn);
#endif
	STp->dirty = 1;
	result  = osst_flush_write_buffer(STp, aSRpnt);
	result |= osst_flush_drive_buffer(STp, aSRpnt);
	STp->last_mark_ppos = this_mark_ppos;
	STp->last_mark_lbn  = this_mark_lbn;
	if (STp->header_cache != NULL && STp->filemark_cnt < OS_FM_TAB_MAX)
		STp->header_cache->dat_fm_tab.fm_tab_ent[STp->filemark_cnt] = htonl(this_mark_ppos);
	if (STp->filemark_cnt++ == 0)
		STp->first_mark_ppos = this_mark_ppos;
	return result;
}

static int osst_write_eod(struct osst_tape * STp, struct scsi_request ** aSRpnt)
{
	int	result;
#if DEBUG
	char  * name = tape_name(STp);
#endif

	if (STp->raw) return 0;

	STp->write_type = OS_WRITE_EOD;
	STp->eod_frame_ppos = STp->first_frame_position;
#if DEBUG
	printk(OSST_DEB_MSG "%s:D: Writing EOD at fppos %d (fseq %d, lblk %d)\n", name,
			STp->eod_frame_ppos, STp->frame_seq_number, STp->logical_blk_num);
#endif
	STp->dirty = 1;

	result  = osst_flush_write_buffer(STp, aSRpnt);	
	result |= osst_flush_drive_buffer(STp, aSRpnt);
	STp->eod_frame_lfa = --(STp->frame_seq_number);
	return result;
}

static int osst_write_filler(struct osst_tape * STp, struct scsi_request ** aSRpnt, int where, int count)
{
	char * name = tape_name(STp);

#if DEBUG
	printk(OSST_DEB_MSG "%s:D: Reached onstream write filler group %d\n", name, where);
#endif
	osst_wait_ready(STp, aSRpnt, 60 * 5, 0);
	osst_set_frame_position(STp, aSRpnt, where, 0);
	STp->write_type = OS_WRITE_FILLER;
	while (count--) {
		memcpy(STp->buffer->b_data, "Filler", 6);
		STp->buffer->buffer_bytes = 6;
		STp->dirty = 1;
		if (osst_flush_write_buffer(STp, aSRpnt)) {
			printk(KERN_INFO "%s:I: Couldn't write filler frame\n", name);
			return (-EIO);
		}
	}
#if DEBUG
	printk(OSST_DEB_MSG "%s:D: Exiting onstream write filler group\n", name);
#endif
	return osst_flush_drive_buffer(STp, aSRpnt);
}

static int __osst_write_header(struct osst_tape * STp, struct scsi_request ** aSRpnt, int where, int count)
{
	char * name = tape_name(STp);
	int     result;

#if DEBUG
	printk(OSST_DEB_MSG "%s:D: Reached onstream write header group %d\n", name, where);
#endif
	osst_wait_ready(STp, aSRpnt, 60 * 5, 0);
	osst_set_frame_position(STp, aSRpnt, where, 0);
	STp->write_type = OS_WRITE_HEADER;
	while (count--) {
		osst_copy_to_buffer(STp->buffer, (unsigned char *)STp->header_cache);
		STp->buffer->buffer_bytes = sizeof(os_header_t);
		STp->dirty = 1;
		if (osst_flush_write_buffer(STp, aSRpnt)) {
			printk(KERN_INFO "%s:I: Couldn't write header frame\n", name);
			return (-EIO);
		}
	}
	result = osst_flush_drive_buffer(STp, aSRpnt);
#if DEBUG
	printk(OSST_DEB_MSG "%s:D: Write onstream header group %s\n", name, result?"failed":"done");
#endif
	return result;
}

static int osst_write_header(struct osst_tape * STp, struct scsi_request ** aSRpnt, int locate_eod)
{
	os_header_t * header;
	int	      result;
	char        * name = tape_name(STp);

#if DEBUG
	printk(OSST_DEB_MSG "%s:D: Writing tape header\n", name);
#endif
	if (STp->raw) return 0;

	if (STp->header_cache == NULL) {
		if ((STp->header_cache = (os_header_t *)vmalloc(sizeof(os_header_t))) == NULL) {
			printk(KERN_ERR "%s:E: Failed to allocate header cache\n", name);
			return (-ENOMEM);
		}
		memset(STp->header_cache, 0, sizeof(os_header_t));
#if DEBUG
		printk(OSST_DEB_MSG "%s:D: Allocated and cleared memory for header cache\n", name);
#endif
	}
	if (STp->header_ok) STp->update_frame_cntr++;
	else                STp->update_frame_cntr = 0;

	header = STp->header_cache;
	strcpy(header->ident_str, "ADR_SEQ");
	header->major_rev      = 1;
	header->minor_rev      = 4;
	header->ext_trk_tb_off = htons(17192);
	header->pt_par_num     = 1;
	header->partition[0].partition_num              = OS_DATA_PARTITION;
	header->partition[0].par_desc_ver               = OS_PARTITION_VERSION;
	header->partition[0].wrt_pass_cntr              = htons(STp->wrt_pass_cntr);
	header->partition[0].first_frame_ppos           = htonl(STp->first_data_ppos);
	header->partition[0].last_frame_ppos            = htonl(STp->capacity);
	header->partition[0].eod_frame_ppos             = htonl(STp->eod_frame_ppos);
	header->cfg_col_width                           = htonl(20);
	header->dat_col_width                           = htonl(1500);
	header->qfa_col_width                           = htonl(0);
	header->ext_track_tb.nr_stream_part             = 1;
	header->ext_track_tb.et_ent_sz                  = 32;
	header->ext_track_tb.dat_ext_trk_ey.et_part_num = 0;
	header->ext_track_tb.dat_ext_trk_ey.fmt         = 1;
	header->ext_track_tb.dat_ext_trk_ey.fm_tab_off  = htons(17736);
	header->ext_track_tb.dat_ext_trk_ey.last_hlb_hi = 0;
	header->ext_track_tb.dat_ext_trk_ey.last_hlb    = htonl(STp->eod_frame_lfa);
	header->ext_track_tb.dat_ext_trk_ey.last_pp	= htonl(STp->eod_frame_ppos);
	header->dat_fm_tab.fm_part_num                  = 0;
	header->dat_fm_tab.fm_tab_ent_sz                = 4;
	header->dat_fm_tab.fm_tab_ent_cnt               = htons(STp->filemark_cnt<OS_FM_TAB_MAX?
								STp->filemark_cnt:OS_FM_TAB_MAX);

	result  = __osst_write_header(STp, aSRpnt, 0xbae, 5);
	if (STp->update_frame_cntr == 0)
		    osst_write_filler(STp, aSRpnt, 0xbb3, 5);
	result &= __osst_write_header(STp, aSRpnt,     5, 5);

	if (locate_eod) {
#if DEBUG
		printk(OSST_DEB_MSG "%s:D: Locating back to eod frame addr %d\n", name, STp->eod_frame_ppos);
#endif
		osst_set_frame_position(STp, aSRpnt, STp->eod_frame_ppos, 0);
	}
	if (result)
		printk(KERN_ERR "%s:E: Write header failed\n", name);
	else {
		memcpy(STp->application_sig, "LIN4", 4);
		STp->linux_media         = 1;
		STp->linux_media_version = 4;
		STp->header_ok           = 1;
	}
	return result;
}

static int osst_reset_header(struct osst_tape * STp, struct scsi_request ** aSRpnt)
{
	if (STp->header_cache != NULL)
		memset(STp->header_cache, 0, sizeof(os_header_t));

	STp->logical_blk_num = STp->frame_seq_number = 0;
	STp->frame_in_buffer = 0;
	STp->eod_frame_ppos = STp->first_data_ppos = 0x0000000A;
	STp->filemark_cnt = 0;
	STp->first_mark_ppos = STp->last_mark_ppos = STp->last_mark_lbn = -1;
	return osst_write_header(STp, aSRpnt, 1);
}

static int __osst_analyze_headers(struct osst_tape * STp, struct scsi_request ** aSRpnt, int ppos)
{
	char        * name = tape_name(STp);
	os_header_t * header;
	os_aux_t    * aux;
	char          id_string[8];
	int	      linux_media_version,
		      update_frame_cntr;

	if (STp->raw)
		return 1;

	if (ppos == 5 || ppos == 0xbae || STp->buffer->syscall_result) {
		if (osst_set_frame_position(STp, aSRpnt, ppos, 0))
			printk(KERN_WARNING "%s:W: Couldn't position tape\n", name);
		osst_wait_ready(STp, aSRpnt, 60 * 15, 0);
		if (osst_initiate_read (STp, aSRpnt)) {
			printk(KERN_WARNING "%s:W: Couldn't initiate read\n", name);
			return 0;
		}
	}
	if (osst_read_frame(STp, aSRpnt, 180)) {
#if DEBUG
		printk(OSST_DEB_MSG "%s:D: Couldn't read header frame\n", name);
#endif
		return 0;
	}
	header = (os_header_t *) STp->buffer->b_data;	/* warning: only first segment addressable */
	aux = STp->buffer->aux;
	if (aux->frame_type != OS_FRAME_TYPE_HEADER) {
#if DEBUG
		printk(OSST_DEB_MSG "%s:D: Skipping non-header frame (%d)\n", name, ppos);
#endif
		return 0;
	}
	if (ntohl(aux->frame_seq_num)              != 0                   ||
	    ntohl(aux->logical_blk_num)            != 0                   ||
	          aux->partition.partition_num     != OS_CONFIG_PARTITION ||
	    ntohl(aux->partition.first_frame_ppos) != 0                   ||
	    ntohl(aux->partition.last_frame_ppos)  != 0xbb7               ) {
#if DEBUG
		printk(OSST_DEB_MSG "%s:D: Invalid header frame (%d,%d,%d,%d,%d)\n", name,
				ntohl(aux->frame_seq_num), ntohl(aux->logical_blk_num),
			       	aux->partition.partition_num, ntohl(aux->partition.first_frame_ppos),
			       	ntohl(aux->partition.last_frame_ppos));
#endif
		return 0;
	}
	if (strncmp(header->ident_str, "ADR_SEQ", 7) != 0 &&
	    strncmp(header->ident_str, "ADR-SEQ", 7) != 0) {
		strlcpy(id_string, header->ident_str, 8);
#if DEBUG
		printk(OSST_DEB_MSG "%s:D: Invalid header identification string %s\n", name, id_string);
#endif
		return 0;
	}
	update_frame_cntr = ntohl(aux->update_frame_cntr);
	if (update_frame_cntr < STp->update_frame_cntr) {
#if DEBUG
		printk(OSST_DEB_MSG "%s:D: Skipping frame %d with update_frame_counter %d<%d\n",
				   name, ppos, update_frame_cntr, STp->update_frame_cntr);
#endif
		return 0;
	}
	if (header->major_rev != 1 || header->minor_rev != 4 ) {
#if DEBUG
		printk(OSST_DEB_MSG "%s:D: %s revision %d.%d detected (1.4 supported)\n", 
				 name, (header->major_rev != 1 || header->minor_rev < 2 || 
				       header->minor_rev  > 4 )? "Invalid" : "Warning:",
				 header->major_rev, header->minor_rev);
#endif
		if (header->major_rev != 1 || header->minor_rev < 2 || header->minor_rev > 4)
			return 0;
	}
#if DEBUG
	if (header->pt_par_num != 1)
		printk(KERN_INFO "%s:W: %d partitions defined, only one supported\n", 
				 name, header->pt_par_num);
#endif
	memcpy(id_string, aux->application_sig, 4);
	id_string[4] = 0;
	if (memcmp(id_string, "LIN", 3) == 0) {
		STp->linux_media = 1;
		linux_media_version = id_string[3] - '0';
		if (linux_media_version != 4)
			printk(KERN_INFO "%s:I: Linux media version %d detected (current 4)\n",
					 name, linux_media_version);
	} else {
		printk(KERN_WARNING "%s:W: Non Linux media detected (%s)\n", name, id_string);
		return 0;
	}
	if (linux_media_version < STp->linux_media_version) {
#if DEBUG
		printk(OSST_DEB_MSG "%s:D: Skipping frame %d with linux_media_version %d\n",
				  name, ppos, linux_media_version);
#endif
		return 0;
	}
	if (linux_media_version > STp->linux_media_version) {
#if DEBUG
		printk(OSST_DEB_MSG "%s:D: Frame %d sets linux_media_version to %d\n",
				   name, ppos, linux_media_version);
#endif
		memcpy(STp->application_sig, id_string, 5);
		STp->linux_media_version = linux_media_version;
		STp->update_frame_cntr = -1;
	}
	if (update_frame_cntr > STp->update_frame_cntr) {
#if DEBUG
		printk(OSST_DEB_MSG "%s:D: Frame %d sets update_frame_counter to %d\n",
				   name, ppos, update_frame_cntr);
#endif
		if (STp->header_cache == NULL) {
			if ((STp->header_cache = (os_header_t *)vmalloc(sizeof(os_header_t))) == NULL) {
				printk(KERN_ERR "%s:E: Failed to allocate header cache\n", name);
				return 0;
			}
#if DEBUG
			printk(OSST_DEB_MSG "%s:D: Allocated memory for header cache\n", name);
#endif
		}
		osst_copy_from_buffer(STp->buffer, (unsigned char *)STp->header_cache);
		header = STp->header_cache;	/* further accesses from cached (full) copy */

		STp->wrt_pass_cntr     = ntohs(header->partition[0].wrt_pass_cntr);
		STp->first_data_ppos   = ntohl(header->partition[0].first_frame_ppos);
		STp->eod_frame_ppos    = ntohl(header->partition[0].eod_frame_ppos);
		STp->eod_frame_lfa     = ntohl(header->ext_track_tb.dat_ext_trk_ey.last_hlb);
		STp->filemark_cnt      = ntohl(aux->filemark_cnt);
		STp->first_mark_ppos   = ntohl(aux->next_mark_ppos);
		STp->last_mark_ppos    = ntohl(aux->last_mark_ppos);
		STp->last_mark_lbn     = ntohl(aux->last_mark_lbn);
		STp->update_frame_cntr = update_frame_cntr;
#if DEBUG
	printk(OSST_DEB_MSG "%s:D: Detected write pass %d, update frame counter %d, filemark counter %d\n",
			  name, STp->wrt_pass_cntr, STp->update_frame_cntr, STp->filemark_cnt);
	printk(OSST_DEB_MSG "%s:D: first data frame on tape = %d, last = %d, eod frame = %d\n", name,
			  STp->first_data_ppos,
			  ntohl(header->partition[0].last_frame_ppos),
			  ntohl(header->partition[0].eod_frame_ppos));
	printk(OSST_DEB_MSG "%s:D: first mark on tape = %d, last = %d, eod frame = %d\n", 
			  name, STp->first_mark_ppos, STp->last_mark_ppos, STp->eod_frame_ppos);
#endif
		if (header->minor_rev < 4 && STp->linux_media_version == 4) {
#if DEBUG
			printk(OSST_DEB_MSG "%s:D: Moving filemark list to ADR 1.4 location\n", name);
#endif
			memcpy((void *)header->dat_fm_tab.fm_tab_ent, 
			       (void *)header->old_filemark_list, sizeof(header->dat_fm_tab.fm_tab_ent));
			memset((void *)header->old_filemark_list, 0, sizeof(header->old_filemark_list));
		}
		if (header->minor_rev == 4   &&
		    (header->ext_trk_tb_off                          != htons(17192)               ||
		     header->partition[0].partition_num              != OS_DATA_PARTITION          ||
		     header->partition[0].par_desc_ver               != OS_PARTITION_VERSION       ||
		     header->partition[0].last_frame_ppos            != htonl(STp->capacity)       ||
		     header->cfg_col_width                           != htonl(20)                  ||
		     header->dat_col_width                           != htonl(1500)                ||
		     header->qfa_col_width                           != htonl(0)                   ||
		     header->ext_track_tb.nr_stream_part             != 1                          ||
		     header->ext_track_tb.et_ent_sz                  != 32                         ||
		     header->ext_track_tb.dat_ext_trk_ey.et_part_num != OS_DATA_PARTITION          ||
		     header->ext_track_tb.dat_ext_trk_ey.fmt         != 1                          ||
		     header->ext_track_tb.dat_ext_trk_ey.fm_tab_off  != htons(17736)               ||
		     header->ext_track_tb.dat_ext_trk_ey.last_hlb_hi != 0                          ||
		     header->ext_track_tb.dat_ext_trk_ey.last_pp     != htonl(STp->eod_frame_ppos) ||
		     header->dat_fm_tab.fm_part_num                  != OS_DATA_PARTITION          ||
		     header->dat_fm_tab.fm_tab_ent_sz                != 4                          ||
		     header->dat_fm_tab.fm_tab_ent_cnt               !=
			     htons(STp->filemark_cnt<OS_FM_TAB_MAX?STp->filemark_cnt:OS_FM_TAB_MAX)))
			printk(KERN_WARNING "%s:W: Failed consistency check ADR 1.4 format\n", name);

	}

	return 1;
}

static int osst_analyze_headers(struct osst_tape * STp, struct scsi_request ** aSRpnt)
{
	int	position, ppos;
	int	first, last;
	int	valid = 0;
	char  * name  = tape_name(STp);

	position = osst_get_frame_position(STp, aSRpnt);

	if (STp->raw) {
		STp->header_ok = STp->linux_media = 1;
		STp->linux_media_version = 0;
		return 1;
	}
	STp->header_ok = STp->linux_media = STp->linux_media_version = 0;
	STp->wrt_pass_cntr = STp->update_frame_cntr = -1;
	STp->eod_frame_ppos = STp->first_data_ppos = -1;
	STp->first_mark_ppos = STp->last_mark_ppos = STp->last_mark_lbn = -1;
#if DEBUG
	printk(OSST_DEB_MSG "%s:D: Reading header\n", name);
#endif

	/* optimization for speed - if we are positioned at ppos 10, read second group first  */	
	/* TODO try the ADR 1.1 locations for the second group if we have no valid one yet... */

	first = position==10?0xbae: 5;
	last  = position==10?0xbb3:10;

	for (ppos = first; ppos < last; ppos++)
		if (__osst_analyze_headers(STp, aSRpnt, ppos))
			valid = 1;

	first = position==10? 5:0xbae;
	last  = position==10?10:0xbb3;

	for (ppos = first; ppos < last; ppos++)
		if (__osst_analyze_headers(STp, aSRpnt, ppos))
			valid = 1;

	if (!valid) {
		printk(KERN_ERR "%s:E: Failed to find valid ADRL header, new media?\n", name);
		STp->eod_frame_ppos = STp->first_data_ppos = 0;
		osst_set_frame_position(STp, aSRpnt, 10, 0);
		return 0;
	}
	if (position <= STp->first_data_ppos) {
		position = STp->first_data_ppos;
		STp->ps[0].drv_file = STp->ps[0].drv_block = STp->frame_seq_number = STp->logical_blk_num = 0;
	}
	osst_set_frame_position(STp, aSRpnt, position, 0);
	STp->header_ok = 1;

	return 1;
}

static int osst_verify_position(struct osst_tape * STp, struct scsi_request ** aSRpnt)
{
	int	frame_position  = STp->first_frame_position;
	int	frame_seq_numbr = STp->frame_seq_number;
	int	logical_blk_num = STp->logical_blk_num;
       	int	halfway_frame   = STp->frame_in_buffer;
	int	read_pointer    = STp->buffer->read_pointer;
	int	prev_mark_ppos  = -1;
	int	actual_mark_ppos, i, n;
#if DEBUG
	char  * name = tape_name(STp);

	printk(OSST_DEB_MSG "%s:D: Verify that the tape is really the one we think before writing\n", name);
#endif
	osst_set_frame_position(STp, aSRpnt, frame_position - 1, 0);
	if (osst_get_logical_frame(STp, aSRpnt, -1, 0) < 0) {
#if DEBUG
		printk(OSST_DEB_MSG "%s:D: Couldn't get logical blk num in verify_position\n", name);
#endif
		return (-EIO);
	}
	if (STp->linux_media_version >= 4) {
		for (i=0; i<STp->filemark_cnt; i++)
			if ((n=ntohl(STp->header_cache->dat_fm_tab.fm_tab_ent[i])) < frame_position)
				prev_mark_ppos = n;
	} else
		prev_mark_ppos = frame_position - 1;  /* usually - we don't really know */
	actual_mark_ppos = STp->buffer->aux->frame_type == OS_FRAME_TYPE_MARKER ?
				frame_position - 1 : ntohl(STp->buffer->aux->last_mark_ppos);
	if (frame_position  != STp->first_frame_position                   ||
	    frame_seq_numbr != STp->frame_seq_number + (halfway_frame?0:1) ||
	    prev_mark_ppos  != actual_mark_ppos                            ) {
#if DEBUG
		printk(OSST_DEB_MSG "%s:D: Block mismatch: fppos %d-%d, fseq %d-%d, mark %d-%d\n", name,
				  STp->first_frame_position, frame_position, 
				  STp->frame_seq_number + (halfway_frame?0:1),
				  frame_seq_numbr, actual_mark_ppos, prev_mark_ppos);
#endif
		return (-EIO);
	}
	if (halfway_frame) {
		/* prepare buffer for append and rewrite on top of original */
		osst_set_frame_position(STp, aSRpnt, frame_position - 1, 0);
		STp->buffer->buffer_bytes  = read_pointer;
		STp->ps[STp->partition].rw = ST_WRITING;
		STp->dirty                 = 1;
	}
	STp->frame_in_buffer  = halfway_frame;
	STp->frame_seq_number = frame_seq_numbr;
	STp->logical_blk_num  = logical_blk_num;
	return 0;
}

/* Acc. to OnStream, the vers. numbering is the following:
 * X.XX for released versions (X=digit), 
 * XXXY for unreleased versions (Y=letter)
 * Ordering 1.05 < 106A < 106B < ...  < 106a < ... < 1.06
 * This fn makes monoton numbers out of this scheme ...
 */
static unsigned int osst_parse_firmware_rev (const char * str)
{
	if (str[1] == '.') {
		return (str[0]-'0')*10000
			+(str[2]-'0')*1000
			+(str[3]-'0')*100;
	} else {
		return (str[0]-'0')*10000
			+(str[1]-'0')*1000
			+(str[2]-'0')*100 - 100
			+(str[3]-'@');
	}
}

/*
 * Configure the OnStream SCII tape drive for default operation
 */
static int osst_configure_onstream(struct osst_tape *STp, struct scsi_request ** aSRpnt)
{
	unsigned char                  cmd[MAX_COMMAND_SIZE];
	char                         * name = tape_name(STp);
	struct scsi_request                 * SRpnt = * aSRpnt;
	osst_mode_parameter_header_t * header;
	osst_block_size_page_t       * bs;
	osst_capabilities_page_t     * cp;
	osst_tape_paramtr_page_t     * prm;
	int                            drive_buffer_size;

	if (STp->ready != ST_READY) {
#if DEBUG
	    printk(OSST_DEB_MSG "%s:D: Not Ready\n", name);
#endif
	    return (-EIO);
	}
	
	if (STp->os_fw_rev < 10600) {
	    printk(KERN_INFO "%s:I: Old OnStream firmware revision detected (%s),\n", name, STp->device->rev);
	    printk(KERN_INFO "%s:I: an upgrade to version 1.06 or above is recommended\n", name);
	}

	/*
	 * Configure 32.5KB (data+aux) frame size.
         * Get the current frame size from the block size mode page
	 */
	memset(cmd, 0, MAX_COMMAND_SIZE);
	cmd[0] = MODE_SENSE;
	cmd[1] = 8;
	cmd[2] = BLOCK_SIZE_PAGE;
	cmd[4] = BLOCK_SIZE_PAGE_LENGTH + MODE_HEADER_LENGTH;

	SRpnt = osst_do_scsi(SRpnt, STp, cmd, cmd[4], DMA_FROM_DEVICE, STp->timeout, 0, 1);
	if (SRpnt == NULL) {
#if DEBUG
 	    printk(OSST_DEB_MSG "osst :D: Busy\n");
#endif
	    return (-EBUSY);
	}
	*aSRpnt = SRpnt;
	if ((STp->buffer)->syscall_result != 0) {
	    printk (KERN_ERR "%s:E: Can't get tape block size mode page\n", name);
	    return (-EIO);
	}

	header = (osst_mode_parameter_header_t *) (STp->buffer)->b_data;
	bs = (osst_block_size_page_t *) ((STp->buffer)->b_data + sizeof(osst_mode_parameter_header_t) + header->bdl);

#if DEBUG
	printk(OSST_DEB_MSG "%s:D: 32KB play back: %s\n",   name, bs->play32     ? "Yes" : "No");
	printk(OSST_DEB_MSG "%s:D: 32.5KB play back: %s\n", name, bs->play32_5   ? "Yes" : "No");
	printk(OSST_DEB_MSG "%s:D: 32KB record: %s\n",      name, bs->record32   ? "Yes" : "No");
	printk(OSST_DEB_MSG "%s:D: 32.5KB record: %s\n",    name, bs->record32_5 ? "Yes" : "No");
#endif

	/*
	 * Configure default auto columns mode, 32.5KB transfer mode
	 */ 
	bs->one = 1;
	bs->play32 = 0;
	bs->play32_5 = 1;
	bs->record32 = 0;
	bs->record32_5 = 1;

	memset(cmd, 0, MAX_COMMAND_SIZE);
	cmd[0] = MODE_SELECT;
	cmd[1] = 0x10;
	cmd[4] = BLOCK_SIZE_PAGE_LENGTH + MODE_HEADER_LENGTH;

	SRpnt = osst_do_scsi(SRpnt, STp, cmd, cmd[4], DMA_TO_DEVICE, STp->timeout, 0, 1);
	*aSRpnt = SRpnt;
	if ((STp->buffer)->syscall_result != 0) {
	    printk (KERN_ERR "%s:E: Couldn't set tape block size mode page\n", name);
	    return (-EIO);
	}

#if DEBUG
	printk(KERN_INFO "%s:D: Drive Block Size changed to 32.5K\n", name);
	 /*
	 * In debug mode, we want to see as many errors as possible
	 * to test the error recovery mechanism.
	 */
	osst_set_retries(STp, aSRpnt, 0);
	SRpnt = * aSRpnt;
#endif

	/*
	 * Set vendor name to 'LIN4' for "Linux support version 4".
	 */

	memset(cmd, 0, MAX_COMMAND_SIZE);
	cmd[0] = MODE_SELECT;
	cmd[1] = 0x10;
	cmd[4] = VENDOR_IDENT_PAGE_LENGTH + MODE_HEADER_LENGTH;

	header->mode_data_length = VENDOR_IDENT_PAGE_LENGTH + MODE_HEADER_LENGTH - 1;
	header->medium_type      = 0;	/* Medium Type - ignoring */
	header->dsp              = 0;	/* Reserved */
	header->bdl              = 0;	/* Block Descriptor Length */
	
	(STp->buffer)->b_data[MODE_HEADER_LENGTH + 0] = VENDOR_IDENT_PAGE | (1 << 7);
	(STp->buffer)->b_data[MODE_HEADER_LENGTH + 1] = 6;
	(STp->buffer)->b_data[MODE_HEADER_LENGTH + 2] = 'L';
	(STp->buffer)->b_data[MODE_HEADER_LENGTH + 3] = 'I';
	(STp->buffer)->b_data[MODE_HEADER_LENGTH + 4] = 'N';
	(STp->buffer)->b_data[MODE_HEADER_LENGTH + 5] = '4';
	(STp->buffer)->b_data[MODE_HEADER_LENGTH + 6] = 0;
	(STp->buffer)->b_data[MODE_HEADER_LENGTH + 7] = 0;

	SRpnt = osst_do_scsi(SRpnt, STp, cmd, cmd[4], DMA_TO_DEVICE, STp->timeout, 0, 1);
	*aSRpnt = SRpnt;

	if ((STp->buffer)->syscall_result != 0) {
	    printk (KERN_ERR "%s:E: Couldn't set vendor name to %s\n", name, 
			(char *) ((STp->buffer)->b_data + MODE_HEADER_LENGTH + 2));
	    return (-EIO);
	}

	memset(cmd, 0, MAX_COMMAND_SIZE);
	cmd[0] = MODE_SENSE;
	cmd[1] = 8;
	cmd[2] = CAPABILITIES_PAGE;
	cmd[4] = CAPABILITIES_PAGE_LENGTH + MODE_HEADER_LENGTH;

	SRpnt = osst_do_scsi(SRpnt, STp, cmd, cmd[4], DMA_FROM_DEVICE, STp->timeout, 0, 1);
	*aSRpnt = SRpnt;

	if ((STp->buffer)->syscall_result != 0) {
	    printk (KERN_ERR "%s:E: Can't get capabilities page\n", name);
	    return (-EIO);
	}

	header = (osst_mode_parameter_header_t *) (STp->buffer)->b_data;
	cp     = (osst_capabilities_page_t    *) ((STp->buffer)->b_data +
		 sizeof(osst_mode_parameter_header_t) + header->bdl);

	drive_buffer_size = ntohs(cp->buffer_size) / 2;

	memset(cmd, 0, MAX_COMMAND_SIZE);
	cmd[0] = MODE_SENSE;
	cmd[1] = 8;
	cmd[2] = TAPE_PARAMTR_PAGE;
	cmd[4] = TAPE_PARAMTR_PAGE_LENGTH + MODE_HEADER_LENGTH;

	SRpnt = osst_do_scsi(SRpnt, STp, cmd, cmd[4], DMA_FROM_DEVICE, STp->timeout, 0, 1);
	*aSRpnt = SRpnt;

	if ((STp->buffer)->syscall_result != 0) {
	    printk (KERN_ERR "%s:E: Can't get tape parameter page\n", name);
	    return (-EIO);
	}

	header = (osst_mode_parameter_header_t *) (STp->buffer)->b_data;
	prm    = (osst_tape_paramtr_page_t    *) ((STp->buffer)->b_data +
		 sizeof(osst_mode_parameter_header_t) + header->bdl);

	STp->density  = prm->density;
	STp->capacity = ntohs(prm->segtrk) * ntohs(prm->trks);
#if DEBUG
	printk(OSST_DEB_MSG "%s:D: Density %d, tape length: %dMB, drive buffer size: %dKB\n",
			  name, STp->density, STp->capacity / 32, drive_buffer_size);
#endif

	return 0;
	
}


/* Step over EOF if it has been inadvertently crossed (ioctl not used because
   it messes up the block number). */
static int cross_eof(struct osst_tape *STp, struct scsi_request ** aSRpnt, int forward)
{
	int	result;
	char  * name = tape_name(STp);

#if DEBUG
	if (debugging)
		printk(OSST_DEB_MSG "%s:D: Stepping over filemark %s.\n",
	   			  name, forward ? "forward" : "backward");
#endif

	if (forward) {
	   /* assumes that the filemark is already read by the drive, so this is low cost */
	   result = osst_space_over_filemarks_forward_slow(STp, aSRpnt, MTFSF, 1);
	}
	else
	   /* assumes this is only called if we just read the filemark! */
	   result = osst_seek_logical_blk(STp, aSRpnt, STp->logical_blk_num - 1);

	if (result < 0)
	   printk(KERN_WARNING "%s:W: Stepping over filemark %s failed.\n",
				name, forward ? "forward" : "backward");

	return result;
}


/* Get the tape position. */

static int osst_get_frame_position(struct osst_tape *STp, struct scsi_request ** aSRpnt)
{
	unsigned char		scmd[MAX_COMMAND_SIZE];
	struct scsi_request   * SRpnt;
	int			result = 0;
	char    	      * name   = tape_name(STp);

	/* KG: We want to be able to use it for checking Write Buffer availability
	 *  and thus don't want to risk to overwrite anything. Exchange buffers ... */
	char		mybuf[24];
	char	      * olddata = STp->buffer->b_data;
	int		oldsize = STp->buffer->buffer_size;

	if (STp->ready != ST_READY) return (-EIO);

	memset (scmd, 0, MAX_COMMAND_SIZE);
	scmd[0] = READ_POSITION;

	STp->buffer->b_data = mybuf; STp->buffer->buffer_size = 24;
	SRpnt = osst_do_scsi(*aSRpnt, STp, scmd, 20, DMA_FROM_DEVICE,
				      STp->timeout, MAX_RETRIES, 1);
	if (!SRpnt) {
		STp->buffer->b_data = olddata; STp->buffer->buffer_size = oldsize;
		return (-EBUSY);
	}
	*aSRpnt = SRpnt;

	if (STp->buffer->syscall_result)
		result = ((SRpnt->sr_sense_buffer[2] & 0x0f) == 3) ? -EIO : -EINVAL;	/* 3: Write Error */

	if (result == -EINVAL)
		printk(KERN_ERR "%s:E: Can't read tape position.\n", name);
	else {
		if (result == -EIO) {	/* re-read position - this needs to preserve media errors */
			unsigned char mysense[16];
			memcpy (mysense, SRpnt->sr_sense_buffer, 16);
			memset (scmd, 0, MAX_COMMAND_SIZE);
			scmd[0] = READ_POSITION;
			STp->buffer->b_data = mybuf; STp->buffer->buffer_size = 24;
			SRpnt = osst_do_scsi(SRpnt, STp, scmd, 20, DMA_FROM_DEVICE,
						    STp->timeout, MAX_RETRIES, 1);
#if DEBUG
			printk(OSST_DEB_MSG "%s:D: Reread position, reason=[%02x:%02x:%02x], result=[%s%02x:%02x:%02x]\n",
					name, mysense[2], mysense[12], mysense[13], STp->buffer->syscall_result?"":"ok:",
					SRpnt->sr_sense_buffer[2],SRpnt->sr_sense_buffer[12],SRpnt->sr_sense_buffer[13]);
#endif
			if (!STp->buffer->syscall_result)
				memcpy (SRpnt->sr_sense_buffer, mysense, 16);
			else
				printk(KERN_WARNING "%s:W: Double error in get position\n", name);
		}
		STp->first_frame_position = ((STp->buffer)->b_data[4] << 24)
					  + ((STp->buffer)->b_data[5] << 16)
					  + ((STp->buffer)->b_data[6] << 8)
					  +  (STp->buffer)->b_data[7];
		STp->last_frame_position  = ((STp->buffer)->b_data[ 8] << 24)
					  + ((STp->buffer)->b_data[ 9] << 16)
					  + ((STp->buffer)->b_data[10] <<  8)
					  +  (STp->buffer)->b_data[11];
		STp->cur_frames           =  (STp->buffer)->b_data[15];
#if DEBUG
		if (debugging) {
			printk(OSST_DEB_MSG "%s:D: Drive Positions: host %d, tape %d%s, buffer %d\n", name,
					    STp->first_frame_position, STp->last_frame_position,
					    ((STp->buffer)->b_data[0]&0x80)?" (BOP)":
					    ((STp->buffer)->b_data[0]&0x40)?" (EOP)":"",
					    STp->cur_frames);
		}
#endif
		if (STp->cur_frames == 0 && STp->first_frame_position != STp->last_frame_position) {
#if DEBUG
			printk(OSST_DEB_MSG "%s:D: Correcting read position %d, %d, %d\n", name,
					STp->first_frame_position, STp->last_frame_position, STp->cur_frames);
#endif
			STp->first_frame_position = STp->last_frame_position;
		}
	}
	STp->buffer->b_data = olddata; STp->buffer->buffer_size = oldsize;

	return (result == 0 ? STp->first_frame_position : result);
}


/* Set the tape block */
static int osst_set_frame_position(struct osst_tape *STp, struct scsi_request ** aSRpnt, int ppos, int skip)
{
	unsigned char		scmd[MAX_COMMAND_SIZE];
	struct scsi_request   * SRpnt;
	struct st_partstat    * STps;
	int			result = 0;
	int			pp     = (ppos == 3000 && !skip)? 0 : ppos;
	char		      * name   = tape_name(STp);

	if (STp->ready != ST_READY) return (-EIO);

	STps = &(STp->ps[STp->partition]);

	if (ppos < 0 || ppos > STp->capacity) {
		printk(KERN_WARNING "%s:W: Reposition request %d out of range\n", name, ppos);
		pp = ppos = ppos < 0 ? 0 : (STp->capacity - 1);
		result = (-EINVAL);
	}

	do {
#if DEBUG
		if (debugging)
			printk(OSST_DEB_MSG "%s:D: Setting ppos to %d.\n", name, pp);
#endif
		memset (scmd, 0, MAX_COMMAND_SIZE);
		scmd[0] = SEEK_10;
		scmd[1] = 1;
		scmd[3] = (pp >> 24);
		scmd[4] = (pp >> 16);
		scmd[5] = (pp >> 8);
		scmd[6] =  pp;
		if (skip)
			scmd[9] = 0x80;

		SRpnt = osst_do_scsi(*aSRpnt, STp, scmd, 0, DMA_NONE, STp->long_timeout,
								MAX_RETRIES, 1);
		if (!SRpnt)
			return (-EBUSY);
		*aSRpnt  = SRpnt;

		if ((STp->buffer)->syscall_result != 0) {
#if DEBUG
			printk(OSST_DEB_MSG "%s:D: SEEK command from %d to %d failed.\n",
					name, STp->first_frame_position, pp);
#endif
			result = (-EIO);
		}
		if (pp != ppos)
			osst_wait_ready(STp, aSRpnt, 5 * 60, OSST_WAIT_POSITION_COMPLETE);
	} while ((pp != ppos) && (pp = ppos));
	STp->first_frame_position = STp->last_frame_position = ppos;
	STps->eof = ST_NOEOF;
	STps->at_sm = 0;
	STps->rw = ST_IDLE;
	STp->frame_in_buffer = 0;
	return result;
}

static int osst_write_trailer(struct osst_tape *STp, struct scsi_request ** aSRpnt, int leave_at_EOT)
{
	struct st_partstat * STps = &(STp->ps[STp->partition]);
	int result = 0;

	if (STp->write_type != OS_WRITE_NEW_MARK) {
		/* true unless the user wrote the filemark for us */
		result = osst_flush_drive_buffer(STp, aSRpnt);
		if (result < 0) goto out;
		result = osst_write_filemark(STp, aSRpnt);
		if (result < 0) goto out;

		if (STps->drv_file >= 0)
			STps->drv_file++ ;
		STps->drv_block = 0;
	}
	result = osst_write_eod(STp, aSRpnt);
	osst_write_header(STp, aSRpnt, leave_at_EOT);

	STps->eof = ST_FM;
out:
	return result;
}

/* osst versions of st functions - augmented and stripped to suit OnStream only */

/* Flush the write buffer (never need to write if variable blocksize). */
static int osst_flush_write_buffer(struct osst_tape *STp, struct scsi_request ** aSRpnt)
{
	int			offset, transfer, blks = 0;
	int			result = 0;
	unsigned char		cmd[MAX_COMMAND_SIZE];
	struct scsi_request   * SRpnt = *aSRpnt;
	struct st_partstat    * STps;
	char		      * name = tape_name(STp);

	if ((STp->buffer)->writing) {
		if (SRpnt == (STp->buffer)->last_SRpnt)
#if DEBUG
			{ printk(OSST_DEB_MSG
	 "%s:D: aSRpnt points to scsi_request that write_behind_check will release -- cleared\n", name);
#endif
			*aSRpnt = SRpnt = NULL;
#if DEBUG
			} else if (SRpnt)
				printk(OSST_DEB_MSG
	 "%s:D: aSRpnt does not point to scsi_request that write_behind_check will release -- strange\n", name);
#endif	
		osst_write_behind_check(STp);
		if ((STp->buffer)->syscall_result) {
#if DEBUG
			if (debugging)
				printk(OSST_DEB_MSG "%s:D: Async write error (flush) %x.\n",
				       name, (STp->buffer)->midlevel_result);
#endif
			if ((STp->buffer)->midlevel_result == INT_MAX)
				return (-ENOSPC);
			return (-EIO);
		}
	}

	result = 0;
	if (STp->dirty == 1) {

		STp->write_count++;
		STps     = &(STp->ps[STp->partition]);
		STps->rw = ST_WRITING;
		offset   = STp->buffer->buffer_bytes;
		blks     = (offset + STp->block_size - 1) / STp->block_size;
		transfer = OS_FRAME_SIZE;
		
		if (offset < OS_DATA_SIZE)
			osst_zero_buffer_tail(STp->buffer);

		if (STp->poll)
			if (osst_wait_frame (STp, aSRpnt, STp->first_frame_position, -50, 120))
				result = osst_recover_wait_frame(STp, aSRpnt, 1);

		memset(cmd, 0, MAX_COMMAND_SIZE);
		cmd[0] = WRITE_6;
		cmd[1] = 1;
		cmd[4] = 1;

		switch	(STp->write_type) {
		   case OS_WRITE_DATA:
#if DEBUG
   			if (debugging)
				printk(OSST_DEB_MSG "%s:D: Writing %d blocks to frame %d, lblks %d-%d\n",
					name, blks, STp->frame_seq_number, 
					STp->logical_blk_num - blks, STp->logical_blk_num - 1);
#endif
			osst_init_aux(STp, OS_FRAME_TYPE_DATA, STp->frame_seq_number++,
				      STp->logical_blk_num - blks, STp->block_size, blks);
			break;
		   case OS_WRITE_EOD:
			osst_init_aux(STp, OS_FRAME_TYPE_EOD, STp->frame_seq_number++,
				      STp->logical_blk_num, 0, 0);
			break;
		   case OS_WRITE_NEW_MARK:
			osst_init_aux(STp, OS_FRAME_TYPE_MARKER, STp->frame_seq_number++,
				      STp->logical_blk_num++, 0, blks=1);
			break;
		   case OS_WRITE_HEADER:
			osst_init_aux(STp, OS_FRAME_TYPE_HEADER, 0, 0, 0, blks=0);
			break;
		default: /* probably FILLER */
			osst_init_aux(STp, OS_FRAME_TYPE_FILL, 0, 0, 0, 0);
		}
#if DEBUG
		if (debugging)
			printk(OSST_DEB_MSG "%s:D: Flushing %d bytes, Transfering %d bytes in %d lblocks.\n",
			  			 name, offset, transfer, blks);
#endif

		SRpnt = osst_do_scsi(*aSRpnt, STp, cmd, transfer, DMA_TO_DEVICE,
					      STp->timeout, MAX_RETRIES, 1);
		*aSRpnt = SRpnt;
		if (!SRpnt)
			return (-EBUSY);

		if ((STp->buffer)->syscall_result != 0) {
#if DEBUG
			printk(OSST_DEB_MSG
				"%s:D: write sense [0]=0x%02x [2]=%02x [12]=%02x [13]=%02x\n",
				name, SRpnt->sr_sense_buffer[0], SRpnt->sr_sense_buffer[2],
				SRpnt->sr_sense_buffer[12], SRpnt->sr_sense_buffer[13]);
#endif
			if ((SRpnt->sr_sense_buffer[0] & 0x70) == 0x70 &&
			    (SRpnt->sr_sense_buffer[2] & 0x40) && /* FIXME - SC-30 drive doesn't assert EOM bit */
			    (SRpnt->sr_sense_buffer[2] & 0x0f) == NO_SENSE) {
				STp->dirty = 0;
				(STp->buffer)->buffer_bytes = 0;
				result = (-ENOSPC);
			}
			else {
				if (osst_write_error_recovery(STp, aSRpnt, 1)) {
					printk(KERN_ERR "%s:E: Error on flush write.\n", name);
					result = (-EIO);
				}
			}
			STps->drv_block = (-1);		/* FIXME - even if write recovery succeeds? */
		}
		else {
			STp->first_frame_position++;
			STp->dirty = 0;
			(STp->buffer)->buffer_bytes = 0;
		}
	}
#if DEBUG
	printk(OSST_DEB_MSG "%s:D: Exit flush write buffer with code %d\n", name, result);
#endif
	return result;
}


/* Flush the tape buffer. The tape will be positioned correctly unless
   seek_next is true. */
static int osst_flush_buffer(struct osst_tape * STp, struct scsi_request ** aSRpnt, int seek_next)
{
	struct st_partstat * STps;
	int    backspace = 0, result = 0;
#if DEBUG
	char * name = tape_name(STp);
#endif

	/*
	 * If there was a bus reset, block further access
	 * to this device.
	 */
	if( STp->pos_unknown)
		return (-EIO);

	if (STp->ready != ST_READY)
		return 0;

	STps = &(STp->ps[STp->partition]);
	if (STps->rw == ST_WRITING || STp->dirty) {	/* Writing */
		STp->write_type = OS_WRITE_DATA;
		return osst_flush_write_buffer(STp, aSRpnt);
	}
	if (STp->block_size == 0)
		return 0;

#if DEBUG
	printk(OSST_DEB_MSG "%s:D: Reached flush (read) buffer\n", name);
#endif

	if (!STp->can_bsr) {
		backspace = ((STp->buffer)->buffer_bytes + (STp->buffer)->read_pointer) / STp->block_size -
			    ((STp->buffer)->read_pointer + STp->block_size - 1        ) / STp->block_size ;
		(STp->buffer)->buffer_bytes = 0;
		(STp->buffer)->read_pointer = 0;
		STp->frame_in_buffer = 0;		/* FIXME is this relevant w. OSST? */
	}

	if (!seek_next) {
		if (STps->eof == ST_FM_HIT) {
			result = cross_eof(STp, aSRpnt, 0); /* Back over the EOF hit */
			if (!result)
				STps->eof = ST_NOEOF;
			else {
				if (STps->drv_file >= 0)
					STps->drv_file++;
				STps->drv_block = 0;
			}
		}
		if (!result && backspace > 0)	/* TODO -- design and run a test case for this */
			result = osst_seek_logical_blk(STp, aSRpnt, STp->logical_blk_num - backspace);
	}
	else if (STps->eof == ST_FM_HIT) {
		if (STps->drv_file >= 0)
			STps->drv_file++;
		STps->drv_block = 0;
		STps->eof = ST_NOEOF;
	}

	return result;
}

static int osst_write_frame(struct osst_tape * STp, struct scsi_request ** aSRpnt, int synchronous)
{
	unsigned char		cmd[MAX_COMMAND_SIZE];
	struct scsi_request   * SRpnt;
	int			blks;
#if DEBUG
	char		      * name = tape_name(STp);
#endif

	if ((!STp-> raw) && (STp->first_frame_position == 0xbae)) { /* _must_ preserve buffer! */
#if DEBUG
		printk(OSST_DEB_MSG "%s:D: Reaching config partition.\n", name);
#endif
		if (osst_flush_drive_buffer(STp, aSRpnt) < 0) {
			return (-EIO);
		}
		/* error recovery may have bumped us past the header partition */
		if (osst_get_frame_position(STp, aSRpnt) < 0xbb8) {
#if DEBUG
			printk(OSST_DEB_MSG "%s:D: Skipping over config partition.\n", name);
#endif
		osst_position_tape_and_confirm(STp, aSRpnt, 0xbb8);
		}
	}

	if (STp->poll)
		if (osst_wait_frame (STp, aSRpnt, STp->first_frame_position, -48, 120))
			if (osst_recover_wait_frame(STp, aSRpnt, 1))
				return (-EIO);

//	osst_build_stats(STp, &SRpnt);

	STp->ps[STp->partition].rw = ST_WRITING;
	STp->write_type            = OS_WRITE_DATA;
			
	memset(cmd, 0, MAX_COMMAND_SIZE);
	cmd[0]   = WRITE_6;
	cmd[1]   = 1;
	cmd[4]   = 1;						/* one frame at a time... */
	blks     = STp->buffer->buffer_bytes / STp->block_size;
#if DEBUG
	if (debugging)
		printk(OSST_DEB_MSG "%s:D: Writing %d blocks to frame %d, lblks %d-%d\n", name, blks, 
			STp->frame_seq_number, STp->logical_blk_num - blks, STp->logical_blk_num - 1);
#endif
	osst_init_aux(STp, OS_FRAME_TYPE_DATA, STp->frame_seq_number++,
		      STp->logical_blk_num - blks, STp->block_size, blks);

#if DEBUG
	if (!synchronous)
		STp->write_pending = 1;
#endif
	SRpnt = osst_do_scsi(*aSRpnt, STp, cmd, OS_FRAME_SIZE, DMA_TO_DEVICE, STp->timeout,
									MAX_RETRIES, synchronous);
	if (!SRpnt)
		return (-EBUSY);
	*aSRpnt = SRpnt;

	if (synchronous) {
		if (STp->buffer->syscall_result != 0) {
#if DEBUG
			if (debugging)
				printk(OSST_DEB_MSG "%s:D: Error on write:\n", name);
#endif
			if ((SRpnt->sr_sense_buffer[0] & 0x70) == 0x70 &&
			    (SRpnt->sr_sense_buffer[2] & 0x40)) {
				if ((SRpnt->sr_sense_buffer[2] & 0x0f) == VOLUME_OVERFLOW)
					return (-ENOSPC);
			}
			else {
				if (osst_write_error_recovery(STp, aSRpnt, 1))
					return (-EIO);
			}
		}
		else
			STp->first_frame_position++;
	}

	STp->write_count++;

	return 0;
}

/* Lock or unlock the drive door. Don't use when struct scsi_request allocated. */
static int do_door_lock(struct osst_tape * STp, int do_lock)
{
	int retval, cmd;

	cmd = do_lock ? SCSI_IOCTL_DOORLOCK : SCSI_IOCTL_DOORUNLOCK;
#if DEBUG
	printk(OSST_DEB_MSG "%s:D: %socking drive door.\n", tape_name(STp), do_lock ? "L" : "Unl");
#endif
	retval = scsi_ioctl(STp->device, cmd, NULL);
	if (!retval) {
		STp->door_locked = do_lock ? ST_LOCKED_EXPLICIT : ST_UNLOCKED;
	}
	else {
		STp->door_locked = ST_LOCK_FAILS;
	}
	return retval;
}

/* Set the internal state after reset */
static void reset_state(struct osst_tape *STp)
{
	int i;
	struct st_partstat *STps;

	STp->pos_unknown = 0;
	for (i = 0; i < ST_NBR_PARTITIONS; i++) {
		STps = &(STp->ps[i]);
		STps->rw = ST_IDLE;
		STps->eof = ST_NOEOF;
		STps->at_sm = 0;
		STps->last_block_valid = 0;
		STps->drv_block = -1;
		STps->drv_file = -1;
	}
}
				

/* Entry points to osst */

/* Write command */
static ssize_t osst_write(struct file * filp, const char __user * buf, size_t count, loff_t *ppos)
{
	ssize_t		      total, retval = 0;
	ssize_t		      i, do_count, blks, transfer;
	int		      write_threshold;
	int		      doing_write = 0;
	const char   __user * b_point;
	struct scsi_request * SRpnt = NULL;
	struct st_modedef   * STm;
	struct st_partstat  * STps;
	struct osst_tape    * STp  = filp->private_data;
	char		    * name = tape_name(STp);


	if (down_interruptible(&STp->lock))
		return (-ERESTARTSYS);

	/*
	 * If we are in the middle of error recovery, don't let anyone
	 * else try and use this device.  Also, if error recovery fails, it
	 * may try and take the device offline, in which case all further
	 * access to the device is prohibited.
	 */
	if( !scsi_block_when_processing_errors(STp->device) ) {
		retval = (-ENXIO);
		goto out;
	}
	
	if (STp->ready != ST_READY) {
		if (STp->ready == ST_NO_TAPE)
			retval = (-ENOMEDIUM);
		else
			retval = (-EIO);
		goto out;
	}
	STm = &(STp->modes[STp->current_mode]);
	if (!STm->defined) {
		retval = (-ENXIO);
		goto out;
	}
	if (count == 0)
		goto out;

	/*
	 * If there was a bus reset, block further access
	 * to this device.
	 */
	if (STp->pos_unknown) {
		retval = (-EIO);
		goto out;
	}

#if DEBUG
	if (!STp->in_use) {
		printk(OSST_DEB_MSG "%s:D: Incorrect device.\n", name);
		retval = (-EIO);
		goto out;
	}
#endif

	if (STp->write_prot) {
		retval = (-EACCES);
		goto out;
	}

	/* Write must be integral number of blocks */
	if (STp->block_size != 0 && (count % STp->block_size) != 0) {
		printk(KERN_ERR "%s:E: Write (%Zd bytes) not multiple of tape block size (%d%c).\n",
				       name, count, STp->block_size<1024?
				       STp->block_size:STp->block_size/1024, STp->block_size<1024?'b':'k');
		retval = (-EINVAL);
		goto out;
	}

	if (STp->first_frame_position >= STp->capacity - OSST_EOM_RESERVE) {
		printk(KERN_ERR "%s:E: Write truncated at EOM early warning (frame %d).\n",
				       name, STp->first_frame_position);
		retval = (-ENOSPC);
		goto out;
	}

	if (STp->do_auto_lock && STp->door_locked == ST_UNLOCKED && !do_door_lock(STp, 1))
		STp->door_locked = ST_LOCKED_AUTO;

	STps = &(STp->ps[STp->partition]);

	if (STps->rw == ST_READING) {
#if DEBUG
		printk(OSST_DEB_MSG "%s:D: Switching from read to write at file %d, block %d\n", name, 
					STps->drv_file, STps->drv_block);
#endif
		retval = osst_flush_buffer(STp, &SRpnt, 0);
		if (retval)
			goto out;
		STps->rw = ST_IDLE;
	}
	if (STps->rw != ST_WRITING) {
		/* Are we totally rewriting this tape? */
		if (!STp->header_ok ||
		    (STp->first_frame_position == STp->first_data_ppos && STps->drv_block < 0) ||
		    (STps->drv_file == 0 && STps->drv_block == 0)) {
			STp->wrt_pass_cntr++;
#if DEBUG
			printk(OSST_DEB_MSG "%s:D: Allocating next write pass counter: %d\n",
						  name, STp->wrt_pass_cntr);
#endif
			osst_reset_header(STp, &SRpnt);
			STps->drv_file = STps->drv_block = 0;
		}
		/* Do we know where we'll be writing on the tape? */
		else {
			if ((STp->fast_open && osst_verify_position(STp, &SRpnt)) ||
			  		STps->drv_file < 0 || STps->drv_block < 0) {
				if (STp->first_frame_position == STp->eod_frame_ppos) {	/* at EOD */
			  		STps->drv_file = STp->filemark_cnt;
			  		STps->drv_block = 0;
				}
				else {
					/* We have no idea where the tape is positioned - give up */
#if DEBUG
					printk(OSST_DEB_MSG
						"%s:D: Cannot write at indeterminate position.\n", name);
#endif
					retval = (-EIO);
					goto out;
				}
      			}	  
			if ((STps->drv_file + STps->drv_block) > 0 && STps->drv_file < STp->filemark_cnt) {
				STp->filemark_cnt = STps->drv_file;
				STp->last_mark_ppos =
				       	ntohl(STp->header_cache->dat_fm_tab.fm_tab_ent[STp->filemark_cnt-1]);
				printk(KERN_WARNING
					"%s:W: Overwriting file %d with old write pass counter %d\n",
						name, STps->drv_file, STp->wrt_pass_cntr);
				printk(KERN_WARNING
					"%s:W: may lead to stale data being accepted on reading back!\n",
						name);
#if DEBUG
				printk(OSST_DEB_MSG
				  "%s:D: resetting filemark count to %d and last mark ppos,lbn to %d,%d\n",
					name, STp->filemark_cnt, STp->last_mark_ppos, STp->last_mark_lbn);
#endif
			}
		}
		STp->fast_open = 0;
	}
	if (!STp->header_ok) {
#if DEBUG
		printk(OSST_DEB_MSG "%s:D: Write cannot proceed without valid headers\n", name);
#endif
		retval = (-EIO);
		goto out;
	}

	if ((STp->buffer)->writing) {
if (SRpnt) printk(KERN_ERR "%s:A: Not supposed to have SRpnt at line %d\n", name, __LINE__);
		osst_write_behind_check(STp);
		if ((STp->buffer)->syscall_result) {
#if DEBUG
		if (debugging)
			printk(OSST_DEB_MSG "%s:D: Async write error (write) %x.\n", name,
						 (STp->buffer)->midlevel_result);
#endif
		if ((STp->buffer)->midlevel_result == INT_MAX)
			STps->eof = ST_EOM_OK;
		else
			STps->eof = ST_EOM_ERROR;
		}
	}
	if (STps->eof == ST_EOM_OK) {
		retval = (-ENOSPC);
		goto out;
	}
	else if (STps->eof == ST_EOM_ERROR) {
		retval = (-EIO);
		goto out;
	}

	/* Check the buffer readability in cases where copy_user might catch
		 the problems after some tape movement. */
	if ((copy_from_user(&i, buf, 1) != 0 ||
	     copy_from_user(&i, buf + count - 1, 1) != 0)) {
		retval = (-EFAULT);
		goto out;
	}

	if (!STm->do_buffer_writes) {
		write_threshold = 1;
	}
	else
		write_threshold = (STp->buffer)->buffer_blocks * STp->block_size;
	if (!STm->do_async_writes)
		write_threshold--;

	total = count;
#if DEBUG
	if (debugging)
		printk(OSST_DEB_MSG "%s:D: Writing %d bytes to file %d block %d lblk %d fseq %d fppos %d\n",
				name, count, STps->drv_file, STps->drv_block,
				STp->logical_blk_num, STp->frame_seq_number, STp->first_frame_position);
#endif
	b_point = buf;
	while ((STp->buffer)->buffer_bytes + count > write_threshold)
	{
		doing_write = 1;
		do_count = (STp->buffer)->buffer_blocks * STp->block_size -
			   (STp->buffer)->buffer_bytes;
		if (do_count > count)
			do_count = count;

		i = append_to_buffer(b_point, STp->buffer, do_count);
		if (i) {
			retval = i;
			goto out;
		}

		blks = do_count / STp->block_size;
		STp->logical_blk_num += blks;  /* logical_blk_num is incremented as data is moved from user */
  
		i = osst_write_frame(STp, &SRpnt, 1);

		if (i == (-ENOSPC)) {
			transfer = STp->buffer->writing;	/* FIXME -- check this logic */
			if (transfer <= do_count) {
				filp->f_pos += do_count - transfer;
				count -= do_count - transfer;
				if (STps->drv_block >= 0) {
					STps->drv_block += (do_count - transfer) / STp->block_size;
				}
				STps->eof = ST_EOM_OK;
				retval = (-ENOSPC);		/* EOM within current request */
#if DEBUG
				if (debugging)
				      printk(OSST_DEB_MSG "%s:D: EOM with %d bytes unwritten.\n",
							     name, transfer);
#endif
			}
			else {
				STps->eof = ST_EOM_ERROR;
				STps->drv_block = (-1);		/* Too cautious? */
				retval = (-EIO);		/* EOM for old data */
#if DEBUG
				if (debugging)
				      printk(OSST_DEB_MSG "%s:D: EOM with lost data.\n", name);
#endif
			}
		}
		else
			retval = i;
			
		if (retval < 0) {
			if (SRpnt != NULL) {
				scsi_release_request(SRpnt);
				SRpnt = NULL;
			}
			STp->buffer->buffer_bytes = 0;
			STp->dirty = 0;
			if (count < total)
				retval = total - count;
			goto out;
		}

		filp->f_pos += do_count;
		b_point += do_count;
		count -= do_count;
		if (STps->drv_block >= 0) {
			STps->drv_block += blks;
		}
		STp->buffer->buffer_bytes = 0;
		STp->dirty = 0;
	}  /* end while write threshold exceeded */

	if (count != 0) {
		STp->dirty = 1;
		i = append_to_buffer(b_point, STp->buffer, count);
		if (i) {
			retval = i;
			goto out;
		}
		blks = count / STp->block_size;
		STp->logical_blk_num += blks;
		if (STps->drv_block >= 0) {
			STps->drv_block += blks;
		}
		filp->f_pos += count;
		count = 0;
	}

	if (doing_write && (STp->buffer)->syscall_result != 0) {
		retval = (STp->buffer)->syscall_result;
		goto out;
	}

	if (STm->do_async_writes && ((STp->buffer)->buffer_bytes >= STp->write_threshold)) { 
		/* Schedule an asynchronous write */
		(STp->buffer)->writing = ((STp->buffer)->buffer_bytes /
					   STp->block_size) * STp->block_size;
		STp->dirty = !((STp->buffer)->writing ==
				          (STp->buffer)->buffer_bytes);

		i = osst_write_frame(STp, &SRpnt, 0);
		if (i < 0) {
			retval = (-EIO);
			goto out;
		}
		SRpnt = NULL;			/* Prevent releasing this request! */
	}
	STps->at_sm &= (total == 0);
	if (total > 0)
		STps->eof = ST_NOEOF;

	retval = total;

out:
	if (SRpnt != NULL) scsi_release_request(SRpnt);

	up(&STp->lock);

	return retval;
}


/* Read command */
static ssize_t osst_read(struct file * filp, char __user * buf, size_t count, loff_t *ppos)
{
	ssize_t		      total, retval = 0;
	ssize_t		      i, transfer;
	int		      special;
	struct st_modedef   * STm;
	struct st_partstat  * STps;
	struct scsi_request * SRpnt = NULL;
	struct osst_tape    * STp   = filp->private_data;
	char		    * name  = tape_name(STp);


	if (down_interruptible(&STp->lock))
		return (-ERESTARTSYS);

	/*
	 * If we are in the middle of error recovery, don't let anyone
	 * else try and use this device.  Also, if error recovery fails, it
	 * may try and take the device offline, in which case all further
	 * access to the device is prohibited.
	 */
	if( !scsi_block_when_processing_errors(STp->device) ) {
		retval = (-ENXIO);
		goto out;
	}
	
	if (STp->ready != ST_READY) {
		if (STp->ready == ST_NO_TAPE)
			retval = (-ENOMEDIUM);
		else
			retval = (-EIO);
		goto out;
	}
	STm = &(STp->modes[STp->current_mode]);
	if (!STm->defined) {
		retval = (-ENXIO);
		goto out;
	}
#if DEBUG
	if (!STp->in_use) {
		printk(OSST_DEB_MSG "%s:D: Incorrect device.\n", name);
		retval = (-EIO);
		goto out;
	}
#endif
	/* Must have initialized medium */
	if (!STp->header_ok) {
		retval = (-EIO);
		goto out;
	}

	if (STp->do_auto_lock && STp->door_locked == ST_UNLOCKED && !do_door_lock(STp, 1))
		STp->door_locked = ST_LOCKED_AUTO;

	STps = &(STp->ps[STp->partition]);
	if (STps->rw == ST_WRITING) {
		retval = osst_flush_buffer(STp, &SRpnt, 0);
		if (retval)
			goto out;
		STps->rw = ST_IDLE;
		/* FIXME -- this may leave the tape without EOD and up2date headers */
	}

	if ((count % STp->block_size) != 0) {
		printk(KERN_WARNING
		    "%s:W: Read (%Zd bytes) not multiple of tape block size (%d%c).\n", name, count,
		    STp->block_size<1024?STp->block_size:STp->block_size/1024, STp->block_size<1024?'b':'k');
	}

#if DEBUG
	if (debugging && STps->eof != ST_NOEOF)
		printk(OSST_DEB_MSG "%s:D: EOF/EOM flag up (%d). Bytes %d\n", name,
				     STps->eof, (STp->buffer)->buffer_bytes);
#endif
	if ((STp->buffer)->buffer_bytes == 0 &&
	     STps->eof >= ST_EOD_1) {
		if (STps->eof < ST_EOD) {
			STps->eof += 1;
			retval = 0;
			goto out;
		}
		retval = (-EIO);  /* EOM or Blank Check */
		goto out;
	}

	/* Check the buffer writability before any tape movement. Don't alter
		 buffer data. */
	if (copy_from_user(&i, buf, 1)             != 0 ||
	    copy_to_user  (buf, &i, 1)             != 0 ||
	    copy_from_user(&i, buf + count - 1, 1) != 0 ||
	    copy_to_user  (buf + count - 1, &i, 1) != 0) {
		retval = (-EFAULT);
		goto out;
	}

	/* Loop until enough data in buffer or a special condition found */
	for (total = 0, special = 0; total < count - STp->block_size + 1 && !special; ) {

		/* Get new data if the buffer is empty */
		if ((STp->buffer)->buffer_bytes == 0) {
			if (STps->eof == ST_FM_HIT)
				break;
			special = osst_get_logical_frame(STp, &SRpnt, STp->frame_seq_number, 0);
			if (special < 0) { 			/* No need to continue read */
				STp->frame_in_buffer = 0;
				retval = special;
				goto out;
			}
		}

		/* Move the data from driver buffer to user buffer */
		if ((STp->buffer)->buffer_bytes > 0) {
#if DEBUG
			if (debugging && STps->eof != ST_NOEOF)
			    printk(OSST_DEB_MSG "%s:D: EOF up (%d). Left %d, needed %d.\n", name,
						 STps->eof, (STp->buffer)->buffer_bytes, count - total);
#endif
		       	/* force multiple of block size, note block_size may have been adjusted */
			transfer = (((STp->buffer)->buffer_bytes < count - total ?
				     (STp->buffer)->buffer_bytes : count - total)/
					STp->block_size) * STp->block_size;

			if (transfer == 0) {
				printk(KERN_WARNING
				  "%s:W: Nothing can be transfered, requested %Zd, tape block size (%d%c).\n",
			   		name, count, STp->block_size < 1024?
					STp->block_size:STp->block_size/1024,
				       	STp->block_size<1024?'b':'k');
				break;
			}
			i = from_buffer(STp->buffer, buf, transfer);
			if (i)  {
				retval = i;
				goto out;
			}
			STp->logical_blk_num += transfer / STp->block_size;
			STps->drv_block      += transfer / STp->block_size;
			filp->f_pos          += transfer;
			buf                  += transfer;
			total                += transfer;
		}
 
		if ((STp->buffer)->buffer_bytes == 0) {
#if DEBUG
			if (debugging)
				printk(OSST_DEB_MSG "%s:D: Finished with frame %d\n",
					       	name, STp->frame_seq_number);
#endif
			STp->frame_in_buffer = 0;
			STp->frame_seq_number++;              /* frame to look for next time */
		}
	} /* for (total = 0, special = 0; total < count && !special; ) */

	/* Change the eof state if no data from tape or buffer */
	if (total == 0) {
		if (STps->eof == ST_FM_HIT) {
			STps->eof = (STp->first_frame_position >= STp->eod_frame_ppos)?ST_EOD_2:ST_FM;
			STps->drv_block = 0;
			if (STps->drv_file >= 0)
				STps->drv_file++;
		}
		else if (STps->eof == ST_EOD_1) {
			STps->eof = ST_EOD_2;
			if (STps->drv_block > 0 && STps->drv_file >= 0)
				STps->drv_file++;
			STps->drv_block = 0;
		}
		else if (STps->eof == ST_EOD_2)
			STps->eof = ST_EOD;
	}
	else if (STps->eof == ST_FM)
		STps->eof = ST_NOEOF;

	retval = total;

out:
	if (SRpnt != NULL) scsi_release_request(SRpnt);

	up(&STp->lock);

	return retval;
}


/* Set the driver options */
static void osst_log_options(struct osst_tape *STp, struct st_modedef *STm, char *name)
{
  printk(KERN_INFO
"%s:I: Mode %d options: buffer writes: %d, async writes: %d, read ahead: %d\n",
	 name, STp->current_mode, STm->do_buffer_writes, STm->do_async_writes,
	 STm->do_read_ahead);
  printk(KERN_INFO
"%s:I:    can bsr: %d, two FMs: %d, fast mteom: %d, auto lock: %d,\n",
	 name, STp->can_bsr, STp->two_fm, STp->fast_mteom, STp->do_auto_lock);
  printk(KERN_INFO
"%s:I:    defs for wr: %d, no block limits: %d, partitions: %d, s2 log: %d\n",
	 name, STm->defaults_for_writes, STp->omit_blklims, STp->can_partitions,
	 STp->scsi2_logical);
  printk(KERN_INFO
"%s:I:    sysv: %d\n", name, STm->sysv);
#if DEBUG
  printk(KERN_INFO
	 "%s:D:    debugging: %d\n",
	 name, debugging);
#endif
}


static int osst_set_options(struct osst_tape *STp, long options)
{
	int		    value;
	long		    code;
	struct st_modedef * STm;
	char		  * name = tape_name(STp);

	STm = &(STp->modes[STp->current_mode]);
	if (!STm->defined) {
		memcpy(STm, &(STp->modes[0]), sizeof(*STm));
		modes_defined = 1;
#if DEBUG
		if (debugging)
			printk(OSST_DEB_MSG "%s:D: Initialized mode %d definition from mode 0\n",
					     name, STp->current_mode);
#endif
	}

	code = options & MT_ST_OPTIONS;
	if (code == MT_ST_BOOLEANS) {
		STm->do_buffer_writes = (options & MT_ST_BUFFER_WRITES) != 0;
		STm->do_async_writes  = (options & MT_ST_ASYNC_WRITES) != 0;
		STm->defaults_for_writes = (options & MT_ST_DEF_WRITES) != 0;
		STm->do_read_ahead    = (options & MT_ST_READ_AHEAD) != 0;
		STp->two_fm	      = (options & MT_ST_TWO_FM) != 0;
		STp->fast_mteom	      = (options & MT_ST_FAST_MTEOM) != 0;
		STp->do_auto_lock     = (options & MT_ST_AUTO_LOCK) != 0;
		STp->can_bsr          = (options & MT_ST_CAN_BSR) != 0;
		STp->omit_blklims     = (options & MT_ST_NO_BLKLIMS) != 0;
		if ((STp->device)->scsi_level >= SCSI_2)
			STp->can_partitions = (options & MT_ST_CAN_PARTITIONS) != 0;
		STp->scsi2_logical    = (options & MT_ST_SCSI2LOGICAL) != 0;
		STm->sysv	      = (options & MT_ST_SYSV) != 0;
#if DEBUG
		debugging = (options & MT_ST_DEBUGGING) != 0;
#endif
		osst_log_options(STp, STm, name);
	}
	else if (code == MT_ST_SETBOOLEANS || code == MT_ST_CLEARBOOLEANS) {
		value = (code == MT_ST_SETBOOLEANS);
		if ((options & MT_ST_BUFFER_WRITES) != 0)
			STm->do_buffer_writes = value;
		if ((options & MT_ST_ASYNC_WRITES) != 0)
			STm->do_async_writes = value;
		if ((options & MT_ST_DEF_WRITES) != 0)
			STm->defaults_for_writes = value;
		if ((options & MT_ST_READ_AHEAD) != 0)
			STm->do_read_ahead = value;
		if ((options & MT_ST_TWO_FM) != 0)
			STp->two_fm = value;
		if ((options & MT_ST_FAST_MTEOM) != 0)
			STp->fast_mteom = value;
		if ((options & MT_ST_AUTO_LOCK) != 0)
			STp->do_auto_lock = value;
		if ((options & MT_ST_CAN_BSR) != 0)
			STp->can_bsr = value;
		if ((options & MT_ST_NO_BLKLIMS) != 0)
			STp->omit_blklims = value;
		if ((STp->device)->scsi_level >= SCSI_2 &&
		    (options & MT_ST_CAN_PARTITIONS) != 0)
			STp->can_partitions = value;
		if ((options & MT_ST_SCSI2LOGICAL) != 0)
			STp->scsi2_logical = value;
		if ((options & MT_ST_SYSV) != 0)
			STm->sysv = value;
#if DEBUG
		if ((options & MT_ST_DEBUGGING) != 0)
			debugging = value;
#endif
		osst_log_options(STp, STm, name);
	}
	else if (code == MT_ST_WRITE_THRESHOLD) {
		value = (options & ~MT_ST_OPTIONS) * ST_KILOBYTE;
		if (value < 1 || value > osst_buffer_size) {
			printk(KERN_WARNING "%s:W: Write threshold %d too small or too large.\n",
					     name, value);
			return (-EIO);
		}
		STp->write_threshold = value;
		printk(KERN_INFO "%s:I: Write threshold set to %d bytes.\n",
				  name, value);
	}
	else if (code == MT_ST_DEF_BLKSIZE) {
		value = (options & ~MT_ST_OPTIONS);
		if (value == ~MT_ST_OPTIONS) {
			STm->default_blksize = (-1);
			printk(KERN_INFO "%s:I: Default block size disabled.\n", name);
		}
		else {
			if (value < 512 || value > OS_DATA_SIZE || OS_DATA_SIZE % value) {
				printk(KERN_WARNING "%s:W: Default block size cannot be set to %d.\n",
							 name, value);
				return (-EINVAL);
			}
			STm->default_blksize = value;
			printk(KERN_INFO "%s:I: Default block size set to %d bytes.\n",
					  name, STm->default_blksize);
		}
	}
	else if (code == MT_ST_TIMEOUTS) {
		value = (options & ~MT_ST_OPTIONS);
		if ((value & MT_ST_SET_LONG_TIMEOUT) != 0) {
			STp->long_timeout = (value & ~MT_ST_SET_LONG_TIMEOUT) * HZ;
			printk(KERN_INFO "%s:I: Long timeout set to %d seconds.\n", name,
					     (value & ~MT_ST_SET_LONG_TIMEOUT));
		}
		else {
			STp->timeout = value * HZ;
			printk(KERN_INFO "%s:I: Normal timeout set to %d seconds.\n", name, value);
		}
	}
	else if (code == MT_ST_DEF_OPTIONS) {
		code = (options & ~MT_ST_CLEAR_DEFAULT);
		value = (options & MT_ST_CLEAR_DEFAULT);
		if (code == MT_ST_DEF_DENSITY) {
			if (value == MT_ST_CLEAR_DEFAULT) {
				STm->default_density = (-1);
				printk(KERN_INFO "%s:I: Density default disabled.\n", name);
			}
			else {
				STm->default_density = value & 0xff;
				printk(KERN_INFO "%s:I: Density default set to %x\n",
						  name, STm->default_density);
			}
		}
		else if (code == MT_ST_DEF_DRVBUFFER) {
			if (value == MT_ST_CLEAR_DEFAULT) {
				STp->default_drvbuffer = 0xff;
				printk(KERN_INFO "%s:I: Drive buffer default disabled.\n", name);
			}
			else {
				STp->default_drvbuffer = value & 7;
				printk(KERN_INFO "%s:I: Drive buffer default set to %x\n",
						  name, STp->default_drvbuffer);
			}
		}
		else if (code == MT_ST_DEF_COMPRESSION) {
			if (value == MT_ST_CLEAR_DEFAULT) {
				STm->default_compression = ST_DONT_TOUCH;
				printk(KERN_INFO "%s:I: Compression default disabled.\n", name);
			}
			else {
				STm->default_compression = (value & 1 ? ST_YES : ST_NO);
				printk(KERN_INFO "%s:I: Compression default set to %x\n",
						  name, (value & 1));
			}
		}
	}
	else
		return (-EIO);

	return 0;
}


/* Internal ioctl function */
static int osst_int_ioctl(struct osst_tape * STp, struct scsi_request ** aSRpnt,
			     unsigned int cmd_in, unsigned long arg)
{
	int			timeout;
	long			ltmp;
	int			i, ioctl_result;
	int			chg_eof = 1;
	unsigned char		cmd[MAX_COMMAND_SIZE];
	struct scsi_request   * SRpnt = * aSRpnt;
	struct st_partstat    * STps;
	int			fileno, blkno, at_sm, frame_seq_numbr, logical_blk_num;
	int			datalen = 0, direction = DMA_NONE;
	char		      * name = tape_name(STp);

	if (STp->ready != ST_READY && cmd_in != MTLOAD) {
		if (STp->ready == ST_NO_TAPE)
			return (-ENOMEDIUM);
		else
			return (-EIO);
	}
	timeout = STp->long_timeout;
	STps = &(STp->ps[STp->partition]);
	fileno = STps->drv_file;
	blkno = STps->drv_block;
	at_sm = STps->at_sm;
	frame_seq_numbr = STp->frame_seq_number;
	logical_blk_num = STp->logical_blk_num;

	memset(cmd, 0, MAX_COMMAND_SIZE);
	switch (cmd_in) {
	 case MTFSFM:
		chg_eof = 0; /* Changed from the FSF after this */
	 case MTFSF:
		if (STp->raw)
		   return (-EIO);
		if (STp->linux_media)
		   ioctl_result = osst_space_over_filemarks_forward_fast(STp, &SRpnt, cmd_in, arg);
		else
		   ioctl_result = osst_space_over_filemarks_forward_slow(STp, &SRpnt, cmd_in, arg);
		if (fileno >= 0)
		   fileno += arg;
		blkno = 0;
		at_sm &= (arg == 0);
		goto os_bypass;

	 case MTBSF:
		chg_eof = 0; /* Changed from the FSF after this */
	 case MTBSFM:
		if (STp->raw)
		   return (-EIO);
		ioctl_result = osst_space_over_filemarks_backward(STp, &SRpnt, cmd_in, arg);
		if (fileno >= 0)
		   fileno -= arg;
		blkno = (-1);  /* We can't know the block number */
		at_sm &= (arg == 0);
		goto os_bypass;

	 case MTFSR:
	 case MTBSR:
#if DEBUG
		if (debugging)
		   printk(OSST_DEB_MSG "%s:D: Skipping %lu blocks %s from logical block %d\n",
				name, arg, cmd_in==MTFSR?"forward":"backward", logical_blk_num);
#endif
		if (cmd_in == MTFSR) {
		   logical_blk_num += arg;
		   if (blkno >= 0) blkno += arg;
		}
		else {
		   logical_blk_num -= arg;
		   if (blkno >= 0) blkno -= arg;
		}
		ioctl_result = osst_seek_logical_blk(STp, &SRpnt, logical_blk_num);
		fileno = STps->drv_file;
		blkno  = STps->drv_block;
		at_sm &= (arg == 0);
		goto os_bypass;

	 case MTFSS:
		cmd[0] = SPACE;
		cmd[1] = 0x04; /* Space Setmarks */   /* FIXME -- OS can't do this? */
		cmd[2] = (arg >> 16);
		cmd[3] = (arg >> 8);
		cmd[4] = arg;
#if DEBUG
		if (debugging)
			printk(OSST_DEB_MSG "%s:D: Spacing tape forward %d setmarks.\n", name,
		cmd[2] * 65536 + cmd[3] * 256 + cmd[4]);
#endif
		if (arg != 0) {
			blkno = fileno = (-1);
			at_sm = 1;
		}
		break;
	 case MTBSS:
		cmd[0] = SPACE;
		cmd[1] = 0x04; /* Space Setmarks */   /* FIXME -- OS can't do this? */
		ltmp = (-arg);
		cmd[2] = (ltmp >> 16);
		cmd[3] = (ltmp >> 8);
		cmd[4] = ltmp;
#if DEBUG
		if (debugging) {
			if (cmd[2] & 0x80)
			   ltmp = 0xff000000;
			ltmp = ltmp | (cmd[2] << 16) | (cmd[3] << 8) | cmd[4];
			printk(OSST_DEB_MSG "%s:D: Spacing tape backward %ld setmarks.\n",
						name, (-ltmp));
		 }
#endif
		 if (arg != 0) {
			blkno = fileno = (-1);
			at_sm = 1;
		 }
		 break;
	 case MTWEOF:
		 if ((STps->rw == ST_WRITING || STp->dirty) && !STp->pos_unknown) {
			STp->write_type = OS_WRITE_DATA;
			ioctl_result = osst_flush_write_buffer(STp, &SRpnt);
		 } else
			ioctl_result = 0;
#if DEBUG
		 if (debugging) 
			   printk(OSST_DEB_MSG "%s:D: Writing %ld filemark(s).\n", name, arg);
#endif
		 for (i=0; i<arg; i++)
			ioctl_result |= osst_write_filemark(STp, &SRpnt);
		 if (fileno >= 0) fileno += arg;
		 if (blkno  >= 0) blkno   = 0;
		 goto os_bypass;

	 case MTWSM:
		 if (STp->write_prot)
			return (-EACCES);
		 if (!STp->raw)
			return 0;
		 cmd[0] = WRITE_FILEMARKS;   /* FIXME -- need OS version */
		 if (cmd_in == MTWSM)
			 cmd[1] = 2;
		 cmd[2] = (arg >> 16);
		 cmd[3] = (arg >> 8);
		 cmd[4] = arg;
		 timeout = STp->timeout;
#if DEBUG
		 if (debugging) 
			   printk(OSST_DEB_MSG "%s:D: Writing %d setmark(s).\n", name,
				  cmd[2] * 65536 + cmd[3] * 256 + cmd[4]);
#endif
		 if (fileno >= 0)
			fileno += arg;
		 blkno = 0;
		 at_sm = (cmd_in == MTWSM);
		 break;
	 case MTOFFL:
	 case MTLOAD:
	 case MTUNLOAD:
	 case MTRETEN:
		 cmd[0] = START_STOP;
		 cmd[1] = 1;			/* Don't wait for completion */
		 if (cmd_in == MTLOAD) {
		     if (STp->ready == ST_NO_TAPE)
			 cmd[4] = 4;		/* open tray */
		      else
			 cmd[4] = 1;		/* load */
		 }
		 if (cmd_in == MTRETEN)
			 cmd[4] = 3;		/* retension then mount */
		 if (cmd_in == MTOFFL)
			 cmd[4] = 4;		/* rewind then eject */
		 timeout = STp->timeout;
#if DEBUG
		 if (debugging) {
			 switch (cmd_in) {
				 case MTUNLOAD:
					 printk(OSST_DEB_MSG "%s:D: Unloading tape.\n", name);
					 break;
				 case MTLOAD:
					 printk(OSST_DEB_MSG "%s:D: Loading tape.\n", name);
					 break;
				 case MTRETEN:
					 printk(OSST_DEB_MSG "%s:D: Retensioning tape.\n", name);
					 break;
				 case MTOFFL:
					 printk(OSST_DEB_MSG "%s:D: Ejecting tape.\n", name);
					 break;
			 }
		 }
#endif
       fileno = blkno = at_sm = frame_seq_numbr = logical_blk_num = 0 ;
		 break;
	 case MTNOP:
#if DEBUG
		 if (debugging)
			 printk(OSST_DEB_MSG "%s:D: No-op on tape.\n", name);
#endif
		 return 0;  /* Should do something ? */
		 break;
	 case MTEOM:
#if DEBUG
		if (debugging)
		   printk(OSST_DEB_MSG "%s:D: Spacing to end of recorded medium.\n", name);
#endif
		if ((osst_position_tape_and_confirm(STp, &SRpnt, STp->eod_frame_ppos) < 0) ||
			    (osst_get_logical_frame(STp, &SRpnt, -1, 0)               < 0)) {
		   ioctl_result = -EIO;
		   goto os_bypass;
		}
		if (STp->buffer->aux->frame_type != OS_FRAME_TYPE_EOD) {
#if DEBUG
		   printk(OSST_DEB_MSG "%s:D: No EOD frame found where expected.\n", name);
#endif
		   ioctl_result = -EIO;
		   goto os_bypass;
		}
		ioctl_result = osst_set_frame_position(STp, &SRpnt, STp->eod_frame_ppos, 0);
		fileno = STp->filemark_cnt;
		blkno  = at_sm = 0;
		goto os_bypass;

	 case MTERASE:
		if (STp->write_prot)
		   return (-EACCES);
		ioctl_result = osst_reset_header(STp, &SRpnt);
		i = osst_write_eod(STp, &SRpnt);
		if (i < ioctl_result) ioctl_result = i;
		i = osst_position_tape_and_confirm(STp, &SRpnt, STp->eod_frame_ppos);
		if (i < ioctl_result) ioctl_result = i;
		fileno = blkno = at_sm = 0 ;
		goto os_bypass;

	 case MTREW:
		cmd[0] = REZERO_UNIT; /* rewind */
		cmd[1] = 1;
#if DEBUG
		if (debugging)
		   printk(OSST_DEB_MSG "%s:D: Rewinding tape, Immed=%d.\n", name, cmd[1]);
#endif
		fileno = blkno = at_sm = frame_seq_numbr = logical_blk_num = 0 ;
		break;

	 case MTSETBLK:           /* Set block length */
		 if ((STps->drv_block == 0 )			  &&
		     !STp->dirty				  &&
		     ((STp->buffer)->buffer_bytes == 0)		  &&
		     ((arg & MT_ST_BLKSIZE_MASK) >= 512 )	  && 
		     ((arg & MT_ST_BLKSIZE_MASK) <= OS_DATA_SIZE) &&
		     !(OS_DATA_SIZE % (arg & MT_ST_BLKSIZE_MASK))  ) {
			 /*
			  * Only allowed to change the block size if you opened the
			  * device at the beginning of a file before writing anything.
			  * Note, that when reading, changing block_size is futile,
			  * as the size used when writing overrides it.
			  */
			 STp->block_size = (arg & MT_ST_BLKSIZE_MASK);
			 printk(KERN_INFO "%s:I: Block size set to %d bytes.\n",
					   name, STp->block_size);
			 return 0;
		 }
	 case MTSETDENSITY:       /* Set tape density */
	 case MTSETDRVBUFFER:     /* Set drive buffering */
	 case SET_DENS_AND_BLK:   /* Set density and block size */
		 chg_eof = 0;
		 if (STp->dirty || (STp->buffer)->buffer_bytes != 0)
			 return (-EIO);       /* Not allowed if data in buffer */
		 if ((cmd_in == MTSETBLK || cmd_in == SET_DENS_AND_BLK) &&
		     (arg & MT_ST_BLKSIZE_MASK) != 0                    &&
		     (arg & MT_ST_BLKSIZE_MASK) != STp->block_size       ) {
			 printk(KERN_WARNING "%s:W: Illegal to set block size to %d%s.\n",
						name, (int)(arg & MT_ST_BLKSIZE_MASK),
						(OS_DATA_SIZE % (arg & MT_ST_BLKSIZE_MASK))?"":" now");
			 return (-EINVAL);
		 }
		 return 0;  /* FIXME silently ignore if block size didn't change */

	 default:
		return (-ENOSYS);
	}

	SRpnt = osst_do_scsi(SRpnt, STp, cmd, datalen, direction, timeout, MAX_RETRIES, 1);

	ioctl_result = (STp->buffer)->syscall_result;

	if (!SRpnt) {
#if DEBUG
		printk(OSST_DEB_MSG "%s:D: Couldn't exec scsi cmd for IOCTL\n", name);
#endif
		return ioctl_result;
	}

	if (!ioctl_result) {  /* SCSI command successful */
		STp->frame_seq_number = frame_seq_numbr;
		STp->logical_blk_num  = logical_blk_num;
	}

os_bypass:
#if DEBUG
	if (debugging)
		printk(OSST_DEB_MSG "%s:D: IOCTL (%d) Result=%d\n", name, cmd_in, ioctl_result);
#endif

	if (!ioctl_result) {				/* success */

		if (cmd_in == MTFSFM) {
			 fileno--;
			 blkno--;
		}
		if (cmd_in == MTBSFM) {
			 fileno++;
			 blkno++;
		}
		STps->drv_block = blkno;
		STps->drv_file = fileno;
		STps->at_sm = at_sm;

		if (cmd_in == MTEOM)
			STps->eof = ST_EOD;
		else if ((cmd_in == MTFSFM || cmd_in == MTBSF) && STps->eof == ST_FM_HIT) {
			ioctl_result = osst_seek_logical_blk(STp, &SRpnt, STp->logical_blk_num-1);
			STps->drv_block++;
			STp->logical_blk_num++;
			STp->frame_seq_number++;
			STp->frame_in_buffer = 0;
			STp->buffer->read_pointer = 0;
		}
		else if (cmd_in == MTFSF)
			STps->eof = (STp->first_frame_position >= STp->eod_frame_ppos)?ST_EOD:ST_FM;
		else if (chg_eof)
			STps->eof = ST_NOEOF;

		if (cmd_in == MTOFFL || cmd_in == MTUNLOAD)
			STp->rew_at_close = 0;
		else if (cmd_in == MTLOAD) {
			for (i=0; i < ST_NBR_PARTITIONS; i++) {
			    STp->ps[i].rw = ST_IDLE;
			    STp->ps[i].last_block_valid = 0;/* FIXME - where else is this field maintained? */
			}
			STp->partition = 0;
		}

		if (cmd_in == MTREW) {
			ioctl_result = osst_position_tape_and_confirm(STp, &SRpnt, STp->first_data_ppos); 
			if (ioctl_result > 0)
				ioctl_result = 0;
		}

	} else if (cmd_in == MTBSF || cmd_in == MTBSFM ) {
		if (osst_position_tape_and_confirm(STp, &SRpnt, STp->first_data_ppos) < 0)
			STps->drv_file = STps->drv_block = -1;
		else
			STps->drv_file = STps->drv_block = 0;
		STps->eof = ST_NOEOF;
	} else if (cmd_in == MTFSF || cmd_in == MTFSFM) {
		if (osst_position_tape_and_confirm(STp, &SRpnt, STp->eod_frame_ppos) < 0)
			STps->drv_file = STps->drv_block = -1;
		else {
			STps->drv_file  = STp->filemark_cnt;
			STps->drv_block = 0;
		}
		STps->eof = ST_EOD;
	} else if (cmd_in == MTBSR || cmd_in == MTFSR || cmd_in == MTWEOF || cmd_in == MTEOM) {
		STps->drv_file = STps->drv_block = (-1);
		STps->eof = ST_NOEOF;
		STp->header_ok = 0;
	} else if (cmd_in == MTERASE) {
		STp->header_ok = 0;
	} else if (SRpnt) {  /* SCSI command was not completely successful. */
		if (SRpnt->sr_sense_buffer[2] & 0x40) {
			STps->eof = ST_EOM_OK;
			STps->drv_block = 0;
		}
		if (chg_eof)
			STps->eof = ST_NOEOF;

		if ((SRpnt->sr_sense_buffer[2] & 0x0f) == BLANK_CHECK)
			STps->eof = ST_EOD;

		if (cmd_in == MTLOAD && osst_wait_for_medium(STp, &SRpnt, 60))
			ioctl_result = osst_wait_ready(STp, &SRpnt, 5 * 60, OSST_WAIT_POSITION_COMPLETE);
	}
	*aSRpnt = SRpnt;

	return ioctl_result;
}


/* Open the device */
static int os_scsi_tape_open(struct inode * inode, struct file * filp)
{
	unsigned short	      flags;
	int		      i, b_size, new_session = 0, retval = 0;
	unsigned char	      cmd[MAX_COMMAND_SIZE];
	struct scsi_request * SRpnt = NULL;
	struct osst_tape    * STp;
	struct st_modedef   * STm;
	struct st_partstat  * STps;
	char		    * name;
	int		      dev  = TAPE_NR(inode);
	int		      mode = TAPE_MODE(inode);

	/*
	 * We really want to do nonseekable_open(inode, filp); here, but some
	 * versions of tar incorrectly call lseek on tapes and bail out if that
	 * fails.  So we disallow pread() and pwrite(), but permit lseeks.
	 */
	filp->f_mode &= ~(FMODE_PREAD | FMODE_PWRITE);

	write_lock(&os_scsi_tapes_lock);
	if (dev >= osst_max_dev || os_scsi_tapes == NULL ||
	    (STp = os_scsi_tapes[dev]) == NULL || !STp->device) {
		write_unlock(&os_scsi_tapes_lock);
		return (-ENXIO);
	}

	name = tape_name(STp);

	if (STp->in_use) {
		write_unlock(&os_scsi_tapes_lock);
#if DEBUG
		printk(OSST_DEB_MSG "%s:D: Device already in use.\n", name);
#endif
		return (-EBUSY);
	}
	if (scsi_device_get(STp->device)) {
		write_unlock(&os_scsi_tapes_lock);
#if DEBUG
                printk(OSST_DEB_MSG "%s:D: Failed scsi_device_get.\n", name);
#endif
		return (-ENXIO);
	}
	filp->private_data = STp;
	STp->in_use = 1;
	write_unlock(&os_scsi_tapes_lock);
	STp->rew_at_close = TAPE_REWIND(inode);

	if( !scsi_block_when_processing_errors(STp->device) ) {
		return -ENXIO;
	}

	if (mode != STp->current_mode) {
#if DEBUG
		if (debugging)
			printk(OSST_DEB_MSG "%s:D: Mode change from %d to %d.\n",
					       name, STp->current_mode, mode);
#endif
		new_session = 1;
		STp->current_mode = mode;
	}
	STm = &(STp->modes[STp->current_mode]);

	flags = filp->f_flags;
	STp->write_prot = ((flags & O_ACCMODE) == O_RDONLY);

	STp->raw = TAPE_IS_RAW(inode);
	if (STp->raw)
		STp->header_ok = 0;

	/* Allocate data segments for this device's tape buffer */
	if (!enlarge_buffer(STp->buffer, STp->restr_dma)) {
		printk(KERN_ERR "%s:E: Unable to allocate memory segments for tape buffer.\n", name);
		retval = (-EOVERFLOW);
		goto err_out;
	}
	if (STp->buffer->buffer_size >= OS_FRAME_SIZE) {
		for (i = 0, b_size = 0; 
		     (i < STp->buffer->sg_segs) && ((b_size + STp->buffer->sg[i].length) <= OS_DATA_SIZE); 
		     b_size += STp->buffer->sg[i++].length);
		STp->buffer->aux = (os_aux_t *) (page_address(STp->buffer->sg[i].page) + OS_DATA_SIZE - b_size);
#if DEBUG
		printk(OSST_DEB_MSG "%s:D: b_data points to %p in segment 0 at %p\n", name,
			STp->buffer->b_data, page_address(STp->buffer->sg[0].page));
		printk(OSST_DEB_MSG "%s:D: AUX points to %p in segment %d at %p\n", name,
			 STp->buffer->aux, i, page_address(STp->buffer->sg[i].page));
#endif
	} else {
		STp->buffer->aux = NULL; /* this had better never happen! */
		printk(KERN_NOTICE "%s:A: Framesize %d too large for buffer.\n", name, OS_FRAME_SIZE);
		retval = (-EIO);
		goto err_out;
	}
	STp->buffer->writing = 0;
	STp->buffer->syscall_result = 0;
	STp->dirty = 0;
	for (i=0; i < ST_NBR_PARTITIONS; i++) {
		STps = &(STp->ps[i]);
		STps->rw = ST_IDLE;
	}
	STp->ready = ST_READY;
#if DEBUG
	STp->nbr_waits = STp->nbr_finished = 0;
#endif

	memset (cmd, 0, MAX_COMMAND_SIZE);
	cmd[0] = TEST_UNIT_READY;

	SRpnt = osst_do_scsi(NULL, STp, cmd, 0, DMA_NONE, STp->timeout, MAX_RETRIES, 1);
	if (!SRpnt) {
		retval = (STp->buffer)->syscall_result;		/* FIXME - valid? */
		goto err_out;
	}
	if ((SRpnt->sr_sense_buffer[0] & 0x70) == 0x70      &&
	    (SRpnt->sr_sense_buffer[2] & 0x0f) == NOT_READY &&
	     SRpnt->sr_sense_buffer[12]        == 4         ) {
#if DEBUG
		printk(OSST_DEB_MSG "%s:D: Unit not ready, cause %x\n", name, SRpnt->sr_sense_buffer[13]);
#endif
		if (filp->f_flags & O_NONBLOCK) {
			retval = -EAGAIN;
			goto err_out;
		}
		if (SRpnt->sr_sense_buffer[13] == 2) {	/* initialize command required (LOAD) */
			memset (cmd, 0, MAX_COMMAND_SIZE);
        		cmd[0] = START_STOP;
			cmd[1] = 1;
			cmd[4] = 1;
			SRpnt = osst_do_scsi(SRpnt, STp, cmd, 0, DMA_NONE,
					     STp->timeout, MAX_RETRIES, 1);
		}
		osst_wait_ready(STp, &SRpnt, (SRpnt->sr_sense_buffer[13]==1?15:3) * 60, 0);
	}
	if ((SRpnt->sr_sense_buffer[0] & 0x70) == 0x70 &&
	    (SRpnt->sr_sense_buffer[2] & 0x0f) == UNIT_ATTENTION) { /* New media? */
#if DEBUG
		printk(OSST_DEB_MSG "%s:D: Unit wants attention\n", name);
#endif
		STp->header_ok = 0;

		for (i=0; i < 10; i++) {

			memset (cmd, 0, MAX_COMMAND_SIZE);
			cmd[0] = TEST_UNIT_READY;

			SRpnt = osst_do_scsi(SRpnt, STp, cmd, 0, DMA_NONE,
					     STp->timeout, MAX_RETRIES, 1);
			if ((SRpnt->sr_sense_buffer[0] & 0x70) != 0x70 ||
			    (SRpnt->sr_sense_buffer[2] & 0x0f) != UNIT_ATTENTION)
				break;
		}

		STp->pos_unknown = 0;
		STp->partition = STp->new_partition = 0;
		if (STp->can_partitions)
			STp->nbr_partitions = 1;  /* This guess will be updated later if necessary */
		for (i=0; i < ST_NBR_PARTITIONS; i++) {
			STps = &(STp->ps[i]);
			STps->rw = ST_IDLE;		/* FIXME - seems to be redundant... */
			STps->eof = ST_NOEOF;
			STps->at_sm = 0;
			STps->last_block_valid = 0;
			STps->drv_block = 0;
			STps->drv_file = 0 ;
		}
		new_session = 1;
		STp->recover_count = 0;
		STp->abort_count = 0;
	}
	/*
	 * if we have valid headers from before, and the drive/tape seem untouched,
	 * open without reconfiguring and re-reading the headers
	 */
	if (!STp->buffer->syscall_result && STp->header_ok &&
	    !SRpnt->sr_result && SRpnt->sr_sense_buffer[0] == 0) {

		memset(cmd, 0, MAX_COMMAND_SIZE);
		cmd[0] = MODE_SENSE;
		cmd[1] = 8;
		cmd[2] = VENDOR_IDENT_PAGE;
		cmd[4] = VENDOR_IDENT_PAGE_LENGTH + MODE_HEADER_LENGTH;

		SRpnt = osst_do_scsi(SRpnt, STp, cmd, cmd[4], DMA_FROM_DEVICE, STp->timeout, 0, 1);

		if (STp->buffer->syscall_result                     ||
		    STp->buffer->b_data[MODE_HEADER_LENGTH + 2] != 'L' ||
		    STp->buffer->b_data[MODE_HEADER_LENGTH + 3] != 'I' ||
		    STp->buffer->b_data[MODE_HEADER_LENGTH + 4] != 'N' ||
		    STp->buffer->b_data[MODE_HEADER_LENGTH + 5] != '4'  ) {
#if DEBUG
			printk(OSST_DEB_MSG "%s:D: Signature was changed to %c%c%c%c\n", name,
			  STp->buffer->b_data[MODE_HEADER_LENGTH + 2],
			  STp->buffer->b_data[MODE_HEADER_LENGTH + 3],
			  STp->buffer->b_data[MODE_HEADER_LENGTH + 4],
			  STp->buffer->b_data[MODE_HEADER_LENGTH + 5]);
#endif
			STp->header_ok = 0;
		}
		i = STp->first_frame_position;
		if (STp->header_ok && i == osst_get_frame_position(STp, &SRpnt)) {
			if (STp->door_locked == ST_UNLOCKED) {
				if (do_door_lock(STp, 1))
					printk(KERN_INFO "%s:I: Can't lock drive door\n", name);
				else
					STp->door_locked = ST_LOCKED_AUTO;
			}
			if (!STp->frame_in_buffer) {
				STp->block_size = (STm->default_blksize > 0) ?
							STm->default_blksize : OS_DATA_SIZE;
				STp->buffer->buffer_bytes = STp->buffer->read_pointer = 0;
			}
			STp->buffer->buffer_blocks = OS_DATA_SIZE / STp->block_size;
			STp->fast_open = 1;
			scsi_release_request(SRpnt);
			return 0;
		}
#if DEBUG
		if (i != STp->first_frame_position)
			printk(OSST_DEB_MSG "%s:D: Tape position changed from %d to %d\n",
						name, i, STp->first_frame_position);
#endif
		STp->header_ok = 0;
	}
	STp->fast_open = 0;

	if ((STp->buffer)->syscall_result != 0 &&   /* in all error conditions except no medium */ 
	    (SRpnt->sr_sense_buffer[2] != 2 || SRpnt->sr_sense_buffer[12] != 0x3A) ) {

		memset(cmd, 0, MAX_COMMAND_SIZE);
		cmd[0] = MODE_SELECT;
		cmd[1] = 0x10;
		cmd[4] = 4 + MODE_HEADER_LENGTH;

		(STp->buffer)->b_data[0] = cmd[4] - 1;
		(STp->buffer)->b_data[1] = 0;			/* Medium Type - ignoring */
		(STp->buffer)->b_data[2] = 0;			/* Reserved */
		(STp->buffer)->b_data[3] = 0;			/* Block Descriptor Length */
		(STp->buffer)->b_data[MODE_HEADER_LENGTH + 0] = 0x3f;
		(STp->buffer)->b_data[MODE_HEADER_LENGTH + 1] = 1;
		(STp->buffer)->b_data[MODE_HEADER_LENGTH + 2] = 2;
		(STp->buffer)->b_data[MODE_HEADER_LENGTH + 3] = 3;

#if DEBUG
		printk(OSST_DEB_MSG "%s:D: Applying soft reset\n", name);
#endif
		SRpnt = osst_do_scsi(SRpnt, STp, cmd, cmd[4], DMA_TO_DEVICE, STp->timeout, 0, 1);

		STp->header_ok = 0;

		for (i=0; i < 10; i++) {

			memset (cmd, 0, MAX_COMMAND_SIZE);
			cmd[0] = TEST_UNIT_READY;

			SRpnt = osst_do_scsi(SRpnt, STp, cmd, 0, DMA_NONE,
						    STp->timeout, MAX_RETRIES, 1);
			if ((SRpnt->sr_sense_buffer[0] & 0x70) != 0x70 ||
			    (SRpnt->sr_sense_buffer[2] & 0x0f) == NOT_READY)
			break;

			if ((SRpnt->sr_sense_buffer[2] & 0x0f) == UNIT_ATTENTION) {
				STp->pos_unknown = 0;
				STp->partition = STp->new_partition = 0;
				if (STp->can_partitions)
					STp->nbr_partitions = 1;  /* This guess will be updated later if necessary */
				for (i=0; i < ST_NBR_PARTITIONS; i++) {
					STps = &(STp->ps[i]);
					STps->rw = ST_IDLE;
					STps->eof = ST_NOEOF;
					STps->at_sm = 0;
					STps->last_block_valid = 0;
					STps->drv_block = 0;
					STps->drv_file = 0 ;
				}
				new_session = 1;
			}
		}
	}

	if (osst_wait_ready(STp, &SRpnt, 15 * 60, 0))		/* FIXME - not allowed with NOBLOCK */
		 printk(KERN_INFO "%s:I: Device did not become Ready in open\n", name);

	if ((STp->buffer)->syscall_result != 0) {
		if ((STp->device)->scsi_level >= SCSI_2 &&
		    (SRpnt->sr_sense_buffer[0] & 0x70) == 0x70 &&
		    (SRpnt->sr_sense_buffer[2] & 0x0f) == NOT_READY &&
		     SRpnt->sr_sense_buffer[12] == 0x3a) { /* Check ASC */
			STp->ready = ST_NO_TAPE;
		} else
			STp->ready = ST_NOT_READY;
		scsi_release_request(SRpnt);
		SRpnt = NULL;
		STp->density = 0;   	/* Clear the erroneous "residue" */
		STp->write_prot = 0;
		STp->block_size = 0;
		STp->ps[0].drv_file = STp->ps[0].drv_block = (-1);
		STp->partition = STp->new_partition = 0;
		STp->door_locked = ST_UNLOCKED;
		return 0;
	}

	osst_configure_onstream(STp, &SRpnt);

	STp->block_size = STp->raw ? OS_FRAME_SIZE : (
			     (STm->default_blksize > 0) ? STm->default_blksize : OS_DATA_SIZE);
	STp->buffer->buffer_blocks = STp->raw ? 1 : OS_DATA_SIZE / STp->block_size;
	STp->buffer->buffer_bytes  =
	STp->buffer->read_pointer  =
	STp->frame_in_buffer       = 0;

#if DEBUG
	if (debugging)
		printk(OSST_DEB_MSG "%s:D: Block size: %d, frame size: %d, buffer size: %d (%d blocks).\n",
		     name, STp->block_size, OS_FRAME_SIZE, (STp->buffer)->buffer_size,
		     (STp->buffer)->buffer_blocks);
#endif

	if (STp->drv_write_prot) {
		STp->write_prot = 1;
#if DEBUG
		if (debugging)
			printk(OSST_DEB_MSG "%s:D: Write protected\n", name);
#endif
		if ((flags & O_ACCMODE) == O_WRONLY || (flags & O_ACCMODE) == O_RDWR) {
			retval = (-EROFS);
			goto err_out;
		}
	}

	if (new_session) {  /* Change the drive parameters for the new mode */
#if DEBUG
		if (debugging)
	printk(OSST_DEB_MSG "%s:D: New Session\n", name);
#endif
		STp->density_changed = STp->blksize_changed = 0;
		STp->compression_changed = 0;
	}

	/*
	 * properly position the tape and check the ADR headers
	 */
	if (STp->door_locked == ST_UNLOCKED) {
		 if (do_door_lock(STp, 1))
			printk(KERN_INFO "%s:I: Can't lock drive door\n", name);
		 else
			STp->door_locked = ST_LOCKED_AUTO;
	}

	osst_analyze_headers(STp, &SRpnt);

	scsi_release_request(SRpnt);
	SRpnt = NULL;

	return 0;

err_out:
	if (SRpnt != NULL)
		scsi_release_request(SRpnt);
	normalize_buffer(STp->buffer);
	STp->header_ok = 0;
	STp->in_use = 0;
	scsi_device_put(STp->device);

	return retval;
}


/* Flush the tape buffer before close */
static int os_scsi_tape_flush(struct file * filp)
{
	int		      result = 0, result2;
	struct osst_tape    * STp    = filp->private_data;
	struct st_modedef   * STm    = &(STp->modes[STp->current_mode]);
	struct st_partstat  * STps   = &(STp->ps[STp->partition]);
	struct scsi_request * SRpnt  = NULL;
	char		    * name   = tape_name(STp);

	if (file_count(filp) > 1)
		return 0;

	if ((STps->rw == ST_WRITING || STp->dirty) && !STp->pos_unknown) {
		STp->write_type = OS_WRITE_DATA;
		result = osst_flush_write_buffer(STp, &SRpnt);
		if (result != 0 && result != (-ENOSPC))
			goto out;
	}
	if ( STps->rw >= ST_WRITING && !STp->pos_unknown) {

#if DEBUG
		if (debugging) {
			printk(OSST_DEB_MSG "%s:D: File length %ld bytes.\n",
					       name, (long)(filp->f_pos));
			printk(OSST_DEB_MSG "%s:D: Async write waits %d, finished %d.\n",
					       name, STp->nbr_waits, STp->nbr_finished);
		}
#endif
		result = osst_write_trailer(STp, &SRpnt, !(STp->rew_at_close));
#if DEBUG
		if (debugging)
			printk(OSST_DEB_MSG "%s:D: Buffer flushed, %d EOF(s) written\n",
					       name, 1+STp->two_fm);
#endif
	}
	else if (!STp->rew_at_close) {
		STps = &(STp->ps[STp->partition]);
		if (!STm->sysv || STps->rw != ST_READING) {
			if (STp->can_bsr)
				result = osst_flush_buffer(STp, &SRpnt, 0); /* this is the default path */
			else if (STps->eof == ST_FM_HIT) {
				result = cross_eof(STp, &SRpnt, 0);
					if (result) {
						if (STps->drv_file >= 0)
							STps->drv_file++;
						STps->drv_block = 0;
						STps->eof = ST_FM;
					}
					else
						STps->eof = ST_NOEOF;
			}
		}
		else if ((STps->eof == ST_NOEOF &&
			  !(result = cross_eof(STp, &SRpnt, 1))) ||
			 STps->eof == ST_FM_HIT) {
			if (STps->drv_file >= 0)
				STps->drv_file++;
			STps->drv_block = 0;
			STps->eof = ST_FM;
		}
	}

out:
	if (STp->rew_at_close) {
		result2 = osst_position_tape_and_confirm(STp, &SRpnt, STp->first_data_ppos);
		STps->drv_file = STps->drv_block = STp->frame_seq_number = STp->logical_blk_num = 0;
		if (result == 0 && result2 < 0)
			result = result2;
	}
	if (SRpnt) scsi_release_request(SRpnt);

	if (STp->abort_count || STp->recover_count) {
		printk(KERN_INFO "%s:I:", name);
		if (STp->abort_count)
			printk(" %d unrecovered errors", STp->abort_count);
		if (STp->recover_count)
			printk(" %d recovered errors", STp->recover_count);
		if (STp->write_count)
			printk(" in %d frames written", STp->write_count);
		if (STp->read_count)
			printk(" in %d frames read", STp->read_count);
		printk("\n");
		STp->recover_count = 0;
		STp->abort_count   = 0;
	}
	STp->write_count = 0;
	STp->read_count  = 0;

	return result;
}


/* Close the device and release it */
static int os_scsi_tape_close(struct inode * inode, struct file * filp)
{
	int		      result = 0;
	struct osst_tape    * STp    = filp->private_data;

	if (STp->door_locked == ST_LOCKED_AUTO)
		do_door_lock(STp, 0);

	if (STp->raw)
		STp->header_ok = 0;
	
	normalize_buffer(STp->buffer);
	write_lock(&os_scsi_tapes_lock);
	STp->in_use = 0;
	write_unlock(&os_scsi_tapes_lock);

	scsi_device_put(STp->device);

	return result;
}


/* The ioctl command */
static int osst_ioctl(struct inode * inode,struct file * file,
	 unsigned int cmd_in, unsigned long arg)
{
	int		      i, cmd_nr, cmd_type, retval = 0;
	unsigned int	      blk;
	struct st_modedef   * STm;
	struct st_partstat  * STps;
	struct scsi_request * SRpnt = NULL;
	struct osst_tape    * STp   = file->private_data;
	char		    * name  = tape_name(STp);
	void	    __user  * p     = (void __user *)arg;

	if (down_interruptible(&STp->lock))
		return -ERESTARTSYS;

#if DEBUG
	if (debugging && !STp->in_use) {
		printk(OSST_DEB_MSG "%s:D: Incorrect device.\n", name);
		retval = (-EIO);
		goto out;
	}
#endif
	STm = &(STp->modes[STp->current_mode]);
	STps = &(STp->ps[STp->partition]);

	/*
	 * If we are in the middle of error recovery, don't let anyone
	 * else try and use this device.  Also, if error recovery fails, it
	 * may try and take the device offline, in which case all further
	 * access to the device is prohibited.
	 */
	if( !scsi_block_when_processing_errors(STp->device) ) {
		retval = (-ENXIO);
		goto out;
	}

	cmd_type = _IOC_TYPE(cmd_in);
	cmd_nr   = _IOC_NR(cmd_in);
#if DEBUG
	printk(OSST_DEB_MSG "%s:D: Ioctl %d,%d in %s mode\n", name,
			    cmd_type, cmd_nr, STp->raw?"raw":"normal");
#endif
	if (cmd_type == _IOC_TYPE(MTIOCTOP) && cmd_nr == _IOC_NR(MTIOCTOP)) {
		struct mtop mtc;
		int    auto_weof = 0;

		if (_IOC_SIZE(cmd_in) != sizeof(mtc)) {
			retval = (-EINVAL);
			goto out;
		}

		i = copy_from_user((char *) &mtc, p, sizeof(struct mtop));
		if (i) {
			retval = (-EFAULT);
			goto out;
		}

		if (mtc.mt_op == MTSETDRVBUFFER && !capable(CAP_SYS_ADMIN)) {
			printk(KERN_WARNING "%s:W: MTSETDRVBUFFER only allowed for root.\n", name);
			retval = (-EPERM);
			goto out;
		}

		if (!STm->defined && (mtc.mt_op != MTSETDRVBUFFER && (mtc.mt_count & MT_ST_OPTIONS) == 0)) {
			retval = (-ENXIO);
			goto out;
		}

		if (!STp->pos_unknown) {

			if (STps->eof == ST_FM_HIT) {
				if (mtc.mt_op == MTFSF || mtc.mt_op == MTFSFM|| mtc.mt_op == MTEOM) {
					mtc.mt_count -= 1;
					if (STps->drv_file >= 0)
						STps->drv_file += 1;
				}
				else if (mtc.mt_op == MTBSF || mtc.mt_op == MTBSFM) {
					mtc.mt_count += 1;
					if (STps->drv_file >= 0)
						STps->drv_file += 1;
				}
			}

			if (mtc.mt_op == MTSEEK) {
				/* Old position must be restored if partition will be changed */
				i = !STp->can_partitions || (STp->new_partition != STp->partition);
			}
			else {
				i = mtc.mt_op == MTREW   || mtc.mt_op == MTOFFL ||
				    mtc.mt_op == MTRETEN || mtc.mt_op == MTEOM  ||
				    mtc.mt_op == MTLOCK  || mtc.mt_op == MTLOAD ||
				    mtc.mt_op == MTFSF   || mtc.mt_op == MTFSFM ||
				    mtc.mt_op == MTBSF   || mtc.mt_op == MTBSFM ||
				    mtc.mt_op == MTCOMPRESSION;
			}
			i = osst_flush_buffer(STp, &SRpnt, i);
			if (i < 0) {
				retval = i;
				goto out;
			}
		}
		else {
			/*
			 * If there was a bus reset, block further access
			 * to this device.  If the user wants to rewind the tape,
			 * then reset the flag and allow access again.
			 */
			if(mtc.mt_op != MTREW   &&
			   mtc.mt_op != MTOFFL  &&
			   mtc.mt_op != MTRETEN &&
			   mtc.mt_op != MTERASE &&
			   mtc.mt_op != MTSEEK  &&
			   mtc.mt_op != MTEOM)   {
				retval = (-EIO);
				goto out;
			}
			reset_state(STp);
			/* remove this when the midlevel properly clears was_reset */
			STp->device->was_reset = 0;
		}

		if (mtc.mt_op != MTCOMPRESSION  && mtc.mt_op != MTLOCK         &&
		    mtc.mt_op != MTNOP          && mtc.mt_op != MTSETBLK       &&
		    mtc.mt_op != MTSETDENSITY   && mtc.mt_op != MTSETDRVBUFFER && 
		    mtc.mt_op != MTMKPART       && mtc.mt_op != MTSETPART      &&
		    mtc.mt_op != MTWEOF         && mtc.mt_op != MTWSM           ) {

			/*
			 * The user tells us to move to another position on the tape.
			 * If we were appending to the tape content, that would leave
			 * the tape without proper end, in that case write EOD and
			 * update the header to reflect its position.
			 */
#if DEBUG
			printk(KERN_WARNING "%s:D: auto_weod %s at ffp=%d,efp=%d,fsn=%d,lbn=%d,fn=%d,bn=%d\n", name,
					STps->rw >= ST_WRITING ? "write" : STps->rw == ST_READING ? "read" : "idle",
					STp->first_frame_position, STp->eod_frame_ppos, STp->frame_seq_number,
					STp->logical_blk_num, STps->drv_file, STps->drv_block );
#endif
			if (STps->rw >= ST_WRITING && STp->first_frame_position >= STp->eod_frame_ppos) {
				auto_weof = ((STp->write_type != OS_WRITE_NEW_MARK) &&
							!(mtc.mt_op == MTREW || mtc.mt_op == MTOFFL));
				i = osst_write_trailer(STp, &SRpnt,
							!(mtc.mt_op == MTREW || mtc.mt_op == MTOFFL));
#if DEBUG
				printk(KERN_WARNING "%s:D: post trailer xeof=%d,ffp=%d,efp=%d,fsn=%d,lbn=%d,fn=%d,bn=%d\n",
						name, auto_weof, STp->first_frame_position, STp->eod_frame_ppos,
						STp->frame_seq_number, STp->logical_blk_num, STps->drv_file, STps->drv_block );
#endif
				if (i < 0) {
					retval = i;
					goto out;
				}
			}
			STps->rw = ST_IDLE;
		}

		if (mtc.mt_op == MTOFFL && STp->door_locked != ST_UNLOCKED)
			do_door_lock(STp, 0);  /* Ignore result! */

		if (mtc.mt_op == MTSETDRVBUFFER &&
		   (mtc.mt_count & MT_ST_OPTIONS) != 0) {
			retval = osst_set_options(STp, mtc.mt_count);
			goto out;
		}

		if (mtc.mt_op == MTSETPART) {
			if (mtc.mt_count >= STp->nbr_partitions)
				retval = -EINVAL;
			else {
				STp->new_partition = mtc.mt_count;
				retval = 0;
			}
			goto out;
		}

		if (mtc.mt_op == MTMKPART) {
			if (!STp->can_partitions) {
				retval = (-EINVAL);
				goto out;
			}
			if ((i = osst_int_ioctl(STp, &SRpnt, MTREW, 0)) < 0 /*||
			    (i = partition_tape(inode, mtc.mt_count)) < 0*/) {
				retval = i;
				goto out;
			}
			for (i=0; i < ST_NBR_PARTITIONS; i++) {
				STp->ps[i].rw = ST_IDLE;
				STp->ps[i].at_sm = 0;
				STp->ps[i].last_block_valid = 0;
			}
			STp->partition = STp->new_partition = 0;
			STp->nbr_partitions = 1;  /* Bad guess ?-) */
			STps->drv_block = STps->drv_file = 0;
			retval = 0;
			goto out;
	 	}

		if (mtc.mt_op == MTSEEK) {
			if (STp->raw)
				i = osst_set_frame_position(STp, &SRpnt, mtc.mt_count, 0);
			else
				i = osst_seek_sector(STp, &SRpnt, mtc.mt_count);
			if (!STp->can_partitions)
				STp->ps[0].rw = ST_IDLE;
			retval = i;
			goto out;
		}
 
		if (mtc.mt_op == MTLOCK || mtc.mt_op == MTUNLOCK) {
			retval = do_door_lock(STp, (mtc.mt_op == MTLOCK));
			goto out;
		}

		if (auto_weof)
			cross_eof(STp, &SRpnt, 0);

		if (mtc.mt_op == MTCOMPRESSION)
			retval = -EINVAL;       /* OnStream drives don't have compression hardware */
		else
			/* MTBSF MTBSFM MTBSR MTBSS MTEOM MTERASE MTFSF MTFSFB MTFSR MTFSS
			 * MTLOAD MTOFFL MTRESET MTRETEN MTREW MTUNLOAD MTWEOF MTWSM */
			retval = osst_int_ioctl(STp, &SRpnt, mtc.mt_op, mtc.mt_count);
		goto out;
	}

	if (!STm->defined) {
		retval = (-ENXIO);
		goto out;
	}

	if ((i = osst_flush_buffer(STp, &SRpnt, 0)) < 0) {
		retval = i;
		goto out;
	}

	if (cmd_type == _IOC_TYPE(MTIOCGET) && cmd_nr == _IOC_NR(MTIOCGET)) {
		struct mtget mt_status;

		if (_IOC_SIZE(cmd_in) != sizeof(struct mtget)) {
			 retval = (-EINVAL);
			 goto out;
		}

		mt_status.mt_type = MT_ISONSTREAM_SC;
		mt_status.mt_erreg = STp->recover_erreg << MT_ST_SOFTERR_SHIFT;
		mt_status.mt_dsreg =
			((STp->block_size << MT_ST_BLKSIZE_SHIFT) & MT_ST_BLKSIZE_MASK) |
			((STp->density    << MT_ST_DENSITY_SHIFT) & MT_ST_DENSITY_MASK);
		mt_status.mt_blkno = STps->drv_block;
		mt_status.mt_fileno = STps->drv_file;
		if (STp->block_size != 0) {
			if (STps->rw == ST_WRITING)
				mt_status.mt_blkno += (STp->buffer)->buffer_bytes / STp->block_size;
			else if (STps->rw == ST_READING)
				mt_status.mt_blkno -= ((STp->buffer)->buffer_bytes +
							STp->block_size - 1) / STp->block_size;
		}

		mt_status.mt_gstat = 0;
		if (STp->drv_write_prot)
			mt_status.mt_gstat |= GMT_WR_PROT(0xffffffff);
		if (mt_status.mt_blkno == 0) {
			if (mt_status.mt_fileno == 0)
				mt_status.mt_gstat |= GMT_BOT(0xffffffff);
			else
				mt_status.mt_gstat |= GMT_EOF(0xffffffff);
		}
		mt_status.mt_resid = STp->partition;
		if (STps->eof == ST_EOM_OK || STps->eof == ST_EOM_ERROR)
			mt_status.mt_gstat |= GMT_EOT(0xffffffff);
		else if (STps->eof >= ST_EOM_OK)
			mt_status.mt_gstat |= GMT_EOD(0xffffffff);
		if (STp->density == 1)
			mt_status.mt_gstat |= GMT_D_800(0xffffffff);
		else if (STp->density == 2)
			mt_status.mt_gstat |= GMT_D_1600(0xffffffff);
		else if (STp->density == 3)
			mt_status.mt_gstat |= GMT_D_6250(0xffffffff);
		if (STp->ready == ST_READY)
			mt_status.mt_gstat |= GMT_ONLINE(0xffffffff);
		if (STp->ready == ST_NO_TAPE)
			mt_status.mt_gstat |= GMT_DR_OPEN(0xffffffff);
		if (STps->at_sm)
			mt_status.mt_gstat |= GMT_SM(0xffffffff);
		if (STm->do_async_writes || (STm->do_buffer_writes && STp->block_size != 0) ||
		    STp->drv_buffer != 0)
			mt_status.mt_gstat |= GMT_IM_REP_EN(0xffffffff);

		i = copy_to_user(p, &mt_status, sizeof(struct mtget));
		if (i) {
			retval = (-EFAULT);
			goto out;
		}

		STp->recover_erreg = 0;  /* Clear after read */
		retval = 0;
		goto out;
	} /* End of MTIOCGET */

	if (cmd_type == _IOC_TYPE(MTIOCPOS) && cmd_nr == _IOC_NR(MTIOCPOS)) {
		struct mtpos mt_pos;

		if (_IOC_SIZE(cmd_in) != sizeof(struct mtpos)) {
			retval = (-EINVAL);
			goto out;
		}
		if (STp->raw)
			blk = osst_get_frame_position(STp, &SRpnt);
		else
			blk = osst_get_sector(STp, &SRpnt);
		if (blk < 0) {
			retval = blk;
			goto out;
		}
		mt_pos.mt_blkno = blk;
		i = copy_to_user(p, &mt_pos, sizeof(struct mtpos));
		if (i)
			retval = -EFAULT;
		goto out;
	}
	if (SRpnt) scsi_release_request(SRpnt);

	up(&STp->lock);

	return scsi_ioctl(STp->device, cmd_in, p);

out:
	if (SRpnt) scsi_release_request(SRpnt);

	up(&STp->lock);

	return retval;
}

#ifdef CONFIG_COMPAT
static long osst_compat_ioctl(struct file * file, unsigned int cmd_in, unsigned long arg)
{
	struct osst_tape *STp = file->private_data;
	struct scsi_device *sdev = STp->device;
	int ret = -ENOIOCTLCMD;
	if (sdev->host->hostt->compat_ioctl) {

		ret = sdev->host->hostt->compat_ioctl(sdev, cmd_in, (void __user *)arg);

	}
	return ret;
}
#endif



/* Memory handling routines */

/* Try to allocate a new tape buffer skeleton. Caller must not hold os_scsi_tapes_lock */
static struct osst_buffer * new_tape_buffer( int from_initialization, int need_dma, int max_sg )
{
	int i, priority;
	struct osst_buffer *tb;

	if (from_initialization)
		priority = GFP_ATOMIC;
	else
		priority = GFP_KERNEL;

	i = sizeof(struct osst_buffer) + (osst_max_sg_segs - 1) * sizeof(struct scatterlist);
	tb = (struct osst_buffer *)kmalloc(i, priority);
	if (!tb) {
		printk(KERN_NOTICE "osst :I: Can't allocate new tape buffer.\n");
		return NULL;
	}
	memset(tb, 0, i);
	tb->sg_segs = tb->orig_sg_segs = 0;
	tb->use_sg = max_sg;
	tb->in_use = 1;
	tb->dma = need_dma;
	tb->buffer_size = 0;
#if DEBUG
	if (debugging) 
		printk(OSST_DEB_MSG
			"osst :D: Allocated tape buffer skeleton (%d bytes, %d segments, dma: %d).\n",
			   i, max_sg, need_dma);
#endif
	return tb;
}

/* Try to allocate a temporary (while a user has the device open) enlarged tape buffer */
static int enlarge_buffer(struct osst_buffer *STbuffer, int need_dma)
{
	int segs, nbr, max_segs, b_size, priority, order, got;

	if (STbuffer->buffer_size >= OS_FRAME_SIZE)
		return 1;

	if (STbuffer->sg_segs) {
		printk(KERN_WARNING "osst :A: Buffer not previously normalized.\n");
		normalize_buffer(STbuffer);
	}
	/* See how many segments we can use -- need at least two */
	nbr = max_segs = STbuffer->use_sg;
	if (nbr <= 2)
		return 0;

	priority = GFP_KERNEL /* | __GFP_NOWARN */;
	if (need_dma)
		priority |= GFP_DMA;

	/* Try to allocate the first segment up to OS_DATA_SIZE and the others
	   big enough to reach the goal (code assumes no segments in place) */
	for (b_size = OS_DATA_SIZE, order = OSST_FIRST_ORDER; b_size >= PAGE_SIZE; order--, b_size /= 2) {
		STbuffer->sg[0].page = alloc_pages(priority, order);
		STbuffer->sg[0].offset = 0;
		if (STbuffer->sg[0].page != NULL) {
		    STbuffer->sg[0].length = b_size;
		    STbuffer->b_data = page_address(STbuffer->sg[0].page);
		    break;
		}
	}
	if (STbuffer->sg[0].page == NULL) {
		printk(KERN_NOTICE "osst :I: Can't allocate tape buffer main segment.\n");
		return 0;
	}
	/* Got initial segment of 'bsize,order', continue with same size if possible, except for AUX */
	for (segs=STbuffer->sg_segs=1, got=b_size;
	     segs < max_segs && got < OS_FRAME_SIZE; ) {
		STbuffer->sg[segs].page =
				alloc_pages(priority, (OS_FRAME_SIZE - got <= PAGE_SIZE) ? 0 : order);
		STbuffer->sg[segs].offset = 0;
		if (STbuffer->sg[segs].page == NULL) {
			if (OS_FRAME_SIZE - got <= (max_segs - segs) * b_size / 2 && order) {
				b_size /= 2;  /* Large enough for the rest of the buffers */
				order--;
				continue;
			}
			printk(KERN_WARNING "osst :W: Failed to enlarge buffer to %d bytes.\n",
						OS_FRAME_SIZE);
#if DEBUG
			STbuffer->buffer_size = got;
#endif
			normalize_buffer(STbuffer);
			return 0;
		}
		STbuffer->sg[segs].length = (OS_FRAME_SIZE - got <= PAGE_SIZE / 2) ? (OS_FRAME_SIZE - got) : b_size;
		got += STbuffer->sg[segs].length;
		STbuffer->buffer_size = got;
		STbuffer->sg_segs = ++segs;
	}
#if DEBUG
	if (debugging) {
		printk(OSST_DEB_MSG
			   "osst :D: Expanded tape buffer (%d bytes, %d->%d segments, dma: %d, at: %p).\n",
			   got, STbuffer->orig_sg_segs, STbuffer->sg_segs, need_dma, STbuffer->b_data);
		printk(OSST_DEB_MSG
			   "osst :D: segment sizes: first %d at %p, last %d bytes at %p.\n",
			   STbuffer->sg[0].length, page_address(STbuffer->sg[0].page),
			   STbuffer->sg[segs-1].length, page_address(STbuffer->sg[segs-1].page));
	}
#endif

	return 1;
}


/* Release the segments */
static void normalize_buffer(struct osst_buffer *STbuffer)
{
  int i, order, b_size;

	for (i=0; i < STbuffer->sg_segs; i++) {

		for (b_size = PAGE_SIZE, order = 0;
		     b_size < STbuffer->sg[i].length;
		     b_size *= 2, order++);

		__free_pages(STbuffer->sg[i].page, order);
		STbuffer->buffer_size -= STbuffer->sg[i].length;
	}
#if DEBUG
	if (debugging && STbuffer->orig_sg_segs < STbuffer->sg_segs)
		printk(OSST_DEB_MSG "osst :D: Buffer at %p normalized to %d bytes (segs %d).\n",
			     STbuffer->b_data, STbuffer->buffer_size, STbuffer->sg_segs);
#endif
	STbuffer->sg_segs = STbuffer->orig_sg_segs = 0;
}


/* Move data from the user buffer to the tape buffer. Returns zero (success) or
   negative error code. */
static int append_to_buffer(const char __user *ubp, struct osst_buffer *st_bp, int do_count)
{
	int i, cnt, res, offset;

	for (i=0, offset=st_bp->buffer_bytes;
	     i < st_bp->sg_segs && offset >= st_bp->sg[i].length; i++)
	offset -= st_bp->sg[i].length;
	if (i == st_bp->sg_segs) {  /* Should never happen */
		printk(KERN_WARNING "osst :A: Append_to_buffer offset overflow.\n");
		return (-EIO);
	}
	for ( ; i < st_bp->sg_segs && do_count > 0; i++) {
		cnt = st_bp->sg[i].length - offset < do_count ?
		      st_bp->sg[i].length - offset : do_count;
		res = copy_from_user(page_address(st_bp->sg[i].page) + offset, ubp, cnt);
		if (res)
			return (-EFAULT);
		do_count -= cnt;
		st_bp->buffer_bytes += cnt;
		ubp += cnt;
		offset = 0;
	}
	if (do_count) {  /* Should never happen */
		printk(KERN_WARNING "osst :A: Append_to_buffer overflow (left %d).\n",
		       do_count);
		return (-EIO);
	}
	return 0;
}


/* Move data from the tape buffer to the user buffer. Returns zero (success) or
   negative error code. */
static int from_buffer(struct osst_buffer *st_bp, char __user *ubp, int do_count)
{
	int i, cnt, res, offset;

	for (i=0, offset=st_bp->read_pointer;
	     i < st_bp->sg_segs && offset >= st_bp->sg[i].length; i++)
		offset -= st_bp->sg[i].length;
	if (i == st_bp->sg_segs) {  /* Should never happen */
		printk(KERN_WARNING "osst :A: From_buffer offset overflow.\n");
		return (-EIO);
	}
	for ( ; i < st_bp->sg_segs && do_count > 0; i++) {
		cnt = st_bp->sg[i].length - offset < do_count ?
		      st_bp->sg[i].length - offset : do_count;
		res = copy_to_user(ubp, page_address(st_bp->sg[i].page) + offset, cnt);
		if (res)
			return (-EFAULT);
		do_count -= cnt;
		st_bp->buffer_bytes -= cnt;
		st_bp->read_pointer += cnt;
		ubp += cnt;
		offset = 0;
	}
	if (do_count) {  /* Should never happen */
		printk(KERN_WARNING "osst :A: From_buffer overflow (left %d).\n", do_count);
		return (-EIO);
	}
	return 0;
}

/* Sets the tail of the buffer after fill point to zero.
   Returns zero (success) or negative error code.        */
static int osst_zero_buffer_tail(struct osst_buffer *st_bp)
{
	int	i, offset, do_count, cnt;

	for (i = 0, offset = st_bp->buffer_bytes;
	     i < st_bp->sg_segs && offset >= st_bp->sg[i].length; i++)
		offset -= st_bp->sg[i].length;
	if (i == st_bp->sg_segs) {  /* Should never happen */
		printk(KERN_WARNING "osst :A: Zero_buffer offset overflow.\n");
		return (-EIO);
	}
	for (do_count = OS_DATA_SIZE - st_bp->buffer_bytes;
	     i < st_bp->sg_segs && do_count > 0; i++) {
		cnt = st_bp->sg[i].length - offset < do_count ?
		      st_bp->sg[i].length - offset : do_count ;
		memset(page_address(st_bp->sg[i].page) + offset, 0, cnt);
		do_count -= cnt;
		offset = 0;
	}
	if (do_count) {  /* Should never happen */
		printk(KERN_WARNING "osst :A: Zero_buffer overflow (left %d).\n", do_count);
		return (-EIO);
	}
	return 0;
}

/* Copy a osst 32K chunk of memory into the buffer.
   Returns zero (success) or negative error code.  */
static int osst_copy_to_buffer(struct osst_buffer *st_bp, unsigned char *ptr)
{
	int	i, cnt, do_count = OS_DATA_SIZE;

	for (i = 0; i < st_bp->sg_segs && do_count > 0; i++) {
		cnt = st_bp->sg[i].length < do_count ?
		      st_bp->sg[i].length : do_count ;
		memcpy(page_address(st_bp->sg[i].page), ptr, cnt);
		do_count -= cnt;
		ptr      += cnt;
	}
	if (do_count || i != st_bp->sg_segs-1) {  /* Should never happen */
		printk(KERN_WARNING "osst :A: Copy_to_buffer overflow (left %d at sg %d).\n",
					 do_count, i);
		return (-EIO);
	}
	return 0;
}

/* Copy a osst 32K chunk of memory from the buffer.
   Returns zero (success) or negative error code.  */
static int osst_copy_from_buffer(struct osst_buffer *st_bp, unsigned char *ptr)
{
	int	i, cnt, do_count = OS_DATA_SIZE;

	for (i = 0; i < st_bp->sg_segs && do_count > 0; i++) {
		cnt = st_bp->sg[i].length < do_count ?
		      st_bp->sg[i].length : do_count ;
		memcpy(ptr, page_address(st_bp->sg[i].page), cnt);
		do_count -= cnt;
		ptr      += cnt;
	}
	if (do_count || i != st_bp->sg_segs-1) {  /* Should never happen */
		printk(KERN_WARNING "osst :A: Copy_from_buffer overflow (left %d at sg %d).\n",
					 do_count, i);
		return (-EIO);
	}
	return 0;
}


/* Module housekeeping */

static void validate_options (void)
{
  if (max_dev > 0)
		osst_max_dev = max_dev;  
  if (write_threshold_kbs > 0)
		osst_write_threshold = write_threshold_kbs * ST_KILOBYTE;
  if (osst_write_threshold > osst_buffer_size)
		osst_write_threshold = osst_buffer_size;
  if (max_sg_segs >= OSST_FIRST_SG)
		osst_max_sg_segs = max_sg_segs;
#if DEBUG
  printk(OSST_DEB_MSG "osst :D: max tapes %d, write threshold %d, max s/g segs %d.\n",
			   osst_max_dev, osst_write_threshold, osst_max_sg_segs);
#endif
}
	
#ifndef MODULE
/* Set the boot options. Syntax: osst=xxx,yyy,...
   where xxx is write threshold in 1024 byte blocks,
   and   yyy is number of s/g segments to use. */
static int __init osst_setup (char *str)
{
  int i, ints[5];
  char *stp;

  stp = get_options(str, ARRAY_SIZE(ints), ints);
	
  if (ints[0] > 0) {
	for (i = 0; i < ints[0] && i < ARRAY_SIZE(parms); i++)
		  *parms[i].val = ints[i + 1];
  } else {
	while (stp != NULL) {
		for (i = 0; i < ARRAY_SIZE(parms); i++) {
			int len = strlen(parms[i].name);
			if (!strncmp(stp, parms[i].name, len) &&
			    (*(stp + len) == ':' || *(stp + len) == '=')) {
				*parms[i].val =
					simple_strtoul(stp + len + 1, NULL, 0);
				break;
			}
		}
		if (i >= sizeof(parms) / sizeof(struct osst_dev_parm))
			printk(KERN_INFO "osst :I: Illegal parameter in '%s'\n",
			       stp);
		stp = strchr(stp, ',');
		if (stp)
			stp++;
	}
  }

  return 1;
}

__setup("osst=", osst_setup);

#endif

static struct file_operations osst_fops = {
	.owner =        THIS_MODULE,
	.read =         osst_read,
	.write =        osst_write,
	.ioctl =        osst_ioctl,
#ifdef CONFIG_COMPAT
	.compat_ioctl = osst_compat_ioctl,
#endif
	.open =         os_scsi_tape_open,
	.flush =        os_scsi_tape_flush,
	.release =      os_scsi_tape_close,
};

static int osst_supports(struct scsi_device * SDp)
{
	struct	osst_support_data {
		char *vendor;
		char *model;
		char *rev;
		char *driver_hint; /* Name of the correct driver, NULL if unknown */
	};

static	struct	osst_support_data support_list[] = {
		/* {"XXX", "Yy-", "", NULL},  example */
		SIGS_FROM_OSST,
		{NULL, }};

	struct	osst_support_data *rp;

	/* We are willing to drive OnStream SC-x0 as well as the
	 * 	 * IDE, ParPort, FireWire, USB variants, if accessible by
	 * 	 	 * emulation layer (ide-scsi, usb-storage, ...) */

	for (rp=&(support_list[0]); rp->vendor != NULL; rp++)
		if (!strncmp(rp->vendor, SDp->vendor, strlen(rp->vendor)) &&
		    !strncmp(rp->model, SDp->model, strlen(rp->model)) &&
		    !strncmp(rp->rev, SDp->rev, strlen(rp->rev))) 
			return 1;
	return 0;
}

/*
 * sysfs support for osst driver parameter information
 */

static ssize_t osst_version_show(struct device_driver *ddd, char *buf)
{
	return snprintf(buf, PAGE_SIZE, "%s\n", osst_version);
}

static DRIVER_ATTR(version, S_IRUGO, osst_version_show, NULL);

static void osst_create_driverfs_files(struct device_driver *driverfs)
{
	driver_create_file(driverfs, &driver_attr_version);
}

static void osst_remove_driverfs_files(struct device_driver *driverfs)
{
	driver_remove_file(driverfs, &driver_attr_version);
}

/*
 * sysfs support for accessing ADR header information
 */

static ssize_t osst_adr_rev_show(struct class_device *class_dev, char *buf)
{
	struct osst_tape * STp = (struct osst_tape *) class_get_devdata (class_dev);
	ssize_t l = 0;

	if (STp && STp->header_ok && STp->linux_media)
		l = snprintf(buf, PAGE_SIZE, "%d.%d\n", STp->header_cache->major_rev, STp->header_cache->minor_rev);
	return l;
}

CLASS_DEVICE_ATTR(ADR_rev, S_IRUGO, osst_adr_rev_show, NULL);

static ssize_t osst_linux_media_version_show(struct class_device *class_dev, char *buf)
{
	struct osst_tape * STp = (struct osst_tape *) class_get_devdata (class_dev);
	ssize_t l = 0;

	if (STp && STp->header_ok && STp->linux_media)
		l = snprintf(buf, PAGE_SIZE, "LIN%d\n", STp->linux_media_version);
	return l;
}

CLASS_DEVICE_ATTR(media_version, S_IRUGO, osst_linux_media_version_show, NULL);

static ssize_t osst_capacity_show(struct class_device *class_dev, char *buf)
{
	struct osst_tape * STp = (struct osst_tape *) class_get_devdata (class_dev);
	ssize_t l = 0;

	if (STp && STp->header_ok && STp->linux_media)
		l = snprintf(buf, PAGE_SIZE, "%d\n", STp->capacity);
	return l;
}

CLASS_DEVICE_ATTR(capacity, S_IRUGO, osst_capacity_show, NULL);

static ssize_t osst_first_data_ppos_show(struct class_device *class_dev, char *buf)
{
	struct osst_tape * STp = (struct osst_tape *) class_get_devdata (class_dev);
	ssize_t l = 0;

	if (STp && STp->header_ok && STp->linux_media)
		l = snprintf(buf, PAGE_SIZE, "%d\n", STp->first_data_ppos);
	return l;
}

CLASS_DEVICE_ATTR(BOT_frame, S_IRUGO, osst_first_data_ppos_show, NULL);

static ssize_t osst_eod_frame_ppos_show(struct class_device *class_dev, char *buf)
{
	struct osst_tape * STp = (struct osst_tape *) class_get_devdata (class_dev);
	ssize_t l = 0;

	if (STp && STp->header_ok && STp->linux_media)
		l = snprintf(buf, PAGE_SIZE, "%d\n", STp->eod_frame_ppos);
	return l;
}

CLASS_DEVICE_ATTR(EOD_frame, S_IRUGO, osst_eod_frame_ppos_show, NULL);

static ssize_t osst_filemark_cnt_show(struct class_device *class_dev, char *buf)
{
	struct osst_tape * STp = (struct osst_tape *) class_get_devdata (class_dev);
	ssize_t l = 0;

	if (STp && STp->header_ok && STp->linux_media)
		l = snprintf(buf, PAGE_SIZE, "%d\n", STp->filemark_cnt);
	return l;
}

CLASS_DEVICE_ATTR(file_count, S_IRUGO, osst_filemark_cnt_show, NULL);

static struct class_simple * osst_sysfs_class;

static int osst_sysfs_valid = 0;

static void osst_sysfs_init(void)
{
	osst_sysfs_class = class_simple_create(THIS_MODULE, "onstream_tape");
	if ( IS_ERR(osst_sysfs_class) )
		printk(KERN_WARNING "osst :W: Unable to register sysfs class\n");
	else
		osst_sysfs_valid = 1;
}

static void osst_sysfs_add(dev_t dev, struct device *device, struct osst_tape * STp, char * name)
{
	struct class_device *osst_class_member;

	if (!osst_sysfs_valid) return;

	osst_class_member = class_simple_device_add(osst_sysfs_class, dev, device, "%s", name);
	if (IS_ERR(osst_class_member)) {
		printk(KERN_WARNING "osst :W: Unable to add sysfs class member %s\n", name);
		return;
	}
	class_set_devdata(osst_class_member, STp);
	class_device_create_file(osst_class_member, &class_device_attr_ADR_rev);
	class_device_create_file(osst_class_member, &class_device_attr_media_version);
	class_device_create_file(osst_class_member, &class_device_attr_capacity);
	class_device_create_file(osst_class_member, &class_device_attr_BOT_frame);
	class_device_create_file(osst_class_member, &class_device_attr_EOD_frame);
	class_device_create_file(osst_class_member, &class_device_attr_file_count);
}

static void osst_sysfs_destroy(dev_t dev)
{
	if (!osst_sysfs_valid) return; 

	class_simple_device_remove(dev);
}

static void osst_sysfs_cleanup(void)
{
	if (osst_sysfs_valid) {
		class_simple_destroy(osst_sysfs_class);
		osst_sysfs_valid = 0;
	}
}

/*
 * osst startup / cleanup code
 */

static int osst_probe(struct device *dev)
{
	struct scsi_device * SDp = to_scsi_device(dev);
	struct osst_tape   * tpnt;
	struct st_modedef  * STm;
	struct st_partstat * STps;
	struct osst_buffer * buffer;
	struct gendisk	   * drive;
	int		     i, mode, dev_num;

	if (SDp->type != TYPE_TAPE || !osst_supports(SDp))
		return -ENODEV;

	drive = alloc_disk(1);
	if (!drive) {
		printk(KERN_ERR "osst :E: Out of memory. Device not attached.\n");
		return -ENODEV;
	}

	/* if this is the first attach, build the infrastructure */
	write_lock(&os_scsi_tapes_lock);
	if (os_scsi_tapes == NULL) {
		os_scsi_tapes =
			(struct osst_tape **)kmalloc(osst_max_dev * sizeof(struct osst_tape *),
				   GFP_ATOMIC);
		if (os_scsi_tapes == NULL) {
			write_unlock(&os_scsi_tapes_lock);
			printk(KERN_ERR "osst :E: Unable to allocate array for OnStream SCSI tapes.\n");
			goto out_put_disk;
		}
		for (i=0; i < osst_max_dev; ++i) os_scsi_tapes[i] = NULL;
	}
	
	if (osst_nr_dev >= osst_max_dev) {
		write_unlock(&os_scsi_tapes_lock);
		printk(KERN_ERR "osst :E: Too many tape devices (max. %d).\n", osst_max_dev);
		goto out_put_disk;
	}

	/* find a free minor number */
	for (i=0; os_scsi_tapes[i] && i<osst_max_dev; i++);
	if(i >= osst_max_dev) panic ("Scsi_devices corrupt (osst)");
	dev_num = i;

	/* allocate a struct osst_tape for this device */
	tpnt = (struct osst_tape *)kmalloc(sizeof(struct osst_tape), GFP_ATOMIC);
	if (tpnt == NULL) {
		write_unlock(&os_scsi_tapes_lock);
		printk(KERN_ERR "osst :E: Can't allocate device descriptor, device not attached.\n");
		goto out_put_disk;
	}
	memset(tpnt, 0, sizeof(struct osst_tape));

	/* allocate a buffer for this device */
	i = SDp->host->sg_tablesize;
	if (osst_max_sg_segs < i)
		i = osst_max_sg_segs;
	buffer = new_tape_buffer(1, SDp->host->unchecked_isa_dma, i);
	if (buffer == NULL) {
		write_unlock(&os_scsi_tapes_lock);
		printk(KERN_ERR "osst :E: Unable to allocate a tape buffer, device not attached.\n");
		kfree(tpnt);
		goto out_put_disk;
	}
	os_scsi_tapes[dev_num] = tpnt;
	tpnt->buffer = buffer;
	tpnt->device = SDp;
	drive->private_data = &tpnt->driver;
	sprintf(drive->disk_name, "osst%d", dev_num);
	tpnt->driver = &osst_template;
	tpnt->drive = drive;
	tpnt->in_use = 0;
	tpnt->capacity = 0xfffff;
	tpnt->dirty = 0;
	tpnt->drv_buffer = 1;  /* Try buffering if no mode sense */
	tpnt->restr_dma = (SDp->host)->unchecked_isa_dma;
	tpnt->density = 0;
	tpnt->do_auto_lock = OSST_AUTO_LOCK;
	tpnt->can_bsr = OSST_IN_FILE_POS;
	tpnt->can_partitions = 0;
	tpnt->two_fm = OSST_TWO_FM;
	tpnt->fast_mteom = OSST_FAST_MTEOM;
	tpnt->scsi2_logical = OSST_SCSI2LOGICAL; /* FIXME */
	tpnt->write_threshold = osst_write_threshold;
	tpnt->default_drvbuffer = 0xff; /* No forced buffering */
	tpnt->partition = 0;
	tpnt->new_partition = 0;
	tpnt->nbr_partitions = 0;
	tpnt->min_block = 512;
	tpnt->max_block = OS_DATA_SIZE;
	tpnt->timeout = OSST_TIMEOUT;
	tpnt->long_timeout = OSST_LONG_TIMEOUT;

	/* Recognize OnStream tapes */
	/* We don't need to test for OnStream, as this has been done in detect () */
	tpnt->os_fw_rev = osst_parse_firmware_rev (SDp->rev);
	tpnt->omit_blklims = 1;

	tpnt->poll = (strncmp(SDp->model, "DI-", 3) == 0) || 
		     (strncmp(SDp->model, "FW-", 3) == 0) || OSST_FW_NEED_POLL(tpnt->os_fw_rev,SDp);
	tpnt->frame_in_buffer = 0;
	tpnt->header_ok = 0;
	tpnt->linux_media = 0;
	tpnt->header_cache = NULL;

	for (i=0; i < ST_NBR_MODES; i++) {
		STm = &(tpnt->modes[i]);
		STm->defined = 0;
		STm->sysv = OSST_SYSV;
		STm->defaults_for_writes = 0;
		STm->do_async_writes = OSST_ASYNC_WRITES;
		STm->do_buffer_writes = OSST_BUFFER_WRITES;
		STm->do_read_ahead = OSST_READ_AHEAD;
		STm->default_compression = ST_DONT_TOUCH;
		STm->default_blksize = 512;
		STm->default_density = (-1);  /* No forced density */
	}

	for (i=0; i < ST_NBR_PARTITIONS; i++) {
		STps = &(tpnt->ps[i]);
		STps->rw = ST_IDLE;
		STps->eof = ST_NOEOF;
		STps->at_sm = 0;
		STps->last_block_valid = 0;
		STps->drv_block = (-1);
		STps->drv_file = (-1);
	}

	tpnt->current_mode = 0;
	tpnt->modes[0].defined = 1;
	tpnt->modes[2].defined = 1;
	tpnt->density_changed = tpnt->compression_changed = tpnt->blksize_changed = 0;

	init_MUTEX(&tpnt->lock);
	osst_nr_dev++;
	write_unlock(&os_scsi_tapes_lock);
	{
		char name[8];
		/*  Rewind entry  */
		osst_sysfs_add(MKDEV(OSST_MAJOR, dev_num), dev, tpnt, tape_name(tpnt));
		/*  No-rewind entry  */
		snprintf(name, 8, "%s%s", "n", tape_name(tpnt));
		osst_sysfs_add(MKDEV(OSST_MAJOR, dev_num + 128), dev, tpnt, name);
	}
	for (mode = 0; mode < ST_NBR_MODES; ++mode) {
		/*  Rewind entry  */
		devfs_mk_cdev(MKDEV(OSST_MAJOR, dev_num + (mode << 5)),
				S_IFCHR | S_IRUGO | S_IWUGO,
				"%s/ot%s", SDp->devfs_name, osst_formats[mode]);

		/*  No-rewind entry  */
		devfs_mk_cdev(MKDEV(OSST_MAJOR, dev_num + (mode << 5) + 128),
				S_IFCHR | S_IRUGO | S_IWUGO,
				"%s/ot%sn", SDp->devfs_name, osst_formats[mode]);
	}
	drive->number = devfs_register_tape(SDp->devfs_name);

	printk(KERN_INFO
		"osst :I: Attached OnStream %.5s tape at scsi%d, channel %d, id %d, lun %d as %s\n",
		SDp->model, SDp->host->host_no, SDp->channel, SDp->id, SDp->lun, tape_name(tpnt));

	return 0;

out_put_disk:
        put_disk(drive);
        return -ENODEV;
};

static int osst_remove(struct device *dev)
{
	struct scsi_device * SDp = to_scsi_device(dev);
	struct osst_tape * tpnt;
	int i, mode;

	if ((SDp->type != TYPE_TAPE) || (osst_nr_dev <= 0))
		return 0;

	write_lock(&os_scsi_tapes_lock);
	for(i=0; i < osst_max_dev; i++) {
		if((tpnt = os_scsi_tapes[i]) && (tpnt->device == SDp)) {
			osst_sysfs_destroy(MKDEV(OSST_MAJOR, i));
			osst_sysfs_destroy(MKDEV(OSST_MAJOR, i+128));
			tpnt->device = NULL;
			for (mode = 0; mode < ST_NBR_MODES; ++mode) {
				devfs_remove("%s/ot%s", SDp->devfs_name, osst_formats[mode]);
				devfs_remove("%s/ot%sn", SDp->devfs_name, osst_formats[mode]);
			}
			devfs_unregister_tape(tpnt->drive->number);
			put_disk(tpnt->drive);
			os_scsi_tapes[i] = NULL;
			osst_nr_dev--;
			write_unlock(&os_scsi_tapes_lock);
			if (tpnt->header_cache != NULL) vfree(tpnt->header_cache);
			if (tpnt->buffer) {
				normalize_buffer(tpnt->buffer);
				kfree(tpnt->buffer);
			}
			kfree(tpnt);
			return 0;
		}
	}
	write_unlock(&os_scsi_tapes_lock);
	return 0;
}

static int __init init_osst(void) 
{
	printk(KERN_INFO "osst :I: Tape driver with OnStream support version %s\nosst :I: %s\n", osst_version, cvsid);

	validate_options();
	osst_sysfs_init();

	if ((register_chrdev(OSST_MAJOR,"osst", &osst_fops) < 0) || scsi_register_driver(&osst_template.gendrv)) {
		printk(KERN_ERR "osst :E: Unable to register major %d for OnStream tapes\n", OSST_MAJOR);
		osst_sysfs_cleanup();
		return 1;
	}
	osst_create_driverfs_files(&osst_template.gendrv);

	return 0;
}

static void __exit exit_osst (void)
{
	int i;
	struct osst_tape * STp;

	osst_remove_driverfs_files(&osst_template.gendrv);
	scsi_unregister_driver(&osst_template.gendrv);
	unregister_chrdev(OSST_MAJOR, "osst");
	osst_sysfs_cleanup();

	if (os_scsi_tapes) {
		for (i=0; i < osst_max_dev; ++i) {
			if (!(STp = os_scsi_tapes[i])) continue;
			/* This is defensive, supposed to happen during detach */
			if (STp->header_cache)
				vfree(STp->header_cache);
			if (STp->buffer) {
				normalize_buffer(STp->buffer);
				kfree(STp->buffer);
			}
			put_disk(STp->drive);
			kfree(STp);
		}
		kfree(os_scsi_tapes);
	}
	printk(KERN_INFO "osst :I: Unloaded.\n");
}

module_init(init_osst);
module_exit(exit_osst);
OpenPOWER on IntegriCloud