aboutsummaryrefslogtreecommitdiffstats
path: root/scripts/kconfig/expr.c
blob: 579ece4fa584506a882e9e2bdd3e7fbb28d3b0c1 (plain) (blame)
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
/*
 * Copyright (C) 2002 Roman Zippel <zippel@linux-m68k.org>
 * Released under the terms of the GNU GPL v2.0.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define LKC_DIRECT_LINK
#include "lkc.h"

#define DEBUG_EXPR	0

struct expr *expr_alloc_symbol(struct symbol *sym)
{
	struct expr *e = malloc(sizeof(*e));
	memset(e, 0, sizeof(*e));
	e->type = E_SYMBOL;
	e->left.sym = sym;
	return e;
}

struct expr *expr_alloc_one(enum expr_type type, struct expr *ce)
{
	struct expr *e = malloc(sizeof(*e));
	memset(e, 0, sizeof(*e));
	e->type = type;
	e->left.expr = ce;
	return e;
}

struct expr *expr_alloc_two(enum expr_type type, struct expr *e1, struct expr *e2)
{
	struct expr *e = malloc(sizeof(*e));
	memset(e, 0, sizeof(*e));
	e->type = type;
	e->left.expr = e1;
	e->right.expr = e2;
	return e;
}

struct expr *expr_alloc_comp(enum expr_type type, struct symbol *s1, struct symbol *s2)
{
	struct expr *e = malloc(sizeof(*e));
	memset(e, 0, sizeof(*e));
	e->type = type;
	e->left.sym = s1;
	e->right.sym = s2;
	return e;
}

struct expr *expr_alloc_and(struct expr *e1, struct expr *e2)
{
	if (!e1)
		return e2;
	return e2 ? expr_alloc_two(E_AND, e1, e2) : e1;
}

struct expr *expr_alloc_or(struct expr *e1, struct expr *e2)
{
	if (!e1)
		return e2;
	return e2 ? expr_alloc_two(E_OR, e1, e2) : e1;
}

struct expr *expr_copy(struct expr *org)
{
	struct expr *e;

	if (!org)
		return NULL;

	e = malloc(sizeof(*org));
	memcpy(e, org, sizeof(*org));
	switch (org->type) {
	case E_SYMBOL:
		e->left = org->left;
		break;
	case E_NOT:
		e->left.expr = expr_copy(org->left.expr);
		break;
	case E_EQUAL:
	case E_UNEQUAL:
		e->left.sym = org->left.sym;
		e->right.sym = org->right.sym;
		break;
	case E_AND:
	case E_OR:
	case E_LIST:
		e->left.expr = expr_copy(org->left.expr);
		e->right.expr = expr_copy(org->right.expr);
		break;
	default:
		printf("can't copy type %d\n", e->type);
		free(e);
		e = NULL;
		break;
	}

	return e;
}

void expr_free(struct expr *e)
{
	if (!e)
		return;

	switch (e->type) {
	case E_SYMBOL:
		break;
	case E_NOT:
		expr_free(e->left.expr);
		return;
	case E_EQUAL:
	case E_UNEQUAL:
		break;
	case E_OR:
	case E_AND:
		expr_free(e->left.expr);
		expr_free(e->right.expr);
		break;
	default:
		printf("how to free type %d?\n", e->type);
		break;
	}
	free(e);
}

static int trans_count;

#define e1 (*ep1)
#define e2 (*ep2)

static void __expr_eliminate_eq(enum expr_type type, struct expr **ep1, struct expr **ep2)
{
	if (e1->type == type) {
		__expr_eliminate_eq(type, &e1->left.expr, &e2);
		__expr_eliminate_eq(type, &e1->right.expr, &e2);
		return;
	}
	if (e2->type == type) {
		__expr_eliminate_eq(type, &e1, &e2->left.expr);
		__expr_eliminate_eq(type, &e1, &e2->right.expr);
		return;
	}
	if (e1->type == E_SYMBOL && e2->type == E_SYMBOL &&
	    e1->left.sym == e2->left.sym &&
	    (e1->left.sym == &symbol_yes || e1->left.sym == &symbol_no))
		return;
	if (!expr_eq(e1, e2))
		return;
	trans_count++;
	expr_free(e1); expr_free(e2);
	switch (type) {
	case E_OR:
		e1 = expr_alloc_symbol(&symbol_no);
		e2 = expr_alloc_symbol(&symbol_no);
		break;
	case E_AND:
		e1 = expr_alloc_symbol(&symbol_yes);
		e2 = expr_alloc_symbol(&symbol_yes);
		break;
	default:
		;
	}
}

void expr_eliminate_eq(struct expr **ep1, struct expr **ep2)
{
	if (!e1 || !e2)
		return;
	switch (e1->type) {
	case E_OR:
	case E_AND:
		__expr_eliminate_eq(e1->type, ep1, ep2);
	default:
		;
	}
	if (e1->type != e2->type) switch (e2->type) {
	case E_OR:
	case E_AND:
		__expr_eliminate_eq(e2->type, ep1, ep2);
	default:
		;
	}
	e1 = expr_eliminate_yn(e1);
	e2 = expr_eliminate_yn(e2);
}

#undef e1
#undef e2

int expr_eq(struct expr *e1, struct expr *e2)
{
	int res, old_count;

	if (e1->type != e2->type)
		return 0;
	switch (e1->type) {
	case E_EQUAL:
	case E_UNEQUAL:
		return e1->left.sym == e2->left.sym && e1->right.sym == e2->right.sym;
	case E_SYMBOL:
		return e1->left.sym == e2->left.sym;
	case E_NOT:
		return expr_eq(e1->left.expr, e2->left.expr);
	case E_AND:
	case E_OR:
		e1 = expr_copy(e1);
		e2 = expr_copy(e2);
		old_count = trans_count;
		expr_eliminate_eq(&e1, &e2);
		res = (e1->type == E_SYMBOL && e2->type == E_SYMBOL &&
		       e1->left.sym == e2->left.sym);
		expr_free(e1);
		expr_free(e2);
		trans_count = old_count;
		return res;
	case E_LIST:
	case E_RANGE:
	case E_NONE:
		/* panic */;
	}

	if (DEBUG_EXPR) {
		expr_fprint(e1, stdout);
		printf(" = ");
		expr_fprint(e2, stdout);
		printf(" ?\n");
	}

	return 0;
}

struct expr *expr_eliminate_yn(struct expr *e)
{
	struct expr *tmp;

	if (e) switch (e->type) {
	case E_AND:
		e->left.expr = expr_eliminate_yn(e->left.expr);
		e->right.expr = expr_eliminate_yn(e->right.expr);
		if (e->left.expr->type == E_SYMBOL) {
			if (e->left.expr->left.sym == &symbol_no) {
				expr_free(e->left.expr);
				expr_free(e->right.expr);
				e->type = E_SYMBOL;
				e->left.sym = &symbol_no;
				e->right.expr = NULL;
				return e;
			} else if (e->left.expr->left.sym == &symbol_yes) {
				free(e->left.expr);
				tmp = e->right.expr;
				*e = *(e->right.expr);
				free(tmp);
				return e;
			}
		}
		if (e->right.expr->type == E_SYMBOL) {
			if (e->right.expr->left.sym == &symbol_no) {
				expr_free(e->left.expr);
				expr_free(e->right.expr);
				e->type = E_SYMBOL;
				e->left.sym = &symbol_no;
				e->right.expr = NULL;
				return e;
			} else if (e->right.expr->left.sym == &symbol_yes) {
				free(e->right.expr);
				tmp = e->left.expr;
				*e = *(e->left.expr);
				free(tmp);
				return e;
			}
		}
		break;
	case E_OR:
		e->left.expr = expr_eliminate_yn(e->left.expr);
		e->right.expr = expr_eliminate_yn(e->right.expr);
		if (e->left.expr->type == E_SYMBOL) {
			if (e->left.expr->left.sym == &symbol_no) {
				free(e->left.expr);
				tmp = e->right.expr;
				*e = *(e->right.expr);
				free(tmp);
				return e;
			} else if (e->left.expr->left.sym == &symbol_yes) {
				expr_free(e->left.expr);
				expr_free(e->right.expr);
				e->type = E_SYMBOL;
				e->left.sym = &symbol_yes;
				e->right.expr = NULL;
				return e;
			}
		}
		if (e->right.expr->type == E_SYMBOL) {
			if (e->right.expr->left.sym == &symbol_no) {
				free(e->right.expr);
				tmp = e->left.expr;
				*e = *(e->left.expr);
				free(tmp);
				return e;
			} else if (e->right.expr->left.sym == &symbol_yes) {
				expr_free(e->left.expr);
				expr_free(e->right.expr);
				e->type = E_SYMBOL;
				e->left.sym = &symbol_yes;
				e->right.expr = NULL;
				return e;
			}
		}
		break;
	default:
		;
	}
	return e;
}

/*
 * bool FOO!=n => FOO
 */
struct expr *expr_trans_bool(struct expr *e)
{
	if (!e)
		return NULL;
	switch (e->type) {
	case E_AND:
	case E_OR:
	case E_NOT:
		e->left.expr = expr_trans_bool(e->left.expr);
		e->right.expr = expr_trans_bool(e->right.expr);
		break;
	case E_UNEQUAL:
		// FOO!=n -> FOO
		if (e->left.sym->type == S_TRISTATE) {
			if (e->right.sym == &symbol_no) {
				e->type = E_SYMBOL;
				e->right.sym = NULL;
			}
		}
		break;
	default:
		;
	}
	return e;
}

/*
 * e1 || e2 -> ?
 */
struct expr *expr_join_or(struct expr *e1, struct expr *e2)
{
	struct expr *tmp;
	struct symbol *sym1, *sym2;

	if (expr_eq(e1, e2))
		return expr_copy(e1);
	if (e1->type != E_EQUAL && e1->type != E_UNEQUAL && e1->type != E_SYMBOL && e1->type != E_NOT)
		return NULL;
	if (e2->type != E_EQUAL && e2->type != E_UNEQUAL && e2->type != E_SYMBOL && e2->type != E_NOT)
		return NULL;
	if (e1->type == E_NOT) {
		tmp = e1->left.expr;
		if (tmp->type != E_EQUAL && tmp->type != E_UNEQUAL && tmp->type != E_SYMBOL)
			return NULL;
		sym1 = tmp->left.sym;
	} else
		sym1 = e1->left.sym;
	if (e2->type == E_NOT) {
		if (e2->left.expr->type != E_SYMBOL)
			return NULL;
		sym2 = e2->left.expr->left.sym;
	} else
		sym2 = e2->left.sym;
	if (sym1 != sym2)
		return NULL;
	if (sym1->type != S_BOOLEAN && sym1->type != S_TRISTATE)
		return NULL;
	if (sym1->type == S_TRISTATE) {
		if (e1->type == E_EQUAL && e2->type == E_EQUAL &&
		    ((e1->right.sym == &symbol_yes && e2->right.sym == &symbol_mod) ||
		     (e1->right.sym == &symbol_mod && e2->right.sym == &symbol_yes))) {
			// (a='y') || (a='m') -> (a!='n')
			return expr_alloc_comp(E_UNEQUAL, sym1, &symbol_no);
		}
		if (e1->type == E_EQUAL && e2->type == E_EQUAL &&
		    ((e1->right.sym == &symbol_yes && e2->right.sym == &symbol_no) ||
		     (e1->right.sym == &symbol_no && e2->right.sym == &symbol_yes))) {
			// (a='y') || (a='n') -> (a!='m')
			return expr_alloc_comp(E_UNEQUAL, sym1, &symbol_mod);
		}
		if (e1->type == E_EQUAL && e2->type == E_EQUAL &&
		    ((e1->right.sym == &symbol_mod && e2->right.sym == &symbol_no) ||
		     (e1->right.sym == &symbol_no && e2->right.sym == &symbol_mod))) {
			// (a='m') || (a='n') -> (a!='y')
			return expr_alloc_comp(E_UNEQUAL, sym1, &symbol_yes);
		}
	}
	if (sym1->type == S_BOOLEAN && sym1 == sym2) {
		if ((e1->type == E_NOT && e1->left.expr->type == E_SYMBOL && e2->type == E_SYMBOL) ||
		    (e2->type == E_NOT && e2->left.expr->type == E_SYMBOL && e1->type == E_SYMBOL))
			return expr_alloc_symbol(&symbol_yes);
	}

	if (DEBUG_EXPR) {
		printf("optimize (");
		expr_fprint(e1, stdout);
		printf(") || (");
		expr_fprint(e2, stdout);
		printf(")?\n");
	}
	return NULL;
}

struct expr *expr_join_and(struct expr *e1, struct expr *e2)
{
	struct expr *tmp;
	struct symbol *sym1, *sym2;

	if (expr_eq(e1, e2))
		return expr_copy(e1);
	if (e1->type != E_EQUAL && e1->type != E_UNEQUAL && e1->type != E_SYMBOL && e1->type != E_NOT)
		return NULL;
	if (e2->type != E_EQUAL && e2->type != E_UNEQUAL && e2->type != E_SYMBOL && e2->type != E_NOT)
		return NULL;
	if (e1->type == E_NOT) {
		tmp = e1->left.expr;
		if (tmp->type != E_EQUAL && tmp->type != E_UNEQUAL && tmp->type != E_SYMBOL)
			return NULL;
		sym1 = tmp->left.sym;
	} else
		sym1 = e1->left.sym;
	if (e2->type == E_NOT) {
		if (e2->left.expr->type != E_SYMBOL)
			return NULL;
		sym2 = e2->left.expr->left.sym;
	} else
		sym2 = e2->left.sym;
	if (sym1 != sym2)
		return NULL;
	if (sym1->type != S_BOOLEAN && sym1->type != S_TRISTATE)
		return NULL;

	if ((e1->type == E_SYMBOL && e2->type == E_EQUAL && e2->right.sym == &symbol_yes) ||
	    (e2->type == E_SYMBOL && e1->type == E_EQUAL && e1->right.sym == &symbol_yes))
		// (a) && (a='y') -> (a='y')
		return expr_alloc_comp(E_EQUAL, sym1, &symbol_yes);

	if ((e1->type == E_SYMBOL && e2->type == E_UNEQUAL && e2->right.sym == &symbol_no) ||
	    (e2->type == E_SYMBOL && e1->type == E_UNEQUAL && e1->right.sym == &symbol_no))
		// (a) && (a!='n') -> (a)
		return expr_alloc_symbol(sym1);

	if ((e1->type == E_SYMBOL && e2->type == E_UNEQUAL && e2->right.sym == &symbol_mod) ||
	    (e2->type == E_SYMBOL && e1->type == E_UNEQUAL && e1->right.sym == &symbol_mod))
		// (a) && (a!='m') -> (a='y')
		return expr_alloc_comp(E_EQUAL, sym1, &symbol_yes);

	if (sym1->type == S_TRISTATE) {
		if (e1->type == E_EQUAL && e2->type == E_UNEQUAL) {
			// (a='b') && (a!='c') -> 'b'='c' ? 'n' : a='b'
			sym2 = e1->right.sym;
			if ((e2->right.sym->flags & SYMBOL_CONST) && (sym2->flags & SYMBOL_CONST))
				return sym2 != e2->right.sym ? expr_alloc_comp(E_EQUAL, sym1, sym2)
							     : expr_alloc_symbol(&symbol_no);
		}
		if (e1->type == E_UNEQUAL && e2->type == E_EQUAL) {
			// (a='b') && (a!='c') -> 'b'='c' ? 'n' : a='b'
			sym2 = e2->right.sym;
			if ((e1->right.sym->flags & SYMBOL_CONST) && (sym2->flags & SYMBOL_CONST))
				return sym2 != e1->right.sym ? expr_alloc_comp(E_EQUAL, sym1, sym2)
							     : expr_alloc_symbol(&symbol_no);
		}
		if (e1->type == E_UNEQUAL && e2->type == E_UNEQUAL &&
			   ((e1->right.sym == &symbol_yes && e2->right.sym == &symbol_no) ||
			    (e1->right.sym == &symbol_no && e2->right.sym == &symbol_yes)))
			// (a!='y') && (a!='n') -> (a='m')
			return expr_alloc_comp(E_EQUAL, sym1, &symbol_mod);

		if (e1->type == E_UNEQUAL && e2->type == E_UNEQUAL &&
			   ((e1->right.sym == &symbol_yes && e2->right.sym == &symbol_mod) ||
			    (e1->right.sym == &symbol_mod && e2->right.sym == &symbol_yes)))
			// (a!='y') && (a!='m') -> (a='n')
			return expr_alloc_comp(E_EQUAL, sym1, &symbol_no);

		if (e1->type == E_UNEQUAL && e2->type == E_UNEQUAL &&
			   ((e1->right.sym == &symbol_mod && e2->right.sym == &symbol_no) ||
			    (e1->right.sym == &symbol_no && e2->right.sym == &symbol_mod)))
			// (a!='m') && (a!='n') -> (a='m')
			return expr_alloc_comp(E_EQUAL, sym1, &symbol_yes);

		if ((e1->type == E_SYMBOL && e2->type == E_EQUAL && e2->right.sym == &symbol_mod) ||
		    (e2->type == E_SYMBOL && e1->type == E_EQUAL && e1->right.sym == &symbol_mod) ||
		    (e1->type == E_SYMBOL && e2->type == E_UNEQUAL && e2->right.sym == &symbol_yes) ||
		    (e2->type == E_SYMBOL && e1->type == E_UNEQUAL && e1->right.sym == &symbol_yes))
			return NULL;
	}

	if (DEBUG_EXPR) {
		printf("optimize (");
		expr_fprint(e1, stdout);
		printf(") && (");
		expr_fprint(e2, stdout);
		printf(")?\n");
	}
	return NULL;
}

static void expr_eliminate_dups1(enum expr_type type, struct expr **ep1, struct expr **ep2)
{
#define e1 (*ep1)
#define e2 (*ep2)
	struct expr *tmp;

	if (e1->type == type) {
		expr_eliminate_dups1(type, &e1->left.expr, &e2);
		expr_eliminate_dups1(type, &e1->right.expr, &e2);
		return;
	}
	if (e2->type == type) {
		expr_eliminate_dups1(type, &e1, &e2->left.expr);
		expr_eliminate_dups1(type, &e1, &e2->right.expr);
		return;
	}
	if (e1 == e2)
		return;

	switch (e1->type) {
	case E_OR: case E_AND:
		expr_eliminate_dups1(e1->type, &e1, &e1);
	default:
		;
	}

	switch (type) {
	case E_OR:
		tmp = expr_join_or(e1, e2);
		if (tmp) {
			expr_free(e1); expr_free(e2);
			e1 = expr_alloc_symbol(&symbol_no);
			e2 = tmp;
			trans_count++;
		}
		break;
	case E_AND:
		tmp = expr_join_and(e1, e2);
		if (tmp) {
			expr_free(e1); expr_free(e2);
			e1 = expr_alloc_symbol(&symbol_yes);
			e2 = tmp;
			trans_count++;
		}
		break;
	default:
		;
	}
#undef e1
#undef e2
}

