xref: /illumos-gate/usr/src/uts/common/io/scsi/targets/st.c (revision fa4c0ec8)
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 (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2007 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/kstat.h>
43 #include <sys/ddidmareq.h>
44 #include <sys/ddi.h>
45 #include <sys/sunddi.h>
46 
47 #define	IOSP	KSTAT_IO_PTR(un->un_stats)
48 /*
49  * stats maintained only for reads/writes as commands
50  * like rewind etc skew the wait/busy times
51  */
52 #define	IS_RW(bp) 	((bp)->b_bcount > 0)
53 #define	ST_DO_KSTATS(bp, kstat_function) \
54 	if ((bp != un->un_sbufp) && un->un_stats && IS_RW(bp)) { \
55 		kstat_function(IOSP); \
56 	}
57 
58 #define	ST_DO_ERRSTATS(un, x)  \
59 	if (un->un_errstats) { \
60 		struct st_errstats *stp; \
61 		stp = (struct st_errstats *)un->un_errstats->ks_data; \
62 		stp->x.value.ul++; \
63 	}
64 
65 #define	FILL_SCSI1_LUN(devp, pkt) 					\
66 	if ((devp)->sd_inq->inq_ansi == 0x1) {				\
67 		int _lun;						\
68 		_lun = ddi_prop_get_int(DDI_DEV_T_ANY, (devp)->sd_dev,	\
69 		    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_LUN, 0);		\
70 		if (_lun > 0) {						\
71 			((union scsi_cdb *)(pkt)->pkt_cdbp)->scc_lun =	\
72 			    _lun;					\
73 		}							\
74 	}
75 
76 /*
77  * get an available contig mem header, cp.
78  * when big_enough is true, we will return NULL, if no big enough
79  * contig mem is found.
80  * when big_enough is false, we will try to find cp containing big
81  * enough contig mem. if not found, we will ruturn the last cp available.
82  *
83  * used by st_get_contig_mem()
84  */
85 #define	ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough) {		\
86 	struct contig_mem *tmp_cp = NULL;				\
87 	for ((cp) = (un)->un_contig_mem;				\
88 	    (cp) != NULL;						\
89 	    tmp_cp = (cp), (cp) = (cp)->cm_next) { 			\
90 		if (((cp)->cm_len >= (len)) || 				\
91 		    (!(big_enough) && ((cp)->cm_next == NULL))) { 	\
92 			if (tmp_cp == NULL) { 				\
93 				(un)->un_contig_mem = (cp)->cm_next; 	\
94 			} else { 					\
95 				tmp_cp->cm_next = (cp)->cm_next; 	\
96 			} 						\
97 			(cp)->cm_next = NULL; 				\
98 			(un)->un_contig_mem_available_num--; 		\
99 			break; 						\
100 		} 							\
101 	} 								\
102 }
103 
104 #define	ST_NUM_MEMBERS(array)	(sizeof (array) / sizeof (array[0]))
105 #define	COPY_POS(dest, source) bcopy(source, dest, sizeof (tapepos_t))
106 
107 #define	ONE_K	1024
108 
109 /*
110  * Global External Data Definitions
111  */
112 extern struct scsi_key_strings scsi_cmds[];
113 extern uchar_t	scsi_cdb_size[];
114 
115 /*
116  * Local Static Data
117  */
118 static void *st_state;
119 static char *const st_label = "st";
120 
121 #if defined(__i386) || defined(__amd64)
122 /*
123  * We need to use below DMA attr to alloc physically contiguous
124  * memory to do I/O in big block size
125  */
126 static ddi_dma_attr_t st_contig_mem_dma_attr = {
127 	DMA_ATTR_V0,    /* version number */
128 	0x0,		/* lowest usable address */
129 	0xFFFFFFFFull,  /* high DMA address range */
130 	0xFFFFFFFFull,  /* DMA counter register */
131 	1,		/* DMA address alignment */
132 	1,		/* DMA burstsizes */
133 	1,		/* min effective DMA size */
134 	0xFFFFFFFFull,  /* max DMA xfer size */
135 	0xFFFFFFFFull,  /* segment boundary */
136 	1,		/* s/g list length */
137 	1,		/* granularity of device */
138 	0		/* DMA transfer flags */
139 };
140 
141 static ddi_device_acc_attr_t st_acc_attr = {
142 	DDI_DEVICE_ATTR_V0,
143 	DDI_NEVERSWAP_ACC,
144 	DDI_STRICTORDER_ACC
145 };
146 
147 /* set limitation for the number of contig_mem */
148 static int st_max_contig_mem_num = ST_MAX_CONTIG_MEM_NUM;
149 #endif
150 
151 /*
152  * Tunable parameters
153  *
154  * DISCLAIMER
155  * ----------
156  * These parameters are intended for use only in system testing; if you use
157  * them in production systems, you do so at your own risk. Altering any
158  * variable not listed below may cause unpredictable system behavior.
159  *
160  * st_check_media_time
161  *
162  *   Three second state check
163  *
164  * st_allow_large_xfer
165  *
166  *   Gated with ST_NO_RECSIZE_LIMIT
167  *
168  *   0 - Transfers larger than 64KB will not be allowed
169  *       regardless of the setting of ST_NO_RECSIZE_LIMIT
170  *   1 - Transfers larger than 64KB will be allowed
171  *       if ST_NO_RECSIZE_LIMIT is TRUE for the drive
172  *
173  * st_report_soft_errors_on_close
174  *
175  *  Gated with ST_SOFT_ERROR_REPORTING
176  *
177  *  0 - Errors will not be reported on close regardless
178  *      of the setting of ST_SOFT_ERROR_REPORTING
179  *
180  *  1 - Errors will be reported on close if
181  *      ST_SOFT_ERROR_REPORTING is TRUE for the drive
182  */
183 static int st_selection_retry_count = ST_SEL_RETRY_COUNT;
184 static int st_retry_count	= ST_RETRY_COUNT;
185 
186 static int st_io_time		= ST_IO_TIME;
187 static int st_long_timeout_x	= ST_LONG_TIMEOUT_X;
188 
189 static int st_space_time	= ST_SPACE_TIME;
190 static int st_long_space_time_x	= ST_LONG_SPACE_TIME_X;
191 
192 static int st_error_level	= SCSI_ERR_RETRYABLE;
193 static int st_check_media_time	= 3000000;	/* 3 Second State Check */
194 
195 static int st_max_throttle	= ST_MAX_THROTTLE;
196 
197 static clock_t st_wait_cmds_complete = ST_WAIT_CMDS_COMPLETE;
198 
199 static int st_allow_large_xfer = 1;
200 static int st_report_soft_errors_on_close = 1;
201 
202 /*
203  * End of tunable parameters list
204  */
205 
206 
207 
208 /*
209  * Asynchronous I/O and persistent errors, refer to PSARC/1995/228
210  *
211  * Asynchronous I/O's main offering is that it is a non-blocking way to do
212  * reads and writes.  The driver will queue up all the requests it gets and
213  * have them ready to transport to the HBA.  Unfortunately, we cannot always
214  * just ship the I/O requests to the HBA, as there errors and exceptions
215  * that may happen when we don't want the HBA to continue.  Therein comes
216  * the flush-on-errors capability.  If the HBA supports it, then st will
217  * send in st_max_throttle I/O requests at the same time.
218  *
219  * Persistent errors : This was also reasonably simple.  In the interrupt
220  * routines, if there was an error or exception (FM, LEOT, media error,
221  * transport error), the persistent error bits are set and shuts everything
222  * down, but setting the throttle to zero.  If we hit and exception in the
223  * HBA, and flush-on-errors were set, we wait for all outstanding I/O's to
224  * come back (with CMD_ABORTED), then flush all bp's in the wait queue with
225  * the appropriate error, and this will preserve order. Of course, depending
226  * on the exception we have to show a zero read or write before we show
227  * errors back to the application.
228  */
229 
230 extern const int st_ndrivetypes;	/* defined in st_conf.c */
231 extern const struct st_drivetype st_drivetypes[];
232 extern const char st_conf_version[];
233 
234 #ifdef STDEBUG
235 static int st_soft_error_report_debug = 0;
236 volatile int st_debug = 0;
237 #endif
238 
239 #define	ST_MT02_NAME	"Emulex  MT02 QIC-11/24  "
240 
241 static const struct driver_minor_data {
242 	char	*name;
243 	int	minor;
244 } st_minor_data[] = {
245 	/*
246 	 * The top 4 entries are for the default densities,
247 	 * don't alter their position.
248 	 */
249 	{"",	0},
250 	{"n",	MT_NOREWIND},
251 	{"b",	MT_BSD},
252 	{"bn",	MT_NOREWIND | MT_BSD},
253 	{"l",	MT_DENSITY1},
254 	{"m",	MT_DENSITY2},
255 	{"h",	MT_DENSITY3},
256 	{"c",	MT_DENSITY4},
257 	{"u",	MT_DENSITY4},
258 	{"ln",	MT_DENSITY1 | MT_NOREWIND},
259 	{"mn",	MT_DENSITY2 | MT_NOREWIND},
260 	{"hn",	MT_DENSITY3 | MT_NOREWIND},
261 	{"cn",	MT_DENSITY4 | MT_NOREWIND},
262 	{"un",	MT_DENSITY4 | MT_NOREWIND},
263 	{"lb",	MT_DENSITY1 | MT_BSD},
264 	{"mb",	MT_DENSITY2 | MT_BSD},
265 	{"hb",	MT_DENSITY3 | MT_BSD},
266 	{"cb",	MT_DENSITY4 | MT_BSD},
267 	{"ub",	MT_DENSITY4 | MT_BSD},
268 	{"lbn",	MT_DENSITY1 | MT_NOREWIND | MT_BSD},
269 	{"mbn",	MT_DENSITY2 | MT_NOREWIND | MT_BSD},
270 	{"hbn",	MT_DENSITY3 | MT_NOREWIND | MT_BSD},
271 	{"cbn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD},
272 	{"ubn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD}
273 };
274 
275 /* strings used in many debug and warning messages */
276 static const char wr_str[]  = "write";
277 static const char rd_str[]  = "read";
278 static const char wrg_str[] = "writing";
279 static const char rdg_str[] = "reading";
280 static const char *space_strs[] = {
281 	"records",
282 	"filemarks",
283 	"sequential filemarks",
284 	"eod",
285 	"setmarks",
286 	"sequential setmarks",
287 	"Reserved",
288 	"Reserved"
289 };
290 
291 /* default density offsets in the table above */
292 #define	DEF_BLANK	0
293 #define	DEF_NOREWIND	1
294 #define	DEF_BSD		2
295 #define	DEF_BSD_NR	3
296 
297 /* Sense Key, ASC/ASCQ for which tape ejection is needed */
298 
299 static struct tape_failure_code {
300 	uchar_t key;
301 	uchar_t add_code;
302 	uchar_t qual_code;
303 } st_tape_failure_code[] = {
304 	{ KEY_HARDWARE_ERROR, 0x15, 0x01},
305 	{ KEY_HARDWARE_ERROR, 0x44, 0x00},
306 	{ KEY_HARDWARE_ERROR, 0x53, 0x00},
307 	{ KEY_HARDWARE_ERROR, 0x53, 0x01},
308 	{ KEY_NOT_READY, 0x53, 0x00},
309 	{ 0xff}
310 };
311 
312 /*  clean bit position and mask */
313 
314 static struct cln_bit_position {
315 	ushort_t cln_bit_byte;
316 	uchar_t cln_bit_mask;
317 } st_cln_bit_position[] = {
318 	{ 21, 0x08},
319 	{ 70, 0xc0},
320 	{ 18, 0x81}  /* 80 bit indicates in bit mode, 1 bit clean light is on */
321 };
322 
323 /*
324  * architecture dependent allocation restrictions. For x86, we'll set
325  * dma_attr_addr_hi to st_max_phys_addr and dma_attr_sgllen to
326  * st_sgl_size during _init().
327  */
328 #if defined(__sparc)
329 static ddi_dma_attr_t st_alloc_attr = {
330 	DMA_ATTR_V0,	/* version number */
331 	0x0,		/* lowest usable address */
332 	0xFFFFFFFFull,	/* high DMA address range */
333 	0xFFFFFFFFull,	/* DMA counter register */
334 	1,		/* DMA address alignment */
335 	1,		/* DMA burstsizes */
336 	1,		/* min effective DMA size */
337 	0xFFFFFFFFull,	/* max DMA xfer size */
338 	0xFFFFFFFFull,	/* segment boundary */
339 	1,		/* s/g list length */
340 	512,		/* granularity of device */
341 	0		/* DMA transfer flags */
342 };
343 #elif defined(__x86)
344 static ddi_dma_attr_t st_alloc_attr = {
345 	DMA_ATTR_V0,	/* version number */
346 	0x0,		/* lowest usable address */
347 	0x0,		/* high DMA address range [set in _init()] */
348 	0xFFFFull,	/* DMA counter register */
349 	512,		/* DMA address alignment */
350 	1,		/* DMA burstsizes */
351 	1,		/* min effective DMA size */
352 	0xFFFFFFFFull,	/* max DMA xfer size */
353 	0xFFFFFFFFull,  /* segment boundary */
354 	0,		/* s/g list length */
355 	512,		/* granularity of device [set in _init()] */
356 	0		/* DMA transfer flags */
357 };
358 uint64_t st_max_phys_addr = 0xFFFFFFFFull;
359 int st_sgl_size = 0xF;
360 
361 #endif
362 
363 /*
364  * Configuration Data:
365  *
366  * Device driver ops vector
367  */
368 static int st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p);
369 static int st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p);
370 static int st_read(dev_t  dev,  struct   uio   *uio_p,   cred_t *cred_p);
371 static int st_write(dev_t  dev,  struct  uio   *uio_p,   cred_t *cred_p);
372 static int st_open(dev_t  *devp,  int  flag,  int  otyp,  cred_t *cred_p);
373 static int st_close(dev_t  dev,  int  flag,  int  otyp,  cred_t *cred_p);
374 static int st_strategy(struct buf *bp);
375 static int st_ioctl(dev_t dev, int cmd, intptr_t arg, int  flag,
376 	cred_t *cred_p, int *rval_p);
377 extern int nulldev(), nodev();
378 
379 static struct cb_ops st_cb_ops = {
380 	st_open,		/* open */
381 	st_close,		/* close */
382 	st_strategy,		/* strategy */
383 	nodev,			/* print */
384 	nodev,			/* dump */
385 	st_read,		/* read */
386 	st_write,		/* write */
387 	st_ioctl,		/* ioctl */
388 	nodev,			/* devmap */
389 	nodev,			/* mmap */
390 	nodev,			/* segmap */
391 	nochpoll,		/* poll */
392 	ddi_prop_op,		/* cb_prop_op */
393 	0,			/* streamtab  */
394 	D_64BIT | D_MP | D_NEW | D_HOTPLUG |
395 	D_OPEN_RETURNS_EINTR,	/* cb_flag */
396 	CB_REV,			/* cb_rev */
397 	st_aread, 		/* async I/O read entry point */
398 	st_awrite		/* async I/O write entry point */
399 
400 };
401 
402 static int stinfo(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg,
403 		void **result);
404 static int st_probe(dev_info_t *dev);
405 static int st_attach(dev_info_t *dev, ddi_attach_cmd_t cmd);
406 static int st_detach(dev_info_t *dev, ddi_detach_cmd_t cmd);
407 
408 static struct dev_ops st_ops = {
409 	DEVO_REV,		/* devo_rev, */
410 	0,			/* refcnt  */
411 	stinfo,			/* info */
412 	nulldev,		/* identify */
413 	st_probe,		/* probe */
414 	st_attach,		/* attach */
415 	st_detach,		/* detach */
416 	nodev,			/* reset */
417 	&st_cb_ops,		/* driver operations */
418 	(struct bus_ops *)0,	/* bus operations */
419 	nulldev			/* power */
420 };
421 
422 /*
423  * Local Function Declarations
424  */
425 static char *st_print_scsi_cmd(char cmd);
426 static void st_print_cdb(dev_info_t *dip, char *label, uint_t level,
427     char *title, char *cdb);
428 static void st_clean_print(dev_info_t *dev, char *label, uint_t level,
429 	char *title, char *data, int len);
430 static int st_doattach(struct scsi_device *devp, int (*canwait)());
431 static void st_known_tape_type(struct scsi_tape *un);
432 static int st_get_conf_from_st_dot_conf(struct scsi_tape *, char *,
433     struct st_drivetype *);
434 static int st_get_conf_from_st_conf_dot_c(struct scsi_tape *, char *,
435     struct st_drivetype *);
436 static int st_get_default_conf(struct scsi_tape *, char *,
437     struct st_drivetype *);
438 static int st_rw(dev_t dev, struct uio *uio, int flag);
439 static int st_arw(dev_t dev, struct aio_req *aio, int flag);
440 static int st_find_eod(dev_t dev);
441 static int st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag);
442 static int st_ioctl_cmd(dev_t dev, struct uscsi_cmd *, int flag);
443 static int st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag);
444 static int st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag);
445 static int st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop);
446 static void st_start(struct scsi_tape *un);
447 static int st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
448     clock_t timeout_interval);
449 static int st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
450     clock_t timeout_interval);
451 static int st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp);
452 static void st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp);
453 static void st_init(struct scsi_tape *un);
454 static void st_make_cmd(struct scsi_tape *un, struct buf *bp,
455     int (*func)(caddr_t));
456 static void st_make_uscsi_cmd(struct scsi_tape *, struct uscsi_cmd *,
457     struct buf *bp, int (*func)(caddr_t));
458 static void st_intr(struct scsi_pkt *pkt);
459 static void st_set_state(struct scsi_tape *un);
460 static void st_test_append(struct buf *bp);
461 static int st_runout(caddr_t);
462 static int st_cmd(dev_t dev, int com, int count, int wait);
463 static int st_set_compression(struct scsi_tape *un);
464 static int st_write_fm(dev_t dev, int wfm);
465 static int st_determine_generic(dev_t dev);
466 static int st_determine_density(dev_t dev, int rw);
467 static int st_get_density(dev_t dev);
468 static int st_set_density(dev_t dev);
469 static int st_loadtape(dev_t dev);
470 static int st_modesense(struct scsi_tape *un);
471 static int st_modeselect(struct scsi_tape *un);
472 static int st_handle_incomplete(struct scsi_tape *un, struct buf *bp);
473 static int st_wrongtapetype(struct scsi_tape *un);
474 static int st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt);
475 static int st_handle_sense(struct scsi_tape *un, struct buf *bp);
476 static int st_handle_autosense(struct scsi_tape *un, struct buf *bp);
477 static int st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
478     struct scsi_status *);
479 static int st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag);
480 static void st_update_error_stack(struct scsi_tape *un, struct scsi_pkt *pkt,
481     struct scsi_arq_status *cmd);
482 static void st_empty_error_stack(struct scsi_tape *un);
483 static int st_report_soft_errors(dev_t dev, int flag);
484 static void st_delayed_cv_broadcast(void *arg);
485 static int st_check_media(dev_t dev, enum mtio_state state);
486 static int st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
487 static void st_intr_restart(void *arg);
488 static void st_start_restart(void *arg);
489 static int st_gen_mode_sense(struct scsi_tape *un, int page,
490     struct seq_mode *page_data, int page_size);
491 static int st_change_block_size(dev_t dev, uint32_t nblksz);
492 static int st_gen_mode_select(struct scsi_tape *un, struct seq_mode *page_data,
493     int page_size);
494 static int st_tape_init(dev_t dev);
495 static void st_flush(struct scsi_tape *un);
496 static void st_set_pe_errno(struct scsi_tape *un);
497 static void st_hba_unflush(struct scsi_tape *un);
498 static void st_turn_pe_on(struct scsi_tape *un);
499 static void st_turn_pe_off(struct scsi_tape *un);
500 static void st_set_pe_flag(struct scsi_tape *un);
501 static void st_clear_pe(struct scsi_tape *un);
502 static void st_wait_for_io(struct scsi_tape *un);
503 static int st_set_devconfig_page(struct scsi_tape *un, int compression_on);
504 static int st_set_datacomp_page(struct scsi_tape *un, int compression_on);
505 static int st_reserve_release(struct scsi_tape *un, int command);
506 static int st_check_cdb_for_need_to_reserve(struct scsi_tape *un, caddr_t cdb);
507 static int st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd,
508     int count);
509 static int st_take_ownership(dev_t dev);
510 static int st_check_asc_ascq(struct scsi_tape *un);
511 static int st_check_clean_bit(dev_t dev);
512 static int st_check_alert_flags(dev_t dev);
513 static int st_check_sequential_clean_bit(dev_t dev);
514 static int st_check_sense_clean_bit(dev_t dev);
515 static int st_clear_unit_attentions(dev_t dev_instance, int max_trys);
516 static void st_calculate_timeouts(struct scsi_tape *un);
517 static writablity st_is_drive_worm(struct scsi_tape *un);
518 static int st_read_attributes(struct scsi_tape *un, uint16_t attribute,
519     caddr_t buf, size_t size);
520 static int st_get_special_inquiry(struct scsi_tape *un, uchar_t size,
521     caddr_t dest, uchar_t page);
522 static int st_update_block_pos(struct scsi_tape *un);
523 static int st_interpret_read_pos(struct scsi_tape *un, read_p_types type,
524     size_t data_sz, caddr_t responce);
525 static int st_get_read_pos(struct scsi_tape *un, buf_t *bp);
526 static int st_logical_block_locate(struct scsi_tape *un, uint64_t lblk,
527     uchar_t partition);
528 static int st_mtfsf_ioctl(struct scsi_tape *un, int files);
529 static int st_mtfsr_ioctl(struct scsi_tape *un, int count);
530 static int st_mtbsf_ioctl(struct scsi_tape *un, int files);
531 static int st_mtnbsf_ioctl(struct scsi_tape *un, int count);
532 static int st_mtbsr_ioctl(struct scsi_tape *un, int num);
533 static int st_mtfsfm_ioctl(struct scsi_tape *un, int cnt);
534 static int st_mtbsfm_ioctl(struct scsi_tape *un, int cnt);
535 static int st_backward_space_files(struct scsi_tape *un, int count,
536     int infront);
537 static int st_forward_space_files(struct scsi_tape *un, int files);
538 static int st_scenic_route_to_begining_of_file(struct scsi_tape *un,
539     int32_t fileno);
540 static int st_space_to_begining_of_file(struct scsi_tape *un);
541 static int st_space_records(struct scsi_tape *un, int records);
542 
543 #if defined(__i386) || defined(__amd64)
544 /*
545  * routines for I/O in big block size
546  */
547 static void st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp);
548 static struct contig_mem *st_get_contig_mem(struct scsi_tape *un, size_t len,
549     int alloc_flags);
550 static int st_bigblk_xfer_done(struct buf *bp);
551 static struct buf *st_get_bigblk_bp(struct buf *bp);
552 #endif
553 static void st_print_position(struct scsi_tape *un, const char *comment,
554     tapepos_t *pos);
555 
556 /*
557  * error statistics create/update functions
558  */
559 static int st_create_errstats(struct scsi_tape *, int);
560 static int st_validate_tapemarks(struct scsi_tape *un, tapepos_t *pos);
561 
562 #ifdef STDEBUG
563 static void st_debug_cmds(struct scsi_tape *un, int com, int count, int wait);
564 static char *st_dev_name(dev_t dev);
565 #endif /* STDEBUG */
566 
567 #if !defined(lint)
568 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt",
569     scsi_pkt buf uio scsi_cdb uscsi_cmd))
570 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", scsi_extended_sense scsi_status))
571 _NOTE(SCHEME_PROTECTS_DATA("stable data", scsi_device))
572 _NOTE(DATA_READABLE_WITHOUT_LOCK(st_drivetype scsi_address))
573 #endif
574 
575 /*
576  * autoconfiguration routines.
577  */
578 char _depends_on[] = "misc/scsi";
579 
580 static struct modldrv modldrv = {
581 	&mod_driverops,		/* Type of module. This one is a driver */
582 	"SCSI tape Driver %I%", /* Name of the module. */
583 	&st_ops			/* driver ops */
584 };
585 
586 static struct modlinkage modlinkage = {
587 	MODREV_1, &modldrv, NULL
588 };
589 
590 /*
591  * Notes on Post Reset Behavior in the tape driver:
592  *
593  * When the tape drive is opened, the driver  attempts  to make sure that
594  * the tape head is positioned exactly where it was left when it was last
595  * closed  provided  the  medium  is not  changed.  If the tape  drive is
596  * opened in O_NDELAY mode, the repositioning  (if necessary for any loss
597  * of position due to reset) will happen when the first tape operation or
598  * I/O occurs.  The repositioning (if required) may not be possible under
599  * certain situations such as when the device firmware not able to report
600  * the medium  change in the REQUEST  SENSE data  because of a reset or a
601  * misbehaving  bus  not  allowing  the  reposition  to  happen.  In such
602  * extraordinary  situations, where the driver fails to position the head
603  * at its  original  position,  it will fail the open the first  time, to
604  * save the applications from overwriting the data.  All further attempts
605  * to open the tape device will result in the driver  attempting  to load
606  * the  tape at BOT  (beginning  of  tape).  Also a  warning  message  to
607  * indicate  that further  attempts to open the tape device may result in
608  * the tape being  loaded at BOT will be printed on the  console.  If the
609  * tape  device is opened  in  O_NDELAY  mode,  failure  to  restore  the
610  * original tape head  position,  will result in the failure of the first
611  * tape  operation  or I/O,  Further,  the  driver  will  invalidate  its
612  * internal tape position  which will  necessitate  the  applications  to
613  * validate the position by using either a tape  positioning  ioctl (such
614  * as MTREW) or closing and reopening the tape device.
615  *
616  */
617 
618 int
619 _init(void)
620 {
621 	int	e;
622 
623 	if (((e = ddi_soft_state_init(&st_state,
624 	    sizeof (struct scsi_tape), ST_MAXUNIT)) != 0)) {
625 		return (e);
626 	}
627 
628 	if ((e = mod_install(&modlinkage)) != 0) {
629 		ddi_soft_state_fini(&st_state);
630 	}
631 
632 #if defined(__x86)
633 	/* set the max physical address for iob allocs on x86 */
634 	st_alloc_attr.dma_attr_addr_hi = st_max_phys_addr;
635 
636 	/*
637 	 * set the sgllen for iob allocs on x86. If this is set less than
638 	 * the number of pages the buffer will take (taking into account
639 	 * alignment), it would force the allocator to try and allocate
640 	 * contiguous pages.
641 	 */
642 	st_alloc_attr.dma_attr_sgllen = st_sgl_size;
643 #endif
644 
645 	return (e);
646 }
647 
648 int
649 _fini(void)
650 {
651 	int e;
652 
653 	if ((e = mod_remove(&modlinkage)) != 0) {
654 		return (e);
655 	}
656 
657 	ddi_soft_state_fini(&st_state);
658 
659 	return (e);
660 }
661 
662 int
663 _info(struct modinfo *modinfop)
664 {
665 	return (mod_info(&modlinkage, modinfop));
666 }
667 
668 
669 static int
670 st_probe(dev_info_t *devi)
671 {
672 	int instance;
673 	struct scsi_device *devp;
674 	int rval;
675 
676 #if !defined(__sparc)
677 	char    *tape_prop;
678 	int	tape_prop_len;
679 #endif
680 
681 	ST_ENTR(devi, st_probe);
682 
683 	/* If self identifying device */
684 	if (ddi_dev_is_sid(devi) == DDI_SUCCESS) {
685 		return (DDI_PROBE_DONTCARE);
686 	}
687 
688 #if !defined(__sparc)
689 	/*
690 	 * Since some x86 HBAs have devnodes that look like SCSI as
691 	 * far as we can tell but aren't really SCSI (DADK, like mlx)
692 	 * we check for the presence of the "tape" property.
693 	 */
694 	if (ddi_prop_op(DDI_DEV_T_NONE, devi, PROP_LEN_AND_VAL_ALLOC,
695 	    DDI_PROP_CANSLEEP, "tape",
696 	    (caddr_t)&tape_prop, &tape_prop_len) != DDI_PROP_SUCCESS) {
697 		return (DDI_PROBE_FAILURE);
698 	}
699 	if (strncmp(tape_prop, "sctp", tape_prop_len) != 0) {
700 		kmem_free(tape_prop, tape_prop_len);
701 		return (DDI_PROBE_FAILURE);
702 	}
703 	kmem_free(tape_prop, tape_prop_len);
704 #endif
705 
706 	devp = ddi_get_driver_private(devi);
707 	instance = ddi_get_instance(devi);
708 
709 	if (ddi_get_soft_state(st_state, instance) != NULL) {
710 		return (DDI_PROBE_PARTIAL);
711 	}
712 
713 
714 	/*
715 	 * Turn around and call probe routine to see whether
716 	 * we actually have a tape at this SCSI nexus.
717 	 */
718 	if (scsi_probe(devp, NULL_FUNC) == SCSIPROBE_EXISTS) {
719 
720 		/*
721 		 * In checking the whole inq_dtype byte we are looking at both
722 		 * the Peripheral Qualifier and the Peripheral Device Type.
723 		 * For this driver we are only interested in sequential devices
724 		 * that are connected or capable if connecting to this logical
725 		 * unit.
726 		 */
727 		if (devp->sd_inq->inq_dtype ==
728 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
729 			ST_DEBUG6(devi, st_label, SCSI_DEBUG,
730 			    "probe exists\n");
731 			rval = DDI_PROBE_SUCCESS;
732 		} else {
733 			rval = DDI_PROBE_FAILURE;
734 		}
735 	} else {
736 		ST_DEBUG6(devi, st_label, SCSI_DEBUG,
737 		    "probe failure: nothing there\n");
738 		rval = DDI_PROBE_FAILURE;
739 	}
740 	scsi_unprobe(devp);
741 	return (rval);
742 }
743 
744 static int
745 st_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
746 {
747 	int 	instance;
748 	int	wide;
749 	int 	dev_instance;
750 	int	ret_status;
751 	struct	scsi_device *devp;
752 	int	node_ix;
753 	struct	scsi_tape *un;
754 
755 	ST_ENTR(devi, st_attach);
756 
757 	devp = ddi_get_driver_private(devi);
758 	instance = ddi_get_instance(devi);
759 
760 	switch (cmd) {
761 		case DDI_ATTACH:
762 			if (st_doattach(devp, SLEEP_FUNC) == DDI_FAILURE) {
763 				return (DDI_FAILURE);
764 			}
765 			break;
766 		case DDI_RESUME:
767 			/*
768 			 * Suspend/Resume
769 			 *
770 			 * When the driver suspended, there might be
771 			 * outstanding cmds and therefore we need to
772 			 * reset the suspended flag and resume the scsi
773 			 * watch thread and restart commands and timeouts
774 			 */
775 
776 			if (!(un = ddi_get_soft_state(st_state, instance))) {
777 				return (DDI_FAILURE);
778 			}
779 			dev_instance = ((un->un_dev == 0) ? MTMINOR(instance) :
780 			    un->un_dev);
781 
782 			mutex_enter(ST_MUTEX);
783 
784 			un->un_throttle = un->un_max_throttle;
785 			un->un_tids_at_suspend = 0;
786 			un->un_pwr_mgmt = ST_PWR_NORMAL;
787 
788 			if (un->un_swr_token) {
789 				scsi_watch_resume(un->un_swr_token);
790 			}
791 
792 			/*
793 			 * Restart timeouts
794 			 */
795 			if ((un->un_tids_at_suspend & ST_DELAY_TID) != 0) {
796 				mutex_exit(ST_MUTEX);
797 				un->un_delay_tid = timeout(
798 				    st_delayed_cv_broadcast, un,
799 				    drv_usectohz((clock_t)
800 				    MEDIA_ACCESS_DELAY));
801 				mutex_enter(ST_MUTEX);
802 			}
803 
804 			if (un->un_tids_at_suspend & ST_HIB_TID) {
805 				mutex_exit(ST_MUTEX);
806 				un->un_hib_tid = timeout(st_intr_restart, un,
807 				    ST_STATUS_BUSY_TIMEOUT);
808 				mutex_enter(ST_MUTEX);
809 			}
810 
811 			ret_status = st_clear_unit_attentions(dev_instance, 5);
812 
813 			/*
814 			 * now check if we need to restore the tape position
815 			 */
816 			if ((un->un_suspend_pos.pmode != invalid) &&
817 			    ((un->un_suspend_pos.fileno > 0) ||
818 			    (un->un_suspend_pos.blkno > 0)) ||
819 			    (un->un_suspend_pos.lgclblkno > 0)) {
820 				if (ret_status != 0) {
821 					/*
822 					 * tape didn't get good TUR
823 					 * just print out error messages
824 					 */
825 					scsi_log(ST_DEVINFO, st_label, CE_WARN,
826 					    "st_attach-RESUME: tape failure "
827 					    " tape position will be lost");
828 				} else {
829 					/* this prints errors */
830 					(void) st_validate_tapemarks(un,
831 					    &un->un_suspend_pos);
832 				}
833 				/*
834 				 * there are no retries, if there is an error
835 				 * we don't know if the tape has changed
836 				 */
837 				un->un_suspend_pos.pmode = invalid;
838 			}
839 
840 			/* now we are ready to start up any queued I/Os */
841 			if (un->un_ncmds || un->un_quef) {
842 				st_start(un);
843 			}
844 
845 			cv_broadcast(&un->un_suspend_cv);
846 			mutex_exit(ST_MUTEX);
847 			return (DDI_SUCCESS);
848 
849 		default:
850 			return (DDI_FAILURE);
851 	}
852 
853 	un = ddi_get_soft_state(st_state, instance);
854 
855 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
856 	    "st_attach: instance=%x\n", instance);
857 
858 	/*
859 	 * find the drive type for this target
860 	 */
861 	st_known_tape_type(un);
862 
863 	for (node_ix = 0; node_ix < ST_NUM_MEMBERS(st_minor_data); node_ix++) {
864 		int minor;
865 		char *name;
866 
867 		name  = st_minor_data[node_ix].name;
868 		minor = st_minor_data[node_ix].minor;
869 
870 		/*
871 		 * For default devices set the density to the
872 		 * preferred default density for this device.
873 		 */
874 		if (node_ix <= DEF_BSD_NR) {
875 			minor |= un->un_dp->default_density;
876 		}
877 		minor |= MTMINOR(instance);
878 
879 		if (ddi_create_minor_node(devi, name, S_IFCHR, minor,
880 		    DDI_NT_TAPE, NULL) == DDI_SUCCESS) {
881 			continue;
882 		}
883 
884 		ddi_remove_minor_node(devi, NULL);
885 		if (un) {
886 			cv_destroy(&un->un_clscv);
887 			cv_destroy(&un->un_sbuf_cv);
888 			cv_destroy(&un->un_queue_cv);
889 			cv_destroy(&un->un_state_cv);
890 			cv_destroy(&un->un_suspend_cv);
891 			cv_destroy(&un->un_tape_busy_cv);
892 
893 			if (un->un_sbufp) {
894 				freerbuf(un->un_sbufp);
895 			}
896 			if (un->un_uscsi_rqs_buf) {
897 				kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
898 			}
899 			if (un->un_mspl) {
900 				i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
901 			}
902 			scsi_destroy_pkt(un->un_rqs);
903 			scsi_free_consistent_buf(un->un_rqs_bp);
904 			ddi_soft_state_free(st_state, instance);
905 			devp->sd_private = NULL;
906 			devp->sd_sense = NULL;
907 
908 		}
909 		ddi_prop_remove_all(devi);
910 		return (DDI_FAILURE);
911 	}
912 
913 	/*
914 	 * Add a zero-length attribute to tell the world we support
915 	 * kernel ioctls (for layered drivers)
916 	 */
917 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
918 	    DDI_KERNEL_IOCTL, NULL, 0);
919 
920 	ddi_report_dev((dev_info_t *)devi);
921 
922 	/*
923 	 * If it's a SCSI-2 tape drive which supports wide,
924 	 * tell the host adapter to use wide.
925 	 */
926 	wide = ((devp->sd_inq->inq_rdf == RDF_SCSI2) &&
927 	    (devp->sd_inq->inq_wbus16 || devp->sd_inq->inq_wbus32)) ?  1 : 0;
928 
929 	if (scsi_ifsetcap(ROUTE, "wide-xfer", wide, 1) == 1) {
930 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
931 		    "Wide Transfer %s\n", wide ? "enabled" : "disabled");
932 	}
933 
934 	/*
935 	 * enable autorequest sense; keep the rq packet around in case
936 	 * the autorequest sense fails because of a busy condition
937 	 * do a getcap first in case the capability is not variable
938 	 */
939 	if (scsi_ifgetcap(ROUTE, "auto-rqsense", 1) == 1) {
940 		un->un_arq_enabled = 1;
941 	} else {
942 		un->un_arq_enabled =
943 		    ((scsi_ifsetcap(ROUTE, "auto-rqsense", 1, 1) == 1) ? 1 : 0);
944 	}
945 
946 	ST_DEBUG(devi, st_label, SCSI_DEBUG, "auto request sense %s\n",
947 	    (un->un_arq_enabled ? "enabled" : "disabled"));
948 
949 	un->un_untagged_qing =
950 	    (scsi_ifgetcap(ROUTE, "untagged-qing", 0) == 1);
951 
952 	/*
953 	 * XXX - This is just for 2.6.  to tell users that write buffering
954 	 *	has gone away.
955 	 */
956 	if (un->un_arq_enabled && un->un_untagged_qing) {
957 		if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
958 		    "tape-driver-buffering", 0) != 0) {
959 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
960 			    "Write Data Buffering has been depricated. Your "
961 			    "applications should continue to work normally.\n"
962 			    " But, they should  ported to use Asynchronous "
963 			    " I/O\n"
964 			    " For more information, read about "
965 			    " tape-driver-buffering "
966 			    "property in the st(7d) man page\n");
967 		}
968 	}
969 
970 	un->un_max_throttle = un->un_throttle = un->un_last_throttle = 1;
971 	un->un_flush_on_errors = 0;
972 	un->un_mkr_pkt = (struct scsi_pkt *)NULL;
973 
974 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
975 	    "throttle=%x, max_throttle = %x\n",
976 	    un->un_throttle, un->un_max_throttle);
977 
978 	/* initialize persistent errors to nil */
979 	un->un_persistence = 0;
980 	un->un_persist_errors = 0;
981 
982 	/*
983 	 * Get dma-max from HBA driver. If it is not defined, use 64k
984 	 */
985 	un->un_maxdma	= scsi_ifgetcap(&devp->sd_address, "dma-max", 1);
986 	if (un->un_maxdma == -1) {
987 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
988 		    "Received a value that looked like -1. Using 64k maxdma");
989 		un->un_maxdma = (64 * ONE_K);
990 	}
991 
992 	/*
993 	 * Get the max allowable cdb size
994 	 */
995 	un->un_max_cdb_sz =
996 	    scsi_ifgetcap(&devp->sd_address, "max-cdb-length", 1);
997 	if (un->un_max_cdb_sz < CDB_GROUP0) {
998 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
999 		    "HBA reported max-cdb-length as %d\n", un->un_max_cdb_sz);
1000 		un->un_max_cdb_sz = CDB_GROUP4; /* optimistic default */
1001 	}
1002 
1003 	un->un_maxbsize = MAXBSIZE_UNKNOWN;
1004 
1005 	un->un_mediastate = MTIO_NONE;
1006 	un->un_HeadClean  = TAPE_ALERT_SUPPORT_UNKNOWN;
1007 
1008 	/*
1009 	 * initialize kstats
1010 	 */
1011 	un->un_stats = kstat_create("st", instance, NULL, "tape",
1012 	    KSTAT_TYPE_IO, 1, KSTAT_FLAG_PERSISTENT);
1013 	if (un->un_stats) {
1014 		un->un_stats->ks_lock = ST_MUTEX;
1015 		kstat_install(un->un_stats);
1016 	}
1017 	(void) st_create_errstats(un, instance);
1018 
1019 	return (DDI_SUCCESS);
1020 }
1021 
1022 /*
1023  * st_detach:
1024  *
1025  * we allow a detach if and only if:
1026  *	- no tape is currently inserted
1027  *	- tape position is at BOT or unknown
1028  *		(if it is not at BOT then a no rewind
1029  *		device was opened and we have to preserve state)
1030  *	- it must be in a closed state : no timeouts or scsi_watch requests
1031  *		will exist if it is closed, so we don't need to check for
1032  *		them here.
1033  */
1034 /*ARGSUSED*/
1035 static int
1036 st_detach(dev_info_t *devi, ddi_detach_cmd_t cmd)
1037 {
1038 	int 	instance;
1039 	int 	dev_instance;
1040 	struct scsi_device *devp;
1041 	struct scsi_tape *un;
1042 	clock_t wait_cmds_complete;
1043 
1044 	ST_ENTR(devi, st_detach);
1045 
1046 	instance = ddi_get_instance(devi);
1047 
1048 	if (!(un = ddi_get_soft_state(st_state, instance))) {
1049 		return (DDI_FAILURE);
1050 	}
1051 
1052 	switch (cmd) {
1053 
1054 	case DDI_DETACH:
1055 		/*
1056 		 * Undo what we did in st_attach & st_doattach,
1057 		 * freeing resources and removing things we installed.
1058 		 * The system framework guarantees we are not active
1059 		 * with this devinfo node in any other entry points at
1060 		 * this time.
1061 		 */
1062 
1063 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1064 		    "st_detach: instance=%x, un=%p\n", instance,
1065 		    (void *)un);
1066 
1067 		if (((un->un_dp->options & ST_UNLOADABLE) == 0) ||
1068 		    (un->un_ncmds != 0) || (un->un_quef != NULL) ||
1069 		    (un->un_state != ST_STATE_CLOSED)) {
1070 			/*
1071 			 * we cannot unload some targets because the
1072 			 * inquiry returns junk unless immediately
1073 			 * after a reset
1074 			 */
1075 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
1076 			    "cannot unload instance %x\n", instance);
1077 			return (DDI_FAILURE);
1078 		}
1079 
1080 		/*
1081 		 * if the tape has been removed then we may unload;
1082 		 * do a test unit ready and if it returns NOT READY
1083 		 * then we assume that it is safe to unload.
1084 		 * as a side effect, pmode may be set to invalid if the
1085 		 * the test unit ready fails;
1086 		 * also un_state may be set to non-closed, so reset it
1087 		 */
1088 		if ((un->un_dev) &&		/* Been opened since attach */
1089 		    ((un->un_pos.pmode == legacy) &&
1090 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1091 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1092 		    ((un->un_pos.pmode == logical) &&
1093 		    (un->un_pos.lgclblkno > 0))) {
1094 			mutex_enter(ST_MUTEX);
1095 			/*
1096 			 * Send Test Unit Ready in the hopes that if
1097 			 * the drive is not in the state we think it is.
1098 			 * And the state will be changed so it can be detached.
1099 			 * If the command fails to reach the device and
1100 			 * the drive was not rewound or unloaded we want
1101 			 * to fail the detach till a user command fails
1102 			 * where after the detach will succead.
1103 			 */
1104 			(void) st_cmd(un->un_dev, SCMD_TEST_UNIT_READY,
1105 			    0, SYNC_CMD);
1106 			/*
1107 			 * After TUR un_state may be set to non-closed,
1108 			 * so reset it back.
1109 			 */
1110 			un->un_state = ST_STATE_CLOSED;
1111 			mutex_exit(ST_MUTEX);
1112 		}
1113 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1114 		    "un_status=%x, fileno=%x, blkno=%x\n",
1115 		    un->un_status, un->un_pos.fileno, un->un_pos.blkno);
1116 
1117 		/*
1118 		 * check again:
1119 		 * if we are not at BOT then it is not safe to unload
1120 		 */
1121 		if ((un->un_dev) &&		/* Been opened since attach */
1122 		    (((un->un_pos.pmode == legacy) &&
1123 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1124 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1125 		    ((un->un_pos.pmode == logical) &&
1126 		    (un->un_pos.lgclblkno > 0)))) {
1127 
1128 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1129 			    "cannot detach: pmode=%d fileno=%x, blkno=%x"
1130 			    " lgclblkno=0x%"PRIx64"\n", un->un_pos.pmode,
1131 			    un->un_pos.fileno, un->un_pos.blkno,
1132 			    un->un_pos.lgclblkno);
1133 			return (DDI_FAILURE);
1134 		}
1135 
1136 		/*
1137 		 * Just To make sure that we have released the
1138 		 * tape unit .
1139 		 */
1140 		if (un->un_dev && (un->un_rsvd_status & ST_RESERVE) &&
1141 		    !DEVI_IS_DEVICE_REMOVED(devi)) {
1142 			mutex_enter(ST_MUTEX);
1143 			(void) st_reserve_release(un, ST_RELEASE);
1144 			mutex_exit(ST_MUTEX);
1145 		}
1146 
1147 		/*
1148 		 * now remove other data structures allocated in st_doattach()
1149 		 */
1150 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1151 		    "destroying/freeing\n");
1152 		cv_destroy(&un->un_clscv);
1153 		cv_destroy(&un->un_sbuf_cv);
1154 		cv_destroy(&un->un_queue_cv);
1155 		cv_destroy(&un->un_suspend_cv);
1156 		cv_destroy(&un->un_tape_busy_cv);
1157 
1158 		if (un->un_hib_tid) {
1159 			(void) untimeout(un->un_hib_tid);
1160 			un->un_hib_tid = 0;
1161 		}
1162 
1163 		if (un->un_delay_tid) {
1164 			(void) untimeout(un->un_delay_tid);
1165 			un->un_delay_tid = 0;
1166 		}
1167 		cv_destroy(&un->un_state_cv);
1168 
1169 #if defined(__i386) || defined(__amd64)
1170 		if (un->un_contig_mem_hdl != NULL) {
1171 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1172 		}
1173 #endif
1174 		if (un->un_sbufp) {
1175 			freerbuf(un->un_sbufp);
1176 		}
1177 		if (un->un_uscsi_rqs_buf) {
1178 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1179 		}
1180 		if (un->un_mspl) {
1181 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1182 		}
1183 		if (un->un_rqs) {
1184 			scsi_destroy_pkt(un->un_rqs);
1185 			scsi_free_consistent_buf(un->un_rqs_bp);
1186 		}
1187 		if (un->un_mkr_pkt) {
1188 			scsi_destroy_pkt(un->un_mkr_pkt);
1189 		}
1190 		if (un->un_arq_enabled) {
1191 			(void) scsi_ifsetcap(ROUTE, "auto-rqsense", 0, 1);
1192 		}
1193 		if (un->un_dp_size) {
1194 			kmem_free(un->un_dp, un->un_dp_size);
1195 		}
1196 		if (un->un_stats) {
1197 			kstat_delete(un->un_stats);
1198 			un->un_stats = (kstat_t *)0;
1199 		}
1200 		if (un->un_errstats) {
1201 			kstat_delete(un->un_errstats);
1202 			un->un_errstats = (kstat_t *)0;
1203 		}
1204 		devp = ST_SCSI_DEVP;
1205 		ddi_soft_state_free(st_state, instance);
1206 		devp->sd_private = NULL;
1207 		devp->sd_sense = NULL;
1208 		scsi_unprobe(devp);
1209 		ddi_prop_remove_all(devi);
1210 		ddi_remove_minor_node(devi, NULL);
1211 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach done\n");
1212 		return (DDI_SUCCESS);
1213 
1214 	case DDI_SUSPEND:
1215 
1216 		/*
1217 		 * Suspend/Resume
1218 		 *
1219 		 * To process DDI_SUSPEND, we must do the following:
1220 		 *
1221 		 *  - check ddi_removing_power to see if power will be turned
1222 		 *    off. if so, return DDI_FAILURE
1223 		 *  - check if we are already suspended,
1224 		 *    if so, return DDI_FAILURE
1225 		 *  - check if device state is CLOSED,
1226 		 *    if not, return DDI_FAILURE.
1227 		 *  - wait until outstanding operations complete
1228 		 *  - save tape state
1229 		 *  - block new operations
1230 		 *  - cancel pending timeouts
1231 		 *
1232 		 */
1233 
1234 		if (ddi_removing_power(devi)) {
1235 			return (DDI_FAILURE);
1236 		}
1237 		mutex_enter(ST_MUTEX);
1238 
1239 		/*
1240 		 * Shouldn't already be suspended, if so return failure
1241 		 */
1242 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
1243 			mutex_exit(ST_MUTEX);
1244 			return (DDI_FAILURE);
1245 		}
1246 		if (un->un_state != ST_STATE_CLOSED) {
1247 			mutex_exit(ST_MUTEX);
1248 			return (DDI_FAILURE);
1249 		}
1250 
1251 		/*
1252 		 * Wait for all outstanding I/O's to complete
1253 		 *
1254 		 * we wait on both ncmds and the wait queue for times
1255 		 * when we are flushing after persistent errors are
1256 		 * flagged, which is when ncmds can be 0, and the
1257 		 * queue can still have I/O's.  This way we preserve
1258 		 * order of biodone's.
1259 		 */
1260 		wait_cmds_complete = ddi_get_lbolt();
1261 		wait_cmds_complete +=
1262 		    st_wait_cmds_complete * drv_usectohz(1000000);
1263 		while (un->un_ncmds || un->un_quef ||
1264 		    (un->un_state == ST_STATE_RESOURCE_WAIT)) {
1265 
1266 			if (cv_timedwait(&un->un_tape_busy_cv, ST_MUTEX,
1267 			    wait_cmds_complete) == -1) {
1268 				/*
1269 				 * Time expired then cancel the command
1270 				 */
1271 				mutex_exit(ST_MUTEX);
1272 				if (scsi_reset(ROUTE, RESET_TARGET) == 0) {
1273 					mutex_enter(ST_MUTEX);
1274 					if (un->un_last_throttle) {
1275 						un->un_throttle =
1276 						    un->un_last_throttle;
1277 					}
1278 					mutex_exit(ST_MUTEX);
1279 					return (DDI_FAILURE);
1280 				} else {
1281 					mutex_enter(ST_MUTEX);
1282 					break;
1283 				}
1284 			}
1285 		}
1286 
1287 		/*
1288 		 * DDI_SUSPEND says that the system "may" power down, we
1289 		 * remember the file and block number before rewinding.
1290 		 * we also need to save state before issuing
1291 		 * any WRITE_FILE_MARK command.
1292 		 */
1293 		(void) st_update_block_pos(un);
1294 		COPY_POS(&un->un_suspend_pos, &un->un_pos);
1295 
1296 		dev_instance = ((un->un_dev == 0) ? MTMINOR(instance) :
1297 		    un->un_dev);
1298 
1299 		/*
1300 		 * Issue a zero write file fmk command to tell the drive to
1301 		 * flush any buffered tape marks
1302 		 */
1303 		(void) st_cmd(dev_instance, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
1304 
1305 		/*
1306 		 * Because not all tape drives correctly implement buffer
1307 		 * flushing with the zero write file fmk command, issue a
1308 		 * synchronous rewind command to force data flushing.
1309 		 * st_validate_tapemarks() will do a rewind during DDI_RESUME
1310 		 * anyway.
1311 		 */
1312 		(void) st_cmd(dev_instance, SCMD_REWIND, 0, SYNC_CMD);
1313 
1314 		/* stop any new operations */
1315 		un->un_pwr_mgmt = ST_PWR_SUSPENDED;
1316 		un->un_throttle = 0;
1317 
1318 		/*
1319 		 * cancel any outstanding timeouts
1320 		 */
1321 		if (un->un_delay_tid) {
1322 			timeout_id_t temp_id = un->un_delay_tid;
1323 			un->un_delay_tid = 0;
1324 			un->un_tids_at_suspend |= ST_DELAY_TID;
1325 			mutex_exit(ST_MUTEX);
1326 			(void) untimeout(temp_id);
1327 			mutex_enter(ST_MUTEX);
1328 		}
1329 
1330 		if (un->un_hib_tid) {
1331 			timeout_id_t temp_id = un->un_hib_tid;
1332 			un->un_hib_tid = 0;
1333 			un->un_tids_at_suspend |= ST_HIB_TID;
1334 			mutex_exit(ST_MUTEX);
1335 			(void) untimeout(temp_id);
1336 			mutex_enter(ST_MUTEX);
1337 		}
1338 
1339 		/*
1340 		 * Suspend the scsi_watch_thread
1341 		 */
1342 		if (un->un_swr_token) {
1343 			opaque_t temp_token = un->un_swr_token;
1344 			mutex_exit(ST_MUTEX);
1345 			scsi_watch_suspend(temp_token);
1346 		} else {
1347 			mutex_exit(ST_MUTEX);
1348 		}
1349 
1350 		return (DDI_SUCCESS);
1351 
1352 	default:
1353 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach failed\n");
1354 		return (DDI_FAILURE);
1355 	}
1356 }
1357 
1358 
1359 /* ARGSUSED */
1360 static int
1361 stinfo(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
1362 {
1363 	dev_t dev;
1364 	struct scsi_tape *un;
1365 	int instance, error;
1366 
1367 	ST_ENTR(dip, stinfo);
1368 
1369 	switch (infocmd) {
1370 	case DDI_INFO_DEVT2DEVINFO:
1371 		dev = (dev_t)arg;
1372 		instance = MTUNIT(dev);
1373 		if ((un = ddi_get_soft_state(st_state, instance)) == NULL)
1374 			return (DDI_FAILURE);
1375 		*result = (void *) ST_DEVINFO;
1376 		error = DDI_SUCCESS;
1377 		break;
1378 	case DDI_INFO_DEVT2INSTANCE:
1379 		dev = (dev_t)arg;
1380 		instance = MTUNIT(dev);
1381 		*result = (void *)(uintptr_t)instance;
1382 		error = DDI_SUCCESS;
1383 		break;
1384 	default:
1385 		error = DDI_FAILURE;
1386 	}
1387 	return (error);
1388 }
1389 
1390 static int
1391 st_doattach(struct scsi_device *devp, int (*canwait)())
1392 {
1393 	struct scsi_pkt *rqpkt = NULL;
1394 	struct scsi_tape *un = NULL;
1395 	int km_flags = (canwait != NULL_FUNC) ? KM_SLEEP : KM_NOSLEEP;
1396 	int instance;
1397 	struct buf *bp;
1398 	size_t rlen;
1399 
1400 	ST_FUNC(devp->sd_dev, st_doattach);
1401 	/*
1402 	 * Call the routine scsi_probe to do some of the dirty work.
1403 	 * If the INQUIRY command succeeds, the field sd_inq in the
1404 	 * device structure will be filled in.
1405 	 */
1406 	ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1407 	    "st_doattach(): probing\n");
1408 
1409 	if (scsi_probe(devp, canwait) == SCSIPROBE_EXISTS) {
1410 
1411 		/*
1412 		 * In checking the whole inq_dtype byte we are looking at both
1413 		 * the Peripheral Qualifier and the Peripheral Device Type.
1414 		 * For this driver we are only interested in sequential devices
1415 		 * that are connected or capable if connecting to this logical
1416 		 * unit.
1417 		 */
1418 		if (devp->sd_inq->inq_dtype ==
1419 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
1420 			ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1421 			    "probe exists\n");
1422 		} else {
1423 			/* Something there but not a tape device */
1424 			scsi_unprobe(devp);
1425 			return (DDI_FAILURE);
1426 		}
1427 	} else {
1428 		/* Nothing there */
1429 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1430 		    "probe failure: nothing there\n");
1431 		scsi_unprobe(devp);
1432 		return (DDI_FAILURE);
1433 	}
1434 
1435 	bp = scsi_alloc_consistent_buf(&devp->sd_address, (struct buf *)NULL,
1436 	    SENSE_LENGTH, B_READ, canwait, NULL);
1437 	if (!bp) {
1438 		goto error;
1439 	}
1440 	rqpkt = scsi_init_pkt(&devp->sd_address, NULL, bp, CDB_GROUP0, 1, 0,
1441 	    PKT_CONSISTENT, canwait, NULL);
1442 	if (!rqpkt) {
1443 		goto error;
1444 	}
1445 	devp->sd_sense = (struct scsi_extended_sense *)bp->b_un.b_addr;
1446 	ASSERT(geterror(bp) == NULL);
1447 
1448 	(void) scsi_setup_cdb((union scsi_cdb *)rqpkt->pkt_cdbp,
1449 	    SCMD_REQUEST_SENSE, 0, SENSE_LENGTH, 0);
1450 	FILL_SCSI1_LUN(devp, rqpkt);
1451 
1452 	/*
1453 	 * The actual unit is present.
1454 	 * Now is the time to fill in the rest of our info..
1455 	 */
1456 	instance = ddi_get_instance(devp->sd_dev);
1457 
1458 	if (ddi_soft_state_zalloc(st_state, instance) != DDI_SUCCESS) {
1459 		goto error;
1460 	}
1461 	un = ddi_get_soft_state(st_state, instance);
1462 
1463 	ASSERT(un != NULL);
1464 
1465 	un->un_sbufp = getrbuf(km_flags);
1466 
1467 	un->un_uscsi_rqs_buf = kmem_alloc(SENSE_LENGTH, KM_SLEEP);
1468 
1469 	/*
1470 	 * use i_ddi_mem_alloc() for now until we have an interface to allocate
1471 	 * memory for DMA which doesn't require a DMA handle. ddi_iopb_alloc()
1472 	 * is obsolete and we want more flexibility in controlling the DMA
1473 	 * address constraints.
1474 	 */
1475 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1476 	    sizeof (struct seq_mode), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1477 	    NULL, (caddr_t *)&un->un_mspl, &rlen, NULL);
1478 
1479 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1480 	    sizeof (read_pos_data_t), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1481 	    NULL, (caddr_t *)&un->un_read_pos_data, &rlen, NULL);
1482 
1483 	if (!un->un_sbufp || !un->un_mspl || !un->un_read_pos_data) {
1484 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1485 		    "probe partial failure: no space\n");
1486 		goto error;
1487 	}
1488 
1489 	bzero(un->un_mspl, sizeof (struct seq_mode));
1490 
1491 	cv_init(&un->un_sbuf_cv, NULL, CV_DRIVER, NULL);
1492 	cv_init(&un->un_queue_cv, NULL, CV_DRIVER, NULL);
1493 	cv_init(&un->un_clscv, NULL, CV_DRIVER, NULL);
1494 	cv_init(&un->un_state_cv, NULL, CV_DRIVER, NULL);
1495 #if defined(__i386) || defined(__amd64)
1496 	cv_init(&un->un_contig_mem_cv, NULL, CV_DRIVER, NULL);
1497 #endif
1498 
1499 	/* Initialize power managemnet condition variable */
1500 	cv_init(&un->un_suspend_cv, NULL, CV_DRIVER, NULL);
1501 	cv_init(&un->un_tape_busy_cv, NULL, CV_DRIVER, NULL);
1502 
1503 	rqpkt->pkt_flags |= (FLAG_SENSING | FLAG_HEAD | FLAG_NODISCON);
1504 
1505 	un->un_pos.pmode = invalid;
1506 	rqpkt->pkt_time = st_io_time;
1507 	rqpkt->pkt_comp = st_intr;
1508 	un->un_rqs	= rqpkt;
1509 	un->un_sd	= devp;
1510 	un->un_rqs_bp	= bp;
1511 	un->un_swr_token = (opaque_t)NULL;
1512 	un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
1513 	un->un_wormable = st_is_drive_worm;
1514 	un->un_read_pos_type = LONG_POS;
1515 
1516 	un->un_suspend_pos.pmode = invalid;
1517 
1518 #if defined(__i386) || defined(__amd64)
1519 	if (ddi_dma_alloc_handle(ST_DEVINFO, &st_contig_mem_dma_attr,
1520 	    DDI_DMA_SLEEP, NULL, &un->un_contig_mem_hdl) != DDI_SUCCESS) {
1521 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1522 		    "allocation of contiguous memory dma handle failed!");
1523 		un->un_contig_mem_hdl = NULL;
1524 		goto error;
1525 	}
1526 #endif
1527 
1528 	/*
1529 	 * Since this driver manages devices with "remote" hardware,
1530 	 * i.e. the devices themselves have no "reg" properties,
1531 	 * the SUSPEND/RESUME commands in detach/attach will not be
1532 	 * called by the power management framework unless we request
1533 	 * it by creating a "pm-hardware-state" property and setting it
1534 	 * to value "needs-suspend-resume".
1535 	 */
1536 	if (ddi_prop_update_string(DDI_DEV_T_NONE, devp->sd_dev,
1537 	    "pm-hardware-state", "needs-suspend-resume") !=
1538 	    DDI_PROP_SUCCESS) {
1539 
1540 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1541 		    "ddi_prop_update(\"pm-hardware-state\") failed\n");
1542 		goto error;
1543 	}
1544 
1545 	if (ddi_prop_create(DDI_DEV_T_NONE, devp->sd_dev, DDI_PROP_CANSLEEP,
1546 	    "no-involuntary-power-cycles", NULL, 0) != DDI_PROP_SUCCESS) {
1547 
1548 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1549 		    "ddi_prop_create(\"no-involuntary-power-cycles\") "
1550 		    "failed\n");
1551 		goto error;
1552 	}
1553 
1554 	ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG, "probe success\n");
1555 	return (DDI_SUCCESS);
1556 
1557 error:
1558 	devp->sd_sense = NULL;
1559 
1560 	ddi_remove_minor_node(devp->sd_dev, NULL);
1561 	if (un) {
1562 		if (un->un_mspl) {
1563 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1564 		}
1565 		if (un->un_read_pos_data) {
1566 			i_ddi_mem_free((caddr_t)un->un_read_pos_data, 0);
1567 		}
1568 		if (un->un_sbufp) {
1569 			freerbuf(un->un_sbufp);
1570 		}
1571 		if (un->un_uscsi_rqs_buf) {
1572 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1573 		}
1574 #if defined(__i386) || defined(__amd64)
1575 		if (un->un_contig_mem_hdl != NULL) {
1576 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1577 		}
1578 #endif
1579 		ddi_soft_state_free(st_state, instance);
1580 		devp->sd_private = NULL;
1581 	}
1582 
1583 	if (rqpkt) {
1584 		scsi_destroy_pkt(rqpkt);
1585 	}
1586 
1587 	if (bp) {
1588 		scsi_free_consistent_buf(bp);
1589 	}
1590 
1591 	if (devp->sd_inq) {
1592 		scsi_unprobe(devp);
1593 	}
1594 	return (DDI_FAILURE);
1595 }
1596 
1597 typedef int
1598 (*cfg_functp)(struct scsi_tape *, char *vidpid, struct st_drivetype *);
1599 
1600 static cfg_functp config_functs[] = {
1601 	st_get_conf_from_st_dot_conf,
1602 	st_get_conf_from_st_conf_dot_c,
1603 	st_get_default_conf
1604 };
1605 
1606 
1607 /*
1608  * determine tape type, using tape-config-list or built-in table or
1609  * use a generic tape config entry
1610  */
1611 static void
1612 st_known_tape_type(struct scsi_tape *un)
1613 {
1614 	struct st_drivetype *dp;
1615 	cfg_functp *config_funct;
1616 
1617 	ST_FUNC(ST_DEVINFO, st_known_tape_type);
1618 	/*
1619 	 * XXX:  Emulex MT-02 (and emulators) predates SCSI-1 and has
1620 	 *	 no vid & pid inquiry data.  So, we provide one.
1621 	 */
1622 	if (ST_INQUIRY->inq_len == 0 ||
1623 	    (bcmp("\0\0\0\0\0\0\0\0", ST_INQUIRY->inq_vid, 8) == 0)) {
1624 		(void) strcpy((char *)ST_INQUIRY->inq_vid, ST_MT02_NAME);
1625 	}
1626 
1627 	un->un_dp_size = sizeof (struct st_drivetype);
1628 	dp = kmem_zalloc((size_t)un->un_dp_size, KM_SLEEP);
1629 	un->un_dp = dp;
1630 
1631 	/*
1632 	 * Loop through the configuration methods till one works.
1633 	 */
1634 	for (config_funct = &config_functs[0]; ; config_funct++) {
1635 		if ((*config_funct)(un, ST_INQUIRY->inq_vid, dp)) {
1636 			break;
1637 		}
1638 	}
1639 
1640 	/*
1641 	 * If we didn't just make up this configuration and
1642 	 * all the density codes are the same..
1643 	 * Set Auto Density over ride.
1644 	 */
1645 	if (*config_funct != st_get_default_conf) {
1646 		/*
1647 		 * If this device is one that is configured and all
1648 		 * densities are the same, This saves doing gets and set
1649 		 * that yield nothing.
1650 		 */
1651 		if ((dp->densities[0]) == (dp->densities[1]) &&
1652 		    (dp->densities[0]) == (dp->densities[2]) &&
1653 		    (dp->densities[0]) == (dp->densities[3])) {
1654 
1655 			dp->options |= ST_AUTODEN_OVERRIDE;
1656 		}
1657 	}
1658 
1659 
1660 	/*
1661 	 * Store tape drive characteristics.
1662 	 */
1663 	un->un_status = 0;
1664 	un->un_attached = 1;
1665 	un->un_init_options = dp->options;
1666 
1667 	/* setup operation time-outs based on options */
1668 	st_calculate_timeouts(un);
1669 
1670 	/* make sure if we are supposed to be variable, make it variable */
1671 	if (dp->options & ST_VARIABLE) {
1672 		dp->bsize = 0;
1673 	}
1674 
1675 	scsi_log(ST_DEVINFO, st_label, CE_NOTE, "?<%s>\n", dp->name);
1676 }
1677 
1678 
1679 typedef struct {
1680 	int mask;
1681 	int bottom;
1682 	int top;
1683 	char *name;
1684 } conf_limit;
1685 
1686 static const conf_limit conf_limits[] = {
1687 
1688 	-1,		1,		2,		"conf version",
1689 	-1,		MT_ISTS,	ST_LAST_TYPE,	"drive type",
1690 	-1,		0,		0xffffff,	"block size",
1691 	ST_VALID_OPTS,	0,		ST_VALID_OPTS,	"options",
1692 	-1,		0,		4,		"number of densities",
1693 	-1,		0,		UINT8_MAX,	"density code",
1694 	-1,		0,		3,		"default density",
1695 	-1,		0,		UINT16_MAX,	"non motion timeout",
1696 	-1,		0,		UINT16_MAX,	"I/O timeout",
1697 	-1,		0,		UINT16_MAX,	"space timeout",
1698 	-1,		0,		UINT16_MAX,	"load timeout",
1699 	-1,		0,		UINT16_MAX,	"unload timeout",
1700 	-1,		0,		UINT16_MAX,	"erase timeout",
1701 	0,		0,		0,		NULL
1702 };
1703 
1704 static int
1705 st_validate_conf_data(struct scsi_tape *un, int *list, int list_len,
1706     const char *conf_name)
1707 {
1708 	int dens;
1709 	int ndens;
1710 	int value;
1711 	int type;
1712 	int count;
1713 	const conf_limit *limit = &conf_limits[0];
1714 
1715 	ST_FUNC(ST_DEVINFO, st_validate_conf_data);
1716 
1717 	ST_DEBUG3(ST_DEVINFO, st_label, CE_NOTE,
1718 	    "Checking %d entrys total with %d densities\n", list_len, list[4]);
1719 
1720 	count = list_len;
1721 	type = *list;
1722 	for (;  count && limit->name; count--, list++, limit++) {
1723 
1724 		value = *list;
1725 		if (value & ~limit->mask) {
1726 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1727 			    "%s %s value invalid bits set: 0x%X\n",
1728 			    conf_name, limit->name, value & ~limit->mask);
1729 			*list &= limit->mask;
1730 		} else if (value < limit->bottom) {
1731 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1732 			    "%s %s value too low: value = %d limit %d\n",
1733 			    conf_name, limit->name, value, limit->bottom);
1734 		} else if (value > limit->top) {
1735 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1736 			    "%s %s value too high: value = %d limit %d\n",
1737 			    conf_name, limit->name, value, limit->top);
1738 		} else {
1739 			ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
1740 			    "%s %s value = 0x%X\n",
1741 			    conf_name, limit->name, value);
1742 		}
1743 
1744 		/* If not the number of densities continue */
1745 		if (limit != &conf_limits[4]) {
1746 			continue;
1747 		}
1748 
1749 		/* If number of densities is not in range can't use config */
1750 		if (value < limit->bottom || value > limit->top) {
1751 			return (-1);
1752 		}
1753 
1754 		ndens = min(value, NDENSITIES);
1755 		if ((type == 1) && (list_len - ndens) != 6) {
1756 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1757 			    "%s conf version 1 with %d densities has %d items"
1758 			    " should have %d",
1759 			    conf_name, ndens, list_len, 6 + ndens);
1760 		} else if ((type == 2) && (list_len - ndens) != 13) {
1761 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1762 			    "%s conf version 2 with %d densities has %d items"
1763 			    " should have %d",
1764 			    conf_name, ndens, list_len, 13 + ndens);
1765 		}
1766 
1767 		limit++;
1768 		for (dens = 0; dens < ndens && count; dens++) {
1769 			count--;
1770 			list++;
1771 			value = *list;
1772 			if (value < limit->bottom) {
1773 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1774 				    "%s density[%d] value too low: value ="
1775 				    " 0x%X limit 0x%X\n",
1776 				    conf_name, dens, value, limit->bottom);
1777 			} else if (value > limit->top) {
1778 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1779 				    "%s density[%d] value too high: value ="
1780 				    " 0x%X limit 0x%X\n",
1781 				    conf_name, dens, value, limit->top);
1782 			} else {
1783 				ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
1784 				    "%s density[%d] value = 0x%X\n",
1785 				    conf_name, dens, value);
1786 			}
1787 		}
1788 	}
1789 
1790 	return (0);
1791 }
1792 
1793 static int
1794 st_get_conf_from_st_dot_conf(struct scsi_tape *un, char *vidpid,
1795     struct st_drivetype *dp)
1796 {
1797 	caddr_t config_list = NULL;
1798 	caddr_t data_list = NULL;
1799 	int	*data_ptr;
1800 	caddr_t vidptr, prettyptr, datanameptr;
1801 	size_t	vidlen, prettylen, datanamelen, tripletlen = 0;
1802 	int config_list_len, data_list_len, len, i;
1803 	int version;
1804 	int found = 0;
1805 
1806 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_dot_conf);
1807 
1808 	/*
1809 	 * Determine type of tape controller. Type is determined by
1810 	 * checking the vendor ids of the earlier inquiry command and
1811 	 * comparing those with vids in tape-config-list defined in st.conf
1812 	 */
1813 	if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, DDI_PROP_DONTPASS,
1814 	    "tape-config-list", (caddr_t)&config_list, &config_list_len)
1815 	    != DDI_PROP_SUCCESS) {
1816 		return (found);
1817 	}
1818 
1819 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
1820 	    "st_get_conf_from_st_dot_conf(): st.conf has tape-config-list\n");
1821 
1822 	/*
1823 	 * Compare vids in each triplet - if it matches, get value for
1824 	 * data_name and contruct a st_drivetype struct
1825 	 * tripletlen is not set yet!
1826 	 */
1827 	for (len = config_list_len, vidptr = config_list;
1828 	    len > 0;
1829 	    vidptr += tripletlen, len -= tripletlen) {
1830 
1831 		vidlen = strlen(vidptr);
1832 		prettyptr = vidptr + vidlen + 1;
1833 		prettylen = strlen(prettyptr);
1834 		datanameptr = prettyptr + prettylen + 1;
1835 		datanamelen = strlen(datanameptr);
1836 		tripletlen = vidlen + prettylen + datanamelen + 3;
1837 
1838 		if (vidlen == 0) {
1839 			continue;
1840 		}
1841 
1842 		/*
1843 		 * If inquiry vid dosen't match this triplets vid,
1844 		 * try the next.
1845 		 */
1846 		if (strncasecmp(vidpid, vidptr, vidlen)) {
1847 			continue;
1848 		}
1849 
1850 		/*
1851 		 * if prettylen is zero then use the vid string
1852 		 */
1853 		if (prettylen == 0) {
1854 			prettyptr = vidptr;
1855 			prettylen = vidlen;
1856 		}
1857 
1858 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1859 		    "vid = %s, pretty=%s, dataname = %s\n",
1860 		    vidptr, prettyptr, datanameptr);
1861 
1862 		/*
1863 		 * get the data list
1864 		 */
1865 		if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, 0,
1866 		    datanameptr, (caddr_t)&data_list,
1867 		    &data_list_len) != DDI_PROP_SUCCESS) {
1868 			/*
1869 			 * Error in getting property value
1870 			 * print warning!
1871 			 */
1872 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
1873 			    "data property (%s) has no value\n",
1874 			    datanameptr);
1875 			continue;
1876 		}
1877 
1878 		/*
1879 		 * now initialize the st_drivetype struct
1880 		 */
1881 		(void) strncpy(dp->name, prettyptr, ST_NAMESIZE - 1);
1882 		dp->length = (int)min(vidlen, (VIDPIDLEN - 1));
1883 		(void) strncpy(dp->vid, vidptr, dp->length);
1884 		data_ptr = (int *)data_list;
1885 		/*
1886 		 * check if data is enough for version, type,
1887 		 * bsize, options, # of densities, density1,
1888 		 * density2, ..., default_density
1889 		 */
1890 		if ((data_list_len < 5 * sizeof (int)) ||
1891 		    (data_list_len < 6 * sizeof (int) +
1892 		    *(data_ptr + 4) * sizeof (int))) {
1893 			/*
1894 			 * print warning and skip to next triplet.
1895 			 */
1896 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
1897 			    "data property (%s) incomplete\n",
1898 			    datanameptr);
1899 			kmem_free(data_list, data_list_len);
1900 			continue;
1901 		}
1902 
1903 		if (st_validate_conf_data(un, data_ptr,
1904 		    data_list_len / sizeof (int), datanameptr)) {
1905 			kmem_free(data_list, data_list_len);
1906 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
1907 			    "data property (%s) rejected\n",
1908 			    datanameptr);
1909 			continue;
1910 		}
1911 
1912 		/*
1913 		 * check version
1914 		 */
1915 		version = *data_ptr++;
1916 		if (version != 1 && version != 2) {
1917 			/* print warning but accept it */
1918 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
1919 			    "Version # for data property (%s) "
1920 			    "not set to 1 or 2\n", datanameptr);
1921 		}
1922 
1923 		dp->type    = *data_ptr++;
1924 		dp->bsize   = *data_ptr++;
1925 		dp->options = *data_ptr++;
1926 		dp->options |= ST_DYNAMIC;
1927 		len = *data_ptr++;
1928 		for (i = 0; i < NDENSITIES; i++) {
1929 			if (i < len) {
1930 				dp->densities[i] = *data_ptr++;
1931 			}
1932 		}
1933 		dp->default_density = *data_ptr << 3;
1934 		if (version == 2 &&
1935 		    data_list_len >= (13 + len) * sizeof (int)) {
1936 			data_ptr++;
1937 			dp->non_motion_timeout	= *data_ptr++;
1938 			dp->io_timeout		= *data_ptr++;
1939 			dp->rewind_timeout	= *data_ptr++;
1940 			dp->space_timeout	= *data_ptr++;
1941 			dp->load_timeout	= *data_ptr++;
1942 			dp->unload_timeout	= *data_ptr++;
1943 			dp->erase_timeout	= *data_ptr++;
1944 		}
1945 		kmem_free(data_list, data_list_len);
1946 		found = 1;
1947 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1948 		    "found in st.conf: vid = %s, pretty=%s\n",
1949 		    dp->vid, dp->name);
1950 		break;
1951 	}
1952 
1953 	/*
1954 	 * free up the memory allocated by ddi_getlongprop
1955 	 */
1956 	if (config_list) {
1957 		kmem_free(config_list, config_list_len);
1958 	}
1959 	return (found);
1960 }
1961 
1962 static int
1963 st_get_conf_from_st_conf_dot_c(struct scsi_tape *un, char *vidpid,
1964     struct st_drivetype *dp)
1965 {
1966 	int i;
1967 
1968 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_conf_dot_c);
1969 	/*
1970 	 * Determine type of tape controller.  Type is determined by
1971 	 * checking the result of the earlier inquiry command and
1972 	 * comparing vendor ids with strings in a table declared in st_conf.c.
1973 	 */
1974 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
1975 	    "st_get_conf_from_st_conf_dot_c(): looking at st_drivetypes\n");
1976 
1977 	for (i = 0; i < st_ndrivetypes; i++) {
1978 		if (st_drivetypes[i].length == 0) {
1979 			continue;
1980 		}
1981 		if (strncasecmp(vidpid, st_drivetypes[i].vid,
1982 		    st_drivetypes[i].length)) {
1983 			continue;
1984 		}
1985 		bcopy(&st_drivetypes[i], dp, sizeof (st_drivetypes[i]));
1986 		return (1);
1987 	}
1988 	return (0);
1989 }
1990 
1991 static int
1992 st_get_default_conf(struct scsi_tape *un, char *vidpid, struct st_drivetype *dp)
1993 {
1994 	int i;
1995 
1996 	ST_FUNC(ST_DEVINFO, st_get_default_conf);
1997 
1998 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
1999 	    "st_get_default_conf(): making drivetype from INQ cmd\n");
2000 
2001 
2002 	/*
2003 	 * Make up a name
2004 	 */
2005 	bcopy("Vendor '", dp->name, 8);
2006 	bcopy(vidpid, &dp->name[8], VIDLEN);
2007 	bcopy("' Product '", &dp->name[16], 11);
2008 	bcopy(&vidpid[8], &dp->name[27], PIDLEN);
2009 	dp->name[ST_NAMESIZE - 2] = '\'';
2010 	dp->name[ST_NAMESIZE - 1] = '\0';
2011 	dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2012 	(void) strncpy(dp->vid, ST_INQUIRY->inq_vid, dp->length);
2013 	/*
2014 	 * 'clean' vendor and product strings of non-printing chars
2015 	 */
2016 	for (i = 0; i < ST_NAMESIZE - 2; i++) {
2017 		if (dp->name[i] < ' ' || dp->name[i] > '~') {
2018 			dp->name[i] = '.';
2019 		}
2020 	}
2021 	dp->type = ST_TYPE_INVALID;
2022 	dp->options |= (ST_DYNAMIC | ST_UNLOADABLE | ST_MODE_SEL_COMP);
2023 
2024 	return (1); /* Can Not Fail */
2025 }
2026 
2027 /*
2028  * Regular Unix Entry points
2029  */
2030 
2031 
2032 
2033 /* ARGSUSED */
2034 static int
2035 st_open(dev_t *dev_p, int flag, int otyp, cred_t *cred_p)
2036 {
2037 	dev_t dev = *dev_p;
2038 	int rval = 0;
2039 
2040 	GET_SOFT_STATE(dev);
2041 
2042 	ST_ENTR(ST_DEVINFO, st_open);
2043 
2044 	/*
2045 	 * validate that we are addressing a sensible unit
2046 	 */
2047 	mutex_enter(ST_MUTEX);
2048 
2049 #ifdef	STDEBUG
2050 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2051 	    "st_open(node = %s dev = 0x%lx, flag = %d, otyp = %d)\n",
2052 	    st_dev_name(dev), *dev_p, flag, otyp);
2053 #endif
2054 
2055 	/*
2056 	 * All device accesss go thru st_strategy() where we check
2057 	 * suspend status
2058 	 */
2059 
2060 	if (!un->un_attached) {
2061 		st_known_tape_type(un);
2062 		if (!un->un_attached) {
2063 			rval = ENXIO;
2064 			goto exit;
2065 		}
2066 
2067 	}
2068 
2069 	/*
2070 	 * Check for the case of the tape in the middle of closing.
2071 	 * This isn't simply a check of the current state, because
2072 	 * we could be in state of sensing with the previous state
2073 	 * that of closing.
2074 	 *
2075 	 * And don't allow multiple opens.
2076 	 */
2077 	if (!(flag & (FNDELAY | FNONBLOCK)) && IS_CLOSING(un)) {
2078 		un->un_laststate = un->un_state;
2079 		un->un_state = ST_STATE_CLOSE_PENDING_OPEN;
2080 		while (IS_CLOSING(un) ||
2081 		    un->un_state == ST_STATE_CLOSE_PENDING_OPEN) {
2082 			if (cv_wait_sig(&un->un_clscv, ST_MUTEX) == 0) {
2083 				rval = EINTR;
2084 				un->un_state = un->un_laststate;
2085 				goto exit;
2086 			}
2087 		}
2088 	} else if (un->un_state != ST_STATE_CLOSED) {
2089 		rval = EBUSY;
2090 		goto busy;
2091 	}
2092 
2093 	/*
2094 	 * record current dev
2095 	 */
2096 	un->un_dev = dev;
2097 	un->un_oflags = flag;	/* save for use in st_tape_init() */
2098 	un->un_errno = 0;	/* no errors yet */
2099 	un->un_restore_pos = 0;
2100 	un->un_rqs_state = 0;
2101 
2102 	/*
2103 	 * If we are opening O_NDELAY, or O_NONBLOCK, we don't check for
2104 	 * anything, leave internal states alone, if fileno >= 0
2105 	 */
2106 	if (flag & (FNDELAY | FNONBLOCK)) {
2107 		switch (un->un_pos.pmode) {
2108 
2109 		case invalid:
2110 			un->un_state = ST_STATE_OFFLINE;
2111 			break;
2112 
2113 		case legacy:
2114 			/*
2115 			 * If position is anything other than rewound.
2116 			 */
2117 			if (un->un_pos.fileno != 0 || un->un_pos.blkno != 0) {
2118 				/*
2119 				 * set un_read_only/write-protect status.
2120 				 *
2121 				 * If the tape is not bot we can assume
2122 				 * that mspl->wp_status is set properly.
2123 				 * else
2124 				 * we need to do a mode sense/Tur once
2125 				 * again to get the actual tape status.(since
2126 				 * user might have replaced the tape)
2127 				 * Hence make the st state OFFLINE so that
2128 				 * we re-intialize the tape once again.
2129 				 */
2130 				un->un_read_only =
2131 				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2132 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2133 			} else {
2134 				un->un_state = ST_STATE_OFFLINE;
2135 			}
2136 			break;
2137 		case logical:
2138 			/* swag not sure how we were open last time */
2139 			(void) st_update_block_pos(un);
2140 			if (un->un_pos.lgclblkno == 0) {
2141 				un->un_state = ST_STATE_OFFLINE;
2142 			} else {
2143 				un->un_read_only =
2144 				    (un->un_oflags & FWRITE) ? 0 : 1;
2145 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2146 			}
2147 			break;
2148 		}
2149 		rval = 0;
2150 	} else {
2151 		/*
2152 		 * Not opening O_NDELAY.
2153 		 */
2154 		un->un_state = ST_STATE_OPENING;
2155 
2156 		/*
2157 		 * Clear error entry stack
2158 		 */
2159 		st_empty_error_stack(un);
2160 
2161 		rval = st_tape_init(dev);
2162 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
2163 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2164 			rval = 0; /* so open doesn't fail */
2165 		} else if (rval) {
2166 			/*
2167 			 * Release the tape unit, if reserved and not
2168 			 * preserve reserve.
2169 			 */
2170 			if ((un->un_rsvd_status &
2171 			    (ST_RESERVE | ST_PRESERVE_RESERVE)) == ST_RESERVE) {
2172 				(void) st_reserve_release(un, ST_RELEASE);
2173 			}
2174 		} else {
2175 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2176 		}
2177 	}
2178 
2179 exit:
2180 	/*
2181 	 * we don't want any uninvited guests scrogging our data when we're
2182 	 * busy with something, so for successful opens or failed opens
2183 	 * (except for EBUSY), reset these counters and state appropriately.
2184 	 */
2185 	if (rval != EBUSY) {
2186 		if (rval) {
2187 			un->un_state = ST_STATE_CLOSED;
2188 		}
2189 		un->un_err_resid = 0;
2190 		un->un_retry_ct = 0;
2191 		un->un_tran_retry_ct = 0;
2192 	}
2193 busy:
2194 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2195 	    "st_open: return val = %x, state = %d\n", rval, un->un_state);
2196 	mutex_exit(ST_MUTEX);
2197 	return (rval);
2198 
2199 }
2200 
2201 static int
2202 st_tape_init(dev_t dev)
2203 {
2204 	int err;
2205 	int rval = 0;
2206 
2207 	GET_SOFT_STATE(dev);
2208 
2209 	ST_FUNC(ST_DEVINFO, st_tape_init);
2210 
2211 	ASSERT(mutex_owned(ST_MUTEX));
2212 
2213 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2214 	    "st_tape_init(dev = 0x%lx, oflags = %d)\n", dev, un->un_oflags);
2215 
2216 	/*
2217 	 * Clean up after any errors left by 'last' close.
2218 	 * This also handles the case of the initial open.
2219 	 */
2220 	if (un->un_state != ST_STATE_INITIALIZING) {
2221 		un->un_laststate = un->un_state;
2222 		un->un_state = ST_STATE_OPENING;
2223 	}
2224 
2225 	un->un_kbytes_xferred = 0;
2226 
2227 	/*
2228 	 * do a throw away TUR to clear check condition
2229 	 */
2230 	err = st_cmd(dev, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
2231 
2232 	/*
2233 	 * If test unit ready fails because the drive is reserved
2234 	 * by another host fail the open for no access.
2235 	 */
2236 	if (err) {
2237 		if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
2238 			un->un_state = ST_STATE_CLOSED;
2239 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2240 			    "st_tape_init: RESERVATION CONFLICT\n");
2241 			rval = EACCES;
2242 			goto exit;
2243 		}
2244 	}
2245 
2246 	/*
2247 	 * See whether this is a generic device that we haven't figured
2248 	 * anything out about yet.
2249 	 */
2250 	if (un->un_dp->type == ST_TYPE_INVALID) {
2251 		rval = st_determine_generic(dev);
2252 		if (rval) {
2253 			if (rval != EACCES) {
2254 				rval = EIO;
2255 			}
2256 			un->un_state = ST_STATE_CLOSED;
2257 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2258 			    "st_tape_init: %s invalid type\n",
2259 			    rval == EACCES ? "EACCES" : "EIO");
2260 			goto exit;
2261 		}
2262 		/*
2263 		 * If this is a Unknown Type drive,
2264 		 * Use the READ BLOCK LIMITS to determine if
2265 		 * allow large xfer is approprate if not globally
2266 		 * disabled with st_allow_large_xfer.
2267 		 */
2268 		un->un_allow_large_xfer = (uchar_t)st_allow_large_xfer;
2269 	} else {
2270 
2271 		/*
2272 		 * If we allow_large_xfer (ie >64k) and have not yet found out
2273 		 * the max block size supported by the drive,
2274 		 * find it by issueing a READ_BLKLIM command.
2275 		 * if READ_BLKLIM cmd fails, assume drive doesn't
2276 		 * allow_large_xfer and min/max block sizes as 1 byte and 63k.
2277 		 */
2278 		un->un_allow_large_xfer = st_allow_large_xfer &&
2279 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT);
2280 	}
2281 	/*
2282 	 * if maxbsize is unknown, set the maximum block size.
2283 	 */
2284 	if (un->un_maxbsize == MAXBSIZE_UNKNOWN) {
2285 
2286 		/*
2287 		 * Get the Block limits of the tape drive.
2288 		 * if un->un_allow_large_xfer = 0 , then make sure
2289 		 * that maxbsize is <= ST_MAXRECSIZE_FIXED.
2290 		 */
2291 		un->un_rbl = kmem_zalloc(RBLSIZE, KM_SLEEP);
2292 
2293 		err = st_cmd(dev, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
2294 		if (err) {
2295 			/* Retry */
2296 			err = st_cmd(dev, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
2297 		}
2298 		if (!err) {
2299 
2300 			/*
2301 			 * if cmd successful, use limit returned
2302 			 */
2303 			un->un_maxbsize = (un->un_rbl->max_hi << 16) +
2304 			    (un->un_rbl->max_mid << 8) +
2305 			    un->un_rbl->max_lo;
2306 			un->un_minbsize = (un->un_rbl->min_hi << 8) +
2307 			    un->un_rbl->min_lo;
2308 			un->un_data_mod = 1 << un->un_rbl->granularity;
2309 			if ((un->un_maxbsize == 0) ||
2310 			    (un->un_allow_large_xfer == 0 &&
2311 			    un->un_maxbsize > ST_MAXRECSIZE_FIXED)) {
2312 				un->un_maxbsize = ST_MAXRECSIZE_FIXED;
2313 
2314 			} else if (un->un_dp->type == ST_TYPE_DEFAULT) {
2315 				/*
2316 				 * Drive is not one that is configured, But the
2317 				 * READ BLOCK LIMITS tells us it can do large
2318 				 * xfers.
2319 				 */
2320 				if (un->un_maxbsize > ST_MAXRECSIZE_FIXED) {
2321 					un->un_dp->options |=
2322 					    ST_NO_RECSIZE_LIMIT;
2323 				}
2324 				/*
2325 				 * If max and mimimum block limits are the
2326 				 * same this is a fixed block size device.
2327 				 */
2328 				if (un->un_maxbsize == un->un_minbsize) {
2329 					un->un_dp->options &= ~ST_VARIABLE;
2330 				}
2331 			}
2332 
2333 			if (un->un_minbsize == 0) {
2334 				un->un_minbsize = 1;
2335 			}
2336 
2337 		} else { /* error on read block limits */
2338 
2339 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2340 			    "!st_tape_init: Error on READ BLOCK LIMITS,"
2341 			    " errno = %d un_rsvd_status = 0x%X\n",
2342 			    err, un->un_rsvd_status);
2343 
2344 			/*
2345 			 * since read block limits cmd failed,
2346 			 * do not allow large xfers.
2347 			 * use old values in st_minphys
2348 			 */
2349 			if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
2350 				rval = EACCES;
2351 			} else {
2352 				un->un_allow_large_xfer = 0;
2353 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2354 				    "!Disabling large transfers\n");
2355 
2356 				/*
2357 				 * we guess maxbsize and minbsize
2358 				 */
2359 				if (un->un_bsize) {
2360 					un->un_maxbsize = un->un_minbsize =
2361 					    un->un_bsize;
2362 				} else {
2363 					un->un_maxbsize = ST_MAXRECSIZE_FIXED;
2364 					un->un_minbsize = 1;
2365 				}
2366 				/*
2367 				 * Data Mod must be set,
2368 				 * Even if read block limits fails.
2369 				 * Prevents Divide By Zero in st_rw().
2370 				 */
2371 				un->un_data_mod = 1;
2372 			}
2373 		}
2374 		if (un->un_rbl) {
2375 			kmem_free(un->un_rbl, RBLSIZE);
2376 			un->un_rbl = NULL;
2377 		}
2378 
2379 		if (rval) {
2380 			goto exit;
2381 		}
2382 	}
2383 
2384 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
2385 	    "maxdma = %d, maxbsize = %d, minbsize = %d, %s large xfer\n",
2386 	    un->un_maxdma, un->un_maxbsize, un->un_minbsize,
2387 	    (un->un_allow_large_xfer ? "ALLOW": "DON'T ALLOW"));
2388 
2389 	err = st_cmd(dev, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
2390 
2391 	if (err != 0) {
2392 		if (err == EINTR) {
2393 			un->un_laststate = un->un_state;
2394 			un->un_state = ST_STATE_CLOSED;
2395 			rval = EINTR;
2396 			goto exit;
2397 		}
2398 		/*
2399 		 * Make sure the tape is ready
2400 		 */
2401 		un->un_pos.pmode = invalid;
2402 		if (un->un_status != KEY_UNIT_ATTENTION) {
2403 			/*
2404 			 * allow open no media.  Subsequent MTIOCSTATE
2405 			 * with media present will complete the open
2406 			 * logic.
2407 			 */
2408 			un->un_laststate = un->un_state;
2409 			if (un->un_oflags & (FNONBLOCK|FNDELAY)) {
2410 				un->un_mediastate = MTIO_EJECTED;
2411 				un->un_state = ST_STATE_OFFLINE;
2412 				rval = 0;
2413 				goto exit;
2414 			} else {
2415 				un->un_state = ST_STATE_CLOSED;
2416 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2417 				    "st_tape_init EIO no media, not opened "
2418 				    "O_NONBLOCK|O_EXCL\n");
2419 				rval = EIO;
2420 				goto exit;
2421 			}
2422 		}
2423 	}
2424 
2425 	/*
2426 	 * On each open, initialize block size from drivetype struct,
2427 	 * as it could have been changed by MTSRSZ ioctl.
2428 	 * Now, ST_VARIABLE simply means drive is capable of variable
2429 	 * mode. All drives are assumed to support fixed records.
2430 	 * Hence, un_bsize tells what mode the drive is in.
2431 	 *	un_bsize	= 0	- variable record length
2432 	 *			= x	- fixed record length is x
2433 	 */
2434 	un->un_bsize = un->un_dp->bsize;
2435 
2436 	/*
2437 	 * If saved position is valid go there
2438 	 */
2439 	if (un->un_restore_pos) {
2440 		rval = st_validate_tapemarks(un, &un->un_pos);
2441 		if (rval != 0) {
2442 			if (rval != EACCES) {
2443 				rval = EIO;
2444 			}
2445 			un->un_restore_pos = 0;
2446 			un->un_laststate = un->un_state;
2447 			un->un_state = ST_STATE_CLOSED;
2448 			goto exit;
2449 		}
2450 		un->un_pos.fileno = un->un_save_fileno;
2451 		un->un_pos.blkno = un->un_save_blkno;
2452 		un->un_restore_pos = 0;
2453 	}
2454 
2455 	if (un->un_pos.pmode == invalid) {
2456 		rval = st_loadtape(dev);
2457 		if (rval) {
2458 			if (rval != EACCES) {
2459 				rval = EIO;
2460 			}
2461 			un->un_laststate = un->un_state;
2462 			un->un_state = ST_STATE_CLOSED;
2463 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2464 			    "st_tape_init: %s can't open tape\n",
2465 			    rval == EACCES ? "EACCES" : "EIO");
2466 			goto exit;
2467 		}
2468 	}
2469 
2470 	/*
2471 	 * do a mode sense to pick up state of current write-protect,
2472 	 * Could cause reserve and fail due to conflict.
2473 	 */
2474 	rval = st_modesense(un);
2475 	if (rval == EACCES) {
2476 		goto exit;
2477 	}
2478 
2479 	/*
2480 	 * If we are opening the tape for writing, check
2481 	 * to make sure that the tape can be written.
2482 	 */
2483 	if (un->un_oflags & FWRITE) {
2484 		err = 0;
2485 		if (un->un_mspl->wp) {
2486 			un->un_status = KEY_WRITE_PROTECT;
2487 			un->un_laststate = un->un_state;
2488 			un->un_state = ST_STATE_CLOSED;
2489 			rval = EACCES;
2490 			/*
2491 			 * STK sets the wp bit if volsafe tape is loaded.
2492 			 */
2493 			if ((un->un_dp->type == MT_ISSTK9840) &&
2494 			    (un->un_dp->options & ST_WORMABLE)) {
2495 				un->un_read_only = RDONLY;
2496 			} else {
2497 				goto exit;
2498 			}
2499 		} else {
2500 			un->un_read_only = RDWR;
2501 		}
2502 	} else {
2503 		un->un_read_only = RDONLY;
2504 	}
2505 
2506 	if (un->un_dp->options & ST_WORMABLE) {
2507 		un->un_read_only |= un->un_wormable(un);
2508 
2509 		if (((un->un_read_only == WORM) ||
2510 		    (un->un_read_only == RDWORM)) &&
2511 		    ((un->un_oflags & FWRITE) == FWRITE)) {
2512 			un->un_status = KEY_DATA_PROTECT;
2513 			rval = EACCES;
2514 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
2515 			    "read_only = %d eof = %d oflag = %d\n",
2516 			    un->un_read_only, un->un_pos.eof, un->un_oflags);
2517 		}
2518 	}
2519 
2520 	/*
2521 	 * If we're opening the tape write-only, we need to
2522 	 * write 2 filemarks on the HP 1/2 inch drive, to
2523 	 * create a null file.
2524 	 */
2525 	if ((un->un_read_only == RDWR) ||
2526 	    (un->un_read_only == WORM) && (un->un_oflags & FWRITE)) {
2527 		if (un->un_dp->options & ST_REEL) {
2528 			un->un_fmneeded = 2;
2529 		} else {
2530 			un->un_fmneeded = 1;
2531 		}
2532 	} else {
2533 		un->un_fmneeded = 0;
2534 	}
2535 
2536 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
2537 	    "fmneeded = %x\n", un->un_fmneeded);
2538 
2539 	/*
2540 	 * Make sure the density can be selected correctly.
2541 	 * If WORM can only write at the append point which in most cases
2542 	 * isn't BOP. st_determine_density() with a B_WRITE only attempts
2543 	 * to set and try densities if a BOP.
2544 	 */
2545 	if (st_determine_density(dev,
2546 	    un->un_read_only == RDWR ? B_WRITE : B_READ)) {
2547 		un->un_status = KEY_ILLEGAL_REQUEST;
2548 		un->un_laststate = un->un_state;
2549 		un->un_state = ST_STATE_CLOSED;
2550 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2551 		    "st_tape_init: EIO can't determine density\n");
2552 		rval = EIO;
2553 		goto exit;
2554 	}
2555 
2556 	/*
2557 	 * Destroy the knowledge that we have 'determined'
2558 	 * density so that a later read at BOT comes along
2559 	 * does the right density determination.
2560 	 */
2561 
2562 	un->un_density_known = 0;
2563 
2564 
2565 	/*
2566 	 * Okay, the tape is loaded and either at BOT or somewhere past.
2567 	 * Mark the state such that any I/O or tape space operations
2568 	 * will get/set the right density, etc..
2569 	 */
2570 	un->un_laststate = un->un_state;
2571 	un->un_lastop = ST_OP_NIL;
2572 	un->un_mediastate = MTIO_INSERTED;
2573 	cv_broadcast(&un->un_state_cv);
2574 
2575 	/*
2576 	 *  Set test append flag if writing.
2577 	 *  First write must check that tape is positioned correctly.
2578 	 */
2579 	un->un_test_append = (un->un_oflags & FWRITE);
2580 
2581 exit:
2582 	un->un_err_resid = 0;
2583 	un->un_last_resid = 0;
2584 	un->un_last_count = 0;
2585 
2586 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2587 	    "st_tape_init: return val = %x\n", rval);
2588 	return (rval);
2589 
2590 }
2591 
2592 
2593 
2594 /* ARGSUSED */
2595 static int
2596 st_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
2597 {
2598 	int err = 0;
2599 	int norew, count, last_state;
2600 #if defined(__i386) || defined(__amd64)
2601 	struct contig_mem *cp, *cp_temp;
2602 #endif
2603 
2604 	GET_SOFT_STATE(dev);
2605 
2606 	ST_ENTR(ST_DEVINFO, st_close);
2607 
2608 	/*
2609 	 * wait till all cmds in the pipeline have been completed
2610 	 */
2611 	mutex_enter(ST_MUTEX);
2612 
2613 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2614 	    "st_close(dev = 0x%lx, flag = %d, otyp = %d)\n", dev, flag, otyp);
2615 
2616 	st_wait_for_io(un);
2617 
2618 	/* turn off persistent errors on close, as we want close to succeed */
2619 	TURN_PE_OFF(un);
2620 
2621 	/*
2622 	 * set state to indicate that we are in process of closing
2623 	 */
2624 	last_state = un->un_laststate = un->un_state;
2625 	un->un_state = ST_STATE_CLOSING;
2626 
2627 	/*
2628 	 * BSD behavior:
2629 	 * a close always causes a silent span to the next file if we've hit
2630 	 * an EOF (but not yet read across it).
2631 	 */
2632 #ifdef DEBUG
2633 	if ((st_debug & 0xf) >= 6)
2634 		st_print_position(un, "st_close1:", &un->un_pos);
2635 #endif
2636 
2637 	if (BSD_BEHAVIOR && (un->un_pos.eof == ST_EOF)) {
2638 		if (un->un_pos.pmode != invalid) {
2639 			un->un_pos.fileno++;
2640 			un->un_pos.blkno = 0;
2641 		}
2642 		un->un_pos.eof = ST_NO_EOF;
2643 	}
2644 
2645 	/*
2646 	 * rewinding?
2647 	 */
2648 	norew = (getminor(dev) & MT_NOREWIND);
2649 
2650 	/*
2651 	 * SVR4 behavior for skipping to next file:
2652 	 *
2653 	 * If we have not seen a filemark, space to the next file
2654 	 *
2655 	 * If we have already seen the filemark we are physically in the next
2656 	 * file and we only increment the filenumber
2657 	 */
2658 
2659 
2660 	if (norew && SVR4_BEHAVIOR && (flag & FREAD) &&
2661 	    (un->un_pos.blkno != 0) &&
2662 	    ((un->un_lastop != ST_OP_WRITE) && (un->un_lastop != ST_OP_WEOF))) {
2663 		switch (un->un_pos.eof) {
2664 		case ST_NO_EOF:
2665 			/*
2666 			 * if we were reading and did not read the complete file
2667 			 * skip to the next file, leaving the tape correctly
2668 			 * positioned to read the first record of the next file
2669 			 * Check first for REEL if we are at EOT by trying to
2670 			 * read a block
2671 			 */
2672 			if ((un->un_dp->options & ST_REEL) &&
2673 			    (!(un->un_dp->options & ST_READ_IGNORE_EOFS)) &&
2674 			    (un->un_pos.blkno == 0)) {
2675 				if (st_cmd(dev, SCMD_SPACE, Blk(1), SYNC_CMD)) {
2676 					ST_DEBUG2(ST_DEVINFO, st_label,
2677 					    SCSI_DEBUG,
2678 					    "st_close : EIO can't space\n");
2679 					err = EIO;
2680 					break;
2681 				}
2682 				if (un->un_pos.eof >= ST_EOF_PENDING) {
2683 					un->un_pos.eof = ST_EOT_PENDING;
2684 					un->un_pos.fileno += 1;
2685 					un->un_pos.blkno   = 0;
2686 					break;
2687 				}
2688 			}
2689 			if (st_cmd(dev, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
2690 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2691 				    "st_close: EIO can't space #2\n");
2692 				err = EIO;
2693 			} else {
2694 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2695 				    "st_close2: fileno=%x,blkno=%x,eof=%x\n",
2696 				    un->un_pos.fileno, un->un_pos.blkno,
2697 				    un->un_pos.eof);
2698 				un->un_pos.eof = ST_NO_EOF;
2699 			}
2700 			break;
2701 
2702 		case ST_EOF_PENDING:
2703 		case ST_EOF:
2704 			un->un_pos.fileno += 1;
2705 			un->un_pos.blkno   = 0;
2706 			un->un_pos.eof = ST_NO_EOF;
2707 			break;
2708 
2709 		case ST_EOT:
2710 		case ST_EOT_PENDING:
2711 			/* nothing to do */
2712 			break;
2713 		default:
2714 			scsi_log(ST_DEVINFO, st_label, CE_PANIC,
2715 			    "Undefined state 0x%x", un->un_pos.eof);
2716 
2717 		}
2718 	}
2719 
2720 
2721 	/*
2722 	 * For performance reasons (HP 88780), the driver should
2723 	 * postpone writing the second tape mark until just before a file
2724 	 * positioning ioctl is issued (e.g., rewind).	This means that
2725 	 * the user must not manually rewind the tape because the tape will
2726 	 * be missing the second tape mark which marks EOM.
2727 	 * However, this small performance improvement is not worth the risk.
2728 	 */
2729 
2730 	/*
2731 	 * We need to back up over the filemark we inadvertently popped
2732 	 * over doing a read in between the two filemarks that constitute
2733 	 * logical eot for 1/2" tapes. Note that ST_EOT_PENDING is only
2734 	 * set while reading.
2735 	 *
2736 	 * If we happen to be at physical eot (ST_EOM) (writing case),
2737 	 * the writing of filemark(s) will clear the ST_EOM state, which
2738 	 * we don't want, so we save this state and restore it later.
2739 	 */
2740 
2741 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2742 	    "flag=%x, fmneeded=%x, lastop=%x, eof=%x\n",
2743 	    flag, un->un_fmneeded, un->un_lastop, un->un_pos.eof);
2744 
2745 	if (un->un_pos.eof == ST_EOT_PENDING) {
2746 		if (norew) {
2747 			if (st_cmd(dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)) {
2748 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2749 				    "st_close: EIO can't space #3\n");
2750 				err = EIO;
2751 			} else {
2752 				un->un_pos.blkno = 0;
2753 				un->un_pos.eof = ST_EOT;
2754 			}
2755 		} else {
2756 			un->un_pos.eof = ST_NO_EOF;
2757 		}
2758 
2759 	/*
2760 	 * Do we need to write a file mark?
2761 	 *
2762 	 * only write filemarks if there are fmks to be written and
2763 	 *   - open for write (possibly read/write)
2764 	 *   - the last operation was a write
2765 	 * or:
2766 	 *   -	opened for wronly
2767 	 *   -	no data was written
2768 	 */
2769 	} else if ((un->un_pos.pmode != invalid) && (un->un_fmneeded > 0) &&
2770 	    (((flag & FWRITE) && (un->un_lastop == ST_OP_WRITE)) ||
2771 	    ((flag & FWRITE) && (un->un_lastop == ST_OP_WEOF)) ||
2772 	    ((flag == FWRITE) && (un->un_lastop == ST_OP_NIL)))) {
2773 
2774 		/* save ST_EOM state */
2775 		int was_at_eom = (un->un_pos.eof == ST_EOM) ? 1 : 0;
2776 
2777 		/*
2778 		 * Note that we will write a filemark if we had opened
2779 		 * the tape write only and no data was written, thus
2780 		 * creating a null file.
2781 		 *
2782 		 * If the user already wrote one, we only have to write 1 more.
2783 		 * If they wrote two, we don't have to write any.
2784 		 */
2785 
2786 		count = un->un_fmneeded;
2787 		if (count > 0) {
2788 			if (st_cmd(dev, SCMD_WRITE_FILE_MARK,
2789 			    count, SYNC_CMD)) {
2790 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2791 				    "st_close : EIO can't wfm\n");
2792 				err = EIO;
2793 			}
2794 			if ((un->un_dp->options & ST_REEL) && norew) {
2795 				if (st_cmd(dev, SCMD_SPACE, Fmk((-1)),
2796 				    SYNC_CMD)) {
2797 					ST_DEBUG2(ST_DEVINFO, st_label,
2798 					    SCSI_DEBUG,
2799 					    "st_close : EIO space fmk(-1)\n");
2800 					err = EIO;
2801 				}
2802 				un->un_pos.eof = ST_NO_EOF;
2803 				/* fix up block number */
2804 				un->un_pos.blkno = 0;
2805 			}
2806 		}
2807 
2808 		/*
2809 		 * If we aren't going to be rewinding, and we were at
2810 		 * physical eot, restore the state that indicates we
2811 		 * are at physical eot. Once you have reached physical
2812 		 * eot, and you close the tape, the only thing you can
2813 		 * do on the next open is to rewind. Access to trailer
2814 		 * records is only allowed without closing the device.
2815 		 */
2816 		if (norew == 0 && was_at_eom) {
2817 			un->un_pos.eof = ST_EOM;
2818 		}
2819 	}
2820 
2821 	/*
2822 	 * report soft errors if enabled and available, if we never accessed
2823 	 * the drive, don't get errors. This will prevent some DAT error
2824 	 * messages upon LOG SENSE.
2825 	 */
2826 	if (st_report_soft_errors_on_close &&
2827 	    (un->un_dp->options & ST_SOFT_ERROR_REPORTING) &&
2828 	    (last_state != ST_STATE_OFFLINE)) {
2829 		(void) st_report_soft_errors(dev, flag);
2830 	}
2831 
2832 
2833 	/*
2834 	 * Do we need to rewind? Can we rewind?
2835 	 */
2836 	if (norew == 0 && un->un_pos.pmode != invalid && err == 0) {
2837 		/*
2838 		 * We'd like to rewind with the
2839 		 * 'immediate' bit set, but this
2840 		 * causes problems on some drives
2841 		 * where subsequent opens get a
2842 		 * 'NOT READY' error condition
2843 		 * back while the tape is rewinding,
2844 		 * which is impossible to distinguish
2845 		 * from the condition of 'no tape loaded'.
2846 		 *
2847 		 * Also, for some targets, if you disconnect
2848 		 * with the 'immediate' bit set, you don't
2849 		 * actually return right away, i.e., the
2850 		 * target ignores your request for immediate
2851 		 * return.
2852 		 *
2853 		 * Instead, we'll fire off an async rewind
2854 		 * command. We'll mark the device as closed,
2855 		 * and any subsequent open will stall on
2856 		 * the first TEST_UNIT_READY until the rewind
2857 		 * completes.
2858 		 */
2859 
2860 		/*
2861 		 * Used to be if reserve was not supported we'd send an
2862 		 * asynchronious rewind. Comments above may be slightly invalid
2863 		 * as the immediate bit was never set. Doing an immedate rewind
2864 		 * makes sense, I think fixes to not ready status might handle
2865 		 * the problems described above.
2866 		 */
2867 		if (un->un_sd->sd_inq->inq_ansi < 2) {
2868 			(void) st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD);
2869 		} else {
2870 			(void) st_cmd(dev, SCMD_REWIND, 0, ASYNC_CMD);
2871 		}
2872 	}
2873 
2874 	/*
2875 	 * eject tape if necessary
2876 	 */
2877 	if (un->un_eject_tape_on_failure) {
2878 		un->un_eject_tape_on_failure = 0;
2879 		if (st_cmd(dev, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
2880 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2881 			    "st_close : can't unload tape\n");
2882 		} else {
2883 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2884 			    "st_close : tape unloaded \n");
2885 			un->un_pos.eof = ST_NO_EOF;
2886 			un->un_mediastate = MTIO_EJECTED;
2887 		}
2888 	}
2889 	/*
2890 	 * Release the tape unit, if default reserve/release
2891 	 * behaviour.
2892 	 */
2893 	if ((un->un_rsvd_status &
2894 	    (ST_RESERVE | ST_PRESERVE_RESERVE)) == ST_RESERVE) {
2895 		(void) st_reserve_release(un, ST_RELEASE);
2896 	}
2897 
2898 	/*
2899 	 * clear up state
2900 	 */
2901 	un->un_laststate = un->un_state;
2902 	un->un_state = ST_STATE_CLOSED;
2903 	un->un_lastop = ST_OP_NIL;
2904 	un->un_throttle = 1;	/* assume one request at time, for now */
2905 	un->un_retry_ct = 0;
2906 	un->un_tran_retry_ct = 0;
2907 	un->un_errno = 0;
2908 	un->un_swr_token = (opaque_t)NULL;
2909 	un->un_rsvd_status &= ~(ST_INIT_RESERVE);
2910 
2911 	/* Restore the options to the init time settings */
2912 	if (un->un_init_options & ST_READ_IGNORE_ILI) {
2913 		un->un_dp->options |= ST_READ_IGNORE_ILI;
2914 	} else {
2915 		un->un_dp->options &= ~ST_READ_IGNORE_ILI;
2916 	}
2917 
2918 	if (un->un_init_options & ST_READ_IGNORE_EOFS) {
2919 		un->un_dp->options |= ST_READ_IGNORE_EOFS;
2920 	} else {
2921 		un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
2922 	}
2923 
2924 	if (un->un_init_options & ST_SHORT_FILEMARKS) {
2925 		un->un_dp->options |= ST_SHORT_FILEMARKS;
2926 	} else {
2927 		un->un_dp->options &= ~ST_SHORT_FILEMARKS;
2928 	}
2929 
2930 	ASSERT(mutex_owned(ST_MUTEX));
2931 
2932 	/*
2933 	 * Signal anyone awaiting a close operation to complete.
2934 	 */
2935 	cv_signal(&un->un_clscv);
2936 
2937 	/*
2938 	 * any kind of error on closing causes all state to be tossed
2939 	 */
2940 	if (err && un->un_status != KEY_ILLEGAL_REQUEST) {
2941 		/*
2942 		 * note that st_intr has already set
2943 		 * un_pos.pmode to invalid.
2944 		 */
2945 		un->un_density_known = 0;
2946 	}
2947 
2948 #if defined(__i386) || defined(__amd64)
2949 	/*
2950 	 * free any contiguous mem alloc'ed for big block I/O
2951 	 */
2952 	cp = un->un_contig_mem;
2953 	while (cp) {
2954 		if (cp->cm_addr) {
2955 			ddi_dma_mem_free(&cp->cm_acc_hdl);
2956 		}
2957 		cp_temp = cp;
2958 		cp = cp->cm_next;
2959 		kmem_free(cp_temp,
2960 		    sizeof (struct contig_mem) + biosize());
2961 	}
2962 	un->un_contig_mem_total_num = 0;
2963 	un->un_contig_mem_available_num = 0;
2964 	un->un_contig_mem = NULL;
2965 	un->un_max_contig_mem_len = 0;
2966 #endif
2967 
2968 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2969 	    "st_close3: return val = %x, fileno=%x, blkno=%x, eof=%x\n",
2970 	    err, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
2971 
2972 	mutex_exit(ST_MUTEX);
2973 	return (err);
2974 }
2975 
2976 /*
2977  * These routines perform raw i/o operations.
2978  */
2979 
2980 /* ARGSUSED2 */
2981 static int
2982 st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p)
2983 {
2984 #ifdef DEBUG
2985 	GET_SOFT_STATE(dev);
2986 	ST_ENTR(ST_DEVINFO, st_aread);
2987 #endif
2988 	return (st_arw(dev, aio, B_READ));
2989 }
2990 
2991 
2992 /* ARGSUSED2 */
2993 static int
2994 st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p)
2995 {
2996 #ifdef DEBUG
2997 	GET_SOFT_STATE(dev);
2998 	ST_ENTR(ST_DEVINFO, st_awrite);
2999 #endif
3000 	return (st_arw(dev, aio, B_WRITE));
3001 }
3002 
3003 
3004 
3005 /* ARGSUSED */
3006 static int
3007 st_read(dev_t dev, struct uio *uiop, cred_t *cred_p)
3008 {
3009 #ifdef DEBUG
3010 	GET_SOFT_STATE(dev);
3011 	ST_ENTR(ST_DEVINFO, st_read);
3012 #endif
3013 	return (st_rw(dev, uiop, B_READ));
3014 }
3015 
3016 /* ARGSUSED */
3017 static int
3018 st_write(dev_t dev, struct uio *uiop, cred_t *cred_p)
3019 {
3020 #ifdef DEBUG
3021 	GET_SOFT_STATE(dev);
3022 	ST_ENTR(ST_DEVINFO, st_write);
3023 #endif
3024 	return (st_rw(dev, uiop, B_WRITE));
3025 }
3026 
3027 /*
3028  * Due to historical reasons, old limits are: For variable-length devices:
3029  * if greater than 64KB - 1 (ST_MAXRECSIZE_VARIABLE), block into 64 KB - 2
3030  * ST_MAXRECSIZE_VARIABLE_LIMIT) requests; otherwise,
3031  * (let it through unmodified. For fixed-length record devices:
3032  * 63K (ST_MAXRECSIZE_FIXED) is max (default minphys).
3033  *
3034  * The new limits used are un_maxdma (retrieved using scsi_ifgetcap()
3035  * from the HBA) and un_maxbsize (retrieved by sending SCMD_READ_BLKLIM
3036  * command to the drive).
3037  *
3038  */
3039 static void
3040 st_minphys(struct buf *bp)
3041 {
3042 	struct scsi_tape *un;
3043 
3044 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
3045 
3046 	ST_FUNC(ST_DEVINFO, st_minphys);
3047 
3048 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3049 	    "st_minphys(bp = 0x%p): b_bcount = 0x%lx\n", (void *)bp,
3050 	    bp->b_bcount);
3051 
3052 	if (un->un_allow_large_xfer) {
3053 
3054 		/*
3055 		 * check un_maxbsize for variable length devices only
3056 		 */
3057 		if (un->un_bsize == 0 && bp->b_bcount > un->un_maxbsize) {
3058 			bp->b_bcount = un->un_maxbsize;
3059 		}
3060 		/*
3061 		 * can't go more that HBA maxdma limit in either fixed-length
3062 		 * or variable-length tape drives.
3063 		 */
3064 		if (bp->b_bcount > un->un_maxdma) {
3065 			bp->b_bcount = un->un_maxdma;
3066 		}
3067 	} else {
3068 
3069 		/*
3070 		 *  use old fixed limits
3071 		 */
3072 		if (un->un_bsize == 0) {
3073 			if (bp->b_bcount > ST_MAXRECSIZE_VARIABLE) {
3074 				bp->b_bcount = ST_MAXRECSIZE_VARIABLE_LIMIT;
3075 			}
3076 		} else {
3077 			if (bp->b_bcount > ST_MAXRECSIZE_FIXED) {
3078 				bp->b_bcount = ST_MAXRECSIZE_FIXED;
3079 			}
3080 		}
3081 	}
3082 
3083 	/*
3084 	 * For regular raw I/O and Fixed Block length devices, make sure
3085 	 * the adjusted block count is a whole multiple of the device
3086 	 * block size.
3087 	 */
3088 	if (bp != un->un_sbufp && un->un_bsize) {
3089 		bp->b_bcount -= (bp->b_bcount % un->un_bsize);
3090 	}
3091 }
3092 
3093 static int
3094 st_rw(dev_t dev, struct uio *uio, int flag)
3095 {
3096 	int rval = 0;
3097 	long len;
3098 
3099 	GET_SOFT_STATE(dev);
3100 
3101 	ST_FUNC(ST_DEVINFO, st_rw);
3102 
3103 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3104 	    "st_rw(dev = 0x%lx, flag = %s)\n", dev,
3105 	    (flag == B_READ ? rd_str: wr_str));
3106 
3107 	/* get local copy of transfer length */
3108 	len = uio->uio_iov->iov_len;
3109 
3110 	mutex_enter(ST_MUTEX);
3111 
3112 	/*
3113 	 * Clear error entry stack
3114 	 */
3115 	st_empty_error_stack(un);
3116 
3117 	/*
3118 	 * If in fixed block size mode and requested read or write
3119 	 * is not an even multiple of that block size.
3120 	 */
3121 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
3122 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3123 		    "%s: not modulo %d block size\n",
3124 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3125 		rval = EINVAL;
3126 	}
3127 
3128 	/* If device has set granularity in the READ_BLKLIM we honor it. */
3129 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3130 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3131 		    "%s: not modulo %d device granularity\n",
3132 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
3133 		rval = EINVAL;
3134 	}
3135 
3136 	if (rval != 0) {
3137 		un->un_errno = rval;
3138 		mutex_exit(ST_MUTEX);
3139 		return (rval);
3140 	}
3141 
3142 	/*
3143 	 * Reset this so it can be set if Berkeley and read over a filemark.
3144 	 */
3145 	un->un_silent_skip = 0;
3146 	mutex_exit(ST_MUTEX);
3147 
3148 	len = uio->uio_resid;
3149 
3150 	rval = physio(st_strategy, (struct buf *)NULL,
3151 	    dev, flag, st_minphys, uio);
3152 	/*
3153 	 * if we have hit logical EOT during this xfer and there is not a
3154 	 * full residue, then set eof back  to ST_EOM to make sure that
3155 	 * the user will see at least one zero write
3156 	 * after this short write
3157 	 */
3158 	mutex_enter(ST_MUTEX);
3159 	if (un->un_pos.eof > ST_NO_EOF) {
3160 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3161 		"eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
3162 	}
3163 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
3164 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
3165 			un->un_pos.eof = ST_EOM;
3166 		} else if (uio->uio_resid == len) {
3167 			un->un_pos.eof = ST_NO_EOF;
3168 		}
3169 	}
3170 
3171 	if (un->un_silent_skip && uio->uio_resid != len) {
3172 		un->un_pos.eof = ST_EOF;
3173 		un->un_pos.blkno = un->un_save_blkno;
3174 		un->un_pos.fileno--;
3175 	}
3176 
3177 	un->un_errno = rval;
3178 
3179 	mutex_exit(ST_MUTEX);
3180 
3181 	return (rval);
3182 }
3183 
3184 static int
3185 st_arw(dev_t dev, struct aio_req *aio, int flag)
3186 {
3187 	struct uio *uio = aio->aio_uio;
3188 	int rval = 0;
3189 	long len;
3190 
3191 	GET_SOFT_STATE(dev);
3192 
3193 	ST_FUNC(ST_DEVINFO, st_arw);
3194 
3195 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3196 	    "st_rw(dev = 0x%lx, flag = %s)\n", dev,
3197 	    (flag == B_READ ? rd_str: wr_str));
3198 
3199 	/* get local copy of transfer length */
3200 	len = uio->uio_iov->iov_len;
3201 
3202 	mutex_enter(ST_MUTEX);
3203 
3204 	/*
3205 	 * If in fixed block size mode and requested read or write
3206 	 * is not an even multiple of that block size.
3207 	 */
3208 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
3209 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3210 		    "%s: not modulo %d block size\n",
3211 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3212 		rval = EINVAL;
3213 	}
3214 
3215 	/* If device has set granularity in the READ_BLKLIM we honor it. */
3216 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3217 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3218 		    "%s: not modulo %d device granularity\n",
3219 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
3220 		rval = EINVAL;
3221 	}
3222 
3223 	if (rval != 0) {
3224 		un->un_errno = rval;
3225 		mutex_exit(ST_MUTEX);
3226 		return (rval);
3227 	}
3228 
3229 	mutex_exit(ST_MUTEX);
3230 
3231 	len = uio->uio_resid;
3232 
3233 	rval = aphysio(st_strategy, anocancel, dev, flag, st_minphys, aio);
3234 
3235 	/*
3236 	 * if we have hit logical EOT during this xfer and there is not a
3237 	 * full residue, then set eof back  to ST_EOM to make sure that
3238 	 * the user will see at least one zero write
3239 	 * after this short write
3240 	 *
3241 	 * we keep this here just in case the application is not using
3242 	 * persistent errors
3243 	 */
3244 	mutex_enter(ST_MUTEX);
3245 	if (un->un_pos.eof > ST_NO_EOF) {
3246 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3247 		    "eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
3248 	}
3249 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
3250 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
3251 			un->un_pos.eof = ST_EOM;
3252 		} else if (uio->uio_resid == len && !IS_PE_FLAG_SET(un)) {
3253 			un->un_pos.eof = ST_NO_EOF;
3254 		}
3255 	}
3256 	un->un_errno = rval;
3257 	mutex_exit(ST_MUTEX);
3258 
3259 	return (rval);
3260 }
3261 
3262 
3263 
3264 static int
3265 st_strategy(struct buf *bp)
3266 {
3267 	struct scsi_tape *un;
3268 	dev_t dev = bp->b_edev;
3269 
3270 	/*
3271 	 * validate arguments
3272 	 */
3273 	if ((un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev))) == NULL) {
3274 		bp->b_resid = bp->b_bcount;
3275 		mutex_enter(ST_MUTEX);
3276 		st_bioerror(bp, ENXIO);
3277 		mutex_exit(ST_MUTEX);
3278 		goto error;
3279 	}
3280 
3281 	ST_ENTR(ST_DEVINFO, st_strategy);
3282 
3283 	mutex_enter(ST_MUTEX);
3284 
3285 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
3286 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
3287 	}
3288 
3289 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3290 	    "st_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
3291 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
3292 
3293 	/*
3294 	 * If persistent errors have been flagged, just nix this one. We wait
3295 	 * for any outstanding I/O's below, so we will be in order.
3296 	 */
3297 	if (IS_PE_FLAG_SET(un)) {
3298 		goto exit;
3299 	}
3300 
3301 	if (bp != un->un_sbufp) {
3302 		char reading = bp->b_flags & B_READ;
3303 		int wasopening = 0;
3304 
3305 		/*
3306 		 * If we haven't done/checked reservation on the tape unit
3307 		 * do it now.
3308 		 */
3309 		if ((un->un_rsvd_status &
3310 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
3311 			if ((un->un_dp->options & ST_NO_RESERVE_RELEASE) == 0) {
3312 				if (st_reserve_release(un, ST_RESERVE)) {
3313 					st_bioerror(bp, un->un_errno);
3314 					goto exit;
3315 				}
3316 			} else if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
3317 				/*
3318 				 * Enter here to restore position for possible
3319 				 * resets when the device was closed and opened
3320 				 * in O_NDELAY mode subsequently
3321 				 */
3322 				un->un_state = ST_STATE_INITIALIZING;
3323 				(void) st_cmd(dev, SCMD_TEST_UNIT_READY,
3324 				    0, SYNC_CMD);
3325 				un->un_state = ST_STATE_OPEN_PENDING_IO;
3326 			}
3327 			un->un_rsvd_status |= ST_INIT_RESERVE;
3328 		}
3329 
3330 		/*
3331 		 * If we are offline, we have to initialize everything first.
3332 		 * This is to handle either when opened with O_NDELAY, or
3333 		 * we just got a new tape in the drive, after an offline.
3334 		 * We don't observe O_NDELAY past the open,
3335 		 * as it will not make sense for tapes.
3336 		 */
3337 		if (un->un_state == ST_STATE_OFFLINE || un->un_restore_pos) {
3338 			/* reset state to avoid recursion */
3339 			un->un_state = ST_STATE_INITIALIZING;
3340 			if (st_tape_init(dev)) {
3341 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3342 				    "stioctl : OFFLINE init failure ");
3343 				un->un_state = ST_STATE_OFFLINE;
3344 				un->un_pos.pmode = invalid;
3345 				goto b_done_err;
3346 			}
3347 			un->un_state = ST_STATE_OPEN_PENDING_IO;
3348 		}
3349 		/*
3350 		 * Check for legal operations
3351 		 */
3352 		if (un->un_pos.pmode == invalid) {
3353 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3354 			    "strategy with un->un_pos.pmode invalid\n");
3355 			goto b_done_err;
3356 		}
3357 
3358 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3359 		    "st_strategy(): regular io\n");
3360 
3361 		/*
3362 		 * Process this first. If we were reading, and we're pending
3363 		 * logical eot, that means we've bumped one file mark too far.
3364 		 */
3365 
3366 		/*
3367 		 * Recursion warning: st_cmd will route back through here.
3368 		 */
3369 		if (un->un_pos.eof == ST_EOT_PENDING) {
3370 			if (st_cmd(dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)) {
3371 				un->un_pos.pmode = invalid;
3372 				un->un_density_known = 0;
3373 				goto b_done_err;
3374 			}
3375 			un->un_pos.blkno = 0; /* fix up block number.. */
3376 			un->un_pos.eof = ST_EOT;
3377 		}
3378 
3379 		/*
3380 		 * If we are in the process of opening, we may have to
3381 		 * determine/set the correct density. We also may have
3382 		 * to do a test_append (if QIC) to see whether we are
3383 		 * in a position to append to the end of the tape.
3384 		 *
3385 		 * If we're already at logical eot, we transition
3386 		 * to ST_NO_EOF. If we're at physical eot, we punt
3387 		 * to the switch statement below to handle.
3388 		 */
3389 		if ((un->un_state == ST_STATE_OPEN_PENDING_IO) ||
3390 		    (un->un_test_append && (un->un_dp->options & ST_QIC))) {
3391 
3392 			if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
3393 				if (st_determine_density(dev, (int)reading)) {
3394 					goto b_done_err;
3395 				}
3396 			}
3397 
3398 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3399 			    "pending_io@fileno %d rw %d qic %d eof %d\n",
3400 			    un->un_pos.fileno, (int)reading,
3401 			    (un->un_dp->options & ST_QIC) ? 1 : 0,
3402 			    un->un_pos.eof);
3403 
3404 			if (!reading && un->un_pos.eof != ST_EOM) {
3405 				if (un->un_pos.eof == ST_EOT) {
3406 					un->un_pos.eof = ST_NO_EOF;
3407 				} else if (un->un_pos.pmode != invalid &&
3408 				    (un->un_dp->options & ST_QIC)) {
3409 					/*
3410 					 * st_test_append() will do it all
3411 					 */
3412 					st_test_append(bp);
3413 					goto done;
3414 				}
3415 			}
3416 			if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
3417 				wasopening = 1;
3418 			}
3419 			un->un_laststate = un->un_state;
3420 			un->un_state = ST_STATE_OPEN;
3421 		}
3422 
3423 
3424 		/*
3425 		 * Process rest of END OF FILE and END OF TAPE conditions
3426 		 */
3427 
3428 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3429 		    "eof=%x, wasopening=%x\n",
3430 		    un->un_pos.eof, wasopening);
3431 
3432 		switch (un->un_pos.eof) {
3433 		case ST_EOM:
3434 			/*
3435 			 * This allows writes to proceed past physical
3436 			 * eot. We'll *really* be in trouble if the
3437 			 * user continues blindly writing data too
3438 			 * much past this point (unwind the tape).
3439 			 * Physical eot really means 'early warning
3440 			 * eot' in this context.
3441 			 *
3442 			 * Every other write from now on will succeed
3443 			 * (if sufficient  tape left).
3444 			 * This write will return with resid == count
3445 			 * but the next one should be successful
3446 			 *
3447 			 * Note that we only transition to logical EOT
3448 			 * if the last state wasn't the OPENING state.
3449 			 * We explicitly prohibit running up to physical
3450 			 * eot, closing the device, and then re-opening
3451 			 * to proceed. Trailer records may only be gotten
3452 			 * at by keeping the tape open after hitting eot.
3453 			 *
3454 			 * Also note that ST_EOM cannot be set by reading-
3455 			 * this can only be set during writing. Reading
3456 			 * up to the end of the tape gets a blank check
3457 			 * or a double-filemark indication (ST_EOT_PENDING),
3458 			 * and we prohibit reading after that point.
3459 			 *
3460 			 */
3461 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOM\n");
3462 			if (wasopening == 0) {
3463 				/*
3464 				 * this allows st_rw() to reset it back to
3465 				 * ST_EOM to make sure that the application
3466 				 * will see a zero write
3467 				 */
3468 				un->un_pos.eof = ST_WRITE_AFTER_EOM;
3469 			}
3470 			un->un_status = SUN_KEY_EOT;
3471 			goto b_done;
3472 
3473 		case ST_WRITE_AFTER_EOM:
3474 		case ST_EOT:
3475 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOT\n");
3476 			un->un_status = SUN_KEY_EOT;
3477 			if (SVR4_BEHAVIOR && reading) {
3478 				goto b_done_err;
3479 			}
3480 
3481 			if (reading) {
3482 				goto b_done;
3483 			}
3484 			un->un_pos.eof = ST_NO_EOF;
3485 			break;
3486 
3487 		case ST_EOF_PENDING:
3488 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3489 			    "EOF PENDING\n");
3490 			un->un_status = SUN_KEY_EOF;
3491 			if (SVR4_BEHAVIOR) {
3492 				un->un_pos.eof = ST_EOF;
3493 				goto b_done;
3494 			}
3495 			/* FALLTHROUGH */
3496 		case ST_EOF:
3497 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOF\n");
3498 			un->un_status = SUN_KEY_EOF;
3499 			if (SVR4_BEHAVIOR) {
3500 				goto b_done_err;
3501 			}
3502 
3503 			if (BSD_BEHAVIOR) {
3504 				un->un_pos.eof = ST_NO_EOF;
3505 				un->un_pos.fileno += 1;
3506 				un->un_pos.blkno   = 0;
3507 			}
3508 
3509 			if (reading) {
3510 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3511 				    "now file %d (read)\n",
3512 				    un->un_pos.fileno);
3513 				goto b_done;
3514 			}
3515 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3516 			    "now file %d (write)\n", un->un_pos.fileno);
3517 			break;
3518 		default:
3519 			un->un_status = 0;
3520 			break;
3521 		}
3522 	}
3523 
3524 	bp->b_flags &= ~(B_DONE);
3525 	st_bioerror(bp, 0);
3526 	bp->av_forw = NULL;
3527 	bp->b_resid = 0;
3528 	SET_BP_PKT(bp, 0);
3529 
3530 
3531 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3532 	    "st_strategy: cmd=0x%p  count=%ld  resid=%ld flags=0x%x"
3533 	    " pkt=0x%p\n",
3534 	    (void *)bp->b_forw, bp->b_bcount,
3535 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
3536 
3537 #if defined(__i386) || defined(__amd64)
3538 	/*
3539 	 * We will replace bp with a new bp that can do big blk xfer
3540 	 * if the requested xfer size is bigger than ST_BIGBLK_XFER
3541 	 *
3542 	 * Also, we need to make sure that we're handling real I/O
3543 	 * by checking group 0/1 SCSI I/O commands, if needed
3544 	 */
3545 	if (bp->b_bcount > ST_BIGBLK_XFER &&
3546 	    (bp != un->un_sbufp					||
3547 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_READ		||
3548 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_READ_G1	||
3549 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE	||
3550 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE_G1)) {
3551 		mutex_exit(ST_MUTEX);
3552 		bp = st_get_bigblk_bp(bp);
3553 		mutex_enter(ST_MUTEX);
3554 	}
3555 #endif
3556 
3557 	/* put on wait queue */
3558 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3559 	    "st_strategy: un->un_quef = 0x%p, bp = 0x%p\n",
3560 	    (void *)un->un_quef, (void *)bp);
3561 
3562 	if (un->un_quef) {
3563 		un->un_quel->b_actf = bp;
3564 	} else {
3565 		un->un_quef = bp;
3566 	}
3567 	un->un_quel = bp;
3568 
3569 	ST_DO_KSTATS(bp, kstat_waitq_enter);
3570 
3571 	st_start(un);
3572 
3573 done:
3574 	mutex_exit(ST_MUTEX);
3575 	return (0);
3576 
3577 
3578 error:
3579 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3580 	    "st_strategy: error exit\n");
3581 
3582 	biodone(bp);
3583 	return (0);
3584 
3585 b_done_err:
3586 	st_bioerror(bp, EIO);
3587 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3588 	    "st_strategy : EIO b_done_err\n");
3589 
3590 b_done:
3591 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3592 	    "st_strategy: b_done\n");
3593 
3594 exit:
3595 	/*
3596 	 * make sure no commands are outstanding or waiting before closing,
3597 	 * so we can guarantee order
3598 	 */
3599 	st_wait_for_io(un);
3600 	un->un_err_resid = bp->b_resid = bp->b_bcount;
3601 
3602 	/* override errno here, if persistent errors were flagged */
3603 	if (IS_PE_FLAG_SET(un))
3604 		bioerror(bp, un->un_errno);
3605 
3606 	mutex_exit(ST_MUTEX);
3607 
3608 	biodone(bp);
3609 	ASSERT(mutex_owned(ST_MUTEX) == 0);
3610 	return (0);
3611 }
3612 
3613 
3614 
3615 /*
3616  * this routine spaces forward over filemarks
3617  */
3618 static int
3619 st_space_fmks(dev_t dev, int count)
3620 {
3621 	int rval = 0;
3622 
3623 	GET_SOFT_STATE(dev);
3624 
3625 	ST_FUNC(ST_DEVINFO, st_space_fmks);
3626 
3627 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3628 	    "st_space_fmks(dev = 0x%lx, count = %d)\n", dev, count);
3629 
3630 	ASSERT(mutex_owned(ST_MUTEX));
3631 
3632 	/*
3633 	 * the risk with doing only one space operation is that we
3634 	 * may accidentily jump in old data
3635 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
3636 	 * because the 8200 does not append a marker; in order not to
3637 	 * sacrifice the fast file skip, we do a slow skip if the low
3638 	 * density device has been opened
3639 	 */
3640 
3641 	if ((un->un_dp->options & ST_KNOWS_EOD) &&
3642 	    !((un->un_dp->type == ST_TYPE_EXB8500 && MT_DENSITY(dev) == 0))) {
3643 		if (st_cmd(dev, SCMD_SPACE, Fmk(count), SYNC_CMD)) {
3644 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3645 			    "space_fmks : EIO can't do space cmd #1\n");
3646 			rval = EIO;
3647 		}
3648 	} else {
3649 		while (count > 0) {
3650 			if (st_cmd(dev, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
3651 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3652 				    "space_fmks : EIO can't do space cmd #2\n");
3653 				rval = EIO;
3654 				break;
3655 			}
3656 			count -= 1;
3657 			/*
3658 			 * read a block to see if we have reached
3659 			 * end of medium (double filemark for reel or
3660 			 * medium error for others)
3661 			 */
3662 			if (count > 0) {
3663 				if (st_cmd(dev, SCMD_SPACE, Blk(1),
3664 				    SYNC_CMD)) {
3665 					ST_DEBUG2(ST_DEVINFO, st_label,
3666 					    SCSI_DEBUG,
3667 					    "space_fmks : EIO can't do "
3668 					    "space cmd #3\n");
3669 					rval = EIO;
3670 					break;
3671 				}
3672 				if ((un->un_pos.eof >= ST_EOF_PENDING) &&
3673 				    (un->un_dp->options & ST_REEL)) {
3674 					un->un_status = SUN_KEY_EOT;
3675 					ST_DEBUG2(ST_DEVINFO, st_label,
3676 					    SCSI_DEBUG,
3677 					    "space_fmks : EIO ST_REEL\n");
3678 					rval = EIO;
3679 					break;
3680 				} else if (IN_EOF(un->un_pos)) {
3681 					un->un_pos.eof = ST_NO_EOF;
3682 					un->un_pos.fileno++;
3683 					un->un_pos.blkno = 0;
3684 					count--;
3685 				} else if (un->un_pos.eof > ST_EOF) {
3686 					ST_DEBUG2(ST_DEVINFO, st_label,
3687 					    SCSI_DEBUG,
3688 					    "space_fmks, EIO > ST_EOF\n");
3689 					rval = EIO;
3690 					break;
3691 				}
3692 
3693 			}
3694 		}
3695 		un->un_err_resid = count;
3696 		COPY_POS(&un->un_pos, &un->un_err_pos);
3697 	}
3698 	ASSERT(mutex_owned(ST_MUTEX));
3699 	return (rval);
3700 }
3701 
3702 /*
3703  * this routine spaces to EOD
3704  *
3705  * it keeps track of the current filenumber and returns the filenumber after
3706  * the last successful space operation, we keep the number high because as
3707  * tapes are getting larger, the possibility of more and more files exist,
3708  * 0x100000 (1 Meg of files) probably will never have to be changed any time
3709  * soon
3710  */
3711 #define	MAX_SKIP	0x100000 /* somewhat arbitrary */
3712 
3713 static int
3714 st_find_eod(dev_t dev)
3715 {
3716 	tapepos_t savepos;
3717 	int sp_type;
3718 	struct scsi_tape *un;
3719 	int instance;
3720 	int result;
3721 
3722 	instance = MTUNIT(dev);
3723 	un = ddi_get_soft_state(st_state, instance);
3724 	if (un == NULL) {
3725 		return (-1);
3726 	}
3727 
3728 	ST_FUNC(ST_DEVINFO, st_find_eod);
3729 
3730 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3731 	    "st_find_eod(dev = 0x%lx): fileno = %d\n", dev, un->un_pos.fileno);
3732 
3733 	ASSERT(mutex_owned(ST_MUTEX));
3734 
3735 	COPY_POS(&savepos, &un->un_pos);
3736 
3737 	/*
3738 	 * see if the drive is smart enough to do the skips in
3739 	 * one operation; 1/2" use two filemarks
3740 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
3741 	 * because the 8200 does not append a marker; in order not to
3742 	 * sacrifice the fast file skip, we do a slow skip if the low
3743 	 * density device has been opened
3744 	 */
3745 	if ((un->un_dp->options & ST_KNOWS_EOD) != 0) {
3746 		if ((un->un_dp->type == ST_TYPE_EXB8500) &&
3747 		    (MT_DENSITY(dev) == 0)) {
3748 			sp_type = Fmk(1);
3749 		} else if (un->un_pos.pmode == logical) {
3750 			sp_type = SPACE(SP_EOD, 0);
3751 		} else {
3752 			sp_type = Fmk(MAX_SKIP);
3753 		}
3754 	} else {
3755 		sp_type = Fmk(1);
3756 	}
3757 
3758 	for (;;) {
3759 		result = st_cmd(dev, SCMD_SPACE, sp_type, SYNC_CMD);
3760 
3761 		if (result == 0) {
3762 			COPY_POS(&savepos, &un->un_pos);
3763 		}
3764 
3765 		if (sp_type == SPACE(SP_EOD, 0)) {
3766 			if (result != 0) {
3767 				sp_type = Fmk(MAX_SKIP);
3768 				continue;
3769 			}
3770 
3771 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3772 			    "st_find_eod: 0x%"PRIx64"\n",
3773 			    savepos.lgclblkno);
3774 			/*
3775 			 * What we return will become the current file position.
3776 			 * After completing the space command with the position
3777 			 * mode that is not invalid a read position command will
3778 			 * be automaticly issued. If the drive support the long
3779 			 * read position format a valid file position can be
3780 			 * returned.
3781 			 */
3782 			return (un->un_pos.fileno);
3783 		}
3784 
3785 		if (result != 0) {
3786 			break;
3787 		}
3788 
3789 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3790 		    "count=%x, eof=%x, status=%x\n",
3791 		    SPACE_CNT(sp_type),  un->un_pos.eof, un->un_status);
3792 
3793 		/*
3794 		 * If we're not EOM smart,  space a record
3795 		 * to see whether we're now in the slot between
3796 		 * the two sequential filemarks that logical
3797 		 * EOM consists of (REEL) or hit nowhere land
3798 		 * (8mm).
3799 		 */
3800 		if (sp_type == Fmk(1)) {
3801 			/*
3802 			 * no fast skipping, check a record
3803 			 */
3804 			if (st_cmd(dev, SCMD_SPACE, Blk((1)), SYNC_CMD)) {
3805 				break;
3806 			}
3807 			if ((un->un_pos.eof >= ST_EOF_PENDING) &&
3808 			    (un->un_dp->options & ST_REEL)) {
3809 				un->un_status = KEY_BLANK_CHECK;
3810 				un->un_pos.fileno++;
3811 				un->un_pos.blkno = 0;
3812 				break;
3813 			}
3814 			if (IN_EOF(un->un_pos)) {
3815 				un->un_pos.eof = ST_NO_EOF;
3816 				un->un_pos.fileno++;
3817 				un->un_pos.blkno = 0;
3818 			}
3819 			if (un->un_pos.eof > ST_EOF) {
3820 				break;
3821 			}
3822 		} else {
3823 			if (un->un_pos.eof > ST_EOF) {
3824 				break;
3825 			}
3826 		}
3827 	}
3828 
3829 	if (un->un_dp->options & ST_KNOWS_EOD) {
3830 		COPY_POS(&savepos, &un->un_pos);
3831 	}
3832 
3833 	ASSERT(mutex_owned(ST_MUTEX));
3834 
3835 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3836 	    "st_find_eod: %x\n", savepos.fileno);
3837 	return (savepos.fileno);
3838 }
3839 
3840 
3841 /*
3842  * this routine is frequently used in ioctls below;
3843  * it determines whether we know the density and if not will
3844  * determine it
3845  * if we have written the tape before, one or more filemarks are written
3846  *
3847  * depending on the stepflag, the head is repositioned to where it was before
3848  * the filemarks were written in order not to confuse step counts
3849  */
3850 #define	STEPBACK    0
3851 #define	NO_STEPBACK 1
3852 
3853 static int
3854 st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag)
3855 {
3856 
3857 	GET_SOFT_STATE(dev);
3858 
3859 	ST_FUNC(ST_DEVINFO, st_check_density_or_wfm);
3860 
3861 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3862 	    "st_check_density_or_wfm(dev= 0x%lx, wfm= %d, mode= %d, stpflg= %d)"
3863 	    "\n", dev, wfm, mode, stepflag);
3864 
3865 	ASSERT(mutex_owned(ST_MUTEX));
3866 
3867 	/*
3868 	 * If we don't yet know the density of the tape we have inserted,
3869 	 * we have to either unconditionally set it (if we're 'writing'),
3870 	 * or we have to determine it. As side effects, check for any
3871 	 * write-protect errors, and for the need to put out any file-marks
3872 	 * before positioning a tape.
3873 	 *
3874 	 * If we are going to be spacing forward, and we haven't determined
3875 	 * the tape density yet, we have to do so now...
3876 	 */
3877 	if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
3878 		if (st_determine_density(dev, mode)) {
3879 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3880 			    "check_density_or_wfm : EIO can't determine "
3881 			    "density\n");
3882 			un->un_errno = EIO;
3883 			return (EIO);
3884 		}
3885 		/*
3886 		 * Presumably we are at BOT. If we attempt to write, it will
3887 		 * either work okay, or bomb. We don't do a st_test_append
3888 		 * unless we're past BOT.
3889 		 */
3890 		un->un_laststate = un->un_state;
3891 		un->un_state = ST_STATE_OPEN;
3892 
3893 	} else if (un->un_pos.pmode != invalid && un->un_fmneeded > 0 &&
3894 	    ((un->un_lastop == ST_OP_WEOF && wfm) ||
3895 	    (un->un_lastop == ST_OP_WRITE && wfm))) {
3896 
3897 		tapepos_t spos;
3898 
3899 		COPY_POS(&spos, &un->un_pos);
3900 
3901 		/*
3902 		 * We need to write one or two filemarks.
3903 		 * In the case of the HP, we need to
3904 		 * position the head between the two
3905 		 * marks.
3906 		 */
3907 		if ((un->un_fmneeded > 0) || (un->un_lastop == ST_OP_WEOF)) {
3908 			wfm = un->un_fmneeded;
3909 			un->un_fmneeded = 0;
3910 		}
3911 
3912 		if (st_write_fm(dev, wfm)) {
3913 			un->un_pos.pmode = invalid;
3914 			un->un_density_known = 0;
3915 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3916 			    "check_density_or_wfm : EIO can't write fm\n");
3917 			un->un_errno = EIO;
3918 			return (EIO);
3919 		}
3920 
3921 		if (stepflag == STEPBACK) {
3922 			if (st_cmd(dev, SCMD_SPACE, Fmk((-wfm)), SYNC_CMD)) {
3923 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3924 				    "check_density_or_wfm : EIO can't space "
3925 				    "(-wfm)\n");
3926 				un->un_errno = EIO;
3927 				return (EIO);
3928 			}
3929 			COPY_POS(&un->un_pos, &spos);
3930 		}
3931 	}
3932 
3933 	/*
3934 	 * Whatever we do at this point clears the state of the eof flag.
3935 	 */
3936 
3937 	un->un_pos.eof = ST_NO_EOF;
3938 
3939 	/*
3940 	 * If writing, let's check that we're positioned correctly
3941 	 * at the end of tape before issuing the next write.
3942 	 */
3943 	if (un->un_read_only == RDWR) {
3944 		un->un_test_append = 1;
3945 	}
3946 
3947 	ASSERT(mutex_owned(ST_MUTEX));
3948 	return (0);
3949 }
3950 
3951 
3952 /*
3953  * Wait for all outstaning I/O's to complete
3954  *
3955  * we wait on both ncmds and the wait queue for times when we are flushing
3956  * after persistent errors are flagged, which is when ncmds can be 0, and the
3957  * queue can still have I/O's.  This way we preserve order of biodone's.
3958  */
3959 static void
3960 st_wait_for_io(struct scsi_tape *un)
3961 {
3962 	ST_FUNC(ST_DEVINFO, st_wait_for_io);
3963 	ASSERT(mutex_owned(ST_MUTEX));
3964 	while (un->un_ncmds && un->un_quef) { /* XXX fix for async write@EOM */
3965 		cv_wait(&un->un_queue_cv, ST_MUTEX);
3966 	}
3967 }
3968 
3969 /*
3970  * This routine implements the ioctl calls.  It is called
3971  * from the device switch at normal priority.
3972  */
3973 /*ARGSUSED*/
3974 static int
3975 st_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p,
3976     int *rval_p)
3977 {
3978 	int tmp, rval = 0;
3979 
3980 	GET_SOFT_STATE(dev);
3981 
3982 	ST_ENTR(ST_DEVINFO, st_ioctl);
3983 
3984 	mutex_enter(ST_MUTEX);
3985 
3986 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3987 	    "st_ioctl(): fileno=%x, blkno=%x, eof=%x, state = %d, "
3988 	    "pe_flag = %d\n",
3989 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof, un->un_state,
3990 	    IS_PE_FLAG_SET(un));
3991 
3992 	/*
3993 	 * We don't want to block on these, so let them through
3994 	 * and we don't care about setting driver states here.
3995 	 */
3996 	if ((cmd == MTIOCGETDRIVETYPE) ||
3997 	    (cmd == MTIOCGUARANTEEDORDER) ||
3998 	    (cmd == MTIOCPERSISTENTSTATUS)) {
3999 		goto check_commands;
4000 	}
4001 
4002 	/*
4003 	 * We clear error entry stack except command
4004 	 * MTIOCGETERROR and MTIOCGET
4005 	 */
4006 	if ((cmd != MTIOCGETERROR) &&
4007 	    (cmd != MTIOCGET)) {
4008 		st_empty_error_stack(un);
4009 	}
4010 
4011 	/*
4012 	 * wait for all outstanding commands to complete, or be dequeued.
4013 	 * And because ioctl's are synchronous commands, any return value
4014 	 * after this,  will be in order
4015 	 */
4016 	st_wait_for_io(un);
4017 
4018 	/*
4019 	 * allow only a through clear errors and persistent status, and
4020 	 * status
4021 	 */
4022 	if (IS_PE_FLAG_SET(un)) {
4023 		if ((cmd == MTIOCLRERR) ||
4024 		    (cmd == MTIOCPERSISTENT) ||
4025 		    (cmd == MTIOCGET)) {
4026 			goto check_commands;
4027 		} else {
4028 			rval = un->un_errno;
4029 			goto exit;
4030 		}
4031 	}
4032 
4033 	un->un_throttle = 1;	/* > 1 will never happen here */
4034 	un->un_errno = 0;	/* start clean from here */
4035 
4036 	/*
4037 	 * first and foremost, handle any ST_EOT_PENDING cases.
4038 	 * That is, if a logical eot is pending notice, notice it.
4039 	 */
4040 	if (un->un_pos.eof == ST_EOT_PENDING) {
4041 		int resid = un->un_err_resid;
4042 		uchar_t status = un->un_status;
4043 		uchar_t lastop = un->un_lastop;
4044 
4045 		if (st_cmd(dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)) {
4046 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4047 			    "stioctl : EIO can't space fmk(-1)\n");
4048 			rval = EIO;
4049 			goto exit;
4050 		}
4051 		un->un_lastop = lastop; /* restore last operation */
4052 		if (status == SUN_KEY_EOF) {
4053 			un->un_status = SUN_KEY_EOT;
4054 		} else {
4055 			un->un_status = status;
4056 		}
4057 		un->un_err_resid  = resid;
4058 		/* fix up block number */
4059 		un->un_err_pos.blkno = un->un_pos.blkno = 0;
4060 		/* now we're at logical eot */
4061 		un->un_pos.eof = ST_EOT;
4062 	}
4063 
4064 	/*
4065 	 * now, handle the rest of the situations
4066 	 */
4067 check_commands:
4068 	switch (cmd) {
4069 	case MTIOCGET:
4070 	{
4071 #ifdef _MULTI_DATAMODEL
4072 		/*
4073 		 * For use when a 32 bit app makes a call into a
4074 		 * 64 bit ioctl
4075 		 */
4076 		struct mtget32		mtg_local32;
4077 		struct mtget32 		*mtget_32 = &mtg_local32;
4078 #endif /* _MULTI_DATAMODEL */
4079 
4080 			/* Get tape status */
4081 		struct mtget mtg_local;
4082 		struct mtget *mtget = &mtg_local;
4083 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4084 		    "st_ioctl: MTIOCGET\n");
4085 
4086 		bzero((caddr_t)mtget, sizeof (struct mtget));
4087 		mtget->mt_erreg = un->un_status;
4088 		mtget->mt_resid = un->un_err_resid;
4089 		mtget->mt_dsreg = un->un_retry_ct;
4090 		if (un->un_err_pos.pmode == legacy) {
4091 			mtget->mt_fileno = un->un_err_pos.fileno;
4092 		} else {
4093 			mtget->mt_fileno = -1;
4094 		}
4095 		mtget->mt_blkno = un->un_err_pos.blkno;
4096 		mtget->mt_type = un->un_dp->type;
4097 		mtget->mt_flags = MTF_SCSI | MTF_ASF;
4098 		if (un->un_read_pos_type != NO_POS) {
4099 			mtget->mt_flags |= MTF_LOGICAL_BLOCK;
4100 		}
4101 		if (un->un_dp->options & ST_REEL) {
4102 			mtget->mt_flags |= MTF_REEL;
4103 			mtget->mt_bf = 20;
4104 		} else {		/* 1/4" cartridges */
4105 			switch (mtget->mt_type) {
4106 			/* Emulex cartridge tape */
4107 			case MT_ISMT02:
4108 				mtget->mt_bf = 40;
4109 				break;
4110 			default:
4111 				mtget->mt_bf = 126;
4112 				break;
4113 			}
4114 		}
4115 
4116 		/*
4117 		 * If large transfers are allowed and drive options
4118 		 * has no record size limit set. Calculate blocking
4119 		 * factor from the lesser of maxbsize and maxdma.
4120 		 */
4121 		if ((un->un_allow_large_xfer) &&
4122 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT)) {
4123 			mtget->mt_bf = min(un->un_maxbsize,
4124 			    un->un_maxdma) / SECSIZE;
4125 		}
4126 
4127 			if (un->un_read_only == WORM ||
4128 			    un->un_read_only == RDWORM) {
4129 				mtget->mt_flags |= MTF_WORM_MEDIA;
4130 			}
4131 
4132 			rval = st_check_clean_bit(dev);
4133 			if (rval == -1) {
4134 				rval = EIO;
4135 				goto exit;
4136 			} else {
4137 				mtget->mt_flags |= (ushort_t)rval;
4138 				rval = 0;
4139 			}
4140 
4141 		un->un_status = 0;		/* Reset status */
4142 		un->un_err_resid = 0;
4143 		tmp = sizeof (struct mtget);
4144 
4145 #ifdef _MULTI_DATAMODEL
4146 
4147 		switch (ddi_model_convert_from(flag & FMODELS)) {
4148 		case DDI_MODEL_ILP32:
4149 			/*
4150 			 * Convert 64 bit back to 32 bit before doing
4151 			 * copyout. This is what the ILP32 app expects.
4152 			 */
4153 			mtget_32->mt_erreg = 	mtget->mt_erreg;
4154 			mtget_32->mt_resid = 	mtget->mt_resid;
4155 			mtget_32->mt_dsreg = 	mtget->mt_dsreg;
4156 			mtget_32->mt_fileno = 	(daddr32_t)mtget->mt_fileno;
4157 			mtget_32->mt_blkno = 	(daddr32_t)mtget->mt_blkno;
4158 			mtget_32->mt_type =  	mtget->mt_type;
4159 			mtget_32->mt_flags = 	mtget->mt_flags;
4160 			mtget_32->mt_bf = 	mtget->mt_bf;
4161 
4162 			if (ddi_copyout(mtget_32, (void *)arg,
4163 			    sizeof (struct mtget32), flag)) {
4164 				rval = EFAULT;
4165 			}
4166 			break;
4167 
4168 		case DDI_MODEL_NONE:
4169 			if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
4170 				rval = EFAULT;
4171 			}
4172 			break;
4173 		}
4174 #else /* ! _MULTI_DATAMODE */
4175 		if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
4176 			rval = EFAULT;
4177 		}
4178 #endif /* _MULTI_DATAMODE */
4179 
4180 		break;
4181 	}
4182 	case MTIOCGETERROR:
4183 			/*
4184 			 * get error entry from error stack
4185 			 */
4186 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4187 			    "st_ioctl: MTIOCGETERROR\n");
4188 
4189 			rval = st_get_error_entry(un, arg, flag);
4190 
4191 			break;
4192 
4193 	case MTIOCSTATE:
4194 		{
4195 			/*
4196 			 * return when media presence matches state
4197 			 */
4198 			enum mtio_state state;
4199 
4200 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4201 			    "st_ioctl: MTIOCSTATE\n");
4202 
4203 			if (ddi_copyin((void *)arg, &state, sizeof (int), flag))
4204 				rval = EFAULT;
4205 
4206 			mutex_exit(ST_MUTEX);
4207 
4208 			rval = st_check_media(dev, state);
4209 
4210 			mutex_enter(ST_MUTEX);
4211 
4212 			if (rval != 0) {
4213 				break;
4214 			}
4215 
4216 			if (ddi_copyout(&un->un_mediastate, (void *)arg,
4217 			    sizeof (int), flag))
4218 				rval = EFAULT;
4219 			break;
4220 
4221 		}
4222 
4223 	case MTIOCGETDRIVETYPE:
4224 		{
4225 #ifdef _MULTI_DATAMODEL
4226 		/*
4227 		 * For use when a 32 bit app makes a call into a
4228 		 * 64 bit ioctl
4229 		 */
4230 		struct mtdrivetype_request32	mtdtrq32;
4231 #endif /* _MULTI_DATAMODEL */
4232 
4233 			/*
4234 			 * return mtdrivetype
4235 			 */
4236 			struct mtdrivetype_request mtdtrq;
4237 			struct mtdrivetype mtdrtyp;
4238 			struct mtdrivetype *mtdt = &mtdrtyp;
4239 			struct st_drivetype *stdt = un->un_dp;
4240 
4241 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4242 			    "st_ioctl: MTIOCGETDRIVETYPE\n");
4243 
4244 #ifdef _MULTI_DATAMODEL
4245 		switch (ddi_model_convert_from(flag & FMODELS)) {
4246 		case DDI_MODEL_ILP32:
4247 		{
4248 			if (ddi_copyin((void *)arg, &mtdtrq32,
4249 			    sizeof (struct mtdrivetype_request32), flag)) {
4250 				rval = EFAULT;
4251 				break;
4252 			}
4253 			mtdtrq.size = mtdtrq32.size;
4254 			mtdtrq.mtdtp =
4255 			    (struct  mtdrivetype *)(uintptr_t)mtdtrq32.mtdtp;
4256 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4257 			    "st_ioctl: size 0x%x\n", mtdtrq.size);
4258 			break;
4259 		}
4260 		case DDI_MODEL_NONE:
4261 			if (ddi_copyin((void *)arg, &mtdtrq,
4262 			    sizeof (struct mtdrivetype_request), flag)) {
4263 				rval = EFAULT;
4264 				break;
4265 			}
4266 			break;
4267 		}
4268 
4269 #else /* ! _MULTI_DATAMODEL */
4270 		if (ddi_copyin((void *)arg, &mtdtrq,
4271 		    sizeof (struct mtdrivetype_request), flag)) {
4272 			rval = EFAULT;
4273 			break;
4274 		}
4275 #endif /* _MULTI_DATAMODEL */
4276 
4277 			/*
4278 			 * if requested size is < 0 then return
4279 			 * error.
4280 			 */
4281 			if (mtdtrq.size < 0) {
4282 				rval = EINVAL;
4283 				break;
4284 			}
4285 			bzero(mtdt, sizeof (struct mtdrivetype));
4286 			(void) strncpy(mtdt->name, stdt->name, ST_NAMESIZE);
4287 			(void) strncpy(mtdt->vid, stdt->vid, VIDPIDLEN - 1);
4288 			mtdt->type = stdt->type;
4289 			mtdt->bsize = stdt->bsize;
4290 			mtdt->options = stdt->options;
4291 			mtdt->max_rretries = stdt->max_rretries;
4292 			mtdt->max_wretries = stdt->max_wretries;
4293 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
4294 				mtdt->densities[tmp] = stdt->densities[tmp];
4295 			}
4296 			mtdt->default_density = stdt->default_density;
4297 			/*
4298 			 * Speed hasn't been used since the hayday of reel tape.
4299 			 * For all drives not setting the option ST_KNOWS_MEDIA
4300 			 * the speed member renamed to mediatype are zeros.
4301 			 * Those drives that have ST_KNOWS_MEDIA set use the
4302 			 * new mediatype member which is used to figure the
4303 			 * type of media loaded.
4304 			 *
4305 			 * So as to not break applications speed in the
4306 			 * mtdrivetype structure is not renamed.
4307 			 */
4308 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
4309 				mtdt->speeds[tmp] = stdt->mediatype[tmp];
4310 			}
4311 			mtdt->non_motion_timeout = stdt->non_motion_timeout;
4312 			mtdt->io_timeout = stdt->io_timeout;
4313 			mtdt->rewind_timeout = stdt->rewind_timeout;
4314 			mtdt->space_timeout = stdt->space_timeout;
4315 			mtdt->load_timeout = stdt->load_timeout;
4316 			mtdt->unload_timeout = stdt->unload_timeout;
4317 			mtdt->erase_timeout = stdt->erase_timeout;
4318 
4319 			/*
4320 			 * Limit the maximum length of the result to
4321 			 * sizeof (struct mtdrivetype).
4322 			 */
4323 			tmp = sizeof (struct mtdrivetype);
4324 			if (mtdtrq.size < tmp)
4325 				tmp = mtdtrq.size;
4326 			if (ddi_copyout(mtdt, mtdtrq.mtdtp, tmp, flag)) {
4327 				rval = EFAULT;
4328 			}
4329 			break;
4330 		}
4331 	case MTIOCPERSISTENT:
4332 		{
4333 			int persistence = 0;
4334 
4335 			if (ddi_copyin((void *)arg, &persistence,
4336 			    sizeof (int), flag)) {
4337 				rval = EFAULT;
4338 				break;
4339 			}
4340 
4341 			/* non zero sets it, only 0 turns it off */
4342 			un->un_persistence = (uchar_t)persistence ? 1 : 0;
4343 
4344 			if (un->un_persistence) {
4345 				TURN_PE_ON(un);
4346 			} else {
4347 				TURN_PE_OFF(un);
4348 			}
4349 
4350 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4351 			    "st_ioctl: MTIOCPERSISTENT : persistence = %d\n",
4352 			    un->un_persistence);
4353 
4354 			break;
4355 		}
4356 	case MTIOCPERSISTENTSTATUS:
4357 		{
4358 			int persistence = (int)un->un_persistence;
4359 
4360 			if (ddi_copyout(&persistence, (void *)arg,
4361 			    sizeof (int), flag)) {
4362 				rval = EFAULT;
4363 			}
4364 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4365 			    "st_ioctl: MTIOCPERSISTENTSTATUS:persistece = %d\n",
4366 			    un->un_persistence);
4367 
4368 			break;
4369 		}
4370 
4371 
4372 	case MTIOCLRERR:
4373 		{
4374 			/* clear persistent errors */
4375 
4376 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4377 			    "st_ioctl: MTIOCLRERR\n");
4378 
4379 			CLEAR_PE(un);
4380 
4381 			break;
4382 		}
4383 
4384 	case MTIOCGUARANTEEDORDER:
4385 		{
4386 			/*
4387 			 * this is just a holder to make a valid ioctl and
4388 			 * it won't be in any earlier release
4389 			 */
4390 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4391 			    "st_ioctl: MTIOCGUARANTEEDORDER\n");
4392 
4393 			break;
4394 		}
4395 
4396 	case MTIOCRESERVE:
4397 		{
4398 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4399 			    "st_ioctl: MTIOCRESERVE\n");
4400 
4401 			/*
4402 			 * Check if Reserve/Release is supported.
4403 			 */
4404 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
4405 				rval = ENOTTY;
4406 				break;
4407 			}
4408 
4409 			rval = st_reserve_release(un, ST_RESERVE);
4410 
4411 			if (rval == 0) {
4412 				un->un_rsvd_status |= ST_PRESERVE_RESERVE;
4413 			}
4414 			break;
4415 		}
4416 
4417 	case MTIOCRELEASE:
4418 		{
4419 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4420 			    "st_ioctl: MTIOCRELEASE\n");
4421 
4422 			/*
4423 			 * Check if Reserve/Release is supported.
4424 			 */
4425 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
4426 				rval = ENOTTY;
4427 				break;
4428 			}
4429 
4430 			/*
4431 			 * Used to just clear ST_PRESERVE_RESERVE which
4432 			 * made the reservation release at next close.
4433 			 * As the user may have opened and then done a
4434 			 * persistant reservation we now need to drop
4435 			 * the reservation without closing if the user
4436 			 * attempts to do this.
4437 			 */
4438 			rval = st_reserve_release(un, ST_RELEASE);
4439 
4440 			un->un_rsvd_status &= ~ST_PRESERVE_RESERVE;
4441 
4442 			break;
4443 		}
4444 
4445 	case MTIOCFORCERESERVE:
4446 		{
4447 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4448 			    "st_ioctl: MTIOCFORCERESERVE\n");
4449 
4450 			/*
4451 			 * Check if Reserve/Release is supported.
4452 			 */
4453 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
4454 				rval = ENOTTY;
4455 				break;
4456 			}
4457 			/*
4458 			 * allow only super user to run this.
4459 			 */
4460 			if (drv_priv(cred_p) != 0) {
4461 				rval = EPERM;
4462 				break;
4463 			}
4464 			/*
4465 			 * Throw away reserve,
4466 			 * not using test-unit-ready
4467 			 * since reserve can succeed without tape being
4468 			 * present in the drive.
4469 			 */
4470 			(void) st_reserve_release(un, ST_RESERVE);
4471 
4472 			rval = st_take_ownership(dev);
4473 
4474 			break;
4475 		}
4476 
4477 	case USCSICMD:
4478 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4479 		    "st_ioctl: USCSICMD\n");
4480 	{
4481 		cred_t	*cr;
4482 		cr = ddi_get_cred();
4483 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
4484 			rval = EPERM;
4485 		} else {
4486 			rval = st_ioctl_cmd(dev, (struct uscsi_cmd *)arg,
4487 			    flag);
4488 		}
4489 	}
4490 		break;
4491 
4492 	case MTIOCTOP:
4493 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4494 		    "st_ioctl: MTIOCTOP\n");
4495 		rval = st_mtioctop(un, arg, flag);
4496 		break;
4497 
4498 	case MTIOCLTOP:
4499 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4500 		    "st_ioctl: MTIOLCTOP\n");
4501 		rval = st_mtiocltop(un, arg, flag);
4502 		break;
4503 
4504 	case MTIOCREADIGNOREILI:
4505 		{
4506 			int set_ili;
4507 
4508 			if (ddi_copyin((void *)arg, &set_ili,
4509 			    sizeof (set_ili), flag)) {
4510 				rval = EFAULT;
4511 				break;
4512 			}
4513 
4514 			if (un->un_bsize) {
4515 				rval = ENOTTY;
4516 				break;
4517 			}
4518 
4519 			switch (set_ili) {
4520 			case 0:
4521 				un->un_dp->options &= ~ST_READ_IGNORE_ILI;
4522 				break;
4523 
4524 			case 1:
4525 				un->un_dp->options |= ST_READ_IGNORE_ILI;
4526 				break;
4527 
4528 			default:
4529 				rval = EINVAL;
4530 				break;
4531 			}
4532 			break;
4533 		}
4534 
4535 	case MTIOCREADIGNOREEOFS:
4536 		{
4537 			int ignore_eof;
4538 
4539 			if (ddi_copyin((void *)arg, &ignore_eof,
4540 			    sizeof (ignore_eof), flag)) {
4541 				rval = EFAULT;
4542 				break;
4543 			}
4544 
4545 			if (!(un->un_dp->options & ST_REEL)) {
4546 				rval = ENOTTY;
4547 				break;
4548 			}
4549 
4550 			switch (ignore_eof) {
4551 			case 0:
4552 				un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
4553 				break;
4554 
4555 			case 1:
4556 				un->un_dp->options |= ST_READ_IGNORE_EOFS;
4557 				break;
4558 
4559 			default:
4560 				rval = EINVAL;
4561 				break;
4562 			}
4563 			break;
4564 		}
4565 
4566 	case MTIOCSHORTFMK:
4567 	{
4568 		int short_fmk;
4569 
4570 		if (ddi_copyin((void *)arg, &short_fmk,
4571 		    sizeof (short_fmk), flag)) {
4572 			rval = EFAULT;
4573 			break;
4574 		}
4575 
4576 		switch (un->un_dp->type) {
4577 		case ST_TYPE_EXB8500:
4578 		case ST_TYPE_EXABYTE:
4579 			if (!short_fmk) {
4580 				un->un_dp->options &= ~ST_SHORT_FILEMARKS;
4581 			} else if (short_fmk == 1) {
4582 				un->un_dp->options |= ST_SHORT_FILEMARKS;
4583 			} else {
4584 				rval = EINVAL;
4585 			}
4586 			break;
4587 
4588 		default:
4589 			rval = ENOTTY;
4590 			break;
4591 		}
4592 		break;
4593 	}
4594 
4595 	case MTIOCGETPOS:
4596 		rval = st_update_block_pos(un);
4597 		if (rval == 0) {
4598 			if (ddi_copyout((void *)&un->un_pos, (void *)arg,
4599 			    sizeof (tapepos_t), flag)) {
4600 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
4601 				    "MTIOCGETPOS copy out failed\n");
4602 				rval = EFAULT;
4603 			}
4604 		}
4605 		break;
4606 
4607 	case MTIOCRESTPOS:
4608 	{
4609 		tapepos_t dest;
4610 
4611 		if (ddi_copyin((void *)arg, &dest, sizeof (tapepos_t),
4612 		    flag) != 0) {
4613 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
4614 			    "MTIOCRESTPOS copy in failed\n");
4615 			rval = EFAULT;
4616 			break;
4617 		}
4618 		rval = st_validate_tapemarks(un, &dest);
4619 		if (rval != 0) {
4620 			rval = EIO;
4621 		}
4622 		break;
4623 	}
4624 	default:
4625 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4626 		    "st_ioctl: unknown ioctl\n");
4627 		rval = ENOTTY;
4628 	}
4629 
4630 exit:
4631 	if (!IS_PE_FLAG_SET(un)) {
4632 		un->un_errno = rval;
4633 	}
4634 
4635 	mutex_exit(ST_MUTEX);
4636 
4637 	return (rval);
4638 }
4639 
4640 
4641 /*
4642  * do some MTIOCTOP tape operations
4643  */
4644 static int
4645 st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag)
4646 {
4647 #ifdef _MULTI_DATAMODEL
4648 	/*
4649 	 * For use when a 32 bit app makes a call into a
4650 	 * 64 bit ioctl
4651 	 */
4652 	struct mtop32	mtop_32_for_64;
4653 #endif /* _MULTI_DATAMODEL */
4654 	struct mtop passed;
4655 	struct mtlop local;
4656 	int rval = 0;
4657 
4658 	ST_FUNC(ST_DEVINFO, st_mtioctop);
4659 
4660 	ASSERT(mutex_owned(ST_MUTEX));
4661 
4662 #ifdef _MULTI_DATAMODEL
4663 	switch (ddi_model_convert_from(flag & FMODELS)) {
4664 	case DDI_MODEL_ILP32:
4665 		if (ddi_copyin((void *)arg, &mtop_32_for_64,
4666 		    sizeof (struct mtop32), flag)) {
4667 			return (EFAULT);
4668 		}
4669 		local.mt_op = mtop_32_for_64.mt_op;
4670 		local.mt_count =  (int64_t)mtop_32_for_64.mt_count;
4671 		break;
4672 
4673 	case DDI_MODEL_NONE:
4674 		if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
4675 			return (EFAULT);
4676 		}
4677 		local.mt_op = passed.mt_op;
4678 		/* prevent sign extention */
4679 		local.mt_count = (UINT32_MAX & passed.mt_count);
4680 		break;
4681 	}
4682 
4683 #else /* ! _MULTI_DATAMODEL */
4684 	if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
4685 		return (EFAULT);
4686 	}
4687 	local.mt_op = passed.mt_op;
4688 	/* prevent sign extention */
4689 	local.mt_count = (UINT32_MAX & passed.mt_count);
4690 #endif /* _MULTI_DATAMODEL */
4691 
4692 	rval = st_do_mtioctop(un, &local);
4693 
4694 #ifdef _MULTI_DATAMODEL
4695 	switch (ddi_model_convert_from(flag & FMODELS)) {
4696 	case DDI_MODEL_ILP32:
4697 		if (((uint64_t)local.mt_count) > UINT32_MAX) {
4698 			rval = ERANGE;
4699 			break;
4700 		}
4701 		/*
4702 		 * Convert 64 bit back to 32 bit before doing
4703 		 * copyout. This is what the ILP32 app expects.
4704 		 */
4705 		mtop_32_for_64.mt_op = local.mt_op;
4706 		mtop_32_for_64.mt_count = local.mt_count;
4707 
4708 		if (ddi_copyout(&mtop_32_for_64, (void *)arg,
4709 		    sizeof (struct mtop32), flag)) {
4710 			rval = EFAULT;
4711 		}
4712 		break;
4713 
4714 	case DDI_MODEL_NONE:
4715 		passed.mt_count = local.mt_count;
4716 		passed.mt_op = local.mt_op;
4717 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
4718 			rval = EFAULT;
4719 		}
4720 		break;
4721 	}
4722 #else /* ! _MULTI_DATAMODE */
4723 	if (((uint64_t)local.mt_count) > UINT32_MAX) {
4724 		rval = ERANGE;
4725 	} else {
4726 		passed.mt_op = local.mt_op;
4727 		passed.mt_count = local.mt_count;
4728 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
4729 			rval = EFAULT;
4730 		}
4731 	}
4732 #endif /* _MULTI_DATAMODE */
4733 
4734 
4735 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4736 	    "st_ioctl: fileno=%x, blkno=%x, eof=%x\n", un->un_pos.fileno,
4737 	    un->un_pos.blkno, un->un_pos.eof);
4738 
4739 	if (un->un_pos.pmode == invalid) {
4740 		un->un_density_known = 0;
4741 	}
4742 
4743 	ASSERT(mutex_owned(ST_MUTEX));
4744 	return (rval);
4745 }
4746 
4747 static int
4748 st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag)
4749 {
4750 	struct mtlop local;
4751 	int rval;
4752 
4753 	ST_FUNC(ST_DEVINFO, st_mtiocltop);
4754 	if (ddi_copyin((void *)arg, &local, sizeof (local), flag)) {
4755 		return (EFAULT);
4756 	}
4757 
4758 	rval = st_do_mtioctop(un, &local);
4759 
4760 	if (ddi_copyout(&local, (void *)arg, sizeof (local), flag)) {
4761 		rval = EFAULT;
4762 	}
4763 	return (rval);
4764 }
4765 
4766 
4767 static int
4768 st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop)
4769 {
4770 	dev_t dev = un->un_dev;
4771 	int savefile;
4772 	int rval = 0;
4773 
4774 	ST_FUNC(ST_DEVINFO, st_do_mtioctop);
4775 
4776 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4777 	    "st_do_mtioctop(): mt_op=%x\n", mtop->mt_op);
4778 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4779 	    "fileno=%x, blkno=%x, eof=%x\n",
4780 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
4781 
4782 	un->un_status = 0;
4783 
4784 	/*
4785 	 * if we are going to mess with a tape, we have to make sure we have
4786 	 * one and are not offline (i.e. no tape is initialized).  We let
4787 	 * commands pass here that don't actually touch the tape, except for
4788 	 * loading and initialization (rewinding).
4789 	 */
4790 	if (un->un_state == ST_STATE_OFFLINE) {
4791 		switch (mtop->mt_op) {
4792 		case MTLOAD:
4793 		case MTNOP:
4794 			/*
4795 			 * We don't want strategy calling st_tape_init here,
4796 			 * so, change state
4797 			 */
4798 			un->un_state = ST_STATE_INITIALIZING;
4799 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4800 			    "st_do_mtioctop : OFFLINE state = %d\n",
4801 			    un->un_state);
4802 			break;
4803 		default:
4804 			/*
4805 			 * reinitialize by normal means
4806 			 */
4807 			rval = st_tape_init(dev);
4808 			if (rval) {
4809 				un->un_state = ST_STATE_INITIALIZING;
4810 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4811 				    "st_do_mtioctop : OFFLINE init failure ");
4812 				un->un_state = ST_STATE_OFFLINE;
4813 				un->un_pos.pmode = invalid;
4814 				if (rval != EACCES) {
4815 					rval = EIO;
4816 				}
4817 				return (rval);
4818 			}
4819 			un->un_state = ST_STATE_OPEN_PENDING_IO;
4820 			break;
4821 		}
4822 	}
4823 
4824 	/*
4825 	 * If the file position is invalid, allow only those
4826 	 * commands that properly position the tape and fail
4827 	 * the rest with EIO
4828 	 */
4829 	if (un->un_pos.pmode == invalid) {
4830 		switch (mtop->mt_op) {
4831 		case MTWEOF:
4832 		case MTRETEN:
4833 		case MTERASE:
4834 		case MTEOM:
4835 		case MTFSF:
4836 		case MTFSR:
4837 		case MTBSF:
4838 		case MTNBSF:
4839 		case MTBSR:
4840 		case MTSRSZ:
4841 		case MTGRSZ:
4842 		case MTSEEK:
4843 		case MTBSSF:
4844 		case MTFSSF:
4845 			return (EIO);
4846 			/* NOTREACHED */
4847 		case MTREW:
4848 		case MTLOAD:
4849 		case MTOFFL:
4850 		case MTNOP:
4851 		case MTTELL:
4852 		case MTLOCK:
4853 		case MTUNLOCK:
4854 			break;
4855 
4856 		default:
4857 			return (ENOTTY);
4858 			/* NOTREACHED */
4859 		}
4860 	}
4861 
4862 	switch (mtop->mt_op) {
4863 	case MTERASE:
4864 		/*
4865 		 * MTERASE rewinds the tape, erase it completely, and returns
4866 		 * to the beginning of the tape
4867 		 */
4868 		if (un->un_mspl->wp || un->un_read_only & WORM) {
4869 			un->un_status = KEY_WRITE_PROTECT;
4870 			un->un_err_resid = mtop->mt_count;
4871 			COPY_POS(&un->un_err_pos, &un->un_pos);
4872 			return (EACCES);
4873 		}
4874 		if (un->un_dp->options & ST_REEL) {
4875 			un->un_fmneeded = 2;
4876 		} else {
4877 			un->un_fmneeded = 1;
4878 		}
4879 		if (st_check_density_or_wfm(dev, 1, B_WRITE, NO_STEPBACK) ||
4880 		    st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD) ||
4881 		    st_cmd(dev, SCMD_ERASE, 0, SYNC_CMD)) {
4882 			un->un_pos.pmode = invalid;
4883 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4884 			    "st_do_mtioctop : EIO space or erase or "
4885 			    "check den)\n");
4886 			rval = EIO;
4887 		} else {
4888 			/* QIC and helical scan rewind after erase */
4889 			if (un->un_dp->options & ST_REEL) {
4890 				(void) st_cmd(dev, SCMD_REWIND, 0, ASYNC_CMD);
4891 			}
4892 		}
4893 		break;
4894 
4895 	case MTWEOF:
4896 		/*
4897 		 * write an end-of-file record
4898 		 */
4899 		if (un->un_mspl->wp || un->un_read_only & RDONLY) {
4900 			un->un_status = KEY_WRITE_PROTECT;
4901 			un->un_err_resid = mtop->mt_count;
4902 			COPY_POS(&un->un_err_pos, &un->un_pos);
4903 			return (EACCES);
4904 		}
4905 
4906 		/*
4907 		 * zero count means just flush buffers
4908 		 * negative count is not permitted
4909 		 */
4910 		if (mtop->mt_count < 0) {
4911 			return (EINVAL);
4912 		}
4913 
4914 		/* Not on worm */
4915 		if (un->un_read_only == RDWR) {
4916 			un->un_test_append = 1;
4917 		}
4918 
4919 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4920 			if (st_determine_density(dev, B_WRITE)) {
4921 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4922 				    "st_do_mtioctop : EIO : MTWEOF can't "
4923 				    "determine density");
4924 				return (EIO);
4925 			}
4926 		}
4927 
4928 		rval = st_write_fm(dev, (int)mtop->mt_count);
4929 		if ((rval != 0) && (rval != EACCES)) {
4930 			/*
4931 			 * Failure due to something other than illegal
4932 			 * request results in loss of state (st_intr).
4933 			 */
4934 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4935 			    "st_do_mtioctop : EIO : MTWEOF can't write "
4936 			    "file mark");
4937 			rval = EIO;
4938 		}
4939 		break;
4940 
4941 	case MTRETEN:
4942 		/*
4943 		 * retension the tape
4944 		 */
4945 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK) ||
4946 		    st_cmd(dev, SCMD_LOAD, LD_LOAD | LD_RETEN, SYNC_CMD)) {
4947 			un->un_pos.pmode = invalid;
4948 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4949 			    "st_do_mtioctop : EIO : MTRETEN ");
4950 			rval = EIO;
4951 		}
4952 		break;
4953 
4954 	case MTREW:
4955 		/*
4956 		 * rewind  the tape
4957 		 */
4958 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
4959 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4960 			    "st_do_mtioctop : EIO:MTREW check "
4961 			    "density/wfm failed");
4962 			return (EIO);
4963 		}
4964 		if (st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD)) {
4965 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4966 			    "st_do_mtioctop : EIO : MTREW ");
4967 			rval = EIO;
4968 		}
4969 		break;
4970 
4971 	case MTOFFL:
4972 		/*
4973 		 * rewinds, and, if appropriate, takes the device offline by
4974 		 * unloading the tape
4975 		 */
4976 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
4977 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4978 			    "st_do_mtioctop :EIO:MTOFFL check "
4979 			    "density/wfm failed");
4980 			return (EIO);
4981 		}
4982 		(void) st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD);
4983 		if (st_cmd(dev, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
4984 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4985 			    "st_do_mtioctop : EIO : MTOFFL");
4986 			return (EIO);
4987 		}
4988 		un->un_pos.eof = ST_NO_EOF;
4989 		un->un_laststate = un->un_state;
4990 		un->un_state = ST_STATE_OFFLINE;
4991 		un->un_mediastate = MTIO_EJECTED;
4992 		break;
4993 
4994 	case MTLOAD:
4995 		/*
4996 		 * This is to load a tape into the drive
4997 		 * Note that if the tape is not loaded, the device will have
4998 		 * to be opened via O_NDELAY or O_NONBLOCK.
4999 		 */
5000 		/*
5001 		 * Let's try and clean things up, if we are not
5002 		 * initializing, and then send in the load command, no
5003 		 * matter what.
5004 		 *
5005 		 * load after a media change by the user.
5006 		 */
5007 
5008 		if (un->un_state > ST_STATE_INITIALIZING) {
5009 			(void) st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK);
5010 		}
5011 		rval = st_cmd(dev, SCMD_LOAD, LD_LOAD, SYNC_CMD);
5012 		/* Load command to a drive that doesn't support load */
5013 		if ((rval == EIO) &&
5014 		    ((un->un_status == KEY_NOT_READY) &&
5015 			/* Medium not present */
5016 		    (un->un_uscsi_rqs_buf->es_add_code == 0x3a) ||
5017 		    ((un->un_status == KEY_ILLEGAL_REQUEST) &&
5018 		    (un->un_dp->type == MT_ISSTK9840) &&
5019 			/* CSL not present */
5020 		    (un->un_uscsi_rqs_buf->es_add_code == 0x80)))) {
5021 			rval = ENOTTY;
5022 			break;
5023 		} else if (rval != EACCES) {
5024 			rval = EIO;
5025 		}
5026 		if (rval) {
5027 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5028 			    "st_do_mtioctop : %s : MTLOAD\n",
5029 			    rval == EACCES ? "EACCES" : "EIO");
5030 			/*
5031 			 * If load tape fails, who knows what happened...
5032 			 */
5033 			un->un_pos.pmode = invalid;
5034 			break;
5035 		}
5036 
5037 		/*
5038 		 * reset all counters appropriately using rewind, as if LOAD
5039 		 * succeeds, we are at BOT
5040 		 */
5041 		un->un_state = ST_STATE_INITIALIZING;
5042 
5043 		rval = st_tape_init(dev);
5044 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
5045 			rval = 0;
5046 			break;
5047 		}
5048 
5049 		if (rval != 0) {
5050 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5051 			    "st_do_mtioctop : EIO : MTLOAD calls "
5052 			    "st_tape_init\n");
5053 			rval = EIO;
5054 			un->un_state = ST_STATE_OFFLINE;
5055 		}
5056 
5057 		break;
5058 
5059 	case MTNOP:
5060 		un->un_status = 0;		/* Reset status */
5061 		un->un_err_resid = 0;
5062 		mtop->mt_count = MTUNIT(dev);
5063 		break;
5064 
5065 	case MTEOM:
5066 		/*
5067 		 * positions the tape at a location just after the last file
5068 		 * written on the tape. For cartridge and 8 mm, this after
5069 		 * the last file mark; for reel, this is inbetween the two
5070 		 * last 2 file marks
5071 		 */
5072 		if ((un->un_pos.pmode == legacy && un->un_pos.eof >= ST_EOT) ||
5073 		    (un->un_lastop == ST_OP_WRITE) ||
5074 		    (un->un_lastop == ST_OP_WEOF)) {
5075 			/*
5076 			 * If the command wants to move to logical end
5077 			 * of media, and we're already there, we're done.
5078 			 * If we were at logical eot, we reset the state
5079 			 * to be *not* at logical eot.
5080 			 *
5081 			 * If we're at physical or logical eot, we prohibit
5082 			 * forward space operations (unconditionally).
5083 			 *
5084 			 * Also if the last operation was a write of any
5085 			 * kind the tape is at EOD.
5086 			 */
5087 			return (0);
5088 		}
5089 		/*
5090 		 * physical tape position may not be what we've been
5091 		 * telling the user; adjust the request accordingly
5092 		 */
5093 		if (IN_EOF(un->un_pos)) {
5094 			un->un_pos.fileno++;
5095 			un->un_pos.blkno = 0;
5096 		}
5097 
5098 		if (st_check_density_or_wfm(dev, 1, B_READ, NO_STEPBACK)) {
5099 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5100 			    "st_do_mtioctop : EIO:MTEOM check density/wfm "
5101 			    " failed");
5102 			return (EIO);
5103 		}
5104 
5105 		/*
5106 		 * st_find_eod() returns the last fileno we knew about;
5107 		 */
5108 		savefile = st_find_eod(dev);
5109 
5110 		if ((un->un_status != KEY_BLANK_CHECK) &&
5111 		    (un->un_status != SUN_KEY_EOT)) {
5112 			un->un_pos.pmode = invalid;
5113 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5114 			    "st_do_mtioctop : EIO : MTEOM status check failed");
5115 			rval = EIO;
5116 		} else {
5117 			/*
5118 			 * For 1/2" reel tapes assume logical EOT marked
5119 			 * by two file marks or we don't care that we may
5120 			 * be extending the last file on the tape.
5121 			 */
5122 			if (un->un_dp->options & ST_REEL) {
5123 				if (st_cmd(dev, SCMD_SPACE, Fmk((-1)),
5124 				    SYNC_CMD)) {
5125 					un->un_pos.pmode = invalid;
5126 					ST_DEBUG2(ST_DEVINFO, st_label,
5127 					    SCSI_DEBUG,
5128 					    "st_do_mtioctop : EIO : MTEOM space"
5129 					    " cmd failed");
5130 					rval = EIO;
5131 					break;
5132 				}
5133 				/*
5134 				 * Fix up the block number.
5135 				 */
5136 				un->un_pos.blkno = 0;
5137 				un->un_err_pos.blkno = 0;
5138 			}
5139 			un->un_err_resid = 0;
5140 			un->un_pos.fileno = savefile;
5141 			un->un_pos.eof = ST_EOT;
5142 		}
5143 		un->un_status = 0;
5144 		break;
5145 
5146 	case MTFSF:
5147 		rval = st_mtfsf_ioctl(un, mtop->mt_count);
5148 		break;
5149 
5150 	case MTFSR:
5151 		rval = st_mtfsr_ioctl(un, mtop->mt_count);
5152 		break;
5153 
5154 	case MTBSF:
5155 		rval = st_mtbsf_ioctl(un, mtop->mt_count);
5156 		break;
5157 
5158 	case MTNBSF:
5159 		rval = st_mtnbsf_ioctl(un, mtop->mt_count);
5160 		break;
5161 
5162 	case MTBSR:
5163 		rval = st_mtbsr_ioctl(un, mtop->mt_count);
5164 		break;
5165 
5166 	case MTBSSF:
5167 		rval = st_mtbsfm_ioctl(un, mtop->mt_count);
5168 		break;
5169 
5170 	case MTFSSF:
5171 		rval = st_mtfsfm_ioctl(un, mtop->mt_count);
5172 		break;
5173 
5174 	case MTSRSZ:
5175 
5176 		/*
5177 		 * Set record-size to that sent by user
5178 		 * Check to see if there is reason that the requested
5179 		 * block size should not be set.
5180 		 */
5181 
5182 		/* If requesting variable block size is it ok? */
5183 		if ((mtop->mt_count == 0) &&
5184 		    ((un->un_dp->options & ST_VARIABLE) == 0)) {
5185 			return (ENOTTY);
5186 		}
5187 
5188 		/*
5189 		 * If requested block size is not variable "0",
5190 		 * is it less then minimum.
5191 		 */
5192 		if ((mtop->mt_count != 0) &&
5193 		    (mtop->mt_count < un->un_minbsize)) {
5194 			return (EINVAL);
5195 		}
5196 
5197 		/* Is the requested block size more then maximum */
5198 		if ((mtop->mt_count > min(un->un_maxbsize, un->un_maxdma)) &&
5199 		    (un->un_maxbsize != 0)) {
5200 			return (EINVAL);
5201 		}
5202 
5203 		/* Is requested block size a modulus the device likes */
5204 		if ((mtop->mt_count % un->un_data_mod) != 0) {
5205 			return (EINVAL);
5206 		}
5207 
5208 		if (st_change_block_size(dev, (uint32_t)mtop->mt_count) != 0) {
5209 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5210 			    "st_ioctl : MTSRSZ : EIO : cant set block size");
5211 			return (EIO);
5212 		}
5213 
5214 		return (0);
5215 
5216 	case MTGRSZ:
5217 		/*
5218 		 * Get record-size to the user
5219 		 */
5220 		mtop->mt_count = un->un_bsize;
5221 		rval = 0;
5222 		break;
5223 
5224 	case MTTELL:
5225 		rval = st_update_block_pos(un);
5226 		mtop->mt_count = un->un_pos.lgclblkno;
5227 		break;
5228 
5229 	case MTSEEK:
5230 		rval = st_logical_block_locate(un, (uint64_t)mtop->mt_count,
5231 		    un->un_pos.partition);
5232 		/*
5233 		 * This bit of magic make mt print the actual position if
5234 		 * the resulting position was not what was asked for.
5235 		 */
5236 		if (rval == ESPIPE) {
5237 			rval = EIO;
5238 			if ((uint64_t)mtop->mt_count != un->un_pos.lgclblkno) {
5239 				mtop->mt_op = MTTELL;
5240 				mtop->mt_count = un->un_pos.lgclblkno;
5241 			}
5242 		}
5243 		break;
5244 
5245 	case MTLOCK:
5246 		if (st_cmd(dev, SCMD_DOORLOCK, MR_LOCK, SYNC_CMD)) {
5247 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5248 			    "st_do_mtioctop : EIO : MTLOCK");
5249 			rval = EIO;
5250 		}
5251 		break;
5252 
5253 	case MTUNLOCK:
5254 		if (st_cmd(dev, SCMD_DOORLOCK, MR_UNLOCK, SYNC_CMD)) {
5255 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5256 			    "st_do_mtioctop : EIO : MTUNLOCK");
5257 			rval = EIO;
5258 		}
5259 		break;
5260 
5261 	default:
5262 		rval = ENOTTY;
5263 	}
5264 
5265 	return (rval);
5266 }
5267 
5268 
5269 /*
5270  * Run a command for uscsi ioctl.
5271  */
5272 static int
5273 st_ioctl_cmd(dev_t dev, struct uscsi_cmd *ucmd, int flag)
5274 {
5275 	struct uscsi_cmd	*uscmd;
5276 	struct buf	*bp;
5277 	enum uio_seg	uioseg;
5278 	int	offline_state = 0;
5279 	int	err = 0;
5280 
5281 	GET_SOFT_STATE(dev);
5282 
5283 	ST_FUNC(ST_DEVINFO, st_ioctl_cmd);
5284 
5285 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5286 	    "st_ioctl_cmd(dev = 0x%lx)\n", dev);
5287 
5288 	ASSERT(mutex_owned(ST_MUTEX));
5289 
5290 	/*
5291 	 * We really don't know what commands are coming in here and
5292 	 * we don't want to limit the commands coming in.
5293 	 *
5294 	 * If st_tape_init() gets called from st_strategy(), then we
5295 	 * will hang the process waiting for un->un_sbuf_busy to be cleared,
5296 	 * which it never will, as we set it below.  To prevent
5297 	 * st_tape_init() from getting called, we have to set state to other
5298 	 * than ST_STATE_OFFLINE, so we choose ST_STATE_INITIALIZING, which
5299 	 * achieves this purpose already.
5300 	 *
5301 	 * We use offline_state to preserve the OFFLINE state, if it exists,
5302 	 * so other entry points to the driver might have the chance to call
5303 	 * st_tape_init().
5304 	 */
5305 	if (un->un_state == ST_STATE_OFFLINE) {
5306 		un->un_laststate = ST_STATE_OFFLINE;
5307 		un->un_state = ST_STATE_INITIALIZING;
5308 		offline_state = 1;
5309 	}
5310 
5311 	mutex_exit(ST_MUTEX);
5312 	err = scsi_uscsi_alloc_and_copyin((intptr_t)ucmd, flag,
5313 	    ROUTE, &uscmd);
5314 	mutex_enter(ST_MUTEX);
5315 	if (err != 0) {
5316 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5317 		    "st_ioctl_cmd: scsi_uscsi_alloc_and_copyin failed\n");
5318 		goto exit;
5319 	}
5320 
5321 	uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE : UIO_USERSPACE;
5322 
5323 	/* check to see if this command requires the drive to be reserved */
5324 	if (uscmd->uscsi_cdb != NULL) {
5325 		err = st_check_cdb_for_need_to_reserve(un,
5326 		    &((char *)uscmd->uscsi_cdb)[0]);
5327 		if (err) {
5328 			goto exit_free;
5329 		}
5330 	}
5331 
5332 	/*
5333 	 * Get buffer resources...
5334 	 */
5335 	while (un->un_sbuf_busy)
5336 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
5337 	un->un_sbuf_busy = 1;
5338 
5339 #ifdef STDEBUG
5340 	if ((uscmd->uscsi_cdb != NULL) && (st_debug & 0xf) > 6) {
5341 		int rw = (uscmd->uscsi_flags & USCSI_READ) ? B_READ : B_WRITE;
5342 		st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
5343 		    "uscsi cdb", uscmd->uscsi_cdb);
5344 		if (uscmd->uscsi_buflen) {
5345 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5346 			    "uscsi %s of %ld bytes %s %s space\n",
5347 			    (rw == B_READ) ? rd_str : wr_str,
5348 			    uscmd->uscsi_buflen,
5349 			    (rw == B_READ) ? "to" : "from",
5350 			    (uioseg == UIO_SYSSPACE) ? "system" : "user");
5351 		}
5352 	}
5353 #endif /* ST_DEBUG */
5354 
5355 	/*
5356 	 * Although st_ioctl_cmd() never makes use of these
5357 	 * now, we are just being safe and consistent.
5358 	 */
5359 	uscmd->uscsi_flags &= ~(USCSI_NOINTR | USCSI_NOPARITY |
5360 	    USCSI_OTAG | USCSI_HTAG | USCSI_HEAD);
5361 
5362 	un->un_srqbufp = uscmd->uscsi_rqbuf;
5363 	bp = un->un_sbufp;
5364 	bzero(bp, sizeof (buf_t));
5365 	if (uscmd->uscsi_cdb != NULL) {
5366 		bp->b_forw =
5367 		    (struct buf *)(uintptr_t)((char *)uscmd->uscsi_cdb)[0];
5368 		bp->b_back = (struct buf *)uscmd;
5369 	}
5370 
5371 	mutex_exit(ST_MUTEX);
5372 	err = scsi_uscsi_handle_cmd(dev, uioseg, uscmd,
5373 	    st_strategy, bp, NULL);
5374 	mutex_enter(ST_MUTEX);
5375 
5376 	/*
5377 	 * If scsi reset successful, don't write any filemarks.
5378 	 */
5379 	if ((err == 0) && (uscmd->uscsi_flags &
5380 	    (USCSI_RESET_LUN | USCSI_RESET_TARGET | USCSI_RESET_ALL))) {
5381 		un->un_fmneeded = 0;
5382 	}
5383 
5384 exit_free:
5385 	/*
5386 	 * Free resources
5387 	 */
5388 	un->un_sbuf_busy = 0;
5389 	un->un_srqbufp = NULL;
5390 
5391 	/*
5392 	 * If was a space command need to update logical block position.
5393 	 * If the command failed such that positioning is invalid, Don't
5394 	 * update the position as the user must do this to validate the
5395 	 * position for data protection.
5396 	 */
5397 	if ((uscmd->uscsi_cdb != NULL) &&
5398 	    (uscmd->uscsi_cdb[0] == SCMD_SPACE) &&
5399 	    (un->un_pos.pmode != invalid)) {
5400 		uchar_t status = un->un_status;
5401 		(void) st_update_block_pos(un);
5402 		un->un_status = status;
5403 	}
5404 	cv_signal(&un->un_sbuf_cv);
5405 	mutex_exit(ST_MUTEX);
5406 	(void) scsi_uscsi_copyout_and_free((intptr_t)ucmd, uscmd);
5407 	mutex_enter(ST_MUTEX);
5408 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5409 	    "st_ioctl_cmd returns 0x%x\n", err);
5410 
5411 exit:
5412 	/* don't lose offline state */
5413 	if (offline_state) {
5414 		un->un_state = ST_STATE_OFFLINE;
5415 	}
5416 
5417 	ASSERT(mutex_owned(ST_MUTEX));
5418 	return (err);
5419 }
5420 
5421 static int
5422 st_write_fm(dev_t dev, int wfm)
5423 {
5424 	int i;
5425 	int rval;
5426 
5427 	GET_SOFT_STATE(dev);
5428 
5429 	ST_FUNC(ST_DEVINFO, st_write_fm);
5430 
5431 	ASSERT(mutex_owned(ST_MUTEX));
5432 
5433 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5434 	    "st_write_fm(dev = 0x%lx, wfm = %d)\n", dev, wfm);
5435 
5436 	/*
5437 	 * write one filemark at the time after EOT
5438 	 */
5439 	if (un->un_pos.eof >= ST_EOT) {
5440 		for (i = 0; i < wfm; i++) {
5441 			rval = st_cmd(dev, SCMD_WRITE_FILE_MARK, 1, SYNC_CMD);
5442 			if (rval == EACCES) {
5443 				return (rval);
5444 			}
5445 			if (rval != 0) {
5446 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5447 				    "st_write_fm : EIO : write EOT file mark");
5448 				return (EIO);
5449 			}
5450 		}
5451 	} else {
5452 		rval = st_cmd(dev, SCMD_WRITE_FILE_MARK, wfm, SYNC_CMD);
5453 		if (rval == EACCES) {
5454 			return (rval);
5455 		}
5456 		if (rval) {
5457 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5458 			    "st_write_fm : EIO : write file mark");
5459 			return (EIO);
5460 		}
5461 	}
5462 
5463 	ASSERT(mutex_owned(ST_MUTEX));
5464 	return (0);
5465 }
5466 
5467 #ifdef STDEBUG
5468 static void
5469 start_dump(struct scsi_tape *un, struct buf *bp)
5470 {
5471 	struct scsi_pkt *pkt = BP_PKT(bp);
5472 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
5473 
5474 	ST_FUNC(ST_DEVINFO, start_dump);
5475 
5476 	if ((st_debug & 0xf) < 6)
5477 		return;
5478 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5479 	    "st_start: cmd=0x%p count=%ld resid=%ld flags=0x%x pkt=0x%p\n",
5480 	    (void *)bp->b_forw, bp->b_bcount,
5481 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
5482 
5483 	st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
5484 	    "st_start: cdb",  (caddr_t)cdbp);
5485 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5486 	    "st_start: fileno=%d, blk=%d\n",
5487 	    un->un_pos.fileno, un->un_pos.blkno);
5488 }
5489 #endif
5490 
5491 
5492 /*
5493  * Command start && done functions
5494  */
5495 
5496 /*
5497  * st_start()
5498  *
5499  * Called from:
5500  *  st_strategy() to start a command.
5501  *  st_runout() to retry when scsi_pkt allocation fails on previous attempt(s).
5502  *  st_attach() when resuming from power down state.
5503  *  st_start_restart() to retry transport when device was previously busy.
5504  *  st_done_and_mutex_exit() to start the next command when previous is done.
5505  *
5506  * On entry:
5507  *  scsi_pkt may or may not be allocated.
5508  *
5509  */
5510 static void
5511 st_start(struct scsi_tape *un)
5512 {
5513 	struct buf *bp;
5514 	int status;
5515 
5516 	ST_FUNC(ST_DEVINFO, st_start);
5517 	ASSERT(mutex_owned(ST_MUTEX));
5518 
5519 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5520 	    "st_start(): dev = 0x%lx\n", un->un_dev);
5521 
5522 	if ((bp = un->un_quef) == NULL) {
5523 		return;
5524 	}
5525 
5526 	ASSERT((bp->b_flags & B_DONE) == 0);
5527 
5528 	/*
5529 	 * Don't send more than un_throttle commands to the HBA
5530 	 */
5531 	if ((un->un_throttle <= 0) || (un->un_ncmds >= un->un_throttle)) {
5532 		return;
5533 	}
5534 
5535 	/*
5536 	 * If the buf has no scsi_pkt call st_make_cmd() to get one and
5537 	 * build the command.
5538 	 */
5539 	if (BP_PKT(bp) == NULL) {
5540 		ASSERT((bp->b_flags & B_DONE) == 0);
5541 		st_make_cmd(un, bp, st_runout);
5542 		ASSERT((bp->b_flags & B_DONE) == 0);
5543 		status = geterror(bp);
5544 
5545 		/*
5546 		 * Some HBA's don't call bioerror() to set an error.
5547 		 * And geterror() returns zero if B_ERROR is not set.
5548 		 * So if we get zero we must check b_error.
5549 		 */
5550 		if (status == 0 && bp->b_error != 0) {
5551 			status = bp->b_error;
5552 			bioerror(bp, status);
5553 		}
5554 
5555 		/*
5556 		 * Some HBA's convert DDI_DMA_NORESOURCES into ENOMEM.
5557 		 * In tape ENOMEM has special meaning so we'll change it.
5558 		 */
5559 		if (status == ENOMEM) {
5560 			status = 0;
5561 			bioerror(bp, status);
5562 		}
5563 
5564 		/*
5565 		 * Did it fail and is it retryable?
5566 		 * If so return and wait for the callback through st_runout.
5567 		 * Also looks like scsi_init_pkt() will setup a callback even
5568 		 * if it isn't retryable.
5569 		 */
5570 		if (BP_PKT(bp) == NULL) {
5571 			if (status == 0) {
5572 				/*
5573 				 * If first attempt save state.
5574 				 */
5575 				if (un->un_state != ST_STATE_RESOURCE_WAIT) {
5576 					un->un_laststate = un->un_state;
5577 					un->un_state = ST_STATE_RESOURCE_WAIT;
5578 				}
5579 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5580 				    "temp no resources for pkt\n");
5581 			} else {
5582 				/*
5583 				 * Unlikely that it would be retryable then not.
5584 				 */
5585 				if (un->un_state == ST_STATE_RESOURCE_WAIT) {
5586 					un->un_state = un->un_laststate;
5587 				}
5588 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5589 				    "perm no resources for pkt errno = 0x%x\n",
5590 				    status);
5591 			}
5592 			return;
5593 		}
5594 		/*
5595 		 * Worked this time set the state back.
5596 		 */
5597 		if (un->un_state == ST_STATE_RESOURCE_WAIT) {
5598 			un->un_state = un->un_laststate;
5599 		}
5600 	}
5601 
5602 	/*
5603 	 * move from waitq to runq
5604 	 */
5605 	un->un_quef = bp->b_actf;
5606 	if (un->un_quel == bp) {
5607 		/*
5608 		 *  For the case of queue having one
5609 		 *  element, set the tail pointer to
5610 		 *  point to the element.
5611 		 */
5612 		un->un_quel = bp->b_actf;
5613 	}
5614 
5615 	bp->b_actf = NULL;
5616 
5617 	if (un->un_runqf) {
5618 		un->un_runql->b_actf = bp;
5619 	} else {
5620 		un->un_runqf = bp;
5621 	}
5622 	un->un_runql = bp;
5623 
5624 
5625 	ST_CDB(ST_DEVINFO, "Start CDB", (char *)BP_PKT(bp)->pkt_cdbp);
5626 
5627 #ifdef STDEBUG
5628 	start_dump(un, bp);
5629 #endif
5630 
5631 	/* could not get here if throttle was zero */
5632 	un->un_last_throttle = un->un_throttle;
5633 	un->un_throttle = 0;	/* so nothing else will come in here */
5634 	un->un_ncmds++;
5635 
5636 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
5637 
5638 	mutex_exit(ST_MUTEX);
5639 
5640 	status = scsi_transport(BP_PKT(bp));
5641 
5642 	mutex_enter(ST_MUTEX);
5643 
5644 	if (un->un_last_throttle) {
5645 		un->un_throttle = un->un_last_throttle;
5646 	}
5647 
5648 	if (status != TRAN_ACCEPT) {
5649 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
5650 		mutex_exit(ST_MUTEX);
5651 
5652 		if (status == TRAN_BUSY) {
5653 			/* if too many retries, fail the transport */
5654 			if (st_handle_start_busy(un, bp,
5655 			    ST_TRAN_BUSY_TIMEOUT) == 0)
5656 				goto done;
5657 		}
5658 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
5659 		    "transport rejected\n");
5660 		bp->b_resid = bp->b_bcount;
5661 
5662 
5663 #ifndef __lock_lint
5664 		/*
5665 		 * warlock doesn't understand this potential
5666 		 * recursion?
5667 		 */
5668 		mutex_enter(ST_MUTEX);
5669 		ST_DO_KSTATS(bp, kstat_waitq_exit);
5670 		ST_DO_ERRSTATS(un, st_transerrs);
5671 		st_bioerror(bp, EIO);
5672 		SET_PE_FLAG(un);
5673 		st_done_and_mutex_exit(un, bp);
5674 #endif
5675 	} else {
5676 		un->un_tran_retry_ct = 0;
5677 		mutex_exit(ST_MUTEX);
5678 	}
5679 
5680 done:
5681 
5682 	mutex_enter(ST_MUTEX);
5683 }
5684 
5685 /*
5686  * if the transport is busy, then put this bp back on the waitq
5687  */
5688 static int
5689 st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
5690     clock_t timeout_interval)
5691 {
5692 	struct buf *last_quef, *runq_bp;
5693 	int rval = 0;
5694 
5695 	ST_FUNC(ST_DEVINFO, st_handle_start_busy);
5696 
5697 	mutex_enter(ST_MUTEX);
5698 
5699 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5700 	    "st_handle_start_busy()\n");
5701 
5702 	/*
5703 	 * Check to see if we hit the retry timeout and one last check for
5704 	 * making sure this is the last on the runq, if it is not, we have
5705 	 * to fail
5706 	 */
5707 	if (((int)un->un_tran_retry_ct++ > st_retry_count) ||
5708 	    (un->un_runql != bp)) {
5709 		rval = -1;
5710 		goto exit;
5711 	}
5712 
5713 	/* put the bp back on the waitq */
5714 	if (un->un_quef) {
5715 		last_quef = un->un_quef;
5716 		un->un_quef = bp;
5717 		bp->b_actf = last_quef;
5718 	} else  {
5719 		bp->b_actf = NULL;
5720 		un->un_quef = bp;
5721 		un->un_quel = bp;
5722 	}
5723 
5724 	/*
5725 	 * Decrement un_ncmds so that this
5726 	 * gets thru' st_start() again.
5727 	 */
5728 	un->un_ncmds--;
5729 
5730 	/*
5731 	 * since this is an error case, we won't have to do
5732 	 * this list walking much.  We've already made sure this bp was the
5733 	 * last on the runq
5734 	 */
5735 	runq_bp = un->un_runqf;
5736 
5737 	if (un->un_runqf == bp) {
5738 		un->un_runqf = NULL;
5739 		un->un_runql = NULL;
5740 	} else {
5741 		while (runq_bp) {
5742 			if (runq_bp->b_actf == bp) {
5743 				runq_bp->b_actf = NULL;
5744 				un->un_runql = runq_bp;
5745 				break;
5746 			}
5747 			runq_bp = runq_bp->b_actf;
5748 		}
5749 	}
5750 
5751 
5752 	/*
5753 	 * send a marker pkt, if appropriate
5754 	 */
5755 	st_hba_unflush(un);
5756 
5757 	/*
5758 	 * all queues are aligned, we are just waiting to
5759 	 * transport, don't alloc any more buf p's, when
5760 	 * st_start is reentered.
5761 	 */
5762 	(void) timeout(st_start_restart, un, timeout_interval);
5763 
5764 exit:
5765 	mutex_exit(ST_MUTEX);
5766 	return (rval);
5767 }
5768 
5769 
5770 /*
5771  * st_runout a callback that is called what a resource allocatation failed
5772  */
5773 static int
5774 st_runout(caddr_t arg)
5775 {
5776 	struct scsi_tape *un = (struct scsi_tape *)arg;
5777 	struct buf *bp;
5778 	ASSERT(un != NULL);
5779 
5780 	ST_FUNC(ST_DEVINFO, st_runout);
5781 
5782 	mutex_enter(ST_MUTEX);
5783 
5784 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_runout()\n");
5785 
5786 	bp = un->un_quef;
5787 
5788 	/*
5789 	 * failed scsi_init_pkt(). If errno is zero its retryable.
5790 	 */
5791 	if ((bp != NULL) && (geterror(bp) != 0)) {
5792 
5793 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
5794 		    "errors after pkt alloc (b_flags=0x%x, b_error=0x%x)\n",
5795 		    bp->b_flags, geterror(bp));
5796 		ASSERT((bp->b_flags & B_DONE) == 0);
5797 
5798 		un->un_quef = bp->b_actf;
5799 		if (un->un_quel == bp) {
5800 			/*
5801 			 *  For the case of queue having one
5802 			 *  element, set the tail pointer to
5803 			 *  point to the element.
5804 			 */
5805 			un->un_quel = bp->b_actf;
5806 		}
5807 		mutex_exit(ST_MUTEX);
5808 		bp->b_actf = NULL;
5809 
5810 		ASSERT((bp->b_flags & B_DONE) == 0);
5811 
5812 		/*
5813 		 * Set resid, Error already set, then unblock calling thread.
5814 		 */
5815 		bp->b_resid = bp->b_bcount;
5816 		biodone(bp);
5817 	} else {
5818 		/*
5819 		 * Try Again
5820 		 */
5821 		st_start(un);
5822 		mutex_exit(ST_MUTEX);
5823 	}
5824 
5825 	/*
5826 	 * Comments courtesy of sd.c
5827 	 * The scsi_init_pkt routine allows for the callback function to
5828 	 * return a 0 indicating the callback should be rescheduled or a 1
5829 	 * indicating not to reschedule. This routine always returns 1
5830 	 * because the driver always provides a callback function to
5831 	 * scsi_init_pkt. This results in a callback always being scheduled
5832 	 * (via the scsi_init_pkt callback implementation) if a resource
5833 	 * failure occurs.
5834 	 */
5835 
5836 	return (1);
5837 }
5838 
5839 /*
5840  * st_done_and_mutex_exit()
5841  *	- remove bp from runq
5842  *	- start up the next request
5843  *	- if this was an asynch bp, clean up
5844  *	- exit with released mutex
5845  */
5846 static void
5847 st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp)
5848 {
5849 	struct buf *runqbp, *prevbp;
5850 	int	pe_flagged = 0;
5851 
5852 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
5853 #if !defined(lint)
5854 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
5855 #endif
5856 
5857 	ST_FUNC(ST_DEVINFO, st_done_and_mutex_exit);
5858 
5859 	ASSERT(mutex_owned(ST_MUTEX));
5860 
5861 	/*
5862 	 * if bp is still on the runq (anywhere), then remove it
5863 	 */
5864 	prevbp = NULL;
5865 	for (runqbp = un->un_runqf; runqbp != 0; runqbp = runqbp->b_actf) {
5866 		if (runqbp == bp) {
5867 			if (runqbp == un->un_runqf) {
5868 				un->un_runqf = bp->b_actf;
5869 			} else {
5870 				prevbp->b_actf = bp->b_actf;
5871 			}
5872 			if (un->un_runql == bp) {
5873 				un->un_runql = prevbp;
5874 			}
5875 			break;
5876 		}
5877 		prevbp = runqbp;
5878 	}
5879 	bp->b_actf = NULL;
5880 
5881 	un->un_ncmds--;
5882 	cv_signal(&un->un_queue_cv);
5883 
5884 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5885 	    "st_done_and_mutex_exit(): cmd=0x%x count=%ld resid=%ld  flags="
5886 	    "0x%x\n", (uchar_t)*((caddr_t)(BP_PKT(bp))->pkt_cdbp), bp->b_bcount,
5887 	    bp->b_resid, bp->b_flags);
5888 
5889 
5890 	/*
5891 	 * update kstats with transfer count info
5892 	 */
5893 	if (un->un_stats && (bp != un->un_sbufp) && IS_RW(bp)) {
5894 		uint32_t n_done =  bp->b_bcount - bp->b_resid;
5895 		if (bp->b_flags & B_READ) {
5896 			IOSP->reads++;
5897 			IOSP->nread += n_done;
5898 		} else {
5899 			IOSP->writes++;
5900 			IOSP->nwritten += n_done;
5901 		}
5902 	}
5903 
5904 	/*
5905 	 * Start the next one before releasing resources on this one, if
5906 	 * there is something on the queue and persistent errors has not been
5907 	 * flagged
5908 	 */
5909 
5910 	if ((pe_flagged = IS_PE_FLAG_SET(un)) != 0) {
5911 		un->un_last_resid = bp->b_resid;
5912 		un->un_last_count = bp->b_bcount;
5913 	}
5914 
5915 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
5916 		cv_broadcast(&un->un_tape_busy_cv);
5917 	} else if (un->un_quef && un->un_throttle && !pe_flagged) {
5918 		st_start(un);
5919 	}
5920 
5921 	if (bp == un->un_sbufp && (bp->b_flags & B_ASYNC)) {
5922 		/*
5923 		 * Since we marked this ourselves as ASYNC,
5924 		 * there isn't anybody around waiting for
5925 		 * completion any more.
5926 		 */
5927 		uchar_t com = (uchar_t)(uintptr_t)bp->b_forw;
5928 		if (com == SCMD_READ || com == SCMD_WRITE) {
5929 			bp->b_un.b_addr = (caddr_t)0;
5930 		}
5931 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5932 		    "st_done_and_mutex_exit(async): freeing pkt\n");
5933 		scsi_destroy_pkt(BP_PKT(bp));
5934 		un->un_sbuf_busy = 0;
5935 		cv_signal(&un->un_sbuf_cv);
5936 		mutex_exit(ST_MUTEX);
5937 		return;
5938 	}
5939 
5940 	if (bp == un->un_sbufp && BP_UCMD(bp)) {
5941 		/*
5942 		 * Copy status from scsi_pkt to uscsi_cmd
5943 		 * since st_ioctl_cmd needs it
5944 		 */
5945 		BP_UCMD(bp)->uscsi_status = SCBP_C(BP_PKT(bp));
5946 	}
5947 
5948 
5949 #ifdef STDEBUG
5950 	if (((st_debug & 0xf) >= 4) &&
5951 	    (((un->un_pos.blkno % 100) == 0) || IS_PE_FLAG_SET(un))) {
5952 
5953 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
5954 		    "st_d_a_m_exit(): ncmds = %d, thr = %d, "
5955 		    "un_errno = %d, un_pe = %d\n",
5956 		    un->un_ncmds, un->un_throttle, un->un_errno,
5957 		    un->un_persist_errors);
5958 	}
5959 
5960 #endif
5961 
5962 	mutex_exit(ST_MUTEX);
5963 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5964 	    "st_done_and_mutex_exit: freeing pkt\n");
5965 
5966 	scsi_destroy_pkt(BP_PKT(bp));
5967 
5968 	biodone(bp);
5969 
5970 	/*
5971 	 * now that we biodoned that command, if persistent errors have been
5972 	 * flagged, flush the waitq
5973 	 */
5974 	if (pe_flagged)
5975 		st_flush(un);
5976 }
5977 
5978 
5979 /*
5980  * Tape error, flush tape driver queue.
5981  */
5982 static void
5983 st_flush(struct scsi_tape *un)
5984 {
5985 	struct buf *bp;
5986 
5987 	ST_FUNC(ST_DEVINFO, st_flush);
5988 
5989 	mutex_enter(ST_MUTEX);
5990 
5991 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
5992 	    "st_flush(), ncmds = %d, quef = 0x%p\n",
5993 	    un->un_ncmds, (void *)un->un_quef);
5994 
5995 	/*
5996 	 * if we still have commands outstanding, wait for them to come in
5997 	 * before flushing the queue, and make sure there is a queue
5998 	 */
5999 	if (un->un_ncmds || !un->un_quef)
6000 		goto exit;
6001 
6002 	/*
6003 	 * we have no more commands outstanding, so let's deal with special
6004 	 * cases in the queue for EOM and FM. If we are here, and un_errno
6005 	 * is 0, then we know there was no error and we return a 0 read or
6006 	 * write before showing errors
6007 	 */
6008 
6009 	/* Flush the wait queue. */
6010 	while ((bp = un->un_quef) != NULL) {
6011 		un->un_quef = bp->b_actf;
6012 
6013 		bp->b_resid = bp->b_bcount;
6014 
6015 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6016 		    "st_flush() : blkno=%d, err=%d, b_bcount=%ld\n",
6017 		    un->un_pos.blkno, un->un_errno, bp->b_bcount);
6018 
6019 		st_set_pe_errno(un);
6020 
6021 		bioerror(bp, un->un_errno);
6022 
6023 		mutex_exit(ST_MUTEX);
6024 		/* it should have one, but check anyway */
6025 		if (BP_PKT(bp)) {
6026 			scsi_destroy_pkt(BP_PKT(bp));
6027 		}
6028 		biodone(bp);
6029 		mutex_enter(ST_MUTEX);
6030 	}
6031 
6032 	/*
6033 	 * It's not a bad practice to reset the
6034 	 * waitq tail pointer to NULL.
6035 	 */
6036 	un->un_quel = NULL;
6037 
6038 exit:
6039 	/* we mucked with the queue, so let others know about it */
6040 	cv_signal(&un->un_queue_cv);
6041 	mutex_exit(ST_MUTEX);
6042 }
6043 
6044 
6045 /*
6046  * Utility functions
6047  */
6048 static int
6049 st_determine_generic(dev_t dev)
6050 {
6051 	int bsize;
6052 	static char *cart = "0.25 inch cartridge";
6053 	char *sizestr;
6054 
6055 	GET_SOFT_STATE(dev);
6056 
6057 	ST_FUNC(ST_DEVINFO, st_determine_generic);
6058 
6059 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6060 	    "st_determine_generic(dev = 0x%lx)\n", dev);
6061 
6062 	ASSERT(mutex_owned(ST_MUTEX));
6063 
6064 	if (st_modesense(un)) {
6065 		return (-1);
6066 	}
6067 
6068 	bsize = (un->un_mspl->high_bl << 16)	|
6069 	    (un->un_mspl->mid_bl << 8)	|
6070 	    (un->un_mspl->low_bl);
6071 
6072 	if (bsize == 0) {
6073 		un->un_dp->options |= ST_VARIABLE;
6074 		un->un_dp->bsize = 0;
6075 		un->un_bsize = 0;
6076 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
6077 		/*
6078 		 * record size of this device too big.
6079 		 * try and convert it to variable record length.
6080 		 *
6081 		 */
6082 		un->un_dp->options |= ST_VARIABLE;
6083 		if (st_change_block_size(dev, 0) != 0) {
6084 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
6085 			    "Fixed Record Size %d is too large\n", bsize);
6086 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
6087 			    "Cannot switch to variable record size\n");
6088 			un->un_dp->options &= ~ST_VARIABLE;
6089 			return (-1);
6090 		}
6091 	} else if (st_change_block_size(dev, 0) == 0) {
6092 		/*
6093 		 * If the drive was set to a non zero block size,
6094 		 * See if it can be set to a zero block size.
6095 		 * If it works, ST_VARIABLE so user can set it as they want.
6096 		 */
6097 		un->un_dp->options |= ST_VARIABLE;
6098 		un->un_dp->bsize = 0;
6099 		un->un_bsize = 0;
6100 	} else {
6101 		un->un_dp->bsize = bsize;
6102 		un->un_bsize = bsize;
6103 	}
6104 
6105 
6106 	switch (un->un_mspl->density) {
6107 	default:
6108 	case 0x0:
6109 		/*
6110 		 * default density, cannot determine any other
6111 		 * information.
6112 		 */
6113 		sizestr = "Unknown type- assuming 0.25 inch cartridge";
6114 		un->un_dp->type = ST_TYPE_DEFAULT;
6115 		un->un_dp->options |= (ST_AUTODEN_OVERRIDE|ST_QIC);
6116 		break;
6117 	case 0x1:
6118 	case 0x2:
6119 	case 0x3:
6120 	case 0x6:
6121 		/*
6122 		 * 1/2" reel
6123 		 */
6124 		sizestr = "0.50 inch reel";
6125 		un->un_dp->type = ST_TYPE_REEL;
6126 		un->un_dp->options |= ST_REEL;
6127 		un->un_dp->densities[0] = 0x1;
6128 		un->un_dp->densities[1] = 0x2;
6129 		un->un_dp->densities[2] = 0x6;
6130 		un->un_dp->densities[3] = 0x3;
6131 		break;
6132 	case 0x4:
6133 	case 0x5:
6134 	case 0x7:
6135 	case 0x0b:
6136 
6137 		/*
6138 		 * Quarter inch.
6139 		 */
6140 		sizestr = cart;
6141 		un->un_dp->type = ST_TYPE_DEFAULT;
6142 		un->un_dp->options |= ST_QIC;
6143 
6144 		un->un_dp->densities[1] = 0x4;
6145 		un->un_dp->densities[2] = 0x5;
6146 		un->un_dp->densities[3] = 0x7;
6147 		un->un_dp->densities[0] = 0x0b;
6148 		break;
6149 
6150 	case 0x0f:
6151 	case 0x10:
6152 	case 0x11:
6153 	case 0x12:
6154 		/*
6155 		 * QIC-120, QIC-150, QIC-320, QIC-600
6156 		 */
6157 		sizestr = cart;
6158 		un->un_dp->type = ST_TYPE_DEFAULT;
6159 		un->un_dp->options |= ST_QIC;
6160 		un->un_dp->densities[0] = 0x0f;
6161 		un->un_dp->densities[1] = 0x10;
6162 		un->un_dp->densities[2] = 0x11;
6163 		un->un_dp->densities[3] = 0x12;
6164 		break;
6165 
6166 	case 0x09:
6167 	case 0x0a:
6168 	case 0x0c:
6169 	case 0x0d:
6170 		/*
6171 		 * 1/2" cartridge tapes. Include HI-TC.
6172 		 */
6173 		sizestr = cart;
6174 		sizestr[2] = '5';
6175 		sizestr[3] = '0';
6176 		un->un_dp->type = ST_TYPE_HIC;
6177 		un->un_dp->densities[0] = 0x09;
6178 		un->un_dp->densities[1] = 0x0a;
6179 		un->un_dp->densities[2] = 0x0c;
6180 		un->un_dp->densities[3] = 0x0d;
6181 		break;
6182 
6183 	case 0x13:
6184 			/* DDS-2/DDS-3 scsi spec densities */
6185 	case 0x24:
6186 	case 0x25:
6187 	case 0x26:
6188 		sizestr = "DAT Data Storage (DDS)";
6189 		un->un_dp->type = ST_TYPE_DAT;
6190 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
6191 		break;
6192 
6193 	case 0x14:
6194 		/*
6195 		 * Helical Scan (Exabyte) devices
6196 		 */
6197 		sizestr = "8mm helical scan cartridge";
6198 		un->un_dp->type = ST_TYPE_EXABYTE;
6199 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
6200 		break;
6201 	}
6202 
6203 	/*
6204 	 * Assume LONG ERASE, BSF and BSR
6205 	 */
6206 
6207 	un->un_dp->options |=
6208 	    (ST_LONG_ERASE | ST_UNLOADABLE | ST_BSF | ST_BSR | ST_KNOWS_EOD);
6209 
6210 	/*
6211 	 * Only if mode sense data says no buffered write, set NOBUF
6212 	 */
6213 	if (un->un_mspl->bufm == 0)
6214 		un->un_dp->options |= ST_NOBUF;
6215 
6216 	/*
6217 	 * set up large read and write retry counts
6218 	 */
6219 
6220 	un->un_dp->max_rretries = un->un_dp->max_wretries = 1000;
6221 
6222 	/*
6223 	 * If this is a 0.50 inch reel tape, and
6224 	 * it is *not* variable mode, try and
6225 	 * set it to variable record length
6226 	 * mode.
6227 	 */
6228 	if ((un->un_dp->options & ST_REEL) && un->un_bsize != 0 &&
6229 	    (un->un_dp->options & ST_VARIABLE)) {
6230 		if (st_change_block_size(dev, 0) == 0) {
6231 			un->un_dp->bsize = 0;
6232 			un->un_mspl->high_bl = un->un_mspl->mid_bl =
6233 			    un->un_mspl->low_bl = 0;
6234 		}
6235 	}
6236 
6237 	/*
6238 	 * Write to console about type of device found
6239 	 */
6240 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
6241 	    "Generic Drive, Vendor=%s\n\t%s", un->un_dp->name,
6242 	    sizestr);
6243 	if (un->un_dp->options & ST_VARIABLE) {
6244 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
6245 		    "!Variable record length I/O\n");
6246 	} else {
6247 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
6248 		    "!Fixed record length (%d byte blocks) I/O\n",
6249 		    un->un_dp->bsize);
6250 	}
6251 	ASSERT(mutex_owned(ST_MUTEX));
6252 	return (0);
6253 }
6254 
6255 static int
6256 st_determine_density(dev_t dev, int rw)
6257 {
6258 	int rval = 0;
6259 
6260 	GET_SOFT_STATE(dev);
6261 
6262 	ST_FUNC(ST_DEVINFO, st_determine_density);
6263 
6264 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6265 	    "st_determine_density(dev = 0x%lx, rw = %s)\n",
6266 	    dev, (rw == B_WRITE ? wr_str: rd_str));
6267 
6268 	ASSERT(mutex_owned(ST_MUTEX));
6269 
6270 	/*
6271 	 * If we're past BOT, density is determined already.
6272 	 */
6273 	if (un->un_pos.pmode == logical) {
6274 		if (un->un_pos.lgclblkno != 0) {
6275 			goto exit;
6276 		}
6277 	} else if (un->un_pos.pmode == legacy) {
6278 		if ((un->un_pos.fileno != 0) || (un->un_pos.blkno != 0)) {
6279 			/*
6280 			 * XXX: put in a bitch message about attempting to
6281 			 * XXX: change density past BOT.
6282 			 */
6283 			goto exit;
6284 		}
6285 	} else {
6286 		goto exit;
6287 	}
6288 
6289 
6290 	/*
6291 	 * If we're going to be writing, we set the density
6292 	 */
6293 	if (rw == 0 || rw == B_WRITE) {
6294 		/* un_curdens is used as an index into densities table */
6295 		un->un_curdens = MT_DENSITY(un->un_dev);
6296 		if (st_set_density(dev)) {
6297 			rval = -1;
6298 		}
6299 		goto exit;
6300 	}
6301 
6302 	/*
6303 	 * If density is known already,
6304 	 * we don't have to get it again.(?)
6305 	 */
6306 	if (!un->un_density_known) {
6307 		if (st_get_density(dev)) {
6308 			rval = -1;
6309 		}
6310 	}
6311 
6312 exit:
6313 	ASSERT(mutex_owned(ST_MUTEX));
6314 	return (rval);
6315 }
6316 
6317 
6318 /*
6319  * Try to determine density. We do this by attempting to read the
6320  * first record off the tape, cycling through the available density
6321  * codes as we go.
6322  */
6323 
6324 static int
6325 st_get_density(dev_t dev)
6326 {
6327 	int succes = 0, rval = -1, i;
6328 	uint_t size;
6329 	uchar_t dens, olddens;
6330 
6331 	GET_SOFT_STATE(dev);
6332 
6333 	ST_FUNC(ST_DEVINFO, st_get_density);
6334 
6335 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6336 	    "st_get_density(dev = 0x%lx)\n", dev);
6337 
6338 	ASSERT(mutex_owned(ST_MUTEX));
6339 
6340 	/*
6341 	 * If Auto Density override is enabled The drive has
6342 	 * only one density and there is no point in attempting
6343 	 * find the correct one.
6344 	 *
6345 	 * Since most modern drives auto detect the density
6346 	 * and format of the recorded media before they come
6347 	 * ready. What this function does is a legacy behavior
6348 	 * and modern drives not only don't need it, The backup
6349 	 * utilities that do positioning via uscsi find the un-
6350 	 * expected rewinds problematic.
6351 	 *
6352 	 * The drives that need this are old reel to reel devices.
6353 	 * I took a swag and said they must be scsi-1 or older.
6354 	 * I don't beleave there will any of the newer devices
6355 	 * that need this. There will be some scsi-1 devices that
6356 	 * don't need this but I don't think they will be using the
6357 	 * BIG aftermarket backup and restore utilitys.
6358 	 */
6359 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) ||
6360 	    (un->un_sd->sd_inq->inq_ansi > 1)) {
6361 		un->un_density_known = 1;
6362 		rval = 0;
6363 		goto exit;
6364 	}
6365 
6366 	/*
6367 	 * This will only work on variable record length tapes
6368 	 * if and only if all variable record length tapes autodensity
6369 	 * select.
6370 	 */
6371 	size = (unsigned)(un->un_dp->bsize ? un->un_dp->bsize : SECSIZE);
6372 	un->un_tmpbuf = kmem_alloc(size, KM_SLEEP);
6373 
6374 	/*
6375 	 * Start at the specified density
6376 	 */
6377 
6378 	dens = olddens = un->un_curdens = MT_DENSITY(un->un_dev);
6379 
6380 	for (i = 0; i < NDENSITIES; i++, ((un->un_curdens == NDENSITIES - 1) ?
6381 	    (un->un_curdens = 0) : (un->un_curdens += 1))) {
6382 		/*
6383 		 * If we've done this density before,
6384 		 * don't bother to do it again.
6385 		 */
6386 		dens = un->un_dp->densities[un->un_curdens];
6387 		if (i > 0 && dens == olddens)
6388 			continue;
6389 		olddens = dens;
6390 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6391 		    "trying density 0x%x\n", dens);
6392 		if (st_set_density(dev)) {
6393 			continue;
6394 		}
6395 
6396 		/*
6397 		 * XXX - the creates lots of headaches and slowdowns - must
6398 		 * fix.
6399 		 */
6400 		succes = (st_cmd(dev, SCMD_READ, (int)size, SYNC_CMD) == 0);
6401 		if (st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD)) {
6402 			break;
6403 		}
6404 		if (succes) {
6405 			st_init(un);
6406 			rval = 0;
6407 			un->un_density_known = 1;
6408 			break;
6409 		}
6410 	}
6411 	kmem_free(un->un_tmpbuf, size);
6412 	un->un_tmpbuf = 0;
6413 
6414 exit:
6415 	ASSERT(mutex_owned(ST_MUTEX));
6416 	return (rval);
6417 }
6418 
6419 static int
6420 st_set_density(dev_t dev)
6421 {
6422 	int rval = 0;
6423 
6424 	GET_SOFT_STATE(dev);
6425 
6426 	ST_FUNC(ST_DEVINFO, st_set_density);
6427 
6428 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6429 	    "st_set_density(dev = 0x%lx): density = 0x%x\n", dev,
6430 	    un->un_dp->densities[un->un_curdens]);
6431 
6432 	ASSERT(mutex_owned(ST_MUTEX));
6433 
6434 	un->un_mspl->density = un->un_dp->densities[un->un_curdens];
6435 
6436 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) == 0) {
6437 		/*
6438 		 * If auto density override is not set, Use mode select
6439 		 * to set density and compression.
6440 		 */
6441 		if (st_modeselect(un)) {
6442 			rval = -1;
6443 		}
6444 	} else if ((un->un_dp->options & ST_MODE_SEL_COMP) != 0) {
6445 		/*
6446 		 * If auto density and mode select compression are set,
6447 		 * This is a drive with one density code but compression
6448 		 * can be enabled or disabled.
6449 		 * Set compression but no need to set density.
6450 		 */
6451 		rval = st_set_compression(un);
6452 		if ((rval != 0) && (rval != EALREADY)) {
6453 			rval = -1;
6454 		} else {
6455 			rval = 0;
6456 		}
6457 	}
6458 
6459 	/* If sucessful set density and/or compression, mark density known */
6460 	if (rval == 0) {
6461 		un->un_density_known = 1;
6462 	}
6463 
6464 	ASSERT(mutex_owned(ST_MUTEX));
6465 	return (rval);
6466 }
6467 
6468 static int
6469 st_loadtape(dev_t dev)
6470 {
6471 	int rval;
6472 
6473 	GET_SOFT_STATE(dev);
6474 
6475 	ST_FUNC(ST_DEVINFO, st_load_tape);
6476 
6477 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6478 	    "st_loadtape(dev = 0x%lx)\n", dev);
6479 
6480 	ASSERT(mutex_owned(ST_MUTEX));
6481 
6482 	/*
6483 	 * 'LOAD' the tape to BOT by rewinding
6484 	 */
6485 	rval = st_cmd(dev, SCMD_REWIND, 1, SYNC_CMD);
6486 	if (rval == 0) {
6487 		st_init(un);
6488 		un->un_density_known = 0;
6489 	}
6490 
6491 	ASSERT(mutex_owned(ST_MUTEX));
6492 	return (rval);
6493 }
6494 
6495 
6496 /*
6497  * Note: QIC devices aren't so smart.  If you try to append
6498  * after EOM, the write can fail because the device doesn't know
6499  * it's at EOM.	 In that case, issue a read.  The read should fail
6500  * because there's no data, but the device knows it's at EOM,
6501  * so a subsequent write should succeed.  To further confuse matters,
6502  * the target returns the same error if the tape is positioned
6503  * such that a write would overwrite existing data.  That's why
6504  * we have to do the append test.  A read in the middle of
6505  * recorded data would succeed, thus indicating we're attempting
6506  * something illegal.
6507  */
6508 
6509 
6510 static void
6511 st_test_append(struct buf *bp)
6512 {
6513 	dev_t dev = bp->b_edev;
6514 	struct scsi_tape *un;
6515 	uchar_t status;
6516 	unsigned bcount;
6517 
6518 	un = ddi_get_soft_state(st_state, MTUNIT(dev));
6519 
6520 	ST_FUNC(ST_DEVINFO, st_test_append);
6521 
6522 	ASSERT(mutex_owned(ST_MUTEX));
6523 
6524 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6525 	    "st_test_append(): fileno %d\n", un->un_pos.fileno);
6526 
6527 	un->un_laststate = un->un_state;
6528 	un->un_state = ST_STATE_APPEND_TESTING;
6529 	un->un_test_append = 0;
6530 
6531 	/*
6532 	 * first, map in the buffer, because we're doing a double write --
6533 	 * first into the kernel, then onto the tape.
6534 	 */
6535 	bp_mapin(bp);
6536 
6537 	/*
6538 	 * get a copy of the data....
6539 	 */
6540 	un->un_tmpbuf = kmem_alloc((unsigned)bp->b_bcount, KM_SLEEP);
6541 	bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
6542 
6543 	/*
6544 	 * attempt the write..
6545 	 */
6546 
6547 	if (st_cmd(dev, (int)SCMD_WRITE, (int)bp->b_bcount, SYNC_CMD) == 0) {
6548 success:
6549 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6550 		    "append write succeeded\n");
6551 		bp->b_resid = un->un_sbufp->b_resid;
6552 		mutex_exit(ST_MUTEX);
6553 		bcount = (unsigned)bp->b_bcount;
6554 		biodone(bp);
6555 		mutex_enter(ST_MUTEX);
6556 		un->un_laststate = un->un_state;
6557 		un->un_state = ST_STATE_OPEN;
6558 		kmem_free(un->un_tmpbuf, bcount);
6559 		un->un_tmpbuf = NULL;
6560 		return;
6561 	}
6562 
6563 	/*
6564 	 * The append failed. Do a short read. If that fails,  we are at EOM
6565 	 * so we can retry the write command. If that succeeds, than we're
6566 	 * all screwed up (the controller reported a real error).
6567 	 *
6568 	 * XXX: should the dummy read be > SECSIZE? should it be the device's
6569 	 * XXX: block size?
6570 	 *
6571 	 */
6572 	status = un->un_status;
6573 	un->un_status = 0;
6574 	(void) st_cmd(dev, SCMD_READ, SECSIZE, SYNC_CMD);
6575 	if (un->un_status == KEY_BLANK_CHECK) {
6576 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6577 		    "append at EOM\n");
6578 		/*
6579 		 * Okay- the read failed. We should actually have confused
6580 		 * the controller enough to allow writing. In any case, the
6581 		 * i/o is on its own from here on out.
6582 		 */
6583 		un->un_laststate = un->un_state;
6584 		un->un_state = ST_STATE_OPEN;
6585 		bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
6586 		if (st_cmd(dev, (int)SCMD_WRITE, (int)bp->b_bcount,
6587 		    SYNC_CMD) == 0) {
6588 			goto success;
6589 		}
6590 	}
6591 
6592 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6593 	    "append write failed- not at EOM\n");
6594 	bp->b_resid = bp->b_bcount;
6595 	st_bioerror(bp, EIO);
6596 
6597 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6598 	    "st_test_append : EIO : append write failed - not at EOM");
6599 
6600 	/*
6601 	 * backspace one record to get back to where we were
6602 	 */
6603 	if (st_cmd(dev, SCMD_SPACE, Blk(-1), SYNC_CMD)) {
6604 		un->un_pos.pmode = invalid;
6605 	}
6606 
6607 	un->un_err_resid = bp->b_resid;
6608 	un->un_status = status;
6609 
6610 	/*
6611 	 * Note: biodone will do a bp_mapout()
6612 	 */
6613 	mutex_exit(ST_MUTEX);
6614 	bcount = (unsigned)bp->b_bcount;
6615 	biodone(bp);
6616 	mutex_enter(ST_MUTEX);
6617 	un->un_laststate = un->un_state;
6618 	un->un_state = ST_STATE_OPEN_PENDING_IO;
6619 	kmem_free(un->un_tmpbuf, bcount);
6620 	un->un_tmpbuf = NULL;
6621 }
6622 
6623 /*
6624  * Special command handler
6625  */
6626 
6627 /*
6628  * common st_cmd code. The fourth parameter states
6629  * whether the caller wishes to await the results
6630  * Note the release of the mutex during most of the function
6631  */
6632 static int
6633 st_cmd(dev_t dev, int com, int count, int wait)
6634 {
6635 	struct buf *bp;
6636 	int err;
6637 
6638 	GET_SOFT_STATE(dev);
6639 
6640 	ST_FUNC(ST_DEVINFO, st_cmd);
6641 
6642 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6643 	    "st_cmd(dev = 0x%lx, com = 0x%x, count = %x, wait = %d)\n",
6644 	    dev, com, count, wait);
6645 
6646 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
6647 	ASSERT(mutex_owned(ST_MUTEX));
6648 
6649 #ifdef STDEBUG
6650 	if ((st_debug & 0xf)) {
6651 		st_debug_cmds(un, com, count, wait);
6652 	}
6653 #endif
6654 
6655 	/* check to see if this command requires the drive to be reserved */
6656 	err = st_check_cmd_for_need_to_reserve(un, com, count);
6657 
6658 	if (err) {
6659 		return (err);
6660 	}
6661 
6662 	while (un->un_sbuf_busy)
6663 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
6664 	un->un_sbuf_busy = 1;
6665 
6666 	bp = un->un_sbufp;
6667 	bzero(bp, sizeof (buf_t));
6668 
6669 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
6670 
6671 	/*
6672 	 * Set count to the actual size of the data tranfer.
6673 	 * For commands with no data transfer, set bp->b_bcount
6674 	 * to the value to be used when constructing the
6675 	 * cdb in st_make_cmd().
6676 	 */
6677 	switch (com) {
6678 	case SCMD_READ:
6679 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6680 		    "special read %d\n", count);
6681 		bp->b_flags |= B_READ;
6682 		bp->b_un.b_addr = un->un_tmpbuf;
6683 		break;
6684 
6685 	case SCMD_WRITE:
6686 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6687 		    "special write %d\n", count);
6688 		bp->b_un.b_addr = un->un_tmpbuf;
6689 		break;
6690 
6691 	case SCMD_WRITE_FILE_MARK:
6692 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6693 		    "write %d file marks\n", count);
6694 		bp->b_bcount = count;
6695 		count = 0;
6696 		break;
6697 
6698 	case SCMD_REWIND:
6699 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "rewind\n");
6700 		bp->b_bcount = 0;
6701 		count = 0;
6702 		break;
6703 
6704 	case SCMD_SPACE:
6705 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "space\n");
6706 		/*
6707 		 * XXX The user could have entered a number that will
6708 		 * not fit in the 12 bit count field. Whats new here
6709 		 * checking that. Down the road this should use space(16).
6710 		 */
6711 		if ((SPACE_CNT(count) > 0x7fffff) ||
6712 		    (SPACE_CNT(count) < -(0x7fffff))) {
6713 			un->un_sbuf_busy = 0;
6714 			cv_signal(&un->un_sbuf_cv);
6715 			return (EINVAL);
6716 		}
6717 		bp->b_bcount = count;
6718 		count = 0;
6719 		break;
6720 
6721 	case SCMD_RESERVE:
6722 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "reserve");
6723 		bp->b_bcount = 0;
6724 		count = 0;
6725 		break;
6726 
6727 	case SCMD_RELEASE:
6728 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "release");
6729 		bp->b_bcount = 0;
6730 		count = 0;
6731 		break;
6732 
6733 	case SCMD_LOAD:
6734 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6735 		    "%s tape\n", (count & LD_LOAD) ? "load" : "unload");
6736 		bp->b_bcount = count;
6737 		count = 0;
6738 		break;
6739 
6740 	case SCMD_ERASE:
6741 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6742 		    "erase tape\n");
6743 		bp->b_bcount = 0;
6744 		count = 0;
6745 		break;
6746 
6747 	case SCMD_MODE_SENSE:
6748 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6749 		    "mode sense\n");
6750 		bp->b_flags |= B_READ;
6751 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
6752 		break;
6753 
6754 	case SCMD_MODE_SELECT:
6755 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6756 		    "mode select\n");
6757 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
6758 		break;
6759 
6760 	case SCMD_READ_BLKLIM:
6761 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6762 		    "read block limits\n");
6763 		bp->b_flags |= B_READ;
6764 		bp->b_un.b_addr = (caddr_t)(un->un_rbl);
6765 		break;
6766 
6767 	case SCMD_TEST_UNIT_READY:
6768 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6769 		    "test unit ready\n");
6770 		bp->b_bcount = 0;
6771 		count = 0;
6772 		break;
6773 
6774 	case SCMD_DOORLOCK:
6775 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6776 		    "%s tape\n", (count & MR_LOCK) ? "lock" : "unlock");
6777 		bp->b_bcount = count = 0;
6778 		break;
6779 
6780 	case SCMD_READ_POSITION:
6781 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6782 		    "read position\n");
6783 		switch (un->un_read_pos_type) {
6784 		case LONG_POS:
6785 			count = sizeof (tape_position_long_t);
6786 			break;
6787 		case EXT_POS:
6788 			count = min(count, sizeof (tape_position_ext_t));
6789 			break;
6790 		case SHORT_POS:
6791 			count = sizeof (tape_position_t);
6792 			break;
6793 		default:
6794 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
6795 			    "Unknown read position type 0x%x in "
6796 			    "st_make_cmd()\n", un->un_read_pos_type);
6797 		}
6798 		bp->b_bcount = count;
6799 		bp->b_flags |= B_READ;
6800 		bp->b_un.b_addr = (caddr_t)un->un_read_pos_data;
6801 		break;
6802 
6803 	default:
6804 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
6805 		    "Unhandled scsi command 0x%x in st_cmd()\n", com);
6806 	}
6807 
6808 	mutex_exit(ST_MUTEX);
6809 
6810 	if (count > 0) {
6811 		/*
6812 		 * We're going to do actual I/O.
6813 		 * Set things up for physio.
6814 		 */
6815 		struct iovec aiov;
6816 		struct uio auio;
6817 		struct uio *uio = &auio;
6818 
6819 		bzero(&auio, sizeof (struct uio));
6820 		bzero(&aiov, sizeof (struct iovec));
6821 		aiov.iov_base = bp->b_un.b_addr;
6822 		aiov.iov_len = count;
6823 
6824 		uio->uio_iov = &aiov;
6825 		uio->uio_iovcnt = 1;
6826 		uio->uio_resid = aiov.iov_len;
6827 		uio->uio_segflg = UIO_SYSSPACE;
6828 
6829 		/*
6830 		 * Let physio do the rest...
6831 		 */
6832 		bp->b_forw = (struct buf *)(uintptr_t)com;
6833 		bp->b_back = NULL;
6834 		err = physio(st_strategy, bp, dev,
6835 		    (bp->b_flags & B_READ) ? B_READ : B_WRITE,
6836 		    st_minphys, uio);
6837 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6838 		    "st_cmd: physio returns %d\n", err);
6839 	} else {
6840 		/*
6841 		 * Mimic physio
6842 		 */
6843 		bp->b_forw = (struct buf *)(uintptr_t)com;
6844 		bp->b_back = NULL;
6845 		bp->b_edev = dev;
6846 		bp->b_dev = cmpdev(dev);
6847 		bp->b_blkno = 0;
6848 		bp->b_resid = 0;
6849 		(void) st_strategy(bp);
6850 		if (!wait) {
6851 			/*
6852 			 * This is an async command- the caller won't wait
6853 			 * and doesn't care about errors.
6854 			 */
6855 			mutex_enter(ST_MUTEX);
6856 			return (0);
6857 		}
6858 
6859 		/*
6860 		 * BugTraq #4260046
6861 		 * ----------------
6862 		 * Restore Solaris 2.5.1 behavior, namely call biowait
6863 		 * unconditionally. The old comment said...
6864 		 *
6865 		 * "if strategy was flagged with  persistent errors, we would
6866 		 *  have an error here, and the bp would never be sent, so we
6867 		 *  don't want to wait on a bp that was never sent...or hang"
6868 		 *
6869 		 * The new rationale, courtesy of Chitrank...
6870 		 *
6871 		 * "we should unconditionally biowait() here because
6872 		 *  st_strategy() will do a biodone() in the persistent error
6873 		 *  case and the following biowait() will return immediately.
6874 		 *  If not, in the case of "errors after pkt alloc" in
6875 		 *  st_start(), we will not biowait here which will cause the
6876 		 *  next biowait() to return immediately which will cause
6877 		 *  us to send out the next command. In the case where both of
6878 		 *  these use the sbuf, when the first command completes we'll
6879 		 *  free the packet attached to sbuf and the same pkt will
6880 		 *  get freed again when we complete the second command.
6881 		 *  see esc 518987.  BTW, it is necessary to do biodone() in
6882 		 *  st_start() for the pkt alloc failure case because physio()
6883 		 *  does biowait() and will hang if we don't do biodone()"
6884 		 */
6885 
6886 		err = biowait(bp);
6887 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6888 		    "st_cmd: biowait returns %d\n", err);
6889 	}
6890 	mutex_enter(ST_MUTEX);
6891 
6892 	un->un_sbuf_busy = 0;
6893 
6894 	/*
6895 	 * If was a space command need to update logical block position.
6896 	 * If the command failed such that positioning is invalid, Don't
6897 	 * update the position as the user must do this to validate the
6898 	 * position for data protection.
6899 	 */
6900 	if ((com == SCMD_SPACE) && (un->un_pos.pmode != invalid)) {
6901 		uchar_t status = un->un_status;
6902 		(void) st_update_block_pos(un);
6903 		un->un_status = status;
6904 	}
6905 
6906 	cv_signal(&un->un_sbuf_cv);
6907 	return (err);
6908 }
6909 
6910 static int
6911 st_set_compression(struct scsi_tape *un)
6912 {
6913 	int rval;
6914 	int turn_compression_on;
6915 	minor_t minor;
6916 
6917 	ST_FUNC(ST_DEVINFO, st_set_compression);
6918 
6919 	/*
6920 	 * Drive either dosn't have compression or it is controlled with
6921 	 * special density codes. Return ENOTTY so caller
6922 	 * knows nothing was done.
6923 	 */
6924 	if ((un->un_dp->options & ST_MODE_SEL_COMP) == 0) {
6925 		un->un_comp_page = 0;
6926 		return (ENOTTY);
6927 	}
6928 
6929 	/* set compression based on minor node opened */
6930 	minor = MT_DENSITY(un->un_dev);
6931 
6932 	/*
6933 	 * If this the compression density or
6934 	 * the drive has two densities and uses mode select for
6935 	 * control of compression turn on compression for MT_DENSITY2
6936 	 * as well.
6937 	 */
6938 	if ((minor == ST_COMPRESSION_DENSITY) ||
6939 	    (minor == MT_DENSITY(MT_DENSITY2)) &&
6940 	    (un->un_dp->densities[0] == un->un_dp->densities[1]) &&
6941 	    (un->un_dp->densities[2] == un->un_dp->densities[3]) &&
6942 	    (un->un_dp->densities[0] != un->un_dp->densities[2])) {
6943 
6944 		turn_compression_on = 1;
6945 	} else {
6946 		turn_compression_on = 0;
6947 	}
6948 
6949 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
6950 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
6951 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
6952 
6953 	/*
6954 	 * Need to determine which page does the device use for compression.
6955 	 * First try the data compression page. If this fails try the device
6956 	 * configuration page
6957 	 */
6958 
6959 	if ((un->un_comp_page & ST_DEV_DATACOMP_PAGE) == ST_DEV_DATACOMP_PAGE) {
6960 		rval = st_set_datacomp_page(un, turn_compression_on);
6961 		if (rval == EALREADY) {
6962 			return (rval);
6963 		}
6964 		if (rval != 0) {
6965 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
6966 				/*
6967 				 * This device does not support data
6968 				 * compression page
6969 				 */
6970 				un->un_comp_page = ST_DEV_CONFIG_PAGE;
6971 			} else if (un->un_state >= ST_STATE_OPEN) {
6972 				un->un_pos.pmode = invalid;
6973 				rval = EIO;
6974 			} else {
6975 				rval = -1;
6976 			}
6977 		} else {
6978 			un->un_comp_page = ST_DEV_DATACOMP_PAGE;
6979 		}
6980 	}
6981 
6982 	if ((un->un_comp_page & ST_DEV_CONFIG_PAGE) == ST_DEV_CONFIG_PAGE) {
6983 		rval = st_set_devconfig_page(un, turn_compression_on);
6984 		if (rval == EALREADY) {
6985 			return (rval);
6986 		}
6987 		if (rval != 0) {
6988 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
6989 				/*
6990 				 * This device does not support
6991 				 * compression at all advice the
6992 				 * user and unset ST_MODE_SEL_COMP
6993 				 */
6994 				un->un_dp->options &= ~ST_MODE_SEL_COMP;
6995 				un->un_comp_page = 0;
6996 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
6997 				    "Device Does Not Support Compression\n");
6998 			} else if (un->un_state >= ST_STATE_OPEN) {
6999 				un->un_pos.pmode = invalid;
7000 				rval = EIO;
7001 			} else {
7002 				rval = -1;
7003 			}
7004 		}
7005 	}
7006 
7007 	return (rval);
7008 }
7009 
7010 /*
7011  * set or unset compression thru device configuration page.
7012  */
7013 static int
7014 st_set_devconfig_page(struct scsi_tape *un, int compression_on)
7015 {
7016 	unsigned char cflag;
7017 	int rval = 0;
7018 
7019 
7020 	ST_FUNC(ST_DEVINFO, st_set_devconfig_page);
7021 
7022 	ASSERT(mutex_owned(ST_MUTEX));
7023 	/*
7024 	 * Figure what to set compression flag to.
7025 	 */
7026 	if (compression_on) {
7027 		/* They have selected a compression node */
7028 		if (un->un_dp->type == ST_TYPE_FUJI) {
7029 			cflag = 0x84;   /* use EDRC */
7030 		} else {
7031 			cflag = ST_DEV_CONFIG_DEF_COMP;
7032 		}
7033 	} else {
7034 		cflag = ST_DEV_CONFIG_NO_COMP;
7035 	}
7036 
7037 	/*
7038 	 * If compression is already set the way it was requested.
7039 	 * And if this not the first time we has tried.
7040 	 */
7041 	if ((cflag == un->un_mspl->page.dev.comp_alg) &&
7042 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
7043 		return (EALREADY);
7044 	}
7045 
7046 	un->un_mspl->page.dev.comp_alg = cflag;
7047 	/*
7048 	 * need to send mode select even if correct compression is
7049 	 * already set since need to set density code
7050 	 */
7051 
7052 #ifdef STDEBUG
7053 	if ((st_debug & 0xf) >= 6) {
7054 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7055 		    "st_set_devconfig_page: sense data for mode select",
7056 		    (char *)un->un_mspl, sizeof (struct seq_mode));
7057 	}
7058 #endif
7059 	rval = st_gen_mode_select(un, un->un_mspl, sizeof (struct seq_mode));
7060 
7061 	return (rval);
7062 }
7063 
7064 /*
7065  * set/reset compression bit thru data compression page
7066  */
7067 static int
7068 st_set_datacomp_page(struct scsi_tape *un, int compression_on)
7069 {
7070 	int compression_on_already;
7071 	int rval = 0;
7072 
7073 
7074 	ST_FUNC(ST_DEVINFO, st_set_datacomp_page);
7075 
7076 	ASSERT(mutex_owned(ST_MUTEX));
7077 	/*
7078 	 * If drive is not capable of compression (at this time)
7079 	 * return EALREADY so caller doesn't think that this page
7080 	 * is not supported. This check is for drives that can
7081 	 * disable compression from the front panel or configuration.
7082 	 * I doubt that a drive that supports this page is not really
7083 	 * capable of compression.
7084 	 */
7085 	if (un->un_mspl->page.comp.dcc == 0) {
7086 		return (EALREADY);
7087 	}
7088 
7089 	/* See if compression currently turned on */
7090 	if (un->un_mspl->page.comp.dce) {
7091 		compression_on_already = 1;
7092 	} else {
7093 		compression_on_already = 0;
7094 	}
7095 
7096 	/*
7097 	 * If compression is already set the way it was requested.
7098 	 * And if this not the first time we has tried.
7099 	 */
7100 	if ((compression_on == compression_on_already) &&
7101 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
7102 		return (EALREADY);
7103 	}
7104 
7105 	/*
7106 	 * if we are already set to the appropriate compression
7107 	 * mode, don't set it again
7108 	 */
7109 	if (compression_on) {
7110 		/* compression selected */
7111 		un->un_mspl->page.comp.dce = 1;
7112 	} else {
7113 		un->un_mspl->page.comp.dce = 0;
7114 	}
7115 
7116 
7117 #ifdef STDEBUG
7118 	if ((st_debug & 0xf) >= 6) {
7119 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7120 		    "st_set_datacomp_page: sense data for mode select",
7121 		    (char *)un->un_mspl, sizeof (struct seq_mode));
7122 	}
7123 #endif
7124 	rval = st_gen_mode_select(un, un->un_mspl, sizeof (struct seq_mode));
7125 
7126 	return (rval);
7127 }
7128 
7129 static int
7130 st_modesense(struct scsi_tape *un)
7131 {
7132 	int rval;
7133 	uchar_t page;
7134 
7135 	ST_FUNC(ST_DEVINFO, st_modesense);
7136 
7137 	page = un->un_comp_page;
7138 
7139 	switch (page) {
7140 	case ST_DEV_DATACOMP_PAGE:
7141 	case ST_DEV_CONFIG_PAGE: /* fall through */
7142 		rval = st_gen_mode_sense(un, page, un->un_mspl,
7143 		    sizeof (struct seq_mode));
7144 		break;
7145 
7146 	case ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE:
7147 		if (un->un_dp->options & ST_MODE_SEL_COMP) {
7148 			page = ST_DEV_DATACOMP_PAGE;
7149 			rval = st_gen_mode_sense(un, page, un->un_mspl,
7150 			    sizeof (struct seq_mode));
7151 			if (rval == 0 && un->un_mspl->page_code == page) {
7152 				un->un_comp_page = page;
7153 				break;
7154 			}
7155 			page = ST_DEV_CONFIG_PAGE;
7156 			rval = st_gen_mode_sense(un, page, un->un_mspl,
7157 			    sizeof (struct seq_mode));
7158 			if (rval == 0 && un->un_mspl->page_code == page) {
7159 				un->un_comp_page = page;
7160 				break;
7161 			}
7162 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
7163 			un->un_comp_page = 0;
7164 		} else {
7165 			un->un_comp_page = 0;
7166 		}
7167 
7168 	default:	/* fall through */
7169 		rval = st_cmd(un->un_dev, SCMD_MODE_SENSE, MSIZE, SYNC_CMD);
7170 	}
7171 	return (rval);
7172 }
7173 
7174 static int
7175 st_modeselect(struct scsi_tape *un)
7176 {
7177 	int rval = 0;
7178 	int ix;
7179 
7180 	ST_FUNC(ST_DEVINFO, st_modeselect);
7181 
7182 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7183 	    "st_modeselect(dev = 0x%lx): density = 0x%x\n",
7184 	    un->un_dev, un->un_mspl->density);
7185 
7186 	ASSERT(mutex_owned(ST_MUTEX));
7187 
7188 	/*
7189 	 * The parameter list should be the same for all of the
7190 	 * cases that follow so set them here
7191 	 *
7192 	 * Try mode select first if if fails set fields manually
7193 	 */
7194 	rval = st_modesense(un);
7195 	if (rval != 0) {
7196 		ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
7197 		    "st_modeselect: First mode sense failed\n");
7198 		un->un_mspl->bd_len  = 8;
7199 		un->un_mspl->high_nb = 0;
7200 		un->un_mspl->mid_nb  = 0;
7201 		un->un_mspl->low_nb  = 0;
7202 	}
7203 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
7204 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
7205 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
7206 
7207 
7208 	/*
7209 	 * If configured to use a specific density code for a media type.
7210 	 * curdens is previously set by the minor node opened.
7211 	 * If the media type doesn't match the minor node we change it so it
7212 	 * looks like the correct one was opened.
7213 	 */
7214 	if (un->un_dp->options & ST_KNOWS_MEDIA) {
7215 		uchar_t best;
7216 
7217 		for (best = 0xff, ix = 0; ix < NDENSITIES; ix++) {
7218 			if (un->un_mspl->media_type ==
7219 			    un->un_dp->mediatype[ix]) {
7220 				best = ix;
7221 				/*
7222 				 * It matches but it might not be the only one.
7223 				 * Use the highest matching media type but not
7224 				 * to exceed the density selected by the open.
7225 				 */
7226 				if (ix < un->un_curdens) {
7227 					continue;
7228 				}
7229 				un->un_curdens = ix;
7230 				break;
7231 			}
7232 		}
7233 		/* If a match was found best will not be 0xff any more */
7234 		if (best < NDENSITIES) {
7235 			ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
7236 			    "found media 0x%X using density 0x%X\n",
7237 			    un->un_mspl->media_type,
7238 			    un->un_dp->densities[best]);
7239 			un->un_mspl->density = un->un_dp->densities[best];
7240 		} else {
7241 			/* Otherwise set density based on minor node opened */
7242 			un->un_mspl->density =
7243 			    un->un_dp->densities[un->un_curdens];
7244 		}
7245 	} else {
7246 		un->un_mspl->density = un->un_dp->densities[un->un_curdens];
7247 	}
7248 
7249 	if (un->un_dp->options & ST_NOBUF) {
7250 		un->un_mspl->bufm = 0;
7251 	} else {
7252 		un->un_mspl->bufm = 1;
7253 	}
7254 
7255 	rval = st_set_compression(un);
7256 
7257 	/*
7258 	 * If st_set_compression returned invalid or already it
7259 	 * found no need to do the mode select.
7260 	 * So do it here.
7261 	 */
7262 	if ((rval == ENOTTY) || (rval == EALREADY)) {
7263 
7264 		/* Zero non-writeable fields */
7265 		un->un_mspl->data_len = 0;
7266 		un->un_mspl->media_type = 0;
7267 		un->un_mspl->wp = 0;
7268 
7269 		/* need to set the density code */
7270 		rval = st_cmd(un->un_dev, SCMD_MODE_SELECT, MSIZE, SYNC_CMD);
7271 		if (rval != 0) {
7272 			if (un->un_state >= ST_STATE_OPEN) {
7273 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
7274 				    "unable to set tape mode\n");
7275 				un->un_pos.pmode = invalid;
7276 				rval = EIO;
7277 			} else {
7278 				rval = -1;
7279 			}
7280 		}
7281 	}
7282 
7283 	/*
7284 	 * The spec recommends to send a mode sense after a mode select
7285 	 */
7286 	(void) st_modesense(un);
7287 
7288 	ASSERT(mutex_owned(ST_MUTEX));
7289 
7290 	return (rval);
7291 }
7292 
7293 /*
7294  * st_gen_mode_sense
7295  *
7296  * generic mode sense.. it allows for any page
7297  */
7298 static int
7299 st_gen_mode_sense(struct scsi_tape *un, int page, struct seq_mode *page_data,
7300     int page_size)
7301 {
7302 
7303 	int r;
7304 	char	cdb[CDB_GROUP0];
7305 	struct uscsi_cmd *com;
7306 
7307 	ST_FUNC(ST_DEVINFO, st_gen_mode_sense);
7308 
7309 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
7310 
7311 	bzero(cdb, CDB_GROUP0);
7312 	cdb[0] = SCMD_MODE_SENSE;
7313 	cdb[2] = (char)page;
7314 	cdb[4] = (char)page_size;
7315 
7316 	com->uscsi_cdb = cdb;
7317 	com->uscsi_cdblen = CDB_GROUP0;
7318 	com->uscsi_bufaddr = (caddr_t)page_data;
7319 	com->uscsi_buflen = page_size;
7320 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
7321 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
7322 
7323 	r = st_ioctl_cmd(un->un_dev, com, FKIOCTL);
7324 	kmem_free(com, sizeof (*com));
7325 	return (r);
7326 }
7327 
7328 /*
7329  * st_gen_mode_select
7330  *
7331  * generic mode select.. it allows for any page
7332  */
7333 static int
7334 st_gen_mode_select(struct scsi_tape *un, struct seq_mode *page_data,
7335     int page_size)
7336 {
7337 
7338 	int r;
7339 	char cdb[CDB_GROUP0];
7340 	struct uscsi_cmd *com;
7341 
7342 	ST_FUNC(ST_DEVINFO, st_gen_mode_select);
7343 
7344 	/* Zero non-writeable fields */
7345 	page_data->data_len = 0;
7346 	page_data->media_type = 0;
7347 	page_data->wp = 0;
7348 
7349 	/*
7350 	 * If mode select has any page data, zero the ps (Page Savable) bit.
7351 	 */
7352 	if (page_size > MSIZE) {
7353 		page_data->ps = 0;
7354 	}
7355 
7356 
7357 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
7358 
7359 	/*
7360 	 * then, do a mode select to set what ever info
7361 	 */
7362 	bzero(cdb, CDB_GROUP0);
7363 	cdb[0] = SCMD_MODE_SELECT;
7364 	cdb[1] = 0x10;		/* set PF bit for many third party drives */
7365 	cdb[4] = (char)page_size;
7366 
7367 	com->uscsi_cdb = cdb;
7368 	com->uscsi_cdblen = CDB_GROUP0;
7369 	com->uscsi_bufaddr = (caddr_t)page_data;
7370 	com->uscsi_buflen = page_size;
7371 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
7372 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_WRITE;
7373 
7374 	r = st_ioctl_cmd(un->un_dev, com, FKIOCTL);
7375 
7376 	kmem_free(com, sizeof (*com));
7377 	return (r);
7378 }
7379 
7380 /*
7381  * Changes devices blocksize and bsize to requested blocksize nblksz.
7382  * Returns returned value from first failed call or zero on success.
7383  */
7384 static int
7385 st_change_block_size(dev_t dev, uint32_t nblksz)
7386 {
7387 	struct seq_mode *current;
7388 	int rval;
7389 	uint32_t oldblksz;
7390 
7391 	GET_SOFT_STATE(dev);
7392 
7393 	ST_FUNC(ST_DEVINFO, st_change_block_size);
7394 
7395 	current = kmem_zalloc(MSIZE, KM_SLEEP);
7396 
7397 	/* Read current settings */
7398 	rval = st_gen_mode_sense(un, 0, current, MSIZE);
7399 	if (rval != 0) {
7400 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
7401 		    "mode sense for change block size failed: rval = %d", rval);
7402 		goto finish;
7403 	}
7404 
7405 	/* Figure the current block size */
7406 	oldblksz =
7407 	    (current->high_bl << 16) |
7408 	    (current->mid_bl << 8) |
7409 	    (current->low_bl);
7410 
7411 	/* If current block size is the same as requested were done */
7412 	if (oldblksz == nblksz) {
7413 		un->un_bsize = nblksz;
7414 		rval = 0;
7415 		goto finish;
7416 	}
7417 
7418 	/* Change to requested block size */
7419 	current->high_bl = (uchar_t)(nblksz >> 16);
7420 	current->mid_bl  = (uchar_t)(nblksz >> 8);
7421 	current->low_bl  = (uchar_t)(nblksz);
7422 
7423 	/* Attempt to change block size */
7424 	rval = st_gen_mode_select(un, current, MSIZE);
7425 	if (rval != 0) {
7426 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
7427 		    "Set new block size failed: rval = %d", rval);
7428 		goto finish;
7429 	}
7430 
7431 	/* Read back and verify setting */
7432 	rval = st_modesense(un);
7433 	if (rval == 0) {
7434 		un->un_bsize =
7435 		    (un->un_mspl->high_bl << 16) |
7436 		    (un->un_mspl->mid_bl << 8) |
7437 		    (un->un_mspl->low_bl);
7438 
7439 		if (un->un_bsize != nblksz) {
7440 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
7441 			    "Blocksize set does not equal requested blocksize"
7442 			    "(read: %u requested: %u)\n", nblksz, un->un_bsize);
7443 			rval = EIO;
7444 		}
7445 	}
7446 finish:
7447 	kmem_free(current, MSIZE);
7448 	return (rval);
7449 }
7450 
7451 
7452 static void
7453 st_init(struct scsi_tape *un)
7454 {
7455 	ST_FUNC(ST_DEVINFO, st_init);
7456 
7457 	ASSERT(mutex_owned(ST_MUTEX));
7458 
7459 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7460 	    "st_init(): dev = 0x%lx, will reset fileno, blkno, eof\n",
7461 	    un->un_dev);
7462 
7463 	un->un_pos.blkno = 0;
7464 	un->un_pos.fileno = 0;
7465 	un->un_lastop = ST_OP_NIL;
7466 	un->un_pos.eof = ST_NO_EOF;
7467 	un->un_pwr_mgmt = ST_PWR_NORMAL;
7468 	if (st_error_level != SCSI_ERR_ALL) {
7469 		if (DEBUGGING) {
7470 			st_error_level = SCSI_ERR_ALL;
7471 		} else {
7472 			st_error_level = SCSI_ERR_RETRYABLE;
7473 		}
7474 	}
7475 }
7476 
7477 
7478 static void
7479 st_make_cmd(struct scsi_tape *un, struct buf *bp, int (*func)(caddr_t))
7480 {
7481 	struct scsi_pkt *pkt;
7482 	struct uscsi_cmd *ucmd;
7483 	int count, tval = 0;
7484 	uint_t addr = 0;
7485 	int flags = 0;
7486 	int cdb_len = CDB_GROUP0; /* default */
7487 	uchar_t com;
7488 	char fixbit;
7489 
7490 	ST_FUNC(ST_DEVINFO, st_make_cmd);
7491 
7492 	ASSERT(mutex_owned(ST_MUTEX));
7493 
7494 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7495 	    "st_make_cmd(): dev = 0x%lx\n", un->un_dev);
7496 
7497 
7498 	/*
7499 	 * fixbit is for setting the Fixed Mode and Suppress Incorrect
7500 	 * Length Indicator bits on read/write commands, for setting
7501 	 * the Long bit on erase commands, and for setting the Code
7502 	 * Field bits on space commands.
7503 	 * XXX why do we set lastop here?
7504 	 */
7505 
7506 	if (bp != un->un_sbufp) {		/* regular raw I/O */
7507 		int stat_size = (un->un_arq_enabled ?
7508 		    sizeof (struct scsi_arq_status) : 1);
7509 		pkt = scsi_init_pkt(ROUTE, NULL, bp,
7510 		    CDB_GROUP0, stat_size, 0, 0, func, (caddr_t)un);
7511 		if (pkt == NULL) {
7512 			goto exit;
7513 		}
7514 		SET_BP_PKT(bp, pkt);
7515 		if (un->un_bsize == 0) {
7516 			count = bp->b_bcount;
7517 			fixbit = 0;
7518 		} else {
7519 			count = bp->b_bcount / un->un_bsize;
7520 			fixbit = 1;
7521 		}
7522 		if (bp->b_flags & B_READ) {
7523 			com = SCMD_READ;
7524 			un->un_lastop = ST_OP_READ;
7525 			if ((un->un_bsize == 0) && /* Not Fixed Block */
7526 			    (un->un_dp->options & ST_READ_IGNORE_ILI)) {
7527 				fixbit = 2;
7528 			}
7529 		} else {
7530 			com = SCMD_WRITE;
7531 			un->un_lastop = ST_OP_WRITE;
7532 		}
7533 
7534 		tval = un->un_dp->io_timeout;
7535 
7536 		/*
7537 		 * For really large xfers, increase timeout
7538 		 */
7539 		if (bp->b_bcount > (10 * ONE_MEG))
7540 			tval *= bp->b_bcount/(10 * ONE_MEG);
7541 
7542 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7543 		    "%s %d amt 0x%lx\n", (com == SCMD_WRITE) ?
7544 		    wr_str: rd_str, un->un_pos.blkno, bp->b_bcount);
7545 
7546 	} else if ((ucmd = BP_UCMD(bp)) != NULL) {
7547 		/*
7548 		 * uscsi - build command, allocate scsi resources
7549 		 */
7550 		st_make_uscsi_cmd(un, ucmd, bp, func);
7551 		goto exit;
7552 
7553 	} else {				/* special I/O */
7554 		int stat_size = (un->un_arq_enabled ?
7555 		    sizeof (struct scsi_arq_status) : 1);
7556 		struct buf *allocbp = NULL;
7557 		com = (uchar_t)(uintptr_t)bp->b_forw;
7558 		count = bp->b_bcount;
7559 
7560 		switch (com) {
7561 		case SCMD_READ:
7562 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7563 			    "special read %d\n", count);
7564 			if (un->un_bsize == 0) {
7565 				fixbit = 2;	/* suppress SILI */
7566 			} else {
7567 				fixbit = 1;	/* Fixed Block Mode */
7568 				count /= un->un_bsize;
7569 			}
7570 			allocbp = bp;
7571 			un->un_lastop = ST_OP_READ;
7572 			tval = un->un_dp->io_timeout;
7573 			break;
7574 
7575 		case SCMD_WRITE:
7576 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7577 			    "special write %d\n", count);
7578 			if (un->un_bsize != 0) {
7579 				fixbit = 1;	/* Fixed Block Mode */
7580 				count /= un->un_bsize;
7581 			} else {
7582 				fixbit = 0;
7583 			}
7584 			allocbp = bp;
7585 			un->un_lastop = ST_OP_WRITE;
7586 			tval = un->un_dp->io_timeout;
7587 			break;
7588 
7589 		case SCMD_WRITE_FILE_MARK:
7590 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7591 			    "write %d file marks\n", count);
7592 			un->un_lastop = ST_OP_WEOF;
7593 			fixbit = 0;
7594 			tval = un->un_dp->io_timeout;
7595 			break;
7596 
7597 		case SCMD_REWIND:
7598 			if (bp->b_flags & B_ASYNC) {
7599 				fixbit = 1;
7600 			} else {
7601 				fixbit = 0;
7602 			}
7603 			count = 0;
7604 			un->un_lastop = ST_OP_CTL;
7605 			tval = un->un_dp->rewind_timeout;
7606 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7607 			    "rewind\n");
7608 			break;
7609 
7610 		case SCMD_SPACE:
7611 			fixbit = SPACE_TYPE(count);
7612 			count = (int)SPACE_CNT(count);
7613 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7614 			    "space %s %d from file %d blk %d\n",
7615 			    space_strs[fixbit & 7], count,
7616 			    un->un_pos.fileno, un->un_pos.blkno);
7617 			un->un_lastop = ST_OP_CTL;
7618 			tval = un->un_dp->space_timeout;
7619 			break;
7620 
7621 		case SCMD_LOAD:
7622 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7623 			    "%s tape\n", (count & LD_LOAD) ? "load" : "unload");
7624 			fixbit = 0;
7625 
7626 			/* Loading or Unloading */
7627 			if (count & LD_LOAD) {
7628 				tval = un->un_dp->load_timeout;
7629 			} else {
7630 				tval = un->un_dp->unload_timeout;
7631 			}
7632 			/* Is Retension requested */
7633 			if (count & LD_RETEN) {
7634 				tval += un->un_dp->rewind_timeout;
7635 			}
7636 			un->un_lastop = ST_OP_CTL;
7637 			break;
7638 
7639 		case SCMD_ERASE:
7640 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7641 			    "erase tape\n");
7642 			count = 0;
7643 			/*
7644 			 * We support long erase only
7645 			 */
7646 			fixbit = 1;
7647 			tval = un->un_dp->erase_timeout;
7648 			un->un_lastop = ST_OP_CTL;
7649 			break;
7650 
7651 		case SCMD_MODE_SENSE:
7652 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7653 			    "mode sense\n");
7654 			allocbp = bp;
7655 			fixbit = 0;
7656 			tval = un->un_dp->non_motion_timeout;
7657 			un->un_lastop = ST_OP_CTL;
7658 			break;
7659 
7660 		case SCMD_MODE_SELECT:
7661 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7662 			    "mode select\n");
7663 			allocbp = bp;
7664 			fixbit = 0;
7665 			tval = un->un_dp->non_motion_timeout;
7666 			un->un_lastop = ST_OP_CTL;
7667 			break;
7668 
7669 		case SCMD_RESERVE:
7670 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7671 			    "reserve\n");
7672 			fixbit = 0;
7673 			tval = un->un_dp->non_motion_timeout;
7674 			un->un_lastop = ST_OP_CTL;
7675 			break;
7676 
7677 		case SCMD_RELEASE:
7678 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7679 			    "release\n");
7680 			fixbit = 0;
7681 			tval = un->un_dp->non_motion_timeout;
7682 			un->un_lastop = ST_OP_CTL;
7683 			break;
7684 
7685 		case SCMD_READ_BLKLIM:
7686 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7687 			    "read block limits\n");
7688 			allocbp = bp;
7689 			fixbit = count = 0;
7690 			tval = un->un_dp->non_motion_timeout;
7691 			un->un_lastop = ST_OP_CTL;
7692 			break;
7693 
7694 		case SCMD_TEST_UNIT_READY:
7695 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7696 			    "test unit ready\n");
7697 			fixbit = 0;
7698 			tval = un->un_dp->non_motion_timeout;
7699 			un->un_lastop = ST_OP_CTL;
7700 			break;
7701 
7702 		case SCMD_DOORLOCK:
7703 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7704 			    "prevent/allow media removal\n");
7705 			fixbit = 0;
7706 			tval = un->un_dp->non_motion_timeout;
7707 			un->un_lastop = ST_OP_CTL;
7708 			break;
7709 
7710 		case SCMD_READ_POSITION:
7711 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7712 			    "read position\n");
7713 			fixbit = un->un_read_pos_type;
7714 			cdb_len = CDB_GROUP1;
7715 			tval = un->un_dp->non_motion_timeout;
7716 			allocbp = bp;
7717 			un->un_lastop = ST_OP_CTL;
7718 			switch (un->un_read_pos_type) {
7719 			case LONG_POS:
7720 				count = 0;
7721 				break;
7722 			case EXT_POS:
7723 				count = sizeof (tape_position_ext_t);
7724 				break;
7725 			case SHORT_POS:
7726 				count = 0;
7727 				break;
7728 			default:
7729 				ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7730 				    "Unknown read position type 0x%x in "
7731 				    " st_make_cmd()\n", un->un_read_pos_type);
7732 			}
7733 			break;
7734 
7735 		default:
7736 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7737 			    "Unhandled scsi command 0x%x in st_make_cmd()\n",
7738 			    com);
7739 		}
7740 		pkt = scsi_init_pkt(ROUTE, NULL, allocbp, cdb_len, stat_size,
7741 		    0, 0, func, (caddr_t)un);
7742 		if (pkt == NULL) {
7743 			goto exit;
7744 		}
7745 		if (allocbp) {
7746 			ASSERT(geterror(allocbp) == 0);
7747 		}
7748 
7749 	}
7750 
7751 
7752 	(void) scsi_setup_cdb((union scsi_cdb *)pkt->pkt_cdbp,
7753 	    com, addr, (uint_t)count, 0);
7754 	FILL_SCSI1_LUN(un->un_sd, pkt);
7755 	/*
7756 	 * Initialize the SILI/Fixed bits of the byte 1 of cdb.
7757 	 */
7758 	((union scsi_cdb *)(pkt->pkt_cdbp))->t_code = fixbit;
7759 	pkt->pkt_flags = flags;
7760 
7761 #ifdef STDEBUG
7762 	if ((st_debug & 0xf) >= 6) {
7763 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7764 		    "cmd cdb", (char *)pkt->pkt_cdbp, cdb_len);
7765 	}
7766 #endif
7767 
7768 	/*
7769 	 * If ST_SHORT_FILEMARKS bit is ON for EXABYTE
7770 	 * device, set the Vendor Unique bit to
7771 	 * write Short File Mark.
7772 	 */
7773 	if (com == SCMD_WRITE_FILE_MARK &&
7774 	    un->un_dp->options & ST_SHORT_FILEMARKS) {
7775 		switch (un->un_dp->type) {
7776 		case ST_TYPE_EXB8500:
7777 		case ST_TYPE_EXABYTE:
7778 			/*
7779 			 * Now the Vendor Unique bit 7 in Byte 5 of CDB
7780 			 * is set to to write Short File Mark
7781 			 */
7782 			((union scsi_cdb *)pkt->pkt_cdbp)->g0_vu_1 = 1;
7783 			break;
7784 
7785 		default:
7786 			/*
7787 			 * Well, if ST_SHORT_FILEMARKS is set for other
7788 			 * tape drives, it is just ignored
7789 			 */
7790 			break;
7791 		}
7792 	}
7793 	ASSERT(tval);
7794 	pkt->pkt_time = tval;
7795 	pkt->pkt_comp = st_intr;
7796 	pkt->pkt_private = (opaque_t)bp;
7797 
7798 	SET_BP_PKT(bp, pkt);
7799 
7800 exit:
7801 	ASSERT(mutex_owned(ST_MUTEX));
7802 }
7803 
7804 
7805 /*
7806  * Build a command based on a uscsi command;
7807  */
7808 static void
7809 st_make_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
7810     struct buf *bp, int (*func)(caddr_t))
7811 {
7812 	struct scsi_pkt *pkt;
7813 	caddr_t cdb;
7814 	int	cdblen;
7815 	int stat_size;
7816 
7817 	ST_FUNC(ST_DEVINFO, st_make_uscsi_cmd);
7818 
7819 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7820 	    "st_make_uscsi_cmd(): dev = 0x%lx\n", un->un_dev);
7821 
7822 	if (ucmd->uscsi_flags & USCSI_RQENABLE) {
7823 		stat_size = (un->un_arq_enabled ?
7824 		    sizeof (struct scsi_arq_status) : 1);
7825 	} else {
7826 		stat_size = 1;
7827 	}
7828 
7829 	ASSERT(mutex_owned(ST_MUTEX));
7830 
7831 	cdb = ucmd->uscsi_cdb;
7832 	cdblen = ucmd->uscsi_cdblen;
7833 
7834 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7835 	    "st_make_uscsi_cmd: buflen=%ld bcount=%ld\n",
7836 	    ucmd->uscsi_buflen, bp->b_bcount);
7837 	pkt = scsi_init_pkt(ROUTE, NULL,
7838 	    (bp->b_bcount > 0) ? bp : NULL,
7839 	    cdblen, stat_size, 0, 0, func, (caddr_t)un);
7840 	if (pkt == NULL) {
7841 		goto exit;
7842 	}
7843 
7844 	bcopy(cdb, pkt->pkt_cdbp, (uint_t)cdblen);
7845 
7846 #ifdef STDEBUG
7847 	if ((st_debug & 0xf) >= 6) {
7848 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7849 		    "pkt_cdbp", (char *)cdb, cdblen);
7850 	}
7851 #endif
7852 
7853 	if (ucmd->uscsi_flags & USCSI_SILENT) {
7854 		pkt->pkt_flags |= FLAG_SILENT;
7855 	}
7856 
7857 	pkt->pkt_time = ucmd->uscsi_timeout;
7858 	pkt->pkt_comp = st_intr;
7859 	pkt->pkt_private = (opaque_t)bp;
7860 
7861 	SET_BP_PKT(bp, pkt);
7862 exit:
7863 	ASSERT(mutex_owned(ST_MUTEX));
7864 }
7865 
7866 
7867 /*
7868  * restart cmd currently at the head of the runq
7869  *
7870  * If scsi_transport() succeeds or the retries
7871  * count exhausted, restore the throttle that was
7872  * zeroed out in st_handle_intr_busy().
7873  *
7874  */
7875 static void
7876 st_intr_restart(void *arg)
7877 {
7878 	struct scsi_tape *un = arg;
7879 	struct buf *bp;
7880 	int status = TRAN_ACCEPT;
7881 
7882 	mutex_enter(ST_MUTEX);
7883 
7884 	ST_FUNC(ST_DEVINFO, st_intr_restart);
7885 
7886 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7887 	    "st_intr_restart(), un = 0x%p\n", (void *)un);
7888 
7889 	un->un_hib_tid = 0;
7890 
7891 	/*
7892 	 * move from waitq to runq, if there is anything on the waitq
7893 	 */
7894 	if ((bp = un->un_quef) == NULL) {
7895 		mutex_exit(ST_MUTEX);
7896 		return;
7897 	}
7898 
7899 	/*
7900 	 * Here we know :
7901 	 *	throttle = 0, via st_handle_intr_busy
7902 	 */
7903 
7904 	if (un->un_quel == bp) {
7905 		un->un_quel = NULL;
7906 		un->un_quef = NULL;	/* we know it's the first one */
7907 	} else {
7908 		un->un_quef = bp->b_actf;
7909 	}
7910 	bp->b_actf = NULL;
7911 
7912 	if (un->un_runqf) {
7913 		/*
7914 		 * not good, we don't want to requeue something after
7915 		 * another.
7916 		 */
7917 		mutex_exit(ST_MUTEX);
7918 		goto done_error;
7919 	} else {
7920 		un->un_runqf = bp;
7921 		un->un_runql = bp;
7922 	}
7923 
7924 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
7925 
7926 	mutex_exit(ST_MUTEX);
7927 
7928 	status = scsi_transport(BP_PKT(bp));
7929 
7930 	mutex_enter(ST_MUTEX);
7931 
7932 	if (status != TRAN_ACCEPT) {
7933 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
7934 		mutex_exit(ST_MUTEX);
7935 
7936 		if (status == TRAN_BUSY) {
7937 			if (st_handle_intr_busy(un, bp,
7938 			    ST_TRAN_BUSY_TIMEOUT) == 0)
7939 				return;	/* timeout is setup again */
7940 		}
7941 
7942 	} else {
7943 		un->un_tran_retry_ct = 0;
7944 		if (un->un_last_throttle) {
7945 			un->un_throttle = un->un_last_throttle;
7946 		}
7947 		mutex_exit(ST_MUTEX);
7948 		return;
7949 	}
7950 
7951 done_error:
7952 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
7953 	    "restart transport rejected\n");
7954 	bp->b_resid = bp->b_bcount;
7955 
7956 #ifndef __lock_lint
7957 	/*
7958 	 * warlock doesn't understand this potential
7959 	 * recursion?
7960 	 */
7961 	mutex_enter(ST_MUTEX);
7962 	if (un->un_last_throttle) {
7963 		un->un_throttle = un->un_last_throttle;
7964 	}
7965 	if (status != TRAN_ACCEPT)
7966 		ST_DO_ERRSTATS(un, st_transerrs);
7967 	ST_DO_KSTATS(bp, kstat_waitq_exit);
7968 	SET_PE_FLAG(un);
7969 	st_bioerror(bp, EIO);
7970 	st_done_and_mutex_exit(un, bp);
7971 #endif
7972 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
7973 	    "busy restart aborted\n");
7974 }
7975 
7976 /*
7977  * st_check_media():
7978  * Periodically check the media state using scsi_watch service;
7979  * this service calls back after TUR and possibly request sense
7980  * the callback handler (st_media_watch_cb()) decodes the request sense
7981  * data (if any)
7982  */
7983 
7984 static int
7985 st_check_media(dev_t dev, enum mtio_state state)
7986 {
7987 	int rval = 0;
7988 	enum mtio_state	prev_state;
7989 	opaque_t token = NULL;
7990 
7991 	GET_SOFT_STATE(dev);
7992 
7993 	ST_FUNC(ST_DEVINFO, st_check_media);
7994 
7995 	mutex_enter(ST_MUTEX);
7996 
7997 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
7998 	    "st_check_media:state=%x, mediastate=%x\n",
7999 	    state, un->un_mediastate);
8000 
8001 	prev_state = un->un_mediastate;
8002 
8003 	/*
8004 	 * is there anything to do?
8005 	 */
8006 retry:
8007 	if (state == un->un_mediastate || un->un_mediastate == MTIO_NONE) {
8008 		/*
8009 		 * submit the request to the scsi_watch service;
8010 		 * scsi_media_watch_cb() does the real work
8011 		 */
8012 		mutex_exit(ST_MUTEX);
8013 		token = scsi_watch_request_submit(ST_SCSI_DEVP,
8014 		    st_check_media_time, SENSE_LENGTH,
8015 		    st_media_watch_cb, (caddr_t)dev);
8016 		if (token == NULL) {
8017 			rval = EAGAIN;
8018 			goto done;
8019 		}
8020 		mutex_enter(ST_MUTEX);
8021 
8022 		un->un_swr_token = token;
8023 		un->un_specified_mediastate = state;
8024 
8025 		/*
8026 		 * now wait for media change
8027 		 * we will not be signalled unless mediastate == state but it
8028 		 * still better to test for this condition, since there
8029 		 * is a 5 sec cv_broadcast delay when
8030 		 *  mediastate == MTIO_INSERTED
8031 		 */
8032 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8033 		    "st_check_media:waiting for media state change\n");
8034 		while (un->un_mediastate == state) {
8035 			if (cv_wait_sig(&un->un_state_cv, ST_MUTEX) == 0) {
8036 				mutex_exit(ST_MUTEX);
8037 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8038 				    "st_check_media:waiting for media state "
8039 				    "was interrupted\n");
8040 				rval = EINTR;
8041 				goto done;
8042 			}
8043 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8044 			    "st_check_media:received signal, state=%x\n",
8045 			    un->un_mediastate);
8046 		}
8047 	}
8048 
8049 	/*
8050 	 * if we transitioned to MTIO_INSERTED, media has really been
8051 	 * inserted.  If TUR fails, it is probably a exabyte slow spin up.
8052 	 * Reset and retry the state change.  If everything is ok, replay
8053 	 * the open() logic.
8054 	 */
8055 	if ((un->un_mediastate == MTIO_INSERTED) &&
8056 	    (un->un_state == ST_STATE_OFFLINE)) {
8057 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8058 		    "st_check_media: calling st_cmd to confirm inserted\n");
8059 
8060 		/*
8061 		 * set this early so that TUR will make it through strategy
8062 		 * without triggering a st_tape_init().  We needed it set
8063 		 * before calling st_tape_init() ourselves anyway.  If TUR
8064 		 * fails, set it back
8065 		 */
8066 		un->un_state = ST_STATE_INITIALIZING;
8067 
8068 		/*
8069 		 * If not reserved fail as getting reservation conflict
8070 		 * will make this hang forever.
8071 		 */
8072 		if ((un->un_rsvd_status &
8073 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
8074 			mutex_exit(ST_MUTEX);
8075 			rval = EACCES;
8076 			goto done;
8077 		}
8078 		rval = st_cmd(dev, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
8079 		if (rval == EACCES) {
8080 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8081 			    "st_check_media: TUR got Reservation Conflict\n");
8082 			mutex_exit(ST_MUTEX);
8083 			goto done;
8084 		}
8085 		if (rval) {
8086 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8087 			    "st_check_media: TUR failed, going to retry\n");
8088 			un->un_mediastate = prev_state;
8089 			un->un_state = ST_STATE_OFFLINE;
8090 			goto retry;
8091 		}
8092 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8093 		    "st_check_media: media inserted\n");
8094 
8095 		/* this also rewinds the tape */
8096 		rval = st_tape_init(dev);
8097 		if (rval != 0) {
8098 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8099 			    "st_check_media : OFFLINE init failure ");
8100 			un->un_state = ST_STATE_OFFLINE;
8101 			un->un_pos.pmode = invalid;
8102 		} else {
8103 			un->un_state = ST_STATE_OPEN_PENDING_IO;
8104 			un->un_pos.fileno = 0;
8105 			un->un_pos.blkno = 0;
8106 			un->un_pos.lgclblkno = 0;
8107 		}
8108 	} else if ((un->un_mediastate == MTIO_EJECTED) &&
8109 	    (un->un_state != ST_STATE_OFFLINE)) {
8110 		/*
8111 		 * supported devices must be rewound before ejection
8112 		 * rewind resets fileno & blkno
8113 		 */
8114 		un->un_laststate = un->un_state;
8115 		un->un_state = ST_STATE_OFFLINE;
8116 	}
8117 	mutex_exit(ST_MUTEX);
8118 done:
8119 	if (token) {
8120 		(void) scsi_watch_request_terminate(token,
8121 		    SCSI_WATCH_TERMINATE_WAIT);
8122 		mutex_enter(ST_MUTEX);
8123 		un->un_swr_token = (opaque_t)NULL;
8124 		mutex_exit(ST_MUTEX);
8125 	}
8126 
8127 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_media: done\n");
8128 
8129 	return (rval);
8130 }
8131 
8132 /*
8133  * st_media_watch_cb() is called by scsi_watch_thread for
8134  * verifying the request sense data (if any)
8135  */
8136 static int
8137 st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
8138 {
8139 	struct scsi_status *statusp = resultp->statusp;
8140 	struct scsi_extended_sense *sensep = resultp->sensep;
8141 	uchar_t actual_sense_length = resultp->actual_sense_length;
8142 	struct scsi_tape *un;
8143 	enum mtio_state state = MTIO_NONE;
8144 	int instance;
8145 	dev_t dev = (dev_t)arg;
8146 
8147 	instance = MTUNIT(dev);
8148 	if ((un = ddi_get_soft_state(st_state, instance)) == NULL) {
8149 		return (-1);
8150 	}
8151 
8152 	mutex_enter(ST_MUTEX);
8153 	ST_FUNC(ST_DEVINFO, st_media_watch_cb);
8154 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8155 	    "st_media_watch_cb: status=%x, sensep=%p, len=%x\n",
8156 	    *((char *)statusp), (void *)sensep,
8157 	    actual_sense_length);
8158 
8159 
8160 	/*
8161 	 * if there was a check condition then sensep points to valid
8162 	 * sense data
8163 	 * if status was not a check condition but a reservation or busy
8164 	 * status then the new state is MTIO_NONE
8165 	 */
8166 	if (sensep) {
8167 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8168 		    "st_media_watch_cb: KEY=%x, ASC=%x, ASCQ=%x\n",
8169 		    sensep->es_key, sensep->es_add_code, sensep->es_qual_code);
8170 
8171 		switch (un->un_dp->type) {
8172 		default:
8173 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8174 			    "st_media_watch_cb: unknown drive type %d, "
8175 			    "default to ST_TYPE_HP\n", un->un_dp->type);
8176 		/* FALLTHROUGH */
8177 
8178 		case ST_TYPE_STC3490:	/* STK 4220 1/2" cartridge */
8179 		case ST_TYPE_FUJI:	/* 1/2" cartridge */
8180 		case ST_TYPE_HP:	/* HP 88780 1/2" reel */
8181 			if (un->un_dp->type == ST_TYPE_FUJI) {
8182 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8183 				    "st_media_watch_cb: ST_TYPE_FUJI\n");
8184 			} else {
8185 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8186 				    "st_media_watch_cb: ST_TYPE_HP\n");
8187 			}
8188 			switch (sensep->es_key) {
8189 			case KEY_UNIT_ATTENTION:
8190 				/* not ready to ready transition */
8191 				/* hp/es_qual_code == 80 on>off>on */
8192 				/* hp/es_qual_code == 0 on>off>unld>ld>on */
8193 				if (sensep->es_add_code == 0x28) {
8194 					state = MTIO_INSERTED;
8195 				}
8196 				break;
8197 			case KEY_NOT_READY:
8198 				/* in process, rewinding or loading */
8199 				if ((sensep->es_add_code == 0x04) &&
8200 				    (sensep->es_qual_code == 0x00)) {
8201 					state = MTIO_EJECTED;
8202 				}
8203 				break;
8204 			}
8205 			break;
8206 
8207 		case ST_TYPE_EXB8500:	/* Exabyte 8500 */
8208 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8209 			    "st_media_watch_cb: ST_TYPE_EXB8500\n");
8210 			switch (sensep->es_key) {
8211 			case KEY_UNIT_ATTENTION:
8212 				/* operator medium removal request */
8213 				if ((sensep->es_add_code == 0x5a) &&
8214 				    (sensep->es_qual_code == 0x01)) {
8215 					state = MTIO_EJECTED;
8216 				/* not ready to ready transition */
8217 				} else if ((sensep->es_add_code == 0x28) &&
8218 				    (sensep->es_qual_code == 0x00)) {
8219 					state = MTIO_INSERTED;
8220 				}
8221 				break;
8222 			case KEY_NOT_READY:
8223 				/* medium not present */
8224 				if (sensep->es_add_code == 0x3a) {
8225 					state = MTIO_EJECTED;
8226 				}
8227 				break;
8228 			}
8229 			break;
8230 		case ST_TYPE_EXABYTE:	/* Exabyte 8200 */
8231 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8232 			    "st_media_watch_cb: ST_TYPE_EXABYTE\n");
8233 			switch (sensep->es_key) {
8234 			case KEY_NOT_READY:
8235 				if ((sensep->es_add_code == 0x04) &&
8236 				    (sensep->es_qual_code == 0x00)) {
8237 					/* volume not mounted? */
8238 					state = MTIO_EJECTED;
8239 				} else if (sensep->es_add_code == 0x3a) {
8240 					state = MTIO_EJECTED;
8241 				}
8242 				break;
8243 			case KEY_UNIT_ATTENTION:
8244 				state = MTIO_EJECTED;
8245 				break;
8246 			}
8247 			break;
8248 
8249 		case ST_TYPE_DLT:		/* quantum DLT4xxx */
8250 			switch (sensep->es_key) {
8251 			case KEY_UNIT_ATTENTION:
8252 				if (sensep->es_add_code == 0x28) {
8253 					state = MTIO_INSERTED;
8254 				}
8255 				break;
8256 			case KEY_NOT_READY:
8257 				if (sensep->es_add_code == 0x04) {
8258 					/* in transition but could be either */
8259 					state = un->un_specified_mediastate;
8260 				} else if ((sensep->es_add_code == 0x3a) &&
8261 				    (sensep->es_qual_code == 0x00)) {
8262 					state = MTIO_EJECTED;
8263 				}
8264 				break;
8265 			}
8266 			break;
8267 		}
8268 	} else if (*((char *)statusp) == STATUS_GOOD) {
8269 		state = MTIO_INSERTED;
8270 	}
8271 
8272 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8273 	    "st_media_watch_cb:state=%x, specified=%x\n",
8274 	    state, un->un_specified_mediastate);
8275 
8276 	/*
8277 	 * now signal the waiting thread if this is *not* the specified state;
8278 	 * delay the signal if the state is MTIO_INSERTED
8279 	 * to allow the target to recover
8280 	 */
8281 	if (state != un->un_specified_mediastate) {
8282 		un->un_mediastate = state;
8283 		if (state == MTIO_INSERTED) {
8284 			/*
8285 			 * delay the signal to give the drive a chance
8286 			 * to do what it apparently needs to do
8287 			 */
8288 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8289 			    "st_media_watch_cb:delayed cv_broadcast\n");
8290 			un->un_delay_tid = timeout(st_delayed_cv_broadcast,
8291 			    un, drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
8292 		} else {
8293 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8294 			    "st_media_watch_cb:immediate cv_broadcast\n");
8295 			cv_broadcast(&un->un_state_cv);
8296 		}
8297 	}
8298 	mutex_exit(ST_MUTEX);
8299 	return (0);
8300 }
8301 
8302 /*
8303  * delayed cv_broadcast to allow for target to recover
8304  * from media insertion
8305  */
8306 static void
8307 st_delayed_cv_broadcast(void *arg)
8308 {
8309 	struct scsi_tape *un = arg;
8310 
8311 	ST_FUNC(ST_DEVINFO, st_delayed_cv_broadcast);
8312 
8313 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8314 	    "st_delayed_cv_broadcast:delayed cv_broadcast\n");
8315 
8316 	mutex_enter(ST_MUTEX);
8317 	cv_broadcast(&un->un_state_cv);
8318 	mutex_exit(ST_MUTEX);
8319 }
8320 
8321 /*
8322  * restart cmd currently at the start of the waitq
8323  */
8324 static void
8325 st_start_restart(void *arg)
8326 {
8327 	struct scsi_tape *un = arg;
8328 
8329 	ST_FUNC(ST_DEVINFO, st_start_restart);
8330 
8331 	ASSERT(un != NULL);
8332 
8333 	mutex_enter(ST_MUTEX);
8334 
8335 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8336 	    "st_tran_restart()\n");
8337 
8338 	if (un->un_quef) {
8339 		st_start(un);
8340 	}
8341 
8342 	mutex_exit(ST_MUTEX);
8343 }
8344 
8345 
8346 /*
8347  * Command completion processing
8348  *
8349  */
8350 static void
8351 st_intr(struct scsi_pkt *pkt)
8352 {
8353 	struct scsi_tape *un;
8354 	struct buf *last_runqf;
8355 	struct buf *bp;
8356 	int action = COMMAND_DONE;
8357 	clock_t	timout;
8358 	int	status;
8359 
8360 
8361 	bp = pkt->pkt_private;
8362 
8363 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
8364 
8365 	ST_FUNC(ST_DEVINFO, st_intr);
8366 
8367 	mutex_enter(ST_MUTEX);
8368 
8369 	un->un_rqs_state &= ~(ST_RQS_ERROR);
8370 
8371 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_intr()\n");
8372 
8373 	if (pkt->pkt_reason != CMD_CMPLT) {
8374 
8375 		/* If device has gone away not much else to do */
8376 		if (pkt->pkt_reason == CMD_DEV_GONE) {
8377 			action = COMMAND_DONE_ERROR;
8378 		} else if (un->un_state == ST_STATE_SENSING) {
8379 			ST_DO_ERRSTATS(un, st_transerrs);
8380 			action = COMMAND_DONE_ERROR;
8381 		} else {
8382 			action = st_handle_incomplete(un, bp);
8383 		}
8384 	/*
8385 	 * At this point we know that the command was successfully
8386 	 * completed. Now what?
8387 	 */
8388 	} else if (un->un_arq_enabled &&
8389 	    (pkt->pkt_state & STATE_ARQ_DONE)) {
8390 		/*
8391 		 * the transport layer successfully completed an autorqsense
8392 		 */
8393 		action = st_handle_autosense(un, bp);
8394 
8395 	} else if (un->un_state == ST_STATE_SENSING) {
8396 		/*
8397 		 * okay. We were running a REQUEST SENSE. Find
8398 		 * out what to do next.
8399 		 * some actions are based on un_state, hence
8400 		 * restore the state st was in before ST_STATE_SENSING.
8401 		 */
8402 		un->un_state = un->un_laststate;
8403 		action = st_handle_sense(un, bp);
8404 		/*
8405 		 * set pkt back to original packet in case we will have
8406 		 * to requeue it
8407 		 */
8408 		pkt = BP_PKT(bp);
8409 	} else  if ((SCBP(pkt)->sts_busy) || (SCBP(pkt)->sts_chk)) {
8410 		/*
8411 		 * Okay, we weren't running a REQUEST SENSE. Call a routine
8412 		 * to see if the status bits we're okay. If a request sense
8413 		 * is to be run, that will happen.
8414 		 */
8415 		action = st_check_error(un, pkt);
8416 	}
8417 
8418 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
8419 		switch (action) {
8420 			case QUE_COMMAND:
8421 				/*
8422 				 * return cmd to head to the queue
8423 				 * since we are suspending so that
8424 				 * it gets restarted during resume
8425 				 */
8426 				if (un->un_runqf) {
8427 					last_runqf = un->un_runqf;
8428 					un->un_runqf = bp;
8429 					bp->b_actf = last_runqf;
8430 				} else {
8431 					bp->b_actf = NULL;
8432 					un->un_runqf = bp;
8433 					un->un_runql = bp;
8434 				}
8435 				action = JUST_RETURN;
8436 				break;
8437 
8438 			case QUE_SENSE:
8439 				action = COMMAND_DONE_ERROR;
8440 				break;
8441 
8442 			default:
8443 				break;
8444 		}
8445 	}
8446 
8447 	/*
8448 	 * Restore old state if we were sensing.
8449 	 */
8450 	if (un->un_state == ST_STATE_SENSING && action != QUE_SENSE) {
8451 		un->un_state = un->un_laststate;
8452 	}
8453 
8454 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8455 	    "st_intr: pkt=%p, bp=%p, action=%x, status=%x\n",
8456 	    (void *)pkt, (void *)bp, action, SCBP_C(pkt));
8457 
8458 
8459 	switch (action) {
8460 	case COMMAND_DONE_EACCES:
8461 		/* this is to report a reservation conflict */
8462 		st_bioerror(bp, EACCES);
8463 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8464 		    "Reservation Conflict \n");
8465 		un->un_pos.pmode = invalid;
8466 
8467 		/*FALLTHROUGH*/
8468 	case COMMAND_DONE_ERROR:
8469 		if (un->un_pos.eof < ST_EOT_PENDING &&
8470 		    un->un_state >= ST_STATE_OPEN) {
8471 			/*
8472 			 * all errors set state of the tape to 'unknown'
8473 			 * unless we're at EOT or are doing append testing.
8474 			 * If sense key was illegal request, preserve state.
8475 			 */
8476 			if (un->un_status != KEY_ILLEGAL_REQUEST) {
8477 				un->un_pos.pmode = invalid;
8478 			}
8479 		}
8480 
8481 		un->un_err_resid = bp->b_resid = bp->b_bcount;
8482 		/*
8483 		 * since we have an error (COMMAND_DONE_ERROR), we want to
8484 		 * make sure an error ocurrs, so make sure at least EIO is
8485 		 * returned
8486 		 */
8487 		if (geterror(bp) == 0)
8488 			st_bioerror(bp, EIO);
8489 
8490 		SET_PE_FLAG(un);
8491 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
8492 		    (un->un_errno == EIO)) {
8493 			un->un_rqs_state &= ~(ST_RQS_VALID);
8494 		}
8495 		goto done;
8496 
8497 	case COMMAND_DONE_ERROR_RECOVERED:
8498 		un->un_err_resid = bp->b_resid = bp->b_bcount;
8499 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
8500 		    "st_intr(): COMMAND_DONE_ERROR_RECOVERED");
8501 		if (geterror(bp) == 0) {
8502 			st_bioerror(bp, EIO);
8503 		}
8504 		SET_PE_FLAG(un);
8505 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
8506 		    (un->un_errno == EIO)) {
8507 			un->un_rqs_state &= ~(ST_RQS_VALID);
8508 		}
8509 		/*FALLTHROUGH*/
8510 	case COMMAND_DONE:
8511 		st_set_state(un);
8512 done:
8513 		ST_DO_KSTATS(bp, kstat_runq_exit);
8514 		st_done_and_mutex_exit(un, bp);
8515 		return;
8516 
8517 	case QUE_SENSE:
8518 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors)
8519 			goto sense_error;
8520 
8521 		if (un->un_state != ST_STATE_SENSING) {
8522 			un->un_laststate = un->un_state;
8523 			un->un_state = ST_STATE_SENSING;
8524 		}
8525 
8526 		un->un_rqs->pkt_private = (opaque_t)bp;
8527 		bzero(ST_RQSENSE, SENSE_LENGTH);
8528 
8529 		if (un->un_throttle) {
8530 			un->un_last_throttle = un->un_throttle;
8531 			un->un_throttle = 0;
8532 		}
8533 
8534 		mutex_exit(ST_MUTEX);
8535 
8536 		/*
8537 		 * never retry this, some other command will have nuked the
8538 		 * sense, anyway
8539 		 */
8540 		status = scsi_transport(un->un_rqs);
8541 
8542 		mutex_enter(ST_MUTEX);
8543 
8544 		if (un->un_last_throttle) {
8545 			un->un_throttle = un->un_last_throttle;
8546 		}
8547 
8548 		if (status == TRAN_ACCEPT) {
8549 			mutex_exit(ST_MUTEX);
8550 			return;
8551 		}
8552 		if (status != TRAN_BUSY)
8553 			ST_DO_ERRSTATS(un, st_transerrs);
8554 sense_error:
8555 		un->un_pos.pmode = invalid;
8556 		st_bioerror(bp, EIO);
8557 		SET_PE_FLAG(un);
8558 		goto done;
8559 
8560 	case QUE_BUSY_COMMAND:
8561 		/* longish timeout */
8562 		timout = ST_STATUS_BUSY_TIMEOUT;
8563 		goto que_it_up;
8564 
8565 	case QUE_COMMAND:
8566 		/* short timeout */
8567 		timout = ST_TRAN_BUSY_TIMEOUT;
8568 que_it_up:
8569 		/*
8570 		 * let st_handle_intr_busy put this bp back on waitq and make
8571 		 * checks to see if it is ok to requeue the command.
8572 		 */
8573 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
8574 
8575 		/*
8576 		 * Save the throttle before setting up the timeout
8577 		 */
8578 		if (un->un_throttle) {
8579 			un->un_last_throttle = un->un_throttle;
8580 		}
8581 		mutex_exit(ST_MUTEX);
8582 		if (st_handle_intr_busy(un, bp, timout) == 0)
8583 			return;		/* timeout is setup again */
8584 
8585 		mutex_enter(ST_MUTEX);
8586 		un->un_pos.pmode = invalid;
8587 		un->un_err_resid = bp->b_resid = bp->b_bcount;
8588 		st_bioerror(bp, EIO);
8589 		SET_PE_FLAG(un);
8590 		goto done;
8591 
8592 	case QUE_LAST_COMMAND:
8593 
8594 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors) {
8595 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
8596 			    "un_ncmds: %d can't retry cmd \n", un->un_ncmds);
8597 			goto last_command_error;
8598 		}
8599 		mutex_exit(ST_MUTEX);
8600 		if (st_handle_intr_retry_lcmd(un, bp) == 0)
8601 			return;
8602 		mutex_enter(ST_MUTEX);
8603 last_command_error:
8604 		un->un_err_resid = bp->b_resid = bp->b_bcount;
8605 		un->un_pos.pmode = invalid;
8606 		st_bioerror(bp, EIO);
8607 		SET_PE_FLAG(un);
8608 		goto done;
8609 
8610 	case JUST_RETURN:
8611 	default:
8612 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
8613 		mutex_exit(ST_MUTEX);
8614 		return;
8615 	}
8616 	/*NOTREACHED*/
8617 }
8618 
8619 static int
8620 st_handle_incomplete(struct scsi_tape *un, struct buf *bp)
8621 {
8622 	static char *fail = "SCSI transport failed: reason '%s': %s\n";
8623 	int rval = COMMAND_DONE_ERROR;
8624 	struct scsi_pkt *pkt = (un->un_state == ST_STATE_SENSING) ?
8625 	    un->un_rqs : BP_PKT(bp);
8626 	int result;
8627 
8628 	ST_FUNC(ST_DEVINFO, st_handle_incomplete);
8629 
8630 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8631 	    "st_handle_incomplete(): dev = 0x%lx\n", un->un_dev);
8632 
8633 	ASSERT(mutex_owned(ST_MUTEX));
8634 
8635 	switch (pkt->pkt_reason) {
8636 	case CMD_INCOMPLETE:	/* tran stopped with not normal state */
8637 		/*
8638 		 * this occurs when accessing a powered down drive, no
8639 		 * need to complain; just fail the open
8640 		 */
8641 		ST_CDB(ST_DEVINFO, "Incomplete CDB", (char *)pkt->pkt_cdbp);
8642 
8643 		/*
8644 		 * if we have commands outstanding in HBA, and a command
8645 		 * comes back incomplete, we're hosed, so reset target
8646 		 * If we have the bus, but cmd_incomplete, we probably just
8647 		 * have a failed selection, so don't reset the target, just
8648 		 * requeue the command and try again
8649 		 */
8650 		if ((un->un_ncmds > 1) || (pkt->pkt_state != STATE_GOT_BUS)) {
8651 			goto reset_target;
8652 		}
8653 
8654 		/*
8655 		 * Retry selection a couple more times if we're
8656 		 * open.  If opening, we only try just once to
8657 		 * reduce probe time for nonexistant devices.
8658 		 */
8659 		if ((un->un_laststate > ST_STATE_OPENING) &&
8660 		    ((int)un->un_retry_ct < st_selection_retry_count)) {
8661 			rval = QUE_COMMAND;
8662 		}
8663 		ST_DO_ERRSTATS(un, st_transerrs);
8664 		break;
8665 
8666 	case CMD_ABORTED:
8667 		/*
8668 		 * most likely this is caused by flush-on-error support. If
8669 		 * it was not there, the we're in trouble.
8670 		 */
8671 		if (!un->un_flush_on_errors) {
8672 			un->un_status = SUN_KEY_FATAL;
8673 			goto reset_target;
8674 		}
8675 
8676 		st_set_pe_errno(un);
8677 		bioerror(bp, un->un_errno);
8678 		if (un->un_errno)
8679 			return (COMMAND_DONE_ERROR);
8680 		else
8681 			return (COMMAND_DONE);
8682 
8683 	case CMD_TIMEOUT:	/* Command timed out */
8684 		un->un_status = SUN_KEY_TIMEOUT;
8685 
8686 		/*FALLTHROUGH*/
8687 	default:
8688 reset_target:
8689 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8690 		    "transport completed with %s\n",
8691 		    scsi_rname(pkt->pkt_reason));
8692 		ST_DO_ERRSTATS(un, st_transerrs);
8693 		if ((pkt->pkt_state & STATE_GOT_TARGET) &&
8694 		    ((pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET |
8695 		    STAT_ABORTED)) == 0)) {
8696 
8697 			/*
8698 			 * If we haven't reserved the drive don't reset it.
8699 			 */
8700 			if ((un->un_rsvd_status &
8701 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
8702 				return (rval);
8703 			}
8704 
8705 			/*
8706 			 * if we aren't lost yet we will be soon.
8707 			 */
8708 			un->un_pos.pmode = invalid;
8709 
8710 			mutex_exit(ST_MUTEX);
8711 
8712 			result = scsi_reset(ROUTE, RESET_TARGET);
8713 			/*
8714 			 * if target reset fails, then pull the chain
8715 			 */
8716 			if (result == 0) {
8717 				result = scsi_reset(ROUTE, RESET_ALL);
8718 			}
8719 			mutex_enter(ST_MUTEX);
8720 
8721 			if ((result == 0) && (un->un_state >= ST_STATE_OPEN)) {
8722 				/* no hope left to recover */
8723 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
8724 				    "recovery by resets failed\n");
8725 				return (rval);
8726 			}
8727 		}
8728 	}
8729 
8730 	if ((pkt->pkt_reason == CMD_RESET) || (pkt->pkt_statistics &
8731 	    (STAT_BUS_RESET | STAT_DEV_RESET))) {
8732 		if ((un->un_rsvd_status & ST_RESERVE)) {
8733 			un->un_rsvd_status |= ST_LOST_RESERVE;
8734 			ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8735 			    "Lost Reservation\n");
8736 		}
8737 	}
8738 
8739 	if ((int)un->un_retry_ct++ < st_retry_count) {
8740 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
8741 			rval = QUE_COMMAND;
8742 		} else if (bp == un->un_sbufp) {
8743 			switch ((uchar_t)(uintptr_t)bp->b_forw) {
8744 			case SCMD_MODE_SENSE:
8745 			case SCMD_MODE_SELECT:
8746 			case SCMD_READ_BLKLIM:
8747 			case SCMD_REWIND:
8748 			case SCMD_LOAD:
8749 			case SCMD_TEST_UNIT_READY:
8750 				/*
8751 				 * These commands can be rerun with impunity
8752 				 */
8753 				rval = QUE_COMMAND;
8754 				break;
8755 
8756 			default:
8757 				break;
8758 			}
8759 		}
8760 	} else {
8761 		rval = COMMAND_DONE_ERROR;
8762 	}
8763 
8764 	if (un->un_state >= ST_STATE_OPEN) {
8765 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
8766 		    fail, scsi_rname(pkt->pkt_reason),
8767 		    (rval == COMMAND_DONE_ERROR)?
8768 		    "giving up" : "retrying command");
8769 	}
8770 	return (rval);
8771 }
8772 
8773 /*
8774  * if the device is busy, then put this bp back on the waitq, on the
8775  * interrupt thread, where we want the head of the queue and not the
8776  * end
8777  *
8778  * The callers of this routine should take measures to save the
8779  * un_throttle in un_last_throttle which will be restored in
8780  * st_intr_restart(). The only exception should be st_intr_restart()
8781  * calling this routine for which the saving is already done.
8782  */
8783 static int
8784 st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
8785 	clock_t timeout_interval)
8786 {
8787 	struct buf *last_quef;
8788 	int rval = 0;
8789 
8790 	mutex_enter(ST_MUTEX);
8791 
8792 	ST_FUNC(ST_DEVINFO, st_handle_intr_busy);
8793 
8794 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8795 	    "st_handle_intr_busy(), un = 0x%p\n", (void *)un);
8796 
8797 	/*
8798 	 * Check to see if we hit the retry timeout. We check to make sure
8799 	 * this is the first one on the runq and make sure we have not
8800 	 * queued up any more, so this one has to be the last on the list
8801 	 * also. If it is not, we have to fail.  If it is not the first, but
8802 	 * is the last we are in trouble anyway, as we are in the interrupt
8803 	 * context here.
8804 	 */
8805 	if (((int)un->un_tran_retry_ct++ > st_retry_count) ||
8806 	    ((un->un_runqf != bp) && (un->un_runql != bp))) {
8807 		rval = -1;
8808 		goto exit;
8809 	}
8810 
8811 	/* put the bp back on the waitq */
8812 	if (un->un_quef) {
8813 		last_quef = un->un_quef;
8814 		un->un_quef = bp;
8815 		bp->b_actf = last_quef;
8816 	} else  {
8817 		bp->b_actf = NULL;
8818 		un->un_quef = bp;
8819 		un->un_quel = bp;
8820 	}
8821 
8822 	/*
8823 	 * We know that this is the first and last on the runq at this time,
8824 	 * so we just nullify those two queues
8825 	 */
8826 	un->un_runqf = NULL;
8827 	un->un_runql = NULL;
8828 
8829 	/*
8830 	 * We don't want any other commands being started in the mean time.
8831 	 * If start had just released mutex after putting something on the
8832 	 * runq, we won't even get here.
8833 	 */
8834 	un->un_throttle = 0;
8835 
8836 	/*
8837 	 * send a marker pkt, if appropriate
8838 	 */
8839 	st_hba_unflush(un);
8840 
8841 	/*
8842 	 * all queues are aligned, we are just waiting to
8843 	 * transport
8844 	 */
8845 	un->un_hib_tid = timeout(st_intr_restart, un, timeout_interval);
8846 
8847 exit:
8848 	mutex_exit(ST_MUTEX);
8849 	return (rval);
8850 }
8851 
8852 /*
8853  * To get one error entry from error stack
8854  */
8855 static int
8856 st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag)
8857 {
8858 #ifdef _MULTI_DATAMODEL
8859 	/*
8860 	 * For use when a 32 bit app makes a call into a
8861 	 * 64 bit ioctl
8862 	 */
8863 	struct mterror_entry32 err_entry32;
8864 #endif /* _MULTI_DATAMODEL */
8865 
8866 	int rval = 0;
8867 	struct mterror_entry err_entry;
8868 	struct mterror_entry_stack *err_link_entry_p;
8869 	size_t arq_status_len_in, arq_status_len_kr;
8870 
8871 	ST_FUNC(ST_DEVINFO, st_get_error_entry);
8872 
8873 	ASSERT(mutex_owned(ST_MUTEX));
8874 
8875 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8876 	    "st_get_error_entry()\n");
8877 
8878 	/*
8879 	 * if error record stack empty, return ENXIO
8880 	 */
8881 	if (un->un_error_entry_stk == NULL) {
8882 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8883 		    "st_get_error_entry: Error Entry Stack Empty!\n");
8884 		rval = ENXIO;
8885 		goto ret;
8886 	}
8887 
8888 	/*
8889 	 * get the top entry from stack
8890 	 */
8891 	err_link_entry_p = un->un_error_entry_stk;
8892 	arq_status_len_kr =
8893 	    err_link_entry_p->mtees_entry.mtee_arq_status_len;
8894 
8895 #ifdef _MULTI_DATAMODEL
8896 	switch (ddi_model_convert_from(flag & FMODELS)) {
8897 	case DDI_MODEL_ILP32:
8898 		if (ddi_copyin((void *)arg, &err_entry32,
8899 		    MTERROR_ENTRY_SIZE_32, flag)) {
8900 			rval = EFAULT;
8901 			goto ret;
8902 		}
8903 
8904 		arq_status_len_in =
8905 		    (size_t)err_entry32.mtee_arq_status_len;
8906 
8907 		err_entry32.mtee_cdb_len =
8908 		    (size32_t)err_link_entry_p->mtees_entry.mtee_cdb_len;
8909 
8910 		if (arq_status_len_in > arq_status_len_kr)
8911 			err_entry32.mtee_arq_status_len =
8912 			    (size32_t)arq_status_len_kr;
8913 
8914 		if (ddi_copyout(
8915 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
8916 		    (void *)(uintptr_t)err_entry32.mtee_cdb_buf,
8917 		    err_entry32.mtee_cdb_len, flag)) {
8918 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8919 			    "st_get_error_entry: Copy cdb buffer error!");
8920 			rval = EFAULT;
8921 		}
8922 
8923 		if (ddi_copyout(
8924 		    err_link_entry_p->mtees_entry.mtee_arq_status,
8925 		    (void *)(uintptr_t)err_entry32.mtee_arq_status,
8926 		    err_entry32.mtee_arq_status_len, flag)) {
8927 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8928 			    "st_get_error_entry: copy arq status error!");
8929 			rval = EFAULT;
8930 		}
8931 
8932 		if (ddi_copyout(&err_entry32, (void *)arg,
8933 		    MTERROR_ENTRY_SIZE_32, flag)) {
8934 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8935 			    "st_get_error_entry: copy arq status out error!");
8936 			rval = EFAULT;
8937 		}
8938 		break;
8939 
8940 	case DDI_MODEL_NONE:
8941 		if (ddi_copyin((void *)arg, &err_entry,
8942 		    MTERROR_ENTRY_SIZE_64, flag)) {
8943 			rval = EFAULT;
8944 			goto ret;
8945 		}
8946 		arq_status_len_in = err_entry.mtee_arq_status_len;
8947 
8948 		err_entry.mtee_cdb_len =
8949 		    err_link_entry_p->mtees_entry.mtee_cdb_len;
8950 
8951 		if (arq_status_len_in > arq_status_len_kr)
8952 			err_entry.mtee_arq_status_len =
8953 			    arq_status_len_kr;
8954 
8955 		if (ddi_copyout(
8956 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
8957 		    err_entry.mtee_cdb_buf,
8958 		    err_entry.mtee_cdb_len, flag)) {
8959 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8960 			    "st_get_error_entry: Copy cdb buffer error!");
8961 			rval = EFAULT;
8962 		}
8963 
8964 		if (ddi_copyout(
8965 		    err_link_entry_p->mtees_entry.mtee_arq_status,
8966 		    err_entry.mtee_arq_status,
8967 		    err_entry.mtee_arq_status_len, flag)) {
8968 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8969 			    "st_get_error_entry: copy arq status error!");
8970 			rval = EFAULT;
8971 		}
8972 
8973 		if (ddi_copyout(&err_entry, (void *)arg,
8974 		    MTERROR_ENTRY_SIZE_64, flag)) {
8975 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8976 			    "st_get_error_entry: copy arq status out error!");
8977 			rval = EFAULT;
8978 		}
8979 		break;
8980 	}
8981 #else /* _MULTI_DATAMODEL */
8982 	if (ddi_copyin((void *)arg, &err_entry,
8983 	    MTERROR_ENTRY_SIZE_64, flag)) {
8984 		rval = EFAULT;
8985 		goto ret;
8986 	}
8987 	arq_status_len_in = err_entry.mtee_arq_status_len;
8988 
8989 	err_entry.mtee_cdb_len =
8990 	    err_link_entry_p->mtees_entry.mtee_cdb_len;
8991 
8992 	if (arq_status_len_in > arq_status_len_kr)
8993 		err_entry.mtee_arq_status_len =
8994 		    arq_status_len_kr;
8995 
8996 	if (ddi_copyout(
8997 	    err_link_entry_p->mtees_entry.mtee_cdb_buf,
8998 	    err_entry.mtee_cdb_buf,
8999 	    err_entry.mtee_cdb_len, flag)) {
9000 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9001 		    "st_get_error_entry: Copy cdb buffer error!");
9002 		rval = EFAULT;
9003 	}
9004 
9005 	if (ddi_copyout(
9006 	    err_link_entry_p->mtees_entry.mtee_arq_status,
9007 	    err_entry.mtee_arq_status,
9008 	    err_entry.mtee_arq_status_len, flag)) {
9009 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9010 		    "st_get_error_entry: copy arq status buffer error!");
9011 		rval = EFAULT;
9012 	}
9013 
9014 	if (ddi_copyout(&err_entry, (void *)arg,
9015 	    MTERROR_ENTRY_SIZE_64, flag)) {
9016 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9017 		    "st_get_error_entry: copy arq status out error!");
9018 		rval = EFAULT;
9019 	}
9020 #endif /* _MULTI_DATAMODEL */
9021 
9022 	/*
9023 	 * update stack
9024 	 */
9025 	un->un_error_entry_stk = err_link_entry_p->mtees_nextp;
9026 
9027 	kmem_free(err_link_entry_p->mtees_entry.mtee_cdb_buf,
9028 	    err_link_entry_p->mtees_entry.mtee_cdb_len);
9029 	err_link_entry_p->mtees_entry.mtee_cdb_buf = NULL;
9030 
9031 	kmem_free(err_link_entry_p->mtees_entry.mtee_arq_status,
9032 	    SECMDS_STATUS_SIZE);
9033 	err_link_entry_p->mtees_entry.mtee_arq_status = NULL;
9034 
9035 	kmem_free(err_link_entry_p, MTERROR_LINK_ENTRY_SIZE);
9036 	err_link_entry_p = NULL;
9037 ret:
9038 	return (rval);
9039 }
9040 
9041 /*
9042  * MTIOCGETERROR ioctl needs to retrieve the current sense data along with
9043  * the scsi CDB command which causes the error and generates sense data and
9044  * the scsi status.
9045  *
9046  *      error-record stack
9047  *
9048  *
9049  *             TOP                                     BOTTOM
9050  *              ------------------------------------------
9051  *              |   0   |   1   |   2   |   ...  |   n   |
9052  *              ------------------------------------------
9053  *                  ^
9054  *                  |
9055  *       pointer to error entry
9056  *
9057  * when st driver generates one sense data record, it creates a error-entry
9058  * and pushes it onto the stack.
9059  *
9060  */
9061 
9062 static void
9063 st_update_error_stack(struct scsi_tape *un,
9064 			struct scsi_pkt *pkt,
9065 			struct scsi_arq_status *cmd)
9066 {
9067 	struct mterror_entry_stack *err_entry_tmp;
9068 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
9069 	size_t cdblen = scsi_cdb_size[CDB_GROUPID(cdbp[0])];
9070 
9071 	ST_FUNC(ST_DEVINFO, st_update_error_stack);
9072 
9073 	ASSERT(mutex_owned(ST_MUTEX));
9074 
9075 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9076 	    "st_update_error_stack()\n");
9077 
9078 	ASSERT(cmd);
9079 	ASSERT(cdbp);
9080 	if (cdblen == 0) {
9081 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9082 		    "st_update_error_stack: CDB length error!\n");
9083 		return;
9084 	}
9085 
9086 	err_entry_tmp = kmem_alloc(MTERROR_LINK_ENTRY_SIZE, KM_SLEEP);
9087 	ASSERT(err_entry_tmp != NULL);
9088 
9089 	err_entry_tmp->mtees_entry.mtee_cdb_buf =
9090 	    kmem_alloc(cdblen, KM_SLEEP);
9091 	ASSERT(err_entry_tmp->mtees_entry.mtee_cdb_buf != NULL);
9092 
9093 	err_entry_tmp->mtees_entry.mtee_arq_status =
9094 	    kmem_alloc(SECMDS_STATUS_SIZE, KM_SLEEP);
9095 	ASSERT(err_entry_tmp->mtees_entry.mtee_arq_status != NULL);
9096 
9097 	/*
9098 	 * copy cdb command & length to current error entry
9099 	 */
9100 	err_entry_tmp->mtees_entry.mtee_cdb_len = cdblen;
9101 	bcopy(cdbp, err_entry_tmp->mtees_entry.mtee_cdb_buf, cdblen);
9102 
9103 	/*
9104 	 * copy scsi status length to current error entry
9105 	 */
9106 	err_entry_tmp->mtees_entry.mtee_arq_status_len =
9107 	    SECMDS_STATUS_SIZE;
9108 
9109 	/*
9110 	 * copy sense data and scsi status to current error entry
9111 	 */
9112 	bcopy(cmd, err_entry_tmp->mtees_entry.mtee_arq_status,
9113 	    SECMDS_STATUS_SIZE);
9114 
9115 	err_entry_tmp->mtees_nextp = un->un_error_entry_stk;
9116 	un->un_error_entry_stk = err_entry_tmp;
9117 
9118 }
9119 
9120 /*
9121  * Empty all the error entry in stack
9122  */
9123 static void
9124 st_empty_error_stack(struct scsi_tape *un)
9125 {
9126 	struct mterror_entry_stack *linkp;
9127 
9128 	ST_FUNC(ST_DEVINFO, st_empty_error_stack);
9129 
9130 	ASSERT(mutex_owned(ST_MUTEX));
9131 
9132 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9133 	    "st_empty_entry_stack()\n");
9134 
9135 	while (un->un_error_entry_stk != NULL) {
9136 		linkp = un->un_error_entry_stk;
9137 		un->un_error_entry_stk =
9138 		    un->un_error_entry_stk->mtees_nextp;
9139 		kmem_free(linkp, MTERROR_LINK_ENTRY_SIZE);
9140 		linkp = NULL;
9141 	}
9142 }
9143 
9144 static int
9145 st_handle_sense(struct scsi_tape *un, struct buf *bp)
9146 {
9147 	struct scsi_pkt *pkt = BP_PKT(bp);
9148 	struct scsi_pkt *rqpkt = un->un_rqs;
9149 	struct scsi_arq_status arqstat;
9150 
9151 	int rval = COMMAND_DONE_ERROR;
9152 	int amt;
9153 
9154 	ST_FUNC(ST_DEVINFO, st_handle_sense);
9155 
9156 	ASSERT(mutex_owned(ST_MUTEX));
9157 
9158 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9159 	    "st_handle_sense()\n");
9160 
9161 	if (SCBP(rqpkt)->sts_busy) {
9162 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
9163 		    "busy unit on request sense\n");
9164 		if ((int)un->un_retry_ct++ < st_retry_count) {
9165 			rval = QUE_BUSY_COMMAND;
9166 		}
9167 		return (rval);
9168 	} else if (SCBP(rqpkt)->sts_chk) {
9169 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9170 		    "Check Condition on REQUEST SENSE\n");
9171 		return (rval);
9172 	}
9173 
9174 	/* was there enough data? */
9175 	amt = (int)SENSE_LENGTH - rqpkt->pkt_resid;
9176 	if ((rqpkt->pkt_state & STATE_XFERRED_DATA) == 0 ||
9177 	    (amt < SUN_MIN_SENSE_LENGTH)) {
9178 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9179 		    "REQUEST SENSE couldn't get sense data\n");
9180 		return (rval);
9181 	}
9182 
9183 	bcopy(SCBP(pkt), &arqstat.sts_status,
9184 	    sizeof (struct scsi_status));
9185 	bcopy(SCBP(rqpkt), &arqstat.sts_rqpkt_status,
9186 	    sizeof (struct scsi_status));
9187 	arqstat.sts_rqpkt_reason = rqpkt->pkt_reason;
9188 	arqstat.sts_rqpkt_resid = rqpkt->pkt_resid;
9189 	arqstat.sts_rqpkt_state = rqpkt->pkt_state;
9190 	arqstat.sts_rqpkt_statistics = rqpkt->pkt_statistics;
9191 	bcopy(ST_RQSENSE, &arqstat.sts_sensedata, SENSE_LENGTH);
9192 
9193 	/*
9194 	 * copy one arqstat entry in the sense data buffer
9195 	 */
9196 	st_update_error_stack(un, pkt, &arqstat);
9197 	return (st_decode_sense(un, bp, amt, SCBP(rqpkt)));
9198 }
9199 
9200 static int
9201 st_handle_autosense(struct scsi_tape *un, struct buf *bp)
9202 {
9203 	struct scsi_pkt *pkt = BP_PKT(bp);
9204 	struct scsi_arq_status *arqstat =
9205 	    (struct scsi_arq_status *)pkt->pkt_scbp;
9206 	int rval = COMMAND_DONE_ERROR;
9207 	int amt;
9208 
9209 	ST_FUNC(ST_DEVINFO, st_handle_autosense);
9210 
9211 	ASSERT(mutex_owned(ST_MUTEX));
9212 
9213 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9214 	    "st_handle_autosense()\n");
9215 
9216 	if (arqstat->sts_rqpkt_status.sts_busy) {
9217 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
9218 		    "busy unit on request sense\n");
9219 		/*
9220 		 * we return QUE_SENSE so st_intr will setup the SENSE cmd.
9221 		 * the disadvantage is that we do not have any delay for the
9222 		 * second retry of rqsense and we have to keep a packet around
9223 		 */
9224 		return (QUE_SENSE);
9225 
9226 	} else if (arqstat->sts_rqpkt_reason != CMD_CMPLT) {
9227 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9228 		    "transport error on REQUEST SENSE\n");
9229 		if ((arqstat->sts_rqpkt_state & STATE_GOT_TARGET) &&
9230 		    ((arqstat->sts_rqpkt_statistics &
9231 		    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) == 0)) {
9232 			mutex_exit(ST_MUTEX);
9233 			if (scsi_reset(ROUTE, RESET_TARGET) == 0) {
9234 				/*
9235 				 * if target reset fails, then pull the chain
9236 				 */
9237 				if (scsi_reset(ROUTE, RESET_ALL) == 0) {
9238 					ST_DEBUG6(ST_DEVINFO, st_label,
9239 					    CE_WARN,
9240 					    "recovery by resets failed\n");
9241 				}
9242 			}
9243 			mutex_enter(ST_MUTEX);
9244 		}
9245 		return (rval);
9246 
9247 	} else if (arqstat->sts_rqpkt_status.sts_chk) {
9248 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9249 		    "Check Condition on REQUEST SENSE\n");
9250 		return (rval);
9251 	}
9252 
9253 
9254 	/* was there enough data? */
9255 	amt = (int)SENSE_LENGTH - arqstat->sts_rqpkt_resid;
9256 	if ((arqstat->sts_rqpkt_state & STATE_XFERRED_DATA) == 0 ||
9257 	    (amt < SUN_MIN_SENSE_LENGTH)) {
9258 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9259 		    "REQUEST SENSE couldn't get sense data\n");
9260 		return (rval);
9261 	}
9262 
9263 	/*
9264 	 * copy one arqstat entry in the sense data buffer
9265 	 */
9266 	st_update_error_stack(un, pkt, arqstat);
9267 
9268 	bcopy(&arqstat->sts_sensedata, ST_RQSENSE, SENSE_LENGTH);
9269 
9270 	return (st_decode_sense(un, bp, amt, &arqstat->sts_rqpkt_status));
9271 }
9272 
9273 static int
9274 st_decode_sense(struct scsi_tape *un, struct buf *bp,  int amt,
9275 	struct scsi_status *statusp)
9276 {
9277 	struct scsi_pkt *pkt = BP_PKT(bp);
9278 	int rval = COMMAND_DONE_ERROR;
9279 	long resid;
9280 	struct scsi_extended_sense *sensep = ST_RQSENSE;
9281 	int severity;
9282 	int get_error;
9283 
9284 	ST_FUNC(ST_DEVINFO, st_decode_sense);
9285 
9286 	ASSERT(mutex_owned(ST_MUTEX));
9287 
9288 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9289 	    "st_decode_sense()\n");
9290 
9291 	/*
9292 	 * For uscsi commands, squirrel away a copy of the
9293 	 * results of the Request Sense.
9294 	 */
9295 	if (USCSI_CMD(bp)) {
9296 		struct uscsi_cmd *ucmd = BP_UCMD(bp);
9297 		ucmd->uscsi_rqstatus = *(uchar_t *)statusp;
9298 		if (ucmd->uscsi_rqlen && un->un_srqbufp) {
9299 			uchar_t rqlen = min((uchar_t)amt, ucmd->uscsi_rqlen);
9300 			ucmd->uscsi_rqresid = ucmd->uscsi_rqlen - rqlen;
9301 			bcopy(ST_RQSENSE, un->un_srqbufp, rqlen);
9302 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9303 			    "st_decode_sense: stat=0x%x resid=0x%x\n",
9304 			    ucmd->uscsi_rqstatus, ucmd->uscsi_rqresid);
9305 		}
9306 	}
9307 
9308 	/*
9309 	 * If the drive is an MT-02, reposition the
9310 	 * secondary error code into the proper place.
9311 	 *
9312 	 * XXX	MT-02 is non-CCS tape, so secondary error code
9313 	 * is in byte 8.  However, in SCSI-2, tape has CCS definition
9314 	 * so it's in byte 12.
9315 	 */
9316 	if (un->un_dp->type == ST_TYPE_EMULEX) {
9317 		sensep->es_code = sensep->es_add_info[0];
9318 	}
9319 
9320 	ST_CDB(ST_DEVINFO, "st_decode_sense failed CDB",
9321 	    (caddr_t)&CDBP(pkt)->scc_cmd);
9322 
9323 	ST_SENSE(ST_DEVINFO, "st_decode_sense sense data", (caddr_t)sensep,
9324 	    sizeof (*sensep));
9325 
9326 	/* for normal I/O check extract the resid values. */
9327 	if (bp != un->un_sbufp) {
9328 		if (sensep->es_valid) {
9329 			resid =
9330 			    (sensep->es_info_1 << 24) |
9331 			    (sensep->es_info_2 << 16) |
9332 			    (sensep->es_info_3 << 8)  |
9333 			    (sensep->es_info_4);
9334 			/* If fixed block */
9335 			if (un->un_bsize) {
9336 				resid *= un->un_bsize;
9337 			}
9338 		} else if (pkt->pkt_state & STATE_XFERRED_DATA) {
9339 			resid = pkt->pkt_resid;
9340 		} else {
9341 			resid = bp->b_bcount;
9342 		}
9343 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9344 		    "st_handle_sense (rw): xferred bit = %d, resid=%ld (%d), "
9345 		    "pkt_resid=%ld\n", pkt->pkt_state & STATE_XFERRED_DATA,
9346 		    resid,
9347 		    (sensep->es_info_1 << 24) |
9348 		    (sensep->es_info_2 << 16) |
9349 		    (sensep->es_info_3 << 8)  |
9350 		    (sensep->es_info_4),
9351 		    pkt->pkt_resid);
9352 		/*
9353 		 * The problem is, what should we believe?
9354 		 */
9355 		if (resid && (pkt->pkt_resid == 0)) {
9356 			pkt->pkt_resid = resid;
9357 		}
9358 	} else {
9359 		/*
9360 		 * If the command is SCMD_SPACE, we need to get the
9361 		 * residual as returned in the sense data, to adjust
9362 		 * our idea of current tape position correctly
9363 		 */
9364 		if ((CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
9365 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
9366 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) ||
9367 		    (CDBP(pkt)->scc_cmd == SCMD_WRITE_FILE_MARK) &&
9368 		    (sensep->es_valid)) {
9369 			resid =
9370 			    (sensep->es_info_1 << 24) |
9371 			    (sensep->es_info_2 << 16) |
9372 			    (sensep->es_info_3 << 8)  |
9373 			    (sensep->es_info_4);
9374 			bp->b_resid = resid;
9375 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9376 			    "st_handle_sense(other):	resid=%ld\n", resid);
9377 		} else {
9378 			/*
9379 			 * If the special command is SCMD_READ,
9380 			 * the correct resid will be set later.
9381 			 */
9382 			resid = bp->b_bcount;
9383 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9384 			    "st_handle_sense(special read):  resid=%ld\n",
9385 			    resid);
9386 		}
9387 	}
9388 
9389 	if ((un->un_state >= ST_STATE_OPEN) &&
9390 	    (DEBUGGING || st_error_level == SCSI_ERR_ALL)) {
9391 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
9392 		    "Failed CDB", (char *)pkt->pkt_cdbp);
9393 		st_clean_print(ST_DEVINFO, st_label, CE_CONT,
9394 		    "sense data", (char *)sensep, amt);
9395 		scsi_log(ST_DEVINFO, st_label, CE_CONT,
9396 		    "count 0x%lx resid 0x%lx pktresid 0x%lx\n",
9397 		    bp->b_bcount, resid, pkt->pkt_resid);
9398 	}
9399 
9400 	switch (un->un_status = sensep->es_key) {
9401 	case KEY_NO_SENSE:
9402 		severity = SCSI_ERR_INFO;
9403 
9404 		/*
9405 		 * Erase, locate or rewind operation in progress, retry
9406 		 * ASC  ASCQ
9407 		 *  00   18    Erase operation in progress
9408 		 *  00   19    Locate operation in progress
9409 		 *  00   1A    Rewind operation in progress
9410 		 */
9411 		if (sensep->es_add_code == 0 &&
9412 		    ((sensep->es_qual_code == 0x18) ||
9413 		    (sensep->es_qual_code == 0x19) ||
9414 		    (sensep->es_qual_code == 0x1a))) {
9415 			rval = QUE_COMMAND;
9416 			break;
9417 		}
9418 
9419 		goto common;
9420 
9421 	case KEY_RECOVERABLE_ERROR:
9422 		severity = SCSI_ERR_RECOVERED;
9423 		if ((sensep->es_class == CLASS_EXTENDED_SENSE) &&
9424 		    (sensep->es_code == ST_DEFERRED_ERROR)) {
9425 			if (un->un_dp->options &
9426 			    ST_RETRY_ON_RECOVERED_DEFERRED_ERROR) {
9427 				rval = QUE_LAST_COMMAND;
9428 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
9429 				    severity, un->un_pos.lgclblkno,
9430 				    un->un_err_pos.lgclblkno, scsi_cmds,
9431 				    sensep);
9432 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
9433 				    "Command will be retried\n");
9434 			} else {
9435 				severity = SCSI_ERR_FATAL;
9436 				rval = COMMAND_DONE_ERROR_RECOVERED;
9437 				ST_DO_ERRSTATS(un, st_softerrs);
9438 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
9439 				    severity, un->un_pos.lgclblkno,
9440 				    un->un_err_pos.lgclblkno, scsi_cmds,
9441 				    sensep);
9442 			}
9443 			break;
9444 		}
9445 common:
9446 		/*
9447 		 * XXX only want reads to be stopped by filemarks.
9448 		 * Don't want them to be stopped by EOT.  EOT matters
9449 		 * only on write.
9450 		 */
9451 		if (sensep->es_filmk && !sensep->es_eom) {
9452 			rval = COMMAND_DONE;
9453 		} else if (sensep->es_eom) {
9454 			rval = COMMAND_DONE;
9455 		} else if (sensep->es_ili) {
9456 			/*
9457 			 * Fun with variable length record devices:
9458 			 * for specifying larger blocks sizes than the
9459 			 * actual physical record size.
9460 			 */
9461 			if (un->un_bsize == 0 && resid > 0) {
9462 				/*
9463 				 * XXX! Ugly.
9464 				 * The requested blocksize is > tape blocksize,
9465 				 * so this is ok, so we just return the
9466 				 * actual size xferred.
9467 				 */
9468 				pkt->pkt_resid = resid;
9469 				rval = COMMAND_DONE;
9470 			} else if (un->un_bsize == 0 && resid < 0) {
9471 				/*
9472 				 * The requested blocksize is < tape blocksize,
9473 				 * so this is not ok, so we err with ENOMEM
9474 				 */
9475 				rval = COMMAND_DONE_ERROR_RECOVERED;
9476 				st_bioerror(bp, ENOMEM);
9477 			} else {
9478 				ST_DO_ERRSTATS(un, st_softerrs);
9479 				severity = SCSI_ERR_FATAL;
9480 				rval = COMMAND_DONE_ERROR;
9481 				st_bioerror(bp, EINVAL);
9482 			}
9483 		} else {
9484 			/*
9485 			 * we hope and pray for this just being
9486 			 * something we can ignore (ie. a
9487 			 * truly recoverable soft error)
9488 			 */
9489 			rval = COMMAND_DONE;
9490 		}
9491 		if (sensep->es_filmk) {
9492 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9493 			    "filemark\n");
9494 			un->un_status = SUN_KEY_EOF;
9495 			un->un_pos.eof = ST_EOF_PENDING;
9496 			SET_PE_FLAG(un);
9497 		}
9498 
9499 		/*
9500 		 * ignore eom when reading, a fmk should terminate reading
9501 		 */
9502 		if ((sensep->es_eom) &&
9503 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
9504 			if ((sensep->es_add_code == 0) &&
9505 			    (sensep->es_qual_code == 4)) {
9506 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9507 				    "bot\n");
9508 				un->un_status = SUN_KEY_BOT;
9509 				un->un_pos.eof = ST_NO_EOF;
9510 				un->un_pos.lgclblkno = 0;
9511 				un->un_pos.fileno = 0;
9512 				un->un_pos.blkno = 0;
9513 				un->un_pos.pmode = legacy;
9514 			} else {
9515 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9516 				    "eom\n");
9517 				un->un_status = SUN_KEY_EOT;
9518 				un->un_pos.eof = ST_EOM;
9519 			}
9520 			SET_PE_FLAG(un);
9521 		}
9522 
9523 		break;
9524 
9525 	case KEY_ILLEGAL_REQUEST:
9526 
9527 		if (un->un_laststate >= ST_STATE_OPEN) {
9528 			ST_DO_ERRSTATS(un, st_softerrs);
9529 			severity = SCSI_ERR_FATAL;
9530 		} else {
9531 			severity = SCSI_ERR_INFO;
9532 		}
9533 		break;
9534 
9535 	case KEY_MEDIUM_ERROR:
9536 		ST_DO_ERRSTATS(un, st_harderrs);
9537 		severity = SCSI_ERR_FATAL;
9538 
9539 		/*
9540 		 * for (buffered) writes, a medium error must be fatal
9541 		 */
9542 		if (CDBP(pkt)->scc_cmd != SCMD_WRITE) {
9543 			rval = COMMAND_DONE_ERROR_RECOVERED;
9544 		}
9545 
9546 check_keys:
9547 		/*
9548 		 * attempt to process the keys in the presence of
9549 		 * other errors
9550 		 */
9551 		if (sensep->es_ili && rval != COMMAND_DONE_ERROR) {
9552 			/*
9553 			 * Fun with variable length record devices:
9554 			 * for specifying larger blocks sizes than the
9555 			 * actual physical record size.
9556 			 */
9557 			if (un->un_bsize == 0 && resid > 0) {
9558 				/*
9559 				 * XXX! Ugly
9560 				 */
9561 				pkt->pkt_resid = resid;
9562 			} else if (un->un_bsize == 0 && resid < 0) {
9563 				st_bioerror(bp, EINVAL);
9564 			} else {
9565 				severity = SCSI_ERR_FATAL;
9566 				rval = COMMAND_DONE_ERROR;
9567 				st_bioerror(bp, EINVAL);
9568 			}
9569 		}
9570 		if (sensep->es_filmk) {
9571 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9572 			    "filemark\n");
9573 			un->un_status = SUN_KEY_EOF;
9574 			un->un_pos.eof = ST_EOF_PENDING;
9575 			SET_PE_FLAG(un);
9576 		}
9577 
9578 		/*
9579 		 * ignore eom when reading, a fmk should terminate reading
9580 		 */
9581 		if ((sensep->es_eom) &&
9582 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
9583 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "eom\n");
9584 			un->un_status = SUN_KEY_EOT;
9585 			un->un_pos.eof = ST_EOM;
9586 			SET_PE_FLAG(un);
9587 		}
9588 
9589 		break;
9590 
9591 	case KEY_VOLUME_OVERFLOW:
9592 		ST_DO_ERRSTATS(un, st_softerrs);
9593 		un->un_pos.eof = ST_EOM;
9594 		severity = SCSI_ERR_FATAL;
9595 		rval = COMMAND_DONE_ERROR;
9596 		goto check_keys;
9597 
9598 	case KEY_HARDWARE_ERROR:
9599 		ST_DO_ERRSTATS(un, st_harderrs);
9600 		severity = SCSI_ERR_FATAL;
9601 		rval = COMMAND_DONE_ERROR;
9602 		if (un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE)
9603 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
9604 		break;
9605 
9606 	case KEY_BLANK_CHECK:
9607 		ST_DO_ERRSTATS(un, st_softerrs);
9608 		severity = SCSI_ERR_INFO;
9609 
9610 		/*
9611 		 * if not a special request and some data was xferred then it
9612 		 * it is not an error yet
9613 		 */
9614 		if (bp != un->un_sbufp && (bp->b_flags & B_READ)) {
9615 			/*
9616 			 * no error for read with or without data xferred
9617 			 */
9618 			un->un_status = SUN_KEY_EOT;
9619 			un->un_pos.eof = ST_EOT;
9620 			rval = COMMAND_DONE_ERROR;
9621 			SET_PE_FLAG(un);
9622 			goto check_keys;
9623 		} else if (bp != un->un_sbufp &&
9624 		    (pkt->pkt_state & STATE_XFERRED_DATA)) {
9625 			rval = COMMAND_DONE;
9626 		} else {
9627 			rval = COMMAND_DONE_ERROR_RECOVERED;
9628 		}
9629 
9630 		if (un->un_laststate >= ST_STATE_OPEN) {
9631 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9632 			    "blank check\n");
9633 			un->un_pos.eof = ST_EOM;
9634 		}
9635 		if ((CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
9636 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
9637 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) &&
9638 		    (un->un_dp->options & ST_KNOWS_EOD)) {
9639 			/*
9640 			 * we were doing a fast forward by skipping
9641 			 * multiple fmk at the time
9642 			 */
9643 			st_bioerror(bp, EIO);
9644 			severity = SCSI_ERR_RECOVERED;
9645 			rval	 = COMMAND_DONE;
9646 		}
9647 		SET_PE_FLAG(un);
9648 		goto check_keys;
9649 
9650 	case KEY_WRITE_PROTECT:
9651 		if (st_wrongtapetype(un)) {
9652 			un->un_status = SUN_KEY_WRONGMEDIA;
9653 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9654 		"wrong tape for writing- use DC6150 tape (or equivalent)\n");
9655 			severity = SCSI_ERR_UNKNOWN;
9656 		} else {
9657 			severity = SCSI_ERR_FATAL;
9658 		}
9659 		ST_DO_ERRSTATS(un, st_harderrs);
9660 		rval = COMMAND_DONE_ERROR;
9661 		st_bioerror(bp, EACCES);
9662 		break;
9663 
9664 	case KEY_UNIT_ATTENTION:
9665 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9666 		    "KEY_UNIT_ATTENTION : un_state = %d\n", un->un_state);
9667 
9668 		/*
9669 		 * If we have detected a Bus Reset and the tape
9670 		 * drive has been reserved.
9671 		 */
9672 		if (ST_RQSENSE->es_add_code == 0x29 &&
9673 		    (un->un_rsvd_status & ST_RESERVE)) {
9674 			un->un_rsvd_status |= ST_LOST_RESERVE;
9675 			ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
9676 			    "st_decode_sense: Lost Reservation\n");
9677 		}
9678 
9679 		if (un->un_state <= ST_STATE_OPENING) {
9680 			/*
9681 			 * Look, the tape isn't open yet, now determine
9682 			 * if the cause is a BUS RESET, Save the file and
9683 			 * Block positions for the callers to recover from
9684 			 * the loss of position.
9685 			 */
9686 			if (un->un_pos.pmode != invalid) {
9687 				if (ST_RQSENSE->es_add_code == 0x29) {
9688 					un->un_save_fileno = un->un_pos.fileno;
9689 					un->un_save_blkno = un->un_pos.blkno;
9690 					un->un_restore_pos = 1;
9691 				}
9692 			}
9693 
9694 			if ((int)un->un_retry_ct++ < st_retry_count) {
9695 				rval = QUE_COMMAND;
9696 			} else {
9697 				rval = COMMAND_DONE_ERROR;
9698 			}
9699 			severity = SCSI_ERR_INFO;
9700 
9701 		} else {
9702 			/*
9703 			 * Check if it is an Unexpected Unit Attention.
9704 			 * If state is >= ST_STATE_OPEN, we have
9705 			 * already done the initialization .
9706 			 * In this case it is Fatal Error
9707 			 * since no further reading/writing
9708 			 * can be done with fileno set to < 0.
9709 			 */
9710 			if (un->un_state >= ST_STATE_OPEN) {
9711 				ST_DO_ERRSTATS(un, st_harderrs);
9712 				severity = SCSI_ERR_FATAL;
9713 			} else {
9714 				severity = SCSI_ERR_INFO;
9715 			}
9716 			rval = COMMAND_DONE_ERROR;
9717 		}
9718 		un->un_pos.pmode = invalid;
9719 
9720 		break;
9721 
9722 	case KEY_NOT_READY:
9723 		/*
9724 		 * If in process of getting ready retry.
9725 		 */
9726 		if (sensep->es_add_code  == 0x04 &&
9727 		    sensep->es_qual_code == 0x01 &&
9728 		    un->un_retry_ct++ < st_retry_count) {
9729 			rval = QUE_COMMAND;
9730 			severity = SCSI_ERR_INFO;
9731 		} else {
9732 			/* give up */
9733 			rval = COMMAND_DONE_ERROR;
9734 			severity = SCSI_ERR_FATAL;
9735 		}
9736 
9737 		/*
9738 		 * If this was an error and after device opened
9739 		 * do error stats.
9740 		 */
9741 		if (rval == COMMAND_DONE_ERROR &&
9742 		    un->un_state > ST_STATE_OPENING) {
9743 			ST_DO_ERRSTATS(un, st_harderrs);
9744 		}
9745 
9746 		if (ST_RQSENSE->es_add_code == 0x3a) {
9747 			if (st_error_level >= SCSI_ERR_FATAL)
9748 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
9749 				    "Tape not inserted in drive\n");
9750 			un->un_mediastate = MTIO_EJECTED;
9751 			cv_broadcast(&un->un_state_cv);
9752 		}
9753 		if ((un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE) &&
9754 		    (rval != QUE_COMMAND))
9755 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
9756 		break;
9757 
9758 	case KEY_ABORTED_COMMAND:
9759 
9760 		/*
9761 		 * Probably a parity error...
9762 		 * if we retry here then this may cause data to be
9763 		 * written twice or data skipped during reading
9764 		 */
9765 		ST_DO_ERRSTATS(un, st_harderrs);
9766 		severity = SCSI_ERR_FATAL;
9767 		rval = COMMAND_DONE_ERROR;
9768 		goto check_keys;
9769 
9770 	default:
9771 		/*
9772 		 * Undecoded sense key.	 Try retries and hope
9773 		 * that will fix the problem.  Otherwise, we're
9774 		 * dead.
9775 		 */
9776 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9777 		    "Unhandled Sense Key '%s'\n",
9778 		    sense_keys[un->un_status]);
9779 		ST_DO_ERRSTATS(un, st_harderrs);
9780 		severity = SCSI_ERR_FATAL;
9781 		rval = COMMAND_DONE_ERROR;
9782 		goto check_keys;
9783 	}
9784 
9785 	if ((!(pkt->pkt_flags & FLAG_SILENT) &&
9786 	    un->un_state >= ST_STATE_OPEN) && (DEBUGGING ||
9787 	    (un->un_laststate > ST_STATE_OPENING) &&
9788 	    (severity >= st_error_level))) {
9789 
9790 		scsi_errmsg(ST_SCSI_DEVP, pkt, st_label, severity,
9791 		    un->un_pos.lgclblkno, un->un_err_pos.lgclblkno,
9792 		    scsi_cmds, sensep);
9793 		if (sensep->es_filmk) {
9794 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9795 			    "File Mark Detected\n");
9796 		}
9797 		if (sensep->es_eom) {
9798 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9799 			    "End-of-Media Detected\n");
9800 		}
9801 		if (sensep->es_ili) {
9802 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9803 			    "Incorrect Length Indicator Set\n");
9804 		}
9805 	}
9806 	get_error = geterror(bp);
9807 	if (((rval == COMMAND_DONE_ERROR) ||
9808 	    (rval == COMMAND_DONE_ERROR_RECOVERED)) &&
9809 	    ((get_error == EIO) || (get_error == 0))) {
9810 		un->un_rqs_state |= (ST_RQS_ERROR | ST_RQS_VALID);
9811 		bcopy(ST_RQSENSE, un->un_uscsi_rqs_buf, SENSE_LENGTH);
9812 		if (un->un_rqs_state & ST_RQS_READ) {
9813 			un->un_rqs_state &= ~(ST_RQS_READ);
9814 		} else {
9815 			un->un_rqs_state |= ST_RQS_OVR;
9816 		}
9817 	}
9818 
9819 	return (rval);
9820 }
9821 
9822 
9823 static int
9824 st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp)
9825 {
9826 	int status = TRAN_ACCEPT;
9827 
9828 	mutex_enter(ST_MUTEX);
9829 
9830 	ST_FUNC(ST_DEVINFO, st_handle_intr_retry_lcmd);
9831 
9832 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9833 	    "st_handle_intr_rtr_lcmd(), un = 0x%p\n", (void *)un);
9834 
9835 	/*
9836 	 * Check to see if we hit the retry timeout. We check to make sure
9837 	 * this is the first one on the runq and make sure we have not
9838 	 * queued up any more, so this one has to be the last on the list
9839 	 * also. If it is not, we have to fail.  If it is not the first, but
9840 	 * is the last we are in trouble anyway, as we are in the interrupt
9841 	 * context here.
9842 	 */
9843 	if (((int)un->un_retry_ct > st_retry_count) ||
9844 	    ((un->un_runqf != bp) && (un->un_runql != bp))) {
9845 		goto exit;
9846 	}
9847 
9848 	if (un->un_throttle) {
9849 		un->un_last_throttle = un->un_throttle;
9850 		un->un_throttle = 0;
9851 	}
9852 
9853 	/*
9854 	 * Here we know : bp is the first and last one on the runq
9855 	 * it is not necessary to put it back on the head of the
9856 	 * waitq and then move from waitq to runq. Save this queuing
9857 	 * and call scsi_transport.
9858 	 */
9859 
9860 	mutex_exit(ST_MUTEX);
9861 
9862 	status = scsi_transport(BP_PKT(bp));
9863 
9864 	mutex_enter(ST_MUTEX);
9865 
9866 	if (status == TRAN_ACCEPT) {
9867 		un->un_tran_retry_ct = 0;
9868 		if (un->un_last_throttle) {
9869 			un->un_throttle = un->un_last_throttle;
9870 		}
9871 		mutex_exit(ST_MUTEX);
9872 
9873 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9874 		    "restart transport \n");
9875 		return (0);
9876 	}
9877 
9878 	ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9879 	mutex_exit(ST_MUTEX);
9880 
9881 	if (status == TRAN_BUSY) {
9882 		if (st_handle_intr_busy(un, bp, ST_TRAN_BUSY_TIMEOUT) == 0) {
9883 			return (0);
9884 		}
9885 	}
9886 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9887 	    "restart transport rejected\n");
9888 	mutex_enter(ST_MUTEX);
9889 	ST_DO_ERRSTATS(un, st_transerrs);
9890 	if (un->un_last_throttle) {
9891 		un->un_throttle = un->un_last_throttle;
9892 	}
9893 exit:
9894 	mutex_exit(ST_MUTEX);
9895 	return (-1);
9896 }
9897 
9898 static int
9899 st_wrongtapetype(struct scsi_tape *un)
9900 {
9901 
9902 	ST_FUNC(ST_DEVINFO, st_wrongtapetype);
9903 
9904 	ASSERT(mutex_owned(ST_MUTEX));
9905 
9906 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_wrongtapetype()\n");
9907 
9908 	/*
9909 	 * Hack to handle  600A, 600XTD, 6150 && 660 vs. 300XL tapes...
9910 	 */
9911 	if (un->un_dp && (un->un_dp->options & ST_QIC) && un->un_mspl) {
9912 		switch (un->un_dp->type) {
9913 		case ST_TYPE_WANGTEK:
9914 		case ST_TYPE_ARCHIVE:
9915 			/*
9916 			 * If this really worked, we could go off of
9917 			 * the density codes set in the modesense
9918 			 * page. For this drive, 0x10 == QIC-120,
9919 			 * 0xf == QIC-150, and 0x5 should be for
9920 			 * both QIC-24 and, maybe, QIC-11. However,
9921 			 * the h/w doesn't do what the manual says
9922 			 * that it should, so we'll key off of
9923 			 * getting a WRITE PROTECT error AND wp *not*
9924 			 * set in the mode sense information.
9925 			 */
9926 			/*
9927 			 * XXX but we already know that status is
9928 			 * write protect, so don't check it again.
9929 			 */
9930 
9931 			if (un->un_status == KEY_WRITE_PROTECT &&
9932 			    un->un_mspl->wp == 0) {
9933 				return (1);
9934 			}
9935 			break;
9936 		default:
9937 			break;
9938 		}
9939 	}
9940 	return (0);
9941 }
9942 
9943 static int
9944 st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt)
9945 {
9946 	int action;
9947 
9948 	ST_FUNC(ST_DEVINFO, st_check_error);
9949 
9950 	ASSERT(mutex_owned(ST_MUTEX));
9951 
9952 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_error()\n");
9953 
9954 	if (SCBP_C(pkt) == STATUS_RESERVATION_CONFLICT) {
9955 		action = COMMAND_DONE_EACCES;
9956 		un->un_rsvd_status |= ST_RESERVATION_CONFLICT;
9957 	} else if (SCBP(pkt)->sts_busy) {
9958 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG, "unit busy\n");
9959 		if ((int)un->un_retry_ct++ < st_retry_count) {
9960 			action = QUE_BUSY_COMMAND;
9961 		} else if ((un->un_rsvd_status &
9962 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
9963 			/*
9964 			 * If this is a command done before reserve is done
9965 			 * don't reset.
9966 			 */
9967 			action = COMMAND_DONE_ERROR;
9968 		} else {
9969 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
9970 			    "unit busy too long\n");
9971 			mutex_exit(ST_MUTEX);
9972 			if (scsi_reset(ROUTE, RESET_TARGET) == 0) {
9973 				(void) scsi_reset(ROUTE, RESET_ALL);
9974 			}
9975 			mutex_enter(ST_MUTEX);
9976 			action = COMMAND_DONE_ERROR;
9977 		}
9978 	} else if (SCBP(pkt)->sts_chk) {
9979 		/*
9980 		 * we should only get here if the auto rqsense failed
9981 		 * thru a uscsi cmd without autorequest sense
9982 		 * so we just try again
9983 		 */
9984 		action = QUE_SENSE;
9985 	} else {
9986 		action = COMMAND_DONE;
9987 	}
9988 	return (action);
9989 }
9990 
9991 static void
9992 st_calc_bnum(struct scsi_tape *un, struct buf *bp)
9993 {
9994 	int nblks;
9995 
9996 	ST_FUNC(ST_DEVINFO, st_calc_bnum);
9997 
9998 	ASSERT(mutex_owned(ST_MUTEX));
9999 
10000 	/* If variable block mode */
10001 	if (un->un_bsize == 0) {
10002 		nblks = ((bp->b_bcount - bp->b_resid  == 0) ? 0 : 1);
10003 		un->un_kbytes_xferred += (bp->b_bcount - bp->b_resid) / ONE_K;
10004 	} else {
10005 		nblks = ((bp->b_bcount - bp->b_resid) / un->un_bsize);
10006 		un->un_kbytes_xferred += (nblks * un->un_bsize) / ONE_K;
10007 	}
10008 	un->un_pos.blkno += nblks;
10009 	un->un_pos.lgclblkno += nblks;
10010 }
10011 
10012 static void
10013 st_set_state(struct scsi_tape *un)
10014 {
10015 	struct buf *bp = un->un_runqf;
10016 	struct scsi_pkt *sp = BP_PKT(bp);
10017 	struct uscsi_cmd *ucmd;
10018 
10019 	ST_FUNC(ST_DEVINFO, st_set_state);
10020 
10021 	ASSERT(mutex_owned(ST_MUTEX));
10022 
10023 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10024 	    "st_set_state(): eof=%x	fmneeded=%x  pkt_resid=0x%lx (%ld)\n",
10025 	    un->un_pos.eof, un->un_fmneeded, sp->pkt_resid, sp->pkt_resid);
10026 
10027 	if (bp != un->un_sbufp) {
10028 #ifdef STDEBUG
10029 		if (DEBUGGING && sp->pkt_resid) {
10030 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10031 			    "pkt_resid %ld bcount %ld\n",
10032 			    sp->pkt_resid, bp->b_bcount);
10033 		}
10034 #endif
10035 		bp->b_resid = sp->pkt_resid;
10036 		st_calc_bnum(un, bp);
10037 		if (bp->b_flags & B_READ) {
10038 			un->un_lastop = ST_OP_READ;
10039 			un->un_fmneeded = 0;
10040 		} else {
10041 			un->un_lastop = ST_OP_WRITE;
10042 			if (un->un_dp->options & ST_REEL) {
10043 				un->un_fmneeded = 2;
10044 			} else {
10045 				un->un_fmneeded = 1;
10046 			}
10047 		}
10048 		/*
10049 		 * all is honky dory at this point, so let's
10050 		 * readjust the throttle, to increase speed, if we
10051 		 * have not throttled down.
10052 		 */
10053 		if (un->un_throttle) {
10054 			un->un_throttle = un->un_max_throttle;
10055 		}
10056 	} else {
10057 		optype new_lastop;
10058 		uchar_t cmd = (uchar_t)(intptr_t)bp->b_forw;
10059 
10060 		un->un_lastop = ST_OP_CTL;
10061 
10062 		switch (cmd) {
10063 		case SCMD_WRITE:
10064 			bp->b_resid = sp->pkt_resid;
10065 			new_lastop = ST_OP_WRITE;
10066 			st_calc_bnum(un, bp);
10067 			if (un->un_dp->options & ST_REEL) {
10068 				un->un_fmneeded = 2;
10069 			} else {
10070 				un->un_fmneeded = 1;
10071 			}
10072 			break;
10073 		case SCMD_READ:
10074 			bp->b_resid = sp->pkt_resid;
10075 			new_lastop = ST_OP_READ;
10076 			st_calc_bnum(un, bp);
10077 			un->un_fmneeded = 0;
10078 			break;
10079 		case SCMD_WRITE_FILE_MARK:
10080 		{
10081 			int fmdone;
10082 
10083 			if (un->un_pos.eof != ST_EOM) {
10084 				un->un_pos.eof = ST_NO_EOF;
10085 			}
10086 			fmdone = (bp->b_bcount - bp->b_resid);
10087 			if (fmdone > 0) {
10088 				un->un_lastop = new_lastop = ST_OP_WEOF;
10089 				un->un_pos.lgclblkno += fmdone;
10090 				un->un_pos.fileno += fmdone;
10091 				un->un_pos.blkno = 0;
10092 			} else {
10093 				new_lastop = ST_OP_CTL;
10094 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
10095 				    "Flushed buffer\n");
10096 			}
10097 			if (fmdone > un->un_fmneeded) {
10098 				un->un_fmneeded = 0;
10099 			} else {
10100 				un->un_fmneeded -= fmdone;
10101 			}
10102 			break;
10103 		}
10104 		case SCMD_REWIND:
10105 			un->un_pos.eof = ST_NO_EOF;
10106 			un->un_pos.fileno = 0;
10107 			un->un_pos.blkno = 0;
10108 			un->un_pos.lgclblkno = 0;
10109 			un->un_pos.pmode = legacy;
10110 			new_lastop = ST_OP_CTL;
10111 			break;
10112 
10113 		case SCMD_SPACE:
10114 		{
10115 			int count;
10116 			long resid;
10117 			int done;
10118 
10119 			count = (int)SPACE_CNT(bp->b_bcount);
10120 			/* if was a uscsi space cmd b_bcount == 0 */
10121 			if (count == 0) {
10122 				count =
10123 				    (sp->pkt_cdbp[2] << 16) |
10124 				    (sp->pkt_cdbp[3] << 8)  |
10125 				    (sp->pkt_cdbp[4]);
10126 			}
10127 			resid = (long)SPACE_CNT(bp->b_resid);
10128 			if (count >= 0) {
10129 				done = (count - resid);
10130 			} else {
10131 				done = ((-count) - resid);
10132 			}
10133 			if (done > 0) {
10134 				un->un_lastop = new_lastop = ST_OP_CTL;
10135 			} else {
10136 				new_lastop = ST_OP_CTL;
10137 			}
10138 
10139 			ST_SPAC(ST_DEVINFO, st_label, SCSI_DEBUG,
10140 			    "space cmd: cdb[1] = %s\n"
10141 			    "space data:       = 0x%lx\n"
10142 			    "space count:      = %d\n"
10143 			    "space resid:      = %ld\n"
10144 			    "spaces done:      = %d\n"
10145 			    "fileno before     = %d\n"
10146 			    "blkno before      = %d\n",
10147 			    space_strs[sp->pkt_cdbp[1] & 7],
10148 			    bp->b_bcount,
10149 			    count, resid, done,
10150 			    un->un_pos.fileno, un->un_pos.blkno);
10151 
10152 			switch (sp->pkt_cdbp[1]) {
10153 			case SPACE_TYPE(SP_FLM):
10154 				/* Space file forward */
10155 				if (count >= 0) {
10156 					if (un->un_pos.eof <= ST_EOF) {
10157 						un->un_pos.eof = ST_NO_EOF;
10158 					}
10159 					un->un_pos.fileno += done;
10160 					un->un_pos.blkno = 0;
10161 					break;
10162 				}
10163 				/* Space file backward */
10164 				if (done > un->un_pos.fileno) {
10165 					un->un_pos.fileno = 0;
10166 					un->un_pos.blkno = 0;
10167 				} else {
10168 					un->un_pos.fileno -= done;
10169 					un->un_pos.blkno = INF;
10170 				}
10171 				break;
10172 			case SPACE_TYPE(SP_BLK):
10173 				/* Space block forward */
10174 				if (count >= 0) {
10175 					un->un_pos.blkno += done;
10176 					break;
10177 				}
10178 				/* Space block backward */
10179 				if (un->un_pos.eof >= ST_EOF_PENDING) {
10180 				/*
10181 				 * we stepped back into
10182 				 * a previous file; we are not
10183 				 * making an effort to pretend that
10184 				 * we are still in the current file
10185 				 * ie. logical == physical position
10186 				 * and leave it to st_ioctl to correct
10187 				 */
10188 					if (done > un->un_pos.blkno) {
10189 						un->un_pos.blkno = 0;
10190 					} else {
10191 						un->un_pos.fileno--;
10192 						un->un_pos.blkno = INF;
10193 					}
10194 				} else {
10195 					un->un_pos.blkno -= done;
10196 				}
10197 				break;
10198 			case SPACE_TYPE(SP_SQFLM):
10199 				un->un_pos.pmode = logical;
10200 				un->un_pos.blkno = 0;
10201 				un->un_lastop = new_lastop = ST_OP_CTL;
10202 				break;
10203 			case SPACE_TYPE(SP_EOD):
10204 				un->un_pos.pmode = logical;
10205 				un->un_pos.eof = ST_EOM;
10206 				un->un_status = KEY_BLANK_CHECK;
10207 				break;
10208 			default:
10209 				un->un_pos.pmode = invalid;
10210 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
10211 				    "Unsupported space cmd: %s\n",
10212 				    space_strs[sp->pkt_cdbp[1] & 7]);
10213 
10214 				un->un_lastop = new_lastop = ST_OP_CTL;
10215 			}
10216 
10217 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10218 			    "after_space rs %ld fil %d blk %d\n",
10219 			    resid, un->un_pos.fileno, un->un_pos.blkno);
10220 
10221 			break;
10222 		}
10223 		case SCMD_LOAD:
10224 			if ((bp->b_bcount & (LD_LOAD | LD_EOT)) == LD_LOAD) {
10225 				un->un_pos.fileno = 0;
10226 				un->un_pos.pmode = legacy;
10227 			} else {
10228 				un->un_state = ST_STATE_OFFLINE;
10229 				un->un_pos.pmode = invalid;
10230 			}
10231 			un->un_density_known = 0;
10232 			un->un_pos.eof = ST_NO_EOF;
10233 			un->un_pos.blkno = 0;
10234 			un->un_lastop = new_lastop = ST_OP_CTL;
10235 			break;
10236 		case SCMD_ERASE:
10237 			un->un_pos.eof = ST_NO_EOF;
10238 			un->un_pos.blkno = 0;
10239 			un->un_pos.fileno = 0;
10240 			un->un_pos.lgclblkno = 0;
10241 			un->un_pos.pmode = legacy;
10242 			new_lastop = ST_OP_CTL;
10243 			break;
10244 		case SCMD_RESERVE:
10245 			un->un_rsvd_status |= ST_RESERVE;
10246 			un->un_rsvd_status &=
10247 			    ~(ST_RELEASE | ST_LOST_RESERVE |
10248 			    ST_RESERVATION_CONFLICT);
10249 			new_lastop = un->un_lastop;
10250 			break;
10251 		case SCMD_RELEASE:
10252 			un->un_rsvd_status |= ST_RELEASE;
10253 			un->un_rsvd_status &=
10254 			    ~(ST_RESERVE | ST_LOST_RESERVE |
10255 			    ST_RESERVATION_CONFLICT);
10256 			new_lastop = ST_OP_CTL;
10257 			break;
10258 		case SCMD_PERSISTENT_RESERVE_IN:
10259 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10260 			    "PGR_IN command\n");
10261 			break;
10262 		case SCMD_PERSISTENT_RESERVE_OUT:
10263 			switch (sp->pkt_cdbp[1] & ST_SA_MASK) {
10264 			case ST_SA_SCSI3_RESERVE:
10265 			case ST_SA_SCSI3_PREEMPT:
10266 			case ST_SA_SCSI3_PREEMPTANDABORT:
10267 				un->un_rsvd_status |=
10268 				    ST_APPLICATION_RESERVATIONS;
10269 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10270 				    "PGR Reserve and set: entering"
10271 				    " ST_APPLICATION_RESERVATIONS mode");
10272 				break;
10273 			case ST_SA_SCSI3_RELEASE:
10274 			case ST_SA_SCSI3_CLEAR:
10275 				un->un_rsvd_status &=
10276 				    ~ST_APPLICATION_RESERVATIONS;
10277 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10278 				    "PGR Release and reset: exiting"
10279 				    " ST_APPLICATION_RESERVATIONS mode");
10280 				break;
10281 			}
10282 			break;
10283 		case SCMD_TEST_UNIT_READY:
10284 		case SCMD_READ_BLKLIM:
10285 		case SCMD_REQUEST_SENSE:
10286 		case SCMD_INQUIRY:
10287 		case SCMD_RECOVER_BUF:
10288 		case SCMD_MODE_SELECT:
10289 		case SCMD_MODE_SENSE:
10290 		case SCMD_DOORLOCK:
10291 		case SCMD_READ_BUFFER:
10292 		case SCMD_REPORT_DENSITIES:
10293 		case SCMD_LOG_SELECT_G1:
10294 		case SCMD_LOG_SENSE_G1:
10295 		case SCMD_REPORT_LUNS:
10296 		case SCMD_READ_ATTRIBUTE:
10297 		case SCMD_READ_MEDIA_SERIAL:
10298 			new_lastop = ST_OP_CTL;
10299 			break;
10300 		case SCMD_READ_POSITION:
10301 			new_lastop = ST_OP_CTL;
10302 			if (USCSI_CMD(bp)) {
10303 				(void) st_get_read_pos(un, bp);
10304 			}
10305 			break;
10306 		case SCMD_LOCATE:
10307 		case SCMD_LOCATE_G4:
10308 			/* Locate makes position mode no longer legacy */
10309 			un->un_lastop = new_lastop = ST_OP_CTL;
10310 			break;
10311 		default:
10312 			/*
10313 			 * Unknown command, If was USCSI and USCSI_SILENT
10314 			 * flag was not set, set position to unknown.
10315 			 */
10316 			if ((((ucmd = BP_UCMD(bp)) != NULL) &&
10317 			    (ucmd->uscsi_flags & USCSI_SILENT) == 0)) {
10318 				ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
10319 				    "unknown cmd 0x%X caused loss of state\n",
10320 				    cmd);
10321 			} else {
10322 				break;
10323 			}
10324 			/* FALLTHROUGH */
10325 		case SCMD_WRITE_BUFFER: /* Writes new firmware to device */
10326 			un->un_pos.pmode = invalid;
10327 			un->un_lastop = new_lastop = ST_OP_CTL;
10328 			break;
10329 		}
10330 
10331 		/* new_lastop should have been changed */
10332 		ASSERT(new_lastop != ST_OP_NIL);
10333 
10334 		/* If un_lastop should copy new_lastop  */
10335 		if (((un->un_lastop == ST_OP_WRITE) ||
10336 		    (un->un_lastop == ST_OP_WEOF)) &&
10337 		    new_lastop != ST_OP_CTL) {
10338 			un->un_lastop = new_lastop;
10339 		}
10340 	}
10341 
10342 	/*
10343 	 * In the st driver we have a logical and physical file position.
10344 	 * Under BSD behavior, when you get a zero read, the logical position
10345 	 * is before the filemark but after the last record of the file.
10346 	 * The physical position is after the filemark. MTIOCGET should always
10347 	 * return the logical file position.
10348 	 *
10349 	 * The next read gives a silent skip to the next file.
10350 	 * Under SVR4, the logical file position remains before the filemark
10351 	 * until the file is closed or a space operation is performed.
10352 	 * Hence set err_resid and err_file before changing fileno if case
10353 	 * BSD Behaviour.
10354 	 */
10355 	un->un_err_resid = bp->b_resid;
10356 	COPY_POS(&un->un_err_pos, &un->un_pos);
10357 	un->un_retry_ct = 0;
10358 
10359 
10360 	/*
10361 	 * If we've seen a filemark via the last read operation
10362 	 * advance the file counter, but mark things such that
10363 	 * the next read operation gets a zero count. We have
10364 	 * to put this here to handle the case of sitting right
10365 	 * at the end of a tape file having seen the file mark,
10366 	 * but the tape is closed and then re-opened without
10367 	 * any further i/o. That is, the position information
10368 	 * must be updated before a close.
10369 	 */
10370 
10371 	if (un->un_lastop == ST_OP_READ && un->un_pos.eof == ST_EOF_PENDING) {
10372 		/*
10373 		 * If we're a 1/2" tape, and we get a filemark
10374 		 * right on block 0, *AND* we were not in the
10375 		 * first file on the tape, and we've hit logical EOM.
10376 		 * We'll mark the state so that later we do the
10377 		 * right thing (in st_close(), st_strategy() or
10378 		 * st_ioctl()).
10379 		 *
10380 		 */
10381 		if ((un->un_dp->options & ST_REEL) &&
10382 		    !(un->un_dp->options & ST_READ_IGNORE_EOFS) &&
10383 		    un->un_pos.blkno == 0 && un->un_pos.fileno > 0) {
10384 			un->un_pos.eof = ST_EOT_PENDING;
10385 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10386 			    "eot pending\n");
10387 			un->un_pos.fileno++;
10388 			un->un_pos.blkno = 0;
10389 		} else if (BSD_BEHAVIOR) {
10390 			/*
10391 			 * If the read of the filemark was a side effect
10392 			 * of reading some blocks (i.e., data was actually
10393 			 * read), then the EOF mark is pending and the
10394 			 * bump into the next file awaits the next read
10395 			 * operation (which will return a zero count), or
10396 			 * a close or a space operation, else the bump
10397 			 * into the next file occurs now.
10398 			 */
10399 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10400 			    "resid=%lx, bcount=%lx\n",
10401 			    bp->b_resid, bp->b_bcount);
10402 
10403 			if (bp->b_resid != bp->b_bcount) {
10404 				un->un_pos.eof = ST_EOF;
10405 			} else {
10406 				un->un_silent_skip = 1;
10407 				un->un_pos.eof = ST_NO_EOF;
10408 				un->un_pos.fileno++;
10409 				un->un_pos.lgclblkno++;
10410 				un->un_save_blkno = un->un_pos.blkno;
10411 				un->un_pos.blkno = 0;
10412 			}
10413 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10414 			    "eof of file %d, eof=%d\n",
10415 			    un->un_pos.fileno, un->un_pos.eof);
10416 		} else if (SVR4_BEHAVIOR) {
10417 			/*
10418 			 * If the read of the filemark was a side effect
10419 			 * of reading some blocks (i.e., data was actually
10420 			 * read), then the next read should return 0
10421 			 */
10422 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10423 			    "resid=%lx, bcount=%lx\n",
10424 			    bp->b_resid, bp->b_bcount);
10425 			if (bp->b_resid == bp->b_bcount) {
10426 				un->un_pos.eof = ST_EOF;
10427 			}
10428 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10429 			    "eof of file=%d, eof=%d\n",
10430 			    un->un_pos.fileno, un->un_pos.eof);
10431 		}
10432 	}
10433 }
10434 
10435 /*
10436  * set the correct un_errno, to take corner cases into consideration
10437  */
10438 static void
10439 st_set_pe_errno(struct scsi_tape *un)
10440 {
10441 	ST_FUNC(ST_DEVINFO, st_set_pe_errno);
10442 
10443 	ASSERT(mutex_owned(ST_MUTEX));
10444 
10445 	/* if errno is already set, don't reset it */
10446 	if (un->un_errno)
10447 		return;
10448 
10449 	/* here un_errno == 0 */
10450 	/*
10451 	 * if the last transfer before flushing all the
10452 	 * waiting I/O's, was 0 (resid = count), then we
10453 	 * want to give the user an error on all the rest,
10454 	 * so here.  If there was a transfer, we set the
10455 	 * resid and counts to 0, and let it drop through,
10456 	 * giving a zero return.  the next I/O will then
10457 	 * give an error.
10458 	 */
10459 	if (un->un_last_resid == un->un_last_count) {
10460 		switch (un->un_pos.eof) {
10461 		case ST_EOM:
10462 			un->un_errno = ENOMEM;
10463 			break;
10464 		case ST_EOT:
10465 		case ST_EOF:
10466 			un->un_errno = EIO;
10467 			break;
10468 		}
10469 	} else {
10470 		/*
10471 		 * we know they did not have a zero, so make
10472 		 * sure they get one
10473 		 */
10474 		un->un_last_resid = un->un_last_count = 0;
10475 	}
10476 }
10477 
10478 
10479 /*
10480  * send in a marker pkt to terminate flushing of commands by BBA (via
10481  * flush-on-errors) property.  The HBA will always return TRAN_ACCEPT
10482  */
10483 static void
10484 st_hba_unflush(struct scsi_tape *un)
10485 {
10486 	ST_FUNC(ST_DEVINFO, st_hba_unflush);
10487 
10488 	ASSERT(mutex_owned(ST_MUTEX));
10489 
10490 	if (!un->un_flush_on_errors)
10491 		return;
10492 
10493 #ifdef FLUSH_ON_ERRORS
10494 
10495 	if (!un->un_mkr_pkt) {
10496 		un->un_mkr_pkt = scsi_init_pkt(ROUTE, NULL, (struct buf *)NULL,
10497 		    NULL, 0, 0, 0, SLEEP_FUNC, NULL);
10498 
10499 		/* we slept, so it must be there */
10500 		pkt->pkt_flags |= FLAG_FLUSH_MARKER;
10501 	}
10502 
10503 	mutex_exit(ST_MUTEX);
10504 	scsi_transport(un->un_mkr_pkt);
10505 	mutex_enter(ST_MUTEX);
10506 #endif
10507 }
10508 
10509 static char *
10510 st_print_scsi_cmd(char cmd)
10511 {
10512 	char tmp[64];
10513 	char *cpnt;
10514 
10515 	cpnt = scsi_cmd_name(cmd, scsi_cmds, tmp);
10516 	/* tmp goes out of scope on return and caller sees garbage */
10517 	if (cpnt == tmp) {
10518 		cpnt = "Unknown Command";
10519 	}
10520 	return (cpnt);
10521 }
10522 
10523 static void
10524 st_print_cdb(dev_info_t *dip, char *label, uint_t level,
10525     char *title, char *cdb)
10526 {
10527 	int len = scsi_cdb_size[CDB_GROUPID(cdb[0])];
10528 	char buf[256];
10529 	int instance = ddi_get_instance(dip);
10530 	struct scsi_tape *un;
10531 
10532 	un = ddi_get_soft_state(st_state, instance);
10533 
10534 	ST_FUNC(dip, st_print_cdb);
10535 
10536 #ifdef DEBUG
10537 	if ((st_debug & 0x180) == 0x100) {
10538 		scsi_log(dip, label, level, "node %s cmd %s\n",
10539 		    st_dev_name(un->un_dev), st_print_scsi_cmd(*cdb));
10540 		return;
10541 	}
10542 #endif
10543 	(void) sprintf(buf, "%s for cmd(%s)", title, st_print_scsi_cmd(*cdb));
10544 	st_clean_print(dip, label, level, buf, cdb, len);
10545 }
10546 
10547 static void
10548 st_clean_print(dev_info_t *dev, char *label, uint_t level,
10549     char *title, char *data, int len)
10550 {
10551 	int	i;
10552 	int 	c;
10553 	char	*format;
10554 	char	buf[256];
10555 	uchar_t	byte;
10556 
10557 	ST_FUNC(dev, st_clean_print);
10558 
10559 	(void) sprintf(buf, "%s:\n", title);
10560 	scsi_log(dev, label, level, "%s", buf);
10561 	level = CE_CONT;
10562 	for (i = 0; i < len; ) {
10563 		buf[0] = 0;
10564 		for (c = 0; c < 8 && i < len; c++, i++) {
10565 			byte = (uchar_t)data[i];
10566 			if (byte < 0x10)
10567 				format = "0x0%x ";
10568 			else
10569 				format = "0x%x ";
10570 			(void) sprintf(&buf[(int)strlen(buf)], format, byte);
10571 		}
10572 		(void) sprintf(&buf[(int)strlen(buf)], "\n");
10573 
10574 		scsi_log(dev, label, level, "%s\n", buf);
10575 	}
10576 }
10577 
10578 /*
10579  * Conditionally enabled debugging
10580  */
10581 #ifdef	STDEBUG
10582 static void
10583 st_debug_cmds(struct scsi_tape *un, int com, int count, int wait)
10584 {
10585 	char tmpbuf[64];
10586 
10587 	ST_FUNC(ST_DEVINFO, st_debug_cmds);
10588 
10589 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10590 	    "cmd=%s count=0x%x (%d)	 %ssync\n",
10591 	    scsi_cmd_name(com, scsi_cmds, tmpbuf),
10592 	    count, count,
10593 	    wait == ASYNC_CMD ? "a" : "");
10594 }
10595 
10596 /*
10597  * Returns pointer to name of minor node name of device 'dev'.
10598  */
10599 static char *
10600 st_dev_name(dev_t dev)
10601 {
10602 	struct scsi_tape *un;
10603 	const char density[] = { 'l', 'm', 'h', 'c' };
10604 	static char name[4];
10605 	minor_t minor;
10606 	int instance;
10607 	int nprt = 0;
10608 
10609 	minor = getminor(dev);
10610 	instance = ((minor & 0xff80) >> 5) | (minor & 3);
10611 	un = ddi_get_soft_state(st_state, instance);
10612 	if (un) {
10613 		ST_FUNC(ST_DEVINFO, st_dev_name);
10614 	}
10615 
10616 	name[nprt] = density[(minor & MT_DENSITY_MASK) >> 3];
10617 
10618 	if (minor & MT_BSD) {
10619 		name[++nprt] = 'b';
10620 	}
10621 
10622 	if (minor & MT_NOREWIND) {
10623 		name[++nprt] = 'n';
10624 	}
10625 
10626 	/* NULL terminator */
10627 	name[++nprt] = 0;
10628 
10629 	return (name);
10630 }
10631 #endif	/* STDEBUG */
10632 
10633 /*
10634  * Soft error reporting, so far unique to each drive
10635  *
10636  * Currently supported: exabyte and DAT soft error reporting
10637  */
10638 static int
10639 st_report_exabyte_soft_errors(dev_t dev, int flag)
10640 {
10641 	uchar_t *sensep;
10642 	int amt;
10643 	int rval = 0;
10644 	char cdb[CDB_GROUP0], *c = cdb;
10645 	struct uscsi_cmd *com;
10646 
10647 	GET_SOFT_STATE(dev);
10648 
10649 	ST_FUNC(ST_DEVINFO, st_report_exabyte_soft_errors);
10650 
10651 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10652 	    "st_report_exabyte_soft_errors(dev = 0x%lx, flag = %d)\n",
10653 	    dev, flag);
10654 
10655 	ASSERT(mutex_owned(ST_MUTEX));
10656 
10657 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
10658 	sensep = kmem_zalloc(TAPE_SENSE_LENGTH, KM_SLEEP);
10659 
10660 	*c++ = SCMD_REQUEST_SENSE;
10661 	*c++ = 0;
10662 	*c++ = 0;
10663 	*c++ = 0;
10664 	*c++ = TAPE_SENSE_LENGTH;
10665 	/*
10666 	 * set CLRCNT (byte 5, bit 7 which clears the error counts)
10667 	 */
10668 	*c   = (char)0x80;
10669 
10670 	com->uscsi_cdb = cdb;
10671 	com->uscsi_cdblen = CDB_GROUP0;
10672 	com->uscsi_bufaddr = (caddr_t)sensep;
10673 	com->uscsi_buflen = TAPE_SENSE_LENGTH;
10674 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
10675 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
10676 
10677 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
10678 	if (rval || com->uscsi_status) {
10679 		goto done;
10680 	}
10681 
10682 	/*
10683 	 * was there enough data?
10684 	 */
10685 	amt = (int)TAPE_SENSE_LENGTH - com->uscsi_resid;
10686 
10687 	if ((amt >= 19) && un->un_kbytes_xferred) {
10688 		uint_t count, error_rate;
10689 		uint_t rate;
10690 
10691 		if (sensep[21] & CLN) {
10692 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
10693 			    "Periodic head cleaning required");
10694 		}
10695 		if (un->un_kbytes_xferred < (EXABYTE_MIN_TRANSFER/ONE_K)) {
10696 			goto done;
10697 		}
10698 		/*
10699 		 * check if soft error reporting needs to be done.
10700 		 */
10701 		count = sensep[16] << 16 | sensep[17] << 8 | sensep[18];
10702 		count &= 0xffffff;
10703 		error_rate = (count * 100)/un->un_kbytes_xferred;
10704 
10705 #ifdef	STDEBUG
10706 		if (st_soft_error_report_debug) {
10707 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
10708 			    "Exabyte Soft Error Report:\n");
10709 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10710 			    "read/write error counter: %d\n", count);
10711 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10712 			    "number of bytes transferred: %dK\n",
10713 			    un->un_kbytes_xferred);
10714 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10715 			    "error_rate: %d%%\n", error_rate);
10716 
10717 			if (amt >= 22) {
10718 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10719 				    "unit sense: 0x%b 0x%b 0x%b\n",
10720 				    sensep[19], SENSE_19_BITS,
10721 				    sensep[20], SENSE_20_BITS,
10722 				    sensep[21], SENSE_21_BITS);
10723 			}
10724 			if (amt >= 27) {
10725 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10726 				    "tracking retry counter: %d\n",
10727 				    sensep[26]);
10728 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10729 				    "read/write retry counter: %d\n",
10730 				    sensep[27]);
10731 			}
10732 		}
10733 #endif
10734 
10735 		if (flag & FWRITE) {
10736 			rate = EXABYTE_WRITE_ERROR_THRESHOLD;
10737 		} else {
10738 			rate = EXABYTE_READ_ERROR_THRESHOLD;
10739 		}
10740 		if (error_rate >= rate) {
10741 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
10742 			    "Soft error rate (%d%%) during %s was too high",
10743 			    error_rate,
10744 			    ((flag & FWRITE) ? wrg_str : rdg_str));
10745 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10746 			    "Please, replace tape cartridge\n");
10747 		}
10748 	}
10749 
10750 done:
10751 	kmem_free(com, sizeof (*com));
10752 	kmem_free(sensep, TAPE_SENSE_LENGTH);
10753 
10754 	if (rval != 0) {
10755 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10756 		    "exabyte soft error reporting failed\n");
10757 	}
10758 	return (rval);
10759 }
10760 
10761 /*
10762  * this is very specific to Archive 4mm dat
10763  */
10764 #define	ONE_GIG	(ONE_K * ONE_K * ONE_K)
10765 
10766 static int
10767 st_report_dat_soft_errors(dev_t dev, int flag)
10768 {
10769 	uchar_t *sensep;
10770 	int amt, i;
10771 	int rval = 0;
10772 	char cdb[CDB_GROUP1], *c = cdb;
10773 	struct uscsi_cmd *com;
10774 
10775 	GET_SOFT_STATE(dev);
10776 
10777 	ST_FUNC(ST_DEVINFO, st_report_dat_soft_errors);
10778 
10779 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10780 	    "st_report_dat_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
10781 
10782 	ASSERT(mutex_owned(ST_MUTEX));
10783 
10784 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
10785 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
10786 
10787 	*c++ = SCMD_LOG_SENSE_G1;
10788 	*c++ = 0;
10789 	*c++ = (flag & FWRITE) ? 0x42 : 0x43;
10790 	*c++ = 0;
10791 	*c++ = 0;
10792 	*c++ = 0;
10793 	*c++ = 2;
10794 	*c++ = 0;
10795 	*c++ = (char)LOG_SENSE_LENGTH;
10796 	*c   = 0;
10797 	com->uscsi_cdb    = cdb;
10798 	com->uscsi_cdblen  = CDB_GROUP1;
10799 	com->uscsi_bufaddr = (caddr_t)sensep;
10800 	com->uscsi_buflen  = LOG_SENSE_LENGTH;
10801 	com->uscsi_flags   =
10802 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
10803 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
10804 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
10805 	if (rval) {
10806 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10807 		    "DAT soft error reporting failed\n");
10808 	}
10809 	if (rval || com->uscsi_status) {
10810 		goto done;
10811 	}
10812 
10813 	/*
10814 	 * was there enough data?
10815 	 */
10816 	amt = (int)LOG_SENSE_LENGTH - com->uscsi_resid;
10817 
10818 	if ((amt >= MIN_LOG_SENSE_LENGTH) && un->un_kbytes_xferred) {
10819 		int total, retries, param_code;
10820 
10821 		total = -1;
10822 		retries = -1;
10823 		amt = sensep[3] + 4;
10824 
10825 
10826 #ifdef STDEBUG
10827 		if (st_soft_error_report_debug) {
10828 			(void) printf("logsense:");
10829 			for (i = 0; i < MIN_LOG_SENSE_LENGTH; i++) {
10830 				if (i % 16 == 0) {
10831 					(void) printf("\t\n");
10832 				}
10833 				(void) printf(" %x", sensep[i]);
10834 			}
10835 			(void) printf("\n");
10836 		}
10837 #endif
10838 
10839 		/*
10840 		 * parse the param_codes
10841 		 */
10842 		if (sensep[0] == 2 || sensep[0] == 3) {
10843 			for (i = 4; i < amt; i++) {
10844 				param_code = (sensep[i++] << 8);
10845 				param_code += sensep[i++];
10846 				i++; /* skip control byte */
10847 				if (param_code == 5) {
10848 					if (sensep[i++] == 4) {
10849 						total = (sensep[i++] << 24);
10850 						total += (sensep[i++] << 16);
10851 						total += (sensep[i++] << 8);
10852 						total += sensep[i];
10853 					}
10854 				} else if (param_code == 0x8007) {
10855 					if (sensep[i++] == 2) {
10856 						retries = sensep[i++] << 8;
10857 						retries += sensep[i];
10858 					}
10859 				} else {
10860 					i += sensep[i];
10861 				}
10862 			}
10863 		}
10864 
10865 		/*
10866 		 * if the log sense returned valid numbers then determine
10867 		 * the read and write error thresholds based on the amount of
10868 		 * data transferred
10869 		 */
10870 
10871 		if (total > 0 && retries > 0) {
10872 			short normal_retries = 0;
10873 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10874 			    "total xferred (%s) =%x, retries=%x\n",
10875 			    ((flag & FWRITE) ? wrg_str : rdg_str),
10876 			    total, retries);
10877 
10878 			if (flag & FWRITE) {
10879 				if (total <=
10880 				    WRITE_SOFT_ERROR_WARNING_THRESHOLD) {
10881 					normal_retries =
10882 					    DAT_SMALL_WRITE_ERROR_THRESHOLD;
10883 				} else {
10884 					normal_retries =
10885 					    DAT_LARGE_WRITE_ERROR_THRESHOLD;
10886 				}
10887 			} else {
10888 				if (total <=
10889 				    READ_SOFT_ERROR_WARNING_THRESHOLD) {
10890 					normal_retries =
10891 					    DAT_SMALL_READ_ERROR_THRESHOLD;
10892 				} else {
10893 					normal_retries =
10894 					    DAT_LARGE_READ_ERROR_THRESHOLD;
10895 				}
10896 			}
10897 
10898 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10899 			"normal retries=%d\n", normal_retries);
10900 
10901 			if (retries >= normal_retries) {
10902 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
10903 				    "Soft error rate (retries = %d) during "
10904 				    "%s was too high",  retries,
10905 				    ((flag & FWRITE) ? wrg_str : rdg_str));
10906 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10907 				    "Periodic head cleaning required "
10908 				    "and/or replace tape cartridge\n");
10909 			}
10910 
10911 		} else if (total == -1 || retries == -1) {
10912 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
10913 			    "log sense parameter code does not make sense\n");
10914 		}
10915 	}
10916 
10917 	/*
10918 	 * reset all values
10919 	 */
10920 	c = cdb;
10921 	*c++ = SCMD_LOG_SELECT_G1;
10922 	*c++ = 2;	/* this resets all values */
10923 	*c++ = (char)0xc0;
10924 	*c++ = 0;
10925 	*c++ = 0;
10926 	*c++ = 0;
10927 	*c++ = 0;
10928 	*c++ = 0;
10929 	*c++ = 0;
10930 	*c   = 0;
10931 	com->uscsi_bufaddr = NULL;
10932 	com->uscsi_buflen  = 0;
10933 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT;
10934 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
10935 	if (rval) {
10936 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10937 		    "DAT soft error reset failed\n");
10938 	}
10939 done:
10940 	kmem_free(com, sizeof (*com));
10941 	kmem_free(sensep, LOG_SENSE_LENGTH);
10942 	return (rval);
10943 }
10944 
10945 static int
10946 st_report_soft_errors(dev_t dev, int flag)
10947 {
10948 	GET_SOFT_STATE(dev);
10949 
10950 	ST_FUNC(ST_DEVINFO, st_report_soft_errors);
10951 
10952 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10953 	    "st_report_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
10954 
10955 	ASSERT(mutex_owned(ST_MUTEX));
10956 
10957 	switch (un->un_dp->type) {
10958 	case ST_TYPE_EXB8500:
10959 	case ST_TYPE_EXABYTE:
10960 		return (st_report_exabyte_soft_errors(dev, flag));
10961 		/*NOTREACHED*/
10962 	case ST_TYPE_PYTHON:
10963 		return (st_report_dat_soft_errors(dev, flag));
10964 		/*NOTREACHED*/
10965 	default:
10966 		un->un_dp->options &= ~ST_SOFT_ERROR_REPORTING;
10967 		return (-1);
10968 	}
10969 }
10970 
10971 /*
10972  * persistent error routines
10973  */
10974 
10975 /*
10976  * enable persistent errors, and set the throttle appropriately, checking
10977  * for flush-on-errors capability
10978  */
10979 static void
10980 st_turn_pe_on(struct scsi_tape *un)
10981 {
10982 	ST_FUNC(ST_DEVINFO, st_turn_pe_on);
10983 
10984 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_on\n");
10985 	ASSERT(mutex_owned(ST_MUTEX));
10986 
10987 	un->un_persistence = 1;
10988 
10989 	/*
10990 	 * only use flush-on-errors if auto-request-sense and untagged-qing are
10991 	 * enabled.  This will simplify the error handling for request senses
10992 	 */
10993 
10994 	if (un->un_arq_enabled && un->un_untagged_qing) {
10995 		uchar_t f_o_e;
10996 
10997 		mutex_exit(ST_MUTEX);
10998 		f_o_e = (scsi_ifsetcap(ROUTE, "flush-on-errors", 1, 1) == 1) ?
10999 		    1 : 0;
11000 		mutex_enter(ST_MUTEX);
11001 
11002 		un->un_flush_on_errors = f_o_e;
11003 	} else {
11004 		un->un_flush_on_errors = 0;
11005 	}
11006 
11007 	if (un->un_flush_on_errors)
11008 		un->un_max_throttle = (uchar_t)st_max_throttle;
11009 	else
11010 		un->un_max_throttle = 1;
11011 
11012 	if (un->un_dp->options & ST_RETRY_ON_RECOVERED_DEFERRED_ERROR)
11013 		un->un_max_throttle = 1;
11014 
11015 	/* this will send a marker pkt */
11016 	CLEAR_PE(un);
11017 }
11018 
11019 /*
11020  * This turns persistent errors permanently off
11021  */
11022 static void
11023 st_turn_pe_off(struct scsi_tape *un)
11024 {
11025 	ST_FUNC(ST_DEVINFO, st_turn_pe_off);
11026 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_off\n");
11027 	ASSERT(mutex_owned(ST_MUTEX));
11028 
11029 	/* turn it off for good */
11030 	un->un_persistence = 0;
11031 
11032 	/* this will send a marker pkt */
11033 	CLEAR_PE(un);
11034 
11035 	/* turn off flush on error capability, if enabled */
11036 	if (un->un_flush_on_errors) {
11037 		mutex_exit(ST_MUTEX);
11038 		(void) scsi_ifsetcap(ROUTE, "flush-on-errors", 0, 1);
11039 		mutex_enter(ST_MUTEX);
11040 	}
11041 
11042 
11043 	un->un_flush_on_errors = 0;
11044 }
11045 
11046 /*
11047  * This clear persistent errors, allowing more commands through, and also
11048  * sending a marker packet.
11049  */
11050 static void
11051 st_clear_pe(struct scsi_tape *un)
11052 {
11053 	ST_FUNC(ST_DEVINFO, st_clear_pe);
11054 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_clear\n");
11055 	ASSERT(mutex_owned(ST_MUTEX));
11056 
11057 	un->un_persist_errors = 0;
11058 	un->un_throttle = un->un_last_throttle = 1;
11059 	un->un_errno = 0;
11060 	st_hba_unflush(un);
11061 }
11062 
11063 /*
11064  * This will flag persistent errors, shutting everything down, if the
11065  * application had enabled persistent errors via MTIOCPERSISTENT
11066  */
11067 static void
11068 st_set_pe_flag(struct scsi_tape *un)
11069 {
11070 	ST_FUNC(ST_DEVINFO, st_set_pe_flag);
11071 	ASSERT(mutex_owned(ST_MUTEX));
11072 
11073 	if (un->un_persistence) {
11074 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_flag\n");
11075 		un->un_persist_errors = 1;
11076 		un->un_throttle = un->un_last_throttle = 0;
11077 	}
11078 }
11079 
11080 /*
11081  * List of commands that are allowed to be done while another host holds
11082  * the reservation.
11083  */
11084 struct {
11085 	uchar_t cmd;
11086 	uchar_t byte;	/* byte to look for data */
11087 	uint32_t mask;	/* bits that matter in the above data */
11088 } rcmds[] = {
11089 	{ SCMD_TEST_UNIT_READY, 0, 0 }, /* may fail on older drives */
11090 	{ SCMD_REQUEST_SENSE, 0, 0 },
11091 	{ SCMD_READ_BLKLIM, 0, 0 },
11092 	{ SCMD_INQUIRY, 0, 0 },
11093 	{ SCMD_RESERVE, 0, 0 },
11094 	{ SCMD_RELEASE, 0, 0 },
11095 	{ SCMD_DOORLOCK, 4, 3 },	/* allow (unlock) media access only */
11096 	{ SCMD_REPORT_DENSITIES, 0, 0 },
11097 	{ SCMD_LOG_SENSE_G1, 0, 0 },
11098 	{ SCMD_PERSISTENT_RESERVE_IN, 0, 0 },
11099 	{ SCMD_PERSISTENT_RESERVE_OUT, 0, 0 },
11100 	{ SCMD_REPORT_LUNS, 0, 0 }
11101 };
11102 
11103 static int
11104 st_do_reserve(struct scsi_tape *un)
11105 {
11106 	int rval;
11107 
11108 	ST_FUNC(ST_DEVINFO, st_do_reserve);
11109 
11110 	/*
11111 	 * Issue a Throw-Away reserve command to clear the
11112 	 * check condition.
11113 	 * If the current behaviour of reserve/release is to
11114 	 * hold reservation across opens , and if a Bus reset
11115 	 * has been issued between opens then this command
11116 	 * would set the ST_LOST_RESERVE flags in rsvd_status.
11117 	 * In this case return an EACCES so that user knows that
11118 	 * reservation has been lost in between opens.
11119 	 * If this error is not returned and we continue with
11120 	 * successful open , then user may think position of the
11121 	 * tape is still the same but inreality we would rewind the
11122 	 * tape and continue from BOT.
11123 	 */
11124 	rval = st_reserve_release(un, ST_RESERVE);
11125 	if (rval) {
11126 		if ((un->un_rsvd_status & ST_LOST_RESERVE_BETWEEN_OPENS) ==
11127 		    ST_LOST_RESERVE_BETWEEN_OPENS) {
11128 			un->un_rsvd_status &= ~(ST_LOST_RESERVE | ST_RESERVE);
11129 			un->un_errno = EACCES;
11130 			return (EACCES);
11131 		}
11132 		rval = st_reserve_release(un, ST_RESERVE);
11133 	}
11134 	if (rval == 0) {
11135 		un->un_rsvd_status |= ST_INIT_RESERVE;
11136 	}
11137 
11138 	return (rval);
11139 }
11140 
11141 static int
11142 st_check_cdb_for_need_to_reserve(struct scsi_tape *un, caddr_t cdb)
11143 {
11144 	int i;
11145 	int rval = 0;
11146 
11147 	ST_FUNC(ST_DEVINFO, st_check_cdb_for_need_to_reserve);
11148 
11149 	/*
11150 	 * If already reserved no need to do it again.
11151 	 * Also if Reserve and Release are disabled Just return.
11152 	 */
11153 	if ((un->un_rsvd_status & (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ||
11154 	    (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
11155 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
11156 		    "st_check_cdb_for_need_to_reserve() reserve unneeded %s",
11157 		    st_print_scsi_cmd((uchar_t)cdb[0]));
11158 		return (0);
11159 	}
11160 
11161 	/* See if command is on the list */
11162 	for (i = 0; i < ST_NUM_MEMBERS(rcmds); i++) {
11163 		if ((uchar_t)cdb[0] == rcmds[i].cmd) {
11164 			/*
11165 			 * cmd is on list.
11166 			 * if byte is zero always allowed.
11167 			 */
11168 			if (rcmds[i].byte == 0) {
11169 				return (rval);
11170 			}
11171 			if (((cdb[rcmds[i].byte]) & (rcmds[i].mask)) == 0) {
11172 				return (rval);
11173 			}
11174 			break;
11175 		}
11176 	}
11177 
11178 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
11179 	    "Command %s requires reservation", st_print_scsi_cmd(cdb[0]));
11180 
11181 	rval = st_do_reserve(un);
11182 
11183 	return (rval);
11184 }
11185 
11186 static int
11187 st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd, int cnt)
11188 {
11189 	int i;
11190 	int rval = 0;
11191 
11192 	ST_FUNC(ST_DEVINFO, st_check_cmd_for_need_to_reserve);
11193 
11194 	if ((un->un_rsvd_status & (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ||
11195 	    (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
11196 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
11197 		    "st_check_cmd_for_need_to_reserve() reserve unneeded %s",
11198 		    st_print_scsi_cmd(cmd));
11199 		return (0);
11200 	}
11201 
11202 	/* See if command is on the list */
11203 	for (i = 0; i < ST_NUM_MEMBERS(rcmds); i++) {
11204 		if (cmd == rcmds[i].cmd) {
11205 			/*
11206 			 * cmd is on list.
11207 			 * if byte is zero always allowed.
11208 			 */
11209 			if (rcmds[i].byte == 0) {
11210 				return (rval);
11211 			}
11212 			if (((rcmds[i].mask) & cnt) == 0) {
11213 				return (rval);
11214 			}
11215 			break;
11216 		}
11217 	}
11218 
11219 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
11220 	    "Cmd %s requires reservation", st_print_scsi_cmd(cmd));
11221 
11222 	rval = st_do_reserve(un);
11223 
11224 	return (rval);
11225 }
11226 
11227 static int
11228 st_reserve_release(struct scsi_tape *un, int cmd)
11229 {
11230 	struct uscsi_cmd	uscsi_cmd;
11231 	struct uscsi_cmd	*com = &uscsi_cmd;
11232 	int			rval;
11233 	char			cdb[CDB_GROUP0];
11234 
11235 
11236 
11237 	ST_FUNC(ST_DEVINFO, st_reserve_release);
11238 
11239 	ASSERT(mutex_owned(ST_MUTEX));
11240 
11241 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11242 	    "st_reserve_release: %s \n",
11243 	    (cmd == ST_RELEASE)?  "Releasing":"Reserving");
11244 
11245 	bzero(cdb, CDB_GROUP0);
11246 	if (cmd == ST_RELEASE) {
11247 		cdb[0] = SCMD_RELEASE;
11248 	} else {
11249 		cdb[0] = SCMD_RESERVE;
11250 	}
11251 	bzero(com, sizeof (struct uscsi_cmd));
11252 	com->uscsi_flags = USCSI_WRITE;
11253 	com->uscsi_cdb = cdb;
11254 	com->uscsi_cdblen = CDB_GROUP0;
11255 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
11256 
11257 	rval = st_ioctl_cmd(un->un_dev, com, FKIOCTL);
11258 
11259 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11260 	    "st_reserve_release: rval(1)=%d\n", rval);
11261 
11262 	if (rval) {
11263 		if (com->uscsi_status == STATUS_RESERVATION_CONFLICT) {
11264 			rval = EACCES;
11265 		}
11266 		/*
11267 		 * dynamically turn off reserve/release support
11268 		 * in case of drives which do not support
11269 		 * reserve/release command(ATAPI drives).
11270 		 */
11271 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
11272 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
11273 				un->un_dp->options |= ST_NO_RESERVE_RELEASE;
11274 				ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11275 				    "Tape unit does not support "
11276 				    "reserve/release \n");
11277 			}
11278 			rval = 0;
11279 		}
11280 	}
11281 	return (rval);
11282 }
11283 
11284 static int
11285 st_take_ownership(dev_t dev)
11286 {
11287 	int rval;
11288 
11289 	GET_SOFT_STATE(dev);
11290 
11291 	ST_FUNC(ST_DEVINFO, st_take_ownership);
11292 
11293 	ASSERT(mutex_owned(ST_MUTEX));
11294 
11295 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11296 	    "st_take_ownership: Entering ...\n");
11297 
11298 
11299 	rval = st_reserve_release(un, ST_RESERVE);
11300 	/*
11301 	 * XXX -> Should reset be done only if we get EACCES.
11302 	 * .
11303 	 */
11304 	if (rval) {
11305 		mutex_exit(ST_MUTEX);
11306 		if (scsi_reset(ROUTE, RESET_TARGET) == 0) {
11307 			if (scsi_reset(ROUTE, RESET_ALL) == 0) {
11308 				mutex_enter(ST_MUTEX);
11309 				return (EIO);
11310 			}
11311 		}
11312 		mutex_enter(ST_MUTEX);
11313 		un->un_rsvd_status &=
11314 		    ~(ST_LOST_RESERVE | ST_RESERVATION_CONFLICT);
11315 
11316 		mutex_exit(ST_MUTEX);
11317 		delay(drv_usectohz(ST_RESERVATION_DELAY));
11318 		mutex_enter(ST_MUTEX);
11319 		/*
11320 		 * remove the check condition.
11321 		 */
11322 		(void) st_reserve_release(un, ST_RESERVE);
11323 		if ((rval = st_reserve_release(un, ST_RESERVE)) != 0) {
11324 			if ((st_reserve_release(un, ST_RESERVE)) != 0) {
11325 				rval = (un->un_rsvd_status &
11326 				    ST_RESERVATION_CONFLICT) ? EACCES : EIO;
11327 				return (rval);
11328 			}
11329 		}
11330 		/*
11331 		 * Set tape state to ST_STATE_OFFLINE , in case if
11332 		 * the user wants to continue and start using
11333 		 * the tape.
11334 		 */
11335 		un->un_state = ST_STATE_OFFLINE;
11336 		un->un_rsvd_status |= ST_INIT_RESERVE;
11337 	}
11338 	return (rval);
11339 }
11340 
11341 static int
11342 st_create_errstats(struct scsi_tape *un, int instance)
11343 {
11344 	char	kstatname[KSTAT_STRLEN];
11345 
11346 	ST_FUNC(ST_DEVINFO, st_create_errstats);
11347 
11348 	/*
11349 	 * Create device error kstats
11350 	 */
11351 
11352 	if (un->un_errstats == (kstat_t *)0) {
11353 		(void) sprintf(kstatname, "st%d,err", instance);
11354 		un->un_errstats = kstat_create("sterr", instance, kstatname,
11355 		    "device_error", KSTAT_TYPE_NAMED,
11356 		    sizeof (struct st_errstats) / sizeof (kstat_named_t),
11357 		    KSTAT_FLAG_PERSISTENT);
11358 
11359 		if (un->un_errstats) {
11360 			struct st_errstats	*stp;
11361 
11362 			stp = (struct st_errstats *)un->un_errstats->ks_data;
11363 			kstat_named_init(&stp->st_softerrs, "Soft Errors",
11364 			    KSTAT_DATA_ULONG);
11365 			kstat_named_init(&stp->st_harderrs, "Hard Errors",
11366 			    KSTAT_DATA_ULONG);
11367 			kstat_named_init(&stp->st_transerrs, "Transport Errors",
11368 			    KSTAT_DATA_ULONG);
11369 			kstat_named_init(&stp->st_vid, "Vendor",
11370 			    KSTAT_DATA_CHAR);
11371 			kstat_named_init(&stp->st_pid, "Product",
11372 			    KSTAT_DATA_CHAR);
11373 			kstat_named_init(&stp->st_revision, "Revision",
11374 			    KSTAT_DATA_CHAR);
11375 			kstat_named_init(&stp->st_serial, "Serial No",
11376 			    KSTAT_DATA_CHAR);
11377 			un->un_errstats->ks_private = un;
11378 			un->un_errstats->ks_update = nulldev;
11379 			kstat_install(un->un_errstats);
11380 			/*
11381 			 * Fill in the static data
11382 			 */
11383 			(void) strncpy(&stp->st_vid.value.c[0],
11384 			    ST_INQUIRY->inq_vid, 8);
11385 			/*
11386 			 * XXX:  Emulex MT-02 (and emulators) predates
11387 			 *	 SCSI-1 and has no vid & pid inquiry data.
11388 			 */
11389 			if (ST_INQUIRY->inq_len != 0) {
11390 				(void) strncpy(&stp->st_pid.value.c[0],
11391 				    ST_INQUIRY->inq_pid, 16);
11392 				(void) strncpy(&stp->st_revision.value.c[0],
11393 				    ST_INQUIRY->inq_revision, 4);
11394 				(void) strncpy(&stp->st_serial.value.c[0],
11395 				    ST_INQUIRY->inq_serial, 12);
11396 			}
11397 		}
11398 	}
11399 	return (0);
11400 }
11401 
11402 static int
11403 st_validate_tapemarks(struct scsi_tape *un, tapepos_t *pos)
11404 {
11405 	dev_t dev;
11406 	int rval;
11407 
11408 	ST_FUNC(ST_DEVINFO, st_validate_tapemarks);
11409 
11410 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
11411 	ASSERT(mutex_owned(ST_MUTEX));
11412 
11413 	/* Can't restore an invalid position */
11414 	if (pos->pmode == invalid) {
11415 		return (4);
11416 	}
11417 
11418 	/*
11419 	 * Assumtions:
11420 	 *	If a position was read and is in logical position mode.
11421 	 *	If a drive supports read position it supports locate.
11422 	 *	If the read position type is not NO_POS. even though
11423 	 *	   a read position make not have been attemped yet.
11424 	 *
11425 	 *	The drive can locate to the position.
11426 	 */
11427 	if (pos->pmode == logical || un->un_read_pos_type != NO_POS) {
11428 		/*
11429 		 * If position mode is logical or legacy mode try
11430 		 * to locate there as it is faster.
11431 		 * If it fails try the old way.
11432 		 */
11433 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
11434 		    "Restoring tape position to lgclblkbo=0x%"PRIx64"....",
11435 		    pos->lgclblkno);
11436 
11437 		if (st_logical_block_locate(un, pos->lgclblkno, pos->partition)
11438 		    == 0) {
11439 			/* Assume we are there copy rest of position back */
11440 			if (un->un_pos.lgclblkno == pos->lgclblkno) {
11441 				COPY_POS(&un->un_pos, pos);
11442 			}
11443 			return (0);
11444 		}
11445 
11446 		/*
11447 		 * If logical block locate failed to restore a logical
11448 		 * position, can't recover.
11449 		 */
11450 		if (pos->pmode == logical) {
11451 			return (-1);
11452 		}
11453 	}
11454 
11455 	dev = un->un_dev;
11456 
11457 	scsi_log(ST_DEVINFO, st_label, CE_NOTE,
11458 	    "Restoring tape position at fileno=%x, blkno=%x....",
11459 	    pos->fileno, pos->blkno);
11460 
11461 	/*
11462 	 * Rewind ? Oh yeah, Fidelity has got the STK F/W changed
11463 	 * so as not to rewind tape on RESETS: Gee, Has life ever
11464 	 * been simple in tape land ?
11465 	 */
11466 	rval = st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD);
11467 	if (rval) {
11468 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
11469 		"Failed to restore the last file and block position: In"
11470 		" this state, Tape will be loaded at BOT during next open");
11471 		un->un_pos.pmode = invalid;
11472 		return (rval);
11473 	}
11474 
11475 	/* If the position was as the result of back space file */
11476 	if (pos->blkno > (INF / 2)) {
11477 		/* Go one extra file forward */
11478 		pos->fileno++;
11479 		/* Figure how many blocks to back into the previous file */
11480 		pos->blkno = -(INF - pos->blkno);
11481 	}
11482 
11483 	/* Go to requested fileno */
11484 	if (pos->fileno) {
11485 		rval = st_cmd(dev, SCMD_SPACE, Fmk(pos->fileno), SYNC_CMD);
11486 		if (rval) {
11487 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
11488 			    "Failed to restore the last file position: In this "
11489 			    " state, Tape will be loaded at BOT during next"
11490 			    " open %d", __LINE__);
11491 			un->un_pos.pmode = invalid;
11492 			pos->pmode = invalid;
11493 			return (rval);
11494 		}
11495 	}
11496 
11497 	/*
11498 	 * If backing into a file we already did an extra file forward.
11499 	 * Now we have to back over the filemark to get to the end of
11500 	 * the previous file. The blkno has been ajusted to a negative
11501 	 * value so we will get to the expected location.
11502 	 */
11503 	if (pos->blkno) {
11504 		rval = st_cmd(dev, SCMD_SPACE, Fmk(-1), SYNC_CMD);
11505 		if (rval) {
11506 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
11507 			    "Failed to restore the last file position: In this "
11508 			    " state, Tape will be loaded at BOT during next"
11509 			    " open %d", __LINE__);
11510 			un->un_pos.pmode = invalid;
11511 			pos->pmode = invalid;
11512 			return (rval);
11513 		}
11514 	}
11515 
11516 	/*
11517 	 * The position mode, block and fileno should be correct,
11518 	 * This updates eof and logical position information.
11519 	 */
11520 	un->un_pos.eof = pos->eof;
11521 	un->un_pos.lgclblkno = pos->lgclblkno;
11522 
11523 	return (0);
11524 }
11525 
11526 /*
11527  * check sense key, ASC, ASCQ in order to determine if the tape needs
11528  * to be ejected
11529  */
11530 
11531 static int
11532 st_check_asc_ascq(struct scsi_tape *un)
11533 {
11534 	struct scsi_extended_sense *sensep = ST_RQSENSE;
11535 	struct tape_failure_code   *code;
11536 
11537 	ST_FUNC(ST_DEVINFO, st_check_asc_ascq);
11538 
11539 	for (code = st_tape_failure_code; code->key != 0xff; code++) {
11540 		if ((code->key  == sensep->es_key) &&
11541 		    (code->add_code  == sensep->es_add_code) &&
11542 		    (code->qual_code == sensep->es_qual_code))
11543 			return (1);
11544 	}
11545 	return (0);
11546 }
11547 
11548 /*
11549  * st_logpage_supported() sends a Log Sense command with
11550  * page code = 0 = Supported Log Pages Page to the device,
11551  * to see whether the page 'page' is supported.
11552  * Return values are:
11553  * -1 if the Log Sense command fails
11554  * 0 if page is not supported
11555  * 1 if page is supported
11556  */
11557 
11558 static int
11559 st_logpage_supported(dev_t dev, uchar_t page)
11560 {
11561 	uchar_t *sp, *sensep;
11562 	unsigned length;
11563 	struct uscsi_cmd *com;
11564 	int rval;
11565 	char cdb[CDB_GROUP1] = {
11566 		SCMD_LOG_SENSE_G1,
11567 		0,
11568 		SUPPORTED_LOG_PAGES_PAGE,
11569 		0,
11570 		0,
11571 		0,
11572 		0,
11573 		0,
11574 		(char)LOG_SENSE_LENGTH,
11575 		0
11576 	};
11577 
11578 	GET_SOFT_STATE(dev);
11579 
11580 	ST_FUNC(ST_DEVINFO, st_logpage_supported);
11581 
11582 	ASSERT(mutex_owned(ST_MUTEX));
11583 
11584 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
11585 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
11586 
11587 	com->uscsi_cdb = cdb;
11588 	com->uscsi_cdblen = CDB_GROUP1;
11589 	com->uscsi_bufaddr = (caddr_t)sensep;
11590 	com->uscsi_buflen = LOG_SENSE_LENGTH;
11591 	com->uscsi_flags =
11592 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
11593 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
11594 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
11595 	if (rval || com->uscsi_status) {
11596 		/* uscsi-command failed */
11597 		rval = -1;
11598 	} else {
11599 
11600 		sp = sensep + 3;
11601 
11602 		for (length = *sp++; length > 0; length--, sp++) {
11603 
11604 			if (*sp == page) {
11605 				rval = 1;
11606 				break;
11607 			}
11608 		}
11609 	}
11610 	kmem_free(com, sizeof (struct uscsi_cmd));
11611 	kmem_free(sensep, LOG_SENSE_LENGTH);
11612 	return (rval);
11613 }
11614 
11615 
11616 /*
11617  * st_check_clean_bit() gets the status of the tape's cleaning bit.
11618  *
11619  * If the device does support the TapeAlert log page, then the cleaning bit
11620  * information will be read from this page. Otherwise we will see if one of
11621  * ST_CLN_TYPE_1, ST_CLN_TYPE_2 or ST_CLN_TYPE_3 is set in the properties of
11622  * the device, which means, that we can get the cleaning bit information via
11623  * a RequestSense command.
11624  * If both methods of getting cleaning bit information are not supported
11625  * st_check_clean_bit() will return with 0. Otherwise st_check_clean_bit()
11626  * returns with
11627  * - MTF_TAPE_CLN_SUPPORTED if cleaning bit is not set or
11628  * - MTF_TAPE_CLN_SUPPORTED | MTF_TAPE_HEAD_DIRTY if cleaning bit is set.
11629  * If the call to st_ioctl_cmd() to do the Log Sense or the Request Sense
11630  * command fails, or if the amount of Request Sense data is not enough, then
11631  *  st_check_clean_bit() returns with -1.
11632  */
11633 
11634 static int
11635 st_check_clean_bit(dev_t dev)
11636 {
11637 	int rval = 0;
11638 
11639 	GET_SOFT_STATE(dev);
11640 
11641 	ST_FUNC(ST_DEVINFO, st_check_clean_bit);
11642 
11643 	ASSERT(mutex_owned(ST_MUTEX));
11644 
11645 	if (un->un_HeadClean & TAPE_ALERT_NOT_SUPPORTED) {
11646 		return (rval);
11647 	}
11648 
11649 	if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
11650 
11651 		rval = st_logpage_supported(dev, TAPE_SEQUENTIAL_PAGE);
11652 		if (rval == 1) {
11653 
11654 			un->un_HeadClean |= TAPE_SEQUENTIAL_SUPPORTED;
11655 		}
11656 
11657 		rval = st_logpage_supported(dev, TAPE_ALERT_PAGE);
11658 		if (rval == 1) {
11659 
11660 			un->un_HeadClean |= TAPE_ALERT_SUPPORTED;
11661 		}
11662 
11663 		if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
11664 
11665 			un->un_HeadClean = TAPE_ALERT_NOT_SUPPORTED;
11666 		}
11667 	}
11668 
11669 	rval = 0;
11670 
11671 	if (un->un_HeadClean & TAPE_SEQUENTIAL_SUPPORTED) {
11672 
11673 		rval = st_check_sequential_clean_bit(dev);
11674 	}
11675 
11676 	if ((rval <= 0) && (un->un_HeadClean & TAPE_ALERT_SUPPORTED)) {
11677 
11678 		rval = st_check_alert_flags(dev);
11679 	}
11680 
11681 	if ((rval <= 0) && (un->un_dp->options & ST_CLN_MASK)) {
11682 
11683 		rval = st_check_sense_clean_bit(dev);
11684 	}
11685 
11686 	if (rval < 0) {
11687 		return (rval);
11688 	}
11689 
11690 	/*
11691 	 * If found a supported means to check need to clean.
11692 	 */
11693 	if (rval & MTF_TAPE_CLN_SUPPORTED) {
11694 
11695 		/*
11696 		 * head needs to be cleaned.
11697 		 */
11698 		if (rval & MTF_TAPE_HEAD_DIRTY) {
11699 
11700 			/*
11701 			 * Print log message only first time
11702 			 * found needing cleaned.
11703 			 */
11704 			if ((un->un_HeadClean & TAPE_PREVIOUSLY_DIRTY) == 0) {
11705 
11706 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
11707 				    "Periodic head cleaning required");
11708 
11709 				un->un_HeadClean |= TAPE_PREVIOUSLY_DIRTY;
11710 			}
11711 
11712 		} else {
11713 
11714 			un->un_HeadClean &= ~TAPE_PREVIOUSLY_DIRTY;
11715 		}
11716 	}
11717 
11718 	return (rval);
11719 }
11720 
11721 
11722 static int
11723 st_check_sequential_clean_bit(dev_t dev)
11724 {
11725 	int rval;
11726 	int ix;
11727 	ushort_t parameter;
11728 	struct uscsi_cmd *cmd;
11729 	struct log_sequential_page *sp;
11730 	struct log_sequential_page_parameter *prm;
11731 	char cdb[CDB_GROUP1] = {
11732 		SCMD_LOG_SENSE_G1,
11733 		0,
11734 		TAPE_SEQUENTIAL_PAGE | CURRENT_CUMULATIVE_VALUES,
11735 		0,
11736 		0,
11737 		0,
11738 		0,
11739 		(char)(sizeof (struct log_sequential_page) >> 8),
11740 		(char)(sizeof (struct log_sequential_page)),
11741 		0
11742 	};
11743 
11744 	GET_SOFT_STATE(dev);
11745 
11746 	ST_FUNC(ST_DEVINFO, st_check_sequential_clean_bit);
11747 
11748 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
11749 	sp  = kmem_zalloc(sizeof (struct log_sequential_page), KM_SLEEP);
11750 
11751 	cmd->uscsi_flags   =
11752 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
11753 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
11754 	cmd->uscsi_cdb	   = cdb;
11755 	cmd->uscsi_cdblen  = CDB_GROUP1;
11756 	cmd->uscsi_bufaddr = (caddr_t)sp;
11757 	cmd->uscsi_buflen  = sizeof (struct log_sequential_page);
11758 
11759 	rval = st_ioctl_cmd(dev, cmd, FKIOCTL);
11760 
11761 	if (rval || cmd->uscsi_status || cmd->uscsi_resid) {
11762 
11763 		rval = -1;
11764 
11765 	} else if (sp->log_page.code != TAPE_SEQUENTIAL_PAGE) {
11766 
11767 		rval = -1;
11768 	}
11769 
11770 	prm = &sp->param[0];
11771 
11772 	for (ix = 0; rval == 0 && ix < TAPE_SEQUENTIAL_PAGE_PARA; ix++) {
11773 
11774 		if (prm->log_param.length == 0) {
11775 			break;
11776 		}
11777 
11778 		parameter = (((prm->log_param.pc_hi << 8) & 0xff00) +
11779 		    (prm->log_param.pc_lo & 0xff));
11780 
11781 		if (parameter == SEQUENTIAL_NEED_CLN) {
11782 
11783 			rval = MTF_TAPE_CLN_SUPPORTED;
11784 			if (prm->param_value[prm->log_param.length - 1]) {
11785 
11786 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11787 				    "sequential log says head dirty\n");
11788 				rval |= MTF_TAPE_HEAD_DIRTY;
11789 			}
11790 		}
11791 		prm = (struct log_sequential_page_parameter *)
11792 		    &prm->param_value[prm->log_param.length];
11793 	}
11794 
11795 	kmem_free(cmd, sizeof (struct uscsi_cmd));
11796 	kmem_free(sp,  sizeof (struct log_sequential_page));
11797 
11798 	return (rval);
11799 }
11800 
11801 
11802 static int
11803 st_check_alert_flags(dev_t dev)
11804 {
11805 	struct st_tape_alert *ta;
11806 	struct uscsi_cmd *com;
11807 	unsigned ix, length;
11808 	int rval;
11809 	tape_alert_flags flag;
11810 	char cdb[CDB_GROUP1] = {
11811 		SCMD_LOG_SENSE_G1,
11812 		0,
11813 		TAPE_ALERT_PAGE | CURRENT_THRESHOLD_VALUES,
11814 		0,
11815 		0,
11816 		0,
11817 		0,
11818 		(char)(sizeof (struct st_tape_alert) >> 8),
11819 		(char)(sizeof (struct st_tape_alert)),
11820 		0
11821 	};
11822 
11823 	GET_SOFT_STATE(dev);
11824 
11825 	ST_FUNC(ST_DEVINFO, st_check_alert_clean_bit);
11826 
11827 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
11828 	ta  = kmem_zalloc(sizeof (struct st_tape_alert), KM_SLEEP);
11829 
11830 	com->uscsi_cdb = cdb;
11831 	com->uscsi_cdblen = CDB_GROUP1;
11832 	com->uscsi_bufaddr = (caddr_t)ta;
11833 	com->uscsi_buflen = sizeof (struct st_tape_alert);
11834 	com->uscsi_flags =
11835 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
11836 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
11837 
11838 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
11839 
11840 	if (rval || com->uscsi_status || com->uscsi_resid) {
11841 
11842 		rval = -1; /* uscsi-command failed */
11843 
11844 	} else if (ta->log_page.code != TAPE_ALERT_PAGE) {
11845 
11846 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11847 		"Not Alert Log Page returned 0x%X\n", ta->log_page.code);
11848 		rval = -1;
11849 	}
11850 
11851 	length = (ta->log_page.length_hi << 8) + ta->log_page.length_lo;
11852 
11853 
11854 	if (length != TAPE_ALERT_PARAMETER_LENGTH) {
11855 
11856 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11857 		    "TapeAlert length %d\n", length);
11858 	}
11859 
11860 
11861 	for (ix = 0; ix < TAPE_ALERT_MAX_PARA; ix++) {
11862 
11863 		/*
11864 		 * if rval is bad before the first pass don't bother
11865 		 */
11866 		if (ix == 0 && rval != 0) {
11867 
11868 			break;
11869 		}
11870 
11871 		flag = ((ta->param[ix].log_param.pc_hi << 8) +
11872 		    ta->param[ix].log_param.pc_lo);
11873 
11874 		if ((ta->param[ix].param_value & 1) == 0) {
11875 			continue;
11876 		}
11877 		/*
11878 		 * check to see if current parameter is of interest.
11879 		 * CLEAN_FOR_ERRORS is vendor specific to 9840 9940 stk's.
11880 		 */
11881 		if ((flag == TAF_CLEAN_NOW) ||
11882 		    (flag == TAF_CLEAN_PERIODIC) ||
11883 		    ((flag == CLEAN_FOR_ERRORS) &&
11884 		    (un->un_dp->type == ST_TYPE_STK9840))) {
11885 
11886 			rval = MTF_TAPE_CLN_SUPPORTED;
11887 
11888 
11889 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11890 			    "alert_page drive needs clean %d\n", flag);
11891 			un->un_HeadClean |= TAPE_ALERT_STILL_DIRTY;
11892 			rval |= MTF_TAPE_HEAD_DIRTY;
11893 
11894 		} else if (flag == TAF_CLEANING_MEDIA) {
11895 
11896 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11897 			    "alert_page drive was cleaned\n");
11898 			un->un_HeadClean &= ~TAPE_ALERT_STILL_DIRTY;
11899 		}
11900 
11901 	}
11902 
11903 	/*
11904 	 * Report it as dirty till we see it cleaned
11905 	 */
11906 	if (un->un_HeadClean & TAPE_ALERT_STILL_DIRTY) {
11907 
11908 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11909 		    "alert_page still dirty\n");
11910 		rval |= MTF_TAPE_HEAD_DIRTY;
11911 	}
11912 
11913 	kmem_free(com, sizeof (struct uscsi_cmd));
11914 	kmem_free(ta,  sizeof (struct st_tape_alert));
11915 
11916 	return (rval);
11917 }
11918 
11919 
11920 static int
11921 st_check_sense_clean_bit(dev_t dev)
11922 {
11923 	uchar_t *sensep;
11924 	char cdb[CDB_GROUP0];
11925 	struct uscsi_cmd *com;
11926 	ushort_t byte_pos;
11927 	uchar_t bit_mask;
11928 	unsigned length;
11929 	int index;
11930 	int rval;
11931 
11932 	GET_SOFT_STATE(dev);
11933 
11934 	ST_FUNC(ST_DEVINFO, st_check_sense_clean_bit);
11935 
11936 	/*
11937 	 * Since this tape does not support Tape Alert,
11938 	 * we now try to get the cleanbit status via
11939 	 * Request Sense.
11940 	 */
11941 
11942 	if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_1) {
11943 
11944 		index = 0;
11945 
11946 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_2) {
11947 
11948 		index = 1;
11949 
11950 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_3) {
11951 
11952 		index = 2;
11953 
11954 	} else {
11955 
11956 		return (-1);
11957 	}
11958 
11959 	byte_pos  = st_cln_bit_position[index].cln_bit_byte;
11960 	bit_mask  = st_cln_bit_position[index].cln_bit_mask;
11961 	length = byte_pos + 1;
11962 
11963 	com    = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
11964 	sensep = kmem_zalloc(length, KM_SLEEP);
11965 
11966 	cdb[0] = SCMD_REQUEST_SENSE;
11967 	cdb[1] = 0;
11968 	cdb[2] = 0;
11969 	cdb[3] = 0;
11970 	cdb[4] = (char)length;
11971 	cdb[5] = 0;
11972 
11973 	com->uscsi_cdb = cdb;
11974 	com->uscsi_cdblen = CDB_GROUP0;
11975 	com->uscsi_bufaddr = (caddr_t)sensep;
11976 	com->uscsi_buflen = length;
11977 	com->uscsi_flags =
11978 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
11979 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
11980 
11981 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
11982 
11983 	if (rval || com->uscsi_status || com->uscsi_resid) {
11984 
11985 		rval = -1;
11986 
11987 	} else {
11988 
11989 		rval = MTF_TAPE_CLN_SUPPORTED;
11990 		if ((sensep[byte_pos] & bit_mask) == bit_mask) {
11991 
11992 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11993 			    "sense data says head dirty\n");
11994 			rval |= MTF_TAPE_HEAD_DIRTY;
11995 		}
11996 	}
11997 
11998 	kmem_free(com, sizeof (struct uscsi_cmd));
11999 	kmem_free(sensep, length);
12000 	return (rval);
12001 }
12002 
12003 /*
12004  * st_clear_unit_attention
12005  *
12006  *  	run test unit ready's to clear out outstanding
12007  * 	unit attentions.
12008  * 	returns zero for SUCCESS or the errno from st_cmd call
12009  */
12010 static int
12011 st_clear_unit_attentions(dev_t dev_instance, int max_trys)
12012 {
12013 	int	i    = 0;
12014 	int	rval;
12015 
12016 #ifdef DEBUG
12017 	GET_SOFT_STATE(dev_instance);
12018 	ST_FUNC(ST_DEVINFO, st_clear_unit_attentions);
12019 #endif
12020 
12021 	do {
12022 		rval = st_cmd(dev_instance, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
12023 	} while ((rval != 0) && (rval != ENXIO) && (++i < max_trys));
12024 	return (rval);
12025 }
12026 
12027 static void
12028 st_calculate_timeouts(struct scsi_tape *un)
12029 {
12030 	ST_FUNC(ST_DEVINFO, st_calculate_timeouts);
12031 
12032 	if (un->un_dp->non_motion_timeout == 0) {
12033 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
12034 			un->un_dp->non_motion_timeout =
12035 			    st_io_time * st_long_timeout_x;
12036 		} else {
12037 			un->un_dp->non_motion_timeout = (ushort_t)st_io_time;
12038 		}
12039 	}
12040 
12041 	if (un->un_dp->io_timeout == 0) {
12042 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
12043 			un->un_dp->io_timeout = st_io_time * st_long_timeout_x;
12044 		} else {
12045 			un->un_dp->io_timeout = (ushort_t)st_io_time;
12046 		}
12047 	}
12048 
12049 	if (un->un_dp->rewind_timeout == 0) {
12050 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
12051 			un->un_dp->rewind_timeout =
12052 			    st_space_time * st_long_timeout_x;
12053 		} else {
12054 			un->un_dp->rewind_timeout = (ushort_t)st_space_time;
12055 		}
12056 	}
12057 
12058 	if (un->un_dp->space_timeout == 0) {
12059 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
12060 			un->un_dp->space_timeout =
12061 			    st_space_time * st_long_timeout_x;
12062 		} else {
12063 			un->un_dp->space_timeout = (ushort_t)st_space_time;
12064 		}
12065 	}
12066 
12067 	if (un->un_dp->load_timeout == 0) {
12068 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
12069 			un->un_dp->load_timeout =
12070 			    st_space_time * st_long_timeout_x;
12071 		} else {
12072 			un->un_dp->load_timeout = (ushort_t)st_space_time;
12073 		}
12074 	}
12075 
12076 	if (un->un_dp->unload_timeout == 0) {
12077 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
12078 			un->un_dp->unload_timeout =
12079 			    st_space_time * st_long_timeout_x;
12080 		} else {
12081 			un->un_dp->unload_timeout = (ushort_t)st_space_time;
12082 		}
12083 	}
12084 
12085 	if (un->un_dp->erase_timeout == 0) {
12086 		if (un->un_dp->options & ST_LONG_ERASE) {
12087 			un->un_dp->erase_timeout =
12088 			    st_space_time * st_long_space_time_x;
12089 		} else {
12090 			un->un_dp->erase_timeout = (ushort_t)st_space_time;
12091 		}
12092 	}
12093 }
12094 
12095 
12096 static writablity
12097 st_is_not_wormable(struct scsi_tape *un)
12098 {
12099 	ST_FUNC(ST_DEVINFO, st_is_not_wormable);
12100 	return (RDWR);
12101 }
12102 
12103 static writablity
12104 st_is_hp_dat_tape_worm(struct scsi_tape *un)
12105 {
12106 	writablity wrt;
12107 
12108 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_tape_worm);
12109 
12110 	/* Mode sense should be current */
12111 	if (un->un_mspl->media_type == 1) {
12112 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12113 		    "Drive has WORM media loaded\n");
12114 		wrt = WORM;
12115 	} else {
12116 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12117 		    "Drive has non WORM media loaded\n");
12118 		wrt = RDWR;
12119 	}
12120 	return (wrt);
12121 }
12122 
12123 #define	HP_DAT_INQUIRY 0x4A
12124 static writablity
12125 st_is_hp_dat_worm(struct scsi_tape *un)
12126 {
12127 	char *buf;
12128 	int result;
12129 	writablity wrt;
12130 
12131 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_worm);
12132 
12133 	buf = kmem_zalloc(HP_DAT_INQUIRY, KM_SLEEP);
12134 
12135 	result = st_get_special_inquiry(un, HP_DAT_INQUIRY, buf, 0);
12136 
12137 	if (result != 0) {
12138 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12139 		    "Read Standard Inquiry for WORM support failed");
12140 		wrt = FAILED;
12141 	} else if ((buf[40] & 1) == 0) {
12142 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12143 		    "Drive is NOT WORMable\n");
12144 		/* This drive doesn't support it so don't check again */
12145 		un->un_dp->options &= ~ST_WORMABLE;
12146 		wrt = RDWR;
12147 		un->un_wormable = st_is_not_wormable;
12148 	} else {
12149 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12150 		    "Drive supports WORM version %d\n", buf[40] >> 1);
12151 		un->un_wormable = st_is_hp_dat_tape_worm;
12152 		wrt = un->un_wormable(un);
12153 	}
12154 
12155 	kmem_free(buf, HP_DAT_INQUIRY);
12156 
12157 	/*
12158 	 * If drive doesn't support it no point in checking further.
12159 	 */
12160 	return (wrt);
12161 }
12162 
12163 static writablity
12164 st_is_hp_lto_tape_worm(struct scsi_tape *un)
12165 {
12166 	writablity wrt;
12167 
12168 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_tape_worm);
12169 
12170 	/* Mode sense should be current */
12171 	switch (un->un_mspl->media_type) {
12172 	case 0x00:
12173 		switch (un->un_mspl->density) {
12174 		case 0x40:
12175 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12176 			    "Drive has standard Gen I media loaded\n");
12177 			break;
12178 		case 0x42:
12179 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12180 			    "Drive has standard Gen II media loaded\n");
12181 			break;
12182 		case 0x44:
12183 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12184 			    "Drive has standard Gen III media loaded\n");
12185 			break;
12186 		case 0x46:
12187 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12188 			    "Drive has standard Gen IV media loaded\n");
12189 			break;
12190 		default:
12191 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12192 			    "Drive has standard unknown 0x%X media loaded\n",
12193 			    un->un_mspl->density);
12194 		}
12195 		wrt = RDWR;
12196 		break;
12197 	case 0x01:
12198 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12199 		    "Drive has WORM medium loaded\n");
12200 		wrt = WORM;
12201 		break;
12202 	case 0x80:
12203 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12204 		    "Drive has CD-ROM emulation medium loaded\n");
12205 		wrt = WORM;
12206 		break;
12207 	default:
12208 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12209 		    "Drive has an unexpected medium type 0x%X loaded\n",
12210 		    un->un_mspl->media_type);
12211 		wrt = RDWR;
12212 	}
12213 
12214 	return (wrt);
12215 }
12216 
12217 #define	LTO_REQ_INQUIRY 44
12218 static writablity
12219 st_is_hp_lto_worm(struct scsi_tape *un)
12220 {
12221 	char *buf;
12222 	int result;
12223 	writablity wrt;
12224 
12225 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_worm);
12226 
12227 	buf = kmem_zalloc(LTO_REQ_INQUIRY, KM_SLEEP);
12228 
12229 	result = st_get_special_inquiry(un, LTO_REQ_INQUIRY, buf, 0);
12230 
12231 	if (result != 0) {
12232 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12233 		    "Read Standard Inquiry for WORM support failed");
12234 		wrt = FAILED;
12235 	} else if ((buf[40] & 1) == 0) {
12236 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12237 		    "Drive is NOT WORMable\n");
12238 		/* This drive doesn't support it so don't check again */
12239 		un->un_dp->options &= ~ST_WORMABLE;
12240 		wrt = RDWR;
12241 		un->un_wormable = st_is_not_wormable;
12242 	} else {
12243 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12244 		    "Drive supports WORM version %d\n", buf[40] >> 1);
12245 		un->un_wormable = st_is_hp_lto_tape_worm;
12246 		wrt = un->un_wormable(un);
12247 	}
12248 
12249 	kmem_free(buf, LTO_REQ_INQUIRY);
12250 
12251 	/*
12252 	 * If drive doesn't support it no point in checking further.
12253 	 */
12254 	return (wrt);
12255 }
12256 
12257 static writablity
12258 st_is_t10_worm_device(struct scsi_tape *un)
12259 {
12260 	writablity wrt;
12261 
12262 	ST_FUNC(ST_DEVINFO, st_is_t10_worm_device);
12263 
12264 	if (un->un_mspl->media_type == 0x3c) {
12265 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12266 		    "Drive has WORM media loaded\n");
12267 		wrt = WORM;
12268 	} else {
12269 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12270 		    "Drive has non WORM media loaded\n");
12271 		wrt = RDWR;
12272 	}
12273 	return (wrt);
12274 }
12275 
12276 #define	SEQ_CAP_PAGE	(char)0xb0
12277 static writablity
12278 st_is_t10_worm(struct scsi_tape *un)
12279 {
12280 	char *buf;
12281 	int result;
12282 	writablity wrt;
12283 
12284 	ST_FUNC(ST_DEVINFO, st_is_t10_worm);
12285 
12286 	buf = kmem_zalloc(6, KM_SLEEP);
12287 
12288 	result = st_get_special_inquiry(un, 6, buf, SEQ_CAP_PAGE);
12289 
12290 	if (result != 0) {
12291 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12292 		    "Read Vitial Inquiry for Sequental Capability"
12293 		    " WORM support failed %x", result);
12294 		wrt = FAILED;
12295 	} else if ((buf[4] & 1) == 0) {
12296 		ASSERT(buf[1] == SEQ_CAP_PAGE);
12297 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12298 		    "Drive is NOT WORMable\n");
12299 		/* This drive doesn't support it so don't check again */
12300 		un->un_dp->options &= ~ST_WORMABLE;
12301 		wrt = RDWR;
12302 		un->un_wormable = st_is_not_wormable;
12303 	} else {
12304 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12305 		    "Drive supports WORM\n");
12306 		un->un_wormable = st_is_t10_worm_device;
12307 		wrt = un->un_wormable(un);
12308 	}
12309 
12310 	kmem_free(buf, 6);
12311 
12312 	return (wrt);
12313 }
12314 
12315 
12316 #define	STK_REQ_SENSE 26
12317 
12318 static writablity
12319 st_is_stk_worm(struct scsi_tape *un)
12320 {
12321 	char cdb[CDB_GROUP0] = {SCMD_REQUEST_SENSE, 0, 0, 0, STK_REQ_SENSE, 0};
12322 	struct scsi_extended_sense *sense;
12323 	struct uscsi_cmd *cmd;
12324 	char *buf;
12325 	int result;
12326 	writablity wrt;
12327 
12328 	ST_FUNC(ST_DEVINFO, st_is_stk_worm);
12329 
12330 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
12331 	buf = kmem_alloc(STK_REQ_SENSE, KM_SLEEP);
12332 	sense = (struct scsi_extended_sense *)buf;
12333 
12334 	cmd->uscsi_flags = USCSI_READ;
12335 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
12336 	cmd->uscsi_cdb = &cdb[0];
12337 	cmd->uscsi_bufaddr = buf;
12338 	cmd->uscsi_buflen = STK_REQ_SENSE;
12339 	cmd->uscsi_cdblen = CDB_GROUP0;
12340 	cmd->uscsi_rqlen = 0;
12341 	cmd->uscsi_rqbuf = NULL;
12342 
12343 	result = st_ioctl_cmd(un->un_dev, cmd, FKIOCTL);
12344 
12345 	if (result != 0 || cmd->uscsi_status != 0) {
12346 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12347 		    "Request Sense for WORM failed");
12348 		wrt = RDWR;
12349 	} else if (sense->es_add_len + 8 < 24) {
12350 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12351 		    "Drive didn't send enough sense data for WORM byte %d\n",
12352 		    sense->es_add_len + 8);
12353 		wrt = RDWR;
12354 		un->un_wormable = st_is_not_wormable;
12355 	} else if ((buf[24]) & 0x02) {
12356 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12357 		    "Drive has WORM tape loaded\n");
12358 		wrt = WORM;
12359 		un->un_wormable = st_is_stk_worm;
12360 	} else {
12361 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12362 		    "Drive has normal tape loaded\n");
12363 		wrt = RDWR;
12364 		un->un_wormable = st_is_stk_worm;
12365 	}
12366 
12367 	kmem_free(buf, STK_REQ_SENSE);
12368 	kmem_free(cmd, sizeof (struct uscsi_cmd));
12369 	return (wrt);
12370 }
12371 
12372 #define	DLT_INQ_SZ 44
12373 
12374 static writablity
12375 st_is_dlt_tape_worm(struct scsi_tape *un)
12376 {
12377 	caddr_t buf;
12378 	int result;
12379 	writablity wrt;
12380 
12381 	ST_FUNC(ST_DEVINFO, st_is_dlt_tape_worm);
12382 
12383 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
12384 
12385 	/* Read Attribute Media Type */
12386 
12387 	result = st_read_attributes(un, 0x0408, buf, 10);
12388 
12389 	/*
12390 	 * If this quantum drive is attached via an HBA that cannot
12391 	 * support thr read attributes command return error in the
12392 	 * hope that someday they will support the t10 method.
12393 	 */
12394 	if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
12395 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
12396 		    "Read Attribute Command for WORM Media detection is not "
12397 		    "supported on the HBA that this drive is attached to.");
12398 		wrt = RDWR;
12399 		un->un_wormable = st_is_not_wormable;
12400 		goto out;
12401 	}
12402 
12403 	if (result != 0) {
12404 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12405 		    "Read Attribute Command for WORM Media returned 0x%x",
12406 		    result);
12407 		wrt = RDWR;
12408 		un->un_dp->options &= ~ST_WORMABLE;
12409 		goto out;
12410 	}
12411 
12412 	if ((uchar_t)buf[9] == 0x80) {
12413 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12414 		    "Drive media is WORM\n");
12415 		wrt = WORM;
12416 	} else {
12417 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12418 		    "Drive media is not WORM Media 0x%x\n", (uchar_t)buf[9]);
12419 		wrt = RDWR;
12420 	}
12421 
12422 out:
12423 	kmem_free(buf, DLT_INQ_SZ);
12424 	return (wrt);
12425 }
12426 
12427 static writablity
12428 st_is_dlt_worm(struct scsi_tape *un)
12429 {
12430 	caddr_t buf;
12431 	int result;
12432 	writablity wrt;
12433 
12434 	ST_FUNC(ST_DEVINFO, st_is_dlt_worm);
12435 
12436 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
12437 
12438 	result = st_get_special_inquiry(un, DLT_INQ_SZ, buf, 0xC0);
12439 
12440 	if (result != 0) {
12441 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12442 		    "Read Vendor Specific Inquiry for WORM support failed");
12443 		wrt = RDWR;
12444 		goto out;
12445 	}
12446 
12447 	if ((buf[2] & 1) == 0) {
12448 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12449 		    "Drive is not WORMable\n");
12450 		wrt = RDWR;
12451 		un->un_dp->options &= ~ST_WORMABLE;
12452 		un->un_wormable = st_is_not_wormable;
12453 		goto out;
12454 	} else {
12455 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12456 		    "Drive is WORMable\n");
12457 		un->un_wormable = st_is_dlt_tape_worm;
12458 		wrt = un->un_wormable(un);
12459 	}
12460 out:
12461 	kmem_free(buf, DLT_INQ_SZ);
12462 
12463 	return (wrt);
12464 }
12465 
12466 typedef struct {
12467 	struct modeheader_seq header;
12468 #if defined(_BIT_FIELDS_LTOH) /* X86 */
12469 	uchar_t pagecode	:6,
12470 				:2;
12471 	uchar_t page_len;
12472 	uchar_t syslogalive	:2,
12473 		device		:1,
12474 		abs		:1,
12475 		ulpbot		:1,
12476 		prth		:1,
12477 		ponej		:1,
12478 		ait		:1;
12479 	uchar_t span;
12480 
12481 	uchar_t			:6,
12482 		worm		:1,
12483 		mic		:1;
12484 	uchar_t worm_cap	:1,
12485 				:7;
12486 	uint32_t		:32;
12487 #else /* SPARC */
12488 	uchar_t			:2,
12489 		pagecode	:6;
12490 	uchar_t page_len;
12491 	uchar_t ait		:1,
12492 		device		:1,
12493 		abs		:1,
12494 		ulpbot		:1,
12495 		prth		:1,
12496 		ponej		:1,
12497 		syslogalive	:2;
12498 	uchar_t span;
12499 	uchar_t mic		:1,
12500 		worm		:1,
12501 				:6;
12502 	uchar_t			:7,
12503 		worm_cap	:1;
12504 	uint32_t		:32;
12505 #endif
12506 }ait_dev_con;
12507 
12508 #define	AIT_DEV_PAGE 0x31
12509 static writablity
12510 st_is_sony_worm(struct scsi_tape *un)
12511 {
12512 	int result;
12513 	writablity wrt;
12514 	ait_dev_con *ait_conf;
12515 
12516 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
12517 
12518 	ait_conf = kmem_zalloc(sizeof (ait_dev_con), KM_SLEEP);
12519 
12520 	result = st_gen_mode_sense(un, AIT_DEV_PAGE,
12521 	    (struct seq_mode *)ait_conf, sizeof (ait_dev_con));
12522 
12523 	if (result == 0) {
12524 
12525 		if (ait_conf->pagecode != AIT_DEV_PAGE) {
12526 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12527 			    "returned page 0x%x not 0x%x AIT_DEV_PAGE\n",
12528 			    ait_conf->pagecode, AIT_DEV_PAGE);
12529 			wrt = RDWR;
12530 			un->un_wormable = st_is_not_wormable;
12531 
12532 		} else if (ait_conf->worm_cap) {
12533 
12534 			un->un_wormable = st_is_sony_worm;
12535 
12536 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12537 			    "Drives is WORMable\n");
12538 			if (ait_conf->worm) {
12539 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12540 				    "Media is WORM\n");
12541 				wrt = WORM;
12542 			} else {
12543 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12544 				    "Media is not WORM\n");
12545 				wrt = RDWR;
12546 			}
12547 
12548 		} else {
12549 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12550 			    "Drives not is WORMable\n");
12551 			wrt = RDWR;
12552 			/* No further checking required */
12553 			un->un_dp->options &= ~ST_WORMABLE;
12554 		}
12555 
12556 	} else {
12557 
12558 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12559 		    "AIT device config mode sense page read command failed"
12560 		    " result = %d ", result);
12561 		wrt = FAILED;
12562 		un->un_wormable = st_is_not_wormable;
12563 	}
12564 
12565 	kmem_free(ait_conf, sizeof (ait_dev_con));
12566 	return (wrt);
12567 }
12568 
12569 static writablity
12570 st_is_drive_worm(struct scsi_tape *un)
12571 {
12572 	writablity wrt;
12573 
12574 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
12575 
12576 	switch (un->un_dp->type) {
12577 	case MT_ISDLT:
12578 		wrt = st_is_dlt_worm(un);
12579 		break;
12580 
12581 	case MT_ISSTK9840:
12582 		wrt = st_is_stk_worm(un);
12583 		break;
12584 
12585 	case MT_IS8MM:
12586 	case MT_ISAIT:
12587 		wrt = st_is_sony_worm(un);
12588 		break;
12589 
12590 	case MT_LTO:
12591 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
12592 			wrt = st_is_hp_lto_worm(un);
12593 		} else {
12594 			wrt = st_is_t10_worm(un);
12595 		}
12596 		break;
12597 
12598 	case MT_ISDAT:
12599 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
12600 			wrt = st_is_hp_dat_worm(un);
12601 		} else {
12602 			wrt = st_is_t10_worm(un);
12603 		}
12604 		break;
12605 
12606 	default:
12607 		wrt = FAILED;
12608 		break;
12609 	}
12610 
12611 	/*
12612 	 * If any of the above failed try the t10 standard method.
12613 	 */
12614 	if (wrt == FAILED) {
12615 		wrt = st_is_t10_worm(un);
12616 	}
12617 
12618 	/*
12619 	 * Unknown method for detecting WORM media.
12620 	 */
12621 	if (wrt == FAILED) {
12622 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12623 		    "Unknown method for WORM media detection\n");
12624 		wrt = RDWR;
12625 		un->un_dp->options &= ~ST_WORMABLE;
12626 	}
12627 
12628 	return (wrt);
12629 }
12630 
12631 static int
12632 st_read_attributes(struct scsi_tape *un, uint16_t attribute, caddr_t buf,
12633     size_t size)
12634 {
12635 	char cdb[CDB_GROUP4];
12636 	int result;
12637 	struct uscsi_cmd *cmd;
12638 
12639 	ST_FUNC(ST_DEVINFO, st_read_attributes);
12640 
12641 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
12642 
12643 	cdb[0] = (char)SCMD_READ_ATTRIBUTE;
12644 	cdb[1] = 0;
12645 	cdb[2] = 0;
12646 	cdb[3] = 0;
12647 	cdb[4] = 0;
12648 	cdb[5] = 0;
12649 	cdb[6] = 0;
12650 	cdb[7] = 0;
12651 	cdb[8] = (char)(attribute >> 8);
12652 	cdb[9] = (char)(attribute);
12653 	cdb[10] = (char)(size >> 24);
12654 	cdb[11] = (char)(size >> 16);
12655 	cdb[12] = (char)(size >> 8);
12656 	cdb[13] = (char)(size);
12657 	cdb[14] = 0;
12658 	cdb[15] = 0;
12659 
12660 
12661 	cmd->uscsi_flags = USCSI_READ | USCSI_DIAGNOSE;
12662 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
12663 	cmd->uscsi_cdb = &cdb[0];
12664 	cmd->uscsi_bufaddr = (caddr_t)buf;
12665 	cmd->uscsi_buflen = size;
12666 	cmd->uscsi_cdblen = sizeof (cdb);
12667 
12668 	result = st_ioctl_cmd(un->un_dev, cmd, FKIOCTL);
12669 
12670 	if (result != 0 || cmd->uscsi_status != 0) {
12671 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12672 		    "st_read_attribute failed: result %d status %d\n",
12673 		    result, cmd->uscsi_status);
12674 		if (result == 0) {
12675 			result = EIO;
12676 		}
12677 		goto exit;
12678 	}
12679 
12680 	/*
12681 	 * The attribute retured should match the attribute requested.
12682 	 */
12683 	if (buf[4] != cdb[8] || buf[5] != cdb[9]) {
12684 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
12685 		    "bad? data", buf, size);
12686 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
12687 		    "st_read_attribute got wrong data back expected 0x%x"
12688 		    " got 0x%x\n", attribute, buf[6] << 8 | buf[7]);
12689 		result = EIO;
12690 	}
12691 exit:
12692 	kmem_free(cmd, sizeof (struct uscsi_cmd));
12693 
12694 	return (result);
12695 }
12696 
12697 static int
12698 st_get_special_inquiry(struct scsi_tape *un, uchar_t size, caddr_t dest,
12699     uchar_t page)
12700 {
12701 	char cdb[CDB_GROUP0];
12702 	struct scsi_extended_sense *sense;
12703 	struct uscsi_cmd *cmd;
12704 	int result;
12705 
12706 	ST_FUNC(ST_DEVINFO, st_get_special_inquiry);
12707 
12708 	cdb[0] = SCMD_INQUIRY;
12709 	cdb[1] = page ? 1 : 0;
12710 	cdb[2] = page;
12711 	cdb[3] = 0;
12712 	cdb[4] = size;
12713 	cdb[5] = 0;
12714 
12715 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
12716 	sense = kmem_alloc(sizeof (struct scsi_extended_sense), KM_SLEEP);
12717 
12718 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
12719 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
12720 	cmd->uscsi_cdb = &cdb[0];
12721 	cmd->uscsi_bufaddr = dest;
12722 	cmd->uscsi_buflen = size;
12723 	cmd->uscsi_cdblen = CDB_GROUP0;
12724 	cmd->uscsi_rqlen = sizeof (struct scsi_extended_sense);
12725 	cmd->uscsi_rqbuf = (caddr_t)sense;
12726 
12727 	result = st_ioctl_cmd(un->un_dev, cmd, FKIOCTL);
12728 
12729 	if (result != 0 || cmd->uscsi_status != 0) {
12730 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12731 		    "st_get_special_inquiry() failed for page %x", page);
12732 		if (result == 0) {
12733 			result = EIO;
12734 		}
12735 	}
12736 
12737 	kmem_free(sense, sizeof (struct scsi_extended_sense));
12738 	kmem_free(cmd, sizeof (struct uscsi_cmd));
12739 
12740 	return (result);
12741 }
12742 
12743 
12744 static int
12745 st_update_block_pos(struct scsi_tape *un)
12746 {
12747 	int rval = ENOTTY;
12748 
12749 	ST_FUNC(ST_DEVINFO, st_update_block_pos);
12750 
12751 	while (un->un_read_pos_type != NO_POS) {
12752 		rval = st_cmd(un->un_dev, SCMD_READ_POSITION, 32, SYNC_CMD);
12753 
12754 		if (rval == 0) {
12755 			rval = st_interpret_read_pos(un, un->un_read_pos_type,
12756 			    32, (caddr_t)un->un_read_pos_data);
12757 			break;
12758 		} else if (un->un_status == KEY_UNIT_ATTENTION) {
12759 			continue;
12760 		} else if (un->un_status != KEY_ILLEGAL_REQUEST) {
12761 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
12762 			    "st_update_block_pos() read position cmd %x"
12763 			    " returned %x un_status = %d",
12764 			    un->un_read_pos_type, rval, un->un_status);
12765 			break;
12766 		} else {
12767 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
12768 			    "st_update_block_pos() read position cmd %x"
12769 			    " returned %x", un->un_read_pos_type, rval);
12770 		}
12771 
12772 		switch (un->un_read_pos_type) {
12773 		case SHORT_POS:
12774 			un->un_read_pos_type = NO_POS;
12775 			break;
12776 
12777 		case LONG_POS:
12778 			un->un_read_pos_type = EXT_POS;
12779 			break;
12780 
12781 		case EXT_POS:
12782 			un->un_read_pos_type = SHORT_POS;
12783 			break;
12784 
12785 		default:
12786 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
12787 			    "Unexpected read position type 0x%x",
12788 			    un->un_read_pos_type);
12789 		}
12790 	}
12791 
12792 	return (rval);
12793 }
12794 
12795 static int
12796 st_get_read_pos(struct scsi_tape *un, buf_t *bp)
12797 {
12798 	int result;
12799 	size_t d_sz;
12800 	caddr_t pos_info;
12801 	struct uscsi_cmd *cmd = (struct uscsi_cmd *)bp->b_back;
12802 
12803 	ST_FUNC(ST_DEVINFO, st_get_read_pos);
12804 
12805 	if (cmd->uscsi_bufaddr == NULL || cmd->uscsi_buflen <= 0) {
12806 		return (0);
12807 	}
12808 
12809 	if (bp_mapin_common(bp, VM_NOSLEEP) == NULL) {
12810 
12811 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
12812 		    "bp_mapin_common() failed");
12813 
12814 		return (EIO);
12815 	}
12816 
12817 	pos_info = bp->b_un.b_addr;
12818 	d_sz = bp->b_bcount - bp->b_resid;
12819 
12820 #ifdef DEBUG
12821 	if ((st_debug & 0xf) > 2) {
12822 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
12823 		    "st_get_read_pos() position info",
12824 		    pos_info, bp->b_bcount);
12825 	}
12826 #endif
12827 
12828 	result = st_interpret_read_pos(un, cmd->uscsi_cdb[1], d_sz, pos_info);
12829 
12830 	bp_mapout(bp);
12831 
12832 	return (result);
12833 }
12834 
12835 #if defined(_BIG_ENDIAN)
12836 
12837 #define	FIX_ENDIAN32(x)
12838 #define	FIX_ENDIAN64(x)
12839 
12840 #elif defined(_LITTLE_ENDIAN)
12841 
12842 static void
12843 st_swap32(uint32_t *val)
12844 {
12845 	uint32_t tmp;
12846 
12847 	tmp =  (*val >> 24) & 0xff;
12848 	tmp |= (*val >>  8) & 0xff00;
12849 	tmp |= (*val <<  8) & 0xff0000;
12850 	tmp |= (*val << 24) & 0xff000000;
12851 
12852 	*val = tmp;
12853 }
12854 
12855 static void
12856 st_swap64(uint64_t *val)
12857 {
12858 	uint32_t low;
12859 	uint32_t high;
12860 
12861 	low =  (uint32_t)(*val);
12862 	high = (uint32_t)(*val >> 32);
12863 
12864 	st_swap32(&low);
12865 	st_swap32(&high);
12866 
12867 	*val =  high;
12868 	*val |= ((uint64_t)low << 32);
12869 }
12870 
12871 #define	FIX_ENDIAN32(x) st_swap32(x)
12872 #define	FIX_ENDIAN64(x) st_swap64(x)
12873 #endif
12874 
12875 static int
12876 st_interpret_read_pos(struct scsi_tape *un, read_p_types type,
12877     size_t data_sz, caddr_t responce)
12878 {
12879 	int rval = 0;
12880 
12881 	ST_FUNC(ST_DEVINFO, st_interpret_read_pos);
12882 
12883 	/*
12884 	 * Look at byte 1 of cdb to see what kind of read position
12885 	 * was requested.
12886 	 */
12887 	switch (type) {
12888 
12889 	case SHORT_POS: /* Short data format */
12890 	{
12891 		tape_position_t *pos_info = (tape_position_t *)responce;
12892 		uint32_t value;
12893 
12894 		/* If reserved fields are non zero don't use the data */
12895 		if (pos_info->reserved0 || pos_info->reserved1 ||
12896 		    pos_info->reserved2[0] || pos_info->reserved2[1] ||
12897 		    pos_info->reserved3) {
12898 			rval = EIO;
12899 			break;
12900 		}
12901 		/*
12902 		 * Position is to large to use this type of read position.
12903 		 */
12904 		if (pos_info->posi_err == 1) {
12905 			rval = ERANGE;
12906 			break;
12907 		}
12908 
12909 		if (pos_info->blk_posi_unkwn == 0) {
12910 
12911 			if (un->un_pos.partition !=
12912 			    pos_info->partition_number) {
12913 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12914 				    "SHORT_POS current partition %d read %d\n",
12915 				    un->un_pos.partition,
12916 				    pos_info->partition_number);
12917 			}
12918 			un->un_pos.partition = pos_info->partition_number;
12919 			value = pos_info->host_block;
12920 			FIX_ENDIAN32(&value);
12921 
12922 			if (un->un_pos.lgclblkno != value) {
12923 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12924 				    "SHORT_POS current logical 0x%"PRIx64" read"
12925 				    " 0x%x\n", un->un_pos.lgclblkno, value);
12926 			}
12927 
12928 			un->un_pos.lgclblkno = (uint64_t)value;
12929 
12930 			if (pos_info->begin_of_part && pos_info->end_of_part) {
12931 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
12932 				    "SHORT_POS returned begin and end of"
12933 				    " partition\n");
12934 				break;
12935 			}
12936 			/* Is drive rewound */
12937 			if ((pos_info->begin_of_part == 1) &&
12938 			    (pos_info->host_block == 0)) {
12939 				un->un_pos.blkno = 0;
12940 				un->un_pos.fileno = 0;
12941 				un->un_pos.pmode = legacy;
12942 			} else if (un->un_pos.pmode == invalid) {
12943 				/* If we were lost now were found */
12944 				un->un_pos.pmode = logical;
12945 			}
12946 		} else {
12947 			un->un_pos.pmode = invalid;
12948 		}
12949 		break;
12950 	}
12951 
12952 	case LONG_POS: /* Long data format */
12953 	{
12954 		uint64_t value;
12955 		tape_position_long_t *long_pos_info =
12956 		    (tape_position_long_t *)responce;
12957 
12958 		/* If reserved fields are non zero don't use the data */
12959 		if ((long_pos_info->reserved0) ||
12960 		    (long_pos_info->reserved1) ||
12961 		    (long_pos_info->reserved2)) {
12962 			rval = EIO;
12963 			break;
12964 		}
12965 
12966 		/* Is position Valid */
12967 		if (long_pos_info->blk_posi_unkwn == 0) {
12968 			uint32_t part;
12969 
12970 			part = long_pos_info->partition;
12971 			FIX_ENDIAN32(&part);
12972 			if (un->un_pos.partition != part) {
12973 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12974 				    "LONG_POS current partition %d"
12975 				    " read %d\n", un->un_pos.partition, part);
12976 			}
12977 			un->un_pos.partition = part;
12978 			value = long_pos_info->block_number;
12979 			FIX_ENDIAN64(&value);
12980 			if (un->un_pos.lgclblkno != value) {
12981 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12982 				    "LONG_POS current logical 0x%"PRIx64
12983 				    " read 0x%"PRIx64"\n",
12984 				    un->un_pos.lgclblkno, value);
12985 			}
12986 			un->un_pos.lgclblkno = value;
12987 
12988 			if (long_pos_info->begin_of_part &&
12989 			    long_pos_info->end_of_part) {
12990 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
12991 				    "LONG_POS returned begin and end of"
12992 				    " partition\n");
12993 				break;
12994 			}
12995 			if ((long_pos_info->begin_of_part == 1) &&
12996 			    (long_pos_info->block_number == 0)) {
12997 				un->un_pos.blkno = 0;
12998 				un->un_pos.fileno = 0;
12999 				un->un_pos.pmode = legacy;
13000 			} else if (un->un_pos.pmode == invalid) {
13001 				un->un_pos.pmode = logical;
13002 			}
13003 		} else {
13004 			/*
13005 			 * If the drive doesn't know location,
13006 			 * we don't either.
13007 			 */
13008 			un->un_pos.pmode = invalid;
13009 		}
13010 
13011 		value = long_pos_info->file_number;
13012 		FIX_ENDIAN64(&value);
13013 		/* Is file position valid */
13014 		if (long_pos_info->mrk_posi_unkwn == 0) {
13015 			if (((un->un_pos.pmode == legacy) ||
13016 			    (un->un_pos.pmode == logical)) &&
13017 			    (un->un_pos.fileno != value)) {
13018 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13019 				    "LONG_POS fileno 0x%"PRIx64
13020 				    " not un_pos %x\n", value,
13021 				    un->un_pos.fileno);
13022 			} else if (un->un_pos.pmode == invalid) {
13023 				un->un_pos.pmode = logical;
13024 			}
13025 			un->un_pos.fileno = (int32_t)value;
13026 		} else {
13027 			/*
13028 			 * If the drive doesn't know its position,
13029 			 * we don't either.
13030 			 */
13031 			un->un_pos.pmode = invalid;
13032 		}
13033 		if (un->un_pos.pmode != invalid && long_pos_info->end_of_part) {
13034 			un->un_pos.eof = ST_EOT;
13035 		}
13036 
13037 		break;
13038 	}
13039 
13040 	case EXT_POS: /* Extended data format */
13041 	{
13042 		uint64_t value;
13043 		tape_position_ext_t *ext_pos_info =
13044 		    (tape_position_ext_t *)responce;
13045 
13046 		/* Make sure that there is enough data there */
13047 		if (data_sz < 16) {
13048 			break;
13049 		}
13050 
13051 		/* If reserved fields are non zero don't use the data */
13052 		if (ext_pos_info->reserved0 || ext_pos_info->reserved1) {
13053 			rval = EIO;
13054 			break;
13055 		}
13056 
13057 		/*
13058 		 * In the unlikely event of overflowing 64 bits of position.
13059 		 */
13060 		if (ext_pos_info->posi_err != 0) {
13061 			rval = ERANGE;
13062 			break;
13063 		}
13064 
13065 		/* Is block position information valid */
13066 		if (ext_pos_info->blk_posi_unkwn == 0) {
13067 
13068 			if (un->un_pos.partition != ext_pos_info->partition) {
13069 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13070 				    "EXT_POS current partition %d read %d\n",
13071 				    un->un_pos.partition,
13072 				    ext_pos_info->partition);
13073 			}
13074 			un->un_pos.partition = ext_pos_info->partition;
13075 
13076 			value = ext_pos_info->host_block;
13077 			FIX_ENDIAN64(&value);
13078 			if (un->un_pos.lgclblkno != value) {
13079 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13080 				    "EXT_POS current logical 0x%"PRIx64
13081 				    " read 0x%"PRIx64"\n",
13082 				    un->un_pos.lgclblkno, value);
13083 			}
13084 			un->un_pos.lgclblkno = value;
13085 			if ((ext_pos_info->begin_of_part == 1) &&
13086 			    (ext_pos_info->host_block == 0)) {
13087 				un->un_pos.blkno = 0;
13088 				un->un_pos.fileno = 0;
13089 				un->un_pos.pmode = legacy;
13090 			} else if (un->un_pos.pmode == invalid) {
13091 				un->un_pos.pmode = logical;
13092 			}
13093 		} else {
13094 			un->un_pos.pmode = invalid;
13095 		}
13096 		break;
13097 	}
13098 
13099 	default:
13100 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
13101 		    "Got unexpected SCMD_READ_POSITION type %d\n", type);
13102 		rval = EIO;
13103 	}
13104 
13105 	return (rval);
13106 }
13107 
13108 static int
13109 st_logical_block_locate(struct scsi_tape *un, uint64_t lblk, uchar_t partition)
13110 {
13111 	int rval;
13112 	char cdb[CDB_GROUP4];
13113 	struct uscsi_cmd *cmd;
13114 	struct scsi_extended_sense sense;
13115 
13116 	ST_FUNC(ST_DEVINFO, st_logical_block_locate);
13117 
13118 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13119 
13120 	if (lblk <= INT32_MAX) {
13121 		cmd->uscsi_cdblen = CDB_GROUP1;
13122 		cdb[0] = SCMD_LOCATE;
13123 		cdb[1] = un->un_pos.partition == partition ? 0 : 2;
13124 		cdb[2] = 0;
13125 		cdb[3] = (char)(lblk >> 24);
13126 		cdb[4] = (char)(lblk >> 16);
13127 		cdb[5] = (char)(lblk >> 8);
13128 		cdb[6] = (char)(lblk);
13129 		cdb[7] = 0;
13130 		cdb[8] = partition;
13131 		cdb[9] = 0;
13132 	} else {
13133 		/*
13134 		 * If the drive doesn't give a 64 bit read position data
13135 		 * it is unlikely it will accept 64 bit locates.
13136 		 */
13137 		if (un->un_read_pos_type != LONG_POS) {
13138 			kmem_free(cmd, sizeof (struct uscsi_cmd));
13139 			return (ERANGE);
13140 		}
13141 		cmd->uscsi_cdblen = CDB_GROUP4;
13142 		cdb[0] = (char)SCMD_LOCATE_G4;
13143 		cdb[1] = un->un_pos.partition == partition ? 0 : 2;
13144 		cdb[2] = 0;
13145 		cdb[3] = partition;
13146 		cdb[4] = (char)(lblk >> 56);
13147 		cdb[5] = (char)(lblk >> 48);
13148 		cdb[6] = (char)(lblk >> 40);
13149 		cdb[7] = (char)(lblk >> 32);
13150 		cdb[8] = (char)(lblk >> 24);
13151 		cdb[9] = (char)(lblk >> 16);
13152 		cdb[10] = (char)(lblk >> 8);
13153 		cdb[11] = (char)(lblk);
13154 		cdb[12] = 0;
13155 		cdb[13] = 0;
13156 		cdb[14] = 0;
13157 		cdb[15] = 0;
13158 	}
13159 
13160 
13161 	cmd->uscsi_flags = USCSI_WRITE | USCSI_DIAGNOSE | USCSI_RQENABLE;
13162 	cmd->uscsi_rqbuf = (caddr_t)&sense;
13163 	cmd->uscsi_rqlen = sizeof (sense);
13164 	cmd->uscsi_timeout = un->un_dp->space_timeout;
13165 	cmd->uscsi_cdb = cdb;
13166 
13167 	rval = st_ioctl_cmd(un->un_dev, cmd, FKIOCTL);
13168 
13169 	un->un_pos.pmode = logical;
13170 	un->un_pos.eof = ST_NO_EOF;
13171 
13172 	if (lblk > INT32_MAX) {
13173 		/*
13174 		 * XXX This is a work around till we handle Descriptor format
13175 		 * sense data. Since we are sending a command where the standard
13176 		 * sense data can not correctly represent a correct residual in
13177 		 * 4 bytes.
13178 		 */
13179 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
13180 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13181 			    "Big LOCATE ILLEGAL_REQUEST: rval = %d\n", rval);
13182 			/* Doesn't like big locate command */
13183 			un->un_status = 0;
13184 			rval = ERANGE;
13185 		} else if ((un->un_pos.pmode == invalid) || (rval != 0)) {
13186 			/* Aborted big locate command */
13187 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13188 			    "Big LOCATE resulted in invalid pos: rval = %d\n",
13189 			    rval);
13190 			un->un_status = 0;
13191 			rval = EIO;
13192 		} else if (st_update_block_pos(un)) {
13193 			/* read position failed */
13194 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13195 			    "Big LOCATE and read pos: rval = %d\n", rval);
13196 			rval = EIO;
13197 		} else if (lblk > un->un_pos.lgclblkno) {
13198 			/* read position worked but position was not expected */
13199 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13200 			    "Big LOCATE and recover read less then desired 0x%"
13201 			    PRIx64"\n", un->un_pos.lgclblkno);
13202 			un->un_err_resid = lblk - un->un_pos.lgclblkno;
13203 			un->un_status = KEY_BLANK_CHECK;
13204 			rval = ESPIPE;
13205 		} else if (lblk == un->un_pos.lgclblkno) {
13206 			/* read position was what was expected */
13207 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13208 			    "Big LOCATE and recover seems to have worked\n");
13209 			un->un_err_resid = 0;
13210 			rval = 0;
13211 		} else {
13212 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
13213 			    "BIGLOCATE end up going backwards");
13214 			un->un_err_resid = lblk;
13215 			rval = EIO;
13216 		}
13217 
13218 	} else if (rval == 0) {
13219 		/* Worked as requested */
13220 		un->un_pos.lgclblkno = lblk;
13221 
13222 	} else if (((cmd->uscsi_status & STATUS_MASK) == STATUS_CHECK) &&
13223 	    (cmd->uscsi_resid != 0)) {
13224 		/* Got part way there but wasn't enough blocks on tape */
13225 		un->un_pos.lgclblkno = lblk - cmd->uscsi_resid;
13226 		un->un_err_resid = cmd->uscsi_resid;
13227 		un->un_status = KEY_BLANK_CHECK;
13228 		rval = ESPIPE;
13229 
13230 	} else if (st_update_block_pos(un) == 0) {
13231 		/* Got part way there but drive didn't tell what we missed by */
13232 		un->un_err_resid = lblk - un->un_pos.lgclblkno;
13233 		un->un_status = KEY_BLANK_CHECK;
13234 		rval = ESPIPE;
13235 
13236 	} else {
13237 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13238 		    "Failed LOCATE and recover pos: rval = %d status = %d\n",
13239 		    rval, cmd->uscsi_status);
13240 		un->un_err_resid = lblk;
13241 		un->un_status = KEY_ILLEGAL_REQUEST;
13242 		un->un_pos.pmode = invalid;
13243 		rval = EIO;
13244 	}
13245 
13246 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13247 
13248 	return (rval);
13249 }
13250 
13251 static int
13252 st_mtfsf_ioctl(struct scsi_tape *un, int files)
13253 {
13254 	int rval;
13255 
13256 	ST_FUNC(ST_DEVINFO, st_mtfsf_ioctl);
13257 
13258 
13259 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13260 	    "st_mtfsf_ioctl: count=%x, eof=%x\n", files, un->un_pos.eof);
13261 
13262 	/* pmode == invalid already handled */
13263 	if (un->un_pos.pmode == legacy) {
13264 		/*
13265 		 * forward space over filemark
13266 		 *
13267 		 * For ASF we allow a count of 0 on fsf which means
13268 		 * we just want to go to beginning of current file.
13269 		 * Equivalent to "nbsf(0)" or "bsf(1) + fsf".
13270 		 * Allow stepping over double fmk with reel
13271 		 */
13272 		if ((un->un_pos.eof >= ST_EOT) &&
13273 		    (files > 0) &&
13274 		    ((un->un_dp->options & ST_REEL) == 0)) {
13275 			/* we're at EOM */
13276 			un->un_err_resid = files;
13277 			un->un_status = KEY_BLANK_CHECK;
13278 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13279 			    "st_mtfsf_ioctl: EIO : MTFSF at EOM");
13280 			return (EIO);
13281 		}
13282 
13283 		/*
13284 		 * physical tape position may not be what we've been
13285 		 * telling the user; adjust the request accordingly
13286 		 */
13287 		if (IN_EOF(un->un_pos)) {
13288 			un->un_pos.fileno++;
13289 			un->un_pos.blkno = 0;
13290 			/*
13291 			 * For positive direction case, we're now covered.
13292 			 * For zero or negative direction, we're covered
13293 			 * (almost)
13294 			 */
13295 			files--;
13296 		}
13297 
13298 	}
13299 
13300 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
13301 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13302 		    "st_mtfsf_ioctl: EIO : MTFSF density/wfm failed");
13303 		return (EIO);
13304 	}
13305 
13306 
13307 	/*
13308 	 * Forward space file marks.
13309 	 * We leave ourselves at block zero
13310 	 * of the target file number.
13311 	 */
13312 	if (files < 0) {
13313 		rval = st_backward_space_files(un, -files, 0);
13314 	} else {
13315 		rval = st_forward_space_files(un, files);
13316 	}
13317 
13318 	return (rval);
13319 }
13320 
13321 static int
13322 st_forward_space_files(struct scsi_tape *un, int count)
13323 {
13324 	dev_t dev;
13325 	int rval;
13326 
13327 	ST_FUNC(ST_DEVINFO, st_forward_space_files);
13328 
13329 	dev = un->un_dev;
13330 
13331 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13332 	    "fspace: count=%x, eof=%x\n", count, un->un_pos.eof);
13333 
13334 	ASSERT(count >= 0);
13335 	ASSERT(un->un_pos.pmode != invalid);
13336 
13337 	/*
13338 	 * A space with a count of zero means take me to the start of file.
13339 	 */
13340 	if (count == 0) {
13341 
13342 		/* Hay look were already there */
13343 		if (un->un_pos.pmode == legacy && un->un_pos.blkno == 0 &&
13344 		    un->un_pos.fileno == 0) {
13345 			un->un_err_resid = 0;
13346 			COPY_POS(&un->un_err_pos, &un->un_pos);
13347 			return (0);
13348 		}
13349 
13350 		/*
13351 		 * Well we are in the first file.
13352 		 * A rewind will get to the start.
13353 		 */
13354 		if (un->un_pos.pmode == legacy && un->un_pos.fileno == 0) {
13355 			rval = st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD);
13356 
13357 		/*
13358 		 * Can we backspace to get there?
13359 		 * This should work in logical mode.
13360 		 */
13361 		} else if (un->un_dp->options & ST_BSF) {
13362 			rval = st_space_to_begining_of_file(un);
13363 
13364 		/*
13365 		 * Can't back space but current file number is known,
13366 		 * So rewind and space from the begining of the partition.
13367 		 */
13368 		} else if (un->un_pos.pmode == legacy) {
13369 			rval = st_scenic_route_to_begining_of_file(un,
13370 			    un->un_pos.fileno);
13371 
13372 		/*
13373 		 * pmode is logical and ST_BSF is not set.
13374 		 * The LONG_POS read position contains the fileno.
13375 		 * If the read position works, rewind and space.
13376 		 */
13377 		} else if (un->un_read_pos_type == LONG_POS) {
13378 			rval = st_cmd(dev, SCMD_READ_POSITION, 0, SYNC_CMD);
13379 			if (rval) {
13380 				/*
13381 				 * We didn't get the file position from the
13382 				 * read position command.
13383 				 * We are going to trust the drive to backspace
13384 				 * and then position after the filemark.
13385 				 */
13386 				rval = st_space_to_begining_of_file(un);
13387 			}
13388 			rval = st_interpret_read_pos(un, LONG_POS, 32,
13389 			    (caddr_t)un->un_read_pos_data);
13390 			if ((rval) && (un->un_pos.pmode == invalid)) {
13391 				rval = st_space_to_begining_of_file(un);
13392 			} else {
13393 				rval = st_scenic_route_to_begining_of_file(un,
13394 				    un->un_pos.fileno);
13395 			}
13396 		} else {
13397 			rval = EIO;
13398 		}
13399 		/*
13400 		 * If something didn't work we are lost
13401 		 */
13402 		if (rval != 0) {
13403 			un->un_pos.pmode = invalid;
13404 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13405 			    "st_mtioctop : EIO : fspace pmode invalid");
13406 
13407 			rval = EIO;
13408 		}
13409 
13410 	} else {
13411 		rval = st_space_fmks(dev, count);
13412 	}
13413 
13414 	if (rval != EIO && count < 0) {
13415 		/*
13416 		 * we came here with a count < 0; we now need
13417 		 * to skip back to end up before the filemark
13418 		 */
13419 		rval = st_backward_space_files(un, 1, 1);
13420 	}
13421 
13422 	return (rval);
13423 }
13424 
13425 static int
13426 st_scenic_route_to_begining_of_file(struct scsi_tape *un, int32_t fileno)
13427 {
13428 	int rval;
13429 
13430 	ST_FUNC(ST_DEVINFO, st_scenic_route_to_begining_of_file);
13431 
13432 	if (st_cmd(un->un_dev, SCMD_REWIND, 0, SYNC_CMD)) {
13433 		rval = EIO;
13434 	} else if (st_cmd(un->un_dev, SCMD_SPACE, Fmk(fileno), SYNC_CMD)) {
13435 		rval = EIO;
13436 	}
13437 
13438 	return (rval);
13439 }
13440 
13441 static int
13442 st_space_to_begining_of_file(struct scsi_tape *un)
13443 {
13444 	int rval;
13445 
13446 	ST_FUNC(ST_DEVINFO, st_space_to_begining_of_file);
13447 
13448 	/*
13449 	 * Back space of the file at the begining of the file.
13450 	 */
13451 	rval = st_cmd(un->un_dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD);
13452 	if (rval) {
13453 		rval = EIO;
13454 		return (rval);
13455 	}
13456 
13457 	/*
13458 	 * Other interesting answers might be crashed BOT which isn't bad.
13459 	 */
13460 	if (un->un_status == SUN_KEY_BOT) {
13461 		return (rval);
13462 	}
13463 
13464 	/*
13465 	 * Now we are on the BOP side of the filemark. Forward space to
13466 	 * the EOM side and we are at the begining of the file.
13467 	 */
13468 	rval = st_cmd(un->un_dev, SCMD_SPACE, Fmk(1), SYNC_CMD);
13469 	if (rval) {
13470 		rval = EIO;
13471 	}
13472 
13473 	return (rval);
13474 }
13475 
13476 static int
13477 st_mtfsr_ioctl(struct scsi_tape *un, int count)
13478 {
13479 
13480 	ST_FUNC(ST_DEVINFO, st_mtfsr_ioctl);
13481 
13482 	/*
13483 	 * forward space to inter-record gap
13484 	 *
13485 	 */
13486 
13487 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13488 	    "st_ioctl_fsr: count=%x, eof=%x\n", count, un->un_pos.eof);
13489 
13490 	if (un->un_pos.pmode == legacy) {
13491 		/*
13492 		 * If were are at end of tape and count is forward.
13493 		 * Return blank check.
13494 		 */
13495 		if ((un->un_pos.eof >= ST_EOT) && (count > 0)) {
13496 			/* we're at EOM */
13497 			un->un_err_resid = count;
13498 			un->un_status = KEY_BLANK_CHECK;
13499 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13500 			    "st_mtfsr_ioctl: EIO : MTFSR eof > ST_EOT");
13501 			return (EIO);
13502 		}
13503 
13504 		/*
13505 		 * If count is zero there is nothing to do.
13506 		 */
13507 		if (count == 0) {
13508 			un->un_err_pos.fileno = un->un_pos.fileno;
13509 			un->un_err_pos.blkno = un->un_pos.blkno;
13510 			un->un_err_resid = 0;
13511 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
13512 				un->un_status = SUN_KEY_EOF;
13513 			}
13514 			return (0);
13515 		}
13516 
13517 		/*
13518 		 * physical tape position may not be what we've been
13519 		 * telling the user; adjust the position accordingly
13520 		 */
13521 		if (IN_EOF(un->un_pos)) {
13522 			daddr_t blkno = un->un_pos.blkno;
13523 			int fileno = un->un_pos.fileno;
13524 
13525 			optype lastop = un->un_lastop;
13526 			if (st_cmd(un->un_dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)
13527 			    == -1) {
13528 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13529 				    "st_mtfsr_ioctl:EIO:MTFSR count && IN_EOF");
13530 				return (EIO);
13531 			}
13532 
13533 			un->un_pos.blkno = blkno;
13534 			un->un_pos.fileno = fileno;
13535 			un->un_lastop = lastop;
13536 		}
13537 	}
13538 
13539 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
13540 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13541 		    "st_mtfsr_ioctl: EIO : MTFSR st_check_den");
13542 		return (EIO);
13543 	}
13544 
13545 	return (st_space_records(un, count));
13546 }
13547 
13548 static int
13549 st_space_records(struct scsi_tape *un, int count)
13550 {
13551 	int dblk;
13552 	int rval = 0;
13553 
13554 	ST_FUNC(ST_DEVINFO, st_space_records);
13555 
13556 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13557 	    "st_space_records: count=%x, eof=%x\n", count, un->un_pos.eof);
13558 
13559 	if (un->un_pos.pmode == logical) {
13560 		rval = st_cmd(un->un_dev, SCMD_SPACE, Blk(count), SYNC_CMD);
13561 		if (rval != 0) {
13562 			rval = EIO;
13563 		}
13564 		return (rval);
13565 	}
13566 
13567 	dblk = un->un_pos.blkno + count;
13568 
13569 	/* Already there */
13570 	if (dblk == un->un_pos.blkno) {
13571 		un->un_err_resid = 0;
13572 		COPY_POS(&un->un_err_pos, &un->un_pos);
13573 		return (0);
13574 	}
13575 
13576 	/*
13577 	 * If the destination block is forward
13578 	 * or the drive will backspace records.
13579 	 */
13580 	if (un->un_pos.blkno < dblk || (un->un_dp->options & ST_BSR)) {
13581 		/*
13582 		 * If we're spacing forward, or the device can
13583 		 * backspace records, we can just use the SPACE
13584 		 * command.
13585 		 */
13586 		dblk -= un->un_pos.blkno;
13587 		if (st_cmd(un->un_dev, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
13588 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13589 			    "st_space_records:EIO:space_records can't spc");
13590 			rval = EIO;
13591 		} else if (un->un_pos.eof >= ST_EOF_PENDING) {
13592 			/*
13593 			 * check if we hit BOT/EOT
13594 			 */
13595 			if (dblk < 0 && un->un_pos.eof == ST_EOM) {
13596 				un->un_status = SUN_KEY_BOT;
13597 				un->un_pos.eof = ST_NO_EOF;
13598 			} else if (dblk < 0 &&
13599 			    un->un_pos.eof == ST_EOF_PENDING) {
13600 				int residue = un->un_err_resid;
13601 				/*
13602 				 * we skipped over a filemark
13603 				 * and need to go forward again
13604 				 */
13605 				if (st_cmd(un->un_dev, SCMD_SPACE, Fmk(1),
13606 				    SYNC_CMD)) {
13607 					ST_DEBUG2(ST_DEVINFO, st_label,
13608 					    SCSI_DEBUG, "st_space_records: EIO"
13609 					    " : can't space #2");
13610 					rval = EIO;
13611 				}
13612 				un->un_err_resid = residue;
13613 			}
13614 			if (rval == 0) {
13615 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13616 				    "st_space_records: EIO : space_rec rval"
13617 				    " == 0");
13618 				rval = EIO;
13619 			}
13620 		}
13621 	} else {
13622 		/*
13623 		 * else we rewind, space forward across filemarks to
13624 		 * the desired file, and then space records to the
13625 		 * desired block.
13626 		 */
13627 
13628 		int dfile = un->un_pos.fileno;	/* save current file */
13629 
13630 		if (dblk < 0) {
13631 			/*
13632 			 * Wups - we're backing up over a filemark
13633 			 */
13634 			if (un->un_pos.blkno != 0 &&
13635 			    (st_cmd(un->un_dev, SCMD_REWIND, 0, SYNC_CMD) ||
13636 			    st_cmd(un->un_dev, SCMD_SPACE, Fmk(dfile),
13637 			    SYNC_CMD))) {
13638 				un->un_pos.pmode = invalid;
13639 			}
13640 			un->un_err_resid = -dblk;
13641 			if (un->un_pos.fileno == 0 && un->un_pos.blkno == 0) {
13642 				un->un_status = SUN_KEY_BOT;
13643 				un->un_pos.eof = ST_NO_EOF;
13644 			} else if (un->un_pos.fileno > 0) {
13645 				un->un_status = SUN_KEY_EOF;
13646 				un->un_pos.eof = ST_NO_EOF;
13647 			}
13648 			COPY_POS(&un->un_err_pos, &un->un_pos);
13649 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13650 			    "st_space_records:EIO:space_records : dblk < 0");
13651 			rval = EIO;
13652 		} else if (st_cmd(un->un_dev, SCMD_REWIND, 0, SYNC_CMD) ||
13653 		    st_cmd(un->un_dev, SCMD_SPACE, Fmk(dfile), SYNC_CMD) ||
13654 		    st_cmd(un->un_dev, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
13655 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13656 			    "st_space_records: EIO :space_records : rewind "
13657 			    "and space failed");
13658 			un->un_pos.pmode = invalid;
13659 			rval = EIO;
13660 		}
13661 	}
13662 
13663 	return (rval);
13664 }
13665 
13666 static int
13667 st_mtbsf_ioctl(struct scsi_tape *un, int files)
13668 {
13669 	ST_FUNC(ST_DEVINFO, st_mtbsf_ioctl);
13670 
13671 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13672 	    "st_mtbsf_ioctl: count=%x, eof=%x\n", files, un->un_pos.eof);
13673 	/*
13674 	 * backward space of file filemark (1/2" and 8mm)
13675 	 * tape position will end on the beginning of tape side
13676 	 * of the desired file mark
13677 	 */
13678 	if ((un->un_dp->options & ST_BSF) == 0) {
13679 		return (ENOTTY);
13680 	}
13681 
13682 	if (un->un_pos.pmode == legacy) {
13683 
13684 		/*
13685 		 * If a negative count (which implies a forward space op)
13686 		 * is specified, and we're at logical or physical eot,
13687 		 * bounce the request.
13688 		 */
13689 
13690 		if (un->un_pos.eof >= ST_EOT && files < 0) {
13691 			un->un_err_resid = files;
13692 			un->un_status = SUN_KEY_EOT;
13693 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13694 			    "st_ioctl_mt_bsf : EIO : MTBSF : eof > ST_EOF");
13695 			return (EIO);
13696 		}
13697 		/*
13698 		 * physical tape position may not be what we've been
13699 		 * telling the user; adjust the request accordingly
13700 		 */
13701 		if (IN_EOF(un->un_pos)) {
13702 			un->un_pos.fileno++;
13703 			un->un_pos.blkno = 0;
13704 			files++;
13705 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13706 			    "st_mtbsf_ioctl in eof: count=%d, op=%x\n",
13707 			    files, MTBSF);
13708 
13709 		}
13710 	}
13711 
13712 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
13713 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13714 		    "st_ioctl : EIO : MTBSF : check den wfm");
13715 		return (EIO);
13716 	}
13717 
13718 	if (files <= 0) {
13719 		/*
13720 		 * for a negative count, we need to step forward
13721 		 * first and then step back again
13722 		 */
13723 		files = -files + 1;
13724 		return (st_forward_space_files(un, files));
13725 	}
13726 	return (st_backward_space_files(un, files, 1));
13727 }
13728 
13729 static int
13730 st_backward_space_files(struct scsi_tape *un, int count, int infront)
13731 {
13732 	int end_fileno;
13733 	int skip_cnt;
13734 	int rval = 0;
13735 
13736 	ST_FUNC(ST_DEVINFO, st_backward_space_files);
13737 
13738 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13739 	    "st_backward_space_files: count=%x eof=%x\n",
13740 	    count, un->un_pos.eof);
13741 	/*
13742 	 * Backspace files (MTNBSF): infront == 0
13743 	 *
13744 	 *	For tapes that can backspace, backspace
13745 	 *	count+1 filemarks and then run forward over
13746 	 *	a filemark
13747 	 *
13748 	 *	For tapes that can't backspace,
13749 	 *		calculate desired filenumber
13750 	 *		(un->un_pos.fileno - count), rewind,
13751 	 *		and then space forward this amount
13752 	 *
13753 	 * Backspace filemarks (MTBSF) infront == 1
13754 	 *
13755 	 *	For tapes that can backspace, backspace count
13756 	 *	filemarks
13757 	 *
13758 	 *	For tapes that can't backspace, calculate
13759 	 *	desired filenumber (un->un_pos.fileno - count),
13760 	 *	add 1, rewind, space forward this amount,
13761 	 *	and mark state as ST_EOF_PENDING appropriately.
13762 	 */
13763 
13764 	if (un->un_pos.pmode == logical) {
13765 
13766 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13767 		    "st_backward_space_files: mt_op=%x count=%x"
13768 		    "lgclblkno=%"PRIx64"\n", infront?MTBSF:MTNBSF, count,
13769 		    un->un_pos.lgclblkno);
13770 
13771 
13772 		/* In case a drive that won't back space gets in logical mode */
13773 		if ((un->un_dp->options & ST_BSF) == 0) {
13774 			rval = EIO;
13775 			return (rval);
13776 		}
13777 		if (st_cmd(un->un_dev, SCMD_SPACE, Fmk(-count), SYNC_CMD)) {
13778 			rval = EIO;
13779 			return (rval);
13780 		}
13781 		if ((infront != 0) &&
13782 		    (st_cmd(un->un_dev, SCMD_SPACE, Fmk(1), SYNC_CMD))) {
13783 			rval = EIO;
13784 			return (rval);
13785 		}
13786 		return (rval);
13787 	}
13788 
13789 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13790 	    "st_backward_space_files: mt_op=%x count=%x fileno=%x blkno=%x\n",
13791 	    infront?MTBSF:MTNBSF, count, un->un_pos.fileno, un->un_pos.blkno);
13792 
13793 
13794 
13795 	/*
13796 	 * Handle the simple case of BOT
13797 	 * playing a role in these cmds.
13798 	 * We do this by calculating the
13799 	 * ending file number. If the ending
13800 	 * file is < BOT, rewind and set an
13801 	 * error and mark resid appropriately.
13802 	 * If we're backspacing a file (not a
13803 	 * filemark) and the target file is
13804 	 * the first file on the tape, just
13805 	 * rewind.
13806 	 */
13807 
13808 	/* figure expected destination of this SPACE command */
13809 	end_fileno = un->un_pos.fileno - count;
13810 
13811 	/*
13812 	 * Would the end effect of this SPACE be the same as rewinding?
13813 	 * If so just rewind instead.
13814 	 */
13815 	if ((infront != 0) && (end_fileno < 0) ||
13816 	    (infront == 0) && (end_fileno <= 0)) {
13817 		if (st_cmd(un->un_dev, SCMD_REWIND, 0, SYNC_CMD)) {
13818 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13819 			    "st_backward_space_files: EIO : "
13820 			    "rewind in lou of BSF failed\n");
13821 			rval = EIO;
13822 		}
13823 		if (end_fileno < 0) {
13824 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13825 			    "st_backward_space_files: EIO : "
13826 			    "back space file greater then fileno\n");
13827 			rval = EIO;
13828 			un->un_err_resid = -end_fileno;
13829 			un->un_status = SUN_KEY_BOT;
13830 		}
13831 		return (rval);
13832 	}
13833 
13834 	if (un->un_dp->options & ST_BSF) {
13835 		skip_cnt = 1 - infront;
13836 		/*
13837 		 * If we are going to end up at the beginning
13838 		 * of the file, we have to space one extra file
13839 		 * first, and then space forward later.
13840 		 */
13841 		end_fileno = -(count + skip_cnt);
13842 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
13843 		    "skip_cnt=%x, tmp=%x\n", skip_cnt, end_fileno);
13844 		if (st_cmd(un->un_dev, SCMD_SPACE, Fmk(end_fileno), SYNC_CMD)) {
13845 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13846 			    "st_backward_space_files:EIO:back space fm failed");
13847 			rval = EIO;
13848 		}
13849 	} else {
13850 		if (st_cmd(un->un_dev, SCMD_REWIND, 0, SYNC_CMD)) {
13851 			rval = EIO;
13852 		} else {
13853 			skip_cnt = end_fileno + infront;
13854 		}
13855 	}
13856 
13857 	/*
13858 	 * If we have to space forward, do so...
13859 	 */
13860 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
13861 	    "space forward skip_cnt=%x, rval=%x\n", skip_cnt, rval);
13862 
13863 	if (rval == 0 && skip_cnt) {
13864 		if (st_cmd(un->un_dev, SCMD_SPACE, Fmk(skip_cnt), SYNC_CMD)) {
13865 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13866 			    "st_backward_space_files:EIO:space fm skip count");
13867 			rval = EIO;
13868 		} else if (infront) {
13869 			/*
13870 			 * If we had to space forward, and we're
13871 			 * not a tape that can backspace, mark state
13872 			 * as if we'd just seen a filemark during a
13873 			 * a read.
13874 			 */
13875 			if ((un->un_dp->options & ST_BSF) == 0) {
13876 				un->un_pos.eof = ST_EOF_PENDING;
13877 				un->un_pos.fileno -= 1;
13878 				un->un_pos.blkno = INF;
13879 			}
13880 		}
13881 	}
13882 
13883 	if (rval != 0) {
13884 		un->un_pos.pmode = invalid;
13885 	}
13886 
13887 	return (rval);
13888 }
13889 
13890 static int
13891 st_mtnbsf_ioctl(struct scsi_tape *un, int count)
13892 {
13893 	int rval;
13894 
13895 	ST_FUNC(ST_DEVINFO, st_mtnbsf_ioctl);
13896 
13897 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13898 	    "nbsf: count=%x, eof=%x\n", count, un->un_pos.eof);
13899 
13900 	if (un->un_pos.pmode == legacy) {
13901 		/*
13902 		 * backward space file to beginning of file
13903 		 *
13904 		 * If a negative count (which implies a forward space op)
13905 		 * is specified, and we're at logical or physical eot,
13906 		 * bounce the request.
13907 		 */
13908 
13909 		if (un->un_pos.eof >= ST_EOT && count < 0) {
13910 			un->un_err_resid = count;
13911 			un->un_status = SUN_KEY_EOT;
13912 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13913 			    "st_ioctl : EIO : > EOT and count < 0");
13914 			return (EIO);
13915 		}
13916 		/*
13917 		 * physical tape position may not be what we've been
13918 		 * telling the user; adjust the request accordingly
13919 		 */
13920 		if (IN_EOF(un->un_pos)) {
13921 			un->un_pos.fileno++;
13922 			un->un_pos.blkno = 0;
13923 			count++;
13924 		}
13925 	}
13926 
13927 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
13928 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13929 		    "st_ioctl : EIO : MTNBSF check den and wfm");
13930 		return (EIO);
13931 	}
13932 
13933 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13934 	    "mtnbsf: count=%x, eof=%x\n", count, un->un_pos.eof);
13935 
13936 	if (count <= 0) {
13937 		rval = st_forward_space_files(un, -count);
13938 	} else {
13939 		rval = st_backward_space_files(un, count, 0);
13940 	}
13941 	return (rval);
13942 }
13943 
13944 static int
13945 st_mtbsr_ioctl(struct scsi_tape *un, int num)
13946 {
13947 	ST_FUNC(ST_DEVINFO, st_mtbsr_ioctl);
13948 
13949 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13950 	    "bsr: count=%x, eof=%x\n", num, un->un_pos.eof);
13951 
13952 	if (un->un_pos.pmode == legacy) {
13953 		/*
13954 		 * backward space into inter-record gap
13955 		 *
13956 		 * If a negative count (which implies a forward space op)
13957 		 * is specified, and we're at logical or physical eot,
13958 		 * bounce the request.
13959 		 */
13960 		if (un->un_pos.eof >= ST_EOT && num < 0) {
13961 			un->un_err_resid = num;
13962 			un->un_status = SUN_KEY_EOT;
13963 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13964 			    "st_ioctl : EIO : MTBSR > EOT");
13965 			return (EIO);
13966 		}
13967 
13968 		if (num == 0) {
13969 			COPY_POS(&un->un_err_pos, &un->un_pos);
13970 			un->un_err_resid = 0;
13971 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
13972 				un->un_status = SUN_KEY_EOF;
13973 			}
13974 			return (0);
13975 		}
13976 
13977 		/*
13978 		 * physical tape position may not be what we've been
13979 		 * telling the user; adjust the position accordingly.
13980 		 * bsr can not skip filemarks and continue to skip records
13981 		 * therefore if we are logically before the filemark but
13982 		 * physically at the EOT side of the filemark, we need to step
13983 		 * back; this allows fsr N where N > number of blocks in file
13984 		 * followed by bsr 1 to position at the beginning of last block
13985 		 */
13986 		if (IN_EOF(un->un_pos)) {
13987 			tapepos_t save;
13988 			optype lastop = un->un_lastop;
13989 
13990 			COPY_POS(&save, &un->un_pos);
13991 			if (st_cmd(un->un_dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)
13992 			    == -1) {
13993 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13994 				    "st_write_fm : EIO : MTBSR can't space");
13995 				return (EIO);
13996 			}
13997 
13998 			COPY_POS(&un->un_pos, &save);
13999 			un->un_lastop = lastop;
14000 		}
14001 	}
14002 
14003 	un->un_pos.eof = ST_NO_EOF;
14004 
14005 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
14006 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14007 		    "st_ioctl : EIO : MTBSR : can't set density or wfm");
14008 		return (EIO);
14009 	}
14010 
14011 	num = -num;
14012 	return (st_space_records(un, num));
14013 }
14014 
14015 static int
14016 st_mtfsfm_ioctl(struct scsi_tape *un, int cnt)
14017 {
14018 	int rval;
14019 
14020 	ST_FUNC(ST_DEVINFO, st_mtfsfm_ioctl);
14021 
14022 	rval = st_cmd(un->un_dev, SCMD_SPACE, SPACE(SP_SQFLM, cnt), SYNC_CMD);
14023 	if (rval == 0) {
14024 		un->un_pos.pmode = logical;
14025 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
14026 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
14027 		/*
14028 		 * Drive says invalid field in cdb.
14029 		 * Doesn't like space multiple. Position isn't lost.
14030 		 */
14031 		un->un_err_resid = cnt;
14032 		un->un_status = 0;
14033 		rval = ENOTTY;
14034 	} else {
14035 		un->un_err_resid = cnt;
14036 		un->un_pos.pmode = invalid;
14037 	}
14038 	return (rval);
14039 }
14040 
14041 static int
14042 st_mtbsfm_ioctl(struct scsi_tape *un, int cnt)
14043 {
14044 	int rval;
14045 
14046 	ST_FUNC(ST_DEVINFO, st_mtbsfm_ioctl);
14047 
14048 	rval = st_cmd(un->un_dev, SCMD_SPACE, SPACE(SP_SQFLM, -cnt), SYNC_CMD);
14049 	if (rval == 0) {
14050 		un->un_pos.pmode = logical;
14051 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
14052 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
14053 		/*
14054 		 * Drive says invalid field in cdb.
14055 		 * Doesn't like space multiple. Position isn't lost.
14056 		 */
14057 		un->un_err_resid = cnt;
14058 		un->un_status = 0;
14059 		rval = ENOTTY;
14060 	} else {
14061 		un->un_err_resid = cnt;
14062 		un->un_pos.pmode = invalid;
14063 	}
14064 	return (rval);
14065 }
14066 
14067 #if defined(__i386) || defined(__amd64)
14068 
14069 /*
14070  * release contig_mem and wake up waiting thread, if any
14071  */
14072 static void
14073 st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp)
14074 {
14075 	mutex_enter(ST_MUTEX);
14076 
14077 	ST_FUNC(ST_DEVINFO, st_release_contig_mem);
14078 
14079 	cp->cm_next = un->un_contig_mem;
14080 	un->un_contig_mem = cp;
14081 	un->un_contig_mem_available_num++;
14082 	cv_broadcast(&un->un_contig_mem_cv);
14083 
14084 	mutex_exit(ST_MUTEX);
14085 }
14086 
14087 /*
14088  * St_get_contig_mem will return a contig_mem if there is one available
14089  * in current system. Otherwise, it will try to alloc one, if the total
14090  * number of contig_mem is within st_max_contig_mem_num.
14091  * It will sleep, if allowed by caller or return NULL, if no contig_mem
14092  * is available for now.
14093  */
14094 static struct contig_mem *
14095 st_get_contig_mem(struct scsi_tape *un, size_t len, int alloc_flags)
14096 {
14097 	size_t rlen;
14098 	struct contig_mem *cp = NULL;
14099 	ddi_acc_handle_t acc_hdl;
14100 	caddr_t addr;
14101 	int big_enough = 0;
14102 	int (*dma_alloc_cb)() = (alloc_flags == KM_SLEEP) ?
14103 	    DDI_DMA_SLEEP : DDI_DMA_DONTWAIT;
14104 
14105 	/* Try to get one available contig_mem */
14106 	mutex_enter(ST_MUTEX);
14107 
14108 	ST_FUNC(ST_DEVINFO, st_get_contig_mem);
14109 
14110 	if (un->un_contig_mem_available_num > 0) {
14111 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
14112 	} else if (un->un_contig_mem_total_num < st_max_contig_mem_num) {
14113 		/*
14114 		 * we failed to get one. we're going to
14115 		 * alloc one more contig_mem for this I/O
14116 		 */
14117 		mutex_exit(ST_MUTEX);
14118 		cp = (struct contig_mem *)kmem_zalloc(
14119 		    sizeof (struct contig_mem) + biosize(),
14120 		    alloc_flags);
14121 		if (cp == NULL) {
14122 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14123 			    "alloc contig_mem failure\n");
14124 			return (NULL); /* cannot get one */
14125 		}
14126 		cp->cm_bp = (struct buf *)
14127 		    (((caddr_t)cp) + sizeof (struct contig_mem));
14128 		bioinit(cp->cm_bp);
14129 		mutex_enter(ST_MUTEX);
14130 		un->un_contig_mem_total_num++; /* one more available */
14131 	} else {
14132 		/*
14133 		 * we failed to get one and we're NOT allowed to
14134 		 * alloc more contig_mem
14135 		 */
14136 		if (alloc_flags == KM_SLEEP) {
14137 			while (un->un_contig_mem_available_num <= 0) {
14138 				cv_wait(&un->un_contig_mem_cv,
14139 				    ST_MUTEX);
14140 			}
14141 			ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
14142 		} else {
14143 			mutex_exit(ST_MUTEX);
14144 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14145 			    "alloc contig_mem failure\n");
14146 			return (NULL); /* cannot get one */
14147 		}
14148 	}
14149 	mutex_exit(ST_MUTEX);
14150 
14151 	/* We need to check if this block of mem is big enough for this I/O */
14152 	if (cp->cm_len < len) {
14153 		/* not big enough, need to alloc a new one */
14154 		if (ddi_dma_mem_alloc(un->un_contig_mem_hdl, len, &st_acc_attr,
14155 		    DDI_DMA_STREAMING, dma_alloc_cb, NULL,
14156 		    &addr, &rlen, &acc_hdl) != DDI_SUCCESS) {
14157 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14158 			    "alloc contig_mem failure: not enough mem\n");
14159 			st_release_contig_mem(un, cp);
14160 			cp = NULL;
14161 		} else {
14162 			if (cp->cm_addr) {
14163 				/* release previous one before attach new one */
14164 				ddi_dma_mem_free(&cp->cm_acc_hdl);
14165 			}
14166 			mutex_enter(ST_MUTEX);
14167 			un->un_max_contig_mem_len =
14168 			    un->un_max_contig_mem_len >= len ?
14169 			    un->un_max_contig_mem_len : len;
14170 			mutex_exit(ST_MUTEX);
14171 
14172 			/* attach new mem to this cp */
14173 			cp->cm_addr = addr;
14174 			cp->cm_acc_hdl = acc_hdl;
14175 			cp->cm_len = len;
14176 
14177 			goto alloc_ok; /* get one usable cp */
14178 		}
14179 	} else {
14180 		goto alloc_ok; /* get one usable cp */
14181 	}
14182 
14183 	/* cannot find/alloc a usable cp, when we get here */
14184 
14185 	mutex_enter(ST_MUTEX);
14186 	if ((un->un_max_contig_mem_len < len) ||
14187 	    (alloc_flags != KM_SLEEP)) {
14188 		mutex_exit(ST_MUTEX);
14189 		return (NULL);
14190 	}
14191 
14192 	/*
14193 	 * we're allowed to sleep, and there is one big enough
14194 	 * contig mem in the system, which is currently in use,
14195 	 * wait for it...
14196 	 */
14197 	big_enough = 1;
14198 	do {
14199 		cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
14200 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
14201 	} while (cp == NULL);
14202 	mutex_exit(ST_MUTEX);
14203 
14204 	/* we get the big enough contig mem, finally */
14205 
14206 alloc_ok:
14207 	/* init bp attached to this cp */
14208 	bioreset(cp->cm_bp);
14209 	cp->cm_bp->b_un.b_addr = cp->cm_addr;
14210 	cp->cm_bp->b_private = (void *)cp;
14211 
14212 	return (cp);
14213 }
14214 
14215 /*
14216  * this is the biodone func for the bp used in big block I/O
14217  */
14218 static int
14219 st_bigblk_xfer_done(struct buf *bp)
14220 {
14221 	struct contig_mem *cp;
14222 	struct buf *orig_bp;
14223 	int remapped = 0;
14224 	int ioerr;
14225 	struct scsi_tape *un;
14226 
14227 	/* sanity check */
14228 	if (bp == NULL) {
14229 		return (DDI_FAILURE);
14230 	}
14231 
14232 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
14233 	if (un == NULL) {
14234 		return (DDI_FAILURE);
14235 	}
14236 
14237 	ST_FUNC(ST_DEVINFO, st_bigblk_xfer_done);
14238 
14239 	cp = (struct contig_mem *)bp->b_private;
14240 	orig_bp = cp->cm_bp; /* get back the bp we have replaced */
14241 	cp->cm_bp = bp;
14242 
14243 	/* special handling for special I/O */
14244 	if (cp->cm_use_sbuf) {
14245 #ifndef __lock_lint
14246 		ASSERT(un->un_sbuf_busy);
14247 #endif
14248 		un->un_sbufp = orig_bp;
14249 		cp->cm_use_sbuf = 0;
14250 	}
14251 
14252 	orig_bp->b_resid = bp->b_resid;
14253 	ioerr = geterror(bp);
14254 	if (ioerr != 0) {
14255 		bioerror(orig_bp, ioerr);
14256 	} else if (orig_bp->b_flags & B_READ) {
14257 		/* copy data back to original bp */
14258 		if (orig_bp->b_flags & (B_PHYS | B_PAGEIO)) {
14259 			bp_mapin(orig_bp);
14260 			remapped = 1;
14261 		}
14262 		bcopy(bp->b_un.b_addr, orig_bp->b_un.b_addr,
14263 		    bp->b_bcount - bp->b_resid);
14264 		if (remapped)
14265 			bp_mapout(orig_bp);
14266 	}
14267 
14268 	st_release_contig_mem(un, cp);
14269 
14270 	biodone(orig_bp);
14271 
14272 	return (DDI_SUCCESS);
14273 }
14274 
14275 /*
14276  * We use this func to replace original bp that may not be able to do I/O
14277  * in big block size with one that can
14278  */
14279 static struct buf *
14280 st_get_bigblk_bp(struct buf *bp)
14281 {
14282 	struct contig_mem *cp;
14283 	struct scsi_tape *un;
14284 	struct buf *cont_bp;
14285 	int remapped = 0;
14286 
14287 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
14288 	if (un == NULL) {
14289 		return (bp);
14290 	}
14291 
14292 	ST_FUNC(ST_DEVINFO, st_get_bigblk_bp);
14293 
14294 	/* try to get one contig_mem */
14295 	cp = st_get_contig_mem(un, bp->b_bcount, KM_SLEEP);
14296 	if (!cp) {
14297 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
14298 		    "Cannot alloc contig buf for I/O for %lu blk size",
14299 		    bp->b_bcount);
14300 		return (bp);
14301 	}
14302 	cont_bp = cp->cm_bp;
14303 	cp->cm_bp = bp;
14304 
14305 	/* make sure that we "are" using un_sbufp for special I/O */
14306 	if (bp == un->un_sbufp) {
14307 #ifndef __lock_lint
14308 		ASSERT(un->un_sbuf_busy);
14309 #endif
14310 		un->un_sbufp = cont_bp;
14311 		cp->cm_use_sbuf = 1;
14312 	}
14313 
14314 	/* clone bp */
14315 	cont_bp->b_bcount = bp->b_bcount;
14316 	cont_bp->b_resid = bp->b_resid;
14317 	cont_bp->b_iodone = st_bigblk_xfer_done;
14318 	cont_bp->b_file = bp->b_file;
14319 	cont_bp->b_offset = bp->b_offset;
14320 	cont_bp->b_dip = bp->b_dip;
14321 	cont_bp->b_error = 0;
14322 	cont_bp->b_proc = NULL;
14323 	cont_bp->b_flags = bp->b_flags & ~(B_PAGEIO | B_PHYS | B_SHADOW);
14324 	cont_bp->b_shadow = NULL;
14325 	cont_bp->b_pages = NULL;
14326 	cont_bp->b_edev = bp->b_edev;
14327 	cont_bp->b_dev = bp->b_dev;
14328 	cont_bp->b_lblkno = bp->b_lblkno;
14329 	cont_bp->b_forw = bp->b_forw;
14330 	cont_bp->b_back = bp->b_back;
14331 	cont_bp->av_forw = bp->av_forw;
14332 	cont_bp->av_back = bp->av_back;
14333 	cont_bp->b_bufsize = bp->b_bufsize;
14334 
14335 	/* get data in original bp */
14336 	if (bp->b_flags & B_WRITE) {
14337 		if (bp->b_flags & (B_PHYS | B_PAGEIO)) {
14338 			bp_mapin(bp);
14339 			remapped = 1;
14340 		}
14341 		bcopy(bp->b_un.b_addr, cont_bp->b_un.b_addr, bp->b_bcount);
14342 		if (remapped)
14343 			bp_mapout(bp);
14344 	}
14345 
14346 	return (cont_bp);
14347 }
14348 #else
14349 #ifdef __lock_lint
14350 static int
14351 st_bigblk_xfer_done(struct buf *bp)
14352 {
14353 	return (0);
14354 }
14355 #endif
14356 #endif
14357 
14358 static const char *eof_status[] =
14359 {
14360 	"NO_EOF",
14361 	"EOF_PENDING",
14362 	"EOF",
14363 	"EOT_PENDING",
14364 	"EOT",
14365 	"EOM",
14366 	"AFTER_EOM"
14367 };
14368 static const char *mode[] = {
14369 	"invalid",
14370 	"legacy",
14371 	"logical"
14372 };
14373 
14374 static void
14375 st_print_position(struct scsi_tape *un, const char *comment, tapepos_t *pos)
14376 {
14377 	ST_FUNC(ST_DEVINFO, st_print_position);
14378 	scsi_log(ST_DEVINFO, st_label, CE_NOTE,
14379 	    "%s Position data:\n", comment);
14380 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
14381 	    "Positioning mode = %s", mode[pos->pmode]);
14382 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
14383 	    "End Of File/Tape = %s", eof_status[pos->eof]);
14384 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
14385 	    "File Number      = 0x%x", pos->fileno);
14386 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
14387 	    "Block Number     = 0x%x", pos->blkno);
14388 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
14389 	    "Logical Block    = 0x%"PRIx64, pos->lgclblkno);
14390 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
14391 	    "Partition Number = 0x%x", pos->partition);
14392 }
14393