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