Imported Upstream version 1.1.11
[platform/upstream/cdrkit.git] / libusal / scsi-linux-sg.c
1 /*
2  * This file has been modified for the cdrkit suite.
3  *
4  * The behaviour and appearence of the program code below can differ to a major
5  * extent from the version distributed by the original author(s).
6  *
7  * For details, see Changelog file distributed with the cdrkit package. If you
8  * received this file from another source then ask the distributing person for
9  * a log of modifications.
10  *
11  */
12
13 /* @(#)scsi-linux-sg.c  1.86 05/11/22 Copyright 1997 J. Schilling */
14 /*
15  *      Interface for Linux generic SCSI implementation (sg).
16  *
17  *      This is the interface for the broken Linux SCSI generic driver.
18  *      This is a hack, that tries to emulate the functionality
19  *      of the usal driver.
20  *
21  *      Design flaws of the sg driver:
22  *      -       cannot see if SCSI command could not be send
23  *      -       cannot get SCSI status byte
24  *      -       cannot get real dma count of tranfer
25  *      -       cannot get number of bytes valid in auto sense data
26  *      -       to few data in auto sense (CCS/SCSI-2/SCSI-3 needs >= 18)
27  *
28  *      This code contains support for the sg driver version 2 by
29  *              H. Eißfeld & J. Schilling
30  *      Although this enhanced version has been announced to Linus and Alan,
31  *      there was no reaction at all.
32  *
33  *      About half a year later there occured a version in the official
34  *      Linux that was also called version 2. The interface of this version
35  *      looks like a playground - the enhancements from this version are
36  *      more or less useless for a portable real-world program.
37  *
38  *      With Linux 2.4 the official version of the sg driver is called 3.x
39  *      and seems to be usable again. The main problem now is the curious
40  *      interface that is provided to raise the DMA limit from 32 kB to a
41  *      more reasonable value. To do this in a reliable way, a lot of actions
42  *      are required.
43  *
44  *      Warning: you may change this source, but if you do that
45  *      you need to change the _usal_version and _usal_auth* string below.
46  *      You may not return "schily" for an SCG_AUTHOR request anymore.
47  *      Choose your name instead of "schily" and make clear that the version
48  *      string is related to a modified source.
49  *
50  *      Copyright (c) 1997 J. Schilling
51  */
52 /*
53  * This program is free software; you can redistribute it and/or modify
54  * it under the terms of the GNU General Public License version 2
55  * as published by the Free Software Foundation.
56  *
57  * This program is distributed in the hope that it will be useful,
58  * but WITHOUT ANY WARRANTY; without even the implied warranty of
59  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
60  * GNU General Public License for more details.
61  *
62  * You should have received a copy of the GNU General Public License along with
63  * this program; see the file COPYING.  If not, write to the Free Software
64  * Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
65  */
66
67 #include <linux/version.h>
68 #include <sys/types.h>
69 #include <dirent.h>
70 #include <sys/utsname.h>
71
72 #ifndef LINUX_VERSION_CODE      /* Very old kernel? */
73 #       define LINUX_VERSION_CODE 0
74 #endif
75
76 #if LINUX_VERSION_CODE >= 0x01031a /* <linux/scsi.h> introduced in 1.3.26 */
77 #if LINUX_VERSION_CODE >= 0x020000 /* <scsi/scsi.h> introduced somewhere. */
78 /* Need to fine tune the ifdef so we get the transition point right. */
79 #include <scsi/scsi.h>
80 #else
81 #include <linux/scsi.h>
82 #endif
83 #else                           /* LINUX_VERSION_CODE == 0 Very old kernel? */
84 #define __KERNEL__              /* Some Linux Include files are inconsistent */
85 #include <linux/fs.h>           /* From ancient versions, really needed? */
86 #undef __KERNEL__
87 #include "block/blk.h"          /* From ancient versions, really needed? */
88 #include "scsi/scsi.h"
89 #endif
90
91 #if     defined(HAVE_BROKEN_SCSI_SG_H) || \
92         defined(HAVE_BROKEN_SRC_SCSI_SG_H)
93 /*
94  * Be very careful in case that the Linux Kernel maintainers
95  * unexpectedly fix the bugs in the Linux Lernel include files.
96  * Only introduce the attempt for a workaround in case the include
97  * files are broken anyway.
98  */
99 #define __user
100 #endif
101 #include "scsi/sg.h"
102 #if     defined(HAVE_BROKEN_SCSI_SG_H) || \
103         defined(HAVE_BROKEN_SRC_SCSI_SG_H)
104 #undef  __user
105 #endif
106
107 #undef sense                    /* conflict in struct cdrom_generic_command */
108 #include <linux/cdrom.h>
109
110 #if     defined(CDROM_PACKET_SIZE) && defined(CDROM_SEND_PACKET)
111 #define USE_OLD_ATAPI
112 #endif
113
114 #include <glob.h>
115
116 /*
117  *      Warning: you may change this source, but if you do that
118  *      you need to change the _usal_version and _usal_auth* string below.
119  *      You may not return "schily" for an SCG_AUTHOR request anymore.
120  *      Choose your name instead of "schily" and make clear that the version
121  *      string is related to a modified source.
122  */
123 static  char    _usal_trans_version[] = "scsi-linux-sg.c-1.86"; /* The version for this transport*/
124
125 #ifndef SCSI_IOCTL_GET_BUS_NUMBER
126 #define SCSI_IOCTL_GET_BUS_NUMBER 0x5386
127 #endif
128
129 /*
130  * XXX There must be a better way than duplicating things from system include
131  * XXX files. This is stolen from /usr/src/linux/drivers/scsi/scsi.h
132  */
133 #ifndef DID_OK
134 #define DID_OK          0x00 /* NO error                                */
135 #define DID_NO_CONNECT  0x01 /* Couldn't connect before timeout period  */
136 #define DID_BUS_BUSY    0x02 /* BUS stayed busy through time out period */
137 #define DID_TIME_OUT    0x03 /* TIMED OUT for other reason              */
138 #define DID_BAD_TARGET  0x04 /* BAD target.                             */
139 #define DID_ABORT       0x05 /* Told to abort for some other reason     */
140 #define DID_PARITY      0x06 /* Parity error                            */
141 #define DID_ERROR       0x07 /* Internal error                          */
142 #define DID_RESET       0x08 /* Reset by somebody.                      */
143 #define DID_BAD_INTR    0x09 /* Got an interrupt we weren't expecting.  */
144 #endif
145
146 /*
147  *  These indicate the error that occurred, and what is available.
148  */
149 #ifndef DRIVER_BUSY
150 #define DRIVER_BUSY     0x01
151 #define DRIVER_SOFT     0x02
152 #define DRIVER_MEDIA    0x03
153 #define DRIVER_ERROR    0x04
154
155 #define DRIVER_INVALID  0x05
156 #define DRIVER_TIMEOUT  0x06
157 #define DRIVER_HARD     0x07
158 #define DRIVER_SENSE    0x08
159 #endif
160
161 /*
162  * XXX Should add extra space in buscookies and usalfiles for a "PP bus"
163  * XXX and for two or more "ATAPI busses".
164  */
165 #define MAX_SCG         1256    /* Max # of SCSI controllers */
166 #define MAX_TGT         16
167 #define MAX_LUN         8
168
169 #ifdef  USE_OLD_ATAPI
170 /*
171  * # of virtual buses (schilly_host number)
172  */
173 #define MAX_SCHILLY_HOSTS       MAX_SCG
174 typedef struct {
175         Uchar   typ:4;
176         Uchar   bus:4;
177         Uchar   host:8;
178 } ata_buscookies;
179 #endif
180
181 struct usal_local {
182         int     usalfile;               /* Used for SG_GET_BUFSIZE ioctl()*/
183         short   usalfiles[MAX_SCG][MAX_TGT][MAX_LUN];
184         char    *filenames[MAX_SCG][MAX_TGT][MAX_LUN];
185         short   buscookies[MAX_SCG];
186         int     pgbus;
187         int     pack_id;                /* Should be a random number    */
188         int     drvers;
189         short   isold;
190         short   flags;
191         long    xbufsize;
192         char    *xbuf;
193         char    *SCSIbuf;
194 #ifdef  USE_OLD_ATAPI
195         ata_buscookies  bc[MAX_SCHILLY_HOSTS];
196 #endif
197 };
198 #define usallocal(p)    ((struct usal_local *)((p)->local))
199
200 /*
201  * Flag definitions
202  */
203
204 #ifdef  SG_BIG_BUFF
205 #define MAX_DMA_LINUX   SG_BIG_BUFF     /* Defined in include/scsi/sg.h */
206 #else
207 #define MAX_DMA_LINUX   (4*1024)        /* Old Linux versions           */
208 #endif
209
210 #ifndef SG_MAX_SENSE
211 #       define  SG_MAX_SENSE    16      /* Too small for CCS / SCSI-2   */
212 #endif                                  /* But cannot be changed        */
213
214 #if     !defined(__i386) && !defined(i386) && !defined(mc68000)
215 #define MISALIGN
216 #endif
217 /*#define       MISALIGN*/
218 /*#undef        SG_GET_BUFSIZE*/
219
220
221 #ifdef  MISALIGN
222 static  int     sg_getint(int *ip);
223 #endif
224 static  int     usalo_send(SCSI *usalp);
225 #ifdef  SG_IO
226 static  int     sg_rwsend(SCSI *usalp);
227 #endif
228 static  void    sg_clearnblock(int f);
229 static  BOOL    sg_setup(SCSI *usalp, int f, int busno, int tgt, int tlun, 
230                                                                 int ataidx, char *origname);
231 static  void    sg_initdev(SCSI *usalp, int f);
232 static  int     sg_mapbus(SCSI *usalp, int busno, int ino);
233 static  BOOL    sg_mapdev(SCSI *usalp, int f, int *busp, int *tgtp, int *lunp,
234                                                                  int *chanp, int *inop, int ataidx);
235 #if defined(SG_SET_RESERVED_SIZE) && defined(SG_GET_RESERVED_SIZE)
236 static  long    sg_raisedma(SCSI *usalp, long newmax);
237 #endif
238 static  void    sg_settimeout(int f, int timeout);
239
240 int    sg_open_excl(char *device, int mode, BOOL beQuiet);
241
242 static BOOL get_max_secs(char *dirpath, int *outval);
243
244 #if     defined(USE_PG) && !defined(USE_PG_ONLY)
245 #include "scsi-linux-pg.c"
246 #endif
247 #ifdef  USE_OLD_ATAPI
248 #include "scsi-linux-ata.c"
249 #endif
250
251 BOOL check_linux_26() {
252         int gen, tmp;
253         struct utsname buf;
254         return ( 0==uname( &buf ) && sscanf(buf.release, "%d.%d", &gen, &tmp)>1 && tmp>=6);
255 }
256
257 int sg_open_excl(char *device, int mode, BOOL beQuiet)
258 {
259        int f;
260        int i=0;
261        long interval = beQuiet ? 400000 : 1000000;
262
263        f = open(device, mode|O_EXCL);
264        /* try to reopen locked/busy devices up to five times */
265        for (i = 0; (i < 5) && (f == -1 && errno == EBUSY); i++) {
266                if(!beQuiet)
267                        fprintf(stderr, "Error trying to open %s exclusively (%s)... %s\n",
268                                        device, strerror(errno), 
269                                        (i<4)?"retrying in 1 second.":"giving up.");
270                usleep(interval + interval * rand()/(RAND_MAX+1.0));
271                f = open(device, mode|O_EXCL);
272        }
273        if(i==5 && !beQuiet) {
274                FILE *g = fopen("/proc/mounts", "r");
275                if(g) {
276                        char buf[80];
277                        unsigned int len=strlen(device);
278                        while(!feof(g) && !ferror(g)) {
279                                if(fgets(buf, 79, g) && 0==strncmp(device, buf, len)) {
280                                        fprintf(stderr, "WARNING: %s seems to be mounted!\n", device);
281                                }
282                        }
283                        fclose(g);
284                }
285        }
286        return f;
287 }
288
289 #if 0
290 // Dead code, that sysfs parts may become deprecated soon
291 void map_sg_to_block(char *device, int len) {
292         char globpat[100];
293         glob_t globbuf;
294         snprintf(globpat, 100, "/sys/class/scsi_generic/%s/device/block:*", device+5);
295         memset(&globbuf, 0, sizeof(glob_t));
296         if(0==glob(globpat, GLOB_DOOFFS | GLOB_NOSORT, NULL, &globbuf)) {
297                 char *p = strrchr(globbuf.gl_pathv[0], ':');
298                 if(p) snprintf(device, len, "/dev/%s", p+1);
299         }
300         globfree(&globbuf);
301 }
302 #endif
303
304 /*
305  * Return version information for the low level SCSI transport code.
306  * This has been introduced to make it easier to trace down problems
307  * in applications.
308  */
309 static char *
310 usalo_version(SCSI *usalp, int what)
311 {
312         if (usalp != (SCSI *)0) {
313 #ifdef  USE_PG
314 #error pg-junk
315                 /*
316                  * If we only have a Parallel port or only opened a handle
317                  * for PP, just return PP version.
318                  */
319                 if (usallocal(usalp)->pgbus == 0 ||
320                     (usal_scsibus(usalp) >= 0 &&
321                     usal_scsibus(usalp) == usallocal(usalp)->pgbus))
322                         return (pg_version(usalp, what));
323 #endif
324                 switch (what) {
325
326                 case SCG_VERSION:
327                         return (_usal_trans_version);
328                 /*
329                  * If you changed this source, you are not allowed to
330                  * return "schily" for the SCG_AUTHOR request.
331                  */
332                 case SCG_AUTHOR:
333                         return (_usal_auth_cdrkit);
334                 case SCG_SCCS_ID:
335                         return (__sccsid);
336                 case SCG_KVERSION:
337                         {
338                                 static  char kv[16];
339                                 int     n;
340
341                                 if (usallocal(usalp)->drvers >= 0) {
342                                         n = usallocal(usalp)->drvers;
343                                         snprintf(kv, sizeof (kv),
344                                         "%d.%d.%d",
345                                         n/10000, (n%10000)/100, n%100);
346
347                                         return (kv);
348                                 }
349                         }
350                 }
351         }
352         return ((char *)0);
353 }
354
355 static int
356 usalo_help(SCSI *usalp, FILE *f)
357 {
358         __usal_help(f, "sg", "Generic transport independent SCSI",
359                 "", "bus,target,lun", "1,2,0", TRUE, FALSE);
360 #ifdef  USE_PG
361         pg_help(usalp, f);
362 #endif
363 #ifdef  USE_OLD_ATAPI
364         usalo_ahelp(usalp, f);
365 #endif
366         __usal_help(f, "ATA", "ATA Packet specific SCSI transport using sg interface",
367                 "ATA:", "bus,target,lun", "1,2,0", TRUE, FALSE);
368         return (0);
369 }
370
371 #define in_scanmode (busno < 0 && tgt < 0 && tlun < 0)
372
373 /*
374  * b/t/l is chopped of the device string.
375  */
376 static int
377 usalo_open(SCSI *usalp, char *device)
378 {
379         int     busno   = usal_scsibus(usalp);
380         int     tgt     = usal_target(usalp);
381         int     tlun    = usal_lun(usalp);
382         register int    f;
383         register int    i;
384         register int    b;
385         register int    t;
386         register int    l;
387         register int    nopen = 0;
388         char            devname[64];
389         int fake_atabus=0;
390
391         if (busno >= MAX_SCG || tgt >= MAX_TGT || tlun >= MAX_LUN) {
392                 errno = EINVAL;
393                 if (usalp->errstr)
394                         snprintf(usalp->errstr, SCSI_ERRSTR_SIZE,
395                                 "Illegal value for busno, target or lun '%d,%d,%d'",
396                                 busno, tgt, tlun);
397                 return (-1);
398         }
399
400         struct stat statbuf;
401         if(check_linux_26() && 0!=stat("/sys/kernel", &statbuf)) {
402                 static int warn_sysfs=1;
403                 if(warn_sysfs) {
404                         warn_sysfs=0;
405                         fprintf(stderr, "\nWarning, sysfs is not mounted on /sys!\n"
406                                         "It is recommended to mount sysfs to allow better device configuration\n");
407                         sleep(5);
408                 }
409         }
410
411         if (device != NULL && *device != '\0') {
412                 fake_atabus=0;
413                 if(0==strncmp(device, "OLDATAPI", 8)) {
414                         device+=3;
415                         usalp->ops = &ata_ops;
416                         return (SCGO_OPEN(usalp, device));
417                 }
418                 else if(0==strncmp(device, "ATAPI", 5)) {
419                         if(check_linux_26()) {
420                                 device+=5;
421                                 fake_atabus=1;
422                                 fprintf(stderr, "WARNING: the ATAPI: method is considered deprecated on modern kernels!\n"
423                                                 "Mapping device specification to ATA: method now.\n"
424                                                 "To force the old ATAPI: method, replace ATAPI: with OLDATAPI:\n");
425                         }
426                         else {
427                                 usalp->ops = &ata_ops;
428                                 return (SCGO_OPEN(usalp, device));
429                         }
430                 }
431                 else if(0==strncmp(device, "ATA", 3)) {
432                         fprintf(stderr, "WARNING: the ATA: method is considered deprecated on modern kernels!\n"
433                                         "Use --devices to display the native names.\n");
434                         fake_atabus=1;
435                         device+=3;
436                 }
437                 if(device[0]==':')
438                         device++;
439
440         }
441         else if( ! in_scanmode ) {
442                         fprintf(stderr, "WARNING: the deprecated pseudo SCSI syntax found as device specification.\n"
443                                         "Support for that may cease in the future versions of wodim. For now,\n"
444                                         "the device will be mapped to a block device file where possible.\n"
445                                         "Run \"wodim --devices\" for details.\n" );
446                         sleep(5);
447         }
448
449         if (usalp->local == NULL) {
450                 usalp->local = malloc(sizeof (struct usal_local));
451                 if (usalp->local == NULL)
452                         return (0);
453
454                 usallocal(usalp)->usalfile = -1;
455                 usallocal(usalp)->pgbus = -2;
456                 usallocal(usalp)->SCSIbuf = (char *)-1;
457                 usallocal(usalp)->pack_id = 5;
458                 usallocal(usalp)->drvers = -1;
459                 usallocal(usalp)->isold = -1;
460                 usallocal(usalp)->flags = 0;
461                 usallocal(usalp)->xbufsize = 0L;
462                 usallocal(usalp)->xbuf = NULL;
463
464                 for (b = 0; b < MAX_SCG; b++) {
465                         usallocal(usalp)->buscookies[b] = (short)-1;
466                         for (t = 0; t < MAX_TGT; t++) {
467                                 for (l = 0; l < MAX_LUN; l++) {
468                                         usallocal(usalp)->usalfiles[b][t][l] = (short)-1;
469                                         usallocal(usalp)->filenames[b][t][l] = NULL;
470                                 }
471                         }
472                 }
473         }
474
475         if (device != NULL && *device != '\0')
476         {
477                 /* open ONE directly */
478                 b = -1;
479                 if (device && strncmp(device, "/dev/hd", 7) == 0 && device[8]=='\0') {
480                         b = device[7] - 'a';
481                         if (b < 0 || b > 25)
482                                 b = -1;
483                 }
484                 if(b>=0 && fake_atabus)
485                         b+=1000;
486
487                 f = sg_open_excl(device, O_RDWR | O_NONBLOCK, FALSE);
488
489                 if (f < 0) {
490                         /*
491                          * The pg driver has the same rules to decide whether
492                          * to use openbydev. If we cannot open the device, it
493                          * makes no sense to try the /dev/pg* driver.
494                          */
495                         if (usalp->errstr)
496                                 snprintf(usalp->errstr, SCSI_ERRSTR_SIZE,
497                                                 "Cannot open '%s'",
498                                                 device);
499                         return (0);
500                 }
501                 sg_clearnblock(f);
502                 /* get some fake SCSI data */
503                 sg_mapdev(usalp, f, &busno, &tgt, &tlun, 0, 0, b);
504                 usal_settarget(usalp, busno, tgt, tlun);
505                 if (sg_setup(usalp, f, busno, tgt, tlun, b, device))
506                         return (++nopen);
507         }
508         else {
509                 /* scan and maybe keep one open, sg_setup decides */
510 #define HDX 0
511 #define SCD 1
512 #define SG 2
513                 int h;
514 /*
515 retry_scan_open:
516 */
517                 for(h=HDX; h <= (fake_atabus ? HDX : SG) ; h++) {
518                         char *pattern = NULL;
519                         unsigned int first = 0, last = 0;
520                         switch(h) {
521                                 case(HDX): 
522                                         {
523                                                 pattern="/dev/hd%c";
524                                                 first='a';
525                                                 last='z';
526                                                 break;
527                                         }
528                                 case(SCD):
529                                         {
530                                                 if(!check_linux_26())
531                                                         continue;
532                                                 pattern="/dev/scd%d";
533                                                 first=0;
534                                                 last=255;
535                                                 break;
536                                         }
537                                 case(SG):
538                                         {
539                                                 if(check_linux_26())
540                                                         continue; 
541 #if 0
542                                                 /*
543                                                  * Don't touch it on 2.6 until we have a proper locking scheme
544                                                  */
545                                                         if(nopen<=0)
546                                                                 fprintf(stderr, "Warning, using /dev/sg* for SG_IO operation. This method is considered harmful.\n");
547                                                         else if(found_scd)
548                                                                 continue;
549 #endif
550                                                 pattern="/dev/sg%d";
551                                                 first=0;
552                                                 last=255;
553                                                 break;
554                                         }
555                         }
556                         for(i=first; i<=last; i++) {
557                                 snprintf(devname, sizeof (devname), pattern, i);
558                                 f = sg_open_excl(devname, O_RDWR | O_NONBLOCK, in_scanmode);
559                                 if (f < 0) {
560                                         if (usalp->errstr)
561                                                 snprintf(usalp->errstr, SCSI_ERRSTR_SIZE,
562                                                                 "Cannot open '%s'", devname);
563                                 } else {
564                                         if(h == HDX) { // double-check the capabilities on ATAPI devices
565                                                 int     iparm;
566
567                                                 if (ioctl(f, SG_GET_TIMEOUT, &iparm) < 0) {
568                                                         if (usalp->errstr)
569                                                                 snprintf(usalp->errstr, SCSI_ERRSTR_SIZE,
570                                                                                 "SCSI unsupported with '%s'", devname);
571                                                         close(f);
572                                                         continue;
573                                                 }
574                                         }
575                                         sg_clearnblock(f);      /* Be very proper about this */
576                                         
577                                         /* construct the fake bus number hint, keep it readable */
578                                         b=-1;
579                                         if(h==HDX) {
580                                                 b=i-'a';
581                                                 if(!fake_atabus)
582                                                         b+=1000;
583                                         }
584
585                                         /* sg_setup returns false in scan mode, true if one single target was specified and opened */
586                                         if (sg_setup(usalp, f, busno, tgt, tlun, b, devname))
587                                                 return (++nopen);
588
589                                         if (in_scanmode)
590                                                 nopen++;
591                                 }
592                         }
593
594                         if (nopen > 0 && usalp->errstr)
595                                 usalp->errstr[0] = '\0';
596
597                         /* that's crap, should not be reached in non-scan mode.
598                          * Let's see whether it can be mapped to an atapi
599                          * device to emulate some old cludge's behaviour. 
600                         if(!in_scanmode && busno < 1000 && busno >=0) {
601                                 fake_atabus=1;
602                                 fprintf(stderr, "Unable to open this SCSI ID. Trying to map to old ATA syntax."
603                                                 "This workaround will disappear in the near future. Fix your configuration.");
604                                 goto retry_scan_open;
605                         }
606                         */
607                 }
608         }
609
610         if (usalp->debug > 0) for (b = 0; b < MAX_SCG; b++) {
611                 fprintf((FILE *)usalp->errfile,
612                         "Bus: %d cookie: %X\n",
613                         b, usallocal(usalp)->buscookies[b]);
614                 for (t = 0; t < MAX_TGT; t++) {
615                         for (l = 0; l < MAX_LUN; l++) {
616                                 if (usallocal(usalp)->usalfiles[b][t][l] != (short)-1) {
617                                         fprintf((FILE *)usalp->errfile,
618                                                 "file (%d,%d,%d): %d\n",
619                                                 b, t, l, usallocal(usalp)->usalfiles[b][t][l]);
620                                 }
621                         }
622                 }
623         }
624
625         return (nopen);
626 }
627
628 static int
629 usalo_close(SCSI *usalp)
630 {
631         register int    f;
632         register int    b;
633         register int    t;
634         register int    l;
635
636         if (usalp->local == NULL)
637                 return (-1);
638
639         for (b = 0; b < MAX_SCG; b++) {
640                 if (b == usallocal(usalp)->pgbus)
641                         continue;
642                 usallocal(usalp)->buscookies[b] = (short)-1;
643                 for (t = 0; t < MAX_TGT; t++) {
644                         for (l = 0; l < MAX_LUN; l++) {
645                                 f = usallocal(usalp)->usalfiles[b][t][l];
646                                 if (f >= 0)
647                                         close(f);
648                                 usallocal(usalp)->usalfiles[b][t][l] = (short)-1;
649                                 if(usallocal(usalp)->filenames[b][t][l]) {
650                                         free(usallocal(usalp)->filenames[b][t][l]);
651                                         usallocal(usalp)->filenames[b][t][l]=NULL;
652                                 }
653                         }
654                 }
655         }
656         if (usallocal(usalp)->xbuf != NULL) {
657                 free(usallocal(usalp)->xbuf);
658                 usallocal(usalp)->xbufsize = 0L;
659                 usallocal(usalp)->xbuf = NULL;
660         }
661 #ifdef  USE_PG
662         pg_close(usalp);
663 #endif
664         return (0);
665 }
666
667 /*
668  * The Linux kernel becomes more and more unmaintainable.
669  * Every year, a new incompatible SCSI transport interface is added.
670  * Each of them has it's own contradictory constraints.
671  * While you cannot have O_NONBLOCK set during operation, at least one
672  * of the drivers requires O_NONBLOCK to be set during open().
673  * This is used to clear O_NONBLOCK immediately after open() succeeded.
674  */
675 static void
676 sg_clearnblock(int f)
677 {
678         int     n;
679
680         n = fcntl(f, F_GETFL);
681         n &= ~O_NONBLOCK;
682         fcntl(f, F_SETFL, n);
683 }
684
685 /*!
686  *
687  * Return: TRUE when single target is chosen and was opened successfully, FALSE otherwise (on scans, etc).
688  */
689
690 static BOOL
691 sg_setup(SCSI *usalp, int f, int busno, int tgt, int tlun, int ataidx, char *origname)
692 {
693         int     n;
694         int     Chan;
695         int     Ino;
696         int     Bus;
697         int     Target;
698         int     Lun;
699         BOOL    onetarget = FALSE;
700
701 #ifdef  SG_GET_VERSION_NUM
702         if (usallocal(usalp)->drvers < 0) {
703                 usallocal(usalp)->drvers = 0;
704                 if (ioctl(f, SG_GET_VERSION_NUM, &n) >= 0) {
705                         usallocal(usalp)->drvers = n;
706                         if (usalp->overbose) {
707                                 fprintf((FILE *)usalp->errfile,
708                                         "Linux sg driver version: %d.%d.%d\n",
709                                         n/10000, (n%10000)/100, n%100);
710                         }
711                 }
712         }
713 #endif
714         if (usal_scsibus(usalp) >= 0 && usal_target(usalp) >= 0 && usal_lun(usalp) >= 0)
715                 onetarget = TRUE;
716
717         sg_mapdev(usalp, f, &Bus, &Target, &Lun, &Chan, &Ino, ataidx);
718         /*
719          * For old kernels try to make the best guess.
720          */
721         Ino |= Chan << 8;
722         n = sg_mapbus(usalp, Bus, Ino);
723         if (Bus == -1) {
724                 Bus = n;
725                 if (usalp->debug > 0) {
726                         fprintf((FILE *)usalp->errfile,
727                                 "SCSI Bus: %d (mapped from %d)\n", Bus, Ino);
728                 }
729         }
730
731         if (Bus < 0 || Bus >= MAX_SCG || Target < 0 || Target >= MAX_TGT ||
732                                                 Lun < 0 || Lun >= MAX_LUN) {
733                 return (FALSE);
734         }
735
736         if (usallocal(usalp)->usalfiles[Bus][Target][Lun] == (short)-1)
737                 usallocal(usalp)->usalfiles[Bus][Target][Lun] = (short)f;
738
739         if (usallocal(usalp)->filenames[Bus][Target][Lun] == NULL)
740                 usallocal(usalp)->filenames[Bus][Target][Lun] = strdup(origname);
741
742         if (onetarget) {
743                 if (Bus == busno && Target == tgt && Lun == tlun) {
744                         sg_initdev(usalp, f);
745                         usallocal(usalp)->usalfile = f; /* remember file for ioctl's */
746                         return (TRUE);
747                 } else {
748                         usallocal(usalp)->usalfiles[Bus][Target][Lun] = (short)-1;
749                         close(f);
750                 }
751         } else {
752                 /*
753                  * SCSI bus scanning may cause other generic SCSI activities to
754                  * fail because we set the default timeout and clear command
755                  * queues (in case of the old sg driver interface).
756                  */
757                 sg_initdev(usalp, f);
758                 if (usallocal(usalp)->usalfile < 0)
759                         usallocal(usalp)->usalfile = f; /* remember file for ioctl's */
760         }
761         return (FALSE);
762 }
763
764 static void
765 sg_initdev(SCSI *usalp, int f)
766 {
767         struct sg_rep {
768                 struct sg_header        hd;
769                 unsigned char           rbuf[100];
770         } sg_rep;
771         int     n;
772         int     i;
773         struct stat sb;
774
775         sg_settimeout(f, usalp->deftimeout);
776
777         /*
778          * If it's a block device, don't read.... pre Linux-2.4 /dev/sg*
779          * definitely is a character device and we only need to clear the
780          * queue for old /dev/sg* versions. If somebody ever implements
781          * raw disk access for Linux, this test may fail.
782          */
783         if (fstat(f, &sb) >= 0 && S_ISBLK(sb.st_mode))
784                 return;
785
786         /* Eat any unwanted garbage from prior use of this device */
787
788         n = fcntl(f, F_GETFL);  /* Be very proper about this */
789         fcntl(f, F_SETFL, n|O_NONBLOCK);
790
791         fillbytes((caddr_t)&sg_rep, sizeof (struct sg_header), '\0');
792         sg_rep.hd.reply_len = sizeof (struct sg_header);
793
794         /*
795          * This is really ugly.
796          * We come here if 'f' is related to a raw device. If Linux
797          * will ever have raw devices for /dev/hd* we may get problems.
798          * As long as there is no clean way to find out whether the
799          * filedescriptor 'f' is related to an old /dev/sg* or to
800          * /dev/hd*, we must assume that we found an old /dev/sg* and
801          * clean it up. Unfortunately, reading from /dev/hd* will
802          * Access the medium.
803          */
804         for (i = 0; i < 1000; i++) {    /* Read at least 32k from /dev/sg* */
805                 int     ret;
806
807                 ret = read(f, &sg_rep, sizeof (struct sg_rep));
808                 if (ret > 0)
809                         continue;
810                 if (ret == 0 || errno == EAGAIN || errno == EIO)
811                         break;
812                 if (ret < 0 && i > 10)  /* Stop on repeated unknown error */
813                         break;
814         }
815         fcntl(f, F_SETFL, n);
816 }
817
818 static int
819 sg_mapbus(SCSI *usalp, int busno, int ino)
820 {
821         register int    i;
822
823         if (busno >= 0 && busno < MAX_SCG) {
824                 /*
825                  * SCSI_IOCTL_GET_BUS_NUMBER worked.
826                  * Now we have the problem that Linux does not properly number
827                  * SCSI busses. The Bus number that Linux creates really is
828                  * the controller (card) number. I case of multi SCSI bus
829                  * cards we are lost.
830                  */
831                 if (usallocal(usalp)->buscookies[busno] == (short)-1) {
832                         usallocal(usalp)->buscookies[busno] = ino;
833                         return (busno);
834                 }
835                 /*
836                  * if (usallocal(usalp)->buscookies[busno] != (short)ino)
837                         errmsgno(EX_BAD, "Warning Linux Bus mapping botch.\n");
838                         */
839                 return (busno);
840
841         } else for (i = 0; i < MAX_SCG; i++) {
842                 if (usallocal(usalp)->buscookies[i] == (short)-1) {
843                         usallocal(usalp)->buscookies[i] = ino;
844                         return (i);
845                 }
846
847                 if (usallocal(usalp)->buscookies[i] == ino)
848                         return (i);
849         }
850         return (0);
851 }
852
853 static BOOL
854 sg_mapdev(SCSI *usalp, int f, int *busp, int *tgtp, int *lunp, int *chanp, 
855                          int *inop, int ataidx)
856 {
857         struct  sg_id {
858                 long    l1; /* target | lun << 8 | channel << 16 | low_ino << 24 */
859                 long    l2; /* Unique id */
860         } sg_id;
861         int     Chan;
862         int     Ino;
863         int     Bus;
864         int     Target;
865         int     Lun;
866
867         if (ataidx >= 0) {
868                 /*
869                  * The badly designed /dev/hd* interface maps everything
870                  * to 0,0,0 so we need to do the mapping ourselves.
871                  */
872                 *busp = (ataidx/1000) * 1000;
873                 *tgtp = ataidx%1000;
874                 *lunp = 0;
875                 if (chanp)
876                         *chanp = 0;
877                 if (inop)
878                         *inop = 0;
879                 return (TRUE);
880         }
881         if (ioctl(f, SCSI_IOCTL_GET_IDLUN, &sg_id))
882                 return (FALSE);
883         if (usalp->debug > 0) {
884                 fprintf((FILE *)usalp->errfile,
885                         "l1: 0x%lX l2: 0x%lX\n", sg_id.l1, sg_id.l2);
886         }
887         if (ioctl(f, SCSI_IOCTL_GET_BUS_NUMBER, &Bus) < 0) {
888                 Bus = -1;
889         }
890
891         Target  = sg_id.l1 & 0xFF;
892         Lun     = (sg_id.l1 >> 8) & 0xFF;
893         Chan    = (sg_id.l1 >> 16) & 0xFF;
894         Ino     = (sg_id.l1 >> 24) & 0xFF;
895         if (usalp->debug > 0) {
896                 fprintf((FILE *)usalp->errfile,
897                         "Bus: %d Target: %d Lun: %d Chan: %d Ino: %d\n",
898                         Bus, Target, Lun, Chan, Ino);
899         }
900         *busp = Bus;
901         *tgtp = Target;
902         *lunp = Lun;
903         if (chanp)
904                 *chanp = Chan;
905         if (inop)
906                 *inop = Ino;
907         return (TRUE);
908 }
909
910 #if defined(SG_SET_RESERVED_SIZE) && defined(SG_GET_RESERVED_SIZE)
911 /*
912  * The way Linux does DMA resouce management is a bit curious.
913  * It totally deviates from all other OS and forces long ugly code.
914  * If we are opening all drivers for a SCSI bus scan operation, we need
915  * to set the limit for all open devices.
916  * This may use up all kernel memory ... so do the job carefully.
917  *
918  * A big problem is that SG_SET_RESERVED_SIZE does not return any hint
919  * on whether the request did fail. The only way to find if it worked
920  * is to use SG_GET_RESERVED_SIZE to read back the current values.
921  */
922 static long
923 sg_raisedma(SCSI *usalp, long newmax)
924 {
925         register int    b;
926         register int    t;
927         register int    l;
928         register int    f;
929                 int     val;
930                 int     old;
931
932         /*
933          * First try to raise the DMA limit to a moderate value that
934          * most likely does not use up all kernel memory.
935          */
936         val = 126*1024;
937
938         if (val > MAX_DMA_LINUX) {
939                 for (b = 0; b < MAX_SCG; b++) {
940                         for (t = 0; t < MAX_TGT; t++) {
941                                 for (l = 0; l < MAX_LUN; l++) {
942                                         if ((f = SCGO_FILENO(usalp, b, t, l)) < 0)
943                                                 continue;
944                                         old = 0;
945                                         if (ioctl(f, SG_GET_RESERVED_SIZE, &old) < 0)
946                                                 continue;
947                                         if (val > old)
948                                                 ioctl(f, SG_SET_RESERVED_SIZE, &val);
949                                 }
950                         }
951                 }
952         }
953
954         /*
955          * Now to raise the DMA limit to what we really need.
956          */
957         if (newmax > val) {
958                 val = newmax;
959                 for (b = 0; b < MAX_SCG; b++) {
960                         for (t = 0; t < MAX_TGT; t++) {
961                                 for (l = 0; l < MAX_LUN; l++) {
962                                         if ((f = SCGO_FILENO(usalp, b, t, l)) < 0)
963                                                 continue;
964                                         old = 0;
965                                         if (ioctl(f, SG_GET_RESERVED_SIZE, &old) < 0)
966                                                 continue;
967                                         if (val > old)
968                                                 ioctl(f, SG_SET_RESERVED_SIZE, &val);
969                                 }
970                         }
971                 }
972         }
973
974         /*
975          * To make sure we did not fail (the ioctl does not report errors)
976          * we need to check the DMA limits. We return the smallest value.
977          */
978         for (b = 0; b < MAX_SCG; b++) {
979                 for (t = 0; t < MAX_TGT; t++) {
980                         for (l = 0; l < MAX_LUN; l++) {
981                                 if ((f = SCGO_FILENO(usalp, b, t, l)) < 0)
982                                         continue;
983                                 if (ioctl(f, SG_GET_RESERVED_SIZE, &val) < 0)
984                                         continue;
985                                 if (usalp->debug > 0) {
986                                         fprintf((FILE *)usalp->errfile,
987                                                 "Target (%d,%d,%d): DMA max %d old max: %ld\n",
988                                                 b, t, l, val, newmax);
989                                 }
990                                 if (val < newmax)
991                                         newmax = val;
992                         }
993                 }
994         }
995         return ((long)newmax);
996 }
997 #endif
998
999 static char *freadstring(char *fn, char *out, int len) {
1000         char *ret;
1001         FILE *fd=fopen(fn, "r");
1002         out[0]='\0';
1003         if(!fd) return NULL;
1004         ret = fgets(out, len, fd);
1005         fclose(fd);
1006         return ret;
1007 }
1008
1009 static long
1010 usalo_maxdma(SCSI *usalp, long amt)
1011 {
1012         struct stat stbuf;
1013         long maxdma = MAX_DMA_LINUX;
1014
1015 #if defined(SG_SET_RESERVED_SIZE) && defined(SG_GET_RESERVED_SIZE)
1016         /*
1017          * Use the curious new kernel interface found on Linux >= 2.2.10
1018          * This interface first appeared in 2.2.6 but it was not working.
1019          */
1020         if (usallocal(usalp)->drvers >= 20134)
1021                 maxdma = sg_raisedma(usalp, amt);
1022 #endif
1023         /*
1024          * First try the modern kernel 2.6.1x way to detect the real maximum
1025          * DMA for this specific device, then try the other methods.
1026          */
1027         if(0==fstat(usallocal(usalp)->usalfile, &stbuf)) {
1028                 /* that's ugly, there are so many symlinks in sysfs but none from
1029                  * major:minor to the relevant directory */
1030                 long int major, minor, i;
1031                 major=stbuf.st_rdev>>8;
1032                 minor=stbuf.st_rdev&0xFF;
1033                 if (usalp->debug > 0)
1034                   fprintf(stderr, "Looking for data for major:minor: %ld:%ld\n", major, minor);
1035                 glob_t globbuf;
1036                 memset(&globbuf, 0, sizeof(glob_t));
1037                 /* *dev files contain the major:minor strings to compare */
1038                 glob("/sys/class/scsi_generic/*/device/block*/queue/max_sectors_kb", GLOB_DOOFFS | GLOB_NOSORT, NULL, &globbuf);
1039                 glob("/sys/block/*/device/block*/queue/max_sectors_kb", GLOB_DOOFFS | GLOB_NOSORT | GLOB_APPEND, NULL, &globbuf);
1040                 for(i=0;i<globbuf.gl_pathc; i++) {
1041                         char *cut, *ende;
1042                         char buf[64];
1043                         cut=strstr(globbuf.gl_pathv[i], "/device/")+4;
1044                         *cut='\0';
1045                         freadstring(globbuf.gl_pathv[i], buf, sizeof(buf));
1046                         if(strtol(buf, &ende, 10) == major && ende && atoi(ende) == minor) {
1047                                 *cut='i';
1048                                 freadstring(globbuf.gl_pathv[i], buf, sizeof(buf));
1049                                 return(1024*atoi(buf));
1050                         }
1051
1052                 }
1053                 globfree(&globbuf);
1054         }
1055 #ifdef  SG_GET_BUFSIZE
1056         /*
1057          * We assume that all /dev/sg instances use the same
1058          * maximum buffer size.
1059          */
1060         maxdma = ioctl(usallocal(usalp)->usalfile, SG_GET_BUFSIZE, 0);
1061 #endif
1062         if (maxdma < 0) {
1063 #ifdef  USE_PG
1064                 /*
1065                  * If we only have a Parallel port, just return PP maxdma.
1066                  */
1067                 if (usallocal(usalp)->pgbus == 0)
1068                         return (pg_maxdma(usalp, amt));
1069 #endif
1070                 if (usallocal(usalp)->usalfile >= 0)
1071                         maxdma = MAX_DMA_LINUX;
1072         }
1073 #ifdef  USE_PG
1074         if (usal_scsibus(usalp) == usallocal(usalp)->pgbus)
1075                 return (pg_maxdma(usalp, amt));
1076         if ((usal_scsibus(usalp) < 0) && (pg_maxdma(usalp, amt) < maxdma))
1077                 return (pg_maxdma(usalp, amt));
1078 #endif
1079         return (maxdma);
1080 }
1081
1082 static void *
1083 usalo_getbuf(SCSI *usalp, long amt)
1084 {
1085         char    *ret;
1086
1087         if (usalp->debug > 0) {
1088                 fprintf((FILE *)usalp->errfile,
1089                                 "usalo_getbuf: %ld bytes\n", amt);
1090         }
1091         /*
1092          * For performance reason, we allocate pagesize()
1093          * bytes before the SCSI buffer to avoid
1094          * copying the whole buffer contents when
1095          * setting up the /dev/sg data structures.
1096          */
1097         ret = valloc((size_t)(amt+getpagesize()));
1098         if (ret == NULL)
1099                 return (ret);
1100         usalp->bufbase = ret;
1101         ret += getpagesize();
1102         usallocal(usalp)->SCSIbuf = ret;
1103         return ((void *)ret);
1104 }
1105
1106 static void
1107 usalo_freebuf(SCSI *usalp)
1108 {
1109         if (usalp->bufbase)
1110                 free(usalp->bufbase);
1111         usalp->bufbase = NULL;
1112 }
1113
1114 static BOOL
1115 usalo_havebus(SCSI *usalp, int busno)
1116 {
1117         register int    t;
1118         register int    l;
1119
1120         if (busno < 0 || busno >= MAX_SCG)
1121                 return (FALSE);
1122
1123         if (usalp->local == NULL)
1124                 return (FALSE);
1125
1126         for (t = 0; t < MAX_TGT; t++) {
1127                 for (l = 0; l < MAX_LUN; l++)
1128                         if (usallocal(usalp)->usalfiles[busno][t][l] >= 0)
1129                                 return (TRUE);
1130         }
1131         return (FALSE);
1132 }
1133
1134 static int
1135 usalo_fileno(SCSI *usalp, int busno, int tgt, int tlun)
1136 {
1137         if (busno < 0 || busno >= MAX_SCG ||
1138             tgt < 0 || tgt >= MAX_TGT ||
1139             tlun < 0 || tlun >= MAX_LUN)
1140                 return (-1);
1141
1142         if (usalp->local == NULL)
1143                 return (-1);
1144
1145         return ((int)usallocal(usalp)->usalfiles[busno][tgt][tlun]);
1146 }
1147
1148 static int
1149 usalo_initiator_id(SCSI *usalp)
1150 {
1151 #ifdef  USE_PG
1152         if (usal_scsibus(usalp) == usallocal(usalp)->pgbus)
1153                 return (pg_initiator_id(usalp));
1154 #endif
1155         return (-1);
1156 }
1157
1158 static int
1159 usalo_isatapi(SCSI *usalp)
1160 {
1161         return -1;
1162 #if 0
1163         /*
1164          * Who exactly needs this information? Just for some bitching in wodim?
1165          * Is this an _abstraction_ layer or spam layer?
1166          */
1167 #ifdef  USE_PG
1168         if (usal_scsibus(usalp) == usallocal(usalp)->pgbus)
1169                 return (pg_isatapi(usalp));
1170 #endif
1171
1172         /*
1173          * The /dev/hd* interface always returns TRUE for SG_EMULATED_HOST.
1174          * So this is completely useless.
1175          */
1176         if (usallocal(usalp)->flags & LF_ATA)
1177                 return (-1);
1178
1179 #ifdef  SG_EMULATED_HOST
1180         {
1181         int     emulated = FALSE;
1182
1183         /*
1184          * XXX Should we use this at all?
1185          * XXX The badly designed /dev/hd* interface always
1186          * XXX returns TRUE, even when used with e.g. /dev/sr0.
1187          */
1188         if (ioctl(usalp->fd, SG_EMULATED_HOST, &emulated) >= 0)
1189                 return (emulated != 0);
1190         }
1191 #endif
1192         return (-1);
1193 #endif
1194 }
1195
1196 static int
1197 usalo_reset(SCSI *usalp, int what)
1198 {
1199 #ifdef  SG_SCSI_RESET
1200         int     f = usalp->fd;
1201         int     func = -1;
1202 #endif
1203 #ifdef  USE_PG
1204         if (usal_scsibus(usalp) == usallocal(usalp)->pgbus)
1205                 return (pg_reset(usalp, what));
1206 #endif
1207         /*
1208          * Do we have a SCSI reset in the Linux sg driver?
1209          */
1210 #ifdef  SG_SCSI_RESET
1211         /*
1212          * Newer Linux sg driver seem to finally implement it...
1213          */
1214 #ifdef  SG_SCSI_RESET_NOTHING
1215         func = SG_SCSI_RESET_NOTHING;
1216         if (ioctl(f, SG_SCSI_RESET, &func) >= 0) {
1217                 if (what == SCG_RESET_NOP)
1218                         return (0);
1219 #ifdef  SG_SCSI_RESET_DEVICE
1220                 if (what == SCG_RESET_TGT) {
1221                         func = SG_SCSI_RESET_DEVICE;
1222                         if (ioctl(f, SG_SCSI_RESET, &func) >= 0)
1223                                 return (0);
1224                 }
1225 #endif
1226 #ifdef  SG_SCSI_RESET_BUS
1227                 if (what == SCG_RESET_BUS) {
1228                         func = SG_SCSI_RESET_BUS;
1229                         if (ioctl(f, SG_SCSI_RESET, &func) >= 0)
1230                                 return (0);
1231                 }
1232 #endif
1233         }
1234 #endif
1235 #endif
1236         return (-1);
1237 }
1238
1239 static void
1240 sg_settimeout(int f, int tmo)
1241 {
1242 #ifndef HZ
1243         static int HZ=0;
1244         if (!HZ)
1245                 HZ = sysconf(_SC_CLK_TCK);
1246 #endif
1247         tmo *= HZ;
1248         if (tmo)
1249                 tmo += HZ/2;
1250
1251         if (ioctl(f, SG_SET_TIMEOUT, &tmo) < 0)
1252                 comerr("Cannot set SG_SET_TIMEOUT.\n");
1253 }
1254
1255 /*
1256  * Get misaligned int.
1257  * Needed for all recent processors (sparc/ppc/alpha)
1258  * because the /dev/sg design forces us to do misaligned
1259  * reads of integers.
1260  */
1261 #ifdef  MISALIGN
1262 static int
1263 sg_getint(int *ip)
1264 {
1265                 int     ret;
1266         register char   *cp = (char *)ip;
1267         register char   *tp = (char *)&ret;
1268         register int    i;
1269
1270         for (i = sizeof (int); --i >= 0; )
1271                 *tp++ = *cp++;
1272
1273         return (ret);
1274 }
1275 #define GETINT(a)       sg_getint(&(a))
1276 #else
1277 #define GETINT(a)       (a)
1278 #endif
1279
1280 #ifdef  SG_IO
1281 static int
1282 usalo_send(SCSI *usalp)
1283 {
1284         struct usal_cmd *sp = usalp->scmd;
1285         int             ret;
1286         sg_io_hdr_t     sg_io;
1287         struct timeval  to;
1288
1289         if (usalp->fd < 0) {
1290                 sp->error = SCG_FATAL;
1291                 sp->ux_errno = EIO;
1292                 return (0);
1293         }
1294         if (usallocal(usalp)->isold > 0) {
1295                 return (sg_rwsend(usalp));
1296         }
1297         fillbytes((caddr_t)&sg_io, sizeof (sg_io), '\0');
1298
1299         sg_io.interface_id = 'S';
1300
1301         if (sp->flags & SCG_RECV_DATA) {
1302                 sg_io.dxfer_direction = SG_DXFER_FROM_DEV;
1303         } else if (sp->size > 0) {
1304                 sg_io.dxfer_direction = SG_DXFER_TO_DEV;
1305         } else {
1306                 sg_io.dxfer_direction = SG_DXFER_NONE;
1307         }
1308         sg_io.cmd_len = sp->cdb_len;
1309         if (sp->sense_len > SG_MAX_SENSE)
1310                 sg_io.mx_sb_len = SG_MAX_SENSE;
1311         else
1312                 sg_io.mx_sb_len = sp->sense_len;
1313         sg_io.dxfer_len = sp->size;
1314         sg_io.dxferp = sp->addr;
1315         sg_io.cmdp = sp->cdb.cmd_cdb;
1316         sg_io.sbp = sp->u_sense.cmd_sense;
1317         sg_io.timeout = sp->timeout*1000;
1318         sg_io.flags |= SG_FLAG_DIRECT_IO;
1319
1320         ret = ioctl(usalp->fd, SG_IO, &sg_io);
1321         if (usalp->debug > 0) {
1322                 fprintf((FILE *)usalp->errfile,
1323                                 "ioctl ret: %d\n", ret);
1324         }
1325
1326         if (ret < 0) {
1327                 sp->ux_errno = geterrno();
1328                 /*
1329                  * Check if SCSI command cound not be send at all.
1330                  * Linux usually returns EINVAL for an unknoen ioctl.
1331                  * In case somebody from the Linux kernel team learns that the
1332                  * corect errno would be ENOTTY, we check for this errno too.
1333                  */
1334                 if ((sp->ux_errno == ENOTTY || sp->ux_errno == EINVAL) &&
1335                     usallocal(usalp)->isold < 0) {
1336                         usallocal(usalp)->isold = 1;
1337                         return (sg_rwsend(usalp));
1338                 }
1339                 if (sp->ux_errno == ENXIO ||
1340                     sp->ux_errno == EINVAL || sp->ux_errno == EACCES) {
1341                         return (-1);
1342                 }
1343         }
1344
1345         sp->u_scb.cmd_scb[0] = sg_io.status;
1346         sp->sense_count = sg_io.sb_len_wr;
1347
1348         if (usalp->debug > 0) {
1349                 fprintf((FILE *)usalp->errfile,
1350                                 "host_status: %02X driver_status: %02X\n",
1351                                 sg_io.host_status, sg_io.driver_status);
1352         }
1353
1354         switch (sg_io.host_status) {
1355
1356         case DID_OK:
1357                         /*
1358                          * If there is no DMA overrun and there is a
1359                          * SCSI Status byte != 0 then the SCSI cdb transport
1360                          * was OK and sp->error must be SCG_NO_ERROR.
1361                          */
1362                         if ((sg_io.driver_status & DRIVER_SENSE) != 0) {
1363                                 if (sp->ux_errno == 0)
1364                                         sp->ux_errno = EIO;
1365
1366                                 if (sp->u_sense.cmd_sense[0] != 0 &&
1367                                     sp->u_scb.cmd_scb[0] == 0) {
1368                                         /*
1369                                          * The Linux SCSI system up to 2.4.xx
1370                                          * trashes the status byte in the
1371                                          * kernel. This is true at least for
1372                                          * ide-scsi emulation. Until this gets
1373                                          * fixed, we need this hack.
1374                                          */
1375                                         sp->u_scb.cmd_scb[0] = ST_CHK_COND;
1376                                         if (sp->sense_count == 0)
1377                                                 sp->sense_count = SG_MAX_SENSE;
1378
1379                                         if ((sp->u_sense.cmd_sense[2] == 0) &&
1380                                             (sp->u_sense.cmd_sense[12] == 0) &&
1381                                             (sp->u_sense.cmd_sense[13] == 0)) {
1382                                                 /*
1383                                                  * The Linux SCSI system will
1384                                                  * send a request sense for
1385                                                  * even a dma underrun error.
1386                                                  * Clear CHECK CONDITION state
1387                                                  * in case of No Sense.
1388                                                  */
1389                                                 sp->u_scb.cmd_scb[0] = 0;
1390                                                 sp->u_sense.cmd_sense[0] = 0;
1391                                                 sp->sense_count = 0;
1392                                         }
1393                                 }
1394                         }
1395                         break;
1396
1397         case DID_NO_CONNECT:    /* Arbitration won, retry NO_CONNECT? */
1398                         sp->error = SCG_RETRYABLE;
1399                         break;
1400         case DID_BAD_TARGET:
1401                         sp->error = SCG_FATAL;
1402                         break;
1403
1404         case DID_TIME_OUT:
1405                 __usal_times(usalp);
1406
1407                 if (sp->timeout > 1 && usalp->cmdstop->tv_sec == 0) {
1408                         sp->u_scb.cmd_scb[0] = 0;
1409                         sp->error = SCG_FATAL;  /* a selection timeout */
1410                 } else {
1411                         sp->error = SCG_TIMEOUT;
1412                 }
1413                 break;
1414
1415         default:
1416                 to.tv_sec = sp->timeout;
1417                 to.tv_usec = 500000;
1418                 __usal_times(usalp);
1419
1420                 if (usalp->cmdstop->tv_sec < to.tv_sec ||
1421                     (usalp->cmdstop->tv_sec == to.tv_sec &&
1422                         usalp->cmdstop->tv_usec < to.tv_usec)) {
1423
1424                         sp->ux_errno = 0;
1425                         sp->error = SCG_TIMEOUT;        /* a timeout */
1426                 } else {
1427                         sp->error = SCG_RETRYABLE;
1428                 }
1429                 break;
1430         }
1431         if (sp->error && sp->ux_errno == 0)
1432                 sp->ux_errno = EIO;
1433
1434         sp->resid = sg_io.resid;
1435         return (0);
1436 }
1437 #else
1438 #       define  sg_rwsend       usalo_send
1439 #endif
1440
1441 static int
1442 sg_rwsend(SCSI *usalp)
1443 {
1444         int             f = usalp->fd;
1445         struct usal_cmd *sp = usalp->scmd;
1446         struct sg_rq    *sgp;
1447         struct sg_rq    *sgp2;
1448         int     i;
1449         int     pack_len;
1450         int     reply_len;
1451         int     amt = sp->cdb_len;
1452         struct sg_rq {
1453                 struct sg_header        hd;
1454                 unsigned char           buf[MAX_DMA_LINUX+SCG_MAX_CMD];
1455         } sg_rq;
1456 #ifdef  SG_GET_BUFSIZE          /* We may use a 'sg' version 2 driver   */
1457         char    driver_byte;
1458         char    host_byte;
1459         char    msg_byte;
1460         char    status_byte;
1461 #endif
1462
1463         if (f < 0) {
1464                 sp->error = SCG_FATAL;
1465                 sp->ux_errno = EIO;
1466                 return (0);
1467         }
1468 #ifdef  USE_PG
1469         if (usal_scsibus(usalp) == usallocal(usalp)->pgbus)
1470                 return (pg_send(usalp));
1471 #endif
1472         if (sp->timeout != usalp->deftimeout)
1473                 sg_settimeout(f, sp->timeout);
1474
1475
1476         sgp2 = sgp = &sg_rq;
1477         if (sp->addr == usallocal(usalp)->SCSIbuf) {
1478                 sgp = (struct sg_rq *)
1479                         (usallocal(usalp)->SCSIbuf - (sizeof (struct sg_header) + amt));
1480                 sgp2 = (struct sg_rq *)
1481                         (usallocal(usalp)->SCSIbuf - (sizeof (struct sg_header)));
1482         } else {
1483                 if (usalp->debug > 0) {
1484                         fprintf((FILE *)usalp->errfile,
1485                                 "DMA addr: 0x%8.8lX size: %d - using copy buffer\n",
1486                                 (long)sp->addr, sp->size);
1487                 }
1488                 if (sp->size > (int)(sizeof (sg_rq.buf) - SCG_MAX_CMD)) {
1489
1490                         if (usallocal(usalp)->xbuf == NULL) {
1491                                 usallocal(usalp)->xbufsize = usalp->maxbuf;
1492                                 usallocal(usalp)->xbuf =
1493                                         malloc(usallocal(usalp)->xbufsize +
1494                                                 SCG_MAX_CMD +
1495                                                 sizeof (struct sg_header));
1496                                 if (usalp->debug > 0) {
1497                                         fprintf((FILE *)usalp->errfile,
1498                                                 "Allocated DMA copy buffer, addr: 0x%8.8lX size: %ld\n",
1499                                                 (long)usallocal(usalp)->xbuf,
1500                                                 usalp->maxbuf);
1501                                 }
1502                         }
1503                         if (usallocal(usalp)->xbuf == NULL ||
1504                                 sp->size > usallocal(usalp)->xbufsize) {
1505                                 errno = ENOMEM;
1506                                 return (-1);
1507                         }
1508                         sgp2 = sgp = (struct sg_rq *)usallocal(usalp)->xbuf;
1509                 }
1510         }
1511
1512         /*
1513          * This is done to avoid misaligned access of sgp->some_int
1514          */
1515         pack_len = sizeof (struct sg_header) + amt;
1516         reply_len = sizeof (struct sg_header);
1517         if (sp->flags & SCG_RECV_DATA) {
1518                 reply_len += sp->size;
1519         } else {
1520                 pack_len += sp->size;
1521         }
1522
1523 #ifdef  MISALIGN
1524         /*
1525          * sgp->some_int may be misaligned if (sp->addr == SCSIbuf)
1526          * This is no problem on Intel porocessors, however
1527          * all other processors don't like it.
1528          * sizeof (struct sg_header) + amt is usually not a multiple of
1529          * sizeof (int). For this reason, we fill in the values into sg_rq
1530          * which is always corectly aligned and then copy it to the real
1531          * location if this location differs from sg_rq.
1532          * Never read/write directly to sgp->some_int !!!!!
1533          */
1534         fillbytes((caddr_t)&sg_rq, sizeof (struct sg_header), '\0');
1535
1536         sg_rq.hd.pack_len = pack_len;
1537         sg_rq.hd.reply_len = reply_len;
1538         sg_rq.hd.pack_id = usallocal(usalp)->pack_id++;
1539 /*      sg_rq.hd.result = 0;    not needed because of fillbytes() */
1540
1541         if ((caddr_t)&sg_rq != (caddr_t)sgp)
1542                 movebytes((caddr_t)&sg_rq, (caddr_t)sgp, sizeof (struct sg_header));
1543 #else
1544         fillbytes((caddr_t)sgp, sizeof (struct sg_header), '\0');
1545
1546         sgp->hd.pack_len = pack_len;
1547         sgp->hd.reply_len = reply_len;
1548         sgp->hd.pack_id = usallocal(usalp)->pack_id++;
1549 /*      sgp->hd.result = 0;     not needed because of fillbytes() */
1550 #endif
1551         if (amt == 12)
1552                 sgp->hd.twelve_byte = 1;
1553
1554
1555         for (i = 0; i < amt; i++) {
1556                 sgp->buf[i] = sp->cdb.cmd_cdb[i];
1557         }
1558         if (!(sp->flags & SCG_RECV_DATA)) {
1559                 if ((void *)sp->addr != (void *)&sgp->buf[amt])
1560                         movebytes(sp->addr, &sgp->buf[amt], sp->size);
1561                 amt += sp->size;
1562         }
1563 #ifdef  SG_GET_BUFSIZE
1564         sgp->hd.want_new  = 1;                  /* Order new behaviour  */
1565         sgp->hd.cdb_len   = sp->cdb_len;        /* Set CDB length       */
1566         if (sp->sense_len > SG_MAX_SENSE)
1567                 sgp->hd.sense_len = SG_MAX_SENSE;
1568         else
1569                 sgp->hd.sense_len = sp->sense_len;
1570 #endif
1571         i = sizeof (struct sg_header) + amt;
1572         if ((amt = write(f, sgp, i)) < 0) {                     /* write */
1573                 sg_settimeout(f, usalp->deftimeout);
1574                 return (-1);
1575         } else if (amt != i) {
1576                 errmsg("usalo_send(%s) wrote %d bytes (expected %d).\n",
1577                                                 usalp->cmdname, amt, i);
1578         }
1579
1580         if (sp->addr == usallocal(usalp)->SCSIbuf) {
1581                 movebytes(sgp, sgp2, sizeof (struct sg_header));
1582                 sgp = sgp2;
1583         }
1584         sgp->hd.sense_buffer[0] = 0;
1585         if ((amt = read(f, sgp, reply_len)) < 0) {              /* read */
1586                 sg_settimeout(f, usalp->deftimeout);
1587                 return (-1);
1588         }
1589
1590         if (sp->flags & SCG_RECV_DATA && ((void *)sgp->buf != (void *)sp->addr)) {
1591                 movebytes(sgp->buf, sp->addr, sp->size);
1592         }
1593         sp->ux_errno = GETINT(sgp->hd.result);          /* Unaligned read */
1594         sp->error = SCG_NO_ERROR;
1595
1596 #ifdef  SG_GET_BUFSIZE
1597         if (sgp->hd.grant_new) {
1598                 sp->sense_count = sgp->hd.sense_len;
1599                 pack_len    = GETINT(sgp->hd.sg_cmd_status);    /* Unaligned read */
1600                 driver_byte = (pack_len  >> 24) & 0xFF;
1601                 host_byte   = (pack_len  >> 16) & 0xFF;
1602                 msg_byte    = (pack_len  >> 8) & 0xFF;
1603                 status_byte =  pack_len  & 0xFF;
1604
1605                 switch (host_byte) {
1606
1607                 case DID_OK:
1608                                 if ((driver_byte & DRIVER_SENSE ||
1609                                     sgp->hd.sense_buffer[0] != 0) &&
1610                                     status_byte == 0) {
1611                                         /*
1612                                          * The Linux SCSI system up to 2.4.xx
1613                                          * trashes the status byte in the
1614                                          * kernel. This is true at least for
1615                                          * ide-scsi emulation. Until this gets
1616                                          * fixed, we need this hack.
1617                                          */
1618                                         status_byte = ST_CHK_COND;
1619                                         if (sgp->hd.sense_len == 0)
1620                                                 sgp->hd.sense_len = SG_MAX_SENSE;
1621
1622                                         if ((sp->u_sense.cmd_sense[2] == 0) &&
1623                                             (sp->u_sense.cmd_sense[12] == 0) &&
1624                                             (sp->u_sense.cmd_sense[13] == 0)) {
1625                                                 /*
1626                                                  * The Linux SCSI system will
1627                                                  * send a request sense for
1628                                                  * even a dma underrun error.
1629                                                  * Clear CHECK CONDITION state
1630                                                  * in case of No Sense.
1631                                                  */
1632                                                 sp->u_scb.cmd_scb[0] = 0;
1633                                                 sp->u_sense.cmd_sense[0] = 0;
1634                                                 sp->sense_count = 0;
1635                                         }
1636                                 }
1637                                 break;
1638
1639                 case DID_NO_CONNECT:    /* Arbitration won, retry NO_CONNECT? */
1640                                 sp->error = SCG_RETRYABLE;
1641                                 break;
1642
1643                 case DID_BAD_TARGET:
1644                                 sp->error = SCG_FATAL;
1645                                 break;
1646
1647                 case DID_TIME_OUT:
1648                                 sp->error = SCG_TIMEOUT;
1649                                 break;
1650
1651                 default:
1652                                 sp->error = SCG_RETRYABLE;
1653
1654                                 if ((driver_byte & DRIVER_SENSE ||
1655                                     sgp->hd.sense_buffer[0] != 0) &&
1656                                     status_byte == 0) {
1657                                         status_byte = ST_CHK_COND;
1658                                         sp->error = SCG_NO_ERROR;
1659                                 }
1660                                 if (status_byte != 0 && sgp->hd.sense_len == 0) {
1661                                         sgp->hd.sense_len = SG_MAX_SENSE;
1662                                         sp->error = SCG_NO_ERROR;
1663                                 }
1664                                 break;
1665
1666                 }
1667                 if ((host_byte != DID_OK || status_byte != 0) && sp->ux_errno == 0)
1668                         sp->ux_errno = EIO;
1669                 sp->u_scb.cmd_scb[0] = status_byte;
1670                 if (status_byte & ST_CHK_COND) {
1671                         sp->sense_count = sgp->hd.sense_len;
1672                         movebytes(sgp->hd.sense_buffer, sp->u_sense.cmd_sense, sp->sense_count);
1673                 }
1674         } else
1675 #endif
1676         {
1677                 if (GETINT(sgp->hd.result) == EBUSY) {  /* Unaligned read */
1678                         struct timeval to;
1679
1680                         to.tv_sec = sp->timeout;
1681                         to.tv_usec = 500000;
1682                         __usal_times(usalp);
1683
1684                         if (sp->timeout > 1 && usalp->cmdstop->tv_sec == 0) {
1685                                 sp->u_scb.cmd_scb[0] = 0;
1686                                 sp->ux_errno = EIO;
1687                                 sp->error = SCG_FATAL;  /* a selection timeout */
1688                         } else if (usalp->cmdstop->tv_sec < to.tv_sec ||
1689                             (usalp->cmdstop->tv_sec == to.tv_sec &&
1690                                 usalp->cmdstop->tv_usec < to.tv_usec)) {
1691
1692                                 sp->ux_errno = EIO;
1693                                 sp->error = SCG_TIMEOUT;        /* a timeout */
1694                         } else {
1695                                 sp->error = SCG_RETRYABLE;      /* may be BUS_BUSY */
1696                         }
1697                 }
1698
1699                 if (sp->flags & SCG_RECV_DATA)
1700                         sp->resid = (sp->size + sizeof (struct sg_header)) - amt;
1701                 else
1702                         sp->resid = 0;  /* sg version1 cannot return DMA resid count */
1703
1704                 if (sgp->hd.sense_buffer[0] != 0) {
1705                         sp->scb.chk = 1;
1706                         sp->sense_count = SG_MAX_SENSE;
1707                         movebytes(sgp->hd.sense_buffer, sp->u_sense.cmd_sense, sp->sense_count);
1708                         if (sp->ux_errno == 0)
1709                                 sp->ux_errno = EIO;
1710                 }
1711         }
1712
1713         if (usalp->verbose > 0 && usalp->debug > 0) {
1714 #ifdef  SG_GET_BUFSIZE
1715                 fprintf((FILE *)usalp->errfile,
1716                                 "status: 0x%08X pack_len: %d, reply_len: %d pack_id: %d result: %d wn: %d gn: %d cdb_len: %d sense_len: %d sense[0]: %02X\n",
1717                                 GETINT(sgp->hd.sg_cmd_status),
1718                                 GETINT(sgp->hd.pack_len),
1719                                 GETINT(sgp->hd.reply_len),
1720                                 GETINT(sgp->hd.pack_id),
1721                                 GETINT(sgp->hd.result),
1722                                 sgp->hd.want_new,
1723                                 sgp->hd.grant_new,
1724                                 sgp->hd.cdb_len,
1725                                 sgp->hd.sense_len,
1726                                 sgp->hd.sense_buffer[0]);
1727 #else
1728                 fprintf((FILE *)usalp->errfile,
1729                                 "pack_len: %d, reply_len: %d pack_id: %d result: %d sense[0]: %02X\n",
1730                                 GETINT(sgp->hd.pack_len),
1731                                 GETINT(sgp->hd.reply_len),
1732                                 GETINT(sgp->hd.pack_id),
1733                                 GETINT(sgp->hd.result),
1734                                 sgp->hd.sense_buffer[0]);
1735 #endif
1736 #ifdef  DEBUG
1737                 fprintf((FILE *)usalp->errfile, "sense: ");
1738                 for (i = 0; i < 16; i++)
1739                         fprintf((FILE *)usalp->errfile, "%02X ", sgp->hd.sense_buffer[i]);
1740                 fprintf((FILE *)usalp->errfile, "\n");
1741 #endif
1742         }
1743
1744         if (sp->timeout != usalp->deftimeout)
1745                 sg_settimeout(f, usalp->deftimeout);
1746         return (0);
1747 };
1748
1749 #define HAVE_NAT_NAMES
1750 static char * usalo_natname(SCSI *usalp, int busno, int tgt, int tlun) {
1751         if (busno >= MAX_SCG || tgt >= MAX_TGT || tlun >= MAX_LUN)
1752                 return "BADID";
1753         return usallocal(usalp)->filenames[busno][tgt][tlun];
1754 }