xref: /illumos-gate/usr/src/uts/common/io/scsi/targets/st.c (revision 43d18f1c320355e93c47399bea0b2e022fe06364)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 /*
30  * SCSI	 SCSA-compliant and not-so-DDI-compliant Tape Driver
31  */
32 
33 #if defined(lint) && !defined(DEBUG)
34 #define	DEBUG	1
35 #endif
36 
37 #include <sys/modctl.h>
38 #include <sys/scsi/scsi.h>
39 #include <sys/mtio.h>
40 #include <sys/scsi/targets/stdef.h>
41 #include <sys/file.h>
42 #include <sys/stat.h>
43 #include <sys/kstat.h>
44 #include <sys/ddidmareq.h>
45 #include <sys/ddi.h>
46 #include <sys/sunddi.h>
47 
48 #define	IOSP	KSTAT_IO_PTR(un->un_stats)
49 /*
50  * stats maintained only for reads/writes as commands
51  * like rewind etc skew the wait/busy times
52  */
53 #define	IS_RW(bp) 	((bp)->b_bcount > 0)
54 #define	ST_DO_KSTATS(bp, kstat_function) \
55 	if ((bp != un->un_sbufp) && un->un_stats && IS_RW(bp)) { \
56 		kstat_function(IOSP); \
57 	}
58 
59 #define	ST_DO_ERRSTATS(un, x)  \
60 	if (un->un_errstats) { \
61 		struct st_errstats *stp; \
62 		stp = (struct st_errstats *)un->un_errstats->ks_data; \
63 		stp->x.value.ul++; \
64 	}
65 
66 #define	FILL_SCSI1_LUN(devp, pkt) 					\
67 	if ((devp)->sd_inq->inq_ansi == 0x1) {				\
68 		int _lun;						\
69 		_lun = ddi_prop_get_int(DDI_DEV_T_ANY, (devp)->sd_dev,	\
70 		    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_LUN, 0);		\
71 		if (_lun > 0) {						\
72 			((union scsi_cdb *)(pkt)->pkt_cdbp)->scc_lun =	\
73 			    _lun;					\
74 		}							\
75 	}
76 
77 /*
78  * get an available contig mem header, cp.
79  * when big_enough is true, we will return NULL, if no big enough
80  * contig mem is found.
81  * when big_enough is false, we will try to find cp containing big
82  * enough contig mem. if not found, we will ruturn the last cp available.
83  *
84  * used by st_get_contig_mem()
85  */
86 #define	ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough) {		\
87 	struct contig_mem *tmp_cp = NULL;				\
88 	for ((cp) = (un)->un_contig_mem;				\
89 	    (cp) != NULL;						\
90 	    tmp_cp = (cp), (cp) = (cp)->cm_next) { 			\
91 		if (((cp)->cm_len >= (len)) || 				\
92 		    (!(big_enough) && ((cp)->cm_next == NULL))) { 	\
93 			if (tmp_cp == NULL) { 				\
94 				(un)->un_contig_mem = (cp)->cm_next; 	\
95 			} else { 					\
96 				tmp_cp->cm_next = (cp)->cm_next; 	\
97 			} 						\
98 			(cp)->cm_next = NULL; 				\
99 			(un)->un_contig_mem_available_num--; 		\
100 			break; 						\
101 		} 							\
102 	} 								\
103 }
104 
105 #define	ST_NUM_MEMBERS(array)	(sizeof (array) / sizeof (array[0]))
106 
107 /*
108  * Global External Data Definitions
109  */
110 extern struct scsi_key_strings scsi_cmds[];
111 
112 /*
113  * Local Static Data
114  */
115 static void *st_state;
116 static char *st_label = "st";
117 
118 #if defined(__i386) || defined(__amd64)
119 /*
120  * We need to use below DMA attr to alloc physically contiguous
121  * memory to do I/O in big block size
122  */
123 static ddi_dma_attr_t st_contig_mem_dma_attr = {
124 	DMA_ATTR_V0,    /* version number */
125 	0x0,		/* lowest usable address */
126 	0xFFFFFFFFull,  /* high DMA address range */
127 	0xFFFFFFFFull,  /* DMA counter register */
128 	1,		/* DMA address alignment */
129 	1,		/* DMA burstsizes */
130 	1,		/* min effective DMA size */
131 	0xFFFFFFFFull,  /* max DMA xfer size */
132 	0xFFFFFFFFull,  /* segment boundary */
133 	1,		/* s/g list length */
134 	1,		/* granularity of device */
135 	0		/* DMA transfer flags */
136 };
137 
138 static ddi_device_acc_attr_t st_acc_attr = {
139 	DDI_DEVICE_ATTR_V0,
140 	DDI_NEVERSWAP_ACC,
141 	DDI_STRICTORDER_ACC
142 };
143 
144 /* set limitation for the number of contig_mem */
145 static int st_max_contig_mem_num = ST_MAX_CONTIG_MEM_NUM;
146 #endif
147 
148 /*
149  * Tunable parameters
150  *
151  * DISCLAIMER
152  * ----------
153  * These parameters are intended for use only in system testing; if you use
154  * them in production systems, you do so at your own risk. Altering any
155  * variable not listed below may cause unpredictable system behavior.
156  *
157  * st_check_media_time
158  *
159  *   Three second state check
160  *
161  * st_allow_large_xfer
162  *
163  *   Gated with ST_NO_RECSIZE_LIMIT
164  *
165  *   0 - Transfers larger than 64KB will not be allowed
166  *       regardless of the setting of ST_NO_RECSIZE_LIMIT
167  *   1 - Transfers larger than 64KB will be allowed
168  *       if ST_NO_RECSIZE_LIMIT is TRUE for the drive
169  *
170  * st_report_soft_errors_on_close
171  *
172  *  Gated with ST_SOFT_ERROR_REPORTING
173  *
174  *  0 - Errors will not be reported on close regardless
175  *      of the setting of ST_SOFT_ERROR_REPORTING
176  *
177  *  1 - Errors will be reported on close if
178  *      ST_SOFT_ERROR_REPORTING is TRUE for the drive
179  */
180 static int st_selection_retry_count = ST_SEL_RETRY_COUNT;
181 static int st_retry_count	= ST_RETRY_COUNT;
182 
183 static int st_io_time		= ST_IO_TIME;
184 static int st_long_timeout_x	= ST_LONG_TIMEOUT_X;
185 
186 static int st_space_time	= ST_SPACE_TIME;
187 static int st_long_space_time_x	= ST_LONG_SPACE_TIME_X;
188 
189 static int st_error_level	= SCSI_ERR_RETRYABLE;
190 static int st_check_media_time	= 3000000;	/* 3 Second State Check */
191 
192 static int st_max_throttle	= ST_MAX_THROTTLE;
193 
194 static clock_t st_wait_cmds_complete = ST_WAIT_CMDS_COMPLETE;
195 
196 static int st_allow_large_xfer = 1;
197 static int st_report_soft_errors_on_close = 1;
198 
199 /*
200  * End of tunable parameters list
201  */
202 
203 
204 
205 /*
206  * Asynchronous I/O and persistent errors, refer to PSARC/1995/228
207  *
208  * Asynchronous I/O's main offering is that it is a non-blocking way to do
209  * reads and writes.  The driver will queue up all the requests it gets and
210  * have them ready to transport to the HBA.  Unfortunately, we cannot always
211  * just ship the I/O requests to the HBA, as there errors and exceptions
212  * that may happen when we don't want the HBA to continue.  Therein comes
213  * the flush-on-errors capability.  If the HBA supports it, then st will
214  * send in st_max_throttle I/O requests at the same time.
215  *
216  * Persistent errors : This was also reasonably simple.  In the interrupt
217  * routines, if there was an error or exception (FM, LEOT, media error,
218  * transport error), the persistent error bits are set and shuts everything
219  * down, but setting the throttle to zero.  If we hit and exception in the
220  * HBA, and flush-on-errors were set, we wait for all outstanding I/O's to
221  * come back (with CMD_ABORTED), then flush all bp's in the wait queue with
222  * the appropriate error, and this will preserve order. Of course, depending
223  * on the exception we have to show a zero read or write before we show
224  * errors back to the application.
225  */
226 
227 extern const int st_ndrivetypes;	/* defined in st_conf.c */
228 extern const struct st_drivetype st_drivetypes[];
229 
230 #ifdef STDEBUG
231 static int st_soft_error_report_debug = 0;
232 static int st_debug = 0;
233 #endif
234 
235 #define	ST_MT02_NAME	"Emulex  MT02 QIC-11/24  "
236 
237 static const struct driver_minor_data {
238 	char	*name;
239 	int	minor;
240 } st_minor_data[] = {
241 	/*
242 	 * The top 4 entries are for the default densities,
243 	 * don't alter their position.
244 	 */
245 	{"",	0},
246 	{"n",	MT_NOREWIND},
247 	{"b",	MT_BSD},
248 	{"bn",	MT_NOREWIND | MT_BSD},
249 	{"l",	MT_DENSITY1},
250 	{"m",	MT_DENSITY2},
251 	{"h",	MT_DENSITY3},
252 	{"c",	MT_DENSITY4},
253 	{"u",	MT_DENSITY4},
254 	{"ln",	MT_DENSITY1 | MT_NOREWIND},
255 	{"mn",	MT_DENSITY2 | MT_NOREWIND},
256 	{"hn",	MT_DENSITY3 | MT_NOREWIND},
257 	{"cn",	MT_DENSITY4 | MT_NOREWIND},
258 	{"un",	MT_DENSITY4 | MT_NOREWIND},
259 	{"lb",	MT_DENSITY1 | MT_BSD},
260 	{"mb",	MT_DENSITY2 | MT_BSD},
261 	{"hb",	MT_DENSITY3 | MT_BSD},
262 	{"cb",	MT_DENSITY4 | MT_BSD},
263 	{"ub",	MT_DENSITY4 | MT_BSD},
264 	{"lbn",	MT_DENSITY1 | MT_NOREWIND | MT_BSD},
265 	{"mbn",	MT_DENSITY2 | MT_NOREWIND | MT_BSD},
266 	{"hbn",	MT_DENSITY3 | MT_NOREWIND | MT_BSD},
267 	{"cbn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD},
268 	{"ubn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD}
269 };
270 
271 /* strings used in many debug and warning messages */
272 static const char wr_str[]  = "write";
273 static const char rd_str[]  = "read";
274 static const char wrg_str[] = "writing";
275 static const char rdg_str[] = "reading";
276 
277 /* default density offsets in the table above */
278 #define	DEF_BLANK	0
279 #define	DEF_NOREWIND	1
280 #define	DEF_BSD		2
281 #define	DEF_BSD_NR	3
282 
283 /* Sense Key, ASC/ASCQ for which tape ejection is needed */
284 
285 static struct tape_failure_code {
286 	uchar_t key;
287 	uchar_t add_code;
288 	uchar_t qual_code;
289 } st_tape_failure_code[] = {
290 	{ KEY_HARDWARE_ERROR, 0x15, 0x01},
291 	{ KEY_HARDWARE_ERROR, 0x44, 0x00},
292 	{ KEY_HARDWARE_ERROR, 0x53, 0x00},
293 	{ KEY_HARDWARE_ERROR, 0x53, 0x01},
294 	{ KEY_NOT_READY, 0x53, 0x00},
295 	{ 0xff}
296 };
297 
298 /*  clean bit position and mask */
299 
300 static struct cln_bit_position {
301 	ushort_t cln_bit_byte;
302 	uchar_t cln_bit_mask;
303 } st_cln_bit_position[] = {
304 	{ 21, 0x08},
305 	{ 70, 0xc0},
306 	{ 18, 0x81}  /* 80 bit indicates in bit mode, 1 bit clean light is on */
307 };
308 
309 /*
310  * Configuration Data:
311  *
312  * Device driver ops vector
313  */
314 static int st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p);
315 static int st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p);
316 static int st_read(dev_t  dev,  struct   uio   *uio_p,   cred_t *cred_p);
317 static int st_write(dev_t  dev,  struct  uio   *uio_p,   cred_t *cred_p);
318 static int st_open(dev_t  *devp,  int  flag,  int  otyp,  cred_t *cred_p);
319 static int st_close(dev_t  dev,  int  flag,  int  otyp,  cred_t *cred_p);
320 static int st_strategy(struct buf *bp);
321 static int st_ioctl(dev_t dev, int cmd, intptr_t arg, int  flag,
322 	cred_t *cred_p, int *rval_p);
323 extern int nulldev(), nodev();
324 
325 static struct cb_ops st_cb_ops = {
326 	st_open,			/* open */
327 	st_close,		/* close */
328 	st_strategy,		/* strategy */
329 	nodev,			/* print */
330 	nodev,			/* dump */
331 	st_read,		/* read */
332 	st_write,		/* write */
333 	st_ioctl,		/* ioctl */
334 	nodev,			/* devmap */
335 	nodev,			/* mmap */
336 	nodev,			/* segmap */
337 	nochpoll,		/* poll */
338 	ddi_prop_op,		/* cb_prop_op */
339 	0,			/* streamtab  */
340 	D_64BIT | D_MP | D_NEW | D_HOTPLUG,	/* Driver compatibility flag */
341 	CB_REV,			/* cb_rev */
342 	st_aread, 		/* async I/O read entry point */
343 	st_awrite		/* async I/O write entry point */
344 
345 };
346 
347 static int stinfo(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg,
348 		void **result);
349 static int st_probe(dev_info_t *dev);
350 static int st_attach(dev_info_t *dev, ddi_attach_cmd_t cmd);
351 static int st_detach(dev_info_t *dev, ddi_detach_cmd_t cmd);
352 
353 static struct dev_ops st_ops = {
354 	DEVO_REV,		/* devo_rev, */
355 	0,			/* refcnt  */
356 	stinfo,			/* info */
357 	nulldev,		/* identify */
358 	st_probe,		/* probe */
359 	st_attach,		/* attach */
360 	st_detach,		/* detach */
361 	nodev,			/* reset */
362 	&st_cb_ops,		/* driver operations */
363 	(struct bus_ops *)0,	/* bus operations */
364 	nulldev			/* power */
365 };
366 
367 /*
368  * Local Function Declarations
369  */
370 static void st_clean_print(dev_info_t *dev, char *label, uint_t level,
371 	char *title, char *data, int len);
372 static int st_doattach(struct scsi_device *devp, int (*canwait)());
373 static void st_known_tape_type(struct scsi_tape *un);
374 static int st_get_conf_from_st_dot_conf(struct scsi_tape *, char *,
375     struct st_drivetype *);
376 static int st_get_conf_from_st_conf_dot_c(struct scsi_tape *, char *,
377     struct st_drivetype *);
378 static int st_get_default_conf(struct scsi_tape *, char *,
379     struct st_drivetype *);
380 static int st_rw(dev_t dev, struct uio *uio, int flag);
381 static int st_arw(dev_t dev, struct aio_req *aio, int flag);
382 static int st_find_eom(dev_t dev);
383 static int st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag);
384 static int st_ioctl_cmd(dev_t dev, struct uscsi_cmd *,
385 	enum uio_seg, enum uio_seg, enum uio_seg);
386 static int st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag);
387 static void st_start(struct scsi_tape *un);
388 static int st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
389     clock_t timeout_interval);
390 static int st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
391     clock_t timeout_interval);
392 static int st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp);
393 static void st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp);
394 static void st_init(struct scsi_tape *un);
395 static void st_make_cmd(struct scsi_tape *un, struct buf *bp,
396     int (*func)(caddr_t));
397 static void st_make_uscsi_cmd(struct scsi_tape *, struct uscsi_cmd *,
398     struct buf *bp, int (*func)(caddr_t));
399 static void st_intr(struct scsi_pkt *pkt);
400 static void st_set_state(struct scsi_tape *un);
401 static void st_test_append(struct buf *bp);
402 static int st_runout(caddr_t);
403 static int st_cmd(dev_t dev, int com, int count, int wait);
404 static int st_set_compression(struct scsi_tape *un);
405 static int st_write_fm(dev_t dev, int wfm);
406 static int st_determine_generic(dev_t dev);
407 static int st_determine_density(dev_t dev, int rw);
408 static int st_get_density(dev_t dev);
409 static int st_set_density(dev_t dev);
410 static int st_loadtape(dev_t dev);
411 static int st_modesense(struct scsi_tape *un);
412 static int st_modeselect(struct scsi_tape *un);
413 static int st_handle_incomplete(struct scsi_tape *un, struct buf *bp);
414 static int st_wrongtapetype(struct scsi_tape *un);
415 static int st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt);
416 static int st_handle_sense(struct scsi_tape *un, struct buf *bp);
417 static int st_handle_autosense(struct scsi_tape *un, struct buf *bp);
418 static int st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
419 	struct scsi_status *);
420 static int st_report_soft_errors(dev_t dev, int flag);
421 static void st_delayed_cv_broadcast(void *arg);
422 static int st_check_media(dev_t dev, enum mtio_state state);
423 static int st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
424 static void st_intr_restart(void *arg);
425 static void st_start_restart(void *arg);
426 static int st_gen_mode_sense(struct scsi_tape *un, int page,
427     struct seq_mode *page_data, int page_size);
428 static int st_change_block_size(dev_t dev, uint32_t nblksz);
429 static int st_gen_mode_select(struct scsi_tape *un, struct seq_mode *page_data,
430     int page_size);
431 static int st_tape_init(dev_t dev);
432 static void st_flush(struct scsi_tape *un);
433 static void st_set_pe_errno(struct scsi_tape *un);
434 static void st_hba_unflush(struct scsi_tape *un);
435 static void st_turn_pe_on(struct scsi_tape *un);
436 static void st_turn_pe_off(struct scsi_tape *un);
437 static void st_set_pe_flag(struct scsi_tape *un);
438 static void st_clear_pe(struct scsi_tape *un);
439 static void st_wait_for_io(struct scsi_tape *un);
440 static int st_set_devconfig_page(struct scsi_tape *un, int compression_on);
441 static int st_set_datacomp_page(struct scsi_tape *un, int compression_on);
442 static int st_tape_reservation_init(dev_t dev);
443 static int st_reserve_release(dev_t dev, int command);
444 static int st_take_ownership(dev_t dev);
445 static int st_check_asc_ascq(struct scsi_tape *un);
446 static int st_check_clean_bit(dev_t dev);
447 static int st_check_alert_clean_bit(dev_t dev);
448 static int st_check_sequential_clean_bit(dev_t dev);
449 static int st_check_sense_clean_bit(dev_t dev);
450 static int st_clear_unit_attentions(dev_t dev_instance, int max_trys);
451 static void st_calculate_timeouts(struct scsi_tape *un);
452 
453 #if defined(__i386) || defined(__amd64)
454 /*
455  * routines for I/O in big block size
456  */
457 static void st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp);
458 static struct contig_mem *st_get_contig_mem(struct scsi_tape *un, size_t len,
459     int alloc_flags);
460 static int st_bigblk_xfer_done(struct buf *bp);
461 static struct buf *st_get_bigblk_bp(struct buf *bp);
462 #endif
463 
464 /*
465  * error statistics create/update functions
466  */
467 static int st_create_errstats(struct scsi_tape *, int);
468 static void st_uscsi_minphys(struct buf *bp);
469 static int st_validate_tapemarks(struct scsi_tape *un, int fileno, daddr_t bn);
470 
471 #ifdef STDEBUG
472 static void st_debug_cmds(struct scsi_tape *un, int com, int count, int wait);
473 static char *st_dev_name(dev_t dev);
474 #endif /* STDEBUG */
475 
476 #if !defined(lint)
477 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", scsi_pkt buf uio scsi_cdb))
478 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", scsi_extended_sense scsi_status))
479 _NOTE(SCHEME_PROTECTS_DATA("stable data", scsi_device))
480 _NOTE(DATA_READABLE_WITHOUT_LOCK(st_drivetype scsi_address))
481 #endif
482 
483 /*
484  * autoconfiguration routines.
485  */
486 char _depends_on[] = "misc/scsi";
487 
488 static struct modldrv modldrv = {
489 	&mod_driverops,		/* Type of module. This one is a driver */
490 	"SCSI tape Driver %I%", /* Name of the module. */
491 	&st_ops			/* driver ops */
492 };
493 
494 static struct modlinkage modlinkage = {
495 	MODREV_1, &modldrv, NULL
496 };
497 
498 /*
499  * Notes on Post Reset Behavior in the tape driver:
500  *
501  * When the tape drive is opened, the driver  attempts  to make sure that
502  * the tape head is positioned exactly where it was left when it was last
503  * closed  provided  the  medium  is not  changed.  If the tape  drive is
504  * opened in O_NDELAY mode, the repositioning  (if necessary for any loss
505  * of position due to reset) will happen when the first tape operation or
506  * I/O occurs.  The repositioning (if required) may not be possible under
507  * certain situations such as when the device firmware not able to report
508  * the medium  change in the REQUEST  SENSE data  because of a reset or a
509  * misbehaving  bus  not  allowing  the  reposition  to  happen.  In such
510  * extraordinary  situations, where the driver fails to position the head
511  * at its  original  position,  it will fail the open the first  time, to
512  * save the applications from overwriting the data.  All further attempts
513  * to open the tape device will result in the driver  attempting  to load
514  * the  tape at BOT  (beginning  of  tape).  Also a  warning  message  to
515  * indicate  that further  attempts to open the tape device may result in
516  * the tape being  loaded at BOT will be printed on the  console.  If the
517  * tape  device is opened  in  O_NDELAY  mode,  failure  to  restore  the
518  * original tape head  position,  will result in the failure of the first
519  * tape  operation  or I/O,  Further,  the  driver  will  invalidate  its
520  * internal tape position  which will  necessitate  the  applications  to
521  * validate the position by using either a tape  positioning  ioctl (such
522  * as MTREW) or closing and reopening the tape device.
523  *
524  */
525 
526 int
527 _init(void)
528 {
529 	int e;
530 
531 	if (((e = ddi_soft_state_init(&st_state,
532 	    sizeof (struct scsi_tape), ST_MAXUNIT)) != 0)) {
533 		return (e);
534 	}
535 
536 	if ((e = mod_install(&modlinkage)) != 0) {
537 		ddi_soft_state_fini(&st_state);
538 	}
539 
540 	return (e);
541 }
542 
543 int
544 _fini(void)
545 {
546 	int e;
547 
548 	if ((e = mod_remove(&modlinkage)) != 0) {
549 		return (e);
550 	}
551 
552 	ddi_soft_state_fini(&st_state);
553 
554 	return (e);
555 }
556 
557 int
558 _info(struct modinfo *modinfop)
559 {
560 	return (mod_info(&modlinkage, modinfop));
561 }
562 
563 
564 static int
565 st_probe(dev_info_t *devi)
566 {
567 	int instance;
568 	struct scsi_device *devp;
569 	int rval;
570 
571 #if !defined(__sparc)
572 	char    *tape_prop;
573 	int	tape_prop_len;
574 #endif
575 
576 	/* If self identifying device */
577 	if (ddi_dev_is_sid(devi) == DDI_SUCCESS) {
578 		return (DDI_PROBE_DONTCARE);
579 	}
580 
581 #if !defined(__sparc)
582 	/*
583 	 * Since some x86 HBAs have devnodes that look like SCSI as
584 	 * far as we can tell but aren't really SCSI (DADK, like mlx)
585 	 * we check for the presence of the "tape" property.
586 	 */
587 	if (ddi_prop_op(DDI_DEV_T_NONE, devi, PROP_LEN_AND_VAL_ALLOC,
588 	    DDI_PROP_CANSLEEP, "tape",
589 	    (caddr_t)&tape_prop, &tape_prop_len) != DDI_PROP_SUCCESS) {
590 		return (DDI_PROBE_FAILURE);
591 	}
592 	if (strncmp(tape_prop, "sctp", tape_prop_len) != 0) {
593 		kmem_free(tape_prop, tape_prop_len);
594 		return (DDI_PROBE_FAILURE);
595 	}
596 	kmem_free(tape_prop, tape_prop_len);
597 #endif
598 
599 	devp = ddi_get_driver_private(devi);
600 	instance = ddi_get_instance(devi);
601 
602 	if (ddi_get_soft_state(st_state, instance) != NULL) {
603 		return (DDI_PROBE_PARTIAL);
604 	}
605 
606 
607 	/*
608 	 * Turn around and call probe routine to see whether
609 	 * we actually have a tape at this SCSI nexus.
610 	 */
611 	if (scsi_probe(devp, NULL_FUNC) == SCSIPROBE_EXISTS) {
612 
613 		/*
614 		 * In checking the whole inq_dtype byte we are looking at both
615 		 * the Peripheral Qualifier and the Peripheral Device Type.
616 		 * For this driver we are only interested in sequential devices
617 		 * that are connected or capable if connecting to this logical
618 		 * unit.
619 		 */
620 		if (devp->sd_inq->inq_dtype ==
621 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
622 			ST_DEBUG6(devi, st_label, SCSI_DEBUG,
623 			    "probe exists\n");
624 			rval = DDI_PROBE_SUCCESS;
625 		} else {
626 			rval = DDI_PROBE_FAILURE;
627 		}
628 	} else {
629 		ST_DEBUG6(devi, st_label, SCSI_DEBUG,
630 		    "probe failure: nothing there\n");
631 		rval = DDI_PROBE_FAILURE;
632 	}
633 	scsi_unprobe(devp);
634 	return (rval);
635 }
636 
637 static int
638 st_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
639 {
640 	int 	instance;
641 	int	wide;
642 	int 	dev_instance;
643 	int	ret_status;
644 	struct	scsi_device *devp;
645 	int	node_ix;
646 	struct	scsi_tape *un;
647 
648 	devp = ddi_get_driver_private(devi);
649 	instance = ddi_get_instance(devi);
650 
651 	switch (cmd) {
652 		case DDI_ATTACH:
653 			if (st_doattach(devp, SLEEP_FUNC) == DDI_FAILURE) {
654 				return (DDI_FAILURE);
655 			}
656 			break;
657 		case DDI_RESUME:
658 			/*
659 			 * Suspend/Resume
660 			 *
661 			 * When the driver suspended, there might be
662 			 * outstanding cmds and therefore we need to
663 			 * reset the suspended flag and resume the scsi
664 			 * watch thread and restart commands and timeouts
665 			 */
666 
667 			if (!(un = ddi_get_soft_state(st_state, instance))) {
668 				return (DDI_FAILURE);
669 			}
670 			dev_instance = ((un->un_dev == 0) ? MTMINOR(instance) :
671 			    un->un_dev);
672 
673 			mutex_enter(ST_MUTEX);
674 
675 			un->un_throttle = un->un_max_throttle;
676 			un->un_tids_at_suspend = 0;
677 			un->un_pwr_mgmt = ST_PWR_NORMAL;
678 
679 			if (un->un_swr_token) {
680 				scsi_watch_resume(un->un_swr_token);
681 			}
682 
683 			/*
684 			 * Restart timeouts
685 			 */
686 			if ((un->un_tids_at_suspend & ST_DELAY_TID) != 0) {
687 				mutex_exit(ST_MUTEX);
688 				un->un_delay_tid =
689 				    timeout(st_delayed_cv_broadcast, un,
690 					drv_usectohz((clock_t)
691 					MEDIA_ACCESS_DELAY));
692 				mutex_enter(ST_MUTEX);
693 			}
694 
695 			if (un->un_tids_at_suspend & ST_HIB_TID) {
696 				mutex_exit(ST_MUTEX);
697 				un->un_hib_tid = timeout(st_intr_restart, un,
698 				    ST_STATUS_BUSY_TIMEOUT);
699 				mutex_enter(ST_MUTEX);
700 			}
701 
702 			ret_status = st_clear_unit_attentions(dev_instance, 5);
703 
704 			/*
705 			 * now check if we need to restore the tape position
706 			 */
707 			if ((un->un_suspend_fileno > 0) ||
708 			    (un->un_suspend_blkno > 0)) {
709 				if (ret_status != 0) {
710 					/*
711 					 * tape didn't get good TUR
712 					 * just print out error messages
713 					 */
714 					scsi_log(ST_DEVINFO, st_label, CE_WARN,
715 					    "st_attach-RESUME: tape failure "
716 					    " tape position will be lost");
717 				} else {
718 					/* this prints errors */
719 					(void) st_validate_tapemarks(un,
720 					    un->un_suspend_fileno,
721 					    un->un_suspend_blkno);
722 				}
723 				/*
724 				 * there are no retries, if there is an error
725 				 * we don't know if the tape has changed
726 				 */
727 				un->un_suspend_fileno = 0;
728 				un->un_suspend_blkno = 0;
729 			}
730 
731 			/* now we are ready to start up any queued I/Os */
732 			if (un->un_ncmds || un->un_quef) {
733 				st_start(un);
734 			}
735 
736 			cv_broadcast(&un->un_suspend_cv);
737 			mutex_exit(ST_MUTEX);
738 			return (DDI_SUCCESS);
739 
740 		default:
741 			return (DDI_FAILURE);
742 	}
743 
744 	un = ddi_get_soft_state(st_state, instance);
745 
746 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
747 	    "st_attach: instance=%x\n", instance);
748 
749 	/*
750 	 * find the drive type for this target
751 	 */
752 	st_known_tape_type(un);
753 
754 	for (node_ix = 0; node_ix < ST_NUM_MEMBERS(st_minor_data); node_ix++) {
755 		int minor;
756 		char *name;
757 
758 		name  = st_minor_data[node_ix].name;
759 		minor = st_minor_data[node_ix].minor;
760 
761 		/*
762 		 * For default devices set the density to the
763 		 * preferred default density for this device.
764 		 */
765 		if (node_ix <= DEF_BSD_NR) {
766 			minor |= un->un_dp->default_density;
767 		}
768 		minor |= MTMINOR(instance);
769 
770 		if (ddi_create_minor_node(devi, name, S_IFCHR, minor,
771 		    DDI_NT_TAPE, NULL) == DDI_SUCCESS) {
772 			continue;
773 		}
774 
775 		ddi_remove_minor_node(devi, NULL);
776 		if (un) {
777 			cv_destroy(&un->un_clscv);
778 			cv_destroy(&un->un_sbuf_cv);
779 			cv_destroy(&un->un_queue_cv);
780 			cv_destroy(&un->un_state_cv);
781 			cv_destroy(&un->un_suspend_cv);
782 			cv_destroy(&un->un_tape_busy_cv);
783 
784 			if (un->un_sbufp) {
785 				freerbuf(un->un_sbufp);
786 			}
787 			if (un->un_uscsi_rqs_buf) {
788 				kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
789 			}
790 			if (un->un_mspl) {
791 				ddi_iopb_free((caddr_t)un->un_mspl);
792 			}
793 			scsi_destroy_pkt(un->un_rqs);
794 			scsi_free_consistent_buf(un->un_rqs_bp);
795 			ddi_soft_state_free(st_state, instance);
796 			devp->sd_private = NULL;
797 			devp->sd_sense = NULL;
798 
799 		}
800 		ddi_prop_remove_all(devi);
801 		return (DDI_FAILURE);
802 	}
803 
804 	/*
805 	 * Add a zero-length attribute to tell the world we support
806 	 * kernel ioctls (for layered drivers)
807 	 */
808 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
809 	    DDI_KERNEL_IOCTL, NULL, 0);
810 
811 	ddi_report_dev((dev_info_t *)devi);
812 
813 	/*
814 	 * If it's a SCSI-2 tape drive which supports wide,
815 	 * tell the host adapter to use wide.
816 	 */
817 	wide = ((devp->sd_inq->inq_rdf == RDF_SCSI2) &&
818 	    (devp->sd_inq->inq_wbus16 || devp->sd_inq->inq_wbus32)) ?
819 		1 : 0;
820 
821 	if (scsi_ifsetcap(ROUTE, "wide-xfer", wide, 1) == 1) {
822 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
823 		    "Wide Transfer %s\n", wide ? "enabled" : "disabled");
824 	}
825 
826 	/*
827 	 * enable autorequest sense; keep the rq packet around in case
828 	 * the autorequest sense fails because of a busy condition
829 	 * do a getcap first in case the capability is not variable
830 	 */
831 	if (scsi_ifgetcap(ROUTE, "auto-rqsense", 1) == 1) {
832 		un->un_arq_enabled = 1;
833 	} else {
834 		un->un_arq_enabled =
835 		    ((scsi_ifsetcap(ROUTE, "auto-rqsense", 1, 1) == 1) ? 1 : 0);
836 	}
837 
838 
839 	ST_DEBUG(devi, st_label, SCSI_DEBUG, "auto request sense %s\n",
840 		(un->un_arq_enabled ? "enabled" : "disabled"));
841 
842 	un->un_untagged_qing =
843 	    (scsi_ifgetcap(ROUTE, "untagged-qing", 0) == 1);
844 
845 	/*
846 	 * XXX - This is just for 2.6.  to tell users that write buffering
847 	 *	has gone away.
848 	 */
849 	if (un->un_arq_enabled && un->un_untagged_qing) {
850 		if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
851 		    "tape-driver-buffering", 0) != 0) {
852 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
853 			    "Write Data Buffering has been depricated. Your "
854 			    "applications should continue to work normally.\n"
855 			    " But, they should  ported to use Asynchronous "
856 			    " I/O\n"
857 			    " For more information, read about "
858 			    " tape-driver-buffering "
859 			    "property in the st(7d) man page\n");
860 		}
861 	}
862 
863 	un->un_max_throttle = un->un_throttle = un->un_last_throttle = 1;
864 	un->un_flush_on_errors = 0;
865 	un->un_mkr_pkt = (struct scsi_pkt *)NULL;
866 
867 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
868 	    "throttle=%x, max_throttle = %x\n",
869 	    un->un_throttle, un->un_max_throttle);
870 
871 	/* initialize persistent errors to nil */
872 	un->un_persistence = 0;
873 	un->un_persist_errors = 0;
874 
875 	/*
876 	 * Get dma-max from HBA driver. If it is not defined, use 64k
877 	 */
878 	un->un_maxdma	= scsi_ifgetcap(&devp->sd_address, "dma-max", 1);
879 	if (un->un_maxdma == -1) {
880 		un->un_maxdma = (64 * 1024);
881 	}
882 
883 	un->un_maxbsize = MAXBSIZE_UNKNOWN;
884 
885 	un->un_mediastate = MTIO_NONE;
886 	un->un_HeadClean  = TAPE_ALERT_SUPPORT_UNKNOWN;
887 
888 	/*
889 	 * initialize kstats
890 	 */
891 	un->un_stats = kstat_create("st", instance, NULL, "tape",
892 			KSTAT_TYPE_IO, 1, KSTAT_FLAG_PERSISTENT);
893 	if (un->un_stats) {
894 		un->un_stats->ks_lock = ST_MUTEX;
895 		kstat_install(un->un_stats);
896 	}
897 	(void) st_create_errstats(un, instance);
898 
899 	return (DDI_SUCCESS);
900 }
901 
902 /*
903  * st_detach:
904  *
905  * we allow a detach if and only if:
906  *	- no tape is currently inserted
907  *	- tape position is at BOT or unknown
908  *		(if it is not at BOT then a no rewind
909  *		device was opened and we have to preserve state)
910  *	- it must be in a closed state : no timeouts or scsi_watch requests
911  *		will exist if it is closed, so we don't need to check for
912  *		them here.
913  */
914 /*ARGSUSED*/
915 static int
916 st_detach(dev_info_t *devi, ddi_detach_cmd_t cmd)
917 {
918 	int 	instance;
919 	int 	dev_instance;
920 	struct scsi_device *devp;
921 	struct scsi_tape *un;
922 	clock_t wait_cmds_complete;
923 
924 	instance = ddi_get_instance(devi);
925 
926 	if (!(un = ddi_get_soft_state(st_state, instance))) {
927 		return (DDI_FAILURE);
928 	}
929 
930 	switch (cmd) {
931 
932 	case DDI_DETACH:
933 		/*
934 		 * Undo what we did in st_attach & st_doattach,
935 		 * freeing resources and removing things we installed.
936 		 * The system framework guarantees we are not active
937 		 * with this devinfo node in any other entry points at
938 		 * this time.
939 		 */
940 
941 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
942 		    "st_detach: instance=%x, un=%p\n", instance,
943 		    (void *)un);
944 
945 		if (((un->un_dp->options & ST_UNLOADABLE) == 0) ||
946 		    (un->un_ncmds != 0) || (un->un_quef != NULL) ||
947 		    (un->un_state != ST_STATE_CLOSED)) {
948 			/*
949 			 * we cannot unload some targets because the
950 			 * inquiry returns junk unless immediately
951 			 * after a reset
952 			 */
953 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
954 			    "cannot unload instance %x\n", instance);
955 			return (DDI_FAILURE);
956 		}
957 
958 		/*
959 		 * if the tape has been removed then we may unload;
960 		 * do a test unit ready and if it returns NOT READY
961 		 * then we assume that it is safe to unload.
962 		 * as a side effect, fileno may be set to -1 if the
963 		 * the test unit ready fails;
964 		 * also un_state may be set to non-closed, so reset it
965 		 */
966 		if ((un->un_dev) &&		/* Been opened since attach */
967 		    ((un->un_fileno > 0) ||	/* Known position not rewound */
968 		    (un->un_blkno != 0))) {	/* Or within first file */
969 			mutex_enter(ST_MUTEX);
970 			/*
971 			 * Send Test Unit Ready in the hopes that if
972 			 * the drive is not in the state we think it is.
973 			 * And the state will be changed so it can be detached.
974 			 * If the command fails to reach the device and
975 			 * the drive was not rewound or unloaded we want
976 			 * to fail the detach till a user command fails
977 			 * where after the detach will succead.
978 			 */
979 			(void) st_cmd(un->un_dev, SCMD_TEST_UNIT_READY,
980 			    0, SYNC_CMD);
981 			/*
982 			 * After TUR un_state may be set to non-closed,
983 			 * so reset it back.
984 			 */
985 			un->un_state = ST_STATE_CLOSED;
986 			mutex_exit(ST_MUTEX);
987 		}
988 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
989 		    "un_status=%x, fileno=%x, blkno=%lx\n",
990 		    un->un_status, un->un_fileno, un->un_blkno);
991 
992 		/*
993 		 * check again:
994 		 * if we are not at BOT then it is not safe to unload
995 		 */
996 		if ((un->un_dev) &&		/* Been opened since attach */
997 		    ((un->un_fileno > 0) ||	/* Known position not rewound */
998 		    (un->un_blkno != 0))) {	/* Or within first file */
999 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1000 			    "cannot detach: fileno=%x, blkno=%lx\n",
1001 			    un->un_fileno, un->un_blkno);
1002 			return (DDI_FAILURE);
1003 		}
1004 
1005 		/*
1006 		 * Just To make sure that we have released the
1007 		 * tape unit .
1008 		 */
1009 		if (un->un_dev && (un->un_rsvd_status & ST_RESERVE) &&
1010 		    !DEVI_IS_DEVICE_REMOVED(devi)) {
1011 			mutex_enter(ST_MUTEX);
1012 			(void) st_cmd(un->un_dev, SCMD_RELEASE, 0, SYNC_CMD);
1013 			mutex_exit(ST_MUTEX);
1014 		}
1015 
1016 		/*
1017 		 * now remove other data structures allocated in st_doattach()
1018 		 */
1019 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1020 		    "destroying/freeing\n");
1021 		cv_destroy(&un->un_clscv);
1022 		cv_destroy(&un->un_sbuf_cv);
1023 		cv_destroy(&un->un_queue_cv);
1024 		cv_destroy(&un->un_suspend_cv);
1025 		cv_destroy(&un->un_tape_busy_cv);
1026 
1027 		if (un->un_hib_tid) {
1028 			(void) untimeout(un->un_hib_tid);
1029 			un->un_hib_tid = 0;
1030 		}
1031 
1032 		if (un->un_delay_tid) {
1033 			(void) untimeout(un->un_delay_tid);
1034 			un->un_delay_tid = 0;
1035 		}
1036 		cv_destroy(&un->un_state_cv);
1037 
1038 #if defined(__i386) || defined(__amd64)
1039 		if (un->un_contig_mem_hdl != NULL) {
1040 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1041 		}
1042 #endif
1043 		if (un->un_sbufp) {
1044 			freerbuf(un->un_sbufp);
1045 		}
1046 		if (un->un_uscsi_rqs_buf) {
1047 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1048 		}
1049 		if (un->un_mspl) {
1050 			ddi_iopb_free((caddr_t)un->un_mspl);
1051 		}
1052 		if (un->un_rqs) {
1053 			scsi_destroy_pkt(un->un_rqs);
1054 			scsi_free_consistent_buf(un->un_rqs_bp);
1055 		}
1056 		if (un->un_mkr_pkt) {
1057 			scsi_destroy_pkt(un->un_mkr_pkt);
1058 		}
1059 		if (un->un_arq_enabled) {
1060 			(void) scsi_ifsetcap(ROUTE, "auto-rqsense", 0, 1);
1061 		}
1062 		if (un->un_dp_size) {
1063 			kmem_free(un->un_dp, un->un_dp_size);
1064 		}
1065 		if (un->un_stats) {
1066 			kstat_delete(un->un_stats);
1067 			un->un_stats = (kstat_t *)0;
1068 		}
1069 		if (un->un_errstats) {
1070 			kstat_delete(un->un_errstats);
1071 			un->un_errstats = (kstat_t *)0;
1072 		}
1073 		devp = ST_SCSI_DEVP;
1074 		ddi_soft_state_free(st_state, instance);
1075 		devp->sd_private = NULL;
1076 		devp->sd_sense = NULL;
1077 		scsi_unprobe(devp);
1078 		ddi_prop_remove_all(devi);
1079 		ddi_remove_minor_node(devi, NULL);
1080 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach done\n");
1081 		return (DDI_SUCCESS);
1082 
1083 	case DDI_SUSPEND:
1084 
1085 		/*
1086 		 * Suspend/Resume
1087 		 *
1088 		 * To process DDI_SUSPEND, we must do the following:
1089 		 *
1090 		 *  - check ddi_removing_power to see if power will be turned
1091 		 *    off. if so, return DDI_FAILURE
1092 		 *  - check if we are already suspended,
1093 		 *    if so, return DDI_FAILURE
1094 		 *  - check if device state is CLOSED,
1095 		 *    if not, return DDI_FAILURE.
1096 		 *  - wait until outstanding operations complete
1097 		 *  - save tape state
1098 		 *  - block new operations
1099 		 *  - cancel pending timeouts
1100 		 *
1101 		 */
1102 
1103 		if (ddi_removing_power(devi))
1104 			return (DDI_FAILURE);
1105 
1106 		mutex_enter(ST_MUTEX);
1107 
1108 		/*
1109 		 * Shouldn't already be suspended, if so return failure
1110 		 */
1111 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
1112 			mutex_exit(ST_MUTEX);
1113 			return (DDI_FAILURE);
1114 		}
1115 		if (un->un_state != ST_STATE_CLOSED) {
1116 			mutex_exit(ST_MUTEX);
1117 			return (DDI_FAILURE);
1118 		}
1119 
1120 		/*
1121 		 * Wait for all outstanding I/O's to complete
1122 		 *
1123 		 * we wait on both ncmds and the wait queue for times
1124 		 * when we are flushing after persistent errors are
1125 		 * flagged, which is when ncmds can be 0, and the
1126 		 * queue can still have I/O's.  This way we preserve
1127 		 * order of biodone's.
1128 		 */
1129 		wait_cmds_complete = ddi_get_lbolt();
1130 		wait_cmds_complete +=
1131 		    st_wait_cmds_complete * drv_usectohz(1000000);
1132 		while (un->un_ncmds || un->un_quef ||
1133 		    (un->un_state == ST_STATE_RESOURCE_WAIT)) {
1134 
1135 			if (cv_timedwait(&un->un_tape_busy_cv, ST_MUTEX,
1136 			    wait_cmds_complete) == -1) {
1137 				/*
1138 				 * Time expired then cancel the command
1139 				 */
1140 				mutex_exit(ST_MUTEX);
1141 				if (scsi_reset(ROUTE, RESET_TARGET) == 0) {
1142 					mutex_enter(ST_MUTEX);
1143 					if (un->un_last_throttle) {
1144 						un->un_throttle =
1145 						    un->un_last_throttle;
1146 					}
1147 					mutex_exit(ST_MUTEX);
1148 					return (DDI_FAILURE);
1149 				} else {
1150 					mutex_enter(ST_MUTEX);
1151 					break;
1152 				}
1153 			}
1154 		}
1155 
1156 		/*
1157 		 * DDI_SUSPEND says that the system "may" power down, we
1158 		 * remember the file and block number before rewinding.
1159 		 * we also need to save state before issuing
1160 		 * any WRITE_FILE_MARK command.
1161 		 */
1162 		if (un->un_fileno < 0) {
1163 			un->un_suspend_fileno = 0;
1164 			un->un_suspend_blkno  = 0;
1165 		} else {
1166 			un->un_suspend_fileno = un->un_fileno;
1167 			un->un_suspend_blkno = un->un_blkno;
1168 		}
1169 		dev_instance = ((un->un_dev == 0) ? MTMINOR(instance) :
1170 		    un->un_dev);
1171 
1172 		/*
1173 		 * Issue a zero write file fmk command to tell the drive to
1174 		 * flush any buffered tape marks
1175 		 */
1176 		(void) st_cmd(dev_instance, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
1177 
1178 		/*
1179 		 * Because not all tape drives correctly implement buffer
1180 		 * flushing with the zero write file fmk command, issue a
1181 		 * synchronous rewind command to force data flushing.
1182 		 * st_validate_tapemarks() will do a rewind during DDI_RESUME
1183 		 * anyway.
1184 		 */
1185 		(void) st_cmd(dev_instance, SCMD_REWIND, 0, SYNC_CMD);
1186 
1187 		/* stop any new operations */
1188 		un->un_pwr_mgmt = ST_PWR_SUSPENDED;
1189 		un->un_throttle = 0;
1190 
1191 		/*
1192 		 * cancel any outstanding timeouts
1193 		 */
1194 		if (un->un_delay_tid) {
1195 			timeout_id_t temp_id = un->un_delay_tid;
1196 			un->un_delay_tid = 0;
1197 			un->un_tids_at_suspend |= ST_DELAY_TID;
1198 			mutex_exit(ST_MUTEX);
1199 			(void) untimeout(temp_id);
1200 			mutex_enter(ST_MUTEX);
1201 		}
1202 
1203 		if (un->un_hib_tid) {
1204 			timeout_id_t temp_id = un->un_hib_tid;
1205 			un->un_hib_tid = 0;
1206 			un->un_tids_at_suspend |= ST_HIB_TID;
1207 			mutex_exit(ST_MUTEX);
1208 			(void) untimeout(temp_id);
1209 			mutex_enter(ST_MUTEX);
1210 		}
1211 
1212 		/*
1213 		 * Suspend the scsi_watch_thread
1214 		 */
1215 		if (un->un_swr_token) {
1216 			opaque_t temp_token = un->un_swr_token;
1217 			mutex_exit(ST_MUTEX);
1218 			scsi_watch_suspend(temp_token);
1219 		} else {
1220 			mutex_exit(ST_MUTEX);
1221 		}
1222 
1223 		return (DDI_SUCCESS);
1224 
1225 	default:
1226 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach failed\n");
1227 		return (DDI_FAILURE);
1228 	}
1229 }
1230 
1231 
1232 /* ARGSUSED */
1233 static int
1234 stinfo(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
1235 {
1236 	dev_t dev;
1237 	struct scsi_tape *un;
1238 	int instance, error;
1239 	switch (infocmd) {
1240 	case DDI_INFO_DEVT2DEVINFO:
1241 		dev = (dev_t)arg;
1242 		instance = MTUNIT(dev);
1243 		if ((un = ddi_get_soft_state(st_state, instance)) == NULL)
1244 			return (DDI_FAILURE);
1245 		*result = (void *) ST_DEVINFO;
1246 		error = DDI_SUCCESS;
1247 		break;
1248 	case DDI_INFO_DEVT2INSTANCE:
1249 		dev = (dev_t)arg;
1250 		instance = MTUNIT(dev);
1251 		*result = (void *)(uintptr_t)instance;
1252 		error = DDI_SUCCESS;
1253 		break;
1254 	default:
1255 		error = DDI_FAILURE;
1256 	}
1257 	return (error);
1258 }
1259 
1260 static int
1261 st_doattach(struct scsi_device *devp, int (*canwait)())
1262 {
1263 	struct scsi_pkt *rqpkt = NULL;
1264 	struct scsi_tape *un = NULL;
1265 	int km_flags = (canwait != NULL_FUNC) ? KM_SLEEP : KM_NOSLEEP;
1266 	int instance;
1267 	struct buf *bp;
1268 
1269 	/*
1270 	 * Call the routine scsi_probe to do some of the dirty work.
1271 	 * If the INQUIRY command succeeds, the field sd_inq in the
1272 	 * device structure will be filled in.
1273 	 */
1274 	ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1275 		"st_doattach(): probing\n");
1276 
1277 	if (scsi_probe(devp, canwait) == SCSIPROBE_EXISTS) {
1278 
1279 		/*
1280 		 * In checking the whole inq_dtype byte we are looking at both
1281 		 * the Peripheral Qualifier and the Peripheral Device Type.
1282 		 * For this driver we are only interested in sequential devices
1283 		 * that are connected or capable if connecting to this logical
1284 		 * unit.
1285 		 */
1286 		if (devp->sd_inq->inq_dtype ==
1287 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
1288 			ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1289 			    "probe exists\n");
1290 		} else {
1291 			/* Something there but not a tape device */
1292 			scsi_unprobe(devp);
1293 			return (DDI_FAILURE);
1294 		}
1295 	} else {
1296 		/* Nothing there */
1297 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1298 		    "probe failure: nothing there\n");
1299 		scsi_unprobe(devp);
1300 		return (DDI_FAILURE);
1301 	}
1302 
1303 	bp = scsi_alloc_consistent_buf(&devp->sd_address, (struct buf *)NULL,
1304 	    SENSE_LENGTH, B_READ, canwait, NULL);
1305 	if (!bp) {
1306 		goto error;
1307 	}
1308 	rqpkt = scsi_init_pkt(&devp->sd_address,
1309 	    (struct scsi_pkt *)NULL, bp, CDB_GROUP0, 1, 0,
1310 	    PKT_CONSISTENT, canwait, NULL);
1311 	if (!rqpkt) {
1312 		goto error;
1313 	}
1314 	devp->sd_sense = (struct scsi_extended_sense *)bp->b_un.b_addr;
1315 	ASSERT(geterror(bp) == NULL);
1316 
1317 	(void) scsi_setup_cdb((union scsi_cdb *)rqpkt->pkt_cdbp,
1318 	    SCMD_REQUEST_SENSE, 0, SENSE_LENGTH, 0);
1319 	FILL_SCSI1_LUN(devp, rqpkt);
1320 
1321 	/*
1322 	 * The actual unit is present.
1323 	 * Now is the time to fill in the rest of our info..
1324 	 */
1325 	instance = ddi_get_instance(devp->sd_dev);
1326 
1327 	if (ddi_soft_state_zalloc(st_state, instance) != DDI_SUCCESS) {
1328 		goto error;
1329 	}
1330 	un = ddi_get_soft_state(st_state, instance);
1331 
1332 	un->un_sbufp = getrbuf(km_flags);
1333 
1334 	un->un_uscsi_rqs_buf = kmem_alloc(SENSE_LENGTH, KM_SLEEP);
1335 
1336 	(void) ddi_iopb_alloc(devp->sd_dev, (ddi_dma_lim_t *)0,
1337 		sizeof (struct seq_mode), (caddr_t *)&un->un_mspl);
1338 
1339 	if (!un->un_sbufp || !un->un_mspl) {
1340 		if (un->un_mspl) {
1341 			ddi_iopb_free((caddr_t)un->un_mspl);
1342 		}
1343 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1344 		    "probe partial failure: no space\n");
1345 		goto error;
1346 	}
1347 
1348 	bzero(un->un_mspl, sizeof (struct seq_mode));
1349 
1350 	cv_init(&un->un_sbuf_cv, NULL, CV_DRIVER, NULL);
1351 	cv_init(&un->un_queue_cv, NULL, CV_DRIVER, NULL);
1352 	cv_init(&un->un_clscv, NULL, CV_DRIVER, NULL);
1353 	cv_init(&un->un_state_cv, NULL, CV_DRIVER, NULL);
1354 #if defined(__i386) || defined(__amd64)
1355 	cv_init(&un->un_contig_mem_cv, NULL, CV_DRIVER, NULL);
1356 #endif
1357 
1358 	/* Initialize power managemnet condition variable */
1359 	cv_init(&un->un_suspend_cv, NULL, CV_DRIVER, NULL);
1360 	cv_init(&un->un_tape_busy_cv, NULL, CV_DRIVER, NULL);
1361 
1362 	rqpkt->pkt_flags |= (FLAG_SENSING | FLAG_HEAD | FLAG_NODISCON);
1363 
1364 	un->un_fileno	= -1;
1365 	rqpkt->pkt_time = st_io_time;
1366 	rqpkt->pkt_comp = st_intr;
1367 	un->un_rqs	= rqpkt;
1368 	un->un_sd	= devp;
1369 	un->un_rqs_bp	= bp;
1370 	un->un_swr_token = (opaque_t)NULL;
1371 	un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
1372 
1373 	un->un_suspend_fileno 	= 0;
1374 	un->un_suspend_blkno 	= 0;
1375 
1376 #if defined(__i386) || defined(__amd64)
1377 	if (ddi_dma_alloc_handle(ST_DEVINFO, &st_contig_mem_dma_attr,
1378 		DDI_DMA_SLEEP, NULL, &un->un_contig_mem_hdl) != DDI_SUCCESS) {
1379 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1380 		    "allocation of contiguous memory dma handle failed!");
1381 		un->un_contig_mem_hdl = NULL;
1382 		goto error;
1383 	}
1384 #endif
1385 
1386 	/*
1387 	 * Since this driver manages devices with "remote" hardware,
1388 	 * i.e. the devices themselves have no "reg" properties,
1389 	 * the SUSPEND/RESUME commands in detach/attach will not be
1390 	 * called by the power management framework unless we request
1391 	 * it by creating a "pm-hardware-state" property and setting it
1392 	 * to value "needs-suspend-resume".
1393 	 */
1394 	if (ddi_prop_update_string(DDI_DEV_T_NONE, devp->sd_dev,
1395 	    "pm-hardware-state", "needs-suspend-resume") !=
1396 	    DDI_PROP_SUCCESS) {
1397 
1398 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1399 		    "ddi_prop_update(\"pm-hardware-state\") failed\n");
1400 		goto error;
1401 	}
1402 
1403 	if (ddi_prop_create(DDI_DEV_T_NONE, devp->sd_dev, DDI_PROP_CANSLEEP,
1404 	    "no-involuntary-power-cycles", NULL, 0) != DDI_PROP_SUCCESS) {
1405 
1406 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1407 		    "ddi_prop_create(\"no-involuntary-power-cycles\") "
1408 		    "failed\n");
1409 		goto error;
1410 	}
1411 
1412 	ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG, "probe success\n");
1413 	return (DDI_SUCCESS);
1414 
1415 error:
1416 	devp->sd_sense = NULL;
1417 
1418 	ddi_remove_minor_node(devp->sd_dev, NULL);
1419 	if (un) {
1420 		if (un->un_mspl) {
1421 			ddi_iopb_free((caddr_t)un->un_mspl);
1422 		}
1423 		if (un->un_sbufp) {
1424 			freerbuf(un->un_sbufp);
1425 		}
1426 		if (un->un_uscsi_rqs_buf) {
1427 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1428 		}
1429 #if defined(__i386) || defined(__amd64)
1430 		if (un->un_contig_mem_hdl != NULL) {
1431 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1432 		}
1433 #endif
1434 		ddi_soft_state_free(st_state, instance);
1435 		devp->sd_private = NULL;
1436 	}
1437 
1438 	if (rqpkt) {
1439 		scsi_destroy_pkt(rqpkt);
1440 	}
1441 
1442 	if (bp) {
1443 		scsi_free_consistent_buf(bp);
1444 	}
1445 
1446 	if (devp->sd_inq) {
1447 		scsi_unprobe(devp);
1448 	}
1449 	return (DDI_FAILURE);
1450 }
1451 
1452 typedef int
1453 (*cfg_functp)(struct scsi_tape *, char *vidpid, struct st_drivetype *);
1454 
1455 static cfg_functp config_functs[] = {
1456 	st_get_conf_from_st_dot_conf,
1457 	st_get_conf_from_st_conf_dot_c,
1458 	st_get_default_conf
1459 };
1460 
1461 
1462 /*
1463  * determine tape type, using tape-config-list or built-in table or
1464  * use a generic tape config entry
1465  */
1466 static void
1467 st_known_tape_type(struct scsi_tape *un)
1468 {
1469 	struct st_drivetype *dp;
1470 	cfg_functp *config_funct;
1471 
1472 	/*
1473 	 * XXX:  Emulex MT-02 (and emulators) predates SCSI-1 and has
1474 	 *	 no vid & pid inquiry data.  So, we provide one.
1475 	 */
1476 	if (ST_INQUIRY->inq_len == 0 ||
1477 		(bcmp("\0\0\0\0\0\0\0\0", ST_INQUIRY->inq_vid, 8) == 0)) {
1478 		(void) strcpy((char *)ST_INQUIRY->inq_vid, ST_MT02_NAME);
1479 	}
1480 
1481 	un->un_dp_size = sizeof (struct st_drivetype);
1482 	dp = kmem_zalloc((size_t)un->un_dp_size, KM_SLEEP);
1483 	un->un_dp = dp;
1484 
1485 	/*
1486 	 * Loop through the configuration methods till one works.
1487 	 */
1488 	for (config_funct = &config_functs[0]; ; config_funct++) {
1489 		if ((*config_funct)(un, ST_INQUIRY->inq_vid, dp)) {
1490 			break;
1491 		}
1492 	}
1493 
1494 	/*
1495 	 * If we didn't just make up this configuration and
1496 	 * all the density codes are the same..
1497 	 * Set Auto Density over ride.
1498 	 */
1499 	if (*config_funct != st_get_default_conf) {
1500 		/*
1501 		 * If this device is one that is configured and all
1502 		 * densities are the same, This saves doing gets and set
1503 		 * that yield nothing.
1504 		 */
1505 		if ((dp->densities[0]) == (dp->densities[1]) &&
1506 		    (dp->densities[0]) == (dp->densities[2]) &&
1507 		    (dp->densities[0]) == (dp->densities[3])) {
1508 
1509 			dp->options |= ST_AUTODEN_OVERRIDE;
1510 		}
1511 	}
1512 
1513 
1514 	/*
1515 	 * Store tape drive characteristics.
1516 	 */
1517 	un->un_status = 0;
1518 	un->un_attached = 1;
1519 	un->un_init_options = dp->options;
1520 
1521 	/* setup operation time-outs based on options */
1522 	st_calculate_timeouts(un);
1523 
1524 	/* make sure if we are supposed to be variable, make it variable */
1525 	if (dp->options & ST_VARIABLE) {
1526 		dp->bsize = 0;
1527 	}
1528 
1529 	scsi_log(ST_DEVINFO, st_label, CE_NOTE, "?<%s>\n", dp->name);
1530 }
1531 
1532 
1533 typedef struct {
1534 	int mask;
1535 	int bottom;
1536 	int top;
1537 	char *name;
1538 } conf_limit;
1539 
1540 static const conf_limit conf_limits[] = {
1541 
1542 	-1,		1,		2,		"conf version",
1543 	-1,		MT_ISTS,	ST_LAST_TYPE,	"drive type",
1544 	-1,		0,		0xffffff,	"block size",
1545 	ST_VALID_OPTS,	0,		ST_VALID_OPTS,	"options",
1546 	-1,		0,		4,		"number of densities",
1547 	-1,		0,		UINT8_MAX,	"density code",
1548 	-1,		0,		3,		"default density",
1549 	-1,		0,		UINT16_MAX,	"non motion timeout",
1550 	-1,		0,		UINT16_MAX,	"I/O timeout",
1551 	-1,		0,		UINT16_MAX,	"space timeout",
1552 	-1,		0,		UINT16_MAX,	"load timeout",
1553 	-1,		0,		UINT16_MAX,	"unload timeout",
1554 	-1,		0,		UINT16_MAX,	"erase timeout",
1555 	0,		0,		0,		NULL
1556 };
1557 
1558 static int
1559 st_validate_conf_data(struct scsi_tape *un, int *list, int list_len,
1560     const char *conf_name)
1561 {
1562 	int dens;
1563 	int ndens;
1564 	int value;
1565 	int type;
1566 	int count;
1567 	const conf_limit *limit = &conf_limits[0];
1568 
1569 	ST_DEBUG3(ST_DEVINFO, st_label, CE_NOTE,
1570 	    "Checking %d entrys total with %d densities\n", list_len, list[4]);
1571 
1572 	count = list_len;
1573 	type = *list;
1574 	for (;  count && limit->name; count--, list++, limit++) {
1575 
1576 		value = *list;
1577 		if (value & ~limit->mask) {
1578 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1579 			    "%s %s value invalid bits set: 0x%X\n",
1580 			    conf_name, limit->name, value & ~limit->mask);
1581 			*list &= limit->mask;
1582 		} else if (value < limit->bottom) {
1583 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1584 			    "%s %s value too low: value = %d limit %d\n",
1585 			    conf_name, limit->name, value, limit->bottom);
1586 		} else if (value > limit->top) {
1587 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1588 			    "%s %s value too high: value = %d limit %d\n",
1589 			    conf_name, limit->name, value, limit->top);
1590 		} else {
1591 			ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
1592 			    "%s %s value = 0x%X\n",
1593 			    conf_name, limit->name, value);
1594 		}
1595 
1596 		/* If not the number of densities continue */
1597 		if (limit != &conf_limits[4]) {
1598 			continue;
1599 		}
1600 
1601 		/* If number of densities is not in range can't use config */
1602 		if (value < limit->bottom || value > limit->top) {
1603 			return (-1);
1604 		}
1605 
1606 		ndens = min(value, NDENSITIES);
1607 		if ((type == 1) && (list_len - ndens) != 6) {
1608 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1609 			    "%s conf version 1 with %d densities has %d items"
1610 			    " should have %d",
1611 			    conf_name, ndens, list_len, 6 + ndens);
1612 		} else if ((type == 2) && (list_len - ndens) != 13) {
1613 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1614 			    "%s conf version 2 with %d densities has %d items"
1615 			    " should have %d",
1616 			    conf_name, ndens, list_len, 13 + ndens);
1617 		}
1618 
1619 		limit++;
1620 		for (dens = 0; dens < ndens && count; dens++) {
1621 			count--;
1622 			list++;
1623 			value = *list;
1624 			if (value < limit->bottom) {
1625 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1626 				    "%s density[%d] value too low: value ="
1627 				    " 0x%X limit 0x%X\n",
1628 				    conf_name, dens, value, limit->bottom);
1629 			} else if (value > limit->top) {
1630 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1631 				    "%s density[%d] value too high: value ="
1632 				    " 0x%X limit 0x%X\n",
1633 				    conf_name, dens, value, limit->top);
1634 			} else {
1635 				ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
1636 				    "%s density[%d] value = 0x%X\n",
1637 				    conf_name, dens, value);
1638 			}
1639 		}
1640 	}
1641 
1642 	return (0);
1643 }
1644 
1645 static int
1646 st_get_conf_from_st_dot_conf(struct scsi_tape *un, char *vidpid,
1647     struct st_drivetype *dp)
1648 {
1649 	caddr_t config_list = NULL;
1650 	caddr_t data_list = NULL;
1651 	int	*data_ptr;
1652 	caddr_t vidptr, prettyptr, datanameptr;
1653 	size_t	vidlen, prettylen, datanamelen, tripletlen = 0;
1654 	int config_list_len, data_list_len, len, i;
1655 	int version;
1656 	int found = 0;
1657 
1658 
1659 	/*
1660 	 * Determine type of tape controller. Type is determined by
1661 	 * checking the vendor ids of the earlier inquiry command and
1662 	 * comparing those with vids in tape-config-list defined in st.conf
1663 	 */
1664 	if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, DDI_PROP_DONTPASS,
1665 	    "tape-config-list", (caddr_t)&config_list, &config_list_len)
1666 	    != DDI_PROP_SUCCESS) {
1667 		return (found);
1668 	}
1669 
1670 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
1671 	    "st_get_conf_from_st_dot_conf(): st.conf has tape-config-list\n");
1672 
1673 	/*
1674 	 * Compare vids in each triplet - if it matches, get value for
1675 	 * data_name and contruct a st_drivetype struct
1676 	 * tripletlen is not set yet!
1677 	 */
1678 	for (len = config_list_len, vidptr = config_list;
1679 	    len > 0;
1680 	    vidptr += tripletlen, len -= tripletlen) {
1681 
1682 		vidlen = strlen(vidptr);
1683 		prettyptr = vidptr + vidlen + 1;
1684 		prettylen = strlen(prettyptr);
1685 		datanameptr = prettyptr + prettylen + 1;
1686 		datanamelen = strlen(datanameptr);
1687 		tripletlen = vidlen + prettylen + datanamelen + 3;
1688 
1689 		if (vidlen == 0) {
1690 			continue;
1691 		}
1692 
1693 		/*
1694 		 * If inquiry vid dosen't match this triplets vid,
1695 		 * try the next.
1696 		 */
1697 		if (strncasecmp(vidpid, vidptr, vidlen)) {
1698 			continue;
1699 		}
1700 
1701 		/*
1702 		 * if prettylen is zero then use the vid string
1703 		 */
1704 		if (prettylen == 0) {
1705 			prettyptr = vidptr;
1706 			prettylen = vidlen;
1707 		}
1708 
1709 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1710 		    "vid = %s, pretty=%s, dataname = %s\n",
1711 		    vidptr, prettyptr, datanameptr);
1712 
1713 		/*
1714 		 * get the data list
1715 		 */
1716 		if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, 0,
1717 		    datanameptr, (caddr_t)&data_list,
1718 		    &data_list_len) != DDI_PROP_SUCCESS) {
1719 			/*
1720 			 * Error in getting property value
1721 			 * print warning!
1722 			 */
1723 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
1724 			    "data property (%s) has no value\n",
1725 			    datanameptr);
1726 			continue;
1727 		}
1728 
1729 		/*
1730 		 * now initialize the st_drivetype struct
1731 		 */
1732 		(void) strncpy(dp->name, prettyptr, ST_NAMESIZE - 1);
1733 		dp->length = (int)min(vidlen, (VIDPIDLEN - 1));
1734 		(void) strncpy(dp->vid, vidptr, dp->length);
1735 		data_ptr = (int *)data_list;
1736 		/*
1737 		 * check if data is enough for version, type,
1738 		 * bsize, options, # of densities, density1,
1739 		 * density2, ..., default_density
1740 		 */
1741 		if ((data_list_len < 5 * sizeof (int)) ||
1742 		    (data_list_len < 6 * sizeof (int) +
1743 		    *(data_ptr + 4) * sizeof (int))) {
1744 			/*
1745 			 * print warning and skip to next triplet.
1746 			 */
1747 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
1748 			    "data property (%s) incomplete\n",
1749 			    datanameptr);
1750 			kmem_free(data_list, data_list_len);
1751 			continue;
1752 		}
1753 
1754 		if (st_validate_conf_data(un, data_ptr,
1755 		    data_list_len / sizeof (int), datanameptr)) {
1756 			kmem_free(data_list, data_list_len);
1757 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
1758 			    "data property (%s) rejected\n",
1759 			    datanameptr);
1760 			continue;
1761 		}
1762 
1763 		/*
1764 		 * check version
1765 		 */
1766 		version = *data_ptr++;
1767 		if (version != 1 && version != 2) {
1768 			/* print warning but accept it */
1769 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
1770 			    "Version # for data property (%s) "
1771 			    "not set to 1 or 2\n", datanameptr);
1772 		}
1773 
1774 		dp->type    = *data_ptr++;
1775 		dp->bsize   = *data_ptr++;
1776 		dp->options = *data_ptr++;
1777 		dp->options |= ST_DYNAMIC;
1778 		len = *data_ptr++;
1779 		for (i = 0; i < NDENSITIES; i++) {
1780 			if (i < len) {
1781 				dp->densities[i] = *data_ptr++;
1782 			}
1783 		}
1784 		dp->default_density = *data_ptr << 3;
1785 		if (version == 2 &&
1786 		    data_list_len >= (13 + len) * sizeof (int)) {
1787 			data_ptr++;
1788 			dp->non_motion_timeout	= *data_ptr++;
1789 			dp->io_timeout		= *data_ptr++;
1790 			dp->rewind_timeout	= *data_ptr++;
1791 			dp->space_timeout	= *data_ptr++;
1792 			dp->load_timeout	= *data_ptr++;
1793 			dp->unload_timeout	= *data_ptr++;
1794 			dp->erase_timeout	= *data_ptr++;
1795 		}
1796 		kmem_free(data_list, data_list_len);
1797 		found = 1;
1798 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1799 		    "found in st.conf: vid = %s, pretty=%s\n",
1800 		    dp->vid, dp->name);
1801 		break;
1802 	}
1803 
1804 	/*
1805 	 * free up the memory allocated by ddi_getlongprop
1806 	 */
1807 	if (config_list) {
1808 		kmem_free(config_list, config_list_len);
1809 	}
1810 	return (found);
1811 }
1812 
1813 static int
1814 st_get_conf_from_st_conf_dot_c(struct scsi_tape *un, char *vidpid,
1815     struct st_drivetype *dp)
1816 {
1817 	int i;
1818 
1819 	/*
1820 	 * Determine type of tape controller.  Type is determined by
1821 	 * checking the result of the earlier inquiry command and
1822 	 * comparing vendor ids with strings in a table declared in st_conf.c.
1823 	 */
1824 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
1825 	    "st_get_conf_from_st_conf_dot_c(): looking at st_drivetypes\n");
1826 
1827 	for (i = 0; i < st_ndrivetypes; i++) {
1828 		if (st_drivetypes[i].length == 0) {
1829 			continue;
1830 		}
1831 		if (strncasecmp(vidpid, st_drivetypes[i].vid,
1832 		    st_drivetypes[i].length)) {
1833 			continue;
1834 		}
1835 		bcopy(&st_drivetypes[i], dp, sizeof (st_drivetypes[i]));
1836 		return (1);
1837 	}
1838 	return (0);
1839 }
1840 
1841 static int
1842 st_get_default_conf(struct scsi_tape *un, char *vidpid, struct st_drivetype *dp)
1843 {
1844 	int i;
1845 
1846 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
1847 	    "st_get_default_conf(): making drivetype from INQ cmd\n");
1848 
1849 
1850 	/*
1851 	 * Make up a name
1852 	 */
1853 	bcopy("Vendor '", dp->name, 8);
1854 	bcopy(vidpid, &dp->name[8], VIDLEN);
1855 	bcopy("' Product '", &dp->name[16], 11);
1856 	bcopy(&vidpid[8], &dp->name[27], PIDLEN);
1857 	dp->name[ST_NAMESIZE - 2] = '\'';
1858 	dp->name[ST_NAMESIZE - 1] = '\0';
1859 	dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
1860 	(void) strncpy(dp->vid, ST_INQUIRY->inq_vid, dp->length);
1861 	/*
1862 	 * 'clean' vendor and product strings of non-printing chars
1863 	 */
1864 	for (i = 0; i < ST_NAMESIZE - 2; i++) {
1865 		if (dp->name[i] < ' ' || dp->name[i] > '~') {
1866 			dp->name[i] = '.';
1867 		}
1868 	}
1869 	dp->type = ST_TYPE_INVALID;
1870 	dp->options |= (ST_DYNAMIC | ST_UNLOADABLE | ST_MODE_SEL_COMP);
1871 
1872 	return (1); /* Can Not Fail */
1873 }
1874 
1875 /*
1876  * Regular Unix Entry points
1877  */
1878 
1879 
1880 
1881 /* ARGSUSED */
1882 static int
1883 st_open(dev_t *dev_p, int flag, int otyp, cred_t *cred_p)
1884 {
1885 	dev_t dev = *dev_p;
1886 	int rval = 0;
1887 
1888 	GET_SOFT_STATE(dev);
1889 
1890 	/*
1891 	 * validate that we are addressing a sensible unit
1892 	 */
1893 	mutex_enter(ST_MUTEX);
1894 
1895 #ifdef	STDEBUG
1896 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
1897 	    "st_open(node = %s dev = 0x%lx, flag = %d, otyp = %d)\n",
1898 	    st_dev_name(dev), *dev_p, flag, otyp);
1899 #endif
1900 
1901 	/*
1902 	 * All device accesss go thru st_strategy() where we check
1903 	 * suspend status
1904 	 */
1905 
1906 	if (!un->un_attached) {
1907 		st_known_tape_type(un);
1908 		if (!un->un_attached) {
1909 			rval = ENXIO;
1910 			goto exit;
1911 		}
1912 
1913 	}
1914 
1915 	/*
1916 	 * Check for the case of the tape in the middle of closing.
1917 	 * This isn't simply a check of the current state, because
1918 	 * we could be in state of sensing with the previous state
1919 	 * that of closing.
1920 	 *
1921 	 * And don't allow multiple opens.
1922 	 */
1923 	if (!(flag & (FNDELAY | FNONBLOCK)) && IS_CLOSING(un)) {
1924 		un->un_laststate = un->un_state;
1925 		un->un_state = ST_STATE_CLOSE_PENDING_OPEN;
1926 		while (IS_CLOSING(un) ||
1927 		    un->un_state == ST_STATE_CLOSE_PENDING_OPEN) {
1928 			if (cv_wait_sig(&un->un_clscv, ST_MUTEX) == 0) {
1929 				rval = EINTR;
1930 				un->un_state = un->un_laststate;
1931 				goto exit;
1932 			}
1933 		}
1934 	} else if (un->un_state != ST_STATE_CLOSED) {
1935 		rval = EBUSY;
1936 		goto busy;
1937 	}
1938 
1939 	/*
1940 	 * record current dev
1941 	 */
1942 	un->un_dev = dev;
1943 	un->un_oflags = flag;	/* save for use in st_tape_init() */
1944 	un->un_errno = 0;	/* no errors yet */
1945 	un->un_restore_pos = 0;
1946 	un->un_rqs_state = 0;
1947 
1948 	/*
1949 	 * If we are opening O_NDELAY, or O_NONBLOCK, we don't check for
1950 	 * anything, leave internal states alone, if fileno >= 0
1951 	 */
1952 	if (flag & (FNDELAY | FNONBLOCK)) {
1953 		if (un->un_fileno < 0 || (un->un_fileno == 0 &&
1954 			un->un_blkno == 0)) {
1955 			un->un_state = ST_STATE_OFFLINE;
1956 		} else {
1957 			/*
1958 			 * set un_read_only/write-protect status.
1959 			 *
1960 			 * If the tape is not bot we can assume
1961 			 * that mspl->wp_status is set properly.
1962 			 * else
1963 			 * we need to do a mode sense/Tur once
1964 			 * again to get the actual tape status.(since
1965 			 * user might have replaced the tape)
1966 			 * Hence make the st state OFFLINE so that
1967 			 * we re-intialize the tape once again.
1968 			 */
1969 			if (un->un_fileno > 0 ||
1970 			    (un->un_fileno == 0 && un->un_blkno != 0)) {
1971 				un->un_read_only =
1972 				    (un->un_oflags & FWRITE) ? 0 : 1;
1973 				un->un_state = ST_STATE_OPEN_PENDING_IO;
1974 			} else {
1975 				un->un_state = ST_STATE_OFFLINE;
1976 			}
1977 		}
1978 		rval = 0;
1979 	} else {
1980 		/*
1981 		 * If reserve/release is supported on this drive.
1982 		 * then call st_tape_reservation_init().
1983 		 */
1984 		un->un_state = ST_STATE_OPENING;
1985 
1986 		if (ST_RESERVE_SUPPORTED(un)) {
1987 			rval = st_tape_reservation_init(dev);
1988 			if (rval) {
1989 				goto exit;
1990 			}
1991 		}
1992 		rval = st_tape_init(dev);
1993 		if (rval) {
1994 			/*
1995 			 * Release the tape unit, if no preserve reserve
1996 			 */
1997 			if ((ST_RESERVE_SUPPORTED(un)) &&
1998 			    !(un->un_rsvd_status & ST_PRESERVE_RESERVE)) {
1999 				(void) st_reserve_release(dev, ST_RELEASE);
2000 			}
2001 		} else {
2002 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2003 		}
2004 	}
2005 
2006 exit:
2007 	/*
2008 	 * we don't want any uninvited guests scrogging our data when we're
2009 	 * busy with something, so for successful opens or failed opens
2010 	 * (except for EBUSY), reset these counters and state appropriately.
2011 	 */
2012 	if (rval != EBUSY) {
2013 		if (rval) {
2014 			un->un_state = ST_STATE_CLOSED;
2015 		}
2016 		un->un_err_resid = 0;
2017 		un->un_retry_ct = 0;
2018 		un->un_tran_retry_ct = 0;
2019 	}
2020 busy:
2021 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2022 	    "st_open: return val = %x, state = %d\n", rval, un->un_state);
2023 	mutex_exit(ST_MUTEX);
2024 	return (rval);
2025 
2026 }
2027 
2028 #define	ST_LOST_RESERVE_BETWEEN_OPENS  \
2029 		(ST_RESERVE | ST_LOST_RESERVE | ST_PRESERVE_RESERVE)
2030 
2031 int
2032 st_tape_reservation_init(dev_t dev)
2033 {
2034 	int rval = 0;
2035 
2036 	GET_SOFT_STATE(dev);
2037 
2038 	ASSERT(mutex_owned(ST_MUTEX));
2039 
2040 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2041 	    "st_tape_reservation_init(dev = 0x%lx)\n", dev);
2042 
2043 	/*
2044 	 * Issue a Throw-Away reserve command to clear the
2045 	 * check condition.
2046 	 * If the current behaviour of reserve/release is to
2047 	 * hold reservation across opens , and if a Bus reset
2048 	 * has been issued between opens then this command
2049 	 * would set the ST_LOST_RESERVE flags in rsvd_status.
2050 	 * In this case return an EACCES so that user knows that
2051 	 * reservation has been lost in between opens.
2052 	 * If this error is not returned and we continue with
2053 	 * successful open , then user may think position of the
2054 	 * tape is still the same but inreality we would rewind the
2055 	 * tape and continue from BOT.
2056 	 */
2057 	rval = st_reserve_release(dev, ST_RESERVE);
2058 
2059 	if (rval) {
2060 		if ((un->un_rsvd_status & ST_LOST_RESERVE_BETWEEN_OPENS) ==
2061 			ST_LOST_RESERVE_BETWEEN_OPENS) {
2062 				un->un_rsvd_status &=
2063 					~(ST_LOST_RESERVE | ST_RESERVE);
2064 				un->un_errno = EACCES;
2065 				return (EACCES);
2066 		}
2067 		rval = st_reserve_release(dev, ST_RESERVE);
2068 	}
2069 	if (rval == 0)
2070 		un->un_rsvd_status |= ST_INIT_RESERVE;
2071 
2072 	return (rval);
2073 }
2074 
2075 static int
2076 st_tape_init(dev_t dev)
2077 {
2078 	int err;
2079 	int rval = 0;
2080 
2081 	GET_SOFT_STATE(dev);
2082 
2083 	ASSERT(mutex_owned(ST_MUTEX));
2084 
2085 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2086 	    "st_tape_init(dev = 0x%lx, oflags = %d)\n", dev, un->un_oflags);
2087 
2088 	/*
2089 	 * Clean up after any errors left by 'last' close.
2090 	 * This also handles the case of the initial open.
2091 	 */
2092 	if (un->un_state != ST_STATE_INITIALIZING) {
2093 		un->un_laststate = un->un_state;
2094 		un->un_state = ST_STATE_OPENING;
2095 	}
2096 
2097 	un->un_kbytes_xferred = 0;
2098 
2099 	/*
2100 	 * do a throw away TUR to clear check condition
2101 	 */
2102 	err = st_cmd(dev, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
2103 
2104 	/*
2105 	 * If test unit ready fails because the drive is reserved
2106 	 * by another host fail the open for no access.
2107 	 */
2108 	if (err) {
2109 		if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
2110 			un->un_state = ST_STATE_CLOSED;
2111 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2112 				"st_tape_init: RESERVATION CONFLICT\n");
2113 			rval = EACCES;
2114 			goto exit;
2115 		}
2116 	}
2117 
2118 	/*
2119 	 * See whether this is a generic device that we haven't figured
2120 	 * anything out about yet.
2121 	 */
2122 	if (un->un_dp->type == ST_TYPE_INVALID) {
2123 		if (st_determine_generic(dev)) {
2124 			un->un_state = ST_STATE_CLOSED;
2125 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2126 			    "st_open: EIO invalid type\n");
2127 			rval = EIO;
2128 			goto exit;
2129 		}
2130 		/*
2131 		 * If this is a Unknown Type drive,
2132 		 * Use the READ BLOCK LIMITS to determine if
2133 		 * allow large xfer is approprate if not globally
2134 		 * disabled with st_allow_large_xfer.
2135 		 */
2136 		un->un_allow_large_xfer = (uchar_t)st_allow_large_xfer;
2137 	} else {
2138 
2139 		/*
2140 		 * If we allow_large_xfer (ie >64k) and have not yet found out
2141 		 * the max block size supported by the drive,
2142 		 * find it by issueing a READ_BLKLIM command.
2143 		 * if READ_BLKLIM cmd fails, assume drive doesn't
2144 		 * allow_large_xfer and min/max block sizes as 1 byte and 63k.
2145 		 */
2146 		un->un_allow_large_xfer = st_allow_large_xfer &&
2147 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT);
2148 	}
2149 	/*
2150 	 * if maxbsize is unknown, set the maximum block size.
2151 	 */
2152 	if (un->un_maxbsize == MAXBSIZE_UNKNOWN) {
2153 
2154 		/*
2155 		 * Get the Block limits of the tape drive.
2156 		 * if un->un_allow_large_xfer = 0 , then make sure
2157 		 * that maxbsize is <= ST_MAXRECSIZE_FIXED.
2158 		 */
2159 		un->un_rbl = kmem_zalloc(RBLSIZE, KM_SLEEP);
2160 
2161 		err = st_cmd(dev, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
2162 		if (err) {
2163 			/* Retry */
2164 			err = st_cmd(dev, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
2165 		}
2166 		if (!err) {
2167 
2168 			/*
2169 			 * if cmd successful, use limit returned
2170 			 */
2171 			un->un_maxbsize = (un->un_rbl->max_hi << 16) +
2172 					(un->un_rbl->max_mid << 8) +
2173 					un->un_rbl->max_lo;
2174 			un->un_minbsize = (un->un_rbl->min_hi << 8) +
2175 					un->un_rbl->min_lo;
2176 			un->un_data_mod = 1 << un->un_rbl->granularity;
2177 			if ((un->un_maxbsize == 0) ||
2178 			    (un->un_allow_large_xfer == 0 &&
2179 			    un->un_maxbsize > ST_MAXRECSIZE_FIXED)) {
2180 				un->un_maxbsize = ST_MAXRECSIZE_FIXED;
2181 
2182 			} else if (un->un_dp->type == ST_TYPE_DEFAULT) {
2183 				/*
2184 				 * Drive is not one that is configured, But the
2185 				 * READ BLOCK LIMITS tells us it can do large
2186 				 * xfers.
2187 				 */
2188 				if (un->un_maxbsize > ST_MAXRECSIZE_FIXED) {
2189 					un->un_dp->options |=
2190 					    ST_NO_RECSIZE_LIMIT;
2191 				}
2192 				/*
2193 				 * If max and mimimum block limits are the
2194 				 * same this is a fixed block size device.
2195 				 */
2196 				if (un->un_maxbsize == un->un_minbsize) {
2197 					un->un_dp->options &= ~ST_VARIABLE;
2198 				}
2199 			}
2200 
2201 			if (un->un_minbsize == 0) {
2202 				un->un_minbsize = 1;
2203 			}
2204 
2205 		} else { /* error on read block limits */
2206 
2207 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2208 				"!st_tape_init: Error on READ BLOCK LIMITS,"
2209 				" errno = %d un_rsvd_status = 0x%X\n",
2210 				err, un->un_rsvd_status);
2211 
2212 			/*
2213 			 * since read block limits cmd failed,
2214 			 * do not allow large xfers.
2215 			 * use old values in st_minphys
2216 			 */
2217 			if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
2218 				rval = EACCES;
2219 			} else {
2220 				un->un_allow_large_xfer = 0;
2221 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2222 					"!Disabling large transfers\n");
2223 
2224 				/*
2225 				 * we guess maxbsize and minbsize
2226 				 */
2227 				if (un->un_bsize) {
2228 					un->un_maxbsize = un->un_minbsize =
2229 						un->un_bsize;
2230 				} else {
2231 					un->un_maxbsize = ST_MAXRECSIZE_FIXED;
2232 					un->un_minbsize = 1;
2233 				}
2234 				/*
2235 				 * Data Mod must be set,
2236 				 * Even if read block limits fails.
2237 				 * Prevents Divide By Zero in st_rw().
2238 				 */
2239 				un->un_data_mod = 1;
2240 			}
2241 		}
2242 		if (un->un_rbl) {
2243 			kmem_free(un->un_rbl, RBLSIZE);
2244 			un->un_rbl = NULL;
2245 		}
2246 
2247 		if (rval) {
2248 			goto exit;
2249 		}
2250 	}
2251 
2252 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
2253 	    "maxdma = %d, maxbsize = %d, minbsize = %d, %s large xfer\n",
2254 	    un->un_maxdma, un->un_maxbsize, un->un_minbsize,
2255 	    (un->un_allow_large_xfer ? "ALLOW": "DON'T ALLOW"));
2256 
2257 	err = st_cmd(dev, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
2258 
2259 	if (err != 0) {
2260 		if (err == EINTR) {
2261 			un->un_laststate = un->un_state;
2262 			un->un_state = ST_STATE_CLOSED;
2263 			rval = EINTR;
2264 			goto exit;
2265 		}
2266 		/*
2267 		 * Make sure the tape is ready
2268 		 */
2269 		un->un_fileno = -1;
2270 		if (un->un_status != KEY_UNIT_ATTENTION) {
2271 			/*
2272 			 * allow open no media.  Subsequent MTIOCSTATE
2273 			 * with media present will complete the open
2274 			 * logic.
2275 			 */
2276 			un->un_laststate = un->un_state;
2277 			if (un->un_oflags & (FNONBLOCK|FNDELAY)) {
2278 				un->un_mediastate = MTIO_EJECTED;
2279 				un->un_state = ST_STATE_OFFLINE;
2280 				rval = 0;
2281 				goto exit;
2282 			} else {
2283 				un->un_state = ST_STATE_CLOSED;
2284 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2285 		    "st_open EIO no media, not opened O_NONBLOCK|O_EXCL\n");
2286 				rval = EIO;
2287 				goto exit;
2288 			}
2289 		}
2290 	}
2291 
2292 	/*
2293 	 * On each open, initialize block size from drivetype struct,
2294 	 * as it could have been changed by MTSRSZ ioctl.
2295 	 * Now, ST_VARIABLE simply means drive is capable of variable
2296 	 * mode. All drives are assumed to support fixed records.
2297 	 * Hence, un_bsize tells what mode the drive is in.
2298 	 *	un_bsize	= 0	- variable record length
2299 	 *			= x	- fixed record length is x
2300 	 */
2301 	un->un_bsize = un->un_dp->bsize;
2302 
2303 	if (un->un_restore_pos) {
2304 		if (st_validate_tapemarks(un, un->un_save_fileno,
2305 		    un->un_save_blkno) != 0) {
2306 			un->un_restore_pos = 0;
2307 			un->un_laststate = un->un_state;
2308 			un->un_state = ST_STATE_CLOSED;
2309 			rval = EIO;
2310 			goto exit;
2311 		}
2312 		un->un_restore_pos = 0;
2313 	}
2314 
2315 	if ((un->un_fileno < 0) && st_loadtape(dev)) {
2316 		un->un_laststate = un->un_state;
2317 		un->un_state = ST_STATE_CLOSED;
2318 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2319 		    "st_open : EIO can't open tape\n");
2320 		rval = EIO;
2321 		goto exit;
2322 	}
2323 
2324 	/*
2325 	 * do a mode sense to pick up state of current write-protect,
2326 	 */
2327 	(void) st_modesense(un);
2328 
2329 	/*
2330 	 * If we are opening the tape for writing, check
2331 	 * to make sure that the tape can be written.
2332 	 */
2333 	if (un->un_oflags & FWRITE) {
2334 		err = 0;
2335 		if (un->un_mspl->wp)  {
2336 			un->un_status = KEY_WRITE_PROTECT;
2337 			un->un_laststate = un->un_state;
2338 			un->un_state = ST_STATE_CLOSED;
2339 			rval = EACCES;
2340 			goto exit;
2341 		} else {
2342 			un->un_read_only = 0;
2343 		}
2344 	} else {
2345 		un->un_read_only = 1;
2346 	}
2347 
2348 	/*
2349 	 * If we're opening the tape write-only, we need to
2350 	 * write 2 filemarks on the HP 1/2 inch drive, to
2351 	 * create a null file.
2352 	 */
2353 	if ((un->un_oflags == FWRITE) && (un->un_dp->options & ST_REEL)) {
2354 		un->un_fmneeded = 2;
2355 	} else if (un->un_oflags == FWRITE) {
2356 		un->un_fmneeded = 1;
2357 	} else {
2358 		un->un_fmneeded = 0;
2359 	}
2360 
2361 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
2362 	    "fmneeded = %x\n", un->un_fmneeded);
2363 
2364 	/*
2365 	 * Make sure the density can be selected correctly.
2366 	 */
2367 	if (st_determine_density(dev, B_WRITE)) {
2368 		un->un_status = KEY_ILLEGAL_REQUEST;
2369 		un->un_laststate = un->un_state;
2370 		un->un_state = ST_STATE_CLOSED;
2371 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2372 		    "st_open: EIO can't determine density\n");
2373 		rval = EIO;
2374 		goto exit;
2375 	}
2376 
2377 	/*
2378 	 * Destroy the knowledge that we have 'determined'
2379 	 * density so that a later read at BOT comes along
2380 	 * does the right density determination.
2381 	 */
2382 
2383 	un->un_density_known = 0;
2384 
2385 
2386 	/*
2387 	 * Okay, the tape is loaded and either at BOT or somewhere past.
2388 	 * Mark the state such that any I/O or tape space operations
2389 	 * will get/set the right density, etc..
2390 	 */
2391 	un->un_laststate = un->un_state;
2392 	un->un_lastop = ST_OP_NIL;
2393 	un->un_mediastate = MTIO_INSERTED;
2394 	cv_broadcast(&un->un_state_cv);
2395 
2396 	/*
2397 	 *  Set test append flag if writing.
2398 	 *  First write must check that tape is positioned correctly.
2399 	 */
2400 	un->un_test_append = (un->un_oflags & FWRITE);
2401 
2402 exit:
2403 	un->un_err_resid = 0;
2404 	un->un_last_resid = 0;
2405 	un->un_last_count = 0;
2406 
2407 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2408 	    "st_tape_init: return val = %x\n", rval);
2409 	return (rval);
2410 
2411 }
2412 
2413 
2414 
2415 /* ARGSUSED */
2416 static int
2417 st_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
2418 {
2419 	int err = 0;
2420 	int norew, count, last_state;
2421 #if defined(__i386) || defined(__amd64)
2422 	struct contig_mem *cp, *cp_temp;
2423 #endif
2424 
2425 	GET_SOFT_STATE(dev);
2426 
2427 	/*
2428 	 * wait till all cmds in the pipeline have been completed
2429 	 */
2430 	mutex_enter(ST_MUTEX);
2431 
2432 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2433 	    "st_close(dev = 0x%lx, flag = %d, otyp = %d)\n", dev, flag, otyp);
2434 
2435 	st_wait_for_io(un);
2436 
2437 	/* turn off persistent errors on close, as we want close to succeed */
2438 	TURN_PE_OFF(un);
2439 
2440 	/*
2441 	 * set state to indicate that we are in process of closing
2442 	 */
2443 	last_state = un->un_laststate = un->un_state;
2444 	un->un_state = ST_STATE_CLOSING;
2445 
2446 	/*
2447 	 * BSD behavior:
2448 	 * a close always causes a silent span to the next file if we've hit
2449 	 * an EOF (but not yet read across it).
2450 	 */
2451 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2452 	    "st_close1: fileno=%x, blkno=%lx, un_eof=%x\n", un->un_fileno,
2453 	    un->un_blkno, un->un_eof);
2454 
2455 
2456 	if (BSD_BEHAVIOR && (un->un_eof == ST_EOF)) {
2457 		if (un->un_fileno >= 0) {
2458 			un->un_fileno++;
2459 			un->un_blkno = 0;
2460 		}
2461 		un->un_eof = ST_NO_EOF;
2462 	}
2463 
2464 	/*
2465 	 * rewinding?
2466 	 */
2467 	norew = (getminor(dev) & MT_NOREWIND);
2468 
2469 	/*
2470 	 * SVR4 behavior for skipping to next file:
2471 	 *
2472 	 * If we have not seen a filemark, space to the next file
2473 	 *
2474 	 * If we have already seen the filemark we are physically in the next
2475 	 * file and we only increment the filenumber
2476 	 */
2477 
2478 	if (norew && SVR4_BEHAVIOR && (flag & FREAD) && (un->un_blkno != 0) &&
2479 	    (un->un_lastop != ST_OP_WRITE)) {
2480 		switch (un->un_eof) {
2481 		case ST_NO_EOF:
2482 			/*
2483 			 * if we were reading and did not read the complete file
2484 			 * skip to the next file, leaving the tape correctly
2485 			 * positioned to read the first record of the next file
2486 			 * Check first for REEL if we are at EOT by trying to
2487 			 * read a block
2488 			 */
2489 			if ((un->un_dp->options & ST_REEL) &&
2490 				(!(un->un_dp->options & ST_READ_IGNORE_EOFS)) &&
2491 			    (un->un_blkno == 0)) {
2492 				if (st_cmd(dev, SCMD_SPACE, Blk(1), SYNC_CMD)) {
2493 					ST_DEBUG2(ST_DEVINFO, st_label,
2494 					    SCSI_DEBUG,
2495 					    "st_close : EIO can't space\n");
2496 					err = EIO;
2497 					break;
2498 				}
2499 				if (un->un_eof >= ST_EOF_PENDING) {
2500 					un->un_eof = ST_EOT_PENDING;
2501 					un->un_fileno += 1;
2502 					un->un_blkno   = 0;
2503 					break;
2504 				}
2505 			}
2506 			if (st_cmd(dev, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
2507 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2508 				    "st_close: EIO can't space #2\n");
2509 				err = EIO;
2510 			} else {
2511 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2512 				    "st_close2: fileno=%x,blkno=%lx,"
2513 				    "un_eof=%x\n",
2514 				    un->un_fileno, un->un_blkno, un->un_eof);
2515 				un->un_eof = ST_NO_EOF;
2516 			}
2517 			break;
2518 
2519 		case ST_EOF_PENDING:
2520 		case ST_EOF:
2521 			un->un_fileno += 1;
2522 			un->un_blkno   = 0;
2523 			un->un_eof = ST_NO_EOF;
2524 			break;
2525 
2526 		case ST_EOT:
2527 		case ST_EOT_PENDING:
2528 			/* nothing to do */
2529 			break;
2530 		}
2531 	}
2532 
2533 
2534 	/*
2535 	 * For performance reasons (HP 88780), the driver should
2536 	 * postpone writing the second tape mark until just before a file
2537 	 * positioning ioctl is issued (e.g., rewind).	This means that
2538 	 * the user must not manually rewind the tape because the tape will
2539 	 * be missing the second tape mark which marks EOM.
2540 	 * However, this small performance improvement is not worth the risk.
2541 	 */
2542 
2543 	/*
2544 	 * We need to back up over the filemark we inadvertently popped
2545 	 * over doing a read in between the two filemarks that constitute
2546 	 * logical eot for 1/2" tapes. Note that ST_EOT_PENDING is only
2547 	 * set while reading.
2548 	 *
2549 	 * If we happen to be at physical eot (ST_EOM) (writing case),
2550 	 * the writing of filemark(s) will clear the ST_EOM state, which
2551 	 * we don't want, so we save this state and restore it later.
2552 	 */
2553 
2554 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2555 	    "flag=%x, fmneeded=%x, lastop=%x, eof=%x\n",
2556 		flag, un->un_fmneeded, un->un_lastop, un->un_eof);
2557 
2558 	if (un->un_eof == ST_EOT_PENDING) {
2559 		if (norew) {
2560 			if (st_cmd(dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)) {
2561 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2562 				    "st_close: EIO can't space #3\n");
2563 				err = EIO;
2564 			} else {
2565 				un->un_blkno = 0;
2566 				un->un_eof = ST_EOT;
2567 			}
2568 		} else {
2569 			un->un_eof = ST_NO_EOF;
2570 		}
2571 
2572 	/*
2573 	 * Do we need to write a file mark?
2574 	 *
2575 	 * only write filemarks if there are fmks to be written and
2576 	 *   - open for write (possibly read/write)
2577 	 *   - the last operation was a write
2578 	 * or:
2579 	 *   -	opened for wronly
2580 	 *   -	no data was written
2581 	 */
2582 	} else if ((un->un_fileno >= 0) && (un->un_fmneeded > 0) &&
2583 	    (((flag & FWRITE) && (un->un_lastop == ST_OP_WRITE)) ||
2584 	    ((flag & FWRITE) && (un->un_lastop == ST_OP_WEOF)) ||
2585 	    ((flag == FWRITE) && (un->un_lastop == ST_OP_NIL)))) {
2586 
2587 		/* save ST_EOM state */
2588 		int was_at_eom = (un->un_eof == ST_EOM) ? 1 : 0;
2589 
2590 		/*
2591 		 * Note that we will write a filemark if we had opened
2592 		 * the tape write only and no data was written, thus
2593 		 * creating a null file.
2594 		 *
2595 		 * If the user already wrote one, we only have to write 1 more.
2596 		 * If they wrote two, we don't have to write any.
2597 		 */
2598 
2599 		count = un->un_fmneeded;
2600 		if (count > 0) {
2601 			if (st_cmd(dev, SCMD_WRITE_FILE_MARK,
2602 			    count, SYNC_CMD)) {
2603 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2604 				    "st_close : EIO can't wfm\n");
2605 				err = EIO;
2606 			}
2607 			if ((un->un_dp->options & ST_REEL) && norew) {
2608 				if (st_cmd(dev, SCMD_SPACE, Fmk((-1)),
2609 				    SYNC_CMD)) {
2610 					ST_DEBUG2(ST_DEVINFO, st_label,
2611 					    SCSI_DEBUG,
2612 					    "st_close : EIO space fmk(-1)\n");
2613 					err = EIO;
2614 				}
2615 				un->un_eof = ST_NO_EOF;
2616 				/* fix up block number */
2617 				un->un_blkno = 0;
2618 			}
2619 		}
2620 
2621 		/*
2622 		 * If we aren't going to be rewinding, and we were at
2623 		 * physical eot, restore the state that indicates we
2624 		 * are at physical eot. Once you have reached physical
2625 		 * eot, and you close the tape, the only thing you can
2626 		 * do on the next open is to rewind. Access to trailer
2627 		 * records is only allowed without closing the device.
2628 		 */
2629 		if (norew == 0 && was_at_eom)
2630 			un->un_eof = ST_EOM;
2631 	}
2632 
2633 	/*
2634 	 * report soft errors if enabled and available, if we never accessed
2635 	 * the drive, don't get errors. This will prevent some DAT error
2636 	 * messages upon LOG SENSE.
2637 	 */
2638 	if (st_report_soft_errors_on_close &&
2639 	    (un->un_dp->options & ST_SOFT_ERROR_REPORTING) &&
2640 	    (last_state != ST_STATE_OFFLINE)) {
2641 		/*
2642 		 * Make sure we have reserve the tape unit.
2643 		 * This is the case when we do a O_NDELAY open and
2644 		 * then do a close without any I/O.
2645 		 */
2646 		if (!(un->un_rsvd_status & ST_INIT_RESERVE) &&
2647 			ST_RESERVE_SUPPORTED(un)) {
2648 			if ((err = st_tape_reservation_init(dev))) {
2649 				goto error;
2650 			}
2651 		}
2652 		(void) st_report_soft_errors(dev, flag);
2653 	}
2654 
2655 
2656 	/*
2657 	 * Do we need to rewind? Can we rewind?
2658 	 */
2659 	if (norew == 0 && un->un_fileno >= 0 && err == 0) {
2660 		/*
2661 		 * We'd like to rewind with the
2662 		 * 'immediate' bit set, but this
2663 		 * causes problems on some drives
2664 		 * where subsequent opens get a
2665 		 * 'NOT READY' error condition
2666 		 * back while the tape is rewinding,
2667 		 * which is impossible to distinguish
2668 		 * from the condition of 'no tape loaded'.
2669 		 *
2670 		 * Also, for some targets, if you disconnect
2671 		 * with the 'immediate' bit set, you don't
2672 		 * actually return right away, i.e., the
2673 		 * target ignores your request for immediate
2674 		 * return.
2675 		 *
2676 		 * Instead, we'll fire off an async rewind
2677 		 * command. We'll mark the device as closed,
2678 		 * and any subsequent open will stall on
2679 		 * the first TEST_UNIT_READY until the rewind
2680 		 * completes.
2681 		 *
2682 		 */
2683 		if (!(un->un_rsvd_status & ST_INIT_RESERVE) &&
2684 			ST_RESERVE_SUPPORTED(un)) {
2685 			if ((err = st_tape_reservation_init(dev))) {
2686 				goto error;
2687 			}
2688 		}
2689 		if (ST_RESERVE_SUPPORTED(un)) {
2690 			(void) st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD);
2691 		} else {
2692 			(void) st_cmd(dev, SCMD_REWIND, 0, ASYNC_CMD);
2693 		}
2694 	}
2695 
2696 	/*
2697 	 * eject tape if necessary
2698 	 */
2699 	if (un->un_eject_tape_on_failure) {
2700 		un->un_eject_tape_on_failure = 0;
2701 		if (st_cmd(dev, SCMD_LOAD, 0, SYNC_CMD)) {
2702 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2703 			    "st_close : can't unload tape\n");
2704 		} else {
2705 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2706 			    "st_close : tape unloaded \n");
2707 			un->un_eof = ST_NO_EOF;
2708 			un->un_mediastate = MTIO_EJECTED;
2709 		}
2710 	}
2711 	/*
2712 	 * Release the tape unit, if default reserve/release
2713 	 * behaviour.
2714 	 */
2715 	if (ST_RESERVE_SUPPORTED(un) &&
2716 		!(un->un_rsvd_status & ST_PRESERVE_RESERVE) &&
2717 		    (un->un_rsvd_status & ST_INIT_RESERVE)) {
2718 		(void) st_reserve_release(dev, ST_RELEASE);
2719 	}
2720 
2721 error:
2722 	/*
2723 	 * clear up state
2724 	 */
2725 	un->un_laststate = un->un_state;
2726 	un->un_state = ST_STATE_CLOSED;
2727 	un->un_lastop = ST_OP_NIL;
2728 	un->un_throttle = 1;	/* assume one request at time, for now */
2729 	un->un_retry_ct = 0;
2730 	un->un_tran_retry_ct = 0;
2731 	un->un_errno = 0;
2732 	un->un_swr_token = (opaque_t)NULL;
2733 	un->un_rsvd_status &= ~(ST_INIT_RESERVE);
2734 
2735 	/* Restore the options to the init time settings */
2736 	if (un->un_init_options & ST_READ_IGNORE_ILI) {
2737 		un->un_dp->options |= ST_READ_IGNORE_ILI;
2738 	} else {
2739 		un->un_dp->options &= ~ST_READ_IGNORE_ILI;
2740 	}
2741 
2742 	if (un->un_init_options & ST_READ_IGNORE_EOFS) {
2743 		un->un_dp->options |= ST_READ_IGNORE_EOFS;
2744 	} else {
2745 		un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
2746 	}
2747 
2748 	if (un->un_init_options & ST_SHORT_FILEMARKS) {
2749 		un->un_dp->options |= ST_SHORT_FILEMARKS;
2750 	} else {
2751 		un->un_dp->options &= ~ST_SHORT_FILEMARKS;
2752 	}
2753 
2754 	ASSERT(mutex_owned(ST_MUTEX));
2755 
2756 	/*
2757 	 * Signal anyone awaiting a close operation to complete.
2758 	 */
2759 	cv_signal(&un->un_clscv);
2760 
2761 	/*
2762 	 * any kind of error on closing causes all state to be tossed
2763 	 */
2764 	if (err && un->un_status != KEY_ILLEGAL_REQUEST) {
2765 		un->un_density_known = 0;
2766 		/*
2767 		 * note that st_intr has already set un_fileno to -1
2768 		 */
2769 	}
2770 
2771 #if defined(__i386) || defined(__amd64)
2772 	/*
2773 	 * free any contiguous mem alloc'ed for big block I/O
2774 	 */
2775 	cp = un->un_contig_mem;
2776 	while (cp) {
2777 		if (cp->cm_addr) {
2778 			ddi_dma_mem_free(&cp->cm_acc_hdl);
2779 		}
2780 		cp_temp = cp;
2781 		cp = cp->cm_next;
2782 		kmem_free(cp_temp,
2783 		    sizeof (struct contig_mem) + biosize());
2784 	}
2785 	un->un_contig_mem_total_num = 0;
2786 	un->un_contig_mem_available_num = 0;
2787 	un->un_contig_mem = NULL;
2788 	un->un_max_contig_mem_len = 0;
2789 #endif
2790 
2791 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2792 	    "st_close3: return val = %x, fileno=%x, blkno=%lx, un_eof=%x\n",
2793 			    err, un->un_fileno, un->un_blkno, un->un_eof);
2794 
2795 	mutex_exit(ST_MUTEX);
2796 	return (err);
2797 }
2798 
2799 /*
2800  * These routines perform raw i/o operations.
2801  */
2802 
2803 /* ARGSUSED2 */
2804 static int
2805 st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p)
2806 {
2807 	return (st_arw(dev, aio, B_READ));
2808 }
2809 
2810 
2811 /* ARGSUSED2 */
2812 static int
2813 st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p)
2814 {
2815 	return (st_arw(dev, aio, B_WRITE));
2816 }
2817 
2818 
2819 
2820 /* ARGSUSED */
2821 static int
2822 st_read(dev_t dev, struct uio *uiop, cred_t *cred_p)
2823 {
2824 	return (st_rw(dev, uiop, B_READ));
2825 }
2826 
2827 /* ARGSUSED */
2828 static int
2829 st_write(dev_t dev, struct uio *uiop, cred_t *cred_p)
2830 {
2831 	return (st_rw(dev, uiop, B_WRITE));
2832 }
2833 
2834 /*
2835  * Due to historical reasons, old limits are: For variable-length devices:
2836  * if greater than 64KB - 1 (ST_MAXRECSIZE_VARIABLE), block into 64 KB - 2
2837  * ST_MAXRECSIZE_VARIABLE_LIMIT) requests; otherwise,
2838  * (let it through unmodified. For fixed-length record devices:
2839  * 63K (ST_MAXRECSIZE_FIXED) is max (default minphys).
2840  *
2841  * The new limits used are un_maxdma (retrieved using scsi_ifgetcap()
2842  * from the HBA) and un_maxbsize (retrieved by sending SCMD_READ_BLKLIM
2843  * command to the drive).
2844  *
2845  */
2846 static void
2847 st_minphys(struct buf *bp)
2848 {
2849 	struct scsi_tape *un;
2850 
2851 #if !defined(lint)
2852 	_NOTE(SCHEME_PROTECTS_DATA("stable data", scsi_tape::un_sd));
2853 #endif
2854 
2855 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
2856 
2857 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2858 	    "st_minphys(bp = 0x%p): b_bcount = 0x%lx\n", (void *)bp,
2859 	    bp->b_bcount);
2860 
2861 	if (un->un_allow_large_xfer) {
2862 
2863 		/*
2864 		 * check un_maxbsize for variable length devices only
2865 		 */
2866 		if (un->un_bsize == 0 && bp->b_bcount > un->un_maxbsize) {
2867 			bp->b_bcount = un->un_maxbsize;
2868 		}
2869 		/*
2870 		 * can't go more that HBA maxdma limit in either fixed-length
2871 		 * or variable-length tape drives.
2872 		 */
2873 		if (bp->b_bcount > un->un_maxdma) {
2874 			bp->b_bcount = un->un_maxdma;
2875 		}
2876 	} else {
2877 
2878 		/*
2879 		 *  use old fixed limits
2880 		 */
2881 		if (un->un_bsize == 0) {
2882 			if (bp->b_bcount > ST_MAXRECSIZE_VARIABLE) {
2883 				bp->b_bcount = ST_MAXRECSIZE_VARIABLE_LIMIT;
2884 			}
2885 		} else {
2886 			if (bp->b_bcount > ST_MAXRECSIZE_FIXED) {
2887 				bp->b_bcount = ST_MAXRECSIZE_FIXED;
2888 			}
2889 		}
2890 	}
2891 
2892 #if !defined(lint)
2893 _NOTE(DATA_READABLE_WITHOUT_LOCK(scsi_tape::un_sbufp));
2894 #endif /* lint */
2895 	/*
2896 	 * For regular raw I/O and Fixed Block length devices, make sure
2897 	 * the adjusted block count is a whole multiple of the device
2898 	 * block size.
2899 	 */
2900 	if (bp != un->un_sbufp && un->un_bsize) {
2901 		bp->b_bcount -= (bp->b_bcount % un->un_bsize);
2902 	}
2903 }
2904 
2905 /*ARGSUSED*/
2906 static void
2907 st_uscsi_minphys(struct buf *bp)
2908 {
2909 	/*
2910 	 * do not break up because the CDB count would then be
2911 	 * incorrect and create spurious data underrun errors.
2912 	 */
2913 }
2914 
2915 static int
2916 st_rw(dev_t dev, struct uio *uio, int flag)
2917 {
2918 	int rval = 0;
2919 	long len;
2920 
2921 	GET_SOFT_STATE(dev);
2922 
2923 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2924 	    "st_rw(dev = 0x%lx, flag = %s)\n", dev,
2925 	    (flag == B_READ ? rd_str: wr_str));
2926 
2927 	/* get local copy of transfer length */
2928 	len = uio->uio_iov->iov_len;
2929 
2930 	mutex_enter(ST_MUTEX);
2931 
2932 	/*
2933 	 * If in fixed block size mode and requested read or write
2934 	 * is not an even multiple of that block size.
2935 	 */
2936 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
2937 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
2938 		    "%s: not modulo %d block size\n",
2939 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
2940 		rval = EINVAL;
2941 	}
2942 
2943 	/* If device has set granularity in the READ_BLKLIM we honor it. */
2944 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
2945 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
2946 		    "%s: not modulo %d device granularity\n",
2947 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
2948 		rval = EINVAL;
2949 	}
2950 
2951 	if (rval != 0) {
2952 		un->un_errno = rval;
2953 		mutex_exit(ST_MUTEX);
2954 		return (rval);
2955 	}
2956 
2957 	un->un_silent_skip = 0;
2958 	mutex_exit(ST_MUTEX);
2959 
2960 	len = uio->uio_resid;
2961 
2962 	rval = physio(st_strategy, (struct buf *)NULL,
2963 		dev, flag, st_minphys, uio);
2964 	/*
2965 	 * if we have hit logical EOT during this xfer and there is not a
2966 	 * full residue, then set un_eof back  to ST_EOM to make sure that
2967 	 * the user will see at least one zero write
2968 	 * after this short write
2969 	 */
2970 	mutex_enter(ST_MUTEX);
2971 	if (un->un_eof > ST_NO_EOF) {
2972 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2973 		"un_eof=%d resid=%lx\n", un->un_eof, uio->uio_resid);
2974 	}
2975 	if (un->un_eof >= ST_EOM && (flag == B_WRITE)) {
2976 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
2977 			un->un_eof = ST_EOM;
2978 		} else if (uio->uio_resid == len) {
2979 			un->un_eof = ST_NO_EOF;
2980 		}
2981 	}
2982 
2983 	if (un->un_silent_skip && uio->uio_resid != len) {
2984 		un->un_eof = ST_EOF;
2985 		un->un_blkno = un->un_save_blkno;
2986 		un->un_fileno--;
2987 	}
2988 
2989 	un->un_errno = rval;
2990 
2991 	mutex_exit(ST_MUTEX);
2992 
2993 	return (rval);
2994 }
2995 
2996 static int
2997 st_arw(dev_t dev, struct aio_req *aio, int flag)
2998 {
2999 	struct uio *uio = aio->aio_uio;
3000 	int rval = 0;
3001 	long len;
3002 
3003 	GET_SOFT_STATE(dev);
3004 
3005 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3006 	    "st_rw(dev = 0x%lx, flag = %s)\n", dev,
3007 	    (flag == B_READ ? rd_str: wr_str));
3008 
3009 	/* get local copy of transfer length */
3010 	len = uio->uio_iov->iov_len;
3011 
3012 	mutex_enter(ST_MUTEX);
3013 
3014 	/*
3015 	 * If in fixed block size mode and requested read or write
3016 	 * is not an even multiple of that block size.
3017 	 */
3018 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
3019 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3020 		    "%s: not modulo %d block size\n",
3021 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3022 		rval = EINVAL;
3023 	}
3024 
3025 	/* If device has set granularity in the READ_BLKLIM we honor it. */
3026 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3027 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3028 		    "%s: not modulo %d device granularity\n",
3029 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
3030 		rval = EINVAL;
3031 	}
3032 
3033 	if (rval != 0) {
3034 		un->un_errno = rval;
3035 		mutex_exit(ST_MUTEX);
3036 		return (rval);
3037 	}
3038 
3039 	mutex_exit(ST_MUTEX);
3040 
3041 	len = uio->uio_resid;
3042 
3043 	rval = aphysio(st_strategy, anocancel, dev, flag, st_minphys, aio);
3044 
3045 	/*
3046 	 * if we have hit logical EOT during this xfer and there is not a
3047 	 * full residue, then set un_eof back  to ST_EOM to make sure that
3048 	 * the user will see at least one zero write
3049 	 * after this short write
3050 	 *
3051 	 * we keep this here just in case the application is not using
3052 	 * persistent errors
3053 	 */
3054 	mutex_enter(ST_MUTEX);
3055 	if (un->un_eof > ST_NO_EOF) {
3056 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3057 		    "un_eof=%d resid=%lx\n", un->un_eof, uio->uio_resid);
3058 	}
3059 	if (un->un_eof >= ST_EOM && (flag == B_WRITE)) {
3060 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
3061 			un->un_eof = ST_EOM;
3062 		} else if (uio->uio_resid == len && !IS_PE_FLAG_SET(un)) {
3063 			un->un_eof = ST_NO_EOF;
3064 		}
3065 	}
3066 	un->un_errno = rval;
3067 	mutex_exit(ST_MUTEX);
3068 
3069 	return (rval);
3070 }
3071 
3072 
3073 
3074 static int
3075 st_strategy(struct buf *bp)
3076 {
3077 	struct scsi_tape *un;
3078 	dev_t dev = bp->b_edev;
3079 
3080 	/*
3081 	 * validate arguments
3082 	 */
3083 	if ((un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev))) == NULL) {
3084 		bp->b_resid = bp->b_bcount;
3085 		mutex_enter(ST_MUTEX);
3086 		st_bioerror(bp, ENXIO);
3087 		mutex_exit(ST_MUTEX);
3088 		goto error;
3089 	}
3090 
3091 	mutex_enter(ST_MUTEX);
3092 
3093 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
3094 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
3095 	}
3096 
3097 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3098 	    "st_strategy(): bcount=0x%lx, fileno=%d, blkno=%lx, eof=%d\n",
3099 	    bp->b_bcount, un->un_fileno, un->un_blkno, un->un_eof);
3100 
3101 	/*
3102 	 * If persistent errors have been flagged, just nix this one. We wait
3103 	 * for any outstanding I/O's below, so we will be in order.
3104 	 */
3105 	if (IS_PE_FLAG_SET(un))
3106 		goto exit;
3107 
3108 	if (bp != un->un_sbufp) {
3109 		char reading = bp->b_flags & B_READ;
3110 		int wasopening = 0;
3111 
3112 		/*
3113 		 * If we haven't done/checked reservation on the tape unit
3114 		 * do it now.
3115 		 */
3116 		if (!(un->un_rsvd_status & ST_INIT_RESERVE)) {
3117 		    if (ST_RESERVE_SUPPORTED(un)) {
3118 				if (st_tape_reservation_init(dev)) {
3119 					st_bioerror(bp, un->un_errno);
3120 					goto exit;
3121 				}
3122 		    } else if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
3123 				/*
3124 				 * Enter here to restore position for possible
3125 				 * resets when the device was closed and opened
3126 				 * in O_NDELAY mode subsequently
3127 				 */
3128 				un->un_state = ST_STATE_INITIALIZING;
3129 				(void) st_cmd(dev, SCMD_TEST_UNIT_READY,
3130 				    0, SYNC_CMD);
3131 				un->un_state = ST_STATE_OPEN_PENDING_IO;
3132 			}
3133 		    un->un_rsvd_status |= ST_INIT_RESERVE;
3134 		}
3135 
3136 		/*
3137 		 * If we are offline, we have to initialize everything first.
3138 		 * This is to handle either when opened with O_NDELAY, or
3139 		 * we just got a new tape in the drive, after an offline.
3140 		 * We don't observe O_NDELAY past the open,
3141 		 * as it will not make sense for tapes.
3142 		 */
3143 		if (un->un_state == ST_STATE_OFFLINE || un->un_restore_pos) {
3144 			/* reset state to avoid recursion */
3145 			un->un_state = ST_STATE_INITIALIZING;
3146 			if (st_tape_init(dev)) {
3147 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3148 					"stioctl : OFFLINE init failure ");
3149 				un->un_state = ST_STATE_OFFLINE;
3150 				un->un_fileno = -1;
3151 				goto b_done_err;
3152 			}
3153 			un->un_state = ST_STATE_OPEN_PENDING_IO;
3154 		}
3155 		/*
3156 		 * Check for legal operations
3157 		 */
3158 		if (un->un_fileno < 0) {
3159 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3160 			    "strategy with un->un_fileno < 0\n");
3161 			goto b_done_err;
3162 		}
3163 
3164 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3165 		    "st_strategy(): regular io\n");
3166 
3167 		/*
3168 		 * Process this first. If we were reading, and we're pending
3169 		 * logical eot, that means we've bumped one file mark too far.
3170 		 */
3171 
3172 		/*
3173 		 * Recursion warning: st_cmd will route back through here.
3174 		 */
3175 		if (un->un_eof == ST_EOT_PENDING) {
3176 			if (st_cmd(dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)) {
3177 				un->un_fileno = -1;
3178 				un->un_density_known = 0;
3179 				goto b_done_err;
3180 			}
3181 			un->un_blkno = 0; /* fix up block number.. */
3182 			un->un_eof = ST_EOT;
3183 		}
3184 
3185 		/*
3186 		 * If we are in the process of opening, we may have to
3187 		 * determine/set the correct density. We also may have
3188 		 * to do a test_append (if QIC) to see whether we are
3189 		 * in a position to append to the end of the tape.
3190 		 *
3191 		 * If we're already at logical eot, we transition
3192 		 * to ST_NO_EOF. If we're at physical eot, we punt
3193 		 * to the switch statement below to handle.
3194 		 */
3195 		if ((un->un_state == ST_STATE_OPEN_PENDING_IO) ||
3196 		    (un->un_test_append && (un->un_dp->options & ST_QIC))) {
3197 
3198 			if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
3199 				if (st_determine_density(dev, (int)reading)) {
3200 					goto b_done_err;
3201 				}
3202 			}
3203 
3204 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3205 			    "pending_io@fileno %d rw %d qic %d eof %d\n",
3206 			    un->un_fileno, (int)reading,
3207 			    (un->un_dp->options & ST_QIC) ? 1 : 0,
3208 			    un->un_eof);
3209 
3210 			if (!reading && un->un_eof != ST_EOM) {
3211 				if (un->un_eof == ST_EOT) {
3212 					un->un_eof = ST_NO_EOF;
3213 				} else if (un->un_fileno > 0 &&
3214 				    (un->un_dp->options & ST_QIC)) {
3215 					/*
3216 					 * st_test_append() will do it all
3217 					 */
3218 					st_test_append(bp);
3219 					goto done;
3220 				}
3221 			}
3222 			if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
3223 				wasopening = 1;
3224 			}
3225 			un->un_laststate = un->un_state;
3226 			un->un_state = ST_STATE_OPEN;
3227 		}
3228 
3229 
3230 		/*
3231 		 * Process rest of END OF FILE and END OF TAPE conditions
3232 		 */
3233 
3234 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3235 		    "un_eof=%x, wasopening=%x\n",
3236 		    un->un_eof, wasopening);
3237 
3238 		switch (un->un_eof) {
3239 		case ST_EOM:
3240 			/*
3241 			 * This allows writes to proceed past physical
3242 			 * eot. We'll *really* be in trouble if the
3243 			 * user continues blindly writing data too
3244 			 * much past this point (unwind the tape).
3245 			 * Physical eot really means 'early warning
3246 			 * eot' in this context.
3247 			 *
3248 			 * Every other write from now on will succeed
3249 			 * (if sufficient  tape left).
3250 			 * This write will return with resid == count
3251 			 * but the next one should be successful
3252 			 *
3253 			 * Note that we only transition to logical EOT
3254 			 * if the last state wasn't the OPENING state.
3255 			 * We explicitly prohibit running up to physical
3256 			 * eot, closing the device, and then re-opening
3257 			 * to proceed. Trailer records may only be gotten
3258 			 * at by keeping the tape open after hitting eot.
3259 			 *
3260 			 * Also note that ST_EOM cannot be set by reading-
3261 			 * this can only be set during writing. Reading
3262 			 * up to the end of the tape gets a blank check
3263 			 * or a double-filemark indication (ST_EOT_PENDING),
3264 			 * and we prohibit reading after that point.
3265 			 *
3266 			 */
3267 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOM\n");
3268 			if (wasopening == 0) {
3269 				/*
3270 				 * this allows st_rw() to reset it back to
3271 				 * ST_EOM to make sure that the application
3272 				 * will see a zero write
3273 				 */
3274 				un->un_eof = ST_WRITE_AFTER_EOM;
3275 			}
3276 			un->un_status = SUN_KEY_EOT;
3277 			goto b_done;
3278 
3279 		case ST_WRITE_AFTER_EOM:
3280 		case ST_EOT:
3281 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOT\n");
3282 			un->un_status = SUN_KEY_EOT;
3283 			if (SVR4_BEHAVIOR && reading) {
3284 				goto b_done_err;
3285 			}
3286 
3287 			if (reading) {
3288 				goto b_done;
3289 			}
3290 			un->un_eof = ST_NO_EOF;
3291 			break;
3292 
3293 		case ST_EOF_PENDING:
3294 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3295 			    "EOF PENDING\n");
3296 			un->un_status = SUN_KEY_EOF;
3297 			if (SVR4_BEHAVIOR) {
3298 				un->un_eof = ST_EOF;
3299 				goto b_done;
3300 			}
3301 			/* FALLTHROUGH */
3302 		case ST_EOF:
3303 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOF\n");
3304 			un->un_status = SUN_KEY_EOF;
3305 			if (SVR4_BEHAVIOR) {
3306 				goto b_done_err;
3307 			}
3308 
3309 			if (BSD_BEHAVIOR) {
3310 				un->un_eof = ST_NO_EOF;
3311 				un->un_fileno += 1;
3312 				un->un_blkno   = 0;
3313 			}
3314 
3315 			if (reading) {
3316 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3317 				    "now file %d (read)\n",
3318 				    un->un_fileno);
3319 				goto b_done;
3320 			}
3321 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3322 			    "now file %d (write)\n", un->un_fileno);
3323 			break;
3324 		default:
3325 			un->un_status = 0;
3326 			break;
3327 		}
3328 	}
3329 
3330 	bp->b_flags &= ~(B_DONE);
3331 	st_bioerror(bp, 0);
3332 	bp->av_forw = NULL;
3333 	bp->b_resid = 0;
3334 	SET_BP_PKT(bp, 0);
3335 
3336 
3337 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3338 	    "st_strategy: cmd=0x%p  count=%ld  resid=%ld flags=0x%x"
3339 	    " pkt=0x%p\n",
3340 	    (void *)bp->b_forw, bp->b_bcount,
3341 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
3342 
3343 #if defined(__i386) || defined(__amd64)
3344 	/*
3345 	 * We will replace bp with a new bp that can do big blk xfer
3346 	 * if the requested xfer size is bigger than ST_BIGBLK_XFER
3347 	 *
3348 	 * Also, we need to make sure that we're handling real I/O
3349 	 * by checking group 0/1 SCSI I/O commands, if needed
3350 	 */
3351 	if (bp->b_bcount > ST_BIGBLK_XFER &&
3352 	    (bp != un->un_sbufp					||
3353 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_READ		||
3354 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_READ_G1	||
3355 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE	||
3356 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE_G1)) {
3357 		mutex_exit(ST_MUTEX);
3358 		bp = st_get_bigblk_bp(bp);
3359 		mutex_enter(ST_MUTEX);
3360 	}
3361 #endif
3362 
3363 	/* put on wait queue */
3364 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3365 	    "st_strategy: un->un_quef = 0x%p, bp = 0x%p\n",
3366 	    (void *)un->un_quef, (void *)bp);
3367 
3368 	if (un->un_quef) {
3369 		un->un_quel->b_actf = bp;
3370 	} else {
3371 		un->un_quef = bp;
3372 	}
3373 	un->un_quel = bp;
3374 
3375 	ST_DO_KSTATS(bp, kstat_waitq_enter);
3376 
3377 	st_start(un);
3378 
3379 done:
3380 	mutex_exit(ST_MUTEX);
3381 	return (0);
3382 
3383 
3384 error:
3385 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3386 	    "st_strategy: error exit\n");
3387 
3388 	biodone(bp);
3389 	return (0);
3390 
3391 b_done_err:
3392 	st_bioerror(bp, EIO);
3393 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3394 	    "st_strategy : EIO b_done_err\n");
3395 
3396 b_done:
3397 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3398 	    "st_strategy: b_done\n");
3399 
3400 exit:
3401 	/*
3402 	 * make sure no commands are outstanding or waiting before closing,
3403 	 * so we can guarantee order
3404 	 */
3405 	st_wait_for_io(un);
3406 	un->un_err_resid = bp->b_resid = bp->b_bcount;
3407 
3408 	/* override errno here, if persistent errors were flagged */
3409 	if (IS_PE_FLAG_SET(un))
3410 		bioerror(bp, un->un_errno);
3411 
3412 	mutex_exit(ST_MUTEX);
3413 
3414 	biodone(bp);
3415 	ASSERT(mutex_owned(ST_MUTEX) == 0);
3416 	return (0);
3417 }
3418 
3419 
3420 
3421 /*
3422  * this routine spaces forward over filemarks
3423  */
3424 static int
3425 st_space_fmks(dev_t dev, int count)
3426 {
3427 	int rval = 0;
3428 
3429 	GET_SOFT_STATE(dev);
3430 
3431 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3432 	    "st_space_fmks(dev = 0x%lx, count = %d)\n", dev, count);
3433 
3434 	ASSERT(mutex_owned(ST_MUTEX));
3435 
3436 	/*
3437 	 * the risk with doing only one space operation is that we
3438 	 * may accidentily jump in old data
3439 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
3440 	 * because the 8200 does not append a marker; in order not to
3441 	 * sacrifice the fast file skip, we do a slow skip if the low
3442 	 * density device has been opened
3443 	 */
3444 
3445 	if ((un->un_dp->options & ST_KNOWS_EOD) &&
3446 	    !((un->un_dp->type == ST_TYPE_EXB8500 && MT_DENSITY(dev) == 0))) {
3447 		if (st_cmd(dev, SCMD_SPACE, Fmk(count), SYNC_CMD)) {
3448 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3449 			    "space_fmks : EIO can't do space cmd #1\n");
3450 			rval = EIO;
3451 		}
3452 	} else {
3453 		while (count > 0) {
3454 			if (st_cmd(dev, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
3455 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3456 				    "space_fmks : EIO can't do space cmd #2\n");
3457 				rval = EIO;
3458 				break;
3459 			}
3460 			count -= 1;
3461 			/*
3462 			 * read a block to see if we have reached
3463 			 * end of medium (double filemark for reel or
3464 			 * medium error for others)
3465 			 */
3466 			if (count > 0) {
3467 				if (st_cmd(dev, SCMD_SPACE, Blk(1),
3468 				    SYNC_CMD)) {
3469 					ST_DEBUG2(ST_DEVINFO, st_label,
3470 					    SCSI_DEBUG,
3471 					    "space_fmks : EIO can't do "
3472 					    "space cmd #3\n");
3473 					rval = EIO;
3474 					break;
3475 				}
3476 				if ((un->un_eof >= ST_EOF_PENDING) &&
3477 				    (un->un_dp->options & ST_REEL)) {
3478 					un->un_status = SUN_KEY_EOT;
3479 					ST_DEBUG2(ST_DEVINFO, st_label,
3480 					    SCSI_DEBUG,
3481 					    "space_fmks : EIO ST_REEL\n");
3482 					rval = EIO;
3483 					break;
3484 				} else if (IN_EOF(un)) {
3485 					un->un_eof = ST_NO_EOF;
3486 					un->un_fileno++;
3487 					un->un_blkno = 0;
3488 					count--;
3489 				} else if (un->un_eof > ST_EOF) {
3490 					ST_DEBUG2(ST_DEVINFO, st_label,
3491 					    SCSI_DEBUG,
3492 					    "space_fmks, EIO > ST_EOF\n");
3493 					rval = EIO;
3494 					break;
3495 				}
3496 
3497 			}
3498 		}
3499 		un->un_err_resid = count;
3500 		un->un_err_fileno = un->un_fileno;
3501 		un->un_err_blkno = un->un_blkno;
3502 	}
3503 	ASSERT(mutex_owned(ST_MUTEX));
3504 	return (rval);
3505 }
3506 
3507 /*
3508  * this routine spaces to EOM
3509  *
3510  * it keeps track of the current filenumber and returns the filenumber after
3511  * the last successful space operation, we keep the number high because as
3512  * tapes are getting larger, the possibility of more and more files exist,
3513  * 0x100000 (1 Meg of files) probably will never have to be changed any time
3514  * soon
3515  */
3516 #define	MAX_SKIP	0x100000 /* somewhat arbitrary */
3517 
3518 static int
3519 st_find_eom(dev_t dev)
3520 {
3521 	int count, savefile;
3522 	struct scsi_tape *un;
3523 	int instance;
3524 
3525 	instance = MTUNIT(dev);
3526 	if ((un = ddi_get_soft_state(st_state, instance)) == NULL)
3527 		return (-1);
3528 
3529 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3530 	    "st_find_eom(dev = 0x%lx): fileno = %d\n", dev, un->un_fileno);
3531 
3532 	ASSERT(mutex_owned(ST_MUTEX));
3533 
3534 	savefile = un->un_fileno;
3535 
3536 	/*
3537 	 * see if the drive is smart enough to do the skips in
3538 	 * one operation; 1/2" use two filemarks
3539 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
3540 	 * because the 8200 does not append a marker; in order not to
3541 	 * sacrifice the fast file skip, we do a slow skip if the low
3542 	 * density device has been opened
3543 	 */
3544 	if ((un->un_dp->options & ST_KNOWS_EOD) &&
3545 	    !((un->un_dp->type == ST_TYPE_EXB8500 && MT_DENSITY(dev) == 0))) {
3546 		count = MAX_SKIP;
3547 	} else {
3548 		count = 1;
3549 	}
3550 
3551 	while (st_cmd(dev, SCMD_SPACE, Fmk(count), SYNC_CMD) == 0) {
3552 
3553 		savefile = un->un_fileno;
3554 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3555 			"count=%x, eof=%x, status=%x\n", count,  un->un_eof,
3556 			un->un_status);
3557 
3558 		/*
3559 		 * If we're not EOM smart,  space a record
3560 		 * to see whether we're now in the slot between
3561 		 * the two sequential filemarks that logical
3562 		 * EOM consists of (REEL) or hit nowhere land
3563 		 * (8mm).
3564 		 */
3565 		if (count == 1) {
3566 			/*
3567 			 * no fast skipping, check a record
3568 			 */
3569 			if (st_cmd(dev, SCMD_SPACE, Blk((1)), SYNC_CMD))
3570 				break;
3571 			else if ((un->un_eof >= ST_EOF_PENDING) &&
3572 			    (un->un_dp->options & ST_REEL)) {
3573 				un->un_status = KEY_BLANK_CHECK;
3574 				un->un_fileno++;
3575 				un->un_blkno = 0;
3576 				break;
3577 			} else if (IN_EOF(un)) {
3578 				un->un_eof = ST_NO_EOF;
3579 				un->un_fileno++;
3580 				un->un_blkno = 0;
3581 			} else if (un->un_eof > ST_EOF) {
3582 				break;
3583 			}
3584 		} else {
3585 			if (un->un_eof >  ST_EOF) {
3586 				break;
3587 			}
3588 		}
3589 	}
3590 
3591 	if (un->un_dp->options & ST_KNOWS_EOD) {
3592 		savefile = un->un_fileno;
3593 	}
3594 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3595 	    "st_find_eom: %x\n", savefile);
3596 	ASSERT(mutex_owned(ST_MUTEX));
3597 	return (savefile);
3598 }
3599 
3600 
3601 /*
3602  * this routine is frequently used in ioctls below;
3603  * it determines whether we know the density and if not will
3604  * determine it
3605  * if we have written the tape before, one or more filemarks are written
3606  *
3607  * depending on the stepflag, the head is repositioned to where it was before
3608  * the filemarks were written in order not to confuse step counts
3609  */
3610 #define	STEPBACK    0
3611 #define	NO_STEPBACK 1
3612 
3613 static int
3614 st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag)
3615 {
3616 
3617 	GET_SOFT_STATE(dev);
3618 
3619 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3620 	"st_check_density_or_wfm(dev= 0x%lx, wfm= %d, mode= %d, stpflg= %d)\n",
3621 	dev, wfm, mode, stepflag);
3622 
3623 	ASSERT(mutex_owned(ST_MUTEX));
3624 
3625 	/*
3626 	 * If we don't yet know the density of the tape we have inserted,
3627 	 * we have to either unconditionally set it (if we're 'writing'),
3628 	 * or we have to determine it. As side effects, check for any
3629 	 * write-protect errors, and for the need to put out any file-marks
3630 	 * before positioning a tape.
3631 	 *
3632 	 * If we are going to be spacing forward, and we haven't determined
3633 	 * the tape density yet, we have to do so now...
3634 	 */
3635 	if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
3636 		if (st_determine_density(dev, mode)) {
3637 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3638 			    "check_density_or_wfm : EIO can't determine "
3639 			    "density\n");
3640 			un->un_errno = EIO;
3641 			return (EIO);
3642 		}
3643 		/*
3644 		 * Presumably we are at BOT. If we attempt to write, it will
3645 		 * either work okay, or bomb. We don't do a st_test_append
3646 		 * unless we're past BOT.
3647 		 */
3648 		un->un_laststate = un->un_state;
3649 		un->un_state = ST_STATE_OPEN;
3650 
3651 	} else if (un->un_fileno >= 0 && un->un_fmneeded > 0 &&
3652 	    ((un->un_lastop == ST_OP_WEOF && wfm) ||
3653 	    (un->un_lastop == ST_OP_WRITE && wfm))) {
3654 
3655 		daddr_t blkno = un->un_blkno;
3656 		int fileno = un->un_fileno;
3657 
3658 		/*
3659 		 * We need to write one or two filemarks.
3660 		 * In the case of the HP, we need to
3661 		 * position the head between the two
3662 		 * marks.
3663 		 */
3664 		if ((un->un_fmneeded > 0) || (un->un_lastop == ST_OP_WEOF)) {
3665 			wfm = un->un_fmneeded;
3666 			un->un_fmneeded = 0;
3667 		}
3668 
3669 		if (st_write_fm(dev, wfm)) {
3670 			un->un_fileno = -1;
3671 			un->un_density_known = 0;
3672 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3673 			    "check_density_or_wfm : EIO can't write fm\n");
3674 			un->un_errno = EIO;
3675 			return (EIO);
3676 		}
3677 
3678 		if (stepflag == STEPBACK) {
3679 			if (st_cmd(dev, SCMD_SPACE, Fmk((-wfm)), SYNC_CMD)) {
3680 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3681 				    "check_density_or_wfm : EIO can't space "
3682 				    "(-wfm)\n");
3683 				un->un_errno = EIO;
3684 				return (EIO);
3685 			}
3686 			un->un_blkno = blkno;
3687 			un->un_fileno = fileno;
3688 		}
3689 	}
3690 
3691 	/*
3692 	 * Whatever we do at this point clears the state of the eof flag.
3693 	 */
3694 
3695 	un->un_eof = ST_NO_EOF;
3696 
3697 	/*
3698 	 * If writing, let's check that we're positioned correctly
3699 	 * at the end of tape before issuing the next write.
3700 	 */
3701 	if (!un->un_read_only) {
3702 		un->un_test_append = 1;
3703 	}
3704 
3705 	ASSERT(mutex_owned(ST_MUTEX));
3706 	return (0);
3707 }
3708 
3709 
3710 /*
3711  * Wait for all outstaning I/O's to complete
3712  *
3713  * we wait on both ncmds and the wait queue for times when we are flushing
3714  * after persistent errors are flagged, which is when ncmds can be 0, and the
3715  * queue can still have I/O's.  This way we preserve order of biodone's.
3716  */
3717 static void
3718 st_wait_for_io(struct scsi_tape *un)
3719 {
3720 	ASSERT(mutex_owned(ST_MUTEX));
3721 	while (un->un_ncmds || un->un_quef) {
3722 		cv_wait(&un->un_queue_cv, ST_MUTEX);
3723 	}
3724 }
3725 
3726 /*
3727  * This routine implements the ioctl calls.  It is called
3728  * from the device switch at normal priority.
3729  */
3730 /*ARGSUSED*/
3731 static int
3732 st_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p,
3733     int *rval_p)
3734 {
3735 	int tmp, rval = 0;
3736 
3737 	GET_SOFT_STATE(dev);
3738 
3739 	mutex_enter(ST_MUTEX);
3740 
3741 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3742 	    "st_ioctl(): fileno=%x, blkno=%lx, un_eof=%x, state = %d, "
3743 	    "pe_flag = %d\n",
3744 	    un->un_fileno, un->un_blkno, un->un_eof, un->un_state,
3745 	    IS_PE_FLAG_SET(un));
3746 
3747 	/*
3748 	 * We don't want to block on these, so let them through
3749 	 * and we don't care about setting driver states here.
3750 	 */
3751 	if ((cmd == MTIOCGETDRIVETYPE) ||
3752 	    (cmd == MTIOCGUARANTEEDORDER) ||
3753 	    (cmd == MTIOCPERSISTENTSTATUS)) {
3754 		goto check_commands;
3755 	}
3756 
3757 	/*
3758 	 * wait for all outstanding commands to complete, or be dequeued.
3759 	 * And because ioctl's are synchronous commands, any return value
3760 	 * after this,  will be in order
3761 	 */
3762 	st_wait_for_io(un);
3763 
3764 	/*
3765 	 * allow only a through clear errors and persistent status, and
3766 	 * status
3767 	 */
3768 	if (IS_PE_FLAG_SET(un)) {
3769 		if ((cmd == MTIOCLRERR) ||
3770 		    (cmd == MTIOCPERSISTENT) ||
3771 		    (cmd == MTIOCGET) ||
3772 		    (cmd == USCSIGETRQS)) {
3773 			goto check_commands;
3774 		} else {
3775 			rval = un->un_errno;
3776 			goto exit;
3777 		}
3778 	}
3779 
3780 	un->un_throttle = 1;	/* > 1 will never happen here */
3781 	un->un_errno = 0;	/* start clean from here */
3782 
3783 	/*
3784 	 * first and foremost, handle any ST_EOT_PENDING cases.
3785 	 * That is, if a logical eot is pending notice, notice it.
3786 	 */
3787 	if (un->un_eof == ST_EOT_PENDING) {
3788 		int resid = un->un_err_resid;
3789 		uchar_t status = un->un_status;
3790 		uchar_t lastop = un->un_lastop;
3791 
3792 		if (st_cmd(dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)) {
3793 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3794 			    "stioctl : EIO can't space fmk(-1)\n");
3795 			rval = EIO;
3796 			goto exit;
3797 		}
3798 		un->un_lastop = lastop; /* restore last operation */
3799 		if (status == SUN_KEY_EOF) {
3800 			un->un_status = SUN_KEY_EOT;
3801 		} else {
3802 			un->un_status = status;
3803 		}
3804 		un->un_err_resid  = resid;
3805 		un->un_err_blkno = un->un_blkno = 0; /* fix up block number */
3806 		un->un_eof = ST_EOT;	/* now we're at logical eot */
3807 	}
3808 
3809 	/*
3810 	 * now, handle the rest of the situations
3811 	 */
3812 check_commands:
3813 	switch (cmd) {
3814 	case MTIOCGET:
3815 		{
3816 #ifdef _MULTI_DATAMODEL
3817 			/*
3818 			 * For use when a 32 bit app makes a call into a
3819 			 * 64 bit ioctl
3820 			 */
3821 			struct mtget32		mtg_local32;
3822 			struct mtget32 		*mtget_32 = &mtg_local32;
3823 #endif /* _MULTI_DATAMODEL */
3824 
3825 			/* Get tape status */
3826 			struct mtget mtg_local;
3827 			struct mtget *mtget = &mtg_local;
3828 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3829 				"st_ioctl: MTIOCGET\n");
3830 
3831 			bzero(mtget, sizeof (struct mtget));
3832 			mtget->mt_erreg = un->un_status;
3833 			mtget->mt_resid = un->un_err_resid;
3834 			mtget->mt_dsreg = un->un_retry_ct;
3835 			mtget->mt_fileno = un->un_err_fileno;
3836 			mtget->mt_blkno = un->un_err_blkno;
3837 			mtget->mt_type = un->un_dp->type;
3838 			mtget->mt_flags = MTF_SCSI | MTF_ASF;
3839 			if (un->un_dp->options & ST_REEL) {
3840 				mtget->mt_flags |= MTF_REEL;
3841 				mtget->mt_bf = 20;
3842 			} else {		/* 1/4" cartridges */
3843 				switch (mtget->mt_type) {
3844 				/* Emulex cartridge tape */
3845 				case MT_ISMT02:
3846 					mtget->mt_bf = 40;
3847 					break;
3848 				default:
3849 					mtget->mt_bf = 126;
3850 					break;
3851 				}
3852 			}
3853 
3854 			/*
3855 			 * If large transfers are allowed and drive options
3856 			 * has no record size limit set. Calculate blocking
3857 			 * factor from the lesser of maxbsize and maxdma.
3858 			 */
3859 			if ((un->un_allow_large_xfer) &&
3860 			    (un->un_dp->options & ST_NO_RECSIZE_LIMIT)) {
3861 				mtget->mt_bf = min(un->un_maxbsize,
3862 				    un->un_maxdma) / SECSIZE;
3863 			}
3864 
3865 			rval = st_check_clean_bit(dev);
3866 			if (rval == -1) {
3867 				rval = EIO;
3868 				goto exit;
3869 			} else {
3870 				mtget->mt_flags |= (ushort_t)rval;
3871 				rval = 0;
3872 			}
3873 
3874 			un->un_status = 0;		/* Reset status */
3875 			un->un_err_resid = 0;
3876 			tmp = sizeof (struct mtget);
3877 
3878 #ifdef _MULTI_DATAMODEL
3879 
3880 		switch (ddi_model_convert_from(flag & FMODELS)) {
3881 		case DDI_MODEL_ILP32:
3882 			/*
3883 			 * Convert 64 bit back to 32 bit before doing
3884 			 * copyout. This is what the ILP32 app expects.
3885 			 */
3886 			mtget_32->mt_erreg = 	mtget->mt_erreg;
3887 			mtget_32->mt_resid = 	mtget->mt_resid;
3888 			mtget_32->mt_dsreg = 	mtget->mt_dsreg;
3889 			mtget_32->mt_fileno = 	(daddr32_t)mtget->mt_fileno;
3890 			mtget_32->mt_blkno = 	(daddr32_t)mtget->mt_blkno;
3891 			mtget_32->mt_type =  	mtget->mt_type;
3892 			mtget_32->mt_flags = 	mtget->mt_flags;
3893 			mtget_32->mt_bf = 	mtget->mt_bf;
3894 
3895 			if (ddi_copyout(mtget_32, (void *)arg,
3896 			    sizeof (struct mtget32), flag)) {
3897 				rval = EFAULT;
3898 			}
3899 			break;
3900 
3901 		case DDI_MODEL_NONE:
3902 			if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
3903 				rval = EFAULT;
3904 			}
3905 			break;
3906 		}
3907 #else /* ! _MULTI_DATAMODE */
3908 		if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
3909 			rval = EFAULT;
3910 		}
3911 #endif /* _MULTI_DATAMODE */
3912 
3913 			break;
3914 		}
3915 	case MTIOCSTATE:
3916 		{
3917 			/*
3918 			 * return when media presence matches state
3919 			 */
3920 			enum mtio_state state;
3921 
3922 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3923 				"st_ioctl: MTIOCSTATE\n");
3924 
3925 			if (ddi_copyin((void *)arg, &state, sizeof (int), flag))
3926 				rval = EFAULT;
3927 
3928 			mutex_exit(ST_MUTEX);
3929 
3930 			rval = st_check_media(dev, state);
3931 
3932 			mutex_enter(ST_MUTEX);
3933 
3934 			if (rval != 0) {
3935 				break;
3936 			}
3937 
3938 			if (ddi_copyout(&un->un_mediastate, (void *)arg,
3939 			    sizeof (int), flag))
3940 				rval = EFAULT;
3941 			break;
3942 
3943 		}
3944 
3945 	case MTIOCGETDRIVETYPE:
3946 		{
3947 #ifdef _MULTI_DATAMODEL
3948 		/*
3949 		 * For use when a 32 bit app makes a call into a
3950 		 * 64 bit ioctl
3951 		 */
3952 		struct mtdrivetype_request32	mtdtrq32;
3953 #endif /* _MULTI_DATAMODEL */
3954 
3955 			/*
3956 			 * return mtdrivetype
3957 			 */
3958 			struct mtdrivetype_request mtdtrq;
3959 			struct mtdrivetype mtdrtyp;
3960 			struct mtdrivetype *mtdt = &mtdrtyp;
3961 			struct st_drivetype *stdt = un->un_dp;
3962 
3963 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3964 				"st_ioctl: MTIOCGETDRIVETYPE\n");
3965 
3966 #ifdef _MULTI_DATAMODEL
3967 		switch (ddi_model_convert_from(flag & FMODELS)) {
3968 		case DDI_MODEL_ILP32:
3969 		{
3970 			if (ddi_copyin((void *)arg, &mtdtrq32,
3971 			    sizeof (struct mtdrivetype_request32), flag)) {
3972 				rval = EFAULT;
3973 				break;
3974 			}
3975 			mtdtrq.size = mtdtrq32.size;
3976 			mtdtrq.mtdtp =
3977 			    (struct  mtdrivetype *)(uintptr_t)mtdtrq32.mtdtp;
3978 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3979 				"st_ioctl: size 0x%x\n", mtdtrq.size);
3980 			break;
3981 		}
3982 		case DDI_MODEL_NONE:
3983 			if (ddi_copyin((void *)arg, &mtdtrq,
3984 			    sizeof (struct mtdrivetype_request), flag)) {
3985 				rval = EFAULT;
3986 				break;
3987 			}
3988 			break;
3989 		}
3990 
3991 #else /* ! _MULTI_DATAMODEL */
3992 		if (ddi_copyin((void *)arg, &mtdtrq,
3993 		    sizeof (struct mtdrivetype_request), flag)) {
3994 			rval = EFAULT;
3995 			break;
3996 		}
3997 #endif /* _MULTI_DATAMODEL */
3998 
3999 			/*
4000 			 * if requested size is < 0 then return
4001 			 * error.
4002 			 */
4003 			if (mtdtrq.size < 0) {
4004 				rval = EINVAL;
4005 				break;
4006 			}
4007 			bzero(mtdt, sizeof (struct mtdrivetype));
4008 			(void) strncpy(mtdt->name, stdt->name, ST_NAMESIZE);
4009 			(void) strncpy(mtdt->vid, stdt->vid, VIDPIDLEN - 1);
4010 			mtdt->type = stdt->type;
4011 			mtdt->bsize = stdt->bsize;
4012 			mtdt->options = stdt->options;
4013 			mtdt->max_rretries = stdt->max_rretries;
4014 			mtdt->max_wretries = stdt->max_wretries;
4015 			for (tmp = 0; tmp < NDENSITIES; tmp++)
4016 				mtdt->densities[tmp] = stdt->densities[tmp];
4017 			mtdt->default_density = stdt->default_density;
4018 			/*
4019 			 * Speed hasn't been used since the hayday of reel tape.
4020 			 * For all drives not setting the option ST_KNOWS_MEDIA
4021 			 * the speed member renamed to mediatype are zeros.
4022 			 * Those drives that have ST_KNOWS_MEDIA set use the
4023 			 * new mediatype member which is used to figure the
4024 			 * type of media loaded.
4025 			 *
4026 			 * So as to not break applications speed in the
4027 			 * mtdrivetype structure is not renamed.
4028 			 */
4029 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
4030 				mtdt->speeds[tmp] = stdt->mediatype[tmp];
4031 			}
4032 			mtdt->non_motion_timeout = stdt->non_motion_timeout;
4033 			mtdt->io_timeout = stdt->io_timeout;
4034 			mtdt->rewind_timeout = stdt->rewind_timeout;
4035 			mtdt->space_timeout = stdt->space_timeout;
4036 			mtdt->load_timeout = stdt->load_timeout;
4037 			mtdt->unload_timeout = stdt->unload_timeout;
4038 			mtdt->erase_timeout = stdt->erase_timeout;
4039 
4040 			/*
4041 			 * Limit the maximum length of the result to
4042 			 * sizeof (struct mtdrivetype).
4043 			 */
4044 			tmp = sizeof (struct mtdrivetype);
4045 			if (mtdtrq.size < tmp)
4046 				tmp = mtdtrq.size;
4047 			if (ddi_copyout(mtdt, mtdtrq.mtdtp, tmp, flag)) {
4048 				rval = EFAULT;
4049 			}
4050 			break;
4051 		}
4052 	case MTIOCPERSISTENT:
4053 		{
4054 			int persistence = 0;
4055 
4056 			if (ddi_copyin((void *)arg, &persistence,
4057 			    sizeof (int), flag)) {
4058 				rval = EFAULT;
4059 				break;
4060 			}
4061 
4062 			/* non zero sets it, only 0 turns it off */
4063 			un->un_persistence = (uchar_t)persistence ? 1 : 0;
4064 
4065 			if (un->un_persistence)
4066 				TURN_PE_ON(un);
4067 			else
4068 				TURN_PE_OFF(un);
4069 
4070 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4071 			    "st_ioctl: MTIOCPERSISTENT : persistence = %d\n",
4072 			    un->un_persistence);
4073 
4074 			break;
4075 		}
4076 	case MTIOCPERSISTENTSTATUS:
4077 		{
4078 			int persistence = (int)un->un_persistence;
4079 
4080 			if (ddi_copyout(&persistence, (void *)arg,
4081 			    sizeof (int), flag)) {
4082 				rval = EFAULT;
4083 			}
4084 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4085 			    "st_ioctl: MTIOCPERSISTENTSTATUS:persistece = %d\n",
4086 			    un->un_persistence);
4087 
4088 			break;
4089 		}
4090 
4091 
4092 	case MTIOCLRERR:
4093 		{
4094 			/* clear persistent errors */
4095 
4096 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4097 			    "st_ioctl: MTIOCLRERR\n");
4098 
4099 			CLEAR_PE(un);
4100 
4101 			break;
4102 		}
4103 
4104 	case MTIOCGUARANTEEDORDER:
4105 		{
4106 			/*
4107 			 * this is just a holder to make a valid ioctl and
4108 			 * it won't be in any earlier release
4109 			 */
4110 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4111 			    "st_ioctl: MTIOCGUARANTEEDORDER\n");
4112 
4113 			break;
4114 		}
4115 
4116 	case MTIOCRESERVE:
4117 		{
4118 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4119 			    "st_ioctl: MTIOCRESERVE\n");
4120 
4121 			/*
4122 			 * Check if Reserve/Release is supported.
4123 			 */
4124 			if (!(ST_RESERVE_SUPPORTED(un))) {
4125 				rval = ENOTTY;
4126 				break;
4127 			}
4128 
4129 			rval = st_reserve_release(dev, ST_RESERVE);
4130 
4131 			if (rval == 0) {
4132 				un->un_rsvd_status |= ST_PRESERVE_RESERVE;
4133 			}
4134 			break;
4135 		}
4136 
4137 	case MTIOCRELEASE:
4138 		{
4139 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4140 			    "st_ioctl: MTIOCRELEASE\n");
4141 
4142 			/*
4143 			 * Check if Reserve/Release is supported.
4144 			 */
4145 			if (!(ST_RESERVE_SUPPORTED(un))) {
4146 				rval = ENOTTY;
4147 				break;
4148 			}
4149 
4150 			un->un_rsvd_status &= ~ST_PRESERVE_RESERVE;
4151 
4152 			break;
4153 		}
4154 
4155 	case MTIOCFORCERESERVE:
4156 		{
4157 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4158 			    "st_ioctl: MTIOCFORCERESERVE\n");
4159 
4160 			/*
4161 			 * Check if Reserve/Release is supported.
4162 			 */
4163 			if (!(ST_RESERVE_SUPPORTED(un))) {
4164 				rval = ENOTTY;
4165 				break;
4166 			}
4167 			/*
4168 			 * allow only super user to run this.
4169 			 */
4170 			if (drv_priv(cred_p) != 0) {
4171 				rval = EPERM;
4172 				break;
4173 			}
4174 			/*
4175 			 * Throw away reserve,
4176 			 * not using test-unit-ready
4177 			 * since reserve can succeed without tape being
4178 			 * present in the drive.
4179 			 */
4180 			(void) st_reserve_release(dev, ST_RESERVE);
4181 
4182 			rval = st_take_ownership(dev);
4183 
4184 			break;
4185 		}
4186 	case USCSIGETRQS:
4187 		{
4188 #ifdef _MULTI_DATAMODEL
4189 		/*
4190 		 * For use when a 32 bit app makes a call into a
4191 		 * 64 bit ioctl
4192 		 */
4193 		struct uscsi_rqs32	urqs_32;
4194 		struct uscsi_rqs32	*urqs_32_ptr = &urqs_32;
4195 #endif /* _MULTI_DATAMODEL */
4196 			struct uscsi_rqs	urqs;
4197 			struct uscsi_rqs	*urqs_ptr = &urqs;
4198 			ushort_t		len;
4199 #ifdef _MULTI_DATAMODEL
4200 		switch (ddi_model_convert_from(flag & FMODELS)) {
4201 		case DDI_MODEL_ILP32:
4202 		{
4203 			if (ddi_copyin((void *)arg, urqs_32_ptr,
4204 			    sizeof (struct uscsi_rqs32), flag)) {
4205 				rval = EFAULT;
4206 				break;
4207 			}
4208 			urqs_ptr->rqs_buflen = urqs_32_ptr->rqs_buflen;
4209 			urqs_ptr->rqs_bufaddr =
4210 			    (caddr_t)(uintptr_t)urqs_32_ptr->rqs_bufaddr;
4211 			break;
4212 		}
4213 		case DDI_MODEL_NONE:
4214 			if (ddi_copyin((void *)arg, urqs_ptr,
4215 			    sizeof (struct uscsi_rqs), flag)) {
4216 				rval = EFAULT;
4217 				break;
4218 			}
4219 		}
4220 #else /* ! _MULTI_DATAMODEL */
4221 		if (ddi_copyin((void *)arg, urqs_ptr, sizeof (urqs), flag)) {
4222 			rval = EFAULT;
4223 			break;
4224 		}
4225 #endif /* _MULTI_DATAMODEL */
4226 
4227 			urqs_ptr->rqs_flags = (int)un->un_rqs_state &
4228 			    (ST_RQS_OVR | ST_RQS_VALID);
4229 			if (urqs_ptr->rqs_buflen <= SENSE_LENGTH) {
4230 			    len = urqs_ptr->rqs_buflen;
4231 			    urqs_ptr->rqs_resid = 0;
4232 			} else {
4233 			    len = SENSE_LENGTH;
4234 			    urqs_ptr->rqs_resid = urqs_ptr->rqs_buflen
4235 				    - SENSE_LENGTH;
4236 			}
4237 			if (!(un->un_rqs_state & ST_RQS_VALID)) {
4238 			    urqs_ptr->rqs_resid = urqs_ptr->rqs_buflen;
4239 			}
4240 			un->un_rqs_state |= ST_RQS_READ;
4241 			un->un_rqs_state &= ~(ST_RQS_OVR);
4242 
4243 #ifdef _MULTI_DATAMODEL
4244 		switch (ddi_model_convert_from(flag & FMODELS)) {
4245 		case DDI_MODEL_ILP32:
4246 			urqs_32_ptr->rqs_flags = urqs_ptr->rqs_flags;
4247 			urqs_32_ptr->rqs_resid = urqs_ptr->rqs_resid;
4248 			if (ddi_copyout(&urqs_32, (void *)arg,
4249 			    sizeof (urqs_32), flag)) {
4250 				rval = EFAULT;
4251 			}
4252 			break;
4253 		case DDI_MODEL_NONE:
4254 			if (ddi_copyout(&urqs, (void *)arg, sizeof (urqs),
4255 			    flag)) {
4256 				rval = EFAULT;
4257 			}
4258 			break;
4259 		}
4260 
4261 		if (un->un_rqs_state & ST_RQS_VALID) {
4262 			if (ddi_copyout(un->un_uscsi_rqs_buf,
4263 			    urqs_ptr->rqs_bufaddr, len, flag)) {
4264 				rval = EFAULT;
4265 		    }
4266 		}
4267 #else /* ! _MULTI_DATAMODEL */
4268 		if (ddi_copyout(&urqs, (void *)arg, sizeof (urqs), flag)) {
4269 			rval = EFAULT;
4270 		}
4271 		if (un->un_rqs_state & ST_RQS_VALID) {
4272 			if (ddi_copyout(un->un_uscsi_rqs_buf,
4273 			    urqs_ptr->rqs_bufaddr, len, flag)) {
4274 				rval = EFAULT;
4275 		    }
4276 		}
4277 #endif /* _MULTI_DATAMODEL */
4278 			break;
4279 		}
4280 
4281 	case USCSICMD:
4282 		{
4283 		cred_t	*cr;
4284 #ifdef _MULTI_DATAMODEL
4285 		/*
4286 		 * For use when a 32 bit app makes a call into a
4287 		 * 64 bit ioctl
4288 		 */
4289 		struct uscsi_cmd32	ucmd_32;
4290 		struct uscsi_cmd32	*ucmd_32_ptr = &ucmd_32;
4291 #endif /* _MULTI_DATAMODEL */
4292 
4293 			/*
4294 			 * Run a generic USCSI command
4295 			 */
4296 			struct uscsi_cmd ucmd;
4297 			struct uscsi_cmd *ucmd_ptr = &ucmd;
4298 			enum uio_seg uioseg;
4299 
4300 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4301 				"st_ioctl: USCSICMD\n");
4302 
4303 			cr = ddi_get_cred();
4304 			if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
4305 				rval = EPERM;
4306 				break;
4307 			}
4308 
4309 #ifdef _MULTI_DATAMODEL
4310 		switch (ddi_model_convert_from(flag & FMODELS)) {
4311 		case DDI_MODEL_ILP32:
4312 		{
4313 			if (ddi_copyin((void *)arg, ucmd_32_ptr,
4314 			    sizeof (struct uscsi_cmd32), flag)) {
4315 				rval = EFAULT;
4316 				break;
4317 			}
4318 			uscsi_cmd32touscsi_cmd(ucmd_32_ptr, ucmd_ptr);
4319 			break;
4320 		}
4321 		case DDI_MODEL_NONE:
4322 			if (ddi_copyin((void *)arg, ucmd_ptr, sizeof (ucmd),
4323 			    flag)) {
4324 				rval = EFAULT;
4325 				break;
4326 			}
4327 		}
4328 
4329 #else /* ! _MULTI_DATAMODEL */
4330 		if (ddi_copyin((void *)arg, ucmd_ptr, sizeof (ucmd), flag)) {
4331 			rval = EFAULT;
4332 			break;
4333 		}
4334 #endif /* _MULTI_DATAMODEL */
4335 
4336 
4337 			/*
4338 			 * If we haven't done/checked reservation on the
4339 			 * tape unit do it now.
4340 			 */
4341 			if (ST_RESERVE_SUPPORTED(un) &&
4342 				!(un->un_rsvd_status & ST_INIT_RESERVE)) {
4343 				if (rval = st_tape_reservation_init(dev))
4344 					goto exit;
4345 			}
4346 
4347 			/*
4348 			 * although st_ioctl_cmd() never makes use of these
4349 			 * now, we are just being safe and consistent
4350 			 */
4351 			ucmd.uscsi_flags &= ~(USCSI_NOINTR | USCSI_NOPARITY |
4352 			    USCSI_OTAG | USCSI_HTAG | USCSI_HEAD);
4353 
4354 
4355 			uioseg = (flag & FKIOCTL) ?
4356 			    UIO_SYSSPACE : UIO_USERSPACE;
4357 
4358 			rval = st_ioctl_cmd(dev, &ucmd, uioseg, uioseg, uioseg);
4359 
4360 
4361 #ifdef _MULTI_DATAMODEL
4362 		switch (ddi_model_convert_from(flag & FMODELS)) {
4363 		case DDI_MODEL_ILP32:
4364 			/*
4365 			 * Convert 64 bit back to 32 bit before doing
4366 			 * copyout. This is what the ILP32 app expects.
4367 			 */
4368 			uscsi_cmdtouscsi_cmd32(ucmd_ptr, ucmd_32_ptr);
4369 
4370 			if (ddi_copyout(&ucmd_32, (void *)arg,
4371 			    sizeof (ucmd_32), flag)) {
4372 				if (rval != 0)
4373 					rval = EFAULT;
4374 				}
4375 			break;
4376 
4377 		case DDI_MODEL_NONE:
4378 			if (ddi_copyout(&ucmd, (void *)arg,
4379 			    sizeof (ucmd), flag)) {
4380 				if (rval != 0)
4381 					rval = EFAULT;
4382 				}
4383 			break;
4384 		}
4385 #else /* ! _MULTI_DATAMODEL */
4386 		if (ddi_copyout(&ucmd, (void *)arg, sizeof (ucmd), flag)) {
4387 			if (rval != 0)
4388 				rval = EFAULT;
4389 		}
4390 #endif /* _MULTI_DATAMODEL */
4391 
4392 			break;
4393 		}
4394 
4395 	case MTIOCTOP:
4396 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4397 			"st_ioctl: MTIOCTOP\n");
4398 		rval = st_mtioctop(un, arg, flag);
4399 		break;
4400 
4401 	case MTIOCREADIGNOREILI:
4402 		{
4403 			int set_ili;
4404 
4405 			if (ddi_copyin((void *)arg, &set_ili,
4406 			    sizeof (set_ili), flag)) {
4407 				rval = EFAULT;
4408 				break;
4409 			}
4410 
4411 			if (un->un_bsize) {
4412 				rval = ENOTTY;
4413 				break;
4414 			}
4415 
4416 			switch (set_ili) {
4417 			case 0:
4418 				un->un_dp->options &= ~ST_READ_IGNORE_ILI;
4419 				break;
4420 
4421 			case 1:
4422 				un->un_dp->options |= ST_READ_IGNORE_ILI;
4423 				break;
4424 
4425 			default:
4426 				rval = EINVAL;
4427 				break;
4428 			}
4429 			break;
4430 		}
4431 
4432 	case MTIOCREADIGNOREEOFS:
4433 		{
4434 			int ignore_eof;
4435 
4436 			if (ddi_copyin((void *)arg, &ignore_eof,
4437 			    sizeof (ignore_eof), flag)) {
4438 				rval = EFAULT;
4439 				break;
4440 			}
4441 
4442 			if (!(un->un_dp->options & ST_REEL)) {
4443 				rval = ENOTTY;
4444 				break;
4445 			}
4446 
4447 			switch (ignore_eof) {
4448 			case 0:
4449 				un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
4450 				break;
4451 
4452 			case 1:
4453 				un->un_dp->options |= ST_READ_IGNORE_EOFS;
4454 				break;
4455 
4456 			default:
4457 				rval = EINVAL;
4458 				break;
4459 			}
4460 			break;
4461 		}
4462 
4463 	case MTIOCSHORTFMK:
4464 		{
4465 			int short_fmk;
4466 
4467 			if (ddi_copyin((void *)arg, &short_fmk,
4468 			    sizeof (short_fmk), flag)) {
4469 				rval = EFAULT;
4470 				break;
4471 			}
4472 
4473 			switch (un->un_dp->type) {
4474 			case ST_TYPE_EXB8500:
4475 			case ST_TYPE_EXABYTE:
4476 				if (!short_fmk) {
4477 					un->un_dp->options &=
4478 						~ST_SHORT_FILEMARKS;
4479 				} else if (short_fmk == 1) {
4480 					un->un_dp->options |=
4481 						ST_SHORT_FILEMARKS;
4482 				} else {
4483 					rval = EINVAL;
4484 				}
4485 				break;
4486 
4487 			default:
4488 				rval = ENOTTY;
4489 				break;
4490 			}
4491 			break;
4492 		}
4493 
4494 	default:
4495 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4496 			"st_ioctl: unknown ioctl\n");
4497 		rval = ENOTTY;
4498 	}
4499 
4500 exit:
4501 	if (!IS_PE_FLAG_SET(un))
4502 		un->un_errno = rval;
4503 
4504 	mutex_exit(ST_MUTEX);
4505 
4506 	return (rval);
4507 }
4508 
4509 
4510 /*
4511  * do some MTIOCTOP tape operations
4512  */
4513 static int
4514 st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag)
4515 {
4516 	struct mtop *mtop, local;
4517 	int savefile, tmp, rval = 0;
4518 	dev_t dev = un->un_dev;
4519 #ifdef _MULTI_DATAMODEL
4520 	/*
4521 	 * For use when a 32 bit app makes a call into a
4522 	 * 64 bit ioctl
4523 	 */
4524 	struct mtop32	mtop_32_for_64;
4525 #endif /* _MULTI_DATAMODEL */
4526 
4527 
4528 	ASSERT(mutex_owned(ST_MUTEX));
4529 
4530 	mtop = &local;
4531 #ifdef _MULTI_DATAMODEL
4532 		switch (ddi_model_convert_from(flag & FMODELS)) {
4533 		case DDI_MODEL_ILP32:
4534 		{
4535 			if (ddi_copyin((void *)arg, &mtop_32_for_64,
4536 			    sizeof (struct mtop32), flag)) {
4537 				return (EFAULT);
4538 			}
4539 			mtop->mt_op = mtop_32_for_64.mt_op;
4540 			mtop->mt_count =  (daddr_t)mtop_32_for_64.mt_count;
4541 			break;
4542 		}
4543 		case DDI_MODEL_NONE:
4544 			if (ddi_copyin((void *)arg, mtop,
4545 			    sizeof (struct mtop), flag)) {
4546 				return (EFAULT);
4547 			}
4548 			break;
4549 		}
4550 
4551 #else /* ! _MULTI_DATAMODEL */
4552 		if (ddi_copyin((void *)arg, mtop, sizeof (struct mtop), flag)) {
4553 			return (EFAULT);
4554 		}
4555 #endif /* _MULTI_DATAMODEL */
4556 
4557 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4558 	    "st_mtioctop(): mt_op=%x\n", mtop->mt_op);
4559 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4560 	    "fileno=%x, blkno=%lx, un_eof=%x\n", un->un_fileno, un->un_blkno,
4561 	    un->un_eof);
4562 
4563 	rval = 0;
4564 	un->un_status = 0;
4565 
4566 	/*
4567 	 * If we haven't done/checked reservation on the tape unit
4568 	 * do it now.
4569 	 */
4570 	if (ST_RESERVE_SUPPORTED(un) &&
4571 		!(un->un_rsvd_status & ST_INIT_RESERVE)) {
4572 		if (rval = st_tape_reservation_init(dev))
4573 			return (rval);
4574 	}
4575 	/*
4576 	 * if we are going to mess with a tape, we have to make sure we have
4577 	 * one and are not offline (i.e. no tape is initialized).  We let
4578 	 * commands pass here that don't actually touch the tape, except for
4579 	 * loading and initialization (rewinding).
4580 	 */
4581 	if (un->un_state == ST_STATE_OFFLINE) {
4582 		switch (mtop->mt_op) {
4583 		case MTLOAD:
4584 		case MTNOP:
4585 			/*
4586 			 * We don't want strategy calling st_tape_init here,
4587 			 * so, change state
4588 			 */
4589 			un->un_state = ST_STATE_INITIALIZING;
4590 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4591 			    "st_mtioctop : OFFLINE state = %d\n",
4592 			    un->un_state);
4593 			break;
4594 		default:
4595 			/*
4596 			 * reinitialize by normal means
4597 			 */
4598 			if (st_tape_init(dev)) {
4599 				un->un_state = ST_STATE_INITIALIZING;
4600 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4601 				    "st_mtioctop : OFFLINE init failure ");
4602 				un->un_state = ST_STATE_OFFLINE;
4603 				un->un_fileno = -1;
4604 				return (EIO);
4605 			}
4606 			un->un_state = ST_STATE_OPEN_PENDING_IO;
4607 			break;
4608 		}
4609 	}
4610 
4611 	/*
4612 	 * If the file position is invalid, allow only those
4613 	 * commands that properly position the tape and fail
4614 	 * the rest with EIO
4615 	 */
4616 	if (un->un_fileno < 0) {
4617 		switch (mtop->mt_op) {
4618 		case MTWEOF:
4619 		case MTRETEN:
4620 		case MTERASE:
4621 		case MTEOM:
4622 		case MTFSF:
4623 		case MTFSR:
4624 		case MTBSF:
4625 		case MTNBSF:
4626 		case MTBSR:
4627 		case MTSRSZ:
4628 		case MTGRSZ:
4629 			return (EIO);
4630 			/* NOTREACHED */
4631 		case MTREW:
4632 		case MTLOAD:
4633 		case MTOFFL:
4634 		case MTNOP:
4635 			break;
4636 
4637 		default:
4638 			return (ENOTTY);
4639 			/* NOTREACHED */
4640 		}
4641 	}
4642 
4643 	switch (mtop->mt_op) {
4644 	case MTERASE:
4645 		/*
4646 		 * MTERASE rewinds the tape, erase it completely, and returns
4647 		 * to the beginning of the tape
4648 		 */
4649 		if (un->un_dp->options & ST_REEL)
4650 			un->un_fmneeded = 2;
4651 
4652 		if (un->un_mspl->wp || un->un_read_only) {
4653 			un->un_status = KEY_WRITE_PROTECT;
4654 			un->un_err_resid = mtop->mt_count;
4655 			un->un_err_fileno = un->un_fileno;
4656 			un->un_err_blkno = un->un_blkno;
4657 			return (EACCES);
4658 		}
4659 		if (st_check_density_or_wfm(dev, 1, B_WRITE, NO_STEPBACK) ||
4660 		    st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD) ||
4661 		    st_cmd(dev, SCMD_ERASE, 0, SYNC_CMD)) {
4662 			un->un_fileno = -1;
4663 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4664 			    "st_mtioctop : EIO space or erase or check den)\n");
4665 			rval = EIO;
4666 		} else {
4667 			/* QIC and helical scan rewind after erase */
4668 			if (un->un_dp->options & ST_REEL) {
4669 				(void) st_cmd(dev, SCMD_REWIND, 0, ASYNC_CMD);
4670 			}
4671 		}
4672 		break;
4673 
4674 	case MTWEOF:
4675 		/*
4676 		 * write an end-of-file record
4677 		 */
4678 		if (un->un_mspl->wp || un->un_read_only) {
4679 			un->un_status = KEY_WRITE_PROTECT;
4680 			un->un_err_resid = mtop->mt_count;
4681 			un->un_err_fileno = un->un_fileno;
4682 			un->un_err_blkno = un->un_blkno;
4683 			return (EACCES);
4684 		}
4685 
4686 		/*
4687 		 * zero count means just flush buffers
4688 		 * negative count is not permitted
4689 		 */
4690 		if (mtop->mt_count < 0)
4691 			return (EINVAL);
4692 
4693 		if (!un->un_read_only) {
4694 			un->un_test_append = 1;
4695 		}
4696 
4697 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4698 			if (st_determine_density(dev, B_WRITE)) {
4699 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4700 				    "st_mtioctop : EIO : MTWEOF can't determine"
4701 				    "density");
4702 				return (EIO);
4703 			}
4704 		}
4705 
4706 		if (st_write_fm(dev, (int)mtop->mt_count)) {
4707 			/*
4708 			 * Failure due to something other than illegal
4709 			 * request results in loss of state (st_intr).
4710 			 */
4711 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4712 			    "st_mtioctop : EIO : MTWEOF can't write file mark");
4713 			rval = EIO;
4714 		}
4715 		break;
4716 
4717 	case MTRETEN:
4718 		/*
4719 		 * retension the tape
4720 		 */
4721 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK) ||
4722 		    st_cmd(dev, SCMD_LOAD, 3, SYNC_CMD)) {
4723 			un->un_fileno = -1;
4724 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4725 			    "st_mtioctop : EIO : MTRETEN ");
4726 			rval = EIO;
4727 		}
4728 		break;
4729 
4730 	case MTREW:
4731 		/*
4732 		 * rewind  the tape
4733 		 */
4734 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
4735 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4736 			    "st_mtioctop : EIO:MTREW check density/wfm failed");
4737 			return (EIO);
4738 		}
4739 		if (st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD)) {
4740 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4741 			    "st_mtioctop : EIO : MTREW ");
4742 			rval = EIO;
4743 		}
4744 		break;
4745 
4746 	case MTOFFL:
4747 		/*
4748 		 * rewinds, and, if appropriate, takes the device offline by
4749 		 * unloading the tape
4750 		 */
4751 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
4752 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4753 			    "st_mtioctop :EIO:MTOFFL check density/wfm failed");
4754 			return (EIO);
4755 		}
4756 		(void) st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD);
4757 		if (st_cmd(dev, SCMD_LOAD, 0, SYNC_CMD)) {
4758 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4759 			    "st_mtioctop : EIO : MTOFFL");
4760 			return (EIO);
4761 		}
4762 		un->un_eof = ST_NO_EOF;
4763 		un->un_laststate = un->un_state;
4764 		un->un_state = ST_STATE_OFFLINE;
4765 		un->un_mediastate = MTIO_EJECTED;
4766 		break;
4767 
4768 	case MTLOAD:
4769 		/*
4770 		 * This is to load a tape into the drive
4771 		 * Note that if the tape is not loaded, the device will have
4772 		 * to be opened via O_NDELAY or O_NONBLOCK.
4773 		 */
4774 		/*
4775 		 * Let's try and clean things up, if we are not
4776 		 * initializing, and then send in the load command, no
4777 		 * matter what.
4778 		 *
4779 		 * we try the load twice because some drives fail the first
4780 		 * load after a media change by the user.
4781 		 */
4782 
4783 		if (un->un_state > ST_STATE_INITIALIZING)
4784 			(void) st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK);
4785 
4786 		if (st_cmd(dev, SCMD_LOAD, 1, SYNC_CMD) &&
4787 		    st_cmd(dev, SCMD_LOAD, 1, SYNC_CMD)) {
4788 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4789 			    "st_mtioctop : EIO : MTLOAD\n");
4790 			rval = EIO;
4791 
4792 			/*
4793 			 * If load tape fails, who knows what happened...
4794 			 */
4795 			un->un_fileno = -1;
4796 			rval = EIO;
4797 			break;
4798 		}
4799 
4800 		/*
4801 		 * reset all counters appropriately using rewind, as if LOAD
4802 		 * succeeds, we are at BOT
4803 		 */
4804 		un->un_state = ST_STATE_INITIALIZING;
4805 
4806 		if (st_tape_init(dev)) {
4807 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4808 			    "st_mtioctop : EIO : MTLOAD calls st_tape_init\n");
4809 			rval = EIO;
4810 			un->un_state = ST_STATE_OFFLINE;
4811 		}
4812 
4813 		break;
4814 
4815 	case MTNOP:
4816 		un->un_status = 0;		/* Reset status */
4817 		un->un_err_resid = 0;
4818 		break;
4819 
4820 	case MTEOM:
4821 		/*
4822 		 * positions the tape at a location just after the last file
4823 		 * written on the tape. For cartridge and 8 mm, this after
4824 		 * the last file mark; for reel, this is inbetween the two
4825 		 * last 2 file marks
4826 		 */
4827 		if ((un->un_eof >= ST_EOT) ||
4828 		    (un->un_lastop == ST_OP_WRITE) ||
4829 		    (un->un_lastop == ST_OP_WEOF)) {
4830 			/*
4831 			 * If the command wants to move to logical end
4832 			 * of media, and we're already there, we're done.
4833 			 * If we were at logical eot, we reset the state
4834 			 * to be *not* at logical eot.
4835 			 *
4836 			 * If we're at physical or logical eot, we prohibit
4837 			 * forward space operations (unconditionally).
4838 			 *
4839 			 * Also if the last operation was a write of any
4840 			 * kind the tape is at EOD.
4841 			 */
4842 			return (0);
4843 		}
4844 		/*
4845 		 * physical tape position may not be what we've been
4846 		 * telling the user; adjust the request accordingly
4847 		 */
4848 		if (IN_EOF(un)) {
4849 			un->un_fileno++;
4850 			un->un_blkno = 0;
4851 		}
4852 
4853 		if (st_check_density_or_wfm(dev, 1, B_READ, NO_STEPBACK)) {
4854 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4855 			    "st_mtioctop : EIO:MTEOM check density/wfm failed");
4856 			return (EIO);
4857 		}
4858 
4859 		/*
4860 		 * st_find_eom() returns the last fileno we knew about;
4861 		 */
4862 		savefile = st_find_eom(dev);
4863 
4864 		if ((un->un_status != KEY_BLANK_CHECK) &&
4865 		    (un->un_status != SUN_KEY_EOT)) {
4866 			un->un_fileno = -1;
4867 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4868 			    "st_mtioctop : EIO : MTEOM status check failed");
4869 			rval = EIO;
4870 		} else {
4871 			/*
4872 			 * For 1/2" reel tapes assume logical EOT marked
4873 			 * by two file marks or we don't care that we may
4874 			 * be extending the last file on the tape.
4875 			 */
4876 			if (un->un_dp->options & ST_REEL) {
4877 				if (st_cmd(dev, SCMD_SPACE, Fmk((-1)),
4878 				    SYNC_CMD)) {
4879 					un->un_fileno = -1;
4880 					ST_DEBUG2(ST_DEVINFO, st_label,
4881 					    SCSI_DEBUG,
4882 					    "st_mtioctop : EIO : MTEOM space "
4883 					    "cmd failed");
4884 					rval = EIO;
4885 					break;
4886 				}
4887 				/*
4888 				 * Fix up the block number.
4889 				 */
4890 				un->un_blkno = 0;
4891 				un->un_err_blkno = 0;
4892 			}
4893 			un->un_err_resid = 0;
4894 			un->un_fileno = savefile;
4895 			un->un_eof = ST_EOT;
4896 		}
4897 		un->un_status = 0;
4898 		break;
4899 
4900 	case MTFSF:
4901 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4902 		    "fsf: count=%lx, eof=%x\n", mtop->mt_count,
4903 			un->un_eof);
4904 		/*
4905 		 * forward space over filemark
4906 		 *
4907 		 * For ASF we allow a count of 0 on fsf which means
4908 		 * we just want to go to beginning of current file.
4909 		 * Equivalent to "nbsf(0)" or "bsf(1) + fsf".
4910 		 * Allow stepping over double fmk with reel
4911 		 */
4912 		if ((un->un_eof >= ST_EOT) && (mtop->mt_count > 0) &&
4913 		    ((un->un_dp->options & ST_REEL) == 0)) {
4914 			/* we're at EOM */
4915 			un->un_err_resid = mtop->mt_count;
4916 			un->un_status = KEY_BLANK_CHECK;
4917 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4918 			    "st_mtioctop : EIO : MTFSF at EOM");
4919 			return (EIO);
4920 		}
4921 
4922 		/*
4923 		 * physical tape position may not be what we've been
4924 		 * telling the user; adjust the request accordingly
4925 		 */
4926 		if (IN_EOF(un)) {
4927 			un->un_fileno++;
4928 			un->un_blkno = 0;
4929 			/*
4930 			 * For positive direction case, we're now covered.
4931 			 * For zero or negative direction, we're covered
4932 			 * (almost)
4933 			 */
4934 			mtop->mt_count--;
4935 		}
4936 
4937 		if (st_check_density_or_wfm(dev, 1, B_READ, STEPBACK)) {
4938 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4939 			    "st_mtioctop : EIO : MTFSF density/wfm failed");
4940 			return (EIO);
4941 		}
4942 
4943 
4944 		/*
4945 		 * Forward space file marks.
4946 		 * We leave ourselves at block zero
4947 		 * of the target file number.
4948 		 */
4949 		if (mtop->mt_count < 0) {
4950 			mtop->mt_count = -mtop->mt_count;
4951 			mtop->mt_op = MTNBSF;
4952 			goto bspace;
4953 		}
4954 fspace:
4955 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4956 		    "fspace: count=%lx, eof=%x\n", mtop->mt_count,
4957 			un->un_eof);
4958 		if ((tmp = mtop->mt_count) == 0) {
4959 			if (un->un_blkno == 0) {
4960 				un->un_err_resid = 0;
4961 				un->un_err_fileno = un->un_fileno;
4962 				un->un_err_blkno = un->un_blkno;
4963 				break;
4964 			} else if (un->un_fileno == 0) {
4965 				rval = st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD);
4966 			} else if (un->un_dp->options & ST_BSF) {
4967 				rval = (st_cmd(dev, SCMD_SPACE, Fmk((-1)),
4968 				    SYNC_CMD) ||
4969 				    st_cmd(dev, SCMD_SPACE, Fmk(1), SYNC_CMD));
4970 			} else {
4971 				tmp = un->un_fileno;
4972 				rval = (st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD) ||
4973 				    st_cmd(dev, SCMD_SPACE, (int)Fmk(tmp),
4974 				    SYNC_CMD));
4975 			}
4976 			if (rval != 0) {
4977 				un->un_fileno = -1;
4978 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4979 				    "st_mtioctop : EIO : fspace fileno = -1");
4980 
4981 				rval = EIO;
4982 			}
4983 		} else {
4984 			rval = st_space_fmks(dev, tmp);
4985 		}
4986 
4987 		if (mtop->mt_op == MTBSF && rval != EIO) {
4988 			/*
4989 			 * we came here with a count < 0; we now need
4990 			 * to skip back to end up before the filemark
4991 			 */
4992 			mtop->mt_count = 1;
4993 			goto bspace;
4994 		}
4995 		break;
4996 
4997 
4998 	case MTFSR:
4999 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5000 		    "fsr: count=%lx, eof=%x\n", mtop->mt_count,
5001 			un->un_eof);
5002 		/*
5003 		 * forward space to inter-record gap
5004 		 *
5005 		 */
5006 		if ((un->un_eof >= ST_EOT) && (mtop->mt_count > 0)) {
5007 			/* we're at EOM */
5008 			un->un_err_resid = mtop->mt_count;
5009 			un->un_status = KEY_BLANK_CHECK;
5010 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5011 			    "st_mtioctop : EIO : MTFSR un_eof > ST_EOT");
5012 			return (EIO);
5013 		}
5014 
5015 		if (mtop->mt_count == 0) {
5016 			un->un_err_fileno = un->un_fileno;
5017 			un->un_err_blkno = un->un_blkno;
5018 			un->un_err_resid = 0;
5019 			if (IN_EOF(un) && SVR4_BEHAVIOR) {
5020 				un->un_status = SUN_KEY_EOF;
5021 			}
5022 			return (0);
5023 		}
5024 
5025 		/*
5026 		 * physical tape position may not be what we've been
5027 		 * telling the user; adjust the position accordingly
5028 		 */
5029 		if (IN_EOF(un)) {
5030 			daddr_t blkno = un->un_blkno;
5031 			int fileno = un->un_fileno;
5032 			uchar_t lastop = un->un_lastop;
5033 			if (st_cmd(dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)
5034 			    == -1) {
5035 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5036 				    "st_mtioctop : EIO :MTFSR count && IN_EOF");
5037 				return (EIO);
5038 			}
5039 
5040 			un->un_blkno = blkno;
5041 			un->un_fileno = fileno;
5042 			un->un_lastop = lastop;
5043 		}
5044 
5045 		if (st_check_density_or_wfm(dev, 1, B_READ, STEPBACK)) {
5046 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5047 			    "st_mtioctop : EIO : MTFSR st_check_den");
5048 			return (EIO);
5049 		}
5050 
5051 space_records:
5052 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5053 		    "space_records: count=%lx, eof=%x\n", mtop->mt_count,
5054 			un->un_eof);
5055 		tmp = un->un_blkno + mtop->mt_count;
5056 		if (tmp == un->un_blkno) {
5057 			un->un_err_resid = 0;
5058 			un->un_err_fileno = un->un_fileno;
5059 			un->un_err_blkno = un->un_blkno;
5060 			break;
5061 		} else if (un->un_blkno < tmp ||
5062 		    (un->un_dp->options & ST_BSR)) {
5063 			/*
5064 			 * If we're spacing forward, or the device can
5065 			 * backspace records, we can just use the SPACE
5066 			 * command.
5067 			 */
5068 			tmp = tmp - un->un_blkno;
5069 			if (st_cmd(dev, SCMD_SPACE, Blk(tmp), SYNC_CMD)) {
5070 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5071 				    "st_mtioctop :EIO:space_records can't spc");
5072 				rval = EIO;
5073 			} else if (un->un_eof >= ST_EOF_PENDING) {
5074 				/*
5075 				 * check if we hit BOT/EOT
5076 				 */
5077 				if (tmp < 0 && un->un_eof == ST_EOM) {
5078 					un->un_status = SUN_KEY_BOT;
5079 					un->un_eof = ST_NO_EOF;
5080 				} else if (tmp < 0 && un->un_eof ==
5081 				    ST_EOF_PENDING) {
5082 					int residue = un->un_err_resid;
5083 					/*
5084 					 * we skipped over a filemark
5085 					 * and need to go forward again
5086 					 */
5087 					if (st_cmd(dev, SCMD_SPACE, Fmk(1),
5088 					    SYNC_CMD)) {
5089 						ST_DEBUG2(ST_DEVINFO,
5090 						    st_label, SCSI_DEBUG,
5091 						    "st_mtioctop : EIO : "
5092 						    "space_records can't "
5093 						    "space #2");
5094 						rval = EIO;
5095 					}
5096 					un->un_err_resid = residue;
5097 				}
5098 				if (rval == 0) {
5099 					ST_DEBUG2(ST_DEVINFO, st_label,
5100 					    SCSI_DEBUG,
5101 					    "st_mtioctop : EIO : space_rec rval"
5102 					    " == 0");
5103 					rval = EIO;
5104 				}
5105 			}
5106 		} else {
5107 			/*
5108 			 * else we rewind, space forward across filemarks to
5109 			 * the desired file, and then space records to the
5110 			 * desired block.
5111 			 */
5112 
5113 			int t = un->un_fileno;	/* save current file */
5114 
5115 			if (tmp < 0) {
5116 				/*
5117 				 * Wups - we're backing up over a filemark
5118 				 */
5119 				if (un->un_blkno != 0 &&
5120 				    (st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD) ||
5121 				    st_cmd(dev, SCMD_SPACE, Fmk(t), SYNC_CMD)))
5122 					un->un_fileno = -1;
5123 				un->un_err_resid = -tmp;
5124 				if (un->un_fileno == 0 && un->un_blkno == 0) {
5125 					un->un_status = SUN_KEY_BOT;
5126 					un->un_eof = ST_NO_EOF;
5127 				} else if (un->un_fileno > 0) {
5128 					un->un_status = SUN_KEY_EOF;
5129 					un->un_eof = ST_NO_EOF;
5130 				}
5131 				un->un_err_fileno = un->un_fileno;
5132 				un->un_err_blkno = un->un_blkno;
5133 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5134 				    "st_mtioctop :EIO:space_records : tmp < 0");
5135 				rval = EIO;
5136 			} else if (st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD) ||
5137 				    st_cmd(dev, SCMD_SPACE, Fmk(t), SYNC_CMD) ||
5138 				    st_cmd(dev, SCMD_SPACE, Blk(tmp),
5139 					SYNC_CMD)) {
5140 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5141 				    "st_mtioctop : EIO :space_records : rewind "
5142 				    "and space failed");
5143 				un->un_fileno = -1;
5144 				rval = EIO;
5145 			}
5146 		}
5147 		break;
5148 
5149 
5150 	case MTBSF:
5151 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5152 		    "bsf: count=%lx, eof=%x\n", mtop->mt_count,
5153 			un->un_eof);
5154 		/*
5155 		 * backward space of file filemark (1/2" and 8mm)
5156 		 * tape position will end on the beginning of tape side
5157 		 * of the desired file mark
5158 		 */
5159 		if ((un->un_dp->options & ST_BSF) == 0) {
5160 			return (ENOTTY);
5161 		}
5162 
5163 		/*
5164 		 * If a negative count (which implies a forward space op)
5165 		 * is specified, and we're at logical or physical eot,
5166 		 * bounce the request.
5167 		 */
5168 
5169 		if (un->un_eof >= ST_EOT && mtop->mt_count < 0) {
5170 			un->un_err_resid = mtop->mt_count;
5171 			un->un_status = SUN_KEY_EOT;
5172 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5173 			    "st_ioctl : EIO : MTBSF : un_eof > ST_EOF");
5174 			return (EIO);
5175 		}
5176 		/*
5177 		 * physical tape position may not be what we've been
5178 		 * telling the user; adjust the request accordingly
5179 		 */
5180 		if (IN_EOF(un)) {
5181 			un->un_fileno++;
5182 			un->un_blkno = 0;
5183 			mtop->mt_count++;
5184 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5185 			"bsf in eof: count=%ld, op=%x\n",
5186 			mtop->mt_count, mtop->mt_op);
5187 
5188 		}
5189 
5190 		if (st_check_density_or_wfm(dev, 1, 0, STEPBACK)) {
5191 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5192 			    "st_ioctl : EIO : MTBSF : check den wfm");
5193 			return (EIO);
5194 		}
5195 
5196 		if (mtop->mt_count <= 0) {
5197 			/*
5198 			 * for a negative count, we need to step forward
5199 			 * first and then step back again
5200 			 */
5201 			mtop->mt_count = -mtop->mt_count+1;
5202 			goto fspace;
5203 		}
5204 
5205 bspace:
5206 	{
5207 		int skip_cnt, end_at_eof;
5208 
5209 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5210 		    "bspace: count=%lx, eof=%x\n", mtop->mt_count,
5211 			un->un_eof);
5212 		/*
5213 		 * Backspace files (MTNBSF):
5214 		 *
5215 		 *	For tapes that can backspace, backspace
5216 		 *	count+1 filemarks and then run forward over
5217 		 *	a filemark
5218 		 *
5219 		 *	For tapes that can't backspace,
5220 		 *		calculate desired filenumber
5221 		 *		(un->un_fileno - count), rewind,
5222 		 *		and then space forward this amount
5223 		 *
5224 		 * Backspace filemarks (MTBSF)
5225 		 *
5226 		 *	For tapes that can backspace, backspace count
5227 		 *	filemarks
5228 		 *
5229 		 *	For tapes that can't backspace, calculate
5230 		 *	desired filenumber (un->un_fileno - count),
5231 		 *	add 1, rewind, space forward this amount,
5232 		 *	and mark state as ST_EOF_PENDING appropriately.
5233 		 */
5234 
5235 		if (mtop->mt_op == MTBSF) {
5236 			end_at_eof = 1;
5237 		} else {
5238 			end_at_eof = 0;
5239 		}
5240 
5241 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5242 		    "bspace: mt_op=%x, count=%lx, fileno=%x, blkno=%lx\n",
5243 		    mtop->mt_op, mtop->mt_count, un->un_fileno, un->un_blkno);
5244 
5245 		/*
5246 		 * Handle the simple case of BOT
5247 		 * playing a role in these cmds.
5248 		 * We do this by calculating the
5249 		 * ending file number. If the ending
5250 		 * file is < BOT, rewind and set an
5251 		 * error and mark resid appropriately.
5252 		 * If we're backspacing a file (not a
5253 		 * filemark) and the target file is
5254 		 * the first file on the tape, just
5255 		 * rewind.
5256 		 */
5257 
5258 		tmp = un->un_fileno - mtop->mt_count;
5259 		if ((end_at_eof && tmp < 0) || (end_at_eof == 0 && tmp <= 0)) {
5260 			if (st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD)) {
5261 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5262 				    "st_ioctl : EIO : bspace : end_at_eof && "
5263 				    "tmp < 0");
5264 				rval = EIO;
5265 			}
5266 			if (tmp < 0) {
5267 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5268 				    "st_ioctl : EIO : bspace : tmp < 0");
5269 				rval = EIO;
5270 				un->un_err_resid = -tmp;
5271 				un->un_status = SUN_KEY_BOT;
5272 			}
5273 			break;
5274 		}
5275 
5276 		if (un->un_dp->options & ST_BSF) {
5277 			skip_cnt = 1 - end_at_eof;
5278 			/*
5279 			 * If we are going to end up at the beginning
5280 			 * of the file, we have to space one extra file
5281 			 * first, and then space forward later.
5282 			 */
5283 			tmp = -(mtop->mt_count + skip_cnt);
5284 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5285 			    "skip_cnt=%x, tmp=%x\n", skip_cnt, tmp);
5286 			if (st_cmd(dev, SCMD_SPACE, Fmk(tmp), SYNC_CMD)) {
5287 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5288 				    "st_ioctl : EIO : bspace : can't space "
5289 				    "tmp");
5290 				rval = EIO;
5291 			}
5292 		} else {
5293 			if (st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD)) {
5294 				rval = EIO;
5295 			} else {
5296 				skip_cnt = tmp + end_at_eof;
5297 			}
5298 		}
5299 
5300 		/*
5301 		 * If we have to space forward, do so...
5302 		 */
5303 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5304 		    "space forward skip_cnt=%x, rval=%x\n", skip_cnt, rval);
5305 		if (rval == 0 && skip_cnt) {
5306 			if (st_cmd(dev, SCMD_SPACE, Fmk(skip_cnt), SYNC_CMD)) {
5307 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5308 				    "st_ioctl : EIO : bspace : can't space "
5309 				    "skip_cnt");
5310 				rval = EIO;
5311 			} else if (end_at_eof) {
5312 				/*
5313 				 * If we had to space forward, and we're
5314 				 * not a tape that can backspace, mark state
5315 				 * as if we'd just seen a filemark during a
5316 				 * a read.
5317 				 */
5318 				if ((un->un_dp->options & ST_BSF) == 0) {
5319 					un->un_eof = ST_EOF_PENDING;
5320 					un->un_fileno -= 1;
5321 					un->un_blkno = INF;
5322 				}
5323 			}
5324 		}
5325 
5326 		if (rval != 0) {
5327 			un->un_fileno = -1;
5328 		}
5329 		break;
5330 	}
5331 
5332 	case MTNBSF:
5333 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5334 		    "nbsf: count=%lx, eof=%x\n", mtop->mt_count,
5335 			un->un_eof);
5336 		/*
5337 		 * backward space file to beginning of file
5338 		 *
5339 		 * If a negative count (which implies a forward space op)
5340 		 * is specified, and we're at logical or physical eot,
5341 		 * bounce the request.
5342 		 */
5343 
5344 		if (un->un_eof >= ST_EOT && mtop->mt_count < 0) {
5345 			un->un_err_resid = mtop->mt_count;
5346 			un->un_status = SUN_KEY_EOT;
5347 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5348 			    "st_ioctl : EIO : > EOT and count < 0");
5349 			return (EIO);
5350 		}
5351 		/*
5352 		 * physical tape position may not be what we've been
5353 		 * telling the user; adjust the request accordingly
5354 		 */
5355 		if (IN_EOF(un)) {
5356 			un->un_fileno++;
5357 			un->un_blkno = 0;
5358 			mtop->mt_count++;
5359 		}
5360 
5361 		if (st_check_density_or_wfm(dev, 1, 0, STEPBACK)) {
5362 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5363 			    "st_ioctl : EIO : MTNBSF check den and wfm");
5364 			return (EIO);
5365 		}
5366 
5367 mtnbsf:
5368 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5369 		    "mtnbsf: count=%lx, eof=%x\n", mtop->mt_count,
5370 			un->un_eof);
5371 		if (mtop->mt_count <= 0) {
5372 			mtop->mt_op = MTFSF;
5373 			mtop->mt_count = -mtop->mt_count;
5374 			goto fspace;
5375 		}
5376 		goto bspace;
5377 
5378 	case MTBSR:
5379 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5380 		    "bsr: count=%lx, eof=%x\n", mtop->mt_count,
5381 			un->un_eof);
5382 		/*
5383 		 * backward space into inter-record gap
5384 		 *
5385 		 * If a negative count (which implies a forward space op)
5386 		 * is specified, and we're at logical or physical eot,
5387 		 * bounce the request.
5388 		 */
5389 		if (un->un_eof >= ST_EOT && mtop->mt_count < 0) {
5390 			un->un_err_resid = mtop->mt_count;
5391 			un->un_status = SUN_KEY_EOT;
5392 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5393 			    "st_ioctl : EIO : MTBSR > EOT");
5394 			return (EIO);
5395 		}
5396 
5397 		if (mtop->mt_count == 0) {
5398 			un->un_err_fileno = un->un_fileno;
5399 			un->un_err_blkno = un->un_blkno;
5400 			un->un_err_resid = 0;
5401 			if (IN_EOF(un) && SVR4_BEHAVIOR) {
5402 				un->un_status = SUN_KEY_EOF;
5403 			}
5404 			return (0);
5405 		}
5406 
5407 		/*
5408 		 * physical tape position may not be what we've been
5409 		 * telling the user; adjust the position accordingly.
5410 		 * bsr can not skip filemarks and continue to skip records
5411 		 * therefore if we are logically before the filemark but
5412 		 * physically at the EOT side of the filemark, we need to step
5413 		 * back; this allows fsr N where N > number of blocks in file
5414 		 * followed by bsr 1 to position at the beginning of last block
5415 		 */
5416 		if (IN_EOF(un)) {
5417 			int blkno = un->un_blkno;
5418 			int fileno = un->un_fileno;
5419 			uchar_t lastop = un->un_lastop;
5420 			if (st_cmd(dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)
5421 			    == -1) {
5422 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5423 				    "st_write_fm : EIO : MTBSR can't space");
5424 				return (EIO);
5425 			}
5426 
5427 			un->un_blkno = blkno;
5428 			un->un_fileno = fileno;
5429 			un->un_lastop = lastop;
5430 		}
5431 
5432 		un->un_eof = ST_NO_EOF;
5433 
5434 		if (st_check_density_or_wfm(dev, 1, 0, STEPBACK)) {
5435 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5436 			    "st_ioctl : EIO : MTBSR : can't set density or "
5437 			    "wfm");
5438 			return (EIO);
5439 		}
5440 
5441 		mtop->mt_count = -mtop->mt_count;
5442 		goto space_records;
5443 
5444 	case MTSRSZ:
5445 
5446 		/*
5447 		 * Set record-size to that sent by user
5448 		 * Check to see if there is reason that the requested
5449 		 * block size should not be set.
5450 		 */
5451 
5452 		/* If requesting variable block size is it ok? */
5453 		if ((mtop->mt_count == 0) &&
5454 		    ((un->un_dp->options & ST_VARIABLE) == 0)) {
5455 			return (ENOTTY);
5456 		}
5457 
5458 		/*
5459 		 * If requested block size is not variable "0",
5460 		 * is it less then minimum.
5461 		 */
5462 		if ((mtop->mt_count != 0) &&
5463 		    (mtop->mt_count < un->un_minbsize)) {
5464 			return (EINVAL);
5465 		}
5466 
5467 		/* Is the requested block size more then maximum */
5468 		if ((mtop->mt_count > min(un->un_maxbsize, un->un_maxdma)) &&
5469 		    (un->un_maxbsize != 0)) {
5470 			return (EINVAL);
5471 		}
5472 
5473 		/* Is requested block size a modulus the device likes */
5474 		if ((mtop->mt_count % un->un_data_mod) != 0) {
5475 			return (EINVAL);
5476 		}
5477 
5478 		if (st_change_block_size(dev, (uint32_t)mtop->mt_count) != 0) {
5479 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5480 			    "st_ioctl : MTSRSZ : EIO : cant set block size");
5481 			return (EIO);
5482 		}
5483 
5484 		return (0);
5485 
5486 	case MTGRSZ:
5487 	{
5488 #ifdef _MULTI_DATAMODEL
5489 	/*
5490 	 * For use when a 32 bit app makes a call into a
5491 	 * 64 bit ioctl
5492 	 */
5493 	struct mtop32	mtop_32_for_64;
5494 #endif /* _MULTI_DATAMODEL */
5495 
5496 
5497 		/*
5498 		 * Get record-size to the user
5499 		 */
5500 		mtop->mt_count = un->un_bsize;
5501 
5502 #ifdef _MULTI_DATAMODEL
5503 		switch (ddi_model_convert_from(flag & FMODELS)) {
5504 		case DDI_MODEL_ILP32:
5505 			/*
5506 			 * Convert 64 bit back to 32 bit before doing
5507 			 * copyout. This is what the ILP32 app expects.
5508 			 */
5509 			mtop_32_for_64.mt_op = mtop->mt_op;
5510 			mtop_32_for_64.mt_count = mtop->mt_count;
5511 
5512 			if (ddi_copyout(&mtop_32_for_64, (void *)arg,
5513 			    sizeof (struct mtop32), flag)) {
5514 				return (EFAULT);
5515 			}
5516 			break;
5517 
5518 		case DDI_MODEL_NONE:
5519 			if (ddi_copyout(mtop, (void *)arg,
5520 			    sizeof (struct mtop), flag)) {
5521 				return (EFAULT);
5522 			}
5523 			break;
5524 		}
5525 #else /* ! _MULTI_DATAMODE */
5526 		if (ddi_copyout(mtop, (void *)arg, sizeof (struct mtop), flag))
5527 			return (EFAULT);
5528 
5529 #endif /* _MULTI_DATAMODE */
5530 
5531 		return (0);
5532 	}
5533 	default:
5534 		rval = ENOTTY;
5535 	}
5536 
5537 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5538 	    "st_ioctl: fileno=%x, blkno=%lx, un_eof=%x\n", un->un_fileno,
5539 	    un->un_blkno, un->un_eof);
5540 
5541 	if (un->un_fileno < 0) {
5542 		un->un_density_known = 0;
5543 	}
5544 
5545 	ASSERT(mutex_owned(ST_MUTEX));
5546 	return (rval);
5547 }
5548 
5549 
5550 /*
5551  * Run a command for uscsi ioctl.
5552  * cdbspace is address space of cdb.
5553  * dataspace is address space of the uscsi data buffer.
5554  */
5555 static int
5556 st_ioctl_cmd(dev_t dev, struct uscsi_cmd *ucmd,
5557 	enum uio_seg cdbspace, enum uio_seg dataspace,
5558 	enum uio_seg rqbufspace)
5559 {
5560 	struct buf *bp;
5561 	struct uscsi_cmd *kcmd;
5562 	caddr_t kcdb;
5563 	int flag;
5564 	int err;
5565 	int rqlen;
5566 	int offline_state = 0;
5567 	char *krqbuf = NULL;
5568 
5569 	GET_SOFT_STATE(dev);
5570 
5571 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5572 	    "st_ioctl_cmd(dev = 0x%lx)\n", dev);
5573 
5574 	ASSERT(mutex_owned(ST_MUTEX));
5575 
5576 	/*
5577 	 * We really don't know what commands are coming in here and
5578 	 * we don't want to limit the commands coming in.
5579 	 *
5580 	 * If st_tape_init() gets called from st_strategy(), then we
5581 	 * will hang the process waiting for un->un_sbuf_busy to be cleared,
5582 	 * which it never will, as we set it below.  To prevent
5583 	 * st_tape_init() from getting called, we have to set state to other
5584 	 * than ST_STATE_OFFLINE, so we choose ST_STATE_INITIALIZING, which
5585 	 * achieves this purpose already
5586 	 *
5587 	 * We use offline_state to preserve the OFFLINE state, if it exists,
5588 	 * so other entry points to the driver might have the chance to call
5589 	 * st_tape_init().
5590 	 */
5591 	if (un->un_state == ST_STATE_OFFLINE) {
5592 		un->un_laststate = ST_STATE_OFFLINE;
5593 		un->un_state = ST_STATE_INITIALIZING;
5594 		offline_state = 1;
5595 	}
5596 	/*
5597 	 * Is this a request to reset the bus?
5598 	 * If so, we need go no further.
5599 	 */
5600 	if (ucmd->uscsi_flags & (USCSI_RESET|USCSI_RESET_ALL)) {
5601 		flag = ((ucmd->uscsi_flags & USCSI_RESET_ALL)) ?
5602 			RESET_ALL : RESET_TARGET;
5603 
5604 		mutex_exit(ST_MUTEX);
5605 		err = (scsi_reset(ROUTE, flag)) ? 0 : EIO;
5606 		mutex_enter(ST_MUTEX);
5607 
5608 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5609 			"reset %s %s\n",
5610 			(flag == RESET_ALL) ? "all" : "target",
5611 			(err == 0) ? "ok" : "failed");
5612 		/*
5613 		 * If scsi reset successful, don't write any filemarks.
5614 		 */
5615 		if (err == 0) {
5616 			un->un_fmneeded = 0;
5617 		} else {
5618 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5619 			    "st_ioctl_cmd : EIO : scsi_reset failed");
5620 		}
5621 		goto exit;
5622 	}
5623 
5624 	/*
5625 	 * First do some sanity checks for USCSI commands.
5626 	 */
5627 	if (ucmd->uscsi_cdblen <= 0) {
5628 		return (EINVAL);
5629 	}
5630 
5631 	/*
5632 	 * In order to not worry about where the uscsi structure
5633 	 * or cdb it points to came from, we kmem_alloc copies
5634 	 * of them here.  This will allow reference to the data
5635 	 * they contain long after this process has gone to
5636 	 * sleep and its kernel stack has been unmapped, etc.
5637 	 */
5638 
5639 	kcdb = kmem_alloc((size_t)ucmd->uscsi_cdblen, KM_SLEEP);
5640 	if (cdbspace == UIO_SYSSPACE) {
5641 		bcopy(ucmd->uscsi_cdb, kcdb, ucmd->uscsi_cdblen);
5642 	} else {
5643 		if (ddi_copyin(ucmd->uscsi_cdb, kcdb,
5644 		    (size_t)ucmd->uscsi_cdblen, 0)) {
5645 			kmem_free(kcdb, (size_t)ucmd->uscsi_cdblen);
5646 			err = EFAULT;
5647 			goto exit;
5648 		}
5649 	}
5650 
5651 	kcmd = kmem_alloc(sizeof (struct uscsi_cmd), KM_SLEEP);
5652 	bcopy(ucmd, kcmd, sizeof (struct uscsi_cmd));
5653 	kcmd->uscsi_cdb = kcdb;
5654 
5655 	flag = (kcmd->uscsi_flags & USCSI_READ) ? B_READ : B_WRITE;
5656 
5657 #ifdef STDEBUG
5658 	if (st_debug > 6) {
5659 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
5660 		    "uscsi cdb", kcdb, kcmd->uscsi_cdblen);
5661 		if (kcmd->uscsi_buflen) {
5662 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5663 			"uscsi %s of %ld bytes %s %s space\n",
5664 			(flag == B_READ) ? rd_str : wr_str,
5665 			kcmd->uscsi_buflen,
5666 			(flag == B_READ) ? "to" : "from",
5667 			(dataspace == UIO_SYSSPACE) ? "system" : "user");
5668 		}
5669 	}
5670 #endif /* ST_DEBUG */
5671 
5672 	/*
5673 	 * Initialize Request Sense buffering, if requested.
5674 	 * For user processes, allocate a kernel copy of the sense buffer
5675 	 */
5676 	if ((kcmd->uscsi_flags & USCSI_RQENABLE) &&
5677 			kcmd->uscsi_rqlen && kcmd->uscsi_rqbuf) {
5678 		if (rqbufspace == UIO_USERSPACE) {
5679 			krqbuf = kmem_alloc(SENSE_LENGTH, KM_SLEEP);
5680 		}
5681 		kcmd->uscsi_rqlen = SENSE_LENGTH;
5682 		kcmd->uscsi_rqresid = SENSE_LENGTH;
5683 	} else {
5684 		kcmd->uscsi_rqlen = 0;
5685 		kcmd->uscsi_rqresid = 0;
5686 	}
5687 
5688 	/*
5689 	 * Get buffer resources...
5690 	 */
5691 	while (un->un_sbuf_busy)
5692 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
5693 	un->un_sbuf_busy = 1;
5694 
5695 	un->un_srqbufp = krqbuf;
5696 	bp = un->un_sbufp;
5697 	bzero(bp, sizeof (buf_t));
5698 
5699 	/*
5700 	 * Force asynchronous mode, if necessary.
5701 	 */
5702 	if (ucmd->uscsi_flags & USCSI_ASYNC) {
5703 		mutex_exit(ST_MUTEX);
5704 		if (scsi_ifgetcap(ROUTE, "synchronous", 1) == 1) {
5705 			if (scsi_ifsetcap(ROUTE, "synchronous", 0, 1) == 1) {
5706 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
5707 				    "forced async ok\n");
5708 			} else {
5709 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
5710 				    "forced async failed\n");
5711 				err = EINVAL;
5712 				mutex_enter(ST_MUTEX);
5713 				goto done;
5714 			}
5715 		}
5716 		mutex_enter(ST_MUTEX);
5717 	}
5718 
5719 	/*
5720 	 * Re-enable synchronous mode, if requested
5721 	 */
5722 	if (ucmd->uscsi_flags & USCSI_SYNC) {
5723 		mutex_exit(ST_MUTEX);
5724 		if (scsi_ifgetcap(ROUTE, "synchronous", 1) == 0) {
5725 			int i = scsi_ifsetcap(ROUTE, "synchronous", 1, 1);
5726 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
5727 				"re-enabled sync %s\n",
5728 				(i == 1) ? "ok" : "failed");
5729 		}
5730 		mutex_enter(ST_MUTEX);
5731 	}
5732 
5733 	if (kcmd->uscsi_buflen) {
5734 		/*
5735 		 * We're going to do actual I/O.
5736 		 * Set things up for physio.
5737 		 */
5738 		struct iovec aiov;
5739 		struct uio auio;
5740 		struct uio *uio = &auio;
5741 
5742 		bzero(&auio, sizeof (struct uio));
5743 		bzero(&aiov, sizeof (struct iovec));
5744 		aiov.iov_base = kcmd->uscsi_bufaddr;
5745 		aiov.iov_len = kcmd->uscsi_buflen;
5746 
5747 		uio->uio_iov = &aiov;
5748 		uio->uio_iovcnt = 1;
5749 		uio->uio_resid = aiov.iov_len;
5750 		uio->uio_segflg = dataspace;
5751 
5752 		/*
5753 		 * Let physio do the rest...
5754 		 */
5755 		bp->b_forw = (struct buf *)(uintptr_t)kcdb[0];
5756 		bp->b_back = (struct buf *)kcmd;
5757 
5758 		mutex_exit(ST_MUTEX);
5759 		err = physio(st_strategy, bp, dev, flag, st_uscsi_minphys, uio);
5760 		mutex_enter(ST_MUTEX);
5761 	} else {
5762 		/*
5763 		 * Mimic physio
5764 		 */
5765 		bp->b_forw = (struct buf *)(uintptr_t)kcdb[0];
5766 		bp->b_back = (struct buf *)kcmd;
5767 		bp->b_flags = B_BUSY | flag;
5768 		bp->b_edev = dev;
5769 		bp->b_dev = cmpdev(dev);
5770 		bp->b_bcount = 0;
5771 		bp->b_blkno = 0;
5772 		bp->b_resid = 0;
5773 		mutex_exit(ST_MUTEX);
5774 		(void) st_strategy(bp);
5775 
5776 		/*
5777 		 * BugTraq #4260046
5778 		 * ----------------
5779 		 * See comments in st_cmd.
5780 		 */
5781 
5782 		err = biowait(bp);
5783 		mutex_enter(ST_MUTEX);
5784 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5785 		    "st_ioctl_cmd: biowait returns %d\n", err);
5786 	}
5787 
5788 	/*
5789 	 * Copy status from kernel copy of uscsi_cmd to user copy
5790 	 * of uscsi_cmd - this was saved in st_done_and_mutex_exit()
5791 	 */
5792 	ucmd->uscsi_status = kcmd->uscsi_status;
5793 
5794 done:
5795 	ucmd->uscsi_resid = bp->b_resid;
5796 
5797 	/*
5798 	 * Update the Request Sense status and resid
5799 	 */
5800 	rqlen = kcmd->uscsi_rqlen - kcmd->uscsi_rqresid;
5801 	rqlen = min(((int)ucmd->uscsi_rqlen), rqlen);
5802 	ucmd->uscsi_rqresid = ucmd->uscsi_rqlen - rqlen;
5803 	ucmd->uscsi_rqstatus = kcmd->uscsi_rqstatus;
5804 	/*
5805 	 * Copy out the sense data for user processes
5806 	 */
5807 	if (ucmd->uscsi_rqbuf && rqlen && rqbufspace == UIO_USERSPACE) {
5808 		if (copyout(krqbuf, ucmd->uscsi_rqbuf, rqlen)) {
5809 			err = EFAULT;
5810 		}
5811 	}
5812 
5813 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5814 	    "st_ioctl_cmd status is 0x%x, resid is 0x%lx\n",
5815 	    ucmd->uscsi_status, ucmd->uscsi_resid);
5816 	if (DEBUGGING && (rqlen != 0)) {
5817 		int i, n, len;
5818 		char *data = krqbuf;
5819 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5820 			"rqstatus=0x%x	rqlen=0x%x  rqresid=0x%x\n",
5821 			ucmd->uscsi_rqstatus, ucmd->uscsi_rqlen,
5822 			ucmd->uscsi_rqresid);
5823 		len = (int)ucmd->uscsi_rqlen - ucmd->uscsi_rqresid;
5824 		for (i = 0; i < len; i += 16) {
5825 			n = min(16, len-1);
5826 			st_clean_print(ST_DEVINFO, st_label, CE_NOTE,
5827 				"  ", &data[i], n);
5828 		}
5829 	}
5830 
5831 exit_free:
5832 	/*
5833 	 * Free resources
5834 	 */
5835 	un->un_sbuf_busy = 0;
5836 	un->un_srqbufp = NULL;
5837 	cv_signal(&un->un_sbuf_cv);
5838 
5839 	if (krqbuf) {
5840 		kmem_free(krqbuf, SENSE_LENGTH);
5841 	}
5842 	kmem_free(kcdb, kcmd->uscsi_cdblen);
5843 	kmem_free(kcmd, sizeof (struct uscsi_cmd));
5844 
5845 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5846 	    "st_ioctl_cmd returns 0x%x\n", err);
5847 
5848 
5849 exit:
5850 	/* don't lose offline state */
5851 	if (offline_state)
5852 		un->un_state = ST_STATE_OFFLINE;
5853 
5854 	ASSERT(mutex_owned(ST_MUTEX));
5855 	return (err);
5856 }
5857 
5858 static int
5859 st_write_fm(dev_t dev, int wfm)
5860 {
5861 	int i;
5862 
5863 	GET_SOFT_STATE(dev);
5864 
5865 	ASSERT(mutex_owned(ST_MUTEX));
5866 
5867 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5868 	    "st_write_fm(dev = 0x%lx, wfm = %d)\n", dev, wfm);
5869 
5870 	/*
5871 	 * write one filemark at the time after EOT
5872 	 */
5873 	if (un->un_eof >= ST_EOT) {
5874 		for (i = 0; i < wfm; i++) {
5875 			if (st_cmd(dev, SCMD_WRITE_FILE_MARK, 1, SYNC_CMD)) {
5876 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5877 				    "st_write_fm : EIO : write EOT file mark");
5878 				return (EIO);
5879 			}
5880 		}
5881 	} else if (st_cmd(dev, SCMD_WRITE_FILE_MARK, wfm, SYNC_CMD)) {
5882 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5883 		    "st_write_fm : EIO : write file mark");
5884 		return (EIO);
5885 	}
5886 
5887 	ASSERT(mutex_owned(ST_MUTEX));
5888 	return (0);
5889 }
5890 
5891 #ifdef STDEBUG
5892 static void
5893 start_dump(struct scsi_tape *un, struct buf *bp)
5894 {
5895 	struct scsi_pkt *pkt = BP_PKT(bp);
5896 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
5897 
5898 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5899 	    "st_start: cmd=0x%p count=%ld resid=%ld flags=0x%x pkt=0x%p\n",
5900 	    (void *)bp->b_forw, bp->b_bcount,
5901 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
5902 
5903 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5904 	    "st_start: cdb %x %x %x %x %x %x, fileno=%d, blk=%ld\n",
5905 	    cdbp[0], cdbp[1], cdbp[2],
5906 	    cdbp[3], cdbp[4], cdbp[5], un->un_fileno,
5907 	    un->un_blkno);
5908 }
5909 #endif
5910 
5911 
5912 /*
5913  * Command start && done functions
5914  */
5915 
5916 /*
5917  * st_start()
5918  *
5919  * Called from:
5920  *  st_strategy() to start a command.
5921  *  st_runout() to retry when scsi_pkt allocation fails on previous attempt(s).
5922  *  st_attach() when resuming from power down state.
5923  *  st_start_restart() to retry transport when device was previously busy.
5924  *  st_done_and_mutex_exit() to start the next command when previous is done.
5925  *
5926  * On entry:
5927  *  scsi_pkt may or may not be allocated.
5928  *
5929  */
5930 static void
5931 st_start(struct scsi_tape *un)
5932 {
5933 	struct buf *bp;
5934 	int status;
5935 
5936 	ASSERT(mutex_owned(ST_MUTEX));
5937 
5938 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5939 	    "st_start(): dev = 0x%lx\n", un->un_dev);
5940 
5941 	if ((bp = un->un_quef) == NULL) {
5942 		return;
5943 	}
5944 
5945 	ASSERT((bp->b_flags & B_DONE) == 0);
5946 
5947 	/*
5948 	 * Don't send more than un_throttle commands to the HBA
5949 	 */
5950 	if ((un->un_throttle <= 0) || (un->un_ncmds >= un->un_throttle)) {
5951 		return;
5952 	}
5953 
5954 	/*
5955 	 * If the buf has no scsi_pkt call st_make_cmd() to get one and
5956 	 * build the command.
5957 	 */
5958 	if (BP_PKT(bp) == NULL) {
5959 		ASSERT((bp->b_flags & B_DONE) == 0);
5960 		st_make_cmd(un, bp, st_runout);
5961 		ASSERT((bp->b_flags & B_DONE) == 0);
5962 		status = geterror(bp);
5963 
5964 		/*
5965 		 * Some HBA's don't call bioerror() to set an error.
5966 		 * And geterror() returns zero if B_ERROR is not set.
5967 		 * So if we get zero we must check b_error.
5968 		 */
5969 		if (status == 0 && bp->b_error != 0) {
5970 			status = bp->b_error;
5971 			bioerror(bp, status);
5972 		}
5973 
5974 		/*
5975 		 * Some HBA's convert DDI_DMA_NORESOURCES into ENOMEM.
5976 		 * In tape ENOMEM has special meaning so we'll change it.
5977 		 */
5978 		if (status == ENOMEM) {
5979 			status = 0;
5980 			bioerror(bp, status);
5981 		}
5982 
5983 		/*
5984 		 * Did it fail and is it retryable?
5985 		 * If so return and wait for the callback through st_runout.
5986 		 * Also looks like scsi_init_pkt() will setup a callback even
5987 		 * if it isn't retryable.
5988 		 */
5989 		if (BP_PKT(bp) == NULL) {
5990 			if (status == 0) {
5991 				/*
5992 				 * If first attempt save state.
5993 				 */
5994 				if (un->un_state != ST_STATE_RESOURCE_WAIT) {
5995 					un->un_laststate = un->un_state;
5996 					un->un_state = ST_STATE_RESOURCE_WAIT;
5997 				}
5998 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5999 				    "temp no resources for pkt\n");
6000 			} else {
6001 				/*
6002 				 * Unlikely that it would be retryable then not.
6003 				 */
6004 				if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6005 					un->un_state = un->un_laststate;
6006 				}
6007 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6008 				    "perm no resources for pkt errno = 0x%x\n",
6009 				    status);
6010 			}
6011 			return;
6012 		}
6013 		/*
6014 		 * Worked this time set the state back.
6015 		 */
6016 		if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6017 			un->un_state = un->un_laststate;
6018 		}
6019 	}
6020 
6021 	/*
6022 	 * move from waitq to runq
6023 	 */
6024 	un->un_quef = bp->b_actf;
6025 	if (un->un_quel == bp) {
6026 		/*
6027 		 *  For the case of queue having one
6028 		 *  element, set the tail pointer to
6029 		 *  point to the element.
6030 		 */
6031 		un->un_quel = bp->b_actf;
6032 	}
6033 
6034 	bp->b_actf = NULL;
6035 
6036 	if (un->un_runqf) {
6037 		un->un_runql->b_actf = bp;
6038 	} else {
6039 		un->un_runqf = bp;
6040 	}
6041 	un->un_runql = bp;
6042 
6043 
6044 #ifdef STDEBUG
6045 	start_dump(un, bp);
6046 #endif
6047 
6048 	/* could not get here if throttle was zero */
6049 	un->un_last_throttle = un->un_throttle;
6050 	un->un_throttle = 0;	/* so nothing else will come in here */
6051 	un->un_ncmds++;
6052 
6053 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
6054 
6055 	mutex_exit(ST_MUTEX);
6056 
6057 	status = scsi_transport(BP_PKT(bp));
6058 
6059 	mutex_enter(ST_MUTEX);
6060 
6061 	if (un->un_last_throttle) {
6062 		un->un_throttle = un->un_last_throttle;
6063 	}
6064 
6065 	if (status != TRAN_ACCEPT) {
6066 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
6067 		mutex_exit(ST_MUTEX);
6068 
6069 		if (status == TRAN_BUSY) {
6070 			/* if too many retries, fail the transport */
6071 			if (st_handle_start_busy(un, bp,
6072 			    ST_TRAN_BUSY_TIMEOUT) == 0)
6073 				goto done;
6074 		}
6075 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6076 		    "transport rejected\n");
6077 		bp->b_resid = bp->b_bcount;
6078 
6079 
6080 #ifndef __lock_lint
6081 		/*
6082 		 * warlock doesn't understand this potential
6083 		 * recursion?
6084 		 */
6085 		mutex_enter(ST_MUTEX);
6086 		ST_DO_KSTATS(bp, kstat_waitq_exit);
6087 		ST_DO_ERRSTATS(un, st_transerrs);
6088 		st_bioerror(bp, EIO);
6089 		SET_PE_FLAG(un);
6090 		st_done_and_mutex_exit(un, bp);
6091 #endif
6092 	} else {
6093 		un->un_tran_retry_ct = 0;
6094 		mutex_exit(ST_MUTEX);
6095 	}
6096 
6097 done:
6098 
6099 	mutex_enter(ST_MUTEX);
6100 }
6101 
6102 /*
6103  * if the transport is busy, then put this bp back on the waitq
6104  */
6105 static int
6106 st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
6107     clock_t timeout_interval)
6108 {
6109 	struct buf *last_quef, *runq_bp;
6110 	int rval = 0;
6111 
6112 	mutex_enter(ST_MUTEX);
6113 
6114 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6115 	    "st_handle_start_busy()\n");
6116 
6117 	/*
6118 	 * Check to see if we hit the retry timeout and one last check for
6119 	 * making sure this is the last on the runq, if it is not, we have
6120 	 * to fail
6121 	 */
6122 	if (((int)un->un_tran_retry_ct++ > st_retry_count) ||
6123 	    (un->un_runql != bp)) {
6124 		rval = -1;
6125 		goto exit;
6126 	}
6127 
6128 	/* put the bp back on the waitq */
6129 	if (un->un_quef) {
6130 		last_quef = un->un_quef;
6131 		un->un_quef = bp;
6132 		bp->b_actf = last_quef;
6133 	} else  {
6134 		bp->b_actf = NULL;
6135 		un->un_quef = bp;
6136 		un->un_quel = bp;
6137 	}
6138 
6139 	/*
6140 	 * Decrement un_ncmds so that this
6141 	 * gets thru' st_start() again.
6142 	 */
6143 	un->un_ncmds--;
6144 
6145 	/*
6146 	 * since this is an error case, we won't have to do
6147 	 * this list walking much.  We've already made sure this bp was the
6148 	 * last on the runq
6149 	 */
6150 	runq_bp = un->un_runqf;
6151 
6152 	if (un->un_runqf == bp) {
6153 		un->un_runqf = NULL;
6154 		un->un_runql = NULL;
6155 	} else {
6156 		while (runq_bp) {
6157 			if (runq_bp->b_actf == bp) {
6158 				runq_bp->b_actf = NULL;
6159 				un->un_runql = runq_bp;
6160 				break;
6161 			}
6162 			runq_bp = runq_bp->b_actf;
6163 		}
6164 	}
6165 
6166 
6167 	/*
6168 	 * send a marker pkt, if appropriate
6169 	 */
6170 	st_hba_unflush(un);
6171 
6172 	/*
6173 	 * all queues are aligned, we are just waiting to
6174 	 * transport, don't alloc any more buf p's, when
6175 	 * st_start is reentered.
6176 	 */
6177 	(void) timeout(st_start_restart, un, timeout_interval);
6178 
6179 exit:
6180 	mutex_exit(ST_MUTEX);
6181 	return (rval);
6182 }
6183 
6184 
6185 
6186 /*
6187  * st_runout a callback that is called what a resource allocatation failed
6188  */
6189 static int
6190 st_runout(caddr_t arg)
6191 {
6192 	struct scsi_tape *un = (struct scsi_tape *)arg;
6193 	struct buf *bp;
6194 
6195 	ASSERT(un != NULL);
6196 
6197 	mutex_enter(ST_MUTEX);
6198 
6199 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_runout()\n");
6200 
6201 	bp = un->un_quef;
6202 
6203 	/*
6204 	 * failed scsi_init_pkt(). If errno is zero its retryable.
6205 	 */
6206 	if ((bp != NULL) && (geterror(bp) != 0)) {
6207 
6208 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6209 		    "errors after pkt alloc (b_flags=0x%x, b_error=0x%x)\n",
6210 		    bp->b_flags, geterror(bp));
6211 		ASSERT((bp->b_flags & B_DONE) == 0);
6212 
6213 		un->un_quef = bp->b_actf;
6214 		if (un->un_quel == bp) {
6215 			/*
6216 			 *  For the case of queue having one
6217 			 *  element, set the tail pointer to
6218 			 *  point to the element.
6219 			 */
6220 			un->un_quel = bp->b_actf;
6221 		}
6222 		bp->b_actf = NULL;
6223 
6224 		ASSERT((bp->b_flags & B_DONE) == 0);
6225 
6226 		/*
6227 		 * Set resid, Error already set, then unblock calling thread.
6228 		 */
6229 		bp->b_resid = bp->b_bcount;
6230 		biodone(bp);
6231 	} else {
6232 		/*
6233 		 * Try Again
6234 		 */
6235 		st_start(un);
6236 	}
6237 
6238 	mutex_exit(ST_MUTEX);
6239 
6240 	/*
6241 	 * Comments courtesy of sd.c
6242 	 * The scsi_init_pkt routine allows for the callback function to
6243 	 * return a 0 indicating the callback should be rescheduled or a 1
6244 	 * indicating not to reschedule. This routine always returns 1
6245 	 * because the driver always provides a callback function to
6246 	 * scsi_init_pkt. This results in a callback always being scheduled
6247 	 * (via the scsi_init_pkt callback implementation) if a resource
6248 	 * failure occurs.
6249 	 */
6250 
6251 	return (1);
6252 }
6253 
6254 /*
6255  * st_done_and_mutex_exit()
6256  *	- remove bp from runq
6257  *	- start up the next request
6258  *	- if this was an asynch bp, clean up
6259  *	- exit with released mutex
6260  */
6261 static void
6262 st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp)
6263 {
6264 	struct buf *runqbp, *prevbp;
6265 	int	pe_flagged = 0;
6266 
6267 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
6268 #if !defined(lint)
6269 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
6270 #endif
6271 	ASSERT(mutex_owned(ST_MUTEX));
6272 
6273 	/*
6274 	 * if bp is still on the runq (anywhere), then remove it
6275 	 */
6276 	prevbp = NULL;
6277 	for (runqbp = un->un_runqf; runqbp != 0; runqbp = runqbp->b_actf) {
6278 		if (runqbp == bp) {
6279 			if (runqbp == un->un_runqf) {
6280 				un->un_runqf = bp->b_actf;
6281 			} else {
6282 				prevbp->b_actf = bp->b_actf;
6283 			}
6284 			if (un->un_runql == bp) {
6285 				un->un_runql = prevbp;
6286 			}
6287 			break;
6288 		}
6289 		prevbp = runqbp;
6290 	}
6291 	bp->b_actf = NULL;
6292 
6293 	un->un_ncmds--;
6294 	cv_signal(&un->un_queue_cv);
6295 
6296 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6297 	"st_done_and_mutex_exit(): cmd=0x%x count=%ld resid=%ld  flags=0x%x\n",
6298 		(int)*((caddr_t)(BP_PKT(bp))->pkt_cdbp),
6299 		bp->b_bcount, bp->b_resid, bp->b_flags);
6300 
6301 
6302 	/*
6303 	 * update kstats with transfer count info
6304 	 */
6305 	if (un->un_stats && (bp != un->un_sbufp) && IS_RW(bp)) {
6306 		uint32_t n_done =  bp->b_bcount - bp->b_resid;
6307 		if (bp->b_flags & B_READ) {
6308 			IOSP->reads++;
6309 			IOSP->nread += n_done;
6310 		} else {
6311 			IOSP->writes++;
6312 			IOSP->nwritten += n_done;
6313 		}
6314 	}
6315 
6316 	/*
6317 	 * Start the next one before releasing resources on this one, if
6318 	 * there is something on the queue and persistent errors has not been
6319 	 * flagged
6320 	 */
6321 
6322 	if ((pe_flagged = IS_PE_FLAG_SET(un)) != 0) {
6323 		un->un_last_resid = bp->b_resid;
6324 		un->un_last_count = bp->b_bcount;
6325 	}
6326 
6327 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
6328 		cv_broadcast(&un->un_tape_busy_cv);
6329 	} else if (un->un_quef && un->un_throttle && !pe_flagged) {
6330 		st_start(un);
6331 	}
6332 
6333 	if (bp == un->un_sbufp && (bp->b_flags & B_ASYNC)) {
6334 		/*
6335 		 * Since we marked this ourselves as ASYNC,
6336 		 * there isn't anybody around waiting for
6337 		 * completion any more.
6338 		 */
6339 		uchar_t com = (uchar_t)(uintptr_t)bp->b_forw;
6340 		if (com == SCMD_READ || com == SCMD_WRITE) {
6341 			bp->b_un.b_addr = (caddr_t)0;
6342 		}
6343 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6344 		    "st_done_and_mutex_exit(async): freeing pkt\n");
6345 		scsi_destroy_pkt(BP_PKT(bp));
6346 		un->un_sbuf_busy = 0;
6347 		cv_signal(&un->un_sbuf_cv);
6348 		mutex_exit(ST_MUTEX);
6349 		return;
6350 	}
6351 
6352 	if (bp == un->un_sbufp && BP_UCMD(bp)) {
6353 		/*
6354 		 * Copy status from scsi_pkt to uscsi_cmd
6355 		 * since st_ioctl_cmd needs it
6356 		 */
6357 		BP_UCMD(bp)->uscsi_status = SCBP_C(BP_PKT(bp));
6358 	}
6359 
6360 
6361 #ifdef STDEBUG
6362 	if ((st_debug >= 4) &&
6363 	    (((un->un_blkno % 100) == 0) || IS_PE_FLAG_SET(un))) {
6364 
6365 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6366 		    "st_d_a_m_exit(): ncmds = %d, thr = %d, "
6367 		    "un_errno = %d, un_pe = %d\n",
6368 		    un->un_ncmds, un->un_throttle, un->un_errno,
6369 		    un->un_persist_errors);
6370 	}
6371 
6372 #endif
6373 
6374 	mutex_exit(ST_MUTEX);
6375 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6376 	    "st_done_and_mutex_exit: freeing pkt\n");
6377 
6378 	scsi_destroy_pkt(BP_PKT(bp));
6379 
6380 	biodone(bp);
6381 
6382 	/*
6383 	 * now that we biodoned that command, if persistent errors have been
6384 	 * flagged, flush the waitq
6385 	 */
6386 	if (pe_flagged)
6387 		st_flush(un);
6388 }
6389 
6390 
6391 /*
6392  * Tape error, flush tape driver queue.
6393  */
6394 static void
6395 st_flush(struct scsi_tape *un)
6396 {
6397 	struct buf *bp;
6398 
6399 	mutex_enter(ST_MUTEX);
6400 
6401 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6402 	    "st_flush(), ncmds = %d, quef = 0x%p\n",
6403 	    un->un_ncmds, (void *)un->un_quef);
6404 
6405 	/*
6406 	 * if we still have commands outstanding, wait for them to come in
6407 	 * before flushing the queue, and make sure there is a queue
6408 	 */
6409 	if (un->un_ncmds || !un->un_quef)
6410 		goto exit;
6411 
6412 	/*
6413 	 * we have no more commands outstanding, so let's deal with special
6414 	 * cases in the queue for EOM and FM. If we are here, and un_errno
6415 	 * is 0, then we know there was no error and we return a 0 read or
6416 	 * write before showing errors
6417 	 */
6418 
6419 	/* Flush the wait queue. */
6420 	while ((bp = un->un_quef) != NULL) {
6421 		un->un_quef = bp->b_actf;
6422 
6423 		bp->b_resid = bp->b_bcount;
6424 
6425 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6426 		    "st_flush() : blkno=%ld, err=%d, b_bcount=%ld\n",
6427 		    un->un_blkno, un->un_errno, bp->b_bcount);
6428 
6429 		st_set_pe_errno(un);
6430 
6431 		bioerror(bp, un->un_errno);
6432 
6433 		mutex_exit(ST_MUTEX);
6434 		/* it should have one, but check anyway */
6435 		if (BP_PKT(bp)) {
6436 			scsi_destroy_pkt(BP_PKT(bp));
6437 		}
6438 		biodone(bp);
6439 		mutex_enter(ST_MUTEX);
6440 	}
6441 
6442 	/*
6443 	 * It's not a bad practice to reset the
6444 	 * waitq tail pointer to NULL.
6445 	 */
6446 	un->un_quel = NULL;
6447 
6448 exit:
6449 	/* we mucked with the queue, so let others know about it */
6450 	cv_signal(&un->un_queue_cv);
6451 	mutex_exit(ST_MUTEX);
6452 }
6453 
6454 
6455 /*
6456  * Utility functions
6457  */
6458 static int
6459 st_determine_generic(dev_t dev)
6460 {
6461 	int bsize;
6462 	static char *cart = "0.25 inch cartridge";
6463 	char *sizestr;
6464 
6465 	GET_SOFT_STATE(dev);
6466 
6467 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6468 	    "st_determine_generic(dev = 0x%lx)\n", dev);
6469 
6470 	ASSERT(mutex_owned(ST_MUTEX));
6471 
6472 	if (st_modesense(un)) {
6473 		return (-1);
6474 	}
6475 
6476 	bsize = (un->un_mspl->high_bl << 16)	|
6477 		(un->un_mspl->mid_bl << 8)	|
6478 		(un->un_mspl->low_bl);
6479 
6480 	if (bsize == 0) {
6481 		un->un_dp->options |= ST_VARIABLE;
6482 		un->un_dp->bsize = 0;
6483 		un->un_bsize = 0;
6484 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
6485 		/*
6486 		 * record size of this device too big.
6487 		 * try and convert it to variable record length.
6488 		 *
6489 		 */
6490 		un->un_dp->options |= ST_VARIABLE;
6491 		if (st_change_block_size(dev, 0) != 0) {
6492 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
6493 			    "Fixed Record Size %d is too large\n", bsize);
6494 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
6495 			    "Cannot switch to variable record size\n");
6496 			un->un_dp->options &= ~ST_VARIABLE;
6497 			return (-1);
6498 		}
6499 	} else if (st_change_block_size(dev, 0) == 0) {
6500 		/*
6501 		 * If the drive was set to a non zero block size,
6502 		 * See if it can be set to a zero block size.
6503 		 * If it works, ST_VARIABLE so user can set it as they want.
6504 		 */
6505 		un->un_dp->options |= ST_VARIABLE;
6506 		un->un_dp->bsize = 0;
6507 		un->un_bsize = 0;
6508 	} else {
6509 		un->un_dp->bsize = bsize;
6510 		un->un_bsize = bsize;
6511 	}
6512 
6513 
6514 	switch (un->un_mspl->density) {
6515 	default:
6516 	case 0x0:
6517 		/*
6518 		 * default density, cannot determine any other
6519 		 * information.
6520 		 */
6521 		sizestr = "Unknown type- assuming 0.25 inch cartridge";
6522 		un->un_dp->type = ST_TYPE_DEFAULT;
6523 		un->un_dp->options |= (ST_AUTODEN_OVERRIDE|ST_QIC);
6524 		break;
6525 	case 0x1:
6526 	case 0x2:
6527 	case 0x3:
6528 	case 0x6:
6529 		/*
6530 		 * 1/2" reel
6531 		 */
6532 		sizestr = "0.50 inch reel";
6533 		un->un_dp->type = ST_TYPE_REEL;
6534 		un->un_dp->options |= ST_REEL;
6535 		un->un_dp->densities[0] = 0x1;
6536 		un->un_dp->densities[1] = 0x2;
6537 		un->un_dp->densities[2] = 0x6;
6538 		un->un_dp->densities[3] = 0x3;
6539 		break;
6540 	case 0x4:
6541 	case 0x5:
6542 	case 0x7:
6543 	case 0x0b:
6544 
6545 		/*
6546 		 * Quarter inch.
6547 		 */
6548 		sizestr = cart;
6549 		un->un_dp->type = ST_TYPE_DEFAULT;
6550 		un->un_dp->options |= ST_QIC;
6551 
6552 		un->un_dp->densities[1] = 0x4;
6553 		un->un_dp->densities[2] = 0x5;
6554 		un->un_dp->densities[3] = 0x7;
6555 		un->un_dp->densities[0] = 0x0b;
6556 		break;
6557 
6558 	case 0x0f:
6559 	case 0x10:
6560 	case 0x11:
6561 	case 0x12:
6562 		/*
6563 		 * QIC-120, QIC-150, QIC-320, QIC-600
6564 		 */
6565 		sizestr = cart;
6566 		un->un_dp->type = ST_TYPE_DEFAULT;
6567 		un->un_dp->options |= ST_QIC;
6568 		un->un_dp->densities[0] = 0x0f;
6569 		un->un_dp->densities[1] = 0x10;
6570 		un->un_dp->densities[2] = 0x11;
6571 		un->un_dp->densities[3] = 0x12;
6572 		break;
6573 
6574 	case 0x09:
6575 	case 0x0a:
6576 	case 0x0c:
6577 	case 0x0d:
6578 		/*
6579 		 * 1/2" cartridge tapes. Include HI-TC.
6580 		 */
6581 		sizestr = cart;
6582 		sizestr[2] = '5';
6583 		sizestr[3] = '0';
6584 		un->un_dp->type = ST_TYPE_HIC;
6585 		un->un_dp->densities[0] = 0x09;
6586 		un->un_dp->densities[1] = 0x0a;
6587 		un->un_dp->densities[2] = 0x0c;
6588 		un->un_dp->densities[3] = 0x0d;
6589 		break;
6590 
6591 	case 0x13:
6592 			/* DDS-2/DDS-3 scsi spec densities */
6593 	case 0x24:
6594 	case 0x25:
6595 	case 0x26:
6596 		sizestr = "DAT Data Storage (DDS)";
6597 		un->un_dp->type = ST_TYPE_DAT;
6598 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
6599 		break;
6600 
6601 	case 0x14:
6602 		/*
6603 		 * Helical Scan (Exabyte) devices
6604 		 */
6605 		sizestr = "8mm helical scan cartridge";
6606 		un->un_dp->type = ST_TYPE_EXABYTE;
6607 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
6608 		break;
6609 	}
6610 
6611 	/*
6612 	 * Assume LONG ERASE, BSF and BSR
6613 	 */
6614 
6615 	un->un_dp->options |= (ST_LONG_ERASE|ST_UNLOADABLE|ST_BSF|
6616 				ST_BSR|ST_KNOWS_EOD);
6617 
6618 	/*
6619 	 * Only if mode sense data says no buffered write, set NOBUF
6620 	 */
6621 	if (un->un_mspl->bufm == 0)
6622 		un->un_dp->options |= ST_NOBUF;
6623 
6624 	/*
6625 	 * set up large read and write retry counts
6626 	 */
6627 
6628 	un->un_dp->max_rretries = un->un_dp->max_wretries = 1000;
6629 
6630 	/*
6631 	 * If this is a 0.50 inch reel tape, and
6632 	 * it is *not* variable mode, try and
6633 	 * set it to variable record length
6634 	 * mode.
6635 	 */
6636 	if ((un->un_dp->options & ST_REEL) && un->un_bsize != 0 &&
6637 	    (un->un_dp->options & ST_VARIABLE)) {
6638 		if (st_change_block_size(dev, 0) == 0) {
6639 			un->un_dp->bsize = 0;
6640 			un->un_mspl->high_bl = un->un_mspl->mid_bl =
6641 			    un->un_mspl->low_bl = 0;
6642 		}
6643 	}
6644 
6645 	/*
6646 	 * Write to console about type of device found
6647 	 */
6648 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
6649 	    "Generic Drive, Vendor=%s\n\t%s", un->un_dp->name,
6650 	    sizestr);
6651 	if (un->un_dp->options & ST_VARIABLE) {
6652 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
6653 		    "!Variable record length I/O\n");
6654 	} else {
6655 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
6656 		    "!Fixed record length (%d byte blocks) I/O\n",
6657 		    un->un_dp->bsize);
6658 	}
6659 	ASSERT(mutex_owned(ST_MUTEX));
6660 	return (0);
6661 }
6662 
6663 static int
6664 st_determine_density(dev_t dev, int rw)
6665 {
6666 	int rval = 0;
6667 
6668 	GET_SOFT_STATE(dev);
6669 
6670 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6671 	    "st_determine_density(dev = 0x%lx, rw = %s)\n",
6672 	    dev, (rw == B_WRITE ? wr_str: rd_str));
6673 
6674 	ASSERT(mutex_owned(ST_MUTEX));
6675 
6676 	/*
6677 	 * If we're past BOT, density is determined already.
6678 	 */
6679 	if (un->un_fileno > 0 || (un->un_fileno == 0 && un->un_blkno != 0)) {
6680 		/*
6681 		 * XXX: put in a bitch message about attempting to
6682 		 * XXX: change density past BOT.
6683 		 */
6684 		goto exit;
6685 	}
6686 
6687 	/*
6688 	 * If we're going to be writing, we set the density
6689 	 */
6690 	if (rw == 0 || rw == B_WRITE) {
6691 		/* un_curdens is used as an index into densities table */
6692 		un->un_curdens = MT_DENSITY(un->un_dev);
6693 		if (st_set_density(dev)) {
6694 			rval = -1;
6695 		}
6696 		goto exit;
6697 	}
6698 
6699 	/*
6700 	 * If density is known already,
6701 	 * we don't have to get it again.(?)
6702 	 */
6703 	if (!un->un_density_known) {
6704 		if (st_get_density(dev)) {
6705 			rval = -1;
6706 		}
6707 	}
6708 
6709 exit:
6710 	ASSERT(mutex_owned(ST_MUTEX));
6711 	return (rval);
6712 }
6713 
6714 
6715 /*
6716  * Try to determine density. We do this by attempting to read the
6717  * first record off the tape, cycling through the available density
6718  * codes as we go.
6719  */
6720 
6721 static int
6722 st_get_density(dev_t dev)
6723 {
6724 	int succes = 0, rval = -1, i;
6725 	uint_t size;
6726 	uchar_t dens, olddens;
6727 
6728 	GET_SOFT_STATE(dev);
6729 
6730 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6731 	    "st_get_density(dev = 0x%lx)\n", dev);
6732 
6733 	ASSERT(mutex_owned(ST_MUTEX));
6734 
6735 	/*
6736 	 * If Auto Density override is enabled The drive has
6737 	 * only one density and there is no point in attempting
6738 	 * find the correct one.
6739 	 *
6740 	 * Since most modern drives auto detect the density
6741 	 * and format of the recorded media before they come
6742 	 * ready. What this function does is a legacy behavior
6743 	 * and modern drives not only don't need it, The backup
6744 	 * utilities that do positioning via uscsi find the un-
6745 	 * expected rewinds problematic.
6746 	 *
6747 	 * The drives that need this are old reel to reel devices.
6748 	 * I took a swag and said they must be scsi-1 or older.
6749 	 * I don't beleave there will any of the newer devices
6750 	 * that need this. There will be some scsi-1 devices that
6751 	 * don't need this but I don't think they will be using the
6752 	 * BIG aftermarket backup and restore utilitys.
6753 	 */
6754 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) ||
6755 	    (un->un_sd->sd_inq->inq_ansi > 1)) {
6756 		un->un_density_known = 1;
6757 		rval = 0;
6758 		goto exit;
6759 	}
6760 
6761 	/*
6762 	 * This will only work on variable record length tapes
6763 	 * if and only if all variable record length tapes autodensity
6764 	 * select.
6765 	 */
6766 	size = (unsigned)(un->un_dp->bsize ? un->un_dp->bsize : SECSIZE);
6767 	un->un_tmpbuf = kmem_alloc(size, KM_SLEEP);
6768 
6769 	/*
6770 	 * Start at the specified density
6771 	 */
6772 
6773 	dens = olddens = un->un_curdens = MT_DENSITY(un->un_dev);
6774 
6775 	for (i = 0; i < NDENSITIES; i++, ((un->un_curdens == NDENSITIES - 1) ?
6776 					(un->un_curdens = 0) :
6777 					(un->un_curdens += 1))) {
6778 		/*
6779 		 * If we've done this density before,
6780 		 * don't bother to do it again.
6781 		 */
6782 		dens = un->un_dp->densities[un->un_curdens];
6783 		if (i > 0 && dens == olddens)
6784 			continue;
6785 		olddens = dens;
6786 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6787 		    "trying density 0x%x\n", dens);
6788 		if (st_set_density(dev)) {
6789 			continue;
6790 		}
6791 
6792 		/*
6793 		 * XXX - the creates lots of headaches and slowdowns - must
6794 		 * fix.
6795 		 */
6796 		succes = (st_cmd(dev, SCMD_READ, (int)size, SYNC_CMD) == 0);
6797 		if (st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD)) {
6798 			break;
6799 		}
6800 		if (succes) {
6801 			st_init(un);
6802 			rval = 0;
6803 			un->un_density_known = 1;
6804 			break;
6805 		}
6806 	}
6807 	kmem_free(un->un_tmpbuf, size);
6808 	un->un_tmpbuf = 0;
6809 
6810 exit:
6811 	ASSERT(mutex_owned(ST_MUTEX));
6812 	return (rval);
6813 }
6814 
6815 static int
6816 st_set_density(dev_t dev)
6817 {
6818 	int rval = 0;
6819 
6820 	GET_SOFT_STATE(dev);
6821 
6822 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6823 	    "st_set_density(dev = 0x%lx): density = 0x%x\n", dev,
6824 	    un->un_dp->densities[un->un_curdens]);
6825 
6826 	ASSERT(mutex_owned(ST_MUTEX));
6827 
6828 	un->un_mspl->density = un->un_dp->densities[un->un_curdens];
6829 
6830 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) == 0) {
6831 		/*
6832 		 * If auto density override is not set, Use mode select
6833 		 * to set density and compression.
6834 		 */
6835 		if (st_modeselect(un)) {
6836 			rval = -1;
6837 		}
6838 	} else if ((un->un_dp->options & ST_MODE_SEL_COMP) != 0) {
6839 		/*
6840 		 * If auto density and mode select compression are set,
6841 		 * This is a drive with one density code but compression
6842 		 * can be enabled or disabled.
6843 		 * Set compression but no need to set density.
6844 		 */
6845 		rval = st_set_compression(un);
6846 		if ((rval != 0) && (rval != EALREADY)) {
6847 			rval = -1;
6848 		} else {
6849 			rval = 0;
6850 		}
6851 	}
6852 
6853 	/* If sucessful set density and/or compression, mark density known */
6854 	if (rval == 0) {
6855 		un->un_density_known = 1;
6856 	}
6857 
6858 	ASSERT(mutex_owned(ST_MUTEX));
6859 	return (rval);
6860 }
6861 
6862 static int
6863 st_loadtape(dev_t dev)
6864 {
6865 	int rval = 0;
6866 
6867 	GET_SOFT_STATE(dev);
6868 
6869 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6870 	    "st_loadtape(dev = 0x%lx)\n", dev);
6871 
6872 	ASSERT(mutex_owned(ST_MUTEX));
6873 
6874 	/*
6875 	 * 'LOAD' the tape to BOT by rewinding
6876 	 */
6877 	if (st_cmd(dev, SCMD_REWIND, 1, SYNC_CMD)) {
6878 		rval = -1;
6879 	} else {
6880 		st_init(un);
6881 		un->un_density_known = 0;
6882 	}
6883 
6884 	ASSERT(mutex_owned(ST_MUTEX));
6885 	return (rval);
6886 }
6887 
6888 
6889 /*
6890  * Note: QIC devices aren't so smart.  If you try to append
6891  * after EOM, the write can fail because the device doesn't know
6892  * it's at EOM.	 In that case, issue a read.  The read should fail
6893  * because there's no data, but the device knows it's at EOM,
6894  * so a subsequent write should succeed.  To further confuse matters,
6895  * the target returns the same error if the tape is positioned
6896  * such that a write would overwrite existing data.  That's why
6897  * we have to do the append test.  A read in the middle of
6898  * recorded data would succeed, thus indicating we're attempting
6899  * something illegal.
6900  */
6901 
6902 void bp_mapin(struct buf *bp);
6903 
6904 static void
6905 st_test_append(struct buf *bp)
6906 {
6907 	dev_t dev = bp->b_edev;
6908 	struct scsi_tape *un;
6909 	uchar_t status;
6910 	unsigned bcount;
6911 
6912 	un = ddi_get_soft_state(st_state, MTUNIT(dev));
6913 
6914 	ASSERT(mutex_owned(ST_MUTEX));
6915 
6916 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6917 	    "st_test_append(): fileno %d\n", un->un_fileno);
6918 
6919 	un->un_laststate = un->un_state;
6920 	un->un_state = ST_STATE_APPEND_TESTING;
6921 	un->un_test_append = 0;
6922 
6923 	/*
6924 	 * first, map in the buffer, because we're doing a double write --
6925 	 * first into the kernel, then onto the tape.
6926 	 */
6927 	bp_mapin(bp);
6928 
6929 	/*
6930 	 * get a copy of the data....
6931 	 */
6932 	un->un_tmpbuf = kmem_alloc((unsigned)bp->b_bcount, KM_SLEEP);
6933 	bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
6934 
6935 	/*
6936 	 * attempt the write..
6937 	 */
6938 
6939 	if (st_cmd(dev, (int)SCMD_WRITE, (int)bp->b_bcount, SYNC_CMD) == 0) {
6940 success:
6941 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6942 		    "append write succeeded\n");
6943 		bp->b_resid = un->un_sbufp->b_resid;
6944 		mutex_exit(ST_MUTEX);
6945 		bcount = (unsigned)bp->b_bcount;
6946 		biodone(bp);
6947 		mutex_enter(ST_MUTEX);
6948 		un->un_laststate = un->un_state;
6949 		un->un_state = ST_STATE_OPEN;
6950 		kmem_free(un->un_tmpbuf, bcount);
6951 		un->un_tmpbuf = NULL;
6952 		return;
6953 	}
6954 
6955 	/*
6956 	 * The append failed. Do a short read. If that fails,  we are at EOM
6957 	 * so we can retry the write command. If that succeeds, than we're
6958 	 * all screwed up (the controller reported a real error).
6959 	 *
6960 	 * XXX: should the dummy read be > SECSIZE? should it be the device's
6961 	 * XXX: block size?
6962 	 *
6963 	 */
6964 	status = un->un_status;
6965 	un->un_status = 0;
6966 	(void) st_cmd(dev, SCMD_READ, SECSIZE, SYNC_CMD);
6967 	if (un->un_status == KEY_BLANK_CHECK) {
6968 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6969 		    "append at EOM\n");
6970 		/*
6971 		 * Okay- the read failed. We should actually have confused
6972 		 * the controller enough to allow writing. In any case, the
6973 		 * i/o is on its own from here on out.
6974 		 */
6975 		un->un_laststate = un->un_state;
6976 		un->un_state = ST_STATE_OPEN;
6977 		bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
6978 		if (st_cmd(dev, (int)SCMD_WRITE, (int)bp->b_bcount,
6979 		    SYNC_CMD) == 0) {
6980 			goto success;
6981 		}
6982 	}
6983 
6984 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6985 	    "append write failed- not at EOM\n");
6986 	bp->b_resid = bp->b_bcount;
6987 	st_bioerror(bp, EIO);
6988 
6989 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6990 	    "st_test_append : EIO : append write failed - not at EOM");
6991 
6992 	/*
6993 	 * backspace one record to get back to where we were
6994 	 */
6995 	if (st_cmd(dev, SCMD_SPACE, Blk(-1), SYNC_CMD)) {
6996 		un->un_fileno = -1;
6997 	}
6998 
6999 	un->un_err_resid = bp->b_resid;
7000 	un->un_status = status;
7001 
7002 	/*
7003 	 * Note: biodone will do a bp_mapout()
7004 	 */
7005 	mutex_exit(ST_MUTEX);
7006 	bcount = (unsigned)bp->b_bcount;
7007 	biodone(bp);
7008 	mutex_enter(ST_MUTEX);
7009 	un->un_laststate = un->un_state;
7010 	un->un_state = ST_STATE_OPEN_PENDING_IO;
7011 	kmem_free(un->un_tmpbuf, bcount);
7012 	un->un_tmpbuf = NULL;
7013 }
7014 
7015 /*
7016  * Special command handler
7017  */
7018 
7019 /*
7020  * common st_cmd code. The fourth parameter states
7021  * whether the caller wishes to await the results
7022  * Note the release of the mutex during most of the function
7023  */
7024 static int
7025 st_cmd(dev_t dev, int com, int count, int wait)
7026 {
7027 	struct buf *bp;
7028 	int err;
7029 
7030 	GET_SOFT_STATE(dev);
7031 
7032 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7033 	    "st_cmd(dev = 0x%lx, com = 0x%x, count = %x, wait = %d)\n",
7034 	    dev, com, count, wait);
7035 
7036 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
7037 	ASSERT(mutex_owned(ST_MUTEX));
7038 
7039 #ifdef STDEBUG
7040 	if (st_debug)
7041 		st_debug_cmds(un, com, count, wait);
7042 #endif
7043 
7044 	while (un->un_sbuf_busy)
7045 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
7046 	un->un_sbuf_busy = 1;
7047 
7048 	bp = un->un_sbufp;
7049 	bzero(bp, sizeof (buf_t));
7050 
7051 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
7052 
7053 	/*
7054 	 * Set count to the actual size of the data tranfer.
7055 	 * For commands with no data transfer, set bp->b_bcount
7056 	 * to the value to be used when constructing the
7057 	 * cdb in st_make_cmd().
7058 	 */
7059 	switch (com) {
7060 	case SCMD_READ:
7061 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7062 		    "special read %d\n", count);
7063 		bp->b_flags |= B_READ;
7064 		bp->b_un.b_addr = un->un_tmpbuf;
7065 		break;
7066 
7067 	case SCMD_WRITE:
7068 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7069 		    "special write %d\n", count);
7070 		bp->b_un.b_addr = un->un_tmpbuf;
7071 		break;
7072 
7073 	case SCMD_WRITE_FILE_MARK:
7074 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7075 		    "write %d file marks\n", count);
7076 		bp->b_bcount = count;
7077 		count = 0;
7078 		break;
7079 
7080 	case SCMD_REWIND:
7081 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "rewind\n");
7082 		bp->b_bcount = 0;
7083 		count = 0;
7084 		break;
7085 
7086 	case SCMD_SPACE:
7087 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "space\n");
7088 		bp->b_bcount = count;
7089 		count = 0;
7090 		break;
7091 
7092 	case SCMD_RESERVE:
7093 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "reserve");
7094 		bp->b_bcount = 0;
7095 		count = 0;
7096 		break;
7097 
7098 	case SCMD_RELEASE:
7099 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "release");
7100 		bp->b_bcount = 0;
7101 		count = 0;
7102 		break;
7103 
7104 	case SCMD_LOAD:
7105 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7106 		    "%s tape\n", (count) ? "load" : "unload");
7107 		bp->b_bcount = count;
7108 		count = 0;
7109 		break;
7110 
7111 	case SCMD_ERASE:
7112 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7113 		    "erase tape\n");
7114 		bp->b_bcount = 0;
7115 		count = 0;
7116 		break;
7117 
7118 	case SCMD_MODE_SENSE:
7119 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7120 		    "mode sense\n");
7121 		bp->b_flags |= B_READ;
7122 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7123 		break;
7124 
7125 	case SCMD_MODE_SELECT:
7126 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7127 		    "mode select\n");
7128 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7129 		break;
7130 
7131 	case SCMD_READ_BLKLIM:
7132 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7133 		    "read block limits\n");
7134 		bp->b_flags |= B_READ;
7135 		bp->b_un.b_addr = (caddr_t)(un->un_rbl);
7136 		break;
7137 
7138 	case SCMD_TEST_UNIT_READY:
7139 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7140 		    "test unit ready\n");
7141 		bp->b_bcount = 0;
7142 		count = 0;
7143 		break;
7144 	default:
7145 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7146 		    "Unhandled scsi command 0x%x in st_cmd()\n", com);
7147 	}
7148 
7149 	mutex_exit(ST_MUTEX);
7150 
7151 	if (count > 0) {
7152 		/*
7153 		 * We're going to do actual I/O.
7154 		 * Set things up for physio.
7155 		 */
7156 		struct iovec aiov;
7157 		struct uio auio;
7158 		struct uio *uio = &auio;
7159 
7160 		bzero(&auio, sizeof (struct uio));
7161 		bzero(&aiov, sizeof (struct iovec));
7162 		aiov.iov_base = bp->b_un.b_addr;
7163 		aiov.iov_len = count;
7164 
7165 		uio->uio_iov = &aiov;
7166 		uio->uio_iovcnt = 1;
7167 		uio->uio_resid = aiov.iov_len;
7168 		uio->uio_segflg = UIO_SYSSPACE;
7169 
7170 		/*
7171 		 * Let physio do the rest...
7172 		 */
7173 		bp->b_forw = (struct buf *)(uintptr_t)com;
7174 		bp->b_back = NULL;
7175 		err = physio(st_strategy, bp, dev,
7176 			(bp->b_flags & B_READ) ? B_READ : B_WRITE,
7177 			st_minphys, uio);
7178 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7179 		    "st_cmd: physio returns %d\n", err);
7180 	} else {
7181 		/*
7182 		 * Mimic physio
7183 		 */
7184 		bp->b_forw = (struct buf *)(uintptr_t)com;
7185 		bp->b_back = NULL;
7186 		bp->b_edev = dev;
7187 		bp->b_dev = cmpdev(dev);
7188 		bp->b_blkno = 0;
7189 		bp->b_resid = 0;
7190 		(void) st_strategy(bp);
7191 		if (!wait) {
7192 			/*
7193 			 * This is an async command- the caller won't wait
7194 			 * and doesn't care about errors.
7195 			 */
7196 			mutex_enter(ST_MUTEX);
7197 			return (0);
7198 		}
7199 
7200 		/*
7201 		 * BugTraq #4260046
7202 		 * ----------------
7203 		 * Restore Solaris 2.5.1 behavior, namely call biowait
7204 		 * unconditionally. The old comment said...
7205 		 *
7206 		 * "if strategy was flagged with  persistent errors, we would
7207 		 *  have an error here, and the bp would never be sent, so we
7208 		 *  don't want to wait on a bp that was never sent...or hang"
7209 		 *
7210 		 * The new rationale, courtesy of Chitrank...
7211 		 *
7212 		 * "we should unconditionally biowait() here because
7213 		 *  st_strategy() will do a biodone() in the persistent error
7214 		 *  case and the following biowait() will return immediately.
7215 		 *  If not, in the case of "errors after pkt alloc" in
7216 		 *  st_start(), we will not biowait here which will cause the
7217 		 *  next biowait() to return immediately which will cause
7218 		 *  us to send out the next command. In the case where both of
7219 		 *  these use the sbuf, when the first command completes we'll
7220 		 *  free the packet attached to sbuf and the same pkt will
7221 		 *  get freed again when we complete the second command.
7222 		 *  see esc 518987.  BTW, it is necessary to do biodone() in
7223 		 *  st_start() for the pkt alloc failure case because physio()
7224 		 *  does biowait() and will hang if we don't do biodone()"
7225 		 */
7226 
7227 		err = biowait(bp);
7228 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7229 		    "st_cmd: biowait returns %d\n", err);
7230 	}
7231 	mutex_enter(ST_MUTEX);
7232 
7233 	un->un_sbuf_busy = 0;
7234 	cv_signal(&un->un_sbuf_cv);
7235 	return (err);
7236 }
7237 
7238 static int
7239 st_set_compression(struct scsi_tape *un)
7240 {
7241 	int rval;
7242 	int turn_compression_on;
7243 	minor_t minor;
7244 
7245 	/*
7246 	 * Drive either dosn't have compression or it is controlled with
7247 	 * special density codes. Return ENOTTY so caller
7248 	 * knows nothing was done.
7249 	 */
7250 	if ((un->un_dp->options & ST_MODE_SEL_COMP) == 0) {
7251 		un->un_comp_page = 0;
7252 		return (ENOTTY);
7253 	}
7254 
7255 	/* set compression based on minor node opened */
7256 	minor = MT_DENSITY(un->un_dev);
7257 
7258 	/*
7259 	 * If this the compression density or
7260 	 * the drive has two densities and uses mode select for
7261 	 * control of compression turn on compression for MT_DENSITY2
7262 	 * as well.
7263 	 */
7264 	if ((minor == ST_COMPRESSION_DENSITY) ||
7265 	    (minor == MT_DENSITY(MT_DENSITY2)) &&
7266 	    (un->un_dp->densities[0] == un->un_dp->densities[1]) &&
7267 	    (un->un_dp->densities[2] == un->un_dp->densities[3]) &&
7268 	    (un->un_dp->densities[0] != un->un_dp->densities[2])) {
7269 
7270 		turn_compression_on = 1;
7271 	} else {
7272 		turn_compression_on = 0;
7273 	}
7274 
7275 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
7276 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
7277 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
7278 
7279 	/*
7280 	 * Need to determine which page does the device use for compression.
7281 	 * First try the data compression page. If this fails try the device
7282 	 * configuration page
7283 	 */
7284 
7285 	if ((un->un_comp_page & ST_DEV_DATACOMP_PAGE) == ST_DEV_DATACOMP_PAGE) {
7286 		rval = st_set_datacomp_page(un, turn_compression_on);
7287 		if (rval == EALREADY) {
7288 			return (rval);
7289 		}
7290 		if (rval != 0) {
7291 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7292 				/*
7293 				 * This device does not support data
7294 				 * compression page
7295 				 */
7296 				un->un_comp_page = ST_DEV_CONFIG_PAGE;
7297 			} else if (un->un_state >= ST_STATE_OPEN) {
7298 				un->un_fileno = -1;
7299 				rval = EIO;
7300 			} else {
7301 				rval = -1;
7302 			}
7303 		} else {
7304 			un->un_comp_page = ST_DEV_DATACOMP_PAGE;
7305 		}
7306 	}
7307 
7308 	if ((un->un_comp_page & ST_DEV_CONFIG_PAGE) == ST_DEV_CONFIG_PAGE) {
7309 		rval = st_set_devconfig_page(un, turn_compression_on);
7310 		if (rval == EALREADY) {
7311 			return (rval);
7312 		}
7313 		if (rval != 0) {
7314 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7315 				/*
7316 				 * This device does not support
7317 				 * compression at all advice the
7318 				 * user and unset ST_MODE_SEL_COMP
7319 				 */
7320 				un->un_dp->options &= ~ST_MODE_SEL_COMP;
7321 				un->un_comp_page = 0;
7322 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7323 				    "Device Does Not Support Compression\n");
7324 			} else if (un->un_state >= ST_STATE_OPEN) {
7325 				un->un_fileno = -1;
7326 				rval = EIO;
7327 			} else {
7328 				rval = -1;
7329 			}
7330 		}
7331 	}
7332 
7333 	return (rval);
7334 }
7335 
7336 /*
7337  * set or unset compression thru device configuration page.
7338  */
7339 static int
7340 st_set_devconfig_page(struct scsi_tape *un, int compression_on)
7341 {
7342 	unsigned char cflag;
7343 	int rval = 0;
7344 
7345 	ASSERT(mutex_owned(ST_MUTEX));
7346 
7347 	/*
7348 	 * Figure what to set compression flag to.
7349 	 */
7350 	if (compression_on) {
7351 		/* They have selected a compression node */
7352 		if (un->un_dp->type == ST_TYPE_FUJI) {
7353 			cflag = 0x84;   /* use EDRC */
7354 		} else {
7355 			cflag = ST_DEV_CONFIG_DEF_COMP;
7356 		}
7357 	} else {
7358 		cflag = ST_DEV_CONFIG_NO_COMP;
7359 	}
7360 
7361 	/*
7362 	 * If compression is already set the way it was requested.
7363 	 * And if this not the first time we has tried.
7364 	 */
7365 	if ((cflag == un->un_mspl->page.dev.comp_alg) &&
7366 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
7367 		return (EALREADY);
7368 	}
7369 
7370 	un->un_mspl->page.dev.comp_alg = cflag;
7371 	/*
7372 	 * need to send mode select even if correct compression is
7373 	 * already set since need to set density code
7374 	 */
7375 
7376 #ifdef STDEBUG
7377 	if (st_debug >= 6) {
7378 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7379 		    "st_set_devconfig_page: sense data for mode select",
7380 		    (char *)un->un_mspl, sizeof (struct seq_mode));
7381 	}
7382 #endif
7383 	rval = st_gen_mode_select(un, un->un_mspl, sizeof (struct seq_mode));
7384 
7385 	return (rval);
7386 }
7387 
7388 /*
7389  * set/reset compression bit thru data compression page
7390  */
7391 static int
7392 st_set_datacomp_page(struct scsi_tape *un, int compression_on)
7393 {
7394 	int compression_on_already;
7395 	int rval = 0;
7396 
7397 	ASSERT(mutex_owned(ST_MUTEX));
7398 
7399 	/*
7400 	 * If drive is not capable of compression (at this time)
7401 	 * return EALREADY so caller doesn't think that this page
7402 	 * is not supported. This check is for drives that can
7403 	 * disable compression from the front panel or configuration.
7404 	 * I doubt that a drive that supports this page is not really
7405 	 * capable of compression.
7406 	 */
7407 	if (un->un_mspl->page.comp.dcc == 0) {
7408 		return (EALREADY);
7409 	}
7410 
7411 	/* See if compression currently turned on */
7412 	if (un->un_mspl->page.comp.dce) {
7413 		compression_on_already = 1;
7414 	} else {
7415 		compression_on_already = 0;
7416 	}
7417 
7418 	/*
7419 	 * If compression is already set the way it was requested.
7420 	 * And if this not the first time we has tried.
7421 	 */
7422 	if ((compression_on == compression_on_already) &&
7423 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
7424 		return (EALREADY);
7425 	}
7426 
7427 	/*
7428 	 * if we are already set to the appropriate compression
7429 	 * mode, don't set it again
7430 	 */
7431 	if (compression_on) {
7432 		/* compression selected */
7433 		un->un_mspl->page.comp.dce = 1;
7434 	} else {
7435 		un->un_mspl->page.comp.dce = 0;
7436 	}
7437 
7438 
7439 #ifdef STDEBUG
7440 	if (st_debug >= 6) {
7441 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7442 		    "st_set_datacomp_page: sense data for mode select",
7443 		    (char *)un->un_mspl, sizeof (struct seq_mode));
7444 	}
7445 #endif
7446 	rval = st_gen_mode_select(un, un->un_mspl, sizeof (struct seq_mode));
7447 
7448 	return (rval);
7449 }
7450 
7451 static int
7452 st_modesense(struct scsi_tape *un)
7453 {
7454 	int rval;
7455 	uchar_t page;
7456 
7457 	page = un->un_comp_page;
7458 
7459 	switch (page) {
7460 	case ST_DEV_DATACOMP_PAGE:
7461 	case ST_DEV_CONFIG_PAGE: /* fall through */
7462 		rval = st_gen_mode_sense(un, page, un->un_mspl,
7463 		    sizeof (struct seq_mode));
7464 		break;
7465 
7466 	case ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE:
7467 		if (un->un_dp->options & ST_MODE_SEL_COMP) {
7468 			page = ST_DEV_DATACOMP_PAGE;
7469 			rval = st_gen_mode_sense(un, page, un->un_mspl,
7470 			    sizeof (struct seq_mode));
7471 			if (rval == 0 && un->un_mspl->page_code == page) {
7472 				un->un_comp_page = page;
7473 				break;
7474 			}
7475 			page = ST_DEV_CONFIG_PAGE;
7476 			rval = st_gen_mode_sense(un, page, un->un_mspl,
7477 			    sizeof (struct seq_mode));
7478 			if (rval == 0 && un->un_mspl->page_code == page) {
7479 				un->un_comp_page = page;
7480 				break;
7481 			}
7482 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
7483 			un->un_comp_page = 0;
7484 		} else {
7485 			un->un_comp_page = 0;
7486 		}
7487 
7488 	default:	/* fall through */
7489 		rval = st_cmd(un->un_dev, SCMD_MODE_SENSE, MSIZE, SYNC_CMD);
7490 	}
7491 	return (rval);
7492 }
7493 
7494 static int
7495 st_modeselect(struct scsi_tape *un)
7496 {
7497 	int rval = 0;
7498 	int ix;
7499 
7500 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7501 	    "st_modeselect(dev = 0x%lx): density = 0x%x\n",
7502 	    un->un_dev, un->un_mspl->density);
7503 
7504 	ASSERT(mutex_owned(ST_MUTEX));
7505 
7506 	/*
7507 	 * The parameter list should be the same for all of the
7508 	 * cases that follow so set them here
7509 	 *
7510 	 * Try mode select first if if fails set fields manually
7511 	 */
7512 	rval = st_modesense(un);
7513 	if (rval != 0) {
7514 		ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
7515 		    "st_modeselect: First mode sense failed\n");
7516 		un->un_mspl->bd_len  = 8;
7517 		un->un_mspl->high_nb = 0;
7518 		un->un_mspl->mid_nb  = 0;
7519 		un->un_mspl->low_nb  = 0;
7520 	}
7521 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
7522 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
7523 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
7524 
7525 
7526 	/*
7527 	 * If configured to use a specific density code for a media type.
7528 	 * curdens is previously set by the minor node opened.
7529 	 * If the media type doesn't match the minor node we change it so it
7530 	 * looks like the correct one was opened.
7531 	 */
7532 	if (un->un_dp->options & ST_KNOWS_MEDIA) {
7533 		uchar_t best;
7534 
7535 		for (best = 0xff, ix = 0; ix < NDENSITIES; ix++) {
7536 			if (un->un_mspl->media_type ==
7537 			    un->un_dp->mediatype[ix]) {
7538 				best = ix;
7539 				/*
7540 				 * It matches but it might not be the only one.
7541 				 * Use the highest matching media type but not
7542 				 * to exceed the density selected by the open.
7543 				 */
7544 				if (ix < un->un_curdens) {
7545 					continue;
7546 				}
7547 				un->un_curdens = ix;
7548 				break;
7549 			}
7550 		}
7551 		/* If a match was found best will not be 0xff any more */
7552 		if (best < NDENSITIES) {
7553 			ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
7554 			    "found media 0x%X using density 0x%X\n",
7555 			    un->un_mspl->media_type,
7556 			    un->un_dp->densities[best]);
7557 		}
7558 
7559 		un->un_mspl->density = un->un_dp->densities[best];
7560 
7561 	} else {
7562 		/* Otherwise set density based on minor node opened */
7563 		un->un_mspl->density = un->un_dp->densities[un->un_curdens];
7564 	}
7565 
7566 	if (un->un_dp->options & ST_NOBUF) {
7567 		un->un_mspl->bufm = 0;
7568 	} else {
7569 		un->un_mspl->bufm = 1;
7570 	}
7571 
7572 	rval = st_set_compression(un);
7573 
7574 	/*
7575 	 * If st_set_compression returned invalid or already it
7576 	 * found no need to do the mode select.
7577 	 * So do it here.
7578 	 */
7579 	if ((rval == ENOTTY) || (rval == EALREADY)) {
7580 
7581 		/* Zero non-writeable fields */
7582 		un->un_mspl->data_len = 0;
7583 		un->un_mspl->media_type = 0;
7584 		un->un_mspl->wp = 0;
7585 
7586 		/* need to set the density code */
7587 		rval = st_cmd(un->un_dev, SCMD_MODE_SELECT, MSIZE, SYNC_CMD);
7588 		if (rval != 0) {
7589 			if (un->un_state >= ST_STATE_OPEN) {
7590 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
7591 				    "unable to set tape mode\n");
7592 				un->un_fileno = -1;
7593 				rval = EIO;
7594 			} else {
7595 				rval = -1;
7596 			}
7597 		}
7598 	}
7599 
7600 	/*
7601 	 * The spec recommends to send a mode sense after a mode select
7602 	 */
7603 	(void) st_modesense(un);
7604 
7605 	ASSERT(mutex_owned(ST_MUTEX));
7606 
7607 	return (rval);
7608 }
7609 
7610 /*
7611  * st_gen_mode_sense
7612  *
7613  * generic mode sense.. it allows for any page
7614  */
7615 static int
7616 st_gen_mode_sense(struct scsi_tape *un, int page, struct seq_mode *page_data,
7617     int page_size)
7618 {
7619 
7620 	int r;
7621 	char	cdb[CDB_GROUP0];
7622 	struct uscsi_cmd *com;
7623 
7624 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
7625 
7626 	bzero(cdb, CDB_GROUP0);
7627 	cdb[0] = SCMD_MODE_SENSE;
7628 	cdb[2] = (char)page;
7629 	cdb[4] = (char)page_size;
7630 
7631 	com->uscsi_cdb = cdb;
7632 	com->uscsi_cdblen = CDB_GROUP0;
7633 	com->uscsi_bufaddr = (caddr_t)page_data;
7634 	com->uscsi_buflen = page_size;
7635 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
7636 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT |
7637 			    USCSI_READ | USCSI_RQENABLE;
7638 
7639 	r = st_ioctl_cmd(un->un_dev, com, UIO_SYSSPACE, UIO_SYSSPACE,
7640 		UIO_SYSSPACE);
7641 	kmem_free(com, sizeof (*com));
7642 	return (r);
7643 }
7644 
7645 /*
7646  * st_gen_mode_select
7647  *
7648  * generic mode select.. it allows for any page
7649  */
7650 static int
7651 st_gen_mode_select(struct scsi_tape *un, struct seq_mode *page_data,
7652     int page_size)
7653 {
7654 
7655 	int r;
7656 	char cdb[CDB_GROUP0];
7657 	struct uscsi_cmd *com;
7658 
7659 	/* Zero non-writeable fields */
7660 	page_data->data_len = 0;
7661 	page_data->media_type = 0;
7662 	page_data->wp = 0;
7663 
7664 	/*
7665 	 * If mode select has any page data, zero the ps (Page Savable) bit.
7666 	 */
7667 	if (page_size > MSIZE) {
7668 		page_data->ps = 0;
7669 	}
7670 
7671 
7672 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
7673 
7674 	/*
7675 	 * then, do a mode select to set what ever info
7676 	 */
7677 	bzero(cdb, CDB_GROUP0);
7678 	cdb[0] = SCMD_MODE_SELECT;
7679 	cdb[1] = 0x10;		/* set PF bit for many third party drives */
7680 	cdb[4] = (char)page_size;
7681 
7682 	com->uscsi_cdb = cdb;
7683 	com->uscsi_cdblen = CDB_GROUP0;
7684 	com->uscsi_bufaddr = (caddr_t)page_data;
7685 	com->uscsi_buflen = page_size;
7686 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
7687 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT
7688 		| USCSI_WRITE | USCSI_RQENABLE;
7689 
7690 	r = st_ioctl_cmd(un->un_dev, com, UIO_SYSSPACE, UIO_SYSSPACE,
7691 		UIO_SYSSPACE);
7692 
7693 	kmem_free(com, sizeof (*com));
7694 	return (r);
7695 }
7696 
7697 /*
7698  * Changes devices blocksize and bsize to requested blocksize nblksz.
7699  * Returns returned value from first failed call or zero on success.
7700  */
7701 static int
7702 st_change_block_size(dev_t dev, uint32_t nblksz)
7703 {
7704 	struct seq_mode *current;
7705 	int rval;
7706 	uint32_t oldblksz;
7707 
7708 	GET_SOFT_STATE(dev);
7709 
7710 	current = kmem_zalloc(MSIZE, KM_SLEEP);
7711 
7712 	/* Read current settings */
7713 	rval = st_gen_mode_sense(un, 0, current, MSIZE);
7714 	if (rval != 0) {
7715 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
7716 		    "mode sense for change block size failed: rval = %d", rval);
7717 		goto finish;
7718 	}
7719 
7720 	/* Figure the current block size */
7721 	oldblksz =
7722 	    (current->high_bl << 16) |
7723 	    (current->mid_bl << 8) |
7724 	    (current->low_bl);
7725 
7726 	/* If current block size is the same as requested were done */
7727 	if (oldblksz == nblksz) {
7728 		un->un_bsize = nblksz;
7729 		rval = 0;
7730 		goto finish;
7731 	}
7732 
7733 	/* Change to requested block size */
7734 	current->high_bl = (uchar_t)(nblksz >> 16);
7735 	current->mid_bl  = (uchar_t)(nblksz >> 8);
7736 	current->low_bl  = (uchar_t)(nblksz);
7737 
7738 	/* Attempt to change block size */
7739 	rval = st_gen_mode_select(un, current, MSIZE);
7740 	if (rval != 0) {
7741 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
7742 		    "Set new block size failed: rval = %d", rval);
7743 		goto finish;
7744 	}
7745 
7746 	/* Read back and verify setting */
7747 	rval = st_modesense(un);
7748 	if (rval == 0) {
7749 		un->un_bsize =
7750 		    (un->un_mspl->high_bl << 16) |
7751 		    (un->un_mspl->mid_bl << 8) |
7752 		    (un->un_mspl->low_bl);
7753 
7754 		if (un->un_bsize != nblksz) {
7755 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
7756 			    "Blocksize set does not equal requested blocksize"
7757 			    "(read: %u requested: %u)\n", nblksz, un->un_bsize);
7758 			rval = EIO;
7759 		}
7760 	}
7761 finish:
7762 	kmem_free(current, MSIZE);
7763 	return (rval);
7764 }
7765 
7766 
7767 static void
7768 st_init(struct scsi_tape *un)
7769 {
7770 	ASSERT(mutex_owned(ST_MUTEX));
7771 
7772 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7773 	"st_init(): dev = 0x%lx, will reset fileno, blkno, eof\n", un->un_dev);
7774 
7775 	un->un_blkno = 0;
7776 	un->un_fileno = 0;
7777 	un->un_lastop = ST_OP_NIL;
7778 	un->un_eof = ST_NO_EOF;
7779 	un->un_pwr_mgmt = ST_PWR_NORMAL;
7780 	if (st_error_level != SCSI_ERR_ALL) {
7781 		if (DEBUGGING) {
7782 			st_error_level = SCSI_ERR_ALL;
7783 		} else {
7784 			st_error_level = SCSI_ERR_RETRYABLE;
7785 		}
7786 	}
7787 }
7788 
7789 
7790 static void
7791 st_make_cmd(struct scsi_tape *un, struct buf *bp, int (*func)(caddr_t))
7792 {
7793 	struct scsi_pkt *pkt;
7794 	struct uscsi_cmd *ucmd;
7795 	int count, tval = 0;
7796 	int flags = 0;
7797 	uchar_t com;
7798 	char fixbit;
7799 
7800 	ASSERT(mutex_owned(ST_MUTEX));
7801 
7802 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7803 	    "st_make_cmd(): dev = 0x%lx\n", un->un_dev);
7804 
7805 
7806 	/*
7807 	 * fixbit is for setting the Fixed Mode and Suppress Incorrect
7808 	 * Length Indicator bits on read/write commands, for setting
7809 	 * the Long bit on erase commands, and for setting the Code
7810 	 * Field bits on space commands.
7811 	 * XXX why do we set lastop here?
7812 	 */
7813 
7814 	if (bp != un->un_sbufp) {		/* regular raw I/O */
7815 		int stat_size = (un->un_arq_enabled ?
7816 			sizeof (struct scsi_arq_status) : 1);
7817 		pkt = scsi_init_pkt(ROUTE, NULL, bp,
7818 		    CDB_GROUP0, stat_size, 0, 0, func, (caddr_t)un);
7819 		if (pkt == NULL) {
7820 			goto exit;
7821 		}
7822 		SET_BP_PKT(bp, pkt);
7823 		if (un->un_bsize == 0) {
7824 			count = bp->b_bcount;
7825 			fixbit = 0;
7826 		} else {
7827 			count = bp->b_bcount / un->un_bsize;
7828 			fixbit = 1;
7829 		}
7830 		if (bp->b_flags & B_READ) {
7831 			com = SCMD_READ;
7832 			un->un_lastop = ST_OP_READ;
7833 			if ((un->un_bsize == 0) && /* Not Fixed Block */
7834 			    (un->un_dp->options & ST_READ_IGNORE_ILI)) {
7835 				fixbit = 2;
7836 			}
7837 		} else {
7838 			com = SCMD_WRITE;
7839 			un->un_lastop = ST_OP_WRITE;
7840 		}
7841 
7842 		tval = un->un_dp->io_timeout;
7843 
7844 		/*
7845 		 * For really large xfers, increase timeout
7846 		 */
7847 		if (bp->b_bcount > (10 * ONE_MEG))
7848 			tval *= bp->b_bcount/(10 * ONE_MEG);
7849 
7850 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7851 		    "%s %ld amt 0x%lx\n", (com == SCMD_WRITE) ?
7852 		    wr_str: rd_str, un->un_blkno, bp->b_bcount);
7853 
7854 	} else if ((ucmd = BP_UCMD(bp)) != NULL) {
7855 		/*
7856 		 * uscsi - build command, allocate scsi resources
7857 		 */
7858 		st_make_uscsi_cmd(un, ucmd, bp, func);
7859 		goto exit;
7860 
7861 	} else {				/* special I/O */
7862 		struct buf *allocbp = NULL;
7863 		int stat_size = (un->un_arq_enabled ?
7864 			sizeof (struct scsi_arq_status) : 1);
7865 
7866 
7867 		com = (uchar_t)(uintptr_t)bp->b_forw;
7868 		count = bp->b_bcount;
7869 
7870 		switch (com) {
7871 		case SCMD_READ:
7872 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7873 			    "special read %d\n", count);
7874 			if (un->un_bsize == 0) {
7875 				fixbit = 2;	/* suppress SILI */
7876 			} else {
7877 				fixbit = 1;	/* Fixed Block Mode */
7878 				count /= un->un_bsize;
7879 			}
7880 			allocbp = bp;
7881 			un->un_lastop = ST_OP_READ;
7882 			tval = un->un_dp->io_timeout;
7883 			break;
7884 
7885 		case SCMD_WRITE:
7886 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7887 			    "special write %d\n", count);
7888 			if (un->un_bsize != 0) {
7889 				fixbit = 1;	/* Fixed Block Mode */
7890 				count /= un->un_bsize;
7891 			} else {
7892 				fixbit = 0;
7893 			}
7894 			allocbp = bp;
7895 			un->un_lastop = ST_OP_WRITE;
7896 			tval = un->un_dp->io_timeout;
7897 			break;
7898 
7899 		case SCMD_WRITE_FILE_MARK:
7900 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7901 			    "write %d file marks\n", count);
7902 			un->un_lastop = ST_OP_WEOF;
7903 			fixbit = 0;
7904 			tval = un->un_dp->io_timeout;
7905 			break;
7906 
7907 		case SCMD_REWIND:
7908 			fixbit = 0;
7909 			count = 0;
7910 			un->un_lastop = ST_OP_CTL;
7911 			tval = un->un_dp->rewind_timeout;
7912 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7913 			    "rewind\n");
7914 			break;
7915 
7916 		case SCMD_SPACE:
7917 			fixbit = Isfmk(count);
7918 			count = (int)space_cnt(count);
7919 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7920 			    "space %d %s from file %d blk %ld\n",
7921 			    count, (fixbit) ? "filemarks" : "records",
7922 			    un->un_fileno, un->un_blkno);
7923 			un->un_lastop = ST_OP_CTL;
7924 			tval = un->un_dp->space_timeout;
7925 			break;
7926 
7927 		case SCMD_LOAD:
7928 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7929 			    "%s tape\n", (count & 1) ? "load" : "unload");
7930 			fixbit = 0;
7931 
7932 			/* Loading or Unloading */
7933 			if (count & 1) {
7934 				tval = un->un_dp->load_timeout;
7935 			} else {
7936 				tval = un->un_dp->unload_timeout;
7937 			}
7938 			/* Is Retension requested */
7939 			if (count & 2) {
7940 				tval += un->un_dp->rewind_timeout;
7941 			}
7942 			un->un_lastop = ST_OP_CTL;
7943 			break;
7944 
7945 		case SCMD_ERASE:
7946 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7947 			    "erase tape\n");
7948 			count = 0;
7949 			/*
7950 			 * We support long erase only
7951 			 */
7952 			fixbit = 1;
7953 			tval = un->un_dp->erase_timeout;
7954 			un->un_lastop = ST_OP_CTL;
7955 			break;
7956 
7957 		case SCMD_MODE_SENSE:
7958 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7959 			    "mode sense\n");
7960 			allocbp = bp;
7961 			fixbit = 0;
7962 			tval = un->un_dp->non_motion_timeout;
7963 			break;
7964 
7965 		case SCMD_MODE_SELECT:
7966 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7967 			    "mode select\n");
7968 			allocbp = bp;
7969 			fixbit = 0;
7970 			tval = un->un_dp->non_motion_timeout;
7971 			break;
7972 
7973 		case SCMD_RESERVE:
7974 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7975 			    "reserve\n");
7976 			fixbit = 0;
7977 			tval = un->un_dp->non_motion_timeout;
7978 			break;
7979 
7980 		case SCMD_RELEASE:
7981 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7982 			    "release\n");
7983 			fixbit = 0;
7984 			tval = un->un_dp->non_motion_timeout;
7985 			break;
7986 
7987 		case SCMD_READ_BLKLIM:
7988 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7989 			    "read block limits\n");
7990 			allocbp = bp;
7991 			fixbit = count = 0;
7992 			tval = un->un_dp->non_motion_timeout;
7993 			break;
7994 
7995 		case SCMD_TEST_UNIT_READY:
7996 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7997 			    "test unit ready\n");
7998 			fixbit = 0;
7999 			tval = un->un_dp->non_motion_timeout;
8000 			break;
8001 		default:
8002 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8003 			    "Unhandled scsi command 0x%x in st_make_cmd()\n",
8004 			    com);
8005 		}
8006 		pkt = scsi_init_pkt(ROUTE, NULL, allocbp,
8007 			CDB_GROUP0, stat_size, 0, 0, func, (caddr_t)un);
8008 		if (pkt == NULL) {
8009 			goto exit;
8010 		}
8011 		if (allocbp)
8012 			ASSERT(geterror(allocbp) == 0);
8013 
8014 	}
8015 
8016 	(void) scsi_setup_cdb((union scsi_cdb *)pkt->pkt_cdbp,
8017 	    com, 0, (uint_t)count, 0);
8018 	FILL_SCSI1_LUN(un->un_sd, pkt);
8019 	/*
8020 	 * Initialize the SILI/Fixed bits of the byte 1 of cdb.
8021 	 */
8022 	((union scsi_cdb *)(pkt->pkt_cdbp))->t_code = fixbit;
8023 	pkt->pkt_flags = flags;
8024 
8025 	/*
8026 	 * If ST_SHORT_FILEMARKS bit is ON for EXABYTE
8027 	 * device, set the Vendor Unique bit to
8028 	 * write Short File Mark.
8029 	 */
8030 	if (com == SCMD_WRITE_FILE_MARK &&
8031 		un->un_dp->options & ST_SHORT_FILEMARKS) {
8032 		switch (un->un_dp->type) {
8033 		case ST_TYPE_EXB8500:
8034 		case ST_TYPE_EXABYTE:
8035 			/*
8036 			 * Now the Vendor Unique bit 7 in Byte 5 of CDB
8037 			 * is set to to write Short File Mark
8038 			 */
8039 			((union scsi_cdb *)pkt->pkt_cdbp)->g0_vu_1 = 1;
8040 			break;
8041 
8042 		default:
8043 			/*
8044 			 * Well, if ST_SHORT_FILEMARKS is set for other
8045 			 * tape drives, it is just ignored
8046 			 */
8047 			break;
8048 		}
8049 	}
8050 	ASSERT(tval);
8051 	pkt->pkt_time = tval;
8052 	pkt->pkt_comp = st_intr;
8053 	pkt->pkt_private = (opaque_t)bp;
8054 	SET_BP_PKT(bp, pkt);
8055 
8056 exit:
8057 	ASSERT(mutex_owned(ST_MUTEX));
8058 }
8059 
8060 
8061 /*
8062  * Build a command based on a uscsi command;
8063  */
8064 static void
8065 st_make_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
8066     struct buf *bp, int (*func)(caddr_t))
8067 {
8068 	struct scsi_pkt *pkt;
8069 	caddr_t cdb;
8070 	int	cdblen;
8071 	int stat_size;
8072 
8073 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8074 	    "st_make_uscsi_cmd(): dev = 0x%lx\n", un->un_dev);
8075 
8076 	if (ucmd->uscsi_flags & USCSI_RQENABLE) {
8077 		stat_size = (un->un_arq_enabled ?
8078 		    sizeof (struct scsi_arq_status) : 1);
8079 	} else {
8080 		stat_size = 1;
8081 	}
8082 
8083 	ASSERT(mutex_owned(ST_MUTEX));
8084 
8085 	un->un_lastop = ST_OP_CTL;	/* usual */
8086 
8087 	cdb = ucmd->uscsi_cdb;
8088 	cdblen = ucmd->uscsi_cdblen;
8089 
8090 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8091 	    "st_make_uscsi_cmd: buflen=%ld bcount=%ld\n",
8092 		ucmd->uscsi_buflen, bp->b_bcount);
8093 	pkt = scsi_init_pkt(ROUTE, NULL,
8094 		(bp->b_bcount > 0) ? bp : NULL,
8095 		cdblen, stat_size, 0, 0, func, (caddr_t)un);
8096 	if (pkt == NULL) {
8097 		goto exit;
8098 	}
8099 
8100 	bcopy(cdb, pkt->pkt_cdbp, (uint_t)cdblen);
8101 
8102 #ifdef STDEBUG
8103 	if (st_debug >= 6) {
8104 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
8105 		    "pkt_cdbp", (char *)cdb, cdblen);
8106 	}
8107 #endif
8108 
8109 	if (ucmd->uscsi_flags & USCSI_SILENT) {
8110 		pkt->pkt_flags |= FLAG_SILENT;
8111 	}
8112 
8113 	pkt->pkt_time = ucmd->uscsi_timeout;
8114 	pkt->pkt_comp = st_intr;
8115 	pkt->pkt_private = (opaque_t)bp;
8116 	SET_BP_PKT(bp, pkt);
8117 exit:
8118 	ASSERT(mutex_owned(ST_MUTEX));
8119 }
8120 
8121 
8122 /*
8123  * restart cmd currently at the head of the runq
8124  *
8125  * If scsi_transport() succeeds or the retries
8126  * count exhausted, restore the throttle that was
8127  * zeroed out in st_handle_intr_busy().
8128  *
8129  */
8130 static void
8131 st_intr_restart(void *arg)
8132 {
8133 	struct scsi_tape *un = arg;
8134 	struct buf *bp;
8135 	int status = TRAN_ACCEPT;
8136 
8137 	mutex_enter(ST_MUTEX);
8138 
8139 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8140 		"st_intr_restart(), un = 0x%p\n", (void *)un);
8141 
8142 	un->un_hib_tid = 0;
8143 
8144 	/*
8145 	 * move from waitq to runq, if there is anything on the waitq
8146 	 */
8147 	if ((bp = un->un_quef) == NULL) {
8148 		mutex_exit(ST_MUTEX);
8149 		return;
8150 	}
8151 
8152 	/*
8153 	 * Here we know :
8154 	 *	throttle = 0, via st_handle_intr_busy
8155 	 */
8156 
8157 	if (un->un_quel == bp) {
8158 		un->un_quel = NULL;
8159 		un->un_quef = NULL;	/* we know it's the first one */
8160 	} else {
8161 		un->un_quef = bp->b_actf;
8162 	}
8163 	bp->b_actf = NULL;
8164 
8165 	if (un->un_runqf) {
8166 		/*
8167 		 * not good, we don't want to requeue something after
8168 		 * another.
8169 		 */
8170 		mutex_exit(ST_MUTEX);
8171 		goto done_error;
8172 	} else {
8173 		un->un_runqf = bp;
8174 		un->un_runql = bp;
8175 	}
8176 
8177 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
8178 
8179 	mutex_exit(ST_MUTEX);
8180 
8181 	status = scsi_transport(BP_PKT(bp));
8182 
8183 	mutex_enter(ST_MUTEX);
8184 
8185 	if (status != TRAN_ACCEPT) {
8186 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
8187 		mutex_exit(ST_MUTEX);
8188 
8189 		if (status == TRAN_BUSY) {
8190 			if (st_handle_intr_busy(un, bp,
8191 			    ST_TRAN_BUSY_TIMEOUT) == 0)
8192 				return;	/* timeout is setup again */
8193 		}
8194 
8195 	} else {
8196 		un->un_tran_retry_ct = 0;
8197 		if (un->un_last_throttle) {
8198 			un->un_throttle = un->un_last_throttle;
8199 		}
8200 		mutex_exit(ST_MUTEX);
8201 		return;
8202 	}
8203 
8204 done_error:
8205 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8206 	    "restart transport rejected\n");
8207 	bp->b_resid = bp->b_bcount;
8208 
8209 #ifndef __lock_lint
8210 	/*
8211 	 * warlock doesn't understand this potential
8212 	 * recursion?
8213 	 */
8214 	mutex_enter(ST_MUTEX);
8215 	if (un->un_last_throttle) {
8216 		un->un_throttle = un->un_last_throttle;
8217 	}
8218 	if (status != TRAN_ACCEPT)
8219 		ST_DO_ERRSTATS(un, st_transerrs);
8220 	ST_DO_KSTATS(bp, kstat_waitq_exit);
8221 	SET_PE_FLAG(un);
8222 	st_bioerror(bp, EIO);
8223 	st_done_and_mutex_exit(un, bp);
8224 #endif
8225 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8226 	    "busy restart aborted\n");
8227 }
8228 
8229 /*
8230  * st_check_media():
8231  * Periodically check the media state using scsi_watch service;
8232  * this service calls back after TUR and possibly request sense
8233  * the callback handler (st_media_watch_cb()) decodes the request sense
8234  * data (if any)
8235  */
8236 
8237 static int
8238 st_check_media(dev_t dev, enum mtio_state state)
8239 {
8240 	int rval = 0;
8241 	enum mtio_state	prev_state;
8242 	opaque_t token = NULL;
8243 
8244 	GET_SOFT_STATE(dev);
8245 
8246 	mutex_enter(ST_MUTEX);
8247 
8248 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8249 		"st_check_media:state=%x, mediastate=%x\n",
8250 		state, un->un_mediastate);
8251 
8252 	prev_state = un->un_mediastate;
8253 
8254 	/*
8255 	 * is there anything to do?
8256 	 */
8257 retry:
8258 	if (state == un->un_mediastate || un->un_mediastate == MTIO_NONE) {
8259 		/*
8260 		 * submit the request to the scsi_watch service;
8261 		 * scsi_media_watch_cb() does the real work
8262 		 */
8263 		mutex_exit(ST_MUTEX);
8264 		token = scsi_watch_request_submit(ST_SCSI_DEVP,
8265 			st_check_media_time, SENSE_LENGTH,
8266 			st_media_watch_cb, (caddr_t)dev);
8267 		if (token == NULL) {
8268 			rval = EAGAIN;
8269 			goto done;
8270 		}
8271 		mutex_enter(ST_MUTEX);
8272 
8273 		un->un_swr_token = token;
8274 		un->un_specified_mediastate = state;
8275 
8276 		/*
8277 		 * now wait for media change
8278 		 * we will not be signalled unless mediastate == state but it
8279 		 * still better to test for this condition, since there
8280 		 * is a 5 sec cv_broadcast delay when
8281 		 *  mediastate == MTIO_INSERTED
8282 		 */
8283 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8284 			"st_check_media:waiting for media state change\n");
8285 		while (un->un_mediastate == state) {
8286 			if (cv_wait_sig(&un->un_state_cv, ST_MUTEX) == 0) {
8287 				mutex_exit(ST_MUTEX);
8288 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8289 				    "st_check_media:waiting for media state "
8290 				    "was interrupted\n");
8291 				rval = EINTR;
8292 				goto done;
8293 			}
8294 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8295 			    "st_check_media:received signal, state=%x\n",
8296 			    un->un_mediastate);
8297 		}
8298 	}
8299 
8300 	/*
8301 	 * if we transitioned to MTIO_INSERTED, media has really been
8302 	 * inserted.  If TUR fails, it is probably a exabyte slow spin up.
8303 	 * Reset and retry the state change.  If everything is ok, replay
8304 	 * the open() logic.
8305 	 */
8306 	if ((un->un_mediastate == MTIO_INSERTED) &&
8307 	    (un->un_state == ST_STATE_OFFLINE)) {
8308 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8309 		    "st_check_media: calling st_cmd to confirm inserted\n");
8310 
8311 		/*
8312 		 * set this early so that TUR will make it through strategy
8313 		 * without triggering a st_tape_init().  We needed it set
8314 		 * before calling st_tape_init() ourselves anyway.  If TUR
8315 		 * fails, set it back
8316 		 */
8317 		un->un_state = ST_STATE_INITIALIZING;
8318 		/*
8319 		 * If we haven't done/checked reservation on the
8320 		 * tape unit do it now.
8321 		 */
8322 		if (ST_RESERVE_SUPPORTED(un) &&
8323 			!(un->un_rsvd_status & ST_INIT_RESERVE)) {
8324 				if (rval = st_tape_reservation_init(dev)) {
8325 					mutex_exit(ST_MUTEX);
8326 					goto done;
8327 				}
8328 		}
8329 
8330 		if (st_cmd(dev, SCMD_TEST_UNIT_READY, 0, SYNC_CMD)) {
8331 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8332 			    "st_check_media: TUR failed, going to retry\n");
8333 			un->un_mediastate = prev_state;
8334 			un->un_state = ST_STATE_OFFLINE;
8335 			goto retry;
8336 		}
8337 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8338 		    "st_check_media: media inserted\n");
8339 
8340 		/* this also rewinds the tape */
8341 		rval = st_tape_init(dev);
8342 		if (rval != 0) {
8343 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8344 			    "st_check_media : OFFLINE init failure ");
8345 			un->un_state = ST_STATE_OFFLINE;
8346 			un->un_fileno = -1;
8347 		} else {
8348 			un->un_state = ST_STATE_OPEN_PENDING_IO;
8349 			un->un_fileno = 0;
8350 			un->un_blkno = 0;
8351 		}
8352 	} else if ((un->un_mediastate == MTIO_EJECTED) &&
8353 		(un->un_state != ST_STATE_OFFLINE)) {
8354 		/*
8355 		 * supported devices must be rewound before ejection
8356 		 * rewind resets fileno & blkno
8357 		 */
8358 		un->un_laststate = un->un_state;
8359 		un->un_state = ST_STATE_OFFLINE;
8360 	}
8361 	mutex_exit(ST_MUTEX);
8362 done:
8363 	if (token) {
8364 		(void) scsi_watch_request_terminate(token,
8365 				SCSI_WATCH_TERMINATE_WAIT);
8366 		mutex_enter(ST_MUTEX);
8367 		un->un_swr_token = (opaque_t)NULL;
8368 		mutex_exit(ST_MUTEX);
8369 	}
8370 
8371 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_media: done\n");
8372 
8373 	return (rval);
8374 }
8375 
8376 /*
8377  * st_media_watch_cb() is called by scsi_watch_thread for
8378  * verifying the request sense data (if any)
8379  */
8380 static int
8381 st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
8382 {
8383 	struct scsi_status *statusp = resultp->statusp;
8384 	struct scsi_extended_sense *sensep = resultp->sensep;
8385 	uchar_t actual_sense_length = resultp->actual_sense_length;
8386 	struct scsi_tape *un;
8387 	enum mtio_state state = MTIO_NONE;
8388 	int instance;
8389 	dev_t dev = (dev_t)arg;
8390 
8391 	instance = MTUNIT(dev);
8392 	if ((un = ddi_get_soft_state(st_state, instance)) == NULL) {
8393 		return (-1);
8394 	}
8395 
8396 	mutex_enter(ST_MUTEX);
8397 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8398 		"st_media_watch_cb: status=%x, sensep=%p, len=%x\n",
8399 			*((char *)statusp), (void *)sensep,
8400 			actual_sense_length);
8401 
8402 	/*
8403 	 * if there was a check condition then sensep points to valid
8404 	 * sense data
8405 	 * if status was not a check condition but a reservation or busy
8406 	 * status then the new state is MTIO_NONE
8407 	 */
8408 	if (sensep) {
8409 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8410 		    "st_media_watch_cb: KEY=%x, ASC=%x, ASCQ=%x\n",
8411 		    sensep->es_key, sensep->es_add_code, sensep->es_qual_code);
8412 
8413 		switch (un->un_dp->type) {
8414 		default:
8415 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8416 	    "st_media_watch_cb: unknown drive type %d, default to ST_TYPE_HP\n",
8417 	    un->un_dp->type);
8418 		/* FALLTHROUGH */
8419 
8420 		case ST_TYPE_STC3490:	/* STK 4220 1/2" cartridge */
8421 		case ST_TYPE_FUJI:	/* 1/2" cartridge */
8422 		case ST_TYPE_HP:	/* HP 88780 1/2" reel */
8423 			if (un->un_dp->type == ST_TYPE_FUJI) {
8424 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8425 				    "st_media_watch_cb: ST_TYPE_FUJI\n");
8426 			} else {
8427 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8428 				    "st_media_watch_cb: ST_TYPE_HP\n");
8429 			}
8430 			switch (sensep->es_key) {
8431 			case KEY_UNIT_ATTENTION:
8432 				/* not ready to ready transition */
8433 				/* hp/es_qual_code == 80 on>off>on */
8434 				/* hp/es_qual_code == 0 on>off>unld>ld>on */
8435 				if (sensep->es_add_code == 0x28) {
8436 					state = MTIO_INSERTED;
8437 				}
8438 				break;
8439 			case KEY_NOT_READY:
8440 				/* in process, rewinding or loading */
8441 				if ((sensep->es_add_code == 0x04) &&
8442 				    (sensep->es_qual_code == 0x00)) {
8443 					state = MTIO_EJECTED;
8444 				}
8445 				break;
8446 			}
8447 			break;
8448 
8449 		case ST_TYPE_EXB8500:	/* Exabyte 8500 */
8450 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8451 			    "st_media_watch_cb: ST_TYPE_EXB8500\n");
8452 			switch (sensep->es_key) {
8453 			case KEY_UNIT_ATTENTION:
8454 				/* operator medium removal request */
8455 				if ((sensep->es_add_code == 0x5a) &&
8456 				    (sensep->es_qual_code == 0x01)) {
8457 					state = MTIO_EJECTED;
8458 				/* not ready to ready transition */
8459 				} else if ((sensep->es_add_code == 0x28) &&
8460 				    (sensep->es_qual_code == 0x00)) {
8461 					state = MTIO_INSERTED;
8462 				}
8463 				break;
8464 			case KEY_NOT_READY:
8465 				/* medium not present */
8466 				if (sensep->es_add_code == 0x3a) {
8467 					state = MTIO_EJECTED;
8468 				}
8469 				break;
8470 			}
8471 			break;
8472 		case ST_TYPE_EXABYTE:	/* Exabyte 8200 */
8473 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8474 			    "st_media_watch_cb: ST_TYPE_EXABYTE\n");
8475 			switch (sensep->es_key) {
8476 			case KEY_NOT_READY:
8477 				if ((sensep->es_add_code == 0x04) &&
8478 				    (sensep->es_qual_code == 0x00)) {
8479 					/* volume not mounted? */
8480 					state = MTIO_EJECTED;
8481 				} else if (sensep->es_add_code == 0x3a) {
8482 					state = MTIO_EJECTED;
8483 				}
8484 				break;
8485 			case KEY_UNIT_ATTENTION:
8486 				state = MTIO_EJECTED;
8487 				break;
8488 			}
8489 			break;
8490 
8491 		case ST_TYPE_DLT:		/* quantum DLT4xxx */
8492 			switch (sensep->es_key) {
8493 			case KEY_UNIT_ATTENTION:
8494 				if (sensep->es_add_code == 0x28) {
8495 					state = MTIO_INSERTED;
8496 				}
8497 				break;
8498 			case KEY_NOT_READY:
8499 				if (sensep->es_add_code == 0x04) {
8500 					/* in transition but could be either */
8501 					state = un->un_specified_mediastate;
8502 				} else if ((sensep->es_add_code == 0x3a) &&
8503 				    (sensep->es_qual_code == 0x00)) {
8504 					state = MTIO_EJECTED;
8505 				}
8506 				break;
8507 			}
8508 			break;
8509 		}
8510 	} else if (*((char *)statusp) == STATUS_GOOD) {
8511 		state = MTIO_INSERTED;
8512 	}
8513 
8514 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8515 		"st_media_watch_cb:state=%x, specified=%x\n",
8516 		state, un->un_specified_mediastate);
8517 
8518 	/*
8519 	 * now signal the waiting thread if this is *not* the specified state;
8520 	 * delay the signal if the state is MTIO_INSERTED
8521 	 * to allow the target to recover
8522 	 */
8523 	if (state != un->un_specified_mediastate) {
8524 		un->un_mediastate = state;
8525 		if (state == MTIO_INSERTED) {
8526 			/*
8527 			 * delay the signal to give the drive a chance
8528 			 * to do what it apparently needs to do
8529 			 */
8530 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8531 			    "st_media_watch_cb:delayed cv_broadcast\n");
8532 			un->un_delay_tid = timeout(st_delayed_cv_broadcast,
8533 			    un, drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
8534 		} else {
8535 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8536 				"st_media_watch_cb:immediate cv_broadcast\n");
8537 			cv_broadcast(&un->un_state_cv);
8538 		}
8539 	}
8540 	mutex_exit(ST_MUTEX);
8541 	return (0);
8542 }
8543 
8544 /*
8545  * delayed cv_broadcast to allow for target to recover
8546  * from media insertion
8547  */
8548 static void
8549 st_delayed_cv_broadcast(void *arg)
8550 {
8551 	struct scsi_tape *un = arg;
8552 
8553 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8554 		"st_delayed_cv_broadcast:delayed cv_broadcast\n");
8555 
8556 	mutex_enter(ST_MUTEX);
8557 	cv_broadcast(&un->un_state_cv);
8558 	mutex_exit(ST_MUTEX);
8559 }
8560 
8561 /*
8562  * restart cmd currently at the start of the waitq
8563  */
8564 static void
8565 st_start_restart(void *arg)
8566 {
8567 	struct scsi_tape *un = arg;
8568 
8569 	ASSERT(un != NULL);
8570 
8571 	mutex_enter(ST_MUTEX);
8572 
8573 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8574 		"st_tran_restart()\n");
8575 
8576 	if (un->un_quef) {
8577 		st_start(un);
8578 	}
8579 
8580 	mutex_exit(ST_MUTEX);
8581 }
8582 
8583 
8584 /*
8585  * Command completion processing
8586  *
8587  */
8588 static void
8589 st_intr(struct scsi_pkt *pkt)
8590 {
8591 	struct scsi_tape *un;
8592 	struct buf *last_runqf;
8593 	struct buf *bp;
8594 	int action = COMMAND_DONE;
8595 	clock_t	timout;
8596 	int	status;
8597 
8598 	bp = (struct buf *)pkt->pkt_private;
8599 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
8600 
8601 	mutex_enter(ST_MUTEX);
8602 
8603 	un->un_rqs_state &= ~(ST_RQS_ERROR);
8604 
8605 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_intr()\n");
8606 
8607 	if (pkt->pkt_reason != CMD_CMPLT) {
8608 
8609 		/* If device has gone away not much else to do */
8610 		if (pkt->pkt_reason == CMD_DEV_GONE) {
8611 			action = COMMAND_DONE_ERROR;
8612 		} else if (un->un_state == ST_STATE_SENSING) {
8613 			ST_DO_ERRSTATS(un, st_transerrs);
8614 			action = COMMAND_DONE_ERROR;
8615 		} else {
8616 			action = st_handle_incomplete(un, bp);
8617 		}
8618 	/*
8619 	 * At this point we know that the command was successfully
8620 	 * completed. Now what?
8621 	 */
8622 	} else if (un->un_arq_enabled &&
8623 	    (pkt->pkt_state & STATE_ARQ_DONE)) {
8624 		/*
8625 		 * the transport layer successfully completed an autorqsense
8626 		 */
8627 		action = st_handle_autosense(un, bp);
8628 
8629 	} else if (un->un_state == ST_STATE_SENSING) {
8630 		/*
8631 		 * okay. We were running a REQUEST SENSE. Find
8632 		 * out what to do next.
8633 		 * some actions are based on un_state, hence
8634 		 * restore the state st was in before ST_STATE_SENSING.
8635 		 */
8636 		un->un_state = un->un_laststate;
8637 		action = st_handle_sense(un, bp);
8638 		/*
8639 		 * set pkt back to original packet in case we will have
8640 		 * to requeue it
8641 		 */
8642 		pkt = BP_PKT(bp);
8643 	} else  if ((SCBP(pkt)->sts_busy) || (SCBP(pkt)->sts_chk)) {
8644 		/*
8645 		 * Okay, we weren't running a REQUEST SENSE. Call a routine
8646 		 * to see if the status bits we're okay. If a request sense
8647 		 * is to be run, that will happen.
8648 		 */
8649 		action = st_check_error(un, pkt);
8650 	}
8651 
8652 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
8653 		switch (action) {
8654 			case QUE_COMMAND:
8655 				/*
8656 				 * return cmd to head to the queue
8657 				 * since we are suspending so that
8658 				 * it gets restarted during resume
8659 				 */
8660 				if (un->un_runqf) {
8661 					last_runqf = un->un_runqf;
8662 					un->un_runqf = bp;
8663 					bp->b_actf = last_runqf;
8664 				} else {
8665 					bp->b_actf = NULL;
8666 					un->un_runqf = bp;
8667 					un->un_runql = bp;
8668 				}
8669 				action = JUST_RETURN;
8670 				break;
8671 
8672 			case QUE_SENSE:
8673 				action = COMMAND_DONE_ERROR;
8674 				break;
8675 
8676 			default:
8677 				break;
8678 		}
8679 	}
8680 
8681 	/*
8682 	 * Restore old state if we were sensing.
8683 	 */
8684 	if (un->un_state == ST_STATE_SENSING && action != QUE_SENSE) {
8685 		un->un_state = un->un_laststate;
8686 	}
8687 
8688 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8689 	    "st_intr: pkt=%p, bp=%p, action=%x, status=%x\n",
8690 	    (void *)pkt, (void *)bp, action, SCBP_C(pkt));
8691 
8692 
8693 	switch (action) {
8694 	case COMMAND_DONE_EACCES:
8695 		/* this is to report a reservation conflict */
8696 		st_bioerror(bp, EACCES);
8697 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8698 			"Reservation Conflict \n");
8699 
8700 		/*FALLTHROUGH*/
8701 	case COMMAND_DONE_ERROR:
8702 		if (un->un_eof < ST_EOT_PENDING &&
8703 		    un->un_state >= ST_STATE_OPEN) {
8704 			/*
8705 			 * all errors set state of the tape to 'unknown'
8706 			 * unless we're at EOT or are doing append testing.
8707 			 * If sense key was illegal request, preserve state.
8708 			 */
8709 			if (un->un_status != KEY_ILLEGAL_REQUEST) {
8710 				un->un_fileno = -1;
8711 			}
8712 		}
8713 		un->un_err_resid = bp->b_resid = bp->b_bcount;
8714 		/*
8715 		 * since we have an error (COMMAND_DONE_ERROR), we want to
8716 		 * make sure an error ocurrs, so make sure at least EIO is
8717 		 * returned
8718 		 */
8719 		if (geterror(bp) == 0)
8720 			st_bioerror(bp, EIO);
8721 
8722 		SET_PE_FLAG(un);
8723 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
8724 		    (un->un_errno == EIO)) {
8725 			un->un_rqs_state &= ~(ST_RQS_VALID);
8726 		}
8727 		goto done;
8728 
8729 	case COMMAND_DONE_ERROR_RECOVERED:
8730 		un->un_err_resid = bp->b_resid = bp->b_bcount;
8731 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
8732 		    "st_intr(): COMMAND_DONE_ERROR_RECOVERED");
8733 		if (geterror(bp) == 0)
8734 			st_bioerror(bp, EIO);
8735 		SET_PE_FLAG(un);
8736 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
8737 		    (un->un_errno == EIO)) {
8738 			un->un_rqs_state &= ~(ST_RQS_VALID);
8739 		}
8740 		/*FALLTHROUGH*/
8741 	case COMMAND_DONE:
8742 		st_set_state(un);
8743 done:
8744 		ST_DO_KSTATS(bp, kstat_runq_exit);
8745 		st_done_and_mutex_exit(un, bp);
8746 		return;
8747 
8748 	case QUE_SENSE:
8749 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors)
8750 			goto sense_error;
8751 
8752 		if (un->un_state != ST_STATE_SENSING) {
8753 			un->un_laststate = un->un_state;
8754 			un->un_state = ST_STATE_SENSING;
8755 		}
8756 
8757 		un->un_rqs->pkt_private = (opaque_t)bp;
8758 		bzero(ST_RQSENSE, SENSE_LENGTH);
8759 
8760 		if (un->un_throttle) {
8761 			un->un_last_throttle = un->un_throttle;
8762 			un->un_throttle = 0;
8763 		}
8764 
8765 		mutex_exit(ST_MUTEX);
8766 
8767 		/*
8768 		 * never retry this, some other command will have nuked the
8769 		 * sense, anyway
8770 		 */
8771 		status = scsi_transport(un->un_rqs);
8772 
8773 		mutex_enter(ST_MUTEX);
8774 
8775 		if (un->un_last_throttle) {
8776 			un->un_throttle = un->un_last_throttle;
8777 		}
8778 
8779 		if (status == TRAN_ACCEPT) {
8780 			mutex_exit(ST_MUTEX);
8781 			return;
8782 		}
8783 		if (status != TRAN_BUSY)
8784 			ST_DO_ERRSTATS(un, st_transerrs);
8785 sense_error:
8786 		un->un_fileno = -1;
8787 		st_bioerror(bp, EIO);
8788 		SET_PE_FLAG(un);
8789 		goto done;
8790 
8791 	case QUE_BUSY_COMMAND:
8792 		/* longish timeout */
8793 		timout = ST_STATUS_BUSY_TIMEOUT;
8794 		goto que_it_up;
8795 
8796 	case QUE_COMMAND:
8797 		/* short timeout */
8798 		timout = ST_TRAN_BUSY_TIMEOUT;
8799 que_it_up:
8800 		/*
8801 		 * let st_handle_intr_busy put this bp back on waitq and make
8802 		 * checks to see if it is ok to requeue the command.
8803 		 */
8804 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
8805 
8806 		/*
8807 		 * Save the throttle before setting up the timeout
8808 		 */
8809 		if (un->un_throttle) {
8810 			un->un_last_throttle = un->un_throttle;
8811 		}
8812 		mutex_exit(ST_MUTEX);
8813 		if (st_handle_intr_busy(un, bp, timout) == 0)
8814 			return;		/* timeout is setup again */
8815 
8816 		mutex_enter(ST_MUTEX);
8817 		un->un_fileno = -1;
8818 		un->un_err_resid = bp->b_resid = bp->b_bcount;
8819 		st_bioerror(bp, EIO);
8820 		SET_PE_FLAG(un);
8821 		goto done;
8822 
8823 	case QUE_LAST_COMMAND:
8824 
8825 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors) {
8826 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
8827 			    "un_ncmds: %d can't retry cmd \n", un->un_ncmds);
8828 			goto last_command_error;
8829 		}
8830 		mutex_exit(ST_MUTEX);
8831 		if (st_handle_intr_retry_lcmd(un, bp) == 0)
8832 			return;
8833 		mutex_enter(ST_MUTEX);
8834 last_command_error:
8835 		un->un_err_resid = bp->b_resid = bp->b_bcount;
8836 		un->un_fileno = -1;
8837 		st_bioerror(bp, EIO);
8838 		SET_PE_FLAG(un);
8839 		goto done;
8840 
8841 	case JUST_RETURN:
8842 	default:
8843 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
8844 		mutex_exit(ST_MUTEX);
8845 		return;
8846 	}
8847 	/*NOTREACHED*/
8848 }
8849 
8850 static int
8851 st_handle_incomplete(struct scsi_tape *un, struct buf *bp)
8852 {
8853 	static char *fail = "SCSI transport failed: reason '%s': %s\n";
8854 	int rval = COMMAND_DONE_ERROR;
8855 	struct scsi_pkt *pkt = (un->un_state == ST_STATE_SENSING) ?
8856 			un->un_rqs : BP_PKT(bp);
8857 	int result;
8858 
8859 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8860 		"st_handle_incomplete(): dev = 0x%lx\n", un->un_dev);
8861 
8862 	ASSERT(mutex_owned(ST_MUTEX));
8863 
8864 	switch (pkt->pkt_reason) {
8865 	case CMD_INCOMPLETE:	/* tran stopped with not normal state */
8866 		/*
8867 		 * this occurs when accessing a powered down drive, no
8868 		 * need to complain; just fail the open
8869 		 */
8870 #ifdef STDEBUG
8871 		if (st_debug >= 1) {
8872 			st_clean_print(ST_DEVINFO, st_label, CE_WARN,
8873 			    "Failed CDB", (char *)pkt->pkt_cdbp, CDB_SIZE);
8874 		}
8875 
8876 #endif
8877 		/*
8878 		 * if we have commands outstanding in HBA, and a command
8879 		 * comes back incomplete, we're hosed, so reset target
8880 		 * If we have the bus, but cmd_incomplete, we probably just
8881 		 * have a failed selection, so don't reset the target, just
8882 		 * requeue the command and try again
8883 		 */
8884 		if ((un->un_ncmds > 1) || (pkt->pkt_state != STATE_GOT_BUS)) {
8885 			goto reset_target;
8886 		}
8887 
8888 		/*
8889 		 * Retry selection a couple more times if we're
8890 		 * open.  If opening, we only try just once to
8891 		 * reduce probe time for nonexistant devices.
8892 		 */
8893 		if ((un->un_laststate > ST_STATE_OPENING) &&
8894 		    ((int)un->un_retry_ct < st_selection_retry_count)) {
8895 			rval = QUE_COMMAND;
8896 		}
8897 		ST_DO_ERRSTATS(un, st_transerrs);
8898 		break;
8899 
8900 	case CMD_ABORTED:
8901 		/*
8902 		 * most likely this is caused by flush-on-error support. If
8903 		 * it was not there, the we're in trouble.
8904 		 */
8905 		if (!un->un_flush_on_errors) {
8906 			un->un_status = SUN_KEY_FATAL;
8907 			goto reset_target;
8908 		}
8909 
8910 		st_set_pe_errno(un);
8911 		bioerror(bp, un->un_errno);
8912 		if (un->un_errno)
8913 			return (COMMAND_DONE_ERROR);
8914 		else
8915 			return (COMMAND_DONE);
8916 
8917 	case CMD_TIMEOUT:	/* Command timed out */
8918 		un->un_status = SUN_KEY_TIMEOUT;
8919 
8920 		/*FALLTHROUGH*/
8921 	default:
8922 reset_target:
8923 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8924 		    "transport completed with %s\n",
8925 		    scsi_rname(pkt->pkt_reason));
8926 		ST_DO_ERRSTATS(un, st_transerrs);
8927 		if ((pkt->pkt_state & STATE_GOT_TARGET) &&
8928 		    ((pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET |
8929 			STAT_ABORTED)) == 0)) {
8930 
8931 			mutex_exit(ST_MUTEX);
8932 
8933 			result = scsi_reset(ROUTE, RESET_TARGET);
8934 			/*
8935 			 * if target reset fails, then pull the chain
8936 			 */
8937 			if (result == 0) {
8938 				result = scsi_reset(ROUTE, RESET_ALL);
8939 			}
8940 			mutex_enter(ST_MUTEX);
8941 
8942 			if ((result == 0) && (un->un_state >= ST_STATE_OPEN)) {
8943 				/* no hope left to recover */
8944 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
8945 				    "recovery by resets failed\n");
8946 				return (rval);
8947 			}
8948 		}
8949 	}
8950 
8951 	if ((pkt->pkt_reason == CMD_RESET) || (pkt->pkt_statistics &
8952 		(STAT_BUS_RESET | STAT_DEV_RESET))) {
8953 		if ((un->un_rsvd_status & ST_RESERVE)) {
8954 			un->un_rsvd_status |= ST_LOST_RESERVE;
8955 			ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8956 				"Lost Reservation\n");
8957 		}
8958 	}
8959 
8960 	if ((int)un->un_retry_ct++ < st_retry_count) {
8961 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
8962 			rval = QUE_COMMAND;
8963 		} else if (bp == un->un_sbufp) {
8964 			switch ((uchar_t)(uintptr_t)bp->b_forw) {
8965 			case SCMD_MODE_SENSE:
8966 			case SCMD_MODE_SELECT:
8967 			case SCMD_READ_BLKLIM:
8968 			case SCMD_REWIND:
8969 			case SCMD_LOAD:
8970 			case SCMD_TEST_UNIT_READY:
8971 				/*
8972 				 * These commands can be rerun with impunity
8973 				 */
8974 				rval = QUE_COMMAND;
8975 				break;
8976 
8977 			default:
8978 				break;
8979 			}
8980 		}
8981 	} else {
8982 		rval = COMMAND_DONE_ERROR;
8983 	}
8984 
8985 	if (un->un_state >= ST_STATE_OPEN) {
8986 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
8987 		    fail, scsi_rname(pkt->pkt_reason),
8988 		    (rval == COMMAND_DONE_ERROR)?
8989 		    "giving up" : "retrying command");
8990 	}
8991 	return (rval);
8992 }
8993 
8994 /*
8995  * if the device is busy, then put this bp back on the waitq, on the
8996  * interrupt thread, where we want the head of the queue and not the
8997  * end
8998  *
8999  * The callers of this routine should take measures to save the
9000  * un_throttle in un_last_throttle which will be restored in
9001  * st_intr_restart(). The only exception should be st_intr_restart()
9002  * calling this routine for which the saving is already done.
9003  */
9004 static int
9005 st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
9006 	clock_t timeout_interval)
9007 {
9008 	struct buf *last_quef;
9009 	int rval = 0;
9010 
9011 	mutex_enter(ST_MUTEX);
9012 
9013 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9014 	    "st_handle_intr_busy(), un = 0x%p\n", (void *)un);
9015 
9016 	/*
9017 	 * Check to see if we hit the retry timeout. We check to make sure
9018 	 * this is the first one on the runq and make sure we have not
9019 	 * queued up any more, so this one has to be the last on the list
9020 	 * also. If it is not, we have to fail.  If it is not the first, but
9021 	 * is the last we are in trouble anyway, as we are in the interrupt
9022 	 * context here.
9023 	 */
9024 	if (((int)un->un_tran_retry_ct++ > st_retry_count) ||
9025 	    ((un->un_runqf != bp) && (un->un_runql != bp))) {
9026 		rval = -1;
9027 		goto exit;
9028 	}
9029 
9030 	/* put the bp back on the waitq */
9031 	if (un->un_quef) {
9032 		last_quef = un->un_quef;
9033 		un->un_quef = bp;
9034 		bp->b_actf = last_quef;
9035 	} else  {
9036 		bp->b_actf = NULL;
9037 		un->un_quef = bp;
9038 		un->un_quel = bp;
9039 	}
9040 
9041 	/*
9042 	 * We know that this is the first and last on the runq at this time,
9043 	 * so we just nullify those two queues
9044 	 */
9045 	un->un_runqf = NULL;
9046 	un->un_runql = NULL;
9047 
9048 	/*
9049 	 * We don't want any other commands being started in the mean time.
9050 	 * If start had just released mutex after putting something on the
9051 	 * runq, we won't even get here.
9052 	 */
9053 	un->un_throttle = 0;
9054 
9055 	/*
9056 	 * send a marker pkt, if appropriate
9057 	 */
9058 	st_hba_unflush(un);
9059 
9060 	/*
9061 	 * all queues are aligned, we are just waiting to
9062 	 * transport
9063 	 */
9064 	un->un_hib_tid = timeout(st_intr_restart, un, timeout_interval);
9065 
9066 exit:
9067 	mutex_exit(ST_MUTEX);
9068 	return (rval);
9069 }
9070 
9071 static int
9072 st_handle_sense(struct scsi_tape *un, struct buf *bp)
9073 {
9074 	struct scsi_pkt *rqpkt = un->un_rqs;
9075 	int rval = COMMAND_DONE_ERROR;
9076 	int amt;
9077 
9078 	ASSERT(mutex_owned(ST_MUTEX));
9079 
9080 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9081 		"st_handle_sense()\n");
9082 
9083 	if (SCBP(rqpkt)->sts_busy) {
9084 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
9085 		    "busy unit on request sense\n");
9086 		if ((int)un->un_retry_ct++ < st_retry_count) {
9087 			rval = QUE_BUSY_COMMAND;
9088 		}
9089 		return (rval);
9090 	} else if (SCBP(rqpkt)->sts_chk) {
9091 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9092 		    "Check Condition on REQUEST SENSE\n");
9093 		return (rval);
9094 	}
9095 
9096 	/* was there enough data? */
9097 	amt = (int)SENSE_LENGTH - rqpkt->pkt_resid;
9098 	if ((rqpkt->pkt_state & STATE_XFERRED_DATA) == 0 ||
9099 	    (amt < SUN_MIN_SENSE_LENGTH)) {
9100 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9101 		    "REQUEST SENSE couldn't get sense data\n");
9102 		return (rval);
9103 	}
9104 	return (st_decode_sense(un, bp, amt, SCBP(rqpkt)));
9105 }
9106 
9107 static int
9108 st_handle_autosense(struct scsi_tape *un, struct buf *bp)
9109 {
9110 	struct scsi_pkt *pkt = BP_PKT(bp);
9111 	struct scsi_arq_status *arqstat =
9112 	    (struct scsi_arq_status *)pkt->pkt_scbp;
9113 	int rval = COMMAND_DONE_ERROR;
9114 	int amt;
9115 
9116 	ASSERT(mutex_owned(ST_MUTEX));
9117 
9118 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9119 		"st_handle_autosense()\n");
9120 
9121 	if (arqstat->sts_rqpkt_status.sts_busy) {
9122 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
9123 		    "busy unit on request sense\n");
9124 		/*
9125 		 * we return QUE_SENSE so st_intr will setup the SENSE cmd.
9126 		 * the disadvantage is that we do not have any delay for the
9127 		 * second retry of rqsense and we have to keep a packet around
9128 		 */
9129 		return (QUE_SENSE);
9130 
9131 	} else if (arqstat->sts_rqpkt_reason != CMD_CMPLT) {
9132 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9133 		    "transport error on REQUEST SENSE\n");
9134 		if ((arqstat->sts_rqpkt_state & STATE_GOT_TARGET) &&
9135 		    ((arqstat->sts_rqpkt_statistics &
9136 		    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) == 0)) {
9137 			mutex_exit(ST_MUTEX);
9138 			if (scsi_reset(ROUTE, RESET_TARGET) == 0) {
9139 				/*
9140 				 * if target reset fails, then pull the chain
9141 				 */
9142 				if (scsi_reset(ROUTE, RESET_ALL) == 0) {
9143 					ST_DEBUG6(ST_DEVINFO, st_label,
9144 					    CE_WARN,
9145 					    "recovery by resets failed\n");
9146 				}
9147 			}
9148 			mutex_enter(ST_MUTEX);
9149 		}
9150 		return (rval);
9151 
9152 	} else if (arqstat->sts_rqpkt_status.sts_chk) {
9153 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9154 		    "Check Condition on REQUEST SENSE\n");
9155 		return (rval);
9156 	}
9157 
9158 
9159 	/* was there enough data? */
9160 	amt = (int)SENSE_LENGTH - arqstat->sts_rqpkt_resid;
9161 	if ((arqstat->sts_rqpkt_state & STATE_XFERRED_DATA) == 0 ||
9162 	    (amt < SUN_MIN_SENSE_LENGTH)) {
9163 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9164 		    "REQUEST SENSE couldn't get sense data\n");
9165 		return (rval);
9166 	}
9167 
9168 	bcopy(&arqstat->sts_sensedata, ST_RQSENSE, SENSE_LENGTH);
9169 
9170 	return (st_decode_sense(un, bp, amt, &arqstat->sts_rqpkt_status));
9171 }
9172 
9173 static int
9174 st_decode_sense(struct scsi_tape *un, struct buf *bp,  int amt,
9175 	struct scsi_status *statusp)
9176 {
9177 	struct scsi_pkt *pkt = BP_PKT(bp);
9178 	int rval = COMMAND_DONE_ERROR;
9179 	long resid;
9180 	struct scsi_extended_sense *sensep = ST_RQSENSE;
9181 	int severity;
9182 	int get_error;
9183 
9184 	ASSERT(mutex_owned(ST_MUTEX));
9185 
9186 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9187 		"st_decode_sense()\n");
9188 
9189 	/*
9190 	 * For uscsi commands, squirrel away a copy of the
9191 	 * results of the Request Sense.
9192 	 */
9193 	if (USCSI_CMD(bp)) {
9194 		struct uscsi_cmd *ucmd = BP_UCMD(bp);
9195 		ucmd->uscsi_rqstatus = *(uchar_t *)statusp;
9196 		if (ucmd->uscsi_rqlen && un->un_srqbufp) {
9197 			uchar_t rqlen = min((uchar_t)amt, ucmd->uscsi_rqlen);
9198 			ucmd->uscsi_rqresid = ucmd->uscsi_rqlen - rqlen;
9199 			bcopy(ST_RQSENSE, un->un_srqbufp, rqlen);
9200 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9201 				"st_decode_sense: stat=0x%x resid=0x%x\n",
9202 				ucmd->uscsi_rqstatus, ucmd->uscsi_rqresid);
9203 		}
9204 	}
9205 
9206 	/*
9207 	 * If the drive is an MT-02, reposition the
9208 	 * secondary error code into the proper place.
9209 	 *
9210 	 * XXX	MT-02 is non-CCS tape, so secondary error code
9211 	 * is in byte 8.  However, in SCSI-2, tape has CCS definition
9212 	 * so it's in byte 12.
9213 	 */
9214 	if (un->un_dp->type == ST_TYPE_EMULEX) {
9215 		sensep->es_code = sensep->es_add_info[0];
9216 	}
9217 
9218 	/* for normal I/O check extract the resid values. */
9219 	if (bp != un->un_sbufp) {
9220 		if (sensep->es_valid) {
9221 			resid = (sensep->es_info_1 << 24) |
9222 				(sensep->es_info_2 << 16) |
9223 				(sensep->es_info_3 << 8)  |
9224 				(sensep->es_info_4);
9225 			if (un->un_bsize) {
9226 				resid *= un->un_bsize;
9227 			}
9228 		} else if (pkt->pkt_state & STATE_XFERRED_DATA) {
9229 			resid = pkt->pkt_resid;
9230 		} else {
9231 			resid = bp->b_bcount;
9232 		}
9233 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9234 		    "st_handle_sense (rw): xferred bit = %d, resid=%ld (%d), "
9235 		    "pkt_resid=%ld\n", pkt->pkt_state & STATE_XFERRED_DATA,
9236 		    resid,
9237 		    (sensep->es_info_1 << 24) |
9238 		    (sensep->es_info_2 << 16) |
9239 		    (sensep->es_info_3 << 8)  |
9240 		    (sensep->es_info_4),
9241 		    pkt->pkt_resid);
9242 		/*
9243 		 * The problem is, what should we believe?
9244 		 */
9245 		if (resid && (pkt->pkt_resid == 0)) {
9246 			pkt->pkt_resid = resid;
9247 		}
9248 	} else {
9249 		/*
9250 		 * If the command is SCMD_SPACE, we need to get the
9251 		 * residual as returned in the sense data, to adjust
9252 		 * our idea of current tape position correctly
9253 		 */
9254 		if ((CDBP(pkt)->scc_cmd == SCMD_SPACE ||
9255 		    CDBP(pkt)->scc_cmd == SCMD_WRITE_FILE_MARK) &&
9256 		    (sensep->es_valid)) {
9257 			resid = (sensep->es_info_1 << 24) |
9258 			    (sensep->es_info_2 << 16) |
9259 			    (sensep->es_info_3 << 8)  |
9260 			    (sensep->es_info_4);
9261 			bp->b_resid = resid;
9262 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9263 			    "st_handle_sense(other):	resid=%ld\n",
9264 			    resid);
9265 		} else {
9266 			/*
9267 			 * If the special command is SCMD_READ,
9268 			 * the correct resid will be set later.
9269 			 */
9270 			resid = bp->b_bcount;
9271 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9272 			    "st_handle_sense(special read):  resid=%ld\n",
9273 				resid);
9274 		}
9275 	}
9276 
9277 	if ((un->un_state >= ST_STATE_OPEN) &&
9278 	    (DEBUGGING || st_error_level == SCSI_ERR_ALL)) {
9279 		st_clean_print(ST_DEVINFO, st_label, CE_NOTE,
9280 		    "Failed CDB", (char *)pkt->pkt_cdbp, CDB_SIZE);
9281 		st_clean_print(ST_DEVINFO, st_label, CE_CONT,
9282 		    "sense data", (char *)sensep, amt);
9283 		scsi_log(ST_DEVINFO, st_label, CE_CONT,
9284 		    "count 0x%lx resid 0x%lx pktresid 0x%lx\n",
9285 		    bp->b_bcount, resid, pkt->pkt_resid);
9286 	}
9287 
9288 	switch (un->un_status = sensep->es_key) {
9289 	case KEY_NO_SENSE:
9290 		severity = SCSI_ERR_INFO;
9291 		goto common;
9292 
9293 	case KEY_RECOVERABLE_ERROR:
9294 		severity = SCSI_ERR_RECOVERED;
9295 		if ((sensep->es_class == CLASS_EXTENDED_SENSE) &&
9296 		    (sensep->es_code == ST_DEFERRED_ERROR)) {
9297 		    if (un->un_dp->options &
9298 			ST_RETRY_ON_RECOVERED_DEFERRED_ERROR) {
9299 			    rval = QUE_LAST_COMMAND;
9300 			    scsi_errmsg(ST_SCSI_DEVP, pkt, st_label, severity,
9301 				un->un_blkno, un->un_err_blkno, scsi_cmds,
9302 				sensep);
9303 			    scsi_log(ST_DEVINFO, st_label, CE_CONT,
9304 				"Command will be retried\n");
9305 			} else {
9306 			    severity = SCSI_ERR_FATAL;
9307 			    rval = COMMAND_DONE_ERROR_RECOVERED;
9308 			    ST_DO_ERRSTATS(un, st_softerrs);
9309 			    scsi_errmsg(ST_SCSI_DEVP, pkt, st_label, severity,
9310 				un->un_blkno, un->un_err_blkno, scsi_cmds,
9311 				sensep);
9312 			}
9313 			break;
9314 		}
9315 common:
9316 		/*
9317 		 * XXX only want reads to be stopped by filemarks.
9318 		 * Don't want them to be stopped by EOT.  EOT matters
9319 		 * only on write.
9320 		 */
9321 		if (sensep->es_filmk && !sensep->es_eom) {
9322 			rval = COMMAND_DONE;
9323 		} else if (sensep->es_eom) {
9324 			rval = COMMAND_DONE;
9325 		} else if (sensep->es_ili) {
9326 			/*
9327 			 * Fun with variable length record devices:
9328 			 * for specifying larger blocks sizes than the
9329 			 * actual physical record size.
9330 			 */
9331 			if (un->un_bsize == 0 && resid > 0) {
9332 				/*
9333 				 * XXX! Ugly.
9334 				 * The requested blocksize is > tape blocksize,
9335 				 * so this is ok, so we just return the
9336 				 * actual size xferred.
9337 				 */
9338 				pkt->pkt_resid = resid;
9339 				rval = COMMAND_DONE;
9340 			} else if (un->un_bsize == 0 && resid < 0) {
9341 				/*
9342 				 * The requested blocksize is < tape blocksize,
9343 				 * so this is not ok, so we err with ENOMEM
9344 				 */
9345 				rval = COMMAND_DONE_ERROR_RECOVERED;
9346 				st_bioerror(bp, ENOMEM);
9347 			} else {
9348 				ST_DO_ERRSTATS(un, st_softerrs);
9349 				severity = SCSI_ERR_FATAL;
9350 				rval = COMMAND_DONE_ERROR;
9351 				st_bioerror(bp, EINVAL);
9352 			}
9353 		} else {
9354 			/*
9355 			 * we hope and pray for this just being
9356 			 * something we can ignore (ie. a
9357 			 * truly recoverable soft error)
9358 			 */
9359 			rval = COMMAND_DONE;
9360 		}
9361 		if (sensep->es_filmk) {
9362 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9363 			    "filemark\n");
9364 			un->un_status = SUN_KEY_EOF;
9365 			un->un_eof = ST_EOF_PENDING;
9366 			SET_PE_FLAG(un);
9367 		}
9368 
9369 		/*
9370 		 * ignore eom when reading, a fmk should terminate reading
9371 		 */
9372 		if ((sensep->es_eom) &&
9373 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
9374 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "eom\n");
9375 			un->un_status = SUN_KEY_EOT;
9376 			un->un_eof = ST_EOM;
9377 			SET_PE_FLAG(un);
9378 		}
9379 
9380 		break;
9381 
9382 	case KEY_ILLEGAL_REQUEST:
9383 
9384 		if (un->un_laststate >= ST_STATE_OPEN) {
9385 			ST_DO_ERRSTATS(un, st_softerrs);
9386 			severity = SCSI_ERR_FATAL;
9387 		} else {
9388 			severity = SCSI_ERR_INFO;
9389 		}
9390 		break;
9391 
9392 	case KEY_MEDIUM_ERROR:
9393 		ST_DO_ERRSTATS(un, st_harderrs);
9394 		severity = SCSI_ERR_FATAL;
9395 
9396 		/*
9397 		 * for (buffered) writes, a medium error must be fatal
9398 		 */
9399 		if (CDBP(pkt)->scc_cmd != SCMD_WRITE) {
9400 			rval = COMMAND_DONE_ERROR_RECOVERED;
9401 		}
9402 
9403 check_keys:
9404 		/*
9405 		 * attempt to process the keys in the presence of
9406 		 * other errors
9407 		 */
9408 		if (sensep->es_ili && rval != COMMAND_DONE_ERROR) {
9409 			/*
9410 			 * Fun with variable length record devices:
9411 			 * for specifying larger blocks sizes than the
9412 			 * actual physical record size.
9413 			 */
9414 			if (un->un_bsize == 0 && resid > 0) {
9415 				/*
9416 				 * XXX! Ugly
9417 				 */
9418 				pkt->pkt_resid = resid;
9419 			} else if (un->un_bsize == 0 && resid < 0) {
9420 				st_bioerror(bp, EINVAL);
9421 			} else {
9422 				severity = SCSI_ERR_FATAL;
9423 				rval = COMMAND_DONE_ERROR;
9424 				st_bioerror(bp, EINVAL);
9425 			}
9426 		}
9427 		if (sensep->es_filmk) {
9428 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9429 			    "filemark\n");
9430 			un->un_status = SUN_KEY_EOF;
9431 			un->un_eof = ST_EOF_PENDING;
9432 			SET_PE_FLAG(un);
9433 		}
9434 
9435 		/*
9436 		 * ignore eom when reading, a fmk should terminate reading
9437 		 */
9438 		if ((sensep->es_eom) &&
9439 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
9440 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "eom\n");
9441 			un->un_status = SUN_KEY_EOT;
9442 			un->un_eof = ST_EOM;
9443 			SET_PE_FLAG(un);
9444 		}
9445 
9446 		break;
9447 
9448 	case KEY_VOLUME_OVERFLOW:
9449 		ST_DO_ERRSTATS(un, st_softerrs);
9450 		un->un_eof = ST_EOM;
9451 		severity = SCSI_ERR_FATAL;
9452 		rval = COMMAND_DONE_ERROR;
9453 		goto check_keys;
9454 
9455 	case KEY_HARDWARE_ERROR:
9456 		ST_DO_ERRSTATS(un, st_harderrs);
9457 		severity = SCSI_ERR_FATAL;
9458 		rval = COMMAND_DONE_ERROR;
9459 		if (un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE)
9460 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
9461 		break;
9462 
9463 	case KEY_BLANK_CHECK:
9464 		ST_DO_ERRSTATS(un, st_softerrs);
9465 		severity = SCSI_ERR_INFO;
9466 
9467 		/*
9468 		 * if not a special request and some data was xferred then it
9469 		 * it is not an error yet
9470 		 */
9471 		if (bp != un->un_sbufp && (bp->b_flags & B_READ)) {
9472 			/*
9473 			 * no error for read with or without data xferred
9474 			 */
9475 			un->un_status = SUN_KEY_EOT;
9476 			un->un_eof = ST_EOT;
9477 			rval = COMMAND_DONE_ERROR;
9478 			SET_PE_FLAG(un);
9479 			goto check_keys;
9480 		} else if (bp != un->un_sbufp &&
9481 		    (pkt->pkt_state & STATE_XFERRED_DATA)) {
9482 			rval = COMMAND_DONE;
9483 		} else {
9484 			rval = COMMAND_DONE_ERROR_RECOVERED;
9485 		}
9486 
9487 		if (un->un_laststate >= ST_STATE_OPEN) {
9488 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9489 			    "blank check\n");
9490 			un->un_eof = ST_EOM;
9491 		}
9492 		if ((CDBP(pkt)->scc_cmd == SCMD_SPACE) &&
9493 		    (un->un_dp->options & ST_KNOWS_EOD) &&
9494 		    (severity = SCSI_ERR_INFO)) {
9495 			/*
9496 			 * we were doing a fast forward by skipping
9497 			 * multiple fmk at the time
9498 			 */
9499 			st_bioerror(bp, EIO);
9500 			severity = SCSI_ERR_RECOVERED;
9501 			rval	 = COMMAND_DONE;
9502 		}
9503 		SET_PE_FLAG(un);
9504 		goto check_keys;
9505 
9506 	case KEY_WRITE_PROTECT:
9507 		if (st_wrongtapetype(un)) {
9508 			un->un_status = SUN_KEY_WRONGMEDIA;
9509 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9510 		"wrong tape for writing- use DC6150 tape (or equivalent)\n");
9511 			severity = SCSI_ERR_UNKNOWN;
9512 		} else {
9513 			severity = SCSI_ERR_FATAL;
9514 		}
9515 		ST_DO_ERRSTATS(un, st_harderrs);
9516 		rval = COMMAND_DONE_ERROR;
9517 		st_bioerror(bp, EACCES);
9518 		break;
9519 
9520 	case KEY_UNIT_ATTENTION:
9521 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9522 		    "KEY_UNIT_ATTENTION : un_state = %d\n", un->un_state);
9523 
9524 		/*
9525 		 * If we have detected a Bus Reset and the tape
9526 		 * drive has been reserved.
9527 		 */
9528 		if (ST_RQSENSE->es_add_code == 0x29 &&
9529 			(un->un_rsvd_status & ST_RESERVE)) {
9530 			un->un_rsvd_status |= ST_LOST_RESERVE;
9531 			ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
9532 				"st_decode_sense: Lost Reservation\n");
9533 		}
9534 
9535 		if (un->un_state <= ST_STATE_OPENING) {
9536 			/*
9537 			 * Look, the tape isn't open yet, now determine
9538 			 * if the cause is a BUS RESET, Save the file and
9539 			 * Block positions for the callers to recover from
9540 			 * the loss of position.
9541 			 */
9542 			if ((un->un_fileno >= 0) &&
9543 			(un->un_fileno || un->un_blkno)) {
9544 				if (ST_RQSENSE->es_add_code == 0x29) {
9545 					un->un_save_fileno = un->un_fileno;
9546 					un->un_save_blkno = un->un_blkno;
9547 					un->un_restore_pos = 1;
9548 				}
9549 			}
9550 
9551 			if ((int)un->un_retry_ct++ < st_retry_count) {
9552 				rval = QUE_COMMAND;
9553 			} else {
9554 				rval = COMMAND_DONE_ERROR;
9555 			}
9556 			severity = SCSI_ERR_INFO;
9557 
9558 		} else {
9559 			/*
9560 			 * Check if it is an Unexpected Unit Attention.
9561 			 * If state is >= ST_STATE_OPEN, we have
9562 			 * already done the initialization .
9563 			 * In this case it is Fatal Error
9564 			 * since no further reading/writing
9565 			 * can be done with fileno set to < 0.
9566 			 */
9567 			if (un->un_state >= ST_STATE_OPEN) {
9568 				ST_DO_ERRSTATS(un, st_harderrs);
9569 				severity = SCSI_ERR_FATAL;
9570 			} else {
9571 				severity = SCSI_ERR_INFO;
9572 			}
9573 			rval = COMMAND_DONE_ERROR;
9574 		}
9575 		un->un_fileno = -1;
9576 
9577 		break;
9578 
9579 	case KEY_NOT_READY:
9580 		/*
9581 		 * If in process of getting ready retry.
9582 		 */
9583 		if (sensep->es_add_code  == 0x04 &&
9584 		    sensep->es_qual_code == 0x01 &&
9585 		    un->un_retry_ct++ < st_retry_count) {
9586 			rval = QUE_COMMAND;
9587 			severity = SCSI_ERR_INFO;
9588 		} else {
9589 			/* give up */
9590 			rval = COMMAND_DONE_ERROR;
9591 			severity = SCSI_ERR_FATAL;
9592 		}
9593 
9594 		/*
9595 		 * If this was an error and after device opened
9596 		 * do error stats.
9597 		 */
9598 		if (rval == COMMAND_DONE_ERROR &&
9599 		    un->un_state > ST_STATE_OPENING) {
9600 			ST_DO_ERRSTATS(un, st_harderrs);
9601 		}
9602 
9603 		if (ST_RQSENSE->es_add_code == 0x3a) {
9604 			if (st_error_level >= SCSI_ERR_FATAL)
9605 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
9606 				    "Tape not inserted in drive\n");
9607 			un->un_mediastate = MTIO_EJECTED;
9608 			cv_broadcast(&un->un_state_cv);
9609 		}
9610 		if ((un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE) &&
9611 		    (rval != QUE_COMMAND))
9612 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
9613 		break;
9614 
9615 	case KEY_ABORTED_COMMAND:
9616 
9617 		/*
9618 		 * Probably a parity error...
9619 		 * if we retry here then this may cause data to be
9620 		 * written twice or data skipped during reading
9621 		 */
9622 		ST_DO_ERRSTATS(un, st_harderrs);
9623 		severity = SCSI_ERR_FATAL;
9624 		rval = COMMAND_DONE_ERROR;
9625 		goto check_keys;
9626 
9627 	default:
9628 		/*
9629 		 * Undecoded sense key.	 Try retries and hope
9630 		 * that will fix the problem.  Otherwise, we're
9631 		 * dead.
9632 		 */
9633 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9634 		    "Unhandled Sense Key '%s'\n",
9635 		    sense_keys[un->un_status]);
9636 		ST_DO_ERRSTATS(un, st_harderrs);
9637 		severity = SCSI_ERR_FATAL;
9638 		rval = COMMAND_DONE_ERROR;
9639 		goto check_keys;
9640 	}
9641 
9642 	if ((!(pkt->pkt_flags & FLAG_SILENT) &&
9643 	    un->un_state >= ST_STATE_OPEN) && (DEBUGGING ||
9644 		(un->un_laststate > ST_STATE_OPENING) &&
9645 		(severity >= st_error_level))) {
9646 
9647 		scsi_errmsg(ST_SCSI_DEVP, pkt, st_label, severity,
9648 		    un->un_blkno, un->un_err_blkno, scsi_cmds, sensep);
9649 		if (sensep->es_filmk) {
9650 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9651 			    "File Mark Detected\n");
9652 		}
9653 		if (sensep->es_eom) {
9654 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9655 			    "End-of-Media Detected\n");
9656 		}
9657 		if (sensep->es_ili) {
9658 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9659 			    "Incorrect Length Indicator Set\n");
9660 		}
9661 	}
9662 	get_error = geterror(bp);
9663 	if (((rval == COMMAND_DONE_ERROR) ||
9664 	    (rval == COMMAND_DONE_ERROR_RECOVERED)) &&
9665 	    ((get_error == EIO) || (get_error == 0))) {
9666 		un->un_rqs_state |= (ST_RQS_ERROR | ST_RQS_VALID);
9667 		bcopy(ST_RQSENSE, un->un_uscsi_rqs_buf, SENSE_LENGTH);
9668 		if (un->un_rqs_state & ST_RQS_READ) {
9669 		    un->un_rqs_state &= ~(ST_RQS_READ);
9670 		} else {
9671 		    un->un_rqs_state |= ST_RQS_OVR;
9672 		}
9673 	}
9674 
9675 	return (rval);
9676 }
9677 
9678 
9679 static int
9680 st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp)
9681 {
9682 	int status = TRAN_ACCEPT;
9683 
9684 	mutex_enter(ST_MUTEX);
9685 
9686 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9687 		"st_handle_intr_rtr_lcmd(), un = 0x%p\n", (void *)un);
9688 
9689 	/*
9690 	 * Check to see if we hit the retry timeout. We check to make sure
9691 	 * this is the first one on the runq and make sure we have not
9692 	 * queued up any more, so this one has to be the last on the list
9693 	 * also. If it is not, we have to fail.  If it is not the first, but
9694 	 * is the last we are in trouble anyway, as we are in the interrupt
9695 	 * context here.
9696 	 */
9697 	if (((int)un->un_retry_ct > st_retry_count) ||
9698 	    ((un->un_runqf != bp) && (un->un_runql != bp))) {
9699 	    goto exit;
9700 	}
9701 
9702 	if (un->un_throttle) {
9703 		un->un_last_throttle = un->un_throttle;
9704 		un->un_throttle = 0;
9705 	}
9706 
9707 	/*
9708 	 * Here we know : bp is the first and last one on the runq
9709 	 * it is not necessary to put it back on the head of the
9710 	 * waitq and then move from waitq to runq. Save this queuing
9711 	 * and call scsi_transport.
9712 	 */
9713 
9714 	mutex_exit(ST_MUTEX);
9715 
9716 	status = scsi_transport(BP_PKT(bp));
9717 
9718 	mutex_enter(ST_MUTEX);
9719 
9720 	if (status == TRAN_ACCEPT) {
9721 		un->un_tran_retry_ct = 0;
9722 		if (un->un_last_throttle) {
9723 			un->un_throttle = un->un_last_throttle;
9724 		}
9725 		mutex_exit(ST_MUTEX);
9726 
9727 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9728 		    "restart transport \n");
9729 		return (0);
9730 	}
9731 
9732 	ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9733 	mutex_exit(ST_MUTEX);
9734 
9735 	if (status == TRAN_BUSY) {
9736 	    if (st_handle_intr_busy(un, bp,
9737 		ST_TRAN_BUSY_TIMEOUT) == 0)
9738 		return (0);
9739 	}
9740 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9741 		"restart transport rejected\n");
9742 	mutex_enter(ST_MUTEX);
9743 	ST_DO_ERRSTATS(un, st_transerrs);
9744 	if (un->un_last_throttle) {
9745 		un->un_throttle = un->un_last_throttle;
9746 	}
9747 exit:
9748 	mutex_exit(ST_MUTEX);
9749 	return (-1);
9750 }
9751 
9752 static int
9753 st_wrongtapetype(struct scsi_tape *un)
9754 {
9755 
9756 	ASSERT(mutex_owned(ST_MUTEX));
9757 
9758 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9759 		"st_wrongtapetype()\n");
9760 
9761 	/*
9762 	 * Hack to handle  600A, 600XTD, 6150 && 660 vs. 300XL tapes...
9763 	 */
9764 	if (un->un_dp && (un->un_dp->options & ST_QIC) && un->un_mspl) {
9765 		switch (un->un_dp->type) {
9766 		case ST_TYPE_WANGTEK:
9767 		case ST_TYPE_ARCHIVE:
9768 			/*
9769 			 * If this really worked, we could go off of
9770 			 * the density codes set in the modesense
9771 			 * page. For this drive, 0x10 == QIC-120,
9772 			 * 0xf == QIC-150, and 0x5 should be for
9773 			 * both QIC-24 and, maybe, QIC-11. However,
9774 			 * the h/w doesn't do what the manual says
9775 			 * that it should, so we'll key off of
9776 			 * getting a WRITE PROTECT error AND wp *not*
9777 			 * set in the mode sense information.
9778 			 */
9779 			/*
9780 			 * XXX but we already know that status is
9781 			 * write protect, so don't check it again.
9782 			 */
9783 
9784 			if (un->un_status == KEY_WRITE_PROTECT &&
9785 			    un->un_mspl->wp == 0) {
9786 				return (1);
9787 			}
9788 			break;
9789 		default:
9790 			break;
9791 		}
9792 	}
9793 	return (0);
9794 }
9795 
9796 static int
9797 st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt)
9798 {
9799 	int action;
9800 
9801 	ASSERT(mutex_owned(ST_MUTEX));
9802 
9803 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_error()\n");
9804 
9805 	if (SCBP_C(pkt) == STATUS_RESERVATION_CONFLICT) {
9806 		action = COMMAND_DONE_EACCES;
9807 		un->un_rsvd_status |= ST_RESERVATION_CONFLICT;
9808 	} else if (SCBP(pkt)->sts_busy) {
9809 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG, "unit busy\n");
9810 		if ((int)un->un_retry_ct++ < st_retry_count) {
9811 			action = QUE_BUSY_COMMAND;
9812 		} else {
9813 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
9814 			    "unit busy too long\n");
9815 			mutex_exit(ST_MUTEX);
9816 			if (scsi_reset(ROUTE, RESET_TARGET) == 0) {
9817 				(void) scsi_reset(ROUTE, RESET_ALL);
9818 			}
9819 			mutex_enter(ST_MUTEX);
9820 			action = COMMAND_DONE_ERROR;
9821 		}
9822 	} else if (SCBP(pkt)->sts_chk) {
9823 		/*
9824 		 * we should only get here if the auto rqsense failed
9825 		 * thru a uscsi cmd without autorequest sense
9826 		 * so we just try again
9827 		 */
9828 		action = QUE_SENSE;
9829 	} else {
9830 		action = COMMAND_DONE;
9831 	}
9832 	return (action);
9833 }
9834 
9835 static void
9836 st_calc_bnum(struct scsi_tape *un, struct buf *bp)
9837 {
9838 	int n;
9839 
9840 	ASSERT(mutex_owned(ST_MUTEX));
9841 
9842 	if (un->un_bsize == 0) {
9843 		n = ((bp->b_bcount - bp->b_resid  == 0) ? 0 : 1);
9844 		un->un_kbytes_xferred += (bp->b_bcount - bp->b_resid)/1000;
9845 	} else {
9846 		n = ((bp->b_bcount - bp->b_resid) / un->un_bsize);
9847 	}
9848 	un->un_blkno += n;
9849 }
9850 
9851 static void
9852 st_set_state(struct scsi_tape *un)
9853 {
9854 	struct buf *bp = un->un_runqf;
9855 	struct scsi_pkt *sp = BP_PKT(bp);
9856 	struct uscsi_cmd *ucmd;
9857 
9858 	ASSERT(mutex_owned(ST_MUTEX));
9859 
9860 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9861 	    "st_set_state(): un_eof=%x	fmneeded=%x  pkt_resid=0x%lx (%ld)\n",
9862 		un->un_eof, un->un_fmneeded, sp->pkt_resid, sp->pkt_resid);
9863 
9864 	if (bp != un->un_sbufp) {
9865 #ifdef STDEBUG
9866 		if (DEBUGGING && sp->pkt_resid) {
9867 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9868 			    "pkt_resid %ld bcount %ld\n",
9869 			    sp->pkt_resid, bp->b_bcount);
9870 		}
9871 #endif
9872 		bp->b_resid = sp->pkt_resid;
9873 		st_calc_bnum(un, bp);
9874 		if (bp->b_flags & B_READ) {
9875 			un->un_lastop = ST_OP_READ;
9876 			un->un_fmneeded = 0;
9877 		} else {
9878 			un->un_lastop = ST_OP_WRITE;
9879 			if (un->un_dp->options & ST_REEL) {
9880 				un->un_fmneeded = 2;
9881 			} else {
9882 				un->un_fmneeded = 1;
9883 			}
9884 		}
9885 		/*
9886 		 * all is honky dory at this point, so let's
9887 		 * readjust the throttle, to increase speed, if we
9888 		 * have not throttled down.
9889 		 */
9890 		if (un->un_throttle)
9891 			un->un_throttle = un->un_max_throttle;
9892 	} else {
9893 		char saved_lastop = un->un_lastop;
9894 		uchar_t cmd = (uchar_t)(intptr_t)bp->b_forw;
9895 
9896 		un->un_lastop = ST_OP_CTL;
9897 
9898 		switch (cmd) {
9899 		case SCMD_WRITE:
9900 			bp->b_resid = sp->pkt_resid;
9901 			un->un_lastop = ST_OP_WRITE;
9902 			st_calc_bnum(un, bp);
9903 			if (un->un_dp->options & ST_REEL) {
9904 				un->un_fmneeded = 2;
9905 			} else {
9906 				un->un_fmneeded = 1;
9907 			}
9908 			break;
9909 		case SCMD_READ:
9910 			bp->b_resid = sp->pkt_resid;
9911 			un->un_lastop = ST_OP_READ;
9912 			st_calc_bnum(un, bp);
9913 			un->un_fmneeded = 0;
9914 			break;
9915 		case SCMD_WRITE_FILE_MARK:
9916 			if (un->un_eof != ST_EOM)
9917 				un->un_eof = ST_NO_EOF;
9918 			un->un_lastop = ST_OP_WEOF;
9919 			un->un_fileno += (bp->b_bcount - bp->b_resid);
9920 			un->un_blkno = 0;
9921 			if (un->un_dp->options & ST_REEL) {
9922 				un->un_fmneeded -=
9923 					(bp->b_bcount - bp->b_resid);
9924 				if (un->un_fmneeded < 0) {
9925 					un->un_fmneeded = 0;
9926 				}
9927 			} else {
9928 				un->un_fmneeded = 0;
9929 			}
9930 
9931 			break;
9932 		case SCMD_REWIND:
9933 			un->un_eof = ST_NO_EOF;
9934 			un->un_fileno = 0;
9935 			un->un_blkno = 0;
9936 			break;
9937 
9938 		case SCMD_SPACE:
9939 		{
9940 			int space_fmk, count;
9941 			long resid;
9942 
9943 			count = (int)space_cnt(bp->b_bcount);
9944 			resid = (long)space_cnt(bp->b_resid);
9945 			space_fmk = ((bp->b_bcount) & (1<<24)) ? 1 : 0;
9946 
9947 
9948 			if (count >= 0) {
9949 				if (space_fmk) {
9950 					if (un->un_eof <= ST_EOF) {
9951 						un->un_eof = ST_NO_EOF;
9952 					}
9953 					un->un_fileno += (count - resid);
9954 					un->un_blkno = 0;
9955 				} else {
9956 					un->un_blkno += count - resid;
9957 				}
9958 			} else if (count < 0) {
9959 				if (space_fmk) {
9960 					un->un_fileno -=
9961 					    ((-count) - resid);
9962 					if (un->un_fileno < 0) {
9963 						un->un_fileno = 0;
9964 						un->un_blkno = 0;
9965 					} else {
9966 						un->un_blkno = INF;
9967 					}
9968 				} else {
9969 					if (un->un_eof >= ST_EOF_PENDING) {
9970 					/*
9971 					 * we stepped back into
9972 					 * a previous file; we are not
9973 					 * making an effort to pretend that
9974 					 * we are still in the current file
9975 					 * ie. logical == physical position
9976 					 * and leave it to st_ioctl to correct
9977 					 */
9978 						if (un->un_fileno > 0) {
9979 							un->un_fileno--;
9980 							un->un_blkno = INF;
9981 						} else {
9982 							un->un_blkno = 0;
9983 						}
9984 					} else {
9985 						un->un_blkno -=
9986 						    (-count) - resid;
9987 					}
9988 				}
9989 			}
9990 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9991 			    "aft_space rs %ld fil %d blk %ld\n",
9992 			    resid, un->un_fileno, un->un_blkno);
9993 			break;
9994 		}
9995 		case SCMD_LOAD:
9996 			if (bp->b_bcount & 0x1) {
9997 				un->un_fileno = 0;
9998 			} else {
9999 				un->un_state = ST_STATE_OFFLINE;
10000 				un->un_fileno = -1;
10001 			}
10002 			un->un_density_known = 0;
10003 			un->un_eof = ST_NO_EOF;
10004 			un->un_blkno = 0;
10005 			break;
10006 		case SCMD_ERASE:
10007 			un->un_eof = ST_NO_EOF;
10008 			un->un_blkno = 0;
10009 			un->un_fileno = 0;
10010 			break;
10011 		case SCMD_RESERVE:
10012 			un->un_rsvd_status |= ST_RESERVE;
10013 			un->un_rsvd_status &=
10014 				~(ST_RELEASE | ST_LOST_RESERVE |
10015 					ST_RESERVATION_CONFLICT);
10016 			un->un_lastop = saved_lastop;
10017 			break;
10018 		case SCMD_RELEASE:
10019 			un->un_rsvd_status |= ST_RELEASE;
10020 			un->un_rsvd_status &=
10021 				~(ST_RESERVE | ST_LOST_RESERVE |
10022 					ST_RESERVATION_CONFLICT);
10023 			un->un_lastop = saved_lastop;
10024 			break;
10025 		case SCMD_TEST_UNIT_READY:
10026 		case SCMD_READ_BLKLIM:
10027 		case SCMD_REQUEST_SENSE:
10028 		case SCMD_INQUIRY:
10029 		case SCMD_RECOVER_BUF:
10030 		case SCMD_MODE_SELECT:
10031 		case SCMD_MODE_SENSE:
10032 		case SCMD_DOORLOCK:
10033 		case SCMD_READ_POSITION:
10034 		case SCMD_READ_BUFFER:
10035 		case SCMD_REPORT_DENSITIES:
10036 		case SCMD_LOG_SELECT_G1:
10037 		case SCMD_LOG_SENSE_G1:
10038 		case SCMD_REPORT_LUNS:
10039 			un->un_lastop = saved_lastop;
10040 			break;
10041 		case SCMD_LOCATE:	/* Locate makes position unknown */
10042 		default:
10043 			/*
10044 			 * Unknown command, If was USCSI and USCSI_SILENT
10045 			 * flag was not set, set position to unknown.
10046 			 */
10047 			if ((((ucmd = BP_UCMD(bp)) != NULL) &&
10048 			    (ucmd->uscsi_flags & USCSI_SILENT) == 0)) {
10049 				ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
10050 				    "unknown cmd 0x%X caused loss of state\n",
10051 				    cmd);
10052 			} else {
10053 				break;
10054 			}
10055 			/* FALLTHROUGH */
10056 		case SCMD_WRITE_BUFFER: /* Writes new firmware to device */
10057 			un->un_fileno = -1;
10058 			break;
10059 		}
10060 	}
10061 
10062 	/*
10063 	 * In the st driver we have a logical and physical file position.
10064 	 * Under BSD behavior, when you get a zero read, the logical position
10065 	 * is before the filemark but after the last record of the file.
10066 	 * The physical position is after the filemark. MTIOCGET should always
10067 	 * return the logical file position.
10068 	 *
10069 	 * The next read gives a silent skip to the next file.
10070 	 * Under SVR4, the logical file position remains before the filemark
10071 	 * until the file is closed or a space operation is performed.
10072 	 * Hence set err_resid and err_file before changing fileno if case
10073 	 * BSD Behaviour.
10074 	 */
10075 	un->un_err_resid = bp->b_resid;
10076 	un->un_err_fileno = un->un_fileno;
10077 	un->un_err_blkno = un->un_blkno;
10078 	un->un_retry_ct = 0;
10079 
10080 
10081 	/*
10082 	 * If we've seen a filemark via the last read operation
10083 	 * advance the file counter, but mark things such that
10084 	 * the next read operation gets a zero count. We have
10085 	 * to put this here to handle the case of sitting right
10086 	 * at the end of a tape file having seen the file mark,
10087 	 * but the tape is closed and then re-opened without
10088 	 * any further i/o. That is, the position information
10089 	 * must be updated before a close.
10090 	 */
10091 
10092 	if (un->un_lastop == ST_OP_READ && un->un_eof == ST_EOF_PENDING) {
10093 		/*
10094 		 * If we're a 1/2" tape, and we get a filemark
10095 		 * right on block 0, *AND* we were not in the
10096 		 * first file on the tape, and we've hit logical EOM.
10097 		 * We'll mark the state so that later we do the
10098 		 * right thing (in st_close(), st_strategy() or
10099 		 * st_ioctl()).
10100 		 *
10101 		 */
10102 		if ((un->un_dp->options & ST_REEL) &&
10103 			!(un->un_dp->options & ST_READ_IGNORE_EOFS) &&
10104 		    un->un_blkno == 0 && un->un_fileno > 0) {
10105 			un->un_eof = ST_EOT_PENDING;
10106 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10107 			    "eot pending\n");
10108 			un->un_fileno++;
10109 			un->un_blkno = 0;
10110 		} else if (BSD_BEHAVIOR) {
10111 			/*
10112 			 * If the read of the filemark was a side effect
10113 			 * of reading some blocks (i.e., data was actually
10114 			 * read), then the EOF mark is pending and the
10115 			 * bump into the next file awaits the next read
10116 			 * operation (which will return a zero count), or
10117 			 * a close or a space operation, else the bump
10118 			 * into the next file occurs now.
10119 			 */
10120 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10121 			    "resid=%lx, bcount=%lx\n",
10122 				bp->b_resid, bp->b_bcount);
10123 			if (bp->b_resid != bp->b_bcount) {
10124 				un->un_eof = ST_EOF;
10125 			} else {
10126 				un->un_silent_skip = 1;
10127 				un->un_eof = ST_NO_EOF;
10128 				un->un_fileno++;
10129 				un->un_save_blkno = un->un_blkno;
10130 				un->un_blkno = 0;
10131 			}
10132 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10133 			    "eof of file %d, un_eof=%d\n",
10134 			    un->un_fileno, un->un_eof);
10135 		} else if (SVR4_BEHAVIOR) {
10136 			/*
10137 			 * If the read of the filemark was a side effect
10138 			 * of reading some blocks (i.e., data was actually
10139 			 * read), then the next read should return 0
10140 			 */
10141 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10142 			    "resid=%lx, bcount=%lx\n",
10143 			    bp->b_resid, bp->b_bcount);
10144 			if (bp->b_resid == bp->b_bcount) {
10145 				un->un_eof = ST_EOF;
10146 			}
10147 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10148 			    "eof of file=%d, un_eof=%d\n",
10149 			    un->un_fileno, un->un_eof);
10150 		}
10151 	}
10152 }
10153 
10154 /*
10155  * set the correct un_errno, to take corner cases into consideration
10156  */
10157 static void
10158 st_set_pe_errno(struct scsi_tape *un)
10159 {
10160 	ASSERT(mutex_owned(ST_MUTEX));
10161 
10162 	/* if errno is already set, don't reset it */
10163 	if (un->un_errno)
10164 		return;
10165 
10166 	/* here un_errno == 0 */
10167 	/*
10168 	 * if the last transfer before flushing all the
10169 	 * waiting I/O's, was 0 (resid = count), then we
10170 	 * want to give the user an error on all the rest,
10171 	 * so here.  If there was a transfer, we set the
10172 	 * resid and counts to 0, and let it drop through,
10173 	 * giving a zero return.  the next I/O will then
10174 	 * give an error.
10175 	 */
10176 	if (un->un_last_resid == un->un_last_count) {
10177 		switch (un->un_eof) {
10178 		case ST_EOM:
10179 			un->un_errno = ENOMEM;
10180 			break;
10181 		case ST_EOT:
10182 		case ST_EOF:
10183 			un->un_errno = EIO;
10184 			break;
10185 		}
10186 	} else {
10187 		/*
10188 		 * we know they did not have a zero, so make
10189 		 * sure they get one
10190 		 */
10191 		un->un_last_resid = un->un_last_count = 0;
10192 	}
10193 }
10194 
10195 
10196 /*
10197  * send in a marker pkt to terminate flushing of commands by BBA (via
10198  * flush-on-errors) property.  The HBA will always return TRAN_ACCEPT
10199  */
10200 static void
10201 st_hba_unflush(struct scsi_tape *un)
10202 {
10203 	ASSERT(mutex_owned(ST_MUTEX));
10204 
10205 	if (!un->un_flush_on_errors)
10206 		return;
10207 
10208 #ifdef FLUSH_ON_ERRORS
10209 
10210 	if (!un->un_mkr_pkt) {
10211 		un->un_mkr_pkt = scsi_init_pkt(ROUTE, NULL, (struct buf *)NULL,
10212 		    NULL, 0, 0, 0, SLEEP_FUNC, NULL);
10213 
10214 		/* we slept, so it must be there */
10215 		pkt->pkt_flags |= FLAG_FLUSH_MARKER;
10216 	}
10217 
10218 	mutex_exit(ST_MUTEX);
10219 	scsi_transport(un->un_mkr_pkt);
10220 	mutex_enter(ST_MUTEX);
10221 #endif
10222 }
10223 
10224 static void
10225 st_clean_print(dev_info_t *dev, char *label, uint_t level,
10226 	char *title, char *data, int len)
10227 {
10228 	int	i;
10229 	char	buf[256];
10230 
10231 	(void) sprintf(buf, "%s: ", title);
10232 	for (i = 0; i < len; i++) {
10233 		(void) sprintf(&buf[(int)strlen(buf)], "0x%x ",
10234 			(data[i] & 0xff));
10235 	}
10236 	(void) sprintf(&buf[(int)strlen(buf)], "\n");
10237 
10238 	scsi_log(dev, label, level, "%s", buf);
10239 }
10240 
10241 /*
10242  * Conditionally enabled debugging
10243  */
10244 #ifdef	STDEBUG
10245 static void
10246 st_debug_cmds(struct scsi_tape *un, int com, int count, int wait)
10247 {
10248 	char tmpbuf[64];
10249 
10250 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10251 	    "cmd=%s count=0x%x (%d)	 %ssync\n",
10252 	    scsi_cmd_name(com, scsi_cmds, tmpbuf),
10253 	    count, count,
10254 	    wait == ASYNC_CMD ? "a" : "");
10255 }
10256 
10257 /*
10258  * Returns pointer to name of minor node name of device 'dev'.
10259  */
10260 static char *
10261 st_dev_name(dev_t dev)
10262 {
10263 	const char density[] = { 'l', 'm', 'h', 'c' };
10264 	static char name[4];
10265 	minor_t minor;
10266 	int nprt = 0;
10267 
10268 	minor = getminor(dev);
10269 	name[nprt] = density[(minor & MT_DENSITY_MASK) >> 3];
10270 
10271 	if (minor & MT_BSD) {
10272 		name[++nprt] = 'b';
10273 	}
10274 
10275 	if (minor & MT_NOREWIND) {
10276 		name[++nprt] = 'n';
10277 	}
10278 
10279 	/* NULL terminator */
10280 	name[++nprt] = 0;
10281 
10282 	return (name);
10283 }
10284 #endif	/* STDEBUG */
10285 
10286 /*
10287  * Soft error reporting, so far unique to each drive
10288  *
10289  * Currently supported: exabyte and DAT soft error reporting
10290  */
10291 static int
10292 st_report_exabyte_soft_errors(dev_t dev, int flag)
10293 {
10294 	uchar_t *sensep;
10295 	int amt;
10296 	int rval = 0;
10297 	char cdb[CDB_GROUP0], *c = cdb;
10298 	struct uscsi_cmd *com;
10299 
10300 	GET_SOFT_STATE(dev);
10301 
10302 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10303 	    "st_report_exabyte_soft_errors(dev = 0x%lx, flag = %d)\n",
10304 	    dev, flag);
10305 
10306 	ASSERT(mutex_owned(ST_MUTEX));
10307 
10308 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
10309 	sensep = kmem_zalloc(TAPE_SENSE_LENGTH, KM_SLEEP);
10310 
10311 	*c++ = SCMD_REQUEST_SENSE;
10312 	*c++ = 0;
10313 	*c++ = 0;
10314 	*c++ = 0;
10315 	*c++ = TAPE_SENSE_LENGTH;
10316 	/*
10317 	 * set CLRCNT (byte 5, bit 7 which clears the error counts)
10318 	 */
10319 	*c   = (char)0x80;
10320 
10321 	com->uscsi_cdb = cdb;
10322 	com->uscsi_cdblen = CDB_GROUP0;
10323 	com->uscsi_bufaddr = (caddr_t)sensep;
10324 	com->uscsi_buflen = TAPE_SENSE_LENGTH;
10325 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT
10326 		| USCSI_READ | USCSI_RQENABLE;
10327 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
10328 
10329 	rval = st_ioctl_cmd(dev, com, UIO_SYSSPACE, UIO_SYSSPACE,
10330 		UIO_SYSSPACE);
10331 	if (rval || com->uscsi_status) {
10332 		goto done;
10333 	}
10334 
10335 	/*
10336 	 * was there enough data?
10337 	 */
10338 	amt = (int)TAPE_SENSE_LENGTH - com->uscsi_resid;
10339 
10340 	if ((amt >= 19) && un->un_kbytes_xferred) {
10341 		uint_t count, error_rate;
10342 		uint_t rate;
10343 
10344 		if (sensep[21] & CLN) {
10345 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
10346 			    "Periodic head cleaning required");
10347 		}
10348 		if (un->un_kbytes_xferred < (EXABYTE_MIN_TRANSFER/1000))
10349 			goto done;
10350 		/*
10351 		 * check if soft error reporting needs to be done.
10352 		 */
10353 		count = sensep[16] << 16 | sensep[17] << 8 | sensep[18];
10354 		count &= 0xffffff;
10355 		error_rate = (count * 100)/un->un_kbytes_xferred;
10356 
10357 #ifdef	STDEBUG
10358 		if (st_soft_error_report_debug) {
10359 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
10360 			    "Exabyte Soft Error Report:\n");
10361 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10362 			    "read/write error counter: %d\n", count);
10363 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10364 			    "number of bytes transferred: %dK\n",
10365 				un->un_kbytes_xferred);
10366 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10367 			    "error_rate: %d%%\n", error_rate);
10368 
10369 			if (amt >= 22) {
10370 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10371 				    "unit sense: 0x%b 0x%b 0x%b\n",
10372 				    sensep[19], SENSE_19_BITS,
10373 				    sensep[20], SENSE_20_BITS,
10374 				    sensep[21], SENSE_21_BITS);
10375 			}
10376 			if (amt >= 27) {
10377 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10378 				    "tracking retry counter: %d\n",
10379 				    sensep[26]);
10380 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10381 				    "read/write retry counter: %d\n",
10382 				    sensep[27]);
10383 			}
10384 		}
10385 #endif
10386 
10387 		if (flag & FWRITE) {
10388 			rate = EXABYTE_WRITE_ERROR_THRESHOLD;
10389 		} else {
10390 			rate = EXABYTE_READ_ERROR_THRESHOLD;
10391 		}
10392 		if (error_rate >= rate) {
10393 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
10394 			    "Soft error rate (%d%%) during %s was too high",
10395 			    error_rate,
10396 			    ((flag & FWRITE) ? wrg_str : rdg_str));
10397 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10398 			    "Please, replace tape cartridge\n");
10399 		}
10400 	}
10401 
10402 done:
10403 	kmem_free(com, sizeof (*com));
10404 	kmem_free(sensep, TAPE_SENSE_LENGTH);
10405 
10406 	if (rval != 0) {
10407 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10408 		    "exabyte soft error reporting failed\n");
10409 	}
10410 	return (rval);
10411 }
10412 
10413 /*
10414  * this is very specific to Archive 4mm dat
10415  */
10416 #define	ONEGIG	(1024 * 1024 * 1024)
10417 
10418 static int
10419 st_report_dat_soft_errors(dev_t dev, int flag)
10420 {
10421 	uchar_t *sensep;
10422 	int amt, i;
10423 	int rval = 0;
10424 	char cdb[CDB_GROUP1], *c = cdb;
10425 	struct uscsi_cmd *com;
10426 
10427 	GET_SOFT_STATE(dev);
10428 
10429 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10430 	    "st_report_dat_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
10431 
10432 	ASSERT(mutex_owned(ST_MUTEX));
10433 
10434 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
10435 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
10436 
10437 	*c++ = SCMD_LOG_SENSE_G1;
10438 	*c++ = 0;
10439 	*c++ = (flag & FWRITE) ? 0x42 : 0x43;
10440 	*c++ = 0;
10441 	*c++ = 0;
10442 	*c++ = 0;
10443 	*c++ = 2;
10444 	*c++ = 0;
10445 	*c++ = (char)LOG_SENSE_LENGTH;
10446 	*c   = 0;
10447 	com->uscsi_cdb    = cdb;
10448 	com->uscsi_cdblen  = CDB_GROUP1;
10449 	com->uscsi_bufaddr = (caddr_t)sensep;
10450 	com->uscsi_buflen  = LOG_SENSE_LENGTH;
10451 	com->uscsi_flags   =
10452 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ | USCSI_RQENABLE;
10453 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
10454 	rval =
10455 	    st_ioctl_cmd(dev, com, UIO_SYSSPACE, UIO_SYSSPACE, UIO_SYSSPACE);
10456 	if (rval) {
10457 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10458 		    "DAT soft error reporting failed\n");
10459 	}
10460 	if (rval || com->uscsi_status) {
10461 		goto done;
10462 	}
10463 
10464 	/*
10465 	 * was there enough data?
10466 	 */
10467 	amt = (int)LOG_SENSE_LENGTH - com->uscsi_resid;
10468 
10469 	if ((amt >= MIN_LOG_SENSE_LENGTH) && un->un_kbytes_xferred) {
10470 		int total, retries, param_code;
10471 
10472 		total = -1;
10473 		retries = -1;
10474 		amt = sensep[3] + 4;
10475 
10476 
10477 #ifdef STDEBUG
10478 		if (st_soft_error_report_debug) {
10479 			(void) printf("logsense:");
10480 			for (i = 0; i < MIN_LOG_SENSE_LENGTH; i++) {
10481 				if (i % 16 == 0) {
10482 					(void) printf("\t\n");
10483 				}
10484 				(void) printf(" %x", sensep[i]);
10485 			}
10486 			(void) printf("\n");
10487 		}
10488 #endif
10489 
10490 		/*
10491 		 * parse the param_codes
10492 		 */
10493 		if (sensep[0] == 2 || sensep[0] == 3) {
10494 			for (i = 4; i < amt; i++) {
10495 				param_code = (sensep[i++] << 8);
10496 				param_code += sensep[i++];
10497 				i++; /* skip control byte */
10498 				if (param_code == 5) {
10499 					if (sensep[i++] == 4) {
10500 						total = (sensep[i++] << 24);
10501 						total += (sensep[i++] << 16);
10502 						total += (sensep[i++] << 8);
10503 						total += sensep[i];
10504 					}
10505 				} else if (param_code == 0x8007) {
10506 					if (sensep[i++] == 2) {
10507 						retries = sensep[i++] << 8;
10508 						retries += sensep[i];
10509 					}
10510 				} else {
10511 					i += sensep[i];
10512 				}
10513 			}
10514 		}
10515 
10516 		/*
10517 		 * if the log sense returned valid numbers then determine
10518 		 * the read and write error thresholds based on the amount of
10519 		 * data transferred
10520 		 */
10521 
10522 		if (total > 0 && retries > 0) {
10523 			short normal_retries = 0;
10524 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10525 			"total xferred (%s) =%x, retries=%x\n",
10526 				((flag & FWRITE) ? wrg_str : rdg_str),
10527 				total, retries);
10528 
10529 			if (flag & FWRITE) {
10530 				if (total <=
10531 					WRITE_SOFT_ERROR_WARNING_THRESHOLD) {
10532 					normal_retries =
10533 						DAT_SMALL_WRITE_ERROR_THRESHOLD;
10534 				} else {
10535 					normal_retries =
10536 						DAT_LARGE_WRITE_ERROR_THRESHOLD;
10537 				}
10538 			} else {
10539 				if (total <=
10540 					READ_SOFT_ERROR_WARNING_THRESHOLD) {
10541 					normal_retries =
10542 						DAT_SMALL_READ_ERROR_THRESHOLD;
10543 				} else {
10544 					normal_retries =
10545 						DAT_LARGE_READ_ERROR_THRESHOLD;
10546 				}
10547 			}
10548 
10549 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10550 			"normal retries=%d\n", normal_retries);
10551 
10552 			if (retries >= normal_retries) {
10553 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
10554 				    "Soft error rate (retries = %d) during "
10555 				    "%s was too high",  retries,
10556 				    ((flag & FWRITE) ? wrg_str : rdg_str));
10557 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10558 				    "Periodic head cleaning required "
10559 				    "and/or replace tape cartridge\n");
10560 			}
10561 
10562 		} else if (total == -1 || retries == -1) {
10563 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
10564 			    "log sense parameter code does not make sense\n");
10565 		}
10566 	}
10567 
10568 	/*
10569 	 * reset all values
10570 	 */
10571 	c = cdb;
10572 	*c++ = SCMD_LOG_SELECT_G1;
10573 	*c++ = 2;	/* this resets all values */
10574 	*c++ = (char)0xc0;
10575 	*c++ = 0;
10576 	*c++ = 0;
10577 	*c++ = 0;
10578 	*c++ = 0;
10579 	*c++ = 0;
10580 	*c++ = 0;
10581 	*c   = 0;
10582 	com->uscsi_bufaddr = NULL;
10583 	com->uscsi_buflen  = 0;
10584 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_RQENABLE;
10585 	rval =
10586 	    st_ioctl_cmd(dev, com, UIO_SYSSPACE, UIO_SYSSPACE, UIO_SYSSPACE);
10587 	if (rval) {
10588 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10589 		    "DAT soft error reset failed\n");
10590 	}
10591 done:
10592 	kmem_free(com, sizeof (*com));
10593 	kmem_free(sensep, LOG_SENSE_LENGTH);
10594 	return (rval);
10595 }
10596 
10597 static int
10598 st_report_soft_errors(dev_t dev, int flag)
10599 {
10600 	GET_SOFT_STATE(dev);
10601 
10602 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10603 	    "st_report_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
10604 
10605 	ASSERT(mutex_owned(ST_MUTEX));
10606 
10607 	switch (un->un_dp->type) {
10608 	case ST_TYPE_EXB8500:
10609 	case ST_TYPE_EXABYTE:
10610 		return (st_report_exabyte_soft_errors(dev, flag));
10611 		/*NOTREACHED*/
10612 	case ST_TYPE_PYTHON:
10613 		return (st_report_dat_soft_errors(dev, flag));
10614 		/*NOTREACHED*/
10615 	default:
10616 		un->un_dp->options &= ~ST_SOFT_ERROR_REPORTING;
10617 		return (-1);
10618 	}
10619 }
10620 
10621 /*
10622  * persistent error routines
10623  */
10624 
10625 /*
10626  * enable persistent errors, and set the throttle appropriately, checking
10627  * for flush-on-errors capability
10628  */
10629 static void
10630 st_turn_pe_on(struct scsi_tape *un)
10631 {
10632 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_on\n");
10633 	ASSERT(mutex_owned(ST_MUTEX));
10634 
10635 	un->un_persistence = 1;
10636 
10637 	/*
10638 	 * only use flush-on-errors if auto-request-sense and untagged-qing are
10639 	 * enabled.  This will simplify the error handling for request senses
10640 	 */
10641 
10642 	if (un->un_arq_enabled && un->un_untagged_qing) {
10643 		uchar_t f_o_e;
10644 
10645 		mutex_exit(ST_MUTEX);
10646 		f_o_e = (scsi_ifsetcap(ROUTE, "flush-on-errors", 1, 1) == 1) ?
10647 		    1 : 0;
10648 		mutex_enter(ST_MUTEX);
10649 
10650 		un->un_flush_on_errors = f_o_e;
10651 	} else {
10652 		un->un_flush_on_errors = 0;
10653 	}
10654 
10655 	if (un->un_flush_on_errors)
10656 		un->un_max_throttle = (uchar_t)st_max_throttle;
10657 	else
10658 		un->un_max_throttle = 1;
10659 
10660 	if (un->un_dp->options & ST_RETRY_ON_RECOVERED_DEFERRED_ERROR)
10661 		un->un_max_throttle = 1;
10662 
10663 	/* this will send a marker pkt */
10664 	CLEAR_PE(un);
10665 }
10666 
10667 /*
10668  * This turns persistent errors permanently off
10669  */
10670 static void
10671 st_turn_pe_off(struct scsi_tape *un)
10672 {
10673 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_off\n");
10674 	ASSERT(mutex_owned(ST_MUTEX));
10675 
10676 	/* turn it off for good */
10677 	un->un_persistence = 0;
10678 
10679 	/* this will send a marker pkt */
10680 	CLEAR_PE(un);
10681 
10682 	/* turn off flush on error capability, if enabled */
10683 	if (un->un_flush_on_errors) {
10684 		mutex_exit(ST_MUTEX);
10685 		(void) scsi_ifsetcap(ROUTE, "flush-on-errors", 0, 1);
10686 		mutex_enter(ST_MUTEX);
10687 	}
10688 
10689 
10690 	un->un_flush_on_errors = 0;
10691 }
10692 
10693 /*
10694  * This clear persistent errors, allowing more commands through, and also
10695  * sending a marker packet.
10696  */
10697 static void
10698 st_clear_pe(struct scsi_tape *un)
10699 {
10700 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_clear\n");
10701 	ASSERT(mutex_owned(ST_MUTEX));
10702 
10703 	un->un_persist_errors = 0;
10704 	un->un_throttle = un->un_last_throttle = 1;
10705 	un->un_errno = 0;
10706 	st_hba_unflush(un);
10707 }
10708 
10709 /*
10710  * This will flag persistent errors, shutting everything down, if the
10711  * application had enabled persistent errors via MTIOCPERSISTENT
10712  */
10713 static void
10714 st_set_pe_flag(struct scsi_tape *un)
10715 {
10716 	ASSERT(mutex_owned(ST_MUTEX));
10717 
10718 	if (un->un_persistence) {
10719 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_flag\n");
10720 		un->un_persist_errors = 1;
10721 		un->un_throttle = un->un_last_throttle = 0;
10722 	}
10723 }
10724 
10725 int
10726 st_reserve_release(dev_t dev, int cmd)
10727 {
10728 	struct uscsi_cmd	uscsi_cmd;
10729 	struct uscsi_cmd	*com = &uscsi_cmd;
10730 	int			rval;
10731 	char			cdb[CDB_GROUP0];
10732 
10733 
10734 	GET_SOFT_STATE(dev);
10735 	ASSERT(mutex_owned(ST_MUTEX));
10736 
10737 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10738 		"st_reserve_release: %s \n", (cmd == ST_RELEASE)?
10739 				"Releasing":"Reserving");
10740 
10741 	bzero(cdb, CDB_GROUP0);
10742 	if (cmd == ST_RELEASE) {
10743 		cdb[0] = SCMD_RELEASE;
10744 	} else {
10745 		cdb[0] = SCMD_RESERVE;
10746 	}
10747 	bzero(com, sizeof (struct uscsi_cmd));
10748 	com->uscsi_flags = USCSI_WRITE;
10749 	com->uscsi_cdb = cdb;
10750 	com->uscsi_cdblen = CDB_GROUP0;
10751 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
10752 
10753 	rval = st_ioctl_cmd(dev, com,
10754 		UIO_SYSSPACE, UIO_SYSSPACE, UIO_SYSSPACE);
10755 
10756 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10757 		"st_reserve_release: rval(1)=%d\n", rval);
10758 
10759 	if (rval) {
10760 		if (com->uscsi_status == STATUS_RESERVATION_CONFLICT)
10761 			rval = EACCES;
10762 		/*
10763 		 * dynamically turn off reserve/release support
10764 		 * in case of drives which do not support
10765 		 * reserve/release command(ATAPI drives).
10766 		 */
10767 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
10768 			if (ST_RESERVE_SUPPORTED(un)) {
10769 				un->un_dp->options |= ST_NO_RESERVE_RELEASE;
10770 				ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10771 					"Tape unit does not support "
10772 					"reserve/release \n");
10773 			}
10774 			rval = 0;
10775 		}
10776 	}
10777 	return (rval);
10778 }
10779 
10780 static int
10781 st_take_ownership(dev_t dev)
10782 {
10783 	int rval;
10784 
10785 	GET_SOFT_STATE(dev);
10786 	ASSERT(mutex_owned(ST_MUTEX));
10787 
10788 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10789 		"st_take_ownership: Entering ...\n");
10790 
10791 
10792 	rval = st_reserve_release(dev, ST_RESERVE);
10793 	/*
10794 	 * XXX -> Should reset be done only if we get EACCES.
10795 	 * .
10796 	 */
10797 	if (rval) {
10798 		mutex_exit(ST_MUTEX);
10799 		if (scsi_reset(ROUTE, RESET_TARGET) == 0) {
10800 			if (scsi_reset(ROUTE, RESET_ALL) == 0) {
10801 				mutex_enter(ST_MUTEX);
10802 				return (EIO);
10803 			}
10804 		}
10805 		mutex_enter(ST_MUTEX);
10806 		un->un_rsvd_status &=
10807 			~(ST_LOST_RESERVE | ST_RESERVATION_CONFLICT);
10808 
10809 		mutex_exit(ST_MUTEX);
10810 		delay(drv_usectohz(ST_RESERVATION_DELAY));
10811 		mutex_enter(ST_MUTEX);
10812 		/*
10813 		 * remove the check condition.
10814 		 */
10815 		(void) st_reserve_release(dev, ST_RESERVE);
10816 		if ((rval = st_reserve_release(dev, ST_RESERVE)) != 0) {
10817 			if ((st_reserve_release(dev, ST_RESERVE)) != 0) {
10818 				rval = (un->un_rsvd_status &
10819 					ST_RESERVATION_CONFLICT) ? EACCES : EIO;
10820 				return (rval);
10821 			}
10822 		}
10823 		/*
10824 		 * Set tape state to ST_STATE_OFFLINE , in case if
10825 		 * the user wants to continue and start using
10826 		 * the tape.
10827 		 */
10828 		un->un_state = ST_STATE_OFFLINE;
10829 		un->un_rsvd_status |= ST_INIT_RESERVE;
10830 	}
10831 	return (rval);
10832 }
10833 
10834 static int
10835 st_create_errstats(struct scsi_tape *un, int instance)
10836 {
10837 	char	kstatname[KSTAT_STRLEN];
10838 
10839 	/*
10840 	 * Create device error kstats
10841 	 */
10842 
10843 	if (un->un_errstats == (kstat_t *)0) {
10844 		(void) sprintf(kstatname, "st%d,err", instance);
10845 		un->un_errstats = kstat_create("sterr", instance, kstatname,
10846 			"device_error", KSTAT_TYPE_NAMED,
10847 			sizeof (struct st_errstats) / sizeof (kstat_named_t),
10848 			KSTAT_FLAG_PERSISTENT);
10849 
10850 		if (un->un_errstats) {
10851 			struct st_errstats	*stp;
10852 
10853 			stp = (struct st_errstats *)un->un_errstats->ks_data;
10854 			kstat_named_init(&stp->st_softerrs, "Soft Errors",
10855 				KSTAT_DATA_ULONG);
10856 			kstat_named_init(&stp->st_harderrs, "Hard Errors",
10857 				KSTAT_DATA_ULONG);
10858 			kstat_named_init(&stp->st_transerrs, "Transport Errors",
10859 				KSTAT_DATA_ULONG);
10860 			kstat_named_init(&stp->st_vid, "Vendor",
10861 				KSTAT_DATA_CHAR);
10862 			kstat_named_init(&stp->st_pid, "Product",
10863 				KSTAT_DATA_CHAR);
10864 			kstat_named_init(&stp->st_revision, "Revision",
10865 				KSTAT_DATA_CHAR);
10866 			kstat_named_init(&stp->st_serial, "Serial No",
10867 				KSTAT_DATA_CHAR);
10868 			un->un_errstats->ks_private = un;
10869 			un->un_errstats->ks_update = nulldev;
10870 			kstat_install(un->un_errstats);
10871 			/*
10872 			 * Fill in the static data
10873 			 */
10874 			(void) strncpy(&stp->st_vid.value.c[0],
10875 					ST_INQUIRY->inq_vid, 8);
10876 			/*
10877 			 * XXX:  Emulex MT-02 (and emulators) predates
10878 			 *	 SCSI-1 and has no vid & pid inquiry data.
10879 			 */
10880 			if (ST_INQUIRY->inq_len != 0) {
10881 				(void) strncpy(&stp->st_pid.value.c[0],
10882 					ST_INQUIRY->inq_pid, 16);
10883 				(void) strncpy(&stp->st_revision.value.c[0],
10884 					ST_INQUIRY->inq_revision, 4);
10885 				(void) strncpy(&stp->st_serial.value.c[0],
10886 					ST_INQUIRY->inq_serial, 12);
10887 			}
10888 		}
10889 	}
10890 	return (0);
10891 }
10892 
10893 static int
10894 st_validate_tapemarks(struct scsi_tape *un, int fileno, daddr_t blkno)
10895 {
10896 	dev_t 	dev;
10897 
10898 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
10899 	ASSERT(mutex_owned(ST_MUTEX));
10900 
10901 	dev = un->un_dev;
10902 
10903 	scsi_log(ST_DEVINFO, st_label, CE_NOTE, "Restoring tape"
10904 	" position at fileno=%x, blkno=%lx....", fileno, blkno);
10905 
10906 	/*
10907 	 * Rewind ? Oh yeah, Fidelity has got the STK F/W changed
10908 	 * so as not to rewind tape on RESETS: Gee, Has life ever
10909 	 * been simple in tape land ?
10910 	 */
10911 	if (st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD)) {
10912 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10913 		"Failed to restore the last file and block position: In"
10914 		" this state, Tape will be loaded at BOT during next open");
10915 		un->un_fileno = -1;
10916 		return (1);
10917 	}
10918 
10919 	if (fileno) {
10920 		if (st_cmd(dev, SCMD_SPACE, Fmk(fileno), SYNC_CMD)) {
10921 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
10922 			"Failed to restore the last file position: In this "
10923 			" state, Tape will be loaded at BOT during next open");
10924 			un->un_fileno = -1;
10925 			return (2);
10926 		}
10927 	}
10928 
10929 	if (blkno) {
10930 		if (st_cmd(dev, SCMD_SPACE, Blk(blkno), SYNC_CMD)) {
10931 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
10932 			"Failed to restore the last block position: In this"
10933 			" state, tape will be loaded at BOT during next open");
10934 			un->un_fileno = -1;
10935 			return (3);
10936 		}
10937 	}
10938 
10939 	return (0);
10940 }
10941 
10942 /*
10943  * check sense key, ASC, ASCQ in order to determine if the tape needs
10944  * to be ejected
10945  */
10946 
10947 static int
10948 st_check_asc_ascq(struct scsi_tape *un)
10949 {
10950 	struct scsi_extended_sense *sensep = ST_RQSENSE;
10951 	struct tape_failure_code   *code;
10952 
10953 	for (code = st_tape_failure_code; code->key != 0xff; code++) {
10954 		if ((code->key  == sensep->es_key) &&
10955 		    (code->add_code  == sensep->es_add_code) &&
10956 		    (code->qual_code == sensep->es_qual_code))
10957 			return (1);
10958 	}
10959 	return (0);
10960 }
10961 
10962 /*
10963  * st_logpage_supported() sends a Log Sense command with
10964  * page code = 0 = Supported Log Pages Page to the device,
10965  * to see whether the page 'page' is supported.
10966  * Return values are:
10967  * -1 if the Log Sense command fails
10968  * 0 if page is not supported
10969  * 1 if page is supported
10970  */
10971 
10972 static int
10973 st_logpage_supported(dev_t dev, uchar_t page)
10974 {
10975 	uchar_t *sp, *sensep;
10976 	unsigned length;
10977 	struct uscsi_cmd *com;
10978 	int rval;
10979 	char cdb[CDB_GROUP1] = {
10980 		SCMD_LOG_SENSE_G1,
10981 		0,
10982 		SUPPORTED_LOG_PAGES_PAGE,
10983 		0,
10984 		0,
10985 		0,
10986 		0,
10987 		0,
10988 		(char)LOG_SENSE_LENGTH,
10989 		0
10990 	};
10991 
10992 	GET_SOFT_STATE(dev);
10993 	ASSERT(mutex_owned(ST_MUTEX));
10994 
10995 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
10996 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
10997 
10998 	com->uscsi_cdb = cdb;
10999 	com->uscsi_cdblen = CDB_GROUP1;
11000 	com->uscsi_bufaddr = (caddr_t)sensep;
11001 	com->uscsi_buflen = LOG_SENSE_LENGTH;
11002 	com->uscsi_flags =
11003 		USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ | USCSI_RQENABLE;
11004 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
11005 	rval = st_ioctl_cmd(dev, com, UIO_SYSSPACE, UIO_SYSSPACE, UIO_SYSSPACE);
11006 	if (rval || com->uscsi_status) {
11007 		/* uscsi-command failed */
11008 		rval = -1;
11009 	} else {
11010 
11011 		sp = sensep + 3;
11012 
11013 		for (length = *sp++; length > 0; length--, sp++) {
11014 
11015 			if (*sp == page) {
11016 				rval = 1;
11017 				break;
11018 			}
11019 		}
11020 	}
11021 	kmem_free(com, sizeof (struct uscsi_cmd));
11022 	kmem_free(sensep, LOG_SENSE_LENGTH);
11023 	return (rval);
11024 }
11025 
11026 
11027 /*
11028  * st_check_clean_bit() gets the status of the tape's cleaning bit.
11029  *
11030  * If the device does support the TapeAlert log page, then the cleaning bit
11031  * information will be read from this page. Otherwise we will see if one of
11032  * ST_CLN_TYPE_1, ST_CLN_TYPE_2 or ST_CLN_TYPE_3 is set in the properties of
11033  * the device, which means, that we can get the cleaning bit information via
11034  * a RequestSense command.
11035  * If both methods of getting cleaning bit information are not supported
11036  * st_check_clean_bit() will return with 0. Otherwise st_check_clean_bit()
11037  * returns with
11038  * - MTF_TAPE_CLN_SUPPORTED if cleaning bit is not set or
11039  * - MTF_TAPE_CLN_SUPPORTED | MTF_TAPE_HEAD_DIRTY if cleaning bit is set.
11040  * If the call to st_ioctl_cmd() to do the Log Sense or the Request Sense
11041  * command fails, or if the amount of Request Sense data is not enough, then
11042  *  st_check_clean_bit() returns with -1.
11043  */
11044 
11045 static int
11046 st_check_clean_bit(dev_t dev)
11047 {
11048 	int rval = 0;
11049 
11050 	GET_SOFT_STATE(dev);
11051 
11052 	ASSERT(mutex_owned(ST_MUTEX));
11053 
11054 	if (un->un_HeadClean & TAPE_ALERT_NOT_SUPPORTED) {
11055 		return (rval);
11056 	}
11057 
11058 	if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
11059 
11060 		rval = st_logpage_supported(dev, TAPE_SEQUENTIAL_PAGE);
11061 		if (rval == 1) {
11062 
11063 			un->un_HeadClean |= TAPE_SEQUENTIAL_SUPPORTED;
11064 		}
11065 
11066 		rval = st_logpage_supported(dev, TAPE_ALERT_PAGE);
11067 		if (rval == 1) {
11068 
11069 			un->un_HeadClean |= TAPE_ALERT_SUPPORTED;
11070 		}
11071 
11072 		if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
11073 
11074 			un->un_HeadClean = TAPE_ALERT_NOT_SUPPORTED;
11075 		}
11076 	}
11077 
11078 	rval = 0;
11079 
11080 	if (un->un_HeadClean & TAPE_SEQUENTIAL_SUPPORTED) {
11081 
11082 		rval = st_check_sequential_clean_bit(dev);
11083 	}
11084 
11085 	if ((rval <= 0) && (un->un_HeadClean & TAPE_ALERT_SUPPORTED)) {
11086 
11087 		rval = st_check_alert_clean_bit(dev);
11088 	}
11089 
11090 	if ((rval <= 0) && (un->un_dp->options & ST_CLN_MASK)) {
11091 
11092 		rval = st_check_sense_clean_bit(dev);
11093 	}
11094 
11095 	if (rval < 0) {
11096 		return (rval);
11097 	}
11098 
11099 	/*
11100 	 * If found a supported means to check need to clean.
11101 	 */
11102 	if (rval & MTF_TAPE_CLN_SUPPORTED) {
11103 
11104 		/*
11105 		 * head needs to be cleaned.
11106 		 */
11107 		if (rval & MTF_TAPE_HEAD_DIRTY) {
11108 
11109 			/*
11110 			 * Print log message only first time
11111 			 * found needing cleaned.
11112 			 */
11113 			if ((un->un_HeadClean & TAPE_PREVIOUSLY_DIRTY) == 0) {
11114 
11115 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
11116 				    "Periodic head cleaning required");
11117 
11118 				un->un_HeadClean |= TAPE_PREVIOUSLY_DIRTY;
11119 			}
11120 
11121 		} else {
11122 
11123 			un->un_HeadClean &= ~TAPE_PREVIOUSLY_DIRTY;
11124 		}
11125 	}
11126 
11127 	return (rval);
11128 }
11129 
11130 
11131 static int
11132 st_check_sequential_clean_bit(dev_t dev)
11133 {
11134 	int rval;
11135 	int ix;
11136 	ushort_t parameter;
11137 	struct uscsi_cmd *cmd;
11138 	struct log_sequential_page *sp;
11139 	struct log_sequential_page_parameter *prm;
11140 	char cdb[CDB_GROUP1] = {
11141 		SCMD_LOG_SENSE_G1,
11142 		0,
11143 		TAPE_SEQUENTIAL_PAGE | CURRENT_CUMULATIVE_VALUES,
11144 		0,
11145 		0,
11146 		0,
11147 		0,
11148 		(char)(sizeof (struct log_sequential_page) >> 8),
11149 		(char)(sizeof (struct log_sequential_page)),
11150 		0
11151 	};
11152 
11153 	GET_SOFT_STATE(dev);
11154 
11155 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
11156 	sp  = kmem_zalloc(sizeof (struct log_sequential_page), KM_SLEEP);
11157 
11158 	cmd->uscsi_flags   =
11159 		USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ | USCSI_RQENABLE;
11160 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
11161 	cmd->uscsi_cdb	   = cdb;
11162 	cmd->uscsi_cdblen  = CDB_GROUP1;
11163 	cmd->uscsi_bufaddr = (caddr_t)sp;
11164 	cmd->uscsi_buflen  = sizeof (struct log_sequential_page);
11165 
11166 	rval = st_ioctl_cmd(dev, cmd, UIO_SYSSPACE, UIO_SYSSPACE, UIO_SYSSPACE);
11167 
11168 	if (rval || cmd->uscsi_status || cmd->uscsi_resid) {
11169 
11170 		rval = -1;
11171 
11172 	} else if (sp->log_page.code != TAPE_SEQUENTIAL_PAGE) {
11173 
11174 		rval = -1;
11175 	}
11176 
11177 	prm = &sp->param[0];
11178 
11179 	for (ix = 0; rval == 0 && ix < TAPE_SEQUENTIAL_PAGE_PARA; ix++) {
11180 
11181 		if (prm->log_param.length == 0) {
11182 			break;
11183 		}
11184 
11185 		parameter = (((prm->log_param.pc_hi << 8) & 0xff00) +
11186 			(prm->log_param.pc_lo & 0xff));
11187 
11188 		if (parameter == SEQUENTIAL_NEED_CLN) {
11189 
11190 			rval = MTF_TAPE_CLN_SUPPORTED;
11191 			if (prm->param_value[prm->log_param.length - 1]) {
11192 
11193 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11194 					    "sequential log says head dirty\n");
11195 				rval |= MTF_TAPE_HEAD_DIRTY;
11196 			}
11197 		}
11198 		prm = (struct log_sequential_page_parameter *)
11199 			&prm->param_value[prm->log_param.length];
11200 	}
11201 
11202 	kmem_free(cmd, sizeof (struct uscsi_cmd));
11203 	kmem_free(sp,  sizeof (struct log_sequential_page));
11204 
11205 	return (rval);
11206 }
11207 
11208 
11209 static int
11210 st_check_alert_clean_bit(dev_t dev)
11211 {
11212 	struct st_tape_alert *ta;
11213 	struct uscsi_cmd *com;
11214 	unsigned ix, length;
11215 	int rval;
11216 	ushort_t parameter;
11217 	char cdb[CDB_GROUP1] = {
11218 		SCMD_LOG_SENSE_G1,
11219 		0,
11220 		TAPE_ALERT_PAGE | CURRENT_THRESHOLD_VALUES,
11221 		0,
11222 		0,
11223 		0,
11224 		0,
11225 		(char)(sizeof (struct st_tape_alert) >> 8),
11226 		(char)(sizeof (struct st_tape_alert)),
11227 		0
11228 	};
11229 
11230 	GET_SOFT_STATE(dev);
11231 
11232 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
11233 	ta  = kmem_zalloc(sizeof (struct st_tape_alert), KM_SLEEP);
11234 
11235 	com->uscsi_cdb = cdb;
11236 	com->uscsi_cdblen = CDB_GROUP1;
11237 	com->uscsi_bufaddr = (caddr_t)ta;
11238 	com->uscsi_buflen = sizeof (struct st_tape_alert);
11239 	com->uscsi_flags =
11240 		USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ | USCSI_RQENABLE;
11241 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
11242 
11243 	rval = st_ioctl_cmd(dev, com, UIO_SYSSPACE, UIO_SYSSPACE, UIO_SYSSPACE);
11244 
11245 	if (rval || com->uscsi_status || com->uscsi_resid) {
11246 
11247 		rval = -1; /* uscsi-command failed */
11248 
11249 	} else if (ta->log_page.code != TAPE_ALERT_PAGE) {
11250 
11251 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11252 		"Not Alert Log Page returned 0x%X\n", ta->log_page.code);
11253 		rval = -1;
11254 	}
11255 
11256 	length = (ta->log_page.length_hi << 8) + ta->log_page.length_lo;
11257 
11258 
11259 	if (length != TAPE_ALERT_PARAMETER_LENGTH) {
11260 
11261 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11262 		    "TapeAlert length %d\n", length);
11263 	}
11264 
11265 
11266 	for (ix = 0; ix < TAPE_ALERT_MAX_PARA; ix++) {
11267 
11268 		/*
11269 		 * if rval is bad before the first pass don't bother
11270 		 */
11271 		if (ix == 0 && rval != 0) {
11272 
11273 			break;
11274 		}
11275 
11276 		parameter = ((ta->param[ix].log_param.pc_hi << 8) +
11277 			ta->param[ix].log_param.pc_lo);
11278 
11279 		/*
11280 		 * check to see if current parameter is of interest.
11281 		 * CLEAN_FOR_ERRORS is vendor specific to 9840 9940 stk's.
11282 		 */
11283 		if ((parameter == CLEAN_NOW) ||
11284 		    (parameter == CLEAN_PERIODIC) ||
11285 		    ((parameter == CLEAN_FOR_ERRORS) &&
11286 		    (un->un_dp->type == ST_TYPE_STK9840))) {
11287 
11288 			rval = MTF_TAPE_CLN_SUPPORTED;
11289 
11290 			if (ta->param[ix].param_value & 1) {
11291 
11292 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11293 					    "alert_page drive needs clean %d\n",
11294 					    parameter);
11295 				un->un_HeadClean |= TAPE_ALERT_STILL_DIRTY;
11296 				rval |= MTF_TAPE_HEAD_DIRTY;
11297 			}
11298 
11299 		} else if (parameter == CLEANING_MEDIA) {
11300 
11301 			if (ta->param[ix].param_value & 1) {
11302 
11303 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11304 					    "alert_page drive was cleaned\n");
11305 				un->un_HeadClean &= ~TAPE_ALERT_STILL_DIRTY;
11306 			}
11307 		}
11308 
11309 	}
11310 
11311 	/*
11312 	 * Report it as dirty till we see it cleaned
11313 	 */
11314 	if (un->un_HeadClean & TAPE_ALERT_STILL_DIRTY) {
11315 
11316 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11317 			    "alert_page still dirty\n");
11318 		rval |= MTF_TAPE_HEAD_DIRTY;
11319 	}
11320 
11321 	kmem_free(com, sizeof (struct uscsi_cmd));
11322 	kmem_free(ta,  sizeof (struct st_tape_alert));
11323 
11324 	return (rval);
11325 }
11326 
11327 
11328 static int
11329 st_check_sense_clean_bit(dev_t dev)
11330 {
11331 	uchar_t *sensep;
11332 	char cdb[CDB_GROUP0];
11333 	struct uscsi_cmd *com;
11334 	ushort_t byte_pos;
11335 	uchar_t bit_mask;
11336 	unsigned length;
11337 	int index;
11338 	int rval;
11339 
11340 	GET_SOFT_STATE(dev);
11341 
11342 	/*
11343 	 * Since this tape does not support Tape Alert,
11344 	 * we now try to get the cleanbit status via
11345 	 * Request Sense.
11346 	 */
11347 
11348 	if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_1) {
11349 
11350 		index = 0;
11351 
11352 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_2) {
11353 
11354 		index = 1;
11355 
11356 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_3) {
11357 
11358 		index = 2;
11359 
11360 	} else {
11361 
11362 		return (-1);
11363 	}
11364 
11365 	byte_pos  = st_cln_bit_position[index].cln_bit_byte;
11366 	bit_mask  = st_cln_bit_position[index].cln_bit_mask;
11367 	length = byte_pos + 1;
11368 
11369 	com    = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
11370 	sensep = kmem_zalloc(length, KM_SLEEP);
11371 
11372 	cdb[0] = SCMD_REQUEST_SENSE;
11373 	cdb[1] = 0;
11374 	cdb[2] = 0;
11375 	cdb[3] = 0;
11376 	cdb[4] = (char)length;
11377 	cdb[5] = 0;
11378 
11379 	com->uscsi_cdb = cdb;
11380 	com->uscsi_cdblen = CDB_GROUP0;
11381 	com->uscsi_bufaddr = (caddr_t)sensep;
11382 	com->uscsi_buflen = length;
11383 	com->uscsi_flags =
11384 		USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ | USCSI_RQENABLE;
11385 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
11386 
11387 	rval = st_ioctl_cmd(dev, com, UIO_SYSSPACE, UIO_SYSSPACE,
11388 			UIO_SYSSPACE);
11389 
11390 	if (rval || com->uscsi_status || com->uscsi_resid) {
11391 
11392 		rval = -1;
11393 
11394 	} else {
11395 
11396 		rval = MTF_TAPE_CLN_SUPPORTED;
11397 		if ((sensep[byte_pos] & bit_mask) == bit_mask) {
11398 
11399 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11400 				    "sense data says head dirty\n");
11401 			rval |= MTF_TAPE_HEAD_DIRTY;
11402 		}
11403 	}
11404 
11405 	kmem_free(com, sizeof (struct uscsi_cmd));
11406 	kmem_free(sensep, length);
11407 	return (rval);
11408 }
11409 
11410 /*
11411  * st_clear_unit_attention
11412  *
11413  *  	run test unit ready's to clear out outstanding
11414  * 	unit attentions.
11415  * 	returns zero for SUCCESS or the errno from st_cmd call
11416  */
11417 static int
11418 st_clear_unit_attentions(dev_t dev_instance, int max_trys)
11419 {
11420 	int	i    = 0;
11421 	int	rval;
11422 
11423 	do {
11424 		rval = st_cmd(dev_instance, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
11425 	} while ((rval != 0) && (rval != ENXIO) && (++i < max_trys));
11426 	return (rval);
11427 }
11428 
11429 static void
11430 st_calculate_timeouts(struct scsi_tape *un)
11431 {
11432 	if (un->un_dp->non_motion_timeout == 0) {
11433 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
11434 			un->un_dp->non_motion_timeout =
11435 				st_io_time * st_long_timeout_x;
11436 		} else {
11437 			un->un_dp->non_motion_timeout = (ushort_t)st_io_time;
11438 		}
11439 	}
11440 
11441 	if (un->un_dp->io_timeout == 0) {
11442 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
11443 			un->un_dp->io_timeout = st_io_time * st_long_timeout_x;
11444 		} else {
11445 			un->un_dp->io_timeout = (ushort_t)st_io_time;
11446 		}
11447 	}
11448 
11449 	if (un->un_dp->rewind_timeout == 0) {
11450 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
11451 			un->un_dp->rewind_timeout =
11452 				st_space_time * st_long_timeout_x;
11453 		} else {
11454 			un->un_dp->rewind_timeout = (ushort_t)st_space_time;
11455 		}
11456 	}
11457 
11458 	if (un->un_dp->space_timeout == 0) {
11459 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
11460 			un->un_dp->space_timeout =
11461 				st_space_time * st_long_timeout_x;
11462 		} else {
11463 			un->un_dp->space_timeout = (ushort_t)st_space_time;
11464 		}
11465 	}
11466 
11467 	if (un->un_dp->load_timeout == 0) {
11468 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
11469 			un->un_dp->load_timeout =
11470 				st_space_time * st_long_timeout_x;
11471 		} else {
11472 			un->un_dp->load_timeout = (ushort_t)st_space_time;
11473 		}
11474 	}
11475 
11476 	if (un->un_dp->unload_timeout == 0) {
11477 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
11478 			un->un_dp->unload_timeout =
11479 				st_space_time * st_long_timeout_x;
11480 		} else {
11481 			un->un_dp->unload_timeout = (ushort_t)st_space_time;
11482 		}
11483 	}
11484 
11485 	if (un->un_dp->erase_timeout == 0) {
11486 		if (un->un_dp->options & ST_LONG_ERASE) {
11487 			un->un_dp->erase_timeout =
11488 				st_space_time * st_long_space_time_x;
11489 		} else {
11490 			un->un_dp->erase_timeout = (ushort_t)st_space_time;
11491 		}
11492 	}
11493 }
11494 
11495 #if defined(__i386) || defined(__amd64)
11496 
11497 /*
11498  * release contig_mem and wake up waiting thread, if any
11499  */
11500 static void
11501 st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp)
11502 {
11503 	mutex_enter(ST_MUTEX);
11504 
11505 	cp->cm_next = un->un_contig_mem;
11506 	un->un_contig_mem = cp;
11507 	un->un_contig_mem_available_num++;
11508 	cv_broadcast(&un->un_contig_mem_cv);
11509 
11510 	mutex_exit(ST_MUTEX);
11511 }
11512 
11513 /*
11514  * St_get_contig_mem will return a contig_mem if there is one available
11515  * in current system. Otherwise, it will try to alloc one, if the total
11516  * number of contig_mem is within st_max_contig_mem_num.
11517  * It will sleep, if allowed by caller or return NULL, if no contig_mem
11518  * is available for now.
11519  */
11520 static struct contig_mem *
11521 st_get_contig_mem(struct scsi_tape *un, size_t len, int alloc_flags)
11522 {
11523 	size_t rlen;
11524 	struct contig_mem *cp = NULL;
11525 	ddi_acc_handle_t acc_hdl;
11526 	caddr_t addr;
11527 	int big_enough = 0;
11528 	int (*dma_alloc_cb)() = (alloc_flags == KM_SLEEP) ?
11529 		DDI_DMA_SLEEP : DDI_DMA_DONTWAIT;
11530 
11531 	/* Try to get one available contig_mem */
11532 	mutex_enter(ST_MUTEX);
11533 	if (un->un_contig_mem_available_num > 0) {
11534 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
11535 	} else if (un->un_contig_mem_total_num < st_max_contig_mem_num) {
11536 		/*
11537 		 * we failed to get one. we're going to
11538 		 * alloc one more contig_mem for this I/O
11539 		 */
11540 		mutex_exit(ST_MUTEX);
11541 		cp = (struct contig_mem *)kmem_zalloc(
11542 		    sizeof (struct contig_mem) + biosize(),
11543 		    alloc_flags);
11544 		if (cp == NULL) {
11545 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11546 			    "alloc contig_mem failure\n");
11547 			return (NULL); /* cannot get one */
11548 		}
11549 		cp->cm_bp = (struct buf *)
11550 		    (((caddr_t)cp) + sizeof (struct contig_mem));
11551 		bioinit(cp->cm_bp);
11552 		mutex_enter(ST_MUTEX);
11553 		un->un_contig_mem_total_num++; /* one more available */
11554 	} else {
11555 		/*
11556 		 * we failed to get one and we're NOT allowed to
11557 		 * alloc more contig_mem
11558 		 */
11559 		if (alloc_flags == KM_SLEEP) {
11560 			while (un->un_contig_mem_available_num <= 0) {
11561 				cv_wait(&un->un_contig_mem_cv,
11562 				    ST_MUTEX);
11563 			}
11564 			ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
11565 		} else {
11566 			mutex_exit(ST_MUTEX);
11567 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11568 			    "alloc contig_mem failure\n");
11569 			return (NULL); /* cannot get one */
11570 		}
11571 	}
11572 	mutex_exit(ST_MUTEX);
11573 
11574 	/* We need to check if this block of mem is big enough for this I/O */
11575 	if (cp->cm_len < len) {
11576 		/* not big enough, need to alloc a new one */
11577 		if (ddi_dma_mem_alloc(un->un_contig_mem_hdl, len, &st_acc_attr,
11578 			DDI_DMA_STREAMING, dma_alloc_cb, NULL,
11579 			&addr, &rlen, &acc_hdl) != DDI_SUCCESS) {
11580 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11581 			    "alloc contig_mem failure: not enough mem\n");
11582 			st_release_contig_mem(un, cp);
11583 			cp = NULL;
11584 		} else {
11585 			if (cp->cm_addr) {
11586 				/* release previous one before attach new one */
11587 				ddi_dma_mem_free(&cp->cm_acc_hdl);
11588 			}
11589 			mutex_enter(ST_MUTEX);
11590 			un->un_max_contig_mem_len =
11591 			    un->un_max_contig_mem_len >= len ?
11592 			    un->un_max_contig_mem_len : len;
11593 			mutex_exit(ST_MUTEX);
11594 
11595 			/* attach new mem to this cp */
11596 			cp->cm_addr = addr;
11597 			cp->cm_acc_hdl = acc_hdl;
11598 			cp->cm_len = len;
11599 
11600 			goto alloc_ok; /* get one usable cp */
11601 		}
11602 	} else {
11603 		goto alloc_ok; /* get one usable cp */
11604 	}
11605 
11606 	/* cannot find/alloc a usable cp, when we get here */
11607 
11608 	if ((un->un_max_contig_mem_len < len) ||
11609 	    (alloc_flags != KM_SLEEP)) {
11610 		return (NULL);
11611 	}
11612 
11613 	/*
11614 	 * we're allowed to sleep, and there is one big enough
11615 	 * contig mem in the system, which is currently in use,
11616 	 * wait for it...
11617 	 */
11618 	mutex_enter(ST_MUTEX);
11619 	big_enough = 1;
11620 	do {
11621 		cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
11622 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
11623 	} while (cp == NULL);
11624 	mutex_exit(ST_MUTEX);
11625 
11626 	/* we get the big enough contig mem, finally */
11627 
11628 alloc_ok:
11629 	/* init bp attached to this cp */
11630 	bioreset(cp->cm_bp);
11631 	cp->cm_bp->b_un.b_addr = cp->cm_addr;
11632 	cp->cm_bp->b_private = (void *)cp;
11633 
11634 	return (cp);
11635 }
11636 
11637 /*
11638  * this is the biodone func for the bp used in big block I/O
11639  */
11640 static int
11641 st_bigblk_xfer_done(struct buf *bp)
11642 {
11643 	struct contig_mem *cp;
11644 	struct buf *orig_bp;
11645 	int remapped = 0;
11646 	int ioerr;
11647 	struct scsi_tape *un;
11648 
11649 	/* sanity check */
11650 	if (bp == NULL) {
11651 		return (DDI_FAILURE);
11652 	}
11653 
11654 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
11655 	if (un == NULL) {
11656 		return (DDI_FAILURE);
11657 	}
11658 
11659 	cp = (struct contig_mem *)bp->b_private;
11660 	orig_bp = cp->cm_bp; /* get back the bp we have replaced */
11661 	cp->cm_bp = bp;
11662 
11663 	/* special handling for special I/O */
11664 	if (cp->cm_use_sbuf) {
11665 		ASSERT(un->un_sbuf_busy);
11666 		un->un_sbufp = orig_bp;
11667 		cp->cm_use_sbuf = 0;
11668 	}
11669 
11670 	orig_bp->b_resid = bp->b_resid;
11671 	ioerr = geterror(bp);
11672 	if (ioerr != 0) {
11673 		bioerror(orig_bp, ioerr);
11674 	} else if (orig_bp->b_flags & B_READ) {
11675 		/* copy data back to original bp */
11676 		if (orig_bp->b_flags & (B_PHYS | B_PAGEIO)) {
11677 			bp_mapin(orig_bp);
11678 			remapped = 1;
11679 		}
11680 		bcopy(bp->b_un.b_addr, orig_bp->b_un.b_addr,
11681 			bp->b_bcount - bp->b_resid);
11682 		if (remapped)
11683 			bp_mapout(orig_bp);
11684 	}
11685 
11686 	st_release_contig_mem(un, cp);
11687 
11688 	biodone(orig_bp);
11689 
11690 	return (DDI_SUCCESS);
11691 }
11692 
11693 /*
11694  * We use this func to replace original bp that may not be able to do I/O
11695  * in big block size with one that can
11696  */
11697 static struct buf *
11698 st_get_bigblk_bp(struct buf *bp)
11699 {
11700 	struct contig_mem *cp;
11701 	struct scsi_tape *un;
11702 	struct buf *cont_bp;
11703 	int remapped = 0;
11704 
11705 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
11706 	if (un == NULL) {
11707 		return (bp);
11708 	}
11709 
11710 	/* try to get one contig_mem */
11711 	cp = st_get_contig_mem(un, bp->b_bcount, KM_SLEEP);
11712 	if (!cp) {
11713 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
11714 			"Cannot alloc contig buf for I/O for %lu blk size",
11715 			bp->b_bcount);
11716 		return (bp);
11717 	}
11718 	cont_bp = cp->cm_bp;
11719 	cp->cm_bp = bp;
11720 
11721 	/* make sure that we "are" using un_sbufp for special I/O */
11722 	if (bp == un->un_sbufp) {
11723 		ASSERT(un->un_sbuf_busy);
11724 		un->un_sbufp = cont_bp;
11725 		cp->cm_use_sbuf = 1;
11726 	}
11727 
11728 	/* clone bp */
11729 	cont_bp->b_bcount = bp->b_bcount;
11730 	cont_bp->b_resid = bp->b_resid;
11731 	cont_bp->b_iodone = st_bigblk_xfer_done;
11732 	cont_bp->b_file = bp->b_file;
11733 	cont_bp->b_offset = bp->b_offset;
11734 	cont_bp->b_dip = bp->b_dip;
11735 	cont_bp->b_error = 0;
11736 	cont_bp->b_proc = NULL;
11737 	cont_bp->b_flags = bp->b_flags & ~(B_PAGEIO | B_PHYS | B_SHADOW);
11738 	cont_bp->b_shadow = NULL;
11739 	cont_bp->b_pages = NULL;
11740 	cont_bp->b_edev = bp->b_edev;
11741 	cont_bp->b_dev = bp->b_dev;
11742 	cont_bp->b_lblkno = bp->b_lblkno;
11743 	cont_bp->b_forw = bp->b_forw;
11744 	cont_bp->b_back = bp->b_back;
11745 	cont_bp->av_forw = bp->av_forw;
11746 	cont_bp->av_back = bp->av_back;
11747 	cont_bp->b_bufsize = bp->b_bufsize;
11748 
11749 	/* get data in original bp */
11750 	if (bp->b_flags & B_WRITE) {
11751 		if (bp->b_flags & (B_PHYS | B_PAGEIO)) {
11752 			bp_mapin(bp);
11753 			remapped = 1;
11754 		}
11755 		bcopy(bp->b_un.b_addr, cont_bp->b_un.b_addr, bp->b_bcount);
11756 		if (remapped)
11757 			bp_mapout(bp);
11758 	}
11759 
11760 	return (cont_bp);
11761 }
11762 #endif
11763