File: sanei_scsi.c

package info (click to toggle)
sane 0.72-1.1
  • links: PTS
  • area: main
  • in suites: hamm
  • size: 3,008 kB
  • ctags: 5,180
  • sloc: ansic: 42,911; sh: 4,584; java: 1,421; makefile: 720
file content (1913 lines) | stat: -rw-r--r-- 52,597 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
/* sane - Scanner Access Now Easy.
   Copyright (C) 1996, 1997 David Mosberger-Tang
   This file is part of the SANE package.

   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 of the
   License, or (at your option) any later version.

   This program is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place - Suite 330, Boston,
   MA 02111-1307, USA.

   As a special exception, the authors of SANE give permission for
   additional uses of the libraries contained in this release of SANE.

   The exception is that, if you link a SANE library with other files
   to produce an executable, this does not by itself cause the
   resulting executable to be covered by the GNU General Public
   License.  Your use of that executable is in no way restricted on
   account of linking the SANE library code into it.

   This exception does not, however, invalidate any other reasons why
   the executable file might be covered by the GNU General Public
   License.

   If you submit changes to SANE to the maintainers to be included in
   a subsequent release, you agree by submitting the changes that
   those changes may be distributed with this exception intact.

   If you write modifications of your own for SANE, it is your choice
   whether to permit this exception to apply to your modifications.
   If you do not wish that, delete this exception notice.

   This file provides a generic SCSI interface.  */

#ifdef _AIX
#include <lalloca.h>		/* MUST come first for AIX! */
#endif

#include <sane/config.h>
#include <lalloca.h>

#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

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

#define STUBBED_INTERFACE	0
#define LINUX_INTERFACE		1
#define BSD_INTERFACE		2
#define	HPUX_INTERFACE		3
#define OPENSTEP_INTERFACE	4
#define DECUNIX_INTERFACE	5
#define SCO_OS5_INTERFACE	6
#define IRIX_INTERFACE		7
#define SOLARIS_INTERFACE	8
#define SOLARIS_SG_INTERFACE	9
#define OS2_INTERFACE		10
#define AIX_GSC_INTERFACE	11
#define DOMAINOS_INTERFACE	12

#if defined (HAVE_SCSI_SG_H)
# define USE LINUX_INTERFACE
# include <scsi/sg.h>
#elif defined (HAVE__USR_SRC_LINUX_INCLUDE_SCSI_SG_H)
# define USE LINUX_INTERFACE
# include "/usr/src/linux/include/scsi/sg.h"
#elif defined (HAVE_SYS_SCSICMD)
# define USE SCSO_OS5_INTERFACE
# include <sys/scsi.h>
# include <sys/scsicmd.h>
#elif defined (HAVE_SYS_SCSIIO_H)
# define USE BSD_INTERFACE
# include <sys/scsiio.h>
# ifdef HAVE_SCSI_H
#  include <scsi.h>
# endif
#elif defined (HAVE_BSD_DEV_SCSIREG_H)
# define USE OPENSTEP_INTERFACE
# include <bsd/dev/scsireg.h>
#elif defined (HAVE_IO_CAM_CAM_H)
# define USE DECUNIX_INTERFACE
# include <io/common/iotypes.h>
# include <io/cam/cam.h>
# include <io/cam/dec_cam.h>
# include <io/cam/uagt.h>
# include <io/cam/scsi_all.h>
#elif defined (HAVE_SYS_DSREQ_H)
# define USE IRIX_INTERFACE
# include <sys/dsreq.h>
#elif defined (HAVE_SYS_SCSI_H)
# include <sys/scsi.h>
# ifdef SCTL_READ
#  define USE HPUX_INTERFACE
# else
#  ifdef HAVE_GSCDDS_H
#   define USE AIX_GSC_INTERFACE
#   include <gscdds.h>
#  else
    /* This happens for AIX without gsc and possibly other platforms... */
#  endif
# endif
#elif defined (HAVE_OS2_H)
# define USE OS2_INTERFACE
# define INCL_DOSFILEMGR
# define INCL_DOS
# define INCL_DOSDEVICES
# define INCL_DOSDEVIOCTL
# define INCL_DOSSEMAPHORES
# define INCL_DOSMEMMGR
# include <os2.h>
# include "srb.h"
#elif defined (HAVE_SYS_SCSI_SGDEFS_H)
# define USE SOLARIS_SG_INTERFACE
# include <sys/scsi/sgdefs.h>
#elif defined (HAVE_SYS_SCSI_TARGETS_SCGIO_H)
# define USE SOLARIS_INTERFACE
# define SOL2
# include <sys/scsi/targets/scgio.h>
#elif defined (HAVE_APOLLO_SCSI_H)
# define USE DOMAINOS_INTERFACE
# include <signal.h>	/* Only used for signal name for KillDomainServer */
# include <apollo/base.h>
# include <apollo/ec2.h>
# include <apollo/error.h>
# include <apollo/ms.h>
# include <apollo/mutex.h>
# include <apollo/scsi.h>
# include <apollo/time.h>
# include "sanei_DomainOS.h"
#endif

#ifndef USE
# define USE STUBBED_INTERFACE
#endif

#include <sane/sanei_scsi.h>
#include <sane/sanei.h>

#define BACKEND_NAME	sanei_scsi
#include <sane/sanei_debug.h>

#if USE == DECUNIX_INTERFACE
static int cam_fd = -1;		/* used for SCSI CAM based interfaces */
#endif

#if USE == SOLARIS_INTERFACE
static int unit_ready (int fd);
#endif

#ifdef SG_BIG_BUFF
# define MAX_DATA	SG_BIG_BUFF
#endif

#if USE == OPENSTEP_INTERFACE
# define MAX_DATA	(120*1024)
#endif

#if USE == IRIX_INTERFACE
  /* Actually, the limit varies from 256MB to 1GB :) */
# define MAX_DATA	(8*1024*1024)
#endif

#ifndef MAX_DATA
# define MAX_DATA	(32*1024)
#endif

int sanei_scsi_max_request_size = MAX_DATA;

static struct
  {
    u_int in_use:1;		/* is this fd_info in use? */
    u_int fake_fd:1;		/* is this a fake file descriptor? */
    u_int bus, target, lun;	/* nexus info; used for some interfaces only */
    SANEI_SCSI_Sense_Handler sense_handler;
    void *sense_handler_arg;
    void *pdata;		/* platform-specific data */
  }
 *fd_info;

static u_char cdb_sizes[8] =
  {
    6, 10, 10, 12, 12, 12, 10, 10
  };
#define CDB_SIZE(opcode)	cdb_sizes[(((opcode) >> 5) & 7)]


#if USE == DOMAINOS_INTERFACE

/*
   This includes the server code.  Most of these routines are private to the
   actual server.  The only public ones are:
   sanei_DomainOS_init     Used to initialize the server
   DomainErrorCheck        A common error handling routine
 */

#include "sanei_DomainOS.c"

int ServerInitialized = 0;
pid_t ServerPID;
struct DomainServerCommon *com;
long CommandTriggerValue[2];
ec2_$ptr_t CommandAcceptedPtr[2];
long ResultTriggerValue[2];
ec2_$ptr_t ResultReadyPtr[2];
time_$clock_t Wait16S = {64, 0};		/* Delay of about 16 Seconds */


/* This function is registered as an exit function.  It's purpose is
   to make sure that the Domain SANE Server is stopped.  It tries to
   send an Exit command, and if that fails, it will send SIGQUIT to
   the server.  It will also unmap the common area before it
   returns. */