static void expr_eliminate_dups2(enum expr_type type, struct expr **ep1, struct expr **ep2)
{
#define e1 (*ep1)
#define e2 (*ep2)
	struct expr *tmp, *tmp1, *tmp2;

	if (e1->type == type) {
		expr_eliminate_dups2(type, &e1->left.expr, &e2);
		expr_eliminate_dups2(type, &e1->right.expr, &e2);
		return;
	}
	if (e2->type == type) {
		expr_eliminate_dups2(type, &e1, &e2->left.expr);
		expr_eliminate_dups2(type, &e1, &e2->right.expr);
	}
	if (e1 == e2)
		return;

	switch (e1->type) {
	case E_OR:
		expr_eliminate_dups2(e1->type, &e1, &e1);
		// (FOO || BAR) && (!FOO && !BAR) -> n
		tmp1 = expr_transform(expr_alloc_one(E_NOT, expr_copy(e1)));
		tmp2 = expr_copy(e2);
		tmp = expr_extract_eq_and(&tmp1, &tmp2);
		if (expr_is_yes(tmp1)) {
			expr_free(e1);
			e1 = expr_alloc_symbol(&symbol_no);
			trans_count++;
		}
		expr_free(tmp2);
		expr_free(tmp1);
		expr_free(tmp);
		break;
	case E_AND:
		expr_eliminate_dups2(e1->type, &e1, &e1);
		// (FOO && BAR) || (!FOO || !BAR) -> y
		tmp1 = expr_transform(expr_alloc_one(E_NOT, expr_copy(e1)));
		tmp2 = expr_copy(e2);
		tmp = expr_extract_eq_or(&tmp1, &tmp2);
		if (expr_is_no(tmp1)) {
			expr_free(e1);
			e1 = expr_alloc_symbol(&symbol_yes);
			trans_count++;
		}
		expr_free(tmp2);
		expr_free(tmp1);
		expr_free(tmp);
		break;
	default:
		;
	}
#undef e1
#undef e2
}

struct expr *expr_eliminate_dups(struct expr *e)
{
	int oldcount;
	if (!e)
		return e;

	oldcount = trans_count;
	while (1) {
		trans_count = 0;
		switch (e->type) {
		case E_OR: case E_AND:
			expr_eliminate_dups1(e->type, &e, &e);
			expr_eliminate_dups2(e->type, &e, &e);
		default:
			;
		}
		if (!trans_count)
			break;
		e = expr_eliminate_yn(e);
	}
	trans_count = oldcount;
	return e;
}

struct expr *expr_transform(struct expr *e)
{
	struct expr *tmp;

	if (!e)
		return NULL;
	switch (e->type) {
	case E_EQUAL:
	case E_UNEQUAL:
	case E_SYMBOL:
	case E_LIST:
		break;
	default:
		e->left.expr = expr_transform(e->left.expr);
		e->right.expr = expr_transform(e->right.expr);
	}

	switch (e->type) {
	case E_EQUAL:
		if (e->left.sym->type != S_BOOLEAN)
			break;
		if (e->right.sym == &symbol_no) {
			e->type = E_NOT;
			e->left.expr = expr_alloc_symbol(e->left.sym);
			e->right.sym = NULL;
			break;
		}
		if (e->right.sym == &symbol_mod) {
			printf("boolean symbol %s tested for 'm'? test forced to 'n'\n", e->left.sym->name);
			e->type = E_SYMBOL;
			e->left.sym = &symbol_no;
			e->right.sym = NULL;
			break;
		}
		if (e->right.sym == &symbol_yes) {
			e->type = E_SYMBOL;
			e->right.sym = NULL;
			break;
		}
		break;
	case E_UNEQUAL:
		if (e->left.sym->type != S_BOOLEAN)
			break;
		if (e->right.sym == &symbol_no) {
			e->type = E_SYMBOL;
			e->right.sym = NULL;
			break;
		}
		if (e->right.sym == &symbol_mod) {
			printf("boolean symbol %s tested for 'm'? test forced to 'y'\n", e->left.sym->name);
			e->type = E_SYMBOL;
			e->left.sym = &symbol_yes;
			e->right.sym = NULL;
			break;
		}
		if (e->right.sym == &symbol_yes) {
			e->type = E_NOT;
			e->left.expr = expr_alloc_symbol(e->left.sym);
			e->right.sym = NULL;
			break;
		}
		break;
	case E_NOT:
		switch (e->left.expr->type) {
		case E_NOT:
			// !!a -> a
			tmp = e->left.expr->left.expr;
			free(e->left.expr);
			free(e);
			e = tmp;
			e = expr_transform(e);
			break;
		case E_EQUAL:
		case E_UNEQUAL:
			// !a='x' -> a!='x'
			tmp = e->left.expr;
			free(e);
			e = tmp;
			e->type = e->type == E_EQUAL ? E_UNEQUAL : E_EQUAL;
			break;
		case E_OR:
			// !(a || b) -> !a && !b
			tmp = e->left.expr;
			e->type = E_AND;
			e->right.expr = expr_alloc_one(E_NOT, tmp->right.expr);
			tmp->type = E_NOT;
			tmp->right.expr = NULL;
			e = expr_transform(e);
			break;
		case E_AND:
			// !(a && b) -> !a || !b
			tmp = e->left.expr;
			e->type = E_OR;
			e->right.expr = expr_alloc_one(E_NOT, tmp->right.expr);
			tmp->type = E_NOT;
			tmp->right.expr = NULL;
			e = expr_transform(e);
			break;
		case E_SYMBOL:
			if (e->left.expr->left.sym == &symbol_yes) {
				// !'y' -> 'n'
				tmp = e->left.expr;
				free(e);
				e = tmp;
				e->type = E_SYMBOL;
				e->left.sym = &symbol_no;
				break;
			}
			if (e->left.expr->left.sym == &symbol_mod) {
				// !'m' -> 'm'
				tmp = e->left.expr;
				free(e);
				e = tmp;
				e->type = E_SYMBOL;
				e->left.sym = &symbol_mod;
				break;
			}
			if (e->left.expr->left.sym == &symbol_no) {
				// !'n' -> 'y'
				tmp = e->left.expr;
				free(e);
				e = tmp;
				e->type = E_SYMBOL;
				e->left.sym = &symbol_yes;
				break;
			}
			break;
		default:
			;
		}
		break;
	default:
		;
	}
	return e;
}

int expr_contains_symbol(struct expr *dep, struct symbol *sym)
{
	if (!dep)
		return 0;

	switch (dep->type) {
	case E_AND:
	case E_OR:
		return expr_contains_symbol(dep->left.expr, sym) ||
		       expr_contains_symbol(dep->right.expr, sym);
	case E_SYMBOL:
		return dep->left.sym == sym;
	case E_EQUAL:
	case E_UNEQUAL:
		return dep->left.sym == sym ||
		       dep->right.sym == sym;
	case E_NOT:
		return expr_contains_symbol(dep->left.expr, sym);
	default:
		;
	}
	return 0;
}

bool expr_depends_symbol(struct expr *dep, struct symbol *sym)
{
	if (!dep)
		return false;

	switch (dep->type) {
	case E_AND:
		return expr_depends_symbol(dep->left.expr, sym) ||
		       expr_depends_symbol(dep->right.expr, sym);
	case E_SYMBOL:
		return dep->left.sym == sym;
	case E_EQUAL:
		if (dep->left.sym == sym) {
			if (dep->right.sym == &symbol_yes || dep->right.sym == &symbol_mod)
				return true;
		}
		break;
	case E_UNEQUAL:
		if (dep->left.sym == sym) {
			if (dep->right.sym == &symbol_no)
				return true;
		}
		break;
	default:
		;
	}
 	return false;
}

struct expr *expr_extract_eq_and(struct expr **ep1, struct expr **ep2)
{
	struct expr *tmp = NULL;
	expr_extract_eq(E_AND, &tmp, ep1, ep2);
	if (tmp) {
		*ep1 = expr_eliminate_yn(*ep1);
		*ep2 = expr_eliminate_yn(*ep2);
	}
	return tmp;
}

struct expr *expr_extract_eq_or(struct expr **ep1, struct expr **ep2)
{
	struct expr *tmp = NULL;
	expr_extract_eq(E_OR, &tmp, ep1, ep2);
	if (tmp) {
		*ep1 = expr_eliminate_yn(*ep1);
		*ep2 = expr_eliminate_yn(*ep2);
	}
	return tmp;
}

void expr_extract_eq(enum expr_type type, struct expr **ep, struct expr **ep1, struct expr **ep2)
{
#define e1 (*ep1)
#define e2 (*ep2)
	if (e1->type == type) {
		expr_extract_eq(type, ep, &e1->left.expr, &e2);
		expr_extract_eq(type, ep, &e1->right.expr, &e2);
		return;
	}
	if (e2->type == type) {
		expr_extract_eq(type, ep, ep1, &e2->left.expr);
		expr_extract_eq(type, ep, ep1, &e2->right.expr);
		return;
	}
	if (expr_eq(e1, e2)) {
		*ep = *ep ? expr_alloc_two(type, *ep, e1) : e1;
		expr_free(e2);
		if (type == E_AND) {
			e1 = expr_alloc_symbol(&symbol_yes);
			e2 = expr_alloc_symbol(&symbol_yes);
		} else if (type == E_OR) {
			e1 = expr_alloc_symbol(&symbol_no);
			e2 = expr_alloc_symbol(&symbol_no);
		}
	}
#undef e1
#undef e2
}

struct expr *expr_trans_compare(struct expr *e, enum expr_type type, struct symbol *sym)
{
	struct expr *e1, *e2;

	if (!e) {
		e = expr_alloc_symbol(sym);
		if (type == E_UNEQUAL)
			e = expr_alloc_one(E_NOT, e);
		return e;
	}
	switch (e->type) {
	case E_AND:
		e1 = expr_trans_compare(e->left.expr, E_EQUAL, sym);
		e2 = expr_trans_compare(e->right.expr, E_EQUAL, sym);
		if (sym == &symbol_yes)
			e = expr_alloc_two(E_AND, e1, e2);
		if (sym == &symbol_no)
			e = expr_alloc_two(E_OR, e1, e2);
		if (type == E_UNEQUAL)
			e = expr_alloc_one(E_NOT, e);
		return e;
	case E_OR:
		e1 = expr_trans_compare(e->left.expr, E_EQUAL, sym);
		e2 = expr_trans_compare(e->right.expr, E_EQUAL, sym);
		if (sym == &symbol_yes)
			e = expr_alloc_two(E_OR, e1, e2);
		if (sym == &symbol_no)
			e = expr_alloc_two(E_AND, e1, e2);
		if (type == E_UNEQUAL)
			e = expr_alloc_one(E_NOT, e);
		return e;
	case E_NOT:
		return expr_trans_compare(e->left.expr, type == E_EQUAL ? E_UNEQUAL : E_EQUAL, sym);
	case E_UNEQUAL:
	case E_EQUAL:
		if (type == E_EQUAL) {
			if (sym == &symbol_yes)
				return expr_copy(e);
			if (sym == &symbol_mod)
				return expr_alloc_symbol(&symbol_no);
			if (sym == &symbol_no)
				return expr_alloc_one(E_NOT, expr_copy(e));
		} else {
			if (sym == &symbol_yes)
				return expr_alloc_one(E_NOT, expr_copy(e));
			if (sym == &symbol_mod)
				return expr_alloc_symbol(&symbol_yes);
			if (sym == &symbol_no)
				return expr_copy(e);
		}
		break;
	case E_SYMBOL:
		return expr_alloc_comp(type, e->left.sym, sym);
	case E_LIST:
	case E_RANGE:
	case E_NONE:
		/* panic */;
	}
	return NULL;
}

tristate expr_calc_value(struct expr *e)
{
	tristate val1, val2;
	const char *str1, *str2;

	if (!e)
		return yes;

	switch (e->type) {
	case E_SYMBOL:
		sym_calc_value(e->left.sym);
		return e->left.sym->curr.tri;
	case E_AND:
		val1 = expr_calc_value(e->left.expr);
		val2 = expr_calc_value(e->right.expr);
		return EXPR_AND(val1, val2);
	case E_OR:
		val1 = expr_calc_value(e->left.expr);
		val2 = expr_calc_value(e->right.expr);
		return EXPR_OR(val1, val2);
	case E_NOT:
		val1 = expr_calc_value(e->left.expr);
		return EXPR_NOT(val1);
	case E_EQUAL:
		sym_calc_value(e->left.sym);
		sym_calc_value(e->right.sym);
		str1 = sym_get_string_value(e->left.sym);
		str2 = sym_get_string_value(e->right.sym);
		return !strcmp(str1, str2) ? yes : no;
	case E_UNEQUAL:
		sym_calc_value(e->left.sym);
		sym_calc_value(e->right.sym);
		str1 = sym_get_string_value(e->left.sym);
		str2 = sym_get_string_value(e->right.sym);
		return !strcmp(str1, str2) ? no : yes;
	default:
		printf("expr_calc_value: %d?\n", e->type);
		return no;
	}
}

int expr_compare_type(enum expr_type t1, enum expr_type t2)
{
#if 0
	return 1;
#else
	if (t1 == t2)
		return 0;
	switch (t1) {
	case E_EQUAL:
	case E_UNEQUAL:
		if (t2 == E_NOT)
			return 1;
	case E_NOT:
		if (t2 == E_AND)
			return 1;
	case E_AND:
		if (t2 == E_OR)
			return 1;
	case E_OR:
		if (t2 == E_LIST)
			return 1;
	case E_LIST:
		if (t2 == 0)
			return 1;
	default:
		return -1;
	}
	printf("[%dgt%d?]", t1, t2);
	return 0;
#endif
}

void expr_print(struct expr *e, void (*fn)(void *, struct symbol *, const char *), void *data, int prevtoken)
{
	if (!e) {
		fn(data, NULL, "y");
		return;
	}

	if (expr_compare_type(prevtoken, e->type) > 0)
		fn(data, NULL, "(");
	switch (e->type) {
	case E_SYMBOL:
		if (e->left.sym->name)
			fn(data, e->left.sym, e->left.sym->name);
		else
			fn(data, NULL, "<choice>");
		break;
	case E_NOT:
		fn(data, NULL, "!");
		expr_print(e->left.expr, fn, data, E_NOT);
		break;
	case E_EQUAL:
		if (e->left.sym->name)
			fn(data, e->left.sym, e->left.sym->name);
		else
			fn(data, NULL, "<choice>");
		fn(data, NULL, "=");
		fn(data, e->right.sym, e->right.sym->name);
		break;
	case E_UNEQUAL:
		if (e->left.sym->name)
			fn(data, e->left.sym, e->left.sym->name);
		else
			fn(data, NULL, "<choice>");
		fn(data, NULL, "!=");
		fn(data, e->right.sym, e->right.sym->name);
		break;
	case E_OR:
		expr_print(e->left.expr, fn, data, E_OR);
		fn(data, NULL, " || ");
		expr_print(e->right.expr, fn, data, E_OR);
		break;
	case E_AND:
		expr_print(e->left.expr, fn, data, E_AND);
		fn(data, NULL, " && ");
		expr_print(e->right.expr, fn, data, E_AND);
		break;
	case E_LIST:
		fn(data, e->right.sym, e->right.sym->name);
		if (e->left.expr) {
			fn(data, NULL, " ^ ");
			expr_print(e->left.expr, fn, data, E_LIST);
		}
		break;
	case E_RANGE:
		fn(data, NULL, "[");
		fn(data, e->left.sym, e->left.sym->name);
		fn(data, NULL, " ");
		fn(data, e->right.sym, e->right.sym->name);
		fn(data, NULL, "]");
		break;
	default:
	  {
		char buf[32];
		sprintf(buf, "<unknown type %d>", e->type);
		fn(data, NULL, buf);
		break;
	  }
	}
	if (expr_compare_type(prevtoken, e->type) > 0)
		fn(data, NULL, ")");
}

static void expr_print_file_helper(void *data, struct symbol *sym, const char *str)
{
	fwrite(str, strlen(str), 1, data);
}

void expr_fprint(struct expr *e, FILE *out)
{
	expr_print(e, expr_print_file_helper, out, E_NONE);
}

static void expr_print_gstr_helper(void *data, struct symbol *sym, const char *str)
{
	str_append((struct gstr*)data, str);
}

void expr_gstr_print(struct expr *e, struct gstr *gs)
{
	expr_print(e, expr_print_gstr_helper, gs, E_NONE);
}
5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966
/*
 *  sbpcd.c   CD-ROM device driver for the whole family of traditional,
 *            non-ATAPI IDE-style Matsushita/Panasonic CR-5xx drives.
 *            Works with SoundBlaster compatible cards and with "no-sound"
 *            interface cards like Lasermate, Panasonic CI-101P, Teac, ...
 *            Also for the Longshine LCS-7260 drive.
 *            Also for the IBM "External ISA CD-Rom" drive.
 *            Also for the CreativeLabs CD200 drive.
 *            Also for the TEAC CD-55A drive.
 *            Also for the ECS-AT "Vertos 100" drive.
 *            Not for Sanyo drives (but for the H94A, sjcd is there...).
 *            Not for any other Funai drives than the CD200 types (sometimes
 *             labelled E2550UA or MK4015 or 2800F).
 */

#define VERSION "v4.63 Andrew J. Kroll <ag784@freenet.buffalo.edu> Wed Jul 26 04:24:10 EDT 2000"

/*   Copyright (C) 1993, 1994, 1995  Eberhard Moenkeberg <emoenke@gwdg.de>
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2, or (at your option)
 *   any later version.
 *
 *   You should have received a copy of the GNU General Public License
 *   (for example /usr/src/linux/COPYING); if not, write to the Free
 *   Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 *   If you change this software, you should mail a .diff file with some
 *   description lines to emoenke@gwdg.de. I want to know about it.
 *
 *   If you are the editor of a Linux CD, you should enable sbpcd.c within
 *   your boot floppy kernel and send me one of your CDs for free.
 *
 *   If you would like to port the driver to an other operating system (f.e.
 *   FreeBSD or NetBSD) or use it as an information source, you shall not be
 *   restricted by the GPL under the following conditions:
 *     a) the source code of your work is freely available
 *     b) my part of the work gets mentioned at all places where your 
 *        authorship gets mentioned
 *     c) I receive a copy of your code together with a full installation
 *        package of your operating system for free.
 *
 *
 *  VERSION HISTORY
 *
 *  0.1  initial release, April/May 93, after mcd.c (Martin Harriss)
 *
 *  0.2  thek "repeat:"-loop in do_sbpcd_request did not check for
 *       end-of-request_queue (resulting in kernel panic).
 *       Flow control seems stable, but throughput is not better.  
 *
 *  0.3  interrupt locking totally eliminated (maybe "inb" and "outb"
 *       are still locking) - 0.2 made keyboard-type-ahead losses.
 *       check_sbpcd_media_change added (to use by isofs/inode.c)
 *       - but it detects almost nothing.
 *
 *  0.4  use MAJOR 25 definitely.
 *       Almost total re-design to support double-speed drives and
 *       "naked" (no sound) interface cards ("LaserMate" interface type).
 *       Flow control should be exact now.
 *       Don't occupy the SbPro IRQ line (not needed either); will
 *       live together with Hannu Savolainen's sndkit now.
 *       Speeded up data transfer to 150 kB/sec, with help from Kai
 *       Makisara, the "provider" of the "mt" tape utility.
 *       Give "SpinUp" command if necessary.
 *       First steps to support up to 4 drives (but currently only one).
 *       Implemented audio capabilities - workman should work, xcdplayer
 *       gives some problems.
 *       This version is still consuming too much CPU time, and
 *       sleeping still has to be worked on.
 *       During "long" implied seeks, it seems possible that a 
 *       ReadStatus command gets ignored. That gives the message
 *       "ResponseStatus timed out" (happens about 6 times here during
 *       a "ls -alR" of the YGGDRASIL LGX-Beta CD). Such a case is
 *       handled without data error, but it should get done better.
 *
 *  0.5  Free CPU during waits (again with help from Kai Makisara).
 *       Made it work together with the LILO/kernel setup standard.
 *       Included auto-probing code, as suggested by YGGDRASIL.
 *       Formal redesign to add DDI debugging.
 *       There are still flaws in IOCTL (workman with double speed drive).
 *
 *  1.0  Added support for all drive IDs (0...3, no longer only 0)
 *       and up to 4 drives on one controller.
 *       Added "#define MANY_SESSION" for "old" multi session CDs.
 *
 *  1.1  Do SpinUp for new drives, too.
 *       Revised for clean compile under "old" kernels (0.99pl9).
 *
 *  1.2  Found the "workman with double-speed drive" bug: use the driver's
 *       audio_state, not what the drive is reporting with ReadSubQ.
 *
 *  1.3  Minor cleanups.
 *       Refinements regarding Workman.
 *
 *  1.4  Read XA disks (PhotoCDs) with "old" drives, too (but only the first
 *       session - no chance to fully access a "multi-session" CD).
 *       This currently still is too slow (50 kB/sec) - but possibly
 *       the old drives won't do it faster.
 *       Implemented "door (un)lock" for new drives (still does not work
 *       as wanted - no lock possible after an unlock).
 *       Added some debugging printout for the UPC/EAN code - but my drives 
 *       return only zeroes. Is there no UPC/EAN code written?
 *
 *  1.5  Laborate with UPC/EAN code (not better yet).
 *       Adapt to kernel 1.1.8 change (have to explicitly include
 *       <linux/string.h> now).
 *
 *  1.6  Trying to read audio frames as data. Impossible with the current
 *       drive firmware levels, as it seems. Awaiting any hint. ;-)
 *       Changed "door unlock": repeat it until success.
 *       Changed CDROMSTOP routine (stop somewhat "softer" so that Workman
 *       won't get confused).
 *       Added a third interface type: Sequoia S-1000, as used with the SPEA
 *       Media FX sound card. This interface (usable for Sony and Mitsumi 
 *       drives, too) needs a special configuration setup and behaves like a 
 *       LaserMate type after that. Still experimental - I do not have such
 *       an interface.
 *       Use the "variable BLOCK_SIZE" feature (2048). But it does only work
 *       if you give the mount option "block=2048".
 *       The media_check routine is currently disabled; now that it gets
 *       called as it should I fear it must get synchronized for not to
 *       disturb the normal driver's activity.
 *
 *  2.0  Version number bumped - two reasons:
 *       - reading audio tracks as data works now with CR-562 and CR-563. We
 *       currently do it by an IOCTL (yet has to get standardized), one frame
 *       at a time; that is pretty slow. But it works.
 *       - we are maintaining now up to 4 interfaces (each up to 4 drives):
 *       did it the easy way - a different MAJOR (25, 26, ...) and a different
 *       copy of the driver (sbpcd.c, sbpcd2.c, sbpcd3.c, sbpcd4.c - only
 *       distinguished by the value of SBPCD_ISSUE and the driver's name),
 *       and a common sbpcd.h file.
 *       Bettered the "ReadCapacity error" problem with old CR-52x drives (the
 *       drives sometimes need a manual "eject/insert" before work): just
 *       reset the drive and do again. Needs lots of resets here and sometimes
 *       that does not cure, so this can't be the solution.
 *
 *  2.1  Found bug with multisession CDs (accessing frame 16).
 *       "read audio" works now with address type CDROM_MSF, too.
 *       Bigger audio frame buffer: allows reading max. 4 frames at time; this
 *       gives a significant speedup, but reading more than one frame at once
 *       gives missing chunks at each single frame boundary.
 *
 *  2.2  Kernel interface cleanups: timers, init, setup, media check.
 *
 *  2.3  Let "door lock" and "eject" live together.
 *       Implemented "close tray" (done automatically during open).
 *
 *  2.4  Use different names for device registering.
 *
 *  2.5  Added "#if EJECT" code (default: enabled) to automatically eject
 *       the tray during last call to "sbpcd_release".
 *       Added "#if JUKEBOX" code (default: disabled) to automatically eject
 *       the tray during call to "sbpcd_open" if no disk is in.
 *       Turn on the CD volume of "compatible" sound cards, too; just define
 *       SOUND_BASE (in sbpcd.h) accordingly (default: disabled).
 *
 *  2.6  Nothing new.  
 *
 *  2.7  Added CDROMEJECT_SW ioctl to set the "EJECT" behavior on the fly:
 *       0 disables, 1 enables auto-ejecting. Useful to keep the tray in
 *       during shutdown.
 *
 *  2.8  Added first support (still BETA, I need feedback or a drive) for
 *       the Longshine LCS-7260 drives. They appear as double-speed drives
 *       using the "old" command scheme, extended by tray control and door
 *       lock functions.
 *       Found (and fixed preliminary) a flaw with some multisession CDs: we
 *       have to re-direct not only the accesses to frame 16 (the isofs
 *       routines drive it up to max. 100), but also those to the continuation
 *       (repetition) frames (as far as they exist - currently set fix as
 *       16..20).
 *       Changed default of the "JUKEBOX" define. If you use this default,
 *       your tray will eject if you try to mount without a disk in. Next
 *       mount command will insert the tray - so, just fill in a disk. ;-)
 *
 *  2.9  Fulfilled the Longshine LCS-7260 support; with great help and
 *       experiments by Serge Robyns.
 *       First attempts to support the TEAC CD-55A drives; but still not
 *       usable yet.
 *       Implemented the CDROMMULTISESSION ioctl; this is an attempt to handle
 *       multi session CDs more "transparent" (redirection handling has to be
 *       done within the isofs routines, and only for the special purpose of
 *       obtaining the "right" volume descriptor; accesses to the raw device
 *       should not get redirected).
 *
 *  3.0  Just a "normal" increment, with some provisions to do it better. ;-)
 *       Introduced "#define READ_AUDIO" to specify the maximum number of 
 *       audio frames to grab with one request. This defines a buffer size
 *       within kernel space; a value of 0 will reserve no such space and
 *       disable the CDROMREADAUDIO ioctl. A value of 75 enables the reading
 *       of a whole second with one command, but will use a buffer of more
 *       than 172 kB.
 *       Started CD200 support. Drive detection should work, but nothing
 *       more.
 *
 *  3.1  Working to support the CD200 and the Teac CD-55A drives.
 *       AT-BUS style device numbering no longer used: use SCSI style now.
 *       So, the first "found" device has MINOR 0, regardless of the
 *       jumpered drive ID. This implies modifications to the /dev/sbpcd*
 *       entries for some people, but will help the DAU (german TLA, english:
 *       "newbie", maybe ;-) to install his "first" system from a CD.
 *
 *  3.2  Still testing with CD200 and CD-55A drives.
 *
 *  3.3  Working with CD200 support.
 *
 *  3.4  Auto-probing stops if an address of 0 is seen (to be entered with
 *       the kernel command line).
 *       Made the driver "loadable". If used as a module, "audio copy" is
 *       disabled, and the internal read ahead data buffer has a reduced size
 *       of 4 kB; so, throughput may be reduced a little bit with slow CPUs.
 *
 *  3.5  Provisions to handle weird photoCDs which have an interrupted
 *       "formatting" immediately after the last frames of some files: simply
 *       never "read ahead" with MultiSession CDs. By this, CPU usage may be
 *       increased with those CDs, and there may be a loss in speed.
 *       Re-structured the messaging system.
 *       The "loadable" version no longer has a limited READ_AUDIO buffer
 *       size.
 *       Removed "MANY_SESSION" handling for "old" multi session CDs.
 *       Added "private" IOCTLs CDROMRESET and CDROMVOLREAD.
 *       Started again to support the TEAC CD-55A drives, now that I found
 *       the money for "my own" drive. ;-)
 *       The TEAC CD-55A support is fairly working now.
 *       I have measured that the drive "delivers" at 600 kB/sec (even with
 *       bigger requests than the drive's 64 kB buffer can satisfy), but
 *       the "real" rate does not exceed 520 kB/sec at the moment. 
 *       Caused by the various changes to build in TEAC support, the timed
 *       loops are de-optimized at the moment (less throughput with CR-52x
 *       drives, and the TEAC will give speed only with SBP_BUFFER_FRAMES 64).
 *
 *  3.6  Fixed TEAC data read problems with SbPro interfaces.
 *       Initial size of the READ_AUDIO buffer is 0. Can get set to any size
 *       during runtime.
 *
 *  3.7  Introduced MAX_DRIVES for some poor interface cards (seen with TEAC
 *       drives) which allow only one drive (ID 0); this avoids repetitive
 *       detection under IDs 1..3. 
 *       Elongated cmd_out_T response waiting; necessary for photo CDs with
 *       a lot of sessions.
 *       Bettered the sbpcd_open() behavior with TEAC drives.
 *
 *  3.8  Elongated max_latency for CR-56x drives.
 *
 *  3.9  Finally fixed the long-known SoundScape/SPEA/Sequoia S-1000 interface
 *       configuration bug.
 *       Now Corey, Heiko, Ken, Leo, Vadim/Eric & Werner are invited to copy
 *       the config_spea() routine into their drivers. ;-)
 *
 *  4.0  No "big step" - normal version increment.
 *       Adapted the benefits from 1.3.33.
 *       Fiddled with CDROMREADAUDIO flaws.
 *       Avoid ReadCapacity command with CD200 drives (the MKE 1.01 version
 *       seems not to support it).
 *       Fulfilled "read audio" for CD200 drives, with help of Pete Heist
 *       (heistp@rpi.edu).
 *
 *  4.1  Use loglevel KERN_INFO with printk().
 *       Added support for "Vertos 100" drive ("ECS-AT") - it is very similar
 *       to the Longshine LCS-7260. Give feedback if you can - I never saw
 *       such a drive, and I have no specs.
 *
 *  4.2  Support for Teac 16-bit interface cards. Can't get auto-detected,
 *       so you have to jumper your card to 0x2C0. Still not 100% - come
 *       in contact if you can give qualified feedback.
 *       Use loglevel KERN_NOTICE with printk(). If you get annoyed by a
 *       flood of unwanted messages and the accompanied delay, try to read
 *       my documentation. Especially the Linux CDROM drivers have to do an
 *       important job for the newcomers, so the "distributed" version has
 *       to fit some special needs. Since generations, the flood of messages
 *       is user-configurable (even at runtime), but to get aware of this, one
 *       needs a special mental quality: the ability to read.
 *       
 *  4.3  CD200F does not like to receive a command while the drive is
 *       reading the ToC; still trying to solve it.
 *       Removed some redundant verify_area calls (yes, Heiko Eissfeldt
 *       is visiting all the Linux CDROM drivers ;-).
 *       
 *  4.4  Adapted one idea from tiensivu@pilot.msu.edu's "stripping-down"
 *       experiments: "KLOGD_PAUSE".
 *       Inhibited "play audio" attempts with data CDs. Provisions for a
 *       "data-safe" handling of "mixed" (data plus audio) Cds.
 *
 *  4.5  Meanwhile Gonzalo Tornaria <tornaria@cmat.edu.uy> (GTL) built a
 *       special end_request routine: we seem to have to take care for not
 *       to have two processes working at the request list. My understanding
 *       was and is that ll_rw_blk should not call do_sbpcd_request as long
 *       as there is still one call active (the first call will care for all
 *       outstanding I/Os, and if a second call happens, that is a bug in
 *       ll_rw_blk.c).
 *       "Check media change" without touching any drive.
 *
 *  4.6  Use a semaphore to synchronize multi-activity; elaborated by Rob
 *       Riggs <rriggs@tesser.com>. At the moment, we simply block "read"
 *       against "ioctl" and vice versa. This could be refined further, but
 *       I guess with almost no performance increase.
 *       Experiments to speed up the CD-55A; again with help of Rob Riggs
 *       (to be true, he gave both, idea & code. ;-)
 *
 *  4.61 Ported to Uniform CD-ROM driver by 
 *       Heiko Eissfeldt <heiko@colossus.escape.de> with additional
 *       changes by Erik Andersen <andersee@debian.org>
 *
 *  4.62 Fix a bug where playing audio left the drive in an unusable state.
 *         Heiko Eissfeldt <heiko@colossus.escape.de>
 *
 *  November 1999 -- Make kernel-parameter implementation work with 2.3.x 
 *	             Removed init_module & cleanup_module in favor of 
 *	             module_init & module_exit.
 *	             Torben Mathiasen <tmm@image.dk>
 *
 *  4.63 Bug fixes for audio annoyances, new legacy CDROM maintainer.
 *		Annoying things fixed:
 *		TOC reread on automated disk changes
 *		TOC reread on manual cd changes
 *		Play IOCTL tries to play CD before it's actually ready... sometimes.
 *		CD_AUDIO_COMPLETED state so workman (and other playes) can repeat play.
 *		Andrew J. Kroll <ag784@freenet.buffalo.edu> Wed Jul 26 04:24:10 EDT 2000
 *
 *  4.64 Fix module parameters - were being completely ignored.
 *	 Can also specify max_drives=N as a setup int to get rid of
 *	 "ghost" drives on crap hardware (aren't they all?)   Paul Gortmaker
 *
 *  TODO
 *     implement "read all subchannel data" (96 bytes per frame)
 *     remove alot of the virtual status bits and deal with hardware status
 *     move the change of cd for audio to a better place
 *     add debug levels to insmod parameters (trivial)
 *
 *     special thanks to Kai Makisara (kai.makisara@vtt.fi) for his fine
 *     elaborated speed-up experiments (and the fabulous results!), for
 *     the "push" towards load-free wait loops, and for the extensive mail
 *     thread which brought additional hints and bug fixes.
 *
 */

/*
 * Trying to merge requests breaks this driver horribly (as in it goes
 * boom and apparently has done so since 2.3.41).  As it is a legacy
 * driver for a horribly slow double speed CD on a hideous interface
 * designed for polled operation, I won't lose any sleep in simply
 * disallowing merging.				Paul G.  02/2001
 *
 * Thu May 30 14:14:47 CEST 2002:
 *
 * I have presumably found the reson for the above - there was a bogous
 * end_request substitute, which was manipulating the request queues
 * incorrectly. If someone has access to the actual hardware, and it's
 * still operations - well  please free to test it.
 *
 * Marcin Dalecki
 */

/*
 * Add bio/kdev_t changes for 2.5.x required to make it work again. 
 * Still room for improvement in the request handling here if anyone
 * actually cares.  Bring your own chainsaw.    Paul G.  02/2002
 */


#include <linux/module.h>

#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/timer.h>
#include <linux/fs.h>
#include <linux/kernel.h>
#include <linux/cdrom.h>
#include <linux/ioport.h>
#include <linux/major.h>
#include <linux/string.h>
#include <linux/vmalloc.h>
#include <linux/init.h>
#include <linux/interrupt.h>

#include <asm/system.h>
#include <asm/io.h>
#include <asm/uaccess.h>
#include <stdarg.h>
#include "sbpcd.h"

#define MAJOR_NR MATSUSHITA_CDROM_MAJOR
#include <linux/blkdev.h>

/*==========================================================================*/
#if SBPCD_DIS_IRQ
# define SBPCD_CLI cli()
# define SBPCD_STI sti()
#else
# define SBPCD_CLI
# define SBPCD_STI
#endif

/*==========================================================================*/
/*
 * auto-probing address list
 * inspired by Adam J. Richter from Yggdrasil
 *
 * still not good enough - can cause a hang.
 *   example: a NE 2000 ethernet card at 300 will cause a hang probing 310.
 * if that happens, reboot and use the LILO (kernel) command line.
 * The possibly conflicting ethernet card addresses get NOT probed 
 * by default - to minimize the hang possibilities. 
 *
 * The SB Pro addresses get "mirrored" at 0x6xx and some more locations - to
 * avoid a type error, the 0x2xx-addresses must get checked before 0x6xx.
 *
 * send mail to emoenke@gwdg.de if your interface card is not FULLY
 * represented here.
 */
static int sbpcd[] =
{
	CDROM_PORT, SBPRO, /* probe with user's setup first */
#if DISTRIBUTION
	0x230, 1, /* Soundblaster Pro and 16 (default) */
#if 0
	0x300, 0, /* CI-101P (default), WDH-7001C (default),
		     Galaxy (default), Reveal (one default) */
	0x250, 1, /* OmniCD default, Soundblaster Pro and 16 */
	0x2C0, 3, /* Teac 16-bit cards */
	0x260, 1, /* OmniCD */
	0x320, 0, /* Lasermate, CI-101P, WDH-7001C, Galaxy, Reveal (other default),
		     Longshine LCS-6853 (default) */
	0x338, 0, /* Reveal Sound Wave 32 card model #SC600 */
	0x340, 0, /* Mozart sound card (default), Lasermate, CI-101P */
	0x360, 0, /* Lasermate, CI-101P */
	0x270, 1, /* Soundblaster 16 */
	0x670, 0, /* "sound card #9" */
	0x690, 0, /* "sound card #9" */
	0x338, 2, /* SPEA Media FX, Ensonic SoundScape (default) */
	0x328, 2, /* SPEA Media FX */
	0x348, 2, /* SPEA Media FX */
	0x634, 0, /* some newer sound cards */
	0x638, 0, /* some newer sound cards */
	0x230, 1, /* some newer sound cards */
	/* due to incomplete address decoding of the SbPro card, these must be last */
	0x630, 0, /* "sound card #9" (default) */
	0x650, 0, /* "sound card #9" */
#ifdef MODULE
	/*
	 * some "hazardous" locations (no harm with the loadable version)
	 * (will stop the bus if a NE2000 ethernet card resides at offset -0x10)
	 */
	0x330, 0, /* Lasermate, CI-101P, WDH-7001C */
	0x350, 0, /* Lasermate, CI-101P */
	0x358, 2, /* SPEA Media FX */
	0x370, 0, /* Lasermate, CI-101P */
	0x290, 1, /* Soundblaster 16 */
	0x310, 0, /* Lasermate, CI-101P, WDH-7001C */
#endif /* MODULE */
#endif
#endif /* DISTRIBUTION */
};

/*
 * Protects access to global structures etc.
 */
static  __cacheline_aligned DEFINE_SPINLOCK(sbpcd_lock);
static struct request_queue *sbpcd_queue;

/* You can only set the first pair, from old MODULE_PARM code.  */
static int sbpcd_set(const char *val, struct kernel_param *kp)
{
	get_options((char *)val, 2, (int *)sbpcd);
	return 0;
}
module_param_call(sbpcd, sbpcd_set, NULL, NULL, 0);

#define NUM_PROBE  (sizeof(sbpcd) / sizeof(int))

/*==========================================================================*/

#define INLINE inline

/*==========================================================================*/
/*
 * the forward references:
 */
static void sbp_sleep(u_int);
static void mark_timeout_delay(u_long);
static void mark_timeout_data(u_long);
#if 0
static void mark_timeout_audio(u_long);
#endif
static void sbp_read_cmd(struct request *req);
static int sbp_data(struct request *req);
static int cmd_out(void);
static int DiskInfo(void);

/*==========================================================================*/

/*
 * pattern for printk selection:
 *
 * (1<<DBG_INF)  necessary information
 * (1<<DBG_BSZ)  BLOCK_SIZE trace
 * (1<<DBG_REA)  "read" status trace
 * (1<<DBG_CHK)  "media check" trace
 * (1<<DBG_TIM)  datarate timer test
 * (1<<DBG_INI)  initialization trace
 * (1<<DBG_TOC)  tell TocEntry values
 * (1<<DBG_IOC)  ioctl trace
 * (1<<DBG_STA)  "ResponseStatus" trace
 * (1<<DBG_ERR)  "cc_ReadError" trace
 * (1<<DBG_CMD)  "cmd_out" trace
 * (1<<DBG_WRN)  give explanation before auto-probing
 * (1<<DBG_MUL)  multi session code test
 * (1<<DBG_IDX)  "drive_id != 0" test code
 * (1<<DBG_IOX)  some special information
 * (1<<DBG_DID)  drive ID test
 * (1<<DBG_RES)  drive reset info
 * (1<<DBG_SPI)  SpinUp test info
 * (1<<DBG_IOS)  ioctl trace: "subchannel"
 * (1<<DBG_IO2)  ioctl trace: general
 * (1<<DBG_UPC)  show UPC info
 * (1<<DBG_XA1)  XA mode debugging
 * (1<<DBG_LCK)  door (un)lock info
 * (1<<DBG_SQ1)   dump SubQ frame
 * (1<<DBG_AUD)  "read audio" debugging
 * (1<<DBG_SEQ)  Sequoia interface configuration trace
 * (1<<DBG_LCS)  Longshine LCS-7260 debugging trace
 * (1<<DBG_CD2)  MKE/Funai CD200 debugging trace
 * (1<<DBG_TEA)  TEAC CD-55A debugging trace
 * (1<<DBG_ECS)  ECS-AT (Vertos-100) debugging trace
 * (1<<DBG_000)  unnecessary information
 */
#if DISTRIBUTION
static int sbpcd_debug = (1<<DBG_INF);
#else
static int sbpcd_debug = 0 & ((1<<DBG_INF) |
			  (1<<DBG_TOC) |
			  (1<<DBG_MUL) |
			  (1<<DBG_UPC));
#endif /* DISTRIBUTION */

static int sbpcd_ioaddr = CDROM_PORT;	/* default I/O base address */
static int sbpro_type = SBPRO;
static unsigned char f_16bit;
static unsigned char do_16bit;
static int CDo_command, CDo_reset;
static int CDo_sel_i_d, CDo_enable;
static int CDi_info, CDi_status, CDi_data;
static struct cdrom_msf msf;
static struct cdrom_ti ti;
static struct cdrom_tochdr tochdr;
static struct cdrom_tocentry tocentry;
static struct cdrom_subchnl SC;
static struct cdrom_volctrl volctrl;
static struct cdrom_read_audio read_audio;

static unsigned char msgnum;
static char msgbuf[80];

static int max_drives = MAX_DRIVES;
module_param(max_drives, int, 0);
#ifndef MODULE
static unsigned char setup_done;
static const char *str_sb_l = "soundblaster";
static const char *str_sp_l = "spea";
static const char *str_ss_l = "soundscape";
static const char *str_t16_l = "teac16bit";
static const char *str_ss = "SoundScape";
#endif
static const char *str_sb = "SoundBlaster";
static const char *str_lm = "LaserMate";
static const char *str_sp = "SPEA";
static const char *str_t16 = "Teac16bit";
static const char *type;
static const char *major_name="sbpcd";

/*==========================================================================*/

#ifdef FUTURE
static DECLARE_WAIT_QUEUE_HEAD(sbp_waitq);
#endif /* FUTURE */

static int teac=SBP_TEAC_SPEED;
static int buffers=SBP_BUFFER_FRAMES;

static u_char family0[]="MATSHITA"; /* MKE CR-521, CR-522, CR-523 */
static u_char family1[]="CR-56";    /* MKE CR-562, CR-563 */
static u_char family2[]="CD200";    /* MKE CD200, Funai CD200F */
static u_char familyL[]="LCS-7260"; /* Longshine LCS-7260 */
static u_char familyT[]="CD-55";    /* TEAC CD-55A */
static u_char familyV[]="ECS-AT";   /* ECS Vertos 100 */

static u_int recursion; /* internal testing only */
static u_int fatal_err; /* internal testing only */
static u_int response_count;
static u_int flags_cmd_out;
static u_char cmd_type;
static u_char drvcmd[10];
static u_char infobuf[20];
static u_char xa_head_buf[CD_XA_HEAD];
static u_char xa_tail_buf[CD_XA_TAIL];

#if OLD_BUSY
static volatile u_char busy_data;
static volatile u_char busy_audio; /* true semaphores would be safer */
#endif /* OLD_BUSY */ 
static DECLARE_MUTEX(ioctl_read_sem);
static u_long timeout;
static volatile u_char timed_out_delay;
static volatile u_char timed_out_data;
#if 0
static volatile u_char timed_out_audio;
#endif
static u_int datarate= 1000000;
static u_int maxtim16=16000000;
static u_int maxtim04= 4000000;
static u_int maxtim02= 2000000;
static u_int maxtim_8=   30000;
#if LONG_TIMING
static u_int maxtim_data= 9000;
#else
static u_int maxtim_data= 3000;
#endif /* LONG_TIMING */ 
#if DISTRIBUTION
static int n_retries=6;
#else
static int n_retries=6;
#endif
/*==========================================================================*/

static int ndrives;
static u_char drv_pattern[NR_SBPCD]={speed_auto,speed_auto,speed_auto,speed_auto};

/*==========================================================================*/
/*
 * drive space begins here (needed separate for each unit) 
 */
static struct sbpcd_drive {
	char drv_id;           /* "jumpered" drive ID or -1 */
	char drv_sel;          /* drive select lines bits */
	
	char drive_model[9];
	u_char firmware_version[4];
	char f_eject;          /* auto-eject flag: 0 or 1 */
	u_char *sbp_buf;       /* Pointer to internal data buffer,
				  space allocated during sbpcd_init() */
	u_int sbp_bufsiz;      /* size of sbp_buf (# of frames) */
	int sbp_first_frame;   /* First frame in buffer */
	int sbp_last_frame;    /* Last frame in buffer  */
	int sbp_read_frames;   /* Number of frames being read to buffer */
	int sbp_current;       /* Frame being currently read */
	
	u_char mode;           /* read_mode: READ_M1, READ_M2, READ_SC, READ_AU */
	u_char *aud_buf;       /* Pointer to audio data buffer,
				  space allocated during sbpcd_init() */
	u_int sbp_audsiz;      /* size of aud_buf (# of raw frames) */
	u_int drv_type;
	u_char drv_options;
	int status_bits;
	u_char diskstate_flags;
	u_char sense_byte;
	
	u_char CD_changed;
	char open_count;
	u_char error_byte;
	
	u_char f_multisession;
	u_int lba_multi;
	int first_session;
	int last_session;
	int track_of_last_session;
	
	u_char audio_state;
	u_int pos_audio_start;
	u_int pos_audio_end;
	char vol_chan0;
	u_char vol_ctrl0;
	char vol_chan1;
	u_char vol_ctrl1;
#if 000 /* no supported drive has it */
	char vol_chan2;
	u_char vol_ctrl2;
	char vol_chan3;
	u_char vol_ctrl3;
#endif /*000 */
	u_char volume_control; /* TEAC on/off bits */
	
	u_char SubQ_ctl_adr;
	u_char SubQ_trk;
	u_char SubQ_pnt_idx;
	u_int SubQ_run_tot;
	u_int SubQ_run_trk;
	u_char SubQ_whatisthis;
	
	u_char UPC_ctl_adr;
	u_char UPC_buf[7];
	
	int frame_size;
	int CDsize_frm;
	
	u_char xa_byte; /* 0x20: XA capabilities */
	u_char n_first_track; /* binary */
	u_char n_last_track; /* binary (not bcd), 0x01...0x63 */
	u_int size_msf; /* time of whole CD, position of LeadOut track */
	u_int size_blk;
	
	u_char TocEnt_nixbyte; /* em */
	u_char TocEnt_ctl_adr;
	u_char TocEnt_number;
	u_char TocEnt_format; /* em */
	u_int TocEnt_address;
#ifdef SAFE_MIXED
	char has_data;
#endif /* SAFE_MIXED */ 
	u_char ored_ctl_adr; /* to detect if CDROM contains data tracks */
	
	struct {
		u_char nixbyte; /* em */
		u_char ctl_adr; /* 0x4x: data, 0x0x: audio */
		u_char number;
		u_char format; /* em */ /* 0x00: lba, 0x01: msf */
		u_int address;
	} TocBuffer[MAX_TRACKS+1]; /* last entry faked */ 
	
	int in_SpinUp; /* CR-52x test flag */
	int n_bytes; /* TEAC awaited response count */
	u_char error_state, b3, b4; /* TEAC command error state */
	u_char f_drv_error; /* TEAC command error flag */
	u_char speed_byte;
	int frmsiz;
	u_char f_XA; /* 1: XA */
	u_char type_byte; /* 0, 1, 3 */
	u_char mode_xb_6;
	u_char mode_yb_7;
	u_char mode_xb_8;
	u_char delay;
	struct cdrom_device_info *sbpcd_infop;
	struct gendisk *disk;
} D_S[NR_SBPCD];

static struct sbpcd_drive *current_drive = D_S;

/*
 * drive space ends here (needed separate for each unit)
 */
/*==========================================================================*/
#if 0
unsigned long cli_sti; /* for saving the processor flags */
#endif
/*==========================================================================*/
static DEFINE_TIMER(delay_timer, mark_timeout_delay, 0, 0);
static DEFINE_TIMER(data_timer, mark_timeout_data, 0, 0);
#if 0
static DEFINE_TIMER(audio_timer, mark_timeout_audio, 0, 0);
#endif
/*==========================================================================*/
/*
 * DDI interface
 */
static void msg(int level, const char *fmt, ...)
{
#if DISTRIBUTION
#define MSG_LEVEL KERN_NOTICE
#else
#define MSG_LEVEL KERN_INFO
#endif /* DISTRIBUTION */

	char buf[256];
	va_list args;
	
	if (!(sbpcd_debug&(1<<level))) return;
	
	msgnum++;
	if (msgnum>99) msgnum=0;
	va_start(args, fmt);
	vsnprintf(buf, sizeof(buf), fmt, args);
	va_end(args);
	printk(MSG_LEVEL "%s-%d [%02d]:  %s", major_name, current_drive - D_S, msgnum, buf);
#if KLOGD_PAUSE
	sbp_sleep(KLOGD_PAUSE); /* else messages get lost */
#endif /* KLOGD_PAUSE */ 
	return;
}
/*==========================================================================*/
/*
 * DDI interface: runtime trace bit pattern maintenance
 */
static int sbpcd_dbg_ioctl(unsigned long arg, int level)
{
	switch(arg)
	{
	case 0:	/* OFF */
		sbpcd_debug = DBG_INF;
		break;
		
	default:
		if (arg>=128) sbpcd_debug &= ~(1<<(arg-128));
		else sbpcd_debug |= (1<<arg);
	}
	return (arg);
}
/*==========================================================================*/
static void mark_timeout_delay(u_long i)
{
	timed_out_delay=1;
#if 0
	msg(DBG_TIM,"delay timer expired.\n");
#endif
}
/*==========================================================================*/
static void mark_timeout_data(u_long i)
{
	timed_out_data=1;
#if 0
	msg(DBG_TIM,"data timer expired.\n");
#endif
}
/*==========================================================================*/
#if 0
static void mark_timeout_audio(u_long i)
{
	timed_out_audio=1;
#if 0
	msg(DBG_TIM,"audio timer expired.\n");
#endif
}
#endif
/*==========================================================================*/
/*
 * Wait a little while (used for polling the drive).
 */
static void sbp_sleep(u_int time)
{
	sti();
	schedule_timeout_interruptible(time);
	sti();
}
/*==========================================================================*/
#define RETURN_UP(rc) {up(&ioctl_read_sem); return(rc);}
/*==========================================================================*/
/*
 *  convert logical_block_address to m-s-f_number (3 bytes only)
 */
static INLINE void lba2msf(int lba, u_char *msf)
{
	lba += CD_MSF_OFFSET;
	msf[0] = lba / (CD_SECS*CD_FRAMES);
	lba %= CD_SECS*CD_FRAMES;
	msf[1] = lba / CD_FRAMES;
	msf[2] = lba % CD_FRAMES;
}
/*==========================================================================*/
/*==========================================================================*/
/*
 *  convert msf-bin to msf-bcd
 */
static INLINE void bin2bcdx(u_char *p)  /* must work only up to 75 or 99 */
{
	*p=((*p/10)<<4)|(*p%10);
}
/*==========================================================================*/
static INLINE u_int blk2msf(u_int blk)
{
	MSF msf;
	u_int mm;
	
	msf.c[3] = 0;
	msf.c[2] = (blk + CD_MSF_OFFSET) / (CD_SECS * CD_FRAMES);
	mm = (blk + CD_MSF_OFFSET) % (CD_SECS * CD_FRAMES);
	msf.c[1] = mm / CD_FRAMES;
	msf.c[0] = mm % CD_FRAMES;
	return (msf.n);
}
/*==========================================================================*/
static INLINE u_int make16(u_char rh, u_char rl)
{
	return ((rh<<8)|rl);
}
/*==========================================================================*/
static INLINE u_int make32(u_int rh, u_int rl)
{
	return ((rh<<16)|rl);
}
/*==========================================================================*/
static INLINE u_char swap_nibbles(u_char i)
{
	return ((i<<4)|(i>>4));
}
/*==========================================================================*/
static INLINE u_char byt2bcd(u_char i)
{
	return (((i/10)<<4)+i%10);
}
/*==========================================================================*/
static INLINE u_char bcd2bin(u_char bcd)
{
	return ((bcd>>4)*10+(bcd&0x0F));
}
/*==========================================================================*/
static INLINE int msf2blk(int msfx)
{
	MSF msf;
	int i;
	
	msf.n=msfx;
	i=(msf.c[2] * CD_SECS + msf.c[1]) * CD_FRAMES + msf.c[0] - CD_MSF_OFFSET;
	if (i<0) return (0);
	return (i);
}
/*==========================================================================*/
/*
 *  convert m-s-f_number (3 bytes only) to logical_block_address 
 */
static INLINE int msf2lba(u_char *msf)
{
	int i;
	
	i=(msf[0] * CD_SECS + msf[1]) * CD_FRAMES + msf[2] - CD_MSF_OFFSET;
	if (i<0) return (0);
	return (i);
}
/*==========================================================================*/
/* evaluate cc_ReadError code */ 
static int sta2err(int sta)
{
	if (famT_drive)
	{
		if (sta==0x00) return (0);
		if (sta==0x01) return (-604); /* CRC error */
		if (sta==0x02) return (-602); /* drive not ready */
		if (sta==0x03) return (-607); /* unknown media */
		if (sta==0x04) return (-612); /* general failure */
		if (sta==0x05) return (0);
		if (sta==0x06) return (-ERR_DISKCHANGE); /* disk change */
		if (sta==0x0b) return (-612); /* general failure */
		if (sta==0xff) return (-612); /* general failure */
		return (0);
	}
	else
	{
		if (sta<=2) return (sta);
		if (sta==0x05) return (-604); /* CRC error */
		if (sta==0x06) return (-606); /* seek error */
		if (sta==0x0d) return (-606); /* seek error */
		if (sta==0x0e) return (-603); /* unknown command */
		if (sta==0x14) return (-603); /* unknown command */
		if (sta==0x0c) return (-611); /* read fault */
		if (sta==0x0f) return (-611); /* read fault */
		if (sta==0x10) return (-611); /* read fault */
		if (sta>=0x16) return (-612); /* general failure */
		if (sta==0x11) return (-ERR_DISKCHANGE); /* disk change (LCS: removed) */
		if (famL_drive)
			if (sta==0x12) return (-ERR_DISKCHANGE); /* disk change (inserted) */
		return (-602); /* drive not ready */
	}
}
/*==========================================================================*/
static INLINE void clr_cmdbuf(void)
{
	int i;
	
	for (i=0;i<10;i++) drvcmd[i]=0;
	cmd_type=0;
}
/*==========================================================================*/
static void flush_status(void)
{
	int i;
	
	sbp_sleep(15*HZ/10);
	for (i=maxtim_data;i!=0;i--) inb(CDi_status);
}
/*====================================================================*/
/*
 * CDi status loop for Teac CD-55A (Rob Riggs)
 *
 * This is needed because for some strange reason
 * the CD-55A can take a real long time to give a
 * status response. This seems to happen after we
 * issue a READ command where a long seek is involved.
 *
 * I tried to ensure that we get max throughput with
 * minimal busy waiting. We busy wait at first, then
 * "switch gears" and start sleeping. We sleep for
 * longer periods of time the longer we wait.
 *
 */
static int CDi_stat_loop_T(void)
{
	int	i, gear=1;
	u_long  timeout_1, timeout_2, timeout_3, timeout_4;

	timeout_1 = jiffies + HZ / 50;  /* sbp_sleep(0) for a short period */
	timeout_2 = jiffies + HZ / 5;	/* nap for no more than 200ms */
	timeout_3 = jiffies + 5 * HZ;	/* sleep for up to 5s */
	timeout_4 = jiffies + 45 * HZ;	/* long sleep for up to 45s. */
	do
          {
            i = inb(CDi_status);
            if (!(i&s_not_data_ready)) return (i);
            if (!(i&s_not_result_ready)) return (i);
            switch(gear)
              {
              case 4:
                sbp_sleep(HZ);
                if (time_after(jiffies, timeout_4)) gear++;
                msg(DBG_TEA, "CDi_stat_loop_T: long sleep active.\n");
                break;
              case 3:
                sbp_sleep(HZ/10);
                if (time_after(jiffies, timeout_3)) gear++;
                break;
              case 2:
                sbp_sleep(HZ/100);
                if (time_after(jiffies, timeout_2)) gear++;
                break;
              case 1:
                sbp_sleep(0);
                if (time_after(jiffies, timeout_1)) gear++;
              }
          } while (gear < 5);
	return -1;
}
/*==========================================================================*/
static int CDi_stat_loop(void)
{
	int i,j;
	
	for(timeout = jiffies + 10*HZ, i=maxtim_data; time_before(jiffies, timeout); )
	{
		for ( ;i!=0;i--)
		{
			j=inb(CDi_status);
			if (!(j&s_not_data_ready)) return (j);
			if (!(j&s_not_result_ready)) return (j);
			if (fam0L_drive) if (j&s_attention) return (j);
		}
		sbp_sleep(1);
		i = 1;
	}
	msg(DBG_LCS,"CDi_stat_loop failed in line %d\n", __LINE__);
	return (-1);
}
/*==========================================================================*/
#if 00000
/*==========================================================================*/
static int tst_DataReady(void)
{
	int i;
	
	i=inb(CDi_status);
	if (i&s_not_data_ready) return (0);
	return (1);
}
/*==========================================================================*/
static int tst_ResultReady(void)
{
	int i;
	
	i=inb(CDi_status);
	if (i&s_not_result_ready) return (0);
	return (1);
}
/*==========================================================================*/
static int tst_Attention(void)
{
	int i;
	
	i=inb(CDi_status);
	if (i&s_attention) return (1);
	return (0);
}
/*==========================================================================*/
#endif
/*==========================================================================*/
static int ResponseInfo(void)
{
	int i,j,st=0;
	u_long timeout;
	
	for (i=0,timeout=jiffies+HZ;i<response_count;i++) 
	{
		for (j=maxtim_data; ; )
		{
			for ( ;j!=0;j-- )
			{
				st=inb(CDi_status);
				if (!(st&s_not_result_ready)) break;
			}
			if ((j!=0)||time_after_eq(jiffies, timeout)) break;
			sbp_sleep(1);
			j = 1;
		}
		if (time_after_eq(jiffies, timeout)) break;
		infobuf[i]=inb(CDi_info);
	}
#if 000
	while (!(inb(CDi_status)&s_not_result_ready))
	{
		infobuf[i++]=inb(CDi_info);
	}
	j=i-response_count;
	if (j>0) msg(DBG_INF,"ResponseInfo: got %d trailing bytes.\n",j);
#endif /* 000 */
	for (j=0;j<i;j++)
		sprintf(&msgbuf[j*3]," %02X",infobuf[j]);
	msgbuf[j*3]=0;
	msg(DBG_CMD,"ResponseInfo:%s (%d,%d)\n",msgbuf,response_count,i);
	j=response_count-i;
	if (j>0) return (-j);
	else return (i);
}
/*==========================================================================*/
static void EvaluateStatus(int st)
{
	current_drive->status_bits=0;
	if (fam1_drive) current_drive->status_bits=st|p_success;
	else if (fam0_drive)
	{
		if (st&p_caddin_old) current_drive->status_bits |= p_door_closed|p_caddy_in;
		if (st&p_spinning) current_drive->status_bits |= p_spinning;
		if (st&p_check) current_drive->status_bits |= p_check;
 		if (st&p_success_old) current_drive->status_bits |= p_success;
 		if (st&p_busy_old) current_drive->status_bits |= p_busy_new;
		if (st&p_disk_ok) current_drive->status_bits |= p_disk_ok;
	}
	else if (famLV_drive)
	{
 		current_drive->status_bits |= p_success;
		if (st&p_caddin_old) current_drive->status_bits |= p_disk_ok|p_caddy_in;
		if (st&p_spinning) current_drive->status_bits |= p_spinning;
		if (st&p_check) current_drive->status_bits |= p_check;
		if (st&p_busy_old) current_drive->status_bits |= p_busy_new;
		if (st&p_lcs_door_closed) current_drive->status_bits |= p_door_closed;
		if (st&p_lcs_door_locked) current_drive->status_bits |= p_door_locked;
	}
	else if (fam2_drive)
	{
 		current_drive->status_bits |= p_success;
		if (st&p2_check) current_drive->status_bits |= p1_check;
		if (st&p2_door_closed) current_drive->status_bits |= p1_door_closed;
		if (st&p2_disk_in) current_drive->status_bits |= p1_disk_in;
		if (st&p2_busy1) current_drive->status_bits |= p1_busy;
		if (st&p2_busy2) current_drive->status_bits |= p1_busy;
		if (st&p2_spinning) current_drive->status_bits |= p1_spinning;
		if (st&p2_door_locked) current_drive->status_bits |= p1_door_locked;
		if (st&p2_disk_ok) current_drive->status_bits |= p1_disk_ok;
	}
	else if (famT_drive)
	{
		return; /* still needs to get coded */
 		current_drive->status_bits |= p_success;
		if (st&p2_check) current_drive->status_bits |= p1_check;
		if (st&p2_door_closed) current_drive->status_bits |= p1_door_closed;
		if (st&p2_disk_in) current_drive->status_bits |= p1_disk_in;
		if (st&p2_busy1) current_drive->status_bits |= p1_busy;
		if (st&p2_busy2) current_drive->status_bits |= p1_busy;
		if (st&p2_spinning) current_drive->status_bits |= p1_spinning;
		if (st&p2_door_locked) current_drive->status_bits |= p1_door_locked;
		if (st&p2_disk_ok) current_drive->status_bits |= p1_disk_ok;
	}
	return;
}
/*==========================================================================*/
static int cmd_out_T(void);

static int get_state_T(void)
{
	int i;

	clr_cmdbuf();
	current_drive->n_bytes=1;
	drvcmd[0]=CMDT_STATUS;
	i=cmd_out_T();
	if (i>=0) i=infobuf[0];
	else
	{
		msg(DBG_TEA,"get_state_T error %d\n", i);
		return (i);
	}
	if (i>=0)
		/* 2: closed, disk in */
		current_drive->status_bits=p1_door_closed|p1_disk_in|p1_spinning|p1_disk_ok;
	else if (current_drive->error_state==6)
	{
		/* 3: closed, disk in, changed ("06 xx xx") */
		current_drive->status_bits=p1_door_closed|p1_disk_in;
		current_drive->CD_changed=0xFF;
		current_drive->diskstate_flags &= ~toc_bit;
	}
	else if ((current_drive->error_state!=2)||(current_drive->b3!=0x3A)||(current_drive->b4==0x00))
	{
		/* 1: closed, no disk ("xx yy zz"or "02 3A 00") */
		current_drive->status_bits=p1_door_closed;
		current_drive->open_count=0;
	}
	else if (current_drive->b4==0x01)
	{
		/* 0: open ("02 3A 01") */
		current_drive->status_bits=0;
		current_drive->open_count=0;
	}
	else
	{
		/* 1: closed, no disk ("02 3A xx") */
		current_drive->status_bits=p1_door_closed;
		current_drive->open_count=0;
	}
	return (current_drive->status_bits);
}
/*==========================================================================*/
static int ResponseStatus(void)
{
	int i,j;
	u_long timeout;
	
	msg(DBG_STA,"doing ResponseStatus...\n");
	if (famT_drive) return (get_state_T());
	if (flags_cmd_out & f_respo3) timeout = jiffies;
	else if (flags_cmd_out & f_respo2) timeout = jiffies + 16*HZ;
	else timeout = jiffies + 4*HZ;
	j=maxtim_8;
	do
	{
		for ( ;j!=0;j--)
		{ 
			i=inb(CDi_status);
			if (!(i&s_not_result_ready)) break;
		}
		if ((j!=0)||time_after(jiffies, timeout)) break;
		sbp_sleep(1);
		j = 1;
	}
	while (1);
	if (j==0) 
	{
		if ((flags_cmd_out & f_respo3) == 0)
			msg(DBG_STA,"ResponseStatus: timeout.\n");
		current_drive->status_bits=0;
		return (-401);
	}
	i=inb(CDi_info);
	msg(DBG_STA,"ResponseStatus: response %02X.\n", i);
	EvaluateStatus(i);
	msg(DBG_STA,"status_bits=%02X, i=%02X\n",current_drive->status_bits,i);
	return (current_drive->status_bits);
}
/*==========================================================================*/
static void cc_ReadStatus(void)
{
	int i;
	
	msg(DBG_STA,"giving cc_ReadStatus command\n");
	if (famT_drive) return;
	SBPCD_CLI;
	if (fam0LV_drive) OUT(CDo_command,CMD0_STATUS);
	else if (fam1_drive) OUT(CDo_command,CMD1_STATUS);
	else if (fam2_drive) OUT(CDo_command,CMD2_STATUS);
	if (!fam0LV_drive) for (i=0;i<6;i++) OUT(CDo_command,0);
	SBPCD_STI;
}
/*==========================================================================*/
static int cc_ReadError(void)
{
	int i;

	clr_cmdbuf();
	msg(DBG_ERR,"giving cc_ReadError command.\n");
	if (fam1_drive)
	{
		drvcmd[0]=CMD1_READ_ERR;
		response_count=8;
		flags_cmd_out=f_putcmd|f_ResponseStatus;
	}
	else if (fam0LV_drive)
	{
		drvcmd[0]=CMD0_READ_ERR;
		response_count=6;
		if (famLV_drive)
			flags_cmd_out=f_putcmd;
		else
			flags_cmd_out=f_putcmd|f_getsta|f_ResponseStatus;
	}
	else if (fam2_drive)
	{
		drvcmd[0]=CMD2_READ_ERR;
		response_count=6;
		flags_cmd_out=f_putcmd;
	}
	else if (famT_drive)
	{
		response_count=5;
		drvcmd[0]=CMDT_READ_ERR;
	}
	i=cmd_out();
	current_drive->error_byte=0;
	msg(DBG_ERR,"cc_ReadError: cmd_out(CMDx_READ_ERR) returns %d (%02X)\n",i,i);
	if (i<0) return (i);
	if (fam0V_drive) i=1;
	else i=2;
	current_drive->error_byte=infobuf[i];
	msg(DBG_ERR,"cc_ReadError: infobuf[%d] is %d (%02X)\n",i,current_drive->error_byte,current_drive->error_byte);
	i=sta2err(infobuf[i]);
        if (i==-ERR_DISKCHANGE)
        {
                current_drive->CD_changed=0xFF;
                current_drive->diskstate_flags &= ~toc_bit;
        }
	return (i);
}
/*==========================================================================*/
static int cc_DriveReset(void);

static int cmd_out_T(void)
{
#undef CMDT_TRIES
#define CMDT_TRIES 1000
#define TEST_FALSE_FF 1

	int i, j, l=0, m, ntries;
	unsigned long flags;

	current_drive->error_state=0;
	current_drive->b3=0;
	current_drive->b4=0;
	current_drive->f_drv_error=0;
	for (i=0;i<10;i++) sprintf(&msgbuf[i*3]," %02X",drvcmd[i]);
	msgbuf[i*3]=0;
	msg(DBG_CMD,"cmd_out_T:%s\n",msgbuf);

	OUT(CDo_sel_i_d,0);
	OUT(CDo_enable,current_drive->drv_sel);
	i=inb(CDi_status);
	do_16bit=0;
	if ((f_16bit)&&(!(i&0x80)))
	{
		do_16bit=1;
		msg(DBG_TEA,"cmd_out_T: do_16bit set.\n");
	}
	if (!(i&s_not_result_ready))
	do
	{
		j=inb(CDi_info);
		i=inb(CDi_status);
		sbp_sleep(0);
		msg(DBG_TEA,"cmd_out_T: spurious !s_not_result_ready. (%02X)\n", j);
	}
	while (!(i&s_not_result_ready));
	save_flags(flags); cli();
	for (i=0;i<10;i++) OUT(CDo_command,drvcmd[i]);
	restore_flags(flags);
	for (ntries=CMDT_TRIES;ntries>0;ntries--)
	{
		if (drvcmd[0]==CMDT_READ_VER) sbp_sleep(HZ); /* fixme */
#if 01
		OUT(CDo_sel_i_d,1);
#endif /* 01 */
		if (teac==2)
                  {
                    if ((i=CDi_stat_loop_T()) == -1) break;
                  }
		else
                  {
#if 0
                    OUT(CDo_sel_i_d,1);
#endif /* 0 */ 
                    i=inb(CDi_status);
                  }
		if (!(i&s_not_data_ready)) /* f.e. CMDT_DISKINFO */
		{
			OUT(CDo_sel_i_d,1);
			if (drvcmd[0]==CMDT_READ) return (0); /* handled elsewhere */
			if (drvcmd[0]==CMDT_DISKINFO)
			{
				l=0;
				do
                                {
                                        if (do_16bit)
                                        {
                                                i=inw(CDi_data);
                                                infobuf[l++]=i&0x0ff;
                                                infobuf[l++]=i>>8;
#if TEST_FALSE_FF
                                                if ((l==2)&&(infobuf[0]==0x0ff))
                                                {
                                                        infobuf[0]=infobuf[1];
                                                        l=1;
                                                        msg(DBG_TEA,"cmd_out_T: do_16bit: false first byte!\n");
                                                }
#endif /* TEST_FALSE_FF */ 
                                        }
                                        else infobuf[l++]=inb(CDi_data);
                                        i=inb(CDi_status);
                                }
				while (!(i&s_not_data_ready));
				for (j=0;j<l;j++) sprintf(&msgbuf[j*3]," %02X",infobuf[j]);
				msgbuf[j*3]=0;
				msg(DBG_CMD,"cmd_out_T data response:%s\n", msgbuf);
			}
			else
			{
				msg(DBG_TEA,"cmd_out_T: data response with cmd_%02X!\n",
                                    drvcmd[0]);
				j=0;
				do
				{
                                        if (do_16bit) i=inw(CDi_data);
                                        else i=inb(CDi_data);
                                        j++;
                                        i=inb(CDi_status);
				}
				while (!(i&s_not_data_ready));
				msg(DBG_TEA,"cmd_out_T: data response: discarded %d bytes/words.\n", j);
				fatal_err++;
			}
		}
		i=inb(CDi_status);
		if (!(i&s_not_result_ready))
		{
			OUT(CDo_sel_i_d,0);
			if (drvcmd[0]==CMDT_DISKINFO) m=l;
			else m=0;
			do
			{
				infobuf[m++]=inb(CDi_info);
				i=inb(CDi_status);
			}
			while (!(i&s_not_result_ready));
			for (j=0;j<m;j++) sprintf(&msgbuf[j*3]," %02X",infobuf[j]);
			msgbuf[j*3]=0;
			msg(DBG_CMD,"cmd_out_T info response:%s\n", msgbuf);
			if (drvcmd[0]==CMDT_DISKINFO)
                        {
                                infobuf[0]=infobuf[l];
                                if (infobuf[0]!=0x02) return (l); /* data length */
                        }
			else if (infobuf[0]!=0x02) return (m); /* info length */
			do
			{
				++recursion;
				if (recursion>1) msg(DBG_TEA,"cmd_out_T READ_ERR recursion (%02X): %d !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n", drvcmd[0], recursion);
				clr_cmdbuf();
				drvcmd[0]=CMDT_READ_ERR;
				j=cmd_out_T(); /* !!! recursive here !!! */
				--recursion;
				sbp_sleep(1);
			}
			while (j<0);
			current_drive->error_state=infobuf[2];
			current_drive->b3=infobuf[3];
			current_drive->b4=infobuf[4];
			if (current_drive->f_drv_error)
			{
				current_drive->f_drv_error=0;
				cc_DriveReset();
				current_drive->error_state=2;
			}
			return (-current_drive->error_state-400);
		}
		if (drvcmd[0]==CMDT_READ) return (0); /* handled elsewhere */
		if ((teac==0)||(ntries<(CMDT_TRIES-5))) sbp_sleep(HZ/10);
		else sbp_sleep(HZ/100);
		if (ntries>(CMDT_TRIES-50)) continue;
		msg(DBG_TEA,"cmd_out_T: next CMDT_TRIES (%02X): %d.\n", drvcmd[0], ntries-1);
	}
	current_drive->f_drv_error=1;
	cc_DriveReset();
	current_drive->error_state=2;
	return (-99);
}
/*==========================================================================*/
static int cmd_out(void)
{
	int i=0;
	
	if (famT_drive) return(cmd_out_T());
	
	if (flags_cmd_out&f_putcmd)
	{ 
		unsigned long flags;
		for (i=0;i<7;i++)
			sprintf(&msgbuf[i*3], " %02X", drvcmd[i]);
		msgbuf[i*3]=0;
		msg(DBG_CMD,"cmd_out:%s\n", msgbuf);
		save_flags(flags); cli();
		for (i=0;i<7;i++) OUT(CDo_command,drvcmd[i]);
		restore_flags(flags);
	}
	if (response_count!=0)
	{
		if (cmd_type!=0)
		{
			if (sbpro_type==1) OUT(CDo_sel_i_d,1);
			msg(DBG_INF,"misleaded to try ResponseData.\n");
			if (sbpro_type==1) OUT(CDo_sel_i_d,0);
			return (-22);
		}
		else i=ResponseInfo();
		if (i<0) return (i);
	}
	if (current_drive->in_SpinUp) msg(DBG_SPI,"in_SpinUp: to CDi_stat_loop.\n");
	if (flags_cmd_out&f_lopsta)
	{
		i=CDi_stat_loop();
		if ((i<0)||!(i&s_attention)) return (-8);
	}
	if (!(flags_cmd_out&f_getsta)) goto LOC_229;
	
 LOC_228:
	if (current_drive->in_SpinUp) msg(DBG_SPI,"in_SpinUp: to cc_ReadStatus.\n");
	cc_ReadStatus();
	
 LOC_229:
	if (flags_cmd_out&f_ResponseStatus) 
	{
		if (current_drive->in_SpinUp) msg(DBG_SPI,"in_SpinUp: to ResponseStatus.\n");
		i=ResponseStatus();
		/* builds status_bits, returns orig. status or p_busy_new */
		if (i<0) return (i);
		if (flags_cmd_out&(f_bit1|f_wait_if_busy))
		{
			if (!st_check)
			{
				if ((flags_cmd_out&f_bit1)&&(i&p_success)) goto LOC_232;
				if ((!(flags_cmd_out&f_wait_if_busy))||(!st_busy)) goto LOC_228;
			}
		}
	}
 LOC_232:
	if (!(flags_cmd_out&f_obey_p_check)) return (0);
	if (!st_check) return (0);
	if (current_drive->in_SpinUp) msg(DBG_SPI,"in_SpinUp: to cc_ReadError.\n");
	i=cc_ReadError();
	if (current_drive->in_SpinUp) msg(DBG_SPI,"in_SpinUp: to cmd_out OK.\n");
	msg(DBG_000,"cmd_out: cc_ReadError=%d\n", i);
	return (i);
}
/*==========================================================================*/
static int cc_Seek(u_int pos, char f_blk_msf)
{
	int i;
	
  clr_cmdbuf();
	if (f_blk_msf>1) return (-3);
	if (fam0V_drive)
	{
		drvcmd[0]=CMD0_SEEK;
		if (f_blk_msf==1) pos=msf2blk(pos);
		drvcmd[2]=(pos>>16)&0x00FF;
		drvcmd[3]=(pos>>8)&0x00FF;
		drvcmd[4]=pos&0x00FF;
		if (fam0_drive)
		  flags_cmd_out = f_putcmd | f_respo2 | f_lopsta | f_getsta |
			f_ResponseStatus | f_obey_p_check | f_bit1;
		else
		  flags_cmd_out = f_putcmd;
	}
	else if (fam1L_drive)
	{
		drvcmd[0]=CMD1_SEEK; /* same as CMD1_ and CMDL_ */
		if (f_blk_msf==0) pos=blk2msf(pos);
		drvcmd[1]=(pos>>16)&0x00FF;
		drvcmd[2]=(pos>>8)&0x00FF;
		drvcmd[3]=pos&0x00FF;
		if (famL_drive)
			flags_cmd_out=f_putcmd|f_respo2|f_lopsta|f_getsta|f_ResponseStatus|f_obey_p_check|f_bit1;
		else
			flags_cmd_out=f_putcmd|f_respo2|f_ResponseStatus|f_obey_p_check;
	}
	else if (fam2_drive)
	{
		drvcmd[0]=CMD2_SEEK;
		if (f_blk_msf==0) pos=blk2msf(pos);
		drvcmd[2]=(pos>>24)&0x00FF;
		drvcmd[3]=(pos>>16)&0x00FF;
		drvcmd[4]=(pos>>8)&0x00FF;
		drvcmd[5]=pos&0x00FF;
		flags_cmd_out=f_putcmd|f_ResponseStatus;
	}
	else if (famT_drive)
	{
		drvcmd[0]=CMDT_SEEK;
		if (f_blk_msf==1) pos=msf2blk(pos);
		drvcmd[2]=(pos>>24)&0x00FF;
		drvcmd[3]=(pos>>16)&0x00FF;
		drvcmd[4]=(pos>>8)&0x00FF;
		drvcmd[5]=pos&0x00FF;
		current_drive->n_bytes=1;
	}
	response_count=0;
	i=cmd_out();
	return (i);
}
/*==========================================================================*/
static int cc_SpinUp(void)
{
	int i;
	
	msg(DBG_SPI,"SpinUp.\n");
	current_drive->in_SpinUp = 1;
	clr_cmdbuf();
	if (fam0LV_drive)
	{
		drvcmd[0]=CMD0_SPINUP;
		if (fam0L_drive)
		  flags_cmd_out=f_putcmd|f_respo2|f_lopsta|f_getsta|
		    f_ResponseStatus|f_obey_p_check|f_bit1;
		else
		  flags_cmd_out=f_putcmd;
	}
	else if (fam1_drive)
	{
		drvcmd[0]=CMD1_SPINUP;
		flags_cmd_out=f_putcmd|f_respo2|f_ResponseStatus|f_obey_p_check;
	}
	else if (fam2_drive)
	{
		drvcmd[0]=CMD2_TRAY_CTL;
		drvcmd[4]=0x01; /* "spinup" */
		flags_cmd_out=f_putcmd|f_respo2|f_ResponseStatus|f_obey_p_check;
	}
	else if (famT_drive)
	{
		drvcmd[0]=CMDT_TRAY_CTL;
		drvcmd[4]=0x03; /* "insert", it hopefully spins the drive up */
	}
	response_count=0;
	i=cmd_out();
	current_drive->in_SpinUp = 0;
	return (i);
}
/*==========================================================================*/
static int cc_SpinDown(void)
{
	int i;
	
	if (fam0_drive) return (0);
	clr_cmdbuf();
	response_count=0;
	if (fam1_drive)
	{
		drvcmd[0]=CMD1_SPINDOWN;
		flags_cmd_out=f_putcmd|f_respo2|f_ResponseStatus|f_obey_p_check;
	}
	else if (fam2_drive)
	{
		drvcmd[0]=CMD2_TRAY_CTL;
		drvcmd[4]=0x02; /* "eject" */
		flags_cmd_out=f_putcmd|f_ResponseStatus;
	}
	else if (famL_drive)
	{
		drvcmd[0]=CMDL_SPINDOWN;
		drvcmd[1]=1;
		flags_cmd_out=f_putcmd|f_respo2|f_lopsta|f_getsta|f_ResponseStatus|f_obey_p_check|f_bit1;
	}
	else if (famV_drive)
	{
		drvcmd[0]=CMDV_SPINDOWN;
		flags_cmd_out=f_putcmd;
	}
	else if (famT_drive)
	{
		drvcmd[0]=CMDT_TRAY_CTL;
		drvcmd[4]=0x02; /* "eject" */
	}
	i=cmd_out();
	return (i);
}
/*==========================================================================*/
static int cc_get_mode_T(void)
{
	int i;
	
	clr_cmdbuf();
	response_count=10;
	drvcmd[0]=CMDT_GETMODE;
	drvcmd[4]=response_count;
	i=cmd_out_T();
	return (i);
}
/*==========================================================================*/
static int cc_set_mode_T(void)
{
	int i;
	
	clr_cmdbuf();
	response_count=1;
	drvcmd[0]=CMDT_SETMODE;
	drvcmd[1]=current_drive->speed_byte;
	drvcmd[2]=current_drive->frmsiz>>8;
	drvcmd[3]=current_drive->frmsiz&0x0FF;
	drvcmd[4]=current_drive->f_XA; /* 1: XA */
	drvcmd[5]=current_drive->type_byte; /* 0, 1, 3 */
	drvcmd[6]=current_drive->mode_xb_6;
	drvcmd[7]=current_drive->mode_yb_7|current_drive->volume_control;
	drvcmd[8]=current_drive->mode_xb_8;
	drvcmd[9]=current_drive->delay;
	i=cmd_out_T();
	return (i);
}
/*==========================================================================*/
static int cc_prep_mode_T(void)
{
	int i, j;
	
	i=cc_get_mode_T();
	if (i<0) return (i);
	for (i=0;i<10;i++)
		sprintf(&msgbuf[i*3], " %02X", infobuf[i]);
	msgbuf[i*3]=0;
	msg(DBG_TEA,"CMDT_GETMODE:%s\n", msgbuf);
	current_drive->speed_byte=0x02; /* 0x02: auto quad, 0x82: quad, 0x81: double, 0x80: single */
	current_drive->frmsiz=make16(infobuf[2],infobuf[3]);
	current_drive->f_XA=infobuf[4];
	if (current_drive->f_XA==0) current_drive->type_byte=0;
	else current_drive->type_byte=1;
	current_drive->mode_xb_6=infobuf[6];
	current_drive->mode_yb_7=1;
	current_drive->mode_xb_8=infobuf[8];
	current_drive->delay=0; /* 0, 1, 2, 3 */
	j=cc_set_mode_T();
	i=cc_get_mode_T();
	for (i=0;i<10;i++)
		sprintf(&msgbuf[i*3], " %02X", infobuf[i]);
	msgbuf[i*3]=0;
	msg(DBG_TEA,"CMDT_GETMODE:%s\n", msgbuf);
	return (j);
}
/*==========================================================================*/
static int cc_SetSpeed(u_char speed, u_char x1, u_char x2)
{
	int i;
	
	if (fam0LV_drive) return (0);
	clr_cmdbuf();
	response_count=0;
	if (fam1_drive)
	{
		drvcmd[0]=CMD1_SETMODE;
		drvcmd[1]=0x03;
		drvcmd[2]=speed;
		drvcmd[3]=x1;
		drvcmd[4]=x2;
		flags_cmd_out=f_putcmd|f_ResponseStatus|f_obey_p_check;
	}
	else if (fam2_drive)
	{
		drvcmd[0]=CMD2_SETSPEED;
		if (speed&speed_auto)
		{
			drvcmd[2]=0xFF;
			drvcmd[3]=0xFF;
		}
		else
		{
			drvcmd[2]=0;
			drvcmd[3]=150;
		}
		flags_cmd_out=f_putcmd|f_ResponseStatus|f_obey_p_check;
	}
	else if (famT_drive)
	{
		return (0);
	}
	i=cmd_out();
	return (i);
}
/*==========================================================================*/
static int cc_SetVolume(void)
{
	int i;
	u_char channel0,channel1,volume0,volume1;
	u_char control0,value0,control1,value1;
	
	current_drive->diskstate_flags &= ~volume_bit;
	clr_cmdbuf();
	channel0=current_drive->vol_chan0;
	volume0=current_drive->vol_ctrl0;
	channel1=control1=current_drive->vol_chan1;
	volume1=value1=current_drive->vol_ctrl1;
	control0=value0=0;
	
	if (famV_drive) return (0);

	if (((current_drive->drv_options&audio_mono)!=0)&&(current_drive->drv_type>=drv_211))
	{
		if ((volume0!=0)&&(volume1==0))
		{
			volume1=volume0;
			channel1=channel0;
		}
		else if ((volume0==0)&&(volume1!=0))
		{
			volume0=volume1;
			channel0=channel1;
		}
	}
	if (channel0>1)
	{
		channel0=0;
		volume0=0;
	}
	if (channel1>1)
	{
		channel1=1;
		volume1=0;
	}
	
	if (fam1_drive)
	{
		control0=channel0+1;
		control1=channel1+1;
		value0=(volume0>volume1)?volume0:volume1;
		value1=value0;
		if (volume0==0) control0=0;
		if (volume1==0) control1=0;
		drvcmd[0]=CMD1_SETMODE;
		drvcmd[1]=0x05;
		drvcmd[3]=control0;
		drvcmd[4]=value0;
		drvcmd[5]=control1;
		drvcmd[6]=value1;
		flags_cmd_out=f_putcmd|f_ResponseStatus|f_obey_p_check;
	}
	else if (fam2_drive)
	{
		control0=channel0+1;
		control1=channel1+1;
		value0=(volume0>volume1)?volume0:volume1;
		value1=value0;
		if (volume0==0) control0=0;
		if (volume1==0) control1=0;
		drvcmd[0]=CMD2_SETMODE;
		drvcmd[1]=0x0E;
		drvcmd[3]=control0;
		drvcmd[4]=value0;
		drvcmd[5]=control1;
		drvcmd[6]=value1;
		flags_cmd_out=f_putcmd|f_ResponseStatus;
	}
	else if (famL_drive)
	{
		if ((volume0==0)||(channel0!=0)) control0 |= 0x80;
		if ((volume1==0)||(channel1!=1)) control0 |= 0x40;
		if (volume0|volume1) value0=0x80;
		drvcmd[0]=CMDL_SETMODE;
		drvcmd[1]=0x03;
		drvcmd[4]=control0;
		drvcmd[5]=value0;
		flags_cmd_out=f_putcmd|f_lopsta|f_getsta|f_ResponseStatus|f_obey_p_check|f_bit1;
	}
	else if (fam0_drive) /* different firmware levels */
	{
		if (current_drive->drv_type>=drv_300)
		{
			control0=volume0&0xFC;
			value0=volume1&0xFC;
			if ((volume0!=0)&&(volume0<4)) control0 |= 0x04;
			if ((volume1!=0)&&(volume1<4)) value0 |= 0x04;
			if (channel0!=0) control0 |= 0x01;
			if (channel1==1) value0 |= 0x01;
		}
		else
		{
			value0=(volume0>volume1)?volume0:volume1;
			if (current_drive->drv_type<drv_211)
			{
				if (channel0!=0)
				{
					i=channel1;
					channel1=channel0;
					channel0=i;
					i=volume1;
					volume1=volume0;
					volume0=i;
				}
				if (channel0==channel1)
				{
					if (channel0==0)
					{
						channel1=1;
						volume1=0;
						volume0=value0;
					}
					else
					{
						channel0=0;
						volume0=0;
						volume1=value0;
					}
				}
			}
			
			if ((volume0!=0)&&(volume1!=0))
			{
				if (volume0==0xFF) volume1=0xFF;
				else if (volume1==0xFF) volume0=0xFF;
			}
			else if (current_drive->drv_type<drv_201) volume0=volume1=value0;
			
			if (current_drive->drv_type>=drv_201)
			{
				if (volume0==0) control0 |= 0x80;
				if (volume1==0) control0 |= 0x40;
			}
			if (current_drive->drv_type>=drv_211)
			{
				if (channel0!=0) control0 |= 0x20;
				if (channel1!=1) control0 |= 0x10;
			}
		}
		drvcmd[0]=CMD0_SETMODE;
		drvcmd[1]=0x83;
		drvcmd[4]=control0;
		drvcmd[5]=value0;
		flags_cmd_out=f_putcmd|f_getsta|f_ResponseStatus|f_obey_p_check;
	}
	else if (famT_drive)
	{
		current_drive->volume_control=0;
		if (!volume0) current_drive->volume_control|=0x10;
		if (!volume1) current_drive->volume_control|=0x20;
		i=cc_prep_mode_T();
		if (i<0) return (i);
	}
	if (!famT_drive)
	{
		response_count=0;
		i=cmd_out();
		if (i<0) return (i);
	}
	current_drive->diskstate_flags |= volume_bit;
	return (0);
}
/*==========================================================================*/
static int GetStatus(void)
{
	int i;
	
	if (famT_drive) return (0);
	flags_cmd_out=f_getsta|f_ResponseStatus|f_obey_p_check;
	response_count=0;
	cmd_type=0;
	i=cmd_out();
	return (i);
}
/*==========================================================================*/
static int cc_DriveReset(void)
{
	int i;
	
	msg(DBG_RES,"cc_DriveReset called.\n");
	clr_cmdbuf();
	response_count=0;
	if (fam0LV_drive) OUT(CDo_reset,0x00);
	else if (fam1_drive)
	{
		drvcmd[0]=CMD1_RESET;
		flags_cmd_out=f_putcmd;
		i=cmd_out();
	}
	else if (fam2_drive)
	{
		drvcmd[0]=CMD2_RESET;
		flags_cmd_out=f_putcmd;
		i=cmd_out();
		OUT(CDo_reset,0x00);
	}
	else if (famT_drive)
	{
		OUT(CDo_sel_i_d,0);
		OUT(CDo_enable,current_drive->drv_sel);
		OUT(CDo_command,CMDT_RESET);
		for (i=1;i<10;i++) OUT(CDo_command,0);
	}
	if (fam0LV_drive) sbp_sleep(5*HZ); /* wait 5 seconds */
	else sbp_sleep(1*HZ); /* wait a second */
#if 1
	if (famT_drive)
	{
		msg(DBG_TEA, "================CMDT_RESET given=================.\n");
		sbp_sleep(3*HZ);
	}
#endif /* 1 */ 
	flush_status();
	i=GetStatus();
	if (i<0) return i;
	if (!famT_drive)
		if (current_drive->error_byte!=aud_12) return -501;
	return (0);
}

/*==========================================================================*/
static int SetSpeed(void)
{
	int i, speed;
	
	if (!(current_drive->drv_options&(speed_auto|speed_300|speed_150))) return (0);
	speed=speed_auto;
	if (!(current_drive->drv_options&speed_auto))
	{
		speed |= speed_300;
		if (!(current_drive->drv_options&speed_300)) speed=0;
	}
	i=cc_SetSpeed(speed,0,0);
	return (i);
}

static void switch_drive(struct sbpcd_drive *);

static int sbpcd_select_speed(struct cdrom_device_info *cdi, int speed)
{
	struct sbpcd_drive *p = cdi->handle;
	if (p != current_drive)
		switch_drive(p);

	return cc_SetSpeed(speed == 2 ? speed_300 : speed_150, 0, 0);
}

/*==========================================================================*/
static int DriveReset(void)
{
	int i;
	
	i=cc_DriveReset();
	if (i<0) return (-22);
	do
	{
		i=GetStatus();
		if ((i<0)&&(i!=-ERR_DISKCHANGE)) {
			return (-2); /* from sta2err */
		}
		if (!st_caddy_in) break;
		sbp_sleep(1);
	}
	while (!st_diskok);
#if 000
	current_drive->CD_changed=1;
#endif
	if ((st_door_closed) && (st_caddy_in))
	{
		i=DiskInfo();
		if (i<0) return (-23);
	}
	return (0);
}

static int sbpcd_reset(struct cdrom_device_info *cdi)
{
	struct sbpcd_drive *p = cdi->handle;
	if (p != current_drive)
		switch_drive(p);
	return DriveReset();
}

/*==========================================================================*/
static int cc_PlayAudio(int pos_audio_start,int pos_audio_end)
{
	int i, j, n;
	
	if (current_drive->audio_state==audio_playing) return (-EINVAL);
	clr_cmdbuf();
	response_count=0;
	if (famLV_drive)
	{
		drvcmd[0]=CMDL_PLAY;
		i=msf2blk(pos_audio_start);
		n=msf2blk(pos_audio_end)+1-i;
		drvcmd[1]=(i>>16)&0x00FF;
		drvcmd[2]=(i>>8)&0x00FF;
		drvcmd[3]=i&0x00FF;
		drvcmd[4]=(n>>16)&0x00FF;
		drvcmd[5]=(n>>8)&0x00FF;
		drvcmd[6]=n&0x00FF;
		if (famL_drive)
		flags_cmd_out = f_putcmd | f_respo2 | f_lopsta | f_getsta |
			f_ResponseStatus | f_obey_p_check | f_wait_if_busy;
		else
		  flags_cmd_out = f_putcmd;
	}
	else
	{
		j=1;
		if (fam1_drive)
		{
			drvcmd[0]=CMD1_PLAY_MSF;
			flags_cmd_out = f_putcmd | f_respo2 | f_ResponseStatus |
				f_obey_p_check | f_wait_if_busy;
		}
		else if (fam2_drive)
		{
			drvcmd[0]=CMD2_PLAY_MSF;
			flags_cmd_out = f_putcmd | f_ResponseStatus | f_obey_p_check;
		}
		else if (famT_drive)
		{
			drvcmd[0]=CMDT_PLAY_MSF;
			j=3;
			response_count=1;
		}
		else if (fam0_drive)
		{
			drvcmd[0]=CMD0_PLAY_MSF;
			flags_cmd_out = f_putcmd | f_respo2 | f_lopsta | f_getsta |
				f_ResponseStatus | f_obey_p_check | f_wait_if_busy;
		}
		drvcmd[j]=(pos_audio_start>>16)&0x00FF;
		drvcmd[j+1]=(pos_audio_start>>8)&0x00FF;
		drvcmd[j+2]=pos_audio_start&0x00FF;
		drvcmd[j+3]=(pos_audio_end>>16)&0x00FF;
		drvcmd[j+4]=(pos_audio_end>>8)&0x00FF;
		drvcmd[j+5]=pos_audio_end&0x00FF;
	}
	i=cmd_out();
	return (i);
}
/*==========================================================================*/
static int cc_Pause_Resume(int pau_res)
{
	int i;
	
	clr_cmdbuf();
	response_count=0;
	if (fam1_drive)
	{
		drvcmd[0]=CMD1_PAU_RES;
		if (pau_res!=1) drvcmd[1]=0x80;
		flags_cmd_out=f_putcmd|f_respo2|f_ResponseStatus|f_obey_p_check;
	}
	else if (fam2_drive)
	{
		drvcmd[0]=CMD2_PAU_RES;
		if (pau_res!=1) drvcmd[2]=0x01;
		flags_cmd_out=f_putcmd|f_ResponseStatus;
	}
	else if (fam0LV_drive)
	{
		drvcmd[0]=CMD0_PAU_RES;
		if (pau_res!=1) drvcmd[1]=0x80;
		if (famL_drive)
			flags_cmd_out=f_putcmd|f_respo2|f_lopsta|f_getsta|f_ResponseStatus|
				f_obey_p_check|f_bit1;
		else if (famV_drive)
		  flags_cmd_out=f_putcmd;
		else
			flags_cmd_out=f_putcmd|f_respo2|f_lopsta|f_getsta|f_ResponseStatus|
				f_obey_p_check;
	}
	else if (famT_drive)
	{
		if (pau_res==3)	return (cc_PlayAudio(current_drive->pos_audio_start,current_drive->pos_audio_end));
		else if (pau_res==1) drvcmd[0]=CMDT_PAUSE;
		else return (-56);
	}
	i=cmd_out();
	return (i);
}
/*==========================================================================*/
static int cc_LockDoor(char lock)
{
	int i;
	
	if (fam0_drive) return (0);
	msg(DBG_LCK,"cc_LockDoor: %d (drive %d)\n", lock, current_drive - D_S);
	msg(DBG_LCS,"p_door_locked bit %d before\n", st_door_locked);
	clr_cmdbuf();
	response_count=0;
	if (fam1_drive)
	{
		drvcmd[0]=CMD1_LOCK_CTL;
		if (lock==1) drvcmd[1]=0x01;
		flags_cmd_out=f_putcmd|f_ResponseStatus|f_obey_p_check;
	}
	else if (fam2_drive)
	{
		drvcmd[0]=CMD2_LOCK_CTL;
		if (lock==1) drvcmd[4]=0x01;
		flags_cmd_out=f_putcmd|f_ResponseStatus;
	}
	else if (famLV_drive)
	{
		drvcmd[0]=CMDL_LOCK_CTL;
		if (lock==1) drvcmd[1]=0x01;
		if (famL_drive)
		  flags_cmd_out=f_putcmd|f_respo2|f_lopsta|f_getsta|f_ResponseStatus|f_obey_p_check|f_bit1;
		else
		  flags_cmd_out=f_putcmd;
	}
	else if (famT_drive)
	{
		drvcmd[0]=CMDT_LOCK_CTL;
		if (lock==1) drvcmd[4]=0x01;
	}
	i=cmd_out();
	msg(DBG_LCS,"p_door_locked bit %d after\n", st_door_locked);
	return (i);
}
/*==========================================================================*/
/*==========================================================================*/
static int UnLockDoor(void)
{
	int i,j;
	
	j=20;
	do
	{
		i=cc_LockDoor(0);
		--j;
		sbp_sleep(1);
	}
	while ((i<0)&&(j));
	if (i<0)
	{
		cc_DriveReset();
		return -84;
	}
	return (0);
}
/*==========================================================================*/
static int LockDoor(void)
{
	int i,j;
	
	j=20;
	do
	{
		i=cc_LockDoor(1);
		--j;
		sbp_sleep(1);
	}
	while ((i<0)&&(j));
	if (j==0)
	{		
		cc_DriveReset();
		j=20;
		do
		{
			i=cc_LockDoor(1);
			--j;
			sbp_sleep(1);
		}
		while ((i<0)&&(j));
	}
	return (i);
}

static int sbpcd_lock_door(struct cdrom_device_info *cdi, int lock)
{
  return lock ? LockDoor() : UnLockDoor();
}

/*==========================================================================*/
static int cc_CloseTray(void)
{
	int i;
	
	if (fam0_drive) return (0);
	msg(DBG_LCK,"cc_CloseTray (drive %d)\n", current_drive - D_S);
	msg(DBG_LCS,"p_door_closed bit %d before\n", st_door_closed);
	
	clr_cmdbuf();
	response_count=0;
	if (fam1_drive)
	{
		drvcmd[0]=CMD1_TRAY_CTL;
		flags_cmd_out=f_putcmd|f_respo2|f_ResponseStatus|f_obey_p_check;
	}
	else if (fam2_drive)
	{
		drvcmd[0]=CMD2_TRAY_CTL;
		drvcmd[1]=0x01;
		drvcmd[4]=0x03; /* "insert" */
		flags_cmd_out=f_putcmd|f_ResponseStatus;
	}
	else if (famLV_drive)
	{
		drvcmd[0]=CMDL_TRAY_CTL;
		if (famLV_drive)
		  flags_cmd_out=f_putcmd|f_respo2|f_lopsta|f_getsta|
			f_ResponseStatus|f_obey_p_check|f_bit1;
		else
		  flags_cmd_out=f_putcmd;
	}
	else if (famT_drive)
	{
		drvcmd[0]=CMDT_TRAY_CTL;
		drvcmd[4]=0x03; /* "insert" */
	}
	i=cmd_out();
	msg(DBG_LCS,"p_door_closed bit %d after\n", st_door_closed);

	i=cc_ReadError();
	flags_cmd_out |= f_respo2;
	cc_ReadStatus(); /* command: give 1-byte status */
	i=ResponseStatus();
	if (famT_drive&&(i<0))
	{
		cc_DriveReset();
		i=ResponseStatus();
#if 0
                sbp_sleep(HZ);
#endif /* 0 */ 
		i=ResponseStatus();
	}
	if (i<0)
	{
		msg(DBG_INF,"sbpcd cc_CloseTray: ResponseStatus timed out (%d).\n",i);
	}
	if (!(famT_drive))
	{
		if (!st_spinning)
		{
			cc_SpinUp();
			if (st_check) i=cc_ReadError();
			flags_cmd_out |= f_respo2;
			cc_ReadStatus();
			i=ResponseStatus();
		} else {
		}
	}
	i=DiskInfo();
	return (i);
}

static int sbpcd_tray_move(struct cdrom_device_info *cdi, int position)
{
	int retval=0;
	switch_drive(cdi->handle);
	/* DUH! --AJK */
	if(current_drive->CD_changed != 0xFF) {
		current_drive->CD_changed=0xFF;
		current_drive->diskstate_flags &= ~cd_size_bit;
	}
	if (position == 1) {
		cc_SpinDown();
	} else {
		retval=cc_CloseTray();
	}
  return retval;
}

/*==========================================================================*/
static int cc_ReadSubQ(void)
{
	int i,j;

	current_drive->diskstate_flags &= ~subq_bit;
	for (j=255;j>0;j--)
	{
		clr_cmdbuf();
		if (fam1_drive)
		{
			drvcmd[0]=CMD1_READSUBQ;
			flags_cmd_out=f_putcmd|f_ResponseStatus|f_obey_p_check;
			response_count=11;
		}
		else if (fam2_drive)
		{
			drvcmd[0]=CMD2_READSUBQ;
			drvcmd[1]=0x02;
			drvcmd[3]=0x01;
			flags_cmd_out=f_putcmd;
			response_count=10;
		}
		else if (fam0LV_drive)
		{
			drvcmd[0]=CMD0_READSUBQ;
			drvcmd[1]=0x02;
			if (famLV_drive)
				flags_cmd_out=f_putcmd;
			else
				flags_cmd_out=f_putcmd|f_getsta|f_ResponseStatus|f_obey_p_check;
			response_count=13;
		}
		else if (famT_drive)
		{
			response_count=12;
			drvcmd[0]=CMDT_READSUBQ;
			drvcmd[1]=0x02;
			drvcmd[2]=0x40;
			drvcmd[3]=0x01;
			drvcmd[8]=response_count;
		}
		i=cmd_out();
		if (i<0) return (i);
		for (i=0;i<response_count;i++)
		{
			sprintf(&msgbuf[i*3], " %02X", infobuf[i]);
			msgbuf[i*3]=0;
			msg(DBG_SQ1,"cc_ReadSubQ:%s\n", msgbuf);
		}
		if (famT_drive) break;
		if (infobuf[0]!=0) break;
		if ((!st_spinning) || (j==1))
		{
			current_drive->SubQ_ctl_adr=current_drive->SubQ_trk=current_drive->SubQ_pnt_idx=current_drive->SubQ_whatisthis=0;
			current_drive->SubQ_run_tot=current_drive->SubQ_run_trk=0;
			return (0);
		}
	}
	if (famT_drive) current_drive->SubQ_ctl_adr=infobuf[1];
	else current_drive->SubQ_ctl_adr=swap_nibbles(infobuf[1]);
	current_drive->SubQ_trk=byt2bcd(infobuf[2]);
	current_drive->SubQ_pnt_idx=byt2bcd(infobuf[3]);
	if (fam0LV_drive) i=5;
	else if (fam12_drive) i=4;
	else if (famT_drive) i=8;
	current_drive->SubQ_run_tot=make32(make16(0,infobuf[i]),make16(infobuf[i+1],infobuf[i+2])); /* msf-bin */
	i=7;
	if (fam0LV_drive) i=9;
	else if (fam12_drive) i=7;
	else if (famT_drive) i=4;
	current_drive->SubQ_run_trk=make32(make16(0,infobuf[i]),make16(infobuf[i+1],infobuf[i+2])); /* msf-bin */
	current_drive->SubQ_whatisthis=infobuf[i+3];
	current_drive->diskstate_flags |= subq_bit;
	return (0);
}
/*==========================================================================*/
static int cc_ModeSense(void)
{
	int i;
	
	if (fam2_drive) return (0);
	if (famV_drive) return (0);
	current_drive->diskstate_flags &= ~frame_size_bit;
	clr_cmdbuf();
	if (fam1_drive)
	{
		response_count=5;
		drvcmd[0]=CMD1_GETMODE;
		flags_cmd_out=f_putcmd|f_ResponseStatus|f_obey_p_check;
	}
	else if (fam0L_drive)
	{
		response_count=2;
		drvcmd[0]=CMD0_GETMODE;
		if (famL_drive) flags_cmd_out=f_putcmd;
		else flags_cmd_out=f_putcmd|f_getsta|f_ResponseStatus|f_obey_p_check;
	}
	else if (famT_drive)
	{
		response_count=10;
		drvcmd[0]=CMDT_GETMODE;
		drvcmd[4]=response_count;
	}
	i=cmd_out();
	if (i<0) return (i);
	i=0;
	current_drive->sense_byte=0;
	if (fam1_drive) current_drive->sense_byte=infobuf[i++];
	else if (famT_drive)
	{
		if (infobuf[4]==0x01) current_drive->xa_byte=0x20;
		else current_drive->xa_byte=0;
		i=2;
	}
	current_drive->frame_size=make16(infobuf[i],infobuf[i+1]);
	for (i=0;i<response_count;i++)
		sprintf(&msgbuf[i*3], " %02X", infobuf[i]);
	msgbuf[i*3]=0;
	msg(DBG_XA1,"cc_ModeSense:%s\n", msgbuf);
	
	current_drive->diskstate_flags |= frame_size_bit;
	return (0);
}
/*==========================================================================*/
/*==========================================================================*/
static int cc_ModeSelect(int framesize)
{
	int i;
	
	if (fam2_drive) return (0);
	if (famV_drive) return (0);
	current_drive->diskstate_flags &= ~frame_size_bit;
	clr_cmdbuf();
	current_drive->frame_size=framesize;
	if (framesize==CD_FRAMESIZE_RAW) current_drive->sense_byte=0x82;
	else current_drive->sense_byte=0x00;
	
	msg(DBG_XA1,"cc_ModeSelect: %02X %04X\n",
	    current_drive->sense_byte, current_drive->frame_size);
	
	if (fam1_drive)
	{
		drvcmd[0]=CMD1_SETMODE;
		drvcmd[1]=0x00;
		drvcmd[2]=current_drive->sense_byte;
		drvcmd[3]=(current_drive->frame_size>>8)&0xFF;
		drvcmd[4]=current_drive->frame_size&0xFF;
		flags_cmd_out=f_putcmd|f_ResponseStatus|f_obey_p_check;
	}
	else if (fam0L_drive)
	{
		drvcmd[0]=CMD0_SETMODE;
		drvcmd[1]=0x00;
		drvcmd[2]=(current_drive->frame_size>>8)&0xFF;
		drvcmd[3]=current_drive->frame_size&0xFF;
		drvcmd[4]=0x00;
		if(famL_drive)
			flags_cmd_out=f_putcmd|f_lopsta|f_getsta|f_ResponseStatus|f_obey_p_check;
		else
			flags_cmd_out=f_putcmd|f_getsta|f_ResponseStatus|f_obey_p_check;
	}
	else if (famT_drive)
	{
		return (-1);
	}
	response_count=0;
	i=cmd_out();
	if (i<0) return (i);
	current_drive->diskstate_flags |= frame_size_bit;
	return (0);
}
/*==========================================================================*/
static int cc_GetVolume(void)
{
	int i;
	u_char switches;
	u_char chan0=0;
	u_char vol0=0;
	u_char chan1=1;
	u_char vol1=0;
	
	if (famV_drive) return (0);
	current_drive->diskstate_flags &= ~volume_bit;
	clr_cmdbuf();
	if (fam1_drive)
	{
		drvcmd[0]=CMD1_GETMODE;
		drvcmd[1]=0x05;
		response_count=5;
		flags_cmd_out=f_putcmd|f_ResponseStatus|f_obey_p_check;
	}
	else if (fam2_drive)
	{
		drvcmd[0]=CMD2_GETMODE;
		drvcmd[1]=0x0E;
		response_count=5;
		flags_cmd_out=f_putcmd;
	}
	else if (fam0L_drive)
	{
		drvcmd[0]=CMD0_GETMODE;
		drvcmd[1]=0x03;
		response_count=2;
		if(famL_drive)
			flags_cmd_out=f_putcmd;
		else
			flags_cmd_out=f_putcmd|f_getsta|f_ResponseStatus|f_obey_p_check;
	}
	else if (famT_drive)
	{
		i=cc_get_mode_T();
		if (i<0) return (i);
	}
	if (!famT_drive)
	{
		i=cmd_out();
		if (i<0) return (i);
	}
	if (fam1_drive)
	{
		chan0=infobuf[1]&0x0F;
		vol0=infobuf[2];
		chan1=infobuf[3]&0x0F;
		vol1=infobuf[4];
		if (chan0==0)
		{
			chan0=1;
			vol0=0;
		}
		if (chan1==0)
		{
			chan1=2;
			vol1=0;
		}
		chan0 >>= 1;
		chan1 >>= 1;
	}
	else if (fam2_drive)
	{
		chan0=infobuf[1];
		vol0=infobuf[2];
		chan1=infobuf[3];
		vol1=infobuf[4];
	}
	else if (famL_drive)
	{
		chan0=0;
		chan1=1;
		vol0=vol1=infobuf[1];
		switches=infobuf[0];
		if ((switches&0x80)!=0) chan0=1;
		if ((switches&0x40)!=0) chan1=0;
	}
	else if (fam0_drive) /* different firmware levels */
	{
		chan0=0;
		chan1=1;
		vol0=vol1=infobuf[1];
		if (current_drive->drv_type>=drv_201)
		{
			if (current_drive->drv_type<drv_300)
			{
				switches=infobuf[0];
				if ((switches&0x80)!=0) vol0=0;
				if ((switches&0x40)!=0) vol1=0;
				if (current_drive->drv_type>=drv_211)
				{
					if ((switches&0x20)!=0) chan0=1;
					if ((switches&0x10)!=0) chan1=0;
				}
			}
			else
			{
				vol0=infobuf[0];
				if ((vol0&0x01)!=0) chan0=1;
				if ((vol1&0x01)==0) chan1=0;
				vol0 &= 0xFC;
				vol1 &= 0xFC;
				if (vol0!=0) vol0 += 3;
				if (vol1!=0) vol1 += 3;
			}
		}
	}
	else if (famT_drive)
	{
		current_drive->volume_control=infobuf[7];
		chan0=0;
		chan1=1;
		if (current_drive->volume_control&0x10) vol0=0;
		else vol0=0xff;
		if (current_drive->volume_control&0x20) vol1=0;
		else vol1=0xff;
	}
	current_drive->vol_chan0=chan0;
	current_drive->vol_ctrl0=vol0;
	current_drive->vol_chan1=chan1;
	current_drive->vol_ctrl1=vol1;
#if 000
	current_drive->vol_chan2=2;
	current_drive->vol_ctrl2=0xFF;
	current_drive->vol_chan3=3;
	current_drive->vol_ctrl3=0xFF;
#endif /*  000 */
	current_drive->diskstate_flags |= volume_bit;
	return (0);
}
/*==========================================================================*/
static int cc_ReadCapacity(void)
{
	int i, j;
	
	if (fam2_drive) return (0); /* some firmware lacks this command */
	if (famLV_drive) return (0); /* some firmware lacks this command */
	if (famT_drive) return (0); /* done with cc_ReadTocDescr() */
	current_drive->diskstate_flags &= ~cd_size_bit;
	for (j=3;j>0;j--)
	{
		clr_cmdbuf();
		if (fam1_drive)
		{
			drvcmd[0]=CMD1_CAPACITY;
			response_count=5;
			flags_cmd_out=f_putcmd|f_ResponseStatus|f_obey_p_check;
		}
#if 00
		else if (fam2_drive)
		{
			drvcmd[0]=CMD2_CAPACITY;
			response_count=8;
			flags_cmd_out=f_putcmd;
		}
#endif
		else if (fam0_drive)
		{
			drvcmd[0]=CMD0_CAPACITY;
			response_count=5;
			flags_cmd_out=f_putcmd|f_getsta|f_ResponseStatus|f_obey_p_check;
		}
		i=cmd_out();
		if (i>=0) break;
		msg(DBG_000,"cc_ReadCapacity: cmd_out: err %d\n", i);
		cc_ReadError();
	}
	if (j==0) return (i);
	if (fam1_drive) current_drive->CDsize_frm=msf2blk(make32(make16(0,infobuf[0]),make16(infobuf[1],infobuf[2])))+CD_MSF_OFFSET;
	else if (fam0_drive) current_drive->CDsize_frm=make32(make16(0,infobuf[0]),make16(infobuf[1],infobuf[2]));
#if 00
	else if (fam2_drive) current_drive->CDsize_frm=make32(make16(infobuf[0],infobuf[1]),make16(infobuf[2],infobuf[3]));
#endif
	current_drive->diskstate_flags |= cd_size_bit;
	msg(DBG_000,"cc_ReadCapacity: %d frames.\n", current_drive->CDsize_frm);
	return (0);
}
/*==========================================================================*/
static int cc_ReadTocDescr(void)
{
	int i;
	
	current_drive->diskstate_flags &= ~toc_bit;
	clr_cmdbuf();
	if (fam1_drive)
	{
		drvcmd[0]=CMD1_DISKINFO;
		response_count=6;
		flags_cmd_out=f_putcmd|f_ResponseStatus|f_obey_p_check;
	}
	else if (fam0LV_drive)
	{
		drvcmd[0]=CMD0_DISKINFO;
		response_count=6;
		if(famLV_drive)
			flags_cmd_out=f_putcmd;
		else
			flags_cmd_out=f_putcmd|f_getsta|f_ResponseStatus|f_obey_p_check;
	}
	else if (fam2_drive)
	{
		/* possibly longer timeout periods necessary */
		current_drive->f_multisession=0;
		drvcmd[0]=CMD2_DISKINFO;
		drvcmd[1]=0x02;
		drvcmd[2]=0xAB;
		drvcmd[3]=0xFF; /* session */
		response_count=8;
		flags_cmd_out=f_putcmd;
	}
	else if (famT_drive)
	{
		current_drive->f_multisession=0;
		response_count=12;
		drvcmd[0]=CMDT_DISKINFO;
		drvcmd[1]=0x02;
		drvcmd[6]=CDROM_LEADOUT;
		drvcmd[8]=response_count;
		drvcmd[9]=0x00;
	}
	i=cmd_out();
	if (i<0) return (i);
	if ((famT_drive)&&(i<response_count)) return (-100-i);
	if ((fam1_drive)||(fam2_drive)||(fam0LV_drive))
		current_drive->xa_byte=infobuf[0];
	if (fam2_drive)
	{
		current_drive->first_session=infobuf[1];
		current_drive->last_session=infobuf[2];
		current_drive->n_first_track=infobuf[3];
		current_drive->n_last_track=infobuf[4];
		if (current_drive->first_session!=current_drive->last_session)
		{
			current_drive->f_multisession=1;
			current_drive->lba_multi=msf2blk(make32(make16(0,infobuf[5]),make16(infobuf[6],infobuf[7])));
		}
#if 0
		if (current_drive->first_session!=current_drive->last_session)
		{
			if (current_drive->last_session<=20)
				zwanzig=current_drive->last_session+1;
			else zwanzig=20;
			for (count=current_drive->first_session;count<zwanzig;count++)
			{
				drvcmd[0]=CMD2_DISKINFO;
				drvcmd[1]=0x02;
				drvcmd[2]=0xAB;
				drvcmd[3]=count;
				response_count=8;
				flags_cmd_out=f_putcmd;
				i=cmd_out();
				if (i<0) return (i);
				current_drive->msf_multi_n[count]=make32(make16(0,infobuf[5]),make16(infobuf[6],infobuf[7]));
			}
			current_drive->diskstate_flags |= multisession_bit;
		}
#endif
		drvcmd[0]=CMD2_DISKINFO;
		drvcmd[1]=0x02;
		drvcmd[2]=0xAA;
		drvcmd[3]=0xFF;
		response_count=5;
		flags_cmd_out=f_putcmd;
		i=cmd_out();
		if (i<0) return (i);
		current_drive->size_msf=make32(make16(0,infobuf[2]),make16(infobuf[3],infobuf[4]));
		current_drive->size_blk=msf2blk(current_drive->size_msf);
		current_drive->CDsize_frm=current_drive->size_blk+1;
	}
	else if (famT_drive)
	{
		current_drive->size_msf=make32(make16(infobuf[8],infobuf[9]),make16(infobuf[10],infobuf[11]));
		current_drive->size_blk=msf2blk(current_drive->size_msf);
		current_drive->CDsize_frm=current_drive->size_blk+1;
		current_drive->n_first_track=infobuf[2];
		current_drive->n_last_track=infobuf[3];
	}
	else
	{
		current_drive->n_first_track=infobuf[1];
		current_drive->n_last_track=infobuf[2];
		current_drive->size_msf=make32(make16(0,infobuf[3]),make16(infobuf[4],infobuf[5]));
		current_drive->size_blk=msf2blk(current_drive->size_msf);
		if (famLV_drive) current_drive->CDsize_frm=current_drive->size_blk+1;
	}
	current_drive->diskstate_flags |= toc_bit;
	msg(DBG_TOC,"TocDesc: xa %02X firstt %02X lastt %02X size %08X firstses %02X lastsess %02X\n",
	    current_drive->xa_byte,
	    current_drive->n_first_track,
	    current_drive->n_last_track,
	    current_drive->size_msf,
	    current_drive->first_session,
	    current_drive->last_session);
	return (0);
}
/*==========================================================================*/
static int cc_ReadTocEntry(int num)
{
	int i;
	
	clr_cmdbuf();
	if (fam1_drive)
	{
		drvcmd[0]=CMD1_READTOC;
		drvcmd[2]=num;
		response_count=8;
		flags_cmd_out=f_putcmd|f_ResponseStatus|f_obey_p_check;
	}
	else if (fam2_drive)
	{
		/* possibly longer timeout periods necessary */
		drvcmd[0]=CMD2_DISKINFO;
		drvcmd[1]=0x02;
		drvcmd[2]=num;
		response_count=5;
		flags_cmd_out=f_putcmd;
	}
	else if (fam0LV_drive)
	{
		drvcmd[0]=CMD0_READTOC;
		drvcmd[1]=0x02;
		drvcmd[2]=num;
		response_count=8;
		if (famLV_drive)
			flags_cmd_out=f_putcmd;
		else
		  flags_cmd_out=f_putcmd|f_getsta|f_ResponseStatus|f_obey_p_check;
	}
	else if (famT_drive)
	{
		response_count=12;
		drvcmd[0]=CMDT_DISKINFO;
		drvcmd[1]=0x02;
		drvcmd[6]=num;
		drvcmd[8]=response_count;
		drvcmd[9]=0x00;
	}
	i=cmd_out();
	if (i<0) return (i);
	if ((famT_drive)&&(i<response_count)) return (-100-i);
	if ((fam1_drive)||(fam0LV_drive))
	{
		current_drive->TocEnt_nixbyte=infobuf[0];
		i=1;
	}
	else if (fam2_drive) i=0;
	else if (famT_drive) i=5;
	current_drive->TocEnt_ctl_adr=swap_nibbles(infobuf[i++]);
	if ((fam1_drive)||(fam0L_drive))
	{
		current_drive->TocEnt_number=infobuf[i++];
		current_drive->TocEnt_format=infobuf[i];
	}
	else
	  {
	    current_drive->TocEnt_number=num;
	    current_drive->TocEnt_format=0;
	  }
	if (fam1_drive) i=4;
	else if (fam0LV_drive) i=5;
	else if (fam2_drive) i=2;
	else if (famT_drive) i=9;
	current_drive->TocEnt_address=make32(make16(0,infobuf[i]),
				     make16(infobuf[i+1],infobuf[i+2]));
	for (i=0;i<response_count;i++)
		sprintf(&msgbuf[i*3], " %02X", infobuf[i]);
	msgbuf[i*3]=0;
	msg(DBG_ECS,"TocEntry:%s\n", msgbuf);
	msg(DBG_TOC,"TocEntry: %02X %02X %02X %02X %08X\n",
	    current_drive->TocEnt_nixbyte, current_drive->TocEnt_ctl_adr,
	    current_drive->TocEnt_number, current_drive->TocEnt_format,
	    current_drive->TocEnt_address);
	return (0);
}
/*==========================================================================*/
static int cc_ReadPacket(void)
{
	int i;
	
	clr_cmdbuf();
	drvcmd[0]=CMD0_PACKET;
	drvcmd[1]=response_count;
	if(famL_drive) flags_cmd_out=f_putcmd;
	else if (fam01_drive)
		flags_cmd_out=f_putcmd|f_getsta|f_ResponseStatus|f_obey_p_check;
	else if (fam2_drive) return (-1); /* not implemented yet */
	else if (famT_drive)
	{
		return (-1);
	}
	i=cmd_out();
	return (i);
}
/*==========================================================================*/
static int convert_UPC(u_char *p)
{
	int i;
	
	p++;
	if (fam0L_drive) p[13]=0;
	for (i=0;i<7;i++)
	{
		if (fam1_drive) current_drive->UPC_buf[i]=swap_nibbles(*p++);
		else if (fam0L_drive)
		{
			current_drive->UPC_buf[i]=((*p++)<<4)&0xFF;
			current_drive->UPC_buf[i] |= *p++;
		}
		else if (famT_drive)
		{
			return (-1);
		}
		else /* CD200 */
		{
			return (-1);
		}
	}
	current_drive->UPC_buf[6] &= 0xF0;
	return (0);
}
/*==========================================================================*/
static int cc_ReadUPC(void)
{
	int i;
#if TEST_UPC
	int block, checksum;
#endif /* TEST_UPC */ 
	
	if (fam2_drive) return (0); /* not implemented yet */
	if (famT_drive)	return (0); /* not implemented yet */
	if (famV_drive)	return (0); /* not implemented yet */
#if 1
	if (fam0_drive) return (0); /* but it should work */
#endif
	
	current_drive->diskstate_flags &= ~upc_bit;
#if TEST_UPC
	for (block=CD_MSF_OFFSET+1;block<CD_MSF_OFFSET+200;block++)
	{
#endif /* TEST_UPC */ 
		clr_cmdbuf();
		if (fam1_drive)
		{
			drvcmd[0]=CMD1_READ_UPC;
#if TEST_UPC
			drvcmd[1]=(block>>16)&0xFF;
			drvcmd[2]=(block>>8)&0xFF;
			drvcmd[3]=block&0xFF;
#endif /* TEST_UPC */ 
			response_count=8;
			flags_cmd_out=f_putcmd|f_ResponseStatus|f_obey_p_check;
		}
		else if (fam0L_drive)
		{
			drvcmd[0]=CMD0_READ_UPC;
#if TEST_UPC
			drvcmd[2]=(block>>16)&0xFF;
			drvcmd[3]=(block>>8)&0xFF;
			drvcmd[4]=block&0xFF;
#endif /* TEST_UPC */ 
			response_count=0;
			flags_cmd_out=f_putcmd|f_lopsta|f_getsta|f_ResponseStatus|f_obey_p_check|f_bit1;
		}
		else if (fam2_drive)
		{
			return (-1);
		}
		else if (famT_drive)
		{
			return (-1);
		}
		i=cmd_out();
		if (i<0)
		{
			msg(DBG_000,"cc_ReadUPC cmd_out: err %d\n", i);
			return (i);
		}
		if (fam0L_drive)
		{
			response_count=16;
			if (famL_drive) flags_cmd_out=f_putcmd;
			i=cc_ReadPacket();
			if (i<0)
			{
				msg(DBG_000,"cc_ReadUPC ReadPacket: err %d\n", i);
				return (i);
			}
		}
#if TEST_UPC
		checksum=0;
#endif /* TEST_UPC */ 
		for (i=0;i<(fam1_drive?8:16);i++)
		{
#if TEST_UPC
			checksum |= infobuf[i];
#endif /* TEST_UPC */ 
			sprintf(&msgbuf[i*3], " %02X", infobuf[i]);
		}
		msgbuf[i*3]=0;
		msg(DBG_UPC,"UPC info:%s\n", msgbuf);
#if TEST_UPC
		if ((checksum&0x7F)!=0) break;
	}
#endif /* TEST_UPC */ 
	current_drive->UPC_ctl_adr=0;
	if (fam1_drive) i=0;
	else i=2;
	if ((infobuf[i]&0x80)!=0)
	{
		convert_UPC(&infobuf[i]);
		current_drive->UPC_ctl_adr = (current_drive->TocEnt_ctl_adr & 0xF0) | 0x02;
	}
	for (i=0;i<7;i++)
		sprintf(&msgbuf[i*3], " %02X", current_drive->UPC_buf[i]);
	sprintf(&msgbuf[i*3], " (%02X)", current_drive->UPC_ctl_adr);
	msgbuf[i*3+5]=0;
	msg(DBG_UPC,"UPC code:%s\n", msgbuf);
	current_drive->diskstate_flags |= upc_bit;
	return (0);
}

static int sbpcd_get_mcn(struct cdrom_device_info *cdi, struct cdrom_mcn *mcn)
{
	int i;
	unsigned char *mcnp = mcn->medium_catalog_number;
	unsigned char *resp;

	current_drive->diskstate_flags &= ~upc_bit;
	clr_cmdbuf();
	if (fam1_drive)
	{
		drvcmd[0]=CMD1_READ_UPC;
		response_count=8;
		flags_cmd_out=f_putcmd|f_ResponseStatus|f_obey_p_check;
	}
	else if (fam0L_drive)
	{
		drvcmd[0]=CMD0_READ_UPC;
		response_count=0;
		flags_cmd_out=f_putcmd|f_lopsta|f_getsta|f_ResponseStatus|f_obey_p_check|f_bit1;
	}
	else if (fam2_drive)
	{
		return (-1);
	}
	else if (famT_drive)
	{
		return (-1);
	}
	i=cmd_out();
	if (i<0)
	{
		msg(DBG_000,"cc_ReadUPC cmd_out: err %d\n", i);
		return (i);
	}
	if (fam0L_drive)
	{
		response_count=16;
		if (famL_drive) flags_cmd_out=f_putcmd;
		i=cc_ReadPacket();
		if (i<0)
		{
			msg(DBG_000,"cc_ReadUPC ReadPacket: err %d\n", i);
			return (i);
		}
	}
	current_drive->UPC_ctl_adr=0;
	if (fam1_drive) i=0;
	else i=2;

	resp = infobuf + i;
	if (*resp++ == 0x80) {
		/* packed bcd to single ASCII digits */
		*mcnp++ = (*resp >> 4)     + '0';
		*mcnp++ = (*resp++ & 0x0f) + '0';
		*mcnp++ = (*resp >> 4)     + '0';
		*mcnp++ = (*resp++ & 0x0f) + '0';
		*mcnp++ = (*resp >> 4)     + '0';
		*mcnp++ = (*resp++ & 0x0f) + '0';
		*mcnp++ = (*resp >> 4)     + '0';
		*mcnp++ = (*resp++ & 0x0f) + '0';
		*mcnp++ = (*resp >> 4)     + '0';
		*mcnp++ = (*resp++ & 0x0f) + '0';
		*mcnp++ = (*resp >> 4)     + '0';
		*mcnp++ = (*resp++ & 0x0f) + '0';
		*mcnp++ = (*resp >> 4)     + '0';
	}
	*mcnp = '\0';

	current_drive->diskstate_flags |= upc_bit;
	return (0);
}

/*==========================================================================*/
static int cc_CheckMultiSession(void)
{
	int i;
	
	if (fam2_drive) return (0);
	current_drive->f_multisession=0;
	current_drive->lba_multi=0;
	if (fam0_drive) return (0);
	clr_cmdbuf();
	if (fam1_drive)
	{
		drvcmd[0]=CMD1_MULTISESS;
		response_count=6;
		flags_cmd_out=f_putcmd|f_ResponseStatus|f_obey_p_check;
		i=cmd_out();
		if (i<0) return (i);
		if ((infobuf[0]&0x80)!=0)
		{
			current_drive->f_multisession=1;
			current_drive->lba_multi=msf2blk(make32(make16(0,infobuf[1]),
							make16(infobuf[2],infobuf[3])));
		}
	}
	else if (famLV_drive)
	{
		drvcmd[0]=CMDL_MULTISESS;
		drvcmd[1]=3;
		drvcmd[2]=1;
		response_count=8;
		flags_cmd_out=f_putcmd;
		i=cmd_out();
		if (i<0) return (i);
		current_drive->lba_multi=msf2blk(make32(make16(0,infobuf[5]),
						make16(infobuf[6],infobuf[7])));
	}
	else if (famT_drive)
	{
		response_count=12;
		drvcmd[0]=CMDT_DISKINFO;
		drvcmd[1]=0x02;
		drvcmd[6]=0;
		drvcmd[8]=response_count;
		drvcmd[9]=0x40;
		i=cmd_out();
		if (i<0) return (i);
		if (i<response_count) return (-100-i);
		current_drive->first_session=infobuf[2];
		current_drive->last_session=infobuf[3];
		current_drive->track_of_last_session=infobuf[6];
		if (current_drive->first_session!=current_drive->last_session)
		{
			current_drive->f_multisession=1;
			current_drive->lba_multi=msf2blk(make32(make16(0,infobuf[9]),make16(infobuf[10],infobuf[11])));
		}
	}
	for (i=0;i<response_count;i++)
		sprintf(&msgbuf[i*3], " %02X", infobuf[i]);
	msgbuf[i*3]=0;
	msg(DBG_MUL,"MultiSession Info:%s (%d)\n", msgbuf, current_drive->lba_multi);
	if (current_drive->lba_multi>200)
	{
		current_drive->f_multisession=1;
		msg(DBG_MUL,"MultiSession base: %06X\n", current_drive->lba_multi);
	}
	return (0);
}
/*==========================================================================*/
#ifdef FUTURE
static int cc_SubChanInfo(int frame, int count, u_char *buffer)
	/* "frame" is a RED BOOK (msf-bin) address */
{
	int i;
	
	if (fam0LV_drive) return (-ENOSYS); /* drive firmware lacks it */
	if (famT_drive)
	{
		return (-1);
	}
#if 0
	if (current_drive->audio_state!=audio_playing) return (-ENODATA);
#endif
	clr_cmdbuf();
	drvcmd[0]=CMD1_SUBCHANINF;
	drvcmd[1]=(frame>>16)&0xFF;
	drvcmd[2]=(frame>>8)&0xFF;
	drvcmd[3]=frame&0xFF;
	drvcmd[5]=(count>>8)&0xFF;
	drvcmd[6]=count&0xFF;
	flags_cmd_out=f_putcmd|f_respo2|f_ResponseStatus|f_obey_p_check;
	cmd_type=READ_SC;
	current_drive->frame_size=CD_FRAMESIZE_SUB;
	i=cmd_out(); /* which buffer to use? */
	return (i);
}
#endif /* FUTURE */ 
/*==========================================================================*/
static void __init check_datarate(void)
{
	int i=0;
	
	msg(DBG_IOX,"check_datarate entered.\n");
	datarate=0;
#if TEST_STI
	for (i=0;i<=1000;i++) printk(".");
#endif
	/* set a timer to make (timed_out_delay!=0) after 1.1 seconds */
#if 1
	del_timer(&delay_timer);
#endif
	delay_timer.expires=jiffies+11*HZ/10;
	timed_out_delay=0;
	add_timer(&delay_timer);
#if 0
	msg(DBG_TIM,"delay timer started (11*HZ/10).\n");
#endif
	do
	{
		i=inb(CDi_status);
		datarate++;
#if 1
		if (datarate>0x6FFFFFFF) break;
#endif 
	}
	while (!timed_out_delay);
	del_timer(&delay_timer);
#if 0
	msg(DBG_TIM,"datarate: %04X\n", datarate);
#endif
	if (datarate<65536) datarate=65536;
	maxtim16=datarate*16;
	maxtim04=datarate*4;
	maxtim02=datarate*2;
	maxtim_8=datarate/32;
#if LONG_TIMING