static void 
KillDomainServer (void)
{
  static boolean GotTheLock;
  static status_$t status;
  static pinteger index;

  DBG (1, "Asking Domain SANE Server to exit\n");
  /* First, try to send a command to exit */
  if (GotTheLock = mutex_$lock (&com->CommandLock, Wait16S))
    {
      /* Set the wait time to 16 Seconds (units are 4uS) */
      com->opcode = Exit;
      CommandTriggerValue[0] = ec2_$read (com->CommandAccepted) + 1;
      ec2_$advance (&com->CommandAvailable, &status);
      DomainErrorCheck (status, "Can't advance CommandAvailable EC");
      /* For this wait, we want to allow a timeout as well */
      CommandTriggerValue[1] = (ec2_$read (*CommandAcceptedPtr[1])
				+ DomainECWaitConstant;
      index = ec2_$wait_svc (CommandAcceptedPtr, CommandTriggerValue, 2,
			     &status);
      DomainErrorCheck (status, "Error waiting on Exit command acceptance EC");
      /* Release the lock */
      mutex_$unlock (&com->CommandLock);
      if (index == 1)
	DBG (1, "Domain SANE Server responded to exit request\n");
      else
	DBG (1, "Domain SANE Server did not respond to exit request\n");
    }
  else
    DBG (0, "Could not get mutex lock for killing server\n");
  if ((!GotTheLock) || (index != 1))
    {
      /* If we get here, then we never got the mutex lock, or we timed out
         waiting for an Exit command ack. */
      /* It's now time to be brutal with the server */
      DBG (1, "Sending QUIT signal to Domain SANE Server\n");
      kill (ServerPID, SIGQUIT);
    }
  /* unmap the common area */
  ms_$unmap (com, sizeof (struct DomainServerCommon), &status);
  DomainErrorCheck (status, "Error unmapping common area");
}
#endif /* USE == DOMAINOS_INTERFACE */


#if USE == OS2_INTERFACE

/* Driver info:  */
static HEV postSema = 0;    /* Event Semaphore for posting SRB completion */
static HFILE driver_handle = 0;	/* file handle for device driver */
static PVOID aspi_buf = 0;	/* Big data buffer locked by driver. */
static int aspi_ref_count = 0;	/* # of fds using ASPI */

/* Open OS2 ASPI driver.

   Output: 0 if error, which is reported.  */
static int
open_aspi (void)
{
  ULONG rc;
  ULONG ActionTaken;
  USHORT openSemaReturn;
  USHORT lockSegmentReturn;
  unsigned long cbreturn;
  unsigned long cbParam;

  if (driver_handle)
    return 1;			/* Already open. */
  rc = DosAllocMem (&aspi_buf, sanei_scsi_max_request_size,
		    OBJ_TILE | PAG_READ | PAG_WRITE | PAG_COMMIT);
  if (rc)
    {
      DBG (1, "open_aspi: can't allocate memory\n");
      return 0;
    }
  rc = DosOpen ((PSZ) "aspirou$",	/* open driver */
		&driver_handle,
		&ActionTaken,
		0,
		0,
		FILE_OPEN,
		OPEN_SHARE_DENYREADWRITE | OPEN_ACCESS_READWRITE,
		NULL);
  if (rc)
    {
      /* opening failed -> return false */
      DBG (1, "open_aspi:  opening failed.\n");
      return 0;
    }
  rc = DosCreateEventSem (NULL, &postSema,	/* create event semaphore */
			  DC_SEM_SHARED, 0);
  if (rc)
    {
      /* DosCreateEventSem failed */
      DBG (1, "open_aspi:  couldn't create semaphore.\n");
      return 0;
    }
  rc = DosDevIOCtl (driver_handle, 0x92, 0x03,	/* pass semaphore handle */
		    (void *) &postSema, sizeof (HEV),	/* to driver */
		    &cbParam, (void *) &openSemaReturn,
		    sizeof (USHORT), &cbreturn);
  if (rc || openSemaReturn)
    {
      DBG (1, "open_aspi:  couldn't set semaphore.\n");
      return 0;
    }

  /* Lock aspi_buf. */
  rc = DosDevIOCtl (driver_handle, 0x92, 0x04,	/* pass aspi_buf pointer */
		    (void *) aspi_buf, sizeof (PVOID),	/* to driver */
		    &cbParam, (void *) &lockSegmentReturn,
		    sizeof (USHORT), &cbreturn);
  if (rc || lockSegmentReturn)
    {
      /* DosDevIOCtl failed */
      DBG (1, "open_aspi:  Can't lock buffer.\n");
      return 0;
    }
  return 1;
}

/* Close driver and free everything.  */

static void
close_aspi (void)
{
  if (postSema)
    DosCloseEventSem (postSema);	/* Close event semaphore. */
  postSema = 0;
  if (driver_handle)		/* Close driver. */
    DosClose (driver_handle);
  driver_handle = 0;
  if (aspi_buf)			/* Free buffer. */
    DosFreeMem (aspi_buf);
  aspi_buf = 0;
}

#endif /* USE_OS2_INTERFACE */

SANE_Status
sanei_scsi_open (const char *dev, int *fdp,
		 SANEI_SCSI_Sense_Handler handler, void *handler_arg)
{
  u_int bus = 0, target = 0, lun = 0, fake_fd = 0;
  static int num_alloced = 0;
  char *real_dev = 0;
  void *pdata = 0;
  int fd;
#ifdef __linux__
  static int first_time = 1;
#endif

  DBG_INIT ();

#ifdef __linux__
  if (first_time)
    {
      char buf[32];
      size_t len;
      int fd;

      first_time = 0;

      fd = open ("/proc/sys/kernel/sg-big-buff", O_RDONLY);
      if (fd > 0 && (len = read (fd, buf, sizeof (buf) - 1)) > 0)
	{
	  buf[len] = '\0';
	  sanei_scsi_max_request_size = atoi (buf);
	  DBG (1, "sanei_scsi_open: sanei_scsi_max_request_size=%d bytes\n",
	       sanei_scsi_max_request_size);
	}
    }
#endif

#if USE == OS2_INTERFACE
  if (sscanf (dev, "b%dt%dl%d", &bus, &target, &lun) != 3)
    {
      DBG (1, "sanei_scsi_open: device name %s is not a valid\n",
	   strerror (errno));
      return SANE_STATUS_INVAL;
    }
  if (!open_aspi ())
    {
      /* Open driver if necessary. */
      close_aspi ();
      return SANE_STATUS_INVAL;
    }

  ++aspi_ref_count;

  /* Find fake fd. */
  for (fd = 0; fd < num_alloced; ++fd)
    if (!fd_info[fd].in_use)
      break;
  fake_fd = 1;
#elif USE == DECUNIX_INTERFACE
  {
    UAGT_CAM_SCAN cam_scan;

    if (sscanf (dev, "b%dt%dl%d", &bus, &target, &lun) != 3)
      {
	DBG (1, "sanei_scsi_open: device name %s is not a valid\n",
	     strerror (errno));
	return SANE_STATUS_INVAL;
      }

    if (cam_fd < 0)
      {
	cam_fd = open ("/dev/cam", O_RDWR);
	if (cam_fd < 0)
	  {
	    DBG (1, "sanei_scsi_open: open(/dev/cam) failed: %s\n",
		 strerror (errno));
	    return SANE_STATUS_INVAL;
	  }
      }
    cam_scan.ucs_bus = bus;
    cam_scan.ucs_target = target;
    cam_scan.ucs_lun = lun;
    if (ioctl (cam_fd, UAGT_CAM_SINGLE_SCAN, &cam_scan) < 0)
      {
	DBG (1, "sanei_scsi_open: ioctl(UAGT_CAM_SINGLE_SCAN) failed: %s\n",
	     strerror (errno));
	return SANE_STATUS_INVAL;
      }

    for (fd = 0; fd < num_alloced; ++fd)
      if (!fd_info[fd].in_use)
	break;
  }
#elif USE == DOMAINOS_INTERFACE
  {
    static int index;
    static status_$t status;
    static unsigned long length_mapped;

    DBG (1, "sanei_scsi_open: (dev='%s', int * fdp=%p, "
	 "SANEI_SCSI_Sense_Handler handler=%p)\n", dev, fdp, handler);

    /* See if the server process has started yet */
    if (!ServerInitialized)
      {
	static char *CommonAreaPath;

	/* Initialize the server */
	DBG (2, "Initializing Domain Server\n");

	/* Map the area */
	CommonAreaPath = tmpnam (NULL);
	DBG (2, "Domain Server Common area name is '%s'\n", CommonAreaPath);
	com = ms_$crmapl (CommonAreaPath, strlen (CommonAreaPath), 0,
			  sizeof (struct DomainServerCommon), ms_$cowriters,
			  &status);
	DomainErrorCheck (status, "Can't open common area");
	DBG (2, "Domain Server common area mapped\n");

	/* Initialize the eventcounts */
	ec2_$init (&com->CommandAvailable);
	ec2_$init (&com->CommandAccepted);
	ec2_$init (&com->ResultReady);
	ec2_$init (&com->ResultAccepted);
	DBG (2, "Domain Server EC's initialized\n");
	/* Initialize the mutex locks */
	mutex_$init (&com->CommandLock);
	mutex_$init (&com->ResultLock);
	DBG (2, "Domain Server MutexLock's initialized\n");

	/* Initialize pointers to ECs */
	CommandAcceptedPtr[0] = &com->CommandAccepted;
	ResultReadyPtr[0] = &com->ResultReady;
	time_$get_ec (time_$clockh_key, &CommandAcceptedPtr[1], &status);
	DomainErrorCheck (status, "Can't get time EC");
	ResultReadyPtr[1] = CommandAcceptedPtr[1];

	/* Read the ResultReady EC value, to avoid race with the server */
	ResultTriggerValue[0] = ec2_$read (com->ResultReady) + 1;

	/* Now invoke the server */
	ServerPID = fork ();
	if (!ServerPID)
	  {
	    /* I am the child, call the initialization routine */
	    sanei_DomainOS_init (CommonAreaPath);
	    /* We get here when the server is done, so we just exit. */
	    exit (EXIT_SUCCESS);
	  }

	/* The communication area is open, wait for the initial response */
	ResultTriggerValue[1] = (ec2_$read (*ResultReadyPtr[1])
				 + DomainECWaitConstant);
	index = ec2_$wait_svc (ResultReadyPtr, ResultTriggerValue, 2, &status);
	DomainErrorCheck (status, "Error waiting on initial open EC");
	if (index != 1)
	  {
	    DBG (0, "Domain SANE Server never responded on startup\n");
	    /* Send a quit signal to the server */
	    kill (ServerPID, SIGQUIT);
	    return SANE_STATUS_INVAL;
	  }
	/* Register a function to kill the server when we are done */
	assert (!atexit (KillDomainServer));
	ServerInitialized = 1;
      }

    /* Find fake fd. */
    for (fd = 0; fd < num_alloced; ++fd)
      if (!fd_info[fd].in_use)
	break;
    fake_fd = 1;

    /* Send the command open to the server */
    if (!mutex_$lock (&com->CommandLock, Wait16S))
      {
	DBG (0, "Could not obtain mutex lock for Open\n");
	return SANE_STATUS_INVAL;
      }
    com->opcode = Open;
    strcpy (com->open_path, dev);
    CommandTriggerValue[0] = ec2_$read (com->CommandAccepted) + 1;
    ec2_$advance (&com->CommandAvailable, &status);
    DomainErrorCheck (status, "Can't advance CommandAvailable EC");
    CommandTriggerValue[1] = (ec2_$read (*CommandAcceptedPtr[1])
			      + DomainECWaitConstant);
    index = ec2_$wait_svc (CommandAcceptedPtr, CommandTriggerValue, 2,
			   &status);
    DomainErrorCheck (status, "Error waiting on Open command acceptance EC");
    if (index != 1)
      {
	DBG (0, "Domain SANE Server never accepted Open Command\n");
	return SANE_STATUS_INVAL;
      }

    /* Read the result */
    status = com->CommandStatus;
    DomainErrorCheck (status, "Opening device in server");

    /* Now map the data area, and make it temporary */
    DBG (2, "Mapping server's data block, name is '%s'\n", com->open_path);
    pdata = ms_$mapl (com->open_path, strlen (com->open_path), 0,
		      DomainMaxDataSize + DomainSenseSize, ms_$cowriters,
		      ms_$wr, true, &length_mapped, &status);
    DomainErrorCheck (status, "Mapping Server Data block");
    assert (length_mapped >= DomainMaxDataSize + DomainSenseSize);
    ms_$mk_temporary (pdata, &status);
    DomainErrorCheck (status, "Can't make data block temporary");

    /* Release the lock */
    mutex_$unlock (&com->CommandLock);

    if (status.all != status_$ok)
      {
	/* we have a failure, return an error code, and generate debug
           output */
	DBG (1, "sanei_scsi_open: acquire failed, Domain/OS status is %08x\n",
	     status.all);
	error_$print (status);
	return SANE_STATUS_INVAL;
      }
    else
      {
	/* device acquired, what else to do? */
	fd = com->fd;
      }
  }
#else
#if defined(SGIOCSTL) || (USE == SOLARIS_INTERFACE)
  {
    size_t len;

    /* OpenStep and the Solaris SCG driver are a bit broken in that
       the device name refers to a scsi _bus_, not an individual scsi
       device.  Hence, SANE has to fudge with the device name so we
       know which target to connect to.  For this purpose, we use the
       last character in the device name as the target index.  'a' is
       target 0, 'b', target 1, and so on... */

    len = strlen (dev);
    if (len <= 1)
      {
	DBG (1, "sanei_scsi_open: devicename `%s' too short\n", dev);
	return SANE_STATUS_INVAL;
      }

    real_dev = strdup (dev);
    real_dev[len - 1] = '\0';

    target = dev[len - 1] - 'a';
    if (target > 7)
      {
	DBG (1, "sanei_scsi_open: `%c' is not a valid target id\n",
	     dev[len - 1]);
	return SANE_STATUS_INVAL;
      }
    dev = real_dev;
  }
#endif /* defined(SGIOCSTL) || (USE == SOLARIS_INTERFACE) */

  fd = open (dev, O_RDWR | O_EXCL);
  if (fd < 0)
    {
      DBG (1, "sanei_scsi_open: open() failed: %s\n", strerror (errno));
      return SANE_STATUS_INVAL;
    }

  if (real_dev)
    free (real_dev);

#ifdef SG_SET_TIMEOUT
  /* Set large timeout since some scanners are slow but do not
     disconnect... ;-( */
  {
    int timeout;
    timeout = 10 * 60 * HZ;	/* how about 10 minutes? ;-) */
    ioctl (fd, SG_SET_TIMEOUT, &timeout);
  }
#endif

#ifdef SGIOCSTL
  {
    struct scsi_adr sa;

    sa.sa_target = target;
    sa.sa_lun = 0;
    if (ioctl (fd, SGIOCSTL, &sa) == -1)
      {
	DBG (1, "sanei_scsi_open: failed to attach to target: %u (%s)\n",
	     sa.sa_target, strerror (errno));
	return SANE_STATUS_INVAL;
      }
  }
#endif /* SGIOCSTL */
#endif /* !DECUNIX_INTERFACE */

  if (fd >= num_alloced)
    {
      size_t new_size, old_size;

      old_size = num_alloced * sizeof (fd_info[0]);
      num_alloced = fd + 8;
      new_size = num_alloced * sizeof (fd_info[0]);
      if (fd_info)
	fd_info = realloc (fd_info, new_size);
      else
	fd_info = malloc (new_size);
      memset ((char *) fd_info + old_size, 0, new_size - old_size);
      if (!fd_info)
	{
	  if (!fake_fd)
	    close (fd);
	  return SANE_STATUS_NO_MEM;
	}
    }
  fd_info[fd].in_use = 1;
  fd_info[fd].sense_handler = handler;
  fd_info[fd].sense_handler_arg = handler_arg;
  fd_info[fd].fake_fd = fake_fd;
  fd_info[fd].bus = bus;
  fd_info[fd].target = target;
  fd_info[fd].lun = lun;
  fd_info[fd].pdata = pdata;

#if USE == SOLARIS_INTERFACE
  /* verify that the device really exists: */
  if (!unit_ready (fd))
    {
      sanei_scsi_close (fd);
      return SANE_STATUS_INVAL;
    }
#endif

  if (fdp)
    *fdp = fd;

  return SANE_STATUS_GOOD;
}

void
sanei_scsi_close (int fd)
{
  fd_info[fd].in_use = 0;
  fd_info[fd].sense_handler = 0;
  fd_info[fd].sense_handler_arg = 0;
  if (!fd_info[fd].fake_fd)
    close (fd);

#if USE == DOMAINOS_INTERFACE
  {
    static int index;
    static status_$t status;

    DBG (1, "sanei_scsi_close:  fd=%d\n", fd);

    /* Send the command to the server */
    if (!mutex_$lock (&com->CommandLock, Wait16S))
      {
	DBG (0, "Could not obtain mutex lock for Close command\n");
      }
    else
      {
	com->opcode = Close;
	com->fd = fd;
	CommandTriggerValue[0] = ec2_$read (com->CommandAccepted) + 1;
	ec2_$advance (&com->CommandAvailable, &status);
	DomainErrorCheck (status, "Can't advance CommandAvailable EC");
	CommandTriggerValue[1] = (ec2_$read (*CommandAcceptedPtr[1])
				  + DomainECWaitConstant);
	index = ec2_$wait_svc (CommandAcceptedPtr, CommandTriggerValue, 2,
			       &status);
	DomainErrorCheck (status,
			  "Error waiting on Close command acceptance EC");
	if (index != 1)
	  {
	    DBG (0, "Domain SANE Server never accepted Close Command\n");
	  }

	/* Read the result */
	status = com->CommandStatus;
	/* Release the lock */
	mutex_$unlock (&com->CommandLock);
      }

    /* Unmap the data area */
    ms_$unmap (fd_info[com->fd].pdata, DomainMaxDataSize + DomainSenseSize,
	       &status);
    DomainErrorCheck (status, "Error unmapping device data area");
  }
#endif /* USE == DOMAINOS_INTERFACE */

#if USE == OS2_INTERFACE
  if (--aspi_ref_count <= 0)
    close_aspi ();
#endif /* USE == OS2_INTERFACE */
}


#if USE == DOMAINOS_INTERFACE
#define WE_HAVE_ASYNC_SCSI

void
sanei_scsi_req_flush_all (void)
{
  status_$t status;

  DBG (1, "sanei_scsi_req_flush_all: ()\n");
  /* I have never seen this called, and I'm not sure what to do with it,
     so I guarantee that it will generate a fault, and I can add support
     for it.  */
  assert (1 == 0);
}


SANE_Status
sanei_scsi_req_enter (int fd, const void *src, size_t src_size,
		      void *dst, size_t * dst_size, void **idp)
{
  static int index;
  static SANE_Status sane_status;
  static status_$t status;
  static scsi_$status_t SCSIStatus;
  static void *buf_ptr;

  if (dst_size)
    DBG (1, "sanei_scsi_req_enter: (fd=%x, src=%p, src_size=%x, "
	 "dst=%p, dst_size=%x, *idp=%p)\n",
	 fd, src, src_size, dst, *dst_size, idp);
  else
    DBG (1, "sanei_scsi_req_enter: (fd=%x, src=%p, src_size=%x, "
	 "dst=%p, dst_size=NULL, *idp=%p)\n", fd, src, src_size, dst, idp);

  /* Lock the command structure */
  if (!mutex_$lock (&com->CommandLock, mutex_$wait_forever))
    {
      DBG (0, "Could not obtain mutex lock for Enter Command\n");
      return SANE_STATUS_INVAL;
    }

  /* Fill in the command structure */
  com->opcode = Enter;
  com->fd = fd;
  com->cdb_size = CDB_SIZE (*(u_char *) src);
  if (dst_size)
    com->dst_size = *dst_size;
  memcpy (&com->cdb, src, com->cdb_size);

  /* figure out if this is a read or a write */
  if (dst_size && *dst_size)
    {
      /* dest buffer specified, must be a read */
      assert (com->cdb_size == src_size);
      com->direction = scsi_read;
      buf_ptr = dst;
      com->buf_size = *dst_size;
    }
  else
    {
      /* no dest buffer, must be a write */
      assert (com->cdb_size <= src_size);
      com->direction = scsi_write;
      buf_ptr = (char *) src + com->cdb_size;
      com->buf_size = src_size - com->cdb_size;
      if (com->buf_size)
	memcpy (fd_info[fd].pdata, buf_ptr, com->buf_size);
    }

  CommandTriggerValue[0] = ec2_$read (com->CommandAccepted) + 1;
  ec2_$advance (&com->CommandAvailable, &status);
  DomainErrorCheck (status, "Can't advance CommandAvailable EC");
  CommandTriggerValue[1] = (ec2_$read (*CommandAcceptedPtr[1])
			    + DomainECWaitConstant);
  index = ec2_$wait_svc (CommandAcceptedPtr, CommandTriggerValue, 2, &status);
  DomainErrorCheck (status, "Error waiting on Enter command acceptance EC");
  if (index != 1)
    {
      DBG (0, "Domain SANE Server never accepted Enter Command\n");
      return SANE_STATUS_INVAL;
    }

  /* Read the result */
  status = com->CommandStatus;
  SCSIStatus = com->SCSIStatus;

  /* Release the lock */
  mutex_$unlock (&com->CommandLock);

  /* Now decode the return status */
  if (status.all)
    DBG (1, "Server returned status %08x from Enter command\n", status.all);
  switch (status.all)
    {
    case status_$ok:
      sane_status = SANE_STATUS_GOOD;
      break;
    case scsi_$dma_underrun:
      sane_status = SANE_STATUS_IO_ERROR;
      /* This error is generated by the HP and UMAX backends.  They
         ask for too much data.  For now, the error is ignored :-( */
      sane_status = SANE_STATUS_GOOD;
      break;
    case scsi_$operation_timeout:
      sane_status = SANE_STATUS_DEVICE_BUSY;
      break;
    case scsi_$hdwr_failure:	/* received when both scanners were active */
      sane_status = SANE_STATUS_IO_ERROR;
      break;
    case (status_$ok | 0x80000000):
      /* Special - no Domain/OS error, but fail bit set means to check
         SCSI operation status. */
      DBG (1, "Server returned SCSI status of %08x\n", SCSIStatus);
      switch (SCSIStatus)
	{
	case scsi_check_condition:
	  /* Call the sense handler, if defined */
	  if (fd_info[com->fd].sense_handler)
	    fd_info[com->fd].sense_handler (fd, ((u_char *) (fd_info[fd].pdata)) + DomainMaxDataSize, fd_info[com->fd].sense_handler_arg);
	  sane_status = SANE_STATUS_IO_ERROR;
	  break;
	case scsi_busy:
	  sane_status = SANE_STATUS_DEVICE_BUSY;
	  break;
	default:
	  DBG (0, "Error - Unrecognized SCSI status %08x returned from Enter command\n", SCSIStatus);
	  sane_status = SANE_STATUS_IO_ERROR;
	  exit (EXIT_FAILURE);
	}
      break;
    default:
      DBG (0, "Unmapped status (%08x) returned from Domain SANE Server\n", status.all);
      sane_status = SANE_STATUS_IO_ERROR;
    }

  /* If a read, copy the data into the destination buffer */
  if ((com->direction == scsi_read) && com->dst_size)
    memcpy (buf_ptr, fd_info[fd].pdata, com->dst_size);

  return sane_status;
}


SANE_Status
sanei_scsi_req_wait (void *id)
{
  SANE_Status status;
  DBG (1, "sanei_scsi_req_wait: (id=%p)\n", id);
  status = SANE_STATUS_GOOD;
  return status;
}


SANE_Status
sanei_scsi_cmd (int fd, const void *src, size_t src_size,
		void *dst, size_t * dst_size)
{
  SANE_Status status;
  void *id;

  DBG (1, "sanei_scsi_cmd: (fd=%d)\n", fd);
  status = sanei_scsi_req_enter (fd, src, src_size, dst, dst_size, &id);
  if (status != SANE_STATUS_GOOD)
    return status;
  return sanei_scsi_req_wait (id);
}

#endif /* USE == DOMAINOS_INTERFACE */


#if USE == LINUX_INTERFACE

#include <signal.h>
#include <sys/time.h>

#define WE_HAVE_ASYNC_SCSI

static int pack_id = 0;
static int need_init = 1;
static sigset_t all_signals;

#define ATOMIC(s)					\
do							\
  {							\
    sigset_t old_mask;					\
							\
    if (need_init)					\
      {							\
	need_init = 0;					\
	sigfillset (&all_signals);			\
      }							\
    sigprocmask (SIG_BLOCK, &all_signals, &old_mask);	\
    {s;}						\
    sigprocmask (SIG_SETMASK, &old_mask, 0);		\
  }							\
while (0)

static struct req
  {
    int fd;
    u_int running:1, done:1;
    SANE_Status status;
    size_t *dst_len;
    void *dst;
    struct
      {
	struct sg_header hdr;
	u_int8_t data[SG_BIG_BUFF];
      }
    cdb;
    struct req *next;
  }
*qhead, *qtail, *free_list;

static void
issue (struct req *req)
{
  ssize_t nwritten;

  if (!req || req->running)
    return;

  DBG (4, "sanei_scsi.issue: %p\n", req);

  ATOMIC (req->running = 1;
	  nwritten = write (req->fd, &req->cdb, req->cdb.hdr.pack_len));

  if (nwritten != req->cdb.hdr.pack_len)
    {
      DBG (1, "sanei_scsi.issue: bad write (errno=%s)\n",
	   strerror (errno));
      req->done = 1;
      if (errno == ENOMEM)
	{
	  DBG (1, "sanei_scsi.issue: SG_BIG_BUF inconsistency?  "
	       "Check file PROBLEMS.\n");
	  req->status = SANE_STATUS_NO_MEM;
	}
      else
	req->status = SANE_STATUS_IO_ERROR;
    }
}

void
sanei_scsi_req_flush_all (void)
{
  struct req *req, *next_req;

  for (req = qhead; req; req = next_req)
    {
      if (req->running && !req->done)
	read (req->fd, &req->cdb, req->cdb.hdr.reply_len);
      next_req = req->next;

      req->next = free_list;
      free_list = req;
    }
  qhead = qtail = 0;
}

SANE_Status
sanei_scsi_req_enter (int fd, const void *src, size_t src_size,
		      void *dst, size_t * dst_size, void **idp)
{
  struct req *req;

  if (free_list)
    {
      req = free_list;
      free_list = req->next;
      req->next = 0;
    }
  else
    {
      req = malloc (sizeof (*req));
      if (!req)
	{
	  DBG (1, "sanei_scsi_req_enter: failed to malloc %lu bytes\n",
	       (u_long) sizeof (*req));
	  return SANE_STATUS_NO_MEM;
	}
    }
  req->fd = fd;
  req->running = 0;
  req->done = 0;
  req->status = SANE_STATUS_GOOD;
  req->dst = dst;
  req->dst_len = dst_size;
  memset (&req->cdb.hdr, 0, sizeof (req->cdb.hdr));
  req->cdb.hdr.pack_id = pack_id++;
  req->cdb.hdr.pack_len = src_size + sizeof (req->cdb.hdr);
  req->cdb.hdr.reply_len = (dst_size ? *dst_size : 0) + sizeof (req->cdb.hdr);
  memcpy (&req->cdb.data, src, src_size);

  req->next = 0;
  ATOMIC (if (qtail)
	  {
	  qtail->next = req;
	  qtail = req;
	  }
	  else
	  qhead = qtail = req);

  DBG (4, "scsi_req_enter: entered %p\n", req);

  *idp = req;
  return SANE_STATUS_GOOD;
}

SANE_Status
sanei_scsi_req_wait (void *id)
{
  SANE_Status status = SANE_STATUS_GOOD;
  struct req *req = id;
  ssize_t nread = 0;

  assert (req == qhead);	/* we don't support out-of-order completion */

  DBG (4, "sanei_scsi_req_wait: waiting for %p\n", req);

  issue (req);			/* ensure the command is running */
  if (req->done)
    {
      issue (req->next);	/* issue next command, if any */
      status = req->status;
    }
  else
    {
      fd_set readable;

      /* wait for command completion: */
      FD_ZERO (&readable);
      FD_SET (req->fd, &readable);
      select (req->fd + 1, &readable, 0, 0, 0);

      /* now atomically read result and set DONE: */
      ATOMIC (nread = read (req->fd, &req->cdb, req->cdb.hdr.reply_len);
	      req->done = 1);

      /* Now issue next command asap, if any.  We can't do this
         earlier since the Linux kernel has space for just one big
         buffer.  */
      issue (req->next);

      DBG (4, "sanei_scsi_req_wait: read %ld bytes\n", (long) nread);

      if (nread < 0)
	{
	  DBG (1, "sanei_scsi_req_wait: read returned %ld (errno=%d)\n",
	       (long) nread, errno);
	  status = SANE_STATUS_IO_ERROR;
	}
      else
	{
	  nread -= sizeof (req->cdb.hdr);

	  /* check for errors, but let the sense_handler decide.... */
	  if ((req->cdb.hdr.result != 0) ||
	      ((req->cdb.hdr.sense_buffer[0] & 0x7f) != 0))
	    {
 	      SANEI_SCSI_Sense_Handler handler
		= fd_info[req->fd].sense_handler;
 	      void *arg = fd_info[req->fd].sense_handler_arg;
 
	      DBG(1, "sanei_scsi_req_wait: SCSI command complained: %s\n",
 		  strerror (req->cdb.hdr.result));
 
 	      if (req->cdb.hdr.result == EBUSY)
 		status = SANE_STATUS_DEVICE_BUSY;
 	      else if (handler)
		/* sense handler should return SANE_STATUS_GOOD if it
		   decided all was ok afterall */
 		status = (*handler) (req->fd, req->cdb.hdr.sense_buffer, arg);
 	      else
 		status = SANE_STATUS_IO_ERROR;
 	    }

	  /* if we are ok so far, copy over the return data */
	  if (status == SANE_STATUS_GOOD) 
	    {
	      if (req->dst)
		memcpy (req->dst, req->cdb.data, nread);

	      if (req->dst_len)
		*req->dst_len = nread;
	    }
	}
    }

  /* dequeue and release processed request: */
  ATOMIC (qhead = qhead->next;
	  if (!qhead)
	  qtail = 0;
	  req->next = free_list;
	  free_list = req);
  return status;
}

SANE_Status
sanei_scsi_cmd (int fd, const void *src, size_t src_size,
		void *dst, size_t * dst_size)
{
  SANE_Status status;
  void *id;

  status = sanei_scsi_req_enter (fd, src, src_size, dst, dst_size, &id);
  if (status != SANE_STATUS_GOOD)
    return status;
  return sanei_scsi_req_wait (id);
}

#endif /* USE == LINUX_INTERFACE */


#if USE == BSD_INTERFACE

#ifndef HAVE_SCSIREQ_ENTER
static int
scsireq_enter (int fd, scsireq_t * hdr)
{
  return ioctl (fd, SCIOCCOMMAND, hdr);
}
#endif /* !HAVE_SCSIREQ_ENTER */

SANE_Status
sanei_scsi_cmd (int fd, const void *src, size_t src_size,
		void *dst, size_t * dst_size)
{
  size_t cdb_size;
  scsireq_t hdr;
  int result;

  cdb_size = CDB_SIZE (*(u_char *) src);

  memset (&hdr, 0, sizeof (hdr));
  memcpy (hdr.cmd, src, cdb_size);
  if (dst_size && *dst_size)
    {
      assert (cdb_size == src_size);
      hdr.flags = SCCMD_READ;
      hdr.databuf = dst;
      hdr.datalen = *dst_size;
    }
  else
    {
      assert (cdb_size <= src_size);
      hdr.flags = SCCMD_WRITE;
      hdr.databuf = (char *) src + cdb_size;
      hdr.datalen = src_size;
    }
  hdr.timeout = 60000;		/* 1 minute timeout */
  hdr.cmdlen = cdb_size;
  hdr.senselen = sizeof (hdr.sense);

  result = scsireq_enter (fd, &hdr);
  if (result < 0)
    {
      DBG (1, "sanei_scsi_cmd: scsi_reqenter() failed: %s\n",
	   strerror (errno));
      return SANE_STATUS_IO_ERROR;
    }
  if (hdr.retsts != SCCMD_OK)
    {
      SANEI_SCSI_Sense_Handler handler;

      DBG (1, "sanei_scsi_cmd: scsi returned with status %d\n", hdr.retsts);
      switch (hdr.retsts)
	{
	case SCCMD_TIMEOUT:
	case SCCMD_BUSY:
	  return SANE_STATUS_DEVICE_BUSY;

	case SCCMD_SENSE:
	  handler = fd_info[fd].sense_handler;
	  if (handler)
	    return (*handler) (fd, &hdr.sense[0],
			       fd_info[fd].sense_handler_arg);
	  /* fall through */
	default:
	  return SANE_STATUS_IO_ERROR;
	}
    }

  if (dst_size)
    *dst_size = hdr.datalen_used;

  return SANE_STATUS_GOOD;
}
#endif /* USE == BSD_INTERFACE */


#if USE == HPUX_INTERFACE
/* XXX untested code! */
SANE_Status
sanei_scsi_cmd (int fd, const void *src, size_t src_size,
		void *dst, size_t * dst_size)
{
  struct sctl_io hdr;
  size_t cdb_size;

  cdb_size = CDB_SIZE (*(u_char *) src);

  memset (&hdr, 0, sizeof (hdr));
  memcpy (hdr.cdb, src, src_size);
  if (dst_size && *dst_size)
    {
      assert (cdb_size == src_size);
      hdr.flags = SCTL_READ;
      hdr.data = dst;
      hdr.data_length = *dst_size;
    }
  else
    {
      assert (cdb_size <= src_size);
      hdr.data = (char *) src + cdb_size;
      hdr.data_length = src_size - cdb_size;
    }
  hdr.cdb_length = cdb_size;
  hdr.max_msecs = 60000;	/* 1 minute timeout */
  if (ioctl (fd, SIOC_IO, &hdr) < 0)
    {
      DBG (1, "sanei_scsi_cmd: ioctl(SIOC_IO) failed: %s\n",
	   strerror (errno));
      return SANE_STATUS_IO_ERROR;
    }
  if (hdr.cdb_status)
    DBG (1, "sanei_scsi_cmd: SCSI completed with cdb_status=%d\n",
	 hdr.cdb_status);
  if (dst_size)
    *dst_size = hdr.data_xfer;

  if (hdr.sense_xfer > 0 && (hdr.sense[0] & 0x80) && fd_info[fd].sense_handler)
    return (*fd_info[fd].sense_handler) (fd, hdr.sense,
					 fd_info[fd].sense_handler_arg);
  return SANE_STATUS_GOOD;
}
#endif /* USE == HPUX_INTERFACE */


#if USE == OPENSTEP_INTERFACE
SANE_Status
sanei_scsi_cmd (int fd, const void *src, size_t src_size,
		void *dst, size_t * dst_size)
{
  struct scsi_req hdr;
  size_t cdb_size;

  cdb_size = CDB_SIZE (*(u_char *) src);

  memset (&hdr, 0, sizeof (hdr));
  memcpy (&hdr.sr_cdb, src, cdb_size);
  if (dst_size && *dst_size)
    {
      assert (cdb_size == src_size);
      hdr.sr_dma_dir = SR_DMA_RD;
      hdr.sr_addr = dst;
      hdr.sr_dma_max = *dst_size;
    }
  else
    {
      assert (cdb_size <= src_size);
      hdr.sr_dma_dir = SR_DMA_WR;
      hdr.sr_addr = (char *) src + cdb_size;
      hdr.sr_dma_max = src_size - cdb_size;
    }
  hdr.sr_ioto = 60;		/* I/O timeout in seconds */

  if (ioctl (fd, SGIOCREQ, &hdr) == -1)
    {
      DBG (1, "sanei_scsi_cmd: ioctl(SGIOCREQ) failed: %s\n",
	   strerror (errno));
      return SANE_STATUS_IO_ERROR;
    }
  if (hdr.sr_io_status != 1)
    DBG (1, "sanei_scsi_cmd: SGIOCREQ completed with sr_io_status=%d\n",
	 hdr.sr_io_status);
  if (hdr.sr_scsi_status == SR_IOST_CHKSV && fd_info[fd].sense_handler)
    return (*fd_info[fd].sense_handler) (fd, (u_char *) & hdr.sr_esense,
					 fd_info[fd].sense_handler_arg);
  if (dst_size)
    *dst_size = hdr.sr_dma_xfr;
  return SANE_STATUS_GOOD;
}
#endif /* USE == OPENSTEP_INTERFACE */


#if USE == DECUNIX_INTERFACE
SANE_Status
sanei_scsi_cmd (int fd, const void *src, size_t src_size,
		void *dst, size_t * dst_size)
{
  u_char sense[64];
  UAGT_CAM_CCB hdr;
  CCB_SCSIIO ccb;
  size_t cdb_size;

  cdb_size = CDB_SIZE (*(u_char *) src);

  memset (ccb, 0, sizeof (ccb));
  ccb.cam_ch.my_addr = (CCB_HEADER *) & ccb;
  ccb.cam_ch.cam_ccb_len = sizeof (ccb);
  ccb.cam_ch.cam_func_code = XPT_SCSI_IO;
  ccb.cam_ch.cam_path_id = fd_info[fd].bus;
  ccb.cam_ch.cam_target_id = fd_info[fd].target;
  ccb.cam_ch.cam_target_lun = fd_info[fd].lun;
  ccb.cam_ch.cam_flags = 0;

  if (dst_size && *dst_size)
    {
      assert (cdb_size == src_size);
      ccb.cam_ch.cam_flags |= CAM_DIR_IN;
      ccb.cam_data_ptr = (u_char *) dst;
      ccb.cam_dxfer_len = *dst_size;
    }
  else
    {
      assert (cdb_size <= src_size);
      if (cdb_size == src_size)
	ccb.cam_ch.cam_flags |= CAM_DIR_NONE;
      else
	ccb.cam_ch.cam_flags |= CAM_DIR_OUT;
      ccb.cam_data_ptr = (u_char *) src + cdb_size;
      ccb.cam_dxfer_len = src_size - cdb_size;
    }
  ccb.cam_timeout = 60;		/* set timeout in seconds */
  ccb.cam_cdb_len = cdb_size;
  memcpy (&ccb.cam_cdb_io.cam_cdb_bytes[0], src, cdb_size);

  memset (&hdr, 0, sizeof (hdr));
  hdr.uagt_ccb = (CCB_HEADER *) & ccb;
  hdr.uagt_buffer = ccb.cam_data_ptr;
  hdr.uagt_buflen = ccb.cam_dxfer_len;
  hdr.uagt_snsbuf = sense;
  hdr.uagt_snslen = sizeof (sense);
  hdr.uagt_cdb = 0;		/* indicate that CDB is in CCB */
  hdr.uagt_cdblen = 0;

  if (ioctl (cam_fd, UAGT_CAM_IO, &hdr) < 0)
    {
      DBG (1, "sanei_scsi_cmd: ioctl(UAGT_CAM_IO) failed: %s\n",
	   strerror (errno));
      return SANE_STATUS_IO_ERROR;
    }
  if (ccb.cam_ch.cam_status != CAM_REQ_CMP)
    {
      DBG (1, "sanei_scsi_cmd: UAGT_CAM_IO completed with cam_status=%d\n",
	   ccb.cam_ch.cam_status);

      if (ccb.cam_ch.cam_status == CAM_AUTOSNS_VALID
	  && fd_info[fd].sense_handler)
	return (*fd_info[fd].sense_handler) (fd, sense,
					     fd_info[fd].sense_handler_arg);
      else
	return SANE_STATUS_INVAL;
    }
  if (dst_size)
    *dst_size = ccb.cam_dxfer_len;
  return SANE_STATUS_GOOD;
}
#endif /* USE == DECUNIX_INTERFACE */


#if USE == SCO_OS5_INTERFACE
SANE_Status
sanei_scsi_cmd (int fd, const void *src, size_t src_size,
		void *dst, size_t * dst_size)
{
  static u_char sense_buffer[256];
  struct scsicmd2 sc2;
  struct scsicmd *sc;
  int cdb_size;
  int opcode;
  int i;

  if (fd < 0)
    return SANE_STATUS_IO_ERROR;

  memset (&sc2, 0, sizeof (sc2));
  sc = &sc2.cmd;
  sc2.sense_len = sizeof (sense_buffer);
  sc2.sense_ptr = sense_buffer;

  cdb_size = CDB_SIZE (*(u_char *) src);
  if (dst_size && *dst_size)
    {
      sc->is_write = 0;
      sc->data_ptr = dst;
      sc->data_len = *dst_size;
    }
  else
    {
      sc->data_len = src_size - cdb_size;
      sc->data_ptr = (char *) src + cdb_size;
      sc->is_write = 1;
    }
  memcpy (sc->cdb, src, cdb_size);
  sc->cdb_len = cdb_size;

  /* Send the command down via the "pass-through" interface */
  if (ioctl (fd, SCSIUSERCMD2, &sc2) < 0)
    {
      DBG (1, "sanei_scsi_cmd: ioctl(SCSIUSERCMD2) failed: %s\n",
	   strerror (errno));
      return SANE_STATUS_IO_ERROR;
    }
  if (sc->host_sts || sc->target_sts)
    {
      DBG (1, "sanei_scsi_cmd: SCSIUSERCMD2 completed with "
	   "host_sts=%x, target_sts=%x\n", sc->host_sts, sc->target_sts);
      if (fd_info[fd].sense_handler)
	return (*fd_info[fd].sense_handler) (fd, sense_buffer,
					     fd_info[fd].sense_handler_arg);
      return SANE_STATUS_IO_ERROR;
    }
  return SANE_STATUS_GOOD;
}
#endif /* USE == SCO_OS5_INTERFACE */

#if USE == OS2_INTERFACE
/* XXX untested code! */
SANE_Status
sanei_scsi_cmd (int fd, const void *src, size_t src_size,
		void *dst, size_t * dst_size)
{
  ULONG rc;			/* Returns. */
  unsigned long cbreturn;
  unsigned long cbParam;
  SRB srb;			/* SCSI Request Block */
  ULONG count = 0;		/* For semaphore. */
  size_t cdb_size;

  memset ((char *) &srb, 0, sizeof (srb));	/* Okay, I'm paranoid. */
  cdb_size = CDB_SIZE (*(u_char *) src);	/* Size of command block. */
  srb.cmd = SRB_Command;	/* execute SCSI cmd */
  srb.ha_num = fd_info[fd].bus;	/* host adapter number */
  srb.u.cmd.target = fd_info[fd].target;	/* Target SCSI ID */
  srb.u.cmd.lun = fd_info[fd].lun;	/* Target SCSI LUN */
  srb.flags = SRB_Post;		/* posting enabled */
  if (dst_size && *dst_size)
    {
      /* Reading. */
      assert (*dst_size <= sanei_scsi_max_request_size);
      assert (cdb_size == src_size);
      srb.u.cmd.data_len = *dst_size;
      srb.flags |= SRB_Read;
    }
  else
    {
      /* Writing. */
      srb.u.cmd.data_len = src_size - cdb_size;
      assert (cdb_size <= src_size);
      assert (srb.u.cmd.data_len <= sanei_scsi_max_request_size);
      if (srb.u.cmd.data_len)
	srb.flags |= SRB_Write;
      else
	srb.flags |= SRB_NoTransfer;
      memcpy (aspi_buf, (char *) src + cdb_size, srb.u.cmd.data_len);
    }
  srb.u.cmd.sense_len = 16;	/* length of sense buffer */
  srb.u.cmd.data_ptr = NULL;	/* pointer to data buffer already registered */
  srb.u.cmd.link_ptr = NULL;	/* pointer to next SRB */
  srb.u.cmd.cdb_len = cdb_size;	/* SCSI command length */
  memcpy (&srb.u.cmd.cdb_st[0], (char *) src, cdb_size);

  /* Do the command. */
  rc = DosDevIOCtl (driver_handle, 0x92, 0x02, (void *) &srb,
		    sizeof (SRB), &cbParam,
		    (void *) &srb, sizeof (SRB), &cbreturn);

  if (rc)
    {
      DBG (1, "sanei_scsi_cmd: DosDevIOCtl failed.\n");
      return SANE_STATUS_IO_ERROR;
    }
  if (DosWaitEventSem (postSema, -1) ||		/* wait forever for sema. */
      DosResetEventSem (postSema, &count))	/* reset semaphore. */
    {
      DBG (1, "sanei_scsi_cmd:  semaphore failure.\n");
      return SANE_STATUS_IO_ERROR;
    }

  /* Get sense data if available. */
  if ((srb.status == SRB_Aborted || srb.status == SRB_Error) &&
      srb.u.cmd.target_status == SRB_CheckStatus
      && fd_info[fd].sense_handler != 0)
    {
      SANEI_SCSI_Sense_Handler s_handler = fd_info[fd].sense_handler;
      return (*s_handler) (fd, &srb.u.cmd.cdb_st[cdb_size],
			   fd_info[fd].sense_handler_arg);
    }
  if (srb.status != SRB_Done ||
      srb.u.cmd.ha_status != SRB_NoError ||
      srb.u.cmd.target_status != SRB_NoStatus)
    DBG (1, "sanei_scsi_cmd:  command 0x%02x failed.\n", srb.u.cmd.cdb_st[0]);
  if (dst_size && *dst_size)	/* Reading? */
    memcpy ((char *) dst, aspi_buf, *dst_size);
  return SANE_STATUS_GOOD;
}
#endif /* USE == OS2_INTERFACE */

#if USE == STUBBED_INTERFACE
SANE_Status
sanei_scsi_cmd (int fd, const void *src, size_t src_size,
		void *dst, size_t * dst_size)
{
  return SANE_STATUS_UNSUPPORTED;
}
#endif /* USE == STUBBED_INTERFACE */

#if USE == IRIX_INTERFACE
SANE_Status
sanei_scsi_cmd (int fd, const void *src, size_t src_size,
		void *dst, size_t * dst_size)
{
  dsreq_t scsi_req;		/* SCSI request */
  u_char sensebuf[1024],	/* Request sense buffer */
    databuf[65536];		/* Command data buffer */
  size_t cdb_size;		/* Size of SCSI command */


  cdb_size = CDB_SIZE (*(u_char *) src);

  memset (&scsi_req, 0, sizeof (scsi_req));

  if (dst != NULL)
    {
      /*
       * SCSI command returning/reading data...
       */
      scsi_req.ds_flags = DSRQ_READ | DSRQ_SENSE;
      scsi_req.ds_time = 120 * 1000;
      scsi_req.ds_cmdbuf = (caddr_t) src;
      scsi_req.ds_cmdlen = cdb_size;
      scsi_req.ds_databuf = (caddr_t) dst;
      scsi_req.ds_datalen = *dst_size;
      scsi_req.ds_sensebuf = (caddr_t) sensebuf;
      scsi_req.ds_senselen = sizeof (sensebuf);
    }
  else
    {
      /*
       * SCSI command sending/writing data...
       */
      scsi_req.ds_flags = DSRQ_WRITE | DSRQ_SENSE;
      scsi_req.ds_time = 120 * 1000;
      scsi_req.ds_cmdbuf = (caddr_t) src;
      scsi_req.ds_cmdlen = cdb_size;
      scsi_req.ds_databuf = (caddr_t) databuf;
      scsi_req.ds_datalen = src_size - cdb_size;
      scsi_req.ds_sensebuf = (caddr_t) sensebuf;
      scsi_req.ds_senselen = sizeof (sensebuf);

      /*
       * Copy data portion to local buffer to ensure 32-bit alignment...
       */

      memcpy (databuf, (u_char *) src + cdb_size, src_size - cdb_size);
    }
  if (ioctl (fd, DS_ENTER, &scsi_req) < 0)
    return SANE_STATUS_IO_ERROR;

  if (dst_size != NULL)
    *dst_size = scsi_req.ds_datasent;

  if (scsi_req.ds_status != 0)
    {
      if (scsi_req.ds_status == STA_BUSY)
	return SANE_STATUS_DEVICE_BUSY;
      else if ((sensebuf[0] & 0x80) && fd_info[fd].sense_handler)
	return (*fd_info[fd].sense_handler) (fd, sensebuf,
					     fd_info[fd].sense_handler_arg);
      else
	return SANE_STATUS_IO_ERROR;
    }
  return SANE_STATUS_GOOD;
}
#endif /* USE == IRIX_INTERFACE */

#if USE == AIX_GSC_INTERFACE
SANE_Status
sanei_scsi_cmd (int fd, const void *src, size_t src_size,
		void *dst, size_t * dst_size)
{
  scmd_t scmd;
  size_t cdb_size;
  char sense_buf[32];
  char status;

  cdb_size = CDB_SIZE (*(u_char *) src);

  memset (&scmd, 0, sizeof (scmd));
  if (dst_size && *dst_size)
    {
      assert (cdb_size == src_size);
      scmd.rw = 1;
      scmd.data_buf = dst;
      scmd.datalen = *dst_size;
    }
  else
    {
      assert (cdb_size <= src_size);
      scmd.data_buf = (char *) src + cdb_size;
      scmd.datalen = src_size - cdb_size;
    }
  scmd.cdb = (char *) src;
  scmd.cdblen = cdb_size;
  scmd.timeval = 60;		/* 1 minute timeout */
  scmd.sense_buf = sense_buf;
  scmd.senselen = sizeof (sense_buf);
  scmd.statusp = &status;
  DBG (1, "sanei_scsi_cmd: scmd.rw = %d, scmd.cdblen = %d, ",
       scmd.rw, scmd.cdblen);
  DBG (1, "scmd.cdb = {0x%x,0x%x,0x%x,0x%x,0x%x,0x%x, ...}\n",
       scmd.cdb[0], scmd.cdb[1], scmd.cdb[2],
       scmd.cdb[3], scmd.cdb[4], scmd.cdb[5]);
  if (ioctl (fd, GSC_CMD, &scmd) < 0)
    {
      DBG (1, "sanei_scsi_cmd: ioctl(SIOC_IO) failed: %s\n",
	   strerror (errno));
      return SANE_STATUS_IO_ERROR;
    }
  if (*scmd.statusp)
    DBG (1, "sanei_scsi_cmd: SCSI completed with status=%d\n", *scmd.statusp);

  DBG (1, "sanei_scsi_cmd: dst = {0x%x,0x%x,0x%x,0x%x,0x%x,0x%x, ...}\n",
       *((char *) dst + 0), *((char *) dst + 1), *((char *) dst + 2),
       *((char *) dst + 3), *((char *) dst + 4), *((char *) dst + 5));

  if (dst_size)
    *dst_size = scmd.datalen;

  if (scmd.senselen > 0
      && (scmd.sense_buf[0] & 0x80) && fd_info[fd].sense_handler)
    return (*fd_info[fd].sense_handler) (fd, (u_char *) scmd.sense_buf,
					 fd_info[fd].sense_handler_arg);
  return SANE_STATUS_GOOD;
}
#endif /* USE == AIX_GSC_INTERFACE */

#if USE == SOLARIS_SG_INTERFACE

#ifndef CCS_SENSE_LEN
#define CCS_SENSE_LEN 18
#endif

SANE_Status
sanei_scsi_cmd (int fd, const void *src, size_t src_size,
		void *dst, size_t * dst_size)
{
  struct user_scsi us;
  size_t cdb_size;
  char sensebf[CCS_SENSE_LEN];

  cdb_size = CDB_SIZE (*(u_char *) src);

  /* first put the user scsi structure together.  */
  memset (&us, 0, sizeof (us));
  us.us_cdbp = (caddr_t) src;
  us.us_cdblen = cdb_size;
  us.us_sensep = sensebf;
  us.us_senselen = CCS_SENSE_LEN;
  if (dst && dst_size && *dst_size)
    {
      us.us_bufp = (caddr_t) dst;
      us.us_buflen = *dst_size;
      us.us_flags = USER_SCSI_READ;
    }
  else
    {
      us.us_bufp = (caddr_t) src + cdb_size;
      us.us_buflen = src_size - cdb_size;
      us.us_flags = USER_SCSI_WRITE;
    }
  /* now run it */
  if (ioctl (fd, USER_SCSI, &us) < 0)
    return SANE_STATUS_IO_ERROR;
  if (dst_size)
    *dst_size -= us.us_resid;

  return SANE_STATUS_GOOD;
}
#endif /* USE == SOLARIS_SG_INTERFACE */

#if USE == SOLARIS_INTERFACE

#ifndef SC_NOT_READ
# define SC_NOT_READY		0x02
#endif

#ifndef SC_BUSY
# define SC_BUSY		0x08
#endif
#define DEF_TIMEOUT 60;		/* 1 minute */

/* Choosing one of the following DEF_SCG_FLG's SCG_DISRE_ENA allows
   the SCSI driver to disconnect/reconnect.  SCG_CMD_RETRY allows a
   retry if a retryable error occurs.

   Disallowing SCG_DISRE_ENA slows down the operation of the SCSI bus
   while the scanner is working. If you have severe problems try to
   set it to 0.

   SCG_CMD_RETRY allows the driver to retry some commands.  It should
   normally be set.  For some kinds of odd problems, it may cause the
   machine to hang for some time.  */

#define DEF_SCG_FLG	SCG_DISRE_ENA
/* #define DEF_SCG_FLG  0                               */
/* #define DEF_SCG_FLG  SCG_DISRE_ENA | SCG_CMD_RETRY   */
/* #define DEF_SCG_FLG  SCG_CMD_RETRY                   */

static int d_errs = 100;

static SANE_Status
scsi_cmd (int fd, const void *src, size_t src_size,
	  void *dst, size_t * dst_size, int probing)
{
  struct scg_cmd scmd;
  size_t cdb_size;
  SANEI_SCSI_Sense_Handler handler;

  cdb_size = CDB_SIZE (*(u_char *) src);

  memset (&scmd, 0, sizeof (scmd));
  scmd.flags = DEF_SCG_FLG | (probing ? SCG_SILENT : 0);
  if (dst && dst_size && *dst_size)
    {
      assert (cdb_size == src_size);
      scmd.flags |= SCG_RECV_DATA;
      scmd.addr = dst;
      scmd.size = *dst_size;
    }
  else
    {
      assert (cdb_size <= src_size);
      scmd.addr = (caddr_t) src + cdb_size;
      scmd.size = src_size - cdb_size;
    }
  scmd.cdb_len = cdb_size;
  scmd.sense_len = CCS_SENSE_LEN;
  scmd.target = fd_info[fd].target;
  /* use 2 second timeout when probing, 60 seconds otherwise: */
  scmd.timeout = probing ? 2 : DEF_TIMEOUT;
  memcpy (&scmd.cdb.g0_cdb.cmd, src, cdb_size);
  scmd.cdb.cmd_cdb[1] |= fd_info[fd].lun << 5;
  if (ioctl (fd, SCGIO_CMD, &scmd) < 0)
    return SANE_STATUS_IO_ERROR;
  if (dst_size)
    *dst_size = scmd.size - scmd.resid;
  if (scmd.error == 0 && scmd.errno == 0 && *(u_char *) & scmd.scb == 0)
    return SANE_STATUS_GOOD;

  if (scmd.error == SCG_TIMEOUT)
    DBG (0, "sanei_scsi_cmd %x: timeout\n", scmd.cdb.g0_cdb.cmd);
  else if (probing)
    {
      struct scsi_ext_sense *ext_sense = (struct scsi_ext_sense *) &scmd.sense;

      if (scmd.error < SCG_FATAL
	  && ((scmd.sense.code < 0x70 && scmd.sense.code != 0x04)
	    || (scmd.sense.code >= 0x70 && ext_sense->key != SC_NOT_READY)))
	return SANE_STATUS_GOOD;
    }
  else
    {
      char errbf[128];
      int i, rv, lifes;

      handler = fd_info[fd].sense_handler;
      DBG (3, "cmd=%x, error=%d:%s, bsiz=%d, stat=%x,%x,%x, slen=%d\n",
	   scmd.cdb.g0_cdb.cmd, scmd.error, strerror (scmd.errno),
	   *dst_size, scmd.u_scb.cmd_scb[0], scmd.u_scb.cmd_scb[1],
	   scmd.u_scb.cmd_scb[2], scmd.sense_count);
      *errbf = '\0';
      for (i = 0; i < scmd.sense_count; i++)
	sprintf (errbf + strlen (errbf), "%x,", scmd.u_sense.cmd_sense[i]);
      DBG (3, "sense=%s\n", errbf);

      /* test_unit_ready on a busy unit returns error = 0 or 2 with
         errno=EIO.  I've seen 0 on a CDrom without a CD, and 2 on a
         scanner just busy.

         If (SANE_DEBUG_SANEI_SCSI > 100) lifes =
         SANE_DEBUG_SANEI_SCSI - 100 use up one life for every
         scmd.error abort and dump core when no lifes left
         test_unit_ready commands are not counted.  */
      if (scmd.error)
	{
	  if (sanei_debug_sanei_scsi > 100 &&
	      scmd.cdb.g0_cdb.cmd != SC_TEST_UNIT_READY)
	    {
	      lifes = sanei_debug_sanei_scsi - ++d_errs;
	      DBG (1, "sanei_scsi_cmd: %d lifes left\n", lifes);
	      assert (lifes > 0);
	    }
	  return SANE_STATUS_IO_ERROR;
	}
      if (scmd.u_scb.cmd_scb[0] == SC_BUSY)
	return SANE_STATUS_DEVICE_BUSY;
      if (*(u_char *) & scmd.sense && handler)
	{
	  rv = (*handler) (fd, scmd.u_sense.cmd_sense,
			   fd_info[fd].sense_handler_arg);
	  DBG (2, "sanei_scsi_cmd: sense-handler returns %d\n", rv);
	  return rv;
	}
    }
  return SANE_STATUS_IO_ERROR;
}

SANE_Status
sanei_scsi_cmd (int fd, const void *src, size_t src_size,
		void *dst, size_t * dst_size)
{
  return scsi_cmd (fd, src, src_size, dst, dst_size, 0);
}

static int
unit_ready (int fd)
{
  static const u_char test_unit_ready[] =
  {0, 0, 0, 0, 0, 0};
  int status;

  status = scsi_cmd (fd, test_unit_ready, sizeof (test_unit_ready), 0, 0, 1);
  return (status == SANE_STATUS_GOOD);
}

#endif /* USE == SOLARIS_INTERFACE */

#ifndef WE_HAVE_ASYNC_SCSI

SANE_Status
sanei_scsi_req_enter (int fd, const void *src, size_t src_size,
		      void *dst, size_t * dst_size, void **idp)
{
  return sanei_scsi_cmd (fd, src, src_size, dst, dst_size);
}

SANE_Status
sanei_scsi_req_wait (void *id)
{
  return SANE_STATUS_GOOD;
}

void
sanei_scsi_req_flush_all (void)
{
}

#endif /* WE_HAVE_ASYNC_SCSI